@msafe/sui-app-store 0.0.356 → 0.0.357
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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),ms=(r,e)=>{for(var t in e)Jn(r,t,{get:e[t],enumerable:!0})},wc=(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)):{},wc(e||!r||!r.__esModule?Jn(t,"default",{value:r,enumerable:!0}):t,r)),Md=r=>wc(Jn({},"__esModule",{value:!0}),r);var Em=Ad((Nm,tc)=>{"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,rc=d[3]|0,Y=rc&8191,J=rc>>>13,ac=d[4]|0,Z=ac&8191,tt=ac>>>13,ic=d[5]|0,et=ic&8191,nt=ic>>>13,sc=d[6]|0,ot=sc&8191,rt=sc>>>13,cc=d[7]|0,at=cc&8191,it=cc>>>13,lc=d[8]|0,st=lc&8191,ct=lc>>>13,pc=d[9]|0,lt=pc&8191,pt=pc>>>13,uc=h[0]|0,ut=uc&8191,mt=uc>>>13,mc=h[1]|0,dt=mc&8191,ft=mc>>>13,dc=h[2]|0,ht=dc&8191,gt=dc>>>13,fc=h[3]|0,yt=fc&8191,bt=fc>>>13,hc=h[4]|0,Tt=hc&8191,St=hc>>>13,gc=h[5]|0,wt=gc&8191,It=gc>>>13,yc=h[6]|0,Ct=yc&8191,xt=yc>>>13,bc=h[7]|0,kt=bc&8191,Dt=bc>>>13,Tc=h[8]|0,vt=Tc&8191,At=Tc>>>13,Sc=h[9]|0,Mt=Sc&8191,Ot=Sc>>>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 Hi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Hi>>>26)|0,Hi&=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 Xi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Xi>>>26)|0,Xi&=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 zi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(zi>>>26)|0,zi&=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 Qi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Qi>>>26)|0,Qi&=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 Yi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Yi>>>26)|0,Yi&=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 Ji=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Ji>>>26)|0,Ji&=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 Zi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Zi>>>26)|0,Zi&=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 ts=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ts>>>26)|0,ts&=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 es=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(es>>>26)|0,es&=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 ns=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ns>>>26)|0,ns&=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 os=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(os>>>26)|0,os&=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 rs=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(rs>>>26)|0,rs&=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 as=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(as>>>26)|0,as&=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 is=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(is>>>26)|0,is&=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 ss=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ss>>>26)|0,ss&=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 cs=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(cs>>>26)|0,cs&=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 ls=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ls>>>26)|0,ls&=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 ps=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ps>>>26)|0,ps&=67108863,f=Math.imul(lt,Mt),l=Math.imul(lt,Ot),l=l+Math.imul(pt,Mt)|0,g=Math.imul(pt,Ot);var us=(I+f|0)+((l&8191)<<13)|0;return I=(g+(l>>>13)|0)+(us>>>26)|0,us&=67108863,T[0]=Hi,T[1]=Xi,T[2]=zi,T[3]=Qi,T[4]=Yi,T[5]=Ji,T[6]=Zi,T[7]=ts,T[8]=es,T[9]=ns,T[10]=os,T[11]=rs,T[12]=as,T[13]=is,T[14]=ss,T[15]=cs,T[16]=ls,T[17]=ps,T[18]=us,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 tc>"u"||tc,Nm)});var Hf={};ms(Hf,{appHelpers:()=>Vf});module.exports=Md(Hf);var Ac=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 Cc=require("@alphafi/alphafi-sdk");var Ic=_t(require("sort-keys-recursive")),v=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,Ic.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,Cc.claimRewardTxb)(n.address)}static fromData(t){return new r(t)}};var xc=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,xc.depositDoubleAssetTxb)(o,n.address,a,s)}static fromData(t){return console.log("DepositDoubleAssetIntention.fromData",t),new r(t)}};var kc=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,kc.depositSingleAssetTxb)(o,n.address,a)}static fromData(t){return console.log("DepositSingleAssetIntention.fromData",t),new r(t)}};var Dc=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,Dc.withdrawTxb)(a,o,n.address)}static fromData(t){return console.log("WithdrawIntention.fromData",t),new r(t)}};var vc=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,vc.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:Ac.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 Zc=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 Bc=require("@msafe/sui3-utils");var Oc=require("@mysten/sui/transactions"),Pc=require("bucket-protocol-sdk");var Mc=require("bucket-protocol-sdk"),Lt=(r,e)=>{let t=r==="sui:mainnet"?"mainnet":"testnet";return new Mc.BucketClient(t,e.address)};var Rc=async(r,e,t)=>{let{coinType:n,amount:o,buckToCoin:a}=r,s=new Oc.Transaction,c=Lt(t,e);return await(0,Pc.buildPsmTx)(c,s,n,o,a,e.address),s};var po=class r extends v{constructor(t){super(t);this.data=t}data;txType=Bc.TransactionType.Other;txSubType="psm";async build(t){let{account:n,network:o}=t;return await Rc(this.data,n,o)}static fromData(t){return new r(t)}};var Lc=require("@msafe/sui3-utils");var In=require("@mysten/sui/transactions"),Te=require("bucket-protocol-sdk");var Nc=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},Ec=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},Wc=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},_c=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=Lc.TransactionType.Other;txSubType="borrow";async build(t){let{account:n,network:o}=t;return await Nc(this.data,n,o)}static fromData(t){return new r(t)}};var jc=require("@msafe/sui3-utils");var mo=class r extends v{constructor(t){super(t);this.data=t}data;txType=jc.TransactionType.Other;txSubType="repay";async build(t){let{account:n,network:o}=t;return await Wc(this.data,n,o)}static fromData(t){return new r(t)}};var Uc=require("@msafe/sui3-utils");var fo=class r extends v{constructor(t){super(t);this.data=t}data;txType=Uc.TransactionType.Other;txSubType="withdraw";async build(t){let{account:n,network:o}=t;return await Ec(this.data,n,o)}static fromData(t){return new r(t)}};var Gc=require("@msafe/sui3-utils");var ho=class r extends v{constructor(t){super(t);this.data=t}data;txType=Gc.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 r(t)}};var xn=require("@msafe/sui3-utils");var Cn=require("@mysten/sui/transactions"),Se=require("bucket-protocol-sdk");var qc=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},Fc=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},Kc=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},$c=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 qc(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 Fc(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 Kc(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 $c(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 Vc=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},Hc=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},Xc=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 zc=require("@mysten/sui/transactions"),Qc=require("bucket-protocol-sdk");var Yc=async(r,e,t)=>{let{coinType:n,proofCount:o}=r,a=new zc.Transaction,s=Lt(t,e);return await(0,Qc.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 Vc(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 Hc(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 Xc(this.data,n,o)}static fromData(t){return new r(t)}};var Jc=require("@msafe/sui3-utils");var ko=class r extends v{constructor(t){super(t);this.data=t}data;txType=Jc.TransactionType.Other;txSubType="lock-claim";async build(t){let{account:n,network:o}=t;return await Yc(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:Zc.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 np=require("@msafe/sui3-utils");var cl=require("@msafe/sui3-utils");var tl=_t(require("sort-keys-recursive")),k=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,tl.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",el=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 nl=async(r,e,t,n)=>await(await ee(t,e,n)).Pool.createPoolPayload(r),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.createAddLiquidityFixTokenPayload(r?.parameter),al=async(r,e,t,n)=>await(await ee(t,e,n)).Position.closePositionPayload(r),il=async(r,e,t,n)=>await(await ee(t,e,n)).Position.removeLiquidityPayload(r),sl=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=cl.TransactionType.Other;txSubType="OpenAndAddLiquidity";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 ll=require("@msafe/sui3-utils");var Ao=class r extends k{constructor(t){super(t);this.data=t}data;txType=ll.TransactionType.Other;txSubType="ClaimFeeAndMining";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await sl(s,o,a,n)}static fromData(t){return new r(t)}};var pl=require("@msafe/sui3-utils");var Mo=class r extends k{constructor(t){super(t);this.data=t}data;txType=pl.TransactionType.Other;txSubType="CreatePool";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 ul=require("@msafe/sui3-utils");var Oo=class r extends k{constructor(t){super(t);this.data=t}data;txType=ul.TransactionType.Other;txSubType="DecreaseLiquidity";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 wl=require("@msafe/sui3-utils");var ml=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.openPositionAddLiquidityStakePayload(r),dl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.addLiquidityFixCoinPayload(r),fl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.removeLiquidityPayload(r);var hl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.removeLiquidityPayload(r),gl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.claimFeeAndClmmReward(r),yl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.harvestPayload(r),bl=async(r,e,t,n)=>{let o=await Kt(t,e,n),a=Object.values(r);return await o.Farms.batchHarvestPayload(a)},Tl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.depositPayload(r),Sl=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=wl.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";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 Il=require("@msafe/sui3-utils");var Ro=class r extends k{constructor(t){super(t);this.data=t}data;txType=Il.TransactionType.Other;txSubType="FarmingBatchHarvest";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 Cl=require("@msafe/sui3-utils");var Bo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Cl.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";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 xl=require("@msafe/sui3-utils");var No=class r extends k{constructor(t){super(t);this.data=t}data;txType=xl.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";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 kl=require("@msafe/sui3-utils");var Eo=class r extends k{constructor(t){super(t);this.data=t}data;txType=kl.TransactionType.Other;txSubType="FarmingHarvest";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 Dl=require("@msafe/sui3-utils");var Wo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Dl.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";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 vl=require("@msafe/sui3-utils");var _o=class r extends k{constructor(t){super(t);this.data=t}data;txType=vl.TransactionType.Other;txSubType="FarmingRemoveLiquidity";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 Al=require("@msafe/sui3-utils");var Lo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Al.TransactionType.Other;txSubType="FarmingStake";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 jo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Ml.TransactionType.Other;txSubType="FarmingUnstake";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await Sl(s,o,a,n)}static fromData(t){return new r(t)}};var Ol=require("@msafe/sui3-utils");var Uo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Ol.TransactionType.Other;txSubType="IncreaseLiquidity";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 Bl=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},Pl=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},Rl=async(r,e,t,n)=>r.type==="clmm"?Pl(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):Pl(r,e,t,n);var qo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Bl.TransactionType.Other;txSubType="PosVestingRedeem";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 Nl=require("@msafe/sui3-utils");var Fo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Nl.TransactionType.Other;txSubType="RemoveLiquidity";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 _l=require("@msafe/sui3-utils");var El=require("@mysten/sui/transactions");var Wl=async(r,e,t,n)=>{let{restituteMsafeFastRouterSwapParams:o}=await import("@cetusprotocol/aggregator-sdk"),a=await el(t,e,n),s=new El.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=_l.TransactionType.Other;txSubType="AggregatorSwap";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await Wl(s,o,a,n)}static fromData(t){return new r(t)}};var Ul=require("@msafe/sui3-utils");var ds=require("@mysten/sui/transactions");var Ll=async(r,e,t,n)=>{let o=await kn(t,e,n),a=new ds.Transaction;return a.setSender(e.address),await o.Vaults.deposit(r,a),a},jl=async(r,e,t,n)=>{let o=await kn(t,e,n),a=new ds.Transaction;return await o.Vaults.withdraw(r,a),a};var $o=class r extends k{constructor(t){super(t);this.data=t}data;txType=Ul.TransactionType.Other;txSubType="AddVaultsPosition";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 Gl=require("@msafe/sui3-utils");var Vo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Gl.TransactionType.Other;txSubType="RemoveVaultsPosition";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await jl(s,o,a,n)}static fromData(t){return new r(t)}};var $l=require("@msafe/sui3-utils");var Fl=require("@mysten/sui/transactions"),ql={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},Kl=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 Fl.Transaction;return a.forEach(m=>{c.moveCall({target:`${ql.published_at}::router::redeem`,typeArguments:[ql.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=$l.TransactionType.Other;txSubType="VestingRedeem";async build(t){let{account:n,network:o}=t,{txbParams:a}=this.data;return await Kl(a,n,o)}static fromData(t){return new r(t)}};var Yl=require("@msafe/sui3-utils");var Vl=async(r,e,t,n)=>await(await Qe(t,e,n)).XCetusModule.convertPayload(r),Hl=async(r,e,t,n)=>await(await Qe(t,e,n)).XCetusModule.redeemLockPayload(r),Xl=async(r,e,t,n)=>await(await Qe(t,e,n)).XCetusModule.redeemDividendV3Payload(r.veNftId,r.rewardList),zl=async(r,e,t,n)=>await(await Qe(t,e,n)).XCetusModule.cancelRedeemPayload(r),Ql=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=Yl.TransactionType.Other;txSubType="xCETUSCancelRedeem";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 Jl=require("@msafe/sui3-utils");var zo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Jl.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";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 Zl=require("@msafe/sui3-utils");var Qo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Zl.TransactionType.Other;txSubType="xCETUSConvert";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 tp=require("@msafe/sui3-utils");var Yo=class r extends k{constructor(t){super(t);this.data=t}data;txType=tp.TransactionType.Other;txSubType="xCETUSRedeem";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await Ql(s,o,a,n)}static fromData(t){return new r(t)}};var ep=require("@msafe/sui3-utils");var Jo=class r extends k{constructor(t){super(t);this.data=t}data;txType=ep.TransactionType.Other;txSubType="xCETUSRedeemLock";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 Zo=class{application="cetus";supportSDK="@mysten/sui-v2";async deserialize(e){console.log("Cetus helper deserialize input: ",e);let{appContext:t}=e;return{txType:np.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 jp=require("@msafe/sui3-utils");var fs=require("@mysten/sui/grpc"),ap=require("@mysten/sui/transactions");var op=require("@mysten/sui/grpc"),rp=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:rp.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 op.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 fs.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:ap.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 hs={};ms(hs,{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 gs={};ms(gs,{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",ip=hs,sp=gs,lf=new Map([["dev",{env:"dev",rpc:{url:tf},backend:{url:rf},contract:ip}],["stg",{env:"stg",rpc:{url:ef},backend:{url:af},contract:ip}],["prev",{env:"prev",rpc:{url:nf},backend:{url:sf},contract:sp}],["prod",{env:"prod",rpc:{url:of},backend:{url:cf},contract:sp}]]);function cp(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=cp(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 Ts=require("@mysten/sui/transactions"),On=require("@mysten/sui/utils");var ys=50n,ar=10000n,pp=25n,bs=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 up(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 Cp=require("@mysten/bcs");var vn=class extends j{constructor(e,t){super(3,e,{context:t})}};var fp=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 mp(r){return r.fields&&typeof r.fields=="object"&&!("balance"in r)&&!("config"in r)&&!("status"in r)?r.fields:r}function dp(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 hp(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 gp(r){return r.json&&typeof r.json=="object"?mp(r.json):null}async function yp(r,e){try{let t=uf(r),{object:n}=await t({objectId:e,include:{json:!0,type:!0}}),o=gp(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 bp(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=gp(n);if(o)return{data:{objectId:n.objectId,type:n.type,content:{dataType:"moveObject",type:n.type,fields:o}}}})}async function Tp(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 Sp(r,e){return(await r.listBalances({owner:e})).balances.map(n=>({coinType:n.coinType,totalBalance:n.balance}))}async function wp(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 Ip(r,e=0,t=0){let n=r.commandResults?.[e]?.returnValues?.[t];if(!n)throw new Error("Missing command result");return BigInt(fp.bcs.u64().parse(n.bcs))}var lr=class{constructor(e){this.results=e}results;getU64(e=0,t=0){try{return Ip(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 Cp.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 kp=pr.bcs.struct("StreamMetadata",{groupId:pr.bcs.string(),name:pr.bcs.string()}),mf=64;function Dp(r){return vp(r),kp.serialize(r).toBase64()}function An(r){let e=kp.fromBase64(r);return vp(e),e}function vp(r){if(!xp(r.name))throw new z("Invalid metadata: Name contains unknown character");if(!xp(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 xp(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 Ap=require("nanoid");function Mp(){return(0,Ap.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:Dp({name:e.name,groupId:Mp()}),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 Ts.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:ys,denominator:ar},claimFeePercent:{numerator:pp,denominator:ar},flatFeePerStream:bs}}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 bs}getStreamFeeLocal(e){return e*ys/ar}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new Ts.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 Op="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():up(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(Op)}};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"),Ss=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 ws(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(Ss.Duration.fromMillis(Number(t*e.steps))),o={timeStart:e.timeStart,timeEnd:n,interval:Ss.Duration.fromMillis(Number(t)),steps:e.steps};return this.validateTimeline(o),o}async getBalance(e,t){let n=await Tp(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 Sp(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)}},ws=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 wp(this.suiClient,e)}};var De=require("@mysten/sui/utils"),As=require("luxon");var Bn=require("@mysten/sui/transactions"),Nn=require("@mysten/sui/utils"),Rp=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"),Pp=(1n<<64n)-1n,yr=1e3;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.DateTime.fromMillis(t*yr)}function Cs(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 Cs(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 Is(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return Cs(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:Is((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===Pp?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=Rp.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 yp(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:dp(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 ks(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 xs=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 xs(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 vs(r,e,t){let n=new En(e),o=new Wn(r,n,t);return await ks(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 Ds(t,n,o));this.suiClient=t;this.idIter=n;this.options=o}suiClient;idIter;options},Ds=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 bp(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 vs(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 vs(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=Bp(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=Bp(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++,Np(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 Bp(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)=>As.DateTime.fromISO(n[0].createDate).toMillis()-As.DateTime.fromISO(t[0].createDate).toMillis())}function Np(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=>{Np(n,e)&&(t=!0)}),t}async function bf(r,e,t){let n=await Ep(t,e);return ke.fromObjectData(r,e,n)}async function Tf(r,e,t){let n=[];for(;n.length<e.length;){let o=await Ep(t,e[n.length]);n.push(o)}return Tr.newFromObjectResponse(r,e,n)}async function Ep(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:Ms(r?.status),coinType:Wp(r?.coinType),sender:_p(r?.sender)}}function wf(r){return{status:Ms(r?.status),coinType:Wp(r?.coinType),recipient:_p(r?.recipient)}}function Ms(r){return r===void 0||r.length===0?"all":Array.isArray(r)?r.reduce((e,t)=>{let n=Ms(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 Wp(r){if(r)return Array.isArray(r)?r.length!==0?r.map(e=>(0,De.normalizeStructTag)(e)):void 0:(0,De.normalizeStructTag)(r)}function _p(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 Lp(r,e,t,n="0x2::sui::SUI",o=Cf){let a=new Os(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 Os=class extends rn{constructor(t,n,o,a){super(new Ps(t,n,o,a));this.suiClient=t;this.owner=n;this.coinType=o;this.reqPageSize=a}suiClient;owner;coinType;reqPageSize},Ps=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 hp(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 Rs=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}},Bs=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 Lp(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 Bs(e,this.globals.suiClient);this.globals.connectWallet(t)}connectMSafeAccount(e){let t=new Rs(e);this.globals.connectWallet(t)}async createStream(e){return this.builder().createStreams(e)}async getStream(e){return 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=jp.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 Up=require("@msafe/sui3-utils");var jn=class extends Vt{constructor(t){super(t);this.data=t}data;txType=Up.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 Gp=require("@msafe/sui3-utils");var Un=class extends Vt{constructor(t){super(t);this.data=t}data;txType=Gp.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 qp=require("@msafe/sui3-utils");var Gn=class extends Vt{constructor(t){super(t);this.data=t}data;txType=qp.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 Fp=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,Fp.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 Kp=require("@msafe/sui3-utils");var Fn=class extends Vt{constructor(t){super(t);this.data=t}data;txType=Kp.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 $p=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,$p.buildCoinTransferTxb)(n,this.data,o.address)}static fromData(t){return new r(t)}};var Vp=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,Vp.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 _s=require("@msafe/sui3-utils");var Hp=!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 Ns(){if(!Hp)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),Hp=!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 Es=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 Xp(r,e,t,n){let[o]=await(0,qt.withdrawCoinPTB)(r,e,t);return r.transferObjects([o],r.pure.address(n)),r}async function zp(r,e,t,n){let[o]=await(0,qt.borrowCoinPTB)(r,e,t);return r.transferObjects([o],r.pure.address(n)),r}async function Ws(r,e,t,n){return await(0,qt.repayCoinPTB)(r,e,t,{amount:n}),r}async function Qp(r,e){let t=new Es.Transaction,n=await(0,qt.getUserAvailableLendingRewards)(e,{client:r});return await(0,qt.claimLendingRewardsPTB)(t,n),t}async function Yp(r,e){let t=new Es.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 Qp(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 Yp(t.suiClient,t.account.address)}static fromData(t){return new r(t)}};var Zp=require("@mysten/sui/transactions");var Jp=require("@naviprotocol/lending");async function ae(r){return(0,Jp.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 Zp.Transaction;console.log("build",this.data);let s=await ae(n);return await zp(a,s,o,t.account.address)}static fromData(t){return new r(t)}};var tu=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 tu.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 eu=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 eu.Transaction;console.log("build",this.data);let m=await ae(a);if(a===0){let[w]=c.splitCoins(c.gas,[s]);return Ws(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 Ws(c,m,c.object(S),s)}static fromData(t){return new r(t)}};var nu=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 nu.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 ou=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 ou.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 ru=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),ru.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 Ns(),e.appContext?.content)return{txType:_s.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:_s.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n}=e,o;switch(await Ns(),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"),au=require("@mysten/bcs"),iu=require("@mysten/sui/transactions");var kf="msafe-plain-tx",su=Vn.TransactionSubTypes.others.plain,Ls=class r extends k{constructor(t){super(t);this.data=t}data;txType=Vn.TransactionType.Other;txSubType=su;async build(t){return iu.Transaction.from((0,au.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:su,intentionData:{content:t}}}async build(e){let{suiGrpcClient:t,network:n,account:o}=e;return Ls.fromData(e.intentionData).build({suiGrpcClient:t,network:n,account:o})}};var Ue=require("@mysten/sui/transactions");function cu(r,e){return new er({network:tr(r),baseUrl:e})}var lu="0x2::sui::SUI",pu=1e8;async function uu(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 js(e))}addGrpcHelper(e){this.setApp(e.application,new Us(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)}},js=class{constructor(e){this.helper=e}helper;async deserialize(e){let t=cu(e.network,e.clientUrl),n=await uu(e.transactionBlock);return this.helper.deserialize({...e,suiClient:t,transaction:n})}async build(e){let t=cu(e.network,e.clientUrl),{balance:n}=await t.getBalance({owner:e.account.address,coinType:lu});if(Number(n.balance)<pu)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)}},Us=class{constructor(e){this.helper=e}helper;async deserialize(e){let t=Dn(e.network,e.clientUrl),n=await uu(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:lu});if(Number(n.balance)<pu)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 wu=require("@msafe/sui3-utils"),Iu=require("@scallop-io/sui-scallop-sdk");var Nt=require("@msafe/sui3-utils"),Ks=require("@scallop-io/sui-scallop-sdk");var mu=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,mu.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 Gs=require("@mysten/sui/bcs"),Me=require("@mysten/sui/utils"),qs=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 Gs.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 Gs.bcs.U64.parse(new Uint8Array(t))}typeArg(e){return(0,Me.normalizeStructTag)(this.txBlockTransactions.typeArguments[e])}txArg(e){return this.transaction.blockData.inputs[e]}},_=qs;var Fs=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=Fs;var Oe=require("@mysten/sui/utils"),du=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 fu=(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(`${Ks.OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::redeem_rewards`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`),n=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake`);return e&&(t||n)}get helperClaimLendingReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(t=>new _(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,`${Ks.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"),hu=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=fu(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,`${hu.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 gu=_t(require("sort-keys-recursive")),M=class{constructor(e){this.data=e}data;get application(){return"msafe-core"}serialize(){return JSON.stringify((0,gu.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 yu=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,yu.SUI_TYPE_ARG);b.sui?b.sui.push(U):b.sui=[U]}if(D&&await du(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 bu=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,bu.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 Tu=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,Tu.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 Su=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,Su.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 Iu.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:wu.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 Ku=require("@msafe/sui3-utils");var gn=require("@msafe/sui3-utils"),Re=require("@mysten/sui/utils");var Nu=require("@suilend/sui-fe");var Bu=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"),Vs=_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 Vs.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 Vs.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 xu=require("@mysten/sui/transactions");var Cu=_t(require("sort-keys-recursive")),Ft=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,Cu.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 xu.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 Au=require("@mysten/sui/transactions");var ku=require("@mysten/sui/utils"),hn=require("@suilend/sdk"),Du=require("@suilend/sui-fe"),vu=_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,ku.normalizeStructTag)(c.coinType.name),side:o})).filter(c=>!(0,Du.isSendPoints)(c.rewardCoinType)&&!!s.rewards[Number(c.rewardIndex)]&&new vu.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 Au.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 Mu=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 Mu.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 Ou=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 Ou.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 Pu=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 Pu.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 Ru=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 Ru.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:Bu.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 Hs=async(r,e)=>{let t=await Ba(r,e),n=await fetch(`${Nu.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 Wu=require("@mysten/sui/transactions"),Hn=require("@suilend/springsui-sdk");var Eu=_t(require("sort-keys-recursive")),zt=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,Eu.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 Wu.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 _u=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 _u.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 Lu=require("@mysten/sui/transactions"),ju=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 ju.LstClient.initialize(n,Object.values(s).find(w=>w.type===this.data.outCoinType)),S=new Lu.Transaction;return b.mintAmountAndRebalanceAndSendToUser(S,o.address,this.data.amount),S}static fromData(t){return console.log("StakeIntention.fromData",t),new r(t)}};var Uu=require("@mysten/sui/transactions"),Ga=require("@suilend/sdk"),Gu=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 Gu.LstClient.initialize(n,Object.values(s).find(D=>D.type===this.data.outCoinType)),S=new Uu.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 qu=require("@mysten/sui/transactions"),Fu=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 Fu.LstClient.initialize(n,Object.values(s).find(w=>w.type===this.data.inCoinType)),S=new qu.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 Hs(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:Ku.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 Hs(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 Hu=require("@msafe/sui3-utils");var Xs=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:Xs.TransactionType.Other,type:"mint",intentionData:{amount:t}}}decodeRedeem(e){let{event:{lst_amount_in:t}}=e;return console.log("Decoder.decodeRedeem",t),{txType:Xs.TransactionType.Other,type:"redeem",intentionData:{amount:t}}}};var $u=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 $u.LST(a).mint(o,n.address);return c.setGasBudget(1e8),c}static fromData(t){return console.log("MintIntention.fromData",t),new r(t)}};var Vu=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 Vu.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:Hu.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"),za=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 za.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){let t=new za.Decimal(Ke.bcs.u64().parse(Uint8Array.from((0,Fe.fromBase64)(this.inputs[e].Pure.bytes))));return t.gt(Number.MAX_SAFE_INTEGER)?t.toString():t.toNumber()}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 Qa=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 Ya=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 Ja=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 Za=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 ti=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 ei=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 ni=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 oi=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 ri=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 ai=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 ii=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 si=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 ci=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 zs=require("@mysten/sui/transactions"),Qs=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 zs.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,Qs.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 zs.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,Qs.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 li=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 pi=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 ui=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=ti.fromData(e.intentionData);break;case"AddLiquidity":a=Qa.fromData(e.intentionData);break;case"IncreaseLiquidity":a=oi.fromData(e.intentionData);break;case"DecreaseLiquidity":a=ei.fromData(e.intentionData);break;case"DecreaseLiquidityWithReturn":a=ni.fromData(e.intentionData);break;case"RemoveLiquidity":a=ii.fromData(e.intentionData);break;case"removeLiquidityWithReturn":a=si.fromData(e.intentionData);break;case"CollectFee":a=Ja.fromData(e.intentionData);break;case"CollectReward":a=Za.fromData(e.intentionData);break;case"Burn":a=Ya.fromData(e.intentionData);break;case"Swap":a=ci.fromData(e.intentionData);break;case"PrixJoin":a=ai.fromData(e.intentionData);break;case"PrixClaim":a=ri.fromData(e.intentionData);break;case"SwapExactBaseForQuote":a=li.fromData(e.intentionData);break;case"SwapExactQuoteForBase":a=pi.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 mi=require("@msafe/sui3-utils"),fi=require("@mysten/bcs"),Js=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 di=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(fi.bcs.u64().parse(Uint8Array.from((0,fi.fromBase64)(n.Pure.bytes))))}decodeStake(){return{txType:mi.TransactionType.Other,type:"Stake",intentionData:{amount:this.decodeSplitAmount()}}}decodeUnStake(){return{txType:mi.TransactionType.Other,type:"UnStake",intentionData:{amount:this.decodeSplitAmount()}}}decodeClaimTicket(){let e=this.helper.decodeOwnedObjectId(2);return{txType:mi.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 Ys(e,this.txb)}},Ys=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,Js.normalizeSuiAddress)(t)}};var ym=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 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 gi=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 yi=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 bi=class{application="volo";supportSDK="@mysten/sui-v2";async deserialize(e){let n=new di(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=gi.fromData(e.intentionData);break;case"UnStake":a=yi.fromData(e.intentionData);break;case"ClaimTicket":a=hi.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 Zs=require("@cetusprotocol/common-sdk"),fe=require("@msafe/sui3-utils"),yn=require("@mysten/bcs"),bn=require("@mysten/sui/bcs");var Ti=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,Zs.asIntN)(BigInt(this.getU32(this.getInputIndex(e,2)))).toString()),upperTick:Number((0,Zs.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 Si=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,Si.getQuote)({tokenIn:e.tokenIn.address,tokenOut:e.tokenOut.address,amountIn:new xm.Decimal(e.amountIn).mul(10**e.tokenIn.decimals).toString()}),s=await(0,Si.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 wi=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 Ii=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 Ci=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 xi=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 ki=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 Di=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 vi=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 Ai=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 Mi=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 Ti(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=Di.fromData(e.intentionData);break;case"ProvideLiquidity":a=vi.fromData(e.intentionData);break;case"RemoveLiquidity":a=Ai.fromData(e.intentionData);break;case"ClosePosition":a=Ii.fromData(e.intentionData);break;case"CollectFee":a=Ci.fromData(e.intentionData);break;case"CollectRewards":a=xi.fromData(e.intentionData);break;case"CollectRewardsAndFee":a=ki.fromData(e.intentionData);break;case"Aggregator7KSwap":a=wi.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 Oi(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=Oi(n,a.tokenX.decimals,b),O=Oi(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=Oi(n,a.tokenX.decimals,c),C=Oi(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 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,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 Ri=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 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,{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 Ni=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 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,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 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,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 _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,{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 Li=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 nc=require("@mysten/sui/transactions"),oc=require("@suilend/springsui-sdk"),ec={id:"0x0431232199873db77a92aa645cd43521437e9cc5c6fff07fd03edb88afe0b25a",type:"0x2b6602099970374cf58a2a1b9d96f005fccceb81e92eb059873baf420eb6c717::x_sui::X_SUI",weightHookId:"0x9e35c13dbb0bc437e8ad5a95ec463622f58763e060552ae8d100db77f4904601"},ud=async(r,e,t)=>{let n=await oc.LstClient.initialize(r,r,ec),o=new nc.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 oc.LstClient.initialize(r,r,ec),o=await r.listCoins({owner:e,coinType:ec.type,limit:1e3});if(o.objects.length===0)throw new Error("No lst coins found");let a=new nc.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 ji=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 Ui=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 Gi=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 qi=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 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,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 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,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 $i=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 Vi=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=Ui.fromData(e.intentionData);break;case"AddLiquidity":t=Pi.fromData(e.intentionData);break;case"AddLiquiditySingleSide":t=Ri.fromData(e.intentionData);break;case"ClaimRewards":t=Ei.fromData(e.intentionData);break;case"ClaimAllRewards":t=Bi.fromData(e.intentionData);break;case"ClaimRewardsAs":t=Ni.fromData(e.intentionData);break;case"RemoveLiquidity":t=Li.fromData(e.intentionData);break;case"StakeXSui":t=ji.fromData(e.intentionData);break;case"UnstakeXSui":t=Gi.fromData(e.intentionData);break;case"ManageLiquidity":t=Wi.fromData(e.intentionData);break;case"ManageLiquiditySingleSide":t=_i.fromData(e.intentionData);break;case"Bond":t=qi.fromData(e.intentionData);break;case"Extend":t=Fi.fromData(e.intentionData);break;case"Merge":t=Ki.fromData(e.intentionData);break;case"Unbond":t=$i.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 ui,new Vi,new xa,new bi,new Do,new Na,new Fa,new ao,new Mi,new Ha]);
|
|
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),ms=(r,e)=>{for(var t in e)Jn(r,t,{get:e[t],enumerable:!0})},wc=(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)):{},wc(e||!r||!r.__esModule?Jn(t,"default",{value:r,enumerable:!0}):t,r)),Md=r=>wc(Jn({},"__esModule",{value:!0}),r);var Em=Ad((Nm,tc)=>{"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,rc=d[3]|0,Y=rc&8191,J=rc>>>13,ac=d[4]|0,Z=ac&8191,tt=ac>>>13,ic=d[5]|0,et=ic&8191,nt=ic>>>13,sc=d[6]|0,ot=sc&8191,rt=sc>>>13,cc=d[7]|0,at=cc&8191,it=cc>>>13,lc=d[8]|0,st=lc&8191,ct=lc>>>13,pc=d[9]|0,lt=pc&8191,pt=pc>>>13,uc=h[0]|0,ut=uc&8191,mt=uc>>>13,mc=h[1]|0,dt=mc&8191,ft=mc>>>13,dc=h[2]|0,ht=dc&8191,gt=dc>>>13,fc=h[3]|0,yt=fc&8191,bt=fc>>>13,hc=h[4]|0,Tt=hc&8191,St=hc>>>13,gc=h[5]|0,wt=gc&8191,It=gc>>>13,yc=h[6]|0,Ct=yc&8191,xt=yc>>>13,bc=h[7]|0,kt=bc&8191,Dt=bc>>>13,Tc=h[8]|0,vt=Tc&8191,At=Tc>>>13,Sc=h[9]|0,Mt=Sc&8191,Ot=Sc>>>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 Hi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Hi>>>26)|0,Hi&=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 Xi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Xi>>>26)|0,Xi&=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 zi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(zi>>>26)|0,zi&=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 Qi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Qi>>>26)|0,Qi&=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 Yi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Yi>>>26)|0,Yi&=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 Ji=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Ji>>>26)|0,Ji&=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 Zi=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(Zi>>>26)|0,Zi&=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 ts=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ts>>>26)|0,ts&=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 es=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(es>>>26)|0,es&=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 ns=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ns>>>26)|0,ns&=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 os=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(os>>>26)|0,os&=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 rs=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(rs>>>26)|0,rs&=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 as=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(as>>>26)|0,as&=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 is=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(is>>>26)|0,is&=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 ss=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ss>>>26)|0,ss&=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 cs=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(cs>>>26)|0,cs&=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 ls=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ls>>>26)|0,ls&=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 ps=(I+f|0)+((l&8191)<<13)|0;I=(g+(l>>>13)|0)+(ps>>>26)|0,ps&=67108863,f=Math.imul(lt,Mt),l=Math.imul(lt,Ot),l=l+Math.imul(pt,Mt)|0,g=Math.imul(pt,Ot);var us=(I+f|0)+((l&8191)<<13)|0;return I=(g+(l>>>13)|0)+(us>>>26)|0,us&=67108863,T[0]=Hi,T[1]=Xi,T[2]=zi,T[3]=Qi,T[4]=Yi,T[5]=Ji,T[6]=Zi,T[7]=ts,T[8]=es,T[9]=ns,T[10]=os,T[11]=rs,T[12]=as,T[13]=is,T[14]=ss,T[15]=cs,T[16]=ls,T[17]=ps,T[18]=us,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 Sn(){Wt.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(Sn,Wt);function Ve(){Wt.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(Ve,Wt),Ve.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 Sn;else if(i==="p25519")p=new Ve;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 tc>"u"||tc,Nm)});var Hf={};ms(Hf,{appHelpers:()=>Vf});module.exports=Md(Hf);var Ac=require("@msafe/sui3-utils");var pe=require("@alphafi/alphafi-sdk"),He=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:He.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:He.TransactionType.Other,type:"depositSingleAsset",intentionData:{poolName:e,amount:n}}}decodeWithdraw(e){let t=this.extractXTokensAmount();return console.log("Decoder.decodeWithdraw",t),{txType:He.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:He.TransactionType.Other,type:"withdrawAlpha",intentionData:{withdrawFromLocked:Number(n)>0,xTokensAmount:t}}}decodeClaimReward(){return{txType:He.TransactionType.Other,type:"claimReward",intentionData:{}}}};var Cc=require("@alphafi/alphafi-sdk");var Ic=_t(require("sort-keys-recursive")),v=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,Ic.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,Cc.claimRewardTxb)(n.address)}static fromData(t){return new r(t)}};var xc=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,xc.depositDoubleAssetTxb)(o,n.address,a,s)}static fromData(t){return console.log("DepositDoubleAssetIntention.fromData",t),new r(t)}};var kc=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,kc.depositSingleAssetTxb)(o,n.address,a)}static fromData(t){return console.log("DepositSingleAssetIntention.fromData",t),new r(t)}};var Dc=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,Dc.withdrawTxb)(a,o,n.address)}static fromData(t){return console.log("WithdrawIntention.fromData",t),new r(t)}};var vc=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,vc.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:Ac.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 Zc=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 Bc=require("@msafe/sui3-utils");var Oc=require("@mysten/sui/transactions"),Pc=require("bucket-protocol-sdk");var Mc=require("bucket-protocol-sdk"),Lt=(r,e)=>{let t=r==="sui:mainnet"?"mainnet":"testnet";return new Mc.BucketClient(t,e.address)};var Rc=async(r,e,t)=>{let{coinType:n,amount:o,buckToCoin:a}=r,s=new Oc.Transaction,c=Lt(t,e);return await(0,Pc.buildPsmTx)(c,s,n,o,a,e.address),s};var po=class r extends v{constructor(t){super(t);this.data=t}data;txType=Bc.TransactionType.Other;txSubType="psm";async build(t){let{account:n,network:o}=t;return await Rc(this.data,n,o)}static fromData(t){return new r(t)}};var Lc=require("@msafe/sui3-utils");var wn=require("@mysten/sui/transactions"),Te=require("bucket-protocol-sdk");var Nc=async(r,e,t)=>{let{collateralType:n,collateralAmount:o,borrowAmount:a,insertionPlace:s,strapId:c}=r,m=new wn.Transaction,b=Lt(t,e);return await(0,Te.buildBorrowTx)(b,m,n,o,a,e.address,s,c),m},Ec=async(r,e,t)=>{let{collateralType:n,withdrawAmount:o,insertionPlace:a,strapId:s}=r,c=new wn.Transaction,m=Lt(t,e);return await(0,Te.buildWithdrawTx)(m,c,n,o,e.address,a,s),c},Wc=async(r,e,t)=>{let{collateralType:n,repayAmount:o,withdrawAmount:a,isSurplus:s,insertionPlace:c,strapId:m}=r,b=new wn.Transaction,S=Lt(t,e);return await(0,Te.buildRepayTx)(S,b,n,o,a,e.address,s,c,m),b},_c=async(r,e,t)=>{let{collateralType:n,recipient:o,strapId:a}=r,s=new wn.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=Lc.TransactionType.Other;txSubType="borrow";async build(t){let{account:n,network:o}=t;return await Nc(this.data,n,o)}static fromData(t){return new r(t)}};var jc=require("@msafe/sui3-utils");var mo=class r extends v{constructor(t){super(t);this.data=t}data;txType=jc.TransactionType.Other;txSubType="repay";async build(t){let{account:n,network:o}=t;return await Wc(this.data,n,o)}static fromData(t){return new r(t)}};var Uc=require("@msafe/sui3-utils");var fo=class r extends v{constructor(t){super(t);this.data=t}data;txType=Uc.TransactionType.Other;txSubType="withdraw";async build(t){let{account:n,network:o}=t;return await Ec(this.data,n,o)}static fromData(t){return new r(t)}};var Gc=require("@msafe/sui3-utils");var ho=class r extends v{constructor(t){super(t);this.data=t}data;txType=Gc.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 r(t)}};var Cn=require("@msafe/sui3-utils");var In=require("@mysten/sui/transactions"),Se=require("bucket-protocol-sdk");var qc=async(r,e,t)=>{let{coinType:n,amount:o,isStake:a}=r,s=new In.Transaction,c=Lt(t,e);return await(0,Se.buildSBUCKDepositTx)(c,s,n,o,e.address,a),s},Fc=async(r,e,t)=>{let{stakeProofs:n,amount:o,isStake:a,toBuck:s}=r,c=new In.Transaction,m=Lt(t,e);return await(0,Se.buildSBUCKUnstakeTx)(m,c,n,o,e.address,a,s),c},Kc=async(r,e,t)=>{let{amount:n}=r,o=new In.Transaction,a=Lt(t,e);return await(0,Se.buildSBUCKWithdrawTx)(a,o,n,e.address),o},$c=async(r,e,t)=>{let{stakeProofs:n}=r,o=new In.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=Cn.TransactionType.Other;txSubType="sbuck-deposit";async build(t){let{account:n,network:o}=t;return await qc(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=Cn.TransactionType.Other;txSubType="sbuck-unstake";async build(t){let{account:n,network:o}=t;return await Fc(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=Cn.TransactionType.Other;txSubType="sbuck-withdraw";async build(t){let{account:n,network:o}=t;return await Kc(this.data,n,o)}static fromData(t){return new r(t)}},To=class r extends v{constructor(t){super(t);this.data=t}data;txType=Cn.TransactionType.Other;txSubType="sbuck-claim";async build(t){let{account:n,network:o}=t;return await $c(this.data,n,o)}static fromData(t){return new r(t)}};var xo=require("@msafe/sui3-utils");var So=require("@mysten/sui/transactions"),Xe=require("bucket-protocol-sdk");var Vc=async(r,e,t)=>{let{coinType:n,amount:o}=r,a=new So.Transaction,s=Lt(t,e);return await(0,Xe.buildTankDepositTx)(s,a,n,o,e.address),a},Hc=async(r,e,t)=>{let{coinType:n,amount:o}=r,a=new So.Transaction,s=Lt(t,e);return await(0,Xe.buildTankWithdrawTx)(s,a,n,o,e.address),a},Xc=async(r,e,t)=>{let{coinType:n}=r,o=new So.Transaction,a=Lt(t,e);return await(0,Xe.buildTankClaimTx)(a,o,n,e.address),o};var zc=require("@mysten/sui/transactions"),Qc=require("bucket-protocol-sdk");var Yc=async(r,e,t)=>{let{coinType:n,proofCount:o}=r,a=new zc.Transaction,s=Lt(t,e);return await(0,Qc.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 Vc(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 Hc(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 Xc(this.data,n,o)}static fromData(t){return new r(t)}};var Jc=require("@msafe/sui3-utils");var ko=class r extends v{constructor(t){super(t);this.data=t}data;txType=Jc.TransactionType.Other;txSubType="lock-claim";async build(t){let{account:n,network:o}=t;return await Yc(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:Zc.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 np=require("@msafe/sui3-utils");var cl=require("@msafe/sui3-utils");var tl=_t(require("sort-keys-recursive")),k=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,tl.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",el=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})},xn=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},ze=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 nl=async(r,e,t,n)=>await(await ee(t,e,n)).Pool.createPoolPayload(r),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.createAddLiquidityFixTokenPayload(r?.parameter),al=async(r,e,t,n)=>await(await ee(t,e,n)).Position.closePositionPayload(r),il=async(r,e,t,n)=>await(await ee(t,e,n)).Position.removeLiquidityPayload(r),sl=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=cl.TransactionType.Other;txSubType="OpenAndAddLiquidity";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 ll=require("@msafe/sui3-utils");var Ao=class r extends k{constructor(t){super(t);this.data=t}data;txType=ll.TransactionType.Other;txSubType="ClaimFeeAndMining";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await sl(s,o,a,n)}static fromData(t){return new r(t)}};var pl=require("@msafe/sui3-utils");var Mo=class r extends k{constructor(t){super(t);this.data=t}data;txType=pl.TransactionType.Other;txSubType="CreatePool";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 ul=require("@msafe/sui3-utils");var Oo=class r extends k{constructor(t){super(t);this.data=t}data;txType=ul.TransactionType.Other;txSubType="DecreaseLiquidity";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 wl=require("@msafe/sui3-utils");var ml=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.openPositionAddLiquidityStakePayload(r),dl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.addLiquidityFixCoinPayload(r),fl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.removeLiquidityPayload(r);var hl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.removeLiquidityPayload(r),gl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.claimFeeAndClmmReward(r),yl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.harvestPayload(r),bl=async(r,e,t,n)=>{let o=await Kt(t,e,n),a=Object.values(r);return await o.Farms.batchHarvestPayload(a)},Tl=async(r,e,t,n)=>await(await Kt(t,e,n)).Farms.depositPayload(r),Sl=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=wl.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";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 Il=require("@msafe/sui3-utils");var Ro=class r extends k{constructor(t){super(t);this.data=t}data;txType=Il.TransactionType.Other;txSubType="FarmingBatchHarvest";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 Cl=require("@msafe/sui3-utils");var Bo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Cl.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";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 xl=require("@msafe/sui3-utils");var No=class r extends k{constructor(t){super(t);this.data=t}data;txType=xl.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";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 kl=require("@msafe/sui3-utils");var Eo=class r extends k{constructor(t){super(t);this.data=t}data;txType=kl.TransactionType.Other;txSubType="FarmingHarvest";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 Dl=require("@msafe/sui3-utils");var Wo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Dl.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";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 vl=require("@msafe/sui3-utils");var _o=class r extends k{constructor(t){super(t);this.data=t}data;txType=vl.TransactionType.Other;txSubType="FarmingRemoveLiquidity";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 Al=require("@msafe/sui3-utils");var Lo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Al.TransactionType.Other;txSubType="FarmingStake";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 jo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Ml.TransactionType.Other;txSubType="FarmingUnstake";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await Sl(s,o,a,n)}static fromData(t){return new r(t)}};var Ol=require("@msafe/sui3-utils");var Uo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Ol.TransactionType.Other;txSubType="IncreaseLiquidity";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 Bl=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 xn(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},Pl=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},Rl=async(r,e,t,n)=>r.type==="clmm"?Pl(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):Pl(r,e,t,n);var qo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Bl.TransactionType.Other;txSubType="PosVestingRedeem";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 Nl=require("@msafe/sui3-utils");var Fo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Nl.TransactionType.Other;txSubType="RemoveLiquidity";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 _l=require("@msafe/sui3-utils");var El=require("@mysten/sui/transactions");var Wl=async(r,e,t,n)=>{let{restituteMsafeFastRouterSwapParams:o}=await import("@cetusprotocol/aggregator-sdk"),a=await el(t,e,n),s=new El.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=_l.TransactionType.Other;txSubType="AggregatorSwap";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await Wl(s,o,a,n)}static fromData(t){return new r(t)}};var Ul=require("@msafe/sui3-utils");var ds=require("@mysten/sui/transactions");var Ll=async(r,e,t,n)=>{let o=await xn(t,e,n),a=new ds.Transaction;return a.setSender(e.address),await o.Vaults.deposit(r,a),a},jl=async(r,e,t,n)=>{let o=await xn(t,e,n),a=new ds.Transaction;return await o.Vaults.withdraw(r,a),a};var $o=class r extends k{constructor(t){super(t);this.data=t}data;txType=Ul.TransactionType.Other;txSubType="AddVaultsPosition";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 Gl=require("@msafe/sui3-utils");var Vo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Gl.TransactionType.Other;txSubType="RemoveVaultsPosition";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await jl(s,o,a,n)}static fromData(t){return new r(t)}};var $l=require("@msafe/sui3-utils");var Fl=require("@mysten/sui/transactions"),ql={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},Kl=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 Fl.Transaction;return a.forEach(m=>{c.moveCall({target:`${ql.published_at}::router::redeem`,typeArguments:[ql.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=$l.TransactionType.Other;txSubType="VestingRedeem";async build(t){let{account:n,network:o}=t,{txbParams:a}=this.data;return await Kl(a,n,o)}static fromData(t){return new r(t)}};var Yl=require("@msafe/sui3-utils");var Vl=async(r,e,t,n)=>await(await ze(t,e,n)).XCetusModule.convertPayload(r),Hl=async(r,e,t,n)=>await(await ze(t,e,n)).XCetusModule.redeemLockPayload(r),Xl=async(r,e,t,n)=>await(await ze(t,e,n)).XCetusModule.redeemDividendV3Payload(r.veNftId,r.rewardList),zl=async(r,e,t,n)=>await(await ze(t,e,n)).XCetusModule.cancelRedeemPayload(r),Ql=async(r,e,t,n)=>await(await ze(t,e,n)).XCetusModule.redeemPayload(r);var Xo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Yl.TransactionType.Other;txSubType="xCETUSCancelRedeem";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 Jl=require("@msafe/sui3-utils");var zo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Jl.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";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 Zl=require("@msafe/sui3-utils");var Qo=class r extends k{constructor(t){super(t);this.data=t}data;txType=Zl.TransactionType.Other;txSubType="xCETUSConvert";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 tp=require("@msafe/sui3-utils");var Yo=class r extends k{constructor(t){super(t);this.data=t}data;txType=tp.TransactionType.Other;txSubType="xCETUSRedeem";async build(t){let{suiGrpcClient:n,account:o,network:a}=t,{txbParams:s}=this.data;return await Ql(s,o,a,n)}static fromData(t){return new r(t)}};var ep=require("@msafe/sui3-utils");var Jo=class r extends k{constructor(t){super(t);this.data=t}data;txType=ep.TransactionType.Other;txSubType="xCETUSRedeemLock";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 Zo=class{application="cetus";supportSDK="@mysten/sui-v2";async deserialize(e){console.log("Cetus helper deserialize input: ",e);let{appContext:t}=e;return{txType:np.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 jp=require("@msafe/sui3-utils");var fs=require("@mysten/sui/grpc"),ap=require("@mysten/sui/transactions");var op=require("@mysten/sui/grpc"),rp=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:rp.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 kn(r,e){let t=tr(r),n=new op.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 fs.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:ap.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 hs={};ms(hs,{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 gs={};ms(gs,{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",ip=hs,sp=gs,lf=new Map([["dev",{env:"dev",rpc:{url:tf},backend:{url:rf},contract:ip}],["stg",{env:"stg",rpc:{url:ef},backend:{url:af},contract:ip}],["prev",{env:"prev",rpc:{url:nf},backend:{url:sf},contract:sp}],["prod",{env:"prod",rpc:{url:of},backend:{url:cf},contract:sp}]]);function cp(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 Qe=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 Qe(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new Qe(e.data.code)}throw new Qe(e.status.toString())}async getIncomingStreams(e,t){let n=await 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"},Ye=class r{signer;suiClient;envConfig;_backend;constructor(e,t){this.envConfig=e,this.suiClient=t??kn(pf[e.env],e.rpc.url),e.backend&&(this._backend=new rr(e.backend.url))}static new(e,t){let n=cp(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 On=require("@mysten/sui/transactions");var Ts=require("@mysten/sui/transactions"),Mn=require("@mysten/sui/utils");var ys=50n,ar=10000n,pp=25n,bs=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 up(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 Cp=require("@mysten/bcs");var Dn=class extends j{constructor(e,t){super(3,e,{context:t})}};var fp=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 mp(r){return r.fields&&typeof r.fields=="object"&&!("balance"in r)&&!("config"in r)&&!("status"in r)?r.fields:r}function dp(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 hp(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 gp(r){return r.json&&typeof r.json=="object"?mp(r.json):null}async function yp(r,e){try{let t=uf(r),{object:n}=await t({objectId:e,include:{json:!0,type:!0}}),o=gp(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 bp(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=gp(n);if(o)return{data:{objectId:n.objectId,type:n.type,content:{dataType:"moveObject",type:n.type,fields:o}}}})}async function Tp(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 Sp(r,e){return(await r.listBalances({owner:e})).balances.map(n=>({coinType:n.coinType,totalBalance:n.balance}))}async function wp(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 Ip(r,e=0,t=0){let n=r.commandResults?.[e]?.returnValues?.[t];if(!n)throw new Error("Missing command result");return BigInt(fp.bcs.u64().parse(n.bcs))}var lr=class{constructor(e){this.results=e}results;getU64(e=0,t=0){try{return Ip(this.results,e,t)}catch{let[n,o]=this.getLegacyValue(e,t);if(o!=="u64")throw new Dn("Invalid contract return type.",{ctx:{expectType:"u64",gotType:o}});return Cp.bcs.u64().parse(Uint8Array.from(n))}}getLegacyValue(e=0,t=0){let o=this.results.results?.[e]?.returnValues;if(!o?.[t])throw new Dn("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 kp=pr.bcs.struct("StreamMetadata",{groupId:pr.bcs.string(),name:pr.bcs.string()}),mf=64;function Dp(r){return vp(r),kp.serialize(r).toBase64()}function vn(r){let e=kp.fromBase64(r);return vp(e),e}function vp(r){if(!xp(r.name))throw new z("Invalid metadata: Name contains unknown character");if(!xp(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 xp(r){return/^[\x00-\x7F]+$/.test(r)}var An=require("@mysten/sui/utils");function ur(r,e){return(0,An.normalizeStructTag)(r)===(0,An.normalizeStructTag)(e)}function Ce(r,e){return(0,An.normalizeStructTag)(r)===(0,An.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 Ap=require("nanoid");function Mp(){return(0,Ap.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:Dp({name:e.name,groupId:Mp()}),coinType:(0,Mn.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 Ts.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:ys,denominator:ar},claimFeePercent:{numerator:pp,denominator:ar},flatFeePerStream:bs}}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,Mn.SUI_TYPE_ARG)?[{coinType:n,amount:t.totalAmount+t.streamFeeAmount+t.flatFeeAmount}]:[{coinType:n,amount:t.totalAmount+t.streamFeeAmount},{coinType:Mn.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 bs}getStreamFeeLocal(e){return e*ys/ar}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new Ts.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 Op="0x0000000000000000000000000000000000000000000000000000000000000006";var Je=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():up(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(Op)}};var Ze=class r extends Je{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 Je{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 tn=class{constructor(e){this.globals=e;let t=e.envConfig.contract;this.feeContract=new Ze(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 On.Transaction;return this.streamContract.setAutoClaim(o,{streamId:e,enabled:t,coinType:n})}claimStream(e,t){let n=new On.Transaction;return this.streamContract.claimStream(n,{streamId:e,coinType:t})}claimStreamByProxy(e,t){let n=new On.Transaction;return this.streamContract.claimStreamByProxy(n,{streamId:e,coinType:t})}cancelStream(e,t){let n=new On.Transaction;return this.streamContract.cancelStream(n,{streamId:e,coinType:t}),n}};var en=require("@mysten/sui/utils"),Ss=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 ws(e.suiClient),this.createStreamHelper=new tn(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(Ss.Duration.fromMillis(Number(t*e.steps))),o={timeStart:e.timeStart,timeEnd:n,interval:Ss.Duration.fromMillis(Number(t)),steps:e.steps};return this.validateTimeline(o),o}async getBalance(e,t){let n=await Tp(this.globals.suiClient,{owner:e,coinType:t}),o=await this.getCoinMeta(t);return{...n,coinType:(0,en.normalizeStructTag)(n.coinType),coinMeta:o}}async getAllBalance(e){let t=await Sp(this.globals.suiClient,e),n=await Promise.all(t.map(o=>this.getCoinMeta(o.coinType)));return t.map((o,a)=>({...o,coinType:(0,en.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)}},ws=class{constructor(e){this.suiClient=e;this.coinMetaReg=new Map}suiClient;coinMetaReg;async getCoinMeta(e){let t=(0,en.normalizeStructTag)(e||en.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 wp(this.suiClient,e)}};var De=require("@mysten/sui/utils"),As=require("luxon");var Rn=require("@mysten/sui/transactions"),Bn=require("@mysten/sui/utils"),Rp=require("luxon");var hr=class extends j{constructor(){super(7,"Connected wallet is not creator")}};var Pn=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"),Pp=(1n<<64n)-1n,yr=1e3;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.DateTime.fromMillis(t*yr)}function Cs(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 Rn.Transaction;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Pn;let e=new Rn.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 Pn;let t=new Rn.Transaction;return this.streamContract.setAutoClaim(t,{streamId:this.streamId,coinType:this.coinType,enabled:e}),t}async claimByProxy(){let e=new Rn.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,Bn.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 Cs(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return vn(e).groupId}get name(){let{metadata:e}=this.rawData.config;return vn(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Is(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return Cs(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:Is((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===Pp?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=Rp.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 yp(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,Bn.parseStructTag)(n.type),a=(0,Bn.normalizeStructTag)(o[0]),s=n.fields,c=sr(s.config),m=sr(s.status);return{coinType:a,autoClaim:s.auto_claim,balance:dp(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 nn=class extends j{constructor(e,t){super(9,`Invalid stream group: ${e}`,{context:t})}};async function ks(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 xs=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)}},on=class{constructor(e){this.requester=e;this.pager=new xs(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 vs(r,e,t){let n=new Nn(e),o=new En(r,n,t);return await ks(o)}var Nn=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]}},En=class extends on{constructor(t,n,o){super(new Ds(t,n,o));this.suiClient=t;this.idIter=n;this.options=o}suiClient;idIter;options},Ds=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 bp(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 nn("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 vs(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 vs(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 nn("Not same group ID");if(!this.checkStreamGroup(o))throw new nn("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 Wn=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 Nn(n.flat().map(s=>s.streamId));this.objectIter=new En(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=Bp(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=Bp(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++,Np(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 Bp(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)=>As.DateTime.fromISO(n[0].createDate).toMillis()-As.DateTime.fromISO(t[0].createDate).toMillis())}function Np(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=>{Np(n,e)&&(t=!0)}),t}async function bf(r,e,t){let n=await Ep(t,e);return ke.fromObjectData(r,e,n)}async function Tf(r,e,t){let n=[];for(;n.length<e.length;){let o=await Ep(t,e[n.length]);n.push(o)}return Tr.newFromObjectResponse(r,e,n)}async function Ep(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:Ms(r?.status),coinType:Wp(r?.coinType),sender:_p(r?.sender)}}function wf(r){return{status:Ms(r?.status),coinType:Wp(r?.coinType),recipient:_p(r?.recipient)}}function Ms(r){return r===void 0||r.length===0?"all":Array.isArray(r)?r.reduce((e,t)=>{let n=Ms(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 Wp(r){if(r)return Array.isArray(r)?r.length!==0?r.map(e=>(0,De.normalizeStructTag)(e)):void 0:(0,De.normalizeStructTag)(r)}function _p(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 Lp(r,e,t,n="0x2::sui::SUI",o=Cf){let a=new Os(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 Os=class extends on{constructor(t,n,o,a){super(new Ps(t,n,o,a));this.suiClient=t;this.owner=n;this.coinType=o;this.reqPageSize=a}suiClient;owner;coinType;reqPageSize},Ps=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 hp(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 Rs=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}},Bs=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 Lp(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=Ye.new(e,t),this.helper=new fr(this.globals)}connectSingleWallet(e){let t=new Bs(e,this.globals.suiClient);this.globals.connectWallet(t)}connectMSafeAccount(e){let t=new Rs(e);this.globals.connectWallet(t)}async createStream(e){return this.builder().createStreams(e)}async getStream(e){return ke.new(this.globals,e)}async getIncomingStreams(e,t=10){return Wn.newIncoming({globals:this.globals,query:e,pageSize:t})}async getOutgoingStreams(e,t=10){return Wn.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 tn(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 _n=class extends Vt{constructor(t){super(t);this.data=t}data;txType=jp.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 Up=require("@msafe/sui3-utils");var Ln=class extends Vt{constructor(t){super(t);this.data=t}data;txType=Up.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 Gp=require("@msafe/sui3-utils");var jn=class extends Vt{constructor(t){super(t);this.data=t}data;txType=Gp.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 qp=require("@msafe/sui3-utils");var Un=class extends Vt{constructor(t){super(t);this.data=t}data;txType=qp.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 Fp=require("@mysten/bcs"),je=require("@mysten/sui/bcs"),rn=require("@mysten/sui/utils");function Gn(r){if(!r.Pure)throw new Error("not pure argument");return(0,Fp.fromBase64)(r.Pure.bytes)}var an=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(Gn(t)))}decodeInputAddress(e){let t=this.getInputParam(e);return(0,rn.normalizeSuiAddress)(je.bcs.Address.parse(Gn(t)))}decodeInputString(e){let t=this.getInputParam(e);return je.bcs.String.parse(Gn(t))}decodeInputBool(e){let t=this.getInputParam(e);return je.bcs.Bool.parse(Gn(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,rn.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,rn.normalizeSuiAddress)(t)}static getPureInput(e,t){return(0,je.pureBcsSchemaFromTypeName)(t).parse(Gn(e))}typeArg(e){return(0,rn.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 an(t,this.txb))}getCreationInfoFromMoveCall(e){let t=e.decodeInputString(4),{name:n,groupId:o}=vn(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 Ze(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 an(e,this.txb)}};var Kp=require("@msafe/sui3-utils");var qn=class extends Vt{constructor(t){super(t);this.data=t}data;txType=Kp.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=Ye.new(t==="sui:mainnet"?"prod":"dev",{suiGrpcClient:o}),c=new Dr(a,n).decode(),m;switch(c.type){case"CreateStream":m=new Un(c.info);break;case"SetAutoClaim":m=new qn({streamId:c.streamId,enabled:c.enabled});break;case"Claim":m=new jn({streamId:c.streamId});break;case"ClaimByProxy":m=new Ln({streamId:c.streamId});break;case"Cancel":m=new _n({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 Un(t);break;case"Claim":n=new jn(t);break;case"ClaimByProxy":n=new Ln(t);break;case"SetAutoClaim":n=new qn(t);break;case"Cancel":n=new _n(t);break;default:throw new Error("not implemented")}return n.build({...e})}};var Fn=require("@msafe/sui3-utils");var $p=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,$p.buildCoinTransferTxb)(n,this.data,o.address)}static fromData(t){return new r(t)}};var Vp=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,Vp.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=Fn.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 Fn.TransactionSubTypes.assets.coin.send:a=Ar.fromData(e.intentionData);break;case Fn.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 _s=require("@msafe/sui3-utils");var Hp=!1,Kn={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 Ns(){if(!Hp)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&&(Kn.ProtocolPackage=e),t&&(Kn.borrowFee=t),n&&(Kn.borrowFeeAddress=n),o&&(Kn.pool=o),Hp=!0}catch(r){console.error(r.message)}}var re=Kn;var ve=require("@msafe/sui3-utils"),Ht=require("@mysten/bcs"),sn=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,sn.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,sn.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,sn.normalizeSuiAddress)(t)}typeArg(e){return(0,sn.normalizeStructTag)(this.moveCallData.typeArguments[e])}txArg(e){return this.moveCallData.arguments[e]}};var Es=require("@mysten/sui/transactions"),qt=require("@naviprotocol/lending");async function cn(r,e,t,n){return await(0,qt.depositCoinPTB)(r,e,t,{amount:n}),r}async function Xp(r,e,t,n){let[o]=await(0,qt.withdrawCoinPTB)(r,e,t);return r.transferObjects([o],r.pure.address(n)),r}async function zp(r,e,t,n){let[o]=await(0,qt.borrowCoinPTB)(r,e,t);return r.transferObjects([o],r.pure.address(n)),r}async function Ws(r,e,t,n){return await(0,qt.repayCoinPTB)(r,e,t,{amount:n}),r}async function Qp(r,e){let t=new Es.Transaction,n=await(0,qt.getUserAvailableLendingRewards)(e,{client:r});return await(0,qt.claimLendingRewardsPTB)(t,n),t}async function Yp(r,e){let t=new Es.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 Qp(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 Yp(t.suiClient,t.account.address)}static fromData(t){return new r(t)}};var Zp=require("@mysten/sui/transactions");var Jp=require("@naviprotocol/lending");async function ae(r){return(0,Jp.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 Zp.Transaction;console.log("build",this.data);let s=await ae(n);return await zp(a,s,o,t.account.address)}static fromData(t){return new r(t)}};var tu=require("@mysten/sui/transactions");async function ln(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 tu.Transaction;console.log("build",this.data);let m=await ae(a);if(a===0){let[C]=c.splitCoins(c.gas,[s]);return await cn(c,m,C,s)}let b=await ln(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 cn(c,m,c.object(S),s)}static fromData(t){return new r(t)}};var eu=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 eu.Transaction;console.log("build",this.data);let m=await ae(a);if(a===0){let[w]=c.splitCoins(c.gas,[s]);return Ws(c,m,w,s)}let b=await ln(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 Ws(c,m,c.object(S),s)}static fromData(t){return new r(t)}};var nu=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 nu.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 ou=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 ou.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 cn(s,S,x,b);continue}let w=await ln(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 cn(s,S,s.object(C),b)}return s}static fromData(t){return new r(t)}};var ru=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),ru.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 Ns(),e.appContext?.content)return{txType:_s.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:_s.TransactionType.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n}=e,o;switch(await Ns(),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 $n=require("@msafe/sui3-utils"),au=require("@mysten/bcs"),iu=require("@mysten/sui/transactions");var kf="msafe-plain-tx",su=$n.TransactionSubTypes.others.plain,Ls=class r extends k{constructor(t){super(t);this.data=t}data;txType=$n.TransactionType.Other;txSubType=su;async build(t){return iu.Transaction.from((0,au.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:$n.TransactionType.Other,txSubType:su,intentionData:{content:t}}}async build(e){let{suiGrpcClient:t,network:n,account:o}=e;return Ls.fromData(e.intentionData).build({suiGrpcClient:t,network:n,account:o})}};var Vn=require("@mysten/sui/transactions");function cu(r,e){return new er({network:tr(r),baseUrl:e})}var lu="0x2::sui::SUI",pu=1e8;async function uu(r){if((0,Vn.isTransaction)(r))return r;if(typeof r=="string"||r instanceof Uint8Array)return Vn.Transaction.from(r);if(r&&typeof r=="object"&&"build"in r&&typeof r.build=="function"){let e=await r.build({onlyTransactionKind:!0});return Vn.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 js(e))}addGrpcHelper(e){this.setApp(e.application,new Us(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)}},js=class{constructor(e){this.helper=e}helper;async deserialize(e){let t=cu(e.network,e.clientUrl),n=await uu(e.transactionBlock);return this.helper.deserialize({...e,suiClient:t,transaction:n})}async build(e){let t=cu(e.network,e.clientUrl),{balance:n}=await t.getBalance({owner:e.account.address,coinType:lu});if(Number(n.balance)<pu)throw new Error("Insufficient gas fee");let o=await this.helper.build({...e,suiClient:t});return o.setSender(e.account.address),o}},Us=class{constructor(e){this.helper=e}helper;async deserialize(e){let t=kn(e.network,e.clientUrl),n=await uu(e.transactionBlock);return this.helper.deserialize({...e,suiGrpcClient:t,transaction:n})}async build(e){let t=kn(e.network,e.clientUrl),{balance:n}=await t.core.getBalance({owner:e.account.address,coinType:lu});if(Number(n.balance)<pu)throw new Error("Insufficient gas fee");let o=await this.helper.build({...e,suiGrpcClient:t});return o.setSender(e.account.address),o}};var wu=require("@msafe/sui3-utils"),Iu=require("@scallop-io/sui-scallop-sdk");var Nt=require("@msafe/sui3-utils"),Ks=require("@scallop-io/sui-scallop-sdk");var mu=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,mu.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 Gs=require("@mysten/sui/bcs"),Me=require("@mysten/sui/utils"),qs=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 Gs.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 Gs.bcs.U64.parse(new Uint8Array(t))}typeArg(e){return(0,Me.normalizeStructTag)(this.txBlockTransactions.typeArguments[e])}txArg(e){return this.transaction.blockData.inputs[e]}},_=qs;var Fs=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=Fs;var Oe=require("@mysten/sui/utils"),du=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`},pn={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},Xt={unstakeObligation:(r,e,t)=>r.moveCall(`${pn.id}::user::unstake`,[pn.incentivePools,pn.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(`${pn.id}::user::redeem_rewards`,[pn.incentivePools,pn.incentiveAccounts,r.object(e),r.object(t),Oe.SUI_CLOCK_OBJECT_ID],[(0,Oe.normalizeStructTag)(n)])};var fu=(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(`${Ks.OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::redeem_rewards`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`),n=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake`);return e&&(t||n)}get helperClaimLendingReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(t=>new _(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,`${Ks.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"),hu=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=fu(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,`${hu.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 gu=_t(require("sort-keys-recursive")),M=class{constructor(e){this.data=e}data;get application(){return"msafe-core"}serialize(){return JSON.stringify((0,gu.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 yu=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,yu.SUI_TYPE_ARG);b.sui?b.sui.push(U):b.sui=[U]}if(D&&await du(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 bu=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,bu.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 Tu=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,Tu.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 Su=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,Su.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 Iu.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:wu.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 Ku=require("@msafe/sui3-utils");var hn=require("@msafe/sui3-utils"),Re=require("@mysten/sui/utils");var Nu=require("@suilend/sui-fe");var Bu=require("@msafe/sui3-utils"),Pe=require("@suilend/sdk");var Ue=require("@msafe/sui3-utils"),dn=require("@mysten/bcs"),mn=require("@mysten/sui/utils"),Ge=require("@suilend/sui-fe"),Vs=_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,mn.normalizeStructTag)(e.MintEvent.parsedJson.coin_type.name),n=e.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",t,n),{txType:Ue.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,mn.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 Vs.default((0,dn.toHex)((0,dn.fromBase64)(this.inputs[a].Pure.bytes)),16).toString(),c=s===Ge.MAX_U64.toString();return console.log("decodeWithdraw - isMax:",c,"inputIndex:",a,"inputValue:",s,"MAX_U64.toString():",Ge.MAX_U64.toString()),c&&(o=Ge.MAX_U64.toString()),{txType:Ue.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,mn.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 Vs.default((0,dn.toHex)((0,dn.fromBase64)(this.inputs[a].Pure.bytes)),16).toString(),c=s===Ge.MAX_U64.toString();return console.log("decodeBorrow - isMax:",c,"inputIndex:",a,"inputValue:",s,"MAX_U64.toString():",Ge.MAX_U64.toString()),c&&(o=Ge.MAX_U64.toString()),{txType:Ue.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,mn.normalizeStructTag)(e.RepayEvent.parsedJson.coin_type.name),n=e.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",t,n),{txType:Ue.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,mn.normalizeStructTag)(o.parsedJson.coin_type.name),s=o.parsedJson.liquidity_amount;t[a]=`${+(t[a]??"0")+ +s}`}return console.log("Decoder.decodeClaimRewards",t),{txType:Ue.TransactionType.Other,type:"claim",intentionData:{value:t}}}decodeClaimAndDeposit(){return{txType:Ue.TransactionType.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};var xu=require("@mysten/sui/transactions");var Cu=_t(require("sort-keys-recursive")),Ft=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,Cu.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 xu.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 Au=require("@mysten/sui/transactions");var ku=require("@mysten/sui/utils"),fn=require("@suilend/sdk"),Du=require("@suilend/sui-fe"),vu=_t(require("bignumber.js")),vf=(r,e)=>{let t={[fn.Side.DEPOSIT]:[],[fn.Side.BORROW]:[]};return r.lendingMarket.reserves.forEach(n=>{[fn.Side.DEPOSIT,fn.Side.BORROW].forEach(o=>{let a=o===fn.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,ku.normalizeStructTag)(c.coinType.name),side:o})).filter(c=>!(0,Du.isSendPoints)(c.rewardCoinType)&&!!s.rewards[Number(c.rewardIndex)]&&new vu.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 Au.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 Mu=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 Mu.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 Ou=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 Ou.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 Pu=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 Pu.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 Ru=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 Ru.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:Bu.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 Hs=async(r,e)=>{let t=await Ba(r,e),n=await fetch(`${Nu.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:hn.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:hn.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:hn.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:hn.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:hn.TransactionType.Other,type:"unstake",intentionData:{amount:n,inCoinType:t}}}};var Wu=require("@mysten/sui/transactions"),Hn=require("@suilend/springsui-sdk");var Eu=_t(require("sort-keys-recursive")),zt=class{constructor(e){this.data=e}data;serialize(){return JSON.stringify((0,Eu.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 Wu.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 _u=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 _u.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 Lu=require("@mysten/sui/transactions"),ju=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 ju.LstClient.initialize(n,Object.values(s).find(w=>w.type===this.data.outCoinType)),S=new Lu.Transaction;return b.mintAmountAndRebalanceAndSendToUser(S,o.address,this.data.amount),S}static fromData(t){return console.log("StakeIntention.fromData",t),new r(t)}};var Uu=require("@mysten/sui/transactions"),Ga=require("@suilend/sdk"),Gu=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 Gu.LstClient.initialize(n,Object.values(s).find(D=>D.type===this.data.outCoinType)),S=new Uu.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 qu=require("@mysten/sui/transactions"),Fu=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 Fu.LstClient.initialize(n,Object.values(s).find(w=>w.type===this.data.inCoinType)),S=new qu.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 Hs(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:Ku.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 Hs(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 Hu=require("@msafe/sui3-utils");var Xs=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:Xs.TransactionType.Other,type:"mint",intentionData:{amount:t}}}decodeRedeem(e){let{event:{lst_amount_in:t}}=e;return console.log("Decoder.decodeRedeem",t),{txType:Xs.TransactionType.Other,type:"redeem",intentionData:{amount:t}}}};var $u=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 $u.LST(a).mint(o,n.address);return c.setGasBudget(1e8),c}static fromData(t){return console.log("MintIntention.fromData",t),new r(t)}};var Vu=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 Vu.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:Hu.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"),qe=require("@mysten/bcs"),Fe=require("@mysten/sui/bcs"),za=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 za.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(Fe.bcs.u128().parse(Uint8Array.from((0,qe.fromBase64)(this.inputs[e].Pure.bytes))))}decodeInputU64(e){let t=new za.Decimal(Fe.bcs.u64().parse(Uint8Array.from((0,qe.fromBase64)(this.inputs[e].Pure.bytes))));return t.gt(Number.MAX_SAFE_INTEGER)?t.toString():t.toNumber()}decodeInputU32(e){return Number(Fe.bcs.u32().parse(Uint8Array.from((0,qe.fromBase64)(this.inputs[e].Pure.bytes))))}decodeInputU8(e){return Number(Fe.bcs.u8().parse(Uint8Array.from((0,qe.fromBase64)(this.inputs[e].Pure.bytes))))}decodeInputAddress(e){return Fe.bcs.Address.parse(Uint8Array.from((0,qe.fromBase64)(this.inputs[e].Pure.bytes)))}decodeInputBool(e){return Fe.bcs.bool().parse(Uint8Array.from((0,qe.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 Qa=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 Ya=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 Ja=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 Za=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 ti=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 ei=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 ni=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 oi=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 ri=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 ai=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 ii=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 si=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 ci=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 zs=require("@mysten/sui/transactions"),Qs=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 zs.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,Qs.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 zs.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,Qs.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 li=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 pi=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 ui=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=ti.fromData(e.intentionData);break;case"AddLiquidity":a=Qa.fromData(e.intentionData);break;case"IncreaseLiquidity":a=oi.fromData(e.intentionData);break;case"DecreaseLiquidity":a=ei.fromData(e.intentionData);break;case"DecreaseLiquidityWithReturn":a=ni.fromData(e.intentionData);break;case"RemoveLiquidity":a=ii.fromData(e.intentionData);break;case"removeLiquidityWithReturn":a=si.fromData(e.intentionData);break;case"CollectFee":a=Ja.fromData(e.intentionData);break;case"CollectReward":a=Za.fromData(e.intentionData);break;case"Burn":a=Ya.fromData(e.intentionData);break;case"Swap":a=ci.fromData(e.intentionData);break;case"PrixJoin":a=ai.fromData(e.intentionData);break;case"PrixClaim":a=ri.fromData(e.intentionData);break;case"SwapExactBaseForQuote":a=li.fromData(e.intentionData);break;case"SwapExactQuoteForBase":a=pi.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 mi=require("@msafe/sui3-utils"),fi=require("@mysten/bcs"),Js=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 di=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(fi.bcs.u64().parse(Uint8Array.from((0,fi.fromBase64)(n.Pure.bytes))))}decodeStake(){return{txType:mi.TransactionType.Other,type:"Stake",intentionData:{amount:this.decodeSplitAmount()}}}decodeUnStake(){return{txType:mi.TransactionType.Other,type:"UnStake",intentionData:{amount:this.decodeSplitAmount()}}}decodeClaimTicket(){let e=this.helper.decodeOwnedObjectId(2);return{txType:mi.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 Ys(e,this.txb)}},Ys=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,Js.normalizeSuiAddress)(t)}};var ym=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 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 gi=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 yi=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 bi=class{application="volo";supportSDK="@mysten/sui-v2";async deserialize(e){let n=new di(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=gi.fromData(e.intentionData);break;case"UnStake":a=yi.fromData(e.intentionData);break;case"ClaimTicket":a=hi.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 Zs=require("@cetusprotocol/common-sdk"),fe=require("@msafe/sui3-utils"),gn=require("@mysten/bcs"),yn=require("@mysten/sui/bcs");var Ti=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,Zs.asIntN)(BigInt(this.getU32(this.getInputIndex(e,2)))).toString()),upperTick:Number((0,Zs.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(yn.bcs.u32().parse(Uint8Array.from((0,gn.fromBase64)(this.inputs[e].Pure.bytes))))}getU64(e){return yn.bcs.u64().parse(Uint8Array.from((0,gn.fromBase64)(this.inputs[e].Pure.bytes)))}getU128(e){return yn.bcs.u128().parse(Uint8Array.from((0,gn.fromBase64)(this.inputs[e].Pure.bytes)))}getBoolean(e){return yn.bcs.bool().parse(Uint8Array.from((0,gn.fromBase64)(this.inputs[e].Pure.bytes)))}getAddress(e){return yn.bcs.Address.parse(Uint8Array.from((0,gn.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 Si=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,Si.getQuote)({tokenIn:e.tokenIn.address,tokenOut:e.tokenOut.address,amountIn:new xm.Decimal(e.amountIn).mul(10**e.tokenIn.decimals).toString()}),s=await(0,Si.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 wi=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 Ii=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 Ci=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 xi=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 ki=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 Di=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 vi=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 Ai=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 Mi=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 Ti(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=Di.fromData(e.intentionData);break;case"ProvideLiquidity":a=vi.fromData(e.intentionData);break;case"RemoveLiquidity":a=Ai.fromData(e.intentionData);break;case"ClosePosition":a=Ii.fromData(e.intentionData);break;case"CollectFee":a=Ci.fromData(e.intentionData);break;case"CollectRewards":a=xi.fromData(e.intentionData);break;case"CollectRewardsAndFee":a=ki.fromData(e.intentionData);break;case"Aggregator7KSwap":a=wi.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 bn=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 Ke=(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=bn.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(bn.TickMath.convertI32ToSigned(n),t.tickSpacing),s=Lm(bn.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 Oi(r,e,t){let n=Um(r,e);return Number(r)===0?BigInt(0):Gf(n,t)}async function $e({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=bn.TickMath.sqrtPriceX64ToPrice(new B.default(m?.toString()),t.decimals,n.decimals),S=a?(100-o)/100:(100+o)/100,w=bn.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=Oi(n,a.tokenX.decimals,b),O=Oi(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 $e({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=Oi(n,a.tokenX.decimals,c),C=Oi(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 $e({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}),Ke(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 $e({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}),Ke(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 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,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 Ri=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 Tn="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(Tn)){o.transferObjects(w,o.pure.address(t));return}let C=c?.[a]?.[Tn];if(!C||C.length===0)throw new Error(`No swap route found from ${Tn} 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:[Tn]}),U=Q(Tn);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 $e({suiClient:r.rpcClient,poolId:E.poolId,currentSqrtPrice:E.currentSqrtPrice,tokenX:E.tokenX,tokenY:E.tokenY,slippagePercentage:s,isTokenX:Wt}),{outputCoin:Sn,leftoverCoin:Ve}=r.Pool.swap({txb:o,pool:le,amount:G,inputCoin:O,isXtoY:Wt,limitSqrtPrice:Yn})||{};if(!Sn||!Ve)throw new Error(`Swap Failed: empty swap result for pool ${V}`);if(o.transferObjects([Ve],o.pure.address(t)),O=Sn,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 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,{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&&Ke(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 Ni=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 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,position:s,pool:c}=o,m=new sd.Transaction;return Ke(n,a,s,c,m),m}static fromData(t){return new r(t)}};var cd=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,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 _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,{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 Li=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 nc=require("@mysten/sui/transactions"),oc=require("@suilend/springsui-sdk"),ec={id:"0x0431232199873db77a92aa645cd43521437e9cc5c6fff07fd03edb88afe0b25a",type:"0x2b6602099970374cf58a2a1b9d96f005fccceb81e92eb059873baf420eb6c717::x_sui::X_SUI",weightHookId:"0x9e35c13dbb0bc437e8ad5a95ec463622f58763e060552ae8d100db77f4904601"},ud=async(r,e,t)=>{let n=await oc.LstClient.initialize(r,r,ec),o=new nc.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 oc.LstClient.initialize(r,r,ec),o=await r.listCoins({owner:e,coinType:ec.type,limit:1e3});if(o.objects.length===0)throw new Error("No lst coins found");let a=new nc.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 ji=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 $e({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 Ui=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 Gi=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 qi=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 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,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 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,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 $i=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 Vi=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=Ui.fromData(e.intentionData);break;case"AddLiquidity":t=Pi.fromData(e.intentionData);break;case"AddLiquiditySingleSide":t=Ri.fromData(e.intentionData);break;case"ClaimRewards":t=Ei.fromData(e.intentionData);break;case"ClaimAllRewards":t=Bi.fromData(e.intentionData);break;case"ClaimRewardsAs":t=Ni.fromData(e.intentionData);break;case"RemoveLiquidity":t=Li.fromData(e.intentionData);break;case"StakeXSui":t=ji.fromData(e.intentionData);break;case"UnstakeXSui":t=Gi.fromData(e.intentionData);break;case"ManageLiquidity":t=Wi.fromData(e.intentionData);break;case"ManageLiquiditySingleSide":t=_i.fromData(e.intentionData);break;case"Bond":t=qi.fromData(e.intentionData);break;case"Extend":t=Fi.fromData(e.intentionData);break;case"Merge":t=Ki.fromData(e.intentionData);break;case"Unbond":t=$i.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 ui,new Vi,new xa,new bi,new Do,new Na,new Fa,new ao,new Mi,new Ha]);
|
|
2
2
|
//# sourceMappingURL=index.js.map
|