@raydium-io/raydium-sdk-v2
Version:
An SDK for building applications on top of Raydium.
3 lines • 86 kB
JavaScript
var Hn=Object.defineProperty,jn=Object.defineProperties;var Zn=Object.getOwnPropertyDescriptors;var Ge=Object.getOwnPropertySymbols;var Jt=Object.prototype.hasOwnProperty,Xt=Object.prototype.propertyIsEnumerable;var Yt=(e,t,n)=>t in e?Hn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,q=(e,t)=>{for(var n in t||(t={}))Jt.call(t,n)&&Yt(e,n,t[n]);if(Ge)for(var n of Ge(t))Xt.call(t,n)&&Yt(e,n,t[n]);return e},ie=(e,t)=>jn(e,Zn(t));var ge=(e,t)=>{var n={};for(var r in e)Jt.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Ge)for(var r of Ge(e))t.indexOf(r)<0&&Xt.call(e,r)&&(n[r]=e[r]);return n};import{PublicKey as mt,SystemProgram as Mo}from"@solana/web3.js";import{PublicKey as Jn}from"@solana/web3.js";import{get as Qt,set as zn}from"lodash";var dt=class{constructor(t){this.logLevel=t.logLevel!==void 0?t.logLevel:0,this.name=t.name}set level(t){this.logLevel=t}get time(){return Date.now().toString()}get moduleName(){return this.name}isLogLevel(t){return t<=this.logLevel}error(...t){return this.isLogLevel(0)?(console.error(this.time,this.name,"sdk logger error",...t),this):this}logWithError(...t){let n=t.map(r=>typeof r=="object"?JSON.stringify(r):r).join(", ");throw new Error(n)}warning(...t){return this.isLogLevel(1)?(console.warn(this.time,this.name,"sdk logger warning",...t),this):this}info(...t){return this.isLogLevel(2)?(console.info(this.time,this.name,"sdk logger info",...t),this):this}debug(...t){return this.isLogLevel(3)?(console.debug(this.time,this.name,"sdk logger debug",...t),this):this}},$t={},Yn={};function Z(e){let t=Qt($t,e);if(!t){let n=Qt(Yn,e);t=new dt({name:e,logLevel:n}),zn($t,e,t)}return t}import{MINT_SIZE as Zo,TOKEN_PROGRAM_ID as zo,getTransferFeeConfig as Yo,unpackMint as Jo}from"@solana/spl-token";var ht=Z("Raydium_accountInfo_util");async function en(e,t,n){let{batchRequest:r,commitment:o="confirmed",chunkCount:i=100}=q({batchRequest:!1},n),s=gt(t,i),a=new Array(s.length).fill([]);if(r){let u=s.map(f=>{let p=e._buildArgs([f.map(m=>m.toBase58())],o,"base64");return{methodName:"getMultipleAccounts",args:p}}),c=gt(u,10);a=(await(await Promise.all(c.map(async f=>await e._rpcBatchRequest(f)))).flat()).map(f=>(f.error&&ht.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${f.error.message}`),f.result.value.map(p=>{if(p){let{data:m,executable:d,lamports:g,owner:y,rentEpoch:P}=p;return m.length!==2&&m[1]!=="base64"&&ht.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(m[0],"base64"),executable:d,lamports:g,owner:new Jn(y),rentEpoch:P}}return null})))}else try{a=await Promise.all(s.map(u=>e.getMultipleAccountsInfo(u,o)))}catch(u){u instanceof Error&&ht.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${u.message}`)}return a.flat()}import oe from"bn.js";var we=9e15,le=1e9,bt="0123456789abcdef",je="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Ze="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",yt={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-we,maxE:we,crypto:!1},on,ne,L=!0,Ye="[DecimalError] ",ue=Ye+"Invalid argument: ",sn=Ye+"Precision limit exceeded",an=Ye+"crypto unavailable",cn="[object Decimal]",z=Math.floor,H=Math.pow,Xn=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Qn=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,$n=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,un=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,X=1e7,I=7,er=9007199254740991,tr=je.length-1,wt=Ze.length-1,h={toStringTag:cn};h.absoluteValue=h.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),k(e)};h.ceil=function(){return k(new this.constructor(this),this.e+1,2)};h.clampedTo=h.clamp=function(e,t){var n,r=this,o=r.constructor;if(e=new o(e),t=new o(t),!e.s||!t.s)return new o(NaN);if(e.gt(t))throw Error(ue+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new o(r)};h.comparedTo=h.cmp=function(e){var t,n,r,o,i=this,s=i.d,a=(e=new i.constructor(e)).d,u=i.s,c=e.s;if(!s||!a)return!u||!c?NaN:u!==c?u:s===a?0:!s^u<0?1:-1;if(!s[0]||!a[0])return s[0]?u:a[0]?-c:0;if(u!==c)return u;if(i.e!==e.e)return i.e>e.e^u<0?1:-1;for(r=s.length,o=a.length,t=0,n=r<o?r:o;t<n;++t)if(s[t]!==a[t])return s[t]>a[t]^u<0?1:-1;return r===o?0:r>o^u<0?1:-1};h.cosine=h.cos=function(){var e,t,n=this,r=n.constructor;return n.d?n.d[0]?(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+I,r.rounding=1,n=nr(r,dn(r,n)),r.precision=e,r.rounding=t,k(ne==2||ne==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};h.cubeRoot=h.cbrt=function(){var e,t,n,r,o,i,s,a,u,c,l=this,f=l.constructor;if(!l.isFinite()||l.isZero())return new f(l);for(L=!1,i=l.s*H(l.s*l,1/3),!i||Math.abs(i)==1/0?(n=j(l.d),e=l.e,(i=(e-n.length+1)%3)&&(n+=i==1||i==-2?"0":"00"),i=H(n,1/3),e=z((e+1)/3)-(e%3==(e<0?-1:2)),i==1/0?n="5e"+e:(n=i.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new f(n),r.s=l.s):r=new f(i.toString()),s=(e=f.precision)+3;;)if(a=r,u=a.times(a).times(a),c=u.plus(l),r=K(c.plus(l).times(a),c.plus(u),s+2,1),j(a.d).slice(0,s)===(n=j(r.d)).slice(0,s))if(n=n.slice(s-3,s+1),n=="9999"||!o&&n=="4999"){if(!o&&(k(a,e+1,0),a.times(a).times(a).eq(l))){r=a;break}s+=4,o=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(k(r,e+1,1),t=!r.times(r).times(r).eq(l));break}return L=!0,k(r,e,f.rounding,t)};h.decimalPlaces=h.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-z(this.e/I))*I,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};h.dividedBy=h.div=function(e){return K(this,new this.constructor(e))};h.dividedToIntegerBy=h.divToInt=function(e){var t=this,n=t.constructor;return k(K(t,new n(e),0,1,1),n.precision,n.rounding)};h.equals=h.eq=function(e){return this.cmp(e)===0};h.floor=function(){return k(new this.constructor(this),this.e+1,3)};h.greaterThan=h.gt=function(e){return this.cmp(e)>0};h.greaterThanOrEqualTo=h.gte=function(e){var t=this.cmp(e);return t==1||t===0};h.hyperbolicCosine=h.cosh=function(){var e,t,n,r,o,i=this,s=i.constructor,a=new s(1);if(!i.isFinite())return new s(i.s?1/0:NaN);if(i.isZero())return a;n=s.precision,r=s.rounding,s.precision=n+Math.max(i.e,i.sd())+4,s.rounding=1,o=i.d.length,o<32?(e=Math.ceil(o/3),t=(1/Xe(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),i=Te(s,1,i.times(t),new s(1),!0);for(var u,c=e,l=new s(8);c--;)u=i.times(i),i=a.minus(u.times(l.minus(u.times(l))));return k(i,s.precision=n,s.rounding=r,!0)};h.hyperbolicSine=h.sinh=function(){var e,t,n,r,o=this,i=o.constructor;if(!o.isFinite()||o.isZero())return new i(o);if(t=i.precision,n=i.rounding,i.precision=t+Math.max(o.e,o.sd())+4,i.rounding=1,r=o.d.length,r<3)o=Te(i,2,o,o,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,o=o.times(1/Xe(5,e)),o=Te(i,2,o,o,!0);for(var s,a=new i(5),u=new i(16),c=new i(20);e--;)s=o.times(o),o=o.times(a.plus(s.times(u.times(s).plus(c))))}return i.precision=t,i.rounding=n,k(o,t,n,!0)};h.hyperbolicTangent=h.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,K(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};h.inverseCosine=h.acos=function(){var e,t=this,n=t.constructor,r=t.abs().cmp(1),o=n.precision,i=n.rounding;return r!==-1?r===0?t.isNeg()?J(n,o,i):new n(0):new n(NaN):t.isZero()?J(n,o+4,i).times(.5):(n.precision=o+6,n.rounding=1,t=t.asin(),e=J(n,o+4,i).times(.5),n.precision=o,n.rounding=i,e.minus(t))};h.inverseHyperbolicCosine=h.acosh=function(){var e,t,n=this,r=n.constructor;return n.lte(1)?new r(n.eq(1)?0:NaN):n.isFinite()?(e=r.precision,t=r.rounding,r.precision=e+Math.max(Math.abs(n.e),n.sd())+4,r.rounding=1,L=!1,n=n.times(n).minus(1).sqrt().plus(n),L=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};h.inverseHyperbolicSine=h.asinh=function(){var e,t,n=this,r=n.constructor;return!n.isFinite()||n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+2*Math.max(Math.abs(n.e),n.sd())+6,r.rounding=1,L=!1,n=n.times(n).plus(1).sqrt().plus(n),L=!0,r.precision=e,r.rounding=t,n.ln())};h.inverseHyperbolicTangent=h.atanh=function(){var e,t,n,r,o=this,i=o.constructor;return o.isFinite()?o.e>=0?new i(o.abs().eq(1)?o.s/0:o.isZero()?o:NaN):(e=i.precision,t=i.rounding,r=o.sd(),Math.max(r,e)<2*-o.e-1?k(new i(o),e,t,!0):(i.precision=n=r-o.e,o=K(o.plus(1),new i(1).minus(o),n+e,1),i.precision=e+4,i.rounding=1,o=o.ln(),i.precision=e,i.rounding=t,o.times(.5))):new i(NaN)};h.inverseSine=h.asin=function(){var e,t,n,r,o=this,i=o.constructor;return o.isZero()?new i(o):(t=o.abs().cmp(1),n=i.precision,r=i.rounding,t!==-1?t===0?(e=J(i,n+4,r).times(.5),e.s=o.s,e):new i(NaN):(i.precision=n+6,i.rounding=1,o=o.div(new i(1).minus(o.times(o)).sqrt().plus(1)).atan(),i.precision=n,i.rounding=r,o.times(2)))};h.inverseTangent=h.atan=function(){var e,t,n,r,o,i,s,a,u,c=this,l=c.constructor,f=l.precision,p=l.rounding;if(c.isFinite()){if(c.isZero())return new l(c);if(c.abs().eq(1)&&f+4<=wt)return s=J(l,f+4,p).times(.25),s.s=c.s,s}else{if(!c.s)return new l(NaN);if(f+4<=wt)return s=J(l,f+4,p).times(.5),s.s=c.s,s}for(l.precision=a=f+10,l.rounding=1,n=Math.min(28,a/I+2|0),e=n;e;--e)c=c.div(c.times(c).plus(1).sqrt().plus(1));for(L=!1,t=Math.ceil(a/I),r=1,u=c.times(c),s=new l(c),o=c;e!==-1;)if(o=o.times(u),i=s.minus(o.div(r+=2)),o=o.times(u),s=i.plus(o.div(r+=2)),s.d[t]!==void 0)for(e=t;s.d[e]===i.d[e]&&e--;);return n&&(s=s.times(2<<n-1)),L=!0,k(s,l.precision=f,l.rounding=p,!0)};h.isFinite=function(){return!!this.d};h.isInteger=h.isInt=function(){return!!this.d&&z(this.e/I)>this.d.length-2};h.isNaN=function(){return!this.s};h.isNegative=h.isNeg=function(){return this.s<0};h.isPositive=h.isPos=function(){return this.s>0};h.isZero=function(){return!!this.d&&this.d[0]===0};h.lessThan=h.lt=function(e){return this.cmp(e)<0};h.lessThanOrEqualTo=h.lte=function(e){return this.cmp(e)<1};h.logarithm=h.log=function(e){var t,n,r,o,i,s,a,u,c=this,l=c.constructor,f=l.precision,p=l.rounding,m=5;if(e==null)e=new l(10),t=!0;else{if(e=new l(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new l(NaN);t=e.eq(10)}if(n=c.d,c.s<0||!n||!n[0]||c.eq(1))return new l(n&&!n[0]?-1/0:c.s!=1?NaN:n?0:1/0);if(t)if(n.length>1)i=!0;else{for(o=n[0];o%10===0;)o/=10;i=o!==1}if(L=!1,a=f+m,s=ce(c,a),r=t?ze(l,a+10):ce(e,a),u=K(s,r,a,1),Ce(u.d,o=f,p))do if(a+=10,s=ce(c,a),r=t?ze(l,a+10):ce(e,a),u=K(s,r,a,1),!i){+j(u.d).slice(o+1,o+15)+1==1e14&&(u=k(u,f+1,0));break}while(Ce(u.d,o+=10,p));return L=!0,k(u,f,p)};h.minus=h.sub=function(e){var t,n,r,o,i,s,a,u,c,l,f,p,m=this,d=m.constructor;if(e=new d(e),!m.d||!e.d)return!m.s||!e.s?e=new d(NaN):m.d?e.s=-e.s:e=new d(e.d||m.s!==e.s?m:NaN),e;if(m.s!=e.s)return e.s=-e.s,m.plus(e);if(c=m.d,p=e.d,a=d.precision,u=d.rounding,!c[0]||!p[0]){if(p[0])e.s=-e.s;else if(c[0])e=new d(m);else return new d(u===3?-0:0);return L?k(e,a,u):e}if(n=z(e.e/I),l=z(m.e/I),c=c.slice(),i=l-n,i){for(f=i<0,f?(t=c,i=-i,s=p.length):(t=p,n=l,s=c.length),r=Math.max(Math.ceil(a/I),s)+2,i>r&&(i=r,t.length=1),t.reverse(),r=i;r--;)t.push(0);t.reverse()}else{for(r=c.length,s=p.length,f=r<s,f&&(s=r),r=0;r<s;r++)if(c[r]!=p[r]){f=c[r]<p[r];break}i=0}for(f&&(t=c,c=p,p=t,e.s=-e.s),s=c.length,r=p.length-s;r>0;--r)c[s++]=0;for(r=p.length;r>i;){if(c[--r]<p[r]){for(o=r;o&&c[--o]===0;)c[o]=X-1;--c[o],c[r]+=X}c[r]-=p[r]}for(;c[--s]===0;)c.pop();for(;c[0]===0;c.shift())--n;return c[0]?(e.d=c,e.e=Je(c,n),L?k(e,a,u):e):new d(u===3?-0:0)};h.modulo=h.mod=function(e){var t,n=this,r=n.constructor;return e=new r(e),!n.d||!e.s||e.d&&!e.d[0]?new r(NaN):!e.d||n.d&&!n.d[0]?k(new r(n),r.precision,r.rounding):(L=!1,r.modulo==9?(t=K(n,e.abs(),0,3,1),t.s*=e.s):t=K(n,e,0,r.modulo,1),t=t.times(e),L=!0,n.minus(t))};h.naturalExponential=h.exp=function(){return Tt(this)};h.naturalLogarithm=h.ln=function(){return ce(this)};h.negated=h.neg=function(){var e=new this.constructor(this);return e.s=-e.s,k(e)};h.plus=h.add=function(e){var t,n,r,o,i,s,a,u,c,l,f=this,p=f.constructor;if(e=new p(e),!f.d||!e.d)return!f.s||!e.s?e=new p(NaN):f.d||(e=new p(e.d||f.s===e.s?f:NaN)),e;if(f.s!=e.s)return e.s=-e.s,f.minus(e);if(c=f.d,l=e.d,a=p.precision,u=p.rounding,!c[0]||!l[0])return l[0]||(e=new p(f)),L?k(e,a,u):e;if(i=z(f.e/I),r=z(e.e/I),c=c.slice(),o=i-r,o){for(o<0?(n=c,o=-o,s=l.length):(n=l,r=i,s=c.length),i=Math.ceil(a/I),s=i>s?i+1:s+1,o>s&&(o=s,n.length=1),n.reverse();o--;)n.push(0);n.reverse()}for(s=c.length,o=l.length,s-o<0&&(o=s,n=l,l=c,c=n),t=0;o;)t=(c[--o]=c[o]+l[o]+t)/X|0,c[o]%=X;for(t&&(c.unshift(t),++r),s=c.length;c[--s]==0;)c.pop();return e.d=c,e.e=Je(c,r),L?k(e,a,u):e};h.precision=h.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(ue+e);return n.d?(t=ln(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};h.round=function(){var e=this,t=e.constructor;return k(new t(e),e.e+1,t.rounding)};h.sine=h.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+I,r.rounding=1,n=or(r,dn(r,n)),r.precision=e,r.rounding=t,k(ne>2?n.neg():n,e,t,!0)):new r(NaN)};h.squareRoot=h.sqrt=function(){var e,t,n,r,o,i,s=this,a=s.d,u=s.e,c=s.s,l=s.constructor;if(c!==1||!a||!a[0])return new l(!c||c<0&&(!a||a[0])?NaN:a?s:1/0);for(L=!1,c=Math.sqrt(+s),c==0||c==1/0?(t=j(a),(t.length+u)%2==0&&(t+="0"),c=Math.sqrt(t),u=z((u+1)/2)-(u<0||u%2),c==1/0?t="5e"+u:(t=c.toExponential(),t=t.slice(0,t.indexOf("e")+1)+u),r=new l(t)):r=new l(c.toString()),n=(u=l.precision)+3;;)if(i=r,r=i.plus(K(s,i,n+2,1)).times(.5),j(i.d).slice(0,n)===(t=j(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t=="9999"||!o&&t=="4999"){if(!o&&(k(i,u+1,0),i.times(i).eq(s))){r=i;break}n+=4,o=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(k(r,u+1,1),e=!r.times(r).eq(s));break}return L=!0,k(r,u,l.rounding,e)};h.tangent=h.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,n=n.sin(),n.s=1,n=K(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,k(ne==2||ne==4?n.neg():n,e,t,!0)):new r(NaN)};h.times=h.mul=function(e){var t,n,r,o,i,s,a,u,c,l=this,f=l.constructor,p=l.d,m=(e=new f(e)).d;if(e.s*=l.s,!p||!p[0]||!m||!m[0])return new f(!e.s||p&&!p[0]&&!m||m&&!m[0]&&!p?NaN:!p||!m?e.s/0:e.s*0);for(n=z(l.e/I)+z(e.e/I),u=p.length,c=m.length,u<c&&(i=p,p=m,m=i,s=u,u=c,c=s),i=[],s=u+c,r=s;r--;)i.push(0);for(r=c;--r>=0;){for(t=0,o=u+r;o>r;)a=i[o]+m[r]*p[o-r-1]+t,i[o--]=a%X|0,t=a/X|0;i[o]=(i[o]+t)%X|0}for(;!i[--s];)i.pop();return t?++n:i.shift(),e.d=i,e.e=Je(i,n),L?k(e,f.precision,f.rounding):e};h.toBinary=function(e,t){return Pt(this,2,e,t)};h.toDecimalPlaces=h.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(Y(e,0,le),t===void 0?t=r.rounding:Y(t,0,8),k(n,e+n.e+1,t))};h.toExponential=function(e,t){var n,r=this,o=r.constructor;return e===void 0?n=ee(r,!0):(Y(e,0,le),t===void 0?t=o.rounding:Y(t,0,8),r=k(new o(r),e+1,t),n=ee(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};h.toFixed=function(e,t){var n,r,o=this,i=o.constructor;return e===void 0?n=ee(o):(Y(e,0,le),t===void 0?t=i.rounding:Y(t,0,8),r=k(new i(o),e+o.e+1,t),n=ee(r,!1,e+r.e+1)),o.isNeg()&&!o.isZero()?"-"+n:n};h.toFraction=function(e){var t,n,r,o,i,s,a,u,c,l,f,p,m=this,d=m.d,g=m.constructor;if(!d)return new g(m);if(c=n=new g(1),r=u=new g(0),t=new g(r),i=t.e=ln(d)-m.e-1,s=i%I,t.d[0]=H(10,s<0?I+s:s),e==null)e=i>0?t:c;else{if(a=new g(e),!a.isInt()||a.lt(c))throw Error(ue+a);e=a.gt(t)?i>0?t:c:a}for(L=!1,a=new g(j(d)),l=g.precision,g.precision=i=d.length*I*2;f=K(a,t,0,1,1),o=n.plus(f.times(r)),o.cmp(e)!=1;)n=r,r=o,o=c,c=u.plus(f.times(o)),u=o,o=t,t=a.minus(f.times(o)),a=o;return o=K(e.minus(n),r,0,1,1),u=u.plus(o.times(c)),n=n.plus(o.times(r)),u.s=c.s=m.s,p=K(c,r,i,1).minus(m).abs().cmp(K(u,n,i,1).minus(m).abs())<1?[c,r]:[u,n],g.precision=l,L=!0,p};h.toHexadecimal=h.toHex=function(e,t){return Pt(this,16,e,t)};h.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),e==null){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),t===void 0?t=r.rounding:Y(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&(e.s=n.s),e}return e.d[0]?(L=!1,n=K(n,e,0,t,1).times(e),L=!0,k(n)):(e.s=n.s,n=e),n};h.toNumber=function(){return+this};h.toOctal=function(e,t){return Pt(this,8,e,t)};h.toPower=h.pow=function(e){var t,n,r,o,i,s,a=this,u=a.constructor,c=+(e=new u(e));if(!a.d||!e.d||!a.d[0]||!e.d[0])return new u(H(+a,c));if(a=new u(a),a.eq(1))return a;if(r=u.precision,i=u.rounding,e.eq(1))return k(a,r,i);if(t=z(e.e/I),t>=e.d.length-1&&(n=c<0?-c:c)<=er)return o=fn(u,a,n,r),e.s<0?new u(1).div(o):k(o,r,i);if(s=a.s,s<0){if(t<e.d.length-1)return new u(NaN);if((e.d[t]&1)==0&&(s=1),a.e==0&&a.d[0]==1&&a.d.length==1)return a.s=s,a}return n=H(+a,c),t=n==0||!isFinite(n)?z(c*(Math.log("0."+j(a.d))/Math.LN10+a.e+1)):new u(n+"").e,t>u.maxE+1||t<u.minE-1?new u(t>0?s/0:0):(L=!1,u.rounding=a.s=1,n=Math.min(12,(t+"").length),o=Tt(e.times(ce(a,r+n)),r),o.d&&(o=k(o,r+5,1),Ce(o.d,r,i)&&(t=r+10,o=k(Tt(e.times(ce(a,t+n)),t),t+5,1),+j(o.d).slice(r+1,r+15)+1==1e14&&(o=k(o,r+1,0)))),o.s=s,L=!0,u.rounding=i,k(o,r,i))};h.toPrecision=function(e,t){var n,r=this,o=r.constructor;return e===void 0?n=ee(r,r.e<=o.toExpNeg||r.e>=o.toExpPos):(Y(e,1,le),t===void 0?t=o.rounding:Y(t,0,8),r=k(new o(r),e,t),n=ee(r,e<=r.e||r.e<=o.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};h.toSignificantDigits=h.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(Y(e,1,le),t===void 0?t=r.rounding:Y(t,0,8)),k(new r(n),e,t)};h.toString=function(){var e=this,t=e.constructor,n=ee(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};h.truncated=h.trunc=function(){return k(new this.constructor(this),this.e+1,1)};h.valueOf=h.toJSON=function(){var e=this,t=e.constructor,n=ee(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function j(e){var t,n,r,o=e.length-1,i="",s=e[0];if(o>0){for(i+=s,t=1;t<o;t++)r=e[t]+"",n=I-r.length,n&&(i+=ae(n)),i+=r;s=e[t],r=s+"",n=I-r.length,n&&(i+=ae(n))}else if(s===0)return"0";for(;s%10===0;)s/=10;return i+s}function Y(e,t,n){if(e!==~~e||e<t||e>n)throw Error(ue+e)}function Ce(e,t,n,r){var o,i,s,a;for(i=e[0];i>=10;i/=10)--t;return--t<0?(t+=I,o=0):(o=Math.ceil((t+1)/I),t%=I),i=H(10,I-t),a=e[o]%i|0,r==null?t<3?(t==0?a=a/100|0:t==1&&(a=a/10|0),s=n<4&&a==99999||n>3&&a==49999||a==5e4||a==0):s=(n<4&&a+1==i||n>3&&a+1==i/2)&&(e[o+1]/i/100|0)==H(10,t-2)-1||(a==i/2||a==0)&&(e[o+1]/i/100|0)==0:t<4?(t==0?a=a/1e3|0:t==1?a=a/100|0:t==2&&(a=a/10|0),s=(r||n<4)&&a==9999||!r&&n>3&&a==4999):s=((r||n<4)&&a+1==i||!r&&n>3&&a+1==i/2)&&(e[o+1]/i/1e3|0)==H(10,t-3)-1,s}function He(e,t,n){for(var r,o=[0],i,s=0,a=e.length;s<a;){for(i=o.length;i--;)o[i]*=t;for(o[0]+=bt.indexOf(e.charAt(s++)),r=0;r<o.length;r++)o[r]>n-1&&(o[r+1]===void 0&&(o[r+1]=0),o[r+1]+=o[r]/n|0,o[r]%=n)}return o.reverse()}function nr(e,t){var n,r,o;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),o=(1/Xe(4,n)).toString()):(n=16,o="2.3283064365386962890625e-10"),e.precision+=n,t=Te(e,1,t.times(o),new e(1));for(var i=n;i--;){var s=t.times(t);t=s.times(s).minus(s).times(8).plus(1)}return e.precision-=n,t}var K=function(){function e(r,o,i){var s,a=0,u=r.length;for(r=r.slice();u--;)s=r[u]*o+a,r[u]=s%i|0,a=s/i|0;return a&&r.unshift(a),r}function t(r,o,i,s){var a,u;if(i!=s)u=i>s?1:-1;else for(a=u=0;a<i;a++)if(r[a]!=o[a]){u=r[a]>o[a]?1:-1;break}return u}function n(r,o,i,s){for(var a=0;i--;)r[i]-=a,a=r[i]<o[i]?1:0,r[i]=a*s+r[i]-o[i];for(;!r[0]&&r.length>1;)r.shift()}return function(r,o,i,s,a,u){var c,l,f,p,m,d,g,y,P,A,w,T,b,x,N,B,E,F,M,D,v=r.constructor,U=r.s==o.s?1:-1,O=r.d,C=o.d;if(!O||!O[0]||!C||!C[0])return new v(!r.s||!o.s||(O?C&&O[0]==C[0]:!C)?NaN:O&&O[0]==0||!C?U*0:U/0);for(u?(m=1,l=r.e-o.e):(u=X,m=I,l=z(r.e/m)-z(o.e/m)),M=C.length,E=O.length,P=new v(U),A=P.d=[],f=0;C[f]==(O[f]||0);f++);if(C[f]>(O[f]||0)&&l--,i==null?(x=i=v.precision,s=v.rounding):a?x=i+(r.e-o.e)+1:x=i,x<0)A.push(1),d=!0;else{if(x=x/m+2|0,f=0,M==1){for(p=0,C=C[0],x++;(f<E||p)&&x--;f++)N=p*u+(O[f]||0),A[f]=N/C|0,p=N%C|0;d=p||f<E}else{for(p=u/(C[0]+1)|0,p>1&&(C=e(C,p,u),O=e(O,p,u),M=C.length,E=O.length),B=M,w=O.slice(0,M),T=w.length;T<M;)w[T++]=0;D=C.slice(),D.unshift(0),F=C[0],C[1]>=u/2&&++F;do p=0,c=t(C,w,M,T),c<0?(b=w[0],M!=T&&(b=b*u+(w[1]||0)),p=b/F|0,p>1?(p>=u&&(p=u-1),g=e(C,p,u),y=g.length,T=w.length,c=t(g,w,y,T),c==1&&(p--,n(g,M<y?D:C,y,u))):(p==0&&(c=p=1),g=C.slice()),y=g.length,y<T&&g.unshift(0),n(w,g,T,u),c==-1&&(T=w.length,c=t(C,w,M,T),c<1&&(p++,n(w,M<T?D:C,T,u))),T=w.length):c===0&&(p++,w=[0]),A[f++]=p,c&&w[0]?w[T++]=O[B]||0:(w=[O[B]],T=1);while((B++<E||w[0]!==void 0)&&x--);d=w[0]!==void 0}A[0]||A.shift()}if(m==1)P.e=l,on=d;else{for(f=1,p=A[0];p>=10;p/=10)f++;P.e=f+l*m-1,k(P,a?i+P.e+1:i,s,d)}return P}}();function k(e,t,n,r){var o,i,s,a,u,c,l,f,p,m=e.constructor;e:if(t!=null){if(f=e.d,!f)return e;for(o=1,a=f[0];a>=10;a/=10)o++;if(i=t-o,i<0)i+=I,s=t,l=f[p=0],u=l/H(10,o-s-1)%10|0;else if(p=Math.ceil((i+1)/I),a=f.length,p>=a)if(r){for(;a++<=p;)f.push(0);l=u=0,o=1,i%=I,s=i-I+1}else break e;else{for(l=a=f[p],o=1;a>=10;a/=10)o++;i%=I,s=i-I+o,u=s<0?0:l/H(10,o-s-1)%10|0}if(r=r||t<0||f[p+1]!==void 0||(s<0?l:l%H(10,o-s-1)),c=n<4?(u||r)&&(n==0||n==(e.s<0?3:2)):u>5||u==5&&(n==4||r||n==6&&(i>0?s>0?l/H(10,o-s):0:f[p-1])%10&1||n==(e.s<0?8:7)),t<1||!f[0])return f.length=0,c?(t-=e.e+1,f[0]=H(10,(I-t%I)%I),e.e=-t||0):f[0]=e.e=0,e;if(i==0?(f.length=p,a=1,p--):(f.length=p+1,a=H(10,I-i),f[p]=s>0?(l/H(10,o-s)%H(10,s)|0)*a:0),c)for(;;)if(p==0){for(i=1,s=f[0];s>=10;s/=10)i++;for(s=f[0]+=a,a=1;s>=10;s/=10)a++;i!=a&&(e.e++,f[0]==X&&(f[0]=1));break}else{if(f[p]+=a,f[p]!=X)break;f[p--]=0,a=1}for(i=f.length;f[--i]===0;)f.pop()}return L&&(e.e>m.maxE?(e.d=null,e.e=NaN):e.e<m.minE&&(e.e=0,e.d=[0])),e}function ee(e,t,n){if(!e.isFinite())return mn(e);var r,o=e.e,i=j(e.d),s=i.length;return t?(n&&(r=n-s)>0?i=i.charAt(0)+"."+i.slice(1)+ae(r):s>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(e.e<0?"e":"e+")+e.e):o<0?(i="0."+ae(-o-1)+i,n&&(r=n-s)>0&&(i+=ae(r))):o>=s?(i+=ae(o+1-s),n&&(r=n-o-1)>0&&(i=i+"."+ae(r))):((r=o+1)<s&&(i=i.slice(0,r)+"."+i.slice(r)),n&&(r=n-s)>0&&(o+1===s&&(i+="."),i+=ae(r))),i}function Je(e,t){var n=e[0];for(t*=I;n>=10;n/=10)t++;return t}function ze(e,t,n){if(t>tr)throw L=!0,n&&(e.precision=n),Error(sn);return k(new e(je),t,1,!0)}function J(e,t,n){if(t>wt)throw Error(sn);return k(new e(Ze),t,n,!0)}function ln(e){var t=e.length-1,n=t*I+1;if(t=e[t],t){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}function ae(e){for(var t="";e--;)t+="0";return t}function fn(e,t,n,r){var o,i=new e(1),s=Math.ceil(r/I+4);for(L=!1;;){if(n%2&&(i=i.times(t),nn(i.d,s)&&(o=!0)),n=z(n/2),n===0){n=i.d.length-1,o&&i.d[n]===0&&++i.d[n];break}t=t.times(t),nn(t.d,s)}return L=!0,i}function tn(e){return e.d[e.d.length-1]&1}function pn(e,t,n){for(var r,o=new e(t[0]),i=0;++i<t.length;)if(r=new e(t[i]),r.s)o[n](r)&&(o=r);else{o=r;break}return o}function Tt(e,t){var n,r,o,i,s,a,u,c=0,l=0,f=0,p=e.constructor,m=p.rounding,d=p.precision;if(!e.d||!e.d[0]||e.e>17)return new p(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:0/0);for(t==null?(L=!1,u=d):u=t,a=new p(.03125);e.e>-2;)e=e.times(a),f+=5;for(r=Math.log(H(2,f))/Math.LN10*2+5|0,u+=r,n=i=s=new p(1),p.precision=u;;){if(i=k(i.times(e),u,1),n=n.times(++l),a=s.plus(K(i,n,u,1)),j(a.d).slice(0,u)===j(s.d).slice(0,u)){for(o=f;o--;)s=k(s.times(s),u,1);if(t==null)if(c<3&&Ce(s.d,u-r,m,c))p.precision=u+=10,n=i=a=new p(1),l=0,c++;else return k(s,p.precision=d,m,L=!0);else return p.precision=d,s}s=a}}function ce(e,t){var n,r,o,i,s,a,u,c,l,f,p,m=1,d=10,g=e,y=g.d,P=g.constructor,A=P.rounding,w=P.precision;if(g.s<0||!y||!y[0]||!g.e&&y[0]==1&&y.length==1)return new P(y&&!y[0]?-1/0:g.s!=1?NaN:y?0:g);if(t==null?(L=!1,l=w):l=t,P.precision=l+=d,n=j(y),r=n.charAt(0),Math.abs(i=g.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)g=g.times(e),n=j(g.d),r=n.charAt(0),m++;i=g.e,r>1?(g=new P("0."+n),i++):g=new P(r+"."+n.slice(1))}else return c=ze(P,l+2,w).times(i+""),g=ce(new P(r+"."+n.slice(1)),l-d).plus(c),P.precision=w,t==null?k(g,w,A,L=!0):g;for(f=g,u=s=g=K(g.minus(1),g.plus(1),l,1),p=k(g.times(g),l,1),o=3;;){if(s=k(s.times(p),l,1),c=u.plus(K(s,new P(o),l,1)),j(c.d).slice(0,l)===j(u.d).slice(0,l))if(u=u.times(2),i!==0&&(u=u.plus(ze(P,l+2,w).times(i+""))),u=K(u,new P(m),l,1),t==null)if(Ce(u.d,l-d,A,a))P.precision=l+=d,c=s=g=K(f.minus(1),f.plus(1),l,1),p=k(g.times(g),l,1),o=a=1;else return k(u,P.precision=w,A,L=!0);else return P.precision=w,u;u=c,o+=2}}function mn(e){return String(e.s*e.s/0)}function xt(e,t){var n,r,o;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;r++);for(o=t.length;t.charCodeAt(o-1)===48;--o);if(t=t.slice(r,o),t){if(o-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%I,n<0&&(r+=I),r<o){for(r&&e.d.push(+t.slice(0,r)),o-=I;r<o;)e.d.push(+t.slice(r,r+=I));t=t.slice(r),r=I-t.length}else r-=o;for(;r--;)t+="0";e.d.push(+t),L&&(e.e>e.constructor.maxE?(e.d=null,e.e=NaN):e.e<e.constructor.minE&&(e.e=0,e.d=[0]))}else e.e=0,e.d=[0];return e}function rr(e,t){var n,r,o,i,s,a,u,c,l;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),un.test(t))return xt(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(Qn.test(t))n=16,t=t.toLowerCase();else if(Xn.test(t))n=2;else if($n.test(t))n=8;else throw Error(ue+t);for(i=t.search(/p/i),i>0?(u=+t.slice(i+1),t=t.substring(2,i)):t=t.slice(2),i=t.indexOf("."),s=i>=0,r=e.constructor,s&&(t=t.replace(".",""),a=t.length,i=a-i,o=fn(r,new r(n),i,i*2)),c=He(t,n,X),l=c.length-1,i=l;c[i]===0;--i)c.pop();return i<0?new r(e.s*0):(e.e=Je(c,l),e.d=c,L=!1,s&&(e=K(e,o,a*4)),u&&(e=e.times(Math.abs(u)<54?H(2,u):Qe.pow(2,u))),L=!0,e)}function or(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:Te(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/Xe(5,n)),t=Te(e,2,t,t);for(var o,i=new e(5),s=new e(16),a=new e(20);n--;)o=t.times(t),t=t.times(i.plus(o.times(s.times(o).minus(a))));return t}function Te(e,t,n,r,o){var i,s,a,u,c=1,l=e.precision,f=Math.ceil(l/I);for(L=!1,u=n.times(n),a=new e(r);;){if(s=K(a.times(u),new e(t++*t++),l,1),a=o?r.plus(s):r.minus(s),r=K(s.times(u),new e(t++*t++),l,1),s=a.plus(r),s.d[f]!==void 0){for(i=f;s.d[i]===a.d[i]&&i--;);if(i==-1)break}i=a,a=r,r=s,s=i,c++}return L=!0,s.d.length=f+1,s}function Xe(e,t){for(var n=e;--t;)n*=e;return n}function dn(e,t){var n,r=t.s<0,o=J(e,e.precision,1),i=o.times(.5);if(t=t.abs(),t.lte(i))return ne=r?4:1,t;if(n=t.divToInt(o),n.isZero())ne=r?3:2;else{if(t=t.minus(n.times(o)),t.lte(i))return ne=tn(n)?r?2:3:r?4:1,t;ne=tn(n)?r?1:4:r?3:2}return t.minus(o).abs()}function Pt(e,t,n,r){var o,i,s,a,u,c,l,f,p,m=e.constructor,d=n!==void 0;if(d?(Y(n,1,le),r===void 0?r=m.rounding:Y(r,0,8)):(n=m.precision,r=m.rounding),!e.isFinite())l=mn(e);else{for(l=ee(e),s=l.indexOf("."),d?(o=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):o=t,s>=0&&(l=l.replace(".",""),p=new m(1),p.e=l.length-s,p.d=He(ee(p),10,o),p.e=p.d.length),f=He(l,10,o),i=u=f.length;f[--u]==0;)f.pop();if(!f[0])l=d?"0p+0":"0";else{if(s<0?i--:(e=new m(e),e.d=f,e.e=i,e=K(e,p,n,r,0,o),f=e.d,i=e.e,c=on),s=f[n],a=o/2,c=c||f[n+1]!==void 0,c=r<4?(s!==void 0||c)&&(r===0||r===(e.s<0?3:2)):s>a||s===a&&(r===4||c||r===6&&f[n-1]&1||r===(e.s<0?8:7)),f.length=n,c)for(;++f[--n]>o-1;)f[n]=0,n||(++i,f.unshift(1));for(u=f.length;!f[u-1];--u);for(s=0,l="";s<u;s++)l+=bt.charAt(f[s]);if(d){if(u>1)if(t==16||t==8){for(s=t==16?4:3,--u;u%s;u++)l+="0";for(f=He(l,o,t),u=f.length;!f[u-1];--u);for(s=1,l="1.";s<u;s++)l+=bt.charAt(f[s])}else l=l.charAt(0)+"."+l.slice(1);l=l+(i<0?"p":"p+")+i}else if(i<0){for(;++i;)l="0"+l;l="0."+l}else if(++i>u)for(i-=u;i--;)l+="0";else i<u&&(l=l.slice(0,i)+"."+l.slice(i))}l=(t==16?"0x":t==2?"0b":t==8?"0o":"")+l}return e.s<0?"-"+l:l}function nn(e,t){if(e.length>t)return e.length=t,!0}function ir(e){return new this(e).abs()}function sr(e){return new this(e).acos()}function ar(e){return new this(e).acosh()}function cr(e,t){return new this(e).plus(t)}function ur(e){return new this(e).asin()}function lr(e){return new this(e).asinh()}function fr(e){return new this(e).atan()}function pr(e){return new this(e).atanh()}function mr(e,t){e=new this(e),t=new this(t);var n,r=this.precision,o=this.rounding,i=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=J(this,i,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?J(this,r,o):new this(0),n.s=e.s):!e.d||t.isZero()?(n=J(this,i,1).times(.5),n.s=e.s):t.s<0?(this.precision=i,this.rounding=1,n=this.atan(K(e,t,i,1)),t=J(this,i,1),this.precision=r,this.rounding=o,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(K(e,t,i,1)),n}function dr(e){return new this(e).cbrt()}function hr(e){return k(e=new this(e),e.e+1,2)}function gr(e,t,n){return new this(e).clamp(t,n)}function br(e){if(!e||typeof e!="object")throw Error(Ye+"Object expected");var t,n,r,o=e.defaults===!0,i=["precision",1,le,"rounding",0,8,"toExpNeg",-we,0,"toExpPos",0,we,"maxE",0,we,"minE",-we,0,"modulo",0,9];for(t=0;t<i.length;t+=3)if(n=i[t],o&&(this[n]=yt[n]),(r=e[n])!==void 0)if(z(r)===r&&r>=i[t+1]&&r<=i[t+2])this[n]=r;else throw Error(ue+n+": "+r);if(n="crypto",o&&(this[n]=yt[n]),(r=e[n])!==void 0)if(r===!0||r===!1||r===0||r===1)if(r)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[n]=!0;else throw Error(an);else this[n]=!1;else throw Error(ue+n+": "+r);return this}function yr(e){return new this(e).cos()}function wr(e){return new this(e).cosh()}function hn(e){var t,n,r;function o(i){var s,a,u,c=this;if(!(c instanceof o))return new o(i);if(c.constructor=o,rn(i)){c.s=i.s,L?!i.d||i.e>o.maxE?(c.e=NaN,c.d=null):i.e<o.minE?(c.e=0,c.d=[0]):(c.e=i.e,c.d=i.d.slice()):(c.e=i.e,c.d=i.d?i.d.slice():i.d);return}if(u=typeof i,u==="number"){if(i===0){c.s=1/i<0?-1:1,c.e=0,c.d=[0];return}if(i<0?(i=-i,c.s=-1):c.s=1,i===~~i&&i<1e7){for(s=0,a=i;a>=10;a/=10)s++;L?s>o.maxE?(c.e=NaN,c.d=null):s<o.minE?(c.e=0,c.d=[0]):(c.e=s,c.d=[i]):(c.e=s,c.d=[i]);return}else if(i*0!==0){i||(c.s=NaN),c.e=NaN,c.d=null;return}return xt(c,i.toString())}else if(u!=="string")throw Error(ue+i);return(a=i.charCodeAt(0))===45?(i=i.slice(1),c.s=-1):(a===43&&(i=i.slice(1)),c.s=1),un.test(i)?xt(c,i):rr(c,i)}if(o.prototype=h,o.ROUND_UP=0,o.ROUND_DOWN=1,o.ROUND_CEIL=2,o.ROUND_FLOOR=3,o.ROUND_HALF_UP=4,o.ROUND_HALF_DOWN=5,o.ROUND_HALF_EVEN=6,o.ROUND_HALF_CEIL=7,o.ROUND_HALF_FLOOR=8,o.EUCLID=9,o.config=o.set=br,o.clone=hn,o.isDecimal=rn,o.abs=ir,o.acos=sr,o.acosh=ar,o.add=cr,o.asin=ur,o.asinh=lr,o.atan=fr,o.atanh=pr,o.atan2=mr,o.cbrt=dr,o.ceil=hr,o.clamp=gr,o.cos=yr,o.cosh=wr,o.div=Tr,o.exp=xr,o.floor=Pr,o.hypot=Ar,o.ln=kr,o.log=Sr,o.log10=Br,o.log2=Ir,o.max=Lr,o.min=Cr,o.mod=Nr,o.mul=_r,o.pow=Rr,o.random=Er,o.round=Dr,o.sign=Mr,o.sin=vr,o.sinh=Fr,o.sqrt=Or,o.sub=Kr,o.sum=Ur,o.tan=Vr,o.tanh=Wr,o.trunc=qr,e===void 0&&(e={}),e&&e.defaults!==!0)for(r=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return o.config(e),o}function Tr(e,t){return new this(e).div(t)}function xr(e){return new this(e).exp()}function Pr(e){return k(e=new this(e),e.e+1,3)}function Ar(){var e,t,n=new this(0);for(L=!1,e=0;e<arguments.length;)if(t=new this(arguments[e++]),t.d)n.d&&(n=n.plus(t.times(t)));else{if(t.s)return L=!0,new this(1/0);n=t}return L=!0,n.sqrt()}function rn(e){return e instanceof Qe||e&&e.toStringTag===cn||!1}function kr(e){return new this(e).ln()}function Sr(e,t){return new this(e).log(t)}function Ir(e){return new this(e).log(2)}function Br(e){return new this(e).log(10)}function Lr(){return pn(this,arguments,"lt")}function Cr(){return pn(this,arguments,"gt")}function Nr(e,t){return new this(e).mod(t)}function _r(e,t){return new this(e).mul(t)}function Rr(e,t){return new this(e).pow(t)}function Er(e){var t,n,r,o,i=0,s=new this(1),a=[];if(e===void 0?e=this.precision:Y(e,1,le),r=Math.ceil(e/I),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(r));i<r;)o=t[i],o>=429e7?t[i]=crypto.getRandomValues(new Uint32Array(1))[0]:a[i++]=o%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);i<r;)o=t[i]+(t[i+1]<<8)+(t[i+2]<<16)+((t[i+3]&127)<<24),o>=214e7?crypto.randomBytes(4).copy(t,i):(a.push(o%1e7),i+=4);i=r/4}else throw Error(an);else for(;i<r;)a[i++]=Math.random()*1e7|0;for(r=a[--i],e%=I,r&&e&&(o=H(10,I-e),a[i]=(r/o|0)*o);a[i]===0;i--)a.pop();if(i<0)n=0,a=[0];else{for(n=-1;a[0]===0;n-=I)a.shift();for(r=1,o=a[0];o>=10;o/=10)r++;r<I&&(n-=I-r)}return s.e=n,s.d=a,s}function Dr(e){return k(e=new this(e),e.e+1,this.rounding)}function Mr(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function vr(e){return new this(e).sin()}function Fr(e){return new this(e).sinh()}function Or(e){return new this(e).sqrt()}function Kr(e,t){return new this(e).sub(t)}function Ur(){var e=0,t=arguments,n=new this(t[e]);for(L=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return L=!0,k(n,this.precision,this.rounding)}function Vr(e){return new this(e).tan()}function Wr(e){return new this(e).tanh()}function qr(e){return k(e=new this(e),e.e+1,1)}h[Symbol.for("nodejs.util.inspect.custom")]=h.toString;h[Symbol.toStringTag]="Decimal";var Qe=h.constructor=hn(yt);je=new Qe(je);Ze=new Qe(Ze);import Xr from"big.js";import hi from"bn.js";import Gr from"toformat";var Hr=Gr,Ne=Hr;import et from"big.js";import Zr from"bn.js";import zr from"decimal.js-light";import _e from"bn.js";var gn=9007199254740991;function Q(e){let t=Z("Raydium_parseBigNumberish");if(e instanceof _e)return e;if(typeof e=="string"){if(e.match(/^-?[0-9]+$/))return new _e(e);t.logWithError(`invalid BigNumberish string: ${e}`)}return typeof e=="number"?(e%1&&t.logWithError(`BigNumberish number underflow: ${e}`),(e>=gn||e<=-gn)&&t.logWithError(`BigNumberish number overflow: ${e}`),new _e(String(e))):typeof e=="bigint"?new _e(e.toString()):(t.error(`invalid BigNumberish value: ${e}`),new _e(0))}var $e=Z("module/fraction"),At=Ne(et),Re=Ne(zr),Yr={[0]:Re.ROUND_DOWN,[1]:Re.ROUND_HALF_UP,[2]:Re.ROUND_UP},Jr={[0]:et.roundDown,[1]:et.roundHalfUp,[2]:et.roundUp},V=class{constructor(t,n=new Zr(1)){this.numerator=Q(t),this.denominator=Q(n)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new V(this.denominator,this.numerator)}add(t){let n=t instanceof V?t:new V(Q(t));return this.denominator.eq(n.denominator)?new V(this.numerator.add(n.numerator),this.denominator):new V(this.numerator.mul(n.denominator).add(n.numerator.mul(this.denominator)),this.denominator.mul(n.denominator))}sub(t){let n=t instanceof V?t:new V(Q(t));return this.denominator.eq(n.denominator)?new V(this.numerator.sub(n.numerator),this.denominator):new V(this.numerator.mul(n.denominator).sub(n.numerator.mul(this.denominator)),this.denominator.mul(n.denominator))}mul(t){let n=t instanceof V?t:new V(Q(t));return new V(this.numerator.mul(n.numerator),this.denominator.mul(n.denominator))}div(t){let n=t instanceof V?t:new V(Q(t));return new V(this.numerator.mul(n.denominator),this.denominator.mul(n.numerator))}toSignificant(t,n={groupSeparator:""},r=1){Number.isInteger(t)||$e.logWithError(`${t} is not an integer.`),t<=0&&$e.logWithError(`${t} is not positive.`),Re.set({precision:t+1,rounding:Yr[r]});let o=new Re(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(t);return o.toFormat(o.decimalPlaces(),n)}toFixed(t,n={groupSeparator:""},r=1){return Number.isInteger(t)||$e.logWithError(`${t} is not an integer.`),t<0&&$e.logWithError(`${t} is negative.`),At.DP=t,At.RM=Jr[r]||1,new At(this.numerator.toString()).div(this.denominator.toString()).toFormat(t,n)}isZero(){return this.numerator.isZero()}};var ki=Z("Raydium_amount"),Si=Ne(Xr);import{PublicKey as $r}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as bn}from"@solana/spl-token";var yn={chainId:101,address:$r.default.toBase58(),programId:bn.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}},re={chainId:101,address:"So11111111111111111111111111111111111111112",programId:bn.toBase58(),decimals:9,symbol:"WSOL",name:"Wrapped SOL",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}};import{PublicKey as St}from"@solana/web3.js";import{PublicKey as W,SystemProgram as wn,SYSVAR_RENT_PUBKEY as eo}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as to}from"@solana/spl-token";function kt({pubkey:e,isSigner:t=!1,isWritable:n=!0}){return{pubkey:e,isWritable:n,isSigner:t}}var Ei=[kt({pubkey:to,isWritable:!1}),kt({pubkey:wn.programId,isWritable:!1}),kt({pubkey:eo,isWritable:!1})];function Tn({publicKey:e,transformSol:t}){let n=xn(e.toString());if(n instanceof W)return t&&n.equals(Ee)?se:n;if(t&&n.toString()===Ee.toBase58())return se;if(typeof n=="string"){if(n===W.default.toBase58())return W.default;try{return new W(n)}catch{throw new Error("invalid public key")}}throw new Error("invalid public key")}function xn(e){try{return new W(e)}catch{return e}}var Di=new W("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Mi=new W("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),vi=new W("SysvarRent111111111111111111111111111111111"),Fi=new W("SysvarC1ock11111111111111111111111111111111"),Oi=new W("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Ki=new W("Sysvar1nstructions1111111111111111111111111"),Ui=wn.programId,Vi=new W("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Wi=new W("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),qi=new W("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Gi=new W("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Hi=new W("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),ji=new W("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Zi=new W("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),zi=new W("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Yi=new W("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Ji=new W("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),Xi=new W("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),se=new W("So11111111111111111111111111111111111111112"),Ee=W.default;var It=class{constructor({mint:t,decimals:n,symbol:r,name:o,skipMint:i=!1,isToken2022:s=!1}){if(t===Ee.toBase58()||t instanceof St&&Ee.equals(t)){this.decimals=re.decimals,this.symbol=re.symbol,this.name=re.name,this.mint=new St(re.address),this.isToken2022=!1;return}this.decimals=n,this.symbol=r||t.toString().substring(0,6),this.name=o||t.toString().substring(0,6),this.mint=i?St.default:Tn({publicKey:t}),this.isToken2022=s}equals(t){return this===t?!0:this.mint.equals(t.mint)}},xe=It;xe.WSOL=new It(ie(q({},re),{mint:re.address}));var Bt=class{constructor({decimals:t,symbol:n="UNKNOWN",name:r="UNKNOWN"}){this.decimals=t,this.symbol=n,this.name=r}equals(t){return this===t}},tt=Bt;tt.SOL=new Bt(yn);import no from"bn.js";var us=new V(new no(100));var hs=Z("Raydium_price");var ro=new oe(0),Gs=new oe(1),Hs=new oe(2),js=new oe(3),Zs=new oe(5),Qr=new oe(10),zs=new oe(100),Ys=new oe(1e3),Js=new oe(1e4);function gt(e,t=1,n=[]){let r=[...e];if(t<=0)return n;for(;r.length;)n.push(r.splice(0,t));return n}import{PublicKey as lo}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as fo}from"@solana/spl-token";import{ComputeBudgetProgram as Sn,Keypair as Bn,PublicKey as oo,Transaction as Ln,TransactionMessage as io,VersionedTransaction as Cn}from"@solana/web3.js";var G={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",TransferTip:"TransferTip"};import{TOKEN_PROGRAM_ID as so}from"@solana/spl-token";var In=Z("Raydium_txUtil"),Nn=1644;function nt(e){let t=[],n=[];return e.microLamports&&(t.push(Sn.setComputeUnitPrice({microLamports:e.microLamports})),n.push(G.SetComputeUnitPrice)),e.units&&(t.push(Sn.setComputeUnitLimit({units:e.units})),n.push(G.SetComputeUnitLimit)),{instructions:t,instructionTypes:n}}async function Pe(e,t){var r,o;let n=t!=null?t:"confirmed";return(o=await((r=e.getLatestBlockhash)==null?void 0:r.call(e,{commitment:n})))==null?void 0:o.blockhash}async function rt(e,t){return e.getSignatureStatuses([t]),new Promise((n,r)=>{let o=setTimeout(r,6e4);e.onSignature(t,i=>{if(clearTimeout(o),!i.err){n("");return}r(Object.assign(i.err,{txId:t}))},"confirmed")})}function ao(e,t){e.length<1&&In.logWithError(`no instructions provided: ${e.toString()}`),t.length<1&&In.logWithError(`no signers provided:, ${t.toString()}`);let n=new Ln;n.recentBlockhash="11111111111111111111111111111111",n.feePayer=t[0],n.add(...e);try{return Buffer.from(n.serialize({verifySignatures:!1})).toString("base64").length<Nn}catch{return!1}}function _n(e,t){let[n,r]=oo.findProgramAddressSync(e,t);return{publicKey:n,nonce:r}}function De({instructions:e,payer:t,signers:n}){return ao(e,[t,...n])}function Me({instructions:e,payer:t,lookupTableAddressAccount:n,recentBlockhash:r=Bn.generate().publicKey.toString()}){let i=new io({payerKey:t,recentBlockhash:r,instructions:e}).compileToV0Message(Object.values(n!=null?n:{}));try{return Buffer.from(new Cn(i).serialize()).toString("base64").length<Nn}catch{return!1}}var co=e=>Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e),uo=e=>{let t=e.serialize({requireAllSignatures:!1,verifySignatures:!1});e instanceof Cn&&(t=co(t));try{return t instanceof Buffer?t.toString("base64"):Buffer.from(t).toString("base64")}catch{return t.toString("base64")}};function be(e){let t=[];return e.forEach(n=>{n instanceof Ln&&(n.recentBlockhash||(n.recentBlockhash=so.toBase58()),n.feePayer||(n.feePayer=Bn.generate().publicKey)),t.push(uo(n))}),console.log("simulate tx string:",t),t}function ot(e,t,n){return _n([e.toBuffer(),(n!=null?n:fo).toBuffer(),t.toBuffer()],new lo("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}import{PublicKey as S}from"@solana/web3.js";var ba=new S("EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"),ya=new S("CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T"),wa=new S("9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z"),Ta=new S("FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG"),xa=new S("CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS"),Pa=new S("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"),Aa=new S("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),ka=new S("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"),Sa=new S("5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h"),Ia=new S("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),Ba=new S("CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"),La=new S("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),Ca=new S("kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy"),Na=new S("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),_a=new S("routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS"),Ra=new S("7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"),Ea=new S("6FJon3QE27qgPVggARueB22hLvoh22VzJpXv4rBEoSLF"),Da=new S("CC12se5To1CdEuw7fDS27B7Geo5jJyL7t5UK2B44NgiH"),Ma=new S("9HzJyW1qZsEiSfMUf6L2jo3CcTKAyBmSyKdwQeYisHrC"),va=new S("DropEU8AvevN3UrXWXTMuz3rqnMczQVNjq3kcSdW2SQi"),Fa=new S("CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"),Oa=new S("GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"),Ka=new S("DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8"),Ua=new S("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),Va=new S("3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH"),Wa=new S("LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"),qa=new S("WLHv2UAZm6z4KyaaELi5pjdbJh6RESMva1Rnn8pJVVh"),Ga=new S("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),Ha=new S("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),ja=new S("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),Za=new S("6s1xP3hpbAfFoNtUNF8mfHsjr2Bd97JxFJRWLbL6aHuX");var za={OPEN_BOOK_PROGRAM:new S("EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj"),SERUM_PROGRAM_ID_V3:new S("Ray1111111111111111111111111111111111111111"),AMM_V4:new S("DRaya7Kj3aMWQSy19kSjvmuwq9docCHofyP9kanQGaav"),AMM_STABLE:new S("DRayDdXc1NZQ9C3hRWmoSf8zK4iapgMnjdNZWrfwsP8m"),CLMM_PROGRAM_ID:new S("DRayAUgENGQBKVaX8owNhgzkEDyoHTGVEGHVJT1E9pfH"),CLMM_LOCK_PROGRAM_ID:new S("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),CLMM_LOCK_AUTH_ID:new S("6Aoh8h2Lw2m5UGxYR8AdAL87jTWYeKoxM52mJRzfYwN"),CREATE_CPMM_POOL_PROGRAM:new S("DRaycpLY18LhpbydsBWbVJtxpNv9oXPgjRSfpF2bWpYb"),CREATE_CPMM_POOL_AUTH:new S("CXniRufdq5xL8t8jZAPxsPZDpuudwuJSPWnbcD5Y5Nxq"),CREATE_CPMM_POOL_FEE_ACC:new S("3oE58BKVt8KuYkGxx8zBojugnymWmBiyafWgMrnb6eYy"),LOCK_CPMM_PROGRAM:new S("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),LOCK_CPMM_AUTH:new S("7qWVV8UY2bRJfDLP4s37YzBPKUkVB46DStYJBpYbQzu3"),UTIL1216:S.default,Router:new S("DRaybByLpbUL57LJARs3j8BitTxVfzBg351EaMr5UTCd"),FARM_PROGRAM_ID_V3:new S("DRayWyrLmEW5KEeqs8kdTMMaBabapqagaBC7KWpGtJeZ"),FARM_PROGRAM_ID_V4:new S("Ray1111111111111111111111111111111111111111"),FARM_PROGRAM_ID_V5:new S("DRayiCGSZgku1GTK6rXD6mVDdingXy6APAH1R6R5L2LC"),FARM_PROGRAM_ID_V6:new S("DRayzbYakXs45ELHkzH6vC3fuhQqTAnv5A68gdFuvZyZ"),LAUNCHPAD_PROGRAM:new S("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),LAUNCHPAD_AUTH:new S("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),LAUNCHPAD_PLATFORM:new S("2Jx4KTDrVSdWNazuGpcA8n3ZLTRGGBDxAWhuKe2Xcj2a"),LAUNCHPAD_CONFIG:new S("7ZR4zD7PYfY2XxoG1Gxcy2EgEeGYrpxrwzPuwdUBssEt"),FEE_DESTINATION_ID:new S("9y8ENuuZ3b19quffx9hQvRVygG5ky6snHfRvGpuSfeJy"),MODEL_DATA_PUBKEY:new S("Ray1111111111111111111111111111111111111111")};import Xa from"bn.js";import{PublicKey as Lt,AddressLookupTableAccount as Se}from"@solana/web3.js";async function Ct({connection:e,address:t,cluster:n="mainnet"}){let r=await en(e,[...new Set(t.map(i=>i.toString()))].map(i=>new Lt(i))),o={};for(let i=0;i<t.length;i++){let s=r[i],a=t[i];if(!s)continue;let u=new Se({key:a,state:Se.deserialize(s.data)});o[a.toString()]=u,n==="devnet"?ke[a.toString()]=u:Ae[a.toString()]=u}return o}var Ae={},Nt=async e=>{let t="AcL1Vo8oy1ULiavEcjSUcwfBSForXMudcZvDZy5nzJkU";if(Ae[t])return Ae;let n=new Lt(t),r=await e.getAccountInfo(n);return r&&(Ae[t]=new Se({key:n,state:Se.deserialize(r.data)})),Ae},ke={},_t=async e=>{let t="EFhMuDw1PKEuckuFRW9PavNfTH4LKP5uKHgyXDmWpFCq";if(ke[t])return ke;let n=new Lt(t),r=await e.getAccountInfo(n);return r&&(ke[t]=new Se({key:n,state:Se.deserialize(r.data)})),ke};import{PublicKey as Ie,sendAndConfirmTransaction as Rt,SystemProgram as po,Transaction as ve,TransactionMessage as Fe,VersionedTransaction as Oe}from"@solana/web3.js";import mo from"axios";var it=2e3,st=class{constructor(t){this.instructions=[];this.endInstructions=[];this.lookupTableAddress=[];this.signers=[];this.instructionTypes=[];this.endInstructionTypes=[];this.connection=t.connection,this.feePayer=t.feePayer,this.signAllTransactions=t.signAllTransactions,this.owner=t.owner,this.cluster=t.cluster,this.blockhashCommitment=t.blockhashCommitment,this.loopMultiTxStatus=!!t.loopMultiTxStatus}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 r;let t=(await mo.get(`https://solanacompass.com/api/fees?cacheFreshTime=${3e5}`)).data,{avg:n}=(r=t==null?void 0:t[15])!=null?r:{};if(!!n)return{units:6e5,microLamports:Math.min(Math.ceil(n*1e6/6e5),25e3)}}addCustomComputeBudget(t){if(t){let{instructions:n,instructionTypes:r}=nt(t);return this.instructions.unshift(...n),this.instructionTypes.unshift(...r),!0}return!1}addTipInstruction(t){var n;return t?(this.endInstructions.push(po.transfer({fromPubkey:(n=t.feePayer)!=null?n:this.feePayer,toPubkey:new Ie(t.address),lamports:BigInt(t.amount.toString())})),this.endInstructionTypes.push(G.TransferTip),!0):!1}async calComputeBudget({config:t,defaultIns:n}){try{let r=t||await this.getComputeBudgetConfig();if(this.addCustomComputeBudget(r))return;n&&this.instructions.unshift(...n)}catch{n&&this.instructions.unshift(...n)}}addInstruction({instructions:t=[],endInstructions:n=[],signers:r=[],instructionTypes:o=[],endInstructionTypes:i=[],lookupTableAddress:s=[]}){return this.instructions.push(...t),this.endInstructions.push(...n),this.signers.push(...r),this.instructionTypes.push(...o),this.endInstructionTypes.push(...i),this.lookupTableAddress.push(...s.filter(a=>a!==Ie.default.toString())),this}async versionBuild({txVersion:t,extInfo:n}){return t===0?await this.buildV0(q({},n||{})):this.build(n)}build(t){var r;let n=new ve;return this.allInstructions.length&&n.add(...this.allInstructions),n.feePayer=this.feePayer,((r=this.owner)==null?void 0:r.signer)&&!this.signers.some(o=>o.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 o=>{var l;let{recentBlockHash:i,skipPreflight:s=!0,sendAndConfirm:a,notSendToRpc:u}=o||{},c=i!=null?i:await Pe(this.connection,this.blockhashCommitment);if(n.recentBlockhash=c,this.signers.length&&n.sign(...this.signers),be([n]),(l=this.owner)!=null&&l.isKeyPair)return{txId:a?await Rt(this.connection,n,this.signers.find(p=>p.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 f=await this.signAllTransactions([n]);if(this.signers.length)for(let p of f)try{p.sign(...this.signers)}catch{}return{txId:u?"":await this.connection.sendRawTransaction(f[0].serialize(),{skipPreflight:s}),signedTx:f[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:t||{}}}buildMultiTx(t){var c;let{extraPreBuildData:n=[],extInfo:r}=t,{transaction:o}=this.build(r),i=n.filter(l=>l.transaction.instructions.length>0),s=[o,...i.map(l=>l.transaction)],a=[this.signers,...i.map(l=>l.signers)],u=[...this.instructionTypes,...i.map(l=>l.instructionTypes).flat()];return(c=this.owner)!=null&&c.signer&&a.forEach(l=>{l.some(f=>f.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:s,signers:a,instructionTypes:u,execute:async l=>{var P;let{sequentially:f,onTxUpdate:p,skipTxCount:m=0,recentBlockHash:d,skipPreflight:g=!0}=l||{},y=d!=null?d:await Pe(this.connection,this.blockhashCommitment);if((P=this.owner)!=null&&P.isKeyPair){if(f){let A=[],w=0;for(let T of s){if(++w,w<=m)continue;let b=await Rt(this.connection,T,this.signers.find(x=>x.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:g});A.push(b)}return{txIds:A,signedTxs:s}}return{txIds:await await Promise.all(s.map(async A=>(A.recentBlockhash=y,await this.connection.sendRawTransaction(A.serialize(),{skipPreflight:g})))),signedTxs:s}}if(this.signAllTransactions){let A=s.map((T,b)=>(T.recentBlockhash=y,a[b].length&&T.sign(...a[b]),T));be(A);let w=await this.signAllTransactions(A);if(f){let T=0,b=[],x=async()=>{if(!w[T])return;let N=await this.connection.sendRawTransaction(w[T].serialize(),{skipPreflight:g});b.push({txId:N,status:"sent",signedTx:w[T]}),p==null||p([...b]),T++;let B=!1,E=null,F=null,M=D=>{E!==null&&clearInterval(E),F!==null&&this.connection.removeSignatureListener(F);let v=b.findIndex(U=>U.txId===N);if(v>-1){if(b[v].status==="error"||b[v].status==="success")return;b[v].status=D.err?"error":"success"}p==null||p([...b]),D.err||x()};this.loopMultiTxStatus&&(E=setInterval(async()=>{var D;if(B){clearInterval(E);return}try{let v=await this.connection.getTransaction(N,{commitment:"confirmed",maxSupportedTransactionVersion:0});v&&(B=!0,clearInterval(E),M({err:((D=v.meta)==null?void 0:D.err)||null}),console.log("tx status from getTransaction:",N))}catch(v){B=!0,clearInterval(E),console.error("getTransaction timeout:",v,N)}},it)),F=this.connection.onSignature(N,D=>{if(B){this.connection.removeSignatureListener(F);return}B=!0,M(D)},"confirmed"),this.connection.getSignatureStatus(N)};return await x(),{txIds:b.map(N=>N.txId),signedTxs:w}}else{let T=[];for(let b=0;b<w.length;b+=1){let x=await this.connection.sendRawTransaction(w[b].serialize(),{skipPreflight:g});T.push(x)}return{txIds:T,signedTxs:w}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:r||{}}}async versionMultiBuild({extraPreBuildData:t,txVersion:n,extInfo:r}){return n===0?await this.buildV0MultiTx({extraPreBuildData:t,buildProps:r||{}}):this.buildMultiTx({extraPreBuildData:t,extInfo:r})}async buildV0(t){var g;let d=t||{},{lookupTableCache:n={},lookupTableAddress:r=[],forerunCreate:o,recentBlockhash:i}=d,s=ge(d,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),a=q(q({},this.cluster==="devnet"?await _t(this.connection):await Nt(this.connection)),n),u=Array.from(new Set([...r,...this.lookupTableAddress])),c=[];for(let y of u)a[y]===void 0&&c.push(new Ie(y));let l=await Ct({connection:this.connection,address:c});for(let[y,P]of Object.entries(l))a[y]=P;let f=o?Ie.default.toBase58():i!=null?i:await Pe(this.connection,this.blockhashCommitment),p=new Fe({payerKey:this.feePayer,recentBlockhash:f,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(a));((g=this.owner)==null?void 0:g.signer)&&!this.signers.some(y=>y.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let m=new Oe(p);return m.sign(this.signers),{builder:this,transaction:m,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async y=>{var T;let{skipPreflight:P=!0,sendAndConfirm:A,notSendToRpc:w}=y||{};if(be([m]),(T=this.owner)!=null&&T.isKeyPair){let b=await this.connection.sendTransaction(m,{skipPreflight:P});return A&&await rt(this.connection,b),{txId:b,signedTx:m}}if(this.signAllTransactions){let b=await this.signAllTransactions([m]);if(this.signers.length)for(let x of b)try{x.sign(this.signers)}catch{}return{txId:w?"":await this.connection.sendTransaction(b[0],{skipPreflight:P}),signedTx:b[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:s||{}}}async buildV0MultiTx(t){var c;let{extraPreBuildData:n=[],buildProps:r}=t,{transaction:o}=await this.buildV0(r),i=n.filter(l=>l.builder.instructions.length>0),s=[o,...i.map(l=>l.transaction)],a=[this.signers,...i.map(l=>l.signers)],u=[...this.instructionTypes,...i.map(l=>l.instructionTypes).flat()];return(c=this.owner)!=null&&c.signer&&a.forEach(l=>{l.some(f=>f.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),s.forEach(async(l,f)=>{l.sign(a[f])}),{builder:this,transactions:s,signers:a,instructionTypes:u,buildProps:r,execute:async l=>{var g;let{sequentially:f,onTxUpdate:p,recentBlockHash:m,skipPreflight:d=!0}=l||{};if(m&&s.forEach(y=>y.message.recentBlockhash=m),be(s),(g=this.owner)!=null&&g.isKeyPair){if(f){let y=[];for(let P of s){let A=await this.connection.sendTransaction(P,{skipPreflight:d});await rt(this.connection,A),y.push(A)}return{txIds:y,signedTxs:s}}return{txIds:await Promise.all(s.map(async y=>await this.connection.sendTransaction(y,{skipPreflight:d}))),signedTxs:s}}if(this.signAllTransactions){let y=await this.signAllTransactions(s);if(f){let P=0,A=[],w=async()=>{if(!y[P])return;let T=await this.connection.sendTransaction(y[P],{skipPreflight:d});A.push({txId:T,status:"sent",signedTx:y[P]}),p==null||p([...A]),P++;let b=!1,x=null,N=null,B=E=>{x!==null&&clearInterval(x),N!==null&&this.connection.removeSignatureListener(N);let F=A.findIndex(M=>M.txId===T);if(F>-1){if(A[F].status==="error"||A[F].status==="success")return;A[F].status=E.err?"error":"success"}p==null||p([...A]),E.err||w()};this.loopMultiTxStatus&&(x=setInterval(async()=>{var E;if(b){clearInterval(x);return}try{let F=await this.connection.getTransaction(T,{commitment:"confirmed",maxSupportedTransactionVersion:0});F&&(b=!0,clearInterval(x),B({err:((E=F.meta)==null?void 0:E.err)||null}),console.log("tx status from getTransaction:",T))}catch(F){b=!0,clearInterval(x),console.error("getTransaction timeout:",F,T)}},it)),N=this.connection.onSignature(T,E=>{if(b){this.connection.removeSignatureListener(N);return}b=!0,B(E)},"confirmed"),this.connection.getSignatureStatus(T)};return w(),{txIds:[],signedTxs:y}}else{let P=[];for(let A=0;A<y.length;A+=1){let w=await this.connection.sendTransaction(y[A],{skipPreflight:d});P.push(w)}return{txIds:P,signedTxs:y}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:r||{}}}async sizeCheckBuild(t){var p;let f=t||{},{splitIns:n=[],computeBudgetConfig:r}=f,o=ge(f,["splitIns","computeBudgetConfig"]),i=r?nt(r):{instructions:[],instructionTypes:[]},s=this.signers.reduce((m,d)=>ie(q({},m),{[d.publicKey.toBase58()]:d}),{}),a=[],u=[],c=[],l=0;if(this.allInstructions.forEach(m=>{let d=[...c,m],g=r?[...i.instructions,...d]:d,P=[...new Set(d.map(A=>A.keys.filter(w=>w.isSigner).map(w=>w.pubkey.toString())).flat()).values()].map(A=>new Ie(A));if(m!==n[l]&&c.length<12&&(De({instructions:g,payer:this.feePayer,signers:P})||De({instructions:d,payer:this.feePayer,signers:P})))c.push(m);else{if(c.length===0)throw Error("item ins too big");l+=m===n[l]?1:0,De({instructions:r?[...i.instructions,...c]:[...c],payer:this.feePayer,signers:P})?a.push(new ve().add(...i.instructions,...c)):a.push(new ve().add(...c)),u.push(Array.from(new Set(c.map(A=>A.keys.filter(w=>w.isSigner).map(w=>w.pubkey.toString())).flat())).map(A=>s[A]).filter(A=>A!==void 0)),c=[m]}}),c.length>0){let d=[...new Set(c.map(g=>g.keys.filter(y=>y.isSigner).map(y=>y.pubkey.toString())).flat()).values()].map(g=>s[g]).filter(g=>g!==void 0);De({instructions:r?[...i.instructions,...c]:[...c],payer:this.feePayer,signers:d.map(g=>g.publicKey)})?a.push(new ve().add(...i.instructions,...c)):a.push(new ve().add(...c)),u.push(d)}return a.forEach(m=>m.feePayer=this.feePayer),(p=this.owner)!=null&&p.signer&&u.forEach(m=>{m.some(d=>d.publicKey.equals(this.owner.publicKey))||m.push(this.owner.signer)}),{builder:this,transactions:a,signers:u,instructionTypes:this.instructionTypes,execute:async m=>{var T;let{sequentially:d,onTxUpdate:g,skipTxCount:y=0,recentBlockHash:P,skipPreflight:A=!0}=m||{},w=P!=null?P:await Pe(this.connection,this.blockhashCommitment);if(a.forEach(async(b,x)=>{b.recentBlockhash=w,u[x].length&&b.sign(...u[x])}),be(a),(T=this.owner)!=null&&T.isKeyPair){if(d){let b=0,x=[];for(let N of a){if(++b,b<=y){x.push("tx skipped");continue}let B=await Rt(this.connection,N,this.signers.find(E=>E.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:A});x.push(B)}return{txIds:x,signedTxs:a}}return{txIds:await Promise.all(a.map(async b=>await this.connection.sendRawTransaction(b.serialize(),{skipPreflight:A}))),signedTxs:a}}if(this.signAllTransactions){let b=await this.signAllTransactions(a.slice(y,a.length)),x=[...a.slice(0,y),...b];if(d){let N=0,B=[],E=async()=>{if(!x[N])return;N<y&&(B.push({txId:"",status:"success",signedTx:x[N]}),g==null||g([...B]),N++,E());let F=await this.connection.sendRawTransaction(x[N].serialize(),{skipPreflight:A});B.push({txId:F,status:"sent",signedTx:x[N]}),g==null||g([...B]),N++;let M=!1,D=null,v=null,U=O=>{D!==null&&clearInterval(D),v!==null&&this.connection.removeSignatureListener(v);let C=B.findIndex(de=>de.txId===F);if(C>-1){if(B[C].status==="error"||B[C].status==="success")return;B[C].status=O.err?"error":"success"}g==null||g([...B]),O.err||E()};this.loopMultiTxStatus&&(D=setInterval(async()=>{var O;if(M){clearInterval(D);return}try{let C=await this.connection.getTransaction(F,{commitment:"confirmed",maxSupportedTransactionVersion:0});C&&(M=!0,clearInterval(D),U({err:((O=C.meta)==null?void 0:O.err)||null}),console.log("tx status from getTransaction:",F))}catch(C){M=!0,clearInterval(D),console.error("getTransaction timeout:",C,F)}},it)),v=this.connection.onSignature(F,O=>{if(M){this.connection.removeSignatureListener(v);return}M=!0,U(O)},"confirmed"),this.connection.getSignatureStatus(F)};return await E(),{txIds:B.map(F=>F.txId),signedTxs:x}}else{let N=[];for(let B=0;B<x.length;B+=1){let E=await this.connection.sendRawTransaction(x[B].serialize(),{skipPreflight:A});N.push(E)}return{txIds:N,signedTxs:x}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:o||{}}}async sizeCheckBuildV0(t){var w;let A=t||{},{computeBudgetConfig:n,splitIns:r=[],lookupTableCache:o={},lookupTableAddress:i=[]}=A,s=ge(A,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),a=q(q({},this.cluster==="devnet"?await _t(this.connection):await Nt(this.connection)),o),u=Array.from(new Set([...this.lookupTableAddress,...i])),c=[];for(let T of u)a[T]===void 0&&c.push(new Ie(T));let l=await Ct({connection:this.connection,address:c});for(let[T,b]of Object.entries(l))a[T]=b;let f=n?nt(n):{instructions:[],instructionTypes:[]},p=await Pe(this.connection,this.blockhashCommitment),m=this.signers.reduce((T,b)=>ie(q({},T),{[b.publicKey.toBase58()]:b}),{}),d=[],g=[],y=[],P=0;if(this.allInstructions.forEach(T=>{let b=[...y,T],x=n?[...f.instructions,...b]:b;if(T!==r[P]&&y.length<12&&(Me({instructions:x,payer:this.feePayer,lookupTableAddressAccount:a})||Me({instructions:b,payer:this.feePayer,lookupTableAddressAccount:a})))y.push(T);else{if(y.length===0)throw Error("item ins too big");P+=T===r[P]?1:0;let N={};for(let B of[...new Set(u)])a[B]!==void 0&&(N[B]=a[B]);if(n&&Me({instructions:[...f.instructions,...y],payer:this.feePayer,lookupTableAddressAccount:a,recentBlockhash:p})){let B=new Fe({payerKey:this.feePayer,recentBlockhash:p,instructions:[...f.instructions,...y]}).compileToV0Message(Object.values(a));d.push(new Oe(B))}else{let B=new Fe({payerKey:this.feePayer,recentBlockhash:p,instructions:[...y]}).compileToV0Message(Object.values(a));d.push(new Oe(B))}g.push(Array.from(new Set(y.map(B=>B.keys.filter(E=>E.isSigner).map(E=>E.pubkey.toString())).flat())).map(B=>m[B]).filter(B=>B!==void 0)),y=[T]}}),y.length>0){let b=[...new Set(y.map(x=>x.keys.filter(N=>N.isSigner).map(N=>N.pubkey.toString())).flat()).values()].map(x=>m[x]).filter(x=>x!==void 0);if(n&&Me({instructions:[...f.instructions,...y],payer:this.feePayer,lookupTableAddressAccount:a,recentBlockhash:p})){let x=new Fe({payerKey:this.feePayer,recentBlockhash:p,instructions:[...f.instructions,...y]}).compileToV0Message(Object.values(a));d.push(new Oe(x))}else{let x=new Fe({payerKey:this.feePayer,recentBlockhash:p,instructions:[...y]}).compileToV0Message(Object.values(a));d.push(new Oe(x))}g.push(b)}return(w=this.owner)!=null&&w.signer&&g.forEach(T=>{T.some(b=>b.publicKey.equals(this.owner.publicKey))||T.push(this.owner.signer)}),d.forEach((T,b)=>{T.sign(g[b])}),{builder:this,transactions:d,buildProps:t,signers:g,instructionTypes:this.instructionTypes,execute:async T=>{var F;let{sequentially:b,onTxUpdate:x,skipTxCount:N=0,recentBlockHash:B,skipPreflight:E=!0}=T||{};if(d.map(async(M,D)=>{g[D].length&&M.sign(g[D]),B&&(M.message.recentBlockhash=B)}),be(d),(F=this.owner)!=null&&F.isKeyPair){if(b){let M=0,D=[];for(let v of d){if(++M,M<=N){console.log("skip tx: ",M),D.push("tx skipped");continue}let U=await this.connection.sendTransaction(v,{skipPreflight:E});await rt(this.connection,U),D.push(U)}return{txIds:D,signedTxs:d}}return{txIds:await Promise.all(d.map(async M=>await this.connection.sendTransaction(M,{skipPreflight:E}))),signedTxs:d}}if(this.signAllTransactions){let M=await this.signAllTransactions(d.slice(N,d.length)),D=[...d.slice(0,N),...M];if(b){let v=0,U=[],O=async()=>{if(!D[v])return;if(v<N){U.push({txId:"",status:"success",signedTx:D[v]}),x==null||x([...U]),v++,O();return}let C=await this.connection.sendTransaction(D[v],{skipPreflight:E});U.push({txId:C,status:"sent",signedTx:D[v]}),x==null||x([...U]),v++;let de=!1,ye=null,qe=null,zt=he=>{ye!==null&&clearInterval(ye),qe!==null&&this.connection.removeSignatureListener(qe);let te=U.findIndex(Gn=>Gn.txId===C);if(te>-1){if(U[te].status==="error"||U[te].status==="success")return;U[te].status=he.err?"error":"success"}x==null||x([...U]),he.err||O()};this.loopMultiTxStatus&&(ye=setInterval(async()=>{var he;if(de){clearInterval(ye);return}try{let te=await this.connection.getTransaction(C,{commitment:"confirmed",maxSupportedTransactionVersion:0});te&&(de=!0,clearInterval(ye),zt({err:((he=te.meta)==null?void 0:he.err)||null}),console.log("tx status from getTransaction:",C))}catch(te){de=!0,clearInterval(ye),console.error("getTransaction timeout:",te,C)}},it)),qe=this.connection.onSignature(C,he=>{if(de){this.connection.removeSignatureListener(qe);return}de=!0,zt(he)},"confirmed"),this.connection.getSignatureStatus(C)};return O(),{txIds:[],signedTxs:D}}else{let v=[];for(let U=0;U<D.length;U+=1){let O=await this.connection.sendTransaction(D[U],{skipPreflight:E});v.push(O)}return{txIds:v,signedTxs:D}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:s||{}}}};import{PublicKey as bc}from"@solana/web3.js";import wc from"bn.js";import ho from"bn.js";var kc=new ho(1e6);import{AccountLayout as Le,createAssociatedTokenAccountIdempotentInstruction as jt,TOKEN_PROGRAM_ID as me,TOKEN_2022_PROGRAM_ID as vo}from"@solana/spl-token";var Et=(...e)=>e.map(t=>{try{return typeof t=="object"?JSON.stringify(t):t}catch{return t}}).join(", "),Ke=class{constructor({scope:t,moduleName:n}){this.disabled=!1;this.scope=t,this.logger=Z(n)}createTxBuilder(t){return this.scope.checkOwner(),new st({connection:this.scope.connection,feePayer:t||this.scope.ownerPubKey,cluster:this.scope.cluster,owner:this.scope.owner,blockhashCommitment:this.scope.blockhashCommitment,loopMultiTxStatus:this.scope.loopMultiTxStatus,api:this.scope.api,signAllTransactions:this.scope.signAllTransactions})}logDebug(...t){this.logger.debug(Et(t))}logInfo(...t){this.logger.info(Et(t))}logAndCreateError(...t){let n=Et(t);throw new Error(n)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};import{PublicKey as Co,SystemProgram as No}from"@solana/web3.js";import _o from"bn.js";import{createCloseAccountInstruction as Ro,createInitializeAccountInstruction as Eo,createTransferInstruction as Do,TOKEN_PROGRAM_ID as Be}from"@solana/spl-token";import{Keypair as So,PublicKey as Vn}from"@solana/web3.js";import Io from"bn.js";import{TOKEN_PROGRAM_ID as Bo}from"@solana/spl-token";function go(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function Dt(e,...t){if(!go(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Mt(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Rn(e,t){Dt(e);let n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var ct=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),$=(e,t)=>e<<32-t|e>>>t;var Xc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function bo(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function vt(e){return typeof e=="string"&&(e=bo(e)),Dt(e),e}var at=class{clone(){return this._cloneInto()}},Qc={}.toString;function En(e){let t=r=>e().update(vt(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function yo(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);let o=BigInt(32),i=BigInt(4294967295),s=Number(n>>o&i),a=Number(n&i),u=r?4:0,c=r?0:4;e.setUint32(t+u,s,r),e.setUint32(t+c,a,r)}var Dn=(e,t,n)=>e&t^~e&n,Mn=(e,t,n)=>e&t^e&n^t&n,ut=class extends at{constructor(t,n,r,o){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=ct(this.buffer)}update(t){Mt(this);let{view:n,buffer:r,blockLen:o}=this;t=vt(t);let i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let u=ct(t);for(;o<=i-s;s+=o)this.process(u,s);continue}r.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Mt(this),Rn(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>o-s&&(this.process(r,0),s=0);for(let f=s;f<o;f++)n[f]=0;yo(r,o-8,BigInt(this.length*8),i),this.process(r,0);let a=ct(t),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=u/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<c;f++)a.setUint32(4*f,l[f],i)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return t.length=o,t.pos=a,t.finished=i,t.destroyed=s,o%n&&t.buffer.set(r),t}};var wo=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),fe=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),pe=new Uint32Array(64),Ft=class extends ut{constructor(){super(64,32,8,!1),this.A=fe[0]|0,this.B=fe[1]|0,this.C=fe[2]|0,this.D=fe[3]|0,this.E=fe[4]|0,this.F=fe[5]|0,this.G=fe[6]|0,this.H=fe[7]|0}get(){let{A:t,B:n,C:r,D:o,E:i,F:s,G:a,H:u}=this;return[t,n,r,o,i,s,a,u]}set(t,n,r,o,i,s,a,u){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=u|0}process(t,n){for(let f=0;f<16;f++,n+=4)pe[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){let p=pe[f-15],m=pe[f-2],d=$(p,7)^$(p,18)^p>>>3,g=$(m,17)^$(m,19)^m>>>10;pe[f]=g+pe[f-7]+d+pe[f-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:u,G:c,H:l}=this;for(let f=0;f<64;f++){let p=$(a,6)^$(a,11)^$(a,25),m=l+p+Dn(a,u,c)+wo[f]+pe[f]|0,g=($(r,2)^$(r,13)^$(r,22))+Mn(r,o,i)|0;l=c,c=u,u=a,a=s+m|0,s=i,i=o,o=r,r=m+g|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,u=u+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,o,i,s,a,u,c,l)}roundClean(){pe.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var vn=En(()=>new Ft);import{PublicKey as ko}from"@solana/web3.js";import On,{isBN as sl}from"bn.js";import{bits as au,BitStructure as cu,blob as To,Blob as uu,cstr as lu,f32 as fu,f32be as pu,f64 as mu,f64be as du,greedy as hu,Layout as xo,ns64 as gu,ns64be as bu,nu64 as yu,nu64be as wu,offset as Tu,s16 as xu,s16be as Pu,s24 as Au,s24be as ku,s32 as Su,s32be as Iu,s40 as Bu,s40be as Lu,s48 as Cu,s48be as Nu,s8 as _u,seq as Ru,struct as Eu,Structure as Po,u16 as Du,u16be as Mu,u24 as vu,u24be as Fu,u32 as Ou,u32be as Ku,u40 as Uu,u40be as Vu,u48 as Wu,u48be as qu,u8 as Gu,UInt as Ao,union as Hu,Union as ju,unionLayoutDiscriminator as Zu,utf8 as zu}from"@solana/buffer-layout";var Ot=xo,Fn=Po;var Kt=Ao;var Ut=To;var Vt=class extends Ot{constructor(n,r,o){super(n,o);this.blob=Ut(n),this.signed=r}decode(n,r=0){let o=new On(this.blob.decode(n,r),10,"le");return this.signed?o.fromTwos(this.span*8).clone():o}encode(n,r,o=0){return typeof n=="number"&&(n=new On(n)),this.signed&&(n=n.toTwos(this.span*8)),this.blob.encode(n.toArrayLike(Buffer,"le",this.span),r,o)}};function Kn(e){return new Kt(1,e)}function lt(e){return new Kt(4,e)}function ft(e){return new Vt(8,!1,e)}var Wt=class extends Ot{constructor(n,r,o,i){super(n.span,i);this.layout=n,this.decoder=r,this.encoder=o}decode(n,r){return this.decoder(this.layout.decode(n,r))}encode(n,r,o){return this.layout.encode(this.encoder(n),r,o)}getSpan(n,r){return this.layout.getSpan(n,r)}};function Ue(e){return new Wt(Ut(32),t=>new ko(t),t=>t.toBuffer(),e)}var qt=class extends Fn{decode(t,n){return super.decode(t,n)}};function Un(e,t,n){return new qt(e,t,n)}var Ve=Un([Ue("mint"),Ue("owner"),ft("amount"),lt("delegateOption"),Ue("delegate"),Kn("state"),lt("isNativeOption"),ft("isNative"),ft("delegatedAmount"),lt("closeAuthorityOption"),Ue("closeAuthority")]);var xl=Z("Raydium_Util");function Wn({owner:e,solAccountResp:t,tokenAccountResp:n}){let r=[],o=[];for(let{pubkey:i,account:s}of n.value){let a=Ve.decode(s.data),{mint:u,amount:c}=a;r.push({publicKey:i,mint:u,amount:c,isAssociated:ot(e,u,s.owner).publicKey.equals(i),isNative:!1,programId:s.owner}),o.push({pubkey:i,accountInfo:a,programId:s.owner})}return t&&r.push({mint:Vn.default,amount:new Io(String(t.lamports)),isNative:!0,programId:t.owner}),{tokenAccounts:r,tokenAccountRawInfos:o}}function pt({fromPublicKey:e,programId:t=Bo,assignSeed:n}){let r=n?btoa(n).slice(0,32):So.generate().publicKey.toBase58().slice(0,32);return{publicKey:Lo(e,r,t),seed:r}}function Lo(e,t,n){let r=Buffer.concat([e.toBuffer(),Buffer.from(t),n.toBuffer()]),o=vn(r);return new Vn(o)}function Gt(e){let{mint:t,tokenAccount:n,owner:r,programId:o=Be}=e;return Eo(n,t,r,o)}function We(e){let{tokenAccount:t,payer:n,multiSigners:r=[],owner:o,programId:i=Be}=e;return Ro(t,n,o,r,i)}async function Ht(e){let{connection:t,amount:n,commitment:r,payer:o,owner:i,skipCloseAccount:s}=e,a=await t.getMinimumBalanceForRentExemption(Ve.span,r),u=Q(n).add(new _o(a)),c=pt({fromPublicKey:o,programId:Be});return{addresses:{newAccount:c.publicKey},signers:[],instructions:[No.createAccountWithSeed({fromPubkey:o,basePubkey:o,seed:c.seed,newAccountPubkey:c.publicKey,lamports:u.toNumber(),space:Ve.span,programId:Be}),Gt({mint:new Co(re.address),tokenAccount:c.publicKey,owner:i,programId:Be})],instructionTypes:[G.CreateAccount,G.InitAccount],endInstructionTypes:s?[]:[G.CloseAccount],endInstructions:s?[]:[We({tokenAccount:c.publicKey,payer:o,owner:i})]}}function qn({source:e,destination:t,owner:n,amount:r,multiSigners:o=[],tokenProgram:i=Be}){return Do(e,t,n,BigInt(String(r)),o,i)}var Zt=class extends Ke{constructor(n){super(n);this._tokenAccounts=[];this._tokenAccountRawInfos=[];this._accountListener=[];this._clientOwnedToken=!1;this._notSubscribeAccountChange=!1;this._accountFetchTime=0;let{tokenAccounts:r,tokenAccountRawInfos:o,notSubscribeAccountChange:i}=n;this._tokenAccounts=r||[],this._tokenAccountRawInfos=o||[],this._notSubscribeAccountChange=i!=null?i:!0,this._clientOwnedToken=!!(r||o)}get tokenAccounts(){return this._tokenAccounts}get tokenAccountRawInfos(){return this._tokenAccountRawInfos}set notSubscribeAccountChange(n){this._notSubscribeAccountChange=n}updateTokenAccount({tokenAccounts:n,tokenAccountRawInfos:r}){return n&&(this._tokenAccounts=n),r&&(this._tokenAccountRawInfos=r),this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId),this._accountChangeListenerId=void 0,this._clientOwnedToken=!0,this}addAccountChangeListener(n){return this._accountListener.push(n),this}removeAccountChangeListener(n){return this._accountListener=this._accountListener.filter(r=>r!==n),this}getAssociatedTokenAccount(n,r){return ot(this.scope.ownerPubKey,n,r).publicKey}resetTokenAccounts(){this._clientOwnedToken||(this._tokenAccounts=[],this._tokenAccountRawInfos=[])}async fetchWalletTokenAccounts(n){if(this._clientOwnedToken||!(n!=null&&n.forceUpdate)&&this._tokenAccounts.length&&Date.now()-this._accountFetchTime<(this._notSubscribeAccountChange?1e3*5:1e3*60*3))return{tokenAccounts:this._tokenAccounts,tokenAccountRawInfos:this._tokenAccountRawInfos};this.scope.checkOwner();let o=q(q({},{}),n),[i,s,a]=await Promise.all([this.scope.connection.getAccountInfo(this.scope.ownerPubKey,o.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:me},o.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:vo},o.commitment)]),{tokenAccounts:u,tokenAccountRawInfos:c}=Wn({owner:this.scope.ownerPubKey,solAccountResp:i,tokenAccountResp:{context:s.context,value:[...s.value,...a.value]}});return this._tokenAccounts=u,this._tokenAccountRawInfos=c,this._accountFetchTime=Date.now(),this._notSubscribeAccountChange||(this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId),this._accountChangeListenerId=this.scope.connection.onAccountChange(this.scope.ownerPubKey,()=>{this.fetchWalletTokenAccounts({forceUpdate:!0}),this._accountListener.forEach(l=>l({tokenAccounts:this._tokenAccounts,tokenAccountRawInfos:this._tokenAccountRawInfos}))},{commitment:n==null?void 0:n.commitment})),{tokenAccounts:u,tokenAccountRawInfos:c}}clearAccountChangeCkb(){this._accountChangeListenerId!==void 0&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId)}async getCreatedTokenAccount({mint:n,programId:r=me,associatedOnly:o=!0}){await this.fetchWalletTokenAccounts();let i=this._tokenAccounts.filter(({mint:a})=>a==null?void 0:a.equals(n)).sort((a,u)=>a.amount.lt(u.amount)?1:-1),s=this.getAssociatedTokenAccount(n,r);for(let a of i){let{publicKey:u}=a;if(u&&(!o||o&&s.equals(u)))return u}}async getOrCreateTokenAccount(n){var g,y,P,A;await this.fetchWalletTokenAccounts();let{mint:r,createInfo:o,associatedOnly:i,owner:s,notUseTokenAccount:a=!1,skipCloseAccount:u=!1,checkCreateATAOwner:c=!1,assignSeed:l}=n,f=new mt(n.tokenProgram||me),p=this.getAssociatedTokenAccount(r,new mt(f)),m=(a?[]:this.tokenAccountRawInfos).filter(w=>w.accountInfo.mint.equals(r)&&(!i||w.pubkey.equals(p))).sort((w,T)=>w.accountInfo.amount.lt(T.accountInfo.amount)?1:-1);if(o===void 0||m.length>0)return m.length>0?{account:m[0].pubkey}:{};let d={instructions:[],endInstructions:[],signers:[],instructionTypes:[],endInstructionTypes:[]};if(i){let w=jt(s,p,s,r,f),T=this.tokenAccountRawInfos.find(b=>b.pubkey.equals(p));if(c){let b=await this.scope.connection.getAccountInfo(p);if(b===null)(g=d.instructions)==null||g.push(w),d.instructionTypes.push(G.CreateATA);else if(!(b.owner.equals(f)&&Le.decode(b.data).mint.equals(r)&&Le.decode(b.data).owner.equals(s)))throw Error(`create ata check error -> mint: ${r.toString()}, ata: ${p.toString()}`)}else T===void 0&&(d.instructions.push(w),d.instructionTypes.push(G.CreateATA));if(r.equals(se)&&o.amount){let b=await Ht({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:o.payer||this.scope.ownerPubKey,amount:(y=o.amount)!=null?y:0,skipCloseAccount:u});d.instructions.push(...b.instructions||[]),d.endInstructions.push(...b.endInstructions||[]),d.instructionTypes.push(...b.instructionTypes||[]),d.endInstructionTypes.push(...b.endInstructionTypes||[]),o.amount&&(d.instructions.push(qn({source:b.addresses.newAccount,destination:p,owner:this.scope.ownerPubKey,amount:o.amount,tokenProgram:me})),d.instructionTypes.push(G.TransferAmount))}return!u&&T===void 0&&(d.endInstructions.push(We({owner:s,payer:o.payer||s,tokenAccount:p,programId:f})),d.endInstructionTypes.push(G.CloseAccount)),{account:p,instructionParams:d}}else{let w=pt({fromPublicKey:s,programId:f,assignSeed:l}),T=await this.scope.connection.getMinimumBalanceForRentExemption(Le.span),b=Mo.createAccountWithSeed({fromPubkey:s,basePubkey:s,seed:w.seed,newAccountPubkey:w.publicKey,lamports:T+Number((A=(P=o.amount)==null?void 0:P.toString())!=null?A:0),space:Le.span,programId:f});return d.instructions.push(b,Gt({mint:r,tokenAccount:w.publicKey,owner:this.scope.ownerPubKey,programId:f})),d.instructionTypes.push(G.CreateAccount),d.instructionTypes.push(G.InitAccount),u||(d.endInstructions.push(We({owner:s,payer:o.payer||s,tokenAccount:w.publicKey,programId:f})),d.endInstructionTypes.push(G.CloseAccount)),{account:w.publicKey,instructionParams:d}}}async checkOrCreateAta({mint:n,programId:r=me,autoUnwrapWSOLToSOL:o}){var u;await this.fetchWalletTokenAccounts();let i=(u=this.scope.account.tokenAccounts.find(({mint:c})=>(c==null?void 0:c.toBase58())===n.toBase58()))==null?void 0:u.publicKey,s=this.scope.ownerPubKey,a={};if(!i){let c=this.getAssociatedTokenAccount(n,r),l=await jt(s,c,s,n,r);a.instructions=[l],a.instructionTypes=[G.CreateATA],i=c}return o&&se.toBase58()===n.toBase58()&&(a.endInstructions=[We({owner:s,payer:s,tokenAccount:i,programId:r})],a.endInstructionTypes=[G.CloseAccount]),{pubKey:i,newInstructions:a}}async handleTokenAccount(n){let{side:r,amount:o,mint:i,programId:s=me,tokenAccount:a,payer:u=this.scope.ownerPubKey,bypassAssociatedCheck:c,skipCloseAccount:l,checkCreateATAOwner:f}=n,p=this.getAssociatedTokenAccount(i,s);if(new mt(se).equals(i)){let m=await Ht({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:u,amount:o,skipCloseAccount:l});return q({tokenAccount:m.addresses.newAccount},m)}else if(!a||r==="out"&&!p.equals(a)&&!c){let m=[],d=jt(this.scope.ownerPubKey,p,this.scope.ownerPubKey,i,s);if(f){let g=await this.scope.connection.getAccountInfo(p);if(g===null)m.push(d);else if(!(g.owner.equals(me)&&Le.decode(g.data).mint.equals(i)&&Le.decode(g.data).owner.equals(this.scope.ownerPubKey)))throw Error(`create ata check error -> mint: ${i.toString()}, ata: ${p.toString()}`)}else m.push(d);return{tokenAccount:p,instructions:m,instructionTypes:[G.CreateATA]}}return{tokenAccount:a}}async processTokenAccount(n){let{mint:r,programId:o=me,amount:i,useSOLBalance:s,handleTokenAccount:a,feePayer:u}=n,c,l=this.createTxBuilder(u);if(r.equals(new mt(se))&&s){let f=await this.handleTokenAccount({side:"in",amount:i||0,mint:r,bypassAssociatedCheck:!0,programId:o}),{tokenAccount:m}=f,d=ge(f,["tokenAccount"]);c=m,l.addInstruction(d)}else if(c=await this.getCreatedTokenAccount({mint:r,associatedOnly:!1,programId:o}),!c&&a){let p=await this.scope.account.handleTokenAccount({side:"in",amount:0,mint:r,bypassAssociatedCheck:!0,programId:o}),{tokenAccount:m}=p,d=ge(p,["tokenAccount"]);c=m,l.addInstruction(d)}return q({tokenAccount:c},l.AllTxData)}};export{Zt as default};
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
//# sourceMappingURL=account.mjs.map