snapper-sdk
Version:
An SDK for building applications on top of Snapper.
10 lines • 103 kB
JavaScript
import{PublicKey as W,SystemProgram as Hi}from"@solana/web3.js";import{createAssociatedTokenAccountInstruction as ji}from"@solana/spl-token";import{PublicKey as Kn}from"@solana/web3.js";import{get as Pr,set as Bn}from"lodash";var Lt=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 r=t.map(n=>typeof n=="object"?JSON.stringify(n):n).join(", ");throw new Error(r)}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}},Tr={},Rn={};function Q(e){let t=Pr(Tr,e);if(!t){let r=Pr(Rn,e);t=new Lt({name:e,logLevel:r}),Bn(Tr,e,t)}return t}import{MINT_SIZE as rs,TOKEN_PROGRAM_ID as ns,getTransferFeeConfig as os,unpackMint as is}from"@solana/spl-token";var Bt=Q("Raydium_accountInfo_util");async function kr(e,t,r){let{batchRequest:n,commitment:o="confirmed",chunkCount:i=100}={batchRequest:!1,...r},s=Rt(t,i),a=new Array(s.length).fill([]);if(n){let c=s.map(d=>{let f=e._buildArgs([d.map(p=>p.toBase58())],o,"base64");return{methodName:"getMultipleAccounts",args:f}}),u=Rt(c,10);a=(await(await Promise.all(u.map(async d=>await e._rpcBatchRequest(d)))).flat()).map(d=>(d.error&&Bt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${d.error.message}`),d.result.value.map(f=>{if(f){let{data:p,executable:g,lamports:m,owner:T,rentEpoch:w}=f;return p.length!==2&&p[1]!=="base64"&&Bt.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(p[0],"base64"),executable:g,lamports:m,owner:new Kn(T),rentEpoch:w}}return null})))}else try{a=await Promise.all(s.map(c=>e.getMultipleAccountsInfo(c,o)))}catch(c){c instanceof Error&&Bt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${c.message}`)}return a.flat()}import be from"bn.js";var Ee=9e15,Ae=1e9,Kt="0123456789abcdef",nt="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",ot="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Ct={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Ee,maxE:Ee,crypto:!1},Lr,me,B=!0,st="[DecimalError] ",ke=st+"Invalid argument: ",Br=st+"Precision limit exceeded",Rr=st+"crypto unavailable",Kr="[object Decimal]",ne=Math.floor,$=Math.pow,Cn=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Vn=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,En=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Cr=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,ue=1e7,S=7,Mn=9007199254740991,Nn=nt.length-1,Vt=ot.length-1,y={toStringTag:Kr};y.absoluteValue=y.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),I(e)};y.ceil=function(){return I(new this.constructor(this),this.e+1,2)};y.clampedTo=y.clamp=function(e,t){var r,n=this,o=n.constructor;if(e=new o(e),t=new o(t),!e.s||!t.s)return new o(NaN);if(e.gt(t))throw Error(ke+t);return r=n.cmp(e),r<0?e:n.cmp(t)>0?t:new o(n)};y.comparedTo=y.cmp=function(e){var t,r,n,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(n=s.length,o=a.length,t=0,r=n<o?n:o;t<r;++t)if(s[t]!==a[t])return s[t]>a[t]^c<0?1:-1;return n===o?0:n>o^c<0?1:-1};y.cosine=y.cos=function(){var e,t,r=this,n=r.constructor;return r.d?r.d[0]?(e=n.precision,t=n.rounding,n.precision=e+Math.max(r.e,r.sd())+S,n.rounding=1,r=Fn(n,Fr(n,r)),n.precision=e,n.rounding=t,I(me==2||me==3?r.neg():r,e,t,!0)):new n(1):new n(NaN)};y.cubeRoot=y.cbrt=function(){var e,t,r,n,o,i,s,a,c,u,l=this,d=l.constructor;if(!l.isFinite()||l.isZero())return new d(l);for(B=!1,i=l.s*$(l.s*l,1/3),!i||Math.abs(i)==1/0?(r=re(l.d),e=l.e,(i=(e-r.length+1)%3)&&(r+=i==1||i==-2?"0":"00"),i=$(r,1/3),e=ne((e+1)/3)-(e%3==(e<0?-1:2)),i==1/0?r="5e"+e:(r=i.toExponential(),r=r.slice(0,r.indexOf("e")+1)+e),n=new d(r),n.s=l.s):n=new d(i.toString()),s=(e=d.precision)+3;;)if(a=n,c=a.times(a).times(a),u=c.plus(l),n=G(u.plus(l).times(a),u.plus(c),s+2,1),re(a.d).slice(0,s)===(r=re(n.d)).slice(0,s))if(r=r.slice(s-3,s+1),r=="9999"||!o&&r=="4999"){if(!o&&(I(a,e+1,0),a.times(a).times(a).eq(l))){n=a;break}s+=4,o=1}else{(!+r||!+r.slice(1)&&r.charAt(0)=="5")&&(I(n,e+1,1),t=!n.times(n).times(n).eq(l));break}return B=!0,I(n,e,d.rounding,t)};y.decimalPlaces=y.dp=function(){var e,t=this.d,r=NaN;if(t){if(e=t.length-1,r=(e-ne(this.e/S))*S,e=t[e],e)for(;e%10==0;e/=10)r--;r<0&&(r=0)}return r};y.dividedBy=y.div=function(e){return G(this,new this.constructor(e))};y.dividedToIntegerBy=y.divToInt=function(e){var t=this,r=t.constructor;return I(G(t,new r(e),0,1,1),r.precision,r.rounding)};y.equals=y.eq=function(e){return this.cmp(e)===0};y.floor=function(){return I(new this.constructor(this),this.e+1,3)};y.greaterThan=y.gt=function(e){return this.cmp(e)>0};y.greaterThanOrEqualTo=y.gte=function(e){var t=this.cmp(e);return t==1||t===0};y.hyperbolicCosine=y.cosh=function(){var e,t,r,n,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;r=s.precision,n=s.rounding,s.precision=r+Math.max(i.e,i.sd())+4,s.rounding=1,o=i.d.length,o<32?(e=Math.ceil(o/3),t=(1/ut(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),i=Me(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 I(i,s.precision=r,s.rounding=n,!0)};y.hyperbolicSine=y.sinh=function(){var e,t,r,n,o=this,i=o.constructor;if(!o.isFinite()||o.isZero())return new i(o);if(t=i.precision,r=i.rounding,i.precision=t+Math.max(o.e,o.sd())+4,i.rounding=1,n=o.d.length,n<3)o=Me(i,2,o,o,!0);else{e=1.4*Math.sqrt(n),e=e>16?16:e|0,o=o.times(1/ut(5,e)),o=Me(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=r,I(o,t,r,!0)};y.hyperbolicTangent=y.tanh=function(){var e,t,r=this,n=r.constructor;return r.isFinite()?r.isZero()?new n(r):(e=n.precision,t=n.rounding,n.precision=e+7,n.rounding=1,G(r.sinh(),r.cosh(),n.precision=e,n.rounding=t)):new n(r.s)};y.inverseCosine=y.acos=function(){var e,t=this,r=t.constructor,n=t.abs().cmp(1),o=r.precision,i=r.rounding;return n!==-1?n===0?t.isNeg()?ae(r,o,i):new r(0):new r(NaN):t.isZero()?ae(r,o+4,i).times(.5):(r.precision=o+6,r.rounding=1,t=t.asin(),e=ae(r,o+4,i).times(.5),r.precision=o,r.rounding=i,e.minus(t))};y.inverseHyperbolicCosine=y.acosh=function(){var e,t,r=this,n=r.constructor;return r.lte(1)?new n(r.eq(1)?0:NaN):r.isFinite()?(e=n.precision,t=n.rounding,n.precision=e+Math.max(Math.abs(r.e),r.sd())+4,n.rounding=1,B=!1,r=r.times(r).minus(1).sqrt().plus(r),B=!0,n.precision=e,n.rounding=t,r.ln()):new n(r)};y.inverseHyperbolicSine=y.asinh=function(){var e,t,r=this,n=r.constructor;return!r.isFinite()||r.isZero()?new n(r):(e=n.precision,t=n.rounding,n.precision=e+2*Math.max(Math.abs(r.e),r.sd())+6,n.rounding=1,B=!1,r=r.times(r).plus(1).sqrt().plus(r),B=!0,n.precision=e,n.rounding=t,r.ln())};y.inverseHyperbolicTangent=y.atanh=function(){var e,t,r,n,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,n=o.sd(),Math.max(n,e)<2*-o.e-1?I(new i(o),e,t,!0):(i.precision=r=n-o.e,o=G(o.plus(1),new i(1).minus(o),r+e,1),i.precision=e+4,i.rounding=1,o=o.ln(),i.precision=e,i.rounding=t,o.times(.5))):new i(NaN)};y.inverseSine=y.asin=function(){var e,t,r,n,o=this,i=o.constructor;return o.isZero()?new i(o):(t=o.abs().cmp(1),r=i.precision,n=i.rounding,t!==-1?t===0?(e=ae(i,r+4,n).times(.5),e.s=o.s,e):new i(NaN):(i.precision=r+6,i.rounding=1,o=o.div(new i(1).minus(o.times(o)).sqrt().plus(1)).atan(),i.precision=r,i.rounding=n,o.times(2)))};y.inverseTangent=y.atan=function(){var e,t,r,n,o,i,s,a,c,u=this,l=u.constructor,d=l.precision,f=l.rounding;if(u.isFinite()){if(u.isZero())return new l(u);if(u.abs().eq(1)&&d+4<=Vt)return s=ae(l,d+4,f).times(.25),s.s=u.s,s}else{if(!u.s)return new l(NaN);if(d+4<=Vt)return s=ae(l,d+4,f).times(.5),s.s=u.s,s}for(l.precision=a=d+10,l.rounding=1,r=Math.min(28,a/S+2|0),e=r;e;--e)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(B=!1,t=Math.ceil(a/S),n=1,c=u.times(u),s=new l(u),o=u;e!==-1;)if(o=o.times(c),i=s.minus(o.div(n+=2)),o=o.times(c),s=i.plus(o.div(n+=2)),s.d[t]!==void 0)for(e=t;s.d[e]===i.d[e]&&e--;);return r&&(s=s.times(2<<r-1)),B=!0,I(s,l.precision=d,l.rounding=f,!0)};y.isFinite=function(){return!!this.d};y.isInteger=y.isInt=function(){return!!this.d&&ne(this.e/S)>this.d.length-2};y.isNaN=function(){return!this.s};y.isNegative=y.isNeg=function(){return this.s<0};y.isPositive=y.isPos=function(){return this.s>0};y.isZero=function(){return!!this.d&&this.d[0]===0};y.lessThan=y.lt=function(e){return this.cmp(e)<0};y.lessThanOrEqualTo=y.lte=function(e){return this.cmp(e)<1};y.logarithm=y.log=function(e){var t,r,n,o,i,s,a,c,u=this,l=u.constructor,d=l.precision,f=l.rounding,p=5;if(e==null)e=new l(10),t=!0;else{if(e=new l(e),r=e.d,e.s<0||!r||!r[0]||e.eq(1))return new l(NaN);t=e.eq(10)}if(r=u.d,u.s<0||!r||!r[0]||u.eq(1))return new l(r&&!r[0]?-1/0:u.s!=1?NaN:r?0:1/0);if(t)if(r.length>1)i=!0;else{for(o=r[0];o%10===0;)o/=10;i=o!==1}if(B=!1,a=d+p,s=Te(u,a),n=t?it(l,a+10):Te(e,a),c=G(s,n,a,1),De(c.d,o=d,f))do if(a+=10,s=Te(u,a),n=t?it(l,a+10):Te(e,a),c=G(s,n,a,1),!i){+re(c.d).slice(o+1,o+15)+1==1e14&&(c=I(c,d+1,0));break}while(De(c.d,o+=10,f));return B=!0,I(c,d,f)};y.minus=y.sub=function(e){var t,r,n,o,i,s,a,c,u,l,d,f,p=this,g=p.constructor;if(e=new g(e),!p.d||!e.d)return!p.s||!e.s?e=new g(NaN):p.d?e.s=-e.s:e=new g(e.d||p.s!==e.s?p:NaN),e;if(p.s!=e.s)return e.s=-e.s,p.plus(e);if(u=p.d,f=e.d,a=g.precision,c=g.rounding,!u[0]||!f[0]){if(f[0])e.s=-e.s;else if(u[0])e=new g(p);else return new g(c===3?-0:0);return B?I(e,a,c):e}if(r=ne(e.e/S),l=ne(p.e/S),u=u.slice(),i=l-r,i){for(d=i<0,d?(t=u,i=-i,s=f.length):(t=f,r=l,s=u.length),n=Math.max(Math.ceil(a/S),s)+2,i>n&&(i=n,t.length=1),t.reverse(),n=i;n--;)t.push(0);t.reverse()}else{for(n=u.length,s=f.length,d=n<s,d&&(s=n),n=0;n<s;n++)if(u[n]!=f[n]){d=u[n]<f[n];break}i=0}for(d&&(t=u,u=f,f=t,e.s=-e.s),s=u.length,n=f.length-s;n>0;--n)u[s++]=0;for(n=f.length;n>i;){if(u[--n]<f[n]){for(o=n;o&&u[--o]===0;)u[o]=ue-1;--u[o],u[n]+=ue}u[n]-=f[n]}for(;u[--s]===0;)u.pop();for(;u[0]===0;u.shift())--r;return u[0]?(e.d=u,e.e=at(u,r),B?I(e,a,c):e):new g(c===3?-0:0)};y.modulo=y.mod=function(e){var t,r=this,n=r.constructor;return e=new n(e),!r.d||!e.s||e.d&&!e.d[0]?new n(NaN):!e.d||r.d&&!r.d[0]?I(new n(r),n.precision,n.rounding):(B=!1,n.modulo==9?(t=G(r,e.abs(),0,3,1),t.s*=e.s):t=G(r,e,0,n.modulo,1),t=t.times(e),B=!0,r.minus(t))};y.naturalExponential=y.exp=function(){return Et(this)};y.naturalLogarithm=y.ln=function(){return Te(this)};y.negated=y.neg=function(){var e=new this.constructor(this);return e.s=-e.s,I(e)};y.plus=y.add=function(e){var t,r,n,o,i,s,a,c,u,l,d=this,f=d.constructor;if(e=new f(e),!d.d||!e.d)return!d.s||!e.s?e=new f(NaN):d.d||(e=new f(e.d||d.s===e.s?d:NaN)),e;if(d.s!=e.s)return e.s=-e.s,d.minus(e);if(u=d.d,l=e.d,a=f.precision,c=f.rounding,!u[0]||!l[0])return l[0]||(e=new f(d)),B?I(e,a,c):e;if(i=ne(d.e/S),n=ne(e.e/S),u=u.slice(),o=i-n,o){for(o<0?(r=u,o=-o,s=l.length):(r=l,n=i,s=u.length),i=Math.ceil(a/S),s=i>s?i+1:s+1,o>s&&(o=s,r.length=1),r.reverse();o--;)r.push(0);r.reverse()}for(s=u.length,o=l.length,s-o<0&&(o=s,r=l,l=u,u=r),t=0;o;)t=(u[--o]=u[o]+l[o]+t)/ue|0,u[o]%=ue;for(t&&(u.unshift(t),++n),s=u.length;u[--s]==0;)u.pop();return e.d=u,e.e=at(u,n),B?I(e,a,c):e};y.precision=y.sd=function(e){var t,r=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(ke+e);return r.d?(t=Vr(r.d),e&&r.e+1>t&&(t=r.e+1)):t=NaN,t};y.round=function(){var e=this,t=e.constructor;return I(new t(e),e.e+1,t.rounding)};y.sine=y.sin=function(){var e,t,r=this,n=r.constructor;return r.isFinite()?r.isZero()?new n(r):(e=n.precision,t=n.rounding,n.precision=e+Math.max(r.e,r.sd())+S,n.rounding=1,r=vn(n,Fr(n,r)),n.precision=e,n.rounding=t,I(me>2?r.neg():r,e,t,!0)):new n(NaN)};y.squareRoot=y.sqrt=function(){var e,t,r,n,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(B=!1,u=Math.sqrt(+s),u==0||u==1/0?(t=re(a),(t.length+c)%2==0&&(t+="0"),u=Math.sqrt(t),c=ne((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),n=new l(t)):n=new l(u.toString()),r=(c=l.precision)+3;;)if(i=n,n=i.plus(G(s,i,r+2,1)).times(.5),re(i.d).slice(0,r)===(t=re(n.d)).slice(0,r))if(t=t.slice(r-3,r+1),t=="9999"||!o&&t=="4999"){if(!o&&(I(i,c+1,0),i.times(i).eq(s))){n=i;break}r+=4,o=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(I(n,c+1,1),e=!n.times(n).eq(s));break}return B=!0,I(n,c,l.rounding,e)};y.tangent=y.tan=function(){var e,t,r=this,n=r.constructor;return r.isFinite()?r.isZero()?new n(r):(e=n.precision,t=n.rounding,n.precision=e+10,n.rounding=1,r=r.sin(),r.s=1,r=G(r,new n(1).minus(r.times(r)).sqrt(),e+10,0),n.precision=e,n.rounding=t,I(me==2||me==4?r.neg():r,e,t,!0)):new n(NaN)};y.times=y.mul=function(e){var t,r,n,o,i,s,a,c,u,l=this,d=l.constructor,f=l.d,p=(e=new d(e)).d;if(e.s*=l.s,!f||!f[0]||!p||!p[0])return new d(!e.s||f&&!f[0]&&!p||p&&!p[0]&&!f?NaN:!f||!p?e.s/0:e.s*0);for(r=ne(l.e/S)+ne(e.e/S),c=f.length,u=p.length,c<u&&(i=f,f=p,p=i,s=c,c=u,u=s),i=[],s=c+u,n=s;n--;)i.push(0);for(n=u;--n>=0;){for(t=0,o=c+n;o>n;)a=i[o]+p[n]*f[o-n-1]+t,i[o--]=a%ue|0,t=a/ue|0;i[o]=(i[o]+t)%ue|0}for(;!i[--s];)i.pop();return t?++r:i.shift(),e.d=i,e.e=at(i,r),B?I(e,d.precision,d.rounding):e};y.toBinary=function(e,t){return Nt(this,2,e,t)};y.toDecimalPlaces=y.toDP=function(e,t){var r=this,n=r.constructor;return r=new n(r),e===void 0?r:(ie(e,0,Ae),t===void 0?t=n.rounding:ie(t,0,8),I(r,e+r.e+1,t))};y.toExponential=function(e,t){var r,n=this,o=n.constructor;return e===void 0?r=de(n,!0):(ie(e,0,Ae),t===void 0?t=o.rounding:ie(t,0,8),n=I(new o(n),e+1,t),r=de(n,!0,e+1)),n.isNeg()&&!n.isZero()?"-"+r:r};y.toFixed=function(e,t){var r,n,o=this,i=o.constructor;return e===void 0?r=de(o):(ie(e,0,Ae),t===void 0?t=i.rounding:ie(t,0,8),n=I(new i(o),e+o.e+1,t),r=de(n,!1,e+n.e+1)),o.isNeg()&&!o.isZero()?"-"+r:r};y.toFraction=function(e){var t,r,n,o,i,s,a,c,u,l,d,f,p=this,g=p.d,m=p.constructor;if(!g)return new m(p);if(u=r=new m(1),n=c=new m(0),t=new m(n),i=t.e=Vr(g)-p.e-1,s=i%S,t.d[0]=$(10,s<0?S+s:s),e==null)e=i>0?t:u;else{if(a=new m(e),!a.isInt()||a.lt(u))throw Error(ke+a);e=a.gt(t)?i>0?t:u:a}for(B=!1,a=new m(re(g)),l=m.precision,m.precision=i=g.length*S*2;d=G(a,t,0,1,1),o=r.plus(d.times(n)),o.cmp(e)!=1;)r=n,n=o,o=u,u=c.plus(d.times(o)),c=o,o=t,t=a.minus(d.times(o)),a=o;return o=G(e.minus(r),n,0,1,1),c=c.plus(o.times(u)),r=r.plus(o.times(n)),c.s=u.s=p.s,f=G(u,n,i,1).minus(p).abs().cmp(G(c,r,i,1).minus(p).abs())<1?[u,n]:[c,r],m.precision=l,B=!0,f};y.toHexadecimal=y.toHex=function(e,t){return Nt(this,16,e,t)};y.toNearest=function(e,t){var r=this,n=r.constructor;if(r=new n(r),e==null){if(!r.d)return r;e=new n(1),t=n.rounding}else{if(e=new n(e),t===void 0?t=n.rounding:ie(t,0,8),!r.d)return e.s?r:e;if(!e.d)return e.s&&(e.s=r.s),e}return e.d[0]?(B=!1,r=G(r,e,0,t,1).times(e),B=!0,I(r)):(e.s=r.s,r=e),r};y.toNumber=function(){return+this};y.toOctal=function(e,t){return Nt(this,8,e,t)};y.toPower=y.pow=function(e){var t,r,n,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($(+a,u));if(a=new c(a),a.eq(1))return a;if(n=c.precision,i=c.rounding,e.eq(1))return I(a,n,i);if(t=ne(e.e/S),t>=e.d.length-1&&(r=u<0?-u:u)<=Mn)return o=Er(c,a,r,n),e.s<0?new c(1).div(o):I(o,n,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 r=$(+a,u),t=r==0||!isFinite(r)?ne(u*(Math.log("0."+re(a.d))/Math.LN10+a.e+1)):new c(r+"").e,t>c.maxE+1||t<c.minE-1?new c(t>0?s/0:0):(B=!1,c.rounding=a.s=1,r=Math.min(12,(t+"").length),o=Et(e.times(Te(a,n+r)),n),o.d&&(o=I(o,n+5,1),De(o.d,n,i)&&(t=n+10,o=I(Et(e.times(Te(a,t+r)),t),t+5,1),+re(o.d).slice(n+1,n+15)+1==1e14&&(o=I(o,n+1,0)))),o.s=s,B=!0,c.rounding=i,I(o,n,i))};y.toPrecision=function(e,t){var r,n=this,o=n.constructor;return e===void 0?r=de(n,n.e<=o.toExpNeg||n.e>=o.toExpPos):(ie(e,1,Ae),t===void 0?t=o.rounding:ie(t,0,8),n=I(new o(n),e,t),r=de(n,e<=n.e||n.e<=o.toExpNeg,e)),n.isNeg()&&!n.isZero()?"-"+r:r};y.toSignificantDigits=y.toSD=function(e,t){var r=this,n=r.constructor;return e===void 0?(e=n.precision,t=n.rounding):(ie(e,1,Ae),t===void 0?t=n.rounding:ie(t,0,8)),I(new n(r),e,t)};y.toString=function(){var e=this,t=e.constructor,r=de(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+r:r};y.truncated=y.trunc=function(){return I(new this.constructor(this),this.e+1,1)};y.valueOf=y.toJSON=function(){var e=this,t=e.constructor,r=de(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+r:r};function re(e){var t,r,n,o=e.length-1,i="",s=e[0];if(o>0){for(i+=s,t=1;t<o;t++)n=e[t]+"",r=S-n.length,r&&(i+=Pe(r)),i+=n;s=e[t],n=s+"",r=S-n.length,r&&(i+=Pe(r))}else if(s===0)return"0";for(;s%10===0;)s/=10;return i+s}function ie(e,t,r){if(e!==~~e||e<t||e>r)throw Error(ke+e)}function De(e,t,r,n){var o,i,s,a;for(i=e[0];i>=10;i/=10)--t;return--t<0?(t+=S,o=0):(o=Math.ceil((t+1)/S),t%=S),i=$(10,S-t),a=e[o]%i|0,n==null?t<3?(t==0?a=a/100|0:t==1&&(a=a/10|0),s=r<4&&a==99999||r>3&&a==49999||a==5e4||a==0):s=(r<4&&a+1==i||r>3&&a+1==i/2)&&(e[o+1]/i/100|0)==$(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=(n||r<4)&&a==9999||!n&&r>3&&a==4999):s=((n||r<4)&&a+1==i||!n&&r>3&&a+1==i/2)&&(e[o+1]/i/1e3|0)==$(10,t-3)-1,s}function rt(e,t,r){for(var n,o=[0],i,s=0,a=e.length;s<a;){for(i=o.length;i--;)o[i]*=t;for(o[0]+=Kt.indexOf(e.charAt(s++)),n=0;n<o.length;n++)o[n]>r-1&&(o[n+1]===void 0&&(o[n+1]=0),o[n+1]+=o[n]/r|0,o[n]%=r)}return o.reverse()}function Fn(e,t){var r,n,o;if(t.isZero())return t;n=t.d.length,n<32?(r=Math.ceil(n/3),o=(1/ut(4,r)).toString()):(r=16,o="2.3283064365386962890625e-10"),e.precision+=r,t=Me(e,1,t.times(o),new e(1));for(var i=r;i--;){var s=t.times(t);t=s.times(s).minus(s).times(8).plus(1)}return e.precision-=r,t}var G=function(){function e(n,o,i){var s,a=0,c=n.length;for(n=n.slice();c--;)s=n[c]*o+a,n[c]=s%i|0,a=s/i|0;return a&&n.unshift(a),n}function t(n,o,i,s){var a,c;if(i!=s)c=i>s?1:-1;else for(a=c=0;a<i;a++)if(n[a]!=o[a]){c=n[a]>o[a]?1:-1;break}return c}function r(n,o,i,s){for(var a=0;i--;)n[i]-=a,a=n[i]<o[i]?1:0,n[i]=a*s+n[i]-o[i];for(;!n[0]&&n.length>1;)n.shift()}return function(n,o,i,s,a,c){var u,l,d,f,p,g,m,T,w,x,b,k,A,R,N,_,L,q,U,z,F=n.constructor,te=n.s==o.s?1:-1,X=n.d,D=o.d;if(!X||!X[0]||!D||!D[0])return new F(!n.s||!o.s||(X?D&&X[0]==D[0]:!D)?NaN:X&&X[0]==0||!D?te*0:te/0);for(c?(p=1,l=n.e-o.e):(c=ue,p=S,l=ne(n.e/p)-ne(o.e/p)),U=D.length,L=X.length,w=new F(te),x=w.d=[],d=0;D[d]==(X[d]||0);d++);if(D[d]>(X[d]||0)&&l--,i==null?(R=i=F.precision,s=F.rounding):a?R=i+(n.e-o.e)+1:R=i,R<0)x.push(1),g=!0;else{if(R=R/p+2|0,d=0,U==1){for(f=0,D=D[0],R++;(d<L||f)&&R--;d++)N=f*c+(X[d]||0),x[d]=N/D|0,f=N%D|0;g=f||d<L}else{for(f=c/(D[0]+1)|0,f>1&&(D=e(D,f,c),X=e(X,f,c),U=D.length,L=X.length),_=U,b=X.slice(0,U),k=b.length;k<U;)b[k++]=0;z=D.slice(),z.unshift(0),q=D[0],D[1]>=c/2&&++q;do f=0,u=t(D,b,U,k),u<0?(A=b[0],U!=k&&(A=A*c+(b[1]||0)),f=A/q|0,f>1?(f>=c&&(f=c-1),m=e(D,f,c),T=m.length,k=b.length,u=t(m,b,T,k),u==1&&(f--,r(m,U<T?z:D,T,c))):(f==0&&(u=f=1),m=D.slice()),T=m.length,T<k&&m.unshift(0),r(b,m,k,c),u==-1&&(k=b.length,u=t(D,b,U,k),u<1&&(f++,r(b,U<k?z:D,k,c))),k=b.length):u===0&&(f++,b=[0]),x[d++]=f,u&&b[0]?b[k++]=X[_]||0:(b=[X[_]],k=1);while((_++<L||b[0]!==void 0)&&R--);g=b[0]!==void 0}x[0]||x.shift()}if(p==1)w.e=l,Lr=g;else{for(d=1,f=x[0];f>=10;f/=10)d++;w.e=d+l*p-1,I(w,a?i+w.e+1:i,s,g)}return w}}();function I(e,t,r,n){var o,i,s,a,c,u,l,d,f,p=e.constructor;e:if(t!=null){if(d=e.d,!d)return e;for(o=1,a=d[0];a>=10;a/=10)o++;if(i=t-o,i<0)i+=S,s=t,l=d[f=0],c=l/$(10,o-s-1)%10|0;else if(f=Math.ceil((i+1)/S),a=d.length,f>=a)if(n){for(;a++<=f;)d.push(0);l=c=0,o=1,i%=S,s=i-S+1}else break e;else{for(l=a=d[f],o=1;a>=10;a/=10)o++;i%=S,s=i-S+o,c=s<0?0:l/$(10,o-s-1)%10|0}if(n=n||t<0||d[f+1]!==void 0||(s<0?l:l%$(10,o-s-1)),u=r<4?(c||n)&&(r==0||r==(e.s<0?3:2)):c>5||c==5&&(r==4||n||r==6&&(i>0?s>0?l/$(10,o-s):0:d[f-1])%10&1||r==(e.s<0?8:7)),t<1||!d[0])return d.length=0,u?(t-=e.e+1,d[0]=$(10,(S-t%S)%S),e.e=-t||0):d[0]=e.e=0,e;if(i==0?(d.length=f,a=1,f--):(d.length=f+1,a=$(10,S-i),d[f]=s>0?(l/$(10,o-s)%$(10,s)|0)*a:0),u)for(;;)if(f==0){for(i=1,s=d[0];s>=10;s/=10)i++;for(s=d[0]+=a,a=1;s>=10;s/=10)a++;i!=a&&(e.e++,d[0]==ue&&(d[0]=1));break}else{if(d[f]+=a,d[f]!=ue)break;d[f--]=0,a=1}for(i=d.length;d[--i]===0;)d.pop()}return B&&(e.e>p.maxE?(e.d=null,e.e=NaN):e.e<p.minE&&(e.e=0,e.d=[0])),e}function de(e,t,r){if(!e.isFinite())return Nr(e);var n,o=e.e,i=re(e.d),s=i.length;return t?(r&&(n=r-s)>0?i=i.charAt(0)+"."+i.slice(1)+Pe(n):s>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(e.e<0?"e":"e+")+e.e):o<0?(i="0."+Pe(-o-1)+i,r&&(n=r-s)>0&&(i+=Pe(n))):o>=s?(i+=Pe(o+1-s),r&&(n=r-o-1)>0&&(i=i+"."+Pe(n))):((n=o+1)<s&&(i=i.slice(0,n)+"."+i.slice(n)),r&&(n=r-s)>0&&(o+1===s&&(i+="."),i+=Pe(n))),i}function at(e,t){var r=e[0];for(t*=S;r>=10;r/=10)t++;return t}function it(e,t,r){if(t>Nn)throw B=!0,r&&(e.precision=r),Error(Br);return I(new e(nt),t,1,!0)}function ae(e,t,r){if(t>Vt)throw Error(Br);return I(new e(ot),t,r,!0)}function Vr(e){var t=e.length-1,r=t*S+1;if(t=e[t],t){for(;t%10==0;t/=10)r--;for(t=e[0];t>=10;t/=10)r++}return r}function Pe(e){for(var t="";e--;)t+="0";return t}function Er(e,t,r,n){var o,i=new e(1),s=Math.ceil(n/S+4);for(B=!1;;){if(r%2&&(i=i.times(t),Ir(i.d,s)&&(o=!0)),r=ne(r/2),r===0){r=i.d.length-1,o&&i.d[r]===0&&++i.d[r];break}t=t.times(t),Ir(t.d,s)}return B=!0,i}function Ar(e){return e.d[e.d.length-1]&1}function Mr(e,t,r){for(var n,o=new e(t[0]),i=0;++i<t.length;)if(n=new e(t[i]),n.s)o[r](n)&&(o=n);else{o=n;break}return o}function Et(e,t){var r,n,o,i,s,a,c,u=0,l=0,d=0,f=e.constructor,p=f.rounding,g=f.precision;if(!e.d||!e.d[0]||e.e>17)return new f(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:0/0);for(t==null?(B=!1,c=g):c=t,a=new f(.03125);e.e>-2;)e=e.times(a),d+=5;for(n=Math.log($(2,d))/Math.LN10*2+5|0,c+=n,r=i=s=new f(1),f.precision=c;;){if(i=I(i.times(e),c,1),r=r.times(++l),a=s.plus(G(i,r,c,1)),re(a.d).slice(0,c)===re(s.d).slice(0,c)){for(o=d;o--;)s=I(s.times(s),c,1);if(t==null)if(u<3&&De(s.d,c-n,p,u))f.precision=c+=10,r=i=a=new f(1),l=0,u++;else return I(s,f.precision=g,p,B=!0);else return f.precision=g,s}s=a}}function Te(e,t){var r,n,o,i,s,a,c,u,l,d,f,p=1,g=10,m=e,T=m.d,w=m.constructor,x=w.rounding,b=w.precision;if(m.s<0||!T||!T[0]||!m.e&&T[0]==1&&T.length==1)return new w(T&&!T[0]?-1/0:m.s!=1?NaN:T?0:m);if(t==null?(B=!1,l=b):l=t,w.precision=l+=g,r=re(T),n=r.charAt(0),Math.abs(i=m.e)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)m=m.times(e),r=re(m.d),n=r.charAt(0),p++;i=m.e,n>1?(m=new w("0."+r),i++):m=new w(n+"."+r.slice(1))}else return u=it(w,l+2,b).times(i+""),m=Te(new w(n+"."+r.slice(1)),l-g).plus(u),w.precision=b,t==null?I(m,b,x,B=!0):m;for(d=m,c=s=m=G(m.minus(1),m.plus(1),l,1),f=I(m.times(m),l,1),o=3;;){if(s=I(s.times(f),l,1),u=c.plus(G(s,new w(o),l,1)),re(u.d).slice(0,l)===re(c.d).slice(0,l))if(c=c.times(2),i!==0&&(c=c.plus(it(w,l+2,b).times(i+""))),c=G(c,new w(p),l,1),t==null)if(De(c.d,l-g,x,a))w.precision=l+=g,u=s=m=G(d.minus(1),d.plus(1),l,1),f=I(m.times(m),l,1),o=a=1;else return I(c,w.precision=b,x,B=!0);else return w.precision=b,c;c=u,o+=2}}function Nr(e){return String(e.s*e.s/0)}function Mt(e,t){var r,n,o;for((r=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(r<0&&(r=n),r+=+t.slice(n+1),t=t.substring(0,n)):r<0&&(r=t.length),n=0;t.charCodeAt(n)===48;n++);for(o=t.length;t.charCodeAt(o-1)===48;--o);if(t=t.slice(n,o),t){if(o-=n,e.e=r=r-n-1,e.d=[],n=(r+1)%S,r<0&&(n+=S),n<o){for(n&&e.d.push(+t.slice(0,n)),o-=S;n<o;)e.d.push(+t.slice(n,n+=S));t=t.slice(n),n=S-t.length}else n-=o;for(;n--;)t+="0";e.d.push(+t),B&&(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 _n(e,t){var r,n,o,i,s,a,c,u,l;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),Cr.test(t))return Mt(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(Vn.test(t))r=16,t=t.toLowerCase();else if(Cn.test(t))r=2;else if(En.test(t))r=8;else throw Error(ke+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,n=e.constructor,s&&(t=t.replace(".",""),a=t.length,i=a-i,o=Er(n,new n(r),i,i*2)),u=rt(t,r,ue),l=u.length-1,i=l;u[i]===0;--i)u.pop();return i<0?new n(e.s*0):(e.e=at(u,l),e.d=u,B=!1,s&&(e=G(e,o,a*4)),c&&(e=e.times(Math.abs(c)<54?$(2,c):Oe.pow(2,c))),B=!0,e)}function vn(e,t){var r,n=t.d.length;if(n<3)return t.isZero()?t:Me(e,2,t,t);r=1.4*Math.sqrt(n),r=r>16?16:r|0,t=t.times(1/ut(5,r)),t=Me(e,2,t,t);for(var o,i=new e(5),s=new e(16),a=new e(20);r--;)o=t.times(t),t=t.times(i.plus(o.times(s.times(o).minus(a))));return t}function Me(e,t,r,n,o){var i,s,a,c,u=1,l=e.precision,d=Math.ceil(l/S);for(B=!1,c=r.times(r),a=new e(n);;){if(s=G(a.times(c),new e(t++*t++),l,1),a=o?n.plus(s):n.minus(s),n=G(s.times(c),new e(t++*t++),l,1),s=a.plus(n),s.d[d]!==void 0){for(i=d;s.d[i]===a.d[i]&&i--;);if(i==-1)break}i=a,a=n,n=s,s=i,u++}return B=!0,s.d.length=d+1,s}function ut(e,t){for(var r=e;--t;)r*=e;return r}function Fr(e,t){var r,n=t.s<0,o=ae(e,e.precision,1),i=o.times(.5);if(t=t.abs(),t.lte(i))return me=n?4:1,t;if(r=t.divToInt(o),r.isZero())me=n?3:2;else{if(t=t.minus(r.times(o)),t.lte(i))return me=Ar(r)?n?2:3:n?4:1,t;me=Ar(r)?n?1:4:n?3:2}return t.minus(o).abs()}function Nt(e,t,r,n){var o,i,s,a,c,u,l,d,f,p=e.constructor,g=r!==void 0;if(g?(ie(r,1,Ae),n===void 0?n=p.rounding:ie(n,0,8)):(r=p.precision,n=p.rounding),!e.isFinite())l=Nr(e);else{for(l=de(e),s=l.indexOf("."),g?(o=2,t==16?r=r*4-3:t==8&&(r=r*3-2)):o=t,s>=0&&(l=l.replace(".",""),f=new p(1),f.e=l.length-s,f.d=rt(de(f),10,o),f.e=f.d.length),d=rt(l,10,o),i=c=d.length;d[--c]==0;)d.pop();if(!d[0])l=g?"0p+0":"0";else{if(s<0?i--:(e=new p(e),e.d=d,e.e=i,e=G(e,f,r,n,0,o),d=e.d,i=e.e,u=Lr),s=d[r],a=o/2,u=u||d[r+1]!==void 0,u=n<4?(s!==void 0||u)&&(n===0||n===(e.s<0?3:2)):s>a||s===a&&(n===4||u||n===6&&d[r-1]&1||n===(e.s<0?8:7)),d.length=r,u)for(;++d[--r]>o-1;)d[r]=0,r||(++i,d.unshift(1));for(c=d.length;!d[c-1];--c);for(s=0,l="";s<c;s++)l+=Kt.charAt(d[s]);if(g){if(c>1)if(t==16||t==8){for(s=t==16?4:3,--c;c%s;c++)l+="0";for(d=rt(l,o,t),c=d.length;!d[c-1];--c);for(s=1,l="1.";s<c;s++)l+=Kt.charAt(d[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 Ir(e,t){if(e.length>t)return e.length=t,!0}function Dn(e){return new this(e).abs()}function On(e){return new this(e).acos()}function Wn(e){return new this(e).acosh()}function Un(e,t){return new this(e).plus(t)}function qn(e){return new this(e).asin()}function Gn(e){return new this(e).asinh()}function Hn(e){return new this(e).atan()}function jn(e){return new this(e).atanh()}function zn(e,t){e=new this(e),t=new this(t);var r,n=this.precision,o=this.rounding,i=n+4;return!e.s||!t.s?r=new this(NaN):!e.d&&!t.d?(r=ae(this,i,1).times(t.s>0?.25:.75),r.s=e.s):!t.d||e.isZero()?(r=t.s<0?ae(this,n,o):new this(0),r.s=e.s):!e.d||t.isZero()?(r=ae(this,i,1).times(.5),r.s=e.s):t.s<0?(this.precision=i,this.rounding=1,r=this.atan(G(e,t,i,1)),t=ae(this,i,1),this.precision=n,this.rounding=o,r=e.s<0?r.minus(t):r.plus(t)):r=this.atan(G(e,t,i,1)),r}function Yn(e){return new this(e).cbrt()}function Zn(e){return I(e=new this(e),e.e+1,2)}function Xn(e,t,r){return new this(e).clamp(t,r)}function Qn(e){if(!e||typeof e!="object")throw Error(st+"Object expected");var t,r,n,o=e.defaults===!0,i=["precision",1,Ae,"rounding",0,8,"toExpNeg",-Ee,0,"toExpPos",0,Ee,"maxE",0,Ee,"minE",-Ee,0,"modulo",0,9];for(t=0;t<i.length;t+=3)if(r=i[t],o&&(this[r]=Ct[r]),(n=e[r])!==void 0)if(ne(n)===n&&n>=i[t+1]&&n<=i[t+2])this[r]=n;else throw Error(ke+r+": "+n);if(r="crypto",o&&(this[r]=Ct[r]),(n=e[r])!==void 0)if(n===!0||n===!1||n===0||n===1)if(n)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[r]=!0;else throw Error(Rr);else this[r]=!1;else throw Error(ke+r+": "+n);return this}function Jn(e){return new this(e).cos()}function $n(e){return new this(e).cosh()}function _r(e){var t,r,n;function o(i){var s,a,c,u=this;if(!(u instanceof o))return new o(i);if(u.constructor=o,Sr(i)){u.s=i.s,B?!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++;B?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 Mt(u,i.toString())}else if(c!=="string")throw Error(ke+i);return(a=i.charCodeAt(0))===45?(i=i.slice(1),u.s=-1):(a===43&&(i=i.slice(1)),u.s=1),Cr.test(i)?Mt(u,i):_n(u,i)}if(o.prototype=y,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=Qn,o.clone=_r,o.isDecimal=Sr,o.abs=Dn,o.acos=On,o.acosh=Wn,o.add=Un,o.asin=qn,o.asinh=Gn,o.atan=Hn,o.atanh=jn,o.atan2=zn,o.cbrt=Yn,o.ceil=Zn,o.clamp=Xn,o.cos=Jn,o.cosh=$n,o.div=eo,o.exp=to,o.floor=ro,o.hypot=no,o.ln=oo,o.log=io,o.log10=ao,o.log2=so,o.max=uo,o.min=co,o.mod=lo,o.mul=fo,o.pow=po,o.random=mo,o.round=go,o.sign=yo,o.sin=ho,o.sinh=bo,o.sqrt=wo,o.sub=xo,o.sum=Po,o.tan=To,o.tanh=ko,o.trunc=Ao,e===void 0&&(e={}),e&&e.defaults!==!0)for(n=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],t=0;t<n.length;)e.hasOwnProperty(r=n[t++])||(e[r]=this[r]);return o.config(e),o}function eo(e,t){return new this(e).div(t)}function to(e){return new this(e).exp()}function ro(e){return I(e=new this(e),e.e+1,3)}function no(){var e,t,r=new this(0);for(B=!1,e=0;e<arguments.length;)if(t=new this(arguments[e++]),t.d)r.d&&(r=r.plus(t.times(t)));else{if(t.s)return B=!0,new this(1/0);r=t}return B=!0,r.sqrt()}function Sr(e){return e instanceof Oe||e&&e.toStringTag===Kr||!1}function oo(e){return new this(e).ln()}function io(e,t){return new this(e).log(t)}function so(e){return new this(e).log(2)}function ao(e){return new this(e).log(10)}function uo(){return Mr(this,arguments,"lt")}function co(){return Mr(this,arguments,"gt")}function lo(e,t){return new this(e).mod(t)}function fo(e,t){return new this(e).mul(t)}function po(e,t){return new this(e).pow(t)}function mo(e){var t,r,n,o,i=0,s=new this(1),a=[];if(e===void 0?e=this.precision:ie(e,1,Ae),n=Math.ceil(e/S),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(n));i<n;)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(n*=4);i<n;)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=n/4}else throw Error(Rr);else for(;i<n;)a[i++]=Math.random()*1e7|0;for(n=a[--i],e%=S,n&&e&&(o=$(10,S-e),a[i]=(n/o|0)*o);a[i]===0;i--)a.pop();if(i<0)r=0,a=[0];else{for(r=-1;a[0]===0;r-=S)a.shift();for(n=1,o=a[0];o>=10;o/=10)n++;n<S&&(r-=S-n)}return s.e=r,s.d=a,s}function go(e){return I(e=new this(e),e.e+1,this.rounding)}function yo(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function ho(e){return new this(e).sin()}function bo(e){return new this(e).sinh()}function wo(e){return new this(e).sqrt()}function xo(e,t){return new this(e).sub(t)}function Po(){var e=0,t=arguments,r=new this(t[e]);for(B=!1;r.s&&++e<t.length;)r=r.plus(t[e]);return B=!0,I(r,this.precision,this.rounding)}function To(e){return new this(e).tan()}function ko(e){return new this(e).tanh()}function Ao(e){return I(e=new this(e),e.e+1,1)}y[Symbol.for("nodejs.util.inspect.custom")]=y.toString;y[Symbol.toStringTag]="Decimal";var Oe=y.constructor=_r(Ct);nt=new Oe(nt);ot=new Oe(ot);var Ft=Oe;import Vo from"big.js";import dt from"bn.js";import Io from"toformat";var So=Io,We=So;import lt from"big.js";import Bo from"bn.js";import Ro from"decimal.js-light";import Ue from"bn.js";var vr=9007199254740991;function E(e){let t=Q("Raydium_parseBigNumberish");if(e instanceof Ue)return e;if(typeof e=="string"){if(e.match(/^-?[0-9]+$/))return new Ue(e);t.logWithError(`invalid BigNumberish string: ${e}`)}return typeof e=="number"?(e%1&&t.logWithError(`BigNumberish number underflow: ${e}`),(e>=vr||e<=-vr)&&t.logWithError(`BigNumberish number overflow: ${e}`),new Ue(String(e))):typeof e=="bigint"?new Ue(e.toString()):(t.error(`invalid BigNumberish value: ${e}`),new Ue(0))}var ct=Q("module/fraction"),_t=We(lt),qe=We(Ro),Ko={[0]:qe.ROUND_DOWN,[1]:qe.ROUND_HALF_UP,[2]:qe.ROUND_UP},Co={[0]:lt.roundDown,[1]:lt.roundHalfUp,[2]:lt.roundUp},O=class{constructor(t,r=new Bo(1)){this.numerator=E(t),this.denominator=E(r)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new O(this.denominator,this.numerator)}add(t){let r=t instanceof O?t:new O(E(t));return this.denominator.eq(r.denominator)?new O(this.numerator.add(r.numerator),this.denominator):new O(this.numerator.mul(r.denominator).add(r.numerator.mul(this.denominator)),this.denominator.mul(r.denominator))}sub(t){let r=t instanceof O?t:new O(E(t));return this.denominator.eq(r.denominator)?new O(this.numerator.sub(r.numerator),this.denominator):new O(this.numerator.mul(r.denominator).sub(r.numerator.mul(this.denominator)),this.denominator.mul(r.denominator))}mul(t){let r=t instanceof O?t:new O(E(t));return new O(this.numerator.mul(r.numerator),this.denominator.mul(r.denominator))}div(t){let r=t instanceof O?t:new O(E(t));return new O(this.numerator.mul(r.denominator),this.denominator.mul(r.numerator))}toSignificant(t,r={groupSeparator:""},n=1){Number.isInteger(t)||ct.logWithError(`${t} is not an integer.`),t<=0&&ct.logWithError(`${t} is not positive.`),qe.set({precision:t+1,rounding:Ko[n]});let o=new qe(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(t);return o.toFormat(o.decimalPlaces(),r)}toFixed(t,r={groupSeparator:""},n=1){return Number.isInteger(t)||ct.logWithError(`${t} is not an integer.`),t<0&&ct.logWithError(`${t} is negative.`),_t.DP=t,_t.RM=Co[n]||1,new _t(this.numerator.toString()).div(this.denominator.toString()).toFormat(t,r)}isZero(){return this.numerator.isZero()}};var Eo=Q("Raydium_amount"),Dr=We(Vo);function Mo(e,t){let r="0",n="0";if(e.includes(".")){let o=e.split(".");o.length===2?([r,n]=o,n=n.padEnd(t,"0")):Eo.logWithError(`invalid number string, num: ${e}`)}else r=e;return[r,n.slice(0,t)||n]}var ge=class extends O{constructor(r,n,o=!0,i){let s=new dt(0),a=vt.pow(new dt(r.decimals));if(o)s=E(n);else{let c=new dt(0),u=new dt(0);if(typeof n=="string"||typeof n=="number"||typeof n=="bigint"){let[l,d]=Mo(n.toString(),r.decimals);c=E(l),u=E(d)}c=c.mul(a),s=c.add(u)}super(s,a);this.logger=Q(i||"TokenAmount"),this.token=r}get raw(){return this.numerator}isZero(){return this.raw.isZero()}gt(r){return this.token.equals(r.token)||this.logger.logWithError("gt token not equals"),this.raw.gt(r.raw)}lt(r){return this.token.equals(r.token)||this.logger.logWithError("lt token not equals"),this.raw.lt(r.raw)}add(r){return this.token.equals(r.token)||this.logger.logWithError("add token not equals"),new ge(this.token,this.raw.add(r.raw))}subtract(r){return this.token.equals(r.token)||this.logger.logWithError("sub token not equals"),new ge(this.token,this.raw.sub(r.raw))}toSignificant(r=this.token.decimals,n,o=0){return super.toSignificant(r,n,o)}toFixed(r=this.token.decimals,n,o=0){return r>this.token.decimals&&this.logger.logWithError("decimals overflow"),super.toFixed(r,n,o)}toExact(r={groupSeparator:""}){return Dr.DP=this.token.decimals,new Dr(this.numerator.toString()).div(this.denominator.toString()).toFormat(r)}};import{PublicKey as No}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Or}from"@solana/spl-token";var Wr={chainId:101,address:No.default.toBase58(),programId:Or.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}},oe={chainId:101,address:"So11111111111111111111111111111111111111112",programId:Or.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 Wt}from"@solana/web3.js";import{PublicKey as Y,SystemProgram as Ur,SYSVAR_RENT_PUBKEY as Fo}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as _o}from"@solana/spl-token";function h({pubkey:e,isSigner:t=!1,isWritable:r=!0}){return{pubkey:e,isWritable:r,isSigner:t}}var Dt=[h({pubkey:_o,isWritable:!1}),h({pubkey:Ur.programId,isWritable:!1}),h({pubkey:Fo,isWritable:!1})];function qr({publicKey:e,transformSol:t}){let r=Ot(e.toString());if(r instanceof Y)return t&&r.equals(ee)?pe:r;if(t&&r.toString()===ee.toBase58())return pe;if(typeof r=="string"){if(r===Y.default.toBase58())return Y.default;try{return new Y(r)}catch{throw new Error("invalid public key")}}throw new Error("invalid public key")}function Ot(e){try{return new Y(e)}catch{return e}}var Ds=new Y("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Os=new Y("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),vo=new Y("SysvarRent111111111111111111111111111111111"),Ws=new Y("SysvarC1ock11111111111111111111111111111111"),Us=new Y("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Do=new Y("Sysvar1nstructions1111111111111111111111111"),qs=Ur.programId,Gs=new Y("2cpMA1jNS4obgRz8XNg38QuSP83L1AXpUgfxPNcvnAGj"),Hs=new Y("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),js=new Y("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),zs=new Y("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Ys=new Y("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),Zs=new Y("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Xs=new Y("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Qs=new Y("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Js=new Y("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),$s=new Y("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),ea=new Y("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),pe=new Y("So11111111111111111111111111111111111111112"),ee=Y.default;var Ut=class{constructor({mint:t,decimals:r,symbol:n,name:o,skipMint:i=!1,isToken2022:s=!1}){if(t===ee.toBase58()||t instanceof Wt&&ee.equals(t)){this.decimals=oe.decimals,this.symbol=oe.symbol,this.name=oe.name,this.mint=new Wt(oe.address),this.isToken2022=!1;return}this.decimals=r,this.symbol=n||t.toString().substring(0,6),this.name=o||t.toString().substring(0,6),this.mint=i?Wt.default:qr({publicKey:t}),this.isToken2022=s}equals(t){return this===t?!0:this.mint.equals(t.mint)}},Re=Ut;Re.WSOL=new Ut({...oe,mint:oe.address});var qt=class{constructor({decimals:t,symbol:r="UNKNOWN",name:n="UNKNOWN"}){this.decimals=t,this.symbol=r,this.name=n}equals(t){return this===t}},ft=qt;ft.SOL=new qt(Wr);import Oo from"bn.js";var Gr=new O(new Oo(100)),Ne=class extends O{toSignificant(t=5,r,n){return this.mul(Gr).toSignificant(t,r,n)}toFixed(t=2,r,n){return this.mul(Gr).toFixed(t,r,n)}};var Wo=Q("Raydium_price"),ye=class extends O{constructor(r){let{baseToken:n,quoteToken:o,numerator:i,denominator:s}=r;super(i,s);this.baseToken=n,this.quoteToken=o,this.scalar=new O(Gt(n.decimals),Gt(o.decimals))}get raw(){return new O(this.numerator,this.denominator)}get adjusted(){return super.mul(this.scalar)}invert(){return new ye({baseToken:this.quoteToken,quoteToken:this.baseToken,denominator:this.numerator,numerator:this.denominator})}mul(r){this.quoteToken!==r.baseToken&&Wo.logWithError("mul token not equals");let n=super.mul(r);return new ye({baseToken:this.baseToken,quoteToken:r.quoteToken,denominator:n.denominator,numerator:n.numerator})}toSignificant(r=this.quoteToken.decimals,n,o){return this.adjusted.toSignificant(r,n,o)}toFixed(r=this.quoteToken.decimals,n,o){return this.adjusted.toFixed(r,n,o)}};import{PublicKey as Uo}from"@solana/web3.js";import qo from"bn.js";function Hr(e){return typeof e=="object"&&e!==null&&![Re,ge,Uo,O,qo,ye,Ne].some(t=>typeof t=="object"&&e instanceof t)}function he(e){return typeof e=="string"?Ot(e):Array.isArray(e)?e.map(t=>he(t)):Hr(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,he(r)])):e}var Ht=new be(0),Za=new be(1),Xa=new be(2),Qa=new be(3),Ja=new be(5),vt=new be(10),$a=new be(100),eu=new be(1e3),tu=new be(1e4);function Gt(e){return vt.pow(E(e))}function Rt(e,t=1,r=[]){let n=[...e];if(t<=0)return r;for(;n.length;)r.push(n.splice(0,t));return r}import{PublicKey as Xo}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Qo}from"@solana/spl-token";import{ComputeBudgetProgram as jr,Keypair as Yr,PublicKey as Go,Transaction as Zr,TransactionMessage as Ho,VersionedTransaction as Xr}from"@solana/web3.js";var H={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 jo}from"@solana/spl-token";var zr=Q("Raydium_txUtil"),Qr=1644;function pt(e){let t=[],r=[];return e.microLamports&&(t.push(jr.setComputeUnitPrice({microLamports:e.microLamports})),r.push(H.SetComputeUnitPrice)),e.units&&(t.push(jr.setComputeUnitLimit({units:e.units})),r.push(H.SetComputeUnitLimit)),{instructions:t,instructionTypes:r}}async function Fe(e,t){var n,o;let r=t!=null?t:"confirmed";return(o=await((n=e.getLatestBlockhash)==null?void 0:n.call(e,{commitment:r})))==null?void 0:o.blockhash}async function mt(e,t){return e.getSignatureStatuses([t]),new Promise((r,n)=>{let o=setTimeout(n,6e4);e.onSignature(t,i=>{if(clearTimeout(o),!i.err){r("");return}n(i.err.toString())},"confirmed")})}function zo(e,t){e.length<1&&zr.logWithError(`no instructions provided: ${e.toString()}`),t.length<1&&zr.logWithError(`no signers provided:, ${t.toString()}`);let r=new Zr;r.recentBlockhash="11111111111111111111111111111111",r.feePayer=t[0],r.add(...e);try{return Buffer.from(r.serialize({verifySignatures:!1})).toString("base64").length<Qr}catch{return!1}}function Ke(e,t){let[r,n]=Go.findProgramAddressSync(e,t);return{publicKey:r,nonce:n}}function Ge({instructions:e,payer:t,signers:r}){return zo(e,[t,...r])}function He({instructions:e,payer:t,lookupTableAddressAccount:r,recentBlockhash:n=Yr.generate().publicKey.toString()}){let i=new Ho({payerKey:t,recentBlockhash:n,instructions:e}).compileToV0Message(Object.values(r!=null?r:{}));try{return Buffer.from(new Xr(i).serialize()).toString("base64").length<Qr}catch{return!1}}var Yo=e=>Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e),Zo=e=>{let t=e.serialize({requireAllSignatures:!1,verifySignatures:!1});e instanceof Xr&&(t=Yo(t));try{return t instanceof Buffer?t.toString("base64"):Buffer.from(t).toString("base64")}catch{return t.toString("base64")}};function Ce(e){let t=[];return e.forEach(r=>{r instanceof Zr&&(r.recentBlockhash||(r.recentBlockhash=jo.toBase58()),r.feePayer||(r.feePayer=Yr.generate().publicKey)),t.push(Zo(r))}),console.log("simulate tx string:",t),t}function _e(e,t,r){return Ke([e.toBuffer(),(r!=null?r:Qo).toBuffer(),t.toBuffer()],new Xo("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}import{PublicKey as V}from"@solana/web3.js";var Jr=new V("EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"),$r=new V("9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z"),je=new V("FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG"),Tu=new V("CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS"),ku=new V("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"),Au=new V("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),Iu=new V("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"),Su=new V("5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h"),Lu=new V("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),Bu=new V("CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"),Ru=new V("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),Ku=new V("kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy"),Cu=new V("routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS"),Vu=new V("7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"),Eu=new V("6FJon3QE27qgPVggARueB22hLvoh22VzJpXv4rBEoSLF"),Mu=new V("CC12se5To1CdEuw7fDS27B7Geo5jJyL7t5UK2B44NgiH"),Nu=new V("9HzJyW1qZsEiSfMUf6L2jo3CcTKAyBmSyKdwQeYisHrC"),Fu=new V("DropEU8AvevN3UrXWXTMuz3rqnMczQVNjq3kcSdW2SQi"),_u=new V("SNaPnpKUY656VPwbKmKT8FG4T85g4VWhRH1B4TQUfKs"),vu=new V("9pR79Lqe6wDNjag3v8MeVYUostoXjY2ognTydor6AtEZ"),Du=new V("DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8"),Jo=new V("4AscABy58S62owbByjUUkQfZsP7fxYH1rDYb69V58HPM"),$o=new V("7rQ1QFNosMkUCuh7Z7fPbTHvh73b68sQYdirycEzJVuw"),ei=new V("G11FKBRaAkHAKuLCgLM6K6NUc9rTjPAznRCjZifrTQe2"),Ou=new V("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),ti=new V("DLockwT7X7sxtLmGH9g5kmfcjaBtncdbUmi738m5bvQC"),Wu=new V("3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH"),ri=new V("7AFUeLVRjBfzqK3tTGw8hN48KLQWSk6DTE8xprWdPqix");var Uu={SERUM_MARKET:V.default,OPENBOOK_MARKET:new V("EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj"),UTIL1216:V.default,FarmV3:new V("85BFyr98MbCUU9MVTEgzx1nbhWACbJqLzho6zd6DZcWL"),FarmV5:new V("EcLzTrNg9V7qhcdyXDe2qjtPkiGzDM2UbdRaeaadU5r2"),FarmV6:new V("Farm2hJLcqPtPg8M4rR6DMrsRNc5TPm5Cs4bVQrMe2T7"),AmmV4:new V("HWy1jotHpo6UqeQxx49dpYYdQB8wj9Qk9MdxwjLvDHB8"),AmmStable:new V("DDg4VmQaJV9ogWce7LpcjBA9bv22wRp5uaTPa5pGjijF"),CLMM:new V("devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH"),CLMM_LOCK_PROGRAM_ID:new V("DLockwT7X7sxtLmGH9g5kmfcjaBtncdbUmi738m5bvQC"),CLMM_LOCK_AUTH_ID:new V("8qmHNvu2Kr2C7U8mJL4Vz1vTDxMhVuXKREwU7TNoaVEo"),Router:new V("BVChZ3XFEwTMUk1o9i3HAf91H6mFxSwa5X2wFAWhYPhU"),CREATE_CPMM_POOL_PROGRAM:Jo,CREATE_CPMM_POOL_AUTH:$o,CREATE_CPMM_POOL_FEE_ACC:ei,FEE_DESTINATION_ID:new V("3XMrhbv989VxAMi3DErLV9eJht1pHppW5LbKxe9fkEFR"),LOCK_CPMM_PROGRAM:ti,LCOK_CPMM_AUTH:ri};import Hu from"bn.js";import{PublicKey as en,AddressLookupTableAccount as gt}from"@solana/web3.js";async function jt({connection:e,address:t}){let r=await kr(e,[...new Set(t.map(o=>o.toString()))].map(o=>new en(o))),n={};for(let o=0;o<t.length;o++){let i=r[o],s=t[o];if(!i)continue;let a=new gt({key:s,state:gt.deserialize(i.data)});n[s.toString()]=a,yt[s.toString()]=a}return n}var yt={"2immgwYNHBbyVQKVGCEkgWpi53bLwWNRMB5G2nbgYV17":new gt({key:new en("2immgwYNHBbyVQKVGCEkgWpi53bLwWNRMB5G2nbgYV17"),state:gt.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 ze,sendAndConfirmTransaction as zt,Transaction as Ye,TransactionMessage as Ze,VersionedTransaction as Xe}from"@solana/web3.js";import oi from"axios";var ht=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 n;let t=(await oi.get(`https://solanacompass.com/api/fees?cacheFreshTime=${3e5}`)).data,{avg:r}=(n=t==null?void 0:t[15])!=null?n:{};if(!!r)return{units:6e5,microLamports:Math.min(Math.ceil(r*1e6/6e5),25e3)}}addCustomComputeBudget(t){if(t){let{instructions:r,instructionTypes:n}=pt(t);return this.instructions.unshift(...r),this.instructionTypes.unshift(...n),!0}return!1}async calComputeBudget({config:t,defaultIns:r}){try{let n=t||await this.getComputeBudgetConfig();if(this.addCustomComputeBudget(n))return;r&&this.instructions.unshift(...r)}catch{r&&this.instructions.unshift(...r)}}addInstruction({instructions:t=[],endInstructions:r=[],signers:n=[],instructionTypes:o=[],endInstructionTypes:i=[],lookupTableAddress:s=[]}){return this.instructions.push(...t),this.endInstructions.push(...r),this.signers.push(...n),this.instructionTypes.push(...o),this.endInstructionTypes.push(...i),this.lookupTableAddress.push(...s.filter(a=>a!==ze.default.toString())),this}async versionBuild({txVersion:t,extInfo:r}){return t===0?await this.buildV0({...r||{}}):this.build(r)}build(t){var n;let r=new Ye;return this.allInstructions.length&&r.add(...this.allInstructions),r.feePayer=this.feePayer,((n=this.owner)==null?void 0:n.signer)&&!this.signers.some(o=>o.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer),{builder:this,transaction:r,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 Fe(this.connection,this.blockhashCommitment);if(r.recentBlockhash=c,this.signers.length&&r.sign(...this.signers),Ce([r]),(u=this.owner)!=null&&u.isKeyPair)return{txId:a?await zt(this.connection,r,this.signers.find(d=>d.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:s}):await this.connection.sendRawTransaction(r.serialize(),{skipPreflight:s}),signedTx:r};if(this.signAllTransactions){let l=await this.signAllTransactions([r]);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:r=[],extInfo:n}=t,{transaction:o}=this.build(n),i=r.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(d=>d.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:s,signers:a,instructionTypes:c,execute:async l=>{var T;let{sequentially:d,onTxUpdate:f,recentBlockHash:p,skipPreflight:g=!0}=l||{},m=p!=null?p:await Fe(this.connection,this.blockhashCommitment);if((T=this.owner)!=null&&T.isKeyPair){if(d){let w=[];for(let x of s){let b=await zt(this.connection,x,this.signers.find(k=>k.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:g});w.push(b)}return{txIds:w,signedTxs:s}}return{txIds:await await Promise.all(s.map(async w=>(w.recentBlockhash=m,await this.connection.sendRawTransaction(w.serialize(),{skipPreflight:g})))),signedTxs:s}}if(this.signAllTransactions){let w=s.map((b,k)=>(b.recentBlockhash=m,a[k].length&&b.sign(...a[k]),b));Ce(w);let x=await this.signAllTransactions(w);if(d){let b=0,k=[],A=async()=>{if(!x[b])return;let R=await this.connection.sendRawTransaction(x[b].serialize(),{skipPreflight:g});k.push({txId:R,status:"sent",signedTx:x[b]}),f==null||f([...k]),b++,this.connection.onSignature(R,N=>{let _=k.findIndex(L=>L.txId===R);_>-1&&(k[_].status=N.err?"error":"success"),f==null||f([...k]),N.err||A()},"processed"),this.connection.getSignatureStatus(R)};return await A(),{txIds:k.map(R=>R.txId),signedTxs:x}}else{let b=[];for(let k=0;k<x.length;k+=1){let A=await this.connection.sendRawTransaction(x[k].serialize(),{skipPreflight:g});b.push(A)}return{txIds:b,signedTxs:x}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:n||{}}}async versionMultiBuild({extraPreBuildData:t,txVersion:r,extInfo:n}){return r===0?await this.buildV0MultiTx({extraPreBuildData:t,buildProps:n||{}}):this.buildMultiTx({extraPreBuildData:t,extInfo:n})}async buildV0(t){var g;let{lookupTableCache:r={},lookupTableAddress:n=[],forerunCreate:o,recentBlockhash:i,...s}=t||{},a={...this.cluster==="devnet"?{}:yt,...r},c=Array.from(new Set([...n,...this.lookupTableAddress])),u=[];for(let m of c)a[m]===void 0&&u.push(new ze(m));let l=await jt({connection:this.connection,address:u});for(let[m,T]of Object.entries(l))a[m]=T;let d=o?ze.default.toBase58():i!=null?i:await Fe(this.connection,this.blockhashCommitment),f=new Ze({payerKey:this.feePayer,recentBlockhash:d,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(a));((g=this.owner)==null?void 0:g.signer)&&!this.signers.some(m=>m.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let p=new Xe(f);return p.sign(this.signers),{builder:this,transaction:p,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async m=>{var x;let{skipPreflight:T=!0,sendAndConfirm:w}=m||{};if(Ce([p]),(x=this.owner)!=null&&x.isKeyPair){let b=await this.connection.sendTransaction(p,{skipPreflight:T});return w&&await mt(this.connection,b),{txId:b,signedTx:p}}if(this.signAllTransactions){let b=await this.signAllTransactions([p]);return{txId:await this.connection.sendTransaction(b[0],{skipPreflight:T}),signedTx:b[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:s||{}}}async buildV0MultiTx(t){var u;let{extraPreBuildData:r=[],buildProps:n}=t,{transaction:o}=await this.buildV0(n),i=r.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(d=>d.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),s.forEach(async(l,d)=>{l.sign(a[d])}),{builder:this,transactions:s,signers:a,instructionTypes:c,buildProps:n,execute:async l=>{var m;let{sequentially:d,onTxUpdate:f,recentBlockHash:p,skipPreflight:g=!0}=l||{};if(p&&s.forEach(T=>T.message.recentBlockhash=p),Ce(s),(m=this.owner)!=null&&m.isKeyPair){if(d){let T=[];for(let w of s){let x=await this.connection.sendTransaction(w,{skipPreflight:g});await mt(this.connection,x),T.push(x)}return{txIds:T,signedTxs:s}}return{txIds:await Promise.all(s.map(async T=>await this.connection.sendTransaction(T,{skipPreflight:g}))),signedTxs:s}}if(this.signAllTransactions){let T=await this.signAllTransactions(s);if(d){let w=0,x=[],b=async()=>{if(!T[w])return;let k=await this.connection.sendTransaction(T[w],{skipPreflight:g});x.push({txId:k,status:"sent",signedTx:T[w]}),f==null||f([...x]),w++,this.connection.onSignature(k,A=>{let R=x.findIndex(N=>N.txId===k);R>-1&&(x[R].status=A.err?"error":"success"),f==null||f([...x]),A.err||b()},"processed"),this.connection.getSignatureStatus(k)};return b(),{txIds:[],signedTxs:T}}else{let w=[];for(let x=0;x<T.length;x+=1){let b=await this.connection.sendTransaction(T[x],{skipPreflight:g});w.push(b)}return{txIds:w,signedTxs:T}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:n||{}}}async sizeCheckBuild(t){var u;let{computeBudgetConfig:r,...n}=t||{},o=r?pt(r):{instructions:[],instructionTypes:[]},i=this.signers.reduce((l,d)=>({...l,[d.publicKey.toBase58()]:d}),{}),s=[],a=[],c=[];if(this.allInstructions.forEach(l=>{let d=[...c,l],f=r?[...o.instructions,...d]:d,g=[...new Set(d.map(m=>m.keys.filter(T=>T.isSigner).map(T=>T.pubkey.toString())).flat()).values()].map(m=>new ze(m));if(c.length<12&&Ge({instructions:f,payer:this.feePayer,signers:g})||Ge({instructions:d,payer:this.feePayer,signers:g}))c.push(l);else{if(c.length===0)throw Error("item ins too big");Ge({instructions:r?[...o.instructions,...c]:[...c],payer:this.feePayer,signers:g})?s.push(new Ye().add(...o.instructions,...c)):s.push(new Ye().add(...c)),a.push(Array.from(new Set(c.map(m=>m.keys.filter(T=>T.isSigner).map(T=>T.pubkey.toString())).flat())).map(m=>i[m]).filter(m=>m!==void 0)),c=[l]}}),c.length>0){let d=[...new Set(c.map(f=>f.keys.filter(p=>p.isSigner).map(p=>p.pubkey.toString())).flat()).values()].map(f=>i[f]).filter(f=>f!==void 0);Ge({instructions:r?[...o.instructions,...c]:[...c],payer:this.feePayer,signers:d.map(f=>f.publicKey)})?s.push(new Ye().add(...o.instructions,...c)):s.push(new Ye().add(...c)),a.push(d)}return s.forEach(l=>l.feePayer=this.feePayer),(u=this.owner)!=null&&u.signer&&a.forEach(l=>{l.some(d=>d.publicKey.equals(this.owner.publicKey))||l.push(this.owner.signer)}),{builder:this,transactions:s,signers:a,instructionTypes:this.instructionTypes,execute:async l=>{var T;let{sequentially:d,onTxUpdate:f,recentBlockHash:p,skipPreflight:g=!0}=l||{},m=p!=null?p:await Fe(this.connection,this.blockhashCommitment);if(s.forEach(async(w,x)=>{w.recentBlockhash=m,a[x].length&&w.sign(...a[x])}),Ce(s),(T=this.owner)!=null&&T.isKeyPair){if(d){let w=[];for(let x of s){let b=await zt(this.connection,x,this.signers.find(k=>k.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:g});w.push(b)}return{txIds:w,signedTxs:s}}return{txIds:await Promise.all(s.map(async w=>await this.connection.sendRawTransaction(w.serialize(),{skipPreflight:g}))),signedTxs:s}}if(this.signAllTransactions){let w=await this.signAllTransactions(s);if(d){let x=0,b=[],k=async()=>{if(!w[x])return;let A=await this.connection.sendRawTransaction(w[x].serialize(),{skipPreflight:g});b.push({txId:A,status:"sent",signedTx:w[x]}),f==null||f([...b]),x++,this.connection.onSignature(A,R=>{let N=b.findIndex(_=>_.txId===A);N>-1&&(b[N].status=R.err?"error":"success"),f==null||f([...b]),R.err||k()},"processed"),this.connection.getSignatureStatus(A)};return await k(),{txIds:b.map(A=>A.txId),signedTxs:w}}else{let x=[];for(let b=0;b<w.length;b+=1){let k=await this.connection.sendRawTransaction(w[b].serialize(),{skipPreflight:g});x.push(k)}return{txIds:x,signedTxs:w}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:n||{}}}async sizeCheckBuildV0(t){var T;let{computeBudgetConfig:r,lookupTableCache:n={},lookupTableAddress:o=[],...i}=t||{},s={...this.cluster==="devnet"?{}:yt,...n},a=Array.from(new Set([...this.lookupTableAddress,...o])),c=[];for(let w of a)s[w]===void 0&&c.push(new ze(w));let u=await jt({connection:this.connection,address:c});for(let[w,x]of Object.entries(u))s[w]=x;let l=r?pt(r):{instructions:[],instructionTypes:[]},d=await Fe(this.connection,this.blockhashCommitment),f=this.signers.reduce((w,x)=>({...w,[x.publicKey.toBase58()]:x}),{}),p=[],g=[],m=[];if(this.allInstructions.forEach(w=>{let x=[...m,w],b=r?[...l.instructions,...x]:x;if(m.length<12&&He({instructions:b,payer:this.feePayer,lookupTableAddressAccount:s})||He({instructions:x,payer:this.feePayer,lookupTableAddressAccount:s}))m.push(w);else{if(m.length===0)throw Error("item ins too big");let k={};for(let A of[...new Set(a)])s[A]!==void 0&&(k[A]=s[A]);if(r&&He({instructions:[...l.instructions,...m],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:d})){let A=new Ze({payerKey:this.feePayer,recentBlockhash:d,instructions:[...l.instructions,...m]}).compileToV0Message(Object.values(s));p.push(new Xe(A))}else{let A=new Ze({payerKey:this.feePayer,recentBlockhash:d,instructions:[...m]}).compileToV0Message(Object.values(s));p.push(new Xe(A))}g.push(Array.from(new Set(m.map(A=>A.keys.filter(R=>R.isSigner).map(R=>R.pubkey.toString())).flat())).map(A=>f[A]).filter(A=>A!==void 0)),m=[w]}}),m.length>0){let x=[...new Set(m.map(b=>b.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat()).values()].map(b=>f[b]).filter(b=>b!==void 0);if(r&&He({instructions:[...l.instructions,...m],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:d})){let b=new Ze({payerKey:this.feePayer,recentBlockhash:d,instructions:[...l.instructions,...m]}).compileToV0Message(Object.values(s));p.push(new Xe(b))}else{let b=new Ze({payerKey:this.feePayer,recentBlockhash:d,instructions:[...m]}).compileToV0Message(Object.values(s));p.push(new Xe(b))}g.push(x)}return(T=this.owner)!=null&&T.signer&&g.forEach(w=>{w.some(x=>x.publicKey.equals(this.owner.publicKey))||w.push(this.owner.signer)}),{builder:this,transactions:p,buildProps:t,signers:g,instructionTypes:this.instructionTypes,execute:async w=>{var R;let{sequentially:x,onTxUpdate:b,recentBlockHash:k,skipPreflight:A=!0}=w||{};if(p.map(async(N,_)=>{g[_].length&&N.sign(g[_]),k&&(N.message.recentBlockhash=k)}),Ce(p),(R=this.owner)!=null&&R.isKeyPair){if(x){let N=[];for(let _ of p){let L=await this.connection.sendTransaction(_,{skipPreflight:A});await mt(this.connection,L),N.push(L)}return{txIds:N,signedTxs:p}}return{txIds:await Promise.all(p.map(async N=>await this.connection.sendTransaction(N,{skipPreflight:A}))),signedTxs:p}}if(this.signAllTransactions){let N=await this.signAllTransactions(p);if(x){let _=0,L=[],q=async()=>{if(!N[_])return;let U=await this.connection.sendTransaction(N[_],{skipPreflight:A});L.push({txId:U,status:"sent",signedTx:N[_]}),b==null||b([...L]),_++,this.connection.onSignature(U,z=>{let F=L.findIndex(te=>te.txId===U);F>-1&&(L[F].status=z.err?"error":"success"),b==null||b([...L]),z.err||q()},"processed"),this.connection.getSignatureStatus(U)};return q(),{txIds:[],signedTxs:N}}else{let _=[];for(let L=0;L<N.length;L+=1){let q=await this.connection.sendTransaction(N[L],{skipPreflight:A});_.push(q)}return{txIds:_,signedTxs:N}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:i||{}}}};import{Keypair as bi,PublicKey as wi}from"@solana/web3.js";import ql from"bn.js";import{TOKEN_PROGRAM_ID as xi}from"@solana/spl-token";function ii(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function Yt(e,...t){if(!ii(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 Zt(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 tn(e,t){Yt(e);let r=t.outputLen;if(e.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var wt=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),ce=(e,t)=>e<<32-t|e>>>t;var Bc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function si(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Xt(e){return typeof e=="string"&&(e=si(e)),Yt(e),e}var bt=class{clone(){return this._cloneInto()}},Rc={}.toString;function rn(e){let t=n=>e().update(Xt(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function ai(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?4:0,u=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+u,a,n)}var nn=(e,t,r)=>e&t^~e&r,on=(e,t,r)=>e&t^e&r^t&r,xt=class extends bt{constructor(t,r,n,o){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=wt(this.buffer)}update(t){Zt(this);let{view:r,buffer:n,blockLen:o}=this;t=Xt(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=wt(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Zt(this),tn(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>o-s&&(this.process(n,0),s=0);for(let d=s;d<o;d++)r[d]=0;ai(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=wt(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 d=0;d<u;d++)a.setUint32(4*d,l[d],i)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return t.length=o,t.pos=a,t.finished=i,t.destroyed=s,o%r&&t.buffer.set(n),t}};var ui=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),Qt=class extends xt{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:r,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,r,n,o,i,s,a,c]}set(t,r,n,o,i,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,r){for(let d=0;d<16;d++,r+=4)Se[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){let f=Se[d-15],p=Se[d-2],g=ce(f,7)^ce(f,18)^f>>>3,m=ce(p,17)^ce(p,19)^p>>>10;Se[d]=m+Se[d-7]+g+Se[d-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:u,H:l}=this;for(let d=0;d<64;d++){let f=ce(a,6)^ce(a,11)^ce(a,25),p=l+f+nn(a,c,u)+ui[d]+Se[d]|0,m=(ce(n,2)^ce(n,13)^ce(n,22))+on(n,o,i)|0;l=u,u=c,c=a,a=s+p|0,s=i,i=o,o=n,n=p+m|0}n=n+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(n,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 sn=rn(()=>new Qt);import{PublicKey as gi}from"@solana/web3.js";import ln,{isBN as dn}from"bn.js";import{bits as vc,BitStructure as Dc,blob as ci,Blob as Oc,cstr as Wc,f32 as Uc,f32be as qc,f64 as Gc,f64be as Hc,greedy as jc,Layout as li,ns64 as zc,ns64be as Yc,nu64 as Zc,nu64be as Xc,offset as Qc,s16 as Jc,s16be as $c,s24 as el,s24be as tl,s32 as rl,s32be as nl,s40 as ol,s40be as il,s48 as sl,s48be as al,s8 as ul,seq as di,struct as cl,Structure as fi,u16 as ll,u16be as dl,u24 as fl,u24be as pl,u32 as ml,u32be as gl,u40 as yl,u40be as hl,u48 as bl,u48be as wl,u8 as pi,UInt as mi,union as xl,Union as Pl,unionLayoutDiscriminator as Tl,utf8 as kl}from"@solana/buffer-layout";var Jt=li,an=fi;var $t=mi;var un=pi;var cn=di;var Ve=ci;var ve=class extends Jt{constructor(r,n,o){super(r,o);this.blob=Ve(r),this.signed=n}decode(r,n=0){let o=new ln(this.blob.decode(r,n),10,"le");return this.signed?o.fromTwos(this.span*8).clone():o}encode(r,n,o=0){return typeof r=="number"&&(r=new ln(r)),this.signed&&(r=r.toTwos(this.span*8)),this.blob.encode(r.toArrayLike(Buffer,"le",this.span),n,o)}};function J(e){return new $t(1,e)}function Qe(e){return new $t(4,e)}function P(e){return new ve(8,!1,e)}function we(e){return new ve(16,!1,e)}function fn(e){return new ve(1,!0,e)}function Tt(e){return new ve(8,!0,e)}var Pt=class extends Jt{constructor(r,n,o,i){super(r.span,i);this.layout=r,this.decoder=n,this.encoder=o}decode(r,n){return this.decoder(this.layout.decode(r,n))}encode(r,n,o){return this.layout.encode(this.encoder(r),n,o)}getSpan(r,n){return this.layout.getSpan(r,n)}};function M(e){return new Pt(Ve(32),t=>new gi(t),t=>t.toBuffer(),e)}function kt(e){return new Pt(un(),yi,hi,e)}function yi(e){if(e===0)return!1;if(e===1)return!0;throw new Error("Invalid bool: "+e)}function hi(e){return e?1:0}var er=class extends an{decode(t,r){return super.decode(t,r)}};function j(e,t,r){return new er(e,t,r)}function Z(e,t,r){let n,o=typeof t=="number"?t:dn(t)?t.toNumber():new Proxy(t,{get(i,s){if(!n){let a=Reflect.get(i,"count");n=dn(a)?a.toNumber():a,Reflect.set(i,"count",n)}return Reflect.get(i,s)},set(i,s,a){return s==="count"&&(n=a),Reflect.set(i,s,a)}});return cn(e,o,r)}var Je=j([M("mint"),M("owner"),P("amount"),Qe("delegateOption"),M("delegate"),J("state"),Qe("isNativeOption"),P("isNative"),P("delegatedAmount"),Qe("closeAuthorityOption"),M("closeAuthority")]);var Yl=Q("Raydium_Util");function At({fromPublicKey:e,programId:t=xi}){let r=bi.generate().publicKey.toBase58().slice(0,32);return{publicKey:Pi(e,r,t),seed:r}}function Pi(e,t,r){let n=Buffer.concat([e.toBuffer(),Buffer.from(t),r.toBuffer()]),o=sn(n);return new wi(o)}import{PublicKey as Ti,SystemProgram as ki}from"@solana/web3.js";import Ai from"bn.js";import{createCloseAccountInstruction as Ii,createInitializeAccountInstruction as Si,createTransferInstruction as id,TOKEN_PROGRAM_ID as $e}from"@solana/spl-token";function Li(e){let{mint:t,tokenAccount:r,owner:n,programId:o=$e}=e;return Si(r,t,n,o)}function Bi(e){let{tokenAccount:t,payer:r,multiSigners:n=[],owner:o,programId:i=$e}=e;return Ii(t,r,o,n,i)}async function tr(e){let{connection:t,amount:r,commitment:n,payer:o,owner:i,skipCloseAccount:s}=e,a=await t.getMinimumBalanceForRentExemption(Je.span,n),c=E(r).add(new Ai(a)),u=At({fromPublicKey:o,programId:$e});return{addresses:{newAccount:u.publicKey},signers:[],instructions:[ki.createAccountWithSeed({fromPubkey:o,basePubkey:o,seed:u.seed,newAccountPubkey:u.publicKey,lamports:c.toNumber(),space:Je.span,programId:$e}),Li({mint:new Ti(oe.address),tokenAccount:u.publicKey,owner:i,programId:$e})],instructionTypes:[H.CreateAccount,H.InitAccount],endInstructionTypes:s?[]:[H.CloseAccount],endInstructions:s?[]:[Bi({tokenAccount:u.publicKey,payer:o,owner:i})]}}var rr=(...e)=>e.map(t=>{try{return typeof t=="object"?JSON.stringify(t):t}catch{return t}}).join(", "),et=class{constructor({scope:t,moduleName:r}){this.disabled=!1;this.scope=t,this.logger=Q(r)}createTxBuilder(t){return this.scope.checkOwner(),new ht({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(rr(t))}logInfo(...t){this.logger.info(rr(t))}logAndCreateError(...t){let r=rr(t);throw new Error(r)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};import{PublicKey as gn}from"@solana/web3.js";var nr=j([J("instruction")]),or=j([J("instruction")]),Ri=j([P("rewardState"),P("rewardOpenTime"),P("rewardEndTime"),P("rewardLastUpdateTime"),P("totalReward"),P("totalRewardEmissioned"),P("rewardClaimed"),P("rewardPerSecond"),we("accRewardPerShare"),M("rewardVault"),M("rewardMint"),M("rewardSender"),P("rewardType"),Z(P(),15,"padding")]),Ki=j([P("state"),P("nonce"),M("lpVault"),M("rewardVault"),M(),M(),P(),P(),P("totalReward"),we("perShareReward"),P("lastSlot"),P("perSlotReward")]),Ci=j([P("state"),P("nonce"),M("lpVault"),M("rewardVaultA"),P("totalRewardA"),we("perShareRewardA"),P("perSlotRewardA"),J("option"),M("rewardVaultB"),Ve(7),P("totalRewardB"),we("perShareRewardB"),P("perSlotRewardB"),P("lastSlot"),M()]),Vi=j([P(),P("state"),P("nonce"),P("validRewardTokenNum"),we("rewardMultiplier"),P("rewardPeriodMax"),P("rewardPeriodMin"),P("rewardPeriodExtend"),M("lpMint"),M("lpVault"),Z(Ri,5,"rewardInfos"),M("creator"),M(),Z(P(),32,"padding")]),Ei=new Proxy(Ki,{get(e,t,r){return t==="decode"?(...n)=>{let o=e.decode(...n);return{...o,version:3,rewardInfos:[{rewardVault:o.rewardVault,totalReward:o.totalReward,perSlotReward:o.perSlotReward,perShareReward:o.perShareReward}]}}:Reflect.get(e,t,r)}}),Mi=new Proxy(Ci,{get(e,t,r){return t==="decode"?(...n)=>{let o=e.decode(...n);return{...o,version:5,rewardInfos:[{rewardVault:o.rewardVaultA,totalReward:o.totalRewardA,perSlotReward:o.perSlotRewardA,perShareReward:o.perShareRewardA},{rewardVault:o.rewardVaultB,totalReward:o.totalRewardB,perSlotReward:o.perSlotRewardB,perShareReward:o.perShareRewardB}]}}:Reflect.get(e,t,r)}}),It=new Proxy(Vi,{get(e,t,r){return t==="decode"?(...n)=>{let o=e.decode(...n);return{...o,version:6,rewardInfos:o.rewardInfos.map(i=>{var s;return{...i,rewardType:((s=Object.entries(Le).find(a=>String(a[1])===i.rewardType.toString()))!=null?s:["Standard SPL"])[0]}})}}:Reflect.get(e,t,r)}}),Ni=j([P("isSet"),P("rewardPerSecond"),P("rewardOpenTime"),P("rewardEndTime"),P("rewardType")]),ir=j([J("instruction"),P("nonce"),Z(Ni,5,"rewardTimeInfo")]),sr=j([J("instruction"),P("rewardReopenTime"),P("rewardEndTime"),P("rewardPerSecond")]),ar=j([J("instruction"),P("isSet"),P("rewardPerSecond"),P("rewardOpenTime"),P("rewardEndTime"),P("rewardType")]),xd=j([P("state"),M("id"),M("owner"),P("deposited"),Z(P(),1,"rewardDebts")]),ur=j([P("state"),M("id"),M("owner"),P("deposited"),Z(we(),1,"rewardDebts"),P(""),P("voteLockedBalance"),Z(P(),15)]),Pd=j([P("state"),M("id"),M("owner"),P("deposited"),Z(P(),2,"rewardDebts")]),pn=j([P("state"),M("id"),M("owner"),P("deposited"),Z(we(),2,"rewardDebts"),Z(P(),17)]),mn=j([P(),P("state"),M("id"),M("owner"),P("deposited"),Z(we(),5,"rewardDebts"),Z(P(),16)]),se=j([J("instruction"),P("amount")]),Fi=j([M("mint"),M("grantAuthority"),P("baselineVoteWeightScaledFactor"),P("maxExtraLockupVoteWeightScaledFactor"),P("lockupSaturationSecs"),fn("digitShift"),Z(J(),7,"reserved1"),Z(P(),7,"reserved2")]),_i=j([Ve(8),M("governanceProgramId"),M("realm"),M("realmGoverningTokenMint"),M("realmAuthority"),Z(J(),32,"reserved1"),Z(Fi,4,"votingMints"),Tt("timeOffset"),J("bump"),Z(J(),7,"reserved2"),Z(P(),11,"reserved3")]),vi=j([Tt("startTime"),Tt("endTime"),J("kind"),Z(J(),15,"reserved")]),Di=j([Z(vi,1,"lockup"),P("amountDeposited_native"),P("amountInitiallyLockedNative"),kt("isUsed"),kt("allowClawback"),J("votingMintConfigIdx"),Z(J(),29,"reserved")]),Oi=j([Ve(8),M("voterAuthority"),M("registrar"),Z(Di,32,"deposits"),J("voterBump"),J("voterWweightRecordBump"),Z(J(),94,"reserved")]);var Rd=Q("Raydium_farm_config"),yn=new gn("2cpMA1jNS4obgRz8XNg38QuSP83L1AXpUgfxPNcvnAGj"),hn=new gn("FrspKwj8i3pNmKwXreTveC4fu7KL5ZbGeXdZBe2XViu1");var bn={3:ur,5:pn,6:mn},cr=e=>[3,5,6].indexOf(e)!==-1,lr=e=>{var s;let{version:t,rewardInfos:r,rewardTokenAccountsPublicKeys:n}=e,o=`rewardInfo:${JSON.stringify(r)}, rewardAccount:${JSON.stringify(n)}`,i={3:()=>{if(r.length!==1||n.length!==1)return`rewardInfos or rewardTokenAccounts lengths not equal 1: ${o}`},5:()=>{if(r.length!==n.length)return`rewardInfos and rewardTokenAccounts lengths not equal: ${o}`},6:()=>{if(!n.length||r.length!==n.length)return`no rewardTokenAccounts or rewardInfos and rewardTokenAccounts lengths not equal: ${o}`}};return(s=i[t])==null?void 0:s.call(i)},Le={"Standard SPL":0,"Option tokens":1},xe={[Jr.toString()]:3,[$r.toString()]:5,[je.toString()]:6};import{PublicKey as v,SystemProgram as Pn,SYSVAR_CLOCK_PUBKEY as St,SYSVAR_RENT_PUBKEY as qi,TransactionInstruction as le}from"@solana/web3.js";import Tn from"bn.js";import{ASSOCIATED_TOKEN_PROGRAM_ID as cf,createAssociatedTokenAccountInstruction as lf,TOKEN_PROGRAM_ID as Be}from"@solana/spl-token";import Wi from"bn.js";var Ui=Q("Raydium.farm.util");function tt({programId:e,poolId:t,mint:r,type:n}){let{publicKey:o}=Ke([t.toBuffer(),r.toBuffer(),Buffer.from(n==="lpVault"?"lp_vault_associated_seed":n==="rewardVault"?"reward_vault_associated_seed":"","utf-8")],e);return o}function fe({programId:e,poolId:t,owner:r,version:n}){let{publicKey:o}=Ke([t.toBuffer(),r.toBuffer(),Buffer.from(n===6?"farmer_info_associated_seed":"staker_info_v2_associated_seed","utf-8")],e);return o}var wn=({programId:e,poolId:t})=>Ke([t.toBuffer()],e);function xn(e){return{isSet:new Wi(1),rewardPerSecond:E(e.perSecond),rewardOpenTime:E(e.openTime),rewardEndTime:E(e.endTime),rewardType:E(Le[e.rewardType])}}function dr(e){return E(e.endTime).sub(E(e.openTime)).mul(E(e.perSecond))}function fr(e){let t=bn[e];return t||Ui.logWithError("invalid version",e),t}var Gi=Q("Raydium_farm_instruction"),Pf={voterStakeRegistryCreateVoter:Buffer.from([6,24,245,52,243,255,148,25]),voterStakeRegistryCreateDepositEntry:Buffer.from([185,131,167,186,159,125,19,67]),voterStakeRegistryDeposit:Buffer.from([242,35,198,137,82,225,242,182]),voterStakeRegistryWithdraw:Buffer.from([183,18,70,156,148,109,161,34]),voterStakeRegistryUpdateVoterWeightRecord:Buffer.from([45,185,3,36,109,190,115,169])};function pr(e){let{version:t,id:r,ledger:n,programId:o,owner:i}=e,s={3:9,5:10}[t];s||Gi.logWithError(`invalid farm pool version: ${t}`);let a=Buffer.alloc(nr.span);nr.encode({instruction:s},a);let c=[h({pubkey:r}),h({pubkey:n}),h({pubkey:i,isWritable:!1}),h({pubkey:Pn.programId,isWritable:!1}),h({pubkey:qi,isWritable:!1})];return{instruction:new le({programId:o,keys:c,data:a}),instructionType:H.FarmV3CreateLedger}}function kn(e){var n;let t=Buffer.alloc(ir.span);ir.encode({instruction:0,nonce:new Tn(e.nonce),rewardTimeInfo:e.rewardInfoConfig},t);let r=[...Dt,h({pubkey:e.farmId}),h({pubkey:e.farmAuthority,isWritable:!1}),h({pubkey:e.lpVault}),h({pubkey:e.lpMint,isWritable:!1}),h({pubkey:e.lockVault}),h({pubkey:e.lockMint,isWritable:!1}),h({pubkey:(n=e.lockUserAccount)!=null?n:ee}),h({pubkey:e.owner,isWritable:!1,isSigner:!0})];for(let o of e.rewardInfo)r.push(h({pubkey:o.rewardMint,isWritable:!1}),h({pubkey:o.rewardVault}),h({pubkey:o.userRewardToken}));return{instruction:new le({programId:e.programId,keys:r,data:t}),instructionType:H.FarmV6Create}}function An(e){let t=Buffer.alloc(or.span);or.encode({instruction:5},t);let r=[h({pubkey:Be,isWritable:!1}),h({pubkey:e.id}),h({pubkey:e.authority,isWritable:!1}),h({pubkey:e.lpVault,isWritable:!1}),h({pubkey:e.rewardVault}),h({pubkey:e.userRewardToken}),h({pubkey:e.owner,isWritable:!1,isSigner:!0})];return{instruction:new le({programId:e.programId,keys:r,data:t}),instructionType:H.FarmV6CreatorWithdraw}}function mr({payer:e,rewardVault:t,userRewardTokenPub:r,farmKeys:n,rewardInfo:o}){let i=Buffer.alloc(sr.span);sr.encode({instruction:3,rewardReopenTime:E(o.openTime),rewardEndTime:E(o.endTime),rewardPerSecond:E(o.perSecond)},i);let s=[h({pubkey:Be,isWritable:!1}),h({pubkey:n.id}),h({pubkey:n.lpVault,isWritable:!1}),h({pubkey:t}),h({pubkey:r}),h({pubkey:e,isWritable:!1,isSigner:!0})];return new le({programId:n.programId,keys:s,data:i})}function gr({payer:e,userRewardTokenPub:t,farmKeys:r,rewardVault:n,rewardInfo:o}){let i=Buffer.alloc(ar.span);ar.encode({instruction:4,isSet:new Tn(1),rewardPerSecond:E(o.perSecond),rewardOpenTime:E(o.openTime),rewardEndTime:E(o.endTime),rewardType:E(Le[o.rewardType])},i);let s=[...Dt,h({pubkey:r.id}),h({pubkey:r.authority,isWritable:!1}),h({pubkey:o.mint,isWritable:!1}),h({pubkey:n}),h({pubkey:t}),h({pubkey:e,isWritable:!1,isSigner:!0})];return new le({programId:r.programId,keys:s,data:i})}function yr(e){let{farmInfo:t,farmKeys:r,lpAccount:n,rewardAccounts:o,owner:i,amount:s}=e,[a,c]=[new v(t.programId),new v(t.id)],u=fe({programId:a,poolId:c,owner:i,version:6}),l=Buffer.alloc(se.span);se.encode({instruction:2,amount:E(s)},l);let d=[h({pubkey:Be,isWritable:!1}),h({pubkey:c}),h({pubkey:new v(r.authority),isWritable:!1}),h({pubkey:new v(r.lpVault)}),h({pubkey:u}),h({pubkey:i,isWritable:!1,isSigner:!0}),h({pubkey:n})];for(let f=0;f<r.rewardInfos.length;f++)d.push(h({pubkey:new v(r.rewardInfos[f].vault)})),d.push(h({pubkey:o[f]}));return new le({programId:a,keys:d,data:l})}function hr(e){let{farmInfo:t,farmKeys:r,lpAccount:n,rewardAccounts:o,owner:i,amount:s,userAuxiliaryLedgers:a}=e,[c,u]=[new v(t.programId),new v(t.id)],l=fe({programId:c,poolId:u,owner:i,version:5}),d=Buffer.alloc(se.span);se.encode({instruction:12,amount:E(s)},d);let f=[h({pubkey:u}),h({pubkey:new v(r.authority),isWritable:!1}),h({pubkey:l}),h({pubkey:i,isWritable:!1,isSigner:!0}),h({pubkey:n}),h({pubkey:new v(r.lpVault)}),h({pubkey:o[0]}),h({pubkey:new v(r.rewardInfos[0].vault)}),h({pubkey:St,isWritable:!1}),h({pubkey:Be,isWritable:!1})];for(let p=1;p<r.rewardInfos.length;p++)f.push(h({pubkey:o[p]})),f.push(h({pubkey:new v(r.rewardInfos[p].vault)}));if(a)for(let p of a)f.push(h({pubkey:p}));return new le({programId:c,keys:f,data:d})}function br(e){let{farmInfo:t,farmKeys:r,lpAccount:n,rewardAccounts:o,owner:i,amount:s,userAuxiliaryLedgers:a}=e,[c,u]=[new v(t.programId),new v(t.id)],l=fe({programId:c,poolId:u,owner:i,version:3}),d=Buffer.alloc(se.span);se.encode({instruction:11,amount:E(s)},d);let f=[h({pubkey:u}),h({pubkey:new v(r.authority),isWritable:!1}),h({pubkey:l}),h({pubkey:i,isWritable:!1,isSigner:!0}),h({pubkey:n}),h({pubkey:new v(r.lpVault)}),h({pubkey:o[0]}),h({pubkey:new v(r.rewardInfos[0].vault)}),h({pubkey:St,isWritable:!1}),h({pubkey:Be,isWritable:!1})];if(a)for(let p of a)f.push(h({pubkey:p}));return new le({programId:c,keys:f,data:d})}function In(e){let{farmInfo:t,farmKeys:r,lpAccount:n,rewardAccounts:o,owner:i,amount:s,userAuxiliaryLedgers:a}=e,[c,u]=[new v(t.programId),new v(t.id)],l=fe({programId:c,poolId:u,owner:i,version:3}),d=Buffer.alloc(se.span);se.encode({instruction:10,amount:E(s)},d);let f=[h({pubkey:u}),h({pubkey:new v(r.authority),isWritable:!1}),h({pubkey:l}),h({pubkey:i,isWritable:!1,isSigner:!0}),h({pubkey:n}),h({pubkey:new v(r.lpVault)}),h({pubkey:o[0]}),h({pubkey:new v(r.rewardInfos[0].vault)}),h({pubkey:St,isWritable:!1}),h({pubkey:Be,isWritable:!1})];if(a)for(let p of a)f.push(h({pubkey:p}));return new le({programId:c,keys:f,data:d})}function Sn(e){let{farmInfo:t,farmKeys:r,lpAccount:n,rewardAccounts:o,owner:i,amount:s,userAuxiliaryLedgers:a}=e,[c,u]=[new v(t.programId),new v(t.id)],l=fe({programId:c,poolId:u,owner:i,version:5}),d=Buffer.alloc(se.span);se.encode({instruction:11,amount:E(s)},d);let f=[h({pubkey:u}),h({pubkey:new v(r.authority),isWritable:!1}),h({pubkey:l}),h({pubkey:i,isWritable:!1,isSigner:!0}),h({pubkey:n}),h({pubkey:new v(r.lpVault)}),h({pubkey:o[0]}),h({pubkey:new v(r.rewardInfos[0].vault)}),h({pubkey:St,isWritable:!1}),h({pubkey:Be,isWritable:!1})];for(let p=1;p<r.rewardInfos.length;p++)f.push(h({pubkey:o[p]})),f.push(h({pubkey:new v(r.rewardInfos[p].vault)}));if(a)for(let p of a)f.push(h({pubkey:p}));return new le({programId:c,keys:f,data:d})}function Ln(e){let{farmInfo:t,farmKeys:r,lpAccount:n,rewardAccounts:o,owner:i,amount:s}=e,[a,c]=[new v(t.programId),new v(t.id)],u=fe({programId:a,poolId:c,owner:i,version:6}),l=Buffer.alloc(se.span);se.encode({instruction:1,amount:E(s)},l);let d=[h({pubkey:Be,isWritable:!1}),h({pubkey:Pn.programId,isWritable:!1}),h({pubkey:c}),h({pubkey:new v(r.authority),isWritable:!1}),h({pubkey:new v(r.lpVault)}),h({pubkey:u}),h({pubkey:i,isWritable:!1,isSigner:!0}),h({pubkey:n})];for(let f=0;f<r.rewardInfos.length;f++)d.push(h({pubkey:new v(r.rewardInfos[f].vault)})),d.push(h({pubkey:o[f]}));return new le({programId:a,keys:d,data:l})}var wr=class extends et{async _getUserRewardInfo({payer:t,rewardInfo:r}){if(r.mint.equals(ee)){let n=await tr({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:t,amount:dr({...r,openTime:r.openTime.toString(),endTime:r.endTime.toString()})});return{rewardPubKey:n.addresses.newAccount,newInstruction:n}}return{rewardPubKey:await this.scope.account.getCreatedTokenAccount({mint:r.mint,associatedOnly:!1})}}async create({poolInfo:t,rewardInfos:r,payer:n,programId:o=je,txVersion:i}){this.checkDisabled(),this.scope.checkOwner();let a={lpMint:new W(t.lpMint.address),lockInfo:{lockMint:yn,lockVault:hn},version:6,rewardInfos:r,programId:o},c=this.createTxBuilder(),u=n!=null?n:this.scope.ownerPubKey,l=At({fromPublicKey:u,programId:a.programId}),d=await this.scope.connection.getMinimumBalanceForRentExemption(It.span);c.addInstruction({instructions:[Hi.createAccountWithSeed({fromPubkey:u,basePubkey:u,seed:l.seed,newAccountPubkey:l.publicKey,lamports:d,space:It.span,programId:a.programId})]});let{publicKey:f,nonce:p}=wn({programId:new W(a.programId),poolId:l.publicKey}),g=tt({programId:a.programId,poolId:l.publicKey,mint:a.lpMint,type:"lpVault"}),m=[],T=[];for(let A of a.rewardInfos){A.openTime>=A.endTime&&this.logAndCreateError("start time error","rewardInfo.rewardOpenTime",A.openTime.toString()),isNaN(Le[A.rewardType])&&this.logAndCreateError("rewardType error",A.rewardType),Number(A.perSecond)<=0&&this.logAndCreateError("rewardPerSecond error",A.perSecond),m.push(xn(A));let{rewardPubKey:R,newInstruction:N}=await this._getUserRewardInfo({rewardInfo:A,payer:u});N&&c.addInstruction(N),R||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts);let _=A.mint.equals(ee)?new W(oe.address):A.mint;T.push({rewardMint:_,rewardVault:tt({programId:a.programId,poolId:l.publicKey,mint:_,type:"rewardVault"}),userRewardToken:R})}let{account:w,instructionParams:x}=await this.scope.account.getOrCreateTokenAccount({mint:new W(a.lockInfo.lockMint),owner:this.scope.ownerPubKey,skipCloseAccount:!1,createInfo:{payer:this.scope.ownerPubKey,amount:0},associatedOnly:!1});x&&c.addInstruction(x),w||this.logAndCreateError("cannot found lock vault","tokenAccounts",this.scope.account.tokenAccounts);let{instruction:b,instructionType:k}=kn({farmId:l.publicKey,owner:this.scope.ownerPubKey,farmAuthority:f,lpVault:g,lpMint:a.lpMint,lockVault:a.lockInfo.lockVault,lockMint:a.lockInfo.lockMint,lockUserAccount:w,programId:a.programId,rewardInfo:T,rewardInfoConfig:m,nonce:p});return c.addInstruction({instructions:[b],instructionTypes:[k]}).versionBuild({txVersion:i,extInfo:{farmId:l.publicKey,farmAuthority:f,lpVault:g,lockUserAccount:w,nonce:p}})}async restartReward({farmInfo:t,payer:r,newRewardInfo:n,txVersion:o}){var T;let i=xe[t.programId];i!==6&&this.logAndCreateError("invalid farm version ",i);let s=he((await this.scope.api.fetchFarmKeysById({ids:t.id}))[0]),a={id:s.id,rewardInfos:t.rewardInfos,lpVault:s.lpVault,programId:s.programId};n.openTime>=n.endTime&&this.logAndCreateError("start time error","newRewardInfo",n);let c=r||this.scope.ownerPubKey,u=n.mint.equals(ee)?new W(oe.address):n.mint,l=a.rewardInfos.findIndex(w=>new W(w.mint.address).equals(u)),d=s.rewardInfos[l];d||this.logAndCreateError("configuration does not exist","rewardMint",u);let f=(T=d.vault)!=null?T:ee,p=this.createTxBuilder(),{rewardPubKey:g,newInstruction:m}=await this._getUserRewardInfo({rewardInfo:n,payer:c});return m&&p.addInstruction(m),g||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts),p.addInstruction({instructions:[mr({payer:this.scope.ownerPubKey,rewardVault:f,userRewardTokenPub:g,farmKeys:a,rewardInfo:n})],instructionTypes:[H.FarmV6Restart]}).versionBuild({txVersion:o})}async restartRewards({farmInfo:t,payer:r,newRewardInfos:n,txVersion:o}){var l;let i=xe[t.programId];i!==6&&this.logAndCreateError("invalid farm version ",i);let s=he((await this.scope.api.fetchFarmKeysById({ids:t.id}))[0]),a={id:s.id,rewardInfos:t.rewardInfos,lpVault:s.lpVault,programId:s.programId};n.forEach(d=>{d.openTime>=d.endTime&&this.logAndCreateError("start time error","newRewardInfo",d)});let c=r||this.scope.ownerPubKey,u=this.createTxBuilder();for(let d of n){let f=d.mint.equals(ee)?new W(oe.address):d.mint,p=a.rewardInfos.findIndex(b=>new W(b.mint.address).equals(f)),g=s.rewardInfos[p];g||this.logAndCreateError("configuration does not exist","rewardMint",f);let m=(l=g.vault)!=null?l:ee,{rewardPubKey:T,newInstruction:w}=await this._getUserRewardInfo({rewardInfo:d,payer:c});w&&u.addInstruction(w),T||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts);let x=mr({payer:this.scope.ownerPubKey,rewardVault:m,userRewardTokenPub:T,farmKeys:a,rewardInfo:d});u.addInstruction({instructions:[x],instructionTypes:[H.FarmV6Restart]})}return u.versionBuild({txVersion:o})}async addNewRewardToken(t){let{txVersion:r,farmInfo:n,newRewardInfo:o,payer:i}=t,s=xe[n.programId];s!==6&&this.logAndCreateError("invalid farm version ",s);let a=he((await this.scope.api.fetchFarmKeysById({ids:n.id}))[0]),c=i!=null?i:this.scope.ownerPubKey,u=this.createTxBuilder(),l=o.mint.equals(ee)?new W(oe.address):o.mint,d=tt({programId:new W(n.programId),poolId:new W(n.id),mint:l,type:"rewardVault"}),{rewardPubKey:f,newInstruction:p}=await this._getUserRewardInfo({rewardInfo:o,payer:c});return p&&u.addInstruction(p),f||this.logAndCreateError("annot found target token accounts",this.scope.account.tokenAccounts),o.mint=l,u.addInstruction({instructions:[gr({payer:this.scope.ownerPubKey,userRewardTokenPub:f,farmKeys:a,rewardVault:d,rewardInfo:o})],instructionTypes:[H.FarmV6CreatorAddReward]}).versionBuild({txVersion:r})}async addNewRewardsToken(t){let{txVersion:r,farmInfo:n,newRewardInfos:o,payer:i}=t,s=xe[n.programId];s!==6&&this.logAndCreateError("invalid farm version ",s);let a=he((await this.scope.api.fetchFarmKeysById({ids:n.id}))[0]),c=i!=null?i:this.scope.ownerPubKey,u=this.createTxBuilder();for(let l of o){let d=l.mint.equals(ee)?new W(oe.address):l.mint,f=tt({programId:new W(n.programId),poolId:new W(n.id),mint:d,type:"rewardVault"}),{rewardPubKey:p,newInstruction:g}=await this._getUserRewardInfo({rewardInfo:l,payer:c});g&&u.addInstruction(g),p||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts);let m=gr({payer:this.scope.ownerPubKey,userRewardTokenPub:p,farmKeys:a,rewardVault:f,rewardInfo:{...l,mint:d}});u.addInstruction({instructions:[m],instructionTypes:[H.FarmV6CreatorAddReward]})}return u.versionBuild({txVersion:r})}async deposit(t){let{txVersion:r,farmInfo:n,amount:o,feePayer:i,useSOLBalance:s,associatedOnly:a=!0,checkCreateATAOwner:c=!1,userAuxiliaryLedgers:u,computeBudgetConfig:l}=t;this.scope.availability.addFarm===!1&&this.logAndCreateError("farm deposit feature disabled in your region");let{rewardInfos:d,programId:f}=n,p=xe[f];cr(p)||this.logAndCreateError("invalid farm program:",n.programId);let[g,m]=[new W(n.programId),new W(n.id)],T=(await this.scope.api.fetchFarmKeysById({ids:n.id}))[0],w=fe({programId:g,poolId:m,owner:this.scope.ownerPubKey,version:p}),x=this.createTxBuilder();x.addCustomComputeBudget(l);let b={};for(let F of this.scope.account.tokenAccounts)if(a){let te=_e(this.scope.ownerPubKey,F.mint,F.programId).publicKey;F.publicKey&&te.equals(F.publicKey)&&(b[F.mint.toString()]=F.publicKey)}else b[F.mint.toString()]=F.publicKey;let k=T.lpMint,A=b[k.address];A||this.logAndCreateError("you don't have any lp","lp zero",b);let R=[];for(let F of d){let te=s&&F.mint.address===pe.toString(),X=b[F.mint.address];if(!X){let{account:D,instructionParams:xr}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:F.mint.programId,mint:new W(F.mint.address),notUseTokenAccount:te,createInfo:{payer:i||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!te,associatedOnly:te?!1:a,checkCreateATAOwner:c});X=D,xr&&x.addInstruction(xr)}b[F.mint.address]=X,R.push(X)}let N,_=await this.scope.connection.getAccountInfo(w);if(_&&(N=fr(p).decode(_.data)),n.programId!==je.toString()&&!N){let{instruction:F,instructionType:te}=pr({id:m,programId:g,version:p,ledger:w,owner:this.scope.ownerPubKey});x.addInstruction({instructions:[F],instructionTypes:[te]})}let L=lr({version:p,rewardInfos:d,rewardTokenAccountsPublicKeys:R});L&&this.logAndCreateError(L);let q={amount:E(o),owner:this.scope.ownerPubKey,farmInfo:n,farmKeys:T,lpAccount:A,rewardAccounts:R,userAuxiliaryLedgers:u==null?void 0:u.map(F=>new W(F))},U=p===6?Ln(q):p===5?Sn(q):In(q),z={3:H.FarmV3Deposit,5:H.FarmV5Deposit,6:H.FarmV6Deposit};return x.addInstruction({instructions:[U],instructionTypes:[z[p]]}).versionBuild({txVersion:r})}async withdraw(t){let{txVersion:r,farmInfo:n,amount:o,deposited:i,useSOLBalance:s,feePayer:a,associatedOnly:c=!0,checkCreateATAOwner:u=!1,userAuxiliaryLedgers:l,computeBudgetConfig:d}=t,{rewardInfos:f}=n;this.scope.availability.removeFarm===!1&&this.logAndCreateError("farm withdraw feature disabled in your region");let p=xe[n.programId];cr(p)||this.logAndCreateError("invalid farm program:",n.programId);let g=(await this.scope.api.fetchFarmKeysById({ids:n.id}))[0],m=this.createTxBuilder();m.addCustomComputeBudget(d);let T={};for(let L of this.scope.account.tokenAccounts)if(c){let q=_e(this.scope.ownerPubKey,L.mint).publicKey;L.publicKey&&q.equals(L.publicKey)&&(T[L.mint.toString()]=L.publicKey)}else T[L.mint.toString()]=L.publicKey;if(i)i.isZero()&&this.logAndCreateError("no deposited lp",{farmId:n.id});else{let L=fe({programId:new W(n.programId),poolId:new W(n.id),owner:this.scope.ownerPubKey,version:p}),q=await this.scope.connection.getAccountInfo(L);if(q)fr(p).decode(q.data).deposited.isZero()&&this.logAndCreateError("no deposited lp",{farmId:n.id});else if(p!==6&&(l||[]).length>0){let{instruction:U,instructionType:z}=pr({id:new W(g.id),programId:new W(g.programId),version:p,ledger:L,owner:this.scope.ownerPubKey});m.addInstruction({instructions:[U],instructionTypes:[z]})}else this.logAndCreateError("no lp data",{farmId:n.id,version:p,ledgerData:q})}let w=g.lpMint.address,x=s&&w===pe.toString(),b=T[w.toString()];if(!b){let{account:L,instructionParams:q}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:g.lpMint.programId,mint:new W(w),notUseTokenAccount:x,createInfo:{payer:a||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!0,associatedOnly:x?!1:c,checkCreateATAOwner:u});b=L,q&&m.addInstruction(q)}T[w.toString()]=b;let k=[];for(let L of f){let q=s&&L.mint.address===pe.toString(),U=T[L.mint.address];if(!U){let{account:z,instructionParams:F}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:L.mint.programId,mint:new W(L.mint.address),notUseTokenAccount:q,createInfo:{payer:a||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!q,associatedOnly:q?!1:c,checkCreateATAOwner:u});U=z,F&&m.addInstruction(F)}T[L.mint.address]=U,k.push(U)}let A=lr({version:p,rewardInfos:f,rewardTokenAccountsPublicKeys:k});A&&this.logAndCreateError(A);let R={amount:E(o),owner:this.scope.ownerPubKey,farmInfo:n,farmKeys:g,lpAccount:b,rewardAccounts:k,userAuxiliaryLedgers:l==null?void 0:l.map(L=>new W(L))},N=p===6?yr(R):p===5?hr(R):br(R),_={3:H.FarmV3Withdraw,5:H.FarmV5Withdraw,6:H.FarmV6Withdraw};return m.addInstruction({instructions:[N],instructionTypes:[_[p]]}).versionBuild({txVersion:r})}async withdrawFarmReward({farmInfo:t,withdrawMint:r,txVersion:n}){var p;this.scope.checkOwner();let o=he((await this.scope.api.fetchFarmKeysById({ids:t.id}))[0]),i=xe[t.programId];i!==6&&this.logAndCreateError("invalid farm version",i);let s=t.rewardInfos.findIndex(g=>g.mint.address===ee.toString()?new W(oe.address):r),a=o.rewardInfos[s];a||this.logAndCreateError("withdraw mint error","rewardInfos",t);let c=(p=a==null?void 0:a.vault)!=null?p:ee,u=this.createTxBuilder(),l;if(r.equals(ee)){let g=await tr({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:this.scope.ownerPubKey,amount:dr({...a,openTime:a.openTime,endTime:a.endTime,perSecond:new Ft(a.perSecond).mul(10**a.mint.decimals).toString()})});l=g.addresses.newAccount,u.addInstruction(g)}else{let g=await this.scope.account.getCreatedTokenAccount({mint:r});g===null?(l=await this.scope.account.getAssociatedTokenAccount(r),u.addInstruction({instructions:[ji(this.scope.ownerPubKey,l,this.scope.ownerPubKey,r)],instructionTypes:[H.CreateATA]})):l=g}let{instruction:d,instructionType:f}=An({programId:o.programId,id:o.id,authority:o.authority,lpVault:o.lpVault,rewardVault:c,userRewardToken:l,owner:this.scope.ownerPubKey});return u.addInstruction({instructions:[d],instructionTypes:[f]}).versionBuild({txVersion:n})}async harvestAllRewards(t){let{farmInfoList:r,useSOLBalance:n,feePayer:o,associatedOnly:i=!0,checkCreateATAOwner:s=!1,userAuxiliaryLedgers:a,txVersion:c,computeBudgetConfig:u}=t,l=this.createTxBuilder(),d={};for(let g of this.scope.account.tokenAccounts)if(i){let m=_e(this.scope.ownerPubKey,g.mint).publicKey;g.publicKey&&m.equals(g.publicKey)&&(d[g.mint.toString()]=g.publicKey)}else d[g.mint.toString()]=g.publicKey;let p=(await this.scope.api.fetchFarmKeysById({ids:Object.values(r).map(g=>g.id).join(",")})).reduce((g,m)=>({...g,[m.id]:m}),{});for(let g of Object.values(r)){let{programId:m,lpMint:T,rewardInfos:w,id:x}=g,b=xe[m],k=T.address,A=n&&k===pe.toString(),R=d[k];if(!R){let{account:z,instructionParams:F}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:T.programId,mint:new W(k),notUseTokenAccount:A,createInfo:{payer:o||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!0,associatedOnly:A?!1:i,checkCreateATAOwner:s});R=z,F&&l.addInstruction(F)}d[k.toString()]=R;let N=[];for(let z of w){let F=n&&z.mint.address===pe.toString(),te=d[z.mint.address];if(!te){let{account:X,instructionParams:D}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:z.mint.programId,mint:new W(z.mint.address),notUseTokenAccount:F,createInfo:{payer:o||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!F,associatedOnly:F?!1:i,checkCreateATAOwner:s});te=X,D&&l.addInstruction(D)}d[z.mint.address]=te,N.push(te)}let _=p[x],L={amount:Ht,owner:this.scope.ownerPubKey,farmInfo:g,farmKeys:_,lpAccount:R,rewardAccounts:N,userAuxiliaryLedgers:a==null?void 0:a.map(z=>new W(z))},q=b===6?yr(L):b===5?hr(L):br(L),U={3:H.FarmV3Withdraw,5:H.FarmV5Withdraw,6:H.FarmV6Withdraw};l.addInstruction({instructions:[q],instructionTypes:[U[b]]})}return c===1?l.sizeCheckBuild({computeBudgetConfig:u}):l.sizeCheckBuildV0({computeBudgetConfig:u})}};export{wr 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=farm.mjs.map