@msafe/sui-app-store 0.0.252 → 0.0.254

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.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var dl=Object.create;var ri=Object.defineProperty;var fl=Object.getOwnPropertyDescriptor;var hl=Object.getOwnPropertyNames;var gl=Object.getPrototypeOf,yl=Object.prototype.hasOwnProperty;var bl=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var Sl=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),ms=(a,e)=>{for(var t in e)ri(a,t,{get:e[t],enumerable:!0})},Tl=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of hl(e))!yl.call(a,o)&&o!==t&&ri(a,o,{get:()=>e[o],enumerable:!(n=fl(e,o))||n.enumerable});return a};var wl=(a,e,t)=>(t=a!=null?dl(gl(a)):{},Tl(e||!a||!a.__esModule?ri(t,"default",{value:a,enumerable:!0}):t,a));var cl=Sl((sl,$i)=>{"use strict";(function(a,e){"use strict";function t(y,i){if(!y)throw new Error(i||"Assertion failed")}function n(y,i){y.super_=i;var u=function(){};u.prototype=i.prototype,y.prototype=new u,y.prototype.constructor=y}function o(y,i,u){if(o.isBN(y))return y;this.negative=0,this.words=null,this.length=0,this.red=null,y!==null&&((i==="le"||i==="be")&&(u=i,i=10),this._init(y||0,i||10,u||"be"))}typeof a=="object"?a.exports=o:e.BN=o,o.BN=o,o.wordSize=26;var r;try{typeof window<"u"&&typeof window.Buffer<"u"?r=window.Buffer:r=bl("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,u){return i.cmp(u)>0?i:u},o.min=function(i,u){return i.cmp(u)<0?i:u},o.prototype._init=function(i,u,m){if(typeof i=="number")return this._initNumber(i,u,m);if(typeof i=="object")return this._initArray(i,u,m);u==="hex"&&(u=16),t(u===(u|0)&&u>=2&&u<=36),i=i.toString().replace(/\s+/g,"");var p=0;i[0]==="-"&&(p++,this.negative=1),p<i.length&&(u===16?this._parseHex(i,p,m):(this._parseBase(i,u,p),m==="le"&&this._initArray(this.toArray(),u,m)))},o.prototype._initNumber=function(i,u,m){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),m==="le"&&this._initArray(this.toArray(),u,m)},o.prototype._initArray=function(i,u,m){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 p=0;p<this.length;p++)this.words[p]=0;var h,b,T=0;if(m==="be")for(p=i.length-1,h=0;p>=0;p-=3)b=i[p]|i[p-1]<<8|i[p-2]<<16,this.words[h]|=b<<T&67108863,this.words[h+1]=b>>>26-T&67108863,T+=24,T>=26&&(T-=26,h++);else if(m==="le")for(p=0,h=0;p<i.length;p+=3)b=i[p]|i[p+1]<<8|i[p+2]<<16,this.words[h]|=b<<T&67108863,this.words[h+1]=b>>>26-T&67108863,T+=24,T>=26&&(T-=26,h++);return this._strip()};function c(y,i){var u=y.charCodeAt(i);if(u>=48&&u<=57)return u-48;if(u>=65&&u<=70)return u-55;if(u>=97&&u<=102)return u-87;t(!1,"Invalid character in "+y)}function l(y,i,u){var m=c(y,u);return u-1>=i&&(m|=c(y,u-1)<<4),m}o.prototype._parseHex=function(i,u,m){this.length=Math.ceil((i.length-u)/6),this.words=new Array(this.length);for(var p=0;p<this.length;p++)this.words[p]=0;var h=0,b=0,T;if(m==="be")for(p=i.length-1;p>=u;p-=2)T=l(i,u,p)<<h,this.words[b]|=T&67108863,h>=18?(h-=18,b+=1,this.words[b]|=T>>>26):h+=8;else{var f=i.length-u;for(p=f%2===0?u+1:u;p<i.length;p+=2)T=l(i,u,p)<<h,this.words[b]|=T&67108863,h>=18?(h-=18,b+=1,this.words[b]|=T>>>26):h+=8}this._strip()};function d(y,i,u,m){for(var p=0,h=0,b=Math.min(y.length,u),T=i;T<b;T++){var f=y.charCodeAt(T)-48;p*=m,f>=49?h=f-49+10:f>=17?h=f-17+10:h=f,t(f>=0&&h<m,"Invalid character"),p+=h}return p}o.prototype._parseBase=function(i,u,m){this.words=[0],this.length=1;for(var p=0,h=1;h<=67108863;h*=u)p++;p--,h=h/u|0;for(var b=i.length-m,T=b%p,f=Math.min(b,b-T)+m,s=0,g=m;g<f;g+=p)s=d(i,g,g+p,u),this.imuln(h),this.words[0]+s<67108864?this.words[0]+=s:this._iaddn(s);if(T!==0){var D=1;for(s=d(i,g,i.length,u),g=0;g<T;g++)D*=u;this.imuln(D),this.words[0]+s<67108864?this.words[0]+=s:this._iaddn(s)}this._strip()},o.prototype.copy=function(i){i.words=new Array(this.length);for(var u=0;u<this.length;u++)i.words[u]=this.words[u];i.length=this.length,i.negative=this.negative,i.red=this.red};function S(y,i){y.words=i.words,y.length=i.length,y.negative=i.negative,y.red=i.red}if(o.prototype._move=function(i){S(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")]=w}catch{o.prototype.inspect=w}else o.prototype.inspect=w;function w(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var I=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],C=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],k=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];o.prototype.toString=function(i,u){i=i||10,u=u|0||1;var m;if(i===16||i==="hex"){m="";for(var p=0,h=0,b=0;b<this.length;b++){var T=this.words[b],f=((T<<p|h)&16777215).toString(16);h=T>>>24-p&16777215,p+=2,p>=26&&(p-=26,b--),h!==0||b!==this.length-1?m=I[6-f.length]+f+m:m=f+m}for(h!==0&&(m=h.toString(16)+m);m.length%u!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}if(i===(i|0)&&i>=2&&i<=36){var s=C[i],g=k[i];m="";var D=this.clone();for(D.negative=0;!D.isZero();){var O=D.modrn(g).toString(i);D=D.idivn(g),D.isZero()?m=O+m:m=I[s-O.length]+O+m}for(this.isZero()&&(m="0"+m);m.length%u!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}t(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var 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)},r&&(o.prototype.toBuffer=function(i,u){return this.toArrayLike(r,i,u)}),o.prototype.toArray=function(i,u){return this.toArrayLike(Array,i,u)};var x=function(i,u){return i.allocUnsafe?i.allocUnsafe(u):new i(u)};o.prototype.toArrayLike=function(i,u,m){this._strip();var p=this.byteLength(),h=m||Math.max(1,p);t(p<=h,"byte array longer than desired length"),t(h>0,"Requested array length <= 0");var b=x(i,h),T=u==="le"?"LE":"BE";return this["_toArrayLike"+T](b,p),b},o.prototype._toArrayLikeLE=function(i,u){for(var m=0,p=0,h=0,b=0;h<this.length;h++){var T=this.words[h]<<b|p;i[m++]=T&255,m<i.length&&(i[m++]=T>>8&255),m<i.length&&(i[m++]=T>>16&255),b===6?(m<i.length&&(i[m++]=T>>24&255),p=0,b=0):(p=T>>>24,b+=2)}if(m<i.length)for(i[m++]=p;m<i.length;)i[m++]=0},o.prototype._toArrayLikeBE=function(i,u){for(var m=i.length-1,p=0,h=0,b=0;h<this.length;h++){var T=this.words[h]<<b|p;i[m--]=T&255,m>=0&&(i[m--]=T>>8&255),m>=0&&(i[m--]=T>>16&255),b===6?(m>=0&&(i[m--]=T>>24&255),p=0,b=0):(p=T>>>24,b+=2)}if(m>=0)for(i[m--]=p;m>=0;)i[m--]=0},Math.clz32?o.prototype._countBits=function(i){return 32-Math.clz32(i)}:o.prototype._countBits=function(i){var u=i,m=0;return u>=4096&&(m+=13,u>>>=13),u>=64&&(m+=7,u>>>=7),u>=8&&(m+=4,u>>>=4),u>=2&&(m+=2,u>>>=2),m+u},o.prototype._zeroBits=function(i){if(i===0)return 26;var u=i,m=0;return u&8191||(m+=13,u>>>=13),u&127||(m+=7,u>>>=7),u&15||(m+=4,u>>>=4),u&3||(m+=2,u>>>=2),u&1||m++,m},o.prototype.bitLength=function(){var i=this.words[this.length-1],u=this._countBits(i);return(this.length-1)*26+u};function P(y){for(var i=new Array(y.bitLength()),u=0;u<i.length;u++){var m=u/26|0,p=u%26;i[u]=y.words[m]>>>p&1}return i}o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var i=0,u=0;u<this.length;u++){var m=this._zeroBits(this.words[u]);if(i+=m,m!==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 u=0;u<i.length;u++)this.words[u]=this.words[u]|i.words[u];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 u;this.length>i.length?u=i:u=this;for(var m=0;m<u.length;m++)this.words[m]=this.words[m]&i.words[m];return this.length=u.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 u,m;this.length>i.length?(u=this,m=i):(u=i,m=this);for(var p=0;p<m.length;p++)this.words[p]=u.words[p]^m.words[p];if(this!==u)for(;p<u.length;p++)this.words[p]=u.words[p];return this.length=u.length,this._strip()},o.prototype.ixor=function(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 u=Math.ceil(i/26)|0,m=i%26;this._expand(u),m>0&&u--;for(var p=0;p<u;p++)this.words[p]=~this.words[p]&67108863;return m>0&&(this.words[p]=~this.words[p]&67108863>>26-m),this._strip()},o.prototype.notn=function(i){return this.clone().inotn(i)},o.prototype.setn=function(i,u){t(typeof i=="number"&&i>=0);var m=i/26|0,p=i%26;return this._expand(m+1),u?this.words[m]=this.words[m]|1<<p:this.words[m]=this.words[m]&~(1<<p),this._strip()},o.prototype.iadd=function(i){var u;if(this.negative!==0&&i.negative===0)return this.negative=0,u=this.isub(i),this.negative^=1,this._normSign();if(this.negative===0&&i.negative!==0)return i.negative=0,u=this.isub(i),i.negative=1,u._normSign();var m,p;this.length>i.length?(m=this,p=i):(m=i,p=this);for(var h=0,b=0;b<p.length;b++)u=(m.words[b]|0)+(p.words[b]|0)+h,this.words[b]=u&67108863,h=u>>>26;for(;h!==0&&b<m.length;b++)u=(m.words[b]|0)+h,this.words[b]=u&67108863,h=u>>>26;if(this.length=m.length,h!==0)this.words[this.length]=h,this.length++;else if(m!==this)for(;b<m.length;b++)this.words[b]=m.words[b];return this},o.prototype.add=function(i){var u;return i.negative!==0&&this.negative===0?(i.negative=0,u=this.sub(i),i.negative^=1,u):i.negative===0&&this.negative!==0?(this.negative=0,u=i.sub(this),this.negative=1,u):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 u=this.iadd(i);return i.negative=1,u._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(i),this.negative=1,this._normSign();var m=this.cmp(i);if(m===0)return this.negative=0,this.length=1,this.words[0]=0,this;var p,h;m>0?(p=this,h=i):(p=i,h=this);for(var b=0,T=0;T<h.length;T++)u=(p.words[T]|0)-(h.words[T]|0)+b,b=u>>26,this.words[T]=u&67108863;for(;b!==0&&T<p.length;T++)u=(p.words[T]|0)+b,b=u>>26,this.words[T]=u&67108863;if(b===0&&T<p.length&&p!==this)for(;T<p.length;T++)this.words[T]=p.words[T];return this.length=Math.max(this.length,T),p!==this&&(this.negative=1),this._strip()},o.prototype.sub=function(i){return this.clone().isub(i)};function L(y,i,u){u.negative=i.negative^y.negative;var m=y.length+i.length|0;u.length=m,m=m-1|0;var p=y.words[0]|0,h=i.words[0]|0,b=p*h,T=b&67108863,f=b/67108864|0;u.words[0]=T;for(var s=1;s<m;s++){for(var g=f>>>26,D=f&67108863,O=Math.min(s,i.length-1),M=Math.max(0,s-y.length+1);M<=O;M++){var E=s-M|0;p=y.words[E]|0,h=i.words[M]|0,b=p*h+D,g+=b/67108864|0,D=b&67108863}u.words[s]=D|0,f=g|0}return f!==0?u.words[s]=f|0:u.length--,u._strip()}var V=function(i,u,m){var p=i.words,h=u.words,b=m.words,T=0,f,s,g,D=p[0]|0,O=D&8191,M=D>>>13,E=p[1]|0,_=E&8191,U=E>>>13,ee=p[2]|0,q=ee&8191,F=ee>>>13,Gi=p[3]|0,z=Gi&8191,G=Gi>>>13,Qi=p[4]|0,Q=Qi&8191,J=Qi>>>13,Ji=p[5]|0,X=Ji&8191,Y=Ji>>>13,Xi=p[6]|0,Z=Xi&8191,tt=Xi>>>13,Yi=p[7]|0,et=Yi&8191,nt=Yi>>>13,Zi=p[8]|0,ot=Zi&8191,at=Zi>>>13,ts=p[9]|0,rt=ts&8191,it=ts>>>13,es=h[0]|0,st=es&8191,ct=es>>>13,ns=h[1]|0,lt=ns&8191,ut=ns>>>13,os=h[2]|0,mt=os&8191,pt=os>>>13,as=h[3]|0,dt=as&8191,ft=as>>>13,rs=h[4]|0,ht=rs&8191,gt=rs>>>13,is=h[5]|0,yt=is&8191,bt=is>>>13,ss=h[6]|0,St=ss&8191,Tt=ss>>>13,cs=h[7]|0,wt=cs&8191,It=cs>>>13,ls=h[8]|0,Ct=ls&8191,kt=ls>>>13,us=h[9]|0,vt=us&8191,xt=us>>>13;m.negative=i.negative^u.negative,m.length=19,f=Math.imul(O,st),s=Math.imul(O,ct),s=s+Math.imul(M,st)|0,g=Math.imul(M,ct);var Ur=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Ur>>>26)|0,Ur&=67108863,f=Math.imul(_,st),s=Math.imul(_,ct),s=s+Math.imul(U,st)|0,g=Math.imul(U,ct),f=f+Math.imul(O,lt)|0,s=s+Math.imul(O,ut)|0,s=s+Math.imul(M,lt)|0,g=g+Math.imul(M,ut)|0;var qr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(qr>>>26)|0,qr&=67108863,f=Math.imul(q,st),s=Math.imul(q,ct),s=s+Math.imul(F,st)|0,g=Math.imul(F,ct),f=f+Math.imul(_,lt)|0,s=s+Math.imul(_,ut)|0,s=s+Math.imul(U,lt)|0,g=g+Math.imul(U,ut)|0,f=f+Math.imul(O,mt)|0,s=s+Math.imul(O,pt)|0,s=s+Math.imul(M,mt)|0,g=g+Math.imul(M,pt)|0;var Fr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Fr>>>26)|0,Fr&=67108863,f=Math.imul(z,st),s=Math.imul(z,ct),s=s+Math.imul(G,st)|0,g=Math.imul(G,ct),f=f+Math.imul(q,lt)|0,s=s+Math.imul(q,ut)|0,s=s+Math.imul(F,lt)|0,g=g+Math.imul(F,ut)|0,f=f+Math.imul(_,mt)|0,s=s+Math.imul(_,pt)|0,s=s+Math.imul(U,mt)|0,g=g+Math.imul(U,pt)|0,f=f+Math.imul(O,dt)|0,s=s+Math.imul(O,ft)|0,s=s+Math.imul(M,dt)|0,g=g+Math.imul(M,ft)|0;var Kr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Kr>>>26)|0,Kr&=67108863,f=Math.imul(Q,st),s=Math.imul(Q,ct),s=s+Math.imul(J,st)|0,g=Math.imul(J,ct),f=f+Math.imul(z,lt)|0,s=s+Math.imul(z,ut)|0,s=s+Math.imul(G,lt)|0,g=g+Math.imul(G,ut)|0,f=f+Math.imul(q,mt)|0,s=s+Math.imul(q,pt)|0,s=s+Math.imul(F,mt)|0,g=g+Math.imul(F,pt)|0,f=f+Math.imul(_,dt)|0,s=s+Math.imul(_,ft)|0,s=s+Math.imul(U,dt)|0,g=g+Math.imul(U,ft)|0,f=f+Math.imul(O,ht)|0,s=s+Math.imul(O,gt)|0,s=s+Math.imul(M,ht)|0,g=g+Math.imul(M,gt)|0;var Vr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Vr>>>26)|0,Vr&=67108863,f=Math.imul(X,st),s=Math.imul(X,ct),s=s+Math.imul(Y,st)|0,g=Math.imul(Y,ct),f=f+Math.imul(Q,lt)|0,s=s+Math.imul(Q,ut)|0,s=s+Math.imul(J,lt)|0,g=g+Math.imul(J,ut)|0,f=f+Math.imul(z,mt)|0,s=s+Math.imul(z,pt)|0,s=s+Math.imul(G,mt)|0,g=g+Math.imul(G,pt)|0,f=f+Math.imul(q,dt)|0,s=s+Math.imul(q,ft)|0,s=s+Math.imul(F,dt)|0,g=g+Math.imul(F,ft)|0,f=f+Math.imul(_,ht)|0,s=s+Math.imul(_,gt)|0,s=s+Math.imul(U,ht)|0,g=g+Math.imul(U,gt)|0,f=f+Math.imul(O,yt)|0,s=s+Math.imul(O,bt)|0,s=s+Math.imul(M,yt)|0,g=g+Math.imul(M,bt)|0;var $r=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+($r>>>26)|0,$r&=67108863,f=Math.imul(Z,st),s=Math.imul(Z,ct),s=s+Math.imul(tt,st)|0,g=Math.imul(tt,ct),f=f+Math.imul(X,lt)|0,s=s+Math.imul(X,ut)|0,s=s+Math.imul(Y,lt)|0,g=g+Math.imul(Y,ut)|0,f=f+Math.imul(Q,mt)|0,s=s+Math.imul(Q,pt)|0,s=s+Math.imul(J,mt)|0,g=g+Math.imul(J,pt)|0,f=f+Math.imul(z,dt)|0,s=s+Math.imul(z,ft)|0,s=s+Math.imul(G,dt)|0,g=g+Math.imul(G,ft)|0,f=f+Math.imul(q,ht)|0,s=s+Math.imul(q,gt)|0,s=s+Math.imul(F,ht)|0,g=g+Math.imul(F,gt)|0,f=f+Math.imul(_,yt)|0,s=s+Math.imul(_,bt)|0,s=s+Math.imul(U,yt)|0,g=g+Math.imul(U,bt)|0,f=f+Math.imul(O,St)|0,s=s+Math.imul(O,Tt)|0,s=s+Math.imul(M,St)|0,g=g+Math.imul(M,Tt)|0;var Hr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Hr>>>26)|0,Hr&=67108863,f=Math.imul(et,st),s=Math.imul(et,ct),s=s+Math.imul(nt,st)|0,g=Math.imul(nt,ct),f=f+Math.imul(Z,lt)|0,s=s+Math.imul(Z,ut)|0,s=s+Math.imul(tt,lt)|0,g=g+Math.imul(tt,ut)|0,f=f+Math.imul(X,mt)|0,s=s+Math.imul(X,pt)|0,s=s+Math.imul(Y,mt)|0,g=g+Math.imul(Y,pt)|0,f=f+Math.imul(Q,dt)|0,s=s+Math.imul(Q,ft)|0,s=s+Math.imul(J,dt)|0,g=g+Math.imul(J,ft)|0,f=f+Math.imul(z,ht)|0,s=s+Math.imul(z,gt)|0,s=s+Math.imul(G,ht)|0,g=g+Math.imul(G,gt)|0,f=f+Math.imul(q,yt)|0,s=s+Math.imul(q,bt)|0,s=s+Math.imul(F,yt)|0,g=g+Math.imul(F,bt)|0,f=f+Math.imul(_,St)|0,s=s+Math.imul(_,Tt)|0,s=s+Math.imul(U,St)|0,g=g+Math.imul(U,Tt)|0,f=f+Math.imul(O,wt)|0,s=s+Math.imul(O,It)|0,s=s+Math.imul(M,wt)|0,g=g+Math.imul(M,It)|0;var zr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(zr>>>26)|0,zr&=67108863,f=Math.imul(ot,st),s=Math.imul(ot,ct),s=s+Math.imul(at,st)|0,g=Math.imul(at,ct),f=f+Math.imul(et,lt)|0,s=s+Math.imul(et,ut)|0,s=s+Math.imul(nt,lt)|0,g=g+Math.imul(nt,ut)|0,f=f+Math.imul(Z,mt)|0,s=s+Math.imul(Z,pt)|0,s=s+Math.imul(tt,mt)|0,g=g+Math.imul(tt,pt)|0,f=f+Math.imul(X,dt)|0,s=s+Math.imul(X,ft)|0,s=s+Math.imul(Y,dt)|0,g=g+Math.imul(Y,ft)|0,f=f+Math.imul(Q,ht)|0,s=s+Math.imul(Q,gt)|0,s=s+Math.imul(J,ht)|0,g=g+Math.imul(J,gt)|0,f=f+Math.imul(z,yt)|0,s=s+Math.imul(z,bt)|0,s=s+Math.imul(G,yt)|0,g=g+Math.imul(G,bt)|0,f=f+Math.imul(q,St)|0,s=s+Math.imul(q,Tt)|0,s=s+Math.imul(F,St)|0,g=g+Math.imul(F,Tt)|0,f=f+Math.imul(_,wt)|0,s=s+Math.imul(_,It)|0,s=s+Math.imul(U,wt)|0,g=g+Math.imul(U,It)|0,f=f+Math.imul(O,Ct)|0,s=s+Math.imul(O,kt)|0,s=s+Math.imul(M,Ct)|0,g=g+Math.imul(M,kt)|0;var Gr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Gr>>>26)|0,Gr&=67108863,f=Math.imul(rt,st),s=Math.imul(rt,ct),s=s+Math.imul(it,st)|0,g=Math.imul(it,ct),f=f+Math.imul(ot,lt)|0,s=s+Math.imul(ot,ut)|0,s=s+Math.imul(at,lt)|0,g=g+Math.imul(at,ut)|0,f=f+Math.imul(et,mt)|0,s=s+Math.imul(et,pt)|0,s=s+Math.imul(nt,mt)|0,g=g+Math.imul(nt,pt)|0,f=f+Math.imul(Z,dt)|0,s=s+Math.imul(Z,ft)|0,s=s+Math.imul(tt,dt)|0,g=g+Math.imul(tt,ft)|0,f=f+Math.imul(X,ht)|0,s=s+Math.imul(X,gt)|0,s=s+Math.imul(Y,ht)|0,g=g+Math.imul(Y,gt)|0,f=f+Math.imul(Q,yt)|0,s=s+Math.imul(Q,bt)|0,s=s+Math.imul(J,yt)|0,g=g+Math.imul(J,bt)|0,f=f+Math.imul(z,St)|0,s=s+Math.imul(z,Tt)|0,s=s+Math.imul(G,St)|0,g=g+Math.imul(G,Tt)|0,f=f+Math.imul(q,wt)|0,s=s+Math.imul(q,It)|0,s=s+Math.imul(F,wt)|0,g=g+Math.imul(F,It)|0,f=f+Math.imul(_,Ct)|0,s=s+Math.imul(_,kt)|0,s=s+Math.imul(U,Ct)|0,g=g+Math.imul(U,kt)|0,f=f+Math.imul(O,vt)|0,s=s+Math.imul(O,xt)|0,s=s+Math.imul(M,vt)|0,g=g+Math.imul(M,xt)|0;var Qr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Qr>>>26)|0,Qr&=67108863,f=Math.imul(rt,lt),s=Math.imul(rt,ut),s=s+Math.imul(it,lt)|0,g=Math.imul(it,ut),f=f+Math.imul(ot,mt)|0,s=s+Math.imul(ot,pt)|0,s=s+Math.imul(at,mt)|0,g=g+Math.imul(at,pt)|0,f=f+Math.imul(et,dt)|0,s=s+Math.imul(et,ft)|0,s=s+Math.imul(nt,dt)|0,g=g+Math.imul(nt,ft)|0,f=f+Math.imul(Z,ht)|0,s=s+Math.imul(Z,gt)|0,s=s+Math.imul(tt,ht)|0,g=g+Math.imul(tt,gt)|0,f=f+Math.imul(X,yt)|0,s=s+Math.imul(X,bt)|0,s=s+Math.imul(Y,yt)|0,g=g+Math.imul(Y,bt)|0,f=f+Math.imul(Q,St)|0,s=s+Math.imul(Q,Tt)|0,s=s+Math.imul(J,St)|0,g=g+Math.imul(J,Tt)|0,f=f+Math.imul(z,wt)|0,s=s+Math.imul(z,It)|0,s=s+Math.imul(G,wt)|0,g=g+Math.imul(G,It)|0,f=f+Math.imul(q,Ct)|0,s=s+Math.imul(q,kt)|0,s=s+Math.imul(F,Ct)|0,g=g+Math.imul(F,kt)|0,f=f+Math.imul(_,vt)|0,s=s+Math.imul(_,xt)|0,s=s+Math.imul(U,vt)|0,g=g+Math.imul(U,xt)|0;var Jr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Jr>>>26)|0,Jr&=67108863,f=Math.imul(rt,mt),s=Math.imul(rt,pt),s=s+Math.imul(it,mt)|0,g=Math.imul(it,pt),f=f+Math.imul(ot,dt)|0,s=s+Math.imul(ot,ft)|0,s=s+Math.imul(at,dt)|0,g=g+Math.imul(at,ft)|0,f=f+Math.imul(et,ht)|0,s=s+Math.imul(et,gt)|0,s=s+Math.imul(nt,ht)|0,g=g+Math.imul(nt,gt)|0,f=f+Math.imul(Z,yt)|0,s=s+Math.imul(Z,bt)|0,s=s+Math.imul(tt,yt)|0,g=g+Math.imul(tt,bt)|0,f=f+Math.imul(X,St)|0,s=s+Math.imul(X,Tt)|0,s=s+Math.imul(Y,St)|0,g=g+Math.imul(Y,Tt)|0,f=f+Math.imul(Q,wt)|0,s=s+Math.imul(Q,It)|0,s=s+Math.imul(J,wt)|0,g=g+Math.imul(J,It)|0,f=f+Math.imul(z,Ct)|0,s=s+Math.imul(z,kt)|0,s=s+Math.imul(G,Ct)|0,g=g+Math.imul(G,kt)|0,f=f+Math.imul(q,vt)|0,s=s+Math.imul(q,xt)|0,s=s+Math.imul(F,vt)|0,g=g+Math.imul(F,xt)|0;var Xr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Xr>>>26)|0,Xr&=67108863,f=Math.imul(rt,dt),s=Math.imul(rt,ft),s=s+Math.imul(it,dt)|0,g=Math.imul(it,ft),f=f+Math.imul(ot,ht)|0,s=s+Math.imul(ot,gt)|0,s=s+Math.imul(at,ht)|0,g=g+Math.imul(at,gt)|0,f=f+Math.imul(et,yt)|0,s=s+Math.imul(et,bt)|0,s=s+Math.imul(nt,yt)|0,g=g+Math.imul(nt,bt)|0,f=f+Math.imul(Z,St)|0,s=s+Math.imul(Z,Tt)|0,s=s+Math.imul(tt,St)|0,g=g+Math.imul(tt,Tt)|0,f=f+Math.imul(X,wt)|0,s=s+Math.imul(X,It)|0,s=s+Math.imul(Y,wt)|0,g=g+Math.imul(Y,It)|0,f=f+Math.imul(Q,Ct)|0,s=s+Math.imul(Q,kt)|0,s=s+Math.imul(J,Ct)|0,g=g+Math.imul(J,kt)|0,f=f+Math.imul(z,vt)|0,s=s+Math.imul(z,xt)|0,s=s+Math.imul(G,vt)|0,g=g+Math.imul(G,xt)|0;var Yr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Yr>>>26)|0,Yr&=67108863,f=Math.imul(rt,ht),s=Math.imul(rt,gt),s=s+Math.imul(it,ht)|0,g=Math.imul(it,gt),f=f+Math.imul(ot,yt)|0,s=s+Math.imul(ot,bt)|0,s=s+Math.imul(at,yt)|0,g=g+Math.imul(at,bt)|0,f=f+Math.imul(et,St)|0,s=s+Math.imul(et,Tt)|0,s=s+Math.imul(nt,St)|0,g=g+Math.imul(nt,Tt)|0,f=f+Math.imul(Z,wt)|0,s=s+Math.imul(Z,It)|0,s=s+Math.imul(tt,wt)|0,g=g+Math.imul(tt,It)|0,f=f+Math.imul(X,Ct)|0,s=s+Math.imul(X,kt)|0,s=s+Math.imul(Y,Ct)|0,g=g+Math.imul(Y,kt)|0,f=f+Math.imul(Q,vt)|0,s=s+Math.imul(Q,xt)|0,s=s+Math.imul(J,vt)|0,g=g+Math.imul(J,xt)|0;var Zr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Zr>>>26)|0,Zr&=67108863,f=Math.imul(rt,yt),s=Math.imul(rt,bt),s=s+Math.imul(it,yt)|0,g=Math.imul(it,bt),f=f+Math.imul(ot,St)|0,s=s+Math.imul(ot,Tt)|0,s=s+Math.imul(at,St)|0,g=g+Math.imul(at,Tt)|0,f=f+Math.imul(et,wt)|0,s=s+Math.imul(et,It)|0,s=s+Math.imul(nt,wt)|0,g=g+Math.imul(nt,It)|0,f=f+Math.imul(Z,Ct)|0,s=s+Math.imul(Z,kt)|0,s=s+Math.imul(tt,Ct)|0,g=g+Math.imul(tt,kt)|0,f=f+Math.imul(X,vt)|0,s=s+Math.imul(X,xt)|0,s=s+Math.imul(Y,vt)|0,g=g+Math.imul(Y,xt)|0;var ti=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(ti>>>26)|0,ti&=67108863,f=Math.imul(rt,St),s=Math.imul(rt,Tt),s=s+Math.imul(it,St)|0,g=Math.imul(it,Tt),f=f+Math.imul(ot,wt)|0,s=s+Math.imul(ot,It)|0,s=s+Math.imul(at,wt)|0,g=g+Math.imul(at,It)|0,f=f+Math.imul(et,Ct)|0,s=s+Math.imul(et,kt)|0,s=s+Math.imul(nt,Ct)|0,g=g+Math.imul(nt,kt)|0,f=f+Math.imul(Z,vt)|0,s=s+Math.imul(Z,xt)|0,s=s+Math.imul(tt,vt)|0,g=g+Math.imul(tt,xt)|0;var ei=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(ei>>>26)|0,ei&=67108863,f=Math.imul(rt,wt),s=Math.imul(rt,It),s=s+Math.imul(it,wt)|0,g=Math.imul(it,It),f=f+Math.imul(ot,Ct)|0,s=s+Math.imul(ot,kt)|0,s=s+Math.imul(at,Ct)|0,g=g+Math.imul(at,kt)|0,f=f+Math.imul(et,vt)|0,s=s+Math.imul(et,xt)|0,s=s+Math.imul(nt,vt)|0,g=g+Math.imul(nt,xt)|0;var ni=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(ni>>>26)|0,ni&=67108863,f=Math.imul(rt,Ct),s=Math.imul(rt,kt),s=s+Math.imul(it,Ct)|0,g=Math.imul(it,kt),f=f+Math.imul(ot,vt)|0,s=s+Math.imul(ot,xt)|0,s=s+Math.imul(at,vt)|0,g=g+Math.imul(at,xt)|0;var oi=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(oi>>>26)|0,oi&=67108863,f=Math.imul(rt,vt),s=Math.imul(rt,xt),s=s+Math.imul(it,vt)|0,g=Math.imul(it,xt);var ai=(T+f|0)+((s&8191)<<13)|0;return T=(g+(s>>>13)|0)+(ai>>>26)|0,ai&=67108863,b[0]=Ur,b[1]=qr,b[2]=Fr,b[3]=Kr,b[4]=Vr,b[5]=$r,b[6]=Hr,b[7]=zr,b[8]=Gr,b[9]=Qr,b[10]=Jr,b[11]=Xr,b[12]=Yr,b[13]=Zr,b[14]=ti,b[15]=ei,b[16]=ni,b[17]=oi,b[18]=ai,T!==0&&(b[19]=T,m.length++),m};Math.imul||(V=L);function Wt(y,i,u){u.negative=i.negative^y.negative,u.length=y.length+i.length;for(var m=0,p=0,h=0;h<u.length-1;h++){var b=p;p=0;for(var T=m&67108863,f=Math.min(h,i.length-1),s=Math.max(0,h-y.length+1);s<=f;s++){var g=h-s,D=y.words[g]|0,O=i.words[s]|0,M=D*O,E=M&67108863;b=b+(M/67108864|0)|0,E=E+T|0,T=E&67108863,b=b+(E>>>26)|0,p+=b>>>26,b&=67108863}u.words[h]=T,m=b,b=p}return m!==0?u.words[h]=m:u.length--,u._strip()}function Bt(y,i,u){return Wt(y,i,u)}o.prototype.mulTo=function(i,u){var m,p=this.length+i.length;return this.length===10&&i.length===10?m=V(this,i,u):p<63?m=L(this,i,u):p<1024?m=Wt(this,i,u):m=Bt(this,i,u),m};function Et(y,i){this.x=y,this.y=i}Et.prototype.makeRBT=function(i){for(var u=new Array(i),m=o.prototype._countBits(i)-1,p=0;p<i;p++)u[p]=this.revBin(p,m,i);return u},Et.prototype.revBin=function(i,u,m){if(i===0||i===m-1)return i;for(var p=0,h=0;h<u;h++)p|=(i&1)<<u-h-1,i>>=1;return p},Et.prototype.permute=function(i,u,m,p,h,b){for(var T=0;T<b;T++)p[T]=u[i[T]],h[T]=m[i[T]]},Et.prototype.transform=function(i,u,m,p,h,b){this.permute(b,i,u,m,p,h);for(var T=1;T<h;T<<=1)for(var f=T<<1,s=Math.cos(2*Math.PI/f),g=Math.sin(2*Math.PI/f),D=0;D<h;D+=f)for(var O=s,M=g,E=0;E<T;E++){var _=m[D+E],U=p[D+E],ee=m[D+E+T],q=p[D+E+T],F=O*ee-M*q;q=O*q+M*ee,ee=F,m[D+E]=_+ee,p[D+E]=U+q,m[D+E+T]=_-ee,p[D+E+T]=U-q,E!==f&&(F=s*O-g*M,M=s*M+g*O,O=F)}},Et.prototype.guessLen13b=function(i,u){var m=Math.max(u,i)|1,p=m&1,h=0;for(m=m/2|0;m;m=m>>>1)h++;return 1<<h+1+p},Et.prototype.conjugate=function(i,u,m){if(!(m<=1))for(var p=0;p<m/2;p++){var h=i[p];i[p]=i[m-p-1],i[m-p-1]=h,h=u[p],u[p]=-u[m-p-1],u[m-p-1]=-h}},Et.prototype.normalize13b=function(i,u){for(var m=0,p=0;p<u/2;p++){var h=Math.round(i[2*p+1]/u)*8192+Math.round(i[2*p]/u)+m;i[p]=h&67108863,h<67108864?m=0:m=h/67108864|0}return i},Et.prototype.convert13b=function(i,u,m,p){for(var h=0,b=0;b<u;b++)h=h+(i[b]|0),m[2*b]=h&8191,h=h>>>13,m[2*b+1]=h&8191,h=h>>>13;for(b=2*u;b<p;++b)m[b]=0;t(h===0),t((h&-8192)===0)},Et.prototype.stub=function(i){for(var u=new Array(i),m=0;m<i;m++)u[m]=0;return u},Et.prototype.mulp=function(i,u,m){var p=2*this.guessLen13b(i.length,u.length),h=this.makeRBT(p),b=this.stub(p),T=new Array(p),f=new Array(p),s=new Array(p),g=new Array(p),D=new Array(p),O=new Array(p),M=m.words;M.length=p,this.convert13b(i.words,i.length,T,p),this.convert13b(u.words,u.length,g,p),this.transform(T,b,f,s,p,h),this.transform(g,b,D,O,p,h);for(var E=0;E<p;E++){var _=f[E]*D[E]-s[E]*O[E];s[E]=f[E]*O[E]+s[E]*D[E],f[E]=_}return this.conjugate(f,s,p),this.transform(f,s,M,b,p,h),this.conjugate(M,b,p),this.normalize13b(M,p),m.negative=i.negative^u.negative,m.length=i.length+u.length,m._strip()},o.prototype.mul=function(i){var u=new o(null);return u.words=new Array(this.length+i.length),this.mulTo(i,u)},o.prototype.mulf=function(i){var u=new o(null);return u.words=new Array(this.length+i.length),Bt(this,i,u)},o.prototype.imul=function(i){return this.clone().mulTo(i,this)},o.prototype.imuln=function(i){var u=i<0;u&&(i=-i),t(typeof i=="number"),t(i<67108864);for(var m=0,p=0;p<this.length;p++){var h=(this.words[p]|0)*i,b=(h&67108863)+(m&67108863);m>>=26,m+=h/67108864|0,m+=b>>>26,this.words[p]=b&67108863}return m!==0&&(this.words[p]=m,this.length++),u?this.ineg():this},o.prototype.muln=function(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 u=P(i);if(u.length===0)return new o(1);for(var m=this,p=0;p<u.length&&u[p]===0;p++,m=m.sqr());if(++p<u.length)for(var h=m.sqr();p<u.length;p++,h=h.sqr())u[p]!==0&&(m=m.mul(h));return m},o.prototype.iushln=function(i){t(typeof i=="number"&&i>=0);var u=i%26,m=(i-u)/26,p=67108863>>>26-u<<26-u,h;if(u!==0){var b=0;for(h=0;h<this.length;h++){var T=this.words[h]&p,f=(this.words[h]|0)-T<<u;this.words[h]=f|b,b=T>>>26-u}b&&(this.words[h]=b,this.length++)}if(m!==0){for(h=this.length-1;h>=0;h--)this.words[h+m]=this.words[h];for(h=0;h<m;h++)this.words[h]=0;this.length+=m}return this._strip()},o.prototype.ishln=function(i){return t(this.negative===0),this.iushln(i)},o.prototype.iushrn=function(i,u,m){t(typeof i=="number"&&i>=0);var p;u?p=(u-u%26)/26:p=0;var h=i%26,b=Math.min((i-h)/26,this.length),T=67108863^67108863>>>h<<h,f=m;if(p-=b,p=Math.max(0,p),f){for(var s=0;s<b;s++)f.words[s]=this.words[s];f.length=b}if(b!==0)if(this.length>b)for(this.length-=b,s=0;s<this.length;s++)this.words[s]=this.words[s+b];else this.words[0]=0,this.length=1;var g=0;for(s=this.length-1;s>=0&&(g!==0||s>=p);s--){var D=this.words[s]|0;this.words[s]=g<<26-h|D>>>h,g=D&T}return f&&g!==0&&(f.words[f.length++]=g),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(i,u,m){return t(this.negative===0),this.iushrn(i,u,m)},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 u=i%26,m=(i-u)/26,p=1<<u;if(this.length<=m)return!1;var h=this.words[m];return!!(h&p)},o.prototype.imaskn=function(i){t(typeof i=="number"&&i>=0);var u=i%26,m=(i-u)/26;if(t(this.negative===0,"imaskn works only with positive numbers"),this.length<=m)return this;if(u!==0&&m++,this.length=Math.min(m,this.length),u!==0){var p=67108863^67108863>>>u<<u;this.words[this.length-1]&=p}return this._strip()},o.prototype.maskn=function(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 u=0;u<this.length&&this.words[u]>=67108864;u++)this.words[u]-=67108864,u===this.length-1?this.words[u+1]=1:this.words[u+1]++;return this.length=Math.max(this.length,u+1),this},o.prototype.isubn=function(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 u=0;u<this.length&&this.words[u]<0;u++)this.words[u]+=67108864,this.words[u+1]-=1;return this._strip()},o.prototype.addn=function(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,u,m){var p=i.length+m,h;this._expand(p);var b,T=0;for(h=0;h<i.length;h++){b=(this.words[h+m]|0)+T;var f=(i.words[h]|0)*u;b-=f&67108863,T=(b>>26)-(f/67108864|0),this.words[h+m]=b&67108863}for(;h<this.length-m;h++)b=(this.words[h+m]|0)+T,T=b>>26,this.words[h+m]=b&67108863;if(T===0)return this._strip();for(t(T===-1),T=0,h=0;h<this.length;h++)b=-(this.words[h]|0)+T,T=b>>26,this.words[h]=b&67108863;return this.negative=1,this._strip()},o.prototype._wordDiv=function(i,u){var m=this.length-i.length,p=this.clone(),h=i,b=h.words[h.length-1]|0,T=this._countBits(b);m=26-T,m!==0&&(h=h.ushln(m),p.iushln(m),b=h.words[h.length-1]|0);var f=p.length-h.length,s;if(u!=="mod"){s=new o(null),s.length=f+1,s.words=new Array(s.length);for(var g=0;g<s.length;g++)s.words[g]=0}var D=p.clone()._ishlnsubmul(h,1,f);D.negative===0&&(p=D,s&&(s.words[f]=1));for(var O=f-1;O>=0;O--){var M=(p.words[h.length+O]|0)*67108864+(p.words[h.length+O-1]|0);for(M=Math.min(M/b|0,67108863),p._ishlnsubmul(h,M,O);p.negative!==0;)M--,p.negative=0,p._ishlnsubmul(h,1,O),p.isZero()||(p.negative^=1);s&&(s.words[O]=M)}return s&&s._strip(),p._strip(),u!=="div"&&m!==0&&p.iushrn(m),{div:s||null,mod:p}},o.prototype.divmod=function(i,u,m){if(t(!i.isZero()),this.isZero())return{div:new o(0),mod:new o(0)};var p,h,b;return this.negative!==0&&i.negative===0?(b=this.neg().divmod(i,u),u!=="mod"&&(p=b.div.neg()),u!=="div"&&(h=b.mod.neg(),m&&h.negative!==0&&h.iadd(i)),{div:p,mod:h}):this.negative===0&&i.negative!==0?(b=this.divmod(i.neg(),u),u!=="mod"&&(p=b.div.neg()),{div:p,mod:b.mod}):this.negative&i.negative?(b=this.neg().divmod(i.neg(),u),u!=="div"&&(h=b.mod.neg(),m&&h.negative!==0&&h.isub(i)),{div:b.div,mod:h}):i.length>this.length||this.cmp(i)<0?{div:new o(0),mod:this}:i.length===1?u==="div"?{div:this.divn(i.words[0]),mod:null}:u==="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,u)},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 u=this.divmod(i);if(u.mod.isZero())return u.div;var m=u.div.negative!==0?u.mod.isub(i):u.mod,p=i.ushrn(1),h=i.andln(1),b=m.cmp(p);return b<0||h===1&&b===0?u.div:u.div.negative!==0?u.div.isubn(1):u.div.iaddn(1)},o.prototype.modrn=function(i){var u=i<0;u&&(i=-i),t(i<=67108863);for(var m=(1<<26)%i,p=0,h=this.length-1;h>=0;h--)p=(m*p+(this.words[h]|0))%i;return u?-p:p},o.prototype.modn=function(i){return this.modrn(i)},o.prototype.idivn=function(i){var u=i<0;u&&(i=-i),t(i<=67108863);for(var m=0,p=this.length-1;p>=0;p--){var h=(this.words[p]|0)+m*67108864;this.words[p]=h/i|0,m=h%i}return this._strip(),u?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 u=this,m=i.clone();u.negative!==0?u=u.umod(i):u=u.clone();for(var p=new o(1),h=new o(0),b=new o(0),T=new o(1),f=0;u.isEven()&&m.isEven();)u.iushrn(1),m.iushrn(1),++f;for(var s=m.clone(),g=u.clone();!u.isZero();){for(var D=0,O=1;!(u.words[0]&O)&&D<26;++D,O<<=1);if(D>0)for(u.iushrn(D);D-- >0;)(p.isOdd()||h.isOdd())&&(p.iadd(s),h.isub(g)),p.iushrn(1),h.iushrn(1);for(var M=0,E=1;!(m.words[0]&E)&&M<26;++M,E<<=1);if(M>0)for(m.iushrn(M);M-- >0;)(b.isOdd()||T.isOdd())&&(b.iadd(s),T.isub(g)),b.iushrn(1),T.iushrn(1);u.cmp(m)>=0?(u.isub(m),p.isub(b),h.isub(T)):(m.isub(u),b.isub(p),T.isub(h))}return{a:b,b:T,gcd:m.iushln(f)}},o.prototype._invmp=function(i){t(i.negative===0),t(!i.isZero());var u=this,m=i.clone();u.negative!==0?u=u.umod(i):u=u.clone();for(var p=new o(1),h=new o(0),b=m.clone();u.cmpn(1)>0&&m.cmpn(1)>0;){for(var T=0,f=1;!(u.words[0]&f)&&T<26;++T,f<<=1);if(T>0)for(u.iushrn(T);T-- >0;)p.isOdd()&&p.iadd(b),p.iushrn(1);for(var s=0,g=1;!(m.words[0]&g)&&s<26;++s,g<<=1);if(s>0)for(m.iushrn(s);s-- >0;)h.isOdd()&&h.iadd(b),h.iushrn(1);u.cmp(m)>=0?(u.isub(m),p.isub(h)):(m.isub(u),h.isub(p))}var D;return u.cmpn(1)===0?D=p:D=h,D.cmpn(0)<0&&D.iadd(i),D},o.prototype.gcd=function(i){if(this.isZero())return i.abs();if(i.isZero())return this.abs();var u=this.clone(),m=i.clone();u.negative=0,m.negative=0;for(var p=0;u.isEven()&&m.isEven();p++)u.iushrn(1),m.iushrn(1);do{for(;u.isEven();)u.iushrn(1);for(;m.isEven();)m.iushrn(1);var h=u.cmp(m);if(h<0){var b=u;u=m,m=b}else if(h===0||m.cmpn(1)===0)break;u.isub(m)}while(!0);return m.iushln(p)},o.prototype.invm=function(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 u=i%26,m=(i-u)/26,p=1<<u;if(this.length<=m)return this._expand(m+1),this.words[m]|=p,this;for(var h=p,b=m;h!==0&&b<this.length;b++){var T=this.words[b]|0;T+=h,h=T>>>26,T&=67108863,this.words[b]=T}return h!==0&&(this.words[b]=h,this.length++),this},o.prototype.isZero=function(){return this.length===1&&this.words[0]===0},o.prototype.cmpn=function(i){var u=i<0;if(this.negative!==0&&!u)return-1;if(this.negative===0&&u)return 1;this._strip();var m;if(this.length>1)m=1;else{u&&(i=-i),t(i<=67108863,"Number is too big");var p=this.words[0]|0;m=p===i?0:p<i?-1:1}return this.negative!==0?-m|0:m},o.prototype.cmp=function(i){if(this.negative!==0&&i.negative===0)return-1;if(this.negative===0&&i.negative!==0)return 1;var u=this.ucmp(i);return this.negative!==0?-u|0:u},o.prototype.ucmp=function(i){if(this.length>i.length)return 1;if(this.length<i.length)return-1;for(var u=0,m=this.length-1;m>=0;m--){var p=this.words[m]|0,h=i.words[m]|0;if(p!==h){p<h?u=-1:p>h&&(u=1);break}}return u},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 $(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 Lr={k256:null,p224:null,p192:null,p25519:null};function Lt(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()}Lt.prototype._tmp=function(){var i=new o(null);return i.words=new Array(Math.ceil(this.n/13)),i},Lt.prototype.ireduce=function(i){var u=i,m;do this.split(u,this.tmp),u=this.imulK(u),u=u.iadd(this.tmp),m=u.bitLength();while(m>this.n);var p=m<this.n?-1:u.ucmp(this.p);return p===0?(u.words[0]=0,u.length=1):p>0?u.isub(this.p):u.strip!==void 0?u.strip():u._strip(),u},Lt.prototype.split=function(i,u){i.iushrn(this.n,0,u)},Lt.prototype.imulK=function(i){return i.imul(this.k)};function mn(){Lt.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(mn,Lt),mn.prototype.split=function(i,u){for(var m=4194303,p=Math.min(i.length,9),h=0;h<p;h++)u.words[h]=i.words[h];if(u.length=p,i.length<=9){i.words[0]=0,i.length=1;return}var b=i.words[9];for(u.words[u.length++]=b&m,h=10;h<i.length;h++){var T=i.words[h]|0;i.words[h-10]=(T&m)<<4|b>>>22,b=T}b>>>=22,i.words[h-10]=b,b===0&&i.length>10?i.length-=10:i.length-=9},mn.prototype.imulK=function(i){i.words[i.length]=0,i.words[i.length+1]=0,i.length+=2;for(var u=0,m=0;m<i.length;m++){var p=i.words[m]|0;u+=p*977,i.words[m]=u&67108863,u=p*64+(u/67108864|0)}return i.words[i.length-1]===0&&(i.length--,i.words[i.length-1]===0&&i.length--),i};function Hi(){Lt.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(Hi,Lt);function zi(){Lt.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(zi,Lt);function jr(){Lt.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(jr,Lt),jr.prototype.imulK=function(i){for(var u=0,m=0;m<i.length;m++){var p=(i.words[m]|0)*19+u,h=p&67108863;p>>>=26,i.words[m]=h,u=p}return u!==0&&(i.words[i.length++]=u),i},o._prime=function(i){if(Lr[i])return Lr[i];var u;if(i==="k256")u=new mn;else if(i==="p224")u=new Hi;else if(i==="p192")u=new zi;else if(i==="p25519")u=new jr;else throw new Error("Unknown prime "+i);return Lr[i]=u,u};function $(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}$.prototype._verify1=function(i){t(i.negative===0,"red works only with positives"),t(i.red,"red works only with red numbers")},$.prototype._verify2=function(i,u){t((i.negative|u.negative)===0,"red works only with positives"),t(i.red&&i.red===u.red,"red works only with red numbers")},$.prototype.imod=function(i){return this.prime?this.prime.ireduce(i)._forceRed(this):(S(i,i.umod(this.m)._forceRed(this)),i)},$.prototype.neg=function(i){return i.isZero()?i.clone():this.m.sub(i)._forceRed(this)},$.prototype.add=function(i,u){this._verify2(i,u);var m=i.add(u);return m.cmp(this.m)>=0&&m.isub(this.m),m._forceRed(this)},$.prototype.iadd=function(i,u){this._verify2(i,u);var m=i.iadd(u);return m.cmp(this.m)>=0&&m.isub(this.m),m},$.prototype.sub=function(i,u){this._verify2(i,u);var m=i.sub(u);return m.cmpn(0)<0&&m.iadd(this.m),m._forceRed(this)},$.prototype.isub=function(i,u){this._verify2(i,u);var m=i.isub(u);return m.cmpn(0)<0&&m.iadd(this.m),m},$.prototype.shl=function(i,u){return this._verify1(i),this.imod(i.ushln(u))},$.prototype.imul=function(i,u){return this._verify2(i,u),this.imod(i.imul(u))},$.prototype.mul=function(i,u){return this._verify2(i,u),this.imod(i.mul(u))},$.prototype.isqr=function(i){return this.imul(i,i.clone())},$.prototype.sqr=function(i){return this.mul(i,i)},$.prototype.sqrt=function(i){if(i.isZero())return i.clone();var u=this.m.andln(3);if(t(u%2===1),u===3){var m=this.m.add(new o(1)).iushrn(2);return this.pow(i,m)}for(var p=this.m.subn(1),h=0;!p.isZero()&&p.andln(1)===0;)h++,p.iushrn(1);t(!p.isZero());var b=new o(1).toRed(this),T=b.redNeg(),f=this.m.subn(1).iushrn(1),s=this.m.bitLength();for(s=new o(2*s*s).toRed(this);this.pow(s,f).cmp(T)!==0;)s.redIAdd(T);for(var g=this.pow(s,p),D=this.pow(i,p.addn(1).iushrn(1)),O=this.pow(i,p),M=h;O.cmp(b)!==0;){for(var E=O,_=0;E.cmp(b)!==0;_++)E=E.redSqr();t(_<M);var U=this.pow(g,new o(1).iushln(M-_-1));D=D.redMul(U),g=U.redSqr(),O=O.redMul(g),M=_}return D},$.prototype.invm=function(i){var u=i._invmp(this.m);return u.negative!==0?(u.negative=0,this.imod(u).redNeg()):this.imod(u)},$.prototype.pow=function(i,u){if(u.isZero())return new o(1).toRed(this);if(u.cmpn(1)===0)return i.clone();var m=4,p=new Array(1<<m);p[0]=new o(1).toRed(this),p[1]=i;for(var h=2;h<p.length;h++)p[h]=this.mul(p[h-1],i);var b=p[0],T=0,f=0,s=u.bitLength()%26;for(s===0&&(s=26),h=u.length-1;h>=0;h--){for(var g=u.words[h],D=s-1;D>=0;D--){var O=g>>D&1;if(b!==p[0]&&(b=this.sqr(b)),O===0&&T===0){f=0;continue}T<<=1,T|=O,f++,!(f!==m&&(h!==0||D!==0))&&(b=this.mul(b,p[T]),f=0,T=0)}s=26}return b},$.prototype.convertTo=function(i){var u=i.umod(this.m);return u===i?u.clone():u},$.prototype.convertFrom=function(i){var u=i.clone();return u.red=null,u},o.mont=function(i){return new pe(i)};function pe(y){$.call(this,y),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}n(pe,$),pe.prototype.convertTo=function(i){return this.imod(i.ushln(this.shift))},pe.prototype.convertFrom=function(i){var u=this.imod(i.mul(this.rinv));return u.red=null,u},pe.prototype.imul=function(i,u){if(i.isZero()||u.isZero())return i.words[0]=0,i.length=1,i;var m=i.imul(u),p=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),h=m.isub(p).iushrn(this.shift),b=h;return h.cmp(this.m)>=0?b=h.isub(this.m):h.cmpn(0)<0&&(b=h.iadd(this.m)),b._forceRed(this)},pe.prototype.mul=function(i,u){if(i.isZero()||u.isZero())return new o(0)._forceRed(this);var m=i.mul(u),p=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),h=m.isub(p).iushrn(this.shift),b=h;return h.cmp(this.m)>=0?b=h.isub(this.m):h.cmpn(0)<0&&(b=h.iadd(this.m)),b._forceRed(this)},pe.prototype.invm=function(i){var u=this.imod(i._invmp(this.m).mul(this.r2));return u._forceRed(this)}})(typeof $i>"u"||$i,sl)});import{TransactionType as Rl}from"@msafe/sui3-utils";import{coinsList as Cl,poolIdPoolNameMap as kl,poolInfo as ps,singleAssetPoolCoinMap as vl}from"@alphafi/alphafi-sdk";import{TransactionType as We}from"@msafe/sui3-utils";import{bcs as pn,fromBase64 as dn}from"@mysten/bcs";var fn=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isClaimRewardTransaction())return this.decodeClaimReward();let e=this.getLiquidityChangeEvent();if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson,n=t.pool_id,o=kl[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&&ps[t].assetTypes.length===2}isSingleAssetDepositEvent(e,t){return e.event_type===0&&ps[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=pn.u64().parse(dn(t)):t.length===24?n=pn.u128().parse(dn(t)):t.length===44?n=pn.u256().parse(dn(t)):n=pn.u64().parse(dn(t)),n}decodeDoubleAssetDeposit(e,t){let{amount_a:n,amount_b:o}=t,r=Number(n)>0;return console.log("Decoder.decodeDoubleAssetDeposit",n,o,r),{txType:We.Other,type:"depositDoubleAsset",intentionData:{poolName:e,amount:r?n:o,isAmountA:r}}}decodeSingleAssetDeposit(e,t){let{amount:n}=t;if(console.log("Decoder.decodeSingleAssetDeposit",n),this.getLiquidityChangeEvent().type.includes(":alphafi_navi_pool:")){let{coin:r}=vl[e],{expo:c}=Cl[r];n=Math.floor(Number(n)/10**(9-c)).toString()}return{txType:We.Other,type:"depositSingleAsset",intentionData:{poolName:e,amount:n}}}decodeWithdraw(e){let t=this.extractXTokensAmount();return console.log("Decoder.decodeWithdraw",t),{txType:We.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:We.Other,type:"withdrawAlpha",intentionData:{withdrawFromLocked:Number(n)>0,xTokensAmount:t}}}decodeClaimReward(){return{txType:We.Other,type:"claimReward",intentionData:{}}}};import{claimRewardTxb as Dl}from"@alphafi/alphafi-sdk";import xl from"sort-keys-recursive";var v=class{constructor(e){this.data=e}serialize(){return JSON.stringify(xl(this.data))}};var hn=class a extends v{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t;return await Dl(n.address)}static fromData(t){return new a(t)}};import{depositDoubleAssetTxb as Al}from"@alphafi/alphafi-sdk";var gn=class a extends v{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:o,amount:r,isAmountA:c}=this.data;return await Al(o,n.address,r,c)}static fromData(t){return console.log("DepositDoubleAssetIntention.fromData",t),new a(t)}};import{depositSingleAssetTxb as Ol}from"@alphafi/alphafi-sdk";var yn=class a extends v{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:o,amount:r}=this.data;return await Ol(o,n.address,r)}static fromData(t){return console.log("DepositSingleAssetIntention.fromData",t),new a(t)}};import{withdrawTxb as Ml}from"@alphafi/alphafi-sdk";var bn=class a extends v{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{poolName:o,xTokensAmount:r}=this.data;return await Ml(r,o,n.address)}static fromData(t){return console.log("WithdrawIntention.fromData",t),new a(t)}};import{withdrawAlphaTxb as Pl}from"@alphafi/alphafi-sdk";var Sn=class a extends v{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{withdrawFromLocked:o,xTokensAmount:r}=this.data;return await Pl(r,o,n.address)}static fromData(t){return console.log("WithdrawAlphaIntention.fromData",t),new a(t)}};var Tn=class{application="alphafi";supportSDK="@mysten/sui";async deserialize(e){let{transaction:t,suiClient:n,account:o}=e,r=await n.devInspectTransactionBlock({sender:t.getData().sender,transactionBlock:t});console.log("AlphaFiHelper Sim result - ",r);let l=new fn(t,r).decode();return{txType:Rl.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{account:t}=e;console.log("AlphaFi build transaction type",e.txSubType);let n;switch(e.txSubType){case"depositSingleAsset":n=yn.fromData(e.intentionData);break;case"depositDoubleAsset":n=gn.fromData(e.intentionData);break;case"withdraw":n=bn.fromData(e.intentionData);break;case"withdrawAlpha":n=Sn.fromData(e.intentionData);break;case"claimReward":n=hn.fromData(e.intentionData);break;default:throw new Error("not implemented")}return n.build({account:t})}};import{TransactionType as eu}from"@msafe/sui3-utils";import{TransactionType as _t}from"@msafe/sui3-utils";import{bcs as ii}from"@mysten/sui/bcs";import{SBUCK_FOUNTAIN_PACKAGE_ID as si}from"bucket-protocol-sdk";var wn=class{constructor(e){this.transaction=e}decode(){if(this.isSBUCKDepositTransaction())return this.decodeSBUCKDeposit();if(this.isSBUCKUnstakeTransaction())return this.decodeSBUCKUnstake();if(this.isSBUCKWithdrawTransaction())return this.decodeSBUCKWithdraw();if(this.isSBUCKClaimTransaction())return this.decodeSBUCKClaim();if(this.isLockedClaimTransaction())return this.decodeLockedClaim();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isCloseTransaction())return this.decodeClose();if(this.isTankDepositTransaction())return this.decodeTankDeposit();if(this.isTankWithdrawTransaction())return this.decodeTankWithdraw();if(this.isTankClaimTransaction())return this.decodeTankClaim();if(this.isPsmTransaction())return this.decodePsm();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getMoveCallModuleCommand(e,t){return this.commands.find(n=>n.$kind==="MoveCall"&&n.MoveCall.module===e&&n.MoveCall.function===t)}getMoveCallPackageModuleCommand(e,t,n){return this.commands.find(o=>o.$kind==="MoveCall"&&o.MoveCall.package===e&&o.MoveCall.module===t&&o.MoveCall.function===n)}getMoveCallModuleCommands(e,t){return this.commands.filter(n=>n.$kind==="MoveCall"&&n.MoveCall.module===e&&n.MoveCall.function===t)}getSplitCoinsCommands(){return this.commands.filter(e=>e.$kind==="SplitCoins")}getTransferCommands(){return this.commands.filter(e=>e.$kind==="TransferObjects")}isPsmTransaction(){return!!this.getMoveCallCommand("charge_reservoir")||!!this.getMoveCallCommand("discharge_reservoir")}isStrapNewTransaction(){return!!this.getMoveCallModuleCommand("strap","new")}isBorrowTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","high_top_up")||!!this.getMoveCallModuleCommand("bucket_operations","high_borrow")||!!this.getMoveCallModuleCommand("bucket_operations","high_borrow_with_strap")}isRepayTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","fully_repay")||!!this.getMoveCallModuleCommand("bucket_operations","fully_repay_with_strap")||!!this.getMoveCallModuleCommand("bucket_operations","repay_and_withdraw")||!!this.getMoveCallModuleCommand("bucket_operations","repay_and_withdraw_with_strap")}isWithdrawTransaction(){return!!this.getMoveCallModuleCommand("buck","withdraw")||!!this.getMoveCallModuleCommand("buck","withdraw_with_strap")}isCloseTransaction(){return!!this.getMoveCallModuleCommand("bucket_operations","destroy_empty_strap")}isTankDepositTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","deposit")}isTankWithdrawTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","withdraw")}isTankClaimTransaction(){return!!this.getMoveCallModuleCommand("tank_operations","claim")}isSBUCKDepositTransaction(){return!!this.getMoveCallModuleCommand("buck","buck_to_sbuck")}isSBUCKWithdrawTransaction(){return!!this.getMoveCallModuleCommand("buck","sbuck_to_buck")}isSBUCKStakeTransaction(){return!!this.getMoveCallPackageModuleCommand(si,"fountain_core","stake")}isSBUCKUnstakeTransaction(){return!!this.getMoveCallPackageModuleCommand(si,"fountain_core","force_unstake")}isSBUCKClaimTransaction(){return!!this.getMoveCallPackageModuleCommand(si,"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:_t.Other,type:"psm",intentionData:{coinType:e,amount:n,buckToCoin:t}}}decodeBorrow(){let e="",t="0",n,o=this.getStrapId(),r="0",c=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];if(c.$kind==="Input"&&(r=this.getPureInputU64(c.Input)),this.getMoveCallCommand("high_top_up")){let l=this.getMoveCallCommand("high_top_up").MoveCall;[e]=l.typeArguments;let d=l.arguments[1];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input));let S=l.arguments[3];if(S.$kind==="Input"){let w=this.getPureAddresses(S.Input);w.length===1&&([n]=w)}}else if(this.getMoveCallCommand("high_borrow")){let l=this.getMoveCallCommand("high_borrow").MoveCall;[e]=l.typeArguments;let d=l.arguments[4];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input));let S=l.arguments[5];if(S.$kind==="Input"){let w=this.getPureAddresses(S.Input);w.length===1&&([n]=w)}}else if(this.getMoveCallCommand("high_borrow_with_strap")){let l=this.getMoveCallCommand("high_borrow_with_strap").MoveCall;[e]=l.typeArguments;let d=l.arguments[5];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input));let S=l.arguments[6];if(S.$kind==="Input"){let w=this.getPureAddresses(S.Input);w.length===1&&([n]=w)}}return{txType:_t.Other,type:"borrow",intentionData:{collateralType:e,collateralAmount:r,borrowAmount:t,insertionPlace:n,strapId:o}}}decodeRepay(){let e="",t="0",n="0",r,c=this.getStrapId();if(this.getMoveCallCommand("fully_repay"))[e]=this.getMoveCallCommand("fully_repay").MoveCall.typeArguments;else if(this.getMoveCallCommand("fully_repay_with_strap"))[e]=this.getMoveCallCommand("fully_repay_with_strap").MoveCall.typeArguments;else if(this.getMoveCallCommand("repay_and_withdraw")){let l=this.getMoveCallCommand("repay_and_withdraw").MoveCall;[e]=l.typeArguments;let d=l.arguments[4];d.$kind==="Input"&&(n=this.getPureInputU64(d.Input));let S=l.arguments[5];if(S.$kind==="Input"){let I=this.getPureAddresses(S.Input);I.length===1&&([r]=I)}let w=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];w.$kind==="Input"&&(t=this.getPureInputU64(w.Input))}else if(this.getMoveCallCommand("repay_and_withdraw_with_strap")){let l=this.getMoveCallCommand("repay_and_withdraw_with_strap").MoveCall;[e]=l.typeArguments;let d=l.arguments[5];d.$kind==="Input"&&(n=this.getPureInputU64(d.Input));let S=l.arguments[6];if(S.$kind==="Input"){let I=this.getPureAddresses(S.Input);I.length===1&&([r]=I)}let w=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];w.$kind==="Input"&&(t=this.getPureInputU64(w.Input))}return{txType:_t.Other,type:"repay",intentionData:{collateralType:e,repayAmount:t,withdrawAmount:n,isSurplus:!1,insertionPlace:r,strapId:c}}}decodeWithdraw(){let e="",t="0",n,o=this.getStrapId();if(this.getMoveCallCommand("withdraw_with_strap")){let r=this.getMoveCallCommand("withdraw_with_strap").MoveCall;[e]=r.typeArguments;let c=r.arguments[4];c.$kind==="Input"&&(t=this.getPureInputU64(c.Input));let l=r.arguments[5];if(l.$kind==="Input"){let d=this.getPureAddresses(l.Input);d.length===1&&([n]=d)}}else if(this.getMoveCallCommand("withdraw")){let r=this.getMoveCallCommand("withdraw").MoveCall;[e]=r.typeArguments;let c=r.arguments[3];c.$kind==="Input"&&(t=this.getPureInputU64(c.Input));let l=r.arguments[4];if(l.$kind==="Input"){let d=this.getPureAddresses(l.Input);d.length===1&&([n]=d)}}return{txType:_t.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:_t.Other,type:"close",intentionData:{collateralType:e,strapId:t}}}decodeSBUCKDeposit(){let t=this.getMoveCallCommand("into_balance").MoveCall.typeArguments[0],n="0",r=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];r.$kind==="Input"&&(n=this.getPureInputU64(r.Input));let c=this.isSBUCKStakeTransaction();return console.log("Decoder.decodeSBUCKDeposit",t,n,c),{txType:_t.Other,type:"sbuck-deposit",intentionData:{coinType:t,amount:n,isStake:c}}}decodeSBUCKUnstake(){let e="0",t=this.isSBUCKStakeTransaction();if(t){let d=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];d.$kind==="Input"&&(e=this.getPureInputU64(d.Input))}let n=[],o=this.getMoveCallModuleCommands("proof_rule","unlock");if(o.length>0)for(let l=0;l<o.length;l++){let d=o[l];n.push("")}else{let l=this.getMoveCallModuleCommands("fountain_core","force_unstake");for(let d=0;d<l.length;d++){let w=l[d].MoveCall.arguments[2];if(w.$kind==="Input"){let{objectId:I}=this.inputs[w.Input].UnresolvedObject;n.push(I)}}}let r=this.isSBUCKWithdrawTransaction(),c={stakeProofs:n,amount:e,isStake:t,toBuck:r};return console.log("Decoder.decodeSBUCKUnstake",c),{txType:_t.Other,type:"sbuck-unstake",intentionData:c}}decodeSBUCKWithdraw(){let e="0",n=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return n.$kind==="Input"&&(e=this.getPureInputU64(n.Input)),console.log("Decoder.SBUCKWithdraw",e),{txType:_t.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 r=t[n].MoveCall.arguments[2];if(r.$kind==="Input"){let{objectId:c}=this.inputs[r.Input].UnresolvedObject;e.push(c)}}return console.log("Decoder.decodeSBUCKClaim",e),{txType:_t.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 r=this.getMoveCallModuleCommand("tank_operations","deposit").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankDeposit",r,e),{txType:_t.Other,type:"tank-deposit",intentionData:{coinType:r,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:_t.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:_t.Other,type:"tank-claim",intentionData:{coinType:t}}}decodeLockedClaim(){let e="",t=0,n=this.getMoveCallModuleCommands("proof_rule","claim");for(let r=0;r<n.length;r++)[e]=n[r].MoveCall.typeArguments,t++;let o=this.getMoveCallModuleCommands("lst_proof_rule","claim");for(let r=0;r<o.length;r++)[e]=o[r].MoveCall.typeArguments,t++;return console.log("Decoder.decodeLockedClaim",e,t),{txType:_t.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 ii.U64.fromBase64(t.Pure.bytes)}getPureAddresses(e){let t=this.inputs[e];if(t.$kind!=="Pure")throw new Error("not pure argument");return ii.vector(ii.Address).fromBase64(t.Pure.bytes)}};import{TransactionType as Wl}from"@msafe/sui3-utils";import{Transaction as El}from"@mysten/sui/transactions";import{buildPsmTx as Nl}from"bucket-protocol-sdk";import{BucketClient as Bl}from"bucket-protocol-sdk";var Ot=(a,e)=>{let t=a==="sui:mainnet"?"mainnet":"testnet";return new Bl(t,e.address)};var ds=async(a,e,t)=>{let{coinType:n,amount:o,buckToCoin:r}=a,c=new El,l=Ot(t,e);return await Nl(l,c,n,o,r,e.address),c};var In=class a extends v{constructor(t){super(t);this.data=t}txType=Wl.Other;txSubType="psm";async build(t){let{account:n,network:o}=t;return await ds(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as ql}from"@msafe/sui3-utils";import{Transaction as Cn}from"@mysten/sui/transactions";import{buildBorrowTx as _l,buildCloseTx as Ll,buildRepayTx as jl,buildWithdrawTx as Ul}from"bucket-protocol-sdk";var fs=async(a,e,t)=>{let{collateralType:n,collateralAmount:o,borrowAmount:r,insertionPlace:c,strapId:l}=a,d=new Cn,S=Ot(t,e);return await _l(S,d,n,o,r,e.address,c,l),d},hs=async(a,e,t)=>{let{collateralType:n,withdrawAmount:o,insertionPlace:r,strapId:c}=a,l=new Cn,d=Ot(t,e);return await Ul(d,l,n,o,e.address,r,c),l},gs=async(a,e,t)=>{let{collateralType:n,repayAmount:o,withdrawAmount:r,isSurplus:c,insertionPlace:l,strapId:d}=a,S=new Cn,w=Ot(t,e);return await jl(w,S,n,o,r,e.address,c,l,d),S},ys=async(a,e,t)=>{let{collateralType:n,recipient:o,strapId:r}=a,c=new Cn,l=Ot(t,e);return await Ll(l,c,n,o,r),c};var kn=class a extends v{constructor(t){super(t);this.data=t}txType=ql.Other;txSubType="borrow";async build(t){let{account:n,network:o}=t;return await fs(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Fl}from"@msafe/sui3-utils";var vn=class a extends v{constructor(t){super(t);this.data=t}txType=Fl.Other;txSubType="repay";async build(t){let{account:n,network:o}=t;return await gs(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Kl}from"@msafe/sui3-utils";var xn=class a extends v{constructor(t){super(t);this.data=t}txType=Kl.Other;txSubType="withdraw";async build(t){let{account:n,network:o}=t;return await hs(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Vl}from"@msafe/sui3-utils";var Dn=class a extends v{constructor(t){super(t);this.data=t}txType=Vl.Other;txSubType="close";async build(t){let{account:n,network:o}=t;return await ys(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Bn}from"@msafe/sui3-utils";import{Transaction as An}from"@mysten/sui/transactions";import{buildSBUCKClaimTx as $l,buildSBUCKDepositTx as Hl,buildSBUCKUnstakeTx as zl,buildSBUCKWithdrawTx as Gl}from"bucket-protocol-sdk";var bs=async(a,e,t)=>{let{coinType:n,amount:o,isStake:r}=a,c=new An,l=Ot(t,e);return await Hl(l,c,n,o,e.address,r),c},Ss=async(a,e,t)=>{let{stakeProofs:n,amount:o,isStake:r,toBuck:c}=a,l=new An,d=Ot(t,e);return await zl(d,l,n,o,e.address,r,c),l},Ts=async(a,e,t)=>{let{amount:n}=a,o=new An,r=Ot(t,e);return await Gl(r,o,n,e.address),o},ws=async(a,e,t)=>{let{stakeProofs:n}=a,o=new An,r=Ot(t,e);return await $l(r,o,n,e.address),o};var On=class a extends v{constructor(t){super(t);this.data=t}txType=Bn.Other;txSubType="sbuck-deposit";async build(t){let{account:n,network:o}=t;return await bs(this.data,n,o)}static fromData(t){return new a(t)}},Mn=class a extends v{constructor(t){super(t);this.data=t}txType=Bn.Other;txSubType="sbuck-unstake";async build(t){let{account:n,network:o}=t;return await Ss(this.data,n,o)}static fromData(t){return new a(t)}},Pn=class a extends v{constructor(t){super(t);this.data=t}txType=Bn.Other;txSubType="sbuck-withdraw";async build(t){let{account:n,network:o}=t;return await Ts(this.data,n,o)}static fromData(t){return new a(t)}},Rn=class a extends v{constructor(t){super(t);this.data=t}txType=Bn.Other;txSubType="sbuck-claim";async build(t){let{account:n,network:o}=t;return await ws(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as li}from"@msafe/sui3-utils";import{Transaction as ci}from"@mysten/sui/transactions";import{buildTankClaimTx as Ql,buildTankDepositTx as Jl,buildTankWithdrawTx as Xl}from"bucket-protocol-sdk";var Is=async(a,e,t)=>{let{coinType:n,amount:o}=a,r=new ci,c=Ot(t,e);return await Jl(c,r,n,o,e.address),r},Cs=async(a,e,t)=>{let{coinType:n,amount:o}=a,r=new ci,c=Ot(t,e);return await Xl(c,r,n,o,e.address),r},ks=async(a,e,t)=>{let{coinType:n}=a,o=new ci,r=Ot(t,e);return await Ql(r,o,n,e.address),o};import{Transaction as Yl}from"@mysten/sui/transactions";import{buildLockedClaimTx as Zl}from"bucket-protocol-sdk";var vs=async(a,e,t)=>{let{coinType:n,proofCount:o}=a,r=new Yl,c=Ot(t,e);return await Zl(c,r,n,o,e.address),r};var En=class a extends v{constructor(t){super(t);this.data=t}txType=li.Other;txSubType="tank-deposit";async build(t){let{account:n,network:o}=t;return await Is(this.data,n,o)}static fromData(t){return new a(t)}},Nn=class a extends v{constructor(t){super(t);this.data=t}txType=li.Other;txSubType="tank-withdraw";async build(t){let{account:n,network:o}=t;return await Cs(this.data,n,o)}static fromData(t){return new a(t)}},Wn=class a extends v{constructor(t){super(t);this.data=t}txType=li.Other;txSubType="tank-claim";async build(t){let{account:n,network:o}=t;return await ks(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as tu}from"@msafe/sui3-utils";var _n=class a extends v{constructor(t){super(t);this.data=t}txType=tu.Other;txSubType="lock-claim";async build(t){let{account:n,network:o}=t;return await vs(this.data,n,o)}static fromData(t){return new a(t)}};var Ln=class{application="bucket";supportSDK="@mysten/sui";async deserialize(e){console.log("Bucket helper deserialize input: ",e);let{transaction:t}=e,o=new wn(t).decode();return{txType:eu.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e,r;switch(e.txSubType){case"psm":r=In.fromData(e.intentionData);break;case"borrow":r=kn.fromData(e.intentionData);break;case"withdraw":r=xn.fromData(e.intentionData);break;case"repay":r=vn.fromData(e.intentionData);break;case"close":r=Dn.fromData(e.intentionData);break;case"tank-deposit":r=En.fromData(e.intentionData);break;case"tank-withdraw":r=Nn.fromData(e.intentionData);break;case"tank-claim":r=Wn.fromData(e.intentionData);break;case"sbuck-deposit":r=On.fromData(e.intentionData);break;case"sbuck-unstake":r=Mn.fromData(e.intentionData);break;case"sbuck-withdraw":r=Pn.fromData(e.intentionData);break;case"sbuck-claim":r=Rn.fromData(e.intentionData);break;case"lock-claim":r=_n.fromData(e.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:t,account:n,network:o})}};import{TransactionType as qu}from"@msafe/sui3-utils";import{TransactionType as lu}from"@msafe/sui3-utils";import{AggregatorClient as nu,Env as ou}from"@cetusprotocol/aggregator-sdk";import{CetusFarmsSDK as au}from"@cetusprotocol/farms-sdk";import{CetusClmmSDK as ru}from"@cetusprotocol/sui-clmm-sdk";import{CetusVaultsSDK as iu}from"@cetusprotocol/vaults-sdk";import{CetusXcetusSDK as su}from"@cetusprotocol/xcetus-sdk";import{SuiClient as ui,getFullnodeUrl as xs}from"@mysten/sui/client";var Zt=(a,e)=>{let t=ru.createSDK({env:"mainnet",sui_client:new ui({url:xs("mainnet")})});return t.setSenderAddress(e.address),t},jt=(a,e)=>{let t=au.createSDK({env:"mainnet",sui_client:new ui({url:xs("mainnet")})});return t.setSenderAddress(e.address),t},cu="https://api-sui.cetus.zone/router_v2/find_routes",Ds=(a,e)=>{let t=new ui({url:"https://fullnode.mainnet.sui.io/"});return new nu({endpoint:cu,signer:e.address,client:t,env:ou.Mainnet})},_e=(a,e)=>{let t=iu.createSDK({env:"mainnet"});return t.setSenderAddress(e.address),t},Se=(a,e)=>{let t=su.createSDK({env:"mainnet"});return t.setSenderAddress(e.address),t};var As=async(a,e,t)=>await Zt(t,e).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),Os=async(a,e,t)=>await Zt(t,e).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),Ms=async(a,e,t)=>await Zt(t,e).Position.closePositionPayload(a),Ps=async(a,e,t)=>await Zt(t,e).Position.removeLiquidityPayload(a),Rs=async(a,e,t)=>await Zt(t,e).Rewarder.collectRewarderPayload(a);var jn=class a extends v{constructor(t){super(t);this.data=t}txType=lu.Other;txSubType="OpenAndAddLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await As(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as uu}from"@msafe/sui3-utils";var Un=class a extends v{constructor(t){super(t);this.data=t}txType=uu.Other;txSubType="ClaimFeeAndMining";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Rs(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as mu}from"@msafe/sui3-utils";var qn=class a extends v{constructor(t){super(t);this.data=t}txType=mu.Other;txSubType="DecreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Ps(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as pu}from"@msafe/sui3-utils";var Bs=async(a,e,t)=>await jt(t,e).Farms.openPositionAddLiquidityStakePayload(a),Es=async(a,e,t)=>await jt(t,e).Farms.addLiquidityFixCoinPayload(a),Ns=async(a,e,t)=>await jt(t,e).Farms.removeLiquidityPayload(a),Ws=async(a,e,t)=>await jt(t,e).Farms.removeLiquidityPayload(a),_s=async(a,e,t)=>await jt(t,e).Farms.claimFeeAndClmmReward(a),Ls=async(a,e,t)=>await jt(t,e).Farms.harvestPayload(a),js=async(a,e,t)=>{let n=jt(t,e),o=Object.values(a);return await n.Farms.batchHarvestPayload(o)},Us=async(a,e,t)=>await jt(t,e).Farms.depositPayload(a),qs=async(a,e,t)=>await jt(t,e).Farms.withdrawPayload(a);var Fn=class a extends v{constructor(t){super(t);this.data=t}txType=pu.Other;txSubType="FarmingOpenAndAddLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Bs(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as du}from"@msafe/sui3-utils";var Kn=class a extends v{constructor(t){super(t);this.data=t}txType=du.Other;txSubType="FarmingBatchHarvest";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await js(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as fu}from"@msafe/sui3-utils";var Vn=class a extends v{constructor(t){super(t);this.data=t}txType=fu.Other;txSubType="FarmingClaimFeeAndReward";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await _s(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as hu}from"@msafe/sui3-utils";var $n=class a extends v{constructor(t){super(t);this.data=t}txType=hu.Other;txSubType="FarmingDecreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Ns(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as gu}from"@msafe/sui3-utils";var Hn=class a extends v{constructor(t){super(t);this.data=t}txType=gu.Other;txSubType="FarmingHarvest";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Ls(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as yu}from"@msafe/sui3-utils";var zn=class a extends v{constructor(t){super(t);this.data=t}txType=yu.Other;txSubType="FarmingIncreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Es(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as bu}from"@msafe/sui3-utils";var Gn=class a extends v{constructor(t){super(t);this.data=t}txType=bu.Other;txSubType="FarmingRemoveLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Ws(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Su}from"@msafe/sui3-utils";var Qn=class a extends v{constructor(t){super(t);this.data=t}txType=Su.Other;txSubType="FarmingStake";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Us(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Tu}from"@msafe/sui3-utils";var Jn=class a extends v{constructor(t){super(t);this.data=t}txType=Tu.Other;txSubType="FarmingUnstake";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await qs(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as wu}from"@msafe/sui3-utils";var Xn=class a extends v{constructor(t){super(t);this.data=t}txType=wu.Other;txSubType="IncreaseLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Os(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Du}from"@msafe/sui3-utils";import{Transaction as Yn}from"@mysten/sui/transactions";import Iu,{vaults_mainnet as Cu}from"haedal-vault-sdk";var ku=async(a,e,t)=>{let n=_e(t,e),o=new Yn;return o.setSender(e.address),n.Vest.buildRedeemPayload(a.params,o),o},vu=async(a,e,t)=>{let n=new Iu(Cu);n.senderAddress=e.address;let o=new Yn;return o.setSender(e.address),await n?.Vest.buildRedeemPayload(a.params,o),o},Fs=(a,e,t)=>{let n=Zt(t,e),o=new Yn;return n?.Vest.buildRedeemPayload(a.params,o),o},xu=async(a,e,t)=>{let n=Zt(t,e),o=jt(t,e),r=new Yn,c=await o.Farms.withdrawReturnPayload(a.withdrawParams,r);return n.Vest.buildRedeemPayload(a.redeemParms.map(l=>({...l,clmm_position_id:c})),r),o.Farms.depositPayload({...a.depositParams,clmm_position_id:c},r),r},Ks=async(a,e,t)=>a.type==="clmm"?Fs(a,e,t):a.type==="farms"?xu(a,e,t):a.type==="vaults"?ku(a,e,t):a.type==="haedalVaults"?vu(a,e,t):Fs(a,e,t);var Zn=class a extends v{constructor(t){super(t);this.data=t}txType=Du.Other;txSubType="PosVestingRedeem";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Ks(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Au}from"@msafe/sui3-utils";var to=class a extends v{constructor(t){super(t);this.data=t}txType=Au.Other;txSubType="RemoveLiquidity";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Ms(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Pu}from"@msafe/sui3-utils";import{restituteMsafeFastRouterSwapParams as Ou}from"@cetusprotocol/aggregator-sdk";import{Transaction as Mu}from"@mysten/sui/transactions";var Vs=async(a,e,t)=>{let n=Ds(t,e),o=new Mu;return await n.fastRouterSwap({...a,routers:Ou(a.routers),txb:o}),o};var eo=class a extends v{constructor(t){super(t);this.data=t}txType=Pu.Other;txSubType="AggregatorSwap";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Vs(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Ru}from"@msafe/sui3-utils";import{Transaction as $s}from"@mysten/sui/transactions";var Hs=async(a,e,t)=>{let n=_e(t,e),o=new $s;return o.setSender(e.address),await n.Vaults.deposit(a,o),o},zs=async(a,e,t)=>{let n=_e(t,e),o=new $s;return await n.Vaults.withdraw(a,o),o};var no=class a extends v{constructor(t){super(t);this.data=t}txType=Ru.Other;txSubType="AddVaultsPosition";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Hs(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Bu}from"@msafe/sui3-utils";var oo=class a extends v{constructor(t){super(t);this.data=t}txType=Bu.Other;txSubType="RemoveVaultsPosition";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await zs(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Nu}from"@msafe/sui3-utils";import{Transaction as Eu}from"@mysten/sui/transactions";var Gs={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},Qs=async(a,e,t)=>{console.log("getVestingRedeemTxb txbParams: ",a),console.log("getVestingRedeemTxb account: ",e),console.log("getVestingRedeemTxb network: ",t);let{pool:n,nftId:o,periods:r,CLOCK_ADDRESS:c}=a,l=new Eu;return r.forEach(d=>{l.moveCall({target:`${Gs.published_at}::router::redeem`,typeArguments:[Gs.cetus_coin_type],arguments:[l.object(n),l.object(o),l.pure(d),l.object(c)]})}),l};var ao=class a extends v{constructor(t){super(t);this.data=t}txType=Nu.Other;txSubType="VestingRedeem";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Qs(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Wu}from"@msafe/sui3-utils";var Js=async(a,e,t)=>await Se(t,e).XCetusModule.convertPayload(a),Xs=async(a,e,t)=>await Se(t,e).XCetusModule.redeemLockPayload(a),Ys=async(a,e,t)=>await Se(t,e).XCetusModule.redeemDividendV3Payload(a.veNftId,a.rewardList),Zs=async(a,e,t)=>await Se(t,e).XCetusModule.cancelRedeemPayload(a),tc=async(a,e,t)=>await Se(t,e).XCetusModule.redeemPayload(a);var ro=class a extends v{constructor(t){super(t);this.data=t}txType=Wu.Other;txSubType="xCETUSCancelRedeem";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Zs(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as _u}from"@msafe/sui3-utils";var io=class a extends v{constructor(t){super(t);this.data=t}txType=_u.Other;txSubType="xCETUSClaimStakingRwewards";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Ys(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Lu}from"@msafe/sui3-utils";var so=class a extends v{constructor(t){super(t);this.data=t}txType=Lu.Other;txSubType="xCETUSConvert";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Js(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as ju}from"@msafe/sui3-utils";var co=class a extends v{constructor(t){super(t);this.data=t}txType=ju.Other;txSubType="xCETUSRedeem";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await tc(r,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Uu}from"@msafe/sui3-utils";var lo=class a extends v{constructor(t){super(t);this.data=t}txType=Uu.Other;txSubType="xCETUSRedeemLock";async build(t){let{account:n,network:o}=t,{txbParams:r}=this.data;return await Xs(r,n,o)}static fromData(t){return new a(t)}};var uo=class{application="cetus";supportSDK="@mysten/sui";async deserialize(e){console.log("Cetus helper deserialize input: ",e);let{txbParams:t,action:n}=e;return{txType:qu.Other,txSubType:n,intentionData:{txbParams:{...t},action:n}}}async build(e){let{suiClient:t,account:n,network:o}=e,r;switch(e.txSubType){case"OpenAndAddLiquidity":r=jn.fromData(e.intentionData);break;case"IncreaseLiquidity":r=Xn.fromData(e.intentionData);break;case"DecreaseLiquidity":r=qn.fromData(e.intentionData);break;case"RemoveLiquidity":r=to.fromData(e.intentionData);break;case"ClaimFeeAndMining":r=Un.fromData(e.intentionData);break;case"FarmingOpenAndAddLiquidity":r=Fn.fromData(e.intentionData);break;case"FarmingIncreaseLiquidity":r=zn.fromData(e.intentionData);break;case"FarmingDecreaseLiquidity":r=$n.fromData(e.intentionData);break;case"FarmingRemoveLiquidity":r=Gn.fromData(e.intentionData);break;case"FarmingClaimFeeAndReward":r=Vn.fromData(e.intentionData);break;case"FarmingHarvest":r=Hn.fromData(e.intentionData);break;case"FarmingBatchHarvest":r=Kn.fromData(e.intentionData);break;case"FarmingStake":r=Qn.fromData(e.intentionData);break;case"FarmingUnstake":r=Jn.fromData(e.intentionData);break;case"xCETUSConvert":r=so.fromData(e.intentionData);break;case"xCETUSRedeemLock":r=lo.fromData(e.intentionData);break;case"xCETUSClaimStakingRwewards":r=io.fromData(e.intentionData);break;case"xCETUSCancelRedeem":r=ro.fromData(e.intentionData);break;case"xCETUSRedeem":r=co.fromData(e.intentionData);break;case"VestingRedeem":r=ao.fromData(e.intentionData);break;case"AggregatorSwap":r=eo.fromData(e.intentionData);break;case"AddVaultsPosition":r=no.fromData(e.intentionData);break;case"RemoveVaultsPosition":r=oo.fromData(e.intentionData);break;case"PosVestingRedeem":r=Zn.fromData(e.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:t,account:n,network:o})}};import{TransactionType as jm}from"@msafe/sui3-utils";import Fu from"sort-keys-recursive";var R=class{constructor(e){this.data=e}serialize(){return JSON.stringify(Fu(this.data))}};import{getFullnodeUrl as mo}from"@mysten/sui.js/client";var mi={};ms(mi,{contractId:()=>$u,default:()=>Ju,feeObjId:()=>Gu,roleObjId:()=>Hu,status:()=>Vu,transaction:()=>Ku,upgradeCapObjId:()=>Qu,vaultObjId:()=>zu});var Ku="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Vu="success",$u="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Hu="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",zu="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Gu="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Qu="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Ju={transaction:Ku,status:Vu,contractId:$u,roleObjId:Hu,vaultObjId:zu,feeObjId:Gu,upgradeCapObjId:Qu};var pi={};ms(pi,{contractId:()=>Zu,default:()=>am,feeObjId:()=>nm,roleObjId:()=>tm,status:()=>Yu,transaction:()=>Xu,upgradeCapObjId:()=>om,vaultObjId:()=>em});var Xu="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Yu="success",Zu="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",tm="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",em="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",nm="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",om="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",am={transaction:Xu,status:Yu,contractId:Zu,roleObjId:tm,vaultObjId:em,feeObjId:nm,upgradeCapObjId:om};var rm=mo("testnet"),im=mo("testnet"),sm=mo("mainnet"),cm=mo("mainnet"),lm="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",um="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",mm="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",pm="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",ec=mi,nc=pi,dm=new Map([["dev",{env:"dev",rpc:{url:rm},backend:{url:lm},contract:ec}],["stg",{env:"stg",rpc:{url:im},backend:{url:um},contract:ec}],["prev",{env:"prev",rpc:{url:sm},backend:{url:mm},contract:nc}],["prod",{env:"prod",rpc:{url:cm},backend:{url:pm},contract:nc}]]);function oc(a,e){let t=dm.get(a);if(!t)throw new Error(`Env not supported: ${a}`);return e&&e.rpc&&(t.rpc=e.rpc),e&&e.backend&&(t.backend=e.backend),e&&e.contract&&(t.contract=e.contract),t}import{SuiClient as hm}from"@mysten/sui.js/client";var j=class extends Error{mpayErrorCode;context;constructor(e,t,n={}){let{cause:o,context:r}=n;o?super(`[MPay] ${t}: ${o}`):super(`[MPay] ${t}`),this.mpayErrorCode=e,this.context=r}};var po=class extends j{constructor(){super(11,"Backend is not specified")}};var fo=class extends j{constructor(){super(1,"Wallet not connected")}};import we,{AxiosError as fm}from"axios";var Te=class extends j{constructor(e,t){super(10,e,{context:t})}};var ho=class a{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof fm)throw new Te(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new Te(e.data.code)}throw new Te(e.status.toString())}async getIncomingStreams(e,t){let n=await we.post(`${this.apiURL}/stream`,{recipient:e,...t});return a.parseResponseData(n)}async getOutgoingStreams(e,t){let n=await we.post(`${this.apiURL}/stream`,{sender:e,...t});return a.parseResponseData(n)}async getStreamHistory(e){let t=await we.post(`${this.apiURL}/stream-events`,e),n=a.parseResponseData(t);return n.data.forEach(o=>{let r=o;return r.data.type==="create_stream"?r.data.balance=BigInt(r.data.balance):r.data.type==="cancel_stream"?r.data.withdrawAmount=BigInt(r.data.withdrawAmount):r.data.type==="claim"||r.data.type==="auto_claim"?r.data.claimAmount=BigInt(r.data.claimAmount):r.data.type==="set_auto_claim"&&(r.data.enabled=!!r.data.enabled),r.createdAt=new Date(r.createdAt),r}),n}async getAllCoinTypes(e){let t=await we.post(`${this.apiURL}/stream-info`,{address:e});return a.parseResponseData(t)}async getAllRecipients(e,t){let n=await we.post(`${this.apiURL}/stream-info`,{sender:e,status:t});return a.parseResponseData(n)}async getAllSenders(e,t){let n=await we.post(`${this.apiURL}/stream-info`,{recipient:e,status:t});return a.parseResponseData(n)}};var Ie=class a{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new hm({url:e.rpc.url}),e.backend&&(this._backend=new ho(e.backend.url))}static new(e,t){let n=oc(e,t);return new a(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new po;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 fo;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as Wm,normalizeStructTag as _m,normalizeSuiAddress as Dc}from"@mysten/sui.js/utils";import{TransactionBlock as wo}from"@mysten/sui.js/transactions";import{TransactionBlock as pc}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as dc,normalizeStructTag as Sm}from"@mysten/sui.js/utils";var di=50n,go=10000n,ac=25n,fi=100000000n;var Qt=class{constructor(e){this.object=e}moveArg(e){return e.object(this.object)}},Le=class{constructor(e){this.objects=e}moveArgs(e){return e.makeMoveVec({objects:this.objects.map(t=>e.object(t))})}},ae=class a{constructor(e){this.result=e;return new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(t,n){if(n in t)return Reflect.get(t,n);let o=c=>new a(t.result[c]);if(n===Symbol.iterator)return function*(){let c=0;for(;;)yield o(c),c++};if(typeof n=="symbol")return;let r=parseInt(n,10);if(!(Number.isNaN(r)||r<0))return o(r)}})}moveArg(){return this.result}};import{Buffer as rc}from"buffer";import{normalizeSuiAddress as gm}from"@mysten/sui.js/utils";var je=class extends j{constructor(e,t){super(3,e,{context:t})}};var yo=class{constructor(e){this.results=e}callResult(e){return this.results.results[e]}returnValue(e,t){return e.returnValues[t]}getValue(e=0,t=0){let n=this.callResult(e);return this.returnValue(n,t)}getAddress(e=0,t=0){let[n,o]=this.getValue(e,t);if(o!=="address")throw new je("Invalid contract return type.",{ctx:{expectType:"address",gotType:o}});return gm(rc.from(n).toString("hex"))}getU64(e=0,t=0){let[n,o]=this.getValue(e,t);if(o!=="u64")throw new je("Invalid contract return type.",{ctx:{expectType:"u64",gotType:o}});return rc.from(n).readBigInt64LE()}};import{bcs as sc}from"@mysten/sui.js/bcs";var H=class extends j{constructor(e,t,n){super(2,`Invalid input: ${e}`,{context:{fieldKey:t,fieldValue:n}})}};var cc={groupId:"string",name:"string"},ym=64;function lc(a){return uc(a),sc.ser(cc,a).toString("base64")}function Ue(a){let e=sc.de(cc,a,"base64");return uc(e),e}function uc(a){if(!ic(a.name))throw new H("Invalid metadata: Name contains unknown character");if(!ic(a.groupId))throw new H("Invalid metadata: Group ID contains unknown character");if(a.name.length>ym)throw new H("Invalid metadata: Name exceed max length 64")}function ic(a){return/^[\x00-\x7F]+$/.test(a)}import{normalizeStructTag as bo}from"@mysten/sui.js/utils";function So(a,e){return bo(a)===bo(e)}function re(a,e){return bo(a)===bo(e)}var To="txn.gas";import{nanoid as bm}from"nanoid";function mc(){return bm()}var de=class a{constructor(e,t,n){this.globals=e;this.feeContract=t;this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:lc({name:e.name,groupId:mc()}),coinType:Sm(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 pc,n=this.calculateFeesInternal(e),o=this.getCreateStreamCoinRequests(e,n),r=await this.wallet.requestCoins(o),c=await this.addMergeCoins(t,r[0]),l;o.length>1?l=await this.addMergeCoins(t,r[1]):l=c;for(let d=0;d<e.recipients.length;d++){let S=e.recipients[d],w=this.amountForRecipient(S,e.numberEpoch),I=this.getStreamFeeLocal(w),[C]=t.splitCoins(c,[t.pure(w+I,"u64")]),[k]=t.splitCoins(l,[t.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(t,{paymentCoin:new ae(C),flatFeeCoin:new ae(k),metadata:e.metadata,recipient:S.address,timeStart:e.startTime,cliff:S.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:S.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return t}calculateCreateStreamFees(e){let t=a.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(t)}feeParams(){return{createFeePercent:{numerator:di,denominator:go},claimFeePercent:{numerator:ac,denominator:go},flatFeePerStream:fi}}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===To?n=e.gas:n=e.object(t.primaryCoin),n}getCreateStreamCoinRequests(e,t){let n=e.coinType;return So(n,dc)?[{coinType:n,amount:t.totalAmount+t.streamFeeAmount+t.flatFeeAmount}]:[{coinType:n,amount:t.totalAmount+t.streamFeeAmount},{coinType:dc,amount:t.flatFeeAmount}]}calculateFeesInternal(e){let t=e.recipients.reduce((o,r)=>{let c=this.amountForRecipient(r,e.numberEpoch),l=this.getStreamFeeLocal(c);return{totalAmount:o.totalAmount+c,streamFeeAmount:o.streamFeeAmount+l}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...t}}amountForRecipient(e,t){return BigInt(e.amountPerEpoch)*BigInt(t)+BigInt(e.cliffAmount)}get flatSuiFee(){return fi}getStreamFeeLocal(e){return e*di/go}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new pc,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:t});return new yo(n).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as hc}from"@mysten/sui.js/transactions";var fc="0x0000000000000000000000000000000000000000000000000000000000000006";var Ce=class{constructor(e,t,n){this.moduleName=e;this.config=t;this.globals=n}addContractCall(e,t){let n=`${this.config.contractId}::${this.moduleName}::${t.method}`;return e.add(hc.MoveCall({target:n,arguments:t.arguments.map(o=>o instanceof Le?o.moveArgs(e):o instanceof Qt?o.moveArg(e):o instanceof ae?o.moveArg():e.pure(o)),typeArguments:t.typeArgs})),e}addTransactionBlock(e,t,n=[],o=[]){e.add(hc.MoveCall({target:t,arguments:n.map(r=>r instanceof Le?r.moveArgs(e):r instanceof Qt?r.moveArg(e):r instanceof ae?r.moveArg():e.pure(r)),typeArguments:o}))}makeObject(e){return typeof e=="string"?new Qt(e):e}vaultObject(){return new Qt(this.config.vaultObjId)}roleObject(){return new Qt(this.config.roleObjId)}feeObject(){return new Qt(this.config.feeObjId)}clockObject(){return new Qt(fc)}};var ke=class a extends Ce{constructor(t,n){super(a.ModuleName,t,n);this.config=t;this.globals=n}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(t,n){let o=this.roleObject(),r=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_streaming_fee,arguments:[o,r,n],typeArgs:[]})}setStreamingFlatFee(t,n){let o=this.roleObject(),r=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_streaming_flat_fee,arguments:[o,r,n],typeArgs:[]})}setClaimFee(t,n){let o=this.roleObject(),r=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_claim_fee,arguments:[o,r,n],typeArgs:[]})}streamingFee(t,n){let o=this.feeObject();return this.addContractCall(t,{method:a.MethodName.streaming_fee,arguments:[o,n],typeArgs:[]})}claimFee(t,n){return this.addContractCall(t,{method:a.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(t){return this.addContractCall(t,{method:a.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var Jt=class a extends Ce{constructor(t,n){super(a.ModuleName,t,n);this.config=t;this.globals=n}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(t,n){let o=this.feeObject(),r=this.vaultObject(),c=this.makeObject(n.paymentCoin),l=this.makeObject(n.flatFeeCoin),d=this.clockObject();return this.addContractCall(t,{method:a.MethodName.create_stream,arguments:[o,r,c,l,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,d],typeArgs:[n.coinType]})}setAutoClaim(t,n){let o=this.makeObject(n.streamId);return this.addContractCall(t,{method:a.MethodName.set_auto_claim,arguments:[o,n.enabled],typeArgs:[n.coinType]})}cancelStream(t,n){let o=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(t,{method:a.MethodName.cancel_stream,arguments:[o,r],typeArgs:[n.coinType]})}claimStream(t,n){let o=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(t,{method:a.MethodName.claim_stream,arguments:[o,r],typeArgs:[n.coinType]})}claimStreamByProxy(t,n){let o=this.makeObject(n.streamId),r=this.vaultObject(),c=this.feeObject(),l=this.clockObject();return this.addContractCall(t,{method:a.MethodName.claim_stream_by_proxy,arguments:[o,r,c,l],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream_by_proxy}`}};var ve=class{constructor(e){this.globals=e;let t=e.envConfig.contract;this.feeContract=new ke(t,e),this.streamContract=new Jt(t,e)}feeContract;streamContract;async createStreams(e){let t=de.convertCreateStreamInfoToInternal(e);return this.createStreamHelper().buildCreateStreamTransactionBlock(t)}createStreamHelper(){return new de(this.globals,this.feeContract,this.streamContract)}setAutoClaim(e,t,n){let o=new wo;return this.streamContract.setAutoClaim(o,{streamId:e,enabled:t,coinType:n})}claimStream(e,t){let n=new wo;return this.streamContract.claimStream(n,{streamId:e,coinType:t})}claimStreamByProxy(e,t){let n=new wo;return this.streamContract.claimStreamByProxy(n,{streamId:e,coinType:t})}cancelStream(e,t){let n=new wo;return this.streamContract.cancelStream(n,{streamId:e,coinType:t}),n}};import{normalizeStructTag as hi,SUI_TYPE_ARG as Tm}from"@mysten/sui.js/utils";import{Duration as gc}from"luxon";var Io=class extends j{constructor(e,t){super(12,`Transaction failed: ${t}`,{context:{status:e,msg:t}})}};var wm=1e3,Co=class{constructor(e){this.globals=e;this.coinMetaHelper=new gi(e.suiClient),this.createStreamHelper=new ve(e).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(e){if(e.effects?.status.status!=="success")throw new Io(e.effects?.status.status,e.effects?.status.error);return e.objectChanges.filter(t=>t.type==="created"&&t.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(t=>t.objectId)}calculateCreateStreamFees(e){return this.createStreamHelper.calculateCreateStreamFees(e)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=e.cliff?e.cliff:{numerator:0n,denominator:100n},n=e.totalAmount*t.numerator/t.denominator,o=(e.totalAmount-n)/e.steps,c={realTotalAmount:o*e.steps+n,cliffAmount:n,amountPerStep:o};return this.validateStreamAmount(c,e.totalAmount),c}calculateTimelineByInterval(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=e.timeStart.plus(e.interval.toMillis()*Number(e.steps)),n={timeStart:e.timeStart,timeEnd:t,interval:e.interval,steps:e.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=BigInt(e.total.toMillis())/e.steps,n=e.timeStart.plus(gc.fromMillis(Number(t*e.steps))),o={timeStart:e.timeStart,timeEnd:n,interval:gc.fromMillis(Number(t)),steps:e.steps};return this.validateTimeline(o),o}async getBalance(e,t){let n=await this.globals.suiClient.getBalance({owner:e,coinType:t}),o=await this.getCoinMeta(t);return{...n,coinType:hi(n.coinType),coinMeta:o}}async getAllBalance(e){let t=await this.globals.suiClient.getAllBalances({owner:e}),n=await Promise.all(t.map(o=>this.getCoinMeta(o.coinType)));return t.map((o,r)=>({...o,coinType:hi(o.coinType),coinMeta:n[r]}))}async getCoinMeta(e){return this.coinMetaHelper.getCoinMeta(e)}async simulateTransactionBlock(e){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:e,sender:await this.globals.wallet.address()})}validateStreamAmount(e,t){if(e.amountPerStep===0n)throw new H("Stream amount too small","totalAmount",t);if(e.cliffAmount>e.realTotalAmount)throw new H("Invalid cliff settings")}validateTimeline(e){if(e.interval.toMillis()<wm)throw new H("Interval shall be at least 1 second","interval",e.interval)}},gi=class{constructor(e){this.suiClient=e;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(e){let t=hi(e||Tm);if(this.coinMetaReg.has(t))return this.coinMetaReg.get(t);let n=await this.queryCoinMeta(t);return n&&this.coinMetaReg.set(t,n),n}async queryCoinMeta(e){return await this.suiClient.getCoinMetadata({coinType:e})||void 0}};import{normalizeStructTag as Sc,normalizeSuiAddress as Oo}from"@mysten/sui.js/utils";import{DateTime as Tc}from"luxon";import{TransactionBlock as Do}from"@mysten/sui.js/transactions";import{normalizeStructTag as bc,parseStructTag as km}from"@mysten/sui.js/utils";import{DateTime as vm}from"luxon";var ko=class extends j{constructor(){super(7,"Connected wallet is not creator")}};var qe=class extends j{constructor(){super(8,"Connected wallet is not recipient")}};var Fe=class extends j{constructor(e,t){super(6,e,{context:t})}};var At=class extends j{constructor(e,t={}){super(0,e,t)}};var vo=class extends j{constructor(e){super(5,"Stream not found",{context:{streamId:e}})}};import{DateTime as Im,Duration as Cm}from"luxon";var yc=(1n<<64n)-1n,xo=1e3;function yi(a){let e;typeof a=="number"?e=a:typeof a=="bigint"?e=Number(a):e=a.toMillis();let t=Math.round(e/xo);return Im.fromMillis(t*xo)}function bi(a){let e;typeof a=="number"?e=a:typeof a=="bigint"?e=Number(a):e=a.toMillis();let t=Math.round(e/xo);return Cm.fromMillis(t*xo)}var ie=class a{constructor(e,t,n){this.globals=e;this.streamId=t;this.rawData=n;this.streamContract=new Jt(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,t){let n=await a.fetchStreamData(e,t);return new a(e,t,n)}static fromObjectData(e,t,n){let o=a.parseRawStreamData(t,n);return new a(e,t,o)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await a.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new At("Object Id does not align");this.rawData=a.parseRawStreamData(this.streamId,e)}async historyEvents(e){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:e})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new ko;let e=new Do;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new qe;let e=new Do;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new qe;let t=new Do;return this.streamContract.setAutoClaim(t,{streamId:this.streamId,coinType:this.coinType,enabled:e}),t}async claimByProxy(){let e=new Do;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 bc(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 bi(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Ue(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Ue(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return yi(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return bi(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:yi((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===yc?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=vm.now().toMillis(),t=this.timeStart.toMillis();if(e<t)return-1n;let n=Math.floor((e-t)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,t){let n=await e.suiClient.getObject({id:t,options:{showContent:!0,showType:!0}});return a.parseRawStreamData(t,n)}static parseRawStreamData(e,t){if(t.error)throw t.error.code==="notExists"?new vo(e):new Fe(`get stream data: ${t.error.code}`,{streamId:e,...t.error});let n=t.data.content;if(n.dataType!=="moveObject")throw new Fe("Unexpected object type",{gotType:n.dataType});let{typeParams:o}=km(n.type),r=bc(o[0]),c=n.fields,l=c.config.fields,d=c.status.fields;return{coinType:r,autoClaim:c.auto_claim,balance:BigInt(c.balance.fields.balance),config:{amountPerEpoch:BigInt(l.amount_per_epoch),cancelable:l.cancelable,cliff:BigInt(l.cliff),creator:l.creator,epochInterval:BigInt(l.epoch_interval),metadata:l.metadata,recipient:l.recipient,timeStart:BigInt(l.time_start),totalEpoch:BigInt(l.total_epoch)},status:{status:d.status,epochCanceled:BigInt(d.epoch_canceled),epochClaimed:BigInt(d.epoch_claimed)}}}};var xe=class extends j{constructor(e,t){super(9,`Invalid stream group: ${e}`,{context:t})}};async function Ti(a){let e=[];for(;await a.hasNext();){let t=await a.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var Si=class{constructor(e){this.requester=e;this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},De=class{constructor(e){this.requester=e;this.pager=new Si(e),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}};var xm=25;async function Ii(a,e,t){let n=new Ke(e),o=new Ve(a,n,t);return await Ti(o)}var Ke=class{constructor(e){this.ids=e;this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},Ve=class extends De{constructor(t,n,o){super(new wi(t,n,o));this.suiClient=t;this.idIter=n;this.options=o}},wi=class{constructor(e,t,n){this.suiClient=e;this.stringIter=t;this.options=n;this.filter=n?.filter,this.pageSize=n?.pageSize||xm,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let e=[];for(;e.length<this.pageSize&&await this.stringIter.hasNext();){let r=await this.stringIter.next();r&&e.push(r)}let t=await this.suiClient.multiGetObjects({ids:e,options:this.objectOptions}),n;if(this.filter){let{filter:o}=this;n=t.filter(r=>o?.(r))}else n=t;return{data:n,hasNext:await this.stringIter.hasNext()}}};var Ao=class a{constructor(e,t){this.globals=e;this.streams=t;if(t.length===0)throw new xe("stream size 0");let n=t.map(r=>r.groupId);if(new Set(n).size!==1)throw new H("Stream does not have same group ID")}type="StreamGroup";static async new(e,t){let n=await Ii(e.suiClient,t);return n.forEach(o=>{if(!o)throw new At("stream group object data undefined")}),a.newFromObjectResponse(e,t,n)}static async newFromObjectResponse(e,t,n){let o=await a.parseGroupStreams(e,t,n);return new a(e,o)}static checkStreamGroup(e){let t=e.map(r=>r.groupCommonInfo),n=t[0],o=!0;return t.forEach(r=>{Dm(n,r)||(o=!1)}),o}async refresh(){let e=await Ii(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((r,c)=>ie.fromObjectData(e,t[c],r)).filter(r=>!!r);if(new Set(o.map(r=>r.groupId)).size!==1)throw new xe("Not same group ID");if(!this.checkStreamGroup(o))throw new xe("Not same stream settings");return o}};function Dm(a,e){return a.name===e.name&&a.groupId===e.groupId&&a.creator===e.creator&&a.start.toMillis()===e.start.toMillis()&&a.interval.toMillis()===e.interval.toMillis()&&a.steps===e.steps&&a.cancelable===e.cancelable}var $e=class a{constructor(e,t){this.it=e;this.pageSize=t}static async newIncoming(e){let t=await Mo.newIncoming(e);return new a(t,e.pageSize)}static async newOutgoing(e){let t=await Mo.newOutgoing(e);return new a(t,e.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let e=[];for(;e.length<this.pageSize&&await this.it.hasNext();)e.push(await this.it.next());return e}},Mo=class a{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let t=await Po.newIncomingQuery(e);return new a(t)}static async newOutgoing(e){let t=await Po.newOutgoingQuery(e);return new a(t)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let t=await this.requester.doNextRequest();if(t===null)throw new At("No more results");return t}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new At("No more results");return e}},Po=class a{constructor(e,t,n,o){this.globals=e;this.recipient=t;this.groupRefs=n;this.query=o;this.current=0;let r=new Ke(n.flat().map(c=>c.streamId));this.objectIter=new Ve(e.suiClient,r)}current=0;objectIter;static async newIncomingQuery(e){let t=Rm(e.query),n=await e.globals.walletAddress(),r=(await e.globals.backend.getIncomingStreams(n,t)).filter(l=>Oo(l.recipient)===Oo(n)),c=wc(r);return new a(e.globals,n,c,e.query)}static async newOutgoingQuery(e){let t=Bm(e.query),n=await e.globals.walletAddress(),o=await e.globals.backend.getOutgoingStreams(n,t),r=wc(o);return new a(e.globals,n,r,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 Mm(this.globals,e[0].streamId,this.objectIter);return this.current++,Ic(t,this.query)?t:this.doNextRequest()}if(e.length>1){let t=await Pm(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,Om(t,this.query)?t:this.doNextRequest()}throw new At("Stream group with no stream")}};function wc(a){let e=new Map;return a.forEach(t=>{let n=e.get(t.groupId);n?(n.push(t),e.set(t.groupId,n)):e.set(t.groupId,[t])}),Array.from(e.values()).sort((t,n)=>Tc.fromISO(n[0].createDate).toMillis()-Tc.fromISO(t[0].createDate).toMillis())}function Ic(a,e){if(e===void 0)return!0;let t=Am(a,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?a.progress.claimable!==0n:a.progress.claimable===0n;return t&&n}return t}function Am(a,e){return e===void 0?!0:Array.isArray(e)?e.includes(a.progress.status):a.progress.status===e}function Om(a,e){if(!e)return!0;let t=!1;return a.streams.forEach(n=>{Ic(n,e)&&(t=!0)}),t}async function Mm(a,e,t){let n=await Cc(t,e);return ie.fromObjectData(a,e,n)}async function Pm(a,e,t){let n=[];for(;n.length<e.length;){let o=await Cc(t,e[n.length]);n.push(o)}return Ao.newFromObjectResponse(a,e,n)}async function Cc(a,e){if(!await a.hasNext())throw new At("object iterator has been consumed");let t=await a.next();if(!t||t.error||t.data===void 0||t.data===null)throw new At("object iterator undefined response",{cause:t?.error});if(t?.data?.objectId!==e)throw new At("stream id not aligned");return t}function Rm(a){return{status:Ci(a?.status),coinType:kc(a?.coinType),sender:vc(a?.sender)}}function Bm(a){return{status:Ci(a?.status),coinType:kc(a?.coinType),recipient:vc(a?.recipient)}}function Ci(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((e,t)=>{let n=Ci(t);return!e||e===n?n:"all"},void 0):Em(a)}function Em(a){switch(a){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new H("Unknown stream filtered status")}}function kc(a){if(a)return Array.isArray(a)?a.length!==0?a.map(e=>Sc(e)):void 0:Sc(a)}function vc(a){if(a)return Array.isArray(a)?a.length!==0?a.map(e=>Oo(e)):void 0:Oo(a)}var Ro=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}};var Nm=25;async function xc(a,e,t,n="0x2::sui::SUI",o=Nm){let r=new ki(a,e,n,o),c=BigInt(0),l=[];for(;await r.hasNext()&&c<t;){let d=await r.next();d&&(l.push(d),c+=BigInt(d.balance))}if(c<t)throw new Ro(n,t,c);return l}var ki=class extends De{constructor(t,n,o,r){super(new vi(t,n,o,r));this.suiClient=t;this.owner=n;this.coinType=o;this.reqPageSize=r}},vi=class{constructor(e,t,n,o){this.suiClient=e;this.owner=t;this.coinType=n;this.reqPageSize=o;if(o<=0)throw new At("Invalid reqPageSize")}nextCursor;async doNextRequest(){let e=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=e.nextCursor,{data:e.data,hasNext:e.hasNextPage}}};var xi=class{constructor(e){this.msafe=e}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(e){return this.msafe.requestCoins(e)}},Bo=class{constructor(e){this.account=e}async address(){return this.account.address}},Di=class{constructor(e,t){this.singleWallet=e;this.suiClient=t}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(e){return Promise.all(e.map(t=>this.requestCoin(t)))}async requestCoin(e){if(So(e.coinType,Wm))return{primaryCoin:To};if(e.amount<=0)throw new H("Invalid coin request","coinAmount",e.amount);let t=await xc(this.suiClient,await this.address(),e.amount,e.coinType);if(t.length===0)throw new At("no coins available");return{primaryCoin:t[0].coinObjectId,mergedCoins:t.slice(1).map(n=>n.coinObjectId)}}},Eo=class{globals;helper;constructor(e,t){this.globals=Ie.new(e,t),this.helper=new Co(this.globals)}connectSingleWallet(e){let t=new Di(e,this.globals.suiClient);this.globals.connectWallet(t)}connectMSafeAccount(e){let t=new xi(e);this.globals.connectWallet(t)}async createStream(e){return this.builder().createStreams(e)}async getStream(e){return ie.new(this.globals,e)}async getIncomingStreams(e,t=10){return $e.newIncoming({globals:this.globals,query:e,pageSize:t})}async getOutgoingStreams(e,t=10){return $e.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=>_m(n))}async getRecipientsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllRecipients(t,e)).map(o=>Dc(o))}async getCreatorsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllSenders(t,e)).map(o=>Dc(o))}get wallet(){return this.globals.wallet}builder(){return new ve(this.globals)}};var qt=class extends R{application="mpay";getClient(e,t){let n=new Eo(e==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new Bo(t)),n}};var He=class extends qt{constructor(t){super(t);this.data=t}txType=jm.Stream;txSubType="Cancel";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).cancel()}};import{TransactionType as Um}from"@msafe/sui3-utils";var ze=class extends qt{constructor(t){super(t);this.data=t}txType=Um.Stream;txSubType="ClaimByProxy";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).claimByProxy()}};import{TransactionType as qm}from"@msafe/sui3-utils";var Ge=class extends qt{constructor(t){super(t);this.data=t}txType=qm.Stream;txSubType="Claim";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).claim()}};import{TransactionType as Fm}from"@msafe/sui3-utils";var Qe=class extends qt{constructor(t){super(t);this.data=t}txType=Fm.Stream;txSubType="CreateStream";async build(t){let{network:n,account:o}=t;return this.getClient(n,o).createStream(this.data)}};import{bcs as Ac}from"@mysten/sui.js/bcs";import{normalizeStructTag as Km,normalizeSuiAddress as Je}from"@mysten/sui.js/utils";var Ae=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return BigInt(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return Je(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Ac.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return Je(e.value.Object.ImmOrOwned.objectId)}return Je(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return Je(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return Je(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Ac.de(t,new Uint8Array(n))}typeArg(e){return Km(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};var No=class{constructor(e,t){this.globals=e;this.txb=t}decode(){let e=this.decodeCreateStreamInfo(),t=this.createStreamHelper().calculateCreateStreamFees(e);return{type:"CreateStream",info:e,fees:t}}decodeCreateStreamInfo(){let t=this.createStreamTransactions().map(n=>this.getCreationInfoFromMoveCall(n));return this.aggregateGroupStreamInfo(t)}createStreamTransactions(){let e=this.transactions.filter(t=>t.kind==="MoveCall"&&re(t.target,this.contract.createStreamTarget));if(e.length===0)throw new At("No create stream transactions");return e.map(t=>new Ae(t,this.txb))}getCreationInfoFromMoveCall(e){let t=e.decodeInputString(4),{name:n,groupId:o}=Ue(t),r=e.decodeInputAddress(5),c=e.decodeInputU64(6),l=e.decodeInputU64(7),d=e.decodeInputU64(8),S=e.decodeInputU64(9),w=e.decodeInputU64(10),I=e.decodeInputBool(11),C=e.typeArg(0);return{name:n,groupId:o,recipient:r,timeStart:c,cliff:l,epochInterval:d,totalEpoch:S,amountPerEpoch:w,cancelable:I,coinType:C}}aggregateGroupStreamInfo(e){if(new Set(e.map(o=>JSON.stringify({name:o.name,groupId:o.groupId,timeStart:String(o.timeStart),epochInterval:String(o.epochInterval),totalEpoch:String(o.totalEpoch),cancelable:o.cancelable,coinType:o.coinType}))).size!==1)throw new H("Stream group not have common info");let n=e.map(o=>({address:o.recipient,amountPerStep:o.amountPerEpoch,cliffAmount:o.cliff}));return{name:e[0].name,coinType:e[0].coinType,recipients:n,interval:e[0].epochInterval,steps:e[0].totalEpoch,startTimeMs:e[0].timeStart,cancelable:e[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(e=>e.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new Jt(this.globals.envConfig.contract,this.globals)}get feeContract(){return new ke(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new de(this.globals,this.feeContract,this.contract)}getInputArg(e){if(e.kind!=="Input")throw new Error("not input type");return"value"in e?e:this.txb.blockData.inputs[e.index]}};var Wo=class{constructor(e,t){this.globals=e;this.txb=t;this.contract=new Jt(e.envConfig.contract,e)}contract;decode(){if(this.isCreateStreamTransaction())return this.decodeCreateStreamTransaction();if(this.isClaimByProxyTransaction())return this.decodeClaimByProxyTransaction();if(this.isSetAutoClaimTransaction())return this.decodeSetAutoClaimTransaction();if(this.isCancelStreamTransaction())return this.decodeCancelStreamTransaction();if(this.isClaimStreamTransaction())return this.decodeClaimTransaction();throw new Error("Unknown stream transaction type")}get transactions(){return this.txb.blockData.transactions}isCreateStreamTransaction(){return this.transactions.findIndex(t=>t.kind==="MoveCall"&&re(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&re(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&re(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&re(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&re(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new No(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:e,enabled:t}}decodeClaimTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"Claim",streamId:e}}decodeClaimByProxyTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"ClaimByProxy",streamId:e}}decodeCancelStreamTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"Cancel",streamId:e}}get helper(){let e=this.transactions[0];return new Ae(e,this.txb)}};import{TransactionType as Vm}from"@msafe/sui3-utils";var Xe=class extends qt{constructor(t){super(t);this.data=t}txType=Vm.Stream;txSubType="SetAutoClaim";async build(t){let{network:n,account:o}=t;return(await this.getClient(n,o).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var _o=class{application="mpay";supportSDK="@mysten/sui.js";async deserialize(e){let{network:t,transactionBlock:n}=e,o=Ie.new(t==="sui:mainnet"?"prod":"dev"),c=new Wo(o,n).decode(),l;switch(c.type){case"CreateStream":l=new Qe(c.info);break;case"SetAutoClaim":l=new Xe({streamId:c.streamId,enabled:c.enabled});break;case"Claim":l=new Ge({streamId:c.streamId});break;case"ClaimByProxy":l=new ze({streamId:c.streamId});break;case"Cancel":l=new He({streamId:c.streamId});break;default:throw new Error(`Unknown transaction type: ${c}`)}return{txType:l.txType,txSubType:l.txSubType,intentionData:l.data}}async build(e){let{intentionData:t}=e,n;switch(e.txSubType){case"CreateStream":n=new Qe(t);break;case"Claim":n=new Ge(t);break;case"ClaimByProxy":n=new ze(t);break;case"SetAutoClaim":n=new Xe(t);break;case"Cancel":n=new He(t);break;default:throw new Error("not implemented")}return n.build({...e})}};import{TransactionDefaultApplication as zm,TransactionSubTypes as Oc}from"@msafe/sui3-utils";import{buildCoinTransferTxb as $m}from"@msafe/sui3-utils";var Lo=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t;return $m(n,this.data,o.address)}static fromData(t){return new a(t)}};import{buildObjectTransferTxb as Hm}from"@msafe/sui3-utils";var jo=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t;return Hm(n,this.data,o.address)}static fromData(t){return new a(t)}};var Uo=class{application="msafe-core";supportSDK="@mysten/sui.js";constructor(){this.application=zm}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(e){let{suiClient:t,account:n}=e,o;switch(e.txSubType){case Oc.assets.coin.send:o=Lo.fromData(e.intentionData);break;case Oc.assets.object.send:o=jo.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};import{TransactionType as cp}from"@msafe/sui3-utils";var Mc=!1,Ye={ProtocolPackage:"0x81c408448d0d57b3e371ea94de1d40bf852784d3e225de1e74acab3e8395c18f",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",gasBudget:5e7,PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},wusdc:{name:"wUSDC",assetId:1,coinType:"wusdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"},wbtc:{name:"WBTC",coinType:"wbtc",assetId:8,poolId:"0xd162cbe40f8829ce71c9b3d3bf3a83859689a79fa220b23d70dc0300b777ae6e",type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",reserveObjectId:"0x8b4d81f004e4e9faf4540951a896b6d96e42598a270e6375f598b99742db767e",borrowBalanceParentId:"0x55e1f3c9e6e5cf9fff563bdd61db07a3826458c56ef72c455e049ab3b1b0e99c",supplyBalanceParentId:"0x821e505a0091b089edba94deaa14c2f2230d026bbaa7b85680554441aad447e0"},ausd:{name:"AUSD",coinType:"ausd",assetId:9,poolId:"0xc9208c1e75f990b2c814fa3a45f1bf0e85bb78404cfdb2ae6bb97de58bb30932",type:"0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD",reserveObjectId:"0x918889c6a9d9b93108531d4d59a4ebb9cc4d41689798ffc1d4aed6e1ae816ec0",borrowBalanceParentId:"0x551300b9441c9a3a16ca1d7972c1dbb4715e15004ccd5f001b2c2eee22fd92c1",supplyBalanceParentId:"0xe151af690355de8be1c0281fbd0d483c099ea51920a57c4bf8c9666fd36808fd"},nusdc:{name:"USDC",assetId:10,coinType:"nusdc",poolId:"0xa3582097b4c57630046c0c49a88bfc6b202a3ec0a9db5597c31765f7563755a8",type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",reserveObjectId:"0x4c8a2c72a22ae8da803a8519798d312c86e74a9e0d6ec0eec2bfcf7e4b3fef5e",borrowBalanceParentId:"0xb0b0c7470e96cabbb4f1e8d06bef2fbea65f4dbac52afae8635d9286b1ea9a09",supplyBalanceParentId:"0x08b5ce8574ac3bc9327e66ad5decd34d07ee798f724ad01058e8855ac9acb605"},eth:{name:"ETH",assetId:11,coinType:"eth",poolId:"0x78ba01c21d8301be15690d3c30dc9f111871e38cfb0b2dd4b70cc6052fba41bb",type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",reserveObjectId:"0x376faea6dfbffab9ea808474cb751d91222b6d664f38c0f1d23de442a8edb1ce",borrowBalanceParentId:"0xf0c6ce5cfaee96073876a5fab7426043f3a798b79502c4caeb6d9772cd35af1f",supplyBalanceParentId:"0xc0a0cb43620eb8a84d5a4a50a85650e7fa7ba81e660f9cc2863404fd84591d4b"},usdy:{name:"USDY",assetId:12,coinType:"usdy",poolId:"0x4b6253a9f8cf7f5d31e6d04aed4046b9e325a1681d34e0eff11a8441525d4563",type:"0x960b531667636f39e85867775f52f6b1f220a058c4de786905bdf761e06a56bb::usdy::USDY",reserveObjectId:"",borrowBalanceParentId:"",supplyBalanceParentId:""}},borrowFee:.003,borrowFeeAddress:"0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2"};async function Ai(){if(!Mc)try{let a=await fetch("https://open-api.naviprotocol.io/api/msafe").then(r=>r.json()),{packageId:e,borrowFee:t,borrowFeeAddress:n,pool:o}=a;e&&(Ye.ProtocolPackage=e),t&&(Ye.borrowFee=t),n&&(Ye.borrowFeeAddress=n),o&&(Ye.pool=o),Mc=!0}catch(a){console.error(a.message)}}var $t=Ye;import{TransactionType as he}from"@msafe/sui3-utils";import{bcs as Pc}from"@mysten/sui.js/bcs";import{normalizeStructTag as Qm,normalizeSuiAddress as Ze}from"@mysten/sui.js/utils";var qo=class{constructor(e){this.txb=e}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryBorrowWithFeeTransaction())return this.decodeEntryBorrow();if(this.isEntryMultiDepositTransaction())return this.decodeEntryMultiDeposit();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();if(this.isEntryClaimAndDepositTransaction())return this.decodeEntryClaimAndDeposit();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}isClaimRewardTransaction(){return!!this.transactions.find(t=>!!(t.kind==="MoveCall"&&t.target.includes("claim_reward")))}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::entry_borrow`)}isEntryBorrowWithFeeTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::borrow`)}isEntryMultiDepositTransaction(){let e=`${$t.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.transactions.filter(o=>o.kind==="MoveCall"&&o.target===e);return this.transactions.find(o=>o.kind==="MoveCall"&&o.target.includes("claim_reward"))?!1:t.length>1}isEntryClaimAndDepositTransaction(){let e=`${$t.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.transactions.filter(o=>o.kind==="MoveCall"&&o.target===e);return!!(this.transactions.find(o=>o.kind==="MoveCall"&&o.target.includes("claim_reward"))&&t.length>0)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::withdraw`)}findPoolByAssetId(e){let t=Object.values($t.pool).find(n=>n.assetId===e);if(!t)throw new Error("Pool not found");return t}decodeEntryClaimAndDeposit(){return{txType:he.Other,type:"EntryClaimAndDeposit",intentionData:{type:"entry_claim_and_deposit"}}}decodeClaimReward(){return console.log("decode claims"),{txType:he.Other,type:"ClaimReward",intentionData:{type:"claim_reward"}}}decodeEntryBorrow(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:he.Other,type:"EntryBorrow",intentionData:{amount:t,assetId:e}}}decodeEntryMultiDeposit(){let e=[],t=`${$t.ProtocolPackage}::incentive_v3::entry_deposit`;return this.transactions.forEach(n=>{if(n.kind==="MoveCall"&&n.target===t){let o=new Fo(n,this.txb),r=o.decodeInputU8(3),c=o.decodeInputU64(5);e.push({assetId:r,amount:c})}}),{txType:he.Other,type:"EntryMultiDeposit",intentionData:{list:e}}}decodeEntryDeposit(){let e=this.helper.decodeInputU8(3),t=this.helper.decodeInputU64(5);return{txType:he.Other,type:"EntryDeposit",intentionData:{amount:t,assetId:e}}}decodeEntryRepay(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(6);return{txType:he.Other,type:"EntryRepay",intentionData:{amount:t,assetId:e}}}decodeEntryWithdraw(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:he.Other,type:"EntryWithdraw",intentionData:{amount:t,assetId:e}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target.startsWith($t.ProtocolPackage));return new Fo(e,this.txb)}},Fo=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return Ze(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Pc.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return Ze(e.value.Object.ImmOrOwned.objectId)}return Ze(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return Ze(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return Ze(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Pc.de(t,new Uint8Array(n))}typeArg(e){return Qm(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};import{depositCoin as Jm,withdrawCoin as Xm,repayDebt as Ym,borrowCoin as Zm,claimAllRewardsPTB as tp,claimAllRewardsResupplyPTB as ep}from"navi-sdk";async function Oe(a,e,t,n){return await Jm(a,e,t,n),a}async function Rc(a,e,t,n){let[o]=await Xm(a,e,t);return a.transferObjects([o],a.pure(n)),a}async function Bc(a,e,t,n){let[o]=await Zm(a,e,t);return a.transferObjects([o],a.pure.address(n)),a}async function Oi(a,e,t,n){return await Ym(a,e,t,n),a}async function Ec(a,e){return await tp(a,e)}async function Nc(a,e){return await ep(a,e)}var Ko=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward",n),await Ec(t.suiClient,t.account.address)}static fromData(t){return new a(t)}};var Vo=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{type:n}=this.data;return console.log("claim reward and supply",n),await Nc(t.suiClient,t.account.address)}static fromData(t){return new a(t)}};import{TransactionBlock as op}from"@mysten/sui.js/transactions";import{pool as np}from"navi-sdk";function Xt(a){return Object.values(np).find(e=>String(e.assetId)===String(a))}var $o=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{assetId:n,amount:o}=this.data,r=new op;console.log("build",this.data);let c=Xt(n);return await Bc(r,c,o,t.account.address)}static fromData(t){return new a(t)}};import{TransactionBlock as ap}from"@mysten/sui.js/transactions";async function Me(a,e,t){let n=await a.getCoins({owner:e,coinType:t});return console.log("getTokenObjs",e,n),n}var Ho=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{assetId:r,amount:c}=this.data,l=new ap;console.log("build",this.data);let d=Xt(r);if(r===0){let[C]=l.splitCoins(l.gas,[c]);return await Oe(l,d,C,c)}let S=await Me(n,o.address,d.type);if(!S.data[0])throw new Error(`Insufficient balance for ${d.name} Token`);let w=S.data[0].coinObjectId;if(S.data.length>=2){let C=1;for(;C<S.data.length;)l.mergeCoins(w,[S.data[C].coinObjectId]),C++}return await Oe(l,d,l.object(w),c)}static fromData(t){return new a(t)}};import{TransactionBlock as rp}from"@mysten/sui.js/transactions";var zo=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{assetId:r,amount:c}=this.data,l=new rp;console.log("build",this.data);let d=Xt(r);if(r===0){let[I]=l.splitCoins(l.gas,[c]);return Oi(l,d,I,c)}let S=await Me(n,o.address,d.type);if(!S.data[0])throw new Error(`Insufficient balance for ${d.name} Token`);let w=S.data[0].coinObjectId;if(S.data.length>=2){let I=1;for(;I<S.data.length;)l.mergeCoins(w,[S.data[I].coinObjectId]),I++}return Oi(l,d,l.object(w),c)}static fromData(t){return new a(t)}};import{TransactionBlock as ip}from"@mysten/sui.js/transactions";var Go=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{assetId:n,amount:o}=this.data,r=new ip;console.log("build",this.data);let c=Xt(n);return await Rc(r,c,o,t.account.address)}static fromData(t){return new a(t)}};import{TransactionBlock as sp}from"@mysten/sui.js/transactions";var Qo=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o}=t,{list:r}=this.data,c=new sp;console.log("build",this.data);for(let l=0;l<r.length;l++){let{assetId:d,amount:S}=r[l],w=Xt(d);if(d===0){let[k]=c.splitCoins(c.gas,[S]);await Oe(c,w,k,S);continue}let I=await Me(n,o.address,w.type);if(!I.data[0])throw new Error(`Insufficient balance for ${w.name} Token`);let C=I.data[0].coinObjectId;if(I.data.length>=2){let k=1;for(;k<I.data.length;)c.mergeCoins(C,[I.data[k].coinObjectId]),k++}await Oe(c,w,c.object(C),S)}return c}static fromData(t){return new a(t)}};var Jo=class{application="navi";supportSDK="@mysten/sui.js";async deserialize(e){await Ai();let{transactionBlock:t}=e,o=new qo(t).decode();return{txType:cp.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n}=e,o;switch(await Ai(),e.txSubType){case"EntryDeposit":o=Ho.fromData(e.intentionData);break;case"EntryBorrow":o=$o.fromData(e.intentionData);break;case"EntryRepay":o=zo.fromData(e.intentionData);break;case"EntryWithdraw":o=Go.fromData(e.intentionData);break;case"EntryMultiDeposit":o=Qo.fromData(e.intentionData);break;case"ClaimReward":o=Ko.fromData(e.intentionData);break;case"EntryClaimAndDeposit":o=Vo.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};import{TransactionSubTypes as lp,TransactionType as Wc}from"@msafe/sui3-utils";import{fromHex as up}from"@mysten/bcs";import{Transaction as mp}from"@mysten/sui/transactions";import pp from"sort-keys-recursive";var _c="msafe-plain-tx",Lc=lp.others.plain,Mi=class a{constructor(e){this.data=e}application=_c;txType=Wc.Other;txSubType=Lc;serialize(){return JSON.stringify(pp(this.data))}async build(e){return mp.from(up(this.data.content))}static fromData(e){return new a(e)}},Xo=class{application;supportSDK="@mysten/sui";constructor(){this.application=_c}async deserialize(e){let{content:t}=e.appContext;return{txType:Wc.Other,txSubType:Lc,intentionData:{content:t}}}async build(e){let{suiClient:t,network:n,account:o}=e;return Mi.fromData(e.intentionData).build({suiClient:t,network:n,account:o})}};import{SuiClient as jc}from"@mysten/sui/client";import{Transaction as Sp}from"@mysten/sui/transactions";import{SuiClient as Bi}from"@mysten/sui.js/client";import{TransactionBlock as Tp}from"@mysten/sui.js/transactions";import{RequestManager as gp,HTTPTransport as yp,Client as bp}from"@open-rpc/client-js";var dp={"-32700":"ParseError","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError"},Pi=class extends Error{},Yo=class extends Pi{code;type;constructor(e,t){super(e),this.code=t,this.type=dp[t]??"ServerError"}};function fp(a){let e=new URL(a);return e.protocol=e.protocol.replace("http","ws"),e.toString()}var hp={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5},Zo=class{endpoint;options;#n=0;#a=0;#t=null;#e=null;#r=new Set;#o=new Map;constructor(e,t={}){this.endpoint=e,this.options={...hp,...t},this.endpoint&&this.endpoint.startsWith("http")&&(this.endpoint=fp(this.endpoint))}async makeRequest(e,t){let n=await this.#i();return new Promise((o,r)=>{this.#n+=1,this.#o.set(this.#n,{resolve:o,reject:r,timeout:setTimeout(()=>{this.#o.delete(this.#n),r(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n.send(JSON.stringify({jsonrpc:"2.0",id:this.#n,method:e,params:t}))}).then(({error:o,result:r})=>{if(o)throw new Yo(o.message,o.code);return r})}#i(){return this.#e?this.#e:(this.#e=new Promise(e=>{this.#t?.close(),this.#t=new this.options.WebSocketConstructor(this.endpoint),this.#t.addEventListener("open",()=>{this.#a=0,e(this.#t)}),this.#t.addEventListener("close",()=>{this.#a++,this.#a<=this.options.maxReconnects&&setTimeout(()=>{this.#s()},this.options.reconnectTimeout)}),this.#t.addEventListener("message",({data:t})=>{let n;try{n=JSON.parse(t)}catch(o){console.error(new Error(`Failed to parse RPC message: ${t}`,{cause:o}));return}if("id"in n&&n.id!=null&&this.#o.has(n.id)){let{resolve:o,timeout:r}=this.#o.get(n.id);clearTimeout(r),o(n)}else if("params"in n){let{params:o}=n;this.#r.forEach(r=>{r.subscriptionId===o.subscription&&o.subscription===r.subscriptionId&&r.onMessage(o.result)})}})}),this.#e)}async#s(){return this.#t?.close(),this.#e=null,Promise.allSettled([...this.#r].map(e=>e.subscribe(this)))}async subscribe(e){let t=new Ri(e);return this.#r.add(t),await t.subscribe(this),()=>t.unsubscribe(this)}},Ri=class{subscriptionId=null;input;subscribed=!1;constructor(e){this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){let{subscriptionId:t}=this;return this.subscribed=!1,t==null?!1:(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[t]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;let t=await e.makeRequest(this.input.method,this.input.params);this.subscribed&&(this.subscriptionId=t)}};var se=class{rpcClient;websocketClient;constructor({url:e,websocket:{url:t,...n}={},rpc:o}){let r=new yp(o?.url??e,{headers:{"Content-Type":"application/json",...o?.headers}});this.rpcClient=new bp(new gp([r])),this.websocketClient=new Zo(t??e,n)}async request(e){return await this.rpcClient.request(e)}async subscribe(e){let t=await this.websocketClient.subscribe(e);return async()=>!!await t()}};var ta=class a{apps;constructor(){this.apps=new Map}static fromHelpers(e){let t=new a;for(let n=0;n<e.length;n++){let o=e[n];switch(o.supportSDK){case"@mysten/sui.js":t.addLegacyHelper(o);break;case"@mysten/sui":t.addHelper(o);break;default:throw new Error(`${o.application}: ${o.supportSDK} SDK not supported`)}}return t}addLegacyHelper(e){this.apps.set(e.application,new Ni(e))}addHelper(e){this.apps.set(e.application,new Ei(e))}getAppHelper(e){let t=this.apps.get(e);if(!t)throw new Error(`${e} not registered`);return t}},Ei=class{constructor(e){this.helper=e}async deserialize(e){let t=new jc({transport:new se({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=new Bi({transport:new se({url:e.clientUrl,rpc:{url:e.clientUrl}})}),o=await e.transactionBlock.build({client:n}),r=Sp.from(o);return this.helper.deserialize({...e,suiClient:t,transaction:r})}async build(e){let t=new jc({transport:new se({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=await t.getBalance({owner:e.account.address});if(Number(n.totalBalance)<1e8)throw new Error("Insufficient gas fee");let o=await this.helper.build({...e,suiClient:t});o.setSender(e.account.address);let r=await o.build({client:t});return Tp.from(r)}},Ni=class{constructor(e){this.helper=e}async deserialize(e){let t=new Bi({transport:new se({url:e.clientUrl,rpc:{url:e.clientUrl}})});return this.helper.deserialize({...e,transactionBlock:e.transactionBlock,suiClient:t})}async build(e){let t=new Bi({transport:new se({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=await t.getBalance({owner:e.account.address});if(Number(n.totalBalance)<1e8)throw new Error("Insufficient gas fee");return this.helper.build({...e,suiClient:t})}};import{TransactionType as Mp}from"@msafe/sui3-utils";import{getFullnodeUrl as Pp}from"@mysten/sui/client";import{Scallop as Rp}from"@scallop-io/sui-scallop-sdk";import{TransactionType as Mt}from"@msafe/sui3-utils";import{OLD_BORROW_INCENTIVE_PROTOCOL_ID as Vc}from"@scallop-io/sui-scallop-sdk";import{parseStructTag as wp}from"@mysten/sui/utils";var ce=class{constructor(e,t){this.transaction=e;this.scallopClient=t;this.scallopClient=t,this.inputs=e.getData().inputs,this.commands=e.getData().commands,this.movecallsAsSet=new Set(this.commands.filter(this.isMoveCall).map(n=>`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`))}inputs;commands;movecallsAsSet;get address(){return this.scallopClient.address}get utils(){return this.scallopClient.utils}get coreId(){return{protocolPkg:this.address.get("core.packages.protocol.id"),market:this.address.get("core.market"),version:this.address.get("core.version"),coinDecimalsRegistry:this.address.get("core.coinDecimalsRegistry"),xOracle:this.address.get("core.oracles.xOracle"),spoolPkg:this.address.get("spool.id"),borrowIncentivePkg:this.address.get("borrowIncentive.id"),veScaPkgId:this.address.get("vesca.id"),veScaObjId:this.address.get("vesca.object"),scoin:this.address.get("scoin.id"),referral:this.address.get("referral.id")}}matchMoveCallCommand(e,t){let{address:n,module:o,name:r}=wp(t);return e?e.package===n&&e.module===o&&e.function===r:!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((r,c,l)=>(r[c]=l,r),{}),o=[];return this.commands.forEach(r=>{this.isMoveCall(r)&&r.MoveCall&&t.has(r.MoveCall.package)&&(o[n[r.MoveCall.package]]=r.MoveCall)}),o}hasMoveCallCommand(e){return this.movecallsAsSet.has(e)}};import{bcs as Wi}from"@mysten/sui/bcs";import{normalizeStructTag as Ip,normalizeSuiAddress as tn}from"@mysten/sui/utils";var _i=class a{constructor(e,t,n=0){this.moveCall=e;this.transaction=t;let o=[];e?.MoveCall&&t.getData().commands.filter((r,c)=>{if(r.$kind==="MoveCall"){let l=`${r.MoveCall.package}::${r.MoveCall.module}::${r.MoveCall.function}`,d=`${e.MoveCall.package}::${e.MoveCall.module}::${e.MoveCall.function}`;return l===d?(o.push(c),!0):!1}return!1}),this.cmdIdx=o[n]}cmdIdx;get txBlockTransactions(){return this.transaction.blockData.transactions[this.cmdIdx]}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"U64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"U8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"Address");return tn(t)}decodeInputString(e){return this.decodePureArg(e,"String")}decodeInputBool(e){return this.decodePureArg(e,"Bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.txBlockTransactions.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return t}getNestedInputParam(e){let t=this.txBlockTransactions.arguments[e];if(t.kind!=="NestedResult")throw new Error("not input type");return this.transaction.blockData.transactions[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure,o=Wi[t];return Wi[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 tn(e.value.Object.ImmOrOwned.objectId)}return tn(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return tn(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return tn(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 Wi.U64.parse(new Uint8Array(t))}typeArg(e){return Ip(this.txBlockTransactions.typeArguments[e])}txArg(e){return this.transaction.blockData.inputs[e]}},W=_i;var Li=class{constructor(e,t){this.splitCoin=e;this.txb=t}getAmountInput(){return this.splitCoin.amounts.map(e=>{if(e.kind==="Input")return Number(W.getPureInputValue(e,"U64"))}).filter(e=>e!==void 0)}},Rt=Li;import{normalizeStructTag as Uc,SUI_CLOCK_OBJECT_ID as qc,SUI_TYPE_ARG as Cp}from"@mysten/sui/utils";var Fc=async(a,e)=>{let t=await a.scallopSuiKit.client.getObject({id:e,options:{showContent:!0}});if(t?.data?.content?.dataType!=="moveObject")return!1;let o=t.data.content.fields.lock_key?.fields.name;if(!o)return!1;let r=a.address.get("borrowIncentive.object");return o===`${r.slice(2)}::incentive_account::IncentiveProgramLockKey`},Pe={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},Ft={unstakeObligation:(a,e,t)=>a.moveCall(`${Pe.id}::user::unstake`,[Pe.incentivePools,Pe.incentiveAccounts,a.object(e),a.object(t),qc],[Uc(Cp)]),redeem_rewards:(a,e,t,n)=>a.moveCall(`${Pe.id}::user::redeem_rewards`,[Pe.incentivePools,Pe.incentiveAccounts,a.object(e),a.object(t),qc],[Uc(n)])};var Kc=(a,e)=>{let t=[];for(let n=0;n<a.length;n+=e)t.push(a.slice(n,n+e));return t};var ea=class extends ce{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(`${Vc}::user::redeem_rewards`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`),n=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake`);return e&&(t||n)}get helperClaimLendingReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperClaimBorrowV2Reward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperStakeObligationWithVeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`));return new W(e,this.transaction)}get helperClaimBorrowReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${Vc}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperMint(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::mint::mint`));return new W(e,this.transaction)}get helperUnstakes(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`)).map(t=>new W(t,this.transaction))}get helperRedeems(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`)).map(t=>new W(t,this.transaction))}get helperRedeem(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`));return new W(e,this.transaction)}get helperBurnScoin(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.scoin}::s_coin_converter::burn_s_coin`));return new W(e,this.transaction)}get helperStake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::stake`));return new W(e,this.transaction)}get helperUnstake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`));return new W(e,this.transaction)}get helperDepositCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`));return new W(e,this.transaction)}get helperWithdrawCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`));return new W(e,this.transaction)}get helperBorrow(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow`));return new W(e,this.transaction)}get helperBorrowWithReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow_with_referral`));return new W(e,this.transaction)}get helperRepay(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::repay::repay`));return new W(e,this.transaction)}decodeMigrateScoin(){return{txType:Mt.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:Mt.Other,type:"MigrateAndClaim",intentionData:{obligationKey:t,obligationId:n,rewardCoinName:o,veScaKey:e}}}decodeOpenObligation(){return{txType:Mt.Other,type:"OpenObligation",intentionData:{}}}decodeSupplyLending(){let e=this.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),t=this.helperMint.getNestedInputParam(2),n=new Rt(t,this.transaction).getAmountInput().reduce((o,r)=>o+r,0);return{txType:Mt.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 Rt(t,this.transaction).getAmountInput().reduce((o,r)=>o+r,0);return{txType:Mt.Other,type:"WithdrawLending",intentionData:{amount:n,coinName:e}}}decodeWithdrawLendingScoin(){let e=this.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0));console.log({coinName:e});let t=this.helperBurnScoin.getNestedInputParam(1),n=new Rt(t,this.transaction).getAmountInput().reduce((o,r)=>o+r,0);return{txType:Mt.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 Rt(t,this.transaction).getAmountInput().reduce((r,c)=>r+c,0),o=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:Mt.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:Mt.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:Mt.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),r=this.helperBorrow.decodeOwnedObjectId(2);return{txType:Mt.Other,type:"BorrowWithBoost",intentionData:{amount:n,coinName:e,obligationKey:r,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),r=this.helperBorrowWithReferral.decodeOwnedObjectId(2);return{txType:Mt.Other,type:"BorrowWithReferral",intentionData:{amount:n,coinName:e,obligationKey:r,obligationId:o,veScaKey:t}}}decodeRepay(){let e=this.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),t=this.helperRepay.getNestedInputParam(3),n=new Rt(t,this.transaction).getAmountInput().reduce((r,c)=>r+c,0),o=this.helperRepay.decodeSharedObjectId(1);return{txType:Mt.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 Rt(n,this.transaction).getAmountInput().reduce((c,l)=>c+l,0),r=this.helperRepay.decodeSharedObjectId(1);return{txType:Mt.Other,type:"RepayWithBoost",intentionData:{amount:o,obligationId:r,coinName:e,veScaKey:t}}}decodeStakeSpool(){let e;this.isCreateStakeAccountTransaction()||(e=this.helperStake.decodeOwnedObjectId(1));let t=0;if(this.helperBurnScoin.moveCall){let r=this.helperBurnScoin.getNestedInputParam(1);t=new Rt(r,this.transaction).getAmountInput().reduce((c,l)=>c+l,0)}if(this.helperStake.moveCall&&t===0){let r=this.helperStake.getNestedInputParam(2);t=new Rt(r,this.transaction).getAmountInput().reduce((c,l)=>c+l,0)}let n=this.helperStake.typeArg(0),o=this.utils.parseCoinNameFromType(n);return{txType:Mt.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:Mt.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 Rt(t,this.transaction).getAmountInput().reduce((r,c)=>r+c,0),o;return this.isCreateStakeAccountTransaction()||(o=this.helperStake.decodeOwnedObjectId(1)),{txType:Mt.Other,type:"SupplyAndStakeLending",intentionData:{amount:n,coinName:e,stakeAccountId:o}}}decodeUnstakeAndWithdraw(){let e=[];this.helperUnstakes.forEach(o=>{let r=o.decodeOwnedObjectId(1),c=o.decodeInputU64(2);e.push({id:r,coin:c})});let t=this.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),n=0;if(this.helperBurnScoin.moveCall){let o=this.helperBurnScoin.getNestedInputParam(1);n=new Rt(o,this.transaction).getAmountInput().reduce((r,c)=>r+c,0)}return{txType:Mt.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:n,coinName:t,stakeAccountId:e}}}decodeClaimReward(){let e=[],t=[],n=[];return this.helperClaimLendingReward.forEach(o=>{let r=o.decodeOwnedObjectId(2),c=o.typeArg(0),l=this.utils.parseCoinNameFromType(c);e.push({stakeMarketCoinName:l,stakeAccountId:r})}),this.helperClaimBorrowV2Reward.forEach(o=>{let r=o.decodeSharedObjectId(4),c=o.decodeOwnedObjectId(3),l=this.utils.parseCoinNameFromType(o.typeArg(0));t.push({obligationId:c,obligationKey:r,rewardCoinName:l})}),this.helperClaimBorrowReward.forEach(o=>{let r=o.decodeSharedObjectId(2),c=o.decodeOwnedObjectId(3),l=this.utils.parseCoinNameFromType(o.typeArg(0));n.push({obligationId:c,obligationKey:r,rewardCoinName:l})}),{txType:Mt.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:e,borrowIncentiveV2:t,borrowIncentive:n}}}};import{TransactionType as Ui}from"@msafe/sui3-utils";var na=class extends ce{decode(){if(this.isCreateReferralLink())return this.decodeCreateReferralLink();if(this.isClaimRevenueReferral())return this.decodeClaimRevenueReferral();if(this.isBindReferral())return this.decodeBindReferral()}isClaimRevenueReferral(){return this.hasMoveCallCommand(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)}isCreateReferralLink(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_placeholder_key`)}isBindReferral(){return this.hasMoveCallCommand(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`)}get helperClaimRevenueReferral(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)).map(t=>new W(t,this.transaction))}get helperBindReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`));return new W(e,this.transaction)}decodeCreateReferralLink(){return{txType:Ui.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let e=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),t=this.helperClaimRevenueReferral.map(n=>n.typeArg(0));return{txType:Ui.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:e,coins:t}}}decodeBindReferral(){let e=this.helperBindReferral.decodePureArg(1,"Address");return{txType:Ui.Other,type:"BindReferral",intentionData:{veScaKey:e}}}};import{TransactionType as te}from"@msafe/sui3-utils";import{OLD_BORROW_INCENTIVE_PROTOCOL_ID as kp}from"@scallop-io/sui-scallop-sdk";var oa=class extends ce{async decode(){if(this.isExtendPeriodAndStakeMoreSca())return this.decodePeriodAndStakeMoreSca();if(this.isStakeScaFirsTime()||this.isStakeMoreSca())return this.decodeStakeSca();if(this.isRenewExpiredVeSca())return this.decodeRenewExpiredVeSca();if(this.isExtendPeriod())return this.decodeExtendStakePeriod();if(this.isRedeemSca())return this.decodeRedeemSca();if(this.isMergeVeSca())return this.decodeMergeVesca();if(this.isSplitVeSca())return this.decodeSplitVesca();if(this.isVeScaObligationBindings())return this.decodeVeScaObligationBindings();if(await this.isTransferVeScaKey())return this.decodeTransferVeScaKey()}isStakeScaFirsTime(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`)}isExtendPeriodAndStakeMoreSca(){let e=this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`),t=this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);return!!e&&!!t}isRedeemSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::redeem`)}isStakeMoreSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`)}isExtendPeriod(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`)}isRenewExpiredVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`)}isMergeVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::merge`)}isSplitVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::split`)}isVeScaObligationBindings(){let e=this.commands.filter(l=>this.filterMoveCallCommands(l,`${this.coreId.borrowIncentivePkg}::user::unstake_v2`)),t=this.commands.filter(l=>this.filterMoveCallCommands(l,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`)),n=this.commands.filter(l=>this.filterMoveCallCommands(l,`${this.coreId.borrowIncentivePkg}::user::deactivate_boost_v2`)),o=e.length>0&&t.length>0&&e.length===t.length,r=n.length>0;return this.commands.length===e.length+t.length+n.length&&(o||r)}async isTransferVeScaKey(){let e=this.commands.filter(d=>d.$kind==="TransferObjects");if(e.length!==1)return!1;let{objects:t}=e[0].TransferObjects,n=t.filter(d=>d.$kind==="Input").map(({Input:d})=>d);if(n.length!==t.length)return!1;let o=new Set(n),r=this.inputs.filter((d,S)=>d.$kind==="Object"&&o.has(S)).map(d=>d.Object.ImmOrOwnedObject),c=`${this.coreId.veScaObjId}::ve_sca::VeScaKey`,l=Kc(r.map(({objectId:d})=>d),50);for(let d=0;d<l.length;d++){let S=l[d];if((await this.scallopClient.scallopSuiKit.queryGetObjects(S,{showType:!0})).some(I=>I.type!==c))return!1}return r.length>0}get helperStakeMoreSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`));return new W(e,this.transaction)}get helperStakeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`));return new W(e,this.transaction)}get helperExtendStakePeriod(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`));return new W(e,this.transaction)}get helperRedeemSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::redeem`));return new W(e,this.transaction)}get helperRenewExpired(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`));return new W(e,this.transaction)}get helperOldUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${kp}::user::unstake`));return new W(e,this.transaction)}get helperUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::unstake_v2`));return new W(e,this.transaction)}get helperStakeObligationWithVeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`));return new W(e,this.transaction)}getMergeSplitVeScaHelper(e){let t=this.commands.find(n=>this.filterMoveCallCommands(n,`${this.coreId.veScaPkgId}::ve_sca::${e}`));return new W(t,this.transaction)}getVeScaObligationBindingHelpers(){let e=`${this.coreId.borrowIncentivePkg}::user::unstake_v2`,t=`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`,n=`${this.coreId.borrowIncentivePkg}::user::deactivate_boost_v2`,o=[],r=0,c=0,l=0;return this.commands.forEach(d=>{this.filterMoveCallCommands(d,e)?(o.push({action:"unstake",helper:new W(d,this.transaction,r)}),r++):this.filterMoveCallCommands(d,t)?(o.push({action:"stake",helper:new W(d,this.transaction,c)}),c++):this.filterMoveCallCommands(d,n)&&(o.push({action:"deactivate",helper:new W(d,this.transaction,l)}),l++)}),o}decodeRedeemSca(){let e=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:te.Other,type:"RedeemSca",intentionData:{veScaKey:e}}}decodeRenewExpiredVeSca(){let e=this.helperRenewExpired.getNestedInputParam(4),t=this.helperRenewExpired.decodeInputU64(5),n=new Rt(e,this.transaction).getAmountInput().reduce((x,P)=>x+P,0),o=this.helperRenewExpired.decodeOwnedObjectId(1),r=!!this.helperRedeemSca.moveCall,c=[],l=[],d=[];this.helperOldUnstakeObligation.moveCall&&(c=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(l=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(d=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let S=!1,w=!1,I,C,k=[{condition:c,isOld:!0},{condition:l,isOld:!1},{condition:d,isOld:!1}];for(let x=0;x<k.length;x++)k[x].condition.length>1&&([C,I]=k[x].condition,S=!0,w=k[x].isOld);return{txType:te.Other,type:"RenewExpStakePeriod",intentionData:{amount:n,unlockTime:t,obligationId:I,obligationKey:C,veScaKey:o,isHaveRedeem:r,isObligationLocked:S,isOldBorrowIncentive:w}}}decodeExtendStakePeriod(){let e=this.helperExtendStakePeriod.decodeInputU64(4),t=this.helperExtendStakePeriod.decodeOwnedObjectId(1),n=[],o=[],r=[];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&&(r=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,S,w=[{condition:n,isOld:!0},{condition:o,isOld:!1},{condition:r,isOld:!1}];for(let I=0;I<w.length;I++)w[I].condition.length>1&&([S,d]=w[I].condition,c=!0,l=w[I].isOld);return{txType:te.Other,type:"ExtendStakePeriod",intentionData:{unlockTime:e,obligationId:d,obligationKey:S,veScaKey:t,isObligationLocked:c,isOldBorrowIncentive:l}}}decodePeriodAndStakeMoreSca(){let e=this.helperStakeMoreSca.getNestedInputParam(4),t=this.helperExtendStakePeriod.decodeInputU64(4),n=new Rt(e,this.transaction).getAmountInput().reduce((k,x)=>k+x,0),o=[],r=[],c,l=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(c=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(l=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let d=!1,S=!1,w,I,C=[{condition:o,isOld:!0},{condition:r,isOld:!1},{condition:l,isOld:!1}];for(let k=0;k<C.length;k++)C[k].condition.length>1&&([I,w]=C[k].condition,d=!0,S=C[k].isOld);return{txType:te.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:n,veScaKey:c,unlockTime:t,obligationId:w,obligationKey:I,isOldBorrowIncentive:S,isObligationLocked:d}}}decodeStakeSca(){let e,t;this.helperStakeSca.moveCall&&this.helperStakeMoreSca.moveCall===void 0?(e=this.helperStakeSca.getNestedInputParam(3),t=this.helperStakeSca.decodeInputU64(4)):e=this.helperStakeMoreSca.getNestedInputParam(4);let n=new Rt(e,this.transaction).getAmountInput().reduce((k,x)=>k+x,0),o=[],r=[],c,l=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(r=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(c=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(l=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let d=!1,S=!1,w,I,C=[{condition:o,isOld:!0},{condition:r,isOld:!1},{condition:l,isOld:!1}];for(let k=0;k<C.length;k++)C[k].condition.length>1&&([I,w]=C[k].condition,d=!0,S=C[k].isOld);return{txType:te.Other,type:"StakeSca",intentionData:{amount:n,unlockTime:t,obligationId:w,obligationKey:I,veScaKey:c,isObligationLocked:d,isOldBorrowIncentive:S}}}decodeMergeVesca(){let e=this.getMergeSplitVeScaHelper("merge"),t={targetVeScaKey:e.decodeOwnedObjectId(1),sourceVeScaKey:e.decodeOwnedObjectId(2)};return{txType:te.Other,type:"MergeVeSca",intentionData:t}}decodeSplitVesca(){let e=this.getMergeSplitVeScaHelper("split"),t={targetVeScaKey:e.decodeOwnedObjectId(1),splitAmount:e.decodeInputU64(4)};return{txType:te.Other,type:"SplitVeSca",intentionData:t}}decodeVeScaObligationBindings(){let e=this.getVeScaObligationBindingHelpers(),t=(o,r)=>{switch(o){case"stake":return{veScaKey:r.decodeOwnedObjectId(9),obligationId:r.decodeSharedObjectId(4),obligationKey:r.decodeOwnedObjectId(3)};case"unstake":return{obligationId:r.decodeSharedObjectId(4),obligationKey:r.decodeOwnedObjectId(3)};case"deactivate":return{veScaKey:r.decodeOwnedObjectId(4),obligationId:r.decodeSharedObjectId(3)};default:throw new Error(`Invalid action ${o}`)}},n=e.map(({action:o,helper:r})=>({action:o,args:t(o,r)}));return{txType:te.Other,type:"VeScaObligationBindings",intentionData:{bindingDatas:n}}}decodeTransferVeScaKey(){let e=this.commands.filter(c=>c.$kind==="TransferObjects"),{objects:t}=e[0].TransferObjects,n=t.filter(c=>c.$kind==="Input").map(({Input:c})=>c);if(n.length!==t.length)return!1;let o=new Set(n),r=this.inputs.filter((c,l)=>c.$kind==="Object"&&o.has(l)).map(c=>c.Object.ImmOrOwnedObject);return{xType:te.Other,type:"TransferVeScaKeys",intentionData:{veScaKeys:r}}}};import vp from"sort-keys-recursive";var A=class{constructor(e){this.data=e}get application(){return"msafe-core"}serialize(){return JSON.stringify(vp(this.data))}isObligationLocked=async(e,t)=>{let n=await e.getObject({id:typeof t=="string"?t:t.objectId,options:{showContent:!0}}),o=!1;return n&&n?.data.content?.dataType==="moveObject"&&"lock_key"in n.data.content.fields&&(o=!!n.data.content.fields.lock_key),o};async buildTxWithRefreshObligation(e,t,n){let o=e.builder.createTxBlock();o.setSender(t.walletAddress);let{obligationId:r,obligationKey:c}=t;return await this.isObligationLocked(e.scallopSuiKit.client,r)?(await o.unstakeObligationQuick(r,c),await n(e,o,t),await o.stakeObligationWithVeScaQuick(r,c,t.veScaKey)):await n(e,o,t),o}};var aa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async borrow({account:t,scallopClient:n}){let{coinName:o,amount:r,obligationId:c,obligationKey:l}=this.data,d=t.address;return(await this.buildTxWithRefreshObligation(n,{walletAddress:d,obligationId:c,obligationKey:l},async(w,I)=>{let C=await I.borrowQuick(+r,o,c,l);I.transferObjects([C],d)})).txBlock}async build(t){return this.borrow(t)}static fromData(t){return new a(t)}};var ra=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async borrowWithBoost(t,n){let{obligationId:o,obligationKey:r,veScaKey:c,amount:l,coinName:d}=this.data;return(await this.buildTxWithRefreshObligation(t,{walletAddress:n,obligationId:o,obligationKey:r,veScaKey:c},async(w,I)=>{let C=await I.borrowQuick(+l,d,o,r);I.transferObjects([C],n)})).txBlock}async build(t){return this.borrowWithBoost(t.scallopClient,t.account.address)}static fromData(t){return new a(t)}};var ia=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async borrowWithReferral({account:t,scallopClient:n}){let o=t.address,{obligationId:r,obligationKey:c,veScaKey:l,coinName:d,amount:S}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:o,obligationId:r,obligationKey:c,veScaKey:l},async(I,C)=>{let k=C.claimReferralTicket(d),x=await C.borrowWithReferralQuick(+S,d,k,r,c);C.burnReferralTicket(k,d),C.transferObjects([x],o)})).txBlock}async build(t){return this.borrowWithReferral(t)}static fromData(t){return new a(t)}};import{SUI_TYPE_ARG as xp}from"@mysten/sui/utils";var sa=class a extends A{txType;txSubType;constructor(e={}){super(e)}async claimIncentiveRewards(e,t){let n=e.builder.createTxBlock();n.setSender(t);let o=await e.query.getAllStakeAccounts(t),r=await e.query.getLendings(void 0,t),c=await e.query.getObligations(t),l=Object.values(await e.query.getObligationAccounts(t)??[]),d=(()=>{let C=[...e.constants.whitelist.spool].map(k=>e.utils.parseCoinName(k));return Object.values(r??[]).filter(k=>!!k&&C.includes(k.coinName)).reduce((k,x)=>{let P=e.utils.parseMarketCoinName(x.coinName);return k[P]||(k[P]=0),k[P]+=x.availableClaimCoin,k},{})})(),S={};Object.entries(o).forEach(([C,k])=>{for(let x=0;x<k.length;x++){let P=k[x];if(!d[C])continue;let L=n.claim(P.id,C);S.sui?S.sui.push(L):S.sui=[L]}});let w=(()=>{let C={};return C.sui=Object.values(d).reduce((k,x)=>k+x,0),l.forEach(k=>{Object.values(k.borrowIncentives).forEach(x=>{x&&x.rewards.forEach(P=>{C[P.coinName]||(C[P.coinName]=0),C[P.coinName]?C[P.coinName]+=P.availableClaimCoin:C[P.coinName]=P.availableClaimCoin})})}),C})();if(c.length>0&&l.length>0)for(let C=0;C<l.length;C++){let k=l[C],x=!1,P=c.find(V=>V.id===k.obligationId)?.keyId,L={};if(P){if(Object.values(k.borrowIncentives).forEach(V=>{if(V){let Wt=V.rewards.filter(Bt=>{let Et=Bt.coinName;return Bt.availableClaimCoin>0&&!L[Et]});x=Wt.length>0,Wt.forEach(Bt=>{let Et=n.claimBorrowIncentive(k.obligationId,P,Bt.coinName);L[Bt.coinName]=!0,S[Bt.coinName]?S[Bt.coinName].push(Et):S[Bt.coinName]=[Et]})}}),w.sui>0){let V=Ft.redeem_rewards(n,P,k.obligationId,xp);S.sui?S.sui.push(V):S.sui=[V]}if(x&&await Fc(e.query,k.obligationId)){n.unstakeObligation(k.obligationId,P);let Wt=await e.query.getBindedVeScaKey(k.obligationId);Wt?n.stakeObligationWithVesca(k.obligationId,P,Wt):n.stakeObligation(k.obligationId,P)}}}let I=(await Promise.all(Object.entries(S).map(async([C,k])=>{let x=k[0];if(k.length>1&&n.mergeCoins(x,k.slice(1)),C==="sui"){n.mergeCoins(n.gas,[x]);return}return await e.builder.utils.mergeSimilarCoins(n,x,e.utils.parseCoinType(C),t),x}))).filter(C=>!!C);return I.length>0&&n.transferObjects(I,t),n.txBlock}async build(e){return this.claimIncentiveRewards(e.scallopClient,e.account.address)}static fromData(e={}){return new a(e)}};var ca=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.depositCollateral(this.data.collateralCoinName,+this.data.amount,!1,this.data.obligationId)}static fromData(t){return new a(t)}};var la=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async migrateAndClaim({account:t,scallopClient:n}){let o=t.address,{obligationKey:r,obligationId:c,rewardCoinName:l,veScaKey:d}=this.data,S=n.builder.createTxBlock();S.setSender(o);let w=Ft.redeem_rewards(S,r,c,n.utils.parseCoinType(l));return S.transferObjects([w],o),await S.unstakeObligationQuick(c,r),d?await S.stakeObligationWithVeScaQuick(c,r,d):await S.stakeObligationQuick(c,r),S.txBlock}async build(t){return this.migrateAndClaim(t)}static fromData(t){return new a(t)}};var ua=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.migrateAllMarketCoin(!1,!1)}static fromData(t){return new a(t)}};var ma=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.openObligation(!1)}static fromData(t){return new a(t)}};var pa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async repay({account:t,scallopClient:n}){let o=t.address,{coinName:r,amount:c,obligationId:l,obligationKey:d}=this.data;return(await this.buildTxWithRefreshObligation(n,{walletAddress:o,obligationId:l,obligationKey:d},async(w,I)=>{await I.repayQuick(+c,r,l)})).txBlock}async build(t){return this.repay(t)}static fromData(t){return new a(t)}};var da=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async repayWithBoost({account:t,scallopClient:n}){let o=t.address,{coinName:r,amount:c,obligationId:l,veScaKey:d}=this.data,S=n.builder.createTxBlock();S.setSender(o);let w=n.constants.whitelist.borrowing.has(r);return w&&await S.unstakeObligationQuick(l,void 0),await S.repayQuick(+c,r,l),w&&await S.stakeObligationWithVeScaQuick(l,void 0,d),S.txBlock}async build(t){return this.repayWithBoost(t)}static fromData(t){return new a(t)}};var fa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.deposit(this.data.coinName,+this.data.amount,!1,t.account.address)}static fromData(t){return new a(t)}};var ha=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.unstake(this.data.marketCoinName,+this.data.amount,!1)}static fromData(t){return new a(t)}};var ga=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async unstakeAndWithdraw(t,n,o){let r=t.builder.createTxBlock();r.setSender(o);let{stakeAccountId:c,amount:l,coinName:d}=this.data,S=[];for(let w=0;w<c.length;w++){let{id:I,coin:C}=c[w],k=t.utils.parseMarketCoinName(d),[x]=await r.unstakeQuick(C,k,I);if(x){let P=r.withdraw(x,d);S.push(P)}}if(l>0){let w=await r.withdrawQuick(l,d);S.push(w)}return S.length>1&&r.mergeCoins(S[0],S.slice(1)),r.transferObjects(S,o),r.txBlock}async build(t){return this.unstakeAndWithdraw(t.scallopClient,this.data,t.account.address)}static fromData(t){return new a(t)}};var ya=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.withdrawCollateral(this.data.collateralCoinName,Number(this.data.amount),!1,this.data.obligationId,this.data.obligationKey,t.account.address)}static fromData(t){return new a(t)}};var ba=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.withdraw(this.data.coinName,Number(this.data.amount),!1,t.account.address)}static fromData(t){return new a(t)}};var Sa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async bindReferral({account:t,scallopClient:n}){let o=t.address,r=n.builder.createTxBlock();return r.setSender(o),r.bindToReferral(this.data.veScaKey),r.txBlock}async build(t){return this.bindReferral(t)}static fromData(t){return new a(t)}};var Ta=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async claimRevenueReferral({account:t,scallopClient:n}){let{veScaKey:o,coins:r}=this.data,c=t.address,l=n.builder.createTxBlock();l.setSender(c);let d=r.map(S=>n.utils.parseCoinNameFromType(S));return await l.claimReferralRevenueQuick(o,d),l.txBlock}async build(t){return this.claimRevenueReferral(t)}static fromData(t){return new a(t)}};var wa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async createReferralLink({account:t,scallopClient:n}){let o=t.address,r=n.builder.createTxBlock();r.setSender(o);let c=r.mintEmptyVeSca();return r.transferObjects([c],o),r.txBlock}async build(t){return this.createReferralLink(t)}static fromData(t){return new a(t)}};import{SCA_COIN_TYPE as Dp}from"@scallop-io/sui-scallop-sdk";var Ia=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async extendPeriodAndStakeMoreSca({account:t,scallopClient:n}){let{amount:o,veScaKey:r,unlockTime:c,obligationId:l,obligationKey:d,isOldBorrowIncentive:S,isObligationLocked:w}=this.data,I=t.address,C=n.builder.createTxBlock();C.setSender(I);let k=await n.utils.selectCoins(o,Dp,I),[x,P]=C.takeAmountFromCoins(k,o);return C.extendLockPeriod(r,c),C.extendLockAmount(r,x),C.transferObjects([P],I),!l||!d||(w&&(S?Ft.unstakeObligation(C,l,d):C.unstakeObligation(l,d)),C.stakeObligationWithVesca(l,d,r)),C.txBlock}async build(t){return this.extendPeriodAndStakeMoreSca(t)}static fromData(t){return new a(t)}};var Ca=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async extendStakeScaLockPeriod({account:t,scallopClient:n}){let o=t.address,{veScaKey:r,unlockTime:c,obligationId:l,obligationKey:d,isObligationLocked:S,isOldBorrowIncentive:w}=this.data,I=n.builder.createTxBlock();return I.setSender(o),I.extendLockPeriod(r,c),l&&d&&(S&&(w?Ft.unstakeObligation(I,d,l):I.unstakeObligation(l,d)),I.stakeObligationWithVesca(l,d,r)),I.txBlock}async build(t){return this.extendStakeScaLockPeriod(t)}static fromData(t){return new a(t)}};var ka=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async handleUnsubForKeys(t,n,o){let{targetVeScaKey:r,sourceVeScaKey:c}=this.data,[l,d]=await Promise.all([n.getBindedObligationId(r),n.getBindedObligationId(c)]);l&&await t.unstakeObligationQuick(l),d&&await t.unstakeObligationQuick(d),o(t,r,c),l&&await t.stakeObligationWithVeScaQuick(l,void 0,r),d&&await t.stakeObligationWithVeScaQuick(d,void 0,c)}async build(t){let{scallopClient:n,account:{address:o}}=t,r=n.builder.createTxBlock();return r.setSender(o),await this.handleUnsubForKeys(r,n.query,async(c,l,d)=>{c.mergeVeSca(r.object(l),r.object(d))}),r.txBlock}static fromData(t){return new a(t)}};var va=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async redeemSca({account:t,scallopClient:n}){let{veScaKey:o}=this.data,r=t.address,c=n.builder.createTxBlock();return c.setSender(r),await c.redeemScaQuick(o),c.txBlock}async build(t){return this.redeemSca(t)}static fromData(t){return new a(t)}};import{SCA_COIN_TYPE as Ap}from"@scallop-io/sui-scallop-sdk";var xa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async renewExpiredStakeSca({account:t,scallopClient:n}){let o=t.address,{amount:r,unlockTime:c,veScaKey:l,isHaveRedeem:d,obligation:S,obligationKey:w,isObligationLocked:I,isOldBorrowIncentive:C}=this.data,k=n.builder.createTxBlock();if(k.setSender(o),d){let V=k.redeemSca(l);k.transferObjects([V],o)}let x=await n.builder.utils.selectCoins(r,Ap,o),[P,L]=k.takeAmountFromCoins(x,r);return k.transferObjects([L],o),k.renewExpiredVeSca(l,P,c),!S||!w||(I&&(C?Ft.unstakeObligation(k,w,S):k.unstakeObligation(S,w)),k.stakeObligationWithVesca(S,w,l)),k.txBlock}async build(t){return this.renewExpiredStakeSca(t)}static fromData(t){return new a(t)}};var Da=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async handleUnsubForKeys(t,n,o){let{targetVeScaKey:r,splitAmount:c}=this.data,l=await n.getBindedObligationId(r);l&&await t.unstakeObligationQuick(l),o(t,r,c.toString()),l&&await t.stakeObligationWithVeScaQuick(l,void 0,r)}async build(t){let{scallopClient:n,account:{address:o}}=t,r=n.builder.createTxBlock();return r.setSender(o),await this.handleUnsubForKeys(r,n.query,(c,l,d)=>{let S=c.splitVeSca(l,d.toString());c.transferObjects([S],o)}),r.txBlock}static fromData(t){return new a(t)}};import{SCA_COIN_TYPE as Op}from"@scallop-io/sui-scallop-sdk";var Aa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async stakeSca({account:t,scallopClient:n}){let o=t.address,{amount:r,isObligationLocked:c,isOldBorrowIncentive:l,obligationId:d,obligationKey:S,unlockTime:w,veScaKey:I}=this.data,C=n.builder.createTxBlock();C.setSender(o);let k=await n.utils.selectCoins(r,Op,o),[x,P]=C.takeAmountFromCoins(k,r),L;return I?C.extendLockAmount(I,x):L=C.lockSca(x,w),d&&S&&(c&&(l?Ft.unstakeObligation(C,S,d):C.unstakeObligation(d,S)),C.stakeObligationWithVesca(d,S,I||L)),I||C.transferObjects([L,P],o),C.txBlock}async build(t){return this.stakeSca(t)}static fromData(t){return new a(t)}};var Oa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async supplyAndStake({account:t,scallopClient:n}){let o=t.address,{amount:r,coinName:c,stakeAccountId:l}=this.data,d=n.builder.createTxBlock();d.setSender(o);let S=await d.depositQuick(+r,c),w=n.utils.parseMarketCoinName(c);if(n.constants.whitelist.spool.has(w))return d.txBlock;let I=await n.query.getStakeAccounts(w,o),C=l||(I.length>0?I[0].id:void 0);if(C)await d.stakeQuick(S,w,C);else{let k=d.createStakeAccount(w);await d.stakeQuick(S,w,k),d.transferObjects([k],o)}return d.txBlock}async build(t){return this.supplyAndStake(t)}static fromData(t){return new a(t)}};var Ma=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;handleAction(t,{action:n,args:o}){switch(n){case"deactivate":return t.deactivateBoost(o.obligationId,o.veScaKey);case"stake":return t.stakeObligationWithVesca(o.obligationId,o.obligationKey,o.veScaKey);case"unstake":return t.unstakeObligation(o.obligationId,o.obligationKey);default:throw new Error("Invalid action")}}async build(t){let{scallopClient:n,account:{address:o}}=t,r=n.builder.createTxBlock();r.setSender(o);let{bindingDatas:c}=this.data;return c.forEach(l=>this.handleAction(r,l)),r.txBlock}static fromData(t){return new a(t)}};var Pa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{scallopClient:n,account:{address:o}}=t,r=n.builder.createTxBlock();r.setSender(o);let{veScaKeys:c}=this.data;return r.transferObjects(c.map(l=>r.objectRef(l)),r.pure.address(o)),r.txBlock}static fromData(t){return new a(t)}};var Ra=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async withdrawUnlockedSca({account:t,scallopClient:n}){let{vescaKey:o}=this.data,r=t.address,c=n.builder.createTxBlock();return c.setSender(r),await c.redeemScaQuick(o),c.txBlock}async build(t){return this.withdrawUnlockedSca(t)}static fromData(t){return new a(t)}};var Ba=class{application="scallop";supportSDK="@mysten/sui";scallopClient;async initScallopClient(e,t){if(!this.scallopClient){let n=new Rp({addressId:"67c44a103fe1b8c454eb9699",walletAddress:e,suiClients:[t],fullnodeUrls:[t.transport.rpcClient.requestManager.transports[0]?.uri??Pp("mainnet")]});this.scallopClient=await n.createScallopClient()}}async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;await this.initScallopClient(o.address,n),console.log("transaction",t);let r=new ea(t,this.scallopClient),c=new na(t,this.scallopClient),l=new oa(t,this.scallopClient),d=r.decode()||c.decode()||await l.decode();if(!d)throw new Error("Unknown transaction type");return{txType:Mp.Other,txSubType:d.type,intentionData:d.intentionData}}async build(e){let{suiClient:t,account:n,network:o,txSubType:r,intentionData:c}=e;await this.initScallopClient(n.address,t);let l;switch(r){case"SupplyLending":l=fa.fromData(c);break;case"WithdrawLending":l=ba.fromData(c);break;case"Borrow":l=aa.fromData(c);break;case"Repay":l=pa.fromData(c);break;case"DepositCollateral":l=ca.fromData(c);break;case"WithdrawCollateral":l=ya.fromData(c);break;case"OpenObligation":l=ma.fromData(c);break;case"UnstakeSpool":l=ha.fromData(c);break;case"ClaimIncentiveReward":l=sa.fromData(c);break;case"BorrowWithBoost":l=ra.fromData(c);break;case"StakeSca":l=Aa.fromData(c);break;case"ExtendStakePeriod":l=Ca.fromData(c);break;case"ExtendPeriodAndStakeMore":l=Ia.fromData(c);break;case"RenewExpStakePeriod":l=xa.fromData(c);break;case"WithdrawStakedSca":l=Ra.fromData(c);break;case"SupplyAndStakeLending":l=Oa.fromData(c);break;case"WithdrawAndUnstakeLending":l=ga.fromData(c);break;case"RedeemSca":l=va.fromData(c);break;case"MigrateAndClaim":l=la.fromData(c);break;case"BorrowWithReferral":l=ia.fromData(c);break;case"CreateReferralLink":l=wa.fromData(c);break;case"ClaimRevenueReferral":l=Ta.fromData(c);break;case"BindReferral":l=Sa.fromData(c);break;case"MigrateScoin":l=ua.fromData(c);break;case"RepayWithBoost":l=da.fromData(c);break;case"MergeVeSca":l=ka.fromData(c);break;case"SplitVeSca":l=Da.fromData(c);break;case"VeScaObligationBindings":{l=Ma.fromData(c);break}case"TransferVeScaKeys":{l=Pa.fromData(c);break}default:throw new Error("not implemented")}return l.build({suiClient:t,account:n,network:o,scallopClient:this.scallopClient})}};import{TransactionType as md}from"@msafe/sui3-utils";import{TransactionType as on}from"@msafe/sui3-utils";import{normalizeStructTag as ge}from"@mysten/sui/utils";import{API_URL as Gp}from"@suilend/sui-fe";import{TransactionType as $p}from"@msafe/sui3-utils";import{LENDING_MARKET_ID as Hp,LENDING_MARKET_TYPE as zp,SuilendClient as qi}from"@suilend/sdk";import{TransactionType as Re}from"@msafe/sui3-utils";import{fromBase64 as $c,toHex as Hc}from"@mysten/bcs";import{normalizeStructTag as en}from"@mysten/sui/utils";import{MAX_U64 as Be}from"@suilend/sui-fe";import zc from"bignumber.js";var Ea=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isDepositTransaction())return this.decodeDeposit();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isClaimTransaction())return this.decodeClaim();if(this.isClaimAndDepositTransaction())return this.decodeClaimAndDeposit();throw new Error("Unknown transaction type")}get inputs(){return console.log("this.transaction.getData().inputs",this.transaction.getData().inputs),this.transaction.getData().inputs}get commands(){return console.log("this.transaction.getData().commands",this.transaction.getData().commands),this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}hasDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasClaimTransactionMoveCallCommands(){return!!this.getMoveCallCommand("claim_rewards")}isDepositTransaction(){return!this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}isWithdrawTransaction(){return!!this.getMoveCallCommand("withdraw_ctokens")&&!!this.getMoveCallCommand("redeem_ctokens_and_withdraw_liquidity_request")}isBorrowTransaction(){return!!this.getMoveCallCommand("borrow_request")}isRepayTransaction(){return!!this.getMoveCallCommand("repay")}isClaimTransaction(){return this.hasClaimTransactionMoveCallCommands()&&!this.hasDepositTransactionMoveCallCommands()}isClaimAndDepositTransaction(){return this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}decodeDeposit(){let e={MintEvent:this.simResult.events.find(o=>o.type.includes("lending_market::MintEvent"))},t=en(e.MintEvent.parsedJson.coin_type.name),n=e.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",t,n),{txType:Re.Other,type:"deposit",intentionData:{coinType:t,value:n}}}decodeWithdraw(){let e={withdraw_ctokens:this.getMoveCallCommand("withdraw_ctokens")},t={RedeemEvent:this.simResult.events.find(d=>d.type.includes("lending_market::RedeemEvent"))},n=en(t.RedeemEvent.parsedJson.coin_type.name),o=t.RedeemEvent.parsedJson.liquidity_amount;console.log("Decoder.decodeWithdraw",n,o);let r=e.withdraw_ctokens.MoveCall.arguments[4].Input,c=new zc(Hc($c(this.inputs[r].Pure.bytes)),16).toString(),l=c===Be.toString();return console.log("decodeWithdraw - isMax:",l,"inputIndex:",r,"inputValue:",c,"MAX_U64.toString():",Be.toString()),l&&(o=Be.toString()),{txType:Re.Other,type:"withdraw",intentionData:{coinType:n,value:o}}}decodeBorrow(){let e={borrow_request:this.getMoveCallCommand("borrow_request")},t={BorrowEvent:this.simResult.events.find(d=>d.type.includes("lending_market::BorrowEvent"))},n=en(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 r=e.borrow_request.MoveCall.arguments[4].Input,c=new zc(Hc($c(this.inputs[r].Pure.bytes)),16).toString(),l=c===Be.toString();return console.log("decodeBorrow - isMax:",l,"inputIndex:",r,"inputValue:",c,"MAX_U64.toString():",Be.toString()),l&&(o=Be.toString()),{txType:Re.Other,type:"borrow",intentionData:{coinType:n,value:o}}}decodeRepay(){let e={RepayEvent:this.simResult.events.find(o=>o.type.includes("lending_market::RepayEvent"))},t=en(e.RepayEvent.parsedJson.coin_type.name),n=e.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",t,n),{txType:Re.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],r=en(o.parsedJson.coin_type.name),c=o.parsedJson.liquidity_amount;t[r]=`${+(t[r]??"0")+ +c}`}return console.log("Decoder.decodeClaimRewards",t),{txType:Re.Other,type:"claim",intentionData:{value:t}}}decodeClaimAndDeposit(){return{txType:Re.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};import{Transaction as Np}from"@mysten/sui/transactions";import Ep from"sort-keys-recursive";var Nt=class{constructor(e){this.data=e}serialize(){return JSON.stringify(Ep(this.data))}};var Na=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:r,obligationOwnerCap:c,obligation:l}=t;if(console.log("BorrowIntention.build",n,o,r,c,l),!c||!l)throw new Error("Obligation not found");let d=new Np;return await r.borrowAndSendToUser(o.address,c.id,l.id,this.data.coinType,this.data.value,d),d}static fromData(t){return console.log("BorrowIntention.fromData",t),new a(t)}};import{Transaction as Up}from"@mysten/sui/transactions";import{normalizeStructTag as Wp}from"@mysten/sui/utils";import{Side as nn}from"@suilend/sdk";import{isSendPoints as _p}from"@suilend/sui-fe";import Lp from"bignumber.js";var jp=(a,e)=>{let t={[nn.DEPOSIT]:[],[nn.BORROW]:[]};return a.lendingMarket.reserves.forEach(n=>{[nn.DEPOSIT,nn.BORROW].forEach(o=>{let r=o===nn.DEPOSIT?n.depositsPoolRewardManager:n.borrowsPoolRewardManager,c=e.userRewardManagers.find(l=>l.poolRewardManagerId===r.id);c&&(t[o]=r.poolRewards.map((l,d)=>({reserveArrayIndex:n.arrayIndex,rewardIndex:BigInt(d),rewardCoinType:Wp(l.coinType.name),side:o})).filter(l=>!_p(l.rewardCoinType)&&!!c.rewards[Number(l.rewardIndex)]&&new Lp(c.rewards[Number(l.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(t).flat()},Wa=jp;var _a=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:r,obligationOwnerCap:c,obligation:l}=t;if(console.log("ClaimIntention.build",n,o,r,c,l),!c||!l)throw new Error("Obligation not found");let d=new Up;return r.claimRewardsAndSendToUser(o.address,c.id,Wa(r,l),d),d}static fromData(t){return console.log("ClaimIntention.fromData",t),new a(t)}};import{Transaction as qp}from"@mysten/sui/transactions";var La=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:r,obligationOwnerCap:c,obligation:l}=t;if(console.log("ClaimAndDepositIntention.build",n,o,r,c,l),!c||!l)throw new Error("Obligation not found");let d=new qp;return r.claimRewardsAndDeposit(o.address,c.id,Wa(r,l),d),d}static fromData(t){return console.log("ClaimAndDepositIntention.fromData",t),new a(t)}};import{Transaction as Fp}from"@mysten/sui/transactions";var ja=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:r,obligationOwnerCap:c,obligation:l}=t;console.log("DepositIntention.build",n,o,r,c,l);let d=new Fp;return await r.depositIntoObligation(o.address,this.data.coinType,this.data.value,d,c?.id),d}static fromData(t){return console.log("DepositIntention.fromData",t),new a(t)}};import{Transaction as Kp}from"@mysten/sui/transactions";var Ua=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:r,obligationOwnerCap:c,obligation:l}=t;if(console.log("RepayIntention.build",n,o,r,c,l),!c||!l)throw new Error("Obligation not found");let d=new Kp;return await r.repayIntoObligation(o.address,l.id,this.data.coinType,this.data.value,d),d}static fromData(t){return console.log("RepayIntention.fromData",t),new a(t)}};import{Transaction as Vp}from"@mysten/sui/transactions";var qa=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:r,obligationOwnerCap:c,obligation:l}=t;if(console.log("WithdrawIntention.build",n,o,r,c,l),!c||!l)throw new Error("Obligation not found");let d=new Vp;return await r.withdrawAndSendToUser(o.address,c.id,l.id,this.data.coinType,this.data.value,d),d}static fromData(t){return console.log("WithdrawIntention.fromData",t),new a(t)}};var Fa=async(a,e)=>{let t=await qi.initialize(Hp,zp,a),n=await qi.getObligationOwnerCaps(e.address,t.lendingMarket.$typeArgs,a),o=await Promise.all(n.map(r=>qi.getObligation(r.obligationId,t.lendingMarket.$typeArgs,a)));return console.log("XXX getUtils - suilendClient:",t,"obligations:",o,"obligationOwnerCaps:",n),{suilendClient:t,obligationOwnerCaps:n,obligations:o}},Ka=class{application="Suilend";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;this.utils||(this.utils=await Fa(n,o));let r=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:t});console.log("SuilendAppHelper.deserialize - simResult:",r,"utils:",this.utils,"suiClient:",n);let l=new Ea(t,r).decode();return{txType:$p.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:o,suiClient:r,account:c}=e;this.utils||(this.utils=await Fa(r,c));let l;switch(n){case"deposit":l=ja.fromData(o);break;case"withdraw":l=qa.fromData(o);break;case"borrow":l=Na.fromData(o);break;case"repay":l=Ua.fromData(o);break;case"claim":l=_a.fromData(o);break;case"claimAndDeposit":l=La.fromData(o);break;default:throw new Error("not implemented")}let d=window.localStorage.getItem("obligationId"),S=this.utils.obligations?.find(I=>I.id===d)??this.utils.obligations?.[0],w=this.utils.obligationOwnerCaps?.find(I=>I.obligationId===S?.id);return l.build({network:t,suiClient:r,account:c,suilendClient:this.utils.suilendClient,obligationOwnerCap:w,obligation:S})}};var Fi=async(a,e)=>{let t=await Fa(a,e),n=await fetch(`${Gp}/springsui/lst-info`),o=await n.json();if(n?.statusCode===500)throw new Error("Failed to fetch SpringSui LST data");let c=Object.fromEntries(Object.values(o).map(l=>[l.LIQUID_STAKING_INFO.type,l.LIQUID_STAKING_INFO]));return{...t,LIQUID_STAKING_INFO_MAP:c}};var Va=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isStakeTransaction())return this.decodeStake();if(this.isStakeAndDepositTransaction())return this.decodeStakeAndDeposit();if(this.isConvertTransaction())return this.decodeConvert();if(this.isConvertAndDepositTransaction())return this.decodeConvertAndDeposit();if(this.isUnstakeTransaction())return this.decodeUnstake();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}hasSuilendDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasMintMoveCallCommands(){return!!this.getMoveCallCommand("mint")}hasRedeemMoveCallCommands(){return!!this.getMoveCallCommand("redeem")}isStakeTransaction(){return this.hasMintMoveCallCommands()&&!this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isStakeAndDepositTransaction(){return this.hasMintMoveCallCommands()&&!this.hasRedeemMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isConvertTransaction(){return this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isConvertAndDepositTransaction(){return this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isUnstakeTransaction(){return!this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}decodeStake(){let e={MintEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::MintEvent"))},t=ge(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStake",n),{txType:on.Other,type:"stake",intentionData:{amount:n,outCoinType:t}}}decodeStakeAndDeposit(){let e={MintEvent:this.simResult.events.find(o=>o.type.includes("liquid_staking::MintEvent"))},t=ge(e.MintEvent.parsedJson.event.typename.name),n=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStakeAndDeposit",n),{txType:on.Other,type:"stakeAndDeposit",intentionData:{amount:n,outCoinType:t}}}decodeConvert(){let e={RedeemEvent:this.simResult.events.find(r=>r.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(r=>r.type.includes("liquid_staking::MintEvent"))},t=ge(e.RedeemEvent.parsedJson.event.typename.name),n=ge(e.MintEvent.parsedJson.event.typename.name),o=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvert",o),{txType:on.Other,type:"convert",intentionData:{amount:o,inCoinType:t,outCoinType:n}}}decodeConvertAndDeposit(){let e={RedeemEvent:this.simResult.events.find(r=>r.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(r=>r.type.includes("liquid_staking::MintEvent"))},t=ge(e.RedeemEvent.parsedJson.event.typename.name),n=ge(e.MintEvent.parsedJson.event.typename.name),o=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvertAndDeposit",o),{txType:on.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=ge(e.RedeemEvent.parsedJson.event.typename.name),n=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeUnstake",n),{txType:on.Other,type:"unstake",intentionData:{amount:n,inCoinType:t}}}};import{Transaction as Xp}from"@mysten/sui/transactions";import{convertLstsAndSendToUser as Yp,LstClient as Gc}from"@suilend/springsui-sdk";import Jp from"sort-keys-recursive";var Kt=class{constructor(e){this.data=e}serialize(){return JSON.stringify(Jp(this.data))}};var $a=class a extends Kt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:r,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("ConvertIntention.build",n,o,r,c,l,d);let S=await Gc.initialize(n,Object.values(c).find(C=>C.type===this.data.inCoinType)),w=await Gc.initialize(n,Object.values(c).find(C=>C.type===this.data.outCoinType)),I=new Xp;return Yp(S,w,I,o.address,this.data.amount),I}static fromData(t){return console.log("ConvertIntention.fromData",t),new a(t)}};import{Transaction as Zp}from"@mysten/sui/transactions";import{createObligationIfNoneExists as td,sendObligationToUser as ed}from"@suilend/sdk";import{convertLsts as nd,LstClient as Qc}from"@suilend/springsui-sdk";var Ha=class a extends Kt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:r,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("ConvertAndDepositIntention.build",n,o,r,c,l,d);let S=await Qc.initialize(n,Object.values(c).find(P=>P.type===this.data.inCoinType)),w=await Qc.initialize(n,Object.values(c).find(P=>P.type===this.data.outCoinType)),I=new Zp,{obligationOwnerCapId:C,didCreate:k}=td(r,I,l),x=nd(S,w,I,o.address,this.data.amount);return r.deposit(x,this.data.outCoinType,C,I),k&&ed(C,o.address,I),I}static fromData(t){return console.log("ConvertAndDepositIntention.fromData",t),new a(t)}};import{Transaction as od}from"@mysten/sui/transactions";import{LstClient as ad}from"@suilend/springsui-sdk";var za=class a extends Kt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:r,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("StakeIntention.build",n,o,r,c,l,d);let S=await ad.initialize(n,Object.values(c).find(I=>I.type===this.data.outCoinType)),w=new od;return S.mintAmountAndRebalanceAndSendToUser(w,o.address,this.data.amount),w}static fromData(t){return console.log("StakeIntention.fromData",t),new a(t)}};import{Transaction as rd}from"@mysten/sui/transactions";import{createObligationIfNoneExists as id,sendObligationToUser as sd}from"@suilend/sdk";import{LstClient as cd}from"@suilend/springsui-sdk";var Ga=class a extends Kt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:r,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("StakeAndDepositIntention.build",n,o,r,c,l,d);let S=await cd.initialize(n,Object.values(c).find(x=>x.type===this.data.outCoinType)),w=new rd,{obligationOwnerCapId:I,didCreate:C}=id(r,w,l),k=S.mintAmountAndRebalance(w,o.address,this.data.amount);return r.deposit(k,this.data.outCoinType,I,w),C&&sd(I,o.address,w),w}static fromData(t){return console.log("StakeAndDepositIntention.fromData",t),new a(t)}};import{Transaction as ld}from"@mysten/sui/transactions";import{LstClient as ud}from"@suilend/springsui-sdk";var Qa=class a extends Kt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:n,account:o,suilendClient:r,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("UnstakeIntention.build",n,o,r,c,l,d);let S=await ud.initialize(n,Object.values(c).find(I=>I.type===this.data.inCoinType)),w=new ld;return S.redeemAmountAndSendToUser(w,o.address,this.data.amount),w}static fromData(t){return console.log("UnstakeIntention.fromData",t),new a(t)}};var Ja=class{application="SpringSui";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:n,account:o}=e;this.utils||(this.utils=await Fi(n,o));let r=await n.devInspectTransactionBlock({sender:o.address,transactionBlock:t});console.log("SpringSuiAppHelper.deserialize",r);let l=new Va(t,r).decode();return{txType:md.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{network:t,txSubType:n,intentionData:o,suiClient:r,account:c}=e;this.utils||(this.utils=await Fi(r,c));let l;switch(n){case"stake":l=za.fromData(o);break;case"stakeAndDeposit":l=Ga.fromData(o);break;case"convert":l=$a.fromData(o);break;case"convertAndDeposit":l=Ha.fromData(o);break;case"unstake":l=Qa.fromData(o);break;default:throw new Error("not implemented")}return l.build({network:t,suiClient:r,account:c,suilendClient:this.utils.suilendClient,LIQUID_STAKING_INFO_MAP:this.utils.LIQUID_STAKING_INFO_MAP,obligationOwnerCap:this.utils.obligationOwnerCaps?.[0],obligation:this.utils.obligations?.[0]})}};import{TransactionType as hd}from"@msafe/sui3-utils";import{TransactionType as Jc}from"@msafe/sui3-utils";var Xa=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isMintTransaction()){let e=this.getLiquidityChangeEvent("MintEvent");if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson;return console.log("Decoder event data - ",t),this.decodeMint(t)}if(this.isRedeemTransaction()){let e=this.getLiquidityChangeEvent("RedeemEvent");if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson;return console.log("Decoder event data - ",t),this.decodeRedeem(t)}throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getLiquidityChangeEvent(e){return this.simResult.events.find(t=>this.isLiquidityChangeEventType(t.type,e))}isLiquidityChangeEventType(e,t){return e.includes(t)}isMintTransaction(){return!!this.getMoveCallCommand("mint")}isRedeemTransaction(){return!!this.getMoveCallCommand("redeem")}decodeMint(e){let{event:{sui_amount_in:t}}=e;return console.log("Decoder.decodeMint",t),{txType:Jc.Other,type:"mint",intentionData:{amount:t}}}decodeRedeem(e){let{event:{lst_amount_in:t}}=e;return console.log("Decoder.decodeRedeem",t),{txType:Jc.Other,type:"redeem",intentionData:{amount:t}}}};import{LST as dd}from"@alphafi/stsui-sdk";var Ya=class a extends v{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{amount:o}=this.data,r={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},l=await new dd(r).mint(o,n.address);return l.setGasBudget(1e8),l}static fromData(t){return console.log("MintIntention.fromData",t),new a(t)}};import{LST as fd}from"@alphafi/stsui-sdk";var Za=class a extends v{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:n}=t,{amount:o}=this.data,r={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},l=await new fd(r).redeem(o,n.address);return l.setGasBudget(1e8),l}static fromData(t){return console.log("RedeemIntention.fromData",t),new a(t)}};var tr=class{application="stsui";supportSDK="@mysten/sui";async deserialize(e){let{transaction:t,suiClient:n}=e,o=await n.devInspectTransactionBlock({sender:t.getData().sender,transactionBlock:t});console.log("StSuiHelper Sim result - ",o);let c=new Xa(t,o).decode();return{txType:hd.Other,txSubType:c.type,intentionData:c.intentionData}}async build(e){let{account:t}=e;console.log("StSui build transaction type",e.txSubType);let n;switch(e.txSubType){case"mint":n=Ya.fromData(e.intentionData);break;case"redeem":n=Za.fromData(e.intentionData);break;default:throw new Error("build not implemented")}return n.build({account:t})}};import{TransactionType as Wd}from"@msafe/sui3-utils";import{TurbosSdk as _d}from"turbos-clmm-sdk";import{TransactionType as Vt}from"@msafe/sui3-utils";import{bcs as Xc}from"@mysten/sui.js/bcs";import{normalizeStructTag as yd,normalizeSuiAddress as an}from"@mysten/sui.js/utils";import{BN as bd}from"turbos-clmm-sdk";var Ht={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},zt={PackageId:"0xdee9"};var Sd=(a,e,t,n)=>{if(a===1)switch(n.findIndex(c=>c===e)){case 0:return[!0,!0];case 1:return[!0,!1];case 2:return[!1,!0];case 3:return[!1,!1];default:throw new Error(`not target: ${e}`)}switch(t.findIndex(r=>r===e)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${e}`)}},er=class{constructor(e,t,n){this.txb=e;this.turbosSdk=t;this.config=n}get transactions(){return this.txb.blockData.transactions}get swap1Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b`,`${this.config.PackageId}::swap_router::swap_b_a`]}get swap2Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b_b_c`,`${this.config.PackageId}::swap_router::swap_a_b_c_b`,`${this.config.PackageId}::swap_router::swap_b_a_b_c`,`${this.config.PackageId}::swap_router::swap_b_a_c_b`]}async decode(e){if(this.isSwapTransaction())return this.decodeSwap();if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(e);if(this.isRemoveLiquidityTransaction())return this.decodeRemoveLiquidity(e);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(e);if(this.isCollectFeeTransaction())return this.decodeCollectFee();if(this.isCollectRewardTransaction())return this.decodeCollectReward();if(this.isBurnTransaction())return this.decodeBurn();if(this.isPrixClaimTransaction())return this.decodePrixClaim();if(this.isPrixJoinTransaction())return this.decodePrixJoin();if(this.isSwapExactBaseForQuoteTransaction())return this.decodeSwapExactBaseForQuote();if(this.isSwapExactQuoteForBaseTransaction())return this.decodeSwapExactQuoteForBase();throw new Error("Unknown transaction type")}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}getMoveCallsTransaction(e){return e.every(t=>this.transactions.find(n=>n.kind==="MoveCall"&&n.target===t))}getSwapMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&e.includes(t.target))}isSwapTransaction(){return!!this.getSwapMoveCallTransaction([...this.swap1Layer,...this.swap2Layer])}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect`)}isCollectRewardTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect_reward`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::burn`)}isPrixJoinTransaction(){return!!this.getMoveCallTransaction(`${Ht.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${Ht.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${zt.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${zt.PackageId}::clob_v2::swap_exact_quote_for_base`)}async decodeSwap(){let e=this.transactions.find(k=>k.kind==="MoveCall"),t=0;this.swap2Layer.includes(e.target)&&(t=1);let n=Sd(t,e.target,this.swap1Layer,this.swap2Layer),o=n.map((k,x)=>{let P=this.helper.decodeSharedObjectId(x),L=this.helper.decodeInputU128(4+x+t),V=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new bd(L.toString()));return{pool:P,a2b:k,nextTickIndex:V}}),r=n[0]||t===1?e.typeArguments[0]:e.typeArguments[1],c=t===1?e.typeArguments[4]:n[0]?e.typeArguments[1]:e.typeArguments[0],l=this.helper.decodeInputAddress(6+2*t),d=this.helper.decodeInputU64(7+2*t),S=this.helper.decodeInputBool(5+2*t),w=this.helper.decodeInputU64(2+t),I=this.helper.decodeInputU64(3+t),C=await this.turbosSdk.trade.computeSwapResultV2({pools:[{pool:o[0].pool,a2b:o[0].a2b,amountSpecified:w}],address:l,amountSpecifiedIsInput:S});return{txType:Vt.Other,type:"Swap",intentionData:{routes:o,coinTypeA:r,coinTypeB:c,address:l,amountA:S?w:I,amountB:S?I:w,amountSpecifiedIsInput:S,slippage:"0.1",deadline:d}}}decodeAddLiquidity(){console.log(this.helper,"decodeAddLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),o=this.helper.decodeInputU64(9),r=this.helper.decodeInputU32(4),c=this.helper.decodeInputBool(5),l=this.helper.decodeInputU32(6),d=this.helper.decodeInputBool(7),S=this.helper.decodeInputU64(13);return{txType:Vt.Other,type:"AddLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:n,amountB:o,tickLower:c?-r:r,tickUpper:d?-l:l,deadline:S}}}decodeIncreaseLiquidity(e){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),o=this.helper.decodeInputU64(5),r=this.helper.decodeInputU64(6),c=this.helper.decodeInputU64(9);return{txType:Vt.Other,type:"IncreaseLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:o,amountB:r,nft:n,deadline:c}}}decodeDecreaseLiquidity(e){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),o=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),c=this.helper.decodeInputU64(5),l=this.helper.decodeInputU64(6);return{txType:Vt.Other,type:"DecreaseLiquidity",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:r,amountB:c,slippage:10,address:e,deadline:l}}}decodeCollectFee(){console.log(this.helper,"decodeCollectFee this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),o=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),c=this.helper.decodeInputU64(6);return{txType:Vt.Other,type:"CollectFee",intentionData:{pool:e,address:n,collectAmountA:o,collectAmountB:r,nft:t,deadline:c}}}decodeCollectReward(){console.log(this.helper,"decodeCollectReward this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(6),o=this.collectRewardHelper.map(c=>c.decodeInputU64(5)),r=this.helper.decodeInputU64(7);return{txType:Vt.Other,type:"CollectReward",intentionData:{pool:e,address:n,rewardAmounts:o,nft:t,deadline:r}}}decodeBurn(){console.log(this.helper,"decodeBurn this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2);return{txType:Vt.Other,type:"Burn",intentionData:{pool:e,nft:t}}}decodeRemoveLiquidity(e){console.log(this.helper,"decodeRemoveLiquidity this.helper");let t=this.decreaseLiquidityHelper.decodeSharedObjectId(0),n=this.decreaseLiquidityHelper.decodeSharedObjectId(2),o=this.decreaseLiquidityHelper.decodeInputU64(3),r=this.decreaseLiquidityHelper.decodeInputU64(4),c=this.decreaseLiquidityHelper.decodeInputU64(5),l=this.decreaseLiquidityHelper.decodeInputU64(6),d=this.collectRewardHelper.map(I=>I.decodeInputU64(5)),S=this.collectFeeHelper.decodeInputU64(3)||0,w=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:Vt.Other,type:"RemoveLiquidity",intentionData:{pool:t,decreaseLiquidity:o,nft:n,amountA:r,amountB:c,slippage:10,address:e,collectAmountA:S,collectAmountB:w,rewardAmounts:d,deadline:l}}}decodePrixClaim(){return{txType:Vt.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:Vt.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:Vt.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:Vt.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:e,amountIn:t,token1:n,token2:o}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target!=="0x2::coin::zero"&&t.target!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero");return new le(e,this.txb)}get collectRewardHelper(){return this.transactions.filter(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::collect_reward`).map(t=>new le(t,this.txb))}get collectFeeHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::collect`);return new le(e,this.txb)}get decreaseLiquidityHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::decrease_liquidity`);return new le(e,this.txb)}get swapExactBaseForQuoteHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${zt.PackageId}::clob_v2::swap_exact_base_for_quote`);return new le(e,this.txb)}get swapExactQuoteForBaseHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${zt.PackageId}::clob_v2::swap_exact_quote_for_base`);return new le(e,this.txb)}},le=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU128(e){let t=this.decodePureArg(e,"u128");return Number(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU32(e){let t=this.decodePureArg(e,"u32");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return an(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Xc.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return an(e.value.Object.ImmOrOwned.objectId)}return an(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return an(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return an(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Xc.de(t,new Uint8Array(n))}typeArg(e){return yd(this.moveCall.typeArguments[e])}shortTypeArg(e){return this.moveCall.typeArguments[e]}txArg(e){return this.moveCall.arguments[e]}};import{TurbosSdk as Td}from"turbos-clmm-sdk";var nr=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Td(t.network.replace("sui:",""),t.suiClient),{pool:o,address:r,amountA:c,amountB:l,slippage:d,tickLower:S,tickUpper:w,deadline:I,txb:C}=this.data;return n.pool.addLiquidity({pool:o,slippage:d,address:r,amountA:c,amountB:l,tickLower:S,tickUpper:w,deadline:I,txb:C})}static fromData(t){return new a(t)}};import{TurbosSdk as wd}from"turbos-clmm-sdk";var or=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new wd(t.network.replace("sui:",""),t.suiClient),{pool:o,nft:r,txb:c}=this.data;return n.nft.burn({pool:o,nft:r,txb:c})}static fromData(t){return new a(t)}};import{TurbosSdk as Id}from"turbos-clmm-sdk";var ar=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Id(t.network.replace("sui:",""),t.suiClient),{pool:o,address:r,nft:c,collectAmountA:l,collectAmountB:d,deadline:S,txb:w}=this.data;return n.pool.collectFee({pool:o,address:r,collectAmountA:l,collectAmountB:d,nft:c,deadline:S,txb:w})}static fromData(t){return new a(t)}};import{TurbosSdk as Cd}from"turbos-clmm-sdk";var rr=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Cd(t.network.replace("sui:",""),t.suiClient),{pool:o,address:r,nft:c,rewardAmounts:l,deadline:d,txb:S}=this.data;return n.pool.collectReward({pool:o,address:r,rewardAmounts:l,nft:c,deadline:d,txb:S})}static fromData(t){return new a(t)}};import{TurbosSdk as kd}from"turbos-clmm-sdk";var ir=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new kd(t.network.replace("sui:",""),t.suiClient),{fee:o,address:r,tickLower:c,tickUpper:l,sqrtPrice:d,slippage:S,coinTypeA:w,coinTypeB:I,amountA:C,amountB:k,deadline:x,txb:P}=this.data;return n.pool.createPool({fee:o,amountA:C,amountB:k,address:r,tickLower:c,tickUpper:l,sqrtPrice:d,slippage:S,coinTypeA:w,coinTypeB:I,deadline:x,txb:P})}static fromData(t){return new a(t)}};import{TurbosSdk as vd}from"turbos-clmm-sdk";var sr=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new vd(t.network.replace("sui:",""),t.suiClient),{pool:o,address:r,amountA:c,amountB:l,slippage:d,nft:S,decreaseLiquidity:w,deadline:I,txb:C}=this.data;return n.pool.decreaseLiquidity({pool:o,slippage:d,address:r,amountA:c,amountB:l,nft:S,decreaseLiquidity:w,deadline:I,txb:C})}static fromData(t){return new a(t)}};import{TurbosSdk as xd}from"turbos-clmm-sdk";var cr=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new xd(t.network.replace("sui:",""),t.suiClient),{pool:o,address:r,amountA:c,amountB:l,slippage:d,nft:S,deadline:w,txb:I}=this.data;return n.pool.increaseLiquidity({pool:o,slippage:d,address:r,amountA:c,amountB:l,nft:S,deadline:w,txb:I})}static fromData(t){return new a(t)}};import{TransactionBlock as Dd}from"@mysten/sui.js/transactions";import{SUI_CLOCK_OBJECT_ID as Ad}from"@mysten/sui.js/utils";var lr=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Dd;return n.moveCall({target:`${Ht.PackageId}::claim::claim`,typeArguments:[Ht.turbosCoinType],arguments:[n.object(Ht.Claim),n.object(Ad)]}),n}static fromData(t){return new a(t)}};import{TransactionBlock as Od}from"@mysten/sui.js/transactions";var ur=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Od;return n.moveCall({target:`${Ht.PackageId}::claim::join`,typeArguments:[Ht.turbosCoinType],arguments:[n.object(Ht.Claim)]}),n}static fromData(t){return new a(t)}};import{TransactionBlock as Md}from"@mysten/sui.js/transactions";import{TurbosSdk as Pd}from"turbos-clmm-sdk";var mr=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Pd(t.network.replace("sui:",""),t.suiClient),o=new Md;return o=await n.pool.collectFee({txb:o,...this.data}),o=await n.pool.collectReward({txb:o,...this.data}),o=await n.pool.decreaseLiquidity({txb:o,...this.data}),o=await n.nft.burn({txb:o,nft:this.data.nft,pool:this.data.pool}),o}static fromData(t){return new a(t)}};import{TurbosSdk as Rd}from"turbos-clmm-sdk";var pr=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(this.data,"this.data");let n=new Rd(t.network.replace("sui:",""),t.suiClient),{routes:o,coinTypeA:r,coinTypeB:c,address:l,amountA:d,amountB:S,slippage:w,amountSpecifiedIsInput:I,deadline:C,txb:k}=this.data;return n.trade.swap({routes:o,coinTypeA:r,coinTypeB:c,address:l,amountA:d,amountB:S,amountSpecifiedIsInput:I,slippage:w,deadline:C,txb:k})}static fromData(t){return new a(t)}};import{TurbosSdk as Ed}from"turbos-clmm-sdk";import{TransactionBlock as Yc}from"@mysten/sui.js/transactions";import{normalizeSuiObjectId as Zc}from"@mysten/sui.js/utils";import{unstable_getObjectId as Bd}from"turbos-clmm-sdk";var rn=class{constructor(e){this.turbosSdk=e}async getCoinsData(e,t,n){let o=[],r;do r=await this.turbosSdk.provider.getCoins({owner:e,coinType:t,cursor:r?.nextCursor}),o.push(...r.data);while(r.hasNextPage);let c=[],l=0;return o.sort((d,S)=>Number(S.balance)-Number(d.balance)).some(d=>l>=n?!0:(l+=Number(d.balance),c.push(d),!1)),c}splitAndMergeCoin(e,t,n){if(!e||e.length<1)return[void 0,void 0];if(this.isSuiCoinAddress(e[0].coinType)){let[c]=n.splitCoins(n.gas,[n.pure(t)]);return[c,void 0]}let o=n.object(e[0].coinObjectId);e.length>1&&n.mergeCoins(o,e.slice(1).map(c=>n.object(c.coinObjectId)));let[r]=n.splitCoins(o,[n.pure(t)]);return[r,o]}isSuiCoinAddress(e){return e.toLocaleLowerCase()==="0x2::sui::sui"}async IsAccountCap(e){let t=await this.turbosSdk.provider.getOwnedObjects({owner:e,options:{showContent:!0,showType:!0,showOwner:!0},filter:{StructType:`${zt.PackageId}::custodian_v2::AccountCap`}});return t.data[0]?.data?Bd(t.data[0].data):void 0}createAccount(e){let[t]=e.moveCall({typeArguments:[],target:`${zt.PackageId}::clob_v2::create_account`,arguments:[]});return t}zero(e,t){return t.moveCall({typeArguments:[e],target:"0x2::coin::zero",arguments:[]})}};var tl=89,el=1e6,nl=async a=>{let{token1:e,token2:t,poolId:n,amountIn:o,currentAddress:r,turbosSdk:c}=a,l=new Yc,d=new rn(c),S=await d.getCoinsData(r,t,o),[w,I]=d.splitAndMergeCoin(S,o,l);if(!w)throw new Error(`Not enough balance: ${t}`);let C=await d.IsAccountCap(r),k=C?l.object(C):d.createAccount(l),[x,P,L]=l.moveCall({typeArguments:[e,t],target:`${zt.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[l.object(String(n)),l.pure(tl),k,l.pure(o),l.object(Zc("0x6")),w]});return I&&l.transferObjects([I],l.pure(r)),l.transferObjects([x],l.pure(r)),l.transferObjects([P],l.pure(r)),C||l.transferObjects([k],l.pure(r)),l.setSenderIfNotSet(r),l.setGasBudget(el),l},ol=async a=>{let{token1:e,token2:t,poolId:n,amountIn:o,currentAddress:r,turbosSdk:c}=a,l=new Yc,d=new rn(c),S=await d.getCoinsData(r,e,o),[w,I]=d.splitAndMergeCoin(S,o,l);if(!w)throw new Error(`Not enough balance: ${e}`);let C=await d.IsAccountCap(r),k=C?l.object(C):d.createAccount(l),x=d.zero(t,l),[P,L,V]=l.moveCall({typeArguments:[e,t],target:`${zt.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[l.object(String(n)),l.pure(tl),k,l.pure(o),w,x,l.object(Zc("0x6"))]});return I&&l.transferObjects([I],l.pure(r)),l.transferObjects([P],l.pure(r)),l.transferObjects([L],l.pure(r)),C||l.transferObjects([k],l.pure(r)),l.setSenderIfNotSet(r),l.setGasBudget(el),l};var dr=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Ed(t.network.replace("sui:",""),t.suiClient);return await ol({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new a(t)}};import{TurbosSdk as Nd}from"turbos-clmm-sdk";var fr=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let n=new Nd(t.network.replace("sui:",""),t.suiClient);return await nl({...this.data,turbosSdk:n,currentAddress:t.account.address})}static fromData(t){return new a(t)}};var hr=class{application="turbos";supportSDK="@mysten/sui.js";async deserialize(e){let t=new _d(e.network.replace("sui:",""),e.suiClient),n=await t.contract.getConfig(),{transactionBlock:o,account:r}=e;console.log(e,"input");let l=await new er(o,t,n).decode(r.address);return{txType:Wd.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e,r;switch(console.log(e.intentionData,"intentionData"),e.txSubType){case"CreatePool":r=ir.fromData(e.intentionData);break;case"AddLiquidity":r=nr.fromData(e.intentionData);break;case"IncreaseLiquidity":r=cr.fromData(e.intentionData);break;case"DecreaseLiquidity":r=sr.fromData(e.intentionData);break;case"RemoveLiquidity":r=mr.fromData(e.intentionData);break;case"CollectFee":r=ar.fromData(e.intentionData);break;case"CollectReward":r=rr.fromData(e.intentionData);break;case"Burn":r=or.fromData(e.intentionData);break;case"Swap":r=pr.fromData(e.intentionData);break;case"PrixJoin":r=ur.fromData(e.intentionData);break;case"PrixClaim":r=lr.fromData(e.intentionData);break;case"SwapExactBaseForQuote":r=dr.fromData(e.intentionData);break;case"SwapExactQuoteForBase":r=fr.fromData(e.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:t,account:n,network:o})}};import{TransactionType as Vd}from"@msafe/sui3-utils";import{TransactionType as Ki}from"@msafe/sui3-utils";import{bcs as al}from"@mysten/sui.js/bcs";import{normalizeStructTag as Ud,normalizeSuiAddress as sn}from"@mysten/sui.js/utils";var Ld={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},Dt=Ld;var gr=class{constructor(e){this.txb=e}decode(){if(console.log("txb",this.txb),this.isStakeTransaction())return this.decodeStake();if(this.isUnStakeTransaction())return this.decodeUnStake();if(this.isClaimTicketTransaction())return this.decodeClaimTicket();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}isStakeTransaction(){return!!this.getMoveCallTransaction(`${Dt.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${Dt.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${Dt.packageId}::native_pool::burn_ticket`)}decodeStake(){let e=this.transactions[0].amounts[0].value.toNumber();return{txType:Ki.Other,type:"Stake",intentionData:{amount:e}}}decodeUnStake(){let t=this.transactions.find(n=>n.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:Ki.Other,type:"UnStake",intentionData:{amount:t}}}decodeClaimTicket(){let e=this.helper.decodeOwnedObjectId(2);return console.log(e),{txType:Ki.Other,type:"ClaimTicket",intentionData:{ticketId:e}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target.startsWith(Dt.packageId));return new Vi(e,this.txb)}},Vi=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return sn(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return a.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return al.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return sn(e.value.Object.ImmOrOwned.objectId)}return sn(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return sn(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return sn(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return al.de(t,new Uint8Array(n))}typeArg(e){return Ud(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};import{TransactionBlock as qd}from"@mysten/sui.js/transactions";var yr=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new qd,{ticketId:o}=this.data;return n.moveCall({target:`${Dt.packageId}::native_pool::burn_ticket`,arguments:[n.object(Dt.poolObjectId),n.object(Dt.systemStateObjectId),n.object(o)]}),n}static fromData(t){return new a(t)}};import{TransactionBlock as Fd}from"@mysten/sui.js/transactions";var br=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new Fd,{amount:o}=this.data,[r]=n.splitCoins(n.gas,[n.pure(o)]);return n.moveCall({target:`${Dt.packageId}::native_pool::stake`,arguments:[n.object(Dt.poolObjectId),n.object(Dt.metadataObjectId),n.object(Dt.systemStateObjectId),r]}),n}static fromData(t){return new a(t)}};import{TransactionBlock as Kd}from"@mysten/sui.js/transactions";var Sr=class a extends R{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let n=new Kd,{amount:o}=this.data,r=(await t.suiClient.getAllCoins({owner:t.account.address,limit:100})).data,[c,...l]=r.filter(w=>w.coinType.split("::")[0]===Dt.certType.split("::")[0]),d=n.object(c.coinObjectId);l.length&&n.mergeCoins(d,l.map(w=>n.object(w.coinObjectId)));let S=n.splitCoins(n.object(c.coinObjectId),[n.pure(o)]);return n.moveCall({target:`${Dt.packageId}::native_pool::unstake`,arguments:[n.object(Dt.poolObjectId),n.object(Dt.metadataObjectId),n.object(Dt.systemStateObjectId),S]}),n}static fromData(t){return new a(t)}};var Tr=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(e){let{transactionBlock:t}=e,o=new gr(t).decode();return{txType:Vd.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n}=e,o;switch(e.txSubType){case"Stake":o=br.fromData(e.intentionData);break;case"UnStake":o=Sr.fromData(e.intentionData);break;case"ClaimTicket":o=yr.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({suiClient:t,account:n})}};import{TransactionType as ef}from"@msafe/sui3-utils";import{asIntN as rl}from"@cetusprotocol/common-sdk";import{TransactionType as ye}from"@msafe/sui3-utils";import{fromBase64 as cn}from"@mysten/bcs";import{bcs as ln}from"@mysten/sui/bcs";var wr=class{constructor(e){this.transaction=e}decode(){if(this.isOpenPositionTx())return this.decodeOpenPositionTx();if(this.isClosePositionTx())return this.decodeClosePositionTx();if(this.isProvideLiquidityTx())return this.decodeProvideLiquidityTx();if(this.isRemoveLiquidityTx())return this.decodeRemoveLiquidityTx();if(this.isCollectRewardsAndFeeTx())return this.decodeCollectRewardsAndFeeTx();if(this.isCollectRewardsTx())return this.decodeCollectRewardsTx();if(this.isCollectFeeTx())return this.decodeCollectFeeTx();throw new Error("Unknown transaction type")}decodeOpenPositionTx(){let e=this.getMoveCallCommand("open_position"),t=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:ye.Other,type:"OpenPosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,1)),lowerTick:Number(rl(BigInt(this.getU32(this.getInputIndex(e,2)))).toString()),upperTick:Number(rl(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:ye.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:ye.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:ye.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:ye.Other,type:"CollectRewards",intentionData:{pool:e[0].pool,position:e[0].position,collectRewardTokens:e.map(t=>t.rewardCoinType)}}}decodeCollectFeeTx(){return{txType:ye.Other,type:"CollectFee",intentionData:this.getFeeCallData()}}decodeCollectRewardsAndFeeTx(){let e=this.getFeeCallData();return{txType:ye.Other,type:"CollectRewardsAndFee",intentionData:{pool:e.pool,position:e.position,...this.collectTokens()}}}getFeeCallData(){let e=this.getMoveCallCommand("collect_fee");return{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),collectFeeTokens:this.getTypeArguments(e)}}getCollectRewardCallData(){let e=[];return this.commands.forEach(t=>{t.$kind==="MoveCall"&&t.MoveCall.function==="collect_reward"&&e.push({pool:this.getSharedObjectID(this.getInputIndex(t,2)),position:this.getOwnedObjectID(this.getInputIndex(t,3)),rewardCoinType:this.getTypeArguments(t)[2]})}),e}collectTokens(){let e=this.getFeeCallData(),t=this.getCollectRewardCallData();return{collectFeeTokens:e.collectFeeTokens,collectRewardTokens:t.map(n=>n.rewardCoinType)}}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}isOpenPositionTx(){return!!this.getMoveCallCommand("open_position")}isProvideLiquidityTx(){return!!this.getMoveCallCommand("provide_liquidity_with_fixed_amount")}isRemoveLiquidityTx(){return!!this.getMoveCallCommand("remove_liquidity")}isCollectRewardsTx(){return!!this.getMoveCallCommand("collect_reward")}isCollectFeeTx(){return!!this.getMoveCallCommand("collect_fee")}isCollectRewardsAndFeeTx(){return this.isCollectRewardsTx()&&this.isCollectFeeTx()}isClosePositionTx(){return!!this.getMoveCallCommand("close_position")}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getSharedObjectID(e){return this.inputs[e].Object.SharedObject.objectId}getOwnedObjectID(e){return this.inputs[e].Object.ImmOrOwnedObject.objectId}getU32(e){return String(ln.u32().parse(Uint8Array.from(cn(this.inputs[e].Pure.bytes))))}getU64(e){return ln.u64().parse(Uint8Array.from(cn(this.inputs[e].Pure.bytes)))}getU128(e){return ln.u128().parse(Uint8Array.from(cn(this.inputs[e].Pure.bytes)))}getBoolean(e){return ln.bool().parse(Uint8Array.from(cn(this.inputs[e].Pure.bytes)))}getAddress(e){return ln.Address.parse(Uint8Array.from(cn(this.inputs[e].Pure.bytes)))}getTypeArguments(e){return e.MoveCall.typeArguments||[]}getInputIndex(e,t){return e.MoveCall.arguments[t].Input}};import{TransactionType as Gd}from"@msafe/sui3-utils";import{BN as be,ClmmPoolUtil as zd}from"@firefly-exchange/library-sui";import{SuiClient as $d}from"@firefly-exchange/library-sui";import{OnChainCalls as Hd}from"@firefly-exchange/library-sui/dist/src/spot";var il={rpc:"https://fullnode.mainnet.sui.io/",objects:{GlobalConfig:"0x03db251ba509a8d5d8777b6338836082335d93eecbdd09a11e190a1cff51c352",BasePackage:"0x3492c874c1e3b3e2984e8c41b589e642d4d0a5d6459e5a9cfc2d52fd7c89c267",CurrentPackage:"0x67b34b728c4e28e704dcfecf7c5cf55c7fc593b6c65c20d1836d97c209c1928a"}},me=(a,e)=>{if(a!=="sui:mainnet")throw new Error("Bluefin spot protocol is only available on sui::mainnet");let t=new $d({url:il.rpc});return new Hd(t,il.objects,{address:e.address,isUIWallet:!1})};var Pt=class{static async OpenPosition(e,t,n){let o=me(n,t),r=await o.queryChain.getPool(e.pool),c=this.prototype.buildLiqInput(r,{...e,slippage:0});return await o.openPositionWithFixedAmount(r,e.lowerTick,e.upperTick,c,{returnTx:!0,sender:t.address})}static async provideLiquidity(e,t,n){let o=me(n,t),r=await o.queryChain.getPool(e.pool),c=this.prototype.buildLiqInput(r,e);return await o.provideLiquidityWithFixedAmount(r,e.position,c,{returnTx:!0,sender:t.address})}static async removeLiquidity(e,t,n){let o=me(n,t),r=await o.queryChain.getPool(e.pool);return await o.removeLiquidity(r,e.position,{liquidityAmount:new be(e.liquidity),tokenMaxA:new be(e.maxAmountTokenA),tokenMaxB:new be(e.maxAmountTokenB)},{returnTx:!0,sender:t.address})}static async closePosition(e,t,n){let o=me(n,t),r=await o.queryChain.getPool(e.pool);return await o.closePosition(r,e.position,{returnTx:!0,sender:t.address})}static async collectRewards(e,t,n){let o=me(n,t),r=await o.queryChain.getPool(e.pool);return await o.collectRewards(r,e.position,{rewardCoinsType:e.collectRewardTokens,returnTx:!0,sender:t.address})}static async collectFee(e,t,n){let o=me(n,t),r=await o.queryChain.getPool(e.pool);return await o.collectFee(r,e.position,{returnTx:!0,sender:t.address})}static async collectRewardsAndFee(e,t,n){let o=me(n,t),r=await o.queryChain.getPool(e.pool);return console.log(e.position),await o.collectFeeAndRewards(r,e.position,{returnTx:!0,sender:t.address})}buildLiqInput(e,t){return{...zd.estLiquidityAndCoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new be(t.tokenAmount),t.isTokenAFixed,!0,0,new be(e.current_sqrt_price)),tokenMaxA:new be(t.maxAmountTokenA),tokenMaxB:new be(t.maxAmountTokenB)}}};var Ir=class a extends v{constructor(t){super(t);this.data=t}txType=Gd.Other;txSubType="ClosePosition";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.closePosition(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Qd}from"@msafe/sui3-utils";var Cr=class a extends v{constructor(t){super(t);this.data=t}txType=Qd.Other;txSubType="CollectFee";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.collectFee(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Jd}from"@msafe/sui3-utils";var kr=class a extends v{constructor(t){super(t);this.data=t}txType=Jd.Other;txSubType="CollectRewards";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.collectRewards(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Xd}from"@msafe/sui3-utils";var vr=class a extends v{constructor(t){super(t);this.data=t}txType=Xd.Other;txSubType="CollectRewardsAndFee";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.collectRewardsAndFee(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Yd}from"@msafe/sui3-utils";var xr=class a extends v{constructor(t){super(t);this.data=t}txType=Yd.Other;txSubType="OpenPosition";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.OpenPosition(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as Zd}from"@msafe/sui3-utils";var Dr=class a extends v{constructor(t){super(t);this.data=t}txType=Zd.Other;txSubType="ProvideLiquidity";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.provideLiquidity(this.data,n,o)}static fromData(t){return new a(t)}};import{TransactionType as tf}from"@msafe/sui3-utils";var Ar=class a extends v{constructor(t){super(t);this.data=t}txType=tf.Other;txSubType="RemoveLiquidity";async build(t){let{account:n,network:o}=t;return console.log(this.data),Pt.removeLiquidity(this.data,n,o)}static fromData(t){return new a(t)}};var Or=class{application="bluefin";supportSDK="@mysten/sui";async deserialize(e){console.log("Bluefin helper deserialize input: ",e);let{transaction:t}=e,o=new wr(t).decode();return{txType:ef.Other,txSubType:o.type,intentionData:o.intentionData}}async build(e){let{suiClient:t,account:n,network:o}=e;console.log(e.txSubType);let r;switch(e.txSubType){case"OpenPosition":r=xr.fromData(e.intentionData);break;case"ProvideLiquidity":r=Dr.fromData(e.intentionData);break;case"RemoveLiquidity":r=Ar.fromData(e.intentionData);break;case"ClosePosition":r=Ir.fromData(e.intentionData);break;case"CollectFee":r=Cr.fromData(e.intentionData);break;case"CollectRewards":r=kr.fromData(e.intentionData);break;case"CollectRewardsAndFee":r=vr.fromData(e.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:t,account:n,network:o})}};import{TransactionType as Cf}from"@msafe/sui3-utils";import{MmtSDK as lf}from"@mmt-finance/clmm-sdk";import{Transaction as uf}from"@mysten/sui/transactions";var B=wl(cl());import{convertI32ToSigned as un,TickMath as ll}from"@mmt-finance/clmm-sdk/dist/utils/math/tickMath";var nf="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",Gt=a=>a!=="0x2::sui::SUI"?a:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",of=async({suiClient:a,address:e,type:t})=>{let n,o=[],r=0;do{try{let c=await a.getCoins({owner:e,coinType:t,cursor:n,limit:50});o=o.concat(c.data),n=c.nextCursor,(!c.hasNextPage||r===8)&&(n=null)}catch(c){console.log(c),n=null}r++}while(n!==null);return o},af=(a,e)=>{let t=[],n=BigInt(0);for(let o of e)n<a&&!t.includes(o.objectId)&&(t.push(o.objectId),n+=BigInt(o.balance)),o.balance===BigInt(0)&&!t.includes(o.objectId)&&t.push(o.objectId);if(n>=a)return t;throw new Error("Insufficient balance")},rf=(a,e,t,n)=>{if(a===nf){let[o]=n.splitCoins(n.gas,[n.pure.u64(t)]);return o}else{let o=af(t,e);o.length>1&&n.mergeCoins(n.object(o[0]),o.slice(1).map(c=>n.object(c)));let[r]=n.splitCoins(n.object(o[0]),[n.pure.u64(t)]);return r}};async function Ee(a,e,t,n,o){let r=await of({suiClient:a.rpcClient,address:e,type:t});return rf(Gt(t),r.map(l=>({balance:BigInt(l.balance),objectId:l.coinObjectId})),n,o)}function N(a,e,t){let n=a.toTwos(t).shrn(e);return n.imaskn(t-e+1),n.fromTwos(t-e)}function sf(a){let e;return a&1?e=new B.default("79232123823359799118286999567"):e=new B.default("79228162514264337593543950336"),a&2&&(e=N(e.mul(new B.default("79236085330515764027303304731")),96,256)),a&4&&(e=N(e.mul(new B.default("79244008939048815603706035061")),96,256)),a&8&&(e=N(e.mul(new B.default("79259858533276714757314932305")),96,256)),a&16&&(e=N(e.mul(new B.default("79291567232598584799939703904")),96,256)),a&32&&(e=N(e.mul(new B.default("79355022692464371645785046466")),96,256)),a&64&&(e=N(e.mul(new B.default("79482085999252804386437311141")),96,256)),a&128&&(e=N(e.mul(new B.default("79736823300114093921829183326")),96,256)),a&256&&(e=N(e.mul(new B.default("80248749790819932309965073892")),96,256)),a&512&&(e=N(e.mul(new B.default("81282483887344747381513967011")),96,256)),a&1024&&(e=N(e.mul(new B.default("83390072131320151908154831281")),96,256)),a&2048&&(e=N(e.mul(new B.default("87770609709833776024991924138")),96,256)),a&4096&&(e=N(e.mul(new B.default("97234110755111693312479820773")),96,256)),a&8192&&(e=N(e.mul(new B.default("119332217159966728226237229890")),96,256)),a&16384&&(e=N(e.mul(new B.default("179736315981702064433883588727")),96,256)),a&32768&&(e=N(e.mul(new B.default("407748233172238350107850275304")),96,256)),a&65536&&(e=N(e.mul(new B.default("2098478828474011932436660412517")),96,256)),a&131072&&(e=N(e.mul(new B.default("55581415166113811149459800483533")),96,256)),a&262144&&(e=N(e.mul(new B.default("38992368544603139932233054999993551")),96,256)),N(e,32,256)}function cf(a){let e=Math.abs(a),t;return e&1?t=new B.default("18445821805675392311"):t=new B.default("18446744073709551616"),e&2&&(t=N(t.mul(new B.default("18444899583751176498")),64,256)),e&4&&(t=N(t.mul(new B.default("18443055278223354162")),64,256)),e&8&&(t=N(t.mul(new B.default("18439367220385604838")),64,256)),e&16&&(t=N(t.mul(new B.default("18431993317065449817")),64,256)),e&32&&(t=N(t.mul(new B.default("18417254355718160513")),64,256)),e&64&&(t=N(t.mul(new B.default("18387811781193591352")),64,256)),e&128&&(t=N(t.mul(new B.default("18329067761203520168")),64,256)),e&256&&(t=N(t.mul(new B.default("18212142134806087854")),64,256)),e&512&&(t=N(t.mul(new B.default("17980523815641551639")),64,256)),e&1024&&(t=N(t.mul(new B.default("17526086738831147013")),64,256)),e&2048&&(t=N(t.mul(new B.default("16651378430235024244")),64,256)),e&4096&&(t=N(t.mul(new B.default("15030750278693429944")),64,256)),e&8192&&(t=N(t.mul(new B.default("12247334978882834399")),64,256)),e&16384&&(t=N(t.mul(new B.default("8131365268884726200")),64,256)),e&32768&&(t=N(t.mul(new B.default("3584323654723342297")),64,256)),e&65536&&(t=N(t.mul(new B.default("696457651847595233")),64,256)),e&131072&&(t=N(t.mul(new B.default("26294789957452057")),64,256)),e&262144&&(t=N(t.mul(new B.default("37481735321082")),64,256)),t}var Mr=(a,e,t)=>{let n=un(t?a+a%(e??1):a-a%(e??1));return n>0?new B.default(sf(n)):new B.default(cf(n))},ul=async(a,e,t,n,o,r,c,l,d)=>{let S=Mr(un(l),r.tickSpacing),w=Mr(un(d),r.tickSpacing),I=BigInt(Math.ceil(Number(n)*10**r.tokenX.decimals)),C=BigInt(Math.ceil(Number(o)*10**r.tokenY.decimals)),k,x;Number(n)?k=await Ee(a,t,Gt(r.tokenX.coinType),I,e):[k]=e.moveCall({target:"0x2::coin::zero",typeArguments:[r.tokenX.coinType],arguments:[]}),Number(o)?x=await Ee(a,t,Gt(r.tokenY.coinType),C,e):[x]=e.moveCall({target:"0x2::coin::zero",typeArguments:[r.tokenY.coinType],arguments:[]});let P={objectId:c,tokenXType:r.tokenXType,tokenYType:r.tokenYType,tickSpacing:r.tickSpacing},L=a.Position.openPosition(e,P,S.toString(),w.toString());a.Pool.addLiquidity(e,P,L,k,x,BigInt(0),BigInt(0),t),e.transferObjects([L],e.pure.address(t))},ml=async(a,e,t,n,o,r,c,l,d)=>{try{let S=BigInt(Math.ceil(Number(o)*10**(r?c.tokenX.decimals:c.tokenY.decimals))),w=r?c.tokenX.coinType:c.tokenY.coinType;w=Gt(w);let I=await Ee(a,n,w,S,e),C={objectId:c.poolId,tokenXType:Gt(c.tokenX.coinType),tokenYType:Gt(c.tokenY.coinType),tickSpacing:c.tickSpacing},k=Mr(un(l),c.tickSpacing),x=Mr(un(d),c.tickSpacing),P=a.Position.openPosition(e,C,k.toString(),x.toString()),V=(await t.getObject({id:c.poolId,options:{showContent:!0}}))?.data?.content?.fields?.sqrt_price??c.currentSqrtPrice,Wt=ll.sqrtPriceX64ToPrice(new B.default(V?.toString()),c.tokenX.decimals,c.tokenY.decimals),Bt=ll.priceToSqrtPriceX64(Wt.mul(r?.99:1.01),c.tokenX.decimals,c.tokenY.decimals);await a.Pool.addLiquiditySingleSided(e,C,P,I,BigInt(0),BigInt(0),r,n,BigInt(Bt.toString())),e.transferObjects([P],e.pure.address(n))}catch(S){console.error(S)}};var Pr=class a extends v{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=lf.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,amountA:r,amountB:c,pool:l,selectedLowTick:d,selectedHighTick:S}=n,w=new uf;return await ul(t,w,o,r,c,l,l.poolId,d,S),w}static fromData(t){return new a(t)}};import{MmtSDK as mf}from"@mmt-finance/clmm-sdk";import{Transaction as pf}from"@mysten/sui/transactions";var Rr=class a extends v{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=mf.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,amount:r,isTokenX:c,pool:l,selectedLowTick:d,selectedHighTick:S}=n,w=new pf;return await ml(t,w,t.rpcClient,o,r,c,l,d,S),w}static fromData(t){return new a(t)}};import{MmtSDK as df}from"@mmt-finance/clmm-sdk";import{Transaction as ff}from"@mysten/sui/transactions";var Ne=(a,e,t,n,o)=>{let r={objectId:n.poolId,tokenXType:n.tokenXType,tokenYType:n.tokenYType};(n?.rewarders?.length??0)>0&&a.Pool.collectAllRewards(o,r,n.rewarders.map(c=>({coin_type:c.coinType,flow_rate:c.flowRate,reward_amount:c.rewardAmount,rewards_allocated:c.rewardsAllocated,hasEnded:c.hasEnded})),t.objectId,e),a.Pool.collectFee(o,{objectId:n.poolId,tokenXType:n.tokenXType,tokenYType:n.tokenYType,isStable:n.isStable,tickSpacing:n.tickSpacing},t.objectId,e)};var Br=class a extends v{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=df.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,positions:r,pools:c}=n,l=new ff;for(let d of r){let S=c.find(w=>w.poolId===d.poolId);Ne(t,o,d,S,l)}return l}static fromData(t){return new a(t)}};import{MmtSDK as hf}from"@mmt-finance/clmm-sdk";import{Transaction as gf}from"@mysten/sui/transactions";var Er=class a extends v{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=hf.NEW({network:"mainnet"}),{params:n}=this.data,{address:o,position:r,pool:c}=n,l=new gf;return Ne(t,o,r,c,l),l}static fromData(t){return new a(t)}};import{MmtSDK as yf}from"@mmt-finance/clmm-sdk";import{Transaction as bf}from"@mysten/sui/transactions";import Sf from"bignumber.js";var Nr=class a extends v{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=yf.NEW({network:"mainnet"}),{params:n}=this.data,{pool:o,position:r,address:c,withdrawPercentage:l}=n,d=new bf,S=o.tokenX.coinType,w=o.tokenY.coinType,I={objectId:o.poolId,tokenXType:S,tokenYType:w},C=BigInt(l===100?r.liquidity:new Sf(r.liquidity).multipliedBy(l/100).toFixed(0));return t.Pool.removeLiquidity(d,I,r.objectId,C,BigInt(0),BigInt(0),c),Ne(t,c,r,o,d),l===100&&t.Position.closePosition(d,r.objectId),d}static fromData(t){return new a(t)}};import{MmtSDK as wf}from"@mmt-finance/clmm-sdk";import{Transaction as If}from"@mysten/sui/transactions";import{mappedMmtV3Pool as Tf}from"@mmt-finance/clmm-sdk/dist/utils/poolUtils";var pl=async(a,e,t,n,o,r)=>{let c=BigInt(Math.ceil(Number(n)*10**t.decimals)),l=await Ee(a,o,Gt(t.coinType),c,r),d=t.coinType;for(let S=0;S<e.length;S+=1){let{poolId:w,tokenX:I,tokenY:C,isStable:k}=e[S],{id:x,isReverse:P}=Tf[w]||{id:w,isReverse:!1},L=Gt(I.coinType)===Gt(d);L=P?!L:L;let V=P?C.coinType:I.coinType,Wt=P?I.coinType:C.coinType,Bt=a.Pool.swap(r,{objectId:x,tokenXType:V,tokenYType:Wt,isStable:k},c,l,L,void 0);r.transferObjects([l],r.pure.address(o)),l=Bt,d=L?Wt:V,[c]=r.moveCall({target:"0x2::coin::value",typeArguments:[d],arguments:[l]})}r.transferObjects([l],r.pure.address(o))};var Wr=class a extends v{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=wf.NEW({network:"mainnet"}),{params:n}=this.data,{route:o,tokenIn:r,amountIn:c,address:l}=n,d=new If;return await pl(t,o,r,c,l,d),d}static fromData(t){return new a(t)}};var _r=class{application="mmt-dex";supportSDK="@mysten/sui";async deserialize(e){let{appContext:t}=e;return{txType:Cf.Other,txSubType:t.action,intentionData:t}}async build(e){let t;switch(e.txSubType){case"Swap":t=Wr.fromData(e.intentionData);break;case"AddLiquidity":t=Pr.fromData(e.intentionData);break;case"AddLiquiditySingleSide":t=Rr.fromData(e.intentionData);break;case"ClaimRewards":t=Er.fromData(e.intentionData);break;case"ClaimAllRewards":t=Br.fromData(e.intentionData);break;case"RemoveLiquidity":t=Nr.fromData(e.intentionData);break;default:throw new Error("not implemented")}return t.build()}};var sN=ta.fromHelpers([new Uo,new Jo,new _o,new Xo,new uo,new hr,new _r,new Ba,new Tr,new Ln,new Ka,new Ja,new Tn,new Or,new tr]);export{sN as appHelpers};
1
+ var xl=Object.create;var ir=Object.defineProperty;var vl=Object.getOwnPropertyDescriptor;var Dl=Object.getOwnPropertyNames;var Al=Object.getPrototypeOf,Ol=Object.prototype.hasOwnProperty;var Ml=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var Pl=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),hs=(a,e)=>{for(var t in e)ir(a,t,{get:e[t],enumerable:!0})},Rl=(a,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Dl(e))!Ol.call(a,n)&&n!==t&&ir(a,n,{get:()=>e[n],enumerable:!(o=vl(e,n))||o.enumerable});return a};var Bl=(a,e,t)=>(t=a!=null?xl(Al(a)):{},Rl(e||!a||!a.__esModule?ir(t,"default",{value:a,enumerable:!0}):t,a));var pl=Pl((ml,$r)=>{"use strict";(function(a,e){"use strict";function t(y,r){if(!y)throw new Error(r||"Assertion failed")}function o(y,r){y.super_=r;var u=function(){};u.prototype=r.prototype,y.prototype=new u,y.prototype.constructor=y}function n(y,r,u){if(n.isBN(y))return y;this.negative=0,this.words=null,this.length=0,this.red=null,y!==null&&((r==="le"||r==="be")&&(u=r,r=10),this._init(y||0,r||10,u||"be"))}typeof a=="object"?a.exports=n:e.BN=n,n.BN=n,n.wordSize=26;var i;try{typeof window<"u"&&typeof window.Buffer<"u"?i=window.Buffer:i=Ml("buffer").Buffer}catch{}n.isBN=function(r){return r instanceof n?!0:r!==null&&typeof r=="object"&&r.constructor.wordSize===n.wordSize&&Array.isArray(r.words)},n.max=function(r,u){return r.cmp(u)>0?r:u},n.min=function(r,u){return r.cmp(u)<0?r:u},n.prototype._init=function(r,u,m){if(typeof r=="number")return this._initNumber(r,u,m);if(typeof r=="object")return this._initArray(r,u,m);u==="hex"&&(u=16),t(u===(u|0)&&u>=2&&u<=36),r=r.toString().replace(/\s+/g,"");var p=0;r[0]==="-"&&(p++,this.negative=1),p<r.length&&(u===16?this._parseHex(r,p,m):(this._parseBase(r,u,p),m==="le"&&this._initArray(this.toArray(),u,m)))},n.prototype._initNumber=function(r,u,m){r<0&&(this.negative=1,r=-r),r<67108864?(this.words=[r&67108863],this.length=1):r<4503599627370496?(this.words=[r&67108863,r/67108864&67108863],this.length=2):(t(r<9007199254740992),this.words=[r&67108863,r/67108864&67108863,1],this.length=3),m==="le"&&this._initArray(this.toArray(),u,m)},n.prototype._initArray=function(r,u,m){if(t(typeof r.length=="number"),r.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(r.length/3),this.words=new Array(this.length);for(var p=0;p<this.length;p++)this.words[p]=0;var h,b,T=0;if(m==="be")for(p=r.length-1,h=0;p>=0;p-=3)b=r[p]|r[p-1]<<8|r[p-2]<<16,this.words[h]|=b<<T&67108863,this.words[h+1]=b>>>26-T&67108863,T+=24,T>=26&&(T-=26,h++);else if(m==="le")for(p=0,h=0;p<r.length;p+=3)b=r[p]|r[p+1]<<8|r[p+2]<<16,this.words[h]|=b<<T&67108863,this.words[h+1]=b>>>26-T&67108863,T+=24,T>=26&&(T-=26,h++);return this._strip()};function c(y,r){var u=y.charCodeAt(r);if(u>=48&&u<=57)return u-48;if(u>=65&&u<=70)return u-55;if(u>=97&&u<=102)return u-87;t(!1,"Invalid character in "+y)}function l(y,r,u){var m=c(y,u);return u-1>=r&&(m|=c(y,u-1)<<4),m}n.prototype._parseHex=function(r,u,m){this.length=Math.ceil((r.length-u)/6),this.words=new Array(this.length);for(var p=0;p<this.length;p++)this.words[p]=0;var h=0,b=0,T;if(m==="be")for(p=r.length-1;p>=u;p-=2)T=l(r,u,p)<<h,this.words[b]|=T&67108863,h>=18?(h-=18,b+=1,this.words[b]|=T>>>26):h+=8;else{var f=r.length-u;for(p=f%2===0?u+1:u;p<r.length;p+=2)T=l(r,u,p)<<h,this.words[b]|=T&67108863,h>=18?(h-=18,b+=1,this.words[b]|=T>>>26):h+=8}this._strip()};function d(y,r,u,m){for(var p=0,h=0,b=Math.min(y.length,u),T=r;T<b;T++){var f=y.charCodeAt(T)-48;p*=m,f>=49?h=f-49+10:f>=17?h=f-17+10:h=f,t(f>=0&&h<m,"Invalid character"),p+=h}return p}n.prototype._parseBase=function(r,u,m){this.words=[0],this.length=1;for(var p=0,h=1;h<=67108863;h*=u)p++;p--,h=h/u|0;for(var b=r.length-m,T=b%p,f=Math.min(b,b-T)+m,s=0,g=m;g<f;g+=p)s=d(r,g,g+p,u),this.imuln(h),this.words[0]+s<67108864?this.words[0]+=s:this._iaddn(s);if(T!==0){var D=1;for(s=d(r,g,r.length,u),g=0;g<T;g++)D*=u;this.imuln(D),this.words[0]+s<67108864?this.words[0]+=s:this._iaddn(s)}this._strip()},n.prototype.copy=function(r){r.words=new Array(this.length);for(var u=0;u<this.length;u++)r.words[u]=this.words[u];r.length=this.length,r.negative=this.negative,r.red=this.red};function S(y,r){y.words=r.words,y.length=r.length,y.negative=r.negative,y.red=r.red}if(n.prototype._move=function(r){S(r,this)},n.prototype.clone=function(){var r=new n(null);return this.copy(r),r},n.prototype._expand=function(r){for(;this.length<r;)this.words[this.length++]=0;return this},n.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},n.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{n.prototype[Symbol.for("nodejs.util.inspect.custom")]=w}catch{n.prototype.inspect=w}else n.prototype.inspect=w;function w(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var I=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],C=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],x=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];n.prototype.toString=function(r,u){r=r||10,u=u|0||1;var m;if(r===16||r==="hex"){m="";for(var p=0,h=0,b=0;b<this.length;b++){var T=this.words[b],f=((T<<p|h)&16777215).toString(16);h=T>>>24-p&16777215,p+=2,p>=26&&(p-=26,b--),h!==0||b!==this.length-1?m=I[6-f.length]+f+m:m=f+m}for(h!==0&&(m=h.toString(16)+m);m.length%u!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}if(r===(r|0)&&r>=2&&r<=36){var s=C[r],g=x[r];m="";var D=this.clone();for(D.negative=0;!D.isZero();){var O=D.modrn(g).toString(r);D=D.idivn(g),D.isZero()?m=O+m:m=I[s-O.length]+O+m}for(this.isZero()&&(m="0"+m);m.length%u!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}t(!1,"Base should be between 2 and 36")},n.prototype.toNumber=function(){var r=this.words[0];return this.length===2?r+=this.words[1]*67108864:this.length===3&&this.words[2]===1?r+=4503599627370496+this.words[1]*67108864:this.length>2&&t(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-r:r},n.prototype.toJSON=function(){return this.toString(16,2)},i&&(n.prototype.toBuffer=function(r,u){return this.toArrayLike(i,r,u)}),n.prototype.toArray=function(r,u){return this.toArrayLike(Array,r,u)};var v=function(r,u){return r.allocUnsafe?r.allocUnsafe(u):new r(u)};n.prototype.toArrayLike=function(r,u,m){this._strip();var p=this.byteLength(),h=m||Math.max(1,p);t(p<=h,"byte array longer than desired length"),t(h>0,"Requested array length <= 0");var b=v(r,h),T=u==="le"?"LE":"BE";return this["_toArrayLike"+T](b,p),b},n.prototype._toArrayLikeLE=function(r,u){for(var m=0,p=0,h=0,b=0;h<this.length;h++){var T=this.words[h]<<b|p;r[m++]=T&255,m<r.length&&(r[m++]=T>>8&255),m<r.length&&(r[m++]=T>>16&255),b===6?(m<r.length&&(r[m++]=T>>24&255),p=0,b=0):(p=T>>>24,b+=2)}if(m<r.length)for(r[m++]=p;m<r.length;)r[m++]=0},n.prototype._toArrayLikeBE=function(r,u){for(var m=r.length-1,p=0,h=0,b=0;h<this.length;h++){var T=this.words[h]<<b|p;r[m--]=T&255,m>=0&&(r[m--]=T>>8&255),m>=0&&(r[m--]=T>>16&255),b===6?(m>=0&&(r[m--]=T>>24&255),p=0,b=0):(p=T>>>24,b+=2)}if(m>=0)for(r[m--]=p;m>=0;)r[m--]=0},Math.clz32?n.prototype._countBits=function(r){return 32-Math.clz32(r)}:n.prototype._countBits=function(r){var u=r,m=0;return u>=4096&&(m+=13,u>>>=13),u>=64&&(m+=7,u>>>=7),u>=8&&(m+=4,u>>>=4),u>=2&&(m+=2,u>>>=2),m+u},n.prototype._zeroBits=function(r){if(r===0)return 26;var u=r,m=0;return u&8191||(m+=13,u>>>=13),u&127||(m+=7,u>>>=7),u&15||(m+=4,u>>>=4),u&3||(m+=2,u>>>=2),u&1||m++,m},n.prototype.bitLength=function(){var r=this.words[this.length-1],u=this._countBits(r);return(this.length-1)*26+u};function R(y){for(var r=new Array(y.bitLength()),u=0;u<r.length;u++){var m=u/26|0,p=u%26;r[u]=y.words[m]>>>p&1}return r}n.prototype.zeroBits=function(){if(this.isZero())return 0;for(var r=0,u=0;u<this.length;u++){var m=this._zeroBits(this.words[u]);if(r+=m,m!==26)break}return r},n.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},n.prototype.toTwos=function(r){return this.negative!==0?this.abs().inotn(r).iaddn(1):this.clone()},n.prototype.fromTwos=function(r){return this.testn(r-1)?this.notn(r).iaddn(1).ineg():this.clone()},n.prototype.isNeg=function(){return this.negative!==0},n.prototype.neg=function(){return this.clone().ineg()},n.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},n.prototype.iuor=function(r){for(;this.length<r.length;)this.words[this.length++]=0;for(var u=0;u<r.length;u++)this.words[u]=this.words[u]|r.words[u];return this._strip()},n.prototype.ior=function(r){return t((this.negative|r.negative)===0),this.iuor(r)},n.prototype.or=function(r){return this.length>r.length?this.clone().ior(r):r.clone().ior(this)},n.prototype.uor=function(r){return this.length>r.length?this.clone().iuor(r):r.clone().iuor(this)},n.prototype.iuand=function(r){var u;this.length>r.length?u=r:u=this;for(var m=0;m<u.length;m++)this.words[m]=this.words[m]&r.words[m];return this.length=u.length,this._strip()},n.prototype.iand=function(r){return t((this.negative|r.negative)===0),this.iuand(r)},n.prototype.and=function(r){return this.length>r.length?this.clone().iand(r):r.clone().iand(this)},n.prototype.uand=function(r){return this.length>r.length?this.clone().iuand(r):r.clone().iuand(this)},n.prototype.iuxor=function(r){var u,m;this.length>r.length?(u=this,m=r):(u=r,m=this);for(var p=0;p<m.length;p++)this.words[p]=u.words[p]^m.words[p];if(this!==u)for(;p<u.length;p++)this.words[p]=u.words[p];return this.length=u.length,this._strip()},n.prototype.ixor=function(r){return t((this.negative|r.negative)===0),this.iuxor(r)},n.prototype.xor=function(r){return this.length>r.length?this.clone().ixor(r):r.clone().ixor(this)},n.prototype.uxor=function(r){return this.length>r.length?this.clone().iuxor(r):r.clone().iuxor(this)},n.prototype.inotn=function(r){t(typeof r=="number"&&r>=0);var u=Math.ceil(r/26)|0,m=r%26;this._expand(u),m>0&&u--;for(var p=0;p<u;p++)this.words[p]=~this.words[p]&67108863;return m>0&&(this.words[p]=~this.words[p]&67108863>>26-m),this._strip()},n.prototype.notn=function(r){return this.clone().inotn(r)},n.prototype.setn=function(r,u){t(typeof r=="number"&&r>=0);var m=r/26|0,p=r%26;return this._expand(m+1),u?this.words[m]=this.words[m]|1<<p:this.words[m]=this.words[m]&~(1<<p),this._strip()},n.prototype.iadd=function(r){var u;if(this.negative!==0&&r.negative===0)return this.negative=0,u=this.isub(r),this.negative^=1,this._normSign();if(this.negative===0&&r.negative!==0)return r.negative=0,u=this.isub(r),r.negative=1,u._normSign();var m,p;this.length>r.length?(m=this,p=r):(m=r,p=this);for(var h=0,b=0;b<p.length;b++)u=(m.words[b]|0)+(p.words[b]|0)+h,this.words[b]=u&67108863,h=u>>>26;for(;h!==0&&b<m.length;b++)u=(m.words[b]|0)+h,this.words[b]=u&67108863,h=u>>>26;if(this.length=m.length,h!==0)this.words[this.length]=h,this.length++;else if(m!==this)for(;b<m.length;b++)this.words[b]=m.words[b];return this},n.prototype.add=function(r){var u;return r.negative!==0&&this.negative===0?(r.negative=0,u=this.sub(r),r.negative^=1,u):r.negative===0&&this.negative!==0?(this.negative=0,u=r.sub(this),this.negative=1,u):this.length>r.length?this.clone().iadd(r):r.clone().iadd(this)},n.prototype.isub=function(r){if(r.negative!==0){r.negative=0;var u=this.iadd(r);return r.negative=1,u._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(r),this.negative=1,this._normSign();var m=this.cmp(r);if(m===0)return this.negative=0,this.length=1,this.words[0]=0,this;var p,h;m>0?(p=this,h=r):(p=r,h=this);for(var b=0,T=0;T<h.length;T++)u=(p.words[T]|0)-(h.words[T]|0)+b,b=u>>26,this.words[T]=u&67108863;for(;b!==0&&T<p.length;T++)u=(p.words[T]|0)+b,b=u>>26,this.words[T]=u&67108863;if(b===0&&T<p.length&&p!==this)for(;T<p.length;T++)this.words[T]=p.words[T];return this.length=Math.max(this.length,T),p!==this&&(this.negative=1),this._strip()},n.prototype.sub=function(r){return this.clone().isub(r)};function K(y,r,u){u.negative=r.negative^y.negative;var m=y.length+r.length|0;u.length=m,m=m-1|0;var p=y.words[0]|0,h=r.words[0]|0,b=p*h,T=b&67108863,f=b/67108864|0;u.words[0]=T;for(var s=1;s<m;s++){for(var g=f>>>26,D=f&67108863,O=Math.min(s,r.length-1),M=Math.max(0,s-y.length+1);M<=O;M++){var E=s-M|0;p=y.words[E]|0,h=r.words[M]|0,b=p*h+D,g+=b/67108864|0,D=b&67108863}u.words[s]=D|0,f=g|0}return f!==0?u.words[s]=f|0:u.length--,u._strip()}var V=function(r,u,m){var p=r.words,h=u.words,b=m.words,T=0,f,s,g,D=p[0]|0,O=D&8191,M=D>>>13,E=p[1]|0,_=E&8191,j=E>>>13,te=p[2]|0,U=te&8191,q=te>>>13,Yr=p[3]|0,X=Yr&8191,G=Yr>>>13,Zr=p[4]|0,Q=Zr&8191,z=Zr>>>13,ts=p[5]|0,J=ts&8191,Y=ts>>>13,es=p[6]|0,Z=es&8191,tt=es>>>13,ns=p[7]|0,et=ns&8191,nt=ns>>>13,os=p[8]|0,ot=os&8191,at=os>>>13,as=p[9]|0,it=as&8191,rt=as>>>13,is=h[0]|0,st=is&8191,ct=is>>>13,rs=h[1]|0,lt=rs&8191,ut=rs>>>13,ss=h[2]|0,mt=ss&8191,pt=ss>>>13,cs=h[3]|0,dt=cs&8191,ft=cs>>>13,ls=h[4]|0,ht=ls&8191,gt=ls>>>13,us=h[5]|0,yt=us&8191,bt=us>>>13,ms=h[6]|0,St=ms&8191,Tt=ms>>>13,ps=h[7]|0,wt=ps&8191,It=ps>>>13,ds=h[8]|0,Ct=ds&8191,kt=ds>>>13,fs=h[9]|0,xt=fs&8191,vt=fs>>>13;m.negative=r.negative^u.negative,m.length=19,f=Math.imul(O,st),s=Math.imul(O,ct),s=s+Math.imul(M,st)|0,g=Math.imul(M,ct);var Ui=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Ui>>>26)|0,Ui&=67108863,f=Math.imul(_,st),s=Math.imul(_,ct),s=s+Math.imul(j,st)|0,g=Math.imul(j,ct),f=f+Math.imul(O,lt)|0,s=s+Math.imul(O,ut)|0,s=s+Math.imul(M,lt)|0,g=g+Math.imul(M,ut)|0;var qi=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(qi>>>26)|0,qi&=67108863,f=Math.imul(U,st),s=Math.imul(U,ct),s=s+Math.imul(q,st)|0,g=Math.imul(q,ct),f=f+Math.imul(_,lt)|0,s=s+Math.imul(_,ut)|0,s=s+Math.imul(j,lt)|0,g=g+Math.imul(j,ut)|0,f=f+Math.imul(O,mt)|0,s=s+Math.imul(O,pt)|0,s=s+Math.imul(M,mt)|0,g=g+Math.imul(M,pt)|0;var Fi=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Fi>>>26)|0,Fi&=67108863,f=Math.imul(X,st),s=Math.imul(X,ct),s=s+Math.imul(G,st)|0,g=Math.imul(G,ct),f=f+Math.imul(U,lt)|0,s=s+Math.imul(U,ut)|0,s=s+Math.imul(q,lt)|0,g=g+Math.imul(q,ut)|0,f=f+Math.imul(_,mt)|0,s=s+Math.imul(_,pt)|0,s=s+Math.imul(j,mt)|0,g=g+Math.imul(j,pt)|0,f=f+Math.imul(O,dt)|0,s=s+Math.imul(O,ft)|0,s=s+Math.imul(M,dt)|0,g=g+Math.imul(M,ft)|0;var Ki=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Ki>>>26)|0,Ki&=67108863,f=Math.imul(Q,st),s=Math.imul(Q,ct),s=s+Math.imul(z,st)|0,g=Math.imul(z,ct),f=f+Math.imul(X,lt)|0,s=s+Math.imul(X,ut)|0,s=s+Math.imul(G,lt)|0,g=g+Math.imul(G,ut)|0,f=f+Math.imul(U,mt)|0,s=s+Math.imul(U,pt)|0,s=s+Math.imul(q,mt)|0,g=g+Math.imul(q,pt)|0,f=f+Math.imul(_,dt)|0,s=s+Math.imul(_,ft)|0,s=s+Math.imul(j,dt)|0,g=g+Math.imul(j,ft)|0,f=f+Math.imul(O,ht)|0,s=s+Math.imul(O,gt)|0,s=s+Math.imul(M,ht)|0,g=g+Math.imul(M,gt)|0;var Vi=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Vi>>>26)|0,Vi&=67108863,f=Math.imul(J,st),s=Math.imul(J,ct),s=s+Math.imul(Y,st)|0,g=Math.imul(Y,ct),f=f+Math.imul(Q,lt)|0,s=s+Math.imul(Q,ut)|0,s=s+Math.imul(z,lt)|0,g=g+Math.imul(z,ut)|0,f=f+Math.imul(X,mt)|0,s=s+Math.imul(X,pt)|0,s=s+Math.imul(G,mt)|0,g=g+Math.imul(G,pt)|0,f=f+Math.imul(U,dt)|0,s=s+Math.imul(U,ft)|0,s=s+Math.imul(q,dt)|0,g=g+Math.imul(q,ft)|0,f=f+Math.imul(_,ht)|0,s=s+Math.imul(_,gt)|0,s=s+Math.imul(j,ht)|0,g=g+Math.imul(j,gt)|0,f=f+Math.imul(O,yt)|0,s=s+Math.imul(O,bt)|0,s=s+Math.imul(M,yt)|0,g=g+Math.imul(M,bt)|0;var $i=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+($i>>>26)|0,$i&=67108863,f=Math.imul(Z,st),s=Math.imul(Z,ct),s=s+Math.imul(tt,st)|0,g=Math.imul(tt,ct),f=f+Math.imul(J,lt)|0,s=s+Math.imul(J,ut)|0,s=s+Math.imul(Y,lt)|0,g=g+Math.imul(Y,ut)|0,f=f+Math.imul(Q,mt)|0,s=s+Math.imul(Q,pt)|0,s=s+Math.imul(z,mt)|0,g=g+Math.imul(z,pt)|0,f=f+Math.imul(X,dt)|0,s=s+Math.imul(X,ft)|0,s=s+Math.imul(G,dt)|0,g=g+Math.imul(G,ft)|0,f=f+Math.imul(U,ht)|0,s=s+Math.imul(U,gt)|0,s=s+Math.imul(q,ht)|0,g=g+Math.imul(q,gt)|0,f=f+Math.imul(_,yt)|0,s=s+Math.imul(_,bt)|0,s=s+Math.imul(j,yt)|0,g=g+Math.imul(j,bt)|0,f=f+Math.imul(O,St)|0,s=s+Math.imul(O,Tt)|0,s=s+Math.imul(M,St)|0,g=g+Math.imul(M,Tt)|0;var Hi=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Hi>>>26)|0,Hi&=67108863,f=Math.imul(et,st),s=Math.imul(et,ct),s=s+Math.imul(nt,st)|0,g=Math.imul(nt,ct),f=f+Math.imul(Z,lt)|0,s=s+Math.imul(Z,ut)|0,s=s+Math.imul(tt,lt)|0,g=g+Math.imul(tt,ut)|0,f=f+Math.imul(J,mt)|0,s=s+Math.imul(J,pt)|0,s=s+Math.imul(Y,mt)|0,g=g+Math.imul(Y,pt)|0,f=f+Math.imul(Q,dt)|0,s=s+Math.imul(Q,ft)|0,s=s+Math.imul(z,dt)|0,g=g+Math.imul(z,ft)|0,f=f+Math.imul(X,ht)|0,s=s+Math.imul(X,gt)|0,s=s+Math.imul(G,ht)|0,g=g+Math.imul(G,gt)|0,f=f+Math.imul(U,yt)|0,s=s+Math.imul(U,bt)|0,s=s+Math.imul(q,yt)|0,g=g+Math.imul(q,bt)|0,f=f+Math.imul(_,St)|0,s=s+Math.imul(_,Tt)|0,s=s+Math.imul(j,St)|0,g=g+Math.imul(j,Tt)|0,f=f+Math.imul(O,wt)|0,s=s+Math.imul(O,It)|0,s=s+Math.imul(M,wt)|0,g=g+Math.imul(M,It)|0;var Xi=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Xi>>>26)|0,Xi&=67108863,f=Math.imul(ot,st),s=Math.imul(ot,ct),s=s+Math.imul(at,st)|0,g=Math.imul(at,ct),f=f+Math.imul(et,lt)|0,s=s+Math.imul(et,ut)|0,s=s+Math.imul(nt,lt)|0,g=g+Math.imul(nt,ut)|0,f=f+Math.imul(Z,mt)|0,s=s+Math.imul(Z,pt)|0,s=s+Math.imul(tt,mt)|0,g=g+Math.imul(tt,pt)|0,f=f+Math.imul(J,dt)|0,s=s+Math.imul(J,ft)|0,s=s+Math.imul(Y,dt)|0,g=g+Math.imul(Y,ft)|0,f=f+Math.imul(Q,ht)|0,s=s+Math.imul(Q,gt)|0,s=s+Math.imul(z,ht)|0,g=g+Math.imul(z,gt)|0,f=f+Math.imul(X,yt)|0,s=s+Math.imul(X,bt)|0,s=s+Math.imul(G,yt)|0,g=g+Math.imul(G,bt)|0,f=f+Math.imul(U,St)|0,s=s+Math.imul(U,Tt)|0,s=s+Math.imul(q,St)|0,g=g+Math.imul(q,Tt)|0,f=f+Math.imul(_,wt)|0,s=s+Math.imul(_,It)|0,s=s+Math.imul(j,wt)|0,g=g+Math.imul(j,It)|0,f=f+Math.imul(O,Ct)|0,s=s+Math.imul(O,kt)|0,s=s+Math.imul(M,Ct)|0,g=g+Math.imul(M,kt)|0;var Gi=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Gi>>>26)|0,Gi&=67108863,f=Math.imul(it,st),s=Math.imul(it,ct),s=s+Math.imul(rt,st)|0,g=Math.imul(rt,ct),f=f+Math.imul(ot,lt)|0,s=s+Math.imul(ot,ut)|0,s=s+Math.imul(at,lt)|0,g=g+Math.imul(at,ut)|0,f=f+Math.imul(et,mt)|0,s=s+Math.imul(et,pt)|0,s=s+Math.imul(nt,mt)|0,g=g+Math.imul(nt,pt)|0,f=f+Math.imul(Z,dt)|0,s=s+Math.imul(Z,ft)|0,s=s+Math.imul(tt,dt)|0,g=g+Math.imul(tt,ft)|0,f=f+Math.imul(J,ht)|0,s=s+Math.imul(J,gt)|0,s=s+Math.imul(Y,ht)|0,g=g+Math.imul(Y,gt)|0,f=f+Math.imul(Q,yt)|0,s=s+Math.imul(Q,bt)|0,s=s+Math.imul(z,yt)|0,g=g+Math.imul(z,bt)|0,f=f+Math.imul(X,St)|0,s=s+Math.imul(X,Tt)|0,s=s+Math.imul(G,St)|0,g=g+Math.imul(G,Tt)|0,f=f+Math.imul(U,wt)|0,s=s+Math.imul(U,It)|0,s=s+Math.imul(q,wt)|0,g=g+Math.imul(q,It)|0,f=f+Math.imul(_,Ct)|0,s=s+Math.imul(_,kt)|0,s=s+Math.imul(j,Ct)|0,g=g+Math.imul(j,kt)|0,f=f+Math.imul(O,xt)|0,s=s+Math.imul(O,vt)|0,s=s+Math.imul(M,xt)|0,g=g+Math.imul(M,vt)|0;var Qi=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Qi>>>26)|0,Qi&=67108863,f=Math.imul(it,lt),s=Math.imul(it,ut),s=s+Math.imul(rt,lt)|0,g=Math.imul(rt,ut),f=f+Math.imul(ot,mt)|0,s=s+Math.imul(ot,pt)|0,s=s+Math.imul(at,mt)|0,g=g+Math.imul(at,pt)|0,f=f+Math.imul(et,dt)|0,s=s+Math.imul(et,ft)|0,s=s+Math.imul(nt,dt)|0,g=g+Math.imul(nt,ft)|0,f=f+Math.imul(Z,ht)|0,s=s+Math.imul(Z,gt)|0,s=s+Math.imul(tt,ht)|0,g=g+Math.imul(tt,gt)|0,f=f+Math.imul(J,yt)|0,s=s+Math.imul(J,bt)|0,s=s+Math.imul(Y,yt)|0,g=g+Math.imul(Y,bt)|0,f=f+Math.imul(Q,St)|0,s=s+Math.imul(Q,Tt)|0,s=s+Math.imul(z,St)|0,g=g+Math.imul(z,Tt)|0,f=f+Math.imul(X,wt)|0,s=s+Math.imul(X,It)|0,s=s+Math.imul(G,wt)|0,g=g+Math.imul(G,It)|0,f=f+Math.imul(U,Ct)|0,s=s+Math.imul(U,kt)|0,s=s+Math.imul(q,Ct)|0,g=g+Math.imul(q,kt)|0,f=f+Math.imul(_,xt)|0,s=s+Math.imul(_,vt)|0,s=s+Math.imul(j,xt)|0,g=g+Math.imul(j,vt)|0;var zi=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(zi>>>26)|0,zi&=67108863,f=Math.imul(it,mt),s=Math.imul(it,pt),s=s+Math.imul(rt,mt)|0,g=Math.imul(rt,pt),f=f+Math.imul(ot,dt)|0,s=s+Math.imul(ot,ft)|0,s=s+Math.imul(at,dt)|0,g=g+Math.imul(at,ft)|0,f=f+Math.imul(et,ht)|0,s=s+Math.imul(et,gt)|0,s=s+Math.imul(nt,ht)|0,g=g+Math.imul(nt,gt)|0,f=f+Math.imul(Z,yt)|0,s=s+Math.imul(Z,bt)|0,s=s+Math.imul(tt,yt)|0,g=g+Math.imul(tt,bt)|0,f=f+Math.imul(J,St)|0,s=s+Math.imul(J,Tt)|0,s=s+Math.imul(Y,St)|0,g=g+Math.imul(Y,Tt)|0,f=f+Math.imul(Q,wt)|0,s=s+Math.imul(Q,It)|0,s=s+Math.imul(z,wt)|0,g=g+Math.imul(z,It)|0,f=f+Math.imul(X,Ct)|0,s=s+Math.imul(X,kt)|0,s=s+Math.imul(G,Ct)|0,g=g+Math.imul(G,kt)|0,f=f+Math.imul(U,xt)|0,s=s+Math.imul(U,vt)|0,s=s+Math.imul(q,xt)|0,g=g+Math.imul(q,vt)|0;var Ji=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Ji>>>26)|0,Ji&=67108863,f=Math.imul(it,dt),s=Math.imul(it,ft),s=s+Math.imul(rt,dt)|0,g=Math.imul(rt,ft),f=f+Math.imul(ot,ht)|0,s=s+Math.imul(ot,gt)|0,s=s+Math.imul(at,ht)|0,g=g+Math.imul(at,gt)|0,f=f+Math.imul(et,yt)|0,s=s+Math.imul(et,bt)|0,s=s+Math.imul(nt,yt)|0,g=g+Math.imul(nt,bt)|0,f=f+Math.imul(Z,St)|0,s=s+Math.imul(Z,Tt)|0,s=s+Math.imul(tt,St)|0,g=g+Math.imul(tt,Tt)|0,f=f+Math.imul(J,wt)|0,s=s+Math.imul(J,It)|0,s=s+Math.imul(Y,wt)|0,g=g+Math.imul(Y,It)|0,f=f+Math.imul(Q,Ct)|0,s=s+Math.imul(Q,kt)|0,s=s+Math.imul(z,Ct)|0,g=g+Math.imul(z,kt)|0,f=f+Math.imul(X,xt)|0,s=s+Math.imul(X,vt)|0,s=s+Math.imul(G,xt)|0,g=g+Math.imul(G,vt)|0;var Yi=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Yi>>>26)|0,Yi&=67108863,f=Math.imul(it,ht),s=Math.imul(it,gt),s=s+Math.imul(rt,ht)|0,g=Math.imul(rt,gt),f=f+Math.imul(ot,yt)|0,s=s+Math.imul(ot,bt)|0,s=s+Math.imul(at,yt)|0,g=g+Math.imul(at,bt)|0,f=f+Math.imul(et,St)|0,s=s+Math.imul(et,Tt)|0,s=s+Math.imul(nt,St)|0,g=g+Math.imul(nt,Tt)|0,f=f+Math.imul(Z,wt)|0,s=s+Math.imul(Z,It)|0,s=s+Math.imul(tt,wt)|0,g=g+Math.imul(tt,It)|0,f=f+Math.imul(J,Ct)|0,s=s+Math.imul(J,kt)|0,s=s+Math.imul(Y,Ct)|0,g=g+Math.imul(Y,kt)|0,f=f+Math.imul(Q,xt)|0,s=s+Math.imul(Q,vt)|0,s=s+Math.imul(z,xt)|0,g=g+Math.imul(z,vt)|0;var Zi=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(Zi>>>26)|0,Zi&=67108863,f=Math.imul(it,yt),s=Math.imul(it,bt),s=s+Math.imul(rt,yt)|0,g=Math.imul(rt,bt),f=f+Math.imul(ot,St)|0,s=s+Math.imul(ot,Tt)|0,s=s+Math.imul(at,St)|0,g=g+Math.imul(at,Tt)|0,f=f+Math.imul(et,wt)|0,s=s+Math.imul(et,It)|0,s=s+Math.imul(nt,wt)|0,g=g+Math.imul(nt,It)|0,f=f+Math.imul(Z,Ct)|0,s=s+Math.imul(Z,kt)|0,s=s+Math.imul(tt,Ct)|0,g=g+Math.imul(tt,kt)|0,f=f+Math.imul(J,xt)|0,s=s+Math.imul(J,vt)|0,s=s+Math.imul(Y,xt)|0,g=g+Math.imul(Y,vt)|0;var tr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(tr>>>26)|0,tr&=67108863,f=Math.imul(it,St),s=Math.imul(it,Tt),s=s+Math.imul(rt,St)|0,g=Math.imul(rt,Tt),f=f+Math.imul(ot,wt)|0,s=s+Math.imul(ot,It)|0,s=s+Math.imul(at,wt)|0,g=g+Math.imul(at,It)|0,f=f+Math.imul(et,Ct)|0,s=s+Math.imul(et,kt)|0,s=s+Math.imul(nt,Ct)|0,g=g+Math.imul(nt,kt)|0,f=f+Math.imul(Z,xt)|0,s=s+Math.imul(Z,vt)|0,s=s+Math.imul(tt,xt)|0,g=g+Math.imul(tt,vt)|0;var er=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(er>>>26)|0,er&=67108863,f=Math.imul(it,wt),s=Math.imul(it,It),s=s+Math.imul(rt,wt)|0,g=Math.imul(rt,It),f=f+Math.imul(ot,Ct)|0,s=s+Math.imul(ot,kt)|0,s=s+Math.imul(at,Ct)|0,g=g+Math.imul(at,kt)|0,f=f+Math.imul(et,xt)|0,s=s+Math.imul(et,vt)|0,s=s+Math.imul(nt,xt)|0,g=g+Math.imul(nt,vt)|0;var nr=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(nr>>>26)|0,nr&=67108863,f=Math.imul(it,Ct),s=Math.imul(it,kt),s=s+Math.imul(rt,Ct)|0,g=Math.imul(rt,kt),f=f+Math.imul(ot,xt)|0,s=s+Math.imul(ot,vt)|0,s=s+Math.imul(at,xt)|0,g=g+Math.imul(at,vt)|0;var or=(T+f|0)+((s&8191)<<13)|0;T=(g+(s>>>13)|0)+(or>>>26)|0,or&=67108863,f=Math.imul(it,xt),s=Math.imul(it,vt),s=s+Math.imul(rt,xt)|0,g=Math.imul(rt,vt);var ar=(T+f|0)+((s&8191)<<13)|0;return T=(g+(s>>>13)|0)+(ar>>>26)|0,ar&=67108863,b[0]=Ui,b[1]=qi,b[2]=Fi,b[3]=Ki,b[4]=Vi,b[5]=$i,b[6]=Hi,b[7]=Xi,b[8]=Gi,b[9]=Qi,b[10]=zi,b[11]=Ji,b[12]=Yi,b[13]=Zi,b[14]=tr,b[15]=er,b[16]=nr,b[17]=or,b[18]=ar,T!==0&&(b[19]=T,m.length++),m};Math.imul||(V=K);function Vt(y,r,u){u.negative=r.negative^y.negative,u.length=y.length+r.length;for(var m=0,p=0,h=0;h<u.length-1;h++){var b=p;p=0;for(var T=m&67108863,f=Math.min(h,r.length-1),s=Math.max(0,h-y.length+1);s<=f;s++){var g=h-s,D=y.words[g]|0,O=r.words[s]|0,M=D*O,E=M&67108863;b=b+(M/67108864|0)|0,E=E+T|0,T=E&67108863,b=b+(E>>>26)|0,p+=b>>>26,b&=67108863}u.words[h]=T,m=b,b=p}return m!==0?u.words[h]=m:u.length--,u._strip()}function Et(y,r,u){return Vt(y,r,u)}n.prototype.mulTo=function(r,u){var m,p=this.length+r.length;return this.length===10&&r.length===10?m=V(this,r,u):p<63?m=K(this,r,u):p<1024?m=Vt(this,r,u):m=Et(this,r,u),m};function Pt(y,r){this.x=y,this.y=r}Pt.prototype.makeRBT=function(r){for(var u=new Array(r),m=n.prototype._countBits(r)-1,p=0;p<r;p++)u[p]=this.revBin(p,m,r);return u},Pt.prototype.revBin=function(r,u,m){if(r===0||r===m-1)return r;for(var p=0,h=0;h<u;h++)p|=(r&1)<<u-h-1,r>>=1;return p},Pt.prototype.permute=function(r,u,m,p,h,b){for(var T=0;T<b;T++)p[T]=u[r[T]],h[T]=m[r[T]]},Pt.prototype.transform=function(r,u,m,p,h,b){this.permute(b,r,u,m,p,h);for(var T=1;T<h;T<<=1)for(var f=T<<1,s=Math.cos(2*Math.PI/f),g=Math.sin(2*Math.PI/f),D=0;D<h;D+=f)for(var O=s,M=g,E=0;E<T;E++){var _=m[D+E],j=p[D+E],te=m[D+E+T],U=p[D+E+T],q=O*te-M*U;U=O*U+M*te,te=q,m[D+E]=_+te,p[D+E]=j+U,m[D+E+T]=_-te,p[D+E+T]=j-U,E!==f&&(q=s*O-g*M,M=s*M+g*O,O=q)}},Pt.prototype.guessLen13b=function(r,u){var m=Math.max(u,r)|1,p=m&1,h=0;for(m=m/2|0;m;m=m>>>1)h++;return 1<<h+1+p},Pt.prototype.conjugate=function(r,u,m){if(!(m<=1))for(var p=0;p<m/2;p++){var h=r[p];r[p]=r[m-p-1],r[m-p-1]=h,h=u[p],u[p]=-u[m-p-1],u[m-p-1]=-h}},Pt.prototype.normalize13b=function(r,u){for(var m=0,p=0;p<u/2;p++){var h=Math.round(r[2*p+1]/u)*8192+Math.round(r[2*p]/u)+m;r[p]=h&67108863,h<67108864?m=0:m=h/67108864|0}return r},Pt.prototype.convert13b=function(r,u,m,p){for(var h=0,b=0;b<u;b++)h=h+(r[b]|0),m[2*b]=h&8191,h=h>>>13,m[2*b+1]=h&8191,h=h>>>13;for(b=2*u;b<p;++b)m[b]=0;t(h===0),t((h&-8192)===0)},Pt.prototype.stub=function(r){for(var u=new Array(r),m=0;m<r;m++)u[m]=0;return u},Pt.prototype.mulp=function(r,u,m){var p=2*this.guessLen13b(r.length,u.length),h=this.makeRBT(p),b=this.stub(p),T=new Array(p),f=new Array(p),s=new Array(p),g=new Array(p),D=new Array(p),O=new Array(p),M=m.words;M.length=p,this.convert13b(r.words,r.length,T,p),this.convert13b(u.words,u.length,g,p),this.transform(T,b,f,s,p,h),this.transform(g,b,D,O,p,h);for(var E=0;E<p;E++){var _=f[E]*D[E]-s[E]*O[E];s[E]=f[E]*O[E]+s[E]*D[E],f[E]=_}return this.conjugate(f,s,p),this.transform(f,s,M,b,p,h),this.conjugate(M,b,p),this.normalize13b(M,p),m.negative=r.negative^u.negative,m.length=r.length+u.length,m._strip()},n.prototype.mul=function(r){var u=new n(null);return u.words=new Array(this.length+r.length),this.mulTo(r,u)},n.prototype.mulf=function(r){var u=new n(null);return u.words=new Array(this.length+r.length),Et(this,r,u)},n.prototype.imul=function(r){return this.clone().mulTo(r,this)},n.prototype.imuln=function(r){var u=r<0;u&&(r=-r),t(typeof r=="number"),t(r<67108864);for(var m=0,p=0;p<this.length;p++){var h=(this.words[p]|0)*r,b=(h&67108863)+(m&67108863);m>>=26,m+=h/67108864|0,m+=b>>>26,this.words[p]=b&67108863}return m!==0&&(this.words[p]=m,this.length++),u?this.ineg():this},n.prototype.muln=function(r){return this.clone().imuln(r)},n.prototype.sqr=function(){return this.mul(this)},n.prototype.isqr=function(){return this.imul(this.clone())},n.prototype.pow=function(r){var u=R(r);if(u.length===0)return new n(1);for(var m=this,p=0;p<u.length&&u[p]===0;p++,m=m.sqr());if(++p<u.length)for(var h=m.sqr();p<u.length;p++,h=h.sqr())u[p]!==0&&(m=m.mul(h));return m},n.prototype.iushln=function(r){t(typeof r=="number"&&r>=0);var u=r%26,m=(r-u)/26,p=67108863>>>26-u<<26-u,h;if(u!==0){var b=0;for(h=0;h<this.length;h++){var T=this.words[h]&p,f=(this.words[h]|0)-T<<u;this.words[h]=f|b,b=T>>>26-u}b&&(this.words[h]=b,this.length++)}if(m!==0){for(h=this.length-1;h>=0;h--)this.words[h+m]=this.words[h];for(h=0;h<m;h++)this.words[h]=0;this.length+=m}return this._strip()},n.prototype.ishln=function(r){return t(this.negative===0),this.iushln(r)},n.prototype.iushrn=function(r,u,m){t(typeof r=="number"&&r>=0);var p;u?p=(u-u%26)/26:p=0;var h=r%26,b=Math.min((r-h)/26,this.length),T=67108863^67108863>>>h<<h,f=m;if(p-=b,p=Math.max(0,p),f){for(var s=0;s<b;s++)f.words[s]=this.words[s];f.length=b}if(b!==0)if(this.length>b)for(this.length-=b,s=0;s<this.length;s++)this.words[s]=this.words[s+b];else this.words[0]=0,this.length=1;var g=0;for(s=this.length-1;s>=0&&(g!==0||s>=p);s--){var D=this.words[s]|0;this.words[s]=g<<26-h|D>>>h,g=D&T}return f&&g!==0&&(f.words[f.length++]=g),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},n.prototype.ishrn=function(r,u,m){return t(this.negative===0),this.iushrn(r,u,m)},n.prototype.shln=function(r){return this.clone().ishln(r)},n.prototype.ushln=function(r){return this.clone().iushln(r)},n.prototype.shrn=function(r){return this.clone().ishrn(r)},n.prototype.ushrn=function(r){return this.clone().iushrn(r)},n.prototype.testn=function(r){t(typeof r=="number"&&r>=0);var u=r%26,m=(r-u)/26,p=1<<u;if(this.length<=m)return!1;var h=this.words[m];return!!(h&p)},n.prototype.imaskn=function(r){t(typeof r=="number"&&r>=0);var u=r%26,m=(r-u)/26;if(t(this.negative===0,"imaskn works only with positive numbers"),this.length<=m)return this;if(u!==0&&m++,this.length=Math.min(m,this.length),u!==0){var p=67108863^67108863>>>u<<u;this.words[this.length-1]&=p}return this._strip()},n.prototype.maskn=function(r){return this.clone().imaskn(r)},n.prototype.iaddn=function(r){return t(typeof r=="number"),t(r<67108864),r<0?this.isubn(-r):this.negative!==0?this.length===1&&(this.words[0]|0)<=r?(this.words[0]=r-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(r),this.negative=1,this):this._iaddn(r)},n.prototype._iaddn=function(r){this.words[0]+=r;for(var u=0;u<this.length&&this.words[u]>=67108864;u++)this.words[u]-=67108864,u===this.length-1?this.words[u+1]=1:this.words[u+1]++;return this.length=Math.max(this.length,u+1),this},n.prototype.isubn=function(r){if(t(typeof r=="number"),t(r<67108864),r<0)return this.iaddn(-r);if(this.negative!==0)return this.negative=0,this.iaddn(r),this.negative=1,this;if(this.words[0]-=r,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var u=0;u<this.length&&this.words[u]<0;u++)this.words[u]+=67108864,this.words[u+1]-=1;return this._strip()},n.prototype.addn=function(r){return this.clone().iaddn(r)},n.prototype.subn=function(r){return this.clone().isubn(r)},n.prototype.iabs=function(){return this.negative=0,this},n.prototype.abs=function(){return this.clone().iabs()},n.prototype._ishlnsubmul=function(r,u,m){var p=r.length+m,h;this._expand(p);var b,T=0;for(h=0;h<r.length;h++){b=(this.words[h+m]|0)+T;var f=(r.words[h]|0)*u;b-=f&67108863,T=(b>>26)-(f/67108864|0),this.words[h+m]=b&67108863}for(;h<this.length-m;h++)b=(this.words[h+m]|0)+T,T=b>>26,this.words[h+m]=b&67108863;if(T===0)return this._strip();for(t(T===-1),T=0,h=0;h<this.length;h++)b=-(this.words[h]|0)+T,T=b>>26,this.words[h]=b&67108863;return this.negative=1,this._strip()},n.prototype._wordDiv=function(r,u){var m=this.length-r.length,p=this.clone(),h=r,b=h.words[h.length-1]|0,T=this._countBits(b);m=26-T,m!==0&&(h=h.ushln(m),p.iushln(m),b=h.words[h.length-1]|0);var f=p.length-h.length,s;if(u!=="mod"){s=new n(null),s.length=f+1,s.words=new Array(s.length);for(var g=0;g<s.length;g++)s.words[g]=0}var D=p.clone()._ishlnsubmul(h,1,f);D.negative===0&&(p=D,s&&(s.words[f]=1));for(var O=f-1;O>=0;O--){var M=(p.words[h.length+O]|0)*67108864+(p.words[h.length+O-1]|0);for(M=Math.min(M/b|0,67108863),p._ishlnsubmul(h,M,O);p.negative!==0;)M--,p.negative=0,p._ishlnsubmul(h,1,O),p.isZero()||(p.negative^=1);s&&(s.words[O]=M)}return s&&s._strip(),p._strip(),u!=="div"&&m!==0&&p.iushrn(m),{div:s||null,mod:p}},n.prototype.divmod=function(r,u,m){if(t(!r.isZero()),this.isZero())return{div:new n(0),mod:new n(0)};var p,h,b;return this.negative!==0&&r.negative===0?(b=this.neg().divmod(r,u),u!=="mod"&&(p=b.div.neg()),u!=="div"&&(h=b.mod.neg(),m&&h.negative!==0&&h.iadd(r)),{div:p,mod:h}):this.negative===0&&r.negative!==0?(b=this.divmod(r.neg(),u),u!=="mod"&&(p=b.div.neg()),{div:p,mod:b.mod}):this.negative&r.negative?(b=this.neg().divmod(r.neg(),u),u!=="div"&&(h=b.mod.neg(),m&&h.negative!==0&&h.isub(r)),{div:b.div,mod:h}):r.length>this.length||this.cmp(r)<0?{div:new n(0),mod:this}:r.length===1?u==="div"?{div:this.divn(r.words[0]),mod:null}:u==="mod"?{div:null,mod:new n(this.modrn(r.words[0]))}:{div:this.divn(r.words[0]),mod:new n(this.modrn(r.words[0]))}:this._wordDiv(r,u)},n.prototype.div=function(r){return this.divmod(r,"div",!1).div},n.prototype.mod=function(r){return this.divmod(r,"mod",!1).mod},n.prototype.umod=function(r){return this.divmod(r,"mod",!0).mod},n.prototype.divRound=function(r){var u=this.divmod(r);if(u.mod.isZero())return u.div;var m=u.div.negative!==0?u.mod.isub(r):u.mod,p=r.ushrn(1),h=r.andln(1),b=m.cmp(p);return b<0||h===1&&b===0?u.div:u.div.negative!==0?u.div.isubn(1):u.div.iaddn(1)},n.prototype.modrn=function(r){var u=r<0;u&&(r=-r),t(r<=67108863);for(var m=(1<<26)%r,p=0,h=this.length-1;h>=0;h--)p=(m*p+(this.words[h]|0))%r;return u?-p:p},n.prototype.modn=function(r){return this.modrn(r)},n.prototype.idivn=function(r){var u=r<0;u&&(r=-r),t(r<=67108863);for(var m=0,p=this.length-1;p>=0;p--){var h=(this.words[p]|0)+m*67108864;this.words[p]=h/r|0,m=h%r}return this._strip(),u?this.ineg():this},n.prototype.divn=function(r){return this.clone().idivn(r)},n.prototype.egcd=function(r){t(r.negative===0),t(!r.isZero());var u=this,m=r.clone();u.negative!==0?u=u.umod(r):u=u.clone();for(var p=new n(1),h=new n(0),b=new n(0),T=new n(1),f=0;u.isEven()&&m.isEven();)u.iushrn(1),m.iushrn(1),++f;for(var s=m.clone(),g=u.clone();!u.isZero();){for(var D=0,O=1;!(u.words[0]&O)&&D<26;++D,O<<=1);if(D>0)for(u.iushrn(D);D-- >0;)(p.isOdd()||h.isOdd())&&(p.iadd(s),h.isub(g)),p.iushrn(1),h.iushrn(1);for(var M=0,E=1;!(m.words[0]&E)&&M<26;++M,E<<=1);if(M>0)for(m.iushrn(M);M-- >0;)(b.isOdd()||T.isOdd())&&(b.iadd(s),T.isub(g)),b.iushrn(1),T.iushrn(1);u.cmp(m)>=0?(u.isub(m),p.isub(b),h.isub(T)):(m.isub(u),b.isub(p),T.isub(h))}return{a:b,b:T,gcd:m.iushln(f)}},n.prototype._invmp=function(r){t(r.negative===0),t(!r.isZero());var u=this,m=r.clone();u.negative!==0?u=u.umod(r):u=u.clone();for(var p=new n(1),h=new n(0),b=m.clone();u.cmpn(1)>0&&m.cmpn(1)>0;){for(var T=0,f=1;!(u.words[0]&f)&&T<26;++T,f<<=1);if(T>0)for(u.iushrn(T);T-- >0;)p.isOdd()&&p.iadd(b),p.iushrn(1);for(var s=0,g=1;!(m.words[0]&g)&&s<26;++s,g<<=1);if(s>0)for(m.iushrn(s);s-- >0;)h.isOdd()&&h.iadd(b),h.iushrn(1);u.cmp(m)>=0?(u.isub(m),p.isub(h)):(m.isub(u),h.isub(p))}var D;return u.cmpn(1)===0?D=p:D=h,D.cmpn(0)<0&&D.iadd(r),D},n.prototype.gcd=function(r){if(this.isZero())return r.abs();if(r.isZero())return this.abs();var u=this.clone(),m=r.clone();u.negative=0,m.negative=0;for(var p=0;u.isEven()&&m.isEven();p++)u.iushrn(1),m.iushrn(1);do{for(;u.isEven();)u.iushrn(1);for(;m.isEven();)m.iushrn(1);var h=u.cmp(m);if(h<0){var b=u;u=m,m=b}else if(h===0||m.cmpn(1)===0)break;u.isub(m)}while(!0);return m.iushln(p)},n.prototype.invm=function(r){return this.egcd(r).a.umod(r)},n.prototype.isEven=function(){return(this.words[0]&1)===0},n.prototype.isOdd=function(){return(this.words[0]&1)===1},n.prototype.andln=function(r){return this.words[0]&r},n.prototype.bincn=function(r){t(typeof r=="number");var u=r%26,m=(r-u)/26,p=1<<u;if(this.length<=m)return this._expand(m+1),this.words[m]|=p,this;for(var h=p,b=m;h!==0&&b<this.length;b++){var T=this.words[b]|0;T+=h,h=T>>>26,T&=67108863,this.words[b]=T}return h!==0&&(this.words[b]=h,this.length++),this},n.prototype.isZero=function(){return this.length===1&&this.words[0]===0},n.prototype.cmpn=function(r){var u=r<0;if(this.negative!==0&&!u)return-1;if(this.negative===0&&u)return 1;this._strip();var m;if(this.length>1)m=1;else{u&&(r=-r),t(r<=67108863,"Number is too big");var p=this.words[0]|0;m=p===r?0:p<r?-1:1}return this.negative!==0?-m|0:m},n.prototype.cmp=function(r){if(this.negative!==0&&r.negative===0)return-1;if(this.negative===0&&r.negative!==0)return 1;var u=this.ucmp(r);return this.negative!==0?-u|0:u},n.prototype.ucmp=function(r){if(this.length>r.length)return 1;if(this.length<r.length)return-1;for(var u=0,m=this.length-1;m>=0;m--){var p=this.words[m]|0,h=r.words[m]|0;if(p!==h){p<h?u=-1:p>h&&(u=1);break}}return u},n.prototype.gtn=function(r){return this.cmpn(r)===1},n.prototype.gt=function(r){return this.cmp(r)===1},n.prototype.gten=function(r){return this.cmpn(r)>=0},n.prototype.gte=function(r){return this.cmp(r)>=0},n.prototype.ltn=function(r){return this.cmpn(r)===-1},n.prototype.lt=function(r){return this.cmp(r)===-1},n.prototype.lten=function(r){return this.cmpn(r)<=0},n.prototype.lte=function(r){return this.cmp(r)<=0},n.prototype.eqn=function(r){return this.cmpn(r)===0},n.prototype.eq=function(r){return this.cmp(r)===0},n.red=function(r){return new $(r)},n.prototype.toRed=function(r){return t(!this.red,"Already a number in reduction context"),t(this.negative===0,"red works only with positives"),r.convertTo(this)._forceRed(r)},n.prototype.fromRed=function(){return t(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},n.prototype._forceRed=function(r){return this.red=r,this},n.prototype.forceRed=function(r){return t(!this.red,"Already a number in reduction context"),this._forceRed(r)},n.prototype.redAdd=function(r){return t(this.red,"redAdd works only with red numbers"),this.red.add(this,r)},n.prototype.redIAdd=function(r){return t(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,r)},n.prototype.redSub=function(r){return t(this.red,"redSub works only with red numbers"),this.red.sub(this,r)},n.prototype.redISub=function(r){return t(this.red,"redISub works only with red numbers"),this.red.isub(this,r)},n.prototype.redShl=function(r){return t(this.red,"redShl works only with red numbers"),this.red.shl(this,r)},n.prototype.redMul=function(r){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,r),this.red.mul(this,r)},n.prototype.redIMul=function(r){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,r),this.red.imul(this,r)},n.prototype.redSqr=function(){return t(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},n.prototype.redISqr=function(){return t(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},n.prototype.redSqrt=function(){return t(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},n.prototype.redInvm=function(){return t(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},n.prototype.redNeg=function(){return t(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},n.prototype.redPow=function(r){return t(this.red&&!r.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,r)};var Ne={k256:null,p224:null,p192:null,p25519:null};function _t(y,r){this.name=y,this.p=new n(r,16),this.n=this.p.bitLength(),this.k=new n(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_t.prototype._tmp=function(){var r=new n(null);return r.words=new Array(Math.ceil(this.n/13)),r},_t.prototype.ireduce=function(r){var u=r,m;do this.split(u,this.tmp),u=this.imulK(u),u=u.iadd(this.tmp),m=u.bitLength();while(m>this.n);var p=m<this.n?-1:u.ucmp(this.p);return p===0?(u.words[0]=0,u.length=1):p>0?u.isub(this.p):u.strip!==void 0?u.strip():u._strip(),u},_t.prototype.split=function(r,u){r.iushrn(this.n,0,u)},_t.prototype.imulK=function(r){return r.imul(this.k)};function un(){_t.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}o(un,_t),un.prototype.split=function(r,u){for(var m=4194303,p=Math.min(r.length,9),h=0;h<p;h++)u.words[h]=r.words[h];if(u.length=p,r.length<=9){r.words[0]=0,r.length=1;return}var b=r.words[9];for(u.words[u.length++]=b&m,h=10;h<r.length;h++){var T=r.words[h]|0;r.words[h-10]=(T&m)<<4|b>>>22,b=T}b>>>=22,r.words[h-10]=b,b===0&&r.length>10?r.length-=10:r.length-=9},un.prototype.imulK=function(r){r.words[r.length]=0,r.words[r.length+1]=0,r.length+=2;for(var u=0,m=0;m<r.length;m++){var p=r.words[m]|0;u+=p*977,r.words[m]=u&67108863,u=p*64+(u/67108864|0)}return r.words[r.length-1]===0&&(r.length--,r.words[r.length-1]===0&&r.length--),r};function zr(){_t.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}o(zr,_t);function Jr(){_t.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}o(Jr,_t);function ji(){_t.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}o(ji,_t),ji.prototype.imulK=function(r){for(var u=0,m=0;m<r.length;m++){var p=(r.words[m]|0)*19+u,h=p&67108863;p>>>=26,r.words[m]=h,u=p}return u!==0&&(r.words[r.length++]=u),r},n._prime=function(r){if(Ne[r])return Ne[r];var u;if(r==="k256")u=new un;else if(r==="p224")u=new zr;else if(r==="p192")u=new Jr;else if(r==="p25519")u=new ji;else throw new Error("Unknown prime "+r);return Ne[r]=u,u};function $(y){if(typeof y=="string"){var r=n._prime(y);this.m=r.p,this.prime=r}else t(y.gtn(1),"modulus must be greater than 1"),this.m=y,this.prime=null}$.prototype._verify1=function(r){t(r.negative===0,"red works only with positives"),t(r.red,"red works only with red numbers")},$.prototype._verify2=function(r,u){t((r.negative|u.negative)===0,"red works only with positives"),t(r.red&&r.red===u.red,"red works only with red numbers")},$.prototype.imod=function(r){return this.prime?this.prime.ireduce(r)._forceRed(this):(S(r,r.umod(this.m)._forceRed(this)),r)},$.prototype.neg=function(r){return r.isZero()?r.clone():this.m.sub(r)._forceRed(this)},$.prototype.add=function(r,u){this._verify2(r,u);var m=r.add(u);return m.cmp(this.m)>=0&&m.isub(this.m),m._forceRed(this)},$.prototype.iadd=function(r,u){this._verify2(r,u);var m=r.iadd(u);return m.cmp(this.m)>=0&&m.isub(this.m),m},$.prototype.sub=function(r,u){this._verify2(r,u);var m=r.sub(u);return m.cmpn(0)<0&&m.iadd(this.m),m._forceRed(this)},$.prototype.isub=function(r,u){this._verify2(r,u);var m=r.isub(u);return m.cmpn(0)<0&&m.iadd(this.m),m},$.prototype.shl=function(r,u){return this._verify1(r),this.imod(r.ushln(u))},$.prototype.imul=function(r,u){return this._verify2(r,u),this.imod(r.imul(u))},$.prototype.mul=function(r,u){return this._verify2(r,u),this.imod(r.mul(u))},$.prototype.isqr=function(r){return this.imul(r,r.clone())},$.prototype.sqr=function(r){return this.mul(r,r)},$.prototype.sqrt=function(r){if(r.isZero())return r.clone();var u=this.m.andln(3);if(t(u%2===1),u===3){var m=this.m.add(new n(1)).iushrn(2);return this.pow(r,m)}for(var p=this.m.subn(1),h=0;!p.isZero()&&p.andln(1)===0;)h++,p.iushrn(1);t(!p.isZero());var b=new n(1).toRed(this),T=b.redNeg(),f=this.m.subn(1).iushrn(1),s=this.m.bitLength();for(s=new n(2*s*s).toRed(this);this.pow(s,f).cmp(T)!==0;)s.redIAdd(T);for(var g=this.pow(s,p),D=this.pow(r,p.addn(1).iushrn(1)),O=this.pow(r,p),M=h;O.cmp(b)!==0;){for(var E=O,_=0;E.cmp(b)!==0;_++)E=E.redSqr();t(_<M);var j=this.pow(g,new n(1).iushln(M-_-1));D=D.redMul(j),g=j.redSqr(),O=O.redMul(g),M=_}return D},$.prototype.invm=function(r){var u=r._invmp(this.m);return u.negative!==0?(u.negative=0,this.imod(u).redNeg()):this.imod(u)},$.prototype.pow=function(r,u){if(u.isZero())return new n(1).toRed(this);if(u.cmpn(1)===0)return r.clone();var m=4,p=new Array(1<<m);p[0]=new n(1).toRed(this),p[1]=r;for(var h=2;h<p.length;h++)p[h]=this.mul(p[h-1],r);var b=p[0],T=0,f=0,s=u.bitLength()%26;for(s===0&&(s=26),h=u.length-1;h>=0;h--){for(var g=u.words[h],D=s-1;D>=0;D--){var O=g>>D&1;if(b!==p[0]&&(b=this.sqr(b)),O===0&&T===0){f=0;continue}T<<=1,T|=O,f++,!(f!==m&&(h!==0||D!==0))&&(b=this.mul(b,p[T]),f=0,T=0)}s=26}return b},$.prototype.convertTo=function(r){var u=r.umod(this.m);return u===r?u.clone():u},$.prototype.convertFrom=function(r){var u=r.clone();return u.red=null,u},n.mont=function(r){return new me(r)};function me(y){$.call(this,y),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new n(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)}o(me,$),me.prototype.convertTo=function(r){return this.imod(r.ushln(this.shift))},me.prototype.convertFrom=function(r){var u=this.imod(r.mul(this.rinv));return u.red=null,u},me.prototype.imul=function(r,u){if(r.isZero()||u.isZero())return r.words[0]=0,r.length=1,r;var m=r.imul(u),p=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),h=m.isub(p).iushrn(this.shift),b=h;return h.cmp(this.m)>=0?b=h.isub(this.m):h.cmpn(0)<0&&(b=h.iadd(this.m)),b._forceRed(this)},me.prototype.mul=function(r,u){if(r.isZero()||u.isZero())return new n(0)._forceRed(this);var m=r.mul(u),p=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),h=m.isub(p).iushrn(this.shift),b=h;return h.cmp(this.m)>=0?b=h.isub(this.m):h.cmpn(0)<0&&(b=h.iadd(this.m)),b._forceRed(this)},me.prototype.invm=function(r){var u=this.imod(r._invmp(this.m).mul(this.r2));return u._forceRed(this)}})(typeof $r>"u"||$r,ml)});import{TransactionType as Vl}from"@msafe/sui3-utils";import{coinsList as Nl,poolIdPoolNameMap as Wl,poolInfo as gs,singleAssetPoolCoinMap as _l}from"@alphafi/alphafi-sdk";import{TransactionType as We}from"@msafe/sui3-utils";import{bcs as mn,fromBase64 as pn}from"@mysten/bcs";var dn=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isClaimRewardTransaction())return this.decodeClaimReward();let e=this.getLiquidityChangeEvent();if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson,o=t.pool_id,n=Wl[o];if(console.log("Decoder event data - ",t),console.log("Decoder poolName - ",n),this.isWithdrawAlphaEvent(e))return this.decodeWithdrawAlpha(t);if(this.isWithdrawEvent(t))return this.decodeWithdraw(n);if(this.isDoubleAssetDepositEvent(t,n))return this.decodeDoubleAssetDeposit(n,t);if(this.isSingleAssetDepositEvent(t,n))return this.decodeSingleAssetDeposit(n,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&&gs[t].assetTypes.length===2}isSingleAssetDepositEvent(e,t){return e.event_type===0&&gs[t].assetTypes.length===1}extractXTokensAmount(){let e=this.inputs.find(n=>n.Pure!==void 0);if(!e||!e.Pure?.bytes)throw new Error("Unable to extract xTokensAmount from inputs");let{bytes:t}=e.Pure,o;return t.length===12?o=mn.u64().parse(pn(t)):t.length===24?o=mn.u128().parse(pn(t)):t.length===44?o=mn.u256().parse(pn(t)):o=mn.u64().parse(pn(t)),o}decodeDoubleAssetDeposit(e,t){let{amount_a:o,amount_b:n}=t,i=Number(o)>0;return console.log("Decoder.decodeDoubleAssetDeposit",o,n,i),{txType:We.Other,type:"depositDoubleAsset",intentionData:{poolName:e,amount:i?o:n,isAmountA:i}}}decodeSingleAssetDeposit(e,t){let{amount:o}=t;if(console.log("Decoder.decodeSingleAssetDeposit",o),this.getLiquidityChangeEvent().type.includes(":alphafi_navi_pool:")){let{coin:i}=_l[e],{expo:c}=Nl[i];o=Math.floor(Number(o)/10**(9-c)).toString()}return{txType:We.Other,type:"depositSingleAsset",intentionData:{poolName:e,amount:o}}}decodeWithdraw(e){let t=this.extractXTokensAmount();return console.log("Decoder.decodeWithdraw",t),{txType:We.Other,type:"withdraw",intentionData:{poolName:e,xTokensAmount:t}}}decodeWithdrawAlpha(e){let t=this.extractXTokensAmount(),{amount_withdrawn_from_locked:o}=e;return console.log("Decoder.decodeWithdrawAlpha",t,o),{txType:We.Other,type:"withdrawAlpha",intentionData:{withdrawFromLocked:Number(o)>0,xTokensAmount:t}}}decodeClaimReward(){return{txType:We.Other,type:"claimReward",intentionData:{}}}};import{claimRewardTxb as jl}from"@alphafi/alphafi-sdk";import Ll from"sort-keys-recursive";var k=class{constructor(e){this.data=e}serialize(){return JSON.stringify(Ll(this.data))}};var fn=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:o}=t;return await jl(o.address)}static fromData(t){return new a(t)}};import{depositDoubleAssetTxb as Ul}from"@alphafi/alphafi-sdk";var hn=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:o}=t,{poolName:n,amount:i,isAmountA:c}=this.data;return await Ul(n,o.address,i,c)}static fromData(t){return console.log("DepositDoubleAssetIntention.fromData",t),new a(t)}};import{depositSingleAssetTxb as ql}from"@alphafi/alphafi-sdk";var gn=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:o}=t,{poolName:n,amount:i}=this.data;return await ql(n,o.address,i)}static fromData(t){return console.log("DepositSingleAssetIntention.fromData",t),new a(t)}};import{withdrawTxb as Fl}from"@alphafi/alphafi-sdk";var yn=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:o}=t,{poolName:n,xTokensAmount:i}=this.data;return await Fl(i,n,o.address)}static fromData(t){return console.log("WithdrawIntention.fromData",t),new a(t)}};import{withdrawAlphaTxb as Kl}from"@alphafi/alphafi-sdk";var bn=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:o}=t,{withdrawFromLocked:n,xTokensAmount:i}=this.data;return await Kl(i,n,o.address)}static fromData(t){return console.log("WithdrawAlphaIntention.fromData",t),new a(t)}};var Sn=class{application="alphafi";supportSDK="@mysten/sui";async deserialize(e){let{transaction:t,suiClient:o,account:n}=e,i=await o.devInspectTransactionBlock({sender:t.getData().sender,transactionBlock:t});console.log("AlphaFiHelper Sim result - ",i);let l=new dn(t,i).decode();return{txType:Vl.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{account:t}=e;console.log("AlphaFi build transaction type",e.txSubType);let o;switch(e.txSubType){case"depositSingleAsset":o=gn.fromData(e.intentionData);break;case"depositDoubleAsset":o=hn.fromData(e.intentionData);break;case"withdraw":o=yn.fromData(e.intentionData);break;case"withdrawAlpha":o=bn.fromData(e.intentionData);break;case"claimReward":o=fn.fromData(e.intentionData);break;default:throw new Error("not implemented")}return o.build({account:t})}};import{TransactionType as du}from"@msafe/sui3-utils";import{TransactionType as Wt}from"@msafe/sui3-utils";import{bcs as rr}from"@mysten/sui/bcs";import{SBUCK_FOUNTAIN_PACKAGE_ID as sr}from"bucket-protocol-sdk";var Tn=class{constructor(e){this.transaction=e}decode(){if(this.isSBUCKDepositTransaction())return this.decodeSBUCKDeposit();if(this.isSBUCKUnstakeTransaction())return this.decodeSBUCKUnstake();if(this.isSBUCKWithdrawTransaction())return this.decodeSBUCKWithdraw();if(this.isSBUCKClaimTransaction())return this.decodeSBUCKClaim();if(this.isLockedClaimTransaction())return this.decodeLockedClaim();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isCloseTransaction())return this.decodeClose();if(this.isTankDepositTransaction())return this.decodeTankDeposit();if(this.isTankWithdrawTransaction())return this.decodeTankWithdraw();if(this.isTankClaimTransaction())return this.decodeTankClaim();if(this.isPsmTransaction())return this.decodePsm();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getMoveCallModuleCommand(e,t){return this.commands.find(o=>o.$kind==="MoveCall"&&o.MoveCall.module===e&&o.MoveCall.function===t)}getMoveCallPackageModuleCommand(e,t,o){return this.commands.find(n=>n.$kind==="MoveCall"&&n.MoveCall.package===e&&n.MoveCall.module===t&&n.MoveCall.function===o)}getMoveCallModuleCommands(e,t){return this.commands.filter(o=>o.$kind==="MoveCall"&&o.MoveCall.module===e&&o.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(sr,"fountain_core","stake")}isSBUCKUnstakeTransaction(){return!!this.getMoveCallPackageModuleCommand(sr,"fountain_core","force_unstake")}isSBUCKClaimTransaction(){return!!this.getMoveCallPackageModuleCommand(sr,"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,o="0",n=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return n.$kind==="Input"&&(o=this.getPureInputU64(n.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,o,t),{txType:Wt.Other,type:"psm",intentionData:{coinType:e,amount:o,buckToCoin:t}}}decodeBorrow(){let e="",t="0",o,n=this.getStrapId(),i="0",c=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];if(c.$kind==="Input"&&(i=this.getPureInputU64(c.Input)),this.getMoveCallCommand("high_top_up")){let l=this.getMoveCallCommand("high_top_up").MoveCall;[e]=l.typeArguments;let d=l.arguments[1];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input));let S=l.arguments[3];if(S.$kind==="Input"){let w=this.getPureAddresses(S.Input);w.length===1&&([o]=w)}}else if(this.getMoveCallCommand("high_borrow")){let l=this.getMoveCallCommand("high_borrow").MoveCall;[e]=l.typeArguments;let d=l.arguments[4];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input));let S=l.arguments[5];if(S.$kind==="Input"){let w=this.getPureAddresses(S.Input);w.length===1&&([o]=w)}}else if(this.getMoveCallCommand("high_borrow_with_strap")){let l=this.getMoveCallCommand("high_borrow_with_strap").MoveCall;[e]=l.typeArguments;let d=l.arguments[5];d.$kind==="Input"&&(t=this.getPureInputU64(d.Input));let S=l.arguments[6];if(S.$kind==="Input"){let w=this.getPureAddresses(S.Input);w.length===1&&([o]=w)}}return{txType:Wt.Other,type:"borrow",intentionData:{collateralType:e,collateralAmount:i,borrowAmount:t,insertionPlace:o,strapId:n}}}decodeRepay(){let e="",t="0",o="0",i,c=this.getStrapId();if(this.getMoveCallCommand("fully_repay"))[e]=this.getMoveCallCommand("fully_repay").MoveCall.typeArguments;else if(this.getMoveCallCommand("fully_repay_with_strap"))[e]=this.getMoveCallCommand("fully_repay_with_strap").MoveCall.typeArguments;else if(this.getMoveCallCommand("repay_and_withdraw")){let l=this.getMoveCallCommand("repay_and_withdraw").MoveCall;[e]=l.typeArguments;let d=l.arguments[4];d.$kind==="Input"&&(o=this.getPureInputU64(d.Input));let S=l.arguments[5];if(S.$kind==="Input"){let I=this.getPureAddresses(S.Input);I.length===1&&([i]=I)}let w=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];w.$kind==="Input"&&(t=this.getPureInputU64(w.Input))}else if(this.getMoveCallCommand("repay_and_withdraw_with_strap")){let l=this.getMoveCallCommand("repay_and_withdraw_with_strap").MoveCall;[e]=l.typeArguments;let d=l.arguments[5];d.$kind==="Input"&&(o=this.getPureInputU64(d.Input));let S=l.arguments[6];if(S.$kind==="Input"){let I=this.getPureAddresses(S.Input);I.length===1&&([i]=I)}let w=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];w.$kind==="Input"&&(t=this.getPureInputU64(w.Input))}return{txType:Wt.Other,type:"repay",intentionData:{collateralType:e,repayAmount:t,withdrawAmount:o,isSurplus:!1,insertionPlace:i,strapId:c}}}decodeWithdraw(){let e="",t="0",o,n=this.getStrapId();if(this.getMoveCallCommand("withdraw_with_strap")){let i=this.getMoveCallCommand("withdraw_with_strap").MoveCall;[e]=i.typeArguments;let c=i.arguments[4];c.$kind==="Input"&&(t=this.getPureInputU64(c.Input));let l=i.arguments[5];if(l.$kind==="Input"){let d=this.getPureAddresses(l.Input);d.length===1&&([o]=d)}}else if(this.getMoveCallCommand("withdraw")){let i=this.getMoveCallCommand("withdraw").MoveCall;[e]=i.typeArguments;let c=i.arguments[3];c.$kind==="Input"&&(t=this.getPureInputU64(c.Input));let l=i.arguments[4];if(l.$kind==="Input"){let d=this.getPureAddresses(l.Input);d.length===1&&([o]=d)}}return{txType:Wt.Other,type:"withdraw",intentionData:{collateralType:e,withdrawAmount:t,insertionPlace:o,strapId:n}}}decodeClose(){let e="",t=this.getStrapId();return this.getMoveCallCommand("destroy_empty_strap")&&([e]=this.getMoveCallCommand("destroy_empty_strap").MoveCall.typeArguments),{txType:Wt.Other,type:"close",intentionData:{collateralType:e,strapId:t}}}decodeSBUCKDeposit(){let t=this.getMoveCallCommand("into_balance").MoveCall.typeArguments[0],o="0",i=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];i.$kind==="Input"&&(o=this.getPureInputU64(i.Input));let c=this.isSBUCKStakeTransaction();return console.log("Decoder.decodeSBUCKDeposit",t,o,c),{txType:Wt.Other,type:"sbuck-deposit",intentionData:{coinType:t,amount:o,isStake:c}}}decodeSBUCKUnstake(){let e="0",t=this.isSBUCKStakeTransaction();if(t){let d=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];d.$kind==="Input"&&(e=this.getPureInputU64(d.Input))}let o=[],n=this.getMoveCallModuleCommands("proof_rule","unlock");if(n.length>0)for(let l=0;l<n.length;l++){let d=n[l];o.push("")}else{let l=this.getMoveCallModuleCommands("fountain_core","force_unstake");for(let d=0;d<l.length;d++){let w=l[d].MoveCall.arguments[2];if(w.$kind==="Input"){let{objectId:I}=this.inputs[w.Input].UnresolvedObject;o.push(I)}}}let i=this.isSBUCKWithdrawTransaction(),c={stakeProofs:o,amount:e,isStake:t,toBuck:i};return console.log("Decoder.decodeSBUCKUnstake",c),{txType:Wt.Other,type:"sbuck-unstake",intentionData:c}}decodeSBUCKWithdraw(){let e="0",o=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];return o.$kind==="Input"&&(e=this.getPureInputU64(o.Input)),console.log("Decoder.SBUCKWithdraw",e),{txType:Wt.Other,type:"sbuck-withdraw",intentionData:{amount:e}}}decodeSBUCKClaim(){let e=[],t=this.getMoveCallModuleCommands("fountain_core","claim");for(let o=0;o<t.length;o++){let i=t[o].MoveCall.arguments[2];if(i.$kind==="Input"){let{objectId:c}=this.inputs[i.Input].UnresolvedObject;e.push(c)}}return console.log("Decoder.decodeSBUCKClaim",e),{txType:Wt.Other,type:"sbuck-claim",intentionData:{stakeProofs:e}}}decodeTankDeposit(){let e="0",o=this.getSplitCoinsCommands()[0].SplitCoins.amounts[0];o.$kind==="Input"&&(e=this.getPureInputU64(o.Input));let i=this.getMoveCallModuleCommand("tank_operations","deposit").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankDeposit",i,e),{txType:Wt.Other,type:"tank-deposit",intentionData:{coinType:i,amount:e}}}decodeTankWithdraw(){let e=this.getMoveCallModuleCommand("tank_operations","withdraw").MoveCall,t=e.typeArguments[0],o="0",n=e.arguments[5];return n.$kind==="Input"&&(o=this.getPureInputU64(n.Input)),console.log("Decoder.decodeTankWithdraw",t,o),{txType:Wt.Other,type:"tank-withdraw",intentionData:{coinType:t,amount:o}}}decodeTankClaim(){let t=this.getMoveCallModuleCommand("tank_operations","claim").MoveCall.typeArguments[0];return console.log("Decoder.decodeTankClaim",t),{txType:Wt.Other,type:"tank-claim",intentionData:{coinType:t}}}decodeLockedClaim(){let e="",t=0,o=this.getMoveCallModuleCommands("proof_rule","claim");for(let i=0;i<o.length;i++)[e]=o[i].MoveCall.typeArguments,t++;let n=this.getMoveCallModuleCommands("lst_proof_rule","claim");for(let i=0;i<n.length;i++)[e]=n[i].MoveCall.typeArguments,t++;return console.log("Decoder.decodeLockedClaim",e,t),{txType:Wt.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 o=t.MoveCall.arguments[2];o.$kind==="Input"&&(e=this.inputs[o.Input].UnresolvedObject.objectId)}}return e}getPureInputU64(e){let t=this.inputs[e];if(t.$kind!=="Pure")throw new Error("not pure argument");return rr.U64.fromBase64(t.Pure.bytes)}getPureAddresses(e){let t=this.inputs[e];if(t.$kind!=="Pure")throw new Error("not pure argument");return rr.vector(rr.Address).fromBase64(t.Pure.bytes)}};import{TransactionType as Gl}from"@msafe/sui3-utils";import{Transaction as Hl}from"@mysten/sui/transactions";import{buildPsmTx as Xl}from"bucket-protocol-sdk";import{BucketClient as $l}from"bucket-protocol-sdk";var Ot=(a,e)=>{let t=a==="sui:mainnet"?"mainnet":"testnet";return new $l(t,e.address)};var ys=async(a,e,t)=>{let{coinType:o,amount:n,buckToCoin:i}=a,c=new Hl,l=Ot(t,e);return await Xl(l,c,o,n,i,e.address),c};var wn=class a extends k{constructor(t){super(t);this.data=t}txType=Gl.Other;txSubType="psm";async build(t){let{account:o,network:n}=t;return await ys(this.data,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Zl}from"@msafe/sui3-utils";import{Transaction as In}from"@mysten/sui/transactions";import{buildBorrowTx as Ql,buildCloseTx as zl,buildRepayTx as Jl,buildWithdrawTx as Yl}from"bucket-protocol-sdk";var bs=async(a,e,t)=>{let{collateralType:o,collateralAmount:n,borrowAmount:i,insertionPlace:c,strapId:l}=a,d=new In,S=Ot(t,e);return await Ql(S,d,o,n,i,e.address,c,l),d},Ss=async(a,e,t)=>{let{collateralType:o,withdrawAmount:n,insertionPlace:i,strapId:c}=a,l=new In,d=Ot(t,e);return await Yl(d,l,o,n,e.address,i,c),l},Ts=async(a,e,t)=>{let{collateralType:o,repayAmount:n,withdrawAmount:i,isSurplus:c,insertionPlace:l,strapId:d}=a,S=new In,w=Ot(t,e);return await Jl(w,S,o,n,i,e.address,c,l,d),S},ws=async(a,e,t)=>{let{collateralType:o,recipient:n,strapId:i}=a,c=new In,l=Ot(t,e);return await zl(l,c,o,n,i),c};var Cn=class a extends k{constructor(t){super(t);this.data=t}txType=Zl.Other;txSubType="borrow";async build(t){let{account:o,network:n}=t;return await bs(this.data,o,n)}static fromData(t){return new a(t)}};import{TransactionType as tu}from"@msafe/sui3-utils";var kn=class a extends k{constructor(t){super(t);this.data=t}txType=tu.Other;txSubType="repay";async build(t){let{account:o,network:n}=t;return await Ts(this.data,o,n)}static fromData(t){return new a(t)}};import{TransactionType as eu}from"@msafe/sui3-utils";var xn=class a extends k{constructor(t){super(t);this.data=t}txType=eu.Other;txSubType="withdraw";async build(t){let{account:o,network:n}=t;return await Ss(this.data,o,n)}static fromData(t){return new a(t)}};import{TransactionType as nu}from"@msafe/sui3-utils";var vn=class a extends k{constructor(t){super(t);this.data=t}txType=nu.Other;txSubType="close";async build(t){let{account:o,network:n}=t;return await ws(this.data,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Rn}from"@msafe/sui3-utils";import{Transaction as Dn}from"@mysten/sui/transactions";import{buildSBUCKClaimTx as ou,buildSBUCKDepositTx as au,buildSBUCKUnstakeTx as iu,buildSBUCKWithdrawTx as ru}from"bucket-protocol-sdk";var Is=async(a,e,t)=>{let{coinType:o,amount:n,isStake:i}=a,c=new Dn,l=Ot(t,e);return await au(l,c,o,n,e.address,i),c},Cs=async(a,e,t)=>{let{stakeProofs:o,amount:n,isStake:i,toBuck:c}=a,l=new Dn,d=Ot(t,e);return await iu(d,l,o,n,e.address,i,c),l},ks=async(a,e,t)=>{let{amount:o}=a,n=new Dn,i=Ot(t,e);return await ru(i,n,o,e.address),n},xs=async(a,e,t)=>{let{stakeProofs:o}=a,n=new Dn,i=Ot(t,e);return await ou(i,n,o,e.address),n};var An=class a extends k{constructor(t){super(t);this.data=t}txType=Rn.Other;txSubType="sbuck-deposit";async build(t){let{account:o,network:n}=t;return await Is(this.data,o,n)}static fromData(t){return new a(t)}},On=class a extends k{constructor(t){super(t);this.data=t}txType=Rn.Other;txSubType="sbuck-unstake";async build(t){let{account:o,network:n}=t;return await Cs(this.data,o,n)}static fromData(t){return new a(t)}},Mn=class a extends k{constructor(t){super(t);this.data=t}txType=Rn.Other;txSubType="sbuck-withdraw";async build(t){let{account:o,network:n}=t;return await ks(this.data,o,n)}static fromData(t){return new a(t)}},Pn=class a extends k{constructor(t){super(t);this.data=t}txType=Rn.Other;txSubType="sbuck-claim";async build(t){let{account:o,network:n}=t;return await xs(this.data,o,n)}static fromData(t){return new a(t)}};import{TransactionType as lr}from"@msafe/sui3-utils";import{Transaction as cr}from"@mysten/sui/transactions";import{buildTankClaimTx as su,buildTankDepositTx as cu,buildTankWithdrawTx as lu}from"bucket-protocol-sdk";var vs=async(a,e,t)=>{let{coinType:o,amount:n}=a,i=new cr,c=Ot(t,e);return await cu(c,i,o,n,e.address),i},Ds=async(a,e,t)=>{let{coinType:o,amount:n}=a,i=new cr,c=Ot(t,e);return await lu(c,i,o,n,e.address),i},As=async(a,e,t)=>{let{coinType:o}=a,n=new cr,i=Ot(t,e);return await su(i,n,o,e.address),n};import{Transaction as uu}from"@mysten/sui/transactions";import{buildLockedClaimTx as mu}from"bucket-protocol-sdk";var Os=async(a,e,t)=>{let{coinType:o,proofCount:n}=a,i=new uu,c=Ot(t,e);return await mu(c,i,o,n,e.address),i};var Bn=class a extends k{constructor(t){super(t);this.data=t}txType=lr.Other;txSubType="tank-deposit";async build(t){let{account:o,network:n}=t;return await vs(this.data,o,n)}static fromData(t){return new a(t)}},En=class a extends k{constructor(t){super(t);this.data=t}txType=lr.Other;txSubType="tank-withdraw";async build(t){let{account:o,network:n}=t;return await Ds(this.data,o,n)}static fromData(t){return new a(t)}},Nn=class a extends k{constructor(t){super(t);this.data=t}txType=lr.Other;txSubType="tank-claim";async build(t){let{account:o,network:n}=t;return await As(this.data,o,n)}static fromData(t){return new a(t)}};import{TransactionType as pu}from"@msafe/sui3-utils";var Wn=class a extends k{constructor(t){super(t);this.data=t}txType=pu.Other;txSubType="lock-claim";async build(t){let{account:o,network:n}=t;return await Os(this.data,o,n)}static fromData(t){return new a(t)}};var _n=class{application="bucket";supportSDK="@mysten/sui";async deserialize(e){console.log("Bucket helper deserialize input: ",e);let{transaction:t}=e,n=new Tn(t).decode();return{txType:du.Other,txSubType:n.type,intentionData:n.intentionData}}async build(e){let{suiClient:t,account:o,network:n}=e,i;switch(e.txSubType){case"psm":i=wn.fromData(e.intentionData);break;case"borrow":i=Cn.fromData(e.intentionData);break;case"withdraw":i=xn.fromData(e.intentionData);break;case"repay":i=kn.fromData(e.intentionData);break;case"close":i=vn.fromData(e.intentionData);break;case"tank-deposit":i=Bn.fromData(e.intentionData);break;case"tank-withdraw":i=En.fromData(e.intentionData);break;case"tank-claim":i=Nn.fromData(e.intentionData);break;case"sbuck-deposit":i=An.fromData(e.intentionData);break;case"sbuck-unstake":i=On.fromData(e.intentionData);break;case"sbuck-withdraw":i=Mn.fromData(e.intentionData);break;case"sbuck-claim":i=Pn.fromData(e.intentionData);break;case"lock-claim":i=Wn.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:o,network:n})}};import{TransactionType as Zu}from"@msafe/sui3-utils";import{TransactionType as wu}from"@msafe/sui3-utils";import{AggregatorClient as fu,Env as hu}from"@cetusprotocol/aggregator-sdk";import{CetusFarmsSDK as gu}from"@cetusprotocol/farms-sdk";import{CetusClmmSDK as yu}from"@cetusprotocol/sui-clmm-sdk";import{CetusVaultsSDK as bu}from"@cetusprotocol/vaults-sdk";import{CetusXcetusSDK as Su}from"@cetusprotocol/xcetus-sdk";import{SuiClient as ur,getFullnodeUrl as Ms}from"@mysten/sui/client";var Yt=(a,e)=>{let t=yu.createSDK({env:"mainnet",sui_client:new ur({url:Ms("mainnet")})});return t.setSenderAddress(e.address),t},Lt=(a,e)=>{let t=gu.createSDK({env:"mainnet",sui_client:new ur({url:Ms("mainnet")})});return t.setSenderAddress(e.address),t},Tu="https://api-sui.cetus.zone/router_v2/find_routes",Ps=(a,e)=>{let t=new ur({url:"https://fullnode.mainnet.sui.io/"});return new fu({endpoint:Tu,signer:e.address,client:t,env:hu.Mainnet})},_e=(a,e)=>{let t=bu.createSDK({env:"mainnet"});return t.setSenderAddress(e.address),t},Se=(a,e)=>{let t=Su.createSDK({env:"mainnet"});return t.setSenderAddress(e.address),t};var Rs=async(a,e,t)=>await Yt(t,e).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),Bs=async(a,e,t)=>await Yt(t,e).Position.createAddLiquidityFixTokenPayload(a?.parameter,a?.gasEstimateArg),Es=async(a,e,t)=>await Yt(t,e).Position.closePositionPayload(a),Ns=async(a,e,t)=>await Yt(t,e).Position.removeLiquidityPayload(a),Ws=async(a,e,t)=>await Yt(t,e).Rewarder.collectRewarderPayload(a);var Ln=class a extends k{constructor(t){super(t);this.data=t}txType=wu.Other;txSubType="OpenAndAddLiquidity";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Rs(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Iu}from"@msafe/sui3-utils";var jn=class a extends k{constructor(t){super(t);this.data=t}txType=Iu.Other;txSubType="ClaimFeeAndMining";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Ws(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Cu}from"@msafe/sui3-utils";var Un=class a extends k{constructor(t){super(t);this.data=t}txType=Cu.Other;txSubType="DecreaseLiquidity";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Ns(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as ku}from"@msafe/sui3-utils";var _s=async(a,e,t)=>await Lt(t,e).Farms.openPositionAddLiquidityStakePayload(a),Ls=async(a,e,t)=>await Lt(t,e).Farms.addLiquidityFixCoinPayload(a),js=async(a,e,t)=>await Lt(t,e).Farms.removeLiquidityPayload(a),Us=async(a,e,t)=>await Lt(t,e).Farms.removeLiquidityPayload(a),qs=async(a,e,t)=>await Lt(t,e).Farms.claimFeeAndClmmReward(a),Fs=async(a,e,t)=>await Lt(t,e).Farms.harvestPayload(a),Ks=async(a,e,t)=>{let o=Lt(t,e),n=Object.values(a);return await o.Farms.batchHarvestPayload(n)},Vs=async(a,e,t)=>await Lt(t,e).Farms.depositPayload(a),$s=async(a,e,t)=>await Lt(t,e).Farms.withdrawPayload(a);var qn=class a extends k{constructor(t){super(t);this.data=t}txType=ku.Other;txSubType="FarmingOpenAndAddLiquidity";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await _s(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as xu}from"@msafe/sui3-utils";var Fn=class a extends k{constructor(t){super(t);this.data=t}txType=xu.Other;txSubType="FarmingBatchHarvest";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Ks(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as vu}from"@msafe/sui3-utils";var Kn=class a extends k{constructor(t){super(t);this.data=t}txType=vu.Other;txSubType="FarmingClaimFeeAndReward";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await qs(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Du}from"@msafe/sui3-utils";var Vn=class a extends k{constructor(t){super(t);this.data=t}txType=Du.Other;txSubType="FarmingDecreaseLiquidity";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await js(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Au}from"@msafe/sui3-utils";var $n=class a extends k{constructor(t){super(t);this.data=t}txType=Au.Other;txSubType="FarmingHarvest";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Fs(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Ou}from"@msafe/sui3-utils";var Hn=class a extends k{constructor(t){super(t);this.data=t}txType=Ou.Other;txSubType="FarmingIncreaseLiquidity";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Ls(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Mu}from"@msafe/sui3-utils";var Xn=class a extends k{constructor(t){super(t);this.data=t}txType=Mu.Other;txSubType="FarmingRemoveLiquidity";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Us(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Pu}from"@msafe/sui3-utils";var Gn=class a extends k{constructor(t){super(t);this.data=t}txType=Pu.Other;txSubType="FarmingStake";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Vs(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Ru}from"@msafe/sui3-utils";var Qn=class a extends k{constructor(t){super(t);this.data=t}txType=Ru.Other;txSubType="FarmingUnstake";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await $s(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Bu}from"@msafe/sui3-utils";var zn=class a extends k{constructor(t){super(t);this.data=t}txType=Bu.Other;txSubType="IncreaseLiquidity";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Bs(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as ju}from"@msafe/sui3-utils";import{Transaction as Jn}from"@mysten/sui/transactions";import Eu,{vaults_mainnet as Nu}from"haedal-vault-sdk";var Wu=async(a,e,t)=>{let o=_e(t,e),n=new Jn;return n.setSender(e.address),o.Vest.buildRedeemPayload(a.params,n),n},_u=async(a,e,t)=>{let o=new Eu(Nu);o.senderAddress=e.address;let n=new Jn;return n.setSender(e.address),await o?.Vest.buildRedeemPayload(a.params,n),n},Hs=(a,e,t)=>{let o=Yt(t,e),n=new Jn;return o?.Vest.buildRedeemPayload(a.params,n),n},Lu=async(a,e,t)=>{let o=Yt(t,e),n=Lt(t,e),i=new Jn,c=await n.Farms.withdrawReturnPayload(a.withdrawParams,i);return o.Vest.buildRedeemPayload(a.redeemParms.map(l=>({...l,clmm_position_id:c})),i),n.Farms.depositPayload({...a.depositParams,clmm_position_id:c},i),i},Xs=async(a,e,t)=>a.type==="clmm"?Hs(a,e,t):a.type==="farms"?Lu(a,e,t):a.type==="vaults"?Wu(a,e,t):a.type==="haedalVaults"?_u(a,e,t):Hs(a,e,t);var Yn=class a extends k{constructor(t){super(t);this.data=t}txType=ju.Other;txSubType="PosVestingRedeem";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Xs(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Uu}from"@msafe/sui3-utils";var Zn=class a extends k{constructor(t){super(t);this.data=t}txType=Uu.Other;txSubType="RemoveLiquidity";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Es(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Ku}from"@msafe/sui3-utils";import{restituteMsafeFastRouterSwapParams as qu}from"@cetusprotocol/aggregator-sdk";import{Transaction as Fu}from"@mysten/sui/transactions";var Gs=async(a,e,t)=>{let o=Ps(t,e),n=new Fu;return await o.fastRouterSwap({...a,routers:qu(a.routers),txb:n}),n};var to=class a extends k{constructor(t){super(t);this.data=t}txType=Ku.Other;txSubType="AggregatorSwap";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Gs(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Vu}from"@msafe/sui3-utils";import{Transaction as Qs}from"@mysten/sui/transactions";var zs=async(a,e,t)=>{let o=_e(t,e),n=new Qs;return n.setSender(e.address),await o.Vaults.deposit(a,n),n},Js=async(a,e,t)=>{let o=_e(t,e),n=new Qs;return await o.Vaults.withdraw(a,n),n};var eo=class a extends k{constructor(t){super(t);this.data=t}txType=Vu.Other;txSubType="AddVaultsPosition";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await zs(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as $u}from"@msafe/sui3-utils";var no=class a extends k{constructor(t){super(t);this.data=t}txType=$u.Other;txSubType="RemoveVaultsPosition";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Js(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Xu}from"@msafe/sui3-utils";import{Transaction as Hu}from"@mysten/sui/transactions";var Ys={package_id:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",published_at:"0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31",cetus_coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"},Zs=async(a,e,t)=>{console.log("getVestingRedeemTxb txbParams: ",a),console.log("getVestingRedeemTxb account: ",e),console.log("getVestingRedeemTxb network: ",t);let{pool:o,nftId:n,periods:i,CLOCK_ADDRESS:c}=a,l=new Hu;return i.forEach(d=>{l.moveCall({target:`${Ys.published_at}::router::redeem`,typeArguments:[Ys.cetus_coin_type],arguments:[l.object(o),l.object(n),l.pure(d),l.object(c)]})}),l};var oo=class a extends k{constructor(t){super(t);this.data=t}txType=Xu.Other;txSubType="VestingRedeem";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await Zs(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Gu}from"@msafe/sui3-utils";var tc=async(a,e,t)=>await Se(t,e).XCetusModule.convertPayload(a),ec=async(a,e,t)=>await Se(t,e).XCetusModule.redeemLockPayload(a),nc=async(a,e,t)=>await Se(t,e).XCetusModule.redeemDividendV3Payload(a.veNftId,a.rewardList),oc=async(a,e,t)=>await Se(t,e).XCetusModule.cancelRedeemPayload(a),ac=async(a,e,t)=>await Se(t,e).XCetusModule.redeemPayload(a);var ao=class a extends k{constructor(t){super(t);this.data=t}txType=Gu.Other;txSubType="xCETUSCancelRedeem";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await oc(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Qu}from"@msafe/sui3-utils";var io=class a extends k{constructor(t){super(t);this.data=t}txType=Qu.Other;txSubType="xCETUSClaimStakingRwewards";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await nc(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as zu}from"@msafe/sui3-utils";var ro=class a extends k{constructor(t){super(t);this.data=t}txType=zu.Other;txSubType="xCETUSConvert";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await tc(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Ju}from"@msafe/sui3-utils";var so=class a extends k{constructor(t){super(t);this.data=t}txType=Ju.Other;txSubType="xCETUSRedeem";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await ac(i,o,n)}static fromData(t){return new a(t)}};import{TransactionType as Yu}from"@msafe/sui3-utils";var co=class a extends k{constructor(t){super(t);this.data=t}txType=Yu.Other;txSubType="xCETUSRedeemLock";async build(t){let{account:o,network:n}=t,{txbParams:i}=this.data;return await ec(i,o,n)}static fromData(t){return new a(t)}};var lo=class{application="cetus";supportSDK="@mysten/sui";async deserialize(e){console.log("Cetus helper deserialize input: ",e);let{txbParams:t,action:o}=e;return{txType:Zu.Other,txSubType:o,intentionData:{txbParams:{...t},action:o}}}async build(e){let{suiClient:t,account:o,network:n}=e,i;switch(e.txSubType){case"OpenAndAddLiquidity":i=Ln.fromData(e.intentionData);break;case"IncreaseLiquidity":i=zn.fromData(e.intentionData);break;case"DecreaseLiquidity":i=Un.fromData(e.intentionData);break;case"RemoveLiquidity":i=Zn.fromData(e.intentionData);break;case"ClaimFeeAndMining":i=jn.fromData(e.intentionData);break;case"FarmingOpenAndAddLiquidity":i=qn.fromData(e.intentionData);break;case"FarmingIncreaseLiquidity":i=Hn.fromData(e.intentionData);break;case"FarmingDecreaseLiquidity":i=Vn.fromData(e.intentionData);break;case"FarmingRemoveLiquidity":i=Xn.fromData(e.intentionData);break;case"FarmingClaimFeeAndReward":i=Kn.fromData(e.intentionData);break;case"FarmingHarvest":i=$n.fromData(e.intentionData);break;case"FarmingBatchHarvest":i=Fn.fromData(e.intentionData);break;case"FarmingStake":i=Gn.fromData(e.intentionData);break;case"FarmingUnstake":i=Qn.fromData(e.intentionData);break;case"xCETUSConvert":i=ro.fromData(e.intentionData);break;case"xCETUSRedeemLock":i=co.fromData(e.intentionData);break;case"xCETUSClaimStakingRwewards":i=io.fromData(e.intentionData);break;case"xCETUSCancelRedeem":i=ao.fromData(e.intentionData);break;case"xCETUSRedeem":i=so.fromData(e.intentionData);break;case"VestingRedeem":i=oo.fromData(e.intentionData);break;case"AggregatorSwap":i=to.fromData(e.intentionData);break;case"AddVaultsPosition":i=eo.fromData(e.intentionData);break;case"RemoveVaultsPosition":i=no.fromData(e.intentionData);break;case"PosVestingRedeem":i=Yn.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:o,network:n})}};import{TransactionType as Jm}from"@msafe/sui3-utils";import tm from"sort-keys-recursive";var P=class{constructor(e){this.data=e}serialize(){return JSON.stringify(tm(this.data))}};import{getFullnodeUrl as uo}from"@mysten/sui.js/client";var mr={};hs(mr,{contractId:()=>om,default:()=>cm,feeObjId:()=>rm,roleObjId:()=>am,status:()=>nm,transaction:()=>em,upgradeCapObjId:()=>sm,vaultObjId:()=>im});var em="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",nm="success",om="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",am="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",im="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",rm="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",sm="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",cm={transaction:em,status:nm,contractId:om,roleObjId:am,vaultObjId:im,feeObjId:rm,upgradeCapObjId:sm};var pr={};hs(pr,{contractId:()=>mm,default:()=>gm,feeObjId:()=>fm,roleObjId:()=>pm,status:()=>um,transaction:()=>lm,upgradeCapObjId:()=>hm,vaultObjId:()=>dm});var lm="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",um="success",mm="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",pm="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",dm="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",fm="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",hm="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",gm={transaction:lm,status:um,contractId:mm,roleObjId:pm,vaultObjId:dm,feeObjId:fm,upgradeCapObjId:hm};var ym=uo("testnet"),bm=uo("testnet"),Sm=uo("mainnet"),Tm=uo("mainnet"),wm="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Im="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Cm="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",km="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",ic=mr,rc=pr,xm=new Map([["dev",{env:"dev",rpc:{url:ym},backend:{url:wm},contract:ic}],["stg",{env:"stg",rpc:{url:bm},backend:{url:Im},contract:ic}],["prev",{env:"prev",rpc:{url:Sm},backend:{url:Cm},contract:rc}],["prod",{env:"prod",rpc:{url:Tm},backend:{url:km},contract:rc}]]);function sc(a,e){let t=xm.get(a);if(!t)throw new Error(`Env not supported: ${a}`);return e&&e.rpc&&(t.rpc=e.rpc),e&&e.backend&&(t.backend=e.backend),e&&e.contract&&(t.contract=e.contract),t}import{SuiClient as Dm}from"@mysten/sui.js/client";var L=class extends Error{mpayErrorCode;context;constructor(e,t,o={}){let{cause:n,context:i}=o;n?super(`[MPay] ${t}: ${n}`):super(`[MPay] ${t}`),this.mpayErrorCode=e,this.context=i}};var mo=class extends L{constructor(){super(11,"Backend is not specified")}};var po=class extends L{constructor(){super(1,"Wallet not connected")}};import we,{AxiosError as vm}from"axios";var Te=class extends L{constructor(e,t){super(10,e,{context:t})}};var fo=class a{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof vm)throw new Te(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new Te(e.data.code)}throw new Te(e.status.toString())}async getIncomingStreams(e,t){let o=await we.post(`${this.apiURL}/stream`,{recipient:e,...t});return a.parseResponseData(o)}async getOutgoingStreams(e,t){let o=await we.post(`${this.apiURL}/stream`,{sender:e,...t});return a.parseResponseData(o)}async getStreamHistory(e){let t=await we.post(`${this.apiURL}/stream-events`,e),o=a.parseResponseData(t);return o.data.forEach(n=>{let i=n;return i.data.type==="create_stream"?i.data.balance=BigInt(i.data.balance):i.data.type==="cancel_stream"?i.data.withdrawAmount=BigInt(i.data.withdrawAmount):i.data.type==="claim"||i.data.type==="auto_claim"?i.data.claimAmount=BigInt(i.data.claimAmount):i.data.type==="set_auto_claim"&&(i.data.enabled=!!i.data.enabled),i.createdAt=new Date(i.createdAt),i}),o}async getAllCoinTypes(e){let t=await we.post(`${this.apiURL}/stream-info`,{address:e});return a.parseResponseData(t)}async getAllRecipients(e,t){let o=await we.post(`${this.apiURL}/stream-info`,{sender:e,status:t});return a.parseResponseData(o)}async getAllSenders(e,t){let o=await we.post(`${this.apiURL}/stream-info`,{recipient:e,status:t});return a.parseResponseData(o)}};var Ie=class a{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Dm({url:e.rpc.url}),e.backend&&(this._backend=new fo(e.backend.url))}static new(e,t){let o=sc(e,t);return new a(o)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new mo;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 po;return this.signer}async walletAddress(){return this.wallet.address()}};import{SUI_TYPE_ARG as Gm,normalizeStructTag as Qm,normalizeSuiAddress as Pc}from"@mysten/sui.js/utils";import{TransactionBlock as To}from"@mysten/sui.js/transactions";import{TransactionBlock as gc}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as yc,normalizeStructTag as Pm}from"@mysten/sui.js/utils";var dr=50n,ho=10000n,cc=25n,fr=100000000n;var Gt=class{constructor(e){this.object=e}moveArg(e){return e.object(this.object)}},Le=class{constructor(e){this.objects=e}moveArgs(e){return e.makeMoveVec({objects:this.objects.map(t=>e.object(t))})}},oe=class a{constructor(e){this.result=e;return new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(t,o){if(o in t)return Reflect.get(t,o);let n=c=>new a(t.result[c]);if(o===Symbol.iterator)return function*(){let c=0;for(;;)yield n(c),c++};if(typeof o=="symbol")return;let i=parseInt(o,10);if(!(Number.isNaN(i)||i<0))return n(i)}})}moveArg(){return this.result}};import{Buffer as lc}from"buffer";import{normalizeSuiAddress as Am}from"@mysten/sui.js/utils";var je=class extends L{constructor(e,t){super(3,e,{context:t})}};var go=class{constructor(e){this.results=e}callResult(e){return this.results.results[e]}returnValue(e,t){return e.returnValues[t]}getValue(e=0,t=0){let o=this.callResult(e);return this.returnValue(o,t)}getAddress(e=0,t=0){let[o,n]=this.getValue(e,t);if(n!=="address")throw new je("Invalid contract return type.",{ctx:{expectType:"address",gotType:n}});return Am(lc.from(o).toString("hex"))}getU64(e=0,t=0){let[o,n]=this.getValue(e,t);if(n!=="u64")throw new je("Invalid contract return type.",{ctx:{expectType:"u64",gotType:n}});return lc.from(o).readBigInt64LE()}};import{bcs as mc}from"@mysten/sui.js/bcs";var H=class extends L{constructor(e,t,o){super(2,`Invalid input: ${e}`,{context:{fieldKey:t,fieldValue:o}})}};var pc={groupId:"string",name:"string"},Om=64;function dc(a){return fc(a),mc.ser(pc,a).toString("base64")}function Ue(a){let e=mc.de(pc,a,"base64");return fc(e),e}function fc(a){if(!uc(a.name))throw new H("Invalid metadata: Name contains unknown character");if(!uc(a.groupId))throw new H("Invalid metadata: Group ID contains unknown character");if(a.name.length>Om)throw new H("Invalid metadata: Name exceed max length 64")}function uc(a){return/^[\x00-\x7F]+$/.test(a)}import{normalizeStructTag as yo}from"@mysten/sui.js/utils";function bo(a,e){return yo(a)===yo(e)}function ae(a,e){return yo(a)===yo(e)}var So="txn.gas";import{nanoid as Mm}from"nanoid";function hc(){return Mm()}var pe=class a{constructor(e,t,o){this.globals=e;this.feeContract=t;this.streamContract=o}static convertCreateStreamInfoToInternal(e){return{metadata:dc({name:e.name,groupId:hc()}),coinType:Pm(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 gc,o=this.calculateFeesInternal(e),n=this.getCreateStreamCoinRequests(e,o),i=await this.wallet.requestCoins(n),c=await this.addMergeCoins(t,i[0]),l;n.length>1?l=await this.addMergeCoins(t,i[1]):l=c;for(let d=0;d<e.recipients.length;d++){let S=e.recipients[d],w=this.amountForRecipient(S,e.numberEpoch),I=this.getStreamFeeLocal(w),[C]=t.splitCoins(c,[t.pure(w+I,"u64")]),[x]=t.splitCoins(l,[t.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(t,{paymentCoin:new oe(C),flatFeeCoin:new oe(x),metadata:e.metadata,recipient:S.address,timeStart:e.startTime,cliff:S.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:S.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return t}calculateCreateStreamFees(e){let t=a.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(t)}feeParams(){return{createFeePercent:{numerator:dr,denominator:ho},claimFeePercent:{numerator:cc,denominator:ho},flatFeePerStream:fr}}async addMergeCoins(e,t){let o;return t.mergedCoins&&t.mergedCoins.length?(e.mergeCoins(e.object(t.primaryCoin),t.mergedCoins.map(n=>e.object(n))),o=e.object(t.primaryCoin)):t.primaryCoin===So?o=e.gas:o=e.object(t.primaryCoin),o}getCreateStreamCoinRequests(e,t){let o=e.coinType;return bo(o,yc)?[{coinType:o,amount:t.totalAmount+t.streamFeeAmount+t.flatFeeAmount}]:[{coinType:o,amount:t.totalAmount+t.streamFeeAmount},{coinType:yc,amount:t.flatFeeAmount}]}calculateFeesInternal(e){let t=e.recipients.reduce((n,i)=>{let c=this.amountForRecipient(i,e.numberEpoch),l=this.getStreamFeeLocal(c);return{totalAmount:n.totalAmount+c,streamFeeAmount:n.streamFeeAmount+l}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...t}}amountForRecipient(e,t){return BigInt(e.amountPerEpoch)*BigInt(t)+BigInt(e.cliffAmount)}get flatSuiFee(){return fr}getStreamFeeLocal(e){return e*dr/ho}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new gc,e),o=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:t});return new go(o).getU64()}get wallet(){return this.globals.wallet}};import{Transactions as Sc}from"@mysten/sui.js/transactions";var bc="0x0000000000000000000000000000000000000000000000000000000000000006";var Ce=class{constructor(e,t,o){this.moduleName=e;this.config=t;this.globals=o}addContractCall(e,t){let o=`${this.config.contractId}::${this.moduleName}::${t.method}`;return e.add(Sc.MoveCall({target:o,arguments:t.arguments.map(n=>n instanceof Le?n.moveArgs(e):n instanceof Gt?n.moveArg(e):n instanceof oe?n.moveArg():e.pure(n)),typeArguments:t.typeArgs})),e}addTransactionBlock(e,t,o=[],n=[]){e.add(Sc.MoveCall({target:t,arguments:o.map(i=>i instanceof Le?i.moveArgs(e):i instanceof Gt?i.moveArg(e):i instanceof oe?i.moveArg():e.pure(i)),typeArguments:n}))}makeObject(e){return typeof e=="string"?new Gt(e):e}vaultObject(){return new Gt(this.config.vaultObjId)}roleObject(){return new Gt(this.config.roleObjId)}feeObject(){return new Gt(this.config.feeObjId)}clockObject(){return new Gt(bc)}};var ke=class a extends Ce{constructor(t,o){super(a.ModuleName,t,o);this.config=t;this.globals=o}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,o){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_streaming_fee,arguments:[n,i,o],typeArgs:[]})}setStreamingFlatFee(t,o){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_streaming_flat_fee,arguments:[n,i,o],typeArgs:[]})}setClaimFee(t,o){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(t,{method:a.MethodName.set_claim_fee,arguments:[n,i,o],typeArgs:[]})}streamingFee(t,o){let n=this.feeObject();return this.addContractCall(t,{method:a.MethodName.streaming_fee,arguments:[n,o],typeArgs:[]})}claimFee(t,o){return this.addContractCall(t,{method:a.MethodName.claim_fee,arguments:[this.feeObject(),o],typeArgs:[]})}feeDenominator(t){return this.addContractCall(t,{method:a.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var Qt=class a extends Ce{constructor(t,o){super(a.ModuleName,t,o);this.config=t;this.globals=o}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,o){let n=this.feeObject(),i=this.vaultObject(),c=this.makeObject(o.paymentCoin),l=this.makeObject(o.flatFeeCoin),d=this.clockObject();return this.addContractCall(t,{method:a.MethodName.create_stream,arguments:[n,i,c,l,o.metadata,o.recipient,o.timeStart,o.cliff,o.epochInterval,o.numEpoch,o.amountPerEpoch,o.cancelable,d],typeArgs:[o.coinType]})}setAutoClaim(t,o){let n=this.makeObject(o.streamId);return this.addContractCall(t,{method:a.MethodName.set_auto_claim,arguments:[n,o.enabled],typeArgs:[o.coinType]})}cancelStream(t,o){let n=this.makeObject(o.streamId),i=this.clockObject();return this.addContractCall(t,{method:a.MethodName.cancel_stream,arguments:[n,i],typeArgs:[o.coinType]})}claimStream(t,o){let n=this.makeObject(o.streamId),i=this.clockObject();return this.addContractCall(t,{method:a.MethodName.claim_stream,arguments:[n,i],typeArgs:[o.coinType]})}claimStreamByProxy(t,o){let n=this.makeObject(o.streamId),i=this.vaultObject(),c=this.feeObject(),l=this.clockObject();return this.addContractCall(t,{method:a.MethodName.claim_stream_by_proxy,arguments:[n,i,c,l],typeArgs:[o.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${a.ModuleName}::${a.MethodName.claim_stream_by_proxy}`}};var xe=class{constructor(e){this.globals=e;let t=e.envConfig.contract;this.feeContract=new ke(t,e),this.streamContract=new Qt(t,e)}feeContract;streamContract;async createStreams(e){let t=pe.convertCreateStreamInfoToInternal(e);return this.createStreamHelper().buildCreateStreamTransactionBlock(t)}createStreamHelper(){return new pe(this.globals,this.feeContract,this.streamContract)}setAutoClaim(e,t,o){let n=new To;return this.streamContract.setAutoClaim(n,{streamId:e,enabled:t,coinType:o})}claimStream(e,t){let o=new To;return this.streamContract.claimStream(o,{streamId:e,coinType:t})}claimStreamByProxy(e,t){let o=new To;return this.streamContract.claimStreamByProxy(o,{streamId:e,coinType:t})}cancelStream(e,t){let o=new To;return this.streamContract.cancelStream(o,{streamId:e,coinType:t}),o}};import{normalizeStructTag as hr,SUI_TYPE_ARG as Rm}from"@mysten/sui.js/utils";import{Duration as Tc}from"luxon";var wo=class extends L{constructor(e,t){super(12,`Transaction failed: ${t}`,{context:{status:e,msg:t}})}};var Bm=1e3,Io=class{constructor(e){this.globals=e;this.coinMetaHelper=new gr(e.suiClient),this.createStreamHelper=new xe(e).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(e){if(e.effects?.status.status!=="success")throw new wo(e.effects?.status.status,e.effects?.status.error);return e.objectChanges.filter(t=>t.type==="created"&&t.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(t=>t.objectId)}calculateCreateStreamFees(e){return this.createStreamHelper.calculateCreateStreamFees(e)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=e.cliff?e.cliff:{numerator:0n,denominator:100n},o=e.totalAmount*t.numerator/t.denominator,n=(e.totalAmount-o)/e.steps,c={realTotalAmount:n*e.steps+o,cliffAmount:o,amountPerStep:n};return this.validateStreamAmount(c,e.totalAmount),c}calculateTimelineByInterval(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=e.timeStart.plus(e.interval.toMillis()*Number(e.steps)),o={timeStart:e.timeStart,timeEnd:t,interval:e.interval,steps:e.steps};return this.validateTimeline(o),o}calculateTimelineByTotalDuration(e){if(e.steps===0n)throw new H("Invalid stream steps: 0");let t=BigInt(e.total.toMillis())/e.steps,o=e.timeStart.plus(Tc.fromMillis(Number(t*e.steps))),n={timeStart:e.timeStart,timeEnd:o,interval:Tc.fromMillis(Number(t)),steps:e.steps};return this.validateTimeline(n),n}async getBalance(e,t){let o=await this.globals.suiClient.getBalance({owner:e,coinType:t}),n=await this.getCoinMeta(t);return{...o,coinType:hr(o.coinType),coinMeta:n}}async getAllBalance(e){let t=await this.globals.suiClient.getAllBalances({owner:e}),o=await Promise.all(t.map(n=>this.getCoinMeta(n.coinType)));return t.map((n,i)=>({...n,coinType:hr(n.coinType),coinMeta:o[i]}))}async getCoinMeta(e){return this.coinMetaHelper.getCoinMeta(e)}async simulateTransactionBlock(e){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:e,sender:await this.globals.wallet.address()})}validateStreamAmount(e,t){if(e.amountPerStep===0n)throw new H("Stream amount too small","totalAmount",t);if(e.cliffAmount>e.realTotalAmount)throw new H("Invalid cliff settings")}validateTimeline(e){if(e.interval.toMillis()<Bm)throw new H("Interval shall be at least 1 second","interval",e.interval)}},gr=class{constructor(e){this.suiClient=e;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(e){let t=hr(e||Rm);if(this.coinMetaReg.has(t))return this.coinMetaReg.get(t);let o=await this.queryCoinMeta(t);return o&&this.coinMetaReg.set(t,o),o}async queryCoinMeta(e){return await this.suiClient.getCoinMetadata({coinType:e})||void 0}};import{normalizeStructTag as Cc,normalizeSuiAddress as Ao}from"@mysten/sui.js/utils";import{DateTime as kc}from"luxon";import{TransactionBlock as vo}from"@mysten/sui.js/transactions";import{normalizeStructTag as Ic,parseStructTag as Wm}from"@mysten/sui.js/utils";import{DateTime as _m}from"luxon";var Co=class extends L{constructor(){super(7,"Connected wallet is not creator")}};var qe=class extends L{constructor(){super(8,"Connected wallet is not recipient")}};var Fe=class extends L{constructor(e,t){super(6,e,{context:t})}};var At=class extends L{constructor(e,t={}){super(0,e,t)}};var ko=class extends L{constructor(e){super(5,"Stream not found",{context:{streamId:e}})}};import{DateTime as Em,Duration as Nm}from"luxon";var wc=(1n<<64n)-1n,xo=1e3;function yr(a){let e;typeof a=="number"?e=a:typeof a=="bigint"?e=Number(a):e=a.toMillis();let t=Math.round(e/xo);return Em.fromMillis(t*xo)}function br(a){let e;typeof a=="number"?e=a:typeof a=="bigint"?e=Number(a):e=a.toMillis();let t=Math.round(e/xo);return Nm.fromMillis(t*xo)}var ie=class a{constructor(e,t,o){this.globals=e;this.streamId=t;this.rawData=o;this.streamContract=new Qt(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,t){let o=await a.fetchStreamData(e,t);return new a(e,t,o)}static fromObjectData(e,t,o){let n=a.parseRawStreamData(t,o);return new a(e,t,n)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await a.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new At("Object Id does not align");this.rawData=a.parseRawStreamData(this.streamId,e)}async historyEvents(e){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:e})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new Co;let e=new vo;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new qe;let e=new vo;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new qe;let t=new vo;return this.streamContract.setAutoClaim(t,{streamId:this.streamId,coinType:this.coinType,enabled:e}),t}async claimByProxy(){let e=new vo;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 Ic(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 br(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Ue(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Ue(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return yr(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return br(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:yr((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===wc?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=_m.now().toMillis(),t=this.timeStart.toMillis();if(e<t)return-1n;let o=Math.floor((e-t)/Number(this.rawData.config.epochInterval));return BigInt(o)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(o)}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 o=await e.suiClient.getObject({id:t,options:{showContent:!0,showType:!0}});return a.parseRawStreamData(t,o)}static parseRawStreamData(e,t){if(t.error)throw t.error.code==="notExists"?new ko(e):new Fe(`get stream data: ${t.error.code}`,{streamId:e,...t.error});let o=t.data.content;if(o.dataType!=="moveObject")throw new Fe("Unexpected object type",{gotType:o.dataType});let{typeParams:n}=Wm(o.type),i=Ic(n[0]),c=o.fields,l=c.config.fields,d=c.status.fields;return{coinType:i,autoClaim:c.auto_claim,balance:BigInt(c.balance.fields.balance),config:{amountPerEpoch:BigInt(l.amount_per_epoch),cancelable:l.cancelable,cliff:BigInt(l.cliff),creator:l.creator,epochInterval:BigInt(l.epoch_interval),metadata:l.metadata,recipient:l.recipient,timeStart:BigInt(l.time_start),totalEpoch:BigInt(l.total_epoch)},status:{status:d.status,epochCanceled:BigInt(d.epoch_canceled),epochClaimed:BigInt(d.epoch_claimed)}}}};var ve=class extends L{constructor(e,t){super(9,`Invalid stream group: ${e}`,{context:t})}};async function Tr(a){let e=[];for(;await a.hasNext();){let t=await a.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var Sr=class{constructor(e){this.requester=e;this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},De=class{constructor(e){this.requester=e;this.pager=new Sr(e),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}};var Lm=25;async function Ir(a,e,t){let o=new Ke(e),n=new Ve(a,o,t);return await Tr(n)}var Ke=class{constructor(e){this.ids=e;this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},Ve=class extends De{constructor(t,o,n){super(new wr(t,o,n));this.suiClient=t;this.idIter=o;this.options=n}},wr=class{constructor(e,t,o){this.suiClient=e;this.stringIter=t;this.options=o;this.filter=o?.filter,this.pageSize=o?.pageSize||Lm,this.objectOptions=o?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let e=[];for(;e.length<this.pageSize&&await this.stringIter.hasNext();){let i=await this.stringIter.next();i&&e.push(i)}let t=await this.suiClient.multiGetObjects({ids:e,options:this.objectOptions}),o;if(this.filter){let{filter:n}=this;o=t.filter(i=>n?.(i))}else o=t;return{data:o,hasNext:await this.stringIter.hasNext()}}};var Do=class a{constructor(e,t){this.globals=e;this.streams=t;if(t.length===0)throw new ve("stream size 0");let o=t.map(i=>i.groupId);if(new Set(o).size!==1)throw new H("Stream does not have same group ID")}type="StreamGroup";static async new(e,t){let o=await Ir(e.suiClient,t);return o.forEach(n=>{if(!n)throw new At("stream group object data undefined")}),a.newFromObjectResponse(e,t,o)}static async newFromObjectResponse(e,t,o){let n=await a.parseGroupStreams(e,t,o);return new a(e,n)}static checkStreamGroup(e){let t=e.map(i=>i.groupCommonInfo),o=t[0],n=!0;return t.forEach(i=>{jm(o,i)||(n=!1)}),n}async refresh(){let e=await Ir(this.globals.suiClient,this.streams.map(t=>t.streamId));this.streams.forEach((t,o)=>{t.refreshWithData(e[o])})}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,o){let n=o.map((i,c)=>ie.fromObjectData(e,t[c],i)).filter(i=>!!i);if(new Set(n.map(i=>i.groupId)).size!==1)throw new ve("Not same group ID");if(!this.checkStreamGroup(n))throw new ve("Not same stream settings");return n}};function jm(a,e){return a.name===e.name&&a.groupId===e.groupId&&a.creator===e.creator&&a.start.toMillis()===e.start.toMillis()&&a.interval.toMillis()===e.interval.toMillis()&&a.steps===e.steps&&a.cancelable===e.cancelable}var $e=class a{constructor(e,t){this.it=e;this.pageSize=t}static async newIncoming(e){let t=await Oo.newIncoming(e);return new a(t,e.pageSize)}static async newOutgoing(e){let t=await Oo.newOutgoing(e);return new a(t,e.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let e=[];for(;e.length<this.pageSize&&await this.it.hasNext();)e.push(await this.it.next());return e}},Oo=class a{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let t=await Mo.newIncomingQuery(e);return new a(t)}static async newOutgoing(e){let t=await Mo.newOutgoingQuery(e);return new a(t)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let t=await this.requester.doNextRequest();if(t===null)throw new At("No more results");return t}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new At("No more results");return e}},Mo=class a{constructor(e,t,o,n){this.globals=e;this.recipient=t;this.groupRefs=o;this.query=n;this.current=0;let i=new Ke(o.flat().map(c=>c.streamId));this.objectIter=new Ve(e.suiClient,i)}current=0;objectIter;static async newIncomingQuery(e){let t=Vm(e.query),o=await e.globals.walletAddress(),i=(await e.globals.backend.getIncomingStreams(o,t)).filter(l=>Ao(l.recipient)===Ao(o)),c=xc(i);return new a(e.globals,o,c,e.query)}static async newOutgoingQuery(e){let t=$m(e.query),o=await e.globals.walletAddress(),n=await e.globals.backend.getOutgoingStreams(o,t),i=xc(n);return new a(e.globals,o,i,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let t=await Fm(this.globals,e[0].streamId,this.objectIter);return this.current++,vc(t,this.query)?t:this.doNextRequest()}if(e.length>1){let t=await Km(this.globals,e.map(o=>o.streamId),this.objectIter);return this.current++,qm(t,this.query)?t:this.doNextRequest()}throw new At("Stream group with no stream")}};function xc(a){let e=new Map;return a.forEach(t=>{let o=e.get(t.groupId);o?(o.push(t),e.set(t.groupId,o)):e.set(t.groupId,[t])}),Array.from(e.values()).sort((t,o)=>kc.fromISO(o[0].createDate).toMillis()-kc.fromISO(t[0].createDate).toMillis())}function vc(a,e){if(e===void 0)return!0;let t=Um(a,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let o=e.claimable?a.progress.claimable!==0n:a.progress.claimable===0n;return t&&o}return t}function Um(a,e){return e===void 0?!0:Array.isArray(e)?e.includes(a.progress.status):a.progress.status===e}function qm(a,e){if(!e)return!0;let t=!1;return a.streams.forEach(o=>{vc(o,e)&&(t=!0)}),t}async function Fm(a,e,t){let o=await Dc(t,e);return ie.fromObjectData(a,e,o)}async function Km(a,e,t){let o=[];for(;o.length<e.length;){let n=await Dc(t,e[o.length]);o.push(n)}return Do.newFromObjectResponse(a,e,o)}async function Dc(a,e){if(!await a.hasNext())throw new At("object iterator has been consumed");let t=await a.next();if(!t||t.error||t.data===void 0||t.data===null)throw new At("object iterator undefined response",{cause:t?.error});if(t?.data?.objectId!==e)throw new At("stream id not aligned");return t}function Vm(a){return{status:Cr(a?.status),coinType:Ac(a?.coinType),sender:Oc(a?.sender)}}function $m(a){return{status:Cr(a?.status),coinType:Ac(a?.coinType),recipient:Oc(a?.recipient)}}function Cr(a){return a===void 0||a.length===0?"all":Array.isArray(a)?a.reduce((e,t)=>{let o=Cr(t);return!e||e===o?o:"all"},void 0):Hm(a)}function Hm(a){switch(a){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new H("Unknown stream filtered status")}}function Ac(a){if(a)return Array.isArray(a)?a.length!==0?a.map(e=>Cc(e)):void 0:Cc(a)}function Oc(a){if(a)return Array.isArray(a)?a.length!==0?a.map(e=>Ao(e)):void 0:Ao(a)}var Po=class extends L{constructor(t,o,n){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:o,gotAmount:n}});this.coinType=t;this.requestAmount=o;this.gotAmount=n}};var Xm=25;async function Mc(a,e,t,o="0x2::sui::SUI",n=Xm){let i=new kr(a,e,o,n),c=BigInt(0),l=[];for(;await i.hasNext()&&c<t;){let d=await i.next();d&&(l.push(d),c+=BigInt(d.balance))}if(c<t)throw new Po(o,t,c);return l}var kr=class extends De{constructor(t,o,n,i){super(new xr(t,o,n,i));this.suiClient=t;this.owner=o;this.coinType=n;this.reqPageSize=i}},xr=class{constructor(e,t,o,n){this.suiClient=e;this.owner=t;this.coinType=o;this.reqPageSize=n;if(n<=0)throw new At("Invalid reqPageSize")}nextCursor;async doNextRequest(){let e=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=e.nextCursor,{data:e.data,hasNext:e.hasNextPage}}};var vr=class{constructor(e){this.msafe=e}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(e){return this.msafe.requestCoins(e)}},Ro=class{constructor(e){this.account=e}async address(){return this.account.address}},Dr=class{constructor(e,t){this.singleWallet=e;this.suiClient=t}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(e){return Promise.all(e.map(t=>this.requestCoin(t)))}async requestCoin(e){if(bo(e.coinType,Gm))return{primaryCoin:So};if(e.amount<=0)throw new H("Invalid coin request","coinAmount",e.amount);let t=await Mc(this.suiClient,await this.address(),e.amount,e.coinType);if(t.length===0)throw new At("no coins available");return{primaryCoin:t[0].coinObjectId,mergedCoins:t.slice(1).map(o=>o.coinObjectId)}}},Bo=class{globals;helper;constructor(e,t){this.globals=Ie.new(e,t),this.helper=new Io(this.globals)}connectSingleWallet(e){let t=new Dr(e,this.globals.suiClient);this.globals.connectWallet(t)}connectMSafeAccount(e){let t=new vr(e);this.globals.connectWallet(t)}async createStream(e){return this.builder().createStreams(e)}async getStream(e){return ie.new(this.globals,e)}async getIncomingStreams(e,t=10){return $e.newIncoming({globals:this.globals,query:e,pageSize:t})}async getOutgoingStreams(e,t=10){return $e.newOutgoing({globals:this.globals,query:e,pageSize:t})}async getCoinTypesForStreamFilter(){let e=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(e)).map(o=>Qm(o))}async getRecipientsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllRecipients(t,e)).map(n=>Pc(n))}async getCreatorsForStreamFilter(e){let t=await this.wallet.address();return(await this.globals.backend.getAllSenders(t,e)).map(n=>Pc(n))}get wallet(){return this.globals.wallet}builder(){return new xe(this.globals)}};var Ut=class extends P{application="mpay";getClient(e,t){let o=new Bo(e==="sui:mainnet"?"prod":"dev");return o.connectSingleWallet(new Ro(t)),o}};var He=class extends Ut{constructor(t){super(t);this.data=t}txType=Jm.Stream;txSubType="Cancel";async build(t){let{network:o,account:n}=t;return(await this.getClient(o,n).getStream(this.data.streamId)).cancel()}};import{TransactionType as Ym}from"@msafe/sui3-utils";var Xe=class extends Ut{constructor(t){super(t);this.data=t}txType=Ym.Stream;txSubType="ClaimByProxy";async build(t){let{network:o,account:n}=t;return(await this.getClient(o,n).getStream(this.data.streamId)).claimByProxy()}};import{TransactionType as Zm}from"@msafe/sui3-utils";var Ge=class extends Ut{constructor(t){super(t);this.data=t}txType=Zm.Stream;txSubType="Claim";async build(t){let{network:o,account:n}=t;return(await this.getClient(o,n).getStream(this.data.streamId)).claim()}};import{TransactionType as tp}from"@msafe/sui3-utils";var Qe=class extends Ut{constructor(t){super(t);this.data=t}txType=tp.Stream;txSubType="CreateStream";async build(t){let{network:o,account:n}=t;return this.getClient(o,n).createStream(this.data)}};import{bcs as Rc}from"@mysten/sui.js/bcs";import{normalizeStructTag as ep,normalizeSuiAddress as ze}from"@mysten/sui.js/utils";var Ae=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return BigInt(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return ze(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let o=this.getInputParam(e);return a.getPureInputValue(o,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let o=e.value.Pure;return Rc.de(t,new Uint8Array(o))}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 ze(e.value.Object.ImmOrOwned.objectId)}return ze(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return ze(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return ze(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let o=e.value.Pure;return Rc.de(t,new Uint8Array(o))}typeArg(e){return ep(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};var Eo=class{constructor(e,t){this.globals=e;this.txb=t}decode(){let e=this.decodeCreateStreamInfo(),t=this.createStreamHelper().calculateCreateStreamFees(e);return{type:"CreateStream",info:e,fees:t}}decodeCreateStreamInfo(){let t=this.createStreamTransactions().map(o=>this.getCreationInfoFromMoveCall(o));return this.aggregateGroupStreamInfo(t)}createStreamTransactions(){let e=this.transactions.filter(t=>t.kind==="MoveCall"&&ae(t.target,this.contract.createStreamTarget));if(e.length===0)throw new At("No create stream transactions");return e.map(t=>new Ae(t,this.txb))}getCreationInfoFromMoveCall(e){let t=e.decodeInputString(4),{name:o,groupId:n}=Ue(t),i=e.decodeInputAddress(5),c=e.decodeInputU64(6),l=e.decodeInputU64(7),d=e.decodeInputU64(8),S=e.decodeInputU64(9),w=e.decodeInputU64(10),I=e.decodeInputBool(11),C=e.typeArg(0);return{name:o,groupId:n,recipient:i,timeStart:c,cliff:l,epochInterval:d,totalEpoch:S,amountPerEpoch:w,cancelable:I,coinType:C}}aggregateGroupStreamInfo(e){if(new Set(e.map(n=>JSON.stringify({name:n.name,groupId:n.groupId,timeStart:String(n.timeStart),epochInterval:String(n.epochInterval),totalEpoch:String(n.totalEpoch),cancelable:n.cancelable,coinType:n.coinType}))).size!==1)throw new H("Stream group not have common info");let o=e.map(n=>({address:n.recipient,amountPerStep:n.amountPerEpoch,cliffAmount:n.cliff}));return{name:e[0].name,coinType:e[0].coinType,recipients:o,interval:e[0].epochInterval,steps:e[0].totalEpoch,startTimeMs:e[0].timeStart,cancelable:e[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(e=>e.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new Qt(this.globals.envConfig.contract,this.globals)}get feeContract(){return new ke(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new pe(this.globals,this.feeContract,this.contract)}getInputArg(e){if(e.kind!=="Input")throw new Error("not input type");return"value"in e?e:this.txb.blockData.inputs[e.index]}};var No=class{constructor(e,t){this.globals=e;this.txb=t;this.contract=new Qt(e.envConfig.contract,e)}contract;decode(){if(this.isCreateStreamTransaction())return this.decodeCreateStreamTransaction();if(this.isClaimByProxyTransaction())return this.decodeClaimByProxyTransaction();if(this.isSetAutoClaimTransaction())return this.decodeSetAutoClaimTransaction();if(this.isCancelStreamTransaction())return this.decodeCancelStreamTransaction();if(this.isClaimStreamTransaction())return this.decodeClaimTransaction();throw new Error("Unknown stream transaction type")}get transactions(){return this.txb.blockData.transactions}isCreateStreamTransaction(){return this.transactions.findIndex(t=>t.kind==="MoveCall"&&ae(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&ae(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&ae(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&ae(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&ae(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new Eo(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:e,enabled:t}}decodeClaimTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"Claim",streamId:e}}decodeClaimByProxyTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"ClaimByProxy",streamId:e}}decodeCancelStreamTransaction(){let e=this.helper.decodeSharedObjectId(0);return{type:"Cancel",streamId:e}}get helper(){let e=this.transactions[0];return new Ae(e,this.txb)}};import{TransactionType as np}from"@msafe/sui3-utils";var Je=class extends Ut{constructor(t){super(t);this.data=t}txType=np.Stream;txSubType="SetAutoClaim";async build(t){let{network:o,account:n}=t;return(await this.getClient(o,n).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}};var Wo=class{application="mpay";supportSDK="@mysten/sui.js";async deserialize(e){let{network:t,transactionBlock:o}=e,n=Ie.new(t==="sui:mainnet"?"prod":"dev"),c=new No(n,o).decode(),l;switch(c.type){case"CreateStream":l=new Qe(c.info);break;case"SetAutoClaim":l=new Je({streamId:c.streamId,enabled:c.enabled});break;case"Claim":l=new Ge({streamId:c.streamId});break;case"ClaimByProxy":l=new Xe({streamId:c.streamId});break;case"Cancel":l=new He({streamId:c.streamId});break;default:throw new Error(`Unknown transaction type: ${c}`)}return{txType:l.txType,txSubType:l.txSubType,intentionData:l.data}}async build(e){let{intentionData:t}=e,o;switch(e.txSubType){case"CreateStream":o=new Qe(t);break;case"Claim":o=new Ge(t);break;case"ClaimByProxy":o=new Xe(t);break;case"SetAutoClaim":o=new Je(t);break;case"Cancel":o=new He(t);break;default:throw new Error("not implemented")}return o.build({...e})}};import{TransactionDefaultApplication as ip,TransactionSubTypes as Bc}from"@msafe/sui3-utils";import{buildCoinTransferTxb as op}from"@msafe/sui3-utils";var _o=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n}=t;return op(o,this.data,n.address)}static fromData(t){return new a(t)}};import{buildObjectTransferTxb as ap}from"@msafe/sui3-utils";var Lo=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n}=t;return ap(o,this.data,n.address)}static fromData(t){return new a(t)}};var jo=class{application="msafe-core";supportSDK="@mysten/sui.js";constructor(){this.application=ip}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(e){let{suiClient:t,account:o}=e,n;switch(e.txSubType){case Bc.assets.coin.send:n=_o.fromData(e.intentionData);break;case Bc.assets.object.send:n=Lo.fromData(e.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:t,account:o})}};import{TransactionType as Tp}from"@msafe/sui3-utils";var Ec=!1,Ye={ProtocolPackage:"0x81c408448d0d57b3e371ea94de1d40bf852784d3e225de1e74acab3e8395c18f",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",gasBudget:5e7,PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},wusdc:{name:"wUSDC",assetId:1,coinType:"wusdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"},wbtc:{name:"WBTC",coinType:"wbtc",assetId:8,poolId:"0xd162cbe40f8829ce71c9b3d3bf3a83859689a79fa220b23d70dc0300b777ae6e",type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",reserveObjectId:"0x8b4d81f004e4e9faf4540951a896b6d96e42598a270e6375f598b99742db767e",borrowBalanceParentId:"0x55e1f3c9e6e5cf9fff563bdd61db07a3826458c56ef72c455e049ab3b1b0e99c",supplyBalanceParentId:"0x821e505a0091b089edba94deaa14c2f2230d026bbaa7b85680554441aad447e0"},ausd:{name:"AUSD",coinType:"ausd",assetId:9,poolId:"0xc9208c1e75f990b2c814fa3a45f1bf0e85bb78404cfdb2ae6bb97de58bb30932",type:"0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD",reserveObjectId:"0x918889c6a9d9b93108531d4d59a4ebb9cc4d41689798ffc1d4aed6e1ae816ec0",borrowBalanceParentId:"0x551300b9441c9a3a16ca1d7972c1dbb4715e15004ccd5f001b2c2eee22fd92c1",supplyBalanceParentId:"0xe151af690355de8be1c0281fbd0d483c099ea51920a57c4bf8c9666fd36808fd"},nusdc:{name:"USDC",assetId:10,coinType:"nusdc",poolId:"0xa3582097b4c57630046c0c49a88bfc6b202a3ec0a9db5597c31765f7563755a8",type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",reserveObjectId:"0x4c8a2c72a22ae8da803a8519798d312c86e74a9e0d6ec0eec2bfcf7e4b3fef5e",borrowBalanceParentId:"0xb0b0c7470e96cabbb4f1e8d06bef2fbea65f4dbac52afae8635d9286b1ea9a09",supplyBalanceParentId:"0x08b5ce8574ac3bc9327e66ad5decd34d07ee798f724ad01058e8855ac9acb605"},eth:{name:"ETH",assetId:11,coinType:"eth",poolId:"0x78ba01c21d8301be15690d3c30dc9f111871e38cfb0b2dd4b70cc6052fba41bb",type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",reserveObjectId:"0x376faea6dfbffab9ea808474cb751d91222b6d664f38c0f1d23de442a8edb1ce",borrowBalanceParentId:"0xf0c6ce5cfaee96073876a5fab7426043f3a798b79502c4caeb6d9772cd35af1f",supplyBalanceParentId:"0xc0a0cb43620eb8a84d5a4a50a85650e7fa7ba81e660f9cc2863404fd84591d4b"},usdy:{name:"USDY",assetId:12,coinType:"usdy",poolId:"0x4b6253a9f8cf7f5d31e6d04aed4046b9e325a1681d34e0eff11a8441525d4563",type:"0x960b531667636f39e85867775f52f6b1f220a058c4de786905bdf761e06a56bb::usdy::USDY",reserveObjectId:"",borrowBalanceParentId:"",supplyBalanceParentId:""}},borrowFee:.003,borrowFeeAddress:"0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2"};async function Ar(){if(!Ec)try{let a=await fetch("https://open-api.naviprotocol.io/api/msafe").then(i=>i.json()),{packageId:e,borrowFee:t,borrowFeeAddress:o,pool:n}=a;e&&(Ye.ProtocolPackage=e),t&&(Ye.borrowFee=t),o&&(Ye.borrowFeeAddress=o),n&&(Ye.pool=n),Ec=!0}catch(a){console.error(a.message)}}var $t=Ye;import{TransactionType as fe}from"@msafe/sui3-utils";import{bcs as Nc}from"@mysten/sui.js/bcs";import{normalizeStructTag as sp,normalizeSuiAddress as Ze}from"@mysten/sui.js/utils";var Uo=class{constructor(e){this.txb=e}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryBorrowWithFeeTransaction())return this.decodeEntryBorrow();if(this.isEntryMultiDepositTransaction())return this.decodeEntryMultiDeposit();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();if(this.isEntryClaimAndDepositTransaction())return this.decodeEntryClaimAndDeposit();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}isClaimRewardTransaction(){return!!this.transactions.find(t=>!!(t.kind==="MoveCall"&&t.target.includes("claim_reward")))}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::entry_borrow`)}isEntryBorrowWithFeeTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::borrow`)}isEntryMultiDepositTransaction(){let e=`${$t.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.transactions.filter(n=>n.kind==="MoveCall"&&n.target===e);return this.transactions.find(n=>n.kind==="MoveCall"&&n.target.includes("claim_reward"))?!1:t.length>1}isEntryClaimAndDepositTransaction(){let e=`${$t.ProtocolPackage}::incentive_v3::entry_deposit`,t=this.transactions.filter(n=>n.kind==="MoveCall"&&n.target===e);return!!(this.transactions.find(n=>n.kind==="MoveCall"&&n.target.includes("claim_reward"))&&t.length>0)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${$t.ProtocolPackage}::incentive_v3::withdraw`)}findPoolByAssetId(e){let t=Object.values($t.pool).find(o=>o.assetId===e);if(!t)throw new Error("Pool not found");return t}decodeEntryClaimAndDeposit(){return{txType:fe.Other,type:"EntryClaimAndDeposit",intentionData:{type:"entry_claim_and_deposit"}}}decodeClaimReward(){return console.log("decode claims"),{txType:fe.Other,type:"ClaimReward",intentionData:{type:"claim_reward"}}}decodeEntryBorrow(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:fe.Other,type:"EntryBorrow",intentionData:{amount:t,assetId:e}}}decodeEntryMultiDeposit(){let e=[],t=`${$t.ProtocolPackage}::incentive_v3::entry_deposit`;return this.transactions.forEach(o=>{if(o.kind==="MoveCall"&&o.target===t){let n=new qo(o,this.txb),i=n.decodeInputU8(3),c=n.decodeInputU64(5);e.push({assetId:i,amount:c})}}),{txType:fe.Other,type:"EntryMultiDeposit",intentionData:{list:e}}}decodeEntryDeposit(){let e=this.helper.decodeInputU8(3),t=this.helper.decodeInputU64(5);return{txType:fe.Other,type:"EntryDeposit",intentionData:{amount:t,assetId:e}}}decodeEntryRepay(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(6);return{txType:fe.Other,type:"EntryRepay",intentionData:{amount:t,assetId:e}}}decodeEntryWithdraw(){let e=this.helper.decodeInputU8(4),t=this.helper.decodeInputU64(5);return{txType:fe.Other,type:"EntryWithdraw",intentionData:{amount:t,assetId:e}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target.startsWith($t.ProtocolPackage));return new qo(e,this.txb)}},qo=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return Ze(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let o=this.getInputParam(e);return a.getPureInputValue(o,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let o=e.value.Pure;return Nc.de(t,new Uint8Array(o))}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 Ze(e.value.Object.ImmOrOwned.objectId)}return Ze(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return Ze(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return Ze(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let o=e.value.Pure;return Nc.de(t,new Uint8Array(o))}typeArg(e){return sp(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};import{depositCoin as cp,withdrawCoin as lp,repayDebt as up,borrowCoin as mp,claimAllRewardsPTB as pp,claimAllRewardsResupplyPTB as dp}from"navi-sdk";async function Oe(a,e,t,o){return await cp(a,e,t,o),a}async function Wc(a,e,t,o){let[n]=await lp(a,e,t);return a.transferObjects([n],a.pure(o)),a}async function _c(a,e,t,o){let[n]=await mp(a,e,t);return a.transferObjects([n],a.pure.address(o)),a}async function Or(a,e,t,o){return await up(a,e,t,o),a}async function Lc(a,e){return await pp(a,e)}async function jc(a,e){return await dp(a,e)}var Fo=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{type:o}=this.data;return console.log("claim reward",o),await Lc(t.suiClient,t.account.address)}static fromData(t){return new a(t)}};var Ko=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{type:o}=this.data;return console.log("claim reward and supply",o),await jc(t.suiClient,t.account.address)}static fromData(t){return new a(t)}};import{TransactionBlock as hp}from"@mysten/sui.js/transactions";import{pool as fp}from"navi-sdk";function zt(a){return Object.values(fp).find(e=>String(e.assetId)===String(a))}var Vo=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{assetId:o,amount:n}=this.data,i=new hp;console.log("build",this.data);let c=zt(o);return await _c(i,c,n,t.account.address)}static fromData(t){return new a(t)}};import{TransactionBlock as gp}from"@mysten/sui.js/transactions";async function Me(a,e,t){let o=await a.getCoins({owner:e,coinType:t});return console.log("getTokenObjs",e,o),o}var $o=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n}=t,{assetId:i,amount:c}=this.data,l=new gp;console.log("build",this.data);let d=zt(i);if(i===0){let[C]=l.splitCoins(l.gas,[c]);return await Oe(l,d,C,c)}let S=await Me(o,n.address,d.type);if(!S.data[0])throw new Error(`Insufficient balance for ${d.name} Token`);let w=S.data[0].coinObjectId;if(S.data.length>=2){let C=1;for(;C<S.data.length;)l.mergeCoins(w,[S.data[C].coinObjectId]),C++}return await Oe(l,d,l.object(w),c)}static fromData(t){return new a(t)}};import{TransactionBlock as yp}from"@mysten/sui.js/transactions";var Ho=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n}=t,{assetId:i,amount:c}=this.data,l=new yp;console.log("build",this.data);let d=zt(i);if(i===0){let[I]=l.splitCoins(l.gas,[c]);return Or(l,d,I,c)}let S=await Me(o,n.address,d.type);if(!S.data[0])throw new Error(`Insufficient balance for ${d.name} Token`);let w=S.data[0].coinObjectId;if(S.data.length>=2){let I=1;for(;I<S.data.length;)l.mergeCoins(w,[S.data[I].coinObjectId]),I++}return Or(l,d,l.object(w),c)}static fromData(t){return new a(t)}};import{TransactionBlock as bp}from"@mysten/sui.js/transactions";var Xo=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{assetId:o,amount:n}=this.data,i=new bp;console.log("build",this.data);let c=zt(o);return await Wc(i,c,n,t.account.address)}static fromData(t){return new a(t)}};import{TransactionBlock as Sp}from"@mysten/sui.js/transactions";var Go=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n}=t,{list:i}=this.data,c=new Sp;console.log("build",this.data);for(let l=0;l<i.length;l++){let{assetId:d,amount:S}=i[l],w=zt(d);if(d===0){let[x]=c.splitCoins(c.gas,[S]);await Oe(c,w,x,S);continue}let I=await Me(o,n.address,w.type);if(!I.data[0])throw new Error(`Insufficient balance for ${w.name} Token`);let C=I.data[0].coinObjectId;if(I.data.length>=2){let x=1;for(;x<I.data.length;)c.mergeCoins(C,[I.data[x].coinObjectId]),x++}await Oe(c,w,c.object(C),S)}return c}static fromData(t){return new a(t)}};var Qo=class{application="navi";supportSDK="@mysten/sui.js";async deserialize(e){await Ar();let{transactionBlock:t}=e,n=new Uo(t).decode();return{txType:Tp.Other,txSubType:n.type,intentionData:n.intentionData}}async build(e){let{suiClient:t,account:o}=e,n;switch(await Ar(),e.txSubType){case"EntryDeposit":n=$o.fromData(e.intentionData);break;case"EntryBorrow":n=Vo.fromData(e.intentionData);break;case"EntryRepay":n=Ho.fromData(e.intentionData);break;case"EntryWithdraw":n=Xo.fromData(e.intentionData);break;case"EntryMultiDeposit":n=Go.fromData(e.intentionData);break;case"ClaimReward":n=Fo.fromData(e.intentionData);break;case"EntryClaimAndDeposit":n=Ko.fromData(e.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:t,account:o})}};import{TransactionSubTypes as wp,TransactionType as Uc}from"@msafe/sui3-utils";import{fromHex as Ip}from"@mysten/bcs";import{Transaction as Cp}from"@mysten/sui/transactions";import kp from"sort-keys-recursive";var qc="msafe-plain-tx",Fc=wp.others.plain,Mr=class a{constructor(e){this.data=e}application=qc;txType=Uc.Other;txSubType=Fc;serialize(){return JSON.stringify(kp(this.data))}async build(e){return Cp.from(Ip(this.data.content))}static fromData(e){return new a(e)}},zo=class{application;supportSDK="@mysten/sui";constructor(){this.application=qc}async deserialize(e){let{content:t}=e.appContext;return{txType:Uc.Other,txSubType:Fc,intentionData:{content:t}}}async build(e){let{suiClient:t,network:o,account:n}=e;return Mr.fromData(e.intentionData).build({suiClient:t,network:o,account:n})}};import{SuiClient as Kc}from"@mysten/sui/client";import{Transaction as Pp}from"@mysten/sui/transactions";import{SuiClient as Br}from"@mysten/sui.js/client";import{TransactionBlock as Rp}from"@mysten/sui.js/transactions";import{RequestManager as Ap,HTTPTransport as Op,Client as Mp}from"@open-rpc/client-js";var xp={"-32700":"ParseError","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError"},Pr=class extends Error{},Jo=class extends Pr{code;type;constructor(e,t){super(e),this.code=t,this.type=xp[t]??"ServerError"}};function vp(a){let e=new URL(a);return e.protocol=e.protocol.replace("http","ws"),e.toString()}var Dp={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5},Yo=class{endpoint;options;#n=0;#a=0;#t=null;#e=null;#i=new Set;#o=new Map;constructor(e,t={}){this.endpoint=e,this.options={...Dp,...t},this.endpoint&&this.endpoint.startsWith("http")&&(this.endpoint=vp(this.endpoint))}async makeRequest(e,t){let o=await this.#r();return new Promise((n,i)=>{this.#n+=1,this.#o.set(this.#n,{resolve:n,reject:i,timeout:setTimeout(()=>{this.#o.delete(this.#n),i(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),o.send(JSON.stringify({jsonrpc:"2.0",id:this.#n,method:e,params:t}))}).then(({error:n,result:i})=>{if(n)throw new Jo(n.message,n.code);return i})}#r(){return this.#e?this.#e:(this.#e=new Promise(e=>{this.#t?.close(),this.#t=new this.options.WebSocketConstructor(this.endpoint),this.#t.addEventListener("open",()=>{this.#a=0,e(this.#t)}),this.#t.addEventListener("close",()=>{this.#a++,this.#a<=this.options.maxReconnects&&setTimeout(()=>{this.#s()},this.options.reconnectTimeout)}),this.#t.addEventListener("message",({data:t})=>{let o;try{o=JSON.parse(t)}catch(n){console.error(new Error(`Failed to parse RPC message: ${t}`,{cause:n}));return}if("id"in o&&o.id!=null&&this.#o.has(o.id)){let{resolve:n,timeout:i}=this.#o.get(o.id);clearTimeout(i),n(o)}else if("params"in o){let{params:n}=o;this.#i.forEach(i=>{i.subscriptionId===n.subscription&&n.subscription===i.subscriptionId&&i.onMessage(n.result)})}})}),this.#e)}async#s(){return this.#t?.close(),this.#e=null,Promise.allSettled([...this.#i].map(e=>e.subscribe(this)))}async subscribe(e){let t=new Rr(e);return this.#i.add(t),await t.subscribe(this),()=>t.unsubscribe(this)}},Rr=class{subscriptionId=null;input;subscribed=!1;constructor(e){this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){let{subscriptionId:t}=this;return this.subscribed=!1,t==null?!1:(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[t]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;let t=await e.makeRequest(this.input.method,this.input.params);this.subscribed&&(this.subscriptionId=t)}};var re=class{rpcClient;websocketClient;constructor({url:e,websocket:{url:t,...o}={},rpc:n}){let i=new Op(n?.url??e,{headers:{"Content-Type":"application/json",...n?.headers}});this.rpcClient=new Mp(new Ap([i])),this.websocketClient=new Yo(t??e,o)}async request(e){return await this.rpcClient.request(e)}async subscribe(e){let t=await this.websocketClient.subscribe(e);return async()=>!!await t()}};var Zo=class a{apps;constructor(){this.apps=new Map}static fromHelpers(e){let t=new a;for(let o=0;o<e.length;o++){let n=e[o];switch(n.supportSDK){case"@mysten/sui.js":t.addLegacyHelper(n);break;case"@mysten/sui":t.addHelper(n);break;default:throw new Error(`${n.application}: ${n.supportSDK} SDK not supported`)}}return t}addLegacyHelper(e){this.apps.set(e.application,new Nr(e))}addHelper(e){this.apps.set(e.application,new Er(e))}getAppHelper(e){let t=this.apps.get(e);if(!t)throw new Error(`${e} not registered`);return t}},Er=class{constructor(e){this.helper=e}async deserialize(e){let t=new Kc({transport:new re({url:e.clientUrl,rpc:{url:e.clientUrl}})}),o=new Br({transport:new re({url:e.clientUrl,rpc:{url:e.clientUrl}})}),n=await e.transactionBlock.build({client:o}),i=Pp.from(n);return this.helper.deserialize({...e,suiClient:t,transaction:i})}async build(e){let t=new Kc({transport:new re({url:e.clientUrl,rpc:{url:e.clientUrl}})}),o=await t.getBalance({owner:e.account.address});if(Number(o.totalBalance)<1e8)throw new Error("Insufficient gas fee");let n=await this.helper.build({...e,suiClient:t});n.setSender(e.account.address);let i=await n.build({client:t});return Rp.from(i)}},Nr=class{constructor(e){this.helper=e}async deserialize(e){let t=new Br({transport:new re({url:e.clientUrl,rpc:{url:e.clientUrl}})});return this.helper.deserialize({...e,transactionBlock:e.transactionBlock,suiClient:t})}async build(e){let t=new Br({transport:new re({url:e.clientUrl,rpc:{url:e.clientUrl}})}),o=await t.getBalance({owner:e.account.address});if(Number(o.totalBalance)<1e8)throw new Error("Insufficient gas fee");return this.helper.build({...e,suiClient:t})}};import{TransactionType as Fp}from"@msafe/sui3-utils";import{getFullnodeUrl as Kp}from"@mysten/sui/client";import{Scallop as Vp}from"@scallop-io/sui-scallop-sdk";import{TransactionType as Mt}from"@msafe/sui3-utils";import{OLD_BORROW_INCENTIVE_PROTOCOL_ID as Gc}from"@scallop-io/sui-scallop-sdk";import{parseStructTag as Bp}from"@mysten/sui/utils";var se=class{constructor(e,t){this.transaction=e;this.scallopClient=t;this.scallopClient=t,this.inputs=e.getData().inputs,this.commands=e.getData().commands,this.movecallsAsSet=new Set(this.commands.filter(this.isMoveCall).map(o=>`${o.MoveCall.package}::${o.MoveCall.module}::${o.MoveCall.function}`))}inputs;commands;movecallsAsSet;get address(){return this.scallopClient.address}get utils(){return this.scallopClient.utils}get coreId(){return{protocolPkg:this.address.get("core.packages.protocol.id"),market:this.address.get("core.market"),version:this.address.get("core.version"),coinDecimalsRegistry:this.address.get("core.coinDecimalsRegistry"),xOracle:this.address.get("core.oracles.xOracle"),spoolPkg:this.address.get("spool.id"),borrowIncentivePkg:this.address.get("borrowIncentive.id"),veScaPkgId:this.address.get("vesca.id"),veScaObjId:this.address.get("vesca.object"),scoin:this.address.get("scoin.id"),referral:this.address.get("referral.id")}}matchMoveCallCommand(e,t){let{address:o,module:n,name:i}=Bp(t);return e?e.package===o&&e.module===n&&e.function===i:!1}isMoveCall(e){return e.$kind==="MoveCall"&&!!e.MoveCall}filterMoveCallCommands(e,t){return this.isMoveCall(e)&&this.matchMoveCallCommand(e.MoveCall,t)}getMoveCallCommands(e){let t=new Set(e),o=e.reduce((i,c,l)=>(i[c]=l,i),{}),n=[];return this.commands.forEach(i=>{this.isMoveCall(i)&&i.MoveCall&&t.has(i.MoveCall.package)&&(n[o[i.MoveCall.package]]=i.MoveCall)}),n}hasMoveCallCommand(e){return this.movecallsAsSet.has(e)}};import{bcs as Wr}from"@mysten/sui/bcs";import{normalizeStructTag as Ep,normalizeSuiAddress as tn}from"@mysten/sui/utils";var _r=class a{constructor(e,t,o=0){this.moveCall=e;this.transaction=t;let n=[];e?.MoveCall&&t.getData().commands.filter((i,c)=>{if(i.$kind==="MoveCall"){let l=`${i.MoveCall.package}::${i.MoveCall.module}::${i.MoveCall.function}`,d=`${e.MoveCall.package}::${e.MoveCall.module}::${e.MoveCall.function}`;return l===d?(n.push(c),!0):!1}return!1}),this.cmdIdx=n[o]}cmdIdx;get txBlockTransactions(){return this.transaction.blockData.transactions[this.cmdIdx]}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"U64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"U8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"Address");return tn(t)}decodeInputString(e){return this.decodePureArg(e,"String")}decodeInputBool(e){return this.decodePureArg(e,"Bool")}decodePureArg(e,t){let o=this.getInputParam(e);return a.getPureInputValue(o,t)}getInputParam(e){let t=this.txBlockTransactions.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return t}getNestedInputParam(e){let t=this.txBlockTransactions.arguments[e];if(t.kind!=="NestedResult")throw new Error("not input type");return this.transaction.blockData.transactions[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let o=e.value.Pure,n=Wr[t];return Wr[t].parse(new Uint8Array(o))}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 tn(e.value.Object.ImmOrOwned.objectId)}return tn(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return tn(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return tn(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 Wr.U64.parse(new Uint8Array(t))}typeArg(e){return Ep(this.txBlockTransactions.typeArguments[e])}txArg(e){return this.transaction.blockData.inputs[e]}},W=_r;var Lr=class{constructor(e,t){this.splitCoin=e;this.txb=t}getAmountInput(){return this.splitCoin.amounts.map(e=>{if(e.kind==="Input")return Number(W.getPureInputValue(e,"U64"))}).filter(e=>e!==void 0)}},Bt=Lr;import{normalizeStructTag as Vc,SUI_CLOCK_OBJECT_ID as $c,SUI_TYPE_ARG as Np}from"@mysten/sui/utils";var Hc=async(a,e)=>{let t=await a.scallopSuiKit.client.getObject({id:e,options:{showContent:!0}});if(t?.data?.content?.dataType!=="moveObject")return!1;let n=t.data.content.fields.lock_key?.fields.name;if(!n)return!1;let i=a.address.get("borrowIncentive.object");return n===`${i.slice(2)}::incentive_account::IncentiveProgramLockKey`},Pe={id:"0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410",incentivePools:"0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec",incentiveAccounts:"0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3"},qt={unstakeObligation:(a,e,t)=>a.moveCall(`${Pe.id}::user::unstake`,[Pe.incentivePools,Pe.incentiveAccounts,a.object(e),a.object(t),$c],[Vc(Np)]),redeem_rewards:(a,e,t,o)=>a.moveCall(`${Pe.id}::user::redeem_rewards`,[Pe.incentivePools,Pe.incentiveAccounts,a.object(e),a.object(t),$c],[Vc(o)])};var Xc=(a,e)=>{let t=[];for(let o=0;o<a.length;o+=e)t.push(a.slice(o,o+e));return t};var ta=class extends se{decode(){if(this.isSupplyWithStakeSpoolTransaction())return this.decodeSupplyWithStakeSpool();if(this.isUnstakeAndWithdrawTransaction())return this.decodeUnstakeAndWithdraw();if(this.isStakeSpoolTransaction())return this.decodeStakeSpool();if(this.isDepositCollateralTransaction())return this.decodeDepositCollateral();if(this.isWithdrawCollateralTransaction())return this.decodeWithdrawCollateral();if(this.isWithdrawLendingScoinTransaction())return this.decodeWithdrawLendingScoin();if(this.isWithdrawLendingTransaction())return this.decodeWithdrawLending();if(this.isSupplyLendingTransaction())return this.decodeSupplyLending();if(this.isBorrowWithReferralTransaction())return this.decodeBorrowWithReferral();if(this.isBorrowWithBoostTransaction())return this.decodeBorrowWithBoost();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayWithBoostTransaction())return this.decodeRepayWithBoost();if(this.isRepayTransaction())return this.decodeRepay();if(this.isUnstakeSpoolTransaction())return this.decodeUnstakeSpool();if(this.isMigrateAndClaim())return this.decodeMigrateAndClaim();if(this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isOpenObligationTransaction())return this.decodeOpenObligation();if(this.isMigrateScoinTransaction())return this.decodeMigrateScoin()}isMigrateScoinTransaction(){return this.hasMoveCallCommand(`${this.coreId.scoin}::s_coin_converter::mint_s_coin`)}isSupplyLendingTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::mint::mint`)}isSupplyWithStakeSpoolTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::mint::mint`),t=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::stake`);return e&&t}isUnstakeAndWithdrawTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::unstake`),t=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`);return e&&t}isStakeSpoolTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::stake`)}isWithdrawLendingTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`)}isWithdrawLendingScoinTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::redeem::redeem`),t=this.hasMoveCallCommand(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`);return e&&t}isDepositCollateralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`)}isWithdrawCollateralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`)}isBorrowTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow`)}isBorrowWithBoostTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`);return e&&t}isBorrowWithReferralTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`)}isRepayTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::repay::repay`)}isRepayWithBoostTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.protocolPkg}::repay::repay`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`);return e&&t}isUnstakeSpoolTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::unstake`)}isCreateStakeAccountTransaction(){return this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::new_spool_account`)}isClaimRewardTransaction(){let e=this.hasMoveCallCommand(`${this.coreId.spoolPkg}::user::redeem_rewards`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`);return e||t}isOpenObligationTransaction(){return this.hasMoveCallCommand(`${this.coreId.protocolPkg}::open_obligation::open_obligation`)}isMigrateAndClaim(){let e=this.hasMoveCallCommand(`${Gc}::user::redeem_rewards`),t=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`),o=this.hasMoveCallCommand(`${this.coreId.borrowIncentivePkg}::user::stake`);return e&&(t||o)}get helperClaimLendingReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperClaimBorrowV2Reward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperStakeObligationWithVeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`));return new W(e,this.transaction)}get helperClaimBorrowReward(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${Gc}::user::redeem_rewards`)).map(t=>new W(t,this.transaction))}get helperMint(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::mint::mint`));return new W(e,this.transaction)}get helperUnstakes(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`)).map(t=>new W(t,this.transaction))}get helperRedeems(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`)).map(t=>new W(t,this.transaction))}get helperRedeem(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::redeem::redeem`));return new W(e,this.transaction)}get helperBurnScoin(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.scoin}::s_coin_converter::burn_s_coin`));return new W(e,this.transaction)}get helperStake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::stake`));return new W(e,this.transaction)}get helperUnstake(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.spoolPkg}::user::unstake`));return new W(e,this.transaction)}get helperDepositCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`));return new W(e,this.transaction)}get helperWithdrawCollateral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`));return new W(e,this.transaction)}get helperBorrow(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow`));return new W(e,this.transaction)}get helperBorrowWithReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::borrow::borrow_with_referral`));return new W(e,this.transaction)}get helperRepay(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.protocolPkg}::repay::repay`));return new W(e,this.transaction)}decodeMigrateScoin(){return{txType:Mt.Other,type:"MigrateScoin",intentionData:{}}}decodeMigrateAndClaim(){let e;this.helperStakeObligationWithVeSca.moveCall&&(e=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let t=this.helperClaimBorrowReward[0].decodeOwnedObjectId(2),o=this.helperClaimBorrowReward[0].decodeSharedObjectId(3),n=this.utils.parseCoinNameFromType(this.helperClaimBorrowReward[0].typeArg(0));return{txType:Mt.Other,type:"MigrateAndClaim",intentionData:{obligationKey:t,obligationId:o,rewardCoinName:n,veScaKey:e}}}decodeOpenObligation(){return{txType:Mt.Other,type:"OpenObligation",intentionData:{}}}decodeSupplyLending(){let e=this.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),t=this.helperMint.getNestedInputParam(2),o=new Bt(t,this.transaction).getAmountInput().reduce((n,i)=>n+i,0);return{txType:Mt.Other,type:"SupplyLending",intentionData:{amount:o,coinName:e}}}decodeWithdrawLending(){let e=this.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0)),t=this.helperRedeem.getNestedInputParam(2),o=new Bt(t,this.transaction).getAmountInput().reduce((n,i)=>n+i,0);return{txType:Mt.Other,type:"WithdrawLending",intentionData:{amount:o,coinName:e}}}decodeWithdrawLendingScoin(){let e=this.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0));console.log({coinName:e});let t=this.helperBurnScoin.getNestedInputParam(1),o=new Bt(t,this.transaction).getAmountInput().reduce((n,i)=>n+i,0);return{txType:Mt.Other,type:"WithdrawLending",intentionData:{amount:o,coinName:e}}}decodeDepositCollateral(){let e=this.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0)),t=this.helperDepositCollateral.getNestedInputParam(3),o=new Bt(t,this.transaction).getAmountInput().reduce((i,c)=>i+c,0),n=this.helperDepositCollateral.decodeSharedObjectId(1);return{txType:Mt.Other,type:"DepositCollateral",intentionData:{amount:o,obligationId:n,collateralCoinName:e}}}decodeWithdrawCollateral(){let e=this.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0)),t=this.helperWithdrawCollateral.decodeInputU64(5),o=this.helperWithdrawCollateral.decodeSharedObjectId(1),n=this.helperWithdrawCollateral.decodeOwnedObjectId(2);return{txType:Mt.Other,type:"WithdrawCollateral",intentionData:{amount:t,collateralCoinName:e,obligationKey:n,obligationId:o}}}decodeBorrow(){let e=this.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),t=this.helperBorrow.decodeInputU64(5),o=this.helperBorrow.decodeSharedObjectId(1),n=this.helperBorrow.decodeOwnedObjectId(2);return{txType:Mt.Other,type:"Borrow",intentionData:{amount:t,coinName:e,obligationKey:n,obligationId:o}}}decodeBorrowWithBoost(){let e=this.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0)),t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),o=this.helperBorrow.decodeInputU64(5),n=this.helperBorrow.decodeSharedObjectId(1),i=this.helperBorrow.decodeOwnedObjectId(2);return{txType:Mt.Other,type:"BorrowWithBoost",intentionData:{amount:o,coinName:e,obligationKey:i,obligationId:n,veScaKey:t}}}decodeBorrowWithReferral(){let e=this.utils.parseCoinNameFromType(this.helperBorrowWithReferral.typeArg(0)),t;this.helperStakeObligationWithVeSca.moveCall&&(t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9));let o=this.helperBorrowWithReferral.decodeInputU64(6),n=this.helperBorrowWithReferral.decodeSharedObjectId(1),i=this.helperBorrowWithReferral.decodeOwnedObjectId(2);return{txType:Mt.Other,type:"BorrowWithReferral",intentionData:{amount:o,coinName:e,obligationKey:i,obligationId:n,veScaKey:t}}}decodeRepay(){let e=this.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),t=this.helperRepay.getNestedInputParam(3),o=new Bt(t,this.transaction).getAmountInput().reduce((i,c)=>i+c,0),n=this.helperRepay.decodeSharedObjectId(1);return{txType:Mt.Other,type:"Repay",intentionData:{amount:o,obligationId:n,coinName:e}}}decodeRepayWithBoost(){let e=this.utils.parseCoinNameFromType(this.helperRepay.typeArg(0)),t=this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9),o=this.helperRepay.getNestedInputParam(3),n=new Bt(o,this.transaction).getAmountInput().reduce((c,l)=>c+l,0),i=this.helperRepay.decodeSharedObjectId(1);return{txType:Mt.Other,type:"RepayWithBoost",intentionData:{amount:n,obligationId:i,coinName:e,veScaKey:t}}}decodeStakeSpool(){let e;this.isCreateStakeAccountTransaction()||(e=this.helperStake.decodeOwnedObjectId(1));let t=0;if(this.helperBurnScoin.moveCall){let i=this.helperBurnScoin.getNestedInputParam(1);t=new Bt(i,this.transaction).getAmountInput().reduce((c,l)=>c+l,0)}if(this.helperStake.moveCall&&t===0){let i=this.helperStake.getNestedInputParam(2);t=new Bt(i,this.transaction).getAmountInput().reduce((c,l)=>c+l,0)}let o=this.helperStake.typeArg(0),n=this.utils.parseCoinNameFromType(o);return{txType:Mt.Other,type:"StakeSpool",intentionData:{amount:t,marketCoinName:n,stakeAccountId:e}}}decodeUnstakeSpool(){let e=this.helperUnstake.decodeOwnedObjectId(1),t=this.helperUnstake.decodeInputU64(2),o=this.helperUnstake.typeArg(0),n=this.utils.parseCoinNameFromType(o);return{txType:Mt.Other,type:"UnstakeSpool",intentionData:{amount:t,marketCoinName:n,stakeAccountId:e}}}decodeSupplyWithStakeSpool(){let e=this.utils.parseCoinNameFromType(this.helperMint.typeArg(0)),t=this.helperMint.getNestedInputParam(2),o=new Bt(t,this.transaction).getAmountInput().reduce((i,c)=>i+c,0),n;return this.isCreateStakeAccountTransaction()||(n=this.helperStake.decodeOwnedObjectId(1)),{txType:Mt.Other,type:"SupplyAndStakeLending",intentionData:{amount:o,coinName:e,stakeAccountId:n}}}decodeUnstakeAndWithdraw(){let e=[];this.helperUnstakes.forEach(n=>{let i=n.decodeOwnedObjectId(1),c=n.decodeInputU64(2);e.push({id:i,coin:c})});let t=this.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0)),o=0;if(this.helperBurnScoin.moveCall){let n=this.helperBurnScoin.getNestedInputParam(1);o=new Bt(n,this.transaction).getAmountInput().reduce((i,c)=>i+c,0)}return{txType:Mt.Other,type:"WithdrawAndUnstakeLending",intentionData:{amount:o,coinName:t,stakeAccountId:e}}}decodeClaimReward(){let e=[],t=[],o=[];return this.helperClaimLendingReward.forEach(n=>{let i=n.decodeOwnedObjectId(2),c=n.typeArg(0),l=this.utils.parseCoinNameFromType(c);e.push({stakeMarketCoinName:l,stakeAccountId:i})}),this.helperClaimBorrowV2Reward.forEach(n=>{let i=n.decodeSharedObjectId(4),c=n.decodeOwnedObjectId(3),l=this.utils.parseCoinNameFromType(n.typeArg(0));t.push({obligationId:c,obligationKey:i,rewardCoinName:l})}),this.helperClaimBorrowReward.forEach(n=>{let i=n.decodeSharedObjectId(2),c=n.decodeOwnedObjectId(3),l=this.utils.parseCoinNameFromType(n.typeArg(0));o.push({obligationId:c,obligationKey:i,rewardCoinName:l})}),{txType:Mt.Other,type:"ClaimIncentiveReward",intentionData:{lendingIncentive:e,borrowIncentiveV2:t,borrowIncentive:o}}}};import{TransactionType as Ur}from"@msafe/sui3-utils";var ea=class extends se{decode(){if(this.isCreateReferralLink())return this.decodeCreateReferralLink();if(this.isClaimRevenueReferral())return this.decodeClaimRevenueReferral();if(this.isBindReferral())return this.decodeBindReferral()}isClaimRevenueReferral(){return this.hasMoveCallCommand(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)}isCreateReferralLink(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_placeholder_key`)}isBindReferral(){return this.hasMoveCallCommand(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`)}get helperClaimRevenueReferral(){return this.commands.filter(t=>this.filterMoveCallCommands(t,`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`)).map(t=>new W(t,this.transaction))}get helperBindReferral(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`));return new W(e,this.transaction)}decodeCreateReferralLink(){return{txType:Ur.Other,type:"CreateReferralLink",intentionData:{}}}decodeClaimRevenueReferral(){let e=this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2),t=this.helperClaimRevenueReferral.map(o=>o.typeArg(0));return{txType:Ur.Other,type:"ClaimRevenueReferral",intentionData:{veScaKey:e,coins:t}}}decodeBindReferral(){let e=this.helperBindReferral.decodePureArg(1,"Address");return{txType:Ur.Other,type:"BindReferral",intentionData:{veScaKey:e}}}};import{TransactionType as Zt}from"@msafe/sui3-utils";import{OLD_BORROW_INCENTIVE_PROTOCOL_ID as Wp}from"@scallop-io/sui-scallop-sdk";var na=class extends se{async decode(){if(this.isExtendPeriodAndStakeMoreSca())return this.decodePeriodAndStakeMoreSca();if(this.isStakeScaFirsTime()||this.isStakeMoreSca())return this.decodeStakeSca();if(this.isRenewExpiredVeSca())return this.decodeRenewExpiredVeSca();if(this.isExtendPeriod())return this.decodeExtendStakePeriod();if(this.isRedeemSca())return this.decodeRedeemSca();if(this.isMergeVeSca())return this.decodeMergeVesca();if(this.isSplitVeSca())return this.decodeSplitVesca();if(this.isVeScaObligationBindings())return this.decodeVeScaObligationBindings();if(await this.isTransferVeScaKey())return this.decodeTransferVeScaKey()}isStakeScaFirsTime(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`)}isExtendPeriodAndStakeMoreSca(){let e=this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`),t=this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);return!!e&&!!t}isRedeemSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::redeem`)}isStakeMoreSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`)}isExtendPeriod(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`)}isRenewExpiredVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`)}isMergeVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::merge`)}isSplitVeSca(){return this.hasMoveCallCommand(`${this.coreId.veScaPkgId}::ve_sca::split`)}isVeScaObligationBindings(){let e=this.commands.filter(l=>this.filterMoveCallCommands(l,`${this.coreId.borrowIncentivePkg}::user::unstake_v2`)),t=this.commands.filter(l=>this.filterMoveCallCommands(l,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`)),o=this.commands.filter(l=>this.filterMoveCallCommands(l,`${this.coreId.borrowIncentivePkg}::user::deactivate_boost_v2`)),n=e.length>0&&t.length>0&&e.length===t.length,i=o.length>0;return this.commands.length===e.length+t.length+o.length&&(n||i)}async isTransferVeScaKey(){let e=this.commands.filter(d=>d.$kind==="TransferObjects");if(e.length!==1)return!1;let{objects:t}=e[0].TransferObjects,o=t.filter(d=>d.$kind==="Input").map(({Input:d})=>d);if(o.length!==t.length)return!1;let n=new Set(o),i=this.inputs.filter((d,S)=>d.$kind==="Object"&&n.has(S)).map(d=>d.Object.ImmOrOwnedObject),c=`${this.coreId.veScaObjId}::ve_sca::VeScaKey`,l=Xc(i.map(({objectId:d})=>d),50);for(let d=0;d<l.length;d++){let S=l[d];if((await this.scallopClient.scallopSuiKit.queryGetObjects(S,{showType:!0})).some(I=>I.type!==c))return!1}return i.length>0}get helperStakeMoreSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`));return new W(e,this.transaction)}get helperStakeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`));return new W(e,this.transaction)}get helperExtendStakePeriod(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`));return new W(e,this.transaction)}get helperRedeemSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::redeem`));return new W(e,this.transaction)}get helperRenewExpired(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`));return new W(e,this.transaction)}get helperOldUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${Wp}::user::unstake`));return new W(e,this.transaction)}get helperUnstakeObligation(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::unstake_v2`));return new W(e,this.transaction)}get helperStakeObligationWithVeSca(){let e=this.commands.find(t=>this.filterMoveCallCommands(t,`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`));return new W(e,this.transaction)}getMergeSplitVeScaHelper(e){let t=this.commands.find(o=>this.filterMoveCallCommands(o,`${this.coreId.veScaPkgId}::ve_sca::${e}`));return new W(t,this.transaction)}getVeScaObligationBindingHelpers(){let e=`${this.coreId.borrowIncentivePkg}::user::unstake_v2`,t=`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca_v2`,o=`${this.coreId.borrowIncentivePkg}::user::deactivate_boost_v2`,n=[],i=0,c=0,l=0;return this.commands.forEach(d=>{this.filterMoveCallCommands(d,e)?(n.push({action:"unstake",helper:new W(d,this.transaction,i)}),i++):this.filterMoveCallCommands(d,t)?(n.push({action:"stake",helper:new W(d,this.transaction,c)}),c++):this.filterMoveCallCommands(d,o)&&(n.push({action:"deactivate",helper:new W(d,this.transaction,l)}),l++)}),n}decodeRedeemSca(){let e=this.helperRedeemSca.decodeOwnedObjectId(1);return{txType:Zt.Other,type:"RedeemSca",intentionData:{veScaKey:e}}}decodeRenewExpiredVeSca(){let e=this.helperRenewExpired.getNestedInputParam(4),t=this.helperRenewExpired.decodeInputU64(5),o=new Bt(e,this.transaction).getAmountInput().reduce((v,R)=>v+R,0),n=this.helperRenewExpired.decodeOwnedObjectId(1),i=!!this.helperRedeemSca.moveCall,c=[],l=[],d=[];this.helperOldUnstakeObligation.moveCall&&(c=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(l=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(d=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let S=!1,w=!1,I,C,x=[{condition:c,isOld:!0},{condition:l,isOld:!1},{condition:d,isOld:!1}];for(let v=0;v<x.length;v++)x[v].condition.length>1&&([C,I]=x[v].condition,S=!0,w=x[v].isOld);return{txType:Zt.Other,type:"RenewExpStakePeriod",intentionData:{amount:o,unlockTime:t,obligationId:I,obligationKey:C,veScaKey:n,isHaveRedeem:i,isObligationLocked:S,isOldBorrowIncentive:w}}}decodeExtendStakePeriod(){let e=this.helperExtendStakePeriod.decodeInputU64(4),t=this.helperExtendStakePeriod.decodeOwnedObjectId(1),o=[],n=[],i=[];this.helperOldUnstakeObligation.moveCall&&(o=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(n=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeObligationWithVeSca.moveCall&&(i=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let c=!1,l=!1,d,S,w=[{condition:o,isOld:!0},{condition:n,isOld:!1},{condition:i,isOld:!1}];for(let I=0;I<w.length;I++)w[I].condition.length>1&&([S,d]=w[I].condition,c=!0,l=w[I].isOld);return{txType:Zt.Other,type:"ExtendStakePeriod",intentionData:{unlockTime:e,obligationId:d,obligationKey:S,veScaKey:t,isObligationLocked:c,isOldBorrowIncentive:l}}}decodePeriodAndStakeMoreSca(){let e=this.helperStakeMoreSca.getNestedInputParam(4),t=this.helperExtendStakePeriod.decodeInputU64(4),o=new Bt(e,this.transaction).getAmountInput().reduce((x,v)=>x+v,0),n=[],i=[],c,l=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(i=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(c=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(l=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let d=!1,S=!1,w,I,C=[{condition:n,isOld:!0},{condition:i,isOld:!1},{condition:l,isOld:!1}];for(let x=0;x<C.length;x++)C[x].condition.length>1&&([I,w]=C[x].condition,d=!0,S=C[x].isOld);return{txType:Zt.Other,type:"ExtendPeriodAndStakeMore",intentionData:{amount:o,veScaKey:c,unlockTime:t,obligationId:w,obligationKey:I,isOldBorrowIncentive:S,isObligationLocked:d}}}decodeStakeSca(){let e,t;this.helperStakeSca.moveCall&&this.helperStakeMoreSca.moveCall===void 0?(e=this.helperStakeSca.getNestedInputParam(3),t=this.helperStakeSca.decodeInputU64(4)):e=this.helperStakeMoreSca.getNestedInputParam(4);let o=new Bt(e,this.transaction).getAmountInput().reduce((x,v)=>x+v,0),n=[],i=[],c,l=[];this.helperOldUnstakeObligation.moveCall&&(n=[this.helperOldUnstakeObligation.decodeOwnedObjectId(2),this.helperOldUnstakeObligation.decodeSharedObjectId(3)]),this.helperUnstakeObligation.moveCall&&(i=[this.helperUnstakeObligation.decodeOwnedObjectId(3),this.helperUnstakeObligation.decodeSharedObjectId(4)]),this.helperStakeMoreSca.moveCall&&(c=this.helperStakeMoreSca.decodeOwnedObjectId(1)),this.helperStakeObligationWithVeSca.moveCall&&(l=[this.helperStakeObligationWithVeSca.decodeOwnedObjectId(3),this.helperStakeObligationWithVeSca.decodeSharedObjectId(4)]);let d=!1,S=!1,w,I,C=[{condition:n,isOld:!0},{condition:i,isOld:!1},{condition:l,isOld:!1}];for(let x=0;x<C.length;x++)C[x].condition.length>1&&([I,w]=C[x].condition,d=!0,S=C[x].isOld);return{txType:Zt.Other,type:"StakeSca",intentionData:{amount:o,unlockTime:t,obligationId:w,obligationKey:I,veScaKey:c,isObligationLocked:d,isOldBorrowIncentive:S}}}decodeMergeVesca(){let e=this.getMergeSplitVeScaHelper("merge"),t={targetVeScaKey:e.decodeOwnedObjectId(1),sourceVeScaKey:e.decodeOwnedObjectId(2)};return{txType:Zt.Other,type:"MergeVeSca",intentionData:t}}decodeSplitVesca(){let e=this.getMergeSplitVeScaHelper("split"),t={targetVeScaKey:e.decodeOwnedObjectId(1),splitAmount:e.decodeInputU64(4)};return{txType:Zt.Other,type:"SplitVeSca",intentionData:t}}decodeVeScaObligationBindings(){let e=this.getVeScaObligationBindingHelpers(),t=(n,i)=>{switch(n){case"stake":return{veScaKey:i.decodeOwnedObjectId(9),obligationId:i.decodeSharedObjectId(4),obligationKey:i.decodeOwnedObjectId(3)};case"unstake":return{obligationId:i.decodeSharedObjectId(4),obligationKey:i.decodeOwnedObjectId(3)};case"deactivate":return{veScaKey:i.decodeOwnedObjectId(4),obligationId:i.decodeSharedObjectId(3)};default:throw new Error(`Invalid action ${n}`)}},o=e.map(({action:n,helper:i})=>({action:n,args:t(n,i)}));return{txType:Zt.Other,type:"VeScaObligationBindings",intentionData:{bindingDatas:o}}}decodeTransferVeScaKey(){let e=this.commands.filter(c=>c.$kind==="TransferObjects"),{objects:t}=e[0].TransferObjects,o=t.filter(c=>c.$kind==="Input").map(({Input:c})=>c);if(o.length!==t.length)return!1;let n=new Set(o),i=this.inputs.filter((c,l)=>c.$kind==="Object"&&n.has(l)).map(c=>c.Object.ImmOrOwnedObject);return{xType:Zt.Other,type:"TransferVeScaKeys",intentionData:{veScaKeys:i}}}};import _p from"sort-keys-recursive";var A=class{constructor(e){this.data=e}get application(){return"msafe-core"}serialize(){return JSON.stringify(_p(this.data))}isObligationLocked=async(e,t)=>{let o=await e.getObject({id:typeof t=="string"?t:t.objectId,options:{showContent:!0}}),n=!1;return o&&o?.data.content?.dataType==="moveObject"&&"lock_key"in o.data.content.fields&&(n=!!o.data.content.fields.lock_key),n};async buildTxWithRefreshObligation(e,t,o){let n=e.builder.createTxBlock();n.setSender(t.walletAddress);let{obligationId:i,obligationKey:c}=t;return await this.isObligationLocked(e.scallopSuiKit.client,i)?(await n.unstakeObligationQuick(i,c),await o(e,n,t),await n.stakeObligationWithVeScaQuick(i,c,t.veScaKey)):await o(e,n,t),n}};var oa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async borrow({account:t,scallopClient:o}){let{coinName:n,amount:i,obligationId:c,obligationKey:l}=this.data,d=t.address;return(await this.buildTxWithRefreshObligation(o,{walletAddress:d,obligationId:c,obligationKey:l},async(w,I)=>{let C=await I.borrowQuick(+i,n,c,l);I.transferObjects([C],d)})).txBlock}async build(t){return this.borrow(t)}static fromData(t){return new a(t)}};var aa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async borrowWithBoost(t,o){let{obligationId:n,obligationKey:i,veScaKey:c,amount:l,coinName:d}=this.data;return(await this.buildTxWithRefreshObligation(t,{walletAddress:o,obligationId:n,obligationKey:i,veScaKey:c},async(w,I)=>{let C=await I.borrowQuick(+l,d,n,i);I.transferObjects([C],o)})).txBlock}async build(t){return this.borrowWithBoost(t.scallopClient,t.account.address)}static fromData(t){return new a(t)}};var ia=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async borrowWithReferral({account:t,scallopClient:o}){let n=t.address,{obligationId:i,obligationKey:c,veScaKey:l,coinName:d,amount:S}=this.data;return(await this.buildTxWithRefreshObligation(o,{walletAddress:n,obligationId:i,obligationKey:c,veScaKey:l},async(I,C)=>{let x=C.claimReferralTicket(d),v=await C.borrowWithReferralQuick(+S,d,x,i,c);C.burnReferralTicket(x,d),C.transferObjects([v],n)})).txBlock}async build(t){return this.borrowWithReferral(t)}static fromData(t){return new a(t)}};import{SUI_TYPE_ARG as Lp}from"@mysten/sui/utils";var ra=class a extends A{txType;txSubType;constructor(e={}){super(e)}async claimIncentiveRewards(e,t){let o=e.builder.createTxBlock();o.setSender(t);let n=await e.query.getAllStakeAccounts(t),i=await e.query.getLendings(void 0,t),c=await e.query.getObligations(t),l=Object.values(await e.query.getObligationAccounts(t)??[]),d=(()=>{let C=[...e.constants.whitelist.spool].map(x=>e.utils.parseCoinName(x));return Object.values(i??[]).filter(x=>!!x&&C.includes(x.coinName)).reduce((x,v)=>{let R=e.utils.parseMarketCoinName(v.coinName);return x[R]||(x[R]=0),x[R]+=v.availableClaimCoin,x},{})})(),S={};Object.entries(n).forEach(([C,x])=>{for(let v=0;v<x.length;v++){let R=x[v];if(!d[C])continue;let K=o.claim(R.id,C);S.sui?S.sui.push(K):S.sui=[K]}});let w=(()=>{let C={};return C.sui=Object.values(d).reduce((x,v)=>x+v,0),l.forEach(x=>{Object.values(x.borrowIncentives).forEach(v=>{v&&v.rewards.forEach(R=>{C[R.coinName]||(C[R.coinName]=0),C[R.coinName]?C[R.coinName]+=R.availableClaimCoin:C[R.coinName]=R.availableClaimCoin})})}),C})();if(c.length>0&&l.length>0)for(let C=0;C<l.length;C++){let x=l[C],v=!1,R=c.find(V=>V.id===x.obligationId)?.keyId,K={};if(R){if(Object.values(x.borrowIncentives).forEach(V=>{if(V){let Vt=V.rewards.filter(Et=>{let Pt=Et.coinName;return Et.availableClaimCoin>0&&!K[Pt]});v=Vt.length>0,Vt.forEach(Et=>{let Pt=o.claimBorrowIncentive(x.obligationId,R,Et.coinName);K[Et.coinName]=!0,S[Et.coinName]?S[Et.coinName].push(Pt):S[Et.coinName]=[Pt]})}}),w.sui>0){let V=qt.redeem_rewards(o,R,x.obligationId,Lp);S.sui?S.sui.push(V):S.sui=[V]}if(v&&await Hc(e.query,x.obligationId)){o.unstakeObligation(x.obligationId,R);let Vt=await e.query.getBindedVeScaKey(x.obligationId);Vt?o.stakeObligationWithVesca(x.obligationId,R,Vt):o.stakeObligation(x.obligationId,R)}}}let I=(await Promise.all(Object.entries(S).map(async([C,x])=>{let v=x[0];if(x.length>1&&o.mergeCoins(v,x.slice(1)),C==="sui"){o.mergeCoins(o.gas,[v]);return}return await e.builder.utils.mergeSimilarCoins(o,v,e.utils.parseCoinType(C),t),v}))).filter(C=>!!C);return I.length>0&&o.transferObjects(I,t),o.txBlock}async build(e){return this.claimIncentiveRewards(e.scallopClient,e.account.address)}static fromData(e={}){return new a(e)}};var sa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.depositCollateral(this.data.collateralCoinName,+this.data.amount,!1,this.data.obligationId)}static fromData(t){return new a(t)}};var ca=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async migrateAndClaim({account:t,scallopClient:o}){let n=t.address,{obligationKey:i,obligationId:c,rewardCoinName:l,veScaKey:d}=this.data,S=o.builder.createTxBlock();S.setSender(n);let w=qt.redeem_rewards(S,i,c,o.utils.parseCoinType(l));return S.transferObjects([w],n),await S.unstakeObligationQuick(c,i),d?await S.stakeObligationWithVeScaQuick(c,i,d):await S.stakeObligationQuick(c,i),S.txBlock}async build(t){return this.migrateAndClaim(t)}static fromData(t){return new a(t)}};var la=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.migrateAllMarketCoin(!1,!1)}static fromData(t){return new a(t)}};var ua=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.openObligation(!1)}static fromData(t){return new a(t)}};var ma=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async repay({account:t,scallopClient:o}){let n=t.address,{coinName:i,amount:c,obligationId:l,obligationKey:d}=this.data;return(await this.buildTxWithRefreshObligation(o,{walletAddress:n,obligationId:l,obligationKey:d},async(w,I)=>{await I.repayQuick(+c,i,l)})).txBlock}async build(t){return this.repay(t)}static fromData(t){return new a(t)}};var pa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async repayWithBoost({account:t,scallopClient:o}){let n=t.address,{coinName:i,amount:c,obligationId:l,veScaKey:d}=this.data,S=o.builder.createTxBlock();S.setSender(n);let w=o.constants.whitelist.borrowing.has(i);return w&&await S.unstakeObligationQuick(l,void 0),await S.repayQuick(+c,i,l),w&&await S.stakeObligationWithVeScaQuick(l,void 0,d),S.txBlock}async build(t){return this.repayWithBoost(t)}static fromData(t){return new a(t)}};var da=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.deposit(this.data.coinName,+this.data.amount,!1,t.account.address)}static fromData(t){return new a(t)}};var fa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.unstake(this.data.marketCoinName,+this.data.amount,!1)}static fromData(t){return new a(t)}};var ha=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async unstakeAndWithdraw(t,o,n){let i=t.builder.createTxBlock();i.setSender(n);let{stakeAccountId:c,amount:l,coinName:d}=this.data,S=[];for(let w=0;w<c.length;w++){let{id:I,coin:C}=c[w],x=t.utils.parseMarketCoinName(d),[v]=await i.unstakeQuick(C,x,I);if(v){let R=i.withdraw(v,d);S.push(R)}}if(l>0){let w=await i.withdrawQuick(l,d);S.push(w)}return S.length>1&&i.mergeCoins(S[0],S.slice(1)),i.transferObjects(S,n),i.txBlock}async build(t){return this.unstakeAndWithdraw(t.scallopClient,this.data,t.account.address)}static fromData(t){return new a(t)}};var ga=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.withdrawCollateral(this.data.collateralCoinName,Number(this.data.amount),!1,this.data.obligationId,this.data.obligationKey,t.account.address)}static fromData(t){return new a(t)}};var ya=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){return t.scallopClient.withdraw(this.data.coinName,Number(this.data.amount),!1,t.account.address)}static fromData(t){return new a(t)}};var ba=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async bindReferral({account:t,scallopClient:o}){let n=t.address,i=o.builder.createTxBlock();return i.setSender(n),i.bindToReferral(this.data.veScaKey),i.txBlock}async build(t){return this.bindReferral(t)}static fromData(t){return new a(t)}};var Sa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async claimRevenueReferral({account:t,scallopClient:o}){let{veScaKey:n,coins:i}=this.data,c=t.address,l=o.builder.createTxBlock();l.setSender(c);let d=i.map(S=>o.utils.parseCoinNameFromType(S));return await l.claimReferralRevenueQuick(n,d),l.txBlock}async build(t){return this.claimRevenueReferral(t)}static fromData(t){return new a(t)}};var Ta=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async createReferralLink({account:t,scallopClient:o}){let n=t.address,i=o.builder.createTxBlock();i.setSender(n);let c=i.mintEmptyVeSca();return i.transferObjects([c],n),i.txBlock}async build(t){return this.createReferralLink(t)}static fromData(t){return new a(t)}};import{SCA_COIN_TYPE as jp}from"@scallop-io/sui-scallop-sdk";var wa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async extendPeriodAndStakeMoreSca({account:t,scallopClient:o}){let{amount:n,veScaKey:i,unlockTime:c,obligationId:l,obligationKey:d,isOldBorrowIncentive:S,isObligationLocked:w}=this.data,I=t.address,C=o.builder.createTxBlock();C.setSender(I);let x=await o.utils.selectCoins(n,jp,I),[v,R]=C.takeAmountFromCoins(x,n);return C.extendLockPeriod(i,c),C.extendLockAmount(i,v),C.transferObjects([R],I),!l||!d||(w&&(S?qt.unstakeObligation(C,l,d):C.unstakeObligation(l,d)),C.stakeObligationWithVesca(l,d,i)),C.txBlock}async build(t){return this.extendPeriodAndStakeMoreSca(t)}static fromData(t){return new a(t)}};var Ia=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async extendStakeScaLockPeriod({account:t,scallopClient:o}){let n=t.address,{veScaKey:i,unlockTime:c,obligationId:l,obligationKey:d,isObligationLocked:S,isOldBorrowIncentive:w}=this.data,I=o.builder.createTxBlock();return I.setSender(n),I.extendLockPeriod(i,c),l&&d&&(S&&(w?qt.unstakeObligation(I,d,l):I.unstakeObligation(l,d)),I.stakeObligationWithVesca(l,d,i)),I.txBlock}async build(t){return this.extendStakeScaLockPeriod(t)}static fromData(t){return new a(t)}};var Ca=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async handleUnsubForKeys(t,o,n){let{targetVeScaKey:i,sourceVeScaKey:c}=this.data,[l,d]=await Promise.all([o.getBindedObligationId(i),o.getBindedObligationId(c)]);l&&await t.unstakeObligationQuick(l),d&&await t.unstakeObligationQuick(d),n(t,i,c),l&&await t.stakeObligationWithVeScaQuick(l,void 0,i),d&&await t.stakeObligationWithVeScaQuick(d,void 0,c)}async build(t){let{scallopClient:o,account:{address:n}}=t,i=o.builder.createTxBlock();return i.setSender(n),await this.handleUnsubForKeys(i,o.query,async(c,l,d)=>{c.mergeVeSca(i.object(l),i.object(d))}),i.txBlock}static fromData(t){return new a(t)}};var ka=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async redeemSca({account:t,scallopClient:o}){let{veScaKey:n}=this.data,i=t.address,c=o.builder.createTxBlock();return c.setSender(i),await c.redeemScaQuick(n),c.txBlock}async build(t){return this.redeemSca(t)}static fromData(t){return new a(t)}};import{SCA_COIN_TYPE as Up}from"@scallop-io/sui-scallop-sdk";var xa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async renewExpiredStakeSca({account:t,scallopClient:o}){let n=t.address,{amount:i,unlockTime:c,veScaKey:l,isHaveRedeem:d,obligation:S,obligationKey:w,isObligationLocked:I,isOldBorrowIncentive:C}=this.data,x=o.builder.createTxBlock();if(x.setSender(n),d){let V=x.redeemSca(l);x.transferObjects([V],n)}let v=await o.builder.utils.selectCoins(i,Up,n),[R,K]=x.takeAmountFromCoins(v,i);return x.transferObjects([K],n),x.renewExpiredVeSca(l,R,c),!S||!w||(I&&(C?qt.unstakeObligation(x,w,S):x.unstakeObligation(S,w)),x.stakeObligationWithVesca(S,w,l)),x.txBlock}async build(t){return this.renewExpiredStakeSca(t)}static fromData(t){return new a(t)}};var va=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async handleUnsubForKeys(t,o,n){let{targetVeScaKey:i,splitAmount:c}=this.data,l=await o.getBindedObligationId(i);l&&await t.unstakeObligationQuick(l),n(t,i,c.toString()),l&&await t.stakeObligationWithVeScaQuick(l,void 0,i)}async build(t){let{scallopClient:o,account:{address:n}}=t,i=o.builder.createTxBlock();return i.setSender(n),await this.handleUnsubForKeys(i,o.query,(c,l,d)=>{let S=c.splitVeSca(l,d.toString());c.transferObjects([S],n)}),i.txBlock}static fromData(t){return new a(t)}};import{SCA_COIN_TYPE as qp}from"@scallop-io/sui-scallop-sdk";var Da=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async stakeSca({account:t,scallopClient:o}){let n=t.address,{amount:i,isObligationLocked:c,isOldBorrowIncentive:l,obligationId:d,obligationKey:S,unlockTime:w,veScaKey:I}=this.data,C=o.builder.createTxBlock();C.setSender(n);let x=await o.utils.selectCoins(i,qp,n),[v,R]=C.takeAmountFromCoins(x,i),K;return I?C.extendLockAmount(I,v):K=C.lockSca(v,w),d&&S&&(c&&(l?qt.unstakeObligation(C,S,d):C.unstakeObligation(d,S)),C.stakeObligationWithVesca(d,S,I||K)),I||C.transferObjects([K,R],n),C.txBlock}async build(t){return this.stakeSca(t)}static fromData(t){return new a(t)}};var Aa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async supplyAndStake({account:t,scallopClient:o}){let n=t.address,{amount:i,coinName:c,stakeAccountId:l}=this.data,d=o.builder.createTxBlock();d.setSender(n);let S=await d.depositQuick(+i,c),w=o.utils.parseMarketCoinName(c);if(o.constants.whitelist.spool.has(w))return d.txBlock;let I=await o.query.getStakeAccounts(w,n),C=l||(I.length>0?I[0].id:void 0);if(C)await d.stakeQuick(S,w,C);else{let x=d.createStakeAccount(w);await d.stakeQuick(S,w,x),d.transferObjects([x],n)}return d.txBlock}async build(t){return this.supplyAndStake(t)}static fromData(t){return new a(t)}};var Oa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;handleAction(t,{action:o,args:n}){switch(o){case"deactivate":return t.deactivateBoost(n.obligationId,n.veScaKey);case"stake":return t.stakeObligationWithVesca(n.obligationId,n.obligationKey,n.veScaKey);case"unstake":return t.unstakeObligation(n.obligationId,n.obligationKey);default:throw new Error("Invalid action")}}async build(t){let{scallopClient:o,account:{address:n}}=t,i=o.builder.createTxBlock();i.setSender(n);let{bindingDatas:c}=this.data;return c.forEach(l=>this.handleAction(i,l)),i.txBlock}static fromData(t){return new a(t)}};var Ma=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{scallopClient:o,account:{address:n}}=t,i=o.builder.createTxBlock();i.setSender(n);let{veScaKeys:c}=this.data;return i.transferObjects(c.map(l=>i.objectRef(l)),i.pure.address(n)),i.txBlock}static fromData(t){return new a(t)}};var Pa=class a extends A{constructor(t){super(t);this.data=t}txType;txSubType;async withdrawUnlockedSca({account:t,scallopClient:o}){let{vescaKey:n}=this.data,i=t.address,c=o.builder.createTxBlock();return c.setSender(i),await c.redeemScaQuick(n),c.txBlock}async build(t){return this.withdrawUnlockedSca(t)}static fromData(t){return new a(t)}};var Ra=class{application="scallop";supportSDK="@mysten/sui";scallopClient;async initScallopClient(e,t){if(!this.scallopClient){let o=new Vp({addressId:"67c44a103fe1b8c454eb9699",walletAddress:e,suiClients:[t],fullnodeUrls:[t.transport.rpcClient.requestManager.transports[0]?.uri??Kp("mainnet")]});this.scallopClient=await o.createScallopClient()}}async deserialize(e){let{transaction:t,suiClient:o,account:n}=e;await this.initScallopClient(n.address,o),console.log("transaction",t);let i=new ta(t,this.scallopClient),c=new ea(t,this.scallopClient),l=new na(t,this.scallopClient),d=i.decode()||c.decode()||await l.decode();if(!d)throw new Error("Unknown transaction type");return{txType:Fp.Other,txSubType:d.type,intentionData:d.intentionData}}async build(e){let{suiClient:t,account:o,network:n,txSubType:i,intentionData:c}=e;await this.initScallopClient(o.address,t);let l;switch(i){case"SupplyLending":l=da.fromData(c);break;case"WithdrawLending":l=ya.fromData(c);break;case"Borrow":l=oa.fromData(c);break;case"Repay":l=ma.fromData(c);break;case"DepositCollateral":l=sa.fromData(c);break;case"WithdrawCollateral":l=ga.fromData(c);break;case"OpenObligation":l=ua.fromData(c);break;case"UnstakeSpool":l=fa.fromData(c);break;case"ClaimIncentiveReward":l=ra.fromData(c);break;case"BorrowWithBoost":l=aa.fromData(c);break;case"StakeSca":l=Da.fromData(c);break;case"ExtendStakePeriod":l=Ia.fromData(c);break;case"ExtendPeriodAndStakeMore":l=wa.fromData(c);break;case"RenewExpStakePeriod":l=xa.fromData(c);break;case"WithdrawStakedSca":l=Pa.fromData(c);break;case"SupplyAndStakeLending":l=Aa.fromData(c);break;case"WithdrawAndUnstakeLending":l=ha.fromData(c);break;case"RedeemSca":l=ka.fromData(c);break;case"MigrateAndClaim":l=ca.fromData(c);break;case"BorrowWithReferral":l=ia.fromData(c);break;case"CreateReferralLink":l=Ta.fromData(c);break;case"ClaimRevenueReferral":l=Sa.fromData(c);break;case"BindReferral":l=ba.fromData(c);break;case"MigrateScoin":l=la.fromData(c);break;case"RepayWithBoost":l=pa.fromData(c);break;case"MergeVeSca":l=Ca.fromData(c);break;case"SplitVeSca":l=va.fromData(c);break;case"VeScaObligationBindings":{l=Oa.fromData(c);break}case"TransferVeScaKeys":{l=Ma.fromData(c);break}default:throw new Error("not implemented")}return l.build({suiClient:t,account:o,network:n,scallopClient:this.scallopClient})}};import{TransactionType as Cd}from"@msafe/sui3-utils";import{TransactionType as on}from"@msafe/sui3-utils";import{normalizeStructTag as he}from"@mysten/sui/utils";import{API_URL as rd}from"@suilend/sui-fe";import{TransactionType as od}from"@msafe/sui3-utils";import{LENDING_MARKET_ID as ad,LENDING_MARKET_TYPE as id,SuilendClient as qr}from"@suilend/sdk";import{TransactionType as Re}from"@msafe/sui3-utils";import{fromBase64 as Qc,toHex as zc}from"@mysten/bcs";import{normalizeStructTag as en}from"@mysten/sui/utils";import{MAX_U64 as Be}from"@suilend/sui-fe";import Jc from"bignumber.js";var Ba=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isDepositTransaction())return this.decodeDeposit();if(this.isWithdrawTransaction())return this.decodeWithdraw();if(this.isBorrowTransaction())return this.decodeBorrow();if(this.isRepayTransaction())return this.decodeRepay();if(this.isClaimTransaction())return this.decodeClaim();if(this.isClaimAndDepositTransaction())return this.decodeClaimAndDeposit();throw new Error("Unknown transaction type")}get inputs(){return console.log("this.transaction.getData().inputs",this.transaction.getData().inputs),this.transaction.getData().inputs}get commands(){return console.log("this.transaction.getData().commands",this.transaction.getData().commands),this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}hasDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasClaimTransactionMoveCallCommands(){return!!this.getMoveCallCommand("claim_rewards")}isDepositTransaction(){return!this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}isWithdrawTransaction(){return!!this.getMoveCallCommand("withdraw_ctokens")&&!!this.getMoveCallCommand("redeem_ctokens_and_withdraw_liquidity_request")}isBorrowTransaction(){return!!this.getMoveCallCommand("borrow_request")}isRepayTransaction(){return!!this.getMoveCallCommand("repay")}isClaimTransaction(){return this.hasClaimTransactionMoveCallCommands()&&!this.hasDepositTransactionMoveCallCommands()}isClaimAndDepositTransaction(){return this.hasClaimTransactionMoveCallCommands()&&this.hasDepositTransactionMoveCallCommands()}decodeDeposit(){let e={MintEvent:this.simResult.events.find(n=>n.type.includes("lending_market::MintEvent"))},t=en(e.MintEvent.parsedJson.coin_type.name),o=e.MintEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeDeposit",t,o),{txType:Re.Other,type:"deposit",intentionData:{coinType:t,value:o}}}decodeWithdraw(){let e={withdraw_ctokens:this.getMoveCallCommand("withdraw_ctokens")},t={RedeemEvent:this.simResult.events.find(d=>d.type.includes("lending_market::RedeemEvent"))},o=en(t.RedeemEvent.parsedJson.coin_type.name),n=t.RedeemEvent.parsedJson.liquidity_amount;console.log("Decoder.decodeWithdraw",o,n);let i=e.withdraw_ctokens.MoveCall.arguments[4].Input,c=new Jc(zc(Qc(this.inputs[i].Pure.bytes)),16).toString(),l=c===Be.toString();return console.log("decodeWithdraw - isMax:",l,"inputIndex:",i,"inputValue:",c,"MAX_U64.toString():",Be.toString()),l&&(n=Be.toString()),{txType:Re.Other,type:"withdraw",intentionData:{coinType:o,value:n}}}decodeBorrow(){let e={borrow_request:this.getMoveCallCommand("borrow_request")},t={BorrowEvent:this.simResult.events.find(d=>d.type.includes("lending_market::BorrowEvent"))},o=en(t.BorrowEvent.parsedJson.coin_type.name),n=`${+t.BorrowEvent.parsedJson.liquidity_amount-+t.BorrowEvent.parsedJson.origination_fee_amount}`;console.log("Decoder.decodeBorrow",o,n);let i=e.borrow_request.MoveCall.arguments[4].Input,c=new Jc(zc(Qc(this.inputs[i].Pure.bytes)),16).toString(),l=c===Be.toString();return console.log("decodeBorrow - isMax:",l,"inputIndex:",i,"inputValue:",c,"MAX_U64.toString():",Be.toString()),l&&(n=Be.toString()),{txType:Re.Other,type:"borrow",intentionData:{coinType:o,value:n}}}decodeRepay(){let e={RepayEvent:this.simResult.events.find(n=>n.type.includes("lending_market::RepayEvent"))},t=en(e.RepayEvent.parsedJson.coin_type.name),o=e.RepayEvent.parsedJson.liquidity_amount;return console.log("Decoder.decodeRepay",t,o),{txType:Re.Other,type:"repay",intentionData:{coinType:t,value:o}}}decodeClaim(){let e={ClaimReward:this.simResult.events.filter(o=>o.type.includes("lending_market::ClaimReward"))},t={};for(let o=0;o<e.ClaimReward.length;o++){let n=e.ClaimReward[o],i=en(n.parsedJson.coin_type.name),c=n.parsedJson.liquidity_amount;t[i]=`${+(t[i]??"0")+ +c}`}return console.log("Decoder.decodeClaimRewards",t),{txType:Re.Other,type:"claim",intentionData:{value:t}}}decodeClaimAndDeposit(){return{txType:Re.Other,type:"claimAndDeposit",intentionData:this.decodeClaim().intentionData}}};import{Transaction as Xp}from"@mysten/sui/transactions";import Hp from"sort-keys-recursive";var Nt=class{constructor(e){this.data=e}serialize(){return JSON.stringify(Hp(this.data))}};var Ea=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n,suilendClient:i,obligationOwnerCap:c,obligation:l}=t;if(console.log("BorrowIntention.build",o,n,i,c,l),!c||!l)throw new Error("Obligation not found");let d=new Xp;return await i.borrowAndSendToUser(n.address,c.id,l.id,this.data.coinType,this.data.value,d),d}static fromData(t){return console.log("BorrowIntention.fromData",t),new a(t)}};import{Transaction as Yp}from"@mysten/sui/transactions";import{normalizeStructTag as Gp}from"@mysten/sui/utils";import{Side as nn}from"@suilend/sdk";import{isSendPoints as Qp}from"@suilend/sui-fe";import zp from"bignumber.js";var Jp=(a,e)=>{let t={[nn.DEPOSIT]:[],[nn.BORROW]:[]};return a.lendingMarket.reserves.forEach(o=>{[nn.DEPOSIT,nn.BORROW].forEach(n=>{let i=n===nn.DEPOSIT?o.depositsPoolRewardManager:o.borrowsPoolRewardManager,c=e.userRewardManagers.find(l=>l.poolRewardManagerId===i.id);c&&(t[n]=i.poolRewards.map((l,d)=>({reserveArrayIndex:o.arrayIndex,rewardIndex:BigInt(d),rewardCoinType:Gp(l.coinType.name),side:n})).filter(l=>!Qp(l.rewardCoinType)&&!!c.rewards[Number(l.rewardIndex)]&&new zp(c.rewards[Number(l.rewardIndex)].earnedRewards.value.toString()).gt(0)))})}),Object.values(t).flat()},Na=Jp;var Wa=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n,suilendClient:i,obligationOwnerCap:c,obligation:l}=t;if(console.log("ClaimIntention.build",o,n,i,c,l),!c||!l)throw new Error("Obligation not found");let d=new Yp;return i.claimRewardsAndSendToUser(n.address,c.id,Na(i,l),d),d}static fromData(t){return console.log("ClaimIntention.fromData",t),new a(t)}};import{Transaction as Zp}from"@mysten/sui/transactions";var _a=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n,suilendClient:i,obligationOwnerCap:c,obligation:l}=t;if(console.log("ClaimAndDepositIntention.build",o,n,i,c,l),!c||!l)throw new Error("Obligation not found");let d=new Zp;return i.claimRewardsAndDeposit(n.address,c.id,Na(i,l),d),d}static fromData(t){return console.log("ClaimAndDepositIntention.fromData",t),new a(t)}};import{Transaction as td}from"@mysten/sui/transactions";var La=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n,suilendClient:i,obligationOwnerCap:c,obligation:l}=t;console.log("DepositIntention.build",o,n,i,c,l);let d=new td;return await i.depositIntoObligation(n.address,this.data.coinType,this.data.value,d,c?.id),d}static fromData(t){return console.log("DepositIntention.fromData",t),new a(t)}};import{Transaction as ed}from"@mysten/sui/transactions";var ja=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n,suilendClient:i,obligationOwnerCap:c,obligation:l}=t;if(console.log("RepayIntention.build",o,n,i,c,l),!c||!l)throw new Error("Obligation not found");let d=new ed;return await i.repayIntoObligation(n.address,l.id,this.data.coinType,this.data.value,d),d}static fromData(t){return console.log("RepayIntention.fromData",t),new a(t)}};import{Transaction as nd}from"@mysten/sui/transactions";var Ua=class a extends Nt{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n,suilendClient:i,obligationOwnerCap:c,obligation:l}=t;if(console.log("WithdrawIntention.build",o,n,i,c,l),!c||!l)throw new Error("Obligation not found");let d=new nd;return await i.withdrawAndSendToUser(n.address,c.id,l.id,this.data.coinType,this.data.value,d),d}static fromData(t){return console.log("WithdrawIntention.fromData",t),new a(t)}};var qa=async(a,e)=>{let t=await qr.initialize(ad,id,a),o=await qr.getObligationOwnerCaps(e.address,t.lendingMarket.$typeArgs,a),n=await Promise.all(o.map(i=>qr.getObligation(i.obligationId,t.lendingMarket.$typeArgs,a)));return console.log("XXX getUtils - suilendClient:",t,"obligations:",n,"obligationOwnerCaps:",o),{suilendClient:t,obligationOwnerCaps:o,obligations:n}},Fa=class{application="Suilend";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:o,account:n}=e;this.utils||(this.utils=await qa(o,n));let i=await o.devInspectTransactionBlock({sender:n.address,transactionBlock:t});console.log("SuilendAppHelper.deserialize - simResult:",i,"utils:",this.utils,"suiClient:",o);let l=new Ba(t,i).decode();return{txType:od.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{network:t,txSubType:o,intentionData:n,suiClient:i,account:c}=e;this.utils||(this.utils=await qa(i,c));let l;switch(o){case"deposit":l=La.fromData(n);break;case"withdraw":l=Ua.fromData(n);break;case"borrow":l=Ea.fromData(n);break;case"repay":l=ja.fromData(n);break;case"claim":l=Wa.fromData(n);break;case"claimAndDeposit":l=_a.fromData(n);break;default:throw new Error("not implemented")}let d=window.localStorage.getItem("obligationId"),S=this.utils.obligations?.find(I=>I.id===d)??this.utils.obligations?.[0],w=this.utils.obligationOwnerCaps?.find(I=>I.obligationId===S?.id);return l.build({network:t,suiClient:i,account:c,suilendClient:this.utils.suilendClient,obligationOwnerCap:w,obligation:S})}};var Fr=async(a,e)=>{let t=await qa(a,e),o=await fetch(`${rd}/springsui/lst-info`),n=await o.json();if(o?.statusCode===500)throw new Error("Failed to fetch SpringSui LST data");let c=Object.fromEntries(Object.values(n).map(l=>[l.LIQUID_STAKING_INFO.type,l.LIQUID_STAKING_INFO]));return{...t,LIQUID_STAKING_INFO_MAP:c}};var Ka=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isStakeTransaction())return this.decodeStake();if(this.isStakeAndDepositTransaction())return this.decodeStakeAndDeposit();if(this.isConvertTransaction())return this.decodeConvert();if(this.isConvertAndDepositTransaction())return this.decodeConvertAndDeposit();if(this.isUnstakeTransaction())return this.decodeUnstake();throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}hasSuilendDepositTransactionMoveCallCommands(){return!!this.getMoveCallCommand("deposit_liquidity_and_mint_ctokens")&&!!this.getMoveCallCommand("deposit_ctokens_into_obligation")}hasMintMoveCallCommands(){return!!this.getMoveCallCommand("mint")}hasRedeemMoveCallCommands(){return!!this.getMoveCallCommand("redeem")}isStakeTransaction(){return this.hasMintMoveCallCommands()&&!this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isStakeAndDepositTransaction(){return this.hasMintMoveCallCommands()&&!this.hasRedeemMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isConvertTransaction(){return this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}isConvertAndDepositTransaction(){return this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&this.hasSuilendDepositTransactionMoveCallCommands()}isUnstakeTransaction(){return!this.hasMintMoveCallCommands()&&this.hasRedeemMoveCallCommands()&&!this.hasSuilendDepositTransactionMoveCallCommands()}decodeStake(){let e={MintEvent:this.simResult.events.find(n=>n.type.includes("liquid_staking::MintEvent"))},t=he(e.MintEvent.parsedJson.event.typename.name),o=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStake",o),{txType:on.Other,type:"stake",intentionData:{amount:o,outCoinType:t}}}decodeStakeAndDeposit(){let e={MintEvent:this.simResult.events.find(n=>n.type.includes("liquid_staking::MintEvent"))},t=he(e.MintEvent.parsedJson.event.typename.name),o=e.MintEvent.parsedJson.event.sui_amount_in;return console.log("Decoder.decodeStakeAndDeposit",o),{txType:on.Other,type:"stakeAndDeposit",intentionData:{amount:o,outCoinType:t}}}decodeConvert(){let e={RedeemEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::MintEvent"))},t=he(e.RedeemEvent.parsedJson.event.typename.name),o=he(e.MintEvent.parsedJson.event.typename.name),n=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvert",n),{txType:on.Other,type:"convert",intentionData:{amount:n,inCoinType:t,outCoinType:o}}}decodeConvertAndDeposit(){let e={RedeemEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::RedeemEvent")),MintEvent:this.simResult.events.find(i=>i.type.includes("liquid_staking::MintEvent"))},t=he(e.RedeemEvent.parsedJson.event.typename.name),o=he(e.MintEvent.parsedJson.event.typename.name),n=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeConvertAndDeposit",n),{txType:on.Other,type:"convertAndDeposit",intentionData:{amount:n,inCoinType:t,outCoinType:o}}}decodeUnstake(){let e={RedeemEvent:this.simResult.events.find(n=>n.type.includes("liquid_staking::RedeemEvent"))},t=he(e.RedeemEvent.parsedJson.event.typename.name),o=e.RedeemEvent.parsedJson.event.lst_amount_in;return console.log("Decoder.decodeUnstake",o),{txType:on.Other,type:"unstake",intentionData:{amount:o,inCoinType:t}}}};import{Transaction as ld}from"@mysten/sui/transactions";import{convertLstsAndSendToUser as ud,LstClient as Yc}from"@suilend/springsui-sdk";import cd from"sort-keys-recursive";var Ft=class{constructor(e){this.data=e}serialize(){return JSON.stringify(cd(this.data))}};var Va=class a extends Ft{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n,suilendClient:i,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("ConvertIntention.build",o,n,i,c,l,d);let S=await Yc.initialize(o,Object.values(c).find(C=>C.type===this.data.inCoinType)),w=await Yc.initialize(o,Object.values(c).find(C=>C.type===this.data.outCoinType)),I=new ld;return ud(S,w,I,n.address,this.data.amount),I}static fromData(t){return console.log("ConvertIntention.fromData",t),new a(t)}};import{Transaction as md}from"@mysten/sui/transactions";import{createObligationIfNoneExists as pd,sendObligationToUser as dd}from"@suilend/sdk";import{convertLsts as fd,LstClient as Zc}from"@suilend/springsui-sdk";var $a=class a extends Ft{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n,suilendClient:i,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("ConvertAndDepositIntention.build",o,n,i,c,l,d);let S=await Zc.initialize(o,Object.values(c).find(R=>R.type===this.data.inCoinType)),w=await Zc.initialize(o,Object.values(c).find(R=>R.type===this.data.outCoinType)),I=new md,{obligationOwnerCapId:C,didCreate:x}=pd(i,I,l),v=fd(S,w,I,n.address,this.data.amount);return i.deposit(v,this.data.outCoinType,C,I),x&&dd(C,n.address,I),I}static fromData(t){return console.log("ConvertAndDepositIntention.fromData",t),new a(t)}};import{Transaction as hd}from"@mysten/sui/transactions";import{LstClient as gd}from"@suilend/springsui-sdk";var Ha=class a extends Ft{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n,suilendClient:i,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("StakeIntention.build",o,n,i,c,l,d);let S=await gd.initialize(o,Object.values(c).find(I=>I.type===this.data.outCoinType)),w=new hd;return S.mintAmountAndRebalanceAndSendToUser(w,n.address,this.data.amount),w}static fromData(t){return console.log("StakeIntention.fromData",t),new a(t)}};import{Transaction as yd}from"@mysten/sui/transactions";import{createObligationIfNoneExists as bd,sendObligationToUser as Sd}from"@suilend/sdk";import{LstClient as Td}from"@suilend/springsui-sdk";var Xa=class a extends Ft{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n,suilendClient:i,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("StakeAndDepositIntention.build",o,n,i,c,l,d);let S=await Td.initialize(o,Object.values(c).find(v=>v.type===this.data.outCoinType)),w=new yd,{obligationOwnerCapId:I,didCreate:C}=bd(i,w,l),x=S.mintAmountAndRebalance(w,n.address,this.data.amount);return i.deposit(x,this.data.outCoinType,I,w),C&&Sd(I,n.address,w),w}static fromData(t){return console.log("StakeAndDepositIntention.fromData",t),new a(t)}};import{Transaction as wd}from"@mysten/sui/transactions";import{LstClient as Id}from"@suilend/springsui-sdk";var Ga=class a extends Ft{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{suiClient:o,account:n,suilendClient:i,LIQUID_STAKING_INFO_MAP:c,obligationOwnerCap:l,obligation:d}=t;console.log("UnstakeIntention.build",o,n,i,c,l,d);let S=await Id.initialize(o,Object.values(c).find(I=>I.type===this.data.inCoinType)),w=new wd;return S.redeemAmountAndSendToUser(w,n.address,this.data.amount),w}static fromData(t){return console.log("UnstakeIntention.fromData",t),new a(t)}};var Qa=class{application="SpringSui";supportSDK="@mysten/sui";utils;async deserialize(e){let{transaction:t,suiClient:o,account:n}=e;this.utils||(this.utils=await Fr(o,n));let i=await o.devInspectTransactionBlock({sender:n.address,transactionBlock:t});console.log("SpringSuiAppHelper.deserialize",i);let l=new Ka(t,i).decode();return{txType:Cd.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{network:t,txSubType:o,intentionData:n,suiClient:i,account:c}=e;this.utils||(this.utils=await Fr(i,c));let l;switch(o){case"stake":l=Ha.fromData(n);break;case"stakeAndDeposit":l=Xa.fromData(n);break;case"convert":l=Va.fromData(n);break;case"convertAndDeposit":l=$a.fromData(n);break;case"unstake":l=Ga.fromData(n);break;default:throw new Error("not implemented")}return l.build({network:t,suiClient:i,account:c,suilendClient:this.utils.suilendClient,LIQUID_STAKING_INFO_MAP:this.utils.LIQUID_STAKING_INFO_MAP,obligationOwnerCap:this.utils.obligationOwnerCaps?.[0],obligation:this.utils.obligations?.[0]})}};import{TransactionType as Dd}from"@msafe/sui3-utils";import{TransactionType as tl}from"@msafe/sui3-utils";var za=class{constructor(e,t){this.transaction=e;this.simResult=t}decode(){if(this.isMintTransaction()){let e=this.getLiquidityChangeEvent("MintEvent");if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson;return console.log("Decoder event data - ",t),this.decodeMint(t)}if(this.isRedeemTransaction()){let e=this.getLiquidityChangeEvent("RedeemEvent");if(!e)throw new Error("No liquidity change event found. Unable to decode transaction.");let t=e.parsedJson;return console.log("Decoder event data - ",t),this.decodeRedeem(t)}throw new Error("Unknown transaction type")}get commands(){return this.transaction.getData().commands}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getLiquidityChangeEvent(e){return this.simResult.events.find(t=>this.isLiquidityChangeEventType(t.type,e))}isLiquidityChangeEventType(e,t){return e.includes(t)}isMintTransaction(){return!!this.getMoveCallCommand("mint")}isRedeemTransaction(){return!!this.getMoveCallCommand("redeem")}decodeMint(e){let{event:{sui_amount_in:t}}=e;return console.log("Decoder.decodeMint",t),{txType:tl.Other,type:"mint",intentionData:{amount:t}}}decodeRedeem(e){let{event:{lst_amount_in:t}}=e;return console.log("Decoder.decodeRedeem",t),{txType:tl.Other,type:"redeem",intentionData:{amount:t}}}};import{LST as xd}from"@alphafi/stsui-sdk";var Ja=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:o}=t,{amount:n}=this.data,i={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},l=await new xd(i).mint(n,o.address);return l.setGasBudget(1e8),l}static fromData(t){return console.log("MintIntention.fromData",t),new a(t)}};import{LST as vd}from"@alphafi/stsui-sdk";var Ya=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{account:o}=t,{amount:n}=this.data,i={lstInfo:"0x1adb343ab351458e151bc392fbf1558b3332467f23bda45ae67cd355a57fd5f5",lstCointype:"0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI"},l=await new vd(i).redeem(n,o.address);return l.setGasBudget(1e8),l}static fromData(t){return console.log("RedeemIntention.fromData",t),new a(t)}};var Za=class{application="stsui";supportSDK="@mysten/sui";async deserialize(e){let{transaction:t,suiClient:o}=e,n=await o.devInspectTransactionBlock({sender:t.getData().sender,transactionBlock:t});console.log("StSuiHelper Sim result - ",n);let c=new za(t,n).decode();return{txType:Dd.Other,txSubType:c.type,intentionData:c.intentionData}}async build(e){let{account:t}=e;console.log("StSui build transaction type",e.txSubType);let o;switch(e.txSubType){case"mint":o=Ja.fromData(e.intentionData);break;case"redeem":o=Ya.fromData(e.intentionData);break;default:throw new Error("build not implemented")}return o.build({account:t})}};import{TransactionType as Gd}from"@msafe/sui3-utils";import{TurbosSdk as Qd}from"turbos-clmm-sdk";import{TransactionType as Kt}from"@msafe/sui3-utils";import{bcs as el}from"@mysten/sui.js/bcs";import{normalizeStructTag as Od,normalizeSuiAddress as an}from"@mysten/sui.js/utils";import{BN as Md}from"turbos-clmm-sdk";var Ht={PackageId:"0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97",Claim:"0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894",turbosCoinType:"0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS"},Xt={PackageId:"0xdee9"};var Pd=(a,e,t,o)=>{if(a===1)switch(o.findIndex(c=>c===e)){case 0:return[!0,!0];case 1:return[!0,!1];case 2:return[!1,!0];case 3:return[!1,!1];default:throw new Error(`not target: ${e}`)}switch(t.findIndex(i=>i===e)){case 0:return[!0];case 1:return[!1];default:throw new Error(`not target: ${e}`)}},ti=class{constructor(e,t,o){this.txb=e;this.turbosSdk=t;this.config=o}get transactions(){return this.txb.blockData.transactions}get swap1Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b`,`${this.config.PackageId}::swap_router::swap_b_a`]}get swap2Layer(){return[`${this.config.PackageId}::swap_router::swap_a_b_b_c`,`${this.config.PackageId}::swap_router::swap_a_b_c_b`,`${this.config.PackageId}::swap_router::swap_b_a_b_c`,`${this.config.PackageId}::swap_router::swap_b_a_c_b`]}async decode(e){if(this.isSwapTransaction())return this.decodeSwap();if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(e);if(this.isRemoveLiquidityTransaction())return this.decodeRemoveLiquidity(e);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(e);if(this.isCollectFeeTransaction())return this.decodeCollectFee();if(this.isCollectRewardTransaction())return this.decodeCollectReward();if(this.isBurnTransaction())return this.decodeBurn();if(this.isPrixClaimTransaction())return this.decodePrixClaim();if(this.isPrixJoinTransaction())return this.decodePrixJoin();if(this.isSwapExactBaseForQuoteTransaction())return this.decodeSwapExactBaseForQuote();if(this.isSwapExactQuoteForBaseTransaction())return this.decodeSwapExactQuoteForBase();throw new Error("Unknown transaction type")}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}getMoveCallsTransaction(e){return e.every(t=>this.transactions.find(o=>o.kind==="MoveCall"&&o.target===t))}getSwapMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&e.includes(t.target))}isSwapTransaction(){return!!this.getSwapMoveCallTransaction([...this.swap1Layer,...this.swap2Layer])}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect`)}isCollectRewardTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect_reward`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::burn`)}isPrixJoinTransaction(){return!!this.getMoveCallTransaction(`${Ht.PackageId}::claim::join`)}isPrixClaimTransaction(){return!!this.getMoveCallTransaction(`${Ht.PackageId}::claim::claim`)}isRemoveLiquidityTransaction(){return!!this.getMoveCallsTransaction([`${this.config.PackageId}::position_manager::decrease_liquidity`,`${this.config.PackageId}::position_manager::burn`])}isSwapExactBaseForQuoteTransaction(){return!!this.getMoveCallTransaction(`${Xt.PackageId}::clob_v2::swap_exact_base_for_quote`)}isSwapExactQuoteForBaseTransaction(){return!!this.getMoveCallTransaction(`${Xt.PackageId}::clob_v2::swap_exact_quote_for_base`)}async decodeSwap(){let e=this.transactions.find(x=>x.kind==="MoveCall"),t=0;this.swap2Layer.includes(e.target)&&(t=1);let o=Pd(t,e.target,this.swap1Layer,this.swap2Layer),n=o.map((x,v)=>{let R=this.helper.decodeSharedObjectId(v),K=this.helper.decodeInputU128(4+v+t),V=this.turbosSdk.math.sqrtPriceX64ToTickIndex(new Md(K.toString()));return{pool:R,a2b:x,nextTickIndex:V}}),i=o[0]||t===1?e.typeArguments[0]:e.typeArguments[1],c=t===1?e.typeArguments[4]:o[0]?e.typeArguments[1]:e.typeArguments[0],l=this.helper.decodeInputAddress(6+2*t),d=this.helper.decodeInputU64(7+2*t),S=this.helper.decodeInputBool(5+2*t),w=this.helper.decodeInputU64(2+t),I=this.helper.decodeInputU64(3+t),C=await this.turbosSdk.trade.computeSwapResultV2({pools:[{pool:n[0].pool,a2b:n[0].a2b,amountSpecified:w}],address:l,amountSpecifiedIsInput:S});return{txType:Kt.Other,type:"Swap",intentionData:{routes:n,coinTypeA:i,coinTypeB:c,address:l,amountA:S?w:I,amountB:S?I:w,amountSpecifiedIsInput:S,slippage:"0.1",deadline:d}}}decodeAddLiquidity(){console.log(this.helper,"decodeAddLiquidity this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeInputAddress(12),o=this.helper.decodeInputU64(8),n=this.helper.decodeInputU64(9),i=this.helper.decodeInputU32(4),c=this.helper.decodeInputBool(5),l=this.helper.decodeInputU32(6),d=this.helper.decodeInputBool(7),S=this.helper.decodeInputU64(13);return{txType:Kt.Other,type:"AddLiquidity",intentionData:{pool:e,slippage:10,address:t,amountA:o,amountB:n,tickLower:c?-i:i,tickUpper:d?-l:l,deadline:S}}}decodeIncreaseLiquidity(e){console.log(this.helper,"decodeIncreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),o=this.helper.decodeSharedObjectId(4),n=this.helper.decodeInputU64(5),i=this.helper.decodeInputU64(6),c=this.helper.decodeInputU64(9);return{txType:Kt.Other,type:"IncreaseLiquidity",intentionData:{pool:t,slippage:10,address:e,amountA:n,amountB:i,nft:o,deadline:c}}}decodeDecreaseLiquidity(e){console.log(this.helper,"decodeDecreaseLiquidity this.helper");let t=this.helper.decodeSharedObjectId(0),o=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputU64(3),i=this.helper.decodeInputU64(4),c=this.helper.decodeInputU64(5),l=this.helper.decodeInputU64(6);return{txType:Kt.Other,type:"DecreaseLiquidity",intentionData:{pool:t,decreaseLiquidity:n,nft:o,amountA:i,amountB:c,slippage:10,address:e,deadline:l}}}decodeCollectFee(){console.log(this.helper,"decodeCollectFee this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2),o=this.helper.decodeInputAddress(5),n=this.helper.decodeInputU64(3),i=this.helper.decodeInputU64(4),c=this.helper.decodeInputU64(6);return{txType:Kt.Other,type:"CollectFee",intentionData:{pool:e,address:o,collectAmountA:n,collectAmountB:i,nft:t,deadline:c}}}decodeCollectReward(){console.log(this.helper,"decodeCollectReward this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2),o=this.helper.decodeInputAddress(6),n=this.collectRewardHelper.map(c=>c.decodeInputU64(5)),i=this.helper.decodeInputU64(7);return{txType:Kt.Other,type:"CollectReward",intentionData:{pool:e,address:o,rewardAmounts:n,nft:t,deadline:i}}}decodeBurn(){console.log(this.helper,"decodeBurn this.helper");let e=this.helper.decodeSharedObjectId(0),t=this.helper.decodeSharedObjectId(2);return{txType:Kt.Other,type:"Burn",intentionData:{pool:e,nft:t}}}decodeRemoveLiquidity(e){console.log(this.helper,"decodeRemoveLiquidity this.helper");let t=this.decreaseLiquidityHelper.decodeSharedObjectId(0),o=this.decreaseLiquidityHelper.decodeSharedObjectId(2),n=this.decreaseLiquidityHelper.decodeInputU64(3),i=this.decreaseLiquidityHelper.decodeInputU64(4),c=this.decreaseLiquidityHelper.decodeInputU64(5),l=this.decreaseLiquidityHelper.decodeInputU64(6),d=this.collectRewardHelper.map(I=>I.decodeInputU64(5)),S=this.collectFeeHelper.decodeInputU64(3)||0,w=this.collectFeeHelper.decodeInputU64(4)||0;return{txType:Kt.Other,type:"RemoveLiquidity",intentionData:{pool:t,decreaseLiquidity:n,nft:o,amountA:i,amountB:c,slippage:10,address:e,collectAmountA:S,collectAmountB:w,rewardAmounts:d,deadline:l}}}decodePrixClaim(){return{txType:Kt.Other,type:"PrixClaim",intentionData:{}}}decodePrixJoin(){return{txType:Kt.Other,type:"PrixJoin",intentionData:{}}}decodeSwapExactBaseForQuote(){let e=this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0),t=this.swapExactBaseForQuoteHelper.decodeInputU64(3),o=this.swapExactBaseForQuoteHelper.shortTypeArg(0),n=this.swapExactBaseForQuoteHelper.shortTypeArg(1);return{txType:Kt.Other,type:"SwapExactBaseForQuote",intentionData:{poolId:e,amountIn:t,token1:o,token2:n}}}decodeSwapExactQuoteForBase(){let e=this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0),t=this.swapExactQuoteForBaseHelper.decodeInputU64(3),o=this.swapExactQuoteForBaseHelper.shortTypeArg(0),n=this.swapExactQuoteForBaseHelper.shortTypeArg(1);return{txType:Kt.Other,type:"SwapExactQuoteForBase",intentionData:{poolId:e,amountIn:t,token1:o,token2:n}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target!=="0x2::coin::zero"&&t.target!=="0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero");return new ce(e,this.txb)}get collectRewardHelper(){return this.transactions.filter(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::collect_reward`).map(t=>new ce(t,this.txb))}get collectFeeHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::collect`);return new ce(e,this.txb)}get decreaseLiquidityHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${this.config.PackageId}::position_manager::decrease_liquidity`);return new ce(e,this.txb)}get swapExactBaseForQuoteHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${Xt.PackageId}::clob_v2::swap_exact_base_for_quote`);return new ce(e,this.txb)}get swapExactQuoteForBaseHelper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target===`${Xt.PackageId}::clob_v2::swap_exact_quote_for_base`);return new ce(e,this.txb)}},ce=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU128(e){let t=this.decodePureArg(e,"u128");return Number(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU32(e){let t=this.decodePureArg(e,"u32");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return an(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let o=this.getInputParam(e);return a.getPureInputValue(o,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let o=e.value.Pure;return el.de(t,new Uint8Array(o))}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 an(e.value.Object.ImmOrOwned.objectId)}return an(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return an(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return an(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let o=e.value.Pure;return el.de(t,new Uint8Array(o))}typeArg(e){return Od(this.moveCall.typeArguments[e])}shortTypeArg(e){return this.moveCall.typeArguments[e]}txArg(e){return this.moveCall.arguments[e]}};import{TurbosSdk as Rd}from"turbos-clmm-sdk";var ei=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let o=new Rd(t.network.replace("sui:",""),t.suiClient),{pool:n,address:i,amountA:c,amountB:l,slippage:d,tickLower:S,tickUpper:w,deadline:I,txb:C}=this.data;return o.pool.addLiquidity({pool:n,slippage:d,address:i,amountA:c,amountB:l,tickLower:S,tickUpper:w,deadline:I,txb:C})}static fromData(t){return new a(t)}};import{TurbosSdk as Bd}from"turbos-clmm-sdk";var ni=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let o=new Bd(t.network.replace("sui:",""),t.suiClient),{pool:n,nft:i,txb:c}=this.data;return o.nft.burn({pool:n,nft:i,txb:c})}static fromData(t){return new a(t)}};import{TurbosSdk as Ed}from"turbos-clmm-sdk";var oi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let o=new Ed(t.network.replace("sui:",""),t.suiClient),{pool:n,address:i,nft:c,collectAmountA:l,collectAmountB:d,deadline:S,txb:w}=this.data;return o.pool.collectFee({pool:n,address:i,collectAmountA:l,collectAmountB:d,nft:c,deadline:S,txb:w})}static fromData(t){return new a(t)}};import{TurbosSdk as Nd}from"turbos-clmm-sdk";var ai=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let o=new Nd(t.network.replace("sui:",""),t.suiClient),{pool:n,address:i,nft:c,rewardAmounts:l,deadline:d,txb:S}=this.data;return o.pool.collectReward({pool:n,address:i,rewardAmounts:l,nft:c,deadline:d,txb:S})}static fromData(t){return new a(t)}};import{TurbosSdk as Wd}from"turbos-clmm-sdk";var ii=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let o=new Wd(t.network.replace("sui:",""),t.suiClient),{fee:n,address:i,tickLower:c,tickUpper:l,sqrtPrice:d,slippage:S,coinTypeA:w,coinTypeB:I,amountA:C,amountB:x,deadline:v,txb:R}=this.data;return o.pool.createPool({fee:n,amountA:C,amountB:x,address:i,tickLower:c,tickUpper:l,sqrtPrice:d,slippage:S,coinTypeA:w,coinTypeB:I,deadline:v,txb:R})}static fromData(t){return new a(t)}};import{TurbosSdk as _d}from"turbos-clmm-sdk";var ri=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let o=new _d(t.network.replace("sui:",""),t.suiClient),{pool:n,address:i,amountA:c,amountB:l,slippage:d,nft:S,decreaseLiquidity:w,deadline:I,txb:C}=this.data;return o.pool.decreaseLiquidity({pool:n,slippage:d,address:i,amountA:c,amountB:l,nft:S,decreaseLiquidity:w,deadline:I,txb:C})}static fromData(t){return new a(t)}};import{TurbosSdk as Ld}from"turbos-clmm-sdk";var si=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let o=new Ld(t.network.replace("sui:",""),t.suiClient),{pool:n,address:i,amountA:c,amountB:l,slippage:d,nft:S,deadline:w,txb:I}=this.data;return o.pool.increaseLiquidity({pool:n,slippage:d,address:i,amountA:c,amountB:l,nft:S,deadline:w,txb:I})}static fromData(t){return new a(t)}};import{TransactionBlock as jd}from"@mysten/sui.js/transactions";import{SUI_CLOCK_OBJECT_ID as Ud}from"@mysten/sui.js/utils";var ci=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let o=new jd;return o.moveCall({target:`${Ht.PackageId}::claim::claim`,typeArguments:[Ht.turbosCoinType],arguments:[o.object(Ht.Claim),o.object(Ud)]}),o}static fromData(t){return new a(t)}};import{TransactionBlock as qd}from"@mysten/sui.js/transactions";var li=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let o=new qd;return o.moveCall({target:`${Ht.PackageId}::claim::join`,typeArguments:[Ht.turbosCoinType],arguments:[o.object(Ht.Claim)]}),o}static fromData(t){return new a(t)}};import{TransactionBlock as Fd}from"@mysten/sui.js/transactions";import{TurbosSdk as Kd}from"turbos-clmm-sdk";var ui=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let o=new Kd(t.network.replace("sui:",""),t.suiClient),n=new Fd;return n=await o.pool.collectFee({txb:n,...this.data}),n=await o.pool.collectReward({txb:n,...this.data}),n=await o.pool.decreaseLiquidity({txb:n,...this.data}),n=await o.nft.burn({txb:n,nft:this.data.nft,pool:this.data.pool}),n}static fromData(t){return new a(t)}};import{TurbosSdk as Vd}from"turbos-clmm-sdk";var mi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(this.data,"this.data");let o=new Vd(t.network.replace("sui:",""),t.suiClient),{routes:n,coinTypeA:i,coinTypeB:c,address:l,amountA:d,amountB:S,slippage:w,amountSpecifiedIsInput:I,deadline:C,txb:x}=this.data;return o.trade.swap({routes:n,coinTypeA:i,coinTypeB:c,address:l,amountA:d,amountB:S,amountSpecifiedIsInput:I,slippage:w,deadline:C,txb:x})}static fromData(t){return new a(t)}};import{TurbosSdk as Hd}from"turbos-clmm-sdk";import{TransactionBlock as nl}from"@mysten/sui.js/transactions";import{normalizeSuiObjectId as ol}from"@mysten/sui.js/utils";import{unstable_getObjectId as $d}from"turbos-clmm-sdk";var rn=class{constructor(e){this.turbosSdk=e}async getCoinsData(e,t,o){let n=[],i;do i=await this.turbosSdk.provider.getCoins({owner:e,coinType:t,cursor:i?.nextCursor}),n.push(...i.data);while(i.hasNextPage);let c=[],l=0;return n.sort((d,S)=>Number(S.balance)-Number(d.balance)).some(d=>l>=o?!0:(l+=Number(d.balance),c.push(d),!1)),c}splitAndMergeCoin(e,t,o){if(!e||e.length<1)return[void 0,void 0];if(this.isSuiCoinAddress(e[0].coinType)){let[c]=o.splitCoins(o.gas,[o.pure(t)]);return[c,void 0]}let n=o.object(e[0].coinObjectId);e.length>1&&o.mergeCoins(n,e.slice(1).map(c=>o.object(c.coinObjectId)));let[i]=o.splitCoins(n,[o.pure(t)]);return[i,n]}isSuiCoinAddress(e){return e.toLocaleLowerCase()==="0x2::sui::sui"}async IsAccountCap(e){let t=await this.turbosSdk.provider.getOwnedObjects({owner:e,options:{showContent:!0,showType:!0,showOwner:!0},filter:{StructType:`${Xt.PackageId}::custodian_v2::AccountCap`}});return t.data[0]?.data?$d(t.data[0].data):void 0}createAccount(e){let[t]=e.moveCall({typeArguments:[],target:`${Xt.PackageId}::clob_v2::create_account`,arguments:[]});return t}zero(e,t){return t.moveCall({typeArguments:[e],target:"0x2::coin::zero",arguments:[]})}};var al=89,il=1e6,rl=async a=>{let{token1:e,token2:t,poolId:o,amountIn:n,currentAddress:i,turbosSdk:c}=a,l=new nl,d=new rn(c),S=await d.getCoinsData(i,t,n),[w,I]=d.splitAndMergeCoin(S,n,l);if(!w)throw new Error(`Not enough balance: ${t}`);let C=await d.IsAccountCap(i),x=C?l.object(C):d.createAccount(l),[v,R,K]=l.moveCall({typeArguments:[e,t],target:`${Xt.PackageId}::clob_v2::swap_exact_quote_for_base`,arguments:[l.object(String(o)),l.pure(al),x,l.pure(n),l.object(ol("0x6")),w]});return I&&l.transferObjects([I],l.pure(i)),l.transferObjects([v],l.pure(i)),l.transferObjects([R],l.pure(i)),C||l.transferObjects([x],l.pure(i)),l.setSenderIfNotSet(i),l.setGasBudget(il),l},sl=async a=>{let{token1:e,token2:t,poolId:o,amountIn:n,currentAddress:i,turbosSdk:c}=a,l=new nl,d=new rn(c),S=await d.getCoinsData(i,e,n),[w,I]=d.splitAndMergeCoin(S,n,l);if(!w)throw new Error(`Not enough balance: ${e}`);let C=await d.IsAccountCap(i),x=C?l.object(C):d.createAccount(l),v=d.zero(t,l),[R,K,V]=l.moveCall({typeArguments:[e,t],target:`${Xt.PackageId}::clob_v2::swap_exact_base_for_quote`,arguments:[l.object(String(o)),l.pure(al),x,l.pure(n),w,v,l.object(ol("0x6"))]});return I&&l.transferObjects([I],l.pure(i)),l.transferObjects([R],l.pure(i)),l.transferObjects([K],l.pure(i)),C||l.transferObjects([x],l.pure(i)),l.setSenderIfNotSet(i),l.setGasBudget(il),l};var pi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let o=new Hd(t.network.replace("sui:",""),t.suiClient);return await sl({...this.data,turbosSdk:o,currentAddress:t.account.address})}static fromData(t){return new a(t)}};import{TurbosSdk as Xd}from"turbos-clmm-sdk";var di=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let o=new Xd(t.network.replace("sui:",""),t.suiClient);return await rl({...this.data,turbosSdk:o,currentAddress:t.account.address})}static fromData(t){return new a(t)}};var fi=class{application="turbos";supportSDK="@mysten/sui.js";async deserialize(e){let t=new Qd(e.network.replace("sui:",""),e.suiClient),o=await t.contract.getConfig(),{transactionBlock:n,account:i}=e;console.log(e,"input");let l=await new ti(n,t,o).decode(i.address);return{txType:Gd.Other,txSubType:l.type,intentionData:l.intentionData}}async build(e){let{suiClient:t,account:o,network:n}=e,i;switch(console.log(e.intentionData,"intentionData"),e.txSubType){case"CreatePool":i=ii.fromData(e.intentionData);break;case"AddLiquidity":i=ei.fromData(e.intentionData);break;case"IncreaseLiquidity":i=si.fromData(e.intentionData);break;case"DecreaseLiquidity":i=ri.fromData(e.intentionData);break;case"RemoveLiquidity":i=ui.fromData(e.intentionData);break;case"CollectFee":i=oi.fromData(e.intentionData);break;case"CollectReward":i=ai.fromData(e.intentionData);break;case"Burn":i=ni.fromData(e.intentionData);break;case"Swap":i=mi.fromData(e.intentionData);break;case"PrixJoin":i=li.fromData(e.intentionData);break;case"PrixClaim":i=ci.fromData(e.intentionData);break;case"SwapExactBaseForQuote":i=pi.fromData(e.intentionData);break;case"SwapExactQuoteForBase":i=di.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:o,network:n})}};import{TransactionType as nf}from"@msafe/sui3-utils";import{TransactionType as Kr}from"@msafe/sui3-utils";import{bcs as cl}from"@mysten/sui.js/bcs";import{normalizeStructTag as Yd,normalizeSuiAddress as sn}from"@mysten/sui.js/utils";var zd={packageId:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",poolObjectId:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",metadataObjectId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",systemStateObjectId:"0x0000000000000000000000000000000000000000000000000000000000000005",certType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",gasBudget:5e7},Dt=zd;var hi=class{constructor(e){this.txb=e}decode(){if(console.log("txb",this.txb),this.isStakeTransaction())return this.decodeStake();if(this.isUnStakeTransaction())return this.decodeUnStake();if(this.isClaimTicketTransaction())return this.decodeClaimTicket();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(e){return this.transactions.find(t=>t.kind==="MoveCall"&&t.target===e)}isStakeTransaction(){return!!this.getMoveCallTransaction(`${Dt.packageId}::native_pool::stake`)}isUnStakeTransaction(){return!!this.getMoveCallTransaction(`${Dt.packageId}::native_pool::unstake`)}isClaimTicketTransaction(){return!!this.getMoveCallTransaction(`${Dt.packageId}::native_pool::burn_ticket`)}decodeStake(){let e=this.transactions[0].amounts[0].value.toNumber();return{txType:Kr.Other,type:"Stake",intentionData:{amount:e}}}decodeUnStake(){let t=this.transactions.find(o=>o.kind==="SplitCoins").amounts[0].value.toNumber();return{txType:Kr.Other,type:"UnStake",intentionData:{amount:t}}}decodeClaimTicket(){let e=this.helper.decodeOwnedObjectId(2);return console.log(e),{txType:Kr.Other,type:"ClaimTicket",intentionData:{ticketId:e}}}get helper(){let e=this.transactions.find(t=>t.kind==="MoveCall"&&t.target.startsWith(Dt.packageId));return new Vr(e,this.txb)}},Vr=class a{constructor(e,t){this.moveCall=e;this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return a.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return a.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return sn(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let o=this.getInputParam(e);return a.getPureInputValue(o,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let o=e.value.Pure;return cl.de(t,new Uint8Array(o))}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 sn(e.value.Object.ImmOrOwned.objectId)}return sn(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return sn(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return sn(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let o=e.value.Pure;return cl.de(t,new Uint8Array(o))}typeArg(e){return Yd(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};import{TransactionBlock as Zd}from"@mysten/sui.js/transactions";var gi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let o=new Zd,{ticketId:n}=this.data;return o.moveCall({target:`${Dt.packageId}::native_pool::burn_ticket`,arguments:[o.object(Dt.poolObjectId),o.object(Dt.systemStateObjectId),o.object(n)]}),o}static fromData(t){return new a(t)}};import{TransactionBlock as tf}from"@mysten/sui.js/transactions";var yi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let o=new tf,{amount:n}=this.data,[i]=o.splitCoins(o.gas,[o.pure(n)]);return o.moveCall({target:`${Dt.packageId}::native_pool::stake`,arguments:[o.object(Dt.poolObjectId),o.object(Dt.metadataObjectId),o.object(Dt.systemStateObjectId),i]}),o}static fromData(t){return new a(t)}};import{TransactionBlock as ef}from"@mysten/sui.js/transactions";var bi=class a extends P{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){console.log(t);let o=new ef,{amount:n}=this.data,i=(await t.suiClient.getAllCoins({owner:t.account.address,limit:100})).data,[c,...l]=i.filter(w=>w.coinType.split("::")[0]===Dt.certType.split("::")[0]),d=o.object(c.coinObjectId);l.length&&o.mergeCoins(d,l.map(w=>o.object(w.coinObjectId)));let S=o.splitCoins(o.object(c.coinObjectId),[o.pure(n)]);return o.moveCall({target:`${Dt.packageId}::native_pool::unstake`,arguments:[o.object(Dt.poolObjectId),o.object(Dt.metadataObjectId),o.object(Dt.systemStateObjectId),S]}),o}static fromData(t){return new a(t)}};var Si=class{application="volo";supportSDK="@mysten/sui.js";async deserialize(e){let{transactionBlock:t}=e,n=new hi(t).decode();return{txType:nf.Other,txSubType:n.type,intentionData:n.intentionData}}async build(e){let{suiClient:t,account:o}=e,n;switch(e.txSubType){case"Stake":n=yi.fromData(e.intentionData);break;case"UnStake":n=bi.fromData(e.intentionData);break;case"ClaimTicket":n=gi.fromData(e.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:t,account:o})}};import{TransactionType as ff}from"@msafe/sui3-utils";import{asIntN as ll}from"@cetusprotocol/common-sdk";import{TransactionType as ge}from"@msafe/sui3-utils";import{fromBase64 as cn}from"@mysten/bcs";import{bcs as ln}from"@mysten/sui/bcs";var Ti=class{constructor(e){this.transaction=e}decode(){if(this.isOpenPositionTx())return this.decodeOpenPositionTx();if(this.isClosePositionTx())return this.decodeClosePositionTx();if(this.isProvideLiquidityTx())return this.decodeProvideLiquidityTx();if(this.isRemoveLiquidityTx())return this.decodeRemoveLiquidityTx();if(this.isCollectRewardsAndFeeTx())return this.decodeCollectRewardsAndFeeTx();if(this.isCollectRewardsTx())return this.decodeCollectRewardsTx();if(this.isCollectFeeTx())return this.decodeCollectFeeTx();throw new Error("Unknown transaction type")}decodeOpenPositionTx(){let e=this.getMoveCallCommand("open_position"),t=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:ge.Other,type:"OpenPosition",intentionData:{pool:this.getSharedObjectID(this.getInputIndex(e,1)),lowerTick:Number(ll(BigInt(this.getU32(this.getInputIndex(e,2)))).toString()),upperTick:Number(ll(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:ge.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(o=>o.rewardCoinType),collectFeeTokens:this.getTypeArguments(e)}}}decodeProvideLiquidityTx(){let e=this.getMoveCallCommand("provide_liquidity_with_fixed_amount");return{txType:ge.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:ge.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:ge.Other,type:"CollectRewards",intentionData:{pool:e[0].pool,position:e[0].position,collectRewardTokens:e.map(t=>t.rewardCoinType)}}}decodeCollectFeeTx(){return{txType:ge.Other,type:"CollectFee",intentionData:this.getFeeCallData()}}decodeCollectRewardsAndFeeTx(){let e=this.getFeeCallData();return{txType:ge.Other,type:"CollectRewardsAndFee",intentionData:{pool:e.pool,position:e.position,...this.collectTokens()}}}getFeeCallData(){let e=this.getMoveCallCommand("collect_fee");return{pool:this.getSharedObjectID(this.getInputIndex(e,2)),position:this.getOwnedObjectID(this.getInputIndex(e,3)),collectFeeTokens:this.getTypeArguments(e)}}getCollectRewardCallData(){let e=[];return this.commands.forEach(t=>{t.$kind==="MoveCall"&&t.MoveCall.function==="collect_reward"&&e.push({pool:this.getSharedObjectID(this.getInputIndex(t,2)),position:this.getOwnedObjectID(this.getInputIndex(t,3)),rewardCoinType:this.getTypeArguments(t)[2]})}),e}collectTokens(){let e=this.getFeeCallData(),t=this.getCollectRewardCallData();return{collectFeeTokens:e.collectFeeTokens,collectRewardTokens:t.map(o=>o.rewardCoinType)}}get commands(){return this.transaction.getData().commands}get inputs(){return this.transaction.getData().inputs}isOpenPositionTx(){return!!this.getMoveCallCommand("open_position")}isProvideLiquidityTx(){return!!this.getMoveCallCommand("provide_liquidity_with_fixed_amount")}isRemoveLiquidityTx(){return!!this.getMoveCallCommand("remove_liquidity")}isCollectRewardsTx(){return!!this.getMoveCallCommand("collect_reward")}isCollectFeeTx(){return!!this.getMoveCallCommand("collect_fee")}isCollectRewardsAndFeeTx(){return this.isCollectRewardsTx()&&this.isCollectFeeTx()}isClosePositionTx(){return!!this.getMoveCallCommand("close_position")}getMoveCallCommand(e){return this.commands.find(t=>t.$kind==="MoveCall"&&t.MoveCall.function===e)}getSharedObjectID(e){return this.inputs[e].Object.SharedObject.objectId}getOwnedObjectID(e){return this.inputs[e].Object.ImmOrOwnedObject.objectId}getU32(e){return String(ln.u32().parse(Uint8Array.from(cn(this.inputs[e].Pure.bytes))))}getU64(e){return ln.u64().parse(Uint8Array.from(cn(this.inputs[e].Pure.bytes)))}getU128(e){return ln.u128().parse(Uint8Array.from(cn(this.inputs[e].Pure.bytes)))}getBoolean(e){return ln.bool().parse(Uint8Array.from(cn(this.inputs[e].Pure.bytes)))}getAddress(e){return ln.Address.parse(Uint8Array.from(cn(this.inputs[e].Pure.bytes)))}getTypeArguments(e){return e.MoveCall.typeArguments||[]}getInputIndex(e,t){return e.MoveCall.arguments[t].Input}};import{TransactionType as sf}from"@msafe/sui3-utils";import{BN as ye,ClmmPoolUtil as rf}from"@firefly-exchange/library-sui";import{SuiClient as of}from"@firefly-exchange/library-sui";import{OnChainCalls as af}from"@firefly-exchange/library-sui/dist/src/spot";var ul={rpc:"https://fullnode.mainnet.sui.io/",objects:{GlobalConfig:"0x03db251ba509a8d5d8777b6338836082335d93eecbdd09a11e190a1cff51c352",BasePackage:"0x3492c874c1e3b3e2984e8c41b589e642d4d0a5d6459e5a9cfc2d52fd7c89c267",CurrentPackage:"0x67b34b728c4e28e704dcfecf7c5cf55c7fc593b6c65c20d1836d97c209c1928a"}},ue=(a,e)=>{if(a!=="sui:mainnet")throw new Error("Bluefin spot protocol is only available on sui::mainnet");let t=new of({url:ul.rpc});return new af(t,ul.objects,{address:e.address,isUIWallet:!1})};var Rt=class{static async OpenPosition(e,t,o){let n=ue(o,t),i=await n.queryChain.getPool(e.pool),c=this.prototype.buildLiqInput(i,{...e,slippage:0});return await n.openPositionWithFixedAmount(i,e.lowerTick,e.upperTick,c,{returnTx:!0,sender:t.address})}static async provideLiquidity(e,t,o){let n=ue(o,t),i=await n.queryChain.getPool(e.pool),c=this.prototype.buildLiqInput(i,e);return await n.provideLiquidityWithFixedAmount(i,e.position,c,{returnTx:!0,sender:t.address})}static async removeLiquidity(e,t,o){let n=ue(o,t),i=await n.queryChain.getPool(e.pool);return await n.removeLiquidity(i,e.position,{liquidityAmount:new ye(e.liquidity),tokenMaxA:new ye(e.maxAmountTokenA),tokenMaxB:new ye(e.maxAmountTokenB)},{returnTx:!0,sender:t.address})}static async closePosition(e,t,o){let n=ue(o,t),i=await n.queryChain.getPool(e.pool);return await n.closePosition(i,e.position,{returnTx:!0,sender:t.address})}static async collectRewards(e,t,o){let n=ue(o,t),i=await n.queryChain.getPool(e.pool);return await n.collectRewards(i,e.position,{rewardCoinsType:e.collectRewardTokens,returnTx:!0,sender:t.address})}static async collectFee(e,t,o){let n=ue(o,t),i=await n.queryChain.getPool(e.pool);return await n.collectFee(i,e.position,{returnTx:!0,sender:t.address})}static async collectRewardsAndFee(e,t,o){let n=ue(o,t),i=await n.queryChain.getPool(e.pool);return console.log(e.position),await n.collectFeeAndRewards(i,e.position,{returnTx:!0,sender:t.address})}buildLiqInput(e,t){return{...rf.estLiquidityAndCoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new ye(t.tokenAmount),t.isTokenAFixed,!0,0,new ye(e.current_sqrt_price)),tokenMaxA:new ye(t.maxAmountTokenA),tokenMaxB:new ye(t.maxAmountTokenB)}}};var wi=class a extends k{constructor(t){super(t);this.data=t}txType=sf.Other;txSubType="ClosePosition";async build(t){let{account:o,network:n}=t;return console.log(this.data),Rt.closePosition(this.data,o,n)}static fromData(t){return new a(t)}};import{TransactionType as cf}from"@msafe/sui3-utils";var Ii=class a extends k{constructor(t){super(t);this.data=t}txType=cf.Other;txSubType="CollectFee";async build(t){let{account:o,network:n}=t;return console.log(this.data),Rt.collectFee(this.data,o,n)}static fromData(t){return new a(t)}};import{TransactionType as lf}from"@msafe/sui3-utils";var Ci=class a extends k{constructor(t){super(t);this.data=t}txType=lf.Other;txSubType="CollectRewards";async build(t){let{account:o,network:n}=t;return console.log(this.data),Rt.collectRewards(this.data,o,n)}static fromData(t){return new a(t)}};import{TransactionType as uf}from"@msafe/sui3-utils";var ki=class a extends k{constructor(t){super(t);this.data=t}txType=uf.Other;txSubType="CollectRewardsAndFee";async build(t){let{account:o,network:n}=t;return console.log(this.data),Rt.collectRewardsAndFee(this.data,o,n)}static fromData(t){return new a(t)}};import{TransactionType as mf}from"@msafe/sui3-utils";var xi=class a extends k{constructor(t){super(t);this.data=t}txType=mf.Other;txSubType="OpenPosition";async build(t){let{account:o,network:n}=t;return console.log(this.data),Rt.OpenPosition(this.data,o,n)}static fromData(t){return new a(t)}};import{TransactionType as pf}from"@msafe/sui3-utils";var vi=class a extends k{constructor(t){super(t);this.data=t}txType=pf.Other;txSubType="ProvideLiquidity";async build(t){let{account:o,network:n}=t;return console.log(this.data),Rt.provideLiquidity(this.data,o,n)}static fromData(t){return new a(t)}};import{TransactionType as df}from"@msafe/sui3-utils";var Di=class a extends k{constructor(t){super(t);this.data=t}txType=df.Other;txSubType="RemoveLiquidity";async build(t){let{account:o,network:n}=t;return console.log(this.data),Rt.removeLiquidity(this.data,o,n)}static fromData(t){return new a(t)}};var Ai=class{application="bluefin";supportSDK="@mysten/sui";async deserialize(e){console.log("Bluefin helper deserialize input: ",e);let{transaction:t}=e,n=new Ti(t).decode();return{txType:ff.Other,txSubType:n.type,intentionData:n.intentionData}}async build(e){let{suiClient:t,account:o,network:n}=e;console.log(e.txSubType);let i;switch(e.txSubType){case"OpenPosition":i=xi.fromData(e.intentionData);break;case"ProvideLiquidity":i=vi.fromData(e.intentionData);break;case"RemoveLiquidity":i=Di.fromData(e.intentionData);break;case"ClosePosition":i=wi.fromData(e.intentionData);break;case"CollectFee":i=Ii.fromData(e.intentionData);break;case"CollectRewards":i=Ci.fromData(e.intentionData);break;case"CollectRewardsAndFee":i=ki.fromData(e.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:t,account:o,network:n})}};import{TransactionType as Wf}from"@msafe/sui3-utils";import{MmtSDK as If}from"@mmt-finance/clmm-sdk";import{Transaction as Cf}from"@mysten/sui/transactions";var B=Bl(pl());import{convertI32ToSigned as Hr,TickMath as dl}from"@mmt-finance/clmm-sdk/dist/utils/math/tickMath";var hf="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",be=a=>a!=="0x2::sui::SUI"?a:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",gf=async({suiClient:a,address:e,type:t})=>{let o,n=[],i=0;do{try{let c=await a.getCoins({owner:e,coinType:t,cursor:o,limit:50});n=n.concat(c.data),o=c.nextCursor,(!c.hasNextPage||i===8)&&(o=null)}catch(c){console.log(c),o=null}i++}while(o!==null);return n},yf=(a,e)=>{let t=[],o=BigInt(0);for(let n of e)o<a&&!t.includes(n.objectId)&&(t.push(n.objectId),o+=BigInt(n.balance)),n.balance===BigInt(0)&&!t.includes(n.objectId)&&t.push(n.objectId);if(o>=a)return t;throw new Error("Insufficient balance")},bf=(a,e,t,o)=>{if(a===hf){let[n]=o.splitCoins(o.gas,[o.pure.u64(t)]);return n}else{let n=yf(t,e);n.length>1&&o.mergeCoins(o.object(n[0]),n.slice(1).map(c=>o.object(c)));let[i]=o.splitCoins(o.object(n[0]),[o.pure.u64(t)]);return i}};async function Oi(a,e,t,o,n){let i=await gf({suiClient:a.rpcClient,address:e,type:t});return bf(be(t),i.map(l=>({balance:BigInt(l.balance),objectId:l.coinObjectId})),o,n)}function N(a,e,t){let o=a.toTwos(t).shrn(e);return o.imaskn(t-e+1),o.fromTwos(t-e)}function Sf(a){let e;return a&1?e=new B.default("79232123823359799118286999567"):e=new B.default("79228162514264337593543950336"),a&2&&(e=N(e.mul(new B.default("79236085330515764027303304731")),96,256)),a&4&&(e=N(e.mul(new B.default("79244008939048815603706035061")),96,256)),a&8&&(e=N(e.mul(new B.default("79259858533276714757314932305")),96,256)),a&16&&(e=N(e.mul(new B.default("79291567232598584799939703904")),96,256)),a&32&&(e=N(e.mul(new B.default("79355022692464371645785046466")),96,256)),a&64&&(e=N(e.mul(new B.default("79482085999252804386437311141")),96,256)),a&128&&(e=N(e.mul(new B.default("79736823300114093921829183326")),96,256)),a&256&&(e=N(e.mul(new B.default("80248749790819932309965073892")),96,256)),a&512&&(e=N(e.mul(new B.default("81282483887344747381513967011")),96,256)),a&1024&&(e=N(e.mul(new B.default("83390072131320151908154831281")),96,256)),a&2048&&(e=N(e.mul(new B.default("87770609709833776024991924138")),96,256)),a&4096&&(e=N(e.mul(new B.default("97234110755111693312479820773")),96,256)),a&8192&&(e=N(e.mul(new B.default("119332217159966728226237229890")),96,256)),a&16384&&(e=N(e.mul(new B.default("179736315981702064433883588727")),96,256)),a&32768&&(e=N(e.mul(new B.default("407748233172238350107850275304")),96,256)),a&65536&&(e=N(e.mul(new B.default("2098478828474011932436660412517")),96,256)),a&131072&&(e=N(e.mul(new B.default("55581415166113811149459800483533")),96,256)),a&262144&&(e=N(e.mul(new B.default("38992368544603139932233054999993551")),96,256)),N(e,32,256)}function Tf(a){let e=Math.abs(a),t;return e&1?t=new B.default("18445821805675392311"):t=new B.default("18446744073709551616"),e&2&&(t=N(t.mul(new B.default("18444899583751176498")),64,256)),e&4&&(t=N(t.mul(new B.default("18443055278223354162")),64,256)),e&8&&(t=N(t.mul(new B.default("18439367220385604838")),64,256)),e&16&&(t=N(t.mul(new B.default("18431993317065449817")),64,256)),e&32&&(t=N(t.mul(new B.default("18417254355718160513")),64,256)),e&64&&(t=N(t.mul(new B.default("18387811781193591352")),64,256)),e&128&&(t=N(t.mul(new B.default("18329067761203520168")),64,256)),e&256&&(t=N(t.mul(new B.default("18212142134806087854")),64,256)),e&512&&(t=N(t.mul(new B.default("17980523815641551639")),64,256)),e&1024&&(t=N(t.mul(new B.default("17526086738831147013")),64,256)),e&2048&&(t=N(t.mul(new B.default("16651378430235024244")),64,256)),e&4096&&(t=N(t.mul(new B.default("15030750278693429944")),64,256)),e&8192&&(t=N(t.mul(new B.default("12247334978882834399")),64,256)),e&16384&&(t=N(t.mul(new B.default("8131365268884726200")),64,256)),e&32768&&(t=N(t.mul(new B.default("3584323654723342297")),64,256)),e&65536&&(t=N(t.mul(new B.default("696457651847595233")),64,256)),e&131072&&(t=N(t.mul(new B.default("26294789957452057")),64,256)),e&262144&&(t=N(t.mul(new B.default("37481735321082")),64,256)),t}var fl=(a,e,t)=>{let o=Hr(t?a+a%(e??1):a-a%(e??1));return o>0?new B.default(Sf(o)):new B.default(Tf(o))};function gl(a,e){if(!/^(\d+)(\.\d+)?$/.test(a))return BigInt(0);let[t,o=""]=a.split("."),n=(o+"0".repeat(e)).slice(0,e),c=(t+n).replace(/^0+/,"")||"0";return BigInt(c)}async function Xr({address:a,coinType:e,coinAmount:t,coinDecimals:o,tx:n,mmt:i}){let c=gl(t,o),l;return Number(t)?l=await Oi(i,a,be(e),c,n):[l]=n.moveCall({target:"0x2::coin::zero",typeArguments:[e],arguments:[]}),l}function yl({mmt:a,tx:e,poolModel:t,selectedLowTick:o,selectedHighTick:n}){let i=fl(Hr(o),t.tickSpacing),c=fl(Hr(n),t.tickSpacing);return a.Position.openPosition(e,t,i.toString(),c.toString())}var wf=(a,e)=>a*BigInt(100-e)/BigInt(100);function hl(a,e,t){let o=gl(a,e);return Number(a)===0?BigInt(0):wf(o,t)}async function Gr({poolId:a,currentSqrtPrice:e,tokenX:t,tokenY:o,slippagePercentage:n,isTokenX:i,suiClient:c}){let d=(await c.getObject({id:a,options:{showContent:!0}}))?.data?.content?.fields?.sqrt_price??e,S=dl.sqrtPriceX64ToPrice(new B.default(d?.toString()),t.decimals,o.decimals),w=i?(100-n)/100:(100+n)/100,I=dl.priceToSqrtPriceX64(S.mul(w),t.decimals,o.decimals);return BigInt(I.toString())}var bl=async(a,e,t,o,n,i,c,l,d,S)=>{let w=await Xr({mmt:a,address:t,coinType:i.tokenX.coinType,coinAmount:o,coinDecimals:i.tokenX.decimals,tx:e}),I=await Xr({mmt:a,address:t,coinType:i.tokenY.coinType,coinAmount:n,coinDecimals:i.tokenY.decimals,tx:e}),C={objectId:c,tokenXType:i.tokenXType,tokenYType:i.tokenYType,tickSpacing:i.tickSpacing},x=yl({mmt:a,tx:e,poolModel:C,selectedLowTick:l,selectedHighTick:d}),v=hl(o,i.tokenX.decimals,S),R=hl(n,i.tokenY.decimals,S);a.Pool.addLiquidity(e,C,x,w,I,v,R,t),e.transferObjects([x],e.pure.address(t))},Sl=async(a,e,t,o,n,i,c,l,d,S,w)=>{try{let I=await Xr({mmt:a,address:o,coinType:i?c.tokenX.coinType:c.tokenY.coinType,coinAmount:n,coinDecimals:i?c.tokenX.decimals:c.tokenY.decimals,tx:e}),C={objectId:c.objectId,tokenXType:c.tokenX.coinType,tokenYType:c.tokenY.coinType,tickSpacing:c.tickSpacing},x=yl({mmt:a,tx:e,poolModel:C,selectedLowTick:l,selectedHighTick:d}),v=await Gr({suiClient:t,poolId:c.poolId,currentSqrtPrice:c.currentSqrtPrice,tokenX:c.tokenX,tokenY:c.tokenY,slippagePercentage:S,isTokenX:i});await a.Pool.addLiquiditySingleSidedV2({txb:e,poolModel:C,position:C.objectId,inputCoin:I,isXtoY:i,limitSqrtPrice:v,slippagePercentage:w,transferToAddress:o}),e.transferObjects([x],e.pure.address(o))}catch(I){console.error(I)}};var Mi=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=If.NEW({network:"mainnet"}),{params:o}=this.data,{address:n,amountA:i,amountB:c,pool:l,selectedLowTick:d,selectedHighTick:S,slippage:w}=o,I=new Cf;return await bl(t,I,n,i,c,l,l.objectId,d,S,w),I}static fromData(t){return new a(t)}};import{MmtSDK as kf}from"@mmt-finance/clmm-sdk";import{Transaction as xf}from"@mysten/sui/transactions";var Pi=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=kf.NEW({network:"mainnet"}),{params:o}=this.data,{address:n,amount:i,isTokenX:c,pool:l,selectedLowTick:d,selectedHighTick:S,swapSlippage:w,addLiquiditySlippage:I}=o,C=new xf;return await Sl(t,C,t.rpcClient,n,i,c,l,d,S,w,I),C}static fromData(t){return new a(t)}};import{MmtSDK as vf}from"@mmt-finance/clmm-sdk";import{Transaction as Df}from"@mysten/sui/transactions";var Ee=(a,e,t,o,n)=>{let i={objectId:o.objectId,tokenXType:o.tokenXType,tokenYType:o.tokenYType};(o?.rewarders?.length??0)>0&&a.Pool.collectAllRewards(n,i,o.rewarders,t.objectId,e),a.Pool.collectFee(n,o,t.objectId,e)};var Ri=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=vf.NEW({network:"mainnet"}),{params:o}=this.data,{address:n,positions:i,pools:c}=o,l=new Df;for(let d of i){let S=c.find(w=>w.objectId===d.poolId);Ee(t,n,d,S,l)}return l}static fromData(t){return new a(t)}};import{MmtSDK as Af}from"@mmt-finance/clmm-sdk";import{Transaction as Of}from"@mysten/sui/transactions";var Bi=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=Af.NEW({network:"mainnet"}),{params:o}=this.data,{address:n,position:i,pool:c}=o,l=new Of;return Ee(t,n,i,c,l),l}static fromData(t){return new a(t)}};import{MmtSDK as Mf}from"@mmt-finance/clmm-sdk";import{Transaction as Pf}from"@mysten/sui/transactions";import Rf from"bignumber.js";var Ei=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=Mf.NEW({network:"mainnet"}),{params:o}=this.data,{pool:n,position:i,address:c,withdrawPercentage:l}=o,d=new Pf,S=n.tokenX.coinType,w=n.tokenY.coinType,I={objectId:n.objectId,tokenXType:S,tokenYType:w},C=BigInt(l===100?i.liquidity:new Rf(i.liquidity).multipliedBy(l/100).toFixed(0));return t.Pool.removeLiquidity(d,I,i.objectId,C,BigInt(0),BigInt(0),c),Ee(t,c,i,n,d),l===100&&t.Position.closePosition(d,i.objectId),d}static fromData(t){return new a(t)}};import{Transaction as Tl}from"@mysten/sui/transactions";import{LstClient as wl}from"@suilend/springsui-sdk";var Qr={id:"0x0431232199873db77a92aa645cd43521437e9cc5c6fff07fd03edb88afe0b25a",type:"0x2b6602099970374cf58a2a1b9d96f005fccceb81e92eb059873baf420eb6c717::x_sui::X_SUI",weightHookId:"0x9e35c13dbb0bc437e8ad5a95ec463622f58763e060552ae8d100db77f4904601"},Il=async(a,e,t)=>{let o=await wl.initialize(a,Qr),n=new Tl,[i]=n.splitCoins(n.gas,[BigInt(t)]),c=o.mint(n,i);return n.transferObjects([c],e),n},Cl=async(a,e,t)=>{let o=await wl.initialize(a,Qr),n=await a.getCoins({owner:e,coinType:Qr.type,limit:1e3});if(n.data.length===0)throw new Error("No lst coins found");let i=new Tl,c=n.data[0];n.data.length>1&&i.mergeCoins(c.coinObjectId,n.data.slice(1).map(S=>S.coinObjectId));let[l]=i.splitCoins(c.coinObjectId,[BigInt(t)]),d=o.redeem(i,l);return i.transferObjects([d],e),i};var Ni=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{params:o}=this.data,{address:n,amount:i}=o;return await Il(t.suiClient,n,i)}static fromData(t){return new a(t)}};import{MmtSDK as Ef}from"@mmt-finance/clmm-sdk";import{Transaction as Nf}from"@mysten/sui/transactions";import{mappedMmtV3Pool as Bf}from"@mmt-finance/clmm-sdk/dist/utils/poolUtils";var kl=async(a,e,t,o,n,i,c)=>{let l=BigInt(Math.ceil(Number(o)*10**t.decimals)),d=await Oi(a,n,be(t.coinType),l,i),S=t.coinType;for(let w=0;w<e.length;w+=1){let{objectId:I,tokenX:C,tokenY:x,isStable:v}=e[w],{id:R,isReverse:K}=Bf[I]||{id:I,isReverse:!1},V=be(C.coinType)===be(S);V=K?!V:V;let Vt=K?x.coinType:C.coinType,Et=K?C.coinType:x.coinType,Pt=await Gr({poolId:R,tokenX:C,tokenY:x,slippagePercentage:c,isTokenX:V,suiClient:a.rpcClient}),Ne=a.Pool.swap(i,{objectId:R,tokenXType:Vt,tokenYType:Et,isStable:v},l,d,V,Pt.toString());i.transferObjects([d],i.pure.address(n)),d=Ne,S=V?Et:Vt,[l]=i.moveCall({target:"0x2::coin::value",typeArguments:[S],arguments:[d]})}i.transferObjects([d],i.pure.address(n))};var Wi=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(){let t=Ef.NEW({network:"mainnet"}),{params:o}=this.data,{route:n,tokenIn:i,amountIn:c,address:l,slippage:d}=o,S=new Nf;return await kl(t,n,i,c,l,S,d),S}static fromData(t){return new a(t)}};var _i=class a extends k{constructor(t){super(t);this.data=t}txType;txSubType;async build(t){let{params:o}=this.data,{address:n,amount:i}=o;return await Cl(t.suiClient,n,i)}static fromData(t){return new a(t)}};var Li=class{application="mmt-dex";supportSDK="@mysten/sui";async deserialize(e){let{appContext:t}=e;return{txType:Wf.Other,txSubType:t.action,intentionData:t}}async build(e){let t;switch(e.txSubType){case"Swap":t=Wi.fromData(e.intentionData);break;case"AddLiquidity":t=Mi.fromData(e.intentionData);break;case"AddLiquiditySingleSide":t=Pi.fromData(e.intentionData);break;case"ClaimRewards":t=Bi.fromData(e.intentionData);break;case"ClaimAllRewards":t=Ri.fromData(e.intentionData);break;case"RemoveLiquidity":t=Ei.fromData(e.intentionData);break;case"StakeXSui":t=Ni.fromData(e.intentionData);break;case"UnstakeXSui":t=_i.fromData(e.intentionData);break;default:throw new Error("not implemented")}return t.build({suiClient:e.suiClient})}};var EN=Zo.fromHelpers([new jo,new Qo,new Wo,new zo,new lo,new fi,new Li,new Ra,new Si,new _n,new Fa,new Qa,new Sn,new Ai,new Za]);export{EN as appHelpers};
2
2
  //# sourceMappingURL=index.mjs.map