UNPKG

@raydium-io/raydium-sdk-v2

Version:

An SDK for building applications on top of Raydium.

3 lines 479 kB
var _l=Object.create;var ni=Object.defineProperty,Vl=Object.defineProperties,El=Object.getOwnPropertyDescriptor,Dl=Object.getOwnPropertyDescriptors,Wl=Object.getOwnPropertyNames,nr=Object.getOwnPropertySymbols,ql=Object.getPrototypeOf,aa=Object.prototype.hasOwnProperty,nu=Object.prototype.propertyIsEnumerable;var tu=(d,e,t)=>e in d?ni(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t,N=(d,e)=>{for(var t in e||(e={}))aa.call(e,t)&&tu(d,t,e[t]);if(nr)for(var t of nr(e))nu.call(e,t)&&tu(d,t,e[t]);return d},V=(d,e)=>Vl(d,Dl(e));var Qe=(d,e)=>{var t={};for(var n in d)aa.call(d,n)&&e.indexOf(n)<0&&(t[n]=d[n]);if(d!=null&&nr)for(var n of nr(d))e.indexOf(n)<0&&nu.call(d,n)&&(t[n]=d[n]);return t};var Ul=(d,e)=>{for(var t in e)ni(d,t,{get:e[t],enumerable:!0})},ou=(d,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wl(e))!aa.call(d,o)&&o!==t&&ni(d,o,{get:()=>e[o],enumerable:!(n=El(e,o))||n.enumerable});return d};var te=(d,e,t)=>(t=d!=null?_l(ql(d)):{},ou(e||!d||!d.__esModule?ni(t,"default",{value:d,enumerable:!0}):t,d)),Gl=d=>ou(ni({},"__esModule",{value:!0}),d);var _d={};Ul(_d,{Raydium:()=>er});module.exports=Gl(_d);var Nl=require("lodash");var Ws=te(require("axios"));var la=require("@solana/web3.js");var oi=require("lodash");var sa=class{constructor(e){this.logLevel=e.logLevel!==void 0?e.logLevel:0,this.name=e.name}set level(e){this.logLevel=e}get time(){return Date.now().toString()}get moduleName(){return this.name}isLogLevel(e){return e<=this.logLevel}error(...e){return this.isLogLevel(0)?(console.error(this.time,this.name,"sdk logger error",...e),this):this}logWithError(...e){let t=e.map(n=>typeof n=="object"?JSON.stringify(n):n).join(", ");throw new Error(t)}warning(...e){return this.isLogLevel(1)?(console.warn(this.time,this.name,"sdk logger warning",...e),this):this}info(...e){return this.isLogLevel(2)?(console.info(this.time,this.name,"sdk logger info",...e),this):this}debug(...e){return this.isLogLevel(3)?(console.debug(this.time,this.name,"sdk logger debug",...e),this):this}},iu={},zl={};function Be(d){let e=(0,oi.get)(iu,d);if(!e){let t=(0,oi.get)(zl,d);e=new sa({name:d,logLevel:t}),(0,oi.set)(iu,d,e)}return e}var zn=require("@solana/spl-token"),ua=Be("Raydium_accountInfo_util");async function It(d,e,t){let{batchRequest:n,commitment:o="confirmed",chunkCount:i=100}=N({batchRequest:!1},t),r=ca(e,i),a=new Array(r.length).fill([]);if(n){let u=r.map(l=>{let m=d._buildArgs([l.map(p=>p.toBase58())],o,"base64");return{methodName:"getMultipleAccounts",args:m}}),s=ca(u,10);a=(await(await Promise.all(s.map(async l=>await d._rpcBatchRequest(l)))).flat()).map(l=>(l.error&&ua.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${l.error.message}`),l.result.value.map(m=>{if(m){let{data:p,executable:f,lamports:y,owner:b,rentEpoch:g}=m;return p.length!==2&&p[1]!=="base64"&&ua.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(p[0],"base64"),executable:f,lamports:y,owner:new la.PublicKey(b),rentEpoch:g}}return null})))}else try{a=await Promise.all(r.map(u=>d.getMultipleAccountsInfo(u,o)))}catch(u){u instanceof Error&&ua.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${u.message}`)}return a.flat()}async function Ge(d,e,t){let n=await It(d,e.map(o=>o.pubkey),t);return e.map((o,i)=>V(N({},o),{accountInfo:n[i]}))}async function so({connection:d,mints:e,config:t}){var i,r,a;if(e.length===0)return{};let n=await Ge(d,e.map(u=>({pubkey:Ot(u)})),t),o={};for(let u of n){if(!u.accountInfo||u.accountInfo.data.length<zn.MINT_SIZE){console.log("invalid mint account",u.pubkey.toBase58());continue}let s=(0,zn.unpackMint)(u.pubkey,u.accountInfo,(i=u.accountInfo)==null?void 0:i.owner);o[u.pubkey.toString()]=V(N({},s),{programId:((r=u.accountInfo)==null?void 0:r.owner)||zn.TOKEN_PROGRAM_ID,feeConfig:(a=(0,zn.getTransferFeeConfig)(s))!=null?a:void 0})}return o[la.PublicKey.default.toBase58()]=o[Z.toBase58()],o}var qn=te(require("bn.js")),Md=te(require("decimal.js"));var lu=te(require("big.js")),si=te(require("bn.js"));var ru=te(require("toformat")),Xl=ru.default,ii=Xl;var ri=te(require("big.js")),su=te(require("bn.js")),uu=te(require("decimal.js-light"));var Ro=te(require("bn.js"));var au=9007199254740991;function fe(d){let e=Be("Raydium_parseBigNumberish");if(d instanceof Ro.default)return d;if(typeof d=="string"){if(d.match(/^-?[0-9]+$/))return new Ro.default(d);e.logWithError(`invalid BigNumberish string: ${d}`)}return typeof d=="number"?(d%1&&e.logWithError(`BigNumberish number underflow: ${d}`),(d>=au||d<=-au)&&e.logWithError(`BigNumberish number overflow: ${d}`),new Ro.default(String(d))):typeof d=="bigint"?new Ro.default(d.toString()):(e.error(`invalid BigNumberish value: ${d}`),new Ro.default(0))}var or=Be("module/fraction"),ma=ii(ri.default),ai=ii(uu.default),Hl={[0]:ai.ROUND_DOWN,[1]:ai.ROUND_HALF_UP,[2]:ai.ROUND_UP},Ql={[0]:ri.default.roundDown,[1]:ri.default.roundHalfUp,[2]:ri.default.roundUp},ve=class{constructor(e,t=new su.default(1)){this.numerator=fe(e),this.denominator=fe(t)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new ve(this.denominator,this.numerator)}add(e){let t=e instanceof ve?e:new ve(fe(e));return this.denominator.eq(t.denominator)?new ve(this.numerator.add(t.numerator),this.denominator):new ve(this.numerator.mul(t.denominator).add(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}sub(e){let t=e instanceof ve?e:new ve(fe(e));return this.denominator.eq(t.denominator)?new ve(this.numerator.sub(t.numerator),this.denominator):new ve(this.numerator.mul(t.denominator).sub(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}mul(e){let t=e instanceof ve?e:new ve(fe(e));return new ve(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof ve?e:new ve(fe(e));return new ve(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},n=1){Number.isInteger(e)||or.logWithError(`${e} is not an integer.`),e<=0&&or.logWithError(`${e} is not positive.`),ai.set({precision:e+1,rounding:Hl[n]});let o=new ai(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return o.toFormat(o.decimalPlaces(),t)}toFixed(e,t={groupSeparator:""},n=1){return Number.isInteger(e)||or.logWithError(`${e} is not an integer.`),e<0&&or.logWithError(`${e} is negative.`),ma.DP=e,ma.RM=Ql[n]||1,new ma(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var Zl=Be("Raydium_amount"),cu=ii(lu.default);function jl(d,e){let t="0",n="0";if(d.includes(".")){let o=d.split(".");o.length===2?([t,n]=o,n=n.padEnd(e,"0")):Zl.logWithError(`invalid number string, num: ${d}`)}else t=d;return[t,n.slice(0,e)||n]}var _e=class extends ve{constructor(t,n,o=!0,i){let r=new si.default(0),a=da.pow(new si.default(t.decimals));if(o)r=fe(n);else{let u=new si.default(0),s=new si.default(0);if(typeof n=="string"||typeof n=="number"||typeof n=="bigint"){let[c,l]=jl(n.toString(),t.decimals);u=fe(c),s=fe(l)}u=u.mul(a),r=u.add(s)}super(r,a);this.logger=Be(i||"TokenAmount"),this.token=t}get raw(){return this.numerator}isZero(){return this.raw.isZero()}gt(t){return this.token.equals(t.token)||this.logger.logWithError("gt token not equals"),this.raw.gt(t.raw)}lt(t){return this.token.equals(t.token)||this.logger.logWithError("lt token not equals"),this.raw.lt(t.raw)}add(t){return this.token.equals(t.token)||this.logger.logWithError("add token not equals"),new _e(this.token,this.raw.add(t.raw))}subtract(t){return this.token.equals(t.token)||this.logger.logWithError("sub token not equals"),new _e(this.token,this.raw.sub(t.raw))}toSignificant(t=this.token.decimals,n,o=0){return super.toSignificant(t,n,o)}toFixed(t=this.token.decimals,n,o=0){return t>this.token.decimals&&this.logger.logWithError("decimals overflow"),super.toFixed(t,n,o)}toExact(t={groupSeparator:""}){return cu.DP=this.token.decimals,new cu(this.numerator.toString()).div(this.denominator.toString()).toFormat(t)}};var mu=require("@solana/web3.js"),pa=require("@solana/spl-token"),Xn={chainId:101,address:mu.PublicKey.default.toBase58(),programId:pa.TOKEN_PROGRAM_ID.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}},Ft={chainId:101,address:"So11111111111111111111111111111111111111112",programId:pa.TOKEN_PROGRAM_ID.toBase58(),decimals:9,symbol:"WSOL",name:"Wrapped SOL",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}};var ir=require("@solana/web3.js");var qe=require("@solana/web3.js"),du=require("@solana/spl-token");function K({pubkey:d,isSigner:e=!1,isWritable:t=!0}){return{pubkey:d,isWritable:t,isSigner:e}}var fa=[K({pubkey:du.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:qe.SystemProgram.programId,isWritable:!1}),K({pubkey:qe.SYSVAR_RENT_PUBKEY,isWritable:!1})];function ya({publicKey:d,transformSol:e}){let t=ba(d.toString());if(t instanceof qe.PublicKey)return e&&t.equals(Bt)?Z:t;if(e&&t.toString()===Bt.toBase58())return Z;if(typeof t=="string"){if(t===qe.PublicKey.default.toBase58())return qe.PublicKey.default;try{return new qe.PublicKey(t)}catch{throw new Error("invalid public key")}}throw new Error("invalid public key")}function ba(d){try{return new qe.PublicKey(d)}catch{return d}}var pn=new qe.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),vt=new qe.PublicKey("SysvarRent111111111111111111111111111111111"),mp=new qe.PublicKey("SysvarC1ock11111111111111111111111111111111"),Bn=new qe.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),$l=new qe.PublicKey("Sysvar1nstructions1111111111111111111111111"),pu=qe.SystemProgram.programId,dp=new qe.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),pp=new qe.PublicKey("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),fp=new qe.PublicKey("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),yp=new qe.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),bp=new qe.PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),gp=new qe.PublicKey("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Pp=new qe.PublicKey("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Ap=new qe.PublicKey("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),wp=new qe.PublicKey("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),kp=new qe.PublicKey("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),Tp=new qe.PublicKey("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),Z=new qe.PublicKey("So11111111111111111111111111111111111111112"),Bt=qe.PublicKey.default;function Ot(d){return ya({publicKey:d,transformSol:!0})}var ga=class{constructor({mint:e,decimals:t,symbol:n,name:o,skipMint:i=!1,isToken2022:r=!1}){if(e===Bt.toBase58()||e instanceof ir.PublicKey&&Bt.equals(e)){this.decimals=Ft.decimals,this.symbol=Ft.symbol,this.name=Ft.name,this.mint=new ir.PublicKey(Ft.address),this.isToken2022=!1;return}this.decimals=t,this.symbol=n||e.toString().substring(0,6),this.name=o||e.toString().substring(0,6),this.mint=i?ir.PublicKey.default:ya({publicKey:e}),this.isToken2022=r}equals(e){return this===e?!0:this.mint.equals(e.mint)}},Ze=ga;Ze.WSOL=new ga(V(N({},Ft),{mint:Ft.address}));var Pa=class{constructor({decimals:e,symbol:t="UNKNOWN",name:n="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=n}equals(e){return this===e}},rr=Pa;rr.SOL=new Pa(Xn);var yu=te(require("bn.js"));var fu=new ve(new yu.default(100)),xt=class extends ve{toSignificant(e=5,t,n){return this.mul(fu).toSignificant(e,t,n)}toFixed(e=2,t,n){return this.mul(fu).toFixed(e,t,n)}};var Jl=Be("Raydium_price"),qt=class extends ve{constructor(t){let{baseToken:n,quoteToken:o,numerator:i,denominator:r}=t;super(i,r);this.baseToken=n,this.quoteToken=o,this.scalar=new ve(Aa(n.decimals),Aa(o.decimals))}get raw(){return new ve(this.numerator,this.denominator)}get adjusted(){return super.mul(this.scalar)}invert(){return new qt({baseToken:this.quoteToken,quoteToken:this.baseToken,denominator:this.numerator,numerator:this.denominator})}mul(t){this.quoteToken!==t.baseToken&&Jl.logWithError("mul token not equals");let n=super.mul(t);return new qt({baseToken:this.baseToken,quoteToken:t.quoteToken,denominator:n.denominator,numerator:n.numerator})}toSignificant(t=this.quoteToken.decimals,n,o){return this.adjusted.toSignificant(t,n,o)}toFixed(t=this.quoteToken.decimals,n,o){return this.adjusted.toFixed(t,n,o)}};var Au=require("@solana/web3.js"),Lo=te(require("bn.js"));var ue=require("@solana/buffer-layout"),ar=ue.Layout,bu=ue.Structure;var wa=ue.UInt;var gu=ue.u8,at=ue.u16;var ui=ue.u32;var yt=ue.s32;var Pu=ue.seq;var Ie=ue.blob;var ka=ue.bits,Ta=ue.offset;var uo=class extends ar{constructor(t,n,o){super(t,o);this.blob=Ie(t),this.signed=n}decode(t,n=0){let o=new Lo.default(this.blob.decode(t,n),10,"le");return this.signed?o.fromTwos(this.span*8).clone():o}encode(t,n,o=0){return typeof t=="number"&&(t=new Lo.default(t)),this.signed&&(t=t.toTwos(this.span*8)),this.blob.encode(t.toArrayLike(Buffer,"le",this.span),n,o)}},sr=class extends ar{constructor(t){super(8,t);this._lower=ka(ui(),!1),this._upper=ka(ui(),!1)}addBoolean(t){this._lower.fields.length<32?this._lower.addBoolean(t):this._upper.addBoolean(t)}decode(t,n=0){let o=this._lower.decode(t,n),i=this._upper.decode(t,n+this._lower.span);return N(N({},o),i)}encode(t,n,o=0){return this._lower.encode(t,n,o)+this._upper.encode(t,n,o+this._lower.span)}};function W(d){return new wa(1,d)}function je(d){return new wa(4,d)}function w(d){return new uo(8,!1,d)}function ye(d){return new uo(16,!1,d)}function wu(d){return new uo(1,!0,d)}function Oo(d){return new uo(8,!0,d)}function ku(d){return new uo(16,!0,d)}var co=class extends ar{constructor(t,n,o,i){super(t.span,i);this.layout=t,this.decoder=n,this.encoder=o}decode(t,n){return this.decoder(this.layout.decode(t,n))}encode(t,n,o){return this.layout.encode(this.encoder(t),n,o)}getSpan(t,n){return this.layout.getSpan(t,n)}};function M(d){return new co(Ie(32),e=>new Au.PublicKey(e),e=>e.toBuffer(),d)}function nt(d){return new co(gu(),em,tm,d)}function em(d){if(d===0)return!1;if(d===1)return!0;throw new Error("Invalid bool: "+d)}function tm(d){return d?1:0}function Tu(d,e){let t=ui("length"),n=v([t,j(d,Ta(t,-t.span),"values")]);return new co(n,({values:o})=>o,o=>({values:o}),e)}function nm(d){let e=ui("length"),t=v([e,Ie(Ta(e,-e.span),"data")]);return new co(t,({data:n})=>n,n=>({data:n}),d)}function Ht(d){return new co(nm(),e=>e.toString("utf-8"),e=>Buffer.from(e,"utf-8"),d)}var ha=class extends bu{decode(e,t){return super.decode(e,t)}};function v(d,e,t){return new ha(d,e,t)}function j(d,e,t){let n,o=typeof e=="number"?e:(0,Lo.isBN)(e)?e.toNumber():new Proxy(e,{get(i,r){if(!n){let a=Reflect.get(i,"count");n=(0,Lo.isBN)(a)?a.toNumber():a,Reflect.set(i,"count",n)}return Reflect.get(i,r)},set(i,r,a){return r==="count"&&(n=a),Reflect.set(i,r,a)}});return Pu(d,o,t)}var Nn=v([M("mint"),M("owner"),w("amount"),je("delegateOption"),M("delegate"),W("state"),je("isNativeOption"),w("isNative"),w("delegatedAmount"),je("closeAuthorityOption"),M("closeAuthority")]);var ci=require("@solana/web3.js"),Ku=te(require("bn.js"));var Cu=require("@solana/spl-token");function om(d){return d instanceof Uint8Array||d!=null&&typeof d=="object"&&d.constructor.name==="Uint8Array"}function Ia(d,...e){if(!om(d))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(d.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${d.length}`)}function Ba(d,e=!0){if(d.destroyed)throw new Error("Hash instance has been destroyed");if(e&&d.finished)throw new Error("Hash#digest() has already been called")}function hu(d,e){Ia(d);let t=e.outputLen;if(d.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var cr=d=>new DataView(d.buffer,d.byteOffset,d.byteLength),fn=(d,e)=>d<<32-e|d>>>e;var Qp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function im(d){if(typeof d!="string")throw new Error(`utf8ToBytes expected string, got ${typeof d}`);return new Uint8Array(new TextEncoder().encode(d))}function xa(d){return typeof d=="string"&&(d=im(d)),Ia(d),d}var ur=class{clone(){return this._cloneInto()}},Zp={}.toString;function Iu(d){let e=n=>d().update(xa(n)).digest(),t=d();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>d(),e}function rm(d,e,t,n){if(typeof d.setBigUint64=="function")return d.setBigUint64(e,t,n);let o=BigInt(32),i=BigInt(4294967295),r=Number(t>>o&i),a=Number(t&i),u=n?4:0,s=n?0:4;d.setUint32(e+u,r,n),d.setUint32(e+s,a,n)}var Bu=(d,e,t)=>d&e^~d&t,xu=(d,e,t)=>d&e^d&t^e&t,lr=class extends ur{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=cr(this.buffer)}update(e){Ba(this);let{view:t,buffer:n,blockLen:o}=this;e=xa(e);let i=e.length;for(let r=0;r<i;){let a=Math.min(o-this.pos,i-r);if(a===o){let u=cr(e);for(;o<=i-r;r+=o)this.process(u,r);continue}n.set(e.subarray(r,r+a),this.pos),this.pos+=a,r+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ba(this),hu(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:i}=this,{pos:r}=this;t[r++]=128,this.buffer.subarray(r).fill(0),this.padOffset>o-r&&(this.process(n,0),r=0);for(let l=r;l<o;l++)t[l]=0;rm(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=cr(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let s=u/4,c=this.get();if(s>c.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<s;l++)a.setUint32(4*l,c[l],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:i,destroyed:r,pos:a}=this;return e.length=o,e.pos=a,e.finished=i,e.destroyed=r,o%t&&e.buffer.set(n),e}};var am=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]),Yn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Hn=new Uint32Array(64),Sa=class extends lr{constructor(){super(64,32,8,!1),this.A=Yn[0]|0,this.B=Yn[1]|0,this.C=Yn[2]|0,this.D=Yn[3]|0,this.E=Yn[4]|0,this.F=Yn[5]|0,this.G=Yn[6]|0,this.H=Yn[7]|0}get(){let{A:e,B:t,C:n,D:o,E:i,F:r,G:a,H:u}=this;return[e,t,n,o,i,r,a,u]}set(e,t,n,o,i,r,a,u){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=r|0,this.G=a|0,this.H=u|0}process(e,t){for(let l=0;l<16;l++,t+=4)Hn[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let m=Hn[l-15],p=Hn[l-2],f=fn(m,7)^fn(m,18)^m>>>3,y=fn(p,17)^fn(p,19)^p>>>10;Hn[l]=y+Hn[l-7]+f+Hn[l-16]|0}let{A:n,B:o,C:i,D:r,E:a,F:u,G:s,H:c}=this;for(let l=0;l<64;l++){let m=fn(a,6)^fn(a,11)^fn(a,25),p=c+m+Bu(a,u,s)+am[l]+Hn[l]|0,y=(fn(n,2)^fn(n,13)^fn(n,22))+xu(n,o,i)|0;c=s,s=u,u=a,a=r+p|0,r=i,i=o,o=n,n=p+y|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,r=r+this.D|0,a=a+this.E|0,u=u+this.F|0,s=s+this.G|0,c=c+this.H|0,this.set(n,o,i,r,a,u,s,c)}roundClean(){Hn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Su=Iu(()=>new Sa);function Ru({owner:d,solAccountResp:e,tokenAccountResp:t}){let n=[],o=[];for(let{pubkey:i,account:r}of t.value){let a=Nn.decode(r.data),{mint:u,amount:s}=a;n.push({publicKey:i,mint:u,amount:s,isAssociated:ne(d,u,r.owner).publicKey.equals(i),isNative:!1,programId:r.owner}),o.push({pubkey:i,accountInfo:a,programId:r.owner})}return e&&n.push({mint:ci.PublicKey.default,amount:new Ku.default(String(e.lamports)),isNative:!0,programId:e.owner}),{tokenAccounts:n,tokenAccountRawInfos:o}}function st({fromPublicKey:d,programId:e=Cu.TOKEN_PROGRAM_ID,assignSeed:t}){let n=t?btoa(t).slice(0,32):ci.Keypair.generate().publicKey.toBase58().slice(0,32);return{publicKey:sm(d,n,e),seed:n}}function sm(d,e,t){let n=Buffer.concat([d.toBuffer(),Buffer.from(e),t.toBuffer()]),o=Su(n);return new ci.PublicKey(o)}var mr=require("@solana/web3.js"),Lu=te(require("bn.js"));var en=require("@solana/spl-token");var X={CreateAccount:"CreateAccount",InitAccount:"InitAccount",CreateATA:"CreateATA",CloseAccount:"CloseAccount",TransferAmount:"TransferAmount",InitMint:"InitMint",MintTo:"MintTo",InitMarket:"InitMarket",Util1216OwnerClaim:"Util1216OwnerClaim",SetComputeUnitPrice:"SetComputeUnitPrice",SetComputeUnitLimit:"SetComputeUnitLimit",ClmmCreatePool:"ClmmCreatePool",ClmmOpenPosition:"ClmmOpenPosition",ClmmIncreasePosition:"ClmmIncreasePosition",ClmmDecreasePosition:"ClmmDecreasePosition",ClmmClosePosition:"ClmmClosePosition",ClmmSwapBaseIn:"ClmmSwapBaseIn",ClmmSwapBaseOut:"ClmmSwapBaseOut",ClmmInitReward:"ClmmInitReward",ClmmSetReward:"ClmmSetReward",ClmmCollectReward:"ClmmCollectReward",ClmmLockPosition:"ClmmLockPosition",ClmmHarvestLockPosition:"ClmmHarvestLockPosition",AmmV4Swap:"AmmV4Swap",AmmV4AddLiquidity:"AmmV4AddLiquidity",AmmV4RemoveLiquidity:"AmmV4RemoveLiquidity",AmmV4SimulatePoolInfo:"AmmV4SimulatePoolInfo",AmmV4SwapBaseIn:"AmmV4SwapBaseIn",AmmV4SwapBaseOut:"AmmV4SwapBaseOut",AmmV4CreatePool:"AmmV4CreatePool",AmmV4InitPool:"AmmV4InitPool",AmmV5AddLiquidity:"AmmV5AddLiquidity",AmmV5RemoveLiquidity:"AmmV5RemoveLiquidity",AmmV5SimulatePoolInfo:"AmmV5SimulatePoolInfo",AmmV5SwapBaseIn:"AmmV5SwapBaseIn",AmmV5SwapBaseOut:"AmmV5SwapBaseOut",RouteSwap:"RouteSwap",RouteSwap1:"RouteSwap1",RouteSwap2:"RouteSwap2",FarmV3Deposit:"FarmV3Deposit",FarmV3Withdraw:"FarmV3Withdraw",FarmV3CreateLedger:"FarmV3CreateLedger",FarmV4Withdraw:"FarmV4Withdraw",FarmV5Deposit:"FarmV5Deposit",FarmV5Withdraw:"FarmV5Withdraw",FarmV5CreateLedger:"FarmV5CreateLedger",FarmV6Deposit:"FarmV6Deposit",FarmV6Withdraw:"FarmV6Withdraw",FarmV6Create:"FarmV6Create",FarmV6Restart:"FarmV6Restart",FarmV6CreatorAddReward:"FarmV6CreatorAddReward",FarmV6CreatorWithdraw:"FarmV6CreatorWithdraw",CpmmCreatePool:"CpmmCreatePool",CpmmAddLiquidity:"CpmmAddLiquidity",CpmmWithdrawLiquidity:"CpmmWithdrawLiquidity",CpmmSwapBaseIn:"CpmmSwapBaseIn",CpmmSwapBaseOut:"CpmmSwapBaseOut",CpmmLockLp:"CpmmLockLp",CpmmCollectLockFee:"CpmmCollectLockFee",TransferTip:"TransferTip"};function Ka(d){let{mint:e,tokenAccount:t,owner:n,programId:o=en.TOKEN_PROGRAM_ID}=d;return(0,en.createInitializeAccountInstruction)(t,e,n,o)}function Mn(d){let{tokenAccount:e,payer:t,multiSigners:n=[],owner:o,programId:i=en.TOKEN_PROGRAM_ID}=d;return(0,en.createCloseAccountInstruction)(e,t,o,n,i)}async function Qn(d){let{connection:e,amount:t,commitment:n,payer:o,owner:i,skipCloseAccount:r}=d,a=await e.getMinimumBalanceForRentExemption(Nn.span,n),u=fe(t).add(new Lu.default(a)),s=st({fromPublicKey:o,programId:en.TOKEN_PROGRAM_ID});return{addresses:{newAccount:s.publicKey},signers:[],instructions:[mr.SystemProgram.createAccountWithSeed({fromPubkey:o,basePubkey:o,seed:s.seed,newAccountPubkey:s.publicKey,lamports:u.toNumber(),space:Nn.span,programId:en.TOKEN_PROGRAM_ID}),Ka({mint:new mr.PublicKey(Ft.address),tokenAccount:s.publicKey,owner:i,programId:en.TOKEN_PROGRAM_ID})],instructionTypes:[X.CreateAccount,X.InitAccount],endInstructionTypes:r?[]:[X.CloseAccount],endInstructions:r?[]:[Mn({tokenAccount:s.publicKey,payer:o,owner:i})]}}function Ou({source:d,destination:e,owner:t,amount:n,multiSigners:o=[],tokenProgram:i=en.TOKEN_PROGRAM_ID}){return(0,en.createTransferInstruction)(d,e,t,BigInt(String(n)),o,i)}var yr=require("@solana/web3.js");var be=require("@solana/web3.js"),Nu=new be.PublicKey("EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"),Mu=new be.PublicKey("CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T"),Fu=new be.PublicKey("9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z"),li=new be.PublicKey("FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG"),Cf=new be.PublicKey("CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS"),vu=new be.PublicKey("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"),Ca=new be.PublicKey("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),dr=new be.PublicKey("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"),Rf=new be.PublicKey("5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h"),_u=new be.PublicKey("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),Fn=new be.PublicKey("CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"),mi=new be.PublicKey("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),pr=new be.PublicKey("kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy"),lo=new be.PublicKey("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),Lf=new be.PublicKey("routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS"),Vu=new be.PublicKey("7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"),Zn=new be.PublicKey("CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"),Eu=new be.PublicKey("GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"),Of=new be.PublicKey("DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8"),di=new be.PublicKey("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),fr=new be.PublicKey("3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH"),mt=new be.PublicKey("LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"),Nf=new be.PublicKey("WLHv2UAZm6z4KyaaELi5pjdbJh6RESMva1Rnn8pJVVh"),Mf=new be.PublicKey("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),Ff=new be.PublicKey("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),vf=new be.PublicKey("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),_f=new be.PublicKey("6s1xP3hpbAfFoNtUNF8mfHsjr2Bd97JxFJRWLbL6aHuX");var yn={OPEN_BOOK_PROGRAM:new be.PublicKey("EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj"),SERUM_PROGRAM_ID_V3:new be.PublicKey("Ray1111111111111111111111111111111111111111"),AMM_V4:new be.PublicKey("DRaya7Kj3aMWQSy19kSjvmuwq9docCHofyP9kanQGaav"),AMM_STABLE:new be.PublicKey("DRayDdXc1NZQ9C3hRWmoSf8zK4iapgMnjdNZWrfwsP8m"),CLMM_PROGRAM_ID:new be.PublicKey("DRayAUgENGQBKVaX8owNhgzkEDyoHTGVEGHVJT1E9pfH"),CLMM_LOCK_PROGRAM_ID:new be.PublicKey("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),CLMM_LOCK_AUTH_ID:new be.PublicKey("6Aoh8h2Lw2m5UGxYR8AdAL87jTWYeKoxM52mJRzfYwN"),CREATE_CPMM_POOL_PROGRAM:new be.PublicKey("DRaycpLY18LhpbydsBWbVJtxpNv9oXPgjRSfpF2bWpYb"),CREATE_CPMM_POOL_AUTH:new be.PublicKey("CXniRufdq5xL8t8jZAPxsPZDpuudwuJSPWnbcD5Y5Nxq"),CREATE_CPMM_POOL_FEE_ACC:new be.PublicKey("3oE58BKVt8KuYkGxx8zBojugnymWmBiyafWgMrnb6eYy"),LOCK_CPMM_PROGRAM:new be.PublicKey("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),LOCK_CPMM_AUTH:new be.PublicKey("7qWVV8UY2bRJfDLP4s37YzBPKUkVB46DStYJBpYbQzu3"),UTIL1216:be.PublicKey.default,Router:new be.PublicKey("DRaybByLpbUL57LJARs3j8BitTxVfzBg351EaMr5UTCd"),FARM_PROGRAM_ID_V3:new be.PublicKey("DRayWyrLmEW5KEeqs8kdTMMaBabapqagaBC7KWpGtJeZ"),FARM_PROGRAM_ID_V4:new be.PublicKey("Ray1111111111111111111111111111111111111111"),FARM_PROGRAM_ID_V5:new be.PublicKey("DRayiCGSZgku1GTK6rXD6mVDdingXy6APAH1R6R5L2LC"),FARM_PROGRAM_ID_V6:new be.PublicKey("DRayzbYakXs45ELHkzH6vC3fuhQqTAnv5A68gdFuvZyZ"),LAUNCHPAD_PROGRAM:new be.PublicKey("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),LAUNCHPAD_AUTH:new be.PublicKey("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),LAUNCHPAD_PLATFORM:new be.PublicKey("2Jx4KTDrVSdWNazuGpcA8n3ZLTRGGBDxAWhuKe2Xcj2a"),LAUNCHPAD_CONFIG:new be.PublicKey("7ZR4zD7PYfY2XxoG1Gxcy2EgEeGYrpxrwzPuwdUBssEt"),FEE_DESTINATION_ID:new be.PublicKey("9y8ENuuZ3b19quffx9hQvRVygG5ky6snHfRvGpuSfeJy"),MODEL_DATA_PUBKEY:new be.PublicKey("Ray1111111111111111111111111111111111111111")};var um=require("@solana/spl-token"),Gf=Be("Raydium_farm_config"),Du=new yr.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Wu=new yr.PublicKey("FrspKwj8i3pNmKwXreTveC4fu7KL5ZbGeXdZBe2XViu1");var zf=new yr.PublicKey("3TRTX4dXUpp2eqxi3tvQDFYUV7SdDJjcPE3Y4mbtftaX"),br={3:qu,5:Uu,6:fi},pi={3:Oa,5:Gu,6:zu},Ra=d=>[3,4,5,6].indexOf(d)!==-1,La=d=>{var r;let{version:e,rewardInfos:t,rewardTokenAccountsPublicKeys:n}=d,o=`rewardInfo:${JSON.stringify(t)}, rewardAccount:${JSON.stringify(n)}`,i={3:()=>{if(t.length!==1||n.length!==1)return`rewardInfos or rewardTokenAccounts lengths not equal 1: ${o}`},5:()=>{if(t.length!==n.length)return`rewardInfos and rewardTokenAccounts lengths not equal: ${o}`},6:()=>{if(!n.length||t.length!==n.length)return`no rewardTokenAccounts or rewardInfos and rewardTokenAccounts lengths not equal: ${o}`}};return(r=i[e])==null?void 0:r.call(i)},jn={"Standard SPL":0,"Option tokens":1},tn={[Nu.toString()]:3,[Mu.toString()]:4,[Fu.toString()]:5,[li.toString()]:6,[yn.FARM_PROGRAM_ID_V3.toString()]:3,[yn.FARM_PROGRAM_ID_V4.toString()]:4,[yn.FARM_PROGRAM_ID_V5.toString()]:5,[yn.FARM_PROGRAM_ID_V6.toString()]:6};var Na=v([W("instruction")]),Ma=v([W("instruction")]),cm=v([w("rewardState"),w("rewardOpenTime"),w("rewardEndTime"),w("rewardLastUpdateTime"),w("totalReward"),w("totalRewardEmissioned"),w("rewardClaimed"),w("rewardPerSecond"),ye("accRewardPerShare"),M("rewardVault"),M("rewardMint"),M("rewardSender"),w("rewardType"),j(w(),15,"padding")]),lm=v([w("state"),w("nonce"),M("lpVault"),M("rewardVault"),M(),M(),w(),w(),w("totalReward"),ye("perShareReward"),w("lastSlot"),w("perSlotReward")]),mm=v([w("state"),w("nonce"),M("lpVault"),M("rewardVaultA"),w("totalRewardA"),ye("perShareRewardA"),w("perSlotRewardA"),W("option"),M("rewardVaultB"),Ie(7),w("totalRewardB"),ye("perShareRewardB"),w("perSlotRewardB"),w("lastSlot"),M()]),dm=v([w(),w("state"),w("nonce"),w("validRewardTokenNum"),ye("rewardMultiplier"),w("rewardPeriodMax"),w("rewardPeriodMin"),w("rewardPeriodExtend"),M("lpMint"),M("lpVault"),j(cm,5,"rewardInfos"),M("creator"),M(),j(w(),32,"padding")]),qu=new Proxy(lm,{get(d,e,t){return e==="decode"?(...n)=>{let o=d.decode(...n);return V(N({},o),{version:3,rewardInfos:[{rewardVault:o.rewardVault,totalReward:o.totalReward,perSlotReward:o.perSlotReward,perShareReward:o.perShareReward}]})}:Reflect.get(d,e,t)}}),Uu=new Proxy(mm,{get(d,e,t){return e==="decode"?(...n)=>{let o=d.decode(...n);return V(N({},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(d,e,t)}}),fi=new Proxy(dm,{get(d,e,t){return e==="decode"?(...n)=>{let o=d.decode(...n);return V(N({},o),{version:6,rewardInfos:o.rewardInfos.map(i=>{var r;return V(N({},i),{rewardType:((r=Object.entries(jn).find(a=>String(a[1])===i.rewardType.toString()))!=null?r:["Standard SPL"])[0]})})})}:Reflect.get(d,e,t)}}),pm=v([w("isSet"),w("rewardPerSecond"),w("rewardOpenTime"),w("rewardEndTime"),w("rewardType")]),Fa=v([W("instruction"),w("nonce"),j(pm,5,"rewardTimeInfo")]),va=v([W("instruction"),w("rewardReopenTime"),w("rewardEndTime"),w("rewardPerSecond")]),_a=v([W("instruction"),w("isSet"),w("rewardPerSecond"),w("rewardOpenTime"),w("rewardEndTime"),w("rewardType")]),$f=v([w("state"),M("id"),M("owner"),w("deposited"),j(w(),1,"rewardDebts")]),Oa=v([w("state"),M("id"),M("owner"),w("deposited"),j(ye(),1,"rewardDebts"),w(""),w("voteLockedBalance"),j(w(),15)]),Jf=v([w("state"),M("id"),M("owner"),w("deposited"),j(w(),2,"rewardDebts")]),Gu=v([w("state"),M("id"),M("owner"),w("deposited"),j(ye(),2,"rewardDebts"),j(w(),17)]),zu=v([w(),w("state"),M("id"),M("owner"),w("deposited"),j(ye(),5,"rewardDebts"),j(w(),16)]),nn=v([W("instruction"),w("amount")]),fm=v([M("mint"),M("grantAuthority"),w("baselineVoteWeightScaledFactor"),w("maxExtraLockupVoteWeightScaledFactor"),w("lockupSaturationSecs"),wu("digitShift"),j(W(),7,"reserved1"),j(w(),7,"reserved2")]),ym=v([Ie(8),M("governanceProgramId"),M("realm"),M("realmGoverningTokenMint"),M("realmAuthority"),j(W(),32,"reserved1"),j(fm,4,"votingMints"),Oo("timeOffset"),W("bump"),j(W(),7,"reserved2"),j(w(),11,"reserved3")]),bm=v([Oo("startTime"),Oo("endTime"),W("kind"),j(W(),15,"reserved")]),gm=v([j(bm,1,"lockup"),w("amountDeposited_native"),w("amountInitiallyLockedNative"),nt("isUsed"),nt("allowClawback"),W("votingMintConfigIdx"),j(W(),29,"reserved")]),Pm=v([Ie(8),M("voterAuthority"),M("registrar"),j(gm,32,"deposits"),W("voterBump"),W("voterWweightRecordBump"),j(W(),94,"reserved")]);var ju=te(require("bn.js"));var _t=require("@solana/web3.js");var Yu=require("@solana/spl-token"),Xu=Be("Raydium_txUtil"),Hu=1644;function gr(d){let e=[],t=[];return d.microLamports&&(e.push(_t.ComputeBudgetProgram.setComputeUnitPrice({microLamports:d.microLamports})),t.push(X.SetComputeUnitPrice)),d.units&&(e.push(_t.ComputeBudgetProgram.setComputeUnitLimit({units:d.units})),t.push(X.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}async function No(d,e){var n,o;let t=e!=null?e:"confirmed";return(o=await((n=d.getLatestBlockhash)==null?void 0:n.call(d,{commitment:t})))==null?void 0:o.blockhash}async function Pr(d,e){return d.getSignatureStatuses([e]),new Promise((t,n)=>{let o=setTimeout(n,6e4);d.onSignature(e,i=>{if(clearTimeout(o),!i.err){t("");return}n(Object.assign(i.err,{txId:e}))},"confirmed")})}function Va(d,e){d.length<1&&Xu.logWithError(`no instructions provided: ${d.toString()}`),e.length<1&&Xu.logWithError(`no signers provided:, ${e.toString()}`);let t=new _t.Transaction;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...d);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<Hu}catch{return!1}}function de(d,e){let[t,n]=_t.PublicKey.findProgramAddressSync(d,e);return{publicKey:t,nonce:n}}function yi({instructions:d,payer:e,signers:t}){return Va(d,[e,...t])}function bi({instructions:d,payer:e,lookupTableAddressAccount:t,recentBlockhash:n=_t.Keypair.generate().publicKey.toString()}){let i=new _t.TransactionMessage({payerKey:e,recentBlockhash:n,instructions:d}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new _t.VersionedTransaction(i).serialize()).toString("base64").length<Hu}catch{return!1}}var Am=d=>Buffer.isBuffer(d)?d:d instanceof Uint8Array?Buffer.from(d.buffer,d.byteOffset,d.byteLength):Buffer.from(d),wm=d=>{let e=d.serialize({requireAllSignatures:!1,verifySignatures:!1});d instanceof _t.VersionedTransaction&&(e=Am(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch{return e.toString("base64")}};function mo(d){let e=[];return d.forEach(t=>{t instanceof _t.Transaction&&(t.recentBlockhash||(t.recentBlockhash=Yu.TOKEN_PROGRAM_ID.toBase58()),t.feePayer||(t.feePayer=_t.Keypair.generate().publicKey)),e.push(wm(t))}),console.log("simulate tx string:",e),e}var Qu=require("@solana/web3.js"),Zu=te(require("bn.js"));function km(d){return typeof d=="object"&&d!==null&&![Ze,_e,Qu.PublicKey,ve,Zu.default,qt,xt].some(e=>typeof e=="object"&&d instanceof e)}function Ut(d){return typeof d=="string"?ba(d):Array.isArray(d)?d.map(e=>Ut(e)):km(d)?Object.fromEntries(Object.entries(d).map(([e,t])=>[e,Ut(t)])):d}var Tm=Be("Raydium.farm.util");function gi({programId:d,poolId:e,mint:t,type:n}){let{publicKey:o}=de([e.toBuffer(),t.toBuffer(),Buffer.from(n==="lpVault"?"lp_vault_associated_seed":n==="rewardVault"?"reward_vault_associated_seed":"","utf-8")],d);return o}function sn({programId:d,poolId:e,owner:t,version:n}){let{publicKey:o}=de([e.toBuffer(),t.toBuffer(),Buffer.from(n===6?"farmer_info_associated_seed":"staker_info_v2_associated_seed","utf-8")],d);return o}var $u=({programId:d,poolId:e})=>de([e.toBuffer()],d);function Ju(d){return{isSet:new ju.default(1),rewardPerSecond:fe(d.perSecond),rewardOpenTime:fe(d.openTime),rewardEndTime:fe(d.endTime),rewardType:fe(jn[d.rewardType])}}function Ea(d){return fe(d.endTime).sub(fe(d.openTime)).mul(fe(d.perSecond))}function Pi(d){let e=pi[d];return e||Tm.logWithError("invalid version",d),e}var oe=require("@solana/web3.js"),Da=te(require("bn.js")),un=require("@solana/spl-token");var ec=require("@solana/web3.js"),tc=require("@solana/spl-token");function ne(d,e,t){return de([d.toBuffer(),(t!=null?t:tc.TOKEN_PROGRAM_ID).toBuffer(),e.toBuffer()],new ec.PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}var hm=Be("Raydium_farm_instruction"),ib={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 Ai(d){let{version:e,id:t,ledger:n,programId:o,owner:i}=d,r={3:9,5:10}[e];r||hm.logWithError(`invalid farm pool version: ${e}`);let a=Buffer.alloc(Na.span);Na.encode({instruction:r},a);let u=[K({pubkey:t}),K({pubkey:n}),K({pubkey:i,isWritable:!1}),K({pubkey:oe.SystemProgram.programId,isWritable:!1}),K({pubkey:oe.SYSVAR_RENT_PUBKEY,isWritable:!1})];return{instruction:new oe.TransactionInstruction({programId:o,keys:u,data:a}),instructionType:X.FarmV3CreateLedger}}function nc(d){var n;let e=Buffer.alloc(Fa.span);Fa.encode({instruction:0,nonce:new Da.default(d.nonce),rewardTimeInfo:d.rewardInfoConfig},e);let t=[...fa,K({pubkey:d.farmId}),K({pubkey:d.farmAuthority,isWritable:!1}),K({pubkey:d.lpVault}),K({pubkey:d.lpMint,isWritable:!1}),K({pubkey:d.lockVault}),K({pubkey:d.lockMint,isWritable:!1}),K({pubkey:(n=d.lockUserAccount)!=null?n:Bt}),K({pubkey:d.owner,isWritable:!1,isSigner:!0})];for(let o of d.rewardInfo)t.push(K({pubkey:o.rewardMint,isWritable:!1}),K({pubkey:o.rewardVault}),K({pubkey:o.userRewardToken}));return{instruction:new oe.TransactionInstruction({programId:d.programId,keys:t,data:e}),instructionType:X.FarmV6Create}}function oc(d){let e=Buffer.alloc(Ma.span);Ma.encode({instruction:5},e);let t=[K({pubkey:un.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:d.id}),K({pubkey:d.authority,isWritable:!1}),K({pubkey:d.lpVault,isWritable:!1}),K({pubkey:d.rewardVault}),K({pubkey:d.userRewardToken}),K({pubkey:d.owner,isWritable:!1,isSigner:!0})];return{instruction:new oe.TransactionInstruction({programId:d.programId,keys:t,data:e}),instructionType:X.FarmV6CreatorWithdraw}}function Wa({payer:d,rewardVault:e,userRewardTokenPub:t,farmKeys:n,rewardInfo:o}){let i=Buffer.alloc(va.span);va.encode({instruction:3,rewardReopenTime:fe(o.openTime),rewardEndTime:fe(o.endTime),rewardPerSecond:fe(o.perSecond)},i);let r=[K({pubkey:un.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:n.id}),K({pubkey:n.lpVault,isWritable:!1}),K({pubkey:e}),K({pubkey:t}),K({pubkey:d,isWritable:!1,isSigner:!0})];return new oe.TransactionInstruction({programId:n.programId,keys:r,data:i})}function qa({payer:d,userRewardTokenPub:e,farmKeys:t,rewardVault:n,rewardInfo:o}){let i=Buffer.alloc(_a.span);_a.encode({instruction:4,isSet:new Da.default(1),rewardPerSecond:fe(o.perSecond),rewardOpenTime:fe(o.openTime),rewardEndTime:fe(o.endTime),rewardType:fe(jn[o.rewardType])},i);let r=[...fa,K({pubkey:t.id}),K({pubkey:t.authority,isWritable:!1}),K({pubkey:o.mint,isWritable:!1}),K({pubkey:n}),K({pubkey:e}),K({pubkey:d,isWritable:!1,isSigner:!0})];return new oe.TransactionInstruction({programId:t.programId,keys:r,data:i})}function wi(d){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r}=d,[a,u]=[new oe.PublicKey(e.programId),new oe.PublicKey(e.id)],s=sn({programId:a,poolId:u,owner:i,version:6}),c=Buffer.alloc(nn.span);nn.encode({instruction:2,amount:fe(r)},c);let l=[K({pubkey:un.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:u}),K({pubkey:new oe.PublicKey(t.authority),isWritable:!1}),K({pubkey:new oe.PublicKey(t.lpVault)}),K({pubkey:s}),K({pubkey:i,isWritable:!1,isSigner:!0}),K({pubkey:n})];for(let m=0;m<t.rewardInfos.length;m++)l.push(K({pubkey:new oe.PublicKey(t.rewardInfos[m].vault)})),l.push(K({pubkey:o[m]}));return new oe.TransactionInstruction({programId:a,keys:l,data:c})}function ki(d){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=d,[u,s]=[new oe.PublicKey(e.programId),new oe.PublicKey(e.id)],c=sn({programId:u,poolId:s,owner:i,version:5}),l=Buffer.alloc(nn.span);nn.encode({instruction:12,amount:fe(r)},l);let m=[K({pubkey:s}),K({pubkey:new oe.PublicKey(t.authority),isWritable:!1}),K({pubkey:c}),K({pubkey:i,isWritable:!1,isSigner:!0}),K({pubkey:n}),K({pubkey:new oe.PublicKey(t.lpVault)}),K({pubkey:o[0]}),K({pubkey:new oe.PublicKey(t.rewardInfos[0].vault)}),K({pubkey:oe.SYSVAR_CLOCK_PUBKEY,isWritable:!1}),K({pubkey:un.TOKEN_PROGRAM_ID,isWritable:!1})];for(let p=1;p<t.rewardInfos.length;p++)m.push(K({pubkey:o[p]})),m.push(K({pubkey:new oe.PublicKey(t.rewardInfos[p].vault)}));if(a)for(let p of a)m.push(K({pubkey:p}));return new oe.TransactionInstruction({programId:u,keys:m,data:l})}function ic(d){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=d,[u,s]=[new oe.PublicKey(e.programId),new oe.PublicKey(e.id)],c=v([W("instruction"),w("amount")]),l=[K({pubkey:s}),K({pubkey:new oe.PublicKey(t.authority),isWritable:!1}),K({pubkey:a[0]}),K({pubkey:i,isSigner:!0,isWritable:!1}),K({pubkey:n}),K({pubkey:new oe.PublicKey(t.lpVault)}),K({pubkey:o[0]}),K({pubkey:new oe.PublicKey(t.rewardInfos[0].vault)}),K({pubkey:oe.SYSVAR_CLOCK_PUBKEY,isWritable:!1}),K({pubkey:un.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:o[1]}),K({pubkey:new oe.PublicKey(t.rewardInfos[1].vault)})],m=Buffer.alloc(c.span);return c.encode({instruction:2,amount:r},m),new oe.TransactionInstruction({keys:l,programId:u,data:m})}function Ti(d){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=d,[u,s]=[new oe.PublicKey(e.programId),new oe.PublicKey(e.id)],c=sn({programId:u,poolId:s,owner:i,version:3}),l=Buffer.alloc(nn.span);nn.encode({instruction:11,amount:fe(r)},l);let m=[K({pubkey:s}),K({pubkey:new oe.PublicKey(t.authority),isWritable:!1}),K({pubkey:c}),K({pubkey:i,isWritable:!1,isSigner:!0}),K({pubkey:n}),K({pubkey:new oe.PublicKey(t.lpVault)}),K({pubkey:o[0]}),K({pubkey:new oe.PublicKey(t.rewardInfos[0].vault)}),K({pubkey:oe.SYSVAR_CLOCK_PUBKEY,isWritable:!1}),K({pubkey:un.TOKEN_PROGRAM_ID,isWritable:!1})];if(a)for(let p of a)m.push(K({pubkey:p}));return new oe.TransactionInstruction({programId:u,keys:m,data:l})}function rc(d){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=d,[u,s]=[new oe.PublicKey(e.programId),new oe.PublicKey(e.id)],c=sn({programId:u,poolId:s,owner:i,version:3}),l=Buffer.alloc(nn.span);nn.encode({instruction:10,amount:fe(r)},l);let m=[K({pubkey:s}),K({pubkey:new oe.PublicKey(t.authority),isWritable:!1}),K({pubkey:c}),K({pubkey:i,isWritable:!1,isSigner:!0}),K({pubkey:n}),K({pubkey:new oe.PublicKey(t.lpVault)}),K({pubkey:o[0]}),K({pubkey:new oe.PublicKey(t.rewardInfos[0].vault)}),K({pubkey:oe.SYSVAR_CLOCK_PUBKEY,isWritable:!1}),K({pubkey:un.TOKEN_PROGRAM_ID,isWritable:!1})];if(a)for(let p of a)m.push(K({pubkey:p}));return new oe.TransactionInstruction({programId:u,keys:m,data:l})}function ac(d){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=d,[u,s]=[new oe.PublicKey(e.programId),new oe.PublicKey(e.id)],c=sn({programId:u,poolId:s,owner:i,version:5}),l=Buffer.alloc(nn.span);nn.encode({instruction:11,amount:fe(r)},l);let m=[K({pubkey:s}),K({pubkey:new oe.PublicKey(t.authority),isWritable:!1}),K({pubkey:c}),K({pubkey:i,isWritable:!1,isSigner:!0}),K({pubkey:n}),K({pubkey:new oe.PublicKey(t.lpVault)}),K({pubkey:o[0]}),K({pubkey:new oe.PublicKey(t.rewardInfos[0].vault)}),K({pubkey:oe.SYSVAR_CLOCK_PUBKEY,isWritable:!1}),K({pubkey:un.TOKEN_PROGRAM_ID,isWritable:!1})];for(let p=1;p<t.rewardInfos.length;p++)m.push(K({pubkey:o[p]})),m.push(K({pubkey:new oe.PublicKey(t.rewardInfos[p].vault)}));if(a)for(let p of a)m.push(K({pubkey:p}));return new oe.TransactionInstruction({programId:u,keys:m,data:l})}function sc(d){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r}=d,[a,u]=[new oe.PublicKey(e.programId),new oe.PublicKey(e.id)],s=sn({programId:a,poolId:u,owner:i,version:6}),c=Buffer.alloc(nn.span);nn.encode({instruction:1,amount:fe(r)},c);let l=[K({pubkey:un.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:oe.SystemProgram.programId,isWritable:!1}),K({pubkey:u}),K({pubkey:new oe.PublicKey(t.authority),isWritable:!1}),K({pubkey:new oe.PublicKey(t.lpVault)}),K({pubkey:s}),K({pubkey:i,isWritable:!1,isSigner:!0}),K({pubkey:n})];for(let m=0;m<t.rewardInfos.length;m++)l.push(K({pubkey:new oe.PublicKey(t.rewardInfos[m].vault)})),l.push(K({pubkey:o[m]}));return new oe.TransactionInstruction({programId:a,keys:l,data:c})}var Im=v([je("mintAuthorityOption"),M("mintAuthority"),w("supply"),W("decimals"),W("isInitialized"),je("freezeAuthorityOption"),M("freezeAuthority")]);var Bm=require("@solana/spl-token"),xm=require("@solana/web3.js");var hi=d=>new Ze({mint:d.address,decimals:d.decimals,symbol:d.symbol,name:d.name}),bt=o=>{var i=o,{amount:d,isRaw:e,name:t}=i,n=Qe(i,["amount","isRaw","name"]);return new _e(new Ze({mint:Ot(n.address).toBase58(),decimals:n.decimals,symbol:n.symbol,name:t}),d,e,t)};var wt=o=>{var i=o,{address:d,programId:e,decimals:t}=i,n=Qe(i,["address","programId","decimals"]);return N({chainId:101,address:Ot(d).toBase58(),programId:e,logoURI:"",symbol:"",name:"",decimals:t,tags:[],extensions:n.extensions||{}},n)},xn=d=>d?V(N({},d),{transferFeeConfigAuthority:d.transferFeeConfigAuthority.toBase58(),withdrawWithheldAuthority:d.withdrawWithheldAuthority.toBase58(),withheldAmount:d.withheldAmount.toString(),olderTransferFee:V(N({},d.olderTransferFee),{epoch:d.olderTransferFee.epoch.toString(),maximumFee:d.olderTransferFee.maximumFee.toString()}),newerTransferFee:V(N({},d.newerTransferFee),{epoch:d.newerTransferFee.epoch.toString(),maximumFee:d.newerTransferFee.maximumFee.toString()})}):void 0;var pe=require("@solana/web3.js"),Pe=require("@solana/spl-token"),he=te(require("bn.js")),Ne=te(require("decimal.js"));var We=require("@solana/spl-token"),G=require("@solana/web3.js"),ct=te(require("bn.js")),Kn=te(require("decimal.js"));var Ve=require("@solana/web3.js"),uc=te(require("axios"));var bn=require("@solana/web3.js");async function Ua({connection:d,address:e,cluster:t="mainnet"}){let n=await It(d,[...new Set(e.map(i=>i.toString()))].map(i=>new bn.PublicKey(i))),o={};for(let i=0;i<e.length;i++){let r=n[i],a=e[i];if(!r)continue;let u=new bn.AddressLookupTableAccount({key:a,state:bn.AddressLookupTableAccount.deserialize(r.data)});o[a.toString()]=u,t==="devnet"?Fo[a.toString()]=u:Mo[a.toString()]=u}return o}var Mo={},Ga=async d=>{let e="AcL1Vo8oy1ULiavEcjSUcwfBSForXMudcZvDZy5nzJkU";if(Mo[e])return Mo;let t=new bn.PublicKey(e),n=await d.getAccountInfo(t);return n&&(Mo[e]=new bn.AddressLookupTableAccount({key:t,state:bn.AddressLookupTableAccount.deserialize(n.data)})),Mo},Fo={},za=async d=>{let e="EFhMuDw1PKEuckuFRW9PavNfTH4LKP5uKHgyXDmWpFCq";if(Fo[e])return Fo;let t=new bn.PublicKey(e),n=await d.getAccountInfo(t);return n&&(Fo[e]=new bn.AddressLookupTableAccount({key:t,state:bn.AddressLookupTableAccount.deserialize(n.data)})),Fo};var Ar=2e3,wr=class{constructor(e){this.instructions=[];this.endInstructions=[];this.lookupTableAddress=[];this.signers=[];this.instructionTypes=[];this.endInstructionTypes=[];this.connection=e.connection,this.feePayer=e.feePayer,this.signAllTransactions=e.signAllTransactions,this.owner=e.owner,this.cluster=e.cluster,this.blockhashCommitment=e.blockhashCommitment,this.loopMultiTxStatus=!!e.loopMultiTxStatus}get AllTxData(){return{instructions:this.instructions,endInstructions:this.endInstructions,signers:this.signers,instructionTypes:this.instructionTypes,endInstructionTypes:this.endInstructionTypes,lookupTableAddress:this.lookupTableAddress}}get allInstructions(){return[...this.instructions,...this.endInstructions]}async getComputeBudgetConfig(){var n;let e=(await uc.default.get(`https://solanacompass.com/api/fees?cacheFreshTime=${3e5}`)).data,{avg:t}=(n=e==null?void 0:e[15])!=null?n:{};if(!!t)return{units:6e5,microLamports:Math.min(Math.ceil(t*1e6/6e5),25e3)}}addCustomComputeBudget(e){if(e){let{instructions:t,instructionTypes:n}=gr(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...n),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(Ve.SystemProgram.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new Ve.PublicKey(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(X.TransferTip),!0):!1}async calComputeBudget({config:e,defaultIns:t}){try{let n=e||await this.getComputeBudgetConfig();if(this.addCustomComputeBudget(n))return;t&&this.instructions.unshift(...t)}catch{t&&this.instructions.unshift(...t)}}addInstruction({instructions:e=[],endInstructions:t=[],signers:n=[],instructionTypes:o=[],endInstructionTypes:i=[],lookupTableAddress:r=[]}){return this.instructions.push(...e),this.endInstructions.push(...t),this.signers.push(...n),this.instructionTypes.push(...o),this.endInstructionTypes.push(...i),this.lookupTableAddress.push(...r.filter(a=>a!==Ve.PublicKey.default.toString())),this}async versionBuild({txVersion:e,extInfo:t,lookupTableAddress:n}){return e===0?await this.buildV0(V(N({},t||{}),{lookupTableAddress:n})):this.build(t)}build(e){var n;let t=new Ve.Transaction;return this.allInstructions.length&&t.add(...this.allInstructions),t.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:t,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async o=>{var c;let{recentBlockHash:i,skipPreflight:r=!0,sendAndConfirm:a,notSendToRpc:u}=o||{},s=i!=null?i:await No(this.connection,this.blockhashCommitment);if(t.recentBlockhash=s,this.signers.length&&t.sign(...this.signers),mo([t]),(c=this.owner)!=null&&c.isKeyPair)return{txId:a?await(0,Ve.sendAndConfirmTransaction)(this.connection,t,this.signers.find(m=>m.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:r}):await this.connection.sendRawTransaction(t.serialize(),{skipPreflight:r}),signedTx:t};if(this.signAllTransactions){let l=await this.signAllTransactions([t]);if(this.signers.length)for(let m of l)try{m.sign(...this.signers)}catch{}return{txId:u?"":await this.connection.sendRawTransaction(l[0].serialize(),{skipPreflight:r}),signedTx:l[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:e||{}}}buildMultiTx(e){var s;let{extraPreBuildData:t=[],extInfo:n}=e,{transaction:o}=this.build(n),i=t.filter(c=>c.transaction.instructions.length>0),r=[o,...i.map(c=>c.transaction)],a=[this.signers,...i.map(c=>c.signers)],u=[...this.instructionTypes,...i.map(c=>c.instructionTypes).flat()];return(s=this.owner)!=null&&s.signer&&a.forEach(c=>{c.some(l=>l.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:r,signers:a,instructionTypes:u,execute:async c=>{var g;let{sequentially:l,onTxUpdate:m,skipTxCount:p=0,recentBlockHash:f,skipPreflight:y=!0}=c||{},b=f!=null?f:await No(this.connection,this.blockhashCommitment);if((g=this.owner)!=null&&g.isKeyPair){if(l){let A=[],k=0;for(let h of r){if(++k,k<=p)continue;let P=await(0,Ve.sendAndConfirmTransaction)(this.connection,h,this.signers.find(T=>T.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:y});A.push(P)}return{txIds:A,signedTxs:r}}return{txIds:await await Promise.all(r.map(async A=>(A.recentBlockhash=b,await this.connection.sendRawTransaction(A.serialize(),{skipPreflight:y})))),signedTxs:r}}if(this.signAllTransactions){let A=r.map((h,P)=>(h.recentBlockhash=b,a[P].length&&h.sign(...a[P]),h));mo(A);let k=await this.signAllTransactions(A);if(l){let h=0,P=[],T=async()=>{if(!k[h])return;let I=await this.connection.sendRawTransaction(k[h].serialize(),{skipPreflight:y});P.push({txId:I,status:"sent",signedTx:k[h]}),m==null||m([...P]),h++;let x=!1,S=null,B=null,R=L=>{S!==null&&clearInterval(S),B!==null&&this.connection.removeSignatureListener(B);let O=P.findIndex(C=>C.txId===I);if(O>-1){if(P[O].status==="error"||P[O].status==="success")return;P[O].status=L.err?"error":"success"}m==null||m([...P]),L.err||T()};this.loopMultiTxStatus&&(S=setInterval(async()=>{var L;if(x){clearInterval(S);return}try{let O=await this.connection.getTransaction(I,{commitment:"confirmed",maxSupportedTransactionVersion:0});O&&(x=!0,clearInterval(S),R({err:((L=O.meta)==null?void 0:L.err)||null}),console.log("tx status from getTransaction:",I))}catch(O){x=!0,clearInterval(S),console.error("getTransaction timeout:",O,I)}},Ar)),B=this.connection.onSignature(I,L=>{if(x){this.connection.removeSignatureListener(B);return}x=!0,R(L)},"confirmed"),this.connection.getSignatureStatus(I)};return await T(),{txIds:P.map(I=>I.txId),signedTxs:k}}else{let h=[];for(let P=0;P<k.length;P+=1){let T=await this.connection.sendRawTransaction(k[P].serialize(),{skipPreflight:y});h.push(T)}return{txIds:h,signedTxs:k}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:n||{}}}async versionMultiBuild({extraPreBuildData:e,txVersion:t,extInfo:n}){return t===0?await this.buildV0MultiTx({extraPreBuildData:e,buildProps:n||{}}):this.buildMultiTx({extraPreBuildData:e,extInfo:n})}async buildV0(e){var y;let f=e||{},{lookupTableCache:t={},lookupTableAddress:n=[],forerunCreate:o,recentBlockhash:i}=f,r=Qe(f,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),a=N(N({},this.cluster==="devnet"?await za(this.connection):await Ga(this.connection)),t),u=Array.from(new Set([...n,...this.lookupTableAddress])),s=[];for(let b of u)a[b]===void 0&&s.push(new Ve.PublicKey(b));let c=await Ua({connection:this.connection,address:s});for(let[b,g]of Object.entries(c))a[b]=g;let l=o?Ve.PublicKey.default.toBase58():i!=null?i:await No(this.connection,this.blockhashCommitment),m=new Ve.TransactionMessage({payerKey:this.feePayer,recentBlockhash:l,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(a));((y=this.owner)==null?void 0:y.signer)&&!this.signers.some(b=>b.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let p=new Ve.VersionedTransaction(m);return p.sign(this.signers),{builder:this,transaction:p,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async b=>{var h;let{skipPreflight:g=!0,sendAndConfirm:A,notSendToRpc:k}=b||{};if(mo([p]),(h=this.owner)!=null&&h.isKeyPair){let P=await this.connection.sendTransaction(p,{skipPreflight:g});return A&&await Pr(this.connection,P),{txId:P,signedTx:p}}if(this.signAllTransactions){let P=await this.signAllTransactions([p]);if(this.signers.length)for(let T of P)try{T.sign(this.signers)}catch{}return{txId:k?"":await this.connection.sendTransaction(P[0],{skipPreflight:g}),signedTx:P[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:r||{}}}async buildV0MultiTx(e){var s;let{extraPreBuildData:t=[],buildProps:n}=e,{transaction:o}=await this.buildV0(n),i=t.filter(c=>c.builder.instructions.length>0),r=[o,...i.map(c=>c.transaction)],a=[this.signers,...i.map(c=>c.signers)],u=[...this.instructionTypes,...i.map(c=>c.instructionTypes).flat()];return(s=this.owner)!=null&&s.signer&&a.forEach(c=>{c.some(l=>l.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),r.forEach(async(c,l)=>{c.sign(a[l])}),{builder:this,transactions:r,signers:a,instructionTypes:u,buildProps:n,execute:async c=>{var y;let{sequentially:l,onTxUpdate:m,recentBlockHash:p,skipPreflight:f=!0}=c||{};if(p&&r.forEach(b=>b.message.recentBlockhash=p),mo(r),(y=this.owner)!=null&&y.isKeyPair){if(l){let b=[];for(let g of r){let A=await this.connection.sendTransaction(g,{skipPreflight:f});await Pr(this.connection,A),b.push(A)}return{txIds:b,signedTxs:r}}return{txIds:await Promise.all(r.map(async b=>await this.connection.sendTransaction(b,{skipPreflight:f}))),signedTxs:r}}if(this.signAllTransactions){let b=await this.signAllTransactions(r);if(l){let g=0,A=[],k=async()=>{if(!b[g])return;let h=await this.connection.sendTransaction(b[g],{skipPreflight:f});A.push({txId:h,status:"sent",signedTx:b[g]}),m==null||m([...A]),g++;let P=!1,T=null,I=null,x=S=>{T!==null&&clearInterval(T),I!==null&&this.connection.removeSignatureListener(I);let B=A.findIndex(R=>R.txId===h);if(B>-1){if(A[B].status==="error"||A[B].status==="success")return;A[B].status=S.err?"error":"success"}m==null||m([...A]),S.err||k()};this.loopMultiTxStatus&&(T=setInterval(async()=>{var S;if(P){clearInterval(T);return}try{let B=await this.connection.getTransaction(h,{commitment:"confirmed",maxSupportedTransactionVersion:0});B&&(P=!0,clearInterval(T),x({err:((S=B.meta)==null?void 0:S.err)||null}),console.log("tx status from getTransaction:",h))}catch(B){P=!0,clearInterval(T),console.error("getTransaction timeout:",B,h)}},Ar)),I=this.connection.onSignature(h,S=>{if(P){this.connection.removeSignatureListener(I);return}P=!0,x(S)},"confirmed"),this.connection.getSignatureStatus(h)};return k(),{txIds:[],signedTxs:b}}else{let g=[];for(let A=0;A<b.length;A+=1){let k=await this.connection.sendTransaction(b[A],{skipPreflight:f});g.push(k)}return{txIds:g,signedTxs:b}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:n||{}}}async sizeCheckBuild(e){var m;let l=e||{},{splitIns:t=[],computeBudgetConfig:n}=l,o=Qe(l,["splitIns","computeBudgetConfig"]),i=n?gr(n):{instructions:[],instructionTypes:[]},r=this.signers.reduce((p,f)=>V(N({},p),{[f.publicKey.toBase58()]:f}),{}),a=[],u=[],s=[],c=0;if(this.allInstructions.forEach(p=>{let f=[...s,p],y=n?[...i.instructions,...f]:f,g=[...new Set(f.map(A=>A.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat()).values()].map(A=>new Ve.PublicKey(A));if(p!==t[c]&&s.length<12&&(yi({instructions:y,payer:this.feePayer,signers:g})||yi({instructions:f,payer:this.feePayer,signers:g})))s.push(p);else{if(s.length===0)throw Error("item ins too big");c+=p===t[c]?1:0,yi({instructions:n?[...i.instructions,...s]:[...s],payer:this.feePayer,signers:g})?a.push(new Ve.Transaction().add(...i.instructions,...s)):a.push(new Ve.Transaction().add(...s)),u.push(Array.from(new Set(s.map(A=>A.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat())).map(A=>r[A]).filter(A=>A!==void 0)),s=[p]}}),s.length>0){let f=[...new Set(s.map(y=>y.keys.filter(b=>b.isSigner).map(b=>b.pubkey.toString())).flat()).values()].map(y=>r[y]).filter(y=>y!==void 0);yi({instructions:n?[...i.instructions,...s]:[...s],payer:this.feePayer,signers:f.map(y=>y.publicKey)})?a.push(new Ve.Transaction().add(...i.instructions,...s)):a.push(new Ve.Transaction().add(...s)),u.push(f)}return a.forEach(p=>p.feePayer=this.feePayer),(m=this.owner)!=null&&m.signer&&u.forEach(p=>{p.some(f=>f.publicKey.equals(this.owner.publicKey))||p.push(this.owner.signer)}),{builder:this,transactions:a,signers:u,instructionTypes:this.instructionTypes,execute:async p=>{var h;let{sequentially:f,onTxUpdate:y,skipTxCount:b=0,recentBlockHash:g,skipPreflight:A=!0}=p||{},k=g!=null?g:await No(this.connection,this.blockhashCommitment);if(a.forEach(async(P,T)=>{P.recentBlockhash=k,u[T].length&&P.sign(...u[T])}),mo(a),(h=this.owner)!=null&&h.isKeyPair){if(f){let P=0,T=[];for(let I of a){if(++P,P<=b){T.push("tx skipped");continue}let x=await(0,Ve.sendAndConfirmTransaction)(this.connection,I,this.signers.find(S=>S.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:A});T.push(x)}return{txIds:T,signedTxs:a}}return{txIds:await Promise.all(a.map(async P=>await this.connection.sendRawTransaction(P.serialize(),{skipPreflight:A}))),signedTxs:a}}if(this.signAllTransactions){let P=await this.signAllTransactions(a.slice(b,a.length)),T=[...a.slice(0,b),...P];if(f){let I=0,x=[],S=async()=>{if(!T[I])return;I<b&&(x.push({txId:"",status:"success",signedTx:T[I]}),y==null||y([...x]),I++,S());let B=await this.connection.sendRawTransaction(T[I].serialize(),{skipPreflight:A});x.push({txId:B,status:"sent",signedTx:T[I]}),y==null||y([...x]),I++;let R=!1,L=null,O=null,C=F=>{L!==null&&clearInterval(L),O!==null&&this.connection.removeSignatureListener(O);let E=x.findIndex(_=>_.txId===B);if(E>-1){if(x[E].status==="error"||x[E].status==="success")return;x[E].status=F.err?"error":"success"}y==null||y([...x]),F.err||S()};this.loopMultiTxStatus&&(L=setInterval(async()=>{var F;if(R){clearInterval(L);return}try{let E=await this.connection.getTransaction(B,{commitment:"confirmed",maxSupportedTransactionVersion:0});E&&(R=!0,clearInterval(L),C({err:((F=E.meta)==null?void 0:F.err)||null}),console.log("tx status from getTransaction:",B))}catch(E){R=!0,clearInterval(L),console.error("getTransaction timeout:",E,B)}},Ar)),O=this.connection.onSignature(B,F=>{if(R){this.connection.removeSignatureListener(O);return}R=!0,C(F)},"confirmed"),this.connection.getSignatureStatus(B)};return await S(),{txIds:x.map(B=>B.txId),signedTxs:T}}else{let I=[];for(let x=0;x<T.length;x+=1){let S=await this.connection.sendRawTransaction(T[x].serialize(),{skipPreflight:A});I.push(S)}return{txIds:I,signedTxs:T}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:o||{}}}async sizeCheckBuildV0(e){var h;let k=e||{},{computeBudgetConfig:t,splitIns:n=[],lookupTableCache:o={},lookupTableAddress:i=[],insCountLimit:r=12}=k,a=Qe(k,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress","insCountLimit"]),u=N(N({},this.cluster==="devnet"?await za(this.connection):await Ga(this.connection)),o),s=Array.from(new Set([...this.lookupTableAddress,...i])),c=[];for(let P of s)u[P]===void 0&&c.push(new Ve.PublicKey(P));let l=await Ua({connection:this.connection,address:c});for(let[P,T]of Object.entries(l))u[P]=T;let m=t?gr(t):{instructions:[],instructionTypes:[]},p=await No(this.connection,this.blockhashCommitment),f=this.signers.reduce((P,T)=>V(N({},P),{[T.publicKey.toBase58()]:T}),{}),y=[],b=[],g=[],A=0;if(this.allInstructions.forEach(P=>{let T=[...g,P],I=t?[...m.instructions,...T]:T;if(P!==n[A]&&g.length<r&&(bi({instructions:I,payer:this.feePayer,lookupTableAddressAccount:u})||bi({instructions:T,payer:this.feePayer,lookupTableAddressAccount:u})))g.push(P);else{if(g.length===0)throw Error("item ins too big");A+=P===n[A]?1:0;let x={};for(let S of[...new Set(s)])u[S]!==void 0&&(x[S]=u[S]);if(t&&bi({instructions:[...m.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:u,recentBlockhash:p})){let S=new Ve.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...m.instructions,...g]}).compileToV0Message(Object.values(u));y.push(new Ve.VersionedTransaction(S))}else{let S=new Ve.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(u));y.push(new Ve.VersionedTransaction(S))}b.push(Array.from(new Set(g.map(S=>S.keys.filter(B=>B.isSigner).map(B=>B.pubkey.toString())).flat())).map(S=>f[S]).filter(S=>S!==void 0)),g=[P]}}),g.length>0){let T=[...new Set(g.map(I=>I.keys.filter(x=>x.isSigner).map(x=>x.pubkey.toString())).flat()).values()].map(I=>f[I]).filter(I=>I!==void 0);if(t&&bi({instructions:[...m.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:u,recentBlockhash:p})){let I=new Ve.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...m.instructions,...g]}).compileToV0Message(Object.values(u));y.push(new Ve.VersionedTransaction(I))}else{let I=new Ve.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(u));y.push(new Ve.VersionedTransaction(I))}b.push(T)}return(h=this.owner)!=null&&h.signer&&b.forEach(P=>{P.some(T=>T.publicKey.equals(this.owner.publicKey))||P.push(this.owner.signer)}),y.forEach((P,T)=>{P.sign(b[T])}),{builder:this,transactions:y,buildProps:e,signers:b,instructionTypes:this.instructionTypes,execute:async P=>{var R;let{sequentially:T,onTxUpdate:I,skipTxCount:x=0,recentBlockHash:S,skipPreflight:B=!0}=P||{};if(y.map(async(L,O)=>{b[O].length&&L.sign(b[O]),S&&(L.message.recentBlockhash=S)}),mo(y),(R=this.owner)!=null&&R.isKeyPair){if(T){let L=0,O=[];for(let C of y){if(++L,L<=x){console.log("skip tx: ",L),O.push("tx skipped");continue}let F=await this.connection.sendTransaction(C,{skipPreflight:B});await Pr(this.connection,F),O.push(F)}return{txIds:O,signedTxs:y}}return{txIds:await Promise.all(y.map(async L=>await this.connection.sendTransaction(L,{skipPreflight:B}))),signedTxs:y}}if(this.signAllTransactions){let L=await this.signAllTransactions(y.slice(x,y.length)),O=[...y.slice(0,x),...L];if(T){let C=0,F=[],E=async()=>{if(!O[C])return;if(C<x){F.push({txId:"",status:"success",signedTx:O[C]}),I==null||I([...F]),C++,E();return}let _=await this.connection.sendTransaction(O[C],{skipPreflight:B});F.push({txId:_,status:"sent",signedTx:O[C]}),I==null||I([...F]),C++;let z=!1,H=null,Y=null,J=ie=>{H!==null&&clearInterval(H),Y!==null&&this.connection.removeSignatureListener(Y);let Q=F.findIndex(ge=>ge.txId===_);if(Q>-1){if(F[Q].status==="error"||F[Q].status==="success")return;F[Q].status=ie.err?"error":"success"}I==null||I([...F]),ie.err||E()};this.loopMultiTxStatus&&(H=setInterval(async()=>{var ie;if(z){clearInterval(H);return}try{let Q=await this.connection.getTransaction(_,{commitment:"confirmed",maxSupportedTransactionVersion:0});Q&&(z=!0,clearInterval(H),J({err:((ie=Q.meta)==null?void 0:ie.err)||null}),console.log("tx status from getTransaction:",_))}catch(Q){z=!0,clearInterval(H),console.error("getTransaction timeout:",Q,_)}},Ar)),Y=this.connection.onSignature(_,ie=>{if(z){this.connection.removeSignatureListener(Y);return}z=!0,J(ie)},"confirmed"),this.connection.getSignatureStatus(_)};return E(),{txIds:[],signedTxs:O}}else{let C=[];for(let F=0;F<O.length;F+=1){let E=await this.connection.sendTransaction(O[F],{skipPreflight:B});C.push(E)}return{txIds:C,signedTxs:O}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:a||{}}}};var Xa=(...d)=>d.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch{return e}}).join(", "),ot=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=Be(t)}createTxBuilder(e){return this.scope.checkOwner(),new wr({connection:this.scope.connection,feePayer:e||this.scope.ownerPubKey,cluster:this.scope.cluster,owner:this.scope.owner,blockhashCommitment:this.scope.blockhashCommitment,loopMultiTxStatus:this.scope.loopMultiTxStatus,api:this.scope.api,signAllTransactions:this.scope.signAllTransactions})}logDebug(...e){this.logger.debug(Xa(e))}logInfo(...e){this.logger.info(Xa(e))}logAndCreateError(...e){let t=Xa(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};var le=require("@solana/spl-token"),D=require("@solana/web3.js"),Oi=te(require("bn.js"));var Re=te(require("bn.js")),De=new Re.default(1).shln(64),vo=64,Sm=new Re.default(1).shln(128),Sn=new Re.default(1).shln(64).subn(1),Km=new Re.default(1).shln(128).subn(1),cn=-443636,ln=443636,St=new Re.default("4295048016"),Kt=new Re.default("79226673521066979257578248091"),cc=new Re.default("59543866431248"),lc=new Re.default("184467440737095516"),mc=new Re.default("15793534762490258745"),dc=16,kr=512,Qt=60,zb=new Re.default("18446743708227953217"),pc=[{bit:0,factor:new Re.default("fffcb933bd6fb800",16)},{bit:1,factor:new Re.default("fff97272373d4000",16)},{bit:2,factor:new Re.default("fff2e50f5f657000",16)},{bit:3,factor:new Re.default("ffe5caca7e10f000",16)},{bit:4,factor:new Re.default("ffcb9843d60f7000",16)},{bit:5,factor:new Re.default("ff973b41fa98e800",16)},{bit:6,factor:new Re.default("ff2ea16466c9b000",16)},{bit:7,factor:new Re.default("fe5dee046a9a3800",16)},{bit:8,factor:new Re.default("fcbe86c7900bb000",16)},{bit:9,factor:new Re.default("f987a7253ac65800",16)},{bit:10,factor:new Re.default("f3392b0822bb6000",16)},{bit:11,factor:new Re.default("e7159475a2caf000",16)},{bit:12,factor:new Re.default("d097f3bdfd2f2000",16)},{bit:13,factor:new Re.default("a9f746462d9f8000",16)},{bit:14,factor:new Re.default("70d869a156f31c00",16)},{bit:15,factor:new Re.default("31be135f97ed3200",16)},{bit:16,factor:new Re.default("9aa508b5b85a500",16)},{bit:17,factor:new Re.default("5d6af8dedc582c",16)},{bit:18,factor:new Re.default("2216e584f5fa",16)}],vn=1e6;var Tr=1e5,Ii=1e4,fc=1e4,yc=1e5;var Bi=3,bc=100;var gc=10,Pc=100,_o=14;var $=new Re.default(0),dt=new Re.default(1),Xb=new Re.default(-1),hr={tvl:0,volumeQuote:0,mintAmountA:0,mintAmountB:0,rewardDefaultInfos:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0,day:{volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[0]},week:{volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[0]},month:{volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[0]},pooltype:[]};var Yb=new Re.default("18446744073700000000");var Ya=v([Ie(8),W("bump"),at("index"),M("owner"),je("protocolFeeRate"),je("tradeFeeRate"),at("tickSpacing"),je("fundFeeRate"),j(je(),1),M("fundOwner"),j(w(),3)]),Cm=v([je("blockTimestamp"),Oo("tickCumulative"),j(w(),4)]),Ac=v([Ie(8),nt("initialized"),w("recentEpoch"),at("observationIndex"),M("poolId"),j(Cm,bc,"observations"),j(w(),4)]),Rm=v([at("filterPeriod"),at("decayPeriod"),at("reductionFactor"),je("dynamicFeeControl"),je("maxVolatilityAccumulator"),yt("tickSpacingIndexReference"),je("volatilityReference"),je("volatilityAccumulator"),w("lastUpdateTimestamp"),j(W(),46)]),Lm=v([W("state"),w("openTime"),w("endTime"),w("lastUpdateTime"),ye("emissionsPerSecondX64"),w("totalEmissioned"),w("claimed"),M("mint"),M("vault"),M("creator"),ye("growthGlobalX64")]),fo=v([Ie(8),W("bump"),M("configId"),M("creator"),M("mintA"),M("mintB"),M("vaultA"),M("vaultB"),M("observationId"),W("mintDecimalsA"),W("mintDecimalsB"),at("tickSpacing"),ye("liquidity"),ye("sqrtPriceX64"),yt("tickCurrent"),je(),ye("feeGrowthGlobalX64A"),ye("feeGrowthGlobalX64B"),w("protocolFeesTokenA"),w("protocolFeesTokenB"),j(ye(),4),W("status"),W("feeOn"),Ie(6),j(Lm,Bi,"rewardInfos"),Ie(8*16,"tickArrayBitmap"),j(w(),4),w("fundFeesTokenA"),w("fundFeesTokenB"),w("startTime"),w("recentEpoch"),Rm.replicate("dynamicFeeInfo"),j(w(),46)]),Om=v([ye("growthInsideLastX64"),w("rewardAmountOwed")]),Ir=v([Ie(8),W("bump"),M("nftMint"),M("poolId"),yt("tickLower"),yt("tickUpper"),ye("liquidity"),ye("feeGrowthInsideLastX64A"),ye("feeGrowthInsideLastX64B"),w("tokenFeesOwedA"),w("tokenFeesOwedB"),j(Om,Bi,"rewardInfos"),w("recentEpoch"),j(w(),7)]),jb=v([Ie(8),W("bump"),M("poolId"),yt("tickLower"),yt("tickUpper"),ye("liquidity"),ye("feeGrowthInsideLastX64A"),ye("feeGrowthInsideLastX64B"),w("tokenFeesOwedA"),w("tokenFeesOwedB"),j(ye(),Bi,"rewardGrowthInside"),w("recentEpoch"),j(w(),7)]),Nm=v([yt("tick"),ku("liquidityNet"),ye("liquidityGross"),ye("feeGrowthOutsideX64A"),ye("feeGrowthOutsideX64B"),j(ye(),Bi,"rewardGrowthsOutsideX64"),w("orderPhase"),w("ordersAmount"),w("partFilledOrdersRemaining"),ye("unfilledRatioX64"),j(je(),3)]),Vo=v([Ie(8),M("poolId"),yt("startTickIndex"),j(Nm,Qt,"ticks"),W("initializedTickCount"),w("recentEpoch"),j(W(),107)]),wc=v([Ie(8),W("bump"),j(M(),gc,"operationOwners"),j(M(),Pc,"whitelistMints")]),yo=v([Ie(8),M("poolId"),M("owner"),yt("tick"),nt("zeroForOne"),w("orderPhase"),w("totalAmount"),w("filledAmount"),w("settleBase"),w("settleOutput"),w("openTime"),ye("unfilledRatioX64"),j(w(),4)]),Br=v([Ie(8),M("poolId"),Ie(8*8*_o,"positiveTickArrayBitmap"),Ie(8*8*_o,"negativeTickArrayBitmap")]),$b=v([Ie(8),at("index"),at("filterPeriod"),at("decayPeriod"),at("reductionFactor"),je("dynamicFeeControl"),je("maxVolatilityAccumulator"),j(w(),8)]),kc=v([Ie(8),M("wallet"),W("nonceIndex"),w("orderNonce"),j(w(),4)]),Jb=v([w(),W("bump"),M("owner"),M("poolId"),M("positionId"),M("nftAccount"),j(w(),8)]),Tc=v([Ie(8),W("bump"),M("lockOwner"),M("poolId"),M("positionId"),M("nftAccount"),M("lockNftMint"),w("recentEpoch"),j(w(),8)]);var hc=te(require("bn.js"));function xr(d){let e=Buffer.alloc(2);return e.writeUInt16LE(d),e}function Ha(d){let e=Buffer.alloc(4);return e.writeInt32LE(d),e}function Ic(d){let e=Buffer.alloc(4);return e.writeInt32BE(d),e}function Bc(d){return(typeof d=="number"||typeof d=="bigint")&&(d=new hc.default(d.toString())),d.toArrayLike(Buffer,"be",8)}function xc(d){let e=new ArrayBuffer(1);return new DataView(e).setUint8(0,d),new Uint8Array(e)}var sg=Buffer.from("amm_config","utf8"),Sr=Buffer.from("pool","utf8"),Qa=Buffer.from("pool_vault","utf8"),Mm=Buffer.from("pool_reward_vault","utf8"),Sc=Buffer.from("position","utf8"),Fm=Buffer.from("tick_array","utf8"),vm=Buffer.from("operation","utf8"),_m=Buffer.from("pool_tick_array_bitmap_extension","utf8"),Vm=Buffer.from("observation","utf8"),Em=Buffer.from("support_mint","utf8"),ug=Buffer.from("dynamic_fee_config","utf8"),Dm=Buffer.from("permission","utf8");function Kc(d,e,t,n){return de([Sr,e.toBuffer(),t.toBuffer(),n.toBuffer()],d)}function Cc(d,e){return de([Dm,e.toBuffer()],d)}function Rc(d,e,t,n,o){return de([Sr,e.toBuffer(),t.toBuffer(),n.toBuffer(),xr(o)],d)}function on(d,e,t){return de([Qa,e.toBuffer(),t.toBuffer()],d)}function Lc(d,e,t){return de([Mm,e.toBuffer(),t.toBuffer()],d)}function Ee(d,e,t){return de([Fm,e.toBuffer(),Ic(t)],d)}function gn(d,e,t,n){return de([Sc,e.toBuffer(),Ha(t),Ha(n)],d)}function rn(d,e){return de([Sc,e.toBuffer()],d)}function _n(d){return de([Buffer.from("metadata","utf8"),Bn.toBuffer(),d.toBuffer()],Bn)}function xi(d){return de([vm],d)}function He(d,e){return de([_m,e.toBuffer()],d)}function Za(d,e){return de([Vm,e.toBuffer()],d)}function bo(d,e){return de([Em,e.toBuffer()],d)}function Oc(d,e,t,n){return de([e.toBuffer(),t.toBuffer(),Bc(n)],d)}function Nc(d,e,t){return de([e.toBuffer(),xc(t)],d)}var Mc=Buffer.from("locked_position","utf8");function ja(d,e){return de([Mc,e.toBuffer()],d)}function Eo(d,e){return de([Mc,e.toBuffer()],d)}var Uc=require("js-sha256");var $a=te(require("bn.js")),Kr=te(require("decimal.js"));function ut(d,e,t){if(t.isZero())throw new Error("Division by zero");return d.mul(e).div(t)}function $e(d,e,t){if(t.isZero())throw new Error("Division by zero");let n=d.mul(e),o=n.div(t);return n.mod(t).isZero()?o:o.addn(1)}function Cr(d,e){return d.div(e).add(d.mod(e).isZero()?$:dt)}var mg=new $a.default(1).shln(256).subn(1);function Fc(d){return d.isZero()?-1:d.bitLength()-1}function vc(d,e){return new Kr.default(d.toString()).div(Kr.default.pow(2,64)).toDecimalPlaces(e)}function go(d){return new $a.default(d.mul(Kr.default.pow(2,64)).floor().toFixed())}var Vc=te(require("bn.js"));var gt=te(require("bn.js")),Po=te(require("decimal.js"));var Vn=class{static scanLinearBitmap({bitmap:e,tickSpacing:t,offset:n,checkInfo:o}){let i=[],r=e.length*8,a=0,u=r-1;if(o){let l=o.tick/(t*Qt)-n;o.valueType==="gte"?a=Math.max(0,Math.ceil(l)):u=Math.min(r-1,Math.floor(l))}if(a>u)return i;let s=Math.floor(a/8),c=Math.floor(u/8);for(let l=s;l<=c;l++){if(!e[l])continue;let m=l===s?a%8:0,p=l===c?u%8:7;for(let f=m;f<=p;f++)e[l]&1<<f&&i.push((l*8+f+n)*t*Qt)}return i}static findPoolBitmap({bitmap:e,tickSpacing:t,checkInfo:n}){if(n){let o=Math.floor(n.tick/Qt/t);if(n.valueType==="lte"&&o<-512)return[];if(n.valueType==="gte"&&o>512)return[]}return this.scanLinearBitmap({bitmap:e,tickSpacing:t,offset:-kr,checkInfo:n})}static findPositiveTickArrayBitmap({bitmap:e,tickSpacing:t,checkInfo:n}){if(n){let o=Math.floor(n.tick/Qt/t);if(n.valueType==="lte"&&o<512)return[]}return this.scanLinearBitmap({bitmap:e,tickSpacing:t,offset:kr,checkInfo:n})}static findNegativeTickArrayBitmap({bitmap:e,tickSpacing:t,count:n,checkInfo:o}){let i=[];if(o){let u=Math.floor(o.tick/Qt/t);if(o.valueType==="gte"&&u>=-512)return i}let r=(o==null?void 0:o.valueType)==="lte"?Math.floor(o.tick/(Qt*t))+7680:1/0,a=(o==null?void 0:o.valueType)==="gte"?Math.ceil(o.tick/(Qt*t))+7680:0;e:for(let u=0;u<_o;u++){let s=_o-1-u;for(let c=0;c<512;c++){let l=u*512+c;if(l>r)break e;if(l<a)continue;let m=s*64+Math.floor(c/8);if(!e[m]){c=Math.floor(c/8)*8+7;continue}if(e[m]&1<<c%8){let p=(u*512+c-7680)*Qt*t;if(i.push(p),n!==void 0&&i.length>=n)break e}}}return i}static findTickArrayStartIndex({tickSpacing:e,poolBitmap:t,tickArrayBitmap:n,findInfo:o}){if(o.type==="all")return[...this.findNegativeTickArrayBitmap({tickSpacing:e,bitmap:n.negativeTickArrayBitmap}),...this.findPoolBitmap({tickSpacing:e,bitmap:t}),...this.findPositiveTickArrayBitmap({tickSpacing:e,bitmap:n.positiveTickArrayBitmap})];let i=Te.getTickArrayStartIndex(o.tickArrayCurrent,e),{count:r}=o;if(o.type==="oneForZero"){let a={tick:i,valueType:"gte"},u=[()=>this.findNegativeTickArrayBitmap({tickSpacing:e,bitmap:n.negativeTickArrayBitmap,checkInfo:a}),()=>this.findPoolBitmap({tickSpacing:e,bitmap:t,checkInfo:a}),()=>this.findPositiveTickArrayBitmap({tickSpacing:e,bitmap:n.positiveTickArrayBitmap,checkInfo:a})];return this.collectUntil(u,r)}if(o.type==="zeroForOne"){let a={tick:i,valueType:"lte"},u=[()=>this.findPositiveTickArrayBitmap({tickSpacing:e,bitmap:n.positiveTickArrayBitmap,checkInfo:a}).sort((s,c)=>c-s),()=>this.findPoolBitmap({tickSpacing:e,bitmap:t,checkInfo:a}).sort((s,c)=>c-s),()=>this.findNegativeTickArrayBitmap({tickSpacing:e,bitmap:n.negativeTickArrayBitmap,checkInfo:a}).sort((s,c)=>c-s)];return this.collectUntil(u,r)}throw new Error("find info type check error")}static collectUntil(e,t){let n=[];for(let o of e){if(t!==void 0&&n.length>=t)break;n.push(...o())}return n.slice(0,t)}static findTickArrayAddress(e){return this.findTickArrayStartIndex(e).map(t=>Ee(e.programId,e.poolId,t).publicKey)}static maxTickInTickarrayBitmap(e){return e*Qt*kr}},Te=class{static firstinitializedTick({data:e,zeroForOne:t}){if(t){for(let n=e.ticks.length-1;n>=0;n--)if(se.isInitialized({data:e.ticks[n]}))return e.ticks[n]}else for(let n=0;n<e.ticks.length;n++)if(se.isInitialized({data:e.ticks[n]}))return e.ticks[n]}static nextInitalizedTick({data:e,currentTickIndex:t,tickSpacing:n,zeroForOne:o}){if(this.getTickArrayStartIndex(t,n)!==e.startTickIndex)return;let r=Math.floor((t-e.startTickIndex)/n);if(o){for(let a=r;a>=0;a--)if(se.isInitialized({data:e.ticks[a]}))return e.ticks[a]}else for(let a=r+1;a<Qt;a++)if(se.isInitialized({data:e.ticks[a]}))return e.ticks[a]}static getTickArrayStartIndex(e,t){let n=this.tickCount(t);return Math.floor(e/n)*n}static getTickOffsetInArray(e,t){if(e%t!=0)throw new Error("tickIndex % tickSpacing not equal 0");let n=this.getTickArrayStartIndex(e,t);return Math.floor((e-n)/t)}static tickCount(e){return Qt*e}static getMinTick(e){return Math.ceil(cn/e)*e}static getMaxTick(e){return Math.floor(ln/e)*e}},se=class{static isInitialized({data:e}){return this.hasLiquidity({data:e})||this.hasLimitOrders({data:e})}static hasLimitOrders({data:e}){return!e.ordersAmount.isZero()||!e.partFilledOrdersRemaining.isZero()}static hasLiquidity({data:e}){return!e.liquidityGross.isZero()}static isValidTick(e){return e>=cn&&e<=ln}static checkTick(e){if(!this.isValidTick(e))throw new Error(`Tick ${e} is out of range [${cn}, ${ln}]`)}static getSqrtPriceAtTick(e){this.checkTick(e);let t=Math.abs(e),n=De.clone();for(let{bit:o,factor:i}of pc)(t&1<<o)!==0&&(n=ut(n,i,De));return e>0&&(n=ut(De,De,n)),n}static getLimitOrderOutput({amountIn:e,tick:t,zeroForOne:n}){if(n){let o=se.getPriceAtTick(t,!1);return ut(e,o,De)}else{let o=se.getPriceAtTick(t,!0);return ut(e,De,o)}}static getLimitOrderInput({amountOut:e,tick:t,zeroForOne:n}){if(n){let o=se.getPriceAtTick(t,!0);return $e(e,o,De)}else{let o=se.getPriceAtTick(t,!1);return $e(e,De,o)}}static limitOrderUnfilledAmount({tick:e}){return e.ordersAmount.add(e.partFilledOrdersRemaining)}static matchLimitOrder({tick:e,swapAmount:t,swapDirectionZeroForOne:n,isBaseInput:o,feeRate:i,isFeeOnInput:r}){let a={amountIn:$,amountOut:$,ammFeeAmount:$},u=this.limitOrderUnfilledAmount({tick:e});if(t.isZero()||u.isZero())return a;if(o)r?(a.ammFeeAmount=$e(t,new gt.default(i),Je),a.amountIn=t.sub(a.ammFeeAmount)):a.amountIn=t,a.amountOut=this.getLimitOrderOutput({amountIn:a.amountIn,tick:e.tick,zeroForOne:n}),a.amountOut.gt(u)&&(a.amountOut=u,a.amountIn=this.getLimitOrderInput({amountOut:u,tick:e.tick,zeroForOne:!n}),r&&(a.ammFeeAmount=$e(a.amountIn,new gt.default(i),Je.sub(new gt.default(i)))));else{let l=gt.default.min(t,u);r?a.amountOut=l:a.amountOut=gt.default.min($e(l,Je,Je.sub(new gt.default(i))),u),a.amountIn=this.getLimitOrderInput({amountOut:a.amountOut,tick:e.tick,zeroForOne:!n}),r&&(a.ammFeeAmount=$e(a.amountIn,new gt.default(i),Je.sub(new gt.default(i))))}let s=$;e.partFilledOrdersRemaining.gt($)&&(s=gt.default.min(e.partFilledOrdersRemaining,a.amountOut),s.gt($)&&(e.unfilledRatioX64=ut(e.unfilledRatioX64,e.partFilledOrdersRemaining.sub(s),e.partFilledOrdersRemaining)),e.partFilledOrdersRemaining=e.partFilledOrdersRemaining.sub(s));let c=a.amountOut.sub(s);if(c.gt($)){if(!e.partFilledOrdersRemaining.isZero())throw Error("!tick.partFilledOrdersRemaining.isZero()");if(e.ordersAmount.lt(c))throw Error("InvalidLimitOrderAmount");e.orderPhase=e.orderPhase.add(dt),e.unfilledRatioX64=ut(De,e.ordersAmount.sub(c),e.ordersAmount),e.partFilledOrdersRemaining=e.ordersAmount.sub(c),e.ordersAmount=$}return r||(a.ammFeeAmount=$e(a.amountOut,new gt.default(i),Je),a.amountOut=a.amountOut.sub(a.ammFeeAmount)),a}static getPriceAtTick(e,t){let n=this.getSqrtPriceAtTick(e);return t?n.mul(n).add(De.subn(1)).div(De):n.mul(n).div(De)}static getTickAtSqrtPrice(e){if(!(e.gte(St)&&e.lte(Kt)))throw Error("SqrtPriceX64");let t=Fc(e),n=t-64,o;n>=0?o=new gt.default(n).shln(32):o=new gt.default(-n).shln(32).neg();let i;t>=64?i=e.shrn(t-63):i=e.shln(63-t);let r=new gt.default(0),a=new gt.default(1).shln(63);for(let b=0;b<dc&&!a.isZero();b++){i=i.mul(i);let g=i.shrn(127).toNumber();i=i.shrn(63+g),g&&(r=r.add(a)),a=a.shrn(1)}let u=r.shrn(32),c=o.add(u).mul(cc),l=c.sub(lc),m=c.add(mc),p=this.signedShrn64(l),f=this.signedShrn64(m);return p===f?p:se.getSqrtPriceAtTick(f).lte(e)?f:p}static signedShrn64(e){if(e.isNeg()){let t=new gt.default(1).shln(64),n=e.div(t);return!e.mod(t).isZero()&&e.isNeg()?n.subn(1).toNumber():n.toNumber()}else return e.shrn(64).toNumber()}static sqrtPriceX64ToPrice(e,t,n){let o=e.mul(e),i=t-n,r=20,a=new gt.default(10).pow(new gt.default(r)),u=o.mul(a),s=new gt.default(1).shln(128),l=u.div(s).toString();for(;l.length<=r;)l="0"+l;let m=l.slice(0,-r),p=l.slice(-r),f=m+"."+p;return new Po.default(f).mul(new Po.default(10).pow(i))}static tickToPrice(e,t,n){let o=se.getSqrtPriceAtTick(e);return this.sqrtPriceX64ToPrice(o,t,n)}static priceToTick(e,t,n){let i=e.div(Math.pow(10,t-n)).log().div(new Po.default(1.0001).log()).floor();return Math.max(cn,Math.min(ln,i.toNumber()))}static priceToSqrtPriceX64(e,t,n){let r=e.div(Math.pow(10,t-n)).sqrt().mul(new Po.default(2).pow(64));return new gt.default(r.toFixed(0))}static toTickIndex(e,t){return e>=0?e-e%t:e-e%t-(e%t!==0?t:0)}static getPriceAndTick({price:e,mintADecimals:t,mintBDecimals:n,zeroForOne:o,tickSpacing:i}){let r=e.clamp(1/10**Math.max(t,n),Number.MAX_SAFE_INTEGER);o||(r=new Po.default(1).div(r));let a=se.toTickIndex(se.priceToTick(r,t,n),i),u=se.tickToPrice(a,t,n);return{price:o?u:new Po.default(1).div(u),tick:a}}};async function _c(d,e,t,n,o,i,r=!0){let a=[],u=He(d,t).publicKey,s=await e.getAccountInfo(u),c=Vn.findTickArrayAddress({programId:d,poolId:t,poolBitmap:i,tickArrayBitmap:Br.decode(s.data),tickSpacing:o,findInfo:{type:r?"zeroForOne":"oneForZero",tickArrayCurrent:n}});return(await It(e,c)).forEach((m,p)=>{m&&a.push({address:c[p],value:Vo.decode(m.data)})}),a}var $n=class{static isFullyFilled({orderInfo:e}){return e.totalAmount.eq(e.filledAmount)}static getUnFilledAmount({orderInfo:e}){return e.totalAmount.sub(e.filledAmount)}static settleFilledOrder({orderInfo:e,tickInfo:t}){if(e.settleBase.isZero())return $;if(e.orderPhase.eq(t.orderPhase))return $;if(e.orderPhase.add(dt).eq(t.orderPhase)){let n=e.settleBase.mul(t.unfilledRatioX64),o=e.unfilledRatioX64,i=n.div(o),r=n.mod(o).isZero(),a=e.settleBase.sub(i);if(a.isZero())return $;let u=r?a:a.sub(dt);return se.getLimitOrderOutput({amountIn:u,tick:t.tick,zeroForOne:e.zeroForOne}).sub(e.settleOutput)}else{if(e.orderPhase.add(new Vc.default(2)).lte(t.orderPhase))return se.getLimitOrderOutput({amountIn:e.settleBase,tick:t.tick,zeroForOne:e.zeroForOne}).sub(e.settleOutput);throw Error("invalid order phase")}}};var Si=te(require("bn.js")),Ja=te(require("decimal.js"));var pt=class{static getDeltaAmountAUnsigned(e,t,n,o){e.gt(t)&&([e,t]=[t,e]);let i=n.shln(vo),r=t.sub(e);if(!e.gt($))throw Error("!sqrtPriceX64A.gt(BN_ZERO)");let a=o?Cr($e(i,r,t),e):ut(i,r,t).div(e);if(a.gt(Sn))throw Error("MaxTokenOverflow");return a}static getDeltaAmountBUnsigned(e,t,n,o){e.gt(t)&&([e,t]=[t,e]);let i=o?$e(n,t.sub(e),De):ut(n,t.sub(e),De);if(i.gt(Sn))throw Error("MaxTokenOverflow");return i}static addDelta(e,t){if(t.isNeg()){let n=t.neg();if(e.lt(n))throw new Error("Liquidity underflow");return e.sub(n)}else return e.add(t)}static getLiquidityFromAmountA(e,t,n){if(n.isZero())return $;e.gt(t)&&([e,t]=[t,e]);let o=ut(e,t,De),i=t.sub(e);return ut(n,o,i)}static getLiquidityFromAmountB(e,t,n){if(n.isZero())return $;e.gt(t)&&([e,t]=[t,e]);let o=t.sub(e);return ut(n,De,o)}static getLiquidityFromAmounts(e,t,n,o,i){if(t.gt(n)&&([t,n]=[n,t]),e.lte(t))return this.getLiquidityFromAmountA(t,n,o);if(e.lt(n)){let r=this.getLiquidityFromAmountA(e,n,o),a=this.getLiquidityFromAmountB(t,e,i);return r.lt(a)?r:a}else return this.getLiquidityFromAmountB(t,n,i)}static getAmountsForLiquidity(e,t,n,o,i){t.gt(n)&&([t,n]=[n,t]);let r=$,a=$;return e.lte(t)?r=this.getDeltaAmountAUnsigned(t,n,o,i):e.lt(n)?(r=this.getDeltaAmountAUnsigned(e,n,o,i),a=this.getDeltaAmountBUnsigned(t,e,o,i)):a=this.getDeltaAmountBUnsigned(t,n,o,i),{amountA:r,amountB:a}}static getAmountsFromLiquidityWithSlippage(e,t,n,o,i,r,a){let{amountA:u,amountB:s}=this.getAmountsForLiquidity(e,t,n,o,r),c=i?1+a:1-a,l=new Si.default(new Ja.default(u.toString()).mul(c).toFixed(0)),m=new Si.default(new Ja.default(s.toString()).mul(c).toFixed(0));return{amountSlippageA:l,amountSlippageB:m}}static getLiquidityAndAmountsFromAmount({sqrtPriceCurrentX64:e,sqrtPriceLowerX64:t,sqrtPriceUpperX64:n,amountInfo:o}){let i;if(o.type==="liquidity")i=o.amount;else if(o.type==="amountA")i=e.gte(n)?$:this.getLiquidityFromAmountA(Si.default.max(e,t),n,o.amount);else if(o.type==="amountB")i=e.lte(t)?$:this.getLiquidityFromAmountB(t,Si.default.min(e,n),o.amount);else throw Error("amount info type check error");return N({liquidity:i},this.getAmountsForLiquidity(e,t,n,o.amount,!0))}};var Vt=require("@solana/web3.js"),kt=te(require("bn.js"));var Li=require("@solana/spl-token");var xe=te(require("decimal.js"));var Ao=te(require("bn.js"));var ft=te(require("bn.js"));var Ki=class{static getNextSqrtPriceFromAmountARoundingUp(e,t,n,o){if(n.isZero())return e;let i=t.shln(vo);if(o){let r=n.mul(e),a=i.add(r);if(a.gte(i))return $e(i,e,a);let u=ut(i,dt,e);return $e(i,dt,u.add(n))}else{let r=n.mul(e);if(i.lte(r))throw new Error("Insufficient liquidity for token0 removal");let a=i.sub(r);return $e(i,e,a)}}static getNextSqrtPriceFromAmountBRoundingDown(e,t,n,o){if(n.isZero())return e;if(o){let i=n.shln(vo).div(t);return e.add(i)}else{let i=Cr(n.shln(vo),t);return e.sub(i)}}static getNextSqrtPriceFromInput(e,t,n,o){if(!e.gt($))throw Error("sqrtPriceX64.gt(BN_ZERO)");if(!t.gt($))throw Error("liquidity.gt(BN_ZERO)");return o?this.getNextSqrtPriceFromAmountARoundingUp(e,t,n,!0):this.getNextSqrtPriceFromAmountBRoundingDown(e,t,n,!0)}static getNextSqrtPriceFromOutput(e,t,n,o){if(!e.gt($))throw Error("sqrtPriceX64.gt(BN_ZERO)");if(!t.gt($))throw Error("liquidity.gt(BN_ZERO)");return o?this.getNextSqrtPriceFromAmountBRoundingDown(e,t,n,!1):this.getNextSqrtPriceFromAmountARoundingUp(e,t,n,!1)}};var Pn=class{static newValue({poolInfo:e,amountSpecified:t,zeroForOne:n,feeRate:o,blockTimestamp:i}){let r={amountSpecifiedRemaining:t,amountCalculated:$,sqrtPriceX64:e.sqrtPriceX64,tick:e.tickCurrent,feeGrowthGlobalX64:n?e.feeGrowthGlobalX64A:e.feeGrowthGlobalX64B,lpFee:$,protocolFee:$,fundFee:$,liquidity:e.liquidity,sqrtPriceNextX64:$,tickNext:0,baseFeeRate:o,tickSpacing:e.tickSpacing,tickSpacingIndex:0,dynamicFeeInfo:Do.getDynamicFeeInfo({poolInfo:e})};return r.dynamicFeeInfo&&(r.tickSpacingIndex=Ri.tickSpacingIndexFromTick(r.tick,r.tickSpacing),Do.updateReference({dynamicFeeInfo:r.dynamicFeeInfo,tickSpacingIndex:r.tickSpacingIndex,currentTimestamp:i})),r}static getTargetPriceBasedOnNextTick({data:e,tickNext:t,zeroForOne:n,sqrtPriceLimitX64:o}){e.tickNext=t,e.tickNext<cn?e.tickNext=cn:e.tickNext>ln&&(e.tickNext=ln),e.sqrtPriceNextX64=se.getSqrtPriceAtTick(e.tickNext);let i;if(n&&e.sqrtPriceNextX64.lt(o)||!n&&e.sqrtPriceNextX64.gt(o)?i=o:i=e.sqrtPriceNextX64,n){if(e.tick<e.tickNext)throw Error("data.tick < data.tickNext");if(e.sqrtPriceX64.lt(e.sqrtPriceNextX64))throw Error("data.sqrtPriceX64.lt(data.sqrtPriceNextX64)");if(e.sqrtPriceX64.lt(i))throw Error("data.sqrtPriceX64.lt(targetPrice)")}else{if(e.tickNext<=e.tick)throw Error("data.tickNext <= data.tick");if(e.sqrtPriceNextX64.lt(e.sqrtPriceX64))throw Error("data.sqrtPriceNextX64.lt(data.sqrtPriceX64)");if(i.lt(e.sqrtPriceX64))throw Error("targetPrice.lt(data.sqrtPriceX64)")}return i}static updateVolatilityAccumulator({state:e}){!e.dynamicFeeInfo||Do.updateVolatilityAccumulator({state:e.dynamicFeeInfo,tickSpacingIndex:e.tickSpacingIndex})}static computeDynamicFeeRate({data:e,tickSpacing:t}){let n=e.volatilityAccumulator*t,o=n*n,i=yc*Ii*Ii,r=$e(new ft.default(e.dynamicFeeControl),new ft.default(o),new ft.default(i)).toNumber();return r>Tr?Tr:r}static getTotalFeeRate({data:e}){if(e.dynamicFeeInfo){let t=this.computeDynamicFeeRate({data:e.dynamicFeeInfo,tickSpacing:e.tickSpacing}),n=e.baseFeeRate+t;return Math.min(Tr,n)}return e.baseFeeRate}static getSpacingBoundedPrice({data:e,targetPrice:t,zeroForOne:n}){if(e.dynamicFeeInfo===void 0)return{isSkipped:!0,boundedPrice:t};if(e.liquidity.isZero()||e.dynamicFeeInfo.volatilityAccumulator===e.dynamicFeeInfo.maxVolatilityAccumulator)return{isSkipped:!0,boundedPrice:t};let o=e.tickSpacing,i=n?e.tickSpacingIndex*o:(e.tickSpacingIndex+1)*o,r=Math.max(cn,Math.min(ln,i)),a=se.getSqrtPriceAtTick(r);return n?{isSkipped:!1,boundedPrice:ft.default.max(t,a)}:{isSkipped:!1,boundedPrice:ft.default.min(t,a)}}static applySwapAmounts({state:e,amountIn:t,amountOut:n,feeAmount:o,isBaseInput:i,isFeeOnInput:r,protocolFeeRate:a,fundFeeRate:u}){let s=r?t.add(o):t;i?(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.sub(s),e.amountCalculated=e.amountCalculated.add(n)):(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.sub(n),e.amountCalculated=e.amountCalculated.add(s)),this.splitFee({state:e,feeAmount:o,protocolFeeRate:a,fundFeeRate:u})}static updateDynamicFeeIndex({state:e,zeroForOne:t,isSkippedTickSpacing:n}){if(e.dynamicFeeInfo!==void 0){if(n){let o=e.sqrtPriceX64.eq(e.sqrtPriceNextX64)?e.tickNext:e.tick,i=Ri.tickSpacingIndexFromTick(o,e.tickSpacing);!t&&o%e.tickSpacing===0&&(i=i-1),e.tickSpacingIndex=i,e.dynamicFeeInfo.volatilityAccumulator!==e.dynamicFeeInfo.maxVolatilityAccumulator&&this.updateVolatilityAccumulator({state:e})}e.tickSpacingIndex+=t?-1:1}}static splitFee({state:e,feeAmount:t,protocolFeeRate:n,fundFeeRate:o}){let i=t;if(n.gt($)){let r=t.mul(n).div(new ft.default(Je));e.protocolFee=e.protocolFee.add(r),i=i.sub(r)}if(o.gt($)){let r=t.mul(o).div(new ft.default(Je));e.fundFee=e.fundFee.add(r),i=i.sub(r)}if(e.liquidity.gt($)){let r=ut(i,De,e.liquidity);e.feeGrowthGlobalX64=e.feeGrowthGlobalX64.add(r),e.lpFee=e.lpFee.add(i)}}},Ci=class{static newSwapComputationResult({sqrtPriceNextX64:e}){return{sqrtPriceNextX64:e!=null?e:$,amountIn:$,amountOut:$,feeAmount:$}}static calculateAmountInRange({sqrtPriceCurrentX64:e,sqrtPriceTargetX64:t,liquidity:n,zeroForOne:o,isBaseInput:i}){if(i)try{return o?pt.getDeltaAmountAUnsigned(t,e,n,!0):pt.getDeltaAmountBUnsigned(e,t,n,!0)}catch(r){if(r.message==="MaxTokenOverflow")return null;throw r}else try{return o?pt.getDeltaAmountBUnsigned(t,e,n,!1):pt.getDeltaAmountAUnsigned(e,t,n,!1)}catch(r){if(r.message==="MaxTokenOverflow")return null;throw r}}static computeSwap(e,t,n,o,i,r,a,u){let s=this.newSwapComputationResult({});if(r){let l=u?ut(o,new ft.default(vn-i),new ft.default(vn)):o,m=this.calculateAmountInRange({sqrtPriceCurrentX64:e,sqrtPriceTargetX64:t,liquidity:n,zeroForOne:a,isBaseInput:r});m!==null&&(s.amountIn=m),s.sqrtPriceNextX64=m!==null&&l.gte(s.amountIn)?t:Ki.getNextSqrtPriceFromInput(e,n,l,a)}else{let l=u?o:$e(o,new ft.default(vn),new ft.default(vn-i)),m=this.calculateAmountInRange({sqrtPriceCurrentX64:e,sqrtPriceTargetX64:t,liquidity:n,zeroForOne:a,isBaseInput:r});m!==null&&(s.amountOut=m),s.sqrtPriceNextX64=m!==null&&l.gte(s.amountOut)?t:Ki.getNextSqrtPriceFromOutput(e,n,l,a)}if(a){if(!s.sqrtPriceNextX64.gte(t))throw Error("!result.sqrtPriceNextX64.gte(sqrtPriceTargetX64)")}else if(!t.gte(s.sqrtPriceNextX64))throw Error("!sqrtPriceTargetX64.gte(result.sqrtPriceNextX64)");let c=t.eq(s.sqrtPriceNextX64);if(a?(c&&r||(s.amountIn=pt.getDeltaAmountAUnsigned(s.sqrtPriceNextX64,e,n,!0)),c&&!r||(s.amountOut=pt.getDeltaAmountBUnsigned(s.sqrtPriceNextX64,e,n,!1))):(c&&r||(s.amountIn=pt.getDeltaAmountBUnsigned(e,s.sqrtPriceNextX64,n,!0)),c&&!r||(s.amountOut=pt.getDeltaAmountAUnsigned(e,s.sqrtPriceNextX64,n,!1))),r)u?s.sqrtPriceNextX64.eq(t)?s.feeAmount=$e(s.amountIn,new ft.default(i),new ft.default(vn-i)):s.feeAmount=o.sub(s.amountIn):(s.feeAmount=$e(s.amountOut,new ft.default(i),new ft.default(vn)),s.amountOut=s.amountOut.sub(s.feeAmount),c||(s.amountIn=o));else if(u)s.amountOut=ft.default.min(s.amountOut,o),s.feeAmount=$e(s.amountIn,new ft.default(i),new ft.default(vn-i));else{s.feeAmount=$e(s.amountOut,new ft.default(i),new ft.default(vn));let l=s.amountOut.sub(s.feeAmount);l.gt(o)?(s.feeAmount=s.amountOut.sub(o),s.amountOut=o):s.amountOut=l}return s}};function es({programId:d,poolId:e,poolInfo:t,tickArrays:n,configInfo:o,tickarrayBitmapExtension:i,amountSpecified:r,sqrtPriceLimitX64:a,zeroForOne:u,isBaseInput:s,blockTimestamp:c,includeExtraTickArrays:l}){a.isZero()&&(a=u?new Ao.default(St).addn(1):new Ao.default(Kt).subn(1));let m=0;if(n.length===0)return{allTrade:!1,amountSpecifiedRemaining:r,amountCalculated:$,feeAmount:$,sqrtPriceX64:t.sqrtPriceX64,liquidity:t.liquidity,tickCurrent:t.tickCurrent,accounts:[]};let p=l?Vn.findTickArrayAddress({programId:d,poolId:e,tickSpacing:t.tickSpacing,poolBitmap:t.tickArrayBitmap,tickArrayBitmap:i,findInfo:{type:u?"oneForZero":"zeroForOne",count:2,tickArrayCurrent:t.tickCurrent}}).filter(T=>T.toString()!==n[0].address.toString()):[],f=Te.getTickArrayStartIndex(t.tickCurrent,t.tickSpacing),{firstItckArrayContainsPoolTick:y,firstValidTickArrayStartIndex:b}={firstItckArrayContainsPoolTick:n[m].value.startTickIndex===f,firstValidTickArrayStartIndex:n[m].value.startTickIndex},g=y,A=b,k=n[m],h=Zt.isFeeOnInput(t.feeOn,u),P=Pn.newValue({poolInfo:t,amountSpecified:r,zeroForOne:u,feeRate:o.tradeFeeRate,blockTimestamp:c});for(;!P.amountSpecifiedRemaining.isZero()&&!P.sqrtPriceX64.eq(a);){let T=(()=>{let S=Te.nextInitalizedTick({data:k.value,tickSpacing:P.tickSpacing,zeroForOne:u,currentTickIndex:P.tick});if(S!==void 0)return S;if(g){let B=n[++m];return B===void 0?void 0:(A=B.value.startTickIndex,k=B,Te.firstinitializedTick({data:B.value,zeroForOne:u}))}else return g=!0,Te.firstinitializedTick({data:k.value,zeroForOne:u})})();if(T===void 0)return{allTrade:!1,amountSpecifiedRemaining:P.amountSpecifiedRemaining,amountCalculated:P.amountCalculated,feeAmount:P.lpFee.add(P.fundFee).add(P.protocolFee),sqrtPriceX64:P.sqrtPriceX64,liquidity:P.liquidity,tickCurrent:P.tick,accounts:n.slice(0,m).map(S=>S.address)};let I=Pn.getTargetPriceBasedOnNextTick({data:P,tickNext:T.tick,zeroForOne:u,sqrtPriceLimitX64:a}),x=P.liquidity;do{Pn.updateVolatilityAccumulator({state:P});let S=Pn.getTotalFeeRate({data:P}),{isSkipped:B,boundedPrice:R}=Pn.getSpacingBoundedPrice({data:P,targetPrice:I,zeroForOne:u}),L=!P.sqrtPriceX64.eq(R),O;L?(O=Ci.computeSwap(P.sqrtPriceX64,R,P.liquidity,P.amountSpecifiedRemaining,S,s,u,h),Pn.applySwapAmounts({state:P,amountIn:O.amountIn,amountOut:O.amountOut,feeAmount:O.feeAmount,isBaseInput:s,isFeeOnInput:h,protocolFeeRate:new Ao.default(o.protocolFeeRate),fundFeeRate:new Ao.default(o.fundFeeRate)})):O=Ci.newSwapComputationResult({sqrtPriceNextX64:R});let C=se.limitOrderUnfilledAmount({tick:T});if(P.sqrtPriceNextX64.eq(O.sqrtPriceNextX64)){let F=se.matchLimitOrder({tick:T,swapAmount:P.amountSpecifiedRemaining,swapDirectionZeroForOne:u,isBaseInput:s,feeRate:S,isFeeOnInput:h});if(F.amountIn.gt($)&&Pn.applySwapAmounts({state:P,amountIn:F.amountIn,amountOut:F.amountOut,feeAmount:F.ammFeeAmount,isBaseInput:s,isFeeOnInput:h,protocolFeeRate:new Ao.default(o.protocolFeeRate),fundFeeRate:new Ao.default(o.fundFeeRate)}),se.hasLiquidity({data:T})&&!se.hasLimitOrders({data:T})){let E=u?T.liquidityNet.neg():T.liquidityNet;x=pt.addDelta(P.liquidity,E)}P.tick=u&&!se.hasLimitOrders({data:T})||!u&&se.hasLimitOrders({data:T})?P.tickNext-1:P.tickNext}else P.sqrtPriceX64.eq(O.sqrtPriceNextX64)||(P.tick=se.getTickAtSqrtPrice(O.sqrtPriceNextX64));if(P.sqrtPriceX64=O.sqrtPriceNextX64,Pn.updateDynamicFeeIndex({state:P,zeroForOne:u,isSkippedTickSpacing:B}),P.amountSpecifiedRemaining.isZero()||P.sqrtPriceX64.eq(I)){let F=se.limitOrderUnfilledAmount({tick:T});if(!P.amountSpecifiedRemaining.isZero()&&!F.eq(C)&&!F.isZero())throw Error("!limitOrderUnfilledAmountAfter.isZero()");break}}while(!0);P.liquidity=x}return{allTrade:!0,amountSpecifiedRemaining:$,amountCalculated:P.amountCalculated,feeAmount:P.lpFee.add(P.fundFee).add(P.protocolFee),sqrtPriceX64:P.sqrtPriceX64,liquidity:P.liquidity,tickCurrent:P.tick,accounts:[...p,...n.slice(0,m+1+(l?1:0)).map(T=>T.address)]}}var Ri=class{static tickSpacingIndexFromTick(e,t){return Math.floor(e/t)}},Do=class{static getDynamicFeeInfo({poolInfo:e}){if(!(e.dynamicFeeInfo.filterPeriod===0&&e.dynamicFeeInfo.decayPeriod===0&&e.dynamicFeeInfo.reductionFactor===0&&e.dynamicFeeInfo.dynamicFeeControl===0&&e.dynamicFeeInfo.maxVolatilityAccumulator===0&&e.dynamicFeeInfo.tickSpacingIndexReference===0&&e.dynamicFeeInfo.volatilityReference===0&&e.dynamicFeeInfo.volatilityAccumulator===0&&e.dynamicFeeInfo.lastUpdateTimestamp.isZero()))return e.dynamicFeeInfo}static updateReference({dynamicFeeInfo:e,tickSpacingIndex:t,currentTimestamp:n}){let o=n-e.lastUpdateTimestamp.toNumber();o<e.filterPeriod||(o<e.decayPeriod?(e.tickSpacingIndexReference=t,e.volatilityReference=Math.floor(e.volatilityAccumulator*e.reductionFactor/fc),e.lastUpdateTimestamp=new kt.default(n)):(e.tickSpacingIndexReference=t,e.volatilityReference=0,e.lastUpdateTimestamp=new kt.default(n)))}static updateVolatilityAccumulator({state:e,tickSpacingIndex:t}){let n=Math.abs(e.tickSpacingIndexReference-t),o=e.volatilityReference+n*Ii;e.volatilityAccumulator=Math.min(o,e.maxVolatilityAccumulator)}},Zt=class{static isFeeOnInput(e,t){switch(e){case 0:return!0;case 1:return t;case 2:return!t;default:return!0}}static isFeeOnTokenA(e,t){return e.feeOn===0?t:e.feeOn===1}static isOverflowDefaultTickarrayBitmap({tickSpacing:e,tickIndexs:t}){let{maxTickBoundary:n,minTickBoundary:o}=this.tickArrayStartIndexRange({tickSpacing:e});for(let i of t){let r=Te.getTickArrayStartIndex(i,e);if(r>=n||r<o)return!0}return!1}static tickArrayStartIndexRange({tickSpacing:e}){let t=Vn.maxTickInTickarrayBitmap(e),n=-t;return t>ln&&(t=Te.getTickArrayStartIndex(ln,e)+Te.tickCount(e)),n<cn&&(n=Te.getTickArrayStartIndex(cn,e)),{maxTickBoundary:t,minTickBoundary:n}}static async updatePoolRewardInfos({connection:e,apiPoolInfo:t,chainTime:n,poolLiquidity:o,rewardInfos:i}){var a,u,s;let r=[];for(let c=0;c<i.length;c++){let l=i[c],m=(s=(a=t.rewardDefaultInfos[c])==null?void 0:a.mint.programId)!=null?s:(u=await e.getAccountInfo(l.mint))==null?void 0:u.owner;if(m===void 0)throw Error("get new reward mint info error");let p=V(N({},l),{perSecond:vc(l.emissionsPerSecondX64),remainingRewards:void 0,tokenProgramId:new Vt.PublicKey(m)});if(p.mint.equals(Vt.PublicKey.default)||p.totalEmissioned.eq(Sn))continue;if(n<=p.openTime.toNumber()||o.eq($)){r.push(p);continue}let f=new kt.default(Math.min(p.endTime.toNumber(),n)),y=f.sub(p.lastUpdateTime);if(y.isZero()){r.push(p);continue}let b=$e(y,p.emissionsPerSecondX64,De),g=ut(y,p.emissionsPerSecondX64,o),A,k=p.totalEmissioned.add(b);if(k.lte(Sn))A=k;else{let P=Sn.sub(p.totalEmissioned);A=Sn,g=ut(P,De,o)}let h=p.growthGlobalX64.add(g);r.push(V(N({},p),{growthGlobalX64:h,totalEmissioned:A,lastUpdateTime:f}))}return r}},Pt=class{static getOutputAmountAndRemainAccounts(e,t,n,o,i,r,a){let u=o.toBase58()===e.mintA.address,s=Te.getTickArrayStartIndex(e.accInfo.tickCurrent,e.accInfo.tickSpacing),{allTrade:c,amountCalculated:l,feeAmount:m,sqrtPriceX64:p,accounts:f}=es({programId:e.programId,poolId:e.id,poolInfo:e.accInfo,tickArrays:Object.entries(n).map(y=>({address:y[1].address,value:y[1]})).filter(y=>u?y.value.startTickIndex<=s:y.value.startTickIndex>=s).sort((y,b)=>u?b.value.startTickIndex-y.value.startTickIndex:y.value.startTickIndex-b.value.startTickIndex),configInfo:e.ammConfig,tickarrayBitmapExtension:t,amountSpecified:i,sqrtPriceLimitX64:a!=null?a:$,zeroForOne:u,isBaseInput:!0,blockTimestamp:r,includeExtraTickArrays:!0});return{allTrade:c,expectedAmountOut:l,remainingAccounts:f,executionPrice:p,feeAmount:m}}static getInputAmountAndRemainAccounts(e,t,n,o,i,r,a){let u=o.toBase58()===e.mintB.address,s=Te.getTickArrayStartIndex(e.accInfo.tickCurrent,e.accInfo.tickSpacing),{allTrade:c,amountCalculated:l,feeAmount:m,sqrtPriceX64:p,accounts:f}=es({programId:e.programId,poolId:e.id,poolInfo:e.accInfo,tickArrays:Object.entries(n).map(y=>({address:new Vt.PublicKey(y[0]),value:y[1]})).filter(y=>u?y.value.startTickIndex<=s:y.value.startTickIndex>=s).sort((y,b)=>u?b.value.startTickIndex-y.value.startTickIndex:y.value.startTickIndex-b.value.startTickIndex),configInfo:e.ammConfig,tickarrayBitmapExtension:t,amountSpecified:i,sqrtPriceLimitX64:a!=null?a:$,zeroForOne:u,isBaseInput:!1,blockTimestamp:r,includeExtraTickArrays:!0});return{allTrade:c,expectedAmountIn:l,remainingAccounts:f,executionPrice:p,feeAmount:m}}static async fetchExBitmaps({connection:e,exBitmapAddress:t,batchRequest:n}){let o=await Ge(e,t.map(r=>({pubkey:r})),{batchRequest:n}),i={};for(let r of o)r.accountInfo!==null&&(i[r.pubkey.toString()]=Br.decode(r.accountInfo.data));return i}static async fetchMultiplePoolTickArrays({connection:e,poolKeys:t,batchRequest:n}){let o={},i=[];for(let u of t){let s=[...Vn.findTickArrayStartIndex({tickSpacing:u.tickSpacing,poolBitmap:u.tickArrayBitmap,tickArrayBitmap:u.exBitmapInfo,findInfo:{type:"zeroForOne",count:7,tickArrayCurrent:u.tickCurrent}}),...Vn.findTickArrayStartIndex({tickSpacing:u.tickSpacing,poolBitmap:u.tickArrayBitmap,tickArrayBitmap:u.exBitmapInfo,findInfo:{type:"oneForZero",count:7,tickArrayCurrent:u.tickCurrent}})];for(let c of s){let{publicKey:l}=Ee(u.programId,u.id,c);o[l.toString()]===void 0&&(i.push({pubkey:l}),o[l.toString()]=u.id)}}let r=await Ge(e,i,{batchRequest:n}),a={};for(let u of r){if(!u.accountInfo)continue;let s=o[u.pubkey.toString()];if(!s)continue;a[s.toString()]===void 0&&(a[s.toString()]={});let c=Vo.decode(u.accountInfo.data);a[s.toString()][c.startTickIndex]=V(N({},c),{address:u.pubkey})}return a}static computeAmountOut({poolInfo:e,tickarrayBitmapExtension:t,tickArrayCache:n,baseMint:o,epochInfo:i,amountIn:r,slippage:a,blockTimestamp:u,priceLimit:s=new xe.default(0)}){var O;let c,l=o.toBase58()===e.mintA.address,[m,p]=l?[e.mintA.extensions.feeConfig,e.mintB.extensions.feeConfig]:[e.mintB.extensions.feeConfig,e.mintA.extensions.feeConfig];s.equals(new xe.default(0))?c=l?St.add(new kt.default(1)):Kt.sub(new kt.default(1)):c=se.priceToSqrtPriceX64(s,e.mintA.decimals,e.mintB.decimals);let f=Tt(r,m,i,!1),{allTrade:y,expectedAmountOut:b,remainingAccounts:g,executionPrice:A,feeAmount:k}=Pt.getOutputAmountAndRemainAccounts(e,t,n,o,f.amount.sub((O=f.fee)!=null?O:$),u,c),h=Tt(b,p,i,!1),P=se.sqrtPriceX64ToPrice(A,e.mintA.decimals,e.mintB.decimals),T=l?P:new xe.default(1).div(P),I=b.mul(new kt.default(Math.floor((1-a)*1e10))).div(new kt.default(1e10)),x=Tt(I,p,i,!1),S=l?e.currentPrice:new xe.default(1).div(e.currentPrice),B=new xe.default(T).sub(S).abs(),R=S,L=new xt(new xe.default(B).mul(10**15).toFixed(0),new xe.default(R).mul(10**15).toFixed(0));return{allTrade:y,realAmountIn:f,amountOut:h,minAmountOut:x,expirationTime:En(f.expirationTime,h.expirationTime),currentPrice:e.currentPrice,executionPrice:T,priceImpact:L,fee:k,remainingAccounts:g,executionPriceX64:A}}static computeAmountOutFormat({poolInfo:e,tickarrayBitmapExtension:t,tickArrayCache:n,amountIn:o,tokenOut:i,slippage:r,epochInfo:a,blockTimestamp:u,catchLiquidityInsufficient:s=!1}){let c=i.address===e.mintB.address,[l,m]=c?[e.mintA,e.mintB]:[e.mintB,e.mintA],[p,f]=[new Ze(V(N({},l),{mint:l.address,isToken2022:l.programId===Li.TOKEN_2022_PROGRAM_ID.toBase58()})),new Ze(V(N({},m),{mint:m.address,isToken2022:m.programId===Li.TOKEN_2022_PROGRAM_ID.toBase58()}))],{allTrade:y,realAmountIn:b,amountOut:g,minAmountOut:A,expirationTime:k,currentPrice:h,executionPrice:P,priceImpact:T,fee:I,remainingAccounts:x,executionPriceX64:S}=Pt.computeAmountOut({poolInfo:e,tickarrayBitmapExtension:t,tickArrayCache:n,baseMint:new Vt.PublicKey(l.address),amountIn:o,slippage:r,epochInfo:a,catchLiquidityInsufficient:s,blockTimestamp:u}),B=V(N({},b),{amount:new _e(p,b.amount),fee:b.fee===void 0?void 0:new _e(p,b.fee)}),R=V(N({},g),{amount:new _e(f,g.amount),fee:g.fee===void 0?void 0:new _e(f,g.fee)}),L=V(N({},A),{amount:new _e(f,A.amount),fee:A.fee===void 0?void 0:new _e(f,A.fee)}),O=new qt({baseToken:p,denominator:new kt.default(10).pow(new kt.default(20+p.decimals)),quoteToken:f,numerator:h.mul(new xe.default(10**(20+f.decimals))).toFixed(0)}),C=new qt({baseToken:p,denominator:new kt.default(10).pow(new kt.default(20+p.decimals)),quoteToken:f,numerator:P.mul(new xe.default(10**(20+f.decimals))).toFixed(0)}),F=new _e(p,I);return{allTrade:y,realAmountIn:B,amountOut:R,minAmountOut:L,expirationTime:k,currentPrice:O,executionPrice:C,priceImpact:T,fee:F,remainingAccounts:x,executionPriceX64:S}}static computeAmountIn({poolInfo:e,tickarrayBitmapExtension:t,tickArrayCache:n,baseMint:o,epochInfo:i,amountOut:r,slippage:a,priceLimit:u=new xe.default(0),blockTimestamp:s}){var O;let c=o.toBase58()===e.mintA.address,l={[e.mintA.address]:e.mintA.extensions.feeConfig,[e.mintB.address]:e.mintB.extensions.feeConfig},m;u.equals(new xe.default(0))?m=c?Kt.sub(new kt.default(1)):St.add(new kt.default(1)):m=se.priceToSqrtPriceX64(u,e.mintA.decimals,e.mintB.decimals);let p=Tt(r,l[o.toString()],i,!0),{allTrade:f,expectedAmountIn:y,remainingAccounts:b,executionPrice:g,feeAmount:A}=Pt.getInputAmountAndRemainAccounts(e,t,n,o,p.amount.sub((O=p.fee)!=null?O:$),s,m),k=c?e.mintB.address:e.mintA.address,h=Tt(y,l[k],i,!1),P=se.sqrtPriceX64ToPrice(g,e.mintA.decimals,e.mintB.decimals),T=c?P:new xe.default(1).div(P),I=y.mul(new kt.default(Math.floor((1+a)*1e10))).div(new kt.default(1e10)),x=Tt(I,l[k],i,!0),S=c?e.currentPrice:new xe.default(1).div(e.currentPrice),B=new xe.default(T).sub(S).abs(),R=S,L=new xt(new xe.default(B).mul(10**15).toFixed(0),new xe.default(R).mul(10**15).toFixed(0));return{allTrade:f,amountIn:h,maxAmountIn:x,realAmountOut:p,expirationTime:En(h.expirationTime,p.expirationTime),currentPrice:e.currentPrice,executionPrice:T,priceImpact:L,fee:A,remainingAccounts:b}}static estimateAprsForPriceRangeMultiplier({poolInfo:e,aprType:t,positionTickLowerIndex:n,positionTickUpperIndex:o}){var f,y,b;let i=e[t],r=se.tickToPrice(n,e.mintA.decimals,e.mintB.decimals).toNumber(),a=se.tickToPrice(o,e.mintA.decimals,e.mintB.decimals).toNumber(),u=Math.max(r,i.priceMin),c=Math.min(a,i.priceMax)-u,l=a-r,m=i.priceMax-i.priceMin,p;return c<=0?p=0:l===c?p=m/c:m===c?p=c/l:p=c/m*(c/l),{feeApr:i.feeApr*p,rewardsApr:[((f=i.rewardApr[0])!=null?f:0)*p,((y=i.rewardApr[1])!=null?y:0)*p,((b=i.rewardApr[2])!=null?b:0)*p],apr:i.apr*p}}static estimateAprsForPriceRangeDelta({poolInfo:e,poolLiquidity:t,aprType:n,mintPrice:o,liquidity:i,positionTickLowerIndex:r,positionTickUpperIndex:a,chainTime:u}){let s=n==="day"?1:n==="week"?7:n==="month"?30:0,c=e[n],l=o[Ot(e.mintA.address).toString()],m=o[Ot(e.mintB.address).toString()],p=e.mintA.decimals,f=e.mintB.decimals;if(!c||!l||!m)return{feeApr:0,rewardsApr:[0,0,0],apr:0};let y=se.priceToSqrtPriceX64(new xe.default(e.price),e.mintA.decimals,e.mintB.decimals),b=se.getSqrtPriceAtTick(r),g=se.getSqrtPriceAtTick(a),{amountSlippageA:A,amountSlippageB:k}=pt.getAmountsFromLiquidityWithSlippage(y,b,g,t,!1,!1,0),{amountSlippageA:h,amountSlippageB:P}=pt.getAmountsFromLiquidityWithSlippage(y,b,g,i,!1,!1,0),T=new xe.default(A.toString()).div(new xe.default(10).pow(p)).mul(l.value).add(new xe.default(k.toString()).div(new xe.default(10).pow(f)).mul(m.value)),I=new xe.default(h.toString()).div(new xe.default(10).pow(p)).mul(l.value).add(new xe.default(P.toString()).div(new xe.default(10).pow(f)).mul(m.value)),x=new xe.default(1).div(T.add(I)),B=new xe.default(c.volumeFee).mul(365).div(s).mul(x).mul(100).toNumber(),R=3600*24*365,L=e.rewardDefaultInfos.map(O=>{var E,_;let C=O.mint.decimals,F=o[O.mint.address];return u<((E=O.startTime)!=null?E:0)||u>((_=O.endTime)!=null?_:0)||!O.perSecond||!F||C===void 0?0:new xe.default(F.value).mul(new xe.default(O.perSecond).mul(R)).div(new xe.default(10).pow(C)).mul(x).mul(100).toNumber()});return{feeApr:B,rewardsApr:L,apr:B+L.reduce((O,C)=>O+C,0)}}static async getLiquidityAmountOutFromAmountIn({poolInfo:e,inputA:t,tickLower:n,tickUpper:o,amount:i,slippage:r,add:a,epochInfo:u,amountHasFee:s}){var g,A;let c=se.priceToSqrtPriceX64(new xe.default(e.price),e.mintA.decimals,e.mintB.decimals),l=se.getSqrtPriceAtTick(n),m=se.getSqrtPriceAtTick(o),p=Tt(i,(g=e[t?"mintA":"mintB"].extensions)==null?void 0:g.feeConfig,u,!s),f=new kt.default(new xe.default(p.amount.sub((A=p.fee)!=null?A:$).toString()).toFixed(0)),y;if(c.lte(l))y=t?pt.getLiquidityFromAmountA(l,m,f):new kt.default(0);else if(c.lte(m)){let k=pt.getLiquidityFromAmountA(c,m,f),h=pt.getLiquidityFromAmountB(l,c,f);y=t?k:h}else y=t?new kt.default(0):pt.getLiquidityFromAmountB(l,m,f);let b=await Pt.getAmountsFromLiquidity({epochInfo:u,poolInfo:e,tickLower:n,tickUpper:o,liquidity:y,slippage:r,add:a});return{liquidity:y,amountA:t?p:b.amountA,amountB:t?b.amountB:p,amountSlippageA:t?p:b.amountSlippageA,amountSlippageB:t?b.amountSlippageB:p,expirationTime:b.expirationTime}}static async getAmountsFromLiquidity({epochInfo:e,poolInfo:t,tickLower:n,tickUpper:o,liquidity:i,slippage:r,add:a}){var b,g,A,k;let u=se.getSqrtPriceAtTick(n),s=se.getSqrtPriceAtTick(o),c=a?1+r:1-r,l=pt.getAmountsForLiquidity(se.priceToSqrtPriceX64(new xe.default(t.price),t.mintA.decimals,t.mintB.decimals),u,s,i,a),[m,p]=[Tt(l.amountA,(b=t.mintA.extensions)==null?void 0:b.feeConfig,e,!0),Tt(l.amountB,(g=t.mintB.extensions)==null?void 0:g.feeConfig,e,!0)],[f,y]=[Tt(l.amountA.muln(c),(A=t.mintA.extensions)==null?void 0:A.feeConfig,e,!0),Tt(l.amountB.muln(c),(k=t.mintB.extensions)==null?void 0:k.feeConfig,e,!0)];return{liquidity:i,amountA:m,amountB:p,amountSlippageA:f,amountSlippageB:y,expirationTime:En(m.expirationTime,p.expirationTime)}}static async fetchComputeMultipleClmmInfo({connection:e,poolList:t,rpcDataMap:n={}}){let o=t.filter(s=>!n[s.id]).map(s=>new Vt.PublicKey(s.id));(await It(e,o)).forEach((s,c)=>{!s||(n[o[c].toBase58()]=fo.decode(s.data))});let r=t.map(s=>He(new Vt.PublicKey(s.programId),new Vt.PublicKey(s.id)).publicKey),a=await Pt.fetchExBitmaps({connection:e,exBitmapAddress:r,batchRequest:!1}),u={};return t.reduce((s,c)=>V(N({},s),{[c.id]:V(N({accInfo:n[c.id]},n[c.id]),{id:new Vt.PublicKey(c.id),version:6,programId:new Vt.PublicKey(c.programId),mintA:c.mintA,mintB:c.mintB,ammConfig:V(N({},c.config),{id:new Vt.PublicKey(c.config.id),fundOwner:""}),currentPrice:new xe.default(c.price),exBitmapAccount:He(new Vt.PublicKey(c.programId),new Vt.PublicKey(c.id)).publicKey,exBitmapInfo:a[He(new Vt.PublicKey(c.programId),new Vt.PublicKey(c.id)).publicKey.toBase58()],startTime:n[c.id].startTime.toNumber(),rewardInfos:n[c.id].rewardInfos})}),{})}static async fetchComputeClmmInfo({connection:e,poolInfo:t,rpcData:n}){return(await this.fetchComputeMultipleClmmInfo({connection:e,rpcDataMap:n?{[t.id]:n}:void 0,poolList:[t]}))[t.id]}static async fetchTickArrayInfo({connection:e,programId:t,poolId:n,tick:o,tickSpacing:i}){let r=Te.getTickArrayStartIndex(o,i),a=Ee(t,n,r).publicKey,u=await e.getAccountInfo(a);if(!u)throw new Error(`tick array ${a.toBase58()} not found`);return Vo.decode(u.data)}static async fetchMultipleTickArrayInfo({connection:e,tickInfoList:t}){let n=t.map(i=>{let r=Te.getTickArrayStartIndex(i.tick,i.tickSpacing);return Ee(i.programId,i.poolId,r).publicKey});return(await It(e,n)).map(i=>i&&Vo.decode(i.data))}},ts={volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[]};function Ec(d,e){let t=e!=null?e:{};return V(N({},d),{type:"Concentrated",programId:d.programId.toString(),id:d.id.toString(),rewardDefaultInfos:d.rewardInfos.filter(n=>!n.mint.equals(Vt.PublicKey.default)).map(n=>{var o,i;return{mint:wt({address:n.mint.toBase58(),programId:Li.TOKEN_PROGRAM_ID.toBase58(),decimals:(o=t[n.mint.toBase58()].decimals)!=null?o:6}),perSecond:Number(n.emissionsPerSecondX64.divn(10**((i=t[n.mint.toBase58()].decimals)!=null?i:6)).toString()),startTime:n.openTime.toNumber(),endTime:n.endTime.toNumber()}}),rewardDefaultPoolInfos:"Clmm",price:d.currentPrice.toNumber(),mintAmountA:0,mintAmountB:0,feeRate:d.ammConfig.tradeFeeRate,openTime:d.startTime.toString(),tvl:0,day:ts,week:ts,month:ts,pooltype:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0,burnPercent:0,config:V(N({},d.ammConfig),{id:d.ammConfig.id.toString(),defaultRange:0,defaultRangePoint:[]}),hasDynamicFee:!1,feeOn:"",launchMigratePool:!1,tips:[]})}var qm=te(require("bn.js"));function Ct(d){let e=`global:${d}`;return Buffer.from(Uc.sha256.digest(e)).slice(0,8)}Ac.span;var Dc=Be("Raydium_Clmm"),Rt={createPool:Ct("create_pool"),createCustomizablePool:Ct("create_customizable_pool"),createPermissionedPool:Ct("create_permissioned_pool"),openPositionV2:Ct("open_position_v2"),openPositionWithToken22Nft:Ct("open_position_with_token22_nft"),closePosition:Ct("close_position"),increaseLiquidityV2:Ct("increase_liquidity_v2"),decreaseLiquidityV2:Ct("decrease_liquidity_v2"),initializeReward:Ct("initialize_reward"),setRewardParams:Ct("set_reward_params"),updateRewardInfos:Ct("update_reward_infos"),collectRemainingRewards:Ct("collect_remaining_rewards"),swapV2:Ct("swap_v2"),openLimitOrder:Ct("open_limit_order"),increaseLimitOrder:Ct("increase_limit_order"),decreaseLimitOrder:Ct("decrease_limit_order"),settleLimitOrder:Ct("settle_limit_order"),closeLimitOrder:Ct("close_limit_order")},Wc=[188,37,179,131,82,150,84,73],qc=[16,72,250,198,14,162,212,19],we=class{static createPoolInstruction(e,t,n,o,i,r,a,u,s,c,l,m,p,f){let y=v([ye("sqrtPriceX64"),w("startTime")]),b=[{pubkey:n,isSigner:!0,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:D.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:vt,isSigner:!1,isWritable:!1},...(f!=null?f:[]).map(k=>({pubkey:k,isSigner:!1,isWritable:!1}))],g=Buffer.alloc(y.span);y.encode({sqrtPriceX64:p,startTime:$},g);let A=Buffer.from([...Rt.createPool,...g]);return new D.TransactionInstruction({keys:b,programId:e,data:A})}static createCustomizablePoolInstruction(e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b){let g=v([ye("sqrtPriceX64"),W("collectFeeOn"),nt("enableDynamicFee")]),A=[{pubkey:n,isSigner:!0,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:D.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:vt,isSigner:!1,isWritable:!1},...y.map(P=>({pubkey:P,isSigner:!1,isWritable:!1})),...b?[{pubkey:b,isSigner:!1,isWritable:!1}]:[]],k=Buffer.alloc(g.span);g.encode({sqrtPriceX64:p,collectFeeOn:f,enableDynamicFee:b!==void 0},k);let h=Buffer.from([...Rt.createCustomizablePool,...k]);return new D.TransactionInstruction({keys:A,programId:e,data:h})}static createPermissionedPoolInstruction(e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A,k){let h=v([ye("sqrtPriceX64"),W("collectFeeOn"),nt("enableDynamicFee"),at("seedIndex")]),P=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:D.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:vt,isSigner:!1,isWritable:!1},...A.map(x=>({pubkey:x,isSigner:!1,isWritable:!1})),...k?[{pubkey:k,isSigner:!1,isWritable:!1}]:[]],T=Buffer.alloc(h.span);h.encode({sqrtPriceX64:y,collectFeeOn:b,enableDynamicFee:k!==void 0,seedIndex:g},T);let I=Buffer.from([...Rt.createPermissionedPool,...T]);return new D.TransactionInstruction({keys:P,programId:e,data:I})}static initializeRewardInstruction(e,t,n,o,i,r,a,u,s,c,l,m){let p=v([w("openTime"),w("endTime"),ye("emissionsPerSecondX64")]),f=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:D.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:vt,isSigner:!1,isWritable:!1}],y=Buffer.alloc(p.span);p.encode({openTime:c,endTime:l,emissionsPerSecondX64:m},y);let b=Buffer.from([...Rt.initializeReward,...y]);return new D.TransactionInstruction({keys:f,programId:e,data:b})}static updateRewardInfosInstruction(e,t){let n=[{pubkey:t,isSigner:!1,isWritable:!0}],o=Buffer.from([...Rt.updateRewardInfos]);return new D.TransactionInstruction({keys:n,programId:e,data:o})}static setRewardParamsInstruction(e,t,n,o,i,r,a,u,s,c,l,m){let p=v([W("rewardIndex"),ye("emissionsPerSecondX64"),w("openTime"),w("endTime")]),f=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0}],y=Buffer.alloc(p.span);p.encode({rewardIndex:s,emissionsPerSecondX64:m,openTime:c,endTime:l},y);let b=Buffer.from([...Rt.setRewardParams,...y]);return new D.TransactionInstruction({keys:f,programId:e,data:b})}static closePositionInstruction(e,t,n,o,i,r,a){let u=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:D.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:r?le.TOKEN_2022_PROGRAM_ID:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}];a&&u.push({pubkey:a,isSigner:!1,isWritable:!0});let s=Buffer.from([...Rt.closePosition]);return new D.TransactionInstruction({keys:u,programId:e,data:s})}static openPositionV2Instruction(e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A,k,h,P,T,I,x,S,B,R){let L=v([yt("tickLower"),yt("tickUpper"),yt("tickArrayLowerStart"),yt("tickArrayUpperStart"),ye("liquidity"),w("amountMaxA"),w("amountMaxB"),nt("withMetadata"),W("optionBaseFlag"),nt("baseFlag")]),O=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!0,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:y,isSigner:!1,isWritable:!0},{pubkey:vt,isSigner:!1,isWritable:!1},{pubkey:D.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:le.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:Bn,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:g,isSigner:!1,isWritable:!1},...R?[{pubkey:R,isSigner:!1,isWritable:!0}]:[]],C=Buffer.alloc(L.span);L.encode({tickLower:A,tickUpper:k,tickArrayLowerStart:h,tickArrayUpperStart:P,liquidity:T,amountMaxA:I,amountMaxB:x,withMetadata:S,optionBaseFlag:B!==null?1:0,baseFlag:B!=null?B:!1},C);let F=Buffer.from([...Rt.openPositionV2,...C]);return new D.TransactionInstruction({keys:O,programId:e,data:F})}static increaseLiquidityV2Instruction(e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A,k){let h=v([ye("liquidity"),w("amountMaxA"),w("amountMaxB"),W("optionBaseFlag"),nt("baseFlag")]),P=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},...k?[{pubkey:k,isSigner:!1,isWritable:!0}]:[]],T=Buffer.alloc(h.span);h.encode({liquidity:y,amountMaxA:b,amountMaxB:g,optionBaseFlag:A!==null?1:0,baseFlag:A!=null?A:!1},T);let I=Buffer.from([...Rt.increaseLiquidityV2,...T]);return new D.TransactionInstruction({keys:P,programId:e,data:I})}static decreaseLiquidityV2Instruction(e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A,k){let h=v([ye("liquidity"),w("amountMinA"),w("amountMinB")]),P=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:pn,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},...k?[{pubkey:k,isSigner:!1,isWritable:!0}]:[],...y.map(x=>[{pubkey:x.poolRewardVault,isSigner:!1,isWritable:!0},{pubkey:x.ownerRewardVault,isSigner:!1,isWritable:!0},{pubkey:x.rewardMint,isSigner:!1,isWritable:!1}]).flat()],T=Buffer.alloc(h.span);h.encode({liquidity:b,amountMinA:g,amountMinB:A},T);let I=Buffer.from([...Rt.decreaseLiquidityV2,...T]);return new D.TransactionInstruction({keys:P,programId:e,data:I})}static swapV2Instruction(e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g){let A=v([w("amount"),w("otherAmountThreshold"),ye("sqrtPriceLimitX64"),nt("isBaseInput")]),k=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:pn,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},...g?[{pubkey:g,isSigner:!1,isWritable:!0}]:[],...l.map(T=>({pubkey:T,isSigner:!1,isWritable:!0}))],h=Buffer.alloc(A.span);A.encode({amount:p,otherAmountThreshold:f,sqrtPriceLimitX64:y,isBaseInput:b},h);let P=Buffer.from([...Rt.swapV2,...h]);return new D.TransactionInstruction({keys:k,programId:e,data:P})}static collectRemainingRewardsInstruction(e,t,n,o,i,r,a){let u=v([W("rewardIndex")]),s=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:pn,isSigner:!1,isWritable:!1}],c=Buffer.alloc(u.span);u.encode({rewardIndex:a},c);let l=Buffer.from([...Rt.collectRemainingRewards,...c]);return new D.TransactionInstruction({keys:s,programId:e,data:l})}static openPositionWithToken22NftInstruction(e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A,k,h,P,T,I,x,S,B){let R=v([yt("tickLower"),yt("tickUpper"),yt("tickArrayLowerStart"),yt("tickArrayUpperStart"),ye("liquidity"),w("amountMaxA"),w("amountMaxB"),nt("withMetadata"),W("optionBaseFlag"),nt("baseFlag")]),L=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!0,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:vt,isSigner:!1,isWritable:!1},{pubkey:D.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:le.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:y,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},...B?[{pubkey:B,isSigner:!1,isWritable:!0}]:[]],O=Buffer.alloc(R.span);R.encode({tickLower:g,tickUpper:A,tickArrayLowerStart:k,tickArrayUpperStart:h,liquidity:P,amountMaxA:T,amountMaxB:I,withMetadata:x,optionBaseFlag:S!==null?1:0,baseFlag:S!=null?S:!1},O);let C=Buffer.from([...Rt.openPositionWithToken22Nft,...O]);return new D.TransactionInstruction({keys:L,programId:e,data:C})}static openLimitOrderInstruction(e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A){let k=v([W("nonceIndex"),nt("zeroForOne"),yt("tickIndex"),w("amount")]),h=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:D.SystemProgram.programId,isSigner:!1,isWritable:!1},...A?[{pubkey:A,isSigner:!1,isWritable:!0}]:[]],P=Buffer.alloc(k.span);k.encode({nonceIndex:f,zeroForOne:y,tickIndex:b,amount:g},P);let T=Buffer.from([...Rt.openLimitOrder,...P]);return new D.TransactionInstruction({keys:h,programId:e,data:T})}static increaseLimitOrderInstruction(e,t,n,o,i,r,a,u,s,c){let l=v([w("amount")]),m=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1}],p=Buffer.alloc(l.span);l.encode({amount:c},p);let f=Buffer.from([...Rt.increaseLimitOrder,...p]);return new D.TransactionInstruction({keys:m,programId:e,data:f})}static decreaseLimitOrderInstruction(e,t,n,o,i,r,a,u,s,c,l,m,p,f){let y=v([w("amount"),w("amountMin")]),b=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},...f?[{pubkey:f,isSigner:!1,isWritable:!0}]:[]],g=Buffer.alloc(y.span);y.encode({amount:m,amountMin:p},g);let A=Buffer.from([...Rt.decreaseLimitOrder,...g]);return new D.TransactionInstruction({keys:b,programId:e,data:A})}static settleLimitOrderInstruction(e,t,n,o,i,r,a,u,s){let c=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1}],l=Buffer.from([...Rt.settleLimitOrder]);return new D.TransactionInstruction({keys:c,programId:e,data:l})}static closeLimitOrderInstruction(e,t,n,o){let i=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0}],r=Buffer.from([...Rt.closeLimitOrder]);return new D.TransactionInstruction({keys:i,programId:e,data:r})}static createPoolInstructions(e){let{programId:t,owner:n,mintA:o,mintB:i,ammConfigId:r,initialPriceX64:a,extendMintAccount:u}=e,[s,c]=[new D.PublicKey(o.address),new D.PublicKey(i.address)],[l,m]=[new D.PublicKey(o.programId||le.TOKEN_PROGRAM_ID),new D.PublicKey(i.programId||le.TOKEN_PROGRAM_ID)],{publicKey:p}=Kc(t,r,s,c),{publicKey:f}=Za(t,p),{publicKey:y}=on(t,p,s),{publicKey:b}=on(t,p,c),g=He(t,p).publicKey,A=[this.createPoolInstruction(t,p,n,r,f,s,y,l,c,b,m,g,a,u)];return{signers:[],instructions:A,instructionTypes:[X.CreateAccount,X.ClmmCreatePool],address:{poolId:p,observationId:f,exBitmapAccount:g,mintA:s,mintB:c,mintAProgram:l,mintBProgram:m,mintAVault:y,mintBVault:b},lookupTableAddress:[]}}static createPermissionedPoolInstructions(e){let{programId:t,owner:n,mintA:o,mintB:i,ammConfigId:r,initialPriceX64:a,extendMintAccount:u,payer:s,seedIndex:c}=e,[l,m]=[new D.PublicKey(o.address),new D.PublicKey(i.address)],[p,f]=[new D.PublicKey(o.programId||le.TOKEN_PROGRAM_ID),new D.PublicKey(i.programId||le.TOKEN_PROGRAM_ID)],{publicKey:y}=Rc(t,r,l,m,c),{publicKey:b}=Cc(t,s),{publicKey:g}=Za(t,y),{publicKey:A}=on(t,y,l),{publicKey:k}=on(t,y,m),h=He(t,y).publicKey,P=[this.createPoolInstruction(t,y,n,r,g,l,A,p,m,k,f,h,a,u)];return{signers:[],instructions:P,instructionTypes:[X.CreateAccount,X.ClmmCreatePool],address:{poolId:y,observationId:g,exBitmapAccount:h,mintA:l,mintB:m,mintAProgram:p,mintBProgram:f,mintAVault:A,mintBVault:k,permission:b},lookupTableAddress:[]}}static async openPositionInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,tickLower:o,tickUpper:i,liquidity:r,amountMaxA:a,amountMaxB:u,base:s,withMetadata:c,getEphemeralSigners:l,nft2022:m}){let p=[],[f,y]=[new D.PublicKey(e.programId),new D.PublicKey(e.id)],b;if(l)b=new D.PublicKey((await l(1))[0]);else{let B=D.Keypair.generate();p.push(B),b=B.publicKey}let g=Te.getTickArrayStartIndex(o,e.config.tickSpacing),A=Te.getTickArrayStartIndex(i,e.config.tickSpacing),{publicKey:k}=Ee(f,y,g),{publicKey:h}=Ee(f,y,A),{publicKey:P}=m?ne(n.wallet,b,le.TOKEN_2022_PROGRAM_ID):ne(n.wallet,b,le.TOKEN_PROGRAM_ID),{publicKey:T}=_n(b),{publicKey:I}=rn(f,b),{publicKey:x}=gn(f,y,o,i),S=m?this.openPositionWithToken22NftInstruction(f,n.feePayer,y,n.wallet,b,P,x,k,h,I,n.tokenAccountA,n.tokenAccountB,new D.PublicKey(t.vault.A),new D.PublicKey(t.vault.B),new D.PublicKey(e.mintA.address),new D.PublicKey(e.mintB.address),o,i,g,A,r,a,u,c==="create",s&&s==="MintA",Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,A]})?He(f,y).publicKey:void 0):this.openPositionV2Instruction(f,n.feePayer,y,n.wallet,b,P,T,x,k,h,I,n.tokenAccountA,n.tokenAccountB,new D.PublicKey(t.vault.A),new D.PublicKey(t.vault.B),new D.PublicKey(e.mintA.address),new D.PublicKey(e.mintB.address),o,i,g,A,r,a,u,c==="create",null,Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,A]})?He(f,y).publicKey:void 0);return{signers:p,instructions:[S],instructionTypes:[X.ClmmOpenPosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[],address:{nftMint:b,tickArrayLower:k,tickArrayUpper:h,positionNftAccount:P,metadataAccount:T,personalPosition:I,protocolPosition:x}}}static async openPositionFromBaseInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,tickLower:o,tickUpper:i,base:r,baseAmount:a,otherAmountMax:u,liquidity:s,withMetadata:c,getEphemeralSigners:l,nft2022:m}){let p=[],[f,y]=[new D.PublicKey(e.programId),new D.PublicKey(e.id)],b;if(l)b=new D.PublicKey((await l(1))[0]);else{let B=D.Keypair.generate();p.push(B),b=B.publicKey}let g=Te.getTickArrayStartIndex(o,e.config.tickSpacing),A=Te.getTickArrayStartIndex(i,e.config.tickSpacing),{publicKey:k}=Ee(f,y,g),{publicKey:h}=Ee(f,y,A),{publicKey:P}=m?ne(n.wallet,b,le.TOKEN_2022_PROGRAM_ID):ne(n.wallet,b,le.TOKEN_PROGRAM_ID),{publicKey:T}=_n(b),{publicKey:I}=rn(f,b),{publicKey:x}=gn(f,y,o,i),S=m?this.openPositionWithToken22NftInstruction(f,n.feePayer,y,n.wallet,b,P,x,k,h,I,n.tokenAccountA,n.tokenAccountB,new D.PublicKey(t.vault.A),new D.PublicKey(t.vault.B),new D.PublicKey(e.mintA.address),new D.PublicKey(e.mintB.address),o,i,g,A,s,!r||r==="MintA"?a:u,!r||r==="MintA"?u:a,c==="create",r&&r==="MintA",Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,A]})?He(f,y).publicKey:void 0):this.openPositionV2Instruction(f,n.feePayer,y,n.wallet,b,P,T,x,k,h,I,n.tokenAccountA,n.tokenAccountB,new D.PublicKey(t.vault.A),new D.PublicKey(t.vault.B),new D.PublicKey(e.mintA.address),new D.PublicKey(e.mintB.address),o,i,g,A,$,r==="MintA"?a:u,r==="MintA"?u:a,c==="create",r==="MintA",Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,A]})?He(f,y).publicKey:void 0);return{address:{nftMint:b,tickArrayLower:k,tickArrayUpper:h,positionNftAccount:P,metadataAccount:T,personalPosition:I,protocolPosition:x},instructions:[S],signers:p,instructionTypes:[X.ClmmOpenPosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static async openPositionFromLiquidityInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,tickLower:o,tickUpper:i,liquidity:r,amountMaxA:a,amountMaxB:u,base:s,withMetadata:c,getEphemeralSigners:l,nft2022:m}){let p,f=[];if(l)p=new D.PublicKey((await l(1))[0]);else{let B=D.Keypair.generate();f.push(B),p=B.publicKey}let[y,b]=[new D.PublicKey(e.programId),new D.PublicKey(e.id)],g=Te.getTickArrayStartIndex(o,e.config.tickSpacing),A=Te.getTickArrayStartIndex(i,e.config.tickSpacing),{publicKey:k}=Ee(y,b,g),{publicKey:h}=Ee(y,b,A),{publicKey:P}=m?ne(n.wallet,p,le.TOKEN_2022_PROGRAM_ID):ne(n.wallet,p,le.TOKEN_PROGRAM_ID),{publicKey:T}=_n(p),{publicKey:I}=rn(y,p),{publicKey:x}=gn(y,b,o,i),S=m?this.openPositionWithToken22NftInstruction(y,n.wallet,b,n.wallet,p,P,x,k,h,I,n.tokenAccountA,n.tokenAccountB,new D.PublicKey(t.vault.A),new D.PublicKey(t.vault.B),new D.PublicKey(t.mintA.address),new D.PublicKey(t.mintB.address),o,i,g,A,r,a,u,c==="create",s&&s==="MintA",Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,A]})?He(y,b).publicKey:void 0):this.openPositionV2Instruction(y,n.wallet,b,n.wallet,p,P,T,x,k,h,I,n.tokenAccountA,n.tokenAccountB,new D.PublicKey(t.vault.A),new D.PublicKey(t.vault.B),new D.PublicKey(t.mintA.address),new D.PublicKey(t.mintB.address),o,i,g,A,r,a,u,c==="create",null,Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,A]})?He(y,b).publicKey:void 0);return{address:{nftMint:p,tickArrayLower:k,tickArrayUpper:h,positionNftAccount:P,metadataAccount:T,personalPosition:I,protocolPosition:x},instructions:[S],signers:f,instructionTypes:[X.ClmmOpenPosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static closePositionInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,ownerPosition:o,nft2022:i}){let r=new D.PublicKey(e.programId),a=i?ne(n.wallet,o.nftMint,le.TOKEN_2022_PROGRAM_ID).publicKey:ne(n.wallet,o.nftMint,le.TOKEN_PROGRAM_ID).publicKey,{publicKey:u}=rn(r,o.nftMint),s=[];return s.push(this.closePositionInstruction(r,n.wallet,o.nftMint,a,u,!!i,new D.PublicKey(e.id))),{address:{positionNftAccount:a,personalPosition:u},signers:[],instructions:s,instructionTypes:[X.ClmmClosePosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static increasePositionFromLiquidityInstructions({poolInfo:e,poolKeys:t,ownerPosition:n,ownerInfo:o,liquidity:i,amountMaxA:r,amountMaxB:a,nft2022:u}){let[s,c]=[new D.PublicKey(e.programId),new D.PublicKey(e.id)],l=Te.getTickArrayStartIndex(n.tickLower,e.config.tickSpacing),m=Te.getTickArrayStartIndex(n.tickUpper,e.config.tickSpacing),{publicKey:p}=Ee(s,c,l),{publicKey:f}=Ee(s,c,m),{publicKey:y}=u?ne(o.wallet,n.nftMint,le.TOKEN_2022_PROGRAM_ID):ne(o.wallet,n.nftMint,le.TOKEN_PROGRAM_ID),{publicKey:b}=rn(s,n.nftMint),{publicKey:g}=gn(s,c,n.tickLower,n.tickUpper),A=this.increaseLiquidityV2Instruction(s,o.wallet,y,b,c,g,p,f,o.tokenAccountA,o.tokenAccountB,new D.PublicKey(t.vault.A),new D.PublicKey(t.vault.B),new D.PublicKey(e.mintA.address),new D.PublicKey(e.mintB.address),i,r,a,null,Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[l,m]})?He(s,c).publicKey:void 0);return{address:{tickArrayLower:p,tickArrayUpper:f,positionNftAccount:y,personalPosition:b,protocolPosition:g},signers:[],instructions:[A],instructionTypes:[X.ClmmIncreasePosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static increasePositionFromBaseInstructions({poolInfo:e,poolKeys:t,ownerPosition:n,ownerInfo:o,base:i,baseAmount:r,otherAmountMax:a,nft2022:u}){let[s,c]=[new D.PublicKey(e.programId),new D.PublicKey(e.id)],l=Te.getTickArrayStartIndex(n.tickLower,e.config.tickSpacing),m=Te.getTickArrayStartIndex(n.tickUpper,e.config.tickSpacing),{publicKey:p}=Ee(s,c,l),{publicKey:f}=Ee(s,c,m),{publicKey:y}=u?ne(o.wallet,n.nftMint,le.TOKEN_2022_PROGRAM_ID):ne(o.wallet,n.nftMint,le.TOKEN_PROGRAM_ID),{publicKey:b}=rn(s,n.nftMint),{publicKey:g}=gn(s,c,n.tickLower,n.tickUpper);return{address:{tickArrayLower:p,tickArrayUpper:f,positionNftAccount:y,personalPosition:b,protocolPosition:g},instructions:[this.increaseLiquidityV2Instruction(s,o.wallet,y,b,c,g,p,f,o.tokenAccountA,o.tokenAccountB,new D.PublicKey(t.vault.A),new D.PublicKey(t.vault.B),new D.PublicKey(e.mintA.address),new D.PublicKey(e.mintB.address),$,i==="MintA"?r:a,i==="MintA"?a:r,i==="MintA",Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[l,m]})?He(s,c).publicKey:void 0)],signers:[],instructionTypes:[X.ClmmIncreasePosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static decreaseLiquidityInstructions({poolInfo:e,poolKeys:t,ownerPosition:n,ownerInfo:o,liquidity:i,amountMinA:r,amountMinB:a,programId:u,nft2022:s}){let[c,l]=[new D.PublicKey(e.programId),new D.PublicKey(e.id)],m=Te.getTickArrayStartIndex(n.tickLower,e.config.tickSpacing),p=Te.getTickArrayStartIndex(n.tickUpper,e.config.tickSpacing),{publicKey:f}=Ee(c,l,m),{publicKey:y}=Ee(c,l,p),{publicKey:b}=s?ne(o.wallet,n.nftMint,le.TOKEN_2022_PROGRAM_ID):ne(o.wallet,n.nftMint,u),{publicKey:g}=rn(c,n.nftMint),{publicKey:A}=gn(c,l,n.tickLower,n.tickUpper),k=new Map;for(let I=0;I<t.rewardInfos.length;I++)k.set(t.rewardInfos[I].mint.address,o.rewardAccounts[I]);let h=[];for(let I=0;I<t.rewardInfos.length;I++){let x=t.rewardInfos[I].mint.address,S=k.get(x);S&&h.push({poolRewardVault:new D.PublicKey(t.rewardInfos[I].vault),ownerRewardVault:S,rewardMint:new D.PublicKey(x)})}let P=[],T=this.decreaseLiquidityV2Instruction(c,o.wallet,b,g,l,A,f,y,o.tokenAccountA,o.tokenAccountB,new D.PublicKey(t.vault.A),new D.PublicKey(t.vault.B),new D.PublicKey(e.mintA.address),new D.PublicKey(e.mintB.address),h,i,r,a,Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[m,p]})?He(c,l).publicKey:void 0);return P.push(T),{address:{tickArrayLower:f,tickArrayUpper:y,positionNftAccount:b,personalPosition:g,protocolPosition:A},signers:[],instructions:P,instructionTypes:[X.ClmmDecreasePosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static makeSwapBaseInInstructions({poolInfo:e,poolKeys:t,observationId:n,ownerInfo:o,inputMint:i,amountIn:r,amountOutMin:a,sqrtPriceLimitX64:u,remainingAccounts:s}){let[c,l]=[new D.PublicKey(e.programId),new D.PublicKey(e.id)],[m,p]=[new D.PublicKey(t.vault.A),new D.PublicKey(t.vault.B)],[f,y]=[new D.PublicKey(e.mintA.address),new D.PublicKey(e.mintB.address)],b=e.mintA.address.toString()===i.toString(),g=[this.swapV2Instruction(c,o.wallet,l,new D.PublicKey(e.config.id),b?o.tokenAccountA:o.tokenAccountB,b?o.tokenAccountB:o.tokenAccountA,b?m:p,b?p:m,b?f:y,b?y:f,s,n,r,a,u,!0,He(c,l).publicKey)];return{signers:[],instructions:g,instructionTypes:[X.ClmmSwapBaseIn],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[],address:{}}}static makeSwapBaseOutInstructions({poolInfo:e,poolKeys:t,observationId:n,ownerInfo:o,outputMint:i,amountOut:r,amountInMax:a,sqrtPriceLimitX64:u,remainingAccounts:s}){let[c,l]=[new D.PublicKey(e.programId),new D.PublicKey(e.id)],[m,p]=[new D.PublicKey(t.vault.A),new D.PublicKey(t.vault.B)],[f,y]=[new D.PublicKey(e.mintA.address),new D.PublicKey(e.mintB.address)],b=e.mintB.address.toString()===i.toBase58(),g=[this.swapV2Instruction(c,o.wallet,l,new D.PublicKey(e.config.id),b?o.tokenAccountA:o.tokenAccountB,b?o.tokenAccountB:o.tokenAccountA,b?m:p,b?p:m,b?f:y,b?y:f,s,n,r,a,u,!1,He(c,l).publicKey)];return{signers:[],instructions:g,instructionTypes:[X.ClmmSwapBaseOut],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[],address:{}}}static initRewardInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,rewardInfo:o}){let[i,r]=[new D.PublicKey(e.programId),new D.PublicKey(e.id)],a=Lc(i,r,o.mint).publicKey,u=xi(i).publicKey,s=[this.initializeRewardInstruction(i,n.wallet,r,u,new D.PublicKey(e.config.id),n.tokenAccount,o.programId,o.mint,a,new Oi.default(o.openTime),new Oi.default(o.endTime),o.emissionsPerSecondX64)];return{address:{poolRewardVault:a,operationId:u},signers:[],instructions:s,instructionTypes:[X.ClmmInitReward],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static setRewardInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,rewardInfo:o}){let[i,r]=[new D.PublicKey(e.programId),new D.PublicKey(e.id)],a,u,s;for(let m=0;m<e.rewardDefaultInfos.length;m++)e.rewardDefaultInfos[m].mint.address===o.mint.toString()&&(a=m,u=new D.PublicKey(t.rewardInfos[m].vault),s=new D.PublicKey(t.rewardInfos[m].mint.address));(a===void 0||u===void 0)&&Dc.logWithError("reward mint check error","no reward mint",e.rewardDefaultInfos);let c=xi(i).publicKey,l=[this.setRewardParamsInstruction(i,n.wallet,r,c,new D.PublicKey(e.config.id),n.tokenAccount,u,s,a,new Oi.default(o.openTime),new Oi.default(o.endTime),o.emissionsPerSecondX64)];return{address:{rewardVault:u,operationId:c},signers:[],instructions:l,instructionTypes:[X.ClmmSetReward],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static collectRewardInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,rewardMint:o}){let[i,r]=[new D.PublicKey(e.programId),new D.PublicKey(e.id)],a,u;for(let c=0;c<e.rewardDefaultInfos.length;c++)e.rewardDefaultInfos[c].mint.address===o.toString()&&(a=c,u=new D.PublicKey(t.rewardInfos[c].vault));(a===void 0||u===void 0)&&Dc.logWithError("reward mint check error","no reward mint",e.rewardDefaultInfos);let s=[this.collectRemainingRewardsInstruction(i,n.wallet,r,n.tokenAccount,u,o,a)];return{address:{rewardVault:u},signers:[],instructions:s,instructionTypes:[X.ClmmCollectReward],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static async makeLockPositions({programId:e,authProgramId:t,poolProgramId:n,payer:o,wallet:i,nftMint:r,nft2022:a,getEphemeralSigners:u}){let s=[],c;if(u)c=new D.PublicKey((await u(1))[0]);else{let g=D.Keypair.generate();s.push(g),c=g.publicKey}let l=a?ne(i,r,le.TOKEN_2022_PROGRAM_ID).publicKey:ne(i,r,le.TOKEN_PROGRAM_ID).publicKey,{publicKey:m}=rn(n,r),p=Eo(e,c).publicKey,f=ne(i,c,le.TOKEN_PROGRAM_ID).publicKey,y=_n(c).publicKey,b=we.lockPositionInstructionV2({programId:e,auth:t,payer:o,positionOwner:i,lockOwner:i,positionNftAccount:l,positionId:m,lockPositionId:p,lockNftMint:c,lockNftAccount:f,metadataAccount:y,withMetadata:!0,nft2022:a,positionNftMint:r,authPositionNftAccount:ne(t,r,a?le.TOKEN_2022_PROGRAM_ID:le.TOKEN_PROGRAM_ID).publicKey,positionNftProgram:a?le.TOKEN_2022_PROGRAM_ID:le.TOKEN_PROGRAM_ID});return{address:{positionId:m,lockPositionId:p,lockNftAccount:f,lockNftMint:c,positionNftAccount:l,metadataAccount:y},instructions:[b],signers:s,instructionTypes:[X.ClmmLockPosition],lookupTableAddress:[]}}static lockPositionInstructionV2({programId:e,auth:t,payer:n,positionOwner:o,lockOwner:i,positionNftAccount:r,positionId:a,positionNftMint:u,authPositionNftAccount:s,positionNftProgram:c,lockPositionId:l,lockNftMint:m,lockNftAccount:p,metadataAccount:f,withMetadata:y}){let b=[{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!0},{pubkey:o,isSigner:!0,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!0,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:Bn,isSigner:!1,isWritable:!1},{pubkey:le.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:vt,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:D.SystemProgram.programId,isSigner:!1,isWritable:!1}],g=v([nt("withMetadata")]),A=Buffer.alloc(g.span);g.encode({withMetadata:y},A);let k=Buffer.from([...Wc,...A]);return new D.TransactionInstruction({keys:b,programId:e,data:k})}static lockPositionInstruction({programId:e,authProgramId:t,poolProgramId:n,owner:o,positionNft:i}){let{publicKey:r}=ne(o,i,le.TOKEN_PROGRAM_ID),{publicKey:a}=rn(n,i),u=[{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!0,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:ja(e,a).publicKey,isSigner:!1,isWritable:!0},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:D.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new D.TransactionInstruction({keys:u,programId:e,data:Buffer.from(Wc)})}static harvestLockPositionInstruction(e){let[t,n]=[new D.PublicKey(e.poolKeys.programId),new D.PublicKey(e.poolKeys.id)],o=Te.getTickArrayStartIndex(e.ownerPosition.tickLower,e.poolKeys.config.tickSpacing),i=Te.getTickArrayStartIndex(e.ownerPosition.tickUpper,e.poolKeys.config.tickSpacing),{publicKey:r}=Ee(t,n,o),{publicKey:a}=Ee(t,n,i),{publicKey:u}=ne(e.owner,e.ownerPosition.nftMint,le.TOKEN_PROGRAM_ID),{publicKey:s}=rn(t,e.ownerPosition.nftMint),{publicKey:c}=gn(t,n,e.ownerPosition.tickLower,e.ownerPosition.tickUpper),l=[];for(let f=0;f<e.poolKeys.rewardInfos.length;f++)l.push({poolRewardVault:new D.PublicKey(e.poolKeys.rewardInfos[f].vault),ownerRewardVault:e.ownerRewardAccounts[f],rewardMint:new D.PublicKey(e.poolKeys.rewardInfos[f].mint.address)});let m=[...l.map(f=>[{pubkey:f.poolRewardVault,isSigner:!1,isWritable:!0},{pubkey:f.ownerRewardVault,isSigner:!1,isWritable:!0},{pubkey:f.rewardMint,isSigner:!1,isWritable:!1}]).flat()],p=[{pubkey:e.authProgramId,isSigner:!1,isWritable:!1},{pubkey:ja(e.programId,s).publicKey,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:e.owner,isSigner:!0,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:new D.PublicKey(e.poolKeys.vault.A),isSigner:!1,isWritable:!0},{pubkey:new D.PublicKey(e.poolKeys.vault.B),isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:e.userVaultA,isSigner:!1,isWritable:!0},{pubkey:e.userVaultB,isSigner:!1,isWritable:!0},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:pn,isSigner:!1,isWritable:!1},{pubkey:new D.PublicKey(e.poolKeys.mintA.address),isSigner:!1,isWritable:!1},{pubkey:new D.PublicKey(e.poolKeys.mintB.address),isSigner:!1,isWritable:!1},...m];return new D.TransactionInstruction({keys:p,programId:e.programId,data:Buffer.from(qc)})}static harvestLockPositionInstructionV2({programId:e,auth:t,lockPositionId:n,clmmProgram:o,lockOwner:i,lockNftMint:r,lockNftAccount:a,positionNftAccount:u,positionId:s,poolId:c,protocolPosition:l,vaultA:m,vaultB:p,tickArrayLower:f,tickArrayUpper:y,userVaultA:b,userVaultB:g,mintA:A,mintB:k,rewardAccounts:h,exTickArrayBitmap:P}){let T=[...P?[{pubkey:P,isSigner:!1,isWritable:!0}]:[],...h.map(x=>[{pubkey:x.poolRewardVault,isSigner:!1,isWritable:!0},{pubkey:x.ownerRewardVault,isSigner:!1,isWritable:!0},{pubkey:x.rewardMint,isSigner:!1,isWritable:!1}]).flat()],I=[{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!0,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:y,isSigner:!1,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!0},{pubkey:g,isSigner:!1,isWritable:!0},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:pn,isSigner:!1,isWritable:!1},{pubkey:A,isSigner:!1,isWritable:!1},{pubkey:k,isSigner:!1,isWritable:!1},...T];return new D.TransactionInstruction({keys:I,programId:e,data:Buffer.from(qc)})}};var Ni=class extends ot{constructor(e){super(e)}async getClmmPoolKeys(e){return(await this.scope.api.fetchPoolKeysById({idList:[e]}))[0]}async createPool(e){var P;let{programId:t,owner:n=((P=this.scope.owner)==null?void 0:P.publicKey)||G.PublicKey.default,mint1:o,mint2:i,ammConfig:r,initialPrice:a,computeBudgetConfig:u,txVersion:s,txTipConfig:c,feePayer:l}=e,m=this.createTxBuilder(l),[p,f,y]=new ct.default(new G.PublicKey(o.address).toBuffer()).gt(new ct.default(new G.PublicKey(i.address).toBuffer()))?[i,o,new Kn.default(1).div(a)]:[o,i,a],b=se.priceToSqrtPriceX64(y,p.decimals,f.decimals),g=[],A=[];p.programId===We.TOKEN_2022_PROGRAM_ID.toBase58()&&A.push(bo(t,new G.PublicKey(p.address)).publicKey),f.programId===We.TOKEN_2022_PROGRAM_ID.toBase58()&&A.push(bo(t,new G.PublicKey(f.address)).publicKey),(await this.scope.connection.getMultipleAccountsInfo(A)).forEach((T,I)=>{T&&g.push(A[I])});let h=await we.createPoolInstructions({connection:this.scope.connection,programId:t,owner:n,mintA:p,mintB:f,ammConfigId:r.id,initialPriceX64:b,extendMintAccount:g});return m.addInstruction(h),m.addCustomComputeBudget(u),m.addTipInstruction(c),m.versionBuild({txVersion:s,extInfo:{address:V(N({},h.address),{observationId:h.address.observationId.toBase58(),exBitmapAccount:h.address.exBitmapAccount.toBase58(),programId:t.toString(),id:h.address.poolId.toString(),mintA:p,mintB:f,openTime:"0",vault:{A:h.address.mintAVault.toString(),B:h.address.mintBVault.toString()},rewardInfos:[],config:{id:r.id.toString(),index:r.index,protocolFeeRate:r.protocolFeeRate,tradeFeeRate:r.tradeFeeRate,tickSpacing:r.tickSpacing,fundFeeRate:r.fundFeeRate,description:r.description,defaultRange:0,defaultRangePoint:[]}}),mockPoolInfo:N({type:"Concentrated",rewardDefaultPoolInfos:"Clmm",id:h.address.poolId.toString(),mintA:p,mintB:f,feeRate:r.tradeFeeRate,openTime:"0",programId:t.toString(),price:y.toNumber(),config:{id:r.id.toString(),index:r.index,protocolFeeRate:r.protocolFeeRate,tradeFeeRate:r.tradeFeeRate,tickSpacing:r.tickSpacing,fundFeeRate:r.fundFeeRate,description:r.description,defaultRange:0,defaultRangePoint:[]},feeOn:"Both",hasDynamicFee:!1,launchMigratePool:!1,burnPercent:0,tips:[]},hr)}})}async createCustomizablePool(e){var S;let{programId:t,owner:n=((S=this.scope.owner)==null?void 0:S.publicKey)||G.PublicKey.default,mint1:o,mint2:i,initialPrice:r,ammConfig:a,collectFeeOn:u=0,dynamicFeeConfig:s,computeBudgetConfig:c,txVersion:l,txTipConfig:m,feePayer:p,addSupportMintExt:f}=e,y=this.createTxBuilder(p),[b,g,A]=new ct.default(new G.PublicKey(o.address).toBuffer()).gt(new ct.default(new G.PublicKey(i.address).toBuffer()))?[i,o,new Kn.default(1).div(r)]:[o,i,r],k=se.priceToSqrtPriceX64(A,b.decimals,g.decimals),h=[],P=[];f&&(b.programId===We.TOKEN_2022_PROGRAM_ID.toBase58()&&P.push(bo(t,new G.PublicKey(b.address)).publicKey),g.programId===We.TOKEN_2022_PROGRAM_ID.toBase58()&&P.push(bo(t,new G.PublicKey(g.address)).publicKey),(await this.scope.connection.getMultipleAccountsInfo(P)).forEach((R,L)=>{R&&h.push(P[L])}));let{address:T}=await we.createPoolInstructions({connection:this.scope.connection,programId:t,owner:n,mintA:b,mintB:g,ammConfigId:a.id,initialPriceX64:k,extendMintAccount:h}),I=[];if(s){if(!await this.scope.connection.getAccountInfo(s))throw new Error("Dynamic Fee Config not found. Run 03_admin_create_dynamic_fee_config.ts first.");console.log("Dynamic Fee Config",s.toBase58()),I.push({pubkey:s,isSigner:!1,isWritable:!1})}let x=we.createCustomizablePoolInstruction(t,T.poolId,this.scope.ownerPubKey,a.id,T.mintA,T.mintB,T.mintAVault,T.mintBVault,T.observationId,T.exBitmapAccount,T.mintAProgram,T.mintBProgram,k,u,[...h,...I.map(B=>B.pubkey)],s);return y.addInstruction({instructions:[x]}),y.addCustomComputeBudget(c),y.addTipInstruction(m),y.versionBuild({txVersion:l,extInfo:{address:V(N({},T),{observationId:T.observationId.toBase58(),exBitmapAccount:T.exBitmapAccount.toBase58(),programId:t.toString(),id:T.poolId.toString(),mintA:b,mintB:g,openTime:"0",vault:{A:T.mintAVault.toString(),B:T.mintBVault.toString()},rewardInfos:[],config:{id:a.id.toString(),index:a.index,protocolFeeRate:a.protocolFeeRate,tradeFeeRate:a.tradeFeeRate,tickSpacing:a.tickSpacing,fundFeeRate:a.fundFeeRate,description:a.description,defaultRange:0,defaultRangePoint:[]}}),mockPoolInfo:N({type:"Concentrated",rewardDefaultPoolInfos:"Clmm",id:T.poolId.toString(),mintA:b,mintB:g,feeRate:a.tradeFeeRate,openTime:"0",programId:t.toString(),price:A.toNumber(),config:{id:a.id.toString(),index:a.index,protocolFeeRate:a.protocolFeeRate,tradeFeeRate:a.tradeFeeRate,tickSpacing:a.tickSpacing,fundFeeRate:a.fundFeeRate,description:a.description,defaultRange:0,defaultRangePoint:[]},burnPercent:0,collectFeeOn:u,feeOn:u===0?"Both":u===1?"TokenA":"TokenB",hasDynamicFee:!!s,tips:[],launchMigratePool:!1},hr)}})}async createPermissionedPool(e){var R;let{programId:t,owner:n=((R=this.scope.owner)==null?void 0:R.publicKey)||G.PublicKey.default,mint1:o,mint2:i,initialPrice:r,ammConfig:a,collectFeeOn:u=0,dynamicFeeConfig:s,computeBudgetConfig:c,txVersion:l,txTipConfig:m,feePayer:p,addSupportMintExt:f}=e,y=this.createTxBuilder(p),[b,g,A]=new ct.default(new G.PublicKey(o.address).toBuffer()).gt(new ct.default(new G.PublicKey(i.address).toBuffer()))?[i,o,new Kn.default(1).div(r)]:[o,i,r],k=se.priceToSqrtPriceX64(A,b.decimals,g.decimals),h=[],P=[];f&&(b.programId===We.TOKEN_2022_PROGRAM_ID.toBase58()&&P.push(bo(t,new G.PublicKey(b.address)).publicKey),g.programId===We.TOKEN_2022_PROGRAM_ID.toBase58()&&P.push(bo(t,new G.PublicKey(g.address)).publicKey),(await this.scope.connection.getMultipleAccountsInfo(P)).forEach((O,C)=>{O&&h.push(P[C])}));let T=p!=null?p:this.scope.ownerPubKey,I=Math.floor(Math.random()*Math.pow(2,16))+1,{address:x}=await we.createPermissionedPoolInstructions({connection:this.scope.connection,programId:t,owner:n,mintA:b,mintB:g,ammConfigId:a.id,initialPriceX64:k,extendMintAccount:h,payer:T,seedIndex:I}),S=[];if(s){if(!await this.scope.connection.getAccountInfo(s))throw new Error("Dynamic Fee Config not found. Run 03_admin_create_dynamic_fee_config.ts first.");console.log("Dynamic Fee Config",s.toBase58()),S.push({pubkey:s,isSigner:!1,isWritable:!1})}let B=we.createPermissionedPoolInstruction(t,T,T,x.permission,a.id,x.poolId,x.mintA,x.mintB,x.mintAVault,x.mintBVault,x.observationId,x.exBitmapAccount,x.mintAProgram,x.mintBProgram,k,u,I,[...h,...S.map(L=>L.pubkey)],s);return y.addInstruction({instructions:[B]}),y.addCustomComputeBudget(c),y.addTipInstruction(m),y.versionBuild({txVersion:l,extInfo:{address:V(N({},x),{observationId:x.observationId.toBase58(),exBitmapAccount:x.exBitmapAccount.toBase58(),programId:t.toString(),id:x.poolId.toString(),mintA:b,mintB:g,openTime:"0",vault:{A:x.mintAVault.toString(),B:x.mintBVault.toString()},rewardInfos:[],config:{id:a.id.toString(),index:a.index,protocolFeeRate:a.protocolFeeRate,tradeFeeRate:a.tradeFeeRate,tickSpacing:a.tickSpacing,fundFeeRate:a.fundFeeRate,description:a.description,defaultRange:0,defaultRangePoint:[]}}),mockPoolInfo:N({type:"Concentrated",rewardDefaultPoolInfos:"Clmm",id:x.poolId.toString(),mintA:b,mintB:g,feeRate:a.tradeFeeRate,openTime:"0",programId:t.toString(),price:A.toNumber(),config:{id:a.id.toString(),index:a.index,protocolFeeRate:a.protocolFeeRate,tradeFeeRate:a.tradeFeeRate,tickSpacing:a.tickSpacing,fundFeeRate:a.fundFeeRate,description:a.description,defaultRange:0,defaultRangePoint:[]},burnPercent:0,collectFeeOn:u,feeOn:u===0?"Both":u===1?"TokenA":"TokenB",hasDynamicFee:!!s,tips:[],launchMigratePool:!1},hr)}})}async openPositionFromBase({poolInfo:e,poolKeys:t,ownerInfo:n,tickLower:o,tickUpper:i,base:r=null,baseAmount:a,otherAmountMax:u,liquidity:s=new ct.default(0),nft2022:c,associatedOnly:l=!0,checkCreateATAOwner:m=!1,withMetadata:p="create",getEphemeralSigners:f,computeBudgetConfig:y,txTipConfig:b,txVersion:g,feePayer:A}){this.scope.availability.addConcentratedPosition===!1&&this.logAndCreateError("add position feature disabled in your region"),this.scope.checkOwner();let k=this.createTxBuilder(A),h=null,P=null,T=n.useSOLBalance&&e.mintA.address===Z.toString(),I=n.useSOLBalance&&e.mintB.address===Z.toString(),[x,S]=r==="MintA"?[a,u]:[u,a],{account:B,instructionParams:R}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintA.programId,mint:new G.PublicKey(e.mintA.address),owner:this.scope.ownerPubKey,createInfo:T||x.isZero()?{payer:this.scope.ownerPubKey,amount:x}:void 0,skipCloseAccount:!T,notUseTokenAccount:T,associatedOnly:T?!1:l,checkCreateATAOwner:m});B&&(h=B),k.addInstruction(R||{});let{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintB.programId,mint:new G.PublicKey(e.mintB.address),owner:this.scope.ownerPubKey,createInfo:I||S.isZero()?{payer:this.scope.ownerPubKey,amount:S}:void 0,skipCloseAccount:!I,notUseTokenAccount:I,associatedOnly:I?!1:l,checkCreateATAOwner:m});L&&(P=L),k.addInstruction(O||{}),(!h||!P)&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",{ownerTokenAccountA:h==null?void 0:h.toBase58(),ownerTokenAccountB:P==null?void 0:P.toBase58()});let C=t!=null?t:await this.getClmmPoolKeys(e.id.toString()),F=await we.openPositionFromBaseInstructions({poolInfo:e,poolKeys:C,ownerInfo:V(N({},n),{feePayer:this.scope.ownerPubKey,wallet:this.scope.ownerPubKey,tokenAccountA:h,tokenAccountB:P}),tickLower:o,tickUpper:i,base:r,baseAmount:a,otherAmountMax:u,liquidity:s,withMetadata:p,getEphemeralSigners:f,nft2022:c});return k.addInstruction(F),k.addCustomComputeBudget(y),k.addTipInstruction(b),k.versionBuild({txVersion:g,extInfo:N({},F.address)})}async openPositionFromLiquidity({poolInfo:e,poolKeys:t,ownerInfo:n,amountMaxA:o,amountMaxB:i,base:r=null,tickLower:a,tickUpper:u,liquidity:s,associatedOnly:c=!0,checkCreateATAOwner:l=!1,withMetadata:m="create",txVersion:p,computeBudgetConfig:f,txTipConfig:y,getEphemeralSigners:b,nft2022:g,feePayer:A}){this.scope.availability.createConcentratedPosition===!1&&this.logAndCreateError("open position feature disabled in your region");let k=this.createTxBuilder(A),h=null,P=null,T=n.useSOLBalance&&e.mintA.address===Z.toBase58(),I=n.useSOLBalance&&e.mintB.address===Z.toBase58(),{account:x,instructionParams:S}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintA.programId,mint:new G.PublicKey(e.mintA.address),owner:this.scope.ownerPubKey,createInfo:T||o.isZero()?{payer:this.scope.ownerPubKey,amount:o}:void 0,skipCloseAccount:!T,notUseTokenAccount:T,associatedOnly:T?!1:c,checkCreateATAOwner:l});x&&(h=x),k.addInstruction(S||{});let{account:B,instructionParams:R}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintB.programId,mint:new G.PublicKey(e.mintB.address),owner:this.scope.ownerPubKey,createInfo:I||i.isZero()?{payer:this.scope.ownerPubKey,amount:i}:void 0,skipCloseAccount:!I,notUseTokenAccount:I,associatedOnly:I?!1:c,checkCreateATAOwner:l});B&&(P=B),k.addInstruction(R||{}),(h===void 0||P===void 0)&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",this.scope.account.tokenAccounts);let L=t||await this.getClmmPoolKeys(e.id.toString()),O=await we.openPositionFromLiquidityInstructions({poolInfo:e,poolKeys:L,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:h,tokenAccountB:P},tickLower:a,tickUpper:u,liquidity:s,amountMaxA:o,amountMaxB:i,base:r,withMetadata:m,getEphemeralSigners:b,nft2022:g});return k.addInstruction(O),k.addCustomComputeBudget(f),k.addTipInstruction(y),k.versionBuild({txVersion:p,extInfo:{address:O.address}})}async increasePositionFromLiquidity(e){var B;let{poolInfo:t,poolKeys:n,ownerPosition:o,amountMaxA:i,amountMaxB:r,liquidity:a,ownerInfo:u,associatedOnly:s=!0,checkCreateATAOwner:c=!1,computeBudgetConfig:l,txTipConfig:m,txVersion:p,feePayer:f}=e,y=this.createTxBuilder(f),b,g,A=u.useSOLBalance&&t.mintA.address===Z.toString(),k=u.useSOLBalance&&t.mintB.address===Z.toString(),{account:h,instructionParams:P}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintA.programId,mint:new G.PublicKey(t.mintA.address),notUseTokenAccount:A,owner:this.scope.ownerPubKey,createInfo:A||i.isZero()?{payer:this.scope.ownerPubKey,amount:i}:void 0,skipCloseAccount:!A,associatedOnly:A?!1:s,checkCreateATAOwner:c});h&&(b=h),y.addInstruction(P||{});let{account:T,instructionParams:I}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintB.programId,mint:new G.PublicKey(t.mintB.address),owner:this.scope.ownerPubKey,createInfo:k||r.isZero()?{payer:this.scope.ownerPubKey,amount:r}:void 0,notUseTokenAccount:k,skipCloseAccount:!k,associatedOnly:k?!1:s,checkCreateATAOwner:c});T&&(g=T),y.addInstruction(I||{}),!b&&!g&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",this.scope.account.tokenAccounts);let x=n!=null?n:await this.getClmmPoolKeys(t.id),S=we.increasePositionFromLiquidityInstructions({poolInfo:t,poolKeys:x,ownerPosition:o,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:b,tokenAccountB:g},liquidity:a,amountMaxA:i,amountMaxB:r,nft2022:(B=await this.scope.connection.getAccountInfo(o.nftMint))==null?void 0:B.owner.equals(We.TOKEN_2022_PROGRAM_ID)});return y.addInstruction(S),y.addCustomComputeBudget(l),y.addTipInstruction(m),y.versionBuild({txVersion:p,extInfo:{address:S.address}})}async increasePositionFromBase(e){var S;let{poolInfo:t,ownerPosition:n,base:o,baseAmount:i,otherAmountMax:r,ownerInfo:a,associatedOnly:u=!0,checkCreateATAOwner:s=!1,computeBudgetConfig:c,txTipConfig:l,txVersion:m,feePayer:p}=e,f=this.createTxBuilder(p),y,b,g=a.useSOLBalance&&t.mintA.address===Z.toString(),A=a.useSOLBalance&&t.mintB.address===Z.toString(),{account:k,instructionParams:h}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintA.programId,mint:new G.PublicKey(t.mintA.address),notUseTokenAccount:g,owner:this.scope.ownerPubKey,createInfo:g||(o==="MintA"?i:r).isZero()?{payer:this.scope.ownerPubKey,amount:o==="MintA"?i:r}:void 0,skipCloseAccount:!g,associatedOnly:g?!1:u,checkCreateATAOwner:s});k&&(y=k),f.addInstruction(h||{});let{account:P,instructionParams:T}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintB.programId,mint:new G.PublicKey(t.mintB.address),owner:this.scope.ownerPubKey,createInfo:A||(o==="MintA"?r:i).isZero()?{payer:this.scope.ownerPubKey,amount:o==="MintA"?r:i}:void 0,notUseTokenAccount:A,skipCloseAccount:!A,associatedOnly:A?!1:u,checkCreateATAOwner:s});P&&(b=P),f.addInstruction(T||{}),!y&&!b&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",this.scope.account.tokenAccounts);let I=await this.getClmmPoolKeys(t.id),x=we.increasePositionFromBaseInstructions({poolInfo:t,poolKeys:I,ownerPosition:n,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:y,tokenAccountB:b},base:o,baseAmount:i,otherAmountMax:r,nft2022:(S=await this.scope.connection.getAccountInfo(n.nftMint))==null?void 0:S.owner.equals(We.TOKEN_2022_PROGRAM_ID)});return f.addInstruction(x),f.addCustomComputeBudget(c),f.addTipInstruction(l),f.versionBuild({txVersion:m,extInfo:{address:x.address}})}async decreaseLiquidity(e){var O;let{poolInfo:t,poolKeys:n,ownerPosition:o,ownerInfo:i,amountMinA:r,amountMinB:a,liquidity:u,associatedOnly:s=!0,checkCreateATAOwner:c=!1,computeBudgetConfig:l,txTipConfig:m,txVersion:p,feePayer:f}=e;this.scope.availability.removeConcentratedPosition===!1&&this.logAndCreateError("remove position feature disabled in your region");let y=this.createTxBuilder(f),b=i.useSOLBalance&&t.mintA.address===Z.toString(),g=i.useSOLBalance&&t.mintB.address===Z.toString(),A,k,{account:h,instructionParams:P}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintA.programId,mint:new G.PublicKey(t.mintA.address),notUseTokenAccount:b,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!b,associatedOnly:b?!1:s,checkCreateATAOwner:c});A=h,P&&y.addInstruction(P);let{account:T,instructionParams:I}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintB.programId,mint:new G.PublicKey(t.mintB.address),notUseTokenAccount:g,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!g,associatedOnly:g?!1:s,checkCreateATAOwner:c});k=T,I&&y.addInstruction(I);let x=n!=null?n:await this.getClmmPoolKeys(t.id),S=[];for(let C of x.rewardInfos){let F=i.useSOLBalance&&C.mint.address===Z.toString(),E;if(C.mint.address===t.mintA.address)E=A;else if(C.mint.address===t.mintB.address)E=k;else{let{account:_,instructionParams:z}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new G.PublicKey(C.mint.programId),mint:new G.PublicKey(C.mint.address),notUseTokenAccount:F,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!F,associatedOnly:F?!1:s,checkCreateATAOwner:c});E=_,z&&y.addInstruction(z)}S.push(E)}!A&&!k&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",this.scope.account.tokenAccountRawInfos);let B=(O=await this.scope.connection.getAccountInfo(o.nftMint))==null?void 0:O.owner.equals(We.TOKEN_2022_PROGRAM_ID),R=await we.decreaseLiquidityInstructions({poolInfo:t,poolKeys:x,ownerPosition:o,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:A,tokenAccountB:k,rewardAccounts:S},liquidity:u,amountMinA:r,amountMinB:a,nft2022:B});y.addInstruction({instructions:R.instructions,instructionTypes:[X.ClmmDecreasePosition]});let L=N({},R.address);if(i.closePosition){let C=await we.closePositionInstructions({poolInfo:t,poolKeys:x,ownerInfo:{wallet:this.scope.ownerPubKey},ownerPosition:o,nft2022:B});y.addInstruction({endInstructions:C.instructions,endInstructionTypes:C.instructionTypes}),L=N(N({},L),C.address)}return y.addCustomComputeBudget(l),y.addTipInstruction(m),y.versionBuild({txVersion:p,extInfo:{address:L}})}async lockPosition(e){var f;let{programId:t=mi,authProgramId:n=pr,poolProgramId:o=Fn,ownerPosition:i,payer:r,computeBudgetConfig:a,txTipConfig:u,txVersion:s,getEphemeralSigners:c,feePayer:l}=e,m=this.createTxBuilder(l),p=await we.makeLockPositions({programId:t,authProgramId:n,poolProgramId:o,wallet:this.scope.ownerPubKey,payer:r!=null?r:this.scope.ownerPubKey,nftMint:i.nftMint,getEphemeralSigners:c,nft2022:(f=await this.scope.connection.getAccountInfo(i.nftMint))==null?void 0:f.owner.equals(We.TOKEN_2022_PROGRAM_ID)});return m.addInstruction(p),m.addCustomComputeBudget(a),m.addTipInstruction(u),m.versionBuild({txVersion:s,extInfo:p.address})}async harvestLockPosition(e){let{programId:t=mi,authProgramId:n=pr,clmmProgram:o=Fn,poolKeys:i,lockData:r,ownerInfo:a={useSOLBalance:!0},associatedOnly:u=!0,checkCreateATAOwner:s=!1,computeBudgetConfig:c,txTipConfig:l,txVersion:m,feePayer:p}=e,f=i||await this.getClmmPoolKeys(r.poolId.toString()),y=this.createTxBuilder(p),b=await this.scope.connection.getAccountInfo(r.positionId);b||this.logger.logWithError("position not found",r.positionId);let g=Ir.decode(b.data),A=a.useSOLBalance&&f.mintA.address===Z.toString(),k=a.useSOLBalance&&f.mintB.address===Z.toString(),h,P,{account:T,instructionParams:I}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:f.mintA.programId,mint:new G.PublicKey(f.mintA.address),notUseTokenAccount:A,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!A,associatedOnly:A?!1:u,checkCreateATAOwner:s});h=T,I&&y.addInstruction(I);let{account:x,instructionParams:S}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:f.mintB.programId,mint:new G.PublicKey(f.mintB.address),notUseTokenAccount:k,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!k,associatedOnly:k?!1:u,checkCreateATAOwner:s});P=x,S&&y.addInstruction(S);let B={},R=[];for(let J of f.rewardInfos){let ie=a.useSOLBalance&&J.mint.address===Z.toString(),Q=B[J.mint.address];if(!Q){let{account:ge,instructionParams:re}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new G.PublicKey(J.mint.programId),mint:new G.PublicKey(J.mint.address),notUseTokenAccount:ie,owner:this.scope.ownerPubKey,skipCloseAccount:!ie,createInfo:{payer:this.scope.ownerPubKey,amount:0},associatedOnly:ie?!1:u});Q=ge,re&&y.addInstruction(re)}B[J.mint.address]=Q,R.push(Q)}let L=Eo(t,r.lockNftMint).publicKey,O=ne(this.scope.ownerPubKey,r.lockNftMint,We.TOKEN_PROGRAM_ID).publicKey,C=Te.getTickArrayStartIndex(g.tickLower,f.config.tickSpacing),F=Te.getTickArrayStartIndex(g.tickUpper,f.config.tickSpacing),{publicKey:E}=Ee(new G.PublicKey(f.programId),r.poolId,C),{publicKey:_}=Ee(new G.PublicKey(f.programId),r.poolId,F),{publicKey:z}=gn(new G.PublicKey(f.programId),r.poolId,g.tickLower,g.tickUpper),H=[];for(let J=0;J<f.rewardInfos.length;J++){let ie=f.rewardInfos[J].mint.address,Q=B[ie];Q&&H.push({poolRewardVault:new G.PublicKey(f.rewardInfos[J].vault),ownerRewardVault:Q,rewardMint:new G.PublicKey(ie)})}let Y=await we.harvestLockPositionInstructionV2({programId:t,auth:n,lockPositionId:L,clmmProgram:o,lockOwner:this.scope.ownerPubKey,lockNftMint:r.lockNftMint,lockNftAccount:O,positionNftAccount:r.nftAccount,positionId:r.positionId,poolId:r.poolId,protocolPosition:z,vaultA:new G.PublicKey(f.vault.A),vaultB:new G.PublicKey(f.vault.B),tickArrayLower:E,tickArrayUpper:_,userVaultA:h,userVaultB:P,mintA:new G.PublicKey(f.mintA.address),mintB:new G.PublicKey(f.mintB.address),rewardAccounts:H,exTickArrayBitmap:He(o,r.poolId).publicKey});return y.addInstruction({instructions:[Y],instructionTypes:[X.ClmmHarvestLockPosition]}),y.addCustomComputeBudget(c),y.addTipInstruction(l),y.versionBuild({txVersion:m})}async closePosition({poolInfo:e,poolKeys:t,ownerPosition:n,txVersion:o,computeBudgetConfig:i,txTipConfig:r,feePayer:a}){var l;this.scope.availability.removeConcentratedPosition===!1&&this.logAndCreateError("remove position feature disabled in your region");let u=this.createTxBuilder(a),s=t!=null?t:await this.getClmmPoolKeys(e.id),c=we.closePositionInstructions({poolInfo:e,poolKeys:s,ownerInfo:{wallet:this.scope.ownerPubKey},ownerPosition:n,nft2022:(l=await this.scope.connection.getAccountInfo(n.nftMint))==null?void 0:l.owner.equals(We.TOKEN_2022_PROGRAM_ID)});return u.addCustomComputeBudget(i),u.addTipInstruction(r),u.addInstruction(c).versionBuild({txVersion:o,extInfo:{address:c.address}})}async initReward({poolInfo:e,ownerInfo:t,rewardInfo:n,associatedOnly:o=!0,checkCreateATAOwner:i=!1,computeBudgetConfig:r,txVersion:a,feePayer:u}){n.endTime<=n.openTime&&this.logAndCreateError("reward time error","rewardInfo",n);let s=this.createTxBuilder(u),c=t.useSOLBalance&&n.mint.address.toString()===Z.toString(),l=n.perSecond.mul(n.endTime-n.openTime),{account:m,instructionParams:p}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new G.PublicKey(n.mint.programId),mint:new G.PublicKey(n.mint.address),notUseTokenAccount:!!c,skipCloseAccount:!c,owner:this.scope.ownerPubKey,createInfo:c?{payer:t.feePayer||this.scope.ownerPubKey,amount:new ct.default(new Kn.default(l.toFixed(0)).gte(l)?l.toFixed(0):l.add(1).toFixed(0))}:void 0,associatedOnly:c?!1:o,checkCreateATAOwner:i});p&&s.addInstruction(p),m||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos);let f=await this.getClmmPoolKeys(e.id),y=we.initRewardInstructions({poolInfo:e,poolKeys:f,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:m},rewardInfo:{programId:new G.PublicKey(n.mint.programId),mint:new G.PublicKey(n.mint.address),openTime:n.openTime,endTime:n.endTime,emissionsPerSecondX64:go(n.perSecond)}});return s.addInstruction(y),s.addCustomComputeBudget(r),s.versionBuild({txVersion:a,extInfo:{address:y.address}})}async initRewards({poolInfo:e,poolKeys:t,ownerInfo:n,rewardInfos:o,associatedOnly:i=!0,checkCreateATAOwner:r=!1,computeBudgetConfig:a,txTipConfig:u,txVersion:s,feePayer:c}){for(let p of o)p.endTime<=p.openTime&&this.logAndCreateError("reward time error","rewardInfo",p);let l=this.createTxBuilder(c),m={};for(let p of o){let f=n.useSOLBalance&&p.mint.address===Z.toString(),y=p.perSecond.mul(p.endTime-p.openTime),{account:b,instructionParams:g}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new G.PublicKey(p.mint.programId),mint:new G.PublicKey(p.mint.address),notUseTokenAccount:!!f,skipCloseAccount:!f,owner:this.scope.ownerPubKey,createInfo:f?{payer:n.feePayer||this.scope.ownerPubKey,amount:new ct.default(new Kn.default(y.toFixed(0)).gte(y)?y.toFixed(0):y.add(1).toFixed(0))}:void 0,associatedOnly:f?!1:i,checkCreateATAOwner:r});g&&l.addInstruction(g),b||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos);let A=t!=null?t:await this.getClmmPoolKeys(e.id),k=we.initRewardInstructions({poolInfo:e,poolKeys:A,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:b},rewardInfo:{programId:new G.PublicKey(p.mint.programId),mint:new G.PublicKey(p.mint.address),openTime:p.openTime,endTime:p.endTime,emissionsPerSecondX64:go(p.perSecond)}});m=N(N({},m),k.address),l.addInstruction(k)}return l.addCustomComputeBudget(a),l.addTipInstruction(u),l.versionBuild({txVersion:s,extInfo:{address:m}})}async setReward({poolInfo:e,ownerInfo:t,rewardInfo:n,associatedOnly:o=!0,checkCreateATAOwner:i=!1,computeBudgetConfig:r,txTipConfig:a,txVersion:u,feePayer:s}){n.endTime<=n.openTime&&this.logAndCreateError("reward time error","rewardInfo",n);let c=this.createTxBuilder(s),l=t.useSOLBalance&&n.mint.equals(Z),{account:m,instructionParams:p}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n.programId,mint:n.mint,notUseTokenAccount:l,owner:this.scope.ownerPubKey,createInfo:l?{payer:t.feePayer||this.scope.ownerPubKey,amount:new ct.default(new Kn.default(n.perSecond.mul(n.endTime-n.openTime).toFixed(0)).gte(n.perSecond.mul(n.endTime-n.openTime))?n.perSecond.mul(n.endTime-n.openTime).toFixed(0):n.perSecond.mul(n.endTime-n.openTime).add(1).toFixed(0))}:void 0,associatedOnly:l?!1:o,checkCreateATAOwner:i});p&&c.addInstruction(p),m||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos);let f=await this.getClmmPoolKeys(e.id),y=we.setRewardInstructions({poolInfo:e,poolKeys:f,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:m},rewardInfo:{mint:n.mint,openTime:n.openTime,endTime:n.endTime,emissionsPerSecondX64:go(n.perSecond)}});return c.addInstruction(y),c.addCustomComputeBudget(r),c.addTipInstruction(a),c.versionBuild({txVersion:u,extInfo:{address:y.address}})}async setRewards({poolInfo:e,poolKeys:t,ownerInfo:n,rewardInfos:o,associatedOnly:i=!0,checkCreateATAOwner:r=!1,computeBudgetConfig:a,txTipConfig:u,txVersion:s,feePayer:c}){let l=this.createTxBuilder(c),m={};for(let p of o){p.endTime<=p.openTime&&this.logAndCreateError("reward time error","rewardInfo",p);let f=n.useSOLBalance&&p.mint.address===Z.toString(),{account:y,instructionParams:b}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new G.PublicKey(p.mint.programId),mint:new G.PublicKey(p.mint.address),notUseTokenAccount:f,owner:this.scope.ownerPubKey,createInfo:f?{payer:n.feePayer||this.scope.ownerPubKey,amount:new ct.default(new Kn.default(p.perSecond.mul(p.endTime-p.openTime).toFixed(0)).gte(p.perSecond.mul(p.endTime-p.openTime))?p.perSecond.mul(p.endTime-p.openTime).toFixed(0):p.perSecond.mul(p.endTime-p.openTime).add(1).toFixed(0))}:void 0,associatedOnly:f?!1:i,checkCreateATAOwner:r});b&&l.addInstruction(b),y||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos);let g=t!=null?t:await this.getClmmPoolKeys(e.id),A=we.setRewardInstructions({poolInfo:e,poolKeys:g,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:y},rewardInfo:{mint:new G.PublicKey(p.mint.address),openTime:p.openTime,endTime:p.endTime,emissionsPerSecondX64:go(p.perSecond)}});l.addInstruction(A),m=N(N({},m),A.address)}return l.addCustomComputeBudget(a),l.addTipInstruction(u),l.versionBuild({txVersion:s,extInfo:{address:m}})}async collectReward({poolInfo:e,ownerInfo:t,rewardMint:n,associatedOnly:o=!0,checkCreateATAOwner:i=!1,computeBudgetConfig:r,txTipConfig:a,txVersion:u,feePayer:s}){let c=e.rewardDefaultInfos.find(g=>g.mint.address===n.toString());c||this.logAndCreateError("reward mint error","not found reward mint",n);let l=this.createTxBuilder(s),m=t.useSOLBalance&&n.equals(Z),{account:p,instructionParams:f}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new G.PublicKey(c.mint.programId),mint:n,notUseTokenAccount:m,owner:this.scope.ownerPubKey,skipCloseAccount:!m,createInfo:{payer:t.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:m?!1:o,checkCreateATAOwner:i});f&&l.addInstruction(f),p||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos);let y=await this.getClmmPoolKeys(e.id),b=we.collectRewardInstructions({poolInfo:e,poolKeys:y,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:p},rewardMint:n});return l.addInstruction(b),l.addCustomComputeBudget(r),l.addTipInstruction(a),l.versionBuild({txVersion:u,extInfo:{address:b.address}})}async collectRewards({poolInfo:e,ownerInfo:t,rewardMints:n,associatedOnly:o=!0,checkCreateATAOwner:i=!1,computeBudgetConfig:r,txTipConfig:a,feePayer:u}){let s=this.createTxBuilder(u),c={};for(let l of n){let m=e.rewardDefaultInfos.find(A=>A.mint.address===l.toString());if(!m){this.logAndCreateError("reward mint error","not found reward mint",l);continue}let p=t.useSOLBalance&&l.equals(Z),{account:f,instructionParams:y}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new G.PublicKey(m.mint.programId),mint:l,notUseTokenAccount:p,owner:this.scope.ownerPubKey,skipCloseAccount:!p,createInfo:{payer:t.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:p?!1:o,checkCreateATAOwner:i});f||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos),y&&s.addInstruction(y);let b=await this.getClmmPoolKeys(e.id),g=we.collectRewardInstructions({poolInfo:e,poolKeys:b,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:f},rewardMint:l});s.addInstruction(g),c=N(N({},c),g.address)}return s.addCustomComputeBudget(r),s.addTipInstruction(a),s.build({address:c})}async openLimitOrder({poolInfo:e,baseIn:t=!0,orderTick:n,amount:o,noneIndex:i=0,tickArrayBitmap:r,ownerInfo:a={useSOLBalance:!0},associatedOnly:u=!0,feePayer:s,computeBudgetConfig:c,txTipConfig:l,txVersion:m}){let p=new G.PublicKey(e.id),f=new G.PublicKey(e.programId),y=t?new G.PublicKey(e.mintA.address):new G.PublicKey(e.mintB.address),b=t?new G.PublicKey(e.mintB.address):new G.PublicKey(e.mintA.address),g=new G.PublicKey(e[t?"mintA":"mintB"].programId),A=new G.PublicKey(e[t?"mintB":"mintA"].programId),k=y.equals(Z),h=b.equals(Z),P=a.useSOLBalance&&k,T=a.useSOLBalance&&h,I=this.createTxBuilder(),x=P||!u?void 0:ne(this.scope.ownerPubKey,y,g).publicKey;if(x)I.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,x,this.scope.ownerPubKey,y,g)]});else{let{account:z,instructionParams:H}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:g,mint:y,notUseTokenAccount:P,owner:this.scope.ownerPubKey,skipCloseAccount:!P,createInfo:{payer:a.feePayer||this.scope.ownerPubKey,amount:o},associatedOnly:!P});x=z,H&&I.addInstruction(H)}let S=T||!u?void 0:ne(this.scope.ownerPubKey,b,A).publicKey;if(S)I.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,S,this.scope.ownerPubKey,b,A)]});else{let{account:z,instructionParams:H}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:A,mint:b,notUseTokenAccount:T,owner:this.scope.ownerPubKey,skipCloseAccount:!T,createInfo:{payer:a.feePayer||this.scope.ownerPubKey,amount:o},associatedOnly:!T});S=z,H&&I.addInstruction(H)}let B=Nc(f,this.scope.ownerPubKey,i).publicKey,R=await this.scope.connection.getAccountInfo(B),L=R?kc.decode(R.data).orderNonce:new ct.default(0),O=Oc(f,s||this.scope.ownerPubKey,B,L).publicKey,C=Te.getTickArrayStartIndex(n,e.config.tickSpacing),F=Ee(f,p,C).publicKey,E=on(f,p,new G.PublicKey(e[t?"mintA":"mintB"].address)).publicKey,_=on(f,p,new G.PublicKey(e[t?"mintB":"mintA"].address)).publicKey;return I.addInstruction({instructions:[we.openLimitOrderInstruction(f,s||this.scope.ownerPubKey,p,F,B,O,x,S,E,_,y,b,g,i,t,n,o,r)]}),I.addCustomComputeBudget(c),I.addTipInstruction(l),I.versionBuild({txVersion:m,extInfo:{limitOrder:O}})}async increaseLimitOrder({poolInfo:e,limitOrder:t,amount:n,ownerInfo:o={useSOLBalance:!0},associatedOnly:i=!0,feePayer:r,computeBudgetConfig:a,txTipConfig:u,txVersion:s}){let c=new G.PublicKey(e.id),l=new G.PublicKey(e.programId),m=await this.scope.connection.getAccountInfo(t);m||this.logAndCreateError(`limit order ${t.toBase58()} not exist`);let p=yo.decode(m.data),f=p.zeroForOne?new G.PublicKey(e.mintA.address):new G.PublicKey(e.mintB.address),y=new G.PublicKey(e[p.zeroForOne?"mintA":"mintB"].programId),b=f.equals(Z),g=o.useSOLBalance&&b,A=this.createTxBuilder(),k=g||!i?void 0:ne(this.scope.ownerPubKey,f,y).publicKey;if(k)A.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,k,this.scope.ownerPubKey,f,y)]});else{let{account:I,instructionParams:x}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:y,mint:f,notUseTokenAccount:g,owner:this.scope.ownerPubKey,skipCloseAccount:!g,createInfo:{payer:o.feePayer||this.scope.ownerPubKey,amount:n},associatedOnly:!g});k=I,x&&A.addInstruction(x)}let h=on(l,c,new G.PublicKey(e[p.zeroForOne?"mintA":"mintB"].address)).publicKey,P=Te.getTickArrayStartIndex(p.tick,e.config.tickSpacing),T=Ee(l,c,P).publicKey;return A.addInstruction({instructions:[we.increaseLimitOrderInstruction(l,r||this.scope.ownerPubKey,p.poolId,T,t,k,h,f,y,n)]}),A.addCustomComputeBudget(a),A.addTipInstruction(u),A.versionBuild({txVersion:s})}async decreaseLimitOrder({poolInfo:e,limitOrder:t,limitOrderInfo:n,amount:o,slippage:i=1e3,tickArrayBitmap:r,ownerInfo:a={useSOLBalance:!0},associatedOnly:u=!0,feePayer:s,computeBudgetConfig:c,txTipConfig:l,txVersion:m,forerunCreate:p}){let f=new G.PublicKey(e.id),y=new G.PublicKey(e.programId),b=n;if(!b){let z=await this.scope.connection.getAccountInfo(t);z||this.logAndCreateError(`limit order ${t.toBase58()} not exist`),b=yo.decode(z.data)}let g=o.muln(1e4-i).divn(1e4),A=$n.getUnFilledAmount({orderInfo:b});(A.isZero()||o.gt(A))&&this.logAndCreateError(`amount should be less than unfulfilled amount: ${A.toString()}, amount: ${o.toString()}`);let[k,h]=b.zeroForOne?[new G.PublicKey(e.mintA.address),new G.PublicKey(e.mintB.address)]:[new G.PublicKey(e.mintB.address),new G.PublicKey(e.mintA.address)],[P,T]=b.zeroForOne?[new G.PublicKey(e.mintA.programId),new G.PublicKey(e.mintB.programId)]:[new G.PublicKey(e.mintB.programId),new G.PublicKey(e.mintA.programId)],[I,x]=[k.equals(Z),h.equals(Z)],[S,B]=[a.useSOLBalance&&I,a.useSOLBalance&&x],R=this.createTxBuilder(),L=S||!u?void 0:ne(this.scope.ownerPubKey,k,P).publicKey,O=B||!u?void 0:ne(this.scope.ownerPubKey,h,T).publicKey;if(L)R.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,L,this.scope.ownerPubKey,k,P)]});else{let{account:z,instructionParams:H}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:P,mint:k,notUseTokenAccount:S,owner:this.scope.ownerPubKey,skipCloseAccount:!S,createInfo:{payer:a.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:!S});L=z,H&&R.addInstruction(H)}if(O)R.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,O,this.scope.ownerPubKey,h,T)]});else{let{account:z,instructionParams:H}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:T,mint:h,notUseTokenAccount:B,owner:this.scope.ownerPubKey,skipCloseAccount:!B,createInfo:{payer:a.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:!B});O=z,H&&R.addInstruction(H)}let[C,F]=[on(y,f,k).publicKey,on(y,f,h).publicKey],E=Te.getTickArrayStartIndex(b.tick,e.config.tickSpacing),_=Ee(y,f,E).publicKey;return R.addInstruction({instructions:[we.decreaseLimitOrderInstruction(y,s||this.scope.ownerPubKey,f,_,t,L,O,C,F,k,h,o,g,r)]}),R.addCustomComputeBudget(c),R.addTipInstruction(l),R.versionBuild({txVersion:m,extInfo:{forerunCreate:p}})}async closeLimitOrder({programId:e=Fn,limitOrder:t,autoWithdraw:n=!0,tickArrayBitmap:o,slippage:i=0,feePayer:r,computeBudgetConfig:a,txTipConfig:u,txVersion:s}){let c=await this.scope.connection.getAccountInfo(t);c||this.logAndCreateError(`limit order ${t.toBase58()} not exist`);let l=yo.decode(c.data),m=$n.getUnFilledAmount({orderInfo:l});!n&&!m.isZero()&&this.logAndCreateError(`unfulfilled amount should be 0, (${m.toString()} remaining), please withdraw first or set autoWithdraw: true`);let p=this.createTxBuilder(),f=(await this.scope.api.fetchPoolById({ids:l.poolId.toBase58()}))[0];f||(f=(await this.getSimplePoolInfo(l.poolId)).poolInfo);let y=await Pt.fetchTickArrayInfo({connection:this.scope.connection,programId:e,poolId:l.poolId,tick:l.tick,tickSpacing:f.config.tickSpacing}),b=$n.settleFilledOrder({orderInfo:l,tickInfo:y.ticks.find(g=>g.tick===l.tick)});if(m.isZero()){if(!b.isZero()){let g=await this.settleLimitOrder({limitOrder:t});p.addInstruction(N({},g.builder.AllTxData))}}else{let{builder:g}=await this.decreaseLimitOrder({poolInfo:f,limitOrder:t,limitOrderInfo:l,amount:m,tickArrayBitmap:o,slippage:i,txVersion:0});p.addInstruction({instructions:g.allInstructions})}return p.addInstruction({instructions:[we.closeLimitOrderInstruction(e,r||this.scope.ownerPubKey,this.scope.ownerPubKey,t)]}),p.addCustomComputeBudget(a),p.addTipInstruction(u),p.versionBuild({txVersion:s})}async closeAllLimitOrder({programId:e=Fn,limitOrders:t,autoWithdraw:n=!0,slippage:o=1e4,feePayer:i,computeBudgetConfig:r,txVersion:a}){let u=this.createTxBuilder(),c=(await It(this.scope.connection,t)).map((A,k)=>A?V(N({},yo.decode(A.data)),{pda:t[k]}):null),l=c.filter(Boolean),m=l.map(A=>A.poolId.toBase58()),p=(await this.scope.api.fetchPoolById({ids:m.join(",")})).filter(Boolean),f={};p.forEach(A=>f[A.id]=A);let y=await Pt.fetchMultipleTickArrayInfo({connection:this.scope.connection,tickInfoList:l.map(A=>({programId:e,poolId:A.poolId,tick:A.tick,tickSpacing:f[A.poolId.toString()].config.tickSpacing}))}),b={};y.forEach((A,k)=>{!A||(b[l[k].pda.toBase58()]=A)});let g=0;for(let A of t){let k=c[g];if(!k){g++;continue}let h=$n.getUnFilledAmount({orderInfo:k});!n&&!h.isZero()&&this.logAndCreateError(`${A.toBase58()} order unfulfilled amount should be 0 (${h.toString()} remaining), please withdraw first or set autoWithdraw: true`);let P=f[k.poolId.toBase58()],T=b[A.toBase58()],I=$n.settleFilledOrder({orderInfo:k,tickInfo:T.ticks.find(x=>x.tick===k.tick)});if(h.isZero()){if(!I.isZero()){let x=await this.settleLimitOrder({limitOrder:A,forerunCreate:!0});u.addInstruction(N({},x.builder.AllTxData))}}else{let{builder:x}=await this.decreaseLimitOrder({poolInfo:P,limitOrder:A,limitOrderInfo:k,amount:h,slippage:o,txVersion:0,forerunCreate:!0});u.addInstruction({instructions:x.allInstructions})}u.addInstruction({instructions:[we.closeLimitOrderInstruction(e,i||this.scope.ownerPubKey,this.scope.ownerPubKey,A)]}),g++}return a===0?u.sizeCheckBuildV0({computeBudgetConfig:r}):u.sizeCheckBuild({computeBudgetConfig:r})}async settleLimitOrder({limitOrder:e,feePayer:t,ownerInfo:n={useSOLBalance:!0},associatedOnly:o=!0,computeBudgetConfig:i,txTipConfig:r,txVersion:a,forerunCreate:u}){let s=await this.scope.connection.getAccountInfo(e);s||this.logAndCreateError(`limit order ${e.toBase58()} not exist`);let c=yo.decode(s.data),l=(await this.scope.api.fetchPoolById({ids:c.poolId.toBase58()}))[0];l||(l=(await this.getSimplePoolInfo(c.poolId)).poolInfo);let m=c.zeroForOne?l.mintB:l.mintA,[p,f]=[new G.PublicKey(m.address),new G.PublicKey(m.programId)],y=new G.PublicKey(l.programId),b=this.createTxBuilder(),g=p.equals(Z),A=n.useSOLBalance&&g,k=A||!o?void 0:ne(this.scope.ownerPubKey,p,f).publicKey;if(k)b.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,k,this.scope.ownerPubKey,p,f)]});else{let{account:P,instructionParams:T}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:f,mint:p,notUseTokenAccount:A,owner:this.scope.ownerPubKey,skipCloseAccount:!A,createInfo:{payer:n.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:!A});k=P,T&&b.addInstruction(T)}let h=Te.getTickArrayStartIndex(c.tick,l.config.tickSpacing);return b.addInstruction({instructions:[we.settleLimitOrderInstruction(y,t||this.scope.ownerPubKey,c.poolId,Ee(y,c.poolId,h).publicKey,e,k,on(y,c.poolId,p).publicKey,p,f)]}),b.addCustomComputeBudget(i),b.addTipInstruction(r),b.versionBuild({txVersion:a,extInfo:{forerunCreate:u}})}async settleAllLimitOrder({limitOrders:e,feePayer:t,ownerInfo:n={useSOLBalance:!0},associatedOnly:o=!0,computeBudgetConfig:i,txVersion:r}){let a=await It(this.scope.connection,e),u=[],s=a.map((p,f)=>{if(!p)return;let y=yo.decode(p.data);return u.push(y.poolId.toString()),V(N({},y),{pda:e[f]})}),c=await this.scope.api.fetchPoolById({ids:u.join(",")});c.filter(Boolean).length||(c=(await Promise.all(u.map(f=>this.getSimplePoolInfo(f)))).map(f=>f.poolInfo));let l=this.createTxBuilder(),m={};for(let p of s){if(!p)continue;let f=c.find(I=>I.id===p.poolId.toBase58());if(!f)continue;let y=new G.PublicKey(f.programId),b=new G.PublicKey(p.zeroForOne?f.mintB.address:f.mintA.address),g=b.equals(Z),A=n.useSOLBalance&&g,k=new G.PublicKey(g?We.TOKEN_PROGRAM_ID:(await this.scope.token.getTokenInfo(b)).programId),h=m[b.toBase58()],P=A||!o?void 0:ne(this.scope.ownerPubKey,b,k).publicKey;if(h)P=h;else{if(P)l.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,P,this.scope.ownerPubKey,b,k)]});else{let{account:I,instructionParams:x}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:k,mint:b,notUseTokenAccount:A,owner:this.scope.ownerPubKey,skipCloseAccount:!A,createInfo:{payer:n.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:!A});P=I,x&&l.addInstruction(x)}m[b.toBase58()]=P}let T=Te.getTickArrayStartIndex(p.tick,f.config.tickSpacing);l.addInstruction({instructions:[we.settleLimitOrderInstruction(y,t||this.scope.ownerPubKey,p.poolId,Ee(y,p.poolId,T).publicKey,p.pda,P,on(y,p.poolId,b).publicKey,b,k)]})}return r===0?l.sizeCheckBuildV0({computeBudgetConfig:i}):l.sizeCheckBuild({computeBudgetConfig:i})}async swap({poolInfo:e,poolKeys:t,inputMint:n,amountIn:o,amountOutMin:i,priceLimit:r,observationId:a,ownerInfo:u,remainingAccounts:s,associatedOnly:c=!0,checkCreateATAOwner:l=!1,txVersion:m,computeBudgetConfig:p,txTipConfig:f,feePayer:y}){let b=this.createTxBuilder(y),g=n.toString()===e.mintA.address.toString(),A=u.useSOLBalance&&e.mintA.address.toString()===Z.toBase58(),k=u.useSOLBalance&&e.mintB.address.toString()===Z.toBase58(),h;!r||r.equals(new Kn.default(0))?h=g?St.add(new ct.default(1)):Kt.sub(new ct.default(1)):h=se.priceToSqrtPriceX64(r,e.mintA.decimals,e.mintB.decimals);let P;if(!P){let{account:x,instructionParams:S}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintA.programId,mint:new G.PublicKey(e.mintA.address),notUseTokenAccount:A,owner:this.scope.ownerPubKey,skipCloseAccount:!A,createInfo:A||!g?{payer:u.feePayer||this.scope.ownerPubKey,amount:g?o:0}:void 0,associatedOnly:A?!1:c,checkCreateATAOwner:l});P=x,S&&b.addInstruction(S)}let T;if(!T){let{account:x,instructionParams:S}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintB.programId,mint:new G.PublicKey(e.mintB.address),notUseTokenAccount:k,owner:this.scope.ownerPubKey,skipCloseAccount:!k,createInfo:k||g?{payer:u.feePayer||this.scope.ownerPubKey,amount:g?0:o}:void 0,associatedOnly:k?!1:c,checkCreateATAOwner:l});T=x,S&&b.addInstruction(S)}(!P||!T)&&this.logAndCreateError("user do not have token account",{tokenA:e.mintA.address,tokenB:e.mintB.address,ownerTokenAccountA:P,ownerTokenAccountB:T,mintAUseSOLBalance:A,mintBUseSOLBalance:k,associatedOnly:c});let I=t!=null?t:await this.getClmmPoolKeys(e.id.toString());return b.addInstruction(we.makeSwapBaseInInstructions({poolInfo:V(N({},e),{id:e.id.toString(),programId:e.programId.toString()}),poolKeys:I,observationId:a,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:P,tokenAccountB:T},inputMint:new G.PublicKey(n),amountIn:o,amountOutMin:i,sqrtPriceLimitX64:$,remainingAccounts:s})),b.addCustomComputeBudget(p),b.addTipInstruction(f),b.versionBuild({txVersion:m})}async swapBaseOut({poolInfo:e,poolKeys:t,outputMint:n,amountOut:o,amountInMax:i,priceLimit:r,observationId:a,ownerInfo:u,remainingAccounts:s,associatedOnly:c=!0,checkCreateATAOwner:l=!1,txVersion:m,computeBudgetConfig:p,txTipConfig:f,feePayer:y}){let b=this.createTxBuilder(y),g=n.toString()===e.mintB.address.toString(),A=u.useSOLBalance&&e.mintA.address.toString()===Z.toBase58(),k=u.useSOLBalance&&e.mintB.address.toString()===Z.toBase58(),h;!r||r.equals(new Kn.default(0))?h=g?St.add(new ct.default(1)):Kt.sub(new ct.default(1)):h=se.priceToSqrtPriceX64(r,e.mintA.decimals,e.mintB.decimals);let P;if(!P){let{account:x,instructionParams:S}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintA.programId,mint:new G.PublicKey(e.mintA.address),notUseTokenAccount:A,owner:this.scope.ownerPubKey,skipCloseAccount:!A,createInfo:A||!g?{payer:u.feePayer||this.scope.ownerPubKey,amount:g?i:0}:void 0,associatedOnly:A?!1:c,checkCreateATAOwner:l});P=x,S&&b.addInstruction(S)}let T;if(!T){let{account:x,instructionParams:S}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintB.programId,mint:new G.PublicKey(e.mintB.address),notUseTokenAccount:k,owner:this.scope.ownerPubKey,skipCloseAccount:!k,createInfo:k||g?{payer:u.feePayer||this.scope.ownerPubKey,amount:g?0:i}:void 0,associatedOnly:k?!1:c,checkCreateATAOwner:l});T=x,S&&b.addInstruction(S)}(!P||!T)&&this.logAndCreateError("user do not have token account",{tokenA:e.mintA.address,tokenB:e.mintB.address,ownerTokenAccountA:P,ownerTokenAccountB:T,mintAUseSOLBalance:A,mintBUseSOLBalance:k,associatedOnly:c});let I=t!=null?t:await this.getClmmPoolKeys(e.id.toString());return b.addInstruction(we.makeSwapBaseOutInstructions({poolInfo:V(N({},e),{id:e.id.toString(),programId:e.programId.toString()}),poolKeys:I,observationId:a,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:P,tokenAccountB:T},outputMint:new G.PublicKey(n),amountOut:o,amountInMax:i,sqrtPriceLimitX64:$,remainingAccounts:s})),b.addCustomComputeBudget(p),b.addTipInstruction(f),b.versionBuild({txVersion:m})}async harvestAllRewards({allPoolInfo:e,allPositions:t,lockInfo:n,ownerInfo:o,associatedOnly:i=!0,checkCreateATAOwner:r=!1,programId:a,txVersion:u,computeBudgetConfig:s,feePayer:c,lockProgram:l=mi,lockAuth:m=pr,clmmProgram:p=Fn}){var k,h;let f={};for(let P of this.scope.account.tokenAccountRawInfos)i?ne(this.scope.ownerPubKey,P.accountInfo.mint,a).publicKey.equals(P.pubkey)&&(f[P.accountInfo.mint.toString()]=P.pubkey):f[P.accountInfo.mint.toString()]=P.pubkey;let y=Object.values(t).flat().map(P=>P.nftMint),b=await Ge(this.scope.connection,y.map(P=>({pubkey:P}))),g={};b.forEach(P=>{var T,I;g[P.pubkey.toBase58()]=(I=(T=P==null?void 0:P.accountInfo)==null?void 0:T.owner)!=null?I:null});let A=this.createTxBuilder(c);for(let P of Object.values(e)){if(t[P.id]===void 0||!t[P.id].find(C=>!C.liquidity.isZero()||C.rewardInfos.find(F=>!F.rewardAmountOwed.isZero())))continue;let T=P,I=o.useSOLBalance&&T.mintA.address===Z.toString(),x=o.useSOLBalance&&T.mintB.address===Z.toString(),S=f[T.mintA.address];if(!S)if(I){let{account:C,instructionParams:F}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:T.mintA.programId,mint:new G.PublicKey(T.mintA.address),notUseTokenAccount:I,owner:this.scope.ownerPubKey,skipCloseAccount:!I,createInfo:{payer:o.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:I?!1:i,checkCreateATAOwner:r});S=C,F&&A.addInstruction(F)}else{let C=new G.PublicKey(T.mintA.address);S=this.scope.account.getAssociatedTokenAccount(C,new G.PublicKey(T.mintA.programId)),A.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,S,this.scope.ownerPubKey,C,new G.PublicKey(T.mintA.programId))]})}let B=f[T.mintB.address];if(!B)if(x){let{account:C,instructionParams:F}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:T.mintB.programId,mint:new G.PublicKey(T.mintB.address),notUseTokenAccount:x,owner:this.scope.ownerPubKey,skipCloseAccount:!x,createInfo:{payer:o.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:x?!1:i,checkCreateATAOwner:r});B=C,F&&A.addInstruction(F)}else{let C=new G.PublicKey(T.mintB.address);B=this.scope.account.getAssociatedTokenAccount(C,new G.PublicKey(T.mintB.programId)),A.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,B,this.scope.ownerPubKey,C,new G.PublicKey(T.mintB.programId))]})}f[T.mintA.address]=S,f[T.mintB.address]=B;let R=[];for(let C of T.rewardDefaultInfos){let F=o.useSOLBalance&&C.mint.address===Z.toString(),E=f[C.mint.address];if(!E){let{account:_,instructionParams:z}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new G.PublicKey(C.mint.programId),mint:new G.PublicKey(C.mint.address),notUseTokenAccount:F,owner:this.scope.ownerPubKey,skipCloseAccount:!F,createInfo:{payer:o.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:F?!1:i});E=_,z&&A.addInstruction(z)}f[C.mint.address]=E,R.push(E)}let L=await this.getClmmPoolKeys(T.id),O=[];for(let C=0;C<L.rewardInfos.length;C++)O.push({poolRewardVault:new G.PublicKey(L.rewardInfos[C].vault),ownerRewardVault:R[C],rewardMint:new G.PublicKey(L.rewardInfos[C].mint.address)});for(let C of t[P.id]){let F=(k=n==null?void 0:n[P.id])==null?void 0:k[C.nftMint.toBase58()];if(F){let E=ne(this.scope.ownerPubKey,F.lockNftMint,We.TOKEN_PROGRAM_ID).publicKey,_=Te.getTickArrayStartIndex(C.tickLower,L.config.tickSpacing),z=Te.getTickArrayStartIndex(C.tickUpper,L.config.tickSpacing),{publicKey:H}=Ee(new G.PublicKey(L.programId),F.poolId,_),{publicKey:Y}=Ee(new G.PublicKey(L.programId),F.poolId,z),{publicKey:J}=gn(new G.PublicKey(L.programId),F.poolId,C.tickLower,C.tickUpper),ie=Eo(l,F.lockNftMint).publicKey,Q=we.harvestLockPositionInstructionV2({programId:l,auth:m,lockPositionId:ie,clmmProgram:p,lockOwner:this.scope.ownerPubKey,lockNftMint:F.lockNftMint,lockNftAccount:E,positionNftAccount:F.nftAccount,positionId:F.positionId,poolId:F.poolId,protocolPosition:J,vaultA:new G.PublicKey(L.vault.A),vaultB:new G.PublicKey(L.vault.B),tickArrayLower:H,tickArrayUpper:Y,userVaultA:S,userVaultB:B,mintA:new G.PublicKey(L.mintA.address),mintB:new G.PublicKey(L.mintB.address),rewardAccounts:O,exTickArrayBitmap:He(p,F.poolId).publicKey});A.addInstruction({instructions:[Q],instructionTypes:[X.ClmmHarvestLockPosition],lookupTableAddress:L.lookupTableAccount?[L.lookupTableAccount]:[]})}else{let E=we.decreaseLiquidityInstructions({poolInfo:T,poolKeys:L,ownerPosition:C,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:S,tokenAccountB:B,rewardAccounts:R},liquidity:new ct.default(0),amountMinA:new ct.default(0),amountMinB:new ct.default(0),nft2022:(h=g[C.nftMint.toBase58()])==null?void 0:h.equals(We.TOKEN_2022_PROGRAM_ID)});A.addInstruction(E)}}}return u===0?A.sizeCheckBuildV0({computeBudgetConfig:s}):A.sizeCheckBuild({computeBudgetConfig:s})}async getWhiteListMint({programId:e}){let t=await this.scope.connection.getAccountInfo(xi(e).publicKey);return t?wc.decode(t.data).whitelistMints.filter(o=>!o.equals(G.PublicKey.default)):[]}async getOwnerPositionInfo({programId:e=Fn}){await this.scope.account.fetchWalletTokenAccounts();let n=this.scope.account.tokenAccountRawInfos.filter(r=>r.accountInfo.amount.eq(new ct.default(1))).map(r=>rn(new G.PublicKey(e),r.accountInfo.mint).publicKey),o=await this.scope.connection.getMultipleAccountsInfo(n),i=[];return o.forEach(r=>{if(!r)return;let a=Ir.decode(r.data);i.push(a)}),i}async getOwnerLockedPositionInfo({programId:e=mi}){await this.scope.account.fetchWalletTokenAccounts();let n=this.scope.account.tokenAccountRawInfos.filter(u=>u.accountInfo.amount.eq(new ct.default(1))).map(u=>Eo(new G.PublicKey(e),u.accountInfo.mint).publicKey),o=await this.scope.connection.getMultipleAccountsInfo(n),i=[];o.forEach(u=>{if(!u)return;let s=Tc.decode(u.data);i.push(s)});let r=await this.scope.connection.getMultipleAccountsInfo(i.map(u=>u.positionId)),a=[];return r.forEach(u=>{if(!u)return;let s=Ir.decode(u.data);a.push(s)}),i.map((u,s)=>({position:a[s],lockInfo:u}))}async getRpcClmmPoolInfo({poolId:e}){return(await this.getRpcClmmPoolInfos({poolIds:[e]}))[String(e)]}async getRpcClmmPoolInfos({poolIds:e,config:t}){let n=await Ge(this.scope.connection,e.map(i=>({pubkey:new G.PublicKey(i)})),t),o={};for(let i=0;i<e.length;i++){let r=n[i];if(r===null||!r.accountInfo)throw Error("fetch pool info error: "+String(e[i]));let a=fo.decode(r.accountInfo.data),u=se.sqrtPriceX64ToPrice(a.sqrtPriceX64,a.mintDecimalsA,a.mintDecimalsB).toNumber();o[String(e[i])]=V(N({},a),{currentPrice:u,programId:r.accountInfo.owner})}return o}async getComputeClmmPoolInfos({clmmPoolsRpcInfo:e,mintInfos:t}){let n=new Set(Object.keys(e).map(u=>e[u].configId.toBase58())),o=await Ge(this.scope.connection,Array.from(n).map(u=>({pubkey:new G.PublicKey(u)}))),i={};o.forEach(u=>{!u.accountInfo||(i[u.pubkey.toBase58()]=Ya.decode(u.accountInfo.data))});let r=await Pt.fetchComputeMultipleClmmInfo({connection:this.scope.connection,rpcDataMap:e,poolList:Object.keys(e).map(u=>{var l,m,p,f;let[s,c]=[e[u].mintA.toBase58(),e[u].mintB.toBase58()];return{id:u,programId:e[u].programId.toBase58(),mintA:wt({address:s,decimals:e[u].mintDecimalsA,programId:t[s].programId.toBase58()||We.TOKEN_PROGRAM_ID.toBase58(),extensions:{feeConfig:(l=t[s])!=null&&l.feeConfig?xn((m=t[s])==null?void 0:m.feeConfig):void 0}}),mintB:wt({address:c,decimals:e[u].mintDecimalsB,programId:t[c].programId.toBase58()||We.TOKEN_PROGRAM_ID.toBase58(),extensions:{feeConfig:(p=t[c])!=null&&p.feeConfig?xn((f=t[c])==null?void 0:f.feeConfig):void 0}}),price:e[u].currentPrice,config:V(N({},i[e[u].configId.toBase58()]),{id:e[u].configId.toBase58(),fundFeeRate:0,description:"",defaultRange:0,defaultRangePoint:[]})}})}),a=await Pt.fetchMultiplePoolTickArrays({connection:this.scope.connection,poolKeys:Object.values(r)});return{computeClmmPoolInfo:r,computePoolTickData:a}}async getPoolInfoFromRpc(e){let t=await this.getRpcClmmPoolInfo({poolId:e}),n=new Set([t.mintA.toBase58(),t.mintB.toBase58(),...t.rewardInfos.filter(c=>!c.mint.equals(G.PublicKey.default)).map(c=>c.mint.toBase58())]),o=await so({connection:this.scope.connection,mints:Array.from(n).map(c=>new G.PublicKey(c))}),{computeClmmPoolInfo:i,computePoolTickData:r}=await this.scope.clmm.getComputeClmmPoolInfos({clmmPoolsRpcInfo:{[e]:t},mintInfos:o}),a=await Ge(this.scope.connection,[{pubkey:t.vaultA},{pubkey:t.vaultB}]),u=Ec(i[e],o);if(!a[0].accountInfo||!a[1].accountInfo)throw new Error("pool vault data not found");u.mintAmountA=Number(Nn.decode(a[0].accountInfo.data).amount.toString()),u.mintAmountB=Number(Nn.decode(a[1].accountInfo.data).amount.toString());let s=V(N({},i[e]),{exBitmapAccount:i[e].exBitmapAccount.toBase58(),observationId:i[e].observationId.toBase58(),id:e,programId:t.programId.toBase58(),openTime:t.startTime.toString(),vault:{A:t.vaultA.toBase58(),B:t.vaultB.toBase58()},config:u.config,rewardInfos:i[e].rewardInfos.filter(c=>!c.vault.equals(G.PublicKey.default)).map(c=>{var l;return{mint:wt({address:c.mint.toBase58(),programId:We.TOKEN_PROGRAM_ID.toBase58(),decimals:(l=o[c.mint.toBase58()].decimals)!=null?l:6}),vault:c.vault.toBase58()}})});return{poolInfo:u,poolKeys:s,computePoolInfo:i[e],tickData:r,rpcPoolInfo:t,tickArrays:Object.values(r[e])}}async getSwapPoolInfo(e,t=!0){let{poolInfo:n,rpcData:o}=await this.getSimplePoolInfo(e),i=await this.scope.connection.getAccountInfo(o.configId),r=Ya.decode(i.data),a=new G.PublicKey(n.programId),u=new G.PublicKey(e),s=await _c(a,this.scope.connection,u,o.tickCurrent,r.tickSpacing,o.tickArrayBitmap,t);return{poolInfo:n,rpcData:o,configInfo:r,tickArrays:s}}async getSimplePoolInfo(e){let t=await this.getRpcClmmPoolInfo({poolId:e}),n=await this.scope.connection.getMultipleAccountsInfo([t.mintA,t.mintB]);return{poolInfo:{id:e.toString(),programId:t.programId.toString(),mintA:{address:t.mintA.toString(),programId:n[0].owner.toString(),decimals:t.mintDecimalsA},mintB:{address:t.mintB.toString(),programId:n[1].owner.toString(),decimals:t.mintDecimalsB},config:{id:t.configId.toBase58(),tickSpacing:t.tickSpacing}},rpcData:t}}async getMultipleSimplePoolInfo(e){let t=await this.getRpcClmmPoolInfos({poolIds:e}),n=new Set(Object.values(t).map(r=>[r.mintA.toBase58(),r.mintB.toBase58()]).flat()),o=await so({connection:this.scope.connection,mints:Array.from(n).map(r=>new G.PublicKey(r))}),i={};return e.forEach(r=>{let a=t[r.toString()];if(!a)return null;let u=o[a.mintA.toBase58()],s=o[a.mintB.toBase58()];i[r.toString()]={poolInfo:{id:r.toString(),programId:a.programId.toString(),mintA:{address:a.mintA.toString(),programId:u.programId.toString(),decimals:a.mintDecimalsA},mintB:{address:a.mintB.toString(),programId:s.programId.toString(),decimals:a.mintDecimalsB},config:{id:a.configId.toBase58(),tickSpacing:a.tickSpacing}},rpcData:a}}),i}};var Gc=v([Ie(8),W("bump"),nt("disableCreatePool"),at("index"),w("tradeFeeRate"),w("protocolFeeRate"),w("fundFeeRate"),w("createPoolFee"),M("protocolOwner"),M("fundOwner"),w("creatorFeeRate"),j(w(),15)]),Rr=v([Ie(8),M("configId"),M("poolCreator"),M("vaultA"),M("vaultB"),M("mintLp"),M("mintA"),M("mintB"),M("mintProgramA"),M("mintProgramB"),M("observationId"),W("bump"),W("status"),W("lpDecimals"),W("mintDecimalA"),W("mintDecimalB"),w("lpAmount"),w("protocolFeesMintA"),w("protocolFeesMintB"),w("fundFeesMintA"),w("fundFeesMintB"),w("openTime"),w("epoch"),W("feeOn"),nt("enableCreatorFee"),j(W(),6),w("creatorFeesMintA"),w("creatorFeesMintB"),j(w(),28)]),bA=v([Ie(8),M("configId"),j(w(),30)]);var et=require("@solana/web3.js"),At=require("@solana/spl-token");var Um=Buffer.from("vault_and_lp_mint_auth_seed","utf8"),wA=Buffer.from("amm_config","utf8"),Gm=Buffer.from("pool","utf8"),zm=Buffer.from("pool_lp_mint","utf8"),Xm=Buffer.from("pool_vault","utf8"),Ym=Buffer.from("observation","utf8"),Hm=Buffer.from("permission","utf8"),Qm=Buffer.from("support_mint","utf8");function wo(d){return de([Um],d)}function ns(d,e,t,n){return de([Gm,e.toBuffer(),t.toBuffer(),n.toBuffer()],d)}function Zm(d,e){return de([zm,e.toBuffer()],d)}function zc(d,e,t){return de([Xm,e.toBuffer(),t.toBuffer()],d)}function ko(d,e){return de([Ym,e.toBuffer()],d)}function os({poolId:d,programId:e,configId:t,mintA:n,mintB:o}){let i=wo(e).publicKey,r=d||ns(e,t,n,o).publicKey,a=Zm(e,r).publicKey,u=zc(e,r,n).publicKey,s=zc(e,r,o).publicKey,c=ko(e,r).publicKey;return{poolId:r,configId:t,authority:i,lpMint:a,vaultA:u,vaultB:s,observationId:c}}var jm=Buffer.from("locked_liquidity","utf8");function Wo(d,e){return de([jm,e.toBuffer()],d)}function Xc(d,e){return de([Hm,e.toBuffer()],d)}function is(d,e){return de([Qm,e.toBuffer()],d)}var $m=Be("Raydium_cpmm"),Cn={initialize:[175,175,109,31,13,152,155,237],deposit:[242,35,198,137,82,225,242,182],withdraw:[183,18,70,156,148,109,161,34],swapBaseInput:[143,190,90,218,196,30,51,222],swapBaseOutput:[55,217,98,86,163,74,180,173],lockCpLiquidity:[216,157,29,78,38,51,31,26],collectCpFee:[8,30,51,199,209,184,247,133],createPermissionPda:Buffer.from([135,136,2,216,137,169,181,202]),closePermissionPda:Buffer.from([156,84,32,118,69,135,70,123]),initializeWithPermission:Buffer.from([63,55,254,65,49,178,89,121]),collectCreatorFee:Buffer.from([20,22,86,123,198,28,219,132]),collectCreatorFeePermissionless:Buffer.from([202,202,34,83,226,122,145,229])};function Yc(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A,k,h){let P=v([w("amountMaxA"),w("amountMaxB"),w("openTime")]),T=ns(d,t,i,r).publicKey,I=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!o.equals(T),isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!0},{pubkey:At.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:y,isSigner:!1,isWritable:!1},{pubkey:At.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:pu,isSigner:!1,isWritable:!1},{pubkey:vt,isSigner:!1,isWritable:!1},...(h!=null?h:[]).map(S=>({pubkey:S,isSigner:!1,isWritable:!1}))],x=Buffer.alloc(P.span);return P.encode({amountMaxA:g,amountMaxB:A,openTime:k},x),new et.TransactionInstruction({keys:I,programId:d,data:Buffer.from([...Cn.initialize,...x])})}function Hc(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f){let y=v([w("lpAmount"),w("amountMaxA"),w("amountMaxB")]),b=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:At.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:At.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!0}],g=Buffer.alloc(y.span);return $m.debug("cpmm deposit data",{lpAmount:m.toString(),amountMaxA:p.toString(),amountMaxB:f.toString()}),y.encode({lpAmount:m,amountMaxA:p,amountMaxB:f},g),new et.TransactionInstruction({keys:b,programId:d,data:Buffer.from([...Cn.deposit,...g])})}function Qc(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f){let y=v([w("lpAmount"),w("amountMinA"),w("amountMinB")]),b=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:At.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:At.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:pn,isSigner:!1,isWritable:!1}],g=Buffer.alloc(y.span);return y.encode({lpAmount:m,amountMinA:p,amountMinB:f},g),new et.TransactionInstruction({keys:b,programId:d,data:Buffer.from([...Cn.withdraw,...g])})}function qo(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f,y){let b=v([w("amountIn"),w("amounOutMin")]),g=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!0}],A=Buffer.alloc(b.span);return b.encode({amountIn:f,amounOutMin:y},A),new et.TransactionInstruction({keys:g,programId:d,data:Buffer.from([...Cn.swapBaseInput,...A])})}function Zc(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f,y){let b=v([w("amountInMax"),w("amountOut")]),g=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!0}],A=Buffer.alloc(b.span);return b.encode({amountInMax:f,amountOut:y},A),new et.TransactionInstruction({keys:g,programId:d,data:Buffer.from([...Cn.swapBaseOutput,...A])})}async function jc(d){var b;let{ownerInfo:e,poolInfo:t,poolKeys:n,feeNftOwner:o,getEphemeralSigners:i}=d,r=[],[a,u]=[new et.PublicKey(t.id),new et.PublicKey(t.lpMint.address)],s;if(i)s=new et.PublicKey((await i(1))[0]);else{let g=et.Keypair.generate();r.push(g),s=g.publicKey}let{publicKey:c}=ne(o,s,At.TOKEN_PROGRAM_ID),{publicKey:l}=_n(s),{publicKey:m}=Wo(d.lockProgram,s),{publicKey:p}=ne(e.wallet,u,At.TOKEN_PROGRAM_ID),{publicKey:f}=ne(d.lockAuthProgram,u,At.TOKEN_PROGRAM_ID),y=Jm({programId:d.lockProgram,auth:d.lockAuthProgram,payer:e.feePayer,liquidityOwner:e.wallet,nftOwner:o,nftMint:s,nftAccount:c,poolId:a,lockPda:m,mintLp:u,userLpVault:p,lockLpVault:f,poolVaultA:new et.PublicKey(n.vault.A),poolVaultB:new et.PublicKey(n.vault.B),metadataAccount:l,lpAmount:d.lpAmount,withMetadata:(b=d.withMetadata)!=null?b:!0});return{address:{nftMint:s,nftAccount:c,metadataAccount:l,lockPda:m,userLpVault:p,lockLpVault:f},instructions:[y],signers:r,instructionTypes:[X.CpmmLockLp],lookupTableAddress:[]}}function Jm({programId:d,auth:e,payer:t,liquidityOwner:n,nftOwner:o,nftMint:i,nftAccount:r,poolId:a,lockPda:u,mintLp:s,userLpVault:c,lockLpVault:l,poolVaultA:m,poolVaultB:p,metadataAccount:f,lpAmount:y,withMetadata:b}){let g=[{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:n,isSigner:!0,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!0,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:vt,isSigner:!1,isWritable:!1},{pubkey:et.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:At.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:At.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:Bn,isSigner:!1,isWritable:!1}],A=v([w("lpAmount"),nt("withMetadata")]),k=Buffer.alloc(A.span);A.encode({lpAmount:y,withMetadata:b},k);let h=Buffer.from([...Cn.lockCpLiquidity,...k]);return new et.TransactionInstruction({keys:g,programId:d,data:h})}function rs({programId:d,nftOwner:e,auth:t,nftAccount:n,lockPda:o,poolId:i,mintLp:r,userVaultA:a,userVaultB:u,poolVaultA:s,poolVaultB:c,mintA:l,mintB:m,lockLpVault:p,lpFeeAmount:f,cpmmProgram:y,cpmmAuthProgram:b}){let g=[{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:y!=null?y:Zn,isSigner:!1,isWritable:!1},{pubkey:b!=null?b:Eu,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:At.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:At.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:pn,isSigner:!1,isWritable:!1}],A=v([w("lpFeeAmount")]),k=Buffer.alloc(A.span);A.encode({lpFeeAmount:f},k);let h=Buffer.from([...Cn.collectCpFee,...k]);return new et.TransactionInstruction({keys:g,programId:d,data:h})}function as(d,e,t,n,o,i,r,a,u,s,c,l,m){let p=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:At.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:et.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new et.TransactionInstruction({keys:p,programId:d,data:Cn.collectCreatorFee})}function $c(d,e,t,n,o,i,r,a,u,s,c,l,m){let p=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:At.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:et.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new et.TransactionInstruction({keys:p,programId:d,data:Cn.collectCreatorFeePermissionless})}function Jc(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A,k,h,P,T,I){let x=v([w("amountA"),w("amountB"),w("openTime"),W("feeOn")]),S=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:g,isSigner:!1,isWritable:!0},{pubkey:A,isSigner:!1,isWritable:!0},{pubkey:At.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:y,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:At.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:et.SystemProgram.programId,isSigner:!1,isWritable:!1},...(I!=null?I:[]).map(R=>({pubkey:R,isSigner:!1,isWritable:!1}))],B=Buffer.alloc(x.span);return x.encode({amountA:k,amountB:h,openTime:P,feeOn:T},B),new et.TransactionInstruction({keys:S,programId:d,data:Buffer.from([...Cn.initializeWithPermission,...B])})}var us=te(require("bn.js"));var Fi=te(require("bn.js"));function ss(d,e){if(e.isZero())throw Error("divisor is zero");return d.mod(e)}function ed(d,e){if(e.isZero())throw Error("rhs is zero");let t=d.div(e);return ss(d,e).gt(Mi)&&(t=t.add(new Fi.default(1))),[t,e]}var Mi=new Fi.default(0),vi=class{static swapBaseInputWithoutFees(e,t,n){let o=e.mul(n),i=t.add(e);return o.div(i)}static swapBaseOutputWithoutFees(e,t,n){let o=t.mul(e),i=n.sub(e),[r]=ed(o,i);return r}static lpTokensToTradingTokens(e,t,n,o,i){let r=e.mul(n).div(t),a=e.mul(o).div(t);if(i===0)return{tokenAmount0:r,tokenAmount1:a};if(i===1)return ss(e.mul(n),t).gt(Mi)&&r.gt(Mi)&&(r=r.add(new Fi.default(1))),ss(e.mul(o),t).gt(Mi)&&a.gt(Mi)&&(a=a.add(new Fi.default(1))),{tokenAmount0:r,tokenAmount1:a};throw Error("roundDirection value error")}};var tl=te(require("bn.js"));var el=te(require("bn.js")),Je=new el.default(1e6);var jt=class{static tradingFee(e,t){return _i(e,t,Je)}static protocolFee(e,t){return Lr(e,t,Je)}static fundFee(e,t){return Lr(e,t,Je)}static creatorFee(e,t){return _i(e,t,Je)}static splitCreatorFee(e,t,n){return Lr(e,n,t.add(n))}static calculatePreFeeAmount(e,t){if(t.isZero())return e;let n=e.mul(Je),o=Je.sub(t);return n.add(o).sub(new tl.default(1)).div(o)}};var Vi=class{static validate_supply(e,t){if(e.isZero())throw Error("tokenAmount0 is zero");if(t.isZero())throw Error("tokenAmount1 is zero")}static swapBaseInput(e,t,n,o,i,r,a,u){let s=new us.default(0),c=jt.tradingFee(e,o),l;u?(s=jt.creatorFee(e,i),l=e.sub(c).sub(s)):l=e.sub(c);let m=jt.protocolFee(c,r),p=jt.protocolFee(c,a),f=vi.swapBaseInputWithoutFees(l,t,n),y;return u?y=f:(s=jt.creatorFee(f,i),y=f.sub(s)),{newInputVaultAmount:t.add(l),newOutputVaultAmount:n.sub(f),inputAmount:e,outputAmount:y,tradeFee:c,protocolFee:m,fundFee:p,creatorFee:s}}static swapBaseOutput(e,t,n,o,i,r,a,u){let s,c=new us.default(0),l;if(u)l=e;else{let b=jt.calculatePreFeeAmount(e,i);c=b.sub(e),l=b}let m=vi.swapBaseOutputWithoutFees(l,t,n),p;if(u){let b=jt.calculatePreFeeAmount(m,o.add(i)),g=b.sub(m);c=jt.splitCreatorFee(g,o,i),s=g.sub(c),p=b}else{let b=jt.calculatePreFeeAmount(m,o);s=b.sub(m),p=b}let f=jt.protocolFee(s,r),y=jt.fundFee(s,a);return{newInputVaultAmount:t.add(m),newOutputVaultAmount:n.sub(l),inputAmount:p,outputAmount:e,tradeFee:s,protocolFee:f,fundFee:y,creatorFee:c}}};var cs=te(require("bn.js")),ls=new cs.default(25),Or=new cs.default(1e4);var nl=new Set(["5Q544fKrFoe6tsEbD7S8EmxGTJYAKtTVhAW5Q5pge4j1","3uaZBfHPfmpAHW7dsimC1SnyR61X4bJqQZKWmRSCXJxv","GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"]);var ms=v([W("instruction"),w("amountIn"),w("minAmountOut")]),ds=v([W("instruction"),w("maxAmountIn"),w("amountOut")]),ew=v([W("instruction"),W("nonce")]),td=v([W("instruction"),W("nonce"),w("startTime")]),Nr=v([w("status"),w("nonce"),w("maxOrder"),w("depth"),w("baseDecimal"),w("quoteDecimal"),w("state"),w("resetFlag"),w("minSize"),w("volMaxCutRatio"),w("amountWaveRatio"),w("baseLotSize"),w("quoteLotSize"),w("minPriceMultiplier"),w("maxPriceMultiplier"),w("systemDecimalValue"),w("minSeparateNumerator"),w("minSeparateDenominator"),w("tradeFeeNumerator"),w("tradeFeeDenominator"),w("pnlNumerator"),w("pnlDenominator"),w("swapFeeNumerator"),w("swapFeeDenominator"),w("baseNeedTakePnl"),w("quoteNeedTakePnl"),w("quoteTotalPnl"),w("baseTotalPnl"),w("poolOpenTime"),w("punishPcAmount"),w("punishCoinAmount"),w("orderbookToInitTime"),ye("swapBaseInAmount"),ye("swapQuoteOutAmount"),w("swapBase2QuoteFee"),ye("swapQuoteInAmount"),ye("swapBaseOutAmount"),w("swapQuote2BaseFee"),M("baseVault"),M("quoteVault"),M("baseMint"),M("quoteMint"),M("lpMint"),M("openOrders"),M("marketId"),M("marketProgramId"),M("targetOrders"),M("withdrawQueue"),M("lpVault"),M("owner"),w("lpReserve"),j(w(),3,"padding")]),tw=v([w("accountType"),w("status"),w("nonce"),w("maxOrder"),w("depth"),w("baseDecimal"),w("quoteDecimal"),w("state"),w("resetFlag"),w("minSize"),w("volMaxCutRatio"),w("amountWaveRatio"),w("baseLotSize"),w("quoteLotSize"),w("minPriceMultiplier"),w("maxPriceMultiplier"),w("systemDecimalsValue"),w("abortTradeFactor"),w("priceTickMultiplier"),w("priceTick"),w("minSeparateNumerator"),w("minSeparateDenominator"),w("tradeFeeNumerator"),w("tradeFeeDenominator"),w("pnlNumerator"),w("pnlDenominator"),w("swapFeeNumerator"),w("swapFeeDenominator"),w("baseNeedTakePnl"),w("quoteNeedTakePnl"),w("quoteTotalPnl"),w("baseTotalPnl"),w("poolOpenTime"),w("punishPcAmount"),w("punishCoinAmount"),w("orderbookToInitTime"),ye("swapBaseInAmount"),ye("swapQuoteOutAmount"),ye("swapQuoteInAmount"),ye("swapBaseOutAmount"),w("swapQuote2BaseFee"),w("swapBase2QuoteFee"),M("baseVault"),M("quoteVault"),M("baseMint"),M("quoteMint"),M("lpMint"),M("modelDataAccount"),M("openOrders"),M("marketId"),M("marketProgramId"),M("targetOrders"),M("owner"),j(w(),64,"padding")]),ps=v([W("instruction"),w("baseAmountIn"),w("quoteAmountIn"),w("fixedSide"),w("otherAmountMin")]),fs=v([W("instruction"),w("lpAmount"),w("baseAmountMin"),w("quoteAmountMin")]);var ol=v([w("fee")]);var al=require("@solana/web3.js"),Ei=te(require("decimal.js")),sl=require("@solana/spl-token");var il=require("@solana/web3.js");var nd=Be("Raydium_liquidity_serum");function rl({programId:d,marketId:e}){let t=[e.toBuffer()],n=0,o;for(;n<100;){try{let i=t.concat(Buffer.from([n]),Buffer.alloc(7));o=il.PublicKey.createProgramAddressSync(i,d)}catch(i){if(i instanceof TypeError)throw i;n++;continue}return{publicKey:o,nonce:n}}throw nd.logWithError("unable to find a viable program address nonce","params",{programId:d,marketId:e}),new Error("unable to find a viable program address nonce")}function Mr({programId:d}){let{publicKey:e}=de([Buffer.from("amm_config_account_seed","utf-8")],d);return e}function To({name:d,programId:e,marketId:t}){let{publicKey:n}=de([e.toBuffer(),t.toBuffer(),Buffer.from(d,"utf-8")],e);return n}function od({programId:d,marketId:e}){let{publicKey:t}=de([d.toBuffer(),e.toBuffer(),Buffer.from("open_order_associated_seed","utf-8")],d);return t}function bs({programId:d}){return de([Buffer.from([97,109,109,32,97,117,116,104,111,114,105,116,121])],d)}function gs({version:d,marketVersion:e,marketId:t,baseMint:n,quoteMint:o,baseDecimals:i,quoteDecimals:r,programId:a,marketProgramId:u}){let s=To({name:"amm_associated_seed",programId:a,marketId:t}),c=To({name:"lp_mint_associated_seed",programId:a,marketId:t}),{publicKey:l,nonce:m}=bs({programId:a}),p=To({name:"coin_vault_associated_seed",programId:a,marketId:t}),f=To({name:"pc_vault_associated_seed",programId:a,marketId:t}),y=To({name:"temp_lp_token_associated_seed",programId:a,marketId:t}),b=od({programId:a,marketId:t}),g=To({name:"target_associated_seed",programId:a,marketId:t}),A=To({name:"withdraw_associated_seed",programId:a,marketId:t}),{publicKey:k}=rl({programId:u,marketId:t});return{id:s,baseMint:n,quoteMint:o,lpMint:c,baseDecimals:i,quoteDecimals:r,lpDecimals:i,version:d,programId:a,authority:l,nonce:m,baseVault:p,quoteVault:f,lpVault:y,openOrders:b,targetOrders:g,withdrawQueue:A,marketVersion:e,marketProgramId:u,marketId:t,marketAuthority:k,lookupTableAccount:al.PublicKey.default,configId:Mr({programId:a})}}var ys={volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[]},Fr=d=>{let e={},t=sl.TOKEN_PROGRAM_ID.toBase58();return Object.keys(d).map(n=>{let o=d[n],[i,r]=[o.baseMint.toBase58(),o.quoteMint.toBase58()];e[n]={id:n,version:4,status:o.status.toNumber(),programId:o.programId.toBase58(),mintA:wt({address:i,programId:t,decimals:o.baseDecimal.toNumber()}),mintB:wt({address:r,programId:t,decimals:o.quoteDecimal.toNumber()}),rewardDefaultInfos:[],rewardDefaultPoolInfos:"Ecosystem",price:o.poolPrice.toNumber(),mintAmountA:new Ei.default(o.mintAAmount.toString()).div(10**o.baseDecimal.toNumber()).toNumber(),mintAmountB:new Ei.default(o.mintBAmount.toString()).div(10**o.quoteDecimal.toNumber()).toNumber(),baseReserve:o.baseReserve,quoteReserve:o.quoteReserve,feeRate:new Ei.default(o.tradeFeeNumerator.toString()).div(o.tradeFeeDenominator.toString()).toNumber(),openTime:o.poolOpenTime.toString(),tvl:0,day:ys,week:ys,month:ys,pooltype:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0,type:"Standard",marketId:o.marketId.toBase58(),configId:Mr({programId:o.programId}).toBase58(),lpPrice:0,lpAmount:new Ei.default(o.lpReserve.toString()).div(10**Math.min(o.baseDecimal.toNumber(),o.quoteDecimal.toNumber())).toNumber(),lpMint:wt({address:o.lpMint.toBase58(),programId:t,decimals:Math.min(o.baseDecimal.toNumber(),o.quoteDecimal.toNumber())}),burnPercent:0,feeOn:"Both",hasDynamicFee:!1,tips:[],launchMigratePool:!1}}),e};var Rn=require("@solana/spl-token"),Oe=require("@solana/web3.js");var Di=te(require("bn.js"));var vr=Be("Raydium_liquidity_instruction");function ul(d){let{poolInfo:e,poolKeys:t,userKeys:n,baseAmountIn:o,quoteAmountIn:i,fixedSide:r,otherAmountMin:a,modelDataPubKey:u=lo}=d,s=Buffer.alloc(ps.span);ps.encode({instruction:3,baseAmountIn:fe(o),quoteAmountIn:fe(i),otherAmountMin:fe(a),fixedSide:r==="base"?$:dt},s);let c=[K({pubkey:Rn.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:new Oe.PublicKey(e.id)}),K({pubkey:new Oe.PublicKey(t.authority),isWritable:!1}),K({pubkey:new Oe.PublicKey(t.openOrders),isWritable:!1}),K({pubkey:new Oe.PublicKey(t.targetOrders)}),K({pubkey:new Oe.PublicKey(e.lpMint.address)}),K({pubkey:new Oe.PublicKey(t.vault.A)}),K({pubkey:new Oe.PublicKey(t.vault.B)})];return e.pooltype.includes("StablePool")&&c.push(K({pubkey:u})),c.push(K({pubkey:new Oe.PublicKey(e.marketId),isWritable:!1}),K({pubkey:n.baseTokenAccount}),K({pubkey:n.quoteTokenAccount}),K({pubkey:n.lpTokenAccount}),K({pubkey:n.owner,isWritable:!1,isSigner:!0}),K({pubkey:new Oe.PublicKey(t.marketEventQueue),isWritable:!1})),new Oe.TransactionInstruction({programId:new Oe.PublicKey(e.programId),keys:c,data:s})}function Ps(d){let{poolInfo:e,poolKeys:t,userKeys:n,lpAmount:o,baseAmountMin:i,quoteAmountMin:r,modelDataPubKey:a=lo}=d,u=Ut(t),s=4;if(e.pooltype.includes("StablePool")&&(s=5),s===4||s===5){let c=Buffer.alloc(fs.span);fs.encode({instruction:4,lpAmount:fe(o),baseAmountMin:fe(i),quoteAmountMin:fe(r)},c);let l=[K({pubkey:Rn.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:u.id}),K({pubkey:u.authority,isWritable:!1}),K({pubkey:u.openOrders}),K({pubkey:u.targetOrders}),K({pubkey:u.mintLp.address}),K({pubkey:u.vault.A}),K({pubkey:u.vault.B})];return s===5?l.push(K({pubkey:a})):(l.push(K({pubkey:u.id})),l.push(K({pubkey:u.id}))),l.push(K({pubkey:u.marketProgramId,isWritable:!1}),K({pubkey:u.marketId}),K({pubkey:u.marketBaseVault}),K({pubkey:u.marketQuoteVault}),K({pubkey:u.marketAuthority,isWritable:!1}),K({pubkey:n.lpTokenAccount}),K({pubkey:n.baseTokenAccount}),K({pubkey:n.quoteTokenAccount}),K({pubkey:n.owner,isWritable:!1,isSigner:!0}),K({pubkey:u.marketEventQueue}),K({pubkey:u.marketBids}),K({pubkey:u.marketAsks})),new Oe.TransactionInstruction({programId:u.programId,keys:l,data:c})}return new Oe.TransactionInstruction({programId:u.programId,keys:[]})}function As({programId:d,ammId:e,ammAuthority:t,ammOpenOrders:n,lpMint:o,coinMint:i,pcMint:r,coinVault:a,pcVault:u,withdrawQueue:s,ammTargetOrders:c,poolTempLp:l,marketProgramId:m,marketId:p,userWallet:f,userCoinVault:y,userPcVault:b,userLpVault:g,nonce:A,openTime:k,coinAmount:h,pcAmount:P,ammConfigId:T,feeDestinationId:I}){let x=v([W("instruction"),W("nonce"),w("openTime"),w("pcAmount"),w("coinAmount")]),S=[{pubkey:Rn.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:Rn.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:Oe.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:vt,isSigner:!1,isWritable:!1},{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:T,isSigner:!1,isWritable:!1},{pubkey:I,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!0,isWritable:!0},{pubkey:y,isSigner:!1,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!0},{pubkey:g,isSigner:!1,isWritable:!0}],B=Buffer.alloc(x.span);return x.encode({instruction:1,nonce:A,openTime:k,coinAmount:h,pcAmount:P},B),{instruction:new Oe.TransactionInstruction({keys:S,programId:d,data:B}),instructionType:X.AmmV4CreatePool}}function id({poolKeys:d,userKeys:e,amountIn:t,minAmountOut:n,modelDataPubKey:o=lo},i){let r=Ut(d),a=Buffer.alloc(ms.span);ms.encode({instruction:9,amountIn:fe(t),minAmountOut:fe(n)},a);let u=[K({pubkey:Rn.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:r.id}),K({pubkey:r.authority,isWritable:!1}),K({pubkey:r.openOrders})];return i===4&&u.push(K({pubkey:r.targetOrders})),u.push(K({pubkey:r.vault.A}),K({pubkey:r.vault.B})),i===5&&u.push(K({pubkey:o})),u.push(K({pubkey:r.marketProgramId,isWritable:!1}),K({pubkey:r.marketId}),K({pubkey:r.marketBids}),K({pubkey:r.marketAsks}),K({pubkey:r.marketEventQueue}),K({pubkey:r.marketBaseVault}),K({pubkey:r.marketQuoteVault}),K({pubkey:r.marketAuthority,isWritable:!1}),K({pubkey:e.tokenAccountIn}),K({pubkey:e.tokenAccountOut}),K({pubkey:e.owner,isWritable:!1,isSigner:!0})),new Oe.TransactionInstruction({programId:r.programId,keys:u,data:a})}function rd({poolKeys:d,userKeys:e,maxAmountIn:t,amountOut:n,modelDataPubKey:o=lo},i){let r=Ut(d),a=Buffer.alloc(ds.span);ds.encode({instruction:11,maxAmountIn:fe(t),amountOut:fe(n)},a);let u=[K({pubkey:Rn.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:r.id}),K({pubkey:r.authority,isWritable:!1}),K({pubkey:r.openOrders}),K({pubkey:r.targetOrders}),K({pubkey:r.vault.A}),K({pubkey:r.vault.B})];return i===5&&u.push(K({pubkey:o})),u.push(K({pubkey:r.marketProgramId,isWritable:!1}),K({pubkey:r.marketId}),K({pubkey:r.marketBids}),K({pubkey:r.marketAsks}),K({pubkey:r.marketEventQueue}),K({pubkey:r.marketBaseVault}),K({pubkey:r.marketQuoteVault}),K({pubkey:r.marketAuthority,isWritable:!1}),K({pubkey:e.tokenAccountIn}),K({pubkey:e.tokenAccountOut}),K({pubkey:e.owner,isWritable:!1,isSigner:!0})),new Oe.TransactionInstruction({programId:r.programId,keys:u,data:a})}function ad(d,e,t,n,o,i,r,a,u,s){let c=v([W("instructionId"),w("amountIn"),w("minAmountOut")]),l=Buffer.alloc(c.span);c.encode({instructionId:16,amountIn:u,minAmountOut:s},l);let m=[{pubkey:Rn.TOKEN_PROGRAM_ID,isWritable:!1,isSigner:!1},{pubkey:e,isWritable:!0,isSigner:!1},{pubkey:t,isWritable:!1,isSigner:!1},{pubkey:n,isWritable:!0,isSigner:!1},{pubkey:o,isWritable:!0,isSigner:!1},{pubkey:i,isWritable:!0,isSigner:!1},{pubkey:r,isWritable:!0,isSigner:!1},{pubkey:a,isWritable:!1,isSigner:!0}];return new Oe.TransactionInstruction({programId:d,keys:m,data:l})}function sd(d,e,t,n,o,i,r,a,u,s){let c=v([W("instructionId"),w("maxAmountIn"),w("amountOut")]),l=Buffer.alloc(c.span);c.encode({instructionId:17,maxAmountIn:u,amountOut:s},l);let m=[{pubkey:Rn.TOKEN_PROGRAM_ID,isWritable:!1,isSigner:!1},{pubkey:e,isWritable:!0,isSigner:!1},{pubkey:t,isWritable:!1,isSigner:!1},{pubkey:n,isWritable:!0,isSigner:!1},{pubkey:o,isWritable:!0,isSigner:!1},{pubkey:i,isWritable:!0,isSigner:!1},{pubkey:r,isWritable:!0,isSigner:!1},{pubkey:a,isWritable:!1,isSigner:!0}];return new Oe.TransactionInstruction({programId:d,keys:m,data:l})}function _r(d){let{poolKeys:e,version:t,userKeys:n,amountIn:o,amountOut:i,fixedSide:r}=d;if(t===4){if(r==="in")return ad(new Oe.PublicKey(e.programId),new Oe.PublicKey(e.id),new Oe.PublicKey(e.authority),new Oe.PublicKey(e.vault.A),new Oe.PublicKey(e.vault.B),n.tokenAccountIn,n.tokenAccountOut,n.owner,new Di.default(o.toString()),new Di.default(i.toString()));if(r==="out")return sd(new Oe.PublicKey(e.programId),new Oe.PublicKey(e.id),new Oe.PublicKey(e.authority),new Oe.PublicKey(e.vault.A),new Oe.PublicKey(e.vault.B),n.tokenAccountIn,n.tokenAccountOut,n.owner,new Di.default(o.toString()),new Di.default(i.toString()));vr.logWithError("invalid params","params",d)}throw vr.logWithError("invalid version, only support pool v4","poolKeys.version",t),new Error("invalid version")}function Vr(d){let{poolKeys:e,version:t,userKeys:n,amountIn:o,amountOut:i,fixedSide:r}=d;if(t===4||t===5){let a={poolKeys:e,userKeys:n};if(r==="in")return id(V(N({},a),{amountIn:o,minAmountOut:i}),t);if(r==="out")return rd(V(N({},a),{maxAmountIn:o,amountOut:i}),t);vr.logWithError("invalid params","params",d)}throw vr.logWithError("invalid version","poolKeys.version",t),new Error("invalid version")}var Io=5e4,ud=v([w("x"),w("y"),w("price")]),cd=v([w("accountType"),w("status"),w("multiplier"),w("validDataCount"),j(ud,Io,"DataElement")]);function ld(d,e){return[0,Io-2]}function md(d){return[0,Io-2]}function dd(d){return[0,Io-2]}function pd(d,e,t){let[n,o]=ld(e,t),i=n,r=o,a=0,u=e*d.multiplier/t;for(;i<=r;){if(a=Math.floor((r+i)/2),a===0||a>=Io-2)return[a,a,!1];let s=d.DataElement[a].x*d.multiplier/d.DataElement[a].y,c=d.DataElement[a-1].x*d.multiplier/d.DataElement[a-1].y,l=d.DataElement[a+1].x*d.multiplier/d.DataElement[a+1].y;if(u===s)return[a,a,!0];if(u===c)return[a-1,a-1,!0];if(u===l)return[a+1,a+1,!0];if(u<c)r=a-1;else{if(u>c&&u<s)return[a-1,a,!0];if(u>s&&u<l)return[a,a+1,!0];i=a+1}}return[a,a,!1]}function ws(d,e,t){let[n,o,i]=pd(d,e,t);if(!i)return 0;if(n===o){let r=d.DataElement[n].x;return e*d.multiplier/r}else{let r=d.DataElement[n].x,a=d.DataElement[n].y,u=d.DataElement[o].x,s=d.DataElement[o].y,c=t*(u*a-r*s),l=r*c,m=(u-r)*(e*a-r*t)*s,p=l+m;return e*d.multiplier*c/p}}function ho(d,e,t){return e*d.multiplier/t}function cl(d,e,t){return e*t/d.multiplier}function fd(d,e){let[t,n]=md(e),o=t,i=n,r=0,a=e;for(;o<i;){if(r=Math.floor((i+o)/2),r<=0||r>Io-2)return[r,r,!1];let u=d.DataElement[r].x,s=d.DataElement[r-1].x,c=d.DataElement[r+1].x;if(a===u)return[r,r,!0];if(a===s)return[r-1,r-1,!0];if(a===c)return[r+1,r+1,!0];if(a<s)i=r-1;else{if(a>s&&a<u)return[r-1,r,!0];if(a>u&&a<c)return[r,r+1,!0];o=r+1}}return[r,r,!1]}function yd(d,e){let[t,n]=dd(e),o=t,i=n,r=0,a=e;for(;o<=i;){if(r=Math.floor((i+o)/2),r<=0||r>=Io-2)return[r,r,!1];let u=d.DataElement[r].y,s=d.DataElement[r-1].y,c=d.DataElement[r+1].y;if(a===u)return[r,r,!0];if(a===s)return[r-1,r-1,!0];if(a===c)return[r+1,r+1,!0];if(a<c)o=r+1;else{if(a<s&&a>u)return[r-1,r,!0];if(a<u&&a>c)return[r,r+1,!0];i=r-1}}return[r,r,!1]}function ll(d,e,t,n){let o=n?e+t:e-t,[i,r,a]=fd(d,o);if(!a)return[0,0,!1,a];if(i===r)return[d.DataElement[r].price,d.DataElement[r].y,!1,a];{let u=d.DataElement[i].x,s=d.DataElement[r].x,c=d.DataElement[i].price,l=d.DataElement[r].price,m=d.DataElement[i].y,p=d.DataElement[r].y;if(e>=u&&e<=s)return n?[l,p,!0,a]:[c,m,!0,a];{let f,y;return n?(f=c+(l-c)*(e-u)/(s-u),y=m-(o-u)*d.multiplier/l):(f=c+(l-c)*(e-u)/(s-u),y=p+(s-o)*d.multiplier/c),[f,y,!1,a]}}}function bd(d,e,t,n){let o=n?e-t:e+t,[i,r,a]=yd(d,o);if(!a)return[0,0,!1,a];if(i===r)return[d.DataElement[r].price,d.DataElement[r].x,!1,a];{let u=d.DataElement[i].x,s=d.DataElement[r].x,c=d.DataElement[i].price,l=d.DataElement[r].price,m=d.DataElement[i].y,p=d.DataElement[r].y;if(e>=p&&e<=m)return n?[l,s,!0,a]:[c,u,!0,a];{let f,y;return n?(f=c+(l-c)*(m-e)/(m-p),y=u+l*(m-o)/d.multiplier):(f=c+(l-c)*(m-e)/(m-p),y=s-c*(o-p)/d.multiplier),[f,y,!1,a]}}}function gd(d,e){let t=ll(d,e,0,!1);return t[3]?t[0]:0}function ml(d,e,t,n){let o=ws(d,e,t),i=ho(d,e,o),r=ho(d,t,o),a=ho(d,n,o),u=!0,[s,c,l,m]=ll(d,i,a,u);if(!m)return 0;if(l)return n*d.multiplier/s;{let p=r-c;return cl(d,p,o)}}function dl(d,e,t,n){let o=ws(d,e,t),i=ho(d,e,o),r=ho(d,t,o),a=ho(d,n,o),u=!1,[s,c,l,m]=bd(d,r,a,u);if(!m)return 0;if(l)return n*s/d.multiplier;{let p=i-c;return cl(d,p,o)}}function Pd(d){let e=cd.decode(d);return{accountType:e.accountType.toNumber(),status:e.status.toNumber(),multiplier:e.multiplier.toNumber(),validDataCount:e.validDataCount.toNumber(),DataElement:e.DataElement.map(t=>({x:t.x.toNumber(),y:t.y.toNumber(),price:t.price.toNumber()}))}}function pl(d,e,t,n){let o=gd(d,ho(d,e,ws(d,e,t)))/d.multiplier;return n?o:1/o}var Er=class{constructor({connection:e,modelDataPubKey:t=lo}){this._layoutData={accountType:0,status:0,multiplier:0,validDataCount:0,DataElement:[]};this.connection=e,this.modelDataPubKey=t}get stableModelData(){return this._layoutData}async initStableModelLayout(){if(this._layoutData.validDataCount===0&&this.connection){let e=await this.connection.getAccountInfo(this.modelDataPubKey);e&&(this._layoutData=Pd(e==null?void 0:e.data))}}};var Dn=require("@solana/spl-token"),Me=require("@solana/web3.js"),xo=te(require("bn.js"));var Jn=v([w(),w("epoch"),W("curveType"),at("index"),w("migrateFee"),w("tradeFeeRate"),w("maxShareFeeRate"),w("minSupplyA"),w("maxLockRate"),w("minSellRateA"),w("minMigrateRateA"),w("minFundRaisingB"),M("mintB"),M("protocolFeeOwner"),M("migrateFeeOwner"),M("migrateToAmmWallet"),M("migrateToCpmmWallet"),j(w(),16)]),Ad=v([w("totalLockedAmount"),w("cliffPeriod"),w("unlockPeriod"),w("startTime"),w("totalAllocatedShare")]),An=v([w(),w("epoch"),W("bump"),W("status"),W("mintDecimalsA"),W("mintDecimalsB"),W("migrateType"),w("supply"),w("totalSellA"),w("virtualA"),w("virtualB"),w("realA"),w("realB"),w("totalFundRaisingB"),w("protocolFee"),w("platformFee"),w("migrateFee"),Ad.replicate("vestingSchedule"),M("configId"),M("platformId"),M("mintA"),M("mintB"),M("vaultA"),M("vaultB"),M("creator"),W("mintProgramFlag"),W("cpmmCreatorFeeOn"),w("platformVestingShare"),j(W(),54)]),Fw=v([w(),w("epoch"),M("poolId"),M("beneficiary"),w("claimedAmount"),w("tokenShareAmount"),j(w(),8)]),fl=v([W("migrateType"),W("migrateCpmmFeeOn"),w("supply"),w("totalSellA"),w("totalFundRaisingB"),w("totalLockedAmount"),w("cliffPeriod"),w("unlockPeriod")]),wd=v([w("epoch"),W("index"),M("configId"),fl.replicate("bondingCurveParam"),j(w(),50)]),wn=v([w(),w("epoch"),M("platformClaimFeeWallet"),M("platformLockNftWallet"),w("platformScale"),w("creatorScale"),w("burnScale"),w("feeRate"),j(W(),64,"name"),j(W(),256,"web"),j(W(),256,"img"),M("cpConfigId"),w("creatorFeeRate"),M("transferFeeExtensionAuth"),M("platformVestingWallet"),w("platformVestingScale"),M("platformCpCreator"),W("restrictGlobalConfig"),j(W(),107),Tu(wd,"platformCurve")]);var kd=Buffer.from("vault_auth_seed","utf8"),Td=Buffer.from("global_config","utf8"),hd=Buffer.from("pool_vesting","utf8"),Id=Buffer.from("platform_config","utf8"),Bd=Buffer.from("platform_fee_vault_auth_seed","utf8"),xd=Buffer.from("creator_fee_vault_auth_seed","utf8"),Dw=Buffer.from("platform_global_access","utf8"),Sd=Buffer.from("platform_allow_config","utf8");function Gt(d){return de([kd],d)}function ks(d,e,t,n){return de([Td,e.toBuffer(),Kd(t),xr(n)],d)}function Uo(d,e,t){return de([Sr,e.toBuffer(),t.toBuffer()],d)}function Ts(d,e,t){return de([Qa,e.toBuffer(),t.toBuffer()],d)}function Bo(d){return de([Buffer.from("__event_authority","utf8")],d)}function Kd(d){let e=new ArrayBuffer(1);return new DataView(e).setUint8(0,d),new Uint8Array(e)}function hs(d,e){return de([Id,e.toBuffer()],d)}function Go(d,e,t){return de([hd,e.toBuffer(),t.toBuffer()],d)}function kn(d,e,t){return de([e.toBuffer(),t.toBuffer()],d)}function Is(d){return de([Bd],d)}function Tn(d,e,t){return de([e.toBuffer(),t.toBuffer()],d)}function Bs(d){return de([xd],d)}function Wi(d,e,t){return de([Sd,e.toBuffer(),t.toBuffer()],d)}var Et={initialize:Buffer.from([175,175,109,31,13,152,155,237]),initializeV2:Buffer.from([67,153,175,39,218,16,38,32]),buyExactIn:Buffer.from([250,234,13,123,213,156,19,236]),buyExactOut:Buffer.from([24,211,116,40,105,3,153,56]),sellExactIn:Buffer.from([149,39,222,155,211,124,152,26]),sellExactOut:Buffer.from([95,200,71,34,8,9,11,166]),createVestingAccount:Buffer.from([129,178,2,13,217,172,230,218]),claimVestedToken:Buffer.from([49,33,104,30,189,157,79,35]),createPlatformConfig:Buffer.from([176,90,196,175,253,113,220,20]),claimPlatformFee:Buffer.from([156,39,208,135,76,237,61,72]),updatePlaformConfig:Buffer.from([195,60,76,129,146,45,67,143]),initializeWithToken2022:Buffer.from([37,190,126,222,44,154,171,17]),claimPlatformFeeFromVault:Buffer.from([117,241,198,168,248,218,80,29]),claimCreatorFee:Buffer.from([26,97,138,203,132,171,141,252]),updatePlatformCurveParam:Buffer.from([138,144,138,250,220,128,4,57]),removePlatformCurveParam:Buffer.from([27,30,62,169,93,224,24,145]),createPlatformVestingAccount:Buffer.from([146,71,173,69,98,19,15,106]),createPlatformAllowConfig:Buffer.from([69,71,168,7,214,250,107,102]),closePlatformAllowConfig:Buffer.from([82,205,36,216,16,6,240,215])};function yl(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A,k,h,P,T){let I=v([W("decimals"),Ht("name"),Ht("symbol"),Ht("uri")]),x=v([w("totalLockedAmount"),w("cliffPeriod"),w("unlockPeriod"),W("cpmmCreatorFeeOn")]),S=v([W("index"),w("supply"),w("totalFundRaisingB"),W("migrateType")]),B=v([W("index"),w("supply"),w("totalSellA"),w("totalFundRaisingB"),W("migrateType")]),R=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!0,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:Dn.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:Bn,isSigner:!1,isWritable:!1},{pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:vt,isSigner:!1,isWritable:!1},{pubkey:Bo(d).publicKey,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1}];T&&R.push({pubkey:T,isSigner:!1,isWritable:!1});let L=Buffer.alloc(Buffer.from(f,"utf-8").length+Buffer.from(y,"utf-8").length+Buffer.from(b,"utf-8").length+4*3+1),O=Buffer.alloc(x.span),C=Buffer.alloc(g.type==="ConstantCurve"?B.span:S.span);return I.encode({decimals:p,name:f,symbol:y,uri:b},L),g.type==="ConstantCurve"?B.encode(V(N({index:0},g),{migrateType:g.migrateType==="amm"?0:1}),C):g.type==="FixedCurve"?S.encode(V(N({index:1},g),{migrateType:g.migrateType==="amm"?0:1}),C):g.type==="LinearCurve"&&S.encode(V(N({index:2},g),{migrateType:g.migrateType==="amm"?0:1}),C),x.encode({totalLockedAmount:A,cliffPeriod:k,unlockPeriod:h,cpmmCreatorFeeOn:P},O),new Me.TransactionInstruction({keys:R,programId:d,data:Buffer.from([...Et.initializeV2,...L,...C,...O])})}function bl(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A,k,h,P,T){let I=v([W("decimals"),Ht("name"),Ht("symbol"),Ht("uri")]),x=v([w("totalLockedAmount"),w("cliffPeriod"),w("unlockPeriod"),W("cpmmCreatorFeeOn"),W("transferFeeExtensionParamsOption"),v([at("transferFeeBasePoints"),w("maxinumFee")]).replicate("transferFeeExtensionParams")]),S=v([W("index"),w("supply"),w("totalFundRaisingB"),W("migrateType")]),B=v([W("index"),w("supply"),w("totalSellA"),w("totalFundRaisingB"),W("migrateType")]),R=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!0,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:Dn.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:Bo(d).publicKey,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1}];T&&R.push({pubkey:T,isSigner:!1,isWritable:!1});let L=Buffer.alloc(Buffer.from(p,"utf-8").length+Buffer.from(f,"utf-8").length+Buffer.from(y,"utf-8").length+4*3+1),O=Buffer.alloc(x.span),C=Buffer.alloc(b.type==="ConstantCurve"?B.span:S.span);return I.encode({decimals:m,name:p,symbol:f,uri:y},L),b.type==="ConstantCurve"?B.encode(V(N({index:0},b),{migrateType:b.migrateType==="amm"?0:1}),C):b.type==="FixedCurve"?S.encode(V(N({index:1},b),{migrateType:b.migrateType==="amm"?0:1}),C):b.type==="LinearCurve"&&S.encode(V(N({index:2},b),{migrateType:b.migrateType==="amm"?0:1}),C),x.encode({totalLockedAmount:g,cliffPeriod:A,unlockPeriod:k,cpmmCreatorFeeOn:h,transferFeeExtensionParamsOption:P?1:0,transferFeeExtensionParams:P!=null?P:{transferFeeBasePoints:0,maxinumFee:new xo.default(0)}},O),new Me.TransactionInstruction({keys:R,programId:d,data:Buffer.from([...Et.initializeWithToken2022,...L,...C,...O])})}function qi(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A,k){let h=v([w("amountB"),w("minAmountA"),w("shareFeeRate")]),P=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:Bo(d).publicKey,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1}];k&&P.push({pubkey:k,isSigner:!1,isWritable:!0}),P.push({pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!1}),P.push({pubkey:f,isSigner:!1,isWritable:!0}),P.push({pubkey:y,isSigner:!1,isWritable:!0});let T=Buffer.alloc(h.span);return h.encode({amountB:b,minAmountA:g,shareFeeRate:A!=null?A:new xo.default(0)},T),new Me.TransactionInstruction({keys:P,programId:d,data:Buffer.from([...Et.buyExactIn,...T])})}function gl(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A,k){let h=v([w("amountA"),w("maxAmountB"),w("shareFeeRate")]),P=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:Bo(d).publicKey,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1}];k&&P.push({pubkey:k,isSigner:!1,isWritable:!0}),P.push({pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!1}),P.push({pubkey:f,isSigner:!1,isWritable:!0}),P.push({pubkey:y,isSigner:!1,isWritable:!0});let T=Buffer.alloc(h.span);return h.encode({amountA:b,maxAmountB:g,shareFeeRate:A!=null?A:new xo.default(0)},T),new Me.TransactionInstruction({keys:P,programId:d,data:Buffer.from([...Et.buyExactOut,...T])})}function Dr(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A,k){let h=v([w("amountA"),w("minAmountB"),w("shareFeeRate")]),P=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:Bo(d).publicKey,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1}];k&&P.push({pubkey:k,isSigner:!1,isWritable:!0}),P.push({pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!1}),P.push({pubkey:f,isSigner:!1,isWritable:!0}),P.push({pubkey:y,isSigner:!1,isWritable:!0});let T=Buffer.alloc(h.span);return h.encode({amountA:b,minAmountB:g,shareFeeRate:A!=null?A:new xo.default(0)},T),new Me.TransactionInstruction({keys:P,programId:d,data:Buffer.from([...Et.sellExactIn,...T])})}function Pl(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f,y,b,g,A,k){let h=v([w("amountB"),w("maxAmountA"),w("shareFeeRate")]),P=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:Bo(d).publicKey,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1}];k&&P.push({pubkey:k,isSigner:!1,isWritable:!0}),P.push({pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!1}),P.push({pubkey:f,isSigner:!1,isWritable:!0}),P.push({pubkey:y,isSigner:!1,isWritable:!0});let T=Buffer.alloc(h.span);return h.encode({amountB:b,maxAmountA:g,shareFeeRate:A!=null?A:new xo.default(0)},T),new Me.TransactionInstruction({keys:P,programId:d,data:Buffer.from([...Et.sellExactOut,...T])})}function xs(d,e,t,n,o,i,r,a,u){let s=v([]),c=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:Dn.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}],l=Buffer.alloc(s.span);return s.encode({},l),new Me.TransactionInstruction({keys:c,programId:d,data:Buffer.from([...Et.claimVestedToken,...l])})}function Ss(d,e,t,n,o,i){let r=v([w("shareAmount")]),a=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!1}],u=Buffer.alloc(r.span);return r.encode({shareAmount:i},u),new Me.TransactionInstruction({keys:a,programId:d,data:Buffer.from([...Et.createVestingAccount,...u])})}function Ks(d,e,t,n,o,i,r,a,u){let s=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!0},{pubkey:Dn.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!0}];return new Me.TransactionInstruction({keys:s,programId:d,data:Et.claimPlatformFee})}function Al(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f){let y=v([w("platformScale"),w("creatorScale"),w("burnScale"),w("feeRate"),Ht("name"),Ht("web"),Ht("img"),w("creatorFeeRate"),w("platformVestingScale")]),b=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1}],g=Buffer.alloc(8*6+Buffer.from(l,"utf-8").length+Buffer.from(m,"utf-8").length+Buffer.from(p,"utf-8").length+4*3);return y.encode({platformScale:u.platformScale,creatorScale:u.creatorScale,burnScale:u.burnScale,feeRate:s,name:l,web:m,img:p,creatorFeeRate:c,platformVestingScale:f},g),new Me.TransactionInstruction({keys:b,programId:d,data:Buffer.from([...Et.createPlatformConfig,...g])})}function wl(d,e,t,n){let o=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0}],i;if(n.type==="updateClaimFeeWallet"){let r=v([W("index"),M("value")]);i=Buffer.alloc(r.span),r.encode({index:0,value:n.value},i)}else if(n.type==="updateLockNftWallet"){let r=v([W("index"),M("value")]);i=Buffer.alloc(r.span),r.encode({index:1,value:n.value},i)}else if(n.type==="migrateCpLockNftScale"){let r=v([W("index"),w("platformScale"),w("creatorScale"),w("burnScale")]);i=Buffer.alloc(r.span),r.encode(N({index:2},n.value),i)}else if(n.type==="updateFeeRate"){let r=v([W("index"),w("value")]);i=Buffer.alloc(r.span),r.encode({index:3,value:n.value},i)}else if(n.type==="updateImg"||n.type==="updateName"||n.type==="updateWeb"){let r=v([W("index"),Ht("value")]);i=Buffer.alloc(Buffer.from(n.value,"utf-8").length+4+1*1),n.type==="updateName"?r.encode({index:4,value:n.value},i):n.type==="updateWeb"?r.encode({index:5,value:n.value},i):n.type==="updateImg"&&r.encode({index:6,value:n.value},i)}else if(n.type==="updateCpConfigId"){o.push({pubkey:n.value,isSigner:!1,isWritable:!1});let r=v([W("index")]);i=Buffer.alloc(r.span),r.encode({index:7},i)}else if(n.type==="updateAll"){o.push({pubkey:n.value.cpConfigId,isSigner:!1,isWritable:!1});let r=v([W("index"),M("platformClaimFeeWallet"),M("platformLockNftWallet"),w("platformScale"),w("creatorScale"),w("burnScale"),w("feeRate"),Ht("name"),Ht("web"),Ht("img"),M("transferFeeExtensionAuth"),w("creatorFeeRate"),w("platformVestingScale"),M("platformVestingWallet")]);i=Buffer.alloc(1+32+32+32+8*5+4*3+Buffer.from(n.value.name,"utf-8").length+Buffer.from(n.value.web,"utf-8").length+Buffer.from(n.value.img,"utf-8").length+32+8),r.encode({index:8,platformClaimFeeWallet:n.value.platformClaimFeeWallet,platformLockNftWallet:n.value.platformLockNftWallet,platformVestingWallet:n.value.platformVestingWallet,platformScale:n.value.migrateCpLockNftScale.platformScale,creatorScale:n.value.migrateCpLockNftScale.creatorScale,burnScale:n.value.migrateCpLockNftScale.burnScale,feeRate:n.value.feeRate,name:n.value.name,web:n.value.web,img:n.value.img,transferFeeExtensionAuth:n.value.transferFeeExtensionAuth,creatorFeeRate:n.value.creatorFeeRate,platformVestingScale:n.value.platformVestingScale},i)}else if(n.type==="updateVestingWallet"){let r=v([W("index"),M("value")]);i=Buffer.alloc(r.span),r.encode({index:9,value:n.value},i)}else if(n.type==="updatePlatformVestingScale"){let r=v([W("index"),w("value")]);i=Buffer.alloc(r.span),r.encode({index:10,value:n.value},i)}else if(n.type==="updatePlatformCpCreator"){let r=v([W("index"),M("value")]);i=Buffer.alloc(r.span),r.encode({index:11,value:n.value},i)}else if(n.type==="updateRestrictGlobalConfig"){let r=v([W("index"),w("value")]);i=Buffer.alloc(r.span),r.encode({index:12,value:n.value},i)}else throw Error("updateInfo params type error");return new Me.TransactionInstruction({keys:o,programId:d,data:Buffer.from([...Et.updatePlaformConfig,...i])})}function Cs(d,e,t,n,o,i,r,a){let u=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:Dn.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}];return new Me.TransactionInstruction({keys:u,programId:d,data:Et.claimPlatformFeeFromVault})}function Rs(d,e,t,n,o,i,r){let a=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:Dn.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}];return new Me.TransactionInstruction({keys:a,programId:d,data:Et.claimCreatorFee})}var Hw=new xo.default("18446744073709551615");function kl(d,e,t,n,o,i){let r=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new Me.TransactionInstruction({keys:r,programId:d,data:Et.createPlatformVestingAccount})}function Tl(d,e,t,n,o){let i=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:Me.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new Me.TransactionInstruction({keys:i,programId:d,data:Et.createPlatformAllowConfig})}function hl(d,e,t,n,o){let i=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0}];return new Me.TransactionInstruction({keys:i,programId:d,data:Et.closePlatformAllowConfig})}var zo=require("@solana/spl-token");function Cd(d,e){return d>>e&1?zo.TOKEN_2022_PROGRAM_ID:zo.TOKEN_PROGRAM_ID}function Wr(d){return Cd(d,0)}function Il({mintAProgram:d,mintBProgram:e}){return(d.equals(zo.TOKEN_2022_PROGRAM_ID)?1<<0:0)|(e.equals(zo.TOKEN_2022_PROGRAM_ID)?1<<1:0)}var Ui=te(require("bn.js")),Xo=te(require("decimal.js"));var eo=class{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){throw Error()}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:o}){throw Error()}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){throw Error()}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:o,migrateFee:i,decimalA:r,decimalB:a}){throw Error()}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){throw Error()}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:o,migrateFee:i}){throw Error()}static buyExactIn({poolInfo:e,amount:t}){throw Error()}static buyExactOut({poolInfo:e,amount:t}){throw Error()}static sellExactIn({poolInfo:e,amount:t}){throw Error()}static sellExactOut({poolInfo:e,amount:t}){throw Error()}};var qr=class extends eo{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new Xo.default(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:o}){return new Xo.default(t.toString()).div(e.toString()).mul(10**(n-o))}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new Xo.default(e.virtualB.add(e.realB).toString()).div(e.virtualA.sub(e.realA).toString()).mul(10**(t-n))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:o,migrateFee:i,decimalA:r,decimalB:a}){return new Xo.default(o.sub(i).toString()).div(e.sub(t).sub(n).toString()).mul(10**(r-a))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){let o=e.totalSellA.sub(e.realA),i=e.totalFundRaisingB.sub(e.realB);return new Xo.default(e.virtualB.add(e.realB.add(i)).toString()).div(e.virtualA.sub(e.realA.add(o)).toString()).mul(10**(t-n))}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:o,migrateFee:i}){if(e.lte(n))throw Error("supply need gt total sell");let r=e.sub(n).sub(o);if(r.lte(new Ui.default(0)))throw Error("supplyMinusSellLocked <= 0");let a=t.sub(i);if(a.lte(new Ui.default(0)))throw Error("tfMinusMf <= 0");let u=a.mul(n).mul(n).div(r),s=a.mul(n).div(r).sub(t),c=u.div(s),l=t.mul(t).div(s);if(c.lt(new Ui.default(0))||l.lt(new Ui.default(0)))throw Error("invalid input 0");return{a:c,b:l,c:n}}static buyExactIn({poolInfo:e,amount:t}){return this.getAmountOut({amountIn:t,inputReserve:e.virtualB.add(e.realB),outputReserve:e.virtualA.sub(e.realA)})}static buyExactOut({poolInfo:e,amount:t}){return this.getAmountIn({amountOut:t,inputReserve:e.virtualB.add(e.realB),outputReserve:e.virtualA.sub(e.realA)})}static sellExactIn({poolInfo:e,amount:t}){return this.getAmountOut({amountIn:t,inputReserve:e.virtualA.sub(e.realA),outputReserve:e.virtualB.add(e.realB)})}static sellExactOut({poolInfo:e,amount:t}){return this.getAmountIn({amountOut:t,inputReserve:e.virtualA.sub(e.realA),outputReserve:e.virtualB.add(e.realB)})}static getAmountOut({amountIn:e,inputReserve:t,outputReserve:n}){let o=e.mul(n),i=t.add(e);return o.div(i)}static getAmountIn({amountOut:e,inputReserve:t,outputReserve:n}){let o=t.mul(e),i=n.sub(e);return So(o,i)}};var Xt=te(require("bn.js")),Os=te(require("decimal.js"));var Gi=te(require("bn.js")),Yo=te(require("decimal.js"));var Ur=class extends eo{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new Yo.default(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:o}){return new Yo.default(t.toString()).div(e.toString()).mul(10**(n-o))}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new Yo.default(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:o,migrateFee:i,decimalA:r,decimalB:a}){return new Yo.default(o.sub(i).toString()).div(e.sub(t).sub(n).toString()).mul(10**(r-a))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){let o=e.totalSellA.sub(e.realA),i=e.totalFundRaisingB.sub(e.realB);return new Yo.default(e.virtualB.add(e.realB).add(i).toString()).div(e.virtualA.sub(e.realA).add(o).toString()).mul(10**(t-n))}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:o,migrateFee:i}){let r=e.sub(o);if(r.lte(new Gi.default(0)))throw Error("invalid input 1");let a=new Gi.default(2).mul(t).sub(i),s=t.mul(r).div(a);if(s.lt(new Gi.default(0))||t.lt(new Gi.default(0)))throw Error("invalid input 0");return{a:s,b:t,c:s}}static buyExactIn({poolInfo:e,amount:t}){return this.getAmountOut({amountIn:t,initInput:e.virtualB,initOutput:e.virtualA})}static buyExactOut({poolInfo:e,amount:t}){return this.getAmountIn({amountOut:t,initInput:e.virtualB,initOutput:e.virtualA})}static sellExactIn({poolInfo:e,amount:t}){return this.getAmountOut({amountIn:t,initInput:e.virtualA,initOutput:e.virtualB})}static sellExactOut({poolInfo:e,amount:t}){return this.getAmountIn({amountOut:t,initInput:e.virtualA,initOutput:e.virtualB})}static getAmountOut({amountIn:e,initInput:t,initOutput:n}){return n.mul(e).div(t)}static getAmountIn({amountOut:e,initInput:t,initOutput:n}){let o=t.mul(e);return So(o,n)}};var zt=te(require("bn.js")),to=te(require("decimal.js"));var Ls=te(require("bn.js")),Gr=te(require("decimal.js")),zi=class{static _multipler(e){return new Gr.default(10).pow(e)}static getPrice({priceX64:e,decimalA:t,decimalB:n}){return new Gr.default(e.toString()).div(this._Q64).mul(this._multipler(t)).div(this._multipler(n))}static getPriceX64({price:e,decimalA:t,decimalB:n}){let o=e.mul(this._multipler(n)).div(this._multipler(t));return new Ls.default(o.mul(this._Q64).toFixed(0))}};zi._Q64=new Gr.default(new Ls.default(1).shln(64).toString());var zr=class extends eo{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new to.default(0)}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:o}){return new to.default(0)}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new to.default(e.virtualA.mul(e.realA).toString()).div(zi._Q64).mul(10**(t-n))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:o,migrateFee:i,decimalA:r,decimalB:a}){return new to.default(o.sub(i).toString()).div(e.sub(t).sub(n).toString()).mul(10**(r-a))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){let o=e.totalSellA.sub(e.realA),i=e.totalFundRaisingB.sub(e.realB);return new to.default(e.virtualB.add(e.realB).add(i).toString()).div(e.virtualA.sub(e.realA).add(o).toString()).mul(10**(t-n))}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:o,migrateFee:i}){let r=e.sub(o);if(r.lte(new zt.default(0)))throw Error("supplyMinusLocked need gt 0");let a=t.mul(new zt.default(3)).sub(i),s=t.mul(new zt.default(2)).mul(r).div(a),c=s.mul(s),l=t.mul(new zt.default(2)).mul(De).div(c);if(!l.gt(new zt.default(0)))throw Error("a need gt 0");if(!Sn.gt(l))throw Error("a need lt u64 max");if(l.lt(new zt.default(0))||s.lt(new zt.default(0)))throw Error("invalid input 0");return{a:l,b:new zt.default(0),c:s}}static buyExactIn({poolInfo:e,amount:t}){let n=e.realB.add(t),o=new zt.default(2).mul(n).mul(De).div(e.virtualA);return new zt.default(new to.default(o.toString()).sqrt().toFixed(0)).sub(e.realA)}static buyExactOut({poolInfo:e,amount:t}){let n=e.realA.add(t),o=n.mul(n);return So(e.virtualA.mul(o),new zt.default(2).mul(De)).sub(e.realB)}static sellExactIn({poolInfo:e,amount:t}){let n=e.realA.sub(t),o=n.mul(n),i=So(e.virtualA.mul(o),new zt.default(2).mul(De));return e.realB.sub(i)}static sellExactOut({poolInfo:e,amount:t}){let n=e.realB.sub(t),o=new zt.default(2).mul(n).mul(De).div(e.virtualA),i=new zt.default(new to.default(o.toString()).sqrt().toFixed(0));return e.realA.sub(i)}};var Nt=class{static getPoolCurvePointByPoolInfo({curveType:e,pointCount:t,poolInfo:n}){return this.getPoolCurvePointByInit({curveType:e,pointCount:t,supply:n.supply,totalFundRaising:n.totalFundRaisingB,totalSell:n.totalSellA,totalLockedAmount:n.vestingSchedule.totalLockedAmount,migrateFee:n.migrateFee,decimalA:n.mintDecimalsA,decimalB:n.mintDecimalsB})}static getPoolCurvePointByInit({curveType:e,pointCount:t,supply:n,totalFundRaising:o,totalSell:i,totalLockedAmount:r,migrateFee:a,decimalA:u,decimalB:s}){if(t<3)throw Error("point count < 3");let c=this.getCurve(e),l=c.getInitParam({supply:n,totalFundRaising:o,totalSell:i,totalLockedAmount:r,migrateFee:a}),m=c.getPoolInitPriceByInit(V(N({},l),{decimalA:u,decimalB:s})),p=o.div(new Xt.default(t-1)),f=new Xt.default(0),y=[{price:m,totalSellSupply:0}],{a:b,b:g}=l,A=f,k=f;for(let h=1;h<t;h++){let P=h!==t-1?p:o.sub(k),T=this.buyExactIn({poolInfo:{virtualA:b,virtualB:g,realA:A,realB:k,totalFundRaisingB:o,totalSellA:i},amountB:P,protocolFeeRate:f,platformFeeRate:f,curveType:e,shareFeeRate:f,creatorFeeRate:f,transferFeeConfigA:void 0,transferFeeConfigB:void 0,slot:0});A=A.add(T.amountA.amount),k=k.add(T.amountB);let I=this.getPrice({poolInfo:{virtualA:b,virtualB:g,realA:A,realB:k},decimalA:u,decimalB:s,curveType:e});y.push({price:I,totalSellSupply:new Os.default(A.toString()).div(10**u).toNumber()})}return y}static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n,curveType:o}){return this.getCurve(o).getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n})}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:o,curveType:i}){return this.getCurve(i).getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:o})}static getPrice({poolInfo:e,curveType:t,decimalA:n,decimalB:o}){return this.getCurve(t).getPoolPrice({poolInfo:e,decimalA:n,decimalB:o})}static getEndPrice({poolInfo:e,curveType:t,decimalA:n,decimalB:o}){return this.getCurve(t).getPoolPrice({poolInfo:e,decimalA:n,decimalB:o})}static getPoolEndPriceReal({poolInfo:e,curveType:t,decimalA:n,decimalB:o}){return this.getCurve(t).getPoolEndPriceReal({poolInfo:e,decimalA:n,decimalB:o})}static checkParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:o,decimals:i,config:r,migrateType:a}){if(Number(i)!==6)throw Error("decimals = 6");if(e.mul(r.maxLockRate).div(Je).lt(o))throw Error("total lock amount gte max lock amount");if(e.lt(r.minSupplyA.mul(new Xt.default(10**i))))throw Error("supply lt min supply");let s=e.mul(r.minSellRateA).div(Je);if(n.lt(s))throw Error("invalid input");if(t.lt(r.minFundRaisingB))throw Error("total fund raising lt min fund raising");let c=e.sub(n).sub(o),l=e.mul(r.minMigrateRateA).div(Je);if(c.lt(l))throw Error("migrate lt min migrate amoount");let m=e.sub(n).sub(o),p=new Xt.default(new Os.default(m.mul(t).toString()).sqrt().toFixed(0));if(a==="amm"){let f=new Xt.default(10).pow(new Xt.default(i));if(p.lte(f))throw Error("check migrate lp error")}else if(a==="cpmm"){let f=new Xt.default(100);if(p.lte(f))throw Error("check migrate lp error")}else throw Error("migrate type error")}static buyExactIn({poolInfo:e,amountB:t,protocolFeeRate:n,platformFeeRate:o,curveType:i,shareFeeRate:r,creatorFeeRate:a,transferFeeConfigA:u,transferFeeConfigB:s,slot:c}){var x;let l=Xi(t,s,c),m=t.sub((x=l.fee)!=null?x:new Xt.default(0)),p=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a}),f=this.calculateFee({amount:m,feeRate:p}),y=m.sub(f),b=this.getCurve(i),g=b.buyExactIn({poolInfo:e,amount:y}),A=e.totalSellA.sub(e.realA),k,h,P,T;if(g.gt(A)){k=A;let S=b.buyExactOut({poolInfo:e,amount:k}),B=this.calculatePreFee({postFeeAmount:S,feeRate:p});P=B.sub(S);let R=Ho(B,s,c);h=R.amount,T=R.fee}else k=g,h=t,P=f,T=l.fee;let I=this.splitFee({totalFee:P,protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a});return{amountA:Xi(k,u,c),amountB:h,splitFee:I,transferFeeB:T}}static buyExactOut({poolInfo:e,amountA:t,protocolFeeRate:n,platformFeeRate:o,curveType:i,shareFeeRate:r,creatorFeeRate:a,transferFeeConfigA:u,transferFeeConfigB:s,slot:c}){let l=e.totalSellA.sub(e.realA),m=Ho(t,u,c),p=m.fee?m.amount.add(m.fee):m.amount;t.gt(l)&&(p=l);let y=this.getCurve(i).buyExactOut({poolInfo:e,amount:p}),b=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a}),g=this.calculatePreFee({postFeeAmount:y,feeRate:b}),A=g.sub(y),k=Ho(g,s,c),h=this.splitFee({totalFee:A,protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a});return{amountA:m,amountB:k.amount,splitFee:h,transferFeeB:k.fee}}static sellExactIn({poolInfo:e,amountA:t,protocolFeeRate:n,platformFeeRate:o,curveType:i,shareFeeRate:r,creatorFeeRate:a,transferFeeConfigA:u,transferFeeConfigB:s,slot:c}){var k;let l=this.getCurve(i),m=Xi(t,u,c),p=m.fee?m.amount.sub(m.fee):m.amount,f=l.sellExactIn({poolInfo:e,amount:p}),y=this.calculateFee({amount:f,feeRate:this.totalFeeRate({protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a})}),b=this.splitFee({totalFee:y,protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a}),g=f.sub(y),A=Xi(g,s,c);return{amountA:m,amountB:g.sub((k=A.fee)!=null?k:new Xt.default(0)),splitFee:b,transferFeeB:A.fee}}static sellExactOut({poolInfo:e,amountB:t,protocolFeeRate:n,platformFeeRate:o,curveType:i,shareFeeRate:r,creatorFeeRate:a,transferFeeConfigA:u,transferFeeConfigB:s,slot:c}){let l=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a}),m=Ho(t,s,c),p=m.amount,f=this.calculatePreFee({postFeeAmount:p,feeRate:l});if(e.realB.lt(f))throw Error("Insufficient liquidity");let y=f.sub(p),g=Nt.getCurve(i).sellExactOut({poolInfo:e,amount:f});if(g.gt(e.realA))throw Error();let A=this.splitFee({totalFee:y,protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a});return{amountA:Ho(g,u,c),amountB:t,splitFee:A,transferFeeB:m.fee}}static splitFee({totalFee:e,protocolFeeRate:t,platformFeeRate:n,shareFeeRate:o,creatorFeeRate:i}){let r=this.totalFeeRate({protocolFeeRate:t,platformFeeRate:n,shareFeeRate:o,creatorFeeRate:i}),a=r.isZero()?new Xt.default(0):e.mul(n).div(r),u=r.isZero()?new Xt.default(0):e.mul(o).div(r),s=r.isZero()?new Xt.default(0):e.mul(i).div(r),c=e.sub(a).sub(u).sub(s);return{platformFee:a,shareFee:u,protocolFee:c,creatorFee:s}}static calculateFee({amount:e,feeRate:t}){return _i(e,t,Je)}static calculatePreFee({postFeeAmount:e,feeRate:t}){if(t.isZero())return e;let n=e.mul(Je),o=Je.sub(t);return n.add(o).sub(new Xt.default(1)).div(o)}static totalFeeRate({protocolFeeRate:e,platformFeeRate:t,shareFeeRate:n,creatorFeeRate:o}){if(e.add(t).add(n).add(o).gt(new Xt.default(1e6)))throw Error("total fee rate gt 1_000_000");return e.add(t).add(n).add(o)}static getCurve(e){switch(e){case 0:return qr;case 1:return Ur;case 2:return zr}throw Error("find curve error")}};var ee=require("@solana/spl-token"),ce=te(require("bn.js")),oo=require("@solana/web3.js");var $t=te(require("decimal.js")),Xr={initPriceX64:new ce.default("515752397214619"),supply:new ce.default(1e15),totalSellA:new ce.default(7931e11),totalFundRaisingB:new ce.default(85e9),totalFundRaisingBUSD:new ce.default(125e8),totalLockedAmount:new ce.default("0"),cliffPeriod:new ce.default("0"),unlockPeriod:new ce.default("0"),decimals:6,virtualA:new ce.default("1073471847374405"),virtualB:new ce.default("30050573465"),realA:new ce.default(0),realB:new ce.default(0),protocolFee:new ce.default(0),platformId:new oo.PublicKey("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),vestingSchedule:{totalLockedAmount:new ce.default(0),cliffPeriod:new ce.default(0),unlockPeriod:new ce.default(0),startTime:new ce.default(0),totalAllocatedShare:new ce.default(0)}},no=new ce.default(1e4);var Yi=class extends ot{constructor(e){super(e)}async getMintBTokenInfo({mintB:e,mintBProgram:t,transferFeeConfigB:n,skipCheckMintB:o}){if(e.equals(ee.NATIVE_MINT))return{mintBProgram:ee.TOKEN_PROGRAM_ID,transferFeeConfigB:void 0};if(n)return{mintBProgram:t!=null?t:ee.TOKEN_2022_PROGRAM_ID,transferFeeConfigB:n};if(o||(t==null?void 0:t.equals(ee.TOKEN_PROGRAM_ID)))return{mintBProgram:t!=null?t:ee.TOKEN_PROGRAM_ID,transferFeeConfigB:void 0};let i=await this.scope.connection.getAccountInfo(e);return!i||!i.owner.equals(ee.TOKEN_2022_PROGRAM_ID)?{mintBProgram:t!=null?t:ee.TOKEN_PROGRAM_ID,transferFeeConfigB:void 0}:{mintBProgram:i.owner,transferFeeConfigB:(0,ee.getTransferFeeConfig)((0,ee.unpackMint)(e,i,i.owner))||void 0}}async createLaunchpad(F){var E=F,{programId:e=mt,authProgramId:t,platformId:n=Xr.platformId,mintA:o,decimals:i=6,mintBDecimals:r=9,name:a,symbol:u,uri:s,migrateType:c,configId:l,configInfo:m,txVersion:p,computeBudgetConfig:f,txTipConfig:y,feePayer:b,buyAmount:g,minMintAAmount:A,slippage:k,associatedOnly:h=!0,checkCreateATAOwner:P=!1,extraSigners:T,token2022:I,transferFeeExtensionParams:x,creatorFeeOn:S=0,platformAllowConfig:B,mintBProgram:R,transferFeeConfigB:L,skipCheckMintB:O}=E,C=Qe(E,["programId","authProgramId","platformId","mintA","decimals","mintBDecimals","name","symbol","uri","migrateType","configId","configInfo","txVersion","computeBudgetConfig","txTipConfig","feePayer","buyAmount","minMintAAmount","slippage","associatedOnly","checkCreateATAOwner","extraSigners","token2022","transferFeeExtensionParams","creatorFeeOn","platformAllowConfig","mintBProgram","transferFeeConfigB","skipCheckMintB"]);var Gs,zs,Xs,Ys,Hs,Qs,Zs,js,$s,Js,eu;let _=this.createTxBuilder(b);t=t!=null?t:Gt(e).publicKey,I=!!x,I&&(c="cpmm");let z=m;if(!z&&l){let On=await this.scope.connection.getAccountInfo(l);On&&(z=Jn.decode(On.data))}z||this.logAndCreateError("config not found");let H=z.mintB,Y=z.curveType,{mintBProgram:J,transferFeeConfigB:ie}=await this.getMintBTokenInfo({mintB:H,mintBProgram:R,transferFeeConfigB:L,skipCheckMintB:O}),{publicKey:Q}=Uo(e,o,H),{publicKey:ge}=Ts(e,Q,o),{publicKey:re}=Ts(e,Q,H),{publicKey:ke}=_n(o);this.logDebug(`create token: ${o.toBase58()}, mintB: ${H.toBase58()}, decimals A:${i}/B:${r}, config:${l.toBase58()}`),u.length>10&&this.logAndCreateError("Symbol length should shorter than 11"),s||this.logAndCreateError("uri should not empty");let Le=(await this.scope.api.fetchLaunchConfigs()).find(On=>On.key.pubKey===l.toBase58()),Ae=(Gs=C==null?void 0:C.supply)!=null?Gs:new ce.default(Le.defaultParams.supplyInit),ae=(zs=C==null?void 0:C.totalSellA)!=null?zs:new ce.default(Le.defaultParams.totalSellA),Ce=(Xs=C==null?void 0:C.totalFundRaisingB)!=null?Xs:new ce.default(Le.defaultParams.totalFundRaisingB),Mt=(Ys=C==null?void 0:C.totalLockedAmount)!=null?Ys:new ce.default(0),tt=await this.scope.connection.getAccountInfo(n);tt||this.logAndCreateError("platform id not found:",n.toString());let In=wn.decode(tt.data),Co=In.platformVestingScale,ei=In.feeRate,ti=Nt.getCurve(z.curveType).getInitParam({supply:Ae,totalFundRaising:Ce,totalSell:ae,totalLockedAmount:Mt,migrateFee:z.migrateFee}),Wt;try{Wt=await this.scope.token.getTokenInfo(H)}catch{this.logDebug("can not get mintB info from getTokenInfo")}let dn={epoch:new ce.default(896),bump:254,status:0,mintDecimalsA:i,mintDecimalsB:(Hs=Wt==null?void 0:Wt.decimals)!=null?Hs:r,supply:Ae,totalSellA:ae,mintA:new oo.PublicKey(o),mintB:H,virtualA:ti.a,virtualB:ti.b,realA:Xr.realA,realB:Xr.realB,migrateFee:z.migrateFee,migrateType:c==="amm"?0:1,protocolFee:Xr.protocolFee,platformFee:ei,platformId:n,configId:l,vaultA:ge,vaultB:re,creator:this.scope.ownerPubKey,totalFundRaisingB:Ce,vestingSchedule:{totalLockedAmount:Mt,cliffPeriod:new ce.default(0),unlockPeriod:new ce.default(0),startTime:new ce.default(0),totalAllocatedShare:new ce.default(0)},mintProgramFlag:Il({mintAProgram:I?ee.TOKEN_2022_PROGRAM_ID:ee.TOKEN_PROGRAM_ID,mintBProgram:J}),cpmmCreatorFeeOn:S,platformVestingShare:Co!=null?Co:new ce.default(0)},Ml=Nt.getCurve(z.curveType),{c:Fl}=Ml.getInitParam({supply:dn.supply,totalFundRaising:dn.totalFundRaisingB,totalLockedAmount:Mt,totalSell:z.curveType===0?dn.totalSellA:new ce.default(0),migrateFee:z.migrateFee});try{Nt.checkParam({supply:dn.supply,totalFundRaising:dn.totalFundRaisingB,totalSell:Fl,totalLockedAmount:Mt,decimals:dn.mintDecimalsA,config:z,migrateType:c}),this.logDebug("check init params success")}catch(On){this.logAndCreateError(`check create mint params failed, ${On.message}`)}_.addInstruction({instructions:[I?bl(e,b!=null?b:this.scope.ownerPubKey,this.scope.ownerPubKey,l,n,t,Q,o,H,ge,re,J,i,a,u,s||"https://",{type:Y===0?"ConstantCurve":Y===1?"FixedCurve":Y===2?"LinearCurve":"ConstantCurve",totalSellA:ae,migrateType:c,supply:Ae,totalFundRaisingB:Ce},Mt,(Qs=C==null?void 0:C.cliffPeriod)!=null?Qs:new ce.default(0),(Zs=C==null?void 0:C.unlockPeriod)!=null?Zs:new ce.default(0),S,x,B?Wi(e,n,l).publicKey:void 0):yl(e,b!=null?b:this.scope.ownerPubKey,this.scope.ownerPubKey,l,n,t,Q,o,H,ge,re,ke,J,i,a,u,s||"https://",{type:Y===0?"ConstantCurve":Y===1?"FixedCurve":Y===2?"LinearCurve":"ConstantCurve",totalSellA:ae,migrateType:c,supply:Ae,totalFundRaisingB:Ce},Mt,(js=C==null?void 0:C.cliffPeriod)!=null?js:new ce.default(0),($s=C==null?void 0:C.unlockPeriod)!=null?$s:new ce.default(0),S,B?Wi(e,n,l).publicKey:void 0)]});let oa=I?await this.scope.connection.getEpochInfo():void 0,tr=x?{epoch:BigInt((oa==null?void 0:oa.epoch)||0),maximumFee:BigInt((Js=x==null?void 0:x.maxinumFee.toString())!=null?Js:0),transferFeeBasisPoints:(eu=x==null?void 0:x.transferFeeBasePoints)!=null?eu:0}:void 0,ia={amountA:{amount:new ce.default(0),fee:void 0,expirationTime:void 0},amountB:new ce.default(0),splitFee:{platformFee:new ce.default(0),shareFee:new ce.default(0),protocolFee:new ce.default(0),creatorFee:new ce.default(0)},transferFeeB:void 0},ra;if(T!=null&&T.length&&_.addInstruction({signers:T}),!C.createOnly){let{builder:On,extInfo:vl}=await this.buyToken({programId:e,authProgramId:t,mintAProgram:I?ee.TOKEN_2022_PROGRAM_ID:void 0,mintA:o,mintB:H,mintBProgram:J,transferFeeConfigB:ie,skipCheckMintB:!0,poolInfo:dn,buyAmount:g,minMintAAmount:A,shareFeeRate:C.shareFeeRate,shareFeeReceiver:C.shareFeeReceiver,configInfo:z,platformFeeRate:ei,slippage:k,associatedOnly:h,checkCreateATAOwner:P,skipCheckMintA:!tr,transferFeeConfigA:tr?{transferFeeConfigAuthority:t,withdrawWithheldAuthority:t,withheldAmount:BigInt(0),olderTransferFee:tr,newerTransferFee:tr}:void 0,fromCreate:!0});_.addInstruction(N({},On.AllTxData)),ia=N({},vl),ra=(this.scope.cluster==="devnet"||p===1)&&C.shareFeeReceiver?[On.allInstructions[0]]:void 0}return _.addTipInstruction(y),p===0?_.sizeCheckBuildV0({computeBudgetConfig:f,swapInfo:ia,splitIns:ra,address:V(N({},dn),{poolId:Q})}):_.sizeCheckBuild({computeBudgetConfig:f,swapInfo:ia,splitIns:ra,address:V(N({},dn),{poolId:Q})})}async buyToken({programId:e=mt,authProgramId:t,mintA:n,mintAProgram:o=ee.TOKEN_PROGRAM_ID,mintB:i=ee.NATIVE_MINT,poolInfo:r,configInfo:a,platformFeeRate:u,txVersion:s,computeBudgetConfig:c,txTipConfig:l,feePayer:m,buyAmount:p,minMintAAmount:f,slippage:y,shareFeeRate:b=new ce.default(0),shareFeeReceiver:g,associatedOnly:A=!0,checkCreateATAOwner:k=!1,fromCreate:h=!1,transferFeeConfigA:P,skipCheckMintA:T=!1,mintBProgram:I,transferFeeConfigB:x,skipCheckMintB:S=!1}){var ae,Ce,Mt;p.lte(new ce.default(0))&&this.logAndCreateError("buy amount should gt 0:",p.toString());let B=this.createTxBuilder(m),{publicKey:R}=Uo(e,n,i);t=t!=null?t:Gt(e).publicKey;let L=P;if(!T)if(L)o=ee.TOKEN_2022_PROGRAM_ID;else{let tt=await this.scope.connection.getAccountInfo(n);if(tt&&tt.owner.equals(ee.TOKEN_2022_PROGRAM_ID)){o=tt.owner;let In=(0,ee.unpackMint)(n,tt,o);L=(0,ee.getTransferFeeConfig)(In)||void 0}}let{mintBProgram:O,transferFeeConfigB:C}=await this.getMintBTokenInfo({mintB:i,mintBProgram:I,transferFeeConfigB:x,skipCheckMintB:S}),F=this.scope.account.getAssociatedTokenAccount(n,o),E=i.equals(ee.NATIVE_MINT),_=h&&E,z=_?this.scope.account.getAssociatedTokenAccount(i,O):null,H=E;if(B.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,F,this.scope.ownerPubKey,n,o),..._?[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,z,this.scope.ownerPubKey,i,O),oo.SystemProgram.transfer({fromPubkey:this.scope.ownerPubKey,toPubkey:z,lamports:BigInt(p.toString())}),(0,ee.createSyncNativeInstruction)(z)]:[]]}),!_){let{account:tt,instructionParams:In}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:O,mint:i,owner:this.scope.ownerPubKey,createInfo:H?{payer:this.scope.ownerPubKey,amount:p}:void 0,skipCloseAccount:!H,notUseTokenAccount:H,associatedOnly:H?!1:A,checkCreateATAOwner:k});tt&&(z=tt),B.addInstruction(In||{})}z||this.logAndCreateError(`cannot found mintB(${i.toBase58()}) buy token accounts`,"tokenAccounts",this.scope.account.tokenAccounts);let Y=r;if(!Y){let tt=await this.scope.connection.getAccountInfo(R,{commitment:"processed"});tt||this.logAndCreateError("cannot found pool:",R.toBase58()),Y=An.decode(tt.data)}let J=a,ie=await Ge(this.scope.connection,[J?void 0:Y.configId,Y.platformId].filter(Boolean).map(tt=>({pubkey:tt})));if(!J){let tt=ie.find(In=>In.pubkey.equals(Y.configId));(!tt||!tt.accountInfo)&&this.logAndCreateError("config not found: ",Y.configId.toBase58()),J=Jn.decode(tt.accountInfo.data)}let Q=ie.find(tt=>tt.pubkey.equals(Y.platformId));(!Q||!Q.accountInfo)&&this.logAndCreateError("platform info not found: ",Y.configId.toBase58());let ge=wn.decode(Q.accountInfo.data);u=u||ge.feeRate;let re=Nt.buyExactIn({poolInfo:Y,amountB:p,protocolFeeRate:J.tradeFeeRate,platformFeeRate:u,curveType:J.curveType,shareFeeRate:b,creatorFeeRate:ge.creatorFeeRate,transferFeeConfigA:L,transferFeeConfigB:C,slot:await this.scope.connection.getSlot()}),ke=new $t.default(re.amountA.amount.toString()).sub((Ce=(ae=re.amountA.fee)==null?void 0:ae.toString())!=null?Ce:0),Fe=y?new $t.default(no.sub(y).toNumber()/no.toNumber()).clampedTo(0,1):new $t.default(1),Le=f!=null?f:y?new ce.default(ke.mul(Fe).toFixed(0)):re.amountA.amount.sub((Mt=re.amountA.fee)!=null?Mt:new ce.default(0));re.amountB.lt(p)&&console.log(`maximum ${n.toBase58()} amount can buy is ${re.amountA.toString()}, input ${i.toBase58()} amount: ${re.amountB.toString()}`);let Ae=g?ne(g,i,O).publicKey:void 0;return Ae&&B.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Ae,g,i,O)]}),B.addInstruction({instructions:[qi(e,this.scope.ownerPubKey,t,Y.configId,Y.platformId,R,F,z,Y.vaultA,Y.vaultB,n,i,o,O,kn(e,Y.platformId,i).publicKey,Tn(e,Y.creator,i).publicKey,re.amountB.lt(p)?re.amountB:p,Le,b,Ae)]}),B.addCustomComputeBudget(c),B.addTipInstruction(l),B.versionBuild({txVersion:s,extInfo:V(N({},re),{decimalOutAmount:ke,minDecimalOutAmount:new $t.default(Le.toString())})})}async buyTokenExactOut({programId:e=mt,authProgramId:t,mintA:n,mintAProgram:o=ee.TOKEN_PROGRAM_ID,mintB:i=ee.NATIVE_MINT,poolInfo:r,configInfo:a,transferFeeConfigA:u,platformFeeRate:s,txVersion:c,computeBudgetConfig:l,txTipConfig:m,feePayer:p,maxBuyAmount:f,outAmount:y,slippage:b,shareFeeRate:g=new ce.default(0),shareFeeReceiver:A,associatedOnly:k=!0,checkCreateATAOwner:h=!1,skipCheckMintA:P=!1,mintBProgram:T,transferFeeConfigB:I,skipCheckMintB:x=!1}){y.lte(new ce.default(0))&&this.logAndCreateError("out amount should gt 0:",y.toString());let S=this.createTxBuilder(p),{publicKey:B}=Uo(e,n,i);t=t!=null?t:Gt(e).publicKey;let R=r;if(!R){let Ae=await this.scope.connection.getAccountInfo(B,{commitment:"processed"});Ae||this.logAndCreateError("cannot found pool:",B.toBase58()),R=An.decode(Ae.data)}let L=a,O=await Ge(this.scope.connection,[L?void 0:R.configId,R.platformId].filter(Boolean).map(Ae=>({pubkey:Ae})));if(!L){let Ae=O.find(ae=>ae.pubkey.equals(R.configId));(!Ae||!Ae.accountInfo)&&this.logAndCreateError("config not found: ",R.configId.toBase58()),L=Jn.decode(Ae.accountInfo.data)}let C=O.find(Ae=>Ae.pubkey.equals(R.platformId));(!C||!C.accountInfo)&&this.logAndCreateError("platform info not found: ",R.configId.toBase58());let F=wn.decode(C.accountInfo.data);s=s||F.feeRate;let E=u;if(!P)if(E)o=ee.TOKEN_2022_PROGRAM_ID;else{let Ae=await this.scope.connection.getAccountInfo(n);if(Ae&&Ae.owner.equals(ee.TOKEN_2022_PROGRAM_ID)){o=Ae.owner;let ae=(0,ee.unpackMint)(n,Ae,o);E=(0,ee.getTransferFeeConfig)(ae)||void 0}}let{mintBProgram:_,transferFeeConfigB:z}=await this.getMintBTokenInfo({mintB:i,mintBProgram:T,transferFeeConfigB:I,skipCheckMintB:x}),H=Nt.buyExactOut({poolInfo:R,amountA:y,protocolFeeRate:L.tradeFeeRate,platformFeeRate:s,curveType:L.curveType,shareFeeRate:g,creatorFeeRate:F.creatorFeeRate,transferFeeConfigA:E,transferFeeConfigB:z,slot:await this.scope.connection.getSlot()}),Y=new $t.default(H.amountB.toString()),J=b?new $t.default(no.add(b).toNumber()/no.toNumber()).clampedTo(0,Number.MIN_SAFE_INTEGER):new $t.default(1),ie=(f!=null?f:b)?new ce.default(Y.mul(J).toFixed(0)):H.amountB,Q=this.scope.account.getAssociatedTokenAccount(n,o),ge=null,re=i.equals(ee.NATIVE_MINT);S.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Q,this.scope.ownerPubKey,n,o)]});let{account:ke,instructionParams:Fe}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:_,mint:i,owner:this.scope.ownerPubKey,createInfo:re?{payer:this.scope.ownerPubKey,amount:H.amountB}:void 0,skipCloseAccount:!re,notUseTokenAccount:re,associatedOnly:re?!1:k,checkCreateATAOwner:h});ke&&(ge=ke),S.addInstruction(Fe||{}),ge===void 0&&this.logAndCreateError(`cannot found mintB(${i.toBase58()}) token accounts`,"tokenAccounts",this.scope.account.tokenAccounts);let Le=A?ne(A,i,_).publicKey:void 0;return Le&&S.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Le,A,i,_)]}),S.addInstruction({instructions:[gl(e,this.scope.ownerPubKey,t,R.configId,R.platformId,B,Q,ge,R.vaultA,R.vaultB,n,i,o,_,kn(e,R.platformId,i).publicKey,Tn(e,R.creator,i).publicKey,y,ie,g,Le)]}),S.addCustomComputeBudget(l),S.addTipInstruction(m),S.versionBuild({txVersion:c,extInfo:{maxSpentAmount:ie,outAmount:y}})}async sellToken({programId:e=mt,authProgramId:t,mintAProgram:n=ee.TOKEN_PROGRAM_ID,mintA:o,mintB:i=ee.NATIVE_MINT,poolInfo:r,configInfo:a,platformFeeRate:u,txVersion:s,computeBudgetConfig:c,txTipConfig:l,feePayer:m,sellAmount:p,minAmountB:f,slippage:y,shareFeeRate:b=new ce.default(0),shareFeeReceiver:g,associatedOnly:A=!0,checkCreateATAOwner:k=!1,skipCheckMintA:h=!1,mintBProgram:P,transferFeeConfigB:T,skipCheckMintB:I=!1}){t=t!=null?t:Gt(e).publicKey;let x=this.createTxBuilder(m);p.lte(new ce.default(0))&&this.logAndCreateError("sell amount should be gt 0");let{publicKey:S}=Uo(e,o,i),B;if(!h){let ae=await this.scope.connection.getAccountInfo(o);if(ae&&ae.owner.equals(ee.TOKEN_2022_PROGRAM_ID)){n=ae.owner;let Ce=(0,ee.unpackMint)(o,ae,n);B=(0,ee.getTransferFeeConfig)(Ce)||void 0}}let{mintBProgram:R,transferFeeConfigB:L}=await this.getMintBTokenInfo({mintB:i,mintBProgram:P,transferFeeConfigB:T,skipCheckMintB:I}),O=null,C=null,F=i.equals(ee.NATIVE_MINT),{account:E,instructionParams:_}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n,mint:o,owner:this.scope.ownerPubKey,createInfo:void 0,skipCloseAccount:!0,notUseTokenAccount:!1,associatedOnly:A,checkCreateATAOwner:k});E&&(O=E),x.addInstruction(_||{}),O===void 0&&this.logAndCreateError("cannot found mintA token accounts","tokenAccounts",this.scope.account.tokenAccounts);let{account:z,instructionParams:H}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:R,mint:i,owner:this.scope.ownerPubKey,createInfo:F?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!F,notUseTokenAccount:F,associatedOnly:F?!1:A,checkCreateATAOwner:k});z&&(C=z),x.addInstruction(H||{}),C===void 0&&this.logAndCreateError("cannot found mintB token accounts","tokenAccounts",this.scope.account.tokenAccounts);let Y=r;if(!Y){let ae=await this.scope.connection.getAccountInfo(S,{commitment:"processed"});ae||this.logAndCreateError("cannot found pool",S.toBase58()),Y=An.decode(ae.data)}let J=a,ie=await Ge(this.scope.connection,[J?void 0:Y.configId,Y.platformId].filter(Boolean).map(ae=>({pubkey:ae})));if(!J){let ae=ie.find(Ce=>Ce.pubkey.equals(Y.configId));(!ae||!ae.accountInfo)&&this.logAndCreateError("config not found: ",Y.configId.toBase58()),J=Jn.decode(ae.accountInfo.data)}let Q=ie.find(ae=>ae.pubkey.equals(Y.platformId));(!Q||!Q.accountInfo)&&this.logAndCreateError("platform info not found: ",Y.configId.toBase58());let ge=wn.decode(Q.accountInfo.data);u=u||ge.feeRate;let re=Nt.sellExactIn({poolInfo:Y,amountA:p,protocolFeeRate:J.tradeFeeRate,platformFeeRate:u,curveType:J.curveType,shareFeeRate:b,creatorFeeRate:ge.creatorFeeRate,transferFeeConfigA:B,transferFeeConfigB:L,slot:await this.scope.connection.getSlot()}),ke=new $t.default(re.amountB.toString()),Fe=y?new $t.default(no.sub(y).toNumber()/no.toNumber()).clampedTo(0,1):new $t.default(1),Le=f!=null?f:y?new ce.default(ke.mul(Fe).toFixed(0)):re.amountB;Le.lte(new ce.default(0))&&this.logAndCreateError(`out ${i.toBase58()} amount should be gt 0`);let Ae=g?ne(g,i,R).publicKey:void 0;return Ae&&x.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Ae,g,i,R)]}),x.addInstruction({instructions:[Dr(e,this.scope.ownerPubKey,t,Y.configId,Y.platformId,S,O,C,Y.vaultA,Y.vaultB,o,i,n,R,kn(e,Y.platformId,i).publicKey,Tn(e,Y.creator,i).publicKey,re.amountA.amount.lt(p)?re.amountA.amount:p,Le,b,Ae)]}),x.addCustomComputeBudget(c),x.addTipInstruction(l),x.versionBuild({txVersion:s,extInfo:{outAmount:Le}})}async sellTokenExactOut({programId:e=mt,authProgramId:t,mintAProgram:n=ee.TOKEN_PROGRAM_ID,mintA:o,mintB:i=ee.NATIVE_MINT,poolInfo:r,configInfo:a,platformFeeRate:u,txVersion:s,computeBudgetConfig:c,txTipConfig:l,feePayer:m,inAmount:p,maxSellAmount:f,slippage:y,shareFeeRate:b=new ce.default(0),shareFeeReceiver:g,associatedOnly:A=!0,checkCreateATAOwner:k=!1,skipCheckMintA:h=!1,mintBProgram:P,transferFeeConfigB:T,skipCheckMintB:I=!1}){t=t!=null?t:Gt(e).publicKey;let x=this.createTxBuilder(m);f!=null&&f.lte(new ce.default(0))&&this.logAndCreateError("max sell amount should be gt 0");let{publicKey:S}=Uo(e,o,i),B;if(!h){let ae=await this.scope.connection.getAccountInfo(o);if(ae&&ae.owner.equals(ee.TOKEN_2022_PROGRAM_ID)){n=ae.owner;let Ce=(0,ee.unpackMint)(o,ae,n);B=(0,ee.getTransferFeeConfig)(Ce)||void 0}}let{mintBProgram:R,transferFeeConfigB:L}=await this.getMintBTokenInfo({mintB:i,mintBProgram:P,transferFeeConfigB:T,skipCheckMintB:I}),O=null,C=null,F=i.equals(ee.NATIVE_MINT),{account:E,instructionParams:_}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n,mint:o,owner:this.scope.ownerPubKey,createInfo:void 0,skipCloseAccount:!0,notUseTokenAccount:!1,associatedOnly:A,checkCreateATAOwner:k});E&&(O=E),x.addInstruction(_||{}),O===void 0&&this.logAndCreateError("cannot found mintA token accounts","tokenAccounts",this.scope.account.tokenAccounts);let{account:z,instructionParams:H}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:R,mint:i,owner:this.scope.ownerPubKey,createInfo:F?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!F,notUseTokenAccount:F,associatedOnly:F?!1:A,checkCreateATAOwner:k});z&&(C=z),x.addInstruction(H||{}),C===void 0&&this.logAndCreateError("cannot found mintB token accounts","tokenAccounts",this.scope.account.tokenAccounts);let Y=r;if(!Y){let ae=await this.scope.connection.getAccountInfo(S,{commitment:"processed"});ae||this.logAndCreateError("cannot found pool",S.toBase58()),Y=An.decode(ae.data)}let J=a,ie=await Ge(this.scope.connection,[J?void 0:Y.configId,Y.platformId].filter(Boolean).map(ae=>({pubkey:ae})));if(!J){let ae=ie.find(Ce=>Ce.pubkey.equals(Y.configId));(!ae||!ae.accountInfo)&&this.logAndCreateError("config not found: ",Y.configId.toBase58()),J=Jn.decode(ae.accountInfo.data)}let Q=ie.find(ae=>ae.pubkey.equals(Y.platformId));(!Q||!Q.accountInfo)&&this.logAndCreateError("platform info not found: ",Y.configId.toBase58());let ge=wn.decode(Q.accountInfo.data);u=u||ge.feeRate;let re=Nt.sellExactOut({poolInfo:Y,amountB:p,protocolFeeRate:J.tradeFeeRate,platformFeeRate:u,curveType:J.curveType,shareFeeRate:b,creatorFeeRate:ge.creatorFeeRate,transferFeeConfigA:B,transferFeeConfigB:L,slot:await this.scope.connection.getSlot()}),ke=new $t.default(re.amountA.amount.toString()),Fe=y?new $t.default(no.add(y).toNumber()/no.toNumber()).clampedTo(0,Number.MAX_SAFE_INTEGER):new $t.default(1),Le=(f!=null?f:y)?new ce.default(ke.mul(Fe).toFixed(0)):re.amountA.amount,Ae=g?ne(g,i,R).publicKey:void 0;return Ae&&x.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Ae,g,i,R)]}),x.addInstruction({instructions:[Pl(e,this.scope.ownerPubKey,t,Y.configId,Y.platformId,S,O,C,Y.vaultA,Y.vaultB,o,i,n,R,kn(e,Y.platformId,i).publicKey,Tn(e,Y.creator,i).publicKey,p,Le,b,Ae)]}),x.addCustomComputeBudget(c),x.addTipInstruction(l),x.versionBuild({txVersion:s,extInfo:{maxSellAmount:Le}})}async createPlatformConfig({programId:e=mt,platformAdmin:t,platformClaimFeeWallet:n,platformLockNftWallet:o,platformVestingWallet:i,cpConfigId:r,migrateCpLockNftScale:a,transferFeeExtensionAuth:u,creatorFeeRate:s,feeRate:c,name:l,web:m,img:p,platformVestingScale:f=new ce.default(0),txVersion:y,computeBudgetConfig:b,txTipConfig:g,feePayer:A}){let k=this.createTxBuilder(A),{publicKey:h}=hs(e,t);return k.addInstruction({instructions:[Al(e,t,n,o,i,h,r,u,a,c,s,l,m,p,f)]}),k.addCustomComputeBudget(b),k.addTipInstruction(g),k.versionBuild({txVersion:y,extInfo:{platformId:h}})}async updatePlatformConfig({programId:e=mt,platformAdmin:t,platformId:n,updateInfo:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:u}){let s=this.createTxBuilder(u),c=n!=null?n:hs(e,t).publicKey;return s.addInstruction({instructions:[wl(e,t,c,o)]}),s.addCustomComputeBudget(r),s.addTipInstruction(a),s.versionBuild({txVersion:i})}async createPlatformVestingAccount({programId:e=mt,platformVestingWallet:t,beneficiary:n,platformId:o,poolId:i,vestingRecord:r,txVersion:a,computeBudgetConfig:u,txTipConfig:s,feePayer:c}){let l=this.createTxBuilder(c),m=r!=null?r:Go(e,i,n).publicKey;return l.addInstruction({instructions:[kl(e,t,n,o,i,m)]}),l.addCustomComputeBudget(u),l.addTipInstruction(s),l.versionBuild({txVersion:a})}async claimPlatformFee({programId:e=mt,authProgramId:t,platformId:n,poolId:o,platformClaimFeeWallet:i,mintB:r,vaultB:a,mintBProgram:u,txVersion:s,computeBudgetConfig:c,txTipConfig:l,feePayer:m}){var A;let p=this.createTxBuilder(m);t=t!=null?t:Gt(e).publicKey;let f=r,y=a;if(!f){let k=await this.scope.connection.getAccountInfo(o,{commitment:"processed"});k||this.logAndCreateError("cannot found pool:",o.toBase58());let h=An.decode(k.data),P=await this.scope.connection.getAccountInfo(h.configId,{commitment:"processed"});P||this.logAndCreateError("cannot found config:",h.configId.toBase58()),f=Jn.decode(P.data).mintB,y=y!=null?y:h.vaultB}(!f||!y)&&this.logAndCreateError("cannot found mint info, mintB: ",f.toBase58(),", vaultB: ",(A=y==null?void 0:y.toBase58())!=null?A:"");let{mintBProgram:b}=await this.getMintBTokenInfo({mintB:f,mintBProgram:u}),g=ne(this.scope.ownerPubKey,f,b).publicKey;return p.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,g,this.scope.ownerPubKey,f,b)]}),p.addInstruction({instructions:[Ks(e,i,t,o,n,y,g,f,b)]}),p.addCustomComputeBudget(c),p.addTipInstruction(l),p.versionBuild({txVersion:s})}async claimAllPlatformFee({programId:e=mt,authProgramId:t,platformId:n,platformClaimFeeWallet:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:u}){let s=this.createTxBuilder(u);t=t!=null?t:Gt(e).publicKey;let l=(await this.scope.connection.getProgramAccounts(e,{filters:[{dataSize:An.span},{memcmp:{offset:An.offsetOf("platformId"),bytes:n.toString()}}]})).map(f=>({poolId:f.pubkey,pool:An.decode(f.account.data)})).filter(({pool:f})=>f.platformFee.gt(new ce.default(0))),m={},p=[...new Set(l.map(({pool:f})=>f.mintB.toBase58()))];return p.length&&(await Ge(this.scope.connection,p.map(y=>({pubkey:new oo.PublicKey(y)})))).forEach(y=>{var b,g;m[y.pubkey.toBase58()]=(g=(b=y.accountInfo)==null?void 0:b.owner)!=null?g:ee.TOKEN_PROGRAM_ID}),l.forEach(({poolId:f,pool:y})=>{var A;let b=(A=m[y.mintB.toBase58()])!=null?A:ee.TOKEN_PROGRAM_ID,g=ne(this.scope.ownerPubKey,y.mintB,b).publicKey;s.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,g,this.scope.ownerPubKey,y.mintB,b)]}),s.addInstruction({instructions:[Ks(e,o,t,f,n,y.vaultB,g,y.mintB,b)]})}),s.addTipInstruction(a),i===0?s.sizeCheckBuildV0({computeBudgetConfig:r}):s.sizeCheckBuild({computeBudgetConfig:r})}async createVesting({programId:e=mt,poolId:t,beneficiary:n,shareAmount:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:u}){let s=this.createTxBuilder(u),c=await this.getRpcPoolInfo({poolId:t});o.add(c.vestingSchedule.totalAllocatedShare).gt(c.vestingSchedule.totalLockedAmount)&&this.logAndCreateError("share amount exceed total locked amount");let l=Go(e,t,n).publicKey;return s.addInstruction({instructions:[Ss(e,this.scope.ownerPubKey,n,t,l,o)]}),s.addCustomComputeBudget(r),s.addTipInstruction(a),s.versionBuild({txVersion:i})}async createMultipleVesting({programId:e=mt,poolId:t,beneficiaryList:n,txVersion:o,computeBudgetConfig:i,feePayer:r}){let a=this.createTxBuilder(r);n.length===0&&this.logAndCreateError("beneficiaryList is null");let u=await this.getRpcPoolInfo({poolId:t});return n.reduce((c,l)=>c.add(l.shareAmount),u.vestingSchedule.totalAllocatedShare).gt(u.vestingSchedule.totalLockedAmount)&&this.logAndCreateError("share amount exceed total locked amount"),n.forEach(c=>{let l=Go(e,t,c.wallet).publicKey;a.addInstruction({instructions:[Ss(e,this.scope.ownerPubKey,c.wallet,t,l,c.shareAmount)]})}),o===0?a.sizeCheckBuildV0({computeBudgetConfig:i}):a.sizeCheckBuild({computeBudgetConfig:i})}async claimVesting({programId:e=mt,poolId:t,poolInfo:n,vestingRecord:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:u}){let s=this.createTxBuilder(u),c=Gt(e).publicKey,l=o||Go(e,t,this.scope.ownerPubKey).publicKey,m=n;if(!m){let f=await this.scope.connection.getAccountInfo(t);f||this.logAndCreateError("pool not found"),m=An.decode(f.data)}let p=ne(this.scope.ownerPubKey,m.mintA,ee.TOKEN_PROGRAM_ID).publicKey;return s.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,p,this.scope.ownerPubKey,m.mintA)]}),s.addInstruction({instructions:[xs(e,this.scope.ownerPubKey,c,t,l,p,m.vaultA,m.mintA,ee.TOKEN_PROGRAM_ID)]}),s.addCustomComputeBudget(r),s.addTipInstruction(a),s.versionBuild({txVersion:i})}async claimMultiVesting({programId:e=mt,poolIdList:t,poolsInfo:n={},vestingRecords:o={},txVersion:i,computeBudgetConfig:r,feePayer:a}){let u=this.createTxBuilder(a),s=N({},n),c=Gt(e).publicKey,l=t.filter(m=>!s[m.toBase58()]);if(l.length){let m=await this.getRpcPoolsInfo({poolIdList:l});s=N(N({},s),m.poolInfoMap)}return t.forEach(m=>{let p=m.toBase58(),f=s[p];f||this.logAndCreateError(`pool info not found: ${p}`);let y=o[p]||Go(e,m,this.scope.ownerPubKey).publicKey,b=ne(this.scope.ownerPubKey,f.mintA,ee.TOKEN_PROGRAM_ID).publicKey;u.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,b,this.scope.ownerPubKey,f.mintA)]}),u.addInstruction({instructions:[xs(e,this.scope.ownerPubKey,c,m,y,b,f.vaultA,f.mintA,ee.TOKEN_PROGRAM_ID)]})}),i===0?u.sizeCheckBuildV0({computeBudgetConfig:r}):u.sizeCheckBuild({computeBudgetConfig:r})}async claimVaultPlatformFee({programId:e=mt,platformId:t,mintB:n,mintBProgram:o,claimFeeWallet:i,txVersion:r,computeBudgetConfig:a,txTipConfig:u,feePayer:s}){let c=this.createTxBuilder(s),l=kn(e,t,n).publicKey,m=Is(e).publicKey,{mintBProgram:p}=await this.getMintBTokenInfo({mintB:n,mintBProgram:o}),f=this.scope.account.getAssociatedTokenAccount(n,p);return c.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,f,this.scope.ownerPubKey,n,p),Cs(e,t,i!=null?i:this.scope.ownerPubKey,m,l,f,n,p)]}),c.addCustomComputeBudget(a),c.addTipInstruction(u),c.versionBuild({txVersion:r})}async claimMultipleVaultPlatformFee({programId:e=mt,platformList:t,unwrapSol:n=!0,txVersion:o,computeBudgetConfig:i,feePayer:r,associatedOnly:a=!0,checkCreateATAOwner:u=!1}){let s=this.createTxBuilder(r),c={};return t.forEach(async l=>{var b,g,A;let m=Is(e).publicKey,p=kn(e,l.id,l.mintB).publicKey,f=l.mintB.equals(ee.NATIVE_MINT)&&n,y=c[l.mintB.toBase58()];if(!y){let{account:k,instructionParams:h}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:(b=l.mintBProgram)!=null?b:ee.TOKEN_PROGRAM_ID,mint:l.mintB,owner:this.scope.ownerPubKey,createInfo:f?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!f,notUseTokenAccount:f,associatedOnly:f?!1:a,checkCreateATAOwner:u});k&&(y=k),s.addInstruction(h||{}),y===void 0&&this.logAndCreateError(`cannot found platform ${l.id.toBase58()} mintB(${l.mintB.toBase58()}) token accounts`,"tokenAccounts",this.scope.account.tokenAccounts)}s.addInstruction({instructions:[Cs(e,l.id,(g=l.claimFeeWallet)!=null?g:this.scope.ownerPubKey,m,p,y,l.mintB,(A=l.mintBProgram)!=null?A:ee.TOKEN_PROGRAM_ID)]})}),o===0?s.sizeCheckBuildV0({computeBudgetConfig:i}):s.sizeCheckBuild({computeBudgetConfig:i})}async claimCreatorFee({programId:e=mt,mintB:t,mintBProgram:n,txVersion:o,computeBudgetConfig:i,txTipConfig:r,feePayer:a}){let u=this.createTxBuilder(a),s=Tn(e,this.scope.ownerPubKey,t).publicKey,c=Bs(e).publicKey,{mintBProgram:l}=await this.getMintBTokenInfo({mintB:t,mintBProgram:n}),m=this.scope.account.getAssociatedTokenAccount(t,l);return u.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,m,this.scope.ownerPubKey,t,l),Rs(e,this.scope.ownerPubKey,c,s,m,t,l)]}),u.addCustomComputeBudget(i),u.addTipInstruction(r),u.versionBuild({txVersion:o})}async claimMultipleCreatorFee({programId:e=mt,mintBList:t,txVersion:n,computeBudgetConfig:o,feePayer:i}){let r=this.createTxBuilder(i);return t.forEach(a=>{var p;let u=a.pubKey,s=(p=a.programId)!=null?p:ee.TOKEN_PROGRAM_ID,c=Tn(e,this.scope.ownerPubKey,u).publicKey,l=Bs(e).publicKey,m=this.scope.account.getAssociatedTokenAccount(u,s);r.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,m,this.scope.ownerPubKey,u,s),Rs(e,this.scope.ownerPubKey,l,c,m,u,s)]})}),n==0?r.sizeCheckBuildV0({computeBudgetConfig:o}):r.sizeCheckBuild({computeBudgetConfig:o})}async createPlatformAllowConfig({programId:e=mt,platformAdmin:t,platformId:n,configInfo:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:u}){let s=this.createTxBuilder(u),{publicKey:c}=ks(e,new oo.PublicKey(o.mintB),o.curveType,o.index),{publicKey:l}=Wi(e,n,c);return s.addInstruction({instructions:[Tl(e,t,n,c,l)]}),s.addCustomComputeBudget(r),s.addTipInstruction(a),s.versionBuild({txVersion:i,extInfo:{platformId:n}})}async closePlatformAllowConfig({programId:e=mt,platformAdmin:t,platformId:n,configInfo:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:u}){let s=this.createTxBuilder(u),{publicKey:c}=ks(e,new oo.PublicKey(o.mintB),o.curveType,o.index),{publicKey:l}=Wi(e,n,c);return s.addInstruction({instructions:[hl(e,t,n,c,l)]}),s.addCustomComputeBudget(r),s.addTipInstruction(a),s.versionBuild({txVersion:i,extInfo:{platformId:n}})}async getRpcPoolInfo({poolId:e}){return(await this.getRpcPoolsInfo({poolIdList:[e]})).poolInfoMap[e.toBase58()]}async getRpcPoolsInfo({poolIdList:e,config:t}){let n=await Ge(this.scope.connection,e.map(u=>({pubkey:u})),t),o={},i=[];for(let u=0;u<e.length;u++){let s=n[u];if(s===null||!s.accountInfo)throw Error("fetch pool info error: "+e[u].toBase58());let c=An.decode(s.accountInfo.data);o[e[u].toBase58()]=V(N({},c),{poolId:e[u],programId:s.accountInfo.owner}),i.push(c.configId)}let r=await Ge(this.scope.connection,i.map(u=>({pubkey:u})),t),a={};for(let u=0;u<i.length;u++){let s=r[u];if(s===null||!s.accountInfo)throw Error("fetch config info error: "+i[u].toBase58());let c=Jn.decode(s.accountInfo.data);a[i[u].toBase58()]=V(N({},c),{configId:s.accountInfo.owner})}return{poolInfoMap:Object.keys(o).reduce((u,s)=>V(N({},u),{[s]:V(N({},o[s]),{configInfo:a[o[s].configId.toBase58()]})}),{})}}};var Bl={[Ca.toBase58()]:3},xl={3:Ca};var Ns=v([Ie(5),Ie(8),M("ownAddress"),w("vaultSignerNonce"),M("baseMint"),M("quoteMint"),M("baseVault"),w("baseDepositsTotal"),w("baseFeesAccrued"),M("quoteVault"),w("quoteDepositsTotal"),w("quoteFeesAccrued"),w("quoteDustThreshold"),M("requestQueue"),M("eventQueue"),M("bids"),M("asks"),w("baseLotSize"),w("quoteLotSize"),w("feeRateBps"),w("referrerRebatesAccrued"),Ie(7)]),Sl={3:Ns};var Ms=require("@solana/web3.js");var Yr=Be("Serum"),Hr=class{static getProgramId(e){let t=xl[e];return t||Yr.logWithError("invalid version","version",e),t}static getVersion(e){let t=e.toBase58(),n=Bl[t];return n||Yr.logWithError("invalid program id","programId",t),n}static getStateLayout(e){let t=Sl[e];return t||Yr.logWithError(!!t,"invalid version","version",e),t}static getLayouts(e){return{state:this.getStateLayout(e)}}static getAssociatedAuthority({programId:e,marketId:t}){let n=[t.toBuffer()],o=0,i;for(;o<100;){try{let r=n.concat(Buffer.from([o]),Buffer.alloc(7));i=Ms.PublicKey.createProgramAddressSync(r,e)}catch(r){if(r instanceof TypeError)throw r;o++;continue}return{publicKey:i,nonce:o}}return Yr.logWithError("unable to find a viable program address nonce","params",{programId:e,marketId:t}),{publicKey:Ms.PublicKey.default,nonce:o}}};var Qo=require("@solana/spl-token"),me=require("@solana/web3.js"),Wn=te(require("bn.js"));function Rd(d,e,t,n,o,i,r,a,u,s,c,l,m,p,f){var T;let y=[],b=[K({pubkey:Qo.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:Qo.TOKEN_2022_PROGRAM_ID,isWritable:!1}),K({pubkey:Qo.ASSOCIATED_TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:me.SystemProgram.programId,isWritable:!1}),K({pubkey:e,isSigner:!0})];b.push(K({pubkey:t})),b.push(K({pubkey:o}));let g=[u,s],A=[c,l],k=[i,r,a];for(let I=0;I<g.length;I++){let x=g[I],S=k[I]===x.mintA.address;if(b.push(K({pubkey:new me.PublicKey(x.programId),isWritable:!1})),I===g.length-1?b.push(K({pubkey:o})):b.push(K({pubkey:n})),b.push(K({pubkey:new me.PublicKey(k[I])})),b.push(K({pubkey:new me.PublicKey(k[I+1])})),x.version===6){let B=A[I];b.push(K({pubkey:new me.PublicKey(B.config.id)})),b.push(K({pubkey:new me.PublicKey(B.id)})),b.push(K({pubkey:new me.PublicKey(S?B.vault.A:B.vault.B)})),b.push(K({pubkey:new me.PublicKey(S?B.vault.B:B.vault.A)})),b.push(K({pubkey:new me.PublicKey(x.observationId)})),b.push(K({pubkey:pn})),b.push(K({pubkey:He(new me.PublicKey(x.programId),new me.PublicKey(x.id)).publicKey})),y.push(Ld(x.sqrtPriceX64.toString(),S));for(let R of(T=f[I])!=null?T:[])b.push(K({pubkey:new me.PublicKey(R)}))}else if(x.version===5){let B=A[I];b.push(K({pubkey:new me.PublicKey(B.id)})),b.push(K({pubkey:new me.PublicKey(B.authority),isWritable:!1})),b.push(K({pubkey:new me.PublicKey(B.marketProgramId)})),b.push(K({pubkey:new me.PublicKey(B.marketAuthority)})),b.push(K({pubkey:_u,isWritable:!1})),b.push(K({pubkey:new me.PublicKey(B.openOrders)})),b.push(K({pubkey:new me.PublicKey(B.vault.A)})),b.push(K({pubkey:new me.PublicKey(B.vault.B)})),b.push(K({pubkey:new me.PublicKey(B.id)})),b.push(K({pubkey:new me.PublicKey(B.id)})),b.push(K({pubkey:new me.PublicKey(B.id)})),b.push(K({pubkey:new me.PublicKey(B.id)})),b.push(K({pubkey:new me.PublicKey(B.id)})),b.push(K({pubkey:new me.PublicKey(B.id)})),b.push(K({pubkey:new me.PublicKey(B.marketId)})),b.push(K({pubkey:new me.PublicKey(B.marketBids)})),b.push(K({pubkey:new me.PublicKey(B.marketAsks)})),b.push(K({pubkey:new me.PublicKey(B.marketEventQueue)})),b.push(K({pubkey:new me.PublicKey(B.marketBaseVault)})),b.push(K({pubkey:new me.PublicKey(B.marketQuoteVault)}))}else if(x.version===4){let B=A[I],R=x.status!==1;b.push(K({pubkey:new me.PublicKey(B.id)})),b.push(K({pubkey:new me.PublicKey(B.authority),isWritable:!1})),b.push(K({pubkey:new me.PublicKey(R?B.id:B.marketProgramId)})),b.push(K({pubkey:new me.PublicKey(R?B.id:B.marketAuthority)})),b.push(K({pubkey:new me.PublicKey(R?B.id:B.openOrders)})),b.push(K({pubkey:new me.PublicKey(B.vault.A)})),b.push(K({pubkey:new me.PublicKey(B.vault.B)})),b.push(K({pubkey:new me.PublicKey(R?B.id:B.marketId)})),b.push(K({pubkey:new me.PublicKey(R?B.id:B.marketBids)})),b.push(K({pubkey:new me.PublicKey(R?B.id:B.marketAsks)})),b.push(K({pubkey:new me.PublicKey(R?B.id:B.marketEventQueue)})),b.push(K({pubkey:new me.PublicKey(R?B.id:B.marketBaseVault)})),b.push(K({pubkey:new me.PublicKey(R?B.id:B.marketQuoteVault)}))}else if(x.version===7){let B=A[I];b.push(K({pubkey:new me.PublicKey(B.authority)})),b.push(K({pubkey:new me.PublicKey(B.config.id)})),b.push(K({pubkey:new me.PublicKey(B.id)})),b.push(K({pubkey:new me.PublicKey(S?B.vault.A:B.vault.B)})),b.push(K({pubkey:new me.PublicKey(S?B.vault.B:B.vault.A)})),b.push(K({pubkey:new me.PublicKey(x.observationId)}))}else throw Error("pool type error")}let h=v([W("insId"),w("amountIn"),w("amountOut"),j(ye(),y.length,"clmmPriceLimit")]),P=Buffer.alloc(h.span);return h.encode({insId:0,amountIn:m,amountOut:p,clmmPriceLimit:y},P),new me.TransactionInstruction({keys:b,programId:d,data:P})}function Ld(d,e){if(d)if(e){let t=new Wn.default(d).div(new Wn.default(25));return t.gt(St.add(dt))?t:St.add(dt)}else{let t=new Wn.default(d).mul(new Wn.default(25));return t.lt(Kt.sub(dt))?t:Kt.sub(dt)}else return e?St.add(dt):Kt.sub(dt)}function Kl({routeProgram:d,ownerInfo:e,inputMint:t,swapInfo:n}){var o,i,r,a,u,s,c,l,m;if(n.routeType==="amm")if(n.poolInfo[0].version===6){let p=n.poolKey[0],f=Ut(p),y=t.equals(f.mintA.address)?St.add(dt):Kt.sub(dt);return we.makeSwapBaseInInstructions({poolInfo:p,poolKeys:p,observationId:n.poolInfo[0].observationId,ownerInfo:{wallet:e.wallet,tokenAccountA:f.mintA.address.equals(t)?e.sourceToken:e.destinationToken,tokenAccountB:f.mintA.address.equals(t)?e.destinationToken:e.sourceToken},inputMint:t,amountIn:n.amountIn.amount.raw,amountOutMin:n.minAmountOut.amount.raw.sub((i=(o=n.minAmountOut.fee)==null?void 0:o.raw)!=null?i:new Wn.default(0)),sqrtPriceLimitX64:y,remainingAccounts:(r=n.remainingAccounts[0])!=null?r:[]})}else if(n.poolInfo[0].version===7){let p=n.poolInfo[0],f=t.toString()===n.poolInfo[0].mintA.address;return{signers:[],instructions:[qo(p.programId,e.wallet,p.authority,p.configId,p.id,e.sourceToken,e.destinationToken,f?p.vaultA:p.vaultB,f?p.vaultB:p.vaultA,f?p.mintProgramA:p.mintProgramB,f?p.mintProgramB:p.mintProgramA,new me.PublicKey(p[f?"mintA":"mintB"].address),new me.PublicKey(p[f?"mintB":"mintA"].address),p.observationId,n.amountIn.amount.raw,n.minAmountOut.amount.raw)],lookupTableAddress:[],instructionTypes:[f?X.CpmmSwapBaseIn:X.CpmmSwapBaseOut],address:{}}}else{let p=n.poolKey[0];return{signers:[],instructions:[n.poolInfo[0].pooltype.includes("StablePool")?Vr({poolKeys:p,version:n.poolInfo[0].pooltype.includes("StablePool")?5:4,userKeys:{tokenAccountIn:e.sourceToken,tokenAccountOut:e.destinationToken,owner:e.wallet},amountIn:n.amountIn.amount.raw,amountOut:n.minAmountOut.amount.raw.sub((u=(a=n.minAmountOut.fee)==null?void 0:a.raw)!=null?u:new Wn.default(0)),fixedSide:"in"}):_r({poolKeys:p,version:n.poolInfo[0].pooltype.includes("StablePool")?5:4,userKeys:{tokenAccountIn:e.sourceToken,tokenAccountOut:e.destinationToken,owner:e.wallet},amountIn:n.amountIn.amount.raw,amountOut:n.minAmountOut.amount.raw.sub((c=(s=n.minAmountOut.fee)==null?void 0:s.raw)!=null?c:new Wn.default(0)),fixedSide:"in"})],lookupTableAddress:p.lookupTableAccount?[p.lookupTableAccount]:[],instructionTypes:[n.poolInfo[0].pooltype.includes("StablePool")?X.AmmV5SwapBaseIn:X.AmmV4SwapBaseIn],address:{}}}else if(n.routeType==="route"){let p=n.poolInfo[0],f=n.poolInfo[1],y=n.poolKey[0],b=n.poolKey[1];if(e.routeToken===void 0)throw Error("owner route token account check error");return{signers:[],instructions:[Rd(d,e.wallet,e.sourceToken,e.routeToken,e.destinationToken,t.toString(),n.middleToken.mint.toString(),n.outputMint.toString(),p,f,y,b,n.amountIn.amount.raw,n.minAmountOut.amount.raw.sub((m=(l=n.minAmountOut.fee)==null?void 0:l.raw)!=null?m:new Wn.default(0)),n.remainingAccounts)],instructionTypes:[X.RouteSwap],lookupTableAddress:[y.lookupTableAccount,b.lookupTableAccount].filter(g=>g!==void 0),address:{}}}else throw Error("route type error")}var Lt=new he.default(0);function io(d,e){var n,o,i,r,a;let t=(n=d.extensions)==null?void 0:n.feeConfig;if(!!t)return{transferFeeConfigAuthority:pe.PublicKey.default,withdrawWithheldAuthority:pe.PublicKey.default,withheldAmount:BigInt(0),olderTransferFee:{epoch:BigInt((i=(o=t.olderTransferFee.epoch)!=null?o:e)!=null?i:0),maximumFee:BigInt(t.olderTransferFee.maximumFee),transferFeeBasisPoints:t.olderTransferFee.transferFeeBasisPoints},newerTransferFee:{epoch:BigInt((a=(r=t.newerTransferFee.epoch)!=null?r:e)!=null?a:0),maximumFee:BigInt(t.newerTransferFee.maximumFee),transferFeeBasisPoints:t.newerTransferFee.transferFeeBasisPoints}}}function Qr(d){return d.programId?new pe.PublicKey(d.programId):Pe.TOKEN_PROGRAM_ID}var Hi=class extends ot{constructor(e){super(e)}async getWSolAccounts(){this.scope.checkOwner(),await this.scope.account.fetchWalletTokenAccounts();let e=this.scope.account.tokenAccounts.filter(t=>t.mint.equals(Z));return e.sort((t,n)=>t.isAssociated?1:n.isAssociated||t.amount.lt(n.amount)?-1:1),e}async unWrapWSol(e){let{amount:t,tokenProgram:n,txVersion:o=1,feePayer:i}=e,r=await this.getWSolAccounts(),a=this.createTxBuilder(i);a.addCustomComputeBudget(e.computeBudgetConfig);let u=fe(t);for(let s=0;s<r.length;s++)u.gte(r[s].amount)?(a.addInstruction({instructions:[Mn({tokenAccount:r[s].publicKey,payer:this.scope.ownerPubKey,owner:this.scope.ownerPubKey,programId:n})]}),u.sub(r[s].amount)):a.addInstruction({instructions:[Mn({tokenAccount:r[s].publicKey,payer:this.scope.ownerPubKey,owner:this.scope.ownerPubKey,programId:n})]});return a.versionBuild({txVersion:o})}async wrapWSol(e,t,n,o){let i=this.createTxBuilder(o),r=await Qn({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:this.scope.ownerPubKey,amount:e,skipCloseAccount:!0});return i.addInstruction(r),i.versionBuild({txVersion:n!=null?n:1})}async swap({swapInfo:e,swapPoolKeys:t,ownerInfo:n,computeBudgetConfig:o,routeProgram:i,txVersion:r,feePayer:a}){let u=this.createTxBuilder(a),s=e.amountIn,c=e.amountOut,l=s.amount.token.mint.equals(Z),m=c.amount.token.mint.equals(Z),p=s.amount.token.mint,f=c.amount.token.mint,{account:y,instructionParams:b}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:s.amount.token.isToken2022?Pe.TOKEN_2022_PROGRAM_ID:Pe.TOKEN_PROGRAM_ID,mint:p,notUseTokenAccount:l,owner:this.scope.ownerPubKey,skipCloseAccount:!l,createInfo:l?{payer:this.scope.ownerPubKey,amount:s.amount.raw}:void 0,associatedOnly:l?!1:n.associatedOnly,checkCreateATAOwner:n.checkCreateATAOwner});if(b&&u.addInstruction(b),y===void 0)throw Error("input account check error");let g;if(e.routeType==="route"&&!m)g=this.scope.account.getAssociatedTokenAccount(f,c.amount.token.isToken2022?Pe.TOKEN_2022_PROGRAM_ID:Pe.TOKEN_PROGRAM_ID);else{let{account:P,instructionParams:T}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:c.amount.token.isToken2022?Pe.TOKEN_2022_PROGRAM_ID:Pe.TOKEN_PROGRAM_ID,mint:f,notUseTokenAccount:m,owner:this.scope.ownerPubKey,skipCloseAccount:!0,createInfo:{payer:this.scope.ownerPubKey,amount:0},associatedOnly:m?!1:n.associatedOnly,checkCreateATAOwner:n.checkCreateATAOwner});g=P,T&&u.addInstruction(T)}m&&u.addInstruction({endInstructions:[Mn({owner:this.scope.ownerPubKey,payer:this.scope.ownerPubKey,tokenAccount:g,programId:Pe.TOKEN_PROGRAM_ID})],endInstructionTypes:[X.CloseAccount]});let A;if(e.routeType==="route"){let P=e.middleToken;A=this.scope.account.getAssociatedTokenAccount(P.mint,P.isToken2022?Pe.TOKEN_2022_PROGRAM_ID:Pe.TOKEN_PROGRAM_ID)}let k=t||await this.computePoolToPoolKeys({pools:e.poolInfoList}),h=Kl({routeProgram:i,inputMint:p,swapInfo:V(N({},e),{poolInfo:[...e.poolInfoList],poolKey:k,outputMint:f}),ownerInfo:{wallet:this.scope.ownerPubKey,sourceToken:y,routeToken:A,destinationToken:g}});if(e.feeConfig!==void 0){let P=this.createTxBuilder(),T=s.amount.token.isToken2022?(0,Pe.createTransferCheckedInstruction)(y,s.amount.token.mint,e.feeConfig.feeAccount,this.scope.ownerPubKey,e.feeConfig.feeAmount.toNumber(),s.amount.token.decimals,[],Pe.TOKEN_2022_PROGRAM_ID):(0,Pe.createTransferInstruction)(y,e.feeConfig.feeAccount,this.scope.ownerPubKey,e.feeConfig.feeAmount.toNumber());P.addInstruction({instructions:[T],instructionTypes:[X.TransferAmount]}),P.addInstruction(h);let{transactions:I}=r===0?await P.sizeCheckBuildV0():await P.sizeCheckBuild();I.length<2&&u.addInstruction({instructions:[(0,Pe.createTransferInstruction)(y,e.feeConfig.feeAccount,this.scope.ownerPubKey,e.feeConfig.feeAmount.toNumber())],instructionTypes:[X.TransferAmount]})}return u.addInstruction(h),r===0?u.sizeCheckBuildV0({computeBudgetConfig:o,address:h.address}):u.sizeCheckBuild({computeBudgetConfig:o,address:h.address})}async swapClmmToLaunchMint({inputMint:e,inputAmount:t,fixClmmOut:n=!1,clmmPoolId:o,launchPoolId:i,priceLimit:r,slippage:a=.01,shareFeeRate:u=new he.default(0),shareFeeReceiver:s,launchPlatformInfo:c,slot:l,mintInfo:m,epochInfo:p,ownerInfo:f={useSOLBalance:!0},checkCreateATAOwner:y=!1,computeBudgetConfig:b,txVersion:g,blockTimestamp:A}){let k=(f==null?void 0:f.feePayer)||this.scope.ownerPubKey,h=p!=null?p:await this.scope.fetchEpochInfo(),{clmmPoolData:P,clmmComputeAmount:{maxClmmAmountIn:T,clmmAmountOut:I,remainingAccounts:x},launchPoolInfo:S,launchAuthProgramId:B,launchSwapInfo:R,launchMintProgramB:L,outAmount:O,minOutAmount:C}=await this.computeClmmToLaunchAmount({inputMint:e,inputAmount:t,fixClmmOut:n,clmmPoolId:o,launchPoolId:i,slippage:a,epochInfo:h,shareFeeRate:u,launchPlatformInfo:c,slot:l,mintInfo:m,blockTimestamp:A}),F=e.toString()===P.poolInfo.mintA.address,E=f.useSOLBalance&&P.poolInfo.mintA.address===Z.toBase58(),_=f.useSOLBalance&&P.poolInfo.mintB.address===Z.toBase58(),z={},H;!r||r.equals(new Ne.default(0))?H=F?St.add(new he.default(1)):Kt.sub(new he.default(1)):H=se.priceToSqrtPriceX64(r,P.poolInfo.mintA.decimals,P.poolInfo.mintB.decimals);let Y=this.createTxBuilder(k),[J,ie]=[new pe.PublicKey(P.poolInfo.mintA.address),new pe.PublicKey(P.poolInfo.mintB.address)],[Q,ge]=[new pe.PublicKey(P.poolInfo.mintA.programId),new pe.PublicKey(P.poolInfo.mintB.programId)],re=this.scope.account.getAssociatedTokenAccount(J,Q),ke=this.scope.account.getAssociatedTokenAccount(ie,ge);Y.addInstruction({instructions:[(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,re,this.scope.ownerPubKey,J,Q),(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,ke,this.scope.ownerPubKey,ie,ge)]}),(F&&E||!F&&_)&&Y.addInstruction({instructions:[pe.SystemProgram.transfer({fromPubkey:this.scope.ownerPubKey,toPubkey:F?re:ke,lamports:BigInt(T.toString())}),(0,Pe.createSyncNativeInstruction)(F?re:ke)]}),z[P.poolInfo.mintA.address]=re,z[P.poolInfo.mintB.address]=ke,(!re||!ke)&&this.logAndCreateError("user do not have token account",{ownerTokenAccountA:re,ownerTokenAccountB:ke}),Y.addInstruction(n?we.makeSwapBaseOutInstructions({poolInfo:P.poolInfo,poolKeys:P.poolKeys,observationId:P.computePoolInfo.observationId,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:re,tokenAccountB:ke},outputMint:F?ie:J,amountOut:I,amountInMax:T,sqrtPriceLimitX64:H,remainingAccounts:x}):we.makeSwapBaseInInstructions({poolInfo:P.poolInfo,poolKeys:P.poolKeys,observationId:P.computePoolInfo.observationId,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:re,tokenAccountB:ke},inputMint:new pe.PublicKey(e),amountIn:t,amountOutMin:I,sqrtPriceLimitX64:H,remainingAccounts:x}));let Fe=Wr(S.mintProgramFlag),Le=this.scope.account.getAssociatedTokenAccount(S.mintA,Fe),Ae=z[S.mintB.toBase58()];if(Y.addInstruction({instructions:[(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Le,this.scope.ownerPubKey,S.mintA,Fe)]}),!Ae){let ae=S.mintB.equals(Z),{account:Ce,instructionParams:Mt}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:L,mint:S.mintB,notUseTokenAccount:ae,owner:this.scope.ownerPubKey,skipCloseAccount:!ae,createInfo:ae?{payer:this.scope.ownerPubKey,amount:I}:void 0,associatedOnly:!1,checkCreateATAOwner:y});Ae=Ce,Mt&&Y.addInstruction(Mt)}return Y.addInstruction({instructions:[qi(S.programId,this.scope.ownerPubKey,B,S.configId,S.platformId,new pe.PublicKey(i),Le,Ae,S.vaultA,S.vaultB,S.mintA,S.mintB,Fe,L,kn(S.programId,S.platformId,S.mintB).publicKey,Tn(S.programId,S.creator,S.mintB).publicKey,R.amountB.lt(I)?R.amountB:I,C,u,s)]}),Y.addCustomComputeBudget(b),Y.versionBuild({txVersion:g,extInfo:{routes:[{mint:new pe.PublicKey(e),amount:n?T:t,decimal:P.poolInfo[F?"mintA":"mintB"].decimals},{mint:F?ie:J,amount:I,decimal:P.poolInfo[F?"mintB":"mintA"].decimals},{mint:S.mintA,amount:O,decimal:S.mintDecimalsA}],outAmount:O,minOutAmount:C}})}async computeClmmToLaunchAmount({inputMint:e,inputAmount:t,fixClmmOut:n=!1,clmmPoolId:o,launchPoolId:i,slippage:r,epochInfo:a,shareFeeRate:u=new he.default(0),clmmPoolData:s,launchPoolInfo:c,launchPlatformInfo:l,slot:m,mintInfo:p,blockTimestamp:f}){var _,z;let y=r>0?new Ne.default(r).div(2).toDecimalPlaces(4,Ne.default.ROUND_DOWN).toNumber():r,b=s!=null?s:await this.scope.clmm.getPoolInfoFromRpc(o.toString());if(e.toString()!==b.poolInfo.mintA.address&&e.toString()!==b.poolInfo.mintB.address)throw new Error("input mint does not match clmm pool mints, please check");let g=e.toString()===b.poolInfo.mintA.address,A=b.poolInfo[g?"mintB":"mintA"],k=c;if(k||(k=await this.scope.launchpad.getRpcPoolInfo({poolId:new pe.PublicKey(i)})),A.address!==k.mintB.toBase58())throw new Error(`clmm swap mint(${A.address}) != launch pool mintB(${k.mintB.toBase58()})`);let h=n?await Pt.computeAmountIn({poolInfo:b.computePoolInfo,tickarrayBitmapExtension:b.computePoolInfo.exBitmapInfo,tickArrayCache:b.tickData[o.toString()],amountOut:t,baseMint:new pe.PublicKey(b.poolInfo[g?"mintB":"mintA"].address),slippage:y,epochInfo:a!=null?a:await this.scope.fetchEpochInfo(),blockTimestamp:f}):await Pt.computeAmountOutFormat({poolInfo:b.computePoolInfo,tickarrayBitmapExtension:b.computePoolInfo.exBitmapInfo,tickArrayCache:b.tickData[o.toString()],amountIn:t,tokenOut:A,slippage:y,epochInfo:a!=null?a:await this.scope.fetchEpochInfo(),blockTimestamp:f}),P=l;if(!P){let H=await this.scope.connection.getAccountInfo(k.platformId);P=wn.decode(H.data)}let T=p!=null?p:await this.scope.token.getTokenInfo(k.mintA),I=Gt(k.programId).publicKey,x=io(T,a==null?void 0:a.epoch),S=Qr(A),B=io(A,a==null?void 0:a.epoch),R=n?t:h.minAmountOut.amount.raw,L=Nt.buyExactIn({poolInfo:k,amountB:R,protocolFeeRate:k.configInfo.tradeFeeRate,platformFeeRate:P.feeRate,curveType:k.configInfo.curveType,shareFeeRate:u,creatorFeeRate:P.creatorFeeRate,transferFeeConfigA:x,transferFeeConfigB:B,slot:m!=null?m:await this.scope.connection.getSlot()}),O=L.amountA.amount.sub((_=L.amountA.fee)!=null?_:new he.default(0)),C=new Ne.default(O.toString()),F=new he.default(1e4),E=y?new Ne.default(F.sub(new he.default(y*1e4)).toNumber()/F.toNumber()).clampedTo(0,1):new Ne.default(1);return{clmmPoolData:b,clmmComputeAmount:{maxClmmAmountIn:n?h.maxAmountIn.amount:t,clmmAmountOut:R,remainingAccounts:h.remainingAccounts},clmmComputeInfo:h,launchPoolInfo:k,launchAuthProgramId:I,launchMintTransferFeeConfig:x,launchMintProgramB:S,launchMintTransferFeeConfigB:B,launchSwapInfo:L,outAmount:L.amountA.amount.sub((z=L.amountA.fee)!=null?z:new he.default(0)),minOutAmount:new he.default(C.mul(E).toFixed(0))}}async swapLaunchMintToClmm({inputAmount:e,clmmPoolId:t,launchPoolId:n,priceLimit:o,slippage:i=.01,shareFeeRate:r=new he.default(0),shareFeeReceiver:a,ownerInfo:u={useSOLBalance:!0},checkCreateATAOwner:s=!1,computeBudgetConfig:c,txVersion:l,blockTimestamp:m}){let p=(u==null?void 0:u.feePayer)||this.scope.ownerPubKey,f=await this.scope.fetchEpochInfo(),{clmmPoolData:y,clmmComputeAmount:{remainingAccounts:b},launchPoolInfo:g,launchAuthProgramId:A,launchSwapInfo:k,launchMintProgramB:h,minLaunchOutAmount:P,outAmount:T,minOutAmount:I}=await this.computeLaunchToClmmAmount({inputAmount:e,clmmPoolId:t,launchPoolId:n,slippage:i,epochInfo:f,shareFeeRate:r,blockTimestamp:m}),x=this.createTxBuilder(p),S={},B=Wr(g.mintProgramFlag),{account:R}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:B,mint:g.mintA,notUseTokenAccount:!1,owner:this.scope.ownerPubKey,skipCloseAccount:!0,createInfo:void 0,associatedOnly:!0,checkCreateATAOwner:s});if(!R)throw new Error(`do not have launch mint(${g.mintA.toString()}) token account`);let L=g.mintB.equals(Z),{account:O,instructionParams:C}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:h,mint:g.mintB,notUseTokenAccount:L,owner:this.scope.ownerPubKey,skipCloseAccount:!L,createInfo:{payer:this.scope.ownerPubKey,amount:0},associatedOnly:!1,checkCreateATAOwner:s});if(C&&x.addInstruction(C),!O)throw new Error(`do not have launch mint(${g.mintA.toString()}) token account`);S[g.mintB.toBase58()]=O,x.addInstruction({instructions:[Dr(g.programId,this.scope.ownerPubKey,A,g.configId,g.platformId,new pe.PublicKey(n),R,O,g.vaultA,g.vaultB,g.mintA,g.mintB,B,h,kn(g.programId,g.platformId,g.mintB).publicKey,Tn(g.programId,g.creator,g.mintB).publicKey,k.amountA.amount.lt(e)?k.amountA.amount:e,P,r,a)]});let F=g.mintB.toString()===y.poolInfo.mintA.address,E=u.useSOLBalance&&y.poolInfo.mintA.address===Z.toBase58(),_=u.useSOLBalance&&y.poolInfo.mintB.address===Z.toBase58(),z;!o||o.equals(new Ne.default(0))?z=F?St.add(new he.default(1)):Kt.sub(new he.default(1)):z=se.priceToSqrtPriceX64(o,y.poolInfo.mintA.decimals,y.poolInfo.mintB.decimals);let[H,Y]=[new pe.PublicKey(y.poolInfo.mintA.address),new pe.PublicKey(y.poolInfo.mintB.address)],[J,ie]=[new pe.PublicKey(y.poolInfo.mintA.programId),new pe.PublicKey(y.poolInfo.mintB.programId)],Q=E?void 0:this.scope.account.getAssociatedTokenAccount(H,J),ge=_?void 0:this.scope.account.getAssociatedTokenAccount(Y,ie);if(!Q){let{account:re,instructionParams:ke}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:J,mint:H,notUseTokenAccount:!0,owner:this.scope.ownerPubKey,skipCloseAccount:!1,createInfo:{payer:u.feePayer||this.scope.ownerPubKey,amount:F?e:0},associatedOnly:!1,checkCreateATAOwner:s});Q=re,ke&&x.addInstruction(ke)}if(!ge){let{account:re,instructionParams:ke}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:ie,mint:Y,notUseTokenAccount:!0,owner:this.scope.ownerPubKey,skipCloseAccount:!1,createInfo:{payer:u.feePayer||this.scope.ownerPubKey,amount:F?0:e},associatedOnly:!1,checkCreateATAOwner:s});ge=re,ke&&x.addInstruction(ke)}return S[y.poolInfo.mintA.address]=Q,S[y.poolInfo.mintB.address]=ge,(!Q||!ge)&&this.logAndCreateError("user do not have token account",{ownerTokenAccountA:Q,ownerTokenAccountB:ge}),x.addInstruction(we.makeSwapBaseInInstructions({poolInfo:y.poolInfo,poolKeys:y.poolKeys,observationId:y.computePoolInfo.observationId,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:Q,tokenAccountB:ge},inputMint:new pe.PublicKey(y.poolKeys[F?"mintA":"mintB"].address),amountIn:P,amountOutMin:I,sqrtPriceLimitX64:z,remainingAccounts:b})),x.addCustomComputeBudget(c),x.versionBuild({txVersion:l,extInfo:{routes:[{mint:g.mintA,amount:e,decimal:g.mintDecimalsA},{mint:g.mintB,amount:P,decimal:g.mintDecimalsB},{mint:new pe.PublicKey(y.poolKeys[F?"mintB":"mintA"].address),amount:T,decimal:y.poolKeys[F?"mintB":"mintA"].decimals}],outAmount:T,minOutAmount:I}})}async computeLaunchToClmmAmount({inputAmount:e,clmmPoolId:t,launchPoolId:n,slippage:o,epochInfo:i,shareFeeRate:r=new he.default(0),clmmPoolData:a,launchPoolInfo:u,launchPlatformInfo:s,blockTimestamp:c}){let l=o>0?new Ne.default(o).div(2).toDecimalPlaces(4,Ne.default.ROUND_DOWN).toNumber():o,m=u;m||(m=await this.scope.launchpad.getRpcPoolInfo({poolId:new pe.PublicKey(n)}));let p=m.mintB,f=a!=null?a:await this.scope.clmm.getPoolInfoFromRpc(t.toString());if(p.toString()!==f.poolInfo.mintA.address&&p.toString()!==f.poolInfo.mintB.address)throw new Error("input mint does not match clmm pool mints, please check");let y=p.toString()===f.poolInfo.mintA.address,b=f.poolInfo[y?"mintB":"mintA"],g=f.poolInfo[y?"mintA":"mintB"],A=s;if(!A){let F=await this.scope.connection.getAccountInfo(m.platformId);A=wn.decode(F.data)}let k=await this.scope.token.getTokenInfo(m.mintA),h=Gt(m.programId).publicKey,P=io(k,i==null?void 0:i.epoch),T=Qr(g),I=io(g,i==null?void 0:i.epoch),x=Nt.sellExactIn({poolInfo:m,amountA:e,protocolFeeRate:m.configInfo.tradeFeeRate,platformFeeRate:A.feeRate,curveType:m.configInfo.curveType,shareFeeRate:r,creatorFeeRate:A.creatorFeeRate,transferFeeConfigA:P,transferFeeConfigB:I,slot:await this.scope.connection.getSlot()}),S=x.amountB,B=new Ne.default(S.toString()),R=new he.default(1e4),L=l?new Ne.default(R.sub(new he.default(l*1e4)).toNumber()/R.toNumber()).clampedTo(0,1):new Ne.default(1),O=new he.default(B.mul(L).toFixed(0)),C=await Pt.computeAmountOutFormat({poolInfo:f.computePoolInfo,tickarrayBitmapExtension:f.computePoolInfo.exBitmapInfo,tickArrayCache:f.tickData[t.toString()],amountIn:O,tokenOut:b,slippage:l,epochInfo:i!=null?i:await this.scope.fetchEpochInfo(),blockTimestamp:c});return{clmmPoolData:f,clmmComputeAmount:C,launchPoolInfo:m,launchAuthProgramId:h,launchMintTransferFeeConfig:P,launchMintProgramB:T,launchMintTransferFeeConfigB:I,launchSwapInfo:x,minLaunchOutAmount:O,outAmount:C.amountOut.amount.raw,minOutAmount:C.minAmountOut.amount.raw}}async swapCpmmToLaunchMint({inputMint:e,inputAmount:t,cpmmPoolId:n,launchPoolId:o,poolKeys:i,slippage:r=.01,shareFeeRate:a=new he.default(0),shareFeeReceiver:u,launchPlatformInfo:s,slot:c,mintInfo:l,epochInfo:m,ownerInfo:p={useSOLBalance:!0},checkCreateATAOwner:f=!1,computeBudgetConfig:y,txVersion:b}){let g=(p==null?void 0:p.feePayer)||this.scope.ownerPubKey,A=m!=null?m:await this.scope.fetchEpochInfo(),{computePoolInfo:k,poolKeys:h}=await this.scope.cpmm.getPoolInfoFromRpc(n.toString()),{cpmmComputInfo:P,cpmmPoolData:T,launchPoolInfo:I,launchAuthProgramId:x,launchSwapInfo:S,launchMintProgramB:B,outAmount:R,minOutAmount:L}=await this.computeCpmmToLaunchAmount({inputMint:e,inputAmount:t,cpmmPoolId:n,cpmmPoolData:k,launchPoolId:o,slippage:r,epochInfo:A,shareFeeRate:a,launchPlatformInfo:s,slot:c,mintInfo:l}),O=e.toString()===T.mintA.address,C=p.useSOLBalance&&T.mintA.address===Z.toBase58(),F=p.useSOLBalance&&T.mintB.address===Z.toBase58(),E={},_=this.createTxBuilder(g),[z,H]=[new pe.PublicKey(T.mintA.address),new pe.PublicKey(T.mintB.address)],[Y,J]=[new pe.PublicKey(T.mintA.programId),new pe.PublicKey(T.mintB.programId)],ie=this.scope.account.getAssociatedTokenAccount(z,Y),Q=this.scope.account.getAssociatedTokenAccount(H,J);_.addInstruction({instructions:[(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,ie,this.scope.ownerPubKey,z,Y),(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Q,this.scope.ownerPubKey,H,J)]}),(O&&C||!O&&F)&&_.addInstruction({instructions:[pe.SystemProgram.transfer({fromPubkey:this.scope.ownerPubKey,toPubkey:O?ie:Q,lamports:BigInt(P.amountIn.toString())}),(0,Pe.createSyncNativeInstruction)(O?ie:Q)]}),E[T.mintA.address]=ie,E[T.mintB.address]=Q,(!ie||!Q)&&this.logAndCreateError("user do not have token account",{ownerTokenAccountA:ie,ownerTokenAccountB:Q});let ge=i!=null?i:h;_.addInstruction({instructions:[qo(T.programId,this.scope.ownerPubKey,new pe.PublicKey(ge.authority),new pe.PublicKey(ge.config.id),T.id,O?ie:Q,O?Q:ie,new pe.PublicKey(ge.vault[O?"A":"B"]),new pe.PublicKey(ge.vault[O?"B":"A"]),new pe.PublicKey(O?Y:J!=null?J:Pe.TOKEN_PROGRAM_ID),new pe.PublicKey(O?J:Y!=null?Y:Pe.TOKEN_PROGRAM_ID),O?z:H,O?H:z,ko(T.programId,T.id).publicKey,t,P.swapResult.outputAmount)]});let re=Wr(I.mintProgramFlag),ke=this.scope.account.getAssociatedTokenAccount(I.mintA,re),Fe=E[I.mintB.toBase58()];if(_.addInstruction({instructions:[(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,ke,this.scope.ownerPubKey,I.mintA,re)]}),!Fe){let Le=I.mintB.equals(Z),{account:Ae,instructionParams:ae}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:B,mint:I.mintB,notUseTokenAccount:Le,owner:this.scope.ownerPubKey,skipCloseAccount:!Le,createInfo:Le?{payer:this.scope.ownerPubKey,amount:P.minAmountOut}:void 0,associatedOnly:!1,checkCreateATAOwner:f});Fe=Ae,ae&&_.addInstruction(ae)}return _.addInstruction({instructions:[qi(I.programId,this.scope.ownerPubKey,x,I.configId,I.platformId,new pe.PublicKey(o),ke,Fe,I.vaultA,I.vaultB,I.mintA,I.mintB,re,B,kn(I.programId,I.platformId,I.mintB).publicKey,Tn(I.programId,I.creator,I.mintB).publicKey,S.amountB.lt(P.minAmountOut)?S.amountB:P.minAmountOut,L,a,u)]}),_.addCustomComputeBudget(y),_.versionBuild({txVersion:b,extInfo:{routes:[{mint:new pe.PublicKey(e),amount:t,decimal:T[O?"mintDecimalA":"mintDecimalB"]},{mint:O?H:z,amount:P.minAmountOut,decimal:T[O?"mintB":"mintA"].decimals},{mint:I.mintA,amount:R,decimal:I.mintDecimalsA}],outAmount:R,minOutAmount:L}})}async computeCpmmToLaunchAmount({inputMint:e,inputAmount:t,cpmmPoolId:n,launchPoolId:o,slippage:i,epochInfo:r,shareFeeRate:a=new he.default(0),cpmmPoolData:u,launchPoolInfo:s,launchPlatformInfo:c,slot:l,mintInfo:m}){var F,E;let p=i>0?new Ne.default(i).div(2).toDecimalPlaces(4,Ne.default.ROUND_DOWN).toNumber():i,f=u!=null?u:(await this.scope.cpmm.getPoolInfoFromRpc(n.toString())).computePoolInfo;if(e.toString()!==f.mintA.address&&e.toString()!==f.mintB.address)throw new Error("input mint does not match clmm pool mints, please check");let y=e.toString()===f.mintA.address,b=f[y?"mintB":"mintA"],g=s;if(g||(g=await this.scope.launchpad.getRpcPoolInfo({poolId:new pe.PublicKey(o)})),b.address!==g.mintB.toBase58())throw new Error(`clmm swap mint(${b.address}) != launch pool mintB(${g.mintB.toBase58()})`);let A=c;if(!A){let _=await this.scope.connection.getAccountInfo(g.platformId);A=wn.decode(_.data)}let k=m!=null?m:await this.scope.token.getTokenInfo(g.mintA),h=Gt(g.programId).publicKey,P=io(k,r==null?void 0:r.epoch),T=Qr(b),I=io(b,r==null?void 0:r.epoch),x=await this.scope.cpmm.computeSwapAmount({pool:f,amountIn:t,outputMint:new pe.PublicKey(b.address),slippage:p}),S=x.minAmountOut,B=Nt.buyExactIn({poolInfo:g,amountB:S,protocolFeeRate:g.configInfo.tradeFeeRate,platformFeeRate:A.feeRate,curveType:g.configInfo.curveType,shareFeeRate:a,creatorFeeRate:A.creatorFeeRate,transferFeeConfigA:P,transferFeeConfigB:I,slot:l!=null?l:await this.scope.connection.getSlot()}),R=B.amountA.amount.sub((F=B.amountA.fee)!=null?F:new he.default(0)),L=new Ne.default(R.toString()),O=new he.default(1e4),C=p?new Ne.default(O.sub(new he.default(p*1e4)).toNumber()/O.toNumber()).clampedTo(0,1):new Ne.default(1);return{cpmmPoolData:f,cpmmComputInfo:x,launchPoolInfo:g,launchAuthProgramId:h,launchMintTransferFeeConfig:P,launchMintProgramB:T,launchMintTransferFeeConfigB:I,launchSwapInfo:B,outAmount:B.amountA.amount.sub((E=B.amountA.fee)!=null?E:new he.default(0)),minOutAmount:new he.default(L.mul(C).toFixed(0))}}async computeCpClToLaunchAmount({inputMint:e,inputAmount:t,clmmPoolId:n,cpmmPoolId:o,launchPoolId:i,slippage:r,epochInfo:a,shareFeeRate:u=new he.default(0),cpmmPoolData:s,clmmPoolData:c,launchPoolInfo:l,launchPlatformInfo:m,slot:p,mintInfo:f,blockTimestamp:y}){var Q,ge;let b=r>0?new Ne.default(r).div(2).toDecimalPlaces(4,Ne.default.ROUND_DOWN).toNumber():r,g=c!=null?c:await this.scope.clmm.getPoolInfoFromRpc(n.toString());if(e.toString()!==g.poolInfo.mintA.address&&e.toString()!==g.poolInfo.mintB.address)throw new Error("input mint does not match clmm pool mints, please check");let A=e.toString()===g.poolInfo.mintA.address,k=g.poolInfo[A?"mintB":"mintA"],h=l;if(h||(h=await this.scope.launchpad.getRpcPoolInfo({poolId:new pe.PublicKey(i)})),k.address!==h.mintB.toBase58())throw new Error(`clmm swap mint(${k.address}) != launch pool mintB(${h.mintB.toBase58()})`);let P=m;if(!P){let re=await this.scope.connection.getAccountInfo(h.platformId);P=wn.decode(re.data)}let T=f!=null?f:await this.scope.token.getTokenInfo(h.mintA),I=Gt(h.programId).publicKey,x=io(T,a==null?void 0:a.epoch),S=Qr(k),B=io(k,a==null?void 0:a.epoch),R=await Pt.computeAmountOutFormat({poolInfo:g.computePoolInfo,tickArrayCache:g.tickData[n.toString()],amountIn:t,tokenOut:k,slippage:b,epochInfo:a!=null?a:await this.scope.fetchEpochInfo(),blockTimestamp:y,tickarrayBitmapExtension:g.computePoolInfo.exBitmapInfo}),L=s!=null?s:(await this.scope.cpmm.getPoolInfoFromRpc(o.toString())).computePoolInfo,O=await this.scope.cpmm.computeSwapAmount({pool:L,amountIn:t,outputMint:new pe.PublicKey(k.address),slippage:b}),[C,F]=[R.minAmountOut.amount.raw,O.minAmountOut],E=C.gte(F)?"clmm":"cpmm",_=C.gte(F)?C:F,z=Nt.buyExactIn({poolInfo:h,amountB:_,protocolFeeRate:h.configInfo.tradeFeeRate,platformFeeRate:P.feeRate,curveType:h.configInfo.curveType,shareFeeRate:u,creatorFeeRate:P.creatorFeeRate,transferFeeConfigA:x,transferFeeConfigB:B,slot:p!=null?p:await this.scope.connection.getSlot()}),H=z.amountA.amount.sub((Q=z.amountA.fee)!=null?Q:new he.default(0)),Y=new Ne.default(H.toString()),J=new he.default(1e4),ie=b?new Ne.default(J.sub(new he.default(b*1e4)).toNumber()/J.toNumber()).clampedTo(0,1):new Ne.default(1);return{clmmPoolData:g,clmmComputeAmount:{maxClmmAmountIn:t,clmmAmountOut:_,remainingAccounts:R.remainingAccounts},clmmComputeInfo:R,cpmmComputInfo:O,swapPoolType:E,launchPoolInfo:h,launchAuthProgramId:I,launchMintTransferFeeConfig:x,launchMintProgramB:S,launchMintTransferFeeConfigB:B,launchSwapInfo:z,outAmount:z.amountA.amount.sub((ge=z.amountA.fee)!=null?ge:new he.default(0)),minOutAmount:new he.default(Y.mul(ie).toFixed(0))}}async fetchRoutePoolBasicInfo(e){let{amm:t=dr,clmm:n=Fn,cpmm:o=Zn}=e||{},i=await this.scope.connection.getProgramAccounts(t,{dataSlice:{offset:Nr.offsetOf("baseMint"),length:64}}),r=v([M("baseMint"),M("quoteMint")]),a=i.map(p=>({id:p.pubkey,version:4,mintA:r.decode(p.account.data).baseMint,mintB:r.decode(p.account.data).quoteMint})),u=v([M("mintA"),M("mintB")]),c=(await this.scope.connection.getProgramAccounts(n,{filters:[{dataSize:fo.span}],dataSlice:{offset:fo.offsetOf("mintA"),length:64}})).map(p=>{let f=u.decode(p.account.data);return{id:p.pubkey,version:6,mintA:f.mintA,mintB:f.mintB}}),m=(await this.scope.connection.getProgramAccounts(o,{dataSlice:{offset:Rr.offsetOf("mintA"),length:64}})).map(p=>{let f=u.decode(p.account.data);return{id:p.pubkey,version:7,mintA:f.mintA,mintB:f.mintB}});return{clmmPools:c,ammPools:a,cpmmPools:m}}getAllRoute({inputMint:e,outputMint:t,clmmPools:n,ammPools:o,cpmmPools:i}){e=e.toString()===pe.PublicKey.default.toString()?Z:e,t=t.toString()===pe.PublicKey.default.toString()?Z:t;let r={},a={},u={},s=[],c={};for(let m of n!=null?n:[]){if((m.mintA.equals(e)&&m.mintB.equals(t)||m.mintA.equals(t)&&m.mintB.equals(e))&&(s.push(m),a[m.id.toString()]=m),m.mintA.equals(e)){let p=m.mintB.toString();c[p]===void 0&&(c[p]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p].in.push(m)}if(m.mintB.equals(e)){let p=m.mintA.toString();c[p]===void 0&&(c[p]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p].in.push(m)}if(m.mintA.equals(t)){let p=m.mintB.toString();c[p]===void 0&&(c[p]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p].out.push(m)}if(m.mintB.equals(t)){let p=m.mintA.toString();c[p]===void 0&&(c[p]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p].out.push(m)}}let l=[];for(let m of o)(m.mintA.equals(e)&&m.mintB.equals(t)||m.mintA.equals(t)&&m.mintB.equals(e))&&(s.push(m),r[m.id.toBase58()]=m,l.push(m)),m.mintA.equals(e)&&(c[m.mintB.toBase58()]===void 0&&(c[m.mintB.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[m.mintB.toBase58()].in.push(m)),m.mintB.equals(e)&&(c[m.mintA.toBase58()]===void 0&&(c[m.mintA.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[m.mintA.toBase58()].in.push(m)),m.mintA.equals(t)&&(c[m.mintB.toBase58()]===void 0&&(c[m.mintB.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[m.mintB.toBase58()].out.push(m)),m.mintB.equals(t)&&(c[m.mintA.toBase58()]===void 0&&(c[m.mintA.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[m.mintA.toBase58()].out.push(m));for(let m of i)(m.mintA.equals(e)&&m.mintB.equals(t)||m.mintA.equals(t)&&m.mintB.equals(e))&&(s.push(m),u[m.id.toBase58()]=m),m.mintA.equals(e)&&(c[m.mintB.toBase58()]===void 0&&(c[m.mintB.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[m.mintB.toBase58()].in.push(m)),m.mintB.equals(e)&&(c[m.mintA.toBase58()]===void 0&&(c[m.mintA.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[m.mintA.toBase58()].in.push(m)),m.mintA.equals(t)&&(c[m.mintB.toBase58()]===void 0&&(c[m.mintB.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[m.mintB.toBase58()].out.push(m)),m.mintB.equals(t)&&(c[m.mintA.toBase58()]===void 0&&(c[m.mintA.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[m.mintA.toBase58()].out.push(m));for(let m of Object.keys(c)){if(c[m].in.length===1&&c[m].out.length===1&&c[m].in[0].id.equals(c[m].out[0].id)){delete c[m];continue}if(c[m].in.length===0||c[m].out.length===0){delete c[m];continue}let p=c[m];for(let f of p.in)for(let y of p.out)f.version===6&&a[f.id.toString()]===void 0?a[f.id.toString()]=f:f.version===7&&u[f.id.toString()]===void 0?u[f.id.toString()]=f:(f.version===4||f.version===5)&&r[f.id.toString()]===void 0&&(r[f.id.toString()]=f),y.version===6&&a[y.id.toString()]===void 0?a[y.id.toString()]=y:y.version===7&&u[y.id.toString()]===void 0?u[y.id.toString()]=y:(y.version===4||y.version===5)&&r[y.id.toString()]===void 0&&(r[y.id.toString()]=y)}return{directPath:s,addLiquidityPools:l,routePathDict:c,needSimulate:Object.values(r),needTickArray:Object.values(a),cpmmPoolList:Object.values(u)}}async fetchSwapRoutesData({routes:e,inputMint:t,outputMint:n}){let o=new Set([...e.needTickArray.map(y=>[y.mintA.toBase58(),y.mintB.toBase58()]).flat(),t.toString(),n.toString()]);console.log("fetching amm pools info, total: ",e.needSimulate.length);let i=await this.scope.liquidity.getRpcPoolInfos(e.needSimulate.map(y=>y.id)),r=Fr(i),a={};Object.values(r).forEach(y=>{o.delete(y.mintA.address),a[y.mintA.address]={address:new pe.PublicKey(y.mintA.address),programId:Pe.TOKEN_PROGRAM_ID,mintAuthority:null,supply:BigInt(0),decimals:y.mintA.decimals,isInitialized:!0,freezeAuthority:null,tlvData:Buffer.from("0","hex"),feeConfig:void 0},o.delete(y.mintB.address),a[y.mintB.address]={address:new pe.PublicKey(y.mintB.address),programId:Pe.TOKEN_PROGRAM_ID,mintAuthority:null,supply:BigInt(0),decimals:y.mintB.decimals,isInitialized:!0,freezeAuthority:null,tlvData:Buffer.from("0","hex"),feeConfig:void 0}}),console.log("fetching cpmm pools info, total: ",e.cpmmPoolList.length);let u=await this.scope.cpmm.getRpcPoolInfos(e.cpmmPoolList.map(y=>y.id.toBase58()),!0);Object.values(u).forEach(y=>{let[b,g]=[y.mintA.toBase58(),y.mintB.toBase58()];y.mintProgramA.equals(Pe.TOKEN_PROGRAM_ID)?(o.delete(b),a[b]={address:y.mintA,programId:y.mintProgramA,mintAuthority:null,supply:BigInt(0),decimals:y.mintDecimalA,isInitialized:!0,freezeAuthority:null,tlvData:Buffer.from("0","hex"),feeConfig:void 0}):o.add(b),y.mintProgramB.equals(Pe.TOKEN_PROGRAM_ID)?(o.delete(g),a[g]={address:y.mintB,programId:y.mintProgramB,mintAuthority:null,supply:BigInt(0),decimals:y.mintDecimalB,isInitialized:!0,freezeAuthority:null,tlvData:Buffer.from("0","hex"),feeConfig:void 0}):o.add(g)}),console.log("fetching mints info, total: ",o.size);let s=await so({connection:this.scope.connection,mints:Array.from(o).map(y=>new pe.PublicKey(y))});a=N(N({},a),s);let c=this.scope.cpmm.toComputePoolInfos({pools:u,mintInfos:a});console.log("fetching clmm pools info, total:",e.needTickArray.length);let l=await this.scope.clmm.getRpcClmmPoolInfos({poolIds:e.needTickArray.map(y=>y.id)}),{computeClmmPoolInfo:m,computePoolTickData:p}=await this.scope.clmm.getComputeClmmPoolInfos({clmmPoolsRpcInfo:l,mintInfos:a}),f=Object.keys(e.routePathDict).reduce((y,b)=>V(N({},y),{[b]:V(N({},e.routePathDict[b]),{mintProgram:a[b].programId,mDecimals:a[b].decimals,in:e.routePathDict[b].in.map(g=>r[g.id.toBase58()]||m[g.id.toBase58()]||c[g.id.toBase58()]),out:e.routePathDict[b].out.map(g=>r[g.id.toBase58()]||m[g.id.toBase58()]||c[g.id.toBase58()])})}),{});return{mintInfos:a,ammPoolsRpcInfo:i,ammSimulateCache:r,clmmPoolsRpcInfo:l,computeClmmPoolInfo:m,computePoolTickData:p,computeCpmmData:c,routePathDict:f}}getAllRouteComputeAmountOut({inputTokenAmount:e,outputToken:t,directPath:n,routePathDict:o,simulateCache:i,tickCache:r,slippage:a,chainTime:u,epochInfo:s,feeConfig:c,blockTimestamp:l}){var A,k,h,P,T,I,x,S,B;let m=c===void 0?new he.default(0):e.raw.mul(new he.default(c.feeBps.toNumber())).div(new he.default(1e4)),p=e.raw.sub(m),f=new _e(e.token,p),y=c===void 0?void 0:{feeAmount:m,feeAccount:c.feeAccount},b=V(N({},t),{address:Ot(t.address).toString()}),g=[];for(let R of n)try{g.push(V(N({},this.computeAmountOut({itemPool:R,tickCache:r,simulateCache:i,chainTime:u,epochInfo:s,slippage:a,outputToken:b,amountIn:f,blockTimestamp:l})),{feeConfig:y}))}catch(L){this.logDebug("direct error",R.version,R.id.toString(),L.message)}this.logDebug("direct done");for(let[R,L]of Object.entries(o)){let O={chainId:101,address:R,programId:L.mintProgram.toBase58(),logoURI:"",symbol:"",name:"",decimals:L.mDecimals,tags:[],extensions:{}},C=L.in.map(E=>{try{return{pool:E,data:this.computeAmountOut({itemPool:E,tickCache:r,simulateCache:i,chainTime:u,epochInfo:s,slippage:a,outputToken:O,amountIn:f,blockTimestamp:l})}}catch(_){this.logDebug("route in error",E.version,E.id.toString(),_.message);return}}).sort((E,_)=>{var Y,J,ie,Q;let z=E===void 0?Lt:E.data.amountOut.amount.raw.sub((J=(Y=E.data.amountOut.fee)==null?void 0:Y.raw)!=null?J:Lt),H=_===void 0?Lt:_.data.amountOut.amount.raw.sub((Q=(ie=_.data.amountOut.fee)==null?void 0:ie.raw)!=null?Q:Lt);return z.lt(H)?1:-1})[0];if(C===void 0)continue;let F=new _e(hi(O),C.data.amountOut.amount.raw.sub((k=(A=C.data.amountOut.fee)==null?void 0:A.raw)!=null?k:Lt));for(let E of L.out)try{let _=this.computeAmountOut({itemPool:E,tickCache:r,simulateCache:i,chainTime:u,epochInfo:s,slippage:a,outputToken:b,amountIn:F,blockTimestamp:l});g.push(V(N({},_),{allTrade:!!(C.data.allTrade&&_.allTrade),amountIn:C.data.amountIn,amountOut:_.amountOut,minAmountOut:_.minAmountOut,currentPrice:void 0,executionPrice:new Ne.default(new qt({baseToken:C.data.amountIn.amount.token,denominator:C.data.amountIn.amount.raw,quoteToken:_.amountOut.amount.token,numerator:_.amountOut.amount.raw.sub((P=(h=_.amountOut.fee)==null?void 0:h.raw)!=null?P:Lt)}).toFixed()),priceImpact:new Ne.default(C.data.priceImpact.add(_.priceImpact).toFixed()),fee:[C.data.fee[0],_.fee[0]],routeType:"route",poolInfoList:[C.pool,E],remainingAccounts:[C.data.remainingAccounts[0],_.remainingAccounts[0]],minMiddleAmountFee:(T=_.amountOut.fee)!=null&&T.raw?new _e(C.data.amountOut.amount.token,((x=(I=C.data.amountOut.fee)==null?void 0:I.raw)!=null?x:Lt).add((B=(S=_.amountOut.fee)==null?void 0:S.raw)!=null?B:Lt)):void 0,middleToken:C.data.amountOut.amount.token,poolReady:C.data.poolReady&&_.poolReady,poolType:[C.data.poolType,_.poolType],feeConfig:y,expirationTime:En(C.data.expirationTime,_.expirationTime)}))}catch(_){this.logDebug("route out error",E.version,E.id.toString(),_.message)}}return g.filter(R=>(R.allTrade||this.logDebug(`pool ${R.poolInfoList.map(L=>L.id.toString()).join(",")} filter out since not all trade`),R.allTrade)).sort((R,L)=>R.amountOut.amount.raw.sub(L.amountOut.amount.raw).gt(Lt)?-1:1)}getAllRouteComputeAmountIn({outputTokenAmount:e,directPath:t,routePathDict:n,simulateCache:o,tickCache:i,slippage:r,chainTime:a,epochInfo:u,blockTimestamp:s,feeConfig:c}){var p,f,y,b,g,A,k,h,P;let l=wt({address:Ot(e.token.mint).toBase58(),decimals:e.token.decimals,programId:e.token.isToken2022?Pe.TOKEN_2022_PROGRAM_ID.toBase58():Pe.TOKEN_PROGRAM_ID.toBase58(),extensions:{}}),m=[];for(let T of t)try{let I=this.computeAmountIn({itemPool:T,tickCache:i,simulateCache:o,chainTime:a,epochInfo:u,slippage:r,outputToken:l,amountOut:e.raw,blockTimestamp:s}),x=c===void 0?new he.default(0):I.amountIn.amount.raw.mul(new he.default(c.feeBps.toNumber())).div(new he.default(1e4));m.push(V(N({},I),{feeConfig:c===void 0?void 0:{feeAmount:x,feeAccount:c.feeAccount}}))}catch(I){this.logDebug("direct error",T.version,T.id.toString(),I.message)}this.logDebug("direct done");for(let[T,I]of Object.entries(n)){let x={chainId:101,address:T,programId:I.mintProgram.toBase58(),logoURI:"",symbol:"",name:"",decimals:I.mDecimals,tags:[],extensions:{}},S=I.out.map(R=>{try{return{pool:R,data:this.computeAmountIn({itemPool:R,tickCache:i,simulateCache:o,chainTime:a,epochInfo:u,slippage:r,outputToken:l,amountOut:e.raw,blockTimestamp:s})}}catch(L){this.logDebug("route in error",R.version,R.id.toString(),L.message);return}}).sort((R,L)=>{var F,E,_,z;let O=R===void 0?Lt:R.data.amountIn.amount.raw.add((E=(F=R.data.amountIn.fee)==null?void 0:F.raw)!=null?E:Lt),C=L===void 0?Lt:L.data.amountIn.amount.raw.add((z=(_=L.data.amountIn.fee)==null?void 0:_.raw)!=null?z:Lt);return O.lt(C)?-1:1})[0];if(S===void 0)continue;let B=new _e(hi(x),S.data.amountIn.amount.raw.add((f=(p=S.data.amountIn.fee)==null?void 0:p.raw)!=null?f:Lt));for(let R of I.in)try{let L=this.computeAmountIn({itemPool:R,tickCache:i,simulateCache:o,chainTime:a,epochInfo:u,slippage:r,outputToken:x,amountOut:B.raw,blockTimestamp:s}),O=c===void 0?new he.default(0):L.amountIn.amount.raw.mul(new he.default(c.feeBps.toNumber())).div(new he.default(1e4));m.push(V(N({},L),{allTrade:!!(L.allTrade&&S.data.allTrade),amountIn:L.amountIn,amountOut:S.data.amountOut,maxAmountIn:L.maxAmountIn,currentPrice:void 0,executionPrice:new Ne.default(new qt({baseToken:S.data.amountIn.amount.token,denominator:S.data.amountIn.amount.raw,quoteToken:L.amountOut.amount.token,numerator:L.amountOut.amount.raw.sub((b=(y=L.amountOut.fee)==null?void 0:y.raw)!=null?b:Lt)}).toFixed()),priceImpact:new Ne.default(S.data.priceImpact.add(L.priceImpact).toFixed()),fee:[L.fee[0],S.data.fee[0]],routeType:"route",poolInfoList:[S.pool,R],remainingAccounts:[S.data.remainingAccounts[0],L.remainingAccounts[0]],minMiddleAmountFee:(g=L.amountOut.fee)!=null&&g.raw?new _e(S.data.amountOut.amount.token,((k=(A=S.data.amountOut.fee)==null?void 0:A.raw)!=null?k:Lt).add((P=(h=L.amountOut.fee)==null?void 0:h.raw)!=null?P:Lt)):void 0,middleToken:S.data.amountOut.amount.token,poolReady:S.data.poolReady&&L.poolReady,poolType:[S.data.poolType,L.poolType],feeConfig:c===void 0?void 0:{feeAmount:O,feeAccount:c.feeAccount},expirationTime:En(S.data.expirationTime,L.expirationTime)}))}catch(L){this.logDebug("route out error",R.version,R.id.toString(),L.message)}}return m.filter(T=>(T.allTrade||this.logDebug(`pool ${T.poolInfoList.map(I=>I.id.toString()).join(",")} filter out since not all trade`),T.allTrade)).sort((T,I)=>I.amountIn.amount.raw.sub(T.amountIn.amount.raw).gt(Lt)?-1:1)}computeAmountOut({itemPool:e,tickCache:t,simulateCache:n,chainTime:o,epochInfo:i,slippage:r,outputToken:a,amountIn:u,blockTimestamp:s}){if(e.version===6){let{allTrade:c,realAmountIn:l,amountOut:m,minAmountOut:p,expirationTime:f,currentPrice:y,executionPrice:b,priceImpact:g,fee:A,remainingAccounts:k,executionPriceX64:h}=Pt.computeAmountOutFormat({poolInfo:e,tickarrayBitmapExtension:e.exBitmapInfo,tickArrayCache:t[e.id.toString()],amountIn:u.raw,tokenOut:a,slippage:r,epochInfo:i,catchLiquidityInsufficient:!0,blockTimestamp:s});return{allTrade:c,amountIn:l,amountOut:m,minAmountOut:p,currentPrice:new Ne.default(y.toFixed()),executionPrice:new Ne.default(b.toFixed()),priceImpact:new Ne.default(g.toFixed()),fee:[A],remainingAccounts:[k],routeType:"amm",poolInfoList:[e],poolReady:e.startTime<o,poolType:"CLMM",slippage:r,clmmExPriceX64:[h],expirationTime:En(l.expirationTime,f)}}else if(e.version===7){let{allTrade:c,executionPrice:l,amountOut:m,minAmountOut:p,priceImpact:f,fee:y}=this.scope.cpmm.computeSwapAmount({pool:e,outputMint:a.address,amountIn:u.raw,slippage:r});return{allTrade:c,amountIn:{amount:u,fee:void 0,expirationTime:void 0},amountOut:{amount:bt(V(N({},a),{amount:m})),fee:void 0,expirationTime:void 0},minAmountOut:{amount:bt(V(N({},a),{amount:p})),fee:void 0,expirationTime:void 0},currentPrice:e.poolPrice,executionPrice:l,priceImpact:f,fee:[new _e(u.token,y)],remainingAccounts:[],routeType:"amm",poolInfoList:[e],poolReady:e.openTime.toNumber()<o,poolType:"CPMM",slippage:r,clmmExPriceX64:[void 0],expirationTime:void 0}}else{if(![1,6,7].includes(n[e.id.toString()].status))throw Error("swap error");let{amountOut:c,minAmountOut:l,currentPrice:m,executionPrice:p,priceImpact:f,fee:y}=this.scope.liquidity.computeAmountOut({poolInfo:n[e.id.toString()],amountIn:u.raw,mintIn:u.token.mint,mintOut:a.address,slippage:r});return{amountIn:{amount:u,fee:void 0,expirationTime:void 0},amountOut:{amount:bt(V(N({},a),{amount:c})),fee:void 0,expirationTime:void 0},minAmountOut:{amount:bt(V(N({},a),{amount:l})),fee:void 0,expirationTime:void 0},currentPrice:m,executionPrice:p,priceImpact:f,fee:[new _e(u.token,y)],routeType:"amm",poolInfoList:[e],remainingAccounts:[],poolReady:Number(n[e.id].openTime)<o,poolType:e.version===5?"STABLE":void 0,expirationTime:void 0,allTrade:!0,slippage:r,clmmExPriceX64:[void 0]}}}computeAmountIn({itemPool:e,tickCache:t,simulateCache:n,chainTime:o,epochInfo:i,slippage:r,amountOut:a,outputToken:u,blockTimestamp:s}){let c=u.address===e.mintB.address?e.mintA:e.mintB;if(e.version===6){let{allTrade:l,realAmountOut:m,amountIn:p,maxAmountIn:f,expirationTime:y,currentPrice:b,executionPrice:g,priceImpact:A,fee:k,remainingAccounts:h}=Pt.computeAmountIn({poolInfo:e,tickarrayBitmapExtension:e.exBitmapInfo,tickArrayCache:t[e.id.toString()],amountOut:a,baseMint:new pe.PublicKey(c.address),slippage:r,epochInfo:i,blockTimestamp:s});return{allTrade:l,amountOut:{amount:bt(V(N({},u),{amount:m.amount})),fee:m.fee?bt(V(N({},u),{amount:m.fee})):void 0,expirationTime:void 0},amountIn:{amount:bt(V(N({},c),{amount:p.amount})),fee:p.fee?bt(V(N({},c),{amount:p.fee})):void 0,expirationTime:p.expirationTime},maxAmountIn:{amount:bt(V(N({},c),{amount:f.amount})),fee:f.fee?bt(V(N({},c),{amount:f.fee})):void 0,expirationTime:f.expirationTime},currentPrice:new Ne.default(b.toFixed()),executionPrice:new Ne.default(g.toFixed()),priceImpact:new Ne.default(A.toFixed()),fee:[bt(V(N({},c),{amount:k}))],remainingAccounts:[h],routeType:"amm",poolInfoList:[e],poolReady:e.startTime<o,poolType:"CLMM",slippage:r,clmmExPriceX64:[go(g)],expirationTime:En(m.expirationTime,y)}}else if(e.version===7){let{allTrade:l,executionPrice:m,amountIn:p,amountOut:f,priceImpact:y,fee:b}=this.scope.cpmm.computeSwapAmount({pool:e,outputMint:u.address,amountIn:a,swapBaseIn:!1,slippage:r});return{allTrade:l,amountOut:{amount:bt(V(N({},u),{amount:f})),fee:void 0,expirationTime:void 0},amountIn:{amount:bt(V(N({},c),{amount:p})),fee:void 0,expirationTime:void 0},maxAmountIn:{amount:bt(V(N({},c),{amount:p.mul(new he.default((1+r)*1e4)).div(new he.default(1e4))})),fee:void 0,expirationTime:void 0},currentPrice:e.poolPrice,executionPrice:m,priceImpact:y,fee:[bt(V(N({},c),{amount:b}))],remainingAccounts:[],routeType:"amm",poolInfoList:[e],poolReady:e.openTime.toNumber()<o,poolType:"CPMM",slippage:r,clmmExPriceX64:[void 0],expirationTime:void 0}}else{if(![1,6,7].includes(n[e.id.toString()].status))throw Error("swap error");let{amountIn:l,maxAmountIn:m,currentPrice:p,executionPrice:f,priceImpact:y}=this.scope.liquidity.computeAmountIn({poolInfo:n[e.id.toString()],amountOut:a,mintIn:c.address,mintOut:u.address,slippage:r});return{amountOut:{amount:bt(V(N({},u),{amount:a})),fee:void 0,expirationTime:void 0},amountIn:{amount:bt(V(N({},c),{amount:l})),fee:void 0,expirationTime:void 0},maxAmountIn:{amount:bt(V(N({},c),{amount:m})),fee:void 0,expirationTime:void 0},currentPrice:p,executionPrice:f,priceImpact:y,fee:[bt(V(N({},c),{amount:$}))],routeType:"amm",poolInfoList:[e],remainingAccounts:[],poolReady:Number(n[e.id].openTime)<o,poolType:e.version===5?"STABLE":void 0,expirationTime:void 0,allTrade:!0,slippage:r,clmmExPriceX64:[void 0]}}}async computePoolToPoolKeys({pools:e,clmmRpcData:t={},ammRpcData:n={}}){let o=new Set(e.filter(s=>s.version===6&&!t[s.id.toString()]).map(s=>s.id.toString()));if(o.size>0){let s=await this.scope.clmm.getRpcClmmPoolInfos({poolIds:Array.from(o)});Object.keys(s).forEach(c=>{t[c]=s[c]})}let i=new Set(e.filter(s=>s.version===4&&!n[s.id.toString()]).map(s=>s.id.toString()));if(i.size>0){let s=await this.scope.liquidity.getRpcPoolInfos(Array.from(i));Object.keys(s).forEach(c=>{n[c]=s[c]})}let r=new Set(e.filter(s=>s.version===4).map(s=>s.marketId)),a={};r.size>0&&(await Ge(this.scope.connection,Array.from(r).map(c=>({pubkey:new pe.PublicKey(c)})))).forEach(c=>{if(!c.accountInfo)return;let l=Ns.decode(c.accountInfo.data);a[c.pubkey.toBase58()]={marketId:c.pubkey.toString(),marketProgramId:c.accountInfo.owner.toString(),marketAuthority:Hr.getAssociatedAuthority({programId:c.accountInfo.owner,marketId:c.pubkey}).publicKey.toString(),marketBaseVault:l.baseVault.toString(),marketQuoteVault:l.quoteVault.toString(),marketBids:l.bids.toString(),marketAsks:l.asks.toString(),marketEventQueue:l.eventQueue.toString()}});let u=[];return e.forEach(s=>{if(s.version===6){let c=t[s.id.toString()],l={programId:s.programId.toBase58(),id:s.id.toBase58(),mintA:s.mintA,mintB:s.mintB,openTime:String(s.startTime),vault:{A:c.vaultA.toBase58(),B:c.vaultB.toBase58()},config:V(N({},s.ammConfig),{id:s.ammConfig.id.toString(),defaultRange:0,defaultRangePoint:[]}),rewardInfos:[],observationId:s.observationId.toBase58(),exBitmapAccount:s.exBitmapAccount.toBase58()};u.push(l)}else if(s.version===4){let c=n[s.id.toString()],l=N({programId:s.programId,id:s.id,mintA:s.mintA,mintB:s.mintB,openTime:String(s.openTime),vault:{A:c.baseVault.toBase58(),B:c.quoteVault.toBase58()},authority:bs({programId:new pe.PublicKey(s.programId)}).publicKey.toString(),openOrders:c.openOrders.toBase58(),targetOrders:c.targetOrders.toBase58(),mintLp:s.lpMint},a[s.marketId]||{marketProgramId:c.marketProgramId.toBase58(),marketId:c.marketId.toBase58(),marketAuthority:pe.PublicKey.default.toBase58(),marketBaseVault:pe.PublicKey.default.toBase58(),marketQuoteVault:pe.PublicKey.default.toBase58(),marketBids:pe.PublicKey.default.toBase58(),marketAsks:pe.PublicKey.default.toBase58(),marketEventQueue:pe.PublicKey.default.toBase58()});u.push(l)}else s.version===7&&u.push({observationId:s.observationId.toBase58(),programId:s.programId.toBase58(),id:s.id.toBase58(),mintA:s.mintA,mintB:s.mintB,openTime:String(s.openTime),authority:wo(s.programId).publicKey.toBase58(),vault:{A:s.vaultA.toBase58(),B:s.vaultB.toBase58()},mintLp:wt({address:s.mintLp.toBase58(),programId:Pe.TOKEN_PROGRAM_ID.toBase58(),decimals:s.lpDecimals}),config:V(N({id:s.configId.toBase58()},s.configInfo),{protocolFeeRate:s.configInfo.protocolFeeRate.toNumber(),tradeFeeRate:s.configInfo.tradeFeeRate.toNumber(),fundFeeRate:s.configInfo.fundFeeRate.toNumber(),createPoolFee:s.configInfo.createPoolFee.toString()})})}),u}};var ro=require("@solana/web3.js"),Cl=require("@solana/spl-token"),Fs=te(require("bn.js"));var Dt=class extends ot{static getPdaPoolId(e,t){return de([Dt.SEED_CONFIG.pool.id,t.toBuffer()],e)}static getPdaOwnerId(e,t,n,o){return de([Dt.SEED_CONFIG.owner.id,t.toBuffer(),n.toBuffer(),Buffer.from(new Fs.default(o).toArray())],e)}static async getAllInfo({connection:e,programId:t,poolIds:n,wallet:o,chainTime:i}){if(n.length===0)return[];let r=n.map(c=>Dt.getPdaPoolId(t,c).publicKey),a=[];for(let c=0;c<Dt.VERSION_PROJECT.length;c++)a.push(...r.map(l=>Dt.getPdaOwnerId(t,l,o,c).publicKey));let u=await It(e,[...r,...a]),s=[];for(let c=0;c<u.length;c++){let l=Math.floor(c/n.length),m=c%n.length,p=r[m],f=a[c],y=u[m],b=u[n.length+c];if(!(y&&b)||y.data.length!==Dt.POOL_LAYOUT.span||b.data.length!==Dt.OWNER_LAYOUT.span)continue;let g=Dt.POOL_LAYOUT.decode(y.data),A=Dt.OWNER_LAYOUT.decode(b.data),k=g.openTime.toNumber(),h=g.endTime.toNumber(),P=A.tokenInfo.map(x=>x.debtAmount.gt(new Fs.default(0))).filter(x=>!x).length!==3,T=i>k&&i<h&&g.status===1,I=P&&T;s.push({programId:t,poolId:p,ammId:g.ammId,ownerAccountId:f,snapshotLpAmount:A.lpAmount,project:Dt.VERSION_PROJECT[l],openTime:k,endTime:h,canClaim:I,canClaimErrorType:P?T?void 0:"outOfOperationalTime":"alreadyClaimIt",tokenInfo:g.tokenInfo.map((x,S)=>({mintAddress:x.mintAddress,mintVault:x.mintVault,mintDecimals:x.mintDecimals,perLpLoss:x.perLpLoss,debtAmount:A.tokenInfo[S].debtAmount.add(A.tokenInfo[S].claimedAmount)}))})}return s}async makeClaimTransaction({poolInfo:e,ownerInfo:t,feePayer:n}){t.wallet||this.scope.checkOwner();let o=this.createTxBuilder(n),i=t.wallet||this.scope.ownerPubKey,r=[];for(let s of e.tokenInfo){let{account:c,instructionParams:l}=await this.scope.account.getOrCreateTokenAccount({mint:s.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:s.mintAddress.equals(Ze.WSOL.mint),createInfo:{payer:i,amount:0},skipCloseAccount:!s.mintAddress.equals(Ze.WSOL.mint),associatedOnly:s.mintAddress.equals(Ze.WSOL.mint)?!1:t.associatedOnly});l&&o.addInstruction(l),r.push(c)}o.addInstruction({instructions:[Dt.makeClaimInstruction({programId:e.programId,poolInfo:e,ownerInfo:{wallet:i,ownerPda:e.ownerAccountId,claimAddress:r}})]});let{transaction:a,signers:u}=o.build();return[{transaction:a,signer:u}]}async makeClaimAllTransaction({poolInfos:e,ownerInfo:t,feePayer:n}){let o=this.createTxBuilder(n),i=t.wallet||this.scope.ownerPubKey,r={};for(let c of e){let l=[];for(let m of c.tokenInfo){let{account:p,instructionParams:f}=await this.scope.account.getOrCreateTokenAccount({mint:m.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:m.mintAddress.equals(Ze.WSOL.mint),createInfo:{payer:i,amount:0},skipCloseAccount:!m.mintAddress.equals(Ze.WSOL.mint),associatedOnly:m.mintAddress.equals(Ze.WSOL.mint)?!1:t.associatedOnly});f&&o.addInstruction(f),p&&(r[m.mintAddress.toString()]=p,l.push(p))}o.addInstruction({instructions:[Dt.makeClaimInstruction({programId:c.programId,poolInfo:c,ownerInfo:{wallet:i,ownerPda:c.ownerAccountId,claimAddress:l}})]})}let{transaction:a,signers:u}=o.build(),s=o.allInstructions;return Va(s,[i,...u.map(c=>c.publicKey)])?[{transaction:a,signer:u}]:[{transaction:new ro.Transaction().add(...s.slice(0,o.AllTxData.instructions.length-1)),signer:u},{transaction:new ro.Transaction().add(...s.slice(o.AllTxData.instructions.length-1)),signer:[]},{transaction:new ro.Transaction().add(...o.AllTxData.endInstructions),signer:[]}]}static makeClaimInstruction({programId:e,poolInfo:t,ownerInfo:n}){let o=v([]),i=[{pubkey:n.wallet,isSigner:!0,isWritable:!0},{pubkey:t.poolId,isSigner:!1,isWritable:!0},{pubkey:n.ownerPda,isSigner:!1,isWritable:!0},...n.claimAddress.map(u=>({pubkey:u,isSigner:!1,isWritable:!0})),...t.tokenInfo.map(({mintVault:u})=>({pubkey:u,isSigner:!1,isWritable:!0})),{pubkey:Cl.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}],r=Buffer.alloc(o.span);o.encode({},r);let a=Buffer.from([10,66,208,184,161,6,191,98,...r]);return new ro.TransactionInstruction({keys:i,programId:e,data:a})}},mn=Dt;mn.CLAIMED_NUM=3,mn.POOL_LAYOUT=v([Ie(8),W("bump"),W("status"),w("openTime"),w("endTime"),M("ammId"),j(v([W("mintDecimals"),M("mintAddress"),M("mintVault"),w("perLpLoss"),w("totalClaimedAmount")]),Dt.CLAIMED_NUM,"tokenInfo"),j(w(),10,"padding")]),mn.OWNER_LAYOUT=v([Ie(8),W("bump"),W("version"),M("poolId"),M("owner"),w("lpAmount"),j(v([M("mintAddress"),w("debtAmount"),w("claimedAmount")]),Dt.CLAIMED_NUM,"tokenInfo"),j(w(),4,"padding")]),mn.DEFAULT_POOL_ID=["58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2","6UmmUiYoBjSrhakAobJw8BvkmJtDVxaeBtbt7rxWo1mg","AVs9TA4nWDzfPJE9gGVNJMVhcQy3V9PGazuz33BfG2RA","DVa7Qmb5ct9RCpaU7UTpSaf3GVMYz17vNVU67XpdCRut","7XawhbbxtsRcQA8KTkHT9f9nc6d69UwqCDh6U5EEbEmX","6a1CsrpeZubDjEJE9s1CMVheB6HWM5d7m1cj2jkhyXhj","EoNrn8iUhwgJySD1pHu8Qxm5gSQqLK3za4m8xzD2RuEb","AceAyRTWt4PyB2pHqf2qhDgNZDtKVNaxgL8Ru3V4aN1P","6tmFJbMk5yVHFcFy7X2K8RwHjKLr6KVFLYXpgpBNeAxB"].map(e=>new ro.PublicKey(e)),mn.SEED_CONFIG={pool:{id:Buffer.from("pool_seed","utf8")},owner:{id:Buffer.from("user_claim_seed","utf8")}},mn.VERSION_PROJECT=[void 0,"Francium","Tulip","Larix"];var _s=require("@solana/spl-token"),jo=require("@solana/web3.js"),$o=te(require("bn.js"));var Yt=require("@solana/web3.js"),Zo=require("@solana/spl-token");function Od(d="accountFlags"){let e=new sr(d);return e.addBoolean("initialized"),e.addBoolean("market"),e.addBoolean("openOrders"),e.addBoolean("requestQueue"),e.addBoolean("eventQueue"),e.addBoolean("bids"),e.addBoolean("asks"),e}var vs=v([Ie(5),Od("accountFlags"),M("ownAddress"),w("vaultSignerNonce"),M("baseMint"),M("quoteMint"),M("baseVault"),w("baseDepositsTotal"),w("baseFeesAccrued"),M("quoteVault"),w("quoteDepositsTotal"),w("quoteFeesAccrued"),w("quoteDustThreshold"),M("requestQueue"),M("eventQueue"),M("bids"),M("asks"),w("baseLotSize"),w("quoteLotSize"),w("feeRateBps"),w("referrerRebatesAccrued"),Ie(7)]);function Nd({programId:d,marketInfo:e}){let t=v([W("version"),je("instruction"),w("baseLotSize"),w("quoteLotSize"),at("feeRateBps"),w("vaultSignerNonce"),w("quoteDustThreshold")]),n=[{pubkey:e.id,isSigner:!1,isWritable:!0},{pubkey:e.requestQueue,isSigner:!1,isWritable:!0},{pubkey:e.eventQueue,isSigner:!1,isWritable:!0},{pubkey:e.bids,isSigner:!1,isWritable:!0},{pubkey:e.asks,isSigner:!1,isWritable:!0},{pubkey:e.baseVault,isSigner:!1,isWritable:!0},{pubkey:e.quoteVault,isSigner:!1,isWritable:!0},{pubkey:e.baseMint,isSigner:!1,isWritable:!1},{pubkey:e.quoteMint,isSigner:!1,isWritable:!1},{pubkey:e.authority?e.quoteMint:Yt.SYSVAR_RENT_PUBKEY,isSigner:!1,isWritable:!1}].concat(e.authority?{pubkey:e.authority,isSigner:!1,isWritable:!1}:[]).concat(e.authority&&e.pruneAuthority?{pubkey:e.pruneAuthority,isSigner:!1,isWritable:!1}:[]),o=Buffer.alloc(t.span);return t.encode({version:0,instruction:0,baseLotSize:e.baseLotSize,quoteLotSize:e.quoteLotSize,feeRateBps:e.feeRateBps,vaultSignerNonce:e.vaultSignerNonce,quoteDustThreshold:e.quoteDustThreshold},o),new Yt.TransactionInstruction({keys:n,programId:d,data:o})}async function Zr({connection:d,wallet:e,marketInfo:t}){var r,a,u,s,c,l,m,p;let n=new Yt.Transaction,o=await d.getMinimumBalanceForRentExemption(165);n.add(Yt.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.baseVault.seed,newAccountPubkey:t.baseVault.publicKey,lamports:o,space:165,programId:Zo.TOKEN_PROGRAM_ID}),Yt.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.quoteVault.seed,newAccountPubkey:t.quoteVault.publicKey,lamports:o,space:165,programId:Zo.TOKEN_PROGRAM_ID}),(0,Zo.createInitializeAccountInstruction)(t.baseVault.publicKey,t.baseMint,t.vaultOwner),(0,Zo.createInitializeAccountInstruction)(t.quoteVault.publicKey,t.quoteMint,t.vaultOwner),Yt.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.id.seed,newAccountPubkey:t.id.publicKey,lamports:await d.getMinimumBalanceForRentExemption(vs.span),space:vs.span,programId:t.programId}));let i=new Yt.Transaction;return i.add(Yt.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.requestQueue.seed,newAccountPubkey:t.requestQueue.publicKey,lamports:t.lowestFeeMarket?6208320:await d.getMinimumBalanceForRentExemption((r=t.requestQueueSpace)!=null?r:5120+12),space:t.lowestFeeMarket?764:(a=t.requestQueueSpace)!=null?a:5120+12,programId:t.programId}),Yt.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.eventQueue.seed,newAccountPubkey:t.eventQueue.publicKey,lamports:t.lowestFeeMarket?79594560:await d.getMinimumBalanceForRentExemption((u=t.eventQueueSpace)!=null?u:262144+12),space:t.lowestFeeMarket?11308:(s=t.eventQueueSpace)!=null?s:262144+12,programId:t.programId}),Yt.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.bids.seed,newAccountPubkey:t.bids.publicKey,lamports:t.lowestFeeMarket?101977920:await d.getMinimumBalanceForRentExemption((c=t.orderbookQueueSpace)!=null?c:65536+12),space:t.lowestFeeMarket?14524:(l=t.orderbookQueueSpace)!=null?l:65536+12,programId:t.programId}),Yt.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.asks.seed,newAccountPubkey:t.asks.publicKey,lamports:t.lowestFeeMarket?101977920:await d.getMinimumBalanceForRentExemption((m=t.orderbookQueueSpace)!=null?m:65536+12),space:t.lowestFeeMarket?14524:(p=t.orderbookQueueSpace)!=null?p:65536+12,programId:t.programId}),Nd({programId:t.programId,marketInfo:{id:t.id.publicKey,requestQueue:t.requestQueue.publicKey,eventQueue:t.eventQueue.publicKey,bids:t.bids.publicKey,asks:t.asks.publicKey,baseVault:t.baseVault.publicKey,quoteVault:t.quoteVault.publicKey,baseMint:t.baseMint,quoteMint:t.quoteMint,baseLotSize:t.baseLotSize,quoteLotSize:t.quoteLotSize,feeRateBps:t.feeRateBps,vaultSignerNonce:t.vaultSignerNonce,quoteDustThreshold:t.quoteDustThreshold}})),[{transaction:n,signer:[],instructionTypes:[X.CreateAccount,X.CreateAccount,X.InitAccount,X.InitAccount]},{transaction:i,signer:[],instructionTypes:[X.CreateAccount,X.CreateAccount,X.CreateAccount,X.CreateAccount,X.CreateAccount,X.InitMarket]}]}var Jo=class extends ot{async create({baseInfo:e,quoteInfo:t,lotSize:n,tickSize:o,dexProgramId:i,requestQueueSpace:r,eventQueueSpace:a,orderbookQueueSpace:u,lowestFeeMarket:s,assignSeed:c,txVersion:l,computeBudgetConfig:m,txTipConfig:p,feePayer:f}){let y=this.scope.ownerPubKey,b=c?`${e.mint.toBase58().slice(0,10)}-${t.mint.toBase58().slice(0,10)}-${c}`:void 0,g=st({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-market`}),A=st({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-request`}),k=st({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-event`}),h=st({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-bids`}),P=st({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-asks`}),T=st({fromPublicKey:y,programId:_s.TOKEN_PROGRAM_ID,assignSeed:b&&`${b}-baseVault`}),I=st({fromPublicKey:y,programId:_s.TOKEN_PROGRAM_ID,assignSeed:b&&`${b}-quoteVault`}),x=0,S=new $o.default(100);function B(){let _=new $o.default(0);for(;;)try{return{vaultOwner:jo.PublicKey.createProgramAddressSync([g.publicKey.toBuffer(),_.toArrayLike(Buffer,"le",8)],i),vaultSignerNonce:_}}catch{if(_.iaddn(1),_.gt(new $o.default(25555)))throw Error("find vault owner error")}}let{vaultOwner:R,vaultSignerNonce:L}=B(),O=new $o.default(Math.round(10**e.decimals*n)),C=new $o.default(Math.round(n*10**t.decimals*o));if(O.eq($))throw Error("lot size is too small");if(C.eq($))throw Error("tick size or lot size is too small");let F=await Zr({connection:this.scope.connection,wallet:this.scope.ownerPubKey,marketInfo:{programId:i,id:g,baseMint:e.mint,quoteMint:t.mint,baseVault:T,quoteVault:I,vaultOwner:R,requestQueue:A,eventQueue:k,bids:h,asks:P,feeRateBps:x,quoteDustThreshold:S,vaultSignerNonce:L,baseLotSize:O,quoteLotSize:C,requestQueueSpace:r,eventQueueSpace:a,orderbookQueueSpace:u,lowestFeeMarket:s}}),E=this.createTxBuilder(f);E.addInstruction({instructions:F[0].transaction.instructions,signers:F[0].signer});for await(let _ of F.slice(1,F.length))E.addInstruction({instructions:_.transaction.instructions,signers:_.signer,instructionTypes:_.instructionTypes});return l===0?E.sizeCheckBuildV0({computeBudgetConfig:m,address:{marketId:g.publicKey,requestQueue:A.publicKey,eventQueue:k.publicKey,bids:h.publicKey,asks:P.publicKey,baseVault:T.publicKey,quoteVault:I.publicKey,baseMint:new jo.PublicKey(e.mint),quoteMint:new jo.PublicKey(t.mint)}}):E.sizeCheckBuild({computeBudgetConfig:m,address:{marketId:g.publicKey,requestQueue:A.publicKey,eventQueue:k.publicKey,bids:h.publicKey,asks:P.publicKey,baseVault:T.publicKey,quoteVault:I.publicKey,baseMint:new jo.PublicKey(e.mint),quoteMint:new jo.PublicKey(t.mint)}})}};var CI=new qn.default(2),RI=new qn.default(3),LI=new qn.default(5),da=new qn.default(10),OI=new qn.default(100),NI=new qn.default(1e3),MI=new qn.default(1e4);function Aa(d){return da.pow(fe(d))}function jr(d,e){let t=d.divmod(e);return t.mod.isZero()?t.div:d.isNeg()===e.isNeg()?t.div.iaddn(1):t.div}function _i(d,e,t){return d.mul(e).add(t).sub(new qn.default(1)).div(t)}function Lr(d,e,t){return d.mul(e).div(t)}function ca(d,e=1,t=[]){let n=[...d];if(e<=0)return t;for(;n.length;)t.push(n.splice(0,e));return t}var hn=class{constructor(e){this._owner=e}get publicKey(){return hn.isKeyPair(this._owner)?this._owner.publicKey:this._owner}get signer(){return hn.isKeyPair(this._owner)?this._owner:void 0}get isKeyPair(){return hn.isKeyPair(this._owner)}get isPublicKey(){return hn.isPublicKey(this._owner)}static isKeyPair(e){return e.secretKey!==void 0}static isPublicKey(e){return!hn.isKeyPair(e)}};var Xe=te(require("bn.js")),Ln=1e4;function Tt(d,e,t,n){if(e===void 0)return{amount:d,fee:void 0,expirationTime:void 0};let o=V(N({},e),{olderTransferFee:{epoch:BigInt(e.olderTransferFee.epoch),maximumFee:BigInt(e.olderTransferFee.maximumFee),transferFeeBasisPoints:e.olderTransferFee.transferFeeBasisPoints},newerTransferFee:{epoch:BigInt(e.newerTransferFee.epoch),maximumFee:BigInt(e.newerTransferFee.maximumFee),transferFeeBasisPoints:e.newerTransferFee.transferFeeBasisPoints}}),i=t.epoch<o.newerTransferFee.epoch?o.olderTransferFee:o.newerTransferFee,r=new Xe.default(i.maximumFee.toString()),a=t.epoch<o.newerTransferFee.epoch?(Number(o.newerTransferFee.epoch)*t.slotsInEpoch-t.absoluteSlot)*400/1e3:void 0;if(n)if(i.transferFeeBasisPoints===Ln){let u=new Xe.default(i.maximumFee.toString());return{amount:d.add(u),fee:u,expirationTime:a}}else{let u=ao(d.mul(new Xe.default(Ln)),new Xe.default(Ln-i.transferFeeBasisPoints)),s=new Xe.default(i.maximumFee.toString()),c=u.sub(d).gt(s)?d.add(s):u,l=ao(c.mul(new Xe.default(i.transferFeeBasisPoints)),new Xe.default(Ln)),m=l.gt(r)?r:l;return{amount:c,fee:m,expirationTime:a}}else{let u=ao(d.mul(new Xe.default(i.transferFeeBasisPoints)),new Xe.default(Ln)),s=u.gt(r)?r:u;return{amount:d,fee:s,expirationTime:a}}}function En(d,e){return d===void 0?e:e===void 0?d:Math.min(d,e)}function ao(d,e){let{div:t,mod:n}=d.divmod(e);return n.gt(new Xe.default(0))?t.add(new Xe.default(1)):t}function So(d,e){if(d.isZero())return new Xe.default(0);let t=d.div(e);return t.isZero()?new Xe.default(1):d.mod(e).gt(new Xe.default(0))?t.add(new Xe.default(1)):t}function Xi(d,e,t){if(e===void 0)return{amount:d,fee:void 0,expirationTime:void 0};let n=Math.floor(t/432e3),o=n<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,i=new Xe.default(o.maximumFee.toString()),r=n<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*432e3-t)*400/1e3:void 0,a=ao(d.mul(new Xe.default(o.transferFeeBasisPoints)),new Xe.default(Ln)),u=a.gt(i)?i:a;return{amount:d,fee:u,expirationTime:r}}function Ho(d,e,t){if(e===void 0)return{amount:d,fee:void 0,expirationTime:void 0};let n=Math.floor(t/432e3),o=n<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,i=new Xe.default(o.maximumFee.toString()),r=n<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*432e3-t)*400/1e3:void 0;if(o.transferFeeBasisPoints===Ln){let a=new Xe.default(o.maximumFee.toString());return{amount:d.add(a),fee:a,expirationTime:r}}else{let a=ao(d.mul(new Xe.default(Ln)),new Xe.default(Ln-o.transferFeeBasisPoints)),u=new Xe.default(o.maximumFee.toString()),s=a.sub(d).gt(u)?d.add(u):a,c=ao(s.mul(new Xe.default(o.transferFeeBasisPoints)),new Xe.default(Ln)),l=c.gt(i)?i:c;return{amount:s,fee:l,expirationTime:r}}}var it={BASE_HOST:"https://api-v3.raydium.io",OWNER_BASE_HOST:"https://owner-v1.raydium.io",SERVICE_BASE_HOST:"https://service.raydium.io",MONITOR_BASE_HOST:"https://monitor.raydium.io",SERVICE_1_BASE_HOST:"https://service-v1.raydium.io",TEMP_HOST:"https://temp-api-v1.raydium.io",SEND_TRANSACTION:"/send-transaction",FARM_ARP:"/main/farm/info",FARM_ARP_LINE:"/main/farm-apr-tv",CLMM_CONFIG:"/main/clmm-config",CPMM_CONFIG:"/main/cpmm-config",CLMM_DYNAMIC_CONFIG:"/main/clmm-dynamic-config",VERSION:"/main/version",CHECK_AVAILABILITY:"/v3/main/AvailabilityCheckAPI",RPCS:"/main/rpcs",INFO:"/main/info",STAKE_POOLS:"/main/stake-pools",CHAIN_TIME:"/main/chain-time",TOKEN_LIST:"/mint/list",MINT_INFO_ID:"/mint/ids",JUP_TOKEN_LIST:"https://lite-api.jup.ag/tokens/v2/tag?query=verified",POOL_LIST:"/pools/info/list-v2",POOL_SEARCH_BY_ID:"/pools/info/ids",POOL_SEARCH_MINT:"/pools/info/list-v2",POOL_SEARCH_LP:"/pools/info/lps",POOL_KEY_BY_ID:"/pools/key/ids",POOL_LIQUIDITY_LINE:"/pools/line/liquidity",POOL_POSITION_LINE:"/pools/line/position",FARM_INFO:"/farms/info/ids",FARM_LP_INFO:"/farms/info/lp",FARM_KEYS:"/farms/key/ids",OWNER_CREATED_FARM:"/create-pool/{owner}",OWNER_STAKE_FARMS:"/position/stake/{owner}",OWNER_LOCK_POSITION:"/position/clmm-lock/{owner}",SWAP_HOST:"https://transaction-v1.raydium.io",SWAP_COMPUTE:"/compute/",SWAP_TX:"/transaction/",MINT_PRICE:"/mint/price",MIGRATE_CONFIG:"/main/migrate-lp",PRIORITY_FEE:"/main/auto-fee",CPMM_LOCK:"https://dynamic-ipfs.raydium.io/lock/cpmm/position",LAUNCH_AUTH_HOST:"https://launch-auth-v1.raydium.io",LAUNCH_COMMENT_HOST:"hhttps://launch-forum-v1.raydium.io",LAUNCH_HISTORY_HOST:"https://launch-history-v1.raydium.io",LAUNCH_MINT_HOST:"https://launch-mint-v1.raydium.io"},Rl=V(N({},it),{BASE_HOST:"https://api-v3-devnet.raydium.io",OWNER_BASE_HOST:"https://owner-v1-devnet.raydium.io",SWAP_HOST:"https://transaction-v1-devnet.raydium.io",CPMM_LOCK:"https://dynamic-ipfs-devnet.raydium.io/lock/cpmm/position",TEMP_HOST:"https://temp-api-v1-devnet.raydium.io",LAUNCH_AUTH_HOST:"https://launch-auth-v1-devnet.raydium.io",LAUNCH_COMMENT_HOST:"https://launch-forum-v1-devnet.raydium.io",LAUNCH_HISTORY_HOST:"https://launch-history-v1-devnet.raydium.io",LAUNCH_MINT_HOST:"https://launch-mint-v1-devnet.raydium.io"});var Ll="ray_tab_hash",Vs="ray_req_hash",Fd=()=>{if(typeof window===void 0)return"";let d=sessionStorage.getItem(Ll);return d||(d=`ray-${Date.now()}`,sessionStorage.setItem(Ll,d)),d},$r=async n=>{var o=n,{logCount:d=1e3,removeLastLog:e}=o,t=Qe(o,["logCount","removeLastLog"]);if(typeof window===void 0)return new Promise(r=>r());let i=JSON.parse(localStorage.getItem(Vs)||"[]").slice(0,d-1);e&&i.pop(),new Blob([JSON.stringify(t.data)]).size>1024&&(t.data=JSON.stringify(t.data).substring(0,200)+"..."),i.unshift(V(N({},t),{time:Date.now(),session:Fd()}));try{localStorage.setItem(Vs,JSON.stringify(i))}catch{if(e){let r=!1,a=JSON.stringify(t.data).substring(0,100);for(i[0].data=a+(a.length>100?"...":"");!r;){i.pop();let u=JSON.stringify(t.data).substring(0,100);i[0].data=u+(u.length>100?"...":"");try{localStorage.setItem(Vs,JSON.stringify(i)),r=!0}catch{r=!1}}return new Promise(u=>u())}return $r(V(N({},t),{logCount:d,removeLastLog:!0}))}};var Jr=Be("Raydium_Api"),Es=new Map,Ds=new Map;var ea=class{constructor({cluster:e,timeout:t,logRequests:n,logCount:o,urlConfigs:i}){this.cluster=e,this.urlConfigs=i||{},this.logCount=o||1e3,this.api=Ws.default.create({baseURL:this.urlConfigs.BASE_HOST||(this.cluster==="devnet"?Rl.BASE_HOST:it.BASE_HOST),timeout:t}),this.api.interceptors.request.use(r=>{let{method:a,baseURL:u,url:s}=r;return Jr.debug(`${a==null?void 0:a.toUpperCase()} ${u}${s}`),r},r=>(Jr.error("Request failed"),Promise.reject(r))),this.api.interceptors.response.use(r=>{let{config:a,data:u,status:s}=r,{method:c,baseURL:l,url:m}=a;return n&&$r({status:s,url:`${l}${m}`,params:a.params,data:u,logCount:this.logCount}),Jr.debug(`${c==null?void 0:c.toUpperCase()} ${l}${m}  ${s}`),u},r=>{let{config:a,response:u={}}=r,{status:s}=u,{method:c,baseURL:l,url:m}=a;return n&&$r({status:s,url:`${l}${m}`,params:a.params,data:r.message,logCount:this.logCount}),Jr.error(`${c.toUpperCase()} ${l}${m} ${s||r.message}`),Promise.reject(r)})}async getClmmConfigs(){return(await this.api.get(this.urlConfigs.CLMM_CONFIG||it.CLMM_CONFIG)).data}async getClmmDynamicConfigs(){return(await this.api.get(this.urlConfigs.CLMM_DYNAMIC_CONFIG||it.CLMM_DYNAMIC_CONFIG)).data}async getCpmmConfigs(){return(await this.api.get(this.urlConfigs.CPMM_CONFIG||it.CPMM_CONFIG)).data}async getClmmPoolLines(e){return(await this.api.get(`${this.urlConfigs.POOL_POSITION_LINE||it.POOL_POSITION_LINE}?id=${e}`)).data}async getBlockSlotCountForSecond(e){if(!e)return 2;let n=(await Ws.default.post(e,{id:"getRecentPerformanceSamples",jsonrpc:"2.0",method:"getRecentPerformanceSamples",params:[4]})).result.map(o=>o.numSlots);return n.reduce((o,i)=>o+i,0)/n.length/60}async getChainTimeOffset(){return(await this.api.get(this.urlConfigs.CHAIN_TIME||it.CHAIN_TIME)).data}async getRpcs(){return this.api.get(this.urlConfigs.RPCS||it.RPCS)}async getTokenList(){return(await this.api.get(this.urlConfigs.TOKEN_LIST||it.TOKEN_LIST)).data}async getJupTokenList(){return(await this.api.get("",{baseURL:this.urlConfigs.JUP_TOKEN_LIST||it.JUP_TOKEN_LIST})).map(t=>V(N({},t),{chainId:101,programId:t.tokenProgram,address:t.id,logoURI:t.icon,extensions:{},freeze_authority:null,permanent_delegate:null,mint_authority:t.mintAuthority||null,minted_at:Date.now().toString()}))}async getTokenInfo(e){return(await this.api.get((this.urlConfigs.MINT_INFO_ID||it.MINT_INFO_ID)+`?mints=${e.map(n=>n.toString()).join(",")}`)).data}async getPoolList(e={}){let{type:t="all",sort:n="liquidity",order:o="desc",showFarms:i=!1,nextPageId:r,pageSize:a=100}=e;return(await this.api.get((this.urlConfigs.POOL_LIST||it.POOL_LIST)+`?size=${a}&hasReward=${i}${t&&t!=="all"?`&poolType=${t}`:""}${n?`&sortField=${n}`:""}${o?`&sortType=${o}`:""}${r?`&nextPageId=${r}`:""}`)).data}async fetchPoolById(e){let{ids:t}=e;return(await this.api.get((this.urlConfigs.POOL_SEARCH_BY_ID||it.POOL_SEARCH_BY_ID)+`?ids=${t}`)).data}async fetchPoolKeysById(e){let{idList:t}=e,n=[],o=t.filter(r=>Es.has(r)?(n.push(Es.get(r)),!1):!0),i=[];return o.length&&(i=(await this.api.get((this.urlConfigs.POOL_KEY_BY_ID||it.POOL_KEY_BY_ID)+`?ids=${o.join(",")}`)).data.filter(Boolean),i.forEach(a=>{Es.set(a.id,a)})),n.concat(i)}async fetchPoolByMints(e){let{mint1:t,mint2:n,type:o="all",sort:i,order:r="desc",nextPageId:a}=e,[u,s]=[t&&Ot(t).toBase58(),n&&n!=="undefined"?Ot(n).toBase58():""],[c,l]=s&&u>s?[s,u]:[u,s];if(!u&&!s)throw new Error("not search mints provided");return(await this.api.get((this.urlConfigs.POOL_SEARCH_MINT||it.POOL_SEARCH_MINT)+`?size=100&mint1=${c}${l?`&mint2=${l}`:""}${o&&o!=="all"?`&poolType=${o}`:""}${i?`&sortField=${i}`:""}${r?`&sortType=${r}`:""}${a?`&nextPageId=${a}`:""}`)).data}async fetchPoolByLpMints(e){let{ids:t}=e;return(await this.api.get((this.urlConfigs.POOL_SEARCH_LP||it.POOL_SEARCH_LP)+`?lps=${t}`)).data}async fetchFarmInfoById(e){let{ids:t}=e;return(await this.api.get((this.urlConfigs.FARM_INFO||it.FARM_INFO)+`?ids=${t}`)).data}async fetchFarmKeysById(e){let{ids:t}=e;return(await this.api.get((this.urlConfigs.FARM_KEYS||it.FARM_KEYS)+`?ids=${t}`)).data}async fetchAvailabilityStatus(){return(await this.api.get(this.urlConfigs.CHECK_AVAILABILITY||it.CHECK_AVAILABILITY)).data}async fetchLaunchConfigs(){var t;if((t=Ds.get(this.cluster))!=null&&t.length)return Ds.get(this.cluster);let e=await this.api.get(this.cluster==="devnet"?"https://launch-mint-v1-devnet.raydium.io/main/configs":"https://launch-mint-v1.raydium.io/main/configs");return Ds.set(this.cluster,e.data.data),e.data.data}async fetchFarmPositions(e=""){return(await this.api.get(`${this.urlConfigs.OWNER_BASE_HOST||it.OWNER_BASE_HOST}`+(this.urlConfigs.OWNER_STAKE_FARMS||it.OWNER_STAKE_FARMS).replace("{owner}",e))).data}async fetchCpmmLockInfo(e){return await this.api.get(`${this.urlConfigs.CPMM_LOCK||it.CPMM_LOCK}?id=${e.toString()}`)}};var ta="please provide owner in load() initialization or you can set by calling raydium.setOwner(owner)",Ol="please provide connection in load() initialization or set it by raydium.setConnection(connection)";var Ko=require("@solana/web3.js");var lt=require("@solana/spl-token");var Qi=class extends ot{constructor(t){super(t);this._tokenAccounts=[];this._tokenAccountRawInfos=[];this._accountListener=[];this._clientOwnedToken=!1;this._notSubscribeAccountChange=!1;this._accountFetchTime=0;let{tokenAccounts:n,tokenAccountRawInfos:o,notSubscribeAccountChange:i}=t;this._tokenAccounts=n||[],this._tokenAccountRawInfos=o||[],this._notSubscribeAccountChange=i!=null?i:!0,this._clientOwnedToken=!!(n||o)}get tokenAccounts(){return this._tokenAccounts}get tokenAccountRawInfos(){return this._tokenAccountRawInfos}set notSubscribeAccountChange(t){this._notSubscribeAccountChange=t}updateTokenAccount({tokenAccounts:t,tokenAccountRawInfos:n}){return t&&(this._tokenAccounts=t),n&&(this._tokenAccountRawInfos=n),this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId),this._accountChangeListenerId=void 0,this._clientOwnedToken=!0,this}addAccountChangeListener(t){return this._accountListener.push(t),this}removeAccountChangeListener(t){return this._accountListener=this._accountListener.filter(n=>n!==t),this}getAssociatedTokenAccount(t,n){return ne(this.scope.ownerPubKey,t,n).publicKey}resetTokenAccounts(){this._clientOwnedToken||(this._tokenAccounts=[],this._tokenAccountRawInfos=[])}async fetchWalletTokenAccounts(t){if(this._clientOwnedToken||!(t!=null&&t.forceUpdate)&&this._tokenAccounts.length&&Date.now()-this._accountFetchTime<(this._notSubscribeAccountChange?1e3*5:1e3*60*3))return{tokenAccounts:this._tokenAccounts,tokenAccountRawInfos:this._tokenAccountRawInfos};this.scope.checkOwner();let o=N(N({},{}),t),[i,r,a]=await Promise.all([this.scope.connection.getAccountInfo(this.scope.ownerPubKey,o.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:lt.TOKEN_PROGRAM_ID},o.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:lt.TOKEN_2022_PROGRAM_ID},o.commitment)]),{tokenAccounts:u,tokenAccountRawInfos:s}=Ru({owner:this.scope.ownerPubKey,solAccountResp:i,tokenAccountResp:{context:r.context,value:[...r.value,...a.value]}});return this._tokenAccounts=u,this._tokenAccountRawInfos=s,this._accountFetchTime=Date.now(),this._notSubscribeAccountChange||(this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId),this._accountChangeListenerId=this.scope.connection.onAccountChange(this.scope.ownerPubKey,()=>{this.fetchWalletTokenAccounts({forceUpdate:!0}),this._accountListener.forEach(c=>c({tokenAccounts:this._tokenAccounts,tokenAccountRawInfos:this._tokenAccountRawInfos}))},{commitment:t==null?void 0:t.commitment})),{tokenAccounts:u,tokenAccountRawInfos:s}}clearAccountChangeCkb(){this._accountChangeListenerId!==void 0&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId)}async getCreatedTokenAccount({mint:t,programId:n=lt.TOKEN_PROGRAM_ID,associatedOnly:o=!0}){await this.fetchWalletTokenAccounts();let i=this._tokenAccounts.filter(({mint:a})=>a==null?void 0:a.equals(t)).sort((a,u)=>a.amount.lt(u.amount)?1:-1),r=this.getAssociatedTokenAccount(t,n);for(let a of i){let{publicKey:u}=a;if(u&&(!o||o&&r.equals(u)))return u}}async getOrCreateTokenAccount(t){var y,b,g,A;await this.fetchWalletTokenAccounts();let{mint:n,createInfo:o,associatedOnly:i,owner:r,notUseTokenAccount:a=!1,skipCloseAccount:u=!1,checkCreateATAOwner:s=!1,assignSeed:c}=t,l=new Ko.PublicKey(t.tokenProgram||lt.TOKEN_PROGRAM_ID),m=this.getAssociatedTokenAccount(n,new Ko.PublicKey(l)),p=(a?[]:this.tokenAccountRawInfos).filter(k=>k.accountInfo.mint.equals(n)&&(!i||k.pubkey.equals(m))).sort((k,h)=>k.accountInfo.amount.lt(h.accountInfo.amount)?1:-1);if(o===void 0||p.length>0)return p.length>0?{account:p[0].pubkey}:{};let f={instructions:[],endInstructions:[],signers:[],instructionTypes:[],endInstructionTypes:[]};if(i){let k=(0,lt.createAssociatedTokenAccountIdempotentInstruction)(o.payer||r,m,r,n,l),h=this.tokenAccountRawInfos.find(P=>P.pubkey.equals(m));if(s){let P=await this.scope.connection.getAccountInfo(m);if(P===null)(y=f.instructions)==null||y.push(k),f.instructionTypes.push(X.CreateATA);else if(!(P.owner.equals(l)&&lt.AccountLayout.decode(P.data).mint.equals(n)&&lt.AccountLayout.decode(P.data).owner.equals(r)))throw Error(`create ata check error -> mint: ${n.toString()}, ata: ${m.toString()}`)}else h===void 0&&(f.instructions.push(k),f.instructionTypes.push(X.CreateATA));if(n.equals(Z)&&o.amount){let P=await Qn({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:o.payer||this.scope.ownerPubKey,amount:(b=o.amount)!=null?b:0,skipCloseAccount:u});f.instructions.push(...P.instructions||[]),f.endInstructions.push(...P.endInstructions||[]),f.instructionTypes.push(...P.instructionTypes||[]),f.endInstructionTypes.push(...P.endInstructionTypes||[]),o.amount&&(f.instructions.push(Ou({source:P.addresses.newAccount,destination:m,owner:this.scope.ownerPubKey,amount:o.amount,tokenProgram:lt.TOKEN_PROGRAM_ID})),f.instructionTypes.push(X.TransferAmount))}return!u&&h===void 0&&(f.endInstructions.push(Mn({owner:r,payer:o.payer||r,tokenAccount:m,programId:l})),f.endInstructionTypes.push(X.CloseAccount)),{account:m,instructionParams:f}}else{let k=st({fromPublicKey:r,programId:l,assignSeed:c}),h=await this.scope.connection.getMinimumBalanceForRentExemption(lt.AccountLayout.span),P=Ko.SystemProgram.createAccountWithSeed({fromPubkey:r,basePubkey:r,seed:k.seed,newAccountPubkey:k.publicKey,lamports:h+Number((A=(g=o.amount)==null?void 0:g.toString())!=null?A:0),space:lt.AccountLayout.span,programId:l});return f.instructions.push(P,Ka({mint:n,tokenAccount:k.publicKey,owner:this.scope.ownerPubKey,programId:l})),f.instructionTypes.push(X.CreateAccount),f.instructionTypes.push(X.InitAccount),u||(f.endInstructions.push(Mn({owner:r,payer:o.payer||r,tokenAccount:k.publicKey,programId:l})),f.endInstructionTypes.push(X.CloseAccount)),{account:k.publicKey,instructionParams:f}}}async checkOrCreateAta({mint:t,programId:n=lt.TOKEN_PROGRAM_ID,autoUnwrapWSOLToSOL:o}){var u;await this.fetchWalletTokenAccounts();let i=(u=this.scope.account.tokenAccounts.find(({mint:s})=>(s==null?void 0:s.toBase58())===t.toBase58()))==null?void 0:u.publicKey,r=this.scope.ownerPubKey,a={};if(!i){let s=this.getAssociatedTokenAccount(t,n),c=await(0,lt.createAssociatedTokenAccountIdempotentInstruction)(r,s,r,t,n);a.instructions=[c],a.instructionTypes=[X.CreateATA],i=s}return o&&Z.toBase58()===t.toBase58()&&(a.endInstructions=[Mn({owner:r,payer:r,tokenAccount:i,programId:n})],a.endInstructionTypes=[X.CloseAccount]),{pubKey:i,newInstructions:a}}async handleTokenAccount(t){let{side:n,amount:o,mint:i,programId:r=lt.TOKEN_PROGRAM_ID,tokenAccount:a,payer:u=this.scope.ownerPubKey,bypassAssociatedCheck:s,skipCloseAccount:c,checkCreateATAOwner:l}=t,m=this.getAssociatedTokenAccount(i,r);if(new Ko.PublicKey(Z).equals(i)){let p=await Qn({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:u,amount:o,skipCloseAccount:c});return N({tokenAccount:p.addresses.newAccount},p)}else if(!a||n==="out"&&!m.equals(a)&&!s){let p=[],f=(0,lt.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,m,this.scope.ownerPubKey,i,r);if(l){let y=await this.scope.connection.getAccountInfo(m);if(y===null)p.push(f);else if(!(y.owner.equals(lt.TOKEN_PROGRAM_ID)&&lt.AccountLayout.decode(y.data).mint.equals(i)&&lt.AccountLayout.decode(y.data).owner.equals(this.scope.ownerPubKey)))throw Error(`create ata check error -> mint: ${i.toString()}, ata: ${m.toString()}`)}else p.push(f);return{tokenAccount:m,instructions:p,instructionTypes:[X.CreateATA]}}return{tokenAccount:a}}async processTokenAccount(t){let{mint:n,programId:o=lt.TOKEN_PROGRAM_ID,amount:i,useSOLBalance:r,handleTokenAccount:a,feePayer:u}=t,s,c=this.createTxBuilder(u);if(n.equals(new Ko.PublicKey(Z))&&r){let l=await this.handleTokenAccount({side:"in",amount:i||0,mint:n,bypassAssociatedCheck:!0,programId:o}),{tokenAccount:p}=l,f=Qe(l,["tokenAccount"]);s=p,c.addInstruction(f)}else if(s=await this.getCreatedTokenAccount({mint:n,associatedOnly:!1,programId:o}),!s&&a){let m=await this.scope.account.handleTokenAccount({side:"in",amount:0,mint:n,bypassAssociatedCheck:!0,programId:o}),{tokenAccount:p}=m,f=Qe(m,["tokenAccount"]);s=p,c.addInstruction(f)}return N({tokenAccount:s},c.AllTxData)}};var Se=require("@solana/web3.js"),qs=require("@solana/spl-token");var Un=te(require("decimal.js"));var Gn=te(require("bn.js")),Zi=class extends ot{async _getUserRewardInfo({payer:e,rewardInfo:t}){if(t.mint.equals(Bt)){let n=await Qn({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:e,amount:Ea(V(N({},t),{openTime:t.openTime.toString(),endTime:t.endTime.toString()}))});return{rewardPubKey:n.addresses.newAccount,newInstruction:n}}return{rewardPubKey:await this.scope.account.getCreatedTokenAccount({mint:t.mint,associatedOnly:!1})}}async create({poolInfo:e,rewardInfos:t,payer:n,programId:o=li,txVersion:i,feePayer:r,lockProgram:a}){var I,x;this.checkDisabled(),this.scope.checkOwner();let s={lpMint:new Se.PublicKey(e.lpMint.address),lockInfo:{lockMint:(I=a==null?void 0:a.mint)!=null?I:Du,lockVault:(x=a==null?void 0:a.vault)!=null?x:Wu},version:6,rewardInfos:t,programId:o},c=this.createTxBuilder(r),l=n!=null?n:this.scope.ownerPubKey,m=st({fromPublicKey:l,programId:s.programId}),p=await this.scope.connection.getMinimumBalanceForRentExemption(fi.span);c.addInstruction({instructions:[Se.SystemProgram.createAccountWithSeed({fromPubkey:l,basePubkey:l,seed:m.seed,newAccountPubkey:m.publicKey,lamports:p,space:fi.span,programId:s.programId})]});let{publicKey:f,nonce:y}=$u({programId:new Se.PublicKey(s.programId),poolId:m.publicKey}),b=gi({programId:s.programId,poolId:m.publicKey,mint:s.lpMint,type:"lpVault"}),g=[],A=[];for(let S of s.rewardInfos){S.openTime>=S.endTime&&this.logAndCreateError("start time error","rewardInfo.rewardOpenTime",S.openTime.toString()),isNaN(jn[S.rewardType])&&this.logAndCreateError("rewardType error",S.rewardType),Number(S.perSecond)<=0&&this.logAndCreateError("rewardPerSecond error",S.perSecond),g.push(Ju(S));let{rewardPubKey:B,newInstruction:R}=await this._getUserRewardInfo({rewardInfo:S,payer:l});R&&c.addInstruction(R),B||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts);let L=S.mint.equals(Bt)?new Se.PublicKey(Ft.address):S.mint;A.push({rewardMint:L,rewardVault:gi({programId:s.programId,poolId:m.publicKey,mint:L,type:"rewardVault"}),userRewardToken:B})}let{account:k,instructionParams:h}=await this.scope.account.getOrCreateTokenAccount({mint:new Se.PublicKey(s.lockInfo.lockMint),owner:this.scope.ownerPubKey,skipCloseAccount:!1,createInfo:{payer:this.scope.ownerPubKey,amount:0},associatedOnly:!1});h&&c.addInstruction(h),k||this.logAndCreateError("cannot found lock vault","tokenAccounts",this.scope.account.tokenAccounts);let{instruction:P,instructionType:T}=nc({farmId:m.publicKey,owner:this.scope.ownerPubKey,farmAuthority:f,lpVault:b,lpMint:s.lpMint,lockVault:s.lockInfo.lockVault,lockMint:s.lockInfo.lockMint,lockUserAccount:k,programId:s.programId,rewardInfo:A,rewardInfoConfig:g,nonce:y});return c.addInstruction({instructions:[P],instructionTypes:[T]}).versionBuild({txVersion:i,extInfo:{farmId:m.publicKey,farmAuthority:f,lpVault:b,lockUserAccount:k,nonce:y}})}async restartReward({farmInfo:e,payer:t,newRewardInfo:n,txVersion:o,feePayer:i}){var g;let r=tn[e.programId];r!==6&&this.logAndCreateError("invalid farm version ",r);let a=Ut((await this.scope.api.fetchFarmKeysById({ids:e.id}))[0]),u={id:a.id,rewardInfos:e.rewardInfos,lpVault:a.lpVault,programId:a.programId};n.openTime>=n.endTime&&this.logAndCreateError("start time error","newRewardInfo",n);let s=t||this.scope.ownerPubKey,c=n.mint.equals(Bt)?new Se.PublicKey(Ft.address):n.mint,l=u.rewardInfos.findIndex(A=>new Se.PublicKey(A.mint.address).equals(c)),m=a.rewardInfos[l];m||this.logAndCreateError("configuration does not exist","rewardMint",c);let p=(g=m.vault)!=null?g:Bt,f=this.createTxBuilder(i),{rewardPubKey:y,newInstruction:b}=await this._getUserRewardInfo({rewardInfo:n,payer:s});return b&&f.addInstruction(b),y||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts),f.addInstruction({instructions:[Wa({payer:this.scope.ownerPubKey,rewardVault:p,userRewardTokenPub:y,farmKeys:u,rewardInfo:n})],instructionTypes:[X.FarmV6Restart]}).versionBuild({txVersion:o})}async restartRewards({farmInfo:e,payer:t,newRewardInfos:n,txVersion:o,feePayer:i}){var l;let r=tn[e.programId];r!==6&&this.logAndCreateError("invalid farm version ",r);let a=Ut((await this.scope.api.fetchFarmKeysById({ids:e.id}))[0]),u={id:a.id,rewardInfos:e.rewardInfos,lpVault:a.lpVault,programId:a.programId};n.forEach(m=>{m.openTime>=m.endTime&&this.logAndCreateError("start time error","newRewardInfo",m)});let s=t||this.scope.ownerPubKey,c=this.createTxBuilder(i);for(let m of n){let p=m.mint.equals(Bt)?new Se.PublicKey(Ft.address):m.mint,f=u.rewardInfos.findIndex(h=>new Se.PublicKey(h.mint.address).equals(p)),y=a.rewardInfos[f];y||this.logAndCreateError("configuration does not exist","rewardMint",p);let b=(l=y.vault)!=null?l:Bt,{rewardPubKey:g,newInstruction:A}=await this._getUserRewardInfo({rewardInfo:m,payer:s});A&&c.addInstruction(A),g||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts);let k=Wa({payer:this.scope.ownerPubKey,rewardVault:b,userRewardTokenPub:g,farmKeys:u,rewardInfo:m});c.addInstruction({instructions:[k],instructionTypes:[X.FarmV6Restart]})}return c.versionBuild({txVersion:o})}async addNewRewardToken(e){let{txVersion:t,farmInfo:n,newRewardInfo:o,payer:i,feePayer:r}=e,a=tn[n.programId];a!==6&&this.logAndCreateError("invalid farm version ",a);let u=Ut((await this.scope.api.fetchFarmKeysById({ids:n.id}))[0]),s=i!=null?i:this.scope.ownerPubKey,c=this.createTxBuilder(r),l=o.mint.equals(Bt)?new Se.PublicKey(Ft.address):o.mint,m=gi({programId:new Se.PublicKey(n.programId),poolId:new Se.PublicKey(n.id),mint:l,type:"rewardVault"}),{rewardPubKey:p,newInstruction:f}=await this._getUserRewardInfo({rewardInfo:o,payer:s});return f&&c.addInstruction(f),p||this.logAndCreateError("annot found target token accounts",this.scope.account.tokenAccounts),o.mint=l,c.addInstruction({instructions:[qa({payer:this.scope.ownerPubKey,userRewardTokenPub:p,farmKeys:u,rewardVault:m,rewardInfo:o})],instructionTypes:[X.FarmV6CreatorAddReward]}).versionBuild({txVersion:t})}async addNewRewardsToken(e){let{txVersion:t,farmInfo:n,newRewardInfos:o,payer:i,feePayer:r}=e,a=tn[n.programId];a!==6&&this.logAndCreateError("invalid farm version ",a);let u=Ut((await this.scope.api.fetchFarmKeysById({ids:n.id}))[0]),s=i!=null?i:this.scope.ownerPubKey,c=this.createTxBuilder(r);for(let l of o){let m=l.mint.equals(Bt)?new Se.PublicKey(Ft.address):l.mint,p=gi({programId:new Se.PublicKey(n.programId),poolId:new Se.PublicKey(n.id),mint:m,type:"rewardVault"}),{rewardPubKey:f,newInstruction:y}=await this._getUserRewardInfo({rewardInfo:l,payer:s});y&&c.addInstruction(y),f||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts);let b=qa({payer:this.scope.ownerPubKey,userRewardTokenPub:f,farmKeys:u,rewardVault:p,rewardInfo:V(N({},l),{mint:m})});c.addInstruction({instructions:[b],instructionTypes:[X.FarmV6CreatorAddReward]})}return c.versionBuild({txVersion:t})}async deposit(e){let{txVersion:t,farmInfo:n,amount:o,feePayer:i,useSOLBalance:r,associatedOnly:a=!0,checkCreateATAOwner:u=!1,userAuxiliaryLedgers:s,computeBudgetConfig:c,txTipConfig:l}=e;this.scope.availability.addFarm===!1&&this.logAndCreateError("farm deposit feature disabled in your region");let{rewardInfos:m,programId:p}=n,f=tn[p];f===4&&this.logAndCreateError("V4 has suspended deposits:",n.programId),Ra(f)||this.logAndCreateError("invalid farm program:",n.programId);let[y,b]=[new Se.PublicKey(n.programId),new Se.PublicKey(n.id)],g=(await this.scope.api.fetchFarmKeysById({ids:n.id}))[0],A=sn({programId:y,poolId:b,owner:this.scope.ownerPubKey,version:f}),k=this.createTxBuilder(i);k.addCustomComputeBudget(c),k.addTipInstruction(l);let h={};for(let C of this.scope.account.tokenAccounts)if(a){let F=ne(this.scope.ownerPubKey,C.mint,C.programId).publicKey;C.publicKey&&F.equals(C.publicKey)&&(h[C.mint.toString()]=C.publicKey)}else h[C.mint.toString()]=C.publicKey;let P=g.lpMint,T=h[P.address];T||this.logAndCreateError("you don't have any lp","lp zero",h);let I=[];for(let C of m){let F=r&&C.mint.address===Z.toString(),E=h[C.mint.address];if(!E){let{account:_,instructionParams:z}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:C.mint.programId,mint:new Se.PublicKey(C.mint.address),notUseTokenAccount:F,createInfo:{payer:i||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!F,associatedOnly:F?!1:a,checkCreateATAOwner:u});E=_,z&&k.addInstruction(z)}h[C.mint.address]=E,I.push(E)}let x,S=await this.scope.connection.getAccountInfo(A);if(S&&(x=Pi(f).decode(S.data)),n.programId!==li.toString()&&n.programId!==yn.FARM_PROGRAM_ID_V6.toString()&&!x){let{instruction:C,instructionType:F}=Ai({id:b,programId:y,version:f,ledger:A,owner:this.scope.ownerPubKey});k.addInstruction({instructions:[C],instructionTypes:[F]})}let B=La({version:f,rewardInfos:m,rewardTokenAccountsPublicKeys:I});B&&this.logAndCreateError(B);let R={amount:fe(o),owner:this.scope.ownerPubKey,farmInfo:n,farmKeys:g,lpAccount:T,rewardAccounts:I,userAuxiliaryLedgers:s==null?void 0:s.map(C=>new Se.PublicKey(C))},L=f===6?sc(R):f===5?ac(R):rc(R),O={3:X.FarmV3Deposit,5:X.FarmV5Deposit,6:X.FarmV6Deposit};return k.addInstruction({instructions:[L],instructionTypes:[O[f]]}).versionBuild({txVersion:t})}async withdraw(e){let{txVersion:t,farmInfo:n,amount:o,deposited:i,useSOLBalance:r,feePayer:a,associatedOnly:u=!0,checkCreateATAOwner:s=!1,userAuxiliaryLedgers:c,computeBudgetConfig:l,txTipConfig:m}=e,{rewardInfos:p}=n;this.scope.availability.removeFarm===!1&&this.logAndCreateError("farm withdraw feature disabled in your region");let f=tn[n.programId];Ra(f)||this.logAndCreateError("invalid farm program:",n.programId);let y=(await this.scope.api.fetchFarmKeysById({ids:n.id}))[0],b=this.createTxBuilder(a);b.addCustomComputeBudget(l),b.addTipInstruction(m);let g={};for(let B of this.scope.account.tokenAccounts)if(u){let R=ne(this.scope.ownerPubKey,B.mint).publicKey;B.publicKey&&R.equals(B.publicKey)&&(g[B.mint.toString()]=B.publicKey)}else g[B.mint.toString()]=B.publicKey;if(f!==4){let B=sn({programId:new Se.PublicKey(n.programId),poolId:new Se.PublicKey(n.id),owner:this.scope.ownerPubKey,version:f}),R=await this.scope.connection.getAccountInfo(B);if(R)Pi(f).decode(R.data).deposited.isZero()&&this.logAndCreateError("no deposited lp",{farmId:n.id});else if(f!==6){let{instruction:L,instructionType:O}=Ai({id:new Se.PublicKey(y.id),programId:new Se.PublicKey(y.programId),version:f,ledger:B,owner:this.scope.ownerPubKey});b.addInstruction({instructions:[L],instructionTypes:[O]})}}i&&i.isZero()&&!(c||[]).length&&this.logAndCreateError("no deposited lp",{farmId:n.id});let A=y.lpMint.address,k=r&&A===Z.toString(),h=g[A.toString()];if(!h){let{account:B,instructionParams:R}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:y.lpMint.programId,mint:new Se.PublicKey(A),notUseTokenAccount:k,createInfo:{payer:a||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!0,associatedOnly:k?!1:u,checkCreateATAOwner:s});h=B,R&&b.addInstruction(R)}g[A.toString()]=h;let P=[];for(let B of p){let R=r&&B.mint.address===Z.toString(),L=g[B.mint.address];if(!L){let{account:O,instructionParams:C}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:B.mint.programId,mint:new Se.PublicKey(B.mint.address),notUseTokenAccount:R,createInfo:{payer:a||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!R,associatedOnly:R?!1:u,checkCreateATAOwner:s});L=O,C&&b.addInstruction(C)}g[B.mint.address]=L,P.push(L)}let T=La({version:f,rewardInfos:p,rewardTokenAccountsPublicKeys:P});T&&this.logAndCreateError(T);let I={amount:fe(o),owner:this.scope.ownerPubKey,farmInfo:n,farmKeys:y,lpAccount:h,rewardAccounts:P,userAuxiliaryLedgers:c==null?void 0:c.map(B=>new Se.PublicKey(B))},x=f===6?wi(I):f===5?ki(I):f===4?ic(I):Ti(I),S={3:X.FarmV3Withdraw,4:X.FarmV4Withdraw,5:X.FarmV5Withdraw,6:X.FarmV6Withdraw};return b.addInstruction({instructions:[x],instructionTypes:[S[f]]}).versionBuild({txVersion:t})}async withdrawFarmReward({farmInfo:e,withdrawMint:t,txVersion:n,computeBudgetConfig:o,txTipConfig:i,feePayer:r}){var y;this.scope.checkOwner();let a=Ut((await this.scope.api.fetchFarmKeysById({ids:e.id}))[0]),u=tn[e.programId];u!==6&&this.logAndCreateError("invalid farm version",u);let s=a.rewardInfos.find(b=>Ot(b.mint.address).equals(Ot(t)));s||this.logAndCreateError("withdraw mint error","rewardInfos",e);let c=(y=s==null?void 0:s.vault)!=null?y:Bt,l=this.createTxBuilder(r),m;if(t.equals(Bt)||t.equals(Se.PublicKey.default)){let b=await Qn({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:this.scope.ownerPubKey,amount:Ea(V(N({},s),{openTime:s.openTime,endTime:s.endTime,perSecond:new Un.default(s.perSecond).mul(10**s.mint.decimals).toString()}))});m=b.addresses.newAccount,l.addInstruction(b)}else{let b=await this.scope.account.getCreatedTokenAccount({mint:t});b?m=b:(m=await this.scope.account.getAssociatedTokenAccount(t),l.addInstruction({instructions:[(0,qs.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,m,this.scope.ownerPubKey,t)],instructionTypes:[X.CreateATA]}))}let{instruction:p,instructionType:f}=oc({programId:a.programId,id:a.id,authority:a.authority,lpVault:a.lpVault,rewardVault:c,userRewardToken:m,owner:this.scope.ownerPubKey});return l.addCustomComputeBudget(o),l.addTipInstruction(i),l.addInstruction({instructions:[p],instructionTypes:[f]}).versionBuild({txVersion:n})}async harvestAllRewards(e){let{farmInfoList:t,useSOLBalance:n,feePayer:o,associatedOnly:i=!0,checkCreateATAOwner:r=!1,userAuxiliaryLedgers:a,txVersion:u,computeBudgetConfig:s}=e,c=this.createTxBuilder(o),l={};for(let f of this.scope.account.tokenAccounts)if(i){let y=ne(this.scope.ownerPubKey,f.mint).publicKey;f.publicKey&&y.equals(f.publicKey)&&(l[f.mint.toString()]=f.publicKey)}else l[f.mint.toString()]=f.publicKey;let p=(await this.scope.api.fetchFarmKeysById({ids:Object.values(t).map(f=>f.id).join(",")})).reduce((f,y)=>V(N({},f),{[y.id]:y}),{});for(let f of Object.values(t)){let{programId:y,lpMint:b,rewardInfos:g,id:A}=f,k=tn[y],h=b.address,P=n&&h===Z.toString(),T=l[h];if(!T){let{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:b.programId,mint:new Se.PublicKey(h),notUseTokenAccount:P,createInfo:{payer:o||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!0,associatedOnly:P?!1:i,checkCreateATAOwner:r});T=L,O&&c.addInstruction(O)}l[h.toString()]=T;let I=[];for(let L of g){let O=n&&L.mint.address===Z.toString(),C=l[L.mint.address];if(!C)if(O){let{account:F,instructionParams:E}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:L.mint.programId,mint:new Se.PublicKey(L.mint.address),notUseTokenAccount:O,createInfo:{payer:o||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!O,associatedOnly:O?!1:i,checkCreateATAOwner:r});C=F,E&&c.addInstruction(E)}else{let F=new Se.PublicKey(L.mint.address);C=this.scope.account.getAssociatedTokenAccount(F),c.addInstruction({instructions:[(0,qs.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,C,this.scope.ownerPubKey,F)]})}l[L.mint.address]=C,I.push(C)}let x=p[A],S={amount:$,owner:this.scope.ownerPubKey,farmInfo:f,farmKeys:x,lpAccount:T,rewardAccounts:I,userAuxiliaryLedgers:a==null?void 0:a.map(L=>new Se.PublicKey(L))},B=k===6?wi(S):k===5?ki(S):Ti(S),R={3:X.FarmV3Withdraw,5:X.FarmV5Withdraw,6:X.FarmV6Withdraw};c.addInstruction({instructions:[B],instructionTypes:[R[k]]})}return u===1?c.sizeCheckBuild({computeBudgetConfig:s}):c.sizeCheckBuildV0({computeBudgetConfig:s})}async fetchFarmBalances(){let e=await this.scope.api.fetchFarmPositions(this.scope.ownerPubKey.toBase58()),t=new Map,n=new Map;Object.keys(e||{}).forEach(s=>{var c,l;Object.keys(e[s]).forEach(m=>{Object.keys(e[s][m]).forEach(p=>{var g,A,k,h,P,T;let f=V(N({},e[s][m][p]),{farmId:m,lpMint:s,userVault:p}),y=t.get(s);t.set(s,{lpMint:s,hasAmount:(y==null?void 0:y.hasAmount)||new Un.default(f.lpAmount||0).gt(0),hasV1Data:(y==null?void 0:y.hasV1Data)||f.version==="V1",totalLpAmount:new Un.default((g=y==null?void 0:y.totalLpAmount)!=null?g:0).add(f.lpAmount||0).toString(),totalV1LpAmount:f.version==="V1"?new Un.default((A=y==null?void 0:y.totalV1LpAmount)!=null?A:0).add(f.lpAmount||0).toString():(k=y==null?void 0:y.totalV1LpAmount)!=null?k:"0",data:[...(y==null?void 0:y.data)||[],f]});let b=n.get(m);f.programId,n.set(m,{lpMint:s,hasAmount:(b==null?void 0:b.hasAmount)||new Un.default(f.lpAmount||0).gt(0),hasV1Data:(b==null?void 0:b.hasV1Data)||f.version==="V1",totalLpAmount:new Un.default((h=b==null?void 0:b.totalLpAmount)!=null?h:0).add(f.lpAmount||0).toString(),totalV1LpAmount:f.version==="V1"?new Un.default((P=b==null?void 0:b.totalV1LpAmount)!=null?P:0).add(f.lpAmount||0).toString():(T=b==null?void 0:b.totalV1LpAmount)!=null?T:"0",data:[...(b==null?void 0:b.data)||[],f]})})}),t.set(s,V(N({},t.get(s)),{totalLpAmount:new Un.default((l=(c=t.get(s))==null?void 0:c.totalLpAmount)!=null?l:0).toString()}))});let o=Array.from(n).map(s=>s[1].data).flat(),i=await this.scope.api.fetchFarmInfoById({ids:o.map(s=>s.farmId).join(",")}),r=await It(this.scope.connection,o.map(s=>new Se.PublicKey(s.userVault)));return(await It(this.scope.connection,o.map(s=>new Se.PublicKey(s.farmId)))).map((s,c)=>{var g;if(!s||!r[c])return;let l=tn[o[c].programId];if(!br[l]||!pi[l])return;let m=pi[l].decode(r[c].data),p=br[l].decode(s.data),f;p.version===6?f=(g=p.rewardMultiplier)!=null?g:new Gn.default(10).pow(new Gn.default(9)):f=p.rewardInfos.length===1?new Gn.default(10).pow(new Gn.default(9)):new Gn.default(10).pow(new Gn.default(15));let y=i[c],b=p?p.rewardInfos.map((A,k)=>{var T;let h=m.rewardDebts[k],P=m.deposited.mul((p==null?void 0:p.version)===6?A.accRewardPerShare:A.perShareReward).div(f).sub(h);return P.lt(new Gn.default(0))&&(P=new Gn.default(0)),{mint:(T=y.rewardInfos[k])==null?void 0:T.mint,amount:P.toString()}}):[];return V(N(N({},m),p),{farmInfo:y,pendingRewards:b})}).filter(Boolean)}};var rt=require("@solana/web3.js"),ht=require("@solana/spl-token");var ze=te(require("bn.js")),Ue=te(require("decimal.js"));var ji=class extends ot{constructor(t){super(t);this.stableLayout=new Er({connection:this.scope.connection,modelDataPubKey:this.scope.cluster==="mainnet"?void 0:yn.MODEL_DATA_PUBKEY})}async initLayout(){await this.stableLayout.initStableModelLayout()}async load(){this.checkDisabled()}computePairAmount({poolInfo:t,amount:n,slippage:o,baseIn:i}){let r=new ze.default(new Ue.default(n).mul(10**t[i?"mintA":"mintB"].decimals).toFixed(0)),a=hi(t[i?"mintB":"mintA"]),[u,s]=[new ze.default(new Ue.default(t.mintAmountA).mul(10**t.mintA.decimals).toString()),new ze.default(new Ue.default(t.mintAmountB).mul(10**t.mintB.decimals).toString())],c=new ze.default(new Ue.default(t.lpAmount).mul(10**t.lpMint.decimals).toFixed(0,Ue.default.ROUND_DOWN));this.logDebug("baseReserve:",u.toString(),"quoteReserve:",s.toString()),this.logDebug("tokenIn:",i?t.mintA.symbol:t.mintB.symbol,"amountIn:",r.toString(),"anotherToken:",i?t.mintB.symbol:t.mintA.symbol,"slippage:",`${o.toSignificant()}%`,"baseReserve",u.toString(),"quoteReserve",s.toString());let l=i?"base":"quote";this.logDebug("input side:",l);let m=$;r.isZero()||(m=l==="base"?jr(r.mul(s),u):jr(r.mul(u),s)),this.logDebug("amountRaw:",m.toString(),"lpAmount:",c.toString());let p=jr(r.mul(c),l==="base"?u:s);this.logDebug("liquidity:",p.toString());let f=new xt(new ze.default(1)).add(o),y=new xt(new ze.default(1)).sub(o),b=f.mul(m).quotient,g=y.mul(m).quotient,A=new _e(a,m),k=new _e(a,b),h=new _e(a,g);return this.logDebug("anotherAmount:",A.toFixed(),"maxAnotherAmount:",k.toFixed()),{anotherAmount:A,maxAnotherAmount:k,minAnotherAmount:h,liquidity:p}}async getAmmPoolKeys(t){return(await this.scope.api.fetchPoolKeysById({idList:[t]}))[0]}async addLiquidity(t){let{poolInfo:n,poolKeys:o,amountInA:i,amountInB:r,otherAmountMin:a,fixedSide:u,config:s,txVersion:c,computeBudgetConfig:l,txTipConfig:m,feePayer:p}=t;this.scope.availability.addStandardPosition===!1&&this.logAndCreateError("add liquidity feature disabled in your region"),this.logDebug("amountInA:",i,"amountInB:",r),(i.isZero()||r.isZero())&&this.logAndCreateError("amounts must greater than zero","amountInA & amountInB",{amountInA:i.toFixed(),amountInB:r.toFixed()});let{account:f}=this.scope,{bypassAssociatedCheck:y,checkCreateATAOwner:b}=N({bypassAssociatedCheck:!1,checkCreateATAOwner:!1},s),[g,A]=[i.token,r.token],k=await f.getCreatedTokenAccount({mint:g.mint,associatedOnly:!1}),h=await f.getCreatedTokenAccount({mint:A.mint,associatedOnly:!1});!k&&!h&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",f.tokenAccounts);let P=await f.getCreatedTokenAccount({mint:new rt.PublicKey(n.lpMint.address)}),T=[g,A],I=[k,h],x=[i.raw,r.raw],S=i.token.mint.toBase58()===n.mintA.address?"base":"quote",B="base";["quote","base"].includes(S)||this.logAndCreateError("invalid fixedSide","fixedSide",u),S==="quote"?(T.reverse(),I.reverse(),x.reverse(),B=u==="a"?"quote":"base"):S==="base"&&(B=u==="a"?"base":"quote");let[R,L]=T,[O,C]=I,[F,E]=x,_=o!=null?o:await this.getAmmPoolKeys(n.id),z=this.createTxBuilder(p),re=await f.handleTokenAccount({side:"in",amount:F,mint:R.mint,tokenAccount:O,bypassAssociatedCheck:y,checkCreateATAOwner:b}),{tokenAccount:H}=re,Y=Qe(re,["tokenAccount"]);z.addInstruction(Y);let ke=await f.handleTokenAccount({side:"in",amount:E,mint:L.mint,tokenAccount:C,bypassAssociatedCheck:y,checkCreateATAOwner:b}),{tokenAccount:J}=ke,ie=Qe(ke,["tokenAccount"]);z.addInstruction(ie);let Fe=await f.handleTokenAccount({side:"out",amount:0,mint:new rt.PublicKey(n.lpMint.address),tokenAccount:P,bypassAssociatedCheck:y,checkCreateATAOwner:b}),{tokenAccount:Q}=Fe,ge=Qe(Fe,["tokenAccount"]);return z.addInstruction(ge),z.addInstruction({instructions:[ul({poolInfo:n,poolKeys:_,userKeys:{baseTokenAccount:H,quoteTokenAccount:J,lpTokenAccount:Q,owner:this.scope.ownerPubKey},baseAmountIn:F,quoteAmountIn:E,otherAmountMin:a.raw,fixedSide:B})],instructionTypes:[n.pooltype.includes("StablePool")?X.AmmV5AddLiquidity:X.AmmV4AddLiquidity],lookupTableAddress:_.lookupTableAccount?[_.lookupTableAccount]:[]}),z.addCustomComputeBudget(l),z.addTipInstruction(m),c===0?await z.buildV0():z.build()}async removeLiquidity(t){this.scope.availability.removeStandardPosition===!1&&this.logAndCreateError("remove liquidity feature disabled in your region");let{poolInfo:n,poolKeys:o,lpAmount:i,baseAmountMin:r,quoteAmountMin:a,config:u,txVersion:s,computeBudgetConfig:c,txTipConfig:l,feePayer:m}=t,p=o!=null?o:await this.getAmmPoolKeys(n.id),[f,y,b]=[new rt.PublicKey(n.mintA.address),new rt.PublicKey(n.mintB.address),new rt.PublicKey(n.lpMint.address)];this.logDebug("lpAmount:",i),this.logDebug("baseAmountMin:",r),this.logDebug("quoteAmountMin:",a),i.isZero()&&this.logAndCreateError("amount must greater than zero","lpAmount",i.toString());let{account:g}=this.scope,A=await g.getCreatedTokenAccount({mint:b,associatedOnly:!1});A||this.logAndCreateError("cannot found lpTokenAccount","tokenAccounts",g.tokenAccounts);let k=await g.getCreatedTokenAccount({mint:f}),h=await g.getCreatedTokenAccount({mint:y}),P=this.createTxBuilder(m),{bypassAssociatedCheck:T,checkCreateATAOwner:I}=N({bypassAssociatedCheck:!1,checkCreateATAOwner:!1},u),L=await g.handleTokenAccount({side:"out",amount:0,mint:f,tokenAccount:k,bypassAssociatedCheck:T,checkCreateATAOwner:I}),{tokenAccount:x}=L,S=Qe(L,["tokenAccount"]);P.addInstruction(S);let O=await g.handleTokenAccount({side:"out",amount:0,mint:y,tokenAccount:h,bypassAssociatedCheck:T,checkCreateATAOwner:I}),{tokenAccount:B}=O,R=Qe(O,["tokenAccount"]);return P.addInstruction(R),P.addInstruction({instructions:[Ps({poolInfo:n,poolKeys:p,userKeys:{lpTokenAccount:A,baseTokenAccount:x,quoteTokenAccount:B,owner:this.scope.ownerPubKey},lpAmount:i,baseAmountMin:r,quoteAmountMin:a})],lookupTableAddress:p.lookupTableAccount?[p.lookupTableAccount]:[],instructionTypes:[n.pooltype.includes("StablePool")?X.AmmV5RemoveLiquidity:X.AmmV4RemoveLiquidity]}),P.addCustomComputeBudget(c),P.addTipInstruction(l),s===0?await P.buildV0():P.build()}async removeAllLpAndCreateClmmPosition({poolInfo:t,clmmPoolInfo:n,removeLpAmount:o,createPositionInfo:i,farmInfo:r,userFarmLpAmount:a,base:u,computeBudgetConfig:s,payer:c,userAuxiliaryLedgers:l,tokenProgram:m=ht.TOKEN_PROGRAM_ID,checkCreateATAOwner:p=!0,getEphemeralSigners:f,txVersion:y,feePayer:b}){if((this.scope.availability.removeStandardPosition===!1||this.scope.availability.createConcentratedPosition===!1)&&this.logAndCreateError("remove liquidity or create position feature disabled in your region"),!(t.mintA.address===n.mintA.address||t.mintA.address===n.mintB.address)||!(t.mintB.address===n.mintA.address||t.mintB.address===n.mintB.address))throw Error("mint check error");let g=this.createTxBuilder(b),A={};for(let _ of this.scope.account.tokenAccountRawInfos)(A[_.accountInfo.mint.toString()]===void 0||ne(this.scope.ownerPubKey,_.accountInfo.mint,ht.TOKEN_PROGRAM_ID).publicKey.equals(_.pubkey))&&(A[_.accountInfo.mint.toString()]=_.pubkey);let k=A[t.lpMint.address];if(k===void 0)throw Error("find lp account error in trade accounts");let h=o.add(a!=null?a:new ze.default(0)),P=t.mintA.address===Ze.WSOL.mint.toString(),T=t.mintB.address===Ze.WSOL.mint.toString(),{account:I,instructionParams:x}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:ht.TOKEN_PROGRAM_ID,mint:new rt.PublicKey(t.mintA.address),owner:this.scope.ownerPubKey,createInfo:P?{payer:this.scope.ownerPubKey}:void 0,skipCloseAccount:!P,notUseTokenAccount:P,associatedOnly:!0,checkCreateATAOwner:p});if(g.addInstruction(x||{}),I===void 0)throw new Error("base token account not found");let{account:S,instructionParams:B}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:ht.TOKEN_PROGRAM_ID,mint:new rt.PublicKey(t.mintB.address),owner:this.scope.ownerPubKey,createInfo:T?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!T,notUseTokenAccount:T,associatedOnly:!0,checkCreateATAOwner:p});if(g.addInstruction(B||{}),S===void 0)throw new Error("quote token account not found");if(A[t.mintA.address]=I,A[t.mintB.address]=S,r!==void 0&&!(a!=null&&a.isZero())){let _=tn[r.programId],z=sn({programId:new rt.PublicKey(r.programId),poolId:new rt.PublicKey(r.id),owner:this.scope.ownerPubKey,version:_}),H,Y=await this.scope.connection.getAccountInfo(z);if(Y&&(H=Pi(_).decode(Y.data)),_!==6&&!H){let{instruction:Fe,instructionType:Le}=Ai({id:new rt.PublicKey(r.id),programId:new rt.PublicKey(r.programId),version:_,ledger:z,owner:this.scope.ownerPubKey});g.addInstruction({instructions:[Fe],instructionTypes:[Le]})}let J=[];for(let Fe of r.rewardInfos){let Le=Fe.mint.address===Ze.WSOL.mint.toString();if(A[Fe.mint.address])J.push(A[Fe.mint.address]);else{let{account:Ae,instructionParams:ae}=await this.scope.account.getOrCreateTokenAccount({mint:new rt.PublicKey(Fe.mint.address),tokenProgram:m,owner:this.scope.ownerPubKey,skipCloseAccount:!Le,createInfo:{payer:c||this.scope.ownerPubKey},associatedOnly:!0,checkCreateATAOwner:p});Ae||this.logAndCreateError("farm reward account not found:",Fe.mint.address),ae&&g.addInstruction(ae),J.push(Ae)}}let ie=(await this.scope.api.fetchFarmKeysById({ids:r.id}))[0],Q={userAuxiliaryLedgers:l,amount:a,owner:this.scope.ownerPubKey,farmInfo:r,farmKeys:ie,lpAccount:k,rewardAccounts:J},ge=tn[r.programId],re=ge===6?wi(Q):ge===5?ki(Q):Ti(Q),ke={3:X.FarmV3Withdraw,5:X.FarmV5Withdraw,6:X.FarmV6Withdraw};g.addInstruction({instructions:[re],instructionTypes:[ke[ge]]})}let R=await this.getAmmPoolKeys(t.id),L=Ps({poolInfo:t,poolKeys:R,userKeys:{lpTokenAccount:k,baseTokenAccount:I,quoteTokenAccount:S,owner:this.scope.ownerPubKey},lpAmount:h,baseAmountMin:0,quoteAmountMin:0});g.addInstruction({instructions:[L],instructionTypes:[t.pooltype.includes("StablePool")?X.AmmV5RemoveLiquidity:X.AmmV4RemoveLiquidity],lookupTableAddress:R.lookupTableAccount?[R.lookupTableAccount]:[]});let[O,C]=t.mintA.address===n.mintA.address?[I,S]:[S,I],F=await this.scope.clmm.getClmmPoolKeys(n.id),E=await we.openPositionFromBaseInstructions(V(N({poolInfo:n,poolKeys:F,ownerInfo:{feePayer:this.scope.ownerPubKey,wallet:this.scope.ownerPubKey,tokenAccountA:O,tokenAccountB:C},withMetadata:"create"},i),{liquidity:new ze.default(0),base:u,getEphemeralSigners:f}));return g.addInstruction({instructions:[...E.instructions],signers:E.signers,instructionTypes:[...E.instructionTypes],lookupTableAddress:F.lookupTableAccount?[F.lookupTableAccount]:[]}),y===0?g.sizeCheckBuildV0({computeBudgetConfig:s}):g.sizeCheckBuild({computeBudgetConfig:s})}async createPoolV4({programId:t,marketInfo:n,baseMintInfo:o,quoteMintInfo:i,baseAmount:r,quoteAmount:a,startTime:u,ownerInfo:s,associatedOnly:c=!1,checkCreateATAOwner:l=!1,tokenProgram:m,txVersion:p,feeDestinationId:f,computeBudgetConfig:y,txTipConfig:b,feePayer:g}){var C;let A=s.feePayer||((C=this.scope.owner)==null?void 0:C.publicKey),k=s.useSOLBalance&&o.mint.equals(ht.NATIVE_MINT),h=s.useSOLBalance&&i.mint.equals(ht.NATIVE_MINT),P=this.createTxBuilder(g),{account:T,instructionParams:I}=await this.scope.account.getOrCreateTokenAccount({mint:o.mint,owner:this.scope.ownerPubKey,createInfo:k?{payer:A,amount:r}:void 0,notUseTokenAccount:k,skipCloseAccount:!k,associatedOnly:k?!1:c,checkCreateATAOwner:l});P.addInstruction(I||{});let{account:x,instructionParams:S}=await this.scope.account.getOrCreateTokenAccount({mint:i.mint,owner:this.scope.ownerPubKey,createInfo:h?{payer:A,amount:a}:void 0,notUseTokenAccount:h,skipCloseAccount:!h,associatedOnly:h?!1:c,checkCreateATAOwner:l});if(P.addInstruction(S||{}),T===void 0||x===void 0)throw Error("you don't has some token account");let B=gs({version:4,marketVersion:3,marketId:n.marketId,baseMint:o.mint,quoteMint:i.mint,baseDecimals:o.decimals,quoteDecimals:i.decimals,programId:t,marketProgramId:n.programId}),R={programId:t,ammId:B.id,ammAuthority:B.authority,ammOpenOrders:B.openOrders,lpMint:B.lpMint,coinMint:B.baseMint,pcMint:B.quoteMint,coinVault:B.baseVault,pcVault:B.quoteVault,withdrawQueue:B.withdrawQueue,ammTargetOrders:B.targetOrders,poolTempLp:B.lpVault,marketProgramId:B.marketProgramId,marketId:B.marketId,ammConfigId:B.configId,feeDestinationId:f},{instruction:L,instructionType:O}=As(V(N({},R),{userWallet:this.scope.ownerPubKey,userCoinVault:T,userPcVault:x,userLpVault:ne(this.scope.ownerPubKey,B.lpMint,m).publicKey,nonce:B.nonce,openTime:u,coinAmount:r,pcAmount:a}));return P.addInstruction({instructions:[L],instructionTypes:[O]}),P.addCustomComputeBudget(y),P.addTipInstruction(b),P.versionBuild({txVersion:p,extInfo:{address:R}})}async createMarketAndPoolV4({programId:t=dr,marketProgram:n=vu,feeDestinationId:o=Vu,tokenProgram:i,baseMintInfo:r,quoteMintInfo:a,baseAmount:u,quoteAmount:s,startTime:c,ownerInfo:l,lowestFeeMarket:m,assignSeed:p,associatedOnly:f=!1,checkCreateATAOwner:y=!1,lotSize:b=1,tickSize:g=.01,txVersion:A,computeBudgetConfig:k,txTipConfig:h,feePayer:P}){var ei,na,ti;let T=this.scope.ownerPubKey,I=l.feePayer||((ei=this.scope.owner)==null?void 0:ei.publicKey),x=l.useSOLBalance&&r.mint.equals(ht.NATIVE_MINT),S=l.useSOLBalance&&a.mint.equals(ht.NATIVE_MINT),B=p?`${r.mint.toBase58().slice(0,7)}-${a.mint.toBase58().slice(0,7)}-${p}`:void 0,R=st({fromPublicKey:T,programId:n,assignSeed:B&&`${B}-market`}),L=st({fromPublicKey:T,programId:n,assignSeed:B&&`${B}-request`}),O=st({fromPublicKey:T,programId:n,assignSeed:B&&`${B}-event`}),C=st({fromPublicKey:T,programId:n,assignSeed:B&&`${B}-bids`}),F=st({fromPublicKey:T,programId:n,assignSeed:B&&`${B}-asks`}),E=st({fromPublicKey:T,programId:ht.TOKEN_PROGRAM_ID,assignSeed:B&&`${B}-baseVault`}),_=st({fromPublicKey:T,programId:ht.TOKEN_PROGRAM_ID,assignSeed:B&&`${B}-quoteVault`}),z=0,H=new ze.default(100);function Y(){let Wt=new ze.default(0);for(;;)try{return{vaultOwner:rt.PublicKey.createProgramAddressSync([R.publicKey.toBuffer(),Wt.toArrayLike(Buffer,"le",8)],n),vaultSignerNonce:Wt}}catch{if(Wt.iaddn(1),Wt.gt(new ze.default(25555)))throw Error("find vault owner error")}}let{vaultOwner:J,vaultSignerNonce:ie}=Y(),Q=new ze.default(Math.round(10**r.decimals*b)),ge=new ze.default(Math.round(b*10**a.decimals*g));if(Q.eq($))throw Error("lot size is too small");if(ge.eq($))throw Error("tick size or lot size is too small");let re=await Zr({connection:this.scope.connection,wallet:this.scope.ownerPubKey,marketInfo:{programId:n,vaultOwner:J,baseMint:r.mint,quoteMint:a.mint,id:R,baseVault:E,quoteVault:_,requestQueue:L,eventQueue:O,bids:C,asks:F,feeRateBps:z,quoteDustThreshold:H,vaultSignerNonce:ie,baseLotSize:Q,quoteLotSize:ge,lowestFeeMarket:m}}),ke=this.createTxBuilder(P);ke.addInstruction({instructions:re[0].transaction.instructions,signers:re[0].signer});for await(let Wt of re.slice(1,re.length))ke.addInstruction({instructions:Wt.transaction.instructions,signers:Wt.signer,instructionTypes:Wt.instructionTypes});let{account:Fe,instructionParams:Le}=await this.scope.account.getOrCreateTokenAccount({mint:r.mint,owner:this.scope.ownerPubKey,createInfo:x?{payer:I,amount:u}:void 0,notUseTokenAccount:x,skipCloseAccount:!x,associatedOnly:x?!1:f,checkCreateATAOwner:y,assignSeed:x&&B?`${B}-wsol`:void 0});ke.addInstruction(Le||{});let{account:Ae,instructionParams:ae}=await this.scope.account.getOrCreateTokenAccount({mint:a.mint,owner:this.scope.ownerPubKey,createInfo:S?{payer:I,amount:s}:void 0,notUseTokenAccount:S,skipCloseAccount:!S,associatedOnly:S?!1:f,checkCreateATAOwner:y,assignSeed:S&&B?`${B}-wsol`:void 0});if(ke.addInstruction(ae||{}),Fe===void 0)throw Error("you don't has base token account");if(Ae===void 0)throw Error("you don't has quote token account");let Ce=gs({version:4,marketVersion:3,marketId:R.publicKey,baseMint:r.mint,quoteMint:a.mint,baseDecimals:r.decimals,quoteDecimals:a.decimals,programId:t,marketProgramId:n}),Mt={programId:t,ammId:Ce.id,ammAuthority:Ce.authority,ammOpenOrders:Ce.openOrders,lpMint:Ce.lpMint,coinMint:Ce.baseMint,pcMint:Ce.quoteMint,coinVault:Ce.baseVault,pcVault:Ce.quoteVault,withdrawQueue:Ce.withdrawQueue,ammTargetOrders:Ce.targetOrders,poolTempLp:Ce.lpVault,marketProgramId:Ce.marketProgramId,marketId:Ce.marketId,ammConfigId:Ce.configId,feeDestinationId:o},{instruction:tt,instructionType:In}=As(V(N({},Mt),{userWallet:this.scope.ownerPubKey,userCoinVault:Fe,userPcVault:Ae,userLpVault:ne(this.scope.ownerPubKey,Ce.lpMint,i).publicKey,nonce:Ce.nonce,openTime:c,coinAmount:u,pcAmount:s}));ke.addInstruction({instructions:[tt],instructionTypes:[In]});let Co=x||S?[((na=Le==null?void 0:Le.instructions)==null?void 0:na[0])||((ti=ae==null?void 0:ae.instructions)==null?void 0:ti[0])].filter(Wt=>!!Wt):void 0;return A===0?ke.sizeCheckBuildV0({computeBudgetConfig:k,splitIns:Co,address:N({requestQueue:L.publicKey,eventQueue:O.publicKey,bids:C.publicKey,asks:F.publicKey,baseVault:E.publicKey,quoteVault:_.publicKey,baseMint:new rt.PublicKey(r.mint),quoteMint:new rt.PublicKey(a.mint)},Mt)}):ke.sizeCheckBuild({computeBudgetConfig:k,splitIns:Co,address:N({requestQueue:L.publicKey,eventQueue:O.publicKey,bids:C.publicKey,asks:F.publicKey,baseVault:E.publicKey,quoteVault:_.publicKey,baseMint:new rt.PublicKey(r.mint),quoteMint:new rt.PublicKey(a.mint)},Mt)})}async getCreatePoolFee({programId:t}){let n=Mr({programId:t}),o=await this.scope.connection.getAccountInfo(n,{dataSlice:{offset:536,length:8}});if(o===null)throw Error("get config account error");return ol.decode(o.data).fee}computeAmountOut({poolInfo:t,amountIn:n,mintIn:o,mintOut:i,slippage:r}){let[a,u]=[o.toString(),i.toString()];if(a!==t.mintA.address&&a!==t.mintB.address)throw new Error("toke not match");if(u!==t.mintA.address&&u!==t.mintB.address)throw new Error("toke not match");let{baseReserve:s,quoteReserve:c}=t,l=[s,c],m=[t.mintA.decimals,t.mintB.decimals],p=a==t.mintA.address?"base":"quote";p==="quote"&&(l.reverse(),m.reverse());let[f,y]=l,[b,g]=m,A=t.version===4,k;if(A)k=new Ue.default(y.toString()).div(10**g).div(new Ue.default(f.toString()).div(10**b));else{let O=pl(this.stableLayout.stableModelData,s.toNumber(),c.toNumber(),!1);p==="quote"?k=new Ue.default(1e6).div(O*1e6):k=new Ue.default(O*1e6).div(1e6)}let h=n,P=new ze.default(0),T=new ze.default(0);if(!h.isZero())if(A){T=ao(h.mul(ls),Or);let O=h.sub(T),C=f.add(O);P=y.mul(O).div(C)}else{T=h.mul(new ze.default(2)).div(new ze.default(1e4));let O=h.sub(T);p==="quote"?P=new ze.default(ml(this.stableLayout.stableModelData,c.toNumber(),s.toNumber(),O.toNumber())):P=new ze.default(dl(this.stableLayout.stableModelData,c.toNumber(),s.toNumber(),O.toNumber()))}let I=new ze.default(new Ue.default(P.toString()).mul(1-r).toFixed(0)),x=P,S=I,B=new Ue.default(P.toString()).div(new Ue.default(h.sub(T).toString()).toFixed(0));!h.isZero()&&!P.isZero()&&(B=new Ue.default(P.toString()).div(10**g).div(new Ue.default(h.sub(T).toString()).div(10**b)));let R=k.sub(B).div(k).mul(100);return{amountOut:x,minAmountOut:S,currentPrice:k,executionPrice:B,priceImpact:R,fee:T}}computeAmountIn({poolInfo:t,amountOut:n,mintIn:o,mintOut:i,slippage:r}){let{baseReserve:a,quoteReserve:u}=t;o.toString()!==t.mintA.address&&o.toString()!==t.mintB.address&&this.logAndCreateError("mintIn does not match pool"),i.toString()!==t.mintA.address&&i.toString()!==t.mintB.address&&this.logAndCreateError("mintOut does not match pool"),this.logDebug("baseReserve:",a.toString()),this.logDebug("quoteReserve:",u.toString());let s=o.toString()===t.mintA.address,[c,l]=s?[t.mintA,t.mintB]:[t.mintB,t.mintA];this.logDebug("currencyOut:",l.symbol||l.address),this.logDebug("amountOut:",new Ue.default(n.toString()).div(10**l.decimals).toDecimalPlaces(l.decimals).toString(),c.symbol||c.address),this.logDebug("slippage:",`${r*100}%`);let m=[a,u],p=s?"quote":"base";p==="base"&&m.reverse(),this.logDebug("output side:",p);let[f,y]=m,b=new Ue.default(y.toString()).div(10**t[s?"mintB":"mintA"].decimals).div(new Ue.default(f.toString()).div(10**t[s?"mintA":"mintB"].decimals));this.logDebug("currentPrice:",`1 ${c.symbol||c.address} \u2248 ${b.toString()} ${l.symbol||l.address}`),this.logDebug("currentPrice invert:",`1 ${l.symbol||l.address} \u2248 ${new Ue.default(1).div(b).toString()} ${c.symbol||c.address}`);let g=new ze.default(0),A=n,k=new ze.default(0);if(!A.isZero()){A.gt(y)&&(A=y.sub(new ze.default(1)));let B=y.sub(A),R=f.mul(A).div(B);g=R.mul(Or).div(Or.sub(ls)),k=g.sub(R)}let h=new ze.default(new Ue.default(g.toString()).mul(1+r).toFixed(0)),P=g,T=h;this.logDebug("amountIn:",new Ue.default(P.toString()).div(10**c.decimals).toDecimalPlaces(c.decimals).toString()),this.logDebug("maxAmountIn:",new Ue.default(T.toString()).div(10**c.decimals).toDecimalPlaces(c.decimals).toString());let I=null;!g.isZero()&&!A.isZero()&&(I=new Ue.default(A.toString()).div(10**l.decimals).div(new Ue.default(g.toString()).div(10**c.decimals)),this.logDebug("executionPrice:",`1 ${l.symbol||l.address} \u2248 ${I.toDecimalPlaces(Math.max(t.mintA.decimals,t.mintB.decimals)).toString()} ${c.symbol||c.address}`),this.logDebug("executionPrice invert:",`1 ${l.symbol||l.address} \u2248 ${new Ue.default(1).div(I).toDecimalPlaces(Math.max(t.mintA.decimals,t.mintB.decimals)).toString()} ${c.symbol||c.address}`));let x=b.mul(P.toString()),S=x.sub(n.toString()).abs().div(x);return this.logDebug("priceImpact:",`${S.toString()}%`),{amountIn:P,maxAmountIn:T,currentPrice:b,executionPrice:I,priceImpact:S,fee:k}}async swap({poolInfo:t,poolKeys:n,amountIn:o,amountOut:i,inputMint:r,fixedSide:a,txVersion:u,config:s,computeBudgetConfig:c,txTipConfig:l,feePayer:m}){let p=this.createTxBuilder(m),{associatedOnly:f=!0,inputUseSolBalance:y=!0,outputUseSolBalance:b=!0}=s||{},[g,A]=r===t.mintA.address?[t.mintA,t.mintB]:[t.mintB,t.mintA],k=y&&g.address===Z.toBase58(),h=b&&A.address===Z.toBase58(),{account:P,instructionParams:T}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:ht.TOKEN_PROGRAM_ID,mint:new rt.PublicKey(g.address),owner:this.scope.ownerPubKey,createInfo:k?{payer:this.scope.ownerPubKey,amount:o}:void 0,skipCloseAccount:!k,notUseTokenAccount:k,associatedOnly:f});p.addInstruction(T||{}),P||this.logAndCreateError("input token account not found",{token:g.symbol||g.address,tokenAccountIn:P,inputTokenUseSolBalance:k,associatedOnly:f});let{account:I,instructionParams:x}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:ht.TOKEN_PROGRAM_ID,mint:new rt.PublicKey(A.address),owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!h,notUseTokenAccount:h,associatedOnly:h?!1:f});p.addInstruction(x||{}),I===void 0&&this.logAndCreateError("output token account not found",{token:A.symbol||A.address,tokenAccountOut:I,outputTokenUseSolBalance:h,associatedOnly:f});let S=n||await this.getAmmPoolKeys(t.id),B=4;return t.pooltype.includes("StablePool")&&(B=5),p.addInstruction({instructions:[B===4?_r({version:B,poolKeys:S,userKeys:{tokenAccountIn:P,tokenAccountOut:I,owner:this.scope.ownerPubKey},amountIn:o,amountOut:i,fixedSide:a}):Vr({version:B,poolKeys:S,userKeys:{tokenAccountIn:P,tokenAccountOut:I,owner:this.scope.ownerPubKey},amountIn:o,amountOut:i,fixedSide:a})],instructionTypes:[B===4?X.AmmV4SwapBaseIn:X.AmmV5SwapBaseIn]}),p.addCustomComputeBudget(c),p.addTipInstruction(l),p.versionBuild({txVersion:u})}async getRpcPoolInfo(t){return(await this.getRpcPoolInfos([t]))[t]}async getRpcPoolInfos(t,n){let o=await Ge(this.scope.connection,t.map(c=>({pubkey:new rt.PublicKey(c)})),n),i={},r=[];for(let c=0;c<t.length;c++){let l=o[c];if(l===null||!l.accountInfo)throw Error("fetch pool info error: "+String(t[c]));let m=Nr.decode(l.accountInfo.data);i[String(t[c])]=V(N({},m),{programId:l.accountInfo.owner}),r.push(m.baseVault,m.quoteVault)}let a={},u=await Ge(this.scope.connection,r.map(c=>({pubkey:new rt.PublicKey(c)})),n);for(let c=0;c<r.length;c++){let l=u[c].accountInfo;if(l===null)throw Error("fetch vault info error: "+r[c]);a[String(r[c])]=new ze.default(ht.AccountLayout.decode(l.data).amount.toString())}let s={};for(let[c,l]of Object.entries(i)){let m=a[l.baseVault.toString()].sub(l.baseNeedTakePnl),p=a[l.quoteVault.toString()].sub(l.quoteNeedTakePnl);s[c]=V(N({},l),{baseReserve:m,mintAAmount:a[l.baseVault.toString()],mintBAmount:a[l.quoteVault.toString()],quoteReserve:p,poolPrice:new Ue.default(p.toString()).div(new Ue.default(10).pow(l.quoteDecimal.toString())).div(new Ue.default(m.toString()).div(new Ue.default(10).pow(l.baseDecimal.toString())))})}return s}async getPoolInfoFromRpc({poolId:t}){let n=await this.getRpcPoolInfo(t),o=Fr({[t]:n}),i=o[t],r=await this.scope.tradeV2.computePoolToPoolKeys({pools:[o[t]],ammRpcData:{[t]:n}});return{poolRpcData:n,poolInfo:i,poolKeys:r[0]}}async fetchPoolBalances(){await this.scope.account.fetchWalletTokenAccounts({forceUpdate:!0});let t=this.scope.account.tokenAccounts.filter(a=>!a.mint.equals(rt.PublicKey.default)&&!a.amount.isZero()).map(a=>a.mint),i=(await It(this.scope.connection,t)).map((a,u)=>a&&a.data.length===ht.MintLayout.span?V(N({},ht.MintLayout.decode(a.data)),{address:t[u]}):void 0).filter(Boolean).filter(a=>this.scope.cluster==="devnet"?a:nl.has(a.mintAuthority.toString())),r=await this.scope.api.fetchPoolByLpMints({ids:i.map(a=>a.address.toBase58()).join(",")});return i.map((a,u)=>{var s,c;return{mintData:a,address:a.address,poolInfo:r[u],balance:(c=(s=this.scope.account.tokenAccounts.find(l=>l.mint.equals(a.address)))==null?void 0:s.amount)!=null?c:new ze.default(0)}})}};var q=require("@solana/web3.js"),Ke=require("@solana/spl-token");var Ye=te(require("bn.js")),an=te(require("decimal.js"));var $i=class extends ot{constructor(e){super(e)}async load(){this.checkDisabled()}async getCpmmPoolKeys(e){return(await this.scope.api.fetchPoolKeysById({idList:[e]}))[0]}async getRpcPoolInfo(e,t){return(await this.getRpcPoolInfos([e],t))[e]}async getRpcPoolInfos(e,t){let n=await Ge(this.scope.connection,e.map(l=>({pubkey:new q.PublicKey(l)}))),o={},i=new Set,r=[];for(let l=0;l<e.length;l++){let m=n[l];if(m.accountInfo===null)throw Error("fetch pool info error: "+String(e[l]));let p=Rr.decode(m.accountInfo.data);o[String(e[l])]=V(N({},p),{programId:m.accountInfo.owner}),i.add(String(p.configId)),r.push(p.vaultA,p.vaultB)}let a={};if(t){let l=[...i],m=await Ge(this.scope.connection,l.map(p=>({pubkey:new q.PublicKey(p)})));for(let p=0;p<l.length;p++){let f=m[p].accountInfo;if(f===null)throw Error("fetch pool config error: "+l[p]);a[l[p]]=Gc.decode(f.data)}}let u={},s=await Ge(this.scope.connection,r.map(l=>({pubkey:new q.PublicKey(l)})));for(let l=0;l<r.length;l++){let m=s[l].accountInfo;if(m===null)throw Error("fetch vault info error: "+r[l]);u[String(r[l])]=new Ye.default(Ke.AccountLayout.decode(m.data).amount.toString())}let c={};for(let[l,m]of Object.entries(o)){let p=u[m.vaultA.toString()].sub(m.protocolFeesMintA).sub(m.fundFeesMintA).sub(m.creatorFeesMintA),f=u[m.vaultB.toString()].sub(m.protocolFeesMintB).sub(m.fundFeesMintB).sub(m.creatorFeesMintB);c[l]=V(N({},m),{baseReserve:p,quoteReserve:f,vaultAAmount:u[m.vaultA.toString()],vaultBAmount:u[m.vaultB.toString()],configInfo:a[m.configId.toString()],poolPrice:new an.default(f.toString()).div(new an.default(10).pow(m.mintDecimalB)).div(new an.default(p.toString()).div(new an.default(10).pow(m.mintDecimalA)))})}return c}toComputePoolInfos({pools:e,mintInfos:t}){return Object.keys(e).reduce((n,o)=>{var u,s,c,l;let i=e[o],[r,a]=[i.mintA.toBase58(),i.mintB.toBase58()];return V(N({},n),{[o]:V(N({},i),{id:new q.PublicKey(o),configInfo:i.configInfo,version:7,authority:wo(i.programId).publicKey,mintA:wt({address:r,decimals:i.mintDecimalA,programId:i.mintProgramA.toBase58(),extensions:{feeConfig:(u=t[r])!=null&&u.feeConfig?xn((s=t[r])==null?void 0:s.feeConfig):void 0}}),mintB:wt({address:a,decimals:i.mintDecimalB,programId:i.mintProgramB.toBase58(),extensions:{feeConfig:(c=t[a])!=null&&c.feeConfig?xn((l=t[a])==null?void 0:l.feeConfig):void 0}})})})},{})}async getPoolInfoFromRpc(e){let t=await this.getRpcPoolInfo(e,!0),n=await so({connection:this.scope.connection,mints:[t.mintA,t.mintB]}),o=wt({address:t.mintA.toBase58(),decimals:t.mintDecimalA,programId:t.mintProgramA.toBase58(),extensions:{feeConfig:n[t.mintA.toBase58()].feeConfig?xn(n[t.mintA.toBase58()].feeConfig):void 0}}),i=wt({address:t.mintB.toBase58(),decimals:t.mintDecimalB,programId:t.mintProgramB.toBase58(),extensions:{feeConfig:n[t.mintB.toBase58()].feeConfig?xn(n[t.mintB.toBase58()].feeConfig):void 0}}),r=wt({address:t.mintLp.toBase58(),decimals:t.lpDecimals,programId:Ke.TOKEN_PROGRAM_ID.toBase58()}),a={id:t.configId.toBase58(),index:t.configInfo.index,protocolFeeRate:t.configInfo.protocolFeeRate.toNumber(),tradeFeeRate:t.configInfo.tradeFeeRate.toNumber(),fundFeeRate:t.configInfo.fundFeeRate.toNumber(),createPoolFee:t.configInfo.createPoolFee.toString()},u={volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[]};return{poolInfo:{programId:t.programId.toBase58(),id:e,type:"Standard",lpMint:r,lpPrice:0,lpAmount:t.lpAmount.toNumber(),config:a,mintA:o,mintB:i,rewardDefaultInfos:[],rewardDefaultPoolInfos:"Ecosystem",price:t.poolPrice.toNumber(),mintAmountA:new an.default(t.vaultAAmount.toString()).div(10**o.decimals).toNumber(),mintAmountB:new an.default(t.vaultBAmount.toString()).div(10**i.decimals).toNumber(),feeRate:t.configInfo.tradeFeeRate.toNumber(),openTime:t.openTime.toString(),tvl:0,burnPercent:0,day:u,week:u,month:u,pooltype:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0,feeOn:"",hasDynamicFee:!1,launchMigratePool:!1,tips:[]},poolKeys:{programId:t.programId.toBase58(),id:e,mintA:o,mintB:i,openTime:t.openTime.toString(),vault:{A:t.vaultA.toBase58(),B:t.vaultB.toBase58()},authority:wo(t.programId).publicKey.toBase58(),mintLp:r,config:a,observationId:ko(t.programId,new q.PublicKey(e)).publicKey.toBase58()},rpcData:t,computePoolInfo:V(N({},t),{id:new q.PublicKey(e),configInfo:t.configInfo,version:7,authority:wo(t.programId).publicKey,mintA:o,mintB:i})}}async createPool(y){var b=y,{poolId:e,programId:t,poolFeeAccount:n,startTime:o,ownerInfo:i,associatedOnly:r=!1,checkCreateATAOwner:a=!1,txVersion:u,feeConfig:s,computeBudgetConfig:c,txTipConfig:l,feePayer:m,addSupportMintExt:p}=b,f=Qe(b,["poolId","programId","poolFeeAccount","startTime","ownerInfo","associatedOnly","checkCreateATAOwner","txVersion","feeConfig","computeBudgetConfig","txTipConfig","feePayer","addSupportMintExt"]);var H,Y,J;let g=i.feePayer||((H=this.scope.owner)==null?void 0:H.publicKey),A=new Ye.default(new q.PublicKey(f.mintA.address).toBuffer()).lte(new Ye.default(new q.PublicKey(f.mintB.address).toBuffer())),[k,h]=A?[f.mintA,f.mintB]:[f.mintB,f.mintA],[P,T]=A?[f.mintAAmount,f.mintBAmount]:[f.mintBAmount,f.mintAAmount],I=i.useSOLBalance&&k.address===Ke.NATIVE_MINT.toBase58(),x=i.useSOLBalance&&h.address===Ke.NATIVE_MINT.toBase58(),[S,B]=[new q.PublicKey(k.address),new q.PublicKey(h.address)],R=this.createTxBuilder(m),{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({mint:S,tokenProgram:k.programId,owner:this.scope.ownerPubKey,createInfo:I?{payer:g,amount:P}:void 0,notUseTokenAccount:I,skipCloseAccount:!I,associatedOnly:I?!1:r,checkCreateATAOwner:a});R.addInstruction(O||{});let{account:C,instructionParams:F}=await this.scope.account.getOrCreateTokenAccount({mint:new q.PublicKey(h.address),tokenProgram:h.programId,owner:this.scope.ownerPubKey,createInfo:x?{payer:g,amount:T}:void 0,notUseTokenAccount:x,skipCloseAccount:!x,associatedOnly:x?!1:r,checkCreateATAOwner:a});if(R.addInstruction(F||{}),L===void 0||C===void 0)throw Error(`you don't has some token account, userVaultA: ${L==null?void 0:L.toBase58()}, userVaultB: ${C==null?void 0:C.toBase58()}`);let E=os({poolId:e,programId:t,configId:new q.PublicKey(s.id),mintA:S,mintB:B}),_=[],z=[];return p&&(k.programId===Ke.TOKEN_2022_PROGRAM_ID.toBase58()&&z.push(is(t,new q.PublicKey(k.address)).publicKey),h.programId===Ke.TOKEN_2022_PROGRAM_ID.toBase58()&&z.push(is(t,new q.PublicKey(h.address)).publicKey),(await this.scope.connection.getMultipleAccountsInfo(z)).forEach((Q,ge)=>{Q&&_.push(z[ge])})),R.addInstruction({instructions:[Yc(t,this.scope.ownerPubKey,new q.PublicKey(s.id),E.authority,E.poolId,S,B,E.lpMint,L,C,ne(this.scope.ownerPubKey,E.lpMint).publicKey,E.vaultA,E.vaultB,n,new q.PublicKey((Y=k.programId)!=null?Y:Ke.TOKEN_PROGRAM_ID),new q.PublicKey((J=h.programId)!=null?J:Ke.TOKEN_PROGRAM_ID),E.observationId,P,T,o,_)],instructionTypes:[X.CpmmCreatePool]}),R.addCustomComputeBudget(c),R.addTipInstruction(l),R.versionBuild({txVersion:u,extInfo:{address:V(N({},E),{mintA:k,mintB:h,programId:t,poolFeeAccount:n,feeConfig:s})}})}async addLiquidity(e){let{poolInfo:t,poolKeys:n,inputAmount:o,baseIn:i,slippage:r,computeResult:a,computeBudgetConfig:u,txTipConfig:s,config:c,txVersion:l,feePayer:m}=e;this.scope.availability.addStandardPosition===!1&&this.logAndCreateError("add liquidity feature disabled in your region"),o.isZero()&&this.logAndCreateError("amounts must greater than zero","amountInA",{amountInA:o.toString()});let{account:p}=this.scope,{bypassAssociatedCheck:f,checkCreateATAOwner:y}=N({bypassAssociatedCheck:!1,checkCreateATAOwner:!1},c),b=a?void 0:await this.getRpcPoolInfo(t.id),{liquidity:g,inputAmountFee:A,anotherAmount:k}=a||this.computePairAmount({poolInfo:V(N({},t),{lpAmount:new an.default(b.lpAmount.toString()).div(10**t.lpMint.decimals).toNumber()}),baseReserve:b.baseReserve,quoteReserve:b.quoteReserve,slippage:new xt(0),baseIn:i,epochInfo:await this.scope.fetchEpochInfo(),amount:new an.default(o.toString()).div(10**(i?t.mintA.decimals:t.mintB.decimals))}),h=k.amount,P=t.mintA.address===Ke.NATIVE_MINT.toString(),T=t.mintB.address===Ke.NATIVE_MINT.toString(),I=this.createTxBuilder(m),[x,S]=[new q.PublicKey(t.mintA.address),new q.PublicKey(t.mintB.address)],{account:B,instructionParams:R}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintA.programId,mint:new q.PublicKey(t.mintA.address),owner:this.scope.ownerPubKey,createInfo:P||(i?o:h).isZero()?{payer:this.scope.ownerPubKey,amount:i?o:h}:void 0,skipCloseAccount:!P,notUseTokenAccount:P,associatedOnly:!1,checkCreateATAOwner:y});I.addInstruction(R||{});let{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintB.programId,mint:new q.PublicKey(t.mintB.address),owner:this.scope.ownerPubKey,createInfo:T||(i?h:o).isZero()?{payer:this.scope.ownerPubKey,amount:i?h:o}:void 0,skipCloseAccount:!T,notUseTokenAccount:T,associatedOnly:!1,checkCreateATAOwner:y});I.addInstruction(O||{}),!B&&!L&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",p.tokenAccounts);let C=await p.getCreatedTokenAccount({mint:new q.PublicKey(t.lpMint.address)}),H=await p.handleTokenAccount({side:"out",amount:0,mint:new q.PublicKey(t.lpMint.address),tokenAccount:C,bypassAssociatedCheck:f,checkCreateATAOwner:y}),{tokenAccount:F}=H,E=Qe(H,["tokenAccount"]);I.addInstruction(E);let _=n!=null?n:await this.getCpmmPoolKeys(t.id),z=new xt(new Ye.default(1)).sub(r);return I.addInstruction({instructions:[Hc(new q.PublicKey(t.programId),this.scope.ownerPubKey,new q.PublicKey(_.authority),new q.PublicKey(t.id),F,B,L,new q.PublicKey(_.vault.A),new q.PublicKey(_.vault.B),x,S,new q.PublicKey(t.lpMint.address),a?a==null?void 0:a.liquidity:z.mul(g).quotient,i?A.amount:h,i?h:A.amount)],instructionTypes:[X.CpmmAddLiquidity],lookupTableAddress:_.lookupTableAccount?[_.lookupTableAccount]:[]}),I.addCustomComputeBudget(u),I.addTipInstruction(s),I.versionBuild({txVersion:l,lookupTableAddress:_.lookupTableAccount?[_.lookupTableAccount]:void 0})}async withdrawLiquidity(e){var E,_;let{poolInfo:t,poolKeys:n,lpAmount:o,slippage:i,computeBudgetConfig:r,txTipConfig:a,txVersion:u,feePayer:s,closeWsol:c=!0}=e;this.scope.availability.addStandardPosition===!1&&this.logAndCreateError("add liquidity feature disabled in your region");let l=new xt(new Ye.default(1)).sub(i),m=await this.getRpcPoolInfo(t.id),[p,f]=[l.mul(o.mul(m.baseReserve).div(m.lpAmount)).quotient,l.mul(o.mul(m.quoteReserve).div(m.lpAmount)).quotient],y=await this.scope.fetchEpochInfo(),[b,g]=[Tt(p,t.mintA.extensions.feeConfig,y,!1),Tt(f,t.mintB.extensions.feeConfig,y,!1)],{account:A}=this.scope,k=this.createTxBuilder(s),[h,P]=[new q.PublicKey(t.mintA.address),new q.PublicKey(t.mintB.address)],T=h.equals(Z),I=P.equals(Z),x,S,{account:B,instructionParams:R}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintA.programId,mint:new q.PublicKey(t.mintA.address),notUseTokenAccount:T,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!(T&&c),associatedOnly:!T,checkCreateATAOwner:!1});x=B,R&&k.addInstruction(R);let{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintB.programId,mint:new q.PublicKey(t.mintB.address),notUseTokenAccount:I,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!(I&&c),associatedOnly:!I,checkCreateATAOwner:!1});S=L,O&&k.addInstruction(O),(!x||!S)&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",A.tokenAccounts);let C=await A.getCreatedTokenAccount({mint:new q.PublicKey(t.lpMint.address)});C||this.logAndCreateError("cannot found lp token account","tokenAccounts",A.tokenAccounts);let F=n!=null?n:await this.getCpmmPoolKeys(t.id);return k.addInstruction({instructions:[Qc(new q.PublicKey(t.programId),this.scope.ownerPubKey,new q.PublicKey(F.authority),new q.PublicKey(t.id),C,x,S,new q.PublicKey(F.vault.A),new q.PublicKey(F.vault.B),h,P,new q.PublicKey(t.lpMint.address),o,p.sub((E=b.fee)!=null?E:new Ye.default(0)),f.sub((_=g.fee)!=null?_:new Ye.default(0)))],instructionTypes:[X.CpmmWithdrawLiquidity],lookupTableAddress:F.lookupTableAccount?[F.lookupTableAccount]:[]}),k.addCustomComputeBudget(r),k.addTipInstruction(a),k.versionBuild({txVersion:u,lookupTableAddress:F.lookupTableAccount?[F.lookupTableAccount]:void 0})}async swap(e){var R,L,O,C,F,E;let{poolInfo:t,poolKeys:n,baseIn:o,fixedOut:i,inputAmount:r,swapResult:a,slippage:u=0,config:s,computeBudgetConfig:c,txTipConfig:l,txVersion:m,feePayer:p}=e,{bypassAssociatedCheck:f,checkCreateATAOwner:y,associatedOnly:b}=N({bypassAssociatedCheck:!1,checkCreateATAOwner:!1,associatedOnly:!0},s),g=this.createTxBuilder(p),[A,k]=[new q.PublicKey(t.mintA.address),new q.PublicKey(t.mintB.address)];i?a.inputAmount=a.inputAmount.mul(new Ye.default((1+u)*1e4)).div(new Ye.default(1e4)):a.outputAmount=a.outputAmount.mul(new Ye.default((1-u)*1e4)).div(new Ye.default(1e4));let h=t.mintA.address===Z.toBase58(),P=t.mintB.address===Z.toBase58(),{account:T,instructionParams:I}=await this.scope.account.getOrCreateTokenAccount({mint:A,tokenProgram:new q.PublicKey((R=t.mintA.programId)!=null?R:Ke.TOKEN_PROGRAM_ID),owner:this.scope.ownerPubKey,createInfo:h||!o?{payer:p||this.scope.ownerPubKey,amount:o?a.inputAmount:0}:void 0,notUseTokenAccount:h,skipCloseAccount:!h,associatedOnly:h?!1:b,checkCreateATAOwner:y});I&&g.addInstruction(I);let{account:x,instructionParams:S}=await this.scope.account.getOrCreateTokenAccount({mint:k,tokenProgram:new q.PublicKey((L=t.mintB.programId)!=null?L:Ke.TOKEN_PROGRAM_ID),owner:this.scope.ownerPubKey,createInfo:P||o?{payer:p||this.scope.ownerPubKey,amount:o?0:a.inputAmount}:void 0,notUseTokenAccount:P,skipCloseAccount:!P,associatedOnly:P?!1:b,checkCreateATAOwner:y});S&&g.addInstruction(S),(!T||!x)&&this.logAndCreateError("user do not have token account",{mintA:t.mintA.symbol||t.mintA.address,mintB:t.mintB.symbol||t.mintB.address,mintATokenAcc:T,mintBTokenAcc:x,mintAUseSOLBalance:h,mintBUseSOLBalance:P,associatedOnly:b});let B=n!=null?n:await this.getCpmmPoolKeys(t.id);return g.addInstruction({instructions:[i?Zc(new q.PublicKey(t.programId),this.scope.ownerPubKey,new q.PublicKey(B.authority),new q.PublicKey(B.config.id),new q.PublicKey(t.id),o?T:x,o?x:T,new q.PublicKey(B.vault[o?"A":"B"]),new q.PublicKey(B.vault[o?"B":"A"]),new q.PublicKey((F=t[o?"mintA":"mintB"].programId)!=null?F:Ke.TOKEN_PROGRAM_ID),new q.PublicKey((E=t[o?"mintB":"mintA"].programId)!=null?E:Ke.TOKEN_PROGRAM_ID),o?A:k,o?k:A,ko(new q.PublicKey(t.programId),new q.PublicKey(t.id)).publicKey,a.inputAmount,a.outputAmount):qo(new q.PublicKey(t.programId),this.scope.ownerPubKey,new q.PublicKey(B.authority),new q.PublicKey(B.config.id),new q.PublicKey(t.id),o?T:x,o?x:T,new q.PublicKey(B.vault[o?"A":"B"]),new q.PublicKey(B.vault[o?"B":"A"]),new q.PublicKey((O=t[o?"mintA":"mintB"].programId)!=null?O:Ke.TOKEN_PROGRAM_ID),new q.PublicKey((C=t[o?"mintB":"mintA"].programId)!=null?C:Ke.TOKEN_PROGRAM_ID),o?A:k,o?k:A,ko(new q.PublicKey(t.programId),new q.PublicKey(t.id)).publicKey,r,a.outputAmount)],instructionTypes:[i?X.CpmmSwapBaseOut:X.ClmmSwapBaseIn]}),g.addCustomComputeBudget(c),g.addTipInstruction(l),g.versionBuild({txVersion:m,lookupTableAddress:B.lookupTableAccount?[B.lookupTableAccount]:void 0})}async lockLp(e){var m,p,f,y,b;let{poolInfo:t,lpAmount:n,computeBudgetConfig:o,txTipConfig:i,txVersion:r,feePayer:a,feeNftOwner:u}=e;n.isZero()&&this.logAndCreateError("lpAmount must greater than zero",{lpAmount:n.toString()});let s=this.createTxBuilder(a),c=(m=e.poolKeys)!=null?m:await this.getCpmmPoolKeys(t.id),l=await jc({poolInfo:t,poolKeys:c,ownerInfo:{wallet:this.scope.ownerPubKey,feePayer:(p=e.feePayer)!=null?p:this.scope.ownerPubKey},feeNftOwner:u!=null?u:this.scope.ownerPubKey,lockProgram:(f=e.programId)!=null?f:di,lockAuthProgram:(y=e.authProgram)!=null?y:fr,lpAmount:n,withMetadata:(b=e.withMetadata)!=null?b:!0,getEphemeralSigners:e.getEphemeralSigners});return s.addInstruction(l),s.addCustomComputeBudget(o),s.addTipInstruction(i),s.versionBuild({txVersion:r,extInfo:l.address,lookupTableAddress:c.lookupTableAccount?[c.lookupTableAccount]:void 0})}async harvestLockLp(e){var L;let{poolInfo:t,lpFeeAmount:n,nftMint:o,programId:i=di,authProgram:r=fr,cpmmProgram:a,computeBudgetConfig:u,txTipConfig:s,txVersion:c,closeWsol:l=!0}=e;n.isZero()&&this.logAndCreateError("lpFeeAmount must greater than zero",{lpAmount:n.toString()});let m=e.feePayer||this.scope.ownerPubKey,p=this.createTxBuilder(m),[f,y]=[new q.PublicKey(t.mintA.address),new q.PublicKey(t.mintB.address)],b=f.equals(Z),g=y.equals(Z),A,k,{account:h,instructionParams:P}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintA.programId,mint:new q.PublicKey(t.mintA.address),notUseTokenAccount:b,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!(b&&l),associatedOnly:!b,checkCreateATAOwner:!1});A=h,P&&p.addInstruction(P);let{account:T,instructionParams:I}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintB.programId,mint:new q.PublicKey(t.mintB.address),notUseTokenAccount:g,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!(g&&l),associatedOnly:!g,checkCreateATAOwner:!1});k=T,I&&p.addInstruction(I),(!A||!k)&&this.logAndCreateError("cannot found target token accounts",{tokenAccountA:A,tokenAccountB:k});let x=(L=e.poolKeys)!=null?L:await this.getCpmmPoolKeys(t.id),{publicKey:S}=ne(m,o,Ke.TOKEN_PROGRAM_ID),{publicKey:B}=Wo(i,o),{publicKey:R}=ne(r,new q.PublicKey(t.lpMint.address),Ke.TOKEN_PROGRAM_ID);return p.addInstruction({instructions:[rs({programId:i,nftOwner:this.scope.ownerPubKey,auth:r,nftMint:o,nftAccount:S,lockPda:B,poolId:new q.PublicKey(t.id),mintLp:new q.PublicKey(x.mintLp.address),userVaultA:A,userVaultB:k,poolVaultA:new q.PublicKey(x.vault.A),poolVaultB:new q.PublicKey(x.vault.B),mintA:f,mintB:y,lockLpVault:R,lpFeeAmount:n,cpmmProgram:a==null?void 0:a.programId,cpmmAuthProgram:a==null?void 0:a.authProgram})],instructionTypes:[X.CpmmCollectLockFee]}),p.addCustomComputeBudget(u),p.addTipInstruction(s),p.versionBuild({txVersion:c,lookupTableAddress:x.lookupTableAccount?[x.lookupTableAccount]:void 0})}async harvestMultiLockLp(e){var p;let{lockInfo:t,programId:n=di,authProgram:o=fr,cpmmProgram:i,computeBudgetConfig:r,txVersion:a,closeWsol:u=!0}=e,s=e.feePayer||this.scope.ownerPubKey,c=this.createTxBuilder(s),l={},m=[];for(let f of t){let{poolInfo:y,lpFeeAmount:b,nftMint:g}=f;if(b.isZero())continue;let[A,k]=[new q.PublicKey(y.mintA.address),new q.PublicKey(y.mintB.address)],h=A.equals(Z),P=k.equals(Z),T=l[y.mintA.address],I=l[y.mintB.address];if(!T)if(h){let{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:y.mintA.programId,mint:new q.PublicKey(y.mintA.address),notUseTokenAccount:!0,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!u,associatedOnly:!1,checkCreateATAOwner:!1});T=L,O&&c.addInstruction(O),l[y.mintA.address]=L}else{let L=new q.PublicKey(y.mintA.address);T=this.scope.account.getAssociatedTokenAccount(L,new q.PublicKey(y.mintA.programId)),c.addInstruction({instructions:[(0,Ke.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,T,this.scope.ownerPubKey,L,new q.PublicKey(y.mintA.programId))]}),l[y.mintA.address]=T}if(!I)if(P){let{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:y.mintB.programId,mint:new q.PublicKey(y.mintB.address),notUseTokenAccount:!0,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!u,associatedOnly:!1,checkCreateATAOwner:!1});I=L,O&&c.addInstruction(O),l[y.mintB.address]=L}else{let L=new q.PublicKey(y.mintB.address);I=this.scope.account.getAssociatedTokenAccount(L,new q.PublicKey(y.mintB.programId)),c.addInstruction({instructions:[(0,Ke.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,I,this.scope.ownerPubKey,L,new q.PublicKey(y.mintB.programId))]}),l[y.mintB.address]=I}(!T||!I)&&this.logAndCreateError("cannot found target token accounts",{tokenAccountA:T,tokenAccountB:I});let x=(p=f.poolKeys)!=null?p:await this.getCpmmPoolKeys(y.id);x.lookupTableAccount&&m.push(x.lookupTableAccount);let{publicKey:S}=ne(s,g,Ke.TOKEN_PROGRAM_ID),{publicKey:B}=Wo(n,g),{publicKey:R}=ne(o,new q.PublicKey(y.lpMint.address),Ke.TOKEN_PROGRAM_ID);c.addInstruction({instructions:[rs({programId:n,nftOwner:this.scope.ownerPubKey,auth:o,nftMint:g,nftAccount:S,lockPda:B,poolId:new q.PublicKey(y.id),mintLp:new q.PublicKey(x.mintLp.address),userVaultA:T,userVaultB:I,poolVaultA:new q.PublicKey(x.vault.A),poolVaultB:new q.PublicKey(x.vault.B),mintA:A,mintB:k,lockLpVault:R,lpFeeAmount:b,cpmmProgram:i==null?void 0:i.programId,cpmmAuthProgram:i==null?void 0:i.authProgram})],instructionTypes:[X.CpmmCollectLockFee]})}return a===0?c.sizeCheckBuildV0({computeBudgetConfig:r,lookupTableAddress:m}):c.sizeCheckBuild({computeBudgetConfig:r})}async createPoolWithPermission(y){var b=y,{poolId:e,programId:t,poolFeeAccount:n,startTime:o,ownerInfo:i,associatedOnly:r=!1,checkCreateATAOwner:a=!1,txVersion:u,feeConfig:s,computeBudgetConfig:c,txTipConfig:l,feePayer:m,feeOn:p}=b,f=Qe(b,["poolId","programId","poolFeeAccount","startTime","ownerInfo","associatedOnly","checkCreateATAOwner","txVersion","feeConfig","computeBudgetConfig","txTipConfig","feePayer","feeOn"]);var _,z,H;console.log("***this method only available for wallet with permissions***");let g=i.feePayer||((_=this.scope.owner)==null?void 0:_.publicKey),A=new Ye.default(new q.PublicKey(f.mintA.address).toBuffer()).lte(new Ye.default(new q.PublicKey(f.mintB.address).toBuffer())),[k,h]=A?[f.mintA,f.mintB]:[f.mintB,f.mintA],[P,T]=A?[f.mintAAmount,f.mintBAmount]:[f.mintBAmount,f.mintAAmount],I=i.useSOLBalance&&k.address===Ke.NATIVE_MINT.toBase58(),x=i.useSOLBalance&&h.address===Ke.NATIVE_MINT.toBase58(),[S,B]=[new q.PublicKey(k.address),new q.PublicKey(h.address)],R=this.createTxBuilder(m),{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({mint:S,tokenProgram:k.programId,owner:this.scope.ownerPubKey,createInfo:I?{payer:g,amount:P}:void 0,notUseTokenAccount:I,skipCloseAccount:!I,associatedOnly:I?!1:r,checkCreateATAOwner:a});R.addInstruction(O||{});let{account:C,instructionParams:F}=await this.scope.account.getOrCreateTokenAccount({mint:new q.PublicKey(h.address),tokenProgram:h.programId,owner:this.scope.ownerPubKey,createInfo:x?{payer:g,amount:T}:void 0,notUseTokenAccount:x,skipCloseAccount:!x,associatedOnly:x?!1:r,checkCreateATAOwner:a});if(R.addInstruction(F||{}),L===void 0||C===void 0)throw Error("you don't has some token account");let E=os({poolId:e,programId:t,configId:new q.PublicKey(s.id),mintA:S,mintB:B});return R.addInstruction({instructions:[Jc(t,this.scope.ownerPubKey,this.scope.ownerPubKey,new q.PublicKey(s.id),E.authority,E.poolId,S,B,E.lpMint,L,C,ne(this.scope.ownerPubKey,E.lpMint).publicKey,E.vaultA,E.vaultB,n,new q.PublicKey((z=k.programId)!=null?z:Ke.TOKEN_PROGRAM_ID),new q.PublicKey((H=h.programId)!=null?H:Ke.TOKEN_PROGRAM_ID),E.observationId,Xc(t,this.scope.ownerPubKey).publicKey,P,T,o,p)],instructionTypes:[X.CpmmCreatePool]}),R.addCustomComputeBudget(c),R.addTipInstruction(l),R.versionBuild({txVersion:u,extInfo:{address:V(N({},E),{mintA:k,mintB:h,programId:t,poolFeeAccount:n,feeConfig:s})}})}async collectCreatorFees({poolInfo:e,poolKeys:t,programId:n=Zn,txVersion:o,computeBudgetConfig:i,txTipConfig:r,feePayer:a}){let u=a||this.scope.ownerPubKey,s=this.createTxBuilder(u),c=t!=null?t:await this.getCpmmPoolKeys(e.id),[l,m,p,f]=[new q.PublicKey(e.mintA.address),new q.PublicKey(e.mintB.address),new q.PublicKey(e.mintA.programId),new q.PublicKey(e.mintB.programId)],y=this.scope.account.getAssociatedTokenAccount(l,p),b=this.scope.account.getAssociatedTokenAccount(m,f);return s.addInstruction({instructions:[(0,Ke.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,y,this.scope.ownerPubKey,l,new q.PublicKey(e.mintA.programId)),(0,Ke.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,b,this.scope.ownerPubKey,m,new q.PublicKey(e.mintB.programId))]}),s.addInstruction({instructions:[as(n,this.scope.ownerPubKey,new q.PublicKey(c.authority),new q.PublicKey(c.id),new q.PublicKey(c.config.id),new q.PublicKey(c.vault.A),new q.PublicKey(c.vault.B),l,m,y,b,p,f)],instructionTypes:[]}),s.addCustomComputeBudget(i),s.addTipInstruction(r),s.versionBuild({txVersion:o})}async collectMultiCreatorFees({poolInfoList:e,poolKeyList:t,programId:n=Zn,txVersion:o,computeBudgetConfig:i,feePayer:r}){let a=r||this.scope.ownerPubKey,u=this.createTxBuilder(a),s={},c=t!=null?t:[];if(!c.length){let m=e.map(b=>b.id),p=95,f=[];for(let b=0;b<m.length;b+=p)f.push(m.slice(b,b+p));c=(await Promise.all(f.map(b=>this.scope.api.fetchPoolKeysById({idList:b})))).flat()}let l=c.reduce((m,p)=>V(N({},m),{[p.id]:p}),{});for(let m of e){let p=l[m.id]||await this.getCpmmPoolKeys(m.id),[f,y,b,g]=[new q.PublicKey(m.mintA.address),new q.PublicKey(m.mintB.address),new q.PublicKey(m.mintA.programId),new q.PublicKey(m.mintB.programId)],A=s[m.mintA.address]||this.scope.account.getAssociatedTokenAccount(f,b),k=s[m.mintB.address]||this.scope.account.getAssociatedTokenAccount(y,g);s[m.mintA.address]=A,s[m.mintB.address]=k,u.addInstruction({instructions:[as(n,this.scope.ownerPubKey,new q.PublicKey(p.authority),new q.PublicKey(p.id),new q.PublicKey(p.config.id),new q.PublicKey(p.vault.A),new q.PublicKey(p.vault.B),f,y,A,k,b,g)],instructionTypes:[]})}return o===0?u.sizeCheckBuildV0({computeBudgetConfig:i,lookupTableAddress:c.map(m=>m.lookupTableAccount).filter(Boolean),insCountLimit:6}):u.sizeCheckBuild({computeBudgetConfig:i})}async collectCreatorFeesPermissionless({poolInfo:e,poolKeys:t,programId:n=Zn,txVersion:o,computeBudgetConfig:i,txTipConfig:r,feePayer:a}){let u=a||this.scope.ownerPubKey,s=this.createTxBuilder(u),c=t!=null?t:await this.getCpmmPoolKeys(e.id),[l,m,p,f]=[new q.PublicKey(e.mintA.address),new q.PublicKey(e.mintB.address),new q.PublicKey(e.mintA.programId),new q.PublicKey(e.mintB.programId)],y=this.scope.account.getAssociatedTokenAccount(l,p),b=this.scope.account.getAssociatedTokenAccount(m,f);return s.addInstruction({instructions:[(0,Ke.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,y,this.scope.ownerPubKey,l,new q.PublicKey(e.mintA.programId)),(0,Ke.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,b,this.scope.ownerPubKey,m,new q.PublicKey(e.mintB.programId))]}),s.addInstruction({instructions:[$c(n,u,this.scope.ownerPubKey,new q.PublicKey(c.authority),new q.PublicKey(c.id),new q.PublicKey(c.vault.A),new q.PublicKey(c.vault.B),l,m,y,b,p,f)],instructionTypes:[]}),s.addCustomComputeBudget(i),s.addTipInstruction(r),s.versionBuild({txVersion:o})}computeSwapAmount({pool:e,amountIn:t,outputMint:n,slippage:o,swapBaseIn:i=!0}){let r=n.toString()===e.mintB.address,a=e.feeOn===0||e.feeOn===2,u=i?Vi.swapBaseInput(t,r?e.baseReserve:e.quoteReserve,r?e.quoteReserve:e.baseReserve,e.configInfo.tradeFeeRate,e.configInfo.creatorFeeRate,e.configInfo.protocolFeeRate,e.configInfo.fundFeeRate,a):Vi.swapBaseOutput(t,r?e.baseReserve:e.quoteReserve,r?e.quoteReserve:e.baseReserve,e.configInfo.tradeFeeRate,e.configInfo.creatorFeeRate,e.configInfo.protocolFeeRate,e.configInfo.fundFeeRate,a),s=new an.default(u.outputAmount.toString()).div(u.inputAmount.toString()),c=u.outputAmount.mul(new Ye.default((1-o)*1e4)).div(new Ye.default(1e4));return{allTrade:i?u.inputAmount.eq(t):u.outputAmount.eq(t),amountIn:i?t:u.inputAmount,amountOut:u.outputAmount,minAmountOut:c,executionPrice:s,fee:u.tradeFee,priceImpact:e.poolPrice.sub(s).div(e.poolPrice),swapResult:u}}computePairAmount({poolInfo:e,baseReserve:t,quoteReserve:n,amount:o,slippage:i,epochInfo:r,baseIn:a}){var h,P,T,I,x,S,B,R,L;let u=1-Number(i.toSignificant())/100,s=new Ye.default(new an.default(o).mul(10**e[a?"mintA":"mintB"].decimals).mul(u).toFixed(0)),c=Tt(s,e[a?"mintA":"mintB"].extensions.feeConfig,r,!1),l=s.sub((h=c.fee)!=null?h:new Ye.default(0)),m=new Ye.default(new an.default(e.lpAmount).mul(10**e.lpMint.decimals).toFixed(0,an.default.ROUND_DOWN));this.logDebug("baseReserve:",t.toString(),"quoteReserve:",n.toString()),this.logDebug("tokenIn:",a?e.mintA.symbol:e.mintB.symbol,"amountIn:",s.toString(),"amountInFee:",(T=(P=c.fee)==null?void 0:P.toString())!=null?T:0,"anotherToken:",a?e.mintB.symbol:e.mintA.symbol,"slippage:",`${i.toSignificant()}%`);let p=a?"base":"quote";this.logDebug("input side:",p);let f=l.mul(m).div(p==="base"?t:n),y={amount:$,fee:void 0,expirationTime:void 0};if(!l.isZero()){let O=vd(f,t,n,m);this.logDebug("lpAmountData:",{amountA:O.amountA.toString(),amountB:O.amountB.toString()}),y=Tt(O[a?"amountB":"amountA"],e[a?"mintB":"mintA"].extensions.feeConfig,r,!0)}let b=new xt(new Ye.default(1)).add(i),g=new xt(new Ye.default(1)).sub(i),A=Tt(b.mul(y.amount.sub((I=y.fee)!=null?I:new Ye.default(0))).quotient,e[a?"mintB":"mintA"].extensions.feeConfig,r,!0),k=Tt(g.mul(y.amount.sub((x=y.fee)!=null?x:new Ye.default(0))).quotient,e[a?"mintB":"mintA"].extensions.feeConfig,r,!0);return this.logDebug("anotherAmount:",y.amount.toString(),"anotherAmountFee:",(B=(S=y.fee)==null?void 0:S.toString())!=null?B:0,"maxAnotherAmount:",A.amount.toString(),"maxAnotherAmountFee:",(L=(R=A.fee)==null?void 0:R.toString())!=null?L:0),{inputAmountFee:c,anotherAmount:y,maxAnotherAmount:A,minAnotherAmount:k,liquidity:f}}async fetchCpmmLockBalances(){await this.scope.account.fetchWalletTokenAccounts({forceUpdate:!0});let e=this.scope.account.tokenAccountRawInfos.filter(a=>a.accountInfo.amount.eq(new Ye.default(1))),t=e.map(a=>Wo(this.scope.cluster==="mainnet"?di:yn.LOCK_CPMM_PROGRAM,a.accountInfo.mint).publicKey),n=await Ge(this.scope.connection,t.map(a=>({pubkey:a}))),o=new Map,i=n.filter((a,u)=>(o.set(a.pubkey.toString(),e[u].accountInfo.mint.toString()),!!a.accountInfo)).map(a=>a.pubkey);return(await Promise.all(i.map(a=>this.scope.api.fetchCpmmLockInfo(a)))).map((a,u)=>V(N({},a),{nftMint:new q.PublicKey(o.get(i[u].toString()))}))}};function vd(d,e,t,n){let o=d.mul(e).div(n);!o.isZero()&&!d.mul(e).mod(n).isZero()&&(o=o.add(new Ye.default(1)));let i=d.mul(t).div(n);return!i.isZero()&&!d.mul(t).mod(n).isZero()&&(i=i.add(new Ye.default(1))),{amountA:o,amountB:i}}var Us=require("@solana/web3.js"),Jt=require("@solana/spl-token");var Ji=class extends ot{constructor(t){super(t);this._tokenList=[];this._tokenMap=new Map;this._blackTokenMap=new Set;this._mintGroup={official:new Set,jup:new Set,extra:new Set};this._whiteMap=new Set;this._extraTokenList=[]}async load(t){this.checkDisabled();let{forceUpdate:n=!1,type:o="strict"}=t||{},{mintList:i,blacklist:r,whiteList:a}=await this.scope.fetchV3TokenList(n),u=await this.scope.fetchJupTokenList(n);this._tokenList=[],this._tokenMap=new Map,this._blackTokenMap=new Set(r),this._mintGroup={official:new Set,jup:new Set,extra:new Set},this._whiteMap=new Set(a),this._tokenMap.set(Xn.address,Xn),this._mintGroup.official.add(Xn.address),i.forEach(s=>{var c;this._blackTokenMap.has(s.address)||(this._tokenMap.set(s.address,V(N({},s),{type:"raydium",priority:2,programId:(c=s.programId)!=null?c:s.tags.includes("token-2022")?Jt.TOKEN_2022_PROGRAM_ID.toBase58():Jt.TOKEN_PROGRAM_ID.toBase58()})),this._mintGroup.official.add(s.address))}),u.forEach(s=>{var c;this._blackTokenMap.has(s.address)||this._tokenMap.has(s.address)||(this._tokenMap.set(s.address,V(N({},s),{type:"jupiter",priority:1,programId:(c=s.programId)!=null?c:s.tags.includes("token-2022")?Jt.TOKEN_2022_PROGRAM_ID.toBase58():Jt.TOKEN_PROGRAM_ID.toBase58(),tags:s.freezeAuthority?[...s.tags||[],"hasFreeze"]:s.tags})),this._mintGroup.jup.add(s.address))}),this._extraTokenList.forEach(s=>{this._blackTokenMap.has(s.address)||this._tokenMap.has(s.address)||(this._tokenMap.set(s.address,V(N({},s),{type:"extra",priority:1,programId:s.programId||s.tags.includes("token-2022")?Jt.TOKEN_2022_PROGRAM_ID.toBase58():Jt.TOKEN_PROGRAM_ID.toBase58()})),this._mintGroup.extra.add(s.address))}),this._tokenList=Array.from(this._tokenMap).map(s=>s[1])}get tokenList(){return this._tokenList}get tokenMap(){return this._tokenMap}get blackTokenMap(){return this._blackTokenMap}get mintGroup(){return this._mintGroup}get whiteListMap(){return this._whiteMap}async getTokenInfo(t){if(!t)throw new Error("please input mint");let n=t.toString(),o=this._tokenMap.get(n);if(o)return o;if(n.toLocaleUpperCase()==="SOL")return Xn;let i=(await this.scope.api.getTokenInfo([n]))[0];if(i)return this._mintGroup.extra.add(n),this._tokenMap.set(n,V(N({},i),{priority:2})),i;let r=await this.scope.connection.getAccountInfo(new Us.PublicKey(n));if(!r)throw new Error(`mint address not found: ${n}`);let a=Jt.MintLayout.decode(r.data),u=n.toString().substring(0,6),s=(0,Jt.getTransferFeeConfig)((0,Jt.unpackMint)(new Us.PublicKey(t),r,r.owner)),c={chainId:101,address:n,programId:r.owner.toBase58(),logoURI:"",symbol:u,name:u,decimals:a.decimals,tags:[],extensions:s?{feeConfig:xn(s)}:{},priority:0,type:"unknown"};return this._mintGroup.extra.add(n),this._tokenMap.set(n,c),c}};var er=class{constructor(e){this.rawBalances=new Map;let{connection:t,cluster:n,owner:o,api:i,defaultChainTime:r,defaultChainTimeOffset:a,apiCacheTime:u,blockhashCommitment:s="confirmed",loopMultiTxStatus:c}=e;this._connection=t,this.cluster=n||"mainnet",this._owner=o?new hn(o):void 0,this._signAllTransactions=e.signAllTransactions,this.blockhashCommitment=s,this.loopMultiTxStatus=c,this.api=i,this._apiCacheTime=u||5*60*1e3,this.logger=Be("Raydium"),this.farm=new Zi({scope:this,moduleName:"Raydium_Farm"}),this.account=new Qi({scope:this,moduleName:"Raydium_Account",tokenAccounts:e.tokenAccounts,tokenAccountRawInfos:e.tokenAccountRawInfos}),this.liquidity=new ji({scope:this,moduleName:"Raydium_LiquidityV2"}),this.token=new Ji({scope:this,moduleName:"Raydium_tokenV2"}),this.tradeV2=new Hi({scope:this,moduleName:"Raydium_tradeV2"}),this.clmm=new Ni({scope:this,moduleName:"Raydium_clmm"}),this.cpmm=new $i({scope:this,moduleName:"Raydium_cpmm"}),this.utils1216=new mn({scope:this,moduleName:"Raydium_utils1216"}),this.marketV2=new Jo({scope:this,moduleName:"Raydium_marketV2"}),this.launchpad=new Yi({scope:this,moduleName:"Raydium_lauchpad"}),this.availability={};let l=new Date().getTime();this.apiData={},a&&(this._chainTime={fetched:l,value:{chainTime:r||Date.now()-a,offset:a}})}static async load(e){var c;let t=(0,Nl.merge)({cluster:"mainnet",owner:null,apiRequestInterval:3e5,apiRequestTimeout:1e4},e),{cluster:n,apiRequestTimeout:o,logCount:i,logRequests:r,urlConfigs:a}=t,u=new ea({cluster:n,timeout:o,urlConfigs:a,logCount:i,logRequests:r}),s=new er(V(N({},t),{api:u}));return await s.fetchAvailabilityStatus((c=e.disableFeatureCheck)!=null?c:!0),e.disableLoadToken||await s.token.load({type:e.jupTokenType}),s}get owner(){return this._owner}get ownerPubKey(){if(!this._owner)throw new Error(ta);return this._owner.publicKey}setOwner(e){return this._owner=e?new hn(e):void 0,this.account.resetTokenAccounts(),this}get connection(){if(!this._connection)throw new Error(Ol);return this._connection}setConnection(e){return this._connection=e,this}get signAllTransactions(){return this._signAllTransactions}setSignAllTransactions(e){return this._signAllTransactions=e,this}checkOwner(){if(!this.owner)throw console.error(ta),new Error(ta)}isCacheInvalidate(e){return new Date().getTime()-e>this._apiCacheTime}async fetchChainTime(){try{let e=await this.api.getChainTimeOffset();this._chainTime={fetched:Date.now(),value:{chainTime:Date.now()+e.offset*1e3,offset:e.offset*1e3}}}catch{this._chainTime=void 0}}async fetchV3TokenList(e){if(this.apiData.tokenList&&!this.isCacheInvalidate(this.apiData.tokenList.fetched)&&!e)return this.apiData.tokenList.data;try{let t=await this.api.getTokenList(),n={fetched:Date.now(),data:t};return this.apiData.tokenList=n,n.data}catch(t){return console.error(t),{mintList:[],blacklist:[],whiteList:[]}}}async fetchJupTokenList(e){if(this.cluster==="devnet")return[];let t=this.apiData.jupTokenList;if(t&&!this.isCacheInvalidate(t.fetched)&&!e)return t.data;try{let n=await this.api.getJupTokenList();return this.apiData.jupTokenList={fetched:Date.now(),data:n.map(o=>V(N({},o),{mintAuthority:o.mint_authority||void 0,freezeAuthority:o.freeze_authority||void 0}))},this.apiData.jupTokenList.data}catch(n){return console.error(n),[]}}get chainTimeData(){var e;return(e=this._chainTime)==null?void 0:e.value}async chainTimeOffset(){var e;return this._chainTime&&Date.now()-this._chainTime.fetched<=1e3*60*5?this._chainTime.value.offset:(await this.fetchChainTime(),((e=this._chainTime)==null?void 0:e.value.offset)||0)}async currentBlockChainTime(){var e;return this._chainTime&&Date.now()-this._chainTime.fetched<=1e3*60*5?this._chainTime.value.chainTime:(await this.fetchChainTime(),((e=this._chainTime)==null?void 0:e.value.chainTime)||Date.now())}async fetchEpochInfo(){return this._epochInfo&&Date.now()-this._epochInfo.fetched<=1e3*30?this._epochInfo.value:(this._epochInfo={fetched:Date.now(),value:await this.connection.getEpochInfo()},this._epochInfo.value)}async fetchAvailabilityStatus(e){if(e)return{};try{let t=await this.api.fetchAvailabilityStatus(),n=t.all===!1;return this.availability={all:t.all,swap:n?!1:t.swap,createConcentratedPosition:n?!1:t.createConcentratedPosition,addConcentratedPosition:n?!1:t.addConcentratedPosition,addStandardPosition:n?!1:t.addStandardPosition,removeConcentratedPosition:n?!1:t.removeConcentratedPosition,removeStandardPosition:n?!1:t.removeStandardPosition,addFarm:n?!1:t.addFarm,removeFarm:n?!1:t.removeFarm},t}catch{return{}}}};0&&(module.exports={Raydium});
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
//# sourceMappingURL=raydium.js.map