UNPKG

@raydium-io/raydium-sdk-v2

Version:

An SDK for building applications on top of Raydium.

2 lines 139 kB
var dr=Object.defineProperty,pr=Object.defineProperties;var fr=Object.getOwnPropertyDescriptors;var rn=Object.getOwnPropertySymbols;var Yo=Object.prototype.hasOwnProperty,Ho=Object.prototype.propertyIsEnumerable;var Xo=(a,e,t)=>e in a?dr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,F=(a,e)=>{for(var t in e||(e={}))Yo.call(e,t)&&Xo(a,t,e[t]);if(rn)for(var t of rn(e))Ho.call(e,t)&&Xo(a,t,e[t]);return a},U=(a,e)=>pr(a,fr(e));var ve=(a,e)=>{var t={};for(var n in a)Yo.call(a,n)&&e.indexOf(n)<0&&(t[n]=a[n]);if(a!=null&&rn)for(var n of rn(a))e.indexOf(n)<0&&Ho.call(a,n)&&(t[n]=a[n]);return t};import{get as Qo,set as yr}from"lodash";var En=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}},Zo={},br={};function H(a){let e=Qo(Zo,a);if(!e){let t=Qo(br,a);e=new En({name:a,logLevel:t}),yr(Zo,a,e)}return e}import{PublicKey as Ot,sendAndConfirmTransaction as Ro,SystemProgram as bu,Transaction as Zt,TransactionMessage as $t,VersionedTransaction as jt}from"@solana/web3.js";import gu from"axios";import{PublicKey as So,AddressLookupTableAccount as Lt}from"@solana/web3.js";import{PublicKey as yu}from"@solana/web3.js";import it from"bn.js";import _C from"decimal.js";import Ir from"big.js";import Eu from"bn.js";import gr from"toformat";var Pr=gr,Nt=Pr;import sn from"big.js";import wr from"bn.js";import kr from"decimal.js-light";import Mt from"bn.js";var $o=9007199254740991;function Be(a){let e=H("Raydium_parseBigNumberish");if(a instanceof Mt)return a;if(typeof a=="string"){if(a.match(/^-?[0-9]+$/))return new Mt(a);e.logWithError(`invalid BigNumberish string: ${a}`)}return typeof a=="number"?(a%1&&e.logWithError(`BigNumberish number underflow: ${a}`),(a>=$o||a<=-$o)&&e.logWithError(`BigNumberish number overflow: ${a}`),new Mt(String(a))):typeof a=="bigint"?new Mt(a.toString()):(e.error(`invalid BigNumberish value: ${a}`),new Mt(0))}var an=H("module/fraction"),Dn=Nt(sn),Ft=Nt(kr),Tr={[0]:Ft.ROUND_DOWN,[1]:Ft.ROUND_HALF_UP,[2]:Ft.ROUND_UP},hr={[0]:sn.roundDown,[1]:sn.roundHalfUp,[2]:sn.roundUp},oe=class{constructor(e,t=new wr(1)){this.numerator=Be(e),this.denominator=Be(t)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new oe(this.denominator,this.numerator)}add(e){let t=e instanceof oe?e:new oe(Be(e));return this.denominator.eq(t.denominator)?new oe(this.numerator.add(t.numerator),this.denominator):new oe(this.numerator.mul(t.denominator).add(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}sub(e){let t=e instanceof oe?e:new oe(Be(e));return this.denominator.eq(t.denominator)?new oe(this.numerator.sub(t.numerator),this.denominator):new oe(this.numerator.mul(t.denominator).sub(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}mul(e){let t=e instanceof oe?e:new oe(Be(e));return new oe(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof oe?e:new oe(Be(e));return new oe(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},n=1){Number.isInteger(e)||an.logWithError(`${e} is not an integer.`),e<=0&&an.logWithError(`${e} is not positive.`),Ft.set({precision:e+1,rounding:Tr[n]});let i=new Ft(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return i.toFormat(i.decimalPlaces(),t)}toFixed(e,t={groupSeparator:""},n=1){return Number.isInteger(e)||an.logWithError(`${e} is not an integer.`),e<0&&an.logWithError(`${e} is negative.`),Dn.DP=e,Dn.RM=hr[n]||1,new Dn(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var Hu=H("Raydium_amount"),Qu=Nt(Ir);import{PublicKey as Sr}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as jo}from"@solana/spl-token";var un={chainId:101,address:Sr.default.toBase58(),programId:jo.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}},qe={chainId:101,address:"So11111111111111111111111111111111111111112",programId:jo.toBase58(),decimals:9,symbol:"WSOL",name:"Wrapped SOL",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}};import{PublicKey as qn}from"@solana/web3.js";import{PublicKey as se,SystemProgram as Jo,SYSVAR_RENT_PUBKEY as Kr}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as xr}from"@solana/spl-token";function bt({pubkey:a,isSigner:e=!1,isWritable:t=!0}){return{pubkey:a,isWritable:t,isSigner:e}}var Cr=[bt({pubkey:xr,isWritable:!1}),bt({pubkey:Jo.programId,isWritable:!1}),bt({pubkey:Kr,isWritable:!1})];function ei({publicKey:a,transformSol:e}){let t=ti(a.toString());if(t instanceof se)return e&&t.equals(at)?$e:t;if(e&&t.toString()===at.toBase58())return $e;if(typeof t=="string"){if(t===se.default.toBase58())return se.default;try{return new se(t)}catch{throw new Error("invalid public key")}}throw new Error("invalid public key")}function ti(a){try{return new se(a)}catch{return a}}var Wn=new se("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),gt=new se("SysvarRent111111111111111111111111111111111"),oc=new se("SysvarC1ock11111111111111111111111111111111"),st=new se("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Rr=new se("Sysvar1nstructions1111111111111111111111111"),Lr=Jo.programId,ic=new se("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),rc=new se("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),ac=new se("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),sc=new se("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),uc=new se("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),cc=new se("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),lc=new se("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),mc=new se("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),dc=new se("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),pc=new se("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),fc=new se("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),$e=new se("So11111111111111111111111111111111111111112"),at=se.default;var Un=class{constructor({mint:e,decimals:t,symbol:n,name:i,skipMint:r=!1,isToken2022:s=!1}){if(e===at.toBase58()||e instanceof qn&&at.equals(e)){this.decimals=qe.decimals,this.symbol=qe.symbol,this.name=qe.name,this.mint=new qn(qe.address),this.isToken2022=!1;return}this.decimals=t,this.symbol=n||e.toString().substring(0,6),this.name=i||e.toString().substring(0,6),this.mint=r?qn.default:ei({publicKey:e}),this.isToken2022=s}equals(e){return this===e?!0:this.mint.equals(e.mint)}},ke=Un;ke.WSOL=new Un(U(F({},qe),{mint:qe.address}));var Gn=class{constructor({decimals:e,symbol:t="UNKNOWN",name:n="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=n}equals(e){return this===e}},cn=Gn;cn.SOL=new Gn(un);import Or from"bn.js";var Sc=new oe(new Or(100));var Oc=H("Raydium_price");import{merge as Ex}from"lodash";import Wc from"axios";var ni={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"},Nr=U(F({},ni),{BASE_HOST:"https://api-v3-devnet.raydium.io",OWNER_BASE_HOST:"https://owner-v1-devnet.raydium.io",SWAP_HOST:"https://transaction-v1-devnet.raydium.io",CPMM_LOCK:"https://dynamic-ipfs-devnet.raydium.io/lock/cpmm/position",TEMP_HOST:"https://temp-api-v1-devnet.raydium.io",LAUNCH_AUTH_HOST:"https://launch-auth-v1-devnet.raydium.io",LAUNCH_COMMENT_HOST:"https://launch-forum-v1-devnet.raydium.io",LAUNCH_HISTORY_HOST:"https://launch-history-v1-devnet.raydium.io",LAUNCH_MINT_HOST:"https://launch-mint-v1-devnet.raydium.io"});var ll=H("Raydium_Api");import{PublicKey as Jm,SystemProgram as ed}from"@solana/web3.js";import{AccountLayout as rd,createAssociatedTokenAccountIdempotentInstruction as ad,TOKEN_PROGRAM_ID as sd,TOKEN_2022_PROGRAM_ID as ud}from"@solana/spl-token";import{PublicKey as Rm,SystemProgram as Om}from"@solana/web3.js";import Fm from"bn.js";import{createCloseAccountInstruction as Em,createInitializeAccountInstruction as Dm,createTransferInstruction as Wm,TOKEN_PROGRAM_ID as qm}from"@solana/spl-token";var ye={CreateAccount:"CreateAccount",InitAccount:"InitAccount",CreateATA:"CreateATA",CloseAccount:"CloseAccount",TransferAmount:"TransferAmount",InitMint:"InitMint",MintTo:"MintTo",InitMarket:"InitMarket",Util1216OwnerClaim:"Util1216OwnerClaim",SetComputeUnitPrice:"SetComputeUnitPrice",SetComputeUnitLimit:"SetComputeUnitLimit",ClmmCreatePool:"ClmmCreatePool",ClmmOpenPosition:"ClmmOpenPosition",ClmmIncreasePosition:"ClmmIncreasePosition",ClmmDecreasePosition:"ClmmDecreasePosition",ClmmClosePosition:"ClmmClosePosition",ClmmSwapBaseIn:"ClmmSwapBaseIn",ClmmSwapBaseOut:"ClmmSwapBaseOut",ClmmInitReward:"ClmmInitReward",ClmmSetReward:"ClmmSetReward",ClmmCollectReward:"ClmmCollectReward",ClmmLockPosition:"ClmmLockPosition",ClmmHarvestLockPosition:"ClmmHarvestLockPosition",AmmV4Swap:"AmmV4Swap",AmmV4AddLiquidity:"AmmV4AddLiquidity",AmmV4RemoveLiquidity:"AmmV4RemoveLiquidity",AmmV4SimulatePoolInfo:"AmmV4SimulatePoolInfo",AmmV4SwapBaseIn:"AmmV4SwapBaseIn",AmmV4SwapBaseOut:"AmmV4SwapBaseOut",AmmV4CreatePool:"AmmV4CreatePool",AmmV4InitPool:"AmmV4InitPool",AmmV5AddLiquidity:"AmmV5AddLiquidity",AmmV5RemoveLiquidity:"AmmV5RemoveLiquidity",AmmV5SimulatePoolInfo:"AmmV5SimulatePoolInfo",AmmV5SwapBaseIn:"AmmV5SwapBaseIn",AmmV5SwapBaseOut:"AmmV5SwapBaseOut",RouteSwap:"RouteSwap",RouteSwap1:"RouteSwap1",RouteSwap2:"RouteSwap2",FarmV3Deposit:"FarmV3Deposit",FarmV3Withdraw:"FarmV3Withdraw",FarmV3CreateLedger:"FarmV3CreateLedger",FarmV4Withdraw:"FarmV4Withdraw",FarmV5Deposit:"FarmV5Deposit",FarmV5Withdraw:"FarmV5Withdraw",FarmV5CreateLedger:"FarmV5CreateLedger",FarmV6Deposit:"FarmV6Deposit",FarmV6Withdraw:"FarmV6Withdraw",FarmV6Create:"FarmV6Create",FarmV6Restart:"FarmV6Restart",FarmV6CreatorAddReward:"FarmV6CreatorAddReward",FarmV6CreatorWithdraw:"FarmV6CreatorWithdraw",CpmmCreatePool:"CpmmCreatePool",CpmmAddLiquidity:"CpmmAddLiquidity",CpmmWithdrawLiquidity:"CpmmWithdrawLiquidity",CpmmSwapBaseIn:"CpmmSwapBaseIn",CpmmSwapBaseOut:"CpmmSwapBaseOut",CpmmLockLp:"CpmmLockLp",CpmmCollectLockFee:"CpmmCollectLockFee",TransferTip:"TransferTip"};import{Keypair as gm,PublicKey as Pm}from"@solana/web3.js";import km from"bn.js";import{TOKEN_PROGRAM_ID as Im}from"@solana/spl-token";import{PublicKey as zr}from"@solana/web3.js";import ai,{isBN as si}from"bn.js";import{bits as Mr,BitStructure as Tl,blob as Fr,Blob as hl,cstr as Il,f32 as Bl,f32be as Sl,f64 as Kl,f64be as xl,greedy as Cl,Layout as vr,ns64 as Rl,ns64be as Ll,nu64 as Ol,nu64be as Nl,offset as _r,s16 as Ml,s16be as Fl,s24 as vl,s24be as _l,s32 as Vr,s32be as Vl,s40 as El,s40be as Dl,s48 as Wl,s48be as ql,s8 as Ul,seq as Er,struct as Gl,Structure as Dr,u16 as Wr,u16be as zl,u24 as Xl,u24be as Yl,u32 as qr,u32be as Hl,u40 as Ql,u40be as Zl,u48 as $l,u48be as jl,u8 as Ur,UInt as Gr,union as Jl,Union as em,unionLayoutDiscriminator as tm,utf8 as nm}from"@solana/buffer-layout";var ln=vr,oi=Dr;var zn=Gr;var ii=Ur,ie=Wr;var _t=qr;var _e=Vr;var ri=Er;var X=Fr;var Xn=Mr,Yn=_r;var ut=class extends ln{constructor(t,n,i){super(t,i);this.blob=X(t),this.signed=n}decode(t,n=0){let i=new ai(this.blob.decode(t,n),10,"le");return this.signed?i.fromTwos(this.span*8).clone():i}encode(t,n,i=0){return typeof t=="number"&&(t=new ai(t)),this.signed&&(t=t.toTwos(this.span*8)),this.blob.encode(t.toArrayLike(Buffer,"le",this.span),n,i)}},mn=class extends ln{constructor(t){super(8,t);this._lower=Xn(_t(),!1),this._upper=Xn(_t(),!1)}addBoolean(t){this._lower.fields.length<32?this._lower.addBoolean(t):this._upper.addBoolean(t)}decode(t,n=0){let i=this._lower.decode(t,n),r=this._upper.decode(t,n+this._lower.span);return F(F({},i),r)}encode(t,n,i=0){return this._lower.encode(t,n,i)+this._upper.encode(t,n,i+this._lower.span)}};function k(a){return new zn(1,a)}function ue(a){return new zn(4,a)}function o(a){return new ut(8,!1,a)}function G(a){return new ut(16,!1,a)}function ui(a){return new ut(1,!0,a)}function Pt(a){return new ut(8,!0,a)}function ci(a){return new ut(16,!0,a)}var ct=class extends ln{constructor(t,n,i,r){super(t.span,r);this.layout=t,this.decoder=n,this.encoder=i}decode(t,n){return this.decoder(this.layout.decode(t,n))}encode(t,n,i){return this.layout.encode(this.encoder(t),n,i)}getSpan(t,n){return this.layout.getSpan(t,n)}};function m(a){return new ct(X(32),e=>new zr(e),e=>e.toBuffer(),a)}function Me(a){return new ct(ii(),Xr,Yr,a)}function Xr(a){if(a===0)return!1;if(a===1)return!0;throw new Error("Invalid bool: "+a)}function Yr(a){return a?1:0}function Qn(a,e){let t=_t("length"),n=T([t,R(a,Yn(t,-t.span),"values")]);return new ct(n,({values:i})=>i,i=>({values:i}),e)}function Hr(a){let e=_t("length"),t=T([e,X(Yn(e,-e.span),"data")]);return new ct(t,({data:n})=>n,n=>({data:n}),a)}function Ke(a){return new ct(Hr(),e=>e.toString("utf-8"),e=>Buffer.from(e,"utf-8"),a)}var Hn=class extends oi{decode(e,t){return super.decode(e,t)}};function T(a,e,t){return new Hn(a,e,t)}function R(a,e,t){let n,i=typeof e=="number"?e:si(e)?e.toNumber():new Proxy(e,{get(r,s){if(!n){let l=Reflect.get(r,"count");n=si(l)?l.toNumber():l,Reflect.set(r,"count",n)}return Reflect.get(r,s)},set(r,s,l){return s==="count"&&(n=l),Reflect.set(r,s,l)}});return ri(a,i,t)}var dn=T([m("mint"),m("owner"),o("amount"),ue("delegateOption"),m("delegate"),k("state"),ue("isNativeOption"),o("isNative"),o("delegatedAmount"),ue("closeAuthorityOption"),m("closeAuthority")]);import{PublicKey as sA,SystemProgram as uA}from"@solana/web3.js";import{createAssociatedTokenAccountIdempotentInstruction as lA}from"@solana/spl-token";import{PublicKey as ta}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as na}from"@solana/spl-token";import{ComputeBudgetProgram as mi,Keypair as pi,PublicKey as Zr,Transaction as fi,TransactionMessage as $r,VersionedTransaction as yi}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as jr}from"@solana/spl-token";var di=H("Raydium_txUtil"),bi=1644;function fn(a){let e=[],t=[];return a.microLamports&&(e.push(mi.setComputeUnitPrice({microLamports:a.microLamports})),t.push(ye.SetComputeUnitPrice)),a.units&&(e.push(mi.setComputeUnitLimit({units:a.units})),t.push(ye.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}async function At(a,e){var n,i;let t=e!=null?e:"confirmed";return(i=await((n=a.getLatestBlockhash)==null?void 0:n.call(a,{commitment:t})))==null?void 0:i.blockhash}async function yn(a,e){return a.getSignatureStatuses([e]),new Promise((t,n)=>{let i=setTimeout(n,6e4);a.onSignature(e,r=>{if(clearTimeout(i),!r.err){t("");return}n(Object.assign(r.err,{txId:e}))},"confirmed")})}function Zn(a,e){a.length<1&&di.logWithError(`no instructions provided: ${a.toString()}`),e.length<1&&di.logWithError(`no signers provided:, ${e.toString()}`);let t=new fi;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...a);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<bi}catch{return!1}}function re(a,e){let[t,n]=Zr.findProgramAddressSync(a,e);return{publicKey:t,nonce:n}}function Vt({instructions:a,payer:e,signers:t}){return Zn(a,[e,...t])}function Et({instructions:a,payer:e,lookupTableAddressAccount:t,recentBlockhash:n=pi.generate().publicKey.toString()}){let r=new $r({payerKey:e,recentBlockhash:n,instructions:a}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new yi(r).serialize()).toString("base64").length<bi}catch{return!1}}var Jr=a=>Buffer.isBuffer(a)?a:a instanceof Uint8Array?Buffer.from(a.buffer,a.byteOffset,a.byteLength):Buffer.from(a),ea=a=>{let e=a.serialize({requireAllSignatures:!1,verifySignatures:!1});a instanceof yi&&(e=Jr(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch{return e.toString("base64")}};function lt(a){let e=[];return a.forEach(t=>{t instanceof fi&&(t.recentBlockhash||(t.recentBlockhash=jr.toBase58()),t.feePayer||(t.feePayer=pi.generate().publicKey)),e.push(ea(t))}),console.log("simulate tx string:",e),e}function pe(a,e,t){return re([a.toBuffer(),(t!=null?t:na).toBuffer(),e.toBuffer()],new ta("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}import{PublicKey as D}from"@solana/web3.js";var gi=new D("EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"),Pi=new D("CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T"),Ai=new D("9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z"),$n=new D("FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG"),Cd=new D("CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS"),oa=new D("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"),wi=new D("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),ki=new D("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"),Rd=new D("5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h"),ia=new D("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),Ti=new D("CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"),ra=new D("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),aa=new D("kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy"),hi=new D("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),Ld=new D("routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS"),sa=new D("7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"),jn=new D("CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"),ua=new D("GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"),Od=new D("DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8"),ca=new D("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),la=new D("3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH"),ae=new D("LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"),Nd=new D("WLHv2UAZm6z4KyaaELi5pjdbJh6RESMva1Rnn8pJVVh"),Md=new D("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),Fd=new D("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),vd=new D("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),_d=new D("6s1xP3hpbAfFoNtUNF8mfHsjr2Bd97JxFJRWLbL6aHuX");var Je={OPEN_BOOK_PROGRAM:new D("EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj"),SERUM_PROGRAM_ID_V3:new D("Ray1111111111111111111111111111111111111111"),AMM_V4:new D("DRaya7Kj3aMWQSy19kSjvmuwq9docCHofyP9kanQGaav"),AMM_STABLE:new D("DRayDdXc1NZQ9C3hRWmoSf8zK4iapgMnjdNZWrfwsP8m"),CLMM_PROGRAM_ID:new D("DRayAUgENGQBKVaX8owNhgzkEDyoHTGVEGHVJT1E9pfH"),CLMM_LOCK_PROGRAM_ID:new D("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),CLMM_LOCK_AUTH_ID:new D("6Aoh8h2Lw2m5UGxYR8AdAL87jTWYeKoxM52mJRzfYwN"),CREATE_CPMM_POOL_PROGRAM:new D("DRaycpLY18LhpbydsBWbVJtxpNv9oXPgjRSfpF2bWpYb"),CREATE_CPMM_POOL_AUTH:new D("CXniRufdq5xL8t8jZAPxsPZDpuudwuJSPWnbcD5Y5Nxq"),CREATE_CPMM_POOL_FEE_ACC:new D("3oE58BKVt8KuYkGxx8zBojugnymWmBiyafWgMrnb6eYy"),LOCK_CPMM_PROGRAM:new D("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),LOCK_CPMM_AUTH:new D("7qWVV8UY2bRJfDLP4s37YzBPKUkVB46DStYJBpYbQzu3"),UTIL1216:D.default,Router:new D("DRaybByLpbUL57LJARs3j8BitTxVfzBg351EaMr5UTCd"),FARM_PROGRAM_ID_V3:new D("DRayWyrLmEW5KEeqs8kdTMMaBabapqagaBC7KWpGtJeZ"),FARM_PROGRAM_ID_V4:new D("Ray1111111111111111111111111111111111111111"),FARM_PROGRAM_ID_V5:new D("DRayiCGSZgku1GTK6rXD6mVDdingXy6APAH1R6R5L2LC"),FARM_PROGRAM_ID_V6:new D("DRayzbYakXs45ELHkzH6vC3fuhQqTAnv5A68gdFuvZyZ"),LAUNCHPAD_PROGRAM:new D("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),LAUNCHPAD_AUTH:new D("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),LAUNCHPAD_PLATFORM:new D("2Jx4KTDrVSdWNazuGpcA8n3ZLTRGGBDxAWhuKe2Xcj2a"),LAUNCHPAD_CONFIG:new D("7ZR4zD7PYfY2XxoG1Gxcy2EgEeGYrpxrwzPuwdUBssEt"),FEE_DESTINATION_ID:new D("9y8ENuuZ3b19quffx9hQvRVygG5ky6snHfRvGpuSfeJy"),MODEL_DATA_PUBKEY:new D("Ray1111111111111111111111111111111111111111")};import wA from"decimal.js";import{createAssociatedTokenAccountIdempotentInstruction as qb,TOKEN_2022_PROGRAM_ID as Ub,TOKEN_PROGRAM_ID as Gb}from"@solana/spl-token";import{PublicKey as Xb}from"@solana/web3.js";import Hb from"bn.js";import Zb from"decimal.js";import{TOKEN_PROGRAM_ID as $d}from"@solana/spl-token";import{PublicKey as tp}from"@solana/web3.js";var ma=T([ue("mintAuthorityOption"),m("mintAuthority"),o("supply"),k("decimals"),k("isInitialized"),ue("freezeAuthorityOption"),m("freezeAuthority")]);import{ASSOCIATED_TOKEN_PROGRAM_ID as cb,TOKEN_2022_PROGRAM_ID as lb,TOKEN_PROGRAM_ID as mb}from"@solana/spl-token";import{Keypair as fb,PublicKey as yb,SystemProgram as gb,TransactionInstruction as Pb}from"@solana/web3.js";import wb from"bn.js";import Q from"bn.js";var Ve=new Q(1).shln(64);var da=new Q(1).shln(128),bn=new Q(1).shln(64).subn(1),pa=new Q(1).shln(128).subn(1);var kt=new Q("4295048016"),Tt=new Q("79226673521066979257578248091"),fa=new Q("59543866431248"),ya=new Q("184467440737095516"),ba=new Q("15793534762490258745");var Jn=60,pp=new Q("18446743708227953217"),ga=[{bit:0,factor:new Q("fffcb933bd6fb800",16)},{bit:1,factor:new Q("fff97272373d4000",16)},{bit:2,factor:new Q("fff2e50f5f657000",16)},{bit:3,factor:new Q("ffe5caca7e10f000",16)},{bit:4,factor:new Q("ffcb9843d60f7000",16)},{bit:5,factor:new Q("ff973b41fa98e800",16)},{bit:6,factor:new Q("ff2ea16466c9b000",16)},{bit:7,factor:new Q("fe5dee046a9a3800",16)},{bit:8,factor:new Q("fcbe86c7900bb000",16)},{bit:9,factor:new Q("f987a7253ac65800",16)},{bit:10,factor:new Q("f3392b0822bb6000",16)},{bit:11,factor:new Q("e7159475a2caf000",16)},{bit:12,factor:new Q("d097f3bdfd2f2000",16)},{bit:13,factor:new Q("a9f746462d9f8000",16)},{bit:14,factor:new Q("70d869a156f31c00",16)},{bit:15,factor:new Q("31be135f97ed3200",16)},{bit:16,factor:new Q("9aa508b5b85a500",16)},{bit:17,factor:new Q("5d6af8dedc582c",16)},{bit:18,factor:new Q("2216e584f5fa",16)}];var Dt=3,Ii=100;var Bi=10,Si=100,gn=14;var be=new Q(0),ht=new Q(1),fp=new Q(-1);var yp=new Q("18446744073700000000");var Pa=T([X(8),k("bump"),ie("index"),m("owner"),ue("protocolFeeRate"),ue("tradeFeeRate"),ie("tickSpacing"),ue("fundFeeRate"),R(ue(),1),m("fundOwner"),R(o(),3)]),Aa=T([ue("blockTimestamp"),Pt("tickCumulative"),R(o(),4)]),Ki=T([X(8),Me("initialized"),o("recentEpoch"),ie("observationIndex"),m("poolId"),R(Aa,Ii,"observations"),R(o(),4)]),wa=T([ie("filterPeriod"),ie("decayPeriod"),ie("reductionFactor"),ue("dynamicFeeControl"),ue("maxVolatilityAccumulator"),_e("tickSpacingIndexReference"),ue("volatilityReference"),ue("volatilityAccumulator"),o("lastUpdateTimestamp"),R(k(),46)]),ka=T([k("state"),o("openTime"),o("endTime"),o("lastUpdateTime"),G("emissionsPerSecondX64"),o("totalEmissioned"),o("claimed"),m("mint"),m("vault"),m("creator"),G("growthGlobalX64")]),eo=T([X(8),k("bump"),m("configId"),m("creator"),m("mintA"),m("mintB"),m("vaultA"),m("vaultB"),m("observationId"),k("mintDecimalsA"),k("mintDecimalsB"),ie("tickSpacing"),G("liquidity"),G("sqrtPriceX64"),_e("tickCurrent"),ue(),G("feeGrowthGlobalX64A"),G("feeGrowthGlobalX64B"),o("protocolFeesTokenA"),o("protocolFeesTokenB"),R(G(),4),k("status"),k("feeOn"),X(6),R(ka,Dt,"rewardInfos"),X(8*16,"tickArrayBitmap"),R(o(),4),o("fundFeesTokenA"),o("fundFeesTokenB"),o("startTime"),o("recentEpoch"),wa.replicate("dynamicFeeInfo"),R(o(),46)]),Ta=T([G("growthInsideLastX64"),o("rewardAmountOwed")]),ha=T([X(8),k("bump"),m("nftMint"),m("poolId"),_e("tickLower"),_e("tickUpper"),G("liquidity"),G("feeGrowthInsideLastX64A"),G("feeGrowthInsideLastX64B"),o("tokenFeesOwedA"),o("tokenFeesOwedB"),R(Ta,Dt,"rewardInfos"),o("recentEpoch"),R(o(),7)]),Ap=T([X(8),k("bump"),m("poolId"),_e("tickLower"),_e("tickUpper"),G("liquidity"),G("feeGrowthInsideLastX64A"),G("feeGrowthInsideLastX64B"),o("tokenFeesOwedA"),o("tokenFeesOwedB"),R(G(),Dt,"rewardGrowthInside"),o("recentEpoch"),R(o(),7)]),Ia=T([_e("tick"),ci("liquidityNet"),G("liquidityGross"),G("feeGrowthOutsideX64A"),G("feeGrowthOutsideX64B"),R(G(),Dt,"rewardGrowthsOutsideX64"),o("orderPhase"),o("ordersAmount"),o("partFilledOrdersRemaining"),G("unfilledRatioX64"),R(ue(),3)]),xi=T([X(8),m("poolId"),_e("startTickIndex"),R(Ia,Jn,"ticks"),k("initializedTickCount"),o("recentEpoch"),R(k(),107)]),Ba=T([X(8),k("bump"),R(m(),Bi,"operationOwners"),R(m(),Si,"whitelistMints")]),Sa=T([X(8),m("poolId"),m("owner"),_e("tick"),Me("zeroForOne"),o("orderPhase"),o("totalAmount"),o("filledAmount"),o("settleBase"),o("settleOutput"),o("openTime"),G("unfilledRatioX64"),R(o(),4)]),Ci=T([X(8),m("poolId"),X(8*8*gn,"positiveTickArrayBitmap"),X(8*8*gn,"negativeTickArrayBitmap")]),wp=T([X(8),ie("index"),ie("filterPeriod"),ie("decayPeriod"),ie("reductionFactor"),ue("dynamicFeeControl"),ue("maxVolatilityAccumulator"),R(o(),8)]),Ka=T([X(8),m("wallet"),k("nonceIndex"),o("orderNonce"),R(o(),4)]),kp=T([o(),k("bump"),m("owner"),m("poolId"),m("positionId"),m("nftAccount"),R(o(),8)]),xa=T([X(8),k("bump"),m("lockOwner"),m("poolId"),m("positionId"),m("nftAccount"),m("lockNftMint"),o("recentEpoch"),R(o(),8)]);import Ip from"bn.js";function to(a){let e=Buffer.alloc(2);return e.writeUInt16LE(a),e}var Fp=Buffer.from("amm_config","utf8"),Ri=Buffer.from("pool","utf8"),Li=Buffer.from("pool_vault","utf8"),vp=Buffer.from("pool_reward_vault","utf8"),_p=Buffer.from("position","utf8"),Vp=Buffer.from("tick_array","utf8"),Ep=Buffer.from("operation","utf8"),Dp=Buffer.from("pool_tick_array_bitmap_extension","utf8"),Wp=Buffer.from("observation","utf8"),qp=Buffer.from("support_mint","utf8"),Up=Buffer.from("dynamic_fee_config","utf8"),Gp=Buffer.from("permission","utf8");function Pn(a){return re([Buffer.from("metadata","utf8"),st.toBuffer(),a.toBuffer()],st)}var zp=Buffer.from("locked_position","utf8");import{sha256 as Ua}from"js-sha256";import Ca from"bn.js";import Qp from"decimal.js";var $p=new Ca(1).shln(256).subn(1);import bf from"bn.js";import rf from"bn.js";import sf from"decimal.js";import kf from"bn.js";import hf from"decimal.js";import{PublicKey as cy}from"@solana/web3.js";import my from"bn.js";import{TOKEN_2022_PROGRAM_ID as Ay,TOKEN_PROGRAM_ID as wy}from"@solana/spl-token";import Iy from"decimal.js";import jf from"bn.js";import Ef from"bn.js";import Fy from"bn.js";function ge(a){let e=`global:${a}`;return Buffer.from(Ua.digest(e)).slice(0,8)}Ki.span;var Cb=H("Raydium_Clmm"),Rb={createPool:ge("create_pool"),createCustomizablePool:ge("create_customizable_pool"),createPermissionedPool:ge("create_permissioned_pool"),openPositionV2:ge("open_position_v2"),openPositionWithToken22Nft:ge("open_position_with_token22_nft"),closePosition:ge("close_position"),increaseLiquidityV2:ge("increase_liquidity_v2"),decreaseLiquidityV2:ge("decrease_liquidity_v2"),initializeReward:ge("initialize_reward"),setRewardParams:ge("set_reward_params"),updateRewardInfos:ge("update_reward_infos"),collectRemainingRewards:ge("collect_remaining_rewards"),swapV2:ge("swap_v2"),openLimitOrder:ge("open_limit_order"),increaseLimitOrder:ge("increase_limit_order"),decreaseLimitOrder:ge("decrease_limit_order"),settleLimitOrder:ge("settle_limit_order"),closeLimitOrder:ge("close_limit_order")};import{PublicKey as ro}from"@solana/web3.js";var Ya=T([k("instruction")]),Ha=T([k("instruction")]),Qa=T([o("rewardState"),o("rewardOpenTime"),o("rewardEndTime"),o("rewardLastUpdateTime"),o("totalReward"),o("totalRewardEmissioned"),o("rewardClaimed"),o("rewardPerSecond"),G("accRewardPerShare"),m("rewardVault"),m("rewardMint"),m("rewardSender"),o("rewardType"),R(o(),15,"padding")]),Za=T([o("state"),o("nonce"),m("lpVault"),m("rewardVault"),m(),m(),o(),o(),o("totalReward"),G("perShareReward"),o("lastSlot"),o("perSlotReward")]),$a=T([o("state"),o("nonce"),m("lpVault"),m("rewardVaultA"),o("totalRewardA"),G("perShareRewardA"),o("perSlotRewardA"),k("option"),m("rewardVaultB"),X(7),o("totalRewardB"),G("perShareRewardB"),o("perSlotRewardB"),o("lastSlot"),m()]),ja=T([o(),o("state"),o("nonce"),o("validRewardTokenNum"),G("rewardMultiplier"),o("rewardPeriodMax"),o("rewardPeriodMin"),o("rewardPeriodExtend"),m("lpMint"),m("lpVault"),R(Qa,5,"rewardInfos"),m("creator"),m(),R(o(),32,"padding")]),Ja=new Proxy(Za,{get(a,e,t){return e==="decode"?(...n)=>{let i=a.decode(...n);return U(F({},i),{version:3,rewardInfos:[{rewardVault:i.rewardVault,totalReward:i.totalReward,perSlotReward:i.perSlotReward,perShareReward:i.perShareReward}]})}:Reflect.get(a,e,t)}}),es=new Proxy($a,{get(a,e,t){return e==="decode"?(...n)=>{let i=a.decode(...n);return U(F({},i),{version:5,rewardInfos:[{rewardVault:i.rewardVaultA,totalReward:i.totalRewardA,perSlotReward:i.perSlotRewardA,perShareReward:i.perShareRewardA},{rewardVault:i.rewardVaultB,totalReward:i.totalRewardB,perSlotReward:i.perSlotRewardB,perShareReward:i.perShareRewardB}]})}:Reflect.get(a,e,t)}}),_i=new Proxy(ja,{get(a,e,t){return e==="decode"?(...n)=>{let i=a.decode(...n);return U(F({},i),{version:6,rewardInfos:i.rewardInfos.map(r=>{var s;return U(F({},r),{rewardType:((s=Object.entries(Ut).find(l=>String(l[1])===r.rewardType.toString()))!=null?s:["Standard SPL"])[0]})})})}:Reflect.get(a,e,t)}}),ts=T([o("isSet"),o("rewardPerSecond"),o("rewardOpenTime"),o("rewardEndTime"),o("rewardType")]),ns=T([k("instruction"),o("nonce"),R(ts,5,"rewardTimeInfo")]),os=T([k("instruction"),o("rewardReopenTime"),o("rewardEndTime"),o("rewardPerSecond")]),is=T([k("instruction"),o("isSet"),o("rewardPerSecond"),o("rewardOpenTime"),o("rewardEndTime"),o("rewardType")]),Bg=T([o("state"),m("id"),m("owner"),o("deposited"),R(o(),1,"rewardDebts")]),Vi=T([o("state"),m("id"),m("owner"),o("deposited"),R(G(),1,"rewardDebts"),o(""),o("voteLockedBalance"),R(o(),15)]),Sg=T([o("state"),m("id"),m("owner"),o("deposited"),R(o(),2,"rewardDebts")]),rs=T([o("state"),m("id"),m("owner"),o("deposited"),R(G(),2,"rewardDebts"),R(o(),17)]),as=T([o(),o("state"),m("id"),m("owner"),o("deposited"),R(G(),5,"rewardDebts"),R(o(),16)]),ss=T([k("instruction"),o("amount")]),us=T([m("mint"),m("grantAuthority"),o("baselineVoteWeightScaledFactor"),o("maxExtraLockupVoteWeightScaledFactor"),o("lockupSaturationSecs"),ui("digitShift"),R(k(),7,"reserved1"),R(o(),7,"reserved2")]),cs=T([X(8),m("governanceProgramId"),m("realm"),m("realmGoverningTokenMint"),m("realmAuthority"),R(k(),32,"reserved1"),R(us,4,"votingMints"),Pt("timeOffset"),k("bump"),R(k(),7,"reserved2"),R(o(),11,"reserved3")]),ls=T([Pt("startTime"),Pt("endTime"),k("kind"),R(k(),15,"reserved")]),ms=T([R(ls,1,"lockup"),o("amountDeposited_native"),o("amountInitiallyLockedNative"),Me("isUsed"),Me("allowClawback"),k("votingMintConfigIdx"),R(k(),29,"reserved")]),ds=T([X(8),m("voterAuthority"),m("registrar"),R(ms,32,"deposits"),k("voterBump"),k("voterWweightRecordBump"),R(k(),94,"reserved")]);import{NATIVE_MINT as Fg}from"@solana/spl-token";var vg=H("Raydium_farm_config"),ps=new ro("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),fs=new ro("FrspKwj8i3pNmKwXreTveC4fu7KL5ZbGeXdZBe2XViu1");var _g=new ro("3TRTX4dXUpp2eqxi3tvQDFYUV7SdDJjcPE3Y4mbtftaX");var Ut={"Standard SPL":0,"Option tokens":1},Ei={[gi.toString()]:3,[Pi.toString()]:4,[Ai.toString()]:5,[$n.toString()]:6,[Je.FARM_PROGRAM_ID_V3.toString()]:3,[Je.FARM_PROGRAM_ID_V4.toString()]:4,[Je.FARM_PROGRAM_ID_V5.toString()]:5,[Je.FARM_PROGRAM_ID_V6.toString()]:6};import{PublicKey as TP,SystemProgram as hP,SYSVAR_CLOCK_PUBKEY as IP,SYSVAR_RENT_PUBKEY as BP,TransactionInstruction as SP}from"@solana/web3.js";import xP from"bn.js";import{ASSOCIATED_TOKEN_PROGRAM_ID as RP,createAssociatedTokenAccountIdempotentInstruction as LP,TOKEN_PROGRAM_ID as OP}from"@solana/spl-token";import jg from"bn.js";import{PublicKey as Ug}from"@solana/web3.js";import zg from"bn.js";var mP=H("Raydium.farm.util");var UP=H("Raydium_farm_instruction"),GP={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])};import LA from"bn.js";import{PublicKey as _k}from"@solana/web3.js";import{AccountLayout as Dk,MintLayout as Wk,NATIVE_MINT as qk,TOKEN_PROGRAM_ID as Gk}from"@solana/spl-token";import Te from"bn.js";var Gt=1e4;function hn(a,e){let{div:t,mod:n}=a.divmod(e);return n.gt(new Te(0))?t.add(new Te(1)):t}function dt(a,e){if(a.isZero())return new Te(0);let t=a.div(e);return t.isZero()?new Te(1):a.mod(e).gt(new Te(0))?t.add(new Te(1)):t}function zt(a,e,t){if(e===void 0)return{amount:a,fee:void 0,expirationTime:void 0};let n=Math.floor(t/432e3),i=n<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,r=new Te(i.maximumFee.toString()),s=n<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*432e3-t)*400/1e3:void 0,l=hn(a.mul(new Te(i.transferFeeBasisPoints)),new Te(Gt)),c=l.gt(r)?r:l;return{amount:a,fee:c,expirationTime:s}}function Bt(a,e,t){if(e===void 0)return{amount:a,fee:void 0,expirationTime:void 0};let n=Math.floor(t/432e3),i=n<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,r=new Te(i.maximumFee.toString()),s=n<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*432e3-t)*400/1e3:void 0;if(i.transferFeeBasisPoints===Gt){let l=new Te(i.maximumFee.toString());return{amount:a.add(l),fee:l,expirationTime:s}}else{let l=hn(a.mul(new Te(Gt)),new Te(Gt-i.transferFeeBasisPoints)),c=new Te(i.maximumFee.toString()),u=l.sub(a).gt(c)?a.add(c):l,d=hn(u.mul(new Te(i.transferFeeBasisPoints)),new Te(Gt)),p=d.gt(r)?r:d;return{amount:u,fee:p,expirationTime:s}}}import Wi from"bn.js";var Ts=new Wi(25),hs=new Wi(1e4);import{ASSOCIATED_TOKEN_PROGRAM_ID as tw,TOKEN_PROGRAM_ID as nw}from"@solana/spl-token";import{PublicKey as iw,SystemProgram as rw,SYSVAR_RENT_PUBKEY as aw,TransactionInstruction as sw}from"@solana/web3.js";import yw from"bn.js";var Is=T([k("instruction"),o("amountIn"),o("minAmountOut")]),Bs=T([k("instruction"),o("maxAmountIn"),o("amountOut")]),$A=T([k("instruction"),k("nonce")]),Ss=T([k("instruction"),k("nonce"),o("startTime")]),qi=T([o("status"),o("nonce"),o("maxOrder"),o("depth"),o("baseDecimal"),o("quoteDecimal"),o("state"),o("resetFlag"),o("minSize"),o("volMaxCutRatio"),o("amountWaveRatio"),o("baseLotSize"),o("quoteLotSize"),o("minPriceMultiplier"),o("maxPriceMultiplier"),o("systemDecimalValue"),o("minSeparateNumerator"),o("minSeparateDenominator"),o("tradeFeeNumerator"),o("tradeFeeDenominator"),o("pnlNumerator"),o("pnlDenominator"),o("swapFeeNumerator"),o("swapFeeDenominator"),o("baseNeedTakePnl"),o("quoteNeedTakePnl"),o("quoteTotalPnl"),o("baseTotalPnl"),o("poolOpenTime"),o("punishPcAmount"),o("punishCoinAmount"),o("orderbookToInitTime"),G("swapBaseInAmount"),G("swapQuoteOutAmount"),o("swapBase2QuoteFee"),G("swapQuoteInAmount"),G("swapBaseOutAmount"),o("swapQuote2BaseFee"),m("baseVault"),m("quoteVault"),m("baseMint"),m("quoteMint"),m("lpMint"),m("openOrders"),m("marketId"),m("marketProgramId"),m("targetOrders"),m("withdrawQueue"),m("lpVault"),m("owner"),o("lpReserve"),R(o(),3,"padding")]),jA=T([o("accountType"),o("status"),o("nonce"),o("maxOrder"),o("depth"),o("baseDecimal"),o("quoteDecimal"),o("state"),o("resetFlag"),o("minSize"),o("volMaxCutRatio"),o("amountWaveRatio"),o("baseLotSize"),o("quoteLotSize"),o("minPriceMultiplier"),o("maxPriceMultiplier"),o("systemDecimalsValue"),o("abortTradeFactor"),o("priceTickMultiplier"),o("priceTick"),o("minSeparateNumerator"),o("minSeparateDenominator"),o("tradeFeeNumerator"),o("tradeFeeDenominator"),o("pnlNumerator"),o("pnlDenominator"),o("swapFeeNumerator"),o("swapFeeDenominator"),o("baseNeedTakePnl"),o("quoteNeedTakePnl"),o("quoteTotalPnl"),o("baseTotalPnl"),o("poolOpenTime"),o("punishPcAmount"),o("punishCoinAmount"),o("orderbookToInitTime"),G("swapBaseInAmount"),G("swapQuoteOutAmount"),G("swapQuoteInAmount"),G("swapBaseOutAmount"),o("swapQuote2BaseFee"),o("swapBase2QuoteFee"),m("baseVault"),m("quoteVault"),m("baseMint"),m("quoteMint"),m("lpMint"),m("modelDataAccount"),m("openOrders"),m("marketId"),m("marketProgramId"),m("targetOrders"),m("owner"),R(o(),64,"padding")]),Ks=T([k("instruction"),o("baseAmountIn"),o("quoteAmountIn"),o("fixedSide"),o("otherAmountMin")]),xs=T([k("instruction"),o("lpAmount"),o("baseAmountMin"),o("quoteAmountMin")]);var Cs=T([o("fee")]);var Pw=H("Raydium_liquidity_instruction");var Rs=5e4,Ls=T([o("x"),o("y"),o("price")]),Tw=T([o("accountType"),o("status"),o("multiplier"),o("validDataCount"),R(Ls,Rs,"DataElement")]);import{PublicKey as Mw}from"@solana/web3.js";import vw from"decimal.js";import{TOKEN_PROGRAM_ID as Vw}from"@solana/spl-token";import{PublicKey as Sw}from"@solana/web3.js";var Cw=H("Raydium_liquidity_serum");import lT from"bn.js";import dT from"decimal.js";import{TOKEN_PROGRAM_ID as mk}from"@solana/spl-token";import{PublicKey as pk}from"@solana/web3.js";import yk from"bn.js";import{SystemProgram as jw,SYSVAR_RENT_PUBKEY as Jw,Transaction as ek,TransactionInstruction as tk}from"@solana/web3.js";import{createInitializeAccountInstruction as ok,TOKEN_PROGRAM_ID as ik}from"@solana/spl-token";function Os(a="accountFlags"){let e=new mn(a);return e.addBoolean("initialized"),e.addBoolean("market"),e.addBoolean("openOrders"),e.addBoolean("requestQueue"),e.addBoolean("eventQueue"),e.addBoolean("bids"),e.addBoolean("asks"),e}var Ns=T([X(5),Os("accountFlags"),m("ownAddress"),o("vaultSignerNonce"),m("baseMint"),m("quoteMint"),m("baseVault"),o("baseDepositsTotal"),o("baseFeesAccrued"),m("quoteVault"),o("quoteDepositsTotal"),o("quoteFeesAccrued"),o("quoteDustThreshold"),m("requestQueue"),m("eventQueue"),m("bids"),m("asks"),o("baseLotSize"),o("quoteLotSize"),o("feeRateBps"),o("referrerRebatesAccrued"),X(7)]);import{PublicKey as Dh}from"@solana/web3.js";import{AccountLayout as qh,NATIVE_MINT as Uh,TOKEN_2022_PROGRAM_ID as Gh,TOKEN_PROGRAM_ID as zh,createAssociatedTokenAccountIdempotentInstruction as Xh}from"@solana/spl-token";import vT from"bn.js";import Ds from"bn.js";var TT=new Ds(0);import xT from"bn.js";import Ws from"bn.js";var Ue=new Ws(1e6);import eI from"bn.js";import nI from"decimal.js";import{PublicKey as nh,TransactionInstruction as oh,Keypair as rh,SystemProgram as ah}from"@solana/web3.js";import{ASSOCIATED_TOKEN_PROGRAM_ID as uh,TOKEN_2022_PROGRAM_ID as ch,TOKEN_PROGRAM_ID as lh}from"@solana/spl-token";var WT=Buffer.from("vault_and_lp_mint_auth_seed","utf8"),qT=Buffer.from("amm_config","utf8"),UT=Buffer.from("pool","utf8"),GT=Buffer.from("pool_lp_mint","utf8"),zT=Buffer.from("pool_vault","utf8"),XT=Buffer.from("observation","utf8"),YT=Buffer.from("permission","utf8"),HT=Buffer.from("support_mint","utf8"),QT=Buffer.from("creator_fee_share","utf8");var ZT=Buffer.from("locked_liquidity","utf8");var gh=H("Raydium_cpmm"),Ph={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])};var Us=T([X(8),k("bump"),Me("disableCreatePool"),ie("index"),o("tradeFeeRate"),o("protocolFeeRate"),o("fundFeeRate"),o("createPoolFee"),m("protocolOwner"),m("fundOwner"),o("creatorFeeRate"),o("creatorFeeShareRate"),R(o(),14)]),Ui=T([X(8),m("configId"),m("poolCreator"),m("vaultA"),m("vaultB"),m("mintLp"),m("mintA"),m("mintB"),m("mintProgramA"),m("mintProgramB"),m("observationId"),k("bump"),k("status"),k("lpDecimals"),k("mintDecimalA"),k("mintDecimalB"),o("lpAmount"),o("protocolFeesMintA"),o("protocolFeesMintB"),o("fundFeesMintA"),o("fundFeesMintB"),o("openTime"),o("epoch"),k("feeOn"),Me("enableCreatorFee"),R(k(),6),o("creatorFeesMintA"),o("creatorFeesMintB"),R(o(),28)]),kh=T([X(8),m("configId"),R(o(),30)]),Th=T([X(8),k("bump"),m("creator"),m("ammConfig"),o("shareRate"),R(o(),8)]);import{PublicKey as cK,SystemProgram as lK}from"@solana/web3.js";import{createTransferInstruction as dK,TOKEN_PROGRAM_ID as pK,TOKEN_2022_PROGRAM_ID as fK,createAssociatedTokenAccountIdempotentInstruction as yK,createSyncNativeInstruction as gK,createTransferCheckedInstruction as PK}from"@solana/spl-token";import mu from"bn.js";import kK from"decimal.js";import{ASSOCIATED_TOKEN_PROGRAM_ID as In,TOKEN_2022_PROGRAM_ID as tu,TOKEN_PROGRAM_ID as nu}from"@solana/spl-token";import{SystemProgram as we,TransactionInstruction as me}from"@solana/web3.js";import xt from"bn.js";var Xs=Buffer.from("vault_auth_seed","utf8"),Ys=Buffer.from("global_config","utf8"),Hs=Buffer.from("pool_vesting","utf8"),Qs=Buffer.from("platform_config","utf8"),Zs=Buffer.from("platform_fee_vault_auth_seed","utf8"),$s=Buffer.from("creator_fee_vault_auth_seed","utf8"),QI=Buffer.from("platform_global_access","utf8"),js=Buffer.from("platform_allow_config","utf8"),Js=Buffer.from("platform_curve_rule","utf8");function Ee(a){return re([Xs],a)}function uo(a,e,t,n){return re([Ys,e.toBuffer(),eu(t),to(n)],a)}function St(a,e,t){return re([Ri,e.toBuffer(),t.toBuffer()],a)}function co(a,e,t){return re([Li,e.toBuffer(),t.toBuffer()],a)}function pt(a){return re([Buffer.from("__event_authority","utf8")],a)}function eu(a){let e=new ArrayBuffer(1);return new DataView(e).setUint8(0,a),new Uint8Array(e)}function lo(a,e){return re([Qs,e.toBuffer()],a)}function Kt(a,e,t){return re([Hs,e.toBuffer(),t.toBuffer()],a)}function et(a,e,t){return re([e.toBuffer(),t.toBuffer()],a)}function mo(a){return re([Zs],a)}function tt(a,e,t){return re([e.toBuffer(),t.toBuffer()],a)}function po(a){return re([$s],a)}function Xt(a,e,t){return re([js,e.toBuffer(),t.toBuffer()],a)}function fo(a,e,t){return re([Js,e.toBuffer(),t.toBuffer()],a)}var de={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 zi(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f,y,P,h,B,K,C,I,S,L){let x=T([k("decimals"),Ke("name"),Ke("symbol"),Ke("uri")]),O=T([o("totalLockedAmount"),o("cliffPeriod"),o("unlockPeriod"),k("cpmmCreatorFeeOn")]),M=T([k("index"),o("supply"),o("totalFundRaisingB"),k("migrateType")]),E=T([k("index"),o("supply"),o("totalSellA"),o("totalFundRaisingB"),k("migrateType")]),q=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!0,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:nu,isSigner:!1,isWritable:!1},{pubkey:g,isSigner:!1,isWritable:!1},{pubkey:st,isSigner:!1,isWritable:!1},{pubkey:we.programId,isSigner:!1,isWritable:!1},{pubkey:gt,isSigner:!1,isWritable:!1},{pubkey:pt(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];S&&q.push({pubkey:S,isSigner:!1,isWritable:!1}),L&&q.push({pubkey:L,isSigner:!1,isWritable:!1});let _=Buffer.alloc(Buffer.from(f,"utf-8").length+Buffer.from(y,"utf-8").length+Buffer.from(P,"utf-8").length+4*3+1),N=Buffer.alloc(O.span),W=Buffer.alloc(h.type==="ConstantCurve"?E.span:M.span);return x.encode({decimals:b,name:f,symbol:y,uri:P},_),h.type==="ConstantCurve"?E.encode(U(F({index:0},h),{migrateType:h.migrateType==="amm"?0:1}),W):h.type==="FixedCurve"?M.encode(U(F({index:1},h),{migrateType:h.migrateType==="amm"?0:1}),W):h.type==="LinearCurve"&&M.encode(U(F({index:2},h),{migrateType:h.migrateType==="amm"?0:1}),W),O.encode({totalLockedAmount:B,cliffPeriod:K,unlockPeriod:C,cpmmCreatorFeeOn:I},N),new me({keys:q,programId:a,data:Buffer.from([...de.initializeV2,..._,...W,...N])})}function Xi(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f,y,P,h,B,K,C,I,S,L){let x=T([k("decimals"),Ke("name"),Ke("symbol"),Ke("uri")]),O=T([o("totalLockedAmount"),o("cliffPeriod"),o("unlockPeriod"),k("cpmmCreatorFeeOn"),k("transferFeeExtensionParamsOption"),T([ie("transferFeeBasePoints"),o("maxinumFee")]).replicate("transferFeeExtensionParams")]),M=T([k("index"),o("supply"),o("totalFundRaisingB"),k("migrateType")]),E=T([k("index"),o("supply"),o("totalSellA"),o("totalFundRaisingB"),k("migrateType")]),q=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!0,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:tu,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:we.programId,isSigner:!1,isWritable:!1},{pubkey:pt(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];S&&q.push({pubkey:S,isSigner:!1,isWritable:!1}),L&&q.push({pubkey:L,isSigner:!1,isWritable:!1});let _=Buffer.alloc(Buffer.from(b,"utf-8").length+Buffer.from(f,"utf-8").length+Buffer.from(y,"utf-8").length+4*3+1),N=Buffer.alloc(O.span),W=Buffer.alloc(P.type==="ConstantCurve"?E.span:M.span);return x.encode({decimals:g,name:b,symbol:f,uri:y},_),P.type==="ConstantCurve"?E.encode(U(F({index:0},P),{migrateType:P.migrateType==="amm"?0:1}),W):P.type==="FixedCurve"?M.encode(U(F({index:1},P),{migrateType:P.migrateType==="amm"?0:1}),W):P.type==="LinearCurve"&&M.encode(U(F({index:2},P),{migrateType:P.migrateType==="amm"?0:1}),W),O.encode({totalLockedAmount:h,cliffPeriod:B,unlockPeriod:K,cpmmCreatorFeeOn:C,transferFeeExtensionParamsOption:I?1:0,transferFeeExtensionParams:I!=null?I:{transferFeeBasePoints:0,maxinumFee:new xt(0)}},N),new me({keys:q,programId:a,data:Buffer.from([...de.initializeWithToken2022,..._,...W,...N])})}function yo(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f,y,P,h,B,K){let C=T([o("amountB"),o("minAmountA"),o("shareFeeRate")]),I=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:g,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:pt(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];K&&I.push({pubkey:K,isSigner:!1,isWritable:!0}),I.push({pubkey:we.programId,isSigner:!1,isWritable:!1}),I.push({pubkey:f,isSigner:!1,isWritable:!0}),I.push({pubkey:y,isSigner:!1,isWritable:!0});let S=Buffer.alloc(C.span);return C.encode({amountB:P,minAmountA:h,shareFeeRate:B!=null?B:new xt(0)},S),new me({keys:I,programId:a,data:Buffer.from([...de.buyExactIn,...S])})}function Yi(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f,y,P,h,B,K){let C=T([o("amountA"),o("maxAmountB"),o("shareFeeRate")]),I=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:g,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:pt(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];K&&I.push({pubkey:K,isSigner:!1,isWritable:!0}),I.push({pubkey:we.programId,isSigner:!1,isWritable:!1}),I.push({pubkey:f,isSigner:!1,isWritable:!0}),I.push({pubkey:y,isSigner:!1,isWritable:!0});let S=Buffer.alloc(C.span);return C.encode({amountA:P,maxAmountB:h,shareFeeRate:B!=null?B:new xt(0)},S),new me({keys:I,programId:a,data:Buffer.from([...de.buyExactOut,...S])})}function bo(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f,y,P,h,B,K){let C=T([o("amountA"),o("minAmountB"),o("shareFeeRate")]),I=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:g,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:pt(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];K&&I.push({pubkey:K,isSigner:!1,isWritable:!0}),I.push({pubkey:we.programId,isSigner:!1,isWritable:!1}),I.push({pubkey:f,isSigner:!1,isWritable:!0}),I.push({pubkey:y,isSigner:!1,isWritable:!0});let S=Buffer.alloc(C.span);return C.encode({amountA:P,minAmountB:h,shareFeeRate:B!=null?B:new xt(0)},S),new me({keys:I,programId:a,data:Buffer.from([...de.sellExactIn,...S])})}function Hi(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f,y,P,h,B,K){let C=T([o("amountB"),o("maxAmountA"),o("shareFeeRate")]),I=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:g,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:pt(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];K&&I.push({pubkey:K,isSigner:!1,isWritable:!0}),I.push({pubkey:we.programId,isSigner:!1,isWritable:!1}),I.push({pubkey:f,isSigner:!1,isWritable:!0}),I.push({pubkey:y,isSigner:!1,isWritable:!0});let S=Buffer.alloc(C.span);return C.encode({amountB:P,maxAmountA:h,shareFeeRate:B!=null?B:new xt(0)},S),new me({keys:I,programId:a,data:Buffer.from([...de.sellExactOut,...S])})}function go(a,e,t,n,i,r,s,l,c){let u=T([]),d=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:we.programId,isSigner:!1,isWritable:!1},{pubkey:In,isSigner:!1,isWritable:!1}],p=Buffer.alloc(u.span);return u.encode({},p),new me({keys:d,programId:a,data:Buffer.from([...de.claimVestedToken,...p])})}function Po(a,e,t,n,i,r){let s=T([o("shareAmount")]),l=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:we.programId,isSigner:!1,isWritable:!1}],c=Buffer.alloc(s.span);return s.encode({shareAmount:r},c),new me({keys:l,programId:a,data:Buffer.from([...de.createVestingAccount,...c])})}function Ao(a,e,t,n,i,r,s,l,c){let u=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:we.programId,isSigner:!1,isWritable:!0},{pubkey:In,isSigner:!1,isWritable:!0}];return new me({keys:u,programId:a,data:de.claimPlatformFee})}function Qi(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f){let y=T([o("platformScale"),o("creatorScale"),o("burnScale"),o("feeRate"),Ke("name"),Ke("web"),Ke("img"),o("creatorFeeRate"),o("platformVestingScale")]),P=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:we.programId,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1}],h=Buffer.alloc(8*6+Buffer.from(p,"utf-8").length+Buffer.from(g,"utf-8").length+Buffer.from(b,"utf-8").length+4*3);return y.encode({platformScale:c.platformScale,creatorScale:c.creatorScale,burnScale:c.burnScale,feeRate:u,name:p,web:g,img:b,creatorFeeRate:d,platformVestingScale:f},h),new me({keys:P,programId:a,data:Buffer.from([...de.createPlatformConfig,...h])})}function Zi(a,e,t,n){let i=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0}],r;if(n.type==="updateClaimFeeWallet"){let s=T([k("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:0,value:n.value},r)}else if(n.type==="updateLockNftWallet"){let s=T([k("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:1,value:n.value},r)}else if(n.type==="migrateCpLockNftScale"){let s=T([k("index"),o("platformScale"),o("creatorScale"),o("burnScale")]);r=Buffer.alloc(s.span),s.encode(F({index:2},n.value),r)}else if(n.type==="updateFeeRate"){let s=T([k("index"),o("value")]);r=Buffer.alloc(s.span),s.encode({index:3,value:n.value},r)}else if(n.type==="updateImg"||n.type==="updateName"||n.type==="updateWeb"){let s=T([k("index"),Ke("value")]);r=Buffer.alloc(Buffer.from(n.value,"utf-8").length+4+1*1),n.type==="updateName"?s.encode({index:4,value:n.value},r):n.type==="updateWeb"?s.encode({index:5,value:n.value},r):n.type==="updateImg"&&s.encode({index:6,value:n.value},r)}else if(n.type==="updateCpConfigId"){i.push({pubkey:n.value,isSigner:!1,isWritable:!1});let s=T([k("index")]);r=Buffer.alloc(s.span),s.encode({index:7},r)}else if(n.type==="updateAll"){i.push({pubkey:n.value.cpConfigId,isSigner:!1,isWritable:!1});let s=T([k("index"),m("platformClaimFeeWallet"),m("platformLockNftWallet"),o("platformScale"),o("creatorScale"),o("burnScale"),o("feeRate"),Ke("name"),Ke("web"),Ke("img"),m("transferFeeExtensionAuth"),o("creatorFeeRate"),o("platformVestingScale"),m("platformVestingWallet")]);r=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),s.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},r)}else if(n.type==="updateVestingWallet"){let s=T([k("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:9,value:n.value},r)}else if(n.type==="updatePlatformVestingScale"){let s=T([k("index"),o("value")]);r=Buffer.alloc(s.span),s.encode({index:10,value:n.value},r)}else if(n.type==="updatePlatformCpCreator"){let s=T([k("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:11,value:n.value},r)}else if(n.type==="updateRestrictGlobalConfig"){let s=T([k("index"),o("value")]);r=Buffer.alloc(s.span),s.encode({index:12,value:n.value},r)}else if(n.type==="updateRestrictCurveParam"){let s=T([k("index"),o("value")]);r=Buffer.alloc(s.span),s.encode({index:13,value:n.value},r)}else if(n.type==="updateCurveRuleManager"){let s=T([k("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:14,value:n.value},r)}else throw Error("updateInfo params type error");return new me({keys:i,programId:a,data:Buffer.from([...de.updatePlaformConfig,...r])})}function wo(a,e,t,n,i,r,s,l){let c=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:we.programId,isSigner:!1,isWritable:!1},{pubkey:In,isSigner:!1,isWritable:!1}];return new me({keys:c,programId:a,data:de.claimPlatformFeeFromVault})}function ko(a,e,t,n,i,r,s){let l=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:we.programId,isSigner:!1,isWritable:!1},{pubkey:In,isSigner:!1,isWritable:!1}];return new me({keys:l,programId:a,data:de.claimCreatorFee})}var rB=new xt("18446744073709551615");function $i(a,e,t,n,i,r){let s=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:we.programId,isSigner:!1,isWritable:!1}];return new me({keys:s,programId:a,data:de.createPlatformVestingAccount})}function ji(a,e,t,n,i){let r=[{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:we.programId,isSigner:!1,isWritable:!1}];return new me({keys:r,programId:a,data:de.createPlatformAllowConfig})}function Ji(a,e,t,n,i){let r=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0}];return new me({keys:r,programId:a,data:de.closePlatformAllowConfig})}function ou(a){let e=T([k("field"),k("op"),G("value")]),t=Buffer.alloc(4+a.length*e.span);return t.writeUInt32LE(a.length,0),a.forEach((n,i)=>{e.encode(n,t,4+i*e.span)}),t}function er(a,e,t,n,i){let r=[{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:we.programId,isSigner:!1,isWritable:!1}];return new me({keys:r,programId:a,data:de.createPlatformCurveRule})}function tr(a,e,t,n,i,r,s){let l=[{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:we.programId,isSigner:!1,isWritable:!1}],c=Buffer.alloc(ie().span);return ie().encode(r,c),new me({keys:l,programId:a,data:Buffer.from([...de.updatePlatformCurveRule,...c,...ou(s)])})}function nr(a,e,t,n,i,r){let s=[{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:we.programId,isSigner:!1,isWritable:!1}],l=Buffer.alloc(ie().span);return ie().encode(r,l),new me({keys:s,programId:a,data:Buffer.from([...de.removePlatformCurveRule,...l])})}function or(a,e,t,n,i){let r=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0}];return new me({keys:r,programId:a,data:de.closePlatformCurveRule})}var nt=T([o(),o("epoch"),k("curveType"),ie("index"),o("migrateFee"),o("tradeFeeRate"),o("maxShareFeeRate"),o("minSupplyA"),o("maxLockRate"),o("minSellRateA"),o("minMigrateRateA"),o("minFundRaisingB"),m("mintB"),m("protocolFeeOwner"),m("migrateFeeOwner"),m("migrateToAmmWallet"),m("migrateToCpmmWallet"),R(o(),16)]),iu=T([o("totalLockedAmount"),o("cliffPeriod"),o("unlockPeriod"),o("startTime"),o("totalAllocatedShare")]),De=T([o(),o("epoch"),k("bump"),k("status"),k("mintDecimalsA"),k("mintDecimalsB"),k("migrateType"),o("supply"),o("totalSellA"),o("virtualA"),o("virtualB"),o("realA"),o("realB"),o("totalFundRaisingB"),o("protocolFee"),o("platformFee"),o("migrateFee"),iu.replicate("vestingSchedule"),m("configId"),m("platformId"),m("mintA"),m("mintB"),m("vaultA"),m("vaultB"),m("creator"),k("mintProgramFlag"),k("cpmmCreatorFeeOn"),o("platformVestingShare"),R(k(),54)]),cB=T([o(),o("epoch"),m("poolId"),m("beneficiary"),o("claimedAmount"),o("tokenShareAmount"),R(o(),8)]),ru=T([k("migrateType"),k("migrateCpmmFeeOn"),o("supply"),o("totalSellA"),o("totalFundRaisingB"),o("totalLockedAmount"),o("cliffPeriod"),o("unlockPeriod")]),lB=T([o("epoch"),k("index"),m("configId"),ru.replicate("bondingCurveParam"),R(o(),50)]),ft=T([o(),o("epoch"),m("platformClaimFeeWallet"),m("platformLockNftWallet"),o("platformScale"),o("creatorScale"),o("burnScale"),o("feeRate"),R(k(),64,"name"),R(k(),256,"web"),R(k(),256,"img"),m("cpConfigId"),o("creatorFeeRate"),m("transferFeeExtensionAuth"),m("platformVestingWallet"),o("platformVestingScale"),m("platformCpCreator"),k("restrictGlobalConfig"),k("restrictCurveParam"),m("curveRuleManager"),R(k(),78)]),au=T([k("field"),k("op"),G("value")]),su=T([ie("groupId"),o("epoch"),Qn(au,"constraints")]),Bn=T([o(),k("bump"),k("version"),m("platformId"),m("configId"),o("epoch"),R(o(),8),Qn(su,"groups")]);import{TOKEN_2022_PROGRAM_ID as ir,TOKEN_PROGRAM_ID as pB}from"@solana/spl-token";function rr({mintAProgram:a,mintBProgram:e}){return(a.equals(ir)?1<<0:0)|(e.equals(ir)?1<<1:0)}import uu from"bn.js";var BB=new uu(1e6);import Sn from"bn.js";import Yt from"decimal.js";var ot=class{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){throw Error()}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i}){throw Error()}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){throw Error()}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:i,migrateFee:r,decimalA:s,decimalB:l}){throw Error()}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){throw Error()}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:i,migrateFee:r}){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 Kn=class extends ot{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new Yt(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i}){return new Yt(t.toString()).div(e.toString()).mul(10**(n-i))}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new Yt(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:i,migrateFee:r,decimalA:s,decimalB:l}){return new Yt(i.sub(r).toString()).div(e.sub(t).sub(n).toString()).mul(10**(s-l))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){let i=e.totalSellA.sub(e.realA),r=e.totalFundRaisingB.sub(e.realB);return new Yt(e.virtualB.add(e.realB.add(r)).toString()).div(e.virtualA.sub(e.realA.add(i)).toString()).mul(10**(t-n))}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:i,migrateFee:r}){if(e.lte(n))throw Error("supply need gt total sell");let s=e.sub(n).sub(i);if(s.lte(new Sn(0)))throw Error("supplyMinusSellLocked <= 0");let l=t.sub(r);if(l.lte(new Sn(0)))throw Error("tfMinusMf <= 0");let c=l.mul(n).mul(n).div(s),u=l.mul(n).div(s).sub(t),d=c.div(u),p=t.mul(t).div(u);if(d.lt(new Sn(0))||p.lt(new Sn(0)))throw Error("invalid input 0");return{a:d,b:p,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 i=e.mul(n),r=t.add(e);return i.div(r)}static getAmountIn({amountOut:e,inputReserve:t,outputReserve:n}){let i=t.mul(e),r=n.sub(e);return dt(i,r)}};import Re from"bn.js";import sr from"decimal.js";import xn from"bn.js";import Ht from"decimal.js";var Cn=class extends ot{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new Ht(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i}){return new Ht(t.toString()).div(e.toString()).mul(10**(n-i))}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new Ht(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:i,migrateFee:r,decimalA:s,decimalB:l}){return new Ht(i.sub(r).toString()).div(e.sub(t).sub(n).toString()).mul(10**(s-l))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){let i=e.totalSellA.sub(e.realA),r=e.totalFundRaisingB.sub(e.realB);return new Ht(e.virtualB.add(e.realB).add(r).toString()).div(e.virtualA.sub(e.realA).add(i).toString()).mul(10**(t-n))}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:i,migrateFee:r}){let s=e.sub(i);if(s.lte(new xn(0)))throw Error("invalid input 1");let l=new xn(2).mul(t).sub(r),u=t.mul(s).div(l);if(u.lt(new xn(0))||t.lt(new xn(0)))throw Error("invalid input 0");return{a:u,b:t,c:u}}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 i=t.mul(e);return dt(i,n)}};import Ce from"bn.js";import yt from"decimal.js";import ar from"bn.js";import To from"decimal.js";var Qt=class{static _multipler(e){return new To(10).pow(e)}static getPrice({priceX64:e,decimalA:t,decimalB:n}){return new To(e.toString()).div(this._Q64).mul(this._multipler(t)).div(this._multipler(n))}static getPriceX64({price:e,decimalA:t,decimalB:n}){let i=e.mul(this._multipler(n)).div(this._multipler(t));return new ar(i.mul(this._Q64).toFixed(0))}};Qt._Q64=new To(new ar(1).shln(64).toString());var Rn=class extends ot{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new yt(0)}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i}){return new yt(0)}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new yt(e.virtualA.mul(e.realA).toString()).div(Qt._Q64).mul(10**(t-n))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:i,migrateFee:r,decimalA:s,decimalB:l}){return new yt(i.sub(r).toString()).div(e.sub(t).sub(n).toString()).mul(10**(s-l))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){let i=e.totalSellA.sub(e.realA),r=e.totalFundRaisingB.sub(e.realB);return new yt(e.virtualB.add(e.realB).add(r).toString()).div(e.virtualA.sub(e.realA).add(i).toString()).mul(10**(t-n))}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:i,migrateFee:r}){let s=e.sub(i);if(s.lte(new Ce(0)))throw Error("supplyMinusLocked need gt 0");let l=t.mul(new Ce(3)).sub(r),u=t.mul(new Ce(2)).mul(s).div(l),d=u.mul(u),p=t.mul(new Ce(2)).mul(Ve).div(d);if(!p.gt(new Ce(0)))throw Error("a need gt 0");if(!bn.gt(p))throw Error("a need lt u64 max");if(p.lt(new Ce(0))||u.lt(new Ce(0)))throw Error("invalid input 0");return{a:p,b:new Ce(0),c:u}}static buyExactIn({poolInfo:e,amount:t}){let n=e.realB.add(t),i=new Ce(2).mul(n).mul(Ve).div(e.virtualA);return new Ce(new yt(i.toString()).sqrt().toFixed(0)).sub(e.realA)}static buyExactOut({poolInfo:e,amount:t}){let n=e.realA.add(t),i=n.mul(n);return dt(e.virtualA.mul(i),new Ce(2).mul(Ve)).sub(e.realB)}static sellExactIn({poolInfo:e,amount:t}){let n=e.realA.sub(t),i=n.mul(n),r=dt(e.virtualA.mul(i),new Ce(2).mul(Ve));return e.realB.sub(r)}static sellExactOut({poolInfo:e,amount:t}){let n=e.realB.sub(t),i=new Ce(2).mul(n).mul(Ve).div(e.virtualA),r=new Ce(new yt(i.toString()).sqrt().toFixed(0));return e.realA.sub(r)}};var Oe=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:i,totalSell:r,totalLockedAmount:s,migrateFee:l,decimalA:c,decimalB:u}){if(t<3)throw Error("point count < 3");let d=this.getCurve(e),p=d.getInitParam({supply:n,totalFundRaising:i,totalSell:r,totalLockedAmount:s,migrateFee:l}),g=d.getPoolInitPriceByInit(U(F({},p),{decimalA:c,decimalB:u})),b=i.div(new Re(t-1)),f=new Re(0),y=[{price:g,totalSellSupply:0}],{a:P,b:h}=p,B=f,K=f;for(let C=1;C<t;C++){let I=C!==t-1?b:i.sub(K),S=this.buyExactIn({poolInfo:{virtualA:P,virtualB:h,realA:B,realB:K,totalFundRaisingB:i,totalSellA:r},amountB:I,protocolFeeRate:f,platformFeeRate:f,curveType:e,shareFeeRate:f,creatorFeeRate:f,transferFeeConfigA:void 0,transferFeeConfigB:void 0,slot:0});B=B.add(S.amountA.amount),K=K.add(S.amountB);let L=this.getPrice({poolInfo:{virtualA:P,virtualB:h,realA:B,realB:K},decimalA:c,decimalB:u,curveType:e});y.push({price:L,totalSellSupply:new sr(B.toString()).div(10**c).toNumber()})}return y}static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n,curveType:i}){return this.getCurve(i).getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n})}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i,curveType:r}){return this.getCurve(r).getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i})}static getPrice({poolInfo:e,curveType:t,decimalA:n,decimalB:i}){return this.getCurve(t).getPoolPrice({poolInfo:e,decimalA:n,decimalB:i})}static getEndPrice({poolInfo:e,curveType:t,decimalA:n,decimalB:i}){return this.getCurve(t).getPoolPrice({poolInfo:e,decimalA:n,decimalB:i})}static getPoolEndPriceReal({poolInfo:e,curveType:t,decimalA:n,decimalB:i}){return this.getCurve(t).getPoolEndPriceReal({poolInfo:e,decimalA:n,decimalB:i})}static checkParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:i,decimals:r,config:s,migrateType:l}){if(Number(r)!==6)throw Error("decimals = 6");if(e.mul(s.maxLockRate).div(Ue).lt(i))throw Error("total lock amount gte max lock amount");if(e.lt(s.minSupplyA.mul(new Re(10**r))))throw Error("supply lt min supply");let u=e.mul(s.minSellRateA).div(Ue);if(n.lt(u))throw Error("invalid input");if(t.lt(s.minFundRaisingB))throw Error("total fund raising lt min fund raising");let d=e.sub(n).sub(i),p=e.mul(s.minMigrateRateA).div(Ue);if(d.lt(p))throw Error("migrate lt min migrate amoount");let g=e.sub(n).sub(i),b=new Re(new sr(g.mul(t).toString()).sqrt().toFixed(0));if(l==="amm"){let f=new Re(10).pow(new Re(r));if(b.lte(f))throw Error("check migrate lp error")}else if(l==="cpmm"){let f=new Re(100);if(b.lte(f))throw Error("check migrate lp error")}else throw Error("migrate type error")}static buyExactIn({poolInfo:e,amountB:t,protocolFeeRate:n,platformFeeRate:i,curveType:r,shareFeeRate:s,creatorFeeRate:l,transferFeeConfigA:c,transferFeeConfigB:u,slot:d}){var x;let p=zt(t,u,d),g=t.sub((x=p.fee)!=null?x:new Re(0)),b=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l}),f=this.calculateFee({amount:g,feeRate:b}),y=g.sub(f),P=this.getCurve(r),h=P.buyExactIn({poolInfo:e,amount:y}),B=e.totalSellA.sub(e.realA),K,C,I,S;if(h.gt(B)){K=B;let O=P.buyExactOut({poolInfo:e,amount:K}),M=this.calculatePreFee({postFeeAmount:O,feeRate:b});I=M.sub(O);let E=Bt(M,u,d);C=E.amount,S=E.fee}else K=h,C=t,I=f,S=p.fee;let L=this.splitFee({totalFee:I,protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l});return{amountA:zt(K,c,d),amountB:C,splitFee:L,transferFeeB:S}}static buyExactOut({poolInfo:e,amountA:t,protocolFeeRate:n,platformFeeRate:i,curveType:r,shareFeeRate:s,creatorFeeRate:l,transferFeeConfigA:c,transferFeeConfigB:u,slot:d}){let p=e.totalSellA.sub(e.realA),g=Bt(t,c,d),b=g.fee?g.amount.add(g.fee):g.amount;t.gt(p)&&(b=p);let y=this.getCurve(r).buyExactOut({poolInfo:e,amount:b}),P=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l}),h=this.calculatePreFee({postFeeAmount:y,feeRate:P}),B=h.sub(y),K=Bt(h,u,d),C=this.splitFee({totalFee:B,protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l});return{amountA:g,amountB:K.amount,splitFee:C,transferFeeB:K.fee}}static sellExactIn({poolInfo:e,amountA:t,protocolFeeRate:n,platformFeeRate:i,curveType:r,shareFeeRate:s,creatorFeeRate:l,transferFeeConfigA:c,transferFeeConfigB:u,slot:d}){var K;let p=this.getCurve(r),g=zt(t,c,d),b=g.fee?g.amount.sub(g.fee):g.amount,f=p.sellExactIn({poolInfo:e,amount:b}),y=this.calculateFee({amount:f,feeRate:this.totalFeeRate({protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l})}),P=this.splitFee({totalFee:y,protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l}),h=f.sub(y),B=zt(h,u,d);return{amountA:g,amountB:h.sub((K=B.fee)!=null?K:new Re(0)),splitFee:P,transferFeeB:B.fee}}static sellExactOut({poolInfo:e,amountB:t,protocolFeeRate:n,platformFeeRate:i,curveType:r,shareFeeRate:s,creatorFeeRate:l,transferFeeConfigA:c,transferFeeConfigB:u,slot:d}){let p=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l}),g=Bt(t,u,d),b=g.amount,f=this.calculatePreFee({postFeeAmount:b,feeRate:p});if(e.realB.lt(f))throw Error("Insufficient liquidity");let y=f.sub(b),h=Oe.getCurve(r).sellExactOut({poolInfo:e,amount:f});if(h.gt(e.realA))throw Error();let B=this.splitFee({totalFee:y,protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l});return{amountA:Bt(h,c,d),amountB:t,splitFee:B,transferFeeB:g.fee}}static splitFee({totalFee:e,protocolFeeRate:t,platformFeeRate:n,shareFeeRate:i,creatorFeeRate:r}){let s=this.totalFeeRate({protocolFeeRate:t,platformFeeRate:n,shareFeeRate:i,creatorFeeRate:r}),l=s.isZero()?new Re(0):e.mul(n).div(s),c=s.isZero()?new Re(0):e.mul(i).div(s),u=s.isZero()?new Re(0):e.mul(r).div(s),d=e.sub(l).sub(c).sub(u);return{platformFee:l,shareFee:c,protocolFee:d,creatorFee:u}}static calculateFee({amount:e,feeRate:t}){return so(e,t,Ue)}static calculatePreFee({postFeeAmount:e,feeRate:t}){if(t.isZero())return e;let n=e.mul(Ue),i=Ue.sub(t);return n.add(i).sub(new Re(1)).div(i)}static totalFeeRate({protocolFeeRate:e,platformFeeRate:t,shareFeeRate:n,creatorFeeRate:i}){if(e.add(t).add(n).add(i).gt(new Re(1e6)))throw Error("total fee rate gt 1_000_000");return e.add(t).add(n).add(i)}static getCurve(e){switch(e){case 0:return Kn;case 1:return Cn;case 2:return Rn}throw Error("find curve error")}};var cu={[wi.toBase58()]:3};var lu=T([X(5),X(8),m("ownAddress"),o("vaultSignerNonce"),m("baseMint"),m("quoteMint"),m("baseVault"),o("baseDepositsTotal"),o("baseFeesAccrued"),m("quoteVault"),o("quoteDepositsTotal"),o("quoteFeesAccrued"),o("quoteDustThreshold"),m("requestQueue"),m("eventQueue"),m("bids"),m("asks"),o("baseLotSize"),o("quoteLotSize"),o("feeRateBps"),o("referrerRebatesAccrued"),X(7)]);import{PublicKey as KS}from"@solana/web3.js";var OS=H("Serum");import{ASSOCIATED_TOKEN_PROGRAM_ID as WS,TOKEN_2022_PROGRAM_ID as qS,TOKEN_PROGRAM_ID as US}from"@solana/spl-token";import{PublicKey as zS,SystemProgram as XS,TransactionInstruction as YS}from"@solana/web3.js";import QS from"bn.js";var $K=new mu(0);import{PublicKey as du,Transaction as ho,TransactionInstruction as pu}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as fu}from"@solana/spl-token";import ur from"bn.js";var he=class extends Se{static getPdaPoolId(e,t){return re([he.SEED_CONFIG.pool.id,t.toBuffer()],e)}static getPdaOwnerId(e,t,n,i){return re([he.SEED_CONFIG.owner.id,t.toBuffer(),n.toBuffer(),Buffer.from(new ur(i).toArray())],e)}static async getAllInfo({connection:e,programId:t,poolIds:n,wallet:i,chainTime:r}){if(n.length===0)return[];let s=n.map(d=>he.getPdaPoolId(t,d).publicKey),l=[];for(let d=0;d<he.VERSION_PROJECT.length;d++)l.push(...s.map(p=>he.getPdaOwnerId(t,p,i,d).publicKey));let c=await Ge(e,[...s,...l]),u=[];for(let d=0;d<c.length;d++){let p=Math.floor(d/n.length),g=d%n.length,b=s[g],f=l[d],y=c[g],P=c[n.length+d];if(!(y&&P)||y.data.length!==he.POOL_LAYOUT.span||P.data.length!==he.OWNER_LAYOUT.span)continue;let h=he.POOL_LAYOUT.decode(y.data),B=he.OWNER_LAYOUT.decode(P.data),K=h.openTime.toNumber(),C=h.endTime.toNumber(),I=B.tokenInfo.map(x=>x.debtAmount.gt(new ur(0))).filter(x=>!x).length!==3,S=r>K&&r<C&&h.status===1,L=I&&S;u.push({programId:t,poolId:b,ammId:h.ammId,ownerAccountId:f,snapshotLpAmount:B.lpAmount,project:he.VERSION_PROJECT[p],openTime:K,endTime:C,canClaim:L,canClaimErrorType:I?S?void 0:"outOfOperationalTime":"alreadyClaimIt",tokenInfo:h.tokenInfo.map((x,O)=>({mintAddress:x.mintAddress,mintVault:x.mintVault,mintDecimals:x.mintDecimals,perLpLoss:x.perLpLoss,debtAmount:B.tokenInfo[O].debtAmount.add(B.tokenInfo[O].claimedAmount)}))})}return u}async makeClaimTransaction({poolInfo:e,ownerInfo:t,feePayer:n}){t.wallet||this.scope.checkOwner();let i=this.createTxBuilder(n),r=t.wallet||this.scope.ownerPubKey,s=[];for(let u of e.tokenInfo){let{account:d,instructionParams:p}=await this.scope.account.getOrCreateTokenAccount({mint:u.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:u.mintAddress.equals(ke.WSOL.mint),createInfo:{payer:r,amount:0},skipCloseAccount:!u.mintAddress.equals(ke.WSOL.mint),associatedOnly:u.mintAddress.equals(ke.WSOL.mint)?!1:t.associatedOnly});p&&i.addInstruction(p),s.push(d)}i.addInstruction({instructions:[he.makeClaimInstruction({programId:e.programId,poolInfo:e,ownerInfo:{wallet:r,ownerPda:e.ownerAccountId,claimAddress:s}})]});let{transaction:l,signers:c}=i.build();return[{transaction:l,signer:c}]}async makeClaimAllTransaction({poolInfos:e,ownerInfo:t,feePayer:n}){let i=this.createTxBuilder(n),r=t.wallet||this.scope.ownerPubKey,s={};for(let d of e){let p=[];for(let g of d.tokenInfo){let{account:b,instructionParams:f}=await this.scope.account.getOrCreateTokenAccount({mint:g.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:g.mintAddress.equals(ke.WSOL.mint),createInfo:{payer:r,amount:0},skipCloseAccount:!g.mintAddress.equals(ke.WSOL.mint),associatedOnly:g.mintAddress.equals(ke.WSOL.mint)?!1:t.associatedOnly});f&&i.addInstruction(f),b&&(s[g.mintAddress.toString()]=b,p.push(b))}i.addInstruction({instructions:[he.makeClaimInstruction({programId:d.programId,poolInfo:d,ownerInfo:{wallet:r,ownerPda:d.ownerAccountId,claimAddress:p}})]})}let{transaction:l,signers:c}=i.build(),u=i.allInstructions;return Zn(u,[r,...c.map(d=>d.publicKey)])?[{transaction:l,signer:c}]:[{transaction:new ho().add(...u.slice(0,i.AllTxData.instructions.length-1)),signer:c},{transaction:new ho().add(...u.slice(i.AllTxData.instructions.length-1)),signer:[]},{transaction:new ho().add(...i.AllTxData.endInstructions),signer:[]}]}static makeClaimInstruction({programId:e,poolInfo:t,ownerInfo:n}){let i=T([]),r=[{pubkey:n.wallet,isSigner:!0,isWritable:!0},{pubkey:t.poolId,isSigner:!1,isWritable:!0},{pubkey:n.ownerPda,isSigner:!1,isWritable:!0},...n.claimAddress.map(c=>({pubkey:c,isSigner:!1,isWritable:!0})),...t.tokenInfo.map(({mintVault:c})=>({pubkey:c,isSigner:!1,isWritable:!0})),{pubkey:fu,isSigner:!1,isWritable:!1}],s=Buffer.alloc(i.span);i.encode({},s);let l=Buffer.from([10,66,208,184,161,6,191,98,...s]);return new pu({keys:r,programId:e,data:l})}},We=he;We.CLAIMED_NUM=3,We.POOL_LAYOUT=T([X(8),k("bump"),k("status"),o("openTime"),o("endTime"),m("ammId"),R(T([k("mintDecimals"),m("mintAddress"),m("mintVault"),o("perLpLoss"),o("totalClaimedAmount")]),he.CLAIMED_NUM,"tokenInfo"),R(o(),10,"padding")]),We.OWNER_LAYOUT=T([X(8),k("bump"),k("version"),m("poolId"),m("owner"),o("lpAmount"),R(T([m("mintAddress"),o("debtAmount"),o("claimedAmount")]),he.CLAIMED_NUM,"tokenInfo"),R(o(),4,"padding")]),We.DEFAULT_POOL_ID=["58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2","6UmmUiYoBjSrhakAobJw8BvkmJtDVxaeBtbt7rxWo1mg","AVs9TA4nWDzfPJE9gGVNJMVhcQy3V9PGazuz33BfG2RA","DVa7Qmb5ct9RCpaU7UTpSaf3GVMYz17vNVU67XpdCRut","7XawhbbxtsRcQA8KTkHT9f9nc6d69UwqCDh6U5EEbEmX","6a1CsrpeZubDjEJE9s1CMVheB6HWM5d7m1cj2jkhyXhj","EoNrn8iUhwgJySD1pHu8Qxm5gSQqLK3za4m8xzD2RuEb","AceAyRTWt4PyB2pHqf2qhDgNZDtKVNaxgL8Ru3V4aN1P","6tmFJbMk5yVHFcFy7X2K8RwHjKLr6KVFLYXpgpBNeAxB"].map(e=>new du(e)),We.SEED_CONFIG={pool:{id:Buffer.from("pool_seed","utf8")},owner:{id:Buffer.from("user_claim_seed","utf8")}},We.VERSION_PROJECT=[void 0,"Francium","Tulip","Larix"];import{PublicKey as fx}from"@solana/web3.js";import{getTransferFeeConfig as bx,MintLayout as gx,TOKEN_2022_PROGRAM_ID as Px,TOKEN_PROGRAM_ID as Ax,unpackMint as wx}from"@solana/spl-token";var YC=new it(2),HC=new it(3),QC=new it(5),Br=new it(10),ZC=new it(100),$C=new it(1e3),jC=new it(1e4);function so(a,e,t){return a.mul(e).add(t).sub(new it(1)).div(t)}function Io(a,e=1,t=[]){let n=[...a];if(e<=0)return t;for(;n.length;)t.push(n.splice(0,e));return t}import{MINT_SIZE as KR,TOKEN_PROGRAM_ID as xR,getTransferFeeConfig as CR,unpackMint as RR}from"@solana/spl-token";var Bo=H("Raydium_accountInfo_util");async function Ge(a,e,t){let{batchRequest:n,commitment:i="confirmed",chunkCount:r=100}=F({batchRequest:!1},t),s=Io(e,r),l=new Array(s.length).fill([]);if(n){let c=s.map(p=>{let g=a._buildArgs([p.map(b=>b.toBase58())],i,"base64");return{methodName:"getMultipleAccounts",args:g}}),u=Io(c,10);l=(await(await Promise.all(u.map(async p=>await a._rpcBatchRequest(p)))).flat()).map(p=>(p.error&&Bo.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${p.error.message}`),p.result.value.map(g=>{if(g){let{data:b,executable:f,lamports:y,owner:P,rentEpoch:h}=g;return b.length!==2&&b[1]!=="base64"&&Bo.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(b[0],"base64"),executable:f,lamports:y,owner:new yu(P),rentEpoch:h}}return null})))}else try{l=await Promise.all(s.map(c=>a.getMultipleAccountsInfo(c,i)))}catch(c){c instanceof Error&&Bo.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${c.message}`)}return l.flat()}async function xe(a,e,t){let n=await Ge(a,e.map(i=>i.pubkey),t);return e.map((i,r)=>U(F({},i),{accountInfo:n[r]}))}async function Ko({connection:a,address:e,cluster:t="mainnet"}){let n=await Ge(a,[...new Set(e.map(r=>r.toString()))].map(r=>new So(r))),i={};for(let r=0;r<e.length;r++){let s=n[r],l=e[r];if(!s)continue;let c=new Lt({key:l,state:Lt.deserialize(s.data)});i[l.toString()]=c,t==="devnet"?Rt[l.toString()]=c:Ct[l.toString()]=c}return i}var Ct={},xo=async a=>{let e="AcL1Vo8oy1ULiavEcjSUcwfBSForXMudcZvDZy5nzJkU";if(Ct[e])return Ct;let t=new So(e),n=await a.getAccountInfo(t);return n&&(Ct[e]=new Lt({key:t,state:Lt.deserialize(n.data)})),Ct},Rt={},Co=async a=>{let e="EFhMuDw1PKEuckuFRW9PavNfTH4LKP5uKHgyXDmWpFCq";if(Rt[e])return Rt;let t=new So(e),n=await a.getAccountInfo(t);return n&&(Rt[e]=new Lt({key:t,state:Lt.deserialize(n.data)})),Rt};var On=2e3,Nn=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 gu.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}=fn(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...n),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(bu.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new Ot(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(ye.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:i=[],endInstructionTypes:r=[],lookupTableAddress:s=[]}){return this.instructions.push(...e),this.endInstructions.push(...t),this.signers.push(...n),this.instructionTypes.push(...i),this.endInstructionTypes.push(...r),this.lookupTableAddress.push(...s.filter(l=>l!==Ot.default.toString())),this}async versionBuild({txVersion:e,extInfo:t,lookupTableAddress:n}){return e===0?await this.buildV0(U(F({},t||{}),{lookupTableAddress:n})):this.build(t)}build(e){var n;let t=new Zt;return this.allInstructions.length&&t.add(...this.allInstructions),t.feePayer=this.feePayer,((n=this.owner)==null?void 0:n.signer)&&!this.signers.some(i=>i.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 i=>{var d;let{recentBlockHash:r,skipPreflight:s=!0,sendAndConfirm:l,notSendToRpc:c}=i||{},u=r!=null?r:await At(this.connection,this.blockhashCommitment);if(t.recentBlockhash=u,this.signers.length&&t.sign(...this.signers),lt([t]),(d=this.owner)!=null&&d.isKeyPair)return{txId:l?await Ro(this.connection,t,this.signers.find(g=>g.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:s}):await this.connection.sendRawTransaction(t.serialize(),{skipPreflight:s}),signedTx:t};if(this.signAllTransactions){let p=await this.signAllTransactions([t]);if(this.signers.length)for(let g of p)try{g.sign(...this.signers)}catch{}return{txId:c?"":await this.connection.sendRawTransaction(p[0].serialize(),{skipPreflight:s}),signedTx:p[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:e||{}}}buildMultiTx(e){var u;let{extraPreBuildData:t=[],extInfo:n}=e,{transaction:i}=this.build(n),r=t.filter(d=>d.transaction.instructions.length>0),s=[i,...r.map(d=>d.transaction)],l=[this.signers,...r.map(d=>d.signers)],c=[...this.instructionTypes,...r.map(d=>d.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&l.forEach(d=>{d.some(p=>p.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:s,signers:l,instructionTypes:c,execute:async d=>{var h;let{sequentially:p,onTxUpdate:g,skipTxCount:b=0,recentBlockHash:f,skipPreflight:y=!0}=d||{},P=f!=null?f:await At(this.connection,this.blockhashCommitment);if((h=this.owner)!=null&&h.isKeyPair){if(p){let B=[],K=0;for(let C of s){if(++K,K<=b)continue;let I=await Ro(this.connection,C,this.signers.find(S=>S.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:y});B.push(I)}return{txIds:B,signedTxs:s}}return{txIds:await await Promise.all(s.map(async B=>(B.recentBlockhash=P,await this.connection.sendRawTransaction(B.serialize(),{skipPreflight:y})))),signedTxs:s}}if(this.signAllTransactions){let B=s.map((C,I)=>(C.recentBlockhash=P,l[I].length&&C.sign(...l[I]),C));lt(B);let K=await this.signAllTransactions(B);if(p){let C=0,I=[],S=async()=>{if(!K[C])return;let L=await this.connection.sendRawTransaction(K[C].serialize(),{skipPreflight:y});I.push({txId:L,status:"sent",signedTx:K[C]}),g==null||g([...I]),C++;let x=!1,O=null,M=null,E=q=>{O!==null&&clearInterval(O),M!==null&&this.connection.removeSignatureListener(M);let _=I.findIndex(N=>N.txId===L);if(_>-1){if(I[_].status==="error"||I[_].status==="success")return;I[_].status=q.err?"error":"success"}g==null||g([...I]),q.err||S()};this.loopMultiTxStatus&&(O=setInterval(async()=>{var q;if(x){clearInterval(O);return}try{let _=await this.connection.getTransaction(L,{commitment:"confirmed",maxSupportedTransactionVersion:1});_&&(x=!0,clearInterval(O),E({err:((q=_.meta)==null?void 0:q.err)||null}),console.log("tx status from getTransaction:",L))}catch(_){x=!0,clearInterval(O),console.error("getTransaction timeout:",_,L)}},On)),M=this.connection.onSignature(L,q=>{if(x){this.connection.removeSignatureListener(M);return}x=!0,E(q)},"confirmed"),this.connection.getSignatureStatus(L)};return await S(),{txIds:I.map(L=>L.txId),signedTxs:K}}else{let C=[];for(let I=0;I<K.length;I+=1){let S=await this.connection.sendRawTransaction(K[I].serialize(),{skipPreflight:y});C.push(S)}return{txIds:C,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:i,recentBlockhash:r}=f,s=ve(f,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),l=F(F({},this.cluster==="devnet"?await Co(this.connection):await xo(this.connection)),t),c=Array.from(new Set([...n,...this.lookupTableAddress])),u=[];for(let P of c)l[P]===void 0&&u.push(new Ot(P));let d=await Ko({connection:this.connection,address:u});for(let[P,h]of Object.entries(d))l[P]=h;let p=i?Ot.default.toBase58():r!=null?r:await At(this.connection,this.blockhashCommitment),g=new $t({payerKey:this.feePayer,recentBlockhash:p,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(l));((y=this.owner)==null?void 0:y.signer)&&!this.signers.some(P=>P.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let b=new jt(g);return b.sign(this.signers),{builder:this,transaction:b,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async P=>{var C;let{skipPreflight:h=!0,sendAndConfirm:B,notSendToRpc:K}=P||{};if(lt([b]),(C=this.owner)!=null&&C.isKeyPair){let I=await this.connection.sendTransaction(b,{skipPreflight:h});return B&&await yn(this.connection,I),{txId:I,signedTx:b}}if(this.signAllTransactions){let I=await this.signAllTransactions([b]);if(this.signers.length)for(let S of I)try{S.sign(this.signers)}catch{}return{txId:K?"":await this.connection.sendTransaction(I[0],{skipPreflight:h}),signedTx:I[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:s||{}}}async buildV0MultiTx(e){var u;let{extraPreBuildData:t=[],buildProps:n}=e,{transaction:i}=await this.buildV0(n),r=t.filter(d=>d.builder.instructions.length>0),s=[i,...r.map(d=>d.transaction)],l=[this.signers,...r.map(d=>d.signers)],c=[...this.instructionTypes,...r.map(d=>d.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&l.forEach(d=>{d.some(p=>p.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),s.forEach(async(d,p)=>{d.sign(l[p])}),{builder:this,transactions:s,signers:l,instructionTypes:c,buildProps:n,execute:async d=>{var y;let{sequentially:p,onTxUpdate:g,recentBlockHash:b,skipPreflight:f=!0}=d||{};if(b&&s.forEach(P=>P.message.recentBlockhash=b),lt(s),(y=this.owner)!=null&&y.isKeyPair){if(p){let P=[];for(let h of s){let B=await this.connection.sendTransaction(h,{skipPreflight:f});await yn(this.connection,B),P.push(B)}return{txIds:P,signedTxs:s}}return{txIds:await Promise.all(s.map(async P=>await this.connection.sendTransaction(P,{skipPreflight:f}))),signedTxs:s}}if(this.signAllTransactions){let P=await this.signAllTransactions(s);if(p){let h=0,B=[],K=async()=>{if(!P[h])return;let C=await this.connection.sendTransaction(P[h],{skipPreflight:f});B.push({txId:C,status:"sent",signedTx:P[h]}),g==null||g([...B]),h++;let I=!1,S=null,L=null,x=O=>{S!==null&&clearInterval(S),L!==null&&this.connection.removeSignatureListener(L);let M=B.findIndex(E=>E.txId===C);if(M>-1){if(B[M].status==="error"||B[M].status==="success")return;B[M].status=O.err?"error":"success"}g==null||g([...B]),O.err||K()};this.loopMultiTxStatus&&(S=setInterval(async()=>{var O;if(I){clearInterval(S);return}try{let M=await this.connection.getTransaction(C,{commitment:"confirmed",maxSupportedTransactionVersion:1});M&&(I=!0,clearInterval(S),x({err:((O=M.meta)==null?void 0:O.err)||null}),console.log("tx status from getTransaction:",C))}catch(M){I=!0,clearInterval(S),console.error("getTransaction timeout:",M,C)}},On)),L=this.connection.onSignature(C,O=>{if(I){this.connection.removeSignatureListener(L);return}I=!0,x(O)},"confirmed"),this.connection.getSignatureStatus(C)};return K(),{txIds:[],signedTxs:P}}else{let h=[];for(let B=0;B<P.length;B+=1){let K=await this.connection.sendTransaction(P[B],{skipPreflight:f});h.push(K)}return{txIds:h,signedTxs:P}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:n||{}}}async sizeCheckBuild(e){var g;let p=e||{},{splitIns:t=[],computeBudgetConfig:n}=p,i=ve(p,["splitIns","computeBudgetConfig"]),r=n?fn(n):{instructions:[],instructionTypes:[]},s=this.signers.reduce((b,f)=>U(F({},b),{[f.publicKey.toBase58()]:f}),{}),l=[],c=[],u=[],d=0;if(this.allInstructions.forEach(b=>{let f=[...u,b],y=n?[...r.instructions,...f]:f,h=[...new Set(f.map(B=>B.keys.filter(K=>K.isSigner).map(K=>K.pubkey.toString())).flat()).values()].map(B=>new Ot(B));if(b!==t[d]&&u.length<12&&(Vt({instructions:y,payer:this.feePayer,signers:h})||Vt({instructions:f,payer:this.feePayer,signers:h})))u.push(b);else{if(u.length===0)throw Error("item ins too big");d+=b===t[d]?1:0,Vt({instructions:n?[...r.instructions,...u]:[...u],payer:this.feePayer,signers:h})?l.push(new Zt().add(...r.instructions,...u)):l.push(new Zt().add(...u)),c.push(Array.from(new Set(u.map(B=>B.keys.filter(K=>K.isSigner).map(K=>K.pubkey.toString())).flat())).map(B=>s[B]).filter(B=>B!==void 0)),u=[b]}}),u.length>0){let f=[...new Set(u.map(y=>y.keys.filter(P=>P.isSigner).map(P=>P.pubkey.toString())).flat()).values()].map(y=>s[y]).filter(y=>y!==void 0);Vt({instructions:n?[...r.instructions,...u]:[...u],payer:this.feePayer,signers:f.map(y=>y.publicKey)})?l.push(new Zt().add(...r.instructions,...u)):l.push(new Zt().add(...u)),c.push(f)}return l.forEach(b=>b.feePayer=this.feePayer),(g=this.owner)!=null&&g.signer&&c.forEach(b=>{b.some(f=>f.publicKey.equals(this.owner.publicKey))||b.push(this.owner.signer)}),{builder:this,transactions:l,signers:c,instructionTypes:this.instructionTypes,execute:async b=>{var C;let{sequentially:f,onTxUpdate:y,skipTxCount:P=0,recentBlockHash:h,skipPreflight:B=!0}=b||{},K=h!=null?h:await At(this.connection,this.blockhashCommitment);if(l.forEach(async(I,S)=>{I.recentBlockhash=K,c[S].length&&I.sign(...c[S])}),lt(l),(C=this.owner)!=null&&C.isKeyPair){if(f){let I=0,S=[];for(let L of l){if(++I,I<=P){S.push("tx skipped");continue}let x=await Ro(this.connection,L,this.signers.find(O=>O.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:B});S.push(x)}return{txIds:S,signedTxs:l}}return{txIds:await Promise.all(l.map(async I=>await this.connection.sendRawTransaction(I.serialize(),{skipPreflight:B}))),signedTxs:l}}if(this.signAllTransactions){let I=await this.signAllTransactions(l.slice(P,l.length)),S=[...l.slice(0,P),...I];if(f){let L=0,x=[],O=async()=>{if(!S[L])return;L<P&&(x.push({txId:"",status:"success",signedTx:S[L]}),y==null||y([...x]),L++,O());let M=await this.connection.sendRawTransaction(S[L].serialize(),{skipPreflight:B});x.push({txId:M,status:"sent",signedTx:S[L]}),y==null||y([...x]),L++;let E=!1,q=null,_=null,N=W=>{q!==null&&clearInterval(q),_!==null&&this.connection.removeSignatureListener(_);let $=x.findIndex(J=>J.txId===M);if($>-1){if(x[$].status==="error"||x[$].status==="success")return;x[$].status=W.err?"error":"success"}y==null||y([...x]),W.err||O()};this.loopMultiTxStatus&&(q=setInterval(async()=>{var W;if(E){clearInterval(q);return}try{let $=await this.connection.getTransaction(M,{commitment:"confirmed",maxSupportedTransactionVersion:1});$&&(E=!0,clearInterval(q),N({err:((W=$.meta)==null?void 0:W.err)||null}),console.log("tx status from getTransaction:",M))}catch($){E=!0,clearInterval(q),console.error("getTransaction timeout:",$,M)}},On)),_=this.connection.onSignature(M,W=>{if(E){this.connection.removeSignatureListener(_);return}E=!0,N(W)},"confirmed"),this.connection.getSignatureStatus(M)};return await O(),{txIds:x.map(M=>M.txId),signedTxs:S}}else{let L=[];for(let x=0;x<S.length;x+=1){let O=await this.connection.sendRawTransaction(S[x].serialize(),{skipPreflight:B});L.push(O)}return{txIds:L,signedTxs:S}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:i||{}}}async sizeCheckBuildV0(e){var C;let K=e||{},{computeBudgetConfig:t,splitIns:n=[],lookupTableCache:i={},lookupTableAddress:r=[],insCountLimit:s=12}=K,l=ve(K,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress","insCountLimit"]),c=F(F({},this.cluster==="devnet"?await Co(this.connection):await xo(this.connection)),i),u=Array.from(new Set([...this.lookupTableAddress,...r])),d=[];for(let I of u)c[I]===void 0&&d.push(new Ot(I));let p=await Ko({connection:this.connection,address:d});for(let[I,S]of Object.entries(p))c[I]=S;let g=t?fn(t):{instructions:[],instructionTypes:[]},b=await At(this.connection,this.blockhashCommitment),f=this.signers.reduce((I,S)=>U(F({},I),{[S.publicKey.toBase58()]:S}),{}),y=[],P=[],h=[],B=0;if(this.allInstructions.forEach(I=>{let S=[...h,I],L=t?[...g.instructions,...S]:S;if(I!==n[B]&&h.length<s&&(Et({instructions:L,payer:this.feePayer,lookupTableAddressAccount:c})||Et({instructions:S,payer:this.feePayer,lookupTableAddressAccount:c})))h.push(I);else{if(h.length===0)throw Error("item ins too big");B+=I===n[B]?1:0;let x={};for(let O of[...new Set(u)])c[O]!==void 0&&(x[O]=c[O]);if(t&&Et({instructions:[...g.instructions,...h],payer:this.feePayer,lookupTableAddressAccount:c,recentBlockhash:b})){let O=new $t({payerKey:this.feePayer,recentBlockhash:b,instructions:[...g.instructions,...h]}).compileToV0Message(Object.values(c));y.push(new jt(O))}else{let O=new $t({payerKey:this.feePayer,recentBlockhash:b,instructions:[...h]}).compileToV0Message(Object.values(c));y.push(new jt(O))}P.push(Array.from(new Set(h.map(O=>O.keys.filter(M=>M.isSigner).map(M=>M.pubkey.toString())).flat())).map(O=>f[O]).filter(O=>O!==void 0)),h=[I]}}),h.length>0){let S=[...new Set(h.map(L=>L.keys.filter(x=>x.isSigner).map(x=>x.pubkey.toString())).flat()).values()].map(L=>f[L]).filter(L=>L!==void 0);if(t&&Et({instructions:[...g.instructions,...h],payer:this.feePayer,lookupTableAddressAccount:c,recentBlockhash:b})){let L=new $t({payerKey:this.feePayer,recentBlockhash:b,instructions:[...g.instructions,...h]}).compileToV0Message(Object.values(c));y.push(new jt(L))}else{let L=new $t({payerKey:this.feePayer,recentBlockhash:b,instructions:[...h]}).compileToV0Message(Object.values(c));y.push(new jt(L))}P.push(S)}return(C=this.owner)!=null&&C.signer&&P.forEach(I=>{I.some(S=>S.publicKey.equals(this.owner.publicKey))||I.push(this.owner.signer)}),y.forEach((I,S)=>{I.sign(P[S])}),{builder:this,transactions:y,buildProps:e,signers:P,instructionTypes:this.instructionTypes,execute:async I=>{var E;let{sequentially:S,onTxUpdate:L,skipTxCount:x=0,recentBlockHash:O,skipPreflight:M=!0}=I||{};if(y.map(async(q,_)=>{P[_].length&&q.sign(P[_]),O&&(q.message.recentBlockhash=O)}),lt(y),(E=this.owner)!=null&&E.isKeyPair){if(S){let q=0,_=[];for(let N of y){if(++q,q<=x){console.log("skip tx: ",q),_.push("tx skipped");continue}let W=await this.connection.sendTransaction(N,{skipPreflight:M});await yn(this.connection,W),_.push(W)}return{txIds:_,signedTxs:y}}return{txIds:await Promise.all(y.map(async q=>await this.connection.sendTransaction(q,{skipPreflight:M}))),signedTxs:y}}if(this.signAllTransactions){let q=await this.signAllTransactions(y.slice(x,y.length)),_=[...y.slice(0,x),...q];if(S){let N=0,W=[],$=async()=>{if(!_[N])return;if(N<x){W.push({txId:"",status:"success",signedTx:_[N]}),L==null||L([...W]),N++,$();return}let J=await this.connection.sendTransaction(_[N],{skipPreflight:M});W.push({txId:J,status:"sent",signedTx:_[N]}),L==null||L([...W]),N++;let Y=!1,ee=null,v=null,te=ce=>{ee!==null&&clearInterval(ee),v!==null&&this.connection.removeSignatureListener(v);let j=W.findIndex(fe=>fe.txId===J);if(j>-1){if(W[j].status==="error"||W[j].status==="success")return;W[j].status=ce.err?"error":"success"}L==null||L([...W]),ce.err||$()};this.loopMultiTxStatus&&(ee=setInterval(async()=>{var ce;if(Y){clearInterval(ee);return}try{let j=await this.connection.getTransaction(J,{commitment:"confirmed",maxSupportedTransactionVersion:1});j&&(Y=!0,clearInterval(ee),te({err:((ce=j.meta)==null?void 0:ce.err)||null}),console.log("tx status from getTransaction:",J))}catch(j){Y=!0,clearInterval(ee),console.error("getTransaction timeout:",j,J)}},On)),v=this.connection.onSignature(J,ce=>{if(Y){this.connection.removeSignatureListener(v);return}Y=!0,te(ce)},"confirmed"),this.connection.getSignatureStatus(J)};return $(),{txIds:[],signedTxs:_}}else{let N=[];for(let W=0;W<_.length;W+=1){let $=await this.connection.sendTransaction(_[W],{skipPreflight:M});N.push($)}return{txIds:N,signedTxs:_}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:l||{}}}};var Lo=(...a)=>a.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch{return e}}).join(", "),Se=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=H(t)}createTxBuilder(e){return this.scope.checkOwner(),new Nn({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(Lo(e))}logInfo(...e){this.logger.info(Lo(e))}logAndCreateError(...e){let t=Lo(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};import{NATIVE_MINT as ze,TOKEN_2022_PROGRAM_ID as Xe,TOKEN_PROGRAM_ID as Pe,createAssociatedTokenAccountIdempotentInstruction as Le,createSyncNativeInstruction as Pu,getTransferFeeConfig as Jt,unpackMint as en}from"@solana/spl-token";import V from"bn.js";import{PublicKey as tn,SystemProgram as Au}from"@solana/web3.js";import Ne from"decimal.js";var Mn={initPriceX64:new V("515752397214619"),supply:new V(1e15),totalSellA:new V(7931e11),totalFundRaisingB:new V(85e9),totalFundRaisingBUSD:new V(125e8),totalLockedAmount:new V("0"),cliffPeriod:new V("0"),unlockPeriod:new V("0"),decimals:6,virtualA:new V("1073471847374405"),virtualB:new V("30050573465"),realA:new V(0),realB:new V(0),protocolFee:new V(0),platformId:new tn("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),vestingSchedule:{totalLockedAmount:new V(0),cliffPeriod:new V(0),unlockPeriod:new V(0),startTime:new V(0),totalAllocatedShare:new V(0)}},rt=new V(1e4),WL=new Set(["USDCoctVLVnvTXBEuP9s8hntucdJokbo17RwHuNXemT","USD1ttGY1N17NEEHLmELoaybftRBUSErhqYiQzvEmuB"]),Ln=class extends Se{constructor(e){super(e)}async getMintBTokenInfo({mintB:e,mintBProgram:t,transferFeeConfigB:n,skipCheckMintB:i}){if(e.equals(ze))return{mintBProgram:Pe,transferFeeConfigB:void 0};if(n)return{mintBProgram:t!=null?t:Xe,transferFeeConfigB:n};if(i||(t==null?void 0:t.equals(Pe)))return{mintBProgram:t!=null?t:Pe,transferFeeConfigB:void 0};let r=await this.scope.connection.getAccountInfo(e);return!r||!r.owner.equals(Xe)?{mintBProgram:t!=null?t:Pe,transferFeeConfigB:void 0}:{mintBProgram:r.owner,transferFeeConfigB:Jt(en(e,r,r.owner))||void 0}}async createLaunchpad(W){var $=W,{programId:e=ae,authProgramId:t,platformId:n=Mn.platformId,mintA:i,decimals:r=6,mintBDecimals:s=9,name:l,symbol:c,uri:u,migrateType:d,configId:p,configInfo:g,txVersion:b,computeBudgetConfig:f,txTipConfig:y,feePayer:P,buyAmount:h,minMintAAmount:B,slippage:K,associatedOnly:C=!0,checkCreateATAOwner:I=!1,extraSigners:S,token2022:L,transferFeeExtensionParams:x,creatorFeeOn:O=0,platformAllowConfig:M,mintBProgram:E,transferFeeConfigB:q,skipCheckMintB:_}=$,N=ve($,["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 Fo,vo,_o,Vo,Eo,Do,Wo,qo,Uo,Go,zo;let J=this.createTxBuilder(P);t=t!=null?t:Ee(e).publicKey,L=!!x,L&&(d="cpmm");let Y=g;if(!Y&&p){let Ze=await this.scope.connection.getAccountInfo(p);Ze&&(Y=nt.decode(Ze.data))}Y||this.logAndCreateError("config not found");let ee=Y.mintB,v=Y.curveType,{mintBProgram:te,transferFeeConfigB:ce}=await this.getMintBTokenInfo({mintB:ee,mintBProgram:E,transferFeeConfigB:q,skipCheckMintB:_}),{publicKey:j}=St(e,i,ee),{publicKey:fe}=co(e,j,i),{publicKey:ne}=co(e,j,ee),{publicKey:Fe}=Pn(i);this.logDebug(`create token: ${i.toBase58()}, mintB: ${ee.toBase58()}, decimals A:${r}/B:${s}, config:${p.toBase58()}`),c.length>10&&this.logAndCreateError("Symbol length should shorter than 11"),u||this.logAndCreateError("uri should not empty");let Ae=(await this.scope.api.fetchLaunchConfigs()).find(Ze=>Ze.key.pubKey===p.toBase58()),Z=(Fo=N==null?void 0:N.supply)!=null?Fo:new V(Ae.defaultParams.supplyInit),z=(vo=N==null?void 0:N.totalSellA)!=null?vo:new V(Ae.defaultParams.totalSellA),Ie=(_o=N==null?void 0:N.totalFundRaisingB)!=null?_o:new V(Ae.defaultParams.totalFundRaisingB),Ye=(Vo=N==null?void 0:N.totalLockedAmount)!=null?Vo:new V(0),le=await this.scope.connection.getAccountInfo(n);le||this.logAndCreateError("platform id not found:",n.toString());let He=ft.decode(le.data),Fn=He.platformVestingScale,Oo=He.feeRate,No=Oe.getCurve(Y.curveType).getInitParam({supply:Z,totalFundRaising:Ie,totalSell:z,totalLockedAmount:Ye,migrateFee:Y.migrateFee}),nn;try{nn=await this.scope.token.getTokenInfo(ee)}catch{this.logDebug("can not get mintB info from getTokenInfo")}let Qe={epoch:new V(896),bump:254,status:0,mintDecimalsA:r,mintDecimalsB:(Eo=nn==null?void 0:nn.decimals)!=null?Eo:s,supply:Z,totalSellA:z,mintA:new tn(i),mintB:ee,virtualA:No.a,virtualB:No.b,realA:Mn.realA,realB:Mn.realB,migrateFee:Y.migrateFee,migrateType:d==="amm"?0:1,protocolFee:Mn.protocolFee,platformFee:Oo,platformId:n,configId:p,vaultA:fe,vaultB:ne,creator:this.scope.ownerPubKey,totalFundRaisingB:Ie,vestingSchedule:{totalLockedAmount:Ye,cliffPeriod:new V(0),unlockPeriod:new V(0),startTime:new V(0),totalAllocatedShare:new V(0)},mintProgramFlag:rr({mintAProgram:L?Xe:Pe,mintBProgram:te}),cpmmCreatorFeeOn:O,platformVestingShare:Fn!=null?Fn:new V(0)},cr=Oe.getCurve(Y.curveType),{c:lr}=cr.getInitParam({supply:Qe.supply,totalFundRaising:Qe.totalFundRaisingB,totalLockedAmount:Ye,totalSell:Y.curveType===0?Qe.totalSellA:new V(0),migrateFee:Y.migrateFee});try{Oe.checkParam({supply:Qe.supply,totalFundRaising:Qe.totalFundRaisingB,totalSell:lr,totalLockedAmount:Ye,decimals:Qe.mintDecimalsA,config:Y,migrateType:d}),this.logDebug("check init params success")}catch(Ze){this.logAndCreateError(`check create mint params failed, ${Ze.message}`)}let Mo=He.restrictCurveParam?fo(e,n,p).publicKey:void 0;J.addInstruction({instructions:[L?Xi(e,P!=null?P:this.scope.ownerPubKey,this.scope.ownerPubKey,p,n,t,j,i,ee,fe,ne,te,r,l,c,u||"https://",{type:v===0?"ConstantCurve":v===1?"FixedCurve":v===2?"LinearCurve":"ConstantCurve",totalSellA:z,migrateType:d,supply:Z,totalFundRaisingB:Ie},Ye,(Do=N==null?void 0:N.cliffPeriod)!=null?Do:new V(0),(Wo=N==null?void 0:N.unlockPeriod)!=null?Wo:new V(0),O,x,M?Xt(e,n,p).publicKey:void 0,Mo):zi(e,P!=null?P:this.scope.ownerPubKey,this.scope.ownerPubKey,p,n,t,j,i,ee,fe,ne,Fe,te,r,l,c,u||"https://",{type:v===0?"ConstantCurve":v===1?"FixedCurve":v===2?"LinearCurve":"ConstantCurve",totalSellA:z,migrateType:d,supply:Z,totalFundRaisingB:Ie},Ye,(qo=N==null?void 0:N.cliffPeriod)!=null?qo:new V(0),(Uo=N==null?void 0:N.unlockPeriod)!=null?Uo:new V(0),O,M?Xt(e,n,p).publicKey:void 0,Mo)]});let vn=L?await this.scope.connection.getEpochInfo():void 0,on=x?{epoch:BigInt((vn==null?void 0:vn.epoch)||0),maximumFee:BigInt((Go=x==null?void 0:x.maxinumFee.toString())!=null?Go:0),transferFeeBasisPoints:(zo=x==null?void 0:x.transferFeeBasePoints)!=null?zo:0}:void 0,_n={amountA:{amount:new V(0),fee:void 0,expirationTime:void 0},amountB:new V(0),splitFee:{platformFee:new V(0),shareFee:new V(0),protocolFee:new V(0),creatorFee:new V(0)},transferFeeB:void 0},Vn;if(S!=null&&S.length&&J.addInstruction({signers:S}),!N.createOnly){let{builder:Ze,extInfo:mr}=await this.buyToken({programId:e,authProgramId:t,mintAProgram:L?Xe:void 0,mintA:i,mintB:ee,mintBProgram:te,transferFeeConfigB:ce,skipCheckMintB:!0,poolInfo:Qe,buyAmount:h,minMintAAmount:B,shareFeeRate:N.shareFeeRate,shareFeeReceiver:N.shareFeeReceiver,configInfo:Y,platformFeeRate:Oo,slippage:K,associatedOnly:C,checkCreateATAOwner:I,skipCheckMintA:!on,transferFeeConfigA:on?{transferFeeConfigAuthority:t,withdrawWithheldAuthority:t,withheldAmount:BigInt(0),olderTransferFee:on,newerTransferFee:on}:void 0,fromCreate:!0});J.addInstruction(F({},Ze.AllTxData)),_n=F({},mr),Vn=(this.scope.cluster==="devnet"||b===1)&&N.shareFeeReceiver?[Ze.allInstructions[0]]:void 0}return J.addTipInstruction(y),b===0?J.sizeCheckBuildV0({computeBudgetConfig:f,swapInfo:_n,splitIns:Vn,address:U(F({},Qe),{poolId:j})}):J.sizeCheckBuild({computeBudgetConfig:f,swapInfo:_n,splitIns:Vn,address:U(F({},Qe),{poolId:j})})}async buyToken({programId:e=ae,authProgramId:t,mintA:n,mintAProgram:i=Pe,mintB:r=ze,poolInfo:s,configInfo:l,platformFeeRate:c,txVersion:u,computeBudgetConfig:d,txTipConfig:p,feePayer:g,buyAmount:b,minMintAAmount:f,slippage:y,shareFeeRate:P=new V(0),shareFeeReceiver:h,associatedOnly:B=!0,checkCreateATAOwner:K=!1,fromCreate:C=!1,transferFeeConfigA:I,skipCheckMintA:S=!1,mintBProgram:L,transferFeeConfigB:x,skipCheckMintB:O=!1}){var z,Ie,Ye;b.lte(new V(0))&&this.logAndCreateError("buy amount should gt 0:",b.toString());let M=this.createTxBuilder(g),{publicKey:E}=St(e,n,r);t=t!=null?t:Ee(e).publicKey;let q=I;if(!S)if(q)i=Xe;else{let le=await this.scope.connection.getAccountInfo(n);if(le&&le.owner.equals(Xe)){i=le.owner;let He=en(n,le,i);q=Jt(He)||void 0}}let{mintBProgram:_,transferFeeConfigB:N}=await this.getMintBTokenInfo({mintB:r,mintBProgram:L,transferFeeConfigB:x,skipCheckMintB:O}),W=this.scope.account.getAssociatedTokenAccount(n,i),$=r.equals(ze),J=C&&$,Y=J?this.scope.account.getAssociatedTokenAccount(r,_):null,ee=$;if(M.addInstruction({instructions:[Le(this.scope.ownerPubKey,W,this.scope.ownerPubKey,n,i),...J?[Le(this.scope.ownerPubKey,Y,this.scope.ownerPubKey,r,_),Au.transfer({fromPubkey:this.scope.ownerPubKey,toPubkey:Y,lamports:BigInt(b.toString())}),Pu(Y)]:[]]}),!J){let{account:le,instructionParams:He}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:_,mint:r,owner:this.scope.ownerPubKey,createInfo:ee?{payer:this.scope.ownerPubKey,amount:b}:void 0,skipCloseAccount:!ee,notUseTokenAccount:ee,associatedOnly:ee?!1:B,checkCreateATAOwner:K});le&&(Y=le),M.addInstruction(He||{})}Y||this.logAndCreateError(`cannot found mintB(${r.toBase58()}) buy token accounts`,"tokenAccounts",this.scope.account.tokenAccounts);let v=s;if(!v){let le=await this.scope.connection.getAccountInfo(E,{commitment:"processed"});le||this.logAndCreateError("cannot found pool:",E.toBase58()),v=De.decode(le.data)}let te=l,ce=await xe(this.scope.connection,[te?void 0:v.configId,v.platformId].filter(Boolean).map(le=>({pubkey:le})));if(!te){let le=ce.find(He=>He.pubkey.equals(v.configId));(!le||!le.accountInfo)&&this.logAndCreateError("config not found: ",v.configId.toBase58()),te=nt.decode(le.accountInfo.data)}let j=ce.find(le=>le.pubkey.equals(v.platformId));(!j||!j.accountInfo)&&this.logAndCreateError("platform info not found: ",v.configId.toBase58());let fe=ft.decode(j.accountInfo.data);c=c||fe.feeRate;let ne=Oe.buyExactIn({poolInfo:v,amountB:b,protocolFeeRate:te.tradeFeeRate,platformFeeRate:c,curveType:te.curveType,shareFeeRate:P,creatorFeeRate:fe.creatorFeeRate,transferFeeConfigA:q,transferFeeConfigB:N,slot:await this.scope.connection.getSlot()}),Fe=new Ne(ne.amountA.amount.toString()).sub((Ie=(z=ne.amountA.fee)==null?void 0:z.toString())!=null?Ie:0),je=y?new Ne(rt.sub(y).toNumber()/rt.toNumber()).clampedTo(0,1):new Ne(1),Ae=f!=null?f:y?new V(Fe.mul(je).toFixed(0)):ne.amountA.amount.sub((Ye=ne.amountA.fee)!=null?Ye:new V(0));ne.amountB.lt(b)&&console.log(`maximum ${n.toBase58()} amount can buy is ${ne.amountA.toString()}, input ${r.toBase58()} amount: ${ne.amountB.toString()}`);let Z=h?pe(h,r,_).publicKey:void 0;return Z&&M.addInstruction({instructions:[Le(this.scope.ownerPubKey,Z,h,r,_)]}),M.addInstruction({instructions:[yo(e,this.scope.ownerPubKey,t,v.configId,v.platformId,E,W,Y,v.vaultA,v.vaultB,n,r,i,_,et(e,v.platformId,r).publicKey,tt(e,v.creator,r).publicKey,ne.amountB.lt(b)?ne.amountB:b,Ae,P,Z)]}),M.addCustomComputeBudget(d),M.addTipInstruction(p),M.versionBuild({txVersion:u,extInfo:U(F({},ne),{decimalOutAmount:Fe,minDecimalOutAmount:new Ne(Ae.toString())})})}async buyTokenExactOut({programId:e=ae,authProgramId:t,mintA:n,mintAProgram:i=Pe,mintB:r=ze,poolInfo:s,configInfo:l,transferFeeConfigA:c,platformFeeRate:u,txVersion:d,computeBudgetConfig:p,txTipConfig:g,feePayer:b,maxBuyAmount:f,outAmount:y,slippage:P,shareFeeRate:h=new V(0),shareFeeReceiver:B,associatedOnly:K=!0,checkCreateATAOwner:C=!1,skipCheckMintA:I=!1,mintBProgram:S,transferFeeConfigB:L,skipCheckMintB:x=!1}){y.lte(new V(0))&&this.logAndCreateError("out amount should gt 0:",y.toString());let O=this.createTxBuilder(b),{publicKey:M}=St(e,n,r);t=t!=null?t:Ee(e).publicKey;let E=s;if(!E){let Z=await this.scope.connection.getAccountInfo(M,{commitment:"processed"});Z||this.logAndCreateError("cannot found pool:",M.toBase58()),E=De.decode(Z.data)}let q=l,_=await xe(this.scope.connection,[q?void 0:E.configId,E.platformId].filter(Boolean).map(Z=>({pubkey:Z})));if(!q){let Z=_.find(z=>z.pubkey.equals(E.configId));(!Z||!Z.accountInfo)&&this.logAndCreateError("config not found: ",E.configId.toBase58()),q=nt.decode(Z.accountInfo.data)}let N=_.find(Z=>Z.pubkey.equals(E.platformId));(!N||!N.accountInfo)&&this.logAndCreateError("platform info not found: ",E.configId.toBase58());let W=ft.decode(N.accountInfo.data);u=u||W.feeRate;let $=c;if(!I)if($)i=Xe;else{let Z=await this.scope.connection.getAccountInfo(n);if(Z&&Z.owner.equals(Xe)){i=Z.owner;let z=en(n,Z,i);$=Jt(z)||void 0}}let{mintBProgram:J,transferFeeConfigB:Y}=await this.getMintBTokenInfo({mintB:r,mintBProgram:S,transferFeeConfigB:L,skipCheckMintB:x}),ee=Oe.buyExactOut({poolInfo:E,amountA:y,protocolFeeRate:q.tradeFeeRate,platformFeeRate:u,curveType:q.curveType,shareFeeRate:h,creatorFeeRate:W.creatorFeeRate,transferFeeConfigA:$,transferFeeConfigB:Y,slot:await this.scope.connection.getSlot()}),v=new Ne(ee.amountB.toString()),te=P?new Ne(rt.add(P).toNumber()/rt.toNumber()).clampedTo(0,Number.MIN_SAFE_INTEGER):new Ne(1),ce=(f!=null?f:P)?new V(v.mul(te).toFixed(0)):ee.amountB,j=this.scope.account.getAssociatedTokenAccount(n,i),fe=null,ne=r.equals(ze);O.addInstruction({instructions:[Le(this.scope.ownerPubKey,j,this.scope.ownerPubKey,n,i)]});let{account:Fe,instructionParams:je}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:J,mint:r,owner:this.scope.ownerPubKey,createInfo:ne?{payer:this.scope.ownerPubKey,amount:ee.amountB}:void 0,skipCloseAccount:!ne,notUseTokenAccount:ne,associatedOnly:ne?!1:K,checkCreateATAOwner:C});Fe&&(fe=Fe),O.addInstruction(je||{}),fe===void 0&&this.logAndCreateError(`cannot found mintB(${r.toBase58()}) token accounts`,"tokenAccounts",this.scope.account.tokenAccounts);let Ae=B?pe(B,r,J).publicKey:void 0;return Ae&&O.addInstruction({instructions:[Le(this.scope.ownerPubKey,Ae,B,r,J)]}),O.addInstruction({instructions:[Yi(e,this.scope.ownerPubKey,t,E.configId,E.platformId,M,j,fe,E.vaultA,E.vaultB,n,r,i,J,et(e,E.platformId,r).publicKey,tt(e,E.creator,r).publicKey,y,ce,h,Ae)]}),O.addCustomComputeBudget(p),O.addTipInstruction(g),O.versionBuild({txVersion:d,extInfo:{maxSpentAmount:ce,outAmount:y}})}async sellToken({programId:e=ae,authProgramId:t,mintAProgram:n=Pe,mintA:i,mintB:r=ze,poolInfo:s,configInfo:l,platformFeeRate:c,txVersion:u,computeBudgetConfig:d,txTipConfig:p,feePayer:g,sellAmount:b,minAmountB:f,slippage:y,shareFeeRate:P=new V(0),shareFeeReceiver:h,associatedOnly:B=!0,checkCreateATAOwner:K=!1,skipCheckMintA:C=!1,mintBProgram:I,transferFeeConfigB:S,skipCheckMintB:L=!1}){t=t!=null?t:Ee(e).publicKey;let x=this.createTxBuilder(g);b.lte(new V(0))&&this.logAndCreateError("sell amount should be gt 0");let{publicKey:O}=St(e,i,r),M;if(!C){let z=await this.scope.connection.getAccountInfo(i);if(z&&z.owner.equals(Xe)){n=z.owner;let Ie=en(i,z,n);M=Jt(Ie)||void 0}}let{mintBProgram:E,transferFeeConfigB:q}=await this.getMintBTokenInfo({mintB:r,mintBProgram:I,transferFeeConfigB:S,skipCheckMintB:L}),_=null,N=null,W=r.equals(ze),{account:$,instructionParams:J}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n,mint:i,owner:this.scope.ownerPubKey,createInfo:void 0,skipCloseAccount:!0,notUseTokenAccount:!1,associatedOnly:B,checkCreateATAOwner:K});$&&(_=$),x.addInstruction(J||{}),_===void 0&&this.logAndCreateError("cannot found mintA token accounts","tokenAccounts",this.scope.account.tokenAccounts);let{account:Y,instructionParams:ee}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:E,mint:r,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!W,notUseTokenAccount:W,associatedOnly:W?!1:B,checkCreateATAOwner:K});Y&&(N=Y),x.addInstruction(ee||{}),N||this.logAndCreateError("cannot found mintB token accounts","tokenAccounts",{userTokenAccountB:N});let v=s;if(!v){let z=await this.scope.connection.getAccountInfo(O,{commitment:"processed"});z||this.logAndCreateError("cannot found pool",O.toBase58()),v=De.decode(z.data)}let te=l,ce=await xe(this.scope.connection,[te?void 0:v.configId,v.platformId].filter(Boolean).map(z=>({pubkey:z})));if(!te){let z=ce.find(Ie=>Ie.pubkey.equals(v.configId));(!z||!z.accountInfo)&&this.logAndCreateError("config not found: ",v.configId.toBase58()),te=nt.decode(z.accountInfo.data)}let j=ce.find(z=>z.pubkey.equals(v.platformId));(!j||!j.accountInfo)&&this.logAndCreateError("platform info not found: ",v.configId.toBase58());let fe=ft.decode(j.accountInfo.data);c=c||fe.feeRate;let ne=Oe.sellExactIn({poolInfo:v,amountA:b,protocolFeeRate:te.tradeFeeRate,platformFeeRate:c,curveType:te.curveType,shareFeeRate:P,creatorFeeRate:fe.creatorFeeRate,transferFeeConfigA:M,transferFeeConfigB:q,slot:await this.scope.connection.getSlot()}),Fe=new Ne(ne.amountB.toString()),je=y?new Ne(rt.sub(y).toNumber()/rt.toNumber()).clampedTo(0,1):new Ne(1),Ae=f!=null?f:y?new V(Fe.mul(je).toFixed(0)):ne.amountB;Ae.lte(new V(0))&&this.logAndCreateError(`out ${r.toBase58()} amount should be gt 0`);let Z=h?pe(h,r,E).publicKey:void 0;return Z&&x.addInstruction({instructions:[Le(this.scope.ownerPubKey,Z,h,r,E)]}),x.addInstruction({instructions:[bo(e,this.scope.ownerPubKey,t,v.configId,v.platformId,O,_,N,v.vaultA,v.vaultB,i,r,n,E,et(e,v.platformId,r).publicKey,tt(e,v.creator,r).publicKey,ne.amountA.amount.lt(b)?ne.amountA.amount:b,Ae,P,Z)]}),x.addCustomComputeBudget(d),x.addTipInstruction(p),x.versionBuild({txVersion:u,extInfo:{outAmount:Ae}})}async sellTokenExactOut({programId:e=ae,authProgramId:t,mintAProgram:n=Pe,mintA:i,mintB:r=ze,poolInfo:s,configInfo:l,platformFeeRate:c,txVersion:u,computeBudgetConfig:d,txTipConfig:p,feePayer:g,inAmount:b,maxSellAmount:f,slippage:y,shareFeeRate:P=new V(0),shareFeeReceiver:h,associatedOnly:B=!0,checkCreateATAOwner:K=!1,skipCheckMintA:C=!1,mintBProgram:I,transferFeeConfigB:S,skipCheckMintB:L=!1}){t=t!=null?t:Ee(e).publicKey;let x=this.createTxBuilder(g);f!=null&&f.lte(new V(0))&&this.logAndCreateError("max sell amount should be gt 0");let{publicKey:O}=St(e,i,r),M;if(!C){let z=await this.scope.connection.getAccountInfo(i);if(z&&z.owner.equals(Xe)){n=z.owner;let Ie=en(i,z,n);M=Jt(Ie)||void 0}}let{mintBProgram:E,transferFeeConfigB:q}=await this.getMintBTokenInfo({mintB:r,mintBProgram:I,transferFeeConfigB:S,skipCheckMintB:L}),_=null,N=null,W=r.equals(ze),{account:$,instructionParams:J}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n,mint:i,owner:this.scope.ownerPubKey,createInfo:void 0,skipCloseAccount:!0,notUseTokenAccount:!1,associatedOnly:B,checkCreateATAOwner:K});$&&(_=$),x.addInstruction(J||{}),_===void 0&&this.logAndCreateError("cannot found mintA token accounts","tokenAccounts",this.scope.account.tokenAccounts);let{account:Y,instructionParams:ee}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:E,mint:r,owner:this.scope.ownerPubKey,createInfo:W?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!W,notUseTokenAccount:W,associatedOnly:W?!1:B,checkCreateATAOwner:K});Y&&(N=Y),x.addInstruction(ee||{}),N===void 0&&this.logAndCreateError("cannot found mintB token accounts","tokenAccounts",this.scope.account.tokenAccounts);let v=s;if(!v){let z=await this.scope.connection.getAccountInfo(O,{commitment:"processed"});z||this.logAndCreateError("cannot found pool",O.toBase58()),v=De.decode(z.data)}let te=l,ce=await xe(this.scope.connection,[te?void 0:v.configId,v.platformId].filter(Boolean).map(z=>({pubkey:z})));if(!te){let z=ce.find(Ie=>Ie.pubkey.equals(v.configId));(!z||!z.accountInfo)&&this.logAndCreateError("config not found: ",v.configId.toBase58()),te=nt.decode(z.accountInfo.data)}let j=ce.find(z=>z.pubkey.equals(v.platformId));(!j||!j.accountInfo)&&this.logAndCreateError("platform info not found: ",v.configId.toBase58());let fe=ft.decode(j.accountInfo.data);c=c||fe.feeRate;let ne=Oe.sellExactOut({poolInfo:v,amountB:b,protocolFeeRate:te.tradeFeeRate,platformFeeRate:c,curveType:te.curveType,shareFeeRate:P,creatorFeeRate:fe.creatorFeeRate,transferFeeConfigA:M,transferFeeConfigB:q,slot:await this.scope.connection.getSlot()}),Fe=new Ne(ne.amountA.amount.toString()),je=y?new Ne(rt.add(y).toNumber()/rt.toNumber()).clampedTo(0,Number.MAX_SAFE_INTEGER):new Ne(1),Ae=(f!=null?f:y)?new V(Fe.mul(je).toFixed(0)):ne.amountA.amount,Z=h?pe(h,r,E).publicKey:void 0;return Z&&x.addInstruction({instructions:[Le(this.scope.ownerPubKey,Z,h,r,E)]}),x.addInstruction({instructions:[Hi(e,this.scope.ownerPubKey,t,v.configId,v.platformId,O,_,N,v.vaultA,v.vaultB,i,r,n,E,et(e,v.platformId,r).publicKey,tt(e,v.creator,r).publicKey,b,Ae,P,Z)]}),x.addCustomComputeBudget(d),x.addTipInstruction(p),x.versionBuild({txVersion:u,extInfo:{maxSellAmount:Ae}})}async createPlatformConfig({programId:e=ae,platformAdmin:t,platformClaimFeeWallet:n,platformLockNftWallet:i,platformVestingWallet:r,cpConfigId:s,migrateCpLockNftScale:l,transferFeeExtensionAuth:c,creatorFeeRate:u,feeRate:d,name:p,web:g,img:b,platformVestingScale:f=new V(0),txVersion:y,computeBudgetConfig:P,txTipConfig:h,feePayer:B}){let K=this.createTxBuilder(B),{publicKey:C}=lo(e,t);return K.addInstruction({instructions:[Qi(e,t,n,i,r,C,s,c,l,d,u,p,g,b,f)]}),K.addCustomComputeBudget(P),K.addTipInstruction(h),K.versionBuild({txVersion:y,extInfo:{platformId:C}})}async updatePlatformConfig({programId:e=ae,platformAdmin:t,platformId:n,updateInfo:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),d=n!=null?n:lo(e,t).publicKey;return u.addInstruction({instructions:[Zi(e,t,d,i)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r})}async createPlatformVestingAccount({programId:e=ae,platformVestingWallet:t,beneficiary:n,platformId:i,poolId:r,vestingRecord:s,txVersion:l,computeBudgetConfig:c,txTipConfig:u,feePayer:d}){let p=this.createTxBuilder(d),g=s!=null?s:Kt(e,r,n).publicKey;return p.addInstruction({instructions:[$i(e,t,n,i,r,g)]}),p.addCustomComputeBudget(c),p.addTipInstruction(u),p.versionBuild({txVersion:l})}async claimPlatformFee({programId:e=ae,authProgramId:t,platformId:n,poolId:i,platformClaimFeeWallet:r,mintB:s,vaultB:l,mintBProgram:c,txVersion:u,computeBudgetConfig:d,txTipConfig:p,feePayer:g}){var B;let b=this.createTxBuilder(g);t=t!=null?t:Ee(e).publicKey;let f=s,y=l;if(!f){let K=await this.scope.connection.getAccountInfo(i,{commitment:"processed"});K||this.logAndCreateError("cannot found pool:",i.toBase58());let C=De.decode(K.data),I=await this.scope.connection.getAccountInfo(C.configId,{commitment:"processed"});I||this.logAndCreateError("cannot found config:",C.configId.toBase58()),f=nt.decode(I.data).mintB,y=y!=null?y:C.vaultB}(!f||!y)&&this.logAndCreateError("cannot found mint info, mintB: ",f.toBase58(),", vaultB: ",(B=y==null?void 0:y.toBase58())!=null?B:"");let{mintBProgram:P}=await this.getMintBTokenInfo({mintB:f,mintBProgram:c}),h=pe(this.scope.ownerPubKey,f,P).publicKey;return b.addInstruction({instructions:[Le(this.scope.ownerPubKey,h,this.scope.ownerPubKey,f,P)]}),b.addInstruction({instructions:[Ao(e,r,t,i,n,y,h,f,P)]}),b.addCustomComputeBudget(d),b.addTipInstruction(p),b.versionBuild({txVersion:u})}async claimAllPlatformFee({programId:e=ae,authProgramId:t,platformId:n,platformClaimFeeWallet:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c);t=t!=null?t:Ee(e).publicKey;let p=(await this.scope.connection.getProgramAccounts(e,{filters:[{dataSize:De.span},{memcmp:{offset:De.offsetOf("platformId"),bytes:n.toString()}}]})).map(f=>({poolId:f.pubkey,pool:De.decode(f.account.data)})).filter(({pool:f})=>f.platformFee.gt(new V(0))),g={},b=[...new Set(p.map(({pool:f})=>f.mintB.toBase58()))];return b.length&&(await xe(this.scope.connection,b.map(y=>({pubkey:new tn(y)})))).forEach(y=>{var P,h;g[y.pubkey.toBase58()]=(h=(P=y.accountInfo)==null?void 0:P.owner)!=null?h:Pe}),p.forEach(({poolId:f,pool:y})=>{var B;let P=(B=g[y.mintB.toBase58()])!=null?B:Pe,h=pe(this.scope.ownerPubKey,y.mintB,P).publicKey;u.addInstruction({instructions:[Le(this.scope.ownerPubKey,h,this.scope.ownerPubKey,y.mintB,P)]}),u.addInstruction({instructions:[Ao(e,i,t,f,n,y.vaultB,h,y.mintB,P)]})}),u.addTipInstruction(l),r===0?u.sizeCheckBuildV0({computeBudgetConfig:s}):u.sizeCheckBuild({computeBudgetConfig:s})}async createVesting({programId:e=ae,poolId:t,beneficiary:n,shareAmount:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),d=await this.getRpcPoolInfo({poolId:t});i.add(d.vestingSchedule.totalAllocatedShare).gt(d.vestingSchedule.totalLockedAmount)&&this.logAndCreateError("share amount exceed total locked amount");let p=Kt(e,t,n).publicKey;return u.addInstruction({instructions:[Po(e,this.scope.ownerPubKey,n,t,p,i)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r})}async createMultipleVesting({programId:e=ae,poolId:t,beneficiaryList:n,txVersion:i,computeBudgetConfig:r,feePayer:s}){let l=this.createTxBuilder(s);n.length===0&&this.logAndCreateError("beneficiaryList is null");let c=await this.getRpcPoolInfo({poolId:t});return n.reduce((d,p)=>d.add(p.shareAmount),c.vestingSchedule.totalAllocatedShare).gt(c.vestingSchedule.totalLockedAmount)&&this.logAndCreateError("share amount exceed total locked amount"),n.forEach(d=>{let p=Kt(e,t,d.wallet).publicKey;l.addInstruction({instructions:[Po(e,this.scope.ownerPubKey,d.wallet,t,p,d.shareAmount)]})}),i===0?l.sizeCheckBuildV0({computeBudgetConfig:r}):l.sizeCheckBuild({computeBudgetConfig:r})}async claimVesting({programId:e=ae,poolId:t,poolInfo:n,vestingRecord:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),d=Ee(e).publicKey,p=i||Kt(e,t,this.scope.ownerPubKey).publicKey,g=n;if(!g){let f=await this.scope.connection.getAccountInfo(t);f||this.logAndCreateError("pool not found"),g=De.decode(f.data)}let b=pe(this.scope.ownerPubKey,g.mintA,Pe).publicKey;return u.addInstruction({instructions:[Le(this.scope.ownerPubKey,b,this.scope.ownerPubKey,g.mintA)]}),u.addInstruction({instructions:[go(e,this.scope.ownerPubKey,d,t,p,b,g.vaultA,g.mintA,Pe)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r})}async claimMultiVesting({programId:e=ae,poolIdList:t,poolsInfo:n={},vestingRecords:i={},txVersion:r,computeBudgetConfig:s,feePayer:l}){let c=this.createTxBuilder(l),u=F({},n),d=Ee(e).publicKey,p=t.filter(g=>!u[g.toBase58()]);if(p.length){let g=await this.getRpcPoolsInfo({poolIdList:p});u=F(F({},u),g.poolInfoMap)}return t.forEach(g=>{let b=g.toBase58(),f=u[b];f||this.logAndCreateError(`pool info not found: ${b}`);let y=i[b]||Kt(e,g,this.scope.ownerPubKey).publicKey,P=pe(this.scope.ownerPubKey,f.mintA,Pe).publicKey;c.addInstruction({instructions:[Le(this.scope.ownerPubKey,P,this.scope.ownerPubKey,f.mintA)]}),c.addInstruction({instructions:[go(e,this.scope.ownerPubKey,d,g,y,P,f.vaultA,f.mintA,Pe)]})}),r===0?c.sizeCheckBuildV0({computeBudgetConfig:s}):c.sizeCheckBuild({computeBudgetConfig:s})}async claimVaultPlatformFee({programId:e=ae,platformId:t,mintB:n,mintBProgram:i,claimFeeWallet:r,txVersion:s,computeBudgetConfig:l,txTipConfig:c,feePayer:u}){let d=this.createTxBuilder(u),p=et(e,t,n).publicKey,g=mo(e).publicKey,{mintBProgram:b}=await this.getMintBTokenInfo({mintB:n,mintBProgram:i}),f=this.scope.account.getAssociatedTokenAccount(n,b);return d.addInstruction({instructions:[Le(this.scope.ownerPubKey,f,this.scope.ownerPubKey,n,b),wo(e,t,r!=null?r:this.scope.ownerPubKey,g,p,f,n,b)]}),d.addCustomComputeBudget(l),d.addTipInstruction(c),d.versionBuild({txVersion:s})}async claimMultipleVaultPlatformFee({programId:e=ae,platformList:t,unwrapSol:n=!0,txVersion:i,computeBudgetConfig:r,feePayer:s,associatedOnly:l=!0,checkCreateATAOwner:c=!1}){let u=this.createTxBuilder(s),d={};return t.forEach(async p=>{var P,h,B;let g=mo(e).publicKey,b=et(e,p.id,p.mintB).publicKey,f=p.mintB.equals(ze)&&n,y=d[p.mintB.toBase58()];if(!y){let{account:K,instructionParams:C}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:(P=p.mintBProgram)!=null?P:Pe,mint:p.mintB,owner:this.scope.ownerPubKey,createInfo:f?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!f,notUseTokenAccount:f,associatedOnly:f?!1:l,checkCreateATAOwner:c});K&&(y=K),u.addInstruction(C||{}),y===void 0&&this.logAndCreateError(`cannot found platform ${p.id.toBase58()} mintB(${p.mintB.toBase58()}) token accounts`,"tokenAccounts",this.scope.account.tokenAccounts)}u.addInstruction({instructions:[wo(e,p.id,(h=p.claimFeeWallet)!=null?h:this.scope.ownerPubKey,g,b,y,p.mintB,(B=p.mintBProgram)!=null?B:Pe)]})}),i===0?u.sizeCheckBuildV0({computeBudgetConfig:r}):u.sizeCheckBuild({computeBudgetConfig:r})}async claimCreatorFee({programId:e=ae,mintB:t,mintBProgram:n,txVersion:i,computeBudgetConfig:r,txTipConfig:s,feePayer:l}){let c=this.createTxBuilder(l),u=tt(e,this.scope.ownerPubKey,t).publicKey,d=po(e).publicKey,{mintBProgram:p}=await this.getMintBTokenInfo({mintB:t,mintBProgram:n}),g=this.scope.account.getAssociatedTokenAccount(t,p);return c.addInstruction({instructions:[Le(this.scope.ownerPubKey,g,this.scope.ownerPubKey,t,p),ko(e,this.scope.ownerPubKey,d,u,g,t,p)]}),c.addCustomComputeBudget(r),c.addTipInstruction(s),c.versionBuild({txVersion:i})}async claimMultipleCreatorFee({programId:e=ae,mintBList:t,txVersion:n,computeBudgetConfig:i,feePayer:r}){let s=this.createTxBuilder(r);return t.forEach(l=>{var b;let c=l.pubKey,u=(b=l.programId)!=null?b:Pe,d=tt(e,this.scope.ownerPubKey,c).publicKey,p=po(e).publicKey,g=this.scope.account.getAssociatedTokenAccount(c,u);s.addInstruction({instructions:[Le(this.scope.ownerPubKey,g,this.scope.ownerPubKey,c,u),ko(e,this.scope.ownerPubKey,p,d,g,c,u)]})}),n==0?s.sizeCheckBuildV0({computeBudgetConfig:i}):s.sizeCheckBuild({computeBudgetConfig:i})}async createPlatformAllowConfig({programId:e=ae,platformAdmin:t,platformId:n,configInfo:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),{publicKey:d}=uo(e,new tn(i.mintB),i.curveType,i.index),{publicKey:p}=Xt(e,n,d);return u.addInstruction({instructions:[ji(e,t,n,d,p)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r,extInfo:{platformId:n}})}async closePlatformAllowConfig({programId:e=ae,platformAdmin:t,platformId:n,configInfo:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),{publicKey:d}=uo(e,new tn(i.mintB),i.curveType,i.index),{publicKey:p}=Xt(e,n,d);return u.addInstruction({instructions:[Ji(e,t,n,d,p)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r,extInfo:{platformAllowConfig:p}})}async createPlatformCurveRule({programId:e=ae,curveRuleAuthority:t,platformId:n,configId:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),{publicKey:d}=fo(e,n,i);return u.addInstruction({instructions:[er(e,t!=null?t:this.scope.ownerPubKey,n,i,d)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r,extInfo:{platformCurveRuleId:d}})}async updatePlatformCurveRule({programId:e=ae,curveRuleAuthority:t,platformCurveRuleId:n,groupId:i,constraints:r,txVersion:s,computeBudgetConfig:l,txTipConfig:c,feePayer:u}){let d=this.createTxBuilder(u),p=await this.scope.connection.getAccountInfo(n);if(!p)throw new Error(`platformCurveRule ${n} not found`);let g=Bn.decode(p.data);return d.addInstruction({instructions:[tr(e,t!=null?t:this.scope.ownerPubKey,g.platformId,g.configId,n,i,r)]}),d.addCustomComputeBudget(l),d.addTipInstruction(c),d.versionBuild({txVersion:s})}async removePlatformCurveRule({programId:e=ae,curveRuleAuthority:t,platformCurveRuleId:n,groupId:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),d=await this.scope.connection.getAccountInfo(n);if(!d)throw new Error(`platformCurveRule ${n} not found`);let p=Bn.decode(d.data);return u.addInstruction({instructions:[nr(e,t!=null?t:this.scope.ownerPubKey,p.platformId,p.configId,n,i)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r})}async closePlatformCurveRule({programId:e=ae,curveRuleAuthority:t,platformCurveRuleId:n,txVersion:i,computeBudgetConfig:r,txTipConfig:s,feePayer:l}){let c=this.createTxBuilder(l),u=await this.scope.connection.getAccountInfo(n);if(!u)throw new Error(`platformCurveRule ${n} not found`);let d=Bn.decode(u.data);return c.addInstruction({instructions:[or(e,t!=null?t:this.scope.ownerPubKey,d.platformId,d.configId,n)]}),c.addCustomComputeBudget(r),c.addTipInstruction(s),c.versionBuild({txVersion:i})}async getRpcPoolInfo({poolId:e}){return(await this.getRpcPoolsInfo({poolIdList:[e]})).poolInfoMap[e.toBase58()]}async getRpcPoolsInfo({poolIdList:e,config:t}){let n=await xe(this.scope.connection,e.map(c=>({pubkey:c})),t),i={},r=[];for(let c=0;c<e.length;c++){let u=n[c];if(u===null||!u.accountInfo)throw Error("fetch pool info error: "+e[c].toBase58());let d=De.decode(u.accountInfo.data);i[e[c].toBase58()]=U(F({},d),{poolId:e[c],programId:u.accountInfo.owner}),r.push(d.configId)}let s=await xe(this.scope.connection,r.map(c=>({pubkey:c})),t),l={};for(let c=0;c<r.length;c++){let u=s[c];if(u===null||!u.accountInfo)throw Error("fetch config info error: "+r[c].toBase58());let d=nt.decode(u.accountInfo.data);l[r[c].toBase58()]=U(F({},d),{configId:u.accountInfo.owner})}return{poolInfoMap:Object.keys(i).reduce((c,u)=>U(F({},c),{[u]:U(F({},i[u]),{configInfo:l[i[u].configId.toBase58()]})}),{})}}};export{Mn as LaunchpadPoolInitParam,Ln as default,WL as usdMintBSet};
//# sourceMappingURL=launchpad.mjs.map