@cobaltx/sdk-v2
Version:
An SDK for building applications on top of CobaltX.
9 lines • 110 kB
JavaScript
import Ae from"bn.js";var Oe=9e15,Ie=1e9,Ut="0123456789abcdef",pt="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",ft="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Gt={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Oe,maxE:Oe,crypto:!1},xn,ye,R=!0,gt="[DecimalError] ",Be=gt+"Invalid argument: ",Sn=gt+"Precision limit exceeded",Cn=gt+"crypto unavailable",Kn="[object Decimal]",te=Math.floor,Q=Math.pow,Di=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Fi=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,vi=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Nn=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,ae=1e7,L=7,Wi=9007199254740991,Vi=pt.length-1,Xt=ft.length-1,w={toStringTag:Kn};w.absoluteValue=w.abs=function(){var t=new this.constructor(this);return t.s<0&&(t.s=1),K(t)};w.ceil=function(){return K(new this.constructor(this),this.e+1,2)};w.clampedTo=w.clamp=function(t,e){var n,i=this,r=i.constructor;if(t=new r(t),e=new r(e),!t.s||!e.s)return new r(NaN);if(t.gt(e))throw Error(Be+e);return n=i.cmp(t),n<0?t:i.cmp(e)>0?e:new r(i)};w.comparedTo=w.cmp=function(t){var e,n,i,r,o=this,s=o.d,a=(t=new o.constructor(t)).d,c=o.s,u=t.s;if(!s||!a)return!c||!u?NaN:c!==u?c:s===a?0:!s^c<0?1:-1;if(!s[0]||!a[0])return s[0]?c:a[0]?-u:0;if(c!==u)return c;if(o.e!==t.e)return o.e>t.e^c<0?1:-1;for(i=s.length,r=a.length,e=0,n=i<r?i:r;e<n;++e)if(s[e]!==a[e])return s[e]>a[e]^c<0?1:-1;return i===r?0:i>r^c<0?1:-1};w.cosine=w.cos=function(){var t,e,n=this,i=n.constructor;return n.d?n.d[0]?(t=i.precision,e=i.rounding,i.precision=t+Math.max(n.e,n.sd())+L,i.rounding=1,n=qi(i,En(i,n)),i.precision=t,i.rounding=e,K(ye==2||ye==3?n.neg():n,t,e,!0)):new i(1):new i(NaN)};w.cubeRoot=w.cbrt=function(){var t,e,n,i,r,o,s,a,c,u,l=this,m=l.constructor;if(!l.isFinite()||l.isZero())return new m(l);for(R=!1,o=l.s*Q(l.s*l,1/3),!o||Math.abs(o)==1/0?(n=ee(l.d),t=l.e,(o=(t-n.length+1)%3)&&(n+=o==1||o==-2?"0":"00"),o=Q(n,1/3),t=te((t+1)/3)-(t%3==(t<0?-1:2)),o==1/0?n="5e"+t:(n=o.toExponential(),n=n.slice(0,n.indexOf("e")+1)+t),i=new m(n),i.s=l.s):i=new m(o.toString()),s=(t=m.precision)+3;;)if(a=i,c=a.times(a).times(a),u=c.plus(l),i=G(u.plus(l).times(a),u.plus(c),s+2,1),ee(a.d).slice(0,s)===(n=ee(i.d)).slice(0,s))if(n=n.slice(s-3,s+1),n=="9999"||!r&&n=="4999"){if(!r&&(K(a,t+1,0),a.times(a).times(a).eq(l))){i=a;break}s+=4,r=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(K(i,t+1,1),e=!i.times(i).times(i).eq(l));break}return R=!0,K(i,t,m.rounding,e)};w.decimalPlaces=w.dp=function(){var t,e=this.d,n=NaN;if(e){if(t=e.length-1,n=(t-te(this.e/L))*L,t=e[t],t)for(;t%10==0;t/=10)n--;n<0&&(n=0)}return n};w.dividedBy=w.div=function(t){return G(this,new this.constructor(t))};w.dividedToIntegerBy=w.divToInt=function(t){var e=this,n=e.constructor;return K(G(e,new n(t),0,1,1),n.precision,n.rounding)};w.equals=w.eq=function(t){return this.cmp(t)===0};w.floor=function(){return K(new this.constructor(this),this.e+1,3)};w.greaterThan=w.gt=function(t){return this.cmp(t)>0};w.greaterThanOrEqualTo=w.gte=function(t){var e=this.cmp(t);return e==1||e===0};w.hyperbolicCosine=w.cosh=function(){var t,e,n,i,r,o=this,s=o.constructor,a=new s(1);if(!o.isFinite())return new s(o.s?1/0:NaN);if(o.isZero())return a;n=s.precision,i=s.rounding,s.precision=n+Math.max(o.e,o.sd())+4,s.rounding=1,r=o.d.length,r<32?(t=Math.ceil(r/3),e=(1/wt(4,t)).toString()):(t=16,e="2.3283064365386962890625e-10"),o=Ee(s,1,o.times(e),new s(1),!0);for(var c,u=t,l=new s(8);u--;)c=o.times(o),o=a.minus(c.times(l.minus(c.times(l))));return K(o,s.precision=n,s.rounding=i,!0)};w.hyperbolicSine=w.sinh=function(){var t,e,n,i,r=this,o=r.constructor;if(!r.isFinite()||r.isZero())return new o(r);if(e=o.precision,n=o.rounding,o.precision=e+Math.max(r.e,r.sd())+4,o.rounding=1,i=r.d.length,i<3)r=Ee(o,2,r,r,!0);else{t=1.4*Math.sqrt(i),t=t>16?16:t|0,r=r.times(1/wt(5,t)),r=Ee(o,2,r,r,!0);for(var s,a=new o(5),c=new o(16),u=new o(20);t--;)s=r.times(r),r=r.times(a.plus(s.times(c.times(s).plus(u))))}return o.precision=e,o.rounding=n,K(r,e,n,!0)};w.hyperbolicTangent=w.tanh=function(){var t,e,n=this,i=n.constructor;return n.isFinite()?n.isZero()?new i(n):(t=i.precision,e=i.rounding,i.precision=t+7,i.rounding=1,G(n.sinh(),n.cosh(),i.precision=t,i.rounding=e)):new i(n.s)};w.inverseCosine=w.acos=function(){var t=this,e=t.constructor,n=t.abs().cmp(1),i=e.precision,r=e.rounding;return n!==-1?n===0?t.isNeg()?de(e,i,r):new e(0):new e(NaN):t.isZero()?de(e,i+4,r).times(.5):(e.precision=i+6,e.rounding=1,t=new e(1).minus(t).div(t.plus(1)).sqrt().atan(),e.precision=i,e.rounding=r,t.times(2))};w.inverseHyperbolicCosine=w.acosh=function(){var t,e,n=this,i=n.constructor;return n.lte(1)?new i(n.eq(1)?0:NaN):n.isFinite()?(t=i.precision,e=i.rounding,i.precision=t+Math.max(Math.abs(n.e),n.sd())+4,i.rounding=1,R=!1,n=n.times(n).minus(1).sqrt().plus(n),R=!0,i.precision=t,i.rounding=e,n.ln()):new i(n)};w.inverseHyperbolicSine=w.asinh=function(){var t,e,n=this,i=n.constructor;return!n.isFinite()||n.isZero()?new i(n):(t=i.precision,e=i.rounding,i.precision=t+2*Math.max(Math.abs(n.e),n.sd())+6,i.rounding=1,R=!1,n=n.times(n).plus(1).sqrt().plus(n),R=!0,i.precision=t,i.rounding=e,n.ln())};w.inverseHyperbolicTangent=w.atanh=function(){var t,e,n,i,r=this,o=r.constructor;return r.isFinite()?r.e>=0?new o(r.abs().eq(1)?r.s/0:r.isZero()?r:NaN):(t=o.precision,e=o.rounding,i=r.sd(),Math.max(i,t)<2*-r.e-1?K(new o(r),t,e,!0):(o.precision=n=i-r.e,r=G(r.plus(1),new o(1).minus(r),n+t,1),o.precision=t+4,o.rounding=1,r=r.ln(),o.precision=t,o.rounding=e,r.times(.5))):new o(NaN)};w.inverseSine=w.asin=function(){var t,e,n,i,r=this,o=r.constructor;return r.isZero()?new o(r):(e=r.abs().cmp(1),n=o.precision,i=o.rounding,e!==-1?e===0?(t=de(o,n+4,i).times(.5),t.s=r.s,t):new o(NaN):(o.precision=n+6,o.rounding=1,r=r.div(new o(1).minus(r.times(r)).sqrt().plus(1)).atan(),o.precision=n,o.rounding=i,r.times(2)))};w.inverseTangent=w.atan=function(){var t,e,n,i,r,o,s,a,c,u=this,l=u.constructor,m=l.precision,d=l.rounding;if(u.isFinite()){if(u.isZero())return new l(u);if(u.abs().eq(1)&&m+4<=Xt)return s=de(l,m+4,d).times(.25),s.s=u.s,s}else{if(!u.s)return new l(NaN);if(m+4<=Xt)return s=de(l,m+4,d).times(.5),s.s=u.s,s}for(l.precision=a=m+10,l.rounding=1,n=Math.min(28,a/L+2|0),t=n;t;--t)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(R=!1,e=Math.ceil(a/L),i=1,c=u.times(u),s=new l(u),r=u;t!==-1;)if(r=r.times(c),o=s.minus(r.div(i+=2)),r=r.times(c),s=o.plus(r.div(i+=2)),s.d[e]!==void 0)for(t=e;s.d[t]===o.d[t]&&t--;);return n&&(s=s.times(2<<n-1)),R=!0,K(s,l.precision=m,l.rounding=d,!0)};w.isFinite=function(){return!!this.d};w.isInteger=w.isInt=function(){return!!this.d&&te(this.e/L)>this.d.length-2};w.isNaN=function(){return!this.s};w.isNegative=w.isNeg=function(){return this.s<0};w.isPositive=w.isPos=function(){return this.s>0};w.isZero=function(){return!!this.d&&this.d[0]===0};w.lessThan=w.lt=function(t){return this.cmp(t)<0};w.lessThanOrEqualTo=w.lte=function(t){return this.cmp(t)<1};w.logarithm=w.log=function(t){var e,n,i,r,o,s,a,c,u=this,l=u.constructor,m=l.precision,d=l.rounding,p=5;if(t==null)t=new l(10),e=!0;else{if(t=new l(t),n=t.d,t.s<0||!n||!n[0]||t.eq(1))return new l(NaN);e=t.eq(10)}if(n=u.d,u.s<0||!n||!n[0]||u.eq(1))return new l(n&&!n[0]?-1/0:u.s!=1?NaN:n?0:1/0);if(e)if(n.length>1)o=!0;else{for(r=n[0];r%10===0;)r/=10;o=r!==1}if(R=!1,a=m+p,s=he(u,a),i=e?bt(l,a+10):he(t,a),c=G(s,i,a,1),Xe(c.d,r=m,d))do if(a+=10,s=he(u,a),i=e?bt(l,a+10):he(t,a),c=G(s,i,a,1),!o){+ee(c.d).slice(r+1,r+15)+1==1e14&&(c=K(c,m+1,0));break}while(Xe(c.d,r+=10,d));return R=!0,K(c,m,d)};w.minus=w.sub=function(t){var e,n,i,r,o,s,a,c,u,l,m,d,p=this,b=p.constructor;if(t=new b(t),!p.d||!t.d)return!p.s||!t.s?t=new b(NaN):p.d?t.s=-t.s:t=new b(t.d||p.s!==t.s?p:NaN),t;if(p.s!=t.s)return t.s=-t.s,p.plus(t);if(u=p.d,d=t.d,a=b.precision,c=b.rounding,!u[0]||!d[0]){if(d[0])t.s=-t.s;else if(u[0])t=new b(p);else return new b(c===3?-0:0);return R?K(t,a,c):t}if(n=te(t.e/L),l=te(p.e/L),u=u.slice(),o=l-n,o){for(m=o<0,m?(e=u,o=-o,s=d.length):(e=d,n=l,s=u.length),i=Math.max(Math.ceil(a/L),s)+2,o>i&&(o=i,e.length=1),e.reverse(),i=o;i--;)e.push(0);e.reverse()}else{for(i=u.length,s=d.length,m=i<s,m&&(s=i),i=0;i<s;i++)if(u[i]!=d[i]){m=u[i]<d[i];break}o=0}for(m&&(e=u,u=d,d=e,t.s=-t.s),s=u.length,i=d.length-s;i>0;--i)u[s++]=0;for(i=d.length;i>o;){if(u[--i]<d[i]){for(r=i;r&&u[--r]===0;)u[r]=ae-1;--u[r],u[i]+=ae}u[i]-=d[i]}for(;u[--s]===0;)u.pop();for(;u[0]===0;u.shift())--n;return u[0]?(t.d=u,t.e=yt(u,n),R?K(t,a,c):t):new b(c===3?-0:0)};w.modulo=w.mod=function(t){var e,n=this,i=n.constructor;return t=new i(t),!n.d||!t.s||t.d&&!t.d[0]?new i(NaN):!t.d||n.d&&!n.d[0]?K(new i(n),i.precision,i.rounding):(R=!1,i.modulo==9?(e=G(n,t.abs(),0,3,1),e.s*=t.s):e=G(n,t,0,i.modulo,1),e=e.times(t),R=!0,n.minus(e))};w.naturalExponential=w.exp=function(){return Ht(this)};w.naturalLogarithm=w.ln=function(){return he(this)};w.negated=w.neg=function(){var t=new this.constructor(this);return t.s=-t.s,K(t)};w.plus=w.add=function(t){var e,n,i,r,o,s,a,c,u,l,m=this,d=m.constructor;if(t=new d(t),!m.d||!t.d)return!m.s||!t.s?t=new d(NaN):m.d||(t=new d(t.d||m.s===t.s?m:NaN)),t;if(m.s!=t.s)return t.s=-t.s,m.minus(t);if(u=m.d,l=t.d,a=d.precision,c=d.rounding,!u[0]||!l[0])return l[0]||(t=new d(m)),R?K(t,a,c):t;if(o=te(m.e/L),i=te(t.e/L),u=u.slice(),r=o-i,r){for(r<0?(n=u,r=-r,s=l.length):(n=l,i=o,s=u.length),o=Math.ceil(a/L),s=o>s?o+1:s+1,r>s&&(r=s,n.length=1),n.reverse();r--;)n.push(0);n.reverse()}for(s=u.length,r=l.length,s-r<0&&(r=s,n=l,l=u,u=n),e=0;r;)e=(u[--r]=u[r]+l[r]+e)/ae|0,u[r]%=ae;for(e&&(u.unshift(e),++i),s=u.length;u[--s]==0;)u.pop();return t.d=u,t.e=yt(u,i),R?K(t,a,c):t};w.precision=w.sd=function(t){var e,n=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(Be+t);return n.d?(e=Ln(n.d),t&&n.e+1>e&&(e=n.e+1)):e=NaN,e};w.round=function(){var t=this,e=t.constructor;return K(new e(t),t.e+1,e.rounding)};w.sine=w.sin=function(){var t,e,n=this,i=n.constructor;return n.isFinite()?n.isZero()?new i(n):(t=i.precision,e=i.rounding,i.precision=t+Math.max(n.e,n.sd())+L,i.rounding=1,n=Gi(i,En(i,n)),i.precision=t,i.rounding=e,K(ye>2?n.neg():n,t,e,!0)):new i(NaN)};w.squareRoot=w.sqrt=function(){var t,e,n,i,r,o,s=this,a=s.d,c=s.e,u=s.s,l=s.constructor;if(u!==1||!a||!a[0])return new l(!u||u<0&&(!a||a[0])?NaN:a?s:1/0);for(R=!1,u=Math.sqrt(+s),u==0||u==1/0?(e=ee(a),(e.length+c)%2==0&&(e+="0"),u=Math.sqrt(e),c=te((c+1)/2)-(c<0||c%2),u==1/0?e="5e"+c:(e=u.toExponential(),e=e.slice(0,e.indexOf("e")+1)+c),i=new l(e)):i=new l(u.toString()),n=(c=l.precision)+3;;)if(o=i,i=o.plus(G(s,o,n+2,1)).times(.5),ee(o.d).slice(0,n)===(e=ee(i.d)).slice(0,n))if(e=e.slice(n-3,n+1),e=="9999"||!r&&e=="4999"){if(!r&&(K(o,c+1,0),o.times(o).eq(s))){i=o;break}n+=4,r=1}else{(!+e||!+e.slice(1)&&e.charAt(0)=="5")&&(K(i,c+1,1),t=!i.times(i).eq(s));break}return R=!0,K(i,c,l.rounding,t)};w.tangent=w.tan=function(){var t,e,n=this,i=n.constructor;return n.isFinite()?n.isZero()?new i(n):(t=i.precision,e=i.rounding,i.precision=t+10,i.rounding=1,n=n.sin(),n.s=1,n=G(n,new i(1).minus(n.times(n)).sqrt(),t+10,0),i.precision=t,i.rounding=e,K(ye==2||ye==4?n.neg():n,t,e,!0)):new i(NaN)};w.times=w.mul=function(t){var e,n,i,r,o,s,a,c,u,l=this,m=l.constructor,d=l.d,p=(t=new m(t)).d;if(t.s*=l.s,!d||!d[0]||!p||!p[0])return new m(!t.s||d&&!d[0]&&!p||p&&!p[0]&&!d?NaN:!d||!p?t.s/0:t.s*0);for(n=te(l.e/L)+te(t.e/L),c=d.length,u=p.length,c<u&&(o=d,d=p,p=o,s=c,c=u,u=s),o=[],s=c+u,i=s;i--;)o.push(0);for(i=u;--i>=0;){for(e=0,r=c+i;r>i;)a=o[r]+p[i]*d[r-i-1]+e,o[r--]=a%ae|0,e=a/ae|0;o[r]=(o[r]+e)%ae|0}for(;!o[--s];)o.pop();return e?++n:o.shift(),t.d=o,t.e=yt(o,n),R?K(t,m.precision,m.rounding):t};w.toBinary=function(t,e){return zt(this,2,t,e)};w.toDecimalPlaces=w.toDP=function(t,e){var n=this,i=n.constructor;return n=new i(n),t===void 0?n:(ie(t,0,Ie),e===void 0?e=i.rounding:ie(e,0,8),K(n,t+n.e+1,e))};w.toExponential=function(t,e){var n,i=this,r=i.constructor;return t===void 0?n=pe(i,!0):(ie(t,0,Ie),e===void 0?e=r.rounding:ie(e,0,8),i=K(new r(i),t+1,e),n=pe(i,!0,t+1)),i.isNeg()&&!i.isZero()?"-"+n:n};w.toFixed=function(t,e){var n,i,r=this,o=r.constructor;return t===void 0?n=pe(r):(ie(t,0,Ie),e===void 0?e=o.rounding:ie(e,0,8),i=K(new o(r),t+r.e+1,e),n=pe(i,!1,t+i.e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};w.toFraction=function(t){var e,n,i,r,o,s,a,c,u,l,m,d,p=this,b=p.d,f=p.constructor;if(!b)return new f(p);if(u=n=new f(1),i=c=new f(0),e=new f(i),o=e.e=Ln(b)-p.e-1,s=o%L,e.d[0]=Q(10,s<0?L+s:s),t==null)t=o>0?e:u;else{if(a=new f(t),!a.isInt()||a.lt(u))throw Error(Be+a);t=a.gt(e)?o>0?e:u:a}for(R=!1,a=new f(ee(b)),l=f.precision,f.precision=o=b.length*L*2;m=G(a,e,0,1,1),r=n.plus(m.times(i)),r.cmp(t)!=1;)n=i,i=r,r=u,u=c.plus(m.times(r)),c=r,r=e,e=a.minus(m.times(r)),a=r;return r=G(t.minus(n),i,0,1,1),c=c.plus(r.times(u)),n=n.plus(r.times(i)),c.s=u.s=p.s,d=G(u,i,o,1).minus(p).abs().cmp(G(c,n,o,1).minus(p).abs())<1?[u,i]:[c,n],f.precision=l,R=!0,d};w.toHexadecimal=w.toHex=function(t,e){return zt(this,16,t,e)};w.toNearest=function(t,e){var n=this,i=n.constructor;if(n=new i(n),t==null){if(!n.d)return n;t=new i(1),e=i.rounding}else{if(t=new i(t),e===void 0?e=i.rounding:ie(e,0,8),!n.d)return t.s?n:t;if(!t.d)return t.s&&(t.s=n.s),t}return t.d[0]?(R=!1,n=G(n,t,0,e,1).times(t),R=!0,K(n)):(t.s=n.s,n=t),n};w.toNumber=function(){return+this};w.toOctal=function(t,e){return zt(this,8,t,e)};w.toPower=w.pow=function(t){var e,n,i,r,o,s,a=this,c=a.constructor,u=+(t=new c(t));if(!a.d||!t.d||!a.d[0]||!t.d[0])return new c(Q(+a,u));if(a=new c(a),a.eq(1))return a;if(i=c.precision,o=c.rounding,t.eq(1))return K(a,i,o);if(e=te(t.e/L),e>=t.d.length-1&&(n=u<0?-u:u)<=Wi)return r=Rn(c,a,n,i),t.s<0?new c(1).div(r):K(r,i,o);if(s=a.s,s<0){if(e<t.d.length-1)return new c(NaN);if((t.d[e]&1)==0&&(s=1),a.e==0&&a.d[0]==1&&a.d.length==1)return a.s=s,a}return n=Q(+a,u),e=n==0||!isFinite(n)?te(u*(Math.log("0."+ee(a.d))/Math.LN10+a.e+1)):new c(n+"").e,e>c.maxE+1||e<c.minE-1?new c(e>0?s/0:0):(R=!1,c.rounding=a.s=1,n=Math.min(12,(e+"").length),r=Ht(t.times(he(a,i+n)),i),r.d&&(r=K(r,i+5,1),Xe(r.d,i,o)&&(e=i+10,r=K(Ht(t.times(he(a,e+n)),e),e+5,1),+ee(r.d).slice(i+1,i+15)+1==1e14&&(r=K(r,i+1,0)))),r.s=s,R=!0,c.rounding=o,K(r,i,o))};w.toPrecision=function(t,e){var n,i=this,r=i.constructor;return t===void 0?n=pe(i,i.e<=r.toExpNeg||i.e>=r.toExpPos):(ie(t,1,Ie),e===void 0?e=r.rounding:ie(e,0,8),i=K(new r(i),t,e),n=pe(i,t<=i.e||i.e<=r.toExpNeg,t)),i.isNeg()&&!i.isZero()?"-"+n:n};w.toSignificantDigits=w.toSD=function(t,e){var n=this,i=n.constructor;return t===void 0?(t=i.precision,e=i.rounding):(ie(t,1,Ie),e===void 0?e=i.rounding:ie(e,0,8)),K(new i(n),t,e)};w.toString=function(){var t=this,e=t.constructor,n=pe(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()&&!t.isZero()?"-"+n:n};w.truncated=w.trunc=function(){return K(new this.constructor(this),this.e+1,1)};w.valueOf=w.toJSON=function(){var t=this,e=t.constructor,n=pe(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()?"-"+n:n};function ee(t){var e,n,i,r=t.length-1,o="",s=t[0];if(r>0){for(o+=s,e=1;e<r;e++)i=t[e]+"",n=L-i.length,n&&(o+=Te(n)),o+=i;s=t[e],i=s+"",n=L-i.length,n&&(o+=Te(n))}else if(s===0)return"0";for(;s%10===0;)s/=10;return o+s}function ie(t,e,n){if(t!==~~t||t<e||t>n)throw Error(Be+t)}function Xe(t,e,n,i){var r,o,s,a;for(o=t[0];o>=10;o/=10)--e;return--e<0?(e+=L,r=0):(r=Math.ceil((e+1)/L),e%=L),o=Q(10,L-e),a=t[r]%o|0,i==null?e<3?(e==0?a=a/100|0:e==1&&(a=a/10|0),s=n<4&&a==99999||n>3&&a==49999||a==5e4||a==0):s=(n<4&&a+1==o||n>3&&a+1==o/2)&&(t[r+1]/o/100|0)==Q(10,e-2)-1||(a==o/2||a==0)&&(t[r+1]/o/100|0)==0:e<4?(e==0?a=a/1e3|0:e==1?a=a/100|0:e==2&&(a=a/10|0),s=(i||n<4)&&a==9999||!i&&n>3&&a==4999):s=((i||n<4)&&a+1==o||!i&&n>3&&a+1==o/2)&&(t[r+1]/o/1e3|0)==Q(10,e-3)-1,s}function mt(t,e,n){for(var i,r=[0],o,s=0,a=t.length;s<a;){for(o=r.length;o--;)r[o]*=e;for(r[0]+=Ut.indexOf(t.charAt(s++)),i=0;i<r.length;i++)r[i]>n-1&&(r[i+1]===void 0&&(r[i+1]=0),r[i+1]+=r[i]/n|0,r[i]%=n)}return r.reverse()}function qi(t,e){var n,i,r;if(e.isZero())return e;i=e.d.length,i<32?(n=Math.ceil(i/3),r=(1/wt(4,n)).toString()):(n=16,r="2.3283064365386962890625e-10"),t.precision+=n,e=Ee(t,1,e.times(r),new t(1));for(var o=n;o--;){var s=e.times(e);e=s.times(s).minus(s).times(8).plus(1)}return t.precision-=n,e}var G=function(){function t(i,r,o){var s,a=0,c=i.length;for(i=i.slice();c--;)s=i[c]*r+a,i[c]=s%o|0,a=s/o|0;return a&&i.unshift(a),i}function e(i,r,o,s){var a,c;if(o!=s)c=o>s?1:-1;else for(a=c=0;a<o;a++)if(i[a]!=r[a]){c=i[a]>r[a]?1:-1;break}return c}function n(i,r,o,s){for(var a=0;o--;)i[o]-=a,a=i[o]<r[o]?1:0,i[o]=a*s+i[o]-r[o];for(;!i[0]&&i.length>1;)i.shift()}return function(i,r,o,s,a,c){var u,l,m,d,p,b,f,y,g,P,k,A,h,T,C,N,_,q,M,D,v=i.constructor,W=i.s==r.s?1:-1,U=i.d,F=r.d;if(!U||!U[0]||!F||!F[0])return new v(!i.s||!r.s||(U?F&&U[0]==F[0]:!F)?NaN:U&&U[0]==0||!F?W*0:W/0);for(c?(p=1,l=i.e-r.e):(c=ae,p=L,l=te(i.e/p)-te(r.e/p)),M=F.length,_=U.length,g=new v(W),P=g.d=[],m=0;F[m]==(U[m]||0);m++);if(F[m]>(U[m]||0)&&l--,o==null?(T=o=v.precision,s=v.rounding):a?T=o+(i.e-r.e)+1:T=o,T<0)P.push(1),b=!0;else{if(T=T/p+2|0,m=0,M==1){for(d=0,F=F[0],T++;(m<_||d)&&T--;m++)C=d*c+(U[m]||0),P[m]=C/F|0,d=C%F|0;b=d||m<_}else{for(d=c/(F[0]+1)|0,d>1&&(F=t(F,d,c),U=t(U,d,c),M=F.length,_=U.length),N=M,k=U.slice(0,M),A=k.length;A<M;)k[A++]=0;D=F.slice(),D.unshift(0),q=F[0],F[1]>=c/2&&++q;do d=0,u=e(F,k,M,A),u<0?(h=k[0],M!=A&&(h=h*c+(k[1]||0)),d=h/q|0,d>1?(d>=c&&(d=c-1),f=t(F,d,c),y=f.length,A=k.length,u=e(f,k,y,A),u==1&&(d--,n(f,M<y?D:F,y,c))):(d==0&&(u=d=1),f=F.slice()),y=f.length,y<A&&f.unshift(0),n(k,f,A,c),u==-1&&(A=k.length,u=e(F,k,M,A),u<1&&(d++,n(k,M<A?D:F,A,c))),A=k.length):u===0&&(d++,k=[0]),P[m++]=d,u&&k[0]?k[A++]=U[N]||0:(k=[U[N]],A=1);while((N++<_||k[0]!==void 0)&&T--);b=k[0]!==void 0}P[0]||P.shift()}if(p==1)g.e=l,xn=b;else{for(m=1,d=P[0];d>=10;d/=10)m++;g.e=m+l*p-1,K(g,a?o+g.e+1:o,s,b)}return g}}();function K(t,e,n,i){var r,o,s,a,c,u,l,m,d,p=t.constructor;e:if(e!=null){if(m=t.d,!m)return t;for(r=1,a=m[0];a>=10;a/=10)r++;if(o=e-r,o<0)o+=L,s=e,l=m[d=0],c=l/Q(10,r-s-1)%10|0;else if(d=Math.ceil((o+1)/L),a=m.length,d>=a)if(i){for(;a++<=d;)m.push(0);l=c=0,r=1,o%=L,s=o-L+1}else break e;else{for(l=a=m[d],r=1;a>=10;a/=10)r++;o%=L,s=o-L+r,c=s<0?0:l/Q(10,r-s-1)%10|0}if(i=i||e<0||m[d+1]!==void 0||(s<0?l:l%Q(10,r-s-1)),u=n<4?(c||i)&&(n==0||n==(t.s<0?3:2)):c>5||c==5&&(n==4||i||n==6&&(o>0?s>0?l/Q(10,r-s):0:m[d-1])%10&1||n==(t.s<0?8:7)),e<1||!m[0])return m.length=0,u?(e-=t.e+1,m[0]=Q(10,(L-e%L)%L),t.e=-e||0):m[0]=t.e=0,t;if(o==0?(m.length=d,a=1,d--):(m.length=d+1,a=Q(10,L-o),m[d]=s>0?(l/Q(10,r-s)%Q(10,s)|0)*a:0),u)for(;;)if(d==0){for(o=1,s=m[0];s>=10;s/=10)o++;for(s=m[0]+=a,a=1;s>=10;s/=10)a++;o!=a&&(t.e++,m[0]==ae&&(m[0]=1));break}else{if(m[d]+=a,m[d]!=ae)break;m[d--]=0,a=1}for(o=m.length;m[--o]===0;)m.pop()}return R&&(t.e>p.maxE?(t.d=null,t.e=NaN):t.e<p.minE&&(t.e=0,t.d=[0])),t}function pe(t,e,n){if(!t.isFinite())return On(t);var i,r=t.e,o=ee(t.d),s=o.length;return e?(n&&(i=n-s)>0?o=o.charAt(0)+"."+o.slice(1)+Te(i):s>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(t.e<0?"e":"e+")+t.e):r<0?(o="0."+Te(-r-1)+o,n&&(i=n-s)>0&&(o+=Te(i))):r>=s?(o+=Te(r+1-s),n&&(i=n-r-1)>0&&(o=o+"."+Te(i))):((i=r+1)<s&&(o=o.slice(0,i)+"."+o.slice(i)),n&&(i=n-s)>0&&(r+1===s&&(o+="."),o+=Te(i))),o}function yt(t,e){var n=t[0];for(e*=L;n>=10;n/=10)e++;return e}function bt(t,e,n){if(e>Vi)throw R=!0,n&&(t.precision=n),Error(Sn);return K(new t(pt),e,1,!0)}function de(t,e,n){if(e>Xt)throw Error(Sn);return K(new t(ft),e,n,!0)}function Ln(t){var e=t.length-1,n=e*L+1;if(e=t[e],e){for(;e%10==0;e/=10)n--;for(e=t[0];e>=10;e/=10)n++}return n}function Te(t){for(var e="";t--;)e+="0";return e}function Rn(t,e,n,i){var r,o=new t(1),s=Math.ceil(i/L+4);for(R=!1;;){if(n%2&&(o=o.times(e),Bn(o.d,s)&&(r=!0)),n=te(n/2),n===0){n=o.d.length-1,r&&o.d[n]===0&&++o.d[n];break}e=e.times(e),Bn(e.d,s)}return R=!0,o}function hn(t){return t.d[t.d.length-1]&1}function Mn(t,e,n){for(var i,r,o=new t(e[0]),s=0;++s<e.length;){if(r=new t(e[s]),!r.s){o=r;break}i=o.cmp(r),(i===n||i===0&&o.s===n)&&(o=r)}return o}function Ht(t,e){var n,i,r,o,s,a,c,u=0,l=0,m=0,d=t.constructor,p=d.rounding,b=d.precision;if(!t.d||!t.d[0]||t.e>17)return new d(t.d?t.d[0]?t.s<0?0:1/0:1:t.s?t.s<0?0:t:0/0);for(e==null?(R=!1,c=b):c=e,a=new d(.03125);t.e>-2;)t=t.times(a),m+=5;for(i=Math.log(Q(2,m))/Math.LN10*2+5|0,c+=i,n=o=s=new d(1),d.precision=c;;){if(o=K(o.times(t),c,1),n=n.times(++l),a=s.plus(G(o,n,c,1)),ee(a.d).slice(0,c)===ee(s.d).slice(0,c)){for(r=m;r--;)s=K(s.times(s),c,1);if(e==null)if(u<3&&Xe(s.d,c-i,p,u))d.precision=c+=10,n=o=a=new d(1),l=0,u++;else return K(s,d.precision=b,p,R=!0);else return d.precision=b,s}s=a}}function he(t,e){var n,i,r,o,s,a,c,u,l,m,d,p=1,b=10,f=t,y=f.d,g=f.constructor,P=g.rounding,k=g.precision;if(f.s<0||!y||!y[0]||!f.e&&y[0]==1&&y.length==1)return new g(y&&!y[0]?-1/0:f.s!=1?NaN:y?0:f);if(e==null?(R=!1,l=k):l=e,g.precision=l+=b,n=ee(y),i=n.charAt(0),Math.abs(o=f.e)<15e14){for(;i<7&&i!=1||i==1&&n.charAt(1)>3;)f=f.times(t),n=ee(f.d),i=n.charAt(0),p++;o=f.e,i>1?(f=new g("0."+n),o++):f=new g(i+"."+n.slice(1))}else return u=bt(g,l+2,k).times(o+""),f=he(new g(i+"."+n.slice(1)),l-b).plus(u),g.precision=k,e==null?K(f,k,P,R=!0):f;for(m=f,c=s=f=G(f.minus(1),f.plus(1),l,1),d=K(f.times(f),l,1),r=3;;){if(s=K(s.times(d),l,1),u=c.plus(G(s,new g(r),l,1)),ee(u.d).slice(0,l)===ee(c.d).slice(0,l))if(c=c.times(2),o!==0&&(c=c.plus(bt(g,l+2,k).times(o+""))),c=G(c,new g(p),l,1),e==null)if(Xe(c.d,l-b,P,a))g.precision=l+=b,u=s=f=G(m.minus(1),m.plus(1),l,1),d=K(f.times(f),l,1),r=a=1;else return K(c,g.precision=k,P,R=!0);else return g.precision=k,c;c=u,r+=2}}function On(t){return String(t.s*t.s/0)}function dt(t,e){var n,i,r;for((n=e.indexOf("."))>-1&&(e=e.replace(".","")),(i=e.search(/e/i))>0?(n<0&&(n=i),n+=+e.slice(i+1),e=e.substring(0,i)):n<0&&(n=e.length),i=0;e.charCodeAt(i)===48;i++);for(r=e.length;e.charCodeAt(r-1)===48;--r);if(e=e.slice(i,r),e){if(r-=i,t.e=n=n-i-1,t.d=[],i=(n+1)%L,n<0&&(i+=L),i<r){for(i&&t.d.push(+e.slice(0,i)),r-=L;i<r;)t.d.push(+e.slice(i,i+=L));e=e.slice(i),i=L-e.length}else i-=r;for(;i--;)e+="0";t.d.push(+e),R&&(t.e>t.constructor.maxE?(t.d=null,t.e=NaN):t.e<t.constructor.minE&&(t.e=0,t.d=[0]))}else t.e=0,t.d=[0];return t}function Ui(t,e){var n,i,r,o,s,a,c,u,l;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),Nn.test(e))return dt(t,e)}else if(e==="Infinity"||e==="NaN")return+e||(t.s=NaN),t.e=NaN,t.d=null,t;if(Fi.test(e))n=16,e=e.toLowerCase();else if(Di.test(e))n=2;else if(vi.test(e))n=8;else throw Error(Be+e);for(o=e.search(/p/i),o>0?(c=+e.slice(o+1),e=e.substring(2,o)):e=e.slice(2),o=e.indexOf("."),s=o>=0,i=t.constructor,s&&(e=e.replace(".",""),a=e.length,o=a-o,r=Rn(i,new i(n),o,o*2)),u=mt(e,n,ae),l=u.length-1,o=l;u[o]===0;--o)u.pop();return o<0?new i(t.s*0):(t.e=yt(u,l),t.d=u,R=!1,s&&(t=G(t,r,a*4)),c&&(t=t.times(Math.abs(c)<54?Q(2,c):He.pow(2,c))),R=!0,t)}function Gi(t,e){var n,i=e.d.length;if(i<3)return e.isZero()?e:Ee(t,2,e,e);n=1.4*Math.sqrt(i),n=n>16?16:n|0,e=e.times(1/wt(5,n)),e=Ee(t,2,e,e);for(var r,o=new t(5),s=new t(16),a=new t(20);n--;)r=e.times(e),e=e.times(o.plus(r.times(s.times(r).minus(a))));return e}function Ee(t,e,n,i,r){var o,s,a,c,u=1,l=t.precision,m=Math.ceil(l/L);for(R=!1,c=n.times(n),a=new t(i);;){if(s=G(a.times(c),new t(e++*e++),l,1),a=r?i.plus(s):i.minus(s),i=G(s.times(c),new t(e++*e++),l,1),s=a.plus(i),s.d[m]!==void 0){for(o=m;s.d[o]===a.d[o]&&o--;);if(o==-1)break}o=a,a=i,i=s,s=o,u++}return R=!0,s.d.length=m+1,s}function wt(t,e){for(var n=t;--e;)n*=t;return n}function En(t,e){var n,i=e.s<0,r=de(t,t.precision,1),o=r.times(.5);if(e=e.abs(),e.lte(o))return ye=i?4:1,e;if(n=e.divToInt(r),n.isZero())ye=i?3:2;else{if(e=e.minus(n.times(r)),e.lte(o))return ye=hn(n)?i?2:3:i?4:1,e;ye=hn(n)?i?1:4:i?3:2}return e.minus(r).abs()}function zt(t,e,n,i){var r,o,s,a,c,u,l,m,d,p=t.constructor,b=n!==void 0;if(b?(ie(n,1,Ie),i===void 0?i=p.rounding:ie(i,0,8)):(n=p.precision,i=p.rounding),!t.isFinite())l=On(t);else{for(l=pe(t),s=l.indexOf("."),b?(r=2,e==16?n=n*4-3:e==8&&(n=n*3-2)):r=e,s>=0&&(l=l.replace(".",""),d=new p(1),d.e=l.length-s,d.d=mt(pe(d),10,r),d.e=d.d.length),m=mt(l,10,r),o=c=m.length;m[--c]==0;)m.pop();if(!m[0])l=b?"0p+0":"0";else{if(s<0?o--:(t=new p(t),t.d=m,t.e=o,t=G(t,d,n,i,0,r),m=t.d,o=t.e,u=xn),s=m[n],a=r/2,u=u||m[n+1]!==void 0,u=i<4?(s!==void 0||u)&&(i===0||i===(t.s<0?3:2)):s>a||s===a&&(i===4||u||i===6&&m[n-1]&1||i===(t.s<0?8:7)),m.length=n,u)for(;++m[--n]>r-1;)m[n]=0,n||(++o,m.unshift(1));for(c=m.length;!m[c-1];--c);for(s=0,l="";s<c;s++)l+=Ut.charAt(m[s]);if(b){if(c>1)if(e==16||e==8){for(s=e==16?4:3,--c;c%s;c++)l+="0";for(m=mt(l,r,e),c=m.length;!m[c-1];--c);for(s=1,l="1.";s<c;s++)l+=Ut.charAt(m[s])}else l=l.charAt(0)+"."+l.slice(1);l=l+(o<0?"p":"p+")+o}else if(o<0){for(;++o;)l="0"+l;l="0."+l}else if(++o>c)for(o-=c;o--;)l+="0";else o<c&&(l=l.slice(0,o)+"."+l.slice(o))}l=(e==16?"0x":e==2?"0b":e==8?"0o":"")+l}return t.s<0?"-"+l:l}function Bn(t,e){if(t.length>e)return t.length=e,!0}function Xi(t){return new this(t).abs()}function Hi(t){return new this(t).acos()}function zi(t){return new this(t).acosh()}function Yi(t,e){return new this(t).plus(e)}function ji(t){return new this(t).asin()}function Zi(t){return new this(t).asinh()}function Qi(t){return new this(t).atan()}function Ji(t){return new this(t).atanh()}function $i(t,e){t=new this(t),e=new this(e);var n,i=this.precision,r=this.rounding,o=i+4;return!t.s||!e.s?n=new this(NaN):!t.d&&!e.d?(n=de(this,o,1).times(e.s>0?.25:.75),n.s=t.s):!e.d||t.isZero()?(n=e.s<0?de(this,i,r):new this(0),n.s=t.s):!t.d||e.isZero()?(n=de(this,o,1).times(.5),n.s=t.s):e.s<0?(this.precision=o,this.rounding=1,n=this.atan(G(t,e,o,1)),e=de(this,o,1),this.precision=i,this.rounding=r,n=t.s<0?n.minus(e):n.plus(e)):n=this.atan(G(t,e,o,1)),n}function er(t){return new this(t).cbrt()}function tr(t){return K(t=new this(t),t.e+1,2)}function nr(t,e,n){return new this(t).clamp(e,n)}function ir(t){if(!t||typeof t!="object")throw Error(gt+"Object expected");var e,n,i,r=t.defaults===!0,o=["precision",1,Ie,"rounding",0,8,"toExpNeg",-Oe,0,"toExpPos",0,Oe,"maxE",0,Oe,"minE",-Oe,0,"modulo",0,9];for(e=0;e<o.length;e+=3)if(n=o[e],r&&(this[n]=Gt[n]),(i=t[n])!==void 0)if(te(i)===i&&i>=o[e+1]&&i<=o[e+2])this[n]=i;else throw Error(Be+n+": "+i);if(n="crypto",r&&(this[n]=Gt[n]),(i=t[n])!==void 0)if(i===!0||i===!1||i===0||i===1)if(i)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[n]=!0;else throw Error(Cn);else this[n]=!1;else throw Error(Be+n+": "+i);return this}function rr(t){return new this(t).cos()}function or(t){return new this(t).cosh()}function _n(t){var e,n,i;function r(o){var s,a,c,u=this;if(!(u instanceof r))return new r(o);if(u.constructor=r,In(o)){u.s=o.s,R?!o.d||o.e>r.maxE?(u.e=NaN,u.d=null):o.e<r.minE?(u.e=0,u.d=[0]):(u.e=o.e,u.d=o.d.slice()):(u.e=o.e,u.d=o.d?o.d.slice():o.d);return}if(c=typeof o,c==="number"){if(o===0){u.s=1/o<0?-1:1,u.e=0,u.d=[0];return}if(o<0?(o=-o,u.s=-1):u.s=1,o===~~o&&o<1e7){for(s=0,a=o;a>=10;a/=10)s++;R?s>r.maxE?(u.e=NaN,u.d=null):s<r.minE?(u.e=0,u.d=[0]):(u.e=s,u.d=[o]):(u.e=s,u.d=[o]);return}if(o*0!==0){o||(u.s=NaN),u.e=NaN,u.d=null;return}return dt(u,o.toString())}if(c==="string")return(a=o.charCodeAt(0))===45?(o=o.slice(1),u.s=-1):(a===43&&(o=o.slice(1)),u.s=1),Nn.test(o)?dt(u,o):Ui(u,o);if(c==="bigint")return o<0?(o=-o,u.s=-1):u.s=1,dt(u,o.toString());throw Error(Be+o)}if(r.prototype=w,r.ROUND_UP=0,r.ROUND_DOWN=1,r.ROUND_CEIL=2,r.ROUND_FLOOR=3,r.ROUND_HALF_UP=4,r.ROUND_HALF_DOWN=5,r.ROUND_HALF_EVEN=6,r.ROUND_HALF_CEIL=7,r.ROUND_HALF_FLOOR=8,r.EUCLID=9,r.config=r.set=ir,r.clone=_n,r.isDecimal=In,r.abs=Xi,r.acos=Hi,r.acosh=zi,r.add=Yi,r.asin=ji,r.asinh=Zi,r.atan=Qi,r.atanh=Ji,r.atan2=$i,r.cbrt=er,r.ceil=tr,r.clamp=nr,r.cos=rr,r.cosh=or,r.div=sr,r.exp=ar,r.floor=ur,r.hypot=cr,r.ln=lr,r.log=mr,r.log10=pr,r.log2=dr,r.max=fr,r.min=br,r.mod=gr,r.mul=yr,r.pow=wr,r.random=Ar,r.round=Pr,r.sign=kr,r.sin=Tr,r.sinh=hr,r.sqrt=Br,r.sub=Ir,r.sum=xr,r.tan=Sr,r.tanh=Cr,r.trunc=Kr,t===void 0&&(t={}),t&&t.defaults!==!0)for(i=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<i.length;)t.hasOwnProperty(n=i[e++])||(t[n]=this[n]);return r.config(t),r}function sr(t,e){return new this(t).div(e)}function ar(t){return new this(t).exp()}function ur(t){return K(t=new this(t),t.e+1,3)}function cr(){var t,e,n=new this(0);for(R=!1,t=0;t<arguments.length;)if(e=new this(arguments[t++]),e.d)n.d&&(n=n.plus(e.times(e)));else{if(e.s)return R=!0,new this(1/0);n=e}return R=!0,n.sqrt()}function In(t){return t instanceof He||t&&t.toStringTag===Kn||!1}function lr(t){return new this(t).ln()}function mr(t,e){return new this(t).log(e)}function dr(t){return new this(t).log(2)}function pr(t){return new this(t).log(10)}function fr(){return Mn(this,arguments,-1)}function br(){return Mn(this,arguments,1)}function gr(t,e){return new this(t).mod(e)}function yr(t,e){return new this(t).mul(e)}function wr(t,e){return new this(t).pow(e)}function Ar(t){var e,n,i,r,o=0,s=new this(1),a=[];if(t===void 0?t=this.precision:ie(t,1,Ie),i=Math.ceil(t/L),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(i));o<i;)r=e[o],r>=429e7?e[o]=crypto.getRandomValues(new Uint32Array(1))[0]:a[o++]=r%1e7;else if(crypto.randomBytes){for(e=crypto.randomBytes(i*=4);o<i;)r=e[o]+(e[o+1]<<8)+(e[o+2]<<16)+((e[o+3]&127)<<24),r>=214e7?crypto.randomBytes(4).copy(e,o):(a.push(r%1e7),o+=4);o=i/4}else throw Error(Cn);else for(;o<i;)a[o++]=Math.random()*1e7|0;for(i=a[--o],t%=L,i&&t&&(r=Q(10,L-t),a[o]=(i/r|0)*r);a[o]===0;o--)a.pop();if(o<0)n=0,a=[0];else{for(n=-1;a[0]===0;n-=L)a.shift();for(i=1,r=a[0];r>=10;r/=10)i++;i<L&&(n-=L-i)}return s.e=n,s.d=a,s}function Pr(t){return K(t=new this(t),t.e+1,this.rounding)}function kr(t){return t=new this(t),t.d?t.d[0]?t.s:0*t.s:t.s||NaN}function Tr(t){return new this(t).sin()}function hr(t){return new this(t).sinh()}function Br(t){return new this(t).sqrt()}function Ir(t,e){return new this(t).sub(e)}function xr(){var t=0,e=arguments,n=new this(e[t]);for(R=!1;n.s&&++t<e.length;)n=n.plus(e[t]);return R=!0,K(n,this.precision,this.rounding)}function Sr(t){return new this(t).tan()}function Cr(t){return new this(t).tanh()}function Kr(t){return K(t=new this(t),t.e+1,1)}w[Symbol.for("nodejs.util.inspect.custom")]=w.toString;w[Symbol.toStringTag]="Decimal";var He=w.constructor=_n(Gt);pt=new He(pt);ft=new He(ft);var J=He;import po from"big.js";import Ju from"bn.js";import{get as Dn,set as Nr}from"lodash";var Yt=class{constructor(e){this.logLevel=e.logLevel!==void 0?e.logLevel:0,this.name=e.name}set level(e){this.logLevel=e}get time(){return Date.now().toString()}get moduleName(){return this.name}isLogLevel(e){return e<=this.logLevel}error(...e){return this.isLogLevel(0)?(console.error(this.time,this.name,"sdk logger error",...e),this):this}logWithError(...e){let n=e.map(i=>typeof i=="object"?JSON.stringify(i):i).join(", ");throw new Error(n)}warning(...e){return this.isLogLevel(1)?(console.warn(this.time,this.name,"sdk logger warning",...e),this):this}info(...e){return this.isLogLevel(2)?(console.info(this.time,this.name,"sdk logger info",...e),this):this}debug(...e){return this.isLogLevel(3)?(console.debug(this.time,this.name,"sdk logger debug",...e),this):this}},Fn={},Lr={};function $(t){let e=Dn(Fn,t);if(!e){let n=Dn(Lr,t);e=new Yt({name:t,logLevel:n}),Nr(Fn,t,e)}return e}import{MINT_SIZE as Rr,TOKEN_PROGRAM_ID as Mr,getTransferFeeConfig as Or,unpackMint as Er}from"@solana/spl-token";import{PublicKey as vn}from"@solana/web3.js";var jt=$("CobaltX_accountInfo_util");async function ze(t,e,n){let{batchRequest:i,commitment:r="confirmed",chunkCount:o=100}={batchRequest:!1,...n},s=Zt(e,o),a=new Array(s.length).fill([]);if(i){let c=s.map(m=>{let d=t._buildArgs([m.map(p=>p.toBase58())],r,"base64");return{methodName:"getMultipleAccounts",args:d}}),u=Zt(c,10);a=(await(await Promise.all(u.map(async m=>await t._rpcBatchRequest(m)))).flat()).map(m=>(m.error&&jt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${m.error.message}`),m.result.value.map(d=>{if(d){let{data:p,executable:b,lamports:f,owner:y,rentEpoch:g}=d;return p.length!==2&&p[1]!=="base64"&&jt.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(p[0],"base64"),executable:b,lamports:f,owner:new vn(y),rentEpoch:g}}return null})))}else try{a=await Promise.all(s.map(c=>t.getMultipleAccountsInfo(c,r)))}catch(c){c instanceof Error&&jt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${c.message}`)}return a.flat()}async function Se(t,e,n){let i=await ze(t,e.map(r=>r.pubkey),n);return e.map((r,o)=>({...r,accountInfo:i[o]}))}async function Qt({connection:t,mints:e,network:n,config:i}){var s,a,c;if(e.length===0)return{};let r=await Se(t,e.map(u=>({pubkey:Ye(u,n)})),i),o={};for(let u of r){if(!u.accountInfo||u.accountInfo.data.length<Rr){console.log("invalid mint account",u.pubkey.toBase58());continue}let l=Er(u.pubkey,u.accountInfo,(s=u.accountInfo)==null?void 0:s.owner);o[u.pubkey.toString()]={...l,programId:((a=u.accountInfo)==null?void 0:a.owner)||Mr,feeConfig:(c=Or(l))!=null?c:void 0}}return o[vn.default.toBase58()]=o[ue(n).WSOLMint.toBase58()],o}import je from"bn.js";var Wn=9007199254740991;function fe(t){let e=$("CobaltX_parseBigNumberish");if(t instanceof je)return t;if(typeof t=="string"){if(t.match(/^-?[0-9]+$/))return new je(t);e.logWithError(`invalid BigNumberish string: ${t}`)}return typeof t=="number"?(t%1&&e.logWithError(`BigNumberish number underflow: ${t}`),(t>=Wn||t<=-Wn)&&e.logWithError(`BigNumberish number overflow: ${t}`),new je(String(t))):typeof t=="bigint"?new je(t.toString()):(e.error(`invalid BigNumberish value: ${t}`),new je(0))}import{TOKEN_PROGRAM_ID as Ps}from"@solana/spl-token";import{PublicKey as Ts}from"@solana/web3.js";import{PublicKey as we}from"@solana/web3.js";var _r={["sooneth"]:{NATIVE_TOKEN_SYMBOL:"ETH",SWAP_HOST:"https://trade-api.cobaltx.io",BASE_HOST:"https://api.cobaltx.io",OWNER_BASE_HOST:"https://api.cobaltx.io",SERVICE_BASE_HOST:"https://api.cobaltx.io",MONITOR_BASE_HOST:"https://api.cobaltx.io",SERVICE_1_BASE_HOST:"https://api.cobaltx.io",ANALYTICS_BASE_HOST:"https://api.cobaltx.io",GITHUB_TOKEN_LIST_URL:"https://raw.githubusercontent.com/cobaltx-io/tokens/main/tokens.json",WSOL_MINT_ADDRESS:"So11111111111111111111111111111111111111112",GITHUB_LOGO_URL:"https://raw.githubusercontent.com/cobaltx-io/tokens/main/logo/So11111111111111111111111111111111111111112.png",LOOKUP_TABLE_CACHE:"6fa5xTGwoYJPMLMXaQ4tQFKMoYvXuvsJFLigMJ9a5QeB",CLMM_PROGRAMM_ID:"2TnjBuwqyBB9to5jURagDT7jLmBPefGRiKL2yh1zPZ4V",BONK_MINT_ADDRESS:"71kRXzJMvSeArtXYNEWa8KAjpRJosdMQ7Dpgy5Jt5zfd",SOL_MINT_ADDRESS:"ERFzpDteGNo8LTDKW1WwVGrkRMmA2y9WZHXNHxMA6BSV",USDC_MINT_ADDRESS:"ExYxyorY2x3h8gLcuypnHFQV3F36rmMkQVn7HHV8mUy9",USDT_MINT_ADDRESS:"742wcXVzkhNuEePAot7L3GvPseh93pvYFPgyHLX8mUy9",FULL_TOKEN_NAME:"Wrapped Ethereum",ETH_MINT_ADDRESS:"71kRXzJMvSeArtXYNEWa8KAjpRJosdMQ7Dpgy5Jt5zfd",WRAPPED_TOKEN_SYMBOL:"WETH",INPUT_MINT_ADDRESS:we.default.toString(),OUTPUT_MINT_ADDRESS:"742wcXVzkhNuEePAot7L3GvPseh93pvYFPgyHLX8mUy9",POPULAR_TOKENS:{SOL:we.default.toString(),ETH:"71kRXzJMvSeArtXYNEWa8KAjpRJosdMQ7Dpgy5Jt5zfd",USDC:"ExYxyorY2x3h8gLcuypnHFQV3F36rmMkQVn7HHV8KjtA",USDT:"742wcXVzkhNuEePAot7L3GvPseh93pvYFPgyHLX8mUy9"},WSOL_DECIMALS:9},["svmbnb"]:{NATIVE_TOKEN_SYMBOL:"BNB",SWAP_HOST:"https://trade-api.svmbnb.cobaltx.io",BASE_HOST:"https://api.svmbnb.cobaltx.io",OWNER_BASE_HOST:"https://api.svmbnb.cobaltx.io",SERVICE_BASE_HOST:"https://api.svmbnb.cobaltx.io",MONITOR_BASE_HOST:"https://api.svmbnb.cobaltx.io",SERVICE_1_BASE_HOST:"https://api.svmbnb.cobaltx.io",ANALYTICS_BASE_HOST:"https://api.svmbnb.cobaltx.io",GITHUB_TOKEN_LIST_URL:"https://raw.githubusercontent.com/cobaltx-io/svmbnb-tokens/main/tokens.json",WSOL_MINT_ADDRESS:"So11111111111111111111111111111111111111112",GITHUB_LOGO_URL:"https://raw.githubusercontent.com/cobaltx-io/svmbnb-tokens/main/logo/So11111111111111111111111111111111111111112.svg",LOOKUP_TABLE_CACHE:"GSR5XQGWhpzV9TTduBJR6qPNjYsepMQSGkpaqfrbrW9w",CLMM_PROGRAMM_ID:"6f1b3xyVZbnWMHXBjgW1KPwxmPAgXcRdrvKNn4Nmf1Cn",ETH_MINT_ADDRESS:"H3xpFH1yN5E1zFdAoBrC9Y7m7RfJUeQNLvkHi8kNf9Qu",USDC_MINT_ADDRESS:"5odzAHDpDETYhupMkc6kjiYen3K2nrf8oPmvqmsoNW4L",USDT_MINT_ADDRESS:"s8cRDxnp3VxjB6khRnGDdxv6QbCUPyY9Vn1bgSQQsnG",SOL_MINT_ADDRESS:"So11111111111111111111111111111111111111112",FULL_TOKEN_NAME:"Wrapped BNB",WRAPPED_TOKEN_SYMBOL:"WBNB",INPUT_MINT_ADDRESS:we.default.toBase58(),OUTPUT_MINT_ADDRESS:"ABoT7umUXnx8RtJTeRqKB6myebVjP2wdJGQuV23jVVH3",POPULAR_TOKENS:{SOL:we.default.toString(),ETH:"H3xpFH1yN5E1zFdAoBrC9Y7m7RfJUeQNLvkHi8kNf9Qu",USDC:"5odzAHDpDETYhupMkc6kjiYen3K2nrf8oPmvqmsoNW4L",USDT:"s8cRDxnp3VxjB6khRnGDdxv6QbCUPyY9Vn1bgSQQsnG"},WSOL_DECIMALS:9},["svmbnb_testnet"]:{NATIVE_TOKEN_SYMBOL:"BNB",SWAP_HOST:"https://trade-api.svmbnb.cobaltx.io",BASE_HOST:"https://api.testnet.svmbnb.cobaltx.io",OWNER_BASE_HOST:"https://api.testnet.svmbnb.cobaltx.io",SERVICE_BASE_HOST:"https://api.testnet.svmbnb.cobaltx.io",MONITOR_BASE_HOST:"https://api.testnet.svmbnb.cobaltx.io",SERVICE_1_BASE_HOST:"https://api.testnet.svmbnb.cobaltx.io",ANALYTICS_BASE_HOST:"https://api.testnet.svmbnb.cobaltx.io",GITHUB_TOKEN_LIST_URL:"https://raw.githubusercontent.com/cobaltx-io/svmbnb-testnet-tokens/main/tokens.json",WSOL_MINT_ADDRESS:"So11111111111111111111111111111111111111112",GITHUB_LOGO_URL:"https://raw.githubusercontent.com/cobaltx-io/svmbnb-testnet-tokens/main/logo/So11111111111111111111111111111111111111112.svg",LOOKUP_TABLE_CACHE:"D79gSiTNV9pyLPJyscW5yZYwdPVDrtKsamL3ZfQi6JiM",CLMM_PROGRAMM_ID:"FgycD57kcCZsjpoTAi2u67GTPxm59bPEhycL2Lw1icm1",ETH_MINT_ADDRESS:"5aLr3sV4UNVcMB6CiA3PZTWbgVBRNyMdEp1s5LNfhR95",USDC_MINT_ADDRESS:"jrhUNRxEDpFmGV3sqaWyveS7bVtRQgtHsfBTCdjfMBw",USDT_MINT_ADDRESS:"Ex86C4gmdjvPRNrfyvsyejbjkP6RstNaBC5g3itZw2iv",FULL_TOKEN_NAME:"Wrapped BNB",WRAPPED_TOKEN_SYMBOL:"WBNB",INPUT_MINT_ADDRESS:"bnb",OUTPUT_MINT_ADDRESS:"jrhUNRxEDpFmGV3sqaWyveS7bVtRQgtHsfBTCdjfMBw",POPULAR_TOKENS:{SOL:we.default.toString(),ETH:"5aLr3sV4UNVcMB6CiA3PZTWbgVBRNyMdEp1s5LNfhR95",USDC:"jrhUNRxEDpFmGV3sqaWyveS7bVtRQgtHsfBTCdjfMBw",USDT:"Ex86C4gmdjvPRNrfyvsyejbjkP6RstNaBC5g3itZw2iv"},WSOL_DECIMALS:9},["svmbase_testnet"]:{NATIVE_TOKEN_SYMBOL:"ETH",SWAP_HOST:"https://trade-api.testnet.svmbase.cobaltx.io",BASE_HOST:"https://api.testnet.svmbase.cobaltx.io",OWNER_BASE_HOST:"https://api.testnet.svmbase.cobaltx.io",SERVICE_BASE_HOST:"https://api.testnet.svmbase.cobaltx.io",MONITOR_BASE_HOST:"https://api.testnet.svmbase.cobaltx.io",SERVICE_1_BASE_HOST:"https://api.testnet.svmbase.cobaltx.io",ANALYTICS_BASE_HOST:"https://api.testnet.svmbase.cobaltx.io",GITHUB_TOKEN_LIST_URL:"https://raw.githubusercontent.com/cobaltx-io/svmbase-testnet-tokens/main/tokens.json",WSOL_MINT_ADDRESS:"So11111111111111111111111111111111111111112",GITHUB_LOGO_URL:"https://raw.githubusercontent.com/cobaltx-io/svmbase-testnet-tokens/main/logo/So11111111111111111111111111111111111111112.png",LOOKUP_TABLE_CACHE:"AyPMvNmUUY2jwZ75NxhkLYPraQGNk5DssVfP4TnMcPJF",CLMM_PROGRAMM_ID:"DnZnBqJKiGSYHUHYvkXAbQmkMbwrjfgo4orR7jWyMsik",ETH_MINT_ADDRESS:"71kRXzJMvSeArtXYNEWa8KAjpRJosdMQ7Dpgy5Jt5zfd",USDC_MINT_ADDRESS:"63tPXWPnYeZ9hA3dJsAY5RcQ8YbwEz8uZ5nKu3uFD1aK",USDT_MINT_ADDRESS:"4fyX7hSmPetQC2wRS3YVAhWeFzif7WStarKwTvCXrBtD",FULL_TOKEN_NAME:"Wrapped Ethereum",WRAPPED_TOKEN_SYMBOL:"WETH",INPUT_MINT_ADDRESS:we.default.toString(),OUTPUT_MINT_ADDRESS:"63tPXWPnYeZ9hA3dJsAY5RcQ8YbwEz8uZ5nKu3uFD1aK",POPULAR_TOKENS:{SOL:we.default.toString(),ETH:"So11111111111111111111111111111111111111112",USDC:"63tPXWPnYeZ9hA3dJsAY5RcQ8YbwEz8uZ5nKu3uFD1aK",USDT:"4fyX7hSmPetQC2wRS3YVAhWeFzif7WStarKwTvCXrBtD"},WSOL_DECIMALS:9},["soonbase_mainnet"]:{NATIVE_TOKEN_SYMBOL:"ETH",SWAP_HOST:"https://trade-api.soonbase.cobaltx.io",BASE_HOST:"https://api.soonbase.cobaltx.io",OWNER_BASE_HOST:"https://api.soonbase.cobaltx.io",SERVICE_BASE_HOST:"https://api.soonbase.cobaltx.io",MONITOR_BASE_HOST:"https://api.soonbase.cobaltx.io",SERVICE_1_BASE_HOST:"https://api.soonbase.cobaltx.io",ANALYTICS_BASE_HOST:"https://api.soonbase.cobaltx.io",GITHUB_TOKEN_LIST_URL:"https://raw.githubusercontent.com/cobaltx-io/soonbase-tokens/main/tokens.json",WSOL_MINT_ADDRESS:"So11111111111111111111111111111111111111112",GITHUB_LOGO_URL:"https://raw.githubusercontent.com/cobaltx-io/soonbase-tokens/main/logo/So11111111111111111111111111111111111111112.png",LOOKUP_TABLE_CACHE:"FGRusuLycV6nhSPQc9VX55YjT6DCzJFc59mvTTarSTjK",CLMM_PROGRAMM_ID:"6f1b3xyVZbnWMHXBjgW1KPwxmPAgXcRdrvKNn4Nmf1Cn",ETH_MINT_ADDRESS:"71kRXzJMvSeArtXYNEWa8KAjpRJosdMQ7Dpgy5Jt5zfd",USDC_MINT_ADDRESS:"BoYN2f2gLQS4jpvMSV9dAZwfzKJiKGk4NPck5BjXfujo",USDT_MINT_ADDRESS:"J87bysZjwfS3n6KR21cwbdPZVJWNSFcXpWF5kiChAwQH",FULL_TOKEN_NAME:"Wrapped Ethereum",WRAPPED_TOKEN_SYMBOL:"WETH",INPUT_MINT_ADDRESS:we.default.toString(),OUTPUT_MINT_ADDRESS:"BoYN2f2gLQS4jpvMSV9dAZwfzKJiKGk4NPck5BjXfujo",POPULAR_TOKENS:{SOL:we.default.toString(),ETH:"FkvCG5DcuYCQ1BnPH4ZzTkCdk3VzutgyDAFBec4qAjhh",USDC:"BoYN2f2gLQS4jpvMSV9dAZwfzKJiKGk4NPck5BjXfujo",USDT:"J87bysZjwfS3n6KR21cwbdPZVJWNSFcXpWF5kiChAwQH"},WSOL_DECIMALS:9}},_e=t=>_r[t];import{PublicKey as Es}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Dr}from"@solana/spl-token";import{PublicKey as j,SystemProgram as Vn,SYSVAR_RENT_PUBKEY as Fr}from"@solana/web3.js";function Jt({pubkey:t,isSigner:e=!1,isWritable:n=!0}){return{pubkey:t,isWritable:n,isSigner:e}}var Ns=[Jt({pubkey:Dr,isWritable:!1}),Jt({pubkey:Vn.programId,isWritable:!1}),Jt({pubkey:Fr,isWritable:!1})];function qn({publicKey:t,transformSol:e,network:n}){let i=Un(t.toString());if(e&&n){let{WSOLMint:r}=ue(n);if(i instanceof j)return e&&i.equals($t)?r:i;if(e&&i.toString()===$t.toBase58())return r}else if(i instanceof j)return i;if(typeof i=="string"){if(i===j.default.toBase58())return j.default;try{return new j(i)}catch{throw new Error("invalid public key")}}throw new Error("invalid public key")}function Un(t){try{return new j(t)}catch{return t}}var vr=new j("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),At=new j("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Pt=new j("SysvarRent111111111111111111111111111111111"),Ls=new j("SysvarC1ock11111111111111111111111111111111"),De=new j("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Rs=new j("Sysvar1nstructions1111111111111111111111111"),Gn=Vn.programId,$t=j.default;function ue(t){let e=_e(t);return{USDCMint:new j(e.USDC_MINT_ADDRESS),USDTMint:new j(e.USDT_MINT_ADDRESS),WSOLMint:new j(e.WSOL_MINT_ADDRESS),ETHMint:new j(e.ETH_MINT_ADDRESS),BONK_Mint:e.BONK_MINT_ADDRESS?new j(e.BONK_MINT_ADDRESS):j.default,SOL_Mint:e.SOL_MINT_ADDRESS?new j(e.SOL_MINT_ADDRESS):j.default,INPUT_MINT:new j(e.INPUT_MINT_ADDRESS),OUTPUT_MINT:new j(e.OUTPUT_MINT_ADDRESS)}}function Ye(t,e){return qn({publicKey:t,transformSol:!0,network:e})}import Vr from"toformat";var qr=Vr,Ze=qr;import ht from"big.js";import Gr from"bn.js";import Xr from"decimal.js-light";var Tt=$("module/fraction"),en=Ze(ht),Qe=Ze(Xr),Hr={[0]:Qe.ROUND_DOWN,[1]:Qe.ROUND_HALF_UP,[2]:Qe.ROUND_UP},zr={[0]:ht.roundDown,[1]:ht.roundHalfUp,[2]:ht.roundUp},H=class{constructor(e,n=new Gr(1)){this.numerator=fe(e),this.denominator=fe(n)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new H(this.denominator,this.numerator)}add(e){let n=e instanceof H?e:new H(fe(e));return this.denominator.eq(n.denominator)?new H(this.numerator.add(n.numerator),this.denominator):new H(this.numerator.mul(n.denominator).add(n.numerator.mul(this.denominator)),this.denominator.mul(n.denominator))}sub(e){let n=e instanceof H?e:new H(fe(e));return this.denominator.eq(n.denominator)?new H(this.numerator.sub(n.numerator),this.denominator):new H(this.numerator.mul(n.denominator).sub(n.numerator.mul(this.denominator)),this.denominator.mul(n.denominator))}mul(e){let n=e instanceof H?e:new H(fe(e));return new H(this.numerator.mul(n.numerator),this.denominator.mul(n.denominator))}div(e){let n=e instanceof H?e:new H(fe(e));return new H(this.numerator.mul(n.denominator),this.denominator.mul(n.numerator))}toSignificant(e,n={groupSeparator:""},i=1){Number.isInteger(e)||Tt.logWithError(`${e} is not an integer.`),e<=0&&Tt.logWithError(`${e} is not positive.`),Qe.set({precision:e+1,rounding:Hr[i]});let r=new Qe(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return r.toFormat(r.decimalPlaces(),n)}toFixed(e,n={groupSeparator:""},i=1){return Number.isInteger(e)||Tt.logWithError(`${e} is not an integer.`),e<0&&Tt.logWithError(`${e} is negative.`),en.DP=e,en.RM=zr[i]||1,new en(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,n)}isZero(){return this.numerator.isZero()}};import Yr from"bn.js";var Hn=new H(new Yr(100)),oe=class extends H{toSignificant(e=5,n,i){return this.mul(Hn).toSignificant(e,n,i)}toFixed(e=2,n,i){return this.mul(Hn).toFixed(e,n,i)}};var sa=$("CobaltX_price");function Zt(t,e=1,n=[]){let i=[...t];if(e<=0)return n;for(;i.length;)n.push(i.splice(0,e));return n}import{PublicKey as to}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as no}from"@solana/spl-token";import{ComputeBudgetProgram as zn,Keypair as jn,PublicKey as jr,Transaction as Zn,TransactionMessage as Zr,VersionedTransaction as Qn}from"@solana/web3.js";var re={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"};import{TOKEN_PROGRAM_ID as Qr}from"@solana/spl-token";var Yn=$("CobaltX_txUtil"),Jn=1644;function It(t){let e=[],n=[];return t.microLamports&&(e.push(zn.setComputeUnitPrice({microLamports:t.microLamports})),n.push(re.SetComputeUnitPrice)),t.units&&(e.push(zn.setComputeUnitLimit({units:t.units})),n.push(re.SetComputeUnitLimit)),{instructions:e,instructionTypes:n}}async function Fe(t,e){var i,r;let n=e!=null?e:"confirmed";return(r=await((i=t.getLatestBlockhash)==null?void 0:i.call(t,{commitment:n})))==null?void 0:r.blockhash}async function xt(t,e){return t.getSignatureStatuses([e]),new Promise((n,i)=>{let r=setTimeout(i,6e4);t.onSignature(e,o=>{if(clearTimeout(r),!o.err){n("");return}i(o.err.toString())},"confirmed")})}function Jr(t,e){t.length<1&&Yn.logWithError(`no instructions provided: ${t.toString()}`),e.length<1&&Yn.logWithError(`no signers provided:, ${e.toString()}`);let n=new Zn;n.recentBlockhash="11111111111111111111111111111111",n.feePayer=e[0],n.add(...t);try{return Buffer.from(n.serialize({verifySignatures:!1})).toString("base64").length<Jn}catch{return!1}}function ce(t,e){let[n,i]=jr.findProgramAddressSync(t,e);return{publicKey:n,nonce:i}}function Je({instructions:t,payer:e,signers:n}){return Jr(t,[e,...n])}function $e({instructions:t,payer:e,lookupTableAddressAccount:n,recentBlockhash:i=jn.generate().publicKey.toString()}){let o=new Zr({payerKey:e,recentBlockhash:i,instructions:t}).compileToV0Message(Object.values(n!=null?n:{}));try{return Buffer.from(new Qn(o).serialize()).toString("base64").length<Jn}catch{return!1}}var $r=t=>Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength):Buffer.from(t),eo=t=>{let e=t.serialize({requireAllSignatures:!1,verifySignatures:!1});t instanceof Qn&&(e=$r(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch{return e.toString("base64")}};function Ce(t){let e=[];return t.forEach(n=>{n instanceof Zn&&(n.recentBlockhash||(n.recentBlockhash=Qr.toBase58()),n.feePayer||(n.feePayer=jn.generate().publicKey)),e.push(eo(n))}),console.log("simulate tx string:",e),e}function be(t,e,n){return ce([t.toBuffer(),(n!=null?n:no).toBuffer(),e.toBuffer()],new to("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}import{PublicKey as E}from"@solana/web3.js";var Va=new E("EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"),qa=new E("CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T"),Ua=new E("9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z"),Ga=new E("FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG"),Xa=new E("CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS"),Ha=new E("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"),za=new E("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),Ya=new E("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"),ja=new E("5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h"),Za=new E("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo");var io=new E("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),ro=new E("kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy"),Qa=new E("routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS"),Ja=new E("7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"),$a=new E("6FJon3QE27qgPVggARueB22hLvoh22VzJpXv4rBEoSLF"),eu=new E("CC12se5To1CdEuw7fDS27B7Geo5jJyL7t5UK2B44NgiH"),tu=new E("9HzJyW1qZsEiSfMUf6L2jo3CcTKAyBmSyKdwQeYisHrC"),nu=new E("DropEU8AvevN3UrXWXTMuz3rqnMczQVNjq3kcSdW2SQi"),$n=new E("CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"),ei=new E("GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"),iu=new E("DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8"),oo=new E("CPMDWBwJDtYax9qW7AyRuVC19Cc4L4Vcy4n2BHAbHkCW"),so=new E("7rQ1QFNosMkUCuh7Z7fPbTHvh73b68sQYdirycEzJVuw"),ao=new E("G11FKBRaAkHAKuLCgLM6K6NUc9rTjPAznRCjZifrTQe2"),St=new E("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),uo=new E("DLockwT7X7sxtLmGH9g5kmfcjaBtncdbUmi738m5bvQC"),Ct=new E("3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH"),co=new E("7AFUeLVRjBfzqK3tTGw8hN48KLQWSk6DTE8xprWdPqix");var ru={SERUM_MARKET:E.default,OPENBOOK_MARKET:new E("EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj"),UTIL1216:E.default,FarmV3:new E("85BFyr98MbCUU9MVTEgzx1nbhWACbJqLzho6zd6DZcWL"),FarmV5:new E("EcLzTrNg9V7qhcdyXDe2qjtPkiGzDM2UbdRaeaadU5r2"),FarmV6:new E("Farm2hJLcqPtPg8M4rR6DMrsRNc5TPm5Cs4bVQrMe2T7"),AmmV4:new E("HWy1jotHpo6UqeQxx49dpYYdQB8wj9Qk9MdxwjLvDHB8"),AmmStable:new E("DDg4VmQaJV9ogWce7LpcjBA9bv22wRp5uaTPa5pGjijF"),CLMM:new E("devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH"),CLMM_LOCK_PROGRAM_ID:new E("DLockwT7X7sxtLmGH9g5kmfcjaBtncdbUmi738m5bvQC"),CLMM_LOCK_AUTH_ID:new E("8qmHNvu2Kr2C7U8mJL4Vz1vTDxMhVuXKREwU7TNoaVEo"),Router:new E("BVChZ3XFEwTMUk1o9i3HAf91H6mFxSwa5X2wFAWhYPhU"),CREATE_CPMM_POOL_PROGRAM:oo,CREATE_CPMM_POOL_AUTH:so,CREATE_CPMM_POOL_FEE_ACC:ao,FEE_DESTINATION_ID:new E("3XMrhbv989VxAMi3DErLV9eJht1pHppW5LbKxe9fkEFR"),LOCK_CPMM_PROGRAM:uo,LCOK_CPMM_AUTH:co};import le from"bn.js";var et=1e4;function ge(t,e,n,i){if(e===void 0)return{amount:t,fee:void 0,expirationTime:void 0};let r={...e,olderTransferFee:{epoch:BigInt(e.olderTransferFee.epoch),maximumFee:BigInt(e.olderTransferFee.maximumFee),transferFeeBasisPoints:e.olderTransferFee.transferFeeBasisPoints},newerTransferFee:{epoch:BigInt(e.newerTransferFee.epoch),maximumFee:BigInt(e.newerTransferFee.maximumFee),transferFeeBasisPoints:e.newerTransferFee.transferFeeBasisPoints}},o=n.epoch<r.newerTransferFee.epoch?r.olderTransferFee:r.newerTransferFee,s=new le(o.maximumFee.toString()),a=n.epoch<r.newerTransferFee.epoch?(Number(r.newerTransferFee.epoch)*n.slotsInEpoch-n.absoluteSlot)*400/1e3:void 0;if(i)if(o.transferFeeBasisPoints===et){let c=new le(o.maximumFee.toString());return{amount:t.add(c),fee:c,expirationTime:a}}else{let c=ve(t.mul(new le(et)),new le(et-o.transferFeeBasisPoints)),u=new le(o.maximumFee.toString()),l=c.sub(t).gt(u)?t.add(u):c,m=ve(l.mul(new le(o.transferFeeBasisPoints)),new le(et)),d=m.gt(s)?s:m;return{amount:l,fee:d,expirationTime:a}}else{let c=ve(t.mul(new le(o.transferFeeBasisPoints)),new le(et)),u=c.gt(s)?s:c;return{amount:t,fee:u,expirationTime:a}}}function ve(t,e){let{div:n,mod:i}=t.divmod(e);return i.gt(new le(0))?n.add(new le(1)):n}import{PublicKey as ti,AddressLookupTableAccount as Kt}from"@solana/web3.js";async function rn({connection:t,address:e,network:n}){let i=await ze(t,[...new Set(e.map(o=>o.toString()))].map(o=>new ti(o))),r={};for(let o=0;o<e.length;o++){let s=i[o],a=e[o];if(!s)continue;let c=new Kt({key:a,state:Kt.deserialize(s.data)});r[a.toString()]=c,Nt(n)[a.toString()]=c}return r}function Nt(t){let e=_e(t);return{[e.LOOKUP_TABLE_CACHE]:new Kt({key:new ti(e.LOOKUP_TABLE_CACHE),state:Kt.deserialize(Buffer.from("AQAAAP//////////d49+DAAAAAAAAQZMWvw7GUNJdaccNBVnb57OKakxL2BHLYvhRwVILRsgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMGRm/lIRcy/+ytunLDm+e8jOW7xfcSayxDmzpAAAAABt324ddloZPZy+FGzut5rBy0he1fWzeROoz1hX7/AKkG3fbh7nWP3hhCXbzkbM3athr8TYO5DSf+vfko2KGL/AVKU1D4XciC1hSlVnJ4iilt3x6rq9CmBniISTL07vagBqfVFxksXFEhjMlMPUrxf1ja7gibof1E49vZigAAAAAGp9UXGMd0yShWY5hpHV62i164o5tLbVxzVVshAAAAAIyXJY9OJInxuz0QKRSODYMLWhOZ2v8QhASOe9jb6fhZC3BlsePRfEU4nVJ/awTDzVi4bHMaoP21SbbRvAP4KUbIScv+6Yw2LHF/6K0ZjUPibbSWXCirYPGuuVl7zT789IUPLW4CpHr4JNCatp3ELXDLKMv6JJ+37le50lbBJ2LvDQdRqCgtphMF/imcN7mY5YRx2xE1A3MQ+L4QRaYK9u4GRfZP3LsAd00a+IkCpA22UNQMKdq5BFbJuwuOLqc8zxCTDlqxBG8J0HcxtfogQHDK06ukzfaXiNDKAob1MqBHS9lJxDYCwz8gd5DtFqNSTKG5l1zxIaKpDP/sffi2is1H9aKveyXSu5StXElYRl9SD5As0DHE4N0GLnf84/siiKXVyp4Ez121kLcUui/jLLFZEz/BwZK3Ilf9B9OcsEAeDMKAy2vjGSxQODgBz0QwGA+eP4ZjIjrIAQaXENv31QfLlOdXSRCkaybRniDHF4C8YcwhcvsqrOVuTP4B2Na+9wLdtrB31uz2rtlFI5kahdsnp/d1SrASDInYCtTYtdoke4kX+hoKWcEWM4Tle8pTUkUVv4BxS6fje/EzKBE4Qu9N9LMnrw/JNO0hqMVB4rk/2ou4AB1loQ7FZoPwut2o4KZB+0p9xnbrQKw038qjpHar+PyDwvxBRcu5hpHw3dguezeWv+IwvgW5icu8EGkhGa9AkFPPJT7VMSFb8xowveU=","base64"))})}}import{PublicKey as tt,sendAndConfirmTransaction as on,Transaction as nt,TransactionMessage as it,VersionedTransaction as rt}from"@solana/web3.js";import mo from"axios";var Lt=class{constructor(e){this.instructions=[];this.endInstructions=[];this.lookupTableAddress=[];this.signers=[];this.instructionTypes=[];this.endInstructionTypes=[];this.connection=e.connection,this.feePayer=e.feePayer,this.signAllTransactions=e.signAllTransactions,this.owner=e.owner,this.cluster=e.cluster,this.blockhashCommitment=e.blockhashCommitment,this.api=e.api,this.network=e.network}get AllTxData(){return{instructions:this.instructions,endInstructions:this.endInstructions,signers:this.signers,instructionTypes:this.instructionTypes,endInstructionTypes:this.endInstructionTypes,lookupTableAddress:this.lookupTableAddress}}get allInstructions(){return[...this.instructions,...this.endInstructions]}async getComputeBudgetConfig(){var i;let e=(await mo.get(`https://solanacompass.com/api/fees?cacheFreshTime=${3e5}`)).data,{avg:n}=(i=e==null?void 0:e[15])!=null?i:{};if(!!n)return{units:6e5,microLamports:Math.min(Math.ceil(n*1e6/6e5),25e3)}}addCustomComputeBudget(e){if(e){let{instructions:n,instructionTypes:i}=It(e);return this.instructions.unshift(...n),this.instructionTypes.unshift(...i),!0}return!1}async calComputeBudget({config:e,defaultIns:n}){try{let i=e||await this.getComputeBudgetConfig();if(this.addCustomComputeBudget(i))return;n&&this.instructions.unshift(...n)}catch{n&&this.instructions.unshift(...n)}}addInstruction({instructions:e=[],endInstructions:n=[],signers:i=[],instructionTypes:r=[],endInstructionTypes:o=[],lookupTableAddress:s=[]}){return this.instructions.push(...e),this.endInstructions.push(...n),this.signers.push(...i),this.instructionTypes.push(...r),this.endInstructionTypes.push(...o),this.lookupTableAddress.push(...s.filter(a=>a!==tt.default.toString())),this}async versionBuild({txVersion:e,extInfo:n}){return e===0?await this.buildV0({...n||{}}):this.build(n)}build(e){var i;let n=new nt;return this.allInstructions.length&&n.add(...this.allInstructions),n.feePayer=this.feePayer,((i=this.owner)==null?void 0:i.signer)&&!this.signers.some(r=>r.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 r=>{var u;let{recentBlockHash:o,skipPreflight:s=!0,sendAndConfirm:a}=r||{},c=o!=null?o:await Fe(this.connection,this.blockhashCommitment);if(n.recentBlockhash=c,this.signers.length&&n.sign(...this.signers),Ce([n]),(u=this.owner)!=null&&u.isKeyPair)return{txId:a?await on(this.connection,n,this.signers.find(m=>m.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:s}):await this.connection.sendRawTransaction(n.serialize(),{skipPreflight:s}),signedTx:n};if(this.signAllTransactions){let l=await this.signAllTransactions([n]);return{txId:await this.connection.sendRawTransaction(l[0].serialize(),{skipPreflight:s}),signedTx:l[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:e||{}}}buildMultiTx(e){var u;let{extraPreBuildData:n=[],extInfo:i}=e,{transaction:r}=this.build(i),o=n.filter(l=>l.transaction.instructions.length>0),s=[r,...o.map(l=>l.transaction)],a=[this.signers,...o.map(l=>l.signers)],c=[...this.instructionTypes,...o.map(l=>l.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&a.forEach(l=>{l.some(m=>m.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:s,signers:a,instructionTypes:c,execute:async l=>{var g;let{sequentially:m,onTxUpdate:d,skipTxCount:p=0,recentBlockHash:b,skipPreflight:f=!0}=l||{},y=b!=null?b:await Fe(this.connection,this.blockhashCommitment);if((g=this.owner)!=null&&g.isKeyPair){if(m){let P=[],k=0;for(let A of s){if(++k,k<=p)continue;let h=await on(this.connection,A,this.signers.find(T=>T.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:f});P.push(h)}return{txIds:P,signedTxs:s}}return{txIds:await await Promise.all(s.map(async P=>(P.recentBlockhash=y,await this.connection.sendRawTransaction(P.serialize(),{skipPreflight:f})))),signedTxs:s}}if(this.signAllTransactions){let P=s.map((A,h)=>(A.recentBlockhash=y,a[h].length&&A.sign(...a[h]),A));Ce(P);let k=await this.signAllTransactions(P);if(m){let A=0,h=[],T=async()=>{if(!k[A])return;let C=await this.connection.sendRawTransaction(k[A].serialize(),{skipPreflight:f});h.push({txId:C,status:"sent",signedTx:k[A]}),d==null||d([...h]),A++,this.connection.onSignature(C,N=>{let _=h.findIndex(q=>q.txId===C);_>-1&&(h[_].status=N.err?"error":"success"),d==null||d([...h]),N.err||T()},"processed"),this.connection.getSignatureStatus(C)};return await T(),{txIds:h.map(C=>C.txId),signedTxs:k}}else{let A=[];for(let h=0;h<k.length;h+=1){let T=await this.connection.sendRawTransaction(k[h].serialize(),{skipPreflight:f});A.push(T)}return{txIds:A,signedTxs:k}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:i||{}}}async versionMultiBuild({extraPreBuildData:e,txVersion:n,extInfo:i}){return n===0?await this.buildV0MultiTx({extraPreBuildData:e,buildProps:i||{}}):this.buildMultiTx({extraPreBuildData:e,extInfo:i})}async buildV0(e){var f;let{lookupTableCache:n={},lookupTableAddress:i=[],forerunCreate:r,recentBlockhash:o,network:s=this.network,...a}=e||{},c={...this.cluster==="devnet"?{}:Nt(s),...n},u=Array.from(new Set([...i,...this.lookupTableAddress])),l=[];for(let y of u)c[y]===void 0&&l.push(new tt(y));let m=await rn({connection:this.connection,address:l,network:s});for(let[y,g]of Object.entries(m))c[y]=g;let d=r?tt.default.toBase58():o!=null?o:await Fe(this.connection,this.blockhashCommitment),p=new it({payerKey:this.feePayer,recentBlockhash:d,instructions:[...this.allInstructions]}).compileToV0Message();((f=this.owner)==null?void 0:f.signer)&&!this.signers.some(y=>y.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let b=new rt(p);return b.sign(this.signers),{builder:this,transaction:b,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async y=>{var k;let{skipPreflight:g=!0,sendAndConfirm:P}=y||{};if(Ce([b]),(k=this.owner)!=null&&k.isKeyPair){let A=await this.connection.sendTransaction(b,{skipPreflight:g});return P&&await xt(this.connection,A),{txId:A,signedTx:b}}if(this.signAllTransactions){let A=await this.signAllTransactions([b]);return{txId:await this.connection.sendTransaction(A[0],{skipPreflight:g}),signedTx:A[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:a||{}}}async buildV0MultiTx(e){var u;let{extraPreBuildData:n=[],buildProps:i}=e,{transaction:r}=await this.buildV0(i),o=n.filter(l=>l.builder.instructions.length>0),s=[r,...o.map(l=>l.transaction)],a=[this.signers,...o.map(l=>l.signers)],c=[...this.instructionTypes,...o.map(l=>l.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&a.forEach(l=>{l.some(m=>m.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),s.forEach(async(l,m)=>{l.sign(a[m])}),{builder:this,transactions:s,signers:a,instructionTypes:c,buildProps:i,execute:async l=>{var f;let{sequentially:m,onTxUpdate:d,recentBlockHash:p,skipPreflight:b=!0}=l||{};if(p&&s.forEach(y=>y.message.recentBlockhash=p),Ce(s),(f=this.owner)!=null&&f.isKeyPair){if(m){let y=[];for(let g of s){let P=await this.connection.sendTransaction(g,{skipPreflight:b});await xt(this.connection,P),y.push(P)}return{txIds:y,signedTxs:s}}return{txIds:await Promise.all(s.map(async y=>await this.connection.sendTransaction(y,{skipPreflight:b}))),signedTxs:s}}if(this.signAllTransactions){let y=await this.signAllTransactions(s);if(m){let g=0,P=[],k=async()=>{if(!y[g])return;let A=await this.connection.sendTransaction(y[g],{skipPreflight:b});P.push({txId:A,status:"sent",signedTx:y[g]}),d==null||d([...P]),g++,this.connection.onSignature(A,h=>{let T=P.findIndex(C=>C.txId===A);T>-1&&(P[T].status=h.err?"error":"success"),d==null||d([...P]),h.err||k()},"processed"),this.connection.getSignatureStatus(A)};return k(),{txIds:[],signedTxs:y}}else{let g=[];for(let P=0;P<y.length;P+=1){let k=await this.connection.sendTransaction(y[P],{skipPreflight:b});g.push(k)}return{txIds:g,signedTxs:y}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:i||{}}}async sizeCheckBuild(e){var m;let{splitIns:n=[],computeBudgetConfig:i,...r}=e||{},o=i?It(i):{instructions:[],instructionTypes:[]},s=this.signers.reduce((d,p)=>({...d,[p.publicKey.toBase58()]:p}),{}),a=[],c=[],u=[],l=0;if(this.allInstructions.forEach(d=>{let p=[...u,d],b=i?[...o.instructions,...p]:p,y=[...new Set(p.map(g=>g.keys.filter(P=>P.isSigner).map(P=>P.pubkey.toString())).flat()).values()].map(g=>new tt(g));if(d!==n[l]&&u.length<12&&(Je({instructions:b,payer:this.feePayer,signers:y})||Je({instructions:p,payer:this.feePayer,signers:y})))u.push(d);else{if(u.length===0)throw Error("item ins too big");l+=d===n[l]?1:0,Je({instructions:i?[...o.instructions,...u]:[...u],payer:this.feePayer,signers:y})?a.push(new nt().add(...o.instructions,...u)):a.push(new nt().add(...u)),c.push(Array.from(new Set(u.map(g=>g.keys.filter(P=>P.isSigner).map(P=>P.pubkey.toString())).flat())).map(g=>s[g]).filter(g=>g!==void 0)),u=[d]}}),u.length>0){let p=[...new Set(u.map(b=>b.keys.filter(f=>f.isSigner).map(f=>f.pubkey.toString())).flat()).values()].map(b=>s[b]).filter(b=>b!==void 0);Je({instructions:i?[...o.instructions,...u]:[...u],payer:this.feePayer,signers:p.map(b=>b.publicKey)})?a.push(new nt().add(...o.instructions,...u)):a.push(new nt().add(...u)),c.push(p)}return a.forEach(d=>d.feePayer=this.feePayer),(m=this.owner)!=null&&m.signer&&c.forEach(d=>{d.some(p=>p.publicKey.equals(this.owner.publicKey))||d.push(this.owner.signer)}),{builder:this,transactions:a,signers:c,instructionTypes:this.instructionTypes,execute:async d=>{var k;let{sequentially:p,onTxUpdate:b,skipTxCount:f=0,recentBlockHash:y,skipPreflight:g=!0}=d||{},P=y!=null?y:await Fe(this.connection,this.blockhashCommitment);if(a.forEach(async(A,h)=>{A.recentBlockhash=P,c[h].length&&A.sign(...c[h])}),Ce(a),(k=this.owner)!=null&&k.isKeyPair){if(p){let A=0,h=[];for(let T of a){if(++A,A<=f){h.push("tx skipped");continue}let C=await on(this.connection,T,this.signers.find(N=>N.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:g});h.push(C)}return{txIds:h,signedTxs:a}}return{txIds:await Promise.all(a.map(async A=>await this.connection.sendRawTransaction(A.serialize(),{skipPreflight:g}))),signedTxs:a}}if(this.signAllTransactions){let A=await this.signAllTransactions(a.slice(f,a.length)),h=[...a.slice(0,f),...A];if(p){let T=0,C=[],N=async()=>{if(!h[T])return;T<f&&(C.push({txId:"",status:"success",signedTx:h[T]}),b==null||b([...C]),T++,N());let _=await this.connection.sendRawTransaction(h[T].serialize(),{skipPreflight:g});C.push({txId:_,status:"sent",signedTx:h[T]}),b==null||b([...C]),T++,this.connection.onSignature(_,q=>{let M=C.findIndex(D=>D.txId===_);M>-1&&(C[M].status=q.err?"error":"success"),b==null||b([...C]),q.err||N()},"processed"),this.connection.getSignatureStatus(_)};return await N(),{txIds:C.map(_=>_.txId),signedTxs:h}}else{let T=[];for(let C=0;C<h.length;C+=1){let N=await this.connection.sendRawTransaction(h[C].serialize(),{skipPreflight:g});T.push(N)}return{txIds:T,signedTxs:h}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:r||{}}}async sizeCheckBuildV0(e){var k;let{computeBudgetConfig:n,splitIns:i=[],lookupTableCache:r={},lookupTableAddress:o=[],network:s=this.network,...a}=e||{},c={...this.cluster==="devnet"?{}:Nt(s),...r},u=Array.from(new Set([...this.lookupTableAddress,...o])),l=[];for(let A of u)c[A]===void 0&&l.push(new tt(A));let m=await rn({connection:this.connection,address:l,network:s});for(let[A,h]of Object.entries(m))c[A]=h;let d=n?It(n):{instructions:[],instructionTypes:[]},p=await Fe(this.connection,this.blockhashCommitment),b=this.signers.reduce((A,h)=>({...A,[h.publicKey.toBase58()]:h}),{}),f=[],y=[],g=[],P=0;if(this.allInstructions.forEach(A=>{let h=[...g,A],T=n?[...d.instructions,...h]:h;if(A!==i[P]&&g.length<12&&($e({instructions:T,payer:this.feePayer,lookupTableAddressAccount:c})||$e({instructions:h,payer:this.feePayer,lookupTableAddressAccount:c})))g.push(A);else{if(g.length===0)throw Error("item ins too big");P+=A===i[P]?1:0;let C={};for(let N of[...new Set(u)])c[N]!==void 0&&(C[N]=c[N]);if(n&&$e({instructions:[...d.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:c,recentBlockhash:p})){let N=new it({payerKey:this.feePayer,recentBlockhash:p,instructions:[...d.instructions,...g]}).compileToV0Message(Object.values(c));f.push(new rt(N))}else{let N=new it({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(c));f.push(new rt(N))}y.push(Array.from(new Set(g.map(N=>N.keys.filter(_=>_.isSigner).map(_=>_.pubkey.toString())).flat())).map(N=>b[N]).filter(N=>N!==void 0)),g=[A]}}),g.length>0){let h=[...new Set(g.map(T=>T.keys.filter(C=>C.isSigner).map(C=>C.pubkey.toString())).flat()).values()].map(T=>b[T]).filter(T=>T!==void 0);if(n&&$e({instructions:[...d.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:c,recentBlockhash:p})){let T=new it({payerKey:this.feePayer,recentBlockhash:p,instructions:[...d.instructions,...g]}).compileToV0Message(Object.values(c));f.push(new rt(T))}else{let T=new it({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(c));f.push(new rt(T))}y.push(h)}return(k=this.owner)!=null&&k.signer&&y.forEach(A=>{A.some(h=>h.publicKey.equals(this.owner.publicKey))||A.push(this.owner.signer)}),{builder:this,transactions:f,buildProps:e,signers:y,instructionTypes:this.instructionTypes,execute:async A=>{var q;let{sequentially:h,onTxUpdate:T,skipTxCount:C=0,recentBlockHash:N,skipPreflight:_=!0}=A||{};if(f.map(async(M,D)=>{y[D].length&&M.sign(y[D]),N&&(M.message.recentBlockhash=N)}),Ce(f),(q=this.owner)!=null&&q.isKeyPair){if(h){let M=0,D=[];for(let v of f){if(++M,M<=C){console.log("skip tx: ",M),D.push("tx skipped");continue}let W=await this.connection.sendTransaction(v,{skipPreflight:_});await xt(this.connection,W),D.push(W)}return{txIds:D,signedTxs:f}}return{txIds:await Promise.all(f.map(async M=>await this.connection.sendTransaction(M,{skipPreflight:_}))),signedTxs:f}}if(this.signAllTransactions){let M=await this.signAllTransactions(f.slice(C,f.length)),D=[...f.slice(0,C),...M];if(h){let v=0,W=[],U=async()=>{if(!D[v])return;if(v<C){W.push({txId:"",status:"success",signedTx:D[v]}),T==null||T([...W]),v++,U();return}let F=await this.connection.sendTransaction(D[v],{skipPreflight:_});W.push({txId:F,status:"sent",signedTx:D[v]}),T==null||T([...W]),v++,this.connection.onSignature(F,kn=>{let Tn=W.findIndex(_i=>_i.txId===F);Tn>-1&&(W[Tn].status=kn.err?"error":"success"),T==null||T([...W]),kn.err||U()},"processed"),this.connection.getSignatureStatus(F)};return U(),{txIds:[],signedTxs:D}}else{let v=[];for(let W=0;W<D.length;W+=1){let U=await this.connection.sendTransaction(D[W],{skipPreflight:_});v.push(U)}return{txIds:v,signedTxs:D}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:a||{}}}};import{PublicKey as xu}from"@solana/web3.js";import Cu from"bn.js";var ac=$("CobaltX_amount"),uc=Ze(po);var nn=new Ae(0),Ic=new Ae(1),xc=new Ae(2),Sc=new Ae(3),Cc=new Ae(5),fo=new Ae(10),Kc=new Ae(100),Nc=new Ae(1e3),Lc=new Ae(1e4);import{AccountLayout as es,NATIVE_MINT as qt,TOKEN_PROGRAM_ID as me}from"@solana/spl-token";import{PublicKey as B}from"@solana/web3.js";import an from"bn.js";import Et from"decimal.js-light";import ot from"bn.js";function Rt(t,e){if(e.isZero())throw Error("divisor is zero");return t.mod(e)}function bo(t,e){if(e.isZero())throw Error("rhs is zero");let n=t.div(e);if(n.isZero())throw Error("quotient is zero");let i=Rt(t,e);return i.gt(We)&&(n=n.add(new ot(1)),e=t.div(n),i=Rt(t,n),i.gt(We)&&(e=e.add(new ot(1)))),[n,e]}var We=new ot(0),Mt=class{static swapWithoutFees(e,n,i){let r=n.mul(i),o=n.add(e),[s,a]=bo(r,o),c=a.sub(n),u=i.sub(s);if(u.isZero())throw Error("destinationAmountSwapped is zero");return{sourceAmountSwapped:c,destinationAmountSwapped:u}}static lpTokensToTradingTokens(e,n,i,r,o){let s=e.mul(i).div(n),a=e.mul(r).div(n);if(o===0)return{tokenAmount0:s,tokenAmount1:a};if(o===1)return Rt(e.mul(i),n).gt(We)&&s.gt(We)&&(s=s.add(new ot(1))),Rt(e.mul(r),n).gt(We)&&a.gt(We)&&(a=a.add(new ot(1))),{tokenAmount0:s,tokenAmount1:a};throw Error("roundDirection value error")}};import ii from"bn.js";var sn=new ii(1e6);function go(t,e,n){return t.mul(e).add(n).sub(new ii(1)).div(n)}function ni(t,e,n){return t.mul(e).div(n)}var Ot=class{static tradingFee(e,n){return go(e,n,sn)}static protocolFee(e,n){return ni(e,n,sn)}static fundFee(e,n){return ni(e,n,sn)}};var _t=class{static validate_supply(e,n){if(e.isZero())throw Error("tokenAmount0 is zero");if(n.isZero())throw Error("tokenAmount1 is zero")}static swap(e,n,i,r){let o=Ot.tradingFee(e,r),s=e.sub(o),{sourceAmountSwapped:a,destinationAmountSwapped:c}=Mt.swapWithoutFees(s,n,i),u=a.add(o);return{newSwapSourceAmount:n.add(u),newSwapDestinationAmount:i.sub(c),sourceAmountSwapped:u,destinationAmountSwapped:c,tradeFee:o}}static swapBaseOut({poolMintA:e,poolMintB:n,tradeFeeRate:i,baseReserve:r,quoteReserve:o,outputMint:s,outputAmount:a}){let[c,u,l,m,d]=n.address===s.toString()?[r,o,e.decimals,n.decimals,e.address]:[o,r,n.decimals,e.decimals,n.address],p=new Et(u.toString()).div(10**m).div(new Et(c.toString()).div(10**l)),b=a.gte(u)?u.sub(new an(1)):a,f=u.sub(b),y=ve(c.mul(b),f),g=ve(y.mul(new an(1e6)),new an(1e6).sub(i)),P=g.sub(y),k=new Et(b.toString()).div(10**m).div(new Et(g.toString()).div(10**l)),A=p.isZero()?0:k.sub(p).div(p).abs().toNumber();return{amountRealOut:b,amountIn:g,amountInWithoutFee:y,tradeFee:P,priceImpact:A}}};import Z from"bn.js";var un=(...t)=>t.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch{return e}}).join(", "),Ve=class{constructor({scope:e,moduleName:n,network:i}){this.disabled=!1;this.scope=e,this.logger=$(n),this.network=i}createTxBuilder(e){return this.scope.checkOwner(),new Lt({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,network:this.network})}logDebug(...e){this.logger.debug(un(e))}logInfo(...e){this.logger.info(un(e))}logAndCreateError(...e){let n=un(e);throw new Error(n)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};import{PublicKey as Io}from"@solana/web3.js";import ai,{isBN as ui}from"bn.js";import{bits as Jc,BitStructure as $c,blob as yo,Blob as el,cstr as tl,f32 as nl,f32be as il,f64 as rl,f64be as ol,greedy as sl,Layout as wo,ns64 as al,ns64be as ul,nu64 as cl,nu64be as ll,offset as ml,s16 as dl,s16be as pl,s24 as fl,s24be as bl,s32 as Ao,s32be as gl,s40 as yl,s40be as wl,s48 as Al,s48be as Pl,s8 as kl,seq as Po,struct as Tl,Structure as ko,u16 as To,u16be as hl,u24 as Bl,u24be as Il,u32 as xl,u32be as Sl,u40 as Cl,u40be as Kl,u48 as Nl,u48be as Ll,u8 as ho,UInt as Bo,union as Rl,Union as Ml,unionLayoutDiscriminator as Ol,utf8 as El}from"@solana/buffer-layout";var cn=wo,ri=ko;var ln=Bo;var oi=ho,Ke=To;var Pe=Ao;var si=Po;var ne=yo;var qe=class extends cn{constructor(n,i,r){super(n,r);this.blob=ne(n),this.signed=i}decode(n,i=0){let r=new ai(this.blob.decode(n,i),10,"le");return this.signed?r.fromTwos(this.span*8).clone():r}encode(n,i,r=0){return typeof n=="number"&&(n=new ai(n)),this.signed&&(n=n.toTwos(this.span*8)),this.blob.encode(n.toArrayLike(Buffer,"le",this.span),i,r)}};function z(t){return new ln(1,t)}function ke(t){return new ln(4,t)}function I(t){return new qe(8,!1,t)}function Y(t){return new qe(16,!1,t)}function ci(t){return new qe(8,!0,t)}function li(t){return new qe(16,!0,t)}var Dt=class extends cn{constructor(n,i,r,o){super(n.span,o);this.layout=n,this.decoder=i,this.encoder=r}decode(n,i){return this.decoder(this.layout.decode(n,i))}encode(n,i,r){return this.layout.encode(this.encoder(n),i,r)}getSpan(n,i){return this.layout.getSpan(n,i)}};function O(t){return new Dt(ne(32),e=>new Io(e),e=>e.toBuffer(),t)}function Ne(t){return new Dt(oi(),xo,So,t)}function xo(t){if(t===0)return!1;if(t===1)return!0;throw new Error("Invalid bool: "+t)}function So(t){return t?1:0}var mn=class extends ri{decode(e,n){return super.decode(e,n)}};function V(t,e,n){return new mn(t,e,n)}function X(t,e,n){let i,r=typeof e=="number"?e:ui(e)?e.toNumber():new Proxy(e,{get(o,s){if(!i){let a=Reflect.get(o,"count");i=ui(a)?a.toNumber():a,Reflect.set(o,"count",i)}return Reflect.get(o,s)},set(o,s,a){return s==="count"&&(i=a),Reflect.set(o,s,a)}});return si(t,r,n)}var jl=V([ke("mintAuthorityOption"),O("mintAuthority"),I("supply"),z("decimals"),z("isInitialized"),ke("freezeAuthorityOption"),O("freezeAuthority")]);import{PublicKey as $l}from"@solana/web3.js";import{MintLayout as tm,TOKEN_PROGRAM_ID as im}from"@solana/spl-token";var Le=({address:t,programId:e,decimals:n,network:i,...r})=>({chainId:101,address:Ye(t,i).toBase58(),programId:e,logoURI:"",symbol:"",name:"",decimals:n,tags:[],extensions:r.extensions||{},...r}),Ue=t=>t?{...t,transferFeeConfigAuthority:t.transferFeeConfigAuthority.toBase58(),withdrawWithheldAuthority:t.withdrawWithheldAuthority.toBase58(),withheldAmount:t.withheldAmount.toString(),olderTransferFee:{...t.olderTransferFee,epoch:t.olderTransferFee.epoch.toString(),maximumFee:t.olderTransferFee.maximumFee.toString()},newerTransferFee:{...t.newerTransferFee,epoch:t.newerTransferFee.epoch.toString(),maximumFee:t.newerTransferFee.maximumFee.toString()}}:void 0;import{ASSOCIATED_TOKEN_PROGRAM_ID as xi,TOKEN_2022_PROGRAM_ID as An,TOKEN_PROGRAM_ID as xe}from"@solana/spl-token";import{Keypair as Zo,PublicKey as lt,SystemProgram as Qo,TransactionInstruction as Re}from"@solana/web3.js";var Co=Buffer.from("vault_and_lp_mint_auth_seed","utf8"),bm=Buffer.from("amm_config","utf8"),Ko=Buffer.from("pool","utf8"),No=Buffer.from("pool_lp_mint","utf8"),Lo=Buffer.from("pool_vault","utf8"),Ro=Buffer.from("observation","utf8");function Ft(t){return ce([Co],t)}function dn(t,e,n,i){return ce([Ko,e.toBuffer(),n.toBuffer(),i.toBuffer()],t)}function Mo(t,e){return ce([No,e.toBuffer()],t)}function mi(t,e,n){return ce([Lo,e.toBuffer(),n.toBuffer()],t)}function st(t,e){return ce([Ro,e.toBuffer()],t)}function di({poolId:t,programId:e,configId:n,mintA:i,mintB:r}){let o=Ft(e).publicKey,s=t||dn(e,n,i,r).publicKey,a=Mo(e,s).publicKey,c=mi(e,s,i).publicKey,u=mi(e,s,r).publicKey,l=st(e,s).publicKey;return{poolId:s,configId:n,authority:o,lpMint:a,vaultA:c,vaultB:u,observationId:l}}var Oo=Buffer.from("locked_liquidity","utf8");function vt(t,e){return ce([Oo,e.toBuffer()],t)}import{AccountLayout as jp,TOKEN_2022_PROGRAM_ID as Zp,TOKEN_PROGRAM_ID as Qp}from"@solana/spl-token";import{PublicKey as $p}from"@solana/web3.js";import tf from"bn.js";import{ASSOCIATED_TOKEN_PROGRAM_ID as hp,TOKEN_2022_PROGRAM_ID as Bp,TOKEN_PROGRAM_ID as Ip}from"@solana/spl-token";import{Keypair as Cp,PublicKey as Kp,SystemProgram as Lp,TransactionInstruction as Rp}from"@solana/web3.js";import Op from"bn.js";import tp from"bn.js";import se from"bn.js";var pi=new se(0),fi=new se(1),bi=new se(-1),Wt=new se(1).shln(64),gi=new se(1).shln(128),Eo=Wt.sub(fi);var _o=gi.subn(1),Ge=-443636,at=-Ge,pn=new se("4295048016"),fn=new se("79226673521066979257578248091"),wm=new se("4295048017"),Am=new se("79226673521066979257578248090");var Do=new se(10).pow(new se(6));var Pm=new se("18446744073700000000");import Vd from"bn.js";var Sm=Buffer.from("amm_config","utf8"),Cm=Buffer.from("pool","utf8"),Km=Buffer.from("pool_vault","utf8"),Nm=Buffer.from("pool_reward_vault","utf8"),Lm=Buffer.from("position","utf8"),Rm=Buffer.from("tick_array","utf8"),Mm=Buffer.from("operation","utf8"),Om=Buffer.from("pool_tick_array_bitmap_extension","utf8"),Em=Buffer.from("observation","utf8");function bn(t){return ce([Buffer.from("metadata","utf8"),De.toBuffer(),t.toBuffer()],De)}var _m=Buffer.from("locked_position","utf8");import{TOKEN_2022_PROGRAM_ID as pd}from"@solana/spl-token";import{PublicKey as yd}from"@solana/web3.js";import Ad from"bn.js";import vm from"bn.js";var wn=14;var Vt=60;var Vo=V([ne(8),z("bump"),Ke("index"),O(""),ke("protocolFeeRate"),ke("tradeFeeRate"),Ke("tickSpacing"),X(I(),8,"")]),qo=V([ke("blockTimestamp"),ci("tickCumulative"),X(I(),4)]),Ii=V([ne(8),Ne("initialized"),I("recentEpoch"),Ke("observationIndex"),O("poolId"),X(qo,100,"observations"),X(I(),4)]),Uo=V([z("rewardState"),I("openTime"),I("endTime"),I("lastUpdateTime"),Y("emissionsPerSecondX64"),I("rewardTotalEmissioned"),I("rewardClaimed"),O("tokenMint"),O("tokenVault"),O("creator"),Y("rewardGrowthGlobalX64")]),Ti=V([ne(8),z("bump"),O("ammConfig"),O("creator"),O("mintA"),O("mintB"),O("vaultA"),O("vaultB"),O("observationId"),z("mintDecimalsA"),z("mintDecimalsB"),Ke("tickSpacing"),Y("liquidity"),Y("sqrtPriceX64"),Pe("tickCurrent"),ke(),Y("feeGrowthGlobalX64A"),Y("feeGrowthGlobalX64B"),I("protocolFeesTokenA"),I("protocolFeesTokenB"),Y("swapInAmountTokenA"),Y("swapOutAmountTokenB"),Y("swapInAmountTokenB"),Y("swapOutAmountTokenA"),z("status"),X(z(),7,""),X(Uo,3,"rewardInfos"),X(I(),16,"tickArrayBitmap"),I("totalFeesTokenA"),I("totalFeesClaimedTokenA"),I("totalFeesTokenB"),I("totalFeesClaimedTokenB"),I("fundFeesTokenA"),I("fundFeesTokenB"),I("startTime"),X(I(),15*4-3,"padding")]),Go=V([Y("growthInsideLastX64"),I("rewardAmountOwed")]),hi=V([ne(8),z("bump"),O("nftMint"),O("poolId"),Pe("tickLower"),Pe("tickUpper"),Y("liquidity"),Y("feeGrowthInsideLastX64A"),Y("feeGrowthInsideLastX64B"),I("tokenFeesOwedA"),I("tokenFeesOwedB"),X(Go,3,"rewardInfos"),X(I(),8,"")]),mp=V([ne(8),z("bump"),O("poolId"),Pe("tickLowerIndex"),Pe("tickUpperIndex"),Y("liquidity"),Y("feeGrowthInsideLastX64A"),Y("feeGrowthInsideLastX64B"),I("tokenFeesOwedA"),I("tokenFeesOwedB"),X(Y(),3,"rewardGrowthInside"),X(I(),8,"")]),Xo=V([Pe("tick"),li("liquidityNet"),Y("liquidityGross"),Y("feeGrowthOutsideX64A"),Y("feeGrowthOutsideX64B"),X(Y(),3,"rewardGrowthsOutsideX64"),X(ke(),13,"")]),Ai=V([ne(8),O("poolId"),Pe("startTickIndex"),X(Xo,Vt,"ticks"),z("initializedTickCount"),X(z(),115,"")]),Ho=V([ne(329),X(O(),100,"whitelistMints")]),Wo=V([ne(8),O("poolId"),X(X(I(),8),wn,"positiveTickArrayBitmap"),X(X(I(),8),wn,"negativeTickArrayBitmap")]),dp=V([I(),z("bump"),O("owner"),O("poolId"),O("positionId"),O("nftAccount"),X(I(),8)]),pp=V([ne(8),z("bump"),O("lockOwner"),O("poolId"),O("positionId"),O("nftAccount"),O("lockNftMint"),I("recentEpoch"),X(I(),8)]);Ii.span;var Wp=$("CobaltX_Clmm");var Jo=$("CobaltX_cpmm"),Me={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 Si(t,e,n,i,r,o,s,a,c,u,l,m,d,p,b,f,y,g,P,k){let A=V([I("amountMaxA"),I("amountMaxB"),I("openTime")]),h=dn(t,n,o,s).publicKey,T=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!r.equals(h),isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:y,isSigner:!1,isWritable:!0},{pubkey:xe,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:xi,isSigner:!1,isWritable:!1},{pubkey:Gn,isSigner:!1,isWritable:!1},{pubkey:Pt,isSigner:!1,isWritable:!1}],C=Buffer.alloc(A.span);return A.encode({amountMaxA:g,amountMaxB:P,openTime:k},C),new Re({keys:T,programId:t,data:Buffer.from([...Me.initialize,...C])})}function Ci(t,e,n,i,r,o,s,a,c,u,l,m,d,p,b){let f=V([I("lpAmount"),I("amountMaxA"),I("amountMaxB")]),y=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:xe,isSigner:!1,isWritable:!1},{pubkey:An,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!0}],g=Buffer.alloc(f.span);return Jo.debug("cpmm deposit data",{lpAmount:d.toString(),amountMaxA:p.toString(),amountMaxB:b.toString()}),f.encode({lpAmount:d,amountMaxA:p,amountMaxB:b},g),new Re({keys:y,programId:t,data:Buffer.from([...Me.deposit,...g])})}function Ki(t,e,n,i,r,o,s,a,c,u,l,m,d,p,b){let f=V([I("lpAmount"),I("amountMinA"),I("amountMinB")]),y=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:xe,isSigner:!1,isWritable:!1},{pubkey:An,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:At,isSigner:!1,isWritable:!1}],g=Buffer.alloc(f.span);return f.encode({lpAmount:d,amountMinA:p,amountMinB:b},g),new Re({keys:y,programId:t,data:Buffer.from([...Me.withdraw,...g])})}function Ni(t,e,n,i,r,o,s,a,c,u,l,m,d,p,b,f){let y=V([I("amountIn"),I("amounOutMin")]),g=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!0}],P=Buffer.alloc(y.span);return y.encode({amountIn:b,amounOutMin:f},P),new Re({keys:g,programId:t,data:Buffer.from([...Me.swapBaseInput,...P])})}function Li(t,e,n,i,r,o,s,a,c,u,l,m,d,p,b,f){let y=V([I("amountInMax"),I("amountOut")]),g=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!0}],P=Buffer.alloc(y.span);return y.encode({amountInMax:b,amountOut:f},P),new Re({keys:g,programId:t,data:Buffer.from([...Me.swapBaseOutput,...P])})}async function Ri(t){var f;let{ownerInfo:e,poolInfo:n,poolKeys:i,getEphemeralSigners:r}=t,o=[],[s,a]=[new lt(n.id),new lt(n.lpMint.address)],c;if(r)c=new lt((await r(1))[0]);else{let y=Zo.generate();o.push(y),c=y.publicKey}let{publicKey:u}=be(e.feePayer,c,xe),{publicKey:l}=bn(c),{publicKey:m}=vt(t.lockProgram,c),{publicKey:d}=be(e.feePayer,a,xe),{publicKey:p}=be(t.lockAuthProgram,a,xe),b=$o({programId:t.lockProgram,auth:t.lockAuthProgram,payer:e.feePayer,nftOwner:e.feePayer,liquidityOwner:e.feePayer,nftMint:c,nftAccount:u,poolId:s,lockPda:m,mintLp:a,userLpVault:d,lockLpVault:p,poolVaultA:new lt(i.vault.A),poolVaultB:new lt(i.vault.B),metadataAccount:l,lpAmount:t.lpAmount,withMetadata:(f=t.withMetadata)!=null?f:!0});return{address:{nftMint:c,nftAccount:u,metadataAccount:l,lockPda:m,userLpVault:d,lockLpVault:p},instructions:[b],signers:o,instructionTypes:[re.CpmmLockLp],lookupTableAddress:[]}}function $o({programId:t,auth:e,payer:n,liquidityOwner:i,nftOwner:r,nftMint:o,nftAccount:s,poolId:a,lockPda:c,mintLp:u,userLpVault:l,lockLpVault:m,poolVaultA:d,poolVaultB:p,metadataAccount:b,lpAmount:f,withMetadata:y}){let g=[{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!0},{pubkey:i,isSigner:!0,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!0,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!0},{pubkey:Pt,isSigner:!1,isWritable:!1},{pubkey:Qo.programId,isSigner:!1,isWritable:!1},{pubkey:xe,isSigner:!1,isWritable:!1},{pubkey:xi,isSigner:!1,isWritable:!1},{pubkey:De,isSigner:!1,isWritable:!1}],P=V([I("lpAmount"),Ne("withMetadata")]),k=Buffer.alloc(P.span);P.encode({lpAmount:f,withMetadata:y},k);let A=Buffer.from([...Me.lockCpLiquidity,...k]);return new Re({keys:g,programId:t,data:A})}function Mi({programId:t,nftOwner:e,auth:n,nftAccount:i,lockPda:r,poolId:o,mintLp:s,userVaultA:a,userVaultB:c,poolVaultA:u,poolVaultB:l,mintA:m,mintB:d,lockLpVault:p,lpFeeAmount:b,cpmmProgram:f,cpmmAuthProgram:y}){let g=[{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:f!=null?f:$n,isSigner:!1,isWritable:!1},{pubkey:y!=null?y:ei,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:xe,isSigner:!1,isWritable:!1},{pubkey:An,isSigner:!1,isWritable:!1},{pubkey:At,isSigner:!1,isWritable:!1}],P=V([I("lpFeeAmount")]),k=Buffer.alloc(P.span);P.encode({lpFeeAmount:b},k);let A=Buffer.from([...Me.collectCpFee,...k]);return new Re({keys:g,programId:t,data:A})}var Oi=V([ne(8),z("bump"),Ne("disableCreatePool"),Ke("index"),I("tradeFeeRate"),I("protocolFeeRate"),I("fundFeeRate"),I("createPoolFee"),O("protocolOwner"),O("fundOwner"),X(I(),16)]),Ei=V([ne(8),O("configId"),O("poolCreator"),O("vaultA"),O("vaultB"),O("mintLp"),O("mintA"),O("mintB"),O("mintProgramA"),O("mintProgramB"),O("observationId"),z("bump"),z("status"),z("lpDecimals"),z("mintDecimalA"),z("mintDecimalB"),I("lpAmount"),I("protocolFeesMintA"),I("protocolFeesMintB"),I("fundFeesMintA"),I("fundFeesMintB"),I("openTime"),X(I(),32)]);var Pn=class extends Ve{constructor(e){super(e)}async load(){this.checkDisabled()}async getCpmmPoolKeys(e){return(await this.scope.api.fetchPoolKeysById({idList:[e]}))[0]}async getRpcPoolInfo(e,n){return(await this.getRpcPoolInfos([e],n))[e]}async getRpcPoolInfos(e,n){let i=await Se(this.scope.connection,e.map(m=>({pubkey:new B(m)}))),r={},o=new Set,s=[];for(let m=0;m<e.length;m++){let d=i[m];if(d.accountInfo===null)throw Error("fetch pool info error: "+String(e[m]));let p=Ei.decode(d.accountInfo.data);r[String(e[m])]={...p,programId:d.accountInfo.owner},o.add(String(p.configId)),s.push(p.vaultA,p.vaultB)}let a={};if(n){let m=[...o],d=await Se(this.scope.connection,m.map(p=>({pubkey:new B(p)})));for(let p=0;p<m.length;p++){let b=d[p].accountInfo;if(b===null)throw Error("fetch pool config error: "+m[p]);a[m[p]]=Oi.decode(b.data)}}let c={},u=await Se(this.scope.connection,s.map(m=>({pubkey:new B(m)})));for(let m=0;m<s.length;m++){let d=u[m].accountInfo;if(d===null)throw Error("fetch vault info error: "+s[m]);c[String(s[m])]=new Z(es.decode(d.data).amount.toString())}let l={};for(let[m,d]of Object.entries(r)){let p=c[d.vaultA.toString()].sub(d.protocolFeesMintA).sub(d.fundFeesMintA),b=c[d.vaultB.toString()].sub(d.protocolFeesMintB).sub(d.fundFeesMintB);l[m]={...d,baseReserve:p,quoteReserve:b,vaultAAmount:c[d.vaultA.toString()],vaultBAmount:c[d.vaultB.toString()],configInfo:a[d.configId.toString()],poolPrice:new J(b.toString()).div(new J(10).pow(d.mintDecimalB)).div(new J(p.toString()).div(new J(10).pow(d.mintDecimalA)))}}return l}toComputePoolInfos({pools:e,mintInfos:n}){return Object.keys(e).reduce((i,r)=>{var c,u,l,m;let o=e[r],[s,a]=[o.mintA.toBase58(),o.mintB.toBase58()];return{...i,[r]:{...o,id:new B(r),configInfo:o.configInfo,version:7,authority:Ft(o.programId).publicKey,mintA:Le({address:s,decimals:o.mintDecimalA,programId:o.mintProgramA.toBase58(),extensions:{feeConfig:(c=n[s])!=null&&c.feeConfig?Ue((u=n[s])==null?void 0:u.feeConfig):void 0},network:this.network}),mintB:Le({address:a,decimals:o.mintDecimalB,programId:o.mintProgramB.toBase58(),extensions:{feeConfig:(l=n[a])!=null&&l.feeConfig?Ue((m=n[a])==null?void 0:m.feeConfig):void 0},network:this.network})}}},{})}async getPoolInfoFromRpc(e){let n=await this.getRpcPoolInfo(e,!0),i=await Qt({connection:this.scope.connection,mints:[n.mintA,n.mintB],network:this.network}),r=Le({address:n.mintA.toBase58(),decimals:n.mintDecimalA,programId:n.mintProgramA.toBase58(),extensions:{feeConfig:i[n.mintA.toBase58()].feeConfig?Ue(i[n.mintA.toBase58()].feeConfig):void 0},network:this.network}),o=Le({address:n.mintB.toBase58(),decimals:n.mintDecimalB,programId:n.mintProgramB.toBase58(),extensions:{feeConfig:i[n.mintB.toBase58()].feeConfig?Ue(i[n.mintB.toBase58()].feeConfig):void 0},network:this.network}),s=Le({address:n.mintLp.toBase58(),decimals:n.lpDecimals,programId:me.toBase58(),network:this.network}),a={id:n.configId.toBase58(),index:n.configInfo.index,protocolFeeRate:n.configInfo.protocolFeeRate.toNumber(),tradeFeeRate:n.configInfo.tradeFeeRate.toNumber(),fundFeeRate:n.configInfo.fundFeeRate.toNumber(),createPoolFee:n.configInfo.createPoolFee.toString()},c={volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[]};return{poolInfo:{programId:n.programId.toBase58(),id:e,type:"Standard",lpMint:s,lpPrice:0,lpAmount:n.lpAmount.toNumber(),config:a,mintA:r,mintB:o,rewardDefaultInfos:[],rewardDefaultPoolInfos:"Ecosystem",price:n.poolPrice.toNumber(),mintAmountA:new J(n.vaultAAmount.toString()).div(10**r.decimals).toNumber(),mintAmountB:new J(n.vaultBAmount.toString()).div(10**o.decimals).toNumber(),feeRate:n.configInfo.tradeFeeRate.toNumber(),openTime:n.openTime.toString(),tvl:0,burnPercent:0,day:c,week:c,month:c,pooltype:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0},poolKeys:{programId:n.programId.toBase58(),id:e,mintA:r,mintB:o,openTime:n.openTime.toString(),vault:{A:n.vaultA.toBase58(),B:n.vaultB.toBase58()},authority:Ft(n.programId).publicKey.toBase58(),mintLp:s,config:a,observationId:st(n.programId,new B(e)).publicKey.toBase58()},rpcData:n}}async createPool({poolId:e,programId:n,poolFeeAccount:i,startTime:r,ownerInfo:o,associatedOnly:s=!1,checkCreateATAOwner:a=!1,txVersion:c,feeConfig:u,computeBudgetConfig:l,...m}){var D,v,W;let d=o.feePayer||((D=this.scope.owner)==null?void 0:D.publicKey),p=new Z(new B(m.mintA.address).toBuffer()).lte(new Z(new B(m.mintB.address).toBuffer())),[b,f]=p?[m.mintA,m.mintB]:[m.mintB,m.mintA],[y,g]=p?[m.mintAAmount,m.mintBAmount]:[m.mintBAmount,m.mintAAmount],P=o.useSOLBalance&&b.address===qt.toBase58(),k=o.useSOLBalance&&f.address===qt.toBase58(),[A,h]=[new B(b.address),new B(f.address)],T=this.createTxBuilder(),{account:C,instructionParams:N}=await this.scope.account.getOrCreateTokenAccount({mint:A,tokenProgram:b.programId,owner:this.scope.ownerPubKey,createInfo:P?{payer:d,amount:y}:void 0,notUseTokenAccount:P,skipCloseAccount:!P,associatedOnly:P?!1:s,checkCreateATAOwner:a});T.addInstruction(N||{});let{account:_,instructionParams:q}=await this.scope.account.getOrCreateTokenAccount({mint:new B(f.address),tokenProgram:f.programId,owner:this.scope.ownerPubKey,createInfo:k?{payer:d,amount:g}:void 0,notUseTokenAccount:k,skipCloseAccount:!k,associatedOnly:k?!1:s,checkCreateATAOwner:a});if(T.addInstruction(q||{}),C===void 0||_===void 0)throw Error("you don't has some token account");let M=di({poolId:e,programId:n,configId:new B(u.id),mintA:A,mintB:h});return T.addInstruction({instructions:[Si(n,this.scope.ownerPubKey,new B(u.id),M.authority,M.poolId,A,h,M.lpMint,C,_,be(this.scope.ownerPubKey,M.lpMint).publicKey,M.vaultA,M.vaultB,i,new B((v=b.programId)!=null?v:me),new B((W=f.programId)!=null?W:me),M.observationId,y,g,r)],instructionTypes:[re.CpmmCreatePool]}),T.addCustomComputeBudget(l),T.versionBuild({txVersion:c,extInfo:{address:{...M,mintA:b,mintB:f,programId:n,poolFeeAccount:i,feeConfig:u}}})}async addLiquidity(e){let{poolInfo:n,poolKeys:i,inputAmount:r,baseIn:o,slippage:s,computeResult:a,computeBudgetConfig:c,config:u,txVersion:l}=e;this.scope.availability.addStandardPosition===!1&&this.logAndCreateError("add liquidity feature disabled in your region"),r.isZero()&&this.logAndCreateError("amounts must greater than zero","amountInA",{amountInA:r.toString()});let{account:m}=this.scope,{bypassAssociatedCheck:d,checkCreateATAOwner:p}={bypassAssociatedCheck:!1,checkCreateATAOwner:!1,...u},b=a?void 0:await this.getRpcPoolInfo(n.id),{liquidity:f,inputAmountFee:y,anotherAmount:g}=a||this.computePairAmount({poolInfo:{...n,lpAmount:new J(b.lpAmount.toString()).div(10**n.lpMint.decimals).toNumber()},baseReserve:b.baseReserve,quoteReserve:b.quoteReserve,slippage:new oe(0),baseIn:o,epochInfo:await this.scope.fetchEpochInfo(),amount:new J(r.toString()).div(10**(o?n.mintA.decimals:n.mintB.decimals))}),P=g.amount,k=n.mintA.address===qt.toString(),A=n.mintB.address===qt.toString(),h=this.createTxBuilder(),[T,C]=[new B(n.mintA.address),new B(n.mintB.address)],{account:N,instructionParams:_}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n.mintA.programId,mint:new B(n.mintA.address),owner:this.scope.ownerPubKey,createInfo:k||(o?r:P).isZero()?{payer:this.scope.ownerPubKey,amount:o?r:P}:void 0,skipCloseAccount:!k,notUseTokenAccount:k,associatedOnly:!1,checkCreateATAOwner:p});h.addInstruction(_||{});let{account:q,instructionParams:M}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n.mintB.programId,mint:new B(n.mintB.address),owner:this.scope.ownerPubKey,createInfo:A||(o?P:r).isZero()?{payer:this.scope.ownerPubKey,amount:o?P:r}:void 0,skipCloseAccount:!A,notUseTokenAccount:A,associatedOnly:!1,checkCreateATAOwner:p});h.addInstruction(M||{}),!N&&!q&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",m.tokenAccounts);let D=await m.getCreatedTokenAccount({mint:new B(n.lpMint.address)}),{tokenAccount:v,...W}=await m.handleTokenAccount({side:"out",amount:0,mint:new B(n.lpMint.address),tokenAccount:D,bypassAssociatedCheck:d,checkCreateATAOwner:p});h.addInstruction(W);let U=i!=null?i:await this.getCpmmPoolKeys(n.id),F=new oe(new Z(1)).sub(s);return h.addInstruction({instructions:[Ci(new B(n.programId),this.scope.ownerPubKey,new B(U.authority),new B(n.id),v,N,q,new B(U.vault.A),new B(U.vault.B),T,C,new B(n.lpMint.address),a?a==null?void 0:a.liquidity:F.mul(f).quotient,o?y.amount:P,o?P:y.amount)],instructionTypes:[re.CpmmAddLiquidity],lookupTableAddress:U.lookupTableAccount?[U.lookupTableAccount]:[]}),h.addCustomComputeBudget(c),h.versionBuild({txVersion:l})}async withdrawLiquidity(e){var v,W;let{poolInfo:n,poolKeys:i,lpAmount:r,slippage:o,computeBudgetConfig:s,txVersion:a}=e;this.scope.availability.addStandardPosition===!1&&this.logAndCreateError("add liquidity feature disabled in your region");let c=new oe(new Z(1)).sub(o),u=await this.getRpcPoolInfo(n.id),[l,m]=[c.mul(r.mul(u.baseReserve).div(u.lpAmount)).quotient,c.mul(r.mul(u.quoteReserve).div(u.lpAmount)).quotient],d=await this.scope.fetchEpochInfo(),[p,b]=[ge(l,n.mintA.extensions.feeConfig,d,!1),ge(m,n.mintB.extensions.feeConfig,d,!1)],{account:f}=this.scope,y=this.createTxBuilder(),[g,P]=[new B(n.mintA.address),new B(n.mintB.address)],k=g.equals(ue(this.network).WSOLMint),A=P.equals(ue(this.network).WSOLMint),h,T,{account:C,instructionParams:N}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n.mintA.programId,mint:new B(n.mintA.address),notUseTokenAccount:k,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!k,associatedOnly:!k,checkCreateATAOwner:!1});h=C,N&&y.addInstruction(N);let{account:_,instructionParams:q}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n.mintB.programId,mint:new B(n.mintB.address),notUseTokenAccount:A,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!A,associatedOnly:!A,checkCreateATAOwner:!1});T=_,q&&y.addInstruction(q),(!h||!T)&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",f.tokenAccounts);let M=await f.getCreatedTokenAccount({mint:new B(n.lpMint.address)});M||this.logAndCreateError("cannot found lp token account","tokenAccounts",f.tokenAccounts);let D=i!=null?i:await this.getCpmmPoolKeys(n.id);return y.addInstruction({instructions:[Ki(new B(n.programId),this.scope.ownerPubKey,new B(D.authority),new B(n.id),M,h,T,new B(D.vault.A),new B(D.vault.B),g,P,new B(n.lpMint.address),r,l.sub((v=p.fee)!=null?v:new Z(0)),m.sub((W=b.fee)!=null?W:new Z(0)))],instructionTypes:[re.CpmmWithdrawLiquidity],lookupTableAddress:D.lookupTableAccount?[D.lookupTableAccount]:[]}),y.addCustomComputeBudget(s),y.versionBuild({txVersion:a})}async swap(e){var _,q,M,D,v,W;let{poolInfo:n,poolKeys:i,baseIn:r,fixedOut:o,inputAmount:s,swapResult:a,slippage:c=0,config:u,computeBudgetConfig:l,txVersion:m}=e,{bypassAssociatedCheck:d,checkCreateATAOwner:p,associatedOnly:b}={bypassAssociatedCheck:!1,checkCreateATAOwner:!1,associatedOnly:!0,...u},f=this.createTxBuilder(),[y,g]=[new B(n.mintA.address),new B(n.mintB.address)];o?a.sourceAmountSwapped=a.sourceAmountSwapped.mul(new Z((1+c)*1e4)).div(new Z(1e4)):a.destinationAmountSwapped=a.destinationAmountSwapped.mul(new Z((1-c)*1e4)).div(new Z(1e4));let P=n.mintA.address===ue(this.network).WSOLMint.toBase58(),k=n.mintB.address===ue(this.network).WSOLMint.toBase58(),{account:A,instructionParams:h}=await this.scope.account.getOrCreateTokenAccount({mint:y,tokenProgram:new B((_=n.mintA.programId)!=null?_:me),owner:this.scope.ownerPubKey,createInfo:P||!r?{payer:this.scope.ownerPubKey,amount:r?a.sourceAmountSwapped:0}:void 0,notUseTokenAccount:P,skipCloseAccount:!P,associatedOnly:P?!1:b,checkCreateATAOwner:p});h&&f.addInstruction(h);let{account:T,instructionParams:C}=await this.scope.account.getOrCreateTokenAccount({mint:g,tokenProgram:new B((q=n.mintB.programId)!=null?q:me),owner:this.scope.ownerPubKey,createInfo:k||r?{payer:this.scope.ownerPubKey,amount:r?0:a.sourceAmountSwapped}:void 0,notUseTokenAccount:k,skipCloseAccount:!k,associatedOnly:k?!1:b,checkCreateATAOwner:p});C&&f.addInstruction(C),(!A||!T)&&this.logAndCreateError("user do not have token account",{mintA:n.mintA.symbol||n.mintA.address,mintB:n.mintB.symbol||n.mintB.address,mintATokenAcc:A,mintBTokenAcc:T,mintAUseSOLBalance:P,mintBUseSOLBalance:k,associatedOnly:b});let N=i!=null?i:await this.getCpmmPoolKeys(n.id);return f.addInstruction({instructions:[o?Li(new B(n.programId),this.scope.ownerPubKey,new B(N.authority),new B(N.config.id),new B(n.id),r?A:T,r?T:A,new B(N.vault[r?"A":"B"]),new B(N.vault[r?"B":"A"]),new B((v=n[r?"mintA":"mintB"].programId)!=null?v:me),new B((W=n[r?"mintB":"mintA"].programId)!=null?W:me),r?y:g,r?g:y,st(new B(n.programId),new B(n.id)).publicKey,a.sourceAmountSwapped,a.destinationAmountSwapped):Ni(new B(n.programId),this.scope.ownerPubKey,new B(N.authority),new B(N.config.id),new B(n.id),r?A:T,r?T:A,new B(N.vault[r?"A":"B"]),new B(N.vault[r?"B":"A"]),new B((M=n[r?"mintA":"mintB"].programId)!=null?M:me),new B((D=n[r?"mintB":"mintA"].programId)!=null?D:me),r?y:g,r?g:y,st(new B(n.programId),new B(n.id)).publicKey,s,a.destinationAmountSwapped)],instructionTypes:[o?re.CpmmSwapBaseOut:re.ClmmSwapBaseIn]}),f.addCustomComputeBudget(l),f.versionBuild({txVersion:m})}async lockLp(e){var u,l,m,d,p;let{poolInfo:n,lpAmount:i,computeBudgetConfig:r,txVersion:o}=e;i.isZero()&&this.logAndCreateError("lpAmount must greater than zero",{lpAmount:i.toString()});let s=this.createTxBuilder(),a=(u=e.poolKeys)!=null?u:await this.getCpmmPoolKeys(n.id),c=await Ri({poolInfo:n,poolKeys:a,ownerInfo:{wallet:this.scope.ownerPubKey,feePayer:(l=e.feePayer)!=null?l:this.scope.ownerPubKey},lockProgram:(m=e.programId)!=null?m:St,lockAuthProgram:(d=e.authProgram)!=null?d:Ct,lpAmount:i,withMetadata:(p=e.withMetadata)!=null?p:!0,getEphemeralSigners:e.getEphemeralSigners});return s.addInstruction(c),s.addCustomComputeBudget(r),s.versionBuild({txVersion:o,extInfo:c.address})}async harvestLockLp(e){var q;let{poolInfo:n,lpFeeAmount:i,nftMint:r,programId:o=St,authProgram:s=Ct,cpmmProgram:a,computeBudgetConfig:c,txVersion:u}=e;i.isZero()&&this.logAndCreateError("lpFeeAmount must greater than zero",{lpAmount:i.toString()});let l=e.feePayer||this.scope.ownerPubKey,m=this.createTxBuilder(),[d,p]=[new B(n.mintA.address),new B(n.mintB.address)],b=d.equals(ue(this.network).WSOLMint),f=p.equals(ue(this.network).WSOLMint),y,g,{account:P,instructionParams:k}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n.mintA.programId,mint:new B(n.mintA.address),notUseTokenAccount:b,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!b,associatedOnly:!b,checkCreateATAOwner:!1});y=P,k&&m.addInstruction(k);let{account:A,instructionParams:h}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n.mintB.programId,mint:new B(n.mintB.address),notUseTokenAccount:f,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!f,associatedOnly:!f,checkCreateATAOwner:!1});g=A,h&&m.addInstruction(h),(!y||!g)&&this.logAndCreateError("cannot found target token accounts",{tokenAccountA:y,tokenAccountB:g});let T=(q=e.poolKeys)!=null?q:await this.getCpmmPoolKeys(n.id),{publicKey:C}=be(l,r,me),{publicKey:N}=vt(o,r),{publicKey:_}=be(s,new B(n.lpMint.address),me);return m.addInstruction({instructions:[Mi({programId:o!=null?o:St,nftOwner:this.scope.ownerPubKey,auth:s!=null?s:Ct,nftMint:r,nftAccount:C,lockPda:N,poolId:new B(n.id),mintLp:new B(T.mintLp.address),userVaultA:y,userVaultB:g,poolVaultA:new B(T.vault.A),poolVaultB:new B(T.vault.B),mintA:d,mintB:p,lockLpVault:_,lpFeeAmount:i,cpmmProgram:a==null?void 0:a.programId,cpmmAuthProgram:a==null?void 0:a.authProgram})],instructionTypes:[re.CpmmCollectLockFee]}),m.addCustomComputeBudget(c),m.versionBuild({txVersion:u})}computeSwapAmount({pool:e,amountIn:n,outputMint:i,slippage:r}){let o=i.toString()===e.mintB.address,s=_t.swap(n,o?e.baseReserve:e.quoteReserve,o?e.quoteReserve:e.baseReserve,e.configInfo.tradeFeeRate),a=new J(s.destinationAmountSwapped.toString()).div(s.sourceAmountSwapped.toString()),c=s.destinationAmountSwapped.mul(new Z((1-r)*1e4)).div(new Z(1e4));return{allTrade:s.sourceAmountSwapped.eq(n),amountIn:n,amountOut:s.destinationAmountSwapped,minAmountOut:c,executionPrice:a,fee:s.tradeFee,priceImpact:e.poolPrice.sub(a).div(e.poolPrice)}}computePairAmount({poolInfo:e,baseReserve:n,quoteReserve:i,amount:r,slippage:o,epochInfo:s,baseIn:a}){var A,h,T,C,N,_,q,M,D;let c=1-Number(o.toSignificant())/100,u=new Z(new J(r).mul(10**e[a?"mintA":"mintB"].decimals).mul(c).toFixed(0)),l=ge(u,e[a?"mintA":"mintB"].extensions.feeConfig,s,!1),m=u.sub((A=l.fee)!=null?A:new Z(0)),d=new Z(new J(e.lpAmount).mul(10**e.lpMint.decimals).toFixed(0,J.ROUND_DOWN));this.logDebug("baseReserve:",n.toString(),"quoteReserve:",i.toString()),this.logDebug("tokenIn:",a?e.mintA.symbol:e.mintB.symbol,"amountIn:",u.toString(),"amountInFee:",(T=(h=l.fee)==null?void 0:h.toString())!=null?T:0,"anotherToken:",a?e.mintB.symbol:e.mintA.symbol,"slippage:",`${o.toSignificant()}%`);let p=a?"base":"quote";this.logDebug("input side:",p);let b=m.mul(d).div(p==="base"?n:i),f={amount:nn,fee:void 0,expirationTime:void 0};if(!m.isZero()){let v=ts(b,n,i,d);this.logDebug("lpAmountData:",{amountA:v.amountA.toString(),amountB:v.amountB.toString()}),f=ge(v[a?"amountB":"amountA"],e[a?"mintB":"mintA"].extensions.feeConfig,s,!0)}let y=new oe(new Z(1)).add(o),g=new oe(new Z(1)).sub(o),P=ge(y.mul(f.amount.sub((C=f.fee)!=null?C:new Z(0))).quotient,e[a?"mintB":"mintA"].extensions.feeConfig,s,!0),k=ge(g.mul(f.amount.sub((N=f.fee)!=null?N:new Z(0))).quotient,e[a?"mintB":"mintA"].extensions.feeConfig,s,!0);return this.logDebug("anotherAmount:",f.amount.toString(),"anotherAmountFee:",(q=(_=f.fee)==null?void 0:_.toString())!=null?q:0,"maxAnotherAmount:",P.amount.toString(),"maxAnotherAmountFee:",(D=(M=P.fee)==null?void 0:M.toString())!=null?D:0),{inputAmountFee:l,anotherAmount:f,maxAnotherAmount:P,minAnotherAmount:k,liquidity:b}}};function ts(t,e,n,i){let r=t.mul(e).div(i);!r.isZero()&&!t.mul(e).mod(i).isZero()&&(r=r.add(new Z(1)));let o=t.mul(n).div(i);return!o.isZero()&&!t.mul(n).mod(i).isZero()&&(o=o.add(new Z(1))),{amountA:r,amountB:o}}export{Pn as default};
/*!
* decimal.js v10.5.0
* An arbitrary-precision Decimal type for JavaScript.
* https://github.com/MikeMcl/decimal.js
* Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
* MIT Licence
*/
//# sourceMappingURL=cpmm.mjs.map