UNPKG

@raydium-io/raydium-sdk-v2

Version:

An SDK for building applications on top of Raydium.

2 lines 135 kB
var ar=Object.defineProperty,sr=Object.defineProperties;var ur=Object.getOwnPropertyDescriptors;var rn=Object.getOwnPropertySymbols;var Uo=Object.prototype.hasOwnProperty,Go=Object.prototype.propertyIsEnumerable;var qo=(a,e,t)=>e in a?ar(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,F=(a,e)=>{for(var t in e||(e={}))Uo.call(e,t)&&qo(a,t,e[t]);if(rn)for(var t of rn(e))Go.call(e,t)&&qo(a,t,e[t]);return a},q=(a,e)=>sr(a,ur(e));var ve=(a,e)=>{var t={};for(var n in a)Uo.call(a,n)&&e.indexOf(n)<0&&(t[n]=a[n]);if(a!=null&&rn)for(var n of rn(a))e.indexOf(n)<0&&Go.call(a,n)&&(t[n]=a[n]);return t};import{get as zo,set as cr}from"lodash";var _n=class{constructor(e){this.logLevel=e.logLevel!==void 0?e.logLevel:0,this.name=e.name}set level(e){this.logLevel=e}get time(){return Date.now().toString()}get moduleName(){return this.name}isLogLevel(e){return e<=this.logLevel}error(...e){return this.isLogLevel(0)?(console.error(this.time,this.name,"sdk logger error",...e),this):this}logWithError(...e){let t=e.map(n=>typeof n=="object"?JSON.stringify(n):n).join(", ");throw new Error(t)}warning(...e){return this.isLogLevel(1)?(console.warn(this.time,this.name,"sdk logger warning",...e),this):this}info(...e){return this.isLogLevel(2)?(console.info(this.time,this.name,"sdk logger info",...e),this):this}debug(...e){return this.isLogLevel(3)?(console.debug(this.time,this.name,"sdk logger debug",...e),this):this}},Xo={},lr={};function Q(a){let e=zo(Xo,a);if(!e){let t=zo(lr,a);e=new _n({name:a,logLevel:t}),cr(Xo,a,e)}return e}import{PublicKey as Ot,sendAndConfirmTransaction as Ko,SystemProgram as ru,Transaction as Ht,TransactionMessage as jt,VersionedTransaction as $t}from"@solana/web3.js";import au from"axios";import{PublicKey as ho,AddressLookupTableAccount as Lt}from"@solana/web3.js";import{PublicKey as iu}from"@solana/web3.js";import it from"bn.js";import pC from"decimal.js";import Pr from"big.js";import xu from"bn.js";import mr from"toformat";var dr=mr,Nt=dr;import sn from"big.js";import fr from"bn.js";import yr from"decimal.js-light";import Mt from"bn.js";var Yo=9007199254740991;function Ie(a){let e=Q("Raydium_parseBigNumberish");if(a instanceof Mt)return a;if(typeof a=="string"){if(a.match(/^-?[0-9]+$/))return new Mt(a);e.logWithError(`invalid BigNumberish string: ${a}`)}return typeof a=="number"?(a%1&&e.logWithError(`BigNumberish number underflow: ${a}`),(a>=Yo||a<=-Yo)&&e.logWithError(`BigNumberish number overflow: ${a}`),new Mt(String(a))):typeof a=="bigint"?new Mt(a.toString()):(e.error(`invalid BigNumberish value: ${a}`),new Mt(0))}var an=Q("module/fraction"),En=Nt(sn),Ft=Nt(yr),br={[0]:Ft.ROUND_DOWN,[1]:Ft.ROUND_HALF_UP,[2]:Ft.ROUND_UP},gr={[0]:sn.roundDown,[1]:sn.roundHalfUp,[2]:sn.roundUp},oe=class{constructor(e,t=new fr(1)){this.numerator=Ie(e),this.denominator=Ie(t)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new oe(this.denominator,this.numerator)}add(e){let t=e instanceof oe?e:new oe(Ie(e));return this.denominator.eq(t.denominator)?new oe(this.numerator.add(t.numerator),this.denominator):new oe(this.numerator.mul(t.denominator).add(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}sub(e){let t=e instanceof oe?e:new oe(Ie(e));return this.denominator.eq(t.denominator)?new oe(this.numerator.sub(t.numerator),this.denominator):new oe(this.numerator.mul(t.denominator).sub(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}mul(e){let t=e instanceof oe?e:new oe(Ie(e));return new oe(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof oe?e:new oe(Ie(e));return new oe(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},n=1){Number.isInteger(e)||an.logWithError(`${e} is not an integer.`),e<=0&&an.logWithError(`${e} is not positive.`),Ft.set({precision:e+1,rounding:br[n]});let i=new Ft(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return i.toFormat(i.decimalPlaces(),t)}toFixed(e,t={groupSeparator:""},n=1){return Number.isInteger(e)||an.logWithError(`${e} is not an integer.`),e<0&&an.logWithError(`${e} is negative.`),En.DP=e,En.RM=gr[n]||1,new En(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var Vu=Q("Raydium_amount"),_u=Nt(Pr);import{PublicKey as wr}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Qo}from"@solana/spl-token";var un={chainId:101,address:wr.default.toBase58(),programId:Qo.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}},qe={chainId:101,address:"So11111111111111111111111111111111111111112",programId:Qo.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 Wn}from"@solana/web3.js";import{PublicKey as re,SystemProgram as Zo,SYSVAR_RENT_PUBKEY as kr}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Tr}from"@solana/spl-token";function bt({pubkey:a,isSigner:e=!1,isWritable:t=!0}){return{pubkey:a,isWritable:t,isSigner:e}}var hr=[bt({pubkey:Tr,isWritable:!1}),bt({pubkey:Zo.programId,isWritable:!1}),bt({pubkey:kr,isWritable:!1})];function Ho({publicKey:a,transformSol:e}){let t=jo(a.toString());if(t instanceof re)return e&&t.equals(at)?He:t;if(e&&t.toString()===at.toBase58())return He;if(typeof t=="string"){if(t===re.default.toBase58())return re.default;try{return new re(t)}catch{throw new Error("invalid public key")}}throw new Error("invalid public key")}function jo(a){try{return new re(a)}catch{return a}}var Dn=new re("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),gt=new re("SysvarRent111111111111111111111111111111111"),Xu=new re("SysvarC1ock11111111111111111111111111111111"),st=new re("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Ir=new re("Sysvar1nstructions1111111111111111111111111"),Br=Zo.programId,Yu=new re("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Qu=new re("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),Zu=new re("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Hu=new re("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),ju=new re("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),$u=new re("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Ju=new re("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),ec=new re("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),tc=new re("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),nc=new re("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),oc=new re("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),He=new re("So11111111111111111111111111111111111111112"),at=re.default;var qn=class{constructor({mint:e,decimals:t,symbol:n,name:i,skipMint:r=!1,isToken2022:s=!1}){if(e===at.toBase58()||e instanceof Wn&&at.equals(e)){this.decimals=qe.decimals,this.symbol=qe.symbol,this.name=qe.name,this.mint=new Wn(qe.address),this.isToken2022=!1;return}this.decimals=t,this.symbol=n||e.toString().substring(0,6),this.name=i||e.toString().substring(0,6),this.mint=r?Wn.default:Ho({publicKey:e}),this.isToken2022=s}equals(e){return this===e?!0:this.mint.equals(e.mint)}},Pe=qn;Pe.WSOL=new qn(q(F({},qe),{mint:qe.address}));var Un=class{constructor({decimals:e,symbol:t="UNKNOWN",name:n="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=n}equals(e){return this===e}},cn=Un;cn.SOL=new Un(un);import Sr from"bn.js";var yc=new oe(new Sr(100));var kc=Q("Raydium_price");import{merge as yx}from"lodash";import Rc from"axios";var $o={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"},Kr=q(F({},$o),{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 Jc=Q("Raydium_Api");import{PublicKey as qm,SystemProgram as Um}from"@solana/web3.js";import{AccountLayout as Qm,createAssociatedTokenAccountIdempotentInstruction as Zm,TOKEN_PROGRAM_ID as Hm,TOKEN_2022_PROGRAM_ID as jm}from"@solana/spl-token";import{PublicKey as Am,SystemProgram as km}from"@solana/web3.js";import Im from"bn.js";import{createCloseAccountInstruction as xm,createInitializeAccountInstruction as Cm,createTransferInstruction as Rm,TOKEN_PROGRAM_ID as Lm}from"@solana/spl-token";var pe={CreateAccount:"CreateAccount",InitAccount:"InitAccount",CreateATA:"CreateATA",CloseAccount:"CloseAccount",TransferAmount:"TransferAmount",InitMint:"InitMint",MintTo:"MintTo",InitMarket:"InitMarket",Util1216OwnerClaim:"Util1216OwnerClaim",SetComputeUnitPrice:"SetComputeUnitPrice",SetComputeUnitLimit:"SetComputeUnitLimit",ClmmCreatePool:"ClmmCreatePool",ClmmOpenPosition:"ClmmOpenPosition",ClmmIncreasePosition:"ClmmIncreasePosition",ClmmDecreasePosition:"ClmmDecreasePosition",ClmmClosePosition:"ClmmClosePosition",ClmmSwapBaseIn:"ClmmSwapBaseIn",ClmmSwapBaseOut:"ClmmSwapBaseOut",ClmmInitReward:"ClmmInitReward",ClmmSetReward:"ClmmSetReward",ClmmCollectReward:"ClmmCollectReward",ClmmLockPosition:"ClmmLockPosition",ClmmHarvestLockPosition:"ClmmHarvestLockPosition",AmmV4Swap:"AmmV4Swap",AmmV4AddLiquidity:"AmmV4AddLiquidity",AmmV4RemoveLiquidity:"AmmV4RemoveLiquidity",AmmV4SimulatePoolInfo:"AmmV4SimulatePoolInfo",AmmV4SwapBaseIn:"AmmV4SwapBaseIn",AmmV4SwapBaseOut:"AmmV4SwapBaseOut",AmmV4CreatePool:"AmmV4CreatePool",AmmV4InitPool:"AmmV4InitPool",AmmV5AddLiquidity:"AmmV5AddLiquidity",AmmV5RemoveLiquidity:"AmmV5RemoveLiquidity",AmmV5SimulatePoolInfo:"AmmV5SimulatePoolInfo",AmmV5SwapBaseIn:"AmmV5SwapBaseIn",AmmV5SwapBaseOut:"AmmV5SwapBaseOut",RouteSwap:"RouteSwap",RouteSwap1:"RouteSwap1",RouteSwap2:"RouteSwap2",FarmV3Deposit:"FarmV3Deposit",FarmV3Withdraw:"FarmV3Withdraw",FarmV3CreateLedger:"FarmV3CreateLedger",FarmV4Withdraw:"FarmV4Withdraw",FarmV5Deposit:"FarmV5Deposit",FarmV5Withdraw:"FarmV5Withdraw",FarmV5CreateLedger:"FarmV5CreateLedger",FarmV6Deposit:"FarmV6Deposit",FarmV6Withdraw:"FarmV6Withdraw",FarmV6Create:"FarmV6Create",FarmV6Restart:"FarmV6Restart",FarmV6CreatorAddReward:"FarmV6CreatorAddReward",FarmV6CreatorWithdraw:"FarmV6CreatorWithdraw",CpmmCreatePool:"CpmmCreatePool",CpmmAddLiquidity:"CpmmAddLiquidity",CpmmWithdrawLiquidity:"CpmmWithdrawLiquidity",CpmmSwapBaseIn:"CpmmSwapBaseIn",CpmmSwapBaseOut:"CpmmSwapBaseOut",CpmmLockLp:"CpmmLockLp",CpmmCollectLockFee:"CpmmCollectLockFee",TransferTip:"TransferTip"};import{Keypair as am,PublicKey as sm}from"@solana/web3.js";import lm from"bn.js";import{TOKEN_PROGRAM_ID as pm}from"@solana/spl-token";import{PublicKey as Er}from"@solana/web3.js";import ni,{isBN as oi}from"bn.js";import{bits as xr,BitStructure as ml,blob as Cr,Blob as dl,cstr as pl,f32 as fl,f32be as yl,f64 as bl,f64be as gl,greedy as Pl,Layout as Rr,ns64 as Al,ns64be as wl,nu64 as kl,nu64be as Tl,offset as Lr,s16 as hl,s16be as Il,s24 as Bl,s24be as Sl,s32 as Or,s32be as Kl,s40 as xl,s40be as Cl,s48 as Rl,s48be as Ll,s8 as Ol,seq as Nr,struct as Nl,Structure as Mr,u16 as Fr,u16be as Ml,u24 as Fl,u24be as vl,u32 as vr,u32be as Vl,u40 as _l,u40be as El,u48 as Dl,u48be as Wl,u8 as Vr,UInt as _r,union as ql,Union as Ul,unionLayoutDiscriminator as Gl,utf8 as zl}from"@solana/buffer-layout";var ln=Rr,Jo=Mr;var Gn=_r;var ei=Vr,le=Fr;var Vt=vr;var Ve=Or;var ti=Nr;var X=Cr;var zn=xr,Xn=Lr;var ut=class extends ln{constructor(t,n,i){super(t,i);this.blob=X(t),this.signed=n}decode(t,n=0){let i=new ni(this.blob.decode(t,n),10,"le");return this.signed?i.fromTwos(this.span*8).clone():i}encode(t,n,i=0){return typeof t=="number"&&(t=new ni(t)),this.signed&&(t=t.toTwos(this.span*8)),this.blob.encode(t.toArrayLike(Buffer,"le",this.span),n,i)}},mn=class extends ln{constructor(t){super(8,t);this._lower=zn(Vt(),!1),this._upper=zn(Vt(),!1)}addBoolean(t){this._lower.fields.length<32?this._lower.addBoolean(t):this._upper.addBoolean(t)}decode(t,n=0){let i=this._lower.decode(t,n),r=this._upper.decode(t,n+this._lower.span);return F(F({},i),r)}encode(t,n,i=0){return this._lower.encode(t,n,i)+this._upper.encode(t,n,i+this._lower.span)}};function I(a){return new Gn(1,a)}function ae(a){return new Gn(4,a)}function o(a){return new ut(8,!1,a)}function G(a){return new ut(16,!1,a)}function ii(a){return new ut(1,!0,a)}function Pt(a){return new ut(8,!0,a)}function ri(a){return new ut(16,!0,a)}var ct=class extends ln{constructor(t,n,i,r){super(t.span,r);this.layout=t,this.decoder=n,this.encoder=i}decode(t,n){return this.decoder(this.layout.decode(t,n))}encode(t,n,i){return this.layout.encode(this.encoder(t),n,i)}getSpan(t,n){return this.layout.getSpan(t,n)}};function m(a){return new ct(X(32),e=>new Er(e),e=>e.toBuffer(),a)}function Me(a){return new ct(ei(),Dr,Wr,a)}function Dr(a){if(a===0)return!1;if(a===1)return!0;throw new Error("Invalid bool: "+a)}function Wr(a){return a?1:0}function ai(a,e){let t=Vt("length"),n=T([t,R(a,Xn(t,-t.span),"values")]);return new ct(n,({values:i})=>i,i=>({values:i}),e)}function qr(a){let e=Vt("length"),t=T([e,X(Xn(e,-e.span),"data")]);return new ct(t,({data:n})=>n,n=>({data:n}),a)}function Se(a){return new ct(qr(),e=>e.toString("utf-8"),e=>Buffer.from(e,"utf-8"),a)}var Yn=class extends Jo{decode(e,t){return super.decode(e,t)}};function T(a,e,t){return new Yn(a,e,t)}function R(a,e,t){let n,i=typeof e=="number"?e:oi(e)?e.toNumber():new Proxy(e,{get(r,s){if(!n){let l=Reflect.get(r,"count");n=oi(l)?l.toNumber():l,Reflect.set(r,"count",n)}return Reflect.get(r,s)},set(r,s,l){return s==="count"&&(n=l),Reflect.set(r,s,l)}});return ti(a,i,t)}var dn=T([m("mint"),m("owner"),o("amount"),ae("delegateOption"),m("delegate"),I("state"),ae("isNativeOption"),o("isNative"),o("delegatedAmount"),ae("closeAuthorityOption"),m("closeAuthority")]);import{PublicKey as JP,SystemProgram as eA}from"@solana/web3.js";import{createAssociatedTokenAccountIdempotentInstruction as nA}from"@solana/spl-token";import{PublicKey as Zr}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Hr}from"@solana/spl-token";import{ComputeBudgetProgram as ui,Keypair as li,PublicKey as Gr,Transaction as mi,TransactionMessage as zr,VersionedTransaction as di}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Xr}from"@solana/spl-token";var ci=Q("Raydium_txUtil"),pi=1644;function fn(a){let e=[],t=[];return a.microLamports&&(e.push(ui.setComputeUnitPrice({microLamports:a.microLamports})),t.push(pe.SetComputeUnitPrice)),a.units&&(e.push(ui.setComputeUnitLimit({units:a.units})),t.push(pe.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}async function At(a,e){var n,i;let t=e!=null?e:"confirmed";return(i=await((n=a.getLatestBlockhash)==null?void 0:n.call(a,{commitment:t})))==null?void 0:i.blockhash}async function yn(a,e){return a.getSignatureStatuses([e]),new Promise((t,n)=>{let i=setTimeout(n,6e4);a.onSignature(e,r=>{if(clearTimeout(i),!r.err){t("");return}n(Object.assign(r.err,{txId:e}))},"confirmed")})}function Qn(a,e){a.length<1&&ci.logWithError(`no instructions provided: ${a.toString()}`),e.length<1&&ci.logWithError(`no signers provided:, ${e.toString()}`);let t=new mi;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...a);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<pi}catch{return!1}}function ie(a,e){let[t,n]=Gr.findProgramAddressSync(a,e);return{publicKey:t,nonce:n}}function _t({instructions:a,payer:e,signers:t}){return Qn(a,[e,...t])}function Et({instructions:a,payer:e,lookupTableAddressAccount:t,recentBlockhash:n=li.generate().publicKey.toString()}){let r=new zr({payerKey:e,recentBlockhash:n,instructions:a}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new di(r).serialize()).toString("base64").length<pi}catch{return!1}}var Yr=a=>Buffer.isBuffer(a)?a:a instanceof Uint8Array?Buffer.from(a.buffer,a.byteOffset,a.byteLength):Buffer.from(a),Qr=a=>{let e=a.serialize({requireAllSignatures:!1,verifySignatures:!1});a instanceof di&&(e=Yr(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch{return e.toString("base64")}};function lt(a){let e=[];return a.forEach(t=>{t instanceof mi&&(t.recentBlockhash||(t.recentBlockhash=Xr.toBase58()),t.feePayer||(t.feePayer=li.generate().publicKey)),e.push(Qr(t))}),console.log("simulate tx string:",e),e}function me(a,e,t){return ie([a.toBuffer(),(t!=null?t:Hr).toBuffer(),e.toBuffer()],new Zr("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}import{PublicKey as D}from"@solana/web3.js";var fi=new D("EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"),yi=new D("CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T"),bi=new D("9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z"),Zn=new D("FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG"),Pd=new D("CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS"),jr=new D("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"),gi=new D("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),Pi=new D("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"),Ad=new D("5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h"),$r=new D("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),Ai=new D("CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"),Jr=new D("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),ea=new D("kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy"),wi=new D("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),wd=new D("routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS"),ta=new D("7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"),Hn=new D("CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"),na=new D("GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"),kd=new D("DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8"),oa=new D("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),ia=new D("3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH"),ce=new D("LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"),Td=new D("WLHv2UAZm6z4KyaaELi5pjdbJh6RESMva1Rnn8pJVVh"),hd=new D("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),Id=new D("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),Bd=new D("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),Sd=new D("6s1xP3hpbAfFoNtUNF8mfHsjr2Bd97JxFJRWLbL6aHuX");var Je={OPEN_BOOK_PROGRAM:new D("EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj"),SERUM_PROGRAM_ID_V3:new D("Ray1111111111111111111111111111111111111111"),AMM_V4:new D("DRaya7Kj3aMWQSy19kSjvmuwq9docCHofyP9kanQGaav"),AMM_STABLE:new D("DRayDdXc1NZQ9C3hRWmoSf8zK4iapgMnjdNZWrfwsP8m"),CLMM_PROGRAM_ID:new D("DRayAUgENGQBKVaX8owNhgzkEDyoHTGVEGHVJT1E9pfH"),CLMM_LOCK_PROGRAM_ID:new D("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),CLMM_LOCK_AUTH_ID:new D("6Aoh8h2Lw2m5UGxYR8AdAL87jTWYeKoxM52mJRzfYwN"),CREATE_CPMM_POOL_PROGRAM:new D("DRaycpLY18LhpbydsBWbVJtxpNv9oXPgjRSfpF2bWpYb"),CREATE_CPMM_POOL_AUTH:new D("CXniRufdq5xL8t8jZAPxsPZDpuudwuJSPWnbcD5Y5Nxq"),CREATE_CPMM_POOL_FEE_ACC:new D("3oE58BKVt8KuYkGxx8zBojugnymWmBiyafWgMrnb6eYy"),LOCK_CPMM_PROGRAM:new D("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),LOCK_CPMM_AUTH:new D("7qWVV8UY2bRJfDLP4s37YzBPKUkVB46DStYJBpYbQzu3"),UTIL1216:D.default,Router:new D("DRaybByLpbUL57LJARs3j8BitTxVfzBg351EaMr5UTCd"),FARM_PROGRAM_ID_V3:new D("DRayWyrLmEW5KEeqs8kdTMMaBabapqagaBC7KWpGtJeZ"),FARM_PROGRAM_ID_V4:new D("Ray1111111111111111111111111111111111111111"),FARM_PROGRAM_ID_V5:new D("DRayiCGSZgku1GTK6rXD6mVDdingXy6APAH1R6R5L2LC"),FARM_PROGRAM_ID_V6:new D("DRayzbYakXs45ELHkzH6vC3fuhQqTAnv5A68gdFuvZyZ"),LAUNCHPAD_PROGRAM:new D("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),LAUNCHPAD_AUTH:new D("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),LAUNCHPAD_PLATFORM:new D("2Jx4KTDrVSdWNazuGpcA8n3ZLTRGGBDxAWhuKe2Xcj2a"),LAUNCHPAD_CONFIG:new D("7ZR4zD7PYfY2XxoG1Gxcy2EgEeGYrpxrwzPuwdUBssEt"),FEE_DESTINATION_ID:new D("9y8ENuuZ3b19quffx9hQvRVygG5ky6snHfRvGpuSfeJy"),MODEL_DATA_PUBKEY:new D("Ray1111111111111111111111111111111111111111")};import dA from"decimal.js";import{createAssociatedTokenAccountIdempotentInstruction as Rb,TOKEN_2022_PROGRAM_ID as Lb,TOKEN_PROGRAM_ID as Ob}from"@solana/spl-token";import{PublicKey as Mb}from"@solana/web3.js";import vb from"bn.js";import _b from"decimal.js";import{TOKEN_PROGRAM_ID as Dd}from"@solana/spl-token";import{PublicKey as Gd}from"@solana/web3.js";var ra=T([ae("mintAuthorityOption"),m("mintAuthority"),o("supply"),I("decimals"),I("isInitialized"),ae("freezeAuthorityOption"),m("freezeAuthority")]);import{ASSOCIATED_TOKEN_PROGRAM_ID as $y,TOKEN_2022_PROGRAM_ID as Jy,TOKEN_PROGRAM_ID as eb}from"@solana/spl-token";import{Keypair as ob,PublicKey as ib,SystemProgram as ab,TransactionInstruction as sb}from"@solana/web3.js";import cb from"bn.js";import Z from"bn.js";var _e=new Z(1).shln(64);var aa=new Z(1).shln(128),bn=new Z(1).shln(64).subn(1),sa=new Z(1).shln(128).subn(1);var kt=new Z("4295048016"),Tt=new Z("79226673521066979257578248091"),ua=new Z("59543866431248"),ca=new Z("184467440737095516"),la=new Z("15793534762490258745");var jn=60,np=new Z("18446743708227953217"),ma=[{bit:0,factor:new Z("fffcb933bd6fb800",16)},{bit:1,factor:new Z("fff97272373d4000",16)},{bit:2,factor:new Z("fff2e50f5f657000",16)},{bit:3,factor:new Z("ffe5caca7e10f000",16)},{bit:4,factor:new Z("ffcb9843d60f7000",16)},{bit:5,factor:new Z("ff973b41fa98e800",16)},{bit:6,factor:new Z("ff2ea16466c9b000",16)},{bit:7,factor:new Z("fe5dee046a9a3800",16)},{bit:8,factor:new Z("fcbe86c7900bb000",16)},{bit:9,factor:new Z("f987a7253ac65800",16)},{bit:10,factor:new Z("f3392b0822bb6000",16)},{bit:11,factor:new Z("e7159475a2caf000",16)},{bit:12,factor:new Z("d097f3bdfd2f2000",16)},{bit:13,factor:new Z("a9f746462d9f8000",16)},{bit:14,factor:new Z("70d869a156f31c00",16)},{bit:15,factor:new Z("31be135f97ed3200",16)},{bit:16,factor:new Z("9aa508b5b85a500",16)},{bit:17,factor:new Z("5d6af8dedc582c",16)},{bit:18,factor:new Z("2216e584f5fa",16)}];var Dt=3,ki=100;var Ti=10,hi=100,gn=14;var fe=new Z(0),ht=new Z(1),op=new Z(-1);var ip=new Z("18446744073700000000");var da=T([X(8),I("bump"),le("index"),m("owner"),ae("protocolFeeRate"),ae("tradeFeeRate"),le("tickSpacing"),ae("fundFeeRate"),R(ae(),1),m("fundOwner"),R(o(),3)]),pa=T([ae("blockTimestamp"),Pt("tickCumulative"),R(o(),4)]),Ii=T([X(8),Me("initialized"),o("recentEpoch"),le("observationIndex"),m("poolId"),R(pa,ki,"observations"),R(o(),4)]),fa=T([le("filterPeriod"),le("decayPeriod"),le("reductionFactor"),ae("dynamicFeeControl"),ae("maxVolatilityAccumulator"),Ve("tickSpacingIndexReference"),ae("volatilityReference"),ae("volatilityAccumulator"),o("lastUpdateTimestamp"),R(I(),46)]),ya=T([I("state"),o("openTime"),o("endTime"),o("lastUpdateTime"),G("emissionsPerSecondX64"),o("totalEmissioned"),o("claimed"),m("mint"),m("vault"),m("creator"),G("growthGlobalX64")]),$n=T([X(8),I("bump"),m("configId"),m("creator"),m("mintA"),m("mintB"),m("vaultA"),m("vaultB"),m("observationId"),I("mintDecimalsA"),I("mintDecimalsB"),le("tickSpacing"),G("liquidity"),G("sqrtPriceX64"),Ve("tickCurrent"),ae(),G("feeGrowthGlobalX64A"),G("feeGrowthGlobalX64B"),o("protocolFeesTokenA"),o("protocolFeesTokenB"),R(G(),4),I("status"),I("feeOn"),X(6),R(ya,Dt,"rewardInfos"),X(8*16,"tickArrayBitmap"),R(o(),4),o("fundFeesTokenA"),o("fundFeesTokenB"),o("startTime"),o("recentEpoch"),fa.replicate("dynamicFeeInfo"),R(o(),46)]),ba=T([G("growthInsideLastX64"),o("rewardAmountOwed")]),ga=T([X(8),I("bump"),m("nftMint"),m("poolId"),Ve("tickLower"),Ve("tickUpper"),G("liquidity"),G("feeGrowthInsideLastX64A"),G("feeGrowthInsideLastX64B"),o("tokenFeesOwedA"),o("tokenFeesOwedB"),R(ba,Dt,"rewardInfos"),o("recentEpoch"),R(o(),7)]),up=T([X(8),I("bump"),m("poolId"),Ve("tickLower"),Ve("tickUpper"),G("liquidity"),G("feeGrowthInsideLastX64A"),G("feeGrowthInsideLastX64B"),o("tokenFeesOwedA"),o("tokenFeesOwedB"),R(G(),Dt,"rewardGrowthInside"),o("recentEpoch"),R(o(),7)]),Pa=T([Ve("tick"),ri("liquidityNet"),G("liquidityGross"),G("feeGrowthOutsideX64A"),G("feeGrowthOutsideX64B"),R(G(),Dt,"rewardGrowthsOutsideX64"),o("orderPhase"),o("ordersAmount"),o("partFilledOrdersRemaining"),G("unfilledRatioX64"),R(ae(),3)]),Bi=T([X(8),m("poolId"),Ve("startTickIndex"),R(Pa,jn,"ticks"),I("initializedTickCount"),o("recentEpoch"),R(I(),107)]),Aa=T([X(8),I("bump"),R(m(),Ti,"operationOwners"),R(m(),hi,"whitelistMints")]),wa=T([X(8),m("poolId"),m("owner"),Ve("tick"),Me("zeroForOne"),o("orderPhase"),o("totalAmount"),o("filledAmount"),o("settleBase"),o("settleOutput"),o("openTime"),G("unfilledRatioX64"),R(o(),4)]),Si=T([X(8),m("poolId"),X(8*8*gn,"positiveTickArrayBitmap"),X(8*8*gn,"negativeTickArrayBitmap")]),cp=T([X(8),le("index"),le("filterPeriod"),le("decayPeriod"),le("reductionFactor"),ae("dynamicFeeControl"),ae("maxVolatilityAccumulator"),R(o(),8)]),ka=T([X(8),m("wallet"),I("nonceIndex"),o("orderNonce"),R(o(),4)]),lp=T([o(),I("bump"),m("owner"),m("poolId"),m("positionId"),m("nftAccount"),R(o(),8)]),Ta=T([X(8),I("bump"),m("lockOwner"),m("poolId"),m("positionId"),m("nftAccount"),m("lockNftMint"),o("recentEpoch"),R(o(),8)]);import pp from"bn.js";function Jn(a){let e=Buffer.alloc(2);return e.writeUInt16LE(a),e}var Ip=Buffer.from("amm_config","utf8"),Ki=Buffer.from("pool","utf8"),xi=Buffer.from("pool_vault","utf8"),Bp=Buffer.from("pool_reward_vault","utf8"),Sp=Buffer.from("position","utf8"),Kp=Buffer.from("tick_array","utf8"),xp=Buffer.from("operation","utf8"),Cp=Buffer.from("pool_tick_array_bitmap_extension","utf8"),Rp=Buffer.from("observation","utf8"),Lp=Buffer.from("support_mint","utf8"),Op=Buffer.from("dynamic_fee_config","utf8"),Np=Buffer.from("permission","utf8");function Pn(a){return ie([Buffer.from("metadata","utf8"),st.toBuffer(),a.toBuffer()],st)}var Mp=Buffer.from("locked_position","utf8");import{sha256 as Va}from"js-sha256";import ha from"bn.js";import _p from"decimal.js";var Dp=new ha(1).shln(256).subn(1);import rf from"bn.js";import Yp from"bn.js";import Zp from"decimal.js";import lf from"bn.js";import df from"decimal.js";import{PublicKey as $f}from"@solana/web3.js";import ey from"bn.js";import{TOKEN_2022_PROGRAM_ID as uy,TOKEN_PROGRAM_ID as cy}from"@solana/spl-token";import py from"decimal.js";import Wf from"bn.js";import xf from"bn.js";import Iy from"bn.js";function ye(a){let e=`global:${a}`;return Buffer.from(Va.digest(e)).slice(0,8)}Ii.span;var gb=Q("Raydium_Clmm"),Pb={createPool:ye("create_pool"),createCustomizablePool:ye("create_customizable_pool"),createPermissionedPool:ye("create_permissioned_pool"),openPositionV2:ye("open_position_v2"),openPositionWithToken22Nft:ye("open_position_with_token22_nft"),closePosition:ye("close_position"),increaseLiquidityV2:ye("increase_liquidity_v2"),decreaseLiquidityV2:ye("decrease_liquidity_v2"),initializeReward:ye("initialize_reward"),setRewardParams:ye("set_reward_params"),updateRewardInfos:ye("update_reward_infos"),collectRemainingRewards:ye("collect_remaining_rewards"),swapV2:ye("swap_v2"),openLimitOrder:ye("open_limit_order"),increaseLimitOrder:ye("increase_limit_order"),decreaseLimitOrder:ye("decrease_limit_order"),settleLimitOrder:ye("settle_limit_order"),closeLimitOrder:ye("close_limit_order")};import{PublicKey as oo}from"@solana/web3.js";var Wa=T([I("instruction")]),qa=T([I("instruction")]),Ua=T([o("rewardState"),o("rewardOpenTime"),o("rewardEndTime"),o("rewardLastUpdateTime"),o("totalReward"),o("totalRewardEmissioned"),o("rewardClaimed"),o("rewardPerSecond"),G("accRewardPerShare"),m("rewardVault"),m("rewardMint"),m("rewardSender"),o("rewardType"),R(o(),15,"padding")]),Ga=T([o("state"),o("nonce"),m("lpVault"),m("rewardVault"),m(),m(),o(),o(),o("totalReward"),G("perShareReward"),o("lastSlot"),o("perSlotReward")]),za=T([o("state"),o("nonce"),m("lpVault"),m("rewardVaultA"),o("totalRewardA"),G("perShareRewardA"),o("perSlotRewardA"),I("option"),m("rewardVaultB"),X(7),o("totalRewardB"),G("perShareRewardB"),o("perSlotRewardB"),o("lastSlot"),m()]),Xa=T([o(),o("state"),o("nonce"),o("validRewardTokenNum"),G("rewardMultiplier"),o("rewardPeriodMax"),o("rewardPeriodMin"),o("rewardPeriodExtend"),m("lpMint"),m("lpVault"),R(Ua,5,"rewardInfos"),m("creator"),m(),R(o(),32,"padding")]),Ya=new Proxy(Ga,{get(a,e,t){return e==="decode"?(...n)=>{let i=a.decode(...n);return q(F({},i),{version:3,rewardInfos:[{rewardVault:i.rewardVault,totalReward:i.totalReward,perSlotReward:i.perSlotReward,perShareReward:i.perShareReward}]})}:Reflect.get(a,e,t)}}),Qa=new Proxy(za,{get(a,e,t){return e==="decode"?(...n)=>{let i=a.decode(...n);return q(F({},i),{version:5,rewardInfos:[{rewardVault:i.rewardVaultA,totalReward:i.totalRewardA,perSlotReward:i.perSlotRewardA,perShareReward:i.perShareRewardA},{rewardVault:i.rewardVaultB,totalReward:i.totalRewardB,perSlotReward:i.perSlotRewardB,perShareReward:i.perShareRewardB}]})}:Reflect.get(a,e,t)}}),Mi=new Proxy(Xa,{get(a,e,t){return e==="decode"?(...n)=>{let i=a.decode(...n);return q(F({},i),{version:6,rewardInfos:i.rewardInfos.map(r=>{var s;return q(F({},r),{rewardType:((s=Object.entries(Ut).find(l=>String(l[1])===r.rewardType.toString()))!=null?s:["Standard SPL"])[0]})})})}:Reflect.get(a,e,t)}}),Za=T([o("isSet"),o("rewardPerSecond"),o("rewardOpenTime"),o("rewardEndTime"),o("rewardType")]),Ha=T([I("instruction"),o("nonce"),R(Za,5,"rewardTimeInfo")]),ja=T([I("instruction"),o("rewardReopenTime"),o("rewardEndTime"),o("rewardPerSecond")]),$a=T([I("instruction"),o("isSet"),o("rewardPerSecond"),o("rewardOpenTime"),o("rewardEndTime"),o("rewardType")]),gg=T([o("state"),m("id"),m("owner"),o("deposited"),R(o(),1,"rewardDebts")]),Fi=T([o("state"),m("id"),m("owner"),o("deposited"),R(G(),1,"rewardDebts"),o(""),o("voteLockedBalance"),R(o(),15)]),Pg=T([o("state"),m("id"),m("owner"),o("deposited"),R(o(),2,"rewardDebts")]),Ja=T([o("state"),m("id"),m("owner"),o("deposited"),R(G(),2,"rewardDebts"),R(o(),17)]),es=T([o(),o("state"),m("id"),m("owner"),o("deposited"),R(G(),5,"rewardDebts"),R(o(),16)]),ts=T([I("instruction"),o("amount")]),ns=T([m("mint"),m("grantAuthority"),o("baselineVoteWeightScaledFactor"),o("maxExtraLockupVoteWeightScaledFactor"),o("lockupSaturationSecs"),ii("digitShift"),R(I(),7,"reserved1"),R(o(),7,"reserved2")]),os=T([X(8),m("governanceProgramId"),m("realm"),m("realmGoverningTokenMint"),m("realmAuthority"),R(I(),32,"reserved1"),R(ns,4,"votingMints"),Pt("timeOffset"),I("bump"),R(I(),7,"reserved2"),R(o(),11,"reserved3")]),is=T([Pt("startTime"),Pt("endTime"),I("kind"),R(I(),15,"reserved")]),rs=T([R(is,1,"lockup"),o("amountDeposited_native"),o("amountInitiallyLockedNative"),Me("isUsed"),Me("allowClawback"),I("votingMintConfigIdx"),R(I(),29,"reserved")]),as=T([X(8),m("voterAuthority"),m("registrar"),R(rs,32,"deposits"),I("voterBump"),I("voterWweightRecordBump"),R(I(),94,"reserved")]);import{NATIVE_MINT as Kg}from"@solana/spl-token";var xg=Q("Raydium_farm_config"),ss=new oo("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),us=new oo("FrspKwj8i3pNmKwXreTveC4fu7KL5ZbGeXdZBe2XViu1");var Cg=new oo("3TRTX4dXUpp2eqxi3tvQDFYUV7SdDJjcPE3Y4mbtftaX");var Ut={"Standard SPL":0,"Option tokens":1},vi={[fi.toString()]:3,[yi.toString()]:4,[bi.toString()]:5,[Zn.toString()]:6,[Je.FARM_PROGRAM_ID_V3.toString()]:3,[Je.FARM_PROGRAM_ID_V4.toString()]:4,[Je.FARM_PROGRAM_ID_V5.toString()]:5,[Je.FARM_PROGRAM_ID_V6.toString()]:6};import{PublicKey as fP,SystemProgram as yP,SYSVAR_CLOCK_PUBKEY as bP,SYSVAR_RENT_PUBKEY as gP,TransactionInstruction as PP}from"@solana/web3.js";import wP from"bn.js";import{ASSOCIATED_TOKEN_PROGRAM_ID as TP,createAssociatedTokenAccountIdempotentInstruction as hP,TOKEN_PROGRAM_ID as IP}from"@solana/spl-token";import Gg from"bn.js";import{PublicKey as Fg}from"@solana/web3.js";import Vg from"bn.js";var oP=Q("Raydium.farm.util");var FP=Q("Raydium_farm_instruction"),vP={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 hA from"bn.js";import{PublicKey as Ck}from"@solana/web3.js";import{AccountLayout as Ok,MintLayout as Nk,NATIVE_MINT as Mk,TOKEN_PROGRAM_ID as vk}from"@solana/spl-token";import Ae from"bn.js";var Gt=1e4;function hn(a,e){let{div:t,mod:n}=a.divmod(e);return n.gt(new Ae(0))?t.add(new Ae(1)):t}function dt(a,e){if(a.isZero())return new Ae(0);let t=a.div(e);return t.isZero()?new Ae(1):a.mod(e).gt(new Ae(0))?t.add(new Ae(1)):t}function zt(a,e,t){if(e===void 0)return{amount:a,fee:void 0,expirationTime:void 0};let n=Math.floor(t/432e3),i=n<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,r=new Ae(i.maximumFee.toString()),s=n<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*432e3-t)*400/1e3:void 0,l=hn(a.mul(new Ae(i.transferFeeBasisPoints)),new Ae(Gt)),c=l.gt(r)?r:l;return{amount:a,fee:c,expirationTime:s}}function Bt(a,e,t){if(e===void 0)return{amount:a,fee:void 0,expirationTime:void 0};let n=Math.floor(t/432e3),i=n<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,r=new Ae(i.maximumFee.toString()),s=n<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*432e3-t)*400/1e3:void 0;if(i.transferFeeBasisPoints===Gt){let l=new Ae(i.maximumFee.toString());return{amount:a.add(l),fee:l,expirationTime:s}}else{let l=hn(a.mul(new Ae(Gt)),new Ae(Gt-i.transferFeeBasisPoints)),c=new Ae(i.maximumFee.toString()),u=l.sub(a).gt(c)?a.add(c):l,d=hn(u.mul(new Ae(i.transferFeeBasisPoints)),new Ae(Gt)),p=d.gt(r)?r:d;return{amount:u,fee:p,expirationTime:s}}}import _i from"bn.js";var bs=new _i(25),gs=new _i(1e4);import{ASSOCIATED_TOKEN_PROGRAM_ID as YA,TOKEN_PROGRAM_ID as QA}from"@solana/spl-token";import{PublicKey as HA,SystemProgram as jA,SYSVAR_RENT_PUBKEY as $A,TransactionInstruction as JA}from"@solana/web3.js";import sw from"bn.js";var Ps=T([I("instruction"),o("amountIn"),o("minAmountOut")]),As=T([I("instruction"),o("maxAmountIn"),o("amountOut")]),UA=T([I("instruction"),I("nonce")]),ws=T([I("instruction"),I("nonce"),o("startTime")]),Ei=T([o("status"),o("nonce"),o("maxOrder"),o("depth"),o("baseDecimal"),o("quoteDecimal"),o("state"),o("resetFlag"),o("minSize"),o("volMaxCutRatio"),o("amountWaveRatio"),o("baseLotSize"),o("quoteLotSize"),o("minPriceMultiplier"),o("maxPriceMultiplier"),o("systemDecimalValue"),o("minSeparateNumerator"),o("minSeparateDenominator"),o("tradeFeeNumerator"),o("tradeFeeDenominator"),o("pnlNumerator"),o("pnlDenominator"),o("swapFeeNumerator"),o("swapFeeDenominator"),o("baseNeedTakePnl"),o("quoteNeedTakePnl"),o("quoteTotalPnl"),o("baseTotalPnl"),o("poolOpenTime"),o("punishPcAmount"),o("punishCoinAmount"),o("orderbookToInitTime"),G("swapBaseInAmount"),G("swapQuoteOutAmount"),o("swapBase2QuoteFee"),G("swapQuoteInAmount"),G("swapBaseOutAmount"),o("swapQuote2BaseFee"),m("baseVault"),m("quoteVault"),m("baseMint"),m("quoteMint"),m("lpMint"),m("openOrders"),m("marketId"),m("marketProgramId"),m("targetOrders"),m("withdrawQueue"),m("lpVault"),m("owner"),o("lpReserve"),R(o(),3,"padding")]),GA=T([o("accountType"),o("status"),o("nonce"),o("maxOrder"),o("depth"),o("baseDecimal"),o("quoteDecimal"),o("state"),o("resetFlag"),o("minSize"),o("volMaxCutRatio"),o("amountWaveRatio"),o("baseLotSize"),o("quoteLotSize"),o("minPriceMultiplier"),o("maxPriceMultiplier"),o("systemDecimalsValue"),o("abortTradeFactor"),o("priceTickMultiplier"),o("priceTick"),o("minSeparateNumerator"),o("minSeparateDenominator"),o("tradeFeeNumerator"),o("tradeFeeDenominator"),o("pnlNumerator"),o("pnlDenominator"),o("swapFeeNumerator"),o("swapFeeDenominator"),o("baseNeedTakePnl"),o("quoteNeedTakePnl"),o("quoteTotalPnl"),o("baseTotalPnl"),o("poolOpenTime"),o("punishPcAmount"),o("punishCoinAmount"),o("orderbookToInitTime"),G("swapBaseInAmount"),G("swapQuoteOutAmount"),G("swapQuoteInAmount"),G("swapBaseOutAmount"),o("swapQuote2BaseFee"),o("swapBase2QuoteFee"),m("baseVault"),m("quoteVault"),m("baseMint"),m("quoteMint"),m("lpMint"),m("modelDataAccount"),m("openOrders"),m("marketId"),m("marketProgramId"),m("targetOrders"),m("owner"),R(o(),64,"padding")]),ks=T([I("instruction"),o("baseAmountIn"),o("quoteAmountIn"),o("fixedSide"),o("otherAmountMin")]),Ts=T([I("instruction"),o("lpAmount"),o("baseAmountMin"),o("quoteAmountMin")]);var hs=T([o("fee")]);var lw=Q("Raydium_liquidity_instruction");var Is=5e4,Bs=T([o("x"),o("y"),o("price")]),fw=T([o("accountType"),o("status"),o("multiplier"),o("validDataCount"),R(Bs,Is,"DataElement")]);import{PublicKey as Sw}from"@solana/web3.js";import xw from"decimal.js";import{TOKEN_PROGRAM_ID as Rw}from"@solana/spl-token";import{PublicKey as Pw}from"@solana/web3.js";var kw=Q("Raydium_liquidity_serum");import nT from"bn.js";import iT from"decimal.js";import{TOKEN_PROGRAM_ID as ok}from"@solana/spl-token";import{PublicKey as rk}from"@solana/web3.js";import sk from"bn.js";import{SystemProgram as Gw,SYSVAR_RENT_PUBKEY as zw,Transaction as Xw,TransactionInstruction as Yw}from"@solana/web3.js";import{createInitializeAccountInstruction as Zw,TOKEN_PROGRAM_ID as Hw}from"@solana/spl-token";function Ss(a="accountFlags"){let e=new mn(a);return e.addBoolean("initialized"),e.addBoolean("market"),e.addBoolean("openOrders"),e.addBoolean("requestQueue"),e.addBoolean("eventQueue"),e.addBoolean("bids"),e.addBoolean("asks"),e}var Ks=T([X(5),Ss("accountFlags"),m("ownAddress"),o("vaultSignerNonce"),m("baseMint"),m("quoteMint"),m("baseVault"),o("baseDepositsTotal"),o("baseFeesAccrued"),m("quoteVault"),o("quoteDepositsTotal"),o("quoteFeesAccrued"),o("quoteDustThreshold"),m("requestQueue"),m("eventQueue"),m("bids"),m("asks"),o("baseLotSize"),o("quoteLotSize"),o("feeRateBps"),o("referrerRebatesAccrued"),X(7)]);import{PublicKey as Ch}from"@solana/web3.js";import{AccountLayout as Lh,NATIVE_MINT as Oh,TOKEN_2022_PROGRAM_ID as Nh,TOKEN_PROGRAM_ID as Mh,createAssociatedTokenAccountIdempotentInstruction as Fh}from"@solana/spl-token";import xT from"bn.js";import Ms from"bn.js";var fT=new Ms(0);import wT from"bn.js";import Fs from"bn.js";var Ue=new Fs(1e6);import Uh from"bn.js";import zh from"decimal.js";import{PublicKey as XT,TransactionInstruction as YT,Keypair as ZT,SystemProgram as HT}from"@solana/web3.js";import{ASSOCIATED_TOKEN_PROGRAM_ID as $T,TOKEN_2022_PROGRAM_ID as JT,TOKEN_PROGRAM_ID as eh}from"@solana/spl-token";var NT=Buffer.from("vault_and_lp_mint_auth_seed","utf8"),MT=Buffer.from("amm_config","utf8"),FT=Buffer.from("pool","utf8"),vT=Buffer.from("pool_lp_mint","utf8"),VT=Buffer.from("pool_vault","utf8"),_T=Buffer.from("observation","utf8"),ET=Buffer.from("permission","utf8"),DT=Buffer.from("support_mint","utf8");var WT=Buffer.from("locked_liquidity","utf8");var sh=Q("Raydium_cpmm"),uh={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 Vs=T([X(8),I("bump"),Me("disableCreatePool"),le("index"),o("tradeFeeRate"),o("protocolFeeRate"),o("fundFeeRate"),o("createPoolFee"),m("protocolOwner"),m("fundOwner"),o("creatorFeeRate"),R(o(),15)]),Di=T([X(8),m("configId"),m("poolCreator"),m("vaultA"),m("vaultB"),m("mintLp"),m("mintA"),m("mintB"),m("mintProgramA"),m("mintProgramB"),m("observationId"),I("bump"),I("status"),I("lpDecimals"),I("mintDecimalA"),I("mintDecimalB"),o("lpAmount"),o("protocolFeesMintA"),o("protocolFeesMintB"),o("fundFeesMintA"),o("fundFeesMintB"),o("openTime"),o("epoch"),I("feeOn"),Me("enableCreatorFee"),R(I(),6),o("creatorFeesMintA"),o("creatorFeesMintB"),R(o(),28)]),mh=T([X(8),m("configId"),R(o(),30)]);import{PublicKey as ES,SystemProgram as DS}from"@solana/web3.js";import{createTransferInstruction as qS,TOKEN_PROGRAM_ID as US,TOKEN_2022_PROGRAM_ID as GS,createAssociatedTokenAccountIdempotentInstruction as zS,createSyncNativeInstruction as YS,createTransferCheckedInstruction as QS}from"@solana/spl-token";import eu from"bn.js";import jS from"decimal.js";import{ASSOCIATED_TOKEN_PROGRAM_ID as In,TOKEN_2022_PROGRAM_ID as Hs,TOKEN_PROGRAM_ID as js}from"@solana/spl-token";import{SystemProgram as xe,TransactionInstruction as we}from"@solana/web3.js";import xt from"bn.js";var et=T([o(),o("epoch"),I("curveType"),le("index"),o("migrateFee"),o("tradeFeeRate"),o("maxShareFeeRate"),o("minSupplyA"),o("maxLockRate"),o("minSellRateA"),o("minMigrateRateA"),o("minFundRaisingB"),m("mintB"),m("protocolFeeOwner"),m("migrateFeeOwner"),m("migrateToAmmWallet"),m("migrateToCpmmWallet"),R(o(),16)]),Ds=T([o("totalLockedAmount"),o("cliffPeriod"),o("unlockPeriod"),o("startTime"),o("totalAllocatedShare")]),Ee=T([o(),o("epoch"),I("bump"),I("status"),I("mintDecimalsA"),I("mintDecimalsB"),I("migrateType"),o("supply"),o("totalSellA"),o("virtualA"),o("virtualB"),o("realA"),o("realB"),o("totalFundRaisingB"),o("protocolFee"),o("platformFee"),o("migrateFee"),Ds.replicate("vestingSchedule"),m("configId"),m("platformId"),m("mintA"),m("mintB"),m("vaultA"),m("vaultB"),m("creator"),I("mintProgramFlag"),I("cpmmCreatorFeeOn"),o("platformVestingShare"),R(I(),54)]),vI=T([o(),o("epoch"),m("poolId"),m("beneficiary"),o("claimedAmount"),o("tokenShareAmount"),R(o(),8)]),qi=T([I("migrateType"),I("migrateCpmmFeeOn"),o("supply"),o("totalSellA"),o("totalFundRaisingB"),o("totalLockedAmount"),o("cliffPeriod"),o("unlockPeriod")]),Ws=T([o("epoch"),I("index"),m("configId"),qi.replicate("bondingCurveParam"),R(o(),50)]),pt=T([o(),o("epoch"),m("platformClaimFeeWallet"),m("platformLockNftWallet"),o("platformScale"),o("creatorScale"),o("burnScale"),o("feeRate"),R(I(),64,"name"),R(I(),256,"web"),R(I(),256,"img"),m("cpConfigId"),o("creatorFeeRate"),m("transferFeeExtensionAuth"),m("platformVestingWallet"),o("platformVestingScale"),m("platformCpCreator"),I("restrictGlobalConfig"),R(I(),107),ai(Ws,"platformCurve")]);var qs=Buffer.from("vault_auth_seed","utf8"),Us=Buffer.from("global_config","utf8"),Gs=Buffer.from("pool_vesting","utf8"),zs=Buffer.from("platform_config","utf8"),Xs=Buffer.from("platform_fee_vault_auth_seed","utf8"),Ys=Buffer.from("creator_fee_vault_auth_seed","utf8"),WI=Buffer.from("platform_global_access","utf8"),Qs=Buffer.from("platform_allow_config","utf8");function De(a){return ie([qs],a)}function ao(a,e,t,n){return ie([Us,e.toBuffer(),Zs(t),Jn(n)],a)}function St(a,e,t){return ie([Ki,e.toBuffer(),t.toBuffer()],a)}function so(a,e,t){return ie([xi,e.toBuffer(),t.toBuffer()],a)}function ft(a){return ie([Buffer.from("__event_authority","utf8")],a)}function Zs(a){let e=new ArrayBuffer(1);return new DataView(e).setUint8(0,a),new Uint8Array(e)}function uo(a,e){return ie([zs,e.toBuffer()],a)}function Kt(a,e,t){return ie([Gs,e.toBuffer(),t.toBuffer()],a)}function tt(a,e,t){return ie([e.toBuffer(),t.toBuffer()],a)}function co(a){return ie([Xs],a)}function nt(a,e,t){return ie([e.toBuffer(),t.toBuffer()],a)}function lo(a){return ie([Ys],a)}function Xt(a,e,t){return ie([Qs,e.toBuffer(),t.toBuffer()],a)}var ke={initialize:Buffer.from([175,175,109,31,13,152,155,237]),initializeV2:Buffer.from([67,153,175,39,218,16,38,32]),buyExactIn:Buffer.from([250,234,13,123,213,156,19,236]),buyExactOut:Buffer.from([24,211,116,40,105,3,153,56]),sellExactIn:Buffer.from([149,39,222,155,211,124,152,26]),sellExactOut:Buffer.from([95,200,71,34,8,9,11,166]),createVestingAccount:Buffer.from([129,178,2,13,217,172,230,218]),claimVestedToken:Buffer.from([49,33,104,30,189,157,79,35]),createPlatformConfig:Buffer.from([176,90,196,175,253,113,220,20]),claimPlatformFee:Buffer.from([156,39,208,135,76,237,61,72]),updatePlaformConfig:Buffer.from([195,60,76,129,146,45,67,143]),initializeWithToken2022:Buffer.from([37,190,126,222,44,154,171,17]),claimPlatformFeeFromVault:Buffer.from([117,241,198,168,248,218,80,29]),claimCreatorFee:Buffer.from([26,97,138,203,132,171,141,252]),updatePlatformCurveParam:Buffer.from([138,144,138,250,220,128,4,57]),removePlatformCurveParam:Buffer.from([27,30,62,169,93,224,24,145]),createPlatformVestingAccount:Buffer.from([146,71,173,69,98,19,15,106]),createPlatformAllowConfig:Buffer.from([69,71,168,7,214,250,107,102]),closePlatformAllowConfig:Buffer.from([82,205,36,216,16,6,240,215])};function Ui(a,e,t,n,i,r,s,l,c,u,d,p,P,b,f,y,g,k,B,K,C,h,S){let L=T([I("decimals"),Se("name"),Se("symbol"),Se("uri")]),x=T([o("totalLockedAmount"),o("cliffPeriod"),o("unlockPeriod"),I("cpmmCreatorFeeOn")]),O=T([I("index"),o("supply"),o("totalFundRaisingB"),I("migrateType")]),M=T([I("index"),o("supply"),o("totalSellA"),o("totalFundRaisingB"),I("migrateType")]),E=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!0,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:js,isSigner:!1,isWritable:!1},{pubkey:P,isSigner:!1,isWritable:!1},{pubkey:st,isSigner:!1,isWritable:!1},{pubkey:xe.programId,isSigner:!1,isWritable:!1},{pubkey:gt,isSigner:!1,isWritable:!1},{pubkey:ft(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];S&&E.push({pubkey:S,isSigner:!1,isWritable:!1});let W=Buffer.alloc(Buffer.from(f,"utf-8").length+Buffer.from(y,"utf-8").length+Buffer.from(g,"utf-8").length+4*3+1),V=Buffer.alloc(x.span),N=Buffer.alloc(k.type==="ConstantCurve"?M.span:O.span);return L.encode({decimals:b,name:f,symbol:y,uri:g},W),k.type==="ConstantCurve"?M.encode(q(F({index:0},k),{migrateType:k.migrateType==="amm"?0:1}),N):k.type==="FixedCurve"?O.encode(q(F({index:1},k),{migrateType:k.migrateType==="amm"?0:1}),N):k.type==="LinearCurve"&&O.encode(q(F({index:2},k),{migrateType:k.migrateType==="amm"?0:1}),N),x.encode({totalLockedAmount:B,cliffPeriod:K,unlockPeriod:C,cpmmCreatorFeeOn:h},V),new we({keys:E,programId:a,data:Buffer.from([...ke.initializeV2,...W,...N,...V])})}function Gi(a,e,t,n,i,r,s,l,c,u,d,p,P,b,f,y,g,k,B,K,C,h,S){let L=T([I("decimals"),Se("name"),Se("symbol"),Se("uri")]),x=T([o("totalLockedAmount"),o("cliffPeriod"),o("unlockPeriod"),I("cpmmCreatorFeeOn"),I("transferFeeExtensionParamsOption"),T([le("transferFeeBasePoints"),o("maxinumFee")]).replicate("transferFeeExtensionParams")]),O=T([I("index"),o("supply"),o("totalFundRaisingB"),I("migrateType")]),M=T([I("index"),o("supply"),o("totalSellA"),o("totalFundRaisingB"),I("migrateType")]),E=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!0,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:Hs,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:xe.programId,isSigner:!1,isWritable:!1},{pubkey:ft(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];S&&E.push({pubkey:S,isSigner:!1,isWritable:!1});let W=Buffer.alloc(Buffer.from(b,"utf-8").length+Buffer.from(f,"utf-8").length+Buffer.from(y,"utf-8").length+4*3+1),V=Buffer.alloc(x.span),N=Buffer.alloc(g.type==="ConstantCurve"?M.span:O.span);return L.encode({decimals:P,name:b,symbol:f,uri:y},W),g.type==="ConstantCurve"?M.encode(q(F({index:0},g),{migrateType:g.migrateType==="amm"?0:1}),N):g.type==="FixedCurve"?O.encode(q(F({index:1},g),{migrateType:g.migrateType==="amm"?0:1}),N):g.type==="LinearCurve"&&O.encode(q(F({index:2},g),{migrateType:g.migrateType==="amm"?0:1}),N),x.encode({totalLockedAmount:k,cliffPeriod:B,unlockPeriod:K,cpmmCreatorFeeOn:C,transferFeeExtensionParamsOption:h?1:0,transferFeeExtensionParams:h!=null?h:{transferFeeBasePoints:0,maxinumFee:new xt(0)}},V),new we({keys:E,programId:a,data:Buffer.from([...ke.initializeWithToken2022,...W,...N,...V])})}function mo(a,e,t,n,i,r,s,l,c,u,d,p,P,b,f,y,g,k,B,K){let C=T([o("amountB"),o("minAmountA"),o("shareFeeRate")]),h=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:P,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:ft(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];K&&h.push({pubkey:K,isSigner:!1,isWritable:!0}),h.push({pubkey:xe.programId,isSigner:!1,isWritable:!1}),h.push({pubkey:f,isSigner:!1,isWritable:!0}),h.push({pubkey:y,isSigner:!1,isWritable:!0});let S=Buffer.alloc(C.span);return C.encode({amountB:g,minAmountA:k,shareFeeRate:B!=null?B:new xt(0)},S),new we({keys:h,programId:a,data:Buffer.from([...ke.buyExactIn,...S])})}function zi(a,e,t,n,i,r,s,l,c,u,d,p,P,b,f,y,g,k,B,K){let C=T([o("amountA"),o("maxAmountB"),o("shareFeeRate")]),h=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:P,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:ft(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];K&&h.push({pubkey:K,isSigner:!1,isWritable:!0}),h.push({pubkey:xe.programId,isSigner:!1,isWritable:!1}),h.push({pubkey:f,isSigner:!1,isWritable:!0}),h.push({pubkey:y,isSigner:!1,isWritable:!0});let S=Buffer.alloc(C.span);return C.encode({amountA:g,maxAmountB:k,shareFeeRate:B!=null?B:new xt(0)},S),new we({keys:h,programId:a,data:Buffer.from([...ke.buyExactOut,...S])})}function po(a,e,t,n,i,r,s,l,c,u,d,p,P,b,f,y,g,k,B,K){let C=T([o("amountA"),o("minAmountB"),o("shareFeeRate")]),h=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:P,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:ft(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];K&&h.push({pubkey:K,isSigner:!1,isWritable:!0}),h.push({pubkey:xe.programId,isSigner:!1,isWritable:!1}),h.push({pubkey:f,isSigner:!1,isWritable:!0}),h.push({pubkey:y,isSigner:!1,isWritable:!0});let S=Buffer.alloc(C.span);return C.encode({amountA:g,minAmountB:k,shareFeeRate:B!=null?B:new xt(0)},S),new we({keys:h,programId:a,data:Buffer.from([...ke.sellExactIn,...S])})}function Xi(a,e,t,n,i,r,s,l,c,u,d,p,P,b,f,y,g,k,B,K){let C=T([o("amountB"),o("maxAmountA"),o("shareFeeRate")]),h=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:P,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:ft(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];K&&h.push({pubkey:K,isSigner:!1,isWritable:!0}),h.push({pubkey:xe.programId,isSigner:!1,isWritable:!1}),h.push({pubkey:f,isSigner:!1,isWritable:!0}),h.push({pubkey:y,isSigner:!1,isWritable:!0});let S=Buffer.alloc(C.span);return C.encode({amountB:g,maxAmountA:k,shareFeeRate:B!=null?B:new xt(0)},S),new we({keys:h,programId:a,data:Buffer.from([...ke.sellExactOut,...S])})}function fo(a,e,t,n,i,r,s,l,c){let u=T([]),d=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:xe.programId,isSigner:!1,isWritable:!1},{pubkey:In,isSigner:!1,isWritable:!1}],p=Buffer.alloc(u.span);return u.encode({},p),new we({keys:d,programId:a,data:Buffer.from([...ke.claimVestedToken,...p])})}function yo(a,e,t,n,i,r){let s=T([o("shareAmount")]),l=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:xe.programId,isSigner:!1,isWritable:!1}],c=Buffer.alloc(s.span);return s.encode({shareAmount:r},c),new we({keys:l,programId:a,data:Buffer.from([...ke.createVestingAccount,...c])})}function bo(a,e,t,n,i,r,s,l,c){let u=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:xe.programId,isSigner:!1,isWritable:!0},{pubkey:In,isSigner:!1,isWritable:!0}];return new we({keys:u,programId:a,data:ke.claimPlatformFee})}function Yi(a,e,t,n,i,r,s,l,c,u,d,p,P,b,f){let y=T([o("platformScale"),o("creatorScale"),o("burnScale"),o("feeRate"),Se("name"),Se("web"),Se("img"),o("creatorFeeRate"),o("platformVestingScale")]),g=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:xe.programId,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1}],k=Buffer.alloc(8*6+Buffer.from(p,"utf-8").length+Buffer.from(P,"utf-8").length+Buffer.from(b,"utf-8").length+4*3);return y.encode({platformScale:c.platformScale,creatorScale:c.creatorScale,burnScale:c.burnScale,feeRate:u,name:p,web:P,img:b,creatorFeeRate:d,platformVestingScale:f},k),new we({keys:g,programId:a,data:Buffer.from([...ke.createPlatformConfig,...k])})}function Qi(a,e,t,n){let i=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0}],r;if(n.type==="updateClaimFeeWallet"){let s=T([I("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:0,value:n.value},r)}else if(n.type==="updateLockNftWallet"){let s=T([I("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:1,value:n.value},r)}else if(n.type==="migrateCpLockNftScale"){let s=T([I("index"),o("platformScale"),o("creatorScale"),o("burnScale")]);r=Buffer.alloc(s.span),s.encode(F({index:2},n.value),r)}else if(n.type==="updateFeeRate"){let s=T([I("index"),o("value")]);r=Buffer.alloc(s.span),s.encode({index:3,value:n.value},r)}else if(n.type==="updateImg"||n.type==="updateName"||n.type==="updateWeb"){let s=T([I("index"),Se("value")]);r=Buffer.alloc(Buffer.from(n.value,"utf-8").length+4+1*1),n.type==="updateName"?s.encode({index:4,value:n.value},r):n.type==="updateWeb"?s.encode({index:5,value:n.value},r):n.type==="updateImg"&&s.encode({index:6,value:n.value},r)}else if(n.type==="updateCpConfigId"){i.push({pubkey:n.value,isSigner:!1,isWritable:!1});let s=T([I("index")]);r=Buffer.alloc(s.span),s.encode({index:7},r)}else if(n.type==="updateAll"){i.push({pubkey:n.value.cpConfigId,isSigner:!1,isWritable:!1});let s=T([I("index"),m("platformClaimFeeWallet"),m("platformLockNftWallet"),o("platformScale"),o("creatorScale"),o("burnScale"),o("feeRate"),Se("name"),Se("web"),Se("img"),m("transferFeeExtensionAuth"),o("creatorFeeRate"),o("platformVestingScale"),m("platformVestingWallet")]);r=Buffer.alloc(1+32+32+32+8*5+4*3+Buffer.from(n.value.name,"utf-8").length+Buffer.from(n.value.web,"utf-8").length+Buffer.from(n.value.img,"utf-8").length+32+8),s.encode({index:8,platformClaimFeeWallet:n.value.platformClaimFeeWallet,platformLockNftWallet:n.value.platformLockNftWallet,platformVestingWallet:n.value.platformVestingWallet,platformScale:n.value.migrateCpLockNftScale.platformScale,creatorScale:n.value.migrateCpLockNftScale.creatorScale,burnScale:n.value.migrateCpLockNftScale.burnScale,feeRate:n.value.feeRate,name:n.value.name,web:n.value.web,img:n.value.img,transferFeeExtensionAuth:n.value.transferFeeExtensionAuth,creatorFeeRate:n.value.creatorFeeRate,platformVestingScale:n.value.platformVestingScale},r)}else if(n.type==="updateVestingWallet"){let s=T([I("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:9,value:n.value},r)}else if(n.type==="updatePlatformVestingScale"){let s=T([I("index"),o("value")]);r=Buffer.alloc(s.span),s.encode({index:10,value:n.value},r)}else if(n.type==="updatePlatformCpCreator"){let s=T([I("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:11,value:n.value},r)}else if(n.type==="updateRestrictGlobalConfig"){let s=T([I("index"),o("value")]);r=Buffer.alloc(s.span),s.encode({index:12,value:n.value},r)}else throw Error("updateInfo params type error");return new we({keys:i,programId:a,data:Buffer.from([...ke.updatePlaformConfig,...r])})}function go(a,e,t,n,i,r,s,l){let c=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:xe.programId,isSigner:!1,isWritable:!1},{pubkey:In,isSigner:!1,isWritable:!1}];return new we({keys:c,programId:a,data:ke.claimPlatformFeeFromVault})}function Po(a,e,t,n,i,r,s){let l=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:xe.programId,isSigner:!1,isWritable:!1},{pubkey:In,isSigner:!1,isWritable:!1}];return new we({keys:l,programId:a,data:ke.claimCreatorFee})}var $I=new xt("18446744073709551615");function Zi(a,e,t,n,i,r){let s=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:xe.programId,isSigner:!1,isWritable:!1}];return new we({keys:s,programId:a,data:ke.createPlatformVestingAccount})}function Hi(a,e,t,n,i){let r=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:xe.programId,isSigner:!1,isWritable:!1}];return new we({keys:r,programId:a,data:ke.createPlatformAllowConfig})}function ji(a,e,t,n,i){let r=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0}];return new we({keys:r,programId:a,data:ke.closePlatformAllowConfig})}import{TOKEN_2022_PROGRAM_ID as $i,TOKEN_PROGRAM_ID as nB}from"@solana/spl-token";function Ji({mintAProgram:a,mintBProgram:e}){return(a.equals($i)?1<<0:0)|(e.equals($i)?1<<1:0)}import Bn from"bn.js";import Yt from"decimal.js";var ot=class{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){throw Error()}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i}){throw Error()}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){throw Error()}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:i,migrateFee:r,decimalA:s,decimalB:l}){throw Error()}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){throw Error()}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:i,migrateFee:r}){throw Error()}static buyExactIn({poolInfo:e,amount:t}){throw Error()}static buyExactOut({poolInfo:e,amount:t}){throw Error()}static sellExactIn({poolInfo:e,amount:t}){throw Error()}static sellExactOut({poolInfo:e,amount:t}){throw Error()}};var Sn=class extends ot{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new Yt(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i}){return new Yt(t.toString()).div(e.toString()).mul(10**(n-i))}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new Yt(e.virtualB.add(e.realB).toString()).div(e.virtualA.sub(e.realA).toString()).mul(10**(t-n))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:i,migrateFee:r,decimalA:s,decimalB:l}){return new Yt(i.sub(r).toString()).div(e.sub(t).sub(n).toString()).mul(10**(s-l))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){let i=e.totalSellA.sub(e.realA),r=e.totalFundRaisingB.sub(e.realB);return new Yt(e.virtualB.add(e.realB.add(r)).toString()).div(e.virtualA.sub(e.realA.add(i)).toString()).mul(10**(t-n))}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:i,migrateFee:r}){if(e.lte(n))throw Error("supply need gt total sell");let s=e.sub(n).sub(i);if(s.lte(new Bn(0)))throw Error("supplyMinusSellLocked <= 0");let l=t.sub(r);if(l.lte(new Bn(0)))throw Error("tfMinusMf <= 0");let c=l.mul(n).mul(n).div(s),u=l.mul(n).div(s).sub(t),d=c.div(u),p=t.mul(t).div(u);if(d.lt(new Bn(0))||p.lt(new Bn(0)))throw Error("invalid input 0");return{a:d,b:p,c:n}}static buyExactIn({poolInfo:e,amount:t}){return this.getAmountOut({amountIn:t,inputReserve:e.virtualB.add(e.realB),outputReserve:e.virtualA.sub(e.realA)})}static buyExactOut({poolInfo:e,amount:t}){return this.getAmountIn({amountOut:t,inputReserve:e.virtualB.add(e.realB),outputReserve:e.virtualA.sub(e.realA)})}static sellExactIn({poolInfo:e,amount:t}){return this.getAmountOut({amountIn:t,inputReserve:e.virtualA.sub(e.realA),outputReserve:e.virtualB.add(e.realB)})}static sellExactOut({poolInfo:e,amount:t}){return this.getAmountIn({amountOut:t,inputReserve:e.virtualA.sub(e.realA),outputReserve:e.virtualB.add(e.realB)})}static getAmountOut({amountIn:e,inputReserve:t,outputReserve:n}){let i=e.mul(n),r=t.add(e);return i.div(r)}static getAmountIn({amountOut:e,inputReserve:t,outputReserve:n}){let i=t.mul(e),r=n.sub(e);return dt(i,r)}};import Re from"bn.js";import tr from"decimal.js";import Kn from"bn.js";import Qt from"decimal.js";var xn=class extends ot{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new Qt(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i}){return new Qt(t.toString()).div(e.toString()).mul(10**(n-i))}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new Qt(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:i,migrateFee:r,decimalA:s,decimalB:l}){return new Qt(i.sub(r).toString()).div(e.sub(t).sub(n).toString()).mul(10**(s-l))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){let i=e.totalSellA.sub(e.realA),r=e.totalFundRaisingB.sub(e.realB);return new Qt(e.virtualB.add(e.realB).add(r).toString()).div(e.virtualA.sub(e.realA).add(i).toString()).mul(10**(t-n))}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:i,migrateFee:r}){let s=e.sub(i);if(s.lte(new Kn(0)))throw Error("invalid input 1");let l=new Kn(2).mul(t).sub(r),u=t.mul(s).div(l);if(u.lt(new Kn(0))||t.lt(new Kn(0)))throw Error("invalid input 0");return{a:u,b:t,c:u}}static buyExactIn({poolInfo:e,amount:t}){return this.getAmountOut({amountIn:t,initInput:e.virtualB,initOutput:e.virtualA})}static buyExactOut({poolInfo:e,amount:t}){return this.getAmountIn({amountOut:t,initInput:e.virtualB,initOutput:e.virtualA})}static sellExactIn({poolInfo:e,amount:t}){return this.getAmountOut({amountIn:t,initInput:e.virtualA,initOutput:e.virtualB})}static sellExactOut({poolInfo:e,amount:t}){return this.getAmountIn({amountOut:t,initInput:e.virtualA,initOutput:e.virtualB})}static getAmountOut({amountIn:e,initInput:t,initOutput:n}){return n.mul(e).div(t)}static getAmountIn({amountOut:e,initInput:t,initOutput:n}){let i=t.mul(e);return dt(i,n)}};import Ce from"bn.js";import yt from"decimal.js";import er from"bn.js";import Ao from"decimal.js";var Zt=class{static _multipler(e){return new Ao(10).pow(e)}static getPrice({priceX64:e,decimalA:t,decimalB:n}){return new Ao(e.toString()).div(this._Q64).mul(this._multipler(t)).div(this._multipler(n))}static getPriceX64({price:e,decimalA:t,decimalB:n}){let i=e.mul(this._multipler(n)).div(this._multipler(t));return new er(i.mul(this._Q64).toFixed(0))}};Zt._Q64=new Ao(new er(1).shln(64).toString());var Cn=class extends ot{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new yt(0)}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i}){return new yt(0)}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new yt(e.virtualA.mul(e.realA).toString()).div(Zt._Q64).mul(10**(t-n))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:i,migrateFee:r,decimalA:s,decimalB:l}){return new yt(i.sub(r).toString()).div(e.sub(t).sub(n).toString()).mul(10**(s-l))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){let i=e.totalSellA.sub(e.realA),r=e.totalFundRaisingB.sub(e.realB);return new yt(e.virtualB.add(e.realB).add(r).toString()).div(e.virtualA.sub(e.realA).add(i).toString()).mul(10**(t-n))}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:i,migrateFee:r}){let s=e.sub(i);if(s.lte(new Ce(0)))throw Error("supplyMinusLocked need gt 0");let l=t.mul(new Ce(3)).sub(r),u=t.mul(new Ce(2)).mul(s).div(l),d=u.mul(u),p=t.mul(new Ce(2)).mul(_e).div(d);if(!p.gt(new Ce(0)))throw Error("a need gt 0");if(!bn.gt(p))throw Error("a need lt u64 max");if(p.lt(new Ce(0))||u.lt(new Ce(0)))throw Error("invalid input 0");return{a:p,b:new Ce(0),c:u}}static buyExactIn({poolInfo:e,amount:t}){let n=e.realB.add(t),i=new Ce(2).mul(n).mul(_e).div(e.virtualA);return new Ce(new yt(i.toString()).sqrt().toFixed(0)).sub(e.realA)}static buyExactOut({poolInfo:e,amount:t}){let n=e.realA.add(t),i=n.mul(n);return dt(e.virtualA.mul(i),new Ce(2).mul(_e)).sub(e.realB)}static sellExactIn({poolInfo:e,amount:t}){let n=e.realA.sub(t),i=n.mul(n),r=dt(e.virtualA.mul(i),new Ce(2).mul(_e));return e.realB.sub(r)}static sellExactOut({poolInfo:e,amount:t}){let n=e.realB.sub(t),i=new Ce(2).mul(n).mul(_e).div(e.virtualA),r=new Ce(new yt(i.toString()).sqrt().toFixed(0));return e.realA.sub(r)}};var Oe=class{static getPoolCurvePointByPoolInfo({curveType:e,pointCount:t,poolInfo:n}){return this.getPoolCurvePointByInit({curveType:e,pointCount:t,supply:n.supply,totalFundRaising:n.totalFundRaisingB,totalSell:n.totalSellA,totalLockedAmount:n.vestingSchedule.totalLockedAmount,migrateFee:n.migrateFee,decimalA:n.mintDecimalsA,decimalB:n.mintDecimalsB})}static getPoolCurvePointByInit({curveType:e,pointCount:t,supply:n,totalFundRaising:i,totalSell:r,totalLockedAmount:s,migrateFee:l,decimalA:c,decimalB:u}){if(t<3)throw Error("point count < 3");let d=this.getCurve(e),p=d.getInitParam({supply:n,totalFundRaising:i,totalSell:r,totalLockedAmount:s,migrateFee:l}),P=d.getPoolInitPriceByInit(q(F({},p),{decimalA:c,decimalB:u})),b=i.div(new Re(t-1)),f=new Re(0),y=[{price:P,totalSellSupply:0}],{a:g,b:k}=p,B=f,K=f;for(let C=1;C<t;C++){let h=C!==t-1?b:i.sub(K),S=this.buyExactIn({poolInfo:{virtualA:g,virtualB:k,realA:B,realB:K,totalFundRaisingB:i,totalSellA:r},amountB:h,protocolFeeRate:f,platformFeeRate:f,curveType:e,shareFeeRate:f,creatorFeeRate:f,transferFeeConfigA:void 0,transferFeeConfigB:void 0,slot:0});B=B.add(S.amountA.amount),K=K.add(S.amountB);let L=this.getPrice({poolInfo:{virtualA:g,virtualB:k,realA:B,realB:K},decimalA:c,decimalB:u,curveType:e});y.push({price:L,totalSellSupply:new tr(B.toString()).div(10**c).toNumber()})}return y}static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n,curveType:i}){return this.getCurve(i).getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n})}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i,curveType:r}){return this.getCurve(r).getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i})}static getPrice({poolInfo:e,curveType:t,decimalA:n,decimalB:i}){return this.getCurve(t).getPoolPrice({poolInfo:e,decimalA:n,decimalB:i})}static getEndPrice({poolInfo:e,curveType:t,decimalA:n,decimalB:i}){return this.getCurve(t).getPoolPrice({poolInfo:e,decimalA:n,decimalB:i})}static getPoolEndPriceReal({poolInfo:e,curveType:t,decimalA:n,decimalB:i}){return this.getCurve(t).getPoolEndPriceReal({poolInfo:e,decimalA:n,decimalB:i})}static checkParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:i,decimals:r,config:s,migrateType:l}){if(Number(r)!==6)throw Error("decimals = 6");if(e.mul(s.maxLockRate).div(Ue).lt(i))throw Error("total lock amount gte max lock amount");if(e.lt(s.minSupplyA.mul(new Re(10**r))))throw Error("supply lt min supply");let u=e.mul(s.minSellRateA).div(Ue);if(n.lt(u))throw Error("invalid input");if(t.lt(s.minFundRaisingB))throw Error("total fund raising lt min fund raising");let d=e.sub(n).sub(i),p=e.mul(s.minMigrateRateA).div(Ue);if(d.lt(p))throw Error("migrate lt min migrate amoount");let P=e.sub(n).sub(i),b=new Re(new tr(P.mul(t).toString()).sqrt().toFixed(0));if(l==="amm"){let f=new Re(10).pow(new Re(r));if(b.lte(f))throw Error("check migrate lp error")}else if(l==="cpmm"){let f=new Re(100);if(b.lte(f))throw Error("check migrate lp error")}else throw Error("migrate type error")}static buyExactIn({poolInfo:e,amountB:t,protocolFeeRate:n,platformFeeRate:i,curveType:r,shareFeeRate:s,creatorFeeRate:l,transferFeeConfigA:c,transferFeeConfigB:u,slot:d}){var x;let p=zt(t,u,d),P=t.sub((x=p.fee)!=null?x:new Re(0)),b=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l}),f=this.calculateFee({amount:P,feeRate:b}),y=P.sub(f),g=this.getCurve(r),k=g.buyExactIn({poolInfo:e,amount:y}),B=e.totalSellA.sub(e.realA),K,C,h,S;if(k.gt(B)){K=B;let O=g.buyExactOut({poolInfo:e,amount:K}),M=this.calculatePreFee({postFeeAmount:O,feeRate:b});h=M.sub(O);let E=Bt(M,u,d);C=E.amount,S=E.fee}else K=k,C=t,h=f,S=p.fee;let L=this.splitFee({totalFee:h,protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l});return{amountA:zt(K,c,d),amountB:C,splitFee:L,transferFeeB:S}}static buyExactOut({poolInfo:e,amountA:t,protocolFeeRate:n,platformFeeRate:i,curveType:r,shareFeeRate:s,creatorFeeRate:l,transferFeeConfigA:c,transferFeeConfigB:u,slot:d}){let p=e.totalSellA.sub(e.realA),P=Bt(t,c,d),b=P.fee?P.amount.add(P.fee):P.amount;t.gt(p)&&(b=p);let y=this.getCurve(r).buyExactOut({poolInfo:e,amount:b}),g=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l}),k=this.calculatePreFee({postFeeAmount:y,feeRate:g}),B=k.sub(y),K=Bt(k,u,d),C=this.splitFee({totalFee:B,protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l});return{amountA:P,amountB:K.amount,splitFee:C,transferFeeB:K.fee}}static sellExactIn({poolInfo:e,amountA:t,protocolFeeRate:n,platformFeeRate:i,curveType:r,shareFeeRate:s,creatorFeeRate:l,transferFeeConfigA:c,transferFeeConfigB:u,slot:d}){var K;let p=this.getCurve(r),P=zt(t,c,d),b=P.fee?P.amount.sub(P.fee):P.amount,f=p.sellExactIn({poolInfo:e,amount:b}),y=this.calculateFee({amount:f,feeRate:this.totalFeeRate({protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l})}),g=this.splitFee({totalFee:y,protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l}),k=f.sub(y),B=zt(k,u,d);return{amountA:P,amountB:k.sub((K=B.fee)!=null?K:new Re(0)),splitFee:g,transferFeeB:B.fee}}static sellExactOut({poolInfo:e,amountB:t,protocolFeeRate:n,platformFeeRate:i,curveType:r,shareFeeRate:s,creatorFeeRate:l,transferFeeConfigA:c,transferFeeConfigB:u,slot:d}){let p=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l}),P=Bt(t,u,d),b=P.amount,f=this.calculatePreFee({postFeeAmount:b,feeRate:p});if(e.realB.lt(f))throw Error("Insufficient liquidity");let y=f.sub(b),k=Oe.getCurve(r).sellExactOut({poolInfo:e,amount:f});if(k.gt(e.realA))throw Error();let B=this.splitFee({totalFee:y,protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l});return{amountA:Bt(k,c,d),amountB:t,splitFee:B,transferFeeB:P.fee}}static splitFee({totalFee:e,protocolFeeRate:t,platformFeeRate:n,shareFeeRate:i,creatorFeeRate:r}){let s=this.totalFeeRate({protocolFeeRate:t,platformFeeRate:n,shareFeeRate:i,creatorFeeRate:r}),l=s.isZero()?new Re(0):e.mul(n).div(s),c=s.isZero()?new Re(0):e.mul(i).div(s),u=s.isZero()?new Re(0):e.mul(r).div(s),d=e.sub(l).sub(c).sub(u);return{platformFee:l,shareFee:c,protocolFee:d,creatorFee:u}}static calculateFee({amount:e,feeRate:t}){return ro(e,t,Ue)}static calculatePreFee({postFeeAmount:e,feeRate:t}){if(t.isZero())return e;let n=e.mul(Ue),i=Ue.sub(t);return n.add(i).sub(new Re(1)).div(i)}static totalFeeRate({protocolFeeRate:e,platformFeeRate:t,shareFeeRate:n,creatorFeeRate:i}){if(e.add(t).add(n).add(i).gt(new Re(1e6)))throw Error("total fee rate gt 1_000_000");return e.add(t).add(n).add(i)}static getCurve(e){switch(e){case 0:return Sn;case 1:return xn;case 2:return Cn}throw Error("find curve error")}};var $s={[gi.toBase58()]:3};var Js=T([X(5),X(8),m("ownAddress"),o("vaultSignerNonce"),m("baseMint"),m("quoteMint"),m("baseVault"),o("baseDepositsTotal"),o("baseFeesAccrued"),m("quoteVault"),o("quoteDepositsTotal"),o("quoteFeesAccrued"),o("quoteDustThreshold"),m("requestQueue"),m("eventQueue"),m("bids"),m("asks"),o("baseLotSize"),o("quoteLotSize"),o("feeRateBps"),o("referrerRebatesAccrued"),X(7)]);import{PublicKey as oS}from"@solana/web3.js";var uS=Q("Serum");import{ASSOCIATED_TOKEN_PROGRAM_ID as gS,TOKEN_2022_PROGRAM_ID as PS,TOKEN_PROGRAM_ID as AS}from"@solana/spl-token";import{PublicKey as kS,SystemProgram as TS,TransactionInstruction as hS}from"@solana/web3.js";import BS from"bn.js";var KK=new eu(0);import{PublicKey as tu,Transaction as wo,TransactionInstruction as nu}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as ou}from"@solana/spl-token";import nr from"bn.js";var Te=class extends Be{static getPdaPoolId(e,t){return ie([Te.SEED_CONFIG.pool.id,t.toBuffer()],e)}static getPdaOwnerId(e,t,n,i){return ie([Te.SEED_CONFIG.owner.id,t.toBuffer(),n.toBuffer(),Buffer.from(new nr(i).toArray())],e)}static async getAllInfo({connection:e,programId:t,poolIds:n,wallet:i,chainTime:r}){if(n.length===0)return[];let s=n.map(d=>Te.getPdaPoolId(t,d).publicKey),l=[];for(let d=0;d<Te.VERSION_PROJECT.length;d++)l.push(...s.map(p=>Te.getPdaOwnerId(t,p,i,d).publicKey));let c=await Ge(e,[...s,...l]),u=[];for(let d=0;d<c.length;d++){let p=Math.floor(d/n.length),P=d%n.length,b=s[P],f=l[d],y=c[P],g=c[n.length+d];if(!(y&&g)||y.data.length!==Te.POOL_LAYOUT.span||g.data.length!==Te.OWNER_LAYOUT.span)continue;let k=Te.POOL_LAYOUT.decode(y.data),B=Te.OWNER_LAYOUT.decode(g.data),K=k.openTime.toNumber(),C=k.endTime.toNumber(),h=B.tokenInfo.map(x=>x.debtAmount.gt(new nr(0))).filter(x=>!x).length!==3,S=r>K&&r<C&&k.status===1,L=h&&S;u.push({programId:t,poolId:b,ammId:k.ammId,ownerAccountId:f,snapshotLpAmount:B.lpAmount,project:Te.VERSION_PROJECT[p],openTime:K,endTime:C,canClaim:L,canClaimErrorType:h?S?void 0:"outOfOperationalTime":"alreadyClaimIt",tokenInfo:k.tokenInfo.map((x,O)=>({mintAddress:x.mintAddress,mintVault:x.mintVault,mintDecimals:x.mintDecimals,perLpLoss:x.perLpLoss,debtAmount:B.tokenInfo[O].debtAmount.add(B.tokenInfo[O].claimedAmount)}))})}return u}async makeClaimTransaction({poolInfo:e,ownerInfo:t,feePayer:n}){t.wallet||this.scope.checkOwner();let i=this.createTxBuilder(n),r=t.wallet||this.scope.ownerPubKey,s=[];for(let u of e.tokenInfo){let{account:d,instructionParams:p}=await this.scope.account.getOrCreateTokenAccount({mint:u.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:u.mintAddress.equals(Pe.WSOL.mint),createInfo:{payer:r,amount:0},skipCloseAccount:!u.mintAddress.equals(Pe.WSOL.mint),associatedOnly:u.mintAddress.equals(Pe.WSOL.mint)?!1:t.associatedOnly});p&&i.addInstruction(p),s.push(d)}i.addInstruction({instructions:[Te.makeClaimInstruction({programId:e.programId,poolInfo:e,ownerInfo:{wallet:r,ownerPda:e.ownerAccountId,claimAddress:s}})]});let{transaction:l,signers:c}=i.build();return[{transaction:l,signer:c}]}async makeClaimAllTransaction({poolInfos:e,ownerInfo:t,feePayer:n}){let i=this.createTxBuilder(n),r=t.wallet||this.scope.ownerPubKey,s={};for(let d of e){let p=[];for(let P of d.tokenInfo){let{account:b,instructionParams:f}=await this.scope.account.getOrCreateTokenAccount({mint:P.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:P.mintAddress.equals(Pe.WSOL.mint),createInfo:{payer:r,amount:0},skipCloseAccount:!P.mintAddress.equals(Pe.WSOL.mint),associatedOnly:P.mintAddress.equals(Pe.WSOL.mint)?!1:t.associatedOnly});f&&i.addInstruction(f),b&&(s[P.mintAddress.toString()]=b,p.push(b))}i.addInstruction({instructions:[Te.makeClaimInstruction({programId:d.programId,poolInfo:d,ownerInfo:{wallet:r,ownerPda:d.ownerAccountId,claimAddress:p}})]})}let{transaction:l,signers:c}=i.build(),u=i.allInstructions;return Qn(u,[r,...c.map(d=>d.publicKey)])?[{transaction:l,signer:c}]:[{transaction:new wo().add(...u.slice(0,i.AllTxData.instructions.length-1)),signer:c},{transaction:new wo().add(...u.slice(i.AllTxData.instructions.length-1)),signer:[]},{transaction:new wo().add(...i.AllTxData.endInstructions),signer:[]}]}static makeClaimInstruction({programId:e,poolInfo:t,ownerInfo:n}){let i=T([]),r=[{pubkey:n.wallet,isSigner:!0,isWritable:!0},{pubkey:t.poolId,isSigner:!1,isWritable:!0},{pubkey:n.ownerPda,isSigner:!1,isWritable:!0},...n.claimAddress.map(c=>({pubkey:c,isSigner:!1,isWritable:!0})),...t.tokenInfo.map(({mintVault:c})=>({pubkey:c,isSigner:!1,isWritable:!0})),{pubkey:ou,isSigner:!1,isWritable:!1}],s=Buffer.alloc(i.span);i.encode({},s);let l=Buffer.from([10,66,208,184,161,6,191,98,...s]);return new nu({keys:r,programId:e,data:l})}},We=Te;We.CLAIMED_NUM=3,We.POOL_LAYOUT=T([X(8),I("bump"),I("status"),o("openTime"),o("endTime"),m("ammId"),R(T([I("mintDecimals"),m("mintAddress"),m("mintVault"),o("perLpLoss"),o("totalClaimedAmount")]),Te.CLAIMED_NUM,"tokenInfo"),R(o(),10,"padding")]),We.OWNER_LAYOUT=T([X(8),I("bump"),I("version"),m("poolId"),m("owner"),o("lpAmount"),R(T([m("mintAddress"),o("debtAmount"),o("claimedAmount")]),Te.CLAIMED_NUM,"tokenInfo"),R(o(),4,"padding")]),We.DEFAULT_POOL_ID=["58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2","6UmmUiYoBjSrhakAobJw8BvkmJtDVxaeBtbt7rxWo1mg","AVs9TA4nWDzfPJE9gGVNJMVhcQy3V9PGazuz33BfG2RA","DVa7Qmb5ct9RCpaU7UTpSaf3GVMYz17vNVU67XpdCRut","7XawhbbxtsRcQA8KTkHT9f9nc6d69UwqCDh6U5EEbEmX","6a1CsrpeZubDjEJE9s1CMVheB6HWM5d7m1cj2jkhyXhj","EoNrn8iUhwgJySD1pHu8Qxm5gSQqLK3za4m8xzD2RuEb","AceAyRTWt4PyB2pHqf2qhDgNZDtKVNaxgL8Ru3V4aN1P","6tmFJbMk5yVHFcFy7X2K8RwHjKLr6KVFLYXpgpBNeAxB"].map(e=>new tu(e)),We.SEED_CONFIG={pool:{id:Buffer.from("pool_seed","utf8")},owner:{id:Buffer.from("user_claim_seed","utf8")}},We.VERSION_PROJECT=[void 0,"Francium","Tulip","Larix"];import{PublicKey as GK}from"@solana/web3.js";import{getTransferFeeConfig as XK,MintLayout as YK,TOKEN_2022_PROGRAM_ID as QK,TOKEN_PROGRAM_ID as ZK,unpackMint as HK}from"@solana/spl-token";var hC=new it(2),IC=new it(3),BC=new it(5),Ar=new it(10),SC=new it(100),KC=new it(1e3),xC=new it(1e4);function ro(a,e,t){return a.mul(e).add(t).sub(new it(1)).div(t)}function ko(a,e=1,t=[]){let n=[...a];if(e<=0)return t;for(;n.length;)t.push(n.splice(0,e));return t}import{MINT_SIZE as oR,TOKEN_PROGRAM_ID as iR,getTransferFeeConfig as rR,unpackMint as aR}from"@solana/spl-token";var To=Q("Raydium_accountInfo_util");async function Ge(a,e,t){let{batchRequest:n,commitment:i="confirmed",chunkCount:r=100}=F({batchRequest:!1},t),s=ko(e,r),l=new Array(s.length).fill([]);if(n){let c=s.map(p=>{let P=a._buildArgs([p.map(b=>b.toBase58())],i,"base64");return{methodName:"getMultipleAccounts",args:P}}),u=ko(c,10);l=(await(await Promise.all(u.map(async p=>await a._rpcBatchRequest(p)))).flat()).map(p=>(p.error&&To.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${p.error.message}`),p.result.value.map(P=>{if(P){let{data:b,executable:f,lamports:y,owner:g,rentEpoch:k}=P;return b.length!==2&&b[1]!=="base64"&&To.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(b[0],"base64"),executable:f,lamports:y,owner:new iu(g),rentEpoch:k}}return null})))}else try{l=await Promise.all(s.map(c=>a.getMultipleAccountsInfo(c,i)))}catch(c){c instanceof Error&&To.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${c.message}`)}return l.flat()}async function Ke(a,e,t){let n=await Ge(a,e.map(i=>i.pubkey),t);return e.map((i,r)=>q(F({},i),{accountInfo:n[r]}))}async function Io({connection:a,address:e,cluster:t="mainnet"}){let n=await Ge(a,[...new Set(e.map(r=>r.toString()))].map(r=>new ho(r))),i={};for(let r=0;r<e.length;r++){let s=n[r],l=e[r];if(!s)continue;let c=new Lt({key:l,state:Lt.deserialize(s.data)});i[l.toString()]=c,t==="devnet"?Rt[l.toString()]=c:Ct[l.toString()]=c}return i}var Ct={},Bo=async a=>{let e="AcL1Vo8oy1ULiavEcjSUcwfBSForXMudcZvDZy5nzJkU";if(Ct[e])return Ct;let t=new ho(e),n=await a.getAccountInfo(t);return n&&(Ct[e]=new Lt({key:t,state:Lt.deserialize(n.data)})),Ct},Rt={},So=async a=>{let e="EFhMuDw1PKEuckuFRW9PavNfTH4LKP5uKHgyXDmWpFCq";if(Rt[e])return Rt;let t=new ho(e),n=await a.getAccountInfo(t);return n&&(Rt[e]=new Lt({key:t,state:Lt.deserialize(n.data)})),Rt};var Ln=2e3,On=class{constructor(e){this.instructions=[];this.endInstructions=[];this.lookupTableAddress=[];this.signers=[];this.instructionTypes=[];this.endInstructionTypes=[];this.connection=e.connection,this.feePayer=e.feePayer,this.signAllTransactions=e.signAllTransactions,this.owner=e.owner,this.cluster=e.cluster,this.blockhashCommitment=e.blockhashCommitment,this.loopMultiTxStatus=!!e.loopMultiTxStatus}get AllTxData(){return{instructions:this.instructions,endInstructions:this.endInstructions,signers:this.signers,instructionTypes:this.instructionTypes,endInstructionTypes:this.endInstructionTypes,lookupTableAddress:this.lookupTableAddress}}get allInstructions(){return[...this.instructions,...this.endInstructions]}async getComputeBudgetConfig(){var n;let e=(await au.get(`https://solanacompass.com/api/fees?cacheFreshTime=${3e5}`)).data,{avg:t}=(n=e==null?void 0:e[15])!=null?n:{};if(!!t)return{units:6e5,microLamports:Math.min(Math.ceil(t*1e6/6e5),25e3)}}addCustomComputeBudget(e){if(e){let{instructions:t,instructionTypes:n}=fn(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...n),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(ru.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new Ot(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(pe.TransferTip),!0):!1}async calComputeBudget({config:e,defaultIns:t}){try{let n=e||await this.getComputeBudgetConfig();if(this.addCustomComputeBudget(n))return;t&&this.instructions.unshift(...t)}catch{t&&this.instructions.unshift(...t)}}addInstruction({instructions:e=[],endInstructions:t=[],signers:n=[],instructionTypes:i=[],endInstructionTypes:r=[],lookupTableAddress:s=[]}){return this.instructions.push(...e),this.endInstructions.push(...t),this.signers.push(...n),this.instructionTypes.push(...i),this.endInstructionTypes.push(...r),this.lookupTableAddress.push(...s.filter(l=>l!==Ot.default.toString())),this}async versionBuild({txVersion:e,extInfo:t,lookupTableAddress:n}){return e===0?await this.buildV0(q(F({},t||{}),{lookupTableAddress:n})):this.build(t)}build(e){var n;let t=new Ht;return this.allInstructions.length&&t.add(...this.allInstructions),t.feePayer=this.feePayer,((n=this.owner)==null?void 0:n.signer)&&!this.signers.some(i=>i.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer),{builder:this,transaction:t,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async i=>{var d;let{recentBlockHash:r,skipPreflight:s=!0,sendAndConfirm:l,notSendToRpc:c}=i||{},u=r!=null?r:await At(this.connection,this.blockhashCommitment);if(t.recentBlockhash=u,this.signers.length&&t.sign(...this.signers),lt([t]),(d=this.owner)!=null&&d.isKeyPair)return{txId:l?await Ko(this.connection,t,this.signers.find(P=>P.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:s}):await this.connection.sendRawTransaction(t.serialize(),{skipPreflight:s}),signedTx:t};if(this.signAllTransactions){let p=await this.signAllTransactions([t]);if(this.signers.length)for(let P of p)try{P.sign(...this.signers)}catch{}return{txId:c?"":await this.connection.sendRawTransaction(p[0].serialize(),{skipPreflight:s}),signedTx:p[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:e||{}}}buildMultiTx(e){var u;let{extraPreBuildData:t=[],extInfo:n}=e,{transaction:i}=this.build(n),r=t.filter(d=>d.transaction.instructions.length>0),s=[i,...r.map(d=>d.transaction)],l=[this.signers,...r.map(d=>d.signers)],c=[...this.instructionTypes,...r.map(d=>d.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&l.forEach(d=>{d.some(p=>p.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:s,signers:l,instructionTypes:c,execute:async d=>{var k;let{sequentially:p,onTxUpdate:P,skipTxCount:b=0,recentBlockHash:f,skipPreflight:y=!0}=d||{},g=f!=null?f:await At(this.connection,this.blockhashCommitment);if((k=this.owner)!=null&&k.isKeyPair){if(p){let B=[],K=0;for(let C of s){if(++K,K<=b)continue;let h=await Ko(this.connection,C,this.signers.find(S=>S.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:y});B.push(h)}return{txIds:B,signedTxs:s}}return{txIds:await await Promise.all(s.map(async B=>(B.recentBlockhash=g,await this.connection.sendRawTransaction(B.serialize(),{skipPreflight:y})))),signedTxs:s}}if(this.signAllTransactions){let B=s.map((C,h)=>(C.recentBlockhash=g,l[h].length&&C.sign(...l[h]),C));lt(B);let K=await this.signAllTransactions(B);if(p){let C=0,h=[],S=async()=>{if(!K[C])return;let L=await this.connection.sendRawTransaction(K[C].serialize(),{skipPreflight:y});h.push({txId:L,status:"sent",signedTx:K[C]}),P==null||P([...h]),C++;let x=!1,O=null,M=null,E=W=>{O!==null&&clearInterval(O),M!==null&&this.connection.removeSignatureListener(M);let V=h.findIndex(N=>N.txId===L);if(V>-1){if(h[V].status==="error"||h[V].status==="success")return;h[V].status=W.err?"error":"success"}P==null||P([...h]),W.err||S()};this.loopMultiTxStatus&&(O=setInterval(async()=>{var W;if(x){clearInterval(O);return}try{let V=await this.connection.getTransaction(L,{commitment:"confirmed",maxSupportedTransactionVersion:0});V&&(x=!0,clearInterval(O),E({err:((W=V.meta)==null?void 0:W.err)||null}),console.log("tx status from getTransaction:",L))}catch(V){x=!0,clearInterval(O),console.error("getTransaction timeout:",V,L)}},Ln)),M=this.connection.onSignature(L,W=>{if(x){this.connection.removeSignatureListener(M);return}x=!0,E(W)},"confirmed"),this.connection.getSignatureStatus(L)};return await S(),{txIds:h.map(L=>L.txId),signedTxs:K}}else{let C=[];for(let h=0;h<K.length;h+=1){let S=await this.connection.sendRawTransaction(K[h].serialize(),{skipPreflight:y});C.push(S)}return{txIds:C,signedTxs:K}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:n||{}}}async versionMultiBuild({extraPreBuildData:e,txVersion:t,extInfo:n}){return t===0?await this.buildV0MultiTx({extraPreBuildData:e,buildProps:n||{}}):this.buildMultiTx({extraPreBuildData:e,extInfo:n})}async buildV0(e){var y;let f=e||{},{lookupTableCache:t={},lookupTableAddress:n=[],forerunCreate:i,recentBlockhash:r}=f,s=ve(f,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),l=F(F({},this.cluster==="devnet"?await So(this.connection):await Bo(this.connection)),t),c=Array.from(new Set([...n,...this.lookupTableAddress])),u=[];for(let g of c)l[g]===void 0&&u.push(new Ot(g));let d=await Io({connection:this.connection,address:u});for(let[g,k]of Object.entries(d))l[g]=k;let p=i?Ot.default.toBase58():r!=null?r:await At(this.connection,this.blockhashCommitment),P=new jt({payerKey:this.feePayer,recentBlockhash:p,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(l));((y=this.owner)==null?void 0:y.signer)&&!this.signers.some(g=>g.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let b=new $t(P);return b.sign(this.signers),{builder:this,transaction:b,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async g=>{var C;let{skipPreflight:k=!0,sendAndConfirm:B,notSendToRpc:K}=g||{};if(lt([b]),(C=this.owner)!=null&&C.isKeyPair){let h=await this.connection.sendTransaction(b,{skipPreflight:k});return B&&await yn(this.connection,h),{txId:h,signedTx:b}}if(this.signAllTransactions){let h=await this.signAllTransactions([b]);if(this.signers.length)for(let S of h)try{S.sign(this.signers)}catch{}return{txId:K?"":await this.connection.sendTransaction(h[0],{skipPreflight:k}),signedTx:h[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:s||{}}}async buildV0MultiTx(e){var u;let{extraPreBuildData:t=[],buildProps:n}=e,{transaction:i}=await this.buildV0(n),r=t.filter(d=>d.builder.instructions.length>0),s=[i,...r.map(d=>d.transaction)],l=[this.signers,...r.map(d=>d.signers)],c=[...this.instructionTypes,...r.map(d=>d.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&l.forEach(d=>{d.some(p=>p.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),s.forEach(async(d,p)=>{d.sign(l[p])}),{builder:this,transactions:s,signers:l,instructionTypes:c,buildProps:n,execute:async d=>{var y;let{sequentially:p,onTxUpdate:P,recentBlockHash:b,skipPreflight:f=!0}=d||{};if(b&&s.forEach(g=>g.message.recentBlockhash=b),lt(s),(y=this.owner)!=null&&y.isKeyPair){if(p){let g=[];for(let k of s){let B=await this.connection.sendTransaction(k,{skipPreflight:f});await yn(this.connection,B),g.push(B)}return{txIds:g,signedTxs:s}}return{txIds:await Promise.all(s.map(async g=>await this.connection.sendTransaction(g,{skipPreflight:f}))),signedTxs:s}}if(this.signAllTransactions){let g=await this.signAllTransactions(s);if(p){let k=0,B=[],K=async()=>{if(!g[k])return;let C=await this.connection.sendTransaction(g[k],{skipPreflight:f});B.push({txId:C,status:"sent",signedTx:g[k]}),P==null||P([...B]),k++;let h=!1,S=null,L=null,x=O=>{S!==null&&clearInterval(S),L!==null&&this.connection.removeSignatureListener(L);let M=B.findIndex(E=>E.txId===C);if(M>-1){if(B[M].status==="error"||B[M].status==="success")return;B[M].status=O.err?"error":"success"}P==null||P([...B]),O.err||K()};this.loopMultiTxStatus&&(S=setInterval(async()=>{var O;if(h){clearInterval(S);return}try{let M=await this.connection.getTransaction(C,{commitment:"confirmed",maxSupportedTransactionVersion:0});M&&(h=!0,clearInterval(S),x({err:((O=M.meta)==null?void 0:O.err)||null}),console.log("tx status from getTransaction:",C))}catch(M){h=!0,clearInterval(S),console.error("getTransaction timeout:",M,C)}},Ln)),L=this.connection.onSignature(C,O=>{if(h){this.connection.removeSignatureListener(L);return}h=!0,x(O)},"confirmed"),this.connection.getSignatureStatus(C)};return K(),{txIds:[],signedTxs:g}}else{let k=[];for(let B=0;B<g.length;B+=1){let K=await this.connection.sendTransaction(g[B],{skipPreflight:f});k.push(K)}return{txIds:k,signedTxs:g}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:n||{}}}async sizeCheckBuild(e){var P;let p=e||{},{splitIns:t=[],computeBudgetConfig:n}=p,i=ve(p,["splitIns","computeBudgetConfig"]),r=n?fn(n):{instructions:[],instructionTypes:[]},s=this.signers.reduce((b,f)=>q(F({},b),{[f.publicKey.toBase58()]:f}),{}),l=[],c=[],u=[],d=0;if(this.allInstructions.forEach(b=>{let f=[...u,b],y=n?[...r.instructions,...f]:f,k=[...new Set(f.map(B=>B.keys.filter(K=>K.isSigner).map(K=>K.pubkey.toString())).flat()).values()].map(B=>new Ot(B));if(b!==t[d]&&u.length<12&&(_t({instructions:y,payer:this.feePayer,signers:k})||_t({instructions:f,payer:this.feePayer,signers:k})))u.push(b);else{if(u.length===0)throw Error("item ins too big");d+=b===t[d]?1:0,_t({instructions:n?[...r.instructions,...u]:[...u],payer:this.feePayer,signers:k})?l.push(new Ht().add(...r.instructions,...u)):l.push(new Ht().add(...u)),c.push(Array.from(new Set(u.map(B=>B.keys.filter(K=>K.isSigner).map(K=>K.pubkey.toString())).flat())).map(B=>s[B]).filter(B=>B!==void 0)),u=[b]}}),u.length>0){let f=[...new Set(u.map(y=>y.keys.filter(g=>g.isSigner).map(g=>g.pubkey.toString())).flat()).values()].map(y=>s[y]).filter(y=>y!==void 0);_t({instructions:n?[...r.instructions,...u]:[...u],payer:this.feePayer,signers:f.map(y=>y.publicKey)})?l.push(new Ht().add(...r.instructions,...u)):l.push(new Ht().add(...u)),c.push(f)}return l.forEach(b=>b.feePayer=this.feePayer),(P=this.owner)!=null&&P.signer&&c.forEach(b=>{b.some(f=>f.publicKey.equals(this.owner.publicKey))||b.push(this.owner.signer)}),{builder:this,transactions:l,signers:c,instructionTypes:this.instructionTypes,execute:async b=>{var C;let{sequentially:f,onTxUpdate:y,skipTxCount:g=0,recentBlockHash:k,skipPreflight:B=!0}=b||{},K=k!=null?k:await At(this.connection,this.blockhashCommitment);if(l.forEach(async(h,S)=>{h.recentBlockhash=K,c[S].length&&h.sign(...c[S])}),lt(l),(C=this.owner)!=null&&C.isKeyPair){if(f){let h=0,S=[];for(let L of l){if(++h,h<=g){S.push("tx skipped");continue}let x=await Ko(this.connection,L,this.signers.find(O=>O.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:B});S.push(x)}return{txIds:S,signedTxs:l}}return{txIds:await Promise.all(l.map(async h=>await this.connection.sendRawTransaction(h.serialize(),{skipPreflight:B}))),signedTxs:l}}if(this.signAllTransactions){let h=await this.signAllTransactions(l.slice(g,l.length)),S=[...l.slice(0,g),...h];if(f){let L=0,x=[],O=async()=>{if(!S[L])return;L<g&&(x.push({txId:"",status:"success",signedTx:S[L]}),y==null||y([...x]),L++,O());let M=await this.connection.sendRawTransaction(S[L].serialize(),{skipPreflight:B});x.push({txId:M,status:"sent",signedTx:S[L]}),y==null||y([...x]),L++;let E=!1,W=null,V=null,N=z=>{W!==null&&clearInterval(W),V!==null&&this.connection.removeSignatureListener(V);let j=x.findIndex(J=>J.txId===M);if(j>-1){if(x[j].status==="error"||x[j].status==="success")return;x[j].status=z.err?"error":"success"}y==null||y([...x]),z.err||O()};this.loopMultiTxStatus&&(W=setInterval(async()=>{var z;if(E){clearInterval(W);return}try{let j=await this.connection.getTransaction(M,{commitment:"confirmed",maxSupportedTransactionVersion:0});j&&(E=!0,clearInterval(W),N({err:((z=j.meta)==null?void 0:z.err)||null}),console.log("tx status from getTransaction:",M))}catch(j){E=!0,clearInterval(W),console.error("getTransaction timeout:",j,M)}},Ln)),V=this.connection.onSignature(M,z=>{if(E){this.connection.removeSignatureListener(V);return}E=!0,N(z)},"confirmed"),this.connection.getSignatureStatus(M)};return await O(),{txIds:x.map(M=>M.txId),signedTxs:S}}else{let L=[];for(let x=0;x<S.length;x+=1){let O=await this.connection.sendRawTransaction(S[x].serialize(),{skipPreflight:B});L.push(O)}return{txIds:L,signedTxs:S}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:i||{}}}async sizeCheckBuildV0(e){var C;let K=e||{},{computeBudgetConfig:t,splitIns:n=[],lookupTableCache:i={},lookupTableAddress:r=[],insCountLimit:s=12}=K,l=ve(K,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress","insCountLimit"]),c=F(F({},this.cluster==="devnet"?await So(this.connection):await Bo(this.connection)),i),u=Array.from(new Set([...this.lookupTableAddress,...r])),d=[];for(let h of u)c[h]===void 0&&d.push(new Ot(h));let p=await Io({connection:this.connection,address:d});for(let[h,S]of Object.entries(p))c[h]=S;let P=t?fn(t):{instructions:[],instructionTypes:[]},b=await At(this.connection,this.blockhashCommitment),f=this.signers.reduce((h,S)=>q(F({},h),{[S.publicKey.toBase58()]:S}),{}),y=[],g=[],k=[],B=0;if(this.allInstructions.forEach(h=>{let S=[...k,h],L=t?[...P.instructions,...S]:S;if(h!==n[B]&&k.length<s&&(Et({instructions:L,payer:this.feePayer,lookupTableAddressAccount:c})||Et({instructions:S,payer:this.feePayer,lookupTableAddressAccount:c})))k.push(h);else{if(k.length===0)throw Error("item ins too big");B+=h===n[B]?1:0;let x={};for(let O of[...new Set(u)])c[O]!==void 0&&(x[O]=c[O]);if(t&&Et({instructions:[...P.instructions,...k],payer:this.feePayer,lookupTableAddressAccount:c,recentBlockhash:b})){let O=new jt({payerKey:this.feePayer,recentBlockhash:b,instructions:[...P.instructions,...k]}).compileToV0Message(Object.values(c));y.push(new $t(O))}else{let O=new jt({payerKey:this.feePayer,recentBlockhash:b,instructions:[...k]}).compileToV0Message(Object.values(c));y.push(new $t(O))}g.push(Array.from(new Set(k.map(O=>O.keys.filter(M=>M.isSigner).map(M=>M.pubkey.toString())).flat())).map(O=>f[O]).filter(O=>O!==void 0)),k=[h]}}),k.length>0){let S=[...new Set(k.map(L=>L.keys.filter(x=>x.isSigner).map(x=>x.pubkey.toString())).flat()).values()].map(L=>f[L]).filter(L=>L!==void 0);if(t&&Et({instructions:[...P.instructions,...k],payer:this.feePayer,lookupTableAddressAccount:c,recentBlockhash:b})){let L=new jt({payerKey:this.feePayer,recentBlockhash:b,instructions:[...P.instructions,...k]}).compileToV0Message(Object.values(c));y.push(new $t(L))}else{let L=new jt({payerKey:this.feePayer,recentBlockhash:b,instructions:[...k]}).compileToV0Message(Object.values(c));y.push(new $t(L))}g.push(S)}return(C=this.owner)!=null&&C.signer&&g.forEach(h=>{h.some(S=>S.publicKey.equals(this.owner.publicKey))||h.push(this.owner.signer)}),y.forEach((h,S)=>{h.sign(g[S])}),{builder:this,transactions:y,buildProps:e,signers:g,instructionTypes:this.instructionTypes,execute:async h=>{var E;let{sequentially:S,onTxUpdate:L,skipTxCount:x=0,recentBlockHash:O,skipPreflight:M=!0}=h||{};if(y.map(async(W,V)=>{g[V].length&&W.sign(g[V]),O&&(W.message.recentBlockhash=O)}),lt(y),(E=this.owner)!=null&&E.isKeyPair){if(S){let W=0,V=[];for(let N of y){if(++W,W<=x){console.log("skip tx: ",W),V.push("tx skipped");continue}let z=await this.connection.sendTransaction(N,{skipPreflight:M});await yn(this.connection,z),V.push(z)}return{txIds:V,signedTxs:y}}return{txIds:await Promise.all(y.map(async W=>await this.connection.sendTransaction(W,{skipPreflight:M}))),signedTxs:y}}if(this.signAllTransactions){let W=await this.signAllTransactions(y.slice(x,y.length)),V=[...y.slice(0,x),...W];if(S){let N=0,z=[],j=async()=>{if(!V[N])return;if(N<x){z.push({txId:"",status:"success",signedTx:V[N]}),L==null||L([...z]),N++,j();return}let J=await this.connection.sendTransaction(V[N],{skipPreflight:M});z.push({txId:J,status:"sent",signedTx:V[N]}),L==null||L([...z]),N++;let Y=!1,ee=null,v=null,te=se=>{ee!==null&&clearInterval(ee),v!==null&&this.connection.removeSignatureListener(v);let $=z.findIndex(de=>de.txId===J);if($>-1){if(z[$].status==="error"||z[$].status==="success")return;z[$].status=se.err?"error":"success"}L==null||L([...z]),se.err||j()};this.loopMultiTxStatus&&(ee=setInterval(async()=>{var se;if(Y){clearInterval(ee);return}try{let $=await this.connection.getTransaction(J,{commitment:"confirmed",maxSupportedTransactionVersion:0});$&&(Y=!0,clearInterval(ee),te({err:((se=$.meta)==null?void 0:se.err)||null}),console.log("tx status from getTransaction:",J))}catch($){Y=!0,clearInterval(ee),console.error("getTransaction timeout:",$,J)}},Ln)),v=this.connection.onSignature(J,se=>{if(Y){this.connection.removeSignatureListener(v);return}Y=!0,te(se)},"confirmed"),this.connection.getSignatureStatus(J)};return j(),{txIds:[],signedTxs:V}}else{let N=[];for(let z=0;z<V.length;z+=1){let j=await this.connection.sendTransaction(V[z],{skipPreflight:M});N.push(j)}return{txIds:N,signedTxs:V}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:l||{}}}};var xo=(...a)=>a.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch{return e}}).join(", "),Be=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=Q(t)}createTxBuilder(e){return this.scope.checkOwner(),new On({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(xo(e))}logInfo(...e){this.logger.info(xo(e))}logAndCreateError(...e){let t=xo(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};import{NATIVE_MINT as ze,TOKEN_2022_PROGRAM_ID as Xe,TOKEN_PROGRAM_ID as be,createAssociatedTokenAccountIdempotentInstruction as Le,createSyncNativeInstruction as su,getTransferFeeConfig as Jt,unpackMint as en}from"@solana/spl-token";import _ from"bn.js";import{PublicKey as tn,SystemProgram as uu}from"@solana/web3.js";import Ne from"decimal.js";var Nn={initPriceX64:new _("515752397214619"),supply:new _(1e15),totalSellA:new _(7931e11),totalFundRaisingB:new _(85e9),totalFundRaisingBUSD:new _(125e8),totalLockedAmount:new _("0"),cliffPeriod:new _("0"),unlockPeriod:new _("0"),decimals:6,virtualA:new _("1073471847374405"),virtualB:new _("30050573465"),realA:new _(0),realB:new _(0),protocolFee:new _(0),platformId:new tn("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),vestingSchedule:{totalLockedAmount:new _(0),cliffPeriod:new _(0),unlockPeriod:new _(0),startTime:new _(0),totalAllocatedShare:new _(0)}},rt=new _(1e4),yL=new Set(["USDCoctVLVnvTXBEuP9s8hntucdJokbo17RwHuNXemT","USD1ttGY1N17NEEHLmELoaybftRBUSErhqYiQzvEmuB"]),Rn=class extends Be{constructor(e){super(e)}async getMintBTokenInfo({mintB:e,mintBProgram:t,transferFeeConfigB:n,skipCheckMintB:i}){if(e.equals(ze))return{mintBProgram:be,transferFeeConfigB:void 0};if(n)return{mintBProgram:t!=null?t:Xe,transferFeeConfigB:n};if(i||(t==null?void 0:t.equals(be)))return{mintBProgram:t!=null?t:be,transferFeeConfigB:void 0};let r=await this.scope.connection.getAccountInfo(e);return!r||!r.owner.equals(Xe)?{mintBProgram:t!=null?t:be,transferFeeConfigB:void 0}:{mintBProgram:r.owner,transferFeeConfigB:Jt(en(e,r,r.owner))||void 0}}async createLaunchpad(z){var j=z,{programId:e=ce,authProgramId:t,platformId:n=Nn.platformId,mintA:i,decimals:r=6,mintBDecimals:s=9,name:l,symbol:c,uri:u,migrateType:d,configId:p,configInfo:P,txVersion:b,computeBudgetConfig:f,txTipConfig:y,feePayer:g,buyAmount:k,minMintAAmount:B,slippage:K,associatedOnly:C=!0,checkCreateATAOwner:h=!1,extraSigners:S,token2022:L,transferFeeExtensionParams:x,creatorFeeOn:O=0,platformAllowConfig:M,mintBProgram:E,transferFeeConfigB:W,skipCheckMintB:V}=j,N=ve(j,["programId","authProgramId","platformId","mintA","decimals","mintBDecimals","name","symbol","uri","migrateType","configId","configInfo","txVersion","computeBudgetConfig","txTipConfig","feePayer","buyAmount","minMintAAmount","slippage","associatedOnly","checkCreateATAOwner","extraSigners","token2022","transferFeeExtensionParams","creatorFeeOn","platformAllowConfig","mintBProgram","transferFeeConfigB","skipCheckMintB"]);var Lo,Oo,No,Mo,Fo,vo,Vo,_o,Eo,Do,Wo;let J=this.createTxBuilder(g);t=t!=null?t:De(e).publicKey,L=!!x,L&&(d="cpmm");let Y=P;if(!Y&&p){let Ze=await this.scope.connection.getAccountInfo(p);Ze&&(Y=et.decode(Ze.data))}Y||this.logAndCreateError("config not found");let ee=Y.mintB,v=Y.curveType,{mintBProgram:te,transferFeeConfigB:se}=await this.getMintBTokenInfo({mintB:ee,mintBProgram:E,transferFeeConfigB:W,skipCheckMintB:V}),{publicKey:$}=St(e,i,ee),{publicKey:de}=so(e,$,i),{publicKey:ne}=so(e,$,ee),{publicKey:Fe}=Pn(i);this.logDebug(`create token: ${i.toBase58()}, mintB: ${ee.toBase58()}, decimals A:${r}/B:${s}, config:${p.toBase58()}`),c.length>10&&this.logAndCreateError("Symbol length should shorter than 11"),u||this.logAndCreateError("uri should not empty");let ge=(await this.scope.api.fetchLaunchConfigs()).find(Ze=>Ze.key.pubKey===p.toBase58()),H=(Lo=N==null?void 0:N.supply)!=null?Lo:new _(ge.defaultParams.supplyInit),U=(Oo=N==null?void 0:N.totalSellA)!=null?Oo:new _(ge.defaultParams.totalSellA),he=(No=N==null?void 0:N.totalFundRaisingB)!=null?No:new _(ge.defaultParams.totalFundRaisingB),Ye=(Mo=N==null?void 0:N.totalLockedAmount)!=null?Mo:new _(0),ue=await this.scope.connection.getAccountInfo(n);ue||this.logAndCreateError("platform id not found:",n.toString());let $e=pt.decode(ue.data),Mn=$e.platformVestingScale,Co=$e.feeRate,Ro=Oe.getCurve(Y.curveType).getInitParam({supply:H,totalFundRaising:he,totalSell:U,totalLockedAmount:Ye,migrateFee:Y.migrateFee}),nn;try{nn=await this.scope.token.getTokenInfo(ee)}catch{this.logDebug("can not get mintB info from getTokenInfo")}let Qe={epoch:new _(896),bump:254,status:0,mintDecimalsA:r,mintDecimalsB:(Fo=nn==null?void 0:nn.decimals)!=null?Fo:s,supply:H,totalSellA:U,mintA:new tn(i),mintB:ee,virtualA:Ro.a,virtualB:Ro.b,realA:Nn.realA,realB:Nn.realB,migrateFee:Y.migrateFee,migrateType:d==="amm"?0:1,protocolFee:Nn.protocolFee,platformFee:Co,platformId:n,configId:p,vaultA:de,vaultB:ne,creator:this.scope.ownerPubKey,totalFundRaisingB:he,vestingSchedule:{totalLockedAmount:Ye,cliffPeriod:new _(0),unlockPeriod:new _(0),startTime:new _(0),totalAllocatedShare:new _(0)},mintProgramFlag:Ji({mintAProgram:L?Xe:be,mintBProgram:te}),cpmmCreatorFeeOn:O,platformVestingShare:Mn!=null?Mn:new _(0)},or=Oe.getCurve(Y.curveType),{c:ir}=or.getInitParam({supply:Qe.supply,totalFundRaising:Qe.totalFundRaisingB,totalLockedAmount:Ye,totalSell:Y.curveType===0?Qe.totalSellA:new _(0),migrateFee:Y.migrateFee});try{Oe.checkParam({supply:Qe.supply,totalFundRaising:Qe.totalFundRaisingB,totalSell:ir,totalLockedAmount:Ye,decimals:Qe.mintDecimalsA,config:Y,migrateType:d}),this.logDebug("check init params success")}catch(Ze){this.logAndCreateError(`check create mint params failed, ${Ze.message}`)}J.addInstruction({instructions:[L?Gi(e,g!=null?g:this.scope.ownerPubKey,this.scope.ownerPubKey,p,n,t,$,i,ee,de,ne,te,r,l,c,u||"https://",{type:v===0?"ConstantCurve":v===1?"FixedCurve":v===2?"LinearCurve":"ConstantCurve",totalSellA:U,migrateType:d,supply:H,totalFundRaisingB:he},Ye,(vo=N==null?void 0:N.cliffPeriod)!=null?vo:new _(0),(Vo=N==null?void 0:N.unlockPeriod)!=null?Vo:new _(0),O,x,M?Xt(e,n,p).publicKey:void 0):Ui(e,g!=null?g:this.scope.ownerPubKey,this.scope.ownerPubKey,p,n,t,$,i,ee,de,ne,Fe,te,r,l,c,u||"https://",{type:v===0?"ConstantCurve":v===1?"FixedCurve":v===2?"LinearCurve":"ConstantCurve",totalSellA:U,migrateType:d,supply:H,totalFundRaisingB:he},Ye,(_o=N==null?void 0:N.cliffPeriod)!=null?_o:new _(0),(Eo=N==null?void 0:N.unlockPeriod)!=null?Eo:new _(0),O,M?Xt(e,n,p).publicKey:void 0)]});let Fn=L?await this.scope.connection.getEpochInfo():void 0,on=x?{epoch:BigInt((Fn==null?void 0:Fn.epoch)||0),maximumFee:BigInt((Do=x==null?void 0:x.maxinumFee.toString())!=null?Do:0),transferFeeBasisPoints:(Wo=x==null?void 0:x.transferFeeBasePoints)!=null?Wo:0}:void 0,vn={amountA:{amount:new _(0),fee:void 0,expirationTime:void 0},amountB:new _(0),splitFee:{platformFee:new _(0),shareFee:new _(0),protocolFee:new _(0),creatorFee:new _(0)},transferFeeB:void 0},Vn;if(S!=null&&S.length&&J.addInstruction({signers:S}),!N.createOnly){let{builder:Ze,extInfo:rr}=await this.buyToken({programId:e,authProgramId:t,mintAProgram:L?Xe:void 0,mintA:i,mintB:ee,mintBProgram:te,transferFeeConfigB:se,skipCheckMintB:!0,poolInfo:Qe,buyAmount:k,minMintAAmount:B,shareFeeRate:N.shareFeeRate,shareFeeReceiver:N.shareFeeReceiver,configInfo:Y,platformFeeRate:Co,slippage:K,associatedOnly:C,checkCreateATAOwner:h,skipCheckMintA:!on,transferFeeConfigA:on?{transferFeeConfigAuthority:t,withdrawWithheldAuthority:t,withheldAmount:BigInt(0),olderTransferFee:on,newerTransferFee:on}:void 0,fromCreate:!0});J.addInstruction(F({},Ze.AllTxData)),vn=F({},rr),Vn=(this.scope.cluster==="devnet"||b===1)&&N.shareFeeReceiver?[Ze.allInstructions[0]]:void 0}return J.addTipInstruction(y),b===0?J.sizeCheckBuildV0({computeBudgetConfig:f,swapInfo:vn,splitIns:Vn,address:q(F({},Qe),{poolId:$})}):J.sizeCheckBuild({computeBudgetConfig:f,swapInfo:vn,splitIns:Vn,address:q(F({},Qe),{poolId:$})})}async buyToken({programId:e=ce,authProgramId:t,mintA:n,mintAProgram:i=be,mintB:r=ze,poolInfo:s,configInfo:l,platformFeeRate:c,txVersion:u,computeBudgetConfig:d,txTipConfig:p,feePayer:P,buyAmount:b,minMintAAmount:f,slippage:y,shareFeeRate:g=new _(0),shareFeeReceiver:k,associatedOnly:B=!0,checkCreateATAOwner:K=!1,fromCreate:C=!1,transferFeeConfigA:h,skipCheckMintA:S=!1,mintBProgram:L,transferFeeConfigB:x,skipCheckMintB:O=!1}){var U,he,Ye;b.lte(new _(0))&&this.logAndCreateError("buy amount should gt 0:",b.toString());let M=this.createTxBuilder(P),{publicKey:E}=St(e,n,r);t=t!=null?t:De(e).publicKey;let W=h;if(!S)if(W)i=Xe;else{let ue=await this.scope.connection.getAccountInfo(n);if(ue&&ue.owner.equals(Xe)){i=ue.owner;let $e=en(n,ue,i);W=Jt($e)||void 0}}let{mintBProgram:V,transferFeeConfigB:N}=await this.getMintBTokenInfo({mintB:r,mintBProgram:L,transferFeeConfigB:x,skipCheckMintB:O}),z=this.scope.account.getAssociatedTokenAccount(n,i),j=r.equals(ze),J=C&&j,Y=J?this.scope.account.getAssociatedTokenAccount(r,V):null,ee=j;if(M.addInstruction({instructions:[Le(this.scope.ownerPubKey,z,this.scope.ownerPubKey,n,i),...J?[Le(this.scope.ownerPubKey,Y,this.scope.ownerPubKey,r,V),uu.transfer({fromPubkey:this.scope.ownerPubKey,toPubkey:Y,lamports:BigInt(b.toString())}),su(Y)]:[]]}),!J){let{account:ue,instructionParams:$e}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:V,mint:r,owner:this.scope.ownerPubKey,createInfo:ee?{payer:this.scope.ownerPubKey,amount:b}:void 0,skipCloseAccount:!ee,notUseTokenAccount:ee,associatedOnly:ee?!1:B,checkCreateATAOwner:K});ue&&(Y=ue),M.addInstruction($e||{})}Y||this.logAndCreateError(`cannot found mintB(${r.toBase58()}) buy token accounts`,"tokenAccounts",this.scope.account.tokenAccounts);let v=s;if(!v){let ue=await this.scope.connection.getAccountInfo(E,{commitment:"processed"});ue||this.logAndCreateError("cannot found pool:",E.toBase58()),v=Ee.decode(ue.data)}let te=l,se=await Ke(this.scope.connection,[te?void 0:v.configId,v.platformId].filter(Boolean).map(ue=>({pubkey:ue})));if(!te){let ue=se.find($e=>$e.pubkey.equals(v.configId));(!ue||!ue.accountInfo)&&this.logAndCreateError("config not found: ",v.configId.toBase58()),te=et.decode(ue.accountInfo.data)}let $=se.find(ue=>ue.pubkey.equals(v.platformId));(!$||!$.accountInfo)&&this.logAndCreateError("platform info not found: ",v.configId.toBase58());let de=pt.decode($.accountInfo.data);c=c||de.feeRate;let ne=Oe.buyExactIn({poolInfo:v,amountB:b,protocolFeeRate:te.tradeFeeRate,platformFeeRate:c,curveType:te.curveType,shareFeeRate:g,creatorFeeRate:de.creatorFeeRate,transferFeeConfigA:W,transferFeeConfigB:N,slot:await this.scope.connection.getSlot()}),Fe=new Ne(ne.amountA.amount.toString()).sub((he=(U=ne.amountA.fee)==null?void 0:U.toString())!=null?he:0),je=y?new Ne(rt.sub(y).toNumber()/rt.toNumber()).clampedTo(0,1):new Ne(1),ge=f!=null?f:y?new _(Fe.mul(je).toFixed(0)):ne.amountA.amount.sub((Ye=ne.amountA.fee)!=null?Ye:new _(0));ne.amountB.lt(b)&&console.log(`maximum ${n.toBase58()} amount can buy is ${ne.amountA.toString()}, input ${r.toBase58()} amount: ${ne.amountB.toString()}`);let H=k?me(k,r,V).publicKey:void 0;return H&&M.addInstruction({instructions:[Le(this.scope.ownerPubKey,H,k,r,V)]}),M.addInstruction({instructions:[mo(e,this.scope.ownerPubKey,t,v.configId,v.platformId,E,z,Y,v.vaultA,v.vaultB,n,r,i,V,tt(e,v.platformId,r).publicKey,nt(e,v.creator,r).publicKey,ne.amountB.lt(b)?ne.amountB:b,ge,g,H)]}),M.addCustomComputeBudget(d),M.addTipInstruction(p),M.versionBuild({txVersion:u,extInfo:q(F({},ne),{decimalOutAmount:Fe,minDecimalOutAmount:new Ne(ge.toString())})})}async buyTokenExactOut({programId:e=ce,authProgramId:t,mintA:n,mintAProgram:i=be,mintB:r=ze,poolInfo:s,configInfo:l,transferFeeConfigA:c,platformFeeRate:u,txVersion:d,computeBudgetConfig:p,txTipConfig:P,feePayer:b,maxBuyAmount:f,outAmount:y,slippage:g,shareFeeRate:k=new _(0),shareFeeReceiver:B,associatedOnly:K=!0,checkCreateATAOwner:C=!1,skipCheckMintA:h=!1,mintBProgram:S,transferFeeConfigB:L,skipCheckMintB:x=!1}){y.lte(new _(0))&&this.logAndCreateError("out amount should gt 0:",y.toString());let O=this.createTxBuilder(b),{publicKey:M}=St(e,n,r);t=t!=null?t:De(e).publicKey;let E=s;if(!E){let H=await this.scope.connection.getAccountInfo(M,{commitment:"processed"});H||this.logAndCreateError("cannot found pool:",M.toBase58()),E=Ee.decode(H.data)}let W=l,V=await Ke(this.scope.connection,[W?void 0:E.configId,E.platformId].filter(Boolean).map(H=>({pubkey:H})));if(!W){let H=V.find(U=>U.pubkey.equals(E.configId));(!H||!H.accountInfo)&&this.logAndCreateError("config not found: ",E.configId.toBase58()),W=et.decode(H.accountInfo.data)}let N=V.find(H=>H.pubkey.equals(E.platformId));(!N||!N.accountInfo)&&this.logAndCreateError("platform info not found: ",E.configId.toBase58());let z=pt.decode(N.accountInfo.data);u=u||z.feeRate;let j=c;if(!h)if(j)i=Xe;else{let H=await this.scope.connection.getAccountInfo(n);if(H&&H.owner.equals(Xe)){i=H.owner;let U=en(n,H,i);j=Jt(U)||void 0}}let{mintBProgram:J,transferFeeConfigB:Y}=await this.getMintBTokenInfo({mintB:r,mintBProgram:S,transferFeeConfigB:L,skipCheckMintB:x}),ee=Oe.buyExactOut({poolInfo:E,amountA:y,protocolFeeRate:W.tradeFeeRate,platformFeeRate:u,curveType:W.curveType,shareFeeRate:k,creatorFeeRate:z.creatorFeeRate,transferFeeConfigA:j,transferFeeConfigB:Y,slot:await this.scope.connection.getSlot()}),v=new Ne(ee.amountB.toString()),te=g?new Ne(rt.add(g).toNumber()/rt.toNumber()).clampedTo(0,Number.MIN_SAFE_INTEGER):new Ne(1),se=(f!=null?f:g)?new _(v.mul(te).toFixed(0)):ee.amountB,$=this.scope.account.getAssociatedTokenAccount(n,i),de=null,ne=r.equals(ze);O.addInstruction({instructions:[Le(this.scope.ownerPubKey,$,this.scope.ownerPubKey,n,i)]});let{account:Fe,instructionParams:je}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:J,mint:r,owner:this.scope.ownerPubKey,createInfo:ne?{payer:this.scope.ownerPubKey,amount:ee.amountB}:void 0,skipCloseAccount:!ne,notUseTokenAccount:ne,associatedOnly:ne?!1:K,checkCreateATAOwner:C});Fe&&(de=Fe),O.addInstruction(je||{}),de===void 0&&this.logAndCreateError(`cannot found mintB(${r.toBase58()}) token accounts`,"tokenAccounts",this.scope.account.tokenAccounts);let ge=B?me(B,r,J).publicKey:void 0;return ge&&O.addInstruction({instructions:[Le(this.scope.ownerPubKey,ge,B,r,J)]}),O.addInstruction({instructions:[zi(e,this.scope.ownerPubKey,t,E.configId,E.platformId,M,$,de,E.vaultA,E.vaultB,n,r,i,J,tt(e,E.platformId,r).publicKey,nt(e,E.creator,r).publicKey,y,se,k,ge)]}),O.addCustomComputeBudget(p),O.addTipInstruction(P),O.versionBuild({txVersion:d,extInfo:{maxSpentAmount:se,outAmount:y}})}async sellToken({programId:e=ce,authProgramId:t,mintAProgram:n=be,mintA:i,mintB:r=ze,poolInfo:s,configInfo:l,platformFeeRate:c,txVersion:u,computeBudgetConfig:d,txTipConfig:p,feePayer:P,sellAmount:b,minAmountB:f,slippage:y,shareFeeRate:g=new _(0),shareFeeReceiver:k,associatedOnly:B=!0,checkCreateATAOwner:K=!1,skipCheckMintA:C=!1,mintBProgram:h,transferFeeConfigB:S,skipCheckMintB:L=!1}){t=t!=null?t:De(e).publicKey;let x=this.createTxBuilder(P);b.lte(new _(0))&&this.logAndCreateError("sell amount should be gt 0");let{publicKey:O}=St(e,i,r),M;if(!C){let U=await this.scope.connection.getAccountInfo(i);if(U&&U.owner.equals(Xe)){n=U.owner;let he=en(i,U,n);M=Jt(he)||void 0}}let{mintBProgram:E,transferFeeConfigB:W}=await this.getMintBTokenInfo({mintB:r,mintBProgram:h,transferFeeConfigB:S,skipCheckMintB:L}),V=null,N=null,z=r.equals(ze),{account:j,instructionParams:J}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n,mint:i,owner:this.scope.ownerPubKey,createInfo:void 0,skipCloseAccount:!0,notUseTokenAccount:!1,associatedOnly:B,checkCreateATAOwner:K});j&&(V=j),x.addInstruction(J||{}),V===void 0&&this.logAndCreateError("cannot found mintA token accounts","tokenAccounts",this.scope.account.tokenAccounts);let{account:Y,instructionParams:ee}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:E,mint:r,owner:this.scope.ownerPubKey,createInfo:z?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!z,notUseTokenAccount:z,associatedOnly:z?!1:B,checkCreateATAOwner:K});Y&&(N=Y),x.addInstruction(ee||{}),N===void 0&&this.logAndCreateError("cannot found mintB token accounts","tokenAccounts",this.scope.account.tokenAccounts);let v=s;if(!v){let U=await this.scope.connection.getAccountInfo(O,{commitment:"processed"});U||this.logAndCreateError("cannot found pool",O.toBase58()),v=Ee.decode(U.data)}let te=l,se=await Ke(this.scope.connection,[te?void 0:v.configId,v.platformId].filter(Boolean).map(U=>({pubkey:U})));if(!te){let U=se.find(he=>he.pubkey.equals(v.configId));(!U||!U.accountInfo)&&this.logAndCreateError("config not found: ",v.configId.toBase58()),te=et.decode(U.accountInfo.data)}let $=se.find(U=>U.pubkey.equals(v.platformId));(!$||!$.accountInfo)&&this.logAndCreateError("platform info not found: ",v.configId.toBase58());let de=pt.decode($.accountInfo.data);c=c||de.feeRate;let ne=Oe.sellExactIn({poolInfo:v,amountA:b,protocolFeeRate:te.tradeFeeRate,platformFeeRate:c,curveType:te.curveType,shareFeeRate:g,creatorFeeRate:de.creatorFeeRate,transferFeeConfigA:M,transferFeeConfigB:W,slot:await this.scope.connection.getSlot()}),Fe=new Ne(ne.amountB.toString()),je=y?new Ne(rt.sub(y).toNumber()/rt.toNumber()).clampedTo(0,1):new Ne(1),ge=f!=null?f:y?new _(Fe.mul(je).toFixed(0)):ne.amountB;ge.lte(new _(0))&&this.logAndCreateError(`out ${r.toBase58()} amount should be gt 0`);let H=k?me(k,r,E).publicKey:void 0;return H&&x.addInstruction({instructions:[Le(this.scope.ownerPubKey,H,k,r,E)]}),x.addInstruction({instructions:[po(e,this.scope.ownerPubKey,t,v.configId,v.platformId,O,V,N,v.vaultA,v.vaultB,i,r,n,E,tt(e,v.platformId,r).publicKey,nt(e,v.creator,r).publicKey,ne.amountA.amount.lt(b)?ne.amountA.amount:b,ge,g,H)]}),x.addCustomComputeBudget(d),x.addTipInstruction(p),x.versionBuild({txVersion:u,extInfo:{outAmount:ge}})}async sellTokenExactOut({programId:e=ce,authProgramId:t,mintAProgram:n=be,mintA:i,mintB:r=ze,poolInfo:s,configInfo:l,platformFeeRate:c,txVersion:u,computeBudgetConfig:d,txTipConfig:p,feePayer:P,inAmount:b,maxSellAmount:f,slippage:y,shareFeeRate:g=new _(0),shareFeeReceiver:k,associatedOnly:B=!0,checkCreateATAOwner:K=!1,skipCheckMintA:C=!1,mintBProgram:h,transferFeeConfigB:S,skipCheckMintB:L=!1}){t=t!=null?t:De(e).publicKey;let x=this.createTxBuilder(P);f!=null&&f.lte(new _(0))&&this.logAndCreateError("max sell amount should be gt 0");let{publicKey:O}=St(e,i,r),M;if(!C){let U=await this.scope.connection.getAccountInfo(i);if(U&&U.owner.equals(Xe)){n=U.owner;let he=en(i,U,n);M=Jt(he)||void 0}}let{mintBProgram:E,transferFeeConfigB:W}=await this.getMintBTokenInfo({mintB:r,mintBProgram:h,transferFeeConfigB:S,skipCheckMintB:L}),V=null,N=null,z=r.equals(ze),{account:j,instructionParams:J}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n,mint:i,owner:this.scope.ownerPubKey,createInfo:void 0,skipCloseAccount:!0,notUseTokenAccount:!1,associatedOnly:B,checkCreateATAOwner:K});j&&(V=j),x.addInstruction(J||{}),V===void 0&&this.logAndCreateError("cannot found mintA token accounts","tokenAccounts",this.scope.account.tokenAccounts);let{account:Y,instructionParams:ee}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:E,mint:r,owner:this.scope.ownerPubKey,createInfo:z?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!z,notUseTokenAccount:z,associatedOnly:z?!1:B,checkCreateATAOwner:K});Y&&(N=Y),x.addInstruction(ee||{}),N===void 0&&this.logAndCreateError("cannot found mintB token accounts","tokenAccounts",this.scope.account.tokenAccounts);let v=s;if(!v){let U=await this.scope.connection.getAccountInfo(O,{commitment:"processed"});U||this.logAndCreateError("cannot found pool",O.toBase58()),v=Ee.decode(U.data)}let te=l,se=await Ke(this.scope.connection,[te?void 0:v.configId,v.platformId].filter(Boolean).map(U=>({pubkey:U})));if(!te){let U=se.find(he=>he.pubkey.equals(v.configId));(!U||!U.accountInfo)&&this.logAndCreateError("config not found: ",v.configId.toBase58()),te=et.decode(U.accountInfo.data)}let $=se.find(U=>U.pubkey.equals(v.platformId));(!$||!$.accountInfo)&&this.logAndCreateError("platform info not found: ",v.configId.toBase58());let de=pt.decode($.accountInfo.data);c=c||de.feeRate;let ne=Oe.sellExactOut({poolInfo:v,amountB:b,protocolFeeRate:te.tradeFeeRate,platformFeeRate:c,curveType:te.curveType,shareFeeRate:g,creatorFeeRate:de.creatorFeeRate,transferFeeConfigA:M,transferFeeConfigB:W,slot:await this.scope.connection.getSlot()}),Fe=new Ne(ne.amountA.amount.toString()),je=y?new Ne(rt.add(y).toNumber()/rt.toNumber()).clampedTo(0,Number.MAX_SAFE_INTEGER):new Ne(1),ge=(f!=null?f:y)?new _(Fe.mul(je).toFixed(0)):ne.amountA.amount,H=k?me(k,r,E).publicKey:void 0;return H&&x.addInstruction({instructions:[Le(this.scope.ownerPubKey,H,k,r,E)]}),x.addInstruction({instructions:[Xi(e,this.scope.ownerPubKey,t,v.configId,v.platformId,O,V,N,v.vaultA,v.vaultB,i,r,n,E,tt(e,v.platformId,r).publicKey,nt(e,v.creator,r).publicKey,b,ge,g,H)]}),x.addCustomComputeBudget(d),x.addTipInstruction(p),x.versionBuild({txVersion:u,extInfo:{maxSellAmount:ge}})}async createPlatformConfig({programId:e=ce,platformAdmin:t,platformClaimFeeWallet:n,platformLockNftWallet:i,platformVestingWallet:r,cpConfigId:s,migrateCpLockNftScale:l,transferFeeExtensionAuth:c,creatorFeeRate:u,feeRate:d,name:p,web:P,img:b,platformVestingScale:f=new _(0),txVersion:y,computeBudgetConfig:g,txTipConfig:k,feePayer:B}){let K=this.createTxBuilder(B),{publicKey:C}=uo(e,t);return K.addInstruction({instructions:[Yi(e,t,n,i,r,C,s,c,l,d,u,p,P,b,f)]}),K.addCustomComputeBudget(g),K.addTipInstruction(k),K.versionBuild({txVersion:y,extInfo:{platformId:C}})}async updatePlatformConfig({programId:e=ce,platformAdmin:t,platformId:n,updateInfo:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),d=n!=null?n:uo(e,t).publicKey;return u.addInstruction({instructions:[Qi(e,t,d,i)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r})}async createPlatformVestingAccount({programId:e=ce,platformVestingWallet:t,beneficiary:n,platformId:i,poolId:r,vestingRecord:s,txVersion:l,computeBudgetConfig:c,txTipConfig:u,feePayer:d}){let p=this.createTxBuilder(d),P=s!=null?s:Kt(e,r,n).publicKey;return p.addInstruction({instructions:[Zi(e,t,n,i,r,P)]}),p.addCustomComputeBudget(c),p.addTipInstruction(u),p.versionBuild({txVersion:l})}async claimPlatformFee({programId:e=ce,authProgramId:t,platformId:n,poolId:i,platformClaimFeeWallet:r,mintB:s,vaultB:l,mintBProgram:c,txVersion:u,computeBudgetConfig:d,txTipConfig:p,feePayer:P}){var B;let b=this.createTxBuilder(P);t=t!=null?t:De(e).publicKey;let f=s,y=l;if(!f){let K=await this.scope.connection.getAccountInfo(i,{commitment:"processed"});K||this.logAndCreateError("cannot found pool:",i.toBase58());let C=Ee.decode(K.data),h=await this.scope.connection.getAccountInfo(C.configId,{commitment:"processed"});h||this.logAndCreateError("cannot found config:",C.configId.toBase58()),f=et.decode(h.data).mintB,y=y!=null?y:C.vaultB}(!f||!y)&&this.logAndCreateError("cannot found mint info, mintB: ",f.toBase58(),", vaultB: ",(B=y==null?void 0:y.toBase58())!=null?B:"");let{mintBProgram:g}=await this.getMintBTokenInfo({mintB:f,mintBProgram:c}),k=me(this.scope.ownerPubKey,f,g).publicKey;return b.addInstruction({instructions:[Le(this.scope.ownerPubKey,k,this.scope.ownerPubKey,f,g)]}),b.addInstruction({instructions:[bo(e,r,t,i,n,y,k,f,g)]}),b.addCustomComputeBudget(d),b.addTipInstruction(p),b.versionBuild({txVersion:u})}async claimAllPlatformFee({programId:e=ce,authProgramId:t,platformId:n,platformClaimFeeWallet:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c);t=t!=null?t:De(e).publicKey;let p=(await this.scope.connection.getProgramAccounts(e,{filters:[{dataSize:Ee.span},{memcmp:{offset:Ee.offsetOf("platformId"),bytes:n.toString()}}]})).map(f=>({poolId:f.pubkey,pool:Ee.decode(f.account.data)})).filter(({pool:f})=>f.platformFee.gt(new _(0))),P={},b=[...new Set(p.map(({pool:f})=>f.mintB.toBase58()))];return b.length&&(await Ke(this.scope.connection,b.map(y=>({pubkey:new tn(y)})))).forEach(y=>{var g,k;P[y.pubkey.toBase58()]=(k=(g=y.accountInfo)==null?void 0:g.owner)!=null?k:be}),p.forEach(({poolId:f,pool:y})=>{var B;let g=(B=P[y.mintB.toBase58()])!=null?B:be,k=me(this.scope.ownerPubKey,y.mintB,g).publicKey;u.addInstruction({instructions:[Le(this.scope.ownerPubKey,k,this.scope.ownerPubKey,y.mintB,g)]}),u.addInstruction({instructions:[bo(e,i,t,f,n,y.vaultB,k,y.mintB,g)]})}),u.addTipInstruction(l),r===0?u.sizeCheckBuildV0({computeBudgetConfig:s}):u.sizeCheckBuild({computeBudgetConfig:s})}async createVesting({programId:e=ce,poolId:t,beneficiary:n,shareAmount:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),d=await this.getRpcPoolInfo({poolId:t});i.add(d.vestingSchedule.totalAllocatedShare).gt(d.vestingSchedule.totalLockedAmount)&&this.logAndCreateError("share amount exceed total locked amount");let p=Kt(e,t,n).publicKey;return u.addInstruction({instructions:[yo(e,this.scope.ownerPubKey,n,t,p,i)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r})}async createMultipleVesting({programId:e=ce,poolId:t,beneficiaryList:n,txVersion:i,computeBudgetConfig:r,feePayer:s}){let l=this.createTxBuilder(s);n.length===0&&this.logAndCreateError("beneficiaryList is null");let c=await this.getRpcPoolInfo({poolId:t});return n.reduce((d,p)=>d.add(p.shareAmount),c.vestingSchedule.totalAllocatedShare).gt(c.vestingSchedule.totalLockedAmount)&&this.logAndCreateError("share amount exceed total locked amount"),n.forEach(d=>{let p=Kt(e,t,d.wallet).publicKey;l.addInstruction({instructions:[yo(e,this.scope.ownerPubKey,d.wallet,t,p,d.shareAmount)]})}),i===0?l.sizeCheckBuildV0({computeBudgetConfig:r}):l.sizeCheckBuild({computeBudgetConfig:r})}async claimVesting({programId:e=ce,poolId:t,poolInfo:n,vestingRecord:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),d=De(e).publicKey,p=i||Kt(e,t,this.scope.ownerPubKey).publicKey,P=n;if(!P){let f=await this.scope.connection.getAccountInfo(t);f||this.logAndCreateError("pool not found"),P=Ee.decode(f.data)}let b=me(this.scope.ownerPubKey,P.mintA,be).publicKey;return u.addInstruction({instructions:[Le(this.scope.ownerPubKey,b,this.scope.ownerPubKey,P.mintA)]}),u.addInstruction({instructions:[fo(e,this.scope.ownerPubKey,d,t,p,b,P.vaultA,P.mintA,be)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r})}async claimMultiVesting({programId:e=ce,poolIdList:t,poolsInfo:n={},vestingRecords:i={},txVersion:r,computeBudgetConfig:s,feePayer:l}){let c=this.createTxBuilder(l),u=F({},n),d=De(e).publicKey,p=t.filter(P=>!u[P.toBase58()]);if(p.length){let P=await this.getRpcPoolsInfo({poolIdList:p});u=F(F({},u),P.poolInfoMap)}return t.forEach(P=>{let b=P.toBase58(),f=u[b];f||this.logAndCreateError(`pool info not found: ${b}`);let y=i[b]||Kt(e,P,this.scope.ownerPubKey).publicKey,g=me(this.scope.ownerPubKey,f.mintA,be).publicKey;c.addInstruction({instructions:[Le(this.scope.ownerPubKey,g,this.scope.ownerPubKey,f.mintA)]}),c.addInstruction({instructions:[fo(e,this.scope.ownerPubKey,d,P,y,g,f.vaultA,f.mintA,be)]})}),r===0?c.sizeCheckBuildV0({computeBudgetConfig:s}):c.sizeCheckBuild({computeBudgetConfig:s})}async claimVaultPlatformFee({programId:e=ce,platformId:t,mintB:n,mintBProgram:i,claimFeeWallet:r,txVersion:s,computeBudgetConfig:l,txTipConfig:c,feePayer:u}){let d=this.createTxBuilder(u),p=tt(e,t,n).publicKey,P=co(e).publicKey,{mintBProgram:b}=await this.getMintBTokenInfo({mintB:n,mintBProgram:i}),f=this.scope.account.getAssociatedTokenAccount(n,b);return d.addInstruction({instructions:[Le(this.scope.ownerPubKey,f,this.scope.ownerPubKey,n,b),go(e,t,r!=null?r:this.scope.ownerPubKey,P,p,f,n,b)]}),d.addCustomComputeBudget(l),d.addTipInstruction(c),d.versionBuild({txVersion:s})}async claimMultipleVaultPlatformFee({programId:e=ce,platformList:t,unwrapSol:n=!0,txVersion:i,computeBudgetConfig:r,feePayer:s,associatedOnly:l=!0,checkCreateATAOwner:c=!1}){let u=this.createTxBuilder(s),d={};return t.forEach(async p=>{var g,k,B;let P=co(e).publicKey,b=tt(e,p.id,p.mintB).publicKey,f=p.mintB.equals(ze)&&n,y=d[p.mintB.toBase58()];if(!y){let{account:K,instructionParams:C}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:(g=p.mintBProgram)!=null?g:be,mint:p.mintB,owner:this.scope.ownerPubKey,createInfo:f?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!f,notUseTokenAccount:f,associatedOnly:f?!1:l,checkCreateATAOwner:c});K&&(y=K),u.addInstruction(C||{}),y===void 0&&this.logAndCreateError(`cannot found platform ${p.id.toBase58()} mintB(${p.mintB.toBase58()}) token accounts`,"tokenAccounts",this.scope.account.tokenAccounts)}u.addInstruction({instructions:[go(e,p.id,(k=p.claimFeeWallet)!=null?k:this.scope.ownerPubKey,P,b,y,p.mintB,(B=p.mintBProgram)!=null?B:be)]})}),i===0?u.sizeCheckBuildV0({computeBudgetConfig:r}):u.sizeCheckBuild({computeBudgetConfig:r})}async claimCreatorFee({programId:e=ce,mintB:t,mintBProgram:n,txVersion:i,computeBudgetConfig:r,txTipConfig:s,feePayer:l}){let c=this.createTxBuilder(l),u=nt(e,this.scope.ownerPubKey,t).publicKey,d=lo(e).publicKey,{mintBProgram:p}=await this.getMintBTokenInfo({mintB:t,mintBProgram:n}),P=this.scope.account.getAssociatedTokenAccount(t,p);return c.addInstruction({instructions:[Le(this.scope.ownerPubKey,P,this.scope.ownerPubKey,t,p),Po(e,this.scope.ownerPubKey,d,u,P,t,p)]}),c.addCustomComputeBudget(r),c.addTipInstruction(s),c.versionBuild({txVersion:i})}async claimMultipleCreatorFee({programId:e=ce,mintBList:t,txVersion:n,computeBudgetConfig:i,feePayer:r}){let s=this.createTxBuilder(r);return t.forEach(l=>{var b;let c=l.pubKey,u=(b=l.programId)!=null?b:be,d=nt(e,this.scope.ownerPubKey,c).publicKey,p=lo(e).publicKey,P=this.scope.account.getAssociatedTokenAccount(c,u);s.addInstruction({instructions:[Le(this.scope.ownerPubKey,P,this.scope.ownerPubKey,c,u),Po(e,this.scope.ownerPubKey,p,d,P,c,u)]})}),n==0?s.sizeCheckBuildV0({computeBudgetConfig:i}):s.sizeCheckBuild({computeBudgetConfig:i})}async createPlatformAllowConfig({programId:e=ce,platformAdmin:t,platformId:n,configInfo:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),{publicKey:d}=ao(e,new tn(i.mintB),i.curveType,i.index),{publicKey:p}=Xt(e,n,d);return u.addInstruction({instructions:[Hi(e,t,n,d,p)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r,extInfo:{platformId:n}})}async closePlatformAllowConfig({programId:e=ce,platformAdmin:t,platformId:n,configInfo:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),{publicKey:d}=ao(e,new tn(i.mintB),i.curveType,i.index),{publicKey:p}=Xt(e,n,d);return u.addInstruction({instructions:[ji(e,t,n,d,p)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r,extInfo:{platformId:n}})}async getRpcPoolInfo({poolId:e}){return(await this.getRpcPoolsInfo({poolIdList:[e]})).poolInfoMap[e.toBase58()]}async getRpcPoolsInfo({poolIdList:e,config:t}){let n=await Ke(this.scope.connection,e.map(c=>({pubkey:c})),t),i={},r=[];for(let c=0;c<e.length;c++){let u=n[c];if(u===null||!u.accountInfo)throw Error("fetch pool info error: "+e[c].toBase58());let d=Ee.decode(u.accountInfo.data);i[e[c].toBase58()]=q(F({},d),{poolId:e[c],programId:u.accountInfo.owner}),r.push(d.configId)}let s=await Ke(this.scope.connection,r.map(c=>({pubkey:c})),t),l={};for(let c=0;c<r.length;c++){let u=s[c];if(u===null||!u.accountInfo)throw Error("fetch config info error: "+r[c].toBase58());let d=et.decode(u.accountInfo.data);l[r[c].toBase58()]=q(F({},d),{configId:u.accountInfo.owner})}return{poolInfoMap:Object.keys(i).reduce((c,u)=>q(F({},c),{[u]:q(F({},i[u]),{configInfo:l[i[u].configId.toBase58()]})}),{})}}};export{Nn as LaunchpadPoolInitParam,Rn as default,yL as usdMintBSet};
//# sourceMappingURL=launchpad.mjs.map