@raydium-io/raydium-sdk-v2
Version:
An SDK for building applications on top of Raydium.
3 lines • 484 kB
JavaScript
var zl=Object.create;var ni=Object.defineProperty,Xl=Object.defineProperties,Yl=Object.getOwnPropertyDescriptor,Hl=Object.getOwnPropertyDescriptors,Ql=Object.getOwnPropertyNames,nr=Object.getOwnPropertySymbols,Zl=Object.getPrototypeOf,sa=Object.prototype.hasOwnProperty,su=Object.prototype.propertyIsEnumerable;var au=(m,e,t)=>e in m?ni(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t,N=(m,e)=>{for(var t in e||(e={}))sa.call(e,t)&&au(m,t,e[t]);if(nr)for(var t of nr(e))su.call(e,t)&&au(m,t,e[t]);return m},_=(m,e)=>Xl(m,Hl(e));var $e=(m,e)=>{var t={};for(var n in m)sa.call(m,n)&&e.indexOf(n)<0&&(t[n]=m[n]);if(m!=null&&nr)for(var n of nr(m))e.indexOf(n)<0&&su.call(m,n)&&(t[n]=m[n]);return t};var $l=(m,e)=>{for(var t in e)ni(m,t,{get:e[t],enumerable:!0})},uu=(m,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ql(e))!sa.call(m,o)&&o!==t&&ni(m,o,{get:()=>e[o],enumerable:!(n=Yl(e,o))||n.enumerable});return m};var te=(m,e,t)=>(t=m!=null?zl(Zl(m)):{},uu(e||!m||!m.__esModule?ni(t,"default",{value:m,enumerable:!0}):t,m)),jl=m=>uu(ni({},"__esModule",{value:!0}),m);var Zd={};$l(Zd,{Raydium:()=>er});module.exports=jl(Zd);var Wl=require("lodash");var zs=te(require("axios"));var ma=require("@solana/web3.js");var oi=require("lodash");var ua=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}},cu={},Jl={};function xe(m){let e=(0,oi.get)(cu,m);if(!e){let t=(0,oi.get)(Jl,m);e=new ua({name:m,logLevel:t}),(0,oi.set)(cu,m,e)}return e}var zn=require("@solana/spl-token"),ca=xe("Raydium_accountInfo_util");async function It(m,e,t){let{batchRequest:n,commitment:o="confirmed",chunkCount:i=100}=N({batchRequest:!1},t),r=la(e,i),a=new Array(r.length).fill([]);if(n){let u=r.map(l=>{let d=m._buildArgs([l.map(p=>p.toBase58())],o,"base64");return{methodName:"getMultipleAccounts",args:d}}),s=la(u,10);a=(await(await Promise.all(s.map(async l=>await m._rpcBatchRequest(l)))).flat()).map(l=>(l.error&&ca.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${l.error.message}`),l.result.value.map(d=>{if(d){let{data:p,executable:f,lamports:y,owner:b,rentEpoch:g}=d;return p.length!==2&&p[1]!=="base64"&&ca.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(p[0],"base64"),executable:f,lamports:y,owner:new ma.PublicKey(b),rentEpoch:g}}return null})))}else try{a=await Promise.all(r.map(u=>m.getMultipleAccountsInfo(u,o)))}catch(u){u instanceof Error&&ca.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${u.message}`)}return a.flat()}async function Ge(m,e,t){let n=await It(m,e.map(o=>o.pubkey),t);return e.map((o,i)=>_(N({},o),{accountInfo:n[i]}))}async function so({connection:m,mints:e,config:t}){var i,r,a;if(e.length===0)return{};let n=await Ge(m,e.map(u=>({pubkey:Nt(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()]=_(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[ma.PublicKey.default.toBase58()]=o[$.toBase58()],o}var qn=te(require("bn.js")),Yd=te(require("decimal.js"));var yu=te(require("big.js")),si=te(require("bn.js"));var lu=te(require("toformat")),em=lu.default,ii=em;var ri=te(require("big.js")),du=te(require("bn.js")),pu=te(require("decimal.js-light"));var Ro=te(require("bn.js"));var mu=9007199254740991;function ye(m){let e=xe("Raydium_parseBigNumberish");if(m instanceof Ro.default)return m;if(typeof m=="string"){if(m.match(/^-?[0-9]+$/))return new Ro.default(m);e.logWithError(`invalid BigNumberish string: ${m}`)}return typeof m=="number"?(m%1&&e.logWithError(`BigNumberish number underflow: ${m}`),(m>=mu||m<=-mu)&&e.logWithError(`BigNumberish number overflow: ${m}`),new Ro.default(String(m))):typeof m=="bigint"?new Ro.default(m.toString()):(e.error(`invalid BigNumberish value: ${m}`),new Ro.default(0))}var or=xe("module/fraction"),da=ii(ri.default),ai=ii(pu.default),nm={[0]:ai.ROUND_DOWN,[1]:ai.ROUND_HALF_UP,[2]:ai.ROUND_UP},om={[0]:ri.default.roundDown,[1]:ri.default.roundHalfUp,[2]:ri.default.roundUp},ve=class{constructor(e,t=new du.default(1)){this.numerator=ye(e),this.denominator=ye(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(ye(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(ye(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(ye(e));return new ve(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof ve?e:new ve(ye(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:nm[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.`),da.DP=e,da.RM=om[n]||1,new da(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var im=xe("Raydium_amount"),fu=ii(yu.default);function rm(m,e){let t="0",n="0";if(m.includes(".")){let o=m.split(".");o.length===2?([t,n]=o,n=n.padEnd(e,"0")):im.logWithError(`invalid number string, num: ${m}`)}else t=m;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=pa.pow(new si.default(t.decimals));if(o)r=ye(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]=rm(n.toString(),t.decimals);u=ye(c),s=ye(l)}u=u.mul(a),r=u.add(s)}super(r,a);this.logger=xe(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 fu.DP=this.token.decimals,new fu(this.numerator.toString()).div(this.denominator.toString()).toFormat(t)}};var bu=require("@solana/web3.js"),fa=require("@solana/spl-token"),Xn={chainId:101,address:bu.PublicKey.default.toBase58(),programId:fa.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"}},vt={chainId:101,address:"So11111111111111111111111111111111111111112",programId:fa.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"),gu=require("@solana/spl-token");function K({pubkey:m,isSigner:e=!1,isWritable:t=!0}){return{pubkey:m,isWritable:t,isSigner:e}}var ya=[K({pubkey:gu.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:qe.SystemProgram.programId,isWritable:!1}),K({pubkey:qe.SYSVAR_RENT_PUBKEY,isWritable:!1})];function ba({publicKey:m,transformSol:e}){let t=ga(m.toString());if(t instanceof qe.PublicKey)return e&&t.equals(xt)?$:t;if(e&&t.toString()===xt.toBase58())return $;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 ga(m){try{return new qe.PublicKey(m)}catch{return m}}var fn=new qe.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),_t=new qe.PublicKey("SysvarRent111111111111111111111111111111111"),Bp=new qe.PublicKey("SysvarC1ock11111111111111111111111111111111"),In=new qe.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),am=new qe.PublicKey("Sysvar1nstructions1111111111111111111111111"),Pu=qe.SystemProgram.programId,Ip=new qe.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),xp=new qe.PublicKey("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),Sp=new qe.PublicKey("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Kp=new qe.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Cp=new qe.PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),Rp=new qe.PublicKey("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Lp=new qe.PublicKey("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Op=new qe.PublicKey("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Np=new qe.PublicKey("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Mp=new qe.PublicKey("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),Fp=new qe.PublicKey("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),$=new qe.PublicKey("So11111111111111111111111111111111111111112"),xt=qe.PublicKey.default;function Nt(m){return ba({publicKey:m,transformSol:!0})}var Pa=class{constructor({mint:e,decimals:t,symbol:n,name:o,skipMint:i=!1,isToken2022:r=!1}){if(e===xt.toBase58()||e instanceof ir.PublicKey&&xt.equals(e)){this.decimals=vt.decimals,this.symbol=vt.symbol,this.name=vt.name,this.mint=new ir.PublicKey(vt.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:ba({publicKey:e}),this.isToken2022=r}equals(e){return this===e?!0:this.mint.equals(e.mint)}},je=Pa;je.WSOL=new Pa(_(N({},vt),{mint:vt.address}));var Aa=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=Aa;rr.SOL=new Aa(Xn);var wu=te(require("bn.js"));var Au=new ve(new wu.default(100)),St=class extends ve{toSignificant(e=5,t,n){return this.mul(Au).toSignificant(e,t,n)}toFixed(e=2,t,n){return this.mul(Au).toFixed(e,t,n)}};var sm=xe("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(wa(n.decimals),wa(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&&sm.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 Bu=require("@solana/web3.js"),Lo=te(require("bn.js"));var ue=require("@solana/buffer-layout"),ar=ue.Layout,ku=ue.Structure;var ka=ue.UInt;var Tu=ue.u8,ze=ue.u16;var ui=ue.u32;var yt=ue.s32;var hu=ue.seq;var Be=ue.blob;var Ta=ue.bits,ha=ue.offset;var uo=class extends ar{constructor(t,n,o){super(t,o);this.blob=Be(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=Ta(ui(),!1),this._upper=Ta(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 V(m){return new ka(1,m)}function Je(m){return new ka(4,m)}function w(m){return new uo(8,!1,m)}function ce(m){return new uo(16,!1,m)}function Iu(m){return new uo(1,!0,m)}function Oo(m){return new uo(8,!0,m)}function xu(m){return new uo(16,!0,m)}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 F(m){return new co(Be(32),e=>new Bu.PublicKey(e),e=>e.toBuffer(),m)}function it(m){return new co(Tu(),um,cm,m)}function um(m){if(m===0)return!1;if(m===1)return!0;throw new Error("Invalid bool: "+m)}function cm(m){return m?1:0}function Ia(m,e){let t=ui("length"),n=v([t,Q(m,ha(t,-t.span),"values")]);return new co(n,({values:o})=>o,o=>({values:o}),e)}function lm(m){let e=ui("length"),t=v([e,Be(ha(e,-e.span),"data")]);return new co(t,({data:n})=>n,n=>({data:n}),m)}function Ht(m){return new co(lm(),e=>e.toString("utf-8"),e=>Buffer.from(e,"utf-8"),m)}var Ba=class extends ku{decode(e,t){return super.decode(e,t)}};function v(m,e,t){return new Ba(m,e,t)}function Q(m,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 hu(m,o,t)}var Nn=v([F("mint"),F("owner"),w("amount"),Je("delegateOption"),F("delegate"),V("state"),Je("isNativeOption"),w("isNative"),w("delegatedAmount"),Je("closeAuthorityOption"),F("closeAuthority")]);var ci=require("@solana/web3.js"),Ou=te(require("bn.js"));var Nu=require("@solana/spl-token");function mm(m){return m instanceof Uint8Array||m!=null&&typeof m=="object"&&m.constructor.name==="Uint8Array"}function xa(m,...e){if(!mm(m))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(m.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${m.length}`)}function Sa(m,e=!0){if(m.destroyed)throw new Error("Hash instance has been destroyed");if(e&&m.finished)throw new Error("Hash#digest() has already been called")}function Su(m,e){xa(m);let t=e.outputLen;if(m.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var cr=m=>new DataView(m.buffer,m.byteOffset,m.byteLength),yn=(m,e)=>m<<32-e|m>>>e;var cf=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function dm(m){if(typeof m!="string")throw new Error(`utf8ToBytes expected string, got ${typeof m}`);return new Uint8Array(new TextEncoder().encode(m))}function Ka(m){return typeof m=="string"&&(m=dm(m)),xa(m),m}var ur=class{clone(){return this._cloneInto()}},lf={}.toString;function Ku(m){let e=n=>m().update(Ka(n)).digest(),t=m();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>m(),e}function pm(m,e,t,n){if(typeof m.setBigUint64=="function")return m.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;m.setUint32(e+u,r,n),m.setUint32(e+s,a,n)}var Cu=(m,e,t)=>m&e^~m&t,Ru=(m,e,t)=>m&e^m&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){Sa(this);let{view:t,buffer:n,blockLen:o}=this;e=Ka(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){Sa(this),Su(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;pm(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 fm=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),Ca=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 d=Hn[l-15],p=Hn[l-2],f=yn(d,7)^yn(d,18)^d>>>3,y=yn(p,17)^yn(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 d=yn(a,6)^yn(a,11)^yn(a,25),p=c+d+Cu(a,u,s)+fm[l]+Hn[l]|0,y=(yn(n,2)^yn(n,13)^yn(n,22))+Ru(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 Lu=Ku(()=>new Ca);function Mu({owner:m,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(m,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 Ou.default(String(e.lamports)),isNative:!0,programId:e.owner}),{tokenAccounts:n,tokenAccountRawInfos:o}}function ut({fromPublicKey:m,programId:e=Nu.TOKEN_PROGRAM_ID,assignSeed:t}){let n=t?btoa(t).slice(0,32):ci.Keypair.generate().publicKey.toBase58().slice(0,32);return{publicKey:ym(m,n,e),seed:n}}function ym(m,e,t){let n=Buffer.concat([m.toBuffer(),Buffer.from(e),t.toBuffer()]),o=Lu(n);return new ci.PublicKey(o)}var mr=require("@solana/web3.js"),Fu=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 Ra(m){let{mint:e,tokenAccount:t,owner:n,programId:o=en.TOKEN_PROGRAM_ID}=m;return(0,en.createInitializeAccountInstruction)(t,e,n,o)}function Mn(m){let{tokenAccount:e,destination:t,multiSigners:n=[],owner:o,programId:i=en.TOKEN_PROGRAM_ID}=m;return(0,en.createCloseAccountInstruction)(e,t,o,n,i)}async function Qn(m){let{connection:e,amount:t,commitment:n,closeDestination:o,payer:i,owner:r,skipCloseAccount:a}=m,u=await e.getMinimumBalanceForRentExemption(Nn.span,n),s=ye(t).add(new Fu.default(u)),c=ut({fromPublicKey:i,programId:en.TOKEN_PROGRAM_ID});return{addresses:{newAccount:c.publicKey},signers:[],instructions:[mr.SystemProgram.createAccountWithSeed({fromPubkey:i,basePubkey:i,seed:c.seed,newAccountPubkey:c.publicKey,lamports:s.toNumber(),space:Nn.span,programId:en.TOKEN_PROGRAM_ID}),Ra({mint:new mr.PublicKey(vt.address),tokenAccount:c.publicKey,owner:r,programId:en.TOKEN_PROGRAM_ID})],instructionTypes:[X.CreateAccount,X.InitAccount],endInstructionTypes:a?[]:[X.CloseAccount],endInstructions:a?[]:[Mn({tokenAccount:c.publicKey,destination:o!=null?o:r,owner:r})]}}function vu({source:m,destination:e,owner:t,amount:n,multiSigners:o=[],tokenProgram:i=en.TOKEN_PROGRAM_ID}){return(0,en.createTransferInstruction)(m,e,t,BigInt(String(n)),o,i)}var yr=require("@solana/web3.js");var be=require("@solana/web3.js"),_u=new be.PublicKey("EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"),Vu=new be.PublicKey("CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T"),Eu=new be.PublicKey("9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z"),li=new be.PublicKey("FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG"),qf=new be.PublicKey("CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS"),Du=new be.PublicKey("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"),La=new be.PublicKey("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),dr=new be.PublicKey("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"),Uf=new be.PublicKey("5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h"),Wu=new be.PublicKey("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),Fn=new be.PublicKey("CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"),mi=new be.PublicKey("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),pr=new be.PublicKey("kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy"),lo=new be.PublicKey("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),Gf=new be.PublicKey("routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS"),qu=new be.PublicKey("7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"),Zn=new be.PublicKey("CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"),Uu=new be.PublicKey("GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"),zf=new be.PublicKey("DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8"),di=new be.PublicKey("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),fr=new be.PublicKey("3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH"),Qe=new be.PublicKey("LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"),Xf=new be.PublicKey("WLHv2UAZm6z4KyaaELi5pjdbJh6RESMva1Rnn8pJVVh"),Yf=new be.PublicKey("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),Hf=new be.PublicKey("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),Qf=new be.PublicKey("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),Zf=new be.PublicKey("6s1xP3hpbAfFoNtUNF8mfHsjr2Bd97JxFJRWLbL6aHuX");var bn={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 bm=require("@solana/spl-token"),oy=xe("Raydium_farm_config"),Gu=new yr.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),zu=new yr.PublicKey("FrspKwj8i3pNmKwXreTveC4fu7KL5ZbGeXdZBe2XViu1");var iy=new yr.PublicKey("3TRTX4dXUpp2eqxi3tvQDFYUV7SdDJjcPE3Y4mbtftaX"),br={3:Xu,5:Yu,6:fi},pi={3:Ma,5:Hu,6:Qu},Oa=m=>[3,4,5,6].indexOf(m)!==-1,Na=m=>{var r;let{version:e,rewardInfos:t,rewardTokenAccountsPublicKeys:n}=m,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)},$n={"Standard SPL":0,"Option tokens":1},tn={[_u.toString()]:3,[Vu.toString()]:4,[Eu.toString()]:5,[li.toString()]:6,[bn.FARM_PROGRAM_ID_V3.toString()]:3,[bn.FARM_PROGRAM_ID_V4.toString()]:4,[bn.FARM_PROGRAM_ID_V5.toString()]:5,[bn.FARM_PROGRAM_ID_V6.toString()]:6};var Fa=v([V("instruction")]),va=v([V("instruction")]),gm=v([w("rewardState"),w("rewardOpenTime"),w("rewardEndTime"),w("rewardLastUpdateTime"),w("totalReward"),w("totalRewardEmissioned"),w("rewardClaimed"),w("rewardPerSecond"),ce("accRewardPerShare"),F("rewardVault"),F("rewardMint"),F("rewardSender"),w("rewardType"),Q(w(),15,"padding")]),Pm=v([w("state"),w("nonce"),F("lpVault"),F("rewardVault"),F(),F(),w(),w(),w("totalReward"),ce("perShareReward"),w("lastSlot"),w("perSlotReward")]),Am=v([w("state"),w("nonce"),F("lpVault"),F("rewardVaultA"),w("totalRewardA"),ce("perShareRewardA"),w("perSlotRewardA"),V("option"),F("rewardVaultB"),Be(7),w("totalRewardB"),ce("perShareRewardB"),w("perSlotRewardB"),w("lastSlot"),F()]),wm=v([w(),w("state"),w("nonce"),w("validRewardTokenNum"),ce("rewardMultiplier"),w("rewardPeriodMax"),w("rewardPeriodMin"),w("rewardPeriodExtend"),F("lpMint"),F("lpVault"),Q(gm,5,"rewardInfos"),F("creator"),F(),Q(w(),32,"padding")]),Xu=new Proxy(Pm,{get(m,e,t){return e==="decode"?(...n)=>{let o=m.decode(...n);return _(N({},o),{version:3,rewardInfos:[{rewardVault:o.rewardVault,totalReward:o.totalReward,perSlotReward:o.perSlotReward,perShareReward:o.perShareReward}]})}:Reflect.get(m,e,t)}}),Yu=new Proxy(Am,{get(m,e,t){return e==="decode"?(...n)=>{let o=m.decode(...n);return _(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(m,e,t)}}),fi=new Proxy(wm,{get(m,e,t){return e==="decode"?(...n)=>{let o=m.decode(...n);return _(N({},o),{version:6,rewardInfos:o.rewardInfos.map(i=>{var r;return _(N({},i),{rewardType:((r=Object.entries($n).find(a=>String(a[1])===i.rewardType.toString()))!=null?r:["Standard SPL"])[0]})})})}:Reflect.get(m,e,t)}}),km=v([w("isSet"),w("rewardPerSecond"),w("rewardOpenTime"),w("rewardEndTime"),w("rewardType")]),_a=v([V("instruction"),w("nonce"),Q(km,5,"rewardTimeInfo")]),Va=v([V("instruction"),w("rewardReopenTime"),w("rewardEndTime"),w("rewardPerSecond")]),Ea=v([V("instruction"),w("isSet"),w("rewardPerSecond"),w("rewardOpenTime"),w("rewardEndTime"),w("rewardType")]),my=v([w("state"),F("id"),F("owner"),w("deposited"),Q(w(),1,"rewardDebts")]),Ma=v([w("state"),F("id"),F("owner"),w("deposited"),Q(ce(),1,"rewardDebts"),w(""),w("voteLockedBalance"),Q(w(),15)]),dy=v([w("state"),F("id"),F("owner"),w("deposited"),Q(w(),2,"rewardDebts")]),Hu=v([w("state"),F("id"),F("owner"),w("deposited"),Q(ce(),2,"rewardDebts"),Q(w(),17)]),Qu=v([w(),w("state"),F("id"),F("owner"),w("deposited"),Q(ce(),5,"rewardDebts"),Q(w(),16)]),nn=v([V("instruction"),w("amount")]),Tm=v([F("mint"),F("grantAuthority"),w("baselineVoteWeightScaledFactor"),w("maxExtraLockupVoteWeightScaledFactor"),w("lockupSaturationSecs"),Iu("digitShift"),Q(V(),7,"reserved1"),Q(w(),7,"reserved2")]),hm=v([Be(8),F("governanceProgramId"),F("realm"),F("realmGoverningTokenMint"),F("realmAuthority"),Q(V(),32,"reserved1"),Q(Tm,4,"votingMints"),Oo("timeOffset"),V("bump"),Q(V(),7,"reserved2"),Q(w(),11,"reserved3")]),Bm=v([Oo("startTime"),Oo("endTime"),V("kind"),Q(V(),15,"reserved")]),Im=v([Q(Bm,1,"lockup"),w("amountDeposited_native"),w("amountInitiallyLockedNative"),it("isUsed"),it("allowClawback"),V("votingMintConfigIdx"),Q(V(),29,"reserved")]),xm=v([Be(8),F("voterAuthority"),F("registrar"),Q(Im,32,"deposits"),V("voterBump"),V("voterWweightRecordBump"),Q(V(),94,"reserved")]);var tc=te(require("bn.js"));var Vt=require("@solana/web3.js");var $u=require("@solana/spl-token"),Zu=xe("Raydium_txUtil"),ju=1644;function gr(m){let e=[],t=[];return m.microLamports&&(e.push(Vt.ComputeBudgetProgram.setComputeUnitPrice({microLamports:m.microLamports})),t.push(X.SetComputeUnitPrice)),m.units&&(e.push(Vt.ComputeBudgetProgram.setComputeUnitLimit({units:m.units})),t.push(X.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}async function No(m,e){var n,o;let t=e!=null?e:"confirmed";return(o=await((n=m.getLatestBlockhash)==null?void 0:n.call(m,{commitment:t})))==null?void 0:o.blockhash}async function Pr(m,e){return m.getSignatureStatuses([e]),new Promise((t,n)=>{let o=setTimeout(n,6e4);m.onSignature(e,i=>{if(clearTimeout(o),!i.err){t("");return}n(Object.assign(i.err,{txId:e}))},"confirmed")})}function Da(m,e){m.length<1&&Zu.logWithError(`no instructions provided: ${m.toString()}`),e.length<1&&Zu.logWithError(`no signers provided:, ${e.toString()}`);let t=new Vt.Transaction;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...m);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<ju}catch{return!1}}function le(m,e){let[t,n]=Vt.PublicKey.findProgramAddressSync(m,e);return{publicKey:t,nonce:n}}function yi({instructions:m,payer:e,signers:t}){return Da(m,[e,...t])}function bi({instructions:m,payer:e,lookupTableAddressAccount:t,recentBlockhash:n=Vt.Keypair.generate().publicKey.toString()}){let i=new Vt.TransactionMessage({payerKey:e,recentBlockhash:n,instructions:m}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new Vt.VersionedTransaction(i).serialize()).toString("base64").length<ju}catch{return!1}}var Sm=m=>Buffer.isBuffer(m)?m:m instanceof Uint8Array?Buffer.from(m.buffer,m.byteOffset,m.byteLength):Buffer.from(m),Km=m=>{let e=m.serialize({requireAllSignatures:!1,verifySignatures:!1});m instanceof Vt.VersionedTransaction&&(e=Sm(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch{return e.toString("base64")}};function mo(m){let e=[];return m.forEach(t=>{t instanceof Vt.Transaction&&(t.recentBlockhash||(t.recentBlockhash=$u.TOKEN_PROGRAM_ID.toBase58()),t.feePayer||(t.feePayer=Vt.Keypair.generate().publicKey)),e.push(Km(t))}),console.log("simulate tx string:",e),e}var Ju=require("@solana/web3.js"),ec=te(require("bn.js"));function Cm(m){return typeof m=="object"&&m!==null&&![je,_e,Ju.PublicKey,ve,ec.default,qt,St].some(e=>typeof e=="object"&&m instanceof e)}function Ut(m){return typeof m=="string"?ga(m):Array.isArray(m)?m.map(e=>Ut(e)):Cm(m)?Object.fromEntries(Object.entries(m).map(([e,t])=>[e,Ut(t)])):m}var Rm=xe("Raydium.farm.util");function gi({programId:m,poolId:e,mint:t,type:n}){let{publicKey:o}=le([e.toBuffer(),t.toBuffer(),Buffer.from(n==="lpVault"?"lp_vault_associated_seed":n==="rewardVault"?"reward_vault_associated_seed":"","utf-8")],m);return o}function sn({programId:m,poolId:e,owner:t,version:n}){let{publicKey:o}=le([e.toBuffer(),t.toBuffer(),Buffer.from(n===6?"farmer_info_associated_seed":"staker_info_v2_associated_seed","utf-8")],m);return o}var nc=({programId:m,poolId:e})=>le([e.toBuffer()],m);function oc(m){return{isSet:new tc.default(1),rewardPerSecond:ye(m.perSecond),rewardOpenTime:ye(m.openTime),rewardEndTime:ye(m.endTime),rewardType:ye($n[m.rewardType])}}function Wa(m){return ye(m.endTime).sub(ye(m.openTime)).mul(ye(m.perSecond))}function Pi(m){let e=pi[m];return e||Rm.logWithError("invalid version",m),e}var oe=require("@solana/web3.js"),qa=te(require("bn.js")),un=require("@solana/spl-token");var ic=require("@solana/web3.js"),rc=require("@solana/spl-token");function ne(m,e,t){return le([m.toBuffer(),(t!=null?t:rc.TOKEN_PROGRAM_ID).toBuffer(),e.toBuffer()],new ic.PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}var Lm=xe("Raydium_farm_instruction"),gb={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(m){let{version:e,id:t,ledger:n,programId:o,owner:i}=m,r={3:9,5:10}[e];r||Lm.logWithError(`invalid farm pool version: ${e}`);let a=Buffer.alloc(Fa.span);Fa.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 ac(m){var n;let e=Buffer.alloc(_a.span);_a.encode({instruction:0,nonce:new qa.default(m.nonce),rewardTimeInfo:m.rewardInfoConfig},e);let t=[...ya,K({pubkey:m.farmId}),K({pubkey:m.farmAuthority,isWritable:!1}),K({pubkey:m.lpVault}),K({pubkey:m.lpMint,isWritable:!1}),K({pubkey:m.lockVault}),K({pubkey:m.lockMint,isWritable:!1}),K({pubkey:(n=m.lockUserAccount)!=null?n:xt}),K({pubkey:m.owner,isWritable:!1,isSigner:!0})];for(let o of m.rewardInfo)t.push(K({pubkey:o.rewardMint,isWritable:!1}),K({pubkey:o.rewardVault}),K({pubkey:o.userRewardToken}));return{instruction:new oe.TransactionInstruction({programId:m.programId,keys:t,data:e}),instructionType:X.FarmV6Create}}function sc(m){let e=Buffer.alloc(va.span);va.encode({instruction:5},e);let t=[K({pubkey:un.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:m.id}),K({pubkey:m.authority,isWritable:!1}),K({pubkey:m.lpVault,isWritable:!1}),K({pubkey:m.rewardVault}),K({pubkey:m.userRewardToken}),K({pubkey:m.owner,isWritable:!1,isSigner:!0})];return{instruction:new oe.TransactionInstruction({programId:m.programId,keys:t,data:e}),instructionType:X.FarmV6CreatorWithdraw}}function Ua({payer:m,rewardVault:e,userRewardTokenPub:t,farmKeys:n,rewardInfo:o}){let i=Buffer.alloc(Va.span);Va.encode({instruction:3,rewardReopenTime:ye(o.openTime),rewardEndTime:ye(o.endTime),rewardPerSecond:ye(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:m,isWritable:!1,isSigner:!0})];return new oe.TransactionInstruction({programId:n.programId,keys:r,data:i})}function Ga({payer:m,userRewardTokenPub:e,farmKeys:t,rewardVault:n,rewardInfo:o}){let i=Buffer.alloc(Ea.span);Ea.encode({instruction:4,isSet:new qa.default(1),rewardPerSecond:ye(o.perSecond),rewardOpenTime:ye(o.openTime),rewardEndTime:ye(o.endTime),rewardType:ye($n[o.rewardType])},i);let r=[...ya,K({pubkey:t.id}),K({pubkey:t.authority,isWritable:!1}),K({pubkey:o.mint,isWritable:!1}),K({pubkey:n}),K({pubkey:e}),K({pubkey:m,isWritable:!1,isSigner:!0})];return new oe.TransactionInstruction({programId:t.programId,keys:r,data:i})}function wi(m){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r}=m,[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:ye(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 d=0;d<t.rewardInfos.length;d++)l.push(K({pubkey:new oe.PublicKey(t.rewardInfos[d].vault)})),l.push(K({pubkey:o[d]}));return new oe.TransactionInstruction({programId:a,keys:l,data:c})}function ki(m){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=m,[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:ye(r)},l);let d=[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++)d.push(K({pubkey:o[p]})),d.push(K({pubkey:new oe.PublicKey(t.rewardInfos[p].vault)}));if(a)for(let p of a)d.push(K({pubkey:p}));return new oe.TransactionInstruction({programId:u,keys:d,data:l})}function uc(m){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=m,[u,s]=[new oe.PublicKey(e.programId),new oe.PublicKey(e.id)],c=v([V("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)})],d=Buffer.alloc(c.span);return c.encode({instruction:2,amount:r},d),new oe.TransactionInstruction({keys:l,programId:u,data:d})}function Ti(m){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=m,[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:ye(r)},l);let d=[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)d.push(K({pubkey:p}));return new oe.TransactionInstruction({programId:u,keys:d,data:l})}function cc(m){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=m,[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:ye(r)},l);let d=[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)d.push(K({pubkey:p}));return new oe.TransactionInstruction({programId:u,keys:d,data:l})}function lc(m){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=m,[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:ye(r)},l);let d=[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++)d.push(K({pubkey:o[p]})),d.push(K({pubkey:new oe.PublicKey(t.rewardInfos[p].vault)}));if(a)for(let p of a)d.push(K({pubkey:p}));return new oe.TransactionInstruction({programId:u,keys:d,data:l})}function mc(m){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r}=m,[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:ye(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 d=0;d<t.rewardInfos.length;d++)l.push(K({pubkey:new oe.PublicKey(t.rewardInfos[d].vault)})),l.push(K({pubkey:o[d]}));return new oe.TransactionInstruction({programId:a,keys:l,data:c})}var Om=v([Je("mintAuthorityOption"),F("mintAuthority"),w("supply"),V("decimals"),V("isInitialized"),Je("freezeAuthorityOption"),F("freezeAuthority")]);var Nm=require("@solana/spl-token"),Mm=require("@solana/web3.js");var hi=m=>new je({mint:m.address,decimals:m.decimals,symbol:m.symbol,name:m.name}),bt=o=>{var i=o,{amount:m,isRaw:e,name:t}=i,n=$e(i,["amount","isRaw","name"]);return new _e(new je({mint:Nt(n.address).toBase58(),decimals:n.decimals,symbol:n.symbol,name:t}),m,e,t)};var kt=o=>{var i=o,{address:m,programId:e,decimals:t}=i,n=$e(i,["address","programId","decimals"]);return N({chainId:101,address:Nt(m).toBase58(),programId:e,logoURI:"",symbol:"",name:"",decimals:t,tags:[],extensions:n.extensions||{}},n)},xn=m=>m?_(N({},m),{transferFeeConfigAuthority:m.transferFeeConfigAuthority.toBase58(),withdrawWithheldAuthority:m.withdrawWithheldAuthority.toBase58(),withheldAmount:m.withheldAmount.toString(),olderTransferFee:_(N({},m.olderTransferFee),{epoch:m.olderTransferFee.epoch.toString(),maximumFee:m.olderTransferFee.maximumFee.toString()}),newerTransferFee:_(N({},m.newerTransferFee),{epoch:m.newerTransferFee.epoch.toString(),maximumFee:m.newerTransferFee.maximumFee.toString()})}):void 0;var fe=require("@solana/web3.js"),Pe=require("@solana/spl-token"),he=te(require("bn.js")),Me=te(require("decimal.js"));var We=require("@solana/spl-token"),G=require("@solana/web3.js"),lt=te(require("bn.js")),Kn=te(require("decimal.js"));var Ve=require("@solana/web3.js"),dc=te(require("axios"));var gn=require("@solana/web3.js");async function za({connection:m,address:e,cluster:t="mainnet"}){let n=await It(m,[...new Set(e.map(i=>i.toString()))].map(i=>new gn.PublicKey(i))),o={};for(let i=0;i<e.length;i++){let r=n[i],a=e[i];if(!r)continue;let u=new gn.AddressLookupTableAccount({key:a,state:gn.AddressLookupTableAccount.deserialize(r.data)});o[a.toString()]=u,t==="devnet"?Fo[a.toString()]=u:Mo[a.toString()]=u}return o}var Mo={},Xa=async m=>{let e="AcL1Vo8oy1ULiavEcjSUcwfBSForXMudcZvDZy5nzJkU";if(Mo[e])return Mo;let t=new gn.PublicKey(e),n=await m.getAccountInfo(t);return n&&(Mo[e]=new gn.AddressLookupTableAccount({key:t,state:gn.AddressLookupTableAccount.deserialize(n.data)})),Mo},Fo={},Ya=async m=>{let e="EFhMuDw1PKEuckuFRW9PavNfTH4LKP5uKHgyXDmWpFCq";if(Fo[e])return Fo;let t=new gn.PublicKey(e),n=await m.getAccountInfo(t);return n&&(Fo[e]=new gn.AddressLookupTableAccount({key:t,state:gn.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 dc.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(_(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(d=>d.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 d of l)try{d.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:d,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]}),d==null||d([...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"}d==null||d([...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:1});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=$e(f,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),a=N(N({},this.cluster==="devnet"?await Ya(this.connection):await Xa(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 za({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),d=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(d);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:d,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]}),d==null||d([...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"}d==null||d([...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:1});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 d;let l=e||{},{splitIns:t=[],computeBudgetConfig:n}=l,o=$e(l,["splitIns","computeBudgetConfig"]),i=n?gr(n):{instructions:[],instructionTypes:[]},r=this.signers.reduce((p,f)=>_(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),(d=this.owner)!=null&&d.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=M=>{L!==null&&clearInterval(L),O!==null&&this.connection.removeSignatureListener(O);let D=x.findIndex(E=>E.txId===B);if(D>-1){if(x[D].status==="error"||x[D].status==="success")return;x[D].status=M.err?"error":"success"}y==null||y([...x]),M.err||S()};this.loopMultiTxStatus&&(L=setInterval(async()=>{var M;if(R){clearInterval(L);return}try{let D=await this.connection.getTransaction(B,{commitment:"confirmed",maxSupportedTransactionVersion:1});D&&(R=!0,clearInterval(L),C({err:((M=D.meta)==null?void 0:M.err)||null}),console.log("tx status from getTransaction:",B))}catch(D){R=!0,clearInterval(L),console.error("getTransaction timeout:",D,B)}},Ar)),O=this.connection.onSignature(B,M=>{if(R){this.connection.removeSignatureListener(O);return}R=!0,C(M)},"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=$e(k,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress","insCountLimit"]),u=N(N({},this.cluster==="devnet"?await Ya(this.connection):await Xa(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 za({connection:this.connection,address:c});for(let[P,T]of Object.entries(l))u[P]=T;let d=t?gr(t):{instructions:[],instructionTypes:[]},p=await No(this.connection,this.blockhashCommitment),f=this.signers.reduce((P,T)=>_(N({},P),{[T.publicKey.toBase58()]:T}),{}),y=[],b=[],g=[],A=0;if(this.allInstructions.forEach(P=>{let T=[...g,P],I=t?[...d.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:[...d.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:u,recentBlockhash:p})){let S=new Ve.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...d.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:[...d.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:u,recentBlockhash:p})){let I=new Ve.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...d.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 M=await this.connection.sendTransaction(C,{skipPreflight:B});await Pr(this.connection,M),O.push(M)}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,M=[],D=async()=>{if(!O[C])return;if(C<x){M.push({txId:"",status:"success",signedTx:O[C]}),I==null||I([...M]),C++,D();return}let E=await this.connection.sendTransaction(O[C],{skipPreflight:B});M.push({txId:E,status:"sent",signedTx:O[C]}),I==null||I([...M]),C++;let z=!1,H=null,Y=null,J=ie=>{H!==null&&clearInterval(H),Y!==null&&this.connection.removeSignatureListener(Y);let Z=M.findIndex(ge=>ge.txId===E);if(Z>-1){if(M[Z].status==="error"||M[Z].status==="success")return;M[Z].status=ie.err?"error":"success"}I==null||I([...M]),ie.err||D()};this.loopMultiTxStatus&&(H=setInterval(async()=>{var ie;if(z){clearInterval(H);return}try{let Z=await this.connection.getTransaction(E,{commitment:"confirmed",maxSupportedTransactionVersion:1});Z&&(z=!0,clearInterval(H),J({err:((ie=Z.meta)==null?void 0:ie.err)||null}),console.log("tx status from getTransaction:",E))}catch(Z){z=!0,clearInterval(H),console.error("getTransaction timeout:",Z,E)}},Ar)),Y=this.connection.onSignature(E,ie=>{if(z){this.connection.removeSignatureListener(Y);return}z=!0,J(ie)},"confirmed"),this.connection.getSignatureStatus(E)};return D(),{txIds:[],signedTxs:O}}else{let C=[];for(let M=0;M<O.length;M+=1){let D=await this.connection.sendTransaction(O[M],{skipPreflight:B});C.push(D)}return{txIds:C,signedTxs:O}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:a||{}}}};var Ha=(...m)=>m.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch{return e}}).join(", "),rt=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=xe(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(Ha(e))}logInfo(...e){this.logger.info(Ha(e))}logAndCreateError(...e){let t=Ha(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};var de=require("@solana/spl-token"),W=require("@solana/web3.js"),Oi=te(require("bn.js"));var Le=te(require("bn.js")),De=new Le.default(1).shln(64),vo=64,Fm=new Le.default(1).shln(128),Sn=new Le.default(1).shln(64).subn(1),vm=new Le.default(1).shln(128).subn(1),cn=-443636,ln=443636,Kt=new Le.default("4295048016"),Ct=new Le.default("79226673521066979257578248091"),pc=new Le.default("59543866431248"),fc=new Le.default("184467440737095516"),yc=new Le.default("15793534762490258745"),bc=16,kr=512,Qt=60,ig=new Le.default("18446743708227953217"),gc=[{bit:0,factor:new Le.default("fffcb933bd6fb800",16)},{bit:1,factor:new Le.default("fff97272373d4000",16)},{bit:2,factor:new Le.default("fff2e50f5f657000",16)},{bit:3,factor:new Le.default("ffe5caca7e10f000",16)},{bit:4,factor:new Le.default("ffcb9843d60f7000",16)},{bit:5,factor:new Le.default("ff973b41fa98e800",16)},{bit:6,factor:new Le.default("ff2ea16466c9b000",16)},{bit:7,factor:new Le.default("fe5dee046a9a3800",16)},{bit:8,factor:new Le.default("fcbe86c7900bb000",16)},{bit:9,factor:new Le.default("f987a7253ac65800",16)},{bit:10,factor:new Le.default("f3392b0822bb6000",16)},{bit:11,factor:new Le.default("e7159475a2caf000",16)},{bit:12,factor:new Le.default("d097f3bdfd2f2000",16)},{bit:13,factor:new Le.default("a9f746462d9f8000",16)},{bit:14,factor:new Le.default("70d869a156f31c00",16)},{bit:15,factor:new Le.default("31be135f97ed3200",16)},{bit:16,factor:new Le.default("9aa508b5b85a500",16)},{bit:17,factor:new Le.default("5d6af8dedc582c",16)},{bit:18,factor:new Le.default("2216e584f5fa",16)}],vn=1e6;var Tr=1e5,Bi=1e4,Pc=1e4,Ac=1e5;var Ii=3,wc=100;var kc=10,Tc=100,_o=14;var j=new Le.default(0),dt=new Le.default(1),rg=new Le.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 ag=new Le.default("18446744073700000000");var Qa=v([Be(8),V("bump"),ze("index"),F("owner"),Je("protocolFeeRate"),Je("tradeFeeRate"),ze("tickSpacing"),Je("fundFeeRate"),Q(Je(),1),F("fundOwner"),Q(w(),3)]),_m=v([Je("blockTimestamp"),Oo("tickCumulative"),Q(w(),4)]),hc=v([Be(8),it("initialized"),w("recentEpoch"),ze("observationIndex"),F("poolId"),Q(_m,wc,"observations"),Q(w(),4)]),Vm=v([ze("filterPeriod"),ze("decayPeriod"),ze("reductionFactor"),Je("dynamicFeeControl"),Je("maxVolatilityAccumulator"),yt("tickSpacingIndexReference"),Je("volatilityReference"),Je("volatilityAccumulator"),w("lastUpdateTimestamp"),Q(V(),46)]),Em=v([V("state"),w("openTime"),w("endTime"),w("lastUpdateTime"),ce("emissionsPerSecondX64"),w("totalEmissioned"),w("claimed"),F("mint"),F("vault"),F("creator"),ce("growthGlobalX64")]),fo=v([Be(8),V("bump"),F("configId"),F("creator"),F("mintA"),F("mintB"),F("vaultA"),F("vaultB"),F("observationId"),V("mintDecimalsA"),V("mintDecimalsB"),ze("tickSpacing"),ce("liquidity"),ce("sqrtPriceX64"),yt("tickCurrent"),Je(),ce("feeGrowthGlobalX64A"),ce("feeGrowthGlobalX64B"),w("protocolFeesTokenA"),w("protocolFeesTokenB"),Q(ce(),4),V("status"),V("feeOn"),Be(6),Q(Em,Ii,"rewardInfos"),Be(8*16,"tickArrayBitmap"),Q(w(),4),w("fundFeesTokenA"),w("fundFeesTokenB"),w("startTime"),w("recentEpoch"),Vm.replicate("dynamicFeeInfo"),Q(w(),46)]),Dm=v([ce("growthInsideLastX64"),w("rewardAmountOwed")]),Br=v([Be(8),V("bump"),F("nftMint"),F("poolId"),yt("tickLower"),yt("tickUpper"),ce("liquidity"),ce("feeGrowthInsideLastX64A"),ce("feeGrowthInsideLastX64B"),w("tokenFeesOwedA"),w("tokenFeesOwedB"),Q(Dm,Ii,"rewardInfos"),w("recentEpoch"),Q(w(),7)]),lg=v([Be(8),V("bump"),F("poolId"),yt("tickLower"),yt("tickUpper"),ce("liquidity"),ce("feeGrowthInsideLastX64A"),ce("feeGrowthInsideLastX64B"),w("tokenFeesOwedA"),w("tokenFeesOwedB"),Q(ce(),Ii,"rewardGrowthInside"),w("recentEpoch"),Q(w(),7)]),Wm=v([yt("tick"),xu("liquidityNet"),ce("liquidityGross"),ce("feeGrowthOutsideX64A"),ce("feeGrowthOutsideX64B"),Q(ce(),Ii,"rewardGrowthsOutsideX64"),w("orderPhase"),w("ordersAmount"),w("partFilledOrdersRemaining"),ce("unfilledRatioX64"),Q(Je(),3)]),Vo=v([Be(8),F("poolId"),yt("startTickIndex"),Q(Wm,Qt,"ticks"),V("initializedTickCount"),w("recentEpoch"),Q(V(),107)]),Bc=v([Be(8),V("bump"),Q(F(),kc,"operationOwners"),Q(F(),Tc,"whitelistMints")]),yo=v([Be(8),F("poolId"),F("owner"),yt("tick"),it("zeroForOne"),w("orderPhase"),w("totalAmount"),w("filledAmount"),w("settleBase"),w("settleOutput"),w("openTime"),ce("unfilledRatioX64"),Q(w(),4)]),Ir=v([Be(8),F("poolId"),Be(8*8*_o,"positiveTickArrayBitmap"),Be(8*8*_o,"negativeTickArrayBitmap")]),mg=v([Be(8),ze("index"),ze("filterPeriod"),ze("decayPeriod"),ze("reductionFactor"),Je("dynamicFeeControl"),Je("maxVolatilityAccumulator"),Q(w(),8)]),Ic=v([Be(8),F("wallet"),V("nonceIndex"),w("orderNonce"),Q(w(),4)]),dg=v([w(),V("bump"),F("owner"),F("poolId"),F("positionId"),F("nftAccount"),Q(w(),8)]),xc=v([Be(8),V("bump"),F("lockOwner"),F("poolId"),F("positionId"),F("nftAccount"),F("lockNftMint"),w("recentEpoch"),Q(w(),8)]);var Sc=te(require("bn.js"));function xr(m){let e=Buffer.alloc(2);return e.writeUInt16LE(m),e}function Za(m){let e=Buffer.alloc(4);return e.writeInt32LE(m),e}function Kc(m){let e=Buffer.alloc(4);return e.writeInt32BE(m),e}function Cc(m){return(typeof m=="number"||typeof m=="bigint")&&(m=new Sc.default(m.toString())),m.toArrayLike(Buffer,"be",8)}function Rc(m){let e=new ArrayBuffer(1);return new DataView(e).setUint8(0,m),new Uint8Array(e)}var wg=Buffer.from("amm_config","utf8"),Sr=Buffer.from("pool","utf8"),$a=Buffer.from("pool_vault","utf8"),qm=Buffer.from("pool_reward_vault","utf8"),Lc=Buffer.from("position","utf8"),Um=Buffer.from("tick_array","utf8"),Gm=Buffer.from("operation","utf8"),zm=Buffer.from("pool_tick_array_bitmap_extension","utf8"),Xm=Buffer.from("observation","utf8"),Ym=Buffer.from("support_mint","utf8"),kg=Buffer.from("dynamic_fee_config","utf8"),Hm=Buffer.from("permission","utf8");function Oc(m,e,t,n){return le([Sr,e.toBuffer(),t.toBuffer(),n.toBuffer()],m)}function Nc(m,e){return le([Hm,e.toBuffer()],m)}function Mc(m,e,t,n,o){return le([Sr,e.toBuffer(),t.toBuffer(),n.toBuffer(),xr(o)],m)}function on(m,e,t){return le([$a,e.toBuffer(),t.toBuffer()],m)}function Fc(m,e,t){return le([qm,e.toBuffer(),t.toBuffer()],m)}function Ee(m,e,t){return le([Um,e.toBuffer(),Kc(t)],m)}function Pn(m,e,t,n){return le([Lc,e.toBuffer(),Za(t),Za(n)],m)}function rn(m,e){return le([Lc,e.toBuffer()],m)}function _n(m){return le([Buffer.from("metadata","utf8"),In.toBuffer(),m.toBuffer()],In)}function xi(m){return le([Gm],m)}function Ze(m,e){return le([zm,e.toBuffer()],m)}function ja(m,e){return le([Xm,e.toBuffer()],m)}function bo(m,e){return le([Ym,e.toBuffer()],m)}function vc(m,e,t,n){return le([e.toBuffer(),t.toBuffer(),Cc(n)],m)}function _c(m,e,t){return le([e.toBuffer(),Rc(t)],m)}var Vc=Buffer.from("locked_position","utf8");function Ja(m,e){return le([Vc,e.toBuffer()],m)}function Eo(m,e){return le([Vc,e.toBuffer()],m)}var Yc=require("js-sha256");var es=te(require("bn.js")),Kr=te(require("decimal.js"));function ct(m,e,t){if(t.isZero())throw new Error("Division by zero");return m.mul(e).div(t)}function et(m,e,t){if(t.isZero())throw new Error("Division by zero");let n=m.mul(e),o=n.div(t);return n.mod(t).isZero()?o:o.addn(1)}function Cr(m,e){return m.div(e).add(m.mod(e).isZero()?j:dt)}var Bg=new es.default(1).shln(256).subn(1);function Ec(m){return m.isZero()?-1:m.bitLength()-1}function Dc(m,e){return new Kr.default(m.toString()).div(Kr.default.pow(2,64)).toDecimalPlaces(e)}function go(m){return new es.default(m.mul(Kr.default.pow(2,64)).floor().toFixed())}var qc=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 d=l===s?a%8:0,p=l===c?u%8:7;for(let f=d;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 d=s*64+Math.floor(c/8);if(!e[d]){c=Math.floor(c/8)*8+7;continue}if(e[d]&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 gc)(t&1<<o)!==0&&(n=ct(n,i,De));return e>0&&(n=ct(De,De,n)),n}static getLimitOrderOutput({amountIn:e,tick:t,zeroForOne:n}){if(n){let o=se.getPriceAtTick(t,!1);return ct(e,o,De)}else{let o=se.getPriceAtTick(t,!0);return ct(e,De,o)}}static getLimitOrderInput({amountOut:e,tick:t,zeroForOne:n}){if(n){let o=se.getPriceAtTick(t,!0);return et(e,o,De)}else{let o=se.getPriceAtTick(t,!1);return et(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:j,amountOut:j,ammFeeAmount:j},u=this.limitOrderUnfilledAmount({tick:e});if(t.isZero()||u.isZero())return a;if(o)r?(a.ammFeeAmount=et(t,new gt.default(i),tt),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=et(a.amountIn,new gt.default(i),tt.sub(new gt.default(i)))));else{let l=gt.default.min(t,u);r?a.amountOut=l:a.amountOut=gt.default.min(et(l,tt,tt.sub(new gt.default(i))),u),a.amountIn=this.getLimitOrderInput({amountOut:a.amountOut,tick:e.tick,zeroForOne:!n}),r&&(a.ammFeeAmount=et(a.amountIn,new gt.default(i),tt.sub(new gt.default(i))))}let s=j;e.partFilledOrdersRemaining.gt(j)&&(s=gt.default.min(e.partFilledOrdersRemaining,a.amountOut),s.gt(j)&&(e.unfilledRatioX64=ct(e.unfilledRatioX64,e.partFilledOrdersRemaining.sub(s),e.partFilledOrdersRemaining)),e.partFilledOrdersRemaining=e.partFilledOrdersRemaining.sub(s));let c=a.amountOut.sub(s);if(c.gt(j)){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=ct(De,e.ordersAmount.sub(c),e.ordersAmount),e.partFilledOrdersRemaining=e.ordersAmount.sub(c),e.ordersAmount=j}return r||(a.ammFeeAmount=et(a.amountOut,new gt.default(i),tt),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(Kt)&&e.lte(Ct)))throw Error("SqrtPriceX64");let t=Ec(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<bc&&!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(pc),l=c.sub(fc),d=c.add(yc),p=this.signedShrn64(l),f=this.signedShrn64(d);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 d=l.slice(0,-r),p=l.slice(-r),f=d+"."+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 Wc(m,e,t,n,o,i,r=!0){let a=[],u=Ze(m,t).publicKey,s=await e.getAccountInfo(u),c=Vn.findTickArrayAddress({programId:m,poolId:t,poolBitmap:i,tickArrayBitmap:Ir.decode(s.data),tickSpacing:o,findInfo:{type:r?"zeroForOne":"oneForZero",tickArrayCurrent:n}});return(await It(e,c)).forEach((d,p)=>{d&&a.push({address:c[p],value:Vo.decode(d.data)})}),a}var jn=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 j;if(e.orderPhase.eq(t.orderPhase))return j;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 j;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 qc.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")),ts=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(j))throw Error("!sqrtPriceX64A.gt(BN_ZERO)");let a=o?Cr(et(i,r,t),e):ct(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?et(n,t.sub(e),De):ct(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 j;e.gt(t)&&([e,t]=[t,e]);let o=ct(e,t,De),i=t.sub(e);return ct(n,o,i)}static getLiquidityFromAmountB(e,t,n){if(n.isZero())return j;e.gt(t)&&([e,t]=[t,e]);let o=t.sub(e);return ct(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=j,a=j;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 ts.default(u.toString()).mul(c).toFixed(0)),d=new Si.default(new ts.default(s.toString()).mul(c).toFixed(0));return{amountSlippageA:l,amountSlippageB:d}}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)?j:this.getLiquidityFromAmountA(Si.default.max(e,t),n,o.amount);else if(o.type==="amountB")i=e.lte(t)?j: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 Et=require("@solana/web3.js"),Tt=te(require("bn.js"));var Li=require("@solana/spl-token");var Se=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 et(i,e,a);let u=ct(i,dt,e);return et(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 et(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(j))throw Error("sqrtPriceX64.gt(BN_ZERO)");if(!t.gt(j))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(j))throw Error("sqrtPriceX64.gt(BN_ZERO)");if(!t.gt(j))throw Error("liquidity.gt(BN_ZERO)");return o?this.getNextSqrtPriceFromAmountBRoundingDown(e,t,n,!1):this.getNextSqrtPriceFromAmountARoundingUp(e,t,n,!1)}};var An=class{static newValue({poolInfo:e,amountSpecified:t,zeroForOne:n,feeRate:o,blockTimestamp:i}){let r={amountSpecifiedRemaining:t,amountCalculated:j,sqrtPriceX64:e.sqrtPriceX64,tick:e.tickCurrent,feeGrowthGlobalX64:n?e.feeGrowthGlobalX64A:e.feeGrowthGlobalX64B,lpFee:j,protocolFee:j,fundFee:j,liquidity:e.liquidity,sqrtPriceNextX64:j,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=Ac*Bi*Bi,r=et(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(j)){let r=t.mul(n).div(new ft.default(tt));e.protocolFee=e.protocolFee.add(r),i=i.sub(r)}if(o.gt(j)){let r=t.mul(o).div(new ft.default(tt));e.fundFee=e.fundFee.add(r),i=i.sub(r)}if(e.liquidity.gt(j)){let r=ct(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:j,amountIn:j,amountOut:j,feeAmount:j}}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?ct(o,new ft.default(vn-i),new ft.default(vn)):o,d=this.calculateAmountInRange({sqrtPriceCurrentX64:e,sqrtPriceTargetX64:t,liquidity:n,zeroForOne:a,isBaseInput:r});d!==null&&(s.amountIn=d),s.sqrtPriceNextX64=d!==null&&l.gte(s.amountIn)?t:Ki.getNextSqrtPriceFromInput(e,n,l,a)}else{let l=u?o:et(o,new ft.default(vn),new ft.default(vn-i)),d=this.calculateAmountInRange({sqrtPriceCurrentX64:e,sqrtPriceTargetX64:t,liquidity:n,zeroForOne:a,isBaseInput:r});d!==null&&(s.amountOut=d),s.sqrtPriceNextX64=d!==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=et(s.amountIn,new ft.default(i),new ft.default(vn-i)):s.feeAmount=o.sub(s.amountIn):(s.feeAmount=et(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=et(s.amountIn,new ft.default(i),new ft.default(vn-i));else{s.feeAmount=et(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 ns({programId:m,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(Kt).addn(1):new Ao.default(Ct).subn(1));let d=0;if(n.length===0)return{allTrade:!1,amountSpecifiedRemaining:r,amountCalculated:j,feeAmount:j,sqrtPriceX64:t.sqrtPriceX64,liquidity:t.liquidity,tickCurrent:t.tickCurrent,accounts:[]};let p=l?Vn.findTickArrayAddress({programId:m,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[d].value.startTickIndex===f,firstValidTickArrayStartIndex:n[d].value.startTickIndex},g=y,A=b,k=n[d],h=Zt.isFeeOnInput(t.feeOn,u),P=An.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[++d];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,d).map(S=>S.address)};let I=An.getTargetPriceBasedOnNextTick({data:P,tickNext:T.tick,zeroForOne:u,sqrtPriceLimitX64:a}),x=P.liquidity;do{An.updateVolatilityAccumulator({state:P});let S=An.getTotalFeeRate({data:P}),{isSkipped:B,boundedPrice:R}=An.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),An.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 M=se.matchLimitOrder({tick:T,swapAmount:P.amountSpecifiedRemaining,swapDirectionZeroForOne:u,isBaseInput:s,feeRate:S,isFeeOnInput:h});if(M.amountIn.gt(j)&&An.applySwapAmounts({state:P,amountIn:M.amountIn,amountOut:M.amountOut,feeAmount:M.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 D=u?T.liquidityNet.neg():T.liquidityNet;x=pt.addDelta(P.liquidity,D)}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,An.updateDynamicFeeIndex({state:P,zeroForOne:u,isSkippedTickSpacing:B}),P.amountSpecifiedRemaining.isZero()||P.sqrtPriceX64.eq(I)){let M=se.limitOrderUnfilledAmount({tick:T});if(!P.amountSpecifiedRemaining.isZero()&&!M.eq(C)&&!M.isZero())throw Error("!limitOrderUnfilledAmountAfter.isZero()");break}}while(!0);P.liquidity=x}return{allTrade:!0,amountSpecifiedRemaining:j,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,d+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/Pc),e.lastUpdateTimestamp=new Tt.default(n)):(e.tickSpacingIndexReference=t,e.volatilityReference=0,e.lastUpdateTimestamp=new Tt.default(n)))}static updateVolatilityAccumulator({state:e,tickSpacingIndex:t}){let n=Math.abs(e.tickSpacingIndexReference-t),o=e.volatilityReference+n*Bi;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],d=(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(d===void 0)throw Error("get new reward mint info error");let p=_(N({},l),{perSecond:Dc(l.emissionsPerSecondX64),remainingRewards:void 0,tokenProgramId:new Et.PublicKey(d)});if(p.mint.equals(Et.PublicKey.default)||p.totalEmissioned.eq(Sn))continue;if(n<=p.openTime.toNumber()||o.eq(j)){r.push(p);continue}let f=new Tt.default(Math.min(p.endTime.toNumber(),n)),y=f.sub(p.lastUpdateTime);if(y.isZero()){r.push(p);continue}let b=et(y,p.emissionsPerSecondX64,De),g=ct(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=ct(P,De,o)}let h=p.growthGlobalX64.add(g);r.push(_(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:d,sqrtPriceX64:p,accounts:f}=ns({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:j,zeroForOne:u,isBaseInput:!0,blockTimestamp:r,includeExtraTickArrays:!0});return{allTrade:c,expectedAmountOut:l,remainingAccounts:f,executionPrice:p,feeAmount:d}}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:d,sqrtPriceX64:p,accounts:f}=ns({programId:e.programId,poolId:e.id,poolInfo:e.accInfo,tickArrays:Object.entries(n).map(y=>({address:new Et.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:j,zeroForOne:u,isBaseInput:!1,blockTimestamp:r,includeExtraTickArrays:!0});return{allTrade:c,expectedAmountIn:l,remainingAccounts:f,executionPrice:p,feeAmount:d}}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()]=Ir.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]=_(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 Se.default(0)}){var O;let c,l=o.toBase58()===e.mintA.address,[d,p]=l?[e.mintA.extensions.feeConfig,e.mintB.extensions.feeConfig]:[e.mintB.extensions.feeConfig,e.mintA.extensions.feeConfig];s.equals(new Se.default(0))?c=l?Kt.add(new Tt.default(1)):Ct.sub(new Tt.default(1)):c=se.priceToSqrtPriceX64(s,e.mintA.decimals,e.mintB.decimals);let f=ht(r,d,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:j),u,c),h=ht(b,p,i,!1),P=se.sqrtPriceX64ToPrice(A,e.mintA.decimals,e.mintB.decimals),T=l?P:new Se.default(1).div(P),I=b.mul(new Tt.default(Math.floor((1-a)*1e10))).div(new Tt.default(1e10)),x=ht(I,p,i,!1),S=l?e.currentPrice:new Se.default(1).div(e.currentPrice),B=new Se.default(T).sub(S).abs(),R=S,L=new St(new Se.default(B).mul(10**15).toFixed(0),new Se.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,d]=c?[e.mintA,e.mintB]:[e.mintB,e.mintA],[p,f]=[new je(_(N({},l),{mint:l.address,isToken2022:l.programId===Li.TOKEN_2022_PROGRAM_ID.toBase58()})),new je(_(N({},d),{mint:d.address,isToken2022:d.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 Et.PublicKey(l.address),amountIn:o,slippage:r,epochInfo:a,catchLiquidityInsufficient:s,blockTimestamp:u}),B=_(N({},b),{amount:new _e(p,b.amount),fee:b.fee===void 0?void 0:new _e(p,b.fee)}),R=_(N({},g),{amount:new _e(f,g.amount),fee:g.fee===void 0?void 0:new _e(f,g.fee)}),L=_(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 Tt.default(10).pow(new Tt.default(20+p.decimals)),quoteToken:f,numerator:h.mul(new Se.default(10**(20+f.decimals))).toFixed(0)}),C=new qt({baseToken:p,denominator:new Tt.default(10).pow(new Tt.default(20+p.decimals)),quoteToken:f,numerator:P.mul(new Se.default(10**(20+f.decimals))).toFixed(0)}),M=new _e(p,I);return{allTrade:y,realAmountIn:B,amountOut:R,minAmountOut:L,expirationTime:k,currentPrice:O,executionPrice:C,priceImpact:T,fee:M,remainingAccounts:x,executionPriceX64:S}}static computeAmountIn({poolInfo:e,tickarrayBitmapExtension:t,tickArrayCache:n,baseMint:o,epochInfo:i,amountOut:r,slippage:a,priceLimit:u=new Se.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},d;u.equals(new Se.default(0))?d=c?Ct.sub(new Tt.default(1)):Kt.add(new Tt.default(1)):d=se.priceToSqrtPriceX64(u,e.mintA.decimals,e.mintB.decimals);let p=ht(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:j),s,d),k=c?e.mintB.address:e.mintA.address,h=ht(y,l[k],i,!1),P=se.sqrtPriceX64ToPrice(g,e.mintA.decimals,e.mintB.decimals),T=c?P:new Se.default(1).div(P),I=y.mul(new Tt.default(Math.floor((1+a)*1e10))).div(new Tt.default(1e10)),x=ht(I,l[k],i,!0),S=c?e.currentPrice:new Se.default(1).div(e.currentPrice),B=new Se.default(T).sub(S).abs(),R=S,L=new St(new Se.default(B).mul(10**15).toFixed(0),new Se.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,d=i.priceMax-i.priceMin,p;return c<=0?p=0:l===c?p=d/c:d===c?p=c/l:p=c/d*(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[Nt(e.mintA.address).toString()],d=o[Nt(e.mintB.address).toString()],p=e.mintA.decimals,f=e.mintB.decimals;if(!c||!l||!d)return{feeApr:0,rewardsApr:[0,0,0],apr:0};let y=se.priceToSqrtPriceX64(new Se.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 Se.default(A.toString()).div(new Se.default(10).pow(p)).mul(l.value).add(new Se.default(k.toString()).div(new Se.default(10).pow(f)).mul(d.value)),I=new Se.default(h.toString()).div(new Se.default(10).pow(p)).mul(l.value).add(new Se.default(P.toString()).div(new Se.default(10).pow(f)).mul(d.value)),x=new Se.default(1).div(T.add(I)),B=new Se.default(c.volumeFee).mul(365).div(s).mul(x).mul(100).toNumber(),R=3600*24*365,L=e.rewardDefaultInfos.map(O=>{var D,E;let C=O.mint.decimals,M=o[O.mint.address];return u<((D=O.startTime)!=null?D:0)||u>((E=O.endTime)!=null?E:0)||!O.perSecond||!M||C===void 0?0:new Se.default(M.value).mul(new Se.default(O.perSecond).mul(R)).div(new Se.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 Se.default(e.price),e.mintA.decimals,e.mintB.decimals),l=se.getSqrtPriceAtTick(n),d=se.getSqrtPriceAtTick(o),p=ht(i,(g=e[t?"mintA":"mintB"].extensions)==null?void 0:g.feeConfig,u,!s),f=new Tt.default(new Se.default(p.amount.sub((A=p.fee)!=null?A:j).toString()).toFixed(0)),y;if(c.lte(l))y=t?pt.getLiquidityFromAmountA(l,d,f):new Tt.default(0);else if(c.lte(d)){let k=pt.getLiquidityFromAmountA(c,d,f),h=pt.getLiquidityFromAmountB(l,c,f);y=t?k:h}else y=t?new Tt.default(0):pt.getLiquidityFromAmountB(l,d,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=pt.getAmountsForLiquidity(se.priceToSqrtPriceX64(new Se.default(t.price),t.mintA.decimals,t.mintB.decimals),u,s,i,a),[l,d]=[ht(c.amountA,(b=t.mintA.extensions)==null?void 0:b.feeConfig,e,!0),ht(c.amountB,(g=t.mintB.extensions)==null?void 0:g.feeConfig,e,!0)],p=r*1e4,[f,y]=[ht(c.amountA.muln(1e4-p).divn(1e4),(A=t.mintA.extensions)==null?void 0:A.feeConfig,e,!0),ht(c.amountB.muln(1e4-p).divn(1e4),(k=t.mintB.extensions)==null?void 0:k.feeConfig,e,!0)];return{liquidity:i,amountA:l,amountB:d,amountSlippageA:f,amountSlippageB:y,expirationTime:En(l.expirationTime,d.expirationTime)}}static async fetchComputeMultipleClmmInfo({connection:e,poolList:t,rpcDataMap:n={}}){let o=t.filter(s=>!n[s.id]).map(s=>new Et.PublicKey(s.id));(await It(e,o)).forEach((s,c)=>{!s||(n[o[c].toBase58()]=fo.decode(s.data))});let r=t.map(s=>Ze(new Et.PublicKey(s.programId),new Et.PublicKey(s.id)).publicKey),a=await Pt.fetchExBitmaps({connection:e,exBitmapAddress:r,batchRequest:!1}),u={};return t.reduce((s,c)=>_(N({},s),{[c.id]:_(N({accInfo:n[c.id]},n[c.id]),{id:new Et.PublicKey(c.id),version:6,programId:new Et.PublicKey(c.programId),mintA:c.mintA,mintB:c.mintB,ammConfig:_(N({},c.config),{id:new Et.PublicKey(c.config.id),fundOwner:""}),currentPrice:new Se.default(c.price),exBitmapAccount:Ze(new Et.PublicKey(c.programId),new Et.PublicKey(c.id)).publicKey,exBitmapInfo:a[Ze(new Et.PublicKey(c.programId),new Et.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))}},os={volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[]};function Uc(m,e){let t=e!=null?e:{};return _(N({},m),{type:"Concentrated",programId:m.programId.toString(),id:m.id.toString(),rewardDefaultInfos:m.rewardInfos.filter(n=>!n.mint.equals(Et.PublicKey.default)).map(n=>{var o,i;return{mint:kt({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:m.currentPrice.toNumber(),mintAmountA:0,mintAmountB:0,feeRate:m.ammConfig.tradeFeeRate,openTime:m.startTime.toString(),tvl:0,day:os,week:os,month:os,pooltype:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0,burnPercent:0,config:_(N({},m.ammConfig),{id:m.ammConfig.id.toString(),defaultRange:0,defaultRangePoint:[]}),hasDynamicFee:!1,feeOn:"",launchMigratePool:!1,tips:[]})}var Zm=te(require("bn.js"));function Rt(m){let e=`global:${m}`;return Buffer.from(Yc.sha256.digest(e)).slice(0,8)}hc.span;var Gc=xe("Raydium_Clmm"),Lt={createPool:Rt("create_pool"),createCustomizablePool:Rt("create_customizable_pool"),createPermissionedPool:Rt("create_permissioned_pool"),openPositionV2:Rt("open_position_v2"),openPositionWithToken22Nft:Rt("open_position_with_token22_nft"),closePosition:Rt("close_position"),increaseLiquidityV2:Rt("increase_liquidity_v2"),decreaseLiquidityV2:Rt("decrease_liquidity_v2"),initializeReward:Rt("initialize_reward"),setRewardParams:Rt("set_reward_params"),updateRewardInfos:Rt("update_reward_infos"),collectRemainingRewards:Rt("collect_remaining_rewards"),swapV2:Rt("swap_v2"),openLimitOrder:Rt("open_limit_order"),increaseLimitOrder:Rt("increase_limit_order"),decreaseLimitOrder:Rt("decrease_limit_order"),settleLimitOrder:Rt("settle_limit_order"),closeLimitOrder:Rt("close_limit_order")},zc=[188,37,179,131,82,150,84,73],Xc=[16,72,250,198,14,162,212,19],we=class{static createPoolInstruction(e,t,n,o,i,r,a,u,s,c,l,d,p,f){let y=v([ce("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:d,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:W.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:_t,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:j},g);let A=Buffer.from([...Lt.createPool,...g]);return new W.TransactionInstruction({keys:b,programId:e,data:A})}static createCustomizablePoolInstruction(e,t,n,o,i,r,a,u,s,c,l,d,p,f,y,b){let g=v([ce("sqrtPriceX64"),V("collectFeeOn"),it("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:d,isSigner:!1,isWritable:!1},{pubkey:W.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:_t,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([...Lt.createCustomizablePool,...k]);return new W.TransactionInstruction({keys:A,programId:e,data:h})}static createPermissionedPoolInstruction(e,t,n,o,i,r,a,u,s,c,l,d,p,f,y,b,g,A,k){let h=v([ce("sqrtPriceX64"),V("collectFeeOn"),it("enableDynamicFee"),ze("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:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:W.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:_t,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([...Lt.createPermissionedPool,...T]);return new W.TransactionInstruction({keys:P,programId:e,data:I})}static initializeRewardInstruction(e,t,n,o,i,r,a,u,s,c,l,d){let p=v([w("openTime"),w("endTime"),ce("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:W.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:_t,isSigner:!1,isWritable:!1}],y=Buffer.alloc(p.span);p.encode({openTime:c,endTime:l,emissionsPerSecondX64:d},y);let b=Buffer.from([...Lt.initializeReward,...y]);return new W.TransactionInstruction({keys:f,programId:e,data:b})}static updateRewardInfosInstruction(e,t){let n=[{pubkey:t,isSigner:!1,isWritable:!0}],o=Buffer.from([...Lt.updateRewardInfos]);return new W.TransactionInstruction({keys:n,programId:e,data:o})}static setRewardParamsInstruction(e,t,n,o,i,r,a,u,s,c,l,d){let p=v([V("rewardIndex"),ce("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:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.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:d,openTime:c,endTime:l},y);let b=Buffer.from([...Lt.setRewardParams,...y]);return new W.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:W.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:r?de.TOKEN_2022_PROGRAM_ID:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}];a&&u.push({pubkey:a,isSigner:!1,isWritable:!0});let s=Buffer.from([...Lt.closePosition]);return new W.TransactionInstruction({keys:u,programId:e,data:s})}static openPositionV2Instruction(e,t,n,o,i,r,a,u,s,c,l,d,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"),ce("liquidity"),w("amountMaxA"),w("amountMaxB"),it("withMetadata"),V("optionBaseFlag"),it("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:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:y,isSigner:!1,isWritable:!0},{pubkey:_t,isSigner:!1,isWritable:!1},{pubkey:W.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:In,isSigner:!1,isWritable:!1},{pubkey:de.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 M=Buffer.from([...Lt.openPositionV2,...C]);return new W.TransactionInstruction({keys:O,programId:e,data:M})}static increaseLiquidityV2Instruction(e,t,n,o,i,r,a,u,s,c,l,d,p,f,y,b,g,A,k){let h=v([ce("liquidity"),w("amountMaxA"),w("amountMaxB"),V("optionBaseFlag"),it("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:d,isSigner:!1,isWritable:!0},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.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([...Lt.increaseLiquidityV2,...T]);return new W.TransactionInstruction({keys:P,programId:e,data:I})}static decreaseLiquidityV2Instruction(e,t,n,o,i,r,a,u,s,c,l,d,p,f,y,b,g,A,k){let h=v([ce("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:d,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:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:fn,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([...Lt.decreaseLiquidityV2,...T]);return new W.TransactionInstruction({keys:P,programId:e,data:I})}static swapV2Instruction(e,t,n,o,i,r,a,u,s,c,l,d,p,f,y,b,g){let A=v([w("amount"),w("otherAmountThreshold"),ce("sqrtPriceLimitX64"),it("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:d,isSigner:!1,isWritable:!0},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:fn,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([...Lt.swapV2,...h]);return new W.TransactionInstruction({keys:k,programId:e,data:P})}static collectRemainingRewardsInstruction(e,t,n,o,i,r,a){let u=v([V("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:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:fn,isSigner:!1,isWritable:!1}],c=Buffer.alloc(u.span);u.encode({rewardIndex:a},c);let l=Buffer.from([...Lt.collectRemainingRewards,...c]);return new W.TransactionInstruction({keys:s,programId:e,data:l})}static openPositionWithToken22NftInstruction(e,t,n,o,i,r,a,u,s,c,l,d,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"),ce("liquidity"),w("amountMaxA"),w("amountMaxB"),it("withMetadata"),V("optionBaseFlag"),it("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:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:_t,isSigner:!1,isWritable:!1},{pubkey:W.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.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([...Lt.openPositionWithToken22Nft,...O]);return new W.TransactionInstruction({keys:L,programId:e,data:C})}static openLimitOrderInstruction(e,t,n,o,i,r,a,u,s,c,l,d,p,f,y,b,g,A){let k=v([V("nonceIndex"),it("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:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:W.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([...Lt.openLimitOrder,...P]);return new W.TransactionInstruction({keys:h,programId:e,data:T})}static increaseLimitOrderInstruction(e,t,n,o,i,r,a,u,s,c){let l=v([w("amount")]),d=[{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([...Lt.increaseLimitOrder,...p]);return new W.TransactionInstruction({keys:d,programId:e,data:f})}static decreaseLimitOrderInstruction(e,t,n,o,i,r,a,u,s,c,l,d,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:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},...f?[{pubkey:f,isSigner:!1,isWritable:!0}]:[]],g=Buffer.alloc(y.span);y.encode({amount:d,amountMin:p},g);let A=Buffer.from([...Lt.decreaseLimitOrder,...g]);return new W.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([...Lt.settleLimitOrder]);return new W.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([...Lt.closeLimitOrder]);return new W.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 W.PublicKey(o.address),new W.PublicKey(i.address)],[l,d]=[new W.PublicKey(o.programId||de.TOKEN_PROGRAM_ID),new W.PublicKey(i.programId||de.TOKEN_PROGRAM_ID)],{publicKey:p}=Oc(t,r,s,c),{publicKey:f}=ja(t,p),{publicKey:y}=on(t,p,s),{publicKey:b}=on(t,p,c),g=Ze(t,p).publicKey,A=[this.createPoolInstruction(t,p,n,r,f,s,y,l,c,b,d,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:d,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,d]=[new W.PublicKey(o.address),new W.PublicKey(i.address)],[p,f]=[new W.PublicKey(o.programId||de.TOKEN_PROGRAM_ID),new W.PublicKey(i.programId||de.TOKEN_PROGRAM_ID)],{publicKey:y}=Mc(t,r,l,d,c),{publicKey:b}=Nc(t,s),{publicKey:g}=ja(t,y),{publicKey:A}=on(t,y,l),{publicKey:k}=on(t,y,d),h=Ze(t,y).publicKey,P=[this.createPoolInstruction(t,y,n,r,g,l,A,p,d,k,f,h,a,u)];return{signers:[],instructions:P,instructionTypes:[X.CreateAccount,X.ClmmCreatePool],address:{poolId:y,observationId:g,exBitmapAccount:h,mintA:l,mintB:d,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:d}){let p=[],[f,y]=[new W.PublicKey(e.programId),new W.PublicKey(e.id)],b;if(l)b=new W.PublicKey((await l(1))[0]);else{let B=W.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}=d?ne(n.wallet,b,de.TOKEN_2022_PROGRAM_ID):ne(n.wallet,b,de.TOKEN_PROGRAM_ID),{publicKey:T}=_n(b),{publicKey:I}=rn(f,b),{publicKey:x}=Pn(f,y,o,i),S=d?this.openPositionWithToken22NftInstruction(f,n.feePayer,y,n.wallet,b,P,x,k,h,I,n.tokenAccountA,n.tokenAccountB,new W.PublicKey(t.vault.A),new W.PublicKey(t.vault.B),new W.PublicKey(e.mintA.address),new W.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]})?Ze(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 W.PublicKey(t.vault.A),new W.PublicKey(t.vault.B),new W.PublicKey(e.mintA.address),new W.PublicKey(e.mintB.address),o,i,g,A,r,a,u,c==="create",null,Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,A]})?Ze(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:d}){let p=[],[f,y]=[new W.PublicKey(e.programId),new W.PublicKey(e.id)],b;if(l)b=new W.PublicKey((await l(1))[0]);else{let B=W.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}=d?ne(n.wallet,b,de.TOKEN_2022_PROGRAM_ID):ne(n.wallet,b,de.TOKEN_PROGRAM_ID),{publicKey:T}=_n(b),{publicKey:I}=rn(f,b),{publicKey:x}=Pn(f,y,o,i),S=d?this.openPositionWithToken22NftInstruction(f,n.feePayer,y,n.wallet,b,P,x,k,h,I,n.tokenAccountA,n.tokenAccountB,new W.PublicKey(t.vault.A),new W.PublicKey(t.vault.B),new W.PublicKey(e.mintA.address),new W.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]})?Ze(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 W.PublicKey(t.vault.A),new W.PublicKey(t.vault.B),new W.PublicKey(e.mintA.address),new W.PublicKey(e.mintB.address),o,i,g,A,j,r==="MintA"?a:u,r==="MintA"?u:a,c==="create",r==="MintA",Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,A]})?Ze(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:d}){let p,f=[];if(l)p=new W.PublicKey((await l(1))[0]);else{let B=W.Keypair.generate();f.push(B),p=B.publicKey}let[y,b]=[new W.PublicKey(e.programId),new W.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}=d?ne(n.wallet,p,de.TOKEN_2022_PROGRAM_ID):ne(n.wallet,p,de.TOKEN_PROGRAM_ID),{publicKey:T}=_n(p),{publicKey:I}=rn(y,p),{publicKey:x}=Pn(y,b,o,i),S=d?this.openPositionWithToken22NftInstruction(y,n.wallet,b,n.wallet,p,P,x,k,h,I,n.tokenAccountA,n.tokenAccountB,new W.PublicKey(t.vault.A),new W.PublicKey(t.vault.B),new W.PublicKey(t.mintA.address),new W.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]})?Ze(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 W.PublicKey(t.vault.A),new W.PublicKey(t.vault.B),new W.PublicKey(t.mintA.address),new W.PublicKey(t.mintB.address),o,i,g,A,r,a,u,c==="create",null,Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,A]})?Ze(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 W.PublicKey(e.programId),a=i?ne(n.wallet,o.nftMint,de.TOKEN_2022_PROGRAM_ID).publicKey:ne(n.wallet,o.nftMint,de.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 W.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 W.PublicKey(e.programId),new W.PublicKey(e.id)],l=Te.getTickArrayStartIndex(n.tickLower,e.config.tickSpacing),d=Te.getTickArrayStartIndex(n.tickUpper,e.config.tickSpacing),{publicKey:p}=Ee(s,c,l),{publicKey:f}=Ee(s,c,d),{publicKey:y}=u?ne(o.wallet,n.nftMint,de.TOKEN_2022_PROGRAM_ID):ne(o.wallet,n.nftMint,de.TOKEN_PROGRAM_ID),{publicKey:b}=rn(s,n.nftMint),{publicKey:g}=Pn(s,c,n.tickLower,n.tickUpper),A=this.increaseLiquidityV2Instruction(s,o.wallet,y,b,c,g,p,f,o.tokenAccountA,o.tokenAccountB,new W.PublicKey(t.vault.A),new W.PublicKey(t.vault.B),new W.PublicKey(e.mintA.address),new W.PublicKey(e.mintB.address),i,r,a,null,Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[l,d]})?Ze(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 W.PublicKey(e.programId),new W.PublicKey(e.id)],l=Te.getTickArrayStartIndex(n.tickLower,e.config.tickSpacing),d=Te.getTickArrayStartIndex(n.tickUpper,e.config.tickSpacing),{publicKey:p}=Ee(s,c,l),{publicKey:f}=Ee(s,c,d),{publicKey:y}=u?ne(o.wallet,n.nftMint,de.TOKEN_2022_PROGRAM_ID):ne(o.wallet,n.nftMint,de.TOKEN_PROGRAM_ID),{publicKey:b}=rn(s,n.nftMint),{publicKey:g}=Pn(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 W.PublicKey(t.vault.A),new W.PublicKey(t.vault.B),new W.PublicKey(e.mintA.address),new W.PublicKey(e.mintB.address),j,i==="MintA"?r:a,i==="MintA"?a:r,i==="MintA",Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[l,d]})?Ze(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 W.PublicKey(e.programId),new W.PublicKey(e.id)],d=Te.getTickArrayStartIndex(n.tickLower,e.config.tickSpacing),p=Te.getTickArrayStartIndex(n.tickUpper,e.config.tickSpacing),{publicKey:f}=Ee(c,l,d),{publicKey:y}=Ee(c,l,p),{publicKey:b}=s?ne(o.wallet,n.nftMint,de.TOKEN_2022_PROGRAM_ID):ne(o.wallet,n.nftMint,u),{publicKey:g}=rn(c,n.nftMint),{publicKey:A}=Pn(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 W.PublicKey(t.rewardInfos[I].vault),ownerRewardVault:S,rewardMint:new W.PublicKey(x)})}let P=[],T=this.decreaseLiquidityV2Instruction(c,o.wallet,b,g,l,A,f,y,o.tokenAccountA,o.tokenAccountB,new W.PublicKey(t.vault.A),new W.PublicKey(t.vault.B),new W.PublicKey(e.mintA.address),new W.PublicKey(e.mintB.address),h,i,r,a,Zt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[d,p]})?Ze(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 W.PublicKey(e.programId),new W.PublicKey(e.id)],[d,p]=[new W.PublicKey(t.vault.A),new W.PublicKey(t.vault.B)],[f,y]=[new W.PublicKey(e.mintA.address),new W.PublicKey(e.mintB.address)],b=e.mintA.address.toString()===i.toString(),g=[this.swapV2Instruction(c,o.wallet,l,new W.PublicKey(e.config.id),b?o.tokenAccountA:o.tokenAccountB,b?o.tokenAccountB:o.tokenAccountA,b?d:p,b?p:d,b?f:y,b?y:f,s,n,r,a,u,!0,Ze(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 W.PublicKey(e.programId),new W.PublicKey(e.id)],[d,p]=[new W.PublicKey(t.vault.A),new W.PublicKey(t.vault.B)],[f,y]=[new W.PublicKey(e.mintA.address),new W.PublicKey(e.mintB.address)],b=e.mintB.address.toString()===i.toBase58(),g=[this.swapV2Instruction(c,o.wallet,l,new W.PublicKey(e.config.id),b?o.tokenAccountA:o.tokenAccountB,b?o.tokenAccountB:o.tokenAccountA,b?d:p,b?p:d,b?f:y,b?y:f,s,n,r,a,u,!1,Ze(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 W.PublicKey(e.programId),new W.PublicKey(e.id)],a=Fc(i,r,o.mint).publicKey,u=xi(i).publicKey,s=[this.initializeRewardInstruction(i,n.wallet,r,u,new W.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 W.PublicKey(e.programId),new W.PublicKey(e.id)],a,u,s;for(let d=0;d<e.rewardDefaultInfos.length;d++)e.rewardDefaultInfos[d].mint.address===o.mint.toString()&&(a=d,u=new W.PublicKey(t.rewardInfos[d].vault),s=new W.PublicKey(t.rewardInfos[d].mint.address));(a===void 0||u===void 0)&&Gc.logWithError("reward mint check error","no reward mint",e.rewardDefaultInfos);let c=xi(i).publicKey,l=[this.setRewardParamsInstruction(i,n.wallet,r,c,new W.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 W.PublicKey(e.programId),new W.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 W.PublicKey(t.rewardInfos[c].vault));(a===void 0||u===void 0)&&Gc.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 W.PublicKey((await u(1))[0]);else{let g=W.Keypair.generate();s.push(g),c=g.publicKey}let l=a?ne(i,r,de.TOKEN_2022_PROGRAM_ID).publicKey:ne(i,r,de.TOKEN_PROGRAM_ID).publicKey,{publicKey:d}=rn(n,r),p=Eo(e,c).publicKey,f=ne(i,c,de.TOKEN_PROGRAM_ID).publicKey,y=_n(c).publicKey,b=we.lockPositionInstructionV2({programId:e,auth:t,payer:o,positionOwner:i,lockOwner:i,positionNftAccount:l,positionId:d,lockPositionId:p,lockNftMint:c,lockNftAccount:f,metadataAccount:y,withMetadata:!0,nft2022:a,positionNftMint:r,authPositionNftAccount:ne(t,r,a?de.TOKEN_2022_PROGRAM_ID:de.TOKEN_PROGRAM_ID).publicKey,positionNftProgram:a?de.TOKEN_2022_PROGRAM_ID:de.TOKEN_PROGRAM_ID});return{address:{positionId:d,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:d,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:d,isSigner:!0,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:In,isSigner:!1,isWritable:!1},{pubkey:de.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:_t,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:W.SystemProgram.programId,isSigner:!1,isWritable:!1}],g=v([it("withMetadata")]),A=Buffer.alloc(g.span);g.encode({withMetadata:y},A);let k=Buffer.from([...zc,...A]);return new W.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,de.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:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:W.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new W.TransactionInstruction({keys:u,programId:e,data:Buffer.from(zc)})}static harvestLockPositionInstruction(e){let[t,n]=[new W.PublicKey(e.poolKeys.programId),new W.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,de.TOKEN_PROGRAM_ID),{publicKey:s}=rn(t,e.ownerPosition.nftMint),{publicKey:c}=Pn(t,n,e.ownerPosition.tickLower,e.ownerPosition.tickUpper),l=[];for(let f=0;f<e.poolKeys.rewardInfos.length;f++)l.push({poolRewardVault:new W.PublicKey(e.poolKeys.rewardInfos[f].vault),ownerRewardVault:e.ownerRewardAccounts[f],rewardMint:new W.PublicKey(e.poolKeys.rewardInfos[f].mint.address)});let d=[...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 W.PublicKey(e.poolKeys.vault.A),isSigner:!1,isWritable:!0},{pubkey:new W.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:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:fn,isSigner:!1,isWritable:!1},{pubkey:new W.PublicKey(e.poolKeys.mintA.address),isSigner:!1,isWritable:!1},{pubkey:new W.PublicKey(e.poolKeys.mintB.address),isSigner:!1,isWritable:!1},...d];return new W.TransactionInstruction({keys:p,programId:e.programId,data:Buffer.from(Xc)})}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:d,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:d,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:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:fn,isSigner:!1,isWritable:!1},{pubkey:A,isSigner:!1,isWritable:!1},{pubkey:k,isSigner:!1,isWritable:!1},...T];return new W.TransactionInstruction({keys:I,programId:e,data:Buffer.from(Xc)})}};var Ni=class extends rt{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,d=this.createTxBuilder(l),[p,f,y]=new lt.default(new G.PublicKey(o.address).toBuffer()).gt(new lt.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 d.addInstruction(h),d.addCustomComputeBudget(u),d.addTipInstruction(c),d.versionBuild({txVersion:s,extInfo:{address:_(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 B;let{programId:t,owner:n=((B=this.scope.owner)==null?void 0:B.publicKey)||G.PublicKey.default,mint1:o,mint2:i,initialPrice:r,ammConfig:a,collectFeeOnMint:u,dynamicFeeConfig:s,computeBudgetConfig:c,txVersion:l,txTipConfig:d,feePayer:p,addSupportMintExt:f}=e;if(e.collectFeeOn!==void 0)throw Error("SDK no longer supports this parameter, please use collectFeeOnMint");let y=this.createTxBuilder(p),[b,g,A]=new lt.default(new G.PublicKey(o.address).toBuffer()).gt(new lt.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((L,O)=>{L&&h.push(P[O])}));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;u===void 0?x=0:u.equals(T.mintA)?x=1:u.equals(T.mintB)?x=2:this.logAndCreateError("param collectFeeOnMint find error");let S=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,x,[...h,...I.map(R=>R.pubkey)],s);return y.addInstruction({instructions:[S]}),y.addCustomComputeBudget(c),y.addTipInstruction(d),y.versionBuild({txVersion:l,extInfo:{address:_(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:x,feeOn:x===0?"Both":x===1?"TokenA":"TokenB",hasDynamicFee:!!s,tips:[],launchMigratePool:!1},hr)}})}async createPermissionedPool(e){var L;let{programId:t,owner:n=((L=this.scope.owner)==null?void 0:L.publicKey)||G.PublicKey.default,mint1:o,mint2:i,initialPrice:r,ammConfig:a,collectFeeOnMint:u,dynamicFeeConfig:s,computeBudgetConfig:c,txVersion:l,txTipConfig:d,feePayer:p,addSupportMintExt:f}=e;if(e.collectFeeOn!==void 0)throw Error("SDK no longer supports this parameter, please use collectFeeOnMint");let y=this.createTxBuilder(p),[b,g,A]=new lt.default(new G.PublicKey(o.address).toBuffer()).gt(new lt.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((C,M)=>{C&&h.push(P[M])}));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;u===void 0?B=0:u.equals(x.mintA)?B=1:u.equals(x.mintB)?B=2:this.logAndCreateError("param collectFeeOnMint find error");let R=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,B,I,[...h,...S.map(O=>O.pubkey)],s);return y.addInstruction({instructions:[R]}),y.addCustomComputeBudget(c),y.addTipInstruction(d),y.versionBuild({txVersion:l,extInfo:{address:_(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:B,feeOn:B===0?"Both":B===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 lt.default(0),nft2022:c,associatedOnly:l=!0,checkCreateATAOwner:d=!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===$.toString(),I=n.useSOLBalance&&e.mintB.address===$.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:d});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:d});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()),M=await we.openPositionFromBaseInstructions({poolInfo:e,poolKeys:C,ownerInfo:_(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(M),k.addCustomComputeBudget(y),k.addTipInstruction(b),k.versionBuild({txVersion:g,extInfo:N({},M.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:d="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===$.toBase58(),I=n.useSOLBalance&&e.mintB.address===$.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:d,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:d,txVersion:p,feePayer:f}=e,y=this.createTxBuilder(f),b,g,A=u.useSOLBalance&&t.mintA.address===$.toString(),k=u.useSOLBalance&&t.mintB.address===$.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(d),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:d,feePayer:p}=e,f=this.createTxBuilder(p),y,b,g=a.useSOLBalance&&t.mintA.address===$.toString(),A=a.useSOLBalance&&t.mintB.address===$.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:d,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:d,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===$.toString(),g=i.useSOLBalance&&t.mintB.address===$.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 M=i.useSOLBalance&&C.mint.address===$.toString(),D;if(C.mint.address===t.mintA.address)D=A;else if(C.mint.address===t.mintB.address)D=k;else{let{account:E,instructionParams:z}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new G.PublicKey(C.mint.programId),mint:new G.PublicKey(C.mint.address),notUseTokenAccount:M,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!M,associatedOnly:M?!1:s,checkCreateATAOwner:c});D=E,z&&y.addInstruction(z)}S.push(D)}!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(d),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,d=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 d.addInstruction(p),d.addCustomComputeBudget(a),d.addTipInstruction(u),d.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:d,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=Br.decode(b.data),A=a.useSOLBalance&&f.mintA.address===$.toString(),k=a.useSOLBalance&&f.mintB.address===$.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===$.toString(),Z=B[J.mint.address];if(!Z){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});Z=ge,re&&y.addInstruction(re)}B[J.mint.address]=Z,R.push(Z)}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),M=Te.getTickArrayStartIndex(g.tickUpper,f.config.tickSpacing),{publicKey:D}=Ee(new G.PublicKey(f.programId),r.poolId,C),{publicKey:E}=Ee(new G.PublicKey(f.programId),r.poolId,M),{publicKey:z}=Pn(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,Z=B[ie];Z&&H.push({poolRewardVault:new G.PublicKey(f.rewardInfos[J].vault),ownerRewardVault:Z,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:D,tickArrayUpper:E,userVaultA:h,userVaultB:P,mintA:new G.PublicKey(f.mintA.address),mintB:new G.PublicKey(f.mintB.address),rewardAccounts:H,exTickArrayBitmap:Ze(o,r.poolId).publicKey});return y.addInstruction({instructions:[Y],instructionTypes:[X.ClmmHarvestLockPosition]}),y.addCustomComputeBudget(c),y.addTipInstruction(l),y.versionBuild({txVersion:d})}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()===$.toString(),l=n.perSecond.mul(n.endTime-n.openTime),{account:d,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 lt.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),d||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:d},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),d={};for(let p of o){let f=n.useSOLBalance&&p.mint.address===$.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 lt.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)}});d=N(N({},d),k.address),l.addInstruction(k)}return l.addCustomComputeBudget(a),l.addTipInstruction(u),l.versionBuild({txVersion:s,extInfo:{address:d}})}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($),{account:d,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 lt.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),d||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:d},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),d={};for(let p of o){p.endTime<=p.openTime&&this.logAndCreateError("reward time error","rewardInfo",p);let f=n.useSOLBalance&&p.mint.address===$.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 lt.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),d=N(N({},d),A.address)}return l.addCustomComputeBudget(a),l.addTipInstruction(u),l.versionBuild({txVersion:s,extInfo:{address:d}})}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),d=t.useSOLBalance&&n.equals($),{account:p,instructionParams:f}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new G.PublicKey(c.mint.programId),mint:n,notUseTokenAccount:d,owner:this.scope.ownerPubKey,skipCloseAccount:!d,createInfo:{payer:t.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:d?!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 d=e.rewardDefaultInfos.find(A=>A.mint.address===l.toString());if(!d){this.logAndCreateError("reward mint error","not found reward mint",l);continue}let p=t.useSOLBalance&&l.equals($),{account:f,instructionParams:y}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new G.PublicKey(d.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:d}){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($),h=b.equals($),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:0},associatedOnly:!T});S=z,H&&I.addInstruction(H)}let B=_c(f,this.scope.ownerPubKey,i).publicKey,R=await this.scope.connection.getAccountInfo(B),L=R?Ic.decode(R.data).orderNonce:new lt.default(0),O=vc(f,s||this.scope.ownerPubKey,B,L).publicKey,C=Te.getTickArrayStartIndex(n,e.config.tickSpacing),M=Ee(f,p,C).publicKey,D=on(f,p,new G.PublicKey(e[t?"mintA":"mintB"].address)).publicKey,E=on(f,p,new G.PublicKey(e[t?"mintB":"mintA"].address)).publicKey;return I.addInstruction({instructions:[we.openLimitOrderInstruction(f,s||this.scope.ownerPubKey,p,M,B,O,x,S,D,E,y,b,g,i,t,n,o,r)]}),I.addCustomComputeBudget(c),I.addTipInstruction(l),I.versionBuild({txVersion:d,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),d=await this.scope.connection.getAccountInfo(t);d||this.logAndCreateError(`limit order ${t.toBase58()} not exist`);let p=yo.decode(d.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($),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:d,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=jn.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($),h.equals($)],[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,M]=[on(y,f,k).publicKey,on(y,f,h).publicKey],D=Te.getTickArrayStartIndex(b.tick,e.config.tickSpacing),E=Ee(y,f,D).publicKey;return R.addInstruction({instructions:[we.decreaseLimitOrderInstruction(y,s||this.scope.ownerPubKey,f,E,t,L,O,C,M,k,h,o,g,r)]}),R.addCustomComputeBudget(c),R.addTipInstruction(l),R.versionBuild({txVersion:d,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),d=jn.getUnFilledAmount({orderInfo:l});!n&&!d.isZero()&&this.logAndCreateError(`unfulfilled amount should be 0, (${d.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=jn.settleFilledOrder({orderInfo:l,tickInfo:y.ticks.find(g=>g.tick===l.tick)});if(d.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:d,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?_(N({},yo.decode(A.data)),{pda:t[k]}):null),l=c.filter(Boolean),d=l.map(A=>A.poolId.toBase58()),p=(await this.scope.api.fetchPoolById({ids:d.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=jn.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=jn.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 d=c.zeroForOne?l.mintB:l.mintA,[p,f]=[new G.PublicKey(d.address),new G.PublicKey(d.programId)],y=new G.PublicKey(l.programId),b=this.createTxBuilder(),g=p.equals($),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()),_(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(),d={};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($),A=n.useSOLBalance&&g,k=new G.PublicKey(g?We.TOKEN_PROGRAM_ID:(await this.scope.token.getTokenInfo(b)).programId),h=d[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)}d[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:d,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()===$.toBase58(),k=u.useSOLBalance&&e.mintB.address.toString()===$.toBase58(),h;!r||r.equals(new Kn.default(0))?h=g?Kt.add(new lt.default(1)):Ct.sub(new lt.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:_(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:j,remainingAccounts:s})),b.addCustomComputeBudget(p),b.addTipInstruction(f),b.versionBuild({txVersion:d})}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:d,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()===$.toBase58(),k=u.useSOLBalance&&e.mintB.address.toString()===$.toBase58(),h;!r||r.equals(new Kn.default(0))?h=g?Kt.add(new lt.default(1)):Ct.sub(new lt.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:_(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:j,remainingAccounts:s})),b.addCustomComputeBudget(p),b.addTipInstruction(f),b.versionBuild({txVersion:d})}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:d=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(M=>!M.rewardAmountOwed.isZero())))continue;let T=P,I=o.useSOLBalance&&T.mintA.address===$.toString(),x=o.useSOLBalance&&T.mintB.address===$.toString(),S=f[T.mintA.address];if(!S)if(I){let{account:C,instructionParams:M}=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,M&&A.addInstruction(M)}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:M}=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,M&&A.addInstruction(M)}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 M=o.useSOLBalance&&C.mint.address===$.toString(),D=f[C.mint.address];if(!D){let{account:E,instructionParams:z}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new G.PublicKey(C.mint.programId),mint:new G.PublicKey(C.mint.address),notUseTokenAccount:M,owner:this.scope.ownerPubKey,skipCloseAccount:!M,createInfo:{payer:o.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:M?!1:i});D=E,z&&A.addInstruction(z)}f[C.mint.address]=D,R.push(D)}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 M=(k=n==null?void 0:n[P.id])==null?void 0:k[C.nftMint.toBase58()];if(M){let D=ne(this.scope.ownerPubKey,M.lockNftMint,We.TOKEN_PROGRAM_ID).publicKey,E=Te.getTickArrayStartIndex(C.tickLower,L.config.tickSpacing),z=Te.getTickArrayStartIndex(C.tickUpper,L.config.tickSpacing),{publicKey:H}=Ee(new G.PublicKey(L.programId),M.poolId,E),{publicKey:Y}=Ee(new G.PublicKey(L.programId),M.poolId,z),{publicKey:J}=Pn(new G.PublicKey(L.programId),M.poolId,C.tickLower,C.tickUpper),ie=Eo(l,M.lockNftMint).publicKey,Z=we.harvestLockPositionInstructionV2({programId:l,auth:d,lockPositionId:ie,clmmProgram:p,lockOwner:this.scope.ownerPubKey,lockNftMint:M.lockNftMint,lockNftAccount:D,positionNftAccount:M.nftAccount,positionId:M.positionId,poolId:M.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:Ze(p,M.poolId).publicKey});A.addInstruction({instructions:[Z],instructionTypes:[X.ClmmHarvestLockPosition],lookupTableAddress:L.lookupTableAccount?[L.lookupTableAccount]:[]})}else{let D=we.decreaseLiquidityInstructions({poolInfo:T,poolKeys:L,ownerPosition:C,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:S,tokenAccountB:B,rewardAccounts:R},liquidity:new lt.default(0),amountMinA:new lt.default(0),amountMinB:new lt.default(0),nft2022:(h=g[C.nftMint.toBase58()])==null?void 0:h.equals(We.TOKEN_2022_PROGRAM_ID)});A.addInstruction(D)}}}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?Bc.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 lt.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=Br.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 lt.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=xc.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=Br.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])]=_(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()]=Qa.decode(u.accountInfo.data))});let r=await Pt.fetchComputeMultipleClmmInfo({connection:this.scope.connection,rpcDataMap:e,poolList:Object.keys(e).map(u=>{var l,d,p,f;let[s,c]=[e[u].mintA.toBase58(),e[u].mintB.toBase58()];return{id:u,programId:e[u].programId.toBase58(),mintA:kt({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((d=t[s])==null?void 0:d.feeConfig):void 0}}),mintB:kt({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:_(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=Uc(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=_(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:kt({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=Qa.decode(i.data),a=new G.PublicKey(n.programId),u=new G.PublicKey(e),s=await Wc(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 Hc=v([Be(8),V("bump"),it("disableCreatePool"),ze("index"),w("tradeFeeRate"),w("protocolFeeRate"),w("fundFeeRate"),w("createPoolFee"),F("protocolOwner"),F("fundOwner"),w("creatorFeeRate"),w("creatorFeeShareRate"),Q(w(),14)]),Rr=v([Be(8),F("configId"),F("poolCreator"),F("vaultA"),F("vaultB"),F("mintLp"),F("mintA"),F("mintB"),F("mintProgramA"),F("mintProgramB"),F("observationId"),V("bump"),V("status"),V("lpDecimals"),V("mintDecimalA"),V("mintDecimalB"),w("lpAmount"),w("protocolFeesMintA"),w("protocolFeesMintB"),w("fundFeesMintA"),w("fundFeesMintB"),w("openTime"),w("epoch"),V("feeOn"),it("enableCreatorFee"),Q(V(),6),w("creatorFeesMintA"),w("creatorFeesMintB"),Q(w(),28)]),xA=v([Be(8),F("configId"),Q(w(),30)]),SA=v([Be(8),V("bump"),F("creator"),F("ammConfig"),w("shareRate"),Q(w(),8)]);var nt=require("@solana/web3.js"),At=require("@solana/spl-token");var $m=Buffer.from("vault_and_lp_mint_auth_seed","utf8"),LA=Buffer.from("amm_config","utf8"),jm=Buffer.from("pool","utf8"),Jm=Buffer.from("pool_lp_mint","utf8"),ed=Buffer.from("pool_vault","utf8"),td=Buffer.from("observation","utf8"),nd=Buffer.from("permission","utf8"),od=Buffer.from("support_mint","utf8"),id=Buffer.from("creator_fee_share","utf8");function wo(m){return le([$m],m)}function is(m,e,t,n){return le([jm,e.toBuffer(),t.toBuffer(),n.toBuffer()],m)}function rd(m,e){return le([Jm,e.toBuffer()],m)}function Qc(m,e,t){return le([ed,e.toBuffer(),t.toBuffer()],m)}function ko(m,e){return le([td,e.toBuffer()],m)}function rs({poolId:m,programId:e,configId:t,mintA:n,mintB:o}){let i=wo(e).publicKey,r=m||is(e,t,n,o).publicKey,a=rd(e,r).publicKey,u=Qc(e,r,n).publicKey,s=Qc(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 ad=Buffer.from("locked_liquidity","utf8");function Wo(m,e){return le([ad,e.toBuffer()],m)}function Zc(m,e){return le([nd,e.toBuffer()],m)}function as(m,e){return le([od,e.toBuffer()],m)}function ss(m,e,t){return le([id,e.toBuffer(),t.toBuffer()],m)}var sd=xe("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 $c(m,e,t,n,o,i,r,a,u,s,c,l,d,p,f,y,b,g,A,k,h){let P=v([w("amountMaxA"),w("amountMaxB"),w("openTime")]),T=is(m,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:d,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:_t,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 nt.TransactionInstruction({keys:I,programId:m,data:Buffer.from([...Cn.initialize,...x])})}function jc(m,e,t,n,o,i,r,a,u,s,c,l,d,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 sd.debug("cpmm deposit data",{lpAmount:d.toString(),amountMaxA:p.toString(),amountMaxB:f.toString()}),y.encode({lpAmount:d,amountMaxA:p,amountMaxB:f},g),new nt.TransactionInstruction({keys:b,programId:m,data:Buffer.from([...Cn.deposit,...g])})}function Jc(m,e,t,n,o,i,r,a,u,s,c,l,d,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:fn,isSigner:!1,isWritable:!1}],g=Buffer.alloc(y.span);return y.encode({lpAmount:d,amountMinA:p,amountMinB:f},g),new nt.TransactionInstruction({keys:b,programId:m,data:Buffer.from([...Cn.withdraw,...g])})}function qo(m,e,t,n,o,i,r,a,u,s,c,l,d,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:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!0}],A=Buffer.alloc(b.span);return b.encode({amountIn:f,amounOutMin:y},A),new nt.TransactionInstruction({keys:g,programId:m,data:Buffer.from([...Cn.swapBaseInput,...A])})}function el(m,e,t,n,o,i,r,a,u,s,c,l,d,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:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!0}],A=Buffer.alloc(b.span);return b.encode({amountInMax:f,amountOut:y},A),new nt.TransactionInstruction({keys:g,programId:m,data:Buffer.from([...Cn.swapBaseOutput,...A])})}async function tl(m){var b;let{ownerInfo:e,poolInfo:t,poolKeys:n,feeNftOwner:o,getEphemeralSigners:i}=m,r=[],[a,u]=[new nt.PublicKey(t.id),new nt.PublicKey(t.lpMint.address)],s;if(i)s=new nt.PublicKey((await i(1))[0]);else{let g=nt.Keypair.generate();r.push(g),s=g.publicKey}let{publicKey:c}=ne(o,s,At.TOKEN_PROGRAM_ID),{publicKey:l}=_n(s),{publicKey:d}=Wo(m.lockProgram,s),{publicKey:p}=ne(e.wallet,u,At.TOKEN_PROGRAM_ID),{publicKey:f}=ne(m.lockAuthProgram,u,At.TOKEN_PROGRAM_ID),y=ud({programId:m.lockProgram,auth:m.lockAuthProgram,payer:e.feePayer,liquidityOwner:e.wallet,nftOwner:o,nftMint:s,nftAccount:c,poolId:a,lockPda:d,mintLp:u,userLpVault:p,lockLpVault:f,poolVaultA:new nt.PublicKey(n.vault.A),poolVaultB:new nt.PublicKey(n.vault.B),metadataAccount:l,lpAmount:m.lpAmount,withMetadata:(b=m.withMetadata)!=null?b:!0});return{address:{nftMint:s,nftAccount:c,metadataAccount:l,lockPda:d,userLpVault:p,lockLpVault:f},instructions:[y],signers:r,instructionTypes:[X.CpmmLockLp],lookupTableAddress:[]}}function ud({programId:m,auth:e,payer:t,liquidityOwner:n,nftOwner:o,nftMint:i,nftAccount:r,poolId:a,lockPda:u,mintLp:s,userLpVault:c,lockLpVault:l,poolVaultA:d,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:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:_t,isSigner:!1,isWritable:!1},{pubkey:nt.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:In,isSigner:!1,isWritable:!1}],A=v([w("lpAmount"),it("withMetadata")]),k=Buffer.alloc(A.span);A.encode({lpAmount:y,withMetadata:b},k);let h=Buffer.from([...Cn.lockCpLiquidity,...k]);return new nt.TransactionInstruction({keys:g,programId:m,data:h})}function us({programId:m,nftOwner:e,auth:t,nftAccount:n,lockPda:o,poolId:i,mintLp:r,userVaultA:a,userVaultB:u,poolVaultA:s,poolVaultB:c,mintA:l,mintB:d,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:Uu,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:d,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:fn,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 nt.TransactionInstruction({keys:g,programId:m,data:h})}function cs(m,e,t,n,o,i,r,a,u,s,c,l,d){let p=ss(m,e,o).publicKey,f=[{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:d,isSigner:!1,isWritable:!1},{pubkey:At.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:nt.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1}];return new nt.TransactionInstruction({keys:f,programId:m,data:Cn.collectCreatorFee})}function nl(m,e,t,n,o,i,r,a,u,s,c,l,d,p){let f=ss(m,t,i).publicKey,y=[{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:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:At.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:nt.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1}];return new nt.TransactionInstruction({keys:y,programId:m,data:Cn.collectCreatorFeePermissionless})}function ol(m,e,t,n,o,i,r,a,u,s,c,l,d,p,f,y,b,g,A,k,h,P,T,I){let x=v([w("amountA"),w("amountB"),w("openTime"),V("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:d,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:nt.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 nt.TransactionInstruction({keys:S,programId:m,data:Buffer.from([...Cn.initializeWithPermission,...B])})}var ms=te(require("bn.js"));var Fi=te(require("bn.js"));function ls(m,e){if(e.isZero())throw Error("divisor is zero");return m.mod(e)}function cd(m,e){if(e.isZero())throw Error("rhs is zero");let t=m.div(e);return ls(m,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]=cd(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 ls(e.mul(n),t).gt(Mi)&&r.gt(Mi)&&(r=r.add(new Fi.default(1))),ls(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 rl=te(require("bn.js"));var il=te(require("bn.js")),tt=new il.default(1e6);var $t=class{static tradingFee(e,t){return _i(e,t,tt)}static protocolFee(e,t){return Lr(e,t,tt)}static fundFee(e,t){return Lr(e,t,tt)}static creatorFee(e,t){return _i(e,t,tt)}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(tt),o=tt.sub(t);return n.add(o).sub(new rl.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 ms.default(0),c=$t.tradingFee(e,o),l;u?(s=$t.creatorFee(e,i),l=e.sub(c).sub(s)):l=e.sub(c);let d=$t.protocolFee(c,r),p=$t.protocolFee(c,a),f=vi.swapBaseInputWithoutFees(l,t,n),y;return u?y=f:(s=$t.creatorFee(f,i),y=f.sub(s)),{newInputVaultAmount:t.add(l),newOutputVaultAmount:n.sub(f),inputAmount:e,outputAmount:y,tradeFee:c,protocolFee:d,fundFee:p,creatorFee:s}}static swapBaseOutput(e,t,n,o,i,r,a,u){let s,c=new ms.default(0),l;if(u)l=e;else{let b=$t.calculatePreFeeAmount(e,i);c=b.sub(e),l=b}let d=vi.swapBaseOutputWithoutFees(l,t,n),p;if(u){let b=$t.calculatePreFeeAmount(d,o.add(i)),g=b.sub(d);c=$t.splitCreatorFee(g,o,i),s=g.sub(c),p=b}else{let b=$t.calculatePreFeeAmount(d,o);s=b.sub(d),p=b}let f=$t.protocolFee(s,r),y=$t.fundFee(s,a);return{newInputVaultAmount:t.add(d),newOutputVaultAmount:n.sub(l),inputAmount:p,outputAmount:e,tradeFee:s,protocolFee:f,fundFee:y,creatorFee:c}}};var ds=te(require("bn.js")),ps=new ds.default(25),Or=new ds.default(1e4);var al=new Set(["5Q544fKrFoe6tsEbD7S8EmxGTJYAKtTVhAW5Q5pge4j1","3uaZBfHPfmpAHW7dsimC1SnyR61X4bJqQZKWmRSCXJxv","GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"]);var fs=v([V("instruction"),w("amountIn"),w("minAmountOut")]),ys=v([V("instruction"),w("maxAmountIn"),w("amountOut")]),mw=v([V("instruction"),V("nonce")]),ld=v([V("instruction"),V("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"),ce("swapBaseInAmount"),ce("swapQuoteOutAmount"),w("swapBase2QuoteFee"),ce("swapQuoteInAmount"),ce("swapBaseOutAmount"),w("swapQuote2BaseFee"),F("baseVault"),F("quoteVault"),F("baseMint"),F("quoteMint"),F("lpMint"),F("openOrders"),F("marketId"),F("marketProgramId"),F("targetOrders"),F("withdrawQueue"),F("lpVault"),F("owner"),w("lpReserve"),Q(w(),3,"padding")]),dw=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"),ce("swapBaseInAmount"),ce("swapQuoteOutAmount"),ce("swapQuoteInAmount"),ce("swapBaseOutAmount"),w("swapQuote2BaseFee"),w("swapBase2QuoteFee"),F("baseVault"),F("quoteVault"),F("baseMint"),F("quoteMint"),F("lpMint"),F("modelDataAccount"),F("openOrders"),F("marketId"),F("marketProgramId"),F("targetOrders"),F("owner"),Q(w(),64,"padding")]),bs=v([V("instruction"),w("baseAmountIn"),w("quoteAmountIn"),w("fixedSide"),w("otherAmountMin")]),gs=v([V("instruction"),w("lpAmount"),w("baseAmountMin"),w("quoteAmountMin")]);var sl=v([w("fee")]);var ll=require("@solana/web3.js"),Ei=te(require("decimal.js")),ml=require("@solana/spl-token");var ul=require("@solana/web3.js");var md=xe("Raydium_liquidity_serum");function cl({programId:m,marketId:e}){let t=[e.toBuffer()],n=0,o;for(;n<100;){try{let i=t.concat(Buffer.from([n]),Buffer.alloc(7));o=ul.PublicKey.createProgramAddressSync(i,m)}catch(i){if(i instanceof TypeError)throw i;n++;continue}return{publicKey:o,nonce:n}}throw md.logWithError("unable to find a viable program address nonce","params",{programId:m,marketId:e}),new Error("unable to find a viable program address nonce")}function Mr({programId:m}){let{publicKey:e}=le([Buffer.from("amm_config_account_seed","utf-8")],m);return e}function To({name:m,programId:e,marketId:t}){let{publicKey:n}=le([e.toBuffer(),t.toBuffer(),Buffer.from(m,"utf-8")],e);return n}function dd({programId:m,marketId:e}){let{publicKey:t}=le([m.toBuffer(),e.toBuffer(),Buffer.from("open_order_associated_seed","utf-8")],m);return t}function As({programId:m}){return le([Buffer.from([97,109,109,32,97,117,116,104,111,114,105,116,121])],m)}function ws({version:m,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:d}=As({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=dd({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}=cl({programId:u,marketId:t});return{id:s,baseMint:n,quoteMint:o,lpMint:c,baseDecimals:i,quoteDecimals:r,lpDecimals:i,version:m,programId:a,authority:l,nonce:d,baseVault:p,quoteVault:f,lpVault:y,openOrders:b,targetOrders:g,withdrawQueue:A,marketVersion:e,marketProgramId:u,marketId:t,marketAuthority:k,lookupTableAccount:ll.PublicKey.default,configId:Mr({programId:a})}}var Ps={volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[]},Fr=m=>{let e={},t=ml.TOKEN_PROGRAM_ID.toBase58();return Object.keys(m).map(n=>{let o=m[n],[i,r]=[o.baseMint.toBase58(),o.quoteMint.toBase58()];e[n]={id:n,version:4,status:o.status.toNumber(),programId:o.programId.toBase58(),mintA:kt({address:i,programId:t,decimals:o.baseDecimal.toNumber()}),mintB:kt({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:Ps,week:Ps,month:Ps,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:kt({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"),Ne=require("@solana/web3.js");var Di=te(require("bn.js"));var vr=xe("Raydium_liquidity_instruction");function dl(m){let{poolInfo:e,poolKeys:t,userKeys:n,baseAmountIn:o,quoteAmountIn:i,fixedSide:r,otherAmountMin:a,modelDataPubKey:u=lo}=m,s=Buffer.alloc(bs.span);bs.encode({instruction:3,baseAmountIn:ye(o),quoteAmountIn:ye(i),otherAmountMin:ye(a),fixedSide:r==="base"?j:dt},s);let c=[K({pubkey:Rn.TOKEN_PROGRAM_ID,isWritable:!1}),K({pubkey:new Ne.PublicKey(e.id)}),K({pubkey:new Ne.PublicKey(t.authority),isWritable:!1}),K({pubkey:new Ne.PublicKey(t.openOrders),isWritable:!1}),K({pubkey:new Ne.PublicKey(t.targetOrders)}),K({pubkey:new Ne.PublicKey(e.lpMint.address)}),K({pubkey:new Ne.PublicKey(t.vault.A)}),K({pubkey:new Ne.PublicKey(t.vault.B)})];return e.pooltype.includes("StablePool")&&c.push(K({pubkey:u})),c.push(K({pubkey:new Ne.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 Ne.PublicKey(t.marketEventQueue),isWritable:!1})),new Ne.TransactionInstruction({programId:new Ne.PublicKey(e.programId),keys:c,data:s})}function ks(m){let{poolInfo:e,poolKeys:t,userKeys:n,lpAmount:o,baseAmountMin:i,quoteAmountMin:r,modelDataPubKey:a=lo}=m,u=Ut(t),s=4;if(e.pooltype.includes("StablePool")&&(s=5),s===4||s===5){let c=Buffer.alloc(gs.span);gs.encode({instruction:4,lpAmount:ye(o),baseAmountMin:ye(i),quoteAmountMin:ye(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 Ne.TransactionInstruction({programId:u.programId,keys:l,data:c})}return new Ne.TransactionInstruction({programId:u.programId,keys:[]})}function Ts({programId:m,ammId:e,ammAuthority:t,ammOpenOrders:n,lpMint:o,coinMint:i,pcMint:r,coinVault:a,pcVault:u,withdrawQueue:s,ammTargetOrders:c,poolTempLp:l,marketProgramId:d,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([V("instruction"),V("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:Ne.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:_t,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:d,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 Ne.TransactionInstruction({keys:S,programId:m,data:B}),instructionType:X.AmmV4CreatePool}}function pd({poolKeys:m,userKeys:e,amountIn:t,minAmountOut:n,modelDataPubKey:o=lo},i){let r=Ut(m),a=Buffer.alloc(fs.span);fs.encode({instruction:9,amountIn:ye(t),minAmountOut:ye(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 Ne.TransactionInstruction({programId:r.programId,keys:u,data:a})}function fd({poolKeys:m,userKeys:e,maxAmountIn:t,amountOut:n,modelDataPubKey:o=lo},i){let r=Ut(m),a=Buffer.alloc(ys.span);ys.encode({instruction:11,maxAmountIn:ye(t),amountOut:ye(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 Ne.TransactionInstruction({programId:r.programId,keys:u,data:a})}function yd(m,e,t,n,o,i,r,a,u,s){let c=v([V("instructionId"),w("amountIn"),w("minAmountOut")]),l=Buffer.alloc(c.span);c.encode({instructionId:16,amountIn:u,minAmountOut:s},l);let d=[{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 Ne.TransactionInstruction({programId:m,keys:d,data:l})}function bd(m,e,t,n,o,i,r,a,u,s){let c=v([V("instructionId"),w("maxAmountIn"),w("amountOut")]),l=Buffer.alloc(c.span);c.encode({instructionId:17,maxAmountIn:u,amountOut:s},l);let d=[{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 Ne.TransactionInstruction({programId:m,keys:d,data:l})}function _r(m){let{poolKeys:e,version:t,userKeys:n,amountIn:o,amountOut:i,fixedSide:r}=m;if(t===4){if(r==="in")return yd(new Ne.PublicKey(e.programId),new Ne.PublicKey(e.id),new Ne.PublicKey(e.authority),new Ne.PublicKey(e.vault.A),new Ne.PublicKey(e.vault.B),n.tokenAccountIn,n.tokenAccountOut,n.owner,new Di.default(o.toString()),new Di.default(i.toString()));if(r==="out")return bd(new Ne.PublicKey(e.programId),new Ne.PublicKey(e.id),new Ne.PublicKey(e.authority),new Ne.PublicKey(e.vault.A),new Ne.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",m)}throw vr.logWithError("invalid version, only support pool v4","poolKeys.version",t),new Error("invalid version")}function Vr(m){let{poolKeys:e,version:t,userKeys:n,amountIn:o,amountOut:i,fixedSide:r}=m;if(t===4||t===5){let a={poolKeys:e,userKeys:n};if(r==="in")return pd(_(N({},a),{amountIn:o,minAmountOut:i}),t);if(r==="out")return fd(_(N({},a),{maxAmountIn:o,amountOut:i}),t);vr.logWithError("invalid params","params",m)}throw vr.logWithError("invalid version","poolKeys.version",t),new Error("invalid version")}var Bo=5e4,gd=v([w("x"),w("y"),w("price")]),Pd=v([w("accountType"),w("status"),w("multiplier"),w("validDataCount"),Q(gd,Bo,"DataElement")]);function Ad(m,e){return[0,Bo-2]}function wd(m){return[0,Bo-2]}function kd(m){return[0,Bo-2]}function Td(m,e,t){let[n,o]=Ad(e,t),i=n,r=o,a=0,u=e*m.multiplier/t;for(;i<=r;){if(a=Math.floor((r+i)/2),a===0||a>=Bo-2)return[a,a,!1];let s=m.DataElement[a].x*m.multiplier/m.DataElement[a].y,c=m.DataElement[a-1].x*m.multiplier/m.DataElement[a-1].y,l=m.DataElement[a+1].x*m.multiplier/m.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 hs(m,e,t){let[n,o,i]=Td(m,e,t);if(!i)return 0;if(n===o){let r=m.DataElement[n].x;return e*m.multiplier/r}else{let r=m.DataElement[n].x,a=m.DataElement[n].y,u=m.DataElement[o].x,s=m.DataElement[o].y,c=t*(u*a-r*s),l=r*c,d=(u-r)*(e*a-r*t)*s,p=l+d;return e*m.multiplier*c/p}}function ho(m,e,t){return e*m.multiplier/t}function pl(m,e,t){return e*t/m.multiplier}function hd(m,e){let[t,n]=wd(e),o=t,i=n,r=0,a=e;for(;o<i;){if(r=Math.floor((i+o)/2),r<=0||r>Bo-2)return[r,r,!1];let u=m.DataElement[r].x,s=m.DataElement[r-1].x,c=m.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 Bd(m,e){let[t,n]=kd(e),o=t,i=n,r=0,a=e;for(;o<=i;){if(r=Math.floor((i+o)/2),r<=0||r>=Bo-2)return[r,r,!1];let u=m.DataElement[r].y,s=m.DataElement[r-1].y,c=m.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 fl(m,e,t,n){let o=n?e+t:e-t,[i,r,a]=hd(m,o);if(!a)return[0,0,!1,a];if(i===r)return[m.DataElement[r].price,m.DataElement[r].y,!1,a];{let u=m.DataElement[i].x,s=m.DataElement[r].x,c=m.DataElement[i].price,l=m.DataElement[r].price,d=m.DataElement[i].y,p=m.DataElement[r].y;if(e>=u&&e<=s)return n?[l,p,!0,a]:[c,d,!0,a];{let f,y;return n?(f=c+(l-c)*(e-u)/(s-u),y=d-(o-u)*m.multiplier/l):(f=c+(l-c)*(e-u)/(s-u),y=p+(s-o)*m.multiplier/c),[f,y,!1,a]}}}function Id(m,e,t,n){let o=n?e-t:e+t,[i,r,a]=Bd(m,o);if(!a)return[0,0,!1,a];if(i===r)return[m.DataElement[r].price,m.DataElement[r].x,!1,a];{let u=m.DataElement[i].x,s=m.DataElement[r].x,c=m.DataElement[i].price,l=m.DataElement[r].price,d=m.DataElement[i].y,p=m.DataElement[r].y;if(e>=p&&e<=d)return n?[l,s,!0,a]:[c,u,!0,a];{let f,y;return n?(f=c+(l-c)*(d-e)/(d-p),y=u+l*(d-o)/m.multiplier):(f=c+(l-c)*(d-e)/(d-p),y=s-c*(o-p)/m.multiplier),[f,y,!1,a]}}}function xd(m,e){let t=fl(m,e,0,!1);return t[3]?t[0]:0}function yl(m,e,t,n){let o=hs(m,e,t),i=ho(m,e,o),r=ho(m,t,o),a=ho(m,n,o),u=!0,[s,c,l,d]=fl(m,i,a,u);if(!d)return 0;if(l)return n*m.multiplier/s;{let p=r-c;return pl(m,p,o)}}function bl(m,e,t,n){let o=hs(m,e,t),i=ho(m,e,o),r=ho(m,t,o),a=ho(m,n,o),u=!1,[s,c,l,d]=Id(m,r,a,u);if(!d)return 0;if(l)return n*s/m.multiplier;{let p=i-c;return pl(m,p,o)}}function Sd(m){let e=Pd.decode(m);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 gl(m,e,t,n){let o=xd(m,ho(m,e,hs(m,e,t)))/m.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=Sd(e==null?void 0:e.data))}}};var Dn=require("@solana/spl-token"),Ie=require("@solana/web3.js"),xo=te(require("bn.js"));var Kd=Buffer.from("vault_auth_seed","utf8"),Cd=Buffer.from("global_config","utf8"),Rd=Buffer.from("pool_vesting","utf8"),Ld=Buffer.from("platform_config","utf8"),Od=Buffer.from("platform_fee_vault_auth_seed","utf8"),Nd=Buffer.from("creator_fee_vault_auth_seed","utf8"),Hw=Buffer.from("platform_global_access","utf8"),Md=Buffer.from("platform_allow_config","utf8"),Fd=Buffer.from("platform_curve_rule","utf8");function Gt(m){return le([Kd],m)}function Bs(m,e,t,n){return le([Cd,e.toBuffer(),vd(t),xr(n)],m)}function Uo(m,e,t){return le([Sr,e.toBuffer(),t.toBuffer()],m)}function Is(m,e,t){return le([$a,e.toBuffer(),t.toBuffer()],m)}function Io(m){return le([Buffer.from("__event_authority","utf8")],m)}function vd(m){let e=new ArrayBuffer(1);return new DataView(e).setUint8(0,m),new Uint8Array(e)}function xs(m,e){return le([Ld,e.toBuffer()],m)}function Go(m,e,t){return le([Rd,e.toBuffer(),t.toBuffer()],m)}function wn(m,e,t){return le([e.toBuffer(),t.toBuffer()],m)}function Ss(m){return le([Od],m)}function kn(m,e,t){return le([e.toBuffer(),t.toBuffer()],m)}function Ks(m){return le([Nd],m)}function Wi(m,e,t){return le([Md,e.toBuffer(),t.toBuffer()],m)}function Cs(m,e,t){return le([Fd,e.toBuffer(),t.toBuffer()],m)}var wt={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]),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]),createPlatformCurveRule:Buffer.from([148,71,180,136,122,144,59,21]),updatePlatformCurveRule:Buffer.from([90,100,206,196,54,117,120,139]),removePlatformCurveRule:Buffer.from([236,77,154,138,32,145,127,219]),closePlatformCurveRule:Buffer.from([194,114,82,45,136,88,169,159])};function Pl(m,e,t,n,o,i,r,a,u,s,c,l,d,p,f,y,b,g,A,k,h,P,T,I){let x=v([V("decimals"),Ht("name"),Ht("symbol"),Ht("uri")]),S=v([w("totalLockedAmount"),w("cliffPeriod"),w("unlockPeriod"),V("cpmmCreatorFeeOn")]),B=v([V("index"),w("supply"),w("totalFundRaisingB"),V("migrateType")]),R=v([V("index"),w("supply"),w("totalSellA"),w("totalFundRaisingB"),V("migrateType")]),L=[{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:d,isSigner:!1,isWritable:!1},{pubkey:In,isSigner:!1,isWritable:!1},{pubkey:Ie.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:_t,isSigner:!1,isWritable:!1},{pubkey:Io(m).publicKey,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1}];T&&L.push({pubkey:T,isSigner:!1,isWritable:!1}),I&&L.push({pubkey:I,isSigner:!1,isWritable:!1});let O=Buffer.alloc(Buffer.from(f,"utf-8").length+Buffer.from(y,"utf-8").length+Buffer.from(b,"utf-8").length+4*3+1),C=Buffer.alloc(S.span),M=Buffer.alloc(g.type==="ConstantCurve"?R.span:B.span);return x.encode({decimals:p,name:f,symbol:y,uri:b},O),g.type==="ConstantCurve"?R.encode(_(N({index:0},g),{migrateType:g.migrateType==="amm"?0:1}),M):g.type==="FixedCurve"?B.encode(_(N({index:1},g),{migrateType:g.migrateType==="amm"?0:1}),M):g.type==="LinearCurve"&&B.encode(_(N({index:2},g),{migrateType:g.migrateType==="amm"?0:1}),M),S.encode({totalLockedAmount:A,cliffPeriod:k,unlockPeriod:h,cpmmCreatorFeeOn:P},C),new Ie.TransactionInstruction({keys:L,programId:m,data:Buffer.from([...wt.initializeV2,...O,...M,...C])})}function Al(m,e,t,n,o,i,r,a,u,s,c,l,d,p,f,y,b,g,A,k,h,P,T,I){let x=v([V("decimals"),Ht("name"),Ht("symbol"),Ht("uri")]),S=v([w("totalLockedAmount"),w("cliffPeriod"),w("unlockPeriod"),V("cpmmCreatorFeeOn"),V("transferFeeExtensionParamsOption"),v([ze("transferFeeBasePoints"),w("maxinumFee")]).replicate("transferFeeExtensionParams")]),B=v([V("index"),w("supply"),w("totalFundRaisingB"),V("migrateType")]),R=v([V("index"),w("supply"),w("totalSellA"),w("totalFundRaisingB"),V("migrateType")]),L=[{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:Ie.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:Io(m).publicKey,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1}];T&&L.push({pubkey:T,isSigner:!1,isWritable:!1}),I&&L.push({pubkey:I,isSigner:!1,isWritable:!1});let O=Buffer.alloc(Buffer.from(p,"utf-8").length+Buffer.from(f,"utf-8").length+Buffer.from(y,"utf-8").length+4*3+1),C=Buffer.alloc(S.span),M=Buffer.alloc(b.type==="ConstantCurve"?R.span:B.span);return x.encode({decimals:d,name:p,symbol:f,uri:y},O),b.type==="ConstantCurve"?R.encode(_(N({index:0},b),{migrateType:b.migrateType==="amm"?0:1}),M):b.type==="FixedCurve"?B.encode(_(N({index:1},b),{migrateType:b.migrateType==="amm"?0:1}),M):b.type==="LinearCurve"&&B.encode(_(N({index:2},b),{migrateType:b.migrateType==="amm"?0:1}),M),S.encode({totalLockedAmount:g,cliffPeriod:A,unlockPeriod:k,cpmmCreatorFeeOn:h,transferFeeExtensionParamsOption:P?1:0,transferFeeExtensionParams:P!=null?P:{transferFeeBasePoints:0,maxinumFee:new xo.default(0)}},C),new Ie.TransactionInstruction({keys:L,programId:m,data:Buffer.from([...wt.initializeWithToken2022,...O,...M,...C])})}function qi(m,e,t,n,o,i,r,a,u,s,c,l,d,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:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:Io(m).publicKey,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1}];k&&P.push({pubkey:k,isSigner:!1,isWritable:!0}),P.push({pubkey:Ie.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 Ie.TransactionInstruction({keys:P,programId:m,data:Buffer.from([...wt.buyExactIn,...T])})}function wl(m,e,t,n,o,i,r,a,u,s,c,l,d,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:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:Io(m).publicKey,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1}];k&&P.push({pubkey:k,isSigner:!1,isWritable:!0}),P.push({pubkey:Ie.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 Ie.TransactionInstruction({keys:P,programId:m,data:Buffer.from([...wt.buyExactOut,...T])})}function Dr(m,e,t,n,o,i,r,a,u,s,c,l,d,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:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:Io(m).publicKey,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1}];k&&P.push({pubkey:k,isSigner:!1,isWritable:!0}),P.push({pubkey:Ie.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 Ie.TransactionInstruction({keys:P,programId:m,data:Buffer.from([...wt.sellExactIn,...T])})}function kl(m,e,t,n,o,i,r,a,u,s,c,l,d,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:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:Io(m).publicKey,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1}];k&&P.push({pubkey:k,isSigner:!1,isWritable:!0}),P.push({pubkey:Ie.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 Ie.TransactionInstruction({keys:P,programId:m,data:Buffer.from([...wt.sellExactOut,...T])})}function Rs(m,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:Ie.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 Ie.TransactionInstruction({keys:c,programId:m,data:Buffer.from([...wt.claimVestedToken,...l])})}function Ls(m,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:Ie.SystemProgram.programId,isSigner:!1,isWritable:!1}],u=Buffer.alloc(r.span);return r.encode({shareAmount:i},u),new Ie.TransactionInstruction({keys:a,programId:m,data:Buffer.from([...wt.createVestingAccount,...u])})}function Os(m,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:Ie.SystemProgram.programId,isSigner:!1,isWritable:!0},{pubkey:Dn.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!0}];return new Ie.TransactionInstruction({keys:s,programId:m,data:wt.claimPlatformFee})}function Tl(m,e,t,n,o,i,r,a,u,s,c,l,d,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:Ie.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(d,"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:d,img:p,creatorFeeRate:c,platformVestingScale:f},g),new Ie.TransactionInstruction({keys:b,programId:m,data:Buffer.from([...wt.createPlatformConfig,...g])})}function hl(m,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([V("index"),F("value")]);i=Buffer.alloc(r.span),r.encode({index:0,value:n.value},i)}else if(n.type==="updateLockNftWallet"){let r=v([V("index"),F("value")]);i=Buffer.alloc(r.span),r.encode({index:1,value:n.value},i)}else if(n.type==="migrateCpLockNftScale"){let r=v([V("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([V("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([V("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([V("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([V("index"),F("platformClaimFeeWallet"),F("platformLockNftWallet"),w("platformScale"),w("creatorScale"),w("burnScale"),w("feeRate"),Ht("name"),Ht("web"),Ht("img"),F("transferFeeExtensionAuth"),w("creatorFeeRate"),w("platformVestingScale"),F("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([V("index"),F("value")]);i=Buffer.alloc(r.span),r.encode({index:9,value:n.value},i)}else if(n.type==="updatePlatformVestingScale"){let r=v([V("index"),w("value")]);i=Buffer.alloc(r.span),r.encode({index:10,value:n.value},i)}else if(n.type==="updatePlatformCpCreator"){let r=v([V("index"),F("value")]);i=Buffer.alloc(r.span),r.encode({index:11,value:n.value},i)}else if(n.type==="updateRestrictGlobalConfig"){let r=v([V("index"),w("value")]);i=Buffer.alloc(r.span),r.encode({index:12,value:n.value},i)}else if(n.type==="updateRestrictCurveParam"){let r=v([V("index"),w("value")]);i=Buffer.alloc(r.span),r.encode({index:13,value:n.value},i)}else if(n.type==="updateCurveRuleManager"){let r=v([V("index"),F("value")]);i=Buffer.alloc(r.span),r.encode({index:14,value:n.value},i)}else throw Error("updateInfo params type error");return new Ie.TransactionInstruction({keys:o,programId:m,data:Buffer.from([...wt.updatePlaformConfig,...i])})}function Ns(m,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:Ie.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:Dn.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}];return new Ie.TransactionInstruction({keys:u,programId:m,data:wt.claimPlatformFeeFromVault})}function Ms(m,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:Ie.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:Dn.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}];return new Ie.TransactionInstruction({keys:a,programId:m,data:wt.claimCreatorFee})}var tk=new xo.default("18446744073709551615");function Bl(m,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:Ie.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new Ie.TransactionInstruction({keys:r,programId:m,data:wt.createPlatformVestingAccount})}function Il(m,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:Ie.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new Ie.TransactionInstruction({keys:i,programId:m,data:wt.createPlatformAllowConfig})}function xl(m,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 Ie.TransactionInstruction({keys:i,programId:m,data:wt.closePlatformAllowConfig})}function _d(m){let e=v([V("field"),V("op"),ce("value")]),t=Buffer.alloc(4+m.length*e.span);return t.writeUInt32LE(m.length,0),m.forEach((n,o)=>{e.encode(n,t,4+o*e.span)}),t}function Sl(m,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:Ie.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new Ie.TransactionInstruction({keys:i,programId:m,data:wt.createPlatformCurveRule})}function Kl(m,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:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:Ie.SystemProgram.programId,isSigner:!1,isWritable:!1}],u=Buffer.alloc(ze().span);return ze().encode(i,u),new Ie.TransactionInstruction({keys:a,programId:m,data:Buffer.from([...wt.updatePlatformCurveRule,...u,..._d(r)])})}function Cl(m,e,t,n,o,i){let r=[{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:Ie.SystemProgram.programId,isSigner:!1,isWritable:!1}],a=Buffer.alloc(ze().span);return ze().encode(i,a),new Ie.TransactionInstruction({keys:r,programId:m,data:Buffer.from([...wt.removePlatformCurveRule,...a])})}function Rl(m,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 Ie.TransactionInstruction({keys:i,programId:m,data:wt.closePlatformCurveRule})}var Jn=v([w(),w("epoch"),V("curveType"),ze("index"),w("migrateFee"),w("tradeFeeRate"),w("maxShareFeeRate"),w("minSupplyA"),w("maxLockRate"),w("minSellRateA"),w("minMigrateRateA"),w("minFundRaisingB"),F("mintB"),F("protocolFeeOwner"),F("migrateFeeOwner"),F("migrateToAmmWallet"),F("migrateToCpmmWallet"),Q(w(),16)]),Vd=v([w("totalLockedAmount"),w("cliffPeriod"),w("unlockPeriod"),w("startTime"),w("totalAllocatedShare")]),Tn=v([w(),w("epoch"),V("bump"),V("status"),V("mintDecimalsA"),V("mintDecimalsB"),V("migrateType"),w("supply"),w("totalSellA"),w("virtualA"),w("virtualB"),w("realA"),w("realB"),w("totalFundRaisingB"),w("protocolFee"),w("platformFee"),w("migrateFee"),Vd.replicate("vestingSchedule"),F("configId"),F("platformId"),F("mintA"),F("mintB"),F("vaultA"),F("vaultB"),F("creator"),V("mintProgramFlag"),V("cpmmCreatorFeeOn"),w("platformVestingShare"),Q(V(),54)]),rk=v([w(),w("epoch"),F("poolId"),F("beneficiary"),w("claimedAmount"),w("tokenShareAmount"),Q(w(),8)]),Ed=v([V("migrateType"),V("migrateCpmmFeeOn"),w("supply"),w("totalSellA"),w("totalFundRaisingB"),w("totalLockedAmount"),w("cliffPeriod"),w("unlockPeriod")]),ak=v([w("epoch"),V("index"),F("configId"),Ed.replicate("bondingCurveParam"),Q(w(),50)]),hn=v([w(),w("epoch"),F("platformClaimFeeWallet"),F("platformLockNftWallet"),w("platformScale"),w("creatorScale"),w("burnScale"),w("feeRate"),Q(V(),64,"name"),Q(V(),256,"web"),Q(V(),256,"img"),F("cpConfigId"),w("creatorFeeRate"),F("transferFeeExtensionAuth"),F("platformVestingWallet"),w("platformVestingScale"),F("platformCpCreator"),V("restrictGlobalConfig"),V("restrictCurveParam"),F("curveRuleManager"),Q(V(),78)]),Dd=v([V("field"),V("op"),ce("value")]),Wd=v([ze("groupId"),w("epoch"),Ia(Dd,"constraints")]),Wr=v([w(),V("bump"),V("version"),F("platformId"),F("configId"),w("epoch"),Q(w(),8),Ia(Wd,"groups")]);var zo=require("@solana/spl-token");function qd(m,e){return m>>e&1?zo.TOKEN_2022_PROGRAM_ID:zo.TOKEN_PROGRAM_ID}function qr(m){return qd(m,0)}function Ll({mintAProgram:m,mintBProgram:e}){return(m.equals(zo.TOKEN_2022_PROGRAM_ID)?1<<0:0)|(e.equals(zo.TOKEN_2022_PROGRAM_ID)?1<<1:0)}var Ol=te(require("bn.js"));var Pk=new Ol.default(1e6);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 Ur=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")),vs=te(require("decimal.js"));var Gi=te(require("bn.js")),Yo=te(require("decimal.js"));var Gr=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 Fs=te(require("bn.js")),zr=te(require("decimal.js")),zi=class{static _multipler(e){return new zr.default(10).pow(e)}static getPrice({priceX64:e,decimalA:t,decimalB:n}){return new zr.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 Fs.default(o.mul(this._Q64).toFixed(0))}};zi._Q64=new zr.default(new Fs.default(1).shln(64).toString());var Xr=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 Mt=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}),d=c.getPoolInitPriceByInit(_(N({},l),{decimalA:u,decimalB:s})),p=o.div(new Xt.default(t-1)),f=new Xt.default(0),y=[{price:d,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 vs.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(tt).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(tt);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(tt);if(c.lt(l))throw Error("migrate lt min migrate amoount");let d=e.sub(n).sub(o),p=new Xt.default(new vs.default(d.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),d=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:d,feeRate:p}),y=d.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),d=Ho(t,u,c),p=d.fee?d.amount.add(d.fee):d.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:d,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),d=Xi(t,u,c),p=d.fee?d.amount.sub(d.fee):d.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:d,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}),d=Ho(t,s,c),p=d.amount,f=this.calculatePreFee({postFeeAmount:p,feeRate:l});if(e.realB.lt(f))throw Error("Insufficient liquidity");let y=f.sub(p),g=Mt.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:d.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,tt)}static calculatePreFee({postFeeAmount:e,feeRate:t}){if(t.isZero())return e;let n=e.mul(tt),o=tt.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 Ur;case 1:return Gr;case 2:return Xr}throw Error("find curve error")}};var ee=require("@solana/spl-token"),me=te(require("bn.js")),oo=require("@solana/web3.js");var jt=te(require("decimal.js")),Yr={initPriceX64:new me.default("515752397214619"),supply:new me.default(1e15),totalSellA:new me.default(7931e11),totalFundRaisingB:new me.default(85e9),totalFundRaisingBUSD:new me.default(125e8),totalLockedAmount:new me.default("0"),cliffPeriod:new me.default("0"),unlockPeriod:new me.default("0"),decimals:6,virtualA:new me.default("1073471847374405"),virtualB:new me.default("30050573465"),realA:new me.default(0),realB:new me.default(0),protocolFee:new me.default(0),platformId:new oo.PublicKey("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),vestingSchedule:{totalLockedAmount:new me.default(0),cliffPeriod:new me.default(0),unlockPeriod:new me.default(0),startTime:new me.default(0),totalAllocatedShare:new me.default(0)}},no=new me.default(1e4);var Yi=class extends rt{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(M){var D=M,{programId:e=Qe,authProgramId:t,platformId:n=Yr.platformId,mintA:o,decimals:i=6,mintBDecimals:r=9,name:a,symbol:u,uri:s,migrateType:c,configId:l,configInfo:d,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}=D,C=$e(D,["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 Qs,Zs,$s,js,Js,eu,tu,nu,ou,iu,ru;let E=this.createTxBuilder(b);t=t!=null?t:Gt(e).publicKey,I=!!x,I&&(c="cpmm");let z=d;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:Z}=Uo(e,o,H),{publicKey:ge}=Is(e,Z,o),{publicKey:re}=Is(e,Z,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 Oe=(await this.scope.api.fetchLaunchConfigs()).find(On=>On.key.pubKey===l.toBase58()),Ae=(Qs=C==null?void 0:C.supply)!=null?Qs:new me.default(Oe.defaultParams.supplyInit),ae=(Zs=C==null?void 0:C.totalSellA)!=null?Zs:new me.default(Oe.defaultParams.totalSellA),Re=($s=C==null?void 0:C.totalFundRaisingB)!=null?$s:new me.default(Oe.defaultParams.totalFundRaisingB),Ft=(js=C==null?void 0:C.totalLockedAmount)!=null?js:new me.default(0),ot=await this.scope.connection.getAccountInfo(n);ot||this.logAndCreateError("platform id not found:",n.toString());let dn=hn.decode(ot.data),Co=dn.platformVestingScale,ei=dn.feeRate,ti=Mt.getCurve(z.curveType).getInitParam({supply:Ae,totalFundRaising:Re,totalSell:ae,totalLockedAmount:Ft,migrateFee:z.migrateFee}),Wt;try{Wt=await this.scope.token.getTokenInfo(H)}catch{this.logDebug("can not get mintB info from getTokenInfo")}let pn={epoch:new me.default(896),bump:254,status:0,mintDecimalsA:i,mintDecimalsB:(Js=Wt==null?void 0:Wt.decimals)!=null?Js:r,supply:Ae,totalSellA:ae,mintA:new oo.PublicKey(o),mintB:H,virtualA:ti.a,virtualB:ti.b,realA:Yr.realA,realB:Yr.realB,migrateFee:z.migrateFee,migrateType:c==="amm"?0:1,protocolFee:Yr.protocolFee,platformFee:ei,platformId:n,configId:l,vaultA:ge,vaultB:re,creator:this.scope.ownerPubKey,totalFundRaisingB:Re,vestingSchedule:{totalLockedAmount:Ft,cliffPeriod:new me.default(0),unlockPeriod:new me.default(0),startTime:new me.default(0),totalAllocatedShare:new me.default(0)},mintProgramFlag:Ll({mintAProgram:I?ee.TOKEN_2022_PROGRAM_ID:ee.TOKEN_PROGRAM_ID,mintBProgram:J}),cpmmCreatorFeeOn:S,platformVestingShare:Co!=null?Co:new me.default(0)},ql=Mt.getCurve(z.curveType),{c:Ul}=ql.getInitParam({supply:pn.supply,totalFundRaising:pn.totalFundRaisingB,totalLockedAmount:Ft,totalSell:z.curveType===0?pn.totalSellA:new me.default(0),migrateFee:z.migrateFee});try{Mt.checkParam({supply:pn.supply,totalFundRaising:pn.totalFundRaisingB,totalSell:Ul,totalLockedAmount:Ft,decimals:pn.mintDecimalsA,config:z,migrateType:c}),this.logDebug("check init params success")}catch(On){this.logAndCreateError(`check create mint params failed, ${On.message}`)}let Hs=dn.restrictCurveParam?Cs(e,n,l).publicKey:void 0;E.addInstruction({instructions:[I?Al(e,b!=null?b:this.scope.ownerPubKey,this.scope.ownerPubKey,l,n,t,Z,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:Re},Ft,(eu=C==null?void 0:C.cliffPeriod)!=null?eu:new me.default(0),(tu=C==null?void 0:C.unlockPeriod)!=null?tu:new me.default(0),S,x,B?Wi(e,n,l).publicKey:void 0,Hs):Pl(e,b!=null?b:this.scope.ownerPubKey,this.scope.ownerPubKey,l,n,t,Z,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:Re},Ft,(nu=C==null?void 0:C.cliffPeriod)!=null?nu:new me.default(0),(ou=C==null?void 0:C.unlockPeriod)!=null?ou:new me.default(0),S,B?Wi(e,n,l).publicKey:void 0,Hs)]});let ia=I?await this.scope.connection.getEpochInfo():void 0,tr=x?{epoch:BigInt((ia==null?void 0:ia.epoch)||0),maximumFee:BigInt((iu=x==null?void 0:x.maxinumFee.toString())!=null?iu:0),transferFeeBasisPoints:(ru=x==null?void 0:x.transferFeeBasePoints)!=null?ru:0}:void 0,ra={amountA:{amount:new me.default(0),fee:void 0,expirationTime:void 0},amountB:new me.default(0),splitFee:{platformFee:new me.default(0),shareFee:new me.default(0),protocolFee:new me.default(0),creatorFee:new me.default(0)},transferFeeB:void 0},aa;if(T!=null&&T.length&&E.addInstruction({signers:T}),!C.createOnly){let{builder:On,extInfo:Gl}=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:pn,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});E.addInstruction(N({},On.AllTxData)),ra=N({},Gl),aa=(this.scope.cluster==="devnet"||p===1)&&C.shareFeeReceiver?[On.allInstructions[0]]:void 0}return E.addTipInstruction(y),p===0?E.sizeCheckBuildV0({computeBudgetConfig:f,swapInfo:ra,splitIns:aa,address:_(N({},pn),{poolId:Z})}):E.sizeCheckBuild({computeBudgetConfig:f,swapInfo:ra,splitIns:aa,address:_(N({},pn),{poolId:Z})})}async buyToken({programId:e=Qe,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:d,buyAmount:p,minMintAAmount:f,slippage:y,shareFeeRate:b=new me.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,Re,Ft;p.lte(new me.default(0))&&this.logAndCreateError("buy amount should gt 0:",p.toString());let B=this.createTxBuilder(d),{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 ot=await this.scope.connection.getAccountInfo(n);if(ot&&ot.owner.equals(ee.TOKEN_2022_PROGRAM_ID)){o=ot.owner;let dn=(0,ee.unpackMint)(n,ot,o);L=(0,ee.getTransferFeeConfig)(dn)||void 0}}let{mintBProgram:O,transferFeeConfigB:C}=await this.getMintBTokenInfo({mintB:i,mintBProgram:I,transferFeeConfigB:x,skipCheckMintB:S}),M=this.scope.account.getAssociatedTokenAccount(n,o),D=i.equals(ee.NATIVE_MINT),E=h&&D,z=E?this.scope.account.getAssociatedTokenAccount(i,O):null,H=D;if(B.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,M,this.scope.ownerPubKey,n,o),...E?[(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)]:[]]}),!E){let{account:ot,instructionParams:dn}=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});ot&&(z=ot),B.addInstruction(dn||{})}z||this.logAndCreateError(`cannot found mintB(${i.toBase58()}) buy token accounts`,"tokenAccounts",this.scope.account.tokenAccounts);let Y=r;if(!Y){let ot=await this.scope.connection.getAccountInfo(R,{commitment:"processed"});ot||this.logAndCreateError("cannot found pool:",R.toBase58()),Y=Tn.decode(ot.data)}let J=a,ie=await Ge(this.scope.connection,[J?void 0:Y.configId,Y.platformId].filter(Boolean).map(ot=>({pubkey:ot})));if(!J){let ot=ie.find(dn=>dn.pubkey.equals(Y.configId));(!ot||!ot.accountInfo)&&this.logAndCreateError("config not found: ",Y.configId.toBase58()),J=Jn.decode(ot.accountInfo.data)}let Z=ie.find(ot=>ot.pubkey.equals(Y.platformId));(!Z||!Z.accountInfo)&&this.logAndCreateError("platform info not found: ",Y.configId.toBase58());let ge=hn.decode(Z.accountInfo.data);u=u||ge.feeRate;let re=Mt.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 jt.default(re.amountA.amount.toString()).sub((Re=(ae=re.amountA.fee)==null?void 0:ae.toString())!=null?Re:0),Fe=y?new jt.default(no.sub(y).toNumber()/no.toNumber()).clampedTo(0,1):new jt.default(1),Oe=f!=null?f:y?new me.default(ke.mul(Fe).toFixed(0)):re.amountA.amount.sub((Ft=re.amountA.fee)!=null?Ft:new me.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,M,z,Y.vaultA,Y.vaultB,n,i,o,O,wn(e,Y.platformId,i).publicKey,kn(e,Y.creator,i).publicKey,re.amountB.lt(p)?re.amountB:p,Oe,b,Ae)]}),B.addCustomComputeBudget(c),B.addTipInstruction(l),B.versionBuild({txVersion:s,extInfo:_(N({},re),{decimalOutAmount:ke,minDecimalOutAmount:new jt.default(Oe.toString())})})}async buyTokenExactOut({programId:e=Qe,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:d,feePayer:p,maxBuyAmount:f,outAmount:y,slippage:b,shareFeeRate:g=new me.default(0),shareFeeReceiver:A,associatedOnly:k=!0,checkCreateATAOwner:h=!1,skipCheckMintA:P=!1,mintBProgram:T,transferFeeConfigB:I,skipCheckMintB:x=!1}){y.lte(new me.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=Tn.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 M=hn.decode(C.accountInfo.data);s=s||M.feeRate;let D=u;if(!P)if(D)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);D=(0,ee.getTransferFeeConfig)(ae)||void 0}}let{mintBProgram:E,transferFeeConfigB:z}=await this.getMintBTokenInfo({mintB:i,mintBProgram:T,transferFeeConfigB:I,skipCheckMintB:x}),H=Mt.buyExactOut({poolInfo:R,amountA:y,protocolFeeRate:L.tradeFeeRate,platformFeeRate:s,curveType:L.curveType,shareFeeRate:g,creatorFeeRate:M.creatorFeeRate,transferFeeConfigA:D,transferFeeConfigB:z,slot:await this.scope.connection.getSlot()}),Y=new jt.default(H.amountB.toString()),J=b?new jt.default(no.add(b).toNumber()/no.toNumber()).clampedTo(0,Number.MIN_SAFE_INTEGER):new jt.default(1),ie=(f!=null?f:b)?new me.default(Y.mul(J).toFixed(0)):H.amountB,Z=this.scope.account.getAssociatedTokenAccount(n,o),ge=null,re=i.equals(ee.NATIVE_MINT);S.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Z,this.scope.ownerPubKey,n,o)]});let{account:ke,instructionParams:Fe}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:E,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 Oe=A?ne(A,i,E).publicKey:void 0;return Oe&&S.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Oe,A,i,E)]}),S.addInstruction({instructions:[wl(e,this.scope.ownerPubKey,t,R.configId,R.platformId,B,Z,ge,R.vaultA,R.vaultB,n,i,o,E,wn(e,R.platformId,i).publicKey,kn(e,R.creator,i).publicKey,y,ie,g,Oe)]}),S.addCustomComputeBudget(l),S.addTipInstruction(d),S.versionBuild({txVersion:c,extInfo:{maxSpentAmount:ie,outAmount:y}})}async sellToken({programId:e=Qe,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:d,sellAmount:p,minAmountB:f,slippage:y,shareFeeRate:b=new me.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(d);p.lte(new me.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 Re=(0,ee.unpackMint)(o,ae,n);B=(0,ee.getTransferFeeConfig)(Re)||void 0}}let{mintBProgram:R,transferFeeConfigB:L}=await this.getMintBTokenInfo({mintB:i,mintBProgram:P,transferFeeConfigB:T,skipCheckMintB:I}),O=null,C=null,M=i.equals(ee.NATIVE_MINT),{account:D,instructionParams:E}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n,mint:o,owner:this.scope.ownerPubKey,createInfo:void 0,skipCloseAccount:!0,notUseTokenAccount:!1,associatedOnly:A,checkCreateATAOwner:k});D&&(O=D),x.addInstruction(E||{}),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:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!M,notUseTokenAccount:M,associatedOnly:M?!1:A,checkCreateATAOwner:k});z&&(C=z),x.addInstruction(H||{}),C||this.logAndCreateError("cannot found mintB token accounts","tokenAccounts",{userTokenAccountB:C});let Y=r;if(!Y){let ae=await this.scope.connection.getAccountInfo(S,{commitment:"processed"});ae||this.logAndCreateError("cannot found pool",S.toBase58()),Y=Tn.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(Re=>Re.pubkey.equals(Y.configId));(!ae||!ae.accountInfo)&&this.logAndCreateError("config not found: ",Y.configId.toBase58()),J=Jn.decode(ae.accountInfo.data)}let Z=ie.find(ae=>ae.pubkey.equals(Y.platformId));(!Z||!Z.accountInfo)&&this.logAndCreateError("platform info not found: ",Y.configId.toBase58());let ge=hn.decode(Z.accountInfo.data);u=u||ge.feeRate;let re=Mt.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 jt.default(re.amountB.toString()),Fe=y?new jt.default(no.sub(y).toNumber()/no.toNumber()).clampedTo(0,1):new jt.default(1),Oe=f!=null?f:y?new me.default(ke.mul(Fe).toFixed(0)):re.amountB;Oe.lte(new me.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,wn(e,Y.platformId,i).publicKey,kn(e,Y.creator,i).publicKey,re.amountA.amount.lt(p)?re.amountA.amount:p,Oe,b,Ae)]}),x.addCustomComputeBudget(c),x.addTipInstruction(l),x.versionBuild({txVersion:s,extInfo:{outAmount:Oe}})}async sellTokenExactOut({programId:e=Qe,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:d,inAmount:p,maxSellAmount:f,slippage:y,shareFeeRate:b=new me.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(d);f!=null&&f.lte(new me.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 Re=(0,ee.unpackMint)(o,ae,n);B=(0,ee.getTransferFeeConfig)(Re)||void 0}}let{mintBProgram:R,transferFeeConfigB:L}=await this.getMintBTokenInfo({mintB:i,mintBProgram:P,transferFeeConfigB:T,skipCheckMintB:I}),O=null,C=null,M=i.equals(ee.NATIVE_MINT),{account:D,instructionParams:E}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n,mint:o,owner:this.scope.ownerPubKey,createInfo:void 0,skipCloseAccount:!0,notUseTokenAccount:!1,associatedOnly:A,checkCreateATAOwner:k});D&&(O=D),x.addInstruction(E||{}),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:M?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!M,notUseTokenAccount:M,associatedOnly:M?!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=Tn.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(Re=>Re.pubkey.equals(Y.configId));(!ae||!ae.accountInfo)&&this.logAndCreateError("config not found: ",Y.configId.toBase58()),J=Jn.decode(ae.accountInfo.data)}let Z=ie.find(ae=>ae.pubkey.equals(Y.platformId));(!Z||!Z.accountInfo)&&this.logAndCreateError("platform info not found: ",Y.configId.toBase58());let ge=hn.decode(Z.accountInfo.data);u=u||ge.feeRate;let re=Mt.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 jt.default(re.amountA.amount.toString()),Fe=y?new jt.default(no.add(y).toNumber()/no.toNumber()).clampedTo(0,Number.MAX_SAFE_INTEGER):new jt.default(1),Oe=(f!=null?f:y)?new me.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:[kl(e,this.scope.ownerPubKey,t,Y.configId,Y.platformId,S,O,C,Y.vaultA,Y.vaultB,o,i,n,R,wn(e,Y.platformId,i).publicKey,kn(e,Y.creator,i).publicKey,p,Oe,b,Ae)]}),x.addCustomComputeBudget(c),x.addTipInstruction(l),x.versionBuild({txVersion:s,extInfo:{maxSellAmount:Oe}})}async createPlatformConfig({programId:e=Qe,platformAdmin:t,platformClaimFeeWallet:n,platformLockNftWallet:o,platformVestingWallet:i,cpConfigId:r,migrateCpLockNftScale:a,transferFeeExtensionAuth:u,creatorFeeRate:s,feeRate:c,name:l,web:d,img:p,platformVestingScale:f=new me.default(0),txVersion:y,computeBudgetConfig:b,txTipConfig:g,feePayer:A}){let k=this.createTxBuilder(A),{publicKey:h}=xs(e,t);return k.addInstruction({instructions:[Tl(e,t,n,o,i,h,r,u,a,c,s,l,d,p,f)]}),k.addCustomComputeBudget(b),k.addTipInstruction(g),k.versionBuild({txVersion:y,extInfo:{platformId:h}})}async updatePlatformConfig({programId:e=Qe,platformAdmin:t,platformId:n,updateInfo:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:u}){let s=this.createTxBuilder(u),c=n!=null?n:xs(e,t).publicKey;return s.addInstruction({instructions:[hl(e,t,c,o)]}),s.addCustomComputeBudget(r),s.addTipInstruction(a),s.versionBuild({txVersion:i})}async createPlatformVestingAccount({programId:e=Qe,platformVestingWallet:t,beneficiary:n,platformId:o,poolId:i,vestingRecord:r,txVersion:a,computeBudgetConfig:u,txTipConfig:s,feePayer:c}){let l=this.createTxBuilder(c),d=r!=null?r:Go(e,i,n).publicKey;return l.addInstruction({instructions:[Bl(e,t,n,o,i,d)]}),l.addCustomComputeBudget(u),l.addTipInstruction(s),l.versionBuild({txVersion:a})}async claimPlatformFee({programId:e=Qe,authProgramId:t,platformId:n,poolId:o,platformClaimFeeWallet:i,mintB:r,vaultB:a,mintBProgram:u,txVersion:s,computeBudgetConfig:c,txTipConfig:l,feePayer:d}){var A;let p=this.createTxBuilder(d);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=Tn.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:[Os(e,i,t,o,n,y,g,f,b)]}),p.addCustomComputeBudget(c),p.addTipInstruction(l),p.versionBuild({txVersion:s})}async claimAllPlatformFee({programId:e=Qe,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:Tn.span},{memcmp:{offset:Tn.offsetOf("platformId"),bytes:n.toString()}}]})).map(f=>({poolId:f.pubkey,pool:Tn.decode(f.account.data)})).filter(({pool:f})=>f.platformFee.gt(new me.default(0))),d={},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;d[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=d[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:[Os(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=Qe,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:[Ls(e,this.scope.ownerPubKey,n,t,l,o)]}),s.addCustomComputeBudget(r),s.addTipInstruction(a),s.versionBuild({txVersion:i})}async createMultipleVesting({programId:e=Qe,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:[Ls(e,this.scope.ownerPubKey,c.wallet,t,l,c.shareAmount)]})}),o===0?a.sizeCheckBuildV0({computeBudgetConfig:i}):a.sizeCheckBuild({computeBudgetConfig:i})}async claimVesting({programId:e=Qe,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,d=n;if(!d){let f=await this.scope.connection.getAccountInfo(t);f||this.logAndCreateError("pool not found"),d=Tn.decode(f.data)}let p=ne(this.scope.ownerPubKey,d.mintA,ee.TOKEN_PROGRAM_ID).publicKey;return s.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,p,this.scope.ownerPubKey,d.mintA)]}),s.addInstruction({instructions:[Rs(e,this.scope.ownerPubKey,c,t,l,p,d.vaultA,d.mintA,ee.TOKEN_PROGRAM_ID)]}),s.addCustomComputeBudget(r),s.addTipInstruction(a),s.versionBuild({txVersion:i})}async claimMultiVesting({programId:e=Qe,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(d=>!s[d.toBase58()]);if(l.length){let d=await this.getRpcPoolsInfo({poolIdList:l});s=N(N({},s),d.poolInfoMap)}return t.forEach(d=>{let p=d.toBase58(),f=s[p];f||this.logAndCreateError(`pool info not found: ${p}`);let y=o[p]||Go(e,d,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:[Rs(e,this.scope.ownerPubKey,c,d,y,b,f.vaultA,f.mintA,ee.TOKEN_PROGRAM_ID)]})}),i===0?u.sizeCheckBuildV0({computeBudgetConfig:r}):u.sizeCheckBuild({computeBudgetConfig:r})}async claimVaultPlatformFee({programId:e=Qe,platformId:t,mintB:n,mintBProgram:o,claimFeeWallet:i,txVersion:r,computeBudgetConfig:a,txTipConfig:u,feePayer:s}){let c=this.createTxBuilder(s),l=wn(e,t,n).publicKey,d=Ss(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),Ns(e,t,i!=null?i:this.scope.ownerPubKey,d,l,f,n,p)]}),c.addCustomComputeBudget(a),c.addTipInstruction(u),c.versionBuild({txVersion:r})}async claimMultipleVaultPlatformFee({programId:e=Qe,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 d=Ss(e).publicKey,p=wn(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:[Ns(e,l.id,(g=l.claimFeeWallet)!=null?g:this.scope.ownerPubKey,d,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=Qe,mintB:t,mintBProgram:n,txVersion:o,computeBudgetConfig:i,txTipConfig:r,feePayer:a}){let u=this.createTxBuilder(a),s=kn(e,this.scope.ownerPubKey,t).publicKey,c=Ks(e).publicKey,{mintBProgram:l}=await this.getMintBTokenInfo({mintB:t,mintBProgram:n}),d=this.scope.account.getAssociatedTokenAccount(t,l);return u.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,d,this.scope.ownerPubKey,t,l),Ms(e,this.scope.ownerPubKey,c,s,d,t,l)]}),u.addCustomComputeBudget(i),u.addTipInstruction(r),u.versionBuild({txVersion:o})}async claimMultipleCreatorFee({programId:e=Qe,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=kn(e,this.scope.ownerPubKey,u).publicKey,l=Ks(e).publicKey,d=this.scope.account.getAssociatedTokenAccount(u,s);r.addInstruction({instructions:[(0,ee.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,d,this.scope.ownerPubKey,u,s),Ms(e,this.scope.ownerPubKey,l,c,d,u,s)]})}),n==0?r.sizeCheckBuildV0({computeBudgetConfig:o}):r.sizeCheckBuild({computeBudgetConfig:o})}async createPlatformAllowConfig({programId:e=Qe,platformAdmin:t,platformId:n,configInfo:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:u}){let s=this.createTxBuilder(u),{publicKey:c}=Bs(e,new oo.PublicKey(o.mintB),o.curveType,o.index),{publicKey:l}=Wi(e,n,c);return s.addInstruction({instructions:[Il(e,t,n,c,l)]}),s.addCustomComputeBudget(r),s.addTipInstruction(a),s.versionBuild({txVersion:i,extInfo:{platformId:n}})}async closePlatformAllowConfig({programId:e=Qe,platformAdmin:t,platformId:n,configInfo:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:u}){let s=this.createTxBuilder(u),{publicKey:c}=Bs(e,new oo.PublicKey(o.mintB),o.curveType,o.index),{publicKey:l}=Wi(e,n,c);return s.addInstruction({instructions:[xl(e,t,n,c,l)]}),s.addCustomComputeBudget(r),s.addTipInstruction(a),s.versionBuild({txVersion:i,extInfo:{platformAllowConfig:l}})}async createPlatformCurveRule({programId:e=Qe,curveRuleAuthority:t,platformId:n,configId:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:u}){let s=this.createTxBuilder(u),{publicKey:c}=Cs(e,n,o);return s.addInstruction({instructions:[Sl(e,t!=null?t:this.scope.ownerPubKey,n,o,c)]}),s.addCustomComputeBudget(r),s.addTipInstruction(a),s.versionBuild({txVersion:i,extInfo:{platformCurveRuleId:c}})}async updatePlatformCurveRule({programId:e=Qe,curveRuleAuthority:t,platformCurveRuleId:n,groupId:o,constraints:i,txVersion:r,computeBudgetConfig:a,txTipConfig:u,feePayer:s}){let c=this.createTxBuilder(s),l=await this.scope.connection.getAccountInfo(n);if(!l)throw new Error(`platformCurveRule ${n} not found`);let d=Wr.decode(l.data);return c.addInstruction({instructions:[Kl(e,t!=null?t:this.scope.ownerPubKey,d.platformId,d.configId,n,o,i)]}),c.addCustomComputeBudget(a),c.addTipInstruction(u),c.versionBuild({txVersion:r})}async removePlatformCurveRule({programId:e=Qe,curveRuleAuthority:t,platformCurveRuleId:n,groupId:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:u}){let s=this.createTxBuilder(u),c=await this.scope.connection.getAccountInfo(n);if(!c)throw new Error(`platformCurveRule ${n} not found`);let l=Wr.decode(c.data);return s.addInstruction({instructions:[Cl(e,t!=null?t:this.scope.ownerPubKey,l.platformId,l.configId,n,o)]}),s.addCustomComputeBudget(r),s.addTipInstruction(a),s.versionBuild({txVersion:i})}async closePlatformCurveRule({programId:e=Qe,curveRuleAuthority:t,platformCurveRuleId:n,txVersion:o,computeBudgetConfig:i,txTipConfig:r,feePayer:a}){let u=this.createTxBuilder(a),s=await this.scope.connection.getAccountInfo(n);if(!s)throw new Error(`platformCurveRule ${n} not found`);let c=Wr.decode(s.data);return u.addInstruction({instructions:[Rl(e,t!=null?t:this.scope.ownerPubKey,c.platformId,c.configId,n)]}),u.addCustomComputeBudget(i),u.addTipInstruction(r),u.versionBuild({txVersion:o})}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=Tn.decode(s.accountInfo.data);o[e[u].toBase58()]=_(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()]=_(N({},c),{configId:s.accountInfo.owner})}return{poolInfoMap:Object.keys(o).reduce((u,s)=>_(N({},u),{[s]:_(N({},o[s]),{configInfo:a[o[s].configId.toBase58()]})}),{})}}};var Nl={[La.toBase58()]:3},Ml={3:La};var _s=v([Be(5),Be(8),F("ownAddress"),w("vaultSignerNonce"),F("baseMint"),F("quoteMint"),F("baseVault"),w("baseDepositsTotal"),w("baseFeesAccrued"),F("quoteVault"),w("quoteDepositsTotal"),w("quoteFeesAccrued"),w("quoteDustThreshold"),F("requestQueue"),F("eventQueue"),F("bids"),F("asks"),w("baseLotSize"),w("quoteLotSize"),w("feeRateBps"),w("referrerRebatesAccrued"),Be(7)]),Fl={3:_s};var Vs=require("@solana/web3.js");var Hr=xe("Serum"),Qr=class{static getProgramId(e){let t=Ml[e];return t||Hr.logWithError("invalid version","version",e),t}static getVersion(e){let t=e.toBase58(),n=Nl[t];return n||Hr.logWithError("invalid program id","programId",t),n}static getStateLayout(e){let t=Fl[e];return t||Hr.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=Vs.PublicKey.createProgramAddressSync(r,e)}catch(r){if(r instanceof TypeError)throw r;o++;continue}return{publicKey:i,nonce:o}}return Hr.logWithError("unable to find a viable program address nonce","params",{programId:e,marketId:t}),{publicKey:Vs.PublicKey.default,nonce:o}}};var Qo=require("@solana/spl-token"),pe=require("@solana/web3.js"),Wn=te(require("bn.js"));function Ud(m,e,t,n,o,i,r,a,u,s,c,l,d,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:pe.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 pe.PublicKey(x.programId),isWritable:!1})),I===g.length-1?b.push(K({pubkey:o})):b.push(K({pubkey:n})),b.push(K({pubkey:new pe.PublicKey(k[I])})),b.push(K({pubkey:new pe.PublicKey(k[I+1])})),x.version===6){let B=A[I];b.push(K({pubkey:new pe.PublicKey(B.config.id)})),b.push(K({pubkey:new pe.PublicKey(B.id)})),b.push(K({pubkey:new pe.PublicKey(S?B.vault.A:B.vault.B)})),b.push(K({pubkey:new pe.PublicKey(S?B.vault.B:B.vault.A)})),b.push(K({pubkey:new pe.PublicKey(x.observationId)})),b.push(K({pubkey:fn})),b.push(K({pubkey:Ze(new pe.PublicKey(x.programId),new pe.PublicKey(x.id)).publicKey})),y.push(Gd(x.sqrtPriceX64.toString(),S));for(let R of(T=f[I])!=null?T:[])b.push(K({pubkey:new pe.PublicKey(R)}))}else if(x.version===5){let B=A[I];b.push(K({pubkey:new pe.PublicKey(B.id)})),b.push(K({pubkey:new pe.PublicKey(B.authority),isWritable:!1})),b.push(K({pubkey:new pe.PublicKey(B.marketProgramId)})),b.push(K({pubkey:new pe.PublicKey(B.marketAuthority)})),b.push(K({pubkey:Wu,isWritable:!1})),b.push(K({pubkey:new pe.PublicKey(B.openOrders)})),b.push(K({pubkey:new pe.PublicKey(B.vault.A)})),b.push(K({pubkey:new pe.PublicKey(B.vault.B)})),b.push(K({pubkey:new pe.PublicKey(B.id)})),b.push(K({pubkey:new pe.PublicKey(B.id)})),b.push(K({pubkey:new pe.PublicKey(B.id)})),b.push(K({pubkey:new pe.PublicKey(B.id)})),b.push(K({pubkey:new pe.PublicKey(B.id)})),b.push(K({pubkey:new pe.PublicKey(B.id)})),b.push(K({pubkey:new pe.PublicKey(B.marketId)})),b.push(K({pubkey:new pe.PublicKey(B.marketBids)})),b.push(K({pubkey:new pe.PublicKey(B.marketAsks)})),b.push(K({pubkey:new pe.PublicKey(B.marketEventQueue)})),b.push(K({pubkey:new pe.PublicKey(B.marketBaseVault)})),b.push(K({pubkey:new pe.PublicKey(B.marketQuoteVault)}))}else if(x.version===4){let B=A[I],R=x.status!==1;b.push(K({pubkey:new pe.PublicKey(B.id)})),b.push(K({pubkey:new pe.PublicKey(B.authority),isWritable:!1})),b.push(K({pubkey:new pe.PublicKey(R?B.id:B.marketProgramId)})),b.push(K({pubkey:new pe.PublicKey(R?B.id:B.marketAuthority)})),b.push(K({pubkey:new pe.PublicKey(R?B.id:B.openOrders)})),b.push(K({pubkey:new pe.PublicKey(B.vault.A)})),b.push(K({pubkey:new pe.PublicKey(B.vault.B)})),b.push(K({pubkey:new pe.PublicKey(R?B.id:B.marketId)})),b.push(K({pubkey:new pe.PublicKey(R?B.id:B.marketBids)})),b.push(K({pubkey:new pe.PublicKey(R?B.id:B.marketAsks)})),b.push(K({pubkey:new pe.PublicKey(R?B.id:B.marketEventQueue)})),b.push(K({pubkey:new pe.PublicKey(R?B.id:B.marketBaseVault)})),b.push(K({pubkey:new pe.PublicKey(R?B.id:B.marketQuoteVault)}))}else if(x.version===7){let B=A[I];b.push(K({pubkey:new pe.PublicKey(B.authority)})),b.push(K({pubkey:new pe.PublicKey(B.config.id)})),b.push(K({pubkey:new pe.PublicKey(B.id)})),b.push(K({pubkey:new pe.PublicKey(S?B.vault.A:B.vault.B)})),b.push(K({pubkey:new pe.PublicKey(S?B.vault.B:B.vault.A)})),b.push(K({pubkey:new pe.PublicKey(x.observationId)}))}else throw Error("pool type error")}let h=v([V("insId"),w("amountIn"),w("amountOut"),Q(ce(),y.length,"clmmPriceLimit")]),P=Buffer.alloc(h.span);return h.encode({insId:0,amountIn:d,amountOut:p,clmmPriceLimit:y},P),new pe.TransactionInstruction({keys:b,programId:m,data:P})}function Gd(m,e){if(m)if(e){let t=new Wn.default(m).div(new Wn.default(25));return t.gt(Kt.add(dt))?t:Kt.add(dt)}else{let t=new Wn.default(m).mul(new Wn.default(25));return t.lt(Ct.sub(dt))?t:Ct.sub(dt)}else return e?Kt.add(dt):Ct.sub(dt)}function vl({routeProgram:m,ownerInfo:e,inputMint:t,swapInfo:n}){var o,i,r,a,u,s,c,l,d;if(n.routeType==="amm")if(n.poolInfo[0].version===6){let p=n.poolKey[0],f=Ut(p),y=t.equals(f.mintA.address)?Kt.add(dt):Ct.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 pe.PublicKey(p[f?"mintA":"mintB"].address),new pe.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:[Ud(m,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((d=(l=n.minAmountOut.fee)==null?void 0:l.raw)!=null?d: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 Ot=new he.default(0);function io(m,e){var n,o,i,r,a;let t=(n=m.extensions)==null?void 0:n.feeConfig;if(!!t)return{transferFeeConfigAuthority:fe.PublicKey.default,withdrawWithheldAuthority:fe.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 Zr(m){return m.programId?new fe.PublicKey(m.programId):Pe.TOKEN_PROGRAM_ID}var Hi=class extends rt{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($));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=ye(t);for(let s=0;s<r.length;s++)u.gte(r[s].amount)?(a.addInstruction({instructions:[Mn({tokenAccount:r[s].publicKey,destination:this.scope.ownerPubKey,owner:this.scope.ownerPubKey,programId:n})]}),u.sub(r[s].amount)):a.addInstruction({instructions:[Mn({tokenAccount:r[s].publicKey,destination: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($),d=c.amount.token.mint.equals($),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"&&!d)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:d,owner:this.scope.ownerPubKey,skipCloseAccount:!0,createInfo:{payer:this.scope.ownerPubKey,amount:0},associatedOnly:d?!1:n.associatedOnly,checkCreateATAOwner:n.checkCreateATAOwner});g=P,T&&u.addInstruction(T)}d&&u.addInstruction({endInstructions:[Mn({owner:this.scope.ownerPubKey,destination: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=vl({routeProgram:i,inputMint:p,swapInfo:_(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:d,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:d,blockTimestamp:A}),M=e.toString()===P.poolInfo.mintA.address,D=f.useSOLBalance&&P.poolInfo.mintA.address===$.toBase58(),E=f.useSOLBalance&&P.poolInfo.mintB.address===$.toBase58(),z={},H;!r||r.equals(new Me.default(0))?H=M?Kt.add(new he.default(1)):Ct.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 fe.PublicKey(P.poolInfo.mintA.address),new fe.PublicKey(P.poolInfo.mintB.address)],[Z,ge]=[new fe.PublicKey(P.poolInfo.mintA.programId),new fe.PublicKey(P.poolInfo.mintB.programId)],re=this.scope.account.getAssociatedTokenAccount(J,Z),ke=this.scope.account.getAssociatedTokenAccount(ie,ge);Y.addInstruction({instructions:[(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,re,this.scope.ownerPubKey,J,Z),(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,ke,this.scope.ownerPubKey,ie,ge)]}),(M&&D||!M&&E)&&Y.addInstruction({instructions:[fe.SystemProgram.transfer({fromPubkey:this.scope.ownerPubKey,toPubkey:M?re:ke,lamports:BigInt(T.toString())}),(0,Pe.createSyncNativeInstruction)(M?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:M?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 fe.PublicKey(e),amountIn:t,amountOutMin:I,sqrtPriceLimitX64:H,remainingAccounts:x}));let Fe=qr(S.mintProgramFlag),Oe=this.scope.account.getAssociatedTokenAccount(S.mintA,Fe),Ae=z[S.mintB.toBase58()];if(Y.addInstruction({instructions:[(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Oe,this.scope.ownerPubKey,S.mintA,Fe)]}),!Ae){let ae=S.mintB.equals($),{account:Re,instructionParams:Ft}=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=Re,Ft&&Y.addInstruction(Ft)}return Y.addInstruction({instructions:[qi(S.programId,this.scope.ownerPubKey,B,S.configId,S.platformId,new fe.PublicKey(i),Oe,Ae,S.vaultA,S.vaultB,S.mintA,S.mintB,Fe,L,wn(S.programId,S.platformId,S.mintB).publicKey,kn(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 fe.PublicKey(e),amount:n?T:t,decimal:P.poolInfo[M?"mintA":"mintB"].decimals},{mint:M?ie:J,amount:I,decimal:P.poolInfo[M?"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:d,mintInfo:p,blockTimestamp:f}){var E,z;let y=r>0?new Me.default(r).div(2).toDecimalPlaces(4,Me.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 fe.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 fe.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=hn.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=Zr(A),B=io(A,a==null?void 0:a.epoch),R=n?t:h.minAmountOut.amount.raw,L=Mt.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:d!=null?d:await this.scope.connection.getSlot()}),O=L.amountA.amount.sub((E=L.amountA.fee)!=null?E:new he.default(0)),C=new Me.default(O.toString()),M=new he.default(1e4),D=y?new Me.default(M.sub(new he.default(y*1e4)).toNumber()/M.toNumber()).clampedTo(0,1):new Me.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(D).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:d}){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:d}),x=this.createTxBuilder(p),S={},B=qr(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($),{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 fe.PublicKey(n),R,O,g.vaultA,g.vaultB,g.mintA,g.mintB,B,h,wn(g.programId,g.platformId,g.mintB).publicKey,kn(g.programId,g.creator,g.mintB).publicKey,k.amountA.amount.lt(e)?k.amountA.amount:e,P,r,a)]});let M=g.mintB.toString()===y.poolInfo.mintA.address,D=u.useSOLBalance&&y.poolInfo.mintA.address===$.toBase58(),E=u.useSOLBalance&&y.poolInfo.mintB.address===$.toBase58(),z;!o||o.equals(new Me.default(0))?z=M?Kt.add(new he.default(1)):Ct.sub(new he.default(1)):z=se.priceToSqrtPriceX64(o,y.poolInfo.mintA.decimals,y.poolInfo.mintB.decimals);let[H,Y]=[new fe.PublicKey(y.poolInfo.mintA.address),new fe.PublicKey(y.poolInfo.mintB.address)],[J,ie]=[new fe.PublicKey(y.poolInfo.mintA.programId),new fe.PublicKey(y.poolInfo.mintB.programId)],Z=D?void 0:this.scope.account.getAssociatedTokenAccount(H,J),ge=E?void 0:this.scope.account.getAssociatedTokenAccount(Y,ie);if(!Z){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:M?e:0},associatedOnly:!1,checkCreateATAOwner:s});Z=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:M?0:e},associatedOnly:!1,checkCreateATAOwner:s});ge=re,ke&&x.addInstruction(ke)}return S[y.poolInfo.mintA.address]=Z,S[y.poolInfo.mintB.address]=ge,(!Z||!ge)&&this.logAndCreateError("user do not have token account",{ownerTokenAccountA:Z,ownerTokenAccountB:ge}),x.addInstruction(we.makeSwapBaseInInstructions({poolInfo:y.poolInfo,poolKeys:y.poolKeys,observationId:y.computePoolInfo.observationId,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:Z,tokenAccountB:ge},inputMint:new fe.PublicKey(y.poolKeys[M?"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 fe.PublicKey(y.poolKeys[M?"mintB":"mintA"].address),amount:T,decimal:y.poolKeys[M?"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 Me.default(o).div(2).toDecimalPlaces(4,Me.default.ROUND_DOWN).toNumber():o,d=u;d||(d=await this.scope.launchpad.getRpcPoolInfo({poolId:new fe.PublicKey(n)}));let p=d.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 M=await this.scope.connection.getAccountInfo(d.platformId);A=hn.decode(M.data)}let k=await this.scope.token.getTokenInfo(d.mintA),h=Gt(d.programId).publicKey,P=io(k,i==null?void 0:i.epoch),T=Zr(g),I=io(g,i==null?void 0:i.epoch),x=Mt.sellExactIn({poolInfo:d,amountA:e,protocolFeeRate:d.configInfo.tradeFeeRate,platformFeeRate:A.feeRate,curveType:d.configInfo.curveType,shareFeeRate:r,creatorFeeRate:A.creatorFeeRate,transferFeeConfigA:P,transferFeeConfigB:I,slot:await this.scope.connection.getSlot()}),S=x.amountB,B=new Me.default(S.toString()),R=new he.default(1e4),L=l?new Me.default(R.sub(new he.default(l*1e4)).toNumber()/R.toNumber()).clampedTo(0,1):new Me.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:d,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:d,ownerInfo:p={useSOLBalance:!0},checkCreateATAOwner:f=!1,computeBudgetConfig:y,txVersion:b}){let g=(p==null?void 0:p.feePayer)||this.scope.ownerPubKey,A=d!=null?d: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===$.toBase58(),M=p.useSOLBalance&&T.mintB.address===$.toBase58(),D={},E=this.createTxBuilder(g),[z,H]=[new fe.PublicKey(T.mintA.address),new fe.PublicKey(T.mintB.address)],[Y,J]=[new fe.PublicKey(T.mintA.programId),new fe.PublicKey(T.mintB.programId)],ie=this.scope.account.getAssociatedTokenAccount(z,Y),Z=this.scope.account.getAssociatedTokenAccount(H,J);E.addInstruction({instructions:[(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,ie,this.scope.ownerPubKey,z,Y),(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Z,this.scope.ownerPubKey,H,J)]}),(O&&C||!O&&M)&&E.addInstruction({instructions:[fe.SystemProgram.transfer({fromPubkey:this.scope.ownerPubKey,toPubkey:O?ie:Z,lamports:BigInt(P.amountIn.toString())}),(0,Pe.createSyncNativeInstruction)(O?ie:Z)]}),D[T.mintA.address]=ie,D[T.mintB.address]=Z,(!ie||!Z)&&this.logAndCreateError("user do not have token account",{ownerTokenAccountA:ie,ownerTokenAccountB:Z});let ge=i!=null?i:h;E.addInstruction({instructions:[qo(T.programId,this.scope.ownerPubKey,new fe.PublicKey(ge.authority),new fe.PublicKey(ge.config.id),T.id,O?ie:Z,O?Z:ie,new fe.PublicKey(ge.vault[O?"A":"B"]),new fe.PublicKey(ge.vault[O?"B":"A"]),new fe.PublicKey(O?Y:J!=null?J:Pe.TOKEN_PROGRAM_ID),new fe.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=qr(I.mintProgramFlag),ke=this.scope.account.getAssociatedTokenAccount(I.mintA,re),Fe=D[I.mintB.toBase58()];if(E.addInstruction({instructions:[(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,ke,this.scope.ownerPubKey,I.mintA,re)]}),!Fe){let Oe=I.mintB.equals($),{account:Ae,instructionParams:ae}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:B,mint:I.mintB,notUseTokenAccount:Oe,owner:this.scope.ownerPubKey,skipCloseAccount:!Oe,createInfo:Oe?{payer:this.scope.ownerPubKey,amount:P.minAmountOut}:void 0,associatedOnly:!1,checkCreateATAOwner:f});Fe=Ae,ae&&E.addInstruction(ae)}return E.addInstruction({instructions:[qi(I.programId,this.scope.ownerPubKey,x,I.configId,I.platformId,new fe.PublicKey(o),ke,Fe,I.vaultA,I.vaultB,I.mintA,I.mintB,re,B,wn(I.programId,I.platformId,I.mintB).publicKey,kn(I.programId,I.creator,I.mintB).publicKey,S.amountB.lt(P.minAmountOut)?S.amountB:P.minAmountOut,L,a,u)]}),E.addCustomComputeBudget(y),E.versionBuild({txVersion:b,extInfo:{routes:[{mint:new fe.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:d}){var M,D;let p=i>0?new Me.default(i).div(2).toDecimalPlaces(4,Me.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 fe.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 E=await this.scope.connection.getAccountInfo(g.platformId);A=hn.decode(E.data)}let k=d!=null?d:await this.scope.token.getTokenInfo(g.mintA),h=Gt(g.programId).publicKey,P=io(k,r==null?void 0:r.epoch),T=Zr(b),I=io(b,r==null?void 0:r.epoch),x=await this.scope.cpmm.computeSwapAmount({pool:f,amountIn:t,outputMint:new fe.PublicKey(b.address),slippage:p}),S=x.minAmountOut,B=Mt.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((M=B.amountA.fee)!=null?M:new he.default(0)),L=new Me.default(R.toString()),O=new he.default(1e4),C=p?new Me.default(O.sub(new he.default(p*1e4)).toNumber()/O.toNumber()).clampedTo(0,1):new Me.default(1);return{cpmmPoolData:f,cpmmComputInfo:x,launchPoolInfo:g,launchAuthProgramId:h,launchMintTransferFeeConfig:P,launchMintProgramB:T,launchMintTransferFeeConfigB:I,launchSwapInfo:B,outAmount:B.amountA.amount.sub((D=B.amountA.fee)!=null?D: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:d,slot:p,mintInfo:f,blockTimestamp:y}){var Z,ge;let b=r>0?new Me.default(r).div(2).toDecimalPlaces(4,Me.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 fe.PublicKey(i)})),k.address!==h.mintB.toBase58())throw new Error(`clmm swap mint(${k.address}) != launch pool mintB(${h.mintB.toBase58()})`);let P=d;if(!P){let re=await this.scope.connection.getAccountInfo(h.platformId);P=hn.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=Zr(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 fe.PublicKey(k.address),slippage:b}),[C,M]=[R.minAmountOut.amount.raw,O.minAmountOut],D=C.gte(M)?"clmm":"cpmm",E=C.gte(M)?C:M,z=Mt.buyExactIn({poolInfo:h,amountB:E,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((Z=z.amountA.fee)!=null?Z:new he.default(0)),Y=new Me.default(H.toString()),J=new he.default(1e4),ie=b?new Me.default(J.sub(new he.default(b*1e4)).toNumber()/J.toNumber()).clampedTo(0,1):new Me.default(1);return{clmmPoolData:g,clmmComputeAmount:{maxClmmAmountIn:t,clmmAmountOut:E,remainingAccounts:R.remainingAccounts},clmmComputeInfo:R,cpmmComputInfo:O,swapPoolType:D,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([F("baseMint"),F("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([F("mintA"),F("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}}),d=(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:d}}getAllRoute({inputMint:e,outputMint:t,clmmPools:n,ammPools:o,cpmmPools:i}){e=e.toString()===fe.PublicKey.default.toString()?$:e,t=t.toString()===fe.PublicKey.default.toString()?$:t;let r={},a={},u={},s=[],c={};for(let d of n!=null?n:[]){if((d.mintA.equals(e)&&d.mintB.equals(t)||d.mintA.equals(t)&&d.mintB.equals(e))&&(s.push(d),a[d.id.toString()]=d),d.mintA.equals(e)){let p=d.mintB.toString();c[p]===void 0&&(c[p]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p].in.push(d)}if(d.mintB.equals(e)){let p=d.mintA.toString();c[p]===void 0&&(c[p]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p].in.push(d)}if(d.mintA.equals(t)){let p=d.mintB.toString();c[p]===void 0&&(c[p]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p].out.push(d)}if(d.mintB.equals(t)){let p=d.mintA.toString();c[p]===void 0&&(c[p]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p].out.push(d)}}let l=[];for(let d of o)(d.mintA.equals(e)&&d.mintB.equals(t)||d.mintA.equals(t)&&d.mintB.equals(e))&&(s.push(d),r[d.id.toBase58()]=d,l.push(d)),d.mintA.equals(e)&&(c[d.mintB.toBase58()]===void 0&&(c[d.mintB.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[d.mintB.toBase58()].in.push(d)),d.mintB.equals(e)&&(c[d.mintA.toBase58()]===void 0&&(c[d.mintA.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[d.mintA.toBase58()].in.push(d)),d.mintA.equals(t)&&(c[d.mintB.toBase58()]===void 0&&(c[d.mintB.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[d.mintB.toBase58()].out.push(d)),d.mintB.equals(t)&&(c[d.mintA.toBase58()]===void 0&&(c[d.mintA.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[d.mintA.toBase58()].out.push(d));for(let d of i)(d.mintA.equals(e)&&d.mintB.equals(t)||d.mintA.equals(t)&&d.mintB.equals(e))&&(s.push(d),u[d.id.toBase58()]=d),d.mintA.equals(e)&&(c[d.mintB.toBase58()]===void 0&&(c[d.mintB.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[d.mintB.toBase58()].in.push(d)),d.mintB.equals(e)&&(c[d.mintA.toBase58()]===void 0&&(c[d.mintA.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[d.mintA.toBase58()].in.push(d)),d.mintA.equals(t)&&(c[d.mintB.toBase58()]===void 0&&(c[d.mintB.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[d.mintB.toBase58()].out.push(d)),d.mintB.equals(t)&&(c[d.mintA.toBase58()]===void 0&&(c[d.mintA.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[d.mintA.toBase58()].out.push(d));for(let d of Object.keys(c)){if(c[d].in.length===1&&c[d].out.length===1&&c[d].in[0].id.equals(c[d].out[0].id)){delete c[d];continue}if(c[d].in.length===0||c[d].out.length===0){delete c[d];continue}let p=c[d];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 fe.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 fe.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 fe.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:d,computePoolTickData:p}=await this.scope.clmm.getComputeClmmPoolInfos({clmmPoolsRpcInfo:l,mintInfos:a}),f=Object.keys(e.routePathDict).reduce((y,b)=>_(N({},y),{[b]:_(N({},e.routePathDict[b]),{mintProgram:a[b].programId,mDecimals:a[b].decimals,in:e.routePathDict[b].in.map(g=>r[g.id.toBase58()]||d[g.id.toBase58()]||c[g.id.toBase58()]),out:e.routePathDict[b].out.map(g=>r[g.id.toBase58()]||d[g.id.toBase58()]||c[g.id.toBase58()])})}),{});return{mintInfos:a,ammPoolsRpcInfo:i,ammSimulateCache:r,clmmPoolsRpcInfo:l,computeClmmPoolInfo:d,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 d=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(d),f=new _e(e.token,p),y=c===void 0?void 0:{feeAmount:d,feeAccount:c.feeAccount},b=_(N({},t),{address:Nt(t.address).toString()}),g=[];for(let R of n)try{g.push(_(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(D=>{try{return{pool:D,data:this.computeAmountOut({itemPool:D,tickCache:r,simulateCache:i,chainTime:u,epochInfo:s,slippage:a,outputToken:O,amountIn:f,blockTimestamp:l})}}catch(E){this.logDebug("route in error",D.version,D.id.toString(),E.message);return}}).sort((D,E)=>{var Y,J,ie,Z;let z=D===void 0?Ot:D.data.amountOut.amount.raw.sub((J=(Y=D.data.amountOut.fee)==null?void 0:Y.raw)!=null?J:Ot),H=E===void 0?Ot:E.data.amountOut.amount.raw.sub((Z=(ie=E.data.amountOut.fee)==null?void 0:ie.raw)!=null?Z:Ot);return z.lt(H)?1:-1})[0];if(C===void 0)continue;let M=new _e(hi(O),C.data.amountOut.amount.raw.sub((k=(A=C.data.amountOut.fee)==null?void 0:A.raw)!=null?k:Ot));for(let D of L.out)try{let E=this.computeAmountOut({itemPool:D,tickCache:r,simulateCache:i,chainTime:u,epochInfo:s,slippage:a,outputToken:b,amountIn:M,blockTimestamp:l});g.push(_(N({},E),{allTrade:!!(C.data.allTrade&&E.allTrade),amountIn:C.data.amountIn,amountOut:E.amountOut,minAmountOut:E.minAmountOut,currentPrice:void 0,executionPrice:new Me.default(new qt({baseToken:C.data.amountIn.amount.token,denominator:C.data.amountIn.amount.raw,quoteToken:E.amountOut.amount.token,numerator:E.amountOut.amount.raw.sub((P=(h=E.amountOut.fee)==null?void 0:h.raw)!=null?P:Ot)}).toFixed()),priceImpact:new Me.default(C.data.priceImpact.add(E.priceImpact).toFixed()),fee:[C.data.fee[0],E.fee[0]],routeType:"route",poolInfoList:[C.pool,D],remainingAccounts:[C.data.remainingAccounts[0],E.remainingAccounts[0]],minMiddleAmountFee:(T=E.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:Ot).add((B=(S=E.amountOut.fee)==null?void 0:S.raw)!=null?B:Ot)):void 0,middleToken:C.data.amountOut.amount.token,poolReady:C.data.poolReady&&E.poolReady,poolType:[C.data.poolType,E.poolType],feeConfig:y,expirationTime:En(C.data.expirationTime,E.expirationTime)}))}catch(E){this.logDebug("route out error",D.version,D.id.toString(),E.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(Ot)?-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=kt({address:Nt(e.token.mint).toBase58(),decimals:e.token.decimals,programId:e.token.isToken2022?Pe.TOKEN_2022_PROGRAM_ID.toBase58():Pe.TOKEN_PROGRAM_ID.toBase58(),extensions:{}}),d=[];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));d.push(_(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 M,D,E,z;let O=R===void 0?Ot:R.data.amountIn.amount.raw.add((D=(M=R.data.amountIn.fee)==null?void 0:M.raw)!=null?D:Ot),C=L===void 0?Ot:L.data.amountIn.amount.raw.add((z=(E=L.data.amountIn.fee)==null?void 0:E.raw)!=null?z:Ot);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:Ot));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));d.push(_(N({},L),{allTrade:!!(L.allTrade&&S.data.allTrade),amountIn:L.amountIn,amountOut:S.data.amountOut,maxAmountIn:L.maxAmountIn,currentPrice:void 0,executionPrice:new Me.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:Ot)}).toFixed()),priceImpact:new Me.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:Ot).add((P=(h=L.amountOut.fee)==null?void 0:h.raw)!=null?P:Ot)):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 d.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(Ot)?-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:d,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:d,minAmountOut:p,currentPrice:new Me.default(y.toFixed()),executionPrice:new Me.default(b.toFixed()),priceImpact:new Me.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:d,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(_(N({},a),{amount:d})),fee:void 0,expirationTime:void 0},minAmountOut:{amount:bt(_(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:d,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(_(N({},a),{amount:c})),fee:void 0,expirationTime:void 0},minAmountOut:{amount:bt(_(N({},a),{amount:l})),fee:void 0,expirationTime:void 0},currentPrice:d,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:d,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 fe.PublicKey(c.address),slippage:r,epochInfo:i,blockTimestamp:s});return{allTrade:l,amountOut:{amount:bt(_(N({},u),{amount:d.amount})),fee:d.fee?bt(_(N({},u),{amount:d.fee})):void 0,expirationTime:void 0},amountIn:{amount:bt(_(N({},c),{amount:p.amount})),fee:p.fee?bt(_(N({},c),{amount:p.fee})):void 0,expirationTime:p.expirationTime},maxAmountIn:{amount:bt(_(N({},c),{amount:f.amount})),fee:f.fee?bt(_(N({},c),{amount:f.fee})):void 0,expirationTime:f.expirationTime},currentPrice:new Me.default(b.toFixed()),executionPrice:new Me.default(g.toFixed()),priceImpact:new Me.default(A.toFixed()),fee:[bt(_(N({},c),{amount:k}))],remainingAccounts:[h],routeType:"amm",poolInfoList:[e],poolReady:e.startTime<o,poolType:"CLMM",slippage:r,clmmExPriceX64:[go(g)],expirationTime:En(d.expirationTime,y)}}else if(e.version===7){let{allTrade:l,executionPrice:d,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(_(N({},u),{amount:f})),fee:void 0,expirationTime:void 0},amountIn:{amount:bt(_(N({},c),{amount:p})),fee:void 0,expirationTime:void 0},maxAmountIn:{amount:bt(_(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:d,priceImpact:y,fee:[bt(_(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:d,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(_(N({},u),{amount:a})),fee:void 0,expirationTime:void 0},amountIn:{amount:bt(_(N({},c),{amount:l})),fee:void 0,expirationTime:void 0},maxAmountIn:{amount:bt(_(N({},c),{amount:d})),fee:void 0,expirationTime:void 0},currentPrice:p,executionPrice:f,priceImpact:y,fee:[bt(_(N({},c),{amount:j}))],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 fe.PublicKey(c)})))).forEach(c=>{if(!c.accountInfo)return;let l=_s.decode(c.accountInfo.data);a[c.pubkey.toBase58()]={marketId:c.pubkey.toString(),marketProgramId:c.accountInfo.owner.toString(),marketAuthority:Qr.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:_(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:As({programId:new fe.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:fe.PublicKey.default.toBase58(),marketBaseVault:fe.PublicKey.default.toBase58(),marketQuoteVault:fe.PublicKey.default.toBase58(),marketBids:fe.PublicKey.default.toBase58(),marketAsks:fe.PublicKey.default.toBase58(),marketEventQueue:fe.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:kt({address:s.mintLp.toBase58(),programId:Pe.TOKEN_PROGRAM_ID.toBase58(),decimals:s.lpDecimals}),config:_(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"),_l=require("@solana/spl-token"),Es=te(require("bn.js"));var Dt=class extends rt{static getPdaPoolId(e,t){return le([Dt.SEED_CONFIG.pool.id,t.toBuffer()],e)}static getPdaOwnerId(e,t,n,o){return le([Dt.SEED_CONFIG.owner.id,t.toBuffer(),n.toBuffer(),Buffer.from(new Es.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),d=c%n.length,p=r[d],f=a[c],y=u[d],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 Es.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(je.WSOL.mint),createInfo:{payer:i,amount:0},skipCloseAccount:!s.mintAddress.equals(je.WSOL.mint),associatedOnly:s.mintAddress.equals(je.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 d of c.tokenInfo){let{account:p,instructionParams:f}=await this.scope.account.getOrCreateTokenAccount({mint:d.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:d.mintAddress.equals(je.WSOL.mint),createInfo:{payer:i,amount:0},skipCloseAccount:!d.mintAddress.equals(je.WSOL.mint),associatedOnly:d.mintAddress.equals(je.WSOL.mint)?!1:t.associatedOnly});f&&o.addInstruction(f),p&&(r[d.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 Da(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:_l.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([Be(8),V("bump"),V("status"),w("openTime"),w("endTime"),F("ammId"),Q(v([V("mintDecimals"),F("mintAddress"),F("mintVault"),w("perLpLoss"),w("totalClaimedAmount")]),Dt.CLAIMED_NUM,"tokenInfo"),Q(w(),10,"padding")]),mn.OWNER_LAYOUT=v([Be(8),V("bump"),V("version"),F("poolId"),F("owner"),w("lpAmount"),Q(v([F("mintAddress"),w("debtAmount"),w("claimedAmount")]),Dt.CLAIMED_NUM,"tokenInfo"),Q(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 Ws=require("@solana/spl-token"),$o=require("@solana/web3.js"),jo=te(require("bn.js"));var Yt=require("@solana/web3.js"),Zo=require("@solana/spl-token");function zd(m="accountFlags"){let e=new sr(m);return e.addBoolean("initialized"),e.addBoolean("market"),e.addBoolean("openOrders"),e.addBoolean("requestQueue"),e.addBoolean("eventQueue"),e.addBoolean("bids"),e.addBoolean("asks"),e}var Ds=v([Be(5),zd("accountFlags"),F("ownAddress"),w("vaultSignerNonce"),F("baseMint"),F("quoteMint"),F("baseVault"),w("baseDepositsTotal"),w("baseFeesAccrued"),F("quoteVault"),w("quoteDepositsTotal"),w("quoteFeesAccrued"),w("quoteDustThreshold"),F("requestQueue"),F("eventQueue"),F("bids"),F("asks"),w("baseLotSize"),w("quoteLotSize"),w("feeRateBps"),w("referrerRebatesAccrued"),Be(7)]);function Xd({programId:m,marketInfo:e}){let t=v([V("version"),Je("instruction"),w("baseLotSize"),w("quoteLotSize"),ze("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:m,data:o})}async function $r({connection:m,wallet:e,marketInfo:t}){var r,a,u,s,c,l,d,p;let n=new Yt.Transaction,o=await m.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 m.getMinimumBalanceForRentExemption(Ds.span),space:Ds.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 m.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 m.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 m.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 m.getMinimumBalanceForRentExemption((d=t.orderbookQueueSpace)!=null?d:65536+12),space:t.lowestFeeMarket?14524:(p=t.orderbookQueueSpace)!=null?p:65536+12,programId:t.programId}),Xd({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 rt{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:d,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=ut({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-market`}),A=ut({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-request`}),k=ut({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-event`}),h=ut({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-bids`}),P=ut({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-asks`}),T=ut({fromPublicKey:y,programId:Ws.TOKEN_PROGRAM_ID,assignSeed:b&&`${b}-baseVault`}),I=ut({fromPublicKey:y,programId:Ws.TOKEN_PROGRAM_ID,assignSeed:b&&`${b}-quoteVault`}),x=0,S=new jo.default(100);function B(){let E=new jo.default(0);for(;;)try{return{vaultOwner:$o.PublicKey.createProgramAddressSync([g.publicKey.toBuffer(),E.toArrayLike(Buffer,"le",8)],i),vaultSignerNonce:E}}catch{if(E.iaddn(1),E.gt(new jo.default(25555)))throw Error("find vault owner error")}}let{vaultOwner:R,vaultSignerNonce:L}=B(),O=new jo.default(Math.round(10**e.decimals*n)),C=new jo.default(Math.round(n*10**t.decimals*o));if(O.eq(j))throw Error("lot size is too small");if(C.eq(j))throw Error("tick size or lot size is too small");let M=await $r({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}}),D=this.createTxBuilder(f);D.addInstruction({instructions:M[0].transaction.instructions,signers:M[0].signer});for await(let E of M.slice(1,M.length))D.addInstruction({instructions:E.transaction.instructions,signers:E.signer,instructionTypes:E.instructionTypes});return l===0?D.sizeCheckBuildV0({computeBudgetConfig:d,address:{marketId:g.publicKey,requestQueue:A.publicKey,eventQueue:k.publicKey,bids:h.publicKey,asks:P.publicKey,baseVault:T.publicKey,quoteVault:I.publicKey,baseMint:new $o.PublicKey(e.mint),quoteMint:new $o.PublicKey(t.mint)}}):D.sizeCheckBuild({computeBudgetConfig:d,address:{marketId:g.publicKey,requestQueue:A.publicKey,eventQueue:k.publicKey,bids:h.publicKey,asks:P.publicKey,baseVault:T.publicKey,quoteVault:I.publicKey,baseMint:new $o.PublicKey(e.mint),quoteMint:new $o.PublicKey(t.mint)}})}};var eI=new qn.default(2),tI=new qn.default(3),nI=new qn.default(5),pa=new qn.default(10),oI=new qn.default(100),iI=new qn.default(1e3),rI=new qn.default(1e4);function wa(m){return pa.pow(ye(m))}function jr(m,e){let t=m.divmod(e);return t.mod.isZero()?t.div:m.isNeg()===e.isNeg()?t.div.iaddn(1):t.div}function _i(m,e,t){return m.mul(e).add(t).sub(new qn.default(1)).div(t)}function Lr(m,e,t){return m.mul(e).div(t)}function la(m,e=1,t=[]){let n=[...m];if(e<=0)return t;for(;n.length;)t.push(n.splice(0,e));return t}var Bn=class{constructor(e){this._owner=e}get publicKey(){return Bn.isKeyPair(this._owner)?this._owner.publicKey:this._owner}get signer(){return Bn.isKeyPair(this._owner)?this._owner:void 0}get isKeyPair(){return Bn.isKeyPair(this._owner)}get isPublicKey(){return Bn.isPublicKey(this._owner)}static isKeyPair(e){return e.secretKey!==void 0}static isPublicKey(e){return!Bn.isKeyPair(e)}};var Ye=te(require("bn.js")),Ln=1e4;function ht(m,e,t,n){if(e===void 0)return{amount:m,fee:void 0,expirationTime:void 0};let o=_(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 Ye.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 Ye.default(i.maximumFee.toString());return{amount:m.add(u),fee:u,expirationTime:a}}else{let u=ao(m.mul(new Ye.default(Ln)),new Ye.default(Ln-i.transferFeeBasisPoints)),s=new Ye.default(i.maximumFee.toString()),c=u.sub(m).gt(s)?m.add(s):u,l=ao(c.mul(new Ye.default(i.transferFeeBasisPoints)),new Ye.default(Ln)),d=l.gt(r)?r:l;return{amount:c,fee:d,expirationTime:a}}else{let u=ao(m.mul(new Ye.default(i.transferFeeBasisPoints)),new Ye.default(Ln)),s=u.gt(r)?r:u;return{amount:m,fee:s,expirationTime:a}}}function En(m,e){return m===void 0?e:e===void 0?m:Math.min(m,e)}function ao(m,e){let{div:t,mod:n}=m.divmod(e);return n.gt(new Ye.default(0))?t.add(new Ye.default(1)):t}function So(m,e){if(m.isZero())return new Ye.default(0);let t=m.div(e);return t.isZero()?new Ye.default(1):m.mod(e).gt(new Ye.default(0))?t.add(new Ye.default(1)):t}function Xi(m,e,t){if(e===void 0)return{amount:m,fee:void 0,expirationTime:void 0};let n=Math.floor(t/432e3),o=n<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,i=new Ye.default(o.maximumFee.toString()),r=n<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*432e3-t)*400/1e3:void 0,a=ao(m.mul(new Ye.default(o.transferFeeBasisPoints)),new Ye.default(Ln)),u=a.gt(i)?i:a;return{amount:m,fee:u,expirationTime:r}}function Ho(m,e,t){if(e===void 0)return{amount:m,fee:void 0,expirationTime:void 0};let n=Math.floor(t/432e3),o=n<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,i=new Ye.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 Ye.default(o.maximumFee.toString());return{amount:m.add(a),fee:a,expirationTime:r}}else{let a=ao(m.mul(new Ye.default(Ln)),new Ye.default(Ln-o.transferFeeBasisPoints)),u=new Ye.default(o.maximumFee.toString()),s=a.sub(m).gt(u)?m.add(u):a,c=ao(s.mul(new Ye.default(o.transferFeeBasisPoints)),new Ye.default(Ln)),l=c.gt(i)?i:c;return{amount:s,fee:l,expirationTime:r}}}var at={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"},Vl=_(N({},at),{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 El="ray_tab_hash",qs="ray_req_hash",Hd=()=>{if(typeof window===void 0)return"";let m=sessionStorage.getItem(El);return m||(m=`ray-${Date.now()}`,sessionStorage.setItem(El,m)),m},Jr=async n=>{var o=n,{logCount:m=1e3,removeLastLog:e}=o,t=$e(o,["logCount","removeLastLog"]);if(typeof window===void 0)return new Promise(r=>r());let i=JSON.parse(localStorage.getItem(qs)||"[]").slice(0,m-1);e&&i.pop(),new Blob([JSON.stringify(t.data)]).size>1024&&(t.data=JSON.stringify(t.data).substring(0,200)+"..."),i.unshift(_(N({},t),{time:Date.now(),session:Hd()}));try{localStorage.setItem(qs,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(qs,JSON.stringify(i)),r=!0}catch{r=!1}}return new Promise(u=>u())}return Jr(_(N({},t),{logCount:m,removeLastLog:!0}))}};var ea=xe("Raydium_Api"),Us=new Map,Gs=new Map;var ta=class{constructor({cluster:e,timeout:t,logRequests:n,logCount:o,urlConfigs:i}){this.cluster=e,this.urlConfigs=i||{},this.logCount=o||1e3,this.api=zs.default.create({baseURL:this.urlConfigs.BASE_HOST||(this.cluster==="devnet"?Vl.BASE_HOST:at.BASE_HOST),timeout:t}),this.api.interceptors.request.use(r=>{let{method:a,baseURL:u,url:s}=r;return ea.debug(`${a==null?void 0:a.toUpperCase()} ${u}${s}`),r},r=>(ea.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:d}=a;return n&&Jr({status:s,url:`${l}${d}`,params:a.params,data:u,logCount:this.logCount}),ea.debug(`${c==null?void 0:c.toUpperCase()} ${l}${d} ${s}`),u},r=>{let{config:a,response:u={}}=r,{status:s}=u,{method:c,baseURL:l,url:d}=a;return n&&Jr({status:s,url:`${l}${d}`,params:a.params,data:r.message,logCount:this.logCount}),ea.error(`${c.toUpperCase()} ${l}${d} ${s||r.message}`),Promise.reject(r)})}async getClmmConfigs(){return(await this.api.get(this.urlConfigs.CLMM_CONFIG||at.CLMM_CONFIG)).data}async getClmmDynamicConfigs(){return(await this.api.get(this.urlConfigs.CLMM_DYNAMIC_CONFIG||at.CLMM_DYNAMIC_CONFIG)).data}async getCpmmConfigs(){return(await this.api.get(this.urlConfigs.CPMM_CONFIG||at.CPMM_CONFIG)).data}async getClmmPoolLines(e){return(await this.api.get(`${this.urlConfigs.POOL_POSITION_LINE||at.POOL_POSITION_LINE}?id=${e}`)).data}async getBlockSlotCountForSecond(e){if(!e)return 2;let n=(await zs.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||at.CHAIN_TIME)).data}async getRpcs(){return this.api.get(this.urlConfigs.RPCS||at.RPCS)}async getTokenList(){return(await this.api.get(this.urlConfigs.TOKEN_LIST||at.TOKEN_LIST)).data}async getJupTokenList(){return(await this.api.get("",{baseURL:this.urlConfigs.JUP_TOKEN_LIST||at.JUP_TOKEN_LIST})).map(t=>_(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||at.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||at.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||at.POOL_SEARCH_BY_ID)+`?ids=${t}`)).data}async fetchPoolKeysById(e){let{idList:t}=e,n=[],o=t.filter(r=>Us.has(r)?(n.push(Us.get(r)),!1):!0),i=[];return o.length&&(i=(await this.api.get((this.urlConfigs.POOL_KEY_BY_ID||at.POOL_KEY_BY_ID)+`?ids=${o.join(",")}`)).data.filter(Boolean),i.forEach(a=>{Us.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&&Nt(t).toBase58(),n&&n!=="undefined"?Nt(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||at.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||at.POOL_SEARCH_LP)+`?lps=${t}`)).data}async fetchFarmInfoById(e){let{ids:t}=e;return(await this.api.get((this.urlConfigs.FARM_INFO||at.FARM_INFO)+`?ids=${t}`)).data}async fetchFarmKeysById(e){let{ids:t}=e;return(await this.api.get((this.urlConfigs.FARM_KEYS||at.FARM_KEYS)+`?ids=${t}`)).data}async fetchAvailabilityStatus(){return(await this.api.get(this.urlConfigs.CHECK_AVAILABILITY||at.CHECK_AVAILABILITY)).data}async fetchLaunchConfigs(){var t;if((t=Gs.get(this.cluster))!=null&&t.length)return Gs.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 Gs.set(this.cluster,e.data.data),e.data.data}async fetchFarmPositions(e=""){return(await this.api.get(`${this.urlConfigs.OWNER_BASE_HOST||at.OWNER_BASE_HOST}`+(this.urlConfigs.OWNER_STAKE_FARMS||at.OWNER_STAKE_FARMS).replace("{owner}",e))).data}async fetchCpmmLockInfo(e){return await this.api.get(`${this.urlConfigs.CPMM_LOCK||at.CPMM_LOCK}?id=${e.toString()}`)}};var na="please provide owner in load() initialization or you can set by calling raydium.setOwner(owner)",Dl="please provide connection in load() initialization or set it by raydium.setConnection(connection)";var Ko=require("@solana/web3.js");var mt=require("@solana/spl-token");var Qi=class extends rt{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:mt.TOKEN_PROGRAM_ID},o.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:mt.TOKEN_2022_PROGRAM_ID},o.commitment)]),{tokenAccounts:u,tokenAccountRawInfos:s}=Mu({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=mt.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||mt.TOKEN_PROGRAM_ID),d=this.getAssociatedTokenAccount(n,new Ko.PublicKey(l)),p=(a?[]:this.tokenAccountRawInfos).filter(k=>k.accountInfo.mint.equals(n)&&(!i||k.pubkey.equals(d))).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,mt.createAssociatedTokenAccountIdempotentInstruction)(o.payer||r,d,r,n,l),h=this.tokenAccountRawInfos.find(P=>P.pubkey.equals(d));if(s){let P=await this.scope.connection.getAccountInfo(d);if(P===null)(y=f.instructions)==null||y.push(k),f.instructionTypes.push(X.CreateATA);else if(!(P.owner.equals(l)&&mt.AccountLayout.decode(P.data).mint.equals(n)&&mt.AccountLayout.decode(P.data).owner.equals(r)))throw Error(`create ata check error -> mint: ${n.toString()}, ata: ${d.toString()}`)}else h===void 0&&(f.instructions.push(k),f.instructionTypes.push(X.CreateATA));if(n.equals($)&&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(vu({source:P.addresses.newAccount,destination:d,owner:this.scope.ownerPubKey,amount:o.amount,tokenProgram:mt.TOKEN_PROGRAM_ID})),f.instructionTypes.push(X.TransferAmount))}return!u&&h===void 0&&(f.endInstructions.push(Mn({owner:r,destination:r,tokenAccount:d,programId:l})),f.endInstructionTypes.push(X.CloseAccount)),{account:d,instructionParams:f}}else{let k=ut({fromPublicKey:r,programId:l,assignSeed:c}),h=await this.scope.connection.getMinimumBalanceForRentExemption(mt.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:mt.AccountLayout.span,programId:l});return f.instructions.push(P,Ra({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,destination:r,tokenAccount:k.publicKey,programId:l})),f.endInstructionTypes.push(X.CloseAccount)),{account:k.publicKey,instructionParams:f}}}async checkOrCreateAta({mint:t,programId:n=mt.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,mt.createAssociatedTokenAccountIdempotentInstruction)(r,s,r,t,n);a.instructions=[c],a.instructionTypes=[X.CreateATA],i=s}return o&&$.toBase58()===t.toBase58()&&(a.endInstructions=[Mn({owner:r,destination: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=mt.TOKEN_PROGRAM_ID,tokenAccount:a,payer:u=this.scope.ownerPubKey,bypassAssociatedCheck:s,skipCloseAccount:c,checkCreateATAOwner:l}=t,d=this.getAssociatedTokenAccount(i,r);if(new Ko.PublicKey($).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"&&!d.equals(a)&&!s){let p=[],f=(0,mt.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,d,this.scope.ownerPubKey,i,r);if(l){let y=await this.scope.connection.getAccountInfo(d);if(y===null)p.push(f);else if(!(y.owner.equals(mt.TOKEN_PROGRAM_ID)&&mt.AccountLayout.decode(y.data).mint.equals(i)&&mt.AccountLayout.decode(y.data).owner.equals(this.scope.ownerPubKey)))throw Error(`create ata check error -> mint: ${i.toString()}, ata: ${d.toString()}`)}else p.push(f);return{tokenAccount:d,instructions:p,instructionTypes:[X.CreateATA]}}return{tokenAccount:a}}async processTokenAccount(t){let{mint:n,programId:o=mt.TOKEN_PROGRAM_ID,amount:i,useSOLBalance:r,handleTokenAccount:a,feePayer:u}=t,s,c=this.createTxBuilder(u);if(n.equals(new Ko.PublicKey($))&&r){let l=await this.handleTokenAccount({side:"in",amount:i||0,mint:n,bypassAssociatedCheck:!0,programId:o}),{tokenAccount:p}=l,f=$e(l,["tokenAccount"]);s=p,c.addInstruction(f)}else if(s=await this.getCreatedTokenAccount({mint:n,associatedOnly:!1,programId:o}),!s&&a){let d=await this.scope.account.handleTokenAccount({side:"in",amount:0,mint:n,bypassAssociatedCheck:!0,programId:o}),{tokenAccount:p}=d,f=$e(d,["tokenAccount"]);s=p,c.addInstruction(f)}return N({tokenAccount:s},c.AllTxData)}};var Ke=require("@solana/web3.js"),Xs=require("@solana/spl-token");var Un=te(require("decimal.js"));var Gn=te(require("bn.js")),Zi=class extends rt{async _getUserRewardInfo({payer:e,rewardInfo:t}){if(t.mint.equals(xt)){let n=await Qn({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:e,amount:Wa(_(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 Ke.PublicKey(e.lpMint.address),lockInfo:{lockMint:(I=a==null?void 0:a.mint)!=null?I:Gu,lockVault:(x=a==null?void 0:a.vault)!=null?x:zu},version:6,rewardInfos:t,programId:o},c=this.createTxBuilder(r),l=n!=null?n:this.scope.ownerPubKey,d=ut({fromPublicKey:l,programId:s.programId}),p=await this.scope.connection.getMinimumBalanceForRentExemption(fi.span);c.addInstruction({instructions:[Ke.SystemProgram.createAccountWithSeed({fromPubkey:l,basePubkey:l,seed:d.seed,newAccountPubkey:d.publicKey,lamports:p,space:fi.span,programId:s.programId})]});let{publicKey:f,nonce:y}=nc({programId:new Ke.PublicKey(s.programId),poolId:d.publicKey}),b=gi({programId:s.programId,poolId:d.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($n[S.rewardType])&&this.logAndCreateError("rewardType error",S.rewardType),Number(S.perSecond)<=0&&this.logAndCreateError("rewardPerSecond error",S.perSecond),g.push(oc(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(xt)?new Ke.PublicKey(vt.address):S.mint;A.push({rewardMint:L,rewardVault:gi({programId:s.programId,poolId:d.publicKey,mint:L,type:"rewardVault"}),userRewardToken:B})}let{account:k,instructionParams:h}=await this.scope.account.getOrCreateTokenAccount({mint:new Ke.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}=ac({farmId:d.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:d.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(xt)?new Ke.PublicKey(vt.address):n.mint,l=u.rewardInfos.findIndex(A=>new Ke.PublicKey(A.mint.address).equals(c)),d=a.rewardInfos[l];d||this.logAndCreateError("configuration does not exist","rewardMint",c);let p=(g=d.vault)!=null?g:xt,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:[Ua({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(d=>{d.openTime>=d.endTime&&this.logAndCreateError("start time error","newRewardInfo",d)});let s=t||this.scope.ownerPubKey,c=this.createTxBuilder(i);for(let d of n){let p=d.mint.equals(xt)?new Ke.PublicKey(vt.address):d.mint,f=u.rewardInfos.findIndex(h=>new Ke.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:xt,{rewardPubKey:g,newInstruction:A}=await this._getUserRewardInfo({rewardInfo:d,payer:s});A&&c.addInstruction(A),g||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts);let k=Ua({payer:this.scope.ownerPubKey,rewardVault:b,userRewardTokenPub:g,farmKeys:u,rewardInfo:d});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(xt)?new Ke.PublicKey(vt.address):o.mint,d=gi({programId:new Ke.PublicKey(n.programId),poolId:new Ke.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:[Ga({payer:this.scope.ownerPubKey,userRewardTokenPub:p,farmKeys:u,rewardVault:d,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 d=l.mint.equals(xt)?new Ke.PublicKey(vt.address):l.mint,p=gi({programId:new Ke.PublicKey(n.programId),poolId:new Ke.PublicKey(n.id),mint:d,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=Ga({payer:this.scope.ownerPubKey,userRewardTokenPub:f,farmKeys:u,rewardVault:p,rewardInfo:_(N({},l),{mint:d})});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:d,programId:p}=n,f=tn[p];f===4&&this.logAndCreateError("V4 has suspended deposits:",n.programId),Oa(f)||this.logAndCreateError("invalid farm program:",n.programId);let[y,b]=[new Ke.PublicKey(n.programId),new Ke.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 M=ne(this.scope.ownerPubKey,C.mint,C.programId).publicKey;C.publicKey&&M.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 d){let M=r&&C.mint.address===$.toString(),D=h[C.mint.address];if(!D){let{account:E,instructionParams:z}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:C.mint.programId,mint:new Ke.PublicKey(C.mint.address),notUseTokenAccount:M,createInfo:{payer:i||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!M,associatedOnly:M?!1:a,checkCreateATAOwner:u});D=E,z&&k.addInstruction(z)}h[C.mint.address]=D,I.push(D)}let x,S=await this.scope.connection.getAccountInfo(A);if(S&&(x=Pi(f).decode(S.data)),n.programId!==li.toString()&&n.programId!==bn.FARM_PROGRAM_ID_V6.toString()&&!x){let{instruction:C,instructionType:M}=Ai({id:b,programId:y,version:f,ledger:A,owner:this.scope.ownerPubKey});k.addInstruction({instructions:[C],instructionTypes:[M]})}let B=Na({version:f,rewardInfos:d,rewardTokenAccountsPublicKeys:I});B&&this.logAndCreateError(B);let R={amount:ye(o),owner:this.scope.ownerPubKey,farmInfo:n,farmKeys:g,lpAccount:T,rewardAccounts:I,userAuxiliaryLedgers:s==null?void 0:s.map(C=>new Ke.PublicKey(C))},L=f===6?mc(R):f===5?lc(R):cc(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:d}=e,{rewardInfos:p}=n;this.scope.availability.removeFarm===!1&&this.logAndCreateError("farm withdraw feature disabled in your region");let f=tn[n.programId];Oa(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(d);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 Ke.PublicKey(n.programId),poolId:new Ke.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 Ke.PublicKey(y.id),programId:new Ke.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===$.toString(),h=g[A.toString()];if(!h){let{account:B,instructionParams:R}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:y.lpMint.programId,mint:new Ke.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===$.toString(),L=g[B.mint.address];if(!L){let{account:O,instructionParams:C}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:B.mint.programId,mint:new Ke.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=Na({version:f,rewardInfos:p,rewardTokenAccountsPublicKeys:P});T&&this.logAndCreateError(T);let I={amount:ye(o),owner:this.scope.ownerPubKey,farmInfo:n,farmKeys:y,lpAccount:h,rewardAccounts:P,userAuxiliaryLedgers:c==null?void 0:c.map(B=>new Ke.PublicKey(B))},x=f===6?wi(I):f===5?ki(I):f===4?uc(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=>Nt(b.mint.address).equals(Nt(t)));s||this.logAndCreateError("withdraw mint error","rewardInfos",e);let c=(y=s==null?void 0:s.vault)!=null?y:xt,l=this.createTxBuilder(r),d;if(t.equals(xt)||t.equals(Ke.PublicKey.default)){let b=await Qn({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:this.scope.ownerPubKey,amount:Wa(_(N({},s),{openTime:s.openTime,endTime:s.endTime,perSecond:new Un.default(s.perSecond).mul(10**s.mint.decimals).toString()}))});d=b.addresses.newAccount,l.addInstruction(b)}else{let b=await this.scope.account.getCreatedTokenAccount({mint:t});b?d=b:(d=await this.scope.account.getAssociatedTokenAccount(t),l.addInstruction({instructions:[(0,Xs.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,d,this.scope.ownerPubKey,t)],instructionTypes:[X.CreateATA]}))}let{instruction:p,instructionType:f}=sc({programId:a.programId,id:a.id,authority:a.authority,lpVault:a.lpVault,rewardVault:c,userRewardToken:d,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)=>_(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===$.toString(),T=l[h];if(!T){let{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:b.programId,mint:new Ke.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===$.toString(),C=l[L.mint.address];if(!C)if(O){let{account:M,instructionParams:D}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:L.mint.programId,mint:new Ke.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=M,D&&c.addInstruction(D)}else{let M=new Ke.PublicKey(L.mint.address);C=this.scope.account.getAssociatedTokenAccount(M),c.addInstruction({instructions:[(0,Xs.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,C,this.scope.ownerPubKey,M)]})}l[L.mint.address]=C,I.push(C)}let x=p[A],S={amount:j,owner:this.scope.ownerPubKey,farmInfo:f,farmKeys:x,lpAccount:T,rewardAccounts:I,userAuxiliaryLedgers:a==null?void 0:a.map(L=>new Ke.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(d=>{Object.keys(e[s][d]).forEach(p=>{var g,A,k,h,P,T;let f=_(N({},e[s][d][p]),{farmId:d,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(d);f.programId,n.set(d,{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,_(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 Ke.PublicKey(s.userVault)));return(await It(this.scope.connection,o.map(s=>new Ke.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 d=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=d.rewardDebts[k],P=d.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 _(N(N({},d),p),{farmInfo:y,pendingRewards:b})}).filter(Boolean)}};var st=require("@solana/web3.js"),Bt=require("@solana/spl-token");var Xe=te(require("bn.js")),Ue=te(require("decimal.js"));var $i=class extends rt{constructor(t){super(t);this.stableLayout=new Er({connection:this.scope.connection,modelDataPubKey:this.scope.cluster==="mainnet"?void 0:bn.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 Xe.default(new Ue.default(n).mul(10**t[i?"mintA":"mintB"].decimals).toFixed(0)),a=hi(t[i?"mintB":"mintA"]),[u,s]=[new Xe.default(new Ue.default(t.mintAmountA).mul(10**t.mintA.decimals).toString()),new Xe.default(new Ue.default(t.mintAmountB).mul(10**t.mintB.decimals).toString())],c=new Xe.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 d=j;r.isZero()||(d=l==="base"?jr(r.mul(s),u):jr(r.mul(u),s)),this.logDebug("amountRaw:",d.toString(),"lpAmount:",c.toString());let p=jr(r.mul(c),l==="base"?u:s);this.logDebug("liquidity:",p.toString());let f=new St(new Xe.default(1)).add(o),y=new St(new Xe.default(1)).sub(o),b=f.mul(d).quotient,g=y.mul(d).quotient,A=new _e(a,d),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:d,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 st.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,[M,D]=x,E=o!=null?o:await this.getAmmPoolKeys(n.id),z=this.createTxBuilder(p),re=await f.handleTokenAccount({side:"in",amount:M,mint:R.mint,tokenAccount:O,bypassAssociatedCheck:y,checkCreateATAOwner:b}),{tokenAccount:H}=re,Y=$e(re,["tokenAccount"]);z.addInstruction(Y);let ke=await f.handleTokenAccount({side:"in",amount:D,mint:L.mint,tokenAccount:C,bypassAssociatedCheck:y,checkCreateATAOwner:b}),{tokenAccount:J}=ke,ie=$e(ke,["tokenAccount"]);z.addInstruction(ie);let Fe=await f.handleTokenAccount({side:"out",amount:0,mint:new st.PublicKey(n.lpMint.address),tokenAccount:P,bypassAssociatedCheck:y,checkCreateATAOwner:b}),{tokenAccount:Z}=Fe,ge=$e(Fe,["tokenAccount"]);return z.addInstruction(ge),z.addInstruction({instructions:[dl({poolInfo:n,poolKeys:E,userKeys:{baseTokenAccount:H,quoteTokenAccount:J,lpTokenAccount:Z,owner:this.scope.ownerPubKey},baseAmountIn:M,quoteAmountIn:D,otherAmountMin:a.raw,fixedSide:B})],instructionTypes:[n.pooltype.includes("StablePool")?X.AmmV5AddLiquidity:X.AmmV4AddLiquidity],lookupTableAddress:E.lookupTableAccount?[E.lookupTableAccount]:[]}),z.addCustomComputeBudget(l),z.addTipInstruction(d),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:d}=t,p=o!=null?o:await this.getAmmPoolKeys(n.id),[f,y,b]=[new st.PublicKey(n.mintA.address),new st.PublicKey(n.mintB.address),new st.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(d),{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=$e(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=$e(O,["tokenAccount"]);return P.addInstruction(R),P.addInstruction({instructions:[ks({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:d=Bt.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 E of this.scope.account.tokenAccountRawInfos)(A[E.accountInfo.mint.toString()]===void 0||ne(this.scope.ownerPubKey,E.accountInfo.mint,Bt.TOKEN_PROGRAM_ID).publicKey.equals(E.pubkey))&&(A[E.accountInfo.mint.toString()]=E.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 Xe.default(0)),P=t.mintA.address===je.WSOL.mint.toString(),T=t.mintB.address===je.WSOL.mint.toString(),{account:I,instructionParams:x}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:Bt.TOKEN_PROGRAM_ID,mint:new st.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:Bt.TOKEN_PROGRAM_ID,mint:new st.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 E=tn[r.programId],z=sn({programId:new st.PublicKey(r.programId),poolId:new st.PublicKey(r.id),owner:this.scope.ownerPubKey,version:E}),H,Y=await this.scope.connection.getAccountInfo(z);if(Y&&(H=Pi(E).decode(Y.data)),E!==6&&!H){let{instruction:Fe,instructionType:Oe}=Ai({id:new st.PublicKey(r.id),programId:new st.PublicKey(r.programId),version:E,ledger:z,owner:this.scope.ownerPubKey});g.addInstruction({instructions:[Fe],instructionTypes:[Oe]})}let J=[];for(let Fe of r.rewardInfos){let Oe=Fe.mint.address===je.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 st.PublicKey(Fe.mint.address),tokenProgram:d,owner:this.scope.ownerPubKey,skipCloseAccount:!Oe,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],Z={userAuxiliaryLedgers:l,amount:a,owner:this.scope.ownerPubKey,farmInfo:r,farmKeys:ie,lpAccount:k,rewardAccounts:J},ge=tn[r.programId],re=ge===6?wi(Z):ge===5?ki(Z):Ti(Z),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=ks({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],M=await this.scope.clmm.getClmmPoolKeys(n.id),D=await we.openPositionFromBaseInstructions(_(N({poolInfo:n,poolKeys:M,ownerInfo:{feePayer:this.scope.ownerPubKey,wallet:this.scope.ownerPubKey,tokenAccountA:O,tokenAccountB:C},withMetadata:"create"},i),{liquidity:new Xe.default(0),base:u,getEphemeralSigners:f}));return g.addInstruction({instructions:[...D.instructions],signers:D.signers,instructionTypes:[...D.instructionTypes],lookupTableAddress:M.lookupTableAccount?[M.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:d,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(Bt.NATIVE_MINT),h=s.useSOLBalance&&i.mint.equals(Bt.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=ws({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}=Ts(_(N({},R),{userWallet:this.scope.ownerPubKey,userCoinVault:T,userPcVault:x,userLpVault:ne(this.scope.ownerPubKey,B.lpMint,d).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=Du,feeDestinationId:o=qu,tokenProgram:i,baseMintInfo:r,quoteMintInfo:a,baseAmount:u,quoteAmount:s,startTime:c,ownerInfo:l,lowestFeeMarket:d,assignSeed:p,associatedOnly:f=!1,checkCreateATAOwner:y=!1,lotSize:b=1,tickSize:g=.01,txVersion:A,computeBudgetConfig:k,txTipConfig:h,feePayer:P}){var ei,oa,ti;let T=this.scope.ownerPubKey,I=l.feePayer||((ei=this.scope.owner)==null?void 0:ei.publicKey),x=l.useSOLBalance&&r.mint.equals(Bt.NATIVE_MINT),S=l.useSOLBalance&&a.mint.equals(Bt.NATIVE_MINT),B=p?`${r.mint.toBase58().slice(0,7)}-${a.mint.toBase58().slice(0,7)}-${p}`:void 0,R=ut({fromPublicKey:T,programId:n,assignSeed:B&&`${B}-market`}),L=ut({fromPublicKey:T,programId:n,assignSeed:B&&`${B}-request`}),O=ut({fromPublicKey:T,programId:n,assignSeed:B&&`${B}-event`}),C=ut({fromPublicKey:T,programId:n,assignSeed:B&&`${B}-bids`}),M=ut({fromPublicKey:T,programId:n,assignSeed:B&&`${B}-asks`}),D=ut({fromPublicKey:T,programId:Bt.TOKEN_PROGRAM_ID,assignSeed:B&&`${B}-baseVault`}),E=ut({fromPublicKey:T,programId:Bt.TOKEN_PROGRAM_ID,assignSeed:B&&`${B}-quoteVault`}),z=0,H=new Xe.default(100);function Y(){let Wt=new Xe.default(0);for(;;)try{return{vaultOwner:st.PublicKey.createProgramAddressSync([R.publicKey.toBuffer(),Wt.toArrayLike(Buffer,"le",8)],n),vaultSignerNonce:Wt}}catch{if(Wt.iaddn(1),Wt.gt(new Xe.default(25555)))throw Error("find vault owner error")}}let{vaultOwner:J,vaultSignerNonce:ie}=Y(),Z=new Xe.default(Math.round(10**r.decimals*b)),ge=new Xe.default(Math.round(b*10**a.decimals*g));if(Z.eq(j))throw Error("lot size is too small");if(ge.eq(j))throw Error("tick size or lot size is too small");let re=await $r({connection:this.scope.connection,wallet:this.scope.ownerPubKey,marketInfo:{programId:n,vaultOwner:J,baseMint:r.mint,quoteMint:a.mint,id:R,baseVault:D,quoteVault:E,requestQueue:L,eventQueue:O,bids:C,asks:M,feeRateBps:z,quoteDustThreshold:H,vaultSignerNonce:ie,baseLotSize:Z,quoteLotSize:ge,lowestFeeMarket:d}}),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:Oe}=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(Oe||{});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 Re=ws({version:4,marketVersion:3,marketId:R.publicKey,baseMint:r.mint,quoteMint:a.mint,baseDecimals:r.decimals,quoteDecimals:a.decimals,programId:t,marketProgramId:n}),Ft={programId:t,ammId:Re.id,ammAuthority:Re.authority,ammOpenOrders:Re.openOrders,lpMint:Re.lpMint,coinMint:Re.baseMint,pcMint:Re.quoteMint,coinVault:Re.baseVault,pcVault:Re.quoteVault,withdrawQueue:Re.withdrawQueue,ammTargetOrders:Re.targetOrders,poolTempLp:Re.lpVault,marketProgramId:Re.marketProgramId,marketId:Re.marketId,ammConfigId:Re.configId,feeDestinationId:o},{instruction:ot,instructionType:dn}=Ts(_(N({},Ft),{userWallet:this.scope.ownerPubKey,userCoinVault:Fe,userPcVault:Ae,userLpVault:ne(this.scope.ownerPubKey,Re.lpMint,i).publicKey,nonce:Re.nonce,openTime:c,coinAmount:u,pcAmount:s}));ke.addInstruction({instructions:[ot],instructionTypes:[dn]});let Co=x||S?[((oa=Oe==null?void 0:Oe.instructions)==null?void 0:oa[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:M.publicKey,baseVault:D.publicKey,quoteVault:E.publicKey,baseMint:new st.PublicKey(r.mint),quoteMint:new st.PublicKey(a.mint)},Ft)}):ke.sizeCheckBuild({computeBudgetConfig:k,splitIns:Co,address:N({requestQueue:L.publicKey,eventQueue:O.publicKey,bids:C.publicKey,asks:M.publicKey,baseVault:D.publicKey,quoteVault:E.publicKey,baseMint:new st.PublicKey(r.mint),quoteMint:new st.PublicKey(a.mint)},Ft)})}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 sl.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],d=[t.mintA.decimals,t.mintB.decimals],p=a==t.mintA.address?"base":"quote";p==="quote"&&(l.reverse(),d.reverse());let[f,y]=l,[b,g]=d,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=gl(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 Xe.default(0),T=new Xe.default(0);if(!h.isZero())if(A){T=ao(h.mul(ps),Or);let O=h.sub(T),C=f.add(O);P=y.mul(O).div(C)}else{T=h.mul(new Xe.default(2)).div(new Xe.default(1e4));let O=h.sub(T);p==="quote"?P=new Xe.default(yl(this.stableLayout.stableModelData,c.toNumber(),s.toNumber(),O.toNumber())):P=new Xe.default(bl(this.stableLayout.stableModelData,c.toNumber(),s.toNumber(),O.toNumber()))}let I=new Xe.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 d=[a,u],p=s?"quote":"base";p==="base"&&d.reverse(),this.logDebug("output side:",p);let[f,y]=d,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 Xe.default(0),A=n,k=new Xe.default(0);if(!A.isZero()){A.gt(y)&&(A=y.sub(new Xe.default(1)));let B=y.sub(A),R=f.mul(A).div(B);g=R.mul(Or).div(Or.sub(ps)),k=g.sub(R)}let h=new Xe.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:d}){let p=this.createTxBuilder(d),{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===$.toBase58(),h=b&&A.address===$.toBase58(),{account:P,instructionParams:T}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:Bt.TOKEN_PROGRAM_ID,mint:new st.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:Bt.TOKEN_PROGRAM_ID,mint:new st.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 st.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 d=Nr.decode(l.accountInfo.data);i[String(t[c])]=_(N({},d),{programId:l.accountInfo.owner}),r.push(d.baseVault,d.quoteVault)}let a={},u=await Ge(this.scope.connection,r.map(c=>({pubkey:new st.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 Xe.default(Bt.AccountLayout.decode(l.data).amount.toString())}let s={};for(let[c,l]of Object.entries(i)){let d=a[l.baseVault.toString()].sub(l.baseNeedTakePnl),p=a[l.quoteVault.toString()].sub(l.quoteNeedTakePnl);s[c]=_(N({},l),{baseReserve:d,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(d.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(st.PublicKey.default)&&!a.amount.isZero()).map(a=>a.mint),i=(await It(this.scope.connection,t)).map((a,u)=>a&&a.data.length===Bt.MintLayout.span?_(N({},Bt.MintLayout.decode(a.data)),{address:t[u]}):void 0).filter(Boolean).filter(a=>this.scope.cluster==="devnet"?a:al.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 Xe.default(0)}})}};var q=require("@solana/web3.js"),Ce=require("@solana/spl-token");var He=te(require("bn.js")),an=te(require("decimal.js"));var ji=class extends rt{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 d=n[l];if(d.accountInfo===null)throw Error("fetch pool info error: "+String(e[l]));let p=Rr.decode(d.accountInfo.data);o[String(e[l])]=_(N({},p),{programId:d.accountInfo.owner}),i.add(String(p.configId)),r.push(p.vaultA,p.vaultB)}let a={};if(t){let l=[...i],d=await Ge(this.scope.connection,l.map(p=>({pubkey:new q.PublicKey(p)})));for(let p=0;p<l.length;p++){let f=d[p].accountInfo;if(f===null)throw Error("fetch pool config error: "+l[p]);a[l[p]]=Hc.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 d=s[l].accountInfo;if(d===null)throw Error("fetch vault info error: "+r[l]);u[String(r[l])]=new He.default(Ce.AccountLayout.decode(d.data).amount.toString())}let c={};for(let[l,d]of Object.entries(o)){let p=u[d.vaultA.toString()].sub(d.protocolFeesMintA).sub(d.fundFeesMintA).sub(d.creatorFeesMintA),f=u[d.vaultB.toString()].sub(d.protocolFeesMintB).sub(d.fundFeesMintB).sub(d.creatorFeesMintB);c[l]=_(N({},d),{baseReserve:p,quoteReserve:f,vaultAAmount:u[d.vaultA.toString()],vaultBAmount:u[d.vaultB.toString()],configInfo:a[d.configId.toString()],poolPrice:new an.default(f.toString()).div(new an.default(10).pow(d.mintDecimalB)).div(new an.default(p.toString()).div(new an.default(10).pow(d.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 _(N({},n),{[o]:_(N({},i),{id:new q.PublicKey(o),configInfo:i.configInfo,version:7,authority:wo(i.programId).publicKey,mintA:kt({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:kt({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=kt({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=kt({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=kt({address:t.mintLp.toBase58(),decimals:t.lpDecimals,programId:Ce.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:_(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:d,addSupportMintExt:p}=b,f=$e(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 He.default(new q.PublicKey(f.mintA.address).toBuffer()).lte(new He.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===Ce.NATIVE_MINT.toBase58(),x=i.useSOLBalance&&h.address===Ce.NATIVE_MINT.toBase58(),[S,B]=[new q.PublicKey(k.address),new q.PublicKey(h.address)],R=this.createTxBuilder(d),{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:M}=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(M||{}),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 D=rs({poolId:e,programId:t,configId:new q.PublicKey(s.id),mintA:S,mintB:B}),E=[],z=[];return p&&(k.programId===Ce.TOKEN_2022_PROGRAM_ID.toBase58()&&z.push(as(t,new q.PublicKey(k.address)).publicKey),h.programId===Ce.TOKEN_2022_PROGRAM_ID.toBase58()&&z.push(as(t,new q.PublicKey(h.address)).publicKey),(await this.scope.connection.getMultipleAccountsInfo(z)).forEach((Z,ge)=>{Z&&E.push(z[ge])})),R.addInstruction({instructions:[$c(t,this.scope.ownerPubKey,new q.PublicKey(s.id),D.authority,D.poolId,S,B,D.lpMint,L,C,ne(this.scope.ownerPubKey,D.lpMint).publicKey,D.vaultA,D.vaultB,n,new q.PublicKey((Y=k.programId)!=null?Y:Ce.TOKEN_PROGRAM_ID),new q.PublicKey((J=h.programId)!=null?J:Ce.TOKEN_PROGRAM_ID),D.observationId,P,T,o,E)],instructionTypes:[X.CpmmCreatePool]}),R.addCustomComputeBudget(c),R.addTipInstruction(l),R.versionBuild({txVersion:u,extInfo:{address:_(N({},D),{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:d}=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:_(N({},t),{lpAmount:new an.default(b.lpAmount.toString()).div(10**t.lpMint.decimals).toNumber()}),baseReserve:b.baseReserve,quoteReserve:b.quoteReserve,slippage:new St(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===Ce.NATIVE_MINT.toString(),T=t.mintB.address===Ce.NATIVE_MINT.toString(),I=this.createTxBuilder(d),[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:M}=H,D=$e(H,["tokenAccount"]);I.addInstruction(D);let E=n!=null?n:await this.getCpmmPoolKeys(t.id),z=new St(new He.default(1)).sub(r);return I.addInstruction({instructions:[jc(new q.PublicKey(t.programId),this.scope.ownerPubKey,new q.PublicKey(E.authority),new q.PublicKey(t.id),M,B,L,new q.PublicKey(E.vault.A),new q.PublicKey(E.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:E.lookupTableAccount?[E.lookupTableAccount]:[]}),I.addCustomComputeBudget(u),I.addTipInstruction(s),I.versionBuild({txVersion:l,lookupTableAddress:E.lookupTableAccount?[E.lookupTableAccount]:void 0})}async withdrawLiquidity(e){var D,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 St(new He.default(1)).sub(i),d=await this.getRpcPoolInfo(t.id),[p,f]=[l.mul(o.mul(d.baseReserve).div(d.lpAmount)).quotient,l.mul(o.mul(d.quoteReserve).div(d.lpAmount)).quotient],y=await this.scope.fetchEpochInfo(),[b,g]=[ht(p,t.mintA.extensions.feeConfig,y,!1),ht(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($),I=P.equals($),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 M=n!=null?n:await this.getCpmmPoolKeys(t.id);return k.addInstruction({instructions:[Jc(new q.PublicKey(t.programId),this.scope.ownerPubKey,new q.PublicKey(M.authority),new q.PublicKey(t.id),C,x,S,new q.PublicKey(M.vault.A),new q.PublicKey(M.vault.B),h,P,new q.PublicKey(t.lpMint.address),o,p.sub((D=b.fee)!=null?D:new He.default(0)),f.sub((E=g.fee)!=null?E:new He.default(0)))],instructionTypes:[X.CpmmWithdrawLiquidity],lookupTableAddress:M.lookupTableAccount?[M.lookupTableAccount]:[]}),k.addCustomComputeBudget(r),k.addTipInstruction(a),k.versionBuild({txVersion:u,lookupTableAddress:M.lookupTableAccount?[M.lookupTableAccount]:void 0})}async swap(e){var R,L,O,C,M,D;let{poolInfo:t,poolKeys:n,baseIn:o,fixedOut:i,inputAmount:r,swapResult:a,slippage:u=0,config:s,computeBudgetConfig:c,txTipConfig:l,txVersion:d,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 He.default((1+u)*1e4)).div(new He.default(1e4)):a.outputAmount=a.outputAmount.mul(new He.default((1-u)*1e4)).div(new He.default(1e4));let h=t.mintA.address===$.toBase58(),P=t.mintB.address===$.toBase58(),{account:T,instructionParams:I}=await this.scope.account.getOrCreateTokenAccount({mint:A,tokenProgram:new q.PublicKey((R=t.mintA.programId)!=null?R:Ce.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:Ce.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?el(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((M=t[o?"mintA":"mintB"].programId)!=null?M:Ce.TOKEN_PROGRAM_ID),new q.PublicKey((D=t[o?"mintB":"mintA"].programId)!=null?D:Ce.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:Ce.TOKEN_PROGRAM_ID),new q.PublicKey((C=t[o?"mintB":"mintA"].programId)!=null?C:Ce.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:d,lookupTableAddress:B.lookupTableAccount?[B.lookupTableAccount]:void 0})}async lockLp(e){var d,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=(d=e.poolKeys)!=null?d:await this.getCpmmPoolKeys(t.id),l=await tl({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 d=e.feePayer||this.scope.ownerPubKey,p=this.createTxBuilder(d),[f,y]=[new q.PublicKey(t.mintA.address),new q.PublicKey(t.mintB.address)],b=f.equals($),g=y.equals($),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(d,o,Ce.TOKEN_PROGRAM_ID),{publicKey:B}=Wo(i,o),{publicKey:R}=ne(r,new q.PublicKey(t.lpMint.address),Ce.TOKEN_PROGRAM_ID);return p.addInstruction({instructions:[us({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={},d=[];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($),P=k.equals($),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,Ce.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,Ce.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&&d.push(x.lookupTableAccount);let{publicKey:S}=ne(s,g,Ce.TOKEN_PROGRAM_ID),{publicKey:B}=Wo(n,g),{publicKey:R}=ne(o,new q.PublicKey(y.lpMint.address),Ce.TOKEN_PROGRAM_ID);c.addInstruction({instructions:[us({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:d}):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:d,feeOn:p}=b,f=$e(b,["poolId","programId","poolFeeAccount","startTime","ownerInfo","associatedOnly","checkCreateATAOwner","txVersion","feeConfig","computeBudgetConfig","txTipConfig","feePayer","feeOn"]);var E,z,H;console.log("***this method only available for wallet with permissions***");let g=i.feePayer||((E=this.scope.owner)==null?void 0:E.publicKey),A=new He.default(new q.PublicKey(f.mintA.address).toBuffer()).lte(new He.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===Ce.NATIVE_MINT.toBase58(),x=i.useSOLBalance&&h.address===Ce.NATIVE_MINT.toBase58(),[S,B]=[new q.PublicKey(k.address),new q.PublicKey(h.address)],R=this.createTxBuilder(d),{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:M}=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(M||{}),L===void 0||C===void 0)throw Error("you don't has some token account");let D=rs({poolId:e,programId:t,configId:new q.PublicKey(s.id),mintA:S,mintB:B});return R.addInstruction({instructions:[ol(t,this.scope.ownerPubKey,this.scope.ownerPubKey,new q.PublicKey(s.id),D.authority,D.poolId,S,B,D.lpMint,L,C,ne(this.scope.ownerPubKey,D.lpMint).publicKey,D.vaultA,D.vaultB,n,new q.PublicKey((z=k.programId)!=null?z:Ce.TOKEN_PROGRAM_ID),new q.PublicKey((H=h.programId)!=null?H:Ce.TOKEN_PROGRAM_ID),D.observationId,Zc(t,this.scope.ownerPubKey).publicKey,P,T,o,p)],instructionTypes:[X.CpmmCreatePool]}),R.addCustomComputeBudget(c),R.addTipInstruction(l),R.versionBuild({txVersion:u,extInfo:{address:_(N({},D),{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,d,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(d,f);return s.addInstruction({instructions:[(0,Ce.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,y,this.scope.ownerPubKey,l,new q.PublicKey(e.mintA.programId)),(0,Ce.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,b,this.scope.ownerPubKey,d,new q.PublicKey(e.mintB.programId))]}),s.addInstruction({instructions:[cs(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,d,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 d=e.map(b=>b.id),p=95,f=[];for(let b=0;b<d.length;b+=p)f.push(d.slice(b,b+p));c=(await Promise.all(f.map(b=>this.scope.api.fetchPoolKeysById({idList:b})))).flat()}let l=c.reduce((d,p)=>_(N({},d),{[p.id]:p}),{});for(let d of e){let p=l[d.id]||await this.getCpmmPoolKeys(d.id),[f,y,b,g]=[new q.PublicKey(d.mintA.address),new q.PublicKey(d.mintB.address),new q.PublicKey(d.mintA.programId),new q.PublicKey(d.mintB.programId)],A=s[d.mintA.address]||this.scope.account.getAssociatedTokenAccount(f,b),k=s[d.mintB.address]||this.scope.account.getAssociatedTokenAccount(y,g);s[d.mintA.address]=A,s[d.mintB.address]=k,u.addInstruction({instructions:[cs(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(d=>d.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,d,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(d,f);return s.addInstruction({instructions:[(0,Ce.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,y,this.scope.ownerPubKey,l,new q.PublicKey(e.mintA.programId)),(0,Ce.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,b,this.scope.ownerPubKey,d,new q.PublicKey(e.mintB.programId))]}),s.addInstruction({instructions:[nl(n,u,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,d,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 He.default((1-o)*1e4)).div(new He.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 He.default(new an.default(o).mul(10**e[a?"mintA":"mintB"].decimals).mul(u).toFixed(0)),c=ht(s,e[a?"mintA":"mintB"].extensions.feeConfig,r,!1),l=s.sub((h=c.fee)!=null?h:new He.default(0)),d=new He.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(d).div(p==="base"?t:n),y={amount:j,fee:void 0,expirationTime:void 0};if(!l.isZero()){let O=Qd(f,t,n,d);this.logDebug("lpAmountData:",{amountA:O.amountA.toString(),amountB:O.amountB.toString()}),y=ht(O[a?"amountB":"amountA"],e[a?"mintB":"mintA"].extensions.feeConfig,r,!0)}let b=new St(new He.default(1)).add(i),g=new St(new He.default(1)).sub(i),A=ht(b.mul(y.amount.sub((I=y.fee)!=null?I:new He.default(0))).quotient,e[a?"mintB":"mintA"].extensions.feeConfig,r,!0),k=ht(g.mul(y.amount.sub((x=y.fee)!=null?x:new He.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 He.default(1))),t=e.map(a=>Wo(this.scope.cluster==="mainnet"?di:bn.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)=>_(N({},a),{nftMint:new q.PublicKey(o.get(i[u].toString()))}))}};function Qd(m,e,t,n){let o=m.mul(e).div(n);!o.isZero()&&!m.mul(e).mod(n).isZero()&&(o=o.add(new He.default(1)));let i=m.mul(t).div(n);return!i.isZero()&&!m.mul(t).mod(n).isZero()&&(i=i.add(new He.default(1))),{amountA:o,amountB:i}}var Ys=require("@solana/web3.js"),Jt=require("@solana/spl-token");var Ji=class extends rt{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,_(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,_(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,_(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,_(N({},i),{priority:2})),i;let r=await this.scope.connection.getAccountInfo(new Ys.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 Ys.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 Bn(o):void 0,this._signAllTransactions=e.signAllTransactions,this.blockhashCommitment=s,this.loopMultiTxStatus=c,this.api=i,this._apiCacheTime=u||5*60*1e3,this.logger=xe("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 $i({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 ji({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,Wl.merge)({cluster:"mainnet",owner:null,apiRequestInterval:3e5,apiRequestTimeout:1e4},e),{cluster:n,apiRequestTimeout:o,logCount:i,logRequests:r,urlConfigs:a}=t,u=new ta({cluster:n,timeout:o,urlConfigs:a,logCount:i,logRequests:r}),s=new er(_(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(na);return this._owner.publicKey}setOwner(e){return this._owner=e?new Bn(e):void 0,this.account.resetTokenAccounts(),this}get connection(){if(!this._connection)throw new Error(Dl);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(na),new Error(na)}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=>_(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