UNPKG

@raydium-io/raydium-sdk-v2

Version:

An SDK for building applications on top of Raydium.

2 lines 142 kB
var zr=Object.create;var Et=Object.defineProperty,Xr=Object.defineProperties,Yr=Object.getOwnPropertyDescriptor,Hr=Object.getOwnPropertyDescriptors,Qr=Object.getOwnPropertyNames,dn=Object.getOwnPropertySymbols,Zr=Object.getPrototypeOf,jn=Object.prototype.hasOwnProperty,di=Object.prototype.propertyIsEnumerable;var mi=(a,e,t)=>e in a?Et(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,v=(a,e)=>{for(var t in e||(e={}))jn.call(e,t)&&mi(a,t,e[t]);if(dn)for(var t of dn(e))di.call(e,t)&&mi(a,t,e[t]);return a},z=(a,e)=>Xr(a,Hr(e));var _e=(a,e)=>{var t={};for(var n in a)jn.call(a,n)&&e.indexOf(n)<0&&(t[n]=a[n]);if(a!=null&&dn)for(var n of dn(a))e.indexOf(n)<0&&di.call(a,n)&&(t[n]=a[n]);return t};var $r=(a,e)=>{for(var t in e)Et(a,t,{get:e[t],enumerable:!0})},pi=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Qr(e))!jn.call(a,i)&&i!==t&&Et(a,i,{get:()=>e[i],enumerable:!(n=Yr(e,i))||n.enumerable});return a};var N=(a,e,t)=>(t=a!=null?zr(Zr(a)):{},pi(e||!a||!a.__esModule?Et(t,"default",{value:a,enumerable:!0}):t,a)),jr=a=>pi(Et({},"__esModule",{value:!0}),a);var gc={};$r(gc,{LaunchpadPoolInitParam:()=>cn,default:()=>un,usdMintBSet:()=>bc});module.exports=jr(gc);var Dt=require("lodash");var Jn=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}},fi={},Jr={};function j(a){let e=(0,Dt.get)(fi,a);if(!e){let t=(0,Dt.get)(Jr,a);e=new Jn({name:a,logLevel:t}),(0,Dt.set)(fi,a,e)}return e}var ne=require("@solana/web3.js"),Wr=N(require("axios"));var Ue=require("@solana/web3.js");var Dr=require("@solana/web3.js");var Je=N(require("bn.js")),yc=N(require("decimal.js"));var Ai=N(require("big.js")),ia=N(require("bn.js"));var yi=N(require("toformat")),ea=yi.default,Wt=ea;var qt=N(require("big.js")),gi=N(require("bn.js")),Pi=N(require("decimal.js-light"));var wt=N(require("bn.js"));var bi=9007199254740991;function Ke(a){let e=j("Raydium_parseBigNumberish");if(a instanceof wt.default)return a;if(typeof a=="string"){if(a.match(/^-?[0-9]+$/))return new wt.default(a);e.logWithError(`invalid BigNumberish string: ${a}`)}return typeof a=="number"?(a%1&&e.logWithError(`BigNumberish number underflow: ${a}`),(a>=bi||a<=-bi)&&e.logWithError(`BigNumberish number overflow: ${a}`),new wt.default(String(a))):typeof a=="bigint"?new wt.default(a.toString()):(e.error(`invalid BigNumberish value: ${a}`),new wt.default(0))}var pn=j("module/fraction"),eo=Wt(qt.default),Ut=Wt(Pi.default),na={[0]:Ut.ROUND_DOWN,[1]:Ut.ROUND_HALF_UP,[2]:Ut.ROUND_UP},oa={[0]:qt.default.roundDown,[1]:qt.default.roundHalfUp,[2]:qt.default.roundUp},ue=class{constructor(e,t=new gi.default(1)){this.numerator=Ke(e),this.denominator=Ke(t)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new ue(this.denominator,this.numerator)}add(e){let t=e instanceof ue?e:new ue(Ke(e));return this.denominator.eq(t.denominator)?new ue(this.numerator.add(t.numerator),this.denominator):new ue(this.numerator.mul(t.denominator).add(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}sub(e){let t=e instanceof ue?e:new ue(Ke(e));return this.denominator.eq(t.denominator)?new ue(this.numerator.sub(t.numerator),this.denominator):new ue(this.numerator.mul(t.denominator).sub(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}mul(e){let t=e instanceof ue?e:new ue(Ke(e));return new ue(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof ue?e:new ue(Ke(e));return new ue(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},n=1){Number.isInteger(e)||pn.logWithError(`${e} is not an integer.`),e<=0&&pn.logWithError(`${e} is not positive.`),Ut.set({precision:e+1,rounding:na[n]});let i=new Ut(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)||pn.logWithError(`${e} is not an integer.`),e<0&&pn.logWithError(`${e} is negative.`),eo.DP=e,eo.RM=oa[n]||1,new eo(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var _c=j("Raydium_amount"),Vc=Wt(Ai.default);var wi=require("@solana/web3.js"),to=require("@solana/spl-token"),fn={chainId:101,address:wi.PublicKey.default.toBase58(),programId:to.TOKEN_PROGRAM_ID.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}},Ge={chainId:101,address:"So11111111111111111111111111111111111111112",programId:to.TOKEN_PROGRAM_ID.toBase58(),decimals:9,symbol:"WSOL",name:"Wrapped SOL",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"raydium",extensions:{coingeckoId:"solana"}};var yn=require("@solana/web3.js");var re=require("@solana/web3.js"),ki=require("@solana/spl-token");function kt({pubkey:a,isSigner:e=!1,isWritable:t=!0}){return{pubkey:a,isWritable:t,isSigner:e}}var aa=[kt({pubkey:ki.TOKEN_PROGRAM_ID,isWritable:!1}),kt({pubkey:re.SystemProgram.programId,isWritable:!1}),kt({pubkey:re.SYSVAR_RENT_PUBKEY,isWritable:!1})];function Ti({publicKey:a,transformSol:e}){let t=hi(a.toString());if(t instanceof re.PublicKey)return e&&t.equals(lt)?$e:t;if(e&&t.toString()===lt.toBase58())return $e;if(typeof t=="string"){if(t===re.PublicKey.default.toBase58())return re.PublicKey.default;try{return new re.PublicKey(t)}catch{throw new Error("invalid public key")}}throw new Error("invalid public key")}function hi(a){try{return new re.PublicKey(a)}catch{return a}}var no=new re.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Tt=new re.PublicKey("SysvarRent111111111111111111111111111111111"),qc=new re.PublicKey("SysvarC1ock11111111111111111111111111111111"),mt=new re.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),sa=new re.PublicKey("Sysvar1nstructions1111111111111111111111111"),ua=re.SystemProgram.programId,Uc=new re.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Gc=new re.PublicKey("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),zc=new re.PublicKey("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Xc=new re.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Yc=new re.PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),Hc=new re.PublicKey("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Qc=new re.PublicKey("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Zc=new re.PublicKey("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),$c=new re.PublicKey("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),jc=new re.PublicKey("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),Jc=new re.PublicKey("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),$e=new re.PublicKey("So11111111111111111111111111111111111111112"),lt=re.PublicKey.default;var oo=class{constructor({mint:e,decimals:t,symbol:n,name:i,skipMint:r=!1,isToken2022:s=!1}){if(e===lt.toBase58()||e instanceof yn.PublicKey&&lt.equals(e)){this.decimals=Ge.decimals,this.symbol=Ge.symbol,this.name=Ge.name,this.mint=new yn.PublicKey(Ge.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?yn.PublicKey.default:Ti({publicKey:e}),this.isToken2022=s}equals(e){return this===e?!0:this.mint.equals(e.mint)}},he=oo;he.WSOL=new oo(z(v({},Ge),{mint:Ge.address}));var io=class{constructor({decimals:e,symbol:t="UNKNOWN",name:n="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=n}equals(e){return this===e}},bn=io;bn.SOL=new io(fn);var Ii=N(require("bn.js"));var cl=new ue(new Ii.default(100));var yl=j("Raydium_price");var fc=require("lodash");var la=N(require("axios"));var Bi={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"},ca=z(v({},Bi),{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 zl=j("Raydium_Api");var Fi=require("@solana/web3.js");var Tn=require("@solana/spl-token");var Ni=require("@solana/web3.js"),ba=N(require("bn.js"));var kn=require("@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"};var Oi=require("@solana/web3.js"),fa=N(require("bn.js"));var ya=require("@solana/spl-token");var Ci=require("@solana/web3.js"),ht=N(require("bn.js"));var V=require("@solana/buffer-layout"),gn=V.Layout,Si=V.Structure;var ro=V.UInt;var Ki=V.u8,ce=V.u16;var zt=V.u32;var Ve=V.s32;var xi=V.seq;var H=V.blob;var ao=V.bits,so=V.offset;var dt=class extends gn{constructor(t,n,i){super(t,i);this.blob=H(t),this.signed=n}decode(t,n=0){let i=new ht.default(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 ht.default(t)),this.signed&&(t=t.toTwos(this.span*8)),this.blob.encode(t.toArrayLike(Buffer,"le",this.span),n,i)}},Pn=class extends gn{constructor(t){super(8,t);this._lower=ao(zt(),!1),this._upper=ao(zt(),!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 v(v({},i),r)}encode(t,n,i=0){return this._lower.encode(t,n,i)+this._upper.encode(t,n,i+this._lower.span)}};function w(a){return new ro(1,a)}function de(a){return new ro(4,a)}function o(a){return new dt(8,!1,a)}function X(a){return new dt(16,!1,a)}function Ri(a){return new dt(1,!0,a)}function It(a){return new dt(8,!0,a)}function Li(a){return new dt(16,!0,a)}var pt=class extends gn{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 pt(H(32),e=>new Ci.PublicKey(e),e=>e.toBuffer(),a)}function Fe(a){return new pt(Ki(),ma,da,a)}function ma(a){if(a===0)return!1;if(a===1)return!0;throw new Error("Invalid bool: "+a)}function da(a){return a?1:0}function co(a,e){let t=zt("length"),n=k([t,C(a,so(t,-t.span),"values")]);return new pt(n,({values:i})=>i,i=>({values:i}),e)}function pa(a){let e=zt("length"),t=k([e,H(so(e,-e.span),"data")]);return new pt(t,({data:n})=>n,n=>({data:n}),a)}function Le(a){return new pt(pa(),e=>e.toString("utf-8"),e=>Buffer.from(e,"utf-8"),a)}var uo=class extends Si{decode(e,t){return super.decode(e,t)}};function k(a,e,t){return new uo(a,e,t)}function C(a,e,t){let n,i=typeof e=="number"?e:(0,ht.isBN)(e)?e.toNumber():new Proxy(e,{get(r,s){if(!n){let l=Reflect.get(r,"count");n=(0,ht.isBN)(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 xi(a,i,t)}var An=k([m("mint"),m("owner"),o("amount"),de("delegateOption"),m("delegate"),w("state"),de("isNativeOption"),o("isNative"),o("delegatedAmount"),de("closeAuthorityOption"),m("closeAuthority")]);var fr=require("@solana/web3.js"),su=require("@solana/spl-token");var Ei=require("@solana/web3.js"),Di=require("@solana/spl-token");var Ie=require("@solana/web3.js");var _i=require("@solana/spl-token"),vi=j("Raydium_txUtil"),Vi=1644;function hn(a){let e=[],t=[];return a.microLamports&&(e.push(Ie.ComputeBudgetProgram.setComputeUnitPrice({microLamports:a.microLamports})),t.push(Pe.SetComputeUnitPrice)),a.units&&(e.push(Ie.ComputeBudgetProgram.setComputeUnitLimit({units:a.units})),t.push(Pe.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}async function Bt(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 In(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 lo(a,e){a.length<1&&vi.logWithError(`no instructions provided: ${a.toString()}`),e.length<1&&vi.logWithError(`no signers provided:, ${e.toString()}`);let t=new Ie.Transaction;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...a);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<Vi}catch{return!1}}function le(a,e){let[t,n]=Ie.PublicKey.findProgramAddressSync(a,e);return{publicKey:t,nonce:n}}function Xt({instructions:a,payer:e,signers:t}){return lo(a,[e,...t])}function Yt({instructions:a,payer:e,lookupTableAddressAccount:t,recentBlockhash:n=Ie.Keypair.generate().publicKey.toString()}){let r=new Ie.TransactionMessage({payerKey:e,recentBlockhash:n,instructions:a}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new Ie.VersionedTransaction(r).serialize()).toString("base64").length<Vi}catch{return!1}}var Pa=a=>Buffer.isBuffer(a)?a:a instanceof Uint8Array?Buffer.from(a.buffer,a.byteOffset,a.byteLength):Buffer.from(a),Aa=a=>{let e=a.serialize({requireAllSignatures:!1,verifySignatures:!1});a instanceof Ie.VersionedTransaction&&(e=Pa(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch{return e.toString("base64")}};function ft(a){let e=[];return a.forEach(t=>{t instanceof Ie.Transaction&&(t.recentBlockhash||(t.recentBlockhash=_i.TOKEN_PROGRAM_ID.toBase58()),t.feePayer||(t.feePayer=Ie.Keypair.generate().publicKey)),e.push(Aa(t))}),console.log("simulate tx string:",e),e}function be(a,e,t){return le([a.toBuffer(),(t!=null?t:Di.TOKEN_PROGRAM_ID).toBuffer(),e.toBuffer()],new Ei.PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}var q=require("@solana/web3.js"),Wi=new q.PublicKey("EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"),qi=new q.PublicKey("CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T"),Ui=new q.PublicKey("9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z"),mo=new q.PublicKey("FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG"),Zm=new q.PublicKey("CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS"),wa=new q.PublicKey("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"),Gi=new q.PublicKey("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),zi=new q.PublicKey("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"),$m=new q.PublicKey("5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h"),ka=new q.PublicKey("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),Xi=new q.PublicKey("CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"),Ta=new q.PublicKey("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),ha=new q.PublicKey("kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy"),Yi=new q.PublicKey("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),jm=new q.PublicKey("routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS"),Ia=new q.PublicKey("7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"),po=new q.PublicKey("CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"),Ba=new q.PublicKey("GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"),Jm=new q.PublicKey("DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8"),Sa=new q.PublicKey("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),Ka=new q.PublicKey("3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH"),me=new q.PublicKey("LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"),ed=new q.PublicKey("WLHv2UAZm6z4KyaaELi5pjdbJh6RESMva1Rnn8pJVVh"),td=new q.PublicKey("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),nd=new q.PublicKey("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),od=new q.PublicKey("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),id=new q.PublicKey("6s1xP3hpbAfFoNtUNF8mfHsjr2Bd97JxFJRWLbL6aHuX");var tt={OPEN_BOOK_PROGRAM:new q.PublicKey("EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj"),SERUM_PROGRAM_ID_V3:new q.PublicKey("Ray1111111111111111111111111111111111111111"),AMM_V4:new q.PublicKey("DRaya7Kj3aMWQSy19kSjvmuwq9docCHofyP9kanQGaav"),AMM_STABLE:new q.PublicKey("DRayDdXc1NZQ9C3hRWmoSf8zK4iapgMnjdNZWrfwsP8m"),CLMM_PROGRAM_ID:new q.PublicKey("DRayAUgENGQBKVaX8owNhgzkEDyoHTGVEGHVJT1E9pfH"),CLMM_LOCK_PROGRAM_ID:new q.PublicKey("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),CLMM_LOCK_AUTH_ID:new q.PublicKey("6Aoh8h2Lw2m5UGxYR8AdAL87jTWYeKoxM52mJRzfYwN"),CREATE_CPMM_POOL_PROGRAM:new q.PublicKey("DRaycpLY18LhpbydsBWbVJtxpNv9oXPgjRSfpF2bWpYb"),CREATE_CPMM_POOL_AUTH:new q.PublicKey("CXniRufdq5xL8t8jZAPxsPZDpuudwuJSPWnbcD5Y5Nxq"),CREATE_CPMM_POOL_FEE_ACC:new q.PublicKey("3oE58BKVt8KuYkGxx8zBojugnymWmBiyafWgMrnb6eYy"),LOCK_CPMM_PROGRAM:new q.PublicKey("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),LOCK_CPMM_AUTH:new q.PublicKey("7qWVV8UY2bRJfDLP4s37YzBPKUkVB46DStYJBpYbQzu3"),UTIL1216:q.PublicKey.default,Router:new q.PublicKey("DRaybByLpbUL57LJARs3j8BitTxVfzBg351EaMr5UTCd"),FARM_PROGRAM_ID_V3:new q.PublicKey("DRayWyrLmEW5KEeqs8kdTMMaBabapqagaBC7KWpGtJeZ"),FARM_PROGRAM_ID_V4:new q.PublicKey("Ray1111111111111111111111111111111111111111"),FARM_PROGRAM_ID_V5:new q.PublicKey("DRayiCGSZgku1GTK6rXD6mVDdingXy6APAH1R6R5L2LC"),FARM_PROGRAM_ID_V6:new q.PublicKey("DRayzbYakXs45ELHkzH6vC3fuhQqTAnv5A68gdFuvZyZ"),LAUNCHPAD_PROGRAM:new q.PublicKey("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),LAUNCHPAD_AUTH:new q.PublicKey("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),LAUNCHPAD_PLATFORM:new q.PublicKey("2Jx4KTDrVSdWNazuGpcA8n3ZLTRGGBDxAWhuKe2Xcj2a"),LAUNCHPAD_CONFIG:new q.PublicKey("7ZR4zD7PYfY2XxoG1Gxcy2EgEeGYrpxrwzPuwdUBssEt"),FEE_DESTINATION_ID:new q.PublicKey("9y8ENuuZ3b19quffx9hQvRVygG5ky6snHfRvGpuSfeJy"),MODEL_DATA_PUBKEY:new q.PublicKey("Ray1111111111111111111111111111111111111111")};var uu=N(require("decimal.js"));var ko=require("@solana/spl-token"),hs=require("@solana/web3.js"),Is=N(require("bn.js")),Bs=N(require("decimal.js"));var Ca=require("@solana/spl-token"),Ra=require("@solana/web3.js");var xa=k([de("mintAuthorityOption"),m("mintAuthority"),o("supply"),w("decimals"),w("isInitialized"),de("freezeAuthorityOption"),m("freezeAuthority")]);var Ao=require("@solana/spl-token"),On=require("@solana/web3.js"),ws=N(require("bn.js"));var $=N(require("bn.js")),Ee=new $.default(1).shln(64);var La=new $.default(1).shln(128),Bn=new $.default(1).shln(64).subn(1),Oa=new $.default(1).shln(128).subn(1);var Kt=new $.default("4295048016"),xt=new $.default("79226673521066979257578248091"),Na=new $.default("59543866431248"),Ma=new $.default("184467440737095516"),Fa=new $.default("15793534762490258745");var fo=60,Cd=new $.default("18446743708227953217"),va=[{bit:0,factor:new $.default("fffcb933bd6fb800",16)},{bit:1,factor:new $.default("fff97272373d4000",16)},{bit:2,factor:new $.default("fff2e50f5f657000",16)},{bit:3,factor:new $.default("ffe5caca7e10f000",16)},{bit:4,factor:new $.default("ffcb9843d60f7000",16)},{bit:5,factor:new $.default("ff973b41fa98e800",16)},{bit:6,factor:new $.default("ff2ea16466c9b000",16)},{bit:7,factor:new $.default("fe5dee046a9a3800",16)},{bit:8,factor:new $.default("fcbe86c7900bb000",16)},{bit:9,factor:new $.default("f987a7253ac65800",16)},{bit:10,factor:new $.default("f3392b0822bb6000",16)},{bit:11,factor:new $.default("e7159475a2caf000",16)},{bit:12,factor:new $.default("d097f3bdfd2f2000",16)},{bit:13,factor:new $.default("a9f746462d9f8000",16)},{bit:14,factor:new $.default("70d869a156f31c00",16)},{bit:15,factor:new $.default("31be135f97ed3200",16)},{bit:16,factor:new $.default("9aa508b5b85a500",16)},{bit:17,factor:new $.default("5d6af8dedc582c",16)},{bit:18,factor:new $.default("2216e584f5fa",16)}];var Ht=3,Hi=100;var Qi=10,Zi=100,Sn=14;var Ae=new $.default(0),Ct=new $.default(1),Rd=new $.default(-1);var Ld=new $.default("18446744073700000000");var _a=k([H(8),w("bump"),ce("index"),m("owner"),de("protocolFeeRate"),de("tradeFeeRate"),ce("tickSpacing"),de("fundFeeRate"),C(de(),1),m("fundOwner"),C(o(),3)]),Va=k([de("blockTimestamp"),It("tickCumulative"),C(o(),4)]),$i=k([H(8),Fe("initialized"),o("recentEpoch"),ce("observationIndex"),m("poolId"),C(Va,Hi,"observations"),C(o(),4)]),Ea=k([ce("filterPeriod"),ce("decayPeriod"),ce("reductionFactor"),de("dynamicFeeControl"),de("maxVolatilityAccumulator"),Ve("tickSpacingIndexReference"),de("volatilityReference"),de("volatilityAccumulator"),o("lastUpdateTimestamp"),C(w(),46)]),Da=k([w("state"),o("openTime"),o("endTime"),o("lastUpdateTime"),X("emissionsPerSecondX64"),o("totalEmissioned"),o("claimed"),m("mint"),m("vault"),m("creator"),X("growthGlobalX64")]),yo=k([H(8),w("bump"),m("configId"),m("creator"),m("mintA"),m("mintB"),m("vaultA"),m("vaultB"),m("observationId"),w("mintDecimalsA"),w("mintDecimalsB"),ce("tickSpacing"),X("liquidity"),X("sqrtPriceX64"),Ve("tickCurrent"),de(),X("feeGrowthGlobalX64A"),X("feeGrowthGlobalX64B"),o("protocolFeesTokenA"),o("protocolFeesTokenB"),C(X(),4),w("status"),w("feeOn"),H(6),C(Da,Ht,"rewardInfos"),H(8*16,"tickArrayBitmap"),C(o(),4),o("fundFeesTokenA"),o("fundFeesTokenB"),o("startTime"),o("recentEpoch"),Ea.replicate("dynamicFeeInfo"),C(o(),46)]),Wa=k([X("growthInsideLastX64"),o("rewardAmountOwed")]),qa=k([H(8),w("bump"),m("nftMint"),m("poolId"),Ve("tickLower"),Ve("tickUpper"),X("liquidity"),X("feeGrowthInsideLastX64A"),X("feeGrowthInsideLastX64B"),o("tokenFeesOwedA"),o("tokenFeesOwedB"),C(Wa,Ht,"rewardInfos"),o("recentEpoch"),C(o(),7)]),Fd=k([H(8),w("bump"),m("poolId"),Ve("tickLower"),Ve("tickUpper"),X("liquidity"),X("feeGrowthInsideLastX64A"),X("feeGrowthInsideLastX64B"),o("tokenFeesOwedA"),o("tokenFeesOwedB"),C(X(),Ht,"rewardGrowthInside"),o("recentEpoch"),C(o(),7)]),Ua=k([Ve("tick"),Li("liquidityNet"),X("liquidityGross"),X("feeGrowthOutsideX64A"),X("feeGrowthOutsideX64B"),C(X(),Ht,"rewardGrowthsOutsideX64"),o("orderPhase"),o("ordersAmount"),o("partFilledOrdersRemaining"),X("unfilledRatioX64"),C(de(),3)]),ji=k([H(8),m("poolId"),Ve("startTickIndex"),C(Ua,fo,"ticks"),w("initializedTickCount"),o("recentEpoch"),C(w(),107)]),Ga=k([H(8),w("bump"),C(m(),Qi,"operationOwners"),C(m(),Zi,"whitelistMints")]),za=k([H(8),m("poolId"),m("owner"),Ve("tick"),Fe("zeroForOne"),o("orderPhase"),o("totalAmount"),o("filledAmount"),o("settleBase"),o("settleOutput"),o("openTime"),X("unfilledRatioX64"),C(o(),4)]),Ji=k([H(8),m("poolId"),H(8*8*Sn,"positiveTickArrayBitmap"),H(8*8*Sn,"negativeTickArrayBitmap")]),vd=k([H(8),ce("index"),ce("filterPeriod"),ce("decayPeriod"),ce("reductionFactor"),de("dynamicFeeControl"),de("maxVolatilityAccumulator"),C(o(),8)]),Xa=k([H(8),m("wallet"),w("nonceIndex"),o("orderNonce"),C(o(),4)]),_d=k([o(),w("bump"),m("owner"),m("poolId"),m("positionId"),m("nftAccount"),C(o(),8)]),Ya=k([H(8),w("bump"),m("lockOwner"),m("poolId"),m("positionId"),m("nftAccount"),m("lockNftMint"),o("recentEpoch"),C(o(),8)]);var Ha=N(require("bn.js"));function bo(a){let e=Buffer.alloc(2);return e.writeUInt16LE(a),e}var Qd=Buffer.from("amm_config","utf8"),er=Buffer.from("pool","utf8"),tr=Buffer.from("pool_vault","utf8"),Zd=Buffer.from("pool_reward_vault","utf8"),$d=Buffer.from("position","utf8"),jd=Buffer.from("tick_array","utf8"),Jd=Buffer.from("operation","utf8"),ep=Buffer.from("pool_tick_array_bitmap_extension","utf8"),tp=Buffer.from("observation","utf8"),np=Buffer.from("support_mint","utf8"),op=Buffer.from("dynamic_fee_config","utf8"),ip=Buffer.from("permission","utf8");function Kn(a){return le([Buffer.from("metadata","utf8"),mt.toBuffer(),a.toBuffer()],mt)}var rp=Buffer.from("locked_position","utf8");var sr=require("js-sha256");var nr=N(require("bn.js")),Qa=N(require("decimal.js"));var up=new nr.default(1).shln(256).subn(1);var ja=N(require("bn.js"));var Za=N(require("bn.js")),$a=N(require("decimal.js"));var ts=N(require("bn.js")),ns=N(require("decimal.js"));var cs=require("@solana/web3.js"),ls=N(require("bn.js"));var ar=require("@solana/spl-token");var ms=N(require("decimal.js"));var as=N(require("bn.js"));var is=N(require("bn.js"));var fs=N(require("bn.js"));function we(a){let e=`global:${a}`;return Buffer.from(sr.sha256.digest(e)).slice(0,8)}$i.span;var oy=j("Raydium_Clmm"),iy={createPool:we("create_pool"),createCustomizablePool:we("create_customizable_pool"),createPermissionedPool:we("create_permissioned_pool"),openPositionV2:we("open_position_v2"),openPositionWithToken22Nft:we("open_position_with_token22_nft"),closePosition:we("close_position"),increaseLiquidityV2:we("increase_liquidity_v2"),decreaseLiquidityV2:we("decrease_liquidity_v2"),initializeReward:we("initialize_reward"),setRewardParams:we("set_reward_params"),updateRewardInfos:we("update_reward_infos"),collectRemainingRewards:we("collect_remaining_rewards"),swapV2:we("swap_v2"),openLimitOrder:we("open_limit_order"),increaseLimitOrder:we("increase_limit_order"),decreaseLimitOrder:we("decrease_limit_order"),settleLimitOrder:we("settle_limit_order"),closeLimitOrder:we("close_limit_order")};var Nn=require("@solana/web3.js");var Ks=k([w("instruction")]),xs=k([w("instruction")]),Cs=k([o("rewardState"),o("rewardOpenTime"),o("rewardEndTime"),o("rewardLastUpdateTime"),o("totalReward"),o("totalRewardEmissioned"),o("rewardClaimed"),o("rewardPerSecond"),X("accRewardPerShare"),m("rewardVault"),m("rewardMint"),m("rewardSender"),o("rewardType"),C(o(),15,"padding")]),Rs=k([o("state"),o("nonce"),m("lpVault"),m("rewardVault"),m(),m(),o(),o(),o("totalReward"),X("perShareReward"),o("lastSlot"),o("perSlotReward")]),Ls=k([o("state"),o("nonce"),m("lpVault"),m("rewardVaultA"),o("totalRewardA"),X("perShareRewardA"),o("perSlotRewardA"),w("option"),m("rewardVaultB"),H(7),o("totalRewardB"),X("perShareRewardB"),o("perSlotRewardB"),o("lastSlot"),m()]),Os=k([o(),o("state"),o("nonce"),o("validRewardTokenNum"),X("rewardMultiplier"),o("rewardPeriodMax"),o("rewardPeriodMin"),o("rewardPeriodExtend"),m("lpMint"),m("lpVault"),C(Cs,5,"rewardInfos"),m("creator"),m(),C(o(),32,"padding")]),Ns=new Proxy(Rs,{get(a,e,t){return e==="decode"?(...n)=>{let i=a.decode(...n);return z(v({},i),{version:3,rewardInfos:[{rewardVault:i.rewardVault,totalReward:i.totalReward,perSlotReward:i.perSlotReward,perShareReward:i.perShareReward}]})}:Reflect.get(a,e,t)}}),Ms=new Proxy(Ls,{get(a,e,t){return e==="decode"?(...n)=>{let i=a.decode(...n);return z(v({},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)}}),lr=new Proxy(Os,{get(a,e,t){return e==="decode"?(...n)=>{let i=a.decode(...n);return z(v({},i),{version:6,rewardInfos:i.rewardInfos.map(r=>{var s;return z(v({},r),{rewardType:((s=Object.entries($t).find(l=>String(l[1])===r.rewardType.toString()))!=null?s:["Standard SPL"])[0]})})})}:Reflect.get(a,e,t)}}),Fs=k([o("isSet"),o("rewardPerSecond"),o("rewardOpenTime"),o("rewardEndTime"),o("rewardType")]),vs=k([w("instruction"),o("nonce"),C(Fs,5,"rewardTimeInfo")]),_s=k([w("instruction"),o("rewardReopenTime"),o("rewardEndTime"),o("rewardPerSecond")]),Vs=k([w("instruction"),o("isSet"),o("rewardPerSecond"),o("rewardOpenTime"),o("rewardEndTime"),o("rewardType")]),Uy=k([o("state"),m("id"),m("owner"),o("deposited"),C(o(),1,"rewardDebts")]),mr=k([o("state"),m("id"),m("owner"),o("deposited"),C(X(),1,"rewardDebts"),o(""),o("voteLockedBalance"),C(o(),15)]),Gy=k([o("state"),m("id"),m("owner"),o("deposited"),C(o(),2,"rewardDebts")]),Es=k([o("state"),m("id"),m("owner"),o("deposited"),C(X(),2,"rewardDebts"),C(o(),17)]),Ds=k([o(),o("state"),m("id"),m("owner"),o("deposited"),C(X(),5,"rewardDebts"),C(o(),16)]),Ws=k([w("instruction"),o("amount")]),qs=k([m("mint"),m("grantAuthority"),o("baselineVoteWeightScaledFactor"),o("maxExtraLockupVoteWeightScaledFactor"),o("lockupSaturationSecs"),Ri("digitShift"),C(w(),7,"reserved1"),C(o(),7,"reserved2")]),Us=k([H(8),m("governanceProgramId"),m("realm"),m("realmGoverningTokenMint"),m("realmAuthority"),C(w(),32,"reserved1"),C(qs,4,"votingMints"),It("timeOffset"),w("bump"),C(w(),7,"reserved2"),C(o(),11,"reserved3")]),Gs=k([It("startTime"),It("endTime"),w("kind"),C(w(),15,"reserved")]),zs=k([C(Gs,1,"lockup"),o("amountDeposited_native"),o("amountInitiallyLockedNative"),Fe("isUsed"),Fe("allowClawback"),w("votingMintConfigIdx"),C(w(),29,"reserved")]),Xs=k([H(8),m("voterAuthority"),m("registrar"),C(zs,32,"deposits"),w("voterBump"),w("voterWweightRecordBump"),C(w(),94,"reserved")]);var Ys=require("@solana/spl-token"),$y=j("Raydium_farm_config"),Hs=new Nn.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Qs=new Nn.PublicKey("FrspKwj8i3pNmKwXreTveC4fu7KL5ZbGeXdZBe2XViu1");var jy=new Nn.PublicKey("3TRTX4dXUpp2eqxi3tvQDFYUV7SdDJjcPE3Y4mbtftaX");var $t={"Standard SPL":0,"Option tokens":1},dr={[Wi.toString()]:3,[qi.toString()]:4,[Ui.toString()]:5,[mo.toString()]:6,[tt.FARM_PROGRAM_ID_V3.toString()]:3,[tt.FARM_PROGRAM_ID_V4.toString()]:4,[tt.FARM_PROGRAM_ID_V5.toString()]:5,[tt.FARM_PROGRAM_ID_V6.toString()]:6};var jt=require("@solana/web3.js"),tu=N(require("bn.js")),ho=require("@solana/spl-token");var eu=N(require("bn.js"));var Zs=require("@solana/web3.js"),$s=N(require("bn.js"));var wb=j("Raydium.farm.util");var Db=j("Raydium_farm_instruction"),Wb={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])};var cu=N(require("bn.js"));var vu=require("@solana/web3.js"),_n=require("@solana/spl-token");var Te=N(require("bn.js")),Jt=1e4;function Mn(a,e){let{div:t,mod:n}=a.divmod(e);return n.gt(new Te.default(0))?t.add(new Te.default(1)):t}function bt(a,e){if(a.isZero())return new Te.default(0);let t=a.div(e);return t.isZero()?new Te.default(1):a.mod(e).gt(new Te.default(0))?t.add(new Te.default(1)):t}function en(a,e,t){if(e===void 0)return{amount:a,fee:void 0,expirationTime:void 0};let n=Math.floor(t/432e3),i=n<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,r=new Te.default(i.maximumFee.toString()),s=n<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*432e3-t)*400/1e3:void 0,l=Mn(a.mul(new Te.default(i.transferFeeBasisPoints)),new Te.default(Jt)),c=l.gt(r)?r:l;return{amount:a,fee:c,expirationTime:s}}function Lt(a,e,t){if(e===void 0)return{amount:a,fee:void 0,expirationTime:void 0};let n=Math.floor(t/432e3),i=n<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,r=new Te.default(i.maximumFee.toString()),s=n<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*432e3-t)*400/1e3:void 0;if(i.transferFeeBasisPoints===Jt){let l=new Te.default(i.maximumFee.toString());return{amount:a.add(l),fee:l,expirationTime:s}}else{let l=Mn(a.mul(new Te.default(Jt)),new Te.default(Jt-i.transferFeeBasisPoints)),c=new Te.default(i.maximumFee.toString()),u=l.sub(a).gt(c)?a.add(c):l,d=Mn(u.mul(new Te.default(i.transferFeeBasisPoints)),new Te.default(Jt)),p=d.gt(r)?r:d;return{amount:u,fee:p,expirationTime:s}}}var Io=N(require("bn.js")),lu=new Io.default(25),mu=new Io.default(1e4);var br=require("@solana/spl-token"),Fn=require("@solana/web3.js");var Pu=N(require("bn.js"));var du=k([w("instruction"),o("amountIn"),o("minAmountOut")]),pu=k([w("instruction"),o("maxAmountIn"),o("amountOut")]),_g=k([w("instruction"),w("nonce")]),fu=k([w("instruction"),w("nonce"),o("startTime")]),yr=k([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"),X("swapBaseInAmount"),X("swapQuoteOutAmount"),o("swapBase2QuoteFee"),X("swapQuoteInAmount"),X("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"),C(o(),3,"padding")]),Vg=k([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"),X("swapBaseInAmount"),X("swapQuoteOutAmount"),X("swapQuoteInAmount"),X("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"),C(o(),64,"padding")]),yu=k([w("instruction"),o("baseAmountIn"),o("quoteAmountIn"),o("fixedSide"),o("otherAmountMin")]),bu=k([w("instruction"),o("lpAmount"),o("baseAmountMin"),o("quoteAmountMin")]);var gu=k([o("fee")]);var Hg=j("Raydium_liquidity_instruction");var Au=5e4,wu=k([o("x"),o("y"),o("price")]),jg=k([o("accountType"),o("status"),o("multiplier"),o("validDataCount"),C(wu,Au,"DataElement")]);var Tu=require("@solana/web3.js"),hu=N(require("decimal.js")),Iu=require("@solana/spl-token");var ku=require("@solana/web3.js");var oP=j("Raydium_liquidity_serum");var _u=N(require("bn.js")),Vu=N(require("decimal.js"));var xu=require("@solana/spl-token"),Cu=require("@solana/web3.js"),Ru=N(require("bn.js"));var vn=require("@solana/web3.js"),gr=require("@solana/spl-token");function Bu(a="accountFlags"){let e=new Pn(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 Su=k([H(5),Bu("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"),H(7)]);var zu=require("@solana/web3.js"),tn=require("@solana/spl-token");var Du=N(require("bn.js"));var Pr=N(require("bn.js"));var PA=new Pr.default(0);var Eu=N(require("bn.js"));var Ar=N(require("bn.js")),ze=new Ar.default(1e6);var Xu=N(require("bn.js")),Yu=N(require("decimal.js"));var Vn=require("@solana/web3.js"),So=require("@solana/spl-token");var OA=Buffer.from("vault_and_lp_mint_auth_seed","utf8"),NA=Buffer.from("amm_config","utf8"),MA=Buffer.from("pool","utf8"),FA=Buffer.from("pool_lp_mint","utf8"),vA=Buffer.from("pool_vault","utf8"),_A=Buffer.from("observation","utf8"),VA=Buffer.from("permission","utf8"),EA=Buffer.from("support_mint","utf8"),DA=Buffer.from("creator_fee_share","utf8");var WA=Buffer.from("locked_liquidity","utf8");var JA=j("Raydium_cpmm"),ew={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 qu=k([H(8),w("bump"),Fe("disableCreatePool"),ce("index"),o("tradeFeeRate"),o("protocolFeeRate"),o("fundFeeRate"),o("createPoolFee"),m("protocolOwner"),m("fundOwner"),o("creatorFeeRate"),o("creatorFeeShareRate"),C(o(),14)]),wr=k([H(8),m("configId"),m("poolCreator"),m("vaultA"),m("vaultB"),m("mintLp"),m("mintA"),m("mintB"),m("mintProgramA"),m("mintProgramB"),m("observationId"),w("bump"),w("status"),w("lpDecimals"),w("mintDecimalA"),w("mintDecimalB"),o("lpAmount"),o("protocolFeesMintA"),o("protocolFeesMintB"),o("fundFeesMintA"),o("fundFeesMintB"),o("openTime"),o("epoch"),w("feeOn"),Fe("enableCreatorFee"),C(w(),6),o("creatorFeesMintA"),o("creatorFeesMintB"),C(o(),28)]),ow=k([H(8),m("configId"),C(o(),30)]),iw=k([H(8),w("bump"),m("creator"),m("ammConfig"),o("shareRate"),C(o(),8)]);var _r=require("@solana/web3.js"),vt=require("@solana/spl-token"),Vr=N(require("bn.js")),dc=N(require("decimal.js"));var je=require("@solana/spl-token"),Q=require("@solana/web3.js"),Pt=N(require("bn.js"));var Hu=Buffer.from("vault_auth_seed","utf8"),Qu=Buffer.from("global_config","utf8"),Zu=Buffer.from("pool_vesting","utf8"),$u=Buffer.from("platform_config","utf8"),ju=Buffer.from("platform_fee_vault_auth_seed","utf8"),Ju=Buffer.from("creator_fee_vault_auth_seed","utf8"),Ak=Buffer.from("platform_global_access","utf8"),ec=Buffer.from("platform_allow_config","utf8"),tc=Buffer.from("platform_curve_rule","utf8");function De(a){return le([Hu],a)}function Ko(a,e,t,n){return le([Qu,e.toBuffer(),nc(t),bo(n)],a)}function Ot(a,e,t){return le([er,e.toBuffer(),t.toBuffer()],a)}function xo(a,e,t){return le([tr,e.toBuffer(),t.toBuffer()],a)}function gt(a){return le([Buffer.from("__event_authority","utf8")],a)}function nc(a){let e=new ArrayBuffer(1);return new DataView(e).setUint8(0,a),new Uint8Array(e)}function Co(a,e){return le([$u,e.toBuffer()],a)}function Nt(a,e,t){return le([Zu,e.toBuffer(),t.toBuffer()],a)}function nt(a,e,t){return le([e.toBuffer(),t.toBuffer()],a)}function Ro(a){return le([ju],a)}function ot(a,e,t){return le([e.toBuffer(),t.toBuffer()],a)}function Lo(a){return le([Ju],a)}function nn(a,e,t){return le([ec,e.toBuffer(),t.toBuffer()],a)}function Oo(a,e,t){return le([tc,e.toBuffer(),t.toBuffer()],a)}var ye={initialize:Buffer.from([175,175,109,31,13,152,155,237]),initializeV2:Buffer.from([67,153,175,39,218,16,38,32]),buyExactIn:Buffer.from([250,234,13,123,213,156,19,236]),buyExactOut:Buffer.from([24,211,116,40,105,3,153,56]),sellExactIn:Buffer.from([149,39,222,155,211,124,152,26]),sellExactOut:Buffer.from([95,200,71,34,8,9,11,166]),createVestingAccount:Buffer.from([129,178,2,13,217,172,230,218]),claimVestedToken:Buffer.from([49,33,104,30,189,157,79,35]),createPlatformConfig:Buffer.from([176,90,196,175,253,113,220,20]),claimPlatformFee:Buffer.from([156,39,208,135,76,237,61,72]),updatePlaformConfig:Buffer.from([195,60,76,129,146,45,67,143]),initializeWithToken2022:Buffer.from([37,190,126,222,44,154,171,17]),claimPlatformFeeFromVault:Buffer.from([117,241,198,168,248,218,80,29]),claimCreatorFee:Buffer.from([26,97,138,203,132,171,141,252]),createPlatformVestingAccount:Buffer.from([146,71,173,69,98,19,15,106]),createPlatformAllowConfig:Buffer.from([69,71,168,7,214,250,107,102]),closePlatformAllowConfig:Buffer.from([82,205,36,216,16,6,240,215]),createPlatformCurveRule:Buffer.from([148,71,180,136,122,144,59,21]),updatePlatformCurveRule:Buffer.from([90,100,206,196,54,117,120,139]),removePlatformCurveRule:Buffer.from([236,77,154,138,32,145,127,219]),closePlatformCurveRule:Buffer.from([194,114,82,45,136,88,169,159])};function Tr(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f,y,P,T,I,S,x,h,B,R){let K=k([w("decimals"),Le("name"),Le("symbol"),Le("uri")]),L=k([o("totalLockedAmount"),o("cliffPeriod"),o("unlockPeriod"),w("cpmmCreatorFeeOn")]),F=k([w("index"),o("supply"),o("totalFundRaisingB"),w("migrateType")]),W=k([w("index"),o("supply"),o("totalSellA"),o("totalFundRaisingB"),w("migrateType")]),G=[{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:je.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:g,isSigner:!1,isWritable:!1},{pubkey:mt,isSigner:!1,isWritable:!1},{pubkey:Q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:Tt,isSigner:!1,isWritable:!1},{pubkey:gt(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];B&&G.push({pubkey:B,isSigner:!1,isWritable:!1}),R&&G.push({pubkey:R,isSigner:!1,isWritable:!1});let D=Buffer.alloc(Buffer.from(f,"utf-8").length+Buffer.from(y,"utf-8").length+Buffer.from(P,"utf-8").length+4*3+1),M=Buffer.alloc(L.span),U=Buffer.alloc(T.type==="ConstantCurve"?W.span:F.span);return K.encode({decimals:b,name:f,symbol:y,uri:P},D),T.type==="ConstantCurve"?W.encode(z(v({index:0},T),{migrateType:T.migrateType==="amm"?0:1}),U):T.type==="FixedCurve"?F.encode(z(v({index:1},T),{migrateType:T.migrateType==="amm"?0:1}),U):T.type==="LinearCurve"&&F.encode(z(v({index:2},T),{migrateType:T.migrateType==="amm"?0:1}),U),L.encode({totalLockedAmount:I,cliffPeriod:S,unlockPeriod:x,cpmmCreatorFeeOn:h},M),new Q.TransactionInstruction({keys:G,programId:a,data:Buffer.from([...ye.initializeV2,...D,...U,...M])})}function hr(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f,y,P,T,I,S,x,h,B,R){let K=k([w("decimals"),Le("name"),Le("symbol"),Le("uri")]),L=k([o("totalLockedAmount"),o("cliffPeriod"),o("unlockPeriod"),w("cpmmCreatorFeeOn"),w("transferFeeExtensionParamsOption"),k([ce("transferFeeBasePoints"),o("maxinumFee")]).replicate("transferFeeExtensionParams")]),F=k([w("index"),o("supply"),o("totalFundRaisingB"),w("migrateType")]),W=k([w("index"),o("supply"),o("totalSellA"),o("totalFundRaisingB"),w("migrateType")]),G=[{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:je.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:Q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:gt(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];B&&G.push({pubkey:B,isSigner:!1,isWritable:!1}),R&&G.push({pubkey:R,isSigner:!1,isWritable:!1});let D=Buffer.alloc(Buffer.from(b,"utf-8").length+Buffer.from(f,"utf-8").length+Buffer.from(y,"utf-8").length+4*3+1),M=Buffer.alloc(L.span),U=Buffer.alloc(P.type==="ConstantCurve"?W.span:F.span);return K.encode({decimals:g,name:b,symbol:f,uri:y},D),P.type==="ConstantCurve"?W.encode(z(v({index:0},P),{migrateType:P.migrateType==="amm"?0:1}),U):P.type==="FixedCurve"?F.encode(z(v({index:1},P),{migrateType:P.migrateType==="amm"?0:1}),U):P.type==="LinearCurve"&&F.encode(z(v({index:2},P),{migrateType:P.migrateType==="amm"?0:1}),U),L.encode({totalLockedAmount:T,cliffPeriod:I,unlockPeriod:S,cpmmCreatorFeeOn:x,transferFeeExtensionParamsOption:h?1:0,transferFeeExtensionParams:h!=null?h:{transferFeeBasePoints:0,maxinumFee:new Pt.default(0)}},M),new Q.TransactionInstruction({keys:G,programId:a,data:Buffer.from([...ye.initializeWithToken2022,...D,...U,...M])})}function No(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f,y,P,T,I,S){let x=k([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:g,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:gt(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];S&&h.push({pubkey:S,isSigner:!1,isWritable:!0}),h.push({pubkey:Q.SystemProgram.programId,isSigner:!1,isWritable:!1}),h.push({pubkey:f,isSigner:!1,isWritable:!0}),h.push({pubkey:y,isSigner:!1,isWritable:!0});let B=Buffer.alloc(x.span);return x.encode({amountB:P,minAmountA:T,shareFeeRate:I!=null?I:new Pt.default(0)},B),new Q.TransactionInstruction({keys:h,programId:a,data:Buffer.from([...ye.buyExactIn,...B])})}function Ir(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f,y,P,T,I,S){let x=k([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:g,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:gt(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];S&&h.push({pubkey:S,isSigner:!1,isWritable:!0}),h.push({pubkey:Q.SystemProgram.programId,isSigner:!1,isWritable:!1}),h.push({pubkey:f,isSigner:!1,isWritable:!0}),h.push({pubkey:y,isSigner:!1,isWritable:!0});let B=Buffer.alloc(x.span);return x.encode({amountA:P,maxAmountB:T,shareFeeRate:I!=null?I:new Pt.default(0)},B),new Q.TransactionInstruction({keys:h,programId:a,data:Buffer.from([...ye.buyExactOut,...B])})}function Mo(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f,y,P,T,I,S){let x=k([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:g,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:gt(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];S&&h.push({pubkey:S,isSigner:!1,isWritable:!0}),h.push({pubkey:Q.SystemProgram.programId,isSigner:!1,isWritable:!1}),h.push({pubkey:f,isSigner:!1,isWritable:!0}),h.push({pubkey:y,isSigner:!1,isWritable:!0});let B=Buffer.alloc(x.span);return x.encode({amountA:P,minAmountB:T,shareFeeRate:I!=null?I:new Pt.default(0)},B),new Q.TransactionInstruction({keys:h,programId:a,data:Buffer.from([...ye.sellExactIn,...B])})}function Br(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f,y,P,T,I,S){let x=k([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:g,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:gt(a).publicKey,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];S&&h.push({pubkey:S,isSigner:!1,isWritable:!0}),h.push({pubkey:Q.SystemProgram.programId,isSigner:!1,isWritable:!1}),h.push({pubkey:f,isSigner:!1,isWritable:!0}),h.push({pubkey:y,isSigner:!1,isWritable:!0});let B=Buffer.alloc(x.span);return x.encode({amountB:P,maxAmountA:T,shareFeeRate:I!=null?I:new Pt.default(0)},B),new Q.TransactionInstruction({keys:h,programId:a,data:Buffer.from([...ye.sellExactOut,...B])})}function Fo(a,e,t,n,i,r,s,l,c){let u=k([]),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:Q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:je.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}],p=Buffer.alloc(u.span);return u.encode({},p),new Q.TransactionInstruction({keys:d,programId:a,data:Buffer.from([...ye.claimVestedToken,...p])})}function vo(a,e,t,n,i,r){let s=k([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:Q.SystemProgram.programId,isSigner:!1,isWritable:!1}],c=Buffer.alloc(s.span);return s.encode({shareAmount:r},c),new Q.TransactionInstruction({keys:l,programId:a,data:Buffer.from([...ye.createVestingAccount,...c])})}function _o(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:Q.SystemProgram.programId,isSigner:!1,isWritable:!0},{pubkey:je.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!0}];return new Q.TransactionInstruction({keys:u,programId:a,data:ye.claimPlatformFee})}function Sr(a,e,t,n,i,r,s,l,c,u,d,p,g,b,f){let y=k([o("platformScale"),o("creatorScale"),o("burnScale"),o("feeRate"),Le("name"),Le("web"),Le("img"),o("creatorFeeRate"),o("platformVestingScale")]),P=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:Q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1}],T=Buffer.alloc(8*6+Buffer.from(p,"utf-8").length+Buffer.from(g,"utf-8").length+Buffer.from(b,"utf-8").length+4*3);return y.encode({platformScale:c.platformScale,creatorScale:c.creatorScale,burnScale:c.burnScale,feeRate:u,name:p,web:g,img:b,creatorFeeRate:d,platformVestingScale:f},T),new Q.TransactionInstruction({keys:P,programId:a,data:Buffer.from([...ye.createPlatformConfig,...T])})}function Kr(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=k([w("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:0,value:n.value},r)}else if(n.type==="updateLockNftWallet"){let s=k([w("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:1,value:n.value},r)}else if(n.type==="migrateCpLockNftScale"){let s=k([w("index"),o("platformScale"),o("creatorScale"),o("burnScale")]);r=Buffer.alloc(s.span),s.encode(v({index:2},n.value),r)}else if(n.type==="updateFeeRate"){let s=k([w("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=k([w("index"),Le("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=k([w("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=k([w("index"),m("platformClaimFeeWallet"),m("platformLockNftWallet"),o("platformScale"),o("creatorScale"),o("burnScale"),o("feeRate"),Le("name"),Le("web"),Le("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=k([w("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:9,value:n.value},r)}else if(n.type==="updatePlatformVestingScale"){let s=k([w("index"),o("value")]);r=Buffer.alloc(s.span),s.encode({index:10,value:n.value},r)}else if(n.type==="updatePlatformCpCreator"){let s=k([w("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:11,value:n.value},r)}else if(n.type==="updateRestrictGlobalConfig"){let s=k([w("index"),o("value")]);r=Buffer.alloc(s.span),s.encode({index:12,value:n.value},r)}else if(n.type==="updateRestrictCurveParam"){let s=k([w("index"),o("value")]);r=Buffer.alloc(s.span),s.encode({index:13,value:n.value},r)}else if(n.type==="updateCurveRuleManager"){let s=k([w("index"),m("value")]);r=Buffer.alloc(s.span),s.encode({index:14,value:n.value},r)}else throw Error("updateInfo params type error");return new Q.TransactionInstruction({keys:i,programId:a,data:Buffer.from([...ye.updatePlaformConfig,...r])})}function Vo(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:Q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:je.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}];return new Q.TransactionInstruction({keys:c,programId:a,data:ye.claimPlatformFeeFromVault})}function Eo(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:Q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:je.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}];return new Q.TransactionInstruction({keys:l,programId:a,data:ye.claimCreatorFee})}var Sk=new Pt.default("18446744073709551615");function xr(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:Q.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new Q.TransactionInstruction({keys:s,programId:a,data:ye.createPlatformVestingAccount})}function Cr(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:Q.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new Q.TransactionInstruction({keys:r,programId:a,data:ye.createPlatformAllowConfig})}function Rr(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 Q.TransactionInstruction({keys:r,programId:a,data:ye.closePlatformAllowConfig})}function oc(a){let e=k([w("field"),w("op"),X("value")]),t=Buffer.alloc(4+a.length*e.span);return t.writeUInt32LE(a.length,0),a.forEach((n,i)=>{e.encode(n,t,4+i*e.span)}),t}function Lr(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:Q.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new Q.TransactionInstruction({keys:r,programId:a,data:ye.createPlatformCurveRule})}function Or(a,e,t,n,i,r,s){let l=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:Q.SystemProgram.programId,isSigner:!1,isWritable:!1}],c=Buffer.alloc(ce().span);return ce().encode(r,c),new Q.TransactionInstruction({keys:l,programId:a,data:Buffer.from([...ye.updatePlatformCurveRule,...c,...oc(s)])})}function Nr(a,e,t,n,i,r){let s=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:Q.SystemProgram.programId,isSigner:!1,isWritable:!1}],l=Buffer.alloc(ce().span);return ce().encode(r,l),new Q.TransactionInstruction({keys:s,programId:a,data:Buffer.from([...ye.removePlatformCurveRule,...l])})}function Mr(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 Q.TransactionInstruction({keys:r,programId:a,data:ye.closePlatformCurveRule})}var it=k([o(),o("epoch"),w("curveType"),ce("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"),C(o(),16)]),ic=k([o("totalLockedAmount"),o("cliffPeriod"),o("unlockPeriod"),o("startTime"),o("totalAllocatedShare")]),We=k([o(),o("epoch"),w("bump"),w("status"),w("mintDecimalsA"),w("mintDecimalsB"),w("migrateType"),o("supply"),o("totalSellA"),o("virtualA"),o("virtualB"),o("realA"),o("realB"),o("totalFundRaisingB"),o("protocolFee"),o("platformFee"),o("migrateFee"),ic.replicate("vestingSchedule"),m("configId"),m("platformId"),m("mintA"),m("mintB"),m("vaultA"),m("vaultB"),m("creator"),w("mintProgramFlag"),w("cpmmCreatorFeeOn"),o("platformVestingShare"),C(w(),54)]),Rk=k([o(),o("epoch"),m("poolId"),m("beneficiary"),o("claimedAmount"),o("tokenShareAmount"),C(o(),8)]),rc=k([w("migrateType"),w("migrateCpmmFeeOn"),o("supply"),o("totalSellA"),o("totalFundRaisingB"),o("totalLockedAmount"),o("cliffPeriod"),o("unlockPeriod")]),Lk=k([o("epoch"),w("index"),m("configId"),rc.replicate("bondingCurveParam"),C(o(),50)]),At=k([o(),o("epoch"),m("platformClaimFeeWallet"),m("platformLockNftWallet"),o("platformScale"),o("creatorScale"),o("burnScale"),o("feeRate"),C(w(),64,"name"),C(w(),256,"web"),C(w(),256,"img"),m("cpConfigId"),o("creatorFeeRate"),m("transferFeeExtensionAuth"),m("platformVestingWallet"),o("platformVestingScale"),m("platformCpCreator"),w("restrictGlobalConfig"),w("restrictCurveParam"),m("curveRuleManager"),C(w(),78)]),ac=k([w("field"),w("op"),X("value")]),sc=k([ce("groupId"),o("epoch"),co(ac,"constraints")]),En=k([o(),w("bump"),w("version"),m("platformId"),m("configId"),o("epoch"),C(o(),8),co(sc,"groups")]);var Dn=require("@solana/spl-token");function Fr({mintAProgram:a,mintBProgram:e}){return(a.equals(Dn.TOKEN_2022_PROGRAM_ID)?1<<0:0)|(e.equals(Dn.TOKEN_2022_PROGRAM_ID)?1<<1:0)}var vr=N(require("bn.js"));var Uk=new vr.default(1e6);var on=N(require("bn.js")),Mt=N(require("decimal.js"));var rt=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 Wn=class extends rt{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new Mt.default(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i}){return new Mt.default(t.toString()).div(e.toString()).mul(10**(n-i))}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new Mt.default(e.virtualB.add(e.realB).toString()).div(e.virtualA.sub(e.realA).toString()).mul(10**(t-n))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:i,migrateFee:r,decimalA:s,decimalB:l}){return new Mt.default(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 Mt.default(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 on.default(0)))throw Error("supplyMinusSellLocked <= 0");let l=t.sub(r);if(l.lte(new on.default(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 on.default(0))||p.lt(new on.default(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 bt(i,r)}};var Re=N(require("bn.js")),Wo=N(require("decimal.js"));var rn=N(require("bn.js")),Ft=N(require("decimal.js"));var qn=class extends rt{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new Ft.default(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i}){return new Ft.default(t.toString()).div(e.toString()).mul(10**(n-i))}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new Ft.default(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 Ft.default(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 Ft.default(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 rn.default(0)))throw Error("invalid input 1");let l=new rn.default(2).mul(t).sub(r),u=t.mul(s).div(l);if(u.lt(new rn.default(0))||t.lt(new rn.default(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 bt(i,n)}};var Ce=N(require("bn.js")),at=N(require("decimal.js"));var Do=N(require("bn.js")),Un=N(require("decimal.js")),an=class{static _multipler(e){return new Un.default(10).pow(e)}static getPrice({priceX64:e,decimalA:t,decimalB:n}){return new Un.default(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 Do.default(i.mul(this._Q64).toFixed(0))}};an._Q64=new Un.default(new Do.default(1).shln(64).toString());var Gn=class extends rt{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new at.default(0)}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:i}){return new at.default(0)}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new at.default(e.virtualA.mul(e.realA).toString()).div(an._Q64).mul(10**(t-n))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:i,migrateFee:r,decimalA:s,decimalB:l}){return new at.default(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 at.default(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.default(0)))throw Error("supplyMinusLocked need gt 0");let l=t.mul(new Ce.default(3)).sub(r),u=t.mul(new Ce.default(2)).mul(s).div(l),d=u.mul(u),p=t.mul(new Ce.default(2)).mul(Ee).div(d);if(!p.gt(new Ce.default(0)))throw Error("a need gt 0");if(!Bn.gt(p))throw Error("a need lt u64 max");if(p.lt(new Ce.default(0))||u.lt(new Ce.default(0)))throw Error("invalid input 0");return{a:p,b:new Ce.default(0),c:u}}static buyExactIn({poolInfo:e,amount:t}){let n=e.realB.add(t),i=new Ce.default(2).mul(n).mul(Ee).div(e.virtualA);return new Ce.default(new at.default(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 bt(e.virtualA.mul(i),new Ce.default(2).mul(Ee)).sub(e.realB)}static sellExactIn({poolInfo:e,amount:t}){let n=e.realA.sub(t),i=n.mul(n),r=bt(e.virtualA.mul(i),new Ce.default(2).mul(Ee));return e.realB.sub(r)}static sellExactOut({poolInfo:e,amount:t}){let n=e.realB.sub(t),i=new Ce.default(2).mul(n).mul(Ee).div(e.virtualA),r=new Ce.default(new at.default(i.toString()).sqrt().toFixed(0));return e.realA.sub(r)}};var Me=class{static getPoolCurvePointByPoolInfo({curveType:e,pointCount:t,poolInfo:n}){return this.getPoolCurvePointByInit({curveType:e,pointCount:t,supply:n.supply,totalFundRaising:n.totalFundRaisingB,totalSell:n.totalSellA,totalLockedAmount:n.vestingSchedule.totalLockedAmount,migrateFee:n.migrateFee,decimalA:n.mintDecimalsA,decimalB:n.mintDecimalsB})}static getPoolCurvePointByInit({curveType:e,pointCount:t,supply:n,totalFundRaising:i,totalSell:r,totalLockedAmount:s,migrateFee:l,decimalA:c,decimalB:u}){if(t<3)throw Error("point count < 3");let d=this.getCurve(e),p=d.getInitParam({supply:n,totalFundRaising:i,totalSell:r,totalLockedAmount:s,migrateFee:l}),g=d.getPoolInitPriceByInit(z(v({},p),{decimalA:c,decimalB:u})),b=i.div(new Re.default(t-1)),f=new Re.default(0),y=[{price:g,totalSellSupply:0}],{a:P,b:T}=p,I=f,S=f;for(let x=1;x<t;x++){let h=x!==t-1?b:i.sub(S),B=this.buyExactIn({poolInfo:{virtualA:P,virtualB:T,realA:I,realB:S,totalFundRaisingB:i,totalSellA:r},amountB:h,protocolFeeRate:f,platformFeeRate:f,curveType:e,shareFeeRate:f,creatorFeeRate:f,transferFeeConfigA:void 0,transferFeeConfigB:void 0,slot:0});I=I.add(B.amountA.amount),S=S.add(B.amountB);let R=this.getPrice({poolInfo:{virtualA:P,virtualB:T,realA:I,realB:S},decimalA:c,decimalB:u,curveType:e});y.push({price:R,totalSellSupply:new Wo.default(I.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(ze).lt(i))throw Error("total lock amount gte max lock amount");if(e.lt(s.minSupplyA.mul(new Re.default(10**r))))throw Error("supply lt min supply");let u=e.mul(s.minSellRateA).div(ze);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(ze);if(d.lt(p))throw Error("migrate lt min migrate amoount");let g=e.sub(n).sub(i),b=new Re.default(new Wo.default(g.mul(t).toString()).sqrt().toFixed(0));if(l==="amm"){let f=new Re.default(10).pow(new Re.default(r));if(b.lte(f))throw Error("check migrate lp error")}else if(l==="cpmm"){let f=new Re.default(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 K;let p=en(t,u,d),g=t.sub((K=p.fee)!=null?K:new Re.default(0)),b=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l}),f=this.calculateFee({amount:g,feeRate:b}),y=g.sub(f),P=this.getCurve(r),T=P.buyExactIn({poolInfo:e,amount:y}),I=e.totalSellA.sub(e.realA),S,x,h,B;if(T.gt(I)){S=I;let L=P.buyExactOut({poolInfo:e,amount:S}),F=this.calculatePreFee({postFeeAmount:L,feeRate:b});h=F.sub(L);let W=Lt(F,u,d);x=W.amount,B=W.fee}else S=T,x=t,h=f,B=p.fee;let R=this.splitFee({totalFee:h,protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l});return{amountA:en(S,c,d),amountB:x,splitFee:R,transferFeeB:B}}static buyExactOut({poolInfo:e,amountA:t,protocolFeeRate:n,platformFeeRate:i,curveType:r,shareFeeRate:s,creatorFeeRate:l,transferFeeConfigA:c,transferFeeConfigB:u,slot:d}){let p=e.totalSellA.sub(e.realA),g=Lt(t,c,d),b=g.fee?g.amount.add(g.fee):g.amount;t.gt(p)&&(b=p);let y=this.getCurve(r).buyExactOut({poolInfo:e,amount:b}),P=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l}),T=this.calculatePreFee({postFeeAmount:y,feeRate:P}),I=T.sub(y),S=Lt(T,u,d),x=this.splitFee({totalFee:I,protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l});return{amountA:g,amountB:S.amount,splitFee:x,transferFeeB:S.fee}}static sellExactIn({poolInfo:e,amountA:t,protocolFeeRate:n,platformFeeRate:i,curveType:r,shareFeeRate:s,creatorFeeRate:l,transferFeeConfigA:c,transferFeeConfigB:u,slot:d}){var S;let p=this.getCurve(r),g=en(t,c,d),b=g.fee?g.amount.sub(g.fee):g.amount,f=p.sellExactIn({poolInfo:e,amount:b}),y=this.calculateFee({amount:f,feeRate:this.totalFeeRate({protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l})}),P=this.splitFee({totalFee:y,protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l}),T=f.sub(y),I=en(T,u,d);return{amountA:g,amountB:T.sub((S=I.fee)!=null?S:new Re.default(0)),splitFee:P,transferFeeB:I.fee}}static sellExactOut({poolInfo:e,amountB:t,protocolFeeRate:n,platformFeeRate:i,curveType:r,shareFeeRate:s,creatorFeeRate:l,transferFeeConfigA:c,transferFeeConfigB:u,slot:d}){let p=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l}),g=Lt(t,u,d),b=g.amount,f=this.calculatePreFee({postFeeAmount:b,feeRate:p});if(e.realB.lt(f))throw Error("Insufficient liquidity");let y=f.sub(b),T=Me.getCurve(r).sellExactOut({poolInfo:e,amount:f});if(T.gt(e.realA))throw Error();let I=this.splitFee({totalFee:y,protocolFeeRate:n,platformFeeRate:i,shareFeeRate:s,creatorFeeRate:l});return{amountA:Lt(T,c,d),amountB:t,splitFee:I,transferFeeB:g.fee}}static splitFee({totalFee:e,protocolFeeRate:t,platformFeeRate:n,shareFeeRate:i,creatorFeeRate:r}){let s=this.totalFeeRate({protocolFeeRate:t,platformFeeRate:n,shareFeeRate:i,creatorFeeRate:r}),l=s.isZero()?new Re.default(0):e.mul(n).div(s),c=s.isZero()?new Re.default(0):e.mul(i).div(s),u=s.isZero()?new Re.default(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 Bo(e,t,ze)}static calculatePreFee({postFeeAmount:e,feeRate:t}){if(t.isZero())return e;let n=e.mul(ze),i=ze.sub(t);return n.add(i).sub(new Re.default(1)).div(i)}static totalFeeRate({protocolFeeRate:e,platformFeeRate:t,shareFeeRate:n,creatorFeeRate:i}){if(e.add(t).add(n).add(i).gt(new Re.default(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 Wn;case 1:return qn;case 2:return Gn}throw Error("find curve error")}};var uc={[Gi.toBase58()]:3};var cc=k([H(5),H(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"),H(7)]);var lc=require("@solana/web3.js");var VT=j("Serum");var qo=require("@solana/spl-token"),Uo=require("@solana/web3.js"),mc=N(require("bn.js"));var Mh=new Vr.default(0);var st=require("@solana/web3.js"),Er=require("@solana/spl-token"),Go=N(require("bn.js"));var Be=class extends xe{static getPdaPoolId(e,t){return le([Be.SEED_CONFIG.pool.id,t.toBuffer()],e)}static getPdaOwnerId(e,t,n,i){return le([Be.SEED_CONFIG.owner.id,t.toBuffer(),n.toBuffer(),Buffer.from(new Go.default(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=>Be.getPdaPoolId(t,d).publicKey),l=[];for(let d=0;d<Be.VERSION_PROJECT.length;d++)l.push(...s.map(p=>Be.getPdaOwnerId(t,p,i,d).publicKey));let c=await Xe(e,[...s,...l]),u=[];for(let d=0;d<c.length;d++){let p=Math.floor(d/n.length),g=d%n.length,b=s[g],f=l[d],y=c[g],P=c[n.length+d];if(!(y&&P)||y.data.length!==Be.POOL_LAYOUT.span||P.data.length!==Be.OWNER_LAYOUT.span)continue;let T=Be.POOL_LAYOUT.decode(y.data),I=Be.OWNER_LAYOUT.decode(P.data),S=T.openTime.toNumber(),x=T.endTime.toNumber(),h=I.tokenInfo.map(K=>K.debtAmount.gt(new Go.default(0))).filter(K=>!K).length!==3,B=r>S&&r<x&&T.status===1,R=h&&B;u.push({programId:t,poolId:b,ammId:T.ammId,ownerAccountId:f,snapshotLpAmount:I.lpAmount,project:Be.VERSION_PROJECT[p],openTime:S,endTime:x,canClaim:R,canClaimErrorType:h?B?void 0:"outOfOperationalTime":"alreadyClaimIt",tokenInfo:T.tokenInfo.map((K,L)=>({mintAddress:K.mintAddress,mintVault:K.mintVault,mintDecimals:K.mintDecimals,perLpLoss:K.perLpLoss,debtAmount:I.tokenInfo[L].debtAmount.add(I.tokenInfo[L].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(he.WSOL.mint),createInfo:{payer:r,amount:0},skipCloseAccount:!u.mintAddress.equals(he.WSOL.mint),associatedOnly:u.mintAddress.equals(he.WSOL.mint)?!1:t.associatedOnly});p&&i.addInstruction(p),s.push(d)}i.addInstruction({instructions:[Be.makeClaimInstruction({programId:e.programId,poolInfo:e,ownerInfo:{wallet:r,ownerPda:e.ownerAccountId,claimAddress:s}})]});let{transaction:l,signers:c}=i.build();return[{transaction:l,signer:c}]}async makeClaimAllTransaction({poolInfos:e,ownerInfo:t,feePayer:n}){let i=this.createTxBuilder(n),r=t.wallet||this.scope.ownerPubKey,s={};for(let d of e){let p=[];for(let g of d.tokenInfo){let{account:b,instructionParams:f}=await this.scope.account.getOrCreateTokenAccount({mint:g.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:g.mintAddress.equals(he.WSOL.mint),createInfo:{payer:r,amount:0},skipCloseAccount:!g.mintAddress.equals(he.WSOL.mint),associatedOnly:g.mintAddress.equals(he.WSOL.mint)?!1:t.associatedOnly});f&&i.addInstruction(f),b&&(s[g.mintAddress.toString()]=b,p.push(b))}i.addInstruction({instructions:[Be.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 lo(u,[r,...c.map(d=>d.publicKey)])?[{transaction:l,signer:c}]:[{transaction:new st.Transaction().add(...u.slice(0,i.AllTxData.instructions.length-1)),signer:c},{transaction:new st.Transaction().add(...u.slice(i.AllTxData.instructions.length-1)),signer:[]},{transaction:new st.Transaction().add(...i.AllTxData.endInstructions),signer:[]}]}static makeClaimInstruction({programId:e,poolInfo:t,ownerInfo:n}){let i=k([]),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:Er.TOKEN_PROGRAM_ID,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 st.TransactionInstruction({keys:r,programId:e,data:l})}},qe=Be;qe.CLAIMED_NUM=3,qe.POOL_LAYOUT=k([H(8),w("bump"),w("status"),o("openTime"),o("endTime"),m("ammId"),C(k([w("mintDecimals"),m("mintAddress"),m("mintVault"),o("perLpLoss"),o("totalClaimedAmount")]),Be.CLAIMED_NUM,"tokenInfo"),C(o(),10,"padding")]),qe.OWNER_LAYOUT=k([H(8),w("bump"),w("version"),m("poolId"),m("owner"),o("lpAmount"),C(k([m("mintAddress"),o("debtAmount"),o("claimedAmount")]),Be.CLAIMED_NUM,"tokenInfo"),C(o(),4,"padding")]),qe.DEFAULT_POOL_ID=["58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2","6UmmUiYoBjSrhakAobJw8BvkmJtDVxaeBtbt7rxWo1mg","AVs9TA4nWDzfPJE9gGVNJMVhcQy3V9PGazuz33BfG2RA","DVa7Qmb5ct9RCpaU7UTpSaf3GVMYz17vNVU67XpdCRut","7XawhbbxtsRcQA8KTkHT9f9nc6d69UwqCDh6U5EEbEmX","6a1CsrpeZubDjEJE9s1CMVheB6HWM5d7m1cj2jkhyXhj","EoNrn8iUhwgJySD1pHu8Qxm5gSQqLK3za4m8xzD2RuEb","AceAyRTWt4PyB2pHqf2qhDgNZDtKVNaxgL8Ru3V4aN1P","6tmFJbMk5yVHFcFy7X2K8RwHjKLr6KVFLYXpgpBNeAxB"].map(e=>new st.PublicKey(e)),qe.SEED_CONFIG={pool:{id:Buffer.from("pool_seed","utf8")},owner:{id:Buffer.from("user_claim_seed","utf8")}},qe.VERSION_PROJECT=[void 0,"Francium","Tulip","Larix"];var pc=require("@solana/web3.js"),sn=require("@solana/spl-token");var fB=new Je.default(2),yB=new Je.default(3),bB=new Je.default(5),ra=new Je.default(10),gB=new Je.default(100),PB=new Je.default(1e3),AB=new Je.default(1e4);function Bo(a,e,t){return a.mul(e).add(t).sub(new Je.default(1)).div(t)}function zo(a,e=1,t=[]){let n=[...a];if(e<=0)return t;for(;n.length;)t.push(n.splice(0,e));return t}var zn=require("@solana/spl-token"),Xo=j("Raydium_accountInfo_util");async function Xe(a,e,t){let{batchRequest:n,commitment:i="confirmed",chunkCount:r=100}=v({batchRequest:!1},t),s=zo(e,r),l=new Array(s.length).fill([]);if(n){let c=s.map(p=>{let g=a._buildArgs([p.map(b=>b.toBase58())],i,"base64");return{methodName:"getMultipleAccounts",args:g}}),u=zo(c,10);l=(await(await Promise.all(u.map(async p=>await a._rpcBatchRequest(p)))).flat()).map(p=>(p.error&&Xo.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${p.error.message}`),p.result.value.map(g=>{if(g){let{data:b,executable:f,lamports:y,owner:P,rentEpoch:T}=g;return b.length!==2&&b[1]!=="base64"&&Xo.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(b[0],"base64"),executable:f,lamports:y,owner:new Dr.PublicKey(P),rentEpoch:T}}return null})))}else try{l=await Promise.all(s.map(c=>a.getMultipleAccountsInfo(c,i)))}catch(c){c instanceof Error&&Xo.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${c.message}`)}return l.flat()}async function Oe(a,e,t){let n=await Xe(a,e.map(i=>i.pubkey),t);return e.map((i,r)=>z(v({},i),{accountInfo:n[r]}))}async function Yo({connection:a,address:e,cluster:t="mainnet"}){let n=await Xe(a,[...new Set(e.map(r=>r.toString()))].map(r=>new Ue.PublicKey(r))),i={};for(let r=0;r<e.length;r++){let s=n[r],l=e[r];if(!s)continue;let c=new Ue.AddressLookupTableAccount({key:l,state:Ue.AddressLookupTableAccount.deserialize(s.data)});i[l.toString()]=c,t==="devnet"?Vt[l.toString()]=c:_t[l.toString()]=c}return i}var _t={},Ho=async a=>{let e="AcL1Vo8oy1ULiavEcjSUcwfBSForXMudcZvDZy5nzJkU";if(_t[e])return _t;let t=new Ue.PublicKey(e),n=await a.getAccountInfo(t);return n&&(_t[e]=new Ue.AddressLookupTableAccount({key:t,state:Ue.AddressLookupTableAccount.deserialize(n.data)})),_t},Vt={},Qo=async a=>{let e="EFhMuDw1PKEuckuFRW9PavNfTH4LKP5uKHgyXDmWpFCq";if(Vt[e])return Vt;let t=new Ue.PublicKey(e),n=await a.getAccountInfo(t);return n&&(Vt[e]=new Ue.AddressLookupTableAccount({key:t,state:Ue.AddressLookupTableAccount.deserialize(n.data)})),Vt};var Xn=2e3,Yn=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 Wr.default.get(`https://solanacompass.com/api/fees?cacheFreshTime=${3e5}`)).data,{avg:t}=(n=e==null?void 0:e[15])!=null?n:{};if(!!t)return{units:6e5,microLamports:Math.min(Math.ceil(t*1e6/6e5),25e3)}}addCustomComputeBudget(e){if(e){let{instructions:t,instructionTypes:n}=hn(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...n),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(ne.SystemProgram.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new ne.PublicKey(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!==ne.PublicKey.default.toString())),this}async versionBuild({txVersion:e,extInfo:t,lookupTableAddress:n}){return e===0?await this.buildV0(z(v({},t||{}),{lookupTableAddress:n})):this.build(t)}build(e){var n;let t=new ne.Transaction;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 Bt(this.connection,this.blockhashCommitment);if(t.recentBlockhash=u,this.signers.length&&t.sign(...this.signers),ft([t]),(d=this.owner)!=null&&d.isKeyPair)return{txId:l?await(0,ne.sendAndConfirmTransaction)(this.connection,t,this.signers.find(g=>g.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:s}):await this.connection.sendRawTransaction(t.serialize(),{skipPreflight:s}),signedTx:t};if(this.signAllTransactions){let p=await this.signAllTransactions([t]);if(this.signers.length)for(let g of p)try{g.sign(...this.signers)}catch{}return{txId:c?"":await this.connection.sendRawTransaction(p[0].serialize(),{skipPreflight:s}),signedTx:p[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:e||{}}}buildMultiTx(e){var u;let{extraPreBuildData:t=[],extInfo:n}=e,{transaction:i}=this.build(n),r=t.filter(d=>d.transaction.instructions.length>0),s=[i,...r.map(d=>d.transaction)],l=[this.signers,...r.map(d=>d.signers)],c=[...this.instructionTypes,...r.map(d=>d.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&l.forEach(d=>{d.some(p=>p.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:s,signers:l,instructionTypes:c,execute:async d=>{var T;let{sequentially:p,onTxUpdate:g,skipTxCount:b=0,recentBlockHash:f,skipPreflight:y=!0}=d||{},P=f!=null?f:await Bt(this.connection,this.blockhashCommitment);if((T=this.owner)!=null&&T.isKeyPair){if(p){let I=[],S=0;for(let x of s){if(++S,S<=b)continue;let h=await(0,ne.sendAndConfirmTransaction)(this.connection,x,this.signers.find(B=>B.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:y});I.push(h)}return{txIds:I,signedTxs:s}}return{txIds:await await Promise.all(s.map(async I=>(I.recentBlockhash=P,await this.connection.sendRawTransaction(I.serialize(),{skipPreflight:y})))),signedTxs:s}}if(this.signAllTransactions){let I=s.map((x,h)=>(x.recentBlockhash=P,l[h].length&&x.sign(...l[h]),x));ft(I);let S=await this.signAllTransactions(I);if(p){let x=0,h=[],B=async()=>{if(!S[x])return;let R=await this.connection.sendRawTransaction(S[x].serialize(),{skipPreflight:y});h.push({txId:R,status:"sent",signedTx:S[x]}),g==null||g([...h]),x++;let K=!1,L=null,F=null,W=G=>{L!==null&&clearInterval(L),F!==null&&this.connection.removeSignatureListener(F);let D=h.findIndex(M=>M.txId===R);if(D>-1){if(h[D].status==="error"||h[D].status==="success")return;h[D].status=G.err?"error":"success"}g==null||g([...h]),G.err||B()};this.loopMultiTxStatus&&(L=setInterval(async()=>{var G;if(K){clearInterval(L);return}try{let D=await this.connection.getTransaction(R,{commitment:"confirmed",maxSupportedTransactionVersion:1});D&&(K=!0,clearInterval(L),W({err:((G=D.meta)==null?void 0:G.err)||null}),console.log("tx status from getTransaction:",R))}catch(D){K=!0,clearInterval(L),console.error("getTransaction timeout:",D,R)}},Xn)),F=this.connection.onSignature(R,G=>{if(K){this.connection.removeSignatureListener(F);return}K=!0,W(G)},"confirmed"),this.connection.getSignatureStatus(R)};return await B(),{txIds:h.map(R=>R.txId),signedTxs:S}}else{let x=[];for(let h=0;h<S.length;h+=1){let B=await this.connection.sendRawTransaction(S[h].serialize(),{skipPreflight:y});x.push(B)}return{txIds:x,signedTxs:S}}}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=_e(f,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),l=v(v({},this.cluster==="devnet"?await Qo(this.connection):await Ho(this.connection)),t),c=Array.from(new Set([...n,...this.lookupTableAddress])),u=[];for(let P of c)l[P]===void 0&&u.push(new ne.PublicKey(P));let d=await Yo({connection:this.connection,address:u});for(let[P,T]of Object.entries(d))l[P]=T;let p=i?ne.PublicKey.default.toBase58():r!=null?r:await Bt(this.connection,this.blockhashCommitment),g=new ne.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(l));((y=this.owner)==null?void 0:y.signer)&&!this.signers.some(P=>P.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let b=new ne.VersionedTransaction(g);return b.sign(this.signers),{builder:this,transaction:b,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async P=>{var x;let{skipPreflight:T=!0,sendAndConfirm:I,notSendToRpc:S}=P||{};if(ft([b]),(x=this.owner)!=null&&x.isKeyPair){let h=await this.connection.sendTransaction(b,{skipPreflight:T});return I&&await In(this.connection,h),{txId:h,signedTx:b}}if(this.signAllTransactions){let h=await this.signAllTransactions([b]);if(this.signers.length)for(let B of h)try{B.sign(this.signers)}catch{}return{txId:S?"":await this.connection.sendTransaction(h[0],{skipPreflight:T}),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:g,recentBlockHash:b,skipPreflight:f=!0}=d||{};if(b&&s.forEach(P=>P.message.recentBlockhash=b),ft(s),(y=this.owner)!=null&&y.isKeyPair){if(p){let P=[];for(let T of s){let I=await this.connection.sendTransaction(T,{skipPreflight:f});await In(this.connection,I),P.push(I)}return{txIds:P,signedTxs:s}}return{txIds:await Promise.all(s.map(async P=>await this.connection.sendTransaction(P,{skipPreflight:f}))),signedTxs:s}}if(this.signAllTransactions){let P=await this.signAllTransactions(s);if(p){let T=0,I=[],S=async()=>{if(!P[T])return;let x=await this.connection.sendTransaction(P[T],{skipPreflight:f});I.push({txId:x,status:"sent",signedTx:P[T]}),g==null||g([...I]),T++;let h=!1,B=null,R=null,K=L=>{B!==null&&clearInterval(B),R!==null&&this.connection.removeSignatureListener(R);let F=I.findIndex(W=>W.txId===x);if(F>-1){if(I[F].status==="error"||I[F].status==="success")return;I[F].status=L.err?"error":"success"}g==null||g([...I]),L.err||S()};this.loopMultiTxStatus&&(B=setInterval(async()=>{var L;if(h){clearInterval(B);return}try{let F=await this.connection.getTransaction(x,{commitment:"confirmed",maxSupportedTransactionVersion:1});F&&(h=!0,clearInterval(B),K({err:((L=F.meta)==null?void 0:L.err)||null}),console.log("tx status from getTransaction:",x))}catch(F){h=!0,clearInterval(B),console.error("getTransaction timeout:",F,x)}},Xn)),R=this.connection.onSignature(x,L=>{if(h){this.connection.removeSignatureListener(R);return}h=!0,K(L)},"confirmed"),this.connection.getSignatureStatus(x)};return S(),{txIds:[],signedTxs:P}}else{let T=[];for(let I=0;I<P.length;I+=1){let S=await this.connection.sendTransaction(P[I],{skipPreflight:f});T.push(S)}return{txIds:T,signedTxs:P}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:n||{}}}async sizeCheckBuild(e){var g;let p=e||{},{splitIns:t=[],computeBudgetConfig:n}=p,i=_e(p,["splitIns","computeBudgetConfig"]),r=n?hn(n):{instructions:[],instructionTypes:[]},s=this.signers.reduce((b,f)=>z(v({},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,T=[...new Set(f.map(I=>I.keys.filter(S=>S.isSigner).map(S=>S.pubkey.toString())).flat()).values()].map(I=>new ne.PublicKey(I));if(b!==t[d]&&u.length<12&&(Xt({instructions:y,payer:this.feePayer,signers:T})||Xt({instructions:f,payer:this.feePayer,signers:T})))u.push(b);else{if(u.length===0)throw Error("item ins too big");d+=b===t[d]?1:0,Xt({instructions:n?[...r.instructions,...u]:[...u],payer:this.feePayer,signers:T})?l.push(new ne.Transaction().add(...r.instructions,...u)):l.push(new ne.Transaction().add(...u)),c.push(Array.from(new Set(u.map(I=>I.keys.filter(S=>S.isSigner).map(S=>S.pubkey.toString())).flat())).map(I=>s[I]).filter(I=>I!==void 0)),u=[b]}}),u.length>0){let f=[...new Set(u.map(y=>y.keys.filter(P=>P.isSigner).map(P=>P.pubkey.toString())).flat()).values()].map(y=>s[y]).filter(y=>y!==void 0);Xt({instructions:n?[...r.instructions,...u]:[...u],payer:this.feePayer,signers:f.map(y=>y.publicKey)})?l.push(new ne.Transaction().add(...r.instructions,...u)):l.push(new ne.Transaction().add(...u)),c.push(f)}return l.forEach(b=>b.feePayer=this.feePayer),(g=this.owner)!=null&&g.signer&&c.forEach(b=>{b.some(f=>f.publicKey.equals(this.owner.publicKey))||b.push(this.owner.signer)}),{builder:this,transactions:l,signers:c,instructionTypes:this.instructionTypes,execute:async b=>{var x;let{sequentially:f,onTxUpdate:y,skipTxCount:P=0,recentBlockHash:T,skipPreflight:I=!0}=b||{},S=T!=null?T:await Bt(this.connection,this.blockhashCommitment);if(l.forEach(async(h,B)=>{h.recentBlockhash=S,c[B].length&&h.sign(...c[B])}),ft(l),(x=this.owner)!=null&&x.isKeyPair){if(f){let h=0,B=[];for(let R of l){if(++h,h<=P){B.push("tx skipped");continue}let K=await(0,ne.sendAndConfirmTransaction)(this.connection,R,this.signers.find(L=>L.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:I});B.push(K)}return{txIds:B,signedTxs:l}}return{txIds:await Promise.all(l.map(async h=>await this.connection.sendRawTransaction(h.serialize(),{skipPreflight:I}))),signedTxs:l}}if(this.signAllTransactions){let h=await this.signAllTransactions(l.slice(P,l.length)),B=[...l.slice(0,P),...h];if(f){let R=0,K=[],L=async()=>{if(!B[R])return;R<P&&(K.push({txId:"",status:"success",signedTx:B[R]}),y==null||y([...K]),R++,L());let F=await this.connection.sendRawTransaction(B[R].serialize(),{skipPreflight:I});K.push({txId:F,status:"sent",signedTx:B[R]}),y==null||y([...K]),R++;let W=!1,G=null,D=null,M=U=>{G!==null&&clearInterval(G),D!==null&&this.connection.removeSignatureListener(D);let ee=K.findIndex(oe=>oe.txId===F);if(ee>-1){if(K[ee].status==="error"||K[ee].status==="success")return;K[ee].status=U.err?"error":"success"}y==null||y([...K]),U.err||L()};this.loopMultiTxStatus&&(G=setInterval(async()=>{var U;if(W){clearInterval(G);return}try{let ee=await this.connection.getTransaction(F,{commitment:"confirmed",maxSupportedTransactionVersion:1});ee&&(W=!0,clearInterval(G),M({err:((U=ee.meta)==null?void 0:U.err)||null}),console.log("tx status from getTransaction:",F))}catch(ee){W=!0,clearInterval(G),console.error("getTransaction timeout:",ee,F)}},Xn)),D=this.connection.onSignature(F,U=>{if(W){this.connection.removeSignatureListener(D);return}W=!0,M(U)},"confirmed"),this.connection.getSignatureStatus(F)};return await L(),{txIds:K.map(F=>F.txId),signedTxs:B}}else{let R=[];for(let K=0;K<B.length;K+=1){let L=await this.connection.sendRawTransaction(B[K].serialize(),{skipPreflight:I});R.push(L)}return{txIds:R,signedTxs:B}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:i||{}}}async sizeCheckBuildV0(e){var x;let S=e||{},{computeBudgetConfig:t,splitIns:n=[],lookupTableCache:i={},lookupTableAddress:r=[],insCountLimit:s=12}=S,l=_e(S,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress","insCountLimit"]),c=v(v({},this.cluster==="devnet"?await Qo(this.connection):await Ho(this.connection)),i),u=Array.from(new Set([...this.lookupTableAddress,...r])),d=[];for(let h of u)c[h]===void 0&&d.push(new ne.PublicKey(h));let p=await Yo({connection:this.connection,address:d});for(let[h,B]of Object.entries(p))c[h]=B;let g=t?hn(t):{instructions:[],instructionTypes:[]},b=await Bt(this.connection,this.blockhashCommitment),f=this.signers.reduce((h,B)=>z(v({},h),{[B.publicKey.toBase58()]:B}),{}),y=[],P=[],T=[],I=0;if(this.allInstructions.forEach(h=>{let B=[...T,h],R=t?[...g.instructions,...B]:B;if(h!==n[I]&&T.length<s&&(Yt({instructions:R,payer:this.feePayer,lookupTableAddressAccount:c})||Yt({instructions:B,payer:this.feePayer,lookupTableAddressAccount:c})))T.push(h);else{if(T.length===0)throw Error("item ins too big");I+=h===n[I]?1:0;let K={};for(let L of[...new Set(u)])c[L]!==void 0&&(K[L]=c[L]);if(t&&Yt({instructions:[...g.instructions,...T],payer:this.feePayer,lookupTableAddressAccount:c,recentBlockhash:b})){let L=new ne.TransactionMessage({payerKey:this.feePayer,recentBlockhash:b,instructions:[...g.instructions,...T]}).compileToV0Message(Object.values(c));y.push(new ne.VersionedTransaction(L))}else{let L=new ne.TransactionMessage({payerKey:this.feePayer,recentBlockhash:b,instructions:[...T]}).compileToV0Message(Object.values(c));y.push(new ne.VersionedTransaction(L))}P.push(Array.from(new Set(T.map(L=>L.keys.filter(F=>F.isSigner).map(F=>F.pubkey.toString())).flat())).map(L=>f[L]).filter(L=>L!==void 0)),T=[h]}}),T.length>0){let B=[...new Set(T.map(R=>R.keys.filter(K=>K.isSigner).map(K=>K.pubkey.toString())).flat()).values()].map(R=>f[R]).filter(R=>R!==void 0);if(t&&Yt({instructions:[...g.instructions,...T],payer:this.feePayer,lookupTableAddressAccount:c,recentBlockhash:b})){let R=new ne.TransactionMessage({payerKey:this.feePayer,recentBlockhash:b,instructions:[...g.instructions,...T]}).compileToV0Message(Object.values(c));y.push(new ne.VersionedTransaction(R))}else{let R=new ne.TransactionMessage({payerKey:this.feePayer,recentBlockhash:b,instructions:[...T]}).compileToV0Message(Object.values(c));y.push(new ne.VersionedTransaction(R))}P.push(B)}return(x=this.owner)!=null&&x.signer&&P.forEach(h=>{h.some(B=>B.publicKey.equals(this.owner.publicKey))||h.push(this.owner.signer)}),y.forEach((h,B)=>{h.sign(P[B])}),{builder:this,transactions:y,buildProps:e,signers:P,instructionTypes:this.instructionTypes,execute:async h=>{var W;let{sequentially:B,onTxUpdate:R,skipTxCount:K=0,recentBlockHash:L,skipPreflight:F=!0}=h||{};if(y.map(async(G,D)=>{P[D].length&&G.sign(P[D]),L&&(G.message.recentBlockhash=L)}),ft(y),(W=this.owner)!=null&&W.isKeyPair){if(B){let G=0,D=[];for(let M of y){if(++G,G<=K){console.log("skip tx: ",G),D.push("tx skipped");continue}let U=await this.connection.sendTransaction(M,{skipPreflight:F});await In(this.connection,U),D.push(U)}return{txIds:D,signedTxs:y}}return{txIds:await Promise.all(y.map(async G=>await this.connection.sendTransaction(G,{skipPreflight:F}))),signedTxs:y}}if(this.signAllTransactions){let G=await this.signAllTransactions(y.slice(K,y.length)),D=[...y.slice(0,K),...G];if(B){let M=0,U=[],ee=async()=>{if(!D[M])return;if(M<K){U.push({txId:"",status:"success",signedTx:D[M]}),R==null||R([...U]),M++,ee();return}let oe=await this.connection.sendTransaction(D[M],{skipPreflight:F});U.push({txId:oe,status:"sent",signedTx:D[M]}),R==null||R([...U]),M++;let Z=!1,ie=null,_=null,ae=pe=>{ie!==null&&clearInterval(ie),_!==null&&this.connection.removeSignatureListener(_);let te=U.findIndex(ge=>ge.txId===oe);if(te>-1){if(U[te].status==="error"||U[te].status==="success")return;U[te].status=pe.err?"error":"success"}R==null||R([...U]),pe.err||ee()};this.loopMultiTxStatus&&(ie=setInterval(async()=>{var pe;if(Z){clearInterval(ie);return}try{let te=await this.connection.getTransaction(oe,{commitment:"confirmed",maxSupportedTransactionVersion:1});te&&(Z=!0,clearInterval(ie),ae({err:((pe=te.meta)==null?void 0:pe.err)||null}),console.log("tx status from getTransaction:",oe))}catch(te){Z=!0,clearInterval(ie),console.error("getTransaction timeout:",te,oe)}},Xn)),_=this.connection.onSignature(oe,pe=>{if(Z){this.connection.removeSignatureListener(_);return}Z=!0,ae(pe)},"confirmed"),this.connection.getSignatureStatus(oe)};return ee(),{txIds:[],signedTxs:D}}else{let M=[];for(let U=0;U<D.length;U+=1){let ee=await this.connection.sendTransaction(D[U],{skipPreflight:F});M.push(ee)}return{txIds:M,signedTxs:D}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:l||{}}}};var Zo=(...a)=>a.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch{return e}}).join(", "),xe=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=j(t)}createTxBuilder(e){return this.scope.checkOwner(),new Yn({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(Zo(e))}logInfo(...e){this.logger.info(Zo(e))}logAndCreateError(...e){let t=Zo(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};var O=require("@solana/spl-token"),E=N(require("bn.js")),ct=require("@solana/web3.js");var Ne=N(require("decimal.js")),cn={initPriceX64:new E.default("515752397214619"),supply:new E.default(1e15),totalSellA:new E.default(7931e11),totalFundRaisingB:new E.default(85e9),totalFundRaisingBUSD:new E.default(125e8),totalLockedAmount:new E.default("0"),cliffPeriod:new E.default("0"),unlockPeriod:new E.default("0"),decimals:6,virtualA:new E.default("1073471847374405"),virtualB:new E.default("30050573465"),realA:new E.default(0),realB:new E.default(0),protocolFee:new E.default(0),platformId:new ct.PublicKey("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),vestingSchedule:{totalLockedAmount:new E.default(0),cliffPeriod:new E.default(0),unlockPeriod:new E.default(0),startTime:new E.default(0),totalAllocatedShare:new E.default(0)}},ut=new E.default(1e4),bc=new Set(["USDCoctVLVnvTXBEuP9s8hntucdJokbo17RwHuNXemT","USD1ttGY1N17NEEHLmELoaybftRBUSErhqYiQzvEmuB"]),un=class extends xe{constructor(e){super(e)}async getMintBTokenInfo({mintB:e,mintBProgram:t,transferFeeConfigB:n,skipCheckMintB:i}){if(e.equals(O.NATIVE_MINT))return{mintBProgram:O.TOKEN_PROGRAM_ID,transferFeeConfigB:void 0};if(n)return{mintBProgram:t!=null?t:O.TOKEN_2022_PROGRAM_ID,transferFeeConfigB:n};if(i||(t==null?void 0:t.equals(O.TOKEN_PROGRAM_ID)))return{mintBProgram:t!=null?t:O.TOKEN_PROGRAM_ID,transferFeeConfigB:void 0};let r=await this.scope.connection.getAccountInfo(e);return!r||!r.owner.equals(O.TOKEN_2022_PROGRAM_ID)?{mintBProgram:t!=null?t:O.TOKEN_PROGRAM_ID,transferFeeConfigB:void 0}:{mintBProgram:r.owner,transferFeeConfigB:(0,O.getTransferFeeConfig)((0,O.unpackMint)(e,r,r.owner))||void 0}}async createLaunchpad(U){var ee=U,{programId:e=me,authProgramId:t,platformId:n=cn.platformId,mintA:i,decimals:r=6,mintBDecimals:s=9,name:l,symbol:c,uri:u,migrateType:d,configId:p,configInfo:g,txVersion:b,computeBudgetConfig:f,txTipConfig:y,feePayer:P,buyAmount:T,minMintAAmount:I,slippage:S,associatedOnly:x=!0,checkCreateATAOwner:h=!1,extraSigners:B,token2022:R,transferFeeExtensionParams:K,creatorFeeOn:L=0,platformAllowConfig:F,mintBProgram:W,transferFeeConfigB:G,skipCheckMintB:D}=ee,M=_e(ee,["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 ei,ti,ni,oi,ii,ri,ai,si,ui,ci,li;let oe=this.createTxBuilder(P);t=t!=null?t:De(e).publicKey,R=!!K,R&&(d="cpmm");let Z=g;if(!Z&&p){let Ze=await this.scope.connection.getAccountInfo(p);Ze&&(Z=it.decode(Ze.data))}Z||this.logAndCreateError("config not found");let ie=Z.mintB,_=Z.curveType,{mintBProgram:ae,transferFeeConfigB:pe}=await this.getMintBTokenInfo({mintB:ie,mintBProgram:W,transferFeeConfigB:G,skipCheckMintB:D}),{publicKey:te}=Ot(e,i,ie),{publicKey:ge}=xo(e,te,i),{publicKey:se}=xo(e,te,ie),{publicKey:ve}=Kn(i);this.logDebug(`create token: ${i.toBase58()}, mintB: ${ie.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 ke=(await this.scope.api.fetchLaunchConfigs()).find(Ze=>Ze.key.pubKey===p.toBase58()),J=(ei=M==null?void 0:M.supply)!=null?ei:new E.default(ke.defaultParams.supplyInit),Y=(ti=M==null?void 0:M.totalSellA)!=null?ti:new E.default(ke.defaultParams.totalSellA),Se=(ni=M==null?void 0:M.totalFundRaisingB)!=null?ni:new E.default(ke.defaultParams.totalFundRaisingB),Ye=(oi=M==null?void 0:M.totalLockedAmount)!=null?oi:new E.default(0),fe=await this.scope.connection.getAccountInfo(n);fe||this.logAndCreateError("platform id not found:",n.toString());let He=At.decode(fe.data),Hn=He.platformVestingScale,$o=He.feeRate,jo=Me.getCurve(Z.curveType).getInitParam({supply:J,totalFundRaising:Se,totalSell:Y,totalLockedAmount:Ye,migrateFee:Z.migrateFee}),ln;try{ln=await this.scope.token.getTokenInfo(ie)}catch{this.logDebug("can not get mintB info from getTokenInfo")}let Qe={epoch:new E.default(896),bump:254,status:0,mintDecimalsA:r,mintDecimalsB:(ii=ln==null?void 0:ln.decimals)!=null?ii:s,supply:J,totalSellA:Y,mintA:new ct.PublicKey(i),mintB:ie,virtualA:jo.a,virtualB:jo.b,realA:cn.realA,realB:cn.realB,migrateFee:Z.migrateFee,migrateType:d==="amm"?0:1,protocolFee:cn.protocolFee,platformFee:$o,platformId:n,configId:p,vaultA:ge,vaultB:se,creator:this.scope.ownerPubKey,totalFundRaisingB:Se,vestingSchedule:{totalLockedAmount:Ye,cliffPeriod:new E.default(0),unlockPeriod:new E.default(0),startTime:new E.default(0),totalAllocatedShare:new E.default(0)},mintProgramFlag:Fr({mintAProgram:R?O.TOKEN_2022_PROGRAM_ID:O.TOKEN_PROGRAM_ID,mintBProgram:ae}),cpmmCreatorFeeOn:L,platformVestingShare:Hn!=null?Hn:new E.default(0)},qr=Me.getCurve(Z.curveType),{c:Ur}=qr.getInitParam({supply:Qe.supply,totalFundRaising:Qe.totalFundRaisingB,totalLockedAmount:Ye,totalSell:Z.curveType===0?Qe.totalSellA:new E.default(0),migrateFee:Z.migrateFee});try{Me.checkParam({supply:Qe.supply,totalFundRaising:Qe.totalFundRaisingB,totalSell:Ur,totalLockedAmount:Ye,decimals:Qe.mintDecimalsA,config:Z,migrateType:d}),this.logDebug("check init params success")}catch(Ze){this.logAndCreateError(`check create mint params failed, ${Ze.message}`)}let Jo=He.restrictCurveParam?Oo(e,n,p).publicKey:void 0;oe.addInstruction({instructions:[R?hr(e,P!=null?P:this.scope.ownerPubKey,this.scope.ownerPubKey,p,n,t,te,i,ie,ge,se,ae,r,l,c,u||"https://",{type:_===0?"ConstantCurve":_===1?"FixedCurve":_===2?"LinearCurve":"ConstantCurve",totalSellA:Y,migrateType:d,supply:J,totalFundRaisingB:Se},Ye,(ri=M==null?void 0:M.cliffPeriod)!=null?ri:new E.default(0),(ai=M==null?void 0:M.unlockPeriod)!=null?ai:new E.default(0),L,K,F?nn(e,n,p).publicKey:void 0,Jo):Tr(e,P!=null?P:this.scope.ownerPubKey,this.scope.ownerPubKey,p,n,t,te,i,ie,ge,se,ve,ae,r,l,c,u||"https://",{type:_===0?"ConstantCurve":_===1?"FixedCurve":_===2?"LinearCurve":"ConstantCurve",totalSellA:Y,migrateType:d,supply:J,totalFundRaisingB:Se},Ye,(si=M==null?void 0:M.cliffPeriod)!=null?si:new E.default(0),(ui=M==null?void 0:M.unlockPeriod)!=null?ui:new E.default(0),L,F?nn(e,n,p).publicKey:void 0,Jo)]});let Qn=R?await this.scope.connection.getEpochInfo():void 0,mn=K?{epoch:BigInt((Qn==null?void 0:Qn.epoch)||0),maximumFee:BigInt((ci=K==null?void 0:K.maxinumFee.toString())!=null?ci:0),transferFeeBasisPoints:(li=K==null?void 0:K.transferFeeBasePoints)!=null?li:0}:void 0,Zn={amountA:{amount:new E.default(0),fee:void 0,expirationTime:void 0},amountB:new E.default(0),splitFee:{platformFee:new E.default(0),shareFee:new E.default(0),protocolFee:new E.default(0),creatorFee:new E.default(0)},transferFeeB:void 0},$n;if(B!=null&&B.length&&oe.addInstruction({signers:B}),!M.createOnly){let{builder:Ze,extInfo:Gr}=await this.buyToken({programId:e,authProgramId:t,mintAProgram:R?O.TOKEN_2022_PROGRAM_ID:void 0,mintA:i,mintB:ie,mintBProgram:ae,transferFeeConfigB:pe,skipCheckMintB:!0,poolInfo:Qe,buyAmount:T,minMintAAmount:I,shareFeeRate:M.shareFeeRate,shareFeeReceiver:M.shareFeeReceiver,configInfo:Z,platformFeeRate:$o,slippage:S,associatedOnly:x,checkCreateATAOwner:h,skipCheckMintA:!mn,transferFeeConfigA:mn?{transferFeeConfigAuthority:t,withdrawWithheldAuthority:t,withheldAmount:BigInt(0),olderTransferFee:mn,newerTransferFee:mn}:void 0,fromCreate:!0});oe.addInstruction(v({},Ze.AllTxData)),Zn=v({},Gr),$n=(this.scope.cluster==="devnet"||b===1)&&M.shareFeeReceiver?[Ze.allInstructions[0]]:void 0}return oe.addTipInstruction(y),b===0?oe.sizeCheckBuildV0({computeBudgetConfig:f,swapInfo:Zn,splitIns:$n,address:z(v({},Qe),{poolId:te})}):oe.sizeCheckBuild({computeBudgetConfig:f,swapInfo:Zn,splitIns:$n,address:z(v({},Qe),{poolId:te})})}async buyToken({programId:e=me,authProgramId:t,mintA:n,mintAProgram:i=O.TOKEN_PROGRAM_ID,mintB:r=O.NATIVE_MINT,poolInfo:s,configInfo:l,platformFeeRate:c,txVersion:u,computeBudgetConfig:d,txTipConfig:p,feePayer:g,buyAmount:b,minMintAAmount:f,slippage:y,shareFeeRate:P=new E.default(0),shareFeeReceiver:T,associatedOnly:I=!0,checkCreateATAOwner:S=!1,fromCreate:x=!1,transferFeeConfigA:h,skipCheckMintA:B=!1,mintBProgram:R,transferFeeConfigB:K,skipCheckMintB:L=!1}){var Y,Se,Ye;b.lte(new E.default(0))&&this.logAndCreateError("buy amount should gt 0:",b.toString());let F=this.createTxBuilder(g),{publicKey:W}=Ot(e,n,r);t=t!=null?t:De(e).publicKey;let G=h;if(!B)if(G)i=O.TOKEN_2022_PROGRAM_ID;else{let fe=await this.scope.connection.getAccountInfo(n);if(fe&&fe.owner.equals(O.TOKEN_2022_PROGRAM_ID)){i=fe.owner;let He=(0,O.unpackMint)(n,fe,i);G=(0,O.getTransferFeeConfig)(He)||void 0}}let{mintBProgram:D,transferFeeConfigB:M}=await this.getMintBTokenInfo({mintB:r,mintBProgram:R,transferFeeConfigB:K,skipCheckMintB:L}),U=this.scope.account.getAssociatedTokenAccount(n,i),ee=r.equals(O.NATIVE_MINT),oe=x&&ee,Z=oe?this.scope.account.getAssociatedTokenAccount(r,D):null,ie=ee;if(F.addInstruction({instructions:[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,U,this.scope.ownerPubKey,n,i),...oe?[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Z,this.scope.ownerPubKey,r,D),ct.SystemProgram.transfer({fromPubkey:this.scope.ownerPubKey,toPubkey:Z,lamports:BigInt(b.toString())}),(0,O.createSyncNativeInstruction)(Z)]:[]]}),!oe){let{account:fe,instructionParams:He}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:D,mint:r,owner:this.scope.ownerPubKey,createInfo:ie?{payer:this.scope.ownerPubKey,amount:b}:void 0,skipCloseAccount:!ie,notUseTokenAccount:ie,associatedOnly:ie?!1:I,checkCreateATAOwner:S});fe&&(Z=fe),F.addInstruction(He||{})}Z||this.logAndCreateError(`cannot found mintB(${r.toBase58()}) buy token accounts`,"tokenAccounts",this.scope.account.tokenAccounts);let _=s;if(!_){let fe=await this.scope.connection.getAccountInfo(W,{commitment:"processed"});fe||this.logAndCreateError("cannot found pool:",W.toBase58()),_=We.decode(fe.data)}let ae=l,pe=await Oe(this.scope.connection,[ae?void 0:_.configId,_.platformId].filter(Boolean).map(fe=>({pubkey:fe})));if(!ae){let fe=pe.find(He=>He.pubkey.equals(_.configId));(!fe||!fe.accountInfo)&&this.logAndCreateError("config not found: ",_.configId.toBase58()),ae=it.decode(fe.accountInfo.data)}let te=pe.find(fe=>fe.pubkey.equals(_.platformId));(!te||!te.accountInfo)&&this.logAndCreateError("platform info not found: ",_.configId.toBase58());let ge=At.decode(te.accountInfo.data);c=c||ge.feeRate;let se=Me.buyExactIn({poolInfo:_,amountB:b,protocolFeeRate:ae.tradeFeeRate,platformFeeRate:c,curveType:ae.curveType,shareFeeRate:P,creatorFeeRate:ge.creatorFeeRate,transferFeeConfigA:G,transferFeeConfigB:M,slot:await this.scope.connection.getSlot()}),ve=new Ne.default(se.amountA.amount.toString()).sub((Se=(Y=se.amountA.fee)==null?void 0:Y.toString())!=null?Se:0),et=y?new Ne.default(ut.sub(y).toNumber()/ut.toNumber()).clampedTo(0,1):new Ne.default(1),ke=f!=null?f:y?new E.default(ve.mul(et).toFixed(0)):se.amountA.amount.sub((Ye=se.amountA.fee)!=null?Ye:new E.default(0));se.amountB.lt(b)&&console.log(`maximum ${n.toBase58()} amount can buy is ${se.amountA.toString()}, input ${r.toBase58()} amount: ${se.amountB.toString()}`);let J=T?be(T,r,D).publicKey:void 0;return J&&F.addInstruction({instructions:[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,J,T,r,D)]}),F.addInstruction({instructions:[No(e,this.scope.ownerPubKey,t,_.configId,_.platformId,W,U,Z,_.vaultA,_.vaultB,n,r,i,D,nt(e,_.platformId,r).publicKey,ot(e,_.creator,r).publicKey,se.amountB.lt(b)?se.amountB:b,ke,P,J)]}),F.addCustomComputeBudget(d),F.addTipInstruction(p),F.versionBuild({txVersion:u,extInfo:z(v({},se),{decimalOutAmount:ve,minDecimalOutAmount:new Ne.default(ke.toString())})})}async buyTokenExactOut({programId:e=me,authProgramId:t,mintA:n,mintAProgram:i=O.TOKEN_PROGRAM_ID,mintB:r=O.NATIVE_MINT,poolInfo:s,configInfo:l,transferFeeConfigA:c,platformFeeRate:u,txVersion:d,computeBudgetConfig:p,txTipConfig:g,feePayer:b,maxBuyAmount:f,outAmount:y,slippage:P,shareFeeRate:T=new E.default(0),shareFeeReceiver:I,associatedOnly:S=!0,checkCreateATAOwner:x=!1,skipCheckMintA:h=!1,mintBProgram:B,transferFeeConfigB:R,skipCheckMintB:K=!1}){y.lte(new E.default(0))&&this.logAndCreateError("out amount should gt 0:",y.toString());let L=this.createTxBuilder(b),{publicKey:F}=Ot(e,n,r);t=t!=null?t:De(e).publicKey;let W=s;if(!W){let J=await this.scope.connection.getAccountInfo(F,{commitment:"processed"});J||this.logAndCreateError("cannot found pool:",F.toBase58()),W=We.decode(J.data)}let G=l,D=await Oe(this.scope.connection,[G?void 0:W.configId,W.platformId].filter(Boolean).map(J=>({pubkey:J})));if(!G){let J=D.find(Y=>Y.pubkey.equals(W.configId));(!J||!J.accountInfo)&&this.logAndCreateError("config not found: ",W.configId.toBase58()),G=it.decode(J.accountInfo.data)}let M=D.find(J=>J.pubkey.equals(W.platformId));(!M||!M.accountInfo)&&this.logAndCreateError("platform info not found: ",W.configId.toBase58());let U=At.decode(M.accountInfo.data);u=u||U.feeRate;let ee=c;if(!h)if(ee)i=O.TOKEN_2022_PROGRAM_ID;else{let J=await this.scope.connection.getAccountInfo(n);if(J&&J.owner.equals(O.TOKEN_2022_PROGRAM_ID)){i=J.owner;let Y=(0,O.unpackMint)(n,J,i);ee=(0,O.getTransferFeeConfig)(Y)||void 0}}let{mintBProgram:oe,transferFeeConfigB:Z}=await this.getMintBTokenInfo({mintB:r,mintBProgram:B,transferFeeConfigB:R,skipCheckMintB:K}),ie=Me.buyExactOut({poolInfo:W,amountA:y,protocolFeeRate:G.tradeFeeRate,platformFeeRate:u,curveType:G.curveType,shareFeeRate:T,creatorFeeRate:U.creatorFeeRate,transferFeeConfigA:ee,transferFeeConfigB:Z,slot:await this.scope.connection.getSlot()}),_=new Ne.default(ie.amountB.toString()),ae=P?new Ne.default(ut.add(P).toNumber()/ut.toNumber()).clampedTo(0,Number.MIN_SAFE_INTEGER):new Ne.default(1),pe=(f!=null?f:P)?new E.default(_.mul(ae).toFixed(0)):ie.amountB,te=this.scope.account.getAssociatedTokenAccount(n,i),ge=null,se=r.equals(O.NATIVE_MINT);L.addInstruction({instructions:[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,te,this.scope.ownerPubKey,n,i)]});let{account:ve,instructionParams:et}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:oe,mint:r,owner:this.scope.ownerPubKey,createInfo:se?{payer:this.scope.ownerPubKey,amount:ie.amountB}:void 0,skipCloseAccount:!se,notUseTokenAccount:se,associatedOnly:se?!1:S,checkCreateATAOwner:x});ve&&(ge=ve),L.addInstruction(et||{}),ge===void 0&&this.logAndCreateError(`cannot found mintB(${r.toBase58()}) token accounts`,"tokenAccounts",this.scope.account.tokenAccounts);let ke=I?be(I,r,oe).publicKey:void 0;return ke&&L.addInstruction({instructions:[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,ke,I,r,oe)]}),L.addInstruction({instructions:[Ir(e,this.scope.ownerPubKey,t,W.configId,W.platformId,F,te,ge,W.vaultA,W.vaultB,n,r,i,oe,nt(e,W.platformId,r).publicKey,ot(e,W.creator,r).publicKey,y,pe,T,ke)]}),L.addCustomComputeBudget(p),L.addTipInstruction(g),L.versionBuild({txVersion:d,extInfo:{maxSpentAmount:pe,outAmount:y}})}async sellToken({programId:e=me,authProgramId:t,mintAProgram:n=O.TOKEN_PROGRAM_ID,mintA:i,mintB:r=O.NATIVE_MINT,poolInfo:s,configInfo:l,platformFeeRate:c,txVersion:u,computeBudgetConfig:d,txTipConfig:p,feePayer:g,sellAmount:b,minAmountB:f,slippage:y,shareFeeRate:P=new E.default(0),shareFeeReceiver:T,associatedOnly:I=!0,checkCreateATAOwner:S=!1,skipCheckMintA:x=!1,mintBProgram:h,transferFeeConfigB:B,skipCheckMintB:R=!1}){t=t!=null?t:De(e).publicKey;let K=this.createTxBuilder(g);b.lte(new E.default(0))&&this.logAndCreateError("sell amount should be gt 0");let{publicKey:L}=Ot(e,i,r),F;if(!x){let Y=await this.scope.connection.getAccountInfo(i);if(Y&&Y.owner.equals(O.TOKEN_2022_PROGRAM_ID)){n=Y.owner;let Se=(0,O.unpackMint)(i,Y,n);F=(0,O.getTransferFeeConfig)(Se)||void 0}}let{mintBProgram:W,transferFeeConfigB:G}=await this.getMintBTokenInfo({mintB:r,mintBProgram:h,transferFeeConfigB:B,skipCheckMintB:R}),D=null,M=null,U=r.equals(O.NATIVE_MINT),{account:ee,instructionParams:oe}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n,mint:i,owner:this.scope.ownerPubKey,createInfo:void 0,skipCloseAccount:!0,notUseTokenAccount:!1,associatedOnly:I,checkCreateATAOwner:S});ee&&(D=ee),K.addInstruction(oe||{}),D===void 0&&this.logAndCreateError("cannot found mintA token accounts","tokenAccounts",this.scope.account.tokenAccounts);let{account:Z,instructionParams:ie}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:W,mint:r,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!U,notUseTokenAccount:U,associatedOnly:U?!1:I,checkCreateATAOwner:S});Z&&(M=Z),K.addInstruction(ie||{}),M||this.logAndCreateError("cannot found mintB token accounts","tokenAccounts",{userTokenAccountB:M});let _=s;if(!_){let Y=await this.scope.connection.getAccountInfo(L,{commitment:"processed"});Y||this.logAndCreateError("cannot found pool",L.toBase58()),_=We.decode(Y.data)}let ae=l,pe=await Oe(this.scope.connection,[ae?void 0:_.configId,_.platformId].filter(Boolean).map(Y=>({pubkey:Y})));if(!ae){let Y=pe.find(Se=>Se.pubkey.equals(_.configId));(!Y||!Y.accountInfo)&&this.logAndCreateError("config not found: ",_.configId.toBase58()),ae=it.decode(Y.accountInfo.data)}let te=pe.find(Y=>Y.pubkey.equals(_.platformId));(!te||!te.accountInfo)&&this.logAndCreateError("platform info not found: ",_.configId.toBase58());let ge=At.decode(te.accountInfo.data);c=c||ge.feeRate;let se=Me.sellExactIn({poolInfo:_,amountA:b,protocolFeeRate:ae.tradeFeeRate,platformFeeRate:c,curveType:ae.curveType,shareFeeRate:P,creatorFeeRate:ge.creatorFeeRate,transferFeeConfigA:F,transferFeeConfigB:G,slot:await this.scope.connection.getSlot()}),ve=new Ne.default(se.amountB.toString()),et=y?new Ne.default(ut.sub(y).toNumber()/ut.toNumber()).clampedTo(0,1):new Ne.default(1),ke=f!=null?f:y?new E.default(ve.mul(et).toFixed(0)):se.amountB;ke.lte(new E.default(0))&&this.logAndCreateError(`out ${r.toBase58()} amount should be gt 0`);let J=T?be(T,r,W).publicKey:void 0;return J&&K.addInstruction({instructions:[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,J,T,r,W)]}),K.addInstruction({instructions:[Mo(e,this.scope.ownerPubKey,t,_.configId,_.platformId,L,D,M,_.vaultA,_.vaultB,i,r,n,W,nt(e,_.platformId,r).publicKey,ot(e,_.creator,r).publicKey,se.amountA.amount.lt(b)?se.amountA.amount:b,ke,P,J)]}),K.addCustomComputeBudget(d),K.addTipInstruction(p),K.versionBuild({txVersion:u,extInfo:{outAmount:ke}})}async sellTokenExactOut({programId:e=me,authProgramId:t,mintAProgram:n=O.TOKEN_PROGRAM_ID,mintA:i,mintB:r=O.NATIVE_MINT,poolInfo:s,configInfo:l,platformFeeRate:c,txVersion:u,computeBudgetConfig:d,txTipConfig:p,feePayer:g,inAmount:b,maxSellAmount:f,slippage:y,shareFeeRate:P=new E.default(0),shareFeeReceiver:T,associatedOnly:I=!0,checkCreateATAOwner:S=!1,skipCheckMintA:x=!1,mintBProgram:h,transferFeeConfigB:B,skipCheckMintB:R=!1}){t=t!=null?t:De(e).publicKey;let K=this.createTxBuilder(g);f!=null&&f.lte(new E.default(0))&&this.logAndCreateError("max sell amount should be gt 0");let{publicKey:L}=Ot(e,i,r),F;if(!x){let Y=await this.scope.connection.getAccountInfo(i);if(Y&&Y.owner.equals(O.TOKEN_2022_PROGRAM_ID)){n=Y.owner;let Se=(0,O.unpackMint)(i,Y,n);F=(0,O.getTransferFeeConfig)(Se)||void 0}}let{mintBProgram:W,transferFeeConfigB:G}=await this.getMintBTokenInfo({mintB:r,mintBProgram:h,transferFeeConfigB:B,skipCheckMintB:R}),D=null,M=null,U=r.equals(O.NATIVE_MINT),{account:ee,instructionParams:oe}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n,mint:i,owner:this.scope.ownerPubKey,createInfo:void 0,skipCloseAccount:!0,notUseTokenAccount:!1,associatedOnly:I,checkCreateATAOwner:S});ee&&(D=ee),K.addInstruction(oe||{}),D===void 0&&this.logAndCreateError("cannot found mintA token accounts","tokenAccounts",this.scope.account.tokenAccounts);let{account:Z,instructionParams:ie}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:W,mint:r,owner:this.scope.ownerPubKey,createInfo:U?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!U,notUseTokenAccount:U,associatedOnly:U?!1:I,checkCreateATAOwner:S});Z&&(M=Z),K.addInstruction(ie||{}),M===void 0&&this.logAndCreateError("cannot found mintB token accounts","tokenAccounts",this.scope.account.tokenAccounts);let _=s;if(!_){let Y=await this.scope.connection.getAccountInfo(L,{commitment:"processed"});Y||this.logAndCreateError("cannot found pool",L.toBase58()),_=We.decode(Y.data)}let ae=l,pe=await Oe(this.scope.connection,[ae?void 0:_.configId,_.platformId].filter(Boolean).map(Y=>({pubkey:Y})));if(!ae){let Y=pe.find(Se=>Se.pubkey.equals(_.configId));(!Y||!Y.accountInfo)&&this.logAndCreateError("config not found: ",_.configId.toBase58()),ae=it.decode(Y.accountInfo.data)}let te=pe.find(Y=>Y.pubkey.equals(_.platformId));(!te||!te.accountInfo)&&this.logAndCreateError("platform info not found: ",_.configId.toBase58());let ge=At.decode(te.accountInfo.data);c=c||ge.feeRate;let se=Me.sellExactOut({poolInfo:_,amountB:b,protocolFeeRate:ae.tradeFeeRate,platformFeeRate:c,curveType:ae.curveType,shareFeeRate:P,creatorFeeRate:ge.creatorFeeRate,transferFeeConfigA:F,transferFeeConfigB:G,slot:await this.scope.connection.getSlot()}),ve=new Ne.default(se.amountA.amount.toString()),et=y?new Ne.default(ut.add(y).toNumber()/ut.toNumber()).clampedTo(0,Number.MAX_SAFE_INTEGER):new Ne.default(1),ke=(f!=null?f:y)?new E.default(ve.mul(et).toFixed(0)):se.amountA.amount,J=T?be(T,r,W).publicKey:void 0;return J&&K.addInstruction({instructions:[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,J,T,r,W)]}),K.addInstruction({instructions:[Br(e,this.scope.ownerPubKey,t,_.configId,_.platformId,L,D,M,_.vaultA,_.vaultB,i,r,n,W,nt(e,_.platformId,r).publicKey,ot(e,_.creator,r).publicKey,b,ke,P,J)]}),K.addCustomComputeBudget(d),K.addTipInstruction(p),K.versionBuild({txVersion:u,extInfo:{maxSellAmount:ke}})}async createPlatformConfig({programId:e=me,platformAdmin:t,platformClaimFeeWallet:n,platformLockNftWallet:i,platformVestingWallet:r,cpConfigId:s,migrateCpLockNftScale:l,transferFeeExtensionAuth:c,creatorFeeRate:u,feeRate:d,name:p,web:g,img:b,platformVestingScale:f=new E.default(0),txVersion:y,computeBudgetConfig:P,txTipConfig:T,feePayer:I}){let S=this.createTxBuilder(I),{publicKey:x}=Co(e,t);return S.addInstruction({instructions:[Sr(e,t,n,i,r,x,s,c,l,d,u,p,g,b,f)]}),S.addCustomComputeBudget(P),S.addTipInstruction(T),S.versionBuild({txVersion:y,extInfo:{platformId:x}})}async updatePlatformConfig({programId:e=me,platformAdmin:t,platformId:n,updateInfo:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),d=n!=null?n:Co(e,t).publicKey;return u.addInstruction({instructions:[Kr(e,t,d,i)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r})}async createPlatformVestingAccount({programId:e=me,platformVestingWallet:t,beneficiary:n,platformId:i,poolId:r,vestingRecord:s,txVersion:l,computeBudgetConfig:c,txTipConfig:u,feePayer:d}){let p=this.createTxBuilder(d),g=s!=null?s:Nt(e,r,n).publicKey;return p.addInstruction({instructions:[xr(e,t,n,i,r,g)]}),p.addCustomComputeBudget(c),p.addTipInstruction(u),p.versionBuild({txVersion:l})}async claimPlatformFee({programId:e=me,authProgramId:t,platformId:n,poolId:i,platformClaimFeeWallet:r,mintB:s,vaultB:l,mintBProgram:c,txVersion:u,computeBudgetConfig:d,txTipConfig:p,feePayer:g}){var I;let b=this.createTxBuilder(g);t=t!=null?t:De(e).publicKey;let f=s,y=l;if(!f){let S=await this.scope.connection.getAccountInfo(i,{commitment:"processed"});S||this.logAndCreateError("cannot found pool:",i.toBase58());let x=We.decode(S.data),h=await this.scope.connection.getAccountInfo(x.configId,{commitment:"processed"});h||this.logAndCreateError("cannot found config:",x.configId.toBase58()),f=it.decode(h.data).mintB,y=y!=null?y:x.vaultB}(!f||!y)&&this.logAndCreateError("cannot found mint info, mintB: ",f.toBase58(),", vaultB: ",(I=y==null?void 0:y.toBase58())!=null?I:"");let{mintBProgram:P}=await this.getMintBTokenInfo({mintB:f,mintBProgram:c}),T=be(this.scope.ownerPubKey,f,P).publicKey;return b.addInstruction({instructions:[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,T,this.scope.ownerPubKey,f,P)]}),b.addInstruction({instructions:[_o(e,r,t,i,n,y,T,f,P)]}),b.addCustomComputeBudget(d),b.addTipInstruction(p),b.versionBuild({txVersion:u})}async claimAllPlatformFee({programId:e=me,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:We.span},{memcmp:{offset:We.offsetOf("platformId"),bytes:n.toString()}}]})).map(f=>({poolId:f.pubkey,pool:We.decode(f.account.data)})).filter(({pool:f})=>f.platformFee.gt(new E.default(0))),g={},b=[...new Set(p.map(({pool:f})=>f.mintB.toBase58()))];return b.length&&(await Oe(this.scope.connection,b.map(y=>({pubkey:new ct.PublicKey(y)})))).forEach(y=>{var P,T;g[y.pubkey.toBase58()]=(T=(P=y.accountInfo)==null?void 0:P.owner)!=null?T:O.TOKEN_PROGRAM_ID}),p.forEach(({poolId:f,pool:y})=>{var I;let P=(I=g[y.mintB.toBase58()])!=null?I:O.TOKEN_PROGRAM_ID,T=be(this.scope.ownerPubKey,y.mintB,P).publicKey;u.addInstruction({instructions:[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,T,this.scope.ownerPubKey,y.mintB,P)]}),u.addInstruction({instructions:[_o(e,i,t,f,n,y.vaultB,T,y.mintB,P)]})}),u.addTipInstruction(l),r===0?u.sizeCheckBuildV0({computeBudgetConfig:s}):u.sizeCheckBuild({computeBudgetConfig:s})}async createVesting({programId:e=me,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=Nt(e,t,n).publicKey;return u.addInstruction({instructions:[vo(e,this.scope.ownerPubKey,n,t,p,i)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r})}async createMultipleVesting({programId:e=me,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=Nt(e,t,d.wallet).publicKey;l.addInstruction({instructions:[vo(e,this.scope.ownerPubKey,d.wallet,t,p,d.shareAmount)]})}),i===0?l.sizeCheckBuildV0({computeBudgetConfig:r}):l.sizeCheckBuild({computeBudgetConfig:r})}async claimVesting({programId:e=me,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||Nt(e,t,this.scope.ownerPubKey).publicKey,g=n;if(!g){let f=await this.scope.connection.getAccountInfo(t);f||this.logAndCreateError("pool not found"),g=We.decode(f.data)}let b=be(this.scope.ownerPubKey,g.mintA,O.TOKEN_PROGRAM_ID).publicKey;return u.addInstruction({instructions:[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,b,this.scope.ownerPubKey,g.mintA)]}),u.addInstruction({instructions:[Fo(e,this.scope.ownerPubKey,d,t,p,b,g.vaultA,g.mintA,O.TOKEN_PROGRAM_ID)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r})}async claimMultiVesting({programId:e=me,poolIdList:t,poolsInfo:n={},vestingRecords:i={},txVersion:r,computeBudgetConfig:s,feePayer:l}){let c=this.createTxBuilder(l),u=v({},n),d=De(e).publicKey,p=t.filter(g=>!u[g.toBase58()]);if(p.length){let g=await this.getRpcPoolsInfo({poolIdList:p});u=v(v({},u),g.poolInfoMap)}return t.forEach(g=>{let b=g.toBase58(),f=u[b];f||this.logAndCreateError(`pool info not found: ${b}`);let y=i[b]||Nt(e,g,this.scope.ownerPubKey).publicKey,P=be(this.scope.ownerPubKey,f.mintA,O.TOKEN_PROGRAM_ID).publicKey;c.addInstruction({instructions:[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,P,this.scope.ownerPubKey,f.mintA)]}),c.addInstruction({instructions:[Fo(e,this.scope.ownerPubKey,d,g,y,P,f.vaultA,f.mintA,O.TOKEN_PROGRAM_ID)]})}),r===0?c.sizeCheckBuildV0({computeBudgetConfig:s}):c.sizeCheckBuild({computeBudgetConfig:s})}async claimVaultPlatformFee({programId:e=me,platformId:t,mintB:n,mintBProgram:i,claimFeeWallet:r,txVersion:s,computeBudgetConfig:l,txTipConfig:c,feePayer:u}){let d=this.createTxBuilder(u),p=nt(e,t,n).publicKey,g=Ro(e).publicKey,{mintBProgram:b}=await this.getMintBTokenInfo({mintB:n,mintBProgram:i}),f=this.scope.account.getAssociatedTokenAccount(n,b);return d.addInstruction({instructions:[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,f,this.scope.ownerPubKey,n,b),Vo(e,t,r!=null?r:this.scope.ownerPubKey,g,p,f,n,b)]}),d.addCustomComputeBudget(l),d.addTipInstruction(c),d.versionBuild({txVersion:s})}async claimMultipleVaultPlatformFee({programId:e=me,platformList:t,unwrapSol:n=!0,txVersion:i,computeBudgetConfig:r,feePayer:s,associatedOnly:l=!0,checkCreateATAOwner:c=!1}){let u=this.createTxBuilder(s),d={};return t.forEach(async p=>{var P,T,I;let g=Ro(e).publicKey,b=nt(e,p.id,p.mintB).publicKey,f=p.mintB.equals(O.NATIVE_MINT)&&n,y=d[p.mintB.toBase58()];if(!y){let{account:S,instructionParams:x}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:(P=p.mintBProgram)!=null?P:O.TOKEN_PROGRAM_ID,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});S&&(y=S),u.addInstruction(x||{}),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:[Vo(e,p.id,(T=p.claimFeeWallet)!=null?T:this.scope.ownerPubKey,g,b,y,p.mintB,(I=p.mintBProgram)!=null?I:O.TOKEN_PROGRAM_ID)]})}),i===0?u.sizeCheckBuildV0({computeBudgetConfig:r}):u.sizeCheckBuild({computeBudgetConfig:r})}async claimCreatorFee({programId:e=me,mintB:t,mintBProgram:n,txVersion:i,computeBudgetConfig:r,txTipConfig:s,feePayer:l}){let c=this.createTxBuilder(l),u=ot(e,this.scope.ownerPubKey,t).publicKey,d=Lo(e).publicKey,{mintBProgram:p}=await this.getMintBTokenInfo({mintB:t,mintBProgram:n}),g=this.scope.account.getAssociatedTokenAccount(t,p);return c.addInstruction({instructions:[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,g,this.scope.ownerPubKey,t,p),Eo(e,this.scope.ownerPubKey,d,u,g,t,p)]}),c.addCustomComputeBudget(r),c.addTipInstruction(s),c.versionBuild({txVersion:i})}async claimMultipleCreatorFee({programId:e=me,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:O.TOKEN_PROGRAM_ID,d=ot(e,this.scope.ownerPubKey,c).publicKey,p=Lo(e).publicKey,g=this.scope.account.getAssociatedTokenAccount(c,u);s.addInstruction({instructions:[(0,O.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,g,this.scope.ownerPubKey,c,u),Eo(e,this.scope.ownerPubKey,p,d,g,c,u)]})}),n==0?s.sizeCheckBuildV0({computeBudgetConfig:i}):s.sizeCheckBuild({computeBudgetConfig:i})}async createPlatformAllowConfig({programId:e=me,platformAdmin:t,platformId:n,configInfo:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),{publicKey:d}=Ko(e,new ct.PublicKey(i.mintB),i.curveType,i.index),{publicKey:p}=nn(e,n,d);return u.addInstruction({instructions:[Cr(e,t,n,d,p)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r,extInfo:{platformId:n}})}async closePlatformAllowConfig({programId:e=me,platformAdmin:t,platformId:n,configInfo:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),{publicKey:d}=Ko(e,new ct.PublicKey(i.mintB),i.curveType,i.index),{publicKey:p}=nn(e,n,d);return u.addInstruction({instructions:[Rr(e,t,n,d,p)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r,extInfo:{platformAllowConfig:p}})}async createPlatformCurveRule({programId:e=me,curveRuleAuthority:t,platformId:n,configId:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),{publicKey:d}=Oo(e,n,i);return u.addInstruction({instructions:[Lr(e,t!=null?t:this.scope.ownerPubKey,n,i,d)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r,extInfo:{platformCurveRuleId:d}})}async updatePlatformCurveRule({programId:e=me,curveRuleAuthority:t,platformCurveRuleId:n,groupId:i,constraints:r,txVersion:s,computeBudgetConfig:l,txTipConfig:c,feePayer:u}){let d=this.createTxBuilder(u),p=await this.scope.connection.getAccountInfo(n);if(!p)throw new Error(`platformCurveRule ${n} not found`);let g=En.decode(p.data);return d.addInstruction({instructions:[Or(e,t!=null?t:this.scope.ownerPubKey,g.platformId,g.configId,n,i,r)]}),d.addCustomComputeBudget(l),d.addTipInstruction(c),d.versionBuild({txVersion:s})}async removePlatformCurveRule({programId:e=me,curveRuleAuthority:t,platformCurveRuleId:n,groupId:i,txVersion:r,computeBudgetConfig:s,txTipConfig:l,feePayer:c}){let u=this.createTxBuilder(c),d=await this.scope.connection.getAccountInfo(n);if(!d)throw new Error(`platformCurveRule ${n} not found`);let p=En.decode(d.data);return u.addInstruction({instructions:[Nr(e,t!=null?t:this.scope.ownerPubKey,p.platformId,p.configId,n,i)]}),u.addCustomComputeBudget(s),u.addTipInstruction(l),u.versionBuild({txVersion:r})}async closePlatformCurveRule({programId:e=me,curveRuleAuthority:t,platformCurveRuleId:n,txVersion:i,computeBudgetConfig:r,txTipConfig:s,feePayer:l}){let c=this.createTxBuilder(l),u=await this.scope.connection.getAccountInfo(n);if(!u)throw new Error(`platformCurveRule ${n} not found`);let d=En.decode(u.data);return c.addInstruction({instructions:[Mr(e,t!=null?t:this.scope.ownerPubKey,d.platformId,d.configId,n)]}),c.addCustomComputeBudget(r),c.addTipInstruction(s),c.versionBuild({txVersion:i})}async getRpcPoolInfo({poolId:e}){return(await this.getRpcPoolsInfo({poolIdList:[e]})).poolInfoMap[e.toBase58()]}async getRpcPoolsInfo({poolIdList:e,config:t}){let n=await Oe(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=We.decode(u.accountInfo.data);i[e[c].toBase58()]=z(v({},d),{poolId:e[c],programId:u.accountInfo.owner}),r.push(d.configId)}let s=await Oe(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=it.decode(u.accountInfo.data);l[r[c].toBase58()]=z(v({},d),{configId:u.accountInfo.owner})}return{poolInfoMap:Object.keys(i).reduce((c,u)=>z(v({},c),{[u]:z(v({},i[u]),{configInfo:l[i[u].configId.toBase58()]})}),{})}}};0&&(module.exports={LaunchpadPoolInitParam,usdMintBSet});
//# sourceMappingURL=launchpad.js.map