UNPKG

@raydium-io/raydium-sdk-v2

Version:

An SDK for building applications on top of Raydium.

2 lines 113 kB
var jo=Object.defineProperty,Jo=Object.defineProperties;var ei=Object.getOwnPropertyDescriptors;var Bt=Object.getOwnPropertySymbols;var _n=Object.prototype.hasOwnProperty,Vn=Object.prototype.propertyIsEnumerable;var vn=(i,e,t)=>e in i?jo(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,L=(i,e)=>{for(var t in e||(e={}))_n.call(e,t)&&vn(i,t,e[t]);if(Bt)for(var t of Bt(e))Vn.call(e,t)&&vn(i,t,e[t]);return i},_=(i,e)=>Jo(i,ei(e));var ge=(i,e)=>{var t={};for(var o in i)_n.call(i,o)&&e.indexOf(o)<0&&(t[o]=i[o]);if(i!=null&&Bt)for(var o of Bt(i))e.indexOf(o)<0&&Vn.call(i,o)&&(t[o]=i[o]);return t};import{PublicKey as oi}from"@solana/web3.js";import{get as En,set as ti}from"lodash";var jt=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(o=>typeof o=="object"?JSON.stringify(o):o).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}},Dn={},ni={};function q(i){let e=En(Dn,i);if(!e){let t=En(ni,i);e=new jt({name:i,logLevel:t}),ti(Dn,i,e)}return e}import{MINT_SIZE as Zs,TOKEN_PROGRAM_ID as $s,getTransferFeeConfig as js,unpackMint as Js}from"@solana/spl-token";var Jt=q("Raydium_accountInfo_util");async function he(i,e,t){let{batchRequest:o,commitment:r="confirmed",chunkCount:a=100}=L({batchRequest:!1},t),s=en(e,a),c=new Array(s.length).fill([]);if(o){let f=s.map(T=>{let B=i._buildArgs([T.map(I=>I.toBase58())],r,"base64");return{methodName:"getMultipleAccounts",args:B}}),P=en(f,10);c=(await(await Promise.all(P.map(async T=>await i._rpcBatchRequest(T)))).flat()).map(T=>(T.error&&Jt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${T.error.message}`),T.result.value.map(B=>{if(B){let{data:I,executable:K,lamports:h,owner:A,rentEpoch:w}=B;return I.length!==2&&I[1]!=="base64"&&Jt.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(I[0],"base64"),executable:K,lamports:h,owner:new oi(A),rentEpoch:w}}return null})))}else try{c=await Promise.all(s.map(f=>i.getMultipleAccountsInfo(f,r)))}catch(f){f instanceof Error&&Jt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${f.message}`)}return c.flat()}import xe from"bn.js";import nR from"decimal.js";import mi from"big.js";import bu from"bn.js";import ii from"toformat";var ri=ii,at=ri;import Kt from"big.js";import si from"bn.js";import ui from"decimal.js-light";import st from"bn.js";var Wn=9007199254740991;function ce(i){let e=q("Raydium_parseBigNumberish");if(i instanceof st)return i;if(typeof i=="string"){if(i.match(/^-?[0-9]+$/))return new st(i);e.logWithError(`invalid BigNumberish string: ${i}`)}return typeof i=="number"?(i%1&&e.logWithError(`BigNumberish number underflow: ${i}`),(i>=Wn||i<=-Wn)&&e.logWithError(`BigNumberish number overflow: ${i}`),new st(String(i))):typeof i=="bigint"?new st(i.toString()):(e.error(`invalid BigNumberish value: ${i}`),new st(0))}var St=q("module/fraction"),tn=at(Kt),ut=at(ui),ci={[0]:ut.ROUND_DOWN,[1]:ut.ROUND_HALF_UP,[2]:ut.ROUND_UP},li={[0]:Kt.roundDown,[1]:Kt.roundHalfUp,[2]:Kt.roundUp},z=class{constructor(e,t=new si(1)){this.numerator=ce(e),this.denominator=ce(t)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new z(this.denominator,this.numerator)}add(e){let t=e instanceof z?e:new z(ce(e));return this.denominator.eq(t.denominator)?new z(this.numerator.add(t.numerator),this.denominator):new z(this.numerator.mul(t.denominator).add(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}sub(e){let t=e instanceof z?e:new z(ce(e));return this.denominator.eq(t.denominator)?new z(this.numerator.sub(t.numerator),this.denominator):new z(this.numerator.mul(t.denominator).sub(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}mul(e){let t=e instanceof z?e:new z(ce(e));return new z(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof z?e:new z(ce(e));return new z(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},o=1){Number.isInteger(e)||St.logWithError(`${e} is not an integer.`),e<=0&&St.logWithError(`${e} is not positive.`),ut.set({precision:e+1,rounding:ci[o]});let r=new ut(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return r.toFormat(r.decimalPlaces(),t)}toFixed(e,t={groupSeparator:""},o=1){return Number.isInteger(e)||St.logWithError(`${e} is not an integer.`),e<0&&St.logWithError(`${e} is negative.`),tn.DP=e,tn.RM=li[o]||1,new tn(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var Bu=q("Raydium_amount"),Su=at(mi);import{PublicKey as pi}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as qn}from"@solana/spl-token";var xt={chainId:101,address:pi.default.toBase58(),programId:qn.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}},Pe={chainId:101,address:"So11111111111111111111111111111111111111112",programId:qn.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 on}from"@solana/web3.js";import{PublicKey as Q,SystemProgram as Un,SYSVAR_RENT_PUBKEY as fi}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as yi}from"@solana/spl-token";function De({pubkey:i,isSigner:e=!1,isWritable:t=!0}){return{pubkey:i,isWritable:t,isSigner:e}}var bi=[De({pubkey:yi,isWritable:!1}),De({pubkey:Un.programId,isWritable:!1}),De({pubkey:fi,isWritable:!1})];function Gn({publicKey:i,transformSol:e}){let t=zn(i.toString());if(t instanceof Q)return e&&t.equals(Le)?Ie:t;if(e&&t.toString()===Le.toBase58())return Ie;if(typeof t=="string"){if(t===Q.default.toBase58())return Q.default;try{return new Q(t)}catch{throw new Error("invalid public key")}}throw new Error("invalid public key")}function zn(i){try{return new Q(i)}catch{return i}}var nn=new Q("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Oe=new Q("SysvarRent111111111111111111111111111111111"),Mu=new Q("SysvarC1ock11111111111111111111111111111111"),We=new Q("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),gi=new Q("Sysvar1nstructions1111111111111111111111111"),Pi=Un.programId,Fu=new Q("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),vu=new Q("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),_u=new Q("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Vu=new Q("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Eu=new Q("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),Du=new Q("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Wu=new Q("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),qu=new Q("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Uu=new Q("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Gu=new Q("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),zu=new Q("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),Ie=new Q("So11111111111111111111111111111111111111112"),Le=Q.default;var rn=class{constructor({mint:e,decimals:t,symbol:o,name:r,skipMint:a=!1,isToken2022:s=!1}){if(e===Le.toBase58()||e instanceof on&&Le.equals(e)){this.decimals=Pe.decimals,this.symbol=Pe.symbol,this.name=Pe.name,this.mint=new on(Pe.address),this.isToken2022=!1;return}this.decimals=t,this.symbol=o||e.toString().substring(0,6),this.name=r||e.toString().substring(0,6),this.mint=a?on.default:Gn({publicKey:e}),this.isToken2022=s}equals(e){return this===e?!0:this.mint.equals(e.mint)}},re=rn;re.WSOL=new rn(_(L({},Pe),{mint:Pe.address}));var an=class{constructor({decimals:e,symbol:t="UNKNOWN",name:o="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=o}equals(e){return this===e}},Ct=an;Ct.SOL=new an(xt);import Ai from"bn.js";var oc=new z(new Ai(100));var cc=q("Raydium_price");import{merge as iC}from"lodash";import Pc from"axios";var Xn={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"},wi=_(L({},Xn),{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 Wc=q("Raydium_Api");import{PublicKey as ad,SystemProgram as sd}from"@solana/web3.js";import{AccountLayout as dd,createAssociatedTokenAccountIdempotentInstruction as pd,TOKEN_PROGRAM_ID as fd,TOKEN_2022_PROGRAM_ID as yd}from"@solana/spl-token";import{PublicKey as Xe,sendAndConfirmTransaction as dn,SystemProgram as Si,Transaction as mt,TransactionMessage as dt,VersionedTransaction as pt}from"@solana/web3.js";import Ki from"axios";import{PublicKey as sn,AddressLookupTableAccount as Ge}from"@solana/web3.js";async function un({connection:i,address:e,cluster:t="mainnet"}){let o=await he(i,[...new Set(e.map(a=>a.toString()))].map(a=>new sn(a))),r={};for(let a=0;a<e.length;a++){let s=o[a],c=e[a];if(!s)continue;let f=new Ge({key:c,state:Ge.deserialize(s.data)});r[c.toString()]=f,t==="devnet"?Ue[c.toString()]=f:qe[c.toString()]=f}return r}var qe={},cn=async i=>{let e="AcL1Vo8oy1ULiavEcjSUcwfBSForXMudcZvDZy5nzJkU";if(qe[e])return qe;let t=new sn(e),o=await i.getAccountInfo(t);return o&&(qe[e]=new Ge({key:t,state:Ge.deserialize(o.data)})),qe},Ue={},ln=async i=>{let e="EFhMuDw1PKEuckuFRW9PavNfTH4LKP5uKHgyXDmWpFCq";if(Ue[e])return Ue;let t=new sn(e),o=await i.getAccountInfo(t);return o&&(Ue[e]=new Ge({key:t,state:Ge.deserialize(o.data)})),Ue};var ee={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{ComputeBudgetProgram as Yn,Keypair as Qn,PublicKey as ki,Transaction as Zn,TransactionMessage as Ti,VersionedTransaction as $n}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as hi}from"@solana/spl-token";var Hn=q("Raydium_txUtil"),jn=1644;function Rt(i){let e=[],t=[];return i.microLamports&&(e.push(Yn.setComputeUnitPrice({microLamports:i.microLamports})),t.push(ee.SetComputeUnitPrice)),i.units&&(e.push(Yn.setComputeUnitLimit({units:i.units})),t.push(ee.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}async function ze(i,e){var o,r;let t=e!=null?e:"confirmed";return(r=await((o=i.getLatestBlockhash)==null?void 0:o.call(i,{commitment:t})))==null?void 0:r.blockhash}async function Lt(i,e){return i.getSignatureStatuses([e]),new Promise((t,o)=>{let r=setTimeout(o,6e4);i.onSignature(e,a=>{if(clearTimeout(r),!a.err){t("");return}o(Object.assign(a.err,{txId:e}))},"confirmed")})}function mn(i,e){i.length<1&&Hn.logWithError(`no instructions provided: ${i.toString()}`),e.length<1&&Hn.logWithError(`no signers provided:, ${e.toString()}`);let t=new Zn;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...i);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<jn}catch{return!1}}function Y(i,e){let[t,o]=ki.findProgramAddressSync(i,e);return{publicKey:t,nonce:o}}function ct({instructions:i,payer:e,signers:t}){return mn(i,[e,...t])}function lt({instructions:i,payer:e,lookupTableAddressAccount:t,recentBlockhash:o=Qn.generate().publicKey.toString()}){let a=new Ti({payerKey:e,recentBlockhash:o,instructions:i}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new $n(a).serialize()).toString("base64").length<jn}catch{return!1}}var Ii=i=>Buffer.isBuffer(i)?i:i instanceof Uint8Array?Buffer.from(i.buffer,i.byteOffset,i.byteLength):Buffer.from(i),Bi=i=>{let e=i.serialize({requireAllSignatures:!1,verifySignatures:!1});i instanceof $n&&(e=Ii(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch{return e.toString("base64")}};function Ne(i){let e=[];return i.forEach(t=>{t instanceof Zn&&(t.recentBlockhash||(t.recentBlockhash=hi.toBase58()),t.feePayer||(t.feePayer=Qn.generate().publicKey)),e.push(Bi(t))}),console.log("simulate tx string:",e),e}var Ot=2e3,Nt=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 o;let e=(await Ki.get(`https://solanacompass.com/api/fees?cacheFreshTime=${3e5}`)).data,{avg:t}=(o=e==null?void 0:e[15])!=null?o:{};if(!!t)return{units:6e5,microLamports:Math.min(Math.ceil(t*1e6/6e5),25e3)}}addCustomComputeBudget(e){if(e){let{instructions:t,instructionTypes:o}=Rt(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...o),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(Si.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new Xe(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(ee.TransferTip),!0):!1}async calComputeBudget({config:e,defaultIns:t}){try{let o=e||await this.getComputeBudgetConfig();if(this.addCustomComputeBudget(o))return;t&&this.instructions.unshift(...t)}catch{t&&this.instructions.unshift(...t)}}addInstruction({instructions:e=[],endInstructions:t=[],signers:o=[],instructionTypes:r=[],endInstructionTypes:a=[],lookupTableAddress:s=[]}){return this.instructions.push(...e),this.endInstructions.push(...t),this.signers.push(...o),this.instructionTypes.push(...r),this.endInstructionTypes.push(...a),this.lookupTableAddress.push(...s.filter(c=>c!==Xe.default.toString())),this}async versionBuild({txVersion:e,extInfo:t,lookupTableAddress:o}){return e===0?await this.buildV0(_(L({},t||{}),{lookupTableAddress:o})):this.build(t)}build(e){var o;let t=new mt;return this.allInstructions.length&&t.add(...this.allInstructions),t.feePayer=this.feePayer,((o=this.owner)==null?void 0:o.signer)&&!this.signers.some(r=>r.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 r=>{var b;let{recentBlockHash:a,skipPreflight:s=!0,sendAndConfirm:c,notSendToRpc:f}=r||{},P=a!=null?a:await ze(this.connection,this.blockhashCommitment);if(t.recentBlockhash=P,this.signers.length&&t.sign(...this.signers),Ne([t]),(b=this.owner)!=null&&b.isKeyPair)return{txId:c?await dn(this.connection,t,this.signers.find(B=>B.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 T=await this.signAllTransactions([t]);if(this.signers.length)for(let B of T)try{B.sign(...this.signers)}catch{}return{txId:f?"":await this.connection.sendRawTransaction(T[0].serialize(),{skipPreflight:s}),signedTx:T[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:e||{}}}buildMultiTx(e){var P;let{extraPreBuildData:t=[],extInfo:o}=e,{transaction:r}=this.build(o),a=t.filter(b=>b.transaction.instructions.length>0),s=[r,...a.map(b=>b.transaction)],c=[this.signers,...a.map(b=>b.signers)],f=[...this.instructionTypes,...a.map(b=>b.instructionTypes).flat()];return(P=this.owner)!=null&&P.signer&&c.forEach(b=>{b.some(T=>T.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:s,signers:c,instructionTypes:f,execute:async b=>{var w;let{sequentially:T,onTxUpdate:B,skipTxCount:I=0,recentBlockHash:K,skipPreflight:h=!0}=b||{},A=K!=null?K:await ze(this.connection,this.blockhashCommitment);if((w=this.owner)!=null&&w.isKeyPair){if(T){let k=[],y=0;for(let R of s){if(++y,y<=I)continue;let g=await dn(this.connection,R,this.signers.find(S=>S.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:h});k.push(g)}return{txIds:k,signedTxs:s}}return{txIds:await await Promise.all(s.map(async k=>(k.recentBlockhash=A,await this.connection.sendRawTransaction(k.serialize(),{skipPreflight:h})))),signedTxs:s}}if(this.signAllTransactions){let k=s.map((R,g)=>(R.recentBlockhash=A,c[g].length&&R.sign(...c[g]),R));Ne(k);let y=await this.signAllTransactions(k);if(T){let R=0,g=[],S=async()=>{if(!y[R])return;let C=await this.connection.sendRawTransaction(y[R].serialize(),{skipPreflight:h});g.push({txId:C,status:"sent",signedTx:y[R]}),B==null||B([...g]),R++;let O=!1,N=null,F=null,G=W=>{N!==null&&clearInterval(N),F!==null&&this.connection.removeSignatureListener(F);let E=g.findIndex(H=>H.txId===C);if(E>-1){if(g[E].status==="error"||g[E].status==="success")return;g[E].status=W.err?"error":"success"}B==null||B([...g]),W.err||S()};this.loopMultiTxStatus&&(N=setInterval(async()=>{var W;if(O){clearInterval(N);return}try{let E=await this.connection.getTransaction(C,{commitment:"confirmed",maxSupportedTransactionVersion:1});E&&(O=!0,clearInterval(N),G({err:((W=E.meta)==null?void 0:W.err)||null}),console.log("tx status from getTransaction:",C))}catch(E){O=!0,clearInterval(N),console.error("getTransaction timeout:",E,C)}},Ot)),F=this.connection.onSignature(C,W=>{if(O){this.connection.removeSignatureListener(F);return}O=!0,G(W)},"confirmed"),this.connection.getSignatureStatus(C)};return await S(),{txIds:g.map(C=>C.txId),signedTxs:y}}else{let R=[];for(let g=0;g<y.length;g+=1){let S=await this.connection.sendRawTransaction(y[g].serialize(),{skipPreflight:h});R.push(S)}return{txIds:R,signedTxs:y}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:o||{}}}async versionMultiBuild({extraPreBuildData:e,txVersion:t,extInfo:o}){return t===0?await this.buildV0MultiTx({extraPreBuildData:e,buildProps:o||{}}):this.buildMultiTx({extraPreBuildData:e,extInfo:o})}async buildV0(e){var h;let K=e||{},{lookupTableCache:t={},lookupTableAddress:o=[],forerunCreate:r,recentBlockhash:a}=K,s=ge(K,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),c=L(L({},this.cluster==="devnet"?await ln(this.connection):await cn(this.connection)),t),f=Array.from(new Set([...o,...this.lookupTableAddress])),P=[];for(let A of f)c[A]===void 0&&P.push(new Xe(A));let b=await un({connection:this.connection,address:P});for(let[A,w]of Object.entries(b))c[A]=w;let T=r?Xe.default.toBase58():a!=null?a:await ze(this.connection,this.blockhashCommitment),B=new dt({payerKey:this.feePayer,recentBlockhash:T,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(c));((h=this.owner)==null?void 0:h.signer)&&!this.signers.some(A=>A.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let I=new pt(B);return I.sign(this.signers),{builder:this,transaction:I,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async A=>{var R;let{skipPreflight:w=!0,sendAndConfirm:k,notSendToRpc:y}=A||{};if(Ne([I]),(R=this.owner)!=null&&R.isKeyPair){let g=await this.connection.sendTransaction(I,{skipPreflight:w});return k&&await Lt(this.connection,g),{txId:g,signedTx:I}}if(this.signAllTransactions){let g=await this.signAllTransactions([I]);if(this.signers.length)for(let S of g)try{S.sign(this.signers)}catch{}return{txId:y?"":await this.connection.sendTransaction(g[0],{skipPreflight:w}),signedTx:g[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:s||{}}}async buildV0MultiTx(e){var P;let{extraPreBuildData:t=[],buildProps:o}=e,{transaction:r}=await this.buildV0(o),a=t.filter(b=>b.builder.instructions.length>0),s=[r,...a.map(b=>b.transaction)],c=[this.signers,...a.map(b=>b.signers)],f=[...this.instructionTypes,...a.map(b=>b.instructionTypes).flat()];return(P=this.owner)!=null&&P.signer&&c.forEach(b=>{b.some(T=>T.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),s.forEach(async(b,T)=>{b.sign(c[T])}),{builder:this,transactions:s,signers:c,instructionTypes:f,buildProps:o,execute:async b=>{var h;let{sequentially:T,onTxUpdate:B,recentBlockHash:I,skipPreflight:K=!0}=b||{};if(I&&s.forEach(A=>A.message.recentBlockhash=I),Ne(s),(h=this.owner)!=null&&h.isKeyPair){if(T){let A=[];for(let w of s){let k=await this.connection.sendTransaction(w,{skipPreflight:K});await Lt(this.connection,k),A.push(k)}return{txIds:A,signedTxs:s}}return{txIds:await Promise.all(s.map(async A=>await this.connection.sendTransaction(A,{skipPreflight:K}))),signedTxs:s}}if(this.signAllTransactions){let A=await this.signAllTransactions(s);if(T){let w=0,k=[],y=async()=>{if(!A[w])return;let R=await this.connection.sendTransaction(A[w],{skipPreflight:K});k.push({txId:R,status:"sent",signedTx:A[w]}),B==null||B([...k]),w++;let g=!1,S=null,C=null,O=N=>{S!==null&&clearInterval(S),C!==null&&this.connection.removeSignatureListener(C);let F=k.findIndex(G=>G.txId===R);if(F>-1){if(k[F].status==="error"||k[F].status==="success")return;k[F].status=N.err?"error":"success"}B==null||B([...k]),N.err||y()};this.loopMultiTxStatus&&(S=setInterval(async()=>{var N;if(g){clearInterval(S);return}try{let F=await this.connection.getTransaction(R,{commitment:"confirmed",maxSupportedTransactionVersion:1});F&&(g=!0,clearInterval(S),O({err:((N=F.meta)==null?void 0:N.err)||null}),console.log("tx status from getTransaction:",R))}catch(F){g=!0,clearInterval(S),console.error("getTransaction timeout:",F,R)}},Ot)),C=this.connection.onSignature(R,N=>{if(g){this.connection.removeSignatureListener(C);return}g=!0,O(N)},"confirmed"),this.connection.getSignatureStatus(R)};return y(),{txIds:[],signedTxs:A}}else{let w=[];for(let k=0;k<A.length;k+=1){let y=await this.connection.sendTransaction(A[k],{skipPreflight:K});w.push(y)}return{txIds:w,signedTxs:A}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:o||{}}}async sizeCheckBuild(e){var B;let T=e||{},{splitIns:t=[],computeBudgetConfig:o}=T,r=ge(T,["splitIns","computeBudgetConfig"]),a=o?Rt(o):{instructions:[],instructionTypes:[]},s=this.signers.reduce((I,K)=>_(L({},I),{[K.publicKey.toBase58()]:K}),{}),c=[],f=[],P=[],b=0;if(this.allInstructions.forEach(I=>{let K=[...P,I],h=o?[...a.instructions,...K]:K,w=[...new Set(K.map(k=>k.keys.filter(y=>y.isSigner).map(y=>y.pubkey.toString())).flat()).values()].map(k=>new Xe(k));if(I!==t[b]&&P.length<12&&(ct({instructions:h,payer:this.feePayer,signers:w})||ct({instructions:K,payer:this.feePayer,signers:w})))P.push(I);else{if(P.length===0)throw Error("item ins too big");b+=I===t[b]?1:0,ct({instructions:o?[...a.instructions,...P]:[...P],payer:this.feePayer,signers:w})?c.push(new mt().add(...a.instructions,...P)):c.push(new mt().add(...P)),f.push(Array.from(new Set(P.map(k=>k.keys.filter(y=>y.isSigner).map(y=>y.pubkey.toString())).flat())).map(k=>s[k]).filter(k=>k!==void 0)),P=[I]}}),P.length>0){let K=[...new Set(P.map(h=>h.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat()).values()].map(h=>s[h]).filter(h=>h!==void 0);ct({instructions:o?[...a.instructions,...P]:[...P],payer:this.feePayer,signers:K.map(h=>h.publicKey)})?c.push(new mt().add(...a.instructions,...P)):c.push(new mt().add(...P)),f.push(K)}return c.forEach(I=>I.feePayer=this.feePayer),(B=this.owner)!=null&&B.signer&&f.forEach(I=>{I.some(K=>K.publicKey.equals(this.owner.publicKey))||I.push(this.owner.signer)}),{builder:this,transactions:c,signers:f,instructionTypes:this.instructionTypes,execute:async I=>{var R;let{sequentially:K,onTxUpdate:h,skipTxCount:A=0,recentBlockHash:w,skipPreflight:k=!0}=I||{},y=w!=null?w:await ze(this.connection,this.blockhashCommitment);if(c.forEach(async(g,S)=>{g.recentBlockhash=y,f[S].length&&g.sign(...f[S])}),Ne(c),(R=this.owner)!=null&&R.isKeyPair){if(K){let g=0,S=[];for(let C of c){if(++g,g<=A){S.push("tx skipped");continue}let O=await dn(this.connection,C,this.signers.find(N=>N.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:k});S.push(O)}return{txIds:S,signedTxs:c}}return{txIds:await Promise.all(c.map(async g=>await this.connection.sendRawTransaction(g.serialize(),{skipPreflight:k}))),signedTxs:c}}if(this.signAllTransactions){let g=await this.signAllTransactions(c.slice(A,c.length)),S=[...c.slice(0,A),...g];if(K){let C=0,O=[],N=async()=>{if(!S[C])return;C<A&&(O.push({txId:"",status:"success",signedTx:S[C]}),h==null||h([...O]),C++,N());let F=await this.connection.sendRawTransaction(S[C].serialize(),{skipPreflight:k});O.push({txId:F,status:"sent",signedTx:S[C]}),h==null||h([...O]),C++;let G=!1,W=null,E=null,H=D=>{W!==null&&clearInterval(W),E!==null&&this.connection.removeSignatureListener(E);let ue=O.findIndex(ke=>ke.txId===F);if(ue>-1){if(O[ue].status==="error"||O[ue].status==="success")return;O[ue].status=D.err?"error":"success"}h==null||h([...O]),D.err||N()};this.loopMultiTxStatus&&(W=setInterval(async()=>{var D;if(G){clearInterval(W);return}try{let ue=await this.connection.getTransaction(F,{commitment:"confirmed",maxSupportedTransactionVersion:1});ue&&(G=!0,clearInterval(W),H({err:((D=ue.meta)==null?void 0:D.err)||null}),console.log("tx status from getTransaction:",F))}catch(ue){G=!0,clearInterval(W),console.error("getTransaction timeout:",ue,F)}},Ot)),E=this.connection.onSignature(F,D=>{if(G){this.connection.removeSignatureListener(E);return}G=!0,H(D)},"confirmed"),this.connection.getSignatureStatus(F)};return await N(),{txIds:O.map(F=>F.txId),signedTxs:S}}else{let C=[];for(let O=0;O<S.length;O+=1){let N=await this.connection.sendRawTransaction(S[O].serialize(),{skipPreflight:k});C.push(N)}return{txIds:C,signedTxs:S}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:r||{}}}async sizeCheckBuildV0(e){var R;let y=e||{},{computeBudgetConfig:t,splitIns:o=[],lookupTableCache:r={},lookupTableAddress:a=[],insCountLimit:s=12}=y,c=ge(y,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress","insCountLimit"]),f=L(L({},this.cluster==="devnet"?await ln(this.connection):await cn(this.connection)),r),P=Array.from(new Set([...this.lookupTableAddress,...a])),b=[];for(let g of P)f[g]===void 0&&b.push(new Xe(g));let T=await un({connection:this.connection,address:b});for(let[g,S]of Object.entries(T))f[g]=S;let B=t?Rt(t):{instructions:[],instructionTypes:[]},I=await ze(this.connection,this.blockhashCommitment),K=this.signers.reduce((g,S)=>_(L({},g),{[S.publicKey.toBase58()]:S}),{}),h=[],A=[],w=[],k=0;if(this.allInstructions.forEach(g=>{let S=[...w,g],C=t?[...B.instructions,...S]:S;if(g!==o[k]&&w.length<s&&(lt({instructions:C,payer:this.feePayer,lookupTableAddressAccount:f})||lt({instructions:S,payer:this.feePayer,lookupTableAddressAccount:f})))w.push(g);else{if(w.length===0)throw Error("item ins too big");k+=g===o[k]?1:0;let O={};for(let N of[...new Set(P)])f[N]!==void 0&&(O[N]=f[N]);if(t&&lt({instructions:[...B.instructions,...w],payer:this.feePayer,lookupTableAddressAccount:f,recentBlockhash:I})){let N=new dt({payerKey:this.feePayer,recentBlockhash:I,instructions:[...B.instructions,...w]}).compileToV0Message(Object.values(f));h.push(new pt(N))}else{let N=new dt({payerKey:this.feePayer,recentBlockhash:I,instructions:[...w]}).compileToV0Message(Object.values(f));h.push(new pt(N))}A.push(Array.from(new Set(w.map(N=>N.keys.filter(F=>F.isSigner).map(F=>F.pubkey.toString())).flat())).map(N=>K[N]).filter(N=>N!==void 0)),w=[g]}}),w.length>0){let S=[...new Set(w.map(C=>C.keys.filter(O=>O.isSigner).map(O=>O.pubkey.toString())).flat()).values()].map(C=>K[C]).filter(C=>C!==void 0);if(t&&lt({instructions:[...B.instructions,...w],payer:this.feePayer,lookupTableAddressAccount:f,recentBlockhash:I})){let C=new dt({payerKey:this.feePayer,recentBlockhash:I,instructions:[...B.instructions,...w]}).compileToV0Message(Object.values(f));h.push(new pt(C))}else{let C=new dt({payerKey:this.feePayer,recentBlockhash:I,instructions:[...w]}).compileToV0Message(Object.values(f));h.push(new pt(C))}A.push(S)}return(R=this.owner)!=null&&R.signer&&A.forEach(g=>{g.some(S=>S.publicKey.equals(this.owner.publicKey))||g.push(this.owner.signer)}),h.forEach((g,S)=>{g.sign(A[S])}),{builder:this,transactions:h,buildProps:e,signers:A,instructionTypes:this.instructionTypes,execute:async g=>{var G;let{sequentially:S,onTxUpdate:C,skipTxCount:O=0,recentBlockHash:N,skipPreflight:F=!0}=g||{};if(h.map(async(W,E)=>{A[E].length&&W.sign(A[E]),N&&(W.message.recentBlockhash=N)}),Ne(h),(G=this.owner)!=null&&G.isKeyPair){if(S){let W=0,E=[];for(let H of h){if(++W,W<=O){console.log("skip tx: ",W),E.push("tx skipped");continue}let D=await this.connection.sendTransaction(H,{skipPreflight:F});await Lt(this.connection,D),E.push(D)}return{txIds:E,signedTxs:h}}return{txIds:await Promise.all(h.map(async W=>await this.connection.sendTransaction(W,{skipPreflight:F}))),signedTxs:h}}if(this.signAllTransactions){let W=await this.signAllTransactions(h.slice(O,h.length)),E=[...h.slice(0,O),...W];if(S){let H=0,D=[],ue=async()=>{if(!E[H])return;if(H<O){D.push({txId:"",status:"success",signedTx:E[H]}),C==null||C([...D]),H++,ue();return}let ke=await this.connection.sendTransaction(E[H],{skipPreflight:F});D.push({txId:ke,status:"sent",signedTx:E[H]}),C==null||C([...D]),H++;let it=!1,Ee=null,It=null,Fn=Re=>{Ee!==null&&clearInterval(Ee),It!==null&&this.connection.removeSignatureListener(It);let Te=D.findIndex($o=>$o.txId===ke);if(Te>-1){if(D[Te].status==="error"||D[Te].status==="success")return;D[Te].status=Re.err?"error":"success"}C==null||C([...D]),Re.err||ue()};this.loopMultiTxStatus&&(Ee=setInterval(async()=>{var Re;if(it){clearInterval(Ee);return}try{let Te=await this.connection.getTransaction(ke,{commitment:"confirmed",maxSupportedTransactionVersion:1});Te&&(it=!0,clearInterval(Ee),Fn({err:((Re=Te.meta)==null?void 0:Re.err)||null}),console.log("tx status from getTransaction:",ke))}catch(Te){it=!0,clearInterval(Ee),console.error("getTransaction timeout:",Te,ke)}},Ot)),It=this.connection.onSignature(ke,Re=>{if(it){this.connection.removeSignatureListener(It);return}it=!0,Fn(Re)},"confirmed"),this.connection.getSignatureStatus(ke)};return ue(),{txIds:[],signedTxs:E}}else{let H=[];for(let D=0;D<E.length;D+=1){let ue=await this.connection.sendTransaction(E[D],{skipPreflight:F});H.push(ue)}return{txIds:H,signedTxs:E}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:c||{}}}};var pn=(...i)=>i.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch{return e}}).join(", "),le=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=q(t)}createTxBuilder(e){return this.scope.checkOwner(),new Nt({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(pn(e))}logInfo(...e){this.logger.info(pn(e))}logAndCreateError(...e){let t=pn(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};import{PublicKey as _m,SystemProgram as Em}from"@solana/web3.js";import qm from"bn.js";import{createCloseAccountInstruction as Xm,createInitializeAccountInstruction as Ym,createTransferInstruction as Hm,TOKEN_PROGRAM_ID as Qm}from"@solana/spl-token";import{Keypair as Im,PublicKey as Bm}from"@solana/web3.js";import xm from"bn.js";import{TOKEN_PROGRAM_ID as Lm}from"@solana/spl-token";import{PublicKey as Ei}from"@solana/web3.js";import no,{isBN as oo}from"bn.js";import{bits as xi,BitStructure as Cl,blob as Ci,Blob as Rl,cstr as Ll,f32 as Ol,f32be as Nl,f64 as Ml,f64be as Fl,greedy as vl,Layout as Ri,ns64 as _l,ns64be as Vl,nu64 as El,nu64be as Dl,offset as Li,s16 as Wl,s16be as ql,s24 as Ul,s24be as Gl,s32 as Oi,s32be as zl,s40 as Xl,s40be as Yl,s48 as Hl,s48be as Ql,s8 as Zl,seq as Ni,struct as $l,Structure as Mi,u16 as Fi,u16be as jl,u24 as Jl,u24be as em,u32 as vi,u32be as tm,u40 as nm,u40be as om,u48 as im,u48be as rm,u8 as _i,UInt as Vi,union as am,Union as sm,unionLayoutDiscriminator as um,utf8 as cm}from"@solana/buffer-layout";var Mt=Ri,Jn=Mi;var fn=Vi;var eo=_i,X=Fi;var ft=vi;var fe=Oi;var to=Ni;var V=Ci;var yn=xi,bn=Li;var Fe=class extends Mt{constructor(t,o,r){super(t,r);this.blob=V(t),this.signed=o}decode(t,o=0){let r=new no(this.blob.decode(t,o),10,"le");return this.signed?r.fromTwos(this.span*8).clone():r}encode(t,o,r=0){return typeof t=="number"&&(t=new no(t)),this.signed&&(t=t.toTwos(this.span*8)),this.blob.encode(t.toArrayLike(Buffer,"le",this.span),o,r)}},Ft=class extends Mt{constructor(t){super(8,t);this._lower=yn(ft(),!1),this._upper=yn(ft(),!1)}addBoolean(t){this._lower.fields.length<32?this._lower.addBoolean(t):this._upper.addBoolean(t)}decode(t,o=0){let r=this._lower.decode(t,o),a=this._upper.decode(t,o+this._lower.span);return L(L({},r),a)}encode(t,o,r=0){return this._lower.encode(t,o,r)+this._upper.encode(t,o,r+this._lower.span)}};function l(i){return new fn(1,i)}function Z(i){return new fn(4,i)}function n(i){return new Fe(8,!1,i)}function v(i){return new Fe(16,!1,i)}function io(i){return new Fe(1,!0,i)}function Ye(i){return new Fe(8,!0,i)}function ro(i){return new Fe(16,!0,i)}var ve=class extends Mt{constructor(t,o,r,a){super(t.span,a);this.layout=t,this.decoder=o,this.encoder=r}decode(t,o){return this.decoder(this.layout.decode(t,o))}encode(t,o,r){return this.layout.encode(this.encoder(t),o,r)}getSpan(t,o){return this.layout.getSpan(t,o)}};function u(i){return new ve(V(32),e=>new Ei(e),e=>e.toBuffer(),i)}function pe(i){return new ve(eo(),Di,Wi,i)}function Di(i){if(i===0)return!1;if(i===1)return!0;throw new Error("Invalid bool: "+i)}function Wi(i){return i?1:0}function Pn(i,e){let t=ft("length"),o=m([t,x(i,bn(t,-t.span),"values")]);return new ve(o,({values:r})=>r,r=>({values:r}),e)}function qi(i){let e=ft("length"),t=m([e,V(bn(e,-e.span),"data")]);return new ve(t,({data:o})=>o,o=>({data:o}),i)}function ie(i){return new ve(qi(),e=>e.toString("utf-8"),e=>Buffer.from(e,"utf-8"),i)}var gn=class extends Jn{decode(e,t){return super.decode(e,t)}};function m(i,e,t){return new gn(i,e,t)}function x(i,e,t){let o,r=typeof e=="number"?e:oo(e)?e.toNumber():new Proxy(e,{get(a,s){if(!o){let c=Reflect.get(a,"count");o=oo(c)?c.toNumber():c,Reflect.set(a,"count",o)}return Reflect.get(a,s)},set(a,s,c){return s==="count"&&(o=c),Reflect.set(a,s,c)}});return to(i,r,t)}var vt=m([u("mint"),u("owner"),n("amount"),Z("delegateOption"),u("delegate"),l("state"),Z("isNativeOption"),n("isNative"),n("delegatedAmount"),Z("closeAuthorityOption"),u("closeAuthority")]);import{PublicKey as aA,SystemProgram as sA}from"@solana/web3.js";import{createAssociatedTokenAccountIdempotentInstruction as cA}from"@solana/spl-token";import{PublicKey as Td}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Id}from"@solana/spl-token";import{PublicKey as M}from"@solana/web3.js";var so=new M("EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"),uo=new M("CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T"),co=new M("9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z"),An=new M("FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG"),xd=new M("CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS"),Gi=new M("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"),lo=new M("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),mo=new M("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"),Cd=new M("5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h"),zi=new M("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),po=new M("CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"),Xi=new M("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),Yi=new M("kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy"),fo=new M("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),Rd=new M("routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS"),Hi=new M("7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"),wn=new M("CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"),Qi=new M("GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"),Ld=new M("DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8"),Zi=new M("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),$i=new M("3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH"),ji=new M("LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"),Od=new M("WLHv2UAZm6z4KyaaELi5pjdbJh6RESMva1Rnn8pJVVh"),Nd=new M("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),Md=new M("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),Fd=new M("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),vd=new M("6s1xP3hpbAfFoNtUNF8mfHsjr2Bd97JxFJRWLbL6aHuX");var Be={OPEN_BOOK_PROGRAM:new M("EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj"),SERUM_PROGRAM_ID_V3:new M("Ray1111111111111111111111111111111111111111"),AMM_V4:new M("DRaya7Kj3aMWQSy19kSjvmuwq9docCHofyP9kanQGaav"),AMM_STABLE:new M("DRayDdXc1NZQ9C3hRWmoSf8zK4iapgMnjdNZWrfwsP8m"),CLMM_PROGRAM_ID:new M("DRayAUgENGQBKVaX8owNhgzkEDyoHTGVEGHVJT1E9pfH"),CLMM_LOCK_PROGRAM_ID:new M("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),CLMM_LOCK_AUTH_ID:new M("6Aoh8h2Lw2m5UGxYR8AdAL87jTWYeKoxM52mJRzfYwN"),CREATE_CPMM_POOL_PROGRAM:new M("DRaycpLY18LhpbydsBWbVJtxpNv9oXPgjRSfpF2bWpYb"),CREATE_CPMM_POOL_AUTH:new M("CXniRufdq5xL8t8jZAPxsPZDpuudwuJSPWnbcD5Y5Nxq"),CREATE_CPMM_POOL_FEE_ACC:new M("3oE58BKVt8KuYkGxx8zBojugnymWmBiyafWgMrnb6eYy"),LOCK_CPMM_PROGRAM:new M("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),LOCK_CPMM_AUTH:new M("7qWVV8UY2bRJfDLP4s37YzBPKUkVB46DStYJBpYbQzu3"),UTIL1216:M.default,Router:new M("DRaybByLpbUL57LJARs3j8BitTxVfzBg351EaMr5UTCd"),FARM_PROGRAM_ID_V3:new M("DRayWyrLmEW5KEeqs8kdTMMaBabapqagaBC7KWpGtJeZ"),FARM_PROGRAM_ID_V4:new M("Ray1111111111111111111111111111111111111111"),FARM_PROGRAM_ID_V5:new M("DRayiCGSZgku1GTK6rXD6mVDdingXy6APAH1R6R5L2LC"),FARM_PROGRAM_ID_V6:new M("DRayzbYakXs45ELHkzH6vC3fuhQqTAnv5A68gdFuvZyZ"),LAUNCHPAD_PROGRAM:new M("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),LAUNCHPAD_AUTH:new M("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),LAUNCHPAD_PLATFORM:new M("2Jx4KTDrVSdWNazuGpcA8n3ZLTRGGBDxAWhuKe2Xcj2a"),LAUNCHPAD_CONFIG:new M("7ZR4zD7PYfY2XxoG1Gxcy2EgEeGYrpxrwzPuwdUBssEt"),FEE_DESTINATION_ID:new M("9y8ENuuZ3b19quffx9hQvRVygG5ky6snHfRvGpuSfeJy"),MODEL_DATA_PUBKEY:new M("Ray1111111111111111111111111111111111111111")};import AA from"decimal.js";import{createAssociatedTokenAccountIdempotentInstruction as Wb,TOKEN_2022_PROGRAM_ID as qb,TOKEN_PROGRAM_ID as Ub}from"@solana/spl-token";import{PublicKey as zb}from"@solana/web3.js";import Yb from"bn.js";import Qb from"decimal.js";import{TOKEN_PROGRAM_ID as Zd}from"@solana/spl-token";import{PublicKey as ep}from"@solana/web3.js";var Ji=m([Z("mintAuthorityOption"),u("mintAuthority"),n("supply"),l("decimals"),l("isInitialized"),Z("freezeAuthorityOption"),u("freezeAuthority")]);import{ASSOCIATED_TOKEN_PROGRAM_ID as ub,TOKEN_2022_PROGRAM_ID as cb,TOKEN_PROGRAM_ID as lb}from"@solana/spl-token";import{Keypair as pb,PublicKey as fb,SystemProgram as bb,TransactionInstruction as gb}from"@solana/web3.js";import Ab from"bn.js";import U from"bn.js";var ye=new U(1).shln(64);var er=new U(1).shln(128),Vt=new U(1).shln(64).subn(1),tr=new U(1).shln(128).subn(1);var Qe=new U("4295048016"),Ze=new U("79226673521066979257578248091"),nr=new U("59543866431248"),or=new U("184467440737095516"),ir=new U("15793534762490258745");var kn=60,dp=new U("18446743708227953217"),rr=[{bit:0,factor:new U("fffcb933bd6fb800",16)},{bit:1,factor:new U("fff97272373d4000",16)},{bit:2,factor:new U("fff2e50f5f657000",16)},{bit:3,factor:new U("ffe5caca7e10f000",16)},{bit:4,factor:new U("ffcb9843d60f7000",16)},{bit:5,factor:new U("ff973b41fa98e800",16)},{bit:6,factor:new U("ff2ea16466c9b000",16)},{bit:7,factor:new U("fe5dee046a9a3800",16)},{bit:8,factor:new U("fcbe86c7900bb000",16)},{bit:9,factor:new U("f987a7253ac65800",16)},{bit:10,factor:new U("f3392b0822bb6000",16)},{bit:11,factor:new U("e7159475a2caf000",16)},{bit:12,factor:new U("d097f3bdfd2f2000",16)},{bit:13,factor:new U("a9f746462d9f8000",16)},{bit:14,factor:new U("70d869a156f31c00",16)},{bit:15,factor:new U("31be135f97ed3200",16)},{bit:16,factor:new U("9aa508b5b85a500",16)},{bit:17,factor:new U("5d6af8dedc582c",16)},{bit:18,factor:new U("2216e584f5fa",16)}];var yt=3,yo=100;var bo=10,go=100,Et=14;var te=new U(0),$e=new U(1),pp=new U(-1);var fp=new U("18446744073700000000");var ar=m([V(8),l("bump"),X("index"),u("owner"),Z("protocolFeeRate"),Z("tradeFeeRate"),X("tickSpacing"),Z("fundFeeRate"),x(Z(),1),u("fundOwner"),x(n(),3)]),sr=m([Z("blockTimestamp"),Ye("tickCumulative"),x(n(),4)]),Po=m([V(8),pe("initialized"),n("recentEpoch"),X("observationIndex"),u("poolId"),x(sr,yo,"observations"),x(n(),4)]),ur=m([X("filterPeriod"),X("decayPeriod"),X("reductionFactor"),Z("dynamicFeeControl"),Z("maxVolatilityAccumulator"),fe("tickSpacingIndexReference"),Z("volatilityReference"),Z("volatilityAccumulator"),n("lastUpdateTimestamp"),x(l(),46)]),cr=m([l("state"),n("openTime"),n("endTime"),n("lastUpdateTime"),v("emissionsPerSecondX64"),n("totalEmissioned"),n("claimed"),u("mint"),u("vault"),u("creator"),v("growthGlobalX64")]),Tn=m([V(8),l("bump"),u("configId"),u("creator"),u("mintA"),u("mintB"),u("vaultA"),u("vaultB"),u("observationId"),l("mintDecimalsA"),l("mintDecimalsB"),X("tickSpacing"),v("liquidity"),v("sqrtPriceX64"),fe("tickCurrent"),Z(),v("feeGrowthGlobalX64A"),v("feeGrowthGlobalX64B"),n("protocolFeesTokenA"),n("protocolFeesTokenB"),x(v(),4),l("status"),l("feeOn"),V(6),x(cr,yt,"rewardInfos"),V(8*16,"tickArrayBitmap"),x(n(),4),n("fundFeesTokenA"),n("fundFeesTokenB"),n("startTime"),n("recentEpoch"),ur.replicate("dynamicFeeInfo"),x(n(),46)]),lr=m([v("growthInsideLastX64"),n("rewardAmountOwed")]),mr=m([V(8),l("bump"),u("nftMint"),u("poolId"),fe("tickLower"),fe("tickUpper"),v("liquidity"),v("feeGrowthInsideLastX64A"),v("feeGrowthInsideLastX64B"),n("tokenFeesOwedA"),n("tokenFeesOwedB"),x(lr,yt,"rewardInfos"),n("recentEpoch"),x(n(),7)]),Pp=m([V(8),l("bump"),u("poolId"),fe("tickLower"),fe("tickUpper"),v("liquidity"),v("feeGrowthInsideLastX64A"),v("feeGrowthInsideLastX64B"),n("tokenFeesOwedA"),n("tokenFeesOwedB"),x(v(),yt,"rewardGrowthInside"),n("recentEpoch"),x(n(),7)]),dr=m([fe("tick"),ro("liquidityNet"),v("liquidityGross"),v("feeGrowthOutsideX64A"),v("feeGrowthOutsideX64B"),x(v(),yt,"rewardGrowthsOutsideX64"),n("orderPhase"),n("ordersAmount"),n("partFilledOrdersRemaining"),v("unfilledRatioX64"),x(Z(),3)]),Ao=m([V(8),u("poolId"),fe("startTickIndex"),x(dr,kn,"ticks"),l("initializedTickCount"),n("recentEpoch"),x(l(),107)]),pr=m([V(8),l("bump"),x(u(),bo,"operationOwners"),x(u(),go,"whitelistMints")]),fr=m([V(8),u("poolId"),u("owner"),fe("tick"),pe("zeroForOne"),n("orderPhase"),n("totalAmount"),n("filledAmount"),n("settleBase"),n("settleOutput"),n("openTime"),v("unfilledRatioX64"),x(n(),4)]),wo=m([V(8),u("poolId"),V(8*8*Et,"positiveTickArrayBitmap"),V(8*8*Et,"negativeTickArrayBitmap")]),Ap=m([V(8),X("index"),X("filterPeriod"),X("decayPeriod"),X("reductionFactor"),Z("dynamicFeeControl"),Z("maxVolatilityAccumulator"),x(n(),8)]),yr=m([V(8),u("wallet"),l("nonceIndex"),n("orderNonce"),x(n(),4)]),wp=m([n(),l("bump"),u("owner"),u("poolId"),u("positionId"),u("nftAccount"),x(n(),8)]),br=m([V(8),l("bump"),u("lockOwner"),u("poolId"),u("positionId"),u("nftAccount"),u("lockNftMint"),n("recentEpoch"),x(n(),8)]);import hp from"bn.js";function hn(i){let e=Buffer.alloc(2);return e.writeUInt16LE(i),e}var Mp=Buffer.from("amm_config","utf8"),ko=Buffer.from("pool","utf8"),To=Buffer.from("pool_vault","utf8"),Fp=Buffer.from("pool_reward_vault","utf8"),vp=Buffer.from("position","utf8"),_p=Buffer.from("tick_array","utf8"),Vp=Buffer.from("operation","utf8"),Ep=Buffer.from("pool_tick_array_bitmap_extension","utf8"),Dp=Buffer.from("observation","utf8"),Wp=Buffer.from("support_mint","utf8"),qp=Buffer.from("dynamic_fee_config","utf8"),Up=Buffer.from("permission","utf8");var Gp=Buffer.from("locked_position","utf8");import{sha256 as Lr}from"js-sha256";import gr from"bn.js";import Hp from"decimal.js";var Zp=new gr(1).shln(256).subn(1);import yf from"bn.js";import of from"bn.js";import af from"decimal.js";import wf from"bn.js";import Tf from"decimal.js";import{PublicKey as uy}from"@solana/web3.js";import ly from"bn.js";import{TOKEN_2022_PROGRAM_ID as Py,TOKEN_PROGRAM_ID as Ay}from"@solana/spl-token";import hy from"decimal.js";import $f from"bn.js";import Vf from"bn.js";import My from"bn.js";function ne(i){let e=`global:${i}`;return Buffer.from(Lr.digest(e)).slice(0,8)}Po.span;var xb=q("Raydium_Clmm"),Cb={createPool:ne("create_pool"),createCustomizablePool:ne("create_customizable_pool"),createPermissionedPool:ne("create_permissioned_pool"),openPositionV2:ne("open_position_v2"),openPositionWithToken22Nft:ne("open_position_with_token22_nft"),closePosition:ne("close_position"),increaseLiquidityV2:ne("increase_liquidity_v2"),decreaseLiquidityV2:ne("decrease_liquidity_v2"),initializeReward:ne("initialize_reward"),setRewardParams:ne("set_reward_params"),updateRewardInfos:ne("update_reward_infos"),collectRemainingRewards:ne("collect_remaining_rewards"),swapV2:ne("swap_v2"),openLimitOrder:ne("open_limit_order"),increaseLimitOrder:ne("increase_limit_order"),decreaseLimitOrder:ne("decrease_limit_order"),settleLimitOrder:ne("settle_limit_order"),closeLimitOrder:ne("close_limit_order")};import{PublicKey as Kn}from"@solana/web3.js";var Fr=m([l("instruction")]),vr=m([l("instruction")]),_r=m([n("rewardState"),n("rewardOpenTime"),n("rewardEndTime"),n("rewardLastUpdateTime"),n("totalReward"),n("totalRewardEmissioned"),n("rewardClaimed"),n("rewardPerSecond"),v("accRewardPerShare"),u("rewardVault"),u("rewardMint"),u("rewardSender"),n("rewardType"),x(n(),15,"padding")]),Vr=m([n("state"),n("nonce"),u("lpVault"),u("rewardVault"),u(),u(),n(),n(),n("totalReward"),v("perShareReward"),n("lastSlot"),n("perSlotReward")]),Er=m([n("state"),n("nonce"),u("lpVault"),u("rewardVaultA"),n("totalRewardA"),v("perShareRewardA"),n("perSlotRewardA"),l("option"),u("rewardVaultB"),V(7),n("totalRewardB"),v("perShareRewardB"),n("perSlotRewardB"),n("lastSlot"),u()]),Dr=m([n(),n("state"),n("nonce"),n("validRewardTokenNum"),v("rewardMultiplier"),n("rewardPeriodMax"),n("rewardPeriodMin"),n("rewardPeriodExtend"),u("lpMint"),u("lpVault"),x(_r,5,"rewardInfos"),u("creator"),u(),x(n(),32,"padding")]),Wr=new Proxy(Vr,{get(i,e,t){return e==="decode"?(...o)=>{let r=i.decode(...o);return _(L({},r),{version:3,rewardInfos:[{rewardVault:r.rewardVault,totalReward:r.totalReward,perSlotReward:r.perSlotReward,perShareReward:r.perShareReward}]})}:Reflect.get(i,e,t)}}),qr=new Proxy(Er,{get(i,e,t){return e==="decode"?(...o)=>{let r=i.decode(...o);return _(L({},r),{version:5,rewardInfos:[{rewardVault:r.rewardVaultA,totalReward:r.totalRewardA,perSlotReward:r.perSlotRewardA,perShareReward:r.perShareRewardA},{rewardVault:r.rewardVaultB,totalReward:r.totalRewardB,perSlotReward:r.perSlotRewardB,perShareReward:r.perShareRewardB}]})}:Reflect.get(i,e,t)}}),Co=new Proxy(Dr,{get(i,e,t){return e==="decode"?(...o)=>{let r=i.decode(...o);return _(L({},r),{version:6,rewardInfos:r.rewardInfos.map(a=>{var s;return _(L({},a),{rewardType:((s=Object.entries(Pt).find(c=>String(c[1])===a.rewardType.toString()))!=null?s:["Standard SPL"])[0]})})})}:Reflect.get(i,e,t)}}),Ur=m([n("isSet"),n("rewardPerSecond"),n("rewardOpenTime"),n("rewardEndTime"),n("rewardType")]),Gr=m([l("instruction"),n("nonce"),x(Ur,5,"rewardTimeInfo")]),zr=m([l("instruction"),n("rewardReopenTime"),n("rewardEndTime"),n("rewardPerSecond")]),Xr=m([l("instruction"),n("isSet"),n("rewardPerSecond"),n("rewardOpenTime"),n("rewardEndTime"),n("rewardType")]),Ig=m([n("state"),u("id"),u("owner"),n("deposited"),x(n(),1,"rewardDebts")]),Ro=m([n("state"),u("id"),u("owner"),n("deposited"),x(v(),1,"rewardDebts"),n(""),n("voteLockedBalance"),x(n(),15)]),Bg=m([n("state"),u("id"),u("owner"),n("deposited"),x(n(),2,"rewardDebts")]),Yr=m([n("state"),u("id"),u("owner"),n("deposited"),x(v(),2,"rewardDebts"),x(n(),17)]),Hr=m([n(),n("state"),u("id"),u("owner"),n("deposited"),x(v(),5,"rewardDebts"),x(n(),16)]),Qr=m([l("instruction"),n("amount")]),Zr=m([u("mint"),u("grantAuthority"),n("baselineVoteWeightScaledFactor"),n("maxExtraLockupVoteWeightScaledFactor"),n("lockupSaturationSecs"),io("digitShift"),x(l(),7,"reserved1"),x(n(),7,"reserved2")]),$r=m([V(8),u("governanceProgramId"),u("realm"),u("realmGoverningTokenMint"),u("realmAuthority"),x(l(),32,"reserved1"),x(Zr,4,"votingMints"),Ye("timeOffset"),l("bump"),x(l(),7,"reserved2"),x(n(),11,"reserved3")]),jr=m([Ye("startTime"),Ye("endTime"),l("kind"),x(l(),15,"reserved")]),Jr=m([x(jr,1,"lockup"),n("amountDeposited_native"),n("amountInitiallyLockedNative"),pe("isUsed"),pe("allowClawback"),l("votingMintConfigIdx"),x(l(),29,"reserved")]),ea=m([V(8),u("voterAuthority"),u("registrar"),x(Jr,32,"deposits"),l("voterBump"),l("voterWweightRecordBump"),x(l(),94,"reserved")]);import{NATIVE_MINT as Mg}from"@solana/spl-token";var Fg=q("Raydium_farm_config"),ta=new Kn("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),na=new Kn("FrspKwj8i3pNmKwXreTveC4fu7KL5ZbGeXdZBe2XViu1");var vg=new Kn("3TRTX4dXUpp2eqxi3tvQDFYUV7SdDJjcPE3Y4mbtftaX");var Pt={"Standard SPL":0,"Option tokens":1},Lo={[so.toString()]:3,[uo.toString()]:4,[co.toString()]:5,[An.toString()]:6,[Be.FARM_PROGRAM_ID_V3.toString()]:3,[Be.FARM_PROGRAM_ID_V4.toString()]:4,[Be.FARM_PROGRAM_ID_V5.toString()]:5,[Be.FARM_PROGRAM_ID_V6.toString()]:6};import{PublicKey as kP,SystemProgram as TP,SYSVAR_CLOCK_PUBKEY as hP,SYSVAR_RENT_PUBKEY as IP,TransactionInstruction as BP}from"@solana/web3.js";import KP from"bn.js";import{ASSOCIATED_TOKEN_PROGRAM_ID as CP,createAssociatedTokenAccountIdempotentInstruction as RP,TOKEN_PROGRAM_ID as LP}from"@solana/spl-token";import $g from"bn.js";import{PublicKey as qg}from"@solana/web3.js";import Gg from"bn.js";var lP=q("Raydium.farm.util");var qP=q("Raydium_farm_instruction"),UP={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 RA from"bn.js";import{PublicKey as vk}from"@solana/web3.js";import{AccountLayout as Ek,MintLayout as Dk,NATIVE_MINT as Wk,TOKEN_PROGRAM_ID as Uk}from"@solana/spl-token";import ae from"bn.js";var At=1e4;function Gt(i,e){let{div:t,mod:o}=i.divmod(e);return o.gt(new ae(0))?t.add(new ae(1)):t}function _e(i,e){if(i.isZero())return new ae(0);let t=i.div(e);return t.isZero()?new ae(1):i.mod(e).gt(new ae(0))?t.add(new ae(1)):t}function wt(i,e,t){if(e===void 0)return{amount:i,fee:void 0,expirationTime:void 0};let o=Math.floor(t/432e3),r=o<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,a=new ae(r.maximumFee.toString()),s=o<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*432e3-t)*400/1e3:void 0,c=Gt(i.mul(new ae(r.transferFeeBasisPoints)),new ae(At)),f=c.gt(a)?a:c;return{amount:i,fee:f,expirationTime:s}}function et(i,e,t){if(e===void 0)return{amount:i,fee:void 0,expirationTime:void 0};let o=Math.floor(t/432e3),r=o<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,a=new ae(r.maximumFee.toString()),s=o<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*432e3-t)*400/1e3:void 0;if(r.transferFeeBasisPoints===At){let c=new ae(r.maximumFee.toString());return{amount:i.add(c),fee:c,expirationTime:s}}else{let c=Gt(i.mul(new ae(At)),new ae(At-r.transferFeeBasisPoints)),f=new ae(r.maximumFee.toString()),P=c.sub(i).gt(f)?i.add(f):c,b=Gt(P.mul(new ae(r.transferFeeBasisPoints)),new ae(At)),T=b.gt(a)?a:b;return{amount:P,fee:T,expirationTime:s}}}import No from"bn.js";var la=new No(25),ma=new No(1e4);import{ASSOCIATED_TOKEN_PROGRAM_ID as ew,TOKEN_PROGRAM_ID as tw}from"@solana/spl-token";import{PublicKey as ow,SystemProgram as iw,SYSVAR_RENT_PUBKEY as rw,TransactionInstruction as aw}from"@solana/web3.js";import fw from"bn.js";var da=m([l("instruction"),n("amountIn"),n("minAmountOut")]),pa=m([l("instruction"),n("maxAmountIn"),n("amountOut")]),ZA=m([l("instruction"),l("nonce")]),fa=m([l("instruction"),l("nonce"),n("startTime")]),Mo=m([n("status"),n("nonce"),n("maxOrder"),n("depth"),n("baseDecimal"),n("quoteDecimal"),n("state"),n("resetFlag"),n("minSize"),n("volMaxCutRatio"),n("amountWaveRatio"),n("baseLotSize"),n("quoteLotSize"),n("minPriceMultiplier"),n("maxPriceMultiplier"),n("systemDecimalValue"),n("minSeparateNumerator"),n("minSeparateDenominator"),n("tradeFeeNumerator"),n("tradeFeeDenominator"),n("pnlNumerator"),n("pnlDenominator"),n("swapFeeNumerator"),n("swapFeeDenominator"),n("baseNeedTakePnl"),n("quoteNeedTakePnl"),n("quoteTotalPnl"),n("baseTotalPnl"),n("poolOpenTime"),n("punishPcAmount"),n("punishCoinAmount"),n("orderbookToInitTime"),v("swapBaseInAmount"),v("swapQuoteOutAmount"),n("swapBase2QuoteFee"),v("swapQuoteInAmount"),v("swapBaseOutAmount"),n("swapQuote2BaseFee"),u("baseVault"),u("quoteVault"),u("baseMint"),u("quoteMint"),u("lpMint"),u("openOrders"),u("marketId"),u("marketProgramId"),u("targetOrders"),u("withdrawQueue"),u("lpVault"),u("owner"),n("lpReserve"),x(n(),3,"padding")]),$A=m([n("accountType"),n("status"),n("nonce"),n("maxOrder"),n("depth"),n("baseDecimal"),n("quoteDecimal"),n("state"),n("resetFlag"),n("minSize"),n("volMaxCutRatio"),n("amountWaveRatio"),n("baseLotSize"),n("quoteLotSize"),n("minPriceMultiplier"),n("maxPriceMultiplier"),n("systemDecimalsValue"),n("abortTradeFactor"),n("priceTickMultiplier"),n("priceTick"),n("minSeparateNumerator"),n("minSeparateDenominator"),n("tradeFeeNumerator"),n("tradeFeeDenominator"),n("pnlNumerator"),n("pnlDenominator"),n("swapFeeNumerator"),n("swapFeeDenominator"),n("baseNeedTakePnl"),n("quoteNeedTakePnl"),n("quoteTotalPnl"),n("baseTotalPnl"),n("poolOpenTime"),n("punishPcAmount"),n("punishCoinAmount"),n("orderbookToInitTime"),v("swapBaseInAmount"),v("swapQuoteOutAmount"),v("swapQuoteInAmount"),v("swapBaseOutAmount"),n("swapQuote2BaseFee"),n("swapBase2QuoteFee"),u("baseVault"),u("quoteVault"),u("baseMint"),u("quoteMint"),u("lpMint"),u("modelDataAccount"),u("openOrders"),u("marketId"),u("marketProgramId"),u("targetOrders"),u("owner"),x(n(),64,"padding")]),ya=m([l("instruction"),n("baseAmountIn"),n("quoteAmountIn"),n("fixedSide"),n("otherAmountMin")]),ba=m([l("instruction"),n("lpAmount"),n("baseAmountMin"),n("quoteAmountMin")]);var ga=m([n("fee")]);var gw=q("Raydium_liquidity_instruction");var Pa=5e4,Aa=m([n("x"),n("y"),n("price")]),kw=m([n("accountType"),n("status"),n("multiplier"),n("validDataCount"),x(Aa,Pa,"DataElement")]);import{PublicKey as Nw}from"@solana/web3.js";import Fw from"decimal.js";import{TOKEN_PROGRAM_ID as _w}from"@solana/spl-token";import{PublicKey as Bw}from"@solana/web3.js";var xw=q("Raydium_liquidity_serum");import cT from"bn.js";import mT from"decimal.js";import{TOKEN_PROGRAM_ID as lk}from"@solana/spl-token";import{PublicKey as dk}from"@solana/web3.js";import fk from"bn.js";import{SystemProgram as $w,SYSVAR_RENT_PUBKEY as jw,Transaction as Jw,TransactionInstruction as ek}from"@solana/web3.js";import{createInitializeAccountInstruction as nk,TOKEN_PROGRAM_ID as ok}from"@solana/spl-token";function wa(i="accountFlags"){let e=new Ft(i);return e.addBoolean("initialized"),e.addBoolean("market"),e.addBoolean("openOrders"),e.addBoolean("requestQueue"),e.addBoolean("eventQueue"),e.addBoolean("bids"),e.addBoolean("asks"),e}var ka=m([V(5),wa("accountFlags"),u("ownAddress"),n("vaultSignerNonce"),u("baseMint"),u("quoteMint"),u("baseVault"),n("baseDepositsTotal"),n("baseFeesAccrued"),u("quoteVault"),n("quoteDepositsTotal"),n("quoteFeesAccrued"),n("quoteDustThreshold"),u("requestQueue"),u("eventQueue"),u("bids"),u("asks"),n("baseLotSize"),n("quoteLotSize"),n("feeRateBps"),n("referrerRebatesAccrued"),V(7)]);import{PublicKey as Eh}from"@solana/web3.js";import{AccountLayout as Wh,NATIVE_MINT as qh,TOKEN_2022_PROGRAM_ID as Uh,TOKEN_PROGRAM_ID as Gh,createAssociatedTokenAccountIdempotentInstruction as zh}from"@solana/spl-token";import FT from"bn.js";import xa from"bn.js";var kT=new xa(0);import KT from"bn.js";import Ca from"bn.js";var we=new Ca(1e6);import Jh from"bn.js";import tI from"decimal.js";import{PublicKey as th,TransactionInstruction as nh,Keypair as ih,SystemProgram as rh}from"@solana/web3.js";import{ASSOCIATED_TOKEN_PROGRAM_ID as sh,TOKEN_2022_PROGRAM_ID as uh,TOKEN_PROGRAM_ID as ch}from"@solana/spl-token";var DT=Buffer.from("vault_and_lp_mint_auth_seed","utf8"),WT=Buffer.from("amm_config","utf8"),qT=Buffer.from("pool","utf8"),UT=Buffer.from("pool_lp_mint","utf8"),GT=Buffer.from("pool_vault","utf8"),zT=Buffer.from("observation","utf8"),XT=Buffer.from("permission","utf8"),YT=Buffer.from("support_mint","utf8"),HT=Buffer.from("creator_fee_share","utf8");var QT=Buffer.from("locked_liquidity","utf8");var bh=q("Raydium_cpmm"),gh={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 La=m([V(8),l("bump"),pe("disableCreatePool"),X("index"),n("tradeFeeRate"),n("protocolFeeRate"),n("fundFeeRate"),n("createPoolFee"),u("protocolOwner"),u("fundOwner"),n("creatorFeeRate"),n("creatorFeeShareRate"),x(n(),14)]),Fo=m([V(8),u("configId"),u("poolCreator"),u("vaultA"),u("vaultB"),u("mintLp"),u("mintA"),u("mintB"),u("mintProgramA"),u("mintProgramB"),u("observationId"),l("bump"),l("status"),l("lpDecimals"),l("mintDecimalA"),l("mintDecimalB"),n("lpAmount"),n("protocolFeesMintA"),n("protocolFeesMintB"),n("fundFeesMintA"),n("fundFeesMintB"),n("openTime"),n("epoch"),l("feeOn"),pe("enableCreatorFee"),x(l(),6),n("creatorFeesMintA"),n("creatorFeesMintB"),x(n(),28)]),wh=m([V(8),u("configId"),x(n(),30)]),kh=m([V(8),l("bump"),u("creator"),u("ammConfig"),n("shareRate"),x(n(),8)]);import{PublicKey as MB,SystemProgram as FB}from"@solana/web3.js";import{createTransferInstruction as _B,TOKEN_PROGRAM_ID as VB,TOKEN_2022_PROGRAM_ID as EB,createAssociatedTokenAccountIdempotentInstruction as DB,createSyncNativeInstruction as qB,createTransferCheckedInstruction as UB}from"@solana/spl-token";import va from"bn.js";import XB from"decimal.js";var Ma={[lo.toBase58()]:3};var Fa=m([V(5),V(8),u("ownAddress"),n("vaultSignerNonce"),u("baseMint"),u("quoteMint"),u("baseVault"),n("baseDepositsTotal"),n("baseFeesAccrued"),u("quoteVault"),n("quoteDepositsTotal"),n("quoteFeesAccrued"),n("quoteDustThreshold"),u("requestQueue"),u("eventQueue"),u("bids"),u("asks"),n("baseLotSize"),n("quoteLotSize"),n("feeRateBps"),n("referrerRebatesAccrued"),V(7)]);import{PublicKey as JI}from"@solana/web3.js";var iB=q("Serum");import{ASSOCIATED_TOKEN_PROGRAM_ID as pB,TOKEN_2022_PROGRAM_ID as fB,TOKEN_PROGRAM_ID as yB}from"@solana/spl-token";import{PublicKey as gB,SystemProgram as PB,TransactionInstruction as AB}from"@solana/web3.js";import kB from"bn.js";var TS=new va(0);import{PublicKey as Va,Transaction as Rn,TransactionInstruction as Ea}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Da}from"@solana/spl-token";import Uo from"bn.js";var se=class extends le{static getPdaPoolId(e,t){return Y([se.SEED_CONFIG.pool.id,t.toBuffer()],e)}static getPdaOwnerId(e,t,o,r){return Y([se.SEED_CONFIG.owner.id,t.toBuffer(),o.toBuffer(),Buffer.from(new Uo(r).toArray())],e)}static async getAllInfo({connection:e,programId:t,poolIds:o,wallet:r,chainTime:a}){if(o.length===0)return[];let s=o.map(b=>se.getPdaPoolId(t,b).publicKey),c=[];for(let b=0;b<se.VERSION_PROJECT.length;b++)c.push(...s.map(T=>se.getPdaOwnerId(t,T,r,b).publicKey));let f=await he(e,[...s,...c]),P=[];for(let b=0;b<f.length;b++){let T=Math.floor(b/o.length),B=b%o.length,I=s[B],K=c[b],h=f[B],A=f[o.length+b];if(!(h&&A)||h.data.length!==se.POOL_LAYOUT.span||A.data.length!==se.OWNER_LAYOUT.span)continue;let w=se.POOL_LAYOUT.decode(h.data),k=se.OWNER_LAYOUT.decode(A.data),y=w.openTime.toNumber(),R=w.endTime.toNumber(),g=k.tokenInfo.map(O=>O.debtAmount.gt(new Uo(0))).filter(O=>!O).length!==3,S=a>y&&a<R&&w.status===1,C=g&&S;P.push({programId:t,poolId:I,ammId:w.ammId,ownerAccountId:K,snapshotLpAmount:k.lpAmount,project:se.VERSION_PROJECT[T],openTime:y,endTime:R,canClaim:C,canClaimErrorType:g?S?void 0:"outOfOperationalTime":"alreadyClaimIt",tokenInfo:w.tokenInfo.map((O,N)=>({mintAddress:O.mintAddress,mintVault:O.mintVault,mintDecimals:O.mintDecimals,perLpLoss:O.perLpLoss,debtAmount:k.tokenInfo[N].debtAmount.add(k.tokenInfo[N].claimedAmount)}))})}return P}async makeClaimTransaction({poolInfo:e,ownerInfo:t,feePayer:o}){t.wallet||this.scope.checkOwner();let r=this.createTxBuilder(o),a=t.wallet||this.scope.ownerPubKey,s=[];for(let P of e.tokenInfo){let{account:b,instructionParams:T}=await this.scope.account.getOrCreateTokenAccount({mint:P.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:P.mintAddress.equals(re.WSOL.mint),createInfo:{payer:a,amount:0},skipCloseAccount:!P.mintAddress.equals(re.WSOL.mint),associatedOnly:P.mintAddress.equals(re.WSOL.mint)?!1:t.associatedOnly});T&&r.addInstruction(T),s.push(b)}r.addInstruction({instructions:[se.makeClaimInstruction({programId:e.programId,poolInfo:e,ownerInfo:{wallet:a,ownerPda:e.ownerAccountId,claimAddress:s}})]});let{transaction:c,signers:f}=r.build();return[{transaction:c,signer:f}]}async makeClaimAllTransaction({poolInfos:e,ownerInfo:t,feePayer:o}){let r=this.createTxBuilder(o),a=t.wallet||this.scope.ownerPubKey,s={};for(let b of e){let T=[];for(let B of b.tokenInfo){let{account:I,instructionParams:K}=await this.scope.account.getOrCreateTokenAccount({mint:B.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:B.mintAddress.equals(re.WSOL.mint),createInfo:{payer:a,amount:0},skipCloseAccount:!B.mintAddress.equals(re.WSOL.mint),associatedOnly:B.mintAddress.equals(re.WSOL.mint)?!1:t.associatedOnly});K&&r.addInstruction(K),I&&(s[B.mintAddress.toString()]=I,T.push(I))}r.addInstruction({instructions:[se.makeClaimInstruction({programId:b.programId,poolInfo:b,ownerInfo:{wallet:a,ownerPda:b.ownerAccountId,claimAddress:T}})]})}let{transaction:c,signers:f}=r.build(),P=r.allInstructions;return mn(P,[a,...f.map(b=>b.publicKey)])?[{transaction:c,signer:f}]:[{transaction:new Rn().add(...P.slice(0,r.AllTxData.instructions.length-1)),signer:f},{transaction:new Rn().add(...P.slice(r.AllTxData.instructions.length-1)),signer:[]},{transaction:new Rn().add(...r.AllTxData.endInstructions),signer:[]}]}static makeClaimInstruction({programId:e,poolInfo:t,ownerInfo:o}){let r=m([]),a=[{pubkey:o.wallet,isSigner:!0,isWritable:!0},{pubkey:t.poolId,isSigner:!1,isWritable:!0},{pubkey:o.ownerPda,isSigner:!1,isWritable:!0},...o.claimAddress.map(f=>({pubkey:f,isSigner:!1,isWritable:!0})),...t.tokenInfo.map(({mintVault:f})=>({pubkey:f,isSigner:!1,isWritable:!0})),{pubkey:Da,isSigner:!1,isWritable:!1}],s=Buffer.alloc(r.span);r.encode({},s);let c=Buffer.from([10,66,208,184,161,6,191,98,...s]);return new Ea({keys:a,programId:e,data:c})}},be=se;be.CLAIMED_NUM=3,be.POOL_LAYOUT=m([V(8),l("bump"),l("status"),n("openTime"),n("endTime"),u("ammId"),x(m([l("mintDecimals"),u("mintAddress"),u("mintVault"),n("perLpLoss"),n("totalClaimedAmount")]),se.CLAIMED_NUM,"tokenInfo"),x(n(),10,"padding")]),be.OWNER_LAYOUT=m([V(8),l("bump"),l("version"),u("poolId"),u("owner"),n("lpAmount"),x(m([u("mintAddress"),n("debtAmount"),n("claimedAmount")]),se.CLAIMED_NUM,"tokenInfo"),x(n(),4,"padding")]),be.DEFAULT_POOL_ID=["58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2","6UmmUiYoBjSrhakAobJw8BvkmJtDVxaeBtbt7rxWo1mg","AVs9TA4nWDzfPJE9gGVNJMVhcQy3V9PGazuz33BfG2RA","DVa7Qmb5ct9RCpaU7UTpSaf3GVMYz17vNVU67XpdCRut","7XawhbbxtsRcQA8KTkHT9f9nc6d69UwqCDh6U5EEbEmX","6a1CsrpeZubDjEJE9s1CMVheB6HWM5d7m1cj2jkhyXhj","EoNrn8iUhwgJySD1pHu8Qxm5gSQqLK3za4m8xzD2RuEb","AceAyRTWt4PyB2pHqf2qhDgNZDtKVNaxgL8Ru3V4aN1P","6tmFJbMk5yVHFcFy7X2K8RwHjKLr6KVFLYXpgpBNeAxB"].map(e=>new Va(e)),be.SEED_CONFIG={pool:{id:Buffer.from("pool_seed","utf8")},owner:{id:Buffer.from("user_claim_seed","utf8")}},be.VERSION_PROJECT=[void 0,"Francium","Tulip","Larix"];var Go=(y=>(y[y.CurveType=0]="CurveType",y[y.MigrateType=1]="MigrateType",y[y.MigrateCpmmFeeOn=2]="MigrateCpmmFeeOn",y[y.Supply=3]="Supply",y[y.TotalSellA=4]="TotalSellA",y[y.TotalFundRaisingB=5]="TotalFundRaisingB",y[y.TotalLockedAmount=6]="TotalLockedAmount",y[y.CliffPeriod=7]="CliffPeriod",y[y.UnlockPeriod=8]="UnlockPeriod",y[y.BaseTokenProgram=9]="BaseTokenProgram",y[y.TransferFeeEnabled=10]="TransferFeeEnabled",y[y.TransferFeeBasisPoints=11]="TransferFeeBasisPoints",y[y.TransferFeeMaximumFee=12]="TransferFeeMaximumFee",y[y.SellRateA=13]="SellRateA",y[y.LockRate=14]="LockRate",y[y.MigrateAmountA=15]="MigrateAmountA",y[y.MigrateRateA=16]="MigrateRateA",y[y.FundRaisingRateB=17]="FundRaisingRateB",y[y.UnixTimestamp=18]="UnixTimestamp",y))(Go||{}),zo=[4,13,15,16],Xo=(r=>(r[r.Eq=0]="Eq",r[r.Gte=1]="Gte",r[r.Lte=2]="Lte",r[r.Neq=3]="Neq",r))(Xo||{}),Wa=(t=>(t[t.SplToken=0]="SplToken",t[t.Token2022=1]="Token2022",t))(Wa||{}),Ln=10,On=25,Yo=(t=>(t[t.OnlyTokenB=0]="OnlyTokenB",t[t.BothToken=1]="BothToken",t))(Yo||{});var qa=Buffer.from("vault_auth_seed","utf8"),Ua=Buffer.from("global_config","utf8"),Ga=Buffer.from("pool_vesting","utf8"),za=Buffer.from("platform_config","utf8"),Xa=Buffer.from("platform_fee_vault_auth_seed","utf8"),Ya=Buffer.from("creator_fee_vault_auth_seed","utf8"),Ha=Buffer.from("platform_global_access","utf8"),Qa=Buffer.from("platform_allow_config","utf8"),Za=Buffer.from("platform_curve_rule","utf8");function _o(i){return Y([qa],i)}function $a(i,e,t,o){return Y([Ua,e.toBuffer(),es(t),hn(o)],i)}function ja(i,e,t){return Y([ko,e.toBuffer(),t.toBuffer()],i)}function Ja(i,e,t){return Y([To,e.toBuffer(),t.toBuffer()],i)}function Se(i){return Y([Buffer.from("__event_authority","utf8")],i)}function es(i){let e=new ArrayBuffer(1);return new DataView(e).setUint8(0,i),new Uint8Array(e)}function ts(i,e){return Y([za,e.toBuffer()],i)}function ns(i,e,t){return Y([Ga,e.toBuffer(),t.toBuffer()],i)}function Vo(i,e,t){return Y([e.toBuffer(),t.toBuffer()],i)}function os(i){return Y([Xa],i)}function Eo(i,e,t){return Y([e.toBuffer(),t.toBuffer()],i)}function is(i){return Y([Ya],i)}function WS(i,e,t){return Y([Ha,e.toBuffer(),t.toBuffer()],i)}function rs(i,e,t){return Y([Qa,e.toBuffer(),t.toBuffer()],i)}function as(i,e,t){return Y([Za,e.toBuffer(),t.toBuffer()],i)}import{NATIVE_MINT as ux,TOKEN_2022_PROGRAM_ID as cx,TOKEN_PROGRAM_ID as lx,createAssociatedTokenAccountIdempotentInstruction as dx,createSyncNativeInstruction as px,getTransferFeeConfig as fx,unpackMint as yx}from"@solana/spl-token";import J from"bn.js";import{PublicKey as gs,SystemProgram as Px}from"@solana/web3.js";var ss=m([n(),n("epoch"),l("curveType"),X("index"),n("migrateFee"),n("tradeFeeRate"),n("maxShareFeeRate"),n("minSupplyA"),n("maxLockRate"),n("minSellRateA"),n("minMigrateRateA"),n("minFundRaisingB"),u("mintB"),u("protocolFeeOwner"),u("migrateFeeOwner"),u("migrateToAmmWallet"),u("migrateToCpmmWallet"),x(n(),16)]),us=m([n("totalLockedAmount"),n("cliffPeriod"),n("unlockPeriod"),n("startTime"),n("totalAllocatedShare")]),cs=m([n(),n("epoch"),l("bump"),l("status"),l("mintDecimalsA"),l("mintDecimalsB"),l("migrateType"),n("supply"),n("totalSellA"),n("virtualA"),n("virtualB"),n("realA"),n("realB"),n("totalFundRaisingB"),n("protocolFee"),n("platformFee"),n("migrateFee"),us.replicate("vestingSchedule"),u("configId"),u("platformId"),u("mintA"),u("mintB"),u("vaultA"),u("vaultB"),u("creator"),l("mintProgramFlag"),l("cpmmCreatorFeeOn"),n("platformVestingShare"),x(l(),54)]),GS=m([n(),n("epoch"),u("poolId"),u("beneficiary"),n("claimedAmount"),n("tokenShareAmount"),x(n(),8)]),ls=m([l("migrateType"),l("migrateCpmmFeeOn"),n("supply"),n("totalSellA"),n("totalFundRaisingB"),n("totalLockedAmount"),n("cliffPeriod"),n("unlockPeriod")]),zS=m([n("epoch"),l("index"),u("configId"),ls.replicate("bondingCurveParam"),x(n(),50)]),Do=m([n(),n("epoch"),u("platformClaimFeeWallet"),u("platformLockNftWallet"),n("platformScale"),n("creatorScale"),n("burnScale"),n("feeRate"),x(l(),64,"name"),x(l(),256,"web"),x(l(),256,"img"),u("cpConfigId"),n("creatorFeeRate"),u("transferFeeExtensionAuth"),u("platformVestingWallet"),n("platformVestingScale"),u("platformCpCreator"),l("restrictGlobalConfig"),l("restrictCurveParam"),u("curveRuleManager"),x(l(),78)]),ms=m([l("field"),l("op"),v("value")]),ds=m([X("groupId"),n("epoch"),Pn(ms,"constraints")]),ps=m([n(),l("bump"),l("version"),u("platformId"),u("configId"),n("epoch"),x(n(),8),Pn(ds,"groups")]);import de from"bn.js";import Ho from"decimal.js";import zt from"bn.js";import kt from"decimal.js";var Ke=class{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:o}){throw Error()}static getPoolInitPriceByInit({a:e,b:t,decimalA:o,decimalB:r}){throw Error()}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:o}){throw Error()}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:o,totalFundRaising:r,migrateFee:a,decimalA:s,decimalB:c}){throw Error()}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:o}){throw Error()}static getInitParam({supply:e,totalFundRaising:t,totalSell:o,totalLockedAmount:r,migrateFee:a}){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 Xt=class extends Ke{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:o}){return new kt(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-o))}static getPoolInitPriceByInit({a:e,b:t,decimalA:o,decimalB:r}){return new kt(t.toString()).div(e.toString()).mul(10**(o-r))}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:o}){return new kt(e.virtualB.add(e.realB).toString()).div(e.virtualA.sub(e.realA).toString()).mul(10**(t-o))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:o,totalFundRaising:r,migrateFee:a,decimalA:s,decimalB:c}){return new kt(r.sub(a).toString()).div(e.sub(t).sub(o).toString()).mul(10**(s-c))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:o}){let r=e.totalSellA.sub(e.realA),a=e.totalFundRaisingB.sub(e.realB);return new kt(e.virtualB.add(e.realB.add(a)).toString()).div(e.virtualA.sub(e.realA.add(r)).toString()).mul(10**(t-o))}static getInitParam({supply:e,totalFundRaising:t,totalSell:o,totalLockedAmount:r,migrateFee:a}){if(e.lte(o))throw Error("supply need gt total sell");let s=e.sub(o).sub(r);if(s.lte(new zt(0)))throw Error("supplyMinusSellLocked <= 0");let c=t.sub(a);if(c.lte(new zt(0)))throw Error("tfMinusMf <= 0");let f=c.mul(o).mul(o).div(s),P=c.mul(o).div(s).sub(t),b=f.div(P),T=t.mul(t).div(P);if(b.lt(new zt(0))||T.lt(new zt(0)))throw Error("invalid input 0");return{a:b,b:T,c:o}}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:o}){let r=e.mul(o),a=t.add(e);return r.div(a)}static getAmountIn({amountOut:e,inputReserve:t,outputReserve:o}){let r=t.mul(e),a=o.sub(e);return _e(r,a)}};import Yt from"bn.js";import Tt from"decimal.js";var Ht=class extends Ke{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:o}){return new Tt(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-o))}static getPoolInitPriceByInit({a:e,b:t,decimalA:o,decimalB:r}){return new Tt(t.toString()).div(e.toString()).mul(10**(o-r))}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:o}){return new Tt(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-o))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:o,totalFundRaising:r,migrateFee:a,decimalA:s,decimalB:c}){return new Tt(r.sub(a).toString()).div(e.sub(t).sub(o).toString()).mul(10**(s-c))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:o}){let r=e.totalSellA.sub(e.realA),a=e.totalFundRaisingB.sub(e.realB);return new Tt(e.virtualB.add(e.realB).add(a).toString()).div(e.virtualA.sub(e.realA).add(r).toString()).mul(10**(t-o))}static getInitParam({supply:e,totalFundRaising:t,totalSell:o,totalLockedAmount:r,migrateFee:a}){let s=e.sub(r);if(s.lte(new Yt(0)))throw Error("invalid input 1");let c=new Yt(2).mul(t).sub(a),P=t.mul(s).div(c);if(P.lt(new Yt(0))||t.lt(new Yt(0)))throw Error("invalid input 0");return{a:P,b:t,c:P}}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:o}){return o.mul(e).div(t)}static getAmountIn({amountOut:e,initInput:t,initOutput:o}){let r=t.mul(e);return _e(r,o)}};import me from"bn.js";import Ve from"decimal.js";import nt from"bn.js";import Qt from"decimal.js";var ht=class{static _multipler(e){return new Qt(10).pow(e)}static getPrice({priceX64:e,decimalA:t,decimalB:o}){return new Qt(e.toString()).div(this._Q64).mul(this._multipler(t)).div(this._multipler(o))}static getPriceX64({price:e,decimalA:t,decimalB:o}){let r=e.mul(this._multipler(o)).div(this._multipler(t));return new nt(r.mul(this._Q64).toFixed(0))}};ht._Q64=new Qt(new nt(1).shln(64).toString());function uK({supply:i,totalFundRaisingB:e,totalLockedAmount:t,totalSellA:o,migrateType:r,decimalsA:a}){let s=i.sub(o).sub(t),c=new nt(new Qt(s.mul(e).toString()).sqrt().toFixed(0));if(r==="amm"){if(c.gt(new nt(10).pow(new nt(a))))return!0}else if(r==="cpmm"){if(c.gt(new nt(100)))return!0}else throw Error("migrate type error");return!1}var Zt=class extends Ke{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:o}){return new Ve(0)}static getPoolInitPriceByInit({a:e,b:t,decimalA:o,decimalB:r}){return new Ve(0)}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:o}){return new Ve(e.virtualA.mul(e.realA).toString()).div(ht._Q64).mul(10**(t-o))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:o,totalFundRaising:r,migrateFee:a,decimalA:s,decimalB:c}){return new Ve(r.sub(a).toString()).div(e.sub(t).sub(o).toString()).mul(10**(s-c))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:o}){let r=e.totalSellA.sub(e.realA),a=e.totalFundRaisingB.sub(e.realB);return new Ve(e.virtualB.add(e.realB).add(a).toString()).div(e.virtualA.sub(e.realA).add(r).toString()).mul(10**(t-o))}static getInitParam({supply:e,totalFundRaising:t,totalSell:o,totalLockedAmount:r,migrateFee:a}){let s=e.sub(r);if(s.lte(new me(0)))throw Error("supplyMinusLocked need gt 0");let c=t.mul(new me(3)).sub(a),P=t.mul(new me(2)).mul(s).div(c),b=P.mul(P),T=t.mul(new me(2)).mul(ye).div(b);if(!T.gt(new me(0)))throw Error("a need gt 0");if(!Vt.gt(T))throw Error("a need lt u64 max");if(T.lt(new me(0))||P.lt(new me(0)))throw Error("invalid input 0");return{a:T,b:new me(0),c:P}}static buyExactIn({poolInfo:e,amount:t}){let o=e.realB.add(t),r=new me(2).mul(o).mul(ye).div(e.virtualA);return new me(new Ve(r.toString()).sqrt().toFixed(0)).sub(e.realA)}static buyExactOut({poolInfo:e,amount:t}){let o=e.realA.add(t),r=o.mul(o);return _e(e.virtualA.mul(r),new me(2).mul(ye)).sub(e.realB)}static sellExactIn({poolInfo:e,amount:t}){let o=e.realA.sub(t),r=o.mul(o),a=_e(e.virtualA.mul(r),new me(2).mul(ye));return e.realB.sub(a)}static sellExactOut({poolInfo:e,amount:t}){let o=e.realB.sub(t),r=new me(2).mul(o).mul(ye).div(e.virtualA),a=new me(new Ve(r.toString()).sqrt().toFixed(0));return e.realA.sub(a)}};var tt=class{static getPoolCurvePointByPoolInfo({curveType:e,pointCount:t,poolInfo:o}){return this.getPoolCurvePointByInit({curveType:e,pointCount:t,supply:o.supply,totalFundRaising:o.totalFundRaisingB,totalSell:o.totalSellA,totalLockedAmount:o.vestingSchedule.totalLockedAmount,migrateFee:o.migrateFee,decimalA:o.mintDecimalsA,decimalB:o.mintDecimalsB})}static getPoolCurvePointByInit({curveType:e,pointCount:t,supply:o,totalFundRaising:r,totalSell:a,totalLockedAmount:s,migrateFee:c,decimalA:f,decimalB:P}){if(t<3)throw Error("point count < 3");let b=this.getCurve(e),T=b.getInitParam({supply:o,totalFundRaising:r,totalSell:a,totalLockedAmount:s,migrateFee:c}),B=b.getPoolInitPriceByInit(_(L({},T),{decimalA:f,decimalB:P})),I=r.div(new de(t-1)),K=new de(0),h=[{price:B,totalSellSupply:0}],{a:A,b:w}=T,k=K,y=K;for(let R=1;R<t;R++){let g=R!==t-1?I:r.sub(y),S=this.buyExactIn({poolInfo:{virtualA:A,virtualB:w,realA:k,realB:y,totalFundRaisingB:r,totalSellA:a},amountB:g,protocolFeeRate:K,platformFeeRate:K,curveType:e,shareFeeRate:K,creatorFeeRate:K,transferFeeConfigA:void 0,transferFeeConfigB:void 0,slot:0});k=k.add(S.amountA.amount),y=y.add(S.amountB);let C=this.getPrice({poolInfo:{virtualA:A,virtualB:w,realA:k,realB:y},decimalA:f,decimalB:P,curveType:e});h.push({price:C,totalSellSupply:new Ho(k.toString()).div(10**f).toNumber()})}return h}static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:o,curveType:r}){return this.getCurve(r).getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:o})}static getPoolInitPriceByInit({a:e,b:t,decimalA:o,decimalB:r,curveType:a}){return this.getCurve(a).getPoolInitPriceByInit({a:e,b:t,decimalA:o,decimalB:r})}static getPrice({poolInfo:e,curveType:t,decimalA:o,decimalB:r}){return this.getCurve(t).getPoolPrice({poolInfo:e,decimalA:o,decimalB:r})}static getEndPrice({poolInfo:e,curveType:t,decimalA:o,decimalB:r}){return this.getCurve(t).getPoolPrice({poolInfo:e,decimalA:o,decimalB:r})}static getPoolEndPriceReal({poolInfo:e,curveType:t,decimalA:o,decimalB:r}){return this.getCurve(t).getPoolEndPriceReal({poolInfo:e,decimalA:o,decimalB:r})}static checkParam({supply:e,totalFundRaising:t,totalSell:o,totalLockedAmount:r,decimals:a,config:s,migrateType:c}){if(Number(a)!==6)throw Error("decimals = 6");if(e.mul(s.maxLockRate).div(we).lt(r))throw Error("total lock amount gte max lock amount");if(e.lt(s.minSupplyA.mul(new de(10**a))))throw Error("supply lt min supply");let P=e.mul(s.minSellRateA).div(we);if(o.lt(P))throw Error("invalid input");if(t.lt(s.minFundRaisingB))throw Error("total fund raising lt min fund raising");let b=e.sub(o).sub(r),T=e.mul(s.minMigrateRateA).div(we);if(b.lt(T))throw Error("migrate lt min migrate amoount");let B=e.sub(o).sub(r),I=new de(new Ho(B.mul(t).toString()).sqrt().toFixed(0));if(c==="amm"){let K=new de(10).pow(new de(a));if(I.lte(K))throw Error("check migrate lp error")}else if(c==="cpmm"){let K=new de(100);if(I.lte(K))throw Error("check migrate lp error")}else throw Error("migrate type error")}static buyExactIn({poolInfo:e,amountB:t,protocolFeeRate:o,platformFeeRate:r,curveType:a,shareFeeRate:s,creatorFeeRate:c,transferFeeConfigA:f,transferFeeConfigB:P,slot:b}){var O;let T=wt(t,P,b),B=t.sub((O=T.fee)!=null?O:new de(0)),I=this.totalFeeRate({protocolFeeRate:o,platformFeeRate:r,shareFeeRate:s,creatorFeeRate:c}),K=this.calculateFee({amount:B,feeRate:I}),h=B.sub(K),A=this.getCurve(a),w=A.buyExactIn({poolInfo:e,amount:h}),k=e.totalSellA.sub(e.realA),y,R,g,S;if(w.gt(k)){y=k;let N=A.buyExactOut({poolInfo:e,amount:y}),F=this.calculatePreFee({postFeeAmount:N,feeRate:I});g=F.sub(N);let G=et(F,P,b);R=G.amount,S=G.fee}else y=w,R=t,g=K,S=T.fee;let C=this.splitFee({totalFee:g,protocolFeeRate:o,platformFeeRate:r,shareFeeRate:s,creatorFeeRate:c});return{amountA:wt(y,f,b),amountB:R,splitFee:C,transferFeeB:S}}static buyExactOut({poolInfo:e,amountA:t,protocolFeeRate:o,platformFeeRate:r,curveType:a,shareFeeRate:s,creatorFeeRate:c,transferFeeConfigA:f,transferFeeConfigB:P,slot:b}){let T=e.totalSellA.sub(e.realA),B=et(t,f,b),I=B.fee?B.amount.add(B.fee):B.amount;t.gt(T)&&(I=T);let h=this.getCurve(a).buyExactOut({poolInfo:e,amount:I}),A=this.totalFeeRate({protocolFeeRate:o,platformFeeRate:r,shareFeeRate:s,creatorFeeRate:c}),w=this.calculatePreFee({postFeeAmount:h,feeRate:A}),k=w.sub(h),y=et(w,P,b),R=this.splitFee({totalFee:k,protocolFeeRate:o,platformFeeRate:r,shareFeeRate:s,creatorFeeRate:c});return{amountA:B,amountB:y.amount,splitFee:R,transferFeeB:y.fee}}static sellExactIn({poolInfo:e,amountA:t,protocolFeeRate:o,platformFeeRate:r,curveType:a,shareFeeRate:s,creatorFeeRate:c,transferFeeConfigA:f,transferFeeConfigB:P,slot:b}){var y;let T=this.getCurve(a),B=wt(t,f,b),I=B.fee?B.amount.sub(B.fee):B.amount,K=T.sellExactIn({poolInfo:e,amount:I}),h=this.calculateFee({amount:K,feeRate:this.totalFeeRate({protocolFeeRate:o,platformFeeRate:r,shareFeeRate:s,creatorFeeRate:c})}),A=this.splitFee({totalFee:h,protocolFeeRate:o,platformFeeRate:r,shareFeeRate:s,creatorFeeRate:c}),w=K.sub(h),k=wt(w,P,b);return{amountA:B,amountB:w.sub((y=k.fee)!=null?y:new de(0)),splitFee:A,transferFeeB:k.fee}}static sellExactOut({poolInfo:e,amountB:t,protocolFeeRate:o,platformFeeRate:r,curveType:a,shareFeeRate:s,creatorFeeRate:c,transferFeeConfigA:f,transferFeeConfigB:P,slot:b}){let T=this.totalFeeRate({protocolFeeRate:o,platformFeeRate:r,shareFeeRate:s,creatorFeeRate:c}),B=et(t,P,b),I=B.amount,K=this.calculatePreFee({postFeeAmount:I,feeRate:T});if(e.realB.lt(K))throw Error("Insufficient liquidity");let h=K.sub(I),w=tt.getCurve(a).sellExactOut({poolInfo:e,amount:K});if(w.gt(e.realA))throw Error();let k=this.splitFee({totalFee:h,protocolFeeRate:o,platformFeeRate:r,shareFeeRate:s,creatorFeeRate:c});return{amountA:et(w,f,b),amountB:t,splitFee:k,transferFeeB:B.fee}}static splitFee({totalFee:e,protocolFeeRate:t,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a}){let s=this.totalFeeRate({protocolFeeRate:t,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a}),c=s.isZero()?new de(0):e.mul(o).div(s),f=s.isZero()?new de(0):e.mul(r).div(s),P=s.isZero()?new de(0):e.mul(a).div(s),b=e.sub(c).sub(f).sub(P);return{platformFee:c,shareFee:f,protocolFee:b,creatorFee:P}}static calculateFee({amount:e,feeRate:t}){return Cn(e,t,we)}static calculatePreFee({postFeeAmount:e,feeRate:t}){if(t.isZero())return e;let o=e.mul(we),r=we.sub(t);return o.add(r).sub(new de(1)).div(r)}static totalFeeRate({protocolFeeRate:e,platformFeeRate:t,shareFeeRate:o,creatorFeeRate:r}){if(e.add(t).add(o).add(r).gt(new de(1e6)))throw Error("total fee rate gt 1_000_000");return e.add(t).add(o).add(r)}static getCurve(e){switch(e){case 0:return Xt;case 1:return Ht;case 2:return Zt}throw Error("find curve error")}};import{TOKEN_2022_PROGRAM_ID as Nn,TOKEN_PROGRAM_ID as fs}from"@solana/spl-token";var ys=(t=>(t[t.MintA=0]="MintA",t[t.MintB=1]="MintB",t))(ys||{});function Qo(i,e){return i>>e&1?Nn:fs}function _a(i){return Qo(i,0)}function KK(i){return Qo(i,1)}function bs({mintAProgram:i,mintBProgram:e}){return(i.equals(Nn)?1<<0:0)|(e.equals(Nn)?1<<1:0)}import Bx from"decimal.js";var Sx={initPriceX64:new J("515752397214619"),supply:new J(1e15),totalSellA:new J(7931e11),totalFundRaisingB:new J(85e9),totalFundRaisingBUSD:new J(125e8),totalLockedAmount:new J("0"),cliffPeriod:new J("0"),unlockPeriod:new J("0"),decimals:6,virtualA:new J("1073471847374405"),virtualB:new J("30050573465"),realA:new J(0),realB:new J(0),protocolFee:new J(0),platformId:new gs("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),vestingSchedule:{totalLockedAmount:new J(0),cliffPeriod:new J(0),unlockPeriod:new J(0),startTime:new J(0),totalAllocatedShare:new J(0)}},Kx=new J(1e4),xx=new Set(["USDCoctVLVnvTXBEuP9s8hntucdJokbo17RwHuNXemT","USD1ttGY1N17NEEHLmELoaybftRBUSErhqYiQzvEmuB"]);import{PublicKey as Ox}from"@solana/web3.js";import{getTransferFeeConfig as Mx,MintLayout as Fx,TOKEN_2022_PROGRAM_ID as vx,TOKEN_PROGRAM_ID as _x,unpackMint as Vx}from"@solana/spl-token";var dR=new xe(2),pR=new xe(3),fR=new xe(5),di=new xe(10),yR=new xe(100),bR=new xe(1e3),gR=new xe(1e4);function Cn(i,e,t){return i.mul(e).add(t).sub(new xe(1)).div(t)}function en(i,e=1,t=[]){let o=[...i];if(e<=0)return t;for(;o.length;)t.push(o.splice(0,e));return t}import{ASSOCIATED_TOKEN_PROGRAM_ID as $t,TOKEN_2022_PROGRAM_ID as vs,TOKEN_PROGRAM_ID as Mn}from"@solana/spl-token";import{SystemProgram as oe,TransactionInstruction as $}from"@solana/web3.js";import ot from"bn.js";var j={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 YR(i,e,t,o,r,a,s,c,f,P,b,T,B,I,K,h,A,w,k,y){throw new Error("*** launchlab initialize has been deprecated, please use initializeV2 instead! ***")}function Ps(i,e,t,o,r,a,s,c,f,P,b,T,B,I,K,h,A,w,k,y,R,g,S,C){let O=m([l("decimals"),ie("name"),ie("symbol"),ie("uri")]),N=m([n("totalLockedAmount"),n("cliffPeriod"),n("unlockPeriod"),l("cpmmCreatorFeeOn")]),F=m([l("index"),n("supply"),n("totalFundRaisingB"),l("migrateType")]),G=m([l("index"),n("supply"),n("totalSellA"),n("totalFundRaisingB"),l("migrateType")]),W=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!0,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:P,isSigner:!1,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!0},{pubkey:T,isSigner:!1,isWritable:!0},{pubkey:Mn,isSigner:!1,isWritable:!1},{pubkey:B,isSigner:!1,isWritable:!1},{pubkey:We,isSigner:!1,isWritable:!1},{pubkey:oe.programId,isSigner:!1,isWritable:!1},{pubkey:Oe,isSigner:!1,isWritable:!1},{pubkey:Se(i).publicKey,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1}];S&&W.push({pubkey:S,isSigner:!1,isWritable:!1}),C&&W.push({pubkey:C,isSigner:!1,isWritable:!1});let E=Buffer.alloc(Buffer.from(K,"utf-8").length+Buffer.from(h,"utf-8").length+Buffer.from(A,"utf-8").length+4*3+1),H=Buffer.alloc(N.span),D=Buffer.alloc(w.type==="ConstantCurve"?G.span:F.span);return O.encode({decimals:I,name:K,symbol:h,uri:A},E),w.type==="ConstantCurve"?G.encode(_(L({index:0},w),{migrateType:w.migrateType==="amm"?0:1}),D):w.type==="FixedCurve"?F.encode(_(L({index:1},w),{migrateType:w.migrateType==="amm"?0:1}),D):w.type==="LinearCurve"&&F.encode(_(L({index:2},w),{migrateType:w.migrateType==="amm"?0:1}),D),N.encode({totalLockedAmount:k,cliffPeriod:y,unlockPeriod:R,cpmmCreatorFeeOn:g},H),new $({keys:W,programId:i,data:Buffer.from([...j.initializeV2,...E,...D,...H])})}function As(i,e,t,o,r,a,s,c,f,P,b,T,B,I,K,h,A,w,k,y,R,g,S,C){let O=m([l("decimals"),ie("name"),ie("symbol"),ie("uri")]),N=m([n("totalLockedAmount"),n("cliffPeriod"),n("unlockPeriod"),l("cpmmCreatorFeeOn"),l("transferFeeExtensionParamsOption"),m([X("transferFeeBasePoints"),n("maxinumFee")]).replicate("transferFeeExtensionParams")]),F=m([l("index"),n("supply"),n("totalFundRaisingB"),l("migrateType")]),G=m([l("index"),n("supply"),n("totalSellA"),n("totalFundRaisingB"),l("migrateType")]),W=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!0,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:P,isSigner:!1,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!0},{pubkey:vs,isSigner:!1,isWritable:!1},{pubkey:T,isSigner:!1,isWritable:!1},{pubkey:oe.programId,isSigner:!1,isWritable:!1},{pubkey:Se(i).publicKey,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1}];S&&W.push({pubkey:S,isSigner:!1,isWritable:!1}),C&&W.push({pubkey:C,isSigner:!1,isWritable:!1});let E=Buffer.alloc(Buffer.from(I,"utf-8").length+Buffer.from(K,"utf-8").length+Buffer.from(h,"utf-8").length+4*3+1),H=Buffer.alloc(N.span),D=Buffer.alloc(A.type==="ConstantCurve"?G.span:F.span);return O.encode({decimals:B,name:I,symbol:K,uri:h},E),A.type==="ConstantCurve"?G.encode(_(L({index:0},A),{migrateType:A.migrateType==="amm"?0:1}),D):A.type==="FixedCurve"?F.encode(_(L({index:1},A),{migrateType:A.migrateType==="amm"?0:1}),D):A.type==="LinearCurve"&&F.encode(_(L({index:2},A),{migrateType:A.migrateType==="amm"?0:1}),D),N.encode({totalLockedAmount:w,cliffPeriod:k,unlockPeriod:y,cpmmCreatorFeeOn:R,transferFeeExtensionParamsOption:g?1:0,transferFeeExtensionParams:g!=null?g:{transferFeeBasePoints:0,maxinumFee:new ot(0)}},H),new $({keys:W,programId:i,data:Buffer.from([...j.initializeWithToken2022,...E,...D,...H])})}function Wo(i,e,t,o,r,a,s,c,f,P,b,T,B,I,K,h,A,w,k,y){let R=m([n("amountB"),n("minAmountA"),n("shareFeeRate")]),g=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:P,isSigner:!1,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:T,isSigner:!1,isWritable:!1},{pubkey:B,isSigner:!1,isWritable:!1},{pubkey:I,isSigner:!1,isWritable:!1},{pubkey:Se(i).publicKey,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1}];y&&g.push({pubkey:y,isSigner:!1,isWritable:!0}),g.push({pubkey:oe.programId,isSigner:!1,isWritable:!1}),g.push({pubkey:K,isSigner:!1,isWritable:!0}),g.push({pubkey:h,isSigner:!1,isWritable:!0});let S=Buffer.alloc(R.span);return R.encode({amountB:A,minAmountA:w,shareFeeRate:k!=null?k:new ot(0)},S),new $({keys:g,programId:i,data:Buffer.from([...j.buyExactIn,...S])})}function ws(i,e,t,o,r,a,s,c,f,P,b,T,B,I,K,h,A,w,k,y){let R=m([n("amountA"),n("maxAmountB"),n("shareFeeRate")]),g=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:P,isSigner:!1,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:T,isSigner:!1,isWritable:!1},{pubkey:B,isSigner:!1,isWritable:!1},{pubkey:I,isSigner:!1,isWritable:!1},{pubkey:Se(i).publicKey,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1}];y&&g.push({pubkey:y,isSigner:!1,isWritable:!0}),g.push({pubkey:oe.programId,isSigner:!1,isWritable:!1}),g.push({pubkey:K,isSigner:!1,isWritable:!0}),g.push({pubkey:h,isSigner:!1,isWritable:!0});let S=Buffer.alloc(R.span);return R.encode({amountA:A,maxAmountB:w,shareFeeRate:k!=null?k:new ot(0)},S),new $({keys:g,programId:i,data:Buffer.from([...j.buyExactOut,...S])})}function qo(i,e,t,o,r,a,s,c,f,P,b,T,B,I,K,h,A,w,k,y){let R=m([n("amountA"),n("minAmountB"),n("shareFeeRate")]),g=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:P,isSigner:!1,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:T,isSigner:!1,isWritable:!1},{pubkey:B,isSigner:!1,isWritable:!1},{pubkey:I,isSigner:!1,isWritable:!1},{pubkey:Se(i).publicKey,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1}];y&&g.push({pubkey:y,isSigner:!1,isWritable:!0}),g.push({pubkey:oe.programId,isSigner:!1,isWritable:!1}),g.push({pubkey:K,isSigner:!1,isWritable:!0}),g.push({pubkey:h,isSigner:!1,isWritable:!0});let S=Buffer.alloc(R.span);return R.encode({amountA:A,minAmountB:w,shareFeeRate:k!=null?k:new ot(0)},S),new $({keys:g,programId:i,data:Buffer.from([...j.sellExactIn,...S])})}function ks(i,e,t,o,r,a,s,c,f,P,b,T,B,I,K,h,A,w,k,y){let R=m([n("amountB"),n("maxAmountA"),n("shareFeeRate")]),g=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:P,isSigner:!1,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:T,isSigner:!1,isWritable:!1},{pubkey:B,isSigner:!1,isWritable:!1},{pubkey:I,isSigner:!1,isWritable:!1},{pubkey:Se(i).publicKey,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1}];y&&g.push({pubkey:y,isSigner:!1,isWritable:!0}),g.push({pubkey:oe.programId,isSigner:!1,isWritable:!1}),g.push({pubkey:K,isSigner:!1,isWritable:!0}),g.push({pubkey:h,isSigner:!1,isWritable:!0});let S=Buffer.alloc(R.span);return R.encode({amountB:A,maxAmountA:w,shareFeeRate:k!=null?k:new ot(0)},S),new $({keys:g,programId:i,data:Buffer.from([...j.sellExactOut,...S])})}function Ts(i,e,t,o,r,a,s,c,f){let P=m([]),b=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:oe.programId,isSigner:!1,isWritable:!1},{pubkey:$t,isSigner:!1,isWritable:!1}],T=Buffer.alloc(P.span);return P.encode({},T),new $({keys:b,programId:i,data:Buffer.from([...j.claimVestedToken,...T])})}function hs(i,e,t,o,r,a){let s=m([n("shareAmount")]),c=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:oe.programId,isSigner:!1,isWritable:!1}],f=Buffer.alloc(s.span);return s.encode({shareAmount:a},f),new $({keys:c,programId:i,data:Buffer.from([...j.createVestingAccount,...f])})}function Is(i,e,t,o,r,a,s,c,f){let P=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:oe.programId,isSigner:!1,isWritable:!0},{pubkey:$t,isSigner:!1,isWritable:!0}];return new $({keys:P,programId:i,data:j.claimPlatformFee})}function Bs(i,e,t,o,r,a,s,c,f,P,b,T,B,I,K){let h=m([n("platformScale"),n("creatorScale"),n("burnScale"),n("feeRate"),ie("name"),ie("web"),ie("img"),n("creatorFeeRate"),n("platformVestingScale")]),A=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:oe.programId,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1}],w=Buffer.alloc(8*6+Buffer.from(T,"utf-8").length+Buffer.from(B,"utf-8").length+Buffer.from(I,"utf-8").length+4*3);return h.encode({platformScale:f.platformScale,creatorScale:f.creatorScale,burnScale:f.burnScale,feeRate:P,name:T,web:B,img:I,creatorFeeRate:b,platformVestingScale:K},w),new $({keys:A,programId:i,data:Buffer.from([...j.createPlatformConfig,...w])})}function Ss(i,e,t,o){let r=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0}],a;if(o.type==="updateClaimFeeWallet"){let s=m([l("index"),u("value")]);a=Buffer.alloc(s.span),s.encode({index:0,value:o.value},a)}else if(o.type==="updateLockNftWallet"){let s=m([l("index"),u("value")]);a=Buffer.alloc(s.span),s.encode({index:1,value:o.value},a)}else if(o.type==="migrateCpLockNftScale"){let s=m([l("index"),n("platformScale"),n("creatorScale"),n("burnScale")]);a=Buffer.alloc(s.span),s.encode(L({index:2},o.value),a)}else if(o.type==="updateFeeRate"){let s=m([l("index"),n("value")]);a=Buffer.alloc(s.span),s.encode({index:3,value:o.value},a)}else if(o.type==="updateImg"||o.type==="updateName"||o.type==="updateWeb"){let s=m([l("index"),ie("value")]);a=Buffer.alloc(Buffer.from(o.value,"utf-8").length+4+1*1),o.type==="updateName"?s.encode({index:4,value:o.value},a):o.type==="updateWeb"?s.encode({index:5,value:o.value},a):o.type==="updateImg"&&s.encode({index:6,value:o.value},a)}else if(o.type==="updateCpConfigId"){r.push({pubkey:o.value,isSigner:!1,isWritable:!1});let s=m([l("index")]);a=Buffer.alloc(s.span),s.encode({index:7},a)}else if(o.type==="updateAll"){r.push({pubkey:o.value.cpConfigId,isSigner:!1,isWritable:!1});let s=m([l("index"),u("platformClaimFeeWallet"),u("platformLockNftWallet"),n("platformScale"),n("creatorScale"),n("burnScale"),n("feeRate"),ie("name"),ie("web"),ie("img"),u("transferFeeExtensionAuth"),n("creatorFeeRate"),n("platformVestingScale"),u("platformVestingWallet")]);a=Buffer.alloc(1+32+32+32+8*5+4*3+Buffer.from(o.value.name,"utf-8").length+Buffer.from(o.value.web,"utf-8").length+Buffer.from(o.value.img,"utf-8").length+32+8),s.encode({index:8,platformClaimFeeWallet:o.value.platformClaimFeeWallet,platformLockNftWallet:o.value.platformLockNftWallet,platformVestingWallet:o.value.platformVestingWallet,platformScale:o.value.migrateCpLockNftScale.platformScale,creatorScale:o.value.migrateCpLockNftScale.creatorScale,burnScale:o.value.migrateCpLockNftScale.burnScale,feeRate:o.value.feeRate,name:o.value.name,web:o.value.web,img:o.value.img,transferFeeExtensionAuth:o.value.transferFeeExtensionAuth,creatorFeeRate:o.value.creatorFeeRate,platformVestingScale:o.value.platformVestingScale},a)}else if(o.type==="updateVestingWallet"){let s=m([l("index"),u("value")]);a=Buffer.alloc(s.span),s.encode({index:9,value:o.value},a)}else if(o.type==="updatePlatformVestingScale"){let s=m([l("index"),n("value")]);a=Buffer.alloc(s.span),s.encode({index:10,value:o.value},a)}else if(o.type==="updatePlatformCpCreator"){let s=m([l("index"),u("value")]);a=Buffer.alloc(s.span),s.encode({index:11,value:o.value},a)}else if(o.type==="updateRestrictGlobalConfig"){let s=m([l("index"),n("value")]);a=Buffer.alloc(s.span),s.encode({index:12,value:o.value},a)}else if(o.type==="updateRestrictCurveParam"){let s=m([l("index"),n("value")]);a=Buffer.alloc(s.span),s.encode({index:13,value:o.value},a)}else if(o.type==="updateCurveRuleManager"){let s=m([l("index"),u("value")]);a=Buffer.alloc(s.span),s.encode({index:14,value:o.value},a)}else throw Error("updateInfo params type error");return new $({keys:r,programId:i,data:Buffer.from([...j.updatePlaformConfig,...a])})}function Ks(i,e,t,o,r,a,s,c){let f=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:oe.programId,isSigner:!1,isWritable:!1},{pubkey:$t,isSigner:!1,isWritable:!1}];return new $({keys:f,programId:i,data:j.claimPlatformFeeFromVault})}function xs(i,e,t,o,r,a,s){let c=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:oe.programId,isSigner:!1,isWritable:!1},{pubkey:$t,isSigner:!1,isWritable:!1}];return new $({keys:c,programId:i,data:j.claimCreatorFee})}var HR=new ot("18446744073709551615");function Cs(i,e,t,o,r,a){let s=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:oe.programId,isSigner:!1,isWritable:!1}];return new $({keys:s,programId:i,data:j.createPlatformVestingAccount})}function Rs(i,e,t,o,r){let a=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:oe.programId,isSigner:!1,isWritable:!1}];return new $({keys:a,programId:i,data:j.createPlatformAllowConfig})}function Ls(i,e,t,o,r){let a=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0}];return new $({keys:a,programId:i,data:j.closePlatformAllowConfig})}function _s(i){let e=m([l("field"),l("op"),v("value")]),t=Buffer.alloc(4+i.length*e.span);return t.writeUInt32LE(i.length,0),i.forEach((o,r)=>{e.encode(o,t,4+r*e.span)}),t}function Os(i,e,t,o,r){let a=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:oe.programId,isSigner:!1,isWritable:!1}];return new $({keys:a,programId:i,data:j.createPlatformCurveRule})}function Ns(i,e,t,o,r,a,s){let c=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:oe.programId,isSigner:!1,isWritable:!1}],f=Buffer.alloc(X().span);return X().encode(a,f),new $({keys:c,programId:i,data:Buffer.from([...j.updatePlatformCurveRule,...f,..._s(s)])})}function Ms(i,e,t,o,r,a){let s=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:oe.programId,isSigner:!1,isWritable:!1}],c=Buffer.alloc(X().span);return X().encode(a,c),new $({keys:s,programId:i,data:Buffer.from([...j.removePlatformCurveRule,...c])})}function Fs(i,e,t,o,r){let a=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0}];return new $({keys:a,programId:i,data:j.closePlatformCurveRule})}import Ce from"bn.js";var Vs=new Ce(1e6);function Zo(i,e){var r,a,s,c;let t=f=>i.supply.isZero()?void 0:f.mul(Vs).div(i.supply),o=()=>{let f=i.supply.sub(i.totalSellA).sub(i.totalLockedAmount);return f.isNeg()?void 0:f};switch(e){case 0:return new Ce(i.curveType);case 1:return new Ce(i.migrateType);case 2:return new Ce(i.migrateCpmmFeeOn);case 3:return i.supply;case 4:return i.totalSellA;case 5:return i.totalFundRaisingB;case 6:return i.totalLockedAmount;case 7:return i.cliffPeriod;case 8:return i.unlockPeriod;case 9:return new Ce(i.baseTokenProgram);case 10:return new Ce(i.transferFee===void 0?0:1);case 11:return new Ce((a=(r=i.transferFee)==null?void 0:r.basisPoints)!=null?a:0);case 12:return(c=(s=i.transferFee)==null?void 0:s.maximumFee)!=null?c:new Ce(0);case 13:return t(i.totalSellA);case 14:return t(i.totalLockedAmount);case 15:return o();case 16:{let f=o();return f===void 0?void 0:t(f)}case 17:return t(i.totalFundRaisingB);case 18:return i.unixTimestamp;default:return}}function Es(i,e){let t=Zo(e,i.field);if(t===void 0)return!1;switch(i.op){case 0:return t.eq(i.value);case 1:return t.gte(i.value);case 2:return t.lte(i.value);case 3:return!t.eq(i.value);default:return!1}}function tL({rule:i,context:e}){var r;let t=(r=i==null?void 0:i.groups)!=null?r:[];if(t.length===0)return{ok:!0,groupFailures:[]};let o=[];for(let a of t){let s=a.constraints.filter(c=>!Es(c,e)).map(c=>_(L({},c),{actual:Zo(e,c.field)}));if(s.length===0)return{ok:!0,matchedGroupId:a.groupId,groupFailures:[]};o.push({groupId:a.groupId,unsatisfied:s})}return{ok:!1,groupFailures:o}}function nL({groupId:i,constraints:e,curveType:t,existingGroupIds:o=[]}){let r=[];!o.includes(i)&&o.length>=Ln&&r.push({code:"CurveRuleGroupsExceeded",message:`a rule holds at most ${Ln} groups, and group ${i} would be a new one`}),e.length>On&&r.push({code:"InvalidCurveRuleConstraint",message:`a group holds at most ${On} constraints, got ${e.length}`});let a=new Set;return e.forEach((s,c)=>{s.field>18&&r.push({code:"InvalidCurveRuleConstraint",message:`constraint ${c}: unknown field id ${s.field}`}),s.op>3&&r.push({code:"InvalidCurveRuleConstraint",message:`constraint ${c}: unknown op id ${s.op}`});let f=`${s.field}/${s.op}`;a.has(f)&&r.push({code:"InvalidCurveRuleConstraint",message:`constraint ${c}: field ${s.field} already has an op ${s.op} constraint in this group. A range uses two different ops on one field`}),a.add(f),t!==0&&zo.includes(s.field)&&r.push({code:"CurveRuleFieldNotSupportedByCurve",message:`constraint ${c}: field ${s.field} reads totalSellA, which curve type ${t} derives itself, so the program refuses it on this config`})}),{ok:r.length===0,errors:r}}export{qa as AUTH_SEED,ls as BondingCurveParam,Ua as CONFIG_SEED,Ya as CREATOR_FEE_VAULT_AUTH_SEED,Yo as CpmmCreatorFeeOn,tt as Curve,Ke as CurveBase,ds as CurveRuleGroup,Ht as FixedPriceCurve,zo as LAUNCHPAD_CURVE_RULE_CONSTANT_PRODUCT_ONLY_FIELDS,On as LAUNCHPAD_MAX_CONSTRAINTS_PER_GROUP,Ln as LAUNCHPAD_MAX_CURVE_RULE_GROUPS,Xt as LaunchConstantProductCurve,ss as LaunchpadConfig,Wa as LaunchpadCurveRuleBaseTokenProgram,Go as LaunchpadCurveRuleField,Xo as LaunchpadCurveRuleOp,ys as LaunchpadMintProgramBit,cs as LaunchpadPool,Sx as LaunchpadPoolInitParam,GS as LaunchpadVesting,Zt as LinearPriceCurve,ht as MathLaunch,Qa as PLATFORM_ALLOW_CONFIG_SEED,Za as PLATFORM_CURVE_RULE_SEED,Xa as PLATFORM_FEE_VAULT_AUTH_SEED,Ha as PLATFORM_GLOBAL_ACCESS_SEED,za as PLATFORM_SEED,Ga as POOL_VESTING_SEED,ms as ParamConstraint,Do as PlatformConfig,zS as PlatformCurveParam,ps as PlatformCurveRule,us as VestingSchedule,j as anchorDataBuf,Wo as buyExactInInstruction,ws as buyExactOutInstruction,nL as checkCurveRuleGroupWritable,tL as checkLaunchAgainstCurveRule,uK as checkPoolToAmm,xs as claimCreatorFee,Is as claimPlatformFee,Ks as claimPlatformFeeFromVault,Ts as claimVestedToken,Ls as closePlatformAllowConfigIns,Fs as closePlatformCurveRuleIns,Rs as createPlatformAllowConfigIns,Bs as createPlatformConfig,Os as createPlatformCurveRuleIns,Cs as createPlatformVestingAccountIns,hs as createVestingAccount,Zo as getCurveRuleFieldValue,_a as getLaunchpadPoolMintAProgram,KK as getLaunchpadPoolMintBProgram,Qo as getLaunchpadPoolMintProgram,Se as getPdaCpiEvent,is as getPdaCreatorFeeVaultAuth,Eo as getPdaCreatorVault,_o as getPdaLaunchpadAuth,$a as getPdaLaunchpadConfigId,ja as getPdaLaunchpadPoolId,Ja as getPdaLaunchpadVaultId,rs as getPdaPlatformAllowConfig,WS as getPdaPlatformConfigAccess,as as getPdaPlatformCurveRule,os as getPdaPlatformFeeVaultAuth,ts as getPdaPlatformId,Vo as getPdaPlatformVault,ns as getPdaVestId,YR as initialize,Ps as initializeV2,As as initializeWithToken2022,Es as isCurveRuleConstraintSatisfied,Ms as removePlatformCurveRuleIns,qo as sellExactInInstruction,ks as sellExactOut,bs as toLaunchpadMintProgramFlag,Ss as updatePlatformConfig,Ns as updatePlatformCurveRuleIns,xx as usdMintBSet};
//# sourceMappingURL=index.mjs.map