this.d.length-2},nB.isNaN=function(){return!this.s},nB.isNegative=nB.isNeg=function(){return this.s<0},nB.isPositive=nB.isPos=function(){return this.s>0},nB.isZero=function(){return!!this.d&&0===this.d[0]},nB.lessThan=nB.lt=function(e){return 0>this.cmp(e)},nB.lessThanOrEqualTo=nB.lte=function(e){return 1>this.cmp(e)},nB.logarithm=nB.log=function(e){var t,n,r,i,o,a,s,u=this.constructor,l=u.precision,c=u.rounding;if(null==e)e=new u(10),t=!0;else{if(n=(e=new u(e)).d,e.s<0||!n||!n[0]||e.eq(1))return new u(NaN);t=e.eq(10)}if(n=this.d,this.s<0||!n||!n[0]||this.eq(1))return new u(n&&!n[0]?-1/0:1!=this.s?NaN:n?0:1/0);if(t){if(n.length>1)i=!0;else{for(r=n[0];r%10==0;)r/=10;i=1!==r}}if(nb=!1,nL((s=nD(nZ(this,a=l+5),t?nU(u,a+10):nZ(e,a),a,1)).d,r=l,c))do if(a+=10,s=nD(nZ(this,a),t?nU(u,a+10):nZ(e,a),a,1),!i){+nM(s.d).slice(r+1,r+15)+1==1e14&&(s=nF(s,l+1,0));break}while(nL(s.d,r+=10,c));return nb=!0,nF(s,l,c)},nB.minus=nB.sub=function(e){var t,n,r,i,o,a,s,u,l,c,d,p,f=this.constructor;if(e=new f(e),!this.d||!e.d)return this.s&&e.s?this.d?e.s=-e.s:e=new f(e.d||this.s!==e.s?this:NaN):e=new f(NaN),e;if(this.s!=e.s)return e.s=-e.s,this.plus(e);if(l=this.d,p=e.d,s=f.precision,u=f.rounding,!l[0]||!p[0]){if(p[0])e.s=-e.s;else{if(!l[0])return new f(3===u?-0:0);e=new f(this)}return nb?nF(e,s,u):e}if(n=nA(e.e/7),c=nA(this.e/7),l=l.slice(),o=c-n){for((d=o<0)?(t=l,o=-o,a=p.length):(t=p,n=c,a=l.length),r=Math.max(Math.ceil(s/7),a)+2,o>r&&(o=r,t.length=1),t.reverse(),r=o;r--;)t.push(0);t.reverse()}else{for((d=(r=l.length)<(a=p.length))&&(a=r),r=0;r0;--r)l[a++]=0;for(r=p.length;r>o;){if(l[--r](a=(o=Math.ceil(s/7))>a?o+1:a+1)&&(i=a,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for((a=l.length)-(i=c.length)<0&&(i=a,n=c,c=l,l=n),t=0;i;)t=(l[--i]=l[i]+c[i]+t)/1e7|0,l[i]%=1e7;for(t&&(l.unshift(t),++r),a=l.length;0==l[--a];)l.pop();return e.d=l,e.e=nj(l,r),nb?nF(e,s,u):e},nB.precision=nB.sd=function(e){var t;if(void 0!==e&&!!e!==e&&1!==e&&0!==e)throw Error(nv+e);return this.d?(t=nV(this.d),e&&this.e+1>t&&(t=this.e+1)):t=NaN,t},nB.round=function(){var e=this.constructor;return nF(new e(this),this.e+1,e.rounding)},nB.sine=nB.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+7,r.rounding=1,n=function(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:nQ(e,2,t,t);n=(n=1.4*Math.sqrt(r))>16?16:0|n,t=t.times(1/nJ(5,n)),t=nQ(e,2,t,t);for(var i,o=new e(5),a=new e(16),s=new e(20);n--;)i=t.times(t),t=t.times(o.plus(i.times(a.times(i).minus(s))));return t}(r,n0(r,n)),r.precision=e,r.rounding=t,nF(nf>2?n.neg():n,e,t,!0)):new r(NaN)},nB.squareRoot=nB.sqrt=function(){var e,t,n,r,i,o,a=this.d,s=this.e,u=this.s,l=this.constructor;if(1!==u||!a||!a[0])return new l(!u||u<0&&(!a||a[0])?NaN:a?this:1/0);for(nb=!1,0==(u=Math.sqrt(+this))||u==1/0?(((t=nM(a)).length+s)%2==0&&(t+="0"),u=Math.sqrt(t),s=nA((s+1)/2)-(s<0||s%2),t=u==1/0?"5e"+s:(t=u.toExponential()).slice(0,t.indexOf("e")+1)+s,r=new l(t)):r=new l(u.toString()),n=(s=l.precision)+3;;)if(r=(o=r).plus(nD(this,o,n+2,1)).times(.5),nM(o.d).slice(0,n)===(t=nM(r.d)).slice(0,n)){if("9999"!=(t=t.slice(n-3,n+1))&&(i||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(nF(r,s+1,1),e=!r.times(r).eq(this));break}if(!i&&(nF(o,s+1,0),o.times(o).eq(this))){r=o;break}n+=4,i=1}return nb=!0,nF(r,s,l.rounding,e)},nB.tangent=nB.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,(n=n.sin()).s=1,n=nD(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,nF(2==nf||4==nf?n.neg():n,e,t,!0)):new r(NaN)},nB.times=nB.mul=function(e){var t,n,r,i,o,a,s,u,l,c=this.constructor,d=this.d,p=(e=new c(e)).d;if(e.s*=this.s,!d||!d[0]||!p||!p[0])return new c(e.s&&(!d||d[0]||p)&&(!p||p[0]||d)?d&&p?0*e.s:e.s/0:NaN);for(n=nA(this.e/7)+nA(e.e/7),(u=d.length)<(l=p.length)&&(o=d,d=p,p=o,a=u,u=l,l=a),o=[],r=a=u+l;r--;)o.push(0);for(r=l;--r>=0;){for(t=0,i=u+r;i>r;)s=o[i]+p[r]*d[i-r-1]+t,o[i--]=s%1e7|0,t=s/1e7|0;o[i]=(o[i]+t)%1e7|0}for(;!o[--a];)o.pop();return t?++n:o.shift(),e.d=o,e.e=nj(o,n),nb?nF(e,c.precision,c.rounding):e},nB.toBinary=function(e,t){return n1(this,2,e,t)},nB.toDecimalPlaces=nB.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),void 0===e?n:(nR(e,0,1e9),void 0===t?t=r.rounding:nR(t,0,8),nF(n,e+n.e+1,t))},nB.toExponential=function(e,t){var n,r=this,i=r.constructor;return void 0===e?n=nq(r,!0):(nR(e,0,1e9),void 0===t?t=i.rounding:nR(t,0,8),n=nq(r=nF(new i(r),e+1,t),!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n},nB.toFixed=function(e,t){var n,r,i=this.constructor;return void 0===e?n=nq(this):(nR(e,0,1e9),void 0===t?t=i.rounding:nR(t,0,8),n=nq(r=nF(new i(this),e+this.e+1,t),!1,e+r.e+1)),this.isNeg()&&!this.isZero()?"-"+n:n},nB.toFraction=function(e){var t,n,r,i,o,a,s,u,l,c,d,p,f=this.d,h=this.constructor;if(!f)return new h(this);if(l=n=new h(1),r=u=new h(0),a=(o=(t=new h(r)).e=nV(f)-this.e-1)%7,t.d[0]=nS(10,a<0?7+a:a),null==e)e=o>0?t:l;else{if(!(s=new h(e)).isInt()||s.lt(l))throw Error(nv+s);e=s.gt(t)?o>0?t:l:s}for(nb=!1,s=new h(nM(f)),c=h.precision,h.precision=o=14*f.length;d=nD(s,t,0,1,1),1!=(i=n.plus(d.times(r))).cmp(e);)n=r,r=i,i=l,l=u.plus(d.times(i)),u=i,i=t,t=s.minus(d.times(i)),s=i;return i=nD(e.minus(n),r,0,1,1),u=u.plus(i.times(l)),n=n.plus(i.times(r)),u.s=l.s=this.s,p=1>nD(l,r,o,1).minus(this).abs().cmp(nD(u,n,o,1).minus(this).abs())?[l,r]:[u,n],h.precision=c,nb=!0,p},nB.toHexadecimal=nB.toHex=function(e,t){return n1(this,16,e,t)},nB.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),null==e){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),void 0===t?t=r.rounding:nR(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&(e.s=n.s),e}return e.d[0]?(nb=!1,n=nD(n,e,0,t,1).times(e),nb=!0,nF(n)):(e.s=n.s,n=e),n},nB.toNumber=function(){return+this},nB.toOctal=function(e,t){return n1(this,8,e,t)},nB.toPower=nB.pow=function(e){var t,n,r,i,o,a,s=this,u=s.constructor,l=+(e=new u(e));if(!s.d||!e.d||!s.d[0]||!e.d[0])return new u(nS(+s,l));if((s=new u(s)).eq(1))return s;if(r=u.precision,o=u.rounding,e.eq(1))return nF(s,r,o);if((t=nA(e.e/7))>=e.d.length-1&&(n=l<0?-l:l)<=9007199254740991)return i=n$(u,s,n,r),e.s<0?new u(1).div(i):nF(i,r,o);if((a=s.s)<0){if(tu.maxE+1||t0?a/0:0):(nb=!1,u.rounding=s.s=1,n=Math.min(12,(t+"").length),(i=nG(e.times(nZ(s,r+n)),r)).d&&nL((i=nF(i,r+5,1)).d,r,o)&&(t=r+10,+nM((i=nF(nG(e.times(nZ(s,t+n)),t),t+5,1)).d).slice(r+1,r+15)+1==1e14&&(i=nF(i,r+1,0))),i.s=a,nb=!0,u.rounding=o,nF(i,r,o))},nB.toPrecision=function(e,t){var n,r=this,i=r.constructor;return void 0===e?n=nq(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(nR(e,1,1e9),void 0===t?t=i.rounding:nR(t,0,8),n=nq(r=nF(new i(r),e,t),e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n},nB.toSignificantDigits=nB.toSD=function(e,t){var n=this.constructor;return void 0===e?(e=n.precision,t=n.rounding):(nR(e,1,1e9),void 0===t?t=n.rounding:nR(t,0,8)),nF(new n(this),e,t)},nB.toString=function(){var e=this.constructor,t=nq(this,this.e<=e.toExpNeg||this.e>=e.toExpPos);return this.isNeg()&&!this.isZero()?"-"+t:t},nB.truncated=nB.trunc=function(){return nF(new this.constructor(this),this.e+1,1)},nB.valueOf=nB.toJSON=function(){var e=this.constructor,t=nq(this,this.e<=e.toExpNeg||this.e>=e.toExpPos);return this.isNeg()?"-"+t:t};var nD=function(){function e(e,t,n){var r,i=0,o=e.length;for(e=e.slice();o--;)r=e[o]*t+i,e[o]=r%n|0,i=r/n|0;return i&&e.unshift(i),e}function t(e,t,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;it[i]?1:-1;break}return o}function n(e,t,n,r){for(var i=0;n--;)e[n]-=i,i=e[n]1;)e.shift()}return function(r,i,o,a,s,u){var l,c,d,p,f,h,m,g,y,b,_,v,w,k,x,A,S,I,T,E,P=r.constructor,C=r.s==i.s?1:-1,O=r.d,B=i.d;if(!O||!O[0]||!B||!B[0])return new P(r.s&&i.s&&(O?!B||O[0]!=B[0]:B)?O&&0==O[0]||!B?0*C:C/0:NaN);for(u?(f=1,c=r.e-i.e):(u=1e7,f=7,c=nA(r.e/f)-nA(i.e/f)),T=B.length,S=O.length,b=(y=new P(C)).d=[],d=0;B[d]==(O[d]||0);d++);if(B[d]>(O[d]||0)&&c--,null==o?(k=o=P.precision,a=P.rounding):k=s?o+(r.e-i.e)+1:o,k<0)b.push(1),h=!0;else{if(k=k/f+2|0,d=0,1==T){for(p=0,B=B[0],k++;(d1&&(B=e(B,p,u),O=e(O,p,u),T=B.length,S=O.length),A=T,v=(_=O.slice(0,T)).length;v=u/2&&++I;do p=0,(l=t(B,_,T,v))<0?(w=_[0],T!=v&&(w=w*u+(_[1]||0)),(p=w/I|0)>1?(p>=u&&(p=u-1),g=(m=e(B,p,u)).length,v=_.length,1==(l=t(m,_,g,v))&&(p--,n(m,T=10;p/=10)d++;y.e=d+c*f-1,nF(y,s?o+y.e+1:o,a,h)}return y}}();function nF(e,t,n,r){var i,o,a,s,u,l,c,d,p,f=e.constructor;e:if(null!=t){if(!(d=e.d))return e;for(i=1,s=d[0];s>=10;s/=10)i++;if((o=t-i)<0)o+=7,a=t,u=(c=d[p=0])/nS(10,i-a-1)%10|0;else if(p=Math.ceil((o+1)/7),s=d.length,p>=s){if(r){for(;s++<=p;)d.push(0);c=u=0,i=1,o%=7,a=o-7+1}else break e}else{for(c=s=d[p],i=1;s>=10;s/=10)i++;o%=7,u=(a=o-7+i)<0?0:c/nS(10,i-a-1)%10|0}if(r=r||t<0||void 0!==d[p+1]||(a<0?c:c%nS(10,i-a-1)),l=n<4?(u||r)&&(0==n||n==(e.s<0?3:2)):u>5||5==u&&(4==n||r||6==n&&(o>0?a>0?c/nS(10,i-a):0:d[p-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,l?(t-=e.e+1,d[0]=nS(10,(7-t%7)%7),e.e=-t||0):d[0]=e.e=0,e;if(0==o?(d.length=p,s=1,p--):(d.length=p+1,s=nS(10,7-o),d[p]=a>0?(c/nS(10,i-a)%nS(10,a)|0)*s:0),l)for(;;)if(0==p){for(o=1,a=d[0];a>=10;a/=10)o++;for(a=d[0]+=s,s=1;a>=10;a/=10)s++;o!=s&&(e.e++,1e7==d[0]&&(d[0]=1));break}else{if(d[p]+=s,1e7!=d[p])break;d[p--]=0,s=1}for(o=d.length;0===d[--o];)d.pop()}return nb&&(e.e>f.maxE?(e.d=null,e.e=NaN):e.e0?o=o.charAt(0)+"."+o.slice(1)+nW(r):a>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(e.e<0?"e":"e+")+e.e):i<0?(o="0."+nW(-i-1)+o,n&&(r=n-a)>0&&(o+=nW(r))):i>=a?(o+=nW(i+1-a),n&&(r=n-i-1)>0&&(o=o+"."+nW(r))):((r=i+1)0&&(i+1===a&&(o+="."),o+=nW(r))),o}function nj(e,t){var n=e[0];for(t*=7;n>=10;n/=10)t++;return t}function nU(e,t,n){if(t>nC)throw nb=!0,n&&(e.precision=n),Error(nw);return nF(new e(nm),t,1,!0)}function nz(e,t,n){if(t>nO)throw Error(nw);return nF(new e(ng),t,n,!0)}function nV(e){var t=e.length-1,n=7*t+1;if(t=e[t]){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}function nW(e){for(var t="";e--;)t+="0";return t}function n$(e,t,n,r){var i,o=new e(1),a=Math.ceil(r/7+4);for(nb=!1;;){if(n%2&&n2((o=o.times(t)).d,a)&&(i=!0),0===(n=nA(n/2))){n=o.d.length-1,i&&0===o.d[n]&&++o.d[n];break}n2((t=t.times(t)).d,a)}return nb=!0,o}function nK(e){return 1&e.d[e.d.length-1]}function nH(e,t,n){for(var r,i=new e(t[0]),o=0;++o17)return new p(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:0/0);for(null==t?(nb=!1,u=h):u=t,s=new p(.03125);e.e>-2;)e=e.times(s),d+=5;for(u+=r=Math.log(nS(2,d))/Math.LN10*2+5|0,n=o=a=new p(1),p.precision=u;;){if(o=nF(o.times(e),u,1),n=n.times(++c),nM((s=a.plus(nD(o,n,u,1))).d).slice(0,u)===nM(a.d).slice(0,u)){for(i=d;i--;)a=nF(a.times(a),u,1);if(null!=t)return p.precision=h,a;if(!(l<3&&nL(a.d,u-r,f,l)))return nF(a,p.precision=h,f,nb=!0);p.precision=u+=10,n=o=s=new p(1),c=0,l++}a=s}}function nZ(e,t){var n,r,i,o,a,s,u,l,c,d,p,f=1,h=e,m=h.d,g=h.constructor,y=g.rounding,b=g.precision;if(h.s<0||!m||!m[0]||!h.e&&1==m[0]&&1==m.length)return new g(m&&!m[0]?-1/0:1!=h.s?NaN:m?0:h);if(null==t?(nb=!1,c=b):c=t,g.precision=c+=10,r=(n=nM(m)).charAt(0),!(15e14>Math.abs(o=h.e)))return l=nU(g,c+2,b).times(o+""),h=nZ(new g(r+"."+n.slice(1)),c-10).plus(l),g.precision=b,null==t?nF(h,b,y,nb=!0):h;for(;r<7&&1!=r||1==r&&n.charAt(1)>3;)r=(n=nM((h=h.times(e)).d)).charAt(0),f++;for(o=h.e,r>1?(h=new g("0."+n),o++):h=new g(r+"."+n.slice(1)),d=h,u=a=h=nD(h.minus(1),h.plus(1),c,1),p=nF(h.times(h),c,1),i=3;;){if(a=nF(a.times(p),c,1),nM((l=u.plus(nD(a,new g(i),c,1))).d).slice(0,c)===nM(u.d).slice(0,c)){if(u=u.times(2),0!==o&&(u=u.plus(nU(g,c+2,b).times(o+""))),u=nD(u,new g(f),c,1),null!=t)return g.precision=b,u;if(!nL(u.d,c-10,y,s))return nF(u,g.precision=b,y,nb=!0);g.precision=c+=10,l=a=h=nD(d.minus(1),d.plus(1),c,1),p=nF(h.times(h),c,1),i=s=1}u=l,i+=2}}function nY(e){return String(e.s*e.s/0)}function nX(e,t){var n,r,i;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;48===t.charCodeAt(r);r++);for(i=t.length;48===t.charCodeAt(i-1);--i);if(t=t.slice(r,i)){if(i-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%7,n<0&&(r+=7),re.constructor.maxE?(e.d=null,e.e=NaN):e.e=0&&(c=c.replace(".",""),(p=new f(1)).e=c.length-a,p.d=nN(nq(p),10,i),p.e=p.d.length),o=u=(d=nN(c,10,i)).length;0==d[--u];)d.pop();if(d[0]){if(a<0?o--:((e=new f(e)).d=d,e.e=o,d=(e=nD(e,p,n,r,0,i)).d,o=e.e,l=np),a=d[n],s=i/2,l=l||void 0!==d[n+1],l=r<4?(void 0!==a||l)&&(0===r||r===(e.s<0?3:2)):a>s||a===s&&(4===r||l||6===r&&1&d[n-1]||r===(e.s<0?8:7)),d.length=n,l)for(;++d[--n]>i-1;)d[n]=0,n||(++o,d.unshift(1));for(u=d.length;!d[u-1];--u);for(a=0,c="";a1){if(16==t||8==t){for(a=16==t?4:3,--u;u%a;u++)c+="0";for(u=(d=nN(c,i,t)).length;!d[u-1];--u);for(a=1,c="1.";au)for(o-=u;o--;)c+="0";else ot)return e.length=t,!0}function n6(e){return new this(e).abs()}function n3(e){return new this(e).acos()}function n4(e){return new this(e).acosh()}function n5(e,t){return new this(e).plus(t)}function n8(e){return new this(e).asin()}function n9(e){return new this(e).asinh()}function n7(e){return new this(e).atan()}function re(e){return new this(e).atanh()}function rt(e,t){e=new this(e),t=new this(t);var n,r=this.precision,i=this.rounding,o=r+4;return e.s&&t.s?e.d||t.d?!t.d||e.isZero()?(n=t.s<0?nz(this,r,i):new this(0)).s=e.s:!e.d||t.isZero()?(n=nz(this,o,1).times(.5)).s=e.s:t.s<0?(this.precision=o,this.rounding=1,n=this.atan(nD(e,t,o,1)),t=nz(this,o,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(nD(e,t,o,1)):(n=nz(this,o,1).times(t.s>0?.25:.75)).s=e.s:n=new this(NaN),n}function rn(e){return new this(e).cbrt()}function rr(e){return nF(e=new this(e),e.e+1,2)}function ri(e,t,n){return new this(e).clamp(t,n)}function ro(e){if(!e||"object"!=typeof e)throw Error(n_+"Object expected");var t,n,r,i=!0===e.defaults,o=["precision",1,1e9,"rounding",0,8,"toExpNeg",-9e15,0,"toExpPos",0,9e15,"maxE",0,9e15,"minE",-9e15,0,"modulo",0,9];for(t=0;t=o[t+1]&&r<=o[t+2])this[n]=r;else throw Error(nv+n+": "+r)}if(n="crypto",i&&(this[n]=ny[n]),void 0!==(r=e[n])){if(!0===r||!1===r||0===r||1===r){if(r){if("u">typeof crypto&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[n]=!0;else throw Error(nk)}else this[n]=!1}else throw Error(nv+n+": "+r)}return this}function ra(e){return new this(e).cos()}function rs(e){return new this(e).cosh()}function ru(e,t){return new this(e).div(t)}function rl(e){return new this(e).exp()}function rc(e){return nF(e=new this(e),e.e+1,3)}function rd(){var e,t,n=new this(0);for(nb=!1,e=0;e=429e7?t[o]=crypto.getRandomValues(new Uint32Array(1))[0]:s[o++]=i%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);o=214e7?crypto.randomBytes(4).copy(t,o):(s.push(i%1e7),o+=4);o=r/4}else throw Error(nk)}else for(;o=10;i/=10)r++;r<7&&(n-=7-r)}return a.e=n,a.d=s,a}function rx(e){return nF(e=new this(e),e.e+1,this.rounding)}function rA(e){return(e=new this(e)).d?e.d[0]?e.s:0*e.s:e.s||NaN}function rS(e){return new this(e).sin()}function rI(e){return new this(e).sinh()}function rT(e){return new this(e).sqrt()}function rE(e,t){return new this(e).sub(t)}function rP(){var e=0,t=arguments,n=new this(t[e]);for(nb=!1;n.s&&++eo.maxE?(i.e=NaN,i.d=null):e.e=10;n/=10)t++;nb?t>o.maxE?(i.e=NaN,i.d=null):t-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),nP.test(t))return nX(e,t)}else if("Infinity"===t||"NaN"===t)return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(nT.test(t))n=16,t=t.toLowerCase();else if(nI.test(t))n=2;else if(nE.test(t))n=8;else throw Error(nv+t);for((o=t.search(/p/i))>0?(u=+t.slice(o+1),t=t.substring(2,o)):t=t.slice(2),a=(o=t.indexOf("."))>=0,r=e.constructor,a&&(o=(s=(t=t.replace(".","")).length)-o,i=n$(r,new r(n),o,2*o)),o=c=(l=nN(t,n,1e7)).length-1;0===l[o];--o)l.pop();return o<0?new r(0*e.s):(e.e=nj(l,c),e.d=l,nb=!1,a&&(e=nD(e,i,4*s)),u&&(e=e.times(54>Math.abs(u)?nS(2,u):rM.pow(2,u))),nb=!0,e)}(i,e)}if(o.prototype=nB,o.ROUND_UP=0,o.ROUND_DOWN=1,o.ROUND_CEIL=2,o.ROUND_FLOOR=3,o.ROUND_HALF_UP=4,o.ROUND_HALF_DOWN=5,o.ROUND_HALF_EVEN=6,o.ROUND_HALF_CEIL=7,o.ROUND_HALF_FLOOR=8,o.EUCLID=9,o.config=o.set=ro,o.clone=e,o.isDecimal=rp,o.abs=n6,o.acos=n3,o.acosh=n4,o.add=n5,o.asin=n8,o.asinh=n9,o.atan=n7,o.atanh=re,o.atan2=rt,o.cbrt=rn,o.ceil=rr,o.clamp=ri,o.cos=ra,o.cosh=rs,o.div=ru,o.exp=rl,o.floor=rc,o.hypot=rd,o.ln=rf,o.log=rh,o.log10=rg,o.log2=rm,o.max=ry,o.min=rb,o.mod=r_,o.mul=rv,o.pow=rw,o.random=rk,o.round=rx,o.sign=rA,o.sin=rS,o.sinh=rI,o.sqrt=rT,o.sub=rE,o.sum=rP,o.tan=rC,o.tanh=rO,o.trunc=rB,void 0===t&&(t={}),t&&!0!==t.defaults)for(i=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],n=0;n=9007199254740991||e<=-9007199254740991)&&t.logWithError(`BigNumberish number overflow: ${e}`),new(tb())(String(e))):"bigint"==typeof e?new(tb())(e.toString()):(t.error(`invalid BigNumberish value: ${e}`),new(tb())(0))}var rD=t8("module/fraction"),rF=rR(tP),rq=rR(tM()),rj={0:rq.ROUND_DOWN,1:rq.ROUND_HALF_UP,2:rq.ROUND_UP},rU={0:tP.roundDown,1:tP.roundHalfUp,2:tP.roundUp},rz=class{constructor(e,t=new(tb())(1)){this.numerator=rN(e),this.denominator=rN(t)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new rz(this.denominator,this.numerator)}add(e){let t=e instanceof rz?e:new rz(rN(e));return this.denominator.eq(t.denominator)?new rz(this.numerator.add(t.numerator),this.denominator):new rz(this.numerator.mul(t.denominator).add(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}sub(e){let t=e instanceof rz?e:new rz(rN(e));return this.denominator.eq(t.denominator)?new rz(this.numerator.sub(t.numerator),this.denominator):new rz(this.numerator.mul(t.denominator).sub(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}mul(e){let t=e instanceof rz?e:new rz(rN(e));return new rz(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof rz?e:new rz(rN(e));return new rz(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},n=1){Number.isInteger(e)||rD.logWithError(`${e} is not an integer.`),e<=0&&rD.logWithError(`${e} is not positive.`),rq.set({precision:e+1,rounding:rj[n]});let r=new rq(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return r.toFormat(r.decimalPlaces(),t)}toFixed(e,t={groupSeparator:""},n=1){return Number.isInteger(e)||rD.logWithError(`${e} is not an integer.`),e<0&&rD.logWithError(`${e} is negative.`),rF.DP=e,rF.RM=rU[n]||1,new rF(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}},rV=t8("Raydium_amount"),rW=rR(tP);function r$(e,t){let n="0",r="0";if(e.includes(".")){let i=e.split(".");2===i.length?([n,r]=i,r=r.padEnd(t,"0")):rV.logWithError(`invalid number string, num: ${e}`)}else n=e;return[n,r.slice(0,t)||r]}var rK=class extends rz{constructor(e,t,n=!0,r){let i=new(tb())(0),o=ig.pow(new(tb())(e.decimals));if(n)i=rN(t);else{let n=new(tb())(0),r=new(tb())(0);if("string"==typeof t||"number"==typeof t||"bigint"==typeof t){let[i,o]=r$(t.toString(),e.decimals);n=rN(i),r=rN(o)}i=(n=n.mul(o)).add(r)}super(i,o),this.logger=t8(r||"TokenAmount"),this.token=e}get raw(){return this.numerator}isZero(){return this.raw.isZero()}gt(e){return this.token.equals(e.token)||this.logger.logWithError("gt token not equals"),this.raw.gt(e.raw)}lt(e){return this.token.equals(e.token)||this.logger.logWithError("lt token not equals"),this.raw.lt(e.raw)}add(e){return this.token.equals(e.token)||this.logger.logWithError("add token not equals"),new rK(this.token,this.raw.add(e.raw))}subtract(e){return this.token.equals(e.token)||this.logger.logWithError("sub token not equals"),new rK(this.token,this.raw.sub(e.raw))}toSignificant(e=this.token.decimals,t,n=0){return super.toSignificant(e,t,n)}toFixed(e=this.token.decimals,t,n=0){return e>this.token.decimals&&this.logger.logWithError("decimals overflow"),super.toFixed(e,t,n)}toExact(e={groupSeparator:""}){return rW.DP=this.token.decimals,new rW(this.numerator.toString()).div(this.denominator.toString()).toFormat(e)}},rH=class extends null{constructor(e,t,n=!0,r){let i=new gn(0),o=ig.pow(new gn(e.decimals));if(n)i=rN(t);else{let n=new gn(0),r=new gn(0);if("string"==typeof t||"number"==typeof t||"bigint"==typeof t){let[i,o]=r$(t.toString(),e.decimals);n=rN(i),r=rN(o)}i=(n=n.mul(o)).add(r)}super(i,o),this.logger=t8(r||"TokenAmount"),this.currency=e}get raw(){return this.numerator}isZero(){return this.raw.isZero()}gt(e){return this.currency.equals(e.currency)||this.logger.logWithError("gt currency not equals"),this.raw.gt(e.raw)}lt(e){return this.currency.equals(e.currency)||this.logger.logWithError("lt currency not equals"),this.raw.lt(e.raw)}add(e){return this.currency.equals(e.currency)||this.logger.logWithError("add currency not equals"),new rH(this.currency,this.raw.add(e.raw))}sub(e){return this.currency.equals(e.currency)||this.logger.logWithError("sub currency not equals"),new rH(this.currency,this.raw.sub(e.raw))}toSignificant(e=this.currency.decimals,t,n=0){return super.toSignificant(e,t,n)}toFixed(e=this.currency.decimals,t,n=0){return e>this.currency.decimals&&this.logger.logWithError("decimals overflow"),super.toFixed(e,t,n)}toExact(e={groupSeparator:""}){return rW.DP=this.currency.decimals,new rW(this.numerator.toString()).div(this.denominator.toString()).toFormat(e)}},rG={chainId:101,address:tu.nh.default.toBase58(),programId:td.H_.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}},rZ={chainId:101,address:"So11111111111111111111111111111111111111112",programId:td.H_.toBase58(),decimals:9,symbol:"WSOL",name:"Wrapped SOL",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}};function rY({pubkey:e,isSigner:t=!1,isWritable:n=!0}){return{pubkey:e,isWritable:n,isSigner:t}}var rX=[rY({pubkey:td.H_,isWritable:!1}),rY({pubkey:tu.yc.programId,isWritable:!1}),rY({pubkey:tu.ze,isWritable:!1})];function rQ({publicKey:e,transformSol:t}){let n=rJ(e.toString());if(n instanceof tu.nh)return t&&n.equals(ie)?r7:n;if(t&&n.toString()===ie.toBase58())return r7;if("string"==typeof n){if(n===tu.nh.default.toBase58())return tu.nh.default;try{return new tu.nh(n)}catch{throw Error("invalid public key")}}throw Error("invalid public key")}function rJ(e){try{return new tu.nh(e)}catch{return e}}var r0=new tu.nh("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),r1=new tu.nh("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),r2=new tu.nh("SysvarRent111111111111111111111111111111111"),r6=new tu.nh("SysvarC1ock11111111111111111111111111111111"),r3=new tu.nh("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),r4=(new tu.nh("Sysvar1nstructions1111111111111111111111111"),tu.yc.programId),r5=new tu.nh("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),r8=(new tu.nh("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),new tu.nh("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),new tu.nh("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")),r9=new tu.nh("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),r7=(new tu.nh("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),new tu.nh("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),new tu.nh("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),new tu.nh("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),new tu.nh("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),new tu.nh("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),new tu.nh("So11111111111111111111111111111111111111112")),ie=tu.nh.default;function it(e){return rQ({publicKey:e,transformSol:!0})}var ir=class{constructor({mint:e,decimals:t,symbol:n,name:r,skipMint:i=!1,isToken2022:o=!1}){if(e===ie.toBase58()||e instanceof tu.nh&&ie.equals(e)){this.decimals=rZ.decimals,this.symbol=rZ.symbol,this.name=rZ.name,this.mint=new tu.nh(rZ.address),this.isToken2022=!1;return}this.decimals=t,this.symbol=n||e.toString().substring(0,6),this.name=r||e.toString().substring(0,6),this.mint=i?tu.nh.default:rQ({publicKey:e}),this.isToken2022=o}equals(e){return this===e||this.mint.equals(e.mint)}},ii=ir;ii.WSOL=new ir(t1(t0({},rZ),{mint:rZ.address}));var io=class{constructor({decimals:e,symbol:t="UNKNOWN",name:n="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=n}equals(e){return this===e}};io.SOL=new io(rG);var ia=new rz(new(tb())(100)),is=class extends rz{toSignificant(e=5,t,n){return this.mul(ia).toSignificant(e,t,n)}toFixed(e=2,t,n){return this.mul(ia).toFixed(e,t,n)}},iu=t8("Raydium_price"),il=class extends rz{constructor(e){var t,n;let{baseToken:r,quoteToken:i,numerator:o,denominator:a}=e;super(o,a),this.baseToken=r,this.quoteToken=i,this.scalar=new rz((t=r.decimals,ig.pow(rN(t))),(n=i.decimals,ig.pow(rN(n))))}get raw(){return new rz(this.numerator,this.denominator)}get adjusted(){return super.mul(this.scalar)}invert(){return new il({baseToken:this.quoteToken,quoteToken:this.baseToken,denominator:this.numerator,numerator:this.denominator})}mul(e){this.quoteToken!==e.baseToken&&iu.logWithError("mul token not equals");let t=super.mul(e);return new il({baseToken:this.baseToken,quoteToken:e.quoteToken,denominator:t.denominator,numerator:t.numerator})}toSignificant(e=this.quoteToken.decimals,t,n){return this.adjusted.toSignificant(e,t,n)}toFixed(e=this.quoteToken.decimals,t,n){return this.adjusted.toFixed(e,t,n)}};function ic(e){if(e instanceof is)return new rz(e.numerator,e.denominator);if(e instanceof il)return e.adjusted;if(e instanceof rK)try{return ic(e.toExact())}catch{return new rz(ih)}if(e instanceof rz)return e;let t=function(e){var t;if(void 0===e)return{denominator:"1",numerator:"0"};if(e instanceof tb())return{numerator:e.toString(),denominator:"1"};if(e instanceof rz)return{denominator:e.denominator.toString(),numerator:e.numerator.toString()};let[,n="",r="",i=""]=null!=(t=String(e).replace(",","").match(/(-?)(\d*)\.?(\d*)/))?t:[];return{denominator:"1"+"0".repeat(i.length),numerator:n+("0"===r?"":r)+i||"0",sign:n,int:r,dec:i}}(String(e));return new rz(t.numerator,t.denominator)}function id(e,t){if(null==e||null==t)return!1;let n=ic(e),r=ic(t);return n.sub(r).numerator.eq(ih)}function ip(e){return"string"==typeof e?rJ(e):Array.isArray(e)?e.map(e=>ip(e)):"object"!=typeof e||null===e||[ii,rK,tu.nh,rz,tb(),il,is].some(t=>"object"==typeof t&&e instanceof t)?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,ip(t)]))}var ih=new(tb())(0),im=new(tb())(1),ig=(new(tb())(2),new(tb())(3),new(tb())(5),new(tb())(10));function iy(e,t){let n=e.divmod(t);return n.mod.isZero()?n.div:n.div.isNeg()?n.div.isubn(1):n.div.iaddn(1)}function ib(e,t=1,n=[]){let r=[...e];if(t<=0)return n;for(;r.length;)n.push(r.splice(0,t));return n}new(tb())(100),new(tb())(1e3),new(tb())(1e4);var i_=class{constructor(e){this._owner=e}get publicKey(){return i_.isKeyPair(this._owner)?this._owner.publicKey:this._owner}get signer(){return i_.isKeyPair(this._owner)?this._owner:void 0}get isKeyPair(){return i_.isKeyPair(this._owner)}get isPublicKey(){return i_.isPublicKey(this._owner)}static isKeyPair(e){return void 0!==e.secretKey}static isPublicKey(e){return!i_.isKeyPair(e)}},iv=((a=iv||{})[a.V0=0]="V0",a[a.LEGACY=1]="LEGACY",a),iw={CreateAccount:"CreateAccount",InitAccount:"InitAccount",CreateATA:"CreateATA",CloseAccount:"CloseAccount",TransferAmount:"TransferAmount",InitMint:"InitMint",MintTo:"MintTo",InitMarket:"InitMarket",Util1216OwnerClaim:"Util1216OwnerClaim",SetComputeUnitPrice:"SetComputeUnitPrice",SetComputeUnitLimit:"SetComputeUnitLimit",ClmmCreatePool:"ClmmCreatePool",ClmmOpenPosition:"ClmmOpenPosition",ClmmIncreasePosition:"ClmmIncreasePosition",ClmmDecreasePosition:"ClmmDecreasePosition",ClmmClosePosition:"ClmmClosePosition",ClmmSwapBaseIn:"ClmmSwapBaseIn",ClmmSwapBaseOut:"ClmmSwapBaseOut",ClmmInitReward:"ClmmInitReward",ClmmSetReward:"ClmmSetReward",ClmmCollectReward:"ClmmCollectReward",ClmmLockPosition:"ClmmLockPosition",ClmmHarvestLockPosition:"ClmmHarvestLockPosition",AmmV4Swap:"AmmV4Swap",AmmV4AddLiquidity:"AmmV4AddLiquidity",AmmV4RemoveLiquidity:"AmmV4RemoveLiquidity",AmmV4SimulatePoolInfo:"AmmV4SimulatePoolInfo",AmmV4SwapBaseIn:"AmmV4SwapBaseIn",AmmV4SwapBaseOut:"AmmV4SwapBaseOut",AmmV4CreatePool:"AmmV4CreatePool",AmmV4InitPool:"AmmV4InitPool",AmmV5AddLiquidity:"AmmV5AddLiquidity",AmmV5RemoveLiquidity:"AmmV5RemoveLiquidity",AmmV5SimulatePoolInfo:"AmmV5SimulatePoolInfo",AmmV5SwapBaseIn:"AmmV5SwapBaseIn",AmmV5SwapBaseOut:"AmmV5SwapBaseOut",RouteSwap:"RouteSwap",RouteSwap1:"RouteSwap1",RouteSwap2:"RouteSwap2",FarmV3Deposit:"FarmV3Deposit",FarmV3Withdraw:"FarmV3Withdraw",FarmV3CreateLedger:"FarmV3CreateLedger",FarmV4Withdraw:"FarmV4Withdraw",FarmV5Deposit:"FarmV5Deposit",FarmV5Withdraw:"FarmV5Withdraw",FarmV5CreateLedger:"FarmV5CreateLedger",FarmV6Deposit:"FarmV6Deposit",FarmV6Withdraw:"FarmV6Withdraw",FarmV6Create:"FarmV6Create",FarmV6Restart:"FarmV6Restart",FarmV6CreatorAddReward:"FarmV6CreatorAddReward",FarmV6CreatorWithdraw:"FarmV6CreatorWithdraw",CpmmCreatePool:"CpmmCreatePool",CpmmAddLiquidity:"CpmmAddLiquidity",CpmmWithdrawLiquidity:"CpmmWithdrawLiquidity",CpmmSwapBaseIn:"CpmmSwapBaseIn",CpmmSwapBaseOut:"CpmmSwapBaseOut",CpmmLockLp:"CpmmLockLp",CpmmCollectLockFee:"CpmmCollectLockFee"},ik=t8("Raydium_txUtil");function ix(e){let t=[],n=[];return e.microLamports&&(t.push(tu.Lb.setComputeUnitPrice({microLamports:e.microLamports})),n.push(iw.SetComputeUnitPrice)),e.units&&(t.push(tu.Lb.setComputeUnitLimit({units:e.units})),n.push(iw.SetComputeUnitLimit)),{instructions:t,instructionTypes:n}}async function iA(e,t){var n,r;return null==(r=await (null==(n=e.getLatestBlockhash)?void 0:n.call(e,{commitment:null!=t?t:"confirmed"})))?void 0:r.blockhash}async function iS(e,t){return e.getSignatureStatuses([t]),new Promise((n,r)=>{let i=setTimeout(r,6e4);e.onSignature(t,e=>{if(clearTimeout(i),!e.err){n("");return}r(e.err.toString())},"confirmed")})}function iI(e,t){e.length<1&&ik.logWithError(`no instructions provided: ${e.toString()}`),t.length<1&&ik.logWithError(`no signers provided:, ${t.toString()}`);let n=new tu.YW;n.recentBlockhash="11111111111111111111111111111111",n.feePayer=t[0],n.add(...e);try{return tK.from(n.serialize({verifySignatures:!1})).toString("base64").length<1644}catch{return!1}}async function iT(e,t,n,r=!0){let i=new tu.nh("RaydiumSimuLateTransaction11111111111111111"),o=[],a=new tu.YW;for(let e of(a.feePayer=i,t))iI([...a.instructions,e],[i])||(o.push(a),(a=new tu.YW).feePayer=i),a.add(e);a.instructions.length>0&&o.push(a);let s=[];try{if((s=await iC(e,o,r)).find(e=>null!==e.err))throw Error("rpc simulateTransaction error")}catch(e){e instanceof Error&&ik.logWithError("failed to simulate for instructions","RPC_ERROR",{message:e.message})}let u=[];for(let e of s)if(ik.debug("simulate result:",e),e.logs){let t=e.logs.filter(e=>e&&e.includes(n));ik.debug("filteredLog:",u),t.length||ik.logWithError("simulate log not match keyword","keyword",n),u.push(...t)}return u}function iE(e,t){let n=RegExp(`"${t}":(\\d+)`,"g").exec(e);return n&&2===n.length?n[1]:ik.logWithError(`simulate log fail to match key", key: ${t}`)}function iP(e,t){let[n,r]=tu.nh.findProgramAddressSync(e,t);return{publicKey:n,nonce:r}}async function iC(e,t,n){let r=[];if(n){let n=await e.getLatestBlockhash(),i=[];for(let e of t){e.recentBlockhash=n.blockhash,e.lastValidBlockHeight=n.lastValidBlockHeight;let t=e._compile().serialize(),r=e._serialize(t).toString("base64");i.push(r)}let o=i.map(t=>({methodName:"simulateTransaction",args:e._buildArgs([t],void 0,"base64")})),a=[];for(let e=0;e(await e._rpcBatchRequest(t)).map(e=>e.result.value)))).flat()}else try{r=await Promise.all(t.map(async t=>await (await e.simulateTransaction(t)).value))}catch(e){e instanceof Error&&ik.logWithError("failed to get info for multiple accounts","RPC_ERROR",{message:e.message})}return r}function iO({instructions:e,payer:t,signers:n}){return iI(e,[t,...n])}function iB({instructions:e,payer:t,lookupTableAddressAccount:n,recentBlockhash:r=tu.RG.generate().publicKey.toString()}){let i=new tu.$Z({payerKey:t,recentBlockhash:r,instructions:e}).compileToV0Message(Object.values(null!=n?n:{}));try{return tK.from(new tu.GS(i).serialize()).toString("base64").length<1644}catch{return!1}}var iM=e=>tK.isBuffer(e)?e:e instanceof Uint8Array?tK.from(e.buffer,e.byteOffset,e.byteLength):tK.from(e),iR=e=>{let t=e.serialize({requireAllSignatures:!1,verifySignatures:!1});e instanceof tu.GS&&(t=iM(t));try{return t instanceof tK?t.toString("base64"):tK.from(t).toString("base64")}catch{return t.toString("base64")}};function iL(e){let t=[];return e.forEach(e=>{e instanceof tu.YW&&(e.recentBlockhash||(e.recentBlockhash=td.H_.toBase58()),e.feePayer||(e.feePayer=tu.RG.generate().publicKey)),t.push(iR(e))}),console.log("simulate tx string:",t),t}function iN(e,t,n){return iP([e.toBuffer(),(null!=n?n:td.H_).toBuffer(),t.toBuffer()],new tu.nh("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}var iD=new tu.nh("EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"),iF=new tu.nh("CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T"),iq=new tu.nh("9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z"),ij=new tu.nh("FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG"),iU=new tu.nh("CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS"),iz=new tu.nh("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"),iV=new tu.nh("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),iW=new tu.nh("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"),i$=new tu.nh("5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h"),iK=new tu.nh("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),iH=new tu.nh("CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"),iG=new tu.nh("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),iZ=new tu.nh("kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy"),iY=new tu.nh("routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS"),iX=new tu.nh("7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"),iQ=new tu.nh("6FJon3QE27qgPVggARueB22hLvoh22VzJpXv4rBEoSLF"),iJ=new tu.nh("CC12se5To1CdEuw7fDS27B7Geo5jJyL7t5UK2B44NgiH"),i0=new tu.nh("9HzJyW1qZsEiSfMUf6L2jo3CcTKAyBmSyKdwQeYisHrC"),i1=new tu.nh("DropEU8AvevN3UrXWXTMuz3rqnMczQVNjq3kcSdW2SQi"),i2=new tu.nh("CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"),i6=new tu.nh("GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"),i3=new tu.nh("DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8"),i4=(new tu.nh("CPMDWBwJDtYax9qW7AyRuVC19Cc4L4Vcy4n2BHAbHkCW"),new tu.nh("7rQ1QFNosMkUCuh7Z7fPbTHvh73b68sQYdirycEzJVuw"),new tu.nh("G11FKBRaAkHAKuLCgLM6K6NUc9rTjPAznRCjZifrTQe2"),new tu.nh("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE")),i5=(new tu.nh("DLockwT7X7sxtLmGH9g5kmfcjaBtncdbUmi738m5bvQC"),new tu.nh("3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH")),i8=(new tu.nh("7AFUeLVRjBfzqK3tTGw8hN48KLQWSk6DTE8xprWdPqix"),{IDO_PROGRAM_ID_V1:iQ,IDO_PROGRAM_ID_V2:iJ,IDO_PROGRAM_ID_V3:i0,IDO_PROGRAM_ID_V4:i1}),i9={AMM_V4:iW,AMM_STABLE:i$,CLMM_PROGRAM_ID:iH,CLMM_LOCK_PROGRAM_ID:iG,CLMM_LOCK_AUTH_ID:iZ,FARM_PROGRAM_ID_V3:iD,FARM_PROGRAM_ID_V5:iq,FARM_PROGRAM_ID_V6:ij,OPEN_BOOK_PROGRAM:iz,SERUM_PROGRAM_ID_V3:iV,UTIL1216:iU,Router:iY,CREATE_CPMM_POOL_PROGRAM:i2,CREATE_CPMM_POOL_AUTH:i6,CREATE_CPMM_POOL_FEE_ACC:i3,LOCK_CPMM_PROGRAM:i4,LOCK_CPMM_AUTH:i5};function i7(e,t,n,r){if(void 0===t)return{amount:e,fee:void 0,expirationTime:void 0};let i=t1(t0({},t),{olderTransferFee:{epoch:BigInt(t.olderTransferFee.epoch),maximumFee:BigInt(t.olderTransferFee.maximumFee),transferFeeBasisPoints:t.olderTransferFee.transferFeeBasisPoints},newerTransferFee:{epoch:BigInt(t.newerTransferFee.epoch),maximumFee:BigInt(t.newerTransferFee.maximumFee),transferFeeBasisPoints:t.newerTransferFee.transferFeeBasisPoints}}),o=n.epoche.toString()))].map(e=>new tu.nh(e))),r={};for(let e=0;ee!==tu.nh.default.toString())),this}async versionBuild({txVersion:e,extInfo:t}){return 0===e?await this.buildV0(t0({},t||{})):this.build(t)}build(e){var t;let n=new tu.YW;return this.allInstructions.length&&n.add(...this.allInstructions),n.feePayer=this.feePayer,(null==(t=this.owner)?void 0:t.signer)&&!this.signers.some(e=>e.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer),{builder:this,transaction:n,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async e=>{var t;let{recentBlockHash:r,skipPreflight:i=!0,sendAndConfirm:o}=e||{},a=null!=r?r:await iA(this.connection,this.blockhashCommitment);if(n.recentBlockhash=a,this.signers.length&&n.sign(...this.signers),iL([n]),null!=(t=this.owner)&&t.isKeyPair)return{txId:o?await (0,tu.BV)(this.connection,n,this.signers.find(e=>e.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:i}):await this.connection.sendRawTransaction(n.serialize(),{skipPreflight:i}),signedTx:n};if(this.signAllTransactions){let e=await this.signAllTransactions([n]);return{txId:await this.connection.sendRawTransaction(e[0].serialize(),{skipPreflight:i}),signedTx:e[0]}}throw Error("please provide owner in keypair format or signAllTransactions function")},extInfo:e||{}}}buildMultiTx(e){var t;let{extraPreBuildData:n=[],extInfo:r}=e,{transaction:i}=this.build(r),o=n.filter(e=>e.transaction.instructions.length>0),a=[i,...o.map(e=>e.transaction)],s=[this.signers,...o.map(e=>e.signers)],u=[...this.instructionTypes,...o.map(e=>e.instructionTypes).flat()];return null!=(t=this.owner)&&t.signer&&s.forEach(e=>{e.some(e=>e.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:a,signers:s,instructionTypes:u,execute:async e=>{var t;let{sequentially:n,onTxUpdate:r,skipTxCount:i=0,recentBlockHash:o,skipPreflight:u=!0}=e||{},l=null!=o?o:await iA(this.connection,this.blockhashCommitment);if(null!=(t=this.owner)&&t.isKeyPair){if(n){let e=[],t=0;for(let n of a){if(++t<=i)continue;let r=await (0,tu.BV)(this.connection,n,this.signers.find(e=>e.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:u});e.push(r)}return{txIds:e,signedTxs:a}}return{txIds:await await Promise.all(a.map(async e=>(e.recentBlockhash=l,await this.connection.sendRawTransaction(e.serialize(),{skipPreflight:u})))),signedTxs:a}}if(this.signAllTransactions){let e=a.map((e,t)=>(e.recentBlockhash=l,s[t].length&&e.sign(...s[t]),e));iL(e);let t=await this.signAllTransactions(e);if(n){let e=0,n=[],i=async()=>{if(!t[e])return;let o=await this.connection.sendRawTransaction(t[e].serialize(),{skipPreflight:u});n.push({txId:o,status:"sent",signedTx:t[e]}),null==r||r([...n]),e++,this.connection.onSignature(o,e=>{let t=n.findIndex(e=>e.txId===o);t>-1&&(n[t].status=e.err?"error":"success"),null==r||r([...n]),e.err||i()},"processed"),this.connection.getSignatureStatus(o)};return await i(),{txIds:n.map(e=>e.txId),signedTxs:t}}{let e=[];for(let n=0;ne.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let f=new tu.GS(p);return f.sign(this.signers),{builder:this,transaction:f,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async e=>{var t;let{skipPreflight:n=!0,sendAndConfirm:r}=e||{};if(iL([f]),null!=(t=this.owner)&&t.isKeyPair){let e=await this.connection.sendTransaction(f,{skipPreflight:n});return r&&await iS(this.connection,e),{txId:e,signedTx:f}}if(this.signAllTransactions){let e=await this.signAllTransactions([f]);return{txId:await this.connection.sendTransaction(e[0],{skipPreflight:n}),signedTx:e[0]}}throw Error("please provide owner in keypair format or signAllTransactions function")},extInfo:s||{}}}async buildV0MultiTx(e){var t;let{extraPreBuildData:n=[],buildProps:r}=e,{transaction:i}=await this.buildV0(r),o=n.filter(e=>e.builder.instructions.length>0),a=[i,...o.map(e=>e.transaction)],s=[this.signers,...o.map(e=>e.signers)],u=[...this.instructionTypes,...o.map(e=>e.instructionTypes).flat()];return null!=(t=this.owner)&&t.signer&&s.forEach(e=>{e.some(e=>e.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),a.forEach(async(e,t)=>{e.sign(s[t])}),{builder:this,transactions:a,signers:s,instructionTypes:u,buildProps:r,execute:async e=>{var t;let{sequentially:n,onTxUpdate:r,recentBlockHash:i,skipPreflight:o=!0}=e||{};if(i&&a.forEach(e=>e.message.recentBlockhash=i),iL(a),null!=(t=this.owner)&&t.isKeyPair){if(n){let e=[];for(let t of a){let n=await this.connection.sendTransaction(t,{skipPreflight:o});await iS(this.connection,n),e.push(n)}return{txIds:e,signedTxs:a}}return{txIds:await Promise.all(a.map(async e=>await this.connection.sendTransaction(e,{skipPreflight:o}))),signedTxs:a}}if(this.signAllTransactions){let e=await this.signAllTransactions(a);if(n){let t=0,n=[],i=async()=>{if(!e[t])return;let a=await this.connection.sendTransaction(e[t],{skipPreflight:o});n.push({txId:a,status:"sent",signedTx:e[t]}),null==r||r([...n]),t++,this.connection.onSignature(a,e=>{let t=n.findIndex(e=>e.txId===a);t>-1&&(n[t].status=e.err?"error":"success"),null==r||r([...n]),e.err||i()},"processed"),this.connection.getSignatureStatus(a)};return i(),{txIds:[],signedTxs:e}}{let t=[];for(let n=0;nt1(t0({},e),{[t.publicKey.toBase58()]:t}),{}),u=[],l=[],c=[],d=0;if(this.allInstructions.forEach(e=>{let t=[...c,e],n=i?[...a.instructions,...t]:t,o=[...new Set(t.map(e=>e.keys.filter(e=>e.isSigner).map(e=>e.pubkey.toString())).flat()).values()].map(e=>new tu.nh(e));if(e!==r[d]&&c.length<12&&(iO({instructions:n,payer:this.feePayer,signers:o})||iO({instructions:t,payer:this.feePayer,signers:o})))c.push(e);else{if(0===c.length)throw Error("item ins too big");d+=e===r[d]?1:0,iO({instructions:i?[...a.instructions,...c]:[...c],payer:this.feePayer,signers:o})?u.push(new tu.YW().add(...a.instructions,...c)):u.push(new tu.YW().add(...c)),l.push(Array.from(new Set(c.map(e=>e.keys.filter(e=>e.isSigner).map(e=>e.pubkey.toString())).flat())).map(e=>s[e]).filter(e=>void 0!==e)),c=[e]}}),c.length>0){let e=[...new Set(c.map(e=>e.keys.filter(e=>e.isSigner).map(e=>e.pubkey.toString())).flat()).values()].map(e=>s[e]).filter(e=>void 0!==e);iO({instructions:i?[...a.instructions,...c]:[...c],payer:this.feePayer,signers:e.map(e=>e.publicKey)})?u.push(new tu.YW().add(...a.instructions,...c)):u.push(new tu.YW().add(...c)),l.push(e)}return u.forEach(e=>e.feePayer=this.feePayer),null!=(t=this.owner)&&t.signer&&l.forEach(e=>{e.some(e=>e.publicKey.equals(this.owner.publicKey))||e.push(this.owner.signer)}),{builder:this,transactions:u,signers:l,instructionTypes:this.instructionTypes,execute:async e=>{var t;let{sequentially:n,onTxUpdate:r,skipTxCount:i=0,recentBlockHash:o,skipPreflight:a=!0}=e||{},s=null!=o?o:await iA(this.connection,this.blockhashCommitment);if(u.forEach(async(e,t)=>{e.recentBlockhash=s,l[t].length&&e.sign(...l[t])}),iL(u),null!=(t=this.owner)&&t.isKeyPair){if(n){let e=0,t=[];for(let n of u){if(++e<=i){t.push("tx skipped");continue}let r=await (0,tu.BV)(this.connection,n,this.signers.find(e=>e.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:a});t.push(r)}return{txIds:t,signedTxs:u}}return{txIds:await Promise.all(u.map(async e=>await this.connection.sendRawTransaction(e.serialize(),{skipPreflight:a}))),signedTxs:u}}if(this.signAllTransactions){let e=await this.signAllTransactions(u.slice(i,u.length)),t=[...u.slice(0,i),...e];if(n){let e=0,n=[],o=async()=>{if(!t[e])return;e{let t=n.findIndex(e=>e.txId===s);t>-1&&(n[t].status=e.err?"error":"success"),null==r||r([...n]),e.err||o()},"processed"),this.connection.getSignatureStatus(s)};return await o(),{txIds:n.map(e=>e.txId),signedTxs:t}}{let e=[];for(let n=0;nt1(t0({},e),{[t.publicKey.toBase58()]:t}),{}),h=[],m=[],g=[],y=0;if(this.allInstructions.forEach(e=>{let t=[...g,e],n=r?[...d.instructions,...t]:t;if(e!==i[y]&&g.length<12&&(iB({instructions:n,payer:this.feePayer,lookupTableAddressAccount:u})||iB({instructions:t,payer:this.feePayer,lookupTableAddressAccount:u})))g.push(e);else{if(0===g.length)throw Error("item ins too big");y+=e===i[y]?1:0;let t={};for(let e of[...new Set(l)])void 0!==u[e]&&(t[e]=u[e]);if(r&&iB({instructions:[...d.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:u,recentBlockhash:p})){let e=new tu.$Z({payerKey:this.feePayer,recentBlockhash:p,instructions:[...d.instructions,...g]}).compileToV0Message(Object.values(u));h.push(new tu.GS(e))}else{let e=new tu.$Z({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(u));h.push(new tu.GS(e))}m.push(Array.from(new Set(g.map(e=>e.keys.filter(e=>e.isSigner).map(e=>e.pubkey.toString())).flat())).map(e=>f[e]).filter(e=>void 0!==e)),g=[e]}}),g.length>0){let e=[...new Set(g.map(e=>e.keys.filter(e=>e.isSigner).map(e=>e.pubkey.toString())).flat()).values()].map(e=>f[e]).filter(e=>void 0!==e);if(r&&iB({instructions:[...d.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:u,recentBlockhash:p})){let e=new tu.$Z({payerKey:this.feePayer,recentBlockhash:p,instructions:[...d.instructions,...g]}).compileToV0Message(Object.values(u));h.push(new tu.GS(e))}else{let e=new tu.$Z({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(u));h.push(new tu.GS(e))}m.push(e)}return null!=(t=this.owner)&&t.signer&&m.forEach(e=>{e.some(e=>e.publicKey.equals(this.owner.publicKey))||e.push(this.owner.signer)}),{builder:this,transactions:h,buildProps:e,signers:m,instructionTypes:this.instructionTypes,execute:async e=>{var t;let{sequentially:n,onTxUpdate:r,skipTxCount:i=0,recentBlockHash:o,skipPreflight:a=!0}=e||{};if(h.map(async(e,t)=>{m[t].length&&e.sign(m[t]),o&&(e.message.recentBlockhash=o)}),iL(h),null!=(t=this.owner)&&t.isKeyPair){if(n){let e=0,t=[];for(let n of h){if(++e<=i){console.log("skip tx: ",e),t.push("tx skipped");continue}let r=await this.connection.sendTransaction(n,{skipPreflight:a});await iS(this.connection,r),t.push(r)}return{txIds:t,signedTxs:h}}return{txIds:await Promise.all(h.map(async e=>await this.connection.sendTransaction(e,{skipPreflight:a}))),signedTxs:h}}if(this.signAllTransactions){let e=await this.signAllTransactions(h.slice(i,h.length)),t=[...h.slice(0,i),...e];if(n){let e=0,n=[],o=async()=>{if(!t[e])return;if(e{let t=n.findIndex(e=>e.txId===s);t>-1&&(n[t].status=e.err?"error":"success"),null==r||r([...n]),e.err||o()},"processed"),this.connection.getSignatureStatus(s)};return o(),{txIds:[],signedTxs:t}}{let e=[];for(let n=0;n{window;let e=sessionStorage.getItem(ou);return e||(e=`ray-${Date.now()}`,sessionStorage.setItem(ou,e)),e},od=async e=>{var{logCount:t=1e3,removeLastLog:n}=e,r=t2(e,["logCount","removeLastLog"]);window;let i=JSON.parse(localStorage.getItem(ol)||"[]").slice(0,t-1);n&&i.pop(),new Blob([JSON.stringify(r.data)]).size>1024&&(r.data=JSON.stringify(r.data).substring(0,200)+"..."),i.unshift(t1(t0({},r),{time:Date.now(),session:oc()}));try{localStorage.setItem(ol,JSON.stringify(i))}catch{if(n){let e=!1,t=JSON.stringify(r.data).substring(0,100);for(i[0].data=t+(t.length>100?"...":"");!e;){i.pop();let t=JSON.stringify(r.data).substring(0,100);i[0].data=t+(t.length>100?"...":"");try{localStorage.setItem(ol,JSON.stringify(i)),e=!0}catch{e=!1}}return new Promise(e=>e())}return od(t1(t0({},r),{logCount:t,removeLastLog:!0}))}},op=t8("Raydium_Api"),of=new Map,oh=class{constructor({cluster:e,timeout:t,logRequests:n,logCount:r,urlConfigs:i}){this.cluster=e,this.urlConfigs=i||{},this.logCount=r||1e3,this.api=ts.create({baseURL:this.urlConfigs.BASE_HOST||os.BASE_HOST,timeout:t}),this.api.interceptors.request.use(e=>{let{method:t,baseURL:n,url:r}=e;return op.debug(`${null==t?void 0:t.toUpperCase()} ${n}${r}`),e},e=>(op.error("Request failed"),Promise.reject(e))),this.api.interceptors.response.use(e=>{let{config:t,data:r,status:i}=e,{method:o,baseURL:a,url:s}=t;return n&&od({status:i,url:`${a}${s}`,params:t.params,data:r,logCount:this.logCount}),op.debug(`${null==o?void 0:o.toUpperCase()} ${a}${s} ${i}`),r},e=>{let{config:t,response:r={}}=e,{status:i}=r,{method:o,baseURL:a,url:s}=t;return n&&od({status:i,url:`${a}${s}`,params:t.params,data:e.message,logCount:this.logCount}),op.error(`${o.toUpperCase()} ${a}${s} ${i||e.message}`),Promise.reject(e)})}async getClmmConfigs(){return(await this.api.get(this.urlConfigs.CLMM_CONFIG||os.CLMM_CONFIG)).data}async getCpmmConfigs(){return(await this.api.get(this.urlConfigs.CPMM_CONFIG||os.CPMM_CONFIG)).data}async getClmmPoolLines(e){return(await this.api.get(`${this.urlConfigs.POOL_LIQUIDITY_LINE||os.POOL_LIQUIDITY_LINE}?pool_id=${e}`)).data}async getBlockSlotCountForSecond(e){if(!e)return 2;let t=(await ts.post(e,{id:"getRecentPerformanceSamples",jsonrpc:"2.0",method:"getRecentPerformanceSamples",params:[4]})).result.map(e=>e.numSlots);return t.reduce((e,t)=>e+t,0)/t.length/60}async getChainTimeOffset(){return(await this.api.get(this.urlConfigs.CHAIN_TIME||os.CHAIN_TIME)).data}async getRpcs(){return this.api.get(this.urlConfigs.RPCS||os.RPCS)}async getTokenList(){return(await this.api.get(this.urlConfigs.TOKEN_LIST||os.TOKEN_LIST)).data}async getJupTokenList(){return this.api.get("",{baseURL:this.urlConfigs.JUP_TOKEN_LIST||os.JUP_TOKEN_LIST})}async getTokenInfo(e){return(await this.api.get((this.urlConfigs.MINT_INFO_ID||os.MINT_INFO_ID)+`?mints=${e.map(e=>e.toString()).join(",")}`)).data}async getPoolList(e={}){let{type:t="all",sort:n="liquidity",order:r="desc",page:i=0,pageSize:o=100}=e;return(await this.api.get((this.urlConfigs.POOL_LIST||os.POOL_LIST)+`?poolType=${t}&poolSortField=${n}&sortType=${r}&page=${i}&pageSize=${o}`)).data}async fetchPoolById(e){let{ids:t}=e;return(await this.api.get((this.urlConfigs.POOL_SEARCH_BY_ID||os.POOL_SEARCH_BY_ID)+`?ids=${t}`)).data}async fetchPoolKeysById(e){let{idList:t}=e,n=[],r=t.filter(e=>!of.has(e)||(n.push(of.get(e)),!1)),i=[];return r.length&&(i=(await this.api.get((this.urlConfigs.POOL_KEY_BY_ID||os.POOL_KEY_BY_ID)+`?ids=${r.join(",")}`)).data.filter(Boolean)).forEach(e=>{of.set(e.id,e)}),n.concat(i)}async fetchPoolByMints(e){let{mint1:t,mint2:n,type:r="all",sort:i="default",order:o="desc",page:a=1}=e,[s,u]=[t&&it(t).toBase58(),n&&"undefined"!==n?it(n).toBase58():""],[l,c]=u&&s>u?[u,s]:[s,u];return(await this.api.get((this.urlConfigs.POOL_SEARCH_MINT||os.POOL_SEARCH_MINT)+`?mint1=${l}&mint2=${c}&poolType=${r}&poolSortField=${i}&sortType=${o}&pageSize=100&page=${a}`)).data}async fetchFarmInfoById(e){let{ids:t}=e;return(await this.api.get((this.urlConfigs.FARM_INFO||os.FARM_INFO)+`?ids=${t}`)).data}async fetchFarmKeysById(e){let{ids:t}=e;return(await this.api.get((this.urlConfigs.FARM_KEYS||os.FARM_KEYS)+`?ids=${t}`)).data}async fetchAvailabilityStatus(){return(await this.api.get(this.urlConfigs.CHECK_AVAILABILITY||os.CHECK_AVAILABILITY)).data}async sendTxToJito(e,t){let n=t?this.urlConfigs.JITO_BUNDLE||os.JITO_BUNDLE:this.urlConfigs.JITO_TRANSACTION||os.JITO_TRANSACTION;return(await this.api.post(n,{jsonrpc:"2.0",id:1,method:t?"sendBundle":"sendTransaction",params:e},{baseURL:this.urlConfigs.JITO||os.JITO})).data}},om="please provide owner in load() initialization or you can set by calling raydium.setOwner(owner)",og=(...e)=>e.map(e=>{try{return"object"==typeof e?JSON.stringify(e):e}catch{return e}}).join(", "),oy=class{constructor({scope:e,moduleName:t}){this.disabled=!1,this.scope=e,this.logger=t8(t)}createTxBuilder(e){return this.scope.checkOwner(),new oi({connection:this.scope.connection,feePayer:e||this.scope.ownerPubKey,cluster:this.scope.cluster,owner:this.scope.owner,blockhashCommitment:this.scope.blockhashCommitment,api:this.scope.api,signAllTransactions:this.scope.signAllTransactions})}logDebug(...e){this.logger.debug(og(e))}logInfo(...e){this.logger.info(og(e))}logAndCreateError(...e){throw Error(og(e))}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};function ob(e,...t){if(!(e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function o_(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}var ov=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),ow=(e,t)=>e<<32-t|e>>>t;function ok(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}(e)),ob(e),e}new Uint8Array(new Uint32Array([287454020]).buffer)[0];var ox=class{clone(){return this._cloneInto()}},oA=(e,t,n)=>e&t^~e&n,oS=(e,t,n)=>e&t^e&n^t&n,oI=class extends ox{constructor(e,t,n,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=ov(this.buffer)}update(e){o_(this);let{view:t,buffer:n,blockLen:r}=this,i=(e=ok(e)).length;for(let o=0;or-o&&(this.process(n,0),o=0);for(let e=o;e>i&o),s=Number(n&o);e.setUint32(t+(r?4:0),a,r),e.setUint32(t+(r?0:4),s,r)})(n,r-8,BigInt(8*this.length),i),this.process(n,0);let a=ov(e),s=this.outputLen;if(s%4)throw Error("_sha2: outputLen should be aligned to 32bit");let u=s/4,l=this.get();if(u>l.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e>>3,i=ow(n,17)^ow(n,19)^n>>>10;oP[e]=i+oP[e-7]+r+oP[e-16]|0}let{A:n,B:r,C:i,D:o,E:a,F:s,G:u,H:l}=this;for(let e=0;e<64;e++){let t=l+(ow(a,6)^ow(a,11)^ow(a,25))+oA(a,s,u)+oT[e]+oP[e]|0,c=(ow(n,2)^ow(n,13)^ow(n,22))+oS(n,r,i)|0;l=u,u=s,s=a,a=o+t|0,o=i,i=r,r=n,n=t+c|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,s=s+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,r,i,o,a,s,u,l)}roundClean(){oP.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},oO=(l=()=>new oC,r=e=>l().update(ok(e)).digest(),i=l(),r.outputLen=i.outputLen,r.blockLen=i.blockLen,r.create=()=>l(),r),oB=tp.Ar,oM=tp.vA,oR=(tp.EJ,tp.VQ,tp.fP),oL=(tp.t6,tp._H,tp.u8),oN=tp.KB,oD=(tp.Vb,tp.Jq),oF=(tp.ut,tp.aq,tp._O),oq=(tp.Lb,tp.b7,tp.Gj,tp.qY,tp.hn,tp.$r,tp.s8,tp.Tl,tp.aQ,tp.Xo);tp._n,tp.Yt,tp.gM,tp.xP,tp.O9,tp.u,tp.IS,tp.hO,tp.LN,tp.xn,tp.WZ,tp.eh,tp.Mn;var oj=tp.A9,oU=(tp.G0,tp.K_,tp.Ik),oz=(tp.ZZ,tp.KA,tp.pc);tp.cv;var oV=class extends oB{constructor(e,t,n){super(e,n),this.blob=oU(e),this.signed=t}decode(e,t=0){let n=new(tb())(this.blob.decode(e,t),10,"le");return this.signed?n.fromTwos(8*this.span).clone():n}encode(e,t,n=0){return"number"==typeof e&&(e=new(tb())(e)),this.signed&&(e=e.toTwos(8*this.span)),this.blob.encode(e.toArrayLike(tK,"le",this.span),t,n)}},oW=class extends oB{constructor(e){super(8,e),this._lower=oz(oD(),!1),this._upper=oz(oD(),!1)}addBoolean(e){this._lower.fields.length<32?this._lower.addBoolean(e):this._upper.addBoolean(e)}decode(e,t=0){let n=this._lower.decode(e,t),r=this._upper.decode(e,t+this._lower.span);return t0(t0({},n),r)}encode(e,t,n=0){return this._lower.encode(e,t,n)+this._upper.encode(e,t,n+this._lower.span)}};function o$(e){return new oR(1,e)}function oK(e){return new oR(4,e)}function oH(e){return new oV(8,!1,e)}function oG(e){return new oV(16,!1,e)}function oZ(e){return new oV(8,!0,e)}var oY=class extends oB{constructor(e,t,n,r){super(e.span,r),this.layout=e,this.decoder=t,this.encoder=n}decode(e,t){return this.decoder(this.layout.decode(e,t))}encode(e,t,n){return this.layout.encode(this.encoder(e),t,n)}getSpan(e,t){return this.layout.getSpan(e,t)}};function oX(e){return new oY(oU(32),e=>new tu.nh(e),e=>e.toBuffer(),e)}function oQ(e){return new oY(oL(),oJ,o0,e)}function oJ(e){if(0===e)return!1;if(1===e)return!0;throw Error("Invalid bool: "+e)}function o0(e){return e?1:0}var o1=class extends oM{decode(e,t){return super.decode(e,t)}};function o2(e,t,n){return new o1(e,t,n)}function o6(e,t,n){let r;return oj(e,"number"==typeof t?t:(0,ty.isBN)(t)?t.toNumber():new Proxy(t,{get(e,t){if(!r){let t=Reflect.get(e,"count");r=(0,ty.isBN)(t)?t.toNumber():t,Reflect.set(e,"count",r)}return Reflect.get(e,t)},set:(e,t,n)=>("count"===t&&(r=n),Reflect.set(e,t,n))}),n)}var o3=o2([oX("mint"),oX("owner"),oH("amount"),oK("delegateOption"),oX("delegate"),o$("state"),oK("isNativeOption"),oH("isNative"),oH("delegatedAmount"),oK("closeAuthorityOption"),oX("closeAuthority")]);function o4({fromPublicKey:e,programId:t=td.H_,assignSeed:n}){let r,i=n?btoa(n).slice(0,32):tu.RG.generate().publicKey.toBase58().slice(0,32);return{publicKey:(r=oO(tK.concat([e.toBuffer(),tK.from(i),t.toBuffer()])),new tu.nh(r)),seed:i}}function o5(e){let{mint:t,tokenAccount:n,owner:r,programId:i=td.H_}=e;return tq(n,t,r,i)}function o8(e){let{tokenAccount:t,payer:n,multiSigners:r=[],owner:i,programId:o=td.H_}=e;return function(e,t,n,r=[],i=td.H_){let o=tj([{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0}],n,r),a=tU.alloc(tz.span);return tz.encode({instruction:nd.CloseAccount},a),new tu.Sl({keys:o,programId:i,data:a})}(t,n,i,r,o)}async function o9(e){let{connection:t,amount:n,commitment:r,payer:i,owner:o,skipCloseAccount:a}=e,s=await t.getMinimumBalanceForRentExemption(o3.span,r),u=rN(n).add(new(tb())(s)),l=o4({fromPublicKey:i,programId:td.H_});return{addresses:{newAccount:l.publicKey},signers:[],instructions:[tu.yc.createAccountWithSeed({fromPubkey:i,basePubkey:i,seed:l.seed,newAccountPubkey:l.publicKey,lamports:u.toNumber(),space:o3.span,programId:td.H_}),o5({mint:new tu.nh(rZ.address),tokenAccount:l.publicKey,owner:o,programId:td.H_})],instructionTypes:[iw.CreateAccount,iw.InitAccount],endInstructionTypes:a?[]:[iw.CloseAccount],endInstructions:a?[]:[o8({tokenAccount:l.publicKey,payer:i,owner:o})]}}t8("Raydium_Util");var o7=class extends oy{constructor(e){super(e),this._tokenAccounts=[],this._tokenAccountRawInfos=[],this._accountListener=[],this._clientOwnedToken=!1,this._notSubscribeAccountChange=!1,this._accountFetchTime=0;let{tokenAccounts:t,tokenAccountRawInfos:n,notSubscribeAccountChange:r}=e;this._tokenAccounts=t||[],this._tokenAccountRawInfos=n||[],this._notSubscribeAccountChange=null==r||r,this._clientOwnedToken=!!(t||n)}get tokenAccounts(){return this._tokenAccounts}get tokenAccountRawInfos(){return this._tokenAccountRawInfos}set notSubscribeAccountChange(e){this._notSubscribeAccountChange=e}updateTokenAccount({tokenAccounts:e,tokenAccountRawInfos:t}){return e&&(this._tokenAccounts=e),t&&(this._tokenAccountRawInfos=t),this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId),this._accountChangeListenerId=void 0,this._clientOwnedToken=!0,this}addAccountChangeListener(e){return this._accountListener.push(e),this}removeAccountChangeListener(e){return this._accountListener=this._accountListener.filter(t=>t!==e),this}getAssociatedTokenAccount(e,t){return iN(this.scope.ownerPubKey,e,t).publicKey}resetTokenAccounts(){this._clientOwnedToken||(this._tokenAccounts=[],this._tokenAccountRawInfos=[])}async fetchWalletTokenAccounts(e){if(this._clientOwnedToken||!(null!=e&&e.forceUpdate)&&this._tokenAccounts.length&&Date.now()-this._accountFetchTime<(this._notSubscribeAccountChange?5e3:18e4))return{tokenAccounts:this._tokenAccounts,tokenAccountRawInfos:this._tokenAccountRawInfos};this.scope.checkOwner();let t=t0(t0({},{}),e),[n,r,i]=await Promise.all([this.scope.connection.getAccountInfo(this.scope.ownerPubKey,t.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:td.H_},t.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:td.nA},t.commitment)]),{tokenAccounts:o,tokenAccountRawInfos:a}=function({owner:e,solAccountResp:t,tokenAccountResp:n}){let r=[],i=[];for(let{pubkey:t,account:o}of n.value){let n=o3.decode(o.data),{mint:a,amount:s}=n;r.push({publicKey:t,mint:a,amount:s,isAssociated:iN(e,a,o.owner).publicKey.equals(t),isNative:!1,programId:o.owner}),i.push({pubkey:t,accountInfo:n,programId:o.owner})}return t&&r.push({mint:tu.nh.default,amount:new(tb())(String(t.lamports)),isNative:!0,programId:t.owner}),{tokenAccounts:r,tokenAccountRawInfos:i}}({owner:this.scope.ownerPubKey,solAccountResp:n,tokenAccountResp:{context:r.context,value:[...r.value,...i.value]}});return this._tokenAccounts=o,this._tokenAccountRawInfos=a,this._accountFetchTime=Date.now(),this._notSubscribeAccountChange||(this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId),this._accountChangeListenerId=this.scope.connection.onAccountChange(this.scope.ownerPubKey,()=>{this.fetchWalletTokenAccounts({forceUpdate:!0}),this._accountListener.forEach(e=>e({tokenAccounts:this._tokenAccounts,tokenAccountRawInfos:this._tokenAccountRawInfos}))},{commitment:null==e?void 0:e.commitment})),{tokenAccounts:o,tokenAccountRawInfos:a}}clearAccountChangeCkb(){void 0!==this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId)}async getCreatedTokenAccount({mint:e,programId:t=td.H_,associatedOnly:n=!0}){await this.fetchWalletTokenAccounts();let r=this._tokenAccounts.filter(({mint:t})=>null==t?void 0:t.equals(e)).sort((e,t)=>e.amount.lt(t.amount)?1:-1),i=this.getAssociatedTokenAccount(e,t);for(let e of r){let{publicKey:t}=e;if(t&&(!n||n&&i.equals(t)))return t}}async getOrCreateTokenAccount(e){var t,n,r,i;await this.fetchWalletTokenAccounts();let{mint:o,createInfo:a,associatedOnly:s,owner:u,notUseTokenAccount:l=!1,skipCloseAccount:c=!1,checkCreateATAOwner:d=!1,assignSeed:p}=e,f=new tu.nh(e.tokenProgram||td.H_),h=this.getAssociatedTokenAccount(o,new tu.nh(f)),m=(l?[]:this.tokenAccountRawInfos).filter(e=>e.accountInfo.mint.equals(o)&&(!s||e.pubkey.equals(h))).sort((e,t)=>e.accountInfo.amount.lt(t.accountInfo.amount)?1:-1);if(void 0===a||m.length>0)return m.length>0?{account:m[0].pubkey}:{};let g={instructions:[],endInstructions:[],signers:[],instructionTypes:[],endInstructionTypes:[]};if(s){let e=tL(u,h,u,o,f);if(d){let n=await this.scope.connection.getAccountInfo(h);if(null===n)null==(t=g.instructions)||t.push(e),g.instructionTypes.push(iw.CreateATA);else if(!(n.owner.equals(f)&&tN.p0.decode(n.data).mint.equals(o)&&tN.p0.decode(n.data).owner.equals(u)))throw Error(`create ata check error -> mint: ${o.toString()}, ata: ${h.toString()}`)}else g.instructions.push(e),g.instructionTypes.push(iw.CreateATA);if(o.equals(r7)&&a.amount){let e=await o9({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:a.payer||this.scope.ownerPubKey,amount:null!=(n=a.amount)?n:0,skipCloseAccount:c});g.instructions.push(...e.instructions||[]),g.endInstructions.push(...e.endInstructions||[]),g.instructionTypes.push(...e.instructionTypes||[]),g.endInstructionTypes.push(...e.endInstructionTypes||[]),a.amount&&(g.instructions.push(function({source:e,destination:t,owner:n,amount:r,multiSigners:i=[],tokenProgram:o=td.H_}){return t$(e,t,n,BigInt(String(r)),i,o)}({source:e.addresses.newAccount,destination:h,owner:this.scope.ownerPubKey,amount:a.amount,tokenProgram:td.H_})),g.instructionTypes.push(iw.TransferAmount))}return c||(g.endInstructions.push(o8({owner:u,payer:a.payer||u,tokenAccount:h,programId:f})),g.endInstructionTypes.push(iw.CloseAccount)),{account:h,instructionParams:g}}{let e=o4({fromPublicKey:u,programId:f,assignSeed:p}),t=await this.scope.connection.getMinimumBalanceForRentExemption(tN.p0.span),n=tu.yc.createAccountWithSeed({fromPubkey:u,basePubkey:u,seed:e.seed,newAccountPubkey:e.publicKey,lamports:t+Number(null!=(i=null==(r=a.amount)?void 0:r.toString())?i:0),space:tN.p0.span,programId:f});return g.instructions.push(n,o5({mint:o,tokenAccount:e.publicKey,owner:this.scope.ownerPubKey,programId:f})),g.instructionTypes.push(iw.CreateAccount),g.instructionTypes.push(iw.InitAccount),c||(g.endInstructions.push(o8({owner:u,payer:a.payer||u,tokenAccount:e.publicKey,programId:f})),g.endInstructionTypes.push(iw.CloseAccount)),{account:e.publicKey,instructionParams:g}}}async checkOrCreateAta({mint:e,programId:t=td.H_,autoUnwrapWSOLToSOL:n}){var r;await this.fetchWalletTokenAccounts();let i=null==(r=this.scope.account.tokenAccounts.find(({mint:t})=>(null==t?void 0:t.toBase58())===e.toBase58()))?void 0:r.publicKey,o=this.scope.ownerPubKey,a={};if(!i){let n=this.getAssociatedTokenAccount(e,t),r=await tL(o,n,o,e,t);a.instructions=[r],a.instructionTypes=[iw.CreateATA],i=n}return n&&r7.toBase58()===e.toBase58()&&(a.endInstructions=[o8({owner:o,payer:o,tokenAccount:i,programId:t})],a.endInstructionTypes=[iw.CloseAccount]),{pubKey:i,newInstructions:a}}async handleTokenAccount(e){let{side:t,amount:n,mint:r,programId:i=td.H_,tokenAccount:o,payer:a=this.scope.ownerPubKey,bypassAssociatedCheck:s,skipCloseAccount:u,checkCreateATAOwner:l}=e,c=this.getAssociatedTokenAccount(r,i);if(new tu.nh(r7).equals(r)){let e=await o9({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:a,amount:n,skipCloseAccount:u});return t0({tokenAccount:e.addresses.newAccount},e)}if(!o||"out"===t&&!c.equals(o)&&!s){let e=[],t=tL(this.scope.ownerPubKey,c,this.scope.ownerPubKey,r,i);if(l){let n=await this.scope.connection.getAccountInfo(c);if(null===n)e.push(t);else if(!(n.owner.equals(td.H_)&&tN.p0.decode(n.data).mint.equals(r)&&tN.p0.decode(n.data).owner.equals(this.scope.ownerPubKey)))throw Error(`create ata check error -> mint: ${r.toString()}, ata: ${c.toString()}`)}else e.push(t);return{tokenAccount:c,instructions:e,instructionTypes:[iw.CreateATA]}}return{tokenAccount:o}}async processTokenAccount(e){let{mint:t,programId:n=td.H_,amount:r,useSOLBalance:i,handleTokenAccount:o}=e,a,s=this.createTxBuilder();if(t.equals(new tu.nh(r7))&&i){let e=await this.handleTokenAccount({side:"in",amount:r||0,mint:t,bypassAssociatedCheck:!0,programId:n}),{tokenAccount:i}=e,o=t2(e,["tokenAccount"]);a=i,s.addInstruction(o)}else if(!(a=await this.getCreatedTokenAccount({mint:t,associatedOnly:!1,programId:n}))&&o){let e=await this.scope.account.handleTokenAccount({side:"in",amount:0,mint:t,bypassAssociatedCheck:!0,programId:n}),{tokenAccount:r}=e,i=t2(e,["tokenAccount"]);a=r,s.addInstruction(i)}return t0({tokenAccount:a},s.AllTxData)}},ae=o2([o$("instruction")]),at=o2([o$("instruction")]),an=o2([oH("rewardState"),oH("rewardOpenTime"),oH("rewardEndTime"),oH("rewardLastUpdateTime"),oH("totalReward"),oH("totalRewardEmissioned"),oH("rewardClaimed"),oH("rewardPerSecond"),oG("accRewardPerShare"),oX("rewardVault"),oX("rewardMint"),oX("rewardSender"),oH("rewardType"),o6(oH(),15,"padding")]),ar=o2([oH("state"),oH("nonce"),oX("lpVault"),oX("rewardVault"),oX(),oX(),oH(),oH(),oH("totalReward"),oG("perShareReward"),oH("lastSlot"),oH("perSlotReward")]),ai=o2([oH("state"),oH("nonce"),oX("lpVault"),oX("rewardVaultA"),oH("totalRewardA"),oG("perShareRewardA"),oH("perSlotRewardA"),o$("option"),oX("rewardVaultB"),oU(7),oH("totalRewardB"),oG("perShareRewardB"),oH("perSlotRewardB"),oH("lastSlot"),oX()]),ao=o2([oH(),oH("state"),oH("nonce"),oH("validRewardTokenNum"),oG("rewardMultiplier"),oH("rewardPeriodMax"),oH("rewardPeriodMin"),oH("rewardPeriodExtend"),oX("lpMint"),oX("lpVault"),o6(an,5,"rewardInfos"),oX("creator"),oX(),o6(oH(),32,"padding")]),aa=new Proxy(ar,{get:(e,t,n)=>"decode"===t?(...t)=>{let n=e.decode(...t);return t1(t0({},n),{version:3,rewardInfos:[{rewardVault:n.rewardVault,totalReward:n.totalReward,perSlotReward:n.perSlotReward,perShareReward:n.perShareReward}]})}:Reflect.get(e,t,n)}),as=new Proxy(ai,{get:(e,t,n)=>"decode"===t?(...t)=>{let n=e.decode(...t);return t1(t0({},n),{version:5,rewardInfos:[{rewardVault:n.rewardVaultA,totalReward:n.totalRewardA,perSlotReward:n.perSlotRewardA,perShareReward:n.perShareRewardA},{rewardVault:n.rewardVaultB,totalReward:n.totalRewardB,perSlotReward:n.perSlotRewardB,perShareReward:n.perShareRewardB}]})}:Reflect.get(e,t,n)}),au=new Proxy(ao,{get:(e,t,n)=>"decode"===t?(...t)=>{let n=e.decode(...t);return t1(t0({},n),{version:6,rewardInfos:n.rewardInfos.map(e=>{var t;return t1(t0({},e),{rewardType:(null!=(t=Object.entries(aS).find(t=>String(t[1])===e.rewardType.toString()))?t:["Standard SPL"])[0]})})})}:Reflect.get(e,t,n)}),al=o2([oH("isSet"),oH("rewardPerSecond"),oH("rewardOpenTime"),oH("rewardEndTime"),oH("rewardType")]),ac=o2([o$("instruction"),oH("nonce"),o6(al,5,"rewardTimeInfo")]),ad=o2([o$("instruction"),oH("rewardReopenTime"),oH("rewardEndTime"),oH("rewardPerSecond")]),ap=o2([o$("instruction"),oH("isSet"),oH("rewardPerSecond"),oH("rewardOpenTime"),oH("rewardEndTime"),oH("rewardType")]),af=(o2([oH("state"),oX("id"),oX("owner"),oH("deposited"),o6(oH(),1,"rewardDebts")]),o2([oH("state"),oX("id"),oX("owner"),oH("deposited"),o6(oG(),1,"rewardDebts"),oH(""),oH("voteLockedBalance"),o6(oH(),15)])),ah=(o2([oH("state"),oX("id"),oX("owner"),oH("deposited"),o6(oH(),2,"rewardDebts")]),o2([oH("state"),oX("id"),oX("owner"),oH("deposited"),o6(oG(),2,"rewardDebts"),o6(oH(),17)])),am=o2([oH(),oH("state"),oX("id"),oX("owner"),oH("deposited"),o6(oG(),5,"rewardDebts"),o6(oH(),16)]),ag=o2([o$("instruction"),oH("amount")]),ay=o2([oX("mint"),oX("grantAuthority"),oH("baselineVoteWeightScaledFactor"),oH("maxExtraLockupVoteWeightScaledFactor"),oH("lockupSaturationSecs"),new oV(1,!0,"digitShift"),o6(o$(),7,"reserved1"),o6(oH(),7,"reserved2")]),ab=(o2([oU(8),oX("governanceProgramId"),oX("realm"),oX("realmGoverningTokenMint"),oX("realmAuthority"),o6(o$(),32,"reserved1"),o6(ay,4,"votingMints"),oZ("timeOffset"),o$("bump"),o6(o$(),7,"reserved2"),o6(oH(),11,"reserved3")]),o2([oZ("startTime"),oZ("endTime"),o$("kind"),o6(o$(),15,"reserved")])),a_=o2([o6(ab,1,"lockup"),oH("amountDeposited_native"),oH("amountInitiallyLockedNative"),oQ("isUsed"),oQ("allowClawback"),o$("votingMintConfigIdx"),o6(o$(),29,"reserved")]);o2([oU(8),oX("voterAuthority"),oX("registrar"),o6(a_,32,"deposits"),o$("voterBump"),o$("voterWweightRecordBump"),o6(o$(),94,"reserved")]),t8("Raydium_farm_config");var av=new tu.nh("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),aw=new tu.nh("FrspKwj8i3pNmKwXreTveC4fu7KL5ZbGeXdZBe2XViu1"),ak={3:af,5:ah,6:am},ax=e=>-1!==[3,4,5,6].indexOf(e),aA=e=>{var t;let{version:n,rewardInfos:r,rewardTokenAccountsPublicKeys:i}=e,o=`rewardInfo:${JSON.stringify(r)}, rewardAccount:${JSON.stringify(i)}`,a={3:()=>{if(1!==r.length||1!==i.length)return`rewardInfos or rewardTokenAccounts lengths not equal 1: ${o}`},5:()=>{if(r.length!==i.length)return`rewardInfos and rewardTokenAccounts lengths not equal: ${o}`},6:()=>{if(!i.length||r.length!==i.length)return`no rewardTokenAccounts or rewardInfos and rewardTokenAccounts lengths not equal: ${o}`}};return null==(t=a[n])?void 0:t.call(a)},aS={"Standard SPL":0,"Option tokens":1},aI={[iD.toString()]:3,[iF.toString()]:4,[iq.toString()]:5,[ij.toString()]:6},aT=t8("Raydium.farm.util");function aE({programId:e,poolId:t,mint:n,type:r}){let{publicKey:i}=iP([t.toBuffer(),n.toBuffer(),tK.from("lpVault"===r?"lp_vault_associated_seed":"rewardVault"===r?"reward_vault_associated_seed":"","utf-8")],e);return i}function aP({programId:e,poolId:t,owner:n,version:r}){let{publicKey:i}=iP([t.toBuffer(),n.toBuffer(),tK.from(6===r?"farmer_info_associated_seed":"staker_info_v2_associated_seed","utf-8")],e);return i}var aC=({programId:e,poolId:t})=>iP([t.toBuffer()],e);function aO(e){return rN(e.endTime).sub(rN(e.openTime)).mul(rN(e.perSecond))}function aB(e){let t=ak[e];return t||aT.logWithError("invalid version",e),t}var aM=t8("Raydium_farm_instruction");function aR(e){let{version:t,id:n,ledger:r,programId:i,owner:o}=e,a={3:9,5:10}[t];a||aM.logWithError(`invalid farm pool version: ${t}`);let s=tK.alloc(ae.span);ae.encode({instruction:a},s);let u=[rY({pubkey:n}),rY({pubkey:r}),rY({pubkey:o,isWritable:!1}),rY({pubkey:tu.yc.programId,isWritable:!1}),rY({pubkey:tu.ze,isWritable:!1})];return{instruction:new tu.Sl({programId:i,keys:u,data:s}),instructionType:iw.FarmV3CreateLedger}}function aL({payer:e,rewardVault:t,userRewardTokenPub:n,farmKeys:r,rewardInfo:i}){let o=tK.alloc(ad.span);ad.encode({instruction:3,rewardReopenTime:rN(i.openTime),rewardEndTime:rN(i.endTime),rewardPerSecond:rN(i.perSecond)},o);let a=[rY({pubkey:td.H_,isWritable:!1}),rY({pubkey:r.id}),rY({pubkey:r.lpVault,isWritable:!1}),rY({pubkey:t}),rY({pubkey:n}),rY({pubkey:e,isWritable:!1,isSigner:!0})];return new tu.Sl({programId:r.programId,keys:a,data:o})}function aN({payer:e,userRewardTokenPub:t,farmKeys:n,rewardVault:r,rewardInfo:i}){let o=tK.alloc(ap.span);ap.encode({instruction:4,isSet:new(tb())(1),rewardPerSecond:rN(i.perSecond),rewardOpenTime:rN(i.openTime),rewardEndTime:rN(i.endTime),rewardType:rN(aS[i.rewardType])},o);let a=[...rX,rY({pubkey:n.id}),rY({pubkey:n.authority,isWritable:!1}),rY({pubkey:i.mint,isWritable:!1}),rY({pubkey:r}),rY({pubkey:t}),rY({pubkey:e,isWritable:!1,isSigner:!0})];return new tu.Sl({programId:n.programId,keys:a,data:o})}function aD(e){let{farmInfo:t,farmKeys:n,lpAccount:r,rewardAccounts:i,owner:o,amount:a}=e,[s,u]=[new tu.nh(t.programId),new tu.nh(t.id)],l=aP({programId:s,poolId:u,owner:o,version:6}),c=tK.alloc(ag.span);ag.encode({instruction:2,amount:rN(a)},c);let d=[rY({pubkey:td.H_,isWritable:!1}),rY({pubkey:u}),rY({pubkey:new tu.nh(n.authority),isWritable:!1}),rY({pubkey:new tu.nh(n.lpVault)}),rY({pubkey:l}),rY({pubkey:o,isWritable:!1,isSigner:!0}),rY({pubkey:r})];for(let e=0;e=e.endTime&&this.logAndCreateError("start time error","rewardInfo.rewardOpenTime",e.openTime.toString()),isNaN(aS[e.rewardType])&&this.logAndCreateError("rewardType error",e.rewardType),0>=Number(e.perSecond)&&this.logAndCreateError("rewardPerSecond error",e.perSecond),f.push((m=e,{isSet:new(tb())(1),rewardPerSecond:rN(m.perSecond),rewardOpenTime:rN(m.openTime),rewardEndTime:rN(m.endTime),rewardType:rN(aS[m.rewardType])}));let{rewardPubKey:t,newInstruction:n}=await this._getUserRewardInfo({rewardInfo:e,payer:s});n&&a.addInstruction(n),t||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts);let r=e.mint.equals(ie)?new tu.nh(rZ.address):e.mint;h.push({rewardMint:r,rewardVault:aE({programId:o.programId,poolId:u.publicKey,mint:r,type:"rewardVault"}),userRewardToken:t})}let{account:g,instructionParams:y}=await this.scope.account.getOrCreateTokenAccount({mint:new tu.nh(o.lockInfo.lockMint),owner:this.scope.ownerPubKey,skipCloseAccount:!1,createInfo:{payer:this.scope.ownerPubKey,amount:0},associatedOnly:!1});y&&a.addInstruction(y),g||this.logAndCreateError("cannot found lock vault","tokenAccounts",this.scope.account.tokenAccounts);let{instruction:b,instructionType:_}=function(e){var t;let n=tK.alloc(ac.span);ac.encode({instruction:0,nonce:new(tb())(e.nonce),rewardTimeInfo:e.rewardInfoConfig},n);let r=[...rX,rY({pubkey:e.farmId}),rY({pubkey:e.farmAuthority,isWritable:!1}),rY({pubkey:e.lpVault}),rY({pubkey:e.lpMint,isWritable:!1}),rY({pubkey:e.lockVault}),rY({pubkey:e.lockMint,isWritable:!1}),rY({pubkey:null!=(t=e.lockUserAccount)?t:ie}),rY({pubkey:e.owner,isWritable:!1,isSigner:!0})];for(let t of e.rewardInfo)r.push(rY({pubkey:t.rewardMint,isWritable:!1}),rY({pubkey:t.rewardVault}),rY({pubkey:t.userRewardToken}));return{instruction:new tu.Sl({programId:e.programId,keys:r,data:n}),instructionType:iw.FarmV6Create}}({farmId:u.publicKey,owner:this.scope.ownerPubKey,farmAuthority:c,lpVault:p,lpMint:o.lpMint,lockVault:o.lockInfo.lockVault,lockMint:o.lockInfo.lockMint,lockUserAccount:g,programId:o.programId,rewardInfo:h,rewardInfoConfig:f,nonce:d});return a.addInstruction({instructions:[b],instructionTypes:[_]}).versionBuild({txVersion:i,extInfo:{farmId:u.publicKey,farmAuthority:c,lpVault:p,lockUserAccount:g,nonce:d}})}async restartReward({farmInfo:e,payer:t,newRewardInfo:n,txVersion:r}){var i;let o=aI[e.programId];6!==o&&this.logAndCreateError("invalid farm version ",o);let a=ip((await this.scope.api.fetchFarmKeysById({ids:e.id}))[0]),s={id:a.id,rewardInfos:e.rewardInfos,lpVault:a.lpVault,programId:a.programId};n.openTime>=n.endTime&&this.logAndCreateError("start time error","newRewardInfo",n);let u=t||this.scope.ownerPubKey,l=n.mint.equals(ie)?new tu.nh(rZ.address):n.mint,c=s.rewardInfos.findIndex(e=>new tu.nh(e.mint.address).equals(l)),d=a.rewardInfos[c];d||this.logAndCreateError("configuration does not exist","rewardMint",l);let p=null!=(i=d.vault)?i:ie,f=this.createTxBuilder(),{rewardPubKey:h,newInstruction:m}=await this._getUserRewardInfo({rewardInfo:n,payer:u});return m&&f.addInstruction(m),h||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts),f.addInstruction({instructions:[aL({payer:this.scope.ownerPubKey,rewardVault:p,userRewardTokenPub:h,farmKeys:s,rewardInfo:n})],instructionTypes:[iw.FarmV6Restart]}).versionBuild({txVersion:r})}async restartRewards({farmInfo:e,payer:t,newRewardInfos:n,txVersion:r}){var i;let o=aI[e.programId];6!==o&&this.logAndCreateError("invalid farm version ",o);let a=ip((await this.scope.api.fetchFarmKeysById({ids:e.id}))[0]),s={id:a.id,rewardInfos:e.rewardInfos,lpVault:a.lpVault,programId:a.programId};n.forEach(e=>{e.openTime>=e.endTime&&this.logAndCreateError("start time error","newRewardInfo",e)});let u=t||this.scope.ownerPubKey,l=this.createTxBuilder();for(let e of n){let t=e.mint.equals(ie)?new tu.nh(rZ.address):e.mint,n=s.rewardInfos.findIndex(e=>new tu.nh(e.mint.address).equals(t)),r=a.rewardInfos[n];r||this.logAndCreateError("configuration does not exist","rewardMint",t);let o=null!=(i=r.vault)?i:ie,{rewardPubKey:c,newInstruction:d}=await this._getUserRewardInfo({rewardInfo:e,payer:u});d&&l.addInstruction(d),c||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts);let p=aL({payer:this.scope.ownerPubKey,rewardVault:o,userRewardTokenPub:c,farmKeys:s,rewardInfo:e});l.addInstruction({instructions:[p],instructionTypes:[iw.FarmV6Restart]})}return l.versionBuild({txVersion:r})}async addNewRewardToken(e){let{txVersion:t,farmInfo:n,newRewardInfo:r,payer:i}=e,o=aI[n.programId];6!==o&&this.logAndCreateError("invalid farm version ",o);let a=ip((await this.scope.api.fetchFarmKeysById({ids:n.id}))[0]),s=null!=i?i:this.scope.ownerPubKey,u=this.createTxBuilder(),l=r.mint.equals(ie)?new tu.nh(rZ.address):r.mint,c=aE({programId:new tu.nh(n.programId),poolId:new tu.nh(n.id),mint:l,type:"rewardVault"}),{rewardPubKey:d,newInstruction:p}=await this._getUserRewardInfo({rewardInfo:r,payer:s});return p&&u.addInstruction(p),d||this.logAndCreateError("annot found target token accounts",this.scope.account.tokenAccounts),r.mint=l,u.addInstruction({instructions:[aN({payer:this.scope.ownerPubKey,userRewardTokenPub:d,farmKeys:a,rewardVault:c,rewardInfo:r})],instructionTypes:[iw.FarmV6CreatorAddReward]}).versionBuild({txVersion:t})}async addNewRewardsToken(e){let{txVersion:t,farmInfo:n,newRewardInfos:r,payer:i}=e,o=aI[n.programId];6!==o&&this.logAndCreateError("invalid farm version ",o);let a=ip((await this.scope.api.fetchFarmKeysById({ids:n.id}))[0]),s=null!=i?i:this.scope.ownerPubKey,u=this.createTxBuilder();for(let e of r){let t=e.mint.equals(ie)?new tu.nh(rZ.address):e.mint,r=aE({programId:new tu.nh(n.programId),poolId:new tu.nh(n.id),mint:t,type:"rewardVault"}),{rewardPubKey:i,newInstruction:o}=await this._getUserRewardInfo({rewardInfo:e,payer:s});o&&u.addInstruction(o),i||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts);let l=aN({payer:this.scope.ownerPubKey,userRewardTokenPub:i,farmKeys:a,rewardVault:r,rewardInfo:t1(t0({},e),{mint:t})});u.addInstruction({instructions:[l],instructionTypes:[iw.FarmV6CreatorAddReward]})}return u.versionBuild({txVersion:t})}async deposit(e){let{txVersion:t,farmInfo:n,amount:r,feePayer:i,useSOLBalance:o,associatedOnly:a=!0,checkCreateATAOwner:s=!1,userAuxiliaryLedgers:u,computeBudgetConfig:l}=e;!1===this.scope.availability.addFarm&&this.logAndCreateError("farm deposit feature disabled in your region");let{rewardInfos:c,programId:d}=n,p=aI[d];4===p&&this.logAndCreateError("V4 has suspended deposits:",n.programId),ax(p)||this.logAndCreateError("invalid farm program:",n.programId);let[f,h]=[new tu.nh(n.programId),new tu.nh(n.id)],m=(await this.scope.api.fetchFarmKeysById({ids:n.id}))[0],g=aP({programId:f,poolId:h,owner:this.scope.ownerPubKey,version:p}),y=this.createTxBuilder();y.addCustomComputeBudget(l);let b={};for(let e of this.scope.account.tokenAccounts)if(a){let t=iN(this.scope.ownerPubKey,e.mint,e.programId).publicKey;e.publicKey&&t.equals(e.publicKey)&&(b[e.mint.toString()]=e.publicKey)}else b[e.mint.toString()]=e.publicKey;let _=b[m.lpMint.address];_||this.logAndCreateError("you don't have any lp","lp zero",b);let v=[];for(let e of c){let t=o&&e.mint.address===r7.toString(),n=b[e.mint.address];if(!n){let{account:r,instructionParams:o}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mint.programId,mint:new tu.nh(e.mint.address),notUseTokenAccount:t,createInfo:{payer:i||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!t,associatedOnly:!t&&a,checkCreateATAOwner:s});n=r,o&&y.addInstruction(o)}b[e.mint.address]=n,v.push(n)}let w,k=await this.scope.connection.getAccountInfo(g);if(k&&(w=aB(p).decode(k.data)),n.programId!==ij.toString()&&!w){let{instruction:e,instructionType:t}=aR({id:h,programId:f,version:p,ledger:g,owner:this.scope.ownerPubKey});y.addInstruction({instructions:[e],instructionTypes:[t]})}let x=aA({version:p,rewardInfos:c,rewardTokenAccountsPublicKeys:v});x&&this.logAndCreateError(x);let A={amount:rN(r),owner:this.scope.ownerPubKey,farmInfo:n,farmKeys:m,lpAccount:_,rewardAccounts:v,userAuxiliaryLedgers:null==u?void 0:u.map(e=>new tu.nh(e))},S=6===p?function(e){let{farmInfo:t,farmKeys:n,lpAccount:r,rewardAccounts:i,owner:o,amount:a}=e,[s,u]=[new tu.nh(t.programId),new tu.nh(t.id)],l=aP({programId:s,poolId:u,owner:o,version:6}),c=tK.alloc(ag.span);ag.encode({instruction:1,amount:rN(a)},c);let d=[rY({pubkey:td.H_,isWritable:!1}),rY({pubkey:tu.yc.programId,isWritable:!1}),rY({pubkey:u}),rY({pubkey:new tu.nh(n.authority),isWritable:!1}),rY({pubkey:new tu.nh(n.lpVault)}),rY({pubkey:l}),rY({pubkey:o,isWritable:!1,isSigner:!0}),rY({pubkey:r})];for(let e=0;enew tu.nh(e))},k=6===p?aD(w):5===p?aF(w):4===p?function(e){let{farmInfo:t,farmKeys:n,lpAccount:r,rewardAccounts:i,owner:o,amount:a,userAuxiliaryLedgers:s}=e,[u,l]=[new tu.nh(t.programId),new tu.nh(t.id)],c=o2([o$("instruction"),oH("amount")]),d=[rY({pubkey:l}),rY({pubkey:new tu.nh(n.authority),isWritable:!1}),rY({pubkey:s[0]}),rY({pubkey:o,isSigner:!0,isWritable:!1}),rY({pubkey:r}),rY({pubkey:new tu.nh(n.lpVault)}),rY({pubkey:i[0]}),rY({pubkey:new tu.nh(n.rewardInfos[0].vault)}),rY({pubkey:tu.Am,isWritable:!1}),rY({pubkey:td.H_,isWritable:!1}),rY({pubkey:i[1]}),rY({pubkey:new tu.nh(n.rewardInfos[1].vault)})],p=tK.alloc(c.span);return c.encode({instruction:2,amount:a},p),new tu.Sl({keys:d,programId:u,data:p})}(w):aq(w),x={3:iw.FarmV3Withdraw,4:iw.FarmV4Withdraw,5:iw.FarmV5Withdraw,6:iw.FarmV6Withdraw};return h.addInstruction({instructions:[k],instructionTypes:[x[p]]}).versionBuild({txVersion:t})}async withdrawFarmReward({farmInfo:e,withdrawMint:t,txVersion:n,computeBudgetConfig:r}){var i,o;let a,s;this.scope.checkOwner();let u=ip((await this.scope.api.fetchFarmKeysById({ids:e.id}))[0]),l=aI[e.programId];6!==l&&this.logAndCreateError("invalid farm version",l);let c=u.rewardInfos.find(e=>it(e.mint.address).equals(it(t)));c||this.logAndCreateError("withdraw mint error","rewardInfos",e);let d=null!=(i=null==c?void 0:c.vault)?i:ie,p=this.createTxBuilder(),f;if(t.equals(ie)||t.equals(tu.nh.default)){let e=await o9({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:this.scope.ownerPubKey,amount:aO(t1(t0({},c),{openTime:c.openTime,endTime:c.endTime,perSecond:new rM(c.perSecond).mul(10**c.mint.decimals).toString()}))});f=e.addresses.newAccount,p.addInstruction(e)}else{let e=await this.scope.account.getCreatedTokenAccount({mint:t});null===e?(f=await this.scope.account.getAssociatedTokenAccount(t),p.addInstruction({instructions:[tL(this.scope.ownerPubKey,f,this.scope.ownerPubKey,t)],instructionTypes:[iw.CreateATA]})):f=e}let{instruction:h,instructionType:m}=(o={programId:u.programId,id:u.id,authority:u.authority,lpVault:u.lpVault,rewardVault:d,userRewardToken:f,owner:this.scope.ownerPubKey},a=tK.alloc(at.span),at.encode({instruction:5},a),s=[rY({pubkey:td.H_,isWritable:!1}),rY({pubkey:o.id}),rY({pubkey:o.authority,isWritable:!1}),rY({pubkey:o.lpVault,isWritable:!1}),rY({pubkey:o.rewardVault}),rY({pubkey:o.userRewardToken}),rY({pubkey:o.owner,isWritable:!1,isSigner:!0})],{instruction:new tu.Sl({programId:o.programId,keys:s,data:a}),instructionType:iw.FarmV6CreatorWithdraw});return p.addCustomComputeBudget(r),p.addInstruction({instructions:[h],instructionTypes:[m]}).versionBuild({txVersion:n})}async harvestAllRewards(e){let{farmInfoList:t,useSOLBalance:n,feePayer:r,associatedOnly:i=!0,checkCreateATAOwner:o=!1,userAuxiliaryLedgers:a,txVersion:s,computeBudgetConfig:u}=e,l=this.createTxBuilder(),c={};for(let e of this.scope.account.tokenAccounts)if(i){let t=iN(this.scope.ownerPubKey,e.mint).publicKey;e.publicKey&&t.equals(e.publicKey)&&(c[e.mint.toString()]=e.publicKey)}else c[e.mint.toString()]=e.publicKey;let d=(await this.scope.api.fetchFarmKeysById({ids:Object.values(t).map(e=>e.id).join(",")})).reduce((e,t)=>t1(t0({},e),{[t.id]:t}),{});for(let e of Object.values(t)){let{programId:t,lpMint:s,rewardInfos:u,id:p}=e,f=aI[t],h=s.address,m=n&&h===r7.toString(),g=c[h];if(!g){let{account:e,instructionParams:t}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:s.programId,mint:new tu.nh(h),notUseTokenAccount:m,createInfo:{payer:r||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!0,associatedOnly:!m&&i,checkCreateATAOwner:o});g=e,t&&l.addInstruction(t)}c[h.toString()]=g;let y=[];for(let e of u){let t=n&&e.mint.address===r7.toString(),a=c[e.mint.address];if(!a){let{account:n,instructionParams:s}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mint.programId,mint:new tu.nh(e.mint.address),notUseTokenAccount:t,createInfo:{payer:r||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!t,associatedOnly:!t&&i,checkCreateATAOwner:o});a=n,s&&l.addInstruction(s)}c[e.mint.address]=a,y.push(a)}let b=d[p],_={amount:ih,owner:this.scope.ownerPubKey,farmInfo:e,farmKeys:b,lpAccount:g,rewardAccounts:y,userAuxiliaryLedgers:null==a?void 0:a.map(e=>new tu.nh(e))},v=6===f?aD(_):5===f?aF(_):aq(_),w={3:iw.FarmV3Withdraw,5:iw.FarmV5Withdraw,6:iw.FarmV6Withdraw};l.addInstruction({instructions:[v],instructionTypes:[w[f]]})}return 1===s?l.sizeCheckBuild({computeBudgetConfig:u}):l.sizeCheckBuildV0({computeBudgetConfig:u})}},aU=new(tb())(0),az=new(tb())(1),aV=new(tb())(-1),aW=new(tb())(1).shln(64),a$=new(tb())(1).shln(128),aK=aW.sub(az),aH=a$.subn(1),aG=new(tb())("4295048016"),aZ=new(tb())("79226673521066979257578248091"),aY=new(tb())("4295048017"),aX=new(tb())("79226673521066979257578248090"),aQ=new(tb())(10).pow(new(tb())(6)),aJ=((c=aJ||{})[c.rate_500=500]="rate_500",c[c.rate_3000=3e3]="rate_3000",c[c.rate_10000=1e4]="rate_10000",c),a0={tvl:0,volumeQuote:0,mintAmountA:0,mintAmountB:0,rewardDefaultInfos:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0,day:{volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[0]},week:{volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[0]},month:{volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[0]},pooltype:[]};function a1(e){let t=new ArrayBuffer(4);return new DataView(t).setInt32(0,e,!1),new Uint8Array(t)}function a2(e,t){let n=0;for(let r=e-1;r>=0&&!t.testn(r);r--)n++;return n}function a6(e,t){let n=0;for(let r=0;r=t.tick?(r=t.feeGrowthOutsideX64A,i=t.feeGrowthOutsideX64B):(r=e.feeGrowthGlobalX64A.sub(t.feeGrowthOutsideX64A),i=e.feeGrowthGlobalX64B.sub(t.feeGrowthOutsideX64B));let o=new(tb())(0),a=new(tb())(0);return e.tickCurrentnull!==e?sN.decode(e.data):null),d={};for(let e=0;e0?{isExist:!0,nextStartIndex:a[0]}:{isExist:!1,nextStartIndex:0}}static firstInitializedTickInOneArray(e,t,n,r){let i;if(r){let e=sS-1;for(;e>=0;){let t=n.ticks[e];if(t.liquidityGross.gtn(0)){i=t;break}e-=1}}else{let e=0;for(;e=0;){let e=l.ticks[u];if(e.liquidityGross.gtn(0)){a=e;break}u-=1}else for(u+=1;u443636)&&e==sT.getTickArrayStartIndexByTick(-443636,t):e%this.tickCount(t)==0}static tickCount(e){return sS*e}},sh=class{static maxTickInTickarrayBitmap(e){return e*sS*sI}static getBitmapTickBoundary(e,t){let n=this.maxTickInTickarrayBitmap(t),r=Math.floor(Math.abs(e)/n);e<0&&Math.abs(e)%n!=0&&(r+=1);let i=n*r;return e<0?{minValue:-i,maxValue:-i+n}:{minValue:i,maxValue:i+n}}static nextInitializedTickArrayStartIndex(e,t,n,r){var i,o;if(!sf.checkIsValidStartIndex(t,n))throw Error("nextInitializedTickArrayStartIndex check error");let a=this.maxTickInTickarrayBitmap(n),s=r?t-sf.tickCount(n):t+sf.tickCount(n);if(s<-a||s>=a)return{isInit:!1,tickIndex:t};let u=n*sS,l=s/u+512;s<0&&s%u!=0&&l--;let c=Math.abs(l);if(r){let t=a3(1024,i=e.shln(1024-c-1))?null:a2(1024,i);return null!==t?{isInit:!0,tickIndex:(c-t-512)*u}:{isInit:!1,tickIndex:-a}}{let t=a3(1024,o=e.shrn(c))?null:a6(1024,o);return null!==t?{isInit:!0,tickIndex:(c+t-512)*u}:{isInit:!1,tickIndex:a-sf.tickCount(n)}}}},sm=class{static getBitmapOffset(e,t){if(!sf.checkIsValidStartIndex(e,t))throw Error("No enough initialized tickArray");this.checkExtensionBoundary(e,t);let n=sh.maxTickInTickarrayBitmap(t),r=Math.floor(Math.abs(e)/n)-1;return e<0&&Math.abs(e)%n==0&&r--,r}static getBitmap(e,t,n){let r=this.getBitmapOffset(e,t);return e<0?{offset:r,tickarrayBitmap:n.negativeTickArrayBitmap[r]}:{offset:r,tickarrayBitmap:n.positiveTickArrayBitmap[r]}}static checkExtensionBoundary(e,t){let{positiveTickBoundary:n,negativeTickBoundary:r}=this.extensionTickBoundary(t);if(e>=r&&e InvalidTickArrayBoundary")}static extensionTickBoundary(e){let t=sh.maxTickInTickarrayBitmap(e),n=-t;if(443636<=t)throw Error(`extensionTickBoundary check error: 443636, ${t}`);if(n<=-443636)throw Error(`extensionTickBoundary check error: ${n}, -443636`);return{positiveTickBoundary:t,negativeTickBoundary:n}}static checkTickArrayIsInit(e,t,n){let{tickarrayBitmap:r}=this.getBitmap(e,t,n),i=this.tickArrayOffsetInBitmap(e,t);return{isInitialized:sT.mergeTickArrayBitmap(r).testn(i),startIndex:e}}static nextInitializedTickArrayFromOneBitmap(e,t,n,r){let i=sf.tickCount(t),o=n?e-i:e+i,{tickarrayBitmap:a}=this.getBitmap(o,t,r);return this.nextInitializedTickArrayInBitmap(a,o,t,n)}static nextInitializedTickArrayInBitmap(e,t,n,r){let{minValue:i,maxValue:o}=sh.getBitmapTickBoundary(t,n),a=this.tickArrayOffsetInBitmap(t,n);if(r){let r=sT.mergeTickArrayBitmap(e).shln(sI-1-a),o=a3(512,r)?null:a2(512,r);return null!==o?{isInit:!0,tickIndex:t-o*sf.tickCount(n)}:{isInit:!1,tickIndex:i}}{let r=sT.mergeTickArrayBitmap(e).shrn(a),i=a3(512,r)?null:a6(512,r);return null!==i?{isInit:!0,tickIndex:t+i*sf.tickCount(n)}:{isInit:!1,tickIndex:o-sf.tickCount(n)}}}static tickArrayOffsetInBitmap(e,t){let n=Math.abs(e)%sh.maxTickInTickarrayBitmap(t),r=Math.floor(n/sf.tickCount(t));return e<0&&0!=n&&(r=sI-r),r}},sg=class{static getOutputAmountAndRemainAccounts(e,t,n,r,i,o=!1){let a=n.toBase58()===e.mintA.address,s=[],{isExist:u,startIndex:l,nextAccountMeta:c}=this.getFirstInitializedTickArray(e,a);if(!u||void 0===l||!c)throw Error("Invalid tick array");s.push(c);let{allTrade:d,amountCalculated:p,accounts:f,sqrtPriceX64:h,feeAmount:m}=sA.swapCompute(e.programId,e.id,t,e.tickArrayBitmap,e.exBitmapInfo,a,e.ammConfig.tradeFeeRate,e.liquidity,e.tickCurrent,e.tickSpacing,e.sqrtPriceX64,r,l,i,o);return s.push(...f),{allTrade:d,expectedAmountOut:p.mul(aV),remainingAccounts:s,executionPrice:h,feeAmount:m}}static getInputAmountAndRemainAccounts(e,t,n,r,i){let o=n.toBase58()===e.mintB.address,a=[],{isExist:s,startIndex:u,nextAccountMeta:l}=this.getFirstInitializedTickArray(e,o);if(!s||void 0===u||!l)throw Error("Invalid tick array");try{let t=this.preInitializedTickArrayStartIndex(e,o);if(t.isExist){let{publicKey:n}=si(e.programId,e.id,t.nextStartIndex);a.push(n)}}catch{}a.push(l);let{amountCalculated:c,accounts:d,sqrtPriceX64:p,feeAmount:f}=sA.swapCompute(e.programId,e.id,t,e.tickArrayBitmap,e.exBitmapInfo,o,e.ammConfig.tradeFeeRate,e.liquidity,e.tickCurrent,e.tickSpacing,e.sqrtPriceX64,r.mul(aV),u,i);return a.push(...d),{expectedAmountIn:c,remainingAccounts:a,executionPrice:p,feeAmount:f}}static getFirstInitializedTickArray(e,t){let{isInitialized:n,startIndex:r}=sg.isOverflowDefaultTickarrayBitmap(e.tickSpacing,[e.tickCurrent])?sm.checkTickArrayIsInit(sf.getArrayStartIndex(e.tickCurrent,e.tickSpacing),e.tickSpacing,e.exBitmapInfo):sT.checkTickArrayIsInitialized(sT.mergeTickArrayBitmap(e.tickArrayBitmap),e.tickCurrent,e.tickSpacing);if(n){let{publicKey:t}=si(e.programId,e.id,r);return{isExist:!0,startIndex:r,nextAccountMeta:t}}let{isExist:i,nextStartIndex:o}=this.nextInitializedTickArrayStartIndex(e,sf.getArrayStartIndex(e.tickCurrent,e.tickSpacing),t);if(i){let{publicKey:t}=si(e.programId,e.id,o);return{isExist:!0,startIndex:o,nextAccountMeta:t}}return{isExist:!1,nextAccountMeta:void 0,startIndex:void 0}}static preInitializedTickArrayStartIndex(e,t){let n=Math.floor(e.tickCurrent/sf.tickCount(e.tickSpacing)),r=t?sT.searchHightBitFromStart(e.tickArrayBitmap,e.exBitmapInfo,n+1,1,e.tickSpacing):sT.searchLowBitFromStart(e.tickArrayBitmap,e.exBitmapInfo,n-1,1,e.tickSpacing);return r.length>0?{isExist:!0,nextStartIndex:r[0]}:{isExist:!1,nextStartIndex:0}}static nextInitializedTickArrayStartIndex(e,t,n){for(t=sf.getArrayStartIndex(e.tickCurrent,e.tickSpacing);;){let{isInit:r,tickIndex:i}=sh.nextInitializedTickArrayStartIndex(sT.mergeTickArrayBitmap(e.tickArrayBitmap),t,e.tickSpacing,n);if(r)return{isExist:!0,nextStartIndex:i};t=i;let{isInit:o,tickIndex:a}=sm.nextInitializedTickArrayFromOneBitmap(t,e.tickSpacing,n,e.exBitmapInfo);if(o)return{isExist:!0,nextStartIndex:a};if((t=a)<-443636||t>443636)return{isExist:!1,nextStartIndex:0}}}static async updatePoolRewardInfos({connection:e,apiPoolInfo:t,chainTime:n,poolLiquidity:r,rewardInfos:i}){var o,a,s;let u=[];for(let l=0;l=n||t443636&&(t=sf.getArrayStartIndex(443636,e)+sf.tickCount(e)),n<-443636&&(n=sf.getArrayStartIndex(-443636,e)),{maxTickBoundary:t,minTickBoundary:n}}static get_tick_array_offset(e,t){if(!sf.checkIsValidStartIndex(e,t))throw Error("No enough initialized tickArray");return e/sf.tickCount(t)*sI}static async fetchExBitmaps({connection:e,exBitmapAddress:t,batchRequest:n}){let r=await ne(e,t.map(e=>({pubkey:e})),{batchRequest:n}),i={};for(let e of r)null!==e.accountInfo&&(i[e.pubkey.toString()]=sF.decode(e.accountInfo.data));return i}static async fetchMultiplePoolTickArrays({connection:e,poolKeys:t,batchRequest:n}){let r={},i=[];for(let e of t){let t=sT.getTickArrayStartIndexByTick(e.tickCurrent,e.tickSpacing);for(let n of sT.getInitializedTickArrayInRange(e.tickArrayBitmap,e.exBitmapInfo,e.tickSpacing,t,7)){let{publicKey:t}=si(e.programId,e.id,n);i.push({pubkey:t}),r[t.toString()]=e.id}}let o=await ne(e,i,{batchRequest:n}),a={};for(let e of o){if(!e.accountInfo)continue;let t=r[e.pubkey.toString()];if(!t)continue;void 0===a[t.toString()]&&(a[t.toString()]={});let n=sN.decode(e.accountInfo.data);a[t.toString()][n.startTickIndex]=t1(t0({},n),{address:e.pubkey})}return a}static async fetchPoolsAccountPosition({pools:e,connection:t,ownerInfo:n,batchRequest:r=!1,updateOwnerRewardAndFee:i=!0}){var o;let a=[];for(let t=0;te.equals(n.state.programId))||a.push(n.state.programId))}if(n){let s=n.tokenAccounts.map(e=>e.accountInfo.mint),u=[];for(let e of s)for(let t of a)u.push(sa(t,e).publicKey);let l=await t7(t,u,{batchRequest:r}),c={};for(let t of l){if(null===t)continue;let n=sR.decode(t.data),r=n.poolId.toString(),i=e.find(e=>e.state.id.toBase58()===r);if(void 0===i)continue;let a=i.state,s=sT._getTickPriceLegacy({poolInfo:a,tick:n.tickLower,baseIn:!0}),u=sT._getTickPriceLegacy({poolInfo:a,tick:n.tickUpper,baseIn:!0}),{amountA:l,amountB:d}=sx.getAmountsFromLiquidity(a.sqrtPriceX64,s.tickSqrtPriceX64,u.tickSqrtPriceX64,n.liquidity,!1),p=1/(1-Math.sqrt(Math.sqrt(s.price.div(u.price).toNumber())));i.positionAccount=[...null!=(o=i.positionAccount)?o:[],{poolId:n.poolId,nftMint:n.nftMint,priceLower:s.price,priceUpper:u.price,amountA:l,amountB:d,tickLower:n.tickLower,tickUpper:n.tickUpper,liquidity:n.liquidity,feeGrowthInsideLastX64A:n.feeGrowthInsideLastX64A,feeGrowthInsideLastX64B:n.feeGrowthInsideLastX64B,tokenFeesOwedA:n.tokenFeesOwedA,tokenFeesOwedB:n.tokenFeesOwedB,rewardInfos:n.rewardInfos.map(e=>t1(t0({},e),{pendingReward:new(tb())(0)})),leverage:p,tokenFeeAmountA:new(tb())(0),tokenFeeAmountB:new(tb())(0)}];let f=await sT.getTickArrayAddressByTick(i.state.programId,n.poolId,n.tickLower,i.state.tickSpacing),h=await sT.getTickArrayAddressByTick(i.state.programId,n.poolId,n.tickUpper,i.state.tickSpacing);c[`${i.state.programId.toString()}-${n.poolId.toString()}-${n.tickLower}`]=f,c[`${i.state.programId.toString()}-${n.poolId.toString()}-${n.tickUpper}`]=h}if(i){let n=Object.values(c),i=await t7(t,n,{batchRequest:r}),o={};for(let e=0;e{var t,n;let i=e.mint.decimals,o=r[e.mint.address];return s<(null!=(t=e.startTime)?t:0)||s>(null!=(n=e.endTime)?n:0)||!e.perSecond||!o||void 0===i?0:new rM(o.value).mul(new rM(e.perSecond).mul(31536e3)).div(new rM(10).pow(i)).mul(k).mul(100).toNumber()});return{feeApr:x,rewardsApr:A,apr:x+A.reduce((e,t)=>e+t,0)}}static getLiquidityAmountOutFromAmountIn({poolInfo:e,inputA:t,tickLower:n,tickUpper:r,amount:i,slippage:o,add:a,epochInfo:s,amountHasFee:u}){var l,c;let d=sw.priceToSqrtPriceX64(new rM(e.price),e.mintA.decimals,e.mintB.decimals),p=sw.getSqrtPriceX64FromTick(n),f=sw.getSqrtPriceX64FromTick(r),h=i7(i,null==(l=e[t?"mintA":"mintB"].extensions)?void 0:l.feeConfig,s,!u),m=new(tb())(new rM(h.amount.sub(null!=(c=h.fee)?c:aU).toString()).mul(a?1-o:1+o).toFixed(0)),g;if(d.lte(p))g=t?sx.getLiquidityFromTokenAmountA(p,f,m,!a):new(tb())(0);else if(d.lte(f)){let e=sx.getLiquidityFromTokenAmountA(d,f,m,!a),n=sx.getLiquidityFromTokenAmountB(p,d,m);g=t?e:n}else g=t?new(tb())(0):sx.getLiquidityFromTokenAmountB(p,f,m);return sg.getAmountsFromLiquidity({epochInfo:s,poolInfo:e,tickLower:n,tickUpper:r,liquidity:g,slippage:o,add:a})}static async getAmountsFromLiquidity({epochInfo:e,poolInfo:t,tickLower:n,tickUpper:r,liquidity:i,slippage:o,add:a}){var s,u,l,c;let d=sw.getSqrtPriceX64FromTick(n),p=sw.getSqrtPriceX64FromTick(r),f=a?1+o:1-o,h=sx.getAmountsFromLiquidity(sw.priceToSqrtPriceX64(new rM(t.price),t.mintA.decimals,t.mintB.decimals),d,p,i,a),[m,g]=[i7(h.amountA,null==(s=t.mintA.extensions)?void 0:s.feeConfig,e,!0),i7(h.amountB,null==(u=t.mintB.extensions)?void 0:u.feeConfig,e,!0)],[y,b]=[i7(h.amountA.muln(f),null==(l=t.mintA.extensions)?void 0:l.feeConfig,e,!0),i7(h.amountB.muln(f),null==(c=t.mintB.extensions)?void 0:c.feeConfig,e,!0)];return{liquidity:i,amountA:m,amountB:g,amountSlippageA:y,amountSlippageB:b,expirationTime:oe(m.expirationTime,g.expirationTime)}}static async fetchComputeMultipleClmmInfo({connection:e,poolList:t,rpcDataMap:n={}}){let r=t.filter(e=>!n[e.id]).map(e=>new tu.nh(e.id));(await t7(e,r)).forEach((e,t)=>{e&&(n[r[t].toBase58()]=sB.decode(e.data))});let i=t.map(e=>su(new tu.nh(e.programId),new tu.nh(e.id)).publicKey),o=await sg.fetchExBitmaps({connection:e,exBitmapAddress:i,batchRequest:!1});return t.reduce((e,t)=>t1(t0({},e),{[t.id]:t1(t0({},n[t.id]),{id:new tu.nh(t.id),version:6,programId:new tu.nh(t.programId),mintA:t.mintA,mintB:t.mintB,ammConfig:t1(t0({},t.config),{id:new tu.nh(t.config.id),fundOwner:""}),currentPrice:new rM(t.price),exBitmapAccount:su(new tu.nh(t.programId),new tu.nh(t.id)).publicKey,exBitmapInfo:o[su(new tu.nh(t.programId),new tu.nh(t.id)).publicKey.toBase58()],startTime:n[t.id].startTime.toNumber(),rewardInfos:n[t.id].rewardInfos})}),{})}static async fetchComputeClmmInfo({connection:e,poolInfo:t,rpcData:n}){return(await this.fetchComputeMultipleClmmInfo({connection:e,rpcDataMap:n?{[t.id]:n}:void 0,poolList:[t]}))[t.id]}},sy={volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[]},sb=class{static mulDivRoundingUp(e,t,n){let r=e.mul(t),i=r.div(n);return r.mod(n).eq(aU)||(i=i.add(az)),i}static mulDivFloor(e,t,n){if(n.eq(aU))throw Error("division by 0");return e.mul(t).div(n)}static mulDivCeil(e,t,n){if(n.eq(aU))throw Error("division by 0");return e.mul(t).add(n.sub(az)).div(n)}static x64ToDecimal(e,t){return new rM(e.toString()).div(rM.pow(2,64)).toDecimalPlaces(t)}static decimalToX64(e){return new(tb())(e.mul(rM.pow(2,64)).floor().toFixed())}static wrappingSubU128(e,t){return e.add(a$).sub(t).mod(a$)}};function s_(e,t){return sv(e.mul(t),64,256)}function sv(e,t,n){let r=e.toTwos(n).shrn(t);return r.imaskn(n-t+1),r.fromTwos(n-t)}var sw=class{static sqrtPriceX64ToPrice(e,t,n){return sb.x64ToDecimal(e).pow(2).mul(rM.pow(10,t-n))}static priceToSqrtPriceX64(e,t,n){return sb.decimalToX64(e.mul(rM.pow(10,n-t)).sqrt())}static getNextSqrtPriceX64FromInput(e,t,n,r){if(!e.gt(aU))throw Error("sqrtPriceX64 must greater than 0");if(!t.gt(aU))throw Error("liquidity must greater than 0");return r?this.getNextSqrtPriceFromTokenAmountARoundingUp(e,t,n,!0):this.getNextSqrtPriceFromTokenAmountBRoundingDown(e,t,n,!0)}static getNextSqrtPriceX64FromOutput(e,t,n,r){if(!e.gt(aU))throw Error("sqrtPriceX64 must greater than 0");if(!t.gt(aU))throw Error("liquidity must greater than 0");return r?this.getNextSqrtPriceFromTokenAmountBRoundingDown(e,t,n,!1):this.getNextSqrtPriceFromTokenAmountARoundingUp(e,t,n,!1)}static getNextSqrtPriceFromTokenAmountARoundingUp(e,t,n,r){if(n.eq(aU))return e;let i=t.shln(64);if(r){let t=i.add(n.mul(e));return t.gte(i)?sb.mulDivCeil(i,e,t):sb.mulDivRoundingUp(i,az,i.div(e).add(n))}{let t=n.mul(e);if(!i.gt(t))throw Error("getNextSqrtPriceFromTokenAmountARoundingUp,liquidityLeftShift must gt amountMulSqrtPrice");let r=i.sub(t);return sb.mulDivCeil(i,e,r)}}static getNextSqrtPriceFromTokenAmountBRoundingDown(e,t,n,r){let i=n.shln(64);if(r)return e.add(i.div(t));{let n=sb.mulDivRoundingUp(i,az,t);if(!e.gt(n))throw Error("getNextSqrtPriceFromTokenAmountBRoundingDown sqrtPriceX64 must gt amountDivLiquidity");return e.sub(n)}}static getSqrtPriceX64FromTick(e){if(!Number.isInteger(e))throw Error("tick must be integer");if(e<-443636||e>443636)throw Error("tick must be in MIN_TICK and MAX_TICK");let t=e<0?-1*e:e,n=new(tb())((1&t)!=0?"18445821805675395072":"18446744073709551616");return(2&t)!=0&&(n=s_(n,new(tb())("18444899583751176192"))),(4&t)!=0&&(n=s_(n,new(tb())("18443055278223355904"))),(8&t)!=0&&(n=s_(n,new(tb())("18439367220385607680"))),(16&t)!=0&&(n=s_(n,new(tb())("18431993317065453568"))),(32&t)!=0&&(n=s_(n,new(tb())("18417254355718170624"))),(64&t)!=0&&(n=s_(n,new(tb())("18387811781193609216"))),(128&t)!=0&&(n=s_(n,new(tb())("18329067761203558400"))),(256&t)!=0&&(n=s_(n,new(tb())("18212142134806163456"))),(512&t)!=0&&(n=s_(n,new(tb())("17980523815641700352"))),(1024&t)!=0&&(n=s_(n,new(tb())("17526086738831433728"))),(2048&t)!=0&&(n=s_(n,new(tb())("16651378430235570176"))),(4096&t)!=0&&(n=s_(n,new(tb())("15030750278694412288"))),(8192&t)!=0&&(n=s_(n,new(tb())("12247334978884435968"))),(16384&t)!=0&&(n=s_(n,new(tb())("8131365268886854656"))),(32768&t)!=0&&(n=s_(n,new(tb())("3584323654725218816"))),(65536&t)!=0&&(n=s_(n,new(tb())("696457651848324352"))),(131072&t)!=0&&(n=s_(n,new(tb())("26294789957507116"))),(262144&t)!=0&&(n=s_(n,new(tb())("37481735321082"))),e>0&&(n=aH.div(n)),n}static getTickFromPrice(e,t,n){return sw.getTickFromSqrtPriceX64(sw.priceToSqrtPriceX64(e,t,n))}static getTickFromSqrtPriceX64(e){let t;if(e.gt(aZ)||e.lt(aG))throw Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let n=e.bitLength()-1,r=((t=new(tb())(n-64).toTwos(128).shln(32)).imaskn(129),t.fromTwos(128)),i=new(tb())("8000000000000000","hex"),o=0,a=new(tb())(0),s=n>=64?e.shrn(n-63):e.shln(63-n);for(;i.gt(new(tb())(0))&&o<16;){let e=(s=s.mul(s)).shrn(127);s=s.shrn(63+e.toNumber()),a=a.add(i.mul(e)),i=i.shrn(1),o+=1}let u=a.shrn(32),l=r.add(u).mul(new(tb())("59543866431248")),c=sv(l.sub(new(tb())("184467440737095516")),64,128).toNumber(),d=sv(l.add(new(tb())("15793534762490258745")),64,128).toNumber();return c==d?c:sw.getSqrtPriceX64FromTick(d).lte(e)?d:c}},sk=class{static getTickWithPriceAndTickspacing(e,t,n,r){let i=sw.getTickFromSqrtPriceX64(sw.priceToSqrtPriceX64(e,n,r))/t;return(i=i<0?Math.floor(i):Math.ceil(i))*t}static roundPriceWithTickspacing(e,t,n,r){let i=sk.getTickWithPriceAndTickspacing(e,t,n,r),o=sw.getSqrtPriceX64FromTick(i);return sw.sqrtPriceX64ToPrice(o,n,r)}},sx=class{static addDelta(e,t){return e.add(t)}static getTokenAmountAFromLiquidity(e,t,n,r){if(e.gt(t)&&([e,t]=[t,e]),!e.gt(aU))throw Error("sqrtPriceX64A must greater than 0");let i=n.ushln(64),o=t.sub(e);return r?sb.mulDivRoundingUp(sb.mulDivCeil(i,o,t),az,e):sb.mulDivFloor(i,o,t).div(e)}static getTokenAmountBFromLiquidity(e,t,n,r){if(e.gt(t)&&([e,t]=[t,e]),!e.gt(aU))throw Error("sqrtPriceX64A must greater than 0");return r?sb.mulDivCeil(n,t.sub(e),aW):sb.mulDivFloor(n,t.sub(e),aW)}static getLiquidityFromTokenAmountA(e,t,n,r){e.gt(t)&&([e,t]=[t,e]);let i=n.mul(e).mul(t),o=t.sub(e),a=i.div(o);return r?sb.mulDivRoundingUp(a,az,aK):a.shrn(64)}static getLiquidityFromTokenAmountB(e,t,n){return e.gt(t)&&([e,t]=[t,e]),sb.mulDivFloor(n,aK,t.sub(e))}static getLiquidityFromTokenAmounts(e,t,n,r,i){if(t.gt(n)&&([t,n]=[n,t]),e.lte(t))return sx.getLiquidityFromTokenAmountA(t,n,r,!1);if(!e.lt(n))return sx.getLiquidityFromTokenAmountB(t,n,i);{let o=sx.getLiquidityFromTokenAmountA(e,n,r,!1),a=sx.getLiquidityFromTokenAmountB(t,e,i);return o.lt(a)?o:a}}static getAmountsFromLiquidity(e,t,n,r,i){return(t.gt(n)&&([t,n]=[n,t]),e.lte(t))?{amountA:sx.getTokenAmountAFromLiquidity(t,n,r,i),amountB:new(tb())(0)}:e.lt(n)?{amountA:sx.getTokenAmountAFromLiquidity(e,n,r,i),amountB:sx.getTokenAmountBFromLiquidity(t,e,r,i)}:{amountA:new(tb())(0),amountB:sx.getTokenAmountBFromLiquidity(t,n,r,i)}}static getAmountsFromLiquidityWithSlippage(e,t,n,r,i,o,a){let{amountA:s,amountB:u}=sx.getAmountsFromLiquidity(e,t,n,r,o),l=i?1+a:1-a;return{amountSlippageA:new(tb())(new rM(s.toString()).mul(l).toFixed(0)),amountSlippageB:new(tb())(new rM(u.toString()).mul(l).toFixed(0))}}static getAmountsOutFromLiquidity({poolInfo:e,tickLower:t,tickUpper:n,liquidity:r,slippage:i,add:o,epochInfo:a,amountAddFee:s}){var u,l,c,d;let p=sw.priceToSqrtPriceX64(new rM(e.price),e.mintA.decimals,e.mintB.decimals),f=sw.getSqrtPriceX64FromTick(t),h=sw.getSqrtPriceX64FromTick(n),m=o?1+i:1-i,g=sx.getAmountsFromLiquidity(p,f,h,r,o),[y,b]=[i7(g.amountA,null==(u=e.mintA.extensions)?void 0:u.feeConfig,a,s),i7(g.amountB,null==(l=e.mintB.extensions)?void 0:l.feeConfig,a,s)],[_,v]=[i7(new(tb())(new rM(g.amountA.toString()).mul(m).toFixed(0)),null==(c=e.mintA.extensions)?void 0:c.feeConfig,a,s),i7(new(tb())(new rM(g.amountB.toString()).mul(m).toFixed(0)),null==(d=e.mintB.extensions)?void 0:d.feeConfig,a,s)];return{liquidity:r,amountA:y,amountB:b,amountSlippageA:_,amountSlippageB:v,expirationTime:oe(y.expirationTime,b.expirationTime)}}},sA=class{static swapCompute(e,t,n,r,i,o,a,s,u,l,c,d,p,f,h=!1){if(d.eq(aU))throw Error("amountSpecified must not be 0");if(f||(f=o?aG.add(az):aZ.sub(az)),o){if(f.lt(aG))throw Error("sqrtPriceX64 must greater than MIN_SQRT_PRICE_X64");if(f.gte(c))throw Error("sqrtPriceX64 must smaller than current")}else{if(f.gt(aZ))throw Error("sqrtPriceX64 must smaller than MAX_SQRT_PRICE_X64");if(f.lte(c))throw Error("sqrtPriceX64 must greater than current")}let m=d.gt(aU),g={amountSpecifiedRemaining:d,amountCalculated:aU,sqrtPriceX64:c,tick:u>p?Math.min(p+sf.tickCount(l)-1,u):p,accounts:[],liquidity:s,feeAmount:new(tb())(0)},y=p,b=n[p],_=!o&&b.startTickIndex===g.tick;for(;!g.amountSpecifiedRemaining.eq(aU)&&!g.sqrtPriceX64.eq(f);){let s;let u={};u.sqrtPriceStartX64=g.sqrtPriceX64;let c=sT.nextInitTick(b,g.tick,l,o,_)||null,d=null;if(!(null!=c&&c.liquidityGross.gtn(0))){let a=sg.nextInitializedTickArrayStartIndex({tickCurrent:g.tick,tickSpacing:l,tickArrayBitmap:r,exBitmapInfo:i},y,o);if(!a.isExist){if(h)return{allTrade:!1,amountSpecifiedRemaining:g.amountSpecifiedRemaining,amountCalculated:g.amountCalculated,feeAmount:g.feeAmount,sqrtPriceX64:g.sqrtPriceX64,liquidity:g.liquidity,tickCurrent:g.tick,accounts:g.accounts};throw Error("swapCompute LiquidityInsufficient")}let{publicKey:s}=si(e,t,y=a.nextStartIndex);d=s,b=n[y];try{c=sT.firstInitializedTick(b,o)}catch{throw Error("not found next tick info")}}if(u.tickNext=c.tick,u.initialized=c.liquidityGross.gtn(0),p!==y&&d&&(g.accounts.push(d),p=y),u.tickNext<-443636?u.tickNext=-443636:u.tickNext>443636&&(u.tickNext=443636),u.sqrtPriceNextX64=sw.getSqrtPriceX64FromTick(u.tickNext),s=o&&u.sqrtPriceNextX64.lt(f)||!o&&u.sqrtPriceNextX64.gt(f)?f:u.sqrtPriceNextX64,[g.sqrtPriceX64,u.amountIn,u.amountOut,u.feeAmount]=sA.swapStepCompute(g.sqrtPriceX64,s,g.liquidity,g.amountSpecifiedRemaining,a),g.feeAmount=g.feeAmount.add(u.feeAmount),m?(g.amountSpecifiedRemaining=g.amountSpecifiedRemaining.sub(u.amountIn.add(u.feeAmount)),g.amountCalculated=g.amountCalculated.sub(u.amountOut)):(g.amountSpecifiedRemaining=g.amountSpecifiedRemaining.add(u.amountOut),g.amountCalculated=g.amountCalculated.add(u.amountIn.add(u.feeAmount))),g.sqrtPriceX64.eq(u.sqrtPriceNextX64)){if(u.initialized){let e=c.liquidityNet;o&&(e=e.mul(aV)),g.liquidity=sx.addDelta(g.liquidity,e)}_=u.tickNext!=g.tick&&!o&&b.startTickIndex===u.tickNext,g.tick=o?u.tickNext-1:u.tickNext}else if(g.sqrtPriceX64!=u.sqrtPriceStartX64){let e=sw.getTickFromSqrtPriceX64(g.sqrtPriceX64);_=e!=g.tick&&!o&&b.startTickIndex===e,g.tick=e}}try{let{nextStartIndex:n,isExist:a}=sf.nextInitializedTickArray(g.tick,l,o,r,i);a&&p!==n&&(g.accounts.push(si(e,t,n).publicKey),p=n)}catch{}return{allTrade:!0,amountSpecifiedRemaining:aU,amountCalculated:g.amountCalculated,feeAmount:g.feeAmount,sqrtPriceX64:g.sqrtPriceX64,liquidity:g.liquidity,tickCurrent:g.tick,accounts:g.accounts}}static swapStepCompute(e,t,n,r,i){let o={sqrtPriceX64Next:new(tb())(0),amountIn:new(tb())(0),amountOut:new(tb())(0),feeAmount:new(tb())(0)},a=e.gte(t),s=r.gte(aU);if(s){let s=sb.mulDivFloor(r,aQ.sub(new(tb())(i.toString())),aQ);o.amountIn=a?sx.getTokenAmountAFromLiquidity(t,e,n,!0):sx.getTokenAmountBFromLiquidity(e,t,n,!0),s.gte(o.amountIn)?o.sqrtPriceX64Next=t:o.sqrtPriceX64Next=sw.getNextSqrtPriceX64FromInput(e,n,s,a)}else o.amountOut=a?sx.getTokenAmountBFromLiquidity(t,e,n,!1):sx.getTokenAmountAFromLiquidity(e,t,n,!1),r.mul(aV).gte(o.amountOut)?o.sqrtPriceX64Next=t:o.sqrtPriceX64Next=sw.getNextSqrtPriceX64FromOutput(e,n,r.mul(aV),a);let u=t.eq(o.sqrtPriceX64Next);return a?(u&&s||(o.amountIn=sx.getTokenAmountAFromLiquidity(o.sqrtPriceX64Next,e,n,!0)),u&&!s||(o.amountOut=sx.getTokenAmountBFromLiquidity(o.sqrtPriceX64Next,e,n,!1))):(o.amountIn=u&&s?o.amountIn:sx.getTokenAmountBFromLiquidity(e,o.sqrtPriceX64Next,n,!0),o.amountOut=u&&!s?o.amountOut:sx.getTokenAmountAFromLiquidity(e,o.sqrtPriceX64Next,n,!1)),!s&&o.amountOut.gt(r.mul(aV))&&(o.amountOut=r.mul(aV)),s&&!o.sqrtPriceX64Next.eq(t)?o.feeAmount=r.sub(o.amountIn):o.feeAmount=sb.mulDivCeil(o.amountIn,new(tb())(i),aQ.sub(new(tb())(i))),[o.sqrtPriceX64Next,o.amountIn,o.amountOut,o.feeAmount]}},sS=60,sI=512,sT=class{static getTickArrayAddressByTick(e,t,n,r){let i=sT.getTickArrayStartIndexByTick(n,r),{publicKey:o}=si(e,t,i);return o}static getTickOffsetInArray(e,t){if(e%t!=0)throw Error("tickIndex % tickSpacing not equal 0");let n=sT.getTickArrayStartIndexByTick(e,t),r=Math.floor((e-n)/t);if(r<0||r>=sS)throw Error("tick offset in array overflow");return r}static getTickArrayBitIndex(e,t){let n=sf.tickCount(t),r=e/n;return e<0&&e%n!=0?Math.ceil(r)-1:Math.floor(r)}static getTickArrayStartIndexByTick(e,t){return this.getTickArrayBitIndex(e,t)*sf.tickCount(t)}static getTickArrayOffsetInBitmapByTick(e,t){return Math.abs(Math.floor(e/(t*sS))+512)}static checkTickArrayIsInitialized(e,t,n){let r=n*sS,i=Math.abs(Math.floor(t/r)+512);return{isInitialized:e.testn(i),startIndex:(i-512)*r}}static getNextTickArrayStartIndex(e,t,n){return n?e-t*sS:e+t*sS}static mergeTickArrayBitmap(e){let t=new(tb())(0);for(let n=0;ne.liquidityGross.gtn(0))}static searchLowBitFromStart(e,t,n,r,i){let o=[...[...t.negativeTickArrayBitmap].reverse(),e.slice(0,8),e.slice(8,16),...t.positiveTickArrayBitmap].map(e=>sT.mergeTickArrayBitmap(e)),a=[];for(;n>=-7680;){let e=Math.floor((n+7680)/512),t=(n+7680)%512;if(o[e].testn(t)&&a.push(n),n--,a.length===r)break}let s=sf.tickCount(i);return a.map(e=>e*s)}static searchHightBitFromStart(e,t,n,r,i){let o=[...[...t.negativeTickArrayBitmap].reverse(),e.slice(0,8),e.slice(8,16),...t.positiveTickArrayBitmap].map(e=>sT.mergeTickArrayBitmap(e)),a=[];for(;n<7680;){let e=Math.floor((n+7680)/512),t=(n+7680)%512;if(o[e].testn(t)&&a.push(n),n++,a.length===r)break}let s=sf.tickCount(i);return a.map(e=>e*s)}static checkIsOutOfBoundary(e){return e<-443636||e>443636}static nextInitTick(e,t,n,r,i){if(sf.getArrayStartIndex(t,n)!=e.startTickIndex)return null;let o=Math.floor((t-e.startTickIndex)/n);if(r)for(;o>=0;){if(e.ticks[o].liquidityGross.gtn(0))return e.ticks[o];o-=1}else for(i||(o+=1);o=0;){if(e.ticks[t].liquidityGross.gtn(0))return e.ticks[t];t-=1}}else{let t=0;for(;t[{pubkey:e.poolRewardVault,isSigner:!1,isWritable:!0},{pubkey:e.ownerRewardVault,isSigner:!1,isWritable:!0},{pubkey:e.rewardMint,isSigner:!1,isWritable:!1}]).flat()],w=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:td.H_,isSigner:!1,isWritable:!1},{pubkey:td.nA,isSigner:!1,isWritable:!1},{pubkey:r0,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},...v],k=tK.alloc(_.span);_.encode({liquidity:m,amountMinA:g,amountMinB:y},k);let x=tK.from([...sU.decreaseLiquidity,...k]);return new tu.Sl({keys:w,programId:e,data:x})}static decreaseLiquidityInstructions({poolInfo:e,poolKeys:t,ownerPosition:n,ownerInfo:r,liquidity:i,amountMinA:o,amountMinB:a,programId:s,nft2022:u}){let[l,c]=[new tu.nh(e.programId),new tu.nh(e.id)],d=sT.getTickArrayStartIndexByTick(n.tickLower,e.config.tickSpacing),p=sT.getTickArrayStartIndexByTick(n.tickUpper,e.config.tickSpacing),{publicKey:f}=si(l,c,d),{publicKey:h}=si(l,c,p),{publicKey:m}=u?iN(r.wallet,n.nftMint,td.nA):iN(r.wallet,n.nftMint,s),{publicKey:g}=sa(l,n.nftMint),{publicKey:y}=so(l,c,n.tickLower,n.tickUpper),b=[];for(let n=0;n({pubkey:e,isSigner:!1,isWritable:!0}))],_=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:td.H_,isSigner:!1,isWritable:!1},{pubkey:td.nA,isSigner:!1,isWritable:!1},{pubkey:r0,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},...b],v=tK.alloc(y.span);y.encode({amount:p,otherAmountThreshold:f,sqrtPriceLimitX64:h,isBaseInput:m},v);let w=tK.from([...sU.swap,...v]);return new tu.Sl({keys:_,programId:e,data:w})}static makeSwapBaseInInstructions({poolInfo:e,poolKeys:t,observationId:n,ownerInfo:r,inputMint:i,amountIn:o,amountOutMin:a,sqrtPriceLimitX64:s,remainingAccounts:u}){let[l,c]=[new tu.nh(e.programId),new tu.nh(e.id)],[d,p]=[new tu.nh(t.vault.A),new tu.nh(t.vault.B)],[f,h]=[new tu.nh(e.mintA.address),new tu.nh(e.mintB.address)],m=e.mintA.address===i.toString();return{signers:[],instructions:[this.swapInstruction(l,r.wallet,c,new tu.nh(e.config.id),m?r.tokenAccountA:r.tokenAccountB,m?r.tokenAccountB:r.tokenAccountA,m?d:p,m?p:d,m?f:h,m?h:f,u,n,o,a,s,!0,su(l,c).publicKey)],instructionTypes:[iw.ClmmSwapBaseIn],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[],address:{}}}static makeSwapBaseOutInstructions({poolInfo:e,poolKeys:t,observationId:n,ownerInfo:r,outputMint:i,amountOut:o,amountInMax:a,sqrtPriceLimitX64:s,remainingAccounts:u}){let[l,c]=[new tu.nh(e.programId),new tu.nh(e.id)],[d,p]=[new tu.nh(t.vault.A),new tu.nh(t.vault.B)],[f,h]=[new tu.nh(e.mintA.address),new tu.nh(e.mintB.address)],m=e.mintA.address===i.toBase58();return{signers:[],instructions:[this.swapInstruction(l,r.wallet,c,new tu.nh(e.config.id),m?r.tokenAccountB:r.tokenAccountA,m?r.tokenAccountA:r.tokenAccountB,m?p:d,m?d:p,m?h:f,m?f:h,u,n,o,a,s,!1,su(l,c).publicKey)],instructionTypes:[iw.ClmmSwapBaseOut],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[],address:{}}}static initRewardInstruction(e,t,n,r,i,o,a,s,u,l,c,d){let p=o2([oH("openTime"),oH("endTime"),oG("emissionsPerSecondX64")]),f=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:tu.yc.programId,isSigner:!1,isWritable:!1},{pubkey:r2,isSigner:!1,isWritable:!1}],h=tK.alloc(p.span);p.encode({openTime:rN(l),endTime:rN(c),emissionsPerSecondX64:d},h);let m=tK.from([...sU.initReward,...h]);return new tu.Sl({keys:f,programId:e,data:m})}static initRewardInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,rewardInfo:r}){var i;let[o,a]=[new tu.nh(e.programId),new tu.nh(e.id)],s=(i=r.mint,iP([a8,a.toBuffer(),i.toBuffer()],o)).publicKey,u=iP([se],o).publicKey,l=[this.initRewardInstruction(o,n.wallet,a,u,new tu.nh(e.config.id),n.tokenAccount,r.programId,r.mint,s,r.openTime,r.endTime,r.emissionsPerSecondX64)];return{address:{poolRewardVault:s,operationId:u},signers:[],instructions:l,instructionTypes:[iw.ClmmInitReward],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static setRewardInstruction(e,t,n,r,i,o,a,s,u,l,c,d){let p=o2([o$("rewardIndex"),oG("emissionsPerSecondX64"),oH("openTime"),oH("endTime")]),f=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:td.H_,isSigner:!1,isWritable:!1},{pubkey:td.nA,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0}],h=tK.alloc(p.span);p.encode({rewardIndex:u,emissionsPerSecondX64:d,openTime:rN(l),endTime:rN(c)},h);let m=tK.from([...sU.setRewardEmissions,...h]);return new tu.Sl({keys:f,programId:e,data:m})}static setRewardInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,rewardInfo:r}){let[i,o]=[new tu.nh(e.programId),new tu.nh(e.id)],a,s,u;for(let n=0;n[{pubkey:e.poolRewardVault,isSigner:!1,isWritable:!0},{pubkey:e.ownerRewardVault,isSigner:!1,isWritable:!0},{pubkey:e.rewardMint,isSigner:!1,isWritable:!1}]).flat()],p=[{pubkey:e.authProgramId,isSigner:!1,isWritable:!1},{pubkey:sc(e.programId,u).publicKey,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:e.owner,isSigner:!0,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:new tu.nh(e.poolKeys.vault.A),isSigner:!1,isWritable:!0},{pubkey:new tu.nh(e.poolKeys.vault.B),isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:e.userVaultA,isSigner:!1,isWritable:!0},{pubkey:e.userVaultB,isSigner:!1,isWritable:!0},{pubkey:td.H_,isSigner:!1,isWritable:!1},{pubkey:td.nA,isSigner:!1,isWritable:!1},{pubkey:r1,isSigner:!1,isWritable:!1},{pubkey:new tu.nh(e.poolKeys.mintA.address),isSigner:!1,isWritable:!1},{pubkey:new tu.nh(e.poolKeys.mintB.address),isSigner:!1,isWritable:!1},...d];return new tu.Sl({keys:p,programId:e.programId,data:tK.from(sV)})}static harvestLockPositionInstructionV2({programId:e,auth:t,lockPositionId:n,clmmProgram:r,lockOwner:i,lockNftMint:o,lockNftAccount:a,positionNftAccount:s,positionId:u,poolId:l,protocolPosition:c,vaultA:d,vaultB:p,tickArrayLower:f,tickArrayUpper:h,userVaultA:m,userVaultB:g,mintA:y,mintB:b,rewardAccounts:_,exTickArrayBitmap:v}){let w=[...v?[{pubkey:v,isSigner:!1,isWritable:!0}]:[],..._.map(e=>[{pubkey:e.poolRewardVault,isSigner:!1,isWritable:!0},{pubkey:e.ownerRewardVault,isSigner:!1,isWritable:!0},{pubkey:e.rewardMint,isSigner:!1,isWritable:!1}]).flat()],k=[{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!0,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:h,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:g,isSigner:!1,isWritable:!0},{pubkey:td.H_,isSigner:!1,isWritable:!1},{pubkey:td.nA,isSigner:!1,isWritable:!1},{pubkey:r1,isSigner:!1,isWritable:!1},{pubkey:y,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},...w];return new tu.Sl({keys:k,programId:e,data:tK.from(sV)})}};o2([oK("mintAuthorityOption"),oX("mintAuthority"),oH("supply"),o$("decimals"),o$("isInitialized"),oK("freezeAuthorityOption"),oX("freezeAuthority")]);var s$=e=>new ii({mint:e.address,decimals:e.decimals,symbol:e.symbol,name:e.name}),sK=e=>{var{amount:t,isRaw:n,name:r}=e,i=t2(e,["amount","isRaw","name"]);return new rK(new ii({mint:it(i.address).toBase58(),decimals:i.decimals,symbol:i.symbol,name:r}),t,n,r)};function sH(e){return e.address===rG.address?rZ:e}function sG(e){return e.address===rZ.address?rG:e}var sZ=e=>{var{address:t,programId:n,decimals:r}=e,i=t2(e,["address","programId","decimals"]);return t0({chainId:101,address:it(t).toBase58(),programId:n,logoURI:"",symbol:"",name:"",decimals:r,tags:[],extensions:i.extensions||{}},i)},sY=e=>e?t1(t0({},e),{transferFeeConfigAuthority:e.transferFeeConfigAuthority.toBase58(),withdrawWithheldAuthority:e.withdrawWithheldAuthority.toBase58(),withheldAmount:e.withheldAmount.toString(),olderTransferFee:t1(t0({},e.olderTransferFee),{epoch:e.olderTransferFee.epoch.toString(),maximumFee:e.olderTransferFee.maximumFee.toString()}),newerTransferFee:t1(t0({},e.newerTransferFee),{epoch:e.newerTransferFee.epoch.toString(),maximumFee:e.newerTransferFee.maximumFee.toString()})}):void 0,sX=new(tb())(25),sQ=new(tb())(1e4),sJ=o2([o$("instruction"),oH("amountIn"),oH("minAmountOut")]),s0=o2([o$("instruction"),oH("maxAmountIn"),oH("amountOut")]),s1=(o2([o$("instruction"),o$("nonce")]),o2([o$("instruction"),o$("nonce"),oH("startTime")]),o2([oH("status"),oH("nonce"),oH("maxOrder"),oH("depth"),oH("baseDecimal"),oH("quoteDecimal"),oH("state"),oH("resetFlag"),oH("minSize"),oH("volMaxCutRatio"),oH("amountWaveRatio"),oH("baseLotSize"),oH("quoteLotSize"),oH("minPriceMultiplier"),oH("maxPriceMultiplier"),oH("systemDecimalValue"),oH("minSeparateNumerator"),oH("minSeparateDenominator"),oH("tradeFeeNumerator"),oH("tradeFeeDenominator"),oH("pnlNumerator"),oH("pnlDenominator"),oH("swapFeeNumerator"),oH("swapFeeDenominator"),oH("baseNeedTakePnl"),oH("quoteNeedTakePnl"),oH("quoteTotalPnl"),oH("baseTotalPnl"),oH("poolOpenTime"),oH("punishPcAmount"),oH("punishCoinAmount"),oH("orderbookToInitTime"),oG("swapBaseInAmount"),oG("swapQuoteOutAmount"),oH("swapBase2QuoteFee"),oG("swapQuoteInAmount"),oG("swapBaseOutAmount"),oH("swapQuote2BaseFee"),oX("baseVault"),oX("quoteVault"),oX("baseMint"),oX("quoteMint"),oX("lpMint"),oX("openOrders"),oX("marketId"),oX("marketProgramId"),oX("targetOrders"),oX("withdrawQueue"),oX("lpVault"),oX("owner"),oH("lpReserve"),o6(oH(),3,"padding")])),s2=(o2([oH("accountType"),oH("status"),oH("nonce"),oH("maxOrder"),oH("depth"),oH("baseDecimal"),oH("quoteDecimal"),oH("state"),oH("resetFlag"),oH("minSize"),oH("volMaxCutRatio"),oH("amountWaveRatio"),oH("baseLotSize"),oH("quoteLotSize"),oH("minPriceMultiplier"),oH("maxPriceMultiplier"),oH("systemDecimalsValue"),oH("abortTradeFactor"),oH("priceTickMultiplier"),oH("priceTick"),oH("minSeparateNumerator"),oH("minSeparateDenominator"),oH("tradeFeeNumerator"),oH("tradeFeeDenominator"),oH("pnlNumerator"),oH("pnlDenominator"),oH("swapFeeNumerator"),oH("swapFeeDenominator"),oH("baseNeedTakePnl"),oH("quoteNeedTakePnl"),oH("quoteTotalPnl"),oH("baseTotalPnl"),oH("poolOpenTime"),oH("punishPcAmount"),oH("punishCoinAmount"),oH("orderbookToInitTime"),oG("swapBaseInAmount"),oG("swapQuoteOutAmount"),oG("swapQuoteInAmount"),oG("swapBaseOutAmount"),oH("swapQuote2BaseFee"),oH("swapBase2QuoteFee"),oX("baseVault"),oX("quoteVault"),oX("baseMint"),oX("quoteMint"),oX("lpMint"),oX("modelDataAccount"),oX("openOrders"),oX("marketId"),oX("marketProgramId"),oX("targetOrders"),oX("owner"),o6(oH(),64,"padding")]),o2([o$("instruction"),oH("baseAmountIn"),oH("quoteAmountIn"),oH("fixedSide"),oH("otherAmountMin")])),s6=o2([o$("instruction"),oH("lpAmount"),oH("baseAmountMin"),oH("quoteAmountMin")]),s3=o2([oH("fee")]),s4=new tu.nh("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),s5=o2([oH("x"),oH("y"),oH("price")]),s8=o2([oH("accountType"),oH("status"),oH("multiplier"),oH("validDataCount"),o6(s5,5e4,"DataElement")]);function s9(e,t,n){let[r,i,o]=function(e,t,n){let[r,i]=[0,49998],o=r,a=i,s=0,u=t*e.multiplier/n;for(;o<=a&&0!==(s=Math.floor((a+o)/2))&&!(s>=49998);){let t=e.DataElement[s].x*e.multiplier/e.DataElement[s].y,n=e.DataElement[s-1].x*e.multiplier/e.DataElement[s-1].y,r=e.DataElement[s+1].x*e.multiplier/e.DataElement[s+1].y;if(u===t)return[s,s,!0];if(u===n)return[s-1,s-1,!0];if(u===r)return[s+1,s+1,!0];if(un&&ut&&u49998);){let n=e.DataElement[a].x,r=e.DataElement[a-1].x,s=e.DataElement[a+1].x;if(t===n)return[a,a,!0];if(t===r)return[a-1,a-1,!0];if(t===s)return[a+1,a+1,!0];if(tr&&tn&&t=n&&t<=u)return r?[c,p,!0,s]:[l,d,!0,s];{let o,a;return r?(o=l+(c-l)*(t-n)/(u-n),a=d-(i-n)*e.multiplier/c):(o=l+(c-l)*(t-n)/(u-n),a=p+(u-i)*e.multiplier/l),[o,a,!1,s]}}}var un=class{constructor({connection:e}){this._layoutData={accountType:0,status:0,multiplier:0,validDataCount:0,DataElement:[]},this.connection=e}get stableModelData(){return this._layoutData}async initStableModelLayout(){if(0===this._layoutData.validDataCount&&this.connection){var e;let t,n=await this.connection.getAccountInfo(s4);n&&(this._layoutData=(e=null==n?void 0:n.data,{accountType:(t=s8.decode(e)).accountType.toNumber(),status:t.status.toNumber(),multiplier:t.multiplier.toNumber(),validDataCount:t.validDataCount.toNumber(),DataElement:t.DataElement.map(e=>({x:e.x.toNumber(),y:e.y.toNumber(),price:e.price.toNumber()}))}))}}},ur=t8("Raydium_liquidity_instruction");function ui(e){let{poolInfo:t,poolKeys:n,userKeys:r,lpAmount:i,baseAmountMin:o,quoteAmountMin:a}=e,s=ip(n),u=4;if(t.pooltype.includes("StablePool")&&(u=5),4===u||5===u){let e=tK.alloc(s6.span);s6.encode({instruction:4,lpAmount:rN(i),baseAmountMin:rN(o),quoteAmountMin:rN(a)},e);let t=[rY({pubkey:td.H_,isWritable:!1}),rY({pubkey:s.id}),rY({pubkey:s.authority,isWritable:!1}),rY({pubkey:s.openOrders}),rY({pubkey:s.targetOrders}),rY({pubkey:s.mintLp.address}),rY({pubkey:s.vault.A}),rY({pubkey:s.vault.B})];return 5===u?t.push(rY({pubkey:s4})):(t.push(rY({pubkey:s.id})),t.push(rY({pubkey:s.id}))),t.push(rY({pubkey:s.marketProgramId,isWritable:!1}),rY({pubkey:s.marketId}),rY({pubkey:s.marketBaseVault}),rY({pubkey:s.marketQuoteVault}),rY({pubkey:s.marketAuthority,isWritable:!1}),rY({pubkey:r.lpTokenAccount}),rY({pubkey:r.baseTokenAccount}),rY({pubkey:r.quoteTokenAccount}),rY({pubkey:r.owner,isWritable:!1,isSigner:!0}),rY({pubkey:s.marketEventQueue}),rY({pubkey:s.marketBids}),rY({pubkey:s.marketAsks})),new tu.Sl({programId:s.programId,keys:t,data:e})}return new tu.Sl({programId:s.programId,keys:[]})}function uo({programId:e,ammId:t,ammAuthority:n,ammOpenOrders:r,lpMint:i,coinMint:o,pcMint:a,coinVault:s,pcVault:u,withdrawQueue:l,ammTargetOrders:c,poolTempLp:d,marketProgramId:p,marketId:f,userWallet:h,userCoinVault:m,userPcVault:g,userLpVault:y,nonce:b,openTime:_,coinAmount:v,pcAmount:w,ammConfigId:k,feeDestinationId:x}){let A=o2([o$("instruction"),o$("nonce"),oH("openTime"),oH("pcAmount"),oH("coinAmount")]),S=[{pubkey:td.H_,isSigner:!1,isWritable:!1},{pubkey:td._u,isSigner:!1,isWritable:!1},{pubkey:tu.yc.programId,isSigner:!1,isWritable:!1},{pubkey:r2,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:k,isSigner:!1,isWritable:!1},{pubkey:x,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:h,isSigner:!0,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:g,isSigner:!1,isWritable:!0},{pubkey:y,isSigner:!1,isWritable:!0}],I=tK.alloc(A.span);return A.encode({instruction:1,nonce:b,openTime:_,coinAmount:v,pcAmount:w},I),{instruction:new tu.Sl({keys:S,programId:e,data:I}),instructionType:iw.AmmV4CreatePool}}function ua(e){let{poolKeys:t,version:n,userKeys:r,amountIn:i,amountOut:o,fixedSide:a}=e;if(4===n||5===n){let s={poolKeys:t,userKeys:r};if("in"===a)return function({poolKeys:e,userKeys:t,amountIn:n,minAmountOut:r},i){let o=ip(e),a=tK.alloc(sJ.span);sJ.encode({instruction:9,amountIn:rN(n),minAmountOut:rN(r)},a);let s=[rY({pubkey:td.H_,isWritable:!1}),rY({pubkey:o.id}),rY({pubkey:o.authority,isWritable:!1}),rY({pubkey:o.openOrders})];return 4===i&&s.push(rY({pubkey:o.targetOrders})),s.push(rY({pubkey:o.vault.A}),rY({pubkey:o.vault.B})),5===i&&s.push(rY({pubkey:s4})),s.push(rY({pubkey:o.marketProgramId,isWritable:!1}),rY({pubkey:o.marketId}),rY({pubkey:o.marketBids}),rY({pubkey:o.marketAsks}),rY({pubkey:o.marketEventQueue}),rY({pubkey:o.marketBaseVault}),rY({pubkey:o.marketQuoteVault}),rY({pubkey:o.marketAuthority,isWritable:!1}),rY({pubkey:t.tokenAccountIn}),rY({pubkey:t.tokenAccountOut}),rY({pubkey:t.owner,isWritable:!1})),new tu.Sl({programId:o.programId,keys:s,data:a})}(t1(t0({},s),{amountIn:i,minAmountOut:o}),n);if("out"===a)return function({poolKeys:e,userKeys:t,maxAmountIn:n,amountOut:r},i){let o=ip(e),a=tK.alloc(s0.span);s0.encode({instruction:11,maxAmountIn:rN(n),amountOut:rN(r)},a);let s=[rY({pubkey:td.H_,isWritable:!1}),rY({pubkey:o.id}),rY({pubkey:o.authority,isWritable:!1}),rY({pubkey:o.openOrders}),rY({pubkey:o.targetOrders}),rY({pubkey:o.vault.A}),rY({pubkey:o.vault.B})];return 5===i&&s.push(rY({pubkey:s4})),s.push(rY({pubkey:o.marketProgramId,isWritable:!1}),rY({pubkey:o.marketId}),rY({pubkey:o.marketBids}),rY({pubkey:o.marketAsks}),rY({pubkey:o.marketEventQueue}),rY({pubkey:o.marketBaseVault}),rY({pubkey:o.marketQuoteVault}),rY({pubkey:o.marketAuthority,isWritable:!1}),rY({pubkey:t.tokenAccountIn}),rY({pubkey:t.tokenAccountOut}),rY({pubkey:t.owner,isWritable:!1,isSigner:!0})),new tu.Sl({programId:o.programId,keys:s,data:a})}(t1(t0({},s),{maxAmountIn:i,amountOut:o}),n);ur.logWithError("invalid params","params",e)}throw ur.logWithError("invalid version","poolKeys.version",n),Error("invalid version")}var us=t8("Raydium_liquidity_serum");function uu({programId:e}){let{publicKey:t}=iP([tK.from("amm_config_account_seed","utf-8")],e);return t}function ul({name:e,programId:t,marketId:n}){let{publicKey:r}=iP([t.toBuffer(),n.toBuffer(),tK.from(e,"utf-8")],t);return r}function uc({programId:e}){return iP([tK.from([97,109,109,32,97,117,116,104,111,114,105,116,121])],e)}function ud({version:e,marketVersion:t,marketId:n,baseMint:r,quoteMint:i,baseDecimals:o,quoteDecimals:a,programId:s,marketProgramId:u}){let l=ul({name:"amm_associated_seed",programId:s,marketId:n}),c=ul({name:"lp_mint_associated_seed",programId:s,marketId:n}),{publicKey:d,nonce:p}=uc({programId:s}),f=ul({name:"coin_vault_associated_seed",programId:s,marketId:n}),h=ul({name:"pc_vault_associated_seed",programId:s,marketId:n}),m=ul({name:"temp_lp_token_associated_seed",programId:s,marketId:n}),g=function({programId:e,marketId:t}){let{publicKey:n}=iP([e.toBuffer(),t.toBuffer(),tK.from("open_order_associated_seed","utf-8")],e);return n}({programId:s,marketId:n}),y=ul({name:"target_associated_seed",programId:s,marketId:n}),b=ul({name:"withdraw_associated_seed",programId:s,marketId:n}),{publicKey:_}=function({programId:e,marketId:t}){let n=[t.toBuffer()],r=0,i;for(;r<100;){try{let t=n.concat(tK.from([r]),tK.alloc(7));i=tu.nh.createProgramAddressSync(t,e)}catch(e){if(e instanceof TypeError)throw e;r++;continue}return{publicKey:i,nonce:r}}throw us.logWithError("unable to find a viable program address nonce","params",{programId:e,marketId:t}),Error("unable to find a viable program address nonce")}({programId:u,marketId:n});return{id:l,baseMint:r,quoteMint:i,lpMint:c,baseDecimals:o,quoteDecimals:a,lpDecimals:o,version:e,programId:s,authority:d,nonce:p,baseVault:f,quoteVault:h,lpVault:m,openOrders:g,targetOrders:y,withdrawQueue:b,marketVersion:t,marketProgramId:u,marketId:n,marketAuthority:_,lookupTableAccount:tu.nh.default,configId:uu({programId:s})}}async function up({connection:e,poolKeysList:t,config:n}){p||(p=new un({connection:e}),await p.initStableModelLayout());let r=t.map(e=>(function({poolKeys:e}){let t=o2([o$("instruction"),o$("simulateType")]),n=tK.alloc(t.span);t.encode({instruction:12,simulateType:0},n);let r=[rY({pubkey:new tu.nh(e.id),isWritable:!1}),rY({pubkey:new tu.nh(e.authority),isWritable:!1}),rY({pubkey:new tu.nh(e.openOrders),isWritable:!1}),rY({pubkey:new tu.nh(e.vault.A),isWritable:!1}),rY({pubkey:new tu.nh(e.vault.B),isWritable:!1}),rY({pubkey:new tu.nh(e.mintLp.address),isWritable:!1}),rY({pubkey:new tu.nh(e.marketId),isWritable:!1}),rY({pubkey:new tu.nh(e.marketEventQueue),isWritable:!1})];return{instruction:new tu.Sl({programId:new tu.nh(e.programId),keys:r,data:n})}})({poolKeys:e}));return(await iT(e,r.map(e=>e.instruction),"GetPoolData")).map(e=>{let t;let n=(t=e.match(/{["\w:,]+}/g))&&1===t.length?t[0]:ik.logWithError("simulate log fail to match json, keyword: GetPoolData"),r=new(tb())(iE(n,"status")),i=Number(iE(n,"coin_decimals")),o=Number(iE(n,"pc_decimals")),a=Number(iE(n,"lp_decimals")),s=new(tb())(iE(n,"pool_coin_amount")),u=new(tb())(iE(n,"pool_pc_amount")),l=new(tb())(iE(n,"pool_lp_supply")),c="0";try{c=iE(n,"pool_open_time")}catch{}return{status:r,baseDecimals:i,quoteDecimals:o,lpDecimals:a,baseReserve:s,quoteReserve:u,lpSupply:l,startTime:new(tb())(c)}})}var uf={volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[]},uh=e=>{let t={},n=td.H_.toBase58();return Object.keys(e).map(r=>{let i=e[r],[o,a]=[i.baseMint.toBase58(),i.quoteMint.toBase58()];t[r]={id:r,version:4,status:i.status.toNumber(),programId:i.programId.toBase58(),mintA:sZ({address:o,programId:n,decimals:i.baseDecimal.toNumber()}),mintB:sZ({address:a,programId:n,decimals:i.quoteDecimal.toNumber()}),rewardDefaultInfos:[],rewardDefaultPoolInfos:"Ecosystem",price:i.poolPrice.toNumber(),mintAmountA:new rM(i.mintAAmount.toString()).div(10**i.baseDecimal.toNumber()).toNumber(),mintAmountB:new rM(i.mintBAmount.toString()).div(10**i.quoteDecimal.toNumber()).toNumber(),baseReserve:i.baseReserve,quoteReserve:i.quoteReserve,feeRate:new rM(i.tradeFeeNumerator.toString()).div(i.tradeFeeDenominator.toString()).toNumber(),openTime:i.poolOpenTime.toString(),tvl:0,day:uf,week:uf,month:uf,pooltype:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0,type:"Standard",marketId:i.marketId.toBase58(),configId:uu({programId:i.programId}).toBase58(),lpPrice:0,lpAmount:0,lpMint:sZ({address:i.lpMint.toBase58(),programId:n,decimals:Math.min(i.baseDecimal.toNumber(),i.quoteDecimal.toNumber())}),burnPercent:0}}),t},um=o2([oU(5),function(e="accountFlags"){let t=new oW(e);return t.addBoolean("initialized"),t.addBoolean("market"),t.addBoolean("openOrders"),t.addBoolean("requestQueue"),t.addBoolean("eventQueue"),t.addBoolean("bids"),t.addBoolean("asks"),t}("accountFlags"),oX("ownAddress"),oH("vaultSignerNonce"),oX("baseMint"),oX("quoteMint"),oX("baseVault"),oH("baseDepositsTotal"),oH("baseFeesAccrued"),oX("quoteVault"),oH("quoteDepositsTotal"),oH("quoteFeesAccrued"),oH("quoteDustThreshold"),oX("requestQueue"),oX("eventQueue"),oX("bids"),oX("asks"),oH("baseLotSize"),oH("quoteLotSize"),oH("feeRateBps"),oH("referrerRebatesAccrued"),oU(7)]);async function ug({connection:e,wallet:t,marketInfo:n}){var r,i,o,a,s,u,l,c;let d=new tu.YW,p=await e.getMinimumBalanceForRentExemption(165);d.add(tu.yc.createAccountWithSeed({fromPubkey:t,basePubkey:t,seed:n.baseVault.seed,newAccountPubkey:n.baseVault.publicKey,lamports:p,space:165,programId:td.H_}),tu.yc.createAccountWithSeed({fromPubkey:t,basePubkey:t,seed:n.quoteVault.seed,newAccountPubkey:n.quoteVault.publicKey,lamports:p,space:165,programId:td.H_}),tq(n.baseVault.publicKey,n.baseMint,n.vaultOwner),tq(n.quoteVault.publicKey,n.quoteMint,n.vaultOwner),tu.yc.createAccountWithSeed({fromPubkey:t,basePubkey:t,seed:n.id.seed,newAccountPubkey:n.id.publicKey,lamports:await e.getMinimumBalanceForRentExemption(um.span),space:um.span,programId:n.programId}));let f=new tu.YW;return f.add(tu.yc.createAccountWithSeed({fromPubkey:t,basePubkey:t,seed:n.requestQueue.seed,newAccountPubkey:n.requestQueue.publicKey,lamports:n.lowestFeeMarket?6208320:await e.getMinimumBalanceForRentExemption(null!=(r=n.requestQueueSpace)?r:5132),space:n.lowestFeeMarket?764:null!=(i=n.requestQueueSpace)?i:5132,programId:n.programId}),tu.yc.createAccountWithSeed({fromPubkey:t,basePubkey:t,seed:n.eventQueue.seed,newAccountPubkey:n.eventQueue.publicKey,lamports:n.lowestFeeMarket?79594560:await e.getMinimumBalanceForRentExemption(null!=(o=n.eventQueueSpace)?o:262156),space:n.lowestFeeMarket?11308:null!=(a=n.eventQueueSpace)?a:262156,programId:n.programId}),tu.yc.createAccountWithSeed({fromPubkey:t,basePubkey:t,seed:n.bids.seed,newAccountPubkey:n.bids.publicKey,lamports:n.lowestFeeMarket?101977920:await e.getMinimumBalanceForRentExemption(null!=(s=n.orderbookQueueSpace)?s:65548),space:n.lowestFeeMarket?14524:null!=(u=n.orderbookQueueSpace)?u:65548,programId:n.programId}),tu.yc.createAccountWithSeed({fromPubkey:t,basePubkey:t,seed:n.asks.seed,newAccountPubkey:n.asks.publicKey,lamports:n.lowestFeeMarket?101977920:await e.getMinimumBalanceForRentExemption(null!=(l=n.orderbookQueueSpace)?l:65548),space:n.lowestFeeMarket?14524:null!=(c=n.orderbookQueueSpace)?c:65548,programId:n.programId}),function({programId:e,marketInfo:t}){let n=o2([o$("version"),oK("instruction"),oH("baseLotSize"),oH("quoteLotSize"),oN("feeRateBps"),oH("vaultSignerNonce"),oH("quoteDustThreshold")]),r=[{pubkey:t.id,isSigner:!1,isWritable:!0},{pubkey:t.requestQueue,isSigner:!1,isWritable:!0},{pubkey:t.eventQueue,isSigner:!1,isWritable:!0},{pubkey:t.bids,isSigner:!1,isWritable:!0},{pubkey:t.asks,isSigner:!1,isWritable:!0},{pubkey:t.baseVault,isSigner:!1,isWritable:!0},{pubkey:t.quoteVault,isSigner:!1,isWritable:!0},{pubkey:t.baseMint,isSigner:!1,isWritable:!1},{pubkey:t.quoteMint,isSigner:!1,isWritable:!1},{pubkey:t.authority?t.quoteMint:tu.ze,isSigner:!1,isWritable:!1}].concat(t.authority?{pubkey:t.authority,isSigner:!1,isWritable:!1}:[]).concat(t.authority&&t.pruneAuthority?{pubkey:t.pruneAuthority,isSigner:!1,isWritable:!1}:[]),i=tK.alloc(n.span);return n.encode({version:0,instruction:0,baseLotSize:t.baseLotSize,quoteLotSize:t.quoteLotSize,feeRateBps:t.feeRateBps,vaultSignerNonce:t.vaultSignerNonce,quoteDustThreshold:t.quoteDustThreshold},i),new tu.Sl({keys:r,programId:e,data:i})}({programId:n.programId,marketInfo:{id:n.id.publicKey,requestQueue:n.requestQueue.publicKey,eventQueue:n.eventQueue.publicKey,bids:n.bids.publicKey,asks:n.asks.publicKey,baseVault:n.baseVault.publicKey,quoteVault:n.quoteVault.publicKey,baseMint:n.baseMint,quoteMint:n.quoteMint,baseLotSize:n.baseLotSize,quoteLotSize:n.quoteLotSize,feeRateBps:n.feeRateBps,vaultSignerNonce:n.vaultSignerNonce,quoteDustThreshold:n.quoteDustThreshold}})),[{transaction:d,signer:[],instructionTypes:[iw.CreateAccount,iw.CreateAccount,iw.InitAccount,iw.InitAccount]},{transaction:f,signer:[],instructionTypes:[iw.CreateAccount,iw.CreateAccount,iw.CreateAccount,iw.CreateAccount,iw.CreateAccount,iw.InitMarket]}]}var uy=class extends oy{async create({baseInfo:e,quoteInfo:t,lotSize:n,tickSize:r,dexProgramId:i,requestQueueSpace:o,eventQueueSpace:a,orderbookQueueSpace:s,lowestFeeMarket:u,assignSeed:l,txVersion:c,computeBudgetConfig:d}){let p=this.scope.ownerPubKey,f=l?`${e.mint.toBase58().slice(0,10)}-${t.mint.toBase58().slice(0,10)}-${l}`:void 0,h=o4({fromPublicKey:p,programId:i,assignSeed:f&&`${f}-market`}),m=o4({fromPublicKey:p,programId:i,assignSeed:f&&`${f}-request`}),g=o4({fromPublicKey:p,programId:i,assignSeed:f&&`${f}-event`}),y=o4({fromPublicKey:p,programId:i,assignSeed:f&&`${f}-bids`}),b=o4({fromPublicKey:p,programId:i,assignSeed:f&&`${f}-asks`}),_=o4({fromPublicKey:p,programId:td.H_,assignSeed:f&&`${f}-baseVault`}),v=o4({fromPublicKey:p,programId:td.H_,assignSeed:f&&`${f}-quoteVault`}),w=new(tb())(100),{vaultOwner:k,vaultSignerNonce:x}=function(){let e=new(tb())(0);for(;;)try{return{vaultOwner:tu.nh.createProgramAddressSync([h.publicKey.toBuffer(),e.toArrayLike(tK,"le",8)],i),vaultSignerNonce:e}}catch{if(e.iaddn(1),e.gt(new(tb())(25555)))throw Error("find vault owner error")}}(),A=new(tb())(Math.round(10**e.decimals*n)),S=new(tb())(Math.round(n*10**t.decimals*r));if(A.eq(ih))throw Error("lot size is too small");if(S.eq(ih))throw Error("tick size or lot size is too small");let I=await ug({connection:this.scope.connection,wallet:this.scope.ownerPubKey,marketInfo:{programId:i,id:h,baseMint:e.mint,quoteMint:t.mint,baseVault:_,quoteVault:v,vaultOwner:k,requestQueue:m,eventQueue:g,bids:y,asks:b,feeRateBps:0,quoteDustThreshold:w,vaultSignerNonce:x,baseLotSize:A,quoteLotSize:S,requestQueueSpace:o,eventQueueSpace:a,orderbookQueueSpace:s,lowestFeeMarket:u}}),T=this.createTxBuilder();for await(let e of(T.addInstruction({instructions:I[0].transaction.instructions,signers:I[0].signer}),I.slice(1,I.length)))T.addInstruction({instructions:e.transaction.instructions,signers:e.signer,instructionTypes:e.instructionTypes});return 0===c?T.sizeCheckBuildV0({computeBudgetConfig:d,address:{marketId:h.publicKey,requestQueue:m.publicKey,eventQueue:g.publicKey,bids:y.publicKey,asks:b.publicKey,baseVault:_.publicKey,quoteVault:v.publicKey,baseMint:new tu.nh(e.mint),quoteMin:new tu.nh(t.mint)}}):T.sizeCheckBuild({computeBudgetConfig:d,address:{marketId:h.publicKey,requestQueue:m.publicKey,eventQueue:g.publicKey,bids:y.publicKey,asks:b.publicKey,baseVault:_.publicKey,quoteVault:v.publicKey,baseMint:new tu.nh(e.mint),quoteMin:new tu.nh(t.mint)}})}},ub=class extends oy{constructor(e){super(e),this.stableLayout=new un({connection:this.scope.connection})}async initLayout(){await this.stableLayout.initStableModelLayout()}async load(){this.checkDisabled()}computePairAmount({poolInfo:e,amount:t,slippage:n,baseIn:r}){let i=new(tb())(new rM(t).mul(10**e[r?"mintA":"mintB"].decimals).toFixed(0)),o=s$(e[r?"mintB":"mintA"]),[a,s]=[new(tb())(new rM(e.mintAmountA).mul(10**e.mintA.decimals).toString()),new(tb())(new rM(e.mintAmountB).mul(10**e.mintB.decimals).toString())],u=new(tb())(new rM(e.lpAmount).mul(10**e.lpMint.decimals).toFixed(0,rM.ROUND_DOWN));this.logDebug("baseReserve:",a.toString(),"quoteReserve:",s.toString()),this.logDebug("tokenIn:",r?e.mintA.symbol:e.mintB.symbol,"amountIn:",i.toString(),"anotherToken:",r?e.mintB.symbol:e.mintA.symbol,"slippage:",`${n.toSignificant()}%`,"baseReserve",a.toString(),"quoteReserve",s.toString());let l=r?"base":"quote";this.logDebug("input side:",l);let c=ih;i.isZero()||(c="base"===l?iy(i.mul(s),a):iy(i.mul(a),s)),this.logDebug("amountRaw:",c.toString(),"lpAmount:",u.toString());let d=iy(i.mul(u),"base"===l?a:s);this.logDebug("liquidity:",d.toString());let p=new is(new(tb())(1)).add(n),f=new is(new(tb())(1)).sub(n),h=p.mul(c).quotient,m=f.mul(c).quotient,g=new rK(o,c),y=new rK(o,h),b=new rK(o,m);return this.logDebug("anotherAmount:",g.toFixed(),"maxAnotherAmount:",y.toFixed()),{anotherAmount:g,maxAnotherAmount:y,minAnotherAmount:b,liquidity:d}}async getAmmPoolKeys(e){return(await this.scope.api.fetchPoolKeysById({idList:[e]}))[0]}async addLiquidity(e){let{poolInfo:t,poolKeys:n,amountInA:r,amountInB:i,otherAmountMin:o,fixedSide:a,config:s,txVersion:u,computeBudgetConfig:l}=e;!1===this.scope.availability.addStandardPosition&&this.logAndCreateError("add liquidity feature disabled in your region"),this.logDebug("amountInA:",r,"amountInB:",i),(r.isZero()||i.isZero())&&this.logAndCreateError("amounts must greater than zero","amountInA & amountInB",{amountInA:r.toFixed(),amountInB:i.toFixed()});let{account:c}=this.scope,{bypassAssociatedCheck:d,checkCreateATAOwner:p}=t0({bypassAssociatedCheck:!1,checkCreateATAOwner:!1},s),[f,h]=[r.token,i.token],m=await c.getCreatedTokenAccount({mint:f.mint,associatedOnly:!1}),g=await c.getCreatedTokenAccount({mint:h.mint,associatedOnly:!1});m||g||this.logAndCreateError("cannot found target token accounts","tokenAccounts",c.tokenAccounts);let y=await c.getCreatedTokenAccount({mint:new tu.nh(t.lpMint.address)}),b=[f,h],_=[m,g],v=[r.raw,i.raw],w=r.token.mint.toBase58()===t.mintA.address?"base":"quote",k="base";["quote","base"].includes(w)||this.logAndCreateError("invalid fixedSide","fixedSide",a),"quote"===w?(b.reverse(),_.reverse(),v.reverse(),k="a"===a?"quote":"base"):"base"===w&&(k="a"===a?"base":"quote");let[x,A]=b,[S,I]=_,[T,E]=v,P=null!=n?n:await this.getAmmPoolKeys(t.id),C=this.createTxBuilder(),O=await c.handleTokenAccount({side:"in",amount:T,mint:x.mint,tokenAccount:S,bypassAssociatedCheck:d,checkCreateATAOwner:p}),{tokenAccount:B}=O,M=t2(O,["tokenAccount"]);C.addInstruction(M);let R=await c.handleTokenAccount({side:"in",amount:E,mint:A.mint,tokenAccount:I,bypassAssociatedCheck:d,checkCreateATAOwner:p}),{tokenAccount:L}=R,N=t2(R,["tokenAccount"]);C.addInstruction(N);let D=await c.handleTokenAccount({side:"out",amount:0,mint:new tu.nh(t.lpMint.address),tokenAccount:y,bypassAssociatedCheck:d,checkCreateATAOwner:p}),{tokenAccount:F}=D,q=t2(D,["tokenAccount"]);return C.addInstruction(q),C.addInstruction({instructions:[function(e){let{poolInfo:t,poolKeys:n,userKeys:r,baseAmountIn:i,quoteAmountIn:o,fixedSide:a,otherAmountMin:s}=e,u=tK.alloc(s2.span);s2.encode({instruction:3,baseAmountIn:rN(i),quoteAmountIn:rN(o),otherAmountMin:rN(s),fixedSide:"base"===a?ih:im},u);let l=[rY({pubkey:td.H_,isWritable:!1}),rY({pubkey:new tu.nh(t.id)}),rY({pubkey:new tu.nh(n.authority),isWritable:!1}),rY({pubkey:new tu.nh(n.openOrders),isWritable:!1}),rY({pubkey:new tu.nh(n.targetOrders)}),rY({pubkey:new tu.nh(t.lpMint.address)}),rY({pubkey:new tu.nh(n.vault.A)}),rY({pubkey:new tu.nh(n.vault.B)})];return t.pooltype.includes("StablePool")&&l.push(rY({pubkey:s4})),l.push(rY({pubkey:new tu.nh(t.marketId),isWritable:!1}),rY({pubkey:r.baseTokenAccount}),rY({pubkey:r.quoteTokenAccount}),rY({pubkey:r.lpTokenAccount}),rY({pubkey:r.owner,isWritable:!1,isSigner:!0}),rY({pubkey:new tu.nh(n.marketEventQueue),isWritable:!1})),new tu.Sl({programId:new tu.nh(t.programId),keys:l,data:u})}({poolInfo:t,poolKeys:P,userKeys:{baseTokenAccount:B,quoteTokenAccount:L,lpTokenAccount:F,owner:this.scope.ownerPubKey},baseAmountIn:T,quoteAmountIn:E,otherAmountMin:o.raw,fixedSide:k})],instructionTypes:[t.pooltype.includes("StablePool")?iw.AmmV5AddLiquidity:iw.AmmV4AddLiquidity],lookupTableAddress:P.lookupTableAccount?[P.lookupTableAccount]:[]}),C.addCustomComputeBudget(l),0===u&&await C.buildV0(),C.build()}async removeLiquidity(e){!1===this.scope.availability.removeStandardPosition&&this.logAndCreateError("remove liquidity feature disabled in your region");let{poolInfo:t,poolKeys:n,lpAmount:r,baseAmountMin:i,quoteAmountMin:o,config:a,txVersion:s,computeBudgetConfig:u}=e,l=null!=n?n:await this.getAmmPoolKeys(t.id),[c,d,p]=[new tu.nh(t.mintA.address),new tu.nh(t.mintB.address),new tu.nh(t.lpMint.address)];this.logDebug("lpAmount:",r),this.logDebug("baseAmountMin:",i),this.logDebug("quoteAmountMin:",o),r.isZero()&&this.logAndCreateError("amount must greater than zero","lpAmount",r.toString());let{account:f}=this.scope,h=await f.getCreatedTokenAccount({mint:p,associatedOnly:!1});h||this.logAndCreateError("cannot found lpTokenAccount","tokenAccounts",f.tokenAccounts);let m=await f.getCreatedTokenAccount({mint:c}),g=await f.getCreatedTokenAccount({mint:d}),y=this.createTxBuilder(),{bypassAssociatedCheck:b,checkCreateATAOwner:_}=t0({bypassAssociatedCheck:!1,checkCreateATAOwner:!1},a),v=await f.handleTokenAccount({side:"out",amount:0,mint:c,tokenAccount:m,bypassAssociatedCheck:b,checkCreateATAOwner:_}),{tokenAccount:w}=v,k=t2(v,["tokenAccount"]);y.addInstruction(k);let x=await f.handleTokenAccount({side:"out",amount:0,mint:d,tokenAccount:g,bypassAssociatedCheck:b,checkCreateATAOwner:_}),{tokenAccount:A}=x,S=t2(x,["tokenAccount"]);return y.addInstruction(S),y.addInstruction({instructions:[ui({poolInfo:t,poolKeys:l,userKeys:{lpTokenAccount:h,baseTokenAccount:w,quoteTokenAccount:A,owner:this.scope.ownerPubKey},lpAmount:r,baseAmountMin:i,quoteAmountMin:o})],lookupTableAddress:l.lookupTableAccount?[l.lookupTableAccount]:[],instructionTypes:[t.pooltype.includes("StablePool")?iw.AmmV5RemoveLiquidity:iw.AmmV4RemoveLiquidity]}),y.addCustomComputeBudget(u),0===s?await y.buildV0():y.build()}async removeAllLpAndCreateClmmPosition({poolInfo:e,clmmPoolInfo:t,removeLpAmount:n,createPositionInfo:r,farmInfo:i,userFarmLpAmount:o,base:a,computeBudgetConfig:s,payer:u,userAuxiliaryLedgers:l,tokenProgram:c=td.H_,checkCreateATAOwner:d=!0,getEphemeralSigners:p,txVersion:f}){if((!1===this.scope.availability.removeStandardPosition||!1===this.scope.availability.createConcentratedPosition)&&this.logAndCreateError("remove liquidity or create position feature disabled in your region"),!(e.mintA.address===t.mintA.address||e.mintA.address===t.mintB.address)||!(e.mintB.address===t.mintA.address||e.mintB.address===t.mintB.address))throw Error("mint check error");let h=this.createTxBuilder();h.addCustomComputeBudget(s);let m={};for(let e of this.scope.account.tokenAccountRawInfos)(void 0===m[e.accountInfo.mint.toString()]||iN(this.scope.ownerPubKey,e.accountInfo.mint,td.H_).publicKey.equals(e.pubkey))&&(m[e.accountInfo.mint.toString()]=e.pubkey);let g=m[e.lpMint.address];if(void 0===g)throw Error("find lp account error in trade accounts");let y=n.add(null!=o?o:new(tb())(0)),b=e.mintA.address===ii.WSOL.mint.toString(),_=e.mintB.address===ii.WSOL.mint.toString(),{account:v,instructionParams:w}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:td.H_,mint:new tu.nh(e.mintA.address),owner:this.scope.ownerPubKey,createInfo:b?{payer:this.scope.ownerPubKey}:void 0,skipCloseAccount:!b,notUseTokenAccount:b,associatedOnly:!0,checkCreateATAOwner:d});if(h.addInstruction(w||{}),void 0===v)throw Error("base token account not found");let{account:k,instructionParams:x}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:td.H_,mint:new tu.nh(e.mintB.address),owner:this.scope.ownerPubKey,createInfo:_?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!_,notUseTokenAccount:_,associatedOnly:!0,checkCreateATAOwner:d});if(h.addInstruction(x||{}),void 0===k)throw Error("quote token account not found");if(m[e.mintA.address]=v,m[e.mintB.address]=k,void 0!==i&&!(null!=o&&o.isZero())){let e=aI[i.programId],t=aP({programId:new tu.nh(i.programId),poolId:new tu.nh(i.id),owner:this.scope.ownerPubKey,version:e}),n,r=await this.scope.connection.getAccountInfo(t);if(r&&(n=aB(e).decode(r.data)),6!==e&&!n){let{instruction:n,instructionType:r}=aR({id:new tu.nh(i.id),programId:new tu.nh(i.programId),version:e,ledger:t,owner:this.scope.ownerPubKey});h.addInstruction({instructions:[n],instructionTypes:[r]})}let a=[];for(let e of i.rewardInfos){let t=e.mint.address===ii.WSOL.mint.toString();if(m[e.mint.address])a.push(m[e.mint.address]);else{let{account:n,instructionParams:r}=await this.scope.account.getOrCreateTokenAccount({mint:new tu.nh(e.mint.address),tokenProgram:c,owner:this.scope.ownerPubKey,skipCloseAccount:!t,createInfo:{payer:u||this.scope.ownerPubKey},associatedOnly:!0,checkCreateATAOwner:d});n||this.logAndCreateError("farm reward account not found:",e.mint.address),r&&h.addInstruction(r),a.push(n)}}let s=(await this.scope.api.fetchFarmKeysById({ids:i.id}))[0],p={userAuxiliaryLedgers:l,amount:o,owner:this.scope.ownerPubKey,farmInfo:i,farmKeys:s,lpAccount:g,rewardAccounts:a},f=aI[i.programId],y=6===f?aD(p):5===f?aF(p):aq(p),b={3:iw.FarmV3Withdraw,5:iw.FarmV5Withdraw,6:iw.FarmV6Withdraw};h.addInstruction({instructions:[y],instructionTypes:[b[f]]})}let A=await this.getAmmPoolKeys(e.id),S=ui({poolInfo:e,poolKeys:A,userKeys:{lpTokenAccount:g,baseTokenAccount:v,quoteTokenAccount:k,owner:this.scope.ownerPubKey},lpAmount:y,baseAmountMin:0,quoteAmountMin:0});h.addInstruction({instructions:[S],instructionTypes:[e.pooltype.includes("StablePool")?iw.AmmV5RemoveLiquidity:iw.AmmV4RemoveLiquidity],lookupTableAddress:A.lookupTableAccount?[A.lookupTableAccount]:[]});let[I,T]=e.mintA.address===t.mintA.address?[v,k]:[k,v],E=await this.scope.clmm.getClmmPoolKeys(t.id),P=await sW.openPositionFromBaseInstructions(t1(t0({poolInfo:t,poolKeys:E,ownerInfo:{feePayer:this.scope.ownerPubKey,wallet:this.scope.ownerPubKey,tokenAccountA:I,tokenAccountB:T},withMetadata:"create"},r),{base:a,getEphemeralSigners:p}));return h.addInstruction({instructions:[...P.instructions],signers:P.signers,instructionTypes:[...P.instructionTypes],lookupTableAddress:E.lookupTableAccount?[E.lookupTableAccount]:[]}),0===f?h.sizeCheckBuildV0():h.sizeCheckBuild()}async createPoolV4({programId:e,marketInfo:t,baseMintInfo:n,quoteMintInfo:r,baseAmount:i,quoteAmount:o,startTime:a,ownerInfo:s,associatedOnly:u=!1,checkCreateATAOwner:l=!1,tokenProgram:c,txVersion:d,feeDestinationId:p,computeBudgetConfig:f}){var h;let m=s.feePayer||(null==(h=this.scope.owner)?void 0:h.publicKey),g=s.useSOLBalance&&n.mint.equals(td.Gd),y=s.useSOLBalance&&r.mint.equals(td.Gd),b=this.createTxBuilder(),{account:_,instructionParams:v}=await this.scope.account.getOrCreateTokenAccount({mint:n.mint,owner:this.scope.ownerPubKey,createInfo:g?{payer:m,amount:i}:void 0,notUseTokenAccount:g,skipCloseAccount:!g,associatedOnly:!g&&u,checkCreateATAOwner:l});b.addInstruction(v||{});let{account:w,instructionParams:k}=await this.scope.account.getOrCreateTokenAccount({mint:r.mint,owner:this.scope.ownerPubKey,createInfo:y?{payer:m,amount:o}:void 0,notUseTokenAccount:y,skipCloseAccount:!y,associatedOnly:!y&&u,checkCreateATAOwner:l});if(b.addInstruction(k||{}),void 0===_||void 0===w)throw Error("you don't has some token account");let x=ud({version:4,marketVersion:3,marketId:t.marketId,baseMint:n.mint,quoteMint:r.mint,baseDecimals:n.decimals,quoteDecimals:r.decimals,programId:e,marketProgramId:t.programId}),A={programId:e,ammId:x.id,ammAuthority:x.authority,ammOpenOrders:x.openOrders,lpMint:x.lpMint,coinMint:x.baseMint,pcMint:x.quoteMint,coinVault:x.baseVault,pcVault:x.quoteVault,withdrawQueue:x.withdrawQueue,ammTargetOrders:x.targetOrders,poolTempLp:x.lpVault,marketProgramId:x.marketProgramId,marketId:x.marketId,ammConfigId:x.configId,feeDestinationId:p},{instruction:S,instructionType:I}=uo(t1(t0({},A),{userWallet:this.scope.ownerPubKey,userCoinVault:_,userPcVault:w,userLpVault:iN(this.scope.ownerPubKey,x.lpMint,c).publicKey,nonce:x.nonce,openTime:a,coinAmount:i,pcAmount:o}));return b.addInstruction({instructions:[S],instructionTypes:[I]}),b.addCustomComputeBudget(f),b.versionBuild({txVersion:d,extInfo:{address:A}})}async createMarketAndPoolV4({programId:e=iW,marketProgram:t=iz,feeDestinationId:n=iX,tokenProgram:r,baseMintInfo:i,quoteMintInfo:o,baseAmount:a,quoteAmount:s,startTime:u,ownerInfo:l,lowestFeeMarket:c,assignSeed:d,associatedOnly:p=!1,checkCreateATAOwner:f=!1,lotSize:h=1,tickSize:m=.01,txVersion:g,computeBudgetConfig:y}){var b,_,v;let w=this.scope.ownerPubKey,k=l.feePayer||(null==(b=this.scope.owner)?void 0:b.publicKey),x=l.useSOLBalance&&i.mint.equals(td.Gd),A=l.useSOLBalance&&o.mint.equals(td.Gd),S=d?`${i.mint.toBase58().slice(0,7)}-${o.mint.toBase58().slice(0,7)}-${d}`:void 0,I=o4({fromPublicKey:w,programId:t,assignSeed:S&&`${S}-market`}),T=o4({fromPublicKey:w,programId:t,assignSeed:S&&`${S}-request`}),E=o4({fromPublicKey:w,programId:t,assignSeed:S&&`${S}-event`}),P=o4({fromPublicKey:w,programId:t,assignSeed:S&&`${S}-bids`}),C=o4({fromPublicKey:w,programId:t,assignSeed:S&&`${S}-asks`}),O=o4({fromPublicKey:w,programId:td.H_,assignSeed:S&&`${S}-baseVault`}),B=o4({fromPublicKey:w,programId:td.H_,assignSeed:S&&`${S}-quoteVault`}),M=new(tb())(100),{vaultOwner:R,vaultSignerNonce:L}=function(){let e=new(tb())(0);for(;;)try{return{vaultOwner:tu.nh.createProgramAddressSync([I.publicKey.toBuffer(),e.toArrayLike(tK,"le",8)],t),vaultSignerNonce:e}}catch{if(e.iaddn(1),e.gt(new(tb())(25555)))throw Error("find vault owner error")}}(),N=new(tb())(Math.round(10**i.decimals*h)),D=new(tb())(Math.round(h*10**o.decimals*m));if(N.eq(ih))throw Error("lot size is too small");if(D.eq(ih))throw Error("tick size or lot size is too small");let F=await ug({connection:this.scope.connection,wallet:this.scope.ownerPubKey,marketInfo:{programId:t,vaultOwner:R,baseMint:i.mint,quoteMint:o.mint,id:I,baseVault:O,quoteVault:B,requestQueue:T,eventQueue:E,bids:P,asks:C,feeRateBps:0,quoteDustThreshold:M,vaultSignerNonce:L,baseLotSize:N,quoteLotSize:D,lowestFeeMarket:c}}),q=this.createTxBuilder();for await(let e of(q.addInstruction({instructions:F[0].transaction.instructions,signers:F[0].signer}),F.slice(1,F.length)))q.addInstruction({instructions:e.transaction.instructions,signers:e.signer,instructionTypes:e.instructionTypes});let{account:j,instructionParams:U}=await this.scope.account.getOrCreateTokenAccount({mint:i.mint,owner:this.scope.ownerPubKey,createInfo:x?{payer:k,amount:a}:void 0,notUseTokenAccount:x,skipCloseAccount:!x,associatedOnly:!x&&p,checkCreateATAOwner:f,assignSeed:x&&S?`${S}-wsol`:void 0});q.addInstruction(U||{});let{account:z,instructionParams:V}=await this.scope.account.getOrCreateTokenAccount({mint:o.mint,owner:this.scope.ownerPubKey,createInfo:A?{payer:k,amount:s}:void 0,notUseTokenAccount:A,skipCloseAccount:!A,associatedOnly:!A&&p,checkCreateATAOwner:f,assignSeed:A&&S?`${S}-wsol`:void 0});if(q.addInstruction(V||{}),void 0===j)throw Error("you don't has base token account");if(void 0===z)throw Error("you don't has quote token account");let W=ud({version:4,marketVersion:3,marketId:I.publicKey,baseMint:i.mint,quoteMint:o.mint,baseDecimals:i.decimals,quoteDecimals:o.decimals,programId:e,marketProgramId:t}),$={programId:e,ammId:W.id,ammAuthority:W.authority,ammOpenOrders:W.openOrders,lpMint:W.lpMint,coinMint:W.baseMint,pcMint:W.quoteMint,coinVault:W.baseVault,pcVault:W.quoteVault,withdrawQueue:W.withdrawQueue,ammTargetOrders:W.targetOrders,poolTempLp:W.lpVault,marketProgramId:W.marketProgramId,marketId:W.marketId,ammConfigId:W.configId,feeDestinationId:n},{instruction:K,instructionType:H}=uo(t1(t0({},$),{userWallet:this.scope.ownerPubKey,userCoinVault:j,userPcVault:z,userLpVault:iN(this.scope.ownerPubKey,W.lpMint,r).publicKey,nonce:W.nonce,openTime:u,coinAmount:a,pcAmount:s}));q.addInstruction({instructions:[K],instructionTypes:[H]});let G=x||A?[(null==(_=null==U?void 0:U.instructions)?void 0:_[0])||(null==(v=null==V?void 0:V.instructions)?void 0:v[0])].filter(e=>!!e):void 0;return 0===g?q.sizeCheckBuildV0({computeBudgetConfig:y,splitIns:G,address:t0({requestQueue:T.publicKey,eventQueue:E.publicKey,bids:P.publicKey,asks:C.publicKey,baseVault:O.publicKey,quoteVault:B.publicKey,baseMint:new tu.nh(i.mint),quoteMin:new tu.nh(o.mint)},$)}):q.sizeCheckBuild({computeBudgetConfig:y,splitIns:G,address:t0({requestQueue:T.publicKey,eventQueue:E.publicKey,bids:P.publicKey,asks:C.publicKey,baseVault:O.publicKey,quoteVault:B.publicKey,baseMint:new tu.nh(i.mint),quoteMin:new tu.nh(o.mint)},$)})}async getCreatePoolFee({programId:e}){let t=uu({programId:e}),n=await this.scope.connection.getAccountInfo(t,{dataSlice:{offset:536,length:8}});if(null===n)throw Error("get config account error");return s3.decode(n.data).fee}computeAmountOut({poolInfo:e,amountIn:t,mintIn:n,mintOut:r,slippage:i}){let[o,a]=[n.toString(),r.toString()];if(o!==e.mintA.address&&o!==e.mintB.address||a!==e.mintA.address&&a!==e.mintB.address)throw Error("toke not match");let{baseReserve:s,quoteReserve:u}=e,l=[s,u],c=[e.mintA.decimals,e.mintB.decimals],d=o==e.mintA.address?"base":"quote";"quote"===d&&(l.reverse(),c.reverse());let[p,f]=l,[h,m]=c,g=4===e.version,y;if(g)y=new rM(f.toString()).div(10**m).div(new rM(p.toString()).div(10**h));else{var b,_;let e,t;let n=(b=this.stableLayout.stableModelData,_=s.toNumber(),t=((e=ut(b,s7(b,_,s9(b,_,u.toNumber())),0,!1))[3]?e[0]:0)/b.multiplier,1/t);y="quote"===d?new rM(1e6).div(1e6*n):new rM(1e6*n).div(1e6)}let v=new(tb())(0),w=new(tb())(0);if(!t.isZero()){if(g){w=ot(t.mul(sX),sQ);let e=t.sub(w),n=p.add(e);v=f.mul(e).div(n)}else{w=t.mul(new(tb())(2)).div(new(tb())(1e4));let e=t.sub(w);v=new(tb())("quote"===d?function(e,t,n,r){let i=s9(e,t,n),o=s7(e,t,i),a=s7(e,n,i),s=s7(e,r,i),[u,l,c,d]=ut(e,o,s,!0);return d?c?r*e.multiplier/u:ue(e,a-l,i):0}(this.stableLayout.stableModelData,u.toNumber(),s.toNumber(),e.toNumber()):function(e,t,n,r){let i=s9(e,t,n),o=s7(e,t,i),a=s7(e,n,i),s=s7(e,r,i),[u,l,c,d]=function(e,t,n,r){let i=r?t-n:t+n,[o,a,s]=function(e,t){let[n,r]=[0,49998],i=n,o=r,a=0;for(;i<=o&&!((a=Math.floor((o+i)/2))<=0)&&!(a>=49998);){let n=e.DataElement[a].y,r=e.DataElement[a-1].y,s=e.DataElement[a+1].y;if(t===n)return[a,a,!0];if(t===r)return[a-1,a-1,!0];if(t===s)return[a+1,a+1,!0];if(tn)return[a-1,a,!0];if(ts)return[a,a+1,!0];o=a-1}}return[a,a,!1]}(e,i);if(!s)return[0,0,!1,s];if(o===a)return[e.DataElement[a].price,e.DataElement[a].x,!1,s];{let n=e.DataElement[o].x,u=e.DataElement[a].x,l=e.DataElement[o].price,c=e.DataElement[a].price,d=e.DataElement[o].y,p=e.DataElement[a].y;if(t>=p&&t<=d)return r?[c,u,!0,s]:[l,n,!0,s];{let o,a;return r?(o=l+(c-l)*(d-t)/(d-p),a=n+c*(d-i)/e.multiplier):(o=l+(c-l)*(d-t)/(d-p),a=u-l*(i-p)/e.multiplier),[o,a,!1,s]}}}(e,a,s,!1);return d?c?r*u/e.multiplier:ue(e,o-l,i):0}(this.stableLayout.stableModelData,u.toNumber(),s.toNumber(),e.toNumber()))}}let k=new(tb())(new rM(v.toString()).mul(1-i).toFixed(0)),x=v,A=new rM(v.toString()).div(new rM(t.sub(w).toString()).toFixed(0));t.isZero()||v.isZero()||(A=new rM(v.toString()).div(10**m).div(new rM(t.sub(w).toString()).div(10**h)));let S=y.sub(A).div(y).mul(100);return{amountOut:x,minAmountOut:k,currentPrice:y,executionPrice:A,priceImpact:S,fee:w}}computeAmountIn({poolInfo:e,amountOut:t,mintIn:n,mintOut:r,slippage:i}){let{baseReserve:o,quoteReserve:a}=e;n.toString()!==e.mintA.address&&n.toString()!==e.mintB.address&&this.logAndCreateError("mintIn does not match pool"),r.toString()!==e.mintA.address&&r.toString()!==e.mintB.address&&this.logAndCreateError("mintOut does not match pool"),this.logDebug("baseReserve:",o.toString()),this.logDebug("quoteReserve:",a.toString());let s=n.toString()===e.mintA.address,[u,l]=s?[e.mintA,e.mintB]:[e.mintB,e.mintA];this.logDebug("currencyOut:",l.symbol||l.address),this.logDebug("amountOut:",new rM(t.toString()).div(10**l.decimals).toDecimalPlaces(l.decimals).toString(),u.symbol||u.address),this.logDebug("slippage:",`${100*i}%`);let c=[o,a],d=s?"quote":"base";"base"===d&&c.reverse(),this.logDebug("output side:",d);let[p,f]=c,h=new rM(f.toString()).div(10**e[s?"mintB":"mintA"].decimals).div(new rM(p.toString()).div(10**e[s?"mintA":"mintB"].decimals));this.logDebug("currentPrice:",`1 ${u.symbol||u.address} \u2248 ${h.toString()} ${l.symbol||l.address}`),this.logDebug("currentPrice invert:",`1 ${l.symbol||l.address} \u2248 ${new rM(1).div(h).toString()} ${u.symbol||u.address}`);let m=new(tb())(0),g=t;if(!g.isZero()){g.gt(f)&&(g=f.sub(new(tb())(1)));let e=f.sub(g);m=p.mul(g).div(e).mul(sQ).div(sQ.sub(sX))}let y=new(tb())(new rM(m.toString()).mul(1+i).toFixed(0)),b=m;this.logDebug("amountIn:",new rM(b.toString()).div(10**u.decimals).toDecimalPlaces(u.decimals).toString()),this.logDebug("maxAmountIn:",new rM(y.toString()).div(10**u.decimals).toDecimalPlaces(u.decimals).toString());let _=null;m.isZero()||g.isZero()||(_=new rM(g.toString()).div(10**l.decimals).div(new rM(m.toString()).div(10**u.decimals)),this.logDebug("executionPrice:",`1 ${l.symbol||l.address} \u2248 ${_.toDecimalPlaces(Math.max(e.mintA.decimals,e.mintB.decimals)).toString()} ${u.symbol||u.address}`),this.logDebug("executionPrice invert:",`1 ${l.symbol||l.address} \u2248 ${new rM(1).div(_).toDecimalPlaces(Math.max(e.mintA.decimals,e.mintB.decimals)).toString()} ${u.symbol||u.address}`));let v=h.mul(b.toString()),w=v.sub(t.toString()).abs().div(v);return this.logDebug("priceImpact:",`${w.toString()}%`),{amountIn:b,maxAmountIn:y,currentPrice:h,executionPrice:_,priceImpact:w}}async swap({poolInfo:e,poolKeys:t,amountIn:n,amountOut:r,inputMint:i,fixedSide:o,txVersion:a,config:s,computeBudgetConfig:u}){let l=this.createTxBuilder(),{associatedOnly:c=!0,inputUseSolBalance:d=!0,outputUseSolBalance:p=!0}=s||{},[f,h]=i===e.mintA.address?[e.mintA,e.mintB]:[e.mintB,e.mintA],m=d&&f.address===r7.toBase58(),g=p&&h.address===r7.toBase58(),{account:y,instructionParams:b}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:td.H_,mint:new tu.nh(f.address),owner:this.scope.ownerPubKey,createInfo:m?{payer:this.scope.ownerPubKey,amount:n}:void 0,skipCloseAccount:!m,notUseTokenAccount:m,associatedOnly:c});l.addInstruction(b||{}),y||this.logAndCreateError("input token account not found",{token:f.symbol||f.address,tokenAccountIn:y,inputTokenUseSolBalance:m,associatedOnly:c});let{account:_,instructionParams:v}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:td.H_,mint:new tu.nh(h.address),owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!g,notUseTokenAccount:g,associatedOnly:!g&&c});l.addInstruction(v||{}),void 0===_&&this.logAndCreateError("output token account not found",{token:h.symbol||h.address,tokenAccountOut:_,outputTokenUseSolBalance:g,associatedOnly:c});let w=t||await this.getAmmPoolKeys(e.id),k=4;return e.pooltype.includes("StablePool")&&(k=5),l.addInstruction({instructions:[ua({version:k,poolKeys:w,userKeys:{tokenAccountIn:y,tokenAccountOut:_,owner:this.scope.ownerPubKey},amountIn:n,amountOut:r,fixedSide:o})],instructionTypes:[4===k?iw.AmmV4SwapBaseIn:iw.AmmV5SwapBaseIn]}),l.addCustomComputeBudget(u),l.versionBuild({txVersion:a})}async getRpcPoolInfo(e){return(await this.getRpcPoolInfos([e]))[e]}async getRpcPoolInfos(e,t){let n=await ne(this.scope.connection,e.map(e=>({pubkey:new tu.nh(e)})),t),r={},i=[];for(let t=0;t({pubkey:new tu.nh(e)})),t);for(let e=0;ee.mint.address===n.toString());s||this.logAndCreateError("reward mint error","not found reward mint",n);let u=this.createTxBuilder(),l=t.useSOLBalance&&n.equals(r7),{account:c,instructionParams:d}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new tu.nh(s.mint.programId),mint:n,notUseTokenAccount:l,owner:this.scope.ownerPubKey,skipCloseAccount:!l,createInfo:{payer:t.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:!l&&r,checkCreateATAOwner:i});d&&u.addInstruction(d),c||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos);let p=await this.getClmmPoolKeys(e.id),f=sW.collectRewardInstructions({poolInfo:e,poolKeys:p,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:c},rewardMint:n});return u.addInstruction(f),u.addCustomComputeBudget(o),u.versionBuild({txVersion:a,extInfo:{address:f.address}})}async collectRewards({poolInfo:e,ownerInfo:t,rewardMints:n,associatedOnly:r=!0,checkCreateATAOwner:i=!1}){let o=this.createTxBuilder(),a={};for(let s of n){let n=e.rewardDefaultInfos.find(e=>e.mint.address===s.toString());if(!n){this.logAndCreateError("reward mint error","not found reward mint",s);continue}let u=t.useSOLBalance&&s.equals(r7),{account:l,instructionParams:c}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new tu.nh(n.mint.programId),mint:s,notUseTokenAccount:u,owner:this.scope.ownerPubKey,skipCloseAccount:!u,createInfo:{payer:t.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:!u&&r,checkCreateATAOwner:i});l||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos),c&&o.addInstruction(c);let d=await this.getClmmPoolKeys(e.id),p=sW.collectRewardInstructions({poolInfo:e,poolKeys:d,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:l},rewardMint:s});o.addInstruction(p),a=t0(t0({},a),p.address)}return o.build({address:a})}async swap({poolInfo:e,poolKeys:t,inputMint:n,amountIn:r,amountOutMin:i,priceLimit:o,observationId:a,ownerInfo:s,remainingAccounts:u,associatedOnly:l=!0,checkCreateATAOwner:c=!1,txVersion:d,computeBudgetConfig:p}){let f,h,m=this.createTxBuilder(),g=n.toString()===e.mintA.address,y=s.useSOLBalance&&e.mintA.address===r7.toBase58(),b=s.useSOLBalance&&e.mintB.address===r7.toBase58(),_;if(_=!o||o.equals(new rM(0))?g?aG.add(new(tb())(1)):aZ.sub(new(tb())(1)):sw.priceToSqrtPriceX64(o,e.mintA.decimals,e.mintB.decimals),!f){let{account:t,instructionParams:n}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintA.programId,mint:new tu.nh(e.mintA.address),notUseTokenAccount:y,owner:this.scope.ownerPubKey,skipCloseAccount:!y,createInfo:y||!g?{payer:s.feePayer||this.scope.ownerPubKey,amount:g?r:0}:void 0,associatedOnly:!y&&l,checkCreateATAOwner:c});f=t,n&&m.addInstruction(n)}if(!h){let{account:t,instructionParams:n}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintB.programId,mint:new tu.nh(e.mintB.address),notUseTokenAccount:b,owner:this.scope.ownerPubKey,skipCloseAccount:!b,createInfo:b||g?{payer:s.feePayer||this.scope.ownerPubKey,amount:g?0:r}:void 0,associatedOnly:!b&&l,checkCreateATAOwner:c});h=t,n&&m.addInstruction(n)}f&&h||this.logAndCreateError("user do not have token account",{tokenA:e.mintA.symbol||e.mintA.address,tokenB:e.mintB.symbol||e.mintB.address,ownerTokenAccountA:f,ownerTokenAccountB:h,mintAUseSOLBalance:y,mintBUseSOLBalance:b,associatedOnly:l});let v=null!=t?t:await this.getClmmPoolKeys(e.id);return m.addInstruction(sW.makeSwapBaseInInstructions({poolInfo:e,poolKeys:v,observationId:a,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:f,tokenAccountB:h},inputMint:new tu.nh(n),amountIn:r,amountOutMin:i,sqrtPriceLimitX64:_,remainingAccounts:u})),m.addCustomComputeBudget(p),m.versionBuild({txVersion:d})}async swapBaseOut({poolInfo:e,poolKeys:t,outputMint:n,amountOut:r,amountInMax:i,priceLimit:o,observationId:a,ownerInfo:s,remainingAccounts:u,associatedOnly:l=!0,checkCreateATAOwner:c=!1,txVersion:d,computeBudgetConfig:p}){let f,h,m=this.createTxBuilder(),g=n.toString()===e.mintB.address,y=s.useSOLBalance&&e.mintA.address===r7.toBase58(),b=s.useSOLBalance&&e.mintB.address===r7.toBase58(),_;if(_=!o||o.equals(new rM(0))?n.toString()===e.mintB.address?aG.add(new(tb())(1)):aZ.sub(new(tb())(1)):sw.priceToSqrtPriceX64(o,e.mintA.decimals,e.mintB.decimals),!f){let{account:t,instructionParams:n}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintA.programId,mint:new tu.nh(e.mintA.address),notUseTokenAccount:y,owner:this.scope.ownerPubKey,skipCloseAccount:!y,createInfo:y||!g?{payer:s.feePayer||this.scope.ownerPubKey,amount:g?i:0}:void 0,associatedOnly:!y&&l,checkCreateATAOwner:c});f=t,n&&m.addInstruction(n)}if(!h){let{account:t,instructionParams:n}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintB.programId,mint:new tu.nh(e.mintB.address),notUseTokenAccount:b,owner:this.scope.ownerPubKey,skipCloseAccount:!b,createInfo:b||g?{payer:s.feePayer||this.scope.ownerPubKey,amount:g?0:i}:void 0,associatedOnly:!b&&l,checkCreateATAOwner:c});h=t,n&&m.addInstruction(n)}f&&h||this.logAndCreateError("user do not have token account",{tokenA:e.mintA.symbol||e.mintA.address,tokenB:e.mintB.symbol||e.mintB.address,ownerTokenAccountA:f,ownerTokenAccountB:h,mintAUseSOLBalance:y,mintBUseSOLBalance:b,associatedOnly:l});let v=null!=t?t:await this.getClmmPoolKeys(e.id);return m.addInstruction(sW.makeSwapBaseOutInstructions({poolInfo:e,poolKeys:v,observationId:a,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:f,tokenAccountB:h},outputMint:new tu.nh(n),amountOut:r,amountInMax:i,sqrtPriceLimitX64:_,remainingAccounts:u})),m.addCustomComputeBudget(p),m.versionBuild({txVersion:d})}async harvestAllRewards({allPoolInfo:e,allPositions:t,lockInfo:n,ownerInfo:r,associatedOnly:i=!0,checkCreateATAOwner:o=!1,programId:a,txVersion:s,computeBudgetConfig:u}){var l,c;let d={};for(let e of this.scope.account.tokenAccountRawInfos)i?iN(this.scope.ownerPubKey,e.accountInfo.mint,a).publicKey.equals(e.pubkey)&&(d[e.accountInfo.mint.toString()]=e.pubkey):d[e.accountInfo.mint.toString()]=e.pubkey;let p=Object.values(t).flat().map(e=>e.nftMint),f=await ne(this.scope.connection,p.map(e=>({pubkey:e}))),h={};f.forEach(e=>{var t,n;h[e.pubkey.toBase58()]=null!=(n=null==(t=null==e?void 0:e.accountInfo)?void 0:t.owner)?n:null});let m=this.createTxBuilder();for(let a of Object.values(e)){if(void 0===t[a.id]||!t[a.id].find(e=>!e.liquidity.isZero()||e.rewardInfos.find(e=>!e.rewardAmountOwed.isZero())))continue;let e=a,s=r.useSOLBalance&&e.mintA.address===r7.toString(),u=r.useSOLBalance&&e.mintB.address===r7.toString(),p=d[e.mintA.address];if(!p){let{account:t,instructionParams:n}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintA.programId,mint:new tu.nh(e.mintA.address),notUseTokenAccount:s,owner:this.scope.ownerPubKey,skipCloseAccount:!s,createInfo:{payer:r.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:!s&&i,checkCreateATAOwner:o});p=t,n&&m.addInstruction(n)}let f=d[e.mintB.address];if(!f){let{account:t,instructionParams:n}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintB.programId,mint:new tu.nh(e.mintB.address),notUseTokenAccount:u,owner:this.scope.ownerPubKey,skipCloseAccount:!u,createInfo:{payer:r.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:!u&&i,checkCreateATAOwner:o});f=t,n&&m.addInstruction(n)}d[e.mintA.address]=p,d[e.mintB.address]=f;let g=[];for(let t of e.rewardDefaultInfos){let e=r.useSOLBalance&&t.mint.address===r7.toString(),n=d[t.mint.address];if(!n){let{account:o,instructionParams:a}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new tu.nh(t.mint.programId),mint:new tu.nh(t.mint.address),notUseTokenAccount:e,owner:this.scope.ownerPubKey,skipCloseAccount:!e,createInfo:{payer:r.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:!e&&i});n=o,a&&m.addInstruction(a)}d[t.mint.address]=n,g.push(n)}let y=await this.getClmmPoolKeys(e.id),b=[];for(let e=0;e!e.equals(tu.nh.default)):[]}async getOwnerPositionInfo({programId:e}){await this.scope.account.fetchWalletTokenAccounts();let t=this.scope.account.tokenAccountRawInfos.filter(e=>e.accountInfo.amount.eq(new(tb())(1))).map(t=>sa(new tu.nh(e),t.accountInfo.mint).publicKey),n=await this.scope.connection.getMultipleAccountsInfo(t),r=[];return n.forEach(e=>{if(!e)return;let t=sR.decode(e.data);r.push(t)}),r}async getRpcClmmPoolInfo({poolId:e}){return(await this.getRpcClmmPoolInfos({poolIds:[e]}))[String(e)]}async getRpcClmmPoolInfos({poolIds:e,config:t}){let n=await ne(this.scope.connection,e.map(e=>({pubkey:new tu.nh(e)})),t),r={};for(let t=0;te[t].ammConfig.toBase58())),r=await ne(this.scope.connection,Array.from(n).map(e=>({pubkey:new tu.nh(e)}))),i={};r.forEach(e=>{e.accountInfo&&(i[e.pubkey.toBase58()]=sE.decode(e.accountInfo.data))});let o=await sg.fetchComputeMultipleClmmInfo({connection:this.scope.connection,rpcDataMap:e,poolList:Object.keys(e).map(n=>{var r,o,a,s;let[u,l]=[e[n].mintA.toBase58(),e[n].mintB.toBase58()];return{id:n,programId:e[n].programId.toBase58(),mintA:sZ({address:u,decimals:e[n].mintDecimalsA,programId:t[u].programId.toBase58()||td.H_.toBase58(),extensions:{feeConfig:null!=(r=t[u])&&r.feeConfig?sY(null==(o=t[u])?void 0:o.feeConfig):void 0}}),mintB:sZ({address:l,decimals:e[n].mintDecimalsB,programId:t[l].programId.toBase58()||td.H_.toBase58(),extensions:{feeConfig:null!=(a=t[l])&&a.feeConfig?sY(null==(s=t[l])?void 0:s.feeConfig):void 0}}),price:e[n].currentPrice,config:t1(t0({},i[e[n].ammConfig.toBase58()]),{id:e[n].ammConfig.toBase58(),fundFeeRate:0,description:"",defaultRange:0,defaultRangePoint:[]})}})}),a=await sg.fetchMultiplePoolTickArrays({connection:this.scope.connection,poolKeys:Object.values(o)});return{computeClmmPoolInfo:o,computePoolTickData:a}}async getPoolInfoFromRpc(e){var t,n;let r=await this.getRpcClmmPoolInfo({poolId:e}),i=new Set([r.mintA.toBase58(),r.mintB.toBase58()]),o=await nn({connection:this.scope.connection,mints:Array.from(i).map(e=>new tu.nh(e))}),{computeClmmPoolInfo:a,computePoolTickData:s}=await this.scope.clmm.getComputeClmmPoolInfos({clmmPoolsRpcInfo:{[e]:r},mintInfos:o}),u=await ne(this.scope.connection,[{pubkey:r.vaultA},{pubkey:r.vaultB}]),l=t1(t0({},n=a[e]),{type:"Concentrated",programId:n.programId.toString(),id:n.id.toString(),rewardDefaultInfos:[],rewardDefaultPoolInfos:"Clmm",price:n.currentPrice.toNumber(),mintAmountA:0,mintAmountB:0,feeRate:n.ammConfig.tradeFeeRate,openTime:n.startTime.toString(),tvl:0,day:sy,week:sy,month:sy,pooltype:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0,burnPercent:0,config:t1(t0({},n.ammConfig),{id:n.ammConfig.id.toString(),defaultRange:0,defaultRangePoint:[]})});if(!u[0].accountInfo||!u[1].accountInfo)throw Error("pool vault data not found");l.mintAmountA=Number(tN.p0.decode(u[0].accountInfo.data).amount.toString()),l.mintAmountB=Number(tN.p0.decode(null==(t=u[1].accountInfo)?void 0:t.data).amount.toString());let c=t1(t0({},a[e]),{exBitmapAccount:a[e].exBitmapAccount.toBase58(),observationId:a[e].observationId.toBase58(),id:e,programId:r.programId.toBase58(),openTime:r.startTime.toString(),vault:{A:r.vaultA.toBase58(),B:r.vaultB.toBase58()},config:l.config,rewardInfos:a[e].rewardInfos.filter(e=>!e.tokenVault.equals(tu.nh.default)).map(e=>({mint:sZ({address:e.tokenMint.toBase58(),programId:td.H_.toBase58(),decimals:10}),vault:e.tokenVault.toBase58()}))});return{poolInfo:l,poolKeys:c,computePoolInfo:a[e],tickData:s}}};function uv(e,t){if(t.isZero())throw Error("divisor is zero");return e.mod(t)}var uw=new(tb())(0),uk=class{static swapWithoutFees(e,t,n){let[r,i]=function(e,t){if(t.isZero())throw Error("rhs is zero");let n=e.div(t);if(n.isZero())throw Error("quotient is zero");let r=uv(e,t);return r.gt(uw)&&(n=n.add(new(tb())(1)),t=e.div(n),(r=uv(e,n)).gt(uw)&&(t=t.add(new(tb())(1)))),[n,t]}(t.mul(n),t.add(e)),o=i.sub(t),a=n.sub(r);if(a.isZero())throw Error("destinationAmountSwapped is zero");return{sourceAmountSwapped:o,destinationAmountSwapped:a}}static lpTokensToTradingTokens(e,t,n,r,i){let o=e.mul(n).div(t),a=e.mul(r).div(t);if(0===i)return{tokenAmount0:o,tokenAmount1:a};if(1===i)return uv(e.mul(n),t).gt(uw)&&o.gt(uw)&&(o=o.add(new(tb())(1))),uv(e.mul(r),t).gt(uw)&&a.gt(uw)&&(a=a.add(new(tb())(1))),{tokenAmount0:o,tokenAmount1:a};throw Error("roundDirection value error")}},ux=new(tb())(1e6),uA=class{static tradingFee(e,t){return e.mul(t).add(ux).sub(new(tb())(1)).div(ux)}static protocolFee(e,t){return e.mul(t).div(ux)}static fundFee(e,t){return e.mul(t).div(ux)}},uS=((d=uS||{})[d.Floor=0]="Floor",d[d.Ceiling=1]="Ceiling",d),uI=class{static validate_supply(e,t){if(e.isZero())throw Error("tokenAmount0 is zero");if(t.isZero())throw Error("tokenAmount1 is zero")}static swap(e,t,n,r){let i=uA.tradingFee(e,r),o=e.sub(i),{sourceAmountSwapped:a,destinationAmountSwapped:s}=uk.swapWithoutFees(o,t,n),u=a.add(i);return{newSwapSourceAmount:t.add(u),newSwapDestinationAmount:n.sub(s),sourceAmountSwapped:u,destinationAmountSwapped:s,tradeFee:i}}static swapBaseOut({poolMintA:e,poolMintB:t,tradeFeeRate:n,baseReserve:r,quoteReserve:i,outputMint:o,outputAmount:a}){let[s,u,l,c,d]=t.address===o.toString()?[r,i,e.decimals,t.decimals,e.address]:[i,r,t.decimals,e.decimals,t.address],p=new(tM())(u.toString()).div(10**c).div(new(tM())(s.toString()).div(10**l)),f=a.gte(u)?u.sub(new(tb())(1)):a,h=u.sub(f),m=ot(s.mul(f),h),g=ot(m.mul(new(tb())(1e6)),new(tb())(1e6).sub(n)),y=g.sub(m),b=new(tM())(f.toString()).div(10**c).div(new(tM())(g.toString()).div(10**l));return{amountRealOut:f,amountIn:g,amountInWithoutFee:m,tradeFee:y,priceImpact:p.isZero()?0:b.sub(p).div(p).abs().toNumber()}}},uT=tK.from("vault_and_lp_mint_auth_seed","utf8"),uE=tK.from("amm_config","utf8"),uP=tK.from("pool","utf8"),uC=tK.from("pool_lp_mint","utf8"),uO=tK.from("pool_vault","utf8"),uB=tK.from("observation","utf8");function uM(e){return iP([uT],e)}function uR(e,t){let n;return iP([uE,(n=new ArrayBuffer(2),new DataView(n).setUint16(0,t,!1),new Uint8Array(n))],e)}function uL(e,t,n,r){return iP([uP,t.toBuffer(),n.toBuffer(),r.toBuffer()],e)}function uN(e,t,n){return iP([uO,t.toBuffer(),n.toBuffer()],e)}function uD(e,t){return iP([uB,t.toBuffer()],e)}var uF=tK.from("locked_liquidity","utf8");function uq(e,t){return iP([uF,t.toBuffer()],e)}var uj=t8("Raydium_cpmm"),uU={initialize:[175,175,109,31,13,152,155,237],deposit:[242,35,198,137,82,225,242,182],withdraw:[183,18,70,156,148,109,161,34],swapBaseInput:[143,190,90,218,196,30,51,222],swapBaseOutput:[55,217,98,86,163,74,180,173],lockCpLiquidity:[216,157,29,78,38,51,31,26],collectCpFee:[8,30,51,199,209,184,247,133]};function uz(e,t,n,r,i,o,a,s,u,l,c,d,p,f,h,m){let g=o2([oH("amountIn"),oH("amounOutMin")]),y=tK.alloc(g.span);return g.encode({amountIn:h,amounOutMin:m},y),new tu.Sl({keys:[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!0}],programId:e,data:tK.from([...uU.swapBaseInput,...y])})}async function uV(e){var t;let{ownerInfo:n,poolInfo:r,poolKeys:i,getEphemeralSigners:o}=e,a=[],[s,u]=[new tu.nh(r.id),new tu.nh(r.lpMint.address)],l;if(o)l=new tu.nh((await o(1))[0]);else{let e=tu.RG.generate();a.push(e),l=e.publicKey}let{publicKey:c}=iN(n.feePayer,l,td.H_),{publicKey:d}=ss(l),{publicKey:p}=uq(e.lockProgram,l),{publicKey:f}=iN(n.feePayer,u,td.H_),{publicKey:h}=iN(e.lockAuthProgram,u,td.H_),m=function({programId:e,auth:t,payer:n,liquidityOwner:r,nftOwner:i,nftMint:o,nftAccount:a,poolId:s,lockPda:u,mintLp:l,userLpVault:c,lockLpVault:d,poolVaultA:p,poolVaultB:f,metadataAccount:h,lpAmount:m,withMetadata:g}){let y=[{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!0},{pubkey:r,isSigner:!0,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!0,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:h,isSigner:!1,isWritable:!0},{pubkey:r2,isSigner:!1,isWritable:!1},{pubkey:tu.yc.programId,isSigner:!1,isWritable:!1},{pubkey:td.H_,isSigner:!1,isWritable:!1},{pubkey:td._u,isSigner:!1,isWritable:!1},{pubkey:r3,isSigner:!1,isWritable:!1}],b=o2([oH("lpAmount"),oQ("withMetadata")]),_=tK.alloc(b.span);b.encode({lpAmount:m,withMetadata:g},_);let v=tK.from([...uU.lockCpLiquidity,..._]);return new tu.Sl({keys:y,programId:e,data:v})}({programId:e.lockProgram,auth:e.lockAuthProgram,payer:n.feePayer,nftOwner:n.feePayer,liquidityOwner:n.feePayer,nftMint:l,nftAccount:c,poolId:s,lockPda:p,mintLp:u,userLpVault:f,lockLpVault:h,poolVaultA:new tu.nh(i.vault.A),poolVaultB:new tu.nh(i.vault.B),metadataAccount:d,lpAmount:e.lpAmount,withMetadata:null==(t=e.withMetadata)||t});return{address:{nftMint:l,nftAccount:c,metadataAccount:d,lockPda:p,userLpVault:f,lockLpVault:h},instructions:[m],signers:a,instructionTypes:[iw.CpmmLockLp],lookupTableAddress:[]}}var uW=o2([oU(8),o$("bump"),oQ("disableCreatePool"),oN("index"),oH("tradeFeeRate"),oH("protocolFeeRate"),oH("fundFeeRate"),oH("createPoolFee"),oX("protocolOwner"),oX("fundOwner"),o6(oH(),16)]),u$=o2([oU(8),oX("configId"),oX("poolCreator"),oX("vaultA"),oX("vaultB"),oX("mintLp"),oX("mintA"),oX("mintB"),oX("mintProgramA"),oX("mintProgramB"),oX("observationId"),o$("bump"),o$("status"),o$("lpDecimals"),o$("mintDecimalA"),o$("mintDecimalB"),oH("lpAmount"),oH("protocolFeesMintA"),oH("protocolFeesMintB"),oH("fundFeesMintA"),oH("fundFeesMintB"),oH("openTime"),o6(oH(),32)]),uK=class extends oy{constructor(e){super(e)}async load(){this.checkDisabled()}async getCpmmPoolKeys(e){return(await this.scope.api.fetchPoolKeysById({idList:[e]}))[0]}async getRpcPoolInfo(e,t){return(await this.getRpcPoolInfos([e],t))[e]}async getRpcPoolInfos(e,t){let n=await ne(this.scope.connection,e.map(e=>({pubkey:new tu.nh(e)}))),r={},i=new Set,o=[];for(let t=0;t({pubkey:new tu.nh(e)})));for(let n=0;n({pubkey:new tu.nh(e)})));for(let e=0;e{var i,o,a,s;let u=e[r],[l,c]=[u.mintA.toBase58(),u.mintB.toBase58()];return t1(t0({},n),{[r]:t1(t0({},u),{id:new tu.nh(r),configInfo:u.configInfo,version:7,authority:uM(u.programId).publicKey,mintA:sZ({address:l,decimals:u.mintDecimalA,programId:u.mintProgramA.toBase58(),extensions:{feeConfig:null!=(i=t[l])&&i.feeConfig?sY(null==(o=t[l])?void 0:o.feeConfig):void 0}}),mintB:sZ({address:c,decimals:u.mintDecimalB,programId:u.mintProgramB.toBase58(),extensions:{feeConfig:null!=(a=t[c])&&a.feeConfig?sY(null==(s=t[c])?void 0:s.feeConfig):void 0}})})})},{})}async getPoolInfoFromRpc(e){let t=await this.getRpcPoolInfo(e,!0),n=await nn({connection:this.scope.connection,mints:[t.mintA,t.mintB]}),r=sZ({address:t.mintA.toBase58(),decimals:t.mintDecimalA,programId:t.mintProgramA.toBase58(),extensions:{feeConfig:n[t.mintA.toBase58()].feeConfig?sY(n[t.mintA.toBase58()].feeConfig):void 0}}),i=sZ({address:t.mintB.toBase58(),decimals:t.mintDecimalB,programId:t.mintProgramB.toBase58(),extensions:{feeConfig:n[t.mintB.toBase58()].feeConfig?sY(n[t.mintB.toBase58()].feeConfig):void 0}}),o=sZ({address:t.mintLp.toBase58(),decimals:t.lpDecimals,programId:td.H_.toBase58()}),a={id:t.configId.toBase58(),index:t.configInfo.index,protocolFeeRate:t.configInfo.protocolFeeRate.toNumber(),tradeFeeRate:t.configInfo.tradeFeeRate.toNumber(),fundFeeRate:t.configInfo.fundFeeRate.toNumber(),createPoolFee:t.configInfo.createPoolFee.toString()},s={volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[]};return{poolInfo:{programId:t.programId.toBase58(),id:e,type:"Standard",lpMint:o,lpPrice:0,lpAmount:t.lpAmount.toNumber(),config:a,mintA:r,mintB:i,rewardDefaultInfos:[],rewardDefaultPoolInfos:"Ecosystem",price:t.poolPrice.toNumber(),mintAmountA:new rM(t.vaultAAmount.toString()).div(10**r.decimals).toNumber(),mintAmountB:new rM(t.vaultBAmount.toString()).div(10**i.decimals).toNumber(),feeRate:t.configInfo.tradeFeeRate.toNumber(),openTime:t.openTime.toString(),tvl:0,burnPercent:0,day:s,week:s,month:s,pooltype:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0},poolKeys:{programId:t.programId.toBase58(),id:e,mintA:r,mintB:i,openTime:t.openTime.toString(),vault:{A:t.vaultA.toBase58(),B:t.vaultB.toBase58()},authority:uM(t.programId).publicKey.toBase58(),mintLp:o,config:a,observationId:uD(t.programId,new tu.nh(e)).publicKey.toBase58()},rpcData:t}}async createPool(e){let t,n,r,i;var o,a,s,u,l,c,d,p,f,h,m,g,y,b,{poolId:_,programId:v,poolFeeAccount:w,startTime:k,ownerInfo:x,associatedOnly:A=!1,checkCreateATAOwner:S=!1,txVersion:I,feeConfig:T,computeBudgetConfig:E}=e,P=t2(e,["poolId","programId","poolFeeAccount","startTime","ownerInfo","associatedOnly","checkCreateATAOwner","txVersion","feeConfig","computeBudgetConfig"]);let C=x.feePayer||(null==(g=this.scope.owner)?void 0:g.publicKey),O=new(tb())(new tu.nh(P.mintA.address).toBuffer()).lte(new(tb())(new tu.nh(P.mintB.address).toBuffer())),[B,M]=O?[P.mintA,P.mintB]:[P.mintB,P.mintA],[R,L]=O?[P.mintAAmount,P.mintBAmount]:[P.mintBAmount,P.mintAAmount],N=x.useSOLBalance&&B.address===td.Gd.toBase58(),D=x.useSOLBalance&&M.address===td.Gd.toBase58(),[F,q]=[new tu.nh(B.address),new tu.nh(M.address)],j=this.createTxBuilder(),{account:U,instructionParams:z}=await this.scope.account.getOrCreateTokenAccount({mint:F,tokenProgram:B.programId,owner:this.scope.ownerPubKey,createInfo:N?{payer:C,amount:R}:void 0,notUseTokenAccount:N,skipCloseAccount:!N,associatedOnly:!N&&A,checkCreateATAOwner:S});j.addInstruction(z||{});let{account:V,instructionParams:W}=await this.scope.account.getOrCreateTokenAccount({mint:new tu.nh(M.address),tokenProgram:M.programId,owner:this.scope.ownerPubKey,createInfo:D?{payer:C,amount:L}:void 0,notUseTokenAccount:D,skipCloseAccount:!D,associatedOnly:!D&&A,checkCreateATAOwner:S});if(j.addInstruction(W||{}),void 0===U||void 0===V)throw Error("you don't has some token account");let $=function({poolId:e,programId:t,configId:n,mintA:r,mintB:i}){let o=uM(t).publicKey,a=e||uL(t,n,r,i).publicKey,s=iP([uC,a.toBuffer()],t).publicKey,u=uN(t,a,r).publicKey,l=uN(t,a,i).publicKey,c=uD(t,a).publicKey;return{poolId:a,configId:n,authority:o,lpMint:s,vaultA:u,vaultB:l,observationId:c}}({poolId:_,programId:v,configId:new tu.nh(T.id),mintA:F,mintB:q});return j.addInstruction({instructions:[(o=this.scope.ownerPubKey,a=new tu.nh(T.id),s=$.authority,u=$.poolId,l=$.lpMint,c=iN(this.scope.ownerPubKey,$.lpMint).publicKey,d=$.vaultA,p=$.vaultB,f=new tu.nh(null!=(y=B.programId)?y:td.H_),h=new tu.nh(null!=(b=M.programId)?b:td.H_),m=$.observationId,t=o2([oH("amountMaxA"),oH("amountMaxB"),oH("openTime")]),n=uL(v,a,F,q).publicKey,r=[{pubkey:o,isSigner:!0,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!u.equals(n),isWritable:!0},{pubkey:F,isSigner:!1,isWritable:!1},{pubkey:q,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:U,isSigner:!1,isWritable:!0},{pubkey:V,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:w,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:td.H_,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:h,isSigner:!1,isWritable:!1},{pubkey:td._u,isSigner:!1,isWritable:!1},{pubkey:r4,isSigner:!1,isWritable:!1},{pubkey:r2,isSigner:!1,isWritable:!1}],i=tK.alloc(t.span),t.encode({amountMaxA:R,amountMaxB:L,openTime:k},i),new tu.Sl({keys:r,programId:v,data:tK.from([...uU.initialize,...i])}))],instructionTypes:[iw.CpmmCreatePool]}),j.addCustomComputeBudget(E),j.versionBuild({txVersion:I,extInfo:{address:t1(t0({},$),{mintA:B,mintB:M,programId:v,poolFeeAccount:w,feeConfig:T})}})}async addLiquidity(e){var t,n,r,i,o,a,s,u,l,c;let d,p,f,{poolInfo:h,poolKeys:m,inputAmount:g,baseIn:y,slippage:b,computeResult:_,computeBudgetConfig:v,config:w,txVersion:k}=e;!1===this.scope.availability.addStandardPosition&&this.logAndCreateError("add liquidity feature disabled in your region"),g.isZero()&&this.logAndCreateError("amounts must greater than zero","amountInA",{amountInA:g.toString()});let{account:x}=this.scope,{bypassAssociatedCheck:A,checkCreateATAOwner:S}=t0({bypassAssociatedCheck:!1,checkCreateATAOwner:!1},w),I=_?void 0:await this.getRpcPoolInfo(h.id),{liquidity:T,inputAmountFee:E,anotherAmount:P}=_||this.computePairAmount({poolInfo:t1(t0({},h),{lpAmount:new rM(I.lpAmount.toString()).div(10**h.lpMint.decimals).toNumber()}),baseReserve:I.baseReserve,quoteReserve:I.quoteReserve,slippage:new is(0),baseIn:y,epochInfo:await this.scope.fetchEpochInfo(),amount:new rM(g.toString()).div(10**(y?h.mintA.decimals:h.mintB.decimals))}),C=P.amount,O=h.mintA.address===td.Gd.toString(),B=h.mintB.address===td.Gd.toString(),M=this.createTxBuilder(),[R,L]=[new tu.nh(h.mintA.address),new tu.nh(h.mintB.address)],{account:N,instructionParams:D}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:h.mintA.programId,mint:new tu.nh(h.mintA.address),owner:this.scope.ownerPubKey,createInfo:O||(y?g:C).isZero()?{payer:this.scope.ownerPubKey,amount:y?g:C}:void 0,skipCloseAccount:!O,notUseTokenAccount:O,associatedOnly:!1,checkCreateATAOwner:S});M.addInstruction(D||{});let{account:F,instructionParams:q}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:h.mintB.programId,mint:new tu.nh(h.mintB.address),owner:this.scope.ownerPubKey,createInfo:B||(y?C:g).isZero()?{payer:this.scope.ownerPubKey,amount:y?C:g}:void 0,skipCloseAccount:!B,notUseTokenAccount:B,associatedOnly:!1,checkCreateATAOwner:S});M.addInstruction(q||{}),N||F||this.logAndCreateError("cannot found target token accounts","tokenAccounts",x.tokenAccounts);let j=await x.getCreatedTokenAccount({mint:new tu.nh(h.lpMint.address)}),U=await x.handleTokenAccount({side:"out",amount:0,mint:new tu.nh(h.lpMint.address),tokenAccount:j,bypassAssociatedCheck:A,checkCreateATAOwner:S}),{tokenAccount:z}=U,V=t2(U,["tokenAccount"]);M.addInstruction(V);let W=null!=m?m:await this.getCpmmPoolKeys(h.id),$=new is(new(tb())(1)).sub(b);return M.addInstruction({instructions:[(t=new tu.nh(h.programId),n=this.scope.ownerPubKey,r=new tu.nh(W.authority),i=new tu.nh(h.id),o=new tu.nh(W.vault.A),a=new tu.nh(W.vault.B),s=new tu.nh(h.lpMint.address),u=_?null==_?void 0:_.liquidity:$.mul(T).quotient,l=y?E.amount:C,c=y?C:E.amount,d=o2([oH("lpAmount"),oH("amountMaxA"),oH("amountMaxB")]),p=[{pubkey:n,isSigner:!0,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:z,isSigner:!1,isWritable:!0},{pubkey:N,isSigner:!1,isWritable:!0},{pubkey:F,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:td.H_,isSigner:!1,isWritable:!1},{pubkey:td.nA,isSigner:!1,isWritable:!1},{pubkey:R,isSigner:!1,isWritable:!1},{pubkey:L,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0}],f=tK.alloc(d.span),uj.debug("cpmm deposit data",{lpAmount:u.toString(),amountMaxA:l.toString(),amountMaxB:c.toString()}),d.encode({lpAmount:u,amountMaxA:l,amountMaxB:c},f),new tu.Sl({keys:p,programId:t,data:tK.from([...uU.deposit,...f])}))],instructionTypes:[iw.CpmmAddLiquidity],lookupTableAddress:W.lookupTableAccount?[W.lookupTableAccount]:[]}),M.addCustomComputeBudget(v),M.versionBuild({txVersion:k})}async withdrawLiquidity(e){var t,n,r,i,o,a,s,u,l,c,d;let p,f,h;let{poolInfo:m,poolKeys:g,lpAmount:y,slippage:b,computeBudgetConfig:_,txVersion:v}=e;!1===this.scope.availability.addStandardPosition&&this.logAndCreateError("add liquidity feature disabled in your region");let w=new is(new(tb())(1)).sub(b),k=await this.getRpcPoolInfo(m.id),[x,A]=[w.mul(y.mul(k.baseReserve).div(k.lpAmount)).quotient,w.mul(y.mul(k.quoteReserve).div(k.lpAmount)).quotient],S=await this.scope.fetchEpochInfo(),[I,T]=[i7(x,m.mintA.extensions.feeConfig,S,!1),i7(A,m.mintB.extensions.feeConfig,S,!1)],{account:E}=this.scope,P=this.createTxBuilder(),[C,O]=[new tu.nh(m.mintA.address),new tu.nh(m.mintB.address)],B=C.equals(r7),M=O.equals(r7),{account:R,instructionParams:L}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:m.mintA.programId,mint:new tu.nh(m.mintA.address),notUseTokenAccount:B,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!B,associatedOnly:!B,checkCreateATAOwner:!1});L&&P.addInstruction(L);let{account:N,instructionParams:D}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:m.mintB.programId,mint:new tu.nh(m.mintB.address),notUseTokenAccount:M,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!M,associatedOnly:!M,checkCreateATAOwner:!1});D&&P.addInstruction(D),R&&N||this.logAndCreateError("cannot found target token accounts","tokenAccounts",E.tokenAccounts);let F=await E.getCreatedTokenAccount({mint:new tu.nh(m.lpMint.address)});F||this.logAndCreateError("cannot found lp token account","tokenAccounts",E.tokenAccounts);let q=null!=g?g:await this.getCpmmPoolKeys(m.id);return P.addInstruction({instructions:[(r=new tu.nh(m.programId),i=this.scope.ownerPubKey,o=new tu.nh(q.authority),a=new tu.nh(m.id),s=new tu.nh(q.vault.A),u=new tu.nh(q.vault.B),l=new tu.nh(m.lpMint.address),c=x.sub(null!=(t=I.fee)?t:new(tb())(0)),d=A.sub(null!=(n=T.fee)?n:new(tb())(0)),p=o2([oH("lpAmount"),oH("amountMinA"),oH("amountMinB")]),f=[{pubkey:i,isSigner:!0,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:F,isSigner:!1,isWritable:!0},{pubkey:R,isSigner:!1,isWritable:!0},{pubkey:N,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:td.H_,isSigner:!1,isWritable:!1},{pubkey:td.nA,isSigner:!1,isWritable:!1},{pubkey:C,isSigner:!1,isWritable:!1},{pubkey:O,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:r1,isSigner:!1,isWritable:!1}],h=tK.alloc(p.span),p.encode({lpAmount:y,amountMinA:c,amountMinB:d},h),new tu.Sl({keys:f,programId:r,data:tK.from([...uU.withdraw,...h])}))],instructionTypes:[iw.CpmmWithdrawLiquidity],lookupTableAddress:q.lookupTableAccount?[q.lookupTableAccount]:[]}),P.addCustomComputeBudget(_),P.versionBuild({txVersion:v})}async swap(e){var t,n,r,i,o,a,s,u,l,c,d,p,f,h,m,g,y,b;let _,v;let{poolInfo:w,poolKeys:k,baseIn:x,fixedOut:A,inputAmount:S,swapResult:I,slippage:T=0,config:E,computeBudgetConfig:P,txVersion:C}=e,{bypassAssociatedCheck:O,checkCreateATAOwner:B,associatedOnly:M}=t0({bypassAssociatedCheck:!1,checkCreateATAOwner:!1,associatedOnly:!0},E),R=this.createTxBuilder(),[L,N]=[new tu.nh(w.mintA.address),new tu.nh(w.mintB.address)];A?I.sourceAmountSwapped=I.sourceAmountSwapped.mul(new(tb())((1+T)*1e4)).div(new(tb())(1e4)):I.destinationAmountSwapped=I.destinationAmountSwapped.mul(new(tb())((1-T)*1e4)).div(new(tb())(1e4));let D=w.mintA.address===r7.toBase58(),F=w.mintB.address===r7.toBase58(),{account:q,instructionParams:j}=await this.scope.account.getOrCreateTokenAccount({mint:L,tokenProgram:new tu.nh(null!=(t=w.mintA.programId)?t:td.H_),owner:this.scope.ownerPubKey,createInfo:D||!x?{payer:this.scope.ownerPubKey,amount:x?I.sourceAmountSwapped:0}:void 0,notUseTokenAccount:D,skipCloseAccount:!D,associatedOnly:!D&&M,checkCreateATAOwner:B});j&&R.addInstruction(j);let{account:U,instructionParams:z}=await this.scope.account.getOrCreateTokenAccount({mint:N,tokenProgram:new tu.nh(null!=(n=w.mintB.programId)?n:td.H_),owner:this.scope.ownerPubKey,createInfo:F||x?{payer:this.scope.ownerPubKey,amount:x?0:I.sourceAmountSwapped}:void 0,notUseTokenAccount:F,skipCloseAccount:!F,associatedOnly:!F&&M,checkCreateATAOwner:B});z&&R.addInstruction(z),q&&U||this.logAndCreateError("user do not have token account",{mintA:w.mintA.symbol||w.mintA.address,mintB:w.mintB.symbol||w.mintB.address,mintATokenAcc:q,mintBTokenAcc:U,mintAUseSOLBalance:D,mintBUseSOLBalance:F,associatedOnly:M});let V=null!=k?k:await this.getCpmmPoolKeys(w.id);return R.addInstruction({instructions:[A?(s=new tu.nh(w.programId),u=this.scope.ownerPubKey,l=new tu.nh(V.authority),c=new tu.nh(V.config.id),d=new tu.nh(w.id),p=new tu.nh(V.vault[x?"A":"B"]),f=new tu.nh(V.vault[x?"B":"A"]),h=new tu.nh(null!=(o=w[x?"mintA":"mintB"].programId)?o:td.H_),m=new tu.nh(null!=(a=w[x?"mintB":"mintA"].programId)?a:td.H_),g=uD(new tu.nh(w.programId),new tu.nh(w.id)).publicKey,y=I.sourceAmountSwapped,b=I.destinationAmountSwapped,_=o2([oH("amountInMax"),oH("amountOut")]),v=tK.alloc(_.span),_.encode({amountInMax:y,amountOut:b},v),new tu.Sl({keys:[{pubkey:u,isSigner:!0,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:x?q:U,isSigner:!1,isWritable:!0},{pubkey:x?U:q,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:h,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:x?L:N,isSigner:!1,isWritable:!1},{pubkey:x?N:L,isSigner:!1,isWritable:!1},{pubkey:g,isSigner:!1,isWritable:!0}],programId:s,data:tK.from([...uU.swapBaseOutput,...v])})):uz(new tu.nh(w.programId),this.scope.ownerPubKey,new tu.nh(V.authority),new tu.nh(V.config.id),new tu.nh(w.id),x?q:U,x?U:q,new tu.nh(V.vault[x?"A":"B"]),new tu.nh(V.vault[x?"B":"A"]),new tu.nh(null!=(r=w[x?"mintA":"mintB"].programId)?r:td.H_),new tu.nh(null!=(i=w[x?"mintB":"mintA"].programId)?i:td.H_),x?L:N,x?N:L,uD(new tu.nh(w.programId),new tu.nh(w.id)).publicKey,S,I.destinationAmountSwapped)],instructionTypes:[A?iw.CpmmSwapBaseOut:iw.ClmmSwapBaseIn]}),R.addCustomComputeBudget(P),R.versionBuild({txVersion:C})}async lockLp(e){var t,n,r,i,o;let{poolInfo:a,lpAmount:s,computeBudgetConfig:u,txVersion:l}=e;s.isZero()&&this.logAndCreateError("lpAmount must greater than zero",{lpAmount:s.toString()});let c=this.createTxBuilder(),d=null!=(t=e.poolKeys)?t:await this.getCpmmPoolKeys(a.id),p=await uV({poolInfo:a,poolKeys:d,ownerInfo:{wallet:this.scope.ownerPubKey,feePayer:null!=(n=e.feePayer)?n:this.scope.ownerPubKey},lockProgram:null!=(r=e.programId)?r:i4,lockAuthProgram:null!=(i=e.authProgram)?i:i5,lpAmount:s,withMetadata:null==(o=e.withMetadata)||o,getEphemeralSigners:e.getEphemeralSigners});return c.addInstruction(p),c.addCustomComputeBudget(u),c.versionBuild({txVersion:l,extInfo:p.address})}async harvestLockLp(e){var t;let{poolInfo:n,lpFeeAmount:r,nftMint:i,programId:o=i4,authProgram:a=i5,cpmmProgram:s,computeBudgetConfig:u,txVersion:l}=e;r.isZero()&&this.logAndCreateError("lpFeeAmount must greater than zero",{lpAmount:r.toString()});let c=e.feePayer||this.scope.ownerPubKey,d=this.createTxBuilder(),[p,f]=[new tu.nh(n.mintA.address),new tu.nh(n.mintB.address)],h=p.equals(r7),m=f.equals(r7),{account:g,instructionParams:y}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n.mintA.programId,mint:new tu.nh(n.mintA.address),notUseTokenAccount:h,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!h,associatedOnly:!h,checkCreateATAOwner:!1});y&&d.addInstruction(y);let{account:b,instructionParams:_}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n.mintB.programId,mint:new tu.nh(n.mintB.address),notUseTokenAccount:m,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!m,associatedOnly:!m,checkCreateATAOwner:!1});_&&d.addInstruction(_),g&&b||this.logAndCreateError("cannot found target token accounts",{tokenAccountA:g,tokenAccountB:b});let v=null!=(t=e.poolKeys)?t:await this.getCpmmPoolKeys(n.id),{publicKey:w}=iN(c,i,td.H_),{publicKey:k}=uq(o,i),{publicKey:x}=iN(a,new tu.nh(n.lpMint.address),td.H_);return d.addInstruction({instructions:[function({programId:e,nftOwner:t,auth:n,nftAccount:r,lockPda:i,poolId:o,mintLp:a,userVaultA:s,userVaultB:u,poolVaultA:l,poolVaultB:c,mintA:d,mintB:p,lockLpVault:f,lpFeeAmount:h,cpmmProgram:m,cpmmAuthProgram:g}){let y=[{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:null!=m?m:i2,isSigner:!1,isWritable:!1},{pubkey:null!=g?g:i6,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:td.H_,isSigner:!1,isWritable:!1},{pubkey:td.nA,isSigner:!1,isWritable:!1},{pubkey:r1,isSigner:!1,isWritable:!1}],b=o2([oH("lpFeeAmount")]),_=tK.alloc(b.span);b.encode({lpFeeAmount:h},_);let v=tK.from([...uU.collectCpFee,..._]);return new tu.Sl({keys:y,programId:e,data:v})}({programId:null!=o?o:i4,nftOwner:this.scope.ownerPubKey,auth:null!=a?a:i5,nftMint:i,nftAccount:w,lockPda:k,poolId:new tu.nh(n.id),mintLp:new tu.nh(v.mintLp.address),userVaultA:g,userVaultB:b,poolVaultA:new tu.nh(v.vault.A),poolVaultB:new tu.nh(v.vault.B),mintA:p,mintB:f,lockLpVault:x,lpFeeAmount:r,cpmmProgram:null==s?void 0:s.programId,cpmmAuthProgram:null==s?void 0:s.authProgram})],instructionTypes:[iw.CpmmCollectLockFee]}),d.addCustomComputeBudget(u),d.versionBuild({txVersion:l})}computeSwapAmount({pool:e,amountIn:t,outputMint:n,slippage:r}){let i=n.toString()===e.mintB.address,o=uI.swap(t,i?e.baseReserve:e.quoteReserve,i?e.quoteReserve:e.baseReserve,e.configInfo.tradeFeeRate),a=new rM(o.destinationAmountSwapped.toString()).div(o.sourceAmountSwapped.toString()),s=o.destinationAmountSwapped.mul(new(tb())((1-r)*1e4)).div(new(tb())(1e4));return{allTrade:o.sourceAmountSwapped.eq(t),amountIn:t,amountOut:o.destinationAmountSwapped,minAmountOut:s,executionPrice:a,fee:o.tradeFee,priceImpact:e.poolPrice.sub(a).div(e.poolPrice)}}computePairAmount({poolInfo:e,baseReserve:t,quoteReserve:n,amount:r,slippage:i,epochInfo:o,baseIn:a}){var s,u,l,c,d,p,f,h,m;let g=1-Number(i.toSignificant())/100,y=new(tb())(new rM(r).mul(10**e[a?"mintA":"mintB"].decimals).mul(g).toFixed(0)),b=i7(y,e[a?"mintA":"mintB"].extensions.feeConfig,o,!1),_=y.sub(null!=(s=b.fee)?s:new(tb())(0)),v=new(tb())(new rM(e.lpAmount).mul(10**e.lpMint.decimals).toFixed(0,rM.ROUND_DOWN));this.logDebug("baseReserve:",t.toString(),"quoteReserve:",n.toString()),this.logDebug("tokenIn:",a?e.mintA.symbol:e.mintB.symbol,"amountIn:",y.toString(),"amountInFee:",null!=(l=null==(u=b.fee)?void 0:u.toString())?l:0,"anotherToken:",a?e.mintB.symbol:e.mintA.symbol,"slippage:",`${i.toSignificant()}%`);let w=a?"base":"quote";this.logDebug("input side:",w);let k=_.mul(v).div("base"===w?t:n),x={amount:ih,fee:void 0,expirationTime:void 0};if(!_.isZero()){let r,i;let s=((r=k.mul(t).div(v)).isZero()||k.mul(t).mod(v).isZero()||(r=r.add(new(tb())(1))),(i=k.mul(n).div(v)).isZero()||k.mul(n).mod(v).isZero()||(i=i.add(new(tb())(1))),{amountA:r,amountB:i});this.logDebug("lpAmountData:",{amountA:s.amountA.toString(),amountB:s.amountB.toString()}),x=i7(s[a?"amountB":"amountA"],e[a?"mintB":"mintA"].extensions.feeConfig,o,!0)}let A=new is(new(tb())(1)).add(i),S=new is(new(tb())(1)).sub(i),I=i7(A.mul(x.amount.sub(null!=(c=x.fee)?c:new(tb())(0))).quotient,e[a?"mintB":"mintA"].extensions.feeConfig,o,!0),T=i7(S.mul(x.amount.sub(null!=(d=x.fee)?d:new(tb())(0))).quotient,e[a?"mintB":"mintA"].extensions.feeConfig,o,!0);return this.logDebug("anotherAmount:",x.amount.toString(),"anotherAmountFee:",null!=(f=null==(p=x.fee)?void 0:p.toString())?f:0,"maxAnotherAmount:",I.amount.toString(),"maxAnotherAmountFee:",null!=(m=null==(h=I.fee)?void 0:h.toString())?m:0),{inputAmountFee:b,anotherAmount:x,maxAnotherAmount:I,minAnotherAmount:T,liquidity:k}}},uH={[iV.toBase58()]:3},uG={3:iV},uZ=o2([oU(5),oU(8),oX("ownAddress"),oH("vaultSignerNonce"),oX("baseMint"),oX("quoteMint"),oX("baseVault"),oH("baseDepositsTotal"),oH("baseFeesAccrued"),oX("quoteVault"),oH("quoteDepositsTotal"),oH("quoteFeesAccrued"),oH("quoteDustThreshold"),oX("requestQueue"),oX("eventQueue"),oX("bids"),oX("asks"),oH("baseLotSize"),oH("quoteLotSize"),oH("feeRateBps"),oH("referrerRebatesAccrued"),oU(7)]),uY={3:uZ},uX=t8("Serum"),uQ=class{static getProgramId(e){let t=uG[e];return t||uX.logWithError("invalid version","version",e),t}static getVersion(e){let t=e.toBase58(),n=uH[t];return n||uX.logWithError("invalid program id","programId",t),n}static getStateLayout(e){let t=uY[e];return t||uX.logWithError(!!t,"invalid version","version",e),t}static getLayouts(e){return{state:this.getStateLayout(e)}}static getAssociatedAuthority({programId:e,marketId:t}){let n=[t.toBuffer()],r=0,i;for(;r<100;){try{let t=n.concat(tK.from([r]),tK.alloc(7));i=tu.nh.createProgramAddressSync(t,e)}catch(e){if(e instanceof TypeError)throw e;r++;continue}return{publicKey:i,nonce:r}}return uX.logWithError("unable to find a viable program address nonce","params",{programId:e,marketId:t}),{publicKey:tu.nh.default,nonce:r}}},uJ=new(tb())(0),u0=class extends oy{constructor(e){super(e)}async getWSolAccounts(){this.scope.checkOwner(),await this.scope.account.fetchWalletTokenAccounts();let e=this.scope.account.tokenAccounts.filter(e=>e.mint.equals(r7));return e.sort((e,t)=>e.isAssociated?1:t.isAssociated||e.amount.lt(t.amount)?-1:1),e}async unWrapWSol(e){let{amount:t,tokenProgram:n,txVersion:r=1}=e,i=await this.getWSolAccounts(),o=this.createTxBuilder();o.addCustomComputeBudget(e.computeBudgetConfig);let a=await o9({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:this.scope.ownerPubKey,amount:0});o.addInstruction(a);let s=rN(t);for(let e=0;evoid 0!==e),address:{}}}throw Error("route type error")}({routeProgram:i,inputMint:f,swapInfo:t1(t0({},e),{poolInfo:[...e.poolInfoList],poolKey:y,outputMint:h}),ownerInfo:{wallet:this.scope.ownerPubKey,sourceToken:m,routeToken:s,destinationToken:a}});if(void 0!==e.feeConfig){let t=this.createTxBuilder();t.addInstruction({instructions:[t$(m,e.feeConfig.feeAccount,this.scope.ownerPubKey,e.feeConfig.feeAmount.toNumber())],instructionTypes:[iw.TransferAmount]}),t.addInstruction(b);let{transactions:n}=0===o?await t.sizeCheckBuildV0():await t.sizeCheckBuild();n.length<2&&u.addInstruction({instructions:[t$(m,e.feeConfig.feeAccount,this.scope.ownerPubKey,e.feeConfig.feeAmount.toNumber())],instructionTypes:[iw.TransferAmount]})}return u.addInstruction(b),0===o?u.sizeCheckBuildV0({computeBudgetConfig:r,address:b.address}):u.sizeCheckBuild({computeBudgetConfig:r,address:b.address})}async fetchRoutePoolBasicInfo(e){let{amm:t=iW,clmm:n=iH,cpmm:r=i2}=e||{},i=await this.scope.connection.getProgramAccounts(t,{dataSlice:{offset:s1.offsetOf("baseMint"),length:64}}),o=o2([oX("baseMint"),oX("quoteMint")]),a=i.map(e=>({id:e.pubkey,version:4,mintA:o.decode(e.account.data).baseMint,mintB:o.decode(e.account.data).quoteMint})),s=o2([oX("mintA"),oX("mintB")]);return{clmmPools:(await this.scope.connection.getProgramAccounts(n,{filters:[{dataSize:sB.span}],dataSlice:{offset:sB.offsetOf("mintA"),length:64}})).map(e=>{let t=s.decode(e.account.data);return{id:e.pubkey,version:6,mintA:t.mintA,mintB:t.mintB}}),ammPools:a,cpmmPools:(await this.scope.connection.getProgramAccounts(r,{dataSlice:{offset:u$.offsetOf("mintA"),length:64}})).map(e=>{let t=s.decode(e.account.data);return{id:e.pubkey,version:7,mintA:t.mintA,mintB:t.mintB}})}}getAllRoute({inputMint:e,outputMint:t,clmmPools:n,ammPools:r,cpmmPools:i}){e=e.toString()===tu.nh.default.toString()?r7:e,t=t.toString()===tu.nh.default.toString()?r7:t;let o={},a={},s={},u=[],l={};for(let r of null!=n?n:[]){if((r.mintA.equals(e)&&r.mintB.equals(t)||r.mintA.equals(t)&&r.mintB.equals(e))&&(u.push(r),a[r.id.toString()]=r),r.mintA.equals(e)){let e=r.mintB.toString();void 0===l[e]&&(l[e]={mintProgram:td.H_,in:[],out:[],mDecimals:0}),l[e].in.push(r)}if(r.mintB.equals(e)){let e=r.mintA.toString();void 0===l[e]&&(l[e]={mintProgram:td.H_,in:[],out:[],mDecimals:0}),l[e].in.push(r)}if(r.mintA.equals(t)){let e=r.mintB.toString();void 0===l[e]&&(l[e]={mintProgram:td.H_,in:[],out:[],mDecimals:0}),l[e].out.push(r)}if(r.mintB.equals(t)){let e=r.mintA.toString();void 0===l[e]&&(l[e]={mintProgram:td.H_,in:[],out:[],mDecimals:0}),l[e].out.push(r)}}let c=[];for(let n of r)(n.mintA.equals(e)&&n.mintB.equals(t)||n.mintA.equals(t)&&n.mintB.equals(e))&&(u.push(n),o[n.id.toBase58()]=n,c.push(n)),n.mintA.equals(e)&&(void 0===l[n.mintB.toBase58()]&&(l[n.mintB.toBase58()]={mintProgram:td.H_,in:[],out:[],mDecimals:0}),l[n.mintB.toBase58()].in.push(n)),n.mintB.equals(e)&&(void 0===l[n.mintA.toBase58()]&&(l[n.mintA.toBase58()]={mintProgram:td.H_,in:[],out:[],mDecimals:0}),l[n.mintA.toBase58()].in.push(n)),n.mintA.equals(t)&&(void 0===l[n.mintB.toBase58()]&&(l[n.mintB.toBase58()]={mintProgram:td.H_,in:[],out:[],mDecimals:0}),l[n.mintB.toBase58()].out.push(n)),n.mintB.equals(t)&&(void 0===l[n.mintA.toBase58()]&&(l[n.mintA.toBase58()]={mintProgram:td.H_,in:[],out:[],mDecimals:0}),l[n.mintA.toBase58()].out.push(n));for(let n of i)(n.mintA.equals(e)&&n.mintB.equals(t)||n.mintA.equals(t)&&n.mintB.equals(e))&&(u.push(n),s[n.id.toBase58()]=n),n.mintA.equals(e)&&(void 0===l[n.mintB.toBase58()]&&(l[n.mintB.toBase58()]={mintProgram:td.H_,in:[],out:[],mDecimals:0}),l[n.mintB.toBase58()].in.push(n)),n.mintB.equals(e)&&(void 0===l[n.mintA.toBase58()]&&(l[n.mintA.toBase58()]={mintProgram:td.H_,in:[],out:[],mDecimals:0}),l[n.mintA.toBase58()].in.push(n)),n.mintA.equals(t)&&(void 0===l[n.mintB.toBase58()]&&(l[n.mintB.toBase58()]={mintProgram:td.H_,in:[],out:[],mDecimals:0}),l[n.mintB.toBase58()].out.push(n)),n.mintB.equals(t)&&(void 0===l[n.mintA.toBase58()]&&(l[n.mintA.toBase58()]={mintProgram:td.H_,in:[],out:[],mDecimals:0}),l[n.mintA.toBase58()].out.push(n));for(let e of Object.keys(l)){if(1===l[e].in.length&&1===l[e].out.length&&l[e].in[0].id.equals(l[e].out[0].id)||0===l[e].in.length||0===l[e].out.length){delete l[e];continue}let t=l[e];for(let e of t.in)for(let n of t.out)6===e.version&&void 0===a[e.id.toString()]?a[e.id.toString()]=e:7===e.version&&void 0===s[e.id.toString()]?s[e.id.toString()]=e:(4===e.version||5===e.version)&&void 0===o[e.id.toString()]&&(o[e.id.toString()]=e),6===n.version&&void 0===a[n.id.toString()]?a[n.id.toString()]=n:7===n.version&&void 0===s[n.id.toString()]?s[n.id.toString()]=n:(4===n.version||5===n.version)&&void 0===o[n.id.toString()]&&(o[n.id.toString()]=n)}return{directPath:u,addLiquidityPools:c,routePathDict:l,needSimulate:Object.values(o),needTickArray:Object.values(a),cpmmPoolList:Object.values(s)}}async fetchSwapRoutesData({routes:e,inputMint:t,outputMint:n}){let r=new Set([...e.needTickArray.map(e=>[e.mintA.toBase58(),e.mintB.toBase58()]).flat(),t.toString(),n.toString()]);console.log("fetching amm pools info, total: ",e.needSimulate.length);let i=await this.scope.liquidity.getRpcPoolInfos(e.needSimulate.map(e=>e.id)),o=uh(i),a={};Object.values(o).forEach(e=>{r.delete(e.mintA.address),a[e.mintA.address]={address:new tu.nh(e.mintA.address),programId:td.H_,mintAuthority:null,supply:BigInt(0),decimals:e.mintA.decimals,isInitialized:!0,freezeAuthority:null,tlvData:tK.from("0","hex"),feeConfig:void 0},r.delete(e.mintB.address),a[e.mintB.address]={address:new tu.nh(e.mintB.address),programId:td.H_,mintAuthority:null,supply:BigInt(0),decimals:e.mintB.decimals,isInitialized:!0,freezeAuthority:null,tlvData:tK.from("0","hex"),feeConfig:void 0}}),console.log("fetching cpmm pools info, total: ",e.cpmmPoolList.length);let s=await this.scope.cpmm.getRpcPoolInfos(e.cpmmPoolList.map(e=>e.id.toBase58()),!0);Object.values(s).forEach(e=>{let[t,n]=[e.mintA.toBase58(),e.mintB.toBase58()];e.mintProgramA.equals(td.H_)?(r.delete(t),a[t]={address:e.mintA,programId:e.mintProgramA,mintAuthority:null,supply:BigInt(0),decimals:e.mintDecimalA,isInitialized:!0,freezeAuthority:null,tlvData:tK.from("0","hex"),feeConfig:void 0}):r.add(t),e.mintProgramB.equals(td.H_)?(r.delete(n),a[n]={address:e.mintB,programId:e.mintProgramB,mintAuthority:null,supply:BigInt(0),decimals:e.mintDecimalB,isInitialized:!0,freezeAuthority:null,tlvData:tK.from("0","hex"),feeConfig:void 0}):r.add(n)}),console.log("fetching mints info, total: ",r.size);let u=await nn({connection:this.scope.connection,mints:Array.from(r).map(e=>new tu.nh(e))});a=t0(t0({},a),u);let l=this.scope.cpmm.toComputePoolInfos({pools:s,mintInfos:a});console.log("fetching clmm pools info, total:",e.needTickArray.length);let c=await this.scope.clmm.getRpcClmmPoolInfos({poolIds:e.needTickArray.map(e=>e.id)}),{computeClmmPoolInfo:d,computePoolTickData:p}=await this.scope.clmm.getComputeClmmPoolInfos({clmmPoolsRpcInfo:c,mintInfos:a}),f=Object.keys(e.routePathDict).reduce((t,n)=>t1(t0({},t),{[n]:t1(t0({},e.routePathDict[n]),{mintProgram:a[n].programId,mDecimals:a[n].decimals,in:e.routePathDict[n].in.map(e=>o[e.id.toBase58()]||d[e.id.toBase58()]||l[e.id.toBase58()]),out:e.routePathDict[n].out.map(e=>o[e.id.toBase58()]||d[e.id.toBase58()]||l[e.id.toBase58()])})}),{});return{mintInfos:a,ammPoolsRpcInfo:i,ammSimulateCache:o,clmmPoolsRpcInfo:c,computeClmmPoolInfo:d,computePoolTickData:p,computeCpmmData:l,routePathDict:f}}getAllRouteComputeAmountOut({inputTokenAmount:e,outputToken:t,directPath:n,routePathDict:r,simulateCache:i,tickCache:o,slippage:a,chainTime:s,epochInfo:u,feeConfig:l}){var c,d,p,f,h,m,g,y,b;let _=void 0===l?new(tb())(0):e.raw.mul(new(tb())(l.feeBps.toNumber())).div(new(tb())(1e4)),v=e.raw.sub(_),w=new rK(e.token,v),k=void 0===l?void 0:{feeAmount:_,feeAccount:l.feeAccount},x=t1(t0({},t),{address:it(t.address).toString()}),A=[];for(let e of n)try{A.push(t1(t0({},this.computeAmountOut({itemPool:e,tickCache:o,simulateCache:i,chainTime:s,epochInfo:u,slippage:a,outputToken:x,amountIn:w})),{feeConfig:k}))}catch(t){this.logDebug("direct error",e.version,e.id.toString(),t.message)}for(let[e,t]of(this.logDebug("direct done"),Object.entries(r))){let n={chainId:101,address:e,programId:t.mintProgram.toBase58(),logoURI:"",symbol:"",name:"",decimals:t.mDecimals,tags:[],extensions:{}},r=t.in.map(e=>{try{return{pool:e,data:this.computeAmountOut({itemPool:e,tickCache:o,simulateCache:i,chainTime:s,epochInfo:u,slippage:a,outputToken:n,amountIn:w})}}catch(t){this.logDebug("route in error",e.version,e.id.toString(),t.message);return}}).sort((e,t)=>{var n,r,i,o;let a=void 0===e?uJ:e.data.amountOut.amount.raw.sub(null!=(r=null==(n=e.data.amountOut.fee)?void 0:n.raw)?r:uJ),s=void 0===t?uJ:t.data.amountOut.amount.raw.sub(null!=(o=null==(i=t.data.amountOut.fee)?void 0:i.raw)?o:uJ);return a.lt(s)?1:-1})[0];if(void 0===r)continue;let l=new rK(s$(n),r.data.amountOut.amount.raw.sub(null!=(d=null==(c=r.data.amountOut.fee)?void 0:c.raw)?d:uJ));for(let e of t.out)try{let t=this.computeAmountOut({itemPool:e,tickCache:o,simulateCache:i,chainTime:s,epochInfo:u,slippage:a,outputToken:x,amountIn:l});A.push(t1(t0({},t),{allTrade:!!(r.data.allTrade&&t.allTrade),amountIn:r.data.amountIn,amountOut:t.amountOut,minAmountOut:t.minAmountOut,currentPrice:void 0,executionPrice:new rM(new il({baseToken:r.data.amountIn.amount.token,denominator:r.data.amountIn.amount.raw,quoteToken:t.amountOut.amount.token,numerator:t.amountOut.amount.raw.sub(null!=(f=null==(p=t.amountOut.fee)?void 0:p.raw)?f:uJ)}).toFixed()),priceImpact:new rM(r.data.priceImpact.add(t.priceImpact).toFixed()),fee:[r.data.fee[0],t.fee[0]],routeType:"route",poolInfoList:[r.pool,e],remainingAccounts:[r.data.remainingAccounts[0],t.remainingAccounts[0]],minMiddleAmountFee:null!=(h=t.amountOut.fee)&&h.raw?new rK(r.data.amountOut.amount.token,(null!=(g=null==(m=r.data.amountOut.fee)?void 0:m.raw)?g:uJ).add(null!=(b=null==(y=t.amountOut.fee)?void 0:y.raw)?b:uJ)):void 0,middleToken:r.data.amountOut.amount.token,poolReady:r.data.poolReady&&t.poolReady,poolType:[r.data.poolType,t.poolType],feeConfig:k,expirationTime:oe(r.data.expirationTime,t.expirationTime)}))}catch(t){this.logDebug("route out error",e.version,e.id.toString(),t.message)}}return A.filter(e=>(e.allTrade||this.logDebug(`pool ${e.poolInfoList.map(e=>e.id.toString()).join(",")} filter out since not all trade`),e.allTrade)).sort((e,t)=>e.amountOut.amount.raw.sub(t.amountOut.amount.raw).gt(uJ)?-1:1)}computeAmountOut({itemPool:e,tickCache:t,simulateCache:n,chainTime:r,epochInfo:i,slippage:o,outputToken:a,amountIn:s}){if(6===e.version){let{allTrade:n,realAmountIn:u,amountOut:l,minAmountOut:c,expirationTime:d,currentPrice:p,executionPrice:f,priceImpact:h,fee:m,remainingAccounts:g,executionPriceX64:y}=sg.computeAmountOutFormat({poolInfo:e,tickArrayCache:t[e.id.toString()],amountIn:s.raw,tokenOut:a,slippage:o,epochInfo:i,catchLiquidityInsufficient:!0});return{allTrade:n,amountIn:u,amountOut:l,minAmountOut:c,currentPrice:new rM(p.toFixed()),executionPrice:new rM(f.toFixed()),priceImpact:new rM(h.toFixed()),fee:[m],remainingAccounts:[g],routeType:"amm",poolInfoList:[e],poolReady:e.startTime6===e.version&&!t[e.id.toString()]).map(e=>e.id.toString()));if(r.size>0){let e=await this.scope.clmm.getRpcClmmPoolInfos({poolIds:Array.from(r)});Object.keys(e).forEach(n=>{t[n]=e[n]})}if(new Set(e.filter(e=>4===e.version&&!n[e.id.toString()]).map(e=>e.id.toString())).size>0){let e=await this.scope.liquidity.getRpcPoolInfos(Array.from(r));Object.keys(e).forEach(t=>{n[t]=e[t]})}let i=new Set(e.filter(e=>4===e.version).map(e=>e.marketId)),o={};i.size>0&&(await ne(this.scope.connection,Array.from(i).map(e=>({pubkey:new tu.nh(e)})))).forEach(e=>{if(!e.accountInfo)return;let t=uZ.decode(e.accountInfo.data);o[e.pubkey.toBase58()]={marketId:e.pubkey.toString(),marketProgramId:e.accountInfo.owner.toString(),marketAuthority:uQ.getAssociatedAuthority({programId:e.accountInfo.owner,marketId:e.pubkey}).publicKey.toString(),marketBaseVault:t.baseVault.toString(),marketQuoteVault:t.quoteVault.toString(),marketBids:t.bids.toString(),marketAsks:t.asks.toString(),marketEventQueue:t.eventQueue.toString()}});let a=[];return e.forEach(e=>{if(6===e.version){let n=t[e.id.toString()],r={programId:e.programId.toBase58(),id:e.id.toBase58(),mintA:e.mintA,mintB:e.mintB,openTime:String(e.startTime),vault:{A:n.vaultA.toBase58(),B:n.vaultB.toBase58()},config:t1(t0({},e.ammConfig),{id:e.ammConfig.id.toString(),defaultRange:0,defaultRangePoint:[]}),rewardInfos:[],observationId:e.observationId.toBase58(),exBitmapAccount:e.exBitmapAccount.toBase58()};a.push(r)}else if(4===e.version){let t=n[e.id.toString()],r=t0({programId:e.programId,id:e.id,mintA:e.mintA,mintB:e.mintB,openTime:String(e.openTime),vault:{A:t.baseVault.toBase58(),B:t.quoteVault.toBase58()},authority:uc({programId:new tu.nh(e.programId)}).publicKey.toString(),openOrders:t.openOrders.toBase58(),targetOrders:t.targetOrders.toBase58(),mintLp:e.lpMint},o[e.marketId]);a.push(r)}else 7===e.version&&a.push({observationId:e.observationId.toBase58(),programId:e.programId.toBase58(),id:e.id.toBase58(),mintA:e.mintA,mintB:e.mintB,openTime:String(e.openTime),authority:uM(e.programId).publicKey.toBase58(),vault:{A:e.vaultA.toBase58(),B:e.vaultB.toBase58()},mintLp:sZ({address:e.mintLp.toBase58(),programId:td.H_.toBase58(),decimals:e.lpDecimals}),config:t1(t0({id:e.configId.toBase58()},e.configInfo),{protocolFeeRate:e.configInfo.protocolFeeRate.toNumber(),tradeFeeRate:e.configInfo.tradeFeeRate.toNumber(),fundFeeRate:e.configInfo.fundFeeRate.toNumber(),createPoolFee:e.configInfo.createPoolFee.toString()})})}),a}},u1=class extends oy{static getPdaPoolId(e,t){return iP([u1.SEED_CONFIG.pool.id,t.toBuffer()],e)}static getPdaOwnerId(e,t,n,r){return iP([u1.SEED_CONFIG.owner.id,t.toBuffer(),n.toBuffer(),tK.from(new(tb())(r).toArray())],e)}static async getAllInfo({connection:e,programId:t,poolIds:n,wallet:r,chainTime:i}){if(0===n.length)return[];let o=n.map(e=>u1.getPdaPoolId(t,e).publicKey),a=[];for(let e=0;eu1.getPdaOwnerId(t,n,r,e).publicKey));let s=await t7(e,[...o,...a]),u=[];for(let e=0;ee.debtAmount.gt(new(tb())(0))).filter(e=>!e).length,_=i>g&&i({mintAddress:e.mintAddress,mintVault:e.mintVault,mintDecimals:e.mintDecimals,perLpLoss:e.perLpLoss,debtAmount:m.tokenInfo[t].debtAmount.add(m.tokenInfo[t].claimedAmount)}))})}return u}async makeClaimTransaction({poolInfo:e,ownerInfo:t}){t.wallet||this.scope.checkOwner();let n=this.createTxBuilder(),r=t.wallet||this.scope.ownerPubKey,i=[];for(let o of e.tokenInfo){let{account:e,instructionParams:a}=await this.scope.account.getOrCreateTokenAccount({mint:o.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:o.mintAddress.equals(ii.WSOL.mint),createInfo:{payer:r,amount:0},skipCloseAccount:!o.mintAddress.equals(ii.WSOL.mint),associatedOnly:!o.mintAddress.equals(ii.WSOL.mint)&&t.associatedOnly});a&&n.addInstruction(a),i.push(e)}n.addInstruction({instructions:[u1.makeClaimInstruction({programId:e.programId,poolInfo:e,ownerInfo:{wallet:r,ownerPda:e.ownerAccountId,claimAddress:i}})]});let{transaction:o,signers:a}=n.build();return[{transaction:o,signer:a}]}async makeClaimAllTransaction({poolInfos:e,ownerInfo:t}){let n=this.createTxBuilder(),r=t.wallet||this.scope.ownerPubKey,i={};for(let o of e){let e=[];for(let a of o.tokenInfo){let{account:o,instructionParams:s}=await this.scope.account.getOrCreateTokenAccount({mint:a.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:a.mintAddress.equals(ii.WSOL.mint),createInfo:{payer:r,amount:0},skipCloseAccount:!a.mintAddress.equals(ii.WSOL.mint),associatedOnly:!a.mintAddress.equals(ii.WSOL.mint)&&t.associatedOnly});s&&n.addInstruction(s),o&&(i[a.mintAddress.toString()]=o,e.push(o))}n.addInstruction({instructions:[u1.makeClaimInstruction({programId:o.programId,poolInfo:o,ownerInfo:{wallet:r,ownerPda:o.ownerAccountId,claimAddress:e}})]})}let{transaction:o,signers:a}=n.build(),s=n.allInstructions;return iI(s,[r,...a.map(e=>e.publicKey)])?[{transaction:o,signer:a}]:[{transaction:new tu.YW().add(...s.slice(0,n.AllTxData.instructions.length-1)),signer:a},{transaction:new tu.YW().add(...s.slice(n.AllTxData.instructions.length-1)),signer:[]},{transaction:new tu.YW().add(...n.AllTxData.endInstructions),signer:[]}]}static makeClaimInstruction({programId:e,poolInfo:t,ownerInfo:n}){let r=o2([]),i=[{pubkey:n.wallet,isSigner:!0,isWritable:!0},{pubkey:t.poolId,isSigner:!1,isWritable:!0},{pubkey:n.ownerPda,isSigner:!1,isWritable:!0},...n.claimAddress.map(e=>({pubkey:e,isSigner:!1,isWritable:!0})),...t.tokenInfo.map(({mintVault:e})=>({pubkey:e,isSigner:!1,isWritable:!0})),{pubkey:td.H_,isSigner:!1,isWritable:!1}],o=tK.alloc(r.span);r.encode({},o);let a=tK.from([10,66,208,184,161,6,191,98,...o]);return new tu.Sl({keys:i,programId:e,data:a})}},u2=u1;u2.CLAIMED_NUM=3,u2.POOL_LAYOUT=o2([oU(8),o$("bump"),o$("status"),oH("openTime"),oH("endTime"),oX("ammId"),o6(o2([o$("mintDecimals"),oX("mintAddress"),oX("mintVault"),oH("perLpLoss"),oH("totalClaimedAmount")]),u1.CLAIMED_NUM,"tokenInfo"),o6(oH(),10,"padding")]),u2.OWNER_LAYOUT=o2([oU(8),o$("bump"),o$("version"),oX("poolId"),oX("owner"),oH("lpAmount"),o6(o2([oX("mintAddress"),oH("debtAmount"),oH("claimedAmount")]),u1.CLAIMED_NUM,"tokenInfo"),o6(oH(),4,"padding")]),u2.DEFAULT_POOL_ID=["58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2","6UmmUiYoBjSrhakAobJw8BvkmJtDVxaeBtbt7rxWo1mg","AVs9TA4nWDzfPJE9gGVNJMVhcQy3V9PGazuz33BfG2RA","DVa7Qmb5ct9RCpaU7UTpSaf3GVMYz17vNVU67XpdCRut","7XawhbbxtsRcQA8KTkHT9f9nc6d69UwqCDh6U5EEbEmX","6a1CsrpeZubDjEJE9s1CMVheB6HWM5d7m1cj2jkhyXhj","EoNrn8iUhwgJySD1pHu8Qxm5gSQqLK3za4m8xzD2RuEb","AceAyRTWt4PyB2pHqf2qhDgNZDtKVNaxgL8Ru3V4aN1P","6tmFJbMk5yVHFcFy7X2K8RwHjKLr6KVFLYXpgpBNeAxB"].map(e=>new tu.nh(e)),u2.SEED_CONFIG={pool:{id:tK.from("pool_seed","utf8")},owner:{id:tK.from("user_claim_seed","utf8")}},u2.VERSION_PROJECT=[void 0,"Francium","Tulip","Larix"],o2([o$("instruction"),oF("amount")]);var u6=o2([o$("instruction")]);function u3({programId:e},t){let n=[{pubkey:td.H_,isSigner:!1,isWritable:!1},{pubkey:r6,isSigner:!1,isWritable:!1},...Object.entries(t).map(([e,t])=>({pubkey:t,isSigner:"userOwner"===e,isWritable:!["authority","userOwner"].includes(e)}))],r=tK.alloc(u6.span);return u6.encode({instruction:2},r),new tu.Sl({keys:n,programId:e,data:r})}function u4(e){let{poolConfig:t,userKeys:n,side:r}=e,i="base"===r?n.baseTokenAccount:n.quoteTokenAccount,o="base"===r?t.baseVault:t.quoteVault,a=tK.alloc(u6.span);u6.encode({instruction:2},a);let s=[{pubkey:td.H_,isWritable:!1,isSigner:!1},{pubkey:tu.Am,isWritable:!1,isSigner:!1},{pubkey:t.id,isWritable:!0,isSigner:!1},{pubkey:t.authority,isWritable:!1,isSigner:!1},{pubkey:o,isWritable:!0,isSigner:!1},{pubkey:i,isWritable:!0,isSigner:!1},{pubkey:n.ledgerAccount,isWritable:!0,isSigner:!1},{pubkey:n.owner,isWritable:!1,isSigner:!0}];return new tu.Sl({programId:t.programId,keys:s,data:a})}var u5={[i8.IDO_PROGRAM_ID_V1.toString()]:1,[i8.IDO_PROGRAM_ID_V2.toString()]:2,[i8.IDO_PROGRAM_ID_V3.toString()]:3,[i8.IDO_PROGRAM_ID_V4.toString()]:4},u8=class extends oy{async claim({ownerInfo:e,idoKeys:t,associatedOnly:n=!0,checkCreateATAOwner:r=!1,txVersion:i}){let o=this.createTxBuilder(),a=u5[t.programId];a||this.logAndCreateError("invalid version",a);let s=ip(t),[u,l]=[!new(tb())(e.coin).isZero(),!new(tb())(e.pc).isZero()],c=s.projectInfo.mint.address.equals(r7),{account:d,instructionParams:p}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:s.projectInfo.mint.programId,mint:s.projectInfo.mint.address,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!c,notUseTokenAccount:c,associatedOnly:!c&&n,checkCreateATAOwner:r});!d&&u&&this.logAndCreateError("target token accounts not found","mint",t.projectInfo.mint.address),u&&p&&o.addInstruction(p);let f=s.buyInfo.mint.address.equals(r7),{account:h,instructionParams:m}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:s.buyInfo.mint.programId,mint:s.buyInfo.mint.address,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!f,notUseTokenAccount:f,associatedOnly:!f&&n,checkCreateATAOwner:r});if(!d&&l&&this.logAndCreateError("target token accounts not found","mint",t.projectInfo.mint.address),l&&m&&o.addInstruction(m),d&&h||this.logAndCreateError("target token accounts not found","mint",t.projectInfo.mint.address,t.buyInfo.mint.address),3===a)return o.addInstruction({instructions:[...u?[u3({programId:s.programId},{idoId:s.id,authority:s.authority,poolTokenAccount:s.projectInfo.vault,userTokenAccount:d,userIdoInfo:new tu.nh(e.userIdoInfo),userOwner:this.scope.ownerPubKey})]:[],...l?[u3({programId:new tu.nh(t.programId)},{idoId:s.id,authority:s.authority,poolTokenAccount:s.buyInfo.vault,userTokenAccount:h,userIdoInfo:new tu.nh(e.userIdoInfo),userOwner:this.scope.ownerPubKey})]:[]]}).versionBuild({txVersion:i});if(a<3)return u||l||this.logAndCreateError("no claimable rewards"),o.addInstruction({instructions:[u3({programId:s.programId},{idoId:s.id,authority:s.authority,poolQuoteTokenAccount:s.buyInfo.vault,poolBaseTokenAccount:s.projectInfo.vault,userQuoteTokenAccount:h,userBaseTokenAccount:d,userIdoInfo:new tu.nh(e.userIdoInfo),userOwner:this.scope.ownerPubKey})]}).versionBuild({txVersion:i});let g={poolConfig:{id:s.id,programId:s.programId,authority:s.authority,baseVault:s.projectInfo.vault,quoteVault:s.buyInfo.vault,baseToken:t.projectInfo.mint,quoteToken:t.buyInfo.mint},userKeys:{baseTokenAccount:d,quoteTokenAccount:h,ledgerAccount:new tu.nh(e.userIdoInfo),owner:this.scope.ownerPubKey}};return o.addInstruction({instructions:[...u?[u4(t1(t0({},g),{side:"base"}))]:[],...l?[u4(t1(t0({},g),{side:"quote"}))]:[]]}).versionBuild({txVersion:i})}},u9=class extends oy{constructor(e){super(e),this._tokenList=[],this._tokenMap=new Map,this._blackTokenMap=new Map,this._mintGroup={official:new Set,jup:new Set,extra:new Set},this._whiteMap=new Set,this._extraTokenList=[]}async load(e){this.checkDisabled();let{forceUpdate:t=!1,type:n="strict"}=e||{},{mintList:r,blacklist:i,whiteList:o}=await this.scope.fetchV3TokenList(t),a=await this.scope.fetchJupTokenList(t);this._tokenList=[],this._tokenMap=new Map,this._blackTokenMap=new Map,this._mintGroup={official:new Set,jup:new Set,extra:new Set},this._whiteMap=new Set(o),this._tokenMap.set(rG.address,rG),this._mintGroup.official.add(rG.address),i.forEach(e=>{this._blackTokenMap.set(e.address,t1(t0({},e),{priority:-1}))}),r.forEach(e=>{var t;this._blackTokenMap.has(e.address)||(this._tokenMap.set(e.address,t1(t0({},e),{type:"raydium",priority:2,programId:null!=(t=e.programId)?t:e.tags.includes("token-2022")?td.nA.toBase58():td.H_.toBase58()})),this._mintGroup.official.add(e.address))}),a.forEach(e=>{var t;this._blackTokenMap.has(e.address)||this._tokenMap.has(e.address)||(this._tokenMap.set(e.address,t1(t0({},e),{type:"jupiter",priority:1,programId:null!=(t=e.programId)?t:e.tags.includes("token-2022")?td.nA.toBase58():td.H_.toBase58(),tags:e.freezeAuthority?[...e.tags||[],"hasFreeze"]:e.tags})),this._mintGroup.jup.add(e.address))}),this._extraTokenList.forEach(e=>{this._blackTokenMap.has(e.address)||this._tokenMap.has(e.address)||(this._tokenMap.set(e.address,t1(t0({},e),{type:"extra",priority:1,programId:e.programId||e.tags.includes("token-2022")?td.nA.toBase58():td.H_.toBase58()})),this._mintGroup.extra.add(e.address))}),this._tokenList=Array.from(this._tokenMap).map(e=>e[1])}get tokenList(){return this._tokenList}get tokenMap(){return this._tokenMap}get blackTokenMap(){return this._blackTokenMap}get mintGroup(){return this._mintGroup}get whiteListMap(){return this._whiteMap}async getTokenInfo(e){if(!e)throw Error("please input mint");let t=e.toString(),n=this._tokenMap.get(t);if(n)return n;if("SOL"===t.toLocaleUpperCase())return rG;let r=(await this.scope.api.getTokenInfo([t]))[0];if(r)return this._mintGroup.extra.add(t),this._tokenMap.set(t,t1(t0({},r),{priority:2})),r;let i=await this.scope.connection.getAccountInfo(new tu.nh(t));if(!i)throw Error(`mint address not found: ${t}`);let o=tc.qT.decode(i.data),a=t.toString().substring(0,6),s={chainId:101,address:t,programId:i.owner.toBase58(),logoURI:"",symbol:a,name:a,decimals:o.decimals,tags:[],extensions:{},priority:0,type:"unknown"};return this._mintGroup.extra.add(t),this._tokenMap.set(t,s),s}},u7=class{constructor(e){this.rawBalances=new Map;let{connection:t,cluster:n,owner:r,api:i,defaultChainTime:o,defaultChainTimeOffset:a,apiCacheTime:s,blockhashCommitment:u="confirmed"}=e;this._connection=t,this.cluster=n||"mainnet",this._owner=r?new i_(r):void 0,this._signAllTransactions=e.signAllTransactions,this.blockhashCommitment=u,this.api=i,this._apiCacheTime=s||3e5,this.logger=t8("Raydium"),this.farm=new aj({scope:this,moduleName:"Raydium_Farm"}),this.account=new o7({scope:this,moduleName:"Raydium_Account",tokenAccounts:e.tokenAccounts,tokenAccountRawInfos:e.tokenAccountRawInfos}),this.liquidity=new ub({scope:this,moduleName:"Raydium_LiquidityV2"}),this.token=new u9({scope:this,moduleName:"Raydium_tokenV2"}),this.tradeV2=new u0({scope:this,moduleName:"Raydium_tradeV2"}),this.clmm=new u_({scope:this,moduleName:"Raydium_clmm"}),this.cpmm=new uK({scope:this,moduleName:"Raydium_cpmm"}),this.utils1216=new u2({scope:this,moduleName:"Raydium_utils1216"}),this.marketV2=new uy({scope:this,moduleName:"Raydium_marketV2"}),this.ido=new u8({scope:this,moduleName:"Raydium_ido"}),this.availability={};let l=new Date().getTime();this.apiData={},a&&(this._chainTime={fetched:l,value:{chainTime:o||Date.now()-a,offset:a}})}static async load(e){var t;let n=(0,tl.merge)({cluster:"mainnet",owner:null,apiRequestInterval:3e5,apiRequestTimeout:1e4},e),{cluster:r,apiRequestTimeout:i,logCount:o,logRequests:a,urlConfigs:s}=n,u=new oh({cluster:r,timeout:i,urlConfigs:s,logCount:o,logRequests:a}),l=new u7(t1(t0({},n),{api:u}));return await l.fetchAvailabilityStatus(null==(t=e.disableFeatureCheck)||t),e.disableLoadToken||await l.token.load({type:e.jupTokenType}),l}get owner(){return this._owner}get ownerPubKey(){if(!this._owner)throw Error(om);return this._owner.publicKey}setOwner(e){return this._owner=e?new i_(e):void 0,this.account.resetTokenAccounts(),this}get connection(){if(!this._connection)throw Error("please provide connection in load() initialization or set it by raydium.setConnection(connection)");return this._connection}setConnection(e){return this._connection=e,this}get signAllTransactions(){return this._signAllTransactions}setSignAllTransactions(e){return this._signAllTransactions=e,this}checkOwner(){if(!this.owner)throw this.logger.error(om),Error(om)}isCacheInvalidate(e){return new Date().getTime()-e>this._apiCacheTime}async fetchChainTime(){try{let e=await this.api.getChainTimeOffset();this._chainTime={fetched:Date.now(),value:{chainTime:Date.now()+1e3*e.offset,offset:1e3*e.offset}}}catch{this._chainTime=void 0}}async fetchV3TokenList(e){if(this.apiData.tokenList&&!this.isCacheInvalidate(this.apiData.tokenList.fetched)&&!e)return this.apiData.tokenList.data;try{let e=await this.api.getTokenList(),t={fetched:Date.now(),data:e};return this.apiData.tokenList=t,t.data}catch(e){return console.error(e),{mintList:[],blacklist:[],whiteList:[]}}}async fetchJupTokenList(e){let t=this.apiData.jupTokenList;if(t&&!this.isCacheInvalidate(t.fetched)&&!e)return t.data;try{let e=await this.api.getJupTokenList();return this.apiData.jupTokenList={fetched:Date.now(),data:e.map(e=>t1(t0({},e),{mintAuthority:e.mint_authority||void 0,freezeAuthority:e.freeze_authority||void 0}))},this.apiData.jupTokenList.data}catch(e){return console.error(e),[]}}get chainTimeData(){var e;return null==(e=this._chainTime)?void 0:e.value}async chainTimeOffset(){var e;return this._chainTime&&Date.now()-this._chainTime.fetched<=3e5?this._chainTime.value.offset:(await this.fetchChainTime(),(null==(e=this._chainTime)?void 0:e.value.offset)||0)}async currentBlockChainTime(){var e;return this._chainTime&&Date.now()-this._chainTime.fetched<=3e5?this._chainTime.value.chainTime:(await this.fetchChainTime(),(null==(e=this._chainTime)?void 0:e.value.chainTime)||Date.now())}async fetchEpochInfo(){return this._epochInfo&&Date.now()-this._epochInfo.fetched<=3e4||(this._epochInfo={fetched:Date.now(),value:await this.connection.getEpochInfo()}),this._epochInfo.value}async fetchAvailabilityStatus(e){if(e)return{};try{let e=await this.api.fetchAvailabilityStatus(),t=!1===e.all;return this.availability={all:e.all,swap:!t&&e.swap,createConcentratedPosition:!t&&e.createConcentratedPosition,addConcentratedPosition:!t&&e.addConcentratedPosition,addStandardPosition:!t&&e.addStandardPosition,removeConcentratedPosition:!t&&e.removeConcentratedPosition,removeStandardPosition:!t&&e.removeStandardPosition,addFarm:!t&&e.addFarm,removeFarm:!t&&e.removeFarm},e}catch{return{}}}};/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */},93066:function(e,t,n){"use strict";n.d(t,{Xg:function(){return x},ZL:function(){return S},AW:function(){return l}});var r=n(39386),i=n(40475);let o=e=>{let t=e.decode.bind(e),n=e.encode.bind(e);return{decode:t,encode:n}};var a=n(48764).Buffer;let s=e=>t=>{let n=(0,r.Ik)(e,t),{encode:s,decode:u}=o(n),l=n;return l.decode=(e,t)=>{let n=u(e,t);return(0,i.oU)(a.from(n))},l.encode=(t,n,r)=>{let o=(0,i.k$)(t,e);return s(o,n,r)},l},u=e=>t=>{let n=(0,r.Ik)(e,t),{encode:s,decode:u}=o(n),l=n;return l.decode=(e,t)=>{let n=u(e,t);return(0,i.Q5)(a.from(n))},l.encode=(t,n,r)=>{let o=(0,i.zP)(t,e);return s(o,n,r)},l},l=s(8);u(8),s(16),u(16),s(24),u(24),s(32),u(32);var c=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,d=Math.ceil,p=Math.floor,f="[BigNumber Error] ",h=f+"Number primitive has more than 15 significant digits: ",m=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13];function g(e){var t=0|e;return e>0||e===t?t:t-1}function y(e){for(var t,n,r=1,i=e.length,o=e[0]+"";rl^n?1:-1;for(a=0,s=(u=i.length)<(l=o.length)?u:l;ao[a]^n?1:-1;return u==l?0:u>l^n?1:-1}function _(e,t,n,r){if(en||e!==p(e))throw Error(f+(r||"Argument")+("number"==typeof e?en?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function v(e){var t=e.c.length-1;return g(e.e/14)==t&&e.c[t]%2!=0}function w(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function k(e,t,n){var r,i;if(t<0){for(i=n+".";++t;i+=n);e=i+e}else if(r=e.length,++t>r){for(i=n,t-=r;--t;i+=n);e+=i}else tO?f.c=f.e=null:e.e=10;a/=10,o++);o>O?f.c=f.e=null:(f.e=o,f.c=[e]);return}d=String(e)}else{if(!c.test(d=String(e)))return x(f,d,s);f.s=45==d.charCodeAt(0)?(d=d.slice(1),-1):1}(o=d.indexOf("."))>-1&&(d=d.replace(".","")),(a=d.search(/e/i))>0?(o<0&&(o=a),o+=+d.slice(a+1),d=d.substring(0,a)):o<0&&(o=d.length)}else{if(_(t,2,N.length,"Base"),10==t&&D)return z(f=new F(e),I+f.e+1,T);if(d=String(e),s="number"==typeof e){if(0*e!=0)return x(f,d,s,t);if(f.s=1/e<0?(d=d.slice(1),-1):1,F.DEBUG&&d.replace(/^0\.0*|\./,"").length>15)throw Error(h+e)}else f.s=45===d.charCodeAt(0)?(d=d.slice(1),-1):1;for(n=N.slice(0,t),o=a=0,u=d.length;an.indexOf(r=d.charAt(a))){if("."==r){if(a>o){o=u;continue}}else if(!i&&(d==d.toUpperCase()&&(d=d.toLowerCase())||d==d.toLowerCase()&&(d=d.toUpperCase()))){i=!0,a=-1,o=0;continue}return x(f,String(e),s,t)}s=!1,(o=(d=l(d,t,10,f.s)).indexOf("."))>-1?d=d.replace(".",""):o=d.length}for(a=0;48===d.charCodeAt(a);a++);for(u=d.length;48===d.charCodeAt(--u););if(d=d.slice(a,++u)){if(u-=a,s&&F.DEBUG&&u>15&&(e>9007199254740991||e!==p(e)))throw Error(h+f.s*e);if((o=o-a-1)>O)f.c=f.e=null;else if(o=P)?w(u,a):k(u,a,"0");else if(o=(e=z(new F(e),t,n)).e,s=(u=y(e.c)).length,1==r||2==r&&(t<=o||o<=E)){for(;ss){if(--t>0)for(u+=".";t--;u+="0");}else if((t+=o-s)>0)for(o+1==s&&(u+=".");t--;u+="0");return e.s<0&&i?"-"+u:u}function j(e,t){for(var n,r=1,i=new F(e[0]);r=10;i/=10,r++);return(n=r+14*n-1)>O?e.c=e.e=null:n=10;s/=10,i++);if((o=t-i)<0)o+=14,a=t,c=(u=f[l=0])/m[i-a-1]%10|0;else if((l=d((o+1)/14))>=f.length){if(r){for(;f.length<=l;f.push(0));u=c=0,i=1,o%=14,a=o-14+1}else break t}else{for(i=1,u=s=f[l];s>=10;s/=10,i++);o%=14,c=(a=o-14+i)<0?0:u/m[i-a-1]%10|0}if(r=r||t<0||null!=f[l+1]||(a<0?u:u%m[i-a-1]),r=n<4?(c||r)&&(0==n||n==(e.s<0?3:2)):c>5||5==c&&(4==n||r||6==n&&(o>0?a>0?u/m[i-a]:0:f[l-1])%10&1||n==(e.s<0?8:7)),t<1||!f[0])return f.length=0,r?(t-=e.e+1,f[0]=m[(14-t%14)%14],e.e=-t||0):f[0]=e.e=0,e;if(0==o?(f.length=l,s=1,l--):(f.length=l+1,s=m[14-o],f[l]=a>0?p(u/m[i-a]%m[a])*s:0),r)for(;;){if(0==l){for(o=1,a=f[0];a>=10;a/=10,o++);for(a=f[0]+=s,s=1;a>=10;a/=10,s++);o!=s&&(e.e++,1e14==f[0]&&(f[0]=1));break}if(f[l]+=s,1e14!=f[l])break;f[l--]=0,s=1}for(o=f.length;0===f[--o];f.pop());}e.e>O?e.c=e.e=null:e.e=P?w(t,n):k(t,n,"0"),e.s<0?"-"+t:t)}return F.clone=e,F.ROUND_UP=0,F.ROUND_DOWN=1,F.ROUND_CEIL=2,F.ROUND_FLOOR=3,F.ROUND_HALF_UP=4,F.ROUND_HALF_DOWN=5,F.ROUND_HALF_EVEN=6,F.ROUND_HALF_CEIL=7,F.ROUND_HALF_FLOOR=8,F.EUCLID=9,F.config=F.set=function(e){var t,n;if(null!=e){if("object"==typeof e){if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(_(n=e[t],0,1e9,t),I=n),e.hasOwnProperty(t="ROUNDING_MODE")&&(_(n=e[t],0,8,t),T=n),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((n=e[t])&&n.pop?(_(n[0],-1e9,0,t),_(n[1],0,1e9,t),E=n[0],P=n[1]):(_(n,-1e9,1e9,t),E=-(P=n<0?-n:n))),e.hasOwnProperty(t="RANGE")){if((n=e[t])&&n.pop)_(n[0],-1e9,-1,t),_(n[1],1,1e9,t),C=n[0],O=n[1];else if(_(n,-1e9,1e9,t),n)C=-(O=n<0?-n:n);else throw Error(f+t+" cannot be zero: "+n)}if(e.hasOwnProperty(t="CRYPTO")){if(!!(n=e[t])===n){if(n){if("undefined"!=typeof crypto&&crypto&&(crypto.getRandomValues||crypto.randomBytes))B=n;else throw B=!n,Error(f+"crypto unavailable")}else B=n}else throw Error(f+t+" not true or false: "+n)}if(e.hasOwnProperty(t="MODULO_MODE")&&(_(n=e[t],0,9,t),M=n),e.hasOwnProperty(t="POW_PRECISION")&&(_(n=e[t],0,1e9,t),R=n),e.hasOwnProperty(t="FORMAT")){if("object"==typeof(n=e[t]))L=n;else throw Error(f+t+" not an object: "+n)}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(n=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(f+t+" invalid: "+n);D="0123456789"==n.slice(0,10),N=n}}else throw Error(f+"Object expected: "+e)}return{DECIMAL_PLACES:I,ROUNDING_MODE:T,EXPONENTIAL_AT:[E,P],RANGE:[C,O],CRYPTO:B,MODULO_MODE:M,POW_PRECISION:R,FORMAT:L,ALPHABET:N}},F.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!F.DEBUG)return!0;var t,n,r=e.c,i=e.e,o=e.s;t:if("[object Array]"==({}).toString.call(r)){if((1===o||-1===o)&&i>=-1e9&&i<=1e9&&i===p(i)){if(0===r[0]){if(0===i&&1===r.length)return!0;break t}if((t=(i+1)%14)<1&&(t+=14),String(r[0]).length==t){for(t=0;t=1e14||n!==p(n))break t;if(0!==n)return!0}}}else if(null===r&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(f+"Invalid BigNumber: "+e)},F.maximum=F.max=function(){return j(arguments,A.lt)},F.minimum=F.min=function(){return j(arguments,A.gt)},F.random=(n=9007199254740992*Math.random()&2097151?function(){return p(9007199254740992*Math.random())}:function(){return(1073741824*Math.random()|0)*8388608+(8388608*Math.random()|0)},function(e){var t,r,i,o,a,s=0,u=[],l=new F(S);if(null==e?e=I:_(e,0,1e9),o=d(e/14),B){if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(o*=2));s>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[s]=r[0],t[s+1]=r[1]):(u.push(a%1e14),s+=2);s=o/2}else if(crypto.randomBytes){for(t=crypto.randomBytes(o*=7);s=9e15?crypto.randomBytes(7).copy(t,s):(u.push(a%1e14),s+=7);s=o/7}else throw B=!1,Error(f+"crypto unavailable")}if(!B)for(;s=10;a/=10,s++);s<14&&(i-=14-s)}return l.e=i,l.c=u,l}),F.sum=function(){for(var e=1,t=arguments,n=new F(t[0]);en-1&&(null==a[i+1]&&(a[i+1]=0),a[i+1]+=a[i]/n|0,a[i]%=n)}return a.reverse()}return function(n,r,i,o,a){var s,l,c,d,p,f,h,m,g=n.indexOf("."),b=I,_=T;for(g>=0&&(d=R,R=0,n=n.replace(".",""),f=(m=new F(r)).pow(n.length-g),R=d,m.c=t(k(y(f.c),f.e,"0"),10,i,e),m.e=m.c.length),c=d=(h=t(n,r,i,a?(s=N,e):(s=e,N))).length;0==h[--d];h.pop());if(!h[0])return s.charAt(0);if(g<0?--c:(f.c=h,f.e=c,f.s=o,h=(f=u(f,m,b,_,i)).c,p=f.r,c=f.e),g=h[l=c+b+1],d=i/2,p=p||l<0||null!=h[l+1],p=_<4?(null!=g||p)&&(0==_||_==(f.s<0?3:2)):g>d||g==d&&(4==_||p||6==_&&1&h[l-1]||_==(f.s<0?8:7)),l<1||!h[0])n=p?k(s.charAt(1),-b,s.charAt(0)):s.charAt(0);else{if(h.length=l,p)for(--i;++h[--l]>i;)h[l]=0,l||(++c,h=[1].concat(h));for(d=h.length;!h[--d];);for(g=0,n="";g<=d;n+=s.charAt(h[g++]));n=k(n,c,s.charAt(0))}return n}}(),u=function(){function e(e,t,n){var r,i,o,a,s=0,u=e.length,l=t%1e7,c=t/1e7|0;for(e=e.slice();u--;)r=c*(o=e[u]%1e7)+(a=e[u]/1e7|0)*l,s=((i=l*o+r%1e7*1e7+s)/n|0)+(r/1e7|0)+c*a,e[u]=i%n;return s&&(e=[s].concat(e)),e}function t(e,t,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;it[i]?1:-1;break}return o}function n(e,t,n,r){for(var i=0;n--;)e[n]-=i,i=e[n]1;e.splice(0,1));}return function(r,i,o,a,s){var u,l,c,d,f,h,m,y,b,_,v,w,k,x,A,S,I,T=r.s==i.s?1:-1,E=r.c,P=i.c;if(!E||!E[0]||!P||!P[0])return new F(r.s&&i.s&&(E?!P||E[0]!=P[0]:P)?E&&0==E[0]||!P?0*T:T/0:NaN);for(b=(y=new F(T)).c=[],T=o+(l=r.e-i.e)+1,s||(s=1e14,l=g(r.e/14)-g(i.e/14),T=T/14|0),c=0;P[c]==(E[c]||0);c++);if(P[c]>(E[c]||0)&&l--,T<0)b.push(1),d=!0;else{for(x=E.length,S=P.length,c=0,T+=2,(f=p(s/(P[0]+1)))>1&&(P=e(P,f,s),E=e(E,f,s),S=P.length,x=E.length),k=S,v=(_=E.slice(0,S)).length;v=s/2&&A++;do{if(f=0,(u=t(P,_,S,v))<0){if(w=_[0],S!=v&&(w=w*s+(_[1]||0)),(f=p(w/A))>1)for(f>=s&&(f=s-1),m=(h=e(P,f,s)).length,v=_.length;1==t(h,_,m,v);)f--,n(h,St(P,_,S,v);)f++,n(_,S=10;T/=10,c++);z(y,o+(y.e=c+14*l-1)+1,a,d)}else y.e=l,y.r=+d;return y}}(),r=/^(-?)0([xbo])(?=\w[\w.]*$)/i,i=/^([^.]+)\.$/,o=/^\.([^.]+)$/,a=/^-?(Infinity|NaN)$/,s=/^\s*\+(?=[\w.])|^\s+|\s+$/g,x=function(e,t,n,u){var l,c=n?t:t.replace(s,"");if(a.test(c))e.s=isNaN(c)?null:c<0?-1:1;else{if(!n&&(c=c.replace(r,function(e,t,n){return l="x"==(n=n.toLowerCase())?16:"b"==n?2:8,u&&u!=l?e:t}),u&&(l=u,c=c.replace(i,"$1").replace(o,"0.$1")),t!=c))return new F(c,l);if(F.DEBUG)throw Error(f+"Not a"+(u?" base "+u:"")+" number: "+t);e.s=null}e.c=e.e=null},A.absoluteValue=A.abs=function(){var e=new F(this);return e.s<0&&(e.s=1),e},A.comparedTo=function(e,t){return b(this,new F(e,t))},A.decimalPlaces=A.dp=function(e,t){var n,r,i;if(null!=e)return _(e,0,1e9),null==t?t=T:_(t,0,8),z(new F(this),e+this.e+1,t);if(!(n=this.c))return null;if(r=((i=n.length-1)-g(this.e/14))*14,i=n[i])for(;i%10==0;i/=10,r--);return r<0&&(r=0),r},A.dividedBy=A.div=function(e,t){return u(this,new F(e,t),I,T)},A.dividedToIntegerBy=A.idiv=function(e,t){return u(this,new F(e,t),0,1)},A.exponentiatedBy=A.pow=function(e,t){var n,r,i,o,a,s,u,l,c,h=this;if((e=new F(e)).c&&!e.isInteger())throw Error(f+"Exponent not an integer: "+V(e));if(null!=t&&(t=new F(t)),s=e.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!e.c||!e.c[0])return c=new F(Math.pow(+V(h),s?2-v(e):+V(e))),t?c.mod(t):c;if(u=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new F(NaN);(r=!u&&h.isInteger()&&t.isInteger())&&(h=h.mod(t))}else{if(e.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return o=h.s<0&&v(e)?-0:0,h.e>-1&&(o=1/o),new F(u?1/o:o);R&&(o=d(R/14+2))}for(s?(n=new F(.5),u&&(e.s=1),l=v(e)):l=(i=Math.abs(+V(e)))%2,c=new F(S);;){if(l){if(!(c=c.times(h)).c)break;o?c.c.length>o&&(c.c.length=o):r&&(c=c.mod(t))}if(i){if(0===(i=p(i/2)))break;l=i%2}else if(z(e=e.times(n),e.e+1,1),e.e>14)l=v(e);else{if(0==(i=+V(e)))break;l=i%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):r&&(h=h.mod(t))}return r?c:(u&&(c=S.div(c)),t?c.mod(t):o?z(c,R,T,a):c)},A.integerValue=function(e){var t=new F(this);return null==e?e=T:_(e,0,8),z(t,t.e+1,e)},A.isEqualTo=A.eq=function(e,t){return 0===b(this,new F(e,t))},A.isFinite=function(){return!!this.c},A.isGreaterThan=A.gt=function(e,t){return b(this,new F(e,t))>0},A.isGreaterThanOrEqualTo=A.gte=function(e,t){return 1===(t=b(this,new F(e,t)))||0===t},A.isInteger=function(){return!!this.c&&g(this.e/14)>this.c.length-2},A.isLessThan=A.lt=function(e,t){return 0>b(this,new F(e,t))},A.isLessThanOrEqualTo=A.lte=function(e,t){return -1===(t=b(this,new F(e,t)))||0===t},A.isNaN=function(){return!this.s},A.isNegative=function(){return this.s<0},A.isPositive=function(){return this.s>0},A.isZero=function(){return!!this.c&&0==this.c[0]},A.minus=function(e,t){var n,r,i,o,a=this.s;if(t=(e=new F(e,t)).s,!a||!t)return new F(NaN);if(a!=t)return e.s=-t,this.plus(e);var s=this.e/14,u=e.e/14,l=this.c,c=e.c;if(!s||!u){if(!l||!c)return l?(e.s=-t,e):new F(c?this:NaN);if(!l[0]||!c[0])return c[0]?(e.s=-t,e):new F(l[0]?this:3==T?-0:0)}if(s=g(s),u=g(u),l=l.slice(),a=s-u){for((o=a<0)?(a=-a,i=l):(u=s,i=c),i.reverse(),t=a;t--;i.push(0));i.reverse()}else for(r=(o=(a=l.length)<(t=c.length))?a:t,a=t=0;t0)for(;t--;l[n++]=0);for(t=1e14-1;r>a;){if(l[--r]=0;){for(n=0,p=y[i]%1e7,f=y[i]/1e7|0,a=u,o=i+a;o>i;)s=f*(l=m[--a]%1e7)+(c=m[a]/1e7|0)*p,n=((l=p*l+s%1e7*1e7+h[o]+n)/1e14|0)+(s/1e7|0)+f*c,h[o--]=l%1e14;h[o]=n}return n?++r:h.splice(0,1),U(e,h,r)},A.negated=function(){var e=new F(this);return e.s=-e.s||null,e},A.plus=function(e,t){var n,r=this.s;if(t=(e=new F(e,t)).s,!r||!t)return new F(NaN);if(r!=t)return e.s=-t,this.minus(e);var i=this.e/14,o=e.e/14,a=this.c,s=e.c;if(!i||!o){if(!a||!s)return new F(r/0);if(!a[0]||!s[0])return s[0]?e:new F(a[0]?this:0*r)}if(i=g(i),o=g(o),a=a.slice(),r=i-o){for(r>0?(o=i,n=s):(r=-r,n=a),n.reverse();r--;n.push(0));n.reverse()}for((r=a.length)-(t=s.length)<0&&(n=s,s=a,a=n,t=r),r=0;t;)r=(a[--t]=a[t]+s[t]+r)/1e14|0,a[t]=1e14===a[t]?0:a[t]%1e14;return r&&(a=[r].concat(a),++o),U(e,a,o)},A.precision=A.sd=function(e,t){var n,r,i;if(null!=e&&!!e!==e)return _(e,1,1e9),null==t?t=T:_(t,0,8),z(new F(this),e,t);if(!(n=this.c))return null;if(r=14*(i=n.length-1)+1,i=n[i]){for(;i%10==0;i/=10,r--);for(i=n[0];i>=10;i/=10,r++);}return e&&this.e+1>r&&(r=this.e+1),r},A.shiftedBy=function(e){return _(e,-9007199254740991,9007199254740991),this.times("1e"+e)},A.squareRoot=A.sqrt=function(){var e,t,n,r,i,o=this.c,a=this.s,s=this.e,l=I+4,c=new F("0.5");if(1!==a||!o||!o[0])return new F(!a||a<0&&(!o||o[0])?NaN:o?this:1/0);if(0==(a=Math.sqrt(+V(this)))||a==1/0?(((t=y(o)).length+s)%2==0&&(t+="0"),a=Math.sqrt(+t),s=g((s+1)/2)-(s<0||s%2),t=a==1/0?"5e"+s:(t=a.toExponential()).slice(0,t.indexOf("e")+1)+s,n=new F(t)):n=new F(a+""),n.c[0]){for((a=(s=n.e)+l)<3&&(a=0);;)if(i=n,n=c.times(i.plus(u(this,i,l,1))),y(i.c).slice(0,a)===(t=y(n.c)).slice(0,a)){if(n.e0&&h>0){for(i=h%a||a,l=p.substr(0,i);i0&&(l+=u+p.slice(i)),d&&(l="-"+l)}r=c?l+(n.decimalSeparator||"")+((s=+n.fractionGroupSize)?c.replace(RegExp("\\d{"+s+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):c):l}return(n.prefix||"")+r+(n.suffix||"")},A.toFraction=function(e){var t,n,r,i,o,a,s,l,c,d,p,h,g=this.c;if(null!=e&&(!(s=new F(e)).isInteger()&&(s.c||1!==s.s)||s.lt(S)))throw Error(f+"Argument "+(s.isInteger()?"out of range: ":"not an integer: ")+V(s));if(!g)return new F(this);for(t=new F(S),c=n=new F(S),r=l=new F(S),h=y(g),o=t.e=h.length-this.e-1,t.c[0]=m[(a=o%14)<0?14+a:a],e=!e||s.comparedTo(t)>0?o>0?t:c:s,a=O,O=1/0,s=new F(h),l.c[0]=0;d=u(s,t,0,1),1!=(i=n.plus(d.times(r))).comparedTo(e);)n=r,r=i,c=l.plus(d.times(i=c)),l=i,t=s.minus(d.times(i=t)),s=i;return i=u(e.minus(n),r,0,1),l=l.plus(i.times(c)),n=n.plus(i.times(r)),l.s=c.s=this.s,o*=2,p=1>u(c,r,o,T).minus(this).abs().comparedTo(u(l,n,o,T).minus(this).abs())?[c,r]:[l,n],O=a,p},A.toNumber=function(){return+V(this)},A.toPrecision=function(e,t){return null!=e&&_(e,1,1e9),q(this,e,t,2)},A.toString=function(e){var t,n=this,r=n.s,i=n.e;return null===i?r?(t="Infinity",r<0&&(t="-"+t)):t="NaN":(null==e?t=i<=E||i>=P?w(y(n.c),i):k(y(n.c),i,"0"):10===e&&D?t=k(y((n=z(new F(n),I+i+1,T)).c),n.e,"0"):(_(e,2,N.length,"Base"),t=l(k(y(n.c),i,"0"),10,e,r,!0)),r<0&&n.c[0]&&(t="-"+t)),t},A.valueOf=A.toJSON=function(){return V(this)},A._isBigNumber=!0,A[Symbol.toStringTag]="BigNumber",A[Symbol.for("nodejs.util.inspect.custom")]=A.valueOf,null!=t&&F.set(t),F}())("1e+18");let x=e=>{let t=(0,r.u8)(e),{encode:n,decode:i}=o(t),a=t;return a.decode=(e,t)=>{let n=i(e,t);return!!n},a.encode=(e,t,r)=>{let i=Number(e);return n(i,t,r)},a};var A=n(64174);let S=e=>{let t=(0,r.Ik)(32,e),{encode:n,decode:i}=o(t),a=t;return a.decode=(e,t)=>{let n=i(e,t);return new A.nh(n)},a.encode=(e,t,r)=>{let i=e.toBuffer();return n(i,t,r)},a}},39386:function(e,t,n){"use strict";t.Tl=t.s8=t.$r=t.hn=t.qY=t.Gj=t.b7=t.Lb=t._O=t.aq=t.ut=t.Jq=t.Vb=t.KB=t.u8=t.cv=t._H=t.t6=t.VQ=t.EJ=t.vA=t.fP=t.Ar=void 0,t.KA=t.ZZ=t.Ik=t.K_=t.G0=t.A9=t.pc=t.n_=t.Mn=t.eh=t.WZ=t.xn=t.LN=t.hO=t.IS=t.u=t.O9=t.xP=t.gM=t.Yt=t._n=t.Xo=t.aQ=void 0;let r=n(48764);function i(e){if(!(e instanceof Uint8Array))throw TypeError("b must be a Uint8Array")}function o(e){return i(e),r.Buffer.from(e.buffer,e.byteOffset,e.length)}class a{constructor(e,t){if(!Number.isInteger(e))throw TypeError("span must be an integer");this.span=e,this.property=t}makeDestinationObject(){return{}}getSpan(e,t){if(0>this.span)throw RangeError("indeterminate span");return this.span}replicate(e){let t=Object.create(this.constructor.prototype);return Object.assign(t,this),t.property=e,t}fromArray(e){}}function s(e,t){return t.property?e+"["+t.property+"]":e}t.Ar=a;class u extends a{isCount(){throw Error("ExternalLayout is abstract")}}class l extends u{constructor(e=1,t){if(!Number.isInteger(e)||0>=e)throw TypeError("elementSpan must be a (positive) integer");super(-1,t),this.elementSpan=e}isCount(){return!0}decode(e,t=0){i(e);let n=e.length-t;return Math.floor(n/this.elementSpan)}encode(e,t,n){return 0}}class c extends u{constructor(e,t=0,n){if(!(e instanceof a))throw TypeError("layout must be a Layout");if(!Number.isInteger(t))throw TypeError("offset must be integer or undefined");super(e.span,n||e.property),this.layout=e,this.offset=t}isCount(){return this.layout instanceof d||this.layout instanceof p}decode(e,t=0){return this.layout.decode(e,t+this.offset)}encode(e,t,n=0){return this.layout.encode(e,t,n+this.offset)}}class d extends a{constructor(e,t){if(super(e,t),6e+r.encode(i,t,n+e),0);return this.count instanceof u&&this.count.encode(e.length,t,n),i}}class I extends a{constructor(e,t,n){if(!(Array.isArray(e)&&e.reduce((e,t)=>e&&t instanceof a,!0)))throw TypeError("fields must be array of Layout instances");for(let r of("boolean"==typeof t&&void 0===n&&(n=t,t=void 0),e))if(0>r.span&&void 0===r.property)throw Error("fields cannot contain unnamed variable-length layout");let r=-1;try{r=e.reduce((e,t)=>e+t.getSpan(),0)}catch(e){}super(r,t),this.fields=e,this.decodePrefixes=!!n}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0;try{n=this.fields.reduce((n,r)=>{let i=r.getSpan(e,t);return t+=i,n+i},0)}catch(e){throw RangeError("indeterminate span")}return n}decode(e,t=0){i(e);let n=this.makeDestinationObject();for(let r of this.fields)if(void 0!==r.property&&(n[r.property]=r.decode(e,t)),t+=r.getSpan(e,t),this.decodePrefixes&&e.length===t)break;return n}encode(e,t,n=0){let r=n,i=0,o=0;for(let r of this.fields){let a=r.span;if(o=0a&&(a=r.getSpan(t,n)))}i=n,n+=a}return i+o-r}fromArray(e){let t=this.makeDestinationObject();for(let n of this.fields)void 0!==n.property&&0n.span?t=-1:0<=t&&(t+=n.span)}}}t.vA=I;class T{constructor(e){this.property=e}decode(e,t){throw Error("UnionDiscriminator is abstract")}encode(e,t,n){throw Error("UnionDiscriminator is abstract")}}class E extends T{constructor(e,t){if(!(e instanceof u&&e.isCount()))throw TypeError("layout must be an unsigned integer ExternalLayout");super(t||e.property||"variant"),this.layout=e}decode(e,t){return this.layout.decode(e,t)}encode(e,t,n){return this.layout.encode(e,t,n)}}class P extends a{constructor(e,t,n){let r;if(e instanceof d||e instanceof p)r=new E(new c(e));else if(e instanceof u&&e.isCount())r=new E(e);else if(e instanceof T)r=e;else throw TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");if(void 0===t&&(t=null),!(null===t||t instanceof a))throw TypeError("defaultLayout must be null or a Layout");if(null!==t){if(0>t.span)throw Error("defaultLayout must have constant span");void 0===t.property&&(t=t.replicate("content"))}let i=-1;t&&0<=(i=t.span)&&(e instanceof d||e instanceof p)&&(i+=r.layout.span),super(i,n),this.discriminator=r,this.usesPrefixDiscriminator=e instanceof d||e instanceof p,this.defaultLayout=t,this.registry={};let o=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(e){return o(e)},this.configGetSourceVariant=function(e){o=e.bind(this)}}getSpan(e,t=0){if(0<=this.span)return this.span;let n=this.getVariant(e,t);if(!n)throw Error("unable to determine span for unrecognized variant");return n.getSpan(e,t)}defaultGetSourceVariant(e){if(Object.prototype.hasOwnProperty.call(e,this.discriminator.property)){if(this.defaultLayout&&this.defaultLayout.property&&Object.prototype.hasOwnProperty.call(e,this.defaultLayout.property))return;let t=this.registry[e[this.discriminator.property]];if(t&&(!t.layout||t.property&&Object.prototype.hasOwnProperty.call(e,t.property)))return t}else for(let t in this.registry){let n=this.registry[t];if(n.property&&Object.prototype.hasOwnProperty.call(e,n.property))return n}throw Error("unable to infer src variant")}decode(e,t=0){let n;let r=this.discriminator,i=r.decode(e,t),o=this.registry[i];if(void 0===o){let o=this.defaultLayout,a=0;this.usesPrefixDiscriminator&&(a=r.layout.span),(n=this.makeDestinationObject())[r.property]=i,n[o.property]=o.decode(e,t+a)}else n=o.decode(e,t);return n}encode(e,t,n=0){let r=this.getSourceVariant(e);if(void 0===r){let r=this.discriminator,i=this.defaultLayout,o=0;return this.usesPrefixDiscriminator&&(o=r.layout.span),r.encode(e[r.property],t,n),o+i.encode(e[i.property],t,n+o)}return r.encode(e,t,n)}addVariant(e,t,n){let r=new C(this,e,t,n);return this.registry[e]=r,r}getVariant(e,t=0){let n;return n=e instanceof Uint8Array?this.discriminator.decode(e,t):e,this.registry[n]}}t.EJ=P;class C extends a{constructor(e,t,n,r){if(!(e instanceof P))throw TypeError("union must be a Union");if(!Number.isInteger(t)||0>t)throw TypeError("variant must be a (non-negative) integer");if("string"==typeof n&&void 0===r&&(r=n,n=null),n){if(!(n instanceof a))throw TypeError("layout must be a Layout");if(null!==e.defaultLayout&&0<=n.span&&n.span>e.defaultLayout.span)throw Error("variant span exceeds span of containing union");if("string"!=typeof r)throw TypeError("variant must have a String property")}let i=e.span;0>e.span&&0<=(i=n?n.span:0)&&e.usesPrefixDiscriminator&&(i+=e.discriminator.layout.span),super(i,r),this.union=e,this.variant=t,this.layout=n||null}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0;this.union.usesPrefixDiscriminator&&(n=this.union.discriminator.layout.span);let r=0;return this.layout&&(r=this.layout.getSpan(e,t+n)),n+r}decode(e,t=0){let n=this.makeDestinationObject();if(this!==this.union.getVariant(e,t))throw Error("variant mismatch");let r=0;return this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span),this.layout?n[this.property]=this.layout.decode(e,t+r):this.property?n[this.property]=!0:this.union.usesPrefixDiscriminator&&(n[this.union.discriminator.property]=this.variant),n}encode(e,t,n=0){let r=0;if(this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span),this.layout&&!Object.prototype.hasOwnProperty.call(e,this.property))throw TypeError("variant lacks property "+this.property);this.union.discriminator.encode(this.variant,t,n);let i=r;if(this.layout&&(this.layout.encode(e[this.property],t,n+r),i+=this.layout.getSpan(t,n+r),0<=this.union.span&&i>this.union.span))throw Error("encoded variant overruns containing union");return i}fromArray(e){if(this.layout)return this.layout.fromArray(e)}}function O(e){return 0>e&&(e+=4294967296),e}class B extends a{constructor(e,t,n){if(!(e instanceof d||e instanceof p))throw TypeError("word must be a UInt or UIntBE layout");if("string"==typeof t&&void 0===n&&(n=t,t=!1),4=t)throw TypeError("bits must be positive integer");let r=8*e.span,i=e.fields.reduce((e,t)=>e+t.bits,0);if(t+i>r)throw Error("bits too long for span remainder ("+(r-i)+" of "+r+" remain)");this.container=e,this.bits=t,this.valueMask=(1<>>this.start;return i}encode(e){if("number"!=typeof e||!Number.isInteger(e)||e!==O(e&this.valueMask))throw TypeError(s("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);let t=this.container._packedGetValue(),n=O(e<n&&(n=this.length.decode(e,t)),n}decode(e,t=0){let n=this.span;return 0>n&&(n=this.length.decode(e,t)),o(e).slice(t,t+n)}encode(e,t,n){let r=this.length;if(this.length instanceof u&&(r=e.length),!(e instanceof Uint8Array&&r===e.length))throw TypeError(s("Blob.encode",this)+" requires (length "+r+") Uint8Array as src");if(n+r>t.length)throw RangeError("encoding overruns Uint8Array");let i=o(e);return o(t).write(i.toString("hex"),n,r,"hex"),this.length instanceof u&&this.length.encode(r,t,n),r}}t.t6=L;class N extends a{constructor(e){super(-1,e)}getSpan(e,t=0){i(e);let n=t;for(;nt.length)throw RangeError("encoding overruns Buffer");let s=o(t);return i.copy(s,n),s[n+a]=0,a+1}}class D extends a{constructor(e,t){if("string"==typeof e&&void 0===t&&(t=e,e=void 0),void 0===e)e=-1;else if(!Number.isInteger(e))throw TypeError("maxSpan must be an integer");super(-1,t),this.maxSpan=e}getSpan(e,t=0){return i(e),e.length-t}decode(e,t=0){let n=this.getSpan(e,t);if(0<=this.maxSpan&&this.maxSpant.length)throw RangeError("encoding overruns Buffer");return i.copy(o(t),n),a}}t._H=(e,t)=>new l(e,t),t.cv=(e,t,n)=>new c(e,t,n),t.u8=e=>new d(1,e),t.KB=e=>new d(2,e),t.Vb=e=>new d(3,e),t.Jq=e=>new d(4,e),t.ut=e=>new d(5,e),t.aq=e=>new d(6,e),t._O=e=>new y(e),t.Lb=e=>new p(2,e),t.b7=e=>new p(3,e),t.Gj=e=>new p(4,e),t.qY=e=>new p(5,e),t.hn=e=>new p(6,e),t.$r=e=>new b(e),t.s8=e=>new f(1,e),t.Tl=e=>new f(2,e),t.aQ=e=>new f(3,e),t.Xo=e=>new f(4,e),t._n=e=>new f(5,e),t.Yt=e=>new f(6,e),t.gM=e=>new _(e),t.xP=e=>new h(2,e),t.O9=e=>new h(3,e),t.u=e=>new h(4,e),t.IS=e=>new h(5,e),t.hO=e=>new h(6,e),t.LN=e=>new v(e),t.xn=e=>new w(e),t.WZ=e=>new k(e),t.eh=e=>new x(e),t.Mn=e=>new A(e),t.n_=(e,t,n)=>new I(e,t,n),t.pc=(e,t,n)=>new B(e,t,n),t.A9=(e,t,n)=>new S(e,t,n),t.G0=(e,t,n)=>new P(e,t,n),t.K_=(e,t)=>new E(e,t),t.Ik=(e,t)=>new L(e,t),t.ZZ=e=>new N(e),t.KA=(e,t)=>new D(e,t)},79127:function(e,t,n){"use strict";n.d(t,{Gd:function(){return s},H_:function(){return i},_u:function(){return a},nA:function(){return o}});var r=n(64174);let i=new r.nh("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),o=new r.nh("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"),a=new r.nh("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"),s=new r.nh("So11111111111111111111111111111111111111112");new r.nh("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP")},83304:function(e,t,n){"use strict";n.d(t,{lZ:function(){return u},p0:function(){return s}});var r,i,o=n(39386),a=n(93066);n(48764).Buffer,(r=i||(i={}))[r.Uninitialized=0]="Uninitialized",r[r.Initialized=1]="Initialized",r[r.Frozen=2]="Frozen";let s=(0,o.n_)([(0,a.ZL)("mint"),(0,a.ZL)("owner"),(0,a.AW)("amount"),(0,o.Jq)("delegateOption"),(0,a.ZL)("delegate"),(0,o.u8)("state"),(0,o.Jq)("isNativeOption"),(0,a.AW)("isNative"),(0,a.AW)("delegatedAmount"),(0,o.Jq)("closeAuthorityOption"),(0,a.ZL)("closeAuthority")]),u=s.span},26224:function(e,t,n){"use strict";n.d(t,{Bl:function(){return v},qT:function(){return _},MO:function(){return k},rs:function(){return w}});var r,i,o=n(39386),a=n(93066),s=n(64174),u=n(79127);class l extends Error{constructor(e){super(e)}}class c extends l{constructor(){super(...arguments),this.name="TokenAccountNotFoundError"}}class d extends l{constructor(){super(...arguments),this.name="TokenInvalidAccountOwnerError"}}class p extends l{constructor(){super(...arguments),this.name="TokenInvalidAccountSizeError"}}class f extends l{constructor(){super(...arguments),this.name="TokenInvalidMintError"}}class h extends l{constructor(){super(...arguments),this.name="TokenOwnerOffCurveError"}}(r=i||(i={}))[r.Uninitialized=0]="Uninitialized",r[r.Mint=1]="Mint",r[r.Account=2]="Account";var m=n(83304);let g=(0,o.n_)([(0,o.u8)("m"),(0,o.u8)("n"),(0,a.Xg)("isInitialized"),(0,a.ZL)("signer1"),(0,a.ZL)("signer2"),(0,a.ZL)("signer3"),(0,a.ZL)("signer4"),(0,a.ZL)("signer5"),(0,a.ZL)("signer6"),(0,a.ZL)("signer7"),(0,a.ZL)("signer8"),(0,a.ZL)("signer9"),(0,a.ZL)("signer10"),(0,a.ZL)("signer11")]),y=g.span;var b=n(48764).Buffer;let _=(0,o.n_)([(0,o.Jq)("mintAuthorityOption"),(0,a.ZL)("mintAuthority"),(0,a.AW)("supply"),(0,o.u8)("decimals"),(0,a.Xg)("isInitialized"),(0,o.Jq)("freezeAuthorityOption"),(0,a.ZL)("freezeAuthority")]),v=_.span;function w(e,t,n=u.H_){if(!t)throw new c;if(!t.owner.equals(n))throw new d;if(t.data.lengthv){if(t.data.length<=m.lZ||t.data.length===y)throw new p;if(t.data[m.lZ]!=i.Mint)throw new f;o=t.data.slice(m.lZ+1)}return{address:e,mintAuthority:r.mintAuthorityOption?r.mintAuthority:null,supply:r.supply,decimals:r.decimals,isInitialized:r.isInitialized,freezeAuthority:r.freezeAuthorityOption?r.freezeAuthority:null,tlvData:o}}function k(e,t,n=!1,r=u.H_,i=u._u){if(!n&&!s.nh.isOnCurve(t.toBuffer()))throw new h;let[o]=s.nh.findProgramAddressSync([t.toBuffer(),r.toBuffer(),e.toBuffer()],i);return o}},64174:function(e,t,n){"use strict";n.d(t,{gw:function(){return nX},Lb:function(){return iB},ew:function(){return iP},RG:function(){return iC},nh:function(){return nn},Am:function(){return nI},ze:function(){return nE},yc:function(){return nz},YW:function(){return nx},Sl:function(){return nk},$Z:function(){return nA},GS:function(){return nS},Wf:function(){return iK},BV:function(){return nB}});var r,i,o={};n.r(o),n.d(o,{aInRange:function(){return Z},abool:function(){return C},abytes:function(){return P},bitGet:function(){return X},bitLen:function(){return Y},bitMask:function(){return J},bitSet:function(){return Q},bytesToHex:function(){return B},bytesToNumberBE:function(){return F},bytesToNumberLE:function(){return q},concatBytes:function(){return W},createHmacDrbg:function(){return en},ensureBytes:function(){return V},equalBytes:function(){return $},hexToBytes:function(){return D},hexToNumber:function(){return R},inRange:function(){return G},isBytes:function(){return E},memoized:function(){return ea},notImplemented:function(){return eo},numberToBytesBE:function(){return j},numberToBytesLE:function(){return U},numberToHexUnpadded:function(){return M},numberToVarBytesBE:function(){return z},utf8ToBytes:function(){return K},validateObject:function(){return ei}});var a=n(48764),s=n(12785);let u=BigInt(4294967296-1),l=BigInt(32);function c(e,t=!1){return t?{h:Number(e&u),l:Number(e>>l&u)}:{h:0|Number(e>>l&u),l:0|Number(e&u)}}function d(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;iBigInt(e>>>0)<>>0),f=(e,t,n)=>e<>>32-n,h=(e,t,n)=>t<>>32-n,m=(e,t,n)=>t<>>64-n,g=(e,t,n)=>e<>>64-n;var y={fromBig:c,split:d,toBig:p,shrSH:(e,t,n)=>e>>>n,shrSL:(e,t,n)=>e<<32-n|t>>>n,rotrSH:(e,t,n)=>e>>>n|t<<32-n,rotrSL:(e,t,n)=>e<<32-n|t>>>n,rotrBH:(e,t,n)=>e<<64-n|t>>>n-32,rotrBL:(e,t,n)=>e>>>n-32|t<<64-n,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:f,rotlSL:h,rotlBH:m,rotlBL:g,add:function(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/4294967296|0)|0,l:0|i}},add3L:(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),add3H:(e,t,n,r)=>t+n+r+(e/4294967296|0)|0,add4L:(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),add4H:(e,t,n,r,i)=>t+n+r+i+(e/4294967296|0)|0,add5H:(e,t,n,r,i,o)=>t+n+r+i+o+(e/4294967296|0)|0,add5L:(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0)},b=n(40963);let[_,v]=y.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),w=new Uint32Array(80),k=new Uint32Array(80);class x extends s.VR{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:o,Dh:a,Dl:s,Eh:u,El:l,Fh:c,Fl:d,Gh:p,Gl:f,Hh:h,Hl:m}=this;return[e,t,n,r,i,o,a,s,u,l,c,d,p,f,h,m]}set(e,t,n,r,i,o,a,s,u,l,c,d,p,f,h,m){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|o,this.Dh=0|a,this.Dl=0|s,this.Eh=0|u,this.El=0|l,this.Fh=0|c,this.Fl=0|d,this.Gh=0|p,this.Gl=0|f,this.Hh=0|h,this.Hl=0|m}process(e,t){for(let n=0;n<16;n++,t+=4)w[n]=e.getUint32(t),k[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=0|w[e-15],n=0|k[e-15],r=y.rotrSH(t,n,1)^y.rotrSH(t,n,8)^y.shrSH(t,n,7),i=y.rotrSL(t,n,1)^y.rotrSL(t,n,8)^y.shrSL(t,n,7),o=0|w[e-2],a=0|k[e-2],s=y.rotrSH(o,a,19)^y.rotrBH(o,a,61)^y.shrSH(o,a,6),u=y.rotrSL(o,a,19)^y.rotrBL(o,a,61)^y.shrSL(o,a,6),l=y.add4L(i,u,k[e-7],k[e-16]),c=y.add4H(l,r,s,w[e-7],w[e-16]);w[e]=0|c,k[e]=0|l}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:a,Cl:s,Dh:u,Dl:l,Eh:c,El:d,Fh:p,Fl:f,Gh:h,Gl:m,Hh:g,Hl:b}=this;for(let e=0;e<80;e++){let t=y.rotrSH(c,d,14)^y.rotrSH(c,d,18)^y.rotrBH(c,d,41),x=y.rotrSL(c,d,14)^y.rotrSL(c,d,18)^y.rotrBL(c,d,41),A=c&p^~c&h,S=d&f^~d&m,I=y.add5L(b,x,S,v[e],k[e]),T=y.add5H(I,g,t,A,_[e],w[e]),E=0|I,P=y.rotrSH(n,r,28)^y.rotrBH(n,r,34)^y.rotrBH(n,r,39),C=y.rotrSL(n,r,28)^y.rotrBL(n,r,34)^y.rotrBL(n,r,39),O=n&i^n&a^i&a,B=r&o^r&s^o&s;g=0|h,b=0|m,h=0|p,m=0|f,p=0|c,f=0|d,({h:c,l:d}=y.add(0|u,0|l,0|T,0|E)),u=0|a,l=0|s,a=0|i,s=0|o,i=0|n,o=0|r;let M=y.add3L(E,C,B);n=y.add3H(M,T,P,O),r=0|M}({h:n,l:r}=y.add(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:o}=y.add(0|this.Bh,0|this.Bl,0|i,0|o)),({h:a,l:s}=y.add(0|this.Ch,0|this.Cl,0|a,0|s)),({h:u,l:l}=y.add(0|this.Dh,0|this.Dl,0|u,0|l)),({h:c,l:d}=y.add(0|this.Eh,0|this.El,0|c,0|d)),({h:p,l:f}=y.add(0|this.Fh,0|this.Fl,0|p,0|f)),({h:h,l:m}=y.add(0|this.Gh,0|this.Gl,0|h,0|m)),({h:g,l:b}=y.add(0|this.Hh,0|this.Hl,0|g,0|b)),this.set(n,r,i,o,a,s,u,l,c,d,p,f,h,m,g,b)}roundClean(){w.fill(0),k.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}let A=(0,b.hE)(()=>new x),S=BigInt(0),I=BigInt(1),T=BigInt(2);function E(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function P(e){if(!E(e))throw Error("Uint8Array expected")}function C(e,t){if("boolean"!=typeof t)throw Error(`${e} must be valid boolean, got "${t}".`)}let O=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function B(e){P(e);let t="";for(let n=0;n=L._0&&e<=L._9?e-L._0:e>=L._A&&e<=L._F?e-(L._A-10):e>=L._a&&e<=L._f?e-(L._a-10):void 0}function D(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);let t=e.length,n=t/2;if(t%2)throw Error("padded hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let t=0,i=0;t"bigint"==typeof e&&S<=e;function G(e,t,n){return H(e)&&H(t)&&H(n)&&t<=e&&eS;e>>=I,t+=1);return t}function X(e,t){return e>>BigInt(t)&I}function Q(e,t,n){return e|(n?I:S)<(T<new Uint8Array(e),et=e=>Uint8Array.from(e);function en(e,t,n){if("number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");if("function"!=typeof n)throw Error("hmacFn must be a function");let r=ee(e),i=ee(e),o=0,a=()=>{r.fill(1),i.fill(0),o=0},s=(...e)=>n(i,r,...e),u=(e=ee())=>{i=s(et([0]),e),r=s(),0!==e.length&&(i=s(et([1]),e),r=s())},l=()=>{if(o++>=1e3)throw Error("drbg: tried 1000 values");let e=0,n=[];for(;e{let n;for(a(),u(e);!(n=t(l()));)u();return a(),n};return c}let er={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||E(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function ei(e,t,n={}){let r=(t,n,r)=>{let i=er[n];if("function"!=typeof i)throw Error(`Invalid validator "${n}", expected function`);let o=e[t];if((!r||void 0!==o)&&!i(o,e))throw Error(`Invalid param ${String(t)}=${o} (${typeof o}), expected ${n}`)};for(let[e,n]of Object.entries(t))r(e,n,!1);for(let[e,t]of Object.entries(n))r(e,t,!0);return e}let eo=()=>{throw Error("not implemented")};function ea(e){let t=new WeakMap;return(n,...r)=>{let i=t.get(n);if(void 0!==i)return i;let o=e(n,...r);return t.set(n,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */let es=BigInt(0),eu=BigInt(1),el=BigInt(2),ec=BigInt(3),ed=BigInt(4),ep=BigInt(5),ef=BigInt(8);function eh(e,t){let n=e%t;return n>=es?n:t+n}function em(e,t,n){let r=e;for(;t-- >es;)r*=r,r%=n;return r}function eg(e,t){if(e===es||t<=es)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let n=eh(e,t),r=t,i=es,o=eu,a=eu,s=es;for(;n!==es;){let e=r/n,t=r%n,u=i-a*e,l=o-s*e;r=n,n=t,i=a,o=s,a=u,s=l}let u=r;if(u!==eu)throw Error("invert: does not exist");return eh(i,t)}BigInt(9),BigInt(16);let ey=(e,t)=>(eh(e,t)&eu)===eu,eb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function e_(e,t){let n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function ev(e,t,n=!1,r={}){if(e<=es)throw Error(`Expected Field ORDER > 0, got ${e}`);let{nBitLength:i,nByteLength:o}=e_(e,t);if(o>2048)throw Error("Field lengths over 2048 bytes are not supported");let a=function(e){if(e%ed===ec){let t=(e+eu)/ed;return function(e,n){let r=e.pow(n,t);if(!e.eql(e.sqr(r),n))throw Error("Cannot find square root");return r}}if(e%ef===ep){let t=(e-ep)/ef;return function(e,n){let r=e.mul(n,el),i=e.pow(r,t),o=e.mul(n,i),a=e.mul(e.mul(o,el),i),s=e.mul(o,e.sub(a,e.ONE));if(!e.eql(e.sqr(s),n))throw Error("Cannot find square root");return s}}return function(e){let t,n,r;let i=(e-eu)/el;for(t=e-eu,n=0;t%el===es;t/=el,n++);for(r=el;r 0");if(n===eu)return es;let r=eu;for(;t>es;)t&eu&&(r=r*e%n),e=e*e%n,t>>=eu;return r}(r,i,e)!==e-eu;r++);if(1===n){let t=(e+eu)/ed;return function(e,n){let r=e.pow(n,t);if(!e.eql(e.sqr(r),n))throw Error("Cannot find square root");return r}}let o=(t+eu)/el;return function(e,a){if(e.pow(a,i)===e.neg(e.ONE))throw Error("Cannot find square root");let s=n,u=e.pow(e.mul(e.ONE,r),t),l=e.pow(a,o),c=e.pow(a,t);for(;!e.eql(c,e.ONE);){if(e.eql(c,e.ZERO))return e.ZERO;let t=1;for(let n=e.sqr(c);teh(t,e),isValid:t=>{if("bigint"!=typeof t)throw Error(`Invalid field element: expected bigint, got ${typeof t}`);return es<=t&&te===es,isOdd:e=>(e&eu)===eu,neg:t=>eh(-t,e),eql:(e,t)=>e===t,sqr:t=>eh(t*t,e),add:(t,n)=>eh(t+n,e),sub:(t,n)=>eh(t-n,e),mul:(t,n)=>eh(t*n,e),pow:(e,t)=>(function(e,t,n){if(n 0");if(n===es)return e.ONE;if(n===eu)return t;let r=e.ONE,i=t;for(;n>es;)n&eu&&(r=e.mul(r,i)),i=e.sqr(i),n>>=eu;return r})(s,e,t),div:(t,n)=>eh(t*eg(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>eg(t,e),sqrt:r.sqrt||(e=>a(s,e)),invertBatch:e=>(function(e,t){let n=Array(t.length),r=t.reduce((t,r,i)=>e.is0(r)?t:(n[i]=t,e.mul(t,r)),e.ONE),i=e.inv(r);return t.reduceRight((t,r,i)=>e.is0(r)?t:(n[i]=e.mul(t,n[i]),e.mul(t,r)),i),n})(s,e),cmov:(e,t,n)=>n?t:e,toBytes:e=>n?U(e,o):j(e,o),fromBytes:e=>{if(e.length!==o)throw Error(`Fp.fromBytes: expected ${o}, got ${e.length}`);return n?q(e):F(e)}});return Object.freeze(s)}function ew(e){if("bigint"!=typeof e)throw Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function ek(e){let t=ew(e);return t+Math.ceil(t/2)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */let ex=BigInt(0),eA=BigInt(1),eS=new WeakMap,eI=new WeakMap;function eT(e,t){let n=(e,t)=>{let n=t.negate();return e?n:t},r=e=>{if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`Wrong window size=${e}, should be [1..${t}]`)},i=e=>(r(e),{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)});return{constTimeNegate:n,unsafeLadder(t,n){let r=e.ZERO,i=t;for(;n>ex;)n&eA&&(r=r.add(i)),i=i.double(),n>>=eA;return r},precomputeWindow(e,t){let{windows:n,windowSize:r}=i(t),o=[],a=e,s=a;for(let e=0;e>=p,i>s&&(i-=d,o+=eA);let a=t+Math.abs(i)-1,f=e%2!=0,h=i<0;0===i?l=l.add(n(f,r[t])):u=u.add(n(h,r[a]))}return{p:u,f:l}},wNAFCached(e,t,n){let r=eI.get(e)||1,i=eS.get(e);return i||(i=this.precomputeWindow(e,r),1!==r&&eS.set(e,n(i))),this.wNAF(r,i,t)},setWindowSize(e,t){r(t),eI.set(e,t),eS.delete(e)}}}function eE(e){return!function(e){let t=eb.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});ei(e,t)}(e.Fp),ei(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...e_(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */let eP=BigInt(0),eC=BigInt(1),eO=BigInt(2),eB=BigInt(8),eM={zip215:!0},eR=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),eL=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),eN=BigInt(0),eD=BigInt(1),eF=BigInt(2);BigInt(3);let eq=BigInt(5),ej=BigInt(8);function eU(e,t){let n=eh(t*t*t,eR),r=eh(n*n*t,eR),i=function(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),o=e*e%eR*e%eR,a=em(o,eF,eR)*o%eR,s=em(a,eD,eR)*e%eR,u=em(s,eq,eR)*s%eR,l=em(u,t,eR)*u%eR,c=em(l,n,eR)*l%eR,d=em(c,r,eR)*c%eR,p=em(d,i,eR)*d%eR,f=em(p,i,eR)*d%eR,h=em(f,t,eR)*u%eR,m=em(h,eF,eR)*e%eR;return{pow_p_5_8:m,b2:o}}(e*r).pow_p_5_8,o=eh(e*n*i,eR),a=eh(t*o*o,eR),s=o,u=eh(o*eL,eR),l=a===e,c=a===eh(-e,eR),d=a===eh(-e*eL,eR);return l&&(o=s),(c||d)&&(o=u),ey(o,eR)&&(o=eh(-o,eR)),{isValid:l||c,value:o}}let ez=ev(eR,void 0,!0),eV={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:ez,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:ej,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:A,randomBytes:b.O6,adjustScalarBytes:function(e){return e[0]&=248,e[31]&=127,e[31]|=64,e},uvRatio:eU},eW=function(e){let t=function(e){let t=eE(e);return ei(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:n,n:r,prehash:i,hash:o,randomBytes:a,nByteLength:s,h:u}=t,l=eO<{try{return{isValid:!0,value:n.sqrt(e*n.inv(t))}}catch(e){return{isValid:!1,value:eP}}}),p=t.adjustScalarBytes||(e=>e),f=t.domain||((e,t,n)=>{if(C("phflag",n),t.length||n)throw Error("Contexts/pre-hash are not supported");return e});function h(e,t){Z("coordinate "+e,t,eP,l)}function m(e){if(!(e instanceof b))throw Error("ExtendedPoint expected")}let g=ea((e,t)=>{let{ex:r,ey:i,ez:o}=e,a=e.is0();null==t&&(t=a?eB:n.inv(o));let s=c(r*t),u=c(i*t),l=c(o*t);if(a)return{x:eP,y:eC};if(l!==eC)throw Error("invZ was invalid");return{x:s,y:u}}),y=ea(e=>{let{a:n,d:r}=t;if(e.is0())throw Error("bad point: ZERO");let{ex:i,ey:o,ez:a,et:s}=e,u=c(i*i),l=c(o*o),d=c(a*a),p=c(d*d),f=c(u*n),h=c(d*c(f+l)),m=c(p+c(r*c(u*l)));if(h!==m)throw Error("bad point: equation left != right (1)");let g=c(i*o),y=c(a*s);if(g!==y)throw Error("bad point: equation left != right (2)");return!0});class b{constructor(e,t,n,r){this.ex=e,this.ey=t,this.ez=n,this.et=r,h("x",e),h("y",t),h("z",n),h("t",r),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof b)throw Error("extended point not allowed");let{x:t,y:n}=e||{};return h("x",t),h("y",n),new b(t,n,eC,c(t*n))}static normalizeZ(e){let t=n.invertBatch(e.map(e=>e.ez));return e.map((e,n)=>e.toAffine(t[n])).map(b.fromAffine)}_setWindowSize(e){w.setWindowSize(this,e)}assertValidity(){y(this)}equals(e){m(e);let{ex:t,ey:n,ez:r}=this,{ex:i,ey:o,ez:a}=e,s=c(t*a),u=c(i*r),l=c(n*a),d=c(o*r);return s===u&&l===d}is0(){return this.equals(b.ZERO)}negate(){return new b(c(-this.ex),this.ey,this.ez,c(-this.et))}double(){let{a:e}=t,{ex:n,ey:r,ez:i}=this,o=c(n*n),a=c(r*r),s=c(eO*c(i*i)),u=c(e*o),l=n+r,d=c(c(l*l)-o-a),p=u+a,f=p-s,h=u-a,m=c(d*f),g=c(p*h),y=c(d*h),_=c(f*p);return new b(m,g,_,y)}add(e){m(e);let{a:n,d:r}=t,{ex:i,ey:o,ez:a,et:s}=this,{ex:u,ey:l,ez:d,et:p}=e;if(n===BigInt(-1)){let e=c((o-i)*(l+u)),t=c((o+i)*(l-u)),n=c(t-e);if(n===eP)return this.double();let r=c(a*eO*p),f=c(s*eO*d),h=f+r,m=t+e,g=f-r,y=c(h*n),_=c(m*g),v=c(h*g),w=c(n*m);return new b(y,_,w,v)}let f=c(i*u),h=c(o*l),g=c(s*r*p),y=c(a*d),_=c((i+o)*(u+l)-f-h),v=y-g,w=y+g,k=c(h-n*f),x=c(_*v),A=c(w*k),S=c(_*k),I=c(v*w);return new b(x,A,I,S)}subtract(e){return this.add(e.negate())}wNAF(e){return w.wNAFCached(this,e,b.normalizeZ)}multiply(e){Z("scalar",e,eC,r);let{p:t,f:n}=this.wNAF(e);return b.normalizeZ([t,n])[0]}multiplyUnsafe(e){return(Z("scalar",e,eP,r),e===eP)?v:this.equals(v)||e===eC?this:this.equals(_)?this.wNAF(e).p:w.unsafeLadder(this,e)}isSmallOrder(){return this.multiplyUnsafe(u).is0()}isTorsionFree(){return w.unsafeLadder(this,r).is0()}toAffine(e){return g(this,e)}clearCofactor(){let{h:e}=t;return e===eC?this:this.multiplyUnsafe(e)}static fromHex(e,r=!1){let{d:i,a:o}=t,a=n.BYTES;e=V("pointHex",e,a),C("zip215",r);let s=e.slice(),u=e[a-1];s[a-1]=-129&u;let p=q(s),f=r?l:n.ORDER;Z("pointHex.y",p,eP,f);let h=c(p*p),m=c(h-eC),g=c(i*h-o),{isValid:y,value:_}=d(m,g);if(!y)throw Error("Point.fromHex: invalid y coordinate");let v=(_&eC)===eC,w=(128&u)!=0;if(!r&&_===eP&&w)throw Error("Point.fromHex: x=0 and x_0=1");return w!==v&&(_=c(-_)),b.fromAffine({x:_,y:p})}static fromPrivateKey(e){return k(e).point}toRawBytes(){let{x:e,y:t}=this.toAffine(),r=U(t,n.BYTES);return r[r.length-1]|=e&eC?128:0,r}toHex(){return B(this.toRawBytes())}}b.BASE=new b(t.Gx,t.Gy,eC,c(t.Gx*t.Gy)),b.ZERO=new b(eP,eC,eC,eP);let{BASE:_,ZERO:v}=b,w=eT(b,8*s);function k(e){e=V("private key",e,s);let t=V("hashed private key",o(e),2*s),n=p(t.slice(0,s)),i=t.slice(s,2*s),a=eh(q(n),r),u=_.multiply(a),l=u.toRawBytes();return{head:n,prefix:i,scalar:a,point:u,pointBytes:l}}function x(e=new Uint8Array,...t){let n=W(...t);return eh(q(o(f(n,V("context",e),!!i))),r)}return _._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return k(e).pointBytes},sign:function(e,t,o={}){e=V("message",e),i&&(e=i(e));let{prefix:a,scalar:u,pointBytes:l}=k(t),c=x(o.context,a,e),d=_.multiply(c).toRawBytes(),p=x(o.context,d,l,e),f=eh(c+p*u,r);Z("signature.s",f,eP,r);let h=W(d,U(f,n.BYTES));return V("result",h,2*s)},verify:function(e,t,r,o=eM){let a,s,u;let{context:l,zip215:c}=o,d=n.BYTES;e=V("signature",e,2*d),t=V("message",t),void 0!==c&&C("zip215",c),i&&(t=i(t));let p=q(e.slice(d,2*d));try{a=b.fromHex(r,c),s=b.fromHex(e.slice(0,d),c),u=_.multiplyUnsafe(p)}catch(e){return!1}if(!c&&a.isSmallOrder())return!1;let f=x(l,s.toRawBytes(),a.toRawBytes(),t),h=s.add(a.multiplyUnsafe(f));return h.subtract(u).clearCofactor().equals(b.ZERO)},ExtendedPoint:b,utils:{getExtendedPublicKey:k,randomPrivateKey:()=>a(n.BYTES),precompute:(e=8,t=b.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}(eV);function e$(e){if(!(e instanceof eZ))throw Error("RistrettoPoint expected")}let eK=e=>eU(eD,e),eH=e=>eW.CURVE.Fp.create(null&bytesToNumberLE(e));function eG(e){let{d:t}=eW.CURVE,n=eW.CURVE.Fp.ORDER,r=eW.CURVE.Fp.create,i=r(null*e*e),o=r((i+eD)*null),a=BigInt(-1),s=r((a-t*i)*r(i+t)),{isValid:u,value:l}=eU(o,s),c=r(l*e);isNegativeLE(c,n)||(c=r(-c)),u||(l=c),u||(a=i);let d=r(a*(i-eD)*null-s),p=l*l,f=r((l+l)*s),h=r(null*d),m=r(eD-p),g=r(eD+p);return new eW.ExtendedPoint(r(f*g),r(m*h),r(h*g),r(f*m))}class eZ{constructor(e){this.ep=e}static fromAffine(e){return new eZ(eW.ExtendedPoint.fromAffine(e))}static hashToCurve(e){e=ensureBytes("ristrettoHash",e,64);let t=eH(e.slice(0,32)),n=eG(t),r=eH(e.slice(32,64)),i=eG(r);return new eZ(n.add(i))}static fromHex(e){e=ensureBytes("ristrettoHex",e,32);let{a:t,d:n}=eW.CURVE,r=eW.CURVE.Fp.ORDER,i=eW.CURVE.Fp.create,o="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",a=eH(e);if(!equalBytes(numberToBytesLE(a,32),e)||isNegativeLE(a,r))throw Error(o);let s=i(a*a),u=i(eD+t*s),l=i(eD-t*s),c=i(u*u),d=i(l*l),p=i(t*n*c-d),{isValid:f,value:h}=eK(i(p*d)),m=i(h*l),g=i(h*m*p),y=i((a+a)*m);isNegativeLE(y,r)&&(y=i(-y));let b=i(u*g),_=i(y*b);if(!f||isNegativeLE(_,r)||b===eN)throw Error(o);return new eZ(new eW.ExtendedPoint(y,b,eD,_))}toRawBytes(){let e,{ex:t,ey:n,ez:r,et:i}=this.ep,o=eW.CURVE.Fp.ORDER,a=eW.CURVE.Fp.create,s=a(a(r+n)*a(r-n)),u=a(t*n),l=a(u*u),{value:c}=eK(a(s*l)),d=a(c*s),p=a(c*u),f=a(d*p*i);if(isNegativeLE(i*f,o)){let r=a(null*n),i=a(null*t);t=r,n=i,e=a(null*d)}else e=p;isNegativeLE(t*f,o)&&(n=a(-n));let h=a((r-n)*e);return isNegativeLE(h,o)&&(h=a(-h)),numberToBytesLE(h,32)}toHex(){return bytesToHex(this.toRawBytes())}toString(){return this.toHex()}equals(e){e$(e);let{ex:t,ey:n}=this.ep,{ex:r,ey:i}=e.ep,o=eW.CURVE.Fp.create,a=o(t*i)===o(n*r),s=o(n*i)===o(t*r);return a||s}add(e){return e$(e),new eZ(this.ep.add(e.ep))}subtract(e){return e$(e),new eZ(this.ep.subtract(e.ep))}multiply(e){return new eZ(this.ep.multiply(e))}multiplyUnsafe(e){return new eZ(this.ep.multiplyUnsafe(e))}double(){return new eZ(this.ep.double())}negate(){return new eZ(this.ep.negate())}}var eY=n(13550),eX=n.n(eY),eQ=n(10011),eJ=n.n(eQ),e0=n(88281),e1=n(25532),e2=n(39386),e6=n(40475);class e3 extends TypeError{constructor(e,t){let n;let{message:r,explanation:i,...o}=e,{path:a}=e,s=0===a.length?r:`At path: ${a.join(".")} -- ${r}`;super(i??s),null!=i&&(this.cause=s),Object.assign(this,o),this.name=this.constructor.name,this.failures=()=>n??(n=[e,...t()])}}function e4(e){return"object"==typeof e&&null!=e}function e5(e){return e4(e)&&!Array.isArray(e)}function e8(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function*e9(e,t,n,r){var i;for(let o of(e4(i=e)&&"function"==typeof i[Symbol.iterator]||(e=[e]),e)){let e=function(e,t,n,r){if(!0===e)return;!1===e?e={}:"string"==typeof e&&(e={message:e});let{path:i,branch:o}=t,{type:a}=n,{refinement:s,message:u=`Expected a value of type \`${a}\`${s?` with refinement \`${s}\``:""}, but received: \`${e8(r)}\``}=e;return{value:r,type:a,refinement:s,key:i[i.length-1],path:i,branch:o,...e,message:u}}(o,t,n,r);e&&(yield e)}}function*e7(e,t,n={}){let{path:r=[],branch:i=[e],coerce:o=!1,mask:a=!1}=n,s={path:r,branch:i,mask:a};o&&(e=t.coercer(e,s));let u="valid";for(let r of t.validator(e,s))r.explanation=n.message,u="not_valid",yield[r,void 0];for(let[l,c,d]of t.entries(e,s)){let t=e7(c,d,{path:void 0===l?r:[...r,l],branch:void 0===l?i:[...i,c],coerce:o,mask:a,message:n.message});for(let n of t)n[0]?(u=null!=n[0].refinement?"not_refined":"not_valid",yield[n[0],void 0]):o&&(c=n[1],void 0===l?e=c:e instanceof Map?e.set(l,c):e instanceof Set?e.add(c):e4(e)&&(void 0!==c||l in e)&&(e[l]=c))}if("not_valid"!==u)for(let r of t.refiner(e,s))r.explanation=n.message,u="not_refined",yield[r,void 0];"valid"===u&&(yield[void 0,e])}class te{constructor(e){let{type:t,schema:n,validator:r,refiner:i,coercer:o=e=>e,entries:a=function*(){}}=e;this.type=t,this.schema=n,this.entries=a,this.coercer=o,r?this.validator=(e,t)=>{let n=r(e,t);return e9(n,t,this,e)}:this.validator=()=>[],i?this.refiner=(e,t)=>{let n=i(e,t);return e9(n,t,this,e)}:this.refiner=()=>[]}assert(e,t){return function(e,t,n){let r=tr(e,t,{message:n});if(r[0])throw r[0]}(e,this,t)}create(e,t){return tt(e,this,t)}is(e){return tn(e,this)}mask(e,t){return function(e,t,n){let r=tr(e,t,{coerce:!0,mask:!0,message:n});if(!r[0])return r[1];throw r[0]}(e,this,t)}validate(e,t={}){return tr(e,this,t)}}function tt(e,t,n){let r=tr(e,t,{coerce:!0,message:n});if(!r[0])return r[1];throw r[0]}function tn(e,t){let n=tr(e,t);return!n[0]}function tr(e,t,n={}){let r=e7(e,t,n),i=function(e){let{done:t,value:n}=e.next();return t?void 0:n}(r);if(i[0]){let e=new e3(i[0],function*(){for(let e of r)e[0]&&(yield e[0])});return[e,void 0]}{let e=i[1];return[void 0,e]}}function ti(e,t){return new te({type:e,schema:null,validator:t})}function to(e){return new te({type:"array",schema:e,*entries(t){if(e&&Array.isArray(t))for(let[n,r]of t.entries())yield[n,r,e]},coercer:e=>Array.isArray(e)?e.slice():e,validator:e=>Array.isArray(e)||`Expected an array value, but received: ${e8(e)}`})}function ta(){return ti("boolean",e=>"boolean"==typeof e)}function ts(e){return ti("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${e8(t)}`)}function tu(e){let t=e8(e),n=typeof e;return new te({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${e8(n)}`})}function tl(e){return new te({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function tc(){return ti("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${e8(e)}`)}function td(e){return new te({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function tp(e,t){return new te({type:"record",schema:null,*entries(n){if(e4(n))for(let r in n){let i=n[r];yield[r,r,e],yield[r,i,t]}},validator:e=>e5(e)||`Expected an object, but received: ${e8(e)}`,coercer:e=>e5(e)?{...e}:e})}function tf(){return ti("string",e=>"string"==typeof e||`Expected a string, but received: ${e8(e)}`)}function th(e){let t=ti("never",()=>!1);return new te({type:"tuple",schema:null,*entries(n){if(Array.isArray(n)){let r=Math.max(e.length,n.length);for(let i=0;iArray.isArray(e)||`Expected an array, but received: ${e8(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function tm(e){let t=Object.keys(e);return new te({type:"type",schema:e,*entries(n){if(e4(n))for(let r of t)yield[r,n[r],e[r]]},validator:e=>e5(e)||`Expected an object, but received: ${e8(e)}`,coercer:e=>e5(e)?{...e}:e})}function tg(e){let t=e.map(e=>e.type).join(" | ");return new te({type:"union",schema:null,coercer(t,n){for(let r of e){let[e,i]=r.validate(t,{coerce:!0,mask:n.mask});if(!e)return i}return t},validator(n,r){let i=[];for(let t of e){let[...e]=e7(n,t,r),[o]=e;if(!o[0])return[];for(let[t]of e)t&&i.push(t)}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${e8(n)}`,...i]}})}function ty(){return ti("unknown",()=>!0)}function tb(e,t,n){return new te({...e,coercer:(r,i)=>tn(r,t)?e.coercer(n(r,i),i):e.coercer(r,i)})}var t_=n(31198),tv=n.n(t_),tw=n(64714),tk=class extends tw.v{socket;constructor(e,t,n){super(),this.socket=new window.WebSocket(e,n),this.socket.onopen=()=>this.emit("open"),this.socket.onmessage=e=>this.emit("message",e.data),this.socket.onerror=e=>this.emit("error",e),this.socket.onclose=e=>{this.emit("close",e.code,e.reason)}}send(e,t,n){let r=n||t;try{this.socket.send(e),r()}catch(e){r(e)}}close(e,t){this.socket.close(e,t)}addEventListener(e,t,n){this.socket.addEventListener(e,t,n)}},tx=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},tA=class extends tw.v{address;rpc_id;queue;options;autoconnect;ready;reconnect;reconnect_timer_id;reconnect_interval;max_reconnects;rest_options;current_reconnects;generate_request_id;socket;webSocketFactory;dataPack;constructor(e,t="ws://localhost:8080",{autoconnect:n=!0,reconnect:r=!0,reconnect_interval:i=1e3,max_reconnects:o=5,...a}={},s,u){super(),this.webSocketFactory=e,this.queue={},this.rpc_id=0,this.address=t,this.autoconnect=n,this.ready=!1,this.reconnect=r,this.reconnect_timer_id=void 0,this.reconnect_interval=i,this.max_reconnects=o,this.rest_options=a,this.current_reconnects=0,this.generate_request_id=s||(()=>++this.rpc_id),u?this.dataPack=u:this.dataPack=new tx,this.autoconnect&&this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}connect(){this.socket||this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}call(e,t,n,r){return r||"object"!=typeof n||(r=n,n=null),new Promise((i,o)=>{if(!this.ready)return o(Error("socket not ready"));let a=this.generate_request_id(e,t);this.socket.send(this.dataPack.encode({jsonrpc:"2.0",method:e,params:t||void 0,id:a}),r,e=>{if(e)return o(e);this.queue[a]={promise:[i,o]},n&&(this.queue[a].timeout=setTimeout(()=>{delete this.queue[a],o(Error("reply timeout"))},n))})})}async login(e){let t=await this.call("rpc.login",e);if(!t)throw Error("authentication failed");return t}async listMethods(){return await this.call("__listMethods")}notify(e,t){return new Promise((n,r)=>{if(!this.ready)return r(Error("socket not ready"));this.socket.send(this.dataPack.encode({jsonrpc:"2.0",method:e,params:t}),e=>{if(e)return r(e);n()})})}async subscribe(e){"string"==typeof e&&(e=[e]);let t=await this.call("rpc.on",e);if("string"==typeof e&&"ok"!==t[e])throw Error("Failed subscribing to an event '"+e+"' with: "+t[e]);return t}async unsubscribe(e){"string"==typeof e&&(e=[e]);let t=await this.call("rpc.off",e);if("string"==typeof e&&"ok"!==t[e])throw Error("Failed unsubscribing from an event with: "+t);return t}close(e,t){this.socket.close(e||1e3,t)}setAutoReconnect(e){this.reconnect=e}setReconnectInterval(e){this.reconnect_interval=e}setMaxReconnects(e){this.max_reconnects=e}_connect(e,t){clearTimeout(this.reconnect_timer_id),this.socket=this.webSocketFactory(e,t),this.socket.addEventListener("open",()=>{this.ready=!0,this.emit("open"),this.current_reconnects=0}),this.socket.addEventListener("message",({data:e})=>{e instanceof ArrayBuffer&&(e=a.Buffer.from(e).toString());try{e=this.dataPack.decode(e)}catch(e){return}if(e.notification&&this.listeners(e.notification).length){if(!Object.keys(e.params).length)return this.emit(e.notification);let t=[e.notification];if(e.params.constructor===Object)t.push(e.params);else for(let n=0;n{this.emit.apply(this,t)})}if(!this.queue[e.id])return e.method?Promise.resolve().then(()=>{this.emit(e.method,e?.params)}):void 0;"error"in e=="result"in e&&this.queue[e.id].promise[1](Error('Server response malformed. Response must include either "result" or "error", but not both.')),this.queue[e.id].timeout&&clearTimeout(this.queue[e.id].timeout),e.error?this.queue[e.id].promise[1](e.error):this.queue[e.id].promise[0](e.result),delete this.queue[e.id]}),this.socket.addEventListener("error",e=>this.emit("error",e)),this.socket.addEventListener("close",({code:n,reason:r})=>{this.ready&&setTimeout(()=>this.emit("close",n,r),0),this.ready=!1,this.socket=void 0,1e3!==n&&(this.current_reconnects++,this.reconnect&&(this.max_reconnects>this.current_reconnects||0===this.max_reconnects)&&(this.reconnect_timer_id=setTimeout(()=>this._connect(e,t),this.reconnect_interval)))})}},tS=n(77520);let tI=[],tT=[],tE=[],tP=BigInt(0),tC=BigInt(1),tO=BigInt(2),tB=BigInt(7),tM=BigInt(256),tR=BigInt(113);for(let e=0,t=tC,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],tI.push(2*(5*r+n)),tT.push((e+1)*(e+2)/2%64);let i=tP;for(let e=0;e<7;e++)(t=(t<>tB)*tR)%tM)&tO&&(i^=tC<<(tC<n>32?m(e,t,n):f(e,t,n),tF=(e,t,n)=>n>32?g(e,t,n):h(e,t,n);class tq extends b.kb{constructor(e,t,n,r=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,tS.Rx)(n),0>=this.blockLen||this.blockLen>=200)throw Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,b.Jq)(this.state)}keccak(){b.iA||(0,b.l1)(this.state32),function(e,t=24){let n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){let r=(t+8)%10,i=(t+2)%10,o=n[i],a=n[i+1],s=tD(o,a,1)^n[r],u=tF(o,a,1)^n[r+1];for(let n=0;n<50;n+=10)e[t+n]^=s,e[t+n+1]^=u}let t=e[2],i=e[3];for(let n=0;n<24;n++){let r=tT[n],o=tD(t,i,r),a=tF(t,i,r),s=tI[n];t=e[s],i=e[s+1],e[s]=o,e[s+1]=a}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)n[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~n[(r+2)%10]&n[(r+4)%10]}e[0]^=tL[r],e[1]^=tN[r]}n.fill(0)}(this.state32,this.rounds),b.iA||(0,b.l1)(this.state32),this.posOut=0,this.pos=0}update(e){(0,tS.Gg)(this);let{blockLen:t,state:n}=this;e=(0,b.O0)(e);let r=e.length;for(let i=0;i=n&&this.keccak();let o=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,tS.Rx)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,tS.J8)(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:t,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new tq(t,n,r,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}let tj=(0,b.hE)(()=>new tq(136,1,32));class tU extends b.kb{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,(0,tS.vp)(e);let n=(0,b.O0)(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let e=0;enew tU(e,t).update(n).digest();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function tV(e){void 0!==e.lowS&&C("lowS",e.lowS),void 0!==e.prehash&&C("prehash",e.prehash)}tz.create=(e,t)=>new tU(e,t);let{bytesToNumberBE:tW,hexToBytes:t$}=o,tK={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(e){let{Err:t}=tK;if(e.length<2||2!==e[0])throw new t("Invalid signature integer tag");let n=e[1],r=e.subarray(2,n+2);if(!n||r.length!==n)throw new t("Invalid signature integer: wrong length");if(128&r[0])throw new t("Invalid signature integer: negative");if(0===r[0]&&!(128&r[1]))throw new t("Invalid signature integer: unnecessary leading zero");return{d:tW(r),l:e.subarray(n+2)}},toSig(e){let{Err:t}=tK,n="string"==typeof e?t$(e):e;P(n);let r=n.length;if(r<2||48!=n[0])throw new t("Invalid signature tag");if(n[1]!==r-2)throw new t("Invalid signature: incorrect length");let{d:i,l:o}=tK._parseInt(n.subarray(2)),{d:a,l:s}=tK._parseInt(o);if(s.length)throw new t("Invalid signature: left bytes after parsing");return{r:i,s:a}},hexFromSig(e){let t=e=>8&Number.parseInt(e[0],16)?"00"+e:e,n=e=>{let t=e.toString(16);return 1&t.length?`0${t}`:t},r=t(n(e.s)),i=t(n(e.r)),o=r.length/2,a=i.length/2,s=n(o),u=n(a);return`30${n(a+o+4)}02${u}${i}02${s}${r}`}},tH=BigInt(0),tG=BigInt(1),tZ=(BigInt(2),BigInt(3));BigInt(4);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */let tY=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),tX=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),tQ=BigInt(1),tJ=BigInt(2),t0=(e,t)=>(e+t/tJ)/t,t1=ev(tY,void 0,void 0,{sqrt:function(e){let t=BigInt(3),n=BigInt(6),r=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),s=BigInt(88),u=e*e*e%tY,l=u*u*e%tY,c=em(l,t,tY)*l%tY,d=em(c,t,tY)*l%tY,p=em(d,tJ,tY)*u%tY,f=em(p,r,tY)*p%tY,h=em(f,i,tY)*f%tY,m=em(h,a,tY)*h%tY,g=em(m,s,tY)*m%tY,y=em(g,a,tY)*h%tY,b=em(y,t,tY)*l%tY,_=em(b,o,tY)*f%tY,v=em(_,n,tY)*u%tY,w=em(v,tJ,tY);if(!t1.eql(t1.sqr(w),e))throw Error("Cannot find square root");return w}}),t2=function(e,t){let n=t=>(function(e){let t=function(e){let t=eE(e);return ei(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:n,n:r}=t,i=n.BYTES+1,o=2*n.BYTES+1;function a(e){return eh(e,r)}let{ProjectivePoint:s,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:c}=function(e){let t=function(e){let t=eE(e);ei(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:n,Fp:r,a:i}=t;if(n){if(!r.eql(i,r.ZERO))throw Error("Endomorphism can only be defined for Koblitz curves that have a=0");if("object"!=typeof n||"bigint"!=typeof n.beta||"function"!=typeof n.splitScalar)throw Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:n}=t,r=t.toBytes||((e,t,r)=>{let i=t.toAffine();return W(Uint8Array.from([4]),n.toBytes(i.x),n.toBytes(i.y))}),i=t.fromBytes||(e=>{let t=e.subarray(1),r=n.fromBytes(t.subarray(0,n.BYTES)),i=n.fromBytes(t.subarray(n.BYTES,2*n.BYTES));return{x:r,y:i}});function o(e){let{a:r,b:i}=t,o=n.sqr(e),a=n.mul(o,e);return n.add(n.add(a,n.mul(e,r)),i)}if(!n.eql(n.sqr(t.Gy),o(t.Gx)))throw Error("bad generator point: equation left != right");function a(e){let n;let{allowedPrivateKeyLengths:r,nByteLength:i,wrapPrivateKey:o,n:a}=t;if(r&&"bigint"!=typeof e){if(E(e)&&(e=B(e)),"string"!=typeof e||!r.includes(e.length))throw Error("Invalid key");e=e.padStart(2*i,"0")}try{n="bigint"==typeof e?e:F(V("private key",e,i))}catch(t){throw Error(`private key must be ${i} bytes, hex or bigint, not ${typeof e}`)}return o&&(n=eh(n,a)),Z("private key",n,tG,a),n}function s(e){if(!(e instanceof c))throw Error("ProjectivePoint expected")}let u=ea((e,t)=>{let{px:r,py:i,pz:o}=e;if(n.eql(o,n.ONE))return{x:r,y:i};let a=e.is0();null==t&&(t=a?n.ONE:n.inv(o));let s=n.mul(r,t),u=n.mul(i,t),l=n.mul(o,t);if(a)return{x:n.ZERO,y:n.ZERO};if(!n.eql(l,n.ONE))throw Error("invZ was invalid");return{x:s,y:u}}),l=ea(e=>{if(e.is0()){if(t.allowInfinityPoint&&!n.is0(e.py))return;throw Error("bad point: ZERO")}let{x:r,y:i}=e.toAffine();if(!n.isValid(r)||!n.isValid(i))throw Error("bad point: x or y not FE");let a=n.sqr(i),s=o(r);if(!n.eql(a,s))throw Error("bad point: equation left != right");if(!e.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class c{constructor(e,t,r){if(this.px=e,this.py=t,this.pz=r,null==e||!n.isValid(e))throw Error("x required");if(null==t||!n.isValid(t))throw Error("y required");if(null==r||!n.isValid(r))throw Error("z required");Object.freeze(this)}static fromAffine(e){let{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw Error("invalid affine point");if(e instanceof c)throw Error("projective point not allowed");let i=e=>n.eql(e,n.ZERO);return i(t)&&i(r)?c.ZERO:new c(t,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){let t=n.invertBatch(e.map(e=>e.pz));return e.map((e,n)=>e.toAffine(t[n])).map(c.fromAffine)}static fromHex(e){let t=c.fromAffine(i(V("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return c.BASE.multiply(a(e))}_setWindowSize(e){p.setWindowSize(this,e)}assertValidity(){l(this)}hasEvenY(){let{y:e}=this.toAffine();if(n.isOdd)return!n.isOdd(e);throw Error("Field doesn't support isOdd")}equals(e){s(e);let{px:t,py:r,pz:i}=this,{px:o,py:a,pz:u}=e,l=n.eql(n.mul(t,u),n.mul(o,i)),c=n.eql(n.mul(r,u),n.mul(a,i));return l&&c}negate(){return new c(this.px,n.neg(this.py),this.pz)}double(){let{a:e,b:r}=t,i=n.mul(r,tZ),{px:o,py:a,pz:s}=this,u=n.ZERO,l=n.ZERO,d=n.ZERO,p=n.mul(o,o),f=n.mul(a,a),h=n.mul(s,s),m=n.mul(o,a);return m=n.add(m,m),d=n.mul(o,s),d=n.add(d,d),u=n.mul(e,d),l=n.mul(i,h),l=n.add(u,l),u=n.sub(f,l),l=n.add(f,l),l=n.mul(u,l),u=n.mul(m,u),d=n.mul(i,d),h=n.mul(e,h),m=n.sub(p,h),m=n.mul(e,m),m=n.add(m,d),d=n.add(p,p),p=n.add(d,p),p=n.add(p,h),p=n.mul(p,m),l=n.add(l,p),h=n.mul(a,s),h=n.add(h,h),p=n.mul(h,m),u=n.sub(u,p),d=n.mul(h,f),d=n.add(d,d),d=n.add(d,d),new c(u,l,d)}add(e){s(e);let{px:r,py:i,pz:o}=this,{px:a,py:u,pz:l}=e,d=n.ZERO,p=n.ZERO,f=n.ZERO,h=t.a,m=n.mul(t.b,tZ),g=n.mul(r,a),y=n.mul(i,u),b=n.mul(o,l),_=n.add(r,i),v=n.add(a,u);_=n.mul(_,v),v=n.add(g,y),_=n.sub(_,v),v=n.add(r,o);let w=n.add(a,l);return v=n.mul(v,w),w=n.add(g,b),v=n.sub(v,w),w=n.add(i,o),d=n.add(u,l),w=n.mul(w,d),d=n.add(y,b),w=n.sub(w,d),f=n.mul(h,v),d=n.mul(m,b),f=n.add(d,f),d=n.sub(y,f),f=n.add(y,f),p=n.mul(d,f),y=n.add(g,g),y=n.add(y,g),b=n.mul(h,b),v=n.mul(m,v),y=n.add(y,b),b=n.sub(g,b),b=n.mul(h,b),v=n.add(v,b),g=n.mul(y,v),p=n.add(p,g),g=n.mul(w,v),d=n.mul(_,d),d=n.sub(d,g),g=n.mul(_,y),f=n.mul(w,f),f=n.add(f,g),new c(d,p,f)}subtract(e){return this.add(e.negate())}is0(){return this.equals(c.ZERO)}wNAF(e){return p.wNAFCached(this,e,c.normalizeZ)}multiplyUnsafe(e){Z("scalar",e,tH,t.n);let r=c.ZERO;if(e===tH)return r;if(e===tG)return this;let{endo:i}=t;if(!i)return p.unsafeLadder(this,e);let{k1neg:o,k1:a,k2neg:s,k2:u}=i.splitScalar(e),l=r,d=r,f=this;for(;a>tH||u>tH;)a&tG&&(l=l.add(f)),u&tG&&(d=d.add(f)),f=f.double(),a>>=tG,u>>=tG;return o&&(l=l.negate()),s&&(d=d.negate()),d=new c(n.mul(d.px,i.beta),d.py,d.pz),l.add(d)}multiply(e){let r,i;let{endo:o,n:a}=t;if(Z("scalar",e,tG,a),o){let{k1neg:t,k1:a,k2neg:s,k2:u}=o.splitScalar(e),{p:l,f:d}=this.wNAF(a),{p:f,f:h}=this.wNAF(u);l=p.constTimeNegate(t,l),f=p.constTimeNegate(s,f),f=new c(n.mul(f.px,o.beta),f.py,f.pz),r=l.add(f),i=d.add(h)}else{let{p:t,f:n}=this.wNAF(e);r=t,i=n}return c.normalizeZ([r,i])[0]}multiplyAndAddUnsafe(e,t,n){let r=c.BASE,i=(e,t)=>t!==tH&&t!==tG&&e.equals(r)?e.multiply(t):e.multiplyUnsafe(t),o=i(this,t).add(i(e,n));return o.is0()?void 0:o}toAffine(e){return u(this,e)}isTorsionFree(){let{h:e,isTorsionFree:n}=t;if(e===tG)return!0;if(n)return n(c,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:e,clearCofactor:n}=t;return e===tG?this:n?n(c,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return C("isCompressed",e),this.assertValidity(),r(c,this,e)}toHex(e=!0){return C("isCompressed",e),B(this.toRawBytes(e))}}c.BASE=new c(t.Gx,t.Gy,n.ONE),c.ZERO=new c(n.ZERO,n.ONE,n.ZERO);let d=t.nBitLength,p=eT(c,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:c,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:function(e){return G(e,tG,t.n)}}}({...t,toBytes(e,t,r){let i=t.toAffine(),o=n.toBytes(i.x),a=W;return(C("isCompressed",r),r)?a(Uint8Array.from([t.hasEvenY()?2:3]),o):a(Uint8Array.from([4]),o,n.toBytes(i.y))},fromBytes(e){let t=e.length,r=e[0],a=e.subarray(1);if(t===i&&(2===r||3===r)){let e;let t=F(a);if(!G(t,tG,n.ORDER))throw Error("Point is not on curve");let i=l(t);try{e=n.sqrt(i)}catch(t){let e=t instanceof Error?": "+t.message:"";throw Error("Point is not on curve"+e)}let o=(e&tG)===tG;return(1&r)==1!==o&&(e=n.neg(e)),{x:t,y:e}}if(t===o&&4===r){let e=n.fromBytes(a.subarray(0,n.BYTES)),t=n.fromBytes(a.subarray(n.BYTES,2*n.BYTES));return{x:e,y:t}}throw Error(`Point of length ${t} was invalid. Expected ${i} compressed bytes or ${o} uncompressed bytes`)}}),d=e=>B(j(e,t.nByteLength)),p=(e,t,n)=>F(e.slice(t,n));class f{constructor(e,t,n){this.r=e,this.s=t,this.recovery=n,this.assertValidity()}static fromCompact(e){let n=t.nByteLength;return e=V("compactSignature",e,2*n),new f(p(e,0,n),p(e,n,2*n))}static fromDER(e){let{r:t,s:n}=tK.toSig(V("DER",e));return new f(t,n)}assertValidity(){Z("r",this.r,tG,r),Z("s",this.s,tG,r)}addRecoveryBit(e){return new f(this.r,this.s,e)}recoverPublicKey(e){let{r:i,s:o,recovery:u}=this,l=g(V("msgHash",e));if(null==u||![0,1,2,3].includes(u))throw Error("recovery id invalid");let c=2===u||3===u?i+t.n:i;if(c>=n.ORDER)throw Error("recovery id 2 or 3 invalid");let p=s.fromHex(((1&u)==0?"02":"03")+d(c)),f=eg(c,r),h=a(-l*f),m=a(o*f),y=s.BASE.multiplyAndAddUnsafe(p,h,m);if(!y)throw Error("point at infinify");return y.assertValidity(),y}hasHighS(){return this.s>r>>tG}normalizeS(){return this.hasHighS()?new f(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return D(this.toDERHex())}toDERHex(){return tK.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return D(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}function h(e){let t=E(e),n="string"==typeof e,r=(t||n)&&e.length;return t?r===i||r===o:n?r===2*i||r===2*o:e instanceof s}let m=t.bits2int||function(e){let n=F(e),r=8*e.length-t.nBitLength;return r>0?n>>BigInt(r):n},g=t.bits2int_modN||function(e){return a(m(e))},y=J(t.nBitLength);function b(e){return Z(`num < 2^${t.nBitLength}`,e,tH,y),j(e,t.nByteLength)}let _={lowS:t.lowS,prehash:!1},v={lowS:t.lowS,prehash:!1};return s.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return s.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,n=!0){if(h(e))throw Error("first arg must be private key");if(!h(t))throw Error("second arg must be public key");let r=s.fromHex(t);return r.multiply(u(e)).toRawBytes(n)},sign:function(e,i,o=_){let{seed:l,k2sig:d}=function(e,i,o=_){if(["recovered","canonical"].some(e=>e in o))throw Error("sign() legacy options not supported");let{hash:l,randomBytes:d}=t,{lowS:p,prehash:h,extraEntropy:y}=o;null==p&&(p=!0),e=V("msgHash",e),tV(o),h&&(e=V("prehashed msgHash",l(e)));let v=g(e),w=u(i),k=[b(w),b(v)];if(null!=y&&!1!==y){let e=!0===y?d(n.BYTES):y;k.push(V("extraEntropy",e))}let x=W(...k);return{seed:x,k2sig:function(e){let t=m(e);if(!c(t))return;let n=eg(t,r),i=s.BASE.multiply(t).toAffine(),o=a(i.x);if(o===tH)return;let u=a(n*a(v+o*w));if(u===tH)return;let l=(i.x===o?0:2)|Number(i.y&tG),d=u;if(p&&u>r>>tG)d=u>r>>tG?a(-u):u,l^=1;return new f(o,d,l)}}}(e,i,o),p=en(t.hash.outputLen,t.nByteLength,t.hmac);return p(l,d)},verify:function(e,n,i,o=v){let u,l;if(n=V("msgHash",n),i=V("publicKey",i),"strict"in o)throw Error("options.strict was renamed to lowS");tV(o);let{lowS:c,prehash:d}=o;try{if("string"==typeof e||E(e))try{l=f.fromDER(e)}catch(t){if(!(t instanceof tK.Err))throw t;l=f.fromCompact(e)}else if("object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s){let{r:t,s:n}=e;l=new f(t,n)}else throw Error("PARSE");u=s.fromHex(i)}catch(e){if("PARSE"===e.message)throw Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(c&&l.hasHighS())return!1;d&&(n=t.hash(n));let{r:p,s:h}=l,m=g(n),y=eg(h,r),b=a(m*y),_=a(p*y),w=s.BASE.multiplyAndAddUnsafe(u,b,_)?.toAffine();if(!w)return!1;let k=a(w.x);return k===p},ProjectivePoint:s,Signature:f,utils:{isValidPrivateKey(e){try{return u(e),!0}catch(e){return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let e=ek(t.n);return function(e,t,n=!1){let r=e.length,i=ew(t),o=ek(t);if(r<16||r1024)throw Error(`expected ${o}-1024 bytes of input, got ${r}`);let a=n?F(e):q(e),s=eh(a,t-eu)+eu;return n?U(s,i):j(s,i)}(t.randomBytes(e),t.n)},precompute:(e=8,t=s.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}})({...e,hash:t,hmac:(e,...n)=>tz(t,e,(0,b.eV)(...n)),randomBytes:b.O6});return Object.freeze({...n(t),create:n})}({a:BigInt(0),b:BigInt(7),Fp:t1,n:tX,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-tQ*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),r=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=BigInt("0x100000000000000000000000000000000"),o=t0(t*e,tX),a=t0(-n*e,tX),s=eh(e-o*t-a*r,tX),u=eh(-o*n-a*t,tX),l=s>i,c=u>i;if(l&&(s=tX-s),c&&(u=tX-u),s>i||u>i)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:l,k1:s,k2neg:c,k2:u}}}},e0.J);BigInt(0),t2.ProjectivePoint,eW.utils.randomPrivateKey;let t6=()=>{let e=eW.utils.randomPrivateKey(),t=t3(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},t3=eW.getPublicKey;function t4(e){try{return eW.ExtendedPoint.fromHex(e),!0}catch{return!1}}let t5=(e,t)=>eW.sign(e,t.slice(0,32)),t8=eW.verify,t9=e=>a.Buffer.isBuffer(e)?e:e instanceof Uint8Array?a.Buffer.from(e.buffer,e.byteOffset,e.byteLength):a.Buffer.from(e);class t7{constructor(e){Object.assign(this,e)}encode(){return a.Buffer.from((0,e1.serialize)(ne,this))}static decode(e){return(0,e1.deserialize)(ne,this,e)}static decodeUnchecked(e){return(0,e1.deserializeUnchecked)(ne,this,e)}}let ne=new Map,nt=1;class nn extends t7{constructor(e){if(super({}),this._bn=void 0,void 0!==e._bn)this._bn=e._bn;else{if("string"==typeof e){let t=eJ().decode(e);if(32!=t.length)throw Error("Invalid public key input");this._bn=new(eX())(t)}else this._bn=new(eX())(e);if(this._bn.byteLength()>32)throw Error("Invalid public key input")}}static unique(){let e=new nn(nt);return nt+=1,new nn(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return eJ().encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){let e=this.toBuffer();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}toBuffer(){let e=this._bn.toArrayLike(a.Buffer);if(32===e.length)return e;let t=a.Buffer.alloc(32);return e.copy(t,32-e.length),t}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(e,t,n){let r=a.Buffer.concat([e.toBuffer(),a.Buffer.from(t),n.toBuffer()]),i=(0,e0.J)(r);return new nn(i)}static createProgramAddressSync(e,t){let n=a.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw TypeError("Max seed length exceeded");n=a.Buffer.concat([n,t9(e)])}),n=a.Buffer.concat([n,t.toBuffer(),a.Buffer.from("ProgramDerivedAddress")]);let r=(0,e0.J)(n);if(t4(r))throw Error("Invalid seeds, address must fall off the curve");return new nn(r)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let n,r=255;for(;0!=r;){try{let i=e.concat(a.Buffer.from([r]));n=this.createProgramAddressSync(i,t)}catch(e){if(e instanceof TypeError)throw e;r--;continue}return[n,r]}throw Error("Unable to find a viable program address nonce")}static async findProgramAddress(e,t){return this.findProgramAddressSync(e,t)}static isOnCurve(e){let t=new nn(e);return t4(t.toBytes())}}nn.default=new nn("11111111111111111111111111111111"),ne.set(nn,{kind:"struct",fields:[["_bn","u256"]]}),new nn("BPFLoader1111111111111111111111111111111111");class nr extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(nr.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class ni extends Error{constructor(e,t){super(`Transaction was not confirmed in ${t.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${e} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=e}}Object.defineProperty(ni.prototype,"name",{value:"TransactionExpiredTimeoutError"});class no extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(no.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class na{constructor(e,t){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=e,this.accountKeysFromLookups=t}keySegments(){let e=[this.staticAccountKeys];return this.accountKeysFromLookups&&(e.push(this.accountKeysFromLookups.writable),e.push(this.accountKeysFromLookups.readonly)),e}get(e){for(let t of this.keySegments()){if(e256)throw Error("Account index overflow encountered during compilation");let t=new Map;this.keySegments().flat().forEach((e,n)=>{t.set(e.toBase58(),n)});let n=e=>{let n=t.get(e.toBase58());if(void 0===n)throw Error("Encountered an unknown instruction account key during compilation");return n};return e.map(e=>({programIdIndex:n(e.programId),accountKeyIndexes:e.keys.map(e=>n(e.pubkey)),data:e.data}))}}let ns=(e="publicKey")=>e2.Ik(32,e),nu=(e="signature")=>e2.Ik(64,e),nl=(e="string")=>{let t=e2.n_([e2.Jq("length"),e2.Jq("lengthPadding"),e2.Ik(e2.cv(e2.Jq(),-8),"chars")],e),n=t.decode.bind(t),r=t.encode.bind(t),i=t;return i.decode=(e,t)=>{let r=n(e,t);return r.chars.toString()},i.encode=(e,t,n)=>{let i={chars:a.Buffer.from(e,"utf8")};return r(i,t,n)},i.alloc=e=>e2.Jq().span+e2.Jq().span+a.Buffer.from(e,"utf8").length,i};function nc(e){let t=0,n=0;for(;;){let r=e.shift();if(t|=(127&r)<<7*n,n+=1,(128&r)==0)break}return t}function nd(e,t){let n=t;for(;;){let t=127&n;if(0==(n>>=7)){e.push(t);break}t|=128,e.push(t)}}function np(e,t){if(!e)throw Error(t||"Assertion failed")}class nf{constructor(e,t){this.payer=void 0,this.keyMetaMap=void 0,this.payer=e,this.keyMetaMap=t}static compile(e,t){let n=new Map,r=e=>{let t=e.toBase58(),r=n.get(t);return void 0===r&&(r={isSigner:!1,isWritable:!1,isInvoked:!1},n.set(t,r)),r},i=r(t);for(let t of(i.isSigner=!0,i.isWritable=!0,e))for(let e of(r(t.programId).isInvoked=!0,t.keys)){let t=r(e.pubkey);t.isSigner||=e.isSigner,t.isWritable||=e.isWritable}return new nf(t,n)}getMessageComponents(){let e=[...this.keyMetaMap.entries()];np(e.length<=256,"Max static account keys length exceeded");let t=e.filter(([,e])=>e.isSigner&&e.isWritable),n=e.filter(([,e])=>e.isSigner&&!e.isWritable),r=e.filter(([,e])=>!e.isSigner&&e.isWritable),i=e.filter(([,e])=>!e.isSigner&&!e.isWritable),o={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:i.length};{np(t.length>0,"Expected at least one writable signer key");let[e]=t[0];np(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}let a=[...t.map(([e])=>new nn(e)),...n.map(([e])=>new nn(e)),...r.map(([e])=>new nn(e)),...i.map(([e])=>new nn(e))];return[o,a]}extractTableLookup(e){let[t,n]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&e.isWritable),[r,i]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&!e.isWritable);if(0!==t.length||0!==r.length)return[{accountKey:e.key,writableIndexes:t,readonlyIndexes:r},{writable:n,readonly:i}]}drainKeysFoundInLookupTable(e,t){let n=[],r=[];for(let[i,o]of this.keyMetaMap.entries())if(t(o)){let t=new nn(i),o=e.findIndex(e=>e.equals(t));o>=0&&(np(o<256,"Max lookup table index exceeded"),n.push(o),r.push(t),this.keyMetaMap.delete(i))}return[n,r]}}let nh="Reached end of buffer unexpectedly";function nm(e){if(0===e.length)throw Error(nh);return e.shift()}function ng(e,...t){let[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw Error(nh);return e.splice(...t)}class ny{constructor(e){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=e.header,this.accountKeys=e.accountKeys.map(e=>new nn(e)),this.recentBlockhash=e.recentBlockhash,this.instructions=e.instructions,this.instructions.forEach(e=>this.indexToProgramIds.set(e.programIdIndex,this.accountKeys[e.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:eJ().decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new na(this.staticAccountKeys)}static compile(e){let t=nf.compile(e.instructions,e.payerKey),[n,r]=t.getMessageComponents(),i=new na(r),o=i.compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:eJ().encode(e.data)}));return new ny({header:n,accountKeys:r,recentBlockhash:e.recentBlockhash,instructions:o})}isAccountSigner(e){return e=this.header.numRequiredSignatures){let n=this.accountKeys.length-t,r=n-this.header.numReadonlyUnsignedAccounts;return e-t!this.isProgramId(t))}serialize(){let e=this.accountKeys.length,t=[];nd(t,e);let n=this.instructions.map(e=>{let{accounts:t,programIdIndex:n}=e,r=Array.from(eJ().decode(e.data)),i=[];nd(i,t.length);let o=[];return nd(o,r.length),{programIdIndex:n,keyIndicesCount:a.Buffer.from(i),keyIndices:t,dataLength:a.Buffer.from(o),data:r}}),r=[];nd(r,n.length);let i=a.Buffer.alloc(1232);a.Buffer.from(r).copy(i);let o=r.length;n.forEach(e=>{let t=e2.n_([e2.u8("programIdIndex"),e2.Ik(e.keyIndicesCount.length,"keyIndicesCount"),e2.A9(e2.u8("keyIndex"),e.keyIndices.length,"keyIndices"),e2.Ik(e.dataLength.length,"dataLength"),e2.A9(e2.u8("userdatum"),e.data.length,"data")]),n=t.encode(e,i,o);o+=n}),i=i.slice(0,o);let s=e2.n_([e2.Ik(1,"numRequiredSignatures"),e2.Ik(1,"numReadonlySignedAccounts"),e2.Ik(1,"numReadonlyUnsignedAccounts"),e2.Ik(t.length,"keyCount"),e2.A9(ns("key"),e,"keys"),ns("recentBlockhash")]),u={numRequiredSignatures:a.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:a.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:a.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:a.Buffer.from(t),keys:this.accountKeys.map(e=>t9(e.toBytes())),recentBlockhash:eJ().decode(this.recentBlockhash)},l=a.Buffer.alloc(2048),c=s.encode(u,l);return i.copy(l,c),l.slice(0,c+i.length)}static from(e){let t=[...e],n=nm(t);if(n!==(127&n))throw Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");let r=nm(t),i=nm(t),o=nc(t),s=[];for(let e=0;e0)throw Error("Failed to get account keys because address table lookups were not resolved");return new na(this.staticAccountKeys,t)}isAccountSigner(e){return e=n){let t=this.addressTableLookups.reduce((e,t)=>e+t.writableIndexes.length,0);return e-n=this.header.numRequiredSignatures){let r=n-t-this.header.numReadonlyUnsignedAccounts;return e-te.key.equals(n.accountKey));if(!r)throw Error(`Failed to find address lookup table account for table key ${n.accountKey.toBase58()}`);for(let e of n.writableIndexes)if(ee.toBytes()),recentBlockhash:eJ().decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(i),serializedAddressTableLookups:r},a);return a.slice(0,s)}serializeInstructions(){let e=0,t=new Uint8Array(1232);for(let n of this.compiledInstructions){let r=[];nd(r,n.accountKeyIndexes.length);let i=[];nd(i,n.data.length);let o=e2.n_([e2.u8("programIdIndex"),e2.Ik(r.length,"encodedAccountKeyIndexesLength"),e2.A9(e2.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),e2.Ik(i.length,"encodedDataLength"),e2.Ik(n.data.length,"data")]);e+=o.encode({programIdIndex:n.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(r),accountKeyIndexes:n.accountKeyIndexes,encodedDataLength:new Uint8Array(i),data:n.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0,t=new Uint8Array(1232);for(let n of this.addressTableLookups){let r=[];nd(r,n.writableIndexes.length);let i=[];nd(i,n.readonlyIndexes.length);let o=e2.n_([ns("accountKey"),e2.Ik(r.length,"encodedWritableIndexesLength"),e2.A9(e2.u8(),n.writableIndexes.length,"writableIndexes"),e2.Ik(i.length,"encodedReadonlyIndexesLength"),e2.A9(e2.u8(),n.readonlyIndexes.length,"readonlyIndexes")]);e+=o.encode({accountKey:n.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(r),writableIndexes:n.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(i),readonlyIndexes:n.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e],n=nm(t),r=127&n;np(n!==r,"Expected versioned message but received legacy message"),np(0===r,`Expected versioned message with version 0 but found version ${r}`);let i={numRequiredSignatures:nm(t),numReadonlySignedAccounts:nm(t),numReadonlyUnsignedAccounts:nm(t)},o=[],a=nc(t);for(let e=0;e{let t=n_.deserializeMessageVersion(e);if("legacy"===t)return ny.from(e);if(0===t)return nb.deserialize(e);throw Error(`Transaction message version ${t} deserialization is not supported`)}},nv=((r={})[r.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",r[r.PROCESSED=1]="PROCESSED",r[r.TIMED_OUT=2]="TIMED_OUT",r[r.NONCE_INVALID=3]="NONCE_INVALID",r),nw=a.Buffer.alloc(64).fill(0);class nk{constructor(e){this.keys=void 0,this.programId=void 0,this.data=a.Buffer.alloc(0),this.programId=e.programId,this.keys=e.keys,e.data&&(this.data=e.data)}toJSON(){return{keys:this.keys.map(({pubkey:e,isSigner:t,isWritable:n})=>({pubkey:e.toJSON(),isSigner:t,isWritable:n})),programId:this.programId.toJSON(),data:[...this.data]}}}class nx{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(e){if(this.signatures=[],this.feePayer=void 0,this.instructions=[],this.recentBlockhash=void 0,this.lastValidBlockHeight=void 0,this.nonceInfo=void 0,this.minNonceContextSlot=void 0,this._message=void 0,this._json=void 0,!e)return;if(e.feePayer&&(this.feePayer=e.feePayer),e.signatures&&(this.signatures=e.signatures),Object.prototype.hasOwnProperty.call(e,"nonceInfo")){let{minContextSlot:t,nonceInfo:n}=e;this.minNonceContextSlot=t,this.nonceInfo=n}else if(Object.prototype.hasOwnProperty.call(e,"lastValidBlockHeight")){let{blockhash:t,lastValidBlockHeight:n}=e;this.recentBlockhash=t,this.lastValidBlockHeight=n}else{let{recentBlockhash:t,nonceInfo:n}=e;n&&(this.nonceInfo=n),this.recentBlockhash=t}}toJSON(){return{recentBlockhash:this.recentBlockhash||null,feePayer:this.feePayer?this.feePayer.toJSON():null,nonceInfo:this.nonceInfo?{nonce:this.nonceInfo.nonce,nonceInstruction:this.nonceInfo.nonceInstruction.toJSON()}:null,instructions:this.instructions.map(e=>e.toJSON()),signers:this.signatures.map(({publicKey:e})=>e.toJSON())}}add(...e){if(0===e.length)throw Error("No instructions");return e.forEach(e=>{"instructions"in e?this.instructions=this.instructions.concat(e.instructions):"data"in e&&"programId"in e&&"keys"in e?this.instructions.push(e):this.instructions.push(new nk(e))}),this}compileMessage(){let e,t,n;if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;if(this.nonceInfo?(e=this.nonceInfo.nonce,t=this.instructions[0]!=this.nonceInfo.nonceInstruction?[this.nonceInfo.nonceInstruction,...this.instructions]:this.instructions):(e=this.recentBlockhash,t=this.instructions),!e)throw Error("Transaction recentBlockhash required");if(t.length<1&&console.warn("No instructions provided"),this.feePayer)n=this.feePayer;else if(this.signatures.length>0&&this.signatures[0].publicKey)n=this.signatures[0].publicKey;else throw Error("Transaction fee payer required");for(let e=0;e{e.keys.forEach(e=>{i.push({...e})});let t=e.programId.toString();r.includes(t)||r.push(t)}),r.forEach(e=>{i.push({pubkey:new nn(e),isSigner:!1,isWritable:!1})});let o=[];i.forEach(e=>{let t=e.pubkey.toString(),n=o.findIndex(e=>e.pubkey.toString()===t);n>-1?(o[n].isWritable=o[n].isWritable||e.isWritable,o[n].isSigner=o[n].isSigner||e.isSigner):o.push(e)}),o.sort(function(e,t){return e.isSigner!==t.isSigner?e.isSigner?-1:1:e.isWritable!==t.isWritable?e.isWritable?-1:1:e.pubkey.toBase58().localeCompare(t.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});let a=o.findIndex(e=>e.pubkey.equals(n));if(a>-1){let[e]=o.splice(a,1);e.isSigner=!0,e.isWritable=!0,o.unshift(e)}else o.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(let e of this.signatures){let t=o.findIndex(t=>t.pubkey.equals(e.publicKey));if(t>-1)o[t].isSigner||(o[t].isSigner=!0,console.warn("Transaction references a signature that is unnecessary, only the fee payer and instruction signer accounts should sign a transaction. This behavior is deprecated and will throw an error in the next major version release."));else throw Error(`unknown signer: ${e.publicKey.toString()}`)}let s=0,u=0,l=0,c=[],d=[];o.forEach(({pubkey:e,isSigner:t,isWritable:n})=>{t?(c.push(e.toString()),s+=1,n||(u+=1)):(d.push(e.toString()),n||(l+=1))});let p=c.concat(d),f=t.map(e=>{let{data:t,programId:n}=e;return{programIdIndex:p.indexOf(n.toString()),accounts:e.keys.map(e=>p.indexOf(e.pubkey.toString())),data:eJ().encode(t)}});return f.forEach(e=>{np(e.programIdIndex>=0),e.accounts.forEach(e=>np(e>=0))}),new ny({header:{numRequiredSignatures:s,numReadonlySignedAccounts:u,numReadonlyUnsignedAccounts:l},accountKeys:p,recentBlockhash:e,instructions:f})}_compile(){let e=this.compileMessage(),t=e.accountKeys.slice(0,e.header.numRequiredSignatures);if(this.signatures.length===t.length){let n=this.signatures.every((e,n)=>t[n].equals(e.publicKey));if(n)return e}return this.signatures=t.map(e=>({signature:null,publicKey:e})),e}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(e){return(await e.getFeeForMessage(this.compileMessage())).value}setSigners(...e){if(0===e.length)throw Error("No signers");let t=new Set;this.signatures=e.filter(e=>{let n=e.toString();return!t.has(n)&&(t.add(n),!0)}).map(e=>({signature:null,publicKey:e}))}sign(...e){if(0===e.length)throw Error("No signers");let t=new Set,n=[];for(let r of e){let e=r.publicKey.toString();t.has(e)||(t.add(e),n.push(r))}this.signatures=n.map(e=>({signature:null,publicKey:e.publicKey}));let r=this._compile();this._partialSign(r,...n)}partialSign(...e){if(0===e.length)throw Error("No signers");let t=new Set,n=[];for(let r of e){let e=r.publicKey.toString();t.has(e)||(t.add(e),n.push(r))}let r=this._compile();this._partialSign(r,...n)}_partialSign(e,...t){let n=e.serialize();t.forEach(e=>{let t=t5(n,e.secretKey);this._addSignature(e.publicKey,t9(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){np(64===t.length);let n=this.signatures.findIndex(t=>e.equals(t.publicKey));if(n<0)throw Error(`unknown signer: ${e.toString()}`);this.signatures[n].signature=a.Buffer.from(t)}verifySignatures(e=!0){let t=this._getMessageSignednessErrors(this.serializeMessage(),e);return!t}_getMessageSignednessErrors(e,t){let n={};for(let{signature:r,publicKey:i}of this.signatures)null===r?t&&(n.missing||=[]).push(i):t8(r,e,i.toBytes())||(n.invalid||=[]).push(i);return n.invalid||n.missing?n:void 0}serialize(e){let{requireAllSignatures:t,verifySignatures:n}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),r=this.serializeMessage();if(n){let e=this._getMessageSignednessErrors(r,t);if(e){let t="Signature verification failed.";throw e.invalid&&(t+=`
Invalid signature for public key${1===e.invalid.length?"":"(s)"} [\`${e.invalid.map(e=>e.toBase58()).join("`, `")}\`].`),e.missing&&(t+=`
Missing signature for public key${1===e.missing.length?"":"(s)"} [\`${e.missing.map(e=>e.toBase58()).join("`, `")}\`].`),Error(t)}}return this._serialize(r)}_serialize(e){let{signatures:t}=this,n=[];nd(n,t.length);let r=n.length+64*t.length+e.length,i=a.Buffer.alloc(r);return np(t.length<256),a.Buffer.from(n).copy(i,0),t.forEach(({signature:e},t)=>{null!==e&&(np(64===e.length,"signature has invalid length"),a.Buffer.from(e).copy(i,n.length+64*t))}),e.copy(i,n.length+64*t.length),np(i.length<=1232,`Transaction too large: ${i.length} > 1232`),i}get keys(){return np(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return np(1===this.instructions.length),this.instructions[0].programId}get data(){return np(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e],n=nc(t),r=[];for(let e=0;e0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,r)=>{let i={signature:t==eJ().encode(nw)?null:eJ().decode(t),publicKey:e.accountKeys[r]};n.signatures.push(i)}),e.instructions.forEach(t=>{let r=t.accounts.map(t=>{let r=e.accountKeys[t];return{pubkey:r,isSigner:n.signatures.some(e=>e.publicKey.toString()===r.toString())||e.isAccountSigner(t),isWritable:e.isAccountWritable(t)}});n.instructions.push(new nk({keys:r,programId:e.accountKeys[t.programIdIndex],data:eJ().decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}class nA{constructor(e){this.payerKey=void 0,this.instructions=void 0,this.recentBlockhash=void 0,this.payerKey=e.payerKey,this.instructions=e.instructions,this.recentBlockhash=e.recentBlockhash}static decompile(e,t){let{header:n,compiledInstructions:r,recentBlockhash:i}=e,{numRequiredSignatures:o,numReadonlySignedAccounts:a,numReadonlyUnsignedAccounts:s}=n,u=o-a;np(u>0,"Message header is invalid");let l=e.staticAccountKeys.length-o-s;np(l>=0,"Message header is invalid");let c=e.getAccountKeys(t),d=c.get(0);if(void 0===d)throw Error("Failed to decompile message because no account keys were found");let p=[];for(let e of r){let t=[];for(let r of e.accountKeyIndexes){let e;let i=c.get(r);if(void 0===i)throw Error(`Failed to find key for account key index ${r}`);let a=re.equals(r.publicKey));np(e>=0,`Cannot sign with non signer key ${r.publicKey.toBase58()}`),this.signatures[e]=t5(t,r.secretKey)}}addSignature(e,t){np(64===t.byteLength,"Signature must be 64 bytes long");let n=this.message.staticAccountKeys.slice(0,this.message.header.numRequiredSignatures),r=n.findIndex(t=>t.equals(e));np(r>=0,`Can not add signature; \`${e.toBase58()}\` is not required to sign this transaction`),this.signatures[r]=t}}let nI=new nn("SysvarC1ock11111111111111111111111111111111");new nn("SysvarEpochSchedu1e111111111111111111111111"),new nn("Sysvar1nstructions1111111111111111111111111");let nT=new nn("SysvarRecentB1ockHashes11111111111111111111"),nE=new nn("SysvarRent111111111111111111111111111111111");new nn("SysvarRewards111111111111111111111111111111"),new nn("SysvarS1otHashes111111111111111111111111111"),new nn("SysvarS1otHistory11111111111111111111111111");let nP=new nn("SysvarStakeHistory1111111111111111111111111");class nC extends Error{constructor({action:e,signature:t,transactionMessage:n,logs:r}){let i;let o=r?`Logs:
${JSON.stringify(r.slice(-10),null,2)}. `:"",a="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";switch(e){case"send":i=`Transaction ${t} resulted in an error.
${n}. `+o+a;break;case"simulate":i=`Simulation failed.
Message: ${n}.
`+o+a;break;default:i=`Unknown action '${e}'`}super(i),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=t,this.transactionMessage=n,this.transactionLogs=r||void 0}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:void 0}}get logs(){let e=this.transactionLogs;if(null==e||"object"!=typeof e||!("then"in e))return e}async getLogs(e){return Array.isArray(this.transactionLogs)||(this.transactionLogs=new Promise((t,n)=>{e.getTransaction(this.signature).then(e=>{if(e&&e.meta&&e.meta.logMessages){let n=e.meta.logMessages;this.transactionLogs=n,t(n)}else n(Error("Log messages not found"))}).catch(n)})),await this.transactionLogs}}class nO extends Error{constructor({code:e,message:t,data:n},r){super(null!=r?`${r}: ${t}`:t),this.code=void 0,this.data=void 0,this.code=e,this.data=n,this.name="SolanaJSONRPCError"}}async function nB(e,t,n,r){let i;let o=r&&{skipPreflight:r.skipPreflight,preflightCommitment:r.preflightCommitment||r.commitment,maxRetries:r.maxRetries,minContextSlot:r.minContextSlot},a=await e.sendTransaction(t,n,o);if(null!=t.recentBlockhash&&null!=t.lastValidBlockHeight)i=(await e.confirmTransaction({abortSignal:r?.abortSignal,signature:a,blockhash:t.recentBlockhash,lastValidBlockHeight:t.lastValidBlockHeight},r&&r.commitment)).value;else if(null!=t.minNonceContextSlot&&null!=t.nonceInfo){let{nonceInstruction:n}=t.nonceInfo,o=n.keys[0].pubkey;i=(await e.confirmTransaction({abortSignal:r?.abortSignal,minContextSlot:t.minNonceContextSlot,nonceAccountPubkey:o,nonceValue:t.nonceInfo.nonce,signature:a},r&&r.commitment)).value}else r?.abortSignal!=null&&console.warn("sendAndConfirmTransaction(): A transaction with a deprecated confirmation strategy was supplied along with an `abortSignal`. Only transactions having `lastValidBlockHeight` or a combination of `nonceInfo` and `minNonceContextSlot` are abortable."),i=(await e.confirmTransaction(a,r&&r.commitment)).value;if(i.err){if(null!=a)throw new nC({action:"send",signature:a,transactionMessage:`Status: (${JSON.stringify(i)})`});throw Error(`Transaction ${a} failed (${JSON.stringify(i)})`)}return a}function nM(e){return new Promise(t=>setTimeout(t,e))}function nR(e,t){let n=e.layout.span>=0?e.layout.span:function e(t,n){let r=t=>{if(t.span>=0)return t.span;if("function"==typeof t.alloc)return t.alloc(n[t.property]);if("count"in t&&"elementLayout"in t){let e=n[t.property];if(Array.isArray(e))return e.length*r(t.elementLayout)}else if("fields"in t)return e({layout:t},n[t.property]);return 0},i=0;return t.layout.fields.forEach(e=>{i+=r(e)}),i}(e,t),r=a.Buffer.alloc(n),i=Object.assign({instruction:e.index},t);return e.layout.encode(i,r),r}let nL=e2._O("lamportsPerSignature"),nN=e2.n_([e2.Jq("version"),e2.Jq("state"),ns("authorizedPubkey"),ns("nonce"),e2.n_([nL],"feeCalculator")]),nD=nN.span;class nF{constructor(e){this.authorizedPubkey=void 0,this.nonce=void 0,this.feeCalculator=void 0,this.authorizedPubkey=e.authorizedPubkey,this.nonce=e.nonce,this.feeCalculator=e.feeCalculator}static fromAccountData(e){let t=nN.decode(t9(e),0);return new nF({authorizedPubkey:new nn(t.authorizedPubkey),nonce:new nn(t.nonce).toString(),feeCalculator:t.feeCalculator})}}let nq=e=>{let t=e.decode.bind(e),n=e.encode.bind(e);return{decode:t,encode:n}},nj=e=>{let t=(0,e2.Ik)(8,e),{encode:n,decode:r}=nq(t),i=t;return i.decode=(e,t)=>{let n=r(e,t);return(0,e6.oU)(a.Buffer.from(n))},i.encode=(e,t,r)=>{let i=(0,e6.k$)(e,8);return n(i,t,r)},i},nU=Object.freeze({Create:{index:0,layout:e2.n_([e2.Jq("instruction"),e2.gM("lamports"),e2.gM("space"),ns("programId")])},Assign:{index:1,layout:e2.n_([e2.Jq("instruction"),ns("programId")])},Transfer:{index:2,layout:e2.n_([e2.Jq("instruction"),nj("lamports")])},CreateWithSeed:{index:3,layout:e2.n_([e2.Jq("instruction"),ns("base"),nl("seed"),e2.gM("lamports"),e2.gM("space"),ns("programId")])},AdvanceNonceAccount:{index:4,layout:e2.n_([e2.Jq("instruction")])},WithdrawNonceAccount:{index:5,layout:e2.n_([e2.Jq("instruction"),e2.gM("lamports")])},InitializeNonceAccount:{index:6,layout:e2.n_([e2.Jq("instruction"),ns("authorized")])},AuthorizeNonceAccount:{index:7,layout:e2.n_([e2.Jq("instruction"),ns("authorized")])},Allocate:{index:8,layout:e2.n_([e2.Jq("instruction"),e2.gM("space")])},AllocateWithSeed:{index:9,layout:e2.n_([e2.Jq("instruction"),ns("base"),nl("seed"),e2.gM("space"),ns("programId")])},AssignWithSeed:{index:10,layout:e2.n_([e2.Jq("instruction"),ns("base"),nl("seed"),ns("programId")])},TransferWithSeed:{index:11,layout:e2.n_([e2.Jq("instruction"),nj("lamports"),nl("seed"),ns("programId")])},UpgradeNonceAccount:{index:12,layout:e2.n_([e2.Jq("instruction")])}});class nz{constructor(){}static createAccount(e){let t=nU.Create,n=nR(t,{lamports:e.lamports,space:e.space,programId:t9(e.programId.toBuffer())});return new nk({keys:[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!0,isWritable:!0}],programId:this.programId,data:n})}static transfer(e){let t,n;if("basePubkey"in e){let r=nU.TransferWithSeed;t=nR(r,{lamports:BigInt(e.lamports),seed:e.seed,programId:t9(e.programId.toBuffer())}),n=[{pubkey:e.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}else{let r=nU.Transfer;t=nR(r,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new nk({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){let r=nU.AssignWithSeed;t=nR(r,{base:t9(e.basePubkey.toBuffer()),seed:e.seed,programId:t9(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{let r=nU.Assign;t=nR(r,{programId:t9(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new nk({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){let t=nU.CreateWithSeed,n=nR(t,{base:t9(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:t9(e.programId.toBuffer())}),r=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!1,isWritable:!0}];return e.basePubkey.equals(e.fromPubkey)||r.push({pubkey:e.basePubkey,isSigner:!0,isWritable:!1}),new nk({keys:r,programId:this.programId,data:n})}static createNonceAccount(e){let t=new nx;"basePubkey"in e&&"seed"in e?t.add(nz.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:nD,programId:this.programId})):t.add(nz.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:nD,programId:this.programId}));let n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){let t=nU.InitializeNonceAccount,n=nR(t,{authorized:t9(e.authorizedPubkey.toBuffer())}),r={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:nT,isSigner:!1,isWritable:!1},{pubkey:nE,isSigner:!1,isWritable:!1}],programId:this.programId,data:n};return new nk(r)}static nonceAdvance(e){let t=nU.AdvanceNonceAccount,n=nR(t),r={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:nT,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:n};return new nk(r)}static nonceWithdraw(e){let t=nU.WithdrawNonceAccount,n=nR(t,{lamports:e.lamports});return new nk({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:nT,isSigner:!1,isWritable:!1},{pubkey:nE,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:n})}static nonceAuthorize(e){let t=nU.AuthorizeNonceAccount,n=nR(t,{authorized:t9(e.newAuthorizedPubkey.toBuffer())});return new nk({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:n})}static allocate(e){let t,n;if("basePubkey"in e){let r=nU.AllocateWithSeed;t=nR(r,{base:t9(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:t9(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{let r=nU.Allocate;t=nR(r,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new nk({keys:n,programId:this.programId,data:t})}}nz.programId=new nn("11111111111111111111111111111111");class nV{constructor(){}static getMinNumSignatures(e){return 2*(Math.ceil(e/nV.chunkSize)+1+1)}static async load(e,t,n,r,i){{let o=await e.getMinimumBalanceForRentExemption(i.length),a=await e.getAccountInfo(n.publicKey,"confirmed"),s=null;if(null!==a){if(a.executable)return console.error("Program load failed, account is already executable"),!1;a.data.length!==i.length&&(s=s||new nx).add(nz.allocate({accountPubkey:n.publicKey,space:i.length})),a.owner.equals(r)||(s=s||new nx).add(nz.assign({accountPubkey:n.publicKey,programId:r})),a.lamports0?o:1,space:i.length,programId:r}));null!==s&&await nB(e,s,[t,n],{commitment:"confirmed"})}let o=e2.n_([e2.Jq("instruction"),e2.Jq("offset"),e2.Jq("bytesLength"),e2.Jq("bytesLengthPadding"),e2.A9(e2.u8("byte"),e2.cv(e2.Jq(),-8),"bytes")]),s=nV.chunkSize,u=0,l=i,c=[];for(;l.length>0;){let i=l.slice(0,s),d=a.Buffer.alloc(s+16);o.encode({instruction:0,offset:u,bytes:i,bytesLength:0,bytesLengthPadding:0},d);let p=new nx().add({keys:[{pubkey:n.publicKey,isSigner:!0,isWritable:!0}],programId:r,data:d});c.push(nB(e,p,[t,n],{commitment:"confirmed"})),e._rpcEndpoint.includes("solana.com")&&await nM(250),u+=s,l=l.slice(s)}await Promise.all(c);{let i=e2.n_([e2.Jq("instruction")]),o=a.Buffer.alloc(i.span);i.encode({instruction:1},o);let s=new nx().add({keys:[{pubkey:n.publicKey,isSigner:!0,isWritable:!0},{pubkey:nE,isSigner:!1,isWritable:!1}],programId:r,data:o}),u="processed",l=await e.sendTransaction(s,[t,n],{preflightCommitment:u}),{context:c,value:d}=await e.confirmTransaction({signature:l,lastValidBlockHeight:s.lastValidBlockHeight,blockhash:s.recentBlockhash},u);if(d.err)throw Error(`Transaction ${l} failed (${JSON.stringify(d)})`);for(;;){try{let t=await e.getSlot({commitment:u});if(t>c.slot)break}catch{}await new Promise(e=>setTimeout(e,Math.round(200)))}}return!0}}nV.chunkSize=932,new nn("BPFLoader2111111111111111111111111111111111");var nW=Object.prototype.toString,n$=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t},nK=(i=function(e){var t=function e(t,n){var r,i,o,a,s,u,l;if(!0===t)return"true";if(!1===t)return"false";switch(typeof t){case"object":if(null===t)return null;if(t.toJSON&&"function"==typeof t.toJSON)return e(t.toJSON(),n);if("[object Array]"===(l=nW.call(t))){for(r=0,o="[",i=t.length-1;r-1&&(o+=e(t[r],!0)),o+"]"}if("[object Object]"!==l)return JSON.stringify(t);for(i=(a=n$(t).sort()).length,o="",r=0;r1;)e/=2,t++;return t}class nG{constructor(e,t,n,r,i){this.slotsPerEpoch=void 0,this.leaderScheduleSlotOffset=void 0,this.warmup=void 0,this.firstNormalEpoch=void 0,this.firstNormalSlot=void 0,this.slotsPerEpoch=e,this.leaderScheduleSlotOffset=t,this.warmup=n,this.firstNormalEpoch=r,this.firstNormalSlot=i}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,(t|=t>>32)+1))-nH(32)-1,r=this.getSlotsInEpoch(n);return[n,e-(r-32)]}{let t=e-this.firstNormalSlot,n=Math.floor(t/this.slotsPerEpoch),r=this.firstNormalEpoch+n,i=t%this.slotsPerEpoch;return[r,i]}}getFirstSlotInEpoch(e){return e<=this.firstNormalEpoch?(Math.pow(2,e)-1)*32:(e-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}getLastSlotInEpoch(e){return this.getFirstSlotInEpoch(e)+this.getSlotsInEpoch(e)-1}getSlotsInEpoch(e){return e{var n;let r=(n={autoconnect:!0,max_reconnects:5,reconnect:!0,reconnect_interval:1e3,...t},new tk(e,n));return"socket"in r?this.underlyingSocket=r.socket:this.underlyingSocket=r,r};super(r,e,t,n),this.underlyingSocket=void 0}call(...e){let t=this.underlyingSocket?.readyState;return 1===t?super.call(...e):Promise.reject(Error("Tried to call a JSON-RPC method `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}notify(...e){let t=this.underlyingSocket?.readyState;return 1===t?super.notify(...e):Promise.reject(Error("Tried to send a JSON-RPC notification `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}}class nX{constructor(e){this.key=void 0,this.state=void 0,this.key=e.key,this.state=e.state}isActive(){let e=BigInt("0xffffffffffffffff");return this.state.deactivationSlot===e}static deserialize(e){let t=function(e,t){let n;try{n=e.layout.decode(t)}catch(e){throw Error("invalid instruction; "+e)}if(n.typeIndex!==e.index)throw Error(`invalid account data; account type mismatch ${n.typeIndex} != ${e.index}`);return n}(nQ,e),n=e.length-56;np(n>=0,"lookup table is invalid"),np(n%32==0,"lookup table is invalid");let{addresses:r}=e2.n_([e2.A9(ns(),n/32,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new nn(t.authority[0]):void 0,addresses:r.map(e=>new nn(e))}}}let nQ={index:1,layout:e2.n_([e2.Jq("typeIndex"),nj("deactivationSlot"),e2._O("lastExtendedSlot"),e2.u8("lastExtendedStartIndex"),e2.u8(),e2.A9(ns(),e2.cv(e2.u8(),-1),"authority")])},nJ=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i,n0=tb(ts(nn),tf(),e=>new nn(e)),n1=th([tf(),tu("base64")]),n2=tb(ts(a.Buffer),n1,e=>a.Buffer.from(e[0],"base64"));function n6(e){let t,n;if("string"==typeof e)t=e;else if(e){let{commitment:r,...i}=e;t=r,n=i}return{commitment:t,config:n}}function n3(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function n4(e){return tg([tm({jsonrpc:tu("2.0"),id:tf(),result:e}),tm({jsonrpc:tu("2.0"),id:tf(),error:tm({code:ty(),message:tf(),data:td(ti("any",()=>!0))})})])}let n5=n4(ty());function n8(e){return tb(n4(e),n5,t=>"error"in t?t:{...t,result:tt(t.result,e)})}function n9(e){return n8(tm({context:tm({slot:tc()}),value:e}))}function n7(e){return tm({context:tm({slot:tc()}),value:e})}function re(e,t){return 0===e?new nb({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new nn(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:eJ().decode(e.data)})),addressTableLookups:t.addressTableLookups}):new ny(t)}let rt=tm({foundation:tc(),foundationTerm:tc(),initial:tc(),taper:tc(),terminal:tc()}),rn=n8(to(tl(tm({epoch:tc(),effectiveSlot:tc(),amount:tc(),postBalance:tc(),commission:td(tl(tc()))})))),rr=to(tm({slot:tc(),prioritizationFee:tc()})),ri=tm({total:tc(),validator:tc(),foundation:tc(),epoch:tc()}),ro=tm({epoch:tc(),slotIndex:tc(),slotsInEpoch:tc(),absoluteSlot:tc(),blockHeight:td(tc()),transactionCount:td(tc())}),ra=tm({slotsPerEpoch:tc(),leaderScheduleSlotOffset:tc(),warmup:ta(),firstNormalEpoch:tc(),firstNormalSlot:tc()}),rs=tp(tf(),to(tc())),ru=tl(tg([tm({}),tf()])),rl=tm({err:ru}),rc=tu("receivedSignature"),rd=tm({"solana-core":tf(),"feature-set":td(tc())}),rp=tm({program:tf(),programId:n0,parsed:ty()}),rf=tm({programId:n0,accounts:to(n0),data:tf()}),rh=n9(tm({err:tl(tg([tm({}),tf()])),logs:tl(to(tf())),accounts:td(tl(to(tl(tm({executable:ta(),owner:tf(),lamports:tc(),data:to(tf()),rentEpoch:td(tc())}))))),unitsConsumed:td(tc()),returnData:td(tl(tm({programId:tf(),data:th([tf(),tu("base64")])}))),innerInstructions:td(tl(to(tm({index:tc(),instructions:to(tg([rp,rf]))}))))})),rm=n9(tm({byIdentity:tp(tf(),to(tc())),range:tm({firstSlot:tc(),lastSlot:tc()})})),rg=n8(rt),ry=n8(ri),rb=n8(rr),r_=n8(ro),rv=n8(ra),rw=n8(rs),rk=n8(tc()),rx=n9(tm({total:tc(),circulating:tc(),nonCirculating:tc(),nonCirculatingAccounts:to(n0)})),rA=tm({amount:tf(),uiAmount:tl(tc()),decimals:tc(),uiAmountString:td(tf())}),rS=n9(to(tm({address:n0,amount:tf(),uiAmount:tl(tc()),decimals:tc(),uiAmountString:td(tf())}))),rI=n9(to(tm({pubkey:n0,account:tm({executable:ta(),owner:n0,lamports:tc(),data:n2,rentEpoch:tc()})}))),rT=tm({program:tf(),parsed:ty(),space:tc()}),rE=n9(to(tm({pubkey:n0,account:tm({executable:ta(),owner:n0,lamports:tc(),data:rT,rentEpoch:tc()})}))),rP=n9(to(tm({lamports:tc(),address:n0}))),rC=tm({executable:ta(),owner:n0,lamports:tc(),data:n2,rentEpoch:tc()}),rO=tm({pubkey:n0,account:rC}),rB=tb(tg([ts(a.Buffer),rT]),tg([n1,rT]),e=>Array.isArray(e)?tt(e,n2):e),rM=tm({executable:ta(),owner:n0,lamports:tc(),data:rB,rentEpoch:tc()}),rR=tm({pubkey:n0,account:rM}),rL=tm({state:tg([tu("active"),tu("inactive"),tu("activating"),tu("deactivating")]),active:tc(),inactive:tc()}),rN=n8(to(tm({signature:tf(),slot:tc(),err:ru,memo:tl(tf()),blockTime:td(tl(tc()))}))),rD=n8(to(tm({signature:tf(),slot:tc(),err:ru,memo:tl(tf()),blockTime:td(tl(tc()))}))),rF=tm({subscription:tc(),result:n7(rC)}),rq=tm({pubkey:n0,account:rC}),rj=tm({subscription:tc(),result:n7(rq)}),rU=tm({parent:tc(),slot:tc(),root:tc()}),rz=tm({subscription:tc(),result:rU}),rV=tg([tm({type:tg([tu("firstShredReceived"),tu("completed"),tu("optimisticConfirmation"),tu("root")]),slot:tc(),timestamp:tc()}),tm({type:tu("createdBank"),parent:tc(),slot:tc(),timestamp:tc()}),tm({type:tu("frozen"),slot:tc(),timestamp:tc(),stats:tm({numTransactionEntries:tc(),numSuccessfulTransactions:tc(),numFailedTransactions:tc(),maxTransactionsPerEntry:tc()})}),tm({type:tu("dead"),slot:tc(),timestamp:tc(),err:tf()})]),rW=tm({subscription:tc(),result:rV}),r$=tm({subscription:tc(),result:n7(tg([rl,rc]))}),rK=tm({subscription:tc(),result:tc()}),rH=tm({pubkey:tf(),gossip:tl(tf()),tpu:tl(tf()),rpc:tl(tf()),version:tl(tf())}),rG=tm({votePubkey:tf(),nodePubkey:tf(),activatedStake:tc(),epochVoteAccount:ta(),epochCredits:to(th([tc(),tc(),tc()])),commission:tc(),lastVote:tc(),rootSlot:tl(tc())}),rZ=n8(tm({current:to(rG),delinquent:to(rG)})),rY=tg([tu("processed"),tu("confirmed"),tu("finalized")]),rX=tm({slot:tc(),confirmations:tl(tc()),err:ru,confirmationStatus:td(rY)}),rQ=n9(to(tl(rX))),rJ=n8(tc()),r0=tm({accountKey:n0,writableIndexes:to(tc()),readonlyIndexes:to(tc())}),r1=tm({signatures:to(tf()),message:tm({accountKeys:to(tf()),header:tm({numRequiredSignatures:tc(),numReadonlySignedAccounts:tc(),numReadonlyUnsignedAccounts:tc()}),instructions:to(tm({accounts:to(tc()),data:tf(),programIdIndex:tc()})),recentBlockhash:tf(),addressTableLookups:td(to(r0))})}),r2=tm({pubkey:n0,signer:ta(),writable:ta(),source:td(tg([tu("transaction"),tu("lookupTable")]))}),r6=tm({accountKeys:to(r2),signatures:to(tf())}),r3=tm({parsed:ty(),program:tf(),programId:n0}),r4=tm({accounts:to(n0),data:tf(),programId:n0}),r5=tg([r4,r3]),r8=tg([tm({parsed:ty(),program:tf(),programId:tf()}),tm({accounts:to(tf()),data:tf(),programId:tf()})]),r9=tb(r5,r8,e=>"accounts"in e?tt(e,r4):tt(e,r3)),r7=tm({signatures:to(tf()),message:tm({accountKeys:to(r2),instructions:to(r9),recentBlockhash:tf(),addressTableLookups:td(tl(to(r0)))})}),ie=tm({accountIndex:tc(),mint:tf(),owner:td(tf()),uiTokenAmount:rA}),it=tm({writable:to(n0),readonly:to(n0)}),ir=tm({err:ru,fee:tc(),innerInstructions:td(tl(to(tm({index:tc(),instructions:to(tm({accounts:to(tc()),data:tf(),programIdIndex:tc()}))})))),preBalances:to(tc()),postBalances:to(tc()),logMessages:td(tl(to(tf()))),preTokenBalances:td(tl(to(ie))),postTokenBalances:td(tl(to(ie))),loadedAddresses:td(it),computeUnitsConsumed:td(tc())}),ii=tm({err:ru,fee:tc(),innerInstructions:td(tl(to(tm({index:tc(),instructions:to(r9)})))),preBalances:to(tc()),postBalances:to(tc()),logMessages:td(tl(to(tf()))),preTokenBalances:td(tl(to(ie))),postTokenBalances:td(tl(to(ie))),loadedAddresses:td(it),computeUnitsConsumed:td(tc())}),io=tg([tu(0),tu("legacy")]),ia=tm({pubkey:tf(),lamports:tc(),postBalance:tl(tc()),rewardType:tl(tf()),commission:td(tl(tc()))}),is=n8(tl(tm({blockhash:tf(),previousBlockhash:tf(),parentSlot:tc(),transactions:to(tm({transaction:r1,meta:tl(ir),version:td(io)})),rewards:td(to(ia)),blockTime:tl(tc()),blockHeight:tl(tc())}))),iu=n8(tl(tm({blockhash:tf(),previousBlockhash:tf(),parentSlot:tc(),rewards:td(to(ia)),blockTime:tl(tc()),blockHeight:tl(tc())}))),il=n8(tl(tm({blockhash:tf(),previousBlockhash:tf(),parentSlot:tc(),transactions:to(tm({transaction:r6,meta:tl(ir),version:td(io)})),rewards:td(to(ia)),blockTime:tl(tc()),blockHeight:tl(tc())}))),ic=n8(tl(tm({blockhash:tf(),previousBlockhash:tf(),parentSlot:tc(),transactions:to(tm({transaction:r7,meta:tl(ii),version:td(io)})),rewards:td(to(ia)),blockTime:tl(tc()),blockHeight:tl(tc())}))),id=n8(tl(tm({blockhash:tf(),previousBlockhash:tf(),parentSlot:tc(),transactions:to(tm({transaction:r6,meta:tl(ii),version:td(io)})),rewards:td(to(ia)),blockTime:tl(tc()),blockHeight:tl(tc())}))),ip=n8(tl(tm({blockhash:tf(),previousBlockhash:tf(),parentSlot:tc(),rewards:td(to(ia)),blockTime:tl(tc()),blockHeight:tl(tc())}))),ih=n8(tl(tm({blockhash:tf(),previousBlockhash:tf(),parentSlot:tc(),transactions:to(tm({transaction:r1,meta:tl(ir)})),rewards:td(to(ia)),blockTime:tl(tc())}))),im=n8(tl(tm({blockhash:tf(),previousBlockhash:tf(),parentSlot:tc(),signatures:to(tf()),blockTime:tl(tc())}))),ig=n8(tl(tm({slot:tc(),meta:tl(ir),blockTime:td(tl(tc())),transaction:r1,version:td(io)}))),iy=n8(tl(tm({slot:tc(),transaction:r7,meta:tl(ii),blockTime:td(tl(tc())),version:td(io)}))),ib=n9(tm({blockhash:tf(),feeCalculator:tm({lamportsPerSignature:tc()})})),i_=n9(tm({blockhash:tf(),lastValidBlockHeight:tc()})),iv=n9(ta()),iw=tm({slot:tc(),numTransactions:tc(),numSlots:tc(),samplePeriodSecs:tc()}),ik=n8(to(iw)),ix=n9(tl(tm({feeCalculator:tm({lamportsPerSignature:tc()})}))),iA=n8(tf()),iS=n8(tf()),iI=tm({err:ru,logs:to(tf()),signature:tf()}),iT=tm({result:n7(iI),subscription:tc()}),iE={"solana-client":"js/1.0.0-maintenance"};class iP{constructor(e,t){var n,r;let i,o,a,s,u,l;this._commitment=void 0,this._confirmTransactionInitialTimeout=void 0,this._rpcEndpoint=void 0,this._rpcWsEndpoint=void 0,this._rpcClient=void 0,this._rpcRequest=void 0,this._rpcBatchRequest=void 0,this._rpcWebSocket=void 0,this._rpcWebSocketConnected=!1,this._rpcWebSocketHeartbeat=null,this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketGeneration=0,this._disableBlockhashCaching=!1,this._pollingBlockhash=!1,this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]},this._nextClientSubscriptionId=0,this._subscriptionDisposeFunctionsByClientSubscriptionId={},this._subscriptionHashByClientSubscriptionId={},this._subscriptionStateChangeCallbacksByHash={},this._subscriptionCallbacksByServerSubscriptionId={},this._subscriptionsByHash={},this._subscriptionsAutoDisposedByRpc=new Set,this.getBlockHeight=(()=>{let e={};return async t=>{let{commitment:n,config:r}=n6(t),i=this._buildArgs([],n,void 0,r),o=nK(i);return e[o]=e[o]??(async()=>{try{let e=await this._rpcRequest("getBlockHeight",i),t=tt(e,n8(tc()));if("error"in t)throw new nO(t.error,"failed to get block height information");return t.result}finally{delete e[o]}})(),await e[o]}})(),t&&"string"==typeof t?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,i=t.wsEndpoint,o=t.httpHeaders,a=t.fetch,s=t.fetchMiddleware,u=t.disableRetryOnRateLimit,l=t.httpAgent),this._rpcEndpoint=function(e){if(!1===/^https?:/.test(e))throw TypeError("Endpoint URL must start with `http:` or `https:`.");return e}(e),this._rpcWsEndpoint=i||function(e){let t=e.match(nJ);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);let[n,r,i,o]=t,a=e.startsWith("https:")?"wss:":"ws:",s=null==i?null:parseInt(i.slice(1),10),u=null==s?"":`:${s+1}`;return`${a}//${r}${u}${o}`}(e),this._rpcClient=function(e,t,n,r,i,o){let a,s;let u=n||nZ;null!=o&&console.warn("You have supplied an `httpAgent` when creating a `Connection` in a browser environment.It has been ignored; `httpAgent` is only used in Node environments."),r&&(s=async(e,t)=>{let n=await new Promise((n,i)=>{try{r(e,t,(e,t)=>n([e,t]))}catch(e){i(e)}});return await u(...n)});let l=new(tv())(async(n,r)=>{let o={method:"POST",body:n,agent:a,headers:Object.assign({"Content-Type":"application/json"},t||{},iE)};try{let t,n=5,a=500;for(;t=s?await s(e,o):await u(e,o),429===t.status&&!0!==i&&(n-=1,0!==n);)console.error(`Server responded with ${t.status} ${t.statusText}. Retrying after ${a}ms delay...`),await nM(a),a*=2;let l=await t.text();t.ok?r(null,l):r(Error(`${t.status} ${t.statusText}: ${l}`))}catch(e){e instanceof Error&&r(e)}},{});return l}(e,o,a,s,u,l),this._rpcRequest=(n=this._rpcClient,(e,t)=>new Promise((r,i)=>{n.request(e,t,(e,t)=>{if(e){i(e);return}r(t)})})),this._rpcBatchRequest=(r=this._rpcClient,e=>new Promise((t,n)=>{0===e.length&&t([]);let i=e.map(e=>r.request(e.methodName,e.args));r.request(i,(e,r)=>{if(e){n(e);return}t(r)})})),this._rpcWebSocket=new nY(this._rpcWsEndpoint,{autoconnect:!1,max_reconnects:1/0}),this._rpcWebSocket.on("open",this._wsOnOpen.bind(this)),this._rpcWebSocket.on("error",this._wsOnError.bind(this)),this._rpcWebSocket.on("close",this._wsOnClose.bind(this)),this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this)),this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this)),this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this)),this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this)),this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this)),this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this)),this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}get rpcEndpoint(){return this._rpcEndpoint}async getBalanceAndContext(e,t){let{commitment:n,config:r}=n6(t),i=this._buildArgs([e.toBase58()],n,void 0,r),o=await this._rpcRequest("getBalance",i),a=tt(o,n9(tc()));if("error"in a)throw new nO(a.error,`failed to get balance for ${e.toBase58()}`);return a.result}async getBalance(e,t){return await this.getBalanceAndContext(e,t).then(e=>e.value).catch(t=>{throw Error("failed to get balance of account "+e.toBase58()+": "+t)})}async getBlockTime(e){let t=await this._rpcRequest("getBlockTime",[e]),n=tt(t,n8(tl(tc())));if("error"in n)throw new nO(n.error,`failed to get block time for slot ${e}`);return n.result}async getMinimumLedgerSlot(){let e=await this._rpcRequest("minimumLedgerSlot",[]),t=tt(e,n8(tc()));if("error"in t)throw new nO(t.error,"failed to get minimum ledger slot");return t.result}async getFirstAvailableBlock(){let e=await this._rpcRequest("getFirstAvailableBlock",[]),t=tt(e,rk);if("error"in t)throw new nO(t.error,"failed to get first available block");return t.result}async getSupply(e){let t={};t="string"==typeof e?{commitment:e}:e?{...e,commitment:e&&e.commitment||this.commitment}:{commitment:this.commitment};let n=await this._rpcRequest("getSupply",[t]),r=tt(n,rx);if("error"in r)throw new nO(r.error,"failed to get supply");return r.result}async getTokenSupply(e,t){let n=this._buildArgs([e.toBase58()],t),r=await this._rpcRequest("getTokenSupply",n),i=tt(r,n9(rA));if("error"in i)throw new nO(i.error,"failed to get token supply");return i.result}async getTokenAccountBalance(e,t){let n=this._buildArgs([e.toBase58()],t),r=await this._rpcRequest("getTokenAccountBalance",n),i=tt(r,n9(rA));if("error"in i)throw new nO(i.error,"failed to get token account balance");return i.result}async getTokenAccountsByOwner(e,t,n){let{commitment:r,config:i}=n6(n),o=[e.toBase58()];"mint"in t?o.push({mint:t.mint.toBase58()}):o.push({programId:t.programId.toBase58()});let a=this._buildArgs(o,r,"base64",i),s=await this._rpcRequest("getTokenAccountsByOwner",a),u=tt(s,rI);if("error"in u)throw new nO(u.error,`failed to get token accounts owned by account ${e.toBase58()}`);return u.result}async getParsedTokenAccountsByOwner(e,t,n){let r=[e.toBase58()];"mint"in t?r.push({mint:t.mint.toBase58()}):r.push({programId:t.programId.toBase58()});let i=this._buildArgs(r,n,"jsonParsed"),o=await this._rpcRequest("getTokenAccountsByOwner",i),a=tt(o,rE);if("error"in a)throw new nO(a.error,`failed to get token accounts owned by account ${e.toBase58()}`);return a.result}async getLargestAccounts(e){let t={...e,commitment:e&&e.commitment||this.commitment},n=t.filter||t.commitment?[t]:[],r=await this._rpcRequest("getLargestAccounts",n),i=tt(r,rP);if("error"in i)throw new nO(i.error,"failed to get largest accounts");return i.result}async getTokenLargestAccounts(e,t){let n=this._buildArgs([e.toBase58()],t),r=await this._rpcRequest("getTokenLargestAccounts",n),i=tt(r,rS);if("error"in i)throw new nO(i.error,"failed to get token largest accounts");return i.result}async getAccountInfoAndContext(e,t){let{commitment:n,config:r}=n6(t),i=this._buildArgs([e.toBase58()],n,"base64",r),o=await this._rpcRequest("getAccountInfo",i),a=tt(o,n9(tl(rC)));if("error"in a)throw new nO(a.error,`failed to get info about account ${e.toBase58()}`);return a.result}async getParsedAccountInfo(e,t){let{commitment:n,config:r}=n6(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),o=await this._rpcRequest("getAccountInfo",i),a=tt(o,n9(tl(rM)));if("error"in a)throw new nO(a.error,`failed to get info about account ${e.toBase58()}`);return a.result}async getAccountInfo(e,t){try{let n=await this.getAccountInfoAndContext(e,t);return n.value}catch(t){throw Error("failed to get info about account "+e.toBase58()+": "+t)}}async getMultipleParsedAccounts(e,t){let{commitment:n,config:r}=n6(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],n,"jsonParsed",r),a=await this._rpcRequest("getMultipleAccounts",o),s=tt(a,n9(to(tl(rM))));if("error"in s)throw new nO(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfoAndContext(e,t){let{commitment:n,config:r}=n6(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],n,"base64",r),a=await this._rpcRequest("getMultipleAccounts",o),s=tt(a,n9(to(tl(rC))));if("error"in s)throw new nO(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfo(e,t){let n=await this.getMultipleAccountsInfoAndContext(e,t);return n.value}async getStakeActivation(e,t,n){let{commitment:r,config:i}=n6(t),o=this._buildArgs([e.toBase58()],r,void 0,{...i,epoch:null!=n?n:i?.epoch}),a=await this._rpcRequest("getStakeActivation",o),s=tt(a,n8(rL));if("error"in s)throw new nO(s.error,`failed to get Stake Activation ${e.toBase58()}`);return s.result}async getProgramAccounts(e,t){let{commitment:n,config:r}=n6(t),{encoding:i,...o}=r||{},a=this._buildArgs([e.toBase58()],n,i||"base64",{...o,...o.filters?{filters:n3(o.filters)}:null}),s=await this._rpcRequest("getProgramAccounts",a),u=to(rO),l=!0===o.withContext?tt(s,n9(u)):tt(s,n8(u));if("error"in l)throw new nO(l.error,`failed to get accounts owned by program ${e.toBase58()}`);return l.result}async getParsedProgramAccounts(e,t){let{commitment:n,config:r}=n6(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),o=await this._rpcRequest("getProgramAccounts",i),a=tt(o,n8(to(rR)));if("error"in a)throw new nO(a.error,`failed to get accounts owned by program ${e.toBase58()}`);return a.result}async confirmTransaction(e,t){let n,r;if("string"==typeof e)n=e;else{if(e.abortSignal?.aborted)return Promise.reject(e.abortSignal.reason);n=e.signature}try{r=eJ().decode(n)}catch(e){throw Error("signature must be base58 encoded: "+n)}return(np(64===r.length,"signature has invalid length"),"string"==typeof e)?await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:t||this.commitment,signature:n}):"lastValidBlockHeight"in e?await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:t||this.commitment,strategy:e}):await this.confirmTransactionUsingDurableNonceStrategy({commitment:t||this.commitment,strategy:e})}getCancellationPromise(e){return new Promise((t,n)=>{null!=e&&(e.aborted?n(e.reason):e.addEventListener("abort",()=>{n(e.reason)}))})}getTransactionConfirmationPromise({commitment:e,signature:t}){let n,r;let i=!1,o=new Promise((o,a)=>{try{n=this.onSignature(t,(e,t)=>{n=void 0,o({__type:nv.PROCESSED,response:{context:t,value:e}})},e);let s=new Promise(e=>{null==n?e():r=this._onSubscriptionStateChange(n,t=>{"subscribed"===t&&e()})});(async()=>{if(await s,i)return;let n=await this.getSignatureStatus(t);if(i||null==n)return;let{context:r,value:u}=n;if(null!=u){if(u?.err)a(u.err);else{switch(e){case"confirmed":case"single":case"singleGossip":if("processed"===u.confirmationStatus)return;break;case"finalized":case"max":case"root":if("processed"===u.confirmationStatus||"confirmed"===u.confirmationStatus)return}i=!0,o({__type:nv.PROCESSED,response:{context:r,value:u}})}}})()}catch(e){a(e)}}),a=()=>{r&&(r(),r=void 0),null!=n&&(this.removeSignatureListener(n),n=void 0)};return{abortConfirmation:a,confirmationPromise:o}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:n,signature:r}}){let i,o=!1,a=new Promise(t=>{let r=async()=>{try{let t=await this.getBlockHeight(e);return t}catch(e){return -1}};(async()=>{let e=await r();if(!o){for(;e<=n;)if(await nM(1e3),o||(e=await r(),o))return;t({__type:nv.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:s,confirmationPromise:u}=this.getTransactionConfirmationPromise({commitment:e,signature:r}),l=this.getCancellationPromise(t);try{let e=await Promise.race([l,u,a]);if(e.__type===nv.PROCESSED)i=e.response;else throw new nr(r)}finally{o=!0,s()}return i}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:n,nonceAccountPubkey:r,nonceValue:i,signature:o}}){let a,s=!1,u=new Promise(t=>{let o=i,a=null,u=async()=>{try{let{context:t,value:i}=await this.getNonceAndContext(r,{commitment:e,minContextSlot:n});return a=t.slot,i?.nonce}catch(e){return o}};(async()=>{if(o=await u(),!s)for(;;){if(i!==o){t({__type:nv.NONCE_INVALID,slotInWhichNonceDidAdvance:a});return}if(await nM(2e3),s||(o=await u(),s))return}})()}),{abortConfirmation:l,confirmationPromise:c}=this.getTransactionConfirmationPromise({commitment:e,signature:o}),d=this.getCancellationPromise(t);try{let t=await Promise.race([d,c,u]);if(t.__type===nv.PROCESSED)a=t.response;else{let r;for(;;){let e=await this.getSignatureStatus(o);if(null==e)break;if(e.context.slot<(t.slotInWhichNonceDidAdvance??n)){await nM(400);continue}r=e;break}if(r?.value){let{confirmationStatus:t}=r.value;switch(e||"finalized"){case"processed":case"recent":if("processed"!==t&&"confirmed"!==t&&"finalized"!==t)throw new no(o);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==t&&"finalized"!==t)throw new no(o);break;case"finalized":case"max":case"root":if("finalized"!==t)throw new no(o)}a={context:r.context,value:{err:r.value.err}}}else throw new no(o)}}finally{s=!0,l()}return a}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:e,signature:t}){let n,r;let i=new Promise(t=>{let r=this._confirmTransactionInitialTimeout||6e4;switch(e){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":r=this._confirmTransactionInitialTimeout||3e4}n=setTimeout(()=>t({__type:nv.TIMED_OUT,timeoutMs:r}),r)}),{abortConfirmation:o,confirmationPromise:a}=this.getTransactionConfirmationPromise({commitment:e,signature:t});try{let e=await Promise.race([a,i]);if(e.__type===nv.PROCESSED)r=e.response;else throw new ni(t,e.timeoutMs/1e3)}finally{clearTimeout(n),o()}return r}async getClusterNodes(){let e=await this._rpcRequest("getClusterNodes",[]),t=tt(e,n8(to(rH)));if("error"in t)throw new nO(t.error,"failed to get cluster nodes");return t.result}async getVoteAccounts(e){let t=this._buildArgs([],e),n=await this._rpcRequest("getVoteAccounts",t),r=tt(n,rZ);if("error"in r)throw new nO(r.error,"failed to get vote accounts");return r.result}async getSlot(e){let{commitment:t,config:n}=n6(e),r=this._buildArgs([],t,void 0,n),i=await this._rpcRequest("getSlot",r),o=tt(i,n8(tc()));if("error"in o)throw new nO(o.error,"failed to get slot");return o.result}async getSlotLeader(e){let{commitment:t,config:n}=n6(e),r=this._buildArgs([],t,void 0,n),i=await this._rpcRequest("getSlotLeader",r),o=tt(i,n8(tf()));if("error"in o)throw new nO(o.error,"failed to get slot leader");return o.result}async getSlotLeaders(e,t){let n=await this._rpcRequest("getSlotLeaders",[e,t]),r=tt(n,n8(to(n0)));if("error"in r)throw new nO(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){let{context:n,value:r}=await this.getSignatureStatuses([e],t);np(1===r.length);let i=r[0];return{context:n,value:i}}async getSignatureStatuses(e,t){let n=[e];t&&n.push(t);let r=await this._rpcRequest("getSignatureStatuses",n),i=tt(r,rQ);if("error"in i)throw new nO(i.error,"failed to get signature status");return i.result}async getTransactionCount(e){let{commitment:t,config:n}=n6(e),r=this._buildArgs([],t,void 0,n),i=await this._rpcRequest("getTransactionCount",r),o=tt(i,n8(tc()));if("error"in o)throw new nO(o.error,"failed to get transaction count");return o.result}async getTotalSupply(e){let t=await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0});return t.value.total}async getInflationGovernor(e){let t=this._buildArgs([],e),n=await this._rpcRequest("getInflationGovernor",t),r=tt(n,rg);if("error"in r)throw new nO(r.error,"failed to get inflation");return r.result}async getInflationReward(e,t,n){let{commitment:r,config:i}=n6(n),o=this._buildArgs([e.map(e=>e.toBase58())],r,void 0,{...i,epoch:null!=t?t:i?.epoch}),a=await this._rpcRequest("getInflationReward",o),s=tt(a,rn);if("error"in s)throw new nO(s.error,"failed to get inflation reward");return s.result}async getInflationRate(){let e=await this._rpcRequest("getInflationRate",[]),t=tt(e,ry);if("error"in t)throw new nO(t.error,"failed to get inflation rate");return t.result}async getEpochInfo(e){let{commitment:t,config:n}=n6(e),r=this._buildArgs([],t,void 0,n),i=await this._rpcRequest("getEpochInfo",r),o=tt(i,r_);if("error"in o)throw new nO(o.error,"failed to get epoch info");return o.result}async getEpochSchedule(){let e=await this._rpcRequest("getEpochSchedule",[]),t=tt(e,rv);if("error"in t)throw new nO(t.error,"failed to get epoch schedule");let n=t.result;return new nG(n.slotsPerEpoch,n.leaderScheduleSlotOffset,n.warmup,n.firstNormalEpoch,n.firstNormalSlot)}async getLeaderSchedule(){let e=await this._rpcRequest("getLeaderSchedule",[]),t=tt(e,rw);if("error"in t)throw new nO(t.error,"failed to get leader schedule");return t.result}async getMinimumBalanceForRentExemption(e,t){let n=this._buildArgs([e],t),r=await this._rpcRequest("getMinimumBalanceForRentExemption",n),i=tt(r,rJ);return"error"in i?(console.warn("Unable to fetch minimum balance for rent exemption"),0):i.result}async getRecentBlockhashAndContext(e){let t=this._buildArgs([],e),n=await this._rpcRequest("getRecentBlockhash",t),r=tt(n,ib);if("error"in r)throw new nO(r.error,"failed to get recent blockhash");return r.result}async getRecentPerformanceSamples(e){let t=await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),n=tt(t,ik);if("error"in n)throw new nO(n.error,"failed to get recent performance samples");return n.result}async getFeeCalculatorForBlockhash(e,t){let n=this._buildArgs([e],t),r=await this._rpcRequest("getFeeCalculatorForBlockhash",n),i=tt(r,ix);if("error"in i)throw new nO(i.error,"failed to get fee calculator");let{context:o,value:a}=i.result;return{context:o,value:null!==a?a.feeCalculator:null}}async getFeeForMessage(e,t){let n=t9(e.serialize()).toString("base64"),r=this._buildArgs([n],t),i=await this._rpcRequest("getFeeForMessage",r),o=tt(i,n9(tl(tc())));if("error"in o)throw new nO(o.error,"failed to get fee for message");if(null===o.result)throw Error("invalid blockhash");return o.result}async getRecentPrioritizationFees(e){let t=e?.lockedWritableAccounts?.map(e=>e.toBase58()),n=t?.length?[t]:[],r=await this._rpcRequest("getRecentPrioritizationFees",n),i=tt(r,rb);if("error"in i)throw new nO(i.error,"failed to get recent prioritization fees");return i.result}async getRecentBlockhash(e){try{let t=await this.getRecentBlockhashAndContext(e);return t.value}catch(e){throw Error("failed to get recent blockhash: "+e)}}async getLatestBlockhash(e){try{let t=await this.getLatestBlockhashAndContext(e);return t.value}catch(e){throw Error("failed to get recent blockhash: "+e)}}async getLatestBlockhashAndContext(e){let{commitment:t,config:n}=n6(e),r=this._buildArgs([],t,void 0,n),i=await this._rpcRequest("getLatestBlockhash",r),o=tt(i,i_);if("error"in o)throw new nO(o.error,"failed to get latest blockhash");return o.result}async isBlockhashValid(e,t){let{commitment:n,config:r}=n6(t),i=this._buildArgs([e],n,void 0,r),o=await this._rpcRequest("isBlockhashValid",i),a=tt(o,iv);if("error"in a)throw new nO(a.error,"failed to determine if the blockhash `"+e+"`is valid");return a.result}async getVersion(){let e=await this._rpcRequest("getVersion",[]),t=tt(e,n8(rd));if("error"in t)throw new nO(t.error,"failed to get version");return t.result}async getGenesisHash(){let e=await this._rpcRequest("getGenesisHash",[]),t=tt(e,n8(tf()));if("error"in t)throw new nO(t.error,"failed to get genesis hash");return t.result}async getBlock(e,t){let{commitment:n,config:r}=n6(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),o=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{let e=tt(o,il);if("error"in e)throw e.error;return e.result}case"none":{let e=tt(o,iu);if("error"in e)throw e.error;return e.result}default:{let e=tt(o,is);if("error"in e)throw e.error;let{result:t}=e;return t?{...t,transactions:t.transactions.map(({transaction:e,meta:t,version:n})=>({meta:t,transaction:{...e,message:re(n,e.message)},version:n}))}:null}}}catch(e){throw new nO(e,"failed to get confirmed block")}}async getParsedBlock(e,t){let{commitment:n,config:r}=n6(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),o=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{let e=tt(o,id);if("error"in e)throw e.error;return e.result}case"none":{let e=tt(o,ip);if("error"in e)throw e.error;return e.result}default:{let e=tt(o,ic);if("error"in e)throw e.error;return e.result}}}catch(e){throw new nO(e,"failed to get block")}}async getBlockProduction(e){let t,n;if("string"==typeof e)n=e;else if(e){let{commitment:r,...i}=e;n=r,t=i}let r=this._buildArgs([],n,"base64",t),i=await this._rpcRequest("getBlockProduction",r),o=tt(i,rm);if("error"in o)throw new nO(o.error,"failed to get block production information");return o.result}async getTransaction(e,t){let{commitment:n,config:r}=n6(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),o=await this._rpcRequest("getTransaction",i),a=tt(o,ig);if("error"in a)throw new nO(a.error,"failed to get transaction");let s=a.result;return s?{...s,transaction:{...s.transaction,message:re(s.version,s.transaction.message)}}:s}async getParsedTransaction(e,t){let{commitment:n,config:r}=n6(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),o=await this._rpcRequest("getTransaction",i),a=tt(o,iy);if("error"in a)throw new nO(a.error,"failed to get transaction");return a.result}async getParsedTransactions(e,t){let{commitment:n,config:r}=n6(t),i=e.map(e=>{let t=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r);return{methodName:"getTransaction",args:t}}),o=await this._rpcBatchRequest(i),a=o.map(e=>{let t=tt(e,iy);if("error"in t)throw new nO(t.error,"failed to get transactions");return t.result});return a}async getTransactions(e,t){let{commitment:n,config:r}=n6(t),i=e.map(e=>{let t=this._buildArgsAtLeastConfirmed([e],n,void 0,r);return{methodName:"getTransaction",args:t}}),o=await this._rpcBatchRequest(i),a=o.map(e=>{let t=tt(e,ig);if("error"in t)throw new nO(t.error,"failed to get transactions");let n=t.result;return n?{...n,transaction:{...n.transaction,message:re(n.version,n.transaction.message)}}:n});return a}async getConfirmedBlock(e,t){let n=this._buildArgsAtLeastConfirmed([e],t),r=await this._rpcRequest("getConfirmedBlock",n),i=tt(r,ih);if("error"in i)throw new nO(i.error,"failed to get confirmed block");let o=i.result;if(!o)throw Error("Confirmed block "+e+" not found");let a={...o,transactions:o.transactions.map(({transaction:e,meta:t})=>{let n=new ny(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...a,transactions:a.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:nx.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){let r=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),i=await this._rpcRequest("getBlocks",r),o=tt(i,n8(to(tc())));if("error"in o)throw new nO(o.error,"failed to get blocks");return o.result}async getBlockSignatures(e,t){let n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=await this._rpcRequest("getBlock",n),i=tt(r,im);if("error"in i)throw new nO(i.error,"failed to get block");let o=i.result;if(!o)throw Error("Block "+e+" not found");return o}async getConfirmedBlockSignatures(e,t){let n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=await this._rpcRequest("getConfirmedBlock",n),i=tt(r,im);if("error"in i)throw new nO(i.error,"failed to get confirmed block");let o=i.result;if(!o)throw Error("Confirmed block "+e+" not found");return o}async getConfirmedTransaction(e,t){let n=this._buildArgsAtLeastConfirmed([e],t),r=await this._rpcRequest("getConfirmedTransaction",n),i=tt(r,ig);if("error"in i)throw new nO(i.error,"failed to get transaction");let o=i.result;if(!o)return o;let a=new ny(o.transaction.message),s=o.transaction.signatures;return{...o,transaction:nx.populate(a,s)}}async getParsedConfirmedTransaction(e,t){let n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),r=await this._rpcRequest("getConfirmedTransaction",n),i=tt(r,iy);if("error"in i)throw new nO(i.error,"failed to get confirmed transaction");return i.result}async getParsedConfirmedTransactions(e,t){let n=e.map(e=>{let n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed");return{methodName:"getConfirmedTransaction",args:n}}),r=await this._rpcBatchRequest(n),i=r.map(e=>{let t=tt(e,iy);if("error"in t)throw new nO(t.error,"failed to get confirmed transactions");return t.result});return i}async getConfirmedSignaturesForAddress(e,t,n){let r={},i=await this.getFirstAvailableBlock();for(;!("until"in r)&&!(--t<=0)&&!(t0&&(r.until=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}let o=await this.getSlot("finalized");for(;!("before"in r)&&!(++n>o);)try{let e=await this.getConfirmedBlockSignatures(n);e.signatures.length>0&&(r.before=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}let a=await this.getConfirmedSignaturesForAddress2(e,r);return a.map(e=>e.signature)}async getConfirmedSignaturesForAddress2(e,t,n){let r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),i=await this._rpcRequest("getConfirmedSignaturesForAddress2",r),o=tt(i,rN);if("error"in o)throw new nO(o.error,"failed to get confirmed signatures for address");return o.result}async getSignaturesForAddress(e,t,n){let r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),i=await this._rpcRequest("getSignaturesForAddress",r),o=tt(i,rD);if("error"in o)throw new nO(o.error,"failed to get signatures for address");return o.result}async getAddressLookupTable(e,t){let{context:n,value:r}=await this.getAccountInfoAndContext(e,t),i=null;return null!==r&&(i=new nX({key:e,state:nX.deserialize(r.data)})),{context:n,value:i}}async getNonceAndContext(e,t){let{context:n,value:r}=await this.getAccountInfoAndContext(e,t),i=null;return null!==r&&(i=nF.fromAccountData(r.data)),{context:n,value:i}}async getNonce(e,t){return await this.getNonceAndContext(e,t).then(e=>e.value).catch(t=>{throw Error("failed to get nonce for account "+e.toBase58()+": "+t)})}async requestAirdrop(e,t){let n=await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),r=tt(n,iA);if("error"in r)throw new nO(r.error,`airdrop to ${e.toBase58()} failed`);return r.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await nM(100);let e=Date.now()-this._blockhashInfo.lastFetch;if(null!==this._blockhashInfo.latestBlockhash&&!(e>=3e4))return this._blockhashInfo.latestBlockhash}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=!0;try{let e=Date.now(),t=this._blockhashInfo.latestBlockhash,n=t?t.blockhash:null;for(let e=0;e<50;e++){let e=await this.getLatestBlockhash("finalized");if(n!==e.blockhash)return this._blockhashInfo={latestBlockhash:e,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]},e;await nM(200)}throw Error(`Unable to obtain a new blockhash after ${Date.now()-e}ms`)}finally{this._pollingBlockhash=!1}}async getStakeMinimumDelegation(e){let{commitment:t,config:n}=n6(e),r=this._buildArgs([],t,"base64",n),i=await this._rpcRequest("getStakeMinimumDelegation",r),o=tt(i,n9(tc()));if("error"in o)throw new nO(o.error,"failed to get stake minimum delegation");return o.result}async simulateTransaction(e,t,n){let r;if("message"in e){let r=e.serialize(),i=a.Buffer.from(r).toString("base64");if(Array.isArray(t)||void 0!==n)throw Error("Invalid arguments");let o=t||{};o.encoding="base64","commitment"in o||(o.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(o.innerInstructions=t.innerInstructions);let s=[i,o],u=await this._rpcRequest("simulateTransaction",s),l=tt(u,rh);if("error"in l)throw Error("failed to simulate transaction: "+l.error.message);return l.result}if(e instanceof nx?((r=new nx).feePayer=e.feePayer,r.instructions=e.instructions,r.nonceInfo=e.nonceInfo,r.signatures=e.signatures):(r=nx.populate(e))._message=r._json=void 0,void 0!==t&&!Array.isArray(t))throw Error("Invalid arguments");if(r.nonceInfo&&t)r.sign(...t);else{let e=this._disableBlockhashCaching;for(;;){let n=await this._blockhashWithExpiryBlockHeight(e);if(r.lastValidBlockHeight=n.lastValidBlockHeight,r.recentBlockhash=n.blockhash,!t)break;if(r.sign(...t),!r.signature)throw Error("!signature");let i=r.signature.toString("base64");if(this._blockhashInfo.simulatedSignatures.includes(i)||this._blockhashInfo.transactionSignatures.includes(i))e=!0;else{this._blockhashInfo.simulatedSignatures.push(i);break}}}let i=r._compile(),o=i.serialize(),s=r._serialize(o),u=s.toString("base64"),l={encoding:"base64",commitment:this.commitment};if(n){let e=(Array.isArray(n)?n:i.nonProgramIds()).map(e=>e.toBase58());l.accounts={encoding:"base64",addresses:e}}t&&(l.sigVerify=!0),t&&"object"==typeof t&&"innerInstructions"in t&&(l.innerInstructions=t.innerInstructions);let c=[u,l],d=await this._rpcRequest("simulateTransaction",c),p=tt(d,rh);if("error"in p){let e;if("data"in p.error&&(e=p.error.data.logs)&&Array.isArray(e)){let t="\n ",n=t+e.join(t);console.error(p.error.message,n)}throw new nC({action:"simulate",signature:"",transactionMessage:p.error.message,logs:e})}return p.result}async sendTransaction(e,t,n){if("version"in e){if(t&&Array.isArray(t))throw Error("Invalid arguments");let n=e.serialize();return await this.sendRawTransaction(n,t)}if(void 0===t||!Array.isArray(t))throw Error("Invalid arguments");if(e.nonceInfo)e.sign(...t);else{let n=this._disableBlockhashCaching;for(;;){let r=await this._blockhashWithExpiryBlockHeight(n);if(e.lastValidBlockHeight=r.lastValidBlockHeight,e.recentBlockhash=r.blockhash,e.sign(...t),!e.signature)throw Error("!signature");let i=e.signature.toString("base64");if(this._blockhashInfo.transactionSignatures.includes(i))n=!0;else{this._blockhashInfo.transactionSignatures.push(i);break}}}let r=e.serialize();return await this.sendRawTransaction(r,n)}async sendRawTransaction(e,t){let n=t9(e).toString("base64"),r=await this.sendEncodedTransaction(n,t);return r}async sendEncodedTransaction(e,t){let n={encoding:"base64"},r=t&&t.skipPreflight,i=!0===r?"processed":t&&t.preflightCommitment||this.commitment;t&&null!=t.maxRetries&&(n.maxRetries=t.maxRetries),t&&null!=t.minContextSlot&&(n.minContextSlot=t.minContextSlot),r&&(n.skipPreflight=r),i&&(n.preflightCommitment=i);let o=[e,n],a=await this._rpcRequest("sendTransaction",o),s=tt(a,iS);if("error"in s){let e;throw"data"in s.error&&(e=s.error.data.logs),new nC({action:r?"send":"simulate",signature:"",transactionMessage:s.error.message,logs:e})}return s.result}_wsOnOpen(){this._rpcWebSocketConnected=!0,this._rpcWebSocketHeartbeat=setInterval(()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch{}})()},5e3),this._updateSubscriptions()}_wsOnError(e){this._rpcWebSocketConnected=!1,console.error("ws error:",e.message)}_wsOnClose(e){if(this._rpcWebSocketConnected=!1,this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER,this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null),this._rpcWebSocketHeartbeat&&(clearInterval(this._rpcWebSocketHeartbeat),this._rpcWebSocketHeartbeat=null),1e3===e){this._updateSubscriptions();return}this._subscriptionCallbacksByServerSubscriptionId={},Object.entries(this._subscriptionsByHash).forEach(([e,t])=>{this._setSubscription(e,{...t,state:"pending"})})}_setSubscription(e,t){let n=this._subscriptionsByHash[e]?.state;if(this._subscriptionsByHash[e]=t,n!==t.state){let n=this._subscriptionStateChangeCallbacksByHash[e];n&&n.forEach(e=>{try{e(t.state)}catch{}})}}_onSubscriptionStateChange(e,t){let n=this._subscriptionHashByClientSubscriptionId[e];if(null==n)return()=>{};let r=this._subscriptionStateChangeCallbacksByHash[n]||=new Set;return r.add(t),()=>{r.delete(t),0===r.size&&delete this._subscriptionStateChangeCallbacksByHash[n]}}async _updateSubscriptions(){if(0===Object.keys(this._subscriptionsByHash).length){this._rpcWebSocketConnected&&(this._rpcWebSocketConnected=!1,this._rpcWebSocketIdleTimeout=setTimeout(()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(e){e instanceof Error&&console.log(`Error when closing socket connection: ${e.message}`)}},500));return}if(null!==this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketConnected=!0),!this._rpcWebSocketConnected){this._rpcWebSocket.connect();return}let e=this._rpcWebSocketGeneration,t=()=>e===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map(async e=>{let n=this._subscriptionsByHash[e];if(void 0!==n)switch(n.state){case"pending":case"unsubscribed":if(0===n.callbacks.size){delete this._subscriptionsByHash[e],"unsubscribed"===n.state&&delete this._subscriptionCallbacksByServerSubscriptionId[n.serverSubscriptionId],await this._updateSubscriptions();return}await (async()=>{let{args:r,method:i}=n;try{this._setSubscription(e,{...n,state:"subscribing"});let t=await this._rpcWebSocket.call(i,r);this._setSubscription(e,{...n,serverSubscriptionId:t,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[t]=n.callbacks,await this._updateSubscriptions()}catch(o){if(o instanceof Error&&console.error(`${i} error for argument`,r,o.message),!t())return;this._setSubscription(e,{...n,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":0===n.callbacks.size&&await (async()=>{let{serverSubscriptionId:r,unsubscribeMethod:i}=n;if(this._subscriptionsAutoDisposedByRpc.has(r))this._subscriptionsAutoDisposedByRpc.delete(r);else{this._setSubscription(e,{...n,state:"unsubscribing"}),this._setSubscription(e,{...n,state:"unsubscribing"});try{await this._rpcWebSocket.call(i,[r])}catch(r){if(r instanceof Error&&console.error(`${i} error:`,r.message),!t())return;this._setSubscription(e,{...n,state:"subscribed"}),await this._updateSubscriptions();return}}this._setSubscription(e,{...n,state:"unsubscribed"}),await this._updateSubscriptions()})()}}))}_handleServerNotification(e,t){let n=this._subscriptionCallbacksByServerSubscriptionId[e];void 0!==n&&n.forEach(e=>{try{e(...t)}catch(e){console.error(e)}})}_wsOnAccountNotification(e){let{result:t,subscription:n}=tt(e,rF);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){let n=this._nextClientSubscriptionId++,r=nK([e.method,t]),i=this._subscriptionsByHash[r];return void 0===i?this._subscriptionsByHash[r]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:i.callbacks.add(e.callback),this._subscriptionHashByClientSubscriptionId[n]=r,this._subscriptionDisposeFunctionsByClientSubscriptionId[n]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[n],delete this._subscriptionHashByClientSubscriptionId[n];let t=this._subscriptionsByHash[r];np(void 0!==t,`Could not find a \`Subscription\` when tearing down client subscription #${n}`),t.callbacks.delete(e.callback),await this._updateSubscriptions()},this._updateSubscriptions(),n}onAccountChange(e,t,n){let{commitment:r,config:i}=n6(n),o=this._buildArgs([e.toBase58()],r||this._commitment||"finalized","base64",i);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},o)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){let{result:t,subscription:n}=tt(e,rj);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,r){let{commitment:i,config:o}=n6(n),a=this._buildArgs([e.toBase58()],i||this._commitment||"finalized","base64",o||(r?{filters:n3(r)}:void 0));return this._makeSubscription({callback:t,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},a)}async removeProgramAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"program account change")}onLogs(e,t,n){let r=this._buildArgs(["object"==typeof e?{mentions:[e.toString()]}:e],n||this._commitment||"finalized");return this._makeSubscription({callback:t,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},r)}async removeOnLogsListener(e){await this._unsubscribeClientSubscription(e,"logs")}_wsOnLogsNotification(e){let{result:t,subscription:n}=tt(e,iT);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){let{result:t,subscription:n}=tt(e,rz);this._handleServerNotification(n,[t])}onSlotChange(e){return this._makeSubscription({callback:e,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(e){await this._unsubscribeClientSubscription(e,"slot change")}_wsOnSlotUpdatesNotification(e){let{result:t,subscription:n}=tt(e,rW);this._handleServerNotification(n,[t])}onSlotUpdate(e){return this._makeSubscription({callback:e,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(e){await this._unsubscribeClientSubscription(e,"slot update")}async _unsubscribeClientSubscription(e,t){let n=this._subscriptionDisposeFunctionsByClientSubscriptionId[e];n?await n():console.warn(`Ignored unsubscribe request because an active subscription with id \`${e}\` for '${t}' events could not be found.`)}_buildArgs(e,t,n,r){let i=t||this._commitment;if(i||n||r){let t={};n&&(t.encoding=n),i&&(t.commitment=i),r&&(t=Object.assign(t,r)),e.push(t)}return e}_buildArgsAtLeastConfirmed(e,t,n,r){let i=t||this._commitment;if(i&&!["confirmed","finalized"].includes(i))throw Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(e,t,n,r)}_wsOnSignatureNotification(e){let{result:t,subscription:n}=tt(e,r$);"receivedSignature"!==t.value&&this._subscriptionsAutoDisposedByRpc.add(n),this._handleServerNotification(n,"receivedSignature"===t.value?[{type:"received"},t.context]:[{type:"status",result:t.value},t.context])}onSignature(e,t,n){let r=this._buildArgs([e],n||this._commitment||"finalized"),i=this._makeSubscription({callback:(e,n)=>{if("status"===e.type){t(e.result,n);try{this.removeSignatureListener(i)}catch(e){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},r);return i}onSignatureWithOptions(e,t,n){let{commitment:r,...i}={...n,commitment:n&&n.commitment||this._commitment||"finalized"},o=this._buildArgs([e],r,void 0,i),a=this._makeSubscription({callback:(e,n)=>{t(e,n);try{this.removeSignatureListener(a)}catch(e){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},o);return a}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){let{result:t,subscription:n}=tt(e,rK);this._handleServerNotification(n,[t])}onRootChange(e){return this._makeSubscription({callback:e,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(e){await this._unsubscribeClientSubscription(e,"root change")}}class iC{constructor(e){this._keypair=void 0,this._keypair=e??t6()}static generate(){return new iC(t6())}static fromSecretKey(e,t){if(64!==e.byteLength)throw Error("bad secret key size");let n=e.slice(32,64);if(!t||!t.skipValidation){let t=e.slice(0,32),r=t3(t);for(let e=0;e<32;e++)if(n[e]!==r[e])throw Error("provided secretKey is invalid")}return new iC({publicKey:n,secretKey:e})}static fromSeed(e){let t=t3(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new iC({publicKey:t,secretKey:n})}get publicKey(){return new nn(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:e2.n_([e2.Jq("instruction"),nj("recentSlot"),e2.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:e2.n_([e2.Jq("instruction")])},ExtendLookupTable:{index:2,layout:e2.n_([e2.Jq("instruction"),nj(),e2.A9(ns(),e2.cv(e2.Jq(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:e2.n_([e2.Jq("instruction")])},CloseLookupTable:{index:4,layout:e2.n_([e2.Jq("instruction")])}}),new nn("AddressLookupTab1e1111111111111111111111111");let iO=Object.freeze({RequestUnits:{index:0,layout:e2.n_([e2.u8("instruction"),e2.Jq("units"),e2.Jq("additionalFee")])},RequestHeapFrame:{index:1,layout:e2.n_([e2.u8("instruction"),e2.Jq("bytes")])},SetComputeUnitLimit:{index:2,layout:e2.n_([e2.u8("instruction"),e2.Jq("units")])},SetComputeUnitPrice:{index:3,layout:e2.n_([e2.u8("instruction"),nj("microLamports")])}});class iB{constructor(){}static requestUnits(e){let t=iO.RequestUnits,n=nR(t,e);return new nk({keys:[],programId:this.programId,data:n})}static requestHeapFrame(e){let t=iO.RequestHeapFrame,n=nR(t,e);return new nk({keys:[],programId:this.programId,data:n})}static setComputeUnitLimit(e){let t=iO.SetComputeUnitLimit,n=nR(t,e);return new nk({keys:[],programId:this.programId,data:n})}static setComputeUnitPrice(e){let t=iO.SetComputeUnitPrice,n=nR(t,{microLamports:BigInt(e.microLamports)});return new nk({keys:[],programId:this.programId,data:n})}}iB.programId=new nn("ComputeBudget111111111111111111111111111111");let iM=e2.n_([e2.u8("numSignatures"),e2.u8("padding"),e2.KB("signatureOffset"),e2.KB("signatureInstructionIndex"),e2.KB("publicKeyOffset"),e2.KB("publicKeyInstructionIndex"),e2.KB("messageDataOffset"),e2.KB("messageDataSize"),e2.KB("messageInstructionIndex")]);class iR{constructor(){}static createInstructionWithPublicKey(e){let{publicKey:t,message:n,signature:r,instructionIndex:i}=e;np(32===t.length,`Public Key must be 32 bytes but received ${t.length} bytes`),np(64===r.length,`Signature must be 64 bytes but received ${r.length} bytes`);let o=iM.span,s=o+t.length,u=s+r.length,l=a.Buffer.alloc(u+n.length),c=null==i?65535:i;return iM.encode({numSignatures:1,padding:0,signatureOffset:s,signatureInstructionIndex:c,publicKeyOffset:o,publicKeyInstructionIndex:c,messageDataOffset:u,messageDataSize:n.length,messageInstructionIndex:c},l),l.fill(t,o),l.fill(r,s),l.fill(n,u),new nk({keys:[],programId:iR.programId,data:l})}static createInstructionWithPrivateKey(e){let{privateKey:t,message:n,instructionIndex:r}=e;np(64===t.length,`Private key must be 64 bytes but received ${t.length} bytes`);try{let e=iC.fromSecretKey(t),i=e.publicKey.toBytes(),o=t5(n,e.secretKey);return this.createInstructionWithPublicKey({publicKey:i,message:n,signature:o,instructionIndex:r})}catch(e){throw Error(`Error creating instruction; ${e}`)}}}iR.programId=new nn("Ed25519SigVerify111111111111111111111111111");let iL=(e,t)=>{let n=t2.sign(e,t);return[n.toCompactRawBytes(),n.recovery]};t2.utils.isValidPrivateKey;let iN=t2.getPublicKey,iD=e2.n_([e2.u8("numSignatures"),e2.KB("signatureOffset"),e2.u8("signatureInstructionIndex"),e2.KB("ethAddressOffset"),e2.u8("ethAddressInstructionIndex"),e2.KB("messageDataOffset"),e2.KB("messageDataSize"),e2.u8("messageInstructionIndex"),e2.Ik(20,"ethAddress"),e2.Ik(64,"signature"),e2.u8("recoveryId")]);class iF{constructor(){}static publicKeyToEthAddress(e){np(64===e.length,`Public key must be 64 bytes but received ${e.length} bytes`);try{return a.Buffer.from(tj(t9(e))).slice(-20)}catch(e){throw Error(`Error constructing Ethereum address: ${e}`)}}static createInstructionWithPublicKey(e){let{publicKey:t,message:n,signature:r,recoveryId:i,instructionIndex:o}=e;return iF.createInstructionWithEthAddress({ethAddress:iF.publicKeyToEthAddress(t),message:n,signature:r,recoveryId:i,instructionIndex:o})}static createInstructionWithEthAddress(e){let t;let{ethAddress:n,message:r,signature:i,recoveryId:o,instructionIndex:s=0}=e;np(20===(t="string"==typeof n?n.startsWith("0x")?a.Buffer.from(n.substr(2),"hex"):a.Buffer.from(n,"hex"):n).length,`Address must be 20 bytes but received ${t.length} bytes`);let u=12+t.length,l=u+i.length+1,c=a.Buffer.alloc(iD.span+r.length);return iD.encode({numSignatures:1,signatureOffset:u,signatureInstructionIndex:s,ethAddressOffset:12,ethAddressInstructionIndex:s,messageDataOffset:l,messageDataSize:r.length,messageInstructionIndex:s,signature:t9(i),ethAddress:t9(t),recoveryId:o},c),c.fill(t9(r),iD.span),new nk({keys:[],programId:iF.programId,data:c})}static createInstructionWithPrivateKey(e){let{privateKey:t,message:n,instructionIndex:r}=e;np(32===t.length,`Private key must be 32 bytes but received ${t.length} bytes`);try{let e=t9(t),i=iN(e,!1).slice(1),o=a.Buffer.from(tj(t9(n))),[s,u]=iL(o,e);return this.createInstructionWithPublicKey({publicKey:i,message:n,signature:s,recoveryId:u,instructionIndex:r})}catch(e){throw Error(`Error creating instruction; ${e}`)}}}iF.programId=new nn("KeccakSecp256k11111111111111111111111111111");let iq=new nn("StakeConfig11111111111111111111111111111111");class ij{constructor(e,t,n){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=e,this.epoch=t,this.custodian=n}}ij.default=new ij(0,0,nn.default);let iU=Object.freeze({Initialize:{index:0,layout:e2.n_([e2.Jq("instruction"),((e="authorized")=>e2.n_([ns("staker"),ns("withdrawer")],e))(),((e="lockup")=>e2.n_([e2.gM("unixTimestamp"),e2.gM("epoch"),ns("custodian")],e))()])},Authorize:{index:1,layout:e2.n_([e2.Jq("instruction"),ns("newAuthorized"),e2.Jq("stakeAuthorizationType")])},Delegate:{index:2,layout:e2.n_([e2.Jq("instruction")])},Split:{index:3,layout:e2.n_([e2.Jq("instruction"),e2.gM("lamports")])},Withdraw:{index:4,layout:e2.n_([e2.Jq("instruction"),e2.gM("lamports")])},Deactivate:{index:5,layout:e2.n_([e2.Jq("instruction")])},Merge:{index:7,layout:e2.n_([e2.Jq("instruction")])},AuthorizeWithSeed:{index:8,layout:e2.n_([e2.Jq("instruction"),ns("newAuthorized"),e2.Jq("stakeAuthorizationType"),nl("authoritySeed"),ns("authorityOwner")])}});Object.freeze({Staker:{index:0},Withdrawer:{index:1}});class iz{constructor(){}static initialize(e){let{stakePubkey:t,authorized:n,lockup:r}=e,i=r||ij.default,o=iU.Initialize,a=nR(o,{authorized:{staker:t9(n.staker.toBuffer()),withdrawer:t9(n.withdrawer.toBuffer())},lockup:{unixTimestamp:i.unixTimestamp,epoch:i.epoch,custodian:t9(i.custodian.toBuffer())}}),s={keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:nE,isSigner:!1,isWritable:!1}],programId:this.programId,data:a};return new nk(s)}static createAccountWithSeed(e){let t=new nx;t.add(nz.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.stakePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:this.space,programId:this.programId}));let{stakePubkey:n,authorized:r,lockup:i}=e;return t.add(this.initialize({stakePubkey:n,authorized:r,lockup:i}))}static createAccount(e){let t=new nx;t.add(nz.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.stakePubkey,lamports:e.lamports,space:this.space,programId:this.programId}));let{stakePubkey:n,authorized:r,lockup:i}=e;return t.add(this.initialize({stakePubkey:n,authorized:r,lockup:i}))}static delegate(e){let{stakePubkey:t,authorizedPubkey:n,votePubkey:r}=e,i=iU.Delegate,o=nR(i);return new nx().add({keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:nI,isSigner:!1,isWritable:!1},{pubkey:nP,isSigner:!1,isWritable:!1},{pubkey:iq,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}],programId:this.programId,data:o})}static authorize(e){let{stakePubkey:t,authorizedPubkey:n,newAuthorizedPubkey:r,stakeAuthorizationType:i,custodianPubkey:o}=e,a=iU.Authorize,s=nR(a,{newAuthorized:t9(r.toBuffer()),stakeAuthorizationType:i.index}),u=[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:nI,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!0,isWritable:!1}];return o&&u.push({pubkey:o,isSigner:!0,isWritable:!1}),new nx().add({keys:u,programId:this.programId,data:s})}static authorizeWithSeed(e){let{stakePubkey:t,authorityBase:n,authoritySeed:r,authorityOwner:i,newAuthorizedPubkey:o,stakeAuthorizationType:a,custodianPubkey:s}=e,u=iU.AuthorizeWithSeed,l=nR(u,{newAuthorized:t9(o.toBuffer()),stakeAuthorizationType:a.index,authoritySeed:r,authorityOwner:t9(i.toBuffer())}),c=[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!0,isWritable:!1},{pubkey:nI,isSigner:!1,isWritable:!1}];return s&&c.push({pubkey:s,isSigner:!0,isWritable:!1}),new nx().add({keys:c,programId:this.programId,data:l})}static splitInstruction(e){let{stakePubkey:t,authorizedPubkey:n,splitStakePubkey:r,lamports:i}=e,o=iU.Split,a=nR(o,{lamports:i});return new nk({keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!0,isWritable:!1}],programId:this.programId,data:a})}static split(e,t){let n=new nx;return n.add(nz.createAccount({fromPubkey:e.authorizedPubkey,newAccountPubkey:e.splitStakePubkey,lamports:t,space:this.space,programId:this.programId})),n.add(this.splitInstruction(e))}static splitWithSeed(e,t){let{stakePubkey:n,authorizedPubkey:r,splitStakePubkey:i,basePubkey:o,seed:a,lamports:s}=e,u=new nx;return u.add(nz.allocate({accountPubkey:i,basePubkey:o,seed:a,space:this.space,programId:this.programId})),t&&t>0&&u.add(nz.transfer({fromPubkey:e.authorizedPubkey,toPubkey:i,lamports:t})),u.add(this.splitInstruction({stakePubkey:n,authorizedPubkey:r,splitStakePubkey:i,lamports:s}))}static merge(e){let{stakePubkey:t,sourceStakePubKey:n,authorizedPubkey:r}=e,i=iU.Merge,o=nR(i);return new nx().add({keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:nI,isSigner:!1,isWritable:!1},{pubkey:nP,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!0,isWritable:!1}],programId:this.programId,data:o})}static withdraw(e){let{stakePubkey:t,authorizedPubkey:n,toPubkey:r,lamports:i,custodianPubkey:o}=e,a=iU.Withdraw,s=nR(a,{lamports:i}),u=[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:nI,isSigner:!1,isWritable:!1},{pubkey:nP,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}];return o&&u.push({pubkey:o,isSigner:!0,isWritable:!1}),new nx().add({keys:u,programId:this.programId,data:s})}static deactivate(e){let{stakePubkey:t,authorizedPubkey:n}=e,r=iU.Deactivate,i=nR(r);return new nx().add({keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:nI,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}],programId:this.programId,data:i})}}iz.programId=new nn("Stake11111111111111111111111111111111111111"),iz.space=200;let iV=Object.freeze({InitializeAccount:{index:0,layout:e2.n_([e2.Jq("instruction"),((e="voteInit")=>e2.n_([ns("nodePubkey"),ns("authorizedVoter"),ns("authorizedWithdrawer"),e2.u8("commission")],e))()])},Authorize:{index:1,layout:e2.n_([e2.Jq("instruction"),ns("newAuthorized"),e2.Jq("voteAuthorizationType")])},Withdraw:{index:3,layout:e2.n_([e2.Jq("instruction"),e2.gM("lamports")])},UpdateValidatorIdentity:{index:4,layout:e2.n_([e2.Jq("instruction")])},AuthorizeWithSeed:{index:10,layout:e2.n_([e2.Jq("instruction"),((e="voteAuthorizeWithSeedArgs")=>e2.n_([e2.Jq("voteAuthorizationType"),ns("currentAuthorityDerivedKeyOwnerPubkey"),nl("currentAuthorityDerivedKeySeed"),ns("newAuthorized")],e))()])}});Object.freeze({Voter:{index:0},Withdrawer:{index:1}});class iW{constructor(){}static initializeAccount(e){let{votePubkey:t,nodePubkey:n,voteInit:r}=e,i=iV.InitializeAccount,o=nR(i,{voteInit:{nodePubkey:t9(r.nodePubkey.toBuffer()),authorizedVoter:t9(r.authorizedVoter.toBuffer()),authorizedWithdrawer:t9(r.authorizedWithdrawer.toBuffer()),commission:r.commission}}),a={keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:nE,isSigner:!1,isWritable:!1},{pubkey:nI,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}],programId:this.programId,data:o};return new nk(a)}static createAccount(e){let t=new nx;return t.add(nz.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.votePubkey,lamports:e.lamports,space:this.space,programId:this.programId})),t.add(this.initializeAccount({votePubkey:e.votePubkey,nodePubkey:e.voteInit.nodePubkey,voteInit:e.voteInit}))}static authorize(e){let{votePubkey:t,authorizedPubkey:n,newAuthorizedPubkey:r,voteAuthorizationType:i}=e,o=iV.Authorize,a=nR(o,{newAuthorized:t9(r.toBuffer()),voteAuthorizationType:i.index});return new nx().add({keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:nI,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}],programId:this.programId,data:a})}static authorizeWithSeed(e){let{currentAuthorityDerivedKeyBasePubkey:t,currentAuthorityDerivedKeyOwnerPubkey:n,currentAuthorityDerivedKeySeed:r,newAuthorizedPubkey:i,voteAuthorizationType:o,votePubkey:a}=e,s=iV.AuthorizeWithSeed,u=nR(s,{voteAuthorizeWithSeedArgs:{currentAuthorityDerivedKeyOwnerPubkey:t9(n.toBuffer()),currentAuthorityDerivedKeySeed:r,newAuthorized:t9(i.toBuffer()),voteAuthorizationType:o.index}});return new nx().add({keys:[{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:nI,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!0,isWritable:!1}],programId:this.programId,data:u})}static withdraw(e){let{votePubkey:t,authorizedWithdrawerPubkey:n,lamports:r,toPubkey:i}=e,o=iV.Withdraw,a=nR(o,{lamports:r});return new nx().add({keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!0,isWritable:!1}],programId:this.programId,data:a})}static safeWithdraw(e,t,n){if(e.lamports>t-n)throw Error("Withdraw will leave vote account with insufficient funds.");return iW.withdraw(e)}static updateValidatorIdentity(e){let{votePubkey:t,authorizedWithdrawerPubkey:n,nodePubkey:r}=e,i=iV.UpdateValidatorIdentity,o=nR(i);return new nx().add({keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}],programId:this.programId,data:o})}}iW.programId=new nn("Vote111111111111111111111111111111111111111"),iW.space=3762,new nn("Va1idator1nfo111111111111111111111111111111"),tm({name:tf(),website:td(tf()),details:td(tf()),iconUrl:td(tf()),keybaseUsername:td(tf())}),new nn("Vote111111111111111111111111111111111111111"),e2.n_([ns("nodePubkey"),ns("authorizedWithdrawer"),e2.u8("commission"),e2._O(),e2.A9(e2.n_([e2._O("slot"),e2.Jq("confirmationCount")]),e2.cv(e2.Jq(),-8),"votes"),e2.u8("rootSlotValid"),e2._O("rootSlot"),e2._O(),e2.A9(e2.n_([e2._O("epoch"),ns("authorizedVoter")]),e2.cv(e2.Jq(),-8),"authorizedVoters"),e2.n_([e2.A9(e2.n_([ns("authorizedPubkey"),e2._O("epochOfLastAuthorizedSwitch"),e2._O("targetEpoch")]),32,"buf"),e2._O("idx"),e2.u8("isEmpty")],"priorVoters"),e2._O(),e2.A9(e2.n_([e2._O("epoch"),e2._O("credits"),e2._O("prevCredits")]),e2.cv(e2.Jq(),-8),"epochCredits"),e2.n_([e2._O("slot"),e2._O("timestamp")],"lastTimestamp")]);let i$={http:{devnet:"http://api.devnet.solana.com",testnet:"http://api.testnet.solana.com","mainnet-beta":"http://api.mainnet-beta.solana.com/"},https:{devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com","mainnet-beta":"https://api.mainnet-beta.solana.com/"}};function iK(e,t){let n=!1===t?"http":"https";if(!e)return i$[n].devnet;let r=i$[n][e];if(!r)throw Error(`Unknown ${n} cluster: ${e}`);return r}},10011:function(e,t,n){var r=n(58162);e.exports=r("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},36971:function(e,t,n){"use strict";function r(e,t){return t||(t=e.slice(0)),Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}n.d(t,{_:function(){return r}})},98260:function(e,t,n){"use strict";n.d(t,{Bz:function(){return j},WU:function(){return en},YL:function(){return p},Yp:function(){return J},_b:function(){return ec},a_:function(){return s},cW:function(){return eo},fr:function(){return ei},gG:function(){return Y},iA:function(){return $},ih:function(){return H},qn:function(){return ee},tA:function(){return X}});var r,i,o,a,s,u,l,c,d,p,f,h,m,g=n(39499),y=n.n(g),b=n(92600),_=n(29887),v=n.n(_),w=n(93302),k=n.n(w),x=n(12447),A=n.n(x),S=n(6731),I=n(19485),T=n(16441),E=n(38197),P=n(29251);function C(e,t){for(var n=0;n0||(0,b.Z)(!1),U.set({precision:e+1,rounding:V[n]});var r=new U(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return r.toFormat(r.decimalPlaces(),t)},t.toFixed=function(e,t,n){return void 0===t&&(t={groupSeparator:""}),void 0===n&&(n=f.ROUND_HALF_UP),Number.isInteger(e)||(0,b.Z)(!1),e>=0||(0,b.Z)(!1),z.DP=e,z.RM=W[n],new z(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)},O(e,[{key:"quotient",get:function(){return y().divide(this.numerator,this.denominator)}},{key:"remainder",get:function(){return new e(y().remainder(this.numerator,this.denominator),this.denominator)}},{key:"asFraction",get:function(){return new e(this.numerator,this.denominator)}}]),e}(),K=A()(k()),H=function(e){function t(t,n,r){var i;return i=e.call(this,n,r)||this,y().lessThanOrEqual(i.quotient,j)||(0,b.Z)(!1),i.currency=t,i.decimalScale=y().exponentiate(y().BigInt(10),y().BigInt(t.decimals)),i}M(t,e),t.fromRawAmount=function(e,n){return new t(e,n)},t.fromFractionalAmount=function(e,n,r){return new t(e,n,r)};var n=t.prototype;return n.add=function(n){this.currency.equals(n.currency)||(0,b.Z)(!1);var r=e.prototype.add.call(this,n);return t.fromFractionalAmount(this.currency,r.numerator,r.denominator)},n.subtract=function(n){this.currency.equals(n.currency)||(0,b.Z)(!1);var r=e.prototype.subtract.call(this,n);return t.fromFractionalAmount(this.currency,r.numerator,r.denominator)},n.multiply=function(n){var r=e.prototype.multiply.call(this,n);return t.fromFractionalAmount(this.currency,r.numerator,r.denominator)},n.divide=function(n){var r=e.prototype.divide.call(this,n);return t.fromFractionalAmount(this.currency,r.numerator,r.denominator)},n.toSignificant=function(t,n,r){return void 0===t&&(t=6),void 0===r&&(r=f.ROUND_DOWN),e.prototype.divide.call(this,this.decimalScale).toSignificant(t,n,r)},n.toFixed=function(t,n,r){return void 0===t&&(t=this.currency.decimals),void 0===r&&(r=f.ROUND_DOWN),t<=this.currency.decimals||(0,b.Z)(!1),e.prototype.divide.call(this,this.decimalScale).toFixed(t,n,r)},n.toExact=function(e){return void 0===e&&(e={groupSeparator:""}),K.DP=this.currency.decimals,new K(this.quotient.toString()).div(this.decimalScale.toString()).toFormat(e)},O(t,[{key:"wrapped",get:function(){return this.currency.isToken?this:t.fromFractionalAmount(this.currency.wrapped,this.numerator,this.denominator)}}]),t}($),G=new $(y().BigInt(100));function Z(e){return new Y(e.numerator,e.denominator)}var Y=function(e){function t(){var t;return t=e.apply(this,arguments)||this,t.isPercent=!0,t}M(t,e);var n=t.prototype;return n.add=function(t){return Z(e.prototype.add.call(this,t))},n.subtract=function(t){return Z(e.prototype.subtract.call(this,t))},n.multiply=function(t){return Z(e.prototype.multiply.call(this,t))},n.divide=function(t){return Z(e.prototype.divide.call(this,t))},n.toSignificant=function(t,n,r){return void 0===t&&(t=5),e.prototype.multiply.call(this,G).toSignificant(t,n,r)},n.toFixed=function(t,n,r){return void 0===t&&(t=2),e.prototype.multiply.call(this,G).toFixed(t,n,r)},t}($),X=function(e){function t(){for(var t,n,r,i,o,a=arguments.length,s=Array(a),u=0;u=0&&t<255&&Number.isInteger(t)||(0,b.Z)(!1),this.chainId=e,this.decimals=t,this.symbol=n,this.name=r},J=function(e){function t(){var t;return t=e.apply(this,arguments)||this,t.isNative=!0,t.isToken=!1,t}return M(t,e),t}(Q);function ee(e){try{return(0,I.Kn)(e)}catch(t){throw Error(e+" is not a valid address.")}}var et=/^0x[0-9a-fA-F]{40}$/,en=function(e){function t(t,n,r,i,o,a,s,u){var l;return(l=e.call(this,t,r,i,o)||this).isNative=!1,l.isToken=!0,a?l.address=function(e){if(et.test(e))return e;throw Error(e+" is not a valid address.")}(n):l.address=ee(n),s&&(s.gte(S.O$.from(0))||(0,b.Z)(!1)),u&&(u.gte(S.O$.from(0))||(0,b.Z)(!1)),l.buyFeeBps=s,l.sellFeeBps=u,l}M(t,e);var n=t.prototype;return n.equals=function(e){return e.isToken&&this.chainId===e.chainId&&this.address.toLowerCase()===e.address.toLowerCase()},n.sortsBefore=function(e){return this.chainId!==e.chainId&&(0,b.Z)(!1),this.address.toLowerCase()!==e.address.toLowerCase()||(0,b.Z)(!1),this.address.toLowerCase()0||(0,b.Z)(!1),e.length<=n||(0,b.Z)(!1),0===e.length)return e.push(t),null;var i=e.length===n;if(i&&0>=r(e[e.length-1],t))return t;for(var o=0,a=e.length;o>>1;0>=r(e[s],t)?o=s+1:a=s}return e.splice(o,0,t),i?e.pop():null}(function(e){function t(t){return e.call(this,t,18,"ETH","Ether")||this}return M(t,e),t.onChain=function(e){var n;return null!=(n=this._etherCache[e])?n:this._etherCache[e]=new t(e)},t.prototype.equals=function(e){return e.isNative&&e.chainId===this.chainId},O(t,[{key:"wrapped",get:function(){var e=er[this.chainId];return e||(0,b.Z)(!1),e}}]),t})(J)._etherCache={};var ea=y().BigInt(Number.MAX_SAFE_INTEGER),es=y().BigInt(0),eu=y().BigInt(1),el=y().BigInt(2);function ec(e){var t,n;if(y().greaterThanOrEqual(e,es)||(0,b.Z)(!1),y().lessThan(e,ea))return y().BigInt(Math.floor(Math.sqrt(y().toNumber(e))));for(t=e,n=y().add(y().divide(e,el),eu);y().lessThan(n,t);)t=n,n=y().divide(y().add(y().divide(e,n),n),el);return t}},145:function(e,t,n){"use strict";n.d(t,{lk:function(){return o},cK:function(){return eM},Kg:function(){return ew},Ly:function(){return ek},AW:function(){return ex},wh:function(){return eR},cH:function(){return eN},pk:function(){return ei},ho:function(){return eS},d_:function(){return K},Gp:function(){return em},Vm:function(){return ey},zz:function(){return eg},_s:function(){return el}});var r,i,o,a=n(98260),s=n(39499),u=n.n(s),l=n(92600),c=n(84243),d=n(8198),p=n(19485),f=n(6731),h=n(16441),m=n(38197),g=n(29251),y=n(1581);let b=RegExp("^bytes([0-9]+)$"),_=RegExp("^(u?int)([0-9]*)$"),v=RegExp("^(.*)\\[([0-9]*)\\]$"),w=new y.Yd("solidity/5.7.0");function k(e,t){e.length!=t.length&&w.throwArgumentError("wrong number of values; expected ${ types.length }","values",t);let n=[];return e.forEach(function(e,r){n.push(function e(t,n,r){switch(t){case"address":if(r)return(0,h.Bu)(n,32);return(0,h.lE)(n);case"string":return(0,g.Y0)(n);case"bytes":return(0,h.lE)(n);case"bool":if(n=n?"0x01":"0x00",r)return(0,h.Bu)(n,32);return(0,h.lE)(n)}let i=t.match(_);if(i){let e=parseInt(i[2]||"256");return(i[2]&&String(e)!==i[2]||e%8!=0||0===e||e>256)&&w.throwArgumentError("invalid number type","type",t),r&&(e=256),n=f.O$.from(n).toTwos(e),(0,h.Bu)(n,e/8)}if(i=t.match(b)){let e=parseInt(i[1]);return((String(e)!==i[1]||0===e||e>32)&&w.throwArgumentError("invalid bytes type","type",t),(0,h.lE)(n).byteLength!==e&&w.throwArgumentError(`invalid value for ${t}`,"value",n),r)?(0,h.lE)((n+"0000000000000000000000000000000000000000000000000000000000000000").substring(0,66)):n}if((i=t.match(v))&&Array.isArray(n)){let r=i[1],o=parseInt(i[2]||String(n.length));o!=n.length&&w.throwArgumentError(`invalid array length for ${t}`,"value",n);let a=[];return n.forEach(function(t){a.push(e(r,t,!0))}),(0,h.zo)(a)}return w.throwArgumentError("invalid type","type",t)}(e,t[r]))}),(0,h.Dv)((0,h.zo)(n))}var x=JSON.parse('{"Mt":[{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"payable","type":"function"}]}'),A=JSON.parse('{"Mt":[{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_WETH9","type":"address"},{"internalType":"address","name":"_tokenDescriptor_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Collect","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"DecreaseLiquidity","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"IncreaseLiquidity","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PERMIT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WETH9","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"baseURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint128","name":"amount0Max","type":"uint128"},{"internalType":"uint128","name":"amount1Max","type":"uint128"}],"internalType":"struct INonfungiblePositionManager.CollectParams","name":"params","type":"tuple"}],"name":"collect","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"}],"name":"createAndInitializePoolIfNecessary","outputs":[{"internalType":"address","name":"pool","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct INonfungiblePositionManager.DecreaseLiquidityParams","name":"params","type":"tuple"}],"name":"decreaseLiquidity","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"amount0Desired","type":"uint256"},{"internalType":"uint256","name":"amount1Desired","type":"uint256"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct INonfungiblePositionManager.IncreaseLiquidityParams","name":"params","type":"tuple"}],"name":"increaseLiquidity","outputs":[{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint256","name":"amount0Desired","type":"uint256"},{"internalType":"uint256","name":"amount1Desired","type":"uint256"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct INonfungiblePositionManager.MintParams","name":"params","type":"tuple"}],"name":"mint","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"positions","outputs":[{"internalType":"uint96","name":"nonce","type":"uint96"},{"internalType":"address","name":"operator","type":"address"},{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"feeGrowthInside0LastX128","type":"uint256"},{"internalType":"uint256","name":"feeGrowthInside1LastX128","type":"uint256"},{"internalType":"uint128","name":"tokensOwed0","type":"uint128"},{"internalType":"uint128","name":"tokensOwed1","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"refundETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitAllowed","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitAllowedIfNecessary","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitIfNecessary","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"sweepToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"tokenByIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"tokenOfOwnerByIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount0Owed","type":"uint256"},{"internalType":"uint256","name":"amount1Owed","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"uniswapV3MintCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"unwrapWETH9","outputs":[],"stateMutability":"payable","type":"function"},{"stateMutability":"payable","type":"receive"}]}'),S=JSON.parse('{"Mt":[{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitAllowed","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitAllowedIfNecessary","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitIfNecessary","outputs":[],"stateMutability":"payable","type":"function"}]}'),I=JSON.parse('{"Mt":[{"inputs":[],"name":"refundETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"sweepToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"feeBips","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"}],"name":"sweepTokenWithFee","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"unwrapWETH9","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"feeBips","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"}],"name":"unwrapWETH9WithFee","outputs":[],"stateMutability":"payable","type":"function"}]}'),T=JSON.parse('{"Mt":[{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_WETH9","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"WETH9","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"path","type":"bytes"},{"internalType":"uint256","name":"amountIn","type":"uint256"}],"name":"quoteExactInput","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"name":"quoteExactInputSingle","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"path","type":"bytes"},{"internalType":"uint256","name":"amountOut","type":"uint256"}],"name":"quoteExactOutput","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"name":"quoteExactOutputSingle","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"path","type":"bytes"}],"name":"uniswapV3SwapCallback","outputs":[],"stateMutability":"view","type":"function"}]}'),E=JSON.parse('{"Mt":[{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_WETH9","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"WETH9","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"path","type":"bytes"},{"internalType":"uint256","name":"amountIn","type":"uint256"}],"name":"quoteExactInput","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint160[]","name":"sqrtPriceX96AfterList","type":"uint160[]"},{"internalType":"uint32[]","name":"initializedTicksCrossedList","type":"uint32[]"},{"internalType":"uint256","name":"gasEstimate","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IQuoterV2.QuoteExactInputSingleParams","name":"params","type":"tuple"}],"name":"quoteExactInputSingle","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceX96After","type":"uint160"},{"internalType":"uint32","name":"initializedTicksCrossed","type":"uint32"},{"internalType":"uint256","name":"gasEstimate","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"path","type":"bytes"},{"internalType":"uint256","name":"amountOut","type":"uint256"}],"name":"quoteExactOutput","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint160[]","name":"sqrtPriceX96AfterList","type":"uint160[]"},{"internalType":"uint32[]","name":"initializedTicksCrossedList","type":"uint32[]"},{"internalType":"uint256","name":"gasEstimate","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IQuoterV2.QuoteExactOutputSingleParams","name":"params","type":"tuple"}],"name":"quoteExactOutputSingle","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceX96After","type":"uint160"},{"internalType":"uint32","name":"initializedTicksCrossed","type":"uint32"},{"internalType":"uint256","name":"gasEstimate","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"path","type":"bytes"}],"name":"uniswapV3SwapCallback","outputs":[],"stateMutability":"view","type":"function"}]}'),P=JSON.parse('{"Mt":[{"inputs":[{"internalType":"contract IUniswapV3Factory","name":"_factory","type":"address"},{"internalType":"contract INonfungiblePositionManager","name":"_nonfungiblePositionManager","type":"address"},{"internalType":"uint256","name":"_maxIncentiveStartLeadTime","type":"uint256"},{"internalType":"uint256","name":"_maxIncentiveDuration","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"oldOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"DepositTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"indexed":true,"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"indexed":false,"internalType":"uint256","name":"startTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"endTime","type":"uint256"},{"indexed":false,"internalType":"address","name":"refundee","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"IncentiveCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"refund","type":"uint256"}],"name":"IncentiveEnded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"}],"name":"TokenStaked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"}],"name":"TokenUnstaked","type":"event"},{"inputs":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amountRequested","type":"uint256"}],"name":"claimReward","outputs":[{"internalType":"uint256","name":"reward","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"},{"internalType":"address","name":"refundee","type":"address"}],"internalType":"struct IUniswapV3Staker.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"reward","type":"uint256"}],"name":"createIncentive","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"deposits","outputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint48","name":"numberOfStakes","type":"uint48"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"},{"internalType":"address","name":"refundee","type":"address"}],"internalType":"struct IUniswapV3Staker.IncentiveKey","name":"key","type":"tuple"}],"name":"endIncentive","outputs":[{"internalType":"uint256","name":"refund","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"contract IUniswapV3Factory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"},{"internalType":"address","name":"refundee","type":"address"}],"internalType":"struct IUniswapV3Staker.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getRewardInfo","outputs":[{"internalType":"uint256","name":"reward","type":"uint256"},{"internalType":"uint160","name":"secondsInsideX128","type":"uint160"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"incentives","outputs":[{"internalType":"uint256","name":"totalRewardUnclaimed","type":"uint256"},{"internalType":"uint160","name":"totalSecondsClaimedX128","type":"uint160"},{"internalType":"uint96","name":"numberOfStakes","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxIncentiveDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxIncentiveStartLeadTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"nonfungiblePositionManager","outputs":[{"internalType":"contract INonfungiblePositionManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20Minimal","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"rewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"},{"internalType":"address","name":"refundee","type":"address"}],"internalType":"struct IUniswapV3Staker.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"stakeToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes32","name":"incentiveId","type":"bytes32"}],"name":"stakes","outputs":[{"internalType":"uint160","name":"secondsPerLiquidityInsideInitialX128","type":"uint160"},{"internalType":"uint128","name":"liquidity","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"to","type":"address"}],"name":"transferDeposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"},{"internalType":"address","name":"refundee","type":"address"}],"internalType":"struct IUniswapV3Staker.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"unstakeToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"withdrawToken","outputs":[],"stateMutability":"nonpayable","type":"function"}]}'),C=JSON.parse('{"Mt":[{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_WETH9","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"WETH9","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"path","type":"bytes"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMinimum","type":"uint256"}],"internalType":"struct ISwapRouter.ExactInputParams","name":"params","type":"tuple"}],"name":"exactInput","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMinimum","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct ISwapRouter.ExactInputSingleParams","name":"params","type":"tuple"}],"name":"exactInputSingle","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"path","type":"bytes"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMaximum","type":"uint256"}],"internalType":"struct ISwapRouter.ExactOutputParams","name":"params","type":"tuple"}],"name":"exactOutput","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMaximum","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct ISwapRouter.ExactOutputSingleParams","name":"params","type":"tuple"}],"name":"exactOutputSingle","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"refundETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitAllowed","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitAllowedIfNecessary","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitIfNecessary","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"sweepToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"feeBips","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"}],"name":"sweepTokenWithFee","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"uniswapV3SwapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"unwrapWETH9","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"feeBips","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"}],"name":"unwrapWETH9WithFee","outputs":[],"stateMutability":"payable","type":"function"},{"stateMutability":"payable","type":"receive"}]}');function O(){O=function(){return t};var e,t={},n=Object.prototype,r=n.hasOwnProperty,i=Object.defineProperty||function(e,t,n){e[t]=n.value},o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",s=o.asyncIterator||"@@asyncIterator",u=o.toStringTag||"@@toStringTag";function l(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{l({},"")}catch(e){l=function(e,t,n){return e[t]=n}}function c(t,n,r,o){var a,s,u=Object.create((n&&n.prototype instanceof g?n:g).prototype);return i(u,"_invoke",{value:(a=new T(o||[]),s=p,function(n,i){if(s===f)throw Error("Generator is already running");if(s===h){if("throw"===n)throw i;return{value:e,done:!0}}for(a.method=n,a.arg=i;;){var o=a.delegate;if(o){var u=function t(n,r){var i=r.method,o=n.iterator[i];if(o===e)return r.delegate=null,"throw"===i&&n.iterator.return&&(r.method="return",r.arg=e,t(n,r),"throw"===r.method)||"return"!==i&&(r.method="throw",r.arg=TypeError("The iterator does not provide a '"+i+"' method")),m;var a=d(o,n.iterator,r.arg);if("throw"===a.type)return r.method="throw",r.arg=a.arg,r.delegate=null,m;var s=a.arg;return s?s.done?(r[n.resultName]=s.value,r.next=n.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):s:(r.method="throw",r.arg=TypeError("iterator result is not an object"),r.delegate=null,m)}(o,a);if(u){if(u===m)continue;return u}}if("next"===a.method)a.sent=a._sent=a.arg;else if("throw"===a.method){if(s===p)throw s=h,a.arg;a.dispatchException(a.arg)}else"return"===a.method&&a.abrupt("return",a.arg);s=f;var l=d(t,r,a);if("normal"===l.type){if(s=a.done?h:"suspendedYield",l.arg===m)continue;return{value:l.arg,done:a.done}}"throw"===l.type&&(s=h,a.method="throw",a.arg=l.arg)}})}),u}function d(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}t.wrap=c;var p="suspendedStart",f="executing",h="completed",m={};function g(){}function y(){}function b(){}var _={};l(_,a,function(){return this});var v=Object.getPrototypeOf,w=v&&v(v(E([])));w&&w!==n&&r.call(w,a)&&(_=w);var k=b.prototype=g.prototype=Object.create(_);function x(e){["next","throw","return"].forEach(function(t){l(e,t,function(e){return this._invoke(t,e)})})}function A(e,t){var n;i(this,"_invoke",{value:function(i,o){function a(){return new t(function(n,a){!function n(i,o,a,s){var u=d(e[i],e,o);if("throw"!==u.type){var l=u.arg,c=l.value;return c&&"object"==typeof c&&r.call(c,"__await")?t.resolve(c.__await).then(function(e){n("next",e,a,s)},function(e){n("throw",e,a,s)}):t.resolve(c).then(function(e){l.value=e,a(l)},function(e){return n("throw",e,a,s)})}s(u.arg)}(i,o,n,a)})}return n=n?n.then(a,a):a()}})}function S(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function I(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function T(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(S,this),this.reset(!0)}function E(t){if(t||""===t){var n=t[a];if(n)return n.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,o=function n(){for(;++i=0;--o){var a=this.tryEntries[o],s=a.completion;if("root"===a.tryLoc)return i("end");if(a.tryLoc<=this.prev){var u=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(u&&l){if(this.prev=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&r.call(i,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),I(n),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var i=r.arg;I(n)}return i}}throw Error("illegal catch attempt")},delegateYield:function(t,n,r){return this.delegate={iterator:E(t),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=e),m}},t}function B(e,t,n,r,i,o,a){try{var s=e[o](a),u=s.value}catch(e){n(e);return}s.done?t(u):Promise.resolve(u).then(r,i)}function M(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){B(o,r,i,a,s,"next",e)}function s(e){B(o,r,i,a,s,"throw",e)}a(void 0)})}}function R(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var q="0x0000000000000000000000000000000000000000";(r=o||(o={}))[r.LOWEST=100]="LOWEST",r[r.LOW_200=200]="LOW_200",r[r.LOW_300=300]="LOW_300",r[r.LOW_400=400]="LOW_400",r[r.LOW=500]="LOW",r[r.MEDIUM=3e3]="MEDIUM",r[r.HIGH=1e4]="HIGH";var j=((i={})[o.LOWEST]=1,i[o.LOW_200]=4,i[o.LOW_300]=6,i[o.LOW_400]=8,i[o.LOW]=10,i[o.MEDIUM]=60,i[o.HIGH]=200,i),U=u().BigInt(-1),z=u().BigInt(0),V=u().BigInt(1),W=u().exponentiate(u().BigInt(2),u().BigInt(96)),$=u().exponentiate(W,u().BigInt(2));function K(e){var t,n=e.factoryAddress,r=e.tokenA,i=e.tokenB,o=e.fee,s=e.initCodeHashManualOverride,u=e.chainId,l=r.sortsBefore(i)?[r,i]:[i,r],d=l[0],f=l[1],h=(t=[c.$.encode(["address","address","uint24"],[d.address,f.address,o])],(0,m.w)(k(["bytes"],t))),g=null!=s?s:u===a.a_.ZKSYNC?"0x010013f177ea1fcbc4520f9a3ca7cd2d1d77959e05aa66484027cb38e712aeed":"0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54";return u===a.a_.ZKSYNC?(0,a.fr)(n,g,h):(0,p.hB)(n,h,g)}var H=function(){function e(){}return e.mulDivRoundingUp=function(e,t,n){var r=u().multiply(e,t),i=u().divide(r,n);return u().notEqual(u().remainder(r,n),z)&&(i=u().add(i,V)),i},e}(),G=u().subtract(u().exponentiate(u().BigInt(2),u().BigInt(160)),V);function Z(e,t){var n=u().multiply(e,t);return u().bitwiseAnd(n,a.Bz)}var Y=function(){function e(){}return e.getAmount0Delta=function(e,t,n,r){if(u().greaterThan(e,t)){var i=[t,e];e=i[0],t=i[1]}var o=u().leftShift(n,u().BigInt(96)),a=u().subtract(t,e);return r?H.mulDivRoundingUp(H.mulDivRoundingUp(o,a,t),V,e):u().divide(u().divide(u().multiply(o,a),t),e)},e.getAmount1Delta=function(e,t,n,r){if(u().greaterThan(e,t)){var i=[t,e];e=i[0],t=i[1]}return r?H.mulDivRoundingUp(n,u().subtract(t,e),W):u().divide(u().multiply(n,u().subtract(t,e)),W)},e.getNextSqrtPriceFromInput=function(e,t,n,r){return u().greaterThan(e,z)||(0,l.Z)(!1),u().greaterThan(t,z)||(0,l.Z)(!1),r?this.getNextSqrtPriceFromAmount0RoundingUp(e,t,n,!0):this.getNextSqrtPriceFromAmount1RoundingDown(e,t,n,!0)},e.getNextSqrtPriceFromOutput=function(e,t,n,r){return u().greaterThan(e,z)||(0,l.Z)(!1),u().greaterThan(t,z)||(0,l.Z)(!1),r?this.getNextSqrtPriceFromAmount1RoundingDown(e,t,n,!1):this.getNextSqrtPriceFromAmount0RoundingUp(e,t,n,!1)},e.getNextSqrtPriceFromAmount0RoundingUp=function(e,t,n,r){if(u().equal(n,z))return e;var i=u().leftShift(t,u().BigInt(96));if(r){var o=Z(n,e);if(u().equal(u().divide(o,n),e)){var s,c=(s=u().add(i,o),u().bitwiseAnd(s,a.Bz));if(u().greaterThanOrEqual(c,i))return H.mulDivRoundingUp(i,e,c)}return H.mulDivRoundingUp(i,V,u().add(u().divide(i,e),n))}var d=Z(n,e);u().equal(u().divide(d,n),e)||(0,l.Z)(!1),u().greaterThan(i,d)||(0,l.Z)(!1);var p=u().subtract(i,d);return H.mulDivRoundingUp(i,e,p)},e.getNextSqrtPriceFromAmount1RoundingDown=function(e,t,n,r){if(r){var i=u().lessThanOrEqual(n,G)?u().divide(u().leftShift(n,u().BigInt(96)),t):u().divide(u().multiply(n,W),t);return u().add(e,i)}var o=H.mulDivRoundingUp(n,W,t);return u().greaterThan(e,o)||(0,l.Z)(!1),u().subtract(e,o)},e}(),X=u().exponentiate(u().BigInt(10),u().BigInt(6)),Q=function(){function e(){}return e.computeSwapStep=function(e,t,n,r,i){var o={};i=u().BigInt(i);var a=u().greaterThanOrEqual(e,t),s=u().greaterThanOrEqual(r,z);if(s){var l=u().divide(u().multiply(r,u().subtract(X,i)),X);o.amountIn=a?Y.getAmount0Delta(t,e,n,!0):Y.getAmount1Delta(e,t,n,!0),u().greaterThanOrEqual(l,o.amountIn)?o.sqrtRatioNextX96=t:o.sqrtRatioNextX96=Y.getNextSqrtPriceFromInput(e,n,l,a)}else o.amountOut=a?Y.getAmount1Delta(t,e,n,!1):Y.getAmount0Delta(e,t,n,!1),u().greaterThanOrEqual(u().multiply(r,U),o.amountOut)?o.sqrtRatioNextX96=t:o.sqrtRatioNextX96=Y.getNextSqrtPriceFromOutput(e,n,u().multiply(r,U),a);var c=u().equal(t,o.sqrtRatioNextX96);return a?(o.amountIn=c&&s?o.amountIn:Y.getAmount0Delta(o.sqrtRatioNextX96,e,n,!0),o.amountOut=c&&!s?o.amountOut:Y.getAmount1Delta(o.sqrtRatioNextX96,e,n,!1)):(o.amountIn=c&&s?o.amountIn:Y.getAmount1Delta(e,o.sqrtRatioNextX96,n,!0),o.amountOut=c&&!s?o.amountOut:Y.getAmount0Delta(e,o.sqrtRatioNextX96,n,!1)),!s&&u().greaterThan(o.amountOut,u().multiply(r,U))&&(o.amountOut=u().multiply(r,U)),s&&u().notEqual(o.sqrtRatioNextX96,t)?o.feeAmount=u().subtract(r,o.amountIn):o.feeAmount=H.mulDivRoundingUp(o.amountIn,i,u().subtract(X,i)),[o.sqrtRatioNextX96,o.amountIn,o.amountOut,o.feeAmount]},e}(),J=function(){function e(){}return e.addDelta=function(e,t){return u().lessThan(t,z)?u().subtract(e,u().multiply(t,U)):u().add(e,t)},e}(),ee=u().BigInt(2),et=[128,64,32,16,8,4,2,1].map(function(e){return[e,u().exponentiate(ee,u().BigInt(e))]});function en(e,t){return u().signedRightShift(u().multiply(e,u().BigInt(t)),u().BigInt(128))}var er=u().exponentiate(u().BigInt(2),u().BigInt(32)),ei=function(){function e(){}return e.getSqrtRatioAtTick=function(t){t>=e.MIN_TICK&&t<=e.MAX_TICK&&Number.isInteger(t)||(0,l.Z)(!1);var n=t<0?-1*t:t,r=(1&n)!=0?u().BigInt("0xfffcb933bd6fad37aa2d162d1a594001"):u().BigInt("0x100000000000000000000000000000000");return(2&n)!=0&&(r=en(r,"0xfff97272373d413259a46990580e213a")),(4&n)!=0&&(r=en(r,"0xfff2e50f5f656932ef12357cf3c7fdcc")),(8&n)!=0&&(r=en(r,"0xffe5caca7e10e4e61c3624eaa0941cd0")),(16&n)!=0&&(r=en(r,"0xffcb9843d60f6159c9db58835c926644")),(32&n)!=0&&(r=en(r,"0xff973b41fa98c081472e6896dfb254c0")),(64&n)!=0&&(r=en(r,"0xff2ea16466c96a3843ec78b326b52861")),(128&n)!=0&&(r=en(r,"0xfe5dee046a99a2a811c461f1969c3053")),(256&n)!=0&&(r=en(r,"0xfcbe86c7900a88aedcffc83b479aa3a4")),(512&n)!=0&&(r=en(r,"0xf987a7253ac413176f2b074cf7815e54")),(1024&n)!=0&&(r=en(r,"0xf3392b0822b70005940c7a398e4b70f3")),(2048&n)!=0&&(r=en(r,"0xe7159475a2c29b7443b29c7fa6e889d9")),(4096&n)!=0&&(r=en(r,"0xd097f3bdfd2022b8845ad8f792aa5825")),(8192&n)!=0&&(r=en(r,"0xa9f746462d870fdf8a65dc1f90e061e5")),(16384&n)!=0&&(r=en(r,"0x70d869a156d2a1b890bb3df62baf32f7")),(32768&n)!=0&&(r=en(r,"0x31be135f97d08fd981231505542fcfa6")),(65536&n)!=0&&(r=en(r,"0x9aa508b5b7a84e1c677de54f3e99bc9")),(131072&n)!=0&&(r=en(r,"0x5d6af8dedb81196699c329225ee604")),(262144&n)!=0&&(r=en(r,"0x2216e584f5fa1ea926041bedfe98")),(524288&n)!=0&&(r=en(r,"0x48a170391f7dc42444e8fa2")),t>0&&(r=u().divide(a.Bz,r)),u().greaterThan(u().remainder(r,er),z)?u().add(u().divide(r,er),V):u().divide(r,er)},e.getTickAtSqrtRatio=function(t){u().greaterThanOrEqual(t,e.MIN_SQRT_RATIO)&&u().lessThan(t,e.MAX_SQRT_RATIO)||(0,l.Z)(!1);var n,r=u().leftShift(t,u().BigInt(32)),i=function(e){u().greaterThan(e,z)||(0,l.Z)(!1),u().lessThanOrEqual(e,a.Bz)||(0,l.Z)(!1);for(var t,n=0,r=F(et);!(t=r()).done;){var i=t.value,o=i[0],s=i[1];u().greaterThanOrEqual(e,s)&&(e=u().signedRightShift(e,u().BigInt(o)),n+=o)}return n}(r);n=u().greaterThanOrEqual(u().BigInt(i),u().BigInt(128))?u().signedRightShift(r,u().BigInt(i-127)):u().leftShift(r,u().BigInt(127-i));for(var o=u().leftShift(u().subtract(u().BigInt(i),u().BigInt(128)),u().BigInt(64)),s=0;s<14;s++){n=u().signedRightShift(u().multiply(n,n),u().BigInt(127));var c=u().signedRightShift(n,u().BigInt(128));o=u().bitwiseOr(o,u().leftShift(c,u().BigInt(63-s))),n=u().signedRightShift(n,c)}var d=u().multiply(o,u().BigInt("255738958999603826347141")),p=u().toNumber(u().signedRightShift(u().subtract(d,u().BigInt("3402992956809132418596140100660247210")),u().BigInt(128))),f=u().toNumber(u().signedRightShift(u().add(d,u().BigInt("291339464771989622907027621153398088495")),u().BigInt(128)));return p===f?p:u().lessThanOrEqual(e.getSqrtRatioAtTick(f),t)?f:p},e}();function eo(){return(eo=M(O().mark(function e(t,n,r,i,o,a,s,c,d){var p,f,h,m,g,y;return O().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:d||(d=s?u().add(ei.MIN_SQRT_RATIO,V):u().subtract(ei.MAX_SQRT_RATIO,V)),s?(u().greaterThan(d,ei.MIN_SQRT_RATIO)||(0,l.Z)(!1),u().lessThan(d,n)||(0,l.Z)(!1)):(u().lessThan(d,ei.MAX_SQRT_RATIO)||(0,l.Z)(!1),u().greaterThan(d,n)||(0,l.Z)(!1)),p=u().greaterThanOrEqual(c,z),f={amountSpecifiedRemaining:c,amountCalculated:z,sqrtPriceX96:n,tick:r,liquidity:i};case 4:if(!(u().notEqual(f.amountSpecifiedRemaining,z)&&f.sqrtPriceX96!==d)){e.next=35;break}return(h={}).sqrtPriceStartX96=f.sqrtPriceX96,e.next=9,a.nextInitializedTickWithinOneWord(f.tick,s,o);case 9:if(m=e.sent,h.tickNext=m[0],h.initialized=m[1],h.tickNextei.MAX_TICK&&(h.tickNext=ei.MAX_TICK),h.sqrtPriceNextX96=ei.getSqrtRatioAtTick(h.tickNext),g=Q.computeSwapStep(f.sqrtPriceX96,(s?u().lessThan(h.sqrtPriceNextX96,d):u().greaterThan(h.sqrtPriceNextX96,d))?d:h.sqrtPriceNextX96,f.liquidity,f.amountSpecifiedRemaining,t),f.sqrtPriceX96=g[0],h.amountIn=g[1],h.amountOut=g[2],h.feeAmount=g[3],p?(f.amountSpecifiedRemaining=u().subtract(f.amountSpecifiedRemaining,u().add(h.amountIn,h.feeAmount)),f.amountCalculated=u().subtract(f.amountCalculated,h.amountOut)):(f.amountSpecifiedRemaining=u().add(f.amountSpecifiedRemaining,h.amountOut),f.amountCalculated=u().add(f.amountCalculated,u().add(h.amountIn,h.feeAmount))),!u().equal(f.sqrtPriceX96,h.sqrtPriceNextX96)){e.next=32;break}if(!h.initialized){e.next=29;break}return e.t0=u(),e.next=25,a.getTick(h.tickNext);case 25:e.t1=e.sent.liquidityNet,y=e.t0.BigInt.call(e.t0,e.t1),s&&(y=u().multiply(y,U)),f.liquidity=J.addDelta(f.liquidity,y);case 29:f.tick=s?h.tickNext-1:h.tickNext,e.next=33;break;case 32:u().notEqual(f.sqrtPriceX96,h.sqrtPriceStartX96)&&(f.tick=ei.getTickAtSqrtRatio(f.sqrtPriceX96));case 33:e.next=4;break;case 35:return e.abrupt("return",{amountCalculated:f.amountCalculated,sqrtRatioX96:f.sqrtPriceX96,liquidity:f.liquidity,tickCurrent:f.tick});case 36:case"end":return e.stop()}},e)}))).apply(this,arguments)}ei.MIN_TICK=-887272,ei.MAX_TICK=-ei.MIN_TICK,ei.MIN_SQRT_RATIO=u().BigInt("4295128739"),ei.MAX_SQRT_RATIO=u().BigInt("1461446703485210103287273052203988822378723970342");var ea=function(){function e(){}var t,n,r=e.prototype;return r.getTick=(t=M(O().mark(function t(n){return O().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:throw Error(e.ERROR_MESSAGE);case 1:case"end":return t.stop()}},t)})),function(e){return t.apply(this,arguments)}),r.nextInitializedTickWithinOneWord=(n=M(O().mark(function t(n,r,i){return O().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:throw Error(e.ERROR_MESSAGE);case 1:case"end":return t.stop()}},t)})),function(e,t,r){return n.apply(this,arguments)}),e}();function es(e,t){return e.index-t.index}ea.ERROR_MESSAGE="No tick data provider was given";var eu=function(){function e(){}return e.validateList=function(e,t){t>0||(0,l.Z)(!1),e.every(function(e){return e.index%t==0})||(0,l.Z)(!1),u().equal(e.reduce(function(e,t){var n=t.liquidityNet;return u().add(e,n)},z),z)||(0,l.Z)(!1),!function(e,t){for(var n=0;n0)return!1;return!0}(e,es)&&(0,l.Z)(!1)},e.isBelowSmallest=function(e,t){return e.length>0||(0,l.Z)(!1),t0||(0,l.Z)(!1),t>=e[e.length-1].index},e.getTick=function(e,t){var n=e[this.binarySearch(e,t)];return n.index!==t&&(0,l.Z)(!1),n},e.binarySearch=function(e,t){this.isBelowSmallest(e,t)&&(0,l.Z)(!1);for(var n,r=0,i=e.length-1;;){if(e[n=Math.floor((r+i)/2)].index<=t&&(n===e.length-1||e[n+1].index>t))return n;e[n].index>8<<8)*i;if(e.isBelowSmallest(t,n))return[a,!1];var s=e.nextInitializedTick(t,n,r).index,u=Math.max(a,s);return[u,u===s]}var l=(((o+1>>8)+1<<8)-1)*i;if(this.isAtOrAboveLargest(t,n))return[l,!1];var c=this.nextInitializedTick(t,n,r).index,d=Math.min(l,c);return[d,d===c]},e}();function el(e){var t=u().BigInt(e).toString(16);return t.length%2!=0&&(t="0"+t),"0x"+t}function ec(e,t){var n=e.input.wrapped,r=e.pools.reduce(function(e,t,n){var r=e.inputToken,i=e.path,o=e.types,a=t.token0.equals(r)?t.token1:t.token0;return 0===n?{inputToken:a,types:["address","uint24","address"],path:[r.address,t.fee,a.address]}:{inputToken:a,types:[].concat(o,["uint24","address"]),path:[].concat(i,[t.fee,a.address])}},{inputToken:n,path:[],types:[]}),i=r.path,o=r.types;return t?k(o.reverse(),i.reverse()):k(o,i)}function ed(e,t){var n=u().leftShift(u().BigInt(e),u().BigInt(192)),r=u().BigInt(t),i=u().divide(n,r);return(0,a._b)(i)}function ep(e,t,n){if(u().greaterThan(e,t)){var r=[t,e];e=r[0],t=r[1]}var i=u().divide(u().multiply(e,t),W);return u().divide(u().multiply(u().BigInt(n),i),u().subtract(t,e))}function ef(e,t,n){if(u().greaterThan(e,t)){var r=[t,e];e=r[0],t=r[1]}var i=u().multiply(u().multiply(u().BigInt(n),e),t),o=u().multiply(W,u().subtract(t,e));return u().divide(i,o)}function eh(e,t,n){if(u().greaterThan(e,t)){var r=[t,e];e=r[0],t=r[1]}return u().divide(u().multiply(u().BigInt(n),W),u().subtract(t,e))}function em(e,t){Number.isInteger(e)&&Number.isInteger(t)||(0,l.Z)(!1),t>0||(0,l.Z)(!1),e>=ei.MIN_TICK&&e<=ei.MAX_TICK||(0,l.Z)(!1);var n=Math.round(e/t)*t;return nei.MAX_TICK?n-t:n}function eg(e,t,n){var r=ei.getSqrtRatioAtTick(n),i=u().multiply(r,r);return e.sortsBefore(t)?new a.tA(e,t,$,i):new a.tA(e,t,i,$)}function ey(e){var t=e.baseCurrency.sortsBefore(e.quoteCurrency),n=t?ed(e.numerator,e.denominator):ed(e.denominator,e.numerator),r=ei.getTickAtSqrtRatio(n),i=eg(e.baseCurrency,e.quoteCurrency,r+1);return t?!e.lessThan(i)&&r++:!e.greaterThan(i)&&r++,r}var eb=function(e){var t=e.index,n=e.liquidityGross,r=e.liquidityNet;t>=ei.MIN_TICK&&t<=ei.MAX_TICK||(0,l.Z)(!1),this.index=t,this.liquidityGross=u().BigInt(n),this.liquidityNet=u().BigInt(r)},e_=function(){function e(e,t){var n=e.map(function(e){return e instanceof eb?e:new eb(e)});eu.validateList(n,t),this.ticks=n}var t,n,r=e.prototype;return r.getTick=(t=M(O().mark(function e(t){return O().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",eu.getTick(this.ticks,t));case 1:case"end":return e.stop()}},e,this)})),function(e){return t.apply(this,arguments)}),r.nextInitializedTickWithinOneWord=(n=M(O().mark(function e(t,n,r){return O().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",eu.nextInitializedTickWithinOneWord(this.ticks,t,n,r));case 1:case"end":return e.stop()}},e,this)})),function(e,t,r){return n.apply(this,arguments)}),e}(),ev=new ea,ew=function(){function e(e,t,n,r,i,o,a){void 0===a&&(a=ev),Number.isInteger(n)&&n<1e6||(0,l.Z)(!1);var s=ei.getSqrtRatioAtTick(o),c=ei.getSqrtRatioAtTick(o+1);u().greaterThanOrEqual(u().BigInt(r),s)&&u().lessThanOrEqual(u().BigInt(r),c)||(0,l.Z)(!1);var d=e.sortsBefore(t)?[e,t]:[t,e];this.token0=d[0],this.token1=d[1],this.fee=n,this.sqrtRatioX96=u().BigInt(r),this.liquidity=u().BigInt(i),this.tickCurrent=o,this.tickDataProvider=Array.isArray(a)?new e_(a,j[n]):a}e.getAddress=function(e,t,n,r,i){return K({factoryAddress:null!=i?i:"0x1F98431c8aD98523631AE4a59f267346ea31F984",fee:n,tokenA:e,tokenB:t,initCodeHashManualOverride:r})};var t,n,r,i=e.prototype;return i.involvesToken=function(e){return e.equals(this.token0)||e.equals(this.token1)},i.priceOf=function(e){return this.involvesToken(e)||(0,l.Z)(!1),e.equals(this.token0)?this.token0Price:this.token1Price},i.getOutputAmount=(t=M(O().mark(function t(n,r){var i,o,s,c,d,p,f;return O().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return this.involvesToken(n.currency)||(0,l.Z)(!1),i=n.currency.equals(this.token0),t.next=4,this.swap(i,n.quotient,r);case 4:return s=(o=t.sent).amountCalculated,c=o.sqrtRatioX96,d=o.liquidity,p=o.tickCurrent,f=i?this.token1:this.token0,t.abrupt("return",[a.ih.fromRawAmount(f,u().multiply(s,U)),new e(this.token0,this.token1,this.fee,c,d,p,this.tickDataProvider)]);case 11:case"end":return t.stop()}},t,this)})),function(e,n){return t.apply(this,arguments)}),i.getInputAmount=(n=M(O().mark(function t(n,r){var i,o,s,c,d,p,f;return O().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return n.currency.isToken&&this.involvesToken(n.currency)||(0,l.Z)(!1),i=n.currency.equals(this.token1),t.next=4,this.swap(i,u().multiply(n.quotient,U),r);case 4:return s=(o=t.sent).amountCalculated,c=o.sqrtRatioX96,d=o.liquidity,p=o.tickCurrent,f=i?this.token0:this.token1,t.abrupt("return",[a.ih.fromRawAmount(f,s),new e(this.token0,this.token1,this.fee,c,d,p,this.tickDataProvider)]);case 11:case"end":return t.stop()}},t,this)})),function(e,t){return n.apply(this,arguments)}),i.swap=(r=M(O().mark(function e(t,n,r){return O().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",function(e,t,n,r,i,o,a,s,u){return eo.apply(this,arguments)}(u().BigInt(this.fee),this.sqrtRatioX96,this.tickCurrent,this.liquidity,this.tickSpacing,this.tickDataProvider,t,n,r));case 1:case"end":return e.stop()}},e,this)})),function(e,t,n){return r.apply(this,arguments)}),L(e,[{key:"token0Price",get:function(){var e;return null!=(e=this._token0Price)?e:this._token0Price=new a.tA(this.token0,this.token1,$,u().multiply(this.sqrtRatioX96,this.sqrtRatioX96))}},{key:"token1Price",get:function(){var e;return null!=(e=this._token1Price)?e:this._token1Price=new a.tA(this.token1,this.token0,u().multiply(this.sqrtRatioX96,this.sqrtRatioX96),$)}},{key:"chainId",get:function(){return this.token0.chainId}},{key:"tickSpacing",get:function(){return j[this.fee]}}]),e}(),ek=function(){function e(e){var t=e.pool,n=e.liquidity,r=e.tickLower,i=e.tickUpper;this._token0Amount=null,this._token1Amount=null,this._mintAmounts=null,r=ei.MIN_TICK&&r%t.tickSpacing==0||(0,l.Z)(!1),i<=ei.MAX_TICK&&i%t.tickSpacing==0||(0,l.Z)(!1),this.pool=t,this.tickLower=r,this.tickUpper=i,this.liquidity=u().BigInt(n)}var t=e.prototype;return t.ratiosAfterSlippage=function(e){var t=this.pool.token0Price.asFraction.multiply(new a.gG(1).subtract(e)),n=this.pool.token0Price.asFraction.multiply(e.add(1)),r=ed(t.numerator,t.denominator);u().lessThanOrEqual(r,ei.MIN_SQRT_RATIO)&&(r=u().add(ei.MIN_SQRT_RATIO,u().BigInt(1)));var i=ed(n.numerator,n.denominator);return u().greaterThanOrEqual(i,ei.MAX_SQRT_RATIO)&&(i=u().subtract(ei.MAX_SQRT_RATIO,u().BigInt(1))),{sqrtRatioX96Lower:r,sqrtRatioX96Upper:i}},t.mintAmountsWithSlippage=function(t){var n=this.ratiosAfterSlippage(t),r=n.sqrtRatioX96Upper,i=n.sqrtRatioX96Lower,o=new ew(this.pool.token0,this.pool.token1,this.pool.fee,i,0,ei.getTickAtSqrtRatio(i)),a=new ew(this.pool.token0,this.pool.token1,this.pool.fee,r,0,ei.getTickAtSqrtRatio(r)),s=e.fromAmounts(N({pool:this.pool,tickLower:this.tickLower,tickUpper:this.tickUpper},this.mintAmounts,{useFullPrecision:!1}));return{amount0:new e({pool:a,liquidity:s.liquidity,tickLower:this.tickLower,tickUpper:this.tickUpper}).mintAmounts.amount0,amount1:new e({pool:o,liquidity:s.liquidity,tickLower:this.tickLower,tickUpper:this.tickUpper}).mintAmounts.amount1}},t.burnAmountsWithSlippage=function(t){var n=this.ratiosAfterSlippage(t),r=n.sqrtRatioX96Upper,i=n.sqrtRatioX96Lower,o=new ew(this.pool.token0,this.pool.token1,this.pool.fee,i,0,ei.getTickAtSqrtRatio(i)),a=new ew(this.pool.token0,this.pool.token1,this.pool.fee,r,0,ei.getTickAtSqrtRatio(r)),s=new e({pool:a,liquidity:this.liquidity,tickLower:this.tickLower,tickUpper:this.tickUpper}).amount0,u=new e({pool:o,liquidity:this.liquidity,tickLower:this.tickLower,tickUpper:this.tickUpper}).amount1;return{amount0:s.quotient,amount1:u.quotient}},e.fromAmounts=function(t){var n=t.pool,r=t.tickLower,i=t.tickUpper,o=t.amount0,a=t.amount1,s=t.useFullPrecision,l=ei.getSqrtRatioAtTick(r),c=ei.getSqrtRatioAtTick(i);return new e({pool:n,tickLower:r,tickUpper:i,liquidity:function(e,t,n,r,i,o){if(u().greaterThan(t,n)){var a=[n,t];t=a[0],n=a[1]}var s=o?ef:ep;if(u().lessThanOrEqual(e,t))return s(t,n,r);if(!u().lessThan(e,n))return eh(t,n,i);var l=s(e,n,r),c=eh(t,e,i);return u().lessThan(l,c)?l:c}(n.sqrtRatioX96,l,c,o,a,s)})},e.fromAmount0=function(t){var n=t.pool,r=t.tickLower,i=t.tickUpper,o=t.amount0,s=t.useFullPrecision;return e.fromAmounts({pool:n,tickLower:r,tickUpper:i,amount0:o,amount1:a.Bz,useFullPrecision:s})},e.fromAmount1=function(t){var n=t.pool,r=t.tickLower,i=t.tickUpper,o=t.amount1;return e.fromAmounts({pool:n,tickLower:r,tickUpper:i,amount0:a.Bz,amount1:o,useFullPrecision:!0})},L(e,[{key:"token0PriceLower",get:function(){return eg(this.pool.token0,this.pool.token1,this.tickLower)}},{key:"token0PriceUpper",get:function(){return eg(this.pool.token0,this.pool.token1,this.tickUpper)}},{key:"amount0",get:function(){return null===this._token0Amount&&(this.pool.tickCurrent0||(0,l.Z)(!1);var r=e[0].chainId;e.every(function(e){return e.chainId===r})||(0,l.Z)(!1);var i=t.wrapped;e[0].involvesToken(i)||(0,l.Z)(!1),e[e.length-1].involvesToken(n.wrapped)||(0,l.Z)(!1);for(var o,a=[i],s=F(e.entries());!(o=s()).done;){var u=o.value,c=u[0],d=u[1],p=a[c];p.equals(d.token0)||p.equals(d.token1)||(0,l.Z)(!1);var f=p.equals(d.token0)?d.token1:d.token0;a.push(f)}this.pools=e,this.tokenPath=a,this.input=t,this.output=null!=n?n:a[a.length-1]}return L(e,[{key:"chainId",get:function(){return this.pools[0].chainId}},{key:"midPrice",get:function(){if(null!==this._midPrice)return this._midPrice;var e=this.pools.slice(1).reduce(function(e,t){var n=e.nextInput,r=e.price;return n.equals(t.token0)?{nextInput:t.token1,price:r.multiply(t.token0Price)}:{nextInput:t.token0,price:r.multiply(t.token1Price)}},this.pools[0].token0.equals(this.input.wrapped)?{nextInput:this.pools[0].token1,price:this.pools[0].token0Price}:{nextInput:this.pools[0].token0,price:this.pools[0].token1Price}).price;return this._midPrice=new a.tA(this.input,this.output,e.denominator,e.numerator)}}]),e}();function eA(e,t){return(e.inputAmount.currency.equals(t.inputAmount.currency)||(0,l.Z)(!1),e.outputAmount.currency.equals(t.outputAmount.currency)||(0,l.Z)(!1),e.outputAmount.equalTo(t.outputAmount))?e.inputAmount.equalTo(t.inputAmount)?e.swaps.reduce(function(e,t){return e+t.route.tokenPath.length},0)-t.swaps.reduce(function(e,t){return e+t.route.tokenPath.length},0):e.inputAmount.lessThan(t.inputAmount)?-1:1:e.outputAmount.lessThan(t.outputAmount)?1:-1}var eS=function(){function e(e){var t=e.routes,n=e.tradeType,r=t[0].inputAmount.currency,i=t[0].outputAmount.currency;t.every(function(e){var t=e.route;return r.wrapped.equals(t.input.wrapped)})||(0,l.Z)(!1),t.every(function(e){var t=e.route;return i.wrapped.equals(t.output.wrapped)})||(0,l.Z)(!1);for(var o,a=t.map(function(e){return e.route.pools.length}).reduce(function(e,t){return e+t},0),s=new Set,u=F(t);!(o=u()).done;)for(var c,d=o.value.route,p=F(d.pools);!(c=p()).done;){var f=c.value;s.add(ew.getAddress(f.token0,f.token1,f.fee))}a!==s.size&&(0,l.Z)(!1),this.swaps=t,this.tradeType=n}e.exactIn=(t=M(O().mark(function t(n,r){return O().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",e.fromRoute(n,r,a.YL.EXACT_INPUT));case 1:case"end":return t.stop()}},t)})),function(e,n){return t.apply(this,arguments)}),e.exactOut=(n=M(O().mark(function t(n,r){return O().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",e.fromRoute(n,r,a.YL.EXACT_OUTPUT));case 1:case"end":return t.stop()}},t)})),function(e,t){return n.apply(this,arguments)}),e.fromRoute=(r=M(O().mark(function t(n,r,i){var o,s,u,c,d,p,f,h,m;return O().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(o=Array(n.tokenPath.length),i!==a.YL.EXACT_INPUT){t.next=19;break}r.currency.equals(n.input)||(0,l.Z)(!1),o[0]=r.wrapped,c=0;case 5:if(!(c0)){t.next=32;break}return h=n.pools[f-1],t.next=26,h.getInputAmount(o[f]);case 26:m=t.sent[0],o[f-1]=m;case 29:f--,t.next=22;break;case 32:s=a.ih.fromFractionalAmount(n.input,o[0].numerator,o[0].denominator),u=a.ih.fromFractionalAmount(n.output,r.numerator,r.denominator);case 34:return t.abrupt("return",new e({routes:[{inputAmount:s,outputAmount:u,route:n}],tradeType:i}));case 35:case"end":return t.stop()}},t)})),function(e,t,n){return r.apply(this,arguments)}),e.fromRoutes=(i=M(O().mark(function t(n,r){var i,o,s,u,c,d,p,f,h,m,g,y,b,_,v;return O().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:i=[],o=F(n);case 2:if((s=o()).done){t.next=43;break}if(c=(u=s.value).route,d=u.amount,p=Array(c.tokenPath.length),f=void 0,h=void 0,r!==a.YL.EXACT_INPUT){t.next=25;break}d.currency.equals(c.input)||(0,l.Z)(!1),f=a.ih.fromFractionalAmount(c.input,d.numerator,d.denominator),p[0]=a.ih.fromFractionalAmount(c.input.wrapped,d.numerator,d.denominator),m=0;case 12:if(!(m0)){t.next=39;break}return _=c.pools[b-1],t.next=33,_.getInputAmount(p[b]);case 33:v=t.sent[0],p[b-1]=v;case 36:b--,t.next=29;break;case 39:f=a.ih.fromFractionalAmount(c.input,p[0].numerator,p[0].denominator);case 40:i.push({route:c,inputAmount:f,outputAmount:h});case 41:t.next=2;break;case 43:return t.abrupt("return",new e({routes:i,tradeType:r}));case 44:case"end":return t.stop()}},t)})),function(e,t){return i.apply(this,arguments)}),e.createUncheckedTrade=function(t){return new e(N({},t,{routes:[{inputAmount:t.inputAmount,outputAmount:t.outputAmount,route:t.route}]}))},e.createUncheckedTradeWithMultipleRoutes=function(t){return new e(t)};var t,n,r,i,o,s,u=e.prototype;return u.minimumAmountOut=function(e,t){if(void 0===t&&(t=this.outputAmount),e.lessThan(z)&&(0,l.Z)(!1),this.tradeType===a.YL.EXACT_OUTPUT)return t;var n=new a.iA(V).add(e).invert().multiply(t.quotient).quotient;return a.ih.fromRawAmount(t.currency,n)},u.maximumAmountIn=function(e,t){if(void 0===t&&(t=this.inputAmount),e.lessThan(z)&&(0,l.Z)(!1),this.tradeType===a.YL.EXACT_INPUT)return t;var n=new a.iA(V).add(e).multiply(t.quotient).quotient;return a.ih.fromRawAmount(t.currency,n)},u.worstExecutionPrice=function(e){return new a.tA(this.inputAmount.currency,this.outputAmount.currency,this.maximumAmountIn(e).quotient,this.minimumAmountOut(e).quotient)},e.bestTradeExactIn=(o=M(O().mark(function t(n,r,i,o,s,u,c){var d,p,f,h,m,g,y,b,_,v,w;return O().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:f=void 0===(p=(d=void 0===o?{}:o).maxNumResults)?3:p,m=void 0===(h=d.maxHops)?3:h,void 0===s&&(s=[]),void 0===u&&(u=r),void 0===c&&(c=[]),n.length>0||(0,l.Z)(!1),m>0||(0,l.Z)(!1),r===u||s.length>0||(0,l.Z)(!1),g=u.wrapped,y=i.wrapped,b=0;case 10:if(!(b1&&n.length>1)){t.next=43;break}return w=n.slice(0,b).concat(n.slice(b+1,n.length)),t.next=43,e.bestTradeExactIn(w,r,i,{maxNumResults:f,maxHops:m-1},[].concat(s,[_]),v,c);case 43:b++,t.next=10;break;case 46:return t.abrupt("return",c);case 47:case"end":return t.stop()}},t,null,[[15,23]])})),function(e,t,n,r,i,a,s){return o.apply(this,arguments)}),e.bestTradeExactOut=(s=M(O().mark(function t(n,r,i,o,s,u,c){var d,p,f,h,m,g,y,b,_,v,w;return O().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:f=void 0===(p=(d=void 0===o?{}:o).maxNumResults)?3:p,m=void 0===(h=d.maxHops)?3:h,void 0===s&&(s=[]),void 0===u&&(u=i),void 0===c&&(c=[]),n.length>0||(0,l.Z)(!1),m>0||(0,l.Z)(!1),i===u||s.length>0||(0,l.Z)(!1),g=u.wrapped,y=r.wrapped,b=0;case 10:if(!(b1&&n.length>1)){t.next=43;break}return w=n.slice(0,b).concat(n.slice(b+1,n.length)),t.next=43,e.bestTradeExactOut(w,r,i,{maxNumResults:f,maxHops:m-1},[_].concat(s),v,c);case 43:b++,t.next=10;break;case 46:return t.abrupt("return",c);case 47:case"end":return t.stop()}},t,null,[[15,23]])})),function(e,t,n,r,i,o,a){return s.apply(this,arguments)}),L(e,[{key:"route",get:function(){return 1!==this.swaps.length&&(0,l.Z)(!1),this.swaps[0].route}},{key:"inputAmount",get:function(){if(this._inputAmount)return this._inputAmount;var e=this.swaps[0].inputAmount.currency,t=this.swaps.map(function(e){return e.inputAmount}).reduce(function(e,t){return e.add(t)},a.ih.fromRawAmount(e,0));return this._inputAmount=t,this._inputAmount}},{key:"outputAmount",get:function(){if(this._outputAmount)return this._outputAmount;var e=this.swaps[0].outputAmount.currency,t=this.swaps.map(function(e){return e.outputAmount}).reduce(function(e,t){return e.add(t)},a.ih.fromRawAmount(e,0));return this._outputAmount=t,this._outputAmount}},{key:"executionPrice",get:function(){var e;return null!=(e=this._executionPrice)?e:this._executionPrice=new a.tA(this.inputAmount.currency,this.outputAmount.currency,this.inputAmount.quotient,this.outputAmount.quotient)}},{key:"priceImpact",get:function(){if(this._priceImpact)return this._priceImpact;for(var e,t=a.ih.fromRawAmount(this.outputAmount.currency,0),n=F(this.swaps);!(e=n()).done;){var r=e.value,i=r.route,o=r.inputAmount,s=i.midPrice;t=t.add(s.quote(o))}var u=t.subtract(this.outputAmount).divide(t);return this._priceImpact=new a.gG(u.numerator,u.denominator),this._priceImpact}}]),e}(),eI=function(){function e(){}return e.encodeMulticall=function(t){return Array.isArray(t)||(t=[t]),1===t.length?t[0]:e.INTERFACE.encodeFunctionData("multicall",[t])},e.decodeMulticall=function(t){return e.INTERFACE.decodeFunctionData("multicall",t).data},e}();eI.INTERFACE=new d.vU(x.Mt);var eT=function(){function e(){}return e.encodePermit=function(t,n){return"nonce"in n?e.INTERFACE.encodeFunctionData("selfPermitAllowed",[t.address,el(n.nonce),el(n.expiry),n.v,n.r,n.s]):e.INTERFACE.encodeFunctionData("selfPermit",[t.address,el(n.amount),el(n.deadline),n.v,n.r,n.s])},e}();eT.INTERFACE=new d.vU(S.Mt);var eE=function(){function e(){}return e.encodeFeeBips=function(e){return el(e.multiply(1e4).quotient)},e.encodeUnwrapWETH9=function(t,n,r){if(n=(0,a.qn)(n),!r)return e.INTERFACE.encodeFunctionData("unwrapWETH9",[el(t),n]);var i=this.encodeFeeBips(r.fee),o=(0,a.qn)(r.recipient);return e.INTERFACE.encodeFunctionData("unwrapWETH9WithFee",[el(t),n,i,o])},e.encodeSweepToken=function(t,n,r,i){if(r=(0,a.qn)(r),!i)return e.INTERFACE.encodeFunctionData("sweepToken",[t.address,el(n),r]);var o=this.encodeFeeBips(i.fee),s=(0,a.qn)(i.recipient);return e.INTERFACE.encodeFunctionData("sweepTokenWithFee",[t.address,el(n),r,o,s])},e.encodeRefundETH=function(){return e.INTERFACE.encodeFunctionData("refundETH")},e}();eE.INTERFACE=new d.vU(I.Mt);var eP=["expectedCurrencyOwed0","expectedCurrencyOwed1"],eC=el(u().subtract(u().exponentiate(u().BigInt(2),u().BigInt(128)),u().BigInt(1)));function eO(e){return Object.keys(e).some(function(e){return"recipient"===e})}var eB={Permit:[{name:"spender",type:"address"},{name:"tokenId",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},eM=function(){function e(){}return e.encodeCreate=function(t){return e.INTERFACE.encodeFunctionData("createAndInitializePoolIfNecessary",[t.token0.address,t.token1.address,t.fee,el(t.sqrtRatioX96)])},e.createCallParameters=function(e){return{calldata:this.encodeCreate(e),value:el(0)}},e.addCallParameters=function(t,n){u().greaterThan(t.liquidity,z)||(0,l.Z)(!1);var r=[],i=t.mintAmounts,o=i.amount0,s=i.amount1,c=t.mintAmountsWithSlippage(n.slippageTolerance),d=el(c.amount0),p=el(c.amount1),f=el(n.deadline);if(eO(n)&&n.createPool&&r.push(this.encodeCreate(t.pool)),n.token0Permit&&r.push(eT.encodePermit(t.pool.token0,n.token0Permit)),n.token1Permit&&r.push(eT.encodePermit(t.pool.token1,n.token1Permit)),eO(n)){var h=(0,a.qn)(n.recipient);r.push(e.INTERFACE.encodeFunctionData("mint",[{token0:t.pool.token0.address,token1:t.pool.token1.address,fee:t.pool.fee,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Desired:el(o),amount1Desired:el(s),amount0Min:d,amount1Min:p,recipient:h,deadline:f}]))}else r.push(e.INTERFACE.encodeFunctionData("increaseLiquidity",[{tokenId:el(n.tokenId),amount0Desired:el(o),amount1Desired:el(s),amount0Min:d,amount1Min:p,deadline:f}]));var m=el(0);if(n.useNative){var g=n.useNative.wrapped;t.pool.token0.equals(g)||t.pool.token1.equals(g)||(0,l.Z)(!1);var y=t.pool.token0.equals(g)?o:s;u().greaterThan(y,z)&&r.push(eE.encodeRefundETH()),m=el(y)}return{calldata:eI.encodeMulticall(r),value:m}},e.encodeCollect=function(t){var n=[],r=el(t.tokenId),i=t.expectedCurrencyOwed0.currency.isNative||t.expectedCurrencyOwed1.currency.isNative,o=(0,a.qn)(t.recipient);if(n.push(e.INTERFACE.encodeFunctionData("collect",[{tokenId:r,recipient:i?q:o,amount0Max:eC,amount1Max:eC}])),i){var s=t.expectedCurrencyOwed0.currency.isNative?t.expectedCurrencyOwed0.quotient:t.expectedCurrencyOwed1.quotient,u=t.expectedCurrencyOwed0.currency.isNative?t.expectedCurrencyOwed1.currency:t.expectedCurrencyOwed0.currency,l=t.expectedCurrencyOwed0.currency.isNative?t.expectedCurrencyOwed1.quotient:t.expectedCurrencyOwed0.quotient;n.push(eE.encodeUnwrapWETH9(s,o)),n.push(eE.encodeSweepToken(u,l,o))}return n},e.collectCallParameters=function(t){var n=e.encodeCollect(t);return{calldata:eI.encodeMulticall(n),value:el(0)}},e.removeCallParameters=function(t,n){var r=[],i=el(n.deadline),o=el(n.tokenId),s=new ek({pool:t.pool,liquidity:n.liquidityPercentage.multiply(t.liquidity).quotient,tickLower:t.tickLower,tickUpper:t.tickUpper});u().greaterThan(s.liquidity,z)||(0,l.Z)(!1);var c=s.burnAmountsWithSlippage(n.slippageTolerance),d=c.amount0,p=c.amount1;n.permit&&r.push(e.INTERFACE.encodeFunctionData("permit",[(0,a.qn)(n.permit.spender),o,el(n.permit.deadline),n.permit.v,n.permit.r,n.permit.s])),r.push(e.INTERFACE.encodeFunctionData("decreaseLiquidity",[{tokenId:o,liquidity:el(s.liquidity),amount0Min:el(d),amount1Min:el(p),deadline:i}]));var f=n.collectOptions,h=f.expectedCurrencyOwed0,m=f.expectedCurrencyOwed1,g=function(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r=0||(i[n]=e[n]);return i}(f,eP);return r.push.apply(r,e.encodeCollect(N({tokenId:el(n.tokenId),expectedCurrencyOwed0:h.add(a.ih.fromRawAmount(h.currency,d)),expectedCurrencyOwed1:m.add(a.ih.fromRawAmount(m.currency,p))},g))),n.liquidityPercentage.equalTo(V)?n.burnToken&&r.push(e.INTERFACE.encodeFunctionData("burn",[o])):!0!==n.burnToken||(0,l.Z)(!1),{calldata:eI.encodeMulticall(r),value:el(0)}},e.safeTransferFromParameters=function(t){var n=(0,a.qn)(t.recipient),r=(0,a.qn)(t.sender);return{calldata:t.data?e.INTERFACE.encodeFunctionData("safeTransferFrom(address,address,uint256,bytes)",[r,n,el(t.tokenId),t.data]):e.INTERFACE.encodeFunctionData("safeTransferFrom(address,address,uint256)",[r,n,el(t.tokenId)]),value:el(0)}},e.getPermitData=function(e,t,n){return{domain:{name:"Uniswap V3 Positions NFT-V1",chainId:n,version:"1",verifyingContract:t},types:eB,values:e}},e}();eM.INTERFACE=new d.vU(A.Mt);var eR=function(){function e(){}return e.quoteCallParameters=function(e,t,n,r){void 0===r&&(r={});var i=1===e.pools.length,o=el(t.quotient),s=r.useQuoterV2?this.V2INTERFACE:this.V1INTERFACE;if(i){var u,c,d,p={tokenIn:e.tokenPath[0].address,tokenOut:e.tokenPath[1].address,fee:e.pools[0].fee,sqrtPriceLimitX96:el(null!=(c=null==(d=r)?void 0:d.sqrtPriceLimitX96)?c:0)},f=N({},p,n===a.YL.EXACT_INPUT?{amountIn:o}:{amount:o}),h=[p.tokenIn,p.tokenOut,p.fee,o,p.sqrtPriceLimitX96],m=n===a.YL.EXACT_INPUT?"quoteExactInputSingle":"quoteExactOutputSingle";u=s.encodeFunctionData(m,r.useQuoterV2?[f]:h)}else{(null==(g=r)?void 0:g.sqrtPriceLimitX96)!==void 0&&(0,l.Z)(!1);var g,y=ec(e,n===a.YL.EXACT_OUTPUT),b=n===a.YL.EXACT_INPUT?"quoteExactInput":"quoteExactOutput";u=s.encodeFunctionData(b,[y,o])}return{calldata:u,value:el(0)}},e}();eR.V1INTERFACE=new d.vU(T.Mt),eR.V2INTERFACE=new d.vU(E.Mt);var eL=function(){function e(){}return e.encodeClaim=function(t,n){var r,i=[];i.push(e.INTERFACE.encodeFunctionData("unstakeToken",[this._encodeIncentiveKey(t),el(n.tokenId)]));var o=(0,a.qn)(n.recipient),s=null!=(r=n.amount)?r:0;return i.push(e.INTERFACE.encodeFunctionData("claimReward",[t.rewardToken.address,o,el(s)])),i},e.collectRewards=function(t,n){t=Array.isArray(t)?t:[t];for(var r=[],i=0;i1){for(var n,r=[],i=0;i0&&x>_&&w[k].length>0&&(k++,x=(e.length-2)/2,w[k]=[]),w[k]=[...w[k],{allowFailure:!0,callData:e,target:r}]}catch(a){let e=(0,c.S)(a,{abi:t,address:r,args:i,docsPath:"/docs/contract/multicall",functionName:o});if(!n)throw e;w[k]=[...w[k],{allowFailure:!0,callData:"0x",target:r}]}}let A=await Promise.allSettled(w.map(t=>(0,d.s)(e,p.L,"readContract")({abi:r.F8,address:v,args:[t],blockNumber:h,blockTag:m,functionName:"aggregate3",stateOverride:y}))),S=[];for(let e=0;e(0,i.A)(e,{...u,allowFailure:n,blockNumber:a,blockTag:s,chainId:Number.parseInt(t),contracts:r.map(({contract:e})=>e)})))).flat(),o=Object.values(t).flatMap(e=>e.map(({index:e})=>e));return r.reduce((e,t,n)=>(e&&(e[o[n]]=t),e),[])}catch(i){if(i instanceof r.uq)throw i;let t=()=>l.map(t=>(0,o.L)(e,{...t,blockNumber:a,blockTag:s}));if(n)return(await Promise.allSettled(t())).map(e=>"fulfilled"===e.status?{result:e.value,status:"success"}:{error:e.reason,result:void 0,status:"failure"});return await Promise.all(t())}}},93298:function(e,t,n){"use strict";n.d(t,{G:function(){return u}});var r,i,o=n(36922);let a=()=>`@wagmi/core@${o.i}`;var s=function(e,t,n,r){if("a"===n&&!r)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class u extends Error{get docsBaseUrl(){return"https://wagmi.sh/core"}get version(){return a()}constructor(e,t={}){super(),r.add(this),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"WagmiCoreError"});let n=t.cause instanceof u?t.cause.details:t.cause?.message?t.cause.message:t.details,i=t.cause instanceof u&&t.cause.docsPath||t.docsPath;this.message=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...i?[`Docs: ${this.docsBaseUrl}${i}.html${t.docsSlug?`#${t.docsSlug}`:""}`]:[],...n?[`Details: ${n}`]:[],`Version: ${this.version}`].join("\n"),t.cause&&(this.cause=t.cause),this.details=n,this.docsPath=i,this.metaMessages=t.metaMessages,this.shortMessage=e}walk(e){return s(this,r,"m",i).call(this,this,e)}}r=new WeakSet,i=function e(t,n){return n?.(t)?t:t.cause?s(this,r,"m",e).call(this,t.cause,n):t}},31800:function(e,t,n){"use strict";n.d(t,{$S:function(){return l},JK:function(){return s},X4:function(){return i},XZ:function(){return u},aH:function(){return a},wi:function(){return o}});var r=n(93298);class i extends r.G{constructor(){super("Chain not configured."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ChainNotConfiguredError"})}}class o extends r.G{constructor(){super("Connector already connected."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorAlreadyConnectedError"})}}class a extends r.G{constructor(){super("Connector not connected."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorNotConnectedError"})}}class s extends r.G{constructor({address:e,connector:t}){super(`Account "${e}" not found for connector "${t.name}".`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorAccountNotFoundError"})}}class u extends r.G{constructor({connectionChainId:e,connectorChainId:t}){super(`The current chain of the connector (id: ${t}) does not match the connection's chain (id: ${e}).`,{metaMessages:[`Current Chain ID: ${t}`,`Expected Chain ID: ${e}`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorChainMismatchError"})}}class l extends r.G{constructor({connector:e}){super(`Connector "${e.name}" unavailable while reconnecting.`,{details:"During the reconnection step, the only connector methods guaranteed to be available are: `id`, `name`, `type`, `uid`. All other methods are not guaranteed to be available until reconnection completes and connectors are fully restored. This error commonly occurs for connectors that asynchronously inject after reconnection has already started."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ConnectorUnavailableReconnectingError"})}}},28095:function(e,t,n){"use strict";n.d(t,{M:function(){return i},O:function(){return o}});var r=n(93298);class i extends r.G{constructor(){super("Provider not found."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ProviderNotFoundError"})}}class o extends r.G{constructor({connector:e}){super(`"${e.name}" does not support programmatic chain switching.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SwitchChainNotSupportedError"})}}},6591:function(e,t,n){"use strict";function r(e,t,n){let r=e[t.name];if("function"==typeof r)return r;let i=e[n];return"function"==typeof i?i:n=>t(e,n)}n.d(t,{s:function(){return r}})},36922:function(e,t,n){"use strict";n.d(t,{i:function(){return r}});let r="2.16.7"},46278:function(e,t,n){"use strict";let r;function i(e,t){return function(){return e.apply(t,arguments)}}n.d(t,{Z:function(){return e2}});let{toString:o}=Object.prototype,{getPrototypeOf:a}=Object,s=(Z=Object.create(null),e=>{let t=o.call(e);return Z[t]||(Z[t]=t.slice(8,-1).toLowerCase())}),u=e=>(e=e.toLowerCase(),t=>s(t)===e),l=e=>t=>typeof t===e,{isArray:c}=Array,d=l("undefined"),p=u("ArrayBuffer"),f=l("string"),h=l("function"),m=l("number"),g=e=>null!==e&&"object"==typeof e,y=e=>{if("object"!==s(e))return!1;let t=a(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},b=u("Date"),_=u("File"),v=u("Blob"),w=u("FileList"),k=e=>g(e)&&h(e.pipe),x=e=>{let t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||o.call(e)===t||h(e.toString)&&e.toString()===t)},A=u("URLSearchParams"),S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function I(e,t,{allOwnKeys:n=!1}={}){let r,i;if(null!=e){if("object"!=typeof e&&(e=[e]),c(e))for(r=0,i=e.length;r0;)if(t===(n=r[i]).toLowerCase())return n;return null}let E="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:n.g,P=e=>!d(e)&&e!==E,C=(e,t,n,{allOwnKeys:r}={})=>(I(t,(t,r)=>{n&&h(t)?e[r]=i(t,n):e[r]=t},{allOwnKeys:r}),e),O=e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),B=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},M=(e,t,n,r)=>{let i,o,s;let u={};if(t=t||{},null==e)return t;do{for(o=(i=Object.getOwnPropertyNames(e)).length;o-- >0;)s=i[o],(!r||r(s,e,t))&&!u[s]&&(t[s]=e[s],u[s]=!0);e=!1!==n&&a(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},R=(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;let r=e.indexOf(t,n);return -1!==r&&r===n},L=e=>{if(!e)return null;if(c(e))return e;let t=e.length;if(!m(t))return null;let n=Array(t);for(;t-- >0;)n[t]=e[t];return n},N=(Y="undefined"!=typeof Uint8Array&&a(Uint8Array),e=>Y&&e instanceof Y),D=(e,t)=>{let n;let r=e&&e[Symbol.iterator],i=r.call(e);for(;(n=i.next())&&!n.done;){let r=n.value;t.call(e,r[0],r[1])}},F=(e,t)=>{let n;let r=[];for(;null!==(n=e.exec(t));)r.push(n);return r},q=u("HTMLFormElement"),j=e=>e.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,function(e,t,n){return t.toUpperCase()+n}),U=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),z=u("RegExp"),V=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={};I(n,(n,i)=>{!1!==t(n,i,e)&&(r[i]=n)}),Object.defineProperties(e,r)},W=e=>{V(e,(t,n)=>{if(h(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;let r=e[n];if(h(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},$=(e,t)=>{let n={};return(e=>{e.forEach(e=>{n[e]=!0})})(c(e)?e:String(e).split(t)),n},K=()=>{},H=(e,t)=>Number.isFinite(e=+e)?e:t,G=e=>{let t=Array(10),n=(e,r)=>{if(g(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[r]=e;let i=c(e)?[]:{};return I(e,(e,t)=>{let o=n(e,r+1);d(o)||(i[t]=o)}),t[r]=void 0,i}}return e};return n(e,0)};var Z,Y,X={isArray:c,isArrayBuffer:p,isBuffer:function(e){return null!==e&&!d(e)&&null!==e.constructor&&!d(e.constructor)&&h(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:x,isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&p(e.buffer)},isString:f,isNumber:m,isBoolean:e=>!0===e||!1===e,isObject:g,isPlainObject:y,isUndefined:d,isDate:b,isFile:_,isBlob:v,isRegExp:z,isFunction:h,isStream:k,isURLSearchParams:A,isTypedArray:N,isFileList:w,forEach:I,merge:function e(){let{caseless:t}=P(this)&&this||{},n={},r=(r,i)=>{let o=t&&T(n,i)||i;y(n[o])&&y(r)?n[o]=e(n[o],r):y(r)?n[o]=e({},r):c(r)?n[o]=r.slice():n[o]=r};for(let e=0,t=arguments.length;e{ee[e]={value:e}}),Object.defineProperties(Q,ee),Object.defineProperty(J,"isAxiosError",{value:!0}),Q.from=(e,t,n,r,i,o)=>{let a=Object.create(J);return X.toFlatObject(e,a,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),Q.call(a,e.message,t,n,r,i),a.cause=e,a.name=e.name,o&&Object.assign(a,o),a};var et=n(6230),en=n.n(et)(),er=n(48764).Buffer;function ei(e){return X.isPlainObject(e)||X.isArray(e)}function eo(e){return X.endsWith(e,"[]")?e.slice(0,-2):e}function ea(e,t,n){return e?e.concat(t).map(function(e,t){return e=eo(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}let es=X.toFlatObject(X,{},null,function(e){return/^is[A-Z]/.test(e)});var eu=function(e,t,n){var r;if(!X.isObject(e))throw TypeError("target must be an object");t=t||new(en||FormData),n=X.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!X.isUndefined(t[e])});let i=n.metaTokens,o=n.visitor||d,a=n.dots,s=n.indexes,u=n.Blob||"undefined"!=typeof Blob&&Blob,l=u&&(r=t)&&X.isFunction(r.append)&&"FormData"===r[Symbol.toStringTag]&&r[Symbol.iterator];if(!X.isFunction(o))throw TypeError("visitor must be a function");function c(e){if(null===e)return"";if(X.isDate(e))return e.toISOString();if(!l&&X.isBlob(e))throw new Q("Blob is not supported. Use a Buffer instead.");return X.isArrayBuffer(e)||X.isTypedArray(e)?l&&"function"==typeof Blob?new Blob([e]):er.from(e):e}function d(e,n,r){let o=e;if(e&&!r&&"object"==typeof e){if(X.endsWith(n,"{}"))n=i?n:n.slice(0,-2),e=JSON.stringify(e);else{var u;if(X.isArray(e)&&(u=e,X.isArray(u)&&!u.some(ei))||X.isFileList(e)||X.endsWith(n,"[]")&&(o=X.toArray(e)))return n=eo(n),o.forEach(function(e,r){X.isUndefined(e)||null===e||t.append(!0===s?ea([n],r,a):null===s?n:n+"[]",c(e))}),!1}}return!!ei(e)||(t.append(ea(r,n,a),c(e)),!1)}let p=[],f=Object.assign(es,{defaultVisitor:d,convertValue:c,isVisitable:ei});if(!X.isObject(e))throw TypeError("data must be an object");return!function e(n,r){if(!X.isUndefined(n)){if(-1!==p.indexOf(n))throw Error("Circular reference detected in "+r.join("."));p.push(n),X.forEach(n,function(n,i){let a=!(X.isUndefined(n)||null===n)&&o.call(t,n,X.isString(i)?i.trim():i,r,f);!0===a&&e(n,r?r.concat(i):[i])}),p.pop()}}(e),t};function el(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\x00"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function ec(e,t){this._pairs=[],e&&eu(e,this,t)}let ed=ec.prototype;function ep(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ef(e,t,n){let r;if(!t)return e;let i=n&&n.encode||ep,o=n&&n.serialize;if(r=o?o(t,n):X.isURLSearchParams(t)?t.toString():new ec(t,n).toString(i)){let t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+r}return e}ed.append=function(e,t){this._pairs.push([e,t])},ed.toString=function(e){let t=e?function(t){return e.call(this,t,el)}:el;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};var eh=class{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){X.forEach(this.handlers,function(t){null!==t&&e(t)})}},em={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},eg="undefined"!=typeof URLSearchParams?URLSearchParams:ec,ey=FormData;let eb=("undefined"==typeof navigator||"ReactNative"!==(r=navigator.product)&&"NativeScript"!==r&&"NS"!==r)&&"undefined"!=typeof window&&"undefined"!=typeof document,e_="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts;var ev={isBrowser:!0,classes:{URLSearchParams:eg,FormData:ey,Blob},isStandardBrowserEnv:eb,isStandardBrowserWebWorkerEnv:e_,protocols:["http","https","file","blob","url","data"]},ew=function(e){if(X.isFormData(e)&&X.isFunction(e.entries)){let t={};return X.forEachEntry(e,(e,n)=>{!function e(t,n,r,i){let o=t[i++],a=Number.isFinite(+o),s=i>=t.length;if(o=!o&&X.isArray(r)?r.length:o,s)return X.hasOwnProp(r,o)?r[o]=[r[o],n]:r[o]=n,!a;r[o]&&X.isObject(r[o])||(r[o]=[]);let u=e(t,n,r[o],i);return u&&X.isArray(r[o])&&(r[o]=function(e){let t,n;let r={},i=Object.keys(e),o=i.length;for(t=0;t"[]"===e[0]?"":e[1]||e[0]),n,t,0)}),t}return null};let ek={"Content-Type":void 0},ex={transitional:em,adapter:["xhr","http"],transformRequest:[function(e,t){let n;let r=t.getContentType()||"",i=r.indexOf("application/json")>-1,o=X.isObject(e);o&&X.isHTMLForm(e)&&(e=new FormData(e));let a=X.isFormData(e);if(a)return i&&i?JSON.stringify(ew(e)):e;if(X.isArrayBuffer(e)||X.isBuffer(e)||X.isStream(e)||X.isFile(e)||X.isBlob(e))return e;if(X.isArrayBufferView(e))return e.buffer;if(X.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1){var s,u;return(s=e,u=this.formSerializer,eu(s,new ev.classes.URLSearchParams,Object.assign({visitor:function(e,t,n,r){return ev.isNode&&X.isBuffer(e)?(this.append(t,e.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},u))).toString()}if((n=X.isFileList(e))||r.indexOf("multipart/form-data")>-1){let t=this.env&&this.env.FormData;return eu(n?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||i?(t.setContentType("application/json",!1),function(e,t,n){if(X.isString(e))try{return(0,JSON.parse)(e),X.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(0,JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){let t=this.transitional||ex.transitional,n=t&&t.forcedJSONParsing,r="json"===this.responseType;if(e&&X.isString(e)&&(n&&!this.responseType||r)){let n=t&&t.silentJSONParsing;try{return JSON.parse(e)}catch(e){if(!n&&r){if("SyntaxError"===e.name)throw Q.from(e,Q.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ev.classes.FormData,Blob:ev.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};X.forEach(["delete","get","head"],function(e){ex.headers[e]={}}),X.forEach(["post","put","patch"],function(e){ex.headers[e]=X.merge(ek)});let eA=X.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);var eS=e=>{let t,n,r;let i={};return e&&e.split("\n").forEach(function(e){r=e.indexOf(":"),t=e.substring(0,r).trim().toLowerCase(),n=e.substring(r+1).trim(),!t||i[t]&&eA[t]||("set-cookie"===t?i[t]?i[t].push(n):i[t]=[n]:i[t]=i[t]?i[t]+", "+n:n)}),i};let eI=Symbol("internals");function eT(e){return e&&String(e).trim().toLowerCase()}function eE(e){return!1===e||null==e?e:X.isArray(e)?e.map(eE):String(e)}function eP(e,t,n,r){if(X.isFunction(r))return r.call(this,t,n);if(X.isString(t)){if(X.isString(r))return -1!==t.indexOf(r);if(X.isRegExp(r))return r.test(t)}}class eC{constructor(e){e&&this.set(e)}set(e,t,n){let r=this;function i(e,t,n){let i=eT(t);if(!i)throw Error("header name must be a non-empty string");let o=X.findKey(r,i);o&&void 0!==r[o]&&!0!==n&&(void 0!==n||!1===r[o])||(r[o||t]=eE(e))}let o=(e,t)=>X.forEach(e,(e,n)=>i(e,n,t));if(X.isPlainObject(e)||e instanceof this.constructor)o(e,t);else{var a;X.isString(e)&&(e=e.trim())&&(a=e,!/^[-_a-zA-Z]+$/.test(a.trim()))?o(eS(e),t):null!=e&&i(t,e,n)}return this}get(e,t){if(e=eT(e)){let n=X.findKey(this,e);if(n){let e=this[n];if(!t)return e;if(!0===t)return function(e){let t;let n=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;for(;t=r.exec(e);)n[t[1]]=t[2];return n}(e);if(X.isFunction(t))return t.call(this,e,n);if(X.isRegExp(t))return t.exec(e);throw TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=eT(e)){let n=X.findKey(this,e);return!!(n&&(!t||eP(this,this[n],n,t)))}return!1}delete(e,t){let n=this,r=!1;function i(e){if(e=eT(e)){let i=X.findKey(n,e);i&&(!t||eP(n,n[i],i,t))&&(delete n[i],r=!0)}}return X.isArray(e)?e.forEach(i):i(e),r}clear(){return Object.keys(this).forEach(this.delete.bind(this))}normalize(e){let t=this,n={};return X.forEach(this,(r,i)=>{let o=X.findKey(n,i);if(o){t[o]=eE(r),delete t[i];return}let a=e?i.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n):String(i).trim();a!==i&&delete t[i],t[a]=eE(r),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let t=Object.create(null);return X.forEach(this,(n,r)=>{null!=n&&!1!==n&&(t[r]=e&&X.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){let n=new this(e);return t.forEach(e=>n.set(e)),n}static accessor(e){let t=this[eI]=this[eI]={accessors:{}},n=t.accessors,r=this.prototype;function i(e){let t=eT(e);n[t]||(!function(e,t){let n=X.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(e,n,i){return this[r].call(this,t,e,n,i)},configurable:!0})})}(r,e),n[t]=!0)}return X.isArray(e)?e.forEach(i):i(e),this}}function eO(e,t){let n=this||ex,r=t||n,i=eC.from(r.headers),o=r.data;return X.forEach(e,function(e){o=e.call(n,o,i.normalize(),t?t.status:void 0)}),i.normalize(),o}function eB(e){return!!(e&&e.__CANCEL__)}function eM(e,t,n){Q.call(this,null==e?"canceled":e,Q.ERR_CANCELED,t,n),this.name="CanceledError"}eC.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),X.freezeMethods(eC.prototype),X.freezeMethods(eC),X.inherits(eM,Q,{__CANCEL__:!0});var eR=ev.isStandardBrowserEnv?{write:function(e,t,n,r,i,o){let a=[];a.push(e+"="+encodeURIComponent(t)),X.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),X.isString(r)&&a.push("path="+r),X.isString(i)&&a.push("domain="+i),!0===o&&a.push("secure"),document.cookie=a.join("; ")},read:function(e){let t=document.cookie.match(RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}};function eL(e,t){return e&&!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e:t}var eN=ev.isStandardBrowserEnv?function(){let e;let t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");function r(e){let r=e;return t&&(n.setAttribute("href",r),r=n.href),n.setAttribute("href",r),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}return e=r(window.location.href),function(t){let n=X.isString(t)?r(t):t;return n.protocol===e.protocol&&n.host===e.host}}():function(){return!0},eD=function(e,t){let n;e=e||10;let r=Array(e),i=Array(e),o=0,a=0;return t=void 0!==t?t:1e3,function(s){let u=Date.now(),l=i[a];n||(n=u),r[o]=s,i[o]=u;let c=a,d=0;for(;c!==o;)d+=r[c++],c%=e;if((o=(o+1)%e)===a&&(a=(a+1)%e),u-n{let o=i.loaded,a=i.lengthComputable?i.total:void 0,s=o-n,u=r(s);n=o;let l={loaded:o,total:a,progress:a?o/a:void 0,bytes:s,rate:u||void 0,estimated:u&&a&&o<=a?(a-o)/u:void 0,event:i};l[t?"download":"upload"]=!0,e(l)}}let eq="undefined"!=typeof XMLHttpRequest;var ej=eq&&function(e){return new Promise(function(t,n){let r,i=e.data,o=eC.from(e.headers).normalize(),a=e.responseType;function s(){e.cancelToken&&e.cancelToken.unsubscribe(r),e.signal&&e.signal.removeEventListener("abort",r)}X.isFormData(i)&&(ev.isStandardBrowserEnv||ev.isStandardBrowserWebWorkerEnv)&&o.setContentType(!1);let u=new XMLHttpRequest;if(e.auth){let t=e.auth.username||"",n=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";o.set("Authorization","Basic "+btoa(t+":"+n))}let l=eL(e.baseURL,e.url);function c(){if(!u)return;let r=eC.from("getAllResponseHeaders"in u&&u.getAllResponseHeaders()),i=a&&"text"!==a&&"json"!==a?u.response:u.responseText,o={data:i,status:u.status,statusText:u.statusText,headers:r,config:e,request:u};!function(e,t,n){let r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Q("Request failed with status code "+n.status,[Q.ERR_BAD_REQUEST,Q.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}(function(e){t(e),s()},function(e){n(e),s()},o),u=null}if(u.open(e.method.toUpperCase(),ef(l,e.params,e.paramsSerializer),!0),u.timeout=e.timeout,"onloadend"in u?u.onloadend=c:u.onreadystatechange=function(){u&&4===u.readyState&&(0!==u.status||u.responseURL&&0===u.responseURL.indexOf("file:"))&&setTimeout(c)},u.onabort=function(){u&&(n(new Q("Request aborted",Q.ECONNABORTED,e,u)),u=null)},u.onerror=function(){n(new Q("Network Error",Q.ERR_NETWORK,e,u)),u=null},u.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",r=e.transitional||em;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),n(new Q(t,r.clarifyTimeoutError?Q.ETIMEDOUT:Q.ECONNABORTED,e,u)),u=null},ev.isStandardBrowserEnv){let t=(e.withCredentials||eN(l))&&e.xsrfCookieName&&eR.read(e.xsrfCookieName);t&&o.set(e.xsrfHeaderName,t)}void 0===i&&o.setContentType(null),"setRequestHeader"in u&&X.forEach(o.toJSON(),function(e,t){u.setRequestHeader(t,e)}),X.isUndefined(e.withCredentials)||(u.withCredentials=!!e.withCredentials),a&&"json"!==a&&(u.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&u.addEventListener("progress",eF(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&u.upload&&u.upload.addEventListener("progress",eF(e.onUploadProgress)),(e.cancelToken||e.signal)&&(r=t=>{u&&(n(!t||t.type?new eM(null,e,u):t),u.abort(),u=null)},e.cancelToken&&e.cancelToken.subscribe(r),e.signal&&(e.signal.aborted?r():e.signal.addEventListener("abort",r)));let d=function(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(l);if(d&&-1===ev.protocols.indexOf(d)){n(new Q("Unsupported protocol "+d+":",Q.ERR_BAD_REQUEST,e));return}u.send(i||null)})};let eU={http:null,xhr:ej};X.forEach(eU,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});var ez={getAdapter:e=>{let t,n;e=X.isArray(e)?e:[e];let{length:r}=e;for(let i=0;ie instanceof eC?e.toJSON():e;function eK(e,t){t=t||{};let n={};function r(e,t,n){return X.isPlainObject(e)&&X.isPlainObject(t)?X.merge.call({caseless:n},e,t):X.isPlainObject(t)?X.merge({},t):X.isArray(t)?t.slice():t}function i(e,t,n){return X.isUndefined(t)?X.isUndefined(e)?void 0:r(void 0,e,n):r(e,t,n)}function o(e,t){if(!X.isUndefined(t))return r(void 0,t)}function a(e,t){return X.isUndefined(t)?X.isUndefined(e)?void 0:r(void 0,e):r(void 0,t)}function s(n,i,o){return o in t?r(n,i):o in e?r(void 0,n):void 0}let u={url:o,method:o,data:o,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:s,headers:(e,t)=>i(e$(e),e$(t),!0)};return X.forEach(Object.keys(e).concat(Object.keys(t)),function(r){let o=u[r]||i,a=o(e[r],t[r],r);X.isUndefined(a)&&o!==s||(n[r]=a)}),n}let eH="1.2.6",eG={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{eG[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});let eZ={};eG.transitional=function(e,t,n){function r(e,t){return"[Axios v"+eH+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,i,o)=>{if(!1===e)throw new Q(r(i," has been removed"+(t?" in "+t:"")),Q.ERR_DEPRECATED);return t&&!eZ[i]&&(eZ[i]=!0,console.warn(r(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,i,o)}};var eY={assertOptions:function(e,t,n){if("object"!=typeof e)throw new Q("options must be an object",Q.ERR_BAD_OPTION_VALUE);let r=Object.keys(e),i=r.length;for(;i-- >0;){let o=r[i],a=t[o];if(a){let t=e[o],n=void 0===t||a(t,o,e);if(!0!==n)throw new Q("option "+o+" must be "+n,Q.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new Q("Unknown option "+o,Q.ERR_BAD_OPTION)}},validators:eG};let eX=eY.validators;class eQ{constructor(e){this.defaults=e,this.interceptors={request:new eh,response:new eh}}request(e,t){let n,r,i;"string"==typeof e?(t=t||{}).url=e:t=e||{},t=eK(this.defaults,t);let{transitional:o,paramsSerializer:a,headers:s}=t;void 0!==o&&eY.assertOptions(o,{silentJSONParsing:eX.transitional(eX.boolean),forcedJSONParsing:eX.transitional(eX.boolean),clarifyTimeoutError:eX.transitional(eX.boolean)},!1),void 0!==a&&eY.assertOptions(a,{encode:eX.function,serialize:eX.function},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase(),(n=s&&X.merge(s.common,s[t.method]))&&X.forEach(["delete","get","head","post","put","patch","common"],e=>{delete s[e]}),t.headers=eC.concat(n,s);let u=[],l=!0;this.interceptors.request.forEach(function(e){("function"!=typeof e.runWhen||!1!==e.runWhen(t))&&(l=l&&e.synchronous,u.unshift(e.fulfilled,e.rejected))});let c=[];this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let d=0;if(!l){let e=[eW.bind(this),void 0];for(e.unshift.apply(e,u),e.push.apply(e,c),i=e.length,r=Promise.resolve(t);d{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null}),this.promise.then=e=>{let t;let r=new Promise(e=>{n.subscribe(e),t=e}).then(e);return r.cancel=function(){n.unsubscribe(t)},r},e(function(e,r,i){n.reason||(n.reason=new eM(e,r,i),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}static source(){let e;let t=new eJ(function(t){e=t});return{token:t,cancel:e}}}let e0={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(e0).forEach(([e,t])=>{e0[t]=e});let e1=function e(t){let n=new eQ(t),r=i(eQ.prototype.request,n);return X.extend(r,eQ.prototype,n,{allOwnKeys:!0}),X.extend(r,n,null,{allOwnKeys:!0}),r.create=function(n){return e(eK(t,n))},r}(ex);e1.Axios=eQ,e1.CanceledError=eM,e1.CancelToken=eJ,e1.isCancel=eB,e1.VERSION=eH,e1.toFormData=eu,e1.AxiosError=Q,e1.Cancel=e1.CanceledError,e1.all=function(e){return Promise.all(e)},e1.spread=function(e){return function(t){return e.apply(null,t)}},e1.isAxiosError=function(e){return X.isObject(e)&&!0===e.isAxiosError},e1.mergeConfig=eK,e1.AxiosHeaders=eC,e1.formToJSON=e=>ew(X.isHTMLForm(e)?new FormData(e):e),e1.HttpStatusCode=e0,e1.default=e1;var e2=e1},58162:function(e,t,n){"use strict";var r=n(89509).Buffer;e.exports=function(e){if(e.length>=255)throw TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n>>0,c=new Uint8Array(a);e[n];){var d=t[e.charCodeAt(n)];if(255===d)return;for(var p=0,f=a-1;(0!==d||p>>0,c[f]=d%256>>>0,d=d/256>>>0;if(0!==d)throw Error("Non-zero carry");o=p,n++}for(var h=a-o;h!==a&&0===c[h];)h++;var m=r.allocUnsafe(i+(a-h));m.fill(0,0,i);for(var g=i;h!==a;)m[g++]=c[h++];return m}return{encode:function(t){if((Array.isArray(t)||t instanceof Uint8Array)&&(t=r.from(t)),!r.isBuffer(t))throw TypeError("Expected Buffer");if(0===t.length)return"";for(var n=0,i=0,o=0,a=t.length;o!==a&&0===t[o];)o++,n++;for(var l=(a-o)*c+1>>>0,d=new Uint8Array(l);o!==a;){for(var p=t[o],f=0,h=l-1;(0!==p||f>>0,d[h]=p%s>>>0,p=p/s>>>0;if(0!==p)throw Error("Non-zero carry");i=f,o++}for(var m=l-i;m!==l&&0===d[m];)m++;for(var g=u.repeat(n);m0?a-4:a;for(n=0;n>16&255,l[c++]=t>>8&255,l[c++]=255&t;return 2===s&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,l[c++]=255&t),1===s&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,l[c++]=t>>8&255,l[c++]=255&t),l},t.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],a=0,s=r-i;a>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return o.join("")}(e,a,a+16383>s?s:a+16383));return 1===i?o.push(n[(t=e[r-1])>>2]+n[t<<4&63]+"=="):2===i&&o.push(n[(t=(e[r-2]<<8)+e[r-1])>>10]+n[t>>4&63]+n[t<<2&63]+"="),o.join("")};for(var n=[],r=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,s=o.length;a0)throw Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");-1===n&&(n=t);var r=n===t?0:4-n%4;return[n,r]}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},93302:function(e,t,n){var r;!function(i){"use strict";var o,a="[big.js] ",s=a+"Invalid ",u=s+"decimal places",l=s+"rounding mode",c=a+"Division by zero",d={},p=void 0,f=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function h(e,t,n,r){var i=e.c,o=e.e+t+1;if(o=5;else if(2===n)r=i[o]>5||5==i[o]&&(r||o<0||i[o+1]!==p||1&i[o-1]);else if(3===n)r=r||!!i[0];else if(r=!1,0!==n)throw Error(l);if(o<1)i.length=1,r?(e.e=-t,i[0]=1):i[0]=e.e=0;else{if(i.length=o--,r)for(;++i[o]>9;)i[o]=0,o--||(++e.e,i.unshift(1));for(o=i.length;!i[--o];)i.pop()}}else if(n<0||n>3||n!==~~n)throw Error(l);return e}function m(e,t,n,r){var i,o,a=e.constructor,l=!e.c[0];if(n!==p){if(n!==~~n||n<(3==t)||n>1e6)throw Error(3==t?s+"precision":u);for(n=r-(e=new a(e)).e,e.c.length>++r&&h(e,n,a.RM),2==t&&(r=e.e+n+1);e.c.length=a.PE))o=o.charAt(0)+(n>1?"."+o.slice(1):"")+(i<0?"e":"e+")+i;else if(i<0){for(;++i;)o="0"+o;o="0."+o}else if(i>0){if(++i>n)for(i-=n;i--;)o+="0";else i1&&(o=o.charAt(0)+"."+o.slice(1));return e.s<0&&(!l||4==t)?"-"+o:o}d.abs=function(){var e=new this.constructor(this);return e.s=1,e},d.cmp=function(e){var t,n=this.c,r=(e=new this.constructor(e)).c,i=this.s,o=e.s,a=this.e,s=e.e;if(!n[0]||!r[0])return n[0]?i:r[0]?-o:0;if(i!=o)return i;if(t=i<0,a!=s)return a>s^t?1:-1;for(i=-1,o=(a=n.length)<(s=r.length)?a:s;++ir[i]^t?1:-1;return a==s?0:a>s^t?1:-1},d.div=function(e){var t=this.constructor,n=this.c,r=(e=new t(e)).c,i=this.s==e.s?1:-1,o=t.DP;if(o!==~~o||o<0||o>1e6)throw Error(u);if(!r[0])throw Error(c);if(!n[0])return new t(0*i);var a,s,l,d,f,m=r.slice(),g=a=r.length,y=n.length,b=n.slice(0,a),_=b.length,v=e,w=v.c=[],k=0,x=o+(v.e=this.e-e.e)+1;for(v.s=i,i=x<0?0:x,m.unshift(0);_++_?1:-1;else for(f=-1,d=0;++fb[f]?1:-1;break}if(d<0){for(s=_==a?r:m;_;){if(b[--_]x&&h(v,o,t.RM,b[0]!==p),v},d.eq=function(e){return!this.cmp(e)},d.gt=function(e){return this.cmp(e)>0},d.gte=function(e){return this.cmp(e)>-1},d.lt=function(e){return 0>this.cmp(e)},d.lte=function(e){return 1>this.cmp(e)},d.minus=d.sub=function(e){var t,n,r,i,o=this.constructor,a=this.s,s=(e=new o(e)).s;if(a!=s)return e.s=-s,this.plus(e);var u=this.c.slice(),l=this.e,c=e.c,d=e.e;if(!u[0]||!c[0])return c[0]?(e.s=-s,e):new o(u[0]?this:0);if(a=l-d){for((i=a<0)?(a=-a,r=u):(d=l,r=c),r.reverse(),s=a;s--;)r.push(0);r.reverse()}else for(n=((i=u.length0)for(;s--;)u[t++]=0;for(s=t;n>a;){if(u[--n]0?(s=o,t=u):(r=-r,t=a),t.reverse();r--;)t.push(0);t.reverse()}for(a.length-u.length<0&&(t=u,u=a,a=t),r=u.length,i=0;r;a[r]%=10)i=(a[--r]=a[r]+u[r]+i)/10|0;for(i&&(a.unshift(i),++s),r=a.length;0===a[--r];)a.pop();return e.c=a,e.e=s,e},d.pow=function(e){var t=this,n=new t.constructor(1),r=n,i=e<0;if(e!==~~e||e<-1e6||e>1e6)throw Error(s+"exponent");for(i&&(e=-e);1&e&&(r=r.times(t)),e>>=1;)t=t.times(t);return i?n.div(r):r},d.round=function(e,t){var n=this.constructor;if(e===p)e=0;else if(e!==~~e||e<-1e6||e>1e6)throw Error(u);return h(new n(this),e,t===p?n.RM:t)},d.sqrt=function(){var e,t,n,r=this.constructor,i=this.s,o=this.e,s=new r(.5);if(!this.c[0])return new r(this);if(i<0)throw Error(a+"No square root");0===(i=Math.sqrt(this+""))||i===1/0?((t=this.c.join("")).length+o&1||(t+="0"),i=Math.sqrt(t),o=((o+1)/2|0)-(o<0||1&o),e=new r((i==1/0?"1e":(i=i.toExponential()).slice(0,i.indexOf("e")+1))+o)):e=new r(i),o=e.e+(r.DP+=4);do n=e,e=s.times(n.plus(this.div(n)));while(n.c.slice(0,o).join("")!==e.c.slice(0,o).join(""));return h(e,r.DP-=4,r.RM)},d.times=d.mul=function(e){var t,n=this.constructor,r=this.c,i=(e=new n(e)).c,o=r.length,a=i.length,s=this.e,u=e.e;if(e.s=this.s==e.s?1:-1,!r[0]||!i[0])return new n(0*e.s);for(e.e=s+u,os;)a=t[u]+i[s]*r[u-s-1]+a,t[u--]=a%10,a=a/10|0;t[u]=(t[u]+a)%10}for(a?++e.e:t.shift(),s=t.length;!t[--s];)t.pop();return e.c=t,e},d.toExponential=function(e){return m(this,1,e,e)},d.toFixed=function(e){return m(this,2,e,this.e+e)},d.toPrecision=function(e){return m(this,3,e,e-1)},d.toString=function(){return m(this)},d.valueOf=d.toJSON=function(){return m(this,4)},(o=function e(){function t(n){var r=this;if(!(r instanceof t))return n===p?e():new t(n);n instanceof t?(r.s=n.s,r.e=n.e,r.c=n.c.slice()):function(e,t){var n,r,i;if(0===t&&1/t<0)t="-0";else if(!f.test(t+=""))throw Error(s+"number");for(e.s="-"==t.charAt(0)?(t=t.slice(1),-1):1,(n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),i=t.length,r=0;r0&&"0"==t.charAt(--i););for(e.e=n-r-1,e.c=[],n=0;r<=i;)e.c[n++]=+t.charAt(r++)}return e}(r,n),r.constructor=t}return t.prototype=d,t.DP=20,t.RM=1,t.NE=-7,t.PE=21,t.version="5.2.2",t}()).default=o.Big=o,void 0!==(r=(function(){return o}).call(t,n,t,e))&&(e.exports=r)}(0)},40475:function(e,t,n){"use strict";var r=n(48764).Buffer;t.oU=function(e){{let t=r.from(e);t.reverse();let n=t.toString("hex");return 0===n.length?BigInt(0):BigInt(`0x${n}`)}},t.Q5=function(e){{let t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}},t.k$=function(e,t){{let n=e.toString(16),i=r.from(n.padStart(2*t,"0").slice(0,2*t),"hex");return i.reverse(),i}},t.zP=function(e,t){{let n=e.toString(16);return r.from(n.padStart(2*t,"0").slice(0,2*t),"hex")}}},13550:function(e,t,n){!function(e,t){"use strict";function r(e,t){if(!e)throw Error(t||"Assertion failed")}function i(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}function o(e,t,n){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&(("le"===t||"be"===t)&&(n=t,t=10),this._init(e||0,t||10,n||"be"))}"object"==typeof e?e.exports=o:t.BN=o,o.BN=o,o.wordSize=26;try{d="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:n(46601).Buffer}catch(e){}function a(e,t){var n=e.charCodeAt(t);return n>=48&&n<=57?n-48:n>=65&&n<=70?n-55:n>=97&&n<=102?n-87:void r(!1,"Invalid character in "+e)}function s(e,t,n){var r=a(e,n);return n-1>=t&&(r|=a(e,n-1)<<4),r}function u(e,t,n,i){for(var o=0,a=0,s=Math.min(e.length,n),u=t;u