UNPKG

snapper-sdk

Version:

An SDK for building applications on top of Snapper.

10 lines 80.6 kB
import{PublicKey as nt,SystemProgram as bo}from"@solana/web3.js";import{PublicKey as In}from"@solana/web3.js";import{get as Mt,set as Sn}from"lodash";var rt=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}},Dt={},Ln={};function W(e){let t=Mt(Dt,e);if(!t){let n=Mt(Ln,e);t=new rt({name:e,logLevel:n}),Sn(Dt,e,t)}return t}import{MINT_SIZE as Lo,TOKEN_PROGRAM_ID as Io,getTransferFeeConfig as No,unpackMint as Eo}from"@solana/spl-token";var ot=W("Raydium_accountInfo_util");async function Kt(e,t,n){let{batchRequest:r,commitment:o="confirmed",chunkCount:i=100}={batchRequest:!1,...n},s=it(t,i),a=new Array(s.length).fill([]);if(r){let c=s.map(f=>{let p=e._buildArgs([f.map(m=>m.toBase58())],o,"base64");return{methodName:"getMultipleAccounts",args:p}}),u=it(c,10);a=(await(await Promise.all(u.map(async f=>await e._rpcBatchRequest(f)))).flat()).map(f=>(f.error&&ot.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${f.error.message}`),f.result.value.map(p=>{if(p){let{data:m,executable:w,lamports:h,owner:x,rentEpoch:b}=p;return m.length!==2&&m[1]!=="base64"&&ot.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(m[0],"base64"),executable:w,lamports:h,owner:new In(x),rentEpoch:b}}return null})))}else try{a=await Promise.all(s.map(c=>e.getMultipleAccountsInfo(c,o)))}catch(c){c instanceof Error&&ot.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${c.message}`)}return a.flat()}import J from"bn.js";var fe=9e15,oe=1e9,st="0123456789abcdef",Me="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",De="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",at={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-fe,maxE:fe,crypto:!1},Vt,X,k=!0,Oe="[DecimalError] ",re=Oe+"Invalid argument: ",Ut=Oe+"Precision limit exceeded",Wt=Oe+"crypto unavailable",qt="[object Decimal]",q=Math.floor,O=Math.pow,Nn=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,En=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,_n=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Gt=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,j=1e7,A=7,Rn=9007199254740991,Mn=Me.length-1,ct=De.length-1,d={toStringTag:qt};d.absoluteValue=d.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),T(e)};d.ceil=function(){return T(new this.constructor(this),this.e+1,2)};d.clampedTo=d.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(re+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new o(r)};d.comparedTo=d.cmp=function(e){var t,n,r,o,i=this,s=i.d,a=(e=new i.constructor(e)).d,c=i.s,u=e.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(i.e!==e.e)return i.e>e.e^c<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]^c<0?1:-1;return r===o?0:r>o^c<0?1:-1};d.cosine=d.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())+A,r.rounding=1,n=Dn(r,Zt(r,n)),r.precision=e,r.rounding=t,T(X==2||X==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};d.cubeRoot=d.cbrt=function(){var e,t,n,r,o,i,s,a,c,u,l=this,f=l.constructor;if(!l.isFinite()||l.isZero())return new f(l);for(k=!1,i=l.s*O(l.s*l,1/3),!i||Math.abs(i)==1/0?(n=F(l.d),e=l.e,(i=(e-n.length+1)%3)&&(n+=i==1||i==-2?"0":"00"),i=O(n,1/3),e=q((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,c=a.times(a).times(a),u=c.plus(l),r=E(u.plus(l).times(a),u.plus(c),s+2,1),F(a.d).slice(0,s)===(n=F(r.d)).slice(0,s))if(n=n.slice(s-3,s+1),n=="9999"||!o&&n=="4999"){if(!o&&(T(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")&&(T(r,e+1,1),t=!r.times(r).times(r).eq(l));break}return k=!0,T(r,e,f.rounding,t)};d.decimalPlaces=d.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-q(this.e/A))*A,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};d.dividedBy=d.div=function(e){return E(this,new this.constructor(e))};d.dividedToIntegerBy=d.divToInt=function(e){var t=this,n=t.constructor;return T(E(t,new n(e),0,1,1),n.precision,n.rounding)};d.equals=d.eq=function(e){return this.cmp(e)===0};d.floor=function(){return T(new this.constructor(this),this.e+1,3)};d.greaterThan=d.gt=function(e){return this.cmp(e)>0};d.greaterThanOrEqualTo=d.gte=function(e){var t=this.cmp(e);return t==1||t===0};d.hyperbolicCosine=d.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/Fe(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),i=pe(s,1,i.times(t),new s(1),!0);for(var c,u=e,l=new s(8);u--;)c=i.times(i),i=a.minus(c.times(l.minus(c.times(l))));return T(i,s.precision=n,s.rounding=r,!0)};d.hyperbolicSine=d.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=pe(i,2,o,o,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,o=o.times(1/Fe(5,e)),o=pe(i,2,o,o,!0);for(var s,a=new i(5),c=new i(16),u=new i(20);e--;)s=o.times(o),o=o.times(a.plus(s.times(c.times(s).plus(u))))}return i.precision=t,i.rounding=n,T(o,t,n,!0)};d.hyperbolicTangent=d.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,E(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};d.inverseCosine=d.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()?H(n,o,i):new n(0):new n(NaN):t.isZero()?H(n,o+4,i).times(.5):(n.precision=o+6,n.rounding=1,t=t.asin(),e=H(n,o+4,i).times(.5),n.precision=o,n.rounding=i,e.minus(t))};d.inverseHyperbolicCosine=d.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,k=!1,n=n.times(n).minus(1).sqrt().plus(n),k=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};d.inverseHyperbolicSine=d.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,k=!1,n=n.times(n).plus(1).sqrt().plus(n),k=!0,r.precision=e,r.rounding=t,n.ln())};d.inverseHyperbolicTangent=d.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?T(new i(o),e,t,!0):(i.precision=n=r-o.e,o=E(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)};d.inverseSine=d.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=H(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)))};d.inverseTangent=d.atan=function(){var e,t,n,r,o,i,s,a,c,u=this,l=u.constructor,f=l.precision,p=l.rounding;if(u.isFinite()){if(u.isZero())return new l(u);if(u.abs().eq(1)&&f+4<=ct)return s=H(l,f+4,p).times(.25),s.s=u.s,s}else{if(!u.s)return new l(NaN);if(f+4<=ct)return s=H(l,f+4,p).times(.5),s.s=u.s,s}for(l.precision=a=f+10,l.rounding=1,n=Math.min(28,a/A+2|0),e=n;e;--e)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(k=!1,t=Math.ceil(a/A),r=1,c=u.times(u),s=new l(u),o=u;e!==-1;)if(o=o.times(c),i=s.minus(o.div(r+=2)),o=o.times(c),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)),k=!0,T(s,l.precision=f,l.rounding=p,!0)};d.isFinite=function(){return!!this.d};d.isInteger=d.isInt=function(){return!!this.d&&q(this.e/A)>this.d.length-2};d.isNaN=function(){return!this.s};d.isNegative=d.isNeg=function(){return this.s<0};d.isPositive=d.isPos=function(){return this.s>0};d.isZero=function(){return!!this.d&&this.d[0]===0};d.lessThan=d.lt=function(e){return this.cmp(e)<0};d.lessThanOrEqualTo=d.lte=function(e){return this.cmp(e)<1};d.logarithm=d.log=function(e){var t,n,r,o,i,s,a,c,u=this,l=u.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=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(t)if(n.length>1)i=!0;else{for(o=n[0];o%10===0;)o/=10;i=o!==1}if(k=!1,a=f+m,s=ne(u,a),r=t?Ke(l,a+10):ne(e,a),c=E(s,r,a,1),ye(c.d,o=f,p))do if(a+=10,s=ne(u,a),r=t?Ke(l,a+10):ne(e,a),c=E(s,r,a,1),!i){+F(c.d).slice(o+1,o+15)+1==1e14&&(c=T(c,f+1,0));break}while(ye(c.d,o+=10,p));return k=!0,T(c,f,p)};d.minus=d.sub=function(e){var t,n,r,o,i,s,a,c,u,l,f,p,m=this,w=m.constructor;if(e=new w(e),!m.d||!e.d)return!m.s||!e.s?e=new w(NaN):m.d?e.s=-e.s:e=new w(e.d||m.s!==e.s?m:NaN),e;if(m.s!=e.s)return e.s=-e.s,m.plus(e);if(u=m.d,p=e.d,a=w.precision,c=w.rounding,!u[0]||!p[0]){if(p[0])e.s=-e.s;else if(u[0])e=new w(m);else return new w(c===3?-0:0);return k?T(e,a,c):e}if(n=q(e.e/A),l=q(m.e/A),u=u.slice(),i=l-n,i){for(f=i<0,f?(t=u,i=-i,s=p.length):(t=p,n=l,s=u.length),r=Math.max(Math.ceil(a/A),s)+2,i>r&&(i=r,t.length=1),t.reverse(),r=i;r--;)t.push(0);t.reverse()}else{for(r=u.length,s=p.length,f=r<s,f&&(s=r),r=0;r<s;r++)if(u[r]!=p[r]){f=u[r]<p[r];break}i=0}for(f&&(t=u,u=p,p=t,e.s=-e.s),s=u.length,r=p.length-s;r>0;--r)u[s++]=0;for(r=p.length;r>i;){if(u[--r]<p[r]){for(o=r;o&&u[--o]===0;)u[o]=j-1;--u[o],u[r]+=j}u[r]-=p[r]}for(;u[--s]===0;)u.pop();for(;u[0]===0;u.shift())--n;return u[0]?(e.d=u,e.e=ve(u,n),k?T(e,a,c):e):new w(c===3?-0:0)};d.modulo=d.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]?T(new r(n),r.precision,r.rounding):(k=!1,r.modulo==9?(t=E(n,e.abs(),0,3,1),t.s*=e.s):t=E(n,e,0,r.modulo,1),t=t.times(e),k=!0,n.minus(t))};d.naturalExponential=d.exp=function(){return ut(this)};d.naturalLogarithm=d.ln=function(){return ne(this)};d.negated=d.neg=function(){var e=new this.constructor(this);return e.s=-e.s,T(e)};d.plus=d.add=function(e){var t,n,r,o,i,s,a,c,u,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(u=f.d,l=e.d,a=p.precision,c=p.rounding,!u[0]||!l[0])return l[0]||(e=new p(f)),k?T(e,a,c):e;if(i=q(f.e/A),r=q(e.e/A),u=u.slice(),o=i-r,o){for(o<0?(n=u,o=-o,s=l.length):(n=l,r=i,s=u.length),i=Math.ceil(a/A),s=i>s?i+1:s+1,o>s&&(o=s,n.length=1),n.reverse();o--;)n.push(0);n.reverse()}for(s=u.length,o=l.length,s-o<0&&(o=s,n=l,l=u,u=n),t=0;o;)t=(u[--o]=u[o]+l[o]+t)/j|0,u[o]%=j;for(t&&(u.unshift(t),++r),s=u.length;u[--s]==0;)u.pop();return e.d=u,e.e=ve(u,r),k?T(e,a,c):e};d.precision=d.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(re+e);return n.d?(t=Ht(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};d.round=function(){var e=this,t=e.constructor;return T(new t(e),e.e+1,t.rounding)};d.sine=d.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())+A,r.rounding=1,n=On(r,Zt(r,n)),r.precision=e,r.rounding=t,T(X>2?n.neg():n,e,t,!0)):new r(NaN)};d.squareRoot=d.sqrt=function(){var e,t,n,r,o,i,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(k=!1,u=Math.sqrt(+s),u==0||u==1/0?(t=F(a),(t.length+c)%2==0&&(t+="0"),u=Math.sqrt(t),c=q((c+1)/2)-(c<0||c%2),u==1/0?t="5e"+c:(t=u.toExponential(),t=t.slice(0,t.indexOf("e")+1)+c),r=new l(t)):r=new l(u.toString()),n=(c=l.precision)+3;;)if(i=r,r=i.plus(E(s,i,n+2,1)).times(.5),F(i.d).slice(0,n)===(t=F(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t=="9999"||!o&&t=="4999"){if(!o&&(T(i,c+1,0),i.times(i).eq(s))){r=i;break}n+=4,o=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(T(r,c+1,1),e=!r.times(r).eq(s));break}return k=!0,T(r,c,l.rounding,e)};d.tangent=d.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=E(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,T(X==2||X==4?n.neg():n,e,t,!0)):new r(NaN)};d.times=d.mul=function(e){var t,n,r,o,i,s,a,c,u,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=q(l.e/A)+q(e.e/A),c=p.length,u=m.length,c<u&&(i=p,p=m,m=i,s=c,c=u,u=s),i=[],s=c+u,r=s;r--;)i.push(0);for(r=u;--r>=0;){for(t=0,o=c+r;o>r;)a=i[o]+m[r]*p[o-r-1]+t,i[o--]=a%j|0,t=a/j|0;i[o]=(i[o]+t)%j|0}for(;!i[--s];)i.pop();return t?++n:i.shift(),e.d=i,e.e=ve(i,n),k?T(e,f.precision,f.rounding):e};d.toBinary=function(e,t){return ft(this,2,e,t)};d.toDecimalPlaces=d.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(G(e,0,oe),t===void 0?t=r.rounding:G(t,0,8),T(n,e+n.e+1,t))};d.toExponential=function(e,t){var n,r=this,o=r.constructor;return e===void 0?n=Z(r,!0):(G(e,0,oe),t===void 0?t=o.rounding:G(t,0,8),r=T(new o(r),e+1,t),n=Z(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};d.toFixed=function(e,t){var n,r,o=this,i=o.constructor;return e===void 0?n=Z(o):(G(e,0,oe),t===void 0?t=i.rounding:G(t,0,8),r=T(new i(o),e+o.e+1,t),n=Z(r,!1,e+r.e+1)),o.isNeg()&&!o.isZero()?"-"+n:n};d.toFraction=function(e){var t,n,r,o,i,s,a,c,u,l,f,p,m=this,w=m.d,h=m.constructor;if(!w)return new h(m);if(u=n=new h(1),r=c=new h(0),t=new h(r),i=t.e=Ht(w)-m.e-1,s=i%A,t.d[0]=O(10,s<0?A+s:s),e==null)e=i>0?t:u;else{if(a=new h(e),!a.isInt()||a.lt(u))throw Error(re+a);e=a.gt(t)?i>0?t:u:a}for(k=!1,a=new h(F(w)),l=h.precision,h.precision=i=w.length*A*2;f=E(a,t,0,1,1),o=n.plus(f.times(r)),o.cmp(e)!=1;)n=r,r=o,o=u,u=c.plus(f.times(o)),c=o,o=t,t=a.minus(f.times(o)),a=o;return o=E(e.minus(n),r,0,1,1),c=c.plus(o.times(u)),n=n.plus(o.times(r)),c.s=u.s=m.s,p=E(u,r,i,1).minus(m).abs().cmp(E(c,n,i,1).minus(m).abs())<1?[u,r]:[c,n],h.precision=l,k=!0,p};d.toHexadecimal=d.toHex=function(e,t){return ft(this,16,e,t)};d.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:G(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]?(k=!1,n=E(n,e,0,t,1).times(e),k=!0,T(n)):(e.s=n.s,n=e),n};d.toNumber=function(){return+this};d.toOctal=function(e,t){return ft(this,8,e,t)};d.toPower=d.pow=function(e){var t,n,r,o,i,s,a=this,c=a.constructor,u=+(e=new c(e));if(!a.d||!e.d||!a.d[0]||!e.d[0])return new c(O(+a,u));if(a=new c(a),a.eq(1))return a;if(r=c.precision,i=c.rounding,e.eq(1))return T(a,r,i);if(t=q(e.e/A),t>=e.d.length-1&&(n=u<0?-u:u)<=Rn)return o=jt(c,a,n,r),e.s<0?new c(1).div(o):T(o,r,i);if(s=a.s,s<0){if(t<e.d.length-1)return new c(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=O(+a,u),t=n==0||!isFinite(n)?q(u*(Math.log("0."+F(a.d))/Math.LN10+a.e+1)):new c(n+"").e,t>c.maxE+1||t<c.minE-1?new c(t>0?s/0:0):(k=!1,c.rounding=a.s=1,n=Math.min(12,(t+"").length),o=ut(e.times(ne(a,r+n)),r),o.d&&(o=T(o,r+5,1),ye(o.d,r,i)&&(t=r+10,o=T(ut(e.times(ne(a,t+n)),t),t+5,1),+F(o.d).slice(r+1,r+15)+1==1e14&&(o=T(o,r+1,0)))),o.s=s,k=!0,c.rounding=i,T(o,r,i))};d.toPrecision=function(e,t){var n,r=this,o=r.constructor;return e===void 0?n=Z(r,r.e<=o.toExpNeg||r.e>=o.toExpPos):(G(e,1,oe),t===void 0?t=o.rounding:G(t,0,8),r=T(new o(r),e,t),n=Z(r,e<=r.e||r.e<=o.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};d.toSignificantDigits=d.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(G(e,1,oe),t===void 0?t=r.rounding:G(t,0,8)),T(new r(n),e,t)};d.toString=function(){var e=this,t=e.constructor,n=Z(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};d.truncated=d.trunc=function(){return T(new this.constructor(this),this.e+1,1)};d.valueOf=d.toJSON=function(){var e=this,t=e.constructor,n=Z(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function F(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=A-r.length,n&&(i+=te(n)),i+=r;s=e[t],r=s+"",n=A-r.length,n&&(i+=te(n))}else if(s===0)return"0";for(;s%10===0;)s/=10;return i+s}function G(e,t,n){if(e!==~~e||e<t||e>n)throw Error(re+e)}function ye(e,t,n,r){var o,i,s,a;for(i=e[0];i>=10;i/=10)--t;return--t<0?(t+=A,o=0):(o=Math.ceil((t+1)/A),t%=A),i=O(10,A-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)==O(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)==O(10,t-3)-1,s}function Re(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]+=st.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 Dn(e,t){var n,r,o;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),o=(1/Fe(4,n)).toString()):(n=16,o="2.3283064365386962890625e-10"),e.precision+=n,t=pe(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 E=function(){function e(r,o,i){var s,a=0,c=r.length;for(r=r.slice();c--;)s=r[c]*o+a,r[c]=s%i|0,a=s/i|0;return a&&r.unshift(a),r}function t(r,o,i,s){var a,c;if(i!=s)c=i>s?1:-1;else for(a=c=0;a<i;a++)if(r[a]!=o[a]){c=r[a]>o[a]?1:-1;break}return c}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,c){var u,l,f,p,m,w,h,x,b,y,g,P,C,I,N,D,K,$,V,ce,ue=r.constructor,be=r.s==o.s?1:-1,U=r.d,_=o.d;if(!U||!U[0]||!_||!_[0])return new ue(!r.s||!o.s||(U?_&&U[0]==_[0]:!_)?NaN:U&&U[0]==0||!_?be*0:be/0);for(c?(m=1,l=r.e-o.e):(c=j,m=A,l=q(r.e/m)-q(o.e/m)),V=_.length,K=U.length,b=new ue(be),y=b.d=[],f=0;_[f]==(U[f]||0);f++);if(_[f]>(U[f]||0)&&l--,i==null?(I=i=ue.precision,s=ue.rounding):a?I=i+(r.e-o.e)+1:I=i,I<0)y.push(1),w=!0;else{if(I=I/m+2|0,f=0,V==1){for(p=0,_=_[0],I++;(f<K||p)&&I--;f++)N=p*c+(U[f]||0),y[f]=N/_|0,p=N%_|0;w=p||f<K}else{for(p=c/(_[0]+1)|0,p>1&&(_=e(_,p,c),U=e(U,p,c),V=_.length,K=U.length),D=V,g=U.slice(0,V),P=g.length;P<V;)g[P++]=0;ce=_.slice(),ce.unshift(0),$=_[0],_[1]>=c/2&&++$;do p=0,u=t(_,g,V,P),u<0?(C=g[0],V!=P&&(C=C*c+(g[1]||0)),p=C/$|0,p>1?(p>=c&&(p=c-1),h=e(_,p,c),x=h.length,P=g.length,u=t(h,g,x,P),u==1&&(p--,n(h,V<x?ce:_,x,c))):(p==0&&(u=p=1),h=_.slice()),x=h.length,x<P&&h.unshift(0),n(g,h,P,c),u==-1&&(P=g.length,u=t(_,g,V,P),u<1&&(p++,n(g,V<P?ce:_,P,c))),P=g.length):u===0&&(p++,g=[0]),y[f++]=p,u&&g[0]?g[P++]=U[D]||0:(g=[U[D]],P=1);while((D++<K||g[0]!==void 0)&&I--);w=g[0]!==void 0}y[0]||y.shift()}if(m==1)b.e=l,Vt=w;else{for(f=1,p=y[0];p>=10;p/=10)f++;b.e=f+l*m-1,T(b,a?i+b.e+1:i,s,w)}return b}}();function T(e,t,n,r){var o,i,s,a,c,u,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+=A,s=t,l=f[p=0],c=l/O(10,o-s-1)%10|0;else if(p=Math.ceil((i+1)/A),a=f.length,p>=a)if(r){for(;a++<=p;)f.push(0);l=c=0,o=1,i%=A,s=i-A+1}else break e;else{for(l=a=f[p],o=1;a>=10;a/=10)o++;i%=A,s=i-A+o,c=s<0?0:l/O(10,o-s-1)%10|0}if(r=r||t<0||f[p+1]!==void 0||(s<0?l:l%O(10,o-s-1)),u=n<4?(c||r)&&(n==0||n==(e.s<0?3:2)):c>5||c==5&&(n==4||r||n==6&&(i>0?s>0?l/O(10,o-s):0:f[p-1])%10&1||n==(e.s<0?8:7)),t<1||!f[0])return f.length=0,u?(t-=e.e+1,f[0]=O(10,(A-t%A)%A),e.e=-t||0):f[0]=e.e=0,e;if(i==0?(f.length=p,a=1,p--):(f.length=p+1,a=O(10,A-i),f[p]=s>0?(l/O(10,o-s)%O(10,s)|0)*a:0),u)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]==j&&(f[0]=1));break}else{if(f[p]+=a,f[p]!=j)break;f[p--]=0,a=1}for(i=f.length;f[--i]===0;)f.pop()}return k&&(e.e>m.maxE?(e.d=null,e.e=NaN):e.e<m.minE&&(e.e=0,e.d=[0])),e}function Z(e,t,n){if(!e.isFinite())return Yt(e);var r,o=e.e,i=F(e.d),s=i.length;return t?(n&&(r=n-s)>0?i=i.charAt(0)+"."+i.slice(1)+te(r):s>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(e.e<0?"e":"e+")+e.e):o<0?(i="0."+te(-o-1)+i,n&&(r=n-s)>0&&(i+=te(r))):o>=s?(i+=te(o+1-s),n&&(r=n-o-1)>0&&(i=i+"."+te(r))):((r=o+1)<s&&(i=i.slice(0,r)+"."+i.slice(r)),n&&(r=n-s)>0&&(o+1===s&&(i+="."),i+=te(r))),i}function ve(e,t){var n=e[0];for(t*=A;n>=10;n/=10)t++;return t}function Ke(e,t,n){if(t>Mn)throw k=!0,n&&(e.precision=n),Error(Ut);return T(new e(Me),t,1,!0)}function H(e,t,n){if(t>ct)throw Error(Ut);return T(new e(De),t,n,!0)}function Ht(e){var t=e.length-1,n=t*A+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 te(e){for(var t="";e--;)t+="0";return t}function jt(e,t,n,r){var o,i=new e(1),s=Math.ceil(r/A+4);for(k=!1;;){if(n%2&&(i=i.times(t),vt(i.d,s)&&(o=!0)),n=q(n/2),n===0){n=i.d.length-1,o&&i.d[n]===0&&++i.d[n];break}t=t.times(t),vt(t.d,s)}return k=!0,i}function Ot(e){return e.d[e.d.length-1]&1}function zt(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 ut(e,t){var n,r,o,i,s,a,c,u=0,l=0,f=0,p=e.constructor,m=p.rounding,w=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?(k=!1,c=w):c=t,a=new p(.03125);e.e>-2;)e=e.times(a),f+=5;for(r=Math.log(O(2,f))/Math.LN10*2+5|0,c+=r,n=i=s=new p(1),p.precision=c;;){if(i=T(i.times(e),c,1),n=n.times(++l),a=s.plus(E(i,n,c,1)),F(a.d).slice(0,c)===F(s.d).slice(0,c)){for(o=f;o--;)s=T(s.times(s),c,1);if(t==null)if(u<3&&ye(s.d,c-r,m,u))p.precision=c+=10,n=i=a=new p(1),l=0,u++;else return T(s,p.precision=w,m,k=!0);else return p.precision=w,s}s=a}}function ne(e,t){var n,r,o,i,s,a,c,u,l,f,p,m=1,w=10,h=e,x=h.d,b=h.constructor,y=b.rounding,g=b.precision;if(h.s<0||!x||!x[0]||!h.e&&x[0]==1&&x.length==1)return new b(x&&!x[0]?-1/0:h.s!=1?NaN:x?0:h);if(t==null?(k=!1,l=g):l=t,b.precision=l+=w,n=F(x),r=n.charAt(0),Math.abs(i=h.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)h=h.times(e),n=F(h.d),r=n.charAt(0),m++;i=h.e,r>1?(h=new b("0."+n),i++):h=new b(r+"."+n.slice(1))}else return u=Ke(b,l+2,g).times(i+""),h=ne(new b(r+"."+n.slice(1)),l-w).plus(u),b.precision=g,t==null?T(h,g,y,k=!0):h;for(f=h,c=s=h=E(h.minus(1),h.plus(1),l,1),p=T(h.times(h),l,1),o=3;;){if(s=T(s.times(p),l,1),u=c.plus(E(s,new b(o),l,1)),F(u.d).slice(0,l)===F(c.d).slice(0,l))if(c=c.times(2),i!==0&&(c=c.plus(Ke(b,l+2,g).times(i+""))),c=E(c,new b(m),l,1),t==null)if(ye(c.d,l-w,y,a))b.precision=l+=w,u=s=h=E(f.minus(1),f.plus(1),l,1),p=T(h.times(h),l,1),o=a=1;else return T(c,b.precision=g,y,k=!0);else return b.precision=g,c;c=u,o+=2}}function Yt(e){return String(e.s*e.s/0)}function lt(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)%A,n<0&&(r+=A),r<o){for(r&&e.d.push(+t.slice(0,r)),o-=A;r<o;)e.d.push(+t.slice(r,r+=A));t=t.slice(r),r=A-t.length}else r-=o;for(;r--;)t+="0";e.d.push(+t),k&&(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 Kn(e,t){var n,r,o,i,s,a,c,u,l;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),Gt.test(t))return lt(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(En.test(t))n=16,t=t.toLowerCase();else if(Nn.test(t))n=2;else if(_n.test(t))n=8;else throw Error(re+t);for(i=t.search(/p/i),i>0?(c=+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=jt(r,new r(n),i,i*2)),u=Re(t,n,j),l=u.length-1,i=l;u[i]===0;--i)u.pop();return i<0?new r(e.s*0):(e.e=ve(u,l),e.d=u,k=!1,s&&(e=E(e,o,a*4)),c&&(e=e.times(Math.abs(c)<54?O(2,c):Ve.pow(2,c))),k=!0,e)}function On(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:pe(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/Fe(5,n)),t=pe(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 pe(e,t,n,r,o){var i,s,a,c,u=1,l=e.precision,f=Math.ceil(l/A);for(k=!1,c=n.times(n),a=new e(r);;){if(s=E(a.times(c),new e(t++*t++),l,1),a=o?r.plus(s):r.minus(s),r=E(s.times(c),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,u++}return k=!0,s.d.length=f+1,s}function Fe(e,t){for(var n=e;--t;)n*=e;return n}function Zt(e,t){var n,r=t.s<0,o=H(e,e.precision,1),i=o.times(.5);if(t=t.abs(),t.lte(i))return X=r?4:1,t;if(n=t.divToInt(o),n.isZero())X=r?3:2;else{if(t=t.minus(n.times(o)),t.lte(i))return X=Ot(n)?r?2:3:r?4:1,t;X=Ot(n)?r?1:4:r?3:2}return t.minus(o).abs()}function ft(e,t,n,r){var o,i,s,a,c,u,l,f,p,m=e.constructor,w=n!==void 0;if(w?(G(n,1,oe),r===void 0?r=m.rounding:G(r,0,8)):(n=m.precision,r=m.rounding),!e.isFinite())l=Yt(e);else{for(l=Z(e),s=l.indexOf("."),w?(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=Re(Z(p),10,o),p.e=p.d.length),f=Re(l,10,o),i=c=f.length;f[--c]==0;)f.pop();if(!f[0])l=w?"0p+0":"0";else{if(s<0?i--:(e=new m(e),e.d=f,e.e=i,e=E(e,p,n,r,0,o),f=e.d,i=e.e,u=Vt),s=f[n],a=o/2,u=u||f[n+1]!==void 0,u=r<4?(s!==void 0||u)&&(r===0||r===(e.s<0?3:2)):s>a||s===a&&(r===4||u||r===6&&f[n-1]&1||r===(e.s<0?8:7)),f.length=n,u)for(;++f[--n]>o-1;)f[n]=0,n||(++i,f.unshift(1));for(c=f.length;!f[c-1];--c);for(s=0,l="";s<c;s++)l+=st.charAt(f[s]);if(w){if(c>1)if(t==16||t==8){for(s=t==16?4:3,--c;c%s;c++)l+="0";for(f=Re(l,o,t),c=f.length;!f[c-1];--c);for(s=1,l="1.";s<c;s++)l+=st.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>c)for(i-=c;i--;)l+="0";else i<c&&(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 vt(e,t){if(e.length>t)return e.length=t,!0}function vn(e){return new this(e).abs()}function Fn(e){return new this(e).acos()}function Vn(e){return new this(e).acosh()}function Un(e,t){return new this(e).plus(t)}function Wn(e){return new this(e).asin()}function qn(e){return new this(e).asinh()}function Gn(e){return new this(e).atan()}function Hn(e){return new this(e).atanh()}function jn(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=H(this,i,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?H(this,r,o):new this(0),n.s=e.s):!e.d||t.isZero()?(n=H(this,i,1).times(.5),n.s=e.s):t.s<0?(this.precision=i,this.rounding=1,n=this.atan(E(e,t,i,1)),t=H(this,i,1),this.precision=r,this.rounding=o,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(E(e,t,i,1)),n}function zn(e){return new this(e).cbrt()}function Yn(e){return T(e=new this(e),e.e+1,2)}function Zn(e,t,n){return new this(e).clamp(t,n)}function Xn(e){if(!e||typeof e!="object")throw Error(Oe+"Object expected");var t,n,r,o=e.defaults===!0,i=["precision",1,oe,"rounding",0,8,"toExpNeg",-fe,0,"toExpPos",0,fe,"maxE",0,fe,"minE",-fe,0,"modulo",0,9];for(t=0;t<i.length;t+=3)if(n=i[t],o&&(this[n]=at[n]),(r=e[n])!==void 0)if(q(r)===r&&r>=i[t+1]&&r<=i[t+2])this[n]=r;else throw Error(re+n+": "+r);if(n="crypto",o&&(this[n]=at[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(Wt);else this[n]=!1;else throw Error(re+n+": "+r);return this}function Qn(e){return new this(e).cos()}function Jn(e){return new this(e).cosh()}function Xt(e){var t,n,r;function o(i){var s,a,c,u=this;if(!(u instanceof o))return new o(i);if(u.constructor=o,Ft(i)){u.s=i.s,k?!i.d||i.e>o.maxE?(u.e=NaN,u.d=null):i.e<o.minE?(u.e=0,u.d=[0]):(u.e=i.e,u.d=i.d.slice()):(u.e=i.e,u.d=i.d?i.d.slice():i.d);return}if(c=typeof i,c==="number"){if(i===0){u.s=1/i<0?-1:1,u.e=0,u.d=[0];return}if(i<0?(i=-i,u.s=-1):u.s=1,i===~~i&&i<1e7){for(s=0,a=i;a>=10;a/=10)s++;k?s>o.maxE?(u.e=NaN,u.d=null):s<o.minE?(u.e=0,u.d=[0]):(u.e=s,u.d=[i]):(u.e=s,u.d=[i]);return}else if(i*0!==0){i||(u.s=NaN),u.e=NaN,u.d=null;return}return lt(u,i.toString())}else if(c!=="string")throw Error(re+i);return(a=i.charCodeAt(0))===45?(i=i.slice(1),u.s=-1):(a===43&&(i=i.slice(1)),u.s=1),Gt.test(i)?lt(u,i):Kn(u,i)}if(o.prototype=d,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=Xn,o.clone=Xt,o.isDecimal=Ft,o.abs=vn,o.acos=Fn,o.acosh=Vn,o.add=Un,o.asin=Wn,o.asinh=qn,o.atan=Gn,o.atanh=Hn,o.atan2=jn,o.cbrt=zn,o.ceil=Yn,o.clamp=Zn,o.cos=Qn,o.cosh=Jn,o.div=$n,o.exp=er,o.floor=tr,o.hypot=nr,o.ln=rr,o.log=or,o.log10=sr,o.log2=ir,o.max=ar,o.min=cr,o.mod=ur,o.mul=lr,o.pow=fr,o.random=pr,o.round=mr,o.sign=dr,o.sin=hr,o.sinh=gr,o.sqrt=br,o.sub=yr,o.sum=wr,o.tan=xr,o.tanh=Tr,o.trunc=Pr,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 $n(e,t){return new this(e).div(t)}function er(e){return new this(e).exp()}function tr(e){return T(e=new this(e),e.e+1,3)}function nr(){var e,t,n=new this(0);for(k=!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 k=!0,new this(1/0);n=t}return k=!0,n.sqrt()}function Ft(e){return e instanceof Ve||e&&e.toStringTag===qt||!1}function rr(e){return new this(e).ln()}function or(e,t){return new this(e).log(t)}function ir(e){return new this(e).log(2)}function sr(e){return new this(e).log(10)}function ar(){return zt(this,arguments,"lt")}function cr(){return zt(this,arguments,"gt")}function ur(e,t){return new this(e).mod(t)}function lr(e,t){return new this(e).mul(t)}function fr(e,t){return new this(e).pow(t)}function pr(e){var t,n,r,o,i=0,s=new this(1),a=[];if(e===void 0?e=this.precision:G(e,1,oe),r=Math.ceil(e/A),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(Wt);else for(;i<r;)a[i++]=Math.random()*1e7|0;for(r=a[--i],e%=A,r&&e&&(o=O(10,A-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-=A)a.shift();for(r=1,o=a[0];o>=10;o/=10)r++;r<A&&(n-=A-r)}return s.e=n,s.d=a,s}function mr(e){return T(e=new this(e),e.e+1,this.rounding)}function dr(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function hr(e){return new this(e).sin()}function gr(e){return new this(e).sinh()}function br(e){return new this(e).sqrt()}function yr(e,t){return new this(e).sub(t)}function wr(){var e=0,t=arguments,n=new this(t[e]);for(k=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return k=!0,T(n,this.precision,this.rounding)}function xr(e){return new this(e).tan()}function Tr(e){return new this(e).tanh()}function Pr(e){return T(e=new this(e),e.e+1,1)}d[Symbol.for("nodejs.util.inspect.custom")]=d.toString;d[Symbol.toStringTag]="Decimal";var Ve=d.constructor=Xt(at);Me=new Ve(Me);De=new Ve(De);import Nr from"big.js";import Xo from"bn.js";import Ar from"toformat";var kr=Ar,we=kr;import We from"big.js";import Cr from"bn.js";import Sr from"decimal.js-light";import xe from"bn.js";var Qt=9007199254740991;function z(e){let t=W("Raydium_parseBigNumberish");if(e instanceof xe)return e;if(typeof e=="string"){if(e.match(/^-?[0-9]+$/))return new xe(e);t.logWithError(`invalid BigNumberish string: ${e}`)}return typeof e=="number"?(e%1&&t.logWithError(`BigNumberish number underflow: ${e}`),(e>=Qt||e<=-Qt)&&t.logWithError(`BigNumberish number overflow: ${e}`),new xe(String(e))):typeof e=="bigint"?new xe(e.toString()):(t.error(`invalid BigNumberish value: ${e}`),new xe(0))}var Ue=W("module/fraction"),pt=we(We),Te=we(Sr),Lr={[0]:Te.ROUND_DOWN,[1]:Te.ROUND_HALF_UP,[2]:Te.ROUND_UP},Ir={[0]:We.roundDown,[1]:We.roundHalfUp,[2]:We.roundUp},R=class{constructor(t,n=new Cr(1)){this.numerator=z(t),this.denominator=z(n)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new R(this.denominator,this.numerator)}add(t){let n=t instanceof R?t:new R(z(t));return this.denominator.eq(n.denominator)?new R(this.numerator.add(n.numerator),this.denominator):new R(this.numerator.mul(n.denominator).add(n.numerator.mul(this.denominator)),this.denominator.mul(n.denominator))}sub(t){let n=t instanceof R?t:new R(z(t));return this.denominator.eq(n.denominator)?new R(this.numerator.sub(n.numerator),this.denominator):new R(this.numerator.mul(n.denominator).sub(n.numerator.mul(this.denominator)),this.denominator.mul(n.denominator))}mul(t){let n=t instanceof R?t:new R(z(t));return new R(this.numerator.mul(n.numerator),this.denominator.mul(n.denominator))}div(t){let n=t instanceof R?t:new R(z(t));return new R(this.numerator.mul(n.denominator),this.denominator.mul(n.numerator))}toSignificant(t,n={groupSeparator:""},r=1){Number.isInteger(t)||Ue.logWithError(`${t} is not an integer.`),t<=0&&Ue.logWithError(`${t} is not positive.`),Te.set({precision:t+1,rounding:Lr[r]});let o=new Te(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)||Ue.logWithError(`${t} is not an integer.`),t<0&&Ue.logWithError(`${t} is negative.`),pt.DP=t,pt.RM=Ir[r]||1,new pt(this.numerator.toString()).div(this.denominator.toString()).toFormat(t,n)}isZero(){return this.numerator.isZero()}};var ii=W("Raydium_amount"),si=we(Nr);import{PublicKey as _r}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Jt}from"@solana/spl-token";var $t={chainId:101,address:_r.default.toBase58(),programId:Jt.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}},Q={chainId:101,address:"So11111111111111111111111111111111111111112",programId:Jt.toBase58(),decimals:9,symbol:"WSOL",name:"Wrapped SOL",logoURI:"https://img.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}};import{PublicKey as dt}from"@solana/web3.js";import{PublicKey as M,SystemProgram as en,SYSVAR_RENT_PUBKEY as Rr}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Mr}from"@solana/spl-token";function mt({pubkey:e,isSigner:t=!1,isWritable:n=!0}){return{pubkey:e,isWritable:n,isSigner:t}}var di=[mt({pubkey:Mr,isWritable:!1}),mt({pubkey:en.programId,isWritable:!1}),mt({pubkey:Rr,isWritable:!1})];function tn({publicKey:e,transformSol:t}){let n=nn(e.toString());if(n instanceof M)return t&&n.equals(Pe)?ee:n;if(t&&n.toString()===Pe.toBase58())return ee;if(typeof n=="string"){if(n===M.default.toBase58())return M.default;try{return new M(n)}catch{throw new Error("invalid public key")}}throw new Error("invalid public key")}function nn(e){try{return new M(e)}catch{return e}}var hi=new M("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),gi=new M("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),bi=new M("SysvarRent111111111111111111111111111111111"),yi=new M("SysvarC1ock11111111111111111111111111111111"),wi=new M("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),xi=new M("Sysvar1nstructions1111111111111111111111111"),Ti=en.programId,Pi=new M("2cpMA1jNS4obgRz8XNg38QuSP83L1AXpUgfxPNcvnAGj"),Ai=new M("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),ki=new M("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Bi=new M("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Ci=new M("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),Si=new M("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Li=new M("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Ii=new M("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Ni=new M("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Ei=new M("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),_i=new M("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),ee=new M("So11111111111111111111111111111111111111112"),Pe=M.default;var ht=class{constructor({mint:t,decimals:n,symbol:r,name:o,skipMint:i=!1,isToken2022:s=!1}){if(t===Pe.toBase58()||t instanceof dt&&Pe.equals(t)){this.decimals=Q.decimals,this.symbol=Q.symbol,this.name=Q.name,this.mint=new dt(Q.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?dt.default:tn({publicKey:t}),this.isToken2022=s}equals(t){return this===t?!0:this.mint.equals(t.mint)}},me=ht;me.WSOL=new ht({...Q,mint:Q.address});var gt=class{constructor({decimals:t,symbol:n="UNKNOWN",name:r="UNKNOWN"}){this.decimals=t,this.symbol=n,this.name=r}equals(t){return this===t}},qe=gt;qe.SOL=new gt($t);import Dr from"bn.js";var Gi=new R(new Dr(100));var Xi=W("Raydium_price");import{PublicKey as ms}from"@solana/web3.js";import hs from"bn.js";var Kr=new J(0),Ms=new J(1),Ds=new J(2),Ks=new J(3),Os=new J(5),Er=new J(10),vs=new J(100),Fs=new J(1e3),Vs=new J(1e4);function it(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 qr}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Gr}from"@solana/spl-token";import{ComputeBudgetProgram as an,Keypair as un,PublicKey as Or,Transaction as ln,TransactionMessage as vr,VersionedTransaction as fn}from"@solana/web3.js";var v={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",FarmV5Deposit:"FarmV5Deposit",FarmV5Withdraw:"FarmV5Withdraw",FarmV5CreateLedger:"FarmV5CreateLedger",FarmV6Deposit:"FarmV6Deposit",FarmV6Withdraw:"FarmV6Withdraw",FarmV6Create:"FarmV6Create",FarmV6Restart:"FarmV6Restart",FarmV6CreatorAddReward:"FarmV6CreatorAddReward",FarmV6CreatorWithdraw:"FarmV6CreatorWithdraw",CpmmCreatePool:"CpmmCreatePool",CpmmCreateConfig:"CpmmCreateConfig",CpmmAddLiquidity:"CpmmAddLiquidity",CpmmWithdrawLiquidity:"CpmmWithdrawLiquidity",CpmmSwapBaseIn:"CpmmSwapBaseIn",CpmmSwapBaseOut:"CpmmSwapBaseOut",CpmmLockLp:"CpmmLockLp",CpmmCollectLockFee:"CpmmCollectLockFee"};import{TOKEN_PROGRAM_ID as Fr}from"@solana/spl-token";var cn=W("Raydium_txUtil"),pn=1644;function Ge(e){let t=[],n=[];return e.microLamports&&(t.push(an.setComputeUnitPrice({microLamports:e.microLamports})),n.push(v.SetComputeUnitPrice)),e.units&&(t.push(an.setComputeUnitLimit({units:e.units})),n.push(v.SetComputeUnitLimit)),{instructions:t,instructionTypes:n}}async function de(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 He(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(i.err.toString())},"confirmed")})}function Vr(e,t){e.length<1&&cn.logWithError(`no instructions provided: ${e.toString()}`),t.length<1&&cn.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<pn}catch{return!1}}function mn(e,t){let[n,r]=Or.findProgramAddressSync(e,t);return{publicKey:n,nonce:r}}function Ae({instructions:e,payer:t,signers:n}){return Vr(e,[t,...n])}function ke({instructions:e,payer:t,lookupTableAddressAccount:n,recentBlockhash:r=un.generate().publicKey.toString()}){let i=new vr({payerKey:t,recentBlockhash:r,instructions:e}).compileToV0Message(Object.values(n!=null?n:{}));try{return Buffer.from(new fn(i).serialize()).toString("base64").length<pn}catch{return!1}}var Ur=e=>Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e),Wr=e=>{let t=e.serialize({requireAllSignatures:!1,verifySignatures:!1});e instanceof fn&&(t=Ur(t));try{return t instanceof Buffer?t.toString("base64"):Buffer.from(t).toString("base64")}catch{return t.toString("base64")}};function le(e){let t=[];return e.forEach(n=>{n instanceof ln&&(n.recentBlockhash||(n.recentBlockhash=Fr.toBase58()),n.feePayer||(n.feePayer=un.generate().publicKey)),t.push(Wr(n))}),console.log("simulate tx string:",t),t}function je(e,t,n){return mn([e.toBuffer(),(n!=null?n:Gr).toBuffer(),t.toBuffer()],new qr("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}import{PublicKey as B}from"@solana/web3.js";var aa=new B("EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"),ca=new B("9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z"),ua=new B("FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG"),la=new B("CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS"),fa=new B("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"),pa=new B("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),ma=new B("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"),da=new B("5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h"),ha=new B("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),ga=new B("CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"),ba=new B("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),ya=new B("kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy"),wa=new B("routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS"),xa=new B("7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"),Ta=new B("6FJon3QE27qgPVggARueB22hLvoh22VzJpXv4rBEoSLF"),Pa=new B("CC12se5To1CdEuw7fDS27B7Geo5jJyL7t5UK2B44NgiH"),Aa=new B("9HzJyW1qZsEiSfMUf6L2jo3CcTKAyBmSyKdwQeYisHrC"),ka=new B("DropEU8AvevN3UrXWXTMuz3rqnMczQVNjq3kcSdW2SQi"),Ba=new B("SNaPnpKUY656VPwbKmKT8FG4T85g4VWhRH1B4TQUfKs"),Ca=new B("9pR79Lqe6wDNjag3v8MeVYUostoXjY2ognTydor6AtEZ"),Sa=new B("DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8"),Hr=new B("4AscABy58S62owbByjUUkQfZsP7fxYH1rDYb69V58HPM"),jr=new B("7rQ1QFNosMkUCuh7Z7fPbTHvh73b68sQYdirycEzJVuw"),zr=new B("G11FKBRaAkHAKuLCgLM6K6NUc9rTjPAznRCjZifrTQe2"),La=new B("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),Yr=new B("DLockwT7X7sxtLmGH9g5kmfcjaBtncdbUmi738m5bvQC"),Ia=new B("3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH"),Zr=new B("7AFUeLVRjBfzqK3tTGw8hN48KLQWSk6DTE8xprWdPqix");var Na={SERUM_MARKET:B.default,OPENBOOK_MARKET:new B("EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj"),UTIL1216:B.default,FarmV3:new B("85BFyr98MbCUU9MVTEgzx1nbhWACbJqLzho6zd6DZcWL"),FarmV5:new B("EcLzTrNg9V7qhcdyXDe2qjtPkiGzDM2UbdRaeaadU5r2"),FarmV6:new B("Farm2hJLcqPtPg8M4rR6DMrsRNc5TPm5Cs4bVQrMe2T7"),AmmV4:new B("HWy1jotHpo6UqeQxx49dpYYdQB8wj9Qk9MdxwjLvDHB8"),AmmStable:new B("DDg4VmQaJV9ogWce7LpcjBA9bv22wRp5uaTPa5pGjijF"),CLMM:new B("devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH"),CLMM_LOCK_PROGRAM_ID:new B("DLockwT7X7sxtLmGH9g5kmfcjaBtncdbUmi738m5bvQC"),CLMM_LOCK_AUTH_ID:new B("8qmHNvu2Kr2C7U8mJL4Vz1vTDxMhVuXKREwU7TNoaVEo"),Router:new B("BVChZ3XFEwTMUk1o9i3HAf91H6mFxSwa5X2wFAWhYPhU"),CREATE_CPMM_POOL_PROGRAM:Hr,CREATE_CPMM_POOL_AUTH:jr,CREATE_CPMM_POOL_FEE_ACC:zr,FEE_DESTINATION_ID:new B("3XMrhbv989VxAMi3DErLV9eJht1pHppW5LbKxe9fkEFR"),LOCK_CPMM_PROGRAM:Yr,LCOK_CPMM_AUTH:Zr};import Ra from"bn.js";import{PublicKey as dn,AddressLookupTableAccount as ze}from"@solana/web3.js";async function bt({connection:e,address:t}){let n=await Kt(e,[...new Set(t.map(o=>o.toString()))].map(o=>new dn(o))),r={};for(let o=0;o<t.length;o++){let i=n[o],s=t[o];if(!i)continue;let a=new ze({key:s,state:ze.deserialize(i.data)});r[s.toString()]=a,Ye[s.toString()]=a}return r}var Ye={"2immgwYNHBbyVQKVGCEkgWpi53bLwWNRMB5G2nbgYV17":new ze({key:new dn("2immgwYNHBbyVQKVGCEkgWpi53bLwWNRMB5G2nbgYV17"),state:ze.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 Be,sendAndConfirmTransaction as yt,Transaction as Ce,TransactionMessage as Se,VersionedTransaction as Le}from"@solana/web3.js";import Xr from"axios";var Ze=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.api=t.api}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 Xr.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}=Ge(t);return this.instructions.unshift(...n),this.instructionTypes.unshift(...r),!0}return!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!==Be.default.toString())),this}async versionBuild({txVersion:t,extInfo:n}){return t===0?await this.buildV0({...n||{}}):this.build(n)}build(t){var r;let n=new Ce;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 u;let{recentBlockHash:i,skipPreflight:s=!0,sendAndConfirm:a}=o||{},c=i!=null?i:await de(this.connection,this.blockhashCommitment);if(n.recentBlockhash=c,this.signers.length&&n.sign(...this.signers),le([n]),(u=this.owner)!=null&&u.isKeyPair)return{txId:a?await yt(this.connection,n,this.signers.find(f=>f.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:t||{}}}buildMultiTx(t){var u;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)],c=[...this.instructionTypes,...i.map(l=>l.instructionTypes).flat()];return(u=this.owner)!=null&&u.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:c,execute:async l=>{var x;let{sequentially:f,onTxUpdate:p,recentBlockHash:m,skipPreflight:w=!0}=l||{},h=m!=null?m:await de(this.connection,this.blockhashCommitment);if((x=this.owner)!=null&&x.isKeyPair){if(f){let b=[];for(let y of s){let g=await yt(this.connection,y,this.signers.find(P=>P.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:w});b.push(g)}return{txIds:b,signedTxs:s}}return{txIds:await await Promise.all(s.map(async b=>(b.recentBlockhash=h,await this.connection.sendRawTransaction(b.serialize(),{skipPreflight:w})))),signedTxs:s}}if(this.signAllTransactions){let b=s.map((g,P)=>(g.recentBlockhash=h,a[P].length&&g.sign(...a[P]),g));le(b);let y=await this.signAllTransactions(b);if(f){let g=0,P=[],C=async()=>{if(!y[g])return;let I=await this.connection.sendRawTransaction(y[g].serialize(),{skipPreflight:w});P.push({txId:I,status:"sent",signedTx:y[g]}),p==null||p([...P]),g++,this.connection.onSignature(I,N=>{let D=P.findIndex(K=>K.txId===I);D>-1&&(P[D].status=N.err?"error":"success"),p==null||p([...P]),N.err||C()},"processed"),this.connection.getSignatureStatus(I)};return await C(),{txIds:P.map(I=>I.txId),signedTxs:y}}else{let g=[];for(let P=0;P<y.length;P+=1){let C=await this.connection.sendRawTransaction(y[P].serialize(),{skipPreflight:w});g.push(C)}return{txIds:g,signedTxs:y}}}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 w;let{lookupTableCache:n={},lookupTableAddress:r=[],forerunCreate:o,recentBlockhash:i,...s}=t||{},a={...this.cluster==="devnet"?{}:Ye,...n},c=Array.from(new Set([...r,...this.lookupTableAddress])),u=[];for(let h of c)a[h]===void 0&&u.push(new Be(h));let l=await bt({connection:this.connection,address:u});for(let[h,x]of Object.entries(l))a[h]=x;let f=o?Be.default.toBase58():i!=null?i:await de(this.connection,this.blockhashCommitment),p=new Se({payerKey:this.feePayer,recentBlockhash:f,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(a));((w=this.owner)==null?void 0:w.signer)&&!this.signers.some(h=>h.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let m=new Le(p);return m.sign(this.signers),{builder:this,transaction:m,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async h=>{var y;let{skipPreflight:x=!0,sendAndConfirm:b}=h||{};if(le([m]),(y=this.owner)!=null&&y.isKeyPair){let g=await this.connection.sendTransaction(m,{skipPreflight:x});return b&&await He(this.connection,g),{txId:g,signedTx:m}}if(this.signAllTransactions){let g=await this.signAllTransactions([m]);return{txId:await this.connection.sendTransaction(g[0],{skipPreflight:x}),signedTx:g[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:s||{}}}async buildV0MultiTx(t){var u;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)],c=[...this.instructionTypes,...i.map(l=>l.instructionTypes).flat()];return(u=this.owner)!=null&&u.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:c,buildProps:r,execute:async l=>{var h;let{sequentially:f,onTxUpdate:p,recentBlockHash:m,skipPreflight:w=!0}=l||{};if(m&&s.forEach(x=>x.message.recentBlockhash=m),le(s),(h=this.owner)!=null&&h.isKeyPair){if(f){let x=[];for(let b of s){let y=await this.connection.sendTransaction(b,{skipPreflight:w});await He(this.connection,y),x.push(y)}return{txIds:x,signedTxs:s}}return{txIds:await Promise.all(s.map(async x=>await this.connection.sendTransaction(x,{skipPreflight:w}))),signedTxs:s}}if(this.signAllTransactions){let x=await this.signAllTransactions(s);if(f){let b=0,y=[],g=async()=>{if(!x[b])return;let P=await this.connection.sendTransaction(x[b],{skipPreflight:w});y.push({txId:P,status:"sent",signedTx:x[b]}),p==null||p([...y]),b++,this.connection.onSignature(P,C=>{let I=y.findIndex(N=>N.txId===P);I>-1&&(y[I].status=C.err?"error":"success"),p==null||p([...y]),C.err||g()},"processed"),this.connection.getSignatureStatus(P)};return g(),{txIds:[],signedTxs:x}}else{let b=[];for(let y=0;y<x.length;y+=1){let g=await this.connection.sendTransaction(x[y],{skipPreflight:w});b.push(g)}return{txIds:b,signedTxs:x}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:r||{}}}async sizeCheckBuild(t){var u;let{computeBudgetConfig:n,...r}=t||{},o=n?Ge(n):{instructions:[],instructionTypes:[]},i=this.signers.reduce((l,f)=>({...l,[f.publicKey.toBase58()]:f}),{}),s=[],a=[],c=[];if(this.allInstructions.forEach(l=>{let f=[...c,l],p=n?[...o.instructions,...f]:f,w=[...new Set(f.map(h=>h.keys.filter(x=>x.isSigner).map(x=>x.pubkey.toString())).flat()).values()].map(h=>new Be(h));if(c.length<12&&Ae({instructions:p,payer:this.feePayer,signers:w})||Ae({instructions:f,payer:this.feePayer,signers:w}))c.push(l);else{if(c.length===0)throw Error("item ins too big");Ae({instructions:n?[...o.instructions,...c]:[...c],payer:this.feePayer,signers:w})?s.push(new Ce().add(...o.instructions,...c)):s.push(new Ce().add(...c)),a.push(Array.from(new Set(c.map(h=>h.keys.filter(x=>x.isSigner).map(x=>x.pubkey.toString())).flat())).map(h=>i[h]).filter(h=>h!==void 0)),c=[l]}}),c.length>0){let f=[...new Set(c.map(p=>p.keys.filter(m=>m.isSigner).map(m=>m.pubkey.toString())).flat()).values()].map(p=>i[p]).filter(p=>p!==void 0);Ae({instructions:n?[...o.instructions,...c]:[...c],payer:this.feePayer,signers:f.map(p=>p.publicKey)})?s.push(new Ce().add(...o.instructions,...c)):s.push(new Ce().add(...c)),a.push(f)}return s.forEach(l=>l.feePayer=this.feePayer),(u=this.owner)!=null&&u.signer&&a.forEach(l=>{l.some(f=>f.publicKey.equals(this.owner.publicKey))||l.push(this.owner.signer)}),{builder:this,transactions:s,signers:a,instructionTypes:this.instructionTypes,execute:async l=>{var x;let{sequentially:f,onTxUpdate:p,recentBlockHash:m,skipPreflight:w=!0}=l||{},h=m!=null?m:await de(this.connection,this.blockhashCommitment);if(s.forEach(async(b,y)=>{b.recentBlockhash=h,a[y].length&&b.sign(...a[y])}),le(s),(x=this.owner)!=null&&x.isKeyPair){if(f){let b=[];for(let y of s){let g=await yt(this.connection,y,this.signers.find(P=>P.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:w});b.push(g)}return{txIds:b,signedTxs:s}}return{txIds:await Promise.all(s.map(async b=>await this.connection.sendRawTransaction(b.serialize(),{skipPreflight:w}))),signedTxs:s}}if(this.signAllTransactions){let b=await this.signAllTransactions(s);if(f){let y=0,g=[],P=async()=>{if(!b[y])return;let C=await this.connection.sendRawTransaction(b[y].serialize(),{skipPreflight:w});g.push({txId:C,status:"sent",signedTx:b[y]}),p==null||p([...g]),y++,this.connection.onSignature(C,I=>{let N=g.findIndex(D=>D.txId===C);N>-1&&(g[N].status=I.err?"error":"success"),p==null||p([...g]),I.err||P()},"processed"),this.connection.getSignatureStatus(C)};return await P(),{txIds:g.map(C=>C.txId),signedTxs:b}}else{let y=[];for(let g=0;g<b.length;g+=1){let P=await this.connection.sendRawTransaction(b[g].serialize(),{skipPreflight:w});y.push(P)}return{txIds:y,signedTxs:b}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:r||{}}}async sizeCheckBuildV0(t){var x;let{computeBudgetConfig:n,lookupTableCache:r={},lookupTableAddress:o=[],...i}=t||{},s={...this.cluster==="devnet"?{}:Ye,...r},a=Array.from(new Set([...this.lookupTableAddress,...o])),c=[];for(let b of a)s[b]===void 0&&c.push(new Be(b));let u=await bt({connection:this.connection,address:c});for(let[b,y]of Object.entries(u))s[b]=y;let l=n?Ge(n):{instructions:[],instructionTypes:[]},f=await de(this.connection,this.blockhashCommitment),p=this.signers.reduce((b,y)=>({...b,[y.publicKey.toBase58()]:y}),{}),m=[],w=[],h=[];if(this.allInstructions.forEach(b=>{let y=[...h,b],g=n?[...l.instructions,...y]:y;if(h.length<12&&ke({instructions:g,payer:this.feePayer,lookupTableAddressAccount:s})||ke({instructions:y,payer:this.feePayer,lookupTableAddressAccount:s}))h.push(b);else{if(h.length===0)throw Error("item ins too big");let P={};for(let C of[...new Set(a)])s[C]!==void 0&&(P[C]=s[C]);if(n&&ke({instructions:[...l.instructions,...h],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:f})){let C=new Se({payerKey:this.feePayer,recentBlockhash:f,instructions:[...l.instructions,...h]}).compileToV0Message(Object.values(s));m.push(new Le(C))}else{let C=new Se({payerKey:this.feePayer,recentBlockhash:f,instructions:[...h]}).compileToV0Message(Object.values(s));m.push(new Le(C))}w.push(Array.from(new Set(h.map(C=>C.keys.filter(I=>I.isSigner).map(I=>I.pubkey.toString())).flat())).map(C=>p[C]).filter(C=>C!==void 0)),h=[b]}}),h.length>0){let y=[...new Set(h.map(g=>g.keys.filter(P=>P.isSigner).map(P=>P.pubkey.toString())).flat()).values()].map(g=>p[g]).filter(g=>g!==void 0);if(n&&ke({instructions:[...l.instructions,...h],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:f})){let g=new Se({payerKey:this.feePayer,recentBlockhash:f,instructions:[...l.instructions,...h]}).compileToV0Message(Object.values(s));m.push(new Le(g))}else{let g=new Se({payerKey:this.feePayer,recentBlockhash:f,instructions:[...h]}).compileToV0Message(Object.values(s));m.push(new Le(g))}w.push(y)}return(x=this.owner)!=null&&x.signer&&w.forEach(b=>{b.some(y=>y.publicKey.equals(this.owner.publicKey))||b.push(this.owner.signer)}),{builder:this,transactions:m,buildProps:t,signers:w,instructionTypes:this.instructionTypes,execute:async b=>{var I;let{sequentially:y,onTxUpdate:g,recentBlockHash:P,skipPreflight:C=!0}=b||{};if(m.map(async(N,D)=>{w[D].length&&N.sign(w[D]),P&&(N.message.recentBlockhash=P)}),le(m),(I=this.owner)!=null&&I.isKeyPair){if(y){let N=[];for(let D of m){let K=await this.connection.sendTransaction(D,{skipPreflight:C});await He(this.connection,K),N.push(K)}return{txIds:N,signedTxs:m}}return{txIds:await Promise.all(m.map(async N=>await this.connection.sendTransaction(N,{skipPreflight:C}))),signedTxs:m}}if(this.signAllTransactions){let N=await this.signAllTransactions(m);if(y){let D=0,K=[],$=async()=>{if(!N[D])return;let V=await this.connection.sendTransaction(N[D],{skipPreflight:C});K.push({txId:V,status:"sent",signedTx:N[D]}),g==null||g([...K]),D++,this.connection.onSignature(V,ce=>{let ue=K.findIndex(be=>be.txId===V);ue>-1&&(K[ue].status=ce.err?"error":"success"),g==null||g([...K]),ce.err||$()},"processed"),this.connection.getSignatureStatus(V)};return $(),{txIds:[],signedTxs:N}}else{let D=[];for(let K=0;K<N.length;K+=1){let $=await this.connection.sendTransaction(N[K],{skipPreflight:C});D.push($)}return{txIds:D,signedTxs:N}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:i||{}}}};import{AccountLayout as ge,createAssociatedTokenAccountInstruction as _t,TOKEN_PROGRAM_ID as ae,TOKEN_2022_PROGRAM_ID as yo}from"@solana/spl-token";var wt=(...e)=>e.map(t=>{try{return typeof t=="object"?JSON.stringify(t):t}catch{return t}}).join(", "),Ie=class{constructor({scope:t,moduleName:n}){this.disabled=!1;this.scope=t,this.logger=W(n)}createTxBuilder(t){return this.scope.checkOwner(),new Ze({connection:this.scope.connection,feePayer:t||this.scope.ownerPubKey,cluster:this.scope.cluster,owner:this.scope.owner,blockhashCommitment:this.scope.blockhashCommitment,api:this.scope.api,signAllTransactions:this.scope.signAllTransactions})}logDebug(...t){this.logger.debug(wt(t))}logInfo(...t){this.logger.info(wt(t))}logAndCreateError(...t){let n=wt(t);throw new Error(n)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};import{PublicKey as lo,SystemProgram as fo}from"@solana/web3.js";import po from"bn.js";import{createCloseAccountInstruction as mo,createInitializeAccountInstruction as ho,createTransferInstruction as go,TOKEN_PROGRAM_ID as he}from"@solana/spl-token";import{Keypair as so,PublicKey as kn}from"@solana/web3.js";import ao from"bn.js";import{TOKEN_PROGRAM_ID as co}from"@solana/spl-token";function Qr(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function xt(e,...t){if(!Qr(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 Tt(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 hn(e,t){xt(e);let n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var Qe=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Y=(e,t)=>e<<32-t|e>>>t;var Tc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Jr(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Pt(e){return typeof e=="string"&&(e=Jr(e)),xt(e),e}var Xe=class{clone(){return this._cloneInto()}},Pc={}.toString;function gn(e){let t=r=>e().update(Pt(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function $r(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),c=r?4:0,u=r?0:4;e.setUint32(t+c,s,r),e.setUint32(t+u,a,r)}var bn=(e,t,n)=>e&t^~e&n,yn=(e,t,n)=>e&t^e&n^t&n,Je=class extends Xe{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=Qe(this.buffer)}update(t){Tt(this);let{view:n,buffer:r,blockLen:o}=this;t=Pt(t);let i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=Qe(t);for(;o<=i-s;s+=o)this.process(c,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){Tt(this),hn(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;$r(r,o-8,BigInt(this.length*8),i),this.process(r,0);let a=Qe(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;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 eo=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]),ie=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),se=new Uint32Array(64),At=class extends Je{constructor(){super(64,32,8,!1),this.A=ie[0]|0,this.B=ie[1]|0,this.C=ie[2]|0,this.D=ie[3]|0,this.E=ie[4]|0,this.F=ie[5]|0,this.G=ie[6]|0,this.H=ie[7]|0}get(){let{A:t,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[t,n,r,o,i,s,a,c]}set(t,n,r,o,i,s,a,c){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=c|0}process(t,n){for(let f=0;f<16;f++,n+=4)se[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){let p=se[f-15],m=se[f-2],w=Y(p,7)^Y(p,18)^p>>>3,h=Y(m,17)^Y(m,19)^m>>>10;se[f]=h+se[f-7]+w+se[f-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let p=Y(a,6)^Y(a,11)^Y(a,25),m=l+p+bn(a,c,u)+eo[f]+se[f]|0,h=(Y(r,2)^Y(r,13)^Y(r,22))+yn(r,o,i)|0;l=u,u=c,c=a,a=s+m|0,s=i,i=o,o=r,r=m+h|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,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(r,o,i,s,a,c,u,l)}roundClean(){se.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var wn=gn(()=>new At);import{PublicKey as io}from"@solana/web3.js";import Tn,{isBN as Nu}from"bn.js";import{bits as Ec,BitStructure as _c,blob as to,Blob as Rc,cstr as Mc,f32 as Dc,f32be as Kc,f64 as Oc,f64be as vc,greedy as Fc,Layout as no,ns64 as Vc,ns64be as Uc,nu64 as Wc,nu64be as qc,offset as Gc,s16 as Hc,s16be as jc,s24 as zc,s24be as Yc,s32 as Zc,s32be as Xc,s40 as Qc,s40be as Jc,s48 as $c,s48be as eu,s8 as tu,seq as nu,struct as ru,Structure as ro,u16 as ou,u16be as iu,u24 as su,u24be as au,u32 as cu,u32be as uu,u40 as lu,u40be as fu,u48 as pu,u48be as mu,u8 as du,UInt as oo,union as hu,Union as gu,unionLayoutDiscriminator as bu,utf8 as yu}from"@solana/buffer-layout";var kt=no,xn=ro;var Bt=oo;var Ct=to;var St=class extends kt{constructor(n,r,o){super(n,o);this.blob=Ct(n),this.signed=r}decode(n,r=0){let o=new Tn(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 Tn(n)),this.signed&&(n=n.toTwos(this.span*8)),this.blob.encode(n.toArrayLike(Buffer,"le",this.span),r,o)}};function Pn(e){return new Bt(1,e)}function $e(e){return new Bt(4,e)}function et(e){return new St(8,!1,e)}var Lt=class extends kt{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 Ne(e){return new Lt(Ct(32),t=>new io(t),t=>t.toBuffer(),e)}var It=class extends xn{decode(t,n){return super.decode(t,n)}};function An(e,t,n){return new It(e,t,n)}var Ee=An([Ne("mint"),Ne("owner"),et("amount"),$e("delegateOption"),Ne("delegate"),Pn("state"),$e("isNativeOption"),et("isNative"),et("delegatedAmount"),$e("closeAuthorityOption"),Ne("closeAuthority")]);var Hu=W("Raydium_Util");function Bn({owner:e,solAccountResp:t,tokenAccountResp:n}){let r=[],o=[];for(let{pubkey:i,account:s}of n.value){let a=Ee.decode(s.data),{mint:c,amount:u}=a;r.push({publicKey:i,mint:c,amount:u,isAssociated:je(e,c,s.owner).publicKey.equals(i),isNative:!1,programId:s.owner}),o.push({pubkey:i,accountInfo:a,programId:s.owner})}return t&&r.push({mint:kn.default,amount:new ao(String(t.lamports)),isNative:!0,programId:t.owner}),{tokenAccounts:r,tokenAccountRawInfos:o}}function tt({fromPublicKey:e,programId:t=co}){let n=so.generate().publicKey.toBase58().slice(0,32);return{publicKey:uo(e,n,t),seed:n}}function uo(e,t,n){let r=Buffer.concat([e.toBuffer(),Buffer.from(t),n.toBuffer()]),o=wn(r);return new kn(o)}function Nt(e){let{mint:t,tokenAccount:n,owner:r,programId:o=he}=e;return ho(n,t,r,o)}function _e(e){let{tokenAccount:t,payer:n,multiSigners:r=[],owner:o,programId:i=he}=e;return mo(t,n,o,r,i)}async function Et(e){let{connection:t,amount:n,commitment:r,payer:o,owner:i,skipCloseAccount:s}=e,a=await t.getMinimumBalanceForRentExemption(Ee.span,r),c=z(n).add(new po(a)),u=tt({fromPublicKey:o,programId:he});return{addresses:{newAccount:u.publicKey},signers:[],instructions:[fo.createAccountWithSeed({fromPubkey:o,basePubkey:o,seed:u.seed,newAccountPubkey:u.publicKey,lamports:c.toNumber(),space:Ee.span,programId:he}),Nt({mint:new lo(Q.address),tokenAccount:u.publicKey,owner:i,programId:he})],instructionTypes:[v.CreateAccount,v.InitAccount],endInstructionTypes:s?[]:[v.CloseAccount],endInstructions:s?[]:[_e({tokenAccount:u.publicKey,payer:o,owner:i})]}}function Cn({source:e,destination:t,owner:n,amount:r,multiSigners:o=[],tokenProgram:i=he}){return go(e,t,n,BigInt(String(r)),o,i)}var Rt=class extends Ie{constructor(n){super(n);this._tokenAccounts=[];this._tokenAccountRawInfos=[];this._accountListener=[];this._clientOwnedToken=!1;this._accountFetchTime=0;let{tokenAccounts:r,tokenAccountRawInfos:o}=n;this._tokenAccounts=r||[],this._tokenAccountRawInfos=o||[],this._clientOwnedToken=!!(r||o)}get tokenAccounts(){return this._tokenAccounts}get tokenAccountRawInfos(){return this._tokenAccountRawInfos}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 je(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<1e3*60*3)return{tokenAccounts:this._tokenAccounts,tokenAccountRawInfos:this._tokenAccountRawInfos};this.scope.checkOwner();let o={...{},...n},[i,s,a]=await Promise.all([this.scope.connection.getAccountInfo(this.scope.ownerPubKey,o.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:ae},o.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:yo},o.commitment)]),{tokenAccounts:c,tokenAccountRawInfos:u}=Bn({owner:this.scope.ownerPubKey,solAccountResp:i,tokenAccountResp:{context:s.context,value:[...s.value,...a.value]}});return this._tokenAccounts=c,this._tokenAccountRawInfos=u,this._accountFetchTime=Date.now(),this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId),this._accountChangeListenerId=this.scope.connection.onAccountChange(this.scope.ownerPubKey,()=>this.fetchWalletTokenAccounts({forceUpdate:!0}),n==null?void 0:n.commitment),{tokenAccounts:c,tokenAccountRawInfos:u}}async getCreatedTokenAccount({mint:n,programId:r=ae,associatedOnly:o=!0}){await this.fetchWalletTokenAccounts();let i=this._tokenAccounts.filter(({mint:a})=>a==null?void 0:a.equals(n)).sort((a,c)=>a.amount.lt(c.amount)?1:-1),s=this.getAssociatedTokenAccount(n,r);for(let a of i){let{publicKey:c}=a;if(c&&(!o||o&&s.equals(c)))return c}}async getOrCreateTokenAccount(n){var w,h,x,b;await this.fetchWalletTokenAccounts();let{mint:r,createInfo:o,associatedOnly:i,owner:s,notUseTokenAccount:a=!1,skipCloseAccount:c=!1,checkCreateATAOwner:u=!1}=n,l=new nt(n.tokenProgram||ae),f=this.getAssociatedTokenAccount(r,new nt(l)),p=(a?[]:this.tokenAccountRawInfos).filter(y=>y.accountInfo.mint.equals(r)&&(!i||y.pubkey.equals(f))).sort((y,g)=>y.accountInfo.amount.lt(g.accountInfo.amount)?1:-1);if(o===void 0||p.length>0)return p.length>0?{account:p[0].pubkey}:{};let m={instructions:[],endInstructions:[],signers:[],instructionTypes:[],endInstructionTypes:[]};if(i){let y=_t(s,f,s,r,l);if(u){let g=await this.scope.connection.getAccountInfo(f);if(g===null)(w=m.instructions)==null||w.push(y),m.instructionTypes.push(v.CreateATA);else if(!(g.owner.equals(l)&&ge.decode(g.data).mint.equals(r)&&ge.decode(g.data).owner.equals(s)))throw Error(`create ata check error -> mint: ${r.toString()}, ata: ${f.toString()}`)}else m.instructions.push(y),m.instructionTypes.push(v.CreateATA);if(r.equals(ee)&&o.amount){let g=await Et({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:o.payer||this.scope.ownerPubKey,amount:(h=o.amount)!=null?h:0,skipCloseAccount:c});m.instructions.push(...g.instructions||[]),m.endInstructions.push(...g.endInstructions||[]),m.instructionTypes.push(...g.instructionTypes||[]),m.endInstructionTypes.push(...g.endInstructionTypes||[]),o.amount&&(m.instructions.push(Cn({source:g.addresses.newAccount,destination:f,owner:this.scope.ownerPubKey,amount:o.amount,tokenProgram:ae})),m.instructionTypes.push(v.TransferAmount))}return c||(m.endInstructions.push(_e({owner:s,payer:o.payer||s,tokenAccount:f,programId:l})),m.endInstructionTypes.push(v.CloseAccount)),{account:f,instructionParams:m}}else{let y=tt({fromPublicKey:s,programId:l}),g=await this.scope.connection.getMinimumBalanceForRentExemption(ge.span),P=bo.createAccountWithSeed({fromPubkey:s,basePubkey:s,seed:y.seed,newAccountPubkey:y.publicKey,lamports:g+Number((b=(x=o.amount)==null?void 0:x.toString())!=null?b:0),space:ge.span,programId:l});return m.instructions.push(P,Nt({mint:r,tokenAccount:y.publicKey,owner:this.scope.ownerPubKey,programId:l})),m.instructionTypes.push(v.CreateAccount),m.instructionTypes.push(v.InitAccount),c||(m.endInstructions.push(_e({owner:s,payer:o.payer||s,tokenAccount:y.publicKey,programId:l})),m.endInstructionTypes.push(v.CloseAccount)),{account:y.publicKey,instructionParams:m}}}async checkOrCreateAta({mint:n,programId:r=ae,autoUnwrapWSOLToSOL:o}){var c;await this.fetchWalletTokenAccounts();let i=(c=this.scope.account.tokenAccounts.find(({mint:u})=>(u==null?void 0:u.toBase58())===n.toBase58()))==null?void 0:c.publicKey,s=this.scope.ownerPubKey,a={};if(!i){let u=this.getAssociatedTokenAccount(n,r),l=await _t(s,u,s,n,r);a.instructions=[l],a.instructionTypes=[v.CreateATA],i=u}return o&&ee.toBase58()===n.toBase58()&&(a.endInstructions=[_e({owner:s,payer:s,tokenAccount:i,programId:r})],a.endInstructionTypes=[v.CloseAccount]),{pubKey:i,newInstructions:a}}async handleTokenAccount(n){let{side:r,amount:o,mint:i,programId:s=ae,tokenAccount:a,payer:c=this.scope.ownerPubKey,bypassAssociatedCheck:u,skipCloseAccount:l,checkCreateATAOwner:f}=n,p=this.getAssociatedTokenAccount(i,s);if(new nt(ee).equals(i)){let m=await Et({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:c,amount:o,skipCloseAccount:l});return{tokenAccount:m.addresses.newAccount,...m}}else if(!a||r==="out"&&!p.equals(a)&&!u){let m=[],w=_t(this.scope.ownerPubKey,p,this.scope.ownerPubKey,i,s);if(f){let h=await this.scope.connection.getAccountInfo(p);if(h===null)m.push(w);else if(!(h.owner.equals(ae)&&ge.decode(h.data).mint.equals(i)&&ge.decode(h.data).owner.equals(this.scope.ownerPubKey)))throw Error(`create ata check error -> mint: ${i.toString()}, ata: ${p.toString()}`)}else m.push(w);return{tokenAccount:p,instructions:m,instructionTypes:[v.CreateATA]}}return{tokenAccount:a}}async processTokenAccount(n){let{mint:r,programId:o=ae,amount:i,useSOLBalance:s,handleTokenAccount:a}=n,c,u=this.createTxBuilder();if(r.equals(new nt(ee))&&s){let{tokenAccount:l,...f}=await this.handleTokenAccount({side:"in",amount:i||0,mint:r,bypassAssociatedCheck:!0,programId:o});c=l,u.addInstruction(f)}else if(c=await this.getCreatedTokenAccount({mint:r,associatedOnly:!1,programId:o}),!c&&a){let{tokenAccount:l,...f}=await this.scope.account.handleTokenAccount({side:"in",amount:0,mint:r,bypassAssociatedCheck:!0,programId:o});c=l,u.addInstruction(f)}return{tokenAccount:c,...u.AllTxData}}};export{Rt as default};
/*!
 *  decimal.js v10.4.3
 *  An arbitrary-precision Decimal type for JavaScript.
 *  https://github.com/MikeMcl/decimal.js
 *  Copyright (c) 2022 Michael Mclaughlin <M8ch88l@gmail.com>
 *  MIT Licence
 */
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
//# sourceMappingURL=account.mjs.map