@raydium-io/raydium-sdk-v2
Version:
An SDK for building applications on top of Raydium.
3 lines • 531 kB
JavaScript
var Kd=Object.create;var Fi=Object.defineProperty,Cd=Object.defineProperties,Rd=Object.getOwnPropertyDescriptor,Ld=Object.getOwnPropertyDescriptors,Od=Object.getOwnPropertyNames,qr=Object.getOwnPropertySymbols,Nd=Object.getPrototypeOf,Is=Object.prototype.hasOwnProperty,ul=Object.prototype.propertyIsEnumerable;var sl=(l,e,t)=>e in l?Fi(l,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):l[e]=t,N=(l,e)=>{for(var t in e||(e={}))Is.call(e,t)&&sl(l,t,e[t]);if(qr)for(var t of qr(e))ul.call(e,t)&&sl(l,t,e[t]);return l},E=(l,e)=>Cd(l,Ld(e));var $e=(l,e)=>{var t={};for(var n in l)Is.call(l,n)&&e.indexOf(n)<0&&(t[n]=l[n]);if(l!=null&&qr)for(var n of qr(l))e.indexOf(n)<0&&ul.call(l,n)&&(t[n]=l[n]);return t};var Md=(l,e)=>{for(var t in e)Fi(l,t,{get:e[t],enumerable:!0})},cl=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Od(e))!Is.call(l,o)&&o!==t&&Fi(l,o,{get:()=>e[o],enumerable:!(n=Rd(e,o))||n.enumerable});return l};var ie=(l,e,t)=>(t=l!=null?Kd(Nd(l)):{},cl(e||!l||!l.__esModule?Fi(t,"default",{value:l,enumerable:!0}):t,l)),Fd=l=>cl(Fi({},"__esModule",{value:!0}),l);var Qf={};Md(Qf,{AMM_CONFIG_SEED:()=>mm,AUTH_SEED:()=>dd,BIT_PRECISION:()=>du,BN_NEGATIVE_ONE:()=>wp,BN_ONE:()=>dt,BN_ZERO:()=>$,BondingCurveParam:()=>as,CONFIG_SEED:()=>pd,CREATOR_FEE_VAULT_AUTH_SEED:()=>gd,Clmm:()=>li,ClmmConfigLayout:()=>ba,ClmmInstrument:()=>we,CollectFeeOn:()=>ya,ConstantProductCurve:()=>Bi,CpmmConfigInfoLayout:()=>xc,CpmmCreatorFeeOn:()=>Vc,CpmmFee:()=>nn,CpmmPermission:()=>Nf,CpmmPoolInfoLayout:()=>Br,Curve:()=>vt,CurveBase:()=>io,CurveCalculator:()=>xi,DEV_FARM_LOCK_MINT:()=>$p,DEV_FARM_LOCK_VAULT:()=>Jp,DYNAMIC_CONFIG_INDEX:()=>Tp,DYNAMIC_FEE_CONFIG_SEED:()=>Pm,DYNAMIC_FEE_CONTROL_DENOMINATOR:()=>yu,DataElement:()=>Ym,DynamicFeeConfigLayout:()=>Bp,DynamicFeeInfo:()=>Fo,DynamicFeeInfoLayout:()=>am,EXTENSION_TICKARRAY_BITMAP_SIZE:()=>Lo,FARM_LOCK_MINT:()=>Yu,FARM_LOCK_VAULT:()=>Hu,FARM_PROGRAM_TO_VERSION:()=>un,FARM_VERSION_TO_LEDGER_LAYOUT:()=>fi,FARM_VERSION_TO_STATE_LAYOUT:()=>pi,FEE_RATE_DENOMINATOR:()=>Wn,FeeOn:()=>Sc,FixedPriceCurve:()=>Or,LIQUIDITY_FEES_DENOMINATOR:()=>pr,LIQUIDITY_FEES_NUMERATOR:()=>Ua,LIQUIDITY_VERSION_TO_SERUM_VERSION:()=>Wm,LIQUIDITY_VERSION_TO_STATE_LAYOUT:()=>uf,LOCK_LIQUIDITY_SEED:()=>ud,LOG_B_2_X32:()=>cu,LOG_B_P_ERR_MARGIN_LOWER_X64:()=>lu,LOG_B_P_ERR_MARGIN_UPPER_X64:()=>mu,LaunchConstantProductCurve:()=>Rr,LaunchpadConfig:()=>no,LaunchpadMintProgramBit:()=>kd,LaunchpadPool:()=>wn,LaunchpadPoolInitParam:()=>Fr,LaunchpadVesting:()=>Ff,LimitOrderLayout:()=>po,LimitOrderMath:()=>$n,LimitOrderNonceLayout:()=>ku,LinearPriceCurve:()=>Mr,LiquidityMathUtil:()=>pt,LockClPositionLayoutV2:()=>Tu,LockPositionLayout:()=>xp,MAGIC_SQRT_10001:()=>yp,MARKET_STATE_LAYOUT_V2:()=>es,MARKET_STATE_LAYOUT_V3:()=>gs,MARKET_VERSION_TO_STATE_LAYOUT:()=>Gc,MAX_FEE_RATE:()=>bp,MAX_FEE_RATE_NUMERATOR:()=>Ji,MAX_SQRT_PRICE_X64:()=>St,MAX_TICK:()=>fn,MAX_TICK_SPACING:()=>gp,MIN_SQRT_PRICE_X64:()=>xt,MIN_TICK:()=>pn,Market:()=>_r,MathLaunch:()=>Oi,OBSERVATION_NUM:()=>bu,OBSERVATION_UPDATE_DURATION_DEFAULT:()=>Ap,OPERATION_SEED:()=>fm,OPERATION_SIZE_USIZE:()=>gu,ObservationItemLayout:()=>rm,ObservationLayout:()=>Au,OperationLayout:()=>wu,PERMISSION_SEED:()=>Am,PLATFORM_ALLOW_CONFIG_SEED:()=>Ad,PLATFORM_FEE_VAULT_AUTH_SEED:()=>bd,PLATFORM_GLOBAL_ACCESS_SEED:()=>Pd,PLATFORM_SEED:()=>yd,POOL_LOCK_ID_SEED:()=>Nu,POOL_OBSERVATION_SEED:()=>bm,POOL_REWARD_VAULT_SEED:()=>dm,POOL_SEED:()=>ir,POOL_TICK_ARRAY_BITMAP_SEED:()=>ym,POOL_VAULT_SEED:()=>Aa,POOL_VESTING_SEED:()=>fd,POSITION_SEED:()=>xu,PersonalPositionLayout:()=>tr,PlatformConfig:()=>kn,PlatformCurveParam:()=>md,PoolFee:()=>ci,PoolInfoLayout:()=>mo,PoolStatusBitFlag:()=>tm,PoolStatusBitIndex:()=>em,PoolUtil:()=>Jt,PoolUtils:()=>gt,PositionRewardInfoLayout:()=>um,PositionUtils:()=>Du,ProtocolPositionLayout:()=>Ip,Q128:()=>fa,Q64:()=>Ne,REDUCTION_FACTOR_DENOMINATOR:()=>fu,RESOLUTION:()=>Ro,REWARD_NUM:()=>ri,Raydium:()=>Dr,RewardInfoLayout:()=>sm,RewardState:()=>nm,RoundDirection:()=>yc,SERUM_PROGRAMID_TO_VERSION:()=>qc,SERUM_VERSION_TO_PROGRAMID:()=>Uc,SOL_INFO:()=>Sn,SPL_MINT_LAYOUT:()=>pa,SUPPORT_MINT_SEED:()=>gm,SqrtPriceMath:()=>si,StableLayout:()=>gr,SwapMathUtil:()=>ui,SwapState:()=>An,TICK_ARRAY_BITMAP_SIZE:()=>$i,TICK_ARRAY_SEED:()=>pm,TICK_ARRAY_SIZE:()=>$t,TICK_ARRAY_SIZE_USIZE:()=>Pp,TICK_TO_SQRT_PRICE_FACTORS:()=>pu,TOKEN_WSOL:()=>ht,TickArrayBitmapExtensionLayout:()=>nr,TickArrayBitmapUtil:()=>Un,TickArrayLayout:()=>Oo,TickArrayUtil:()=>Te,TickLayout:()=>cm,TickUtil:()=>ae,TradeDirection:()=>rd,TradeDirectionOpposite:()=>ad,U128_MAX:()=>ji,U256_MAX:()=>_p,U64_IGNORE_RANGE:()=>hp,U64_MAX:()=>Mn,UpdateAmmConfigParam:()=>om,UpdateOperationAccountParam:()=>im,VOLATILITY_ACCUMULATOR_SCALE:()=>ii,VestingSchedule:()=>ld,Voter:()=>Xu,VoterDepositEntry:()=>Lm,VoterLockup:()=>Rm,VoterRegistrar:()=>zu,VoterVotingMintConfig:()=>Cm,WHITE_MINT_SIZE_USIZE:()=>Pu,abs:()=>Yp,addLiquidityLayout:()=>Ya,anchorDataBuf:()=>Tt,associatedLedgerAccountLayout:()=>Ba,buyExactInInstruction:()=>Ki,buyExactOutInstruction:()=>Lc,calFarmRewardAmount:()=>Ea,checkPoolToAmm:()=>qf,checkedAdd:()=>Cp,checkedMul:()=>Lp,checkedSub:()=>Rp,claimCreatorFee:()=>bs,claimPlatformFee:()=>fs,claimPlatformFeeFromVault:()=>ys,claimVestedToken:()=>ds,clearBit:()=>Up,clmmComputeInfoToApiInfo:()=>Eu,closeAccountInstruction:()=>Dn,closePlatformAllowConfigIns:()=>_c,collectCpFeeInstruction:()=>is,collectCreatorFeePermissionlessInInstruction:()=>Ic,cpmmLockPositionInstruction:()=>cd,createAssociatedLedgerAccountInstruction:()=>bi,createPlatformAllowConfigIns:()=>vc,createPlatformConfig:()=>Nc,createPlatformVestingAccountIns:()=>Fc,createPoolFeeLayout:()=>ac,createPoolV4InstructionV2:()=>ja,createPoolV4Layout:()=>sf,createVestingAccount:()=>ps,createWSolAccountInstructions:()=>jn,decimalToX64:()=>yo,divRoundingUp:()=>rr,dwLayout:()=>Xt,farmAddRewardLayout:()=>Ca,farmLedgerLayoutV3_1:()=>Zp,farmLedgerLayoutV3_2:()=>di,farmLedgerLayoutV5_1:()=>jp,farmLedgerLayoutV5_2:()=>Uu,farmLedgerLayoutV6_1:()=>Gu,farmRewardInfoToConfig:()=>Zu,farmRewardLayout:()=>Sa,farmRewardRestartLayout:()=>Ka,farmRewardTimeInfoLayout:()=>Km,farmStateV3Layout:()=>Wu,farmStateV5Layout:()=>qu,farmStateV6Layout:()=>mi,fetchMultipleFarmInfoAndUpdate:()=>ef,fetchTickArrays:()=>vu,fixedSwapInLayout:()=>Ga,fixedSwapOutLayout:()=>za,formatLayout:()=>jm,fromSignedI128:()=>Xp,generatePubKey:()=>st,getAssociatedAuthority:()=>Qu,getAssociatedConfigId:()=>Ar,getAssociatedLedgerAccount:()=>Wt,getAssociatedLedgerPoolAccount:()=>yi,getAssociatedOpenOrders:()=>nd,getAssociatedPoolKeys:()=>Ja,getCollectFeeOnDescription:()=>kp,getCpLockPda:()=>Wo,getCpmmPdaAmmConfigId:()=>Rf,getCpmmPdaPoolId:()=>ts,getCreatePoolKeys:()=>ns,getDepositEntryIndex:()=>Da,getDxByDyBaseIn:()=>lc,getDyByDxBaseIn:()=>cc,getFarmLedgerLayout:()=>Vo,getFarmStateLayout:()=>Nm,getLaunchpadPoolMintAProgram:()=>Kr,getLaunchpadPoolMintBProgram:()=>Wf,getLaunchpadPoolMintProgram:()=>Ec,getLiquidityAssociatedAuthority:()=>$a,getLiquidityAssociatedId:()=>bo,getOrderTick:()=>Hp,getPdaAmmConfigId:()=>Sp,getPdaCpiEvent:()=>oo,getPdaCreatorFeeVaultAuth:()=>ms,getPdaCreatorVault:()=>hn,getPdaDynamicFeeConfigAddress:()=>Kp,getPdaExBitmapAccount:()=>He,getPdaLaunchpadAuth:()=>Yt,getPdaLaunchpadConfigId:()=>ss,getPdaLaunchpadPoolId:()=>Uo,getPdaLaunchpadVaultId:()=>us,getPdaLimitOrderAddress:()=>Lu,getPdaLimitOrderNonceAddress:()=>Ou,getPdaLockClPositionIdV2:()=>No,getPdaLockPositionId:()=>ka,getPdaLpMint:()=>sd,getPdaMetadataKey:()=>qn,getPdaMintExAccount:()=>fo,getPdaMintExAccountCp:()=>os,getPdaObservationAccount:()=>wa,getPdaObservationId:()=>Po,getPdaOperationAccount:()=>ai,getPdaPermission:()=>Ku,getPdaPermissionId:()=>Pc,getPdaPermissionedPoolId:()=>Cu,getPdaPersonalPositionAddress:()=>sn,getPdaPlatformAllowConfig:()=>Si,getPdaPlatformConfigAccess:()=>_f,getPdaPlatformFeeVaultAuth:()=>ls,getPdaPlatformId:()=>cs,getPdaPlatformVault:()=>Tn,getPdaPoolAuthority:()=>go,getPdaPoolId:()=>Su,getPdaPoolRewardVaultId:()=>Ru,getPdaPoolVaultId:()=>an,getPdaProtocolPositionAddress:()=>gn,getPdaTickArrayAddress:()=>ve,getPdaVault:()=>gc,getPdaVestId:()=>Go,getRegistrarAddress:()=>Na,getStablePrice:()=>mc,getTokenOwnerRecordAddress:()=>Va,getVoterAddress:()=>va,getVoterWeightRecordAddress:()=>_a,getVotingMintAuthority:()=>Fa,getVotingTokenMint:()=>Ma,governanceCreateTokenOwnerRecord:()=>Vm,i32ToBytes:()=>Pa,i32ToBytesBE:()=>hu,initPoolLayout:()=>Xa,initTokenAccountInstruction:()=>da,initialize:()=>Vf,initializeMarket:()=>od,initializeV2:()=>Cc,initializeWithPermission:()=>Bc,initializeWithToken2022:()=>Rc,isBitSet:()=>Wp,isValidFarmVersion:()=>La,judgeFarmType:()=>tf,leastSignificantBit:()=>Dp,liquidityStateV4Layout:()=>wi,liquidityStateV5Layout:()=>qm,makeAMMSwapInstruction:()=>br,makeAMMSwapV2Instruction:()=>yr,makeAddLiquidityInstruction:()=>sc,makeAddNewRewardInstruction:()=>qa,makeCollectCreatorFeeInstruction:()=>rs,makeCpmmLockInstruction:()=>hc,makeCreateCpmmPoolInInstruction:()=>Ac,makeCreateFarmInstruction:()=>ju,makeCreateMarketInstruction:()=>kr,makeCreatorWithdrawFarmRewardInstruction:()=>$u,makeDepositCpmmInInstruction:()=>wc,makeDepositInstructionV3:()=>ec,makeDepositInstructionV5:()=>tc,makeDepositInstructionV6:()=>nc,makeDepositTokenInstruction:()=>of,makeDepositWithdrawInstruction:()=>af,makeInitPoolInstructionV4:()=>lf,makeRestartRewardInstruction:()=>Wa,makeSwapCpmmBaseInInstruction:()=>qo,makeSwapCpmmBaseOutInstruction:()=>Tc,makeSwapFixedInInstruction:()=>Um,makeSwapFixedOutInstruction:()=>Gm,makeSwapInstruction:()=>Yc,makeTransferInstruction:()=>uu,makeWithdrawCpmmInInstruction:()=>kc,makeWithdrawInstructionV3:()=>Ai,makeWithdrawInstructionV4:()=>Ju,makeWithdrawInstructionV5:()=>Pi,makeWithdrawInstructionV6:()=>gi,makeWithdrawTokenInstruction:()=>rf,mask:()=>ha,mockV3CreatePoolInfo:()=>er,modelDataInfoLayout:()=>Hm,mostSignificantBit:()=>Mu,mulDivCeil:()=>Qe,mulDivFloor:()=>ze,mulDivRound:()=>Np,mulFull:()=>Op,parseTokenAccountResp:()=>su,parseTokenInfo:()=>mp,poolLpAuthority:()=>rc,poolTypeV6:()=>Jn,realFarmStateV3Layout:()=>Bm,realFarmStateV5Layout:()=>xm,realFarmV6Layout:()=>Sm,removeLiquidityInstruction:()=>Za,removeLiquidityLayout:()=>Ha,removePlatformCurveParamInstruction:()=>Df,route1Instruction:()=>Gf,route2Instruction:()=>zf,routeInstruction:()=>Td,sellExactInInstruction:()=>Sr,sellExactOut:()=>Oc,setBit:()=>qp,simulatePoolInfoInstruction:()=>cf,solToWSolToken:()=>pp,splAccountLayout:()=>bn,swapBaseInAutoAccount:()=>Xf,swapBaseInV2Instruction:()=>zm,swapBaseOutAutoAccount:()=>Yf,swapBaseOutV2Instruction:()=>Xm,swapInternal:()=>Ia,toAmmComputePoolInfo:()=>wr,toApiV3Token:()=>At,toFeeConfig:()=>Nn,toLaunchpadMintProgramFlag:()=>Dc,toSignedI128:()=>zp,toToken:()=>oi,toTokenAmount:()=>yt,toTokenInfo:()=>dp,toTransferFeeConfig:()=>ro,toggleBit:()=>Gp,u128CheckedMul:()=>vp,u128SaturatingAdd:()=>Mp,u128SaturatingSub:()=>Fp,u16ToBytes:()=>or,u16ToBytesBE:()=>ga,u256MulDivCeil:()=>Ep,u256MulDivFloor:()=>Vp,u64ToBytes:()=>Iu,u8ToBytes:()=>Bu,unionArr:()=>Hf,updateFarmPoolInfo:()=>Mm,updatePlatformConfig:()=>Mc,updatePlatformCurveParamInstruction:()=>Ef,usdMintBSet:()=>Uf,validateFarmRewards:()=>Oa,voterStakeRegistryCreateDepositEntry:()=>Dm,voterStakeRegistryCreateVoter:()=>Em,voterStakeRegistryDeposit:()=>Fm,voterStakeRegistryUpdateVoterWeightRecord:()=>vm,voterStakeRegistryWithdraw:()=>_m,wSolToSolToken:()=>fp,withdrawRewardLayout:()=>xa,wrappingSubU128:()=>Dt,x64ToDecimal:()=>Fu});module.exports=Fd(Qf);var Id=require("lodash");var js=ie(require("axios"));var Ks=require("@solana/web3.js");var vi=require("lodash");var Bs=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}},ll={},vd={};function Se(l){let e=(0,vi.get)(ll,l);if(!e){let t=(0,vi.get)(vd,l);e=new Bs({name:l,logLevel:t}),(0,vi.set)(ll,l,e)}return e}var ao=require("@solana/spl-token"),xs=Se("Raydium_accountInfo_util");async function Lt(l,e,t){let{batchRequest:n,commitment:o="confirmed",chunkCount:i=100}=N({batchRequest:!1},t),r=Ss(e,i),a=new Array(r.length).fill([]);if(n){let s=r.map(d=>{let p=l._buildArgs([d.map(m=>m.toBase58())],o,"base64");return{methodName:"getMultipleAccounts",args:p}}),u=Ss(s,10);a=(await(await Promise.all(u.map(async d=>await l._rpcBatchRequest(d)))).flat()).map(d=>(d.error&&xs.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${d.error.message}`),d.result.value.map(p=>{if(p){let{data:m,executable:f,lamports:y,owner:b,rentEpoch:g}=p;return m.length!==2&&m[1]!=="base64"&&xs.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(m[0],"base64"),executable:f,lamports:y,owner:new Ks.PublicKey(b),rentEpoch:g}}return null})))}else try{a=await Promise.all(r.map(s=>l.getMultipleAccountsInfo(s,o)))}catch(s){s instanceof Error&&xs.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${s.message}`)}return a.flat()}async function qe(l,e,t){let n=await Lt(l,e.map(o=>o.pubkey),t);return e.map((o,i)=>E(N({},o),{accountInfo:n[i]}))}async function ho({connection:l,mints:e,config:t}){var i,r,a;if(e.length===0)return{};let n=await qe(l,e.map(s=>({pubkey:Vt(s)})),t),o={};for(let s of n){if(!s.accountInfo||s.accountInfo.data.length<ao.MINT_SIZE){console.log("invalid mint account",s.pubkey.toBase58());continue}let u=(0,ao.unpackMint)(s.pubkey,s.accountInfo,(i=s.accountInfo)==null?void 0:i.owner);o[s.pubkey.toString()]=E(N({},u),{programId:((r=s.accountInfo)==null?void 0:r.owner)||ao.TOKEN_PROGRAM_ID,feeConfig:(a=(0,ao.getTransferFeeConfig)(u))!=null?a:void 0})}return o[Ks.PublicKey.default.toBase58()]=o[ee.toBase58()],o}var Hn=ie(require("bn.js")),Gd=ie(require("decimal.js"));var bl=ie(require("big.js")),Di=ie(require("bn.js"));var ml=ie(require("toformat")),_d=ml.default,_i=_d;var Vi=ie(require("big.js")),pl=ie(require("bn.js")),fl=ie(require("decimal.js-light"));var Yo=ie(require("bn.js"));var dl=9007199254740991;function fe(l){let e=Se("Raydium_parseBigNumberish");if(l instanceof Yo.default)return l;if(typeof l=="string"){if(l.match(/^-?[0-9]+$/))return new Yo.default(l);e.logWithError(`invalid BigNumberish string: ${l}`)}return typeof l=="number"?(l%1&&e.logWithError(`BigNumberish number underflow: ${l}`),(l>=dl||l<=-dl)&&e.logWithError(`BigNumberish number overflow: ${l}`),new Yo.default(String(l))):typeof l=="bigint"?new Yo.default(l.toString()):(e.error(`invalid BigNumberish value: ${l}`),new Yo.default(0))}var Ur=Se("module/fraction"),Cs=_i(Vi.default),Ei=_i(fl.default),Ed={[0]:Ei.ROUND_DOWN,[1]:Ei.ROUND_HALF_UP,[2]:Ei.ROUND_UP},Dd={[0]:Vi.default.roundDown,[1]:Vi.default.roundHalfUp,[2]:Vi.default.roundUp},Ve=class{constructor(e,t=new pl.default(1)){this.numerator=fe(e),this.denominator=fe(t)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new Ve(this.denominator,this.numerator)}add(e){let t=e instanceof Ve?e:new Ve(fe(e));return this.denominator.eq(t.denominator)?new Ve(this.numerator.add(t.numerator),this.denominator):new Ve(this.numerator.mul(t.denominator).add(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}sub(e){let t=e instanceof Ve?e:new Ve(fe(e));return this.denominator.eq(t.denominator)?new Ve(this.numerator.sub(t.numerator),this.denominator):new Ve(this.numerator.mul(t.denominator).sub(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}mul(e){let t=e instanceof Ve?e:new Ve(fe(e));return new Ve(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof Ve?e:new Ve(fe(e));return new Ve(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},n=1){Number.isInteger(e)||Ur.logWithError(`${e} is not an integer.`),e<=0&&Ur.logWithError(`${e} is not positive.`),Ei.set({precision:e+1,rounding:Ed[n]});let o=new Ei(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return o.toFormat(o.decimalPlaces(),t)}toFixed(e,t={groupSeparator:""},n=1){return Number.isInteger(e)||Ur.logWithError(`${e} is not an integer.`),e<0&&Ur.logWithError(`${e} is negative.`),Cs.DP=e,Cs.RM=Dd[n]||1,new Cs(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var Wd=Se("Raydium_amount"),yl=_i(bl.default);function qd(l,e){let t="0",n="0";if(l.includes(".")){let o=l.split(".");o.length===2?([t,n]=o,n=n.padEnd(e,"0")):Wd.logWithError(`invalid number string, num: ${l}`)}else t=l;return[t,n.slice(0,e)||n]}var Ee=class extends Ve{constructor(t,n,o=!0,i){let r=new Di.default(0),a=Rs.pow(new Di.default(t.decimals));if(o)r=fe(n);else{let s=new Di.default(0),u=new Di.default(0);if(typeof n=="string"||typeof n=="number"||typeof n=="bigint"){let[c,d]=qd(n.toString(),t.decimals);s=fe(c),u=fe(d)}s=s.mul(a),r=s.add(u)}super(r,a);this.logger=Se(i||"TokenAmount"),this.token=t}get raw(){return this.numerator}isZero(){return this.raw.isZero()}gt(t){return this.token.equals(t.token)||this.logger.logWithError("gt token not equals"),this.raw.gt(t.raw)}lt(t){return this.token.equals(t.token)||this.logger.logWithError("lt token not equals"),this.raw.lt(t.raw)}add(t){return this.token.equals(t.token)||this.logger.logWithError("add token not equals"),new Ee(this.token,this.raw.add(t.raw))}subtract(t){return this.token.equals(t.token)||this.logger.logWithError("sub token not equals"),new Ee(this.token,this.raw.sub(t.raw))}toSignificant(t=this.token.decimals,n,o=0){return super.toSignificant(t,n,o)}toFixed(t=this.token.decimals,n,o=0){return t>this.token.decimals&&this.logger.logWithError("decimals overflow"),super.toFixed(t,n,o)}toExact(t={groupSeparator:""}){return yl.DP=this.token.decimals,new yl(this.numerator.toString()).div(this.denominator.toString()).toFormat(t)}};var gl=require("@solana/web3.js"),Ls=require("@solana/spl-token"),Sn={chainId:101,address:gl.PublicKey.default.toBase58(),programId:Ls.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"}},ht={chainId:101,address:"So11111111111111111111111111111111111111112",programId:Ls.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 zr=require("@solana/web3.js");var Ue=require("@solana/web3.js"),Pl=require("@solana/spl-token");function T({pubkey:l,isSigner:e=!1,isWritable:t=!0}){return{pubkey:l,isWritable:t,isSigner:e}}var Os=[T({pubkey:Pl.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:Ue.SystemProgram.programId,isWritable:!1}),T({pubkey:Ue.SYSVAR_RENT_PUBKEY,isWritable:!1})];function Ns({publicKey:l,transformSol:e}){let t=Ms(l.toString());if(t instanceof Ue.PublicKey)return e&&t.equals(Ot)?ee:t;if(e&&t.toString()===Ot.toBase58())return ee;if(typeof t=="string"){if(t===Ue.PublicKey.default.toBase58())return Ue.PublicKey.default;try{return new Ue.PublicKey(t)}catch{throw new Error("invalid public key")}}throw new Error("invalid public key")}function Ms(l){try{return new Ue.PublicKey(l)}catch{return l}}var mn=new Ue.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),It=new Ue.PublicKey("SysvarRent111111111111111111111111111111111"),hy=new Ue.PublicKey("SysvarC1ock11111111111111111111111111111111"),Kn=new Ue.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Gr=new Ue.PublicKey("Sysvar1nstructions1111111111111111111111111"),Al=Ue.SystemProgram.programId,Iy=new Ue.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),By=new Ue.PublicKey("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),xy=new Ue.PublicKey("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Sy=new Ue.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Ky=new Ue.PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),Cy=new Ue.PublicKey("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Ry=new Ue.PublicKey("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Ly=new Ue.PublicKey("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Oy=new Ue.PublicKey("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Ny=new Ue.PublicKey("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),My=new Ue.PublicKey("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),ee=new Ue.PublicKey("So11111111111111111111111111111111111111112"),Ot=Ue.PublicKey.default;function Vt(l){return Ns({publicKey:l,transformSol:!0})}var Fs=class{constructor({mint:e,decimals:t,symbol:n,name:o,skipMint:i=!1,isToken2022:r=!1}){if(e===Ot.toBase58()||e instanceof zr.PublicKey&&Ot.equals(e)){this.decimals=ht.decimals,this.symbol=ht.symbol,this.name=ht.name,this.mint=new zr.PublicKey(ht.address),this.isToken2022=!1;return}this.decimals=t,this.symbol=n||e.toString().substring(0,6),this.name=o||e.toString().substring(0,6),this.mint=i?zr.PublicKey.default:Ns({publicKey:e}),this.isToken2022=r}equals(e){return this===e?!0:this.mint.equals(e.mint)}},Je=Fs;Je.WSOL=new Fs(E(N({},ht),{mint:ht.address}));var vs=class{constructor({decimals:e,symbol:t="UNKNOWN",name:n="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=n}equals(e){return this===e}},Xr=vs;Xr.SOL=new vs(Sn);var kl=ie(require("bn.js"));var wl=new Ve(new kl.default(100)),Nt=class extends Ve{toSignificant(e=5,t,n){return this.mul(wl).toSignificant(e,t,n)}toFixed(e=2,t,n){return this.mul(wl).toFixed(e,t,n)}};var Ud=Se("Raydium_price"),Zt=class extends Ve{constructor(t){let{baseToken:n,quoteToken:o,numerator:i,denominator:r}=t;super(i,r);this.baseToken=n,this.quoteToken=o,this.scalar=new Ve(_s(n.decimals),_s(o.decimals))}get raw(){return new Ve(this.numerator,this.denominator)}get adjusted(){return super.mul(this.scalar)}invert(){return new Zt({baseToken:this.quoteToken,quoteToken:this.baseToken,denominator:this.numerator,numerator:this.denominator})}mul(t){this.quoteToken!==t.baseToken&&Ud.logWithError("mul token not equals");let n=super.mul(t);return new Zt({baseToken:this.baseToken,quoteToken:t.quoteToken,denominator:n.denominator,numerator:n.numerator})}toSignificant(t=this.quoteToken.decimals,n,o){return this.adjusted.toSignificant(t,n,o)}toFixed(t=this.quoteToken.decimals,n,o){return this.adjusted.toFixed(t,n,o)}};var kb=new Hn.default(2),Tb=new Hn.default(3),hb=new Hn.default(5),Rs=new Hn.default(10),Ib=new Hn.default(100),Bb=new Hn.default(1e3),xb=new Hn.default(1e4);function _s(l){return Rs.pow(fe(l))}function Yr(l,e){let t=l.divmod(e);return t.mod.isZero()?t.div:l.isNeg()===e.isNeg()?t.div.iaddn(1):t.div}function Wi(l,e,t){return l.mul(e).add(t).sub(new Hn.default(1)).div(t)}function Hr(l,e,t){return l.mul(e).div(t)}var Tl=l=>typeof l=="number",zd=l=>l?new Date(l):new Date,Qr=l=>zd(l).getTime();function hl(l,e,t){let n=Tl(e)?e*((t==null?void 0:t.unit)==="s"?1e3:1):Qr(e);return Qr(l)<=n}function Il(l,e,t){let n=Tl(e)?e*((t==null?void 0:t.unit)==="s"?1e3:1):Qr(e);return Qr(l)>n}function Ss(l,e=1,t=[]){let n=[...l];if(e<=0)return t;for(;n.length;)t.push(n.splice(0,e));return t}var Cn=class{constructor(e){this._owner=e}get publicKey(){return Cn.isKeyPair(this._owner)?this._owner.publicKey:this._owner}get signer(){return Cn.isKeyPair(this._owner)?this._owner:void 0}get isKeyPair(){return Cn.isKeyPair(this._owner)}get isPublicKey(){return Cn.isPublicKey(this._owner)}static isKeyPair(e){return e.secretKey!==void 0}static isPublicKey(e){return!Cn.isKeyPair(e)}};var Kl=require("@solana/web3.js"),Cl=require("@solana/spl-token");var Gt=require("@solana/web3.js");var Y={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 xl=require("@solana/spl-token"),Bl=Se("Raydium_txUtil"),Sl=1644;function Zr(l){let e=[],t=[];return l.microLamports&&(e.push(Gt.ComputeBudgetProgram.setComputeUnitPrice({microLamports:l.microLamports})),t.push(Y.SetComputeUnitPrice)),l.units&&(e.push(Gt.ComputeBudgetProgram.setComputeUnitLimit({units:l.units})),t.push(Y.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}async function Ho(l,e){var n,o;let t=e!=null?e:"confirmed";return(o=await((n=l.getLatestBlockhash)==null?void 0:n.call(l,{commitment:t})))==null?void 0:o.blockhash}async function jr(l,e){return l.getSignatureStatuses([e]),new Promise((t,n)=>{let o=setTimeout(n,6e4);l.onSignature(e,i=>{if(clearTimeout(o),!i.err){t("");return}n(Object.assign(i.err,{txId:e}))},"confirmed")})}function Vs(l,e){l.length<1&&Bl.logWithError(`no instructions provided: ${l.toString()}`),e.length<1&&Bl.logWithError(`no signers provided:, ${e.toString()}`);let t=new Gt.Transaction;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...l);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<Sl}catch{return!1}}function re(l,e){let[t,n]=Gt.PublicKey.findProgramAddressSync(l,e);return{publicKey:t,nonce:n}}function qi({instructions:l,payer:e,signers:t}){return Vs(l,[e,...t])}function Ui({instructions:l,payer:e,lookupTableAddressAccount:t,recentBlockhash:n=Gt.Keypair.generate().publicKey.toString()}){let i=new Gt.TransactionMessage({payerKey:e,recentBlockhash:n,instructions:l}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new Gt.VersionedTransaction(i).serialize()).toString("base64").length<Sl}catch{return!1}}var Xd=l=>Buffer.isBuffer(l)?l:l instanceof Uint8Array?Buffer.from(l.buffer,l.byteOffset,l.byteLength):Buffer.from(l),Yd=l=>{let e=l.serialize({requireAllSignatures:!1,verifySignatures:!1});l instanceof Gt.VersionedTransaction&&(e=Xd(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch{return e.toString("base64")}};function Io(l){let e=[];return l.forEach(t=>{t instanceof Gt.Transaction&&(t.recentBlockhash||(t.recentBlockhash=xl.TOKEN_PROGRAM_ID.toBase58()),t.feePayer||(t.feePayer=Gt.Keypair.generate().publicKey)),e.push(Yd(t))}),console.log("simulate tx string:",e),e}function te(l,e,t){return re([l.toBuffer(),(t!=null?t:Cl.TOKEN_PROGRAM_ID).toBuffer(),e.toBuffer()],new Kl.PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}var be=require("@solana/web3.js"),Es=new be.PublicKey("EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"),Ds=new be.PublicKey("CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T"),Ws=new be.PublicKey("9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z"),Qo=new be.PublicKey("FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG"),Hd=new be.PublicKey("CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS"),qs=new be.PublicKey("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"),$r=new be.PublicKey("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),Gi=new be.PublicKey("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"),Qd=new be.PublicKey("5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h"),Jr=new be.PublicKey("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),Vn=new be.PublicKey("CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"),Zo=new be.PublicKey("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),zi=new be.PublicKey("kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy"),so=new be.PublicKey("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),Zd=new be.PublicKey("routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS"),Us=new be.PublicKey("7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5"),Qn=new be.PublicKey("CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"),Gs=new be.PublicKey("GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"),jd=new be.PublicKey("DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8"),jo=new be.PublicKey("LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE"),Xi=new be.PublicKey("3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH"),ct=new be.PublicKey("LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj"),$d=new be.PublicKey("WLHv2UAZm6z4KyaaELi5pjdbJh6RESMva1Rnn8pJVVh"),qb=new be.PublicKey("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),Ub=new be.PublicKey("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),Jd=new be.PublicKey("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),ep=new be.PublicKey("6s1xP3hpbAfFoNtUNF8mfHsjr2Bd97JxFJRWLbL6aHuX"),jt={AMM_V4:Gi,AMM_STABLE:Qd,CLMM_PROGRAM_ID:Vn,CLMM_LOCK_PROGRAM_ID:Zo,CLMM_LOCK_AUTH_ID:zi,FARM_PROGRAM_ID_V3:Es,FARM_PROGRAM_ID_V4:Ds,FARM_PROGRAM_ID_V5:Ws,FARM_PROGRAM_ID_V6:Qo,OPEN_BOOK_PROGRAM:qs,SERUM_PROGRAM_ID_V3:$r,UTIL1216:Hd,Router:Zd,CREATE_CPMM_POOL_PROGRAM:Qn,CREATE_CPMM_POOL_AUTH:Gs,CREATE_CPMM_POOL_FEE_ACC:jd,LOCK_CPMM_PROGRAM:jo,LOCK_CPMM_AUTH:Xi,LAUNCHPAD_PROGRAM:ct,LAUNCHPAD_AUTH:$d,LAUNCHPAD_PLATFORM:Jd,LAUNCHPAD_CONFIG:ep,FEE_DESTINATION_ID:Us,MODEL_DATA_PUBKEY:so},Rn={OPEN_BOOK_PROGRAM:new be.PublicKey("EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj"),SERUM_PROGRAM_ID_V3:new be.PublicKey("Ray1111111111111111111111111111111111111111"),AMM_V4:new be.PublicKey("DRaya7Kj3aMWQSy19kSjvmuwq9docCHofyP9kanQGaav"),AMM_STABLE:new be.PublicKey("DRayDdXc1NZQ9C3hRWmoSf8zK4iapgMnjdNZWrfwsP8m"),CLMM_PROGRAM_ID:new be.PublicKey("DRayAUgENGQBKVaX8owNhgzkEDyoHTGVEGHVJT1E9pfH"),CLMM_LOCK_PROGRAM_ID:new be.PublicKey("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),CLMM_LOCK_AUTH_ID:new be.PublicKey("6Aoh8h2Lw2m5UGxYR8AdAL87jTWYeKoxM52mJRzfYwN"),CREATE_CPMM_POOL_PROGRAM:new be.PublicKey("DRaycpLY18LhpbydsBWbVJtxpNv9oXPgjRSfpF2bWpYb"),CREATE_CPMM_POOL_AUTH:new be.PublicKey("CXniRufdq5xL8t8jZAPxsPZDpuudwuJSPWnbcD5Y5Nxq"),CREATE_CPMM_POOL_FEE_ACC:new be.PublicKey("3oE58BKVt8KuYkGxx8zBojugnymWmBiyafWgMrnb6eYy"),LOCK_CPMM_PROGRAM:new be.PublicKey("DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX"),LOCK_CPMM_AUTH:new be.PublicKey("7qWVV8UY2bRJfDLP4s37YzBPKUkVB46DStYJBpYbQzu3"),UTIL1216:be.PublicKey.default,Router:new be.PublicKey("DRaybByLpbUL57LJARs3j8BitTxVfzBg351EaMr5UTCd"),FARM_PROGRAM_ID_V3:new be.PublicKey("DRayWyrLmEW5KEeqs8kdTMMaBabapqagaBC7KWpGtJeZ"),FARM_PROGRAM_ID_V4:new be.PublicKey("Ray1111111111111111111111111111111111111111"),FARM_PROGRAM_ID_V5:new be.PublicKey("DRayiCGSZgku1GTK6rXD6mVDdingXy6APAH1R6R5L2LC"),FARM_PROGRAM_ID_V6:new be.PublicKey("DRayzbYakXs45ELHkzH6vC3fuhQqTAnv5A68gdFuvZyZ"),LAUNCHPAD_PROGRAM:new be.PublicKey("DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6"),LAUNCHPAD_AUTH:new be.PublicKey("5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq"),LAUNCHPAD_PLATFORM:new be.PublicKey("2Jx4KTDrVSdWNazuGpcA8n3ZLTRGGBDxAWhuKe2Xcj2a"),LAUNCHPAD_CONFIG:new be.PublicKey("7ZR4zD7PYfY2XxoG1Gxcy2EgEeGYrpxrwzPuwdUBssEt"),FEE_DESTINATION_ID:new be.PublicKey("9y8ENuuZ3b19quffx9hQvRVygG5ky6snHfRvGpuSfeJy"),MODEL_DATA_PUBKEY:new be.PublicKey("Ray1111111111111111111111111111111111111111")};var Ye=ie(require("bn.js")),En=1e4;function Bt(l,e,t,n){if(e===void 0)return{amount:l,fee:void 0,expirationTime:void 0};let o=E(N({},e),{olderTransferFee:{epoch:BigInt(e.olderTransferFee.epoch),maximumFee:BigInt(e.olderTransferFee.maximumFee),transferFeeBasisPoints:e.olderTransferFee.transferFeeBasisPoints},newerTransferFee:{epoch:BigInt(e.newerTransferFee.epoch),maximumFee:BigInt(e.newerTransferFee.maximumFee),transferFeeBasisPoints:e.newerTransferFee.transferFeeBasisPoints}}),i=t.epoch<o.newerTransferFee.epoch?o.olderTransferFee:o.newerTransferFee,r=new Ye.default(i.maximumFee.toString()),a=t.epoch<o.newerTransferFee.epoch?(Number(o.newerTransferFee.epoch)*t.slotsInEpoch-t.absoluteSlot)*400/1e3:void 0;if(n)if(i.transferFeeBasisPoints===En){let s=new Ye.default(i.maximumFee.toString());return{amount:l.add(s),fee:s,expirationTime:a}}else{let s=uo(l.mul(new Ye.default(En)),new Ye.default(En-i.transferFeeBasisPoints)),u=new Ye.default(i.maximumFee.toString()),c=s.sub(l).gt(u)?l.add(u):s,d=uo(c.mul(new Ye.default(i.transferFeeBasisPoints)),new Ye.default(En)),p=d.gt(r)?r:d;return{amount:c,fee:p,expirationTime:a}}else{let s=uo(l.mul(new Ye.default(i.transferFeeBasisPoints)),new Ye.default(En)),u=s.gt(r)?r:s;return{amount:l,fee:u,expirationTime:a}}}function Zn(l,e){return l===void 0?e:e===void 0?l:Math.min(l,e)}function uo(l,e){let{div:t,mod:n}=l.divmod(e);return n.gt(new Ye.default(0))?t.add(new Ye.default(1)):t}function Bo(l,e){if(l.isZero())return new Ye.default(0);let t=l.div(e);return t.isZero()?new Ye.default(1):l.mod(e).gt(new Ye.default(0))?t.add(new Ye.default(1)):t}function Yi(l,e,t){if(e===void 0)return{amount:l,fee:void 0,expirationTime:void 0};let n=Math.floor(t/432e3),o=n<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,i=new Ye.default(o.maximumFee.toString()),r=n<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*432e3-t)*400/1e3:void 0,a=uo(l.mul(new Ye.default(o.transferFeeBasisPoints)),new Ye.default(En)),s=a.gt(i)?i:a;return{amount:l,fee:s,expirationTime:r}}function $o(l,e,t){if(e===void 0)return{amount:l,fee:void 0,expirationTime:void 0};let n=Math.floor(t/432e3),o=n<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,i=new Ye.default(o.maximumFee.toString()),r=n<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*432e3-t)*400/1e3:void 0;if(o.transferFeeBasisPoints===En){let a=new Ye.default(o.maximumFee.toString());return{amount:l.add(a),fee:a,expirationTime:r}}else{let a=uo(l.mul(new Ye.default(En)),new Ye.default(En-o.transferFeeBasisPoints)),s=new Ye.default(o.maximumFee.toString()),u=a.sub(l).gt(s)?l.add(s):a,c=uo(u.mul(new Ye.default(o.transferFeeBasisPoints)),new Ye.default(En)),d=c.gt(i)?i:c;return{amount:u,fee:d,expirationTime:r}}}var Ln=require("@solana/web3.js");async function zs({connection:l,address:e,cluster:t="mainnet"}){let n=await Lt(l,[...new Set(e.map(i=>i.toString()))].map(i=>new Ln.PublicKey(i))),o={};for(let i=0;i<e.length;i++){let r=n[i],a=e[i];if(!r)continue;let s=new Ln.AddressLookupTableAccount({key:a,state:Ln.AddressLookupTableAccount.deserialize(r.data)});o[a.toString()]=s,t==="devnet"?ei[a.toString()]=s:Jo[a.toString()]=s}return o}var Jo={},Xs=async l=>{let e="AcL1Vo8oy1ULiavEcjSUcwfBSForXMudcZvDZy5nzJkU";if(Jo[e])return Jo;let t=new Ln.PublicKey(e),n=await l.getAccountInfo(t);return n&&(Jo[e]=new Ln.AddressLookupTableAccount({key:t,state:Ln.AddressLookupTableAccount.deserialize(n.data)})),Jo},ei={},Ys=async l=>{let e="EFhMuDw1PKEuckuFRW9PavNfTH4LKP5uKHgyXDmWpFCq";if(ei[e])return ei;let t=new Ln.PublicKey(e),n=await l.getAccountInfo(t);return n&&(ei[e]=new Ln.AddressLookupTableAccount({key:t,state:Ln.AddressLookupTableAccount.deserialize(n.data)})),ei};var De=require("@solana/web3.js"),Rl=ie(require("axios"));var ea=2e3,ta=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 Rl.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}=Zr(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...n),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(De.SystemProgram.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new De.PublicKey(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(Y.TransferTip),!0):!1}async calComputeBudget({config:e,defaultIns:t}){try{let n=e||await this.getComputeBudgetConfig();if(this.addCustomComputeBudget(n))return;t&&this.instructions.unshift(...t)}catch{t&&this.instructions.unshift(...t)}}addInstruction({instructions:e=[],endInstructions:t=[],signers:n=[],instructionTypes:o=[],endInstructionTypes:i=[],lookupTableAddress:r=[]}){return this.instructions.push(...e),this.endInstructions.push(...t),this.signers.push(...n),this.instructionTypes.push(...o),this.endInstructionTypes.push(...i),this.lookupTableAddress.push(...r.filter(a=>a!==De.PublicKey.default.toString())),this}async versionBuild({txVersion:e,extInfo:t,lookupTableAddress:n}){return e===0?await this.buildV0(E(N({},t||{}),{lookupTableAddress:n})):this.build(t)}build(e){var n;let t=new De.Transaction;return this.allInstructions.length&&t.add(...this.allInstructions),t.feePayer=this.feePayer,((n=this.owner)==null?void 0:n.signer)&&!this.signers.some(o=>o.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer),{builder:this,transaction:t,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async o=>{var c;let{recentBlockHash:i,skipPreflight:r=!0,sendAndConfirm:a,notSendToRpc:s}=o||{},u=i!=null?i:await Ho(this.connection,this.blockhashCommitment);if(t.recentBlockhash=u,this.signers.length&&t.sign(...this.signers),Io([t]),(c=this.owner)!=null&&c.isKeyPair)return{txId:a?await(0,De.sendAndConfirmTransaction)(this.connection,t,this.signers.find(p=>p.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:r}):await this.connection.sendRawTransaction(t.serialize(),{skipPreflight:r}),signedTx:t};if(this.signAllTransactions){let d=await this.signAllTransactions([t]);if(this.signers.length)for(let p of d)try{p.sign(...this.signers)}catch{}return{txId:s?"":await this.connection.sendRawTransaction(d[0].serialize(),{skipPreflight:r}),signedTx:d[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:o}=this.build(n),i=t.filter(c=>c.transaction.instructions.length>0),r=[o,...i.map(c=>c.transaction)],a=[this.signers,...i.map(c=>c.signers)],s=[...this.instructionTypes,...i.map(c=>c.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&a.forEach(c=>{c.some(d=>d.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:r,signers:a,instructionTypes:s,execute:async c=>{var g;let{sequentially:d,onTxUpdate:p,skipTxCount:m=0,recentBlockHash:f,skipPreflight:y=!0}=c||{},b=f!=null?f:await Ho(this.connection,this.blockhashCommitment);if((g=this.owner)!=null&&g.isKeyPair){if(d){let P=[],k=0;for(let I of r){if(++k,k<=m)continue;let A=await(0,De.sendAndConfirmTransaction)(this.connection,I,this.signers.find(h=>h.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:y});P.push(A)}return{txIds:P,signedTxs:r}}return{txIds:await await Promise.all(r.map(async P=>(P.recentBlockhash=b,await this.connection.sendRawTransaction(P.serialize(),{skipPreflight:y})))),signedTxs:r}}if(this.signAllTransactions){let P=r.map((I,A)=>(I.recentBlockhash=b,a[A].length&&I.sign(...a[A]),I));Io(P);let k=await this.signAllTransactions(P);if(d){let I=0,A=[],h=async()=>{if(!k[I])return;let B=await this.connection.sendRawTransaction(k[I].serialize(),{skipPreflight:y});A.push({txId:B,status:"sent",signedTx:k[I]}),p==null||p([...A]),I++;let S=!1,K=null,x=null,C=L=>{K!==null&&clearInterval(K),x!==null&&this.connection.removeSignatureListener(x);let O=A.findIndex(R=>R.txId===B);if(O>-1){if(A[O].status==="error"||A[O].status==="success")return;A[O].status=L.err?"error":"success"}p==null||p([...A]),L.err||h()};this.loopMultiTxStatus&&(K=setInterval(async()=>{var L;if(S){clearInterval(K);return}try{let O=await this.connection.getTransaction(B,{commitment:"confirmed",maxSupportedTransactionVersion:0});O&&(S=!0,clearInterval(K),C({err:((L=O.meta)==null?void 0:L.err)||null}),console.log("tx status from getTransaction:",B))}catch(O){S=!0,clearInterval(K),console.error("getTransaction timeout:",O,B)}},ea)),x=this.connection.onSignature(B,L=>{if(S){this.connection.removeSignatureListener(x);return}S=!0,C(L)},"confirmed"),this.connection.getSignatureStatus(B)};return await h(),{txIds:A.map(B=>B.txId),signedTxs:k}}else{let I=[];for(let A=0;A<k.length;A+=1){let h=await this.connection.sendRawTransaction(k[A].serialize(),{skipPreflight:y});I.push(h)}return{txIds:I,signedTxs:k}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:n||{}}}async versionMultiBuild({extraPreBuildData:e,txVersion:t,extInfo:n}){return t===0?await this.buildV0MultiTx({extraPreBuildData:e,buildProps:n||{}}):this.buildMultiTx({extraPreBuildData:e,extInfo:n})}async buildV0(e){var y;let f=e||{},{lookupTableCache:t={},lookupTableAddress:n=[],forerunCreate:o,recentBlockhash:i}=f,r=$e(f,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),a=N(N({},this.cluster==="devnet"?await Ys(this.connection):await Xs(this.connection)),t),s=Array.from(new Set([...n,...this.lookupTableAddress])),u=[];for(let b of s)a[b]===void 0&&u.push(new De.PublicKey(b));let c=await zs({connection:this.connection,address:u});for(let[b,g]of Object.entries(c))a[b]=g;let d=o?De.PublicKey.default.toBase58():i!=null?i:await Ho(this.connection,this.blockhashCommitment),p=new De.TransactionMessage({payerKey:this.feePayer,recentBlockhash:d,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(a));((y=this.owner)==null?void 0:y.signer)&&!this.signers.some(b=>b.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let m=new De.VersionedTransaction(p);return m.sign(this.signers),{builder:this,transaction:m,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:async b=>{var I;let{skipPreflight:g=!0,sendAndConfirm:P,notSendToRpc:k}=b||{};if(Io([m]),(I=this.owner)!=null&&I.isKeyPair){let A=await this.connection.sendTransaction(m,{skipPreflight:g});return P&&await jr(this.connection,A),{txId:A,signedTx:m}}if(this.signAllTransactions){let A=await this.signAllTransactions([m]);if(this.signers.length)for(let h of A)try{h.sign(this.signers)}catch{}return{txId:k?"":await this.connection.sendTransaction(A[0],{skipPreflight:g}),signedTx:A[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:r||{}}}async buildV0MultiTx(e){var u;let{extraPreBuildData:t=[],buildProps:n}=e,{transaction:o}=await this.buildV0(n),i=t.filter(c=>c.builder.instructions.length>0),r=[o,...i.map(c=>c.transaction)],a=[this.signers,...i.map(c=>c.signers)],s=[...this.instructionTypes,...i.map(c=>c.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&a.forEach(c=>{c.some(d=>d.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),r.forEach(async(c,d)=>{c.sign(a[d])}),{builder:this,transactions:r,signers:a,instructionTypes:s,buildProps:n,execute:async c=>{var y;let{sequentially:d,onTxUpdate:p,recentBlockHash:m,skipPreflight:f=!0}=c||{};if(m&&r.forEach(b=>b.message.recentBlockhash=m),Io(r),(y=this.owner)!=null&&y.isKeyPair){if(d){let b=[];for(let g of r){let P=await this.connection.sendTransaction(g,{skipPreflight:f});await jr(this.connection,P),b.push(P)}return{txIds:b,signedTxs:r}}return{txIds:await Promise.all(r.map(async b=>await this.connection.sendTransaction(b,{skipPreflight:f}))),signedTxs:r}}if(this.signAllTransactions){let b=await this.signAllTransactions(r);if(d){let g=0,P=[],k=async()=>{if(!b[g])return;let I=await this.connection.sendTransaction(b[g],{skipPreflight:f});P.push({txId:I,status:"sent",signedTx:b[g]}),p==null||p([...P]),g++;let A=!1,h=null,B=null,S=K=>{h!==null&&clearInterval(h),B!==null&&this.connection.removeSignatureListener(B);let x=P.findIndex(C=>C.txId===I);if(x>-1){if(P[x].status==="error"||P[x].status==="success")return;P[x].status=K.err?"error":"success"}p==null||p([...P]),K.err||k()};this.loopMultiTxStatus&&(h=setInterval(async()=>{var K;if(A){clearInterval(h);return}try{let x=await this.connection.getTransaction(I,{commitment:"confirmed",maxSupportedTransactionVersion:0});x&&(A=!0,clearInterval(h),S({err:((K=x.meta)==null?void 0:K.err)||null}),console.log("tx status from getTransaction:",I))}catch(x){A=!0,clearInterval(h),console.error("getTransaction timeout:",x,I)}},ea)),B=this.connection.onSignature(I,K=>{if(A){this.connection.removeSignatureListener(B);return}A=!0,S(K)},"confirmed"),this.connection.getSignatureStatus(I)};return k(),{txIds:[],signedTxs:b}}else{let g=[];for(let P=0;P<b.length;P+=1){let k=await this.connection.sendTransaction(b[P],{skipPreflight:f});g.push(k)}return{txIds:g,signedTxs:b}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:n||{}}}async sizeCheckBuild(e){var p;let d=e||{},{splitIns:t=[],computeBudgetConfig:n}=d,o=$e(d,["splitIns","computeBudgetConfig"]),i=n?Zr(n):{instructions:[],instructionTypes:[]},r=this.signers.reduce((m,f)=>E(N({},m),{[f.publicKey.toBase58()]:f}),{}),a=[],s=[],u=[],c=0;if(this.allInstructions.forEach(m=>{let f=[...u,m],y=n?[...i.instructions,...f]:f,g=[...new Set(f.map(P=>P.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat()).values()].map(P=>new De.PublicKey(P));if(m!==t[c]&&u.length<12&&(qi({instructions:y,payer:this.feePayer,signers:g})||qi({instructions:f,payer:this.feePayer,signers:g})))u.push(m);else{if(u.length===0)throw Error("item ins too big");c+=m===t[c]?1:0,qi({instructions:n?[...i.instructions,...u]:[...u],payer:this.feePayer,signers:g})?a.push(new De.Transaction().add(...i.instructions,...u)):a.push(new De.Transaction().add(...u)),s.push(Array.from(new Set(u.map(P=>P.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat())).map(P=>r[P]).filter(P=>P!==void 0)),u=[m]}}),u.length>0){let f=[...new Set(u.map(y=>y.keys.filter(b=>b.isSigner).map(b=>b.pubkey.toString())).flat()).values()].map(y=>r[y]).filter(y=>y!==void 0);qi({instructions:n?[...i.instructions,...u]:[...u],payer:this.feePayer,signers:f.map(y=>y.publicKey)})?a.push(new De.Transaction().add(...i.instructions,...u)):a.push(new De.Transaction().add(...u)),s.push(f)}return a.forEach(m=>m.feePayer=this.feePayer),(p=this.owner)!=null&&p.signer&&s.forEach(m=>{m.some(f=>f.publicKey.equals(this.owner.publicKey))||m.push(this.owner.signer)}),{builder:this,transactions:a,signers:s,instructionTypes:this.instructionTypes,execute:async m=>{var I;let{sequentially:f,onTxUpdate:y,skipTxCount:b=0,recentBlockHash:g,skipPreflight:P=!0}=m||{},k=g!=null?g:await Ho(this.connection,this.blockhashCommitment);if(a.forEach(async(A,h)=>{A.recentBlockhash=k,s[h].length&&A.sign(...s[h])}),Io(a),(I=this.owner)!=null&&I.isKeyPair){if(f){let A=0,h=[];for(let B of a){if(++A,A<=b){h.push("tx skipped");continue}let S=await(0,De.sendAndConfirmTransaction)(this.connection,B,this.signers.find(K=>K.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:P});h.push(S)}return{txIds:h,signedTxs:a}}return{txIds:await Promise.all(a.map(async A=>await this.connection.sendRawTransaction(A.serialize(),{skipPreflight:P}))),signedTxs:a}}if(this.signAllTransactions){let A=await this.signAllTransactions(a.slice(b,a.length)),h=[...a.slice(0,b),...A];if(f){let B=0,S=[],K=async()=>{if(!h[B])return;B<b&&(S.push({txId:"",status:"success",signedTx:h[B]}),y==null||y([...S]),B++,K());let x=await this.connection.sendRawTransaction(h[B].serialize(),{skipPreflight:P});S.push({txId:x,status:"sent",signedTx:h[B]}),y==null||y([...S]),B++;let C=!1,L=null,O=null,R=F=>{L!==null&&clearInterval(L),O!==null&&this.connection.removeSignatureListener(O);let W=S.findIndex(D=>D.txId===x);if(W>-1){if(S[W].status==="error"||S[W].status==="success")return;S[W].status=F.err?"error":"success"}y==null||y([...S]),F.err||K()};this.loopMultiTxStatus&&(L=setInterval(async()=>{var F;if(C){clearInterval(L);return}try{let W=await this.connection.getTransaction(x,{commitment:"confirmed",maxSupportedTransactionVersion:0});W&&(C=!0,clearInterval(L),R({err:((F=W.meta)==null?void 0:F.err)||null}),console.log("tx status from getTransaction:",x))}catch(W){C=!0,clearInterval(L),console.error("getTransaction timeout:",W,x)}},ea)),O=this.connection.onSignature(x,F=>{if(C){this.connection.removeSignatureListener(O);return}C=!0,R(F)},"confirmed"),this.connection.getSignatureStatus(x)};return await K(),{txIds:S.map(x=>x.txId),signedTxs:h}}else{let B=[];for(let S=0;S<h.length;S+=1){let K=await this.connection.sendRawTransaction(h[S].serialize(),{skipPreflight:P});B.push(K)}return{txIds:B,signedTxs:h}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:o||{}}}async sizeCheckBuildV0(e){var I;let k=e||{},{computeBudgetConfig:t,splitIns:n=[],lookupTableCache:o={},lookupTableAddress:i=[],insCountLimit:r=12}=k,a=$e(k,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress","insCountLimit"]),s=N(N({},this.cluster==="devnet"?await Ys(this.connection):await Xs(this.connection)),o),u=Array.from(new Set([...this.lookupTableAddress,...i])),c=[];for(let A of u)s[A]===void 0&&c.push(new De.PublicKey(A));let d=await zs({connection:this.connection,address:c});for(let[A,h]of Object.entries(d))s[A]=h;let p=t?Zr(t):{instructions:[],instructionTypes:[]},m=await Ho(this.connection,this.blockhashCommitment),f=this.signers.reduce((A,h)=>E(N({},A),{[h.publicKey.toBase58()]:h}),{}),y=[],b=[],g=[],P=0;if(this.allInstructions.forEach(A=>{let h=[...g,A],B=t?[...p.instructions,...h]:h;if(A!==n[P]&&g.length<r&&(Ui({instructions:B,payer:this.feePayer,lookupTableAddressAccount:s})||Ui({instructions:h,payer:this.feePayer,lookupTableAddressAccount:s})))g.push(A);else{if(g.length===0)throw Error("item ins too big");P+=A===n[P]?1:0;let S={};for(let K of[...new Set(u)])s[K]!==void 0&&(S[K]=s[K]);if(t&&Ui({instructions:[...p.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:m})){let K=new De.TransactionMessage({payerKey:this.feePayer,recentBlockhash:m,instructions:[...p.instructions,...g]}).compileToV0Message(Object.values(s));y.push(new De.VersionedTransaction(K))}else{let K=new De.TransactionMessage({payerKey:this.feePayer,recentBlockhash:m,instructions:[...g]}).compileToV0Message(Object.values(s));y.push(new De.VersionedTransaction(K))}b.push(Array.from(new Set(g.map(K=>K.keys.filter(x=>x.isSigner).map(x=>x.pubkey.toString())).flat())).map(K=>f[K]).filter(K=>K!==void 0)),g=[A]}}),g.length>0){let h=[...new Set(g.map(B=>B.keys.filter(S=>S.isSigner).map(S=>S.pubkey.toString())).flat()).values()].map(B=>f[B]).filter(B=>B!==void 0);if(t&&Ui({instructions:[...p.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:m})){let B=new De.TransactionMessage({payerKey:this.feePayer,recentBlockhash:m,instructions:[...p.instructions,...g]}).compileToV0Message(Object.values(s));y.push(new De.VersionedTransaction(B))}else{let B=new De.TransactionMessage({payerKey:this.feePayer,recentBlockhash:m,instructions:[...g]}).compileToV0Message(Object.values(s));y.push(new De.VersionedTransaction(B))}b.push(h)}return(I=this.owner)!=null&&I.signer&&b.forEach(A=>{A.some(h=>h.publicKey.equals(this.owner.publicKey))||A.push(this.owner.signer)}),y.forEach((A,h)=>{A.sign(b[h])}),{builder:this,transactions:y,buildProps:e,signers:b,instructionTypes:this.instructionTypes,execute:async A=>{var C;let{sequentially:h,onTxUpdate:B,skipTxCount:S=0,recentBlockHash:K,skipPreflight:x=!0}=A||{};if(y.map(async(L,O)=>{b[O].length&&L.sign(b[O]),K&&(L.message.recentBlockhash=K)}),Io(y),(C=this.owner)!=null&&C.isKeyPair){if(h){let L=0,O=[];for(let R of y){if(++L,L<=S){console.log("skip tx: ",L),O.push("tx skipped");continue}let F=await this.connection.sendTransaction(R,{skipPreflight:x});await jr(this.connection,F),O.push(F)}return{txIds:O,signedTxs:y}}return{txIds:await Promise.all(y.map(async L=>await this.connection.sendTransaction(L,{skipPreflight:x}))),signedTxs:y}}if(this.signAllTransactions){let L=await this.signAllTransactions(y.slice(S,y.length)),O=[...y.slice(0,S),...L];if(h){let R=0,F=[],W=async()=>{if(!O[R])return;if(R<S){F.push({txId:"",status:"success",signedTx:O[R]}),B==null||B([...F]),R++,W();return}let D=await this.connection.sendTransaction(O[R],{skipPreflight:x});F.push({txId:D,status:"sent",signedTx:O[R]}),B==null||B([...F]),R++;let X=!1,Z=null,H=null,ne=se=>{Z!==null&&clearInterval(Z),H!==null&&this.connection.removeSignatureListener(H);let J=F.findIndex(ge=>ge.txId===D);if(J>-1){if(F[J].status==="error"||F[J].status==="success")return;F[J].status=se.err?"error":"success"}B==null||B([...F]),se.err||W()};this.loopMultiTxStatus&&(Z=setInterval(async()=>{var se;if(X){clearInterval(Z);return}try{let J=await this.connection.getTransaction(D,{commitment:"confirmed",maxSupportedTransactionVersion:0});J&&(X=!0,clearInterval(Z),ne({err:((se=J.meta)==null?void 0:se.err)||null}),console.log("tx status from getTransaction:",D))}catch(J){X=!0,clearInterval(Z),console.error("getTransaction timeout:",J,D)}},ea)),H=this.connection.onSignature(D,se=>{if(X){this.connection.removeSignatureListener(H);return}X=!0,ne(se)},"confirmed"),this.connection.getSignatureStatus(D)};return W(),{txIds:[],signedTxs:O}}else{let R=[];for(let F=0;F<O.length;F+=1){let W=await this.connection.sendTransaction(O[F],{skipPreflight:x});R.push(W)}return{txIds:R,signedTxs:O}}}throw new Error("please provide owner in keypair format or signAllTransactions function")},extInfo:a||{}}}};var Ll=require("@solana/web3.js"),Ol=ie(require("bn.js"));function tp(l){return typeof l=="object"&&l!==null&&![Je,Ee,Ll.PublicKey,Ve,Ol.default,Zt,Nt].some(e=>typeof e=="object"&&l instanceof e)}function it(l){return typeof l=="string"?Ms(l):Array.isArray(l)?l.map(e=>it(e)):tp(l)?Object.fromEntries(Object.entries(l).map(([e,t])=>[e,it(t)])):l}var Nl=ie(require("bn.js")),et=new Nl.default(1e6);var rt={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"},Ml=E(N({},rt),{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 Fl="ray_tab_hash",Hs="ray_req_hash",np=()=>{if(typeof window===void 0)return"";let l=sessionStorage.getItem(Fl);return l||(l=`ray-${Date.now()}`,sessionStorage.setItem(Fl,l)),l},na=async n=>{var o=n,{logCount:l=1e3,removeLastLog:e}=o,t=$e(o,["logCount","removeLastLog"]);if(typeof window===void 0)return new Promise(r=>r());let i=JSON.parse(localStorage.getItem(Hs)||"[]").slice(0,l-1);e&&i.pop(),new Blob([JSON.stringify(t.data)]).size>1024&&(t.data=JSON.stringify(t.data).substring(0,200)+"..."),i.unshift(E(N({},t),{time:Date.now(),session:np()}));try{localStorage.setItem(Hs,JSON.stringify(i))}catch{if(e){let r=!1,a=JSON.stringify(t.data).substring(0,100);for(i[0].data=a+(a.length>100?"...":"");!r;){i.pop();let s=JSON.stringify(t.data).substring(0,100);i[0].data=s+(s.length>100?"...":"");try{localStorage.setItem(Hs,JSON.stringify(i)),r=!0}catch{r=!1}}return new Promise(s=>s())}return na(E(N({},t),{logCount:l,removeLastLog:!0}))}};var oa=Se("Raydium_Api"),Qs=new Map,Zs=new Map;var ia=class{constructor({cluster:e,timeout:t,logRequests:n,logCount:o,urlConfigs:i}){this.cluster=e,this.urlConfigs=i||{},this.logCount=o||1e3,this.api=js.default.create({baseURL:this.urlConfigs.BASE_HOST||(this.cluster==="devnet"?Ml.BASE_HOST:rt.BASE_HOST),timeout:t}),this.api.interceptors.request.use(r=>{let{method:a,baseURL:s,url:u}=r;return oa.debug(`${a==null?void 0:a.toUpperCase()} ${s}${u}`),r},r=>(oa.error("Request failed"),Promise.reject(r))),this.api.interceptors.response.use(r=>{let{config:a,data:s,status:u}=r,{method:c,baseURL:d,url:p}=a;return n&&na({status:u,url:`${d}${p}`,params:a.params,data:s,logCount:this.logCount}),oa.debug(`${c==null?void 0:c.toUpperCase()} ${d}${p} ${u}`),s},r=>{let{config:a,response:s={}}=r,{status:u}=s,{method:c,baseURL:d,url:p}=a;return n&&na({status:u,url:`${d}${p}`,params:a.params,data:r.message,logCount:this.logCount}),oa.error(`${c.toUpperCase()} ${d}${p} ${u||r.message}`),Promise.reject(r)})}async getClmmConfigs(){return(await this.api.get(this.urlConfigs.CLMM_CONFIG||rt.CLMM_CONFIG)).data}async getClmmDynamicConfigs(){return(await this.api.get(this.urlConfigs.CLMM_DYNAMIC_CONFIG||rt.CLMM_DYNAMIC_CONFIG)).data}async getCpmmConfigs(){return(await this.api.get(this.urlConfigs.CPMM_CONFIG||rt.CPMM_CONFIG)).data}async getClmmPoolLines(e){return(await this.api.get(`${this.urlConfigs.POOL_POSITION_LINE||rt.POOL_POSITION_LINE}?id=${e}`)).data}async getBlockSlotCountForSecond(e){if(!e)return 2;let n=(await js.default.post(e,{id:"getRecentPerformanceSamples",jsonrpc:"2.0",method:"getRecentPerformanceSamples",params:[4]})).result.map(o=>o.numSlots);return n.reduce((o,i)=>o+i,0)/n.length/60}async getChainTimeOffset(){return(await this.api.get(this.urlConfigs.CHAIN_TIME||rt.CHAIN_TIME)).data}async getRpcs(){return this.api.get(this.urlConfigs.RPCS||rt.RPCS)}async getTokenList(){return(await this.api.get(this.urlConfigs.TOKEN_LIST||rt.TOKEN_LIST)).data}async getJupTokenList(){return(await this.api.get("",{baseURL:this.urlConfigs.JUP_TOKEN_LIST||rt.JUP_TOKEN_LIST})).map(t=>E(N({},t),{chainId:101,programId:t.tokenProgram,address:t.id,logoURI:t.icon,extensions:{},freeze_authority:null,permanent_delegate:null,mint_authority:t.mintAuthority||null,minted_at:Date.now().toString()}))}async getTokenInfo(e){return(await this.api.get((this.urlConfigs.MINT_INFO_ID||rt.MINT_INFO_ID)+`?mints=${e.map(n=>n.toString()).join(",")}`)).data}async getPoolList(e={}){let{type:t="all",sort:n="liquidity",order:o="desc",showFarms:i=!1,nextPageId:r,pageSize:a=100}=e;return(await this.api.get((this.urlConfigs.POOL_LIST||rt.POOL_LIST)+`?size=${a}&hasReward=${i}${t&&t!=="all"?`&poolType=${t}`:""}${n?`&sortField=${n}`:""}${o?`&sortType=${o}`:""}${r?`&nextPageId=${r}`:""}`)).data}async fetchPoolById(e){let{ids:t}=e;return(await this.api.get((this.urlConfigs.POOL_SEARCH_BY_ID||rt.POOL_SEARCH_BY_ID)+`?ids=${t}`)).data}async fetchPoolKeysById(e){let{idList:t}=e,n=[],o=t.filter(r=>Qs.has(r)?(n.push(Qs.get(r)),!1):!0),i=[];return o.length&&(i=(await this.api.get((this.urlConfigs.POOL_KEY_BY_ID||rt.POOL_KEY_BY_ID)+`?ids=${o.join(",")}`)).data.filter(Boolean),i.forEach(a=>{Qs.set(a.id,a)})),n.concat(i)}async fetchPoolByMints(e){let{mint1:t,mint2:n,type:o="all",sort:i,order:r="desc",nextPageId:a}=e,[s,u]=[t&&Vt(t).toBase58(),n&&n!=="undefined"?Vt(n).toBase58():""],[c,d]=u&&s>u?[u,s]:[s,u];if(!s&&!u)throw new Error("not search mints provided");return(await this.api.get((this.urlConfigs.POOL_SEARCH_MINT||rt.POOL_SEARCH_MINT)+`?size=100&mint1=${c}${d?`&mint2=${d}`:""}${o&&o!=="all"?`&poolType=${o}`:""}${i?`&sortField=${i}`:""}${r?`&sortType=${r}`:""}${a?`&nextPageId=${a}`:""}`)).data}async fetchPoolByLpMints(e){let{ids:t}=e;return(await this.api.get((this.urlConfigs.POOL_SEARCH_LP||rt.POOL_SEARCH_LP)+`?lps=${t}`)).data}async fetchFarmInfoById(e){let{ids:t}=e;return(await this.api.get((this.urlConfigs.FARM_INFO||rt.FARM_INFO)+`?ids=${t}`)).data}async fetchFarmKeysById(e){let{ids:t}=e;return(await this.api.get((this.urlConfigs.FARM_KEYS||rt.FARM_KEYS)+`?ids=${t}`)).data}async fetchAvailabilityStatus(){return(await this.api.get(this.urlConfigs.CHECK_AVAILABILITY||rt.CHECK_AVAILABILITY)).data}async fetchLaunchConfigs(){var t;if((t=Zs.get(this.cluster))!=null&&t.length)return Zs.get(this.cluster);let e=await this.api.get(this.cluster==="devnet"?"https://launch-mint-v1-devnet.raydium.io/main/configs":"https://launch-mint-v1.raydium.io/main/configs");return Zs.set(this.cluster,e.data.data),e.data.data}async fetchFarmPositions(e=""){return(await this.api.get(`${this.urlConfigs.OWNER_BASE_HOST||rt.OWNER_BASE_HOST}`+(this.urlConfigs.OWNER_STAKE_FARMS||rt.OWNER_STAKE_FARMS).replace("{owner}",e))).data}async fetchCpmmLockInfo(e){return await this.api.get(`${this.urlConfigs.CPMM_LOCK||rt.CPMM_LOCK}?id=${e.toString()}`)}};var ra="please provide owner in load() initialization or you can set by calling raydium.setOwner(owner)",vl="please provide connection in load() initialization or set it by raydium.setConnection(connection)";var Co=require("@solana/web3.js");var mt=require("@solana/spl-token");var $s=(...l)=>l.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch{return e}}).join(", "),at=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=Se(t)}createTxBuilder(e){return this.scope.checkOwner(),new ta({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($s(e))}logInfo(...e){this.logger.info($s(e))}logAndCreateError(...e){let t=$s(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};var ma=require("@solana/web3.js"),jl=ie(require("bn.js"));var dn=require("@solana/spl-token");var Qi=require("@solana/web3.js"),Ql=ie(require("bn.js"));var Zl=require("@solana/spl-token");function op(l){return l instanceof Uint8Array||l!=null&&typeof l=="object"&&l.constructor.name==="Uint8Array"}function Js(l,...e){if(!op(l))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(l.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${l.length}`)}function eu(l,e=!0){if(l.destroyed)throw new Error("Hash instance has been destroyed");if(e&&l.finished)throw new Error("Hash#digest() has already been called")}function _l(l,e){Js(l);let t=e.outputLen;if(l.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var sa=l=>new DataView(l.buffer,l.byteOffset,l.byteLength),On=(l,e)=>l<<32-e|l>>>e;var fP=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ip(l){if(typeof l!="string")throw new Error(`utf8ToBytes expected string, got ${typeof l}`);return new Uint8Array(new TextEncoder().encode(l))}function tu(l){return typeof l=="string"&&(l=ip(l)),Js(l),l}var aa=class{clone(){return this._cloneInto()}},yP={}.toString;function Vl(l){let e=n=>l().update(tu(n)).digest(),t=l();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>l(),e}function rp(l,e,t,n){if(typeof l.setBigUint64=="function")return l.setBigUint64(e,t,n);let o=BigInt(32),i=BigInt(4294967295),r=Number(t>>o&i),a=Number(t&i),s=n?4:0,u=n?0:4;l.setUint32(e+s,r,n),l.setUint32(e+u,a,n)}var El=(l,e,t)=>l&e^~l&t,Dl=(l,e,t)=>l&e^l&t^e&t,ua=class extends aa{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=sa(this.buffer)}update(e){eu(this);let{view:t,buffer:n,blockLen:o}=this;e=tu(e);let i=e.length;for(let r=0;r<i;){let a=Math.min(o-this.pos,i-r);if(a===o){let s=sa(e);for(;o<=i-r;r+=o)this.process(s,r);continue}n.set(e.subarray(r,r+a),this.pos),this.pos+=a,r+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){eu(this),_l(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:i}=this,{pos:r}=this;t[r++]=128,this.buffer.subarray(r).fill(0),this.padOffset>o-r&&(this.process(n,0),r=0);for(let d=r;d<o;d++)t[d]=0;rp(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=sa(e),s=this.outputLen;if(s%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=s/4,c=this.get();if(u>c.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<u;d++)a.setUint32(4*d,c[d],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:i,destroyed:r,pos:a}=this;return e.length=o,e.pos=a,e.finished=i,e.destroyed=r,o%t&&e.buffer.set(n),e}};var ap=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),co=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),lo=new Uint32Array(64),nu=class extends ua{constructor(){super(64,32,8,!1),this.A=co[0]|0,this.B=co[1]|0,this.C=co[2]|0,this.D=co[3]|0,this.E=co[4]|0,this.F=co[5]|0,this.G=co[6]|0,this.H=co[7]|0}get(){let{A:e,B:t,C:n,D:o,E:i,F:r,G:a,H:s}=this;return[e,t,n,o,i,r,a,s]}set(e,t,n,o,i,r,a,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=r|0,this.G=a|0,this.H=s|0}process(e,t){for(let d=0;d<16;d++,t+=4)lo[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=lo[d-15],m=lo[d-2],f=On(p,7)^On(p,18)^p>>>3,y=On(m,17)^On(m,19)^m>>>10;lo[d]=y+lo[d-7]+f+lo[d-16]|0}let{A:n,B:o,C:i,D:r,E:a,F:s,G:u,H:c}=this;for(let d=0;d<64;d++){let p=On(a,6)^On(a,11)^On(a,25),m=c+p+El(a,s,u)+ap[d]+lo[d]|0,y=(On(n,2)^On(n,13)^On(n,22))+Dl(n,o,i)|0;c=u,u=s,s=a,a=r+m|0,r=i,i=o,o=n,n=m+y|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,r=r+this.D|0,a=a+this.E|0,s=s+this.F|0,u=u+this.G|0,c=c+this.H|0,this.set(n,o,i,r,a,s,u,c)}roundClean(){lo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Wl=Vl(()=>new nu);var zl=require("@solana/web3.js"),ti=ie(require("bn.js"));var le=require("@solana/buffer-layout"),ca=le.Layout,ql=le.Structure;var ou=le.UInt;var Ul=le.u8,lt=le.u16;var Hi=le.u32;var Pt=le.s32;var Gl=le.seq;var Be=le.blob;var iu=le.bits,ru=le.offset;var So=class extends ca{constructor(t,n,o){super(t,o);this.blob=Be(t),this.signed=n}decode(t,n=0){let o=new ti.default(this.blob.decode(t,n),10,"le");return this.signed?o.fromTwos(this.span*8).clone():o}encode(t,n,o=0){return typeof t=="number"&&(t=new ti.default(t)),this.signed&&(t=t.toTwos(this.span*8)),this.blob.encode(t.toArrayLike(Buffer,"le",this.span),n,o)}},la=class extends ca{constructor(t){super(8,t);this._lower=iu(Hi(),!1),this._upper=iu(Hi(),!1)}addBoolean(t){this._lower.fields.length<32?this._lower.addBoolean(t):this._upper.addBoolean(t)}decode(t,n=0){let o=this._lower.decode(t,n),i=this._upper.decode(t,n+this._lower.span);return N(N({},o),i)}encode(t,n,o=0){return this._lower.encode(t,n,o)+this._upper.encode(t,n,o+this._lower.span)}};function V(l){return new ou(1,l)}function je(l){return new ou(4,l)}function w(l){return new So(8,!1,l)}function pe(l){return new So(16,!1,l)}function Xl(l){return new So(1,!0,l)}function ni(l){return new So(8,!0,l)}function Yl(l){return new So(16,!0,l)}var Ko=class extends ca{constructor(t,n,o,i){super(t.span,i);this.layout=t,this.decoder=n,this.encoder=o}decode(t,n){return this.decoder(this.layout.decode(t,n))}encode(t,n,o){return this.layout.encode(this.encoder(t),n,o)}getSpan(t,n){return this.layout.getSpan(t,n)}};function M(l){return new Ko(Be(32),e=>new zl.PublicKey(e),e=>e.toBuffer(),l)}function tt(l){return new Ko(Ul(),sp,up,l)}function sp(l){if(l===0)return!1;if(l===1)return!0;throw new Error("Invalid bool: "+l)}function up(l){return l?1:0}function Hl(l,e){let t=Hi("length"),n=v([t,j(l,ru(t,-t.span),"values")]);return new Ko(n,({values:o})=>o,o=>({values:o}),e)}function cp(l){let e=Hi("length"),t=v([e,Be(ru(e,-e.span),"data")]);return new Ko(t,({data:n})=>n,n=>({data:n}),l)}function Et(l){return new Ko(cp(),e=>e.toString("utf-8"),e=>Buffer.from(e,"utf-8"),l)}var au=class extends ql{decode(e,t){return super.decode(e,t)}};function v(l,e,t){return new au(l,e,t)}function j(l,e,t){let n,o=typeof e=="number"?e:(0,ti.isBN)(e)?e.toNumber():new Proxy(e,{get(i,r){if(!n){let a=Reflect.get(i,"count");n=(0,ti.isBN)(a)?a.toNumber():a,Reflect.set(i,"count",n)}return Reflect.get(i,r)},set(i,r,a){return r==="count"&&(n=a),Reflect.set(i,r,a)}});return Gl(l,o,t)}var bn=v([M("mint"),M("owner"),w("amount"),je("delegateOption"),M("delegate"),V("state"),je("isNativeOption"),w("isNative"),w("delegatedAmount"),je("closeAuthorityOption"),M("closeAuthority")]);function su({owner:l,solAccountResp:e,tokenAccountResp:t}){let n=[],o=[];for(let{pubkey:i,account:r}of t.value){let a=bn.decode(r.data),{mint:s,amount:u}=a;n.push({publicKey:i,mint:s,amount:u,isAssociated:te(l,s,r.owner).publicKey.equals(i),isNative:!1,programId:r.owner}),o.push({pubkey:i,accountInfo:a,programId:r.owner})}return e&&n.push({mint:Qi.PublicKey.default,amount:new Ql.default(String(e.lamports)),isNative:!0,programId:e.owner}),{tokenAccounts:n,tokenAccountRawInfos:o}}function st({fromPublicKey:l,programId:e=Zl.TOKEN_PROGRAM_ID,assignSeed:t}){let n=t?btoa(t).slice(0,32):Qi.Keypair.generate().publicKey.toBase58().slice(0,32);return{publicKey:lp(l,n,e),seed:n}}function lp(l,e,t){let n=Buffer.concat([l.toBuffer(),Buffer.from(e),t.toBuffer()]),o=Wl(n);return new Qi.PublicKey(o)}function da(l){let{mint:e,tokenAccount:t,owner:n,programId:o=dn.TOKEN_PROGRAM_ID}=l;return(0,dn.createInitializeAccountInstruction)(t,e,n,o)}function Dn(l){let{tokenAccount:e,payer:t,multiSigners:n=[],owner:o,programId:i=dn.TOKEN_PROGRAM_ID}=l;return(0,dn.createCloseAccountInstruction)(e,t,o,n,i)}async function jn(l){let{connection:e,amount:t,commitment:n,payer:o,owner:i,skipCloseAccount:r}=l,a=await e.getMinimumBalanceForRentExemption(bn.span,n),s=fe(t).add(new jl.default(a)),u=st({fromPublicKey:o,programId:dn.TOKEN_PROGRAM_ID});return{addresses:{newAccount:u.publicKey},signers:[],instructions:[ma.SystemProgram.createAccountWithSeed({fromPubkey:o,basePubkey:o,seed:u.seed,newAccountPubkey:u.publicKey,lamports:s.toNumber(),space:bn.span,programId:dn.TOKEN_PROGRAM_ID}),da({mint:new ma.PublicKey(ht.address),tokenAccount:u.publicKey,owner:i,programId:dn.TOKEN_PROGRAM_ID})],instructionTypes:[Y.CreateAccount,Y.InitAccount],endInstructionTypes:r?[]:[Y.CloseAccount],endInstructions:r?[]:[Dn({tokenAccount:u.publicKey,payer:o,owner:i})]}}function uu({source:l,destination:e,owner:t,amount:n,multiSigners:o=[],tokenProgram:i=dn.TOKEN_PROGRAM_ID}){return(0,dn.createTransferInstruction)(l,e,t,BigInt(String(n)),o,i)}var Zi=class extends at{constructor(t){super(t);this._tokenAccounts=[];this._tokenAccountRawInfos=[];this._accountListener=[];this._clientOwnedToken=!1;this._notSubscribeAccountChange=!1;this._accountFetchTime=0;let{tokenAccounts:n,tokenAccountRawInfos:o,notSubscribeAccountChange:i}=t;this._tokenAccounts=n||[],this._tokenAccountRawInfos=o||[],this._notSubscribeAccountChange=i!=null?i:!0,this._clientOwnedToken=!!(n||o)}get tokenAccounts(){return this._tokenAccounts}get tokenAccountRawInfos(){return this._tokenAccountRawInfos}set notSubscribeAccountChange(t){this._notSubscribeAccountChange=t}updateTokenAccount({tokenAccounts:t,tokenAccountRawInfos:n}){return t&&(this._tokenAccounts=t),n&&(this._tokenAccountRawInfos=n),this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId),this._accountChangeListenerId=void 0,this._clientOwnedToken=!0,this}addAccountChangeListener(t){return this._accountListener.push(t),this}removeAccountChangeListener(t){return this._accountListener=this._accountListener.filter(n=>n!==t),this}getAssociatedTokenAccount(t,n){return te(this.scope.ownerPubKey,t,n).publicKey}resetTokenAccounts(){this._clientOwnedToken||(this._tokenAccounts=[],this._tokenAccountRawInfos=[])}async fetchWalletTokenAccounts(t){if(this._clientOwnedToken||!(t!=null&&t.forceUpdate)&&this._tokenAccounts.length&&Date.now()-this._accountFetchTime<(this._notSubscribeAccountChange?1e3*5:1e3*60*3))return{tokenAccounts:this._tokenAccounts,tokenAccountRawInfos:this._tokenAccountRawInfos};this.scope.checkOwner();let o=N(N({},{}),t),[i,r,a]=await Promise.all([this.scope.connection.getAccountInfo(this.scope.ownerPubKey,o.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:mt.TOKEN_PROGRAM_ID},o.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:mt.TOKEN_2022_PROGRAM_ID},o.commitment)]),{tokenAccounts:s,tokenAccountRawInfos:u}=su({owner:this.scope.ownerPubKey,solAccountResp:i,tokenAccountResp:{context:r.context,value:[...r.value,...a.value]}});return this._tokenAccounts=s,this._tokenAccountRawInfos=u,this._accountFetchTime=Date.now(),this._notSubscribeAccountChange||(this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId),this._accountChangeListenerId=this.scope.connection.onAccountChange(this.scope.ownerPubKey,()=>{this.fetchWalletTokenAccounts({forceUpdate:!0}),this._accountListener.forEach(c=>c({tokenAccounts:this._tokenAccounts,tokenAccountRawInfos:this._tokenAccountRawInfos}))},{commitment:t==null?void 0:t.commitment})),{tokenAccounts:s,tokenAccountRawInfos:u}}clearAccountChangeCkb(){this._accountChangeListenerId!==void 0&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId)}async getCreatedTokenAccount({mint:t,programId:n=mt.TOKEN_PROGRAM_ID,associatedOnly:o=!0}){await this.fetchWalletTokenAccounts();let i=this._tokenAccounts.filter(({mint:a})=>a==null?void 0:a.equals(t)).sort((a,s)=>a.amount.lt(s.amount)?1:-1),r=this.getAssociatedTokenAccount(t,n);for(let a of i){let{publicKey:s}=a;if(s&&(!o||o&&r.equals(s)))return s}}async getOrCreateTokenAccount(t){var y,b,g,P;await this.fetchWalletTokenAccounts();let{mint:n,createInfo:o,associatedOnly:i,owner:r,notUseTokenAccount:a=!1,skipCloseAccount:s=!1,checkCreateATAOwner:u=!1,assignSeed:c}=t,d=new Co.PublicKey(t.tokenProgram||mt.TOKEN_PROGRAM_ID),p=this.getAssociatedTokenAccount(n,new Co.PublicKey(d)),m=(a?[]:this.tokenAccountRawInfos).filter(k=>k.accountInfo.mint.equals(n)&&(!i||k.pubkey.equals(p))).sort((k,I)=>k.accountInfo.amount.lt(I.accountInfo.amount)?1:-1);if(o===void 0||m.length>0)return m.length>0?{account:m[0].pubkey}:{};let f={instructions:[],endInstructions:[],signers:[],instructionTypes:[],endInstructionTypes:[]};if(i){let k=(0,mt.createAssociatedTokenAccountIdempotentInstruction)(o.payer||r,p,r,n,d),I=this.tokenAccountRawInfos.find(A=>A.pubkey.equals(p));if(u){let A=await this.scope.connection.getAccountInfo(p);if(A===null)(y=f.instructions)==null||y.push(k),f.instructionTypes.push(Y.CreateATA);else if(!(A.owner.equals(d)&&mt.AccountLayout.decode(A.data).mint.equals(n)&&mt.AccountLayout.decode(A.data).owner.equals(r)))throw Error(`create ata check error -> mint: ${n.toString()}, ata: ${p.toString()}`)}else I===void 0&&(f.instructions.push(k),f.instructionTypes.push(Y.CreateATA));if(n.equals(ee)&&o.amount){let A=await jn({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:o.payer||this.scope.ownerPubKey,amount:(b=o.amount)!=null?b:0,skipCloseAccount:s});f.instructions.push(...A.instructions||[]),f.endInstructions.push(...A.endInstructions||[]),f.instructionTypes.push(...A.instructionTypes||[]),f.endInstructionTypes.push(...A.endInstructionTypes||[]),o.amount&&(f.instructions.push(uu({source:A.addresses.newAccount,destination:p,owner:this.scope.ownerPubKey,amount:o.amount,tokenProgram:mt.TOKEN_PROGRAM_ID})),f.instructionTypes.push(Y.TransferAmount))}return!s&&I===void 0&&(f.endInstructions.push(Dn({owner:r,payer:o.payer||r,tokenAccount:p,programId:d})),f.endInstructionTypes.push(Y.CloseAccount)),{account:p,instructionParams:f}}else{let k=st({fromPublicKey:r,programId:d,assignSeed:c}),I=await this.scope.connection.getMinimumBalanceForRentExemption(mt.AccountLayout.span),A=Co.SystemProgram.createAccountWithSeed({fromPubkey:r,basePubkey:r,seed:k.seed,newAccountPubkey:k.publicKey,lamports:I+Number((P=(g=o.amount)==null?void 0:g.toString())!=null?P:0),space:mt.AccountLayout.span,programId:d});return f.instructions.push(A,da({mint:n,tokenAccount:k.publicKey,owner:this.scope.ownerPubKey,programId:d})),f.instructionTypes.push(Y.CreateAccount),f.instructionTypes.push(Y.InitAccount),s||(f.endInstructions.push(Dn({owner:r,payer:o.payer||r,tokenAccount:k.publicKey,programId:d})),f.endInstructionTypes.push(Y.CloseAccount)),{account:k.publicKey,instructionParams:f}}}async checkOrCreateAta({mint:t,programId:n=mt.TOKEN_PROGRAM_ID,autoUnwrapWSOLToSOL:o}){var s;await this.fetchWalletTokenAccounts();let i=(s=this.scope.account.tokenAccounts.find(({mint:u})=>(u==null?void 0:u.toBase58())===t.toBase58()))==null?void 0:s.publicKey,r=this.scope.ownerPubKey,a={};if(!i){let u=this.getAssociatedTokenAccount(t,n),c=await(0,mt.createAssociatedTokenAccountIdempotentInstruction)(r,u,r,t,n);a.instructions=[c],a.instructionTypes=[Y.CreateATA],i=u}return o&&ee.toBase58()===t.toBase58()&&(a.endInstructions=[Dn({owner:r,payer:r,tokenAccount:i,programId:n})],a.endInstructionTypes=[Y.CloseAccount]),{pubKey:i,newInstructions:a}}async handleTokenAccount(t){let{side:n,amount:o,mint:i,programId:r=mt.TOKEN_PROGRAM_ID,tokenAccount:a,payer:s=this.scope.ownerPubKey,bypassAssociatedCheck:u,skipCloseAccount:c,checkCreateATAOwner:d}=t,p=this.getAssociatedTokenAccount(i,r);if(new Co.PublicKey(ee).equals(i)){let m=await jn({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:s,amount:o,skipCloseAccount:c});return N({tokenAccount:m.addresses.newAccount},m)}else if(!a||n==="out"&&!p.equals(a)&&!u){let m=[],f=(0,mt.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,p,this.scope.ownerPubKey,i,r);if(d){let y=await this.scope.connection.getAccountInfo(p);if(y===null)m.push(f);else if(!(y.owner.equals(mt.TOKEN_PROGRAM_ID)&&mt.AccountLayout.decode(y.data).mint.equals(i)&&mt.AccountLayout.decode(y.data).owner.equals(this.scope.ownerPubKey)))throw Error(`create ata check error -> mint: ${i.toString()}, ata: ${p.toString()}`)}else m.push(f);return{tokenAccount:p,instructions:m,instructionTypes:[Y.CreateATA]}}return{tokenAccount:a}}async processTokenAccount(t){let{mint:n,programId:o=mt.TOKEN_PROGRAM_ID,amount:i,useSOLBalance:r,handleTokenAccount:a,feePayer:s}=t,u,c=this.createTxBuilder(s);if(n.equals(new Co.PublicKey(ee))&&r){let d=await this.handleTokenAccount({side:"in",amount:i||0,mint:n,bypassAssociatedCheck:!0,programId:o}),{tokenAccount:m}=d,f=$e(d,["tokenAccount"]);u=m,c.addInstruction(f)}else if(u=await this.getCreatedTokenAccount({mint:n,associatedOnly:!1,programId:o}),!u&&a){let p=await this.scope.account.handleTokenAccount({side:"in",amount:0,mint:n,bypassAssociatedCheck:!0,programId:o}),{tokenAccount:m}=p,f=$e(p,["tokenAccount"]);u=m,c.addInstruction(f)}return N({tokenAccount:u},c.AllTxData)}};var Ce=require("@solana/web3.js"),oc=require("@solana/spl-token");var eo=ie(require("decimal.js"));var We=require("@solana/spl-token"),z=require("@solana/web3.js"),ft=ie(require("bn.js")),Gn=ie(require("decimal.js"));var $l=require("@solana/spl-token"),Jl=require("@solana/web3.js");var pa=v([je("mintAuthorityOption"),M("mintAuthority"),w("supply"),V("decimals"),V("isInitialized"),je("freezeAuthorityOption"),M("freezeAuthority")]);var mp=async({connection:l,mint:e})=>{let t=await l.getAccountInfo(new Jl.PublicKey(e));return!t||t.data.length!==pa.span?void 0:pa.decode(t.data)},dp=({mint:l,decimals:e,programId:t=$l.TOKEN_PROGRAM_ID,logoURI:n="",priority:o=3})=>{let i=l.toBase58().substring(0,6);return{address:l.toBase58(),decimals:e,symbol:i,logoURI:n,extensions:{},chainId:101,programId:t.toString(),name:i,tags:[],priority:o}},oi=l=>new Je({mint:l.address,decimals:l.decimals,symbol:l.symbol,name:l.name}),yt=o=>{var i=o,{amount:l,isRaw:e,name:t}=i,n=$e(i,["amount","isRaw","name"]);return new Ee(new Je({mint:Vt(n.address).toBase58(),decimals:n.decimals,symbol:n.symbol,name:t}),l,e,t)};function pp(l){return l.address===Sn.address?ht:l}function fp(l){return l.address===ht.address?Sn:l}var At=o=>{var i=o,{address:l,programId:e,decimals:t}=i,n=$e(i,["address","programId","decimals"]);return N({chainId:101,address:Vt(l).toBase58(),programId:e,logoURI:"",symbol:"",name:"",decimals:t,tags:[],extensions:n.extensions||{}},n)},Nn=l=>l?E(N({},l),{transferFeeConfigAuthority:l.transferFeeConfigAuthority.toBase58(),withdrawWithheldAuthority:l.withdrawWithheldAuthority.toBase58(),withheldAmount:l.withheldAmount.toString(),olderTransferFee:E(N({},l.olderTransferFee),{epoch:l.olderTransferFee.epoch.toString(),maximumFee:l.olderTransferFee.maximumFee.toString()}),newerTransferFee:E(N({},l.newerTransferFee),{epoch:l.newerTransferFee.epoch.toString(),maximumFee:l.newerTransferFee.maximumFee.toString()})}):void 0;var de=require("@solana/spl-token"),q=require("@solana/web3.js"),ur=ie(require("bn.js"));var Oe=ie(require("bn.js")),Ne=new Oe.default(1).shln(64),Ro=64,fa=new Oe.default(1).shln(128),Mn=new Oe.default(1).shln(64).subn(1),ji=new Oe.default(1).shln(128).subn(1),pn=-443636,fn=443636,xt=new Oe.default("4295048016"),St=new Oe.default("79226673521066979257578248091"),cu=new Oe.default("59543866431248"),lu=new Oe.default("184467440737095516"),mu=new Oe.default("15793534762490258745"),du=16,$i=512,$t=60,yp=new Oe.default("18446743708227953217"),pu=[{bit:0,factor:new Oe.default("fffcb933bd6fb800",16)},{bit:1,factor:new Oe.default("fff97272373d4000",16)},{bit:2,factor:new Oe.default("fff2e50f5f657000",16)},{bit:3,factor:new Oe.default("ffe5caca7e10f000",16)},{bit:4,factor:new Oe.default("ffcb9843d60f7000",16)},{bit:5,factor:new Oe.default("ff973b41fa98e800",16)},{bit:6,factor:new Oe.default("ff2ea16466c9b000",16)},{bit:7,factor:new Oe.default("fe5dee046a9a3800",16)},{bit:8,factor:new Oe.default("fcbe86c7900bb000",16)},{bit:9,factor:new Oe.default("f987a7253ac65800",16)},{bit:10,factor:new Oe.default("f3392b0822bb6000",16)},{bit:11,factor:new Oe.default("e7159475a2caf000",16)},{bit:12,factor:new Oe.default("d097f3bdfd2f2000",16)},{bit:13,factor:new Oe.default("a9f746462d9f8000",16)},{bit:14,factor:new Oe.default("70d869a156f31c00",16)},{bit:15,factor:new Oe.default("31be135f97ed3200",16)},{bit:16,factor:new Oe.default("9aa508b5b85a500",16)},{bit:17,factor:new Oe.default("5d6af8dedc582c",16)},{bit:18,factor:new Oe.default("2216e584f5fa",16)}],Wn=1e6,bp=1e5,ya=(n=>(n[n.FromInput=0]="FromInput",n[n.TokenOnlyA=1]="TokenOnlyA",n[n.TokenOnlyB=2]="TokenOnlyB",n))(ya||{}),gp=1e3,Ji=1e5,ii=1e4,fu=1e4,yu=1e5,Pp=60,ri=3,bu=100,Ap=15,gu=10,Pu=100,Lo=14,em=(r=>(r[r.OpenPositionOrIncreaseLiquidity=0]="OpenPositionOrIncreaseLiquidity",r[r.DecreaseLiquidity=1]="DecreaseLiquidity",r[r.CollectFee=2]="CollectFee",r[r.CollectReward=3]="CollectReward",r[r.Swap=4]="Swap",r[r.LimitOrder=5]="LimitOrder",r))(em||{}),tm=(t=>(t[t.Enable=0]="Enable",t[t.Disable=1]="Disable",t))(tm||{}),nm=(o=>(o[o.Uninitialized=0]="Uninitialized",o[o.Initialized=1]="Initialized",o[o.Opening=2]="Opening",o[o.Ended=3]="Ended",o))(nm||{}),om=(i=>(i[i.TradeFeeRate=0]="TradeFeeRate",i[i.ProtocolFeeRate=1]="ProtocolFeeRate",i[i.FundFeeRate=2]="FundFeeRate",i[i.NewOwner=3]="NewOwner",i[i.NewFundOwner=4]="NewFundOwner",i))(om||{}),im=(o=>(o[o.UpdateOperationOwner=0]="UpdateOperationOwner",o[o.RemoveOperationOwner=1]="RemoveOperationOwner",o[o.UpdateWhitelistMint=2]="UpdateWhitelistMint",o[o.RemoveWhitelistMint=3]="RemoveWhitelistMint",o))(im||{}),$=new Oe.default(0),dt=new Oe.default(1),wp=new Oe.default(-1),er={tvl:0,volumeQuote:0,mintAmountA:0,mintAmountB:0,rewardDefaultInfos:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0,day:{volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[0]},week:{volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[0]},month:{volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[0]},pooltype:[]};function kp(l){switch(l){case 0:return"0 (FromInput - fee from input token)";case 1:return"1 (Token0Only - fee from token0)";case 2:return"2 (Token1Only - fee from token1)";default:return`${l} (unknown)`}}var Tp=2,hp=new Oe.default("18446744073700000000");var ba=v([Be(8),V("bump"),lt("index"),M("owner"),je("protocolFeeRate"),je("tradeFeeRate"),lt("tickSpacing"),je("fundFeeRate"),j(je(),1),M("fundOwner"),j(w(),3)]),rm=v([je("blockTimestamp"),ni("tickCumulative"),j(w(),4)]),Au=v([Be(8),tt("initialized"),w("recentEpoch"),lt("observationIndex"),M("poolId"),j(rm,bu,"observations"),j(w(),4)]),am=v([lt("filterPeriod"),lt("decayPeriod"),lt("reductionFactor"),je("dynamicFeeControl"),je("maxVolatilityAccumulator"),Pt("tickSpacingIndexReference"),je("volatilityReference"),je("volatilityAccumulator"),w("lastUpdateTimestamp"),j(V(),46)]),sm=v([V("state"),w("openTime"),w("endTime"),w("lastUpdateTime"),pe("emissionsPerSecondX64"),w("totalEmissioned"),w("claimed"),M("mint"),M("vault"),M("creator"),pe("growthGlobalX64")]),mo=v([Be(8),V("bump"),M("configId"),M("creator"),M("mintA"),M("mintB"),M("vaultA"),M("vaultB"),M("observationId"),V("mintDecimalsA"),V("mintDecimalsB"),lt("tickSpacing"),pe("liquidity"),pe("sqrtPriceX64"),Pt("tickCurrent"),je(),pe("feeGrowthGlobalX64A"),pe("feeGrowthGlobalX64B"),w("protocolFeesTokenA"),w("protocolFeesTokenB"),j(pe(),4),V("status"),V("feeOn"),Be(6),j(sm,ri,"rewardInfos"),Be(8*16,"tickArrayBitmap"),j(w(),4),w("fundFeesTokenA"),w("fundFeesTokenB"),w("startTime"),w("recentEpoch"),am.replicate("dynamicFeeInfo"),j(w(),46)]),um=v([pe("growthInsideLastX64"),w("rewardAmountOwed")]),tr=v([Be(8),V("bump"),M("nftMint"),M("poolId"),Pt("tickLower"),Pt("tickUpper"),pe("liquidity"),pe("feeGrowthInsideLastX64A"),pe("feeGrowthInsideLastX64B"),w("tokenFeesOwedA"),w("tokenFeesOwedB"),j(um,ri,"rewardInfos"),w("recentEpoch"),j(w(),7)]),Ip=v([Be(8),V("bump"),M("poolId"),Pt("tickLower"),Pt("tickUpper"),pe("liquidity"),pe("feeGrowthInsideLastX64A"),pe("feeGrowthInsideLastX64B"),w("tokenFeesOwedA"),w("tokenFeesOwedB"),j(pe(),ri,"rewardGrowthInside"),w("recentEpoch"),j(w(),7)]),cm=v([Pt("tick"),Yl("liquidityNet"),pe("liquidityGross"),pe("feeGrowthOutsideX64A"),pe("feeGrowthOutsideX64B"),j(pe(),ri,"rewardGrowthsOutsideX64"),w("orderPhase"),w("ordersAmount"),w("partFilledOrdersRemaining"),pe("unfilledRatioX64"),j(je(),3)]),Oo=v([Be(8),M("poolId"),Pt("startTickIndex"),j(cm,$t,"ticks"),V("initializedTickCount"),w("recentEpoch"),j(V(),107)]),wu=v([Be(8),V("bump"),j(M(),gu,"operationOwners"),j(M(),Pu,"whitelistMints")]),po=v([Be(8),M("poolId"),M("owner"),Pt("tick"),tt("zeroForOne"),w("orderPhase"),w("totalAmount"),w("filledAmount"),w("settleBase"),w("settleOutput"),w("openTime"),pe("unfilledRatioX64"),j(w(),4)]),nr=v([Be(8),M("poolId"),Be(8*8*Lo,"positiveTickArrayBitmap"),Be(8*8*Lo,"negativeTickArrayBitmap")]),Bp=v([Be(8),lt("index"),lt("filterPeriod"),lt("decayPeriod"),lt("reductionFactor"),je("dynamicFeeControl"),je("maxVolatilityAccumulator"),j(w(),8)]),ku=v([Be(8),M("wallet"),V("nonceIndex"),w("orderNonce"),j(w(),4)]),xp=v([w(),V("bump"),M("owner"),M("poolId"),M("positionId"),M("nftAccount"),j(w(),8)]),Tu=v([Be(8),V("bump"),M("lockOwner"),M("poolId"),M("positionId"),M("nftAccount"),M("lockNftMint"),w("recentEpoch"),j(w(),8)]);var lm=ie(require("bn.js"));function or(l){let e=Buffer.alloc(2);return e.writeUInt16LE(l),e}function ga(l){let e=Buffer.alloc(2);return e.writeUInt16BE(l),e}function Pa(l){let e=Buffer.alloc(4);return e.writeInt32LE(l),e}function hu(l){let e=Buffer.alloc(4);return e.writeInt32BE(l),e}function Iu(l){return(typeof l=="number"||typeof l=="bigint")&&(l=new lm.default(l.toString())),l.toArrayLike(Buffer,"be",8)}function Bu(l){let e=new ArrayBuffer(1);return new DataView(e).setUint8(0,l),new Uint8Array(e)}var mm=Buffer.from("amm_config","utf8"),ir=Buffer.from("pool","utf8"),Aa=Buffer.from("pool_vault","utf8"),dm=Buffer.from("pool_reward_vault","utf8"),xu=Buffer.from("position","utf8"),pm=Buffer.from("tick_array","utf8"),fm=Buffer.from("operation","utf8"),ym=Buffer.from("pool_tick_array_bitmap_extension","utf8"),bm=Buffer.from("observation","utf8"),gm=Buffer.from("support_mint","utf8"),Pm=Buffer.from("dynamic_fee_config","utf8"),Am=Buffer.from("permission","utf8");function Sp(l,e){return re([mm,ga(e)],l)}function Su(l,e,t,n){return re([ir,e.toBuffer(),t.toBuffer(),n.toBuffer()],l)}function Ku(l,e){return re([Am,e.toBuffer()],l)}function Cu(l,e,t,n,o){return re([ir,e.toBuffer(),t.toBuffer(),n.toBuffer(),or(o)],l)}function an(l,e,t){return re([Aa,e.toBuffer(),t.toBuffer()],l)}function Ru(l,e,t){return re([dm,e.toBuffer(),t.toBuffer()],l)}function ve(l,e,t){return re([pm,e.toBuffer(),hu(t)],l)}function gn(l,e,t,n){return re([xu,e.toBuffer(),Pa(t),Pa(n)],l)}function sn(l,e){return re([xu,e.toBuffer()],l)}function qn(l){return re([Buffer.from("metadata","utf8"),Kn.toBuffer(),l.toBuffer()],Kn)}function ai(l){return re([fm],l)}function He(l,e){return re([ym,e.toBuffer()],l)}function wa(l,e){return re([bm,e.toBuffer()],l)}function fo(l,e){return re([gm,e.toBuffer()],l)}function Lu(l,e,t,n){return re([e.toBuffer(),t.toBuffer(),Iu(n)],l)}function Kp(l,e){return re([Pm,ga(e)],l)}function Ou(l,e,t){return re([e.toBuffer(),Bu(t)],l)}var Nu=Buffer.from("locked_position","utf8");function ka(l,e){return re([Nu,e.toBuffer()],l)}function No(l,e){return re([Nu,e.toBuffer()],l)}var Im=require("js-sha256");var Pn=ie(require("bn.js")),Ta=ie(require("decimal.js"));function ha(l){return new Pn.default(1).shln(l).subn(1)}function Cp(l,e,t){let n=l.add(e),o=ha(t);if(n.gt(o))throw new Error(`Addition overflow: result exceeds ${t} bits`);return n}function Rp(l,e){if(l.lt(e))throw new Error("Subtraction underflow");return l.sub(e)}function Lp(l,e,t){let n=l.mul(e),o=ha(t);if(n.gt(o))throw new Error(`Multiplication overflow: result exceeds ${t} bits`);return n}function Op(l,e){let t=l.mul(e),n=t.and(ha(128)),o=t.shrn(128);return[n,o]}function ze(l,e,t){if(t.isZero())throw new Error("Division by zero");return l.mul(e).div(t)}function Qe(l,e,t){if(t.isZero())throw new Error("Division by zero");let n=l.mul(e),o=n.div(t);return n.mod(t).isZero()?o:o.addn(1)}function Np(l,e,t,n){return n?Qe(l,e,t):ze(l,e,t)}function rr(l,e){return l.div(e).add(l.mod(e).isZero()?$:dt)}function Mp(l,e){let t=l.add(e);return t.gt(ji)?ji:t}function Fp(l,e){return l.gt(e)?l.sub(e):new Pn.default(0)}function vp(l,e){let t=l.mul(e);if(t.gt(ji))throw new Error("U128 multiplication overflow");return t}var _p=new Pn.default(1).shln(256).subn(1);function Vp(l,e,t){if(t.isZero())throw new Error("Division by zero");return l.mul(e).div(t)}function Ep(l,e,t){if(t.isZero())throw new Error("Division by zero");let n=l.mul(e),o=n.div(t);return n.mod(t).isZero()?o:o.addn(1)}function Mu(l){return l.isZero()?-1:l.bitLength()-1}function Dp(l){if(l.isZero())return-1;let e=0,t=l.clone();for(;t.and(new Pn.default(1)).isZero();)t=t.shrn(1),e++;return e}function Wp(l,e){return l.testn(e)}function qp(l,e){return l.or(new Pn.default(1).shln(e))}function Up(l,e){return l.and(new Pn.default(1).shln(e).notn(256))}function Gp(l,e){return l.xor(new Pn.default(1).shln(e))}function zp(l){let e=new Pn.default(1).shln(127);return l.and(e).isZero()?l:l.sub(new Pn.default(1).shln(128))}function Xp(l){return l.isNeg()?l.add(new Pn.default(1).shln(128)):l}function Yp(l){return l.isNeg()?l.neg():l}function Fu(l,e){return new Ta.default(l.toString()).div(Ta.default.pow(2,64)).toDecimalPlaces(e)}function yo(l){return new Pn.default(l.mul(Ta.default.pow(2,64)).floor().toFixed())}function Dt(l,e){return l.add(fa).sub(e).mod(fa)}var wm=ie(require("bn.js"));var wt=ie(require("bn.js")),Mo=ie(require("decimal.js"));var Un=class{static scanLinearBitmap({bitmap:e,tickSpacing:t,offset:n,checkInfo:o}){let i=[],r=e.length*8,a=0,s=r-1;if(o){let d=o.tick/(t*$t)-n;o.valueType==="gte"?a=Math.max(0,Math.ceil(d)):s=Math.min(r-1,Math.floor(d))}if(a>s)return i;let u=Math.floor(a/8),c=Math.floor(s/8);for(let d=u;d<=c;d++){if(!e[d])continue;let p=d===u?a%8:0,m=d===c?s%8:7;for(let f=p;f<=m;f++)e[d]&1<<f&&i.push((d*8+f+n)*t*$t)}return i}static findPoolBitmap({bitmap:e,tickSpacing:t,checkInfo:n}){if(n){let o=Math.floor(n.tick/$t/t);if(n.valueType==="lte"&&o<-512)return[];if(n.valueType==="gte"&&o>512)return[]}return this.scanLinearBitmap({bitmap:e,tickSpacing:t,offset:-$i,checkInfo:n})}static findPositiveTickArrayBitmap({bitmap:e,tickSpacing:t,checkInfo:n}){if(n){let o=Math.floor(n.tick/$t/t);if(n.valueType==="lte"&&o<512)return[]}return this.scanLinearBitmap({bitmap:e,tickSpacing:t,offset:$i,checkInfo:n})}static findNegativeTickArrayBitmap({bitmap:e,tickSpacing:t,count:n,checkInfo:o}){let i=[];if(o){let s=Math.floor(o.tick/$t/t);if(o.valueType==="gte"&&s>=-512)return i}let r=(o==null?void 0:o.valueType)==="lte"?Math.floor(o.tick/($t*t))+7680:1/0,a=(o==null?void 0:o.valueType)==="gte"?Math.ceil(o.tick/($t*t))+7680:0;e:for(let s=0;s<Lo;s++){let u=Lo-1-s;for(let c=0;c<512;c++){let d=s*512+c;if(d>r)break e;if(d<a)continue;let p=u*64+Math.floor(c/8);if(!e[p]){c=Math.floor(c/8)*8+7;continue}if(e[p]&1<<c%8){let m=(s*512+c-7680)*$t*t;if(i.push(m),n!==void 0&&i.length>=n)break e}}}return i}static findTickArrayStartIndex({tickSpacing:e,poolBitmap:t,tickArrayBitmap:n,findInfo:o}){if(o.type==="all")return[...this.findNegativeTickArrayBitmap({tickSpacing:e,bitmap:n.negativeTickArrayBitmap}),...this.findPoolBitmap({tickSpacing:e,bitmap:t}),...this.findPositiveTickArrayBitmap({tickSpacing:e,bitmap:n.positiveTickArrayBitmap})];let i=Te.getTickArrayStartIndex(o.tickArrayCurrent,e),{count:r}=o;if(o.type==="oneForZero"){let a={tick:i,valueType:"gte"},s=[()=>this.findNegativeTickArrayBitmap({tickSpacing:e,bitmap:n.negativeTickArrayBitmap,checkInfo:a}),()=>this.findPoolBitmap({tickSpacing:e,bitmap:t,checkInfo:a}),()=>this.findPositiveTickArrayBitmap({tickSpacing:e,bitmap:n.positiveTickArrayBitmap,checkInfo:a})];return this.collectUntil(s,r)}if(o.type==="zeroForOne"){let a={tick:i,valueType:"lte"},s=[()=>this.findPositiveTickArrayBitmap({tickSpacing:e,bitmap:n.positiveTickArrayBitmap,checkInfo:a}).sort((u,c)=>c-u),()=>this.findPoolBitmap({tickSpacing:e,bitmap:t,checkInfo:a}).sort((u,c)=>c-u),()=>this.findNegativeTickArrayBitmap({tickSpacing:e,bitmap:n.negativeTickArrayBitmap,checkInfo:a}).sort((u,c)=>c-u)];return this.collectUntil(s,r)}throw new Error("find info type check error")}static collectUntil(e,t){let n=[];for(let o of e){if(t!==void 0&&n.length>=t)break;n.push(...o())}return n.slice(0,t)}static findTickArrayAddress(e){return this.findTickArrayStartIndex(e).map(t=>ve(e.programId,e.poolId,t).publicKey)}static maxTickInTickarrayBitmap(e){return e*$t*$i}},Te=class{static firstinitializedTick({data:e,zeroForOne:t}){if(t){for(let n=e.ticks.length-1;n>=0;n--)if(ae.isInitialized({data:e.ticks[n]}))return e.ticks[n]}else for(let n=0;n<e.ticks.length;n++)if(ae.isInitialized({data:e.ticks[n]}))return e.ticks[n]}static nextInitalizedTick({data:e,currentTickIndex:t,tickSpacing:n,zeroForOne:o}){if(this.getTickArrayStartIndex(t,n)!==e.startTickIndex)return;let r=Math.floor((t-e.startTickIndex)/n);if(o){for(let a=r;a>=0;a--)if(ae.isInitialized({data:e.ticks[a]}))return e.ticks[a]}else for(let a=r+1;a<$t;a++)if(ae.isInitialized({data:e.ticks[a]}))return e.ticks[a]}static getTickArrayStartIndex(e,t){let n=this.tickCount(t);return Math.floor(e/n)*n}static getTickOffsetInArray(e,t){if(e%t!=0)throw new Error("tickIndex % tickSpacing not equal 0");let n=this.getTickArrayStartIndex(e,t);return Math.floor((e-n)/t)}static tickCount(e){return $t*e}static getMinTick(e){return Math.ceil(pn/e)*e}static getMaxTick(e){return Math.floor(fn/e)*e}},ae=class{static isInitialized({data:e}){return this.hasLiquidity({data:e})||this.hasLimitOrders({data:e})}static hasLimitOrders({data:e}){return!e.ordersAmount.isZero()||!e.partFilledOrdersRemaining.isZero()}static hasLiquidity({data:e}){return!e.liquidityGross.isZero()}static isValidTick(e){return e>=pn&&e<=fn}static checkTick(e){if(!this.isValidTick(e))throw new Error(`Tick ${e} is out of range [${pn}, ${fn}]`)}static getSqrtPriceAtTick(e){this.checkTick(e);let t=Math.abs(e),n=Ne.clone();for(let{bit:o,factor:i}of pu)(t&1<<o)!==0&&(n=ze(n,i,Ne));return e>0&&(n=ze(Ne,Ne,n)),n}static getLimitOrderOutput({amountIn:e,tick:t,zeroForOne:n}){if(n){let o=ae.getPriceAtTick(t,!1);return ze(e,o,Ne)}else{let o=ae.getPriceAtTick(t,!0);return ze(e,Ne,o)}}static getLimitOrderInput({amountOut:e,tick:t,zeroForOne:n}){if(n){let o=ae.getPriceAtTick(t,!0);return Qe(e,o,Ne)}else{let o=ae.getPriceAtTick(t,!1);return Qe(e,Ne,o)}}static limitOrderUnfilledAmount({tick:e}){return e.ordersAmount.add(e.partFilledOrdersRemaining)}static matchLimitOrder({tick:e,swapAmount:t,swapDirectionZeroForOne:n,isBaseInput:o,feeRate:i,isFeeOnInput:r}){let a={amountIn:$,amountOut:$,ammFeeAmount:$},s=this.limitOrderUnfilledAmount({tick:e});if(t.isZero()||s.isZero())return a;if(o)r?(a.ammFeeAmount=Qe(t,new wt.default(i),et),a.amountIn=t.sub(a.ammFeeAmount)):a.amountIn=t,a.amountOut=this.getLimitOrderOutput({amountIn:a.amountIn,tick:e.tick,zeroForOne:n}),a.amountOut.gt(s)&&(a.amountOut=s,a.amountIn=this.getLimitOrderInput({amountOut:s,tick:e.tick,zeroForOne:!n}),r&&(a.ammFeeAmount=Qe(a.amountIn,new wt.default(i),et.sub(new wt.default(i)))));else{let d=wt.default.min(t,s);r?a.amountOut=d:a.amountOut=wt.default.min(Qe(d,et,et.sub(new wt.default(i))),s),a.amountIn=this.getLimitOrderInput({amountOut:a.amountOut,tick:e.tick,zeroForOne:!n}),r&&(a.ammFeeAmount=Qe(a.amountIn,new wt.default(i),et.sub(new wt.default(i))))}let u=$;e.partFilledOrdersRemaining.gt($)&&(u=wt.default.min(e.partFilledOrdersRemaining,a.amountOut),u.gt($)&&(e.unfilledRatioX64=ze(e.unfilledRatioX64,e.partFilledOrdersRemaining.sub(u),e.partFilledOrdersRemaining)),e.partFilledOrdersRemaining=e.partFilledOrdersRemaining.sub(u));let c=a.amountOut.sub(u);if(c.gt($)){if(!e.partFilledOrdersRemaining.isZero())throw Error("!tick.partFilledOrdersRemaining.isZero()");if(e.ordersAmount.lt(c))throw Error("InvalidLimitOrderAmount");e.orderPhase=e.orderPhase.add(dt),e.unfilledRatioX64=ze(Ne,e.ordersAmount.sub(c),e.ordersAmount),e.partFilledOrdersRemaining=e.ordersAmount.sub(c),e.ordersAmount=$}return r||(a.ammFeeAmount=Qe(a.amountOut,new wt.default(i),et),a.amountOut=a.amountOut.sub(a.ammFeeAmount)),a}static getPriceAtTick(e,t){let n=this.getSqrtPriceAtTick(e);return t?n.mul(n).add(Ne.subn(1)).div(Ne):n.mul(n).div(Ne)}static getTickAtSqrtPrice(e){if(!(e.gte(xt)&&e.lte(St)))throw Error("SqrtPriceX64");let t=Mu(e),n=t-64,o;n>=0?o=new wt.default(n).shln(32):o=new wt.default(-n).shln(32).neg();let i;t>=64?i=e.shrn(t-63):i=e.shln(63-t);let r=new wt.default(0),a=new wt.default(1).shln(63);for(let b=0;b<du&&!a.isZero();b++){i=i.mul(i);let g=i.shrn(127).toNumber();i=i.shrn(63+g),g&&(r=r.add(a)),a=a.shrn(1)}let s=r.shrn(32),c=o.add(s).mul(cu),d=c.sub(lu),p=c.add(mu),m=this.signedShrn64(d),f=this.signedShrn64(p);return m===f?m:ae.getSqrtPriceAtTick(f).lte(e)?f:m}static signedShrn64(e){if(e.isNeg()){let t=new wt.default(1).shln(64),n=e.div(t);return!e.mod(t).isZero()&&e.isNeg()?n.subn(1).toNumber():n.toNumber()}else return e.shrn(64).toNumber()}static sqrtPriceX64ToPrice(e,t,n){let o=e.mul(e),i=t-n,r=20,a=new wt.default(10).pow(new wt.default(r)),s=o.mul(a),u=new wt.default(1).shln(128),d=s.div(u).toString();for(;d.length<=r;)d="0"+d;let p=d.slice(0,-r),m=d.slice(-r),f=p+"."+m;return new Mo.default(f).mul(new Mo.default(10).pow(i))}static tickToPrice(e,t,n){let o=ae.getSqrtPriceAtTick(e);return this.sqrtPriceX64ToPrice(o,t,n)}static priceToTick(e,t,n){let i=e.div(Math.pow(10,t-n)).log().div(new Mo.default(1.0001).log()).floor();return Math.max(pn,Math.min(fn,i.toNumber()))}static priceToSqrtPriceX64(e,t,n){let r=e.div(Math.pow(10,t-n)).sqrt().mul(new Mo.default(2).pow(64));return new wt.default(r.toFixed(0))}static toTickIndex(e,t){return e>=0?e-e%t:e-e%t-(e%t!==0?t:0)}static getPriceAndTick({price:e,mintADecimals:t,mintBDecimals:n,zeroForOne:o,tickSpacing:i}){let r=e.clamp(1/10**Math.max(t,n),Number.MAX_SAFE_INTEGER);o||(r=new Mo.default(1).div(r));let a=ae.toTickIndex(ae.priceToTick(r,t,n),i),s=ae.tickToPrice(a,t,n);return{price:o?s:new Mo.default(1).div(s),tick:a}}};async function vu(l,e,t,n,o,i,r=!0){let a=[],s=He(l,t).publicKey,u=await e.getAccountInfo(s),c=Un.findTickArrayAddress({programId:l,poolId:t,poolBitmap:i,tickArrayBitmap:nr.decode(u.data),tickSpacing:o,findInfo:{type:r?"zeroForOne":"oneForZero",tickArrayCurrent:n}});return(await Lt(e,c)).forEach((p,m)=>{p&&a.push({address:c[m],value:Oo.decode(p.data)})}),a}var $n=class{static isFullyFilled({orderInfo:e}){return e.totalAmount.eq(e.filledAmount)}static getUnFilledAmount({orderInfo:e}){return e.totalAmount.sub(e.filledAmount)}static settleFilledOrder({orderInfo:e,tickInfo:t}){if(e.settleBase.isZero())return $;if(e.orderPhase.eq(t.orderPhase))return $;if(e.orderPhase.add(dt).eq(t.orderPhase)){let n=e.settleBase.mul(t.unfilledRatioX64),o=e.unfilledRatioX64,i=n.div(o),r=n.mod(o).isZero(),a=e.settleBase.sub(i);if(a.isZero())return $;let s=r?a:a.sub(dt);return ae.getLimitOrderOutput({amountIn:s,tick:t.tick,zeroForOne:e.zeroForOne}).sub(e.settleOutput)}else{if(e.orderPhase.add(new wm.default(2)).lte(t.orderPhase))return ae.getLimitOrderOutput({amountIn:e.settleBase,tick:t.tick,zeroForOne:e.zeroForOne}).sub(e.settleOutput);throw Error("invalid order phase")}}};var ar=ie(require("bn.js")),_u=ie(require("decimal.js"));var pt=class{static getDeltaAmountAUnsigned(e,t,n,o){e.gt(t)&&([e,t]=[t,e]);let i=n.shln(Ro),r=t.sub(e);if(!e.gt($))throw Error("!sqrtPriceX64A.gt(BN_ZERO)");let a=o?rr(Qe(i,r,t),e):ze(i,r,t).div(e);if(a.gt(Mn))throw Error("MaxTokenOverflow");return a}static getDeltaAmountBUnsigned(e,t,n,o){e.gt(t)&&([e,t]=[t,e]);let i=o?Qe(n,t.sub(e),Ne):ze(n,t.sub(e),Ne);if(i.gt(Mn))throw Error("MaxTokenOverflow");return i}static addDelta(e,t){if(t.isNeg()){let n=t.neg();if(e.lt(n))throw new Error("Liquidity underflow");return e.sub(n)}else return e.add(t)}static getLiquidityFromAmountA(e,t,n){if(n.isZero())return $;e.gt(t)&&([e,t]=[t,e]);let o=ze(e,t,Ne),i=t.sub(e);return ze(n,o,i)}static getLiquidityFromAmountB(e,t,n){if(n.isZero())return $;e.gt(t)&&([e,t]=[t,e]);let o=t.sub(e);return ze(n,Ne,o)}static getLiquidityFromAmounts(e,t,n,o,i){if(t.gt(n)&&([t,n]=[n,t]),e.lte(t))return this.getLiquidityFromAmountA(t,n,o);if(e.lt(n)){let r=this.getLiquidityFromAmountA(e,n,o),a=this.getLiquidityFromAmountB(t,e,i);return r.lt(a)?r:a}else return this.getLiquidityFromAmountB(t,n,i)}static getAmountsForLiquidity(e,t,n,o,i){t.gt(n)&&([t,n]=[n,t]);let r=$,a=$;return e.lte(t)?r=this.getDeltaAmountAUnsigned(t,n,o,i):e.lt(n)?(r=this.getDeltaAmountAUnsigned(e,n,o,i),a=this.getDeltaAmountBUnsigned(t,e,o,i)):a=this.getDeltaAmountBUnsigned(t,n,o,i),{amountA:r,amountB:a}}static getAmountsFromLiquidityWithSlippage(e,t,n,o,i,r,a){let{amountA:s,amountB:u}=this.getAmountsForLiquidity(e,t,n,o,r),c=i?1+a:1-a,d=new ar.default(new _u.default(s.toString()).mul(c).toFixed(0)),p=new ar.default(new _u.default(u.toString()).mul(c).toFixed(0));return{amountSlippageA:d,amountSlippageB:p}}static getLiquidityAndAmountsFromAmount({sqrtPriceCurrentX64:e,sqrtPriceLowerX64:t,sqrtPriceUpperX64:n,amountInfo:o}){let i;if(o.type==="liquidity")i=o.amount;else if(o.type==="amountA")i=e.gte(n)?$:this.getLiquidityFromAmountA(ar.default.max(e,t),n,o.amount);else if(o.type==="amountB")i=e.lte(t)?$:this.getLiquidityFromAmountB(t,ar.default.min(e,n),o.amount);else throw Error("amount info type check error");return N({liquidity:i},this.getAmountsForLiquidity(e,t,n,o.amount,!0))}};var Hp=({baseIn:l,price:e,mintADecimal:t,mintBDecimal:n,tickSpacing:o})=>{let i=ae.priceToTick(e,t,n),r=ae.toTickIndex(i,o),a=ae.tickToPrice(r,t,n);return{tick:r,price:a}};var zt=require("@solana/web3.js"),Kt=ie(require("bn.js"));var sr=require("@solana/spl-token");var Ke=ie(require("decimal.js"));var vo=ie(require("bn.js"));var bt=ie(require("bn.js"));var si=class{static getNextSqrtPriceFromAmountARoundingUp(e,t,n,o){if(n.isZero())return e;let i=t.shln(Ro);if(o){let r=n.mul(e),a=i.add(r);if(a.gte(i))return Qe(i,e,a);let s=ze(i,dt,e);return Qe(i,dt,s.add(n))}else{let r=n.mul(e);if(i.lte(r))throw new Error("Insufficient liquidity for token0 removal");let a=i.sub(r);return Qe(i,e,a)}}static getNextSqrtPriceFromAmountBRoundingDown(e,t,n,o){if(n.isZero())return e;if(o){let i=n.shln(Ro).div(t);return e.add(i)}else{let i=rr(n.shln(Ro),t);return e.sub(i)}}static getNextSqrtPriceFromInput(e,t,n,o){if(!e.gt($))throw Error("sqrtPriceX64.gt(BN_ZERO)");if(!t.gt($))throw Error("liquidity.gt(BN_ZERO)");return o?this.getNextSqrtPriceFromAmountARoundingUp(e,t,n,!0):this.getNextSqrtPriceFromAmountBRoundingDown(e,t,n,!0)}static getNextSqrtPriceFromOutput(e,t,n,o){if(!e.gt($))throw Error("sqrtPriceX64.gt(BN_ZERO)");if(!t.gt($))throw Error("liquidity.gt(BN_ZERO)");return o?this.getNextSqrtPriceFromAmountBRoundingDown(e,t,n,!1):this.getNextSqrtPriceFromAmountARoundingUp(e,t,n,!1)}};var An=class{static newValue({poolInfo:e,amountSpecified:t,zeroForOne:n,feeRate:o,blockTimestamp:i}){let r={amountSpecifiedRemaining:t,amountCalculated:$,sqrtPriceX64:e.sqrtPriceX64,tick:e.tickCurrent,feeGrowthGlobalX64:n?e.feeGrowthGlobalX64A:e.feeGrowthGlobalX64B,lpFee:$,protocolFee:$,fundFee:$,liquidity:e.liquidity,sqrtPriceNextX64:$,tickNext:0,baseFeeRate:o,tickSpacing:e.tickSpacing,tickSpacingIndex:0,dynamicFeeInfo:Fo.getDynamicFeeInfo({poolInfo:e})};return r.dynamicFeeInfo&&(r.tickSpacingIndex=ci.tickSpacingIndexFromTick(r.tick,r.tickSpacing),Fo.updateReference({dynamicFeeInfo:r.dynamicFeeInfo,tickSpacingIndex:r.tickSpacingIndex,currentTimestamp:i})),r}static getTargetPriceBasedOnNextTick({data:e,tickNext:t,zeroForOne:n,sqrtPriceLimitX64:o}){e.tickNext=t,e.tickNext<pn?e.tickNext=pn:e.tickNext>fn&&(e.tickNext=fn),e.sqrtPriceNextX64=ae.getSqrtPriceAtTick(e.tickNext);let i;if(n&&e.sqrtPriceNextX64.lt(o)||!n&&e.sqrtPriceNextX64.gt(o)?i=o:i=e.sqrtPriceNextX64,n){if(e.tick<e.tickNext)throw Error("data.tick < data.tickNext");if(e.sqrtPriceX64.lt(e.sqrtPriceNextX64))throw Error("data.sqrtPriceX64.lt(data.sqrtPriceNextX64)");if(e.sqrtPriceX64.lt(i))throw Error("data.sqrtPriceX64.lt(targetPrice)")}else{if(e.tickNext<=e.tick)throw Error("data.tickNext <= data.tick");if(e.sqrtPriceNextX64.lt(e.sqrtPriceX64))throw Error("data.sqrtPriceNextX64.lt(data.sqrtPriceX64)");if(i.lt(e.sqrtPriceX64))throw Error("targetPrice.lt(data.sqrtPriceX64)")}return i}static updateVolatilityAccumulator({state:e}){!e.dynamicFeeInfo||Fo.updateVolatilityAccumulator({state:e.dynamicFeeInfo,tickSpacingIndex:e.tickSpacingIndex})}static computeDynamicFeeRate({data:e,tickSpacing:t}){let n=e.volatilityAccumulator*t,o=n*n,i=yu*ii*ii,r=Qe(new bt.default(e.dynamicFeeControl),new bt.default(o),new bt.default(i)).toNumber();return r>Ji?Ji:r}static getTotalFeeRate({data:e}){if(e.dynamicFeeInfo){let t=this.computeDynamicFeeRate({data:e.dynamicFeeInfo,tickSpacing:e.tickSpacing}),n=e.baseFeeRate+t;return Math.min(Ji,n)}return e.baseFeeRate}static getSpacingBoundedPrice({data:e,targetPrice:t,zeroForOne:n}){if(e.dynamicFeeInfo===void 0)return{isSkipped:!0,boundedPrice:t};if(e.liquidity.isZero()||e.dynamicFeeInfo.volatilityAccumulator===e.dynamicFeeInfo.maxVolatilityAccumulator)return{isSkipped:!0,boundedPrice:t};let o=e.tickSpacing,i=n?e.tickSpacingIndex*o:(e.tickSpacingIndex+1)*o,r=Math.max(pn,Math.min(fn,i)),a=ae.getSqrtPriceAtTick(r);return n?{isSkipped:!1,boundedPrice:bt.default.max(t,a)}:{isSkipped:!1,boundedPrice:bt.default.min(t,a)}}static applySwapAmounts({state:e,amountIn:t,amountOut:n,feeAmount:o,isBaseInput:i,isFeeOnInput:r,protocolFeeRate:a,fundFeeRate:s}){let u=r?t.add(o):t;i?(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.sub(u),e.amountCalculated=e.amountCalculated.add(n)):(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.sub(n),e.amountCalculated=e.amountCalculated.add(u)),this.splitFee({state:e,feeAmount:o,protocolFeeRate:a,fundFeeRate:s})}static updateDynamicFeeIndex({state:e,zeroForOne:t,isSkippedTickSpacing:n}){if(e.dynamicFeeInfo!==void 0){if(n){let o=e.sqrtPriceX64.eq(e.sqrtPriceNextX64)?e.tickNext:e.tick,i=ci.tickSpacingIndexFromTick(o,e.tickSpacing);!t&&o%e.tickSpacing===0&&(i=i-1),e.tickSpacingIndex=i,e.dynamicFeeInfo.volatilityAccumulator!==e.dynamicFeeInfo.maxVolatilityAccumulator&&this.updateVolatilityAccumulator({state:e})}e.tickSpacingIndex+=t?-1:1}}static splitFee({state:e,feeAmount:t,protocolFeeRate:n,fundFeeRate:o}){let i=t;if(n.gt($)){let r=t.mul(n).div(new bt.default(et));e.protocolFee=e.protocolFee.add(r),i=i.sub(r)}if(o.gt($)){let r=t.mul(o).div(new bt.default(et));e.fundFee=e.fundFee.add(r),i=i.sub(r)}if(e.liquidity.gt($)){let r=ze(i,Ne,e.liquidity);e.feeGrowthGlobalX64=e.feeGrowthGlobalX64.add(r),e.lpFee=e.lpFee.add(i)}}},ui=class{static newSwapComputationResult({sqrtPriceNextX64:e}){return{sqrtPriceNextX64:e!=null?e:$,amountIn:$,amountOut:$,feeAmount:$}}static calculateAmountInRange({sqrtPriceCurrentX64:e,sqrtPriceTargetX64:t,liquidity:n,zeroForOne:o,isBaseInput:i}){if(i)try{return o?pt.getDeltaAmountAUnsigned(t,e,n,!0):pt.getDeltaAmountBUnsigned(e,t,n,!0)}catch(r){if(r.message==="MaxTokenOverflow")return null;throw r}else try{return o?pt.getDeltaAmountBUnsigned(t,e,n,!1):pt.getDeltaAmountAUnsigned(e,t,n,!1)}catch(r){if(r.message==="MaxTokenOverflow")return null;throw r}}static computeSwap(e,t,n,o,i,r,a,s){let u=this.newSwapComputationResult({});if(r){let d=s?ze(o,new bt.default(Wn-i),new bt.default(Wn)):o,p=this.calculateAmountInRange({sqrtPriceCurrentX64:e,sqrtPriceTargetX64:t,liquidity:n,zeroForOne:a,isBaseInput:r});p!==null&&(u.amountIn=p),u.sqrtPriceNextX64=p!==null&&d.gte(u.amountIn)?t:si.getNextSqrtPriceFromInput(e,n,d,a)}else{let d=s?o:Qe(o,new bt.default(Wn),new bt.default(Wn-i)),p=this.calculateAmountInRange({sqrtPriceCurrentX64:e,sqrtPriceTargetX64:t,liquidity:n,zeroForOne:a,isBaseInput:r});p!==null&&(u.amountOut=p),u.sqrtPriceNextX64=p!==null&&d.gte(u.amountOut)?t:si.getNextSqrtPriceFromOutput(e,n,d,a)}if(a){if(!u.sqrtPriceNextX64.gte(t))throw Error("!result.sqrtPriceNextX64.gte(sqrtPriceTargetX64)")}else if(!t.gte(u.sqrtPriceNextX64))throw Error("!sqrtPriceTargetX64.gte(result.sqrtPriceNextX64)");let c=t.eq(u.sqrtPriceNextX64);if(a?(c&&r||(u.amountIn=pt.getDeltaAmountAUnsigned(u.sqrtPriceNextX64,e,n,!0)),c&&!r||(u.amountOut=pt.getDeltaAmountBUnsigned(u.sqrtPriceNextX64,e,n,!1))):(c&&r||(u.amountIn=pt.getDeltaAmountBUnsigned(e,u.sqrtPriceNextX64,n,!0)),c&&!r||(u.amountOut=pt.getDeltaAmountAUnsigned(e,u.sqrtPriceNextX64,n,!1))),r)s?u.sqrtPriceNextX64.eq(t)?u.feeAmount=Qe(u.amountIn,new bt.default(i),new bt.default(Wn-i)):u.feeAmount=o.sub(u.amountIn):(u.feeAmount=Qe(u.amountOut,new bt.default(i),new bt.default(Wn)),u.amountOut=u.amountOut.sub(u.feeAmount),c||(u.amountIn=o));else if(s)u.amountOut=bt.default.min(u.amountOut,o),u.feeAmount=Qe(u.amountIn,new bt.default(i),new bt.default(Wn-i));else{u.feeAmount=Qe(u.amountOut,new bt.default(i),new bt.default(Wn));let d=u.amountOut.sub(u.feeAmount);d.gt(o)?(u.feeAmount=u.amountOut.sub(o),u.amountOut=o):u.amountOut=d}return u}};function Ia({programId:l,poolId:e,poolInfo:t,tickArrays:n,configInfo:o,tickarrayBitmapExtension:i,amountSpecified:r,sqrtPriceLimitX64:a,zeroForOne:s,isBaseInput:u,blockTimestamp:c,includeExtraTickArrays:d}){a.isZero()&&(a=s?new vo.default(xt).addn(1):new vo.default(St).subn(1));let p=0;if(n.length===0)return{allTrade:!1,amountSpecifiedRemaining:r,amountCalculated:$,feeAmount:$,sqrtPriceX64:t.sqrtPriceX64,liquidity:t.liquidity,tickCurrent:t.tickCurrent,accounts:[]};let m=d?Un.findTickArrayAddress({programId:l,poolId:e,tickSpacing:t.tickSpacing,poolBitmap:t.tickArrayBitmap,tickArrayBitmap:i,findInfo:{type:s?"oneForZero":"zeroForOne",count:2,tickArrayCurrent:t.tickCurrent}}).filter(h=>h.toString()!==n[0].address.toString()):[],f=Te.getTickArrayStartIndex(t.tickCurrent,t.tickSpacing),{firstItckArrayContainsPoolTick:y,firstValidTickArrayStartIndex:b}={firstItckArrayContainsPoolTick:n[p].value.startTickIndex===f,firstValidTickArrayStartIndex:n[p].value.startTickIndex},g=y,P=b,k=n[p],I=Jt.isFeeOnInput(t.feeOn,s),A=An.newValue({poolInfo:t,amountSpecified:r,zeroForOne:s,feeRate:o.tradeFeeRate,blockTimestamp:c});for(;!A.amountSpecifiedRemaining.isZero()&&!A.sqrtPriceX64.eq(a);){let h=(()=>{let K=Te.nextInitalizedTick({data:k.value,tickSpacing:A.tickSpacing,zeroForOne:s,currentTickIndex:A.tick});if(K!==void 0)return K;if(g){let x=n[++p];return x===void 0?void 0:(P=x.value.startTickIndex,k=x,Te.firstinitializedTick({data:x.value,zeroForOne:s}))}else return g=!0,Te.firstinitializedTick({data:k.value,zeroForOne:s})})();if(h===void 0)return{allTrade:!1,amountSpecifiedRemaining:A.amountSpecifiedRemaining,amountCalculated:A.amountCalculated,feeAmount:A.lpFee.add(A.fundFee).add(A.protocolFee),sqrtPriceX64:A.sqrtPriceX64,liquidity:A.liquidity,tickCurrent:A.tick,accounts:n.slice(0,p).map(K=>K.address)};let B=An.getTargetPriceBasedOnNextTick({data:A,tickNext:h.tick,zeroForOne:s,sqrtPriceLimitX64:a}),S=A.liquidity;do{An.updateVolatilityAccumulator({state:A});let K=An.getTotalFeeRate({data:A}),{isSkipped:x,boundedPrice:C}=An.getSpacingBoundedPrice({data:A,targetPrice:B,zeroForOne:s}),L=!A.sqrtPriceX64.eq(C),O;L?(O=ui.computeSwap(A.sqrtPriceX64,C,A.liquidity,A.amountSpecifiedRemaining,K,u,s,I),An.applySwapAmounts({state:A,amountIn:O.amountIn,amountOut:O.amountOut,feeAmount:O.feeAmount,isBaseInput:u,isFeeOnInput:I,protocolFeeRate:new vo.default(o.protocolFeeRate),fundFeeRate:new vo.default(o.fundFeeRate)})):O=ui.newSwapComputationResult({sqrtPriceNextX64:C});let R=ae.limitOrderUnfilledAmount({tick:h});if(A.sqrtPriceNextX64.eq(O.sqrtPriceNextX64)){let F=ae.matchLimitOrder({tick:h,swapAmount:A.amountSpecifiedRemaining,swapDirectionZeroForOne:s,isBaseInput:u,feeRate:K,isFeeOnInput:I});if(F.amountIn.gt($)&&An.applySwapAmounts({state:A,amountIn:F.amountIn,amountOut:F.amountOut,feeAmount:F.ammFeeAmount,isBaseInput:u,isFeeOnInput:I,protocolFeeRate:new vo.default(o.protocolFeeRate),fundFeeRate:new vo.default(o.fundFeeRate)}),ae.hasLiquidity({data:h})&&!ae.hasLimitOrders({data:h})){let W=s?h.liquidityNet.neg():h.liquidityNet;S=pt.addDelta(A.liquidity,W)}A.tick=s&&!ae.hasLimitOrders({data:h})||!s&&ae.hasLimitOrders({data:h})?A.tickNext-1:A.tickNext}else A.sqrtPriceX64.eq(O.sqrtPriceNextX64)||(A.tick=ae.getTickAtSqrtPrice(O.sqrtPriceNextX64));if(A.sqrtPriceX64=O.sqrtPriceNextX64,An.updateDynamicFeeIndex({state:A,zeroForOne:s,isSkippedTickSpacing:x}),A.amountSpecifiedRemaining.isZero()||A.sqrtPriceX64.eq(B)){let F=ae.limitOrderUnfilledAmount({tick:h});if(!A.amountSpecifiedRemaining.isZero()&&!F.eq(R)&&!F.isZero())throw Error("!limitOrderUnfilledAmountAfter.isZero()");break}}while(!0);A.liquidity=S}return{allTrade:!0,amountSpecifiedRemaining:$,amountCalculated:A.amountCalculated,feeAmount:A.lpFee.add(A.fundFee).add(A.protocolFee),sqrtPriceX64:A.sqrtPriceX64,liquidity:A.liquidity,tickCurrent:A.tick,accounts:[...m,...n.slice(0,p+1+(d?1:0)).map(h=>h.address)]}}var ci=class{static tickSpacingIndexFromTick(e,t){return Math.floor(e/t)}},Fo=class{static getDynamicFeeInfo({poolInfo:e}){if(!(e.dynamicFeeInfo.filterPeriod===0&&e.dynamicFeeInfo.decayPeriod===0&&e.dynamicFeeInfo.reductionFactor===0&&e.dynamicFeeInfo.dynamicFeeControl===0&&e.dynamicFeeInfo.maxVolatilityAccumulator===0&&e.dynamicFeeInfo.tickSpacingIndexReference===0&&e.dynamicFeeInfo.volatilityReference===0&&e.dynamicFeeInfo.volatilityAccumulator===0&&e.dynamicFeeInfo.lastUpdateTimestamp.isZero()))return e.dynamicFeeInfo}static updateReference({dynamicFeeInfo:e,tickSpacingIndex:t,currentTimestamp:n}){let o=n-e.lastUpdateTimestamp.toNumber();o<e.filterPeriod||(o<e.decayPeriod?(e.tickSpacingIndexReference=t,e.volatilityReference=Math.floor(e.volatilityAccumulator*e.reductionFactor/fu),e.lastUpdateTimestamp=new Kt.default(n)):(e.tickSpacingIndexReference=t,e.volatilityReference=0,e.lastUpdateTimestamp=new Kt.default(n)))}static updateVolatilityAccumulator({state:e,tickSpacingIndex:t}){let n=Math.abs(e.tickSpacingIndexReference-t),o=e.volatilityReference+n*ii;e.volatilityAccumulator=Math.min(o,e.maxVolatilityAccumulator)}},Jt=class{static isFeeOnInput(e,t){switch(e){case 0:return!0;case 1:return t;case 2:return!t;default:return!0}}static isFeeOnTokenA(e,t){return e.feeOn===0?t:e.feeOn===1}static isOverflowDefaultTickarrayBitmap({tickSpacing:e,tickIndexs:t}){let{maxTickBoundary:n,minTickBoundary:o}=this.tickArrayStartIndexRange({tickSpacing:e});for(let i of t){let r=Te.getTickArrayStartIndex(i,e);if(r>=n||r<o)return!0}return!1}static tickArrayStartIndexRange({tickSpacing:e}){let t=Un.maxTickInTickarrayBitmap(e),n=-t;return t>fn&&(t=Te.getTickArrayStartIndex(fn,e)+Te.tickCount(e)),n<pn&&(n=Te.getTickArrayStartIndex(pn,e)),{maxTickBoundary:t,minTickBoundary:n}}static async updatePoolRewardInfos({connection:e,apiPoolInfo:t,chainTime:n,poolLiquidity:o,rewardInfos:i}){var a,s,u;let r=[];for(let c=0;c<i.length;c++){let d=i[c],p=(u=(a=t.rewardDefaultInfos[c])==null?void 0:a.mint.programId)!=null?u:(s=await e.getAccountInfo(d.mint))==null?void 0:s.owner;if(p===void 0)throw Error("get new reward mint info error");let m=E(N({},d),{perSecond:Fu(d.emissionsPerSecondX64),remainingRewards:void 0,tokenProgramId:new zt.PublicKey(p)});if(m.mint.equals(zt.PublicKey.default)||m.totalEmissioned.eq(Mn))continue;if(n<=m.openTime.toNumber()||o.eq($)){r.push(m);continue}let f=new Kt.default(Math.min(m.endTime.toNumber(),n)),y=f.sub(m.lastUpdateTime);if(y.isZero()){r.push(m);continue}let b=Qe(y,m.emissionsPerSecondX64,Ne),g=ze(y,m.emissionsPerSecondX64,o),P,k=m.totalEmissioned.add(b);if(k.lte(Mn))P=k;else{let A=Mn.sub(m.totalEmissioned);P=Mn,g=ze(A,Ne,o)}let I=m.growthGlobalX64.add(g);r.push(E(N({},m),{growthGlobalX64:I,totalEmissioned:P,lastUpdateTime:f}))}return r}},gt=class{static getOutputAmountAndRemainAccounts(e,t,n,o,i,r,a){let s=o.toBase58()===e.mintA.address,u=Te.getTickArrayStartIndex(e.accInfo.tickCurrent,e.accInfo.tickSpacing),{allTrade:c,amountCalculated:d,feeAmount:p,sqrtPriceX64:m,accounts:f}=Ia({programId:e.programId,poolId:e.id,poolInfo:e.accInfo,tickArrays:Object.entries(n).map(y=>({address:y[1].address,value:y[1]})).filter(y=>s?y.value.startTickIndex<=u:y.value.startTickIndex>=u).sort((y,b)=>s?b.value.startTickIndex-y.value.startTickIndex:y.value.startTickIndex-b.value.startTickIndex),configInfo:e.ammConfig,tickarrayBitmapExtension:t,amountSpecified:i,sqrtPriceLimitX64:a!=null?a:$,zeroForOne:s,isBaseInput:!0,blockTimestamp:r,includeExtraTickArrays:!0});return{allTrade:c,expectedAmountOut:d,remainingAccounts:f,executionPrice:m,feeAmount:p}}static getInputAmountAndRemainAccounts(e,t,n,o,i,r,a){let s=o.toBase58()===e.mintB.address,u=Te.getTickArrayStartIndex(e.accInfo.tickCurrent,e.accInfo.tickSpacing),{allTrade:c,amountCalculated:d,feeAmount:p,sqrtPriceX64:m,accounts:f}=Ia({programId:e.programId,poolId:e.id,poolInfo:e.accInfo,tickArrays:Object.entries(n).map(y=>({address:new zt.PublicKey(y[0]),value:y[1]})).filter(y=>s?y.value.startTickIndex<=u:y.value.startTickIndex>=u).sort((y,b)=>s?b.value.startTickIndex-y.value.startTickIndex:y.value.startTickIndex-b.value.startTickIndex),configInfo:e.ammConfig,tickarrayBitmapExtension:t,amountSpecified:i,sqrtPriceLimitX64:a!=null?a:$,zeroForOne:s,isBaseInput:!1,blockTimestamp:r,includeExtraTickArrays:!0});return{allTrade:c,expectedAmountIn:d,remainingAccounts:f,executionPrice:m,feeAmount:p}}static async fetchExBitmaps({connection:e,exBitmapAddress:t,batchRequest:n}){let o=await qe(e,t.map(r=>({pubkey:r})),{batchRequest:n}),i={};for(let r of o)r.accountInfo!==null&&(i[r.pubkey.toString()]=nr.decode(r.accountInfo.data));return i}static async fetchMultiplePoolTickArrays({connection:e,poolKeys:t,batchRequest:n}){let o={},i=[];for(let s of t){let u=[...Un.findTickArrayStartIndex({tickSpacing:s.tickSpacing,poolBitmap:s.tickArrayBitmap,tickArrayBitmap:s.exBitmapInfo,findInfo:{type:"zeroForOne",count:7,tickArrayCurrent:s.tickCurrent}}),...Un.findTickArrayStartIndex({tickSpacing:s.tickSpacing,poolBitmap:s.tickArrayBitmap,tickArrayBitmap:s.exBitmapInfo,findInfo:{type:"oneForZero",count:7,tickArrayCurrent:s.tickCurrent}})];for(let c of u){let{publicKey:d}=ve(s.programId,s.id,c);o[d.toString()]===void 0&&(i.push({pubkey:d}),o[d.toString()]=s.id)}}let r=await qe(e,i,{batchRequest:n}),a={};for(let s of r){if(!s.accountInfo)continue;let u=o[s.pubkey.toString()];if(!u)continue;a[u.toString()]===void 0&&(a[u.toString()]={});let c=Oo.decode(s.accountInfo.data);a[u.toString()][c.startTickIndex]=E(N({},c),{address:s.pubkey})}return a}static computeAmountOut({poolInfo:e,tickarrayBitmapExtension:t,tickArrayCache:n,baseMint:o,epochInfo:i,amountIn:r,slippage:a,blockTimestamp:s,priceLimit:u=new Ke.default(0)}){var O;let c,d=o.toBase58()===e.mintA.address,[p,m]=d?[e.mintA.extensions.feeConfig,e.mintB.extensions.feeConfig]:[e.mintB.extensions.feeConfig,e.mintA.extensions.feeConfig];u.equals(new Ke.default(0))?c=d?xt.add(new Kt.default(1)):St.sub(new Kt.default(1)):c=ae.priceToSqrtPriceX64(u,e.mintA.decimals,e.mintB.decimals);let f=Bt(r,p,i,!1),{allTrade:y,expectedAmountOut:b,remainingAccounts:g,executionPrice:P,feeAmount:k}=gt.getOutputAmountAndRemainAccounts(e,t,n,o,f.amount.sub((O=f.fee)!=null?O:$),s,c),I=Bt(b,m,i,!1),A=ae.sqrtPriceX64ToPrice(P,e.mintA.decimals,e.mintB.decimals),h=d?A:new Ke.default(1).div(A),B=b.mul(new Kt.default(Math.floor((1-a)*1e10))).div(new Kt.default(1e10)),S=Bt(B,m,i,!1),K=d?e.currentPrice:new Ke.default(1).div(e.currentPrice),x=new Ke.default(h).sub(K).abs(),C=K,L=new Nt(new Ke.default(x).mul(10**15).toFixed(0),new Ke.default(C).mul(10**15).toFixed(0));return{allTrade:y,realAmountIn:f,amountOut:I,minAmountOut:S,expirationTime:Zn(f.expirationTime,I.expirationTime),currentPrice:e.currentPrice,executionPrice:h,priceImpact:L,fee:k,remainingAccounts:g,executionPriceX64:P}}static computeAmountOutFormat({poolInfo:e,tickarrayBitmapExtension:t,tickArrayCache:n,amountIn:o,tokenOut:i,slippage:r,epochInfo:a,blockTimestamp:s,catchLiquidityInsufficient:u=!1}){let c=i.address===e.mintB.address,[d,p]=c?[e.mintA,e.mintB]:[e.mintB,e.mintA],[m,f]=[new Je(E(N({},d),{mint:d.address,isToken2022:d.programId===sr.TOKEN_2022_PROGRAM_ID.toBase58()})),new Je(E(N({},p),{mint:p.address,isToken2022:p.programId===sr.TOKEN_2022_PROGRAM_ID.toBase58()}))],{allTrade:y,realAmountIn:b,amountOut:g,minAmountOut:P,expirationTime:k,currentPrice:I,executionPrice:A,priceImpact:h,fee:B,remainingAccounts:S,executionPriceX64:K}=gt.computeAmountOut({poolInfo:e,tickarrayBitmapExtension:t,tickArrayCache:n,baseMint:new zt.PublicKey(d.address),amountIn:o,slippage:r,epochInfo:a,catchLiquidityInsufficient:u,blockTimestamp:s}),x=E(N({},b),{amount:new Ee(m,b.amount),fee:b.fee===void 0?void 0:new Ee(m,b.fee)}),C=E(N({},g),{amount:new Ee(f,g.amount),fee:g.fee===void 0?void 0:new Ee(f,g.fee)}),L=E(N({},P),{amount:new Ee(f,P.amount),fee:P.fee===void 0?void 0:new Ee(f,P.fee)}),O=new Zt({baseToken:m,denominator:new Kt.default(10).pow(new Kt.default(20+m.decimals)),quoteToken:f,numerator:I.mul(new Ke.default(10**(20+f.decimals))).toFixed(0)}),R=new Zt({baseToken:m,denominator:new Kt.default(10).pow(new Kt.default(20+m.decimals)),quoteToken:f,numerator:A.mul(new Ke.default(10**(20+f.decimals))).toFixed(0)}),F=new Ee(m,B);return{allTrade:y,realAmountIn:x,amountOut:C,minAmountOut:L,expirationTime:k,currentPrice:O,executionPrice:R,priceImpact:h,fee:F,remainingAccounts:S,executionPriceX64:K}}static computeAmountIn({poolInfo:e,tickarrayBitmapExtension:t,tickArrayCache:n,baseMint:o,epochInfo:i,amountOut:r,slippage:a,priceLimit:s=new Ke.default(0),blockTimestamp:u}){var O;let c=o.toBase58()===e.mintA.address,d={[e.mintA.address]:e.mintA.extensions.feeConfig,[e.mintB.address]:e.mintB.extensions.feeConfig},p;s.equals(new Ke.default(0))?p=c?St.sub(new Kt.default(1)):xt.add(new Kt.default(1)):p=ae.priceToSqrtPriceX64(s,e.mintA.decimals,e.mintB.decimals);let m=Bt(r,d[o.toString()],i,!0),{allTrade:f,expectedAmountIn:y,remainingAccounts:b,executionPrice:g,feeAmount:P}=gt.getInputAmountAndRemainAccounts(e,t,n,o,m.amount.sub((O=m.fee)!=null?O:$),u,p),k=c?e.mintB.address:e.mintA.address,I=Bt(y,d[k],i,!1),A=ae.sqrtPriceX64ToPrice(g,e.mintA.decimals,e.mintB.decimals),h=c?A:new Ke.default(1).div(A),B=y.mul(new Kt.default(Math.floor((1+a)*1e10))).div(new Kt.default(1e10)),S=Bt(B,d[k],i,!0),K=c?e.currentPrice:new Ke.default(1).div(e.currentPrice),x=new Ke.default(h).sub(K).abs(),C=K,L=new Nt(new Ke.default(x).mul(10**15).toFixed(0),new Ke.default(C).mul(10**15).toFixed(0));return{allTrade:f,amountIn:I,maxAmountIn:S,realAmountOut:m,expirationTime:Zn(I.expirationTime,m.expirationTime),currentPrice:e.currentPrice,executionPrice:h,priceImpact:L,fee:P,remainingAccounts:b}}static estimateAprsForPriceRangeMultiplier({poolInfo:e,aprType:t,positionTickLowerIndex:n,positionTickUpperIndex:o}){var f,y,b;let i=e[t],r=ae.tickToPrice(n,e.mintA.decimals,e.mintB.decimals).toNumber(),a=ae.tickToPrice(o,e.mintA.decimals,e.mintB.decimals).toNumber(),s=Math.max(r,i.priceMin),c=Math.min(a,i.priceMax)-s,d=a-r,p=i.priceMax-i.priceMin,m;return c<=0?m=0:d===c?m=p/c:p===c?m=c/d:m=c/p*(c/d),{feeApr:i.feeApr*m,rewardsApr:[((f=i.rewardApr[0])!=null?f:0)*m,((y=i.rewardApr[1])!=null?y:0)*m,((b=i.rewardApr[2])!=null?b:0)*m],apr:i.apr*m}}static estimateAprsForPriceRangeDelta({poolInfo:e,poolLiquidity:t,aprType:n,mintPrice:o,liquidity:i,positionTickLowerIndex:r,positionTickUpperIndex:a,chainTime:s}){let u=n==="day"?1:n==="week"?7:n==="month"?30:0,c=e[n],d=o[Vt(e.mintA.address).toString()],p=o[Vt(e.mintB.address).toString()],m=e.mintA.decimals,f=e.mintB.decimals;if(!c||!d||!p)return{feeApr:0,rewardsApr:[0,0,0],apr:0};let y=ae.priceToSqrtPriceX64(new Ke.default(e.price),e.mintA.decimals,e.mintB.decimals),b=ae.getSqrtPriceAtTick(r),g=ae.getSqrtPriceAtTick(a),{amountSlippageA:P,amountSlippageB:k}=pt.getAmountsFromLiquidityWithSlippage(y,b,g,t,!1,!1,0),{amountSlippageA:I,amountSlippageB:A}=pt.getAmountsFromLiquidityWithSlippage(y,b,g,i,!1,!1,0),h=new Ke.default(P.toString()).div(new Ke.default(10).pow(m)).mul(d.value).add(new Ke.default(k.toString()).div(new Ke.default(10).pow(f)).mul(p.value)),B=new Ke.default(I.toString()).div(new Ke.default(10).pow(m)).mul(d.value).add(new Ke.default(A.toString()).div(new Ke.default(10).pow(f)).mul(p.value)),S=new Ke.default(1).div(h.add(B)),x=new Ke.default(c.volumeFee).mul(365).div(u).mul(S).mul(100).toNumber(),C=3600*24*365,L=e.rewardDefaultInfos.map(O=>{var W,D;let R=O.mint.decimals,F=o[O.mint.address];return s<((W=O.startTime)!=null?W:0)||s>((D=O.endTime)!=null?D:0)||!O.perSecond||!F||R===void 0?0:new Ke.default(F.value).mul(new Ke.default(O.perSecond).mul(C)).div(new Ke.default(10).pow(R)).mul(S).mul(100).toNumber()});return{feeApr:x,rewardsApr:L,apr:x+L.reduce((O,R)=>O+R,0)}}static async getLiquidityAmountOutFromAmountIn({poolInfo:e,inputA:t,tickLower:n,tickUpper:o,amount:i,slippage:r,add:a,epochInfo:s,amountHasFee:u}){var g,P;let c=ae.priceToSqrtPriceX64(new Ke.default(e.price),e.mintA.decimals,e.mintB.decimals),d=ae.getSqrtPriceAtTick(n),p=ae.getSqrtPriceAtTick(o),m=Bt(i,(g=e[t?"mintA":"mintB"].extensions)==null?void 0:g.feeConfig,s,!u),f=new Kt.default(new Ke.default(m.amount.sub((P=m.fee)!=null?P:$).toString()).toFixed(0)),y;if(c.lte(d))y=t?pt.getLiquidityFromAmountA(d,p,f):new Kt.default(0);else if(c.lte(p)){let k=pt.getLiquidityFromAmountA(c,p,f),I=pt.getLiquidityFromAmountB(d,c,f);y=t?k:I}else y=t?new Kt.default(0):pt.getLiquidityFromAmountB(d,p,f);let b=await gt.getAmountsFromLiquidity({epochInfo:s,poolInfo:e,tickLower:n,tickUpper:o,liquidity:y,slippage:r,add:a});return{liquidity:y,amountA:t?m:b.amountA,amountB:t?b.amountB:m,amountSlippageA:t?m:b.amountSlippageA,amountSlippageB:t?b.amountSlippageB:m,expirationTime:b.expirationTime}}static async getAmountsFromLiquidity({epochInfo:e,poolInfo:t,tickLower:n,tickUpper:o,liquidity:i,slippage:r,add:a}){var b,g,P,k;let s=ae.getSqrtPriceAtTick(n),u=ae.getSqrtPriceAtTick(o),c=a?1+r:1-r,d=pt.getAmountsForLiquidity(ae.priceToSqrtPriceX64(new Ke.default(t.price),t.mintA.decimals,t.mintB.decimals),s,u,i,a),[p,m]=[Bt(d.amountA,(b=t.mintA.extensions)==null?void 0:b.feeConfig,e,!0),Bt(d.amountB,(g=t.mintB.extensions)==null?void 0:g.feeConfig,e,!0)],[f,y]=[Bt(d.amountA.muln(c),(P=t.mintA.extensions)==null?void 0:P.feeConfig,e,!0),Bt(d.amountB.muln(c),(k=t.mintB.extensions)==null?void 0:k.feeConfig,e,!0)];return{liquidity:i,amountA:p,amountB:m,amountSlippageA:f,amountSlippageB:y,expirationTime:Zn(p.expirationTime,m.expirationTime)}}static async fetchComputeMultipleClmmInfo({connection:e,poolList:t,rpcDataMap:n={}}){let o=t.filter(u=>!n[u.id]).map(u=>new zt.PublicKey(u.id));(await Lt(e,o)).forEach((u,c)=>{!u||(n[o[c].toBase58()]=mo.decode(u.data))});let r=t.map(u=>He(new zt.PublicKey(u.programId),new zt.PublicKey(u.id)).publicKey),a=await gt.fetchExBitmaps({connection:e,exBitmapAddress:r,batchRequest:!1}),s={};return t.reduce((u,c)=>E(N({},u),{[c.id]:E(N({accInfo:n[c.id]},n[c.id]),{id:new zt.PublicKey(c.id),version:6,programId:new zt.PublicKey(c.programId),mintA:c.mintA,mintB:c.mintB,ammConfig:E(N({},c.config),{id:new zt.PublicKey(c.config.id),fundOwner:""}),currentPrice:new Ke.default(c.price),exBitmapAccount:He(new zt.PublicKey(c.programId),new zt.PublicKey(c.id)).publicKey,exBitmapInfo:a[He(new zt.PublicKey(c.programId),new zt.PublicKey(c.id)).publicKey.toBase58()],startTime:n[c.id].startTime.toNumber(),rewardInfos:n[c.id].rewardInfos})}),{})}static async fetchComputeClmmInfo({connection:e,poolInfo:t,rpcData:n}){return(await this.fetchComputeMultipleClmmInfo({connection:e,rpcDataMap:n?{[t.id]:n}:void 0,poolList:[t]}))[t.id]}static async fetchTickArrayInfo({connection:e,programId:t,poolId:n,tick:o,tickSpacing:i}){let r=Te.getTickArrayStartIndex(o,i),a=ve(t,n,r).publicKey,s=await e.getAccountInfo(a);if(!s)throw new Error(`tick array ${a.toBase58()} not found`);return Oo.decode(s.data)}static async fetchMultipleTickArrayInfo({connection:e,tickInfoList:t}){let n=t.map(i=>{let r=Te.getTickArrayStartIndex(i.tick,i.tickSpacing);return ve(i.programId,i.poolId,r).publicKey});return(await Lt(e,n)).map(i=>i&&Oo.decode(i.data))}},Vu={volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[]};function Eu(l,e){let t=e!=null?e:{};return E(N({},l),{type:"Concentrated",programId:l.programId.toString(),id:l.id.toString(),rewardDefaultInfos:l.rewardInfos.filter(n=>!n.mint.equals(zt.PublicKey.default)).map(n=>{var o,i;return{mint:At({address:n.mint.toBase58(),programId:sr.TOKEN_PROGRAM_ID.toBase58(),decimals:(o=t[n.mint.toBase58()].decimals)!=null?o:6}),perSecond:Number(n.emissionsPerSecondX64.divn(10**((i=t[n.mint.toBase58()].decimals)!=null?i:6)).toString()),startTime:n.openTime.toNumber(),endTime:n.endTime.toNumber()}}),rewardDefaultPoolInfos:"Clmm",price:l.currentPrice.toNumber(),mintAmountA:0,mintAmountB:0,feeRate:l.ammConfig.tradeFeeRate,openTime:l.startTime.toString(),tvl:0,day:Vu,week:Vu,month:Vu,pooltype:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0,burnPercent:0,config:E(N({},l.ammConfig),{id:l.ammConfig.id.toString(),defaultRange:0,defaultRangePoint:[]}),hasDynamicFee:!1,feeOn:"",launchMigratePool:!1,tips:[]})}var _o=ie(require("bn.js"));var Du=class{static getfeeGrowthInside(e,t,n){let o=new _o.default(0),i=new _o.default(0);e.tickCurrent>=t.tick?(o=t.feeGrowthOutsideX64A,i=t.feeGrowthOutsideX64B):(o=Dt(e.feeGrowthGlobalX64A,t.feeGrowthOutsideX64A),i=Dt(e.feeGrowthGlobalX64B,t.feeGrowthOutsideX64B));let r=new _o.default(0),a=new _o.default(0);e.tickCurrent<n.tick?(r=n.feeGrowthOutsideX64A,a=n.feeGrowthOutsideX64B):(r=Dt(e.feeGrowthGlobalX64A,n.feeGrowthOutsideX64A),a=Dt(e.feeGrowthGlobalX64B,n.feeGrowthOutsideX64B));let s=Dt(Dt(e.feeGrowthGlobalX64A,o),r),u=Dt(Dt(e.feeGrowthGlobalX64B,i),a);return{feeGrowthInsideX64A:s,feeGrowthInsideBX64:u}}static GetPositionFees(e,t,n,o){let{feeGrowthInsideX64A:i,feeGrowthInsideBX64:r}=this.getfeeGrowthInside(e,n,o),a=ze(Dt(i,t.feeGrowthInsideLastX64A),t.liquidity,Ne),s=t.tokenFeesOwedA.add(a),u=ze(Dt(r,t.feeGrowthInsideLastX64B),t.liquidity,Ne),c=t.tokenFeesOwedB.add(u);return{tokenFeeAmountA:s,tokenFeeAmountB:c}}static GetPositionRewards(e,t,n,o){let i=[],r=this.getRewardGrowthInside(e.tickCurrent,n,o,e.rewardInfos);for(let a=0;a<r.length;a++){let s=r[a],u=t.rewardInfos[a],c=Dt(s,u.growthInsideLastX64),d=ze(c,t.liquidity,Ne),p=u.rewardAmountOwed.add(d);i.push(p)}return i}static getRewardGrowthInside(e,t,n,o){let i=[];for(let r=0;r<o.length;r++){let a=new _o.default(0);t.liquidityGross.eqn(0)?a=o[r].growthGlobalX64:e<t.tick?a=Dt(o[r].growthGlobalX64,t.rewardGrowthsOutsideX64[r]):a=t.rewardGrowthsOutsideX64[r];let s=new _o.default(0);n.liquidityGross.eqn(0)||(e<n.tick?s=n.rewardGrowthsOutsideX64[r]:s=Dt(o[r].growthGlobalX64,n.rewardGrowthsOutsideX64[r])),i.push(Dt(Dt(o[r].growthGlobalX64,a),s))}return i}};function Mt(l){let e=`global:${l}`;return Buffer.from(Im.sha256.digest(e)).slice(0,8)}Au.span;var km=Se("Raydium_Clmm"),Ft={createPool:Mt("create_pool"),createCustomizablePool:Mt("create_customizable_pool"),createPermissionedPool:Mt("create_permissioned_pool"),openPositionV2:Mt("open_position_v2"),openPositionWithToken22Nft:Mt("open_position_with_token22_nft"),closePosition:Mt("close_position"),increaseLiquidityV2:Mt("increase_liquidity_v2"),decreaseLiquidityV2:Mt("decrease_liquidity_v2"),initializeReward:Mt("initialize_reward"),setRewardParams:Mt("set_reward_params"),updateRewardInfos:Mt("update_reward_infos"),collectRemainingRewards:Mt("collect_remaining_rewards"),swapV2:Mt("swap_v2"),openLimitOrder:Mt("open_limit_order"),increaseLimitOrder:Mt("increase_limit_order"),decreaseLimitOrder:Mt("decrease_limit_order"),settleLimitOrder:Mt("settle_limit_order"),closeLimitOrder:Mt("close_limit_order")},Tm=[188,37,179,131,82,150,84,73],hm=[16,72,250,198,14,162,212,19],we=class{static createPoolInstruction(e,t,n,o,i,r,a,s,u,c,d,p,m,f){let y=v([pe("sqrtPriceX64"),w("startTime")]),b=[{pubkey:n,isSigner:!0,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:It,isSigner:!1,isWritable:!1},...(f!=null?f:[]).map(k=>({pubkey:k,isSigner:!1,isWritable:!1}))],g=Buffer.alloc(y.span);y.encode({sqrtPriceX64:m,startTime:$},g);let P=Buffer.from([...Ft.createPool,...g]);return new q.TransactionInstruction({keys:b,programId:e,data:P})}static createCustomizablePoolInstruction(e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b){let g=v([pe("sqrtPriceX64"),V("collectFeeOn"),tt("enableDynamicFee")]),P=[{pubkey:n,isSigner:!0,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:It,isSigner:!1,isWritable:!1},...y.map(A=>({pubkey:A,isSigner:!1,isWritable:!1})),...b?[{pubkey:b,isSigner:!1,isWritable:!1}]:[]],k=Buffer.alloc(g.span);g.encode({sqrtPriceX64:m,collectFeeOn:f,enableDynamicFee:b!==void 0},k);let I=Buffer.from([...Ft.createCustomizablePool,...k]);return new q.TransactionInstruction({keys:P,programId:e,data:I})}static createPermissionedPoolInstruction(e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k){let I=v([pe("sqrtPriceX64"),V("collectFeeOn"),tt("enableDynamicFee"),lt("seedIndex")]),A=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:It,isSigner:!1,isWritable:!1},...P.map(S=>({pubkey:S,isSigner:!1,isWritable:!1})),...k?[{pubkey:k,isSigner:!1,isWritable:!1}]:[]],h=Buffer.alloc(I.span);I.encode({sqrtPriceX64:y,collectFeeOn:b,enableDynamicFee:k!==void 0,seedIndex:g},h);let B=Buffer.from([...Ft.createPermissionedPool,...h]);return new q.TransactionInstruction({keys:A,programId:e,data:B})}static initializeRewardInstruction(e,t,n,o,i,r,a,s,u,c,d,p){let m=v([w("openTime"),w("endTime"),pe("emissionsPerSecondX64")]),f=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:It,isSigner:!1,isWritable:!1}],y=Buffer.alloc(m.span);m.encode({openTime:c,endTime:d,emissionsPerSecondX64:p},y);let b=Buffer.from([...Ft.initializeReward,...y]);return new q.TransactionInstruction({keys:f,programId:e,data:b})}static updateRewardInfosInstruction(e,t){let n=[{pubkey:t,isSigner:!1,isWritable:!0}],o=Buffer.from([...Ft.updateRewardInfos]);return new q.TransactionInstruction({keys:n,programId:e,data:o})}static setRewardParamsInstruction(e,t,n,o,i,r,a,s,u,c,d,p){let m=v([V("rewardIndex"),pe("emissionsPerSecondX64"),w("openTime"),w("endTime")]),f=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0}],y=Buffer.alloc(m.span);m.encode({rewardIndex:u,emissionsPerSecondX64:p,openTime:c,endTime:d},y);let b=Buffer.from([...Ft.setRewardParams,...y]);return new q.TransactionInstruction({keys:f,programId:e,data:b})}static closePositionInstruction(e,t,n,o,i,r,a){let s=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:r?de.TOKEN_2022_PROGRAM_ID:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}];a&&s.push({pubkey:a,isSigner:!1,isWritable:!0});let u=Buffer.from([...Ft.closePosition]);return new q.TransactionInstruction({keys:s,programId:e,data:u})}static openPositionV2Instruction(e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k,I,A,h,B,S,K,x,C){let L=v([Pt("tickLower"),Pt("tickUpper"),Pt("tickArrayLowerStart"),Pt("tickArrayUpperStart"),pe("liquidity"),w("amountMaxA"),w("amountMaxB"),tt("withMetadata"),V("optionBaseFlag"),tt("baseFlag")]),O=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!0,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:y,isSigner:!1,isWritable:!0},{pubkey:It,isSigner:!1,isWritable:!1},{pubkey:q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:Kn,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:g,isSigner:!1,isWritable:!1},...C?[{pubkey:C,isSigner:!1,isWritable:!0}]:[]],R=Buffer.alloc(L.span);L.encode({tickLower:P,tickUpper:k,tickArrayLowerStart:I,tickArrayUpperStart:A,liquidity:h,amountMaxA:B,amountMaxB:S,withMetadata:K,optionBaseFlag:x!==null?1:0,baseFlag:x!=null?x:!1},R);let F=Buffer.from([...Ft.openPositionV2,...R]);return new q.TransactionInstruction({keys:O,programId:e,data:F})}static increaseLiquidityV2Instruction(e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k){let I=v([pe("liquidity"),w("amountMaxA"),w("amountMaxB"),V("optionBaseFlag"),tt("baseFlag")]),A=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},...k?[{pubkey:k,isSigner:!1,isWritable:!0}]:[]],h=Buffer.alloc(I.span);I.encode({liquidity:y,amountMaxA:b,amountMaxB:g,optionBaseFlag:P!==null?1:0,baseFlag:P!=null?P:!1},h);let B=Buffer.from([...Ft.increaseLiquidityV2,...h]);return new q.TransactionInstruction({keys:A,programId:e,data:B})}static decreaseLiquidityV2Instruction(e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k){let I=v([pe("liquidity"),w("amountMinA"),w("amountMinB")]),A=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:mn,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},...k?[{pubkey:k,isSigner:!1,isWritable:!0}]:[],...y.map(S=>[{pubkey:S.poolRewardVault,isSigner:!1,isWritable:!0},{pubkey:S.ownerRewardVault,isSigner:!1,isWritable:!0},{pubkey:S.rewardMint,isSigner:!1,isWritable:!1}]).flat()],h=Buffer.alloc(I.span);I.encode({liquidity:b,amountMinA:g,amountMinB:P},h);let B=Buffer.from([...Ft.decreaseLiquidityV2,...h]);return new q.TransactionInstruction({keys:A,programId:e,data:B})}static swapV2Instruction(e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g){let P=v([w("amount"),w("otherAmountThreshold"),pe("sqrtPriceLimitX64"),tt("isBaseInput")]),k=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:mn,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},...g?[{pubkey:g,isSigner:!1,isWritable:!0}]:[],...d.map(h=>({pubkey:h,isSigner:!1,isWritable:!0}))],I=Buffer.alloc(P.span);P.encode({amount:m,otherAmountThreshold:f,sqrtPriceLimitX64:y,isBaseInput:b},I);let A=Buffer.from([...Ft.swapV2,...I]);return new q.TransactionInstruction({keys:k,programId:e,data:A})}static collectRemainingRewardsInstruction(e,t,n,o,i,r,a){let s=v([V("rewardIndex")]),u=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:mn,isSigner:!1,isWritable:!1}],c=Buffer.alloc(s.span);s.encode({rewardIndex:a},c);let d=Buffer.from([...Ft.collectRemainingRewards,...c]);return new q.TransactionInstruction({keys:u,programId:e,data:d})}static openPositionWithToken22NftInstruction(e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k,I,A,h,B,S,K,x){let C=v([Pt("tickLower"),Pt("tickUpper"),Pt("tickArrayLowerStart"),Pt("tickArrayUpperStart"),pe("liquidity"),w("amountMaxA"),w("amountMaxB"),tt("withMetadata"),V("optionBaseFlag"),tt("baseFlag")]),L=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!0,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:It,isSigner:!1,isWritable:!1},{pubkey:q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:y,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},...x?[{pubkey:x,isSigner:!1,isWritable:!0}]:[]],O=Buffer.alloc(C.span);C.encode({tickLower:g,tickUpper:P,tickArrayLowerStart:k,tickArrayUpperStart:I,liquidity:A,amountMaxA:h,amountMaxB:B,withMetadata:S,optionBaseFlag:K!==null?1:0,baseFlag:K!=null?K:!1},O);let R=Buffer.from([...Ft.openPositionWithToken22Nft,...O]);return new q.TransactionInstruction({keys:L,programId:e,data:R})}static openLimitOrderInstruction(e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P){let k=v([V("nonceIndex"),tt("zeroForOne"),Pt("tickIndex"),w("amount")]),I=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:q.SystemProgram.programId,isSigner:!1,isWritable:!1},...P?[{pubkey:P,isSigner:!1,isWritable:!0}]:[]],A=Buffer.alloc(k.span);k.encode({nonceIndex:f,zeroForOne:y,tickIndex:b,amount:g},A);let h=Buffer.from([...Ft.openLimitOrder,...A]);return new q.TransactionInstruction({keys:I,programId:e,data:h})}static increaseLimitOrderInstruction(e,t,n,o,i,r,a,s,u,c){let d=v([w("amount")]),p=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1}],m=Buffer.alloc(d.span);d.encode({amount:c},m);let f=Buffer.from([...Ft.increaseLimitOrder,...m]);return new q.TransactionInstruction({keys:p,programId:e,data:f})}static decreaseLimitOrderInstruction(e,t,n,o,i,r,a,s,u,c,d,p,m,f){let y=v([w("amount"),w("amountMin")]),b=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},...f?[{pubkey:f,isSigner:!1,isWritable:!0}]:[]],g=Buffer.alloc(y.span);y.encode({amount:p,amountMin:m},g);let P=Buffer.from([...Ft.decreaseLimitOrder,...g]);return new q.TransactionInstruction({keys:b,programId:e,data:P})}static settleLimitOrderInstruction(e,t,n,o,i,r,a,s,u){let c=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1}],d=Buffer.from([...Ft.settleLimitOrder]);return new q.TransactionInstruction({keys:c,programId:e,data:d})}static closeLimitOrderInstruction(e,t,n,o){let i=[{pubkey:t,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0}],r=Buffer.from([...Ft.closeLimitOrder]);return new q.TransactionInstruction({keys:i,programId:e,data:r})}static createPoolInstructions(e){let{programId:t,owner:n,mintA:o,mintB:i,ammConfigId:r,initialPriceX64:a,extendMintAccount:s}=e,[u,c]=[new q.PublicKey(o.address),new q.PublicKey(i.address)],[d,p]=[new q.PublicKey(o.programId||de.TOKEN_PROGRAM_ID),new q.PublicKey(i.programId||de.TOKEN_PROGRAM_ID)],{publicKey:m}=Su(t,r,u,c),{publicKey:f}=wa(t,m),{publicKey:y}=an(t,m,u),{publicKey:b}=an(t,m,c),g=He(t,m).publicKey,P=[this.createPoolInstruction(t,m,n,r,f,u,y,d,c,b,p,g,a,s)];return{signers:[],instructions:P,instructionTypes:[Y.CreateAccount,Y.ClmmCreatePool],address:{poolId:m,observationId:f,exBitmapAccount:g,mintA:u,mintB:c,mintAProgram:d,mintBProgram:p,mintAVault:y,mintBVault:b},lookupTableAddress:[]}}static createPermissionedPoolInstructions(e){let{programId:t,owner:n,mintA:o,mintB:i,ammConfigId:r,initialPriceX64:a,extendMintAccount:s,payer:u,seedIndex:c}=e,[d,p]=[new q.PublicKey(o.address),new q.PublicKey(i.address)],[m,f]=[new q.PublicKey(o.programId||de.TOKEN_PROGRAM_ID),new q.PublicKey(i.programId||de.TOKEN_PROGRAM_ID)],{publicKey:y}=Cu(t,r,d,p,c),{publicKey:b}=Ku(t,u),{publicKey:g}=wa(t,y),{publicKey:P}=an(t,y,d),{publicKey:k}=an(t,y,p),I=He(t,y).publicKey,A=[this.createPoolInstruction(t,y,n,r,g,d,P,m,p,k,f,I,a,s)];return{signers:[],instructions:A,instructionTypes:[Y.CreateAccount,Y.ClmmCreatePool],address:{poolId:y,observationId:g,exBitmapAccount:I,mintA:d,mintB:p,mintAProgram:m,mintBProgram:f,mintAVault:P,mintBVault:k,permission:b},lookupTableAddress:[]}}static async openPositionInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,tickLower:o,tickUpper:i,liquidity:r,amountMaxA:a,amountMaxB:s,base:u,withMetadata:c,getEphemeralSigners:d,nft2022:p}){let m=[],[f,y]=[new q.PublicKey(e.programId),new q.PublicKey(e.id)],b;if(d)b=new q.PublicKey((await d(1))[0]);else{let x=q.Keypair.generate();m.push(x),b=x.publicKey}let g=Te.getTickArrayStartIndex(o,e.config.tickSpacing),P=Te.getTickArrayStartIndex(i,e.config.tickSpacing),{publicKey:k}=ve(f,y,g),{publicKey:I}=ve(f,y,P),{publicKey:A}=p?te(n.wallet,b,de.TOKEN_2022_PROGRAM_ID):te(n.wallet,b,de.TOKEN_PROGRAM_ID),{publicKey:h}=qn(b),{publicKey:B}=sn(f,b),{publicKey:S}=gn(f,y,o,i),K=p?this.openPositionWithToken22NftInstruction(f,n.feePayer,y,n.wallet,b,A,S,k,I,B,n.tokenAccountA,n.tokenAccountB,new q.PublicKey(t.vault.A),new q.PublicKey(t.vault.B),new q.PublicKey(e.mintA.address),new q.PublicKey(e.mintB.address),o,i,g,P,r,a,s,c==="create",u&&u==="MintA",Jt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,P]})?He(f,y).publicKey:void 0):this.openPositionV2Instruction(f,n.feePayer,y,n.wallet,b,A,h,S,k,I,B,n.tokenAccountA,n.tokenAccountB,new q.PublicKey(t.vault.A),new q.PublicKey(t.vault.B),new q.PublicKey(e.mintA.address),new q.PublicKey(e.mintB.address),o,i,g,P,r,a,s,c==="create",null,Jt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,P]})?He(f,y).publicKey:void 0);return{signers:m,instructions:[K],instructionTypes:[Y.ClmmOpenPosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[],address:{nftMint:b,tickArrayLower:k,tickArrayUpper:I,positionNftAccount:A,metadataAccount:h,personalPosition:B,protocolPosition:S}}}static async openPositionFromBaseInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,tickLower:o,tickUpper:i,base:r,baseAmount:a,otherAmountMax:s,liquidity:u,withMetadata:c,getEphemeralSigners:d,nft2022:p}){let m=[],[f,y]=[new q.PublicKey(e.programId),new q.PublicKey(e.id)],b;if(d)b=new q.PublicKey((await d(1))[0]);else{let x=q.Keypair.generate();m.push(x),b=x.publicKey}let g=Te.getTickArrayStartIndex(o,e.config.tickSpacing),P=Te.getTickArrayStartIndex(i,e.config.tickSpacing),{publicKey:k}=ve(f,y,g),{publicKey:I}=ve(f,y,P),{publicKey:A}=p?te(n.wallet,b,de.TOKEN_2022_PROGRAM_ID):te(n.wallet,b,de.TOKEN_PROGRAM_ID),{publicKey:h}=qn(b),{publicKey:B}=sn(f,b),{publicKey:S}=gn(f,y,o,i),K=p?this.openPositionWithToken22NftInstruction(f,n.feePayer,y,n.wallet,b,A,S,k,I,B,n.tokenAccountA,n.tokenAccountB,new q.PublicKey(t.vault.A),new q.PublicKey(t.vault.B),new q.PublicKey(e.mintA.address),new q.PublicKey(e.mintB.address),o,i,g,P,u,!r||r==="MintA"?a:s,!r||r==="MintA"?s:a,c==="create",r&&r==="MintA",Jt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,P]})?He(f,y).publicKey:void 0):this.openPositionV2Instruction(f,n.feePayer,y,n.wallet,b,A,h,S,k,I,B,n.tokenAccountA,n.tokenAccountB,new q.PublicKey(t.vault.A),new q.PublicKey(t.vault.B),new q.PublicKey(e.mintA.address),new q.PublicKey(e.mintB.address),o,i,g,P,$,r==="MintA"?a:s,r==="MintA"?s:a,c==="create",r==="MintA",Jt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,P]})?He(f,y).publicKey:void 0);return{address:{nftMint:b,tickArrayLower:k,tickArrayUpper:I,positionNftAccount:A,metadataAccount:h,personalPosition:B,protocolPosition:S},instructions:[K],signers:m,instructionTypes:[Y.ClmmOpenPosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static async openPositionFromLiquidityInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,tickLower:o,tickUpper:i,liquidity:r,amountMaxA:a,amountMaxB:s,base:u,withMetadata:c,getEphemeralSigners:d,nft2022:p}){let m,f=[];if(d)m=new q.PublicKey((await d(1))[0]);else{let x=q.Keypair.generate();f.push(x),m=x.publicKey}let[y,b]=[new q.PublicKey(e.programId),new q.PublicKey(e.id)],g=Te.getTickArrayStartIndex(o,e.config.tickSpacing),P=Te.getTickArrayStartIndex(i,e.config.tickSpacing),{publicKey:k}=ve(y,b,g),{publicKey:I}=ve(y,b,P),{publicKey:A}=p?te(n.wallet,m,de.TOKEN_2022_PROGRAM_ID):te(n.wallet,m,de.TOKEN_PROGRAM_ID),{publicKey:h}=qn(m),{publicKey:B}=sn(y,m),{publicKey:S}=gn(y,b,o,i),K=p?this.openPositionWithToken22NftInstruction(y,n.wallet,b,n.wallet,m,A,S,k,I,B,n.tokenAccountA,n.tokenAccountB,new q.PublicKey(t.vault.A),new q.PublicKey(t.vault.B),new q.PublicKey(t.mintA.address),new q.PublicKey(t.mintB.address),o,i,g,P,r,a,s,c==="create",u&&u==="MintA",Jt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,P]})?He(y,b).publicKey:void 0):this.openPositionV2Instruction(y,n.wallet,b,n.wallet,m,A,h,S,k,I,B,n.tokenAccountA,n.tokenAccountB,new q.PublicKey(t.vault.A),new q.PublicKey(t.vault.B),new q.PublicKey(t.mintA.address),new q.PublicKey(t.mintB.address),o,i,g,P,r,a,s,c==="create",null,Jt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[g,P]})?He(y,b).publicKey:void 0);return{address:{nftMint:m,tickArrayLower:k,tickArrayUpper:I,positionNftAccount:A,metadataAccount:h,personalPosition:B,protocolPosition:S},instructions:[K],signers:f,instructionTypes:[Y.ClmmOpenPosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static closePositionInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,ownerPosition:o,nft2022:i}){let r=new q.PublicKey(e.programId),a=i?te(n.wallet,o.nftMint,de.TOKEN_2022_PROGRAM_ID).publicKey:te(n.wallet,o.nftMint,de.TOKEN_PROGRAM_ID).publicKey,{publicKey:s}=sn(r,o.nftMint),u=[];return u.push(this.closePositionInstruction(r,n.wallet,o.nftMint,a,s,!!i,new q.PublicKey(e.id))),{address:{positionNftAccount:a,personalPosition:s},signers:[],instructions:u,instructionTypes:[Y.ClmmClosePosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static increasePositionFromLiquidityInstructions({poolInfo:e,poolKeys:t,ownerPosition:n,ownerInfo:o,liquidity:i,amountMaxA:r,amountMaxB:a,nft2022:s}){let[u,c]=[new q.PublicKey(e.programId),new q.PublicKey(e.id)],d=Te.getTickArrayStartIndex(n.tickLower,e.config.tickSpacing),p=Te.getTickArrayStartIndex(n.tickUpper,e.config.tickSpacing),{publicKey:m}=ve(u,c,d),{publicKey:f}=ve(u,c,p),{publicKey:y}=s?te(o.wallet,n.nftMint,de.TOKEN_2022_PROGRAM_ID):te(o.wallet,n.nftMint,de.TOKEN_PROGRAM_ID),{publicKey:b}=sn(u,n.nftMint),{publicKey:g}=gn(u,c,n.tickLower,n.tickUpper),P=this.increaseLiquidityV2Instruction(u,o.wallet,y,b,c,g,m,f,o.tokenAccountA,o.tokenAccountB,new q.PublicKey(t.vault.A),new q.PublicKey(t.vault.B),new q.PublicKey(e.mintA.address),new q.PublicKey(e.mintB.address),i,r,a,null,Jt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[d,p]})?He(u,c).publicKey:void 0);return{address:{tickArrayLower:m,tickArrayUpper:f,positionNftAccount:y,personalPosition:b,protocolPosition:g},signers:[],instructions:[P],instructionTypes:[Y.ClmmIncreasePosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static increasePositionFromBaseInstructions({poolInfo:e,poolKeys:t,ownerPosition:n,ownerInfo:o,base:i,baseAmount:r,otherAmountMax:a,nft2022:s}){let[u,c]=[new q.PublicKey(e.programId),new q.PublicKey(e.id)],d=Te.getTickArrayStartIndex(n.tickLower,e.config.tickSpacing),p=Te.getTickArrayStartIndex(n.tickUpper,e.config.tickSpacing),{publicKey:m}=ve(u,c,d),{publicKey:f}=ve(u,c,p),{publicKey:y}=s?te(o.wallet,n.nftMint,de.TOKEN_2022_PROGRAM_ID):te(o.wallet,n.nftMint,de.TOKEN_PROGRAM_ID),{publicKey:b}=sn(u,n.nftMint),{publicKey:g}=gn(u,c,n.tickLower,n.tickUpper);return{address:{tickArrayLower:m,tickArrayUpper:f,positionNftAccount:y,personalPosition:b,protocolPosition:g},instructions:[this.increaseLiquidityV2Instruction(u,o.wallet,y,b,c,g,m,f,o.tokenAccountA,o.tokenAccountB,new q.PublicKey(t.vault.A),new q.PublicKey(t.vault.B),new q.PublicKey(e.mintA.address),new q.PublicKey(e.mintB.address),$,i==="MintA"?r:a,i==="MintA"?a:r,i==="MintA",Jt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[d,p]})?He(u,c).publicKey:void 0)],signers:[],instructionTypes:[Y.ClmmIncreasePosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static decreaseLiquidityInstructions({poolInfo:e,poolKeys:t,ownerPosition:n,ownerInfo:o,liquidity:i,amountMinA:r,amountMinB:a,programId:s,nft2022:u}){let[c,d]=[new q.PublicKey(e.programId),new q.PublicKey(e.id)],p=Te.getTickArrayStartIndex(n.tickLower,e.config.tickSpacing),m=Te.getTickArrayStartIndex(n.tickUpper,e.config.tickSpacing),{publicKey:f}=ve(c,d,p),{publicKey:y}=ve(c,d,m),{publicKey:b}=u?te(o.wallet,n.nftMint,de.TOKEN_2022_PROGRAM_ID):te(o.wallet,n.nftMint,s),{publicKey:g}=sn(c,n.nftMint),{publicKey:P}=gn(c,d,n.tickLower,n.tickUpper),k=new Map;for(let B=0;B<t.rewardInfos.length;B++)k.set(t.rewardInfos[B].mint.address,o.rewardAccounts[B]);let I=[];for(let B=0;B<t.rewardInfos.length;B++){let S=t.rewardInfos[B].mint.address,K=k.get(S);K&&I.push({poolRewardVault:new q.PublicKey(t.rewardInfos[B].vault),ownerRewardVault:K,rewardMint:new q.PublicKey(S)})}let A=[],h=this.decreaseLiquidityV2Instruction(c,o.wallet,b,g,d,P,f,y,o.tokenAccountA,o.tokenAccountB,new q.PublicKey(t.vault.A),new q.PublicKey(t.vault.B),new q.PublicKey(e.mintA.address),new q.PublicKey(e.mintB.address),I,i,r,a,Jt.isOverflowDefaultTickarrayBitmap({tickSpacing:e.config.tickSpacing,tickIndexs:[p,m]})?He(c,d).publicKey:void 0);return A.push(h),{address:{tickArrayLower:f,tickArrayUpper:y,positionNftAccount:b,personalPosition:g,protocolPosition:P},signers:[],instructions:A,instructionTypes:[Y.ClmmDecreasePosition],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static makeSwapBaseInInstructions({poolInfo:e,poolKeys:t,observationId:n,ownerInfo:o,inputMint:i,amountIn:r,amountOutMin:a,sqrtPriceLimitX64:s,remainingAccounts:u}){let[c,d]=[new q.PublicKey(e.programId),new q.PublicKey(e.id)],[p,m]=[new q.PublicKey(t.vault.A),new q.PublicKey(t.vault.B)],[f,y]=[new q.PublicKey(e.mintA.address),new q.PublicKey(e.mintB.address)],b=e.mintA.address.toString()===i.toString(),g=[this.swapV2Instruction(c,o.wallet,d,new q.PublicKey(e.config.id),b?o.tokenAccountA:o.tokenAccountB,b?o.tokenAccountB:o.tokenAccountA,b?p:m,b?m:p,b?f:y,b?y:f,u,n,r,a,s,!0,He(c,d).publicKey)];return{signers:[],instructions:g,instructionTypes:[Y.ClmmSwapBaseIn],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[],address:{}}}static makeSwapBaseOutInstructions({poolInfo:e,poolKeys:t,observationId:n,ownerInfo:o,outputMint:i,amountOut:r,amountInMax:a,sqrtPriceLimitX64:s,remainingAccounts:u}){let[c,d]=[new q.PublicKey(e.programId),new q.PublicKey(e.id)],[p,m]=[new q.PublicKey(t.vault.A),new q.PublicKey(t.vault.B)],[f,y]=[new q.PublicKey(e.mintA.address),new q.PublicKey(e.mintB.address)],b=e.mintB.address.toString()===i.toBase58(),g=[this.swapV2Instruction(c,o.wallet,d,new q.PublicKey(e.config.id),b?o.tokenAccountA:o.tokenAccountB,b?o.tokenAccountB:o.tokenAccountA,b?p:m,b?m:p,b?f:y,b?y:f,u,n,r,a,s,!1,He(c,d).publicKey)];return{signers:[],instructions:g,instructionTypes:[Y.ClmmSwapBaseOut],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[],address:{}}}static initRewardInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,rewardInfo:o}){let[i,r]=[new q.PublicKey(e.programId),new q.PublicKey(e.id)],a=Ru(i,r,o.mint).publicKey,s=ai(i).publicKey,u=[this.initializeRewardInstruction(i,n.wallet,r,s,new q.PublicKey(e.config.id),n.tokenAccount,o.programId,o.mint,a,new ur.default(o.openTime),new ur.default(o.endTime),o.emissionsPerSecondX64)];return{address:{poolRewardVault:a,operationId:s},signers:[],instructions:u,instructionTypes:[Y.ClmmInitReward],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static setRewardInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,rewardInfo:o}){let[i,r]=[new q.PublicKey(e.programId),new q.PublicKey(e.id)],a,s,u;for(let p=0;p<e.rewardDefaultInfos.length;p++)e.rewardDefaultInfos[p].mint.address===o.mint.toString()&&(a=p,s=new q.PublicKey(t.rewardInfos[p].vault),u=new q.PublicKey(t.rewardInfos[p].mint.address));(a===void 0||s===void 0)&&km.logWithError("reward mint check error","no reward mint",e.rewardDefaultInfos);let c=ai(i).publicKey,d=[this.setRewardParamsInstruction(i,n.wallet,r,c,new q.PublicKey(e.config.id),n.tokenAccount,s,u,a,new ur.default(o.openTime),new ur.default(o.endTime),o.emissionsPerSecondX64)];return{address:{rewardVault:s,operationId:c},signers:[],instructions:d,instructionTypes:[Y.ClmmSetReward],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static collectRewardInstructions({poolInfo:e,poolKeys:t,ownerInfo:n,rewardMint:o}){let[i,r]=[new q.PublicKey(e.programId),new q.PublicKey(e.id)],a,s;for(let c=0;c<e.rewardDefaultInfos.length;c++)e.rewardDefaultInfos[c].mint.address===o.toString()&&(a=c,s=new q.PublicKey(t.rewardInfos[c].vault));(a===void 0||s===void 0)&&km.logWithError("reward mint check error","no reward mint",e.rewardDefaultInfos);let u=[this.collectRemainingRewardsInstruction(i,n.wallet,r,n.tokenAccount,s,o,a)];return{address:{rewardVault:s},signers:[],instructions:u,instructionTypes:[Y.ClmmCollectReward],lookupTableAddress:t.lookupTableAccount?[t.lookupTableAccount]:[]}}static async makeLockPositions({programId:e,authProgramId:t,poolProgramId:n,payer:o,wallet:i,nftMint:r,nft2022:a,getEphemeralSigners:s}){let u=[],c;if(s)c=new q.PublicKey((await s(1))[0]);else{let g=q.Keypair.generate();u.push(g),c=g.publicKey}let d=a?te(i,r,de.TOKEN_2022_PROGRAM_ID).publicKey:te(i,r,de.TOKEN_PROGRAM_ID).publicKey,{publicKey:p}=sn(n,r),m=No(e,c).publicKey,f=te(i,c,de.TOKEN_PROGRAM_ID).publicKey,y=qn(c).publicKey,b=we.lockPositionInstructionV2({programId:e,auth:t,payer:o,positionOwner:i,lockOwner:i,positionNftAccount:d,positionId:p,lockPositionId:m,lockNftMint:c,lockNftAccount:f,metadataAccount:y,withMetadata:!0,nft2022:a,positionNftMint:r,authPositionNftAccount:te(t,r,a?de.TOKEN_2022_PROGRAM_ID:de.TOKEN_PROGRAM_ID).publicKey,positionNftProgram:a?de.TOKEN_2022_PROGRAM_ID:de.TOKEN_PROGRAM_ID});return{address:{positionId:p,lockPositionId:m,lockNftAccount:f,lockNftMint:c,positionNftAccount:d,metadataAccount:y},instructions:[b],signers:u,instructionTypes:[Y.ClmmLockPosition],lookupTableAddress:[]}}static lockPositionInstructionV2({programId:e,auth:t,payer:n,positionOwner:o,lockOwner:i,positionNftAccount:r,positionId:a,positionNftMint:s,authPositionNftAccount:u,positionNftProgram:c,lockPositionId:d,lockNftMint:p,lockNftAccount:m,metadataAccount:f,withMetadata:y}){let b=[{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!0},{pubkey:o,isSigner:!0,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!0,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:Kn,isSigner:!1,isWritable:!1},{pubkey:de.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:It,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:q.SystemProgram.programId,isSigner:!1,isWritable:!1}],g=v([tt("withMetadata")]),P=Buffer.alloc(g.span);g.encode({withMetadata:y},P);let k=Buffer.from([...Tm,...P]);return new q.TransactionInstruction({keys:b,programId:e,data:k})}static lockPositionInstruction({programId:e,authProgramId:t,poolProgramId:n,owner:o,positionNft:i}){let{publicKey:r}=te(o,i,de.TOKEN_PROGRAM_ID),{publicKey:a}=sn(n,i),s=[{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!0,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:ka(e,a).publicKey,isSigner:!1,isWritable:!0},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:q.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new q.TransactionInstruction({keys:s,programId:e,data:Buffer.from(Tm)})}static harvestLockPositionInstruction(e){let[t,n]=[new q.PublicKey(e.poolKeys.programId),new q.PublicKey(e.poolKeys.id)],o=Te.getTickArrayStartIndex(e.ownerPosition.tickLower,e.poolKeys.config.tickSpacing),i=Te.getTickArrayStartIndex(e.ownerPosition.tickUpper,e.poolKeys.config.tickSpacing),{publicKey:r}=ve(t,n,o),{publicKey:a}=ve(t,n,i),{publicKey:s}=te(e.owner,e.ownerPosition.nftMint,de.TOKEN_PROGRAM_ID),{publicKey:u}=sn(t,e.ownerPosition.nftMint),{publicKey:c}=gn(t,n,e.ownerPosition.tickLower,e.ownerPosition.tickUpper),d=[];for(let f=0;f<e.poolKeys.rewardInfos.length;f++)d.push({poolRewardVault:new q.PublicKey(e.poolKeys.rewardInfos[f].vault),ownerRewardVault:e.ownerRewardAccounts[f],rewardMint:new q.PublicKey(e.poolKeys.rewardInfos[f].mint.address)});let p=[...d.map(f=>[{pubkey:f.poolRewardVault,isSigner:!1,isWritable:!0},{pubkey:f.ownerRewardVault,isSigner:!1,isWritable:!0},{pubkey:f.rewardMint,isSigner:!1,isWritable:!1}]).flat()],m=[{pubkey:e.authProgramId,isSigner:!1,isWritable:!1},{pubkey:ka(e.programId,u).publicKey,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:e.owner,isSigner:!0,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:new q.PublicKey(e.poolKeys.vault.A),isSigner:!1,isWritable:!0},{pubkey:new q.PublicKey(e.poolKeys.vault.B),isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:e.userVaultA,isSigner:!1,isWritable:!0},{pubkey:e.userVaultB,isSigner:!1,isWritable:!0},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:mn,isSigner:!1,isWritable:!1},{pubkey:new q.PublicKey(e.poolKeys.mintA.address),isSigner:!1,isWritable:!1},{pubkey:new q.PublicKey(e.poolKeys.mintB.address),isSigner:!1,isWritable:!1},...p];return new q.TransactionInstruction({keys:m,programId:e.programId,data:Buffer.from(hm)})}static harvestLockPositionInstructionV2({programId:e,auth:t,lockPositionId:n,clmmProgram:o,lockOwner:i,lockNftMint:r,lockNftAccount:a,positionNftAccount:s,positionId:u,poolId:c,protocolPosition:d,vaultA:p,vaultB:m,tickArrayLower:f,tickArrayUpper:y,userVaultA:b,userVaultB:g,mintA:P,mintB:k,rewardAccounts:I,exTickArrayBitmap:A}){let h=[...A?[{pubkey:A,isSigner:!1,isWritable:!0}]:[],...I.map(S=>[{pubkey:S.poolRewardVault,isSigner:!1,isWritable:!0},{pubkey:S.ownerRewardVault,isSigner:!1,isWritable:!0},{pubkey:S.rewardMint,isSigner:!1,isWritable:!1}]).flat()],B=[{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!0,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:y,isSigner:!1,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!0},{pubkey:g,isSigner:!1,isWritable:!0},{pubkey:de.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:de.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:mn,isSigner:!1,isWritable:!1},{pubkey:P,isSigner:!1,isWritable:!1},{pubkey:k,isSigner:!1,isWritable:!1},...h];return new q.TransactionInstruction({keys:B,programId:e,data:Buffer.from(hm)})}};var li=class extends at{constructor(e){super(e)}async getClmmPoolKeys(e){return(await this.scope.api.fetchPoolKeysById({idList:[e]}))[0]}async createPool(e){var A;let{programId:t,owner:n=((A=this.scope.owner)==null?void 0:A.publicKey)||z.PublicKey.default,mint1:o,mint2:i,ammConfig:r,initialPrice:a,computeBudgetConfig:s,txVersion:u,txTipConfig:c,feePayer:d}=e,p=this.createTxBuilder(d),[m,f,y]=new ft.default(new z.PublicKey(o.address).toBuffer()).gt(new ft.default(new z.PublicKey(i.address).toBuffer()))?[i,o,new Gn.default(1).div(a)]:[o,i,a],b=ae.priceToSqrtPriceX64(y,m.decimals,f.decimals),g=[],P=[];m.programId===We.TOKEN_2022_PROGRAM_ID.toBase58()&&P.push(fo(t,new z.PublicKey(m.address)).publicKey),f.programId===We.TOKEN_2022_PROGRAM_ID.toBase58()&&P.push(fo(t,new z.PublicKey(f.address)).publicKey),(await this.scope.connection.getMultipleAccountsInfo(P)).forEach((h,B)=>{h&&g.push(P[B])});let I=await we.createPoolInstructions({connection:this.scope.connection,programId:t,owner:n,mintA:m,mintB:f,ammConfigId:r.id,initialPriceX64:b,extendMintAccount:g});return p.addInstruction(I),p.addCustomComputeBudget(s),p.addTipInstruction(c),p.versionBuild({txVersion:u,extInfo:{address:E(N({},I.address),{observationId:I.address.observationId.toBase58(),exBitmapAccount:I.address.exBitmapAccount.toBase58(),programId:t.toString(),id:I.address.poolId.toString(),mintA:m,mintB:f,openTime:"0",vault:{A:I.address.mintAVault.toString(),B:I.address.mintBVault.toString()},rewardInfos:[],config:{id:r.id.toString(),index:r.index,protocolFeeRate:r.protocolFeeRate,tradeFeeRate:r.tradeFeeRate,tickSpacing:r.tickSpacing,fundFeeRate:r.fundFeeRate,description:r.description,defaultRange:0,defaultRangePoint:[]}}),mockPoolInfo:N({type:"Concentrated",rewardDefaultPoolInfos:"Clmm",id:I.address.poolId.toString(),mintA:m,mintB:f,feeRate:r.tradeFeeRate,openTime:"0",programId:t.toString(),price:y.toNumber(),config:{id:r.id.toString(),index:r.index,protocolFeeRate:r.protocolFeeRate,tradeFeeRate:r.tradeFeeRate,tickSpacing:r.tickSpacing,fundFeeRate:r.fundFeeRate,description:r.description,defaultRange:0,defaultRangePoint:[]},feeOn:"Both",hasDynamicFee:!1,launchMigratePool:!1,burnPercent:0,tips:[]},er)}})}async createCustomizablePool(e){var K;let{programId:t,owner:n=((K=this.scope.owner)==null?void 0:K.publicKey)||z.PublicKey.default,mint1:o,mint2:i,initialPrice:r,ammConfig:a,collectFeeOn:s=0,dynamicFeeConfig:u,computeBudgetConfig:c,txVersion:d,txTipConfig:p,feePayer:m,addSupportMintExt:f}=e,y=this.createTxBuilder(m),[b,g,P]=new ft.default(new z.PublicKey(o.address).toBuffer()).gt(new ft.default(new z.PublicKey(i.address).toBuffer()))?[i,o,new Gn.default(1).div(r)]:[o,i,r],k=ae.priceToSqrtPriceX64(P,b.decimals,g.decimals),I=[],A=[];f&&(b.programId===We.TOKEN_2022_PROGRAM_ID.toBase58()&&A.push(fo(t,new z.PublicKey(b.address)).publicKey),g.programId===We.TOKEN_2022_PROGRAM_ID.toBase58()&&A.push(fo(t,new z.PublicKey(g.address)).publicKey),(await this.scope.connection.getMultipleAccountsInfo(A)).forEach((C,L)=>{C&&I.push(A[L])}));let{address:h}=await we.createPoolInstructions({connection:this.scope.connection,programId:t,owner:n,mintA:b,mintB:g,ammConfigId:a.id,initialPriceX64:k,extendMintAccount:I}),B=[];if(u){if(!await this.scope.connection.getAccountInfo(u))throw new Error("Dynamic Fee Config not found. Run 03_admin_create_dynamic_fee_config.ts first.");console.log("Dynamic Fee Config",u.toBase58()),B.push({pubkey:u,isSigner:!1,isWritable:!1})}let S=we.createCustomizablePoolInstruction(t,h.poolId,this.scope.ownerPubKey,a.id,h.mintA,h.mintB,h.mintAVault,h.mintBVault,h.observationId,h.exBitmapAccount,h.mintAProgram,h.mintBProgram,k,s,[...I,...B.map(x=>x.pubkey)],u);return y.addInstruction({instructions:[S]}),y.addCustomComputeBudget(c),y.addTipInstruction(p),y.versionBuild({txVersion:d,extInfo:{address:E(N({},h),{observationId:h.observationId.toBase58(),exBitmapAccount:h.exBitmapAccount.toBase58(),programId:t.toString(),id:h.poolId.toString(),mintA:b,mintB:g,openTime:"0",vault:{A:h.mintAVault.toString(),B:h.mintBVault.toString()},rewardInfos:[],config:{id:a.id.toString(),index:a.index,protocolFeeRate:a.protocolFeeRate,tradeFeeRate:a.tradeFeeRate,tickSpacing:a.tickSpacing,fundFeeRate:a.fundFeeRate,description:a.description,defaultRange:0,defaultRangePoint:[]}}),mockPoolInfo:N({type:"Concentrated",rewardDefaultPoolInfos:"Clmm",id:h.poolId.toString(),mintA:b,mintB:g,feeRate:a.tradeFeeRate,openTime:"0",programId:t.toString(),price:P.toNumber(),config:{id:a.id.toString(),index:a.index,protocolFeeRate:a.protocolFeeRate,tradeFeeRate:a.tradeFeeRate,tickSpacing:a.tickSpacing,fundFeeRate:a.fundFeeRate,description:a.description,defaultRange:0,defaultRangePoint:[]},burnPercent:0,collectFeeOn:s,feeOn:s===0?"Both":s===1?"TokenA":"TokenB",hasDynamicFee:!!u,tips:[],launchMigratePool:!1},er)}})}async createPermissionedPool(e){var C;let{programId:t,owner:n=((C=this.scope.owner)==null?void 0:C.publicKey)||z.PublicKey.default,mint1:o,mint2:i,initialPrice:r,ammConfig:a,collectFeeOn:s=0,dynamicFeeConfig:u,computeBudgetConfig:c,txVersion:d,txTipConfig:p,feePayer:m,addSupportMintExt:f}=e,y=this.createTxBuilder(m),[b,g,P]=new ft.default(new z.PublicKey(o.address).toBuffer()).gt(new ft.default(new z.PublicKey(i.address).toBuffer()))?[i,o,new Gn.default(1).div(r)]:[o,i,r],k=ae.priceToSqrtPriceX64(P,b.decimals,g.decimals),I=[],A=[];f&&(b.programId===We.TOKEN_2022_PROGRAM_ID.toBase58()&&A.push(fo(t,new z.PublicKey(b.address)).publicKey),g.programId===We.TOKEN_2022_PROGRAM_ID.toBase58()&&A.push(fo(t,new z.PublicKey(g.address)).publicKey),(await this.scope.connection.getMultipleAccountsInfo(A)).forEach((O,R)=>{O&&I.push(A[R])}));let h=m!=null?m:this.scope.ownerPubKey,B=Math.floor(Math.random()*Math.pow(2,16))+1,{address:S}=await we.createPermissionedPoolInstructions({connection:this.scope.connection,programId:t,owner:n,mintA:b,mintB:g,ammConfigId:a.id,initialPriceX64:k,extendMintAccount:I,payer:h,seedIndex:B}),K=[];if(u){if(!await this.scope.connection.getAccountInfo(u))throw new Error("Dynamic Fee Config not found. Run 03_admin_create_dynamic_fee_config.ts first.");console.log("Dynamic Fee Config",u.toBase58()),K.push({pubkey:u,isSigner:!1,isWritable:!1})}let x=we.createPermissionedPoolInstruction(t,h,h,S.permission,a.id,S.poolId,S.mintA,S.mintB,S.mintAVault,S.mintBVault,S.observationId,S.exBitmapAccount,S.mintAProgram,S.mintBProgram,k,s,B,[...I,...K.map(L=>L.pubkey)],u);return y.addInstruction({instructions:[x]}),y.addCustomComputeBudget(c),y.addTipInstruction(p),y.versionBuild({txVersion:d,extInfo:{address:E(N({},S),{observationId:S.observationId.toBase58(),exBitmapAccount:S.exBitmapAccount.toBase58(),programId:t.toString(),id:S.poolId.toString(),mintA:b,mintB:g,openTime:"0",vault:{A:S.mintAVault.toString(),B:S.mintBVault.toString()},rewardInfos:[],config:{id:a.id.toString(),index:a.index,protocolFeeRate:a.protocolFeeRate,tradeFeeRate:a.tradeFeeRate,tickSpacing:a.tickSpacing,fundFeeRate:a.fundFeeRate,description:a.description,defaultRange:0,defaultRangePoint:[]}}),mockPoolInfo:N({type:"Concentrated",rewardDefaultPoolInfos:"Clmm",id:S.poolId.toString(),mintA:b,mintB:g,feeRate:a.tradeFeeRate,openTime:"0",programId:t.toString(),price:P.toNumber(),config:{id:a.id.toString(),index:a.index,protocolFeeRate:a.protocolFeeRate,tradeFeeRate:a.tradeFeeRate,tickSpacing:a.tickSpacing,fundFeeRate:a.fundFeeRate,description:a.description,defaultRange:0,defaultRangePoint:[]},burnPercent:0,collectFeeOn:s,feeOn:s===0?"Both":s===1?"TokenA":"TokenB",hasDynamicFee:!!u,tips:[],launchMigratePool:!1},er)}})}async openPositionFromBase({poolInfo:e,poolKeys:t,ownerInfo:n,tickLower:o,tickUpper:i,base:r=null,baseAmount:a,otherAmountMax:s,liquidity:u=new ft.default(0),nft2022:c,associatedOnly:d=!0,checkCreateATAOwner:p=!1,withMetadata:m="create",getEphemeralSigners:f,computeBudgetConfig:y,txTipConfig:b,txVersion:g,feePayer:P}){this.scope.availability.addConcentratedPosition===!1&&this.logAndCreateError("add position feature disabled in your region"),this.scope.checkOwner();let k=this.createTxBuilder(P),I=null,A=null,h=n.useSOLBalance&&e.mintA.address===ee.toString(),B=n.useSOLBalance&&e.mintB.address===ee.toString(),[S,K]=r==="MintA"?[a,s]:[s,a],{account:x,instructionParams:C}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintA.programId,mint:new z.PublicKey(e.mintA.address),owner:this.scope.ownerPubKey,createInfo:h||S.isZero()?{payer:this.scope.ownerPubKey,amount:S}:void 0,skipCloseAccount:!h,notUseTokenAccount:h,associatedOnly:h?!1:d,checkCreateATAOwner:p});x&&(I=x),k.addInstruction(C||{});let{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintB.programId,mint:new z.PublicKey(e.mintB.address),owner:this.scope.ownerPubKey,createInfo:B||K.isZero()?{payer:this.scope.ownerPubKey,amount:K}:void 0,skipCloseAccount:!B,notUseTokenAccount:B,associatedOnly:B?!1:d,checkCreateATAOwner:p});L&&(A=L),k.addInstruction(O||{}),(!I||!A)&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",{ownerTokenAccountA:I==null?void 0:I.toBase58(),ownerTokenAccountB:A==null?void 0:A.toBase58()});let R=t!=null?t:await this.getClmmPoolKeys(e.id.toString()),F=await we.openPositionFromBaseInstructions({poolInfo:e,poolKeys:R,ownerInfo:E(N({},n),{feePayer:this.scope.ownerPubKey,wallet:this.scope.ownerPubKey,tokenAccountA:I,tokenAccountB:A}),tickLower:o,tickUpper:i,base:r,baseAmount:a,otherAmountMax:s,liquidity:u,withMetadata:m,getEphemeralSigners:f,nft2022:c});return k.addInstruction(F),k.addCustomComputeBudget(y),k.addTipInstruction(b),k.versionBuild({txVersion:g,extInfo:N({},F.address)})}async openPositionFromLiquidity({poolInfo:e,poolKeys:t,ownerInfo:n,amountMaxA:o,amountMaxB:i,base:r=null,tickLower:a,tickUpper:s,liquidity:u,associatedOnly:c=!0,checkCreateATAOwner:d=!1,withMetadata:p="create",txVersion:m,computeBudgetConfig:f,txTipConfig:y,getEphemeralSigners:b,nft2022:g,feePayer:P}){this.scope.availability.createConcentratedPosition===!1&&this.logAndCreateError("open position feature disabled in your region");let k=this.createTxBuilder(P),I=null,A=null,h=n.useSOLBalance&&e.mintA.address===ee.toBase58(),B=n.useSOLBalance&&e.mintB.address===ee.toBase58(),{account:S,instructionParams:K}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintA.programId,mint:new z.PublicKey(e.mintA.address),owner:this.scope.ownerPubKey,createInfo:h||o.isZero()?{payer:this.scope.ownerPubKey,amount:o}:void 0,skipCloseAccount:!h,notUseTokenAccount:h,associatedOnly:h?!1:c,checkCreateATAOwner:d});S&&(I=S),k.addInstruction(K||{});let{account:x,instructionParams:C}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintB.programId,mint:new z.PublicKey(e.mintB.address),owner:this.scope.ownerPubKey,createInfo:B||i.isZero()?{payer:this.scope.ownerPubKey,amount:i}:void 0,skipCloseAccount:!B,notUseTokenAccount:B,associatedOnly:B?!1:c,checkCreateATAOwner:d});x&&(A=x),k.addInstruction(C||{}),(I===void 0||A===void 0)&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",this.scope.account.tokenAccounts);let L=t||await this.getClmmPoolKeys(e.id.toString()),O=await we.openPositionFromLiquidityInstructions({poolInfo:e,poolKeys:L,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:I,tokenAccountB:A},tickLower:a,tickUpper:s,liquidity:u,amountMaxA:o,amountMaxB:i,base:r,withMetadata:p,getEphemeralSigners:b,nft2022:g});return k.addInstruction(O),k.addCustomComputeBudget(f),k.addTipInstruction(y),k.versionBuild({txVersion:m,extInfo:{address:O.address}})}async increasePositionFromLiquidity(e){var x;let{poolInfo:t,poolKeys:n,ownerPosition:o,amountMaxA:i,amountMaxB:r,liquidity:a,ownerInfo:s,associatedOnly:u=!0,checkCreateATAOwner:c=!1,computeBudgetConfig:d,txTipConfig:p,txVersion:m,feePayer:f}=e,y=this.createTxBuilder(f),b,g,P=s.useSOLBalance&&t.mintA.address===ee.toString(),k=s.useSOLBalance&&t.mintB.address===ee.toString(),{account:I,instructionParams:A}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintA.programId,mint:new z.PublicKey(t.mintA.address),notUseTokenAccount:P,owner:this.scope.ownerPubKey,createInfo:P||i.isZero()?{payer:this.scope.ownerPubKey,amount:i}:void 0,skipCloseAccount:!P,associatedOnly:P?!1:u,checkCreateATAOwner:c});I&&(b=I),y.addInstruction(A||{});let{account:h,instructionParams:B}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintB.programId,mint:new z.PublicKey(t.mintB.address),owner:this.scope.ownerPubKey,createInfo:k||r.isZero()?{payer:this.scope.ownerPubKey,amount:r}:void 0,notUseTokenAccount:k,skipCloseAccount:!k,associatedOnly:k?!1:u,checkCreateATAOwner:c});h&&(g=h),y.addInstruction(B||{}),!b&&!g&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",this.scope.account.tokenAccounts);let S=n!=null?n:await this.getClmmPoolKeys(t.id),K=we.increasePositionFromLiquidityInstructions({poolInfo:t,poolKeys:S,ownerPosition:o,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:b,tokenAccountB:g},liquidity:a,amountMaxA:i,amountMaxB:r,nft2022:(x=await this.scope.connection.getAccountInfo(o.nftMint))==null?void 0:x.owner.equals(We.TOKEN_2022_PROGRAM_ID)});return y.addInstruction(K),y.addCustomComputeBudget(d),y.addTipInstruction(p),y.versionBuild({txVersion:m,extInfo:{address:K.address}})}async increasePositionFromBase(e){var K;let{poolInfo:t,ownerPosition:n,base:o,baseAmount:i,otherAmountMax:r,ownerInfo:a,associatedOnly:s=!0,checkCreateATAOwner:u=!1,computeBudgetConfig:c,txTipConfig:d,txVersion:p,feePayer:m}=e,f=this.createTxBuilder(m),y,b,g=a.useSOLBalance&&t.mintA.address===ee.toString(),P=a.useSOLBalance&&t.mintB.address===ee.toString(),{account:k,instructionParams:I}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintA.programId,mint:new z.PublicKey(t.mintA.address),notUseTokenAccount:g,owner:this.scope.ownerPubKey,createInfo:g||(o==="MintA"?i:r).isZero()?{payer:this.scope.ownerPubKey,amount:o==="MintA"?i:r}:void 0,skipCloseAccount:!g,associatedOnly:g?!1:s,checkCreateATAOwner:u});k&&(y=k),f.addInstruction(I||{});let{account:A,instructionParams:h}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintB.programId,mint:new z.PublicKey(t.mintB.address),owner:this.scope.ownerPubKey,createInfo:P||(o==="MintA"?r:i).isZero()?{payer:this.scope.ownerPubKey,amount:o==="MintA"?r:i}:void 0,notUseTokenAccount:P,skipCloseAccount:!P,associatedOnly:P?!1:s,checkCreateATAOwner:u});A&&(b=A),f.addInstruction(h||{}),!y&&!b&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",this.scope.account.tokenAccounts);let B=await this.getClmmPoolKeys(t.id),S=we.increasePositionFromBaseInstructions({poolInfo:t,poolKeys:B,ownerPosition:n,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:y,tokenAccountB:b},base:o,baseAmount:i,otherAmountMax:r,nft2022:(K=await this.scope.connection.getAccountInfo(n.nftMint))==null?void 0:K.owner.equals(We.TOKEN_2022_PROGRAM_ID)});return f.addInstruction(S),f.addCustomComputeBudget(c),f.addTipInstruction(d),f.versionBuild({txVersion:p,extInfo:{address:S.address}})}async decreaseLiquidity(e){var O;let{poolInfo:t,poolKeys:n,ownerPosition:o,ownerInfo:i,amountMinA:r,amountMinB:a,liquidity:s,associatedOnly:u=!0,checkCreateATAOwner:c=!1,computeBudgetConfig:d,txTipConfig:p,txVersion:m,feePayer:f}=e;this.scope.availability.removeConcentratedPosition===!1&&this.logAndCreateError("remove position feature disabled in your region");let y=this.createTxBuilder(f),b=i.useSOLBalance&&t.mintA.address===ee.toString(),g=i.useSOLBalance&&t.mintB.address===ee.toString(),P,k,{account:I,instructionParams:A}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintA.programId,mint:new z.PublicKey(t.mintA.address),notUseTokenAccount:b,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!b,associatedOnly:b?!1:u,checkCreateATAOwner:c});P=I,A&&y.addInstruction(A);let{account:h,instructionParams:B}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintB.programId,mint:new z.PublicKey(t.mintB.address),notUseTokenAccount:g,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!g,associatedOnly:g?!1:u,checkCreateATAOwner:c});k=h,B&&y.addInstruction(B);let S=n!=null?n:await this.getClmmPoolKeys(t.id),K=[];for(let R of S.rewardInfos){let F=i.useSOLBalance&&R.mint.address===ee.toString(),W;if(R.mint.address===t.mintA.address)W=P;else if(R.mint.address===t.mintB.address)W=k;else{let{account:D,instructionParams:X}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new z.PublicKey(R.mint.programId),mint:new z.PublicKey(R.mint.address),notUseTokenAccount:F,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!F,associatedOnly:F?!1:u,checkCreateATAOwner:c});W=D,X&&y.addInstruction(X)}K.push(W)}!P&&!k&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",this.scope.account.tokenAccountRawInfos);let x=(O=await this.scope.connection.getAccountInfo(o.nftMint))==null?void 0:O.owner.equals(We.TOKEN_2022_PROGRAM_ID),C=await we.decreaseLiquidityInstructions({poolInfo:t,poolKeys:S,ownerPosition:o,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:P,tokenAccountB:k,rewardAccounts:K},liquidity:s,amountMinA:r,amountMinB:a,nft2022:x});y.addInstruction({instructions:C.instructions,instructionTypes:[Y.ClmmDecreasePosition]});let L=N({},C.address);if(i.closePosition){let R=await we.closePositionInstructions({poolInfo:t,poolKeys:S,ownerInfo:{wallet:this.scope.ownerPubKey},ownerPosition:o,nft2022:x});y.addInstruction({endInstructions:R.instructions,endInstructionTypes:R.instructionTypes}),L=N(N({},L),R.address)}return y.addCustomComputeBudget(d),y.addTipInstruction(p),y.versionBuild({txVersion:m,extInfo:{address:L}})}async lockPosition(e){var f;let{programId:t=Zo,authProgramId:n=zi,poolProgramId:o=Vn,ownerPosition:i,payer:r,computeBudgetConfig:a,txTipConfig:s,txVersion:u,getEphemeralSigners:c,feePayer:d}=e,p=this.createTxBuilder(d),m=await we.makeLockPositions({programId:t,authProgramId:n,poolProgramId:o,wallet:this.scope.ownerPubKey,payer:r!=null?r:this.scope.ownerPubKey,nftMint:i.nftMint,getEphemeralSigners:c,nft2022:(f=await this.scope.connection.getAccountInfo(i.nftMint))==null?void 0:f.owner.equals(We.TOKEN_2022_PROGRAM_ID)});return p.addInstruction(m),p.addCustomComputeBudget(a),p.addTipInstruction(s),p.versionBuild({txVersion:u,extInfo:m.address})}async harvestLockPosition(e){let{programId:t=Zo,authProgramId:n=zi,clmmProgram:o=Vn,poolKeys:i,lockData:r,ownerInfo:a={useSOLBalance:!0},associatedOnly:s=!0,checkCreateATAOwner:u=!1,computeBudgetConfig:c,txTipConfig:d,txVersion:p,feePayer:m}=e,f=i||await this.getClmmPoolKeys(r.poolId.toString()),y=this.createTxBuilder(m),b=await this.scope.connection.getAccountInfo(r.positionId);b||this.logger.logWithError("position not found",r.positionId);let g=tr.decode(b.data),P=a.useSOLBalance&&f.mintA.address===ee.toString(),k=a.useSOLBalance&&f.mintB.address===ee.toString(),I,A,{account:h,instructionParams:B}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:f.mintA.programId,mint:new z.PublicKey(f.mintA.address),notUseTokenAccount:P,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!P,associatedOnly:P?!1:s,checkCreateATAOwner:u});I=h,B&&y.addInstruction(B);let{account:S,instructionParams:K}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:f.mintB.programId,mint:new z.PublicKey(f.mintB.address),notUseTokenAccount:k,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!k,associatedOnly:k?!1:s,checkCreateATAOwner:u});A=S,K&&y.addInstruction(K);let x={},C=[];for(let ne of f.rewardInfos){let se=a.useSOLBalance&&ne.mint.address===ee.toString(),J=x[ne.mint.address];if(!J){let{account:ge,instructionParams:ue}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new z.PublicKey(ne.mint.programId),mint:new z.PublicKey(ne.mint.address),notUseTokenAccount:se,owner:this.scope.ownerPubKey,skipCloseAccount:!se,createInfo:{payer:this.scope.ownerPubKey,amount:0},associatedOnly:se?!1:s});J=ge,ue&&y.addInstruction(ue)}x[ne.mint.address]=J,C.push(J)}let L=No(t,r.lockNftMint).publicKey,O=te(this.scope.ownerPubKey,r.lockNftMint,We.TOKEN_PROGRAM_ID).publicKey,R=Te.getTickArrayStartIndex(g.tickLower,f.config.tickSpacing),F=Te.getTickArrayStartIndex(g.tickUpper,f.config.tickSpacing),{publicKey:W}=ve(new z.PublicKey(f.programId),r.poolId,R),{publicKey:D}=ve(new z.PublicKey(f.programId),r.poolId,F),{publicKey:X}=gn(new z.PublicKey(f.programId),r.poolId,g.tickLower,g.tickUpper),Z=[];for(let ne=0;ne<f.rewardInfos.length;ne++){let se=f.rewardInfos[ne].mint.address,J=x[se];J&&Z.push({poolRewardVault:new z.PublicKey(f.rewardInfos[ne].vault),ownerRewardVault:J,rewardMint:new z.PublicKey(se)})}let H=await we.harvestLockPositionInstructionV2({programId:t,auth:n,lockPositionId:L,clmmProgram:o,lockOwner:this.scope.ownerPubKey,lockNftMint:r.lockNftMint,lockNftAccount:O,positionNftAccount:r.nftAccount,positionId:r.positionId,poolId:r.poolId,protocolPosition:X,vaultA:new z.PublicKey(f.vault.A),vaultB:new z.PublicKey(f.vault.B),tickArrayLower:W,tickArrayUpper:D,userVaultA:I,userVaultB:A,mintA:new z.PublicKey(f.mintA.address),mintB:new z.PublicKey(f.mintB.address),rewardAccounts:Z,exTickArrayBitmap:He(o,r.poolId).publicKey});return y.addInstruction({instructions:[H],instructionTypes:[Y.ClmmHarvestLockPosition]}),y.addCustomComputeBudget(c),y.addTipInstruction(d),y.versionBuild({txVersion:p})}async closePosition({poolInfo:e,poolKeys:t,ownerPosition:n,txVersion:o,computeBudgetConfig:i,txTipConfig:r,feePayer:a}){var d;this.scope.availability.removeConcentratedPosition===!1&&this.logAndCreateError("remove position feature disabled in your region");let s=this.createTxBuilder(a),u=t!=null?t:await this.getClmmPoolKeys(e.id),c=we.closePositionInstructions({poolInfo:e,poolKeys:u,ownerInfo:{wallet:this.scope.ownerPubKey},ownerPosition:n,nft2022:(d=await this.scope.connection.getAccountInfo(n.nftMint))==null?void 0:d.owner.equals(We.TOKEN_2022_PROGRAM_ID)});return s.addCustomComputeBudget(i),s.addTipInstruction(r),s.addInstruction(c).versionBuild({txVersion:o,extInfo:{address:c.address}})}async initReward({poolInfo:e,ownerInfo:t,rewardInfo:n,associatedOnly:o=!0,checkCreateATAOwner:i=!1,computeBudgetConfig:r,txVersion:a,feePayer:s}){n.endTime<=n.openTime&&this.logAndCreateError("reward time error","rewardInfo",n);let u=this.createTxBuilder(s),c=t.useSOLBalance&&n.mint.address.toString()===ee.toString(),d=n.perSecond.mul(n.endTime-n.openTime),{account:p,instructionParams:m}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new z.PublicKey(n.mint.programId),mint:new z.PublicKey(n.mint.address),notUseTokenAccount:!!c,skipCloseAccount:!c,owner:this.scope.ownerPubKey,createInfo:c?{payer:t.feePayer||this.scope.ownerPubKey,amount:new ft.default(new Gn.default(d.toFixed(0)).gte(d)?d.toFixed(0):d.add(1).toFixed(0))}:void 0,associatedOnly:c?!1:o,checkCreateATAOwner:i});m&&u.addInstruction(m),p||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos);let f=await this.getClmmPoolKeys(e.id),y=we.initRewardInstructions({poolInfo:e,poolKeys:f,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:p},rewardInfo:{programId:new z.PublicKey(n.mint.programId),mint:new z.PublicKey(n.mint.address),openTime:n.openTime,endTime:n.endTime,emissionsPerSecondX64:yo(n.perSecond)}});return u.addInstruction(y),u.addCustomComputeBudget(r),u.versionBuild({txVersion:a,extInfo:{address:y.address}})}async initRewards({poolInfo:e,poolKeys:t,ownerInfo:n,rewardInfos:o,associatedOnly:i=!0,checkCreateATAOwner:r=!1,computeBudgetConfig:a,txTipConfig:s,txVersion:u,feePayer:c}){for(let m of o)m.endTime<=m.openTime&&this.logAndCreateError("reward time error","rewardInfo",m);let d=this.createTxBuilder(c),p={};for(let m of o){let f=n.useSOLBalance&&m.mint.address===ee.toString(),y=m.perSecond.mul(m.endTime-m.openTime),{account:b,instructionParams:g}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new z.PublicKey(m.mint.programId),mint:new z.PublicKey(m.mint.address),notUseTokenAccount:!!f,skipCloseAccount:!f,owner:this.scope.ownerPubKey,createInfo:f?{payer:n.feePayer||this.scope.ownerPubKey,amount:new ft.default(new Gn.default(y.toFixed(0)).gte(y)?y.toFixed(0):y.add(1).toFixed(0))}:void 0,associatedOnly:f?!1:i,checkCreateATAOwner:r});g&&d.addInstruction(g),b||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos);let P=t!=null?t:await this.getClmmPoolKeys(e.id),k=we.initRewardInstructions({poolInfo:e,poolKeys:P,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:b},rewardInfo:{programId:new z.PublicKey(m.mint.programId),mint:new z.PublicKey(m.mint.address),openTime:m.openTime,endTime:m.endTime,emissionsPerSecondX64:yo(m.perSecond)}});p=N(N({},p),k.address),d.addInstruction(k)}return d.addCustomComputeBudget(a),d.addTipInstruction(s),d.versionBuild({txVersion:u,extInfo:{address:p}})}async setReward({poolInfo:e,ownerInfo:t,rewardInfo:n,associatedOnly:o=!0,checkCreateATAOwner:i=!1,computeBudgetConfig:r,txTipConfig:a,txVersion:s,feePayer:u}){n.endTime<=n.openTime&&this.logAndCreateError("reward time error","rewardInfo",n);let c=this.createTxBuilder(u),d=t.useSOLBalance&&n.mint.equals(ee),{account:p,instructionParams:m}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n.programId,mint:n.mint,notUseTokenAccount:d,owner:this.scope.ownerPubKey,createInfo:d?{payer:t.feePayer||this.scope.ownerPubKey,amount:new ft.default(new Gn.default(n.perSecond.mul(n.endTime-n.openTime).toFixed(0)).gte(n.perSecond.mul(n.endTime-n.openTime))?n.perSecond.mul(n.endTime-n.openTime).toFixed(0):n.perSecond.mul(n.endTime-n.openTime).add(1).toFixed(0))}:void 0,associatedOnly:d?!1:o,checkCreateATAOwner:i});m&&c.addInstruction(m),p||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos);let f=await this.getClmmPoolKeys(e.id),y=we.setRewardInstructions({poolInfo:e,poolKeys:f,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:p},rewardInfo:{mint:n.mint,openTime:n.openTime,endTime:n.endTime,emissionsPerSecondX64:yo(n.perSecond)}});return c.addInstruction(y),c.addCustomComputeBudget(r),c.addTipInstruction(a),c.versionBuild({txVersion:s,extInfo:{address:y.address}})}async setRewards({poolInfo:e,poolKeys:t,ownerInfo:n,rewardInfos:o,associatedOnly:i=!0,checkCreateATAOwner:r=!1,computeBudgetConfig:a,txTipConfig:s,txVersion:u,feePayer:c}){let d=this.createTxBuilder(c),p={};for(let m of o){m.endTime<=m.openTime&&this.logAndCreateError("reward time error","rewardInfo",m);let f=n.useSOLBalance&&m.mint.address===ee.toString(),{account:y,instructionParams:b}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new z.PublicKey(m.mint.programId),mint:new z.PublicKey(m.mint.address),notUseTokenAccount:f,owner:this.scope.ownerPubKey,createInfo:f?{payer:n.feePayer||this.scope.ownerPubKey,amount:new ft.default(new Gn.default(m.perSecond.mul(m.endTime-m.openTime).toFixed(0)).gte(m.perSecond.mul(m.endTime-m.openTime))?m.perSecond.mul(m.endTime-m.openTime).toFixed(0):m.perSecond.mul(m.endTime-m.openTime).add(1).toFixed(0))}:void 0,associatedOnly:f?!1:i,checkCreateATAOwner:r});b&&d.addInstruction(b),y||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos);let g=t!=null?t:await this.getClmmPoolKeys(e.id),P=we.setRewardInstructions({poolInfo:e,poolKeys:g,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:y},rewardInfo:{mint:new z.PublicKey(m.mint.address),openTime:m.openTime,endTime:m.endTime,emissionsPerSecondX64:yo(m.perSecond)}});d.addInstruction(P),p=N(N({},p),P.address)}return d.addCustomComputeBudget(a),d.addTipInstruction(s),d.versionBuild({txVersion:u,extInfo:{address:p}})}async collectReward({poolInfo:e,ownerInfo:t,rewardMint:n,associatedOnly:o=!0,checkCreateATAOwner:i=!1,computeBudgetConfig:r,txTipConfig:a,txVersion:s,feePayer:u}){let c=e.rewardDefaultInfos.find(g=>g.mint.address===n.toString());c||this.logAndCreateError("reward mint error","not found reward mint",n);let d=this.createTxBuilder(u),p=t.useSOLBalance&&n.equals(ee),{account:m,instructionParams:f}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new z.PublicKey(c.mint.programId),mint:n,notUseTokenAccount:p,owner:this.scope.ownerPubKey,skipCloseAccount:!p,createInfo:{payer:t.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:p?!1:o,checkCreateATAOwner:i});f&&d.addInstruction(f),m||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos);let y=await this.getClmmPoolKeys(e.id),b=we.collectRewardInstructions({poolInfo:e,poolKeys:y,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:m},rewardMint:n});return d.addInstruction(b),d.addCustomComputeBudget(r),d.addTipInstruction(a),d.versionBuild({txVersion:s,extInfo:{address:b.address}})}async collectRewards({poolInfo:e,ownerInfo:t,rewardMints:n,associatedOnly:o=!0,checkCreateATAOwner:i=!1,computeBudgetConfig:r,txTipConfig:a,feePayer:s}){let u=this.createTxBuilder(s),c={};for(let d of n){let p=e.rewardDefaultInfos.find(P=>P.mint.address===d.toString());if(!p){this.logAndCreateError("reward mint error","not found reward mint",d);continue}let m=t.useSOLBalance&&d.equals(ee),{account:f,instructionParams:y}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new z.PublicKey(p.mint.programId),mint:d,notUseTokenAccount:m,owner:this.scope.ownerPubKey,skipCloseAccount:!m,createInfo:{payer:t.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:m?!1:o,checkCreateATAOwner:i});f||this.logAndCreateError("no money","ownerRewardAccount",this.scope.account.tokenAccountRawInfos),y&&u.addInstruction(y);let b=await this.getClmmPoolKeys(e.id),g=we.collectRewardInstructions({poolInfo:e,poolKeys:b,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccount:f},rewardMint:d});u.addInstruction(g),c=N(N({},c),g.address)}return u.addCustomComputeBudget(r),u.addTipInstruction(a),u.build({address:c})}async openLimitOrder({poolInfo:e,baseIn:t=!0,orderTick:n,amount:o,noneIndex:i=0,tickArrayBitmap:r,ownerInfo:a={useSOLBalance:!0},associatedOnly:s=!0,feePayer:u,computeBudgetConfig:c,txTipConfig:d,txVersion:p}){let m=new z.PublicKey(e.id),f=new z.PublicKey(e.programId),y=t?new z.PublicKey(e.mintA.address):new z.PublicKey(e.mintB.address),b=t?new z.PublicKey(e.mintB.address):new z.PublicKey(e.mintA.address),g=new z.PublicKey(e[t?"mintA":"mintB"].programId),P=new z.PublicKey(e[t?"mintB":"mintA"].programId),k=y.equals(ee),I=b.equals(ee),A=a.useSOLBalance&&k,h=a.useSOLBalance&&I,B=this.createTxBuilder(),S=A||!s?void 0:te(this.scope.ownerPubKey,y,g).publicKey;if(S)B.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,S,this.scope.ownerPubKey,y,g)]});else{let{account:X,instructionParams:Z}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:g,mint:y,notUseTokenAccount:A,owner:this.scope.ownerPubKey,skipCloseAccount:!A,createInfo:{payer:a.feePayer||this.scope.ownerPubKey,amount:o},associatedOnly:!A});S=X,Z&&B.addInstruction(Z)}let K=h||!s?void 0:te(this.scope.ownerPubKey,b,P).publicKey;if(K)B.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,K,this.scope.ownerPubKey,b,P)]});else{let{account:X,instructionParams:Z}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:P,mint:b,notUseTokenAccount:h,owner:this.scope.ownerPubKey,skipCloseAccount:!h,createInfo:{payer:a.feePayer||this.scope.ownerPubKey,amount:o},associatedOnly:!h});K=X,Z&&B.addInstruction(Z)}let x=Ou(f,this.scope.ownerPubKey,i).publicKey,C=await this.scope.connection.getAccountInfo(x),L=C?ku.decode(C.data).orderNonce:new ft.default(0),O=Lu(f,u||this.scope.ownerPubKey,x,L).publicKey,R=Te.getTickArrayStartIndex(n,e.config.tickSpacing),F=ve(f,m,R).publicKey,W=an(f,m,new z.PublicKey(e[t?"mintA":"mintB"].address)).publicKey,D=an(f,m,new z.PublicKey(e[t?"mintB":"mintA"].address)).publicKey;return B.addInstruction({instructions:[we.openLimitOrderInstruction(f,u||this.scope.ownerPubKey,m,F,x,O,S,K,W,D,y,b,g,i,t,n,o,r)]}),B.addCustomComputeBudget(c),B.addTipInstruction(d),B.versionBuild({txVersion:p,extInfo:{limitOrder:O}})}async increaseLimitOrder({poolInfo:e,limitOrder:t,amount:n,ownerInfo:o={useSOLBalance:!0},associatedOnly:i=!0,feePayer:r,computeBudgetConfig:a,txTipConfig:s,txVersion:u}){let c=new z.PublicKey(e.id),d=new z.PublicKey(e.programId),p=await this.scope.connection.getAccountInfo(t);p||this.logAndCreateError(`limit order ${t.toBase58()} not exist`);let m=po.decode(p.data),f=m.zeroForOne?new z.PublicKey(e.mintA.address):new z.PublicKey(e.mintB.address),y=new z.PublicKey(e[m.zeroForOne?"mintA":"mintB"].programId),b=f.equals(ee),g=o.useSOLBalance&&b,P=this.createTxBuilder(),k=g||!i?void 0:te(this.scope.ownerPubKey,f,y).publicKey;if(k)P.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,k,this.scope.ownerPubKey,f,y)]});else{let{account:B,instructionParams:S}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:y,mint:f,notUseTokenAccount:g,owner:this.scope.ownerPubKey,skipCloseAccount:!g,createInfo:{payer:o.feePayer||this.scope.ownerPubKey,amount:n},associatedOnly:!g});k=B,S&&P.addInstruction(S)}let I=an(d,c,new z.PublicKey(e[m.zeroForOne?"mintA":"mintB"].address)).publicKey,A=Te.getTickArrayStartIndex(m.tick,e.config.tickSpacing),h=ve(d,c,A).publicKey;return P.addInstruction({instructions:[we.increaseLimitOrderInstruction(d,r||this.scope.ownerPubKey,m.poolId,h,t,k,I,f,y,n)]}),P.addCustomComputeBudget(a),P.addTipInstruction(s),P.versionBuild({txVersion:u})}async decreaseLimitOrder({poolInfo:e,limitOrder:t,limitOrderInfo:n,amount:o,slippage:i=1e3,tickArrayBitmap:r,ownerInfo:a={useSOLBalance:!0},associatedOnly:s=!0,feePayer:u,computeBudgetConfig:c,txTipConfig:d,txVersion:p,forerunCreate:m}){let f=new z.PublicKey(e.id),y=new z.PublicKey(e.programId),b=n;if(!b){let X=await this.scope.connection.getAccountInfo(t);X||this.logAndCreateError(`limit order ${t.toBase58()} not exist`),b=po.decode(X.data)}let g=o.muln(1e4-i).divn(1e4),P=$n.getUnFilledAmount({orderInfo:b});(P.isZero()||o.gt(P))&&this.logAndCreateError(`amount should be less than unfulfilled amount: ${P.toString()}, amount: ${o.toString()}`);let[k,I]=b.zeroForOne?[new z.PublicKey(e.mintA.address),new z.PublicKey(e.mintB.address)]:[new z.PublicKey(e.mintB.address),new z.PublicKey(e.mintA.address)],[A,h]=b.zeroForOne?[new z.PublicKey(e.mintA.programId),new z.PublicKey(e.mintB.programId)]:[new z.PublicKey(e.mintB.programId),new z.PublicKey(e.mintA.programId)],[B,S]=[k.equals(ee),I.equals(ee)],[K,x]=[a.useSOLBalance&&B,a.useSOLBalance&&S],C=this.createTxBuilder(),L=K||!s?void 0:te(this.scope.ownerPubKey,k,A).publicKey,O=x||!s?void 0:te(this.scope.ownerPubKey,I,h).publicKey;if(L)C.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,L,this.scope.ownerPubKey,k,A)]});else{let{account:X,instructionParams:Z}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:A,mint:k,notUseTokenAccount:K,owner:this.scope.ownerPubKey,skipCloseAccount:!K,createInfo:{payer:a.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:!K});L=X,Z&&C.addInstruction(Z)}if(O)C.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,O,this.scope.ownerPubKey,I,h)]});else{let{account:X,instructionParams:Z}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:h,mint:I,notUseTokenAccount:x,owner:this.scope.ownerPubKey,skipCloseAccount:!x,createInfo:{payer:a.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:!x});O=X,Z&&C.addInstruction(Z)}let[R,F]=[an(y,f,k).publicKey,an(y,f,I).publicKey],W=Te.getTickArrayStartIndex(b.tick,e.config.tickSpacing),D=ve(y,f,W).publicKey;return C.addInstruction({instructions:[we.decreaseLimitOrderInstruction(y,u||this.scope.ownerPubKey,f,D,t,L,O,R,F,k,I,o,g,r)]}),C.addCustomComputeBudget(c),C.addTipInstruction(d),C.versionBuild({txVersion:p,extInfo:{forerunCreate:m}})}async closeLimitOrder({programId:e=Vn,limitOrder:t,autoWithdraw:n=!0,tickArrayBitmap:o,slippage:i=0,feePayer:r,computeBudgetConfig:a,txTipConfig:s,txVersion:u}){let c=await this.scope.connection.getAccountInfo(t);c||this.logAndCreateError(`limit order ${t.toBase58()} not exist`);let d=po.decode(c.data),p=$n.getUnFilledAmount({orderInfo:d});!n&&!p.isZero()&&this.logAndCreateError(`unfulfilled amount should be 0, (${p.toString()} remaining), please withdraw first or set autoWithdraw: true`);let m=this.createTxBuilder(),f=(await this.scope.api.fetchPoolById({ids:d.poolId.toBase58()}))[0];f||(f=(await this.getSimplePoolInfo(d.poolId)).poolInfo);let y=await gt.fetchTickArrayInfo({connection:this.scope.connection,programId:e,poolId:d.poolId,tick:d.tick,tickSpacing:f.config.tickSpacing}),b=$n.settleFilledOrder({orderInfo:d,tickInfo:y.ticks.find(g=>g.tick===d.tick)});if(p.isZero()){if(!b.isZero()){let g=await this.settleLimitOrder({limitOrder:t});m.addInstruction(N({},g.builder.AllTxData))}}else{let{builder:g}=await this.decreaseLimitOrder({poolInfo:f,limitOrder:t,limitOrderInfo:d,amount:p,tickArrayBitmap:o,slippage:i,txVersion:0});m.addInstruction({instructions:g.allInstructions})}return m.addInstruction({instructions:[we.closeLimitOrderInstruction(e,r||this.scope.ownerPubKey,this.scope.ownerPubKey,t)]}),m.addCustomComputeBudget(a),m.addTipInstruction(s),m.versionBuild({txVersion:u})}async closeAllLimitOrder({programId:e=Vn,limitOrders:t,autoWithdraw:n=!0,slippage:o=1e4,feePayer:i,computeBudgetConfig:r,txVersion:a}){let s=this.createTxBuilder(),c=(await Lt(this.scope.connection,t)).map((P,k)=>P?E(N({},po.decode(P.data)),{pda:t[k]}):null),d=c.filter(Boolean),p=d.map(P=>P.poolId.toBase58()),m=(await this.scope.api.fetchPoolById({ids:p.join(",")})).filter(Boolean),f={};m.forEach(P=>f[P.id]=P);let y=await gt.fetchMultipleTickArrayInfo({connection:this.scope.connection,tickInfoList:d.map(P=>({programId:e,poolId:P.poolId,tick:P.tick,tickSpacing:f[P.poolId.toString()].config.tickSpacing}))}),b={};y.forEach((P,k)=>{!P||(b[d[k].pda.toBase58()]=P)});let g=0;for(let P of t){let k=c[g];if(!k){g++;continue}let I=$n.getUnFilledAmount({orderInfo:k});!n&&!I.isZero()&&this.logAndCreateError(`${P.toBase58()} order unfulfilled amount should be 0 (${I.toString()} remaining), please withdraw first or set autoWithdraw: true`);let A=f[k.poolId.toBase58()],h=b[P.toBase58()],B=$n.settleFilledOrder({orderInfo:k,tickInfo:h.ticks.find(S=>S.tick===k.tick)});if(I.isZero()){if(!B.isZero()){let S=await this.settleLimitOrder({limitOrder:P,forerunCreate:!0});s.addInstruction(N({},S.builder.AllTxData))}}else{let{builder:S}=await this.decreaseLimitOrder({poolInfo:A,limitOrder:P,limitOrderInfo:k,amount:I,slippage:o,txVersion:0,forerunCreate:!0});s.addInstruction({instructions:S.allInstructions})}s.addInstruction({instructions:[we.closeLimitOrderInstruction(e,i||this.scope.ownerPubKey,this.scope.ownerPubKey,P)]}),g++}return a===0?s.sizeCheckBuildV0({computeBudgetConfig:r}):s.sizeCheckBuild({computeBudgetConfig:r})}async settleLimitOrder({limitOrder:e,feePayer:t,ownerInfo:n={useSOLBalance:!0},associatedOnly:o=!0,computeBudgetConfig:i,txTipConfig:r,txVersion:a,forerunCreate:s}){let u=await this.scope.connection.getAccountInfo(e);u||this.logAndCreateError(`limit order ${e.toBase58()} not exist`);let c=po.decode(u.data),d=(await this.scope.api.fetchPoolById({ids:c.poolId.toBase58()}))[0];d||(d=(await this.getSimplePoolInfo(c.poolId)).poolInfo);let p=c.zeroForOne?d.mintB:d.mintA,[m,f]=[new z.PublicKey(p.address),new z.PublicKey(p.programId)],y=new z.PublicKey(d.programId),b=this.createTxBuilder(),g=m.equals(ee),P=n.useSOLBalance&&g,k=P||!o?void 0:te(this.scope.ownerPubKey,m,f).publicKey;if(k)b.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,k,this.scope.ownerPubKey,m,f)]});else{let{account:A,instructionParams:h}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:f,mint:m,notUseTokenAccount:P,owner:this.scope.ownerPubKey,skipCloseAccount:!P,createInfo:{payer:n.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:!P});k=A,h&&b.addInstruction(h)}let I=Te.getTickArrayStartIndex(c.tick,d.config.tickSpacing);return b.addInstruction({instructions:[we.settleLimitOrderInstruction(y,t||this.scope.ownerPubKey,c.poolId,ve(y,c.poolId,I).publicKey,e,k,an(y,c.poolId,m).publicKey,m,f)]}),b.addCustomComputeBudget(i),b.addTipInstruction(r),b.versionBuild({txVersion:a,extInfo:{forerunCreate:s}})}async settleAllLimitOrder({limitOrders:e,feePayer:t,ownerInfo:n={useSOLBalance:!0},associatedOnly:o=!0,computeBudgetConfig:i,txVersion:r}){let a=await Lt(this.scope.connection,e),s=[],u=a.map((m,f)=>{if(!m)return;let y=po.decode(m.data);return s.push(y.poolId.toString()),E(N({},y),{pda:e[f]})}),c=await this.scope.api.fetchPoolById({ids:s.join(",")});c.filter(Boolean).length||(c=(await Promise.all(s.map(f=>this.getSimplePoolInfo(f)))).map(f=>f.poolInfo));let d=this.createTxBuilder(),p={};for(let m of u){if(!m)continue;let f=c.find(B=>B.id===m.poolId.toBase58());if(!f)continue;let y=new z.PublicKey(f.programId),b=new z.PublicKey(m.zeroForOne?f.mintB.address:f.mintA.address),g=b.equals(ee),P=n.useSOLBalance&&g,k=new z.PublicKey(g?We.TOKEN_PROGRAM_ID:(await this.scope.token.getTokenInfo(b)).programId),I=p[b.toBase58()],A=P||!o?void 0:te(this.scope.ownerPubKey,b,k).publicKey;if(I)A=I;else{if(A)d.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,A,this.scope.ownerPubKey,b,k)]});else{let{account:B,instructionParams:S}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:k,mint:b,notUseTokenAccount:P,owner:this.scope.ownerPubKey,skipCloseAccount:!P,createInfo:{payer:n.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:!P});A=B,S&&d.addInstruction(S)}p[b.toBase58()]=A}let h=Te.getTickArrayStartIndex(m.tick,f.config.tickSpacing);d.addInstruction({instructions:[we.settleLimitOrderInstruction(y,t||this.scope.ownerPubKey,m.poolId,ve(y,m.poolId,h).publicKey,m.pda,A,an(y,m.poolId,b).publicKey,b,k)]})}return r===0?d.sizeCheckBuildV0({computeBudgetConfig:i}):d.sizeCheckBuild({computeBudgetConfig:i})}async swap({poolInfo:e,poolKeys:t,inputMint:n,amountIn:o,amountOutMin:i,priceLimit:r,observationId:a,ownerInfo:s,remainingAccounts:u,associatedOnly:c=!0,checkCreateATAOwner:d=!1,txVersion:p,computeBudgetConfig:m,txTipConfig:f,feePayer:y}){let b=this.createTxBuilder(y),g=n.toString()===e.mintA.address.toString(),P=s.useSOLBalance&&e.mintA.address.toString()===ee.toBase58(),k=s.useSOLBalance&&e.mintB.address.toString()===ee.toBase58(),I;!r||r.equals(new Gn.default(0))?I=g?xt.add(new ft.default(1)):St.sub(new ft.default(1)):I=ae.priceToSqrtPriceX64(r,e.mintA.decimals,e.mintB.decimals);let A;if(!A){let{account:S,instructionParams:K}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintA.programId,mint:new z.PublicKey(e.mintA.address),notUseTokenAccount:P,owner:this.scope.ownerPubKey,skipCloseAccount:!P,createInfo:P||!g?{payer:s.feePayer||this.scope.ownerPubKey,amount:g?o:0}:void 0,associatedOnly:P?!1:c,checkCreateATAOwner:d});A=S,K&&b.addInstruction(K)}let h;if(!h){let{account:S,instructionParams:K}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintB.programId,mint:new z.PublicKey(e.mintB.address),notUseTokenAccount:k,owner:this.scope.ownerPubKey,skipCloseAccount:!k,createInfo:k||g?{payer:s.feePayer||this.scope.ownerPubKey,amount:g?0:o}:void 0,associatedOnly:k?!1:c,checkCreateATAOwner:d});h=S,K&&b.addInstruction(K)}(!A||!h)&&this.logAndCreateError("user do not have token account",{tokenA:e.mintA.address,tokenB:e.mintB.address,ownerTokenAccountA:A,ownerTokenAccountB:h,mintAUseSOLBalance:P,mintBUseSOLBalance:k,associatedOnly:c});let B=t!=null?t:await this.getClmmPoolKeys(e.id.toString());return b.addInstruction(we.makeSwapBaseInInstructions({poolInfo:E(N({},e),{id:e.id.toString(),programId:e.programId.toString()}),poolKeys:B,observationId:a,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:A,tokenAccountB:h},inputMint:new z.PublicKey(n),amountIn:o,amountOutMin:i,sqrtPriceLimitX64:$,remainingAccounts:u})),b.addCustomComputeBudget(m),b.addTipInstruction(f),b.versionBuild({txVersion:p})}async swapBaseOut({poolInfo:e,poolKeys:t,outputMint:n,amountOut:o,amountInMax:i,priceLimit:r,observationId:a,ownerInfo:s,remainingAccounts:u,associatedOnly:c=!0,checkCreateATAOwner:d=!1,txVersion:p,computeBudgetConfig:m,txTipConfig:f,feePayer:y}){let b=this.createTxBuilder(y),g=n.toString()===e.mintB.address.toString(),P=s.useSOLBalance&&e.mintA.address.toString()===ee.toBase58(),k=s.useSOLBalance&&e.mintB.address.toString()===ee.toBase58(),I;!r||r.equals(new Gn.default(0))?I=g?xt.add(new ft.default(1)):St.sub(new ft.default(1)):I=ae.priceToSqrtPriceX64(r,e.mintA.decimals,e.mintB.decimals);let A;if(!A){let{account:S,instructionParams:K}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintA.programId,mint:new z.PublicKey(e.mintA.address),notUseTokenAccount:P,owner:this.scope.ownerPubKey,skipCloseAccount:!P,createInfo:P||!g?{payer:s.feePayer||this.scope.ownerPubKey,amount:g?i:0}:void 0,associatedOnly:P?!1:c,checkCreateATAOwner:d});A=S,K&&b.addInstruction(K)}let h;if(!h){let{account:S,instructionParams:K}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:e.mintB.programId,mint:new z.PublicKey(e.mintB.address),notUseTokenAccount:k,owner:this.scope.ownerPubKey,skipCloseAccount:!k,createInfo:k||g?{payer:s.feePayer||this.scope.ownerPubKey,amount:g?0:i}:void 0,associatedOnly:k?!1:c,checkCreateATAOwner:d});h=S,K&&b.addInstruction(K)}(!A||!h)&&this.logAndCreateError("user do not have token account",{tokenA:e.mintA.address,tokenB:e.mintB.address,ownerTokenAccountA:A,ownerTokenAccountB:h,mintAUseSOLBalance:P,mintBUseSOLBalance:k,associatedOnly:c});let B=t!=null?t:await this.getClmmPoolKeys(e.id.toString());return b.addInstruction(we.makeSwapBaseOutInstructions({poolInfo:E(N({},e),{id:e.id.toString(),programId:e.programId.toString()}),poolKeys:B,observationId:a,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:A,tokenAccountB:h},outputMint:new z.PublicKey(n),amountOut:o,amountInMax:i,sqrtPriceLimitX64:$,remainingAccounts:u})),b.addCustomComputeBudget(m),b.addTipInstruction(f),b.versionBuild({txVersion:p})}async harvestAllRewards({allPoolInfo:e,allPositions:t,lockInfo:n,ownerInfo:o,associatedOnly:i=!0,checkCreateATAOwner:r=!1,programId:a,txVersion:s,computeBudgetConfig:u,feePayer:c,lockProgram:d=Zo,lockAuth:p=zi,clmmProgram:m=Vn}){var k,I;let f={};for(let A of this.scope.account.tokenAccountRawInfos)i?te(this.scope.ownerPubKey,A.accountInfo.mint,a).publicKey.equals(A.pubkey)&&(f[A.accountInfo.mint.toString()]=A.pubkey):f[A.accountInfo.mint.toString()]=A.pubkey;let y=Object.values(t).flat().map(A=>A.nftMint),b=await qe(this.scope.connection,y.map(A=>({pubkey:A}))),g={};b.forEach(A=>{var h,B;g[A.pubkey.toBase58()]=(B=(h=A==null?void 0:A.accountInfo)==null?void 0:h.owner)!=null?B:null});let P=this.createTxBuilder(c);for(let A of Object.values(e)){if(t[A.id]===void 0||!t[A.id].find(R=>!R.liquidity.isZero()||R.rewardInfos.find(F=>!F.rewardAmountOwed.isZero())))continue;let h=A,B=o.useSOLBalance&&h.mintA.address===ee.toString(),S=o.useSOLBalance&&h.mintB.address===ee.toString(),K=f[h.mintA.address];if(!K)if(B){let{account:R,instructionParams:F}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:h.mintA.programId,mint:new z.PublicKey(h.mintA.address),notUseTokenAccount:B,owner:this.scope.ownerPubKey,skipCloseAccount:!B,createInfo:{payer:o.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:B?!1:i,checkCreateATAOwner:r});K=R,F&&P.addInstruction(F)}else{let R=new z.PublicKey(h.mintA.address);K=this.scope.account.getAssociatedTokenAccount(R,new z.PublicKey(h.mintA.programId)),P.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,K,this.scope.ownerPubKey,R,new z.PublicKey(h.mintA.programId))]})}let x=f[h.mintB.address];if(!x)if(S){let{account:R,instructionParams:F}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:h.mintB.programId,mint:new z.PublicKey(h.mintB.address),notUseTokenAccount:S,owner:this.scope.ownerPubKey,skipCloseAccount:!S,createInfo:{payer:o.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:S?!1:i,checkCreateATAOwner:r});x=R,F&&P.addInstruction(F)}else{let R=new z.PublicKey(h.mintB.address);x=this.scope.account.getAssociatedTokenAccount(R,new z.PublicKey(h.mintB.programId)),P.addInstruction({instructions:[(0,We.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,x,this.scope.ownerPubKey,R,new z.PublicKey(h.mintB.programId))]})}f[h.mintA.address]=K,f[h.mintB.address]=x;let C=[];for(let R of h.rewardDefaultInfos){let F=o.useSOLBalance&&R.mint.address===ee.toString(),W=f[R.mint.address];if(!W){let{account:D,instructionParams:X}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:new z.PublicKey(R.mint.programId),mint:new z.PublicKey(R.mint.address),notUseTokenAccount:F,owner:this.scope.ownerPubKey,skipCloseAccount:!F,createInfo:{payer:o.feePayer||this.scope.ownerPubKey,amount:0},associatedOnly:F?!1:i});W=D,X&&P.addInstruction(X)}f[R.mint.address]=W,C.push(W)}let L=await this.getClmmPoolKeys(h.id),O=[];for(let R=0;R<L.rewardInfos.length;R++)O.push({poolRewardVault:new z.PublicKey(L.rewardInfos[R].vault),ownerRewardVault:C[R],rewardMint:new z.PublicKey(L.rewardInfos[R].mint.address)});for(let R of t[A.id]){let F=(k=n==null?void 0:n[A.id])==null?void 0:k[R.nftMint.toBase58()];if(F){let W=te(this.scope.ownerPubKey,F.lockNftMint,We.TOKEN_PROGRAM_ID).publicKey,D=Te.getTickArrayStartIndex(R.tickLower,L.config.tickSpacing),X=Te.getTickArrayStartIndex(R.tickUpper,L.config.tickSpacing),{publicKey:Z}=ve(new z.PublicKey(L.programId),F.poolId,D),{publicKey:H}=ve(new z.PublicKey(L.programId),F.poolId,X),{publicKey:ne}=gn(new z.PublicKey(L.programId),F.poolId,R.tickLower,R.tickUpper),se=No(d,F.lockNftMint).publicKey,J=we.harvestLockPositionInstructionV2({programId:d,auth:p,lockPositionId:se,clmmProgram:m,lockOwner:this.scope.ownerPubKey,lockNftMint:F.lockNftMint,lockNftAccount:W,positionNftAccount:F.nftAccount,positionId:F.positionId,poolId:F.poolId,protocolPosition:ne,vaultA:new z.PublicKey(L.vault.A),vaultB:new z.PublicKey(L.vault.B),tickArrayLower:Z,tickArrayUpper:H,userVaultA:K,userVaultB:x,mintA:new z.PublicKey(L.mintA.address),mintB:new z.PublicKey(L.mintB.address),rewardAccounts:O,exTickArrayBitmap:He(m,F.poolId).publicKey});P.addInstruction({instructions:[J],instructionTypes:[Y.ClmmHarvestLockPosition],lookupTableAddress:L.lookupTableAccount?[L.lookupTableAccount]:[]})}else{let W=we.decreaseLiquidityInstructions({poolInfo:h,poolKeys:L,ownerPosition:R,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:K,tokenAccountB:x,rewardAccounts:C},liquidity:new ft.default(0),amountMinA:new ft.default(0),amountMinB:new ft.default(0),nft2022:(I=g[R.nftMint.toBase58()])==null?void 0:I.equals(We.TOKEN_2022_PROGRAM_ID)});P.addInstruction(W)}}}return s===0?P.sizeCheckBuildV0({computeBudgetConfig:u}):P.sizeCheckBuild({computeBudgetConfig:u})}async getWhiteListMint({programId:e}){let t=await this.scope.connection.getAccountInfo(ai(e).publicKey);return t?wu.decode(t.data).whitelistMints.filter(o=>!o.equals(z.PublicKey.default)):[]}async getOwnerPositionInfo({programId:e=Vn}){await this.scope.account.fetchWalletTokenAccounts();let n=this.scope.account.tokenAccountRawInfos.filter(r=>r.accountInfo.amount.eq(new ft.default(1))).map(r=>sn(new z.PublicKey(e),r.accountInfo.mint).publicKey),o=await this.scope.connection.getMultipleAccountsInfo(n),i=[];return o.forEach(r=>{if(!r)return;let a=tr.decode(r.data);i.push(a)}),i}async getOwnerLockedPositionInfo({programId:e=Zo}){await this.scope.account.fetchWalletTokenAccounts();let n=this.scope.account.tokenAccountRawInfos.filter(s=>s.accountInfo.amount.eq(new ft.default(1))).map(s=>No(new z.PublicKey(e),s.accountInfo.mint).publicKey),o=await this.scope.connection.getMultipleAccountsInfo(n),i=[];o.forEach(s=>{if(!s)return;let u=Tu.decode(s.data);i.push(u)});let r=await this.scope.connection.getMultipleAccountsInfo(i.map(s=>s.positionId)),a=[];return r.forEach(s=>{if(!s)return;let u=tr.decode(s.data);a.push(u)}),i.map((s,u)=>({position:a[u],lockInfo:s}))}async getRpcClmmPoolInfo({poolId:e}){return(await this.getRpcClmmPoolInfos({poolIds:[e]}))[String(e)]}async getRpcClmmPoolInfos({poolIds:e,config:t}){let n=await qe(this.scope.connection,e.map(i=>({pubkey:new z.PublicKey(i)})),t),o={};for(let i=0;i<e.length;i++){let r=n[i];if(r===null||!r.accountInfo)throw Error("fetch pool info error: "+String(e[i]));let a=mo.decode(r.accountInfo.data),s=ae.sqrtPriceX64ToPrice(a.sqrtPriceX64,a.mintDecimalsA,a.mintDecimalsB).toNumber();o[String(e[i])]=E(N({},a),{currentPrice:s,programId:r.accountInfo.owner})}return o}async getComputeClmmPoolInfos({clmmPoolsRpcInfo:e,mintInfos:t}){let n=new Set(Object.keys(e).map(s=>e[s].configId.toBase58())),o=await qe(this.scope.connection,Array.from(n).map(s=>({pubkey:new z.PublicKey(s)}))),i={};o.forEach(s=>{!s.accountInfo||(i[s.pubkey.toBase58()]=ba.decode(s.accountInfo.data))});let r=await gt.fetchComputeMultipleClmmInfo({connection:this.scope.connection,rpcDataMap:e,poolList:Object.keys(e).map(s=>{var d,p,m,f;let[u,c]=[e[s].mintA.toBase58(),e[s].mintB.toBase58()];return{id:s,programId:e[s].programId.toBase58(),mintA:At({address:u,decimals:e[s].mintDecimalsA,programId:t[u].programId.toBase58()||We.TOKEN_PROGRAM_ID.toBase58(),extensions:{feeConfig:(d=t[u])!=null&&d.feeConfig?Nn((p=t[u])==null?void 0:p.feeConfig):void 0}}),mintB:At({address:c,decimals:e[s].mintDecimalsB,programId:t[c].programId.toBase58()||We.TOKEN_PROGRAM_ID.toBase58(),extensions:{feeConfig:(m=t[c])!=null&&m.feeConfig?Nn((f=t[c])==null?void 0:f.feeConfig):void 0}}),price:e[s].currentPrice,config:E(N({},i[e[s].configId.toBase58()]),{id:e[s].configId.toBase58(),fundFeeRate:0,description:"",defaultRange:0,defaultRangePoint:[]})}})}),a=await gt.fetchMultiplePoolTickArrays({connection:this.scope.connection,poolKeys:Object.values(r)});return{computeClmmPoolInfo:r,computePoolTickData:a}}async getPoolInfoFromRpc(e){let t=await this.getRpcClmmPoolInfo({poolId:e}),n=new Set([t.mintA.toBase58(),t.mintB.toBase58(),...t.rewardInfos.filter(c=>!c.mint.equals(z.PublicKey.default)).map(c=>c.mint.toBase58())]),o=await ho({connection:this.scope.connection,mints:Array.from(n).map(c=>new z.PublicKey(c))}),{computeClmmPoolInfo:i,computePoolTickData:r}=await this.scope.clmm.getComputeClmmPoolInfos({clmmPoolsRpcInfo:{[e]:t},mintInfos:o}),a=await qe(this.scope.connection,[{pubkey:t.vaultA},{pubkey:t.vaultB}]),s=Eu(i[e],o);if(!a[0].accountInfo||!a[1].accountInfo)throw new Error("pool vault data not found");s.mintAmountA=Number(bn.decode(a[0].accountInfo.data).amount.toString()),s.mintAmountB=Number(bn.decode(a[1].accountInfo.data).amount.toString());let u=E(N({},i[e]),{exBitmapAccount:i[e].exBitmapAccount.toBase58(),observationId:i[e].observationId.toBase58(),id:e,programId:t.programId.toBase58(),openTime:t.startTime.toString(),vault:{A:t.vaultA.toBase58(),B:t.vaultB.toBase58()},config:s.config,rewardInfos:i[e].rewardInfos.filter(c=>!c.vault.equals(z.PublicKey.default)).map(c=>{var d;return{mint:At({address:c.mint.toBase58(),programId:We.TOKEN_PROGRAM_ID.toBase58(),decimals:(d=o[c.mint.toBase58()].decimals)!=null?d:6}),vault:c.vault.toBase58()}})});return{poolInfo:s,poolKeys:u,computePoolInfo:i[e],tickData:r,rpcPoolInfo:t,tickArrays:Object.values(r[e])}}async getSwapPoolInfo(e,t=!0){let{poolInfo:n,rpcData:o}=await this.getSimplePoolInfo(e),i=await this.scope.connection.getAccountInfo(o.configId),r=ba.decode(i.data),a=new z.PublicKey(n.programId),s=new z.PublicKey(e),u=await vu(a,this.scope.connection,s,o.tickCurrent,r.tickSpacing,o.tickArrayBitmap,t);return{poolInfo:n,rpcData:o,configInfo:r,tickArrays:u}}async getSimplePoolInfo(e){let t=await this.getRpcClmmPoolInfo({poolId:e}),n=await this.scope.connection.getMultipleAccountsInfo([t.mintA,t.mintB]);return{poolInfo:{id:e.toString(),programId:t.programId.toString(),mintA:{address:t.mintA.toString(),programId:n[0].owner.toString(),decimals:t.mintDecimalsA},mintB:{address:t.mintB.toString(),programId:n[1].owner.toString(),decimals:t.mintDecimalsB},config:{id:t.configId.toBase58(),tickSpacing:t.tickSpacing}},rpcData:t}}async getMultipleSimplePoolInfo(e){let t=await this.getRpcClmmPoolInfos({poolIds:e}),n=new Set(Object.values(t).map(r=>[r.mintA.toBase58(),r.mintB.toBase58()]).flat()),o=await ho({connection:this.scope.connection,mints:Array.from(n).map(r=>new z.PublicKey(r))}),i={};return e.forEach(r=>{let a=t[r.toString()];if(!a)return null;let s=o[a.mintA.toBase58()],u=o[a.mintB.toBase58()];i[r.toString()]={poolInfo:{id:r.toString(),programId:a.programId.toString(),mintA:{address:a.mintA.toString(),programId:s.programId.toString(),decimals:a.mintDecimalsA},mintB:{address:a.mintB.toString(),programId:u.programId.toString(),decimals:a.mintDecimalsB},config:{id:a.configId.toBase58(),tickSpacing:a.tickSpacing}},rpcData:a}}),i}};var Ra=require("@solana/web3.js");var Ba=v([V("instruction")]),xa=v([V("instruction")]),Qp=v([w("rewardState"),w("rewardOpenTime"),w("rewardEndTime"),w("rewardLastUpdateTime"),w("totalReward"),w("totalRewardEmissioned"),w("rewardClaimed"),w("rewardPerSecond"),pe("accRewardPerShare"),M("rewardVault"),M("rewardMint"),M("rewardSender"),w("rewardType"),j(w(),15,"padding")]),Bm=v([w("state"),w("nonce"),M("lpVault"),M("rewardVault"),M(),M(),w(),w(),w("totalReward"),pe("perShareReward"),w("lastSlot"),w("perSlotReward")]),xm=v([w("state"),w("nonce"),M("lpVault"),M("rewardVaultA"),w("totalRewardA"),pe("perShareRewardA"),w("perSlotRewardA"),V("option"),M("rewardVaultB"),Be(7),w("totalRewardB"),pe("perShareRewardB"),w("perSlotRewardB"),w("lastSlot"),M()]),Sm=v([w(),w("state"),w("nonce"),w("validRewardTokenNum"),pe("rewardMultiplier"),w("rewardPeriodMax"),w("rewardPeriodMin"),w("rewardPeriodExtend"),M("lpMint"),M("lpVault"),j(Qp,5,"rewardInfos"),M("creator"),M(),j(w(),32,"padding")]),Wu=new Proxy(Bm,{get(l,e,t){return e==="decode"?(...n)=>{let o=l.decode(...n);return E(N({},o),{version:3,rewardInfos:[{rewardVault:o.rewardVault,totalReward:o.totalReward,perSlotReward:o.perSlotReward,perShareReward:o.perShareReward}]})}:Reflect.get(l,e,t)}}),qu=new Proxy(xm,{get(l,e,t){return e==="decode"?(...n)=>{let o=l.decode(...n);return E(N({},o),{version:5,rewardInfos:[{rewardVault:o.rewardVaultA,totalReward:o.totalRewardA,perSlotReward:o.perSlotRewardA,perShareReward:o.perShareRewardA},{rewardVault:o.rewardVaultB,totalReward:o.totalRewardB,perSlotReward:o.perSlotRewardB,perShareReward:o.perShareRewardB}]})}:Reflect.get(l,e,t)}}),mi=new Proxy(Sm,{get(l,e,t){return e==="decode"?(...n)=>{let o=l.decode(...n);return E(N({},o),{version:6,rewardInfos:o.rewardInfos.map(i=>{var r;return E(N({},i),{rewardType:((r=Object.entries(Jn).find(a=>String(a[1])===i.rewardType.toString()))!=null?r:["Standard SPL"])[0]})})})}:Reflect.get(l,e,t)}}),Km=v([w("isSet"),w("rewardPerSecond"),w("rewardOpenTime"),w("rewardEndTime"),w("rewardType")]),Sa=v([V("instruction"),w("nonce"),j(Km,5,"rewardTimeInfo")]),Ka=v([V("instruction"),w("rewardReopenTime"),w("rewardEndTime"),w("rewardPerSecond")]),Ca=v([V("instruction"),w("isSet"),w("rewardPerSecond"),w("rewardOpenTime"),w("rewardEndTime"),w("rewardType")]),Zp=v([w("state"),M("id"),M("owner"),w("deposited"),j(w(),1,"rewardDebts")]),di=v([w("state"),M("id"),M("owner"),w("deposited"),j(pe(),1,"rewardDebts"),w(""),w("voteLockedBalance"),j(w(),15)]),jp=v([w("state"),M("id"),M("owner"),w("deposited"),j(w(),2,"rewardDebts")]),Uu=v([w("state"),M("id"),M("owner"),w("deposited"),j(pe(),2,"rewardDebts"),j(w(),17)]),Gu=v([w(),w("state"),M("id"),M("owner"),w("deposited"),j(pe(),5,"rewardDebts"),j(w(),16)]),Xt=v([V("instruction"),w("amount")]),Cm=v([M("mint"),M("grantAuthority"),w("baselineVoteWeightScaledFactor"),w("maxExtraLockupVoteWeightScaledFactor"),w("lockupSaturationSecs"),Xl("digitShift"),j(V(),7,"reserved1"),j(w(),7,"reserved2")]),zu=v([Be(8),M("governanceProgramId"),M("realm"),M("realmGoverningTokenMint"),M("realmAuthority"),j(V(),32,"reserved1"),j(Cm,4,"votingMints"),ni("timeOffset"),V("bump"),j(V(),7,"reserved2"),j(w(),11,"reserved3")]),Rm=v([ni("startTime"),ni("endTime"),V("kind"),j(V(),15,"reserved")]),Lm=v([j(Rm,1,"lockup"),w("amountDeposited_native"),w("amountInitiallyLockedNative"),tt("isUsed"),tt("allowClawback"),V("votingMintConfigIdx"),j(V(),29,"reserved")]),Xu=v([Be(8),M("voterAuthority"),M("registrar"),j(Lm,32,"deposits"),V("voterBump"),V("voterWweightRecordBump"),j(V(),94,"reserved")]);var Om=require("@solana/spl-token"),Uk=Se("Raydium_farm_config"),Yu=new Ra.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Hu=new Ra.PublicKey("FrspKwj8i3pNmKwXreTveC4fu7KL5ZbGeXdZBe2XViu1"),$p=Om.NATIVE_MINT,Jp=new Ra.PublicKey("3TRTX4dXUpp2eqxi3tvQDFYUV7SdDJjcPE3Y4mbtftaX"),pi={3:Wu,5:qu,6:mi},fi={3:di,5:Uu,6:Gu},La=l=>[3,4,5,6].indexOf(l)!==-1,Oa=l=>{var r;let{version:e,rewardInfos:t,rewardTokenAccountsPublicKeys:n}=l,o=`rewardInfo:${JSON.stringify(t)}, rewardAccount:${JSON.stringify(n)}`,i={3:()=>{if(t.length!==1||n.length!==1)return`rewardInfos or rewardTokenAccounts lengths not equal 1: ${o}`},5:()=>{if(t.length!==n.length)return`rewardInfos and rewardTokenAccounts lengths not equal: ${o}`},6:()=>{if(!n.length||t.length!==n.length)return`no rewardTokenAccounts or rewardInfos and rewardTokenAccounts lengths not equal: ${o}`}};return(r=i[e])==null?void 0:r.call(i)},Jn={"Standard SPL":0,"Option tokens":1},un={[Es.toString()]:3,[Ds.toString()]:4,[Ws.toString()]:5,[Qo.toString()]:6,[Rn.FARM_PROGRAM_ID_V3.toString()]:3,[Rn.FARM_PROGRAM_ID_V4.toString()]:4,[Rn.FARM_PROGRAM_ID_V5.toString()]:5,[Rn.FARM_PROGRAM_ID_V6.toString()]:6};var Q=require("@solana/web3.js"),lr=ie(require("bn.js")),Ct=require("@solana/spl-token");function Na(l,e,t){return re([e.toBuffer(),Buffer.from("registrar","utf8"),t.toBuffer()],l)}function Ma(l,e){return re([e.toBuffer(),Buffer.from("voting_mint_seed","utf8")],l)}function Fa(l,e){return re([e.toBuffer()],l)}function va(l,e,t){return re([e.toBuffer(),Buffer.from("voter","utf8"),t.toBuffer()],l)}function _a(l,e,t){return re([e.toBuffer(),Buffer.from("voter-weight-record","utf8"),t.toBuffer()],l)}function Va(l,e,t,n){return re([Buffer.from("governance","utf8"),e.toBuffer(),t.toBuffer(),n.toBuffer()],l)}var en=ie(require("bn.js"));var cr=Se("Raydium.farm.util");function yi({programId:l,poolId:e,mint:t,type:n}){let{publicKey:o}=re([e.toBuffer(),t.toBuffer(),Buffer.from(n==="lpVault"?"lp_vault_associated_seed":n==="rewardVault"?"reward_vault_associated_seed":"","utf-8")],l);return o}function Wt({programId:l,poolId:e,owner:t,version:n}){let{publicKey:o}=re([e.toBuffer(),t.toBuffer(),Buffer.from(n===6?"farmer_info_associated_seed":"staker_info_v2_associated_seed","utf-8")],l);return o}var Qu=({programId:l,poolId:e})=>re([e.toBuffer()],l);function Zu(l){return{isSet:new en.default(1),rewardPerSecond:fe(l.perSecond),rewardOpenTime:fe(l.openTime),rewardEndTime:fe(l.endTime),rewardType:fe(Jn[l.rewardType])}}function Ea(l){return fe(l.endTime).sub(fe(l.openTime)).mul(fe(l.perSecond))}function Vo(l){let e=fi[l];return e||cr.logWithError("invalid version",l),e}function Nm(l){let e=pi[l];return e||cr.logWithError("invalid version",l),e}function Mm(l,e,t,n){if(l.version===3||l.version===5){if(l.lastSlot.gte(new en.default(t)))return l;let o=new en.default(t).sub(l.lastSlot);l.lastSlot=new en.default(t);for(let i of l.rewardInfos){if(e.amount.eq(new en.default(0)))continue;let r=i.perSlotReward.mul(o);i.perShareReward=i.perShareReward.add(r.mul(new en.default(10).pow(new en.default(l.version===3?9:15))).div(e.amount)),i.totalReward=i.totalReward.add(r)}}else if(l.version===6)for(let o of l.rewardInfos){if(o.rewardState.eq(new en.default(0)))continue;let i=en.default.min(new en.default(n),o.rewardEndTime);if(o.rewardOpenTime.gte(i))continue;let a=i.sub(o.rewardLastUpdateTime).mul(o.rewardPerSecond),s=o.totalReward.sub(o.totalRewardEmissioned);s.lt(a)?(a=s,o.rewardLastUpdateTime=o.rewardLastUpdateTime.add(s.div(o.rewardPerSecond))):o.rewardLastUpdateTime=i,!e.amount.eq(new en.default(0))&&(o.accRewardPerShare=o.accRewardPerShare.add(a.mul(l.rewardMultiplier).div(e.amount)),o.totalRewardEmissioned=o.totalRewardEmissioned.add(a))}return l}async function ef({connection:l,farmPools:e,owner:t,config:n,chainTime:o}){let i=!1,r=!1,a=new en.default(10),s=[];for(let p of e){let m=it(p);m.version===6?r=!0:i=!0,s.push({pubkey:m.id,version:m.version,key:"state",poolId:m.id},{pubkey:m.lpVault,version:m.version,key:"lpVault",poolId:m.id}),t&&s.push({pubkey:Wt({programId:m.programId,poolId:m.id,owner:t,version:p.version}),version:m.version,key:"ledger",poolId:m.id})}let u={},c=await qe(l,s,n);for(let{pubkey:p,version:m,key:f,poolId:y,accountInfo:b}of c){let g=y.toBase58();if(u[g]=N({},u[g]),f==="state"){let P=Nm(m);(!b||!b.data||b.data.length!==P.span)&&cr.logWithError(`invalid farm state account info, pools.id, ${p}`),u[g].state=P.decode(b.data)}else if(f==="lpVault")(!b||!b.data||b.data.length!==bn.span)&&cr.logWithError(`invalid farm lp vault account info, pools.lpVault, ${p}`),u[g].lpVault=bn.decode(b.data);else if(f==="ledger"){let P=Vo(m);b&&b.data&&(b.data.length!==P.span&&cr.logWithError(`invalid farm ledger account info, ledger, ${p}`),u[g].ledger=P.decode(b.data))}}let d=r||i?await l.getSlot():0;for(let p of Object.keys(u))u[p]!==void 0&&(u[p].state=Mm(u[p].state,u[p].lpVault,d,o));for(let[p,{state:m,ledger:f}]of Object.entries(u))if(f){let y=m.version===6?m.rewardMultiplier:m.rewardInfos.length===1?a.pow(new en.default(9)):a.pow(new en.default(15)),b=m.rewardInfos.map((g,P)=>{let k=f.rewardDebts[P];return f.deposited.mul(m.version===6?g.accRewardPerShare:g.perShareReward).div(y).sub(k)});u[p].wrapped=E(N({},u[p].wrapped),{pendingRewards:b})}return u}function tf(l,e=Date.now()){if(l.version===6){let t=l.state.rewardInfos;if(t.every(({rewardOpenTime:n})=>hl(e,n.toNumber(),{unit:"s"})))return"upcoming pool";if(t.every(({rewardEndTime:n})=>Il(e,n.toNumber(),{unit:"s"})))return"closed pool"}else{let t=l.state.rewardInfos.map(({perSlotReward:n})=>n);if(t.length===2){if(String(t[0])==="0"&&String(t[1])!=="0")return"normal fusion pool";if(String(t[0])!=="0"&&String(t[1])!=="0")return"dual fusion pool";if(String(t[0])==="0"&&String(t[1])==="0")return"closed pool"}else if(t.length===1&&String(t[0])==="0")return"closed pool"}}async function Da(l,e,t,n){let o=await l.getAccountInfo(e);if(o===null)throw Error("registrar info check error");let r=zu.decode(o.data).votingMints.findIndex(c=>c.mint.equals(n));if(r===-1)throw Error("find voter mint error");let a=await l.getAccountInfo(t);if(a===null)return{index:r,isInit:!1};let u=Xu.decode(a.data).deposits.findIndex(c=>c.isUsed&&c.votingMintConfigIdx===r);return u===-1?{index:r,isInit:!1}:{index:u,isInit:!0}}var nf=Se("Raydium_farm_instruction"),mr={voterStakeRegistryCreateVoter:Buffer.from([6,24,245,52,243,255,148,25]),voterStakeRegistryCreateDepositEntry:Buffer.from([185,131,167,186,159,125,19,67]),voterStakeRegistryDeposit:Buffer.from([242,35,198,137,82,225,242,182]),voterStakeRegistryWithdraw:Buffer.from([183,18,70,156,148,109,161,34]),voterStakeRegistryUpdateVoterWeightRecord:Buffer.from([45,185,3,36,109,190,115,169])};function bi(l){let{version:e,id:t,ledger:n,programId:o,owner:i}=l,r={3:9,5:10}[e];r||nf.logWithError(`invalid farm pool version: ${e}`);let a=Buffer.alloc(Ba.span);Ba.encode({instruction:r},a);let s=[T({pubkey:t}),T({pubkey:n}),T({pubkey:i,isWritable:!1}),T({pubkey:Q.SystemProgram.programId,isWritable:!1}),T({pubkey:Q.SYSVAR_RENT_PUBKEY,isWritable:!1})];return{instruction:new Q.TransactionInstruction({programId:o,keys:s,data:a}),instructionType:Y.FarmV3CreateLedger}}function ju(l){var n;let e=Buffer.alloc(Sa.span);Sa.encode({instruction:0,nonce:new lr.default(l.nonce),rewardTimeInfo:l.rewardInfoConfig},e);let t=[...Os,T({pubkey:l.farmId}),T({pubkey:l.farmAuthority,isWritable:!1}),T({pubkey:l.lpVault}),T({pubkey:l.lpMint,isWritable:!1}),T({pubkey:l.lockVault}),T({pubkey:l.lockMint,isWritable:!1}),T({pubkey:(n=l.lockUserAccount)!=null?n:Ot}),T({pubkey:l.owner,isWritable:!1,isSigner:!0})];for(let o of l.rewardInfo)t.push(T({pubkey:o.rewardMint,isWritable:!1}),T({pubkey:o.rewardVault}),T({pubkey:o.userRewardToken}));return{instruction:new Q.TransactionInstruction({programId:l.programId,keys:t,data:e}),instructionType:Y.FarmV6Create}}function $u(l){let e=Buffer.alloc(xa.span);xa.encode({instruction:5},e);let t=[T({pubkey:Ct.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:l.id}),T({pubkey:l.authority,isWritable:!1}),T({pubkey:l.lpVault,isWritable:!1}),T({pubkey:l.rewardVault}),T({pubkey:l.userRewardToken}),T({pubkey:l.owner,isWritable:!1,isSigner:!0})];return{instruction:new Q.TransactionInstruction({programId:l.programId,keys:t,data:e}),instructionType:Y.FarmV6CreatorWithdraw}}function Fm(l,e,t,n,o,i,r,a,s,u,c,d,p){let m=v([V("depositEntryIndex"),w("amount")]),f=[{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:Ct.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:Gr,isSigner:!1,isWritable:!1}],y=Buffer.alloc(m.span);m.encode({depositEntryIndex:d,amount:p},y);let b=Buffer.from([...mr.voterStakeRegistryDeposit,...y]);return new Q.TransactionInstruction({keys:f,programId:l,data:b})}function vm(l,e,t,n){let o=v([]),i=[{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:Q.SystemProgram.programId,isSigner:!1,isWritable:!1}],r=Buffer.alloc(o.span);o.encode({},r);let a=Buffer.from([...mr.voterStakeRegistryUpdateVoterWeightRecord,...r]);return new Q.TransactionInstruction({keys:i,programId:l,data:a})}function _m(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f){let y=v([V("depositEntryIndex"),w("amount")]),b=[{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!0,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:Ct.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:Gr,isSigner:!1,isWritable:!1}],g=Buffer.alloc(y.span);y.encode({depositEntryIndex:m,amount:f},g);let P=Buffer.from([...mr.voterStakeRegistryWithdraw,...g]);return new Q.TransactionInstruction({keys:b,programId:l,data:P})}function Vm(l,e,t,n,o,i){let r=v([V("ins")]),a=[{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!0,isWritable:!0},{pubkey:Q.SystemProgram.programId,isSigner:!1,isWritable:!1}],s=Buffer.alloc(r.span);return r.encode({ins:23},s),new Q.TransactionInstruction({keys:a,programId:l,data:s})}function Em(l,e,t,n,o,i,r,a){let s=v([V("voterBump"),V("voterWeightRecordBump")]),u=[{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!0,isWritable:!0},{pubkey:Q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:It,isSigner:!1,isWritable:!1},{pubkey:Gr,isSigner:!1,isWritable:!1}],c=Buffer.alloc(s.span);s.encode({voterBump:r,voterWeightRecordBump:a},c);let d=Buffer.from([...mr.voterStakeRegistryCreateVoter,...c]);return new Q.TransactionInstruction({keys:u,programId:l,data:d})}function Dm(l,e,t,n,o,i,r,a,s,u,c,d){let p=v([V("depositEntryIndex"),V("kind"),V("option"),w("startTs"),je("periods"),tt("allowClawback")]),m=[{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!0,isWritable:!1},{pubkey:i,isSigner:!0,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:Q.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:Ct.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:Ct.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:It,isSigner:!1,isWritable:!1}],f=Buffer.alloc(p.span);p.encode({depositEntryIndex:a,kind:s,option:u===void 0?0:1,startTs:u,periods:c,allowClawback:d},f);let y=Buffer.from([...mr.voterStakeRegistryCreateDepositEntry,...f]);return new Q.TransactionInstruction({keys:m,programId:l,data:y})}async function of({connection:l,programId:e,governanceProgramId:t,voteWeightAddinProgramId:n,realm:o,communityTokenMint:i,owner:r,poolId:a,tokenProgram:s}){let u=Na(n,o,i).publicKey,c=Wt({programId:e,poolId:a,owner:r,version:3}),d=await l.getAccountInfo(c);if(d===null)throw Error("user is not staker");let p=di.decode(d.data),m=p.deposited.sub(p.voteLockedBalance);if(console.log("amount",m.toString()),m.eq(new lr.default(0)))throw Error("user do not has new stake amount");let f=Ma(e,a).publicKey,y=Fa(e,a).publicKey,{publicKey:b,nonce:g}=va(n,u,r),P=te(b,f,s).publicKey,{publicKey:k,nonce:I}=_a(n,u,r),A=Va(t,o,i,r).publicKey,h=[],B=te(r,f,s).publicKey;if(await l.getAccountInfo(B)===null&&h.push((0,Ct.createAssociatedTokenAccountIdempotentInstruction)(r,B,r,f)),await l.getAccountInfo(b)===null){let L=Vm(t,o,r,i,r,A);h.push(L,Em(n,u,b,k,r,r,g,I))}let{index:x,isInit:C}=await Da(l,u,b,f);return C||h.push(Dm(n,u,b,P,r,r,f,x,0,void 0,0,!1)),h.push(Fm(n,u,b,P,B,r,c,a,f,y,e,x,m),vm(n,u,b,k)),h}async function rf({connection:l,programId:e,governanceProgramId:t,voteWeightAddinProgramId:n,realm:o,communityTokenMint:i,owner:r,poolId:a,tokenProgram:s}){let u=Na(n,o,i).publicKey,c=Wt({programId:e,poolId:a,owner:r,version:3}),d=await l.getAccountInfo(c);if(d===null)throw Error("user is not staker");let p=di.decode(d.data);if(p.voteLockedBalance.eq(new lr.default(0)))throw Error("user has vote locked balance = 0");let m=Ma(e,a).publicKey,f=Fa(e,a).publicKey,{publicKey:y}=va(n,u,r),b=te(y,m,s).publicKey,{publicKey:g}=_a(n,u,r),P=Va(t,o,i,r).publicKey,k=[],{index:I,isInit:A}=await Da(l,u,y,m);if(!A)throw Error("deposit entry index check error");return k.push(_m(n,u,y,r,P,g,b,te(r,m,s).publicKey,c,a,m,f,e,I,p.voteLockedBalance)),k}function Wa({payer:l,rewardVault:e,userRewardTokenPub:t,farmKeys:n,rewardInfo:o}){let i=Buffer.alloc(Ka.span);Ka.encode({instruction:3,rewardReopenTime:fe(o.openTime),rewardEndTime:fe(o.endTime),rewardPerSecond:fe(o.perSecond)},i);let r=[T({pubkey:Ct.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:n.id}),T({pubkey:n.lpVault,isWritable:!1}),T({pubkey:e}),T({pubkey:t}),T({pubkey:l,isWritable:!1,isSigner:!0})];return new Q.TransactionInstruction({programId:n.programId,keys:r,data:i})}function qa({payer:l,userRewardTokenPub:e,farmKeys:t,rewardVault:n,rewardInfo:o}){let i=Buffer.alloc(Ca.span);Ca.encode({instruction:4,isSet:new lr.default(1),rewardPerSecond:fe(o.perSecond),rewardOpenTime:fe(o.openTime),rewardEndTime:fe(o.endTime),rewardType:fe(Jn[o.rewardType])},i);let r=[...Os,T({pubkey:t.id}),T({pubkey:t.authority,isWritable:!1}),T({pubkey:o.mint,isWritable:!1}),T({pubkey:n}),T({pubkey:e}),T({pubkey:l,isWritable:!1,isSigner:!0})];return new Q.TransactionInstruction({programId:t.programId,keys:r,data:i})}function af(l){let{farmInfo:e,farmKeys:t,version:n,lpAccount:o,rewardAccounts:i,owner:r,instruction:a,amount:s,deposit:u}=l,[c,d]=[new Q.PublicKey(e.programId),new Q.PublicKey(e.id)],p=Wt({programId:c,poolId:d,owner:r,version:n}),m=Buffer.alloc(Xt.span);Xt.encode({instruction:a,amount:s},m);let f=n===6?[T({pubkey:Ct.TOKEN_PROGRAM_ID,isWritable:!1}),...u?[T({pubkey:Q.SystemProgram.programId,isWritable:!1})]:[],T({pubkey:d}),T({pubkey:new Q.PublicKey(t.authority),isWritable:!1}),T({pubkey:new Q.PublicKey(t.lpVault)}),T({pubkey:p}),T({pubkey:r,isWritable:!1,isSigner:!0}),T({pubkey:o})]:[T({pubkey:d}),T({pubkey:new Q.PublicKey(t.authority),isWritable:!1}),T({pubkey:p}),T({pubkey:r,isWritable:!1,isSigner:!0}),T({pubkey:o}),T({pubkey:new Q.PublicKey(t.lpVault)}),T({pubkey:i[0]}),T({pubkey:new Q.PublicKey(t.rewardInfos[0].vault)}),T({pubkey:Q.SYSVAR_CLOCK_PUBKEY,isWritable:!1}),T({pubkey:Ct.TOKEN_PROGRAM_ID,isWritable:!1})];if(n===5)for(let y=1;y<t.rewardInfos.length;y++)f.push(T({pubkey:i[y]})),f.push(T({pubkey:new Q.PublicKey(t.rewardInfos[y].vault)}));if(n===6)for(let y=0;y<t.rewardInfos.length;y++)f.push(T({pubkey:new Q.PublicKey(t.rewardInfos[y].vault)})),f.push(T({pubkey:i[y]}));return new Q.TransactionInstruction({programId:c,keys:f,data:m})}function gi(l){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r}=l,[a,s]=[new Q.PublicKey(e.programId),new Q.PublicKey(e.id)],u=Wt({programId:a,poolId:s,owner:i,version:6}),c=Buffer.alloc(Xt.span);Xt.encode({instruction:2,amount:fe(r)},c);let d=[T({pubkey:Ct.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:s}),T({pubkey:new Q.PublicKey(t.authority),isWritable:!1}),T({pubkey:new Q.PublicKey(t.lpVault)}),T({pubkey:u}),T({pubkey:i,isWritable:!1,isSigner:!0}),T({pubkey:n})];for(let p=0;p<t.rewardInfos.length;p++)d.push(T({pubkey:new Q.PublicKey(t.rewardInfos[p].vault)})),d.push(T({pubkey:o[p]}));return new Q.TransactionInstruction({programId:a,keys:d,data:c})}function Pi(l){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=l,[s,u]=[new Q.PublicKey(e.programId),new Q.PublicKey(e.id)],c=Wt({programId:s,poolId:u,owner:i,version:5}),d=Buffer.alloc(Xt.span);Xt.encode({instruction:12,amount:fe(r)},d);let p=[T({pubkey:u}),T({pubkey:new Q.PublicKey(t.authority),isWritable:!1}),T({pubkey:c}),T({pubkey:i,isWritable:!1,isSigner:!0}),T({pubkey:n}),T({pubkey:new Q.PublicKey(t.lpVault)}),T({pubkey:o[0]}),T({pubkey:new Q.PublicKey(t.rewardInfos[0].vault)}),T({pubkey:Q.SYSVAR_CLOCK_PUBKEY,isWritable:!1}),T({pubkey:Ct.TOKEN_PROGRAM_ID,isWritable:!1})];for(let m=1;m<t.rewardInfos.length;m++)p.push(T({pubkey:o[m]})),p.push(T({pubkey:new Q.PublicKey(t.rewardInfos[m].vault)}));if(a)for(let m of a)p.push(T({pubkey:m}));return new Q.TransactionInstruction({programId:s,keys:p,data:d})}function Ju(l){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=l,[s,u]=[new Q.PublicKey(e.programId),new Q.PublicKey(e.id)],c=v([V("instruction"),w("amount")]),d=[T({pubkey:u}),T({pubkey:new Q.PublicKey(t.authority),isWritable:!1}),T({pubkey:a[0]}),T({pubkey:i,isSigner:!0,isWritable:!1}),T({pubkey:n}),T({pubkey:new Q.PublicKey(t.lpVault)}),T({pubkey:o[0]}),T({pubkey:new Q.PublicKey(t.rewardInfos[0].vault)}),T({pubkey:Q.SYSVAR_CLOCK_PUBKEY,isWritable:!1}),T({pubkey:Ct.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:o[1]}),T({pubkey:new Q.PublicKey(t.rewardInfos[1].vault)})],p=Buffer.alloc(c.span);return c.encode({instruction:2,amount:r},p),new Q.TransactionInstruction({keys:d,programId:s,data:p})}function Ai(l){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=l,[s,u]=[new Q.PublicKey(e.programId),new Q.PublicKey(e.id)],c=Wt({programId:s,poolId:u,owner:i,version:3}),d=Buffer.alloc(Xt.span);Xt.encode({instruction:11,amount:fe(r)},d);let p=[T({pubkey:u}),T({pubkey:new Q.PublicKey(t.authority),isWritable:!1}),T({pubkey:c}),T({pubkey:i,isWritable:!1,isSigner:!0}),T({pubkey:n}),T({pubkey:new Q.PublicKey(t.lpVault)}),T({pubkey:o[0]}),T({pubkey:new Q.PublicKey(t.rewardInfos[0].vault)}),T({pubkey:Q.SYSVAR_CLOCK_PUBKEY,isWritable:!1}),T({pubkey:Ct.TOKEN_PROGRAM_ID,isWritable:!1})];if(a)for(let m of a)p.push(T({pubkey:m}));return new Q.TransactionInstruction({programId:s,keys:p,data:d})}function ec(l){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=l,[s,u]=[new Q.PublicKey(e.programId),new Q.PublicKey(e.id)],c=Wt({programId:s,poolId:u,owner:i,version:3}),d=Buffer.alloc(Xt.span);Xt.encode({instruction:10,amount:fe(r)},d);let p=[T({pubkey:u}),T({pubkey:new Q.PublicKey(t.authority),isWritable:!1}),T({pubkey:c}),T({pubkey:i,isWritable:!1,isSigner:!0}),T({pubkey:n}),T({pubkey:new Q.PublicKey(t.lpVault)}),T({pubkey:o[0]}),T({pubkey:new Q.PublicKey(t.rewardInfos[0].vault)}),T({pubkey:Q.SYSVAR_CLOCK_PUBKEY,isWritable:!1}),T({pubkey:Ct.TOKEN_PROGRAM_ID,isWritable:!1})];if(a)for(let m of a)p.push(T({pubkey:m}));return new Q.TransactionInstruction({programId:s,keys:p,data:d})}function tc(l){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r,userAuxiliaryLedgers:a}=l,[s,u]=[new Q.PublicKey(e.programId),new Q.PublicKey(e.id)],c=Wt({programId:s,poolId:u,owner:i,version:5}),d=Buffer.alloc(Xt.span);Xt.encode({instruction:11,amount:fe(r)},d);let p=[T({pubkey:u}),T({pubkey:new Q.PublicKey(t.authority),isWritable:!1}),T({pubkey:c}),T({pubkey:i,isWritable:!1,isSigner:!0}),T({pubkey:n}),T({pubkey:new Q.PublicKey(t.lpVault)}),T({pubkey:o[0]}),T({pubkey:new Q.PublicKey(t.rewardInfos[0].vault)}),T({pubkey:Q.SYSVAR_CLOCK_PUBKEY,isWritable:!1}),T({pubkey:Ct.TOKEN_PROGRAM_ID,isWritable:!1})];for(let m=1;m<t.rewardInfos.length;m++)p.push(T({pubkey:o[m]})),p.push(T({pubkey:new Q.PublicKey(t.rewardInfos[m].vault)}));if(a)for(let m of a)p.push(T({pubkey:m}));return new Q.TransactionInstruction({programId:s,keys:p,data:d})}function nc(l){let{farmInfo:e,farmKeys:t,lpAccount:n,rewardAccounts:o,owner:i,amount:r}=l,[a,s]=[new Q.PublicKey(e.programId),new Q.PublicKey(e.id)],u=Wt({programId:a,poolId:s,owner:i,version:6}),c=Buffer.alloc(Xt.span);Xt.encode({instruction:1,amount:fe(r)},c);let d=[T({pubkey:Ct.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:Q.SystemProgram.programId,isWritable:!1}),T({pubkey:s}),T({pubkey:new Q.PublicKey(t.authority),isWritable:!1}),T({pubkey:new Q.PublicKey(t.lpVault)}),T({pubkey:u}),T({pubkey:i,isWritable:!1,isSigner:!0}),T({pubkey:n})];for(let p=0;p<t.rewardInfos.length;p++)d.push(T({pubkey:new Q.PublicKey(t.rewardInfos[p].vault)})),d.push(T({pubkey:o[p]}));return new Q.TransactionInstruction({programId:a,keys:d,data:c})}var to=ie(require("bn.js")),dr=class extends at{async _getUserRewardInfo({payer:e,rewardInfo:t}){if(t.mint.equals(Ot)){let n=await jn({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:e,amount:Ea(E(N({},t),{openTime:t.openTime.toString(),endTime:t.endTime.toString()}))});return{rewardPubKey:n.addresses.newAccount,newInstruction:n}}return{rewardPubKey:await this.scope.account.getCreatedTokenAccount({mint:t.mint,associatedOnly:!1})}}async create({poolInfo:e,rewardInfos:t,payer:n,programId:o=Qo,txVersion:i,feePayer:r,lockProgram:a}){var B,S;this.checkDisabled(),this.scope.checkOwner();let u={lpMint:new Ce.PublicKey(e.lpMint.address),lockInfo:{lockMint:(B=a==null?void 0:a.mint)!=null?B:Yu,lockVault:(S=a==null?void 0:a.vault)!=null?S:Hu},version:6,rewardInfos:t,programId:o},c=this.createTxBuilder(r),d=n!=null?n:this.scope.ownerPubKey,p=st({fromPublicKey:d,programId:u.programId}),m=await this.scope.connection.getMinimumBalanceForRentExemption(mi.span);c.addInstruction({instructions:[Ce.SystemProgram.createAccountWithSeed({fromPubkey:d,basePubkey:d,seed:p.seed,newAccountPubkey:p.publicKey,lamports:m,space:mi.span,programId:u.programId})]});let{publicKey:f,nonce:y}=Qu({programId:new Ce.PublicKey(u.programId),poolId:p.publicKey}),b=yi({programId:u.programId,poolId:p.publicKey,mint:u.lpMint,type:"lpVault"}),g=[],P=[];for(let K of u.rewardInfos){K.openTime>=K.endTime&&this.logAndCreateError("start time error","rewardInfo.rewardOpenTime",K.openTime.toString()),isNaN(Jn[K.rewardType])&&this.logAndCreateError("rewardType error",K.rewardType),Number(K.perSecond)<=0&&this.logAndCreateError("rewardPerSecond error",K.perSecond),g.push(Zu(K));let{rewardPubKey:x,newInstruction:C}=await this._getUserRewardInfo({rewardInfo:K,payer:d});C&&c.addInstruction(C),x||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts);let L=K.mint.equals(Ot)?new Ce.PublicKey(ht.address):K.mint;P.push({rewardMint:L,rewardVault:yi({programId:u.programId,poolId:p.publicKey,mint:L,type:"rewardVault"}),userRewardToken:x})}let{account:k,instructionParams:I}=await this.scope.account.getOrCreateTokenAccount({mint:new Ce.PublicKey(u.lockInfo.lockMint),owner:this.scope.ownerPubKey,skipCloseAccount:!1,createInfo:{payer:this.scope.ownerPubKey,amount:0},associatedOnly:!1});I&&c.addInstruction(I),k||this.logAndCreateError("cannot found lock vault","tokenAccounts",this.scope.account.tokenAccounts);let{instruction:A,instructionType:h}=ju({farmId:p.publicKey,owner:this.scope.ownerPubKey,farmAuthority:f,lpVault:b,lpMint:u.lpMint,lockVault:u.lockInfo.lockVault,lockMint:u.lockInfo.lockMint,lockUserAccount:k,programId:u.programId,rewardInfo:P,rewardInfoConfig:g,nonce:y});return c.addInstruction({instructions:[A],instructionTypes:[h]}).versionBuild({txVersion:i,extInfo:{farmId:p.publicKey,farmAuthority:f,lpVault:b,lockUserAccount:k,nonce:y}})}async restartReward({farmInfo:e,payer:t,newRewardInfo:n,txVersion:o,feePayer:i}){var g;let r=un[e.programId];r!==6&&this.logAndCreateError("invalid farm version ",r);let a=it((await this.scope.api.fetchFarmKeysById({ids:e.id}))[0]),s={id:a.id,rewardInfos:e.rewardInfos,lpVault:a.lpVault,programId:a.programId};n.openTime>=n.endTime&&this.logAndCreateError("start time error","newRewardInfo",n);let u=t||this.scope.ownerPubKey,c=n.mint.equals(Ot)?new Ce.PublicKey(ht.address):n.mint,d=s.rewardInfos.findIndex(P=>new Ce.PublicKey(P.mint.address).equals(c)),p=a.rewardInfos[d];p||this.logAndCreateError("configuration does not exist","rewardMint",c);let m=(g=p.vault)!=null?g:Ot,f=this.createTxBuilder(i),{rewardPubKey:y,newInstruction:b}=await this._getUserRewardInfo({rewardInfo:n,payer:u});return b&&f.addInstruction(b),y||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts),f.addInstruction({instructions:[Wa({payer:this.scope.ownerPubKey,rewardVault:m,userRewardTokenPub:y,farmKeys:s,rewardInfo:n})],instructionTypes:[Y.FarmV6Restart]}).versionBuild({txVersion:o})}async restartRewards({farmInfo:e,payer:t,newRewardInfos:n,txVersion:o,feePayer:i}){var d;let r=un[e.programId];r!==6&&this.logAndCreateError("invalid farm version ",r);let a=it((await this.scope.api.fetchFarmKeysById({ids:e.id}))[0]),s={id:a.id,rewardInfos:e.rewardInfos,lpVault:a.lpVault,programId:a.programId};n.forEach(p=>{p.openTime>=p.endTime&&this.logAndCreateError("start time error","newRewardInfo",p)});let u=t||this.scope.ownerPubKey,c=this.createTxBuilder(i);for(let p of n){let m=p.mint.equals(Ot)?new Ce.PublicKey(ht.address):p.mint,f=s.rewardInfos.findIndex(I=>new Ce.PublicKey(I.mint.address).equals(m)),y=a.rewardInfos[f];y||this.logAndCreateError("configuration does not exist","rewardMint",m);let b=(d=y.vault)!=null?d:Ot,{rewardPubKey:g,newInstruction:P}=await this._getUserRewardInfo({rewardInfo:p,payer:u});P&&c.addInstruction(P),g||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts);let k=Wa({payer:this.scope.ownerPubKey,rewardVault:b,userRewardTokenPub:g,farmKeys:s,rewardInfo:p});c.addInstruction({instructions:[k],instructionTypes:[Y.FarmV6Restart]})}return c.versionBuild({txVersion:o})}async addNewRewardToken(e){let{txVersion:t,farmInfo:n,newRewardInfo:o,payer:i,feePayer:r}=e,a=un[n.programId];a!==6&&this.logAndCreateError("invalid farm version ",a);let s=it((await this.scope.api.fetchFarmKeysById({ids:n.id}))[0]),u=i!=null?i:this.scope.ownerPubKey,c=this.createTxBuilder(r),d=o.mint.equals(Ot)?new Ce.PublicKey(ht.address):o.mint,p=yi({programId:new Ce.PublicKey(n.programId),poolId:new Ce.PublicKey(n.id),mint:d,type:"rewardVault"}),{rewardPubKey:m,newInstruction:f}=await this._getUserRewardInfo({rewardInfo:o,payer:u});return f&&c.addInstruction(f),m||this.logAndCreateError("annot found target token accounts",this.scope.account.tokenAccounts),o.mint=d,c.addInstruction({instructions:[qa({payer:this.scope.ownerPubKey,userRewardTokenPub:m,farmKeys:s,rewardVault:p,rewardInfo:o})],instructionTypes:[Y.FarmV6CreatorAddReward]}).versionBuild({txVersion:t})}async addNewRewardsToken(e){let{txVersion:t,farmInfo:n,newRewardInfos:o,payer:i,feePayer:r}=e,a=un[n.programId];a!==6&&this.logAndCreateError("invalid farm version ",a);let s=it((await this.scope.api.fetchFarmKeysById({ids:n.id}))[0]),u=i!=null?i:this.scope.ownerPubKey,c=this.createTxBuilder(r);for(let d of o){let p=d.mint.equals(Ot)?new Ce.PublicKey(ht.address):d.mint,m=yi({programId:new Ce.PublicKey(n.programId),poolId:new Ce.PublicKey(n.id),mint:p,type:"rewardVault"}),{rewardPubKey:f,newInstruction:y}=await this._getUserRewardInfo({rewardInfo:d,payer:u});y&&c.addInstruction(y),f||this.logAndCreateError("cannot found target token accounts",this.scope.account.tokenAccounts);let b=qa({payer:this.scope.ownerPubKey,userRewardTokenPub:f,farmKeys:s,rewardVault:m,rewardInfo:E(N({},d),{mint:p})});c.addInstruction({instructions:[b],instructionTypes:[Y.FarmV6CreatorAddReward]})}return c.versionBuild({txVersion:t})}async deposit(e){let{txVersion:t,farmInfo:n,amount:o,feePayer:i,useSOLBalance:r,associatedOnly:a=!0,checkCreateATAOwner:s=!1,userAuxiliaryLedgers:u,computeBudgetConfig:c,txTipConfig:d}=e;this.scope.availability.addFarm===!1&&this.logAndCreateError("farm deposit feature disabled in your region");let{rewardInfos:p,programId:m}=n,f=un[m];f===4&&this.logAndCreateError("V4 has suspended deposits:",n.programId),La(f)||this.logAndCreateError("invalid farm program:",n.programId);let[y,b]=[new Ce.PublicKey(n.programId),new Ce.PublicKey(n.id)],g=(await this.scope.api.fetchFarmKeysById({ids:n.id}))[0],P=Wt({programId:y,poolId:b,owner:this.scope.ownerPubKey,version:f}),k=this.createTxBuilder(i);k.addCustomComputeBudget(c),k.addTipInstruction(d);let I={};for(let R of this.scope.account.tokenAccounts)if(a){let F=te(this.scope.ownerPubKey,R.mint,R.programId).publicKey;R.publicKey&&F.equals(R.publicKey)&&(I[R.mint.toString()]=R.publicKey)}else I[R.mint.toString()]=R.publicKey;let A=g.lpMint,h=I[A.address];h||this.logAndCreateError("you don't have any lp","lp zero",I);let B=[];for(let R of p){let F=r&&R.mint.address===ee.toString(),W=I[R.mint.address];if(!W){let{account:D,instructionParams:X}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:R.mint.programId,mint:new Ce.PublicKey(R.mint.address),notUseTokenAccount:F,createInfo:{payer:i||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!F,associatedOnly:F?!1:a,checkCreateATAOwner:s});W=D,X&&k.addInstruction(X)}I[R.mint.address]=W,B.push(W)}let S,K=await this.scope.connection.getAccountInfo(P);if(K&&(S=Vo(f).decode(K.data)),n.programId!==Qo.toString()&&n.programId!==Rn.FARM_PROGRAM_ID_V6.toString()&&!S){let{instruction:R,instructionType:F}=bi({id:b,programId:y,version:f,ledger:P,owner:this.scope.ownerPubKey});k.addInstruction({instructions:[R],instructionTypes:[F]})}let x=Oa({version:f,rewardInfos:p,rewardTokenAccountsPublicKeys:B});x&&this.logAndCreateError(x);let C={amount:fe(o),owner:this.scope.ownerPubKey,farmInfo:n,farmKeys:g,lpAccount:h,rewardAccounts:B,userAuxiliaryLedgers:u==null?void 0:u.map(R=>new Ce.PublicKey(R))},L=f===6?nc(C):f===5?tc(C):ec(C),O={3:Y.FarmV3Deposit,5:Y.FarmV5Deposit,6:Y.FarmV6Deposit};return k.addInstruction({instructions:[L],instructionTypes:[O[f]]}).versionBuild({txVersion:t})}async withdraw(e){let{txVersion:t,farmInfo:n,amount:o,deposited:i,useSOLBalance:r,feePayer:a,associatedOnly:s=!0,checkCreateATAOwner:u=!1,userAuxiliaryLedgers:c,computeBudgetConfig:d,txTipConfig:p}=e,{rewardInfos:m}=n;this.scope.availability.removeFarm===!1&&this.logAndCreateError("farm withdraw feature disabled in your region");let f=un[n.programId];La(f)||this.logAndCreateError("invalid farm program:",n.programId);let y=(await this.scope.api.fetchFarmKeysById({ids:n.id}))[0],b=this.createTxBuilder(a);b.addCustomComputeBudget(d),b.addTipInstruction(p);let g={};for(let x of this.scope.account.tokenAccounts)if(s){let C=te(this.scope.ownerPubKey,x.mint).publicKey;x.publicKey&&C.equals(x.publicKey)&&(g[x.mint.toString()]=x.publicKey)}else g[x.mint.toString()]=x.publicKey;if(f!==4){let x=Wt({programId:new Ce.PublicKey(n.programId),poolId:new Ce.PublicKey(n.id),owner:this.scope.ownerPubKey,version:f}),C=await this.scope.connection.getAccountInfo(x);if(C)Vo(f).decode(C.data).deposited.isZero()&&this.logAndCreateError("no deposited lp",{farmId:n.id});else if(f!==6){let{instruction:L,instructionType:O}=bi({id:new Ce.PublicKey(y.id),programId:new Ce.PublicKey(y.programId),version:f,ledger:x,owner:this.scope.ownerPubKey});b.addInstruction({instructions:[L],instructionTypes:[O]})}}i&&i.isZero()&&!(c||[]).length&&this.logAndCreateError("no deposited lp",{farmId:n.id});let P=y.lpMint.address,k=r&&P===ee.toString(),I=g[P.toString()];if(!I){let{account:x,instructionParams:C}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:y.lpMint.programId,mint:new Ce.PublicKey(P),notUseTokenAccount:k,createInfo:{payer:a||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!0,associatedOnly:k?!1:s,checkCreateATAOwner:u});I=x,C&&b.addInstruction(C)}g[P.toString()]=I;let A=[];for(let x of m){let C=r&&x.mint.address===ee.toString(),L=g[x.mint.address];if(!L){let{account:O,instructionParams:R}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:x.mint.programId,mint:new Ce.PublicKey(x.mint.address),notUseTokenAccount:C,createInfo:{payer:a||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!C,associatedOnly:C?!1:s,checkCreateATAOwner:u});L=O,R&&b.addInstruction(R)}g[x.mint.address]=L,A.push(L)}let h=Oa({version:f,rewardInfos:m,rewardTokenAccountsPublicKeys:A});h&&this.logAndCreateError(h);let B={amount:fe(o),owner:this.scope.ownerPubKey,farmInfo:n,farmKeys:y,lpAccount:I,rewardAccounts:A,userAuxiliaryLedgers:c==null?void 0:c.map(x=>new Ce.PublicKey(x))},S=f===6?gi(B):f===5?Pi(B):f===4?Ju(B):Ai(B),K={3:Y.FarmV3Withdraw,4:Y.FarmV4Withdraw,5:Y.FarmV5Withdraw,6:Y.FarmV6Withdraw};return b.addInstruction({instructions:[S],instructionTypes:[K[f]]}).versionBuild({txVersion:t})}async withdrawFarmReward({farmInfo:e,withdrawMint:t,txVersion:n,computeBudgetConfig:o,txTipConfig:i,feePayer:r}){var y;this.scope.checkOwner();let a=it((await this.scope.api.fetchFarmKeysById({ids:e.id}))[0]),s=un[e.programId];s!==6&&this.logAndCreateError("invalid farm version",s);let u=a.rewardInfos.find(b=>Vt(b.mint.address).equals(Vt(t)));u||this.logAndCreateError("withdraw mint error","rewardInfos",e);let c=(y=u==null?void 0:u.vault)!=null?y:Ot,d=this.createTxBuilder(r),p;if(t.equals(Ot)||t.equals(Ce.PublicKey.default)){let b=await jn({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:this.scope.ownerPubKey,amount:Ea(E(N({},u),{openTime:u.openTime,endTime:u.endTime,perSecond:new eo.default(u.perSecond).mul(10**u.mint.decimals).toString()}))});p=b.addresses.newAccount,d.addInstruction(b)}else{let b=await this.scope.account.getCreatedTokenAccount({mint:t});b?p=b:(p=await this.scope.account.getAssociatedTokenAccount(t),d.addInstruction({instructions:[(0,oc.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,p,this.scope.ownerPubKey,t)],instructionTypes:[Y.CreateATA]}))}let{instruction:m,instructionType:f}=$u({programId:a.programId,id:a.id,authority:a.authority,lpVault:a.lpVault,rewardVault:c,userRewardToken:p,owner:this.scope.ownerPubKey});return d.addCustomComputeBudget(o),d.addTipInstruction(i),d.addInstruction({instructions:[m],instructionTypes:[f]}).versionBuild({txVersion:n})}async harvestAllRewards(e){let{farmInfoList:t,useSOLBalance:n,feePayer:o,associatedOnly:i=!0,checkCreateATAOwner:r=!1,userAuxiliaryLedgers:a,txVersion:s,computeBudgetConfig:u}=e,c=this.createTxBuilder(o),d={};for(let f of this.scope.account.tokenAccounts)if(i){let y=te(this.scope.ownerPubKey,f.mint).publicKey;f.publicKey&&y.equals(f.publicKey)&&(d[f.mint.toString()]=f.publicKey)}else d[f.mint.toString()]=f.publicKey;let m=(await this.scope.api.fetchFarmKeysById({ids:Object.values(t).map(f=>f.id).join(",")})).reduce((f,y)=>E(N({},f),{[y.id]:y}),{});for(let f of Object.values(t)){let{programId:y,lpMint:b,rewardInfos:g,id:P}=f,k=un[y],I=b.address,A=n&&I===ee.toString(),h=d[I];if(!h){let{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:b.programId,mint:new Ce.PublicKey(I),notUseTokenAccount:A,createInfo:{payer:o||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!0,associatedOnly:A?!1:i,checkCreateATAOwner:r});h=L,O&&c.addInstruction(O)}d[I.toString()]=h;let B=[];for(let L of g){let O=n&&L.mint.address===ee.toString(),R=d[L.mint.address];if(!R)if(O){let{account:F,instructionParams:W}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:L.mint.programId,mint:new Ce.PublicKey(L.mint.address),notUseTokenAccount:O,createInfo:{payer:o||this.scope.ownerPubKey,amount:0},owner:this.scope.ownerPubKey,skipCloseAccount:!O,associatedOnly:O?!1:i,checkCreateATAOwner:r});R=F,W&&c.addInstruction(W)}else{let F=new Ce.PublicKey(L.mint.address);R=this.scope.account.getAssociatedTokenAccount(F),c.addInstruction({instructions:[(0,oc.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,R,this.scope.ownerPubKey,F)]})}d[L.mint.address]=R,B.push(R)}let S=m[P],K={amount:$,owner:this.scope.ownerPubKey,farmInfo:f,farmKeys:S,lpAccount:h,rewardAccounts:B,userAuxiliaryLedgers:a==null?void 0:a.map(L=>new Ce.PublicKey(L))},x=k===6?gi(K):k===5?Pi(K):Ai(K),C={3:Y.FarmV3Withdraw,5:Y.FarmV5Withdraw,6:Y.FarmV6Withdraw};c.addInstruction({instructions:[x],instructionTypes:[C[k]]})}return s===1?c.sizeCheckBuild({computeBudgetConfig:u}):c.sizeCheckBuildV0({computeBudgetConfig:u})}async fetchFarmBalances(){let e=await this.scope.api.fetchFarmPositions(this.scope.ownerPubKey.toBase58()),t=new Map,n=new Map;Object.keys(e||{}).forEach(u=>{var c,d;Object.keys(e[u]).forEach(p=>{Object.keys(e[u][p]).forEach(m=>{var g,P,k,I,A,h;let f=E(N({},e[u][p][m]),{farmId:p,lpMint:u,userVault:m}),y=t.get(u);t.set(u,{lpMint:u,hasAmount:(y==null?void 0:y.hasAmount)||new eo.default(f.lpAmount||0).gt(0),hasV1Data:(y==null?void 0:y.hasV1Data)||f.version==="V1",totalLpAmount:new eo.default((g=y==null?void 0:y.totalLpAmount)!=null?g:0).add(f.lpAmount||0).toString(),totalV1LpAmount:f.version==="V1"?new eo.default((P=y==null?void 0:y.totalV1LpAmount)!=null?P:0).add(f.lpAmount||0).toString():(k=y==null?void 0:y.totalV1LpAmount)!=null?k:"0",data:[...(y==null?void 0:y.data)||[],f]});let b=n.get(p);f.programId,n.set(p,{lpMint:u,hasAmount:(b==null?void 0:b.hasAmount)||new eo.default(f.lpAmount||0).gt(0),hasV1Data:(b==null?void 0:b.hasV1Data)||f.version==="V1",totalLpAmount:new eo.default((I=b==null?void 0:b.totalLpAmount)!=null?I:0).add(f.lpAmount||0).toString(),totalV1LpAmount:f.version==="V1"?new eo.default((A=b==null?void 0:b.totalV1LpAmount)!=null?A:0).add(f.lpAmount||0).toString():(h=b==null?void 0:b.totalV1LpAmount)!=null?h:"0",data:[...(b==null?void 0:b.data)||[],f]})})}),t.set(u,E(N({},t.get(u)),{totalLpAmount:new eo.default((d=(c=t.get(u))==null?void 0:c.totalLpAmount)!=null?d:0).toString()}))});let o=Array.from(n).map(u=>u[1].data).flat(),i=await this.scope.api.fetchFarmInfoById({ids:o.map(u=>u.farmId).join(",")}),r=await Lt(this.scope.connection,o.map(u=>new Ce.PublicKey(u.userVault)));return(await Lt(this.scope.connection,o.map(u=>new Ce.PublicKey(u.farmId)))).map((u,c)=>{var g;if(!u||!r[c])return;let d=un[o[c].programId];if(!pi[d]||!fi[d])return;let p=fi[d].decode(r[c].data),m=pi[d].decode(u.data),f;m.version===6?f=(g=m.rewardMultiplier)!=null?g:new to.default(10).pow(new to.default(9)):f=m.rewardInfos.length===1?new to.default(10).pow(new to.default(9)):new to.default(10).pow(new to.default(15));let y=i[c],b=m?m.rewardInfos.map((P,k)=>{var h;let I=p.rewardDebts[k],A=p.deposited.mul((m==null?void 0:m.version)===6?P.accRewardPerShare:P.perShareReward).div(f).sub(I);return A.lt(new to.default(0))&&(A=new to.default(0)),{mint:(h=y.rewardInfos[k])==null?void 0:h.mint,amount:A.toString()}}):[];return E(N(N({},p),m),{farmInfo:y,pendingRewards:b})}).filter(Boolean)}};var ut=require("@solana/web3.js"),Rt=require("@solana/spl-token");var ic=ie(require("bn.js")),Ua=new ic.default(25),pr=new ic.default(1e4),Wm={4:3,5:3},rc=new Set(["5Q544fKrFoe6tsEbD7S8EmxGTJYAKtTVhAW5Q5pge4j1","3uaZBfHPfmpAHW7dsimC1SnyR61X4bJqQZKWmRSCXJxv","GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL"]);var Fn=require("@solana/spl-token"),Ae=require("@solana/web3.js");var fr=ie(require("bn.js"));var Ga=v([V("instruction"),w("amountIn"),w("minAmountOut")]),za=v([V("instruction"),w("maxAmountIn"),w("amountOut")]),sf=v([V("instruction"),V("nonce")]),Xa=v([V("instruction"),V("nonce"),w("startTime")]),wi=v([w("status"),w("nonce"),w("maxOrder"),w("depth"),w("baseDecimal"),w("quoteDecimal"),w("state"),w("resetFlag"),w("minSize"),w("volMaxCutRatio"),w("amountWaveRatio"),w("baseLotSize"),w("quoteLotSize"),w("minPriceMultiplier"),w("maxPriceMultiplier"),w("systemDecimalValue"),w("minSeparateNumerator"),w("minSeparateDenominator"),w("tradeFeeNumerator"),w("tradeFeeDenominator"),w("pnlNumerator"),w("pnlDenominator"),w("swapFeeNumerator"),w("swapFeeDenominator"),w("baseNeedTakePnl"),w("quoteNeedTakePnl"),w("quoteTotalPnl"),w("baseTotalPnl"),w("poolOpenTime"),w("punishPcAmount"),w("punishCoinAmount"),w("orderbookToInitTime"),pe("swapBaseInAmount"),pe("swapQuoteOutAmount"),w("swapBase2QuoteFee"),pe("swapQuoteInAmount"),pe("swapBaseOutAmount"),w("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"),w("lpReserve"),j(w(),3,"padding")]),qm=v([w("accountType"),w("status"),w("nonce"),w("maxOrder"),w("depth"),w("baseDecimal"),w("quoteDecimal"),w("state"),w("resetFlag"),w("minSize"),w("volMaxCutRatio"),w("amountWaveRatio"),w("baseLotSize"),w("quoteLotSize"),w("minPriceMultiplier"),w("maxPriceMultiplier"),w("systemDecimalsValue"),w("abortTradeFactor"),w("priceTickMultiplier"),w("priceTick"),w("minSeparateNumerator"),w("minSeparateDenominator"),w("tradeFeeNumerator"),w("tradeFeeDenominator"),w("pnlNumerator"),w("pnlDenominator"),w("swapFeeNumerator"),w("swapFeeDenominator"),w("baseNeedTakePnl"),w("quoteNeedTakePnl"),w("quoteTotalPnl"),w("baseTotalPnl"),w("poolOpenTime"),w("punishPcAmount"),w("punishCoinAmount"),w("orderbookToInitTime"),pe("swapBaseInAmount"),pe("swapQuoteOutAmount"),pe("swapQuoteInAmount"),pe("swapBaseOutAmount"),w("swapQuote2BaseFee"),w("swapBase2QuoteFee"),M("baseVault"),M("quoteVault"),M("baseMint"),M("quoteMint"),M("lpMint"),M("modelDataAccount"),M("openOrders"),M("marketId"),M("marketProgramId"),M("targetOrders"),M("owner"),j(w(),64,"padding")]),Ya=v([V("instruction"),w("baseAmountIn"),w("quoteAmountIn"),w("fixedSide"),w("otherAmountMin")]),Ha=v([V("instruction"),w("lpAmount"),w("baseAmountMin"),w("quoteAmountMin")]),uf={4:wi,5:qm},ac=v([w("fee")]);var Qa=Se("Raydium_liquidity_instruction");function sc(l){let{poolInfo:e,poolKeys:t,userKeys:n,baseAmountIn:o,quoteAmountIn:i,fixedSide:r,otherAmountMin:a,modelDataPubKey:s=so}=l,u=Buffer.alloc(Ya.span);Ya.encode({instruction:3,baseAmountIn:fe(o),quoteAmountIn:fe(i),otherAmountMin:fe(a),fixedSide:r==="base"?$:dt},u);let c=[T({pubkey:Fn.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:new Ae.PublicKey(e.id)}),T({pubkey:new Ae.PublicKey(t.authority),isWritable:!1}),T({pubkey:new Ae.PublicKey(t.openOrders),isWritable:!1}),T({pubkey:new Ae.PublicKey(t.targetOrders)}),T({pubkey:new Ae.PublicKey(e.lpMint.address)}),T({pubkey:new Ae.PublicKey(t.vault.A)}),T({pubkey:new Ae.PublicKey(t.vault.B)})];return e.pooltype.includes("StablePool")&&c.push(T({pubkey:s})),c.push(T({pubkey:new Ae.PublicKey(e.marketId),isWritable:!1}),T({pubkey:n.baseTokenAccount}),T({pubkey:n.quoteTokenAccount}),T({pubkey:n.lpTokenAccount}),T({pubkey:n.owner,isWritable:!1,isSigner:!0}),T({pubkey:new Ae.PublicKey(t.marketEventQueue),isWritable:!1})),new Ae.TransactionInstruction({programId:new Ae.PublicKey(e.programId),keys:c,data:u})}function Za(l){let{poolInfo:e,poolKeys:t,userKeys:n,lpAmount:o,baseAmountMin:i,quoteAmountMin:r,modelDataPubKey:a=so}=l,s=it(t),u=4;if(e.pooltype.includes("StablePool")&&(u=5),u===4||u===5){let c=Buffer.alloc(Ha.span);Ha.encode({instruction:4,lpAmount:fe(o),baseAmountMin:fe(i),quoteAmountMin:fe(r)},c);let d=[T({pubkey:Fn.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:s.id}),T({pubkey:s.authority,isWritable:!1}),T({pubkey:s.openOrders}),T({pubkey:s.targetOrders}),T({pubkey:s.mintLp.address}),T({pubkey:s.vault.A}),T({pubkey:s.vault.B})];return u===5?d.push(T({pubkey:a})):(d.push(T({pubkey:s.id})),d.push(T({pubkey:s.id}))),d.push(T({pubkey:s.marketProgramId,isWritable:!1}),T({pubkey:s.marketId}),T({pubkey:s.marketBaseVault}),T({pubkey:s.marketQuoteVault}),T({pubkey:s.marketAuthority,isWritable:!1}),T({pubkey:n.lpTokenAccount}),T({pubkey:n.baseTokenAccount}),T({pubkey:n.quoteTokenAccount}),T({pubkey:n.owner,isWritable:!1,isSigner:!0}),T({pubkey:s.marketEventQueue}),T({pubkey:s.marketBids}),T({pubkey:s.marketAsks})),new Ae.TransactionInstruction({programId:s.programId,keys:d,data:c})}return new Ae.TransactionInstruction({programId:s.programId,keys:[]})}function ja({programId:l,ammId:e,ammAuthority:t,ammOpenOrders:n,lpMint:o,coinMint:i,pcMint:r,coinVault:a,pcVault:s,withdrawQueue:u,ammTargetOrders:c,poolTempLp:d,marketProgramId:p,marketId:m,userWallet:f,userCoinVault:y,userPcVault:b,userLpVault:g,nonce:P,openTime:k,coinAmount:I,pcAmount:A,ammConfigId:h,feeDestinationId:B}){let S=v([V("instruction"),V("nonce"),w("openTime"),w("pcAmount"),w("coinAmount")]),K=[{pubkey:Fn.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:Fn.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:Ae.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:It,isSigner:!1,isWritable:!1},{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:h,isSigner:!1,isWritable:!1},{pubkey:B,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!0,isWritable:!0},{pubkey:y,isSigner:!1,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!0},{pubkey:g,isSigner:!1,isWritable:!0}],x=Buffer.alloc(S.span);return S.encode({instruction:1,nonce:P,openTime:k,coinAmount:I,pcAmount:A},x),{instruction:new Ae.TransactionInstruction({keys:K,programId:l,data:x}),instructionType:Y.AmmV4CreatePool}}function cf(l){let e=v([V("instruction"),V("simulateType")]),t=Buffer.alloc(e.span);e.encode({instruction:12,simulateType:0},t);let n=[T({pubkey:new Ae.PublicKey(l.id),isWritable:!1}),T({pubkey:new Ae.PublicKey(l.authority),isWritable:!1}),T({pubkey:new Ae.PublicKey(l.openOrders),isWritable:!1}),T({pubkey:new Ae.PublicKey(l.vault.A),isWritable:!1}),T({pubkey:new Ae.PublicKey(l.vault.B),isWritable:!1}),T({pubkey:new Ae.PublicKey(l.mintLp.address),isWritable:!1}),T({pubkey:new Ae.PublicKey(l.marketId),isWritable:!1}),T({pubkey:new Ae.PublicKey(l.marketEventQueue),isWritable:!1})];return new Ae.TransactionInstruction({programId:new Ae.PublicKey(l.programId),keys:n,data:t})}function Um({poolKeys:l,userKeys:e,amountIn:t,minAmountOut:n,modelDataPubKey:o=so},i){let r=it(l),a=Buffer.alloc(Ga.span);Ga.encode({instruction:9,amountIn:fe(t),minAmountOut:fe(n)},a);let s=[T({pubkey:Fn.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:r.id}),T({pubkey:r.authority,isWritable:!1}),T({pubkey:r.openOrders})];return i===4&&s.push(T({pubkey:r.targetOrders})),s.push(T({pubkey:r.vault.A}),T({pubkey:r.vault.B})),i===5&&s.push(T({pubkey:o})),s.push(T({pubkey:r.marketProgramId,isWritable:!1}),T({pubkey:r.marketId}),T({pubkey:r.marketBids}),T({pubkey:r.marketAsks}),T({pubkey:r.marketEventQueue}),T({pubkey:r.marketBaseVault}),T({pubkey:r.marketQuoteVault}),T({pubkey:r.marketAuthority,isWritable:!1}),T({pubkey:e.tokenAccountIn}),T({pubkey:e.tokenAccountOut}),T({pubkey:e.owner,isWritable:!1,isSigner:!0})),new Ae.TransactionInstruction({programId:r.programId,keys:s,data:a})}function Gm({poolKeys:l,userKeys:e,maxAmountIn:t,amountOut:n,modelDataPubKey:o=so},i){let r=it(l),a=Buffer.alloc(za.span);za.encode({instruction:11,maxAmountIn:fe(t),amountOut:fe(n)},a);let s=[T({pubkey:Fn.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:r.id}),T({pubkey:r.authority,isWritable:!1}),T({pubkey:r.openOrders}),T({pubkey:r.targetOrders}),T({pubkey:r.vault.A}),T({pubkey:r.vault.B})];return i===5&&s.push(T({pubkey:o})),s.push(T({pubkey:r.marketProgramId,isWritable:!1}),T({pubkey:r.marketId}),T({pubkey:r.marketBids}),T({pubkey:r.marketAsks}),T({pubkey:r.marketEventQueue}),T({pubkey:r.marketBaseVault}),T({pubkey:r.marketQuoteVault}),T({pubkey:r.marketAuthority,isWritable:!1}),T({pubkey:e.tokenAccountIn}),T({pubkey:e.tokenAccountOut}),T({pubkey:e.owner,isWritable:!1,isSigner:!0})),new Ae.TransactionInstruction({programId:r.programId,keys:s,data:a})}function zm(l,e,t,n,o,i,r,a,s,u){let c=v([V("instructionId"),w("amountIn"),w("minAmountOut")]),d=Buffer.alloc(c.span);c.encode({instructionId:16,amountIn:s,minAmountOut:u},d);let p=[{pubkey:Fn.TOKEN_PROGRAM_ID,isWritable:!1,isSigner:!1},{pubkey:e,isWritable:!0,isSigner:!1},{pubkey:t,isWritable:!1,isSigner:!1},{pubkey:n,isWritable:!0,isSigner:!1},{pubkey:o,isWritable:!0,isSigner:!1},{pubkey:i,isWritable:!0,isSigner:!1},{pubkey:r,isWritable:!0,isSigner:!1},{pubkey:a,isWritable:!1,isSigner:!0}];return new Ae.TransactionInstruction({programId:l,keys:p,data:d})}function Xm(l,e,t,n,o,i,r,a,s,u){let c=v([V("instructionId"),w("maxAmountIn"),w("amountOut")]),d=Buffer.alloc(c.span);c.encode({instructionId:17,maxAmountIn:s,amountOut:u},d);let p=[{pubkey:Fn.TOKEN_PROGRAM_ID,isWritable:!1,isSigner:!1},{pubkey:e,isWritable:!0,isSigner:!1},{pubkey:t,isWritable:!1,isSigner:!1},{pubkey:n,isWritable:!0,isSigner:!1},{pubkey:o,isWritable:!0,isSigner:!1},{pubkey:i,isWritable:!0,isSigner:!1},{pubkey:r,isWritable:!0,isSigner:!1},{pubkey:a,isWritable:!1,isSigner:!0}];return new Ae.TransactionInstruction({programId:l,keys:p,data:d})}function yr(l){let{poolKeys:e,version:t,userKeys:n,amountIn:o,amountOut:i,fixedSide:r}=l;if(t===4){if(r==="in")return zm(new Ae.PublicKey(e.programId),new Ae.PublicKey(e.id),new Ae.PublicKey(e.authority),new Ae.PublicKey(e.vault.A),new Ae.PublicKey(e.vault.B),n.tokenAccountIn,n.tokenAccountOut,n.owner,new fr.default(o.toString()),new fr.default(i.toString()));if(r==="out")return Xm(new Ae.PublicKey(e.programId),new Ae.PublicKey(e.id),new Ae.PublicKey(e.authority),new Ae.PublicKey(e.vault.A),new Ae.PublicKey(e.vault.B),n.tokenAccountIn,n.tokenAccountOut,n.owner,new fr.default(o.toString()),new fr.default(i.toString()));Qa.logWithError("invalid params","params",l)}throw Qa.logWithError("invalid version, only support pool v4","poolKeys.version",t),new Error("invalid version")}function br(l){let{poolKeys:e,version:t,userKeys:n,amountIn:o,amountOut:i,fixedSide:r}=l;if(t===4||t===5){let a={poolKeys:e,userKeys:n};if(r==="in")return Um(E(N({},a),{amountIn:o,minAmountOut:i}),t);if(r==="out")return Gm(E(N({},a),{maxAmountIn:o,amountOut:i}),t);Qa.logWithError("invalid params","params",l)}throw Qa.logWithError("invalid version","poolKeys.version",t),new Error("invalid version")}function lf({poolKeys:l,userKeys:e,startTime:t}){let n=Buffer.alloc(Xa.span);Xa.encode({instruction:0,nonce:5,startTime:fe(t)},n);let o=it(l),i=[T({pubkey:Fn.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:Ae.SystemProgram.programId,isWritable:!1}),T({pubkey:Ae.SYSVAR_RENT_PUBKEY,isWritable:!1}),T({pubkey:o.id}),T({pubkey:o.authority,isWritable:!1}),T({pubkey:o.openOrders}),T({pubkey:o.mintLp.address}),T({pubkey:o.mintA.address,isWritable:!1}),T({pubkey:o.mintB.address,isWritable:!1}),T({pubkey:o.vault.A,isWritable:!1}),T({pubkey:o.vault.B,isWritable:!1}),T({pubkey:o.id}),T({pubkey:o.targetOrders}),T({pubkey:e.lpTokenAccount}),T({pubkey:o.id,isWritable:!1}),T({pubkey:o.marketProgramId,isWritable:!1}),T({pubkey:o.marketId,isWritable:!1}),T({pubkey:e.payer,isSigner:!0})];return new Ae.TransactionInstruction({programId:o.programId,keys:i,data:n})}var Do=5e4,Ym=v([w("x"),w("y"),w("price")]),Hm=v([w("accountType"),w("status"),w("multiplier"),w("validDataCount"),j(Ym,Do,"DataElement")]);function mf(l,e){return[0,Do-2]}function df(l){return[0,Do-2]}function pf(l){return[0,Do-2]}function ff(l,e,t){let[n,o]=mf(e,t),i=n,r=o,a=0,s=e*l.multiplier/t;for(;i<=r;){if(a=Math.floor((r+i)/2),a===0||a>=Do-2)return[a,a,!1];let u=l.DataElement[a].x*l.multiplier/l.DataElement[a].y,c=l.DataElement[a-1].x*l.multiplier/l.DataElement[a-1].y,d=l.DataElement[a+1].x*l.multiplier/l.DataElement[a+1].y;if(s===u)return[a,a,!0];if(s===c)return[a-1,a-1,!0];if(s===d)return[a+1,a+1,!0];if(s<c)r=a-1;else{if(s>c&&s<u)return[a-1,a,!0];if(s>u&&s<d)return[a,a+1,!0];i=a+1}}return[a,a,!1]}function uc(l,e,t){let[n,o,i]=ff(l,e,t);if(!i)return 0;if(n===o){let r=l.DataElement[n].x;return e*l.multiplier/r}else{let r=l.DataElement[n].x,a=l.DataElement[n].y,s=l.DataElement[o].x,u=l.DataElement[o].y,c=t*(s*a-r*u),d=r*c,p=(s-r)*(e*a-r*t)*u,m=d+p;return e*l.multiplier*c/m}}function Eo(l,e,t){return e*l.multiplier/t}function Qm(l,e,t){return e*t/l.multiplier}function yf(l,e){let[t,n]=df(e),o=t,i=n,r=0,a=e;for(;o<i;){if(r=Math.floor((i+o)/2),r<=0||r>Do-2)return[r,r,!1];let s=l.DataElement[r].x,u=l.DataElement[r-1].x,c=l.DataElement[r+1].x;if(a===s)return[r,r,!0];if(a===u)return[r-1,r-1,!0];if(a===c)return[r+1,r+1,!0];if(a<u)i=r-1;else{if(a>u&&a<s)return[r-1,r,!0];if(a>s&&a<c)return[r,r+1,!0];o=r+1}}return[r,r,!1]}function bf(l,e){let[t,n]=pf(e),o=t,i=n,r=0,a=e;for(;o<=i;){if(r=Math.floor((i+o)/2),r<=0||r>=Do-2)return[r,r,!1];let s=l.DataElement[r].y,u=l.DataElement[r-1].y,c=l.DataElement[r+1].y;if(a===s)return[r,r,!0];if(a===u)return[r-1,r-1,!0];if(a===c)return[r+1,r+1,!0];if(a<c)o=r+1;else{if(a<u&&a>s)return[r-1,r,!0];if(a<s&&a>c)return[r,r+1,!0];i=r-1}}return[r,r,!1]}function Zm(l,e,t,n){let o=n?e+t:e-t,[i,r,a]=yf(l,o);if(!a)return[0,0,!1,a];if(i===r)return[l.DataElement[r].price,l.DataElement[r].y,!1,a];{let s=l.DataElement[i].x,u=l.DataElement[r].x,c=l.DataElement[i].price,d=l.DataElement[r].price,p=l.DataElement[i].y,m=l.DataElement[r].y;if(e>=s&&e<=u)return n?[d,m,!0,a]:[c,p,!0,a];{let f,y;return n?(f=c+(d-c)*(e-s)/(u-s),y=p-(o-s)*l.multiplier/d):(f=c+(d-c)*(e-s)/(u-s),y=m+(u-o)*l.multiplier/c),[f,y,!1,a]}}}function gf(l,e,t,n){let o=n?e-t:e+t,[i,r,a]=bf(l,o);if(!a)return[0,0,!1,a];if(i===r)return[l.DataElement[r].price,l.DataElement[r].x,!1,a];{let s=l.DataElement[i].x,u=l.DataElement[r].x,c=l.DataElement[i].price,d=l.DataElement[r].price,p=l.DataElement[i].y,m=l.DataElement[r].y;if(e>=m&&e<=p)return n?[d,u,!0,a]:[c,s,!0,a];{let f,y;return n?(f=c+(d-c)*(p-e)/(p-m),y=s+d*(p-o)/l.multiplier):(f=c+(d-c)*(p-e)/(p-m),y=u-c*(o-m)/l.multiplier),[f,y,!1,a]}}}function Pf(l,e){let t=Zm(l,e,0,!1);return t[3]?t[0]:0}function cc(l,e,t,n){let o=uc(l,e,t),i=Eo(l,e,o),r=Eo(l,t,o),a=Eo(l,n,o),s=!0,[u,c,d,p]=Zm(l,i,a,s);if(!p)return 0;if(d)return n*l.multiplier/u;{let m=r-c;return Qm(l,m,o)}}function lc(l,e,t,n){let o=uc(l,e,t),i=Eo(l,e,o),r=Eo(l,t,o),a=Eo(l,n,o),s=!1,[u,c,d,p]=gf(l,r,a,s);if(!p)return 0;if(d)return n*u/l.multiplier;{let m=i-c;return Qm(l,m,o)}}function jm(l){let e=Hm.decode(l);return{accountType:e.accountType.toNumber(),status:e.status.toNumber(),multiplier:e.multiplier.toNumber(),validDataCount:e.validDataCount.toNumber(),DataElement:e.DataElement.map(t=>({x:t.x.toNumber(),y:t.y.toNumber(),price:t.price.toNumber()}))}}function mc(l,e,t,n){let o=Pf(l,Eo(l,e,uc(l,e,t)))/l.multiplier;return n?o:1/o}var gr=class{constructor({connection:e,modelDataPubKey:t=so}){this._layoutData={accountType:0,status:0,multiplier:0,validDataCount:0,DataElement:[]};this.connection=e,this.modelDataPubKey=t}get stableModelData(){return this._layoutData}async initStableModelLayout(){if(this._layoutData.validDataCount===0&&this.connection){let e=await this.connection.getAccountInfo(this.modelDataPubKey);e&&(this._layoutData=jm(e==null?void 0:e.data))}}};var ed=require("@solana/web3.js"),Pr=ie(require("decimal.js")),td=require("@solana/spl-token");var $m=require("@solana/web3.js");var Af=Se("Raydium_liquidity_serum");function Jm({programId:l,marketId:e}){let t=[e.toBuffer()],n=0,o;for(;n<100;){try{let i=t.concat(Buffer.from([n]),Buffer.alloc(7));o=$m.PublicKey.createProgramAddressSync(i,l)}catch(i){if(i instanceof TypeError)throw i;n++;continue}return{publicKey:o,nonce:n}}throw Af.logWithError("unable to find a viable program address nonce","params",{programId:l,marketId:e}),new Error("unable to find a viable program address nonce")}function Ar({programId:l}){let{publicKey:e}=re([Buffer.from("amm_config_account_seed","utf-8")],l);return e}function bo({name:l,programId:e,marketId:t}){let{publicKey:n}=re([e.toBuffer(),t.toBuffer(),Buffer.from(l,"utf-8")],e);return n}function nd({programId:l,marketId:e}){let{publicKey:t}=re([l.toBuffer(),e.toBuffer(),Buffer.from("open_order_associated_seed","utf-8")],l);return t}function $a({programId:l}){return re([Buffer.from([97,109,109,32,97,117,116,104,111,114,105,116,121])],l)}function Ja({version:l,marketVersion:e,marketId:t,baseMint:n,quoteMint:o,baseDecimals:i,quoteDecimals:r,programId:a,marketProgramId:s}){let u=bo({name:"amm_associated_seed",programId:a,marketId:t}),c=bo({name:"lp_mint_associated_seed",programId:a,marketId:t}),{publicKey:d,nonce:p}=$a({programId:a}),m=bo({name:"coin_vault_associated_seed",programId:a,marketId:t}),f=bo({name:"pc_vault_associated_seed",programId:a,marketId:t}),y=bo({name:"temp_lp_token_associated_seed",programId:a,marketId:t}),b=nd({programId:a,marketId:t}),g=bo({name:"target_associated_seed",programId:a,marketId:t}),P=bo({name:"withdraw_associated_seed",programId:a,marketId:t}),{publicKey:k}=Jm({programId:s,marketId:t});return{id:u,baseMint:n,quoteMint:o,lpMint:c,baseDecimals:i,quoteDecimals:r,lpDecimals:i,version:l,programId:a,authority:d,nonce:p,baseVault:m,quoteVault:f,lpVault:y,openOrders:b,targetOrders:g,withdrawQueue:P,marketVersion:e,marketProgramId:s,marketId:t,marketAuthority:k,lookupTableAccount:ed.PublicKey.default,configId:Ar({programId:a})}}var dc={volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[]},wr=l=>{let e={},t=td.TOKEN_PROGRAM_ID.toBase58();return Object.keys(l).map(n=>{let o=l[n],[i,r]=[o.baseMint.toBase58(),o.quoteMint.toBase58()];e[n]={id:n,version:4,status:o.status.toNumber(),programId:o.programId.toBase58(),mintA:At({address:i,programId:t,decimals:o.baseDecimal.toNumber()}),mintB:At({address:r,programId:t,decimals:o.quoteDecimal.toNumber()}),rewardDefaultInfos:[],rewardDefaultPoolInfos:"Ecosystem",price:o.poolPrice.toNumber(),mintAmountA:new Pr.default(o.mintAAmount.toString()).div(10**o.baseDecimal.toNumber()).toNumber(),mintAmountB:new Pr.default(o.mintBAmount.toString()).div(10**o.quoteDecimal.toNumber()).toNumber(),baseReserve:o.baseReserve,quoteReserve:o.quoteReserve,feeRate:new Pr.default(o.tradeFeeNumerator.toString()).div(o.tradeFeeDenominator.toString()).toNumber(),openTime:o.poolOpenTime.toString(),tvl:0,day:dc,week:dc,month:dc,pooltype:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0,type:"Standard",marketId:o.marketId.toBase58(),configId:Ar({programId:o.programId}).toBase58(),lpPrice:0,lpAmount:new Pr.default(o.lpReserve.toString()).div(10**Math.min(o.baseDecimal.toNumber(),o.quoteDecimal.toNumber())).toNumber(),lpMint:At({address:o.lpMint.toBase58(),programId:t,decimals:Math.min(o.baseDecimal.toNumber(),o.quoteDecimal.toNumber())}),burnPercent:0,feeOn:"Both",hasDynamicFee:!1,tips:[],launchMigratePool:!1}}),e};var Xe=ie(require("bn.js")),Ge=ie(require("decimal.js"));var pc=require("@solana/spl-token"),Ti=require("@solana/web3.js"),hi=ie(require("bn.js"));var tn=require("@solana/web3.js"),ki=require("@solana/spl-token");function wf(l="accountFlags"){let e=new la(l);return e.addBoolean("initialized"),e.addBoolean("market"),e.addBoolean("openOrders"),e.addBoolean("requestQueue"),e.addBoolean("eventQueue"),e.addBoolean("bids"),e.addBoolean("asks"),e}var es=v([Be(5),wf("accountFlags"),M("ownAddress"),w("vaultSignerNonce"),M("baseMint"),M("quoteMint"),M("baseVault"),w("baseDepositsTotal"),w("baseFeesAccrued"),M("quoteVault"),w("quoteDepositsTotal"),w("quoteFeesAccrued"),w("quoteDustThreshold"),M("requestQueue"),M("eventQueue"),M("bids"),M("asks"),w("baseLotSize"),w("quoteLotSize"),w("feeRateBps"),w("referrerRebatesAccrued"),Be(7)]);function od({programId:l,marketInfo:e}){let t=v([V("version"),je("instruction"),w("baseLotSize"),w("quoteLotSize"),lt("feeRateBps"),w("vaultSignerNonce"),w("quoteDustThreshold")]),n=[{pubkey:e.id,isSigner:!1,isWritable:!0},{pubkey:e.requestQueue,isSigner:!1,isWritable:!0},{pubkey:e.eventQueue,isSigner:!1,isWritable:!0},{pubkey:e.bids,isSigner:!1,isWritable:!0},{pubkey:e.asks,isSigner:!1,isWritable:!0},{pubkey:e.baseVault,isSigner:!1,isWritable:!0},{pubkey:e.quoteVault,isSigner:!1,isWritable:!0},{pubkey:e.baseMint,isSigner:!1,isWritable:!1},{pubkey:e.quoteMint,isSigner:!1,isWritable:!1},{pubkey:e.authority?e.quoteMint:tn.SYSVAR_RENT_PUBKEY,isSigner:!1,isWritable:!1}].concat(e.authority?{pubkey:e.authority,isSigner:!1,isWritable:!1}:[]).concat(e.authority&&e.pruneAuthority?{pubkey:e.pruneAuthority,isSigner:!1,isWritable:!1}:[]),o=Buffer.alloc(t.span);return t.encode({version:0,instruction:0,baseLotSize:e.baseLotSize,quoteLotSize:e.quoteLotSize,feeRateBps:e.feeRateBps,vaultSignerNonce:e.vaultSignerNonce,quoteDustThreshold:e.quoteDustThreshold},o),new tn.TransactionInstruction({keys:n,programId:l,data:o})}async function kr({connection:l,wallet:e,marketInfo:t}){var r,a,s,u,c,d,p,m;let n=new tn.Transaction,o=await l.getMinimumBalanceForRentExemption(165);n.add(tn.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.baseVault.seed,newAccountPubkey:t.baseVault.publicKey,lamports:o,space:165,programId:ki.TOKEN_PROGRAM_ID}),tn.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.quoteVault.seed,newAccountPubkey:t.quoteVault.publicKey,lamports:o,space:165,programId:ki.TOKEN_PROGRAM_ID}),(0,ki.createInitializeAccountInstruction)(t.baseVault.publicKey,t.baseMint,t.vaultOwner),(0,ki.createInitializeAccountInstruction)(t.quoteVault.publicKey,t.quoteMint,t.vaultOwner),tn.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.id.seed,newAccountPubkey:t.id.publicKey,lamports:await l.getMinimumBalanceForRentExemption(es.span),space:es.span,programId:t.programId}));let i=new tn.Transaction;return i.add(tn.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.requestQueue.seed,newAccountPubkey:t.requestQueue.publicKey,lamports:t.lowestFeeMarket?6208320:await l.getMinimumBalanceForRentExemption((r=t.requestQueueSpace)!=null?r:5120+12),space:t.lowestFeeMarket?764:(a=t.requestQueueSpace)!=null?a:5120+12,programId:t.programId}),tn.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.eventQueue.seed,newAccountPubkey:t.eventQueue.publicKey,lamports:t.lowestFeeMarket?79594560:await l.getMinimumBalanceForRentExemption((s=t.eventQueueSpace)!=null?s:262144+12),space:t.lowestFeeMarket?11308:(u=t.eventQueueSpace)!=null?u:262144+12,programId:t.programId}),tn.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.bids.seed,newAccountPubkey:t.bids.publicKey,lamports:t.lowestFeeMarket?101977920:await l.getMinimumBalanceForRentExemption((c=t.orderbookQueueSpace)!=null?c:65536+12),space:t.lowestFeeMarket?14524:(d=t.orderbookQueueSpace)!=null?d:65536+12,programId:t.programId}),tn.SystemProgram.createAccountWithSeed({fromPubkey:e,basePubkey:e,seed:t.asks.seed,newAccountPubkey:t.asks.publicKey,lamports:t.lowestFeeMarket?101977920:await l.getMinimumBalanceForRentExemption((p=t.orderbookQueueSpace)!=null?p:65536+12),space:t.lowestFeeMarket?14524:(m=t.orderbookQueueSpace)!=null?m:65536+12,programId:t.programId}),od({programId:t.programId,marketInfo:{id:t.id.publicKey,requestQueue:t.requestQueue.publicKey,eventQueue:t.eventQueue.publicKey,bids:t.bids.publicKey,asks:t.asks.publicKey,baseVault:t.baseVault.publicKey,quoteVault:t.quoteVault.publicKey,baseMint:t.baseMint,quoteMint:t.quoteMint,baseLotSize:t.baseLotSize,quoteLotSize:t.quoteLotSize,feeRateBps:t.feeRateBps,vaultSignerNonce:t.vaultSignerNonce,quoteDustThreshold:t.quoteDustThreshold}})),[{transaction:n,signer:[],instructionTypes:[Y.CreateAccount,Y.CreateAccount,Y.InitAccount,Y.InitAccount]},{transaction:i,signer:[],instructionTypes:[Y.CreateAccount,Y.CreateAccount,Y.CreateAccount,Y.CreateAccount,Y.CreateAccount,Y.InitMarket]}]}var Ii=class extends at{async create({baseInfo:e,quoteInfo:t,lotSize:n,tickSize:o,dexProgramId:i,requestQueueSpace:r,eventQueueSpace:a,orderbookQueueSpace:s,lowestFeeMarket:u,assignSeed:c,txVersion:d,computeBudgetConfig:p,txTipConfig:m,feePayer:f}){let y=this.scope.ownerPubKey,b=c?`${e.mint.toBase58().slice(0,10)}-${t.mint.toBase58().slice(0,10)}-${c}`:void 0,g=st({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-market`}),P=st({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-request`}),k=st({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-event`}),I=st({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-bids`}),A=st({fromPublicKey:y,programId:i,assignSeed:b&&`${b}-asks`}),h=st({fromPublicKey:y,programId:pc.TOKEN_PROGRAM_ID,assignSeed:b&&`${b}-baseVault`}),B=st({fromPublicKey:y,programId:pc.TOKEN_PROGRAM_ID,assignSeed:b&&`${b}-quoteVault`}),S=0,K=new hi.default(100);function x(){let D=new hi.default(0);for(;;)try{return{vaultOwner:Ti.PublicKey.createProgramAddressSync([g.publicKey.toBuffer(),D.toArrayLike(Buffer,"le",8)],i),vaultSignerNonce:D}}catch{if(D.iaddn(1),D.gt(new hi.default(25555)))throw Error("find vault owner error")}}let{vaultOwner:C,vaultSignerNonce:L}=x(),O=new hi.default(Math.round(10**e.decimals*n)),R=new hi.default(Math.round(n*10**t.decimals*o));if(O.eq($))throw Error("lot size is too small");if(R.eq($))throw Error("tick size or lot size is too small");let F=await kr({connection:this.scope.connection,wallet:this.scope.ownerPubKey,marketInfo:{programId:i,id:g,baseMint:e.mint,quoteMint:t.mint,baseVault:h,quoteVault:B,vaultOwner:C,requestQueue:P,eventQueue:k,bids:I,asks:A,feeRateBps:S,quoteDustThreshold:K,vaultSignerNonce:L,baseLotSize:O,quoteLotSize:R,requestQueueSpace:r,eventQueueSpace:a,orderbookQueueSpace:s,lowestFeeMarket:u}}),W=this.createTxBuilder(f);W.addInstruction({instructions:F[0].transaction.instructions,signers:F[0].signer});for await(let D of F.slice(1,F.length))W.addInstruction({instructions:D.transaction.instructions,signers:D.signer,instructionTypes:D.instructionTypes});return d===0?W.sizeCheckBuildV0({computeBudgetConfig:p,address:{marketId:g.publicKey,requestQueue:P.publicKey,eventQueue:k.publicKey,bids:I.publicKey,asks:A.publicKey,baseVault:h.publicKey,quoteVault:B.publicKey,baseMint:new Ti.PublicKey(e.mint),quoteMint:new Ti.PublicKey(t.mint)}}):W.sizeCheckBuild({computeBudgetConfig:p,address:{marketId:g.publicKey,requestQueue:P.publicKey,eventQueue:k.publicKey,bids:I.publicKey,asks:A.publicKey,baseVault:h.publicKey,quoteVault:B.publicKey,baseMint:new Ti.PublicKey(e.mint),quoteMint:new Ti.PublicKey(t.mint)}})}};var Tr=class extends at{constructor(t){super(t);this.stableLayout=new gr({connection:this.scope.connection,modelDataPubKey:this.scope.cluster==="mainnet"?void 0:Rn.MODEL_DATA_PUBKEY})}async initLayout(){await this.stableLayout.initStableModelLayout()}async load(){this.checkDisabled()}computePairAmount({poolInfo:t,amount:n,slippage:o,baseIn:i}){let r=new Xe.default(new Ge.default(n).mul(10**t[i?"mintA":"mintB"].decimals).toFixed(0)),a=oi(t[i?"mintB":"mintA"]),[s,u]=[new Xe.default(new Ge.default(t.mintAmountA).mul(10**t.mintA.decimals).toString()),new Xe.default(new Ge.default(t.mintAmountB).mul(10**t.mintB.decimals).toString())],c=new Xe.default(new Ge.default(t.lpAmount).mul(10**t.lpMint.decimals).toFixed(0,Ge.default.ROUND_DOWN));this.logDebug("baseReserve:",s.toString(),"quoteReserve:",u.toString()),this.logDebug("tokenIn:",i?t.mintA.symbol:t.mintB.symbol,"amountIn:",r.toString(),"anotherToken:",i?t.mintB.symbol:t.mintA.symbol,"slippage:",`${o.toSignificant()}%`,"baseReserve",s.toString(),"quoteReserve",u.toString());let d=i?"base":"quote";this.logDebug("input side:",d);let p=$;r.isZero()||(p=d==="base"?Yr(r.mul(u),s):Yr(r.mul(s),u)),this.logDebug("amountRaw:",p.toString(),"lpAmount:",c.toString());let m=Yr(r.mul(c),d==="base"?s:u);this.logDebug("liquidity:",m.toString());let f=new Nt(new Xe.default(1)).add(o),y=new Nt(new Xe.default(1)).sub(o),b=f.mul(p).quotient,g=y.mul(p).quotient,P=new Ee(a,p),k=new Ee(a,b),I=new Ee(a,g);return this.logDebug("anotherAmount:",P.toFixed(),"maxAnotherAmount:",k.toFixed()),{anotherAmount:P,maxAnotherAmount:k,minAnotherAmount:I,liquidity:m}}async getAmmPoolKeys(t){return(await this.scope.api.fetchPoolKeysById({idList:[t]}))[0]}async addLiquidity(t){let{poolInfo:n,poolKeys:o,amountInA:i,amountInB:r,otherAmountMin:a,fixedSide:s,config:u,txVersion:c,computeBudgetConfig:d,txTipConfig:p,feePayer:m}=t;this.scope.availability.addStandardPosition===!1&&this.logAndCreateError("add liquidity feature disabled in your region"),this.logDebug("amountInA:",i,"amountInB:",r),(i.isZero()||r.isZero())&&this.logAndCreateError("amounts must greater than zero","amountInA & amountInB",{amountInA:i.toFixed(),amountInB:r.toFixed()});let{account:f}=this.scope,{bypassAssociatedCheck:y,checkCreateATAOwner:b}=N({bypassAssociatedCheck:!1,checkCreateATAOwner:!1},u),[g,P]=[i.token,r.token],k=await f.getCreatedTokenAccount({mint:g.mint,associatedOnly:!1}),I=await f.getCreatedTokenAccount({mint:P.mint,associatedOnly:!1});!k&&!I&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",f.tokenAccounts);let A=await f.getCreatedTokenAccount({mint:new ut.PublicKey(n.lpMint.address)}),h=[g,P],B=[k,I],S=[i.raw,r.raw],K=i.token.mint.toBase58()===n.mintA.address?"base":"quote",x="base";["quote","base"].includes(K)||this.logAndCreateError("invalid fixedSide","fixedSide",s),K==="quote"?(h.reverse(),B.reverse(),S.reverse(),x=s==="a"?"quote":"base"):K==="base"&&(x=s==="a"?"base":"quote");let[C,L]=h,[O,R]=B,[F,W]=S,D=o!=null?o:await this.getAmmPoolKeys(n.id),X=this.createTxBuilder(m),ue=await f.handleTokenAccount({side:"in",amount:F,mint:C.mint,tokenAccount:O,bypassAssociatedCheck:y,checkCreateATAOwner:b}),{tokenAccount:Z}=ue,H=$e(ue,["tokenAccount"]);X.addInstruction(H);let he=await f.handleTokenAccount({side:"in",amount:W,mint:L.mint,tokenAccount:R,bypassAssociatedCheck:y,checkCreateATAOwner:b}),{tokenAccount:ne}=he,se=$e(he,["tokenAccount"]);X.addInstruction(se);let _e=await f.handleTokenAccount({side:"out",amount:0,mint:new ut.PublicKey(n.lpMint.address),tokenAccount:A,bypassAssociatedCheck:y,checkCreateATAOwner:b}),{tokenAccount:J}=_e,ge=$e(_e,["tokenAccount"]);return X.addInstruction(ge),X.addInstruction({instructions:[sc({poolInfo:n,poolKeys:D,userKeys:{baseTokenAccount:Z,quoteTokenAccount:ne,lpTokenAccount:J,owner:this.scope.ownerPubKey},baseAmountIn:F,quoteAmountIn:W,otherAmountMin:a.raw,fixedSide:x})],instructionTypes:[n.pooltype.includes("StablePool")?Y.AmmV5AddLiquidity:Y.AmmV4AddLiquidity],lookupTableAddress:D.lookupTableAccount?[D.lookupTableAccount]:[]}),X.addCustomComputeBudget(d),X.addTipInstruction(p),c===0?await X.buildV0():X.build()}async removeLiquidity(t){this.scope.availability.removeStandardPosition===!1&&this.logAndCreateError("remove liquidity feature disabled in your region");let{poolInfo:n,poolKeys:o,lpAmount:i,baseAmountMin:r,quoteAmountMin:a,config:s,txVersion:u,computeBudgetConfig:c,txTipConfig:d,feePayer:p}=t,m=o!=null?o:await this.getAmmPoolKeys(n.id),[f,y,b]=[new ut.PublicKey(n.mintA.address),new ut.PublicKey(n.mintB.address),new ut.PublicKey(n.lpMint.address)];this.logDebug("lpAmount:",i),this.logDebug("baseAmountMin:",r),this.logDebug("quoteAmountMin:",a),i.isZero()&&this.logAndCreateError("amount must greater than zero","lpAmount",i.toString());let{account:g}=this.scope,P=await g.getCreatedTokenAccount({mint:b,associatedOnly:!1});P||this.logAndCreateError("cannot found lpTokenAccount","tokenAccounts",g.tokenAccounts);let k=await g.getCreatedTokenAccount({mint:f}),I=await g.getCreatedTokenAccount({mint:y}),A=this.createTxBuilder(p),{bypassAssociatedCheck:h,checkCreateATAOwner:B}=N({bypassAssociatedCheck:!1,checkCreateATAOwner:!1},s),L=await g.handleTokenAccount({side:"out",amount:0,mint:f,tokenAccount:k,bypassAssociatedCheck:h,checkCreateATAOwner:B}),{tokenAccount:S}=L,K=$e(L,["tokenAccount"]);A.addInstruction(K);let O=await g.handleTokenAccount({side:"out",amount:0,mint:y,tokenAccount:I,bypassAssociatedCheck:h,checkCreateATAOwner:B}),{tokenAccount:x}=O,C=$e(O,["tokenAccount"]);return A.addInstruction(C),A.addInstruction({instructions:[Za({poolInfo:n,poolKeys:m,userKeys:{lpTokenAccount:P,baseTokenAccount:S,quoteTokenAccount:x,owner:this.scope.ownerPubKey},lpAmount:i,baseAmountMin:r,quoteAmountMin:a})],lookupTableAddress:m.lookupTableAccount?[m.lookupTableAccount]:[],instructionTypes:[n.pooltype.includes("StablePool")?Y.AmmV5RemoveLiquidity:Y.AmmV4RemoveLiquidity]}),A.addCustomComputeBudget(c),A.addTipInstruction(d),u===0?await A.buildV0():A.build()}async removeAllLpAndCreateClmmPosition({poolInfo:t,clmmPoolInfo:n,removeLpAmount:o,createPositionInfo:i,farmInfo:r,userFarmLpAmount:a,base:s,computeBudgetConfig:u,payer:c,userAuxiliaryLedgers:d,tokenProgram:p=Rt.TOKEN_PROGRAM_ID,checkCreateATAOwner:m=!0,getEphemeralSigners:f,txVersion:y,feePayer:b}){if((this.scope.availability.removeStandardPosition===!1||this.scope.availability.createConcentratedPosition===!1)&&this.logAndCreateError("remove liquidity or create position feature disabled in your region"),!(t.mintA.address===n.mintA.address||t.mintA.address===n.mintB.address)||!(t.mintB.address===n.mintA.address||t.mintB.address===n.mintB.address))throw Error("mint check error");let g=this.createTxBuilder(b),P={};for(let D of this.scope.account.tokenAccountRawInfos)(P[D.accountInfo.mint.toString()]===void 0||te(this.scope.ownerPubKey,D.accountInfo.mint,Rt.TOKEN_PROGRAM_ID).publicKey.equals(D.pubkey))&&(P[D.accountInfo.mint.toString()]=D.pubkey);let k=P[t.lpMint.address];if(k===void 0)throw Error("find lp account error in trade accounts");let I=o.add(a!=null?a:new Xe.default(0)),A=t.mintA.address===Je.WSOL.mint.toString(),h=t.mintB.address===Je.WSOL.mint.toString(),{account:B,instructionParams:S}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:Rt.TOKEN_PROGRAM_ID,mint:new ut.PublicKey(t.mintA.address),owner:this.scope.ownerPubKey,createInfo:A?{payer:this.scope.ownerPubKey}:void 0,skipCloseAccount:!A,notUseTokenAccount:A,associatedOnly:!0,checkCreateATAOwner:m});if(g.addInstruction(S||{}),B===void 0)throw new Error("base token account not found");let{account:K,instructionParams:x}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:Rt.TOKEN_PROGRAM_ID,mint:new ut.PublicKey(t.mintB.address),owner:this.scope.ownerPubKey,createInfo:h?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!h,notUseTokenAccount:h,associatedOnly:!0,checkCreateATAOwner:m});if(g.addInstruction(x||{}),K===void 0)throw new Error("quote token account not found");if(P[t.mintA.address]=B,P[t.mintB.address]=K,r!==void 0&&!(a!=null&&a.isZero())){let D=un[r.programId],X=Wt({programId:new ut.PublicKey(r.programId),poolId:new ut.PublicKey(r.id),owner:this.scope.ownerPubKey,version:D}),Z,H=await this.scope.connection.getAccountInfo(X);if(H&&(Z=Vo(D).decode(H.data)),D!==6&&!Z){let{instruction:_e,instructionType:Me}=bi({id:new ut.PublicKey(r.id),programId:new ut.PublicKey(r.programId),version:D,ledger:X,owner:this.scope.ownerPubKey});g.addInstruction({instructions:[_e],instructionTypes:[Me]})}let ne=[];for(let _e of r.rewardInfos){let Me=_e.mint.address===Je.WSOL.mint.toString();if(P[_e.mint.address])ne.push(P[_e.mint.address]);else{let{account:ke,instructionParams:ce}=await this.scope.account.getOrCreateTokenAccount({mint:new ut.PublicKey(_e.mint.address),tokenProgram:p,owner:this.scope.ownerPubKey,skipCloseAccount:!Me,createInfo:{payer:c||this.scope.ownerPubKey},associatedOnly:!0,checkCreateATAOwner:m});ke||this.logAndCreateError("farm reward account not found:",_e.mint.address),ce&&g.addInstruction(ce),ne.push(ke)}}let se=(await this.scope.api.fetchFarmKeysById({ids:r.id}))[0],J={userAuxiliaryLedgers:d,amount:a,owner:this.scope.ownerPubKey,farmInfo:r,farmKeys:se,lpAccount:k,rewardAccounts:ne},ge=un[r.programId],ue=ge===6?gi(J):ge===5?Pi(J):Ai(J),he={3:Y.FarmV3Withdraw,5:Y.FarmV5Withdraw,6:Y.FarmV6Withdraw};g.addInstruction({instructions:[ue],instructionTypes:[he[ge]]})}let C=await this.getAmmPoolKeys(t.id),L=Za({poolInfo:t,poolKeys:C,userKeys:{lpTokenAccount:k,baseTokenAccount:B,quoteTokenAccount:K,owner:this.scope.ownerPubKey},lpAmount:I,baseAmountMin:0,quoteAmountMin:0});g.addInstruction({instructions:[L],instructionTypes:[t.pooltype.includes("StablePool")?Y.AmmV5RemoveLiquidity:Y.AmmV4RemoveLiquidity],lookupTableAddress:C.lookupTableAccount?[C.lookupTableAccount]:[]});let[O,R]=t.mintA.address===n.mintA.address?[B,K]:[K,B],F=await this.scope.clmm.getClmmPoolKeys(n.id),W=await we.openPositionFromBaseInstructions(E(N({poolInfo:n,poolKeys:F,ownerInfo:{feePayer:this.scope.ownerPubKey,wallet:this.scope.ownerPubKey,tokenAccountA:O,tokenAccountB:R},withMetadata:"create"},i),{liquidity:new Xe.default(0),base:s,getEphemeralSigners:f}));return g.addInstruction({instructions:[...W.instructions],signers:W.signers,instructionTypes:[...W.instructionTypes],lookupTableAddress:F.lookupTableAccount?[F.lookupTableAccount]:[]}),y===0?g.sizeCheckBuildV0({computeBudgetConfig:u}):g.sizeCheckBuild({computeBudgetConfig:u})}async createPoolV4({programId:t,marketInfo:n,baseMintInfo:o,quoteMintInfo:i,baseAmount:r,quoteAmount:a,startTime:s,ownerInfo:u,associatedOnly:c=!1,checkCreateATAOwner:d=!1,tokenProgram:p,txVersion:m,feeDestinationId:f,computeBudgetConfig:y,txTipConfig:b,feePayer:g}){var R;let P=u.feePayer||((R=this.scope.owner)==null?void 0:R.publicKey),k=u.useSOLBalance&&o.mint.equals(Rt.NATIVE_MINT),I=u.useSOLBalance&&i.mint.equals(Rt.NATIVE_MINT),A=this.createTxBuilder(g),{account:h,instructionParams:B}=await this.scope.account.getOrCreateTokenAccount({mint:o.mint,owner:this.scope.ownerPubKey,createInfo:k?{payer:P,amount:r}:void 0,notUseTokenAccount:k,skipCloseAccount:!k,associatedOnly:k?!1:c,checkCreateATAOwner:d});A.addInstruction(B||{});let{account:S,instructionParams:K}=await this.scope.account.getOrCreateTokenAccount({mint:i.mint,owner:this.scope.ownerPubKey,createInfo:I?{payer:P,amount:a}:void 0,notUseTokenAccount:I,skipCloseAccount:!I,associatedOnly:I?!1:c,checkCreateATAOwner:d});if(A.addInstruction(K||{}),h===void 0||S===void 0)throw Error("you don't has some token account");let x=Ja({version:4,marketVersion:3,marketId:n.marketId,baseMint:o.mint,quoteMint:i.mint,baseDecimals:o.decimals,quoteDecimals:i.decimals,programId:t,marketProgramId:n.programId}),C={programId:t,ammId:x.id,ammAuthority:x.authority,ammOpenOrders:x.openOrders,lpMint:x.lpMint,coinMint:x.baseMint,pcMint:x.quoteMint,coinVault:x.baseVault,pcVault:x.quoteVault,withdrawQueue:x.withdrawQueue,ammTargetOrders:x.targetOrders,poolTempLp:x.lpVault,marketProgramId:x.marketProgramId,marketId:x.marketId,ammConfigId:x.configId,feeDestinationId:f},{instruction:L,instructionType:O}=ja(E(N({},C),{userWallet:this.scope.ownerPubKey,userCoinVault:h,userPcVault:S,userLpVault:te(this.scope.ownerPubKey,x.lpMint,p).publicKey,nonce:x.nonce,openTime:s,coinAmount:r,pcAmount:a}));return A.addInstruction({instructions:[L],instructionTypes:[O]}),A.addCustomComputeBudget(y),A.addTipInstruction(b),A.versionBuild({txVersion:m,extInfo:{address:C}})}async createMarketAndPoolV4({programId:t=Gi,marketProgram:n=qs,feeDestinationId:o=Us,tokenProgram:i,baseMintInfo:r,quoteMintInfo:a,baseAmount:s,quoteAmount:u,startTime:c,ownerInfo:d,lowestFeeMarket:p,assignSeed:m,associatedOnly:f=!1,checkCreateATAOwner:y=!1,lotSize:b=1,tickSize:g=.01,txVersion:P,computeBudgetConfig:k,txTipConfig:I,feePayer:A}){var Ni,ws,Mi;let h=this.scope.ownerPubKey,B=d.feePayer||((Ni=this.scope.owner)==null?void 0:Ni.publicKey),S=d.useSOLBalance&&r.mint.equals(Rt.NATIVE_MINT),K=d.useSOLBalance&&a.mint.equals(Rt.NATIVE_MINT),x=m?`${r.mint.toBase58().slice(0,7)}-${a.mint.toBase58().slice(0,7)}-${m}`:void 0,C=st({fromPublicKey:h,programId:n,assignSeed:x&&`${x}-market`}),L=st({fromPublicKey:h,programId:n,assignSeed:x&&`${x}-request`}),O=st({fromPublicKey:h,programId:n,assignSeed:x&&`${x}-event`}),R=st({fromPublicKey:h,programId:n,assignSeed:x&&`${x}-bids`}),F=st({fromPublicKey:h,programId:n,assignSeed:x&&`${x}-asks`}),W=st({fromPublicKey:h,programId:Rt.TOKEN_PROGRAM_ID,assignSeed:x&&`${x}-baseVault`}),D=st({fromPublicKey:h,programId:Rt.TOKEN_PROGRAM_ID,assignSeed:x&&`${x}-quoteVault`}),X=0,Z=new Xe.default(100);function H(){let Qt=new Xe.default(0);for(;;)try{return{vaultOwner:ut.PublicKey.createProgramAddressSync([C.publicKey.toBuffer(),Qt.toArrayLike(Buffer,"le",8)],n),vaultSignerNonce:Qt}}catch{if(Qt.iaddn(1),Qt.gt(new Xe.default(25555)))throw Error("find vault owner error")}}let{vaultOwner:ne,vaultSignerNonce:se}=H(),J=new Xe.default(Math.round(10**r.decimals*b)),ge=new Xe.default(Math.round(b*10**a.decimals*g));if(J.eq($))throw Error("lot size is too small");if(ge.eq($))throw Error("tick size or lot size is too small");let ue=await kr({connection:this.scope.connection,wallet:this.scope.ownerPubKey,marketInfo:{programId:n,vaultOwner:ne,baseMint:r.mint,quoteMint:a.mint,id:C,baseVault:W,quoteVault:D,requestQueue:L,eventQueue:O,bids:R,asks:F,feeRateBps:X,quoteDustThreshold:Z,vaultSignerNonce:se,baseLotSize:J,quoteLotSize:ge,lowestFeeMarket:p}}),he=this.createTxBuilder(A);he.addInstruction({instructions:ue[0].transaction.instructions,signers:ue[0].signer});for await(let Qt of ue.slice(1,ue.length))he.addInstruction({instructions:Qt.transaction.instructions,signers:Qt.signer,instructionTypes:Qt.instructionTypes});let{account:_e,instructionParams:Me}=await this.scope.account.getOrCreateTokenAccount({mint:r.mint,owner:this.scope.ownerPubKey,createInfo:S?{payer:B,amount:s}:void 0,notUseTokenAccount:S,skipCloseAccount:!S,associatedOnly:S?!1:f,checkCreateATAOwner:y,assignSeed:S&&x?`${x}-wsol`:void 0});he.addInstruction(Me||{});let{account:ke,instructionParams:ce}=await this.scope.account.getOrCreateTokenAccount({mint:a.mint,owner:this.scope.ownerPubKey,createInfo:K?{payer:B,amount:u}:void 0,notUseTokenAccount:K,skipCloseAccount:!K,associatedOnly:K?!1:f,checkCreateATAOwner:y,assignSeed:K&&x?`${x}-wsol`:void 0});if(he.addInstruction(ce||{}),_e===void 0)throw Error("you don't has base token account");if(ke===void 0)throw Error("you don't has quote token account");let Le=Ja({version:4,marketVersion:3,marketId:C.publicKey,baseMint:r.mint,quoteMint:a.mint,baseDecimals:r.decimals,quoteDecimals:a.decimals,programId:t,marketProgramId:n}),Ut={programId:t,ammId:Le.id,ammAuthority:Le.authority,ammOpenOrders:Le.openOrders,lpMint:Le.lpMint,coinMint:Le.baseMint,pcMint:Le.quoteMint,coinVault:Le.baseVault,pcVault:Le.quoteVault,withdrawQueue:Le.withdrawQueue,ammTargetOrders:Le.targetOrders,poolTempLp:Le.lpVault,marketProgramId:Le.marketProgramId,marketId:Le.marketId,ammConfigId:Le.configId,feeDestinationId:o},{instruction:ot,instructionType:_n}=ja(E(N({},Ut),{userWallet:this.scope.ownerPubKey,userCoinVault:_e,userPcVault:ke,userLpVault:te(this.scope.ownerPubKey,Le.lpMint,i).publicKey,nonce:Le.nonce,openTime:c,coinAmount:s,pcAmount:u}));he.addInstruction({instructions:[ot],instructionTypes:[_n]});let Xo=S||K?[((ws=Me==null?void 0:Me.instructions)==null?void 0:ws[0])||((Mi=ce==null?void 0:ce.instructions)==null?void 0:Mi[0])].filter(Qt=>!!Qt):void 0;return P===0?he.sizeCheckBuildV0({computeBudgetConfig:k,splitIns:Xo,address:N({requestQueue:L.publicKey,eventQueue:O.publicKey,bids:R.publicKey,asks:F.publicKey,baseVault:W.publicKey,quoteVault:D.publicKey,baseMint:new ut.PublicKey(r.mint),quoteMint:new ut.PublicKey(a.mint)},Ut)}):he.sizeCheckBuild({computeBudgetConfig:k,splitIns:Xo,address:N({requestQueue:L.publicKey,eventQueue:O.publicKey,bids:R.publicKey,asks:F.publicKey,baseVault:W.publicKey,quoteVault:D.publicKey,baseMint:new ut.PublicKey(r.mint),quoteMint:new ut.PublicKey(a.mint)},Ut)})}async getCreatePoolFee({programId:t}){let n=Ar({programId:t}),o=await this.scope.connection.getAccountInfo(n,{dataSlice:{offset:536,length:8}});if(o===null)throw Error("get config account error");return ac.decode(o.data).fee}computeAmountOut({poolInfo:t,amountIn:n,mintIn:o,mintOut:i,slippage:r}){let[a,s]=[o.toString(),i.toString()];if(a!==t.mintA.address&&a!==t.mintB.address)throw new Error("toke not match");if(s!==t.mintA.address&&s!==t.mintB.address)throw new Error("toke not match");let{baseReserve:u,quoteReserve:c}=t,d=[u,c],p=[t.mintA.decimals,t.mintB.decimals],m=a==t.mintA.address?"base":"quote";m==="quote"&&(d.reverse(),p.reverse());let[f,y]=d,[b,g]=p,P=t.version===4,k;if(P)k=new Ge.default(y.toString()).div(10**g).div(new Ge.default(f.toString()).div(10**b));else{let O=mc(this.stableLayout.stableModelData,u.toNumber(),c.toNumber(),!1);m==="quote"?k=new Ge.default(1e6).div(O*1e6):k=new Ge.default(O*1e6).div(1e6)}let I=n,A=new Xe.default(0),h=new Xe.default(0);if(!I.isZero())if(P){h=uo(I.mul(Ua),pr);let O=I.sub(h),R=f.add(O);A=y.mul(O).div(R)}else{h=I.mul(new Xe.default(2)).div(new Xe.default(1e4));let O=I.sub(h);m==="quote"?A=new Xe.default(cc(this.stableLayout.stableModelData,c.toNumber(),u.toNumber(),O.toNumber())):A=new Xe.default(lc(this.stableLayout.stableModelData,c.toNumber(),u.toNumber(),O.toNumber()))}let B=new Xe.default(new Ge.default(A.toString()).mul(1-r).toFixed(0)),S=A,K=B,x=new Ge.default(A.toString()).div(new Ge.default(I.sub(h).toString()).toFixed(0));!I.isZero()&&!A.isZero()&&(x=new Ge.default(A.toString()).div(10**g).div(new Ge.default(I.sub(h).toString()).div(10**b)));let C=k.sub(x).div(k).mul(100);return{amountOut:S,minAmountOut:K,currentPrice:k,executionPrice:x,priceImpact:C,fee:h}}computeAmountIn({poolInfo:t,amountOut:n,mintIn:o,mintOut:i,slippage:r}){let{baseReserve:a,quoteReserve:s}=t;o.toString()!==t.mintA.address&&o.toString()!==t.mintB.address&&this.logAndCreateError("mintIn does not match pool"),i.toString()!==t.mintA.address&&i.toString()!==t.mintB.address&&this.logAndCreateError("mintOut does not match pool"),this.logDebug("baseReserve:",a.toString()),this.logDebug("quoteReserve:",s.toString());let u=o.toString()===t.mintA.address,[c,d]=u?[t.mintA,t.mintB]:[t.mintB,t.mintA];this.logDebug("currencyOut:",d.symbol||d.address),this.logDebug("amountOut:",new Ge.default(n.toString()).div(10**d.decimals).toDecimalPlaces(d.decimals).toString(),c.symbol||c.address),this.logDebug("slippage:",`${r*100}%`);let p=[a,s],m=u?"quote":"base";m==="base"&&p.reverse(),this.logDebug("output side:",m);let[f,y]=p,b=new Ge.default(y.toString()).div(10**t[u?"mintB":"mintA"].decimals).div(new Ge.default(f.toString()).div(10**t[u?"mintA":"mintB"].decimals));this.logDebug("currentPrice:",`1 ${c.symbol||c.address} \u2248 ${b.toString()} ${d.symbol||d.address}`),this.logDebug("currentPrice invert:",`1 ${d.symbol||d.address} \u2248 ${new Ge.default(1).div(b).toString()} ${c.symbol||c.address}`);let g=new Xe.default(0),P=n,k=new Xe.default(0);if(!P.isZero()){P.gt(y)&&(P=y.sub(new Xe.default(1)));let x=y.sub(P),C=f.mul(P).div(x);g=C.mul(pr).div(pr.sub(Ua)),k=g.sub(C)}let I=new Xe.default(new Ge.default(g.toString()).mul(1+r).toFixed(0)),A=g,h=I;this.logDebug("amountIn:",new Ge.default(A.toString()).div(10**c.decimals).toDecimalPlaces(c.decimals).toString()),this.logDebug("maxAmountIn:",new Ge.default(h.toString()).div(10**c.decimals).toDecimalPlaces(c.decimals).toString());let B=null;!g.isZero()&&!P.isZero()&&(B=new Ge.default(P.toString()).div(10**d.decimals).div(new Ge.default(g.toString()).div(10**c.decimals)),this.logDebug("executionPrice:",`1 ${d.symbol||d.address} \u2248 ${B.toDecimalPlaces(Math.max(t.mintA.decimals,t.mintB.decimals)).toString()} ${c.symbol||c.address}`),this.logDebug("executionPrice invert:",`1 ${d.symbol||d.address} \u2248 ${new Ge.default(1).div(B).toDecimalPlaces(Math.max(t.mintA.decimals,t.mintB.decimals)).toString()} ${c.symbol||c.address}`));let S=b.mul(A.toString()),K=S.sub(n.toString()).abs().div(S);return this.logDebug("priceImpact:",`${K.toString()}%`),{amountIn:A,maxAmountIn:h,currentPrice:b,executionPrice:B,priceImpact:K,fee:k}}async swap({poolInfo:t,poolKeys:n,amountIn:o,amountOut:i,inputMint:r,fixedSide:a,txVersion:s,config:u,computeBudgetConfig:c,txTipConfig:d,feePayer:p}){let m=this.createTxBuilder(p),{associatedOnly:f=!0,inputUseSolBalance:y=!0,outputUseSolBalance:b=!0}=u||{},[g,P]=r===t.mintA.address?[t.mintA,t.mintB]:[t.mintB,t.mintA],k=y&&g.address===ee.toBase58(),I=b&&P.address===ee.toBase58(),{account:A,instructionParams:h}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:Rt.TOKEN_PROGRAM_ID,mint:new ut.PublicKey(g.address),owner:this.scope.ownerPubKey,createInfo:k?{payer:this.scope.ownerPubKey,amount:o}:void 0,skipCloseAccount:!k,notUseTokenAccount:k,associatedOnly:f});m.addInstruction(h||{}),A||this.logAndCreateError("input token account not found",{token:g.symbol||g.address,tokenAccountIn:A,inputTokenUseSolBalance:k,associatedOnly:f});let{account:B,instructionParams:S}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:Rt.TOKEN_PROGRAM_ID,mint:new ut.PublicKey(P.address),owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!I,notUseTokenAccount:I,associatedOnly:I?!1:f});m.addInstruction(S||{}),B===void 0&&this.logAndCreateError("output token account not found",{token:P.symbol||P.address,tokenAccountOut:B,outputTokenUseSolBalance:I,associatedOnly:f});let K=n||await this.getAmmPoolKeys(t.id),x=4;return t.pooltype.includes("StablePool")&&(x=5),m.addInstruction({instructions:[x===4?yr({version:x,poolKeys:K,userKeys:{tokenAccountIn:A,tokenAccountOut:B,owner:this.scope.ownerPubKey},amountIn:o,amountOut:i,fixedSide:a}):br({version:x,poolKeys:K,userKeys:{tokenAccountIn:A,tokenAccountOut:B,owner:this.scope.ownerPubKey},amountIn:o,amountOut:i,fixedSide:a})],instructionTypes:[x===4?Y.AmmV4SwapBaseIn:Y.AmmV5SwapBaseIn]}),m.addCustomComputeBudget(c),m.addTipInstruction(d),m.versionBuild({txVersion:s})}async getRpcPoolInfo(t){return(await this.getRpcPoolInfos([t]))[t]}async getRpcPoolInfos(t,n){let o=await qe(this.scope.connection,t.map(c=>({pubkey:new ut.PublicKey(c)})),n),i={},r=[];for(let c=0;c<t.length;c++){let d=o[c];if(d===null||!d.accountInfo)throw Error("fetch pool info error: "+String(t[c]));let p=wi.decode(d.accountInfo.data);i[String(t[c])]=E(N({},p),{programId:d.accountInfo.owner}),r.push(p.baseVault,p.quoteVault)}let a={},s=await qe(this.scope.connection,r.map(c=>({pubkey:new ut.PublicKey(c)})),n);for(let c=0;c<r.length;c++){let d=s[c].accountInfo;if(d===null)throw Error("fetch vault info error: "+r[c]);a[String(r[c])]=new Xe.default(Rt.AccountLayout.decode(d.data).amount.toString())}let u={};for(let[c,d]of Object.entries(i)){let p=a[d.baseVault.toString()].sub(d.baseNeedTakePnl),m=a[d.quoteVault.toString()].sub(d.quoteNeedTakePnl);u[c]=E(N({},d),{baseReserve:p,mintAAmount:a[d.baseVault.toString()],mintBAmount:a[d.quoteVault.toString()],quoteReserve:m,poolPrice:new Ge.default(m.toString()).div(new Ge.default(10).pow(d.quoteDecimal.toString())).div(new Ge.default(p.toString()).div(new Ge.default(10).pow(d.baseDecimal.toString())))})}return u}async getPoolInfoFromRpc({poolId:t}){let n=await this.getRpcPoolInfo(t),o=wr({[t]:n}),i=o[t],r=await this.scope.tradeV2.computePoolToPoolKeys({pools:[o[t]],ammRpcData:{[t]:n}});return{poolRpcData:n,poolInfo:i,poolKeys:r[0]}}async fetchPoolBalances(){await this.scope.account.fetchWalletTokenAccounts({forceUpdate:!0});let t=this.scope.account.tokenAccounts.filter(a=>!a.mint.equals(ut.PublicKey.default)&&!a.amount.isZero()).map(a=>a.mint),i=(await Lt(this.scope.connection,t)).map((a,s)=>a&&a.data.length===Rt.MintLayout.span?E(N({},Rt.MintLayout.decode(a.data)),{address:t[s]}):void 0).filter(Boolean).filter(a=>this.scope.cluster==="devnet"?a:rc.has(a.mintAuthority.toString())),r=await this.scope.api.fetchPoolByLpMints({ids:i.map(a=>a.address.toBase58()).join(",")});return i.map((a,s)=>{var u,c;return{mintData:a,address:a.address,poolInfo:r[s],balance:(c=(u=this.scope.account.tokenAccounts.find(d=>d.mint.equals(a.address)))==null?void 0:u.amount)!=null?c:new Xe.default(0)}})}};var U=require("@solana/web3.js"),Re=require("@solana/spl-token");var bc=ie(require("bn.js"));var Ir=ie(require("bn.js"));function fc(l,e){if(e.isZero())throw Error("divisor is zero");return l.mod(e)}function kf(l,e){if(e.isZero())throw Error("rhs is zero");let t=l.div(e);return fc(l,e).gt(hr)&&(t=t.add(new Ir.default(1))),[t,e]}var hr=new Ir.default(0),Bi=class{static swapBaseInputWithoutFees(e,t,n){let o=e.mul(n),i=t.add(e);return o.div(i)}static swapBaseOutputWithoutFees(e,t,n){let o=t.mul(e),i=n.sub(e),[r]=kf(o,i);return r}static lpTokensToTradingTokens(e,t,n,o,i){let r=e.mul(n).div(t),a=e.mul(o).div(t);if(i===0)return{tokenAmount0:r,tokenAmount1:a};if(i===1)return fc(e.mul(n),t).gt(hr)&&r.gt(hr)&&(r=r.add(new Ir.default(1))),fc(e.mul(o),t).gt(hr)&&a.gt(hr)&&(a=a.add(new Ir.default(1))),{tokenAmount0:r,tokenAmount1:a};throw Error("roundDirection value error")}};var id=ie(require("bn.js"));var nn=class{static tradingFee(e,t){return Wi(e,t,et)}static protocolFee(e,t){return Hr(e,t,et)}static fundFee(e,t){return Hr(e,t,et)}static creatorFee(e,t){return Wi(e,t,et)}static splitCreatorFee(e,t,n){return Hr(e,n,t.add(n))}static calculatePreFeeAmount(e,t){if(t.isZero())return e;let n=e.mul(et),o=et.sub(t);return n.add(o).sub(new id.default(1)).div(o)}};var yc=(t=>(t[t.Floor=0]="Floor",t[t.Ceiling=1]="Ceiling",t))(yc||{}),rd=(t=>(t[t.ZeroForOne=0]="ZeroForOne",t[t.OneForZero=1]="OneForZero",t))(rd||{}),ad=(t=>(t[t.OneForZero=0]="OneForZero",t[t.ZeroForOne=1]="ZeroForOne",t))(ad||{}),xi=class{static validate_supply(e,t){if(e.isZero())throw Error("tokenAmount0 is zero");if(t.isZero())throw Error("tokenAmount1 is zero")}static swapBaseInput(e,t,n,o,i,r,a,s){let u=new bc.default(0),c=nn.tradingFee(e,o),d;s?(u=nn.creatorFee(e,i),d=e.sub(c).sub(u)):d=e.sub(c);let p=nn.protocolFee(c,r),m=nn.protocolFee(c,a),f=Bi.swapBaseInputWithoutFees(d,t,n),y;return s?y=f:(u=nn.creatorFee(f,i),y=f.sub(u)),{newInputVaultAmount:t.add(d),newOutputVaultAmount:n.sub(f),inputAmount:e,outputAmount:y,tradeFee:c,protocolFee:p,fundFee:m,creatorFee:u}}static swapBaseOutput(e,t,n,o,i,r,a,s){let u,c=new bc.default(0),d;if(s)d=e;else{let b=nn.calculatePreFeeAmount(e,i);c=b.sub(e),d=b}let p=Bi.swapBaseOutputWithoutFees(d,t,n),m;if(s){let b=nn.calculatePreFeeAmount(p,o.add(i)),g=b.sub(p);c=nn.splitCreatorFee(g,o,i),u=g.sub(c),m=b}else{let b=nn.calculatePreFeeAmount(p,o);u=b.sub(p),m=b}let f=nn.protocolFee(u,r),y=nn.fundFee(u,a);return{newInputVaultAmount:t.add(p),newOutputVaultAmount:n.sub(d),inputAmount:m,outputAmount:e,tradeFee:u,protocolFee:f,fundFee:y,creatorFee:c}}};var Ze=ie(require("bn.js")),yn=ie(require("decimal.js"));var nt=require("@solana/web3.js"),kt=require("@solana/spl-token");var Tf=Buffer.from("vault_and_lp_mint_auth_seed","utf8"),hf=Buffer.from("amm_config","utf8"),If=Buffer.from("pool","utf8"),Bf=Buffer.from("pool_lp_mint","utf8"),xf=Buffer.from("pool_vault","utf8"),Sf=Buffer.from("observation","utf8"),Kf=Buffer.from("permission","utf8"),Cf=Buffer.from("support_mint","utf8");function go(l){return re([Tf],l)}function Rf(l,e){return re([hf,Lf(e)],l)}function ts(l,e,t,n){return re([If,e.toBuffer(),t.toBuffer(),n.toBuffer()],l)}function sd(l,e){return re([Bf,e.toBuffer()],l)}function gc(l,e,t){return re([xf,e.toBuffer(),t.toBuffer()],l)}function Po(l,e){return re([Sf,e.toBuffer()],l)}function Lf(l){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,l,!1),new Uint8Array(e)}function ns({poolId:l,programId:e,configId:t,mintA:n,mintB:o}){let i=go(e).publicKey,r=l||ts(e,t,n,o).publicKey,a=sd(e,r).publicKey,s=gc(e,r,n).publicKey,u=gc(e,r,o).publicKey,c=Po(e,r).publicKey;return{poolId:r,configId:t,authority:i,lpMint:a,vaultA:s,vaultB:u,observationId:c}}var ud=Buffer.from("locked_liquidity","utf8");function Wo(l,e){return re([ud,e.toBuffer()],l)}function Pc(l,e){return re([Kf,e.toBuffer()],l)}function os(l,e){return re([Cf,e.toBuffer()],l)}var Of=Se("Raydium_cpmm"),zn={initialize:[175,175,109,31,13,152,155,237],deposit:[242,35,198,137,82,225,242,182],withdraw:[183,18,70,156,148,109,161,34],swapBaseInput:[143,190,90,218,196,30,51,222],swapBaseOutput:[55,217,98,86,163,74,180,173],lockCpLiquidity:[216,157,29,78,38,51,31,26],collectCpFee:[8,30,51,199,209,184,247,133],createPermissionPda:Buffer.from([135,136,2,216,137,169,181,202]),closePermissionPda:Buffer.from([156,84,32,118,69,135,70,123]),initializeWithPermission:Buffer.from([63,55,254,65,49,178,89,121]),collectCreatorFee:Buffer.from([20,22,86,123,198,28,219,132]),collectCreatorFeePermissionless:Buffer.from([202,202,34,83,226,122,145,229])};function Ac(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k,I){let A=v([w("amountMaxA"),w("amountMaxB"),w("openTime")]),h=ts(l,t,i,r).publicKey,B=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!o.equals(h),isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!0},{pubkey:kt.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:y,isSigner:!1,isWritable:!1},{pubkey:kt.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:Al,isSigner:!1,isWritable:!1},{pubkey:It,isSigner:!1,isWritable:!1},...(I!=null?I:[]).map(K=>({pubkey:K,isSigner:!1,isWritable:!1}))],S=Buffer.alloc(A.span);return A.encode({amountMaxA:g,amountMaxB:P,openTime:k},S),new nt.TransactionInstruction({keys:B,programId:l,data:Buffer.from([...zn.initialize,...S])})}function wc(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f){let y=v([w("lpAmount"),w("amountMaxA"),w("amountMaxB")]),b=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:kt.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:kt.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!0}],g=Buffer.alloc(y.span);return Of.debug("cpmm deposit data",{lpAmount:p.toString(),amountMaxA:m.toString(),amountMaxB:f.toString()}),y.encode({lpAmount:p,amountMaxA:m,amountMaxB:f},g),new nt.TransactionInstruction({keys:b,programId:l,data:Buffer.from([...zn.deposit,...g])})}function kc(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f){let y=v([w("lpAmount"),w("amountMinA"),w("amountMinB")]),b=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:kt.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:kt.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:mn,isSigner:!1,isWritable:!1}],g=Buffer.alloc(y.span);return y.encode({lpAmount:p,amountMinA:m,amountMinB:f},g),new nt.TransactionInstruction({keys:b,programId:l,data:Buffer.from([...zn.withdraw,...g])})}function qo(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f,y){let b=v([w("amountIn"),w("amounOutMin")]),g=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!0}],P=Buffer.alloc(b.span);return b.encode({amountIn:f,amounOutMin:y},P),new nt.TransactionInstruction({keys:g,programId:l,data:Buffer.from([...zn.swapBaseInput,...P])})}function Tc(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f,y){let b=v([w("amountInMax"),w("amountOut")]),g=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!0}],P=Buffer.alloc(b.span);return b.encode({amountInMax:f,amountOut:y},P),new nt.TransactionInstruction({keys:g,programId:l,data:Buffer.from([...zn.swapBaseOutput,...P])})}async function hc(l){var b;let{ownerInfo:e,poolInfo:t,poolKeys:n,feeNftOwner:o,getEphemeralSigners:i}=l,r=[],[a,s]=[new nt.PublicKey(t.id),new nt.PublicKey(t.lpMint.address)],u;if(i)u=new nt.PublicKey((await i(1))[0]);else{let g=nt.Keypair.generate();r.push(g),u=g.publicKey}let{publicKey:c}=te(o,u,kt.TOKEN_PROGRAM_ID),{publicKey:d}=qn(u),{publicKey:p}=Wo(l.lockProgram,u),{publicKey:m}=te(e.wallet,s,kt.TOKEN_PROGRAM_ID),{publicKey:f}=te(l.lockAuthProgram,s,kt.TOKEN_PROGRAM_ID),y=cd({programId:l.lockProgram,auth:l.lockAuthProgram,payer:e.feePayer,liquidityOwner:e.wallet,nftOwner:o,nftMint:u,nftAccount:c,poolId:a,lockPda:p,mintLp:s,userLpVault:m,lockLpVault:f,poolVaultA:new nt.PublicKey(n.vault.A),poolVaultB:new nt.PublicKey(n.vault.B),metadataAccount:d,lpAmount:l.lpAmount,withMetadata:(b=l.withMetadata)!=null?b:!0});return{address:{nftMint:u,nftAccount:c,metadataAccount:d,lockPda:p,userLpVault:m,lockLpVault:f},instructions:[y],signers:r,instructionTypes:[Y.CpmmLockLp],lookupTableAddress:[]}}function cd({programId:l,auth:e,payer:t,liquidityOwner:n,nftOwner:o,nftMint:i,nftAccount:r,poolId:a,lockPda:s,mintLp:u,userLpVault:c,lockLpVault:d,poolVaultA:p,poolVaultB:m,metadataAccount:f,lpAmount:y,withMetadata:b}){let g=[{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:n,isSigner:!0,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!0,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:It,isSigner:!1,isWritable:!1},{pubkey:nt.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:kt.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:kt.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:Kn,isSigner:!1,isWritable:!1}],P=v([w("lpAmount"),tt("withMetadata")]),k=Buffer.alloc(P.span);P.encode({lpAmount:y,withMetadata:b},k);let I=Buffer.from([...zn.lockCpLiquidity,...k]);return new nt.TransactionInstruction({keys:g,programId:l,data:I})}function is({programId:l,nftOwner:e,auth:t,nftAccount:n,lockPda:o,poolId:i,mintLp:r,userVaultA:a,userVaultB:s,poolVaultA:u,poolVaultB:c,mintA:d,mintB:p,lockLpVault:m,lpFeeAmount:f,cpmmProgram:y,cpmmAuthProgram:b}){let g=[{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:y!=null?y:Qn,isSigner:!1,isWritable:!1},{pubkey:b!=null?b:Gs,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:kt.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:kt.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:mn,isSigner:!1,isWritable:!1}],P=v([w("lpFeeAmount")]),k=Buffer.alloc(P.span);P.encode({lpFeeAmount:f},k);let I=Buffer.from([...zn.collectCpFee,...k]);return new nt.TransactionInstruction({keys:g,programId:l,data:I})}function rs(l,e,t,n,o,i,r,a,s,u,c,d,p){let m=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:kt.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:nt.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new nt.TransactionInstruction({keys:m,programId:l,data:zn.collectCreatorFee})}function Ic(l,e,t,n,o,i,r,a,s,u,c,d,p){let m=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:kt.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:nt.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new nt.TransactionInstruction({keys:m,programId:l,data:zn.collectCreatorFeePermissionless})}function Bc(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k,I,A,h,B){let S=v([w("amountA"),w("amountB"),w("openTime"),V("feeOn")]),K=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:g,isSigner:!1,isWritable:!0},{pubkey:P,isSigner:!1,isWritable:!0},{pubkey:kt.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:y,isSigner:!1,isWritable:!1},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:kt.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:nt.SystemProgram.programId,isSigner:!1,isWritable:!1},...(B!=null?B:[]).map(C=>({pubkey:C,isSigner:!1,isWritable:!1}))],x=Buffer.alloc(S.span);return S.encode({amountA:k,amountB:I,openTime:A,feeOn:h},x),new nt.TransactionInstruction({keys:K,programId:l,data:Buffer.from([...zn.initializeWithPermission,...x])})}var xc=v([Be(8),V("bump"),tt("disableCreatePool"),lt("index"),w("tradeFeeRate"),w("protocolFeeRate"),w("fundFeeRate"),w("createPoolFee"),M("protocolOwner"),M("fundOwner"),w("creatorFeeRate"),j(w(),15)]),Br=v([Be(8),M("configId"),M("poolCreator"),M("vaultA"),M("vaultB"),M("mintLp"),M("mintA"),M("mintB"),M("mintProgramA"),M("mintProgramB"),M("observationId"),V("bump"),V("status"),V("lpDecimals"),V("mintDecimalA"),V("mintDecimalB"),w("lpAmount"),w("protocolFeesMintA"),w("protocolFeesMintB"),w("fundFeesMintA"),w("fundFeesMintB"),w("openTime"),w("epoch"),V("feeOn"),tt("enableCreatorFee"),j(V(),6),w("creatorFeesMintA"),w("creatorFeesMintB"),j(w(),28)]),Nf=v([Be(8),M("configId"),j(w(),30)]);var Sc=(n=>(n[n.BothToken=0]="BothToken",n[n.OnlyTokenA=1]="OnlyTokenA",n[n.OnlyTokenB=2]="OnlyTokenB",n))(Sc||{});var xr=class extends at{constructor(e){super(e)}async load(){this.checkDisabled()}async getCpmmPoolKeys(e){return(await this.scope.api.fetchPoolKeysById({idList:[e]}))[0]}async getRpcPoolInfo(e,t){return(await this.getRpcPoolInfos([e],t))[e]}async getRpcPoolInfos(e,t){let n=await qe(this.scope.connection,e.map(d=>({pubkey:new U.PublicKey(d)}))),o={},i=new Set,r=[];for(let d=0;d<e.length;d++){let p=n[d];if(p.accountInfo===null)throw Error("fetch pool info error: "+String(e[d]));let m=Br.decode(p.accountInfo.data);o[String(e[d])]=E(N({},m),{programId:p.accountInfo.owner}),i.add(String(m.configId)),r.push(m.vaultA,m.vaultB)}let a={};if(t){let d=[...i],p=await qe(this.scope.connection,d.map(m=>({pubkey:new U.PublicKey(m)})));for(let m=0;m<d.length;m++){let f=p[m].accountInfo;if(f===null)throw Error("fetch pool config error: "+d[m]);a[d[m]]=xc.decode(f.data)}}let s={},u=await qe(this.scope.connection,r.map(d=>({pubkey:new U.PublicKey(d)})));for(let d=0;d<r.length;d++){let p=u[d].accountInfo;if(p===null)throw Error("fetch vault info error: "+r[d]);s[String(r[d])]=new Ze.default(Re.AccountLayout.decode(p.data).amount.toString())}let c={};for(let[d,p]of Object.entries(o)){let m=s[p.vaultA.toString()].sub(p.protocolFeesMintA).sub(p.fundFeesMintA).sub(p.creatorFeesMintA),f=s[p.vaultB.toString()].sub(p.protocolFeesMintB).sub(p.fundFeesMintB).sub(p.creatorFeesMintB);c[d]=E(N({},p),{baseReserve:m,quoteReserve:f,vaultAAmount:s[p.vaultA.toString()],vaultBAmount:s[p.vaultB.toString()],configInfo:a[p.configId.toString()],poolPrice:new yn.default(f.toString()).div(new yn.default(10).pow(p.mintDecimalB)).div(new yn.default(m.toString()).div(new yn.default(10).pow(p.mintDecimalA)))})}return c}toComputePoolInfos({pools:e,mintInfos:t}){return Object.keys(e).reduce((n,o)=>{var s,u,c,d;let i=e[o],[r,a]=[i.mintA.toBase58(),i.mintB.toBase58()];return E(N({},n),{[o]:E(N({},i),{id:new U.PublicKey(o),configInfo:i.configInfo,version:7,authority:go(i.programId).publicKey,mintA:At({address:r,decimals:i.mintDecimalA,programId:i.mintProgramA.toBase58(),extensions:{feeConfig:(s=t[r])!=null&&s.feeConfig?Nn((u=t[r])==null?void 0:u.feeConfig):void 0}}),mintB:At({address:a,decimals:i.mintDecimalB,programId:i.mintProgramB.toBase58(),extensions:{feeConfig:(c=t[a])!=null&&c.feeConfig?Nn((d=t[a])==null?void 0:d.feeConfig):void 0}})})})},{})}async getPoolInfoFromRpc(e){let t=await this.getRpcPoolInfo(e,!0),n=await ho({connection:this.scope.connection,mints:[t.mintA,t.mintB]}),o=At({address:t.mintA.toBase58(),decimals:t.mintDecimalA,programId:t.mintProgramA.toBase58(),extensions:{feeConfig:n[t.mintA.toBase58()].feeConfig?Nn(n[t.mintA.toBase58()].feeConfig):void 0}}),i=At({address:t.mintB.toBase58(),decimals:t.mintDecimalB,programId:t.mintProgramB.toBase58(),extensions:{feeConfig:n[t.mintB.toBase58()].feeConfig?Nn(n[t.mintB.toBase58()].feeConfig):void 0}}),r=At({address:t.mintLp.toBase58(),decimals:t.lpDecimals,programId:Re.TOKEN_PROGRAM_ID.toBase58()}),a={id:t.configId.toBase58(),index:t.configInfo.index,protocolFeeRate:t.configInfo.protocolFeeRate.toNumber(),tradeFeeRate:t.configInfo.tradeFeeRate.toNumber(),fundFeeRate:t.configInfo.fundFeeRate.toNumber(),createPoolFee:t.configInfo.createPoolFee.toString()},s={volume:0,volumeQuote:0,volumeFee:0,apr:0,feeApr:0,priceMin:0,priceMax:0,rewardApr:[]};return{poolInfo:{programId:t.programId.toBase58(),id:e,type:"Standard",lpMint:r,lpPrice:0,lpAmount:t.lpAmount.toNumber(),config:a,mintA:o,mintB:i,rewardDefaultInfos:[],rewardDefaultPoolInfos:"Ecosystem",price:t.poolPrice.toNumber(),mintAmountA:new yn.default(t.vaultAAmount.toString()).div(10**o.decimals).toNumber(),mintAmountB:new yn.default(t.vaultBAmount.toString()).div(10**i.decimals).toNumber(),feeRate:t.configInfo.tradeFeeRate.toNumber(),openTime:t.openTime.toString(),tvl:0,burnPercent:0,day:s,week:s,month:s,pooltype:[],farmUpcomingCount:0,farmOngoingCount:0,farmFinishedCount:0,feeOn:"",hasDynamicFee:!1,launchMigratePool:!1,tips:[]},poolKeys:{programId:t.programId.toBase58(),id:e,mintA:o,mintB:i,openTime:t.openTime.toString(),vault:{A:t.vaultA.toBase58(),B:t.vaultB.toBase58()},authority:go(t.programId).publicKey.toBase58(),mintLp:r,config:a,observationId:Po(t.programId,new U.PublicKey(e)).publicKey.toBase58()},rpcData:t,computePoolInfo:E(N({},t),{id:new U.PublicKey(e),configInfo:t.configInfo,version:7,authority:go(t.programId).publicKey,mintA:o,mintB:i})}}async createPool(y){var b=y,{poolId:e,programId:t,poolFeeAccount:n,startTime:o,ownerInfo:i,associatedOnly:r=!1,checkCreateATAOwner:a=!1,txVersion:s,feeConfig:u,computeBudgetConfig:c,txTipConfig:d,feePayer:p,addSupportMintExt:m}=b,f=$e(b,["poolId","programId","poolFeeAccount","startTime","ownerInfo","associatedOnly","checkCreateATAOwner","txVersion","feeConfig","computeBudgetConfig","txTipConfig","feePayer","addSupportMintExt"]);var Z,H,ne;let g=i.feePayer||((Z=this.scope.owner)==null?void 0:Z.publicKey),P=new Ze.default(new U.PublicKey(f.mintA.address).toBuffer()).lte(new Ze.default(new U.PublicKey(f.mintB.address).toBuffer())),[k,I]=P?[f.mintA,f.mintB]:[f.mintB,f.mintA],[A,h]=P?[f.mintAAmount,f.mintBAmount]:[f.mintBAmount,f.mintAAmount],B=i.useSOLBalance&&k.address===Re.NATIVE_MINT.toBase58(),S=i.useSOLBalance&&I.address===Re.NATIVE_MINT.toBase58(),[K,x]=[new U.PublicKey(k.address),new U.PublicKey(I.address)],C=this.createTxBuilder(p),{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({mint:K,tokenProgram:k.programId,owner:this.scope.ownerPubKey,createInfo:B?{payer:g,amount:A}:void 0,notUseTokenAccount:B,skipCloseAccount:!B,associatedOnly:B?!1:r,checkCreateATAOwner:a});C.addInstruction(O||{});let{account:R,instructionParams:F}=await this.scope.account.getOrCreateTokenAccount({mint:new U.PublicKey(I.address),tokenProgram:I.programId,owner:this.scope.ownerPubKey,createInfo:S?{payer:g,amount:h}:void 0,notUseTokenAccount:S,skipCloseAccount:!S,associatedOnly:S?!1:r,checkCreateATAOwner:a});if(C.addInstruction(F||{}),L===void 0||R===void 0)throw Error(`you don't has some token account, userVaultA: ${L==null?void 0:L.toBase58()}, userVaultB: ${R==null?void 0:R.toBase58()}`);let W=ns({poolId:e,programId:t,configId:new U.PublicKey(u.id),mintA:K,mintB:x}),D=[],X=[];return m&&(k.programId===Re.TOKEN_2022_PROGRAM_ID.toBase58()&&X.push(os(t,new U.PublicKey(k.address)).publicKey),I.programId===Re.TOKEN_2022_PROGRAM_ID.toBase58()&&X.push(os(t,new U.PublicKey(I.address)).publicKey),(await this.scope.connection.getMultipleAccountsInfo(X)).forEach((J,ge)=>{J&&D.push(X[ge])})),C.addInstruction({instructions:[Ac(t,this.scope.ownerPubKey,new U.PublicKey(u.id),W.authority,W.poolId,K,x,W.lpMint,L,R,te(this.scope.ownerPubKey,W.lpMint).publicKey,W.vaultA,W.vaultB,n,new U.PublicKey((H=k.programId)!=null?H:Re.TOKEN_PROGRAM_ID),new U.PublicKey((ne=I.programId)!=null?ne:Re.TOKEN_PROGRAM_ID),W.observationId,A,h,o,D)],instructionTypes:[Y.CpmmCreatePool]}),C.addCustomComputeBudget(c),C.addTipInstruction(d),C.versionBuild({txVersion:s,extInfo:{address:E(N({},W),{mintA:k,mintB:I,programId:t,poolFeeAccount:n,feeConfig:u})}})}async addLiquidity(e){let{poolInfo:t,poolKeys:n,inputAmount:o,baseIn:i,slippage:r,computeResult:a,computeBudgetConfig:s,txTipConfig:u,config:c,txVersion:d,feePayer:p}=e;this.scope.availability.addStandardPosition===!1&&this.logAndCreateError("add liquidity feature disabled in your region"),o.isZero()&&this.logAndCreateError("amounts must greater than zero","amountInA",{amountInA:o.toString()});let{account:m}=this.scope,{bypassAssociatedCheck:f,checkCreateATAOwner:y}=N({bypassAssociatedCheck:!1,checkCreateATAOwner:!1},c),b=a?void 0:await this.getRpcPoolInfo(t.id),{liquidity:g,inputAmountFee:P,anotherAmount:k}=a||this.computePairAmount({poolInfo:E(N({},t),{lpAmount:new yn.default(b.lpAmount.toString()).div(10**t.lpMint.decimals).toNumber()}),baseReserve:b.baseReserve,quoteReserve:b.quoteReserve,slippage:new Nt(0),baseIn:i,epochInfo:await this.scope.fetchEpochInfo(),amount:new yn.default(o.toString()).div(10**(i?t.mintA.decimals:t.mintB.decimals))}),I=k.amount,A=t.mintA.address===Re.NATIVE_MINT.toString(),h=t.mintB.address===Re.NATIVE_MINT.toString(),B=this.createTxBuilder(p),[S,K]=[new U.PublicKey(t.mintA.address),new U.PublicKey(t.mintB.address)],{account:x,instructionParams:C}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintA.programId,mint:new U.PublicKey(t.mintA.address),owner:this.scope.ownerPubKey,createInfo:A||(i?o:I).isZero()?{payer:this.scope.ownerPubKey,amount:i?o:I}:void 0,skipCloseAccount:!A,notUseTokenAccount:A,associatedOnly:!1,checkCreateATAOwner:y});B.addInstruction(C||{});let{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintB.programId,mint:new U.PublicKey(t.mintB.address),owner:this.scope.ownerPubKey,createInfo:h||(i?I:o).isZero()?{payer:this.scope.ownerPubKey,amount:i?I:o}:void 0,skipCloseAccount:!h,notUseTokenAccount:h,associatedOnly:!1,checkCreateATAOwner:y});B.addInstruction(O||{}),!x&&!L&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",m.tokenAccounts);let R=await m.getCreatedTokenAccount({mint:new U.PublicKey(t.lpMint.address)}),Z=await m.handleTokenAccount({side:"out",amount:0,mint:new U.PublicKey(t.lpMint.address),tokenAccount:R,bypassAssociatedCheck:f,checkCreateATAOwner:y}),{tokenAccount:F}=Z,W=$e(Z,["tokenAccount"]);B.addInstruction(W);let D=n!=null?n:await this.getCpmmPoolKeys(t.id),X=new Nt(new Ze.default(1)).sub(r);return B.addInstruction({instructions:[wc(new U.PublicKey(t.programId),this.scope.ownerPubKey,new U.PublicKey(D.authority),new U.PublicKey(t.id),F,x,L,new U.PublicKey(D.vault.A),new U.PublicKey(D.vault.B),S,K,new U.PublicKey(t.lpMint.address),a?a==null?void 0:a.liquidity:X.mul(g).quotient,i?P.amount:I,i?I:P.amount)],instructionTypes:[Y.CpmmAddLiquidity],lookupTableAddress:D.lookupTableAccount?[D.lookupTableAccount]:[]}),B.addCustomComputeBudget(s),B.addTipInstruction(u),B.versionBuild({txVersion:d,lookupTableAddress:D.lookupTableAccount?[D.lookupTableAccount]:void 0})}async withdrawLiquidity(e){var W,D;let{poolInfo:t,poolKeys:n,lpAmount:o,slippage:i,computeBudgetConfig:r,txTipConfig:a,txVersion:s,feePayer:u,closeWsol:c=!0}=e;this.scope.availability.addStandardPosition===!1&&this.logAndCreateError("add liquidity feature disabled in your region");let d=new Nt(new Ze.default(1)).sub(i),p=await this.getRpcPoolInfo(t.id),[m,f]=[d.mul(o.mul(p.baseReserve).div(p.lpAmount)).quotient,d.mul(o.mul(p.quoteReserve).div(p.lpAmount)).quotient],y=await this.scope.fetchEpochInfo(),[b,g]=[Bt(m,t.mintA.extensions.feeConfig,y,!1),Bt(f,t.mintB.extensions.feeConfig,y,!1)],{account:P}=this.scope,k=this.createTxBuilder(u),[I,A]=[new U.PublicKey(t.mintA.address),new U.PublicKey(t.mintB.address)],h=I.equals(ee),B=A.equals(ee),S,K,{account:x,instructionParams:C}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintA.programId,mint:new U.PublicKey(t.mintA.address),notUseTokenAccount:h,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!(h&&c),associatedOnly:!h,checkCreateATAOwner:!1});S=x,C&&k.addInstruction(C);let{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintB.programId,mint:new U.PublicKey(t.mintB.address),notUseTokenAccount:B,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!(B&&c),associatedOnly:!B,checkCreateATAOwner:!1});K=L,O&&k.addInstruction(O),(!S||!K)&&this.logAndCreateError("cannot found target token accounts","tokenAccounts",P.tokenAccounts);let R=await P.getCreatedTokenAccount({mint:new U.PublicKey(t.lpMint.address)});R||this.logAndCreateError("cannot found lp token account","tokenAccounts",P.tokenAccounts);let F=n!=null?n:await this.getCpmmPoolKeys(t.id);return k.addInstruction({instructions:[kc(new U.PublicKey(t.programId),this.scope.ownerPubKey,new U.PublicKey(F.authority),new U.PublicKey(t.id),R,S,K,new U.PublicKey(F.vault.A),new U.PublicKey(F.vault.B),I,A,new U.PublicKey(t.lpMint.address),o,m.sub((W=b.fee)!=null?W:new Ze.default(0)),f.sub((D=g.fee)!=null?D:new Ze.default(0)))],instructionTypes:[Y.CpmmWithdrawLiquidity],lookupTableAddress:F.lookupTableAccount?[F.lookupTableAccount]:[]}),k.addCustomComputeBudget(r),k.addTipInstruction(a),k.versionBuild({txVersion:s,lookupTableAddress:F.lookupTableAccount?[F.lookupTableAccount]:void 0})}async swap(e){var C,L,O,R,F,W;let{poolInfo:t,poolKeys:n,baseIn:o,fixedOut:i,inputAmount:r,swapResult:a,slippage:s=0,config:u,computeBudgetConfig:c,txTipConfig:d,txVersion:p,feePayer:m}=e,{bypassAssociatedCheck:f,checkCreateATAOwner:y,associatedOnly:b}=N({bypassAssociatedCheck:!1,checkCreateATAOwner:!1,associatedOnly:!0},u),g=this.createTxBuilder(m),[P,k]=[new U.PublicKey(t.mintA.address),new U.PublicKey(t.mintB.address)];i?a.inputAmount=a.inputAmount.mul(new Ze.default((1+s)*1e4)).div(new Ze.default(1e4)):a.outputAmount=a.outputAmount.mul(new Ze.default((1-s)*1e4)).div(new Ze.default(1e4));let I=t.mintA.address===ee.toBase58(),A=t.mintB.address===ee.toBase58(),{account:h,instructionParams:B}=await this.scope.account.getOrCreateTokenAccount({mint:P,tokenProgram:new U.PublicKey((C=t.mintA.programId)!=null?C:Re.TOKEN_PROGRAM_ID),owner:this.scope.ownerPubKey,createInfo:I||!o?{payer:m||this.scope.ownerPubKey,amount:o?a.inputAmount:0}:void 0,notUseTokenAccount:I,skipCloseAccount:!I,associatedOnly:I?!1:b,checkCreateATAOwner:y});B&&g.addInstruction(B);let{account:S,instructionParams:K}=await this.scope.account.getOrCreateTokenAccount({mint:k,tokenProgram:new U.PublicKey((L=t.mintB.programId)!=null?L:Re.TOKEN_PROGRAM_ID),owner:this.scope.ownerPubKey,createInfo:A||o?{payer:m||this.scope.ownerPubKey,amount:o?0:a.inputAmount}:void 0,notUseTokenAccount:A,skipCloseAccount:!A,associatedOnly:A?!1:b,checkCreateATAOwner:y});K&&g.addInstruction(K),(!h||!S)&&this.logAndCreateError("user do not have token account",{mintA:t.mintA.symbol||t.mintA.address,mintB:t.mintB.symbol||t.mintB.address,mintATokenAcc:h,mintBTokenAcc:S,mintAUseSOLBalance:I,mintBUseSOLBalance:A,associatedOnly:b});let x=n!=null?n:await this.getCpmmPoolKeys(t.id);return g.addInstruction({instructions:[i?Tc(new U.PublicKey(t.programId),this.scope.ownerPubKey,new U.PublicKey(x.authority),new U.PublicKey(x.config.id),new U.PublicKey(t.id),o?h:S,o?S:h,new U.PublicKey(x.vault[o?"A":"B"]),new U.PublicKey(x.vault[o?"B":"A"]),new U.PublicKey((F=t[o?"mintA":"mintB"].programId)!=null?F:Re.TOKEN_PROGRAM_ID),new U.PublicKey((W=t[o?"mintB":"mintA"].programId)!=null?W:Re.TOKEN_PROGRAM_ID),o?P:k,o?k:P,Po(new U.PublicKey(t.programId),new U.PublicKey(t.id)).publicKey,a.inputAmount,a.outputAmount):qo(new U.PublicKey(t.programId),this.scope.ownerPubKey,new U.PublicKey(x.authority),new U.PublicKey(x.config.id),new U.PublicKey(t.id),o?h:S,o?S:h,new U.PublicKey(x.vault[o?"A":"B"]),new U.PublicKey(x.vault[o?"B":"A"]),new U.PublicKey((O=t[o?"mintA":"mintB"].programId)!=null?O:Re.TOKEN_PROGRAM_ID),new U.PublicKey((R=t[o?"mintB":"mintA"].programId)!=null?R:Re.TOKEN_PROGRAM_ID),o?P:k,o?k:P,Po(new U.PublicKey(t.programId),new U.PublicKey(t.id)).publicKey,r,a.outputAmount)],instructionTypes:[i?Y.CpmmSwapBaseOut:Y.ClmmSwapBaseIn]}),g.addCustomComputeBudget(c),g.addTipInstruction(d),g.versionBuild({txVersion:p,lookupTableAddress:x.lookupTableAccount?[x.lookupTableAccount]:void 0})}async lockLp(e){var p,m,f,y,b;let{poolInfo:t,lpAmount:n,computeBudgetConfig:o,txTipConfig:i,txVersion:r,feePayer:a,feeNftOwner:s}=e;n.isZero()&&this.logAndCreateError("lpAmount must greater than zero",{lpAmount:n.toString()});let u=this.createTxBuilder(a),c=(p=e.poolKeys)!=null?p:await this.getCpmmPoolKeys(t.id),d=await hc({poolInfo:t,poolKeys:c,ownerInfo:{wallet:this.scope.ownerPubKey,feePayer:(m=e.feePayer)!=null?m:this.scope.ownerPubKey},feeNftOwner:s!=null?s:this.scope.ownerPubKey,lockProgram:(f=e.programId)!=null?f:jo,lockAuthProgram:(y=e.authProgram)!=null?y:Xi,lpAmount:n,withMetadata:(b=e.withMetadata)!=null?b:!0,getEphemeralSigners:e.getEphemeralSigners});return u.addInstruction(d),u.addCustomComputeBudget(o),u.addTipInstruction(i),u.versionBuild({txVersion:r,extInfo:d.address,lookupTableAddress:c.lookupTableAccount?[c.lookupTableAccount]:void 0})}async harvestLockLp(e){var L;let{poolInfo:t,lpFeeAmount:n,nftMint:o,programId:i=jo,authProgram:r=Xi,cpmmProgram:a,computeBudgetConfig:s,txTipConfig:u,txVersion:c,closeWsol:d=!0}=e;n.isZero()&&this.logAndCreateError("lpFeeAmount must greater than zero",{lpAmount:n.toString()});let p=e.feePayer||this.scope.ownerPubKey,m=this.createTxBuilder(p),[f,y]=[new U.PublicKey(t.mintA.address),new U.PublicKey(t.mintB.address)],b=f.equals(ee),g=y.equals(ee),P,k,{account:I,instructionParams:A}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintA.programId,mint:new U.PublicKey(t.mintA.address),notUseTokenAccount:b,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!(b&&d),associatedOnly:!b,checkCreateATAOwner:!1});P=I,A&&m.addInstruction(A);let{account:h,instructionParams:B}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:t.mintB.programId,mint:new U.PublicKey(t.mintB.address),notUseTokenAccount:g,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!(g&&d),associatedOnly:!g,checkCreateATAOwner:!1});k=h,B&&m.addInstruction(B),(!P||!k)&&this.logAndCreateError("cannot found target token accounts",{tokenAccountA:P,tokenAccountB:k});let S=(L=e.poolKeys)!=null?L:await this.getCpmmPoolKeys(t.id),{publicKey:K}=te(p,o,Re.TOKEN_PROGRAM_ID),{publicKey:x}=Wo(i,o),{publicKey:C}=te(r,new U.PublicKey(t.lpMint.address),Re.TOKEN_PROGRAM_ID);return m.addInstruction({instructions:[is({programId:i,nftOwner:this.scope.ownerPubKey,auth:r,nftMint:o,nftAccount:K,lockPda:x,poolId:new U.PublicKey(t.id),mintLp:new U.PublicKey(S.mintLp.address),userVaultA:P,userVaultB:k,poolVaultA:new U.PublicKey(S.vault.A),poolVaultB:new U.PublicKey(S.vault.B),mintA:f,mintB:y,lockLpVault:C,lpFeeAmount:n,cpmmProgram:a==null?void 0:a.programId,cpmmAuthProgram:a==null?void 0:a.authProgram})],instructionTypes:[Y.CpmmCollectLockFee]}),m.addCustomComputeBudget(s),m.addTipInstruction(u),m.versionBuild({txVersion:c,lookupTableAddress:S.lookupTableAccount?[S.lookupTableAccount]:void 0})}async harvestMultiLockLp(e){var m;let{lockInfo:t,programId:n=jo,authProgram:o=Xi,cpmmProgram:i,computeBudgetConfig:r,txVersion:a,closeWsol:s=!0}=e,u=e.feePayer||this.scope.ownerPubKey,c=this.createTxBuilder(u),d={},p=[];for(let f of t){let{poolInfo:y,lpFeeAmount:b,nftMint:g}=f;if(b.isZero())continue;let[P,k]=[new U.PublicKey(y.mintA.address),new U.PublicKey(y.mintB.address)],I=P.equals(ee),A=k.equals(ee),h=d[y.mintA.address],B=d[y.mintB.address];if(!h)if(I){let{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:y.mintA.programId,mint:new U.PublicKey(y.mintA.address),notUseTokenAccount:!0,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!s,associatedOnly:!1,checkCreateATAOwner:!1});h=L,O&&c.addInstruction(O),d[y.mintA.address]=L}else{let L=new U.PublicKey(y.mintA.address);h=this.scope.account.getAssociatedTokenAccount(L,new U.PublicKey(y.mintA.programId)),c.addInstruction({instructions:[(0,Re.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,h,this.scope.ownerPubKey,L,new U.PublicKey(y.mintA.programId))]}),d[y.mintA.address]=h}if(!B)if(A){let{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:y.mintB.programId,mint:new U.PublicKey(y.mintB.address),notUseTokenAccount:!0,owner:this.scope.ownerPubKey,createInfo:{payer:this.scope.ownerPubKey,amount:0},skipCloseAccount:!s,associatedOnly:!1,checkCreateATAOwner:!1});B=L,O&&c.addInstruction(O),d[y.mintB.address]=L}else{let L=new U.PublicKey(y.mintB.address);B=this.scope.account.getAssociatedTokenAccount(L,new U.PublicKey(y.mintB.programId)),c.addInstruction({instructions:[(0,Re.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,B,this.scope.ownerPubKey,L,new U.PublicKey(y.mintB.programId))]}),d[y.mintB.address]=B}(!h||!B)&&this.logAndCreateError("cannot found target token accounts",{tokenAccountA:h,tokenAccountB:B});let S=(m=f.poolKeys)!=null?m:await this.getCpmmPoolKeys(y.id);S.lookupTableAccount&&p.push(S.lookupTableAccount);let{publicKey:K}=te(u,g,Re.TOKEN_PROGRAM_ID),{publicKey:x}=Wo(n,g),{publicKey:C}=te(o,new U.PublicKey(y.lpMint.address),Re.TOKEN_PROGRAM_ID);c.addInstruction({instructions:[is({programId:n,nftOwner:this.scope.ownerPubKey,auth:o,nftMint:g,nftAccount:K,lockPda:x,poolId:new U.PublicKey(y.id),mintLp:new U.PublicKey(S.mintLp.address),userVaultA:h,userVaultB:B,poolVaultA:new U.PublicKey(S.vault.A),poolVaultB:new U.PublicKey(S.vault.B),mintA:P,mintB:k,lockLpVault:C,lpFeeAmount:b,cpmmProgram:i==null?void 0:i.programId,cpmmAuthProgram:i==null?void 0:i.authProgram})],instructionTypes:[Y.CpmmCollectLockFee]})}return a===0?c.sizeCheckBuildV0({computeBudgetConfig:r,lookupTableAddress:p}):c.sizeCheckBuild({computeBudgetConfig:r})}async createPoolWithPermission(y){var b=y,{poolId:e,programId:t,poolFeeAccount:n,startTime:o,ownerInfo:i,associatedOnly:r=!1,checkCreateATAOwner:a=!1,txVersion:s,feeConfig:u,computeBudgetConfig:c,txTipConfig:d,feePayer:p,feeOn:m}=b,f=$e(b,["poolId","programId","poolFeeAccount","startTime","ownerInfo","associatedOnly","checkCreateATAOwner","txVersion","feeConfig","computeBudgetConfig","txTipConfig","feePayer","feeOn"]);var D,X,Z;console.log("***this method only available for wallet with permissions***");let g=i.feePayer||((D=this.scope.owner)==null?void 0:D.publicKey),P=new Ze.default(new U.PublicKey(f.mintA.address).toBuffer()).lte(new Ze.default(new U.PublicKey(f.mintB.address).toBuffer())),[k,I]=P?[f.mintA,f.mintB]:[f.mintB,f.mintA],[A,h]=P?[f.mintAAmount,f.mintBAmount]:[f.mintBAmount,f.mintAAmount],B=i.useSOLBalance&&k.address===Re.NATIVE_MINT.toBase58(),S=i.useSOLBalance&&I.address===Re.NATIVE_MINT.toBase58(),[K,x]=[new U.PublicKey(k.address),new U.PublicKey(I.address)],C=this.createTxBuilder(p),{account:L,instructionParams:O}=await this.scope.account.getOrCreateTokenAccount({mint:K,tokenProgram:k.programId,owner:this.scope.ownerPubKey,createInfo:B?{payer:g,amount:A}:void 0,notUseTokenAccount:B,skipCloseAccount:!B,associatedOnly:B?!1:r,checkCreateATAOwner:a});C.addInstruction(O||{});let{account:R,instructionParams:F}=await this.scope.account.getOrCreateTokenAccount({mint:new U.PublicKey(I.address),tokenProgram:I.programId,owner:this.scope.ownerPubKey,createInfo:S?{payer:g,amount:h}:void 0,notUseTokenAccount:S,skipCloseAccount:!S,associatedOnly:S?!1:r,checkCreateATAOwner:a});if(C.addInstruction(F||{}),L===void 0||R===void 0)throw Error("you don't has some token account");let W=ns({poolId:e,programId:t,configId:new U.PublicKey(u.id),mintA:K,mintB:x});return C.addInstruction({instructions:[Bc(t,this.scope.ownerPubKey,this.scope.ownerPubKey,new U.PublicKey(u.id),W.authority,W.poolId,K,x,W.lpMint,L,R,te(this.scope.ownerPubKey,W.lpMint).publicKey,W.vaultA,W.vaultB,n,new U.PublicKey((X=k.programId)!=null?X:Re.TOKEN_PROGRAM_ID),new U.PublicKey((Z=I.programId)!=null?Z:Re.TOKEN_PROGRAM_ID),W.observationId,Pc(t,this.scope.ownerPubKey).publicKey,A,h,o,m)],instructionTypes:[Y.CpmmCreatePool]}),C.addCustomComputeBudget(c),C.addTipInstruction(d),C.versionBuild({txVersion:s,extInfo:{address:E(N({},W),{mintA:k,mintB:I,programId:t,poolFeeAccount:n,feeConfig:u})}})}async collectCreatorFees({poolInfo:e,poolKeys:t,programId:n=Qn,txVersion:o,computeBudgetConfig:i,txTipConfig:r,feePayer:a}){let s=a||this.scope.ownerPubKey,u=this.createTxBuilder(s),c=t!=null?t:await this.getCpmmPoolKeys(e.id),[d,p,m,f]=[new U.PublicKey(e.mintA.address),new U.PublicKey(e.mintB.address),new U.PublicKey(e.mintA.programId),new U.PublicKey(e.mintB.programId)],y=this.scope.account.getAssociatedTokenAccount(d,m),b=this.scope.account.getAssociatedTokenAccount(p,f);return u.addInstruction({instructions:[(0,Re.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,y,this.scope.ownerPubKey,d,new U.PublicKey(e.mintA.programId)),(0,Re.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,b,this.scope.ownerPubKey,p,new U.PublicKey(e.mintB.programId))]}),u.addInstruction({instructions:[rs(n,this.scope.ownerPubKey,new U.PublicKey(c.authority),new U.PublicKey(c.id),new U.PublicKey(c.config.id),new U.PublicKey(c.vault.A),new U.PublicKey(c.vault.B),d,p,y,b,m,f)],instructionTypes:[]}),u.addCustomComputeBudget(i),u.addTipInstruction(r),u.versionBuild({txVersion:o})}async collectMultiCreatorFees({poolInfoList:e,poolKeyList:t,programId:n=Qn,txVersion:o,computeBudgetConfig:i,feePayer:r}){let a=r||this.scope.ownerPubKey,s=this.createTxBuilder(a),u={},c=t!=null?t:[];if(!c.length){let p=e.map(b=>b.id),m=95,f=[];for(let b=0;b<p.length;b+=m)f.push(p.slice(b,b+m));c=(await Promise.all(f.map(b=>this.scope.api.fetchPoolKeysById({idList:b})))).flat()}let d=c.reduce((p,m)=>E(N({},p),{[m.id]:m}),{});for(let p of e){let m=d[p.id]||await this.getCpmmPoolKeys(p.id),[f,y,b,g]=[new U.PublicKey(p.mintA.address),new U.PublicKey(p.mintB.address),new U.PublicKey(p.mintA.programId),new U.PublicKey(p.mintB.programId)],P=u[p.mintA.address]||this.scope.account.getAssociatedTokenAccount(f,b),k=u[p.mintB.address]||this.scope.account.getAssociatedTokenAccount(y,g);u[p.mintA.address]=P,u[p.mintB.address]=k,s.addInstruction({instructions:[rs(n,this.scope.ownerPubKey,new U.PublicKey(m.authority),new U.PublicKey(m.id),new U.PublicKey(m.config.id),new U.PublicKey(m.vault.A),new U.PublicKey(m.vault.B),f,y,P,k,b,g)],instructionTypes:[]})}return o===0?s.sizeCheckBuildV0({computeBudgetConfig:i,lookupTableAddress:c.map(p=>p.lookupTableAccount).filter(Boolean),insCountLimit:6}):s.sizeCheckBuild({computeBudgetConfig:i})}async collectCreatorFeesPermissionless({poolInfo:e,poolKeys:t,programId:n=Qn,txVersion:o,computeBudgetConfig:i,txTipConfig:r,feePayer:a}){let s=a||this.scope.ownerPubKey,u=this.createTxBuilder(s),c=t!=null?t:await this.getCpmmPoolKeys(e.id),[d,p,m,f]=[new U.PublicKey(e.mintA.address),new U.PublicKey(e.mintB.address),new U.PublicKey(e.mintA.programId),new U.PublicKey(e.mintB.programId)],y=this.scope.account.getAssociatedTokenAccount(d,m),b=this.scope.account.getAssociatedTokenAccount(p,f);return u.addInstruction({instructions:[(0,Re.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,y,this.scope.ownerPubKey,d,new U.PublicKey(e.mintA.programId)),(0,Re.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,b,this.scope.ownerPubKey,p,new U.PublicKey(e.mintB.programId))]}),u.addInstruction({instructions:[Ic(n,s,this.scope.ownerPubKey,new U.PublicKey(c.authority),new U.PublicKey(c.id),new U.PublicKey(c.vault.A),new U.PublicKey(c.vault.B),d,p,y,b,m,f)],instructionTypes:[]}),u.addCustomComputeBudget(i),u.addTipInstruction(r),u.versionBuild({txVersion:o})}computeSwapAmount({pool:e,amountIn:t,outputMint:n,slippage:o,swapBaseIn:i=!0}){let r=n.toString()===e.mintB.address,a=e.feeOn===0||e.feeOn===2,s=i?xi.swapBaseInput(t,r?e.baseReserve:e.quoteReserve,r?e.quoteReserve:e.baseReserve,e.configInfo.tradeFeeRate,e.configInfo.creatorFeeRate,e.configInfo.protocolFeeRate,e.configInfo.fundFeeRate,a):xi.swapBaseOutput(t,r?e.baseReserve:e.quoteReserve,r?e.quoteReserve:e.baseReserve,e.configInfo.tradeFeeRate,e.configInfo.creatorFeeRate,e.configInfo.protocolFeeRate,e.configInfo.fundFeeRate,a),u=new yn.default(s.outputAmount.toString()).div(s.inputAmount.toString()),c=s.outputAmount.mul(new Ze.default((1-o)*1e4)).div(new Ze.default(1e4));return{allTrade:i?s.inputAmount.eq(t):s.outputAmount.eq(t),amountIn:i?t:s.inputAmount,amountOut:s.outputAmount,minAmountOut:c,executionPrice:u,fee:s.tradeFee,priceImpact:e.poolPrice.sub(u).div(e.poolPrice),swapResult:s}}computePairAmount({poolInfo:e,baseReserve:t,quoteReserve:n,amount:o,slippage:i,epochInfo:r,baseIn:a}){var I,A,h,B,S,K,x,C,L;let s=1-Number(i.toSignificant())/100,u=new Ze.default(new yn.default(o).mul(10**e[a?"mintA":"mintB"].decimals).mul(s).toFixed(0)),c=Bt(u,e[a?"mintA":"mintB"].extensions.feeConfig,r,!1),d=u.sub((I=c.fee)!=null?I:new Ze.default(0)),p=new Ze.default(new yn.default(e.lpAmount).mul(10**e.lpMint.decimals).toFixed(0,yn.default.ROUND_DOWN));this.logDebug("baseReserve:",t.toString(),"quoteReserve:",n.toString()),this.logDebug("tokenIn:",a?e.mintA.symbol:e.mintB.symbol,"amountIn:",u.toString(),"amountInFee:",(h=(A=c.fee)==null?void 0:A.toString())!=null?h:0,"anotherToken:",a?e.mintB.symbol:e.mintA.symbol,"slippage:",`${i.toSignificant()}%`);let m=a?"base":"quote";this.logDebug("input side:",m);let f=d.mul(p).div(m==="base"?t:n),y={amount:$,fee:void 0,expirationTime:void 0};if(!d.isZero()){let O=Mf(f,t,n,p);this.logDebug("lpAmountData:",{amountA:O.amountA.toString(),amountB:O.amountB.toString()}),y=Bt(O[a?"amountB":"amountA"],e[a?"mintB":"mintA"].extensions.feeConfig,r,!0)}let b=new Nt(new Ze.default(1)).add(i),g=new Nt(new Ze.default(1)).sub(i),P=Bt(b.mul(y.amount.sub((B=y.fee)!=null?B:new Ze.default(0))).quotient,e[a?"mintB":"mintA"].extensions.feeConfig,r,!0),k=Bt(g.mul(y.amount.sub((S=y.fee)!=null?S:new Ze.default(0))).quotient,e[a?"mintB":"mintA"].extensions.feeConfig,r,!0);return this.logDebug("anotherAmount:",y.amount.toString(),"anotherAmountFee:",(x=(K=y.fee)==null?void 0:K.toString())!=null?x:0,"maxAnotherAmount:",P.amount.toString(),"maxAnotherAmountFee:",(L=(C=P.fee)==null?void 0:C.toString())!=null?L:0),{inputAmountFee:c,anotherAmount:y,maxAnotherAmount:P,minAnotherAmount:k,liquidity:f}}async fetchCpmmLockBalances(){await this.scope.account.fetchWalletTokenAccounts({forceUpdate:!0});let e=this.scope.account.tokenAccountRawInfos.filter(a=>a.accountInfo.amount.eq(new Ze.default(1))),t=e.map(a=>Wo(this.scope.cluster==="mainnet"?jo:Rn.LOCK_CPMM_PROGRAM,a.accountInfo.mint).publicKey),n=await qe(this.scope.connection,t.map(a=>({pubkey:a}))),o=new Map,i=n.filter((a,s)=>(o.set(a.pubkey.toString(),e[s].accountInfo.mint.toString()),!!a.accountInfo)).map(a=>a.pubkey);return(await Promise.all(i.map(a=>this.scope.api.fetchCpmmLockInfo(a)))).map((a,s)=>E(N({},a),{nftMint:new U.PublicKey(o.get(i[s].toString()))}))}};function Mf(l,e,t,n){let o=l.mul(e).div(n);!o.isZero()&&!l.mul(e).mod(n).isZero()&&(o=o.add(new Ze.default(1)));let i=l.mul(t).div(n);return!i.isZero()&&!l.mul(t).mod(n).isZero()&&(i=i.add(new Ze.default(1))),{amountA:o,amountB:i}}var ye=require("@solana/web3.js"),Pe=require("@solana/spl-token"),Ie=ie(require("bn.js")),Fe=ie(require("decimal.js"));var vn=require("@solana/spl-token"),xe=require("@solana/web3.js"),Xn=ie(require("bn.js"));var no=v([w(),w("epoch"),V("curveType"),lt("index"),w("migrateFee"),w("tradeFeeRate"),w("maxShareFeeRate"),w("minSupplyA"),w("maxLockRate"),w("minSellRateA"),w("minMigrateRateA"),w("minFundRaisingB"),M("mintB"),M("protocolFeeOwner"),M("migrateFeeOwner"),M("migrateToAmmWallet"),M("migrateToCpmmWallet"),j(w(),16)]),ld=v([w("totalLockedAmount"),w("cliffPeriod"),w("unlockPeriod"),w("startTime"),w("totalAllocatedShare")]),wn=v([w(),w("epoch"),V("bump"),V("status"),V("mintDecimalsA"),V("mintDecimalsB"),V("migrateType"),w("supply"),w("totalSellA"),w("virtualA"),w("virtualB"),w("realA"),w("realB"),w("totalFundRaisingB"),w("protocolFee"),w("platformFee"),w("migrateFee"),ld.replicate("vestingSchedule"),M("configId"),M("platformId"),M("mintA"),M("mintB"),M("vaultA"),M("vaultB"),M("creator"),V("mintProgramFlag"),V("cpmmCreatorFeeOn"),w("platformVestingShare"),j(V(),54)]),Ff=v([w(),w("epoch"),M("poolId"),M("beneficiary"),w("claimedAmount"),w("tokenShareAmount"),j(w(),8)]),as=v([V("migrateType"),V("migrateCpmmFeeOn"),w("supply"),w("totalSellA"),w("totalFundRaisingB"),w("totalLockedAmount"),w("cliffPeriod"),w("unlockPeriod")]),md=v([w("epoch"),V("index"),M("configId"),as.replicate("bondingCurveParam"),j(w(),50)]),kn=v([w(),w("epoch"),M("platformClaimFeeWallet"),M("platformLockNftWallet"),w("platformScale"),w("creatorScale"),w("burnScale"),w("feeRate"),j(V(),64,"name"),j(V(),256,"web"),j(V(),256,"img"),M("cpConfigId"),w("creatorFeeRate"),M("transferFeeExtensionAuth"),M("platformVestingWallet"),w("platformVestingScale"),M("platformCpCreator"),V("restrictGlobalConfig"),j(V(),107),Hl(md,"platformCurve")]);var dd=Buffer.from("vault_auth_seed","utf8"),pd=Buffer.from("global_config","utf8"),fd=Buffer.from("pool_vesting","utf8"),yd=Buffer.from("platform_config","utf8"),bd=Buffer.from("platform_fee_vault_auth_seed","utf8"),gd=Buffer.from("creator_fee_vault_auth_seed","utf8"),Pd=Buffer.from("platform_global_access","utf8"),Ad=Buffer.from("platform_allow_config","utf8");function Yt(l){return re([dd],l)}function ss(l,e,t,n){return re([pd,e.toBuffer(),vf(t),or(n)],l)}function Uo(l,e,t){return re([ir,e.toBuffer(),t.toBuffer()],l)}function us(l,e,t){return re([Aa,e.toBuffer(),t.toBuffer()],l)}function oo(l){return re([Buffer.from("__event_authority","utf8")],l)}function vf(l){let e=new ArrayBuffer(1);return new DataView(e).setUint8(0,l),new Uint8Array(e)}function cs(l,e){return re([yd,e.toBuffer()],l)}function Go(l,e,t){return re([fd,e.toBuffer(),t.toBuffer()],l)}function Tn(l,e,t){return re([e.toBuffer(),t.toBuffer()],l)}function ls(l){return re([bd],l)}function hn(l,e,t){return re([e.toBuffer(),t.toBuffer()],l)}function ms(l){return re([gd],l)}function _f(l,e,t){return re([Pd,e.toBuffer(),t.toBuffer()],l)}function Si(l,e,t){return re([Ad,e.toBuffer(),t.toBuffer()],l)}var Tt={initialize:Buffer.from([175,175,109,31,13,152,155,237]),initializeV2:Buffer.from([67,153,175,39,218,16,38,32]),buyExactIn:Buffer.from([250,234,13,123,213,156,19,236]),buyExactOut:Buffer.from([24,211,116,40,105,3,153,56]),sellExactIn:Buffer.from([149,39,222,155,211,124,152,26]),sellExactOut:Buffer.from([95,200,71,34,8,9,11,166]),createVestingAccount:Buffer.from([129,178,2,13,217,172,230,218]),claimVestedToken:Buffer.from([49,33,104,30,189,157,79,35]),createPlatformConfig:Buffer.from([176,90,196,175,253,113,220,20]),claimPlatformFee:Buffer.from([156,39,208,135,76,237,61,72]),updatePlaformConfig:Buffer.from([195,60,76,129,146,45,67,143]),initializeWithToken2022:Buffer.from([37,190,126,222,44,154,171,17]),claimPlatformFeeFromVault:Buffer.from([117,241,198,168,248,218,80,29]),claimCreatorFee:Buffer.from([26,97,138,203,132,171,141,252]),updatePlatformCurveParam:Buffer.from([138,144,138,250,220,128,4,57]),removePlatformCurveParam:Buffer.from([27,30,62,169,93,224,24,145]),createPlatformVestingAccount:Buffer.from([146,71,173,69,98,19,15,106]),createPlatformAllowConfig:Buffer.from([69,71,168,7,214,250,107,102]),closePlatformAllowConfig:Buffer.from([82,205,36,216,16,6,240,215])};function Vf(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k){throw new Error("*** launchlab initialize has been deprecated, please use initializeV2 instead! ***")}function Cc(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k,I,A,h){let B=v([V("decimals"),Et("name"),Et("symbol"),Et("uri")]),S=v([w("totalLockedAmount"),w("cliffPeriod"),w("unlockPeriod"),V("cpmmCreatorFeeOn")]),K=v([V("index"),w("supply"),w("totalFundRaisingB"),V("migrateType")]),x=v([V("index"),w("supply"),w("totalSellA"),w("totalFundRaisingB"),V("migrateType")]),C=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!0,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:vn.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:Kn,isSigner:!1,isWritable:!1},{pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:It,isSigner:!1,isWritable:!1},{pubkey:oo(l).publicKey,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1}];h&&C.push({pubkey:h,isSigner:!1,isWritable:!1});let L=Buffer.alloc(Buffer.from(f,"utf-8").length+Buffer.from(y,"utf-8").length+Buffer.from(b,"utf-8").length+4*3+1),O=Buffer.alloc(S.span),R=Buffer.alloc(g.type==="ConstantCurve"?x.span:K.span);return B.encode({decimals:m,name:f,symbol:y,uri:b},L),g.type==="ConstantCurve"?x.encode(E(N({index:0},g),{migrateType:g.migrateType==="amm"?0:1}),R):g.type==="FixedCurve"?K.encode(E(N({index:1},g),{migrateType:g.migrateType==="amm"?0:1}),R):g.type==="LinearCurve"&&K.encode(E(N({index:2},g),{migrateType:g.migrateType==="amm"?0:1}),R),S.encode({totalLockedAmount:P,cliffPeriod:k,unlockPeriod:I,cpmmCreatorFeeOn:A},O),new xe.TransactionInstruction({keys:C,programId:l,data:Buffer.from([...Tt.initializeV2,...L,...R,...O])})}function Rc(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k,I,A,h){let B=v([V("decimals"),Et("name"),Et("symbol"),Et("uri")]),S=v([w("totalLockedAmount"),w("cliffPeriod"),w("unlockPeriod"),V("cpmmCreatorFeeOn"),V("transferFeeExtensionParamsOption"),v([lt("transferFeeBasePoints"),w("maxinumFee")]).replicate("transferFeeExtensionParams")]),K=v([V("index"),w("supply"),w("totalFundRaisingB"),V("migrateType")]),x=v([V("index"),w("supply"),w("totalSellA"),w("totalFundRaisingB"),V("migrateType")]),C=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!0,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:vn.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:oo(l).publicKey,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1}];h&&C.push({pubkey:h,isSigner:!1,isWritable:!1});let L=Buffer.alloc(Buffer.from(m,"utf-8").length+Buffer.from(f,"utf-8").length+Buffer.from(y,"utf-8").length+4*3+1),O=Buffer.alloc(S.span),R=Buffer.alloc(b.type==="ConstantCurve"?x.span:K.span);return B.encode({decimals:p,name:m,symbol:f,uri:y},L),b.type==="ConstantCurve"?x.encode(E(N({index:0},b),{migrateType:b.migrateType==="amm"?0:1}),R):b.type==="FixedCurve"?K.encode(E(N({index:1},b),{migrateType:b.migrateType==="amm"?0:1}),R):b.type==="LinearCurve"&&K.encode(E(N({index:2},b),{migrateType:b.migrateType==="amm"?0:1}),R),S.encode({totalLockedAmount:g,cliffPeriod:P,unlockPeriod:k,cpmmCreatorFeeOn:I,transferFeeExtensionParamsOption:A?1:0,transferFeeExtensionParams:A!=null?A:{transferFeeBasePoints:0,maxinumFee:new Xn.default(0)}},O),new xe.TransactionInstruction({keys:C,programId:l,data:Buffer.from([...Tt.initializeWithToken2022,...L,...R,...O])})}function Ki(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k){let I=v([w("amountB"),w("minAmountA"),w("shareFeeRate")]),A=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:oo(l).publicKey,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1}];k&&A.push({pubkey:k,isSigner:!1,isWritable:!0}),A.push({pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1}),A.push({pubkey:f,isSigner:!1,isWritable:!0}),A.push({pubkey:y,isSigner:!1,isWritable:!0});let h=Buffer.alloc(I.span);return I.encode({amountB:b,minAmountA:g,shareFeeRate:P!=null?P:new Xn.default(0)},h),new xe.TransactionInstruction({keys:A,programId:l,data:Buffer.from([...Tt.buyExactIn,...h])})}function Lc(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k){let I=v([w("amountA"),w("maxAmountB"),w("shareFeeRate")]),A=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:oo(l).publicKey,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1}];k&&A.push({pubkey:k,isSigner:!1,isWritable:!0}),A.push({pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1}),A.push({pubkey:f,isSigner:!1,isWritable:!0}),A.push({pubkey:y,isSigner:!1,isWritable:!0});let h=Buffer.alloc(I.span);return I.encode({amountA:b,maxAmountB:g,shareFeeRate:P!=null?P:new Xn.default(0)},h),new xe.TransactionInstruction({keys:A,programId:l,data:Buffer.from([...Tt.buyExactOut,...h])})}function Sr(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k){let I=v([w("amountA"),w("minAmountB"),w("shareFeeRate")]),A=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:oo(l).publicKey,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1}];k&&A.push({pubkey:k,isSigner:!1,isWritable:!0}),A.push({pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1}),A.push({pubkey:f,isSigner:!1,isWritable:!0}),A.push({pubkey:y,isSigner:!1,isWritable:!0});let h=Buffer.alloc(I.span);return I.encode({amountA:b,minAmountB:g,shareFeeRate:P!=null?P:new Xn.default(0)},h),new xe.TransactionInstruction({keys:A,programId:l,data:Buffer.from([...Tt.sellExactIn,...h])})}function Oc(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f,y,b,g,P,k){let I=v([w("amountB"),w("maxAmountA"),w("shareFeeRate")]),A=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:p,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:oo(l).publicKey,isSigner:!1,isWritable:!1},{pubkey:l,isSigner:!1,isWritable:!1}];k&&A.push({pubkey:k,isSigner:!1,isWritable:!0}),A.push({pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1}),A.push({pubkey:f,isSigner:!1,isWritable:!0}),A.push({pubkey:y,isSigner:!1,isWritable:!0});let h=Buffer.alloc(I.span);return I.encode({amountB:b,maxAmountA:g,shareFeeRate:P!=null?P:new Xn.default(0)},h),new xe.TransactionInstruction({keys:A,programId:l,data:Buffer.from([...Tt.sellExactOut,...h])})}function ds(l,e,t,n,o,i,r,a,s){let u=v([]),c=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:vn.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}],d=Buffer.alloc(u.span);return u.encode({},d),new xe.TransactionInstruction({keys:c,programId:l,data:Buffer.from([...Tt.claimVestedToken,...d])})}function ps(l,e,t,n,o,i){let r=v([w("shareAmount")]),a=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1}],s=Buffer.alloc(r.span);return r.encode({shareAmount:i},s),new xe.TransactionInstruction({keys:a,programId:l,data:Buffer.from([...Tt.createVestingAccount,...s])})}function fs(l,e,t,n,o,i,r,a,s){let u=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!0},{pubkey:vn.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!0}];return new xe.TransactionInstruction({keys:u,programId:l,data:Tt.claimPlatformFee})}function Nc(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f){let y=v([w("platformScale"),w("creatorScale"),w("burnScale"),w("feeRate"),Et("name"),Et("web"),Et("img"),w("creatorFeeRate"),w("platformVestingScale")]),b=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1}],g=Buffer.alloc(8*6+Buffer.from(d,"utf-8").length+Buffer.from(p,"utf-8").length+Buffer.from(m,"utf-8").length+4*3);return y.encode({platformScale:s.platformScale,creatorScale:s.creatorScale,burnScale:s.burnScale,feeRate:u,name:d,web:p,img:m,creatorFeeRate:c,platformVestingScale:f},g),new xe.TransactionInstruction({keys:b,programId:l,data:Buffer.from([...Tt.createPlatformConfig,...g])})}function Mc(l,e,t,n){let o=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0}],i;if(n.type==="updateClaimFeeWallet"){let r=v([V("index"),M("value")]);i=Buffer.alloc(r.span),r.encode({index:0,value:n.value},i)}else if(n.type==="updateLockNftWallet"){let r=v([V("index"),M("value")]);i=Buffer.alloc(r.span),r.encode({index:1,value:n.value},i)}else if(n.type==="migrateCpLockNftScale"){let r=v([V("index"),w("platformScale"),w("creatorScale"),w("burnScale")]);i=Buffer.alloc(r.span),r.encode(N({index:2},n.value),i)}else if(n.type==="updateFeeRate"){let r=v([V("index"),w("value")]);i=Buffer.alloc(r.span),r.encode({index:3,value:n.value},i)}else if(n.type==="updateImg"||n.type==="updateName"||n.type==="updateWeb"){let r=v([V("index"),Et("value")]);i=Buffer.alloc(Buffer.from(n.value,"utf-8").length+4+1*1),n.type==="updateName"?r.encode({index:4,value:n.value},i):n.type==="updateWeb"?r.encode({index:5,value:n.value},i):n.type==="updateImg"&&r.encode({index:6,value:n.value},i)}else if(n.type==="updateCpConfigId"){o.push({pubkey:n.value,isSigner:!1,isWritable:!1});let r=v([V("index")]);i=Buffer.alloc(r.span),r.encode({index:7},i)}else if(n.type==="updateAll"){o.push({pubkey:n.value.cpConfigId,isSigner:!1,isWritable:!1});let r=v([V("index"),M("platformClaimFeeWallet"),M("platformLockNftWallet"),w("platformScale"),w("creatorScale"),w("burnScale"),w("feeRate"),Et("name"),Et("web"),Et("img"),M("transferFeeExtensionAuth"),w("creatorFeeRate"),w("platformVestingScale"),M("platformVestingWallet")]);i=Buffer.alloc(1+32+32+32+8*5+4*3+Buffer.from(n.value.name,"utf-8").length+Buffer.from(n.value.web,"utf-8").length+Buffer.from(n.value.img,"utf-8").length+32+8),r.encode({index:8,platformClaimFeeWallet:n.value.platformClaimFeeWallet,platformLockNftWallet:n.value.platformLockNftWallet,platformVestingWallet:n.value.platformVestingWallet,platformScale:n.value.migrateCpLockNftScale.platformScale,creatorScale:n.value.migrateCpLockNftScale.creatorScale,burnScale:n.value.migrateCpLockNftScale.burnScale,feeRate:n.value.feeRate,name:n.value.name,web:n.value.web,img:n.value.img,transferFeeExtensionAuth:n.value.transferFeeExtensionAuth,creatorFeeRate:n.value.creatorFeeRate,platformVestingScale:n.value.platformVestingScale},i)}else if(n.type==="updateVestingWallet"){let r=v([V("index"),M("value")]);i=Buffer.alloc(r.span),r.encode({index:9,value:n.value},i)}else if(n.type==="updatePlatformVestingScale"){let r=v([V("index"),w("value")]);i=Buffer.alloc(r.span),r.encode({index:10,value:n.value},i)}else if(n.type==="updatePlatformCpCreator"){let r=v([V("index"),M("value")]);i=Buffer.alloc(r.span),r.encode({index:11,value:n.value},i)}else if(n.type==="updateRestrictGlobalConfig"){let r=v([V("index"),w("value")]);i=Buffer.alloc(r.span),r.encode({index:12,value:n.value},i)}else throw Error("updateInfo params type error");return new xe.TransactionInstruction({keys:o,programId:l,data:Buffer.from([...Tt.updatePlaformConfig,...i])})}function ys(l,e,t,n,o,i,r,a){let s=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:vn.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}];return new xe.TransactionInstruction({keys:s,programId:l,data:Tt.claimPlatformFeeFromVault})}function bs(l,e,t,n,o,i,r){let a=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:vn.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}];return new xe.TransactionInstruction({keys:a,programId:l,data:Tt.claimCreatorFee})}var wd=255,Kc=new Xn.default("18446744073709551615");function Ef(l,e,t,n,o,i){let r=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1}],a=Buffer.alloc(1*2+8*6+V().span);return V().encode(o,a),as.encode({migrateType:i.migrateType?i.migrateType:wd,migrateCpmmFeeOn:i.migrateCpmmFeeOn?i.migrateCpmmFeeOn:wd,supply:i.supply?i.supply:new Xn.default(0),totalSellA:i.totalSellA?i.totalSellA:new Xn.default(0),totalFundRaisingB:i.totalFundRaisingB?i.totalFundRaisingB:new Xn.default(0),totalLockedAmount:i.totalLockedAmount?i.totalLockedAmount:Kc,cliffPeriod:i.cliffPeriod?i.cliffPeriod:Kc,unlockPeriod:i.unlockPeriod?i.unlockPeriod:Kc},a,1),new xe.TransactionInstruction({keys:r,programId:l,data:Buffer.from([...Tt.updatePlatformCurveParam,...a])})}function Df(l,e,t,n){let o=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!0}],i=Buffer.alloc(V().span);return V().encode(n,i),new xe.TransactionInstruction({keys:o,programId:l,data:Buffer.from([...Tt.removePlatformCurveParam,...i,1,2])})}function Fc(l,e,t,n,o,i){let r=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new xe.TransactionInstruction({keys:r,programId:l,data:Tt.createPlatformVestingAccount})}function vc(l,e,t,n,o){let i=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:xe.SystemProgram.programId,isSigner:!1,isWritable:!1}];return new xe.TransactionInstruction({keys:i,programId:l,data:Tt.createPlatformAllowConfig})}function _c(l,e,t,n,o){let i=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0}];return new xe.TransactionInstruction({keys:i,programId:l,data:Tt.closePlatformAllowConfig})}var Vc=(t=>(t[t.OnlyTokenB=0]="OnlyTokenB",t[t.BothToken=1]="BothToken",t))(Vc||{});var Ci=require("@solana/spl-token"),kd=(t=>(t[t.MintA=0]="MintA",t[t.MintB=1]="MintB",t))(kd||{});function Ec(l,e){return l>>e&1?Ci.TOKEN_2022_PROGRAM_ID:Ci.TOKEN_PROGRAM_ID}function Kr(l){return Ec(l,0)}function Wf(l){return Ec(l,1)}function Dc({mintAProgram:l,mintBProgram:e}){return(l.equals(Ci.TOKEN_2022_PROGRAM_ID)?1<<0:0)|(e.equals(Ci.TOKEN_2022_PROGRAM_ID)?1<<1:0)}var Cr=ie(require("bn.js")),Ri=ie(require("decimal.js"));var io=class{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){throw Error()}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:o}){throw Error()}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){throw Error()}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:o,migrateFee:i,decimalA:r,decimalB:a}){throw Error()}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){throw Error()}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:o,migrateFee:i}){throw Error()}static buyExactIn({poolInfo:e,amount:t}){throw Error()}static buyExactOut({poolInfo:e,amount:t}){throw Error()}static sellExactIn({poolInfo:e,amount:t}){throw Error()}static sellExactOut({poolInfo:e,amount:t}){throw Error()}};var Rr=class extends io{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new Ri.default(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:o}){return new Ri.default(t.toString()).div(e.toString()).mul(10**(n-o))}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new Ri.default(e.virtualB.add(e.realB).toString()).div(e.virtualA.sub(e.realA).toString()).mul(10**(t-n))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:o,migrateFee:i,decimalA:r,decimalB:a}){return new Ri.default(o.sub(i).toString()).div(e.sub(t).sub(n).toString()).mul(10**(r-a))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){let o=e.totalSellA.sub(e.realA),i=e.totalFundRaisingB.sub(e.realB);return new Ri.default(e.virtualB.add(e.realB.add(i)).toString()).div(e.virtualA.sub(e.realA.add(o)).toString()).mul(10**(t-n))}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:o,migrateFee:i}){if(e.lte(n))throw Error("supply need gt total sell");let r=e.sub(n).sub(o);if(r.lte(new Cr.default(0)))throw Error("supplyMinusSellLocked <= 0");let a=t.sub(i);if(a.lte(new Cr.default(0)))throw Error("tfMinusMf <= 0");let s=a.mul(n).mul(n).div(r),u=a.mul(n).div(r).sub(t),c=s.div(u),d=t.mul(t).div(u);if(c.lt(new Cr.default(0))||d.lt(new Cr.default(0)))throw Error("invalid input 0");return{a:c,b:d,c:n}}static buyExactIn({poolInfo:e,amount:t}){return this.getAmountOut({amountIn:t,inputReserve:e.virtualB.add(e.realB),outputReserve:e.virtualA.sub(e.realA)})}static buyExactOut({poolInfo:e,amount:t}){return this.getAmountIn({amountOut:t,inputReserve:e.virtualB.add(e.realB),outputReserve:e.virtualA.sub(e.realA)})}static sellExactIn({poolInfo:e,amount:t}){return this.getAmountOut({amountIn:t,inputReserve:e.virtualA.sub(e.realA),outputReserve:e.virtualB.add(e.realB)})}static sellExactOut({poolInfo:e,amount:t}){return this.getAmountIn({amountOut:t,inputReserve:e.virtualA.sub(e.realA),outputReserve:e.virtualB.add(e.realB)})}static getAmountOut({amountIn:e,inputReserve:t,outputReserve:n}){let o=e.mul(n),i=t.add(e);return o.div(i)}static getAmountIn({amountOut:e,inputReserve:t,outputReserve:n}){let o=t.mul(e),i=n.sub(e);return Bo(o,i)}};var rn=ie(require("bn.js")),Wc=ie(require("decimal.js"));var Lr=ie(require("bn.js")),Li=ie(require("decimal.js"));var Or=class extends io{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new Li.default(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:o}){return new Li.default(t.toString()).div(e.toString()).mul(10**(n-o))}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new Li.default(e.virtualB.toString()).div(e.virtualA.toString()).mul(10**(t-n))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:o,migrateFee:i,decimalA:r,decimalB:a}){return new Li.default(o.sub(i).toString()).div(e.sub(t).sub(n).toString()).mul(10**(r-a))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){let o=e.totalSellA.sub(e.realA),i=e.totalFundRaisingB.sub(e.realB);return new Li.default(e.virtualB.add(e.realB).add(i).toString()).div(e.virtualA.sub(e.realA).add(o).toString()).mul(10**(t-n))}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:o,migrateFee:i}){let r=e.sub(o);if(r.lte(new Lr.default(0)))throw Error("invalid input 1");let a=new Lr.default(2).mul(t).sub(i),u=t.mul(r).div(a);if(u.lt(new Lr.default(0))||t.lt(new Lr.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 o=t.mul(e);return Bo(o,n)}};var on=ie(require("bn.js")),Ao=ie(require("decimal.js"));var zo=ie(require("bn.js")),Nr=ie(require("decimal.js")),Oi=class{static _multipler(e){return new Nr.default(10).pow(e)}static getPrice({priceX64:e,decimalA:t,decimalB:n}){return new Nr.default(e.toString()).div(this._Q64).mul(this._multipler(t)).div(this._multipler(n))}static getPriceX64({price:e,decimalA:t,decimalB:n}){let o=e.mul(this._multipler(n)).div(this._multipler(t));return new zo.default(o.mul(this._Q64).toFixed(0))}};Oi._Q64=new Nr.default(new zo.default(1).shln(64).toString());function qf({supply:l,totalFundRaisingB:e,totalLockedAmount:t,totalSellA:n,migrateType:o,decimalsA:i}){let r=l.sub(n).sub(t),a=new zo.default(new Nr.default(r.mul(e).toString()).sqrt().toFixed(0));if(o==="amm"){if(a.gt(new zo.default(10).pow(new zo.default(i))))return!0}else if(o==="cpmm"){if(a.gt(new zo.default(100)))return!0}else throw Error("migrate type error");return!1}var Mr=class extends io{static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n}){return new Ao.default(0)}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:o}){return new Ao.default(0)}static getPoolPrice({poolInfo:e,decimalA:t,decimalB:n}){return new Ao.default(e.virtualA.mul(e.realA).toString()).div(Oi._Q64).mul(10**(t-n))}static getPoolEndPrice({supply:e,totalSell:t,totalLockedAmount:n,totalFundRaising:o,migrateFee:i,decimalA:r,decimalB:a}){return new Ao.default(o.sub(i).toString()).div(e.sub(t).sub(n).toString()).mul(10**(r-a))}static getPoolEndPriceReal({poolInfo:e,decimalA:t,decimalB:n}){let o=e.totalSellA.sub(e.realA),i=e.totalFundRaisingB.sub(e.realB);return new Ao.default(e.virtualB.add(e.realB).add(i).toString()).div(e.virtualA.sub(e.realA).add(o).toString()).mul(10**(t-n))}static getInitParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:o,migrateFee:i}){let r=e.sub(o);if(r.lte(new on.default(0)))throw Error("supplyMinusLocked need gt 0");let a=t.mul(new on.default(3)).sub(i),u=t.mul(new on.default(2)).mul(r).div(a),c=u.mul(u),d=t.mul(new on.default(2)).mul(Ne).div(c);if(!d.gt(new on.default(0)))throw Error("a need gt 0");if(!Mn.gt(d))throw Error("a need lt u64 max");if(d.lt(new on.default(0))||u.lt(new on.default(0)))throw Error("invalid input 0");return{a:d,b:new on.default(0),c:u}}static buyExactIn({poolInfo:e,amount:t}){let n=e.realB.add(t),o=new on.default(2).mul(n).mul(Ne).div(e.virtualA);return new on.default(new Ao.default(o.toString()).sqrt().toFixed(0)).sub(e.realA)}static buyExactOut({poolInfo:e,amount:t}){let n=e.realA.add(t),o=n.mul(n);return Bo(e.virtualA.mul(o),new on.default(2).mul(Ne)).sub(e.realB)}static sellExactIn({poolInfo:e,amount:t}){let n=e.realA.sub(t),o=n.mul(n),i=Bo(e.virtualA.mul(o),new on.default(2).mul(Ne));return e.realB.sub(i)}static sellExactOut({poolInfo:e,amount:t}){let n=e.realB.sub(t),o=new on.default(2).mul(n).mul(Ne).div(e.virtualA),i=new on.default(new Ao.default(o.toString()).sqrt().toFixed(0));return e.realA.sub(i)}};var vt=class{static getPoolCurvePointByPoolInfo({curveType:e,pointCount:t,poolInfo:n}){return this.getPoolCurvePointByInit({curveType:e,pointCount:t,supply:n.supply,totalFundRaising:n.totalFundRaisingB,totalSell:n.totalSellA,totalLockedAmount:n.vestingSchedule.totalLockedAmount,migrateFee:n.migrateFee,decimalA:n.mintDecimalsA,decimalB:n.mintDecimalsB})}static getPoolCurvePointByInit({curveType:e,pointCount:t,supply:n,totalFundRaising:o,totalSell:i,totalLockedAmount:r,migrateFee:a,decimalA:s,decimalB:u}){if(t<3)throw Error("point count < 3");let c=this.getCurve(e),d=c.getInitParam({supply:n,totalFundRaising:o,totalSell:i,totalLockedAmount:r,migrateFee:a}),p=c.getPoolInitPriceByInit(E(N({},d),{decimalA:s,decimalB:u})),m=o.div(new rn.default(t-1)),f=new rn.default(0),y=[{price:p,totalSellSupply:0}],{a:b,b:g}=d,P=f,k=f;for(let I=1;I<t;I++){let A=I!==t-1?m:o.sub(k),h=this.buyExactIn({poolInfo:{virtualA:b,virtualB:g,realA:P,realB:k,totalFundRaisingB:o,totalSellA:i},amountB:A,protocolFeeRate:f,platformFeeRate:f,curveType:e,shareFeeRate:f,creatorFeeRate:f,transferFeeConfigA:void 0,transferFeeConfigB:void 0,slot:0});P=P.add(h.amountA.amount),k=k.add(h.amountB);let B=this.getPrice({poolInfo:{virtualA:b,virtualB:g,realA:P,realB:k},decimalA:s,decimalB:u,curveType:e});y.push({price:B,totalSellSupply:new Wc.default(P.toString()).div(10**s).toNumber()})}return y}static getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n,curveType:o}){return this.getCurve(o).getPoolInitPriceByPool({poolInfo:e,decimalA:t,decimalB:n})}static getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:o,curveType:i}){return this.getCurve(i).getPoolInitPriceByInit({a:e,b:t,decimalA:n,decimalB:o})}static getPrice({poolInfo:e,curveType:t,decimalA:n,decimalB:o}){return this.getCurve(t).getPoolPrice({poolInfo:e,decimalA:n,decimalB:o})}static getEndPrice({poolInfo:e,curveType:t,decimalA:n,decimalB:o}){return this.getCurve(t).getPoolPrice({poolInfo:e,decimalA:n,decimalB:o})}static getPoolEndPriceReal({poolInfo:e,curveType:t,decimalA:n,decimalB:o}){return this.getCurve(t).getPoolEndPriceReal({poolInfo:e,decimalA:n,decimalB:o})}static checkParam({supply:e,totalFundRaising:t,totalSell:n,totalLockedAmount:o,decimals:i,config:r,migrateType:a}){if(Number(i)!==6)throw Error("decimals = 6");if(e.mul(r.maxLockRate).div(et).lt(o))throw Error("total lock amount gte max lock amount");if(e.lt(r.minSupplyA.mul(new rn.default(10**i))))throw Error("supply lt min supply");let u=e.mul(r.minSellRateA).div(et);if(n.lt(u))throw Error("invalid input");if(t.lt(r.minFundRaisingB))throw Error("total fund raising lt min fund raising");let c=e.sub(n).sub(o),d=e.mul(r.minMigrateRateA).div(et);if(c.lt(d))throw Error("migrate lt min migrate amoount");let p=e.sub(n).sub(o),m=new rn.default(new Wc.default(p.mul(t).toString()).sqrt().toFixed(0));if(a==="amm"){let f=new rn.default(10).pow(new rn.default(i));if(m.lte(f))throw Error("check migrate lp error")}else if(a==="cpmm"){let f=new rn.default(100);if(m.lte(f))throw Error("check migrate lp error")}else throw Error("migrate type error")}static buyExactIn({poolInfo:e,amountB:t,protocolFeeRate:n,platformFeeRate:o,curveType:i,shareFeeRate:r,creatorFeeRate:a,transferFeeConfigA:s,transferFeeConfigB:u,slot:c}){var S;let d=Yi(t,u,c),p=t.sub((S=d.fee)!=null?S:new rn.default(0)),m=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a}),f=this.calculateFee({amount:p,feeRate:m}),y=p.sub(f),b=this.getCurve(i),g=b.buyExactIn({poolInfo:e,amount:y}),P=e.totalSellA.sub(e.realA),k,I,A,h;if(g.gt(P)){k=P;let K=b.buyExactOut({poolInfo:e,amount:k}),x=this.calculatePreFee({postFeeAmount:K,feeRate:m});A=x.sub(K);let C=$o(x,u,c);I=C.amount,h=C.fee}else k=g,I=t,A=f,h=d.fee;let B=this.splitFee({totalFee:A,protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a});return{amountA:Yi(k,s,c),amountB:I,splitFee:B,transferFeeB:h}}static buyExactOut({poolInfo:e,amountA:t,protocolFeeRate:n,platformFeeRate:o,curveType:i,shareFeeRate:r,creatorFeeRate:a,transferFeeConfigA:s,transferFeeConfigB:u,slot:c}){let d=e.totalSellA.sub(e.realA),p=$o(t,s,c),m=p.fee?p.amount.add(p.fee):p.amount;t.gt(d)&&(m=d);let y=this.getCurve(i).buyExactOut({poolInfo:e,amount:m}),b=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a}),g=this.calculatePreFee({postFeeAmount:y,feeRate:b}),P=g.sub(y),k=$o(g,u,c),I=this.splitFee({totalFee:P,protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a});return{amountA:p,amountB:k.amount,splitFee:I,transferFeeB:k.fee}}static sellExactIn({poolInfo:e,amountA:t,protocolFeeRate:n,platformFeeRate:o,curveType:i,shareFeeRate:r,creatorFeeRate:a,transferFeeConfigA:s,transferFeeConfigB:u,slot:c}){var k;let d=this.getCurve(i),p=Yi(t,s,c),m=p.fee?p.amount.sub(p.fee):p.amount,f=d.sellExactIn({poolInfo:e,amount:m}),y=this.calculateFee({amount:f,feeRate:this.totalFeeRate({protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a})}),b=this.splitFee({totalFee:y,protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a}),g=f.sub(y),P=Yi(g,u,c);return{amountA:p,amountB:g.sub((k=P.fee)!=null?k:new rn.default(0)),splitFee:b,transferFeeB:P.fee}}static sellExactOut({poolInfo:e,amountB:t,protocolFeeRate:n,platformFeeRate:o,curveType:i,shareFeeRate:r,creatorFeeRate:a,transferFeeConfigA:s,transferFeeConfigB:u,slot:c}){let d=this.totalFeeRate({protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a}),p=$o(t,u,c),m=p.amount,f=this.calculatePreFee({postFeeAmount:m,feeRate:d});if(e.realB.lt(f))throw Error("Insufficient liquidity");let y=f.sub(m),g=vt.getCurve(i).sellExactOut({poolInfo:e,amount:f});if(g.gt(e.realA))throw Error();let P=this.splitFee({totalFee:y,protocolFeeRate:n,platformFeeRate:o,shareFeeRate:r,creatorFeeRate:a});return{amountA:$o(g,s,c),amountB:t,splitFee:P,transferFeeB:p.fee}}static splitFee({totalFee:e,protocolFeeRate:t,platformFeeRate:n,shareFeeRate:o,creatorFeeRate:i}){let r=this.totalFeeRate({protocolFeeRate:t,platformFeeRate:n,shareFeeRate:o,creatorFeeRate:i}),a=r.isZero()?new rn.default(0):e.mul(n).div(r),s=r.isZero()?new rn.default(0):e.mul(o).div(r),u=r.isZero()?new rn.default(0):e.mul(i).div(r),c=e.sub(a).sub(s).sub(u);return{platformFee:a,shareFee:s,protocolFee:c,creatorFee:u}}static calculateFee({amount:e,feeRate:t}){return Wi(e,t,et)}static calculatePreFee({postFeeAmount:e,feeRate:t}){if(t.isZero())return e;let n=e.mul(et),o=et.sub(t);return n.add(o).sub(new rn.default(1)).div(o)}static totalFeeRate({protocolFeeRate:e,platformFeeRate:t,shareFeeRate:n,creatorFeeRate:o}){if(e.add(t).add(n).add(o).gt(new rn.default(1e6)))throw Error("total fee rate gt 1_000_000");return e.add(t).add(n).add(o)}static getCurve(e){switch(e){case 0:return Rr;case 1:return Or;case 2:return Mr}throw Error("find curve error")}};var oe=require("@solana/spl-token"),me=ie(require("bn.js")),ko=require("@solana/web3.js");var cn=ie(require("decimal.js")),Fr={initPriceX64:new me.default("515752397214619"),supply:new me.default(1e15),totalSellA:new me.default(7931e11),totalFundRaisingB:new me.default(85e9),totalFundRaisingBUSD:new me.default(125e8),totalLockedAmount:new me.default("0"),cliffPeriod:new me.default("0"),unlockPeriod:new me.default("0"),decimals:6,virtualA:new me.default("1073471847374405"),virtualB:new me.default("30050573465"),realA:new me.default(0),realB:new me.default(0),protocolFee:new me.default(0),platformId:new ko.PublicKey("4Bu96XjU84XjPDSpveTVf6LYGCkfW5FK7SNkREWcEfV4"),vestingSchedule:{totalLockedAmount:new me.default(0),cliffPeriod:new me.default(0),unlockPeriod:new me.default(0),startTime:new me.default(0),totalAllocatedShare:new me.default(0)}},wo=new me.default(1e4),Uf=new Set(["USDCoctVLVnvTXBEuP9s8hntucdJokbo17RwHuNXemT","USD1ttGY1N17NEEHLmELoaybftRBUSErhqYiQzvEmuB"]),vr=class extends at{constructor(e){super(e)}async getMintBTokenInfo({mintB:e,mintBProgram:t,transferFeeConfigB:n,skipCheckMintB:o}){if(e.equals(oe.NATIVE_MINT))return{mintBProgram:oe.TOKEN_PROGRAM_ID,transferFeeConfigB:void 0};if(n)return{mintBProgram:t!=null?t:oe.TOKEN_2022_PROGRAM_ID,transferFeeConfigB:n};if(o||(t==null?void 0:t.equals(oe.TOKEN_PROGRAM_ID)))return{mintBProgram:t!=null?t:oe.TOKEN_PROGRAM_ID,transferFeeConfigB:void 0};let i=await this.scope.connection.getAccountInfo(e);return!i||!i.owner.equals(oe.TOKEN_2022_PROGRAM_ID)?{mintBProgram:t!=null?t:oe.TOKEN_PROGRAM_ID,transferFeeConfigB:void 0}:{mintBProgram:i.owner,transferFeeConfigB:(0,oe.getTransferFeeConfig)((0,oe.unpackMint)(e,i,i.owner))||void 0}}async createLaunchpad(F){var W=F,{programId:e=ct,authProgramId:t,platformId:n=Fr.platformId,mintA:o,decimals:i=6,mintBDecimals:r=9,name:a,symbol:s,uri:u,migrateType:c,configId:d,configInfo:p,txVersion:m,computeBudgetConfig:f,txTipConfig:y,feePayer:b,buyAmount:g,minMintAAmount:P,slippage:k,associatedOnly:I=!0,checkCreateATAOwner:A=!1,extraSigners:h,token2022:B,transferFeeExtensionParams:S,creatorFeeOn:K=0,platformAllowConfig:x,mintBProgram:C,transferFeeConfigB:L,skipCheckMintB:O}=W,R=$e(W,["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 Zc,jc,$c,Jc,el,tl,nl,ol,il,rl,al;let D=this.createTxBuilder(b);t=t!=null?t:Yt(e).publicKey,B=!!S,B&&(c="cpmm");let X=p;if(!X&&d){let Yn=await this.scope.connection.getAccountInfo(d);Yn&&(X=no.decode(Yn.data))}X||this.logAndCreateError("config not found");let Z=X.mintB,H=X.curveType,{mintBProgram:ne,transferFeeConfigB:se}=await this.getMintBTokenInfo({mintB:Z,mintBProgram:C,transferFeeConfigB:L,skipCheckMintB:O}),{publicKey:J}=Uo(e,o,Z),{publicKey:ge}=us(e,J,o),{publicKey:ue}=us(e,J,Z),{publicKey:he}=qn(o);this.logDebug(`create token: ${o.toBase58()}, mintB: ${Z.toBase58()}, decimals A:${i}/B:${r}, config:${d.toBase58()}`),s.length>10&&this.logAndCreateError("Symbol length should shorter than 11"),u||this.logAndCreateError("uri should not empty");let Me=(await this.scope.api.fetchLaunchConfigs()).find(Yn=>Yn.key.pubKey===d.toBase58()),ke=(Zc=R==null?void 0:R.supply)!=null?Zc:new me.default(Me.defaultParams.supplyInit),ce=(jc=R==null?void 0:R.totalSellA)!=null?jc:new me.default(Me.defaultParams.totalSellA),Le=($c=R==null?void 0:R.totalFundRaisingB)!=null?$c:new me.default(Me.defaultParams.totalFundRaisingB),Ut=(Jc=R==null?void 0:R.totalLockedAmount)!=null?Jc:new me.default(0),ot=await this.scope.connection.getAccountInfo(n);ot||this.logAndCreateError("platform id not found:",n.toString());let _n=kn.decode(ot.data),Xo=_n.platformVestingScale,Ni=_n.feeRate,Mi=vt.getCurve(X.curveType).getInitParam({supply:ke,totalFundRaising:Le,totalSell:ce,totalLockedAmount:Ut,migrateFee:X.migrateFee}),Qt;try{Qt=await this.scope.token.getTokenInfo(Z)}catch{this.logDebug("can not get mintB info from getTokenInfo")}let xn={epoch:new me.default(896),bump:254,status:0,mintDecimalsA:i,mintDecimalsB:(el=Qt==null?void 0:Qt.decimals)!=null?el:r,supply:ke,totalSellA:ce,mintA:new ko.PublicKey(o),mintB:Z,virtualA:Mi.a,virtualB:Mi.b,realA:Fr.realA,realB:Fr.realB,migrateFee:X.migrateFee,migrateType:c==="amm"?0:1,protocolFee:Fr.protocolFee,platformFee:Ni,platformId:n,configId:d,vaultA:ge,vaultB:ue,creator:this.scope.ownerPubKey,totalFundRaisingB:Le,vestingSchedule:{totalLockedAmount:Ut,cliffPeriod:new me.default(0),unlockPeriod:new me.default(0),startTime:new me.default(0),totalAllocatedShare:new me.default(0)},mintProgramFlag:Dc({mintAProgram:B?oe.TOKEN_2022_PROGRAM_ID:oe.TOKEN_PROGRAM_ID,mintBProgram:ne}),cpmmCreatorFeeOn:K,platformVestingShare:Xo!=null?Xo:new me.default(0)},Bd=vt.getCurve(X.curveType),{c:xd}=Bd.getInitParam({supply:xn.supply,totalFundRaising:xn.totalFundRaisingB,totalLockedAmount:Ut,totalSell:X.curveType===0?xn.totalSellA:new me.default(0),migrateFee:X.migrateFee});try{vt.checkParam({supply:xn.supply,totalFundRaising:xn.totalFundRaisingB,totalSell:xd,totalLockedAmount:Ut,decimals:xn.mintDecimalsA,config:X,migrateType:c}),this.logDebug("check init params success")}catch(Yn){this.logAndCreateError(`check create mint params failed, ${Yn.message}`)}D.addInstruction({instructions:[B?Rc(e,b!=null?b:this.scope.ownerPubKey,this.scope.ownerPubKey,d,n,t,J,o,Z,ge,ue,ne,i,a,s,u||"https://",{type:H===0?"ConstantCurve":H===1?"FixedCurve":H===2?"LinearCurve":"ConstantCurve",totalSellA:ce,migrateType:c,supply:ke,totalFundRaisingB:Le},Ut,(tl=R==null?void 0:R.cliffPeriod)!=null?tl:new me.default(0),(nl=R==null?void 0:R.unlockPeriod)!=null?nl:new me.default(0),K,S,x?Si(e,n,d).publicKey:void 0):Cc(e,b!=null?b:this.scope.ownerPubKey,this.scope.ownerPubKey,d,n,t,J,o,Z,ge,ue,he,ne,i,a,s,u||"https://",{type:H===0?"ConstantCurve":H===1?"FixedCurve":H===2?"LinearCurve":"ConstantCurve",totalSellA:ce,migrateType:c,supply:ke,totalFundRaisingB:Le},Ut,(ol=R==null?void 0:R.cliffPeriod)!=null?ol:new me.default(0),(il=R==null?void 0:R.unlockPeriod)!=null?il:new me.default(0),K,x?Si(e,n,d).publicKey:void 0)]});let ks=B?await this.scope.connection.getEpochInfo():void 0,Wr=S?{epoch:BigInt((ks==null?void 0:ks.epoch)||0),maximumFee:BigInt((rl=S==null?void 0:S.maxinumFee.toString())!=null?rl:0),transferFeeBasisPoints:(al=S==null?void 0:S.transferFeeBasePoints)!=null?al:0}:void 0,Ts={amountA:{amount:new me.default(0),fee:void 0,expirationTime:void 0},amountB:new me.default(0),splitFee:{platformFee:new me.default(0),shareFee:new me.default(0),protocolFee:new me.default(0),creatorFee:new me.default(0)},transferFeeB:void 0},hs;if(h!=null&&h.length&&D.addInstruction({signers:h}),!R.createOnly){let{builder:Yn,extInfo:Sd}=await this.buyToken({programId:e,authProgramId:t,mintAProgram:B?oe.TOKEN_2022_PROGRAM_ID:void 0,mintA:o,mintB:Z,mintBProgram:ne,transferFeeConfigB:se,skipCheckMintB:!0,poolInfo:xn,buyAmount:g,minMintAAmount:P,shareFeeRate:R.shareFeeRate,shareFeeReceiver:R.shareFeeReceiver,configInfo:X,platformFeeRate:Ni,slippage:k,associatedOnly:I,checkCreateATAOwner:A,skipCheckMintA:!Wr,transferFeeConfigA:Wr?{transferFeeConfigAuthority:t,withdrawWithheldAuthority:t,withheldAmount:BigInt(0),olderTransferFee:Wr,newerTransferFee:Wr}:void 0,fromCreate:!0});D.addInstruction(N({},Yn.AllTxData)),Ts=N({},Sd),hs=(this.scope.cluster==="devnet"||m===1)&&R.shareFeeReceiver?[Yn.allInstructions[0]]:void 0}return D.addTipInstruction(y),m===0?D.sizeCheckBuildV0({computeBudgetConfig:f,swapInfo:Ts,splitIns:hs,address:E(N({},xn),{poolId:J})}):D.sizeCheckBuild({computeBudgetConfig:f,swapInfo:Ts,splitIns:hs,address:E(N({},xn),{poolId:J})})}async buyToken({programId:e=ct,authProgramId:t,mintA:n,mintAProgram:o=oe.TOKEN_PROGRAM_ID,mintB:i=oe.NATIVE_MINT,poolInfo:r,configInfo:a,platformFeeRate:s,txVersion:u,computeBudgetConfig:c,txTipConfig:d,feePayer:p,buyAmount:m,minMintAAmount:f,slippage:y,shareFeeRate:b=new me.default(0),shareFeeReceiver:g,associatedOnly:P=!0,checkCreateATAOwner:k=!1,fromCreate:I=!1,transferFeeConfigA:A,skipCheckMintA:h=!1,mintBProgram:B,transferFeeConfigB:S,skipCheckMintB:K=!1}){var ce,Le,Ut;m.lte(new me.default(0))&&this.logAndCreateError("buy amount should gt 0:",m.toString());let x=this.createTxBuilder(p),{publicKey:C}=Uo(e,n,i);t=t!=null?t:Yt(e).publicKey;let L=A;if(!h)if(L)o=oe.TOKEN_2022_PROGRAM_ID;else{let ot=await this.scope.connection.getAccountInfo(n);if(ot&&ot.owner.equals(oe.TOKEN_2022_PROGRAM_ID)){o=ot.owner;let _n=(0,oe.unpackMint)(n,ot,o);L=(0,oe.getTransferFeeConfig)(_n)||void 0}}let{mintBProgram:O,transferFeeConfigB:R}=await this.getMintBTokenInfo({mintB:i,mintBProgram:B,transferFeeConfigB:S,skipCheckMintB:K}),F=this.scope.account.getAssociatedTokenAccount(n,o),W=i.equals(oe.NATIVE_MINT),D=I&&W,X=D?this.scope.account.getAssociatedTokenAccount(i,O):null,Z=W;if(x.addInstruction({instructions:[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,F,this.scope.ownerPubKey,n,o),...D?[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,X,this.scope.ownerPubKey,i,O),ko.SystemProgram.transfer({fromPubkey:this.scope.ownerPubKey,toPubkey:X,lamports:BigInt(m.toString())}),(0,oe.createSyncNativeInstruction)(X)]:[]]}),!D){let{account:ot,instructionParams:_n}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:O,mint:i,owner:this.scope.ownerPubKey,createInfo:Z?{payer:this.scope.ownerPubKey,amount:m}:void 0,skipCloseAccount:!Z,notUseTokenAccount:Z,associatedOnly:Z?!1:P,checkCreateATAOwner:k});ot&&(X=ot),x.addInstruction(_n||{})}X||this.logAndCreateError(`cannot found mintB(${i.toBase58()}) buy token accounts`,"tokenAccounts",this.scope.account.tokenAccounts);let H=r;if(!H){let ot=await this.scope.connection.getAccountInfo(C,{commitment:"processed"});ot||this.logAndCreateError("cannot found pool:",C.toBase58()),H=wn.decode(ot.data)}let ne=a,se=await qe(this.scope.connection,[ne?void 0:H.configId,H.platformId].filter(Boolean).map(ot=>({pubkey:ot})));if(!ne){let ot=se.find(_n=>_n.pubkey.equals(H.configId));(!ot||!ot.accountInfo)&&this.logAndCreateError("config not found: ",H.configId.toBase58()),ne=no.decode(ot.accountInfo.data)}let J=se.find(ot=>ot.pubkey.equals(H.platformId));(!J||!J.accountInfo)&&this.logAndCreateError("platform info not found: ",H.configId.toBase58());let ge=kn.decode(J.accountInfo.data);s=s||ge.feeRate;let ue=vt.buyExactIn({poolInfo:H,amountB:m,protocolFeeRate:ne.tradeFeeRate,platformFeeRate:s,curveType:ne.curveType,shareFeeRate:b,creatorFeeRate:ge.creatorFeeRate,transferFeeConfigA:L,transferFeeConfigB:R,slot:await this.scope.connection.getSlot()}),he=new cn.default(ue.amountA.amount.toString()).sub((Le=(ce=ue.amountA.fee)==null?void 0:ce.toString())!=null?Le:0),_e=y?new cn.default(wo.sub(y).toNumber()/wo.toNumber()).clampedTo(0,1):new cn.default(1),Me=f!=null?f:y?new me.default(he.mul(_e).toFixed(0)):ue.amountA.amount.sub((Ut=ue.amountA.fee)!=null?Ut:new me.default(0));ue.amountB.lt(m)&&console.log(`maximum ${n.toBase58()} amount can buy is ${ue.amountA.toString()}, input ${i.toBase58()} amount: ${ue.amountB.toString()}`);let ke=g?te(g,i,O).publicKey:void 0;return ke&&x.addInstruction({instructions:[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,ke,g,i,O)]}),x.addInstruction({instructions:[Ki(e,this.scope.ownerPubKey,t,H.configId,H.platformId,C,F,X,H.vaultA,H.vaultB,n,i,o,O,Tn(e,H.platformId,i).publicKey,hn(e,H.creator,i).publicKey,ue.amountB.lt(m)?ue.amountB:m,Me,b,ke)]}),x.addCustomComputeBudget(c),x.addTipInstruction(d),x.versionBuild({txVersion:u,extInfo:E(N({},ue),{decimalOutAmount:he,minDecimalOutAmount:new cn.default(Me.toString())})})}async buyTokenExactOut({programId:e=ct,authProgramId:t,mintA:n,mintAProgram:o=oe.TOKEN_PROGRAM_ID,mintB:i=oe.NATIVE_MINT,poolInfo:r,configInfo:a,transferFeeConfigA:s,platformFeeRate:u,txVersion:c,computeBudgetConfig:d,txTipConfig:p,feePayer:m,maxBuyAmount:f,outAmount:y,slippage:b,shareFeeRate:g=new me.default(0),shareFeeReceiver:P,associatedOnly:k=!0,checkCreateATAOwner:I=!1,skipCheckMintA:A=!1,mintBProgram:h,transferFeeConfigB:B,skipCheckMintB:S=!1}){y.lte(new me.default(0))&&this.logAndCreateError("out amount should gt 0:",y.toString());let K=this.createTxBuilder(m),{publicKey:x}=Uo(e,n,i);t=t!=null?t:Yt(e).publicKey;let C=r;if(!C){let ke=await this.scope.connection.getAccountInfo(x,{commitment:"processed"});ke||this.logAndCreateError("cannot found pool:",x.toBase58()),C=wn.decode(ke.data)}let L=a,O=await qe(this.scope.connection,[L?void 0:C.configId,C.platformId].filter(Boolean).map(ke=>({pubkey:ke})));if(!L){let ke=O.find(ce=>ce.pubkey.equals(C.configId));(!ke||!ke.accountInfo)&&this.logAndCreateError("config not found: ",C.configId.toBase58()),L=no.decode(ke.accountInfo.data)}let R=O.find(ke=>ke.pubkey.equals(C.platformId));(!R||!R.accountInfo)&&this.logAndCreateError("platform info not found: ",C.configId.toBase58());let F=kn.decode(R.accountInfo.data);u=u||F.feeRate;let W=s;if(!A)if(W)o=oe.TOKEN_2022_PROGRAM_ID;else{let ke=await this.scope.connection.getAccountInfo(n);if(ke&&ke.owner.equals(oe.TOKEN_2022_PROGRAM_ID)){o=ke.owner;let ce=(0,oe.unpackMint)(n,ke,o);W=(0,oe.getTransferFeeConfig)(ce)||void 0}}let{mintBProgram:D,transferFeeConfigB:X}=await this.getMintBTokenInfo({mintB:i,mintBProgram:h,transferFeeConfigB:B,skipCheckMintB:S}),Z=vt.buyExactOut({poolInfo:C,amountA:y,protocolFeeRate:L.tradeFeeRate,platformFeeRate:u,curveType:L.curveType,shareFeeRate:g,creatorFeeRate:F.creatorFeeRate,transferFeeConfigA:W,transferFeeConfigB:X,slot:await this.scope.connection.getSlot()}),H=new cn.default(Z.amountB.toString()),ne=b?new cn.default(wo.add(b).toNumber()/wo.toNumber()).clampedTo(0,Number.MIN_SAFE_INTEGER):new cn.default(1),se=(f!=null?f:b)?new me.default(H.mul(ne).toFixed(0)):Z.amountB,J=this.scope.account.getAssociatedTokenAccount(n,o),ge=null,ue=i.equals(oe.NATIVE_MINT);K.addInstruction({instructions:[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,J,this.scope.ownerPubKey,n,o)]});let{account:he,instructionParams:_e}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:D,mint:i,owner:this.scope.ownerPubKey,createInfo:ue?{payer:this.scope.ownerPubKey,amount:Z.amountB}:void 0,skipCloseAccount:!ue,notUseTokenAccount:ue,associatedOnly:ue?!1:k,checkCreateATAOwner:I});he&&(ge=he),K.addInstruction(_e||{}),ge===void 0&&this.logAndCreateError(`cannot found mintB(${i.toBase58()}) token accounts`,"tokenAccounts",this.scope.account.tokenAccounts);let Me=P?te(P,i,D).publicKey:void 0;return Me&&K.addInstruction({instructions:[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Me,P,i,D)]}),K.addInstruction({instructions:[Lc(e,this.scope.ownerPubKey,t,C.configId,C.platformId,x,J,ge,C.vaultA,C.vaultB,n,i,o,D,Tn(e,C.platformId,i).publicKey,hn(e,C.creator,i).publicKey,y,se,g,Me)]}),K.addCustomComputeBudget(d),K.addTipInstruction(p),K.versionBuild({txVersion:c,extInfo:{maxSpentAmount:se,outAmount:y}})}async sellToken({programId:e=ct,authProgramId:t,mintAProgram:n=oe.TOKEN_PROGRAM_ID,mintA:o,mintB:i=oe.NATIVE_MINT,poolInfo:r,configInfo:a,platformFeeRate:s,txVersion:u,computeBudgetConfig:c,txTipConfig:d,feePayer:p,sellAmount:m,minAmountB:f,slippage:y,shareFeeRate:b=new me.default(0),shareFeeReceiver:g,associatedOnly:P=!0,checkCreateATAOwner:k=!1,skipCheckMintA:I=!1,mintBProgram:A,transferFeeConfigB:h,skipCheckMintB:B=!1}){t=t!=null?t:Yt(e).publicKey;let S=this.createTxBuilder(p);m.lte(new me.default(0))&&this.logAndCreateError("sell amount should be gt 0");let{publicKey:K}=Uo(e,o,i),x;if(!I){let ce=await this.scope.connection.getAccountInfo(o);if(ce&&ce.owner.equals(oe.TOKEN_2022_PROGRAM_ID)){n=ce.owner;let Le=(0,oe.unpackMint)(o,ce,n);x=(0,oe.getTransferFeeConfig)(Le)||void 0}}let{mintBProgram:C,transferFeeConfigB:L}=await this.getMintBTokenInfo({mintB:i,mintBProgram:A,transferFeeConfigB:h,skipCheckMintB:B}),O=null,R=null,F=i.equals(oe.NATIVE_MINT),{account:W,instructionParams:D}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n,mint:o,owner:this.scope.ownerPubKey,createInfo:void 0,skipCloseAccount:!0,notUseTokenAccount:!1,associatedOnly:P,checkCreateATAOwner:k});W&&(O=W),S.addInstruction(D||{}),O===void 0&&this.logAndCreateError("cannot found mintA token accounts","tokenAccounts",this.scope.account.tokenAccounts);let{account:X,instructionParams:Z}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:C,mint:i,owner:this.scope.ownerPubKey,createInfo:F?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!F,notUseTokenAccount:F,associatedOnly:F?!1:P,checkCreateATAOwner:k});X&&(R=X),S.addInstruction(Z||{}),R===void 0&&this.logAndCreateError("cannot found mintB token accounts","tokenAccounts",this.scope.account.tokenAccounts);let H=r;if(!H){let ce=await this.scope.connection.getAccountInfo(K,{commitment:"processed"});ce||this.logAndCreateError("cannot found pool",K.toBase58()),H=wn.decode(ce.data)}let ne=a,se=await qe(this.scope.connection,[ne?void 0:H.configId,H.platformId].filter(Boolean).map(ce=>({pubkey:ce})));if(!ne){let ce=se.find(Le=>Le.pubkey.equals(H.configId));(!ce||!ce.accountInfo)&&this.logAndCreateError("config not found: ",H.configId.toBase58()),ne=no.decode(ce.accountInfo.data)}let J=se.find(ce=>ce.pubkey.equals(H.platformId));(!J||!J.accountInfo)&&this.logAndCreateError("platform info not found: ",H.configId.toBase58());let ge=kn.decode(J.accountInfo.data);s=s||ge.feeRate;let ue=vt.sellExactIn({poolInfo:H,amountA:m,protocolFeeRate:ne.tradeFeeRate,platformFeeRate:s,curveType:ne.curveType,shareFeeRate:b,creatorFeeRate:ge.creatorFeeRate,transferFeeConfigA:x,transferFeeConfigB:L,slot:await this.scope.connection.getSlot()}),he=new cn.default(ue.amountB.toString()),_e=y?new cn.default(wo.sub(y).toNumber()/wo.toNumber()).clampedTo(0,1):new cn.default(1),Me=f!=null?f:y?new me.default(he.mul(_e).toFixed(0)):ue.amountB;Me.lte(new me.default(0))&&this.logAndCreateError(`out ${i.toBase58()} amount should be gt 0`);let ke=g?te(g,i,C).publicKey:void 0;return ke&&S.addInstruction({instructions:[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,ke,g,i,C)]}),S.addInstruction({instructions:[Sr(e,this.scope.ownerPubKey,t,H.configId,H.platformId,K,O,R,H.vaultA,H.vaultB,o,i,n,C,Tn(e,H.platformId,i).publicKey,hn(e,H.creator,i).publicKey,ue.amountA.amount.lt(m)?ue.amountA.amount:m,Me,b,ke)]}),S.addCustomComputeBudget(c),S.addTipInstruction(d),S.versionBuild({txVersion:u,extInfo:{outAmount:Me}})}async sellTokenExactOut({programId:e=ct,authProgramId:t,mintAProgram:n=oe.TOKEN_PROGRAM_ID,mintA:o,mintB:i=oe.NATIVE_MINT,poolInfo:r,configInfo:a,platformFeeRate:s,txVersion:u,computeBudgetConfig:c,txTipConfig:d,feePayer:p,inAmount:m,maxSellAmount:f,slippage:y,shareFeeRate:b=new me.default(0),shareFeeReceiver:g,associatedOnly:P=!0,checkCreateATAOwner:k=!1,skipCheckMintA:I=!1,mintBProgram:A,transferFeeConfigB:h,skipCheckMintB:B=!1}){t=t!=null?t:Yt(e).publicKey;let S=this.createTxBuilder(p);f!=null&&f.lte(new me.default(0))&&this.logAndCreateError("max sell amount should be gt 0");let{publicKey:K}=Uo(e,o,i),x;if(!I){let ce=await this.scope.connection.getAccountInfo(o);if(ce&&ce.owner.equals(oe.TOKEN_2022_PROGRAM_ID)){n=ce.owner;let Le=(0,oe.unpackMint)(o,ce,n);x=(0,oe.getTransferFeeConfig)(Le)||void 0}}let{mintBProgram:C,transferFeeConfigB:L}=await this.getMintBTokenInfo({mintB:i,mintBProgram:A,transferFeeConfigB:h,skipCheckMintB:B}),O=null,R=null,F=i.equals(oe.NATIVE_MINT),{account:W,instructionParams:D}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:n,mint:o,owner:this.scope.ownerPubKey,createInfo:void 0,skipCloseAccount:!0,notUseTokenAccount:!1,associatedOnly:P,checkCreateATAOwner:k});W&&(O=W),S.addInstruction(D||{}),O===void 0&&this.logAndCreateError("cannot found mintA token accounts","tokenAccounts",this.scope.account.tokenAccounts);let{account:X,instructionParams:Z}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:C,mint:i,owner:this.scope.ownerPubKey,createInfo:F?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!F,notUseTokenAccount:F,associatedOnly:F?!1:P,checkCreateATAOwner:k});X&&(R=X),S.addInstruction(Z||{}),R===void 0&&this.logAndCreateError("cannot found mintB token accounts","tokenAccounts",this.scope.account.tokenAccounts);let H=r;if(!H){let ce=await this.scope.connection.getAccountInfo(K,{commitment:"processed"});ce||this.logAndCreateError("cannot found pool",K.toBase58()),H=wn.decode(ce.data)}let ne=a,se=await qe(this.scope.connection,[ne?void 0:H.configId,H.platformId].filter(Boolean).map(ce=>({pubkey:ce})));if(!ne){let ce=se.find(Le=>Le.pubkey.equals(H.configId));(!ce||!ce.accountInfo)&&this.logAndCreateError("config not found: ",H.configId.toBase58()),ne=no.decode(ce.accountInfo.data)}let J=se.find(ce=>ce.pubkey.equals(H.platformId));(!J||!J.accountInfo)&&this.logAndCreateError("platform info not found: ",H.configId.toBase58());let ge=kn.decode(J.accountInfo.data);s=s||ge.feeRate;let ue=vt.sellExactOut({poolInfo:H,amountB:m,protocolFeeRate:ne.tradeFeeRate,platformFeeRate:s,curveType:ne.curveType,shareFeeRate:b,creatorFeeRate:ge.creatorFeeRate,transferFeeConfigA:x,transferFeeConfigB:L,slot:await this.scope.connection.getSlot()}),he=new cn.default(ue.amountA.amount.toString()),_e=y?new cn.default(wo.add(y).toNumber()/wo.toNumber()).clampedTo(0,Number.MAX_SAFE_INTEGER):new cn.default(1),Me=(f!=null?f:y)?new me.default(he.mul(_e).toFixed(0)):ue.amountA.amount,ke=g?te(g,i,C).publicKey:void 0;return ke&&S.addInstruction({instructions:[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,ke,g,i,C)]}),S.addInstruction({instructions:[Oc(e,this.scope.ownerPubKey,t,H.configId,H.platformId,K,O,R,H.vaultA,H.vaultB,o,i,n,C,Tn(e,H.platformId,i).publicKey,hn(e,H.creator,i).publicKey,m,Me,b,ke)]}),S.addCustomComputeBudget(c),S.addTipInstruction(d),S.versionBuild({txVersion:u,extInfo:{maxSellAmount:Me}})}async createPlatformConfig({programId:e=ct,platformAdmin:t,platformClaimFeeWallet:n,platformLockNftWallet:o,platformVestingWallet:i,cpConfigId:r,migrateCpLockNftScale:a,transferFeeExtensionAuth:s,creatorFeeRate:u,feeRate:c,name:d,web:p,img:m,platformVestingScale:f=new me.default(0),txVersion:y,computeBudgetConfig:b,txTipConfig:g,feePayer:P}){let k=this.createTxBuilder(P),{publicKey:I}=cs(e,t);return k.addInstruction({instructions:[Nc(e,t,n,o,i,I,r,s,a,c,u,d,p,m,f)]}),k.addCustomComputeBudget(b),k.addTipInstruction(g),k.versionBuild({txVersion:y,extInfo:{platformId:I}})}async updatePlatformConfig({programId:e=ct,platformAdmin:t,platformId:n,updateInfo:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:s}){let u=this.createTxBuilder(s),c=n!=null?n:cs(e,t).publicKey;return u.addInstruction({instructions:[Mc(e,t,c,o)]}),u.addCustomComputeBudget(r),u.addTipInstruction(a),u.versionBuild({txVersion:i})}async createPlatformVestingAccount({programId:e=ct,platformVestingWallet:t,beneficiary:n,platformId:o,poolId:i,vestingRecord:r,txVersion:a,computeBudgetConfig:s,txTipConfig:u,feePayer:c}){let d=this.createTxBuilder(c),p=r!=null?r:Go(e,i,n).publicKey;return d.addInstruction({instructions:[Fc(e,t,n,o,i,p)]}),d.addCustomComputeBudget(s),d.addTipInstruction(u),d.versionBuild({txVersion:a})}async claimPlatformFee({programId:e=ct,authProgramId:t,platformId:n,poolId:o,platformClaimFeeWallet:i,mintB:r,vaultB:a,mintBProgram:s,txVersion:u,computeBudgetConfig:c,txTipConfig:d,feePayer:p}){var P;let m=this.createTxBuilder(p);t=t!=null?t:Yt(e).publicKey;let f=r,y=a;if(!f){let k=await this.scope.connection.getAccountInfo(o,{commitment:"processed"});k||this.logAndCreateError("cannot found pool:",o.toBase58());let I=wn.decode(k.data),A=await this.scope.connection.getAccountInfo(I.configId,{commitment:"processed"});A||this.logAndCreateError("cannot found config:",I.configId.toBase58()),f=no.decode(A.data).mintB,y=y!=null?y:I.vaultB}(!f||!y)&&this.logAndCreateError("cannot found mint info, mintB: ",f.toBase58(),", vaultB: ",(P=y==null?void 0:y.toBase58())!=null?P:"");let{mintBProgram:b}=await this.getMintBTokenInfo({mintB:f,mintBProgram:s}),g=te(this.scope.ownerPubKey,f,b).publicKey;return m.addInstruction({instructions:[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,g,this.scope.ownerPubKey,f,b)]}),m.addInstruction({instructions:[fs(e,i,t,o,n,y,g,f,b)]}),m.addCustomComputeBudget(c),m.addTipInstruction(d),m.versionBuild({txVersion:u})}async claimAllPlatformFee({programId:e=ct,authProgramId:t,platformId:n,platformClaimFeeWallet:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:s}){let u=this.createTxBuilder(s);t=t!=null?t:Yt(e).publicKey;let d=(await this.scope.connection.getProgramAccounts(e,{filters:[{dataSize:wn.span},{memcmp:{offset:wn.offsetOf("platformId"),bytes:n.toString()}}]})).map(f=>({poolId:f.pubkey,pool:wn.decode(f.account.data)})).filter(({pool:f})=>f.platformFee.gt(new me.default(0))),p={},m=[...new Set(d.map(({pool:f})=>f.mintB.toBase58()))];return m.length&&(await qe(this.scope.connection,m.map(y=>({pubkey:new ko.PublicKey(y)})))).forEach(y=>{var b,g;p[y.pubkey.toBase58()]=(g=(b=y.accountInfo)==null?void 0:b.owner)!=null?g:oe.TOKEN_PROGRAM_ID}),d.forEach(({poolId:f,pool:y})=>{var P;let b=(P=p[y.mintB.toBase58()])!=null?P:oe.TOKEN_PROGRAM_ID,g=te(this.scope.ownerPubKey,y.mintB,b).publicKey;u.addInstruction({instructions:[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,g,this.scope.ownerPubKey,y.mintB,b)]}),u.addInstruction({instructions:[fs(e,o,t,f,n,y.vaultB,g,y.mintB,b)]})}),u.addTipInstruction(a),i===0?u.sizeCheckBuildV0({computeBudgetConfig:r}):u.sizeCheckBuild({computeBudgetConfig:r})}async createVesting({programId:e=ct,poolId:t,beneficiary:n,shareAmount:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:s}){let u=this.createTxBuilder(s),c=await this.getRpcPoolInfo({poolId:t});o.add(c.vestingSchedule.totalAllocatedShare).gt(c.vestingSchedule.totalLockedAmount)&&this.logAndCreateError("share amount exceed total locked amount");let d=Go(e,t,n).publicKey;return u.addInstruction({instructions:[ps(e,this.scope.ownerPubKey,n,t,d,o)]}),u.addCustomComputeBudget(r),u.addTipInstruction(a),u.versionBuild({txVersion:i})}async createMultipleVesting({programId:e=ct,poolId:t,beneficiaryList:n,txVersion:o,computeBudgetConfig:i,feePayer:r}){let a=this.createTxBuilder(r);n.length===0&&this.logAndCreateError("beneficiaryList is null");let s=await this.getRpcPoolInfo({poolId:t});return n.reduce((c,d)=>c.add(d.shareAmount),s.vestingSchedule.totalAllocatedShare).gt(s.vestingSchedule.totalLockedAmount)&&this.logAndCreateError("share amount exceed total locked amount"),n.forEach(c=>{let d=Go(e,t,c.wallet).publicKey;a.addInstruction({instructions:[ps(e,this.scope.ownerPubKey,c.wallet,t,d,c.shareAmount)]})}),o===0?a.sizeCheckBuildV0({computeBudgetConfig:i}):a.sizeCheckBuild({computeBudgetConfig:i})}async claimVesting({programId:e=ct,poolId:t,poolInfo:n,vestingRecord:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:s}){let u=this.createTxBuilder(s),c=Yt(e).publicKey,d=o||Go(e,t,this.scope.ownerPubKey).publicKey,p=n;if(!p){let f=await this.scope.connection.getAccountInfo(t);f||this.logAndCreateError("pool not found"),p=wn.decode(f.data)}let m=te(this.scope.ownerPubKey,p.mintA,oe.TOKEN_PROGRAM_ID).publicKey;return u.addInstruction({instructions:[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,m,this.scope.ownerPubKey,p.mintA)]}),u.addInstruction({instructions:[ds(e,this.scope.ownerPubKey,c,t,d,m,p.vaultA,p.mintA,oe.TOKEN_PROGRAM_ID)]}),u.addCustomComputeBudget(r),u.addTipInstruction(a),u.versionBuild({txVersion:i})}async claimMultiVesting({programId:e=ct,poolIdList:t,poolsInfo:n={},vestingRecords:o={},txVersion:i,computeBudgetConfig:r,feePayer:a}){let s=this.createTxBuilder(a),u=N({},n),c=Yt(e).publicKey,d=t.filter(p=>!u[p.toBase58()]);if(d.length){let p=await this.getRpcPoolsInfo({poolIdList:d});u=N(N({},u),p.poolInfoMap)}return t.forEach(p=>{let m=p.toBase58(),f=u[m];f||this.logAndCreateError(`pool info not found: ${m}`);let y=o[m]||Go(e,p,this.scope.ownerPubKey).publicKey,b=te(this.scope.ownerPubKey,f.mintA,oe.TOKEN_PROGRAM_ID).publicKey;s.addInstruction({instructions:[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,b,this.scope.ownerPubKey,f.mintA)]}),s.addInstruction({instructions:[ds(e,this.scope.ownerPubKey,c,p,y,b,f.vaultA,f.mintA,oe.TOKEN_PROGRAM_ID)]})}),i===0?s.sizeCheckBuildV0({computeBudgetConfig:r}):s.sizeCheckBuild({computeBudgetConfig:r})}async claimVaultPlatformFee({programId:e=ct,platformId:t,mintB:n,mintBProgram:o,claimFeeWallet:i,txVersion:r,computeBudgetConfig:a,txTipConfig:s,feePayer:u}){let c=this.createTxBuilder(u),d=Tn(e,t,n).publicKey,p=ls(e).publicKey,{mintBProgram:m}=await this.getMintBTokenInfo({mintB:n,mintBProgram:o}),f=this.scope.account.getAssociatedTokenAccount(n,m);return c.addInstruction({instructions:[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,f,this.scope.ownerPubKey,n,m),ys(e,t,i!=null?i:this.scope.ownerPubKey,p,d,f,n,m)]}),c.addCustomComputeBudget(a),c.addTipInstruction(s),c.versionBuild({txVersion:r})}async claimMultipleVaultPlatformFee({programId:e=ct,platformList:t,unwrapSol:n=!0,txVersion:o,computeBudgetConfig:i,feePayer:r,associatedOnly:a=!0,checkCreateATAOwner:s=!1}){let u=this.createTxBuilder(r),c={};return t.forEach(async d=>{var b,g,P;let p=ls(e).publicKey,m=Tn(e,d.id,d.mintB).publicKey,f=d.mintB.equals(oe.NATIVE_MINT)&&n,y=c[d.mintB.toBase58()];if(!y){let{account:k,instructionParams:I}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:(b=d.mintBProgram)!=null?b:oe.TOKEN_PROGRAM_ID,mint:d.mintB,owner:this.scope.ownerPubKey,createInfo:f?{payer:this.scope.ownerPubKey,amount:0}:void 0,skipCloseAccount:!f,notUseTokenAccount:f,associatedOnly:f?!1:a,checkCreateATAOwner:s});k&&(y=k),u.addInstruction(I||{}),y===void 0&&this.logAndCreateError(`cannot found platform ${d.id.toBase58()} mintB(${d.mintB.toBase58()}) token accounts`,"tokenAccounts",this.scope.account.tokenAccounts)}u.addInstruction({instructions:[ys(e,d.id,(g=d.claimFeeWallet)!=null?g:this.scope.ownerPubKey,p,m,y,d.mintB,(P=d.mintBProgram)!=null?P:oe.TOKEN_PROGRAM_ID)]})}),o===0?u.sizeCheckBuildV0({computeBudgetConfig:i}):u.sizeCheckBuild({computeBudgetConfig:i})}async claimCreatorFee({programId:e=ct,mintB:t,mintBProgram:n,txVersion:o,computeBudgetConfig:i,txTipConfig:r,feePayer:a}){let s=this.createTxBuilder(a),u=hn(e,this.scope.ownerPubKey,t).publicKey,c=ms(e).publicKey,{mintBProgram:d}=await this.getMintBTokenInfo({mintB:t,mintBProgram:n}),p=this.scope.account.getAssociatedTokenAccount(t,d);return s.addInstruction({instructions:[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,p,this.scope.ownerPubKey,t,d),bs(e,this.scope.ownerPubKey,c,u,p,t,d)]}),s.addCustomComputeBudget(i),s.addTipInstruction(r),s.versionBuild({txVersion:o})}async claimMultipleCreatorFee({programId:e=ct,mintBList:t,txVersion:n,computeBudgetConfig:o,feePayer:i}){let r=this.createTxBuilder(i);return t.forEach(a=>{var m;let s=a.pubKey,u=(m=a.programId)!=null?m:oe.TOKEN_PROGRAM_ID,c=hn(e,this.scope.ownerPubKey,s).publicKey,d=ms(e).publicKey,p=this.scope.account.getAssociatedTokenAccount(s,u);r.addInstruction({instructions:[(0,oe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,p,this.scope.ownerPubKey,s,u),bs(e,this.scope.ownerPubKey,d,c,p,s,u)]})}),n==0?r.sizeCheckBuildV0({computeBudgetConfig:o}):r.sizeCheckBuild({computeBudgetConfig:o})}async createPlatformAllowConfig({programId:e=ct,platformAdmin:t,platformId:n,configInfo:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:s}){let u=this.createTxBuilder(s),{publicKey:c}=ss(e,new ko.PublicKey(o.mintB),o.curveType,o.index),{publicKey:d}=Si(e,n,c);return u.addInstruction({instructions:[vc(e,t,n,c,d)]}),u.addCustomComputeBudget(r),u.addTipInstruction(a),u.versionBuild({txVersion:i,extInfo:{platformId:n}})}async closePlatformAllowConfig({programId:e=ct,platformAdmin:t,platformId:n,configInfo:o,txVersion:i,computeBudgetConfig:r,txTipConfig:a,feePayer:s}){let u=this.createTxBuilder(s),{publicKey:c}=ss(e,new ko.PublicKey(o.mintB),o.curveType,o.index),{publicKey:d}=Si(e,n,c);return u.addInstruction({instructions:[_c(e,t,n,c,d)]}),u.addCustomComputeBudget(r),u.addTipInstruction(a),u.versionBuild({txVersion:i,extInfo:{platformId:n}})}async getRpcPoolInfo({poolId:e}){return(await this.getRpcPoolsInfo({poolIdList:[e]})).poolInfoMap[e.toBase58()]}async getRpcPoolsInfo({poolIdList:e,config:t}){let n=await qe(this.scope.connection,e.map(s=>({pubkey:s})),t),o={},i=[];for(let s=0;s<e.length;s++){let u=n[s];if(u===null||!u.accountInfo)throw Error("fetch pool info error: "+e[s].toBase58());let c=wn.decode(u.accountInfo.data);o[e[s].toBase58()]=E(N({},c),{poolId:e[s],programId:u.accountInfo.owner}),i.push(c.configId)}let r=await qe(this.scope.connection,i.map(s=>({pubkey:s})),t),a={};for(let s=0;s<i.length;s++){let u=r[s];if(u===null||!u.accountInfo)throw Error("fetch config info error: "+i[s].toBase58());let c=no.decode(u.accountInfo.data);a[i[s].toBase58()]=E(N({},c),{configId:u.accountInfo.owner})}return{poolInfoMap:Object.keys(o).reduce((s,u)=>E(N({},s),{[u]:E(N({},o[u]),{configInfo:a[o[u].configId.toBase58()]})}),{})}}};var qc={[$r.toBase58()]:3},Uc={3:$r};var gs=v([Be(5),Be(8),M("ownAddress"),w("vaultSignerNonce"),M("baseMint"),M("quoteMint"),M("baseVault"),w("baseDepositsTotal"),w("baseFeesAccrued"),M("quoteVault"),w("quoteDepositsTotal"),w("quoteFeesAccrued"),w("quoteDustThreshold"),M("requestQueue"),M("eventQueue"),M("bids"),M("asks"),w("baseLotSize"),w("quoteLotSize"),w("feeRateBps"),w("referrerRebatesAccrued"),Be(7)]),Gc={3:gs};var zc=require("@solana/web3.js");var Ps=Se("Serum"),_r=class{static getProgramId(e){let t=Uc[e];return t||Ps.logWithError("invalid version","version",e),t}static getVersion(e){let t=e.toBase58(),n=qc[t];return n||Ps.logWithError("invalid program id","programId",t),n}static getStateLayout(e){let t=Gc[e];return t||Ps.logWithError(!!t,"invalid version","version",e),t}static getLayouts(e){return{state:this.getStateLayout(e)}}static getAssociatedAuthority({programId:e,marketId:t}){let n=[t.toBuffer()],o=0,i;for(;o<100;){try{let r=n.concat(Buffer.from([o]),Buffer.alloc(7));i=zc.PublicKey.createProgramAddressSync(r,e)}catch(r){if(r instanceof TypeError)throw r;o++;continue}return{publicKey:i,nonce:o}}return Ps.logWithError("unable to find a viable program address nonce","params",{programId:e,marketId:t}),{publicKey:zc.PublicKey.default,nonce:o}}};var qt=require("@solana/spl-token"),_=require("@solana/web3.js"),In=ie(require("bn.js"));function Gf(l,e,t,n,o,i,r,a,s,u,c,d){let p=v([V("instruction"),w("amountIn"),w("amountOut")]),m=[{pubkey:_.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:qt.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:new _.PublicKey(t.programId),isSigner:!1,isWritable:!1},{pubkey:new _.PublicKey(t.id),isSigner:!1,isWritable:!0},{pubkey:new _.PublicKey(n.id),isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!0,isWritable:!1}];if(e.type==="Concentrated"){let y=it(t);m.push({pubkey:y.config.id,isSigner:!1,isWritable:!1},{pubkey:y.id,isSigner:!1,isWritable:!0},{pubkey:y.mintA.address.equals(s)?y.vault.A:y.vault.B,isSigner:!1,isWritable:!0},{pubkey:y.mintA.address.equals(s)?y.vault.B:y.vault.A,isSigner:!1,isWritable:!0},{pubkey:y.id,isSigner:!1,isWritable:!0},...d.map(b=>({pubkey:b,isSigner:!1,isWritable:!0})))}else if(e.pooltype.includes("StablePool")){let y=it(t);m.push({pubkey:y.authority,isSigner:!1,isWritable:!1},{pubkey:y.marketProgramId,isSigner:!1,isWritable:!1},{pubkey:y.id,isSigner:!1,isWritable:!0},{pubkey:new _.PublicKey("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),isSigner:!1,isWritable:!1},{pubkey:y.openOrders,isSigner:!1,isWritable:!0},{pubkey:y.vault.A,isSigner:!1,isWritable:!0},{pubkey:y.vault.B,isSigner:!1,isWritable:!0},{pubkey:y.marketId,isSigner:!1,isWritable:!0},{pubkey:y.marketBids,isSigner:!1,isWritable:!0},{pubkey:y.marketAsks,isSigner:!1,isWritable:!0},{pubkey:y.marketEventQueue,isSigner:!1,isWritable:!0},{pubkey:y.id,isSigner:!1,isWritable:!0},{pubkey:y.id,isSigner:!1,isWritable:!0})}else{let y=it(t);m.push({pubkey:y.authority,isSigner:!1,isWritable:!1},{pubkey:y.marketProgramId,isSigner:!1,isWritable:!1},{pubkey:y.marketAuthority,isSigner:!1,isWritable:!1},{pubkey:y.openOrders,isSigner:!1,isWritable:!0},{pubkey:y.vault.A,isSigner:!1,isWritable:!0},{pubkey:y.vault.B,isSigner:!1,isWritable:!0},{pubkey:y.marketId,isSigner:!1,isWritable:!0},{pubkey:y.marketBids,isSigner:!1,isWritable:!0},{pubkey:y.marketAsks,isSigner:!1,isWritable:!0},{pubkey:y.marketEventQueue,isSigner:!1,isWritable:!0},...y.marketProgramId.toString()==="srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"?[{pubkey:y.marketBaseVault,isSigner:!1,isWritable:!0},{pubkey:y.marketQuoteVault,isSigner:!1,isWritable:!0}]:[{pubkey:y.id,isSigner:!1,isWritable:!0},{pubkey:y.id,isSigner:!1,isWritable:!0}])}let f=Buffer.alloc(p.span);return p.encode({instruction:4,amountIn:u,amountOut:c},f),new _.TransactionInstruction({keys:m,programId:l,data:f})}function zf(l,e,t,n,o,i,r,a,s,u){let c=v([V("instruction")]),d=[{pubkey:_.SystemProgram.programId,isSigner:!1,isWritable:!1},{pubkey:qt.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:new _.PublicKey(String(n.programId)),isSigner:!1,isWritable:!1},{pubkey:new _.PublicKey(String(n.id)),isSigner:!1,isWritable:!0},{pubkey:new _.PublicKey(String(t.id)),isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!0,isWritable:!1}];if(e.type==="Concentrated"){let m=it(n);d.push({pubkey:m.config.id,isSigner:!1,isWritable:!1},{pubkey:m.id,isSigner:!1,isWritable:!0},{pubkey:m.mintA.address.equals(s)?m.vault.A:m.vault.B,isSigner:!1,isWritable:!0},{pubkey:m.mintA.address.equals(s)?m.vault.B:m.vault.A,isSigner:!1,isWritable:!0},{pubkey:m.id,isSigner:!1,isWritable:!0},...u.map(f=>({pubkey:f,isSigner:!1,isWritable:!0})))}else if(e.pooltype.includes("StablePool")){let m=it(n);d.push({pubkey:m.authority,isSigner:!1,isWritable:!1},{pubkey:m.marketProgramId,isSigner:!1,isWritable:!1},{pubkey:m.id,isSigner:!1,isWritable:!0},{pubkey:new _.PublicKey("CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo"),isSigner:!1,isWritable:!1},{pubkey:m.openOrders,isSigner:!1,isWritable:!0},{pubkey:m.vault.A,isSigner:!1,isWritable:!0},{pubkey:m.vault.B,isSigner:!1,isWritable:!0},{pubkey:m.marketId,isSigner:!1,isWritable:!0},{pubkey:m.marketBids,isSigner:!1,isWritable:!0},{pubkey:m.marketAsks,isSigner:!1,isWritable:!0},{pubkey:m.marketEventQueue,isSigner:!1,isWritable:!0},{pubkey:m.id,isSigner:!1,isWritable:!0},{pubkey:m.id,isSigner:!1,isWritable:!0})}else{let m=it(n);d.push({pubkey:m.authority,isSigner:!1,isWritable:!1},{pubkey:m.marketProgramId,isSigner:!1,isWritable:!1},{pubkey:m.marketAuthority,isSigner:!1,isWritable:!1},{pubkey:m.openOrders,isSigner:!1,isWritable:!0},{pubkey:m.vault.A,isSigner:!1,isWritable:!0},{pubkey:m.vault.B,isSigner:!1,isWritable:!0},{pubkey:m.marketId,isSigner:!1,isWritable:!0},{pubkey:m.marketBids,isSigner:!1,isWritable:!0},{pubkey:m.marketAsks,isSigner:!1,isWritable:!0},{pubkey:m.marketEventQueue,isSigner:!1,isWritable:!0},...m.marketProgramId.toString()==="srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"?[{pubkey:m.marketBaseVault,isSigner:!1,isWritable:!0},{pubkey:m.marketQuoteVault,isSigner:!1,isWritable:!0}]:[{pubkey:m.id,isSigner:!1,isWritable:!0},{pubkey:m.id,isSigner:!1,isWritable:!0}])}let p=Buffer.alloc(c.span);return c.encode({instruction:5},p),new _.TransactionInstruction({keys:d,programId:l,data:p})}function Td(l,e,t,n,o,i,r,a,s,u,c,d,p,m,f){var h;let y=[],b=[T({pubkey:qt.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:qt.TOKEN_2022_PROGRAM_ID,isWritable:!1}),T({pubkey:qt.ASSOCIATED_TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:_.SystemProgram.programId,isWritable:!1}),T({pubkey:e,isSigner:!0})];b.push(T({pubkey:t})),b.push(T({pubkey:o}));let g=[s,u],P=[c,d],k=[i,r,a];for(let B=0;B<g.length;B++){let S=g[B],K=k[B]===S.mintA.address;if(b.push(T({pubkey:new _.PublicKey(S.programId),isWritable:!1})),B===g.length-1?b.push(T({pubkey:o})):b.push(T({pubkey:n})),b.push(T({pubkey:new _.PublicKey(k[B])})),b.push(T({pubkey:new _.PublicKey(k[B+1])})),S.version===6){let x=P[B];b.push(T({pubkey:new _.PublicKey(x.config.id)})),b.push(T({pubkey:new _.PublicKey(x.id)})),b.push(T({pubkey:new _.PublicKey(K?x.vault.A:x.vault.B)})),b.push(T({pubkey:new _.PublicKey(K?x.vault.B:x.vault.A)})),b.push(T({pubkey:new _.PublicKey(S.observationId)})),b.push(T({pubkey:mn})),b.push(T({pubkey:He(new _.PublicKey(S.programId),new _.PublicKey(S.id)).publicKey})),y.push(Xc(S.sqrtPriceX64.toString(),K));for(let C of(h=f[B])!=null?h:[])b.push(T({pubkey:new _.PublicKey(C)}))}else if(S.version===5){let x=P[B];b.push(T({pubkey:new _.PublicKey(x.id)})),b.push(T({pubkey:new _.PublicKey(x.authority),isWritable:!1})),b.push(T({pubkey:new _.PublicKey(x.marketProgramId)})),b.push(T({pubkey:new _.PublicKey(x.marketAuthority)})),b.push(T({pubkey:Jr,isWritable:!1})),b.push(T({pubkey:new _.PublicKey(x.openOrders)})),b.push(T({pubkey:new _.PublicKey(x.vault.A)})),b.push(T({pubkey:new _.PublicKey(x.vault.B)})),b.push(T({pubkey:new _.PublicKey(x.id)})),b.push(T({pubkey:new _.PublicKey(x.id)})),b.push(T({pubkey:new _.PublicKey(x.id)})),b.push(T({pubkey:new _.PublicKey(x.id)})),b.push(T({pubkey:new _.PublicKey(x.id)})),b.push(T({pubkey:new _.PublicKey(x.id)})),b.push(T({pubkey:new _.PublicKey(x.marketId)})),b.push(T({pubkey:new _.PublicKey(x.marketBids)})),b.push(T({pubkey:new _.PublicKey(x.marketAsks)})),b.push(T({pubkey:new _.PublicKey(x.marketEventQueue)})),b.push(T({pubkey:new _.PublicKey(x.marketBaseVault)})),b.push(T({pubkey:new _.PublicKey(x.marketQuoteVault)}))}else if(S.version===4){let x=P[B],C=S.status!==1;b.push(T({pubkey:new _.PublicKey(x.id)})),b.push(T({pubkey:new _.PublicKey(x.authority),isWritable:!1})),b.push(T({pubkey:new _.PublicKey(C?x.id:x.marketProgramId)})),b.push(T({pubkey:new _.PublicKey(C?x.id:x.marketAuthority)})),b.push(T({pubkey:new _.PublicKey(C?x.id:x.openOrders)})),b.push(T({pubkey:new _.PublicKey(x.vault.A)})),b.push(T({pubkey:new _.PublicKey(x.vault.B)})),b.push(T({pubkey:new _.PublicKey(C?x.id:x.marketId)})),b.push(T({pubkey:new _.PublicKey(C?x.id:x.marketBids)})),b.push(T({pubkey:new _.PublicKey(C?x.id:x.marketAsks)})),b.push(T({pubkey:new _.PublicKey(C?x.id:x.marketEventQueue)})),b.push(T({pubkey:new _.PublicKey(C?x.id:x.marketBaseVault)})),b.push(T({pubkey:new _.PublicKey(C?x.id:x.marketQuoteVault)}))}else if(S.version===7){let x=P[B];b.push(T({pubkey:new _.PublicKey(x.authority)})),b.push(T({pubkey:new _.PublicKey(x.config.id)})),b.push(T({pubkey:new _.PublicKey(x.id)})),b.push(T({pubkey:new _.PublicKey(K?x.vault.A:x.vault.B)})),b.push(T({pubkey:new _.PublicKey(K?x.vault.B:x.vault.A)})),b.push(T({pubkey:new _.PublicKey(S.observationId)}))}else throw Error("pool type error")}let I=v([V("insId"),w("amountIn"),w("amountOut"),j(pe(),y.length,"clmmPriceLimit")]),A=Buffer.alloc(I.span);return I.encode({insId:0,amountIn:p,amountOut:m,clmmPriceLimit:y},A),new _.TransactionInstruction({keys:b,programId:l,data:A})}function Xc(l,e){if(l)if(e){let t=new In.default(l).div(new In.default(25));return t.gt(xt.add(dt))?t:xt.add(dt)}else{let t=new In.default(l).mul(new In.default(25));return t.lt(St.sub(dt))?t:St.sub(dt)}else return e?xt.add(dt):St.sub(dt)}function Yc({routeProgram:l,ownerInfo:e,inputMint:t,swapInfo:n}){var o,i,r,a,s,u,c,d,p;if(n.routeType==="amm")if(n.poolInfo[0].version===6){let m=n.poolKey[0],f=it(m),y=t.equals(f.mintA.address)?xt.add(dt):St.sub(dt);return we.makeSwapBaseInInstructions({poolInfo:m,poolKeys:m,observationId:n.poolInfo[0].observationId,ownerInfo:{wallet:e.wallet,tokenAccountA:f.mintA.address.equals(t)?e.sourceToken:e.destinationToken,tokenAccountB:f.mintA.address.equals(t)?e.destinationToken:e.sourceToken},inputMint:t,amountIn:n.amountIn.amount.raw,amountOutMin:n.minAmountOut.amount.raw.sub((i=(o=n.minAmountOut.fee)==null?void 0:o.raw)!=null?i:new In.default(0)),sqrtPriceLimitX64:y,remainingAccounts:(r=n.remainingAccounts[0])!=null?r:[]})}else if(n.poolInfo[0].version===7){let m=n.poolInfo[0],f=t.toString()===n.poolInfo[0].mintA.address;return{signers:[],instructions:[qo(m.programId,e.wallet,m.authority,m.configId,m.id,e.sourceToken,e.destinationToken,f?m.vaultA:m.vaultB,f?m.vaultB:m.vaultA,f?m.mintProgramA:m.mintProgramB,f?m.mintProgramB:m.mintProgramA,new _.PublicKey(m[f?"mintA":"mintB"].address),new _.PublicKey(m[f?"mintB":"mintA"].address),m.observationId,n.amountIn.amount.raw,n.minAmountOut.amount.raw)],lookupTableAddress:[],instructionTypes:[f?Y.CpmmSwapBaseIn:Y.CpmmSwapBaseOut],address:{}}}else{let m=n.poolKey[0];return{signers:[],instructions:[n.poolInfo[0].pooltype.includes("StablePool")?br({poolKeys:m,version:n.poolInfo[0].pooltype.includes("StablePool")?5:4,userKeys:{tokenAccountIn:e.sourceToken,tokenAccountOut:e.destinationToken,owner:e.wallet},amountIn:n.amountIn.amount.raw,amountOut:n.minAmountOut.amount.raw.sub((s=(a=n.minAmountOut.fee)==null?void 0:a.raw)!=null?s:new In.default(0)),fixedSide:"in"}):yr({poolKeys:m,version:n.poolInfo[0].pooltype.includes("StablePool")?5:4,userKeys:{tokenAccountIn:e.sourceToken,tokenAccountOut:e.destinationToken,owner:e.wallet},amountIn:n.amountIn.amount.raw,amountOut:n.minAmountOut.amount.raw.sub((c=(u=n.minAmountOut.fee)==null?void 0:u.raw)!=null?c:new In.default(0)),fixedSide:"in"})],lookupTableAddress:m.lookupTableAccount?[m.lookupTableAccount]:[],instructionTypes:[n.poolInfo[0].pooltype.includes("StablePool")?Y.AmmV5SwapBaseIn:Y.AmmV4SwapBaseIn],address:{}}}else if(n.routeType==="route"){let m=n.poolInfo[0],f=n.poolInfo[1],y=n.poolKey[0],b=n.poolKey[1];if(e.routeToken===void 0)throw Error("owner route token account check error");return{signers:[],instructions:[Td(l,e.wallet,e.sourceToken,e.routeToken,e.destinationToken,t.toString(),n.middleToken.mint.toString(),n.outputMint.toString(),m,f,y,b,n.amountIn.amount.raw,n.minAmountOut.amount.raw.sub((p=(d=n.minAmountOut.fee)==null?void 0:d.raw)!=null?p:new In.default(0)),n.remainingAccounts)],instructionTypes:[Y.RouteSwap],lookupTableAddress:[y.lookupTableAccount,b.lookupTableAccount].filter(g=>g!==void 0),address:{}}}else throw Error("route type error")}function Xf({programId:l,wallet:e,amount:t,inputAccount:n,outputAccount:o,routeInfo:i,poolKeys:r}){var p;if(i.success===!1)throw Error("route info error");let a=[],s=[T({pubkey:qt.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:qt.TOKEN_2022_PROGRAM_ID,isWritable:!1}),T({pubkey:qt.ASSOCIATED_TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:_.SystemProgram.programId,isWritable:!1}),T({pubkey:e,isSigner:!0})],u={[i.data.inputMint]:n,[i.data.outputMint]:o};s.push(T({pubkey:u[i.data.inputMint]})),s.push(T({pubkey:u[i.data.outputMint]}));for(let m=0;m<r.length;m++){let f=i.data.routePlan[m],y=r[m],b=f.inputMint===y.mintA.address;if(s.push(T({pubkey:new _.PublicKey(y.programId),isWritable:!1})),m===r.length-1)s.push(T({pubkey:u[f.outputMint]}));else{let g=f.outputMint;if(u[g]===void 0){let P=te(e,new _.PublicKey(g),y.programId===jt.CLMM_PROGRAM_ID.toBase58()||y.programId===jt.CREATE_CPMM_POOL_PROGRAM.toBase58()?new _.PublicKey(b?y.mintB.programId:y.mintA.programId):qt.TOKEN_PROGRAM_ID).publicKey;u[g]=P}s.push(T({pubkey:u[g]}))}if(s.push(T({pubkey:new _.PublicKey(f.inputMint)})),s.push(T({pubkey:new _.PublicKey(f.outputMint)})),y.programId===jt.CLMM_PROGRAM_ID.toBase58()){let g=y;s.push(T({pubkey:new _.PublicKey(g.config.id)})),s.push(T({pubkey:new _.PublicKey(g.id)})),s.push(T({pubkey:new _.PublicKey(b?g.vault.A:g.vault.B)})),s.push(T({pubkey:new _.PublicKey(b?g.vault.B:g.vault.A)})),s.push(T({pubkey:new _.PublicKey(g.observationId)})),s.push(T({pubkey:mn,isWritable:!1})),s.push(T({pubkey:new _.PublicKey(g.exBitmapAccount)})),a.push(Xc(f.lastPoolPriceX64,b));for(let P of(p=f.remainingAccounts)!=null?p:[])s.push(T({pubkey:new _.PublicKey(P)}))}else if(y.programId===jt.AMM_STABLE.toBase58()){let g=y;s.push(T({pubkey:new _.PublicKey(g.id)})),s.push(T({pubkey:new _.PublicKey(g.authority),isWritable:!1})),s.push(T({pubkey:new _.PublicKey(g.marketProgramId),isWritable:!1})),s.push(T({pubkey:new _.PublicKey(g.marketAuthority),isWritable:!1})),s.push(T({pubkey:Jr,isWritable:!1})),s.push(T({pubkey:new _.PublicKey(g.openOrders)})),s.push(T({pubkey:new _.PublicKey(g.vault.A)})),s.push(T({pubkey:new _.PublicKey(g.vault.B)})),s.push(T({pubkey:new _.PublicKey(g.marketId)})),s.push(T({pubkey:new _.PublicKey(g.marketBids)})),s.push(T({pubkey:new _.PublicKey(g.marketAsks)})),s.push(T({pubkey:new _.PublicKey(g.marketEventQueue)})),s.push(T({pubkey:new _.PublicKey(g.marketBaseVault)})),s.push(T({pubkey:new _.PublicKey(g.marketQuoteVault)}))}else if(y.programId===jt.AMM_V4.toBase58()){let g=y;s.push(T({pubkey:new _.PublicKey(g.id)})),s.push(T({pubkey:new _.PublicKey(g.authority),isWritable:!1})),s.push(T({pubkey:new _.PublicKey(g.id)})),s.push(T({pubkey:new _.PublicKey(g.id)})),s.push(T({pubkey:new _.PublicKey(g.id)})),s.push(T({pubkey:new _.PublicKey(g.vault.A)})),s.push(T({pubkey:new _.PublicKey(g.vault.B)})),s.push(T({pubkey:new _.PublicKey(g.id)})),s.push(T({pubkey:new _.PublicKey(g.id)})),s.push(T({pubkey:new _.PublicKey(g.id)})),s.push(T({pubkey:new _.PublicKey(g.id)})),s.push(T({pubkey:new _.PublicKey(g.id)})),s.push(T({pubkey:new _.PublicKey(g.id)}))}else if(y.programId===jt.CREATE_CPMM_POOL_PROGRAM.toBase58()){let g=y;s.push(T({pubkey:new _.PublicKey(g.authority)})),s.push(T({pubkey:new _.PublicKey(g.config.id)})),s.push(T({pubkey:new _.PublicKey(g.id)})),s.push(T({pubkey:new _.PublicKey(b?g.vault.A:g.vault.B)})),s.push(T({pubkey:new _.PublicKey(b?g.vault.B:g.vault.A)})),s.push(T({pubkey:new _.PublicKey(g.observationId)}))}else throw Error("pool type error")}let c=v([V("insId"),w("amountIn"),w("amountOut"),j(pe(),a.length,"clmmPriceLimit")]),d=Buffer.alloc(c.span);return c.encode({insId:0,amountIn:t,amountOut:new In.default(i.data.otherAmountThreshold),clmmPriceLimit:a},d),new _.TransactionInstruction({keys:s,programId:l,data:d})}function Yf({programId:l,wallet:e,inputAccount:t,outputAccount:n,routeInfo:o,poolKeys:i}){var d;if(o.success===!1)throw Error("route info error");let r=[],a=[T({pubkey:qt.TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:qt.TOKEN_2022_PROGRAM_ID,isWritable:!1}),T({pubkey:qt.ASSOCIATED_TOKEN_PROGRAM_ID,isWritable:!1}),T({pubkey:_.SystemProgram.programId,isWritable:!1}),T({pubkey:e,isSigner:!0})],s={[o.data.inputMint]:t,[o.data.outputMint]:n};for(let p=i.length-1;p>=0;p--){let m=o.data.routePlan[p],f=i[p],y=m.inputMint===f.mintA.address;if(a.push(T({pubkey:new _.PublicKey(f.programId)})),p===0)a.push(T({pubkey:s[m.inputMint]}));else{let b=m.inputMint;if(s[b]===void 0){let g=te(e,new _.PublicKey(b),f.programId===jt.CLMM_PROGRAM_ID.toBase58()||f.programId===jt.CREATE_CPMM_POOL_PROGRAM.toBase58()?new _.PublicKey(y?f.mintA.programId:f.mintB.programId):qt.TOKEN_PROGRAM_ID).publicKey;s[b]=g}a.push(T({pubkey:s[b]}))}if(p===i.length-1)a.push(T({pubkey:s[m.outputMint]}));else{let b=m.outputMint;if(s[b]===void 0){let g=te(e,new _.PublicKey(b),f.programId===jt.CLMM_PROGRAM_ID.toBase58()||f.programId===jt.CREATE_CPMM_POOL_PROGRAM.toBase58()?new _.PublicKey(y?f.mintB.programId:f.mintA.programId):qt.TOKEN_PROGRAM_ID).publicKey;s[b]=g}a.push(T({pubkey:s[b]}))}if(a.push(T({pubkey:new _.PublicKey(m.inputMint)})),a.push(T({pubkey:new _.PublicKey(m.outputMint)})),f.programId===jt.CLMM_PROGRAM_ID.toBase58()){let b=f;a.push(T({pubkey:new _.PublicKey(b.config.id)})),a.push(T({pubkey:new _.PublicKey(b.id)})),a.push(T({pubkey:new _.PublicKey(y?b.vault.A:b.vault.B)})),a.push(T({pubkey:new _.PublicKey(y?b.vault.B:b.vault.A)})),a.push(T({pubkey:new _.PublicKey(b.observationId)})),a.push(T({pubkey:mn,isWritable:!1})),a.push(T({pubkey:new _.PublicKey(b.exBitmapAccount)})),r.push(Xc(m.lastPoolPriceX64,y));for(let g of(d=m.remainingAccounts)!=null?d:[])a.push(T({pubkey:new _.PublicKey(g)}))}else if(f.programId===jt.AMM_STABLE.toBase58()){let b=f;a.push(T({pubkey:new _.PublicKey(b.id)})),a.push(T({pubkey:new _.PublicKey(b.authority),isWritable:!1})),a.push(T({pubkey:new _.PublicKey(b.marketProgramId),isWritable:!1})),a.push(T({pubkey:new _.PublicKey(b.marketAuthority),isWritable:!1})),a.push(T({pubkey:Jr,isWritable:!1})),a.push(T({pubkey:new _.PublicKey(b.openOrders)})),a.push(T({pubkey:new _.PublicKey(b.vault.A)})),a.push(T({pubkey:new _.PublicKey(b.vault.B)})),a.push(T({pubkey:new _.PublicKey(b.marketId)})),a.push(T({pubkey:new _.PublicKey(b.marketBids)})),a.push(T({pubkey:new _.PublicKey(b.marketAsks)})),a.push(T({pubkey:new _.PublicKey(b.marketEventQueue)})),a.push(T({pubkey:new _.PublicKey(b.marketBaseVault)})),a.push(T({pubkey:new _.PublicKey(b.marketQuoteVault)}))}else if(f.programId===jt.AMM_V4.toBase58()){let b=f;a.push(T({pubkey:new _.PublicKey(b.id)})),a.push(T({pubkey:new _.PublicKey(b.authority),isWritable:!1})),a.push(T({pubkey:new _.PublicKey(b.id)})),a.push(T({pubkey:new _.PublicKey(b.id)})),a.push(T({pubkey:new _.PublicKey(b.id)})),a.push(T({pubkey:new _.PublicKey(b.vault.A)})),a.push(T({pubkey:new _.PublicKey(b.vault.B)})),a.push(T({pubkey:new _.PublicKey(b.id)})),a.push(T({pubkey:new _.PublicKey(b.id)})),a.push(T({pubkey:new _.PublicKey(b.id)})),a.push(T({pubkey:new _.PublicKey(b.id)})),a.push(T({pubkey:new _.PublicKey(b.id)})),a.push(T({pubkey:new _.PublicKey(b.id)}))}else if(f.programId===jt.CREATE_CPMM_POOL_PROGRAM.toBase58()){let b=f;a.push(T({pubkey:new _.PublicKey(b.authority)})),a.push(T({pubkey:new _.PublicKey(b.config.id)})),a.push(T({pubkey:new _.PublicKey(b.id)})),a.push(T({pubkey:new _.PublicKey(y?b.vault.A:b.vault.B)})),a.push(T({pubkey:new _.PublicKey(y?b.vault.B:b.vault.A)})),a.push(T({pubkey:new _.PublicKey(b.observationId)}))}else throw Error("pool type error")}let u=v([V("insId"),w("amountIn"),w("amountOut"),j(pe(),r.length,"clmmPriceLimit")]),c=Buffer.alloc(u.span);return u.encode({insId:1,amountIn:new In.default(o.data.otherAmountThreshold),amountOut:new In.default(o.data.outputAmount),clmmPriceLimit:r},c),new _.TransactionInstruction({keys:a,programId:l,data:c})}var _t=new Ie.default(0);function ro(l,e){var n,o,i,r,a;let t=(n=l.extensions)==null?void 0:n.feeConfig;if(!!t)return{transferFeeConfigAuthority:ye.PublicKey.default,withdrawWithheldAuthority:ye.PublicKey.default,withheldAmount:BigInt(0),olderTransferFee:{epoch:BigInt((i=(o=t.olderTransferFee.epoch)!=null?o:e)!=null?i:0),maximumFee:BigInt(t.olderTransferFee.maximumFee),transferFeeBasisPoints:t.olderTransferFee.transferFeeBasisPoints},newerTransferFee:{epoch:BigInt((a=(r=t.newerTransferFee.epoch)!=null?r:e)!=null?a:0),maximumFee:BigInt(t.newerTransferFee.maximumFee),transferFeeBasisPoints:t.newerTransferFee.transferFeeBasisPoints}}}function As(l){return l.programId?new ye.PublicKey(l.programId):Pe.TOKEN_PROGRAM_ID}var Vr=class extends at{constructor(e){super(e)}async getWSolAccounts(){this.scope.checkOwner(),await this.scope.account.fetchWalletTokenAccounts();let e=this.scope.account.tokenAccounts.filter(t=>t.mint.equals(ee));return e.sort((t,n)=>t.isAssociated?1:n.isAssociated||t.amount.lt(n.amount)?-1:1),e}async unWrapWSol(e){let{amount:t,tokenProgram:n,txVersion:o=1,feePayer:i}=e,r=await this.getWSolAccounts(),a=this.createTxBuilder(i);a.addCustomComputeBudget(e.computeBudgetConfig);let s=fe(t);for(let u=0;u<r.length;u++)s.gte(r[u].amount)?(a.addInstruction({instructions:[Dn({tokenAccount:r[u].publicKey,payer:this.scope.ownerPubKey,owner:this.scope.ownerPubKey,programId:n})]}),s.sub(r[u].amount)):a.addInstruction({instructions:[Dn({tokenAccount:r[u].publicKey,payer:this.scope.ownerPubKey,owner:this.scope.ownerPubKey,programId:n})]});return a.versionBuild({txVersion:o})}async wrapWSol(e,t,n,o){let i=this.createTxBuilder(o),r=await jn({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:this.scope.ownerPubKey,amount:e,skipCloseAccount:!0});return i.addInstruction(r),i.versionBuild({txVersion:n!=null?n:1})}async swap({swapInfo:e,swapPoolKeys:t,ownerInfo:n,computeBudgetConfig:o,routeProgram:i,txVersion:r,feePayer:a}){let s=this.createTxBuilder(a),u=e.amountIn,c=e.amountOut,d=u.amount.token.mint.equals(ee),p=c.amount.token.mint.equals(ee),m=u.amount.token.mint,f=c.amount.token.mint,{account:y,instructionParams:b}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:u.amount.token.isToken2022?Pe.TOKEN_2022_PROGRAM_ID:Pe.TOKEN_PROGRAM_ID,mint:m,notUseTokenAccount:d,owner:this.scope.ownerPubKey,skipCloseAccount:!d,createInfo:d?{payer:this.scope.ownerPubKey,amount:u.amount.raw}:void 0,associatedOnly:d?!1:n.associatedOnly,checkCreateATAOwner:n.checkCreateATAOwner});if(b&&s.addInstruction(b),y===void 0)throw Error("input account check error");let g;if(e.routeType==="route"&&!p)g=this.scope.account.getAssociatedTokenAccount(f,c.amount.token.isToken2022?Pe.TOKEN_2022_PROGRAM_ID:Pe.TOKEN_PROGRAM_ID);else{let{account:A,instructionParams:h}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:c.amount.token.isToken2022?Pe.TOKEN_2022_PROGRAM_ID:Pe.TOKEN_PROGRAM_ID,mint:f,notUseTokenAccount:p,owner:this.scope.ownerPubKey,skipCloseAccount:!0,createInfo:{payer:this.scope.ownerPubKey,amount:0},associatedOnly:p?!1:n.associatedOnly,checkCreateATAOwner:n.checkCreateATAOwner});g=A,h&&s.addInstruction(h)}p&&s.addInstruction({endInstructions:[Dn({owner:this.scope.ownerPubKey,payer:this.scope.ownerPubKey,tokenAccount:g,programId:Pe.TOKEN_PROGRAM_ID})],endInstructionTypes:[Y.CloseAccount]});let P;if(e.routeType==="route"){let A=e.middleToken;P=this.scope.account.getAssociatedTokenAccount(A.mint,A.isToken2022?Pe.TOKEN_2022_PROGRAM_ID:Pe.TOKEN_PROGRAM_ID)}let k=t||await this.computePoolToPoolKeys({pools:e.poolInfoList}),I=Yc({routeProgram:i,inputMint:m,swapInfo:E(N({},e),{poolInfo:[...e.poolInfoList],poolKey:k,outputMint:f}),ownerInfo:{wallet:this.scope.ownerPubKey,sourceToken:y,routeToken:P,destinationToken:g}});if(e.feeConfig!==void 0){let A=this.createTxBuilder(),h=u.amount.token.isToken2022?(0,Pe.createTransferCheckedInstruction)(y,u.amount.token.mint,e.feeConfig.feeAccount,this.scope.ownerPubKey,e.feeConfig.feeAmount.toNumber(),u.amount.token.decimals,[],Pe.TOKEN_2022_PROGRAM_ID):(0,Pe.createTransferInstruction)(y,e.feeConfig.feeAccount,this.scope.ownerPubKey,e.feeConfig.feeAmount.toNumber());A.addInstruction({instructions:[h],instructionTypes:[Y.TransferAmount]}),A.addInstruction(I);let{transactions:B}=r===0?await A.sizeCheckBuildV0():await A.sizeCheckBuild();B.length<2&&s.addInstruction({instructions:[(0,Pe.createTransferInstruction)(y,e.feeConfig.feeAccount,this.scope.ownerPubKey,e.feeConfig.feeAmount.toNumber())],instructionTypes:[Y.TransferAmount]})}return s.addInstruction(I),r===0?s.sizeCheckBuildV0({computeBudgetConfig:o,address:I.address}):s.sizeCheckBuild({computeBudgetConfig:o,address:I.address})}async swapClmmToLaunchMint({inputMint:e,inputAmount:t,fixClmmOut:n=!1,clmmPoolId:o,launchPoolId:i,priceLimit:r,slippage:a=.01,shareFeeRate:s=new Ie.default(0),shareFeeReceiver:u,launchPlatformInfo:c,slot:d,mintInfo:p,epochInfo:m,ownerInfo:f={useSOLBalance:!0},checkCreateATAOwner:y=!1,computeBudgetConfig:b,txVersion:g,blockTimestamp:P}){let k=(f==null?void 0:f.feePayer)||this.scope.ownerPubKey,I=m!=null?m:await this.scope.fetchEpochInfo(),{clmmPoolData:A,clmmComputeAmount:{maxClmmAmountIn:h,clmmAmountOut:B,remainingAccounts:S},launchPoolInfo:K,launchAuthProgramId:x,launchSwapInfo:C,launchMintProgramB:L,outAmount:O,minOutAmount:R}=await this.computeClmmToLaunchAmount({inputMint:e,inputAmount:t,fixClmmOut:n,clmmPoolId:o,launchPoolId:i,slippage:a,epochInfo:I,shareFeeRate:s,launchPlatformInfo:c,slot:d,mintInfo:p,blockTimestamp:P}),F=e.toString()===A.poolInfo.mintA.address,W=f.useSOLBalance&&A.poolInfo.mintA.address===ee.toBase58(),D=f.useSOLBalance&&A.poolInfo.mintB.address===ee.toBase58(),X={},Z;!r||r.equals(new Fe.default(0))?Z=F?xt.add(new Ie.default(1)):St.sub(new Ie.default(1)):Z=ae.priceToSqrtPriceX64(r,A.poolInfo.mintA.decimals,A.poolInfo.mintB.decimals);let H=this.createTxBuilder(k),[ne,se]=[new ye.PublicKey(A.poolInfo.mintA.address),new ye.PublicKey(A.poolInfo.mintB.address)],[J,ge]=[new ye.PublicKey(A.poolInfo.mintA.programId),new ye.PublicKey(A.poolInfo.mintB.programId)],ue=this.scope.account.getAssociatedTokenAccount(ne,J),he=this.scope.account.getAssociatedTokenAccount(se,ge);H.addInstruction({instructions:[(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,ue,this.scope.ownerPubKey,ne,J),(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,he,this.scope.ownerPubKey,se,ge)]}),(F&&W||!F&&D)&&H.addInstruction({instructions:[ye.SystemProgram.transfer({fromPubkey:this.scope.ownerPubKey,toPubkey:F?ue:he,lamports:BigInt(h.toString())}),(0,Pe.createSyncNativeInstruction)(F?ue:he)]}),X[A.poolInfo.mintA.address]=ue,X[A.poolInfo.mintB.address]=he,(!ue||!he)&&this.logAndCreateError("user do not have token account",{ownerTokenAccountA:ue,ownerTokenAccountB:he}),H.addInstruction(n?we.makeSwapBaseOutInstructions({poolInfo:A.poolInfo,poolKeys:A.poolKeys,observationId:A.computePoolInfo.observationId,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:ue,tokenAccountB:he},outputMint:F?se:ne,amountOut:B,amountInMax:h,sqrtPriceLimitX64:Z,remainingAccounts:S}):we.makeSwapBaseInInstructions({poolInfo:A.poolInfo,poolKeys:A.poolKeys,observationId:A.computePoolInfo.observationId,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:ue,tokenAccountB:he},inputMint:new ye.PublicKey(e),amountIn:t,amountOutMin:B,sqrtPriceLimitX64:Z,remainingAccounts:S}));let _e=Kr(K.mintProgramFlag),Me=this.scope.account.getAssociatedTokenAccount(K.mintA,_e),ke=X[K.mintB.toBase58()];if(H.addInstruction({instructions:[(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,Me,this.scope.ownerPubKey,K.mintA,_e)]}),!ke){let ce=K.mintB.equals(ee),{account:Le,instructionParams:Ut}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:L,mint:K.mintB,notUseTokenAccount:ce,owner:this.scope.ownerPubKey,skipCloseAccount:!ce,createInfo:ce?{payer:this.scope.ownerPubKey,amount:B}:void 0,associatedOnly:!1,checkCreateATAOwner:y});ke=Le,Ut&&H.addInstruction(Ut)}return H.addInstruction({instructions:[Ki(K.programId,this.scope.ownerPubKey,x,K.configId,K.platformId,new ye.PublicKey(i),Me,ke,K.vaultA,K.vaultB,K.mintA,K.mintB,_e,L,Tn(K.programId,K.platformId,K.mintB).publicKey,hn(K.programId,K.creator,K.mintB).publicKey,C.amountB.lt(B)?C.amountB:B,R,s,u)]}),H.addCustomComputeBudget(b),H.versionBuild({txVersion:g,extInfo:{routes:[{mint:new ye.PublicKey(e),amount:n?h:t,decimal:A.poolInfo[F?"mintA":"mintB"].decimals},{mint:F?se:ne,amount:B,decimal:A.poolInfo[F?"mintB":"mintA"].decimals},{mint:K.mintA,amount:O,decimal:K.mintDecimalsA}],outAmount:O,minOutAmount:R}})}async computeClmmToLaunchAmount({inputMint:e,inputAmount:t,fixClmmOut:n=!1,clmmPoolId:o,launchPoolId:i,slippage:r,epochInfo:a,shareFeeRate:s=new Ie.default(0),clmmPoolData:u,launchPoolInfo:c,launchPlatformInfo:d,slot:p,mintInfo:m,blockTimestamp:f}){var D,X;let y=r>0?new Fe.default(r).div(2).toDecimalPlaces(4,Fe.default.ROUND_DOWN).toNumber():r,b=u!=null?u:await this.scope.clmm.getPoolInfoFromRpc(o.toString());if(e.toString()!==b.poolInfo.mintA.address&&e.toString()!==b.poolInfo.mintB.address)throw new Error("input mint does not match clmm pool mints, please check");let g=e.toString()===b.poolInfo.mintA.address,P=b.poolInfo[g?"mintB":"mintA"],k=c;if(k||(k=await this.scope.launchpad.getRpcPoolInfo({poolId:new ye.PublicKey(i)})),P.address!==k.mintB.toBase58())throw new Error(`clmm swap mint(${P.address}) != launch pool mintB(${k.mintB.toBase58()})`);let I=n?await gt.computeAmountIn({poolInfo:b.computePoolInfo,tickarrayBitmapExtension:b.computePoolInfo.exBitmapInfo,tickArrayCache:b.tickData[o.toString()],amountOut:t,baseMint:new ye.PublicKey(b.poolInfo[g?"mintB":"mintA"].address),slippage:y,epochInfo:a!=null?a:await this.scope.fetchEpochInfo(),blockTimestamp:f}):await gt.computeAmountOutFormat({poolInfo:b.computePoolInfo,tickarrayBitmapExtension:b.computePoolInfo.exBitmapInfo,tickArrayCache:b.tickData[o.toString()],amountIn:t,tokenOut:P,slippage:y,epochInfo:a!=null?a:await this.scope.fetchEpochInfo(),blockTimestamp:f}),A=d;if(!A){let Z=await this.scope.connection.getAccountInfo(k.platformId);A=kn.decode(Z.data)}let h=m!=null?m:await this.scope.token.getTokenInfo(k.mintA),B=Yt(k.programId).publicKey,S=ro(h,a==null?void 0:a.epoch),K=As(P),x=ro(P,a==null?void 0:a.epoch),C=n?t:I.minAmountOut.amount.raw,L=vt.buyExactIn({poolInfo:k,amountB:C,protocolFeeRate:k.configInfo.tradeFeeRate,platformFeeRate:A.feeRate,curveType:k.configInfo.curveType,shareFeeRate:s,creatorFeeRate:A.creatorFeeRate,transferFeeConfigA:S,transferFeeConfigB:x,slot:p!=null?p:await this.scope.connection.getSlot()}),O=L.amountA.amount.sub((D=L.amountA.fee)!=null?D:new Ie.default(0)),R=new Fe.default(O.toString()),F=new Ie.default(1e4),W=y?new Fe.default(F.sub(new Ie.default(y*1e4)).toNumber()/F.toNumber()).clampedTo(0,1):new Fe.default(1);return{clmmPoolData:b,clmmComputeAmount:{maxClmmAmountIn:n?I.maxAmountIn.amount:t,clmmAmountOut:C,remainingAccounts:I.remainingAccounts},clmmComputeInfo:I,launchPoolInfo:k,launchAuthProgramId:B,launchMintTransferFeeConfig:S,launchMintProgramB:K,launchMintTransferFeeConfigB:x,launchSwapInfo:L,outAmount:L.amountA.amount.sub((X=L.amountA.fee)!=null?X:new Ie.default(0)),minOutAmount:new Ie.default(R.mul(W).toFixed(0))}}async swapLaunchMintToClmm({inputAmount:e,clmmPoolId:t,launchPoolId:n,priceLimit:o,slippage:i=.01,shareFeeRate:r=new Ie.default(0),shareFeeReceiver:a,ownerInfo:s={useSOLBalance:!0},checkCreateATAOwner:u=!1,computeBudgetConfig:c,txVersion:d,blockTimestamp:p}){let m=(s==null?void 0:s.feePayer)||this.scope.ownerPubKey,f=await this.scope.fetchEpochInfo(),{clmmPoolData:y,clmmComputeAmount:{remainingAccounts:b},launchPoolInfo:g,launchAuthProgramId:P,launchSwapInfo:k,launchMintProgramB:I,minLaunchOutAmount:A,outAmount:h,minOutAmount:B}=await this.computeLaunchToClmmAmount({inputAmount:e,clmmPoolId:t,launchPoolId:n,slippage:i,epochInfo:f,shareFeeRate:r,blockTimestamp:p}),S=this.createTxBuilder(m),K={},x=Kr(g.mintProgramFlag),{account:C}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:x,mint:g.mintA,notUseTokenAccount:!1,owner:this.scope.ownerPubKey,skipCloseAccount:!0,createInfo:void 0,associatedOnly:!0,checkCreateATAOwner:u});if(!C)throw new Error(`do not have launch mint(${g.mintA.toString()}) token account`);let L=g.mintB.equals(ee),{account:O,instructionParams:R}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:I,mint:g.mintB,notUseTokenAccount:L,owner:this.scope.ownerPubKey,skipCloseAccount:!L,createInfo:{payer:this.scope.ownerPubKey,amount:0},associatedOnly:!1,checkCreateATAOwner:u});if(R&&S.addInstruction(R),!O)throw new Error(`do not have launch mint(${g.mintA.toString()}) token account`);K[g.mintB.toBase58()]=O,S.addInstruction({instructions:[Sr(g.programId,this.scope.ownerPubKey,P,g.configId,g.platformId,new ye.PublicKey(n),C,O,g.vaultA,g.vaultB,g.mintA,g.mintB,x,I,Tn(g.programId,g.platformId,g.mintB).publicKey,hn(g.programId,g.creator,g.mintB).publicKey,k.amountA.amount.lt(e)?k.amountA.amount:e,A,r,a)]});let F=g.mintB.toString()===y.poolInfo.mintA.address,W=s.useSOLBalance&&y.poolInfo.mintA.address===ee.toBase58(),D=s.useSOLBalance&&y.poolInfo.mintB.address===ee.toBase58(),X;!o||o.equals(new Fe.default(0))?X=F?xt.add(new Ie.default(1)):St.sub(new Ie.default(1)):X=ae.priceToSqrtPriceX64(o,y.poolInfo.mintA.decimals,y.poolInfo.mintB.decimals);let[Z,H]=[new ye.PublicKey(y.poolInfo.mintA.address),new ye.PublicKey(y.poolInfo.mintB.address)],[ne,se]=[new ye.PublicKey(y.poolInfo.mintA.programId),new ye.PublicKey(y.poolInfo.mintB.programId)],J=W?void 0:this.scope.account.getAssociatedTokenAccount(Z,ne),ge=D?void 0:this.scope.account.getAssociatedTokenAccount(H,se);if(!J){let{account:ue,instructionParams:he}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:ne,mint:Z,notUseTokenAccount:!0,owner:this.scope.ownerPubKey,skipCloseAccount:!1,createInfo:{payer:s.feePayer||this.scope.ownerPubKey,amount:F?e:0},associatedOnly:!1,checkCreateATAOwner:u});J=ue,he&&S.addInstruction(he)}if(!ge){let{account:ue,instructionParams:he}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:se,mint:H,notUseTokenAccount:!0,owner:this.scope.ownerPubKey,skipCloseAccount:!1,createInfo:{payer:s.feePayer||this.scope.ownerPubKey,amount:F?0:e},associatedOnly:!1,checkCreateATAOwner:u});ge=ue,he&&S.addInstruction(he)}return K[y.poolInfo.mintA.address]=J,K[y.poolInfo.mintB.address]=ge,(!J||!ge)&&this.logAndCreateError("user do not have token account",{ownerTokenAccountA:J,ownerTokenAccountB:ge}),S.addInstruction(we.makeSwapBaseInInstructions({poolInfo:y.poolInfo,poolKeys:y.poolKeys,observationId:y.computePoolInfo.observationId,ownerInfo:{wallet:this.scope.ownerPubKey,tokenAccountA:J,tokenAccountB:ge},inputMint:new ye.PublicKey(y.poolKeys[F?"mintA":"mintB"].address),amountIn:A,amountOutMin:B,sqrtPriceLimitX64:X,remainingAccounts:b})),S.addCustomComputeBudget(c),S.versionBuild({txVersion:d,extInfo:{routes:[{mint:g.mintA,amount:e,decimal:g.mintDecimalsA},{mint:g.mintB,amount:A,decimal:g.mintDecimalsB},{mint:new ye.PublicKey(y.poolKeys[F?"mintB":"mintA"].address),amount:h,decimal:y.poolKeys[F?"mintB":"mintA"].decimals}],outAmount:h,minOutAmount:B}})}async computeLaunchToClmmAmount({inputAmount:e,clmmPoolId:t,launchPoolId:n,slippage:o,epochInfo:i,shareFeeRate:r=new Ie.default(0),clmmPoolData:a,launchPoolInfo:s,launchPlatformInfo:u,blockTimestamp:c}){let d=o>0?new Fe.default(o).div(2).toDecimalPlaces(4,Fe.default.ROUND_DOWN).toNumber():o,p=s;p||(p=await this.scope.launchpad.getRpcPoolInfo({poolId:new ye.PublicKey(n)}));let m=p.mintB,f=a!=null?a:await this.scope.clmm.getPoolInfoFromRpc(t.toString());if(m.toString()!==f.poolInfo.mintA.address&&m.toString()!==f.poolInfo.mintB.address)throw new Error("input mint does not match clmm pool mints, please check");let y=m.toString()===f.poolInfo.mintA.address,b=f.poolInfo[y?"mintB":"mintA"],g=f.poolInfo[y?"mintA":"mintB"],P=u;if(!P){let F=await this.scope.connection.getAccountInfo(p.platformId);P=kn.decode(F.data)}let k=await this.scope.token.getTokenInfo(p.mintA),I=Yt(p.programId).publicKey,A=ro(k,i==null?void 0:i.epoch),h=As(g),B=ro(g,i==null?void 0:i.epoch),S=vt.sellExactIn({poolInfo:p,amountA:e,protocolFeeRate:p.configInfo.tradeFeeRate,platformFeeRate:P.feeRate,curveType:p.configInfo.curveType,shareFeeRate:r,creatorFeeRate:P.creatorFeeRate,transferFeeConfigA:A,transferFeeConfigB:B,slot:await this.scope.connection.getSlot()}),K=S.amountB,x=new Fe.default(K.toString()),C=new Ie.default(1e4),L=d?new Fe.default(C.sub(new Ie.default(d*1e4)).toNumber()/C.toNumber()).clampedTo(0,1):new Fe.default(1),O=new Ie.default(x.mul(L).toFixed(0)),R=await gt.computeAmountOutFormat({poolInfo:f.computePoolInfo,tickarrayBitmapExtension:f.computePoolInfo.exBitmapInfo,tickArrayCache:f.tickData[t.toString()],amountIn:O,tokenOut:b,slippage:d,epochInfo:i!=null?i:await this.scope.fetchEpochInfo(),blockTimestamp:c});return{clmmPoolData:f,clmmComputeAmount:R,launchPoolInfo:p,launchAuthProgramId:I,launchMintTransferFeeConfig:A,launchMintProgramB:h,launchMintTransferFeeConfigB:B,launchSwapInfo:S,minLaunchOutAmount:O,outAmount:R.amountOut.amount.raw,minOutAmount:R.minAmountOut.amount.raw}}async swapCpmmToLaunchMint({inputMint:e,inputAmount:t,cpmmPoolId:n,launchPoolId:o,poolKeys:i,slippage:r=.01,shareFeeRate:a=new Ie.default(0),shareFeeReceiver:s,launchPlatformInfo:u,slot:c,mintInfo:d,epochInfo:p,ownerInfo:m={useSOLBalance:!0},checkCreateATAOwner:f=!1,computeBudgetConfig:y,txVersion:b}){let g=(m==null?void 0:m.feePayer)||this.scope.ownerPubKey,P=p!=null?p:await this.scope.fetchEpochInfo(),{computePoolInfo:k,poolKeys:I}=await this.scope.cpmm.getPoolInfoFromRpc(n.toString()),{cpmmComputInfo:A,cpmmPoolData:h,launchPoolInfo:B,launchAuthProgramId:S,launchSwapInfo:K,launchMintProgramB:x,outAmount:C,minOutAmount:L}=await this.computeCpmmToLaunchAmount({inputMint:e,inputAmount:t,cpmmPoolId:n,cpmmPoolData:k,launchPoolId:o,slippage:r,epochInfo:P,shareFeeRate:a,launchPlatformInfo:u,slot:c,mintInfo:d}),O=e.toString()===h.mintA.address,R=m.useSOLBalance&&h.mintA.address===ee.toBase58(),F=m.useSOLBalance&&h.mintB.address===ee.toBase58(),W={},D=this.createTxBuilder(g),[X,Z]=[new ye.PublicKey(h.mintA.address),new ye.PublicKey(h.mintB.address)],[H,ne]=[new ye.PublicKey(h.mintA.programId),new ye.PublicKey(h.mintB.programId)],se=this.scope.account.getAssociatedTokenAccount(X,H),J=this.scope.account.getAssociatedTokenAccount(Z,ne);D.addInstruction({instructions:[(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,se,this.scope.ownerPubKey,X,H),(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,J,this.scope.ownerPubKey,Z,ne)]}),(O&&R||!O&&F)&&D.addInstruction({instructions:[ye.SystemProgram.transfer({fromPubkey:this.scope.ownerPubKey,toPubkey:O?se:J,lamports:BigInt(A.amountIn.toString())}),(0,Pe.createSyncNativeInstruction)(O?se:J)]}),W[h.mintA.address]=se,W[h.mintB.address]=J,(!se||!J)&&this.logAndCreateError("user do not have token account",{ownerTokenAccountA:se,ownerTokenAccountB:J});let ge=i!=null?i:I;D.addInstruction({instructions:[qo(h.programId,this.scope.ownerPubKey,new ye.PublicKey(ge.authority),new ye.PublicKey(ge.config.id),h.id,O?se:J,O?J:se,new ye.PublicKey(ge.vault[O?"A":"B"]),new ye.PublicKey(ge.vault[O?"B":"A"]),new ye.PublicKey(O?H:ne!=null?ne:Pe.TOKEN_PROGRAM_ID),new ye.PublicKey(O?ne:H!=null?H:Pe.TOKEN_PROGRAM_ID),O?X:Z,O?Z:X,Po(h.programId,h.id).publicKey,t,A.swapResult.outputAmount)]});let ue=Kr(B.mintProgramFlag),he=this.scope.account.getAssociatedTokenAccount(B.mintA,ue),_e=W[B.mintB.toBase58()];if(D.addInstruction({instructions:[(0,Pe.createAssociatedTokenAccountIdempotentInstruction)(this.scope.ownerPubKey,he,this.scope.ownerPubKey,B.mintA,ue)]}),!_e){let Me=B.mintB.equals(ee),{account:ke,instructionParams:ce}=await this.scope.account.getOrCreateTokenAccount({tokenProgram:x,mint:B.mintB,notUseTokenAccount:Me,owner:this.scope.ownerPubKey,skipCloseAccount:!Me,createInfo:Me?{payer:this.scope.ownerPubKey,amount:A.minAmountOut}:void 0,associatedOnly:!1,checkCreateATAOwner:f});_e=ke,ce&&D.addInstruction(ce)}return D.addInstruction({instructions:[Ki(B.programId,this.scope.ownerPubKey,S,B.configId,B.platformId,new ye.PublicKey(o),he,_e,B.vaultA,B.vaultB,B.mintA,B.mintB,ue,x,Tn(B.programId,B.platformId,B.mintB).publicKey,hn(B.programId,B.creator,B.mintB).publicKey,K.amountB.lt(A.minAmountOut)?K.amountB:A.minAmountOut,L,a,s)]}),D.addCustomComputeBudget(y),D.versionBuild({txVersion:b,extInfo:{routes:[{mint:new ye.PublicKey(e),amount:t,decimal:h[O?"mintDecimalA":"mintDecimalB"]},{mint:O?Z:X,amount:A.minAmountOut,decimal:h[O?"mintB":"mintA"].decimals},{mint:B.mintA,amount:C,decimal:B.mintDecimalsA}],outAmount:C,minOutAmount:L}})}async computeCpmmToLaunchAmount({inputMint:e,inputAmount:t,cpmmPoolId:n,launchPoolId:o,slippage:i,epochInfo:r,shareFeeRate:a=new Ie.default(0),cpmmPoolData:s,launchPoolInfo:u,launchPlatformInfo:c,slot:d,mintInfo:p}){var F,W;let m=i>0?new Fe.default(i).div(2).toDecimalPlaces(4,Fe.default.ROUND_DOWN).toNumber():i,f=s!=null?s:(await this.scope.cpmm.getPoolInfoFromRpc(n.toString())).computePoolInfo;if(e.toString()!==f.mintA.address&&e.toString()!==f.mintB.address)throw new Error("input mint does not match clmm pool mints, please check");let y=e.toString()===f.mintA.address,b=f[y?"mintB":"mintA"],g=u;if(g||(g=await this.scope.launchpad.getRpcPoolInfo({poolId:new ye.PublicKey(o)})),b.address!==g.mintB.toBase58())throw new Error(`clmm swap mint(${b.address}) != launch pool mintB(${g.mintB.toBase58()})`);let P=c;if(!P){let D=await this.scope.connection.getAccountInfo(g.platformId);P=kn.decode(D.data)}let k=p!=null?p:await this.scope.token.getTokenInfo(g.mintA),I=Yt(g.programId).publicKey,A=ro(k,r==null?void 0:r.epoch),h=As(b),B=ro(b,r==null?void 0:r.epoch),S=await this.scope.cpmm.computeSwapAmount({pool:f,amountIn:t,outputMint:new ye.PublicKey(b.address),slippage:m}),K=S.minAmountOut,x=vt.buyExactIn({poolInfo:g,amountB:K,protocolFeeRate:g.configInfo.tradeFeeRate,platformFeeRate:P.feeRate,curveType:g.configInfo.curveType,shareFeeRate:a,creatorFeeRate:P.creatorFeeRate,transferFeeConfigA:A,transferFeeConfigB:B,slot:d!=null?d:await this.scope.connection.getSlot()}),C=x.amountA.amount.sub((F=x.amountA.fee)!=null?F:new Ie.default(0)),L=new Fe.default(C.toString()),O=new Ie.default(1e4),R=m?new Fe.default(O.sub(new Ie.default(m*1e4)).toNumber()/O.toNumber()).clampedTo(0,1):new Fe.default(1);return{cpmmPoolData:f,cpmmComputInfo:S,launchPoolInfo:g,launchAuthProgramId:I,launchMintTransferFeeConfig:A,launchMintProgramB:h,launchMintTransferFeeConfigB:B,launchSwapInfo:x,outAmount:x.amountA.amount.sub((W=x.amountA.fee)!=null?W:new Ie.default(0)),minOutAmount:new Ie.default(L.mul(R).toFixed(0))}}async computeCpClToLaunchAmount({inputMint:e,inputAmount:t,clmmPoolId:n,cpmmPoolId:o,launchPoolId:i,slippage:r,epochInfo:a,shareFeeRate:s=new Ie.default(0),cpmmPoolData:u,clmmPoolData:c,launchPoolInfo:d,launchPlatformInfo:p,slot:m,mintInfo:f,blockTimestamp:y}){var J,ge;let b=r>0?new Fe.default(r).div(2).toDecimalPlaces(4,Fe.default.ROUND_DOWN).toNumber():r,g=c!=null?c:await this.scope.clmm.getPoolInfoFromRpc(n.toString());if(e.toString()!==g.poolInfo.mintA.address&&e.toString()!==g.poolInfo.mintB.address)throw new Error("input mint does not match clmm pool mints, please check");let P=e.toString()===g.poolInfo.mintA.address,k=g.poolInfo[P?"mintB":"mintA"],I=d;if(I||(I=await this.scope.launchpad.getRpcPoolInfo({poolId:new ye.PublicKey(i)})),k.address!==I.mintB.toBase58())throw new Error(`clmm swap mint(${k.address}) != launch pool mintB(${I.mintB.toBase58()})`);let A=p;if(!A){let ue=await this.scope.connection.getAccountInfo(I.platformId);A=kn.decode(ue.data)}let h=f!=null?f:await this.scope.token.getTokenInfo(I.mintA),B=Yt(I.programId).publicKey,S=ro(h,a==null?void 0:a.epoch),K=As(k),x=ro(k,a==null?void 0:a.epoch),C=await gt.computeAmountOutFormat({poolInfo:g.computePoolInfo,tickArrayCache:g.tickData[n.toString()],amountIn:t,tokenOut:k,slippage:b,epochInfo:a!=null?a:await this.scope.fetchEpochInfo(),blockTimestamp:y,tickarrayBitmapExtension:g.computePoolInfo.exBitmapInfo}),L=u!=null?u:(await this.scope.cpmm.getPoolInfoFromRpc(o.toString())).computePoolInfo,O=await this.scope.cpmm.computeSwapAmount({pool:L,amountIn:t,outputMint:new ye.PublicKey(k.address),slippage:b}),[R,F]=[C.minAmountOut.amount.raw,O.minAmountOut],W=R.gte(F)?"clmm":"cpmm",D=R.gte(F)?R:F,X=vt.buyExactIn({poolInfo:I,amountB:D,protocolFeeRate:I.configInfo.tradeFeeRate,platformFeeRate:A.feeRate,curveType:I.configInfo.curveType,shareFeeRate:s,creatorFeeRate:A.creatorFeeRate,transferFeeConfigA:S,transferFeeConfigB:x,slot:m!=null?m:await this.scope.connection.getSlot()}),Z=X.amountA.amount.sub((J=X.amountA.fee)!=null?J:new Ie.default(0)),H=new Fe.default(Z.toString()),ne=new Ie.default(1e4),se=b?new Fe.default(ne.sub(new Ie.default(b*1e4)).toNumber()/ne.toNumber()).clampedTo(0,1):new Fe.default(1);return{clmmPoolData:g,clmmComputeAmount:{maxClmmAmountIn:t,clmmAmountOut:D,remainingAccounts:C.remainingAccounts},clmmComputeInfo:C,cpmmComputInfo:O,swapPoolType:W,launchPoolInfo:I,launchAuthProgramId:B,launchMintTransferFeeConfig:S,launchMintProgramB:K,launchMintTransferFeeConfigB:x,launchSwapInfo:X,outAmount:X.amountA.amount.sub((ge=X.amountA.fee)!=null?ge:new Ie.default(0)),minOutAmount:new Ie.default(H.mul(se).toFixed(0))}}async fetchRoutePoolBasicInfo(e){let{amm:t=Gi,clmm:n=Vn,cpmm:o=Qn}=e||{},i=await this.scope.connection.getProgramAccounts(t,{dataSlice:{offset:wi.offsetOf("baseMint"),length:64}}),r=v([M("baseMint"),M("quoteMint")]),a=i.map(m=>({id:m.pubkey,version:4,mintA:r.decode(m.account.data).baseMint,mintB:r.decode(m.account.data).quoteMint})),s=v([M("mintA"),M("mintB")]),c=(await this.scope.connection.getProgramAccounts(n,{filters:[{dataSize:mo.span}],dataSlice:{offset:mo.offsetOf("mintA"),length:64}})).map(m=>{let f=s.decode(m.account.data);return{id:m.pubkey,version:6,mintA:f.mintA,mintB:f.mintB}}),p=(await this.scope.connection.getProgramAccounts(o,{dataSlice:{offset:Br.offsetOf("mintA"),length:64}})).map(m=>{let f=s.decode(m.account.data);return{id:m.pubkey,version:7,mintA:f.mintA,mintB:f.mintB}});return{clmmPools:c,ammPools:a,cpmmPools:p}}getAllRoute({inputMint:e,outputMint:t,clmmPools:n,ammPools:o,cpmmPools:i}){e=e.toString()===ye.PublicKey.default.toString()?ee:e,t=t.toString()===ye.PublicKey.default.toString()?ee:t;let r={},a={},s={},u=[],c={};for(let p of n!=null?n:[]){if((p.mintA.equals(e)&&p.mintB.equals(t)||p.mintA.equals(t)&&p.mintB.equals(e))&&(u.push(p),a[p.id.toString()]=p),p.mintA.equals(e)){let m=p.mintB.toString();c[m]===void 0&&(c[m]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[m].in.push(p)}if(p.mintB.equals(e)){let m=p.mintA.toString();c[m]===void 0&&(c[m]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[m].in.push(p)}if(p.mintA.equals(t)){let m=p.mintB.toString();c[m]===void 0&&(c[m]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[m].out.push(p)}if(p.mintB.equals(t)){let m=p.mintA.toString();c[m]===void 0&&(c[m]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[m].out.push(p)}}let d=[];for(let p of o)(p.mintA.equals(e)&&p.mintB.equals(t)||p.mintA.equals(t)&&p.mintB.equals(e))&&(u.push(p),r[p.id.toBase58()]=p,d.push(p)),p.mintA.equals(e)&&(c[p.mintB.toBase58()]===void 0&&(c[p.mintB.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p.mintB.toBase58()].in.push(p)),p.mintB.equals(e)&&(c[p.mintA.toBase58()]===void 0&&(c[p.mintA.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p.mintA.toBase58()].in.push(p)),p.mintA.equals(t)&&(c[p.mintB.toBase58()]===void 0&&(c[p.mintB.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p.mintB.toBase58()].out.push(p)),p.mintB.equals(t)&&(c[p.mintA.toBase58()]===void 0&&(c[p.mintA.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p.mintA.toBase58()].out.push(p));for(let p of i)(p.mintA.equals(e)&&p.mintB.equals(t)||p.mintA.equals(t)&&p.mintB.equals(e))&&(u.push(p),s[p.id.toBase58()]=p),p.mintA.equals(e)&&(c[p.mintB.toBase58()]===void 0&&(c[p.mintB.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p.mintB.toBase58()].in.push(p)),p.mintB.equals(e)&&(c[p.mintA.toBase58()]===void 0&&(c[p.mintA.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p.mintA.toBase58()].in.push(p)),p.mintA.equals(t)&&(c[p.mintB.toBase58()]===void 0&&(c[p.mintB.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p.mintB.toBase58()].out.push(p)),p.mintB.equals(t)&&(c[p.mintA.toBase58()]===void 0&&(c[p.mintA.toBase58()]={mintProgram:Pe.TOKEN_PROGRAM_ID,in:[],out:[],mDecimals:0}),c[p.mintA.toBase58()].out.push(p));for(let p of Object.keys(c)){if(c[p].in.length===1&&c[p].out.length===1&&c[p].in[0].id.equals(c[p].out[0].id)){delete c[p];continue}if(c[p].in.length===0||c[p].out.length===0){delete c[p];continue}let m=c[p];for(let f of m.in)for(let y of m.out)f.version===6&&a[f.id.toString()]===void 0?a[f.id.toString()]=f:f.version===7&&s[f.id.toString()]===void 0?s[f.id.toString()]=f:(f.version===4||f.version===5)&&r[f.id.toString()]===void 0&&(r[f.id.toString()]=f),y.version===6&&a[y.id.toString()]===void 0?a[y.id.toString()]=y:y.version===7&&s[y.id.toString()]===void 0?s[y.id.toString()]=y:(y.version===4||y.version===5)&&r[y.id.toString()]===void 0&&(r[y.id.toString()]=y)}return{directPath:u,addLiquidityPools:d,routePathDict:c,needSimulate:Object.values(r),needTickArray:Object.values(a),cpmmPoolList:Object.values(s)}}async fetchSwapRoutesData({routes:e,inputMint:t,outputMint:n}){let o=new Set([...e.needTickArray.map(y=>[y.mintA.toBase58(),y.mintB.toBase58()]).flat(),t.toString(),n.toString()]);console.log("fetching amm pools info, total: ",e.needSimulate.length);let i=await this.scope.liquidity.getRpcPoolInfos(e.needSimulate.map(y=>y.id)),r=wr(i),a={};Object.values(r).forEach(y=>{o.delete(y.mintA.address),a[y.mintA.address]={address:new ye.PublicKey(y.mintA.address),programId:Pe.TOKEN_PROGRAM_ID,mintAuthority:null,supply:BigInt(0),decimals:y.mintA.decimals,isInitialized:!0,freezeAuthority:null,tlvData:Buffer.from("0","hex"),feeConfig:void 0},o.delete(y.mintB.address),a[y.mintB.address]={address:new ye.PublicKey(y.mintB.address),programId:Pe.TOKEN_PROGRAM_ID,mintAuthority:null,supply:BigInt(0),decimals:y.mintB.decimals,isInitialized:!0,freezeAuthority:null,tlvData:Buffer.from("0","hex"),feeConfig:void 0}}),console.log("fetching cpmm pools info, total: ",e.cpmmPoolList.length);let s=await this.scope.cpmm.getRpcPoolInfos(e.cpmmPoolList.map(y=>y.id.toBase58()),!0);Object.values(s).forEach(y=>{let[b,g]=[y.mintA.toBase58(),y.mintB.toBase58()];y.mintProgramA.equals(Pe.TOKEN_PROGRAM_ID)?(o.delete(b),a[b]={address:y.mintA,programId:y.mintProgramA,mintAuthority:null,supply:BigInt(0),decimals:y.mintDecimalA,isInitialized:!0,freezeAuthority:null,tlvData:Buffer.from("0","hex"),feeConfig:void 0}):o.add(b),y.mintProgramB.equals(Pe.TOKEN_PROGRAM_ID)?(o.delete(g),a[g]={address:y.mintB,programId:y.mintProgramB,mintAuthority:null,supply:BigInt(0),decimals:y.mintDecimalB,isInitialized:!0,freezeAuthority:null,tlvData:Buffer.from("0","hex"),feeConfig:void 0}):o.add(g)}),console.log("fetching mints info, total: ",o.size);let u=await ho({connection:this.scope.connection,mints:Array.from(o).map(y=>new ye.PublicKey(y))});a=N(N({},a),u);let c=this.scope.cpmm.toComputePoolInfos({pools:s,mintInfos:a});console.log("fetching clmm pools info, total:",e.needTickArray.length);let d=await this.scope.clmm.getRpcClmmPoolInfos({poolIds:e.needTickArray.map(y=>y.id)}),{computeClmmPoolInfo:p,computePoolTickData:m}=await this.scope.clmm.getComputeClmmPoolInfos({clmmPoolsRpcInfo:d,mintInfos:a}),f=Object.keys(e.routePathDict).reduce((y,b)=>E(N({},y),{[b]:E(N({},e.routePathDict[b]),{mintProgram:a[b].programId,mDecimals:a[b].decimals,in:e.routePathDict[b].in.map(g=>r[g.id.toBase58()]||p[g.id.toBase58()]||c[g.id.toBase58()]),out:e.routePathDict[b].out.map(g=>r[g.id.toBase58()]||p[g.id.toBase58()]||c[g.id.toBase58()])})}),{});return{mintInfos:a,ammPoolsRpcInfo:i,ammSimulateCache:r,clmmPoolsRpcInfo:d,computeClmmPoolInfo:p,computePoolTickData:m,computeCpmmData:c,routePathDict:f}}getAllRouteComputeAmountOut({inputTokenAmount:e,outputToken:t,directPath:n,routePathDict:o,simulateCache:i,tickCache:r,slippage:a,chainTime:s,epochInfo:u,feeConfig:c,blockTimestamp:d}){var P,k,I,A,h,B,S,K,x;let p=c===void 0?new Ie.default(0):e.raw.mul(new Ie.default(c.feeBps.toNumber())).div(new Ie.default(1e4)),m=e.raw.sub(p),f=new Ee(e.token,m),y=c===void 0?void 0:{feeAmount:p,feeAccount:c.feeAccount},b=E(N({},t),{address:Vt(t.address).toString()}),g=[];for(let C of n)try{g.push(E(N({},this.computeAmountOut({itemPool:C,tickCache:r,simulateCache:i,chainTime:s,epochInfo:u,slippage:a,outputToken:b,amountIn:f,blockTimestamp:d})),{feeConfig:y}))}catch(L){this.logDebug("direct error",C.version,C.id.toString(),L.message)}this.logDebug("direct done");for(let[C,L]of Object.entries(o)){let O={chainId:101,address:C,programId:L.mintProgram.toBase58(),logoURI:"",symbol:"",name:"",decimals:L.mDecimals,tags:[],extensions:{}},R=L.in.map(W=>{try{return{pool:W,data:this.computeAmountOut({itemPool:W,tickCache:r,simulateCache:i,chainTime:s,epochInfo:u,slippage:a,outputToken:O,amountIn:f,blockTimestamp:d})}}catch(D){this.logDebug("route in error",W.version,W.id.toString(),D.message);return}}).sort((W,D)=>{var H,ne,se,J;let X=W===void 0?_t:W.data.amountOut.amount.raw.sub((ne=(H=W.data.amountOut.fee)==null?void 0:H.raw)!=null?ne:_t),Z=D===void 0?_t:D.data.amountOut.amount.raw.sub((J=(se=D.data.amountOut.fee)==null?void 0:se.raw)!=null?J:_t);return X.lt(Z)?1:-1})[0];if(R===void 0)continue;let F=new Ee(oi(O),R.data.amountOut.amount.raw.sub((k=(P=R.data.amountOut.fee)==null?void 0:P.raw)!=null?k:_t));for(let W of L.out)try{let D=this.computeAmountOut({itemPool:W,tickCache:r,simulateCache:i,chainTime:s,epochInfo:u,slippage:a,outputToken:b,amountIn:F,blockTimestamp:d});g.push(E(N({},D),{allTrade:!!(R.data.allTrade&&D.allTrade),amountIn:R.data.amountIn,amountOut:D.amountOut,minAmountOut:D.minAmountOut,currentPrice:void 0,executionPrice:new Fe.default(new Zt({baseToken:R.data.amountIn.amount.token,denominator:R.data.amountIn.amount.raw,quoteToken:D.amountOut.amount.token,numerator:D.amountOut.amount.raw.sub((A=(I=D.amountOut.fee)==null?void 0:I.raw)!=null?A:_t)}).toFixed()),priceImpact:new Fe.default(R.data.priceImpact.add(D.priceImpact).toFixed()),fee:[R.data.fee[0],D.fee[0]],routeType:"route",poolInfoList:[R.pool,W],remainingAccounts:[R.data.remainingAccounts[0],D.remainingAccounts[0]],minMiddleAmountFee:(h=D.amountOut.fee)!=null&&h.raw?new Ee(R.data.amountOut.amount.token,((S=(B=R.data.amountOut.fee)==null?void 0:B.raw)!=null?S:_t).add((x=(K=D.amountOut.fee)==null?void 0:K.raw)!=null?x:_t)):void 0,middleToken:R.data.amountOut.amount.token,poolReady:R.data.poolReady&&D.poolReady,poolType:[R.data.poolType,D.poolType],feeConfig:y,expirationTime:Zn(R.data.expirationTime,D.expirationTime)}))}catch(D){this.logDebug("route out error",W.version,W.id.toString(),D.message)}}return g.filter(C=>(C.allTrade||this.logDebug(`pool ${C.poolInfoList.map(L=>L.id.toString()).join(",")} filter out since not all trade`),C.allTrade)).sort((C,L)=>C.amountOut.amount.raw.sub(L.amountOut.amount.raw).gt(_t)?-1:1)}getAllRouteComputeAmountIn({outputTokenAmount:e,directPath:t,routePathDict:n,simulateCache:o,tickCache:i,slippage:r,chainTime:a,epochInfo:s,blockTimestamp:u,feeConfig:c}){var m,f,y,b,g,P,k,I,A;let d=At({address:Vt(e.token.mint).toBase58(),decimals:e.token.decimals,programId:e.token.isToken2022?Pe.TOKEN_2022_PROGRAM_ID.toBase58():Pe.TOKEN_PROGRAM_ID.toBase58(),extensions:{}}),p=[];for(let h of t)try{let B=this.computeAmountIn({itemPool:h,tickCache:i,simulateCache:o,chainTime:a,epochInfo:s,slippage:r,outputToken:d,amountOut:e.raw,blockTimestamp:u}),S=c===void 0?new Ie.default(0):B.amountIn.amount.raw.mul(new Ie.default(c.feeBps.toNumber())).div(new Ie.default(1e4));p.push(E(N({},B),{feeConfig:c===void 0?void 0:{feeAmount:S,feeAccount:c.feeAccount}}))}catch(B){this.logDebug("direct error",h.version,h.id.toString(),B.message)}this.logDebug("direct done");for(let[h,B]of Object.entries(n)){let S={chainId:101,address:h,programId:B.mintProgram.toBase58(),logoURI:"",symbol:"",name:"",decimals:B.mDecimals,tags:[],extensions:{}},K=B.out.map(C=>{try{return{pool:C,data:this.computeAmountIn({itemPool:C,tickCache:i,simulateCache:o,chainTime:a,epochInfo:s,slippage:r,outputToken:d,amountOut:e.raw,blockTimestamp:u})}}catch(L){this.logDebug("route in error",C.version,C.id.toString(),L.message);return}}).sort((C,L)=>{var F,W,D,X;let O=C===void 0?_t:C.data.amountIn.amount.raw.add((W=(F=C.data.amountIn.fee)==null?void 0:F.raw)!=null?W:_t),R=L===void 0?_t:L.data.amountIn.amount.raw.add((X=(D=L.data.amountIn.fee)==null?void 0:D.raw)!=null?X:_t);return O.lt(R)?-1:1})[0];if(K===void 0)continue;let x=new Ee(oi(S),K.data.amountIn.amount.raw.add((f=(m=K.data.amountIn.fee)==null?void 0:m.raw)!=null?f:_t));for(let C of B.in)try{let L=this.computeAmountIn({itemPool:C,tickCache:i,simulateCache:o,chainTime:a,epochInfo:s,slippage:r,outputToken:S,amountOut:x.raw,blockTimestamp:u}),O=c===void 0?new Ie.default(0):L.amountIn.amount.raw.mul(new Ie.default(c.feeBps.toNumber())).div(new Ie.default(1e4));p.push(E(N({},L),{allTrade:!!(L.allTrade&&K.data.allTrade),amountIn:L.amountIn,amountOut:K.data.amountOut,maxAmountIn:L.maxAmountIn,currentPrice:void 0,executionPrice:new Fe.default(new Zt({baseToken:K.data.amountIn.amount.token,denominator:K.data.amountIn.amount.raw,quoteToken:L.amountOut.amount.token,numerator:L.amountOut.amount.raw.sub((b=(y=L.amountOut.fee)==null?void 0:y.raw)!=null?b:_t)}).toFixed()),priceImpact:new Fe.default(K.data.priceImpact.add(L.priceImpact).toFixed()),fee:[L.fee[0],K.data.fee[0]],routeType:"route",poolInfoList:[K.pool,C],remainingAccounts:[K.data.remainingAccounts[0],L.remainingAccounts[0]],minMiddleAmountFee:(g=L.amountOut.fee)!=null&&g.raw?new Ee(K.data.amountOut.amount.token,((k=(P=K.data.amountOut.fee)==null?void 0:P.raw)!=null?k:_t).add((A=(I=L.amountOut.fee)==null?void 0:I.raw)!=null?A:_t)):void 0,middleToken:K.data.amountOut.amount.token,poolReady:K.data.poolReady&&L.poolReady,poolType:[K.data.poolType,L.poolType],feeConfig:c===void 0?void 0:{feeAmount:O,feeAccount:c.feeAccount},expirationTime:Zn(K.data.expirationTime,L.expirationTime)}))}catch(L){this.logDebug("route out error",C.version,C.id.toString(),L.message)}}return p.filter(h=>(h.allTrade||this.logDebug(`pool ${h.poolInfoList.map(B=>B.id.toString()).join(",")} filter out since not all trade`),h.allTrade)).sort((h,B)=>B.amountIn.amount.raw.sub(h.amountIn.amount.raw).gt(_t)?-1:1)}computeAmountOut({itemPool:e,tickCache:t,simulateCache:n,chainTime:o,epochInfo:i,slippage:r,outputToken:a,amountIn:s,blockTimestamp:u}){if(e.version===6){let{allTrade:c,realAmountIn:d,amountOut:p,minAmountOut:m,expirationTime:f,currentPrice:y,executionPrice:b,priceImpact:g,fee:P,remainingAccounts:k,executionPriceX64:I}=gt.computeAmountOutFormat({poolInfo:e,tickarrayBitmapExtension:e.exBitmapInfo,tickArrayCache:t[e.id.toString()],amountIn:s.raw,tokenOut:a,slippage:r,epochInfo:i,catchLiquidityInsufficient:!0,blockTimestamp:u});return{allTrade:c,amountIn:d,amountOut:p,minAmountOut:m,currentPrice:new Fe.default(y.toFixed()),executionPrice:new Fe.default(b.toFixed()),priceImpact:new Fe.default(g.toFixed()),fee:[P],remainingAccounts:[k],routeType:"amm",poolInfoList:[e],poolReady:e.startTime<o,poolType:"CLMM",slippage:r,clmmExPriceX64:[I],expirationTime:Zn(d.expirationTime,f)}}else if(e.version===7){let{allTrade:c,executionPrice:d,amountOut:p,minAmountOut:m,priceImpact:f,fee:y}=this.scope.cpmm.computeSwapAmount({pool:e,outputMint:a.address,amountIn:s.raw,slippage:r});return{allTrade:c,amountIn:{amount:s,fee:void 0,expirationTime:void 0},amountOut:{amount:yt(E(N({},a),{amount:p})),fee:void 0,expirationTime:void 0},minAmountOut:{amount:yt(E(N({},a),{amount:m})),fee:void 0,expirationTime:void 0},currentPrice:e.poolPrice,executionPrice:d,priceImpact:f,fee:[new Ee(s.token,y)],remainingAccounts:[],routeType:"amm",poolInfoList:[e],poolReady:e.openTime.toNumber()<o,poolType:"CPMM",slippage:r,clmmExPriceX64:[void 0],expirationTime:void 0}}else{if(![1,6,7].includes(n[e.id.toString()].status))throw Error("swap error");let{amountOut:c,minAmountOut:d,currentPrice:p,executionPrice:m,priceImpact:f,fee:y}=this.scope.liquidity.computeAmountOut({poolInfo:n[e.id.toString()],amountIn:s.raw,mintIn:s.token.mint,mintOut:a.address,slippage:r});return{amountIn:{amount:s,fee:void 0,expirationTime:void 0},amountOut:{amount:yt(E(N({},a),{amount:c})),fee:void 0,expirationTime:void 0},minAmountOut:{amount:yt(E(N({},a),{amount:d})),fee:void 0,expirationTime:void 0},currentPrice:p,executionPrice:m,priceImpact:f,fee:[new Ee(s.token,y)],routeType:"amm",poolInfoList:[e],remainingAccounts:[],poolReady:Number(n[e.id].openTime)<o,poolType:e.version===5?"STABLE":void 0,expirationTime:void 0,allTrade:!0,slippage:r,clmmExPriceX64:[void 0]}}}computeAmountIn({itemPool:e,tickCache:t,simulateCache:n,chainTime:o,epochInfo:i,slippage:r,amountOut:a,outputToken:s,blockTimestamp:u}){let c=s.address===e.mintB.address?e.mintA:e.mintB;if(e.version===6){let{allTrade:d,realAmountOut:p,amountIn:m,maxAmountIn:f,expirationTime:y,currentPrice:b,executionPrice:g,priceImpact:P,fee:k,remainingAccounts:I}=gt.computeAmountIn({poolInfo:e,tickarrayBitmapExtension:e.exBitmapInfo,tickArrayCache:t[e.id.toString()],amountOut:a,baseMint:new ye.PublicKey(c.address),slippage:r,epochInfo:i,blockTimestamp:u});return{allTrade:d,amountOut:{amount:yt(E(N({},s),{amount:p.amount})),fee:p.fee?yt(E(N({},s),{amount:p.fee})):void 0,expirationTime:void 0},amountIn:{amount:yt(E(N({},c),{amount:m.amount})),fee:m.fee?yt(E(N({},c),{amount:m.fee})):void 0,expirationTime:m.expirationTime},maxAmountIn:{amount:yt(E(N({},c),{amount:f.amount})),fee:f.fee?yt(E(N({},c),{amount:f.fee})):void 0,expirationTime:f.expirationTime},currentPrice:new Fe.default(b.toFixed()),executionPrice:new Fe.default(g.toFixed()),priceImpact:new Fe.default(P.toFixed()),fee:[yt(E(N({},c),{amount:k}))],remainingAccounts:[I],routeType:"amm",poolInfoList:[e],poolReady:e.startTime<o,poolType:"CLMM",slippage:r,clmmExPriceX64:[yo(g)],expirationTime:Zn(p.expirationTime,y)}}else if(e.version===7){let{allTrade:d,executionPrice:p,amountIn:m,amountOut:f,priceImpact:y,fee:b}=this.scope.cpmm.computeSwapAmount({pool:e,outputMint:s.address,amountIn:a,swapBaseIn:!1,slippage:r});return{allTrade:d,amountOut:{amount:yt(E(N({},s),{amount:f})),fee:void 0,expirationTime:void 0},amountIn:{amount:yt(E(N({},c),{amount:m})),fee:void 0,expirationTime:void 0},maxAmountIn:{amount:yt(E(N({},c),{amount:m.mul(new Ie.default((1+r)*1e4)).div(new Ie.default(1e4))})),fee:void 0,expirationTime:void 0},currentPrice:e.poolPrice,executionPrice:p,priceImpact:y,fee:[yt(E(N({},c),{amount:b}))],remainingAccounts:[],routeType:"amm",poolInfoList:[e],poolReady:e.openTime.toNumber()<o,poolType:"CPMM",slippage:r,clmmExPriceX64:[void 0],expirationTime:void 0}}else{if(![1,6,7].includes(n[e.id.toString()].status))throw Error("swap error");let{amountIn:d,maxAmountIn:p,currentPrice:m,executionPrice:f,priceImpact:y}=this.scope.liquidity.computeAmountIn({poolInfo:n[e.id.toString()],amountOut:a,mintIn:c.address,mintOut:s.address,slippage:r});return{amountOut:{amount:yt(E(N({},s),{amount:a})),fee:void 0,expirationTime:void 0},amountIn:{amount:yt(E(N({},c),{amount:d})),fee:void 0,expirationTime:void 0},maxAmountIn:{amount:yt(E(N({},c),{amount:p})),fee:void 0,expirationTime:void 0},currentPrice:m,executionPrice:f,priceImpact:y,fee:[yt(E(N({},c),{amount:$}))],routeType:"amm",poolInfoList:[e],remainingAccounts:[],poolReady:Number(n[e.id].openTime)<o,poolType:e.version===5?"STABLE":void 0,expirationTime:void 0,allTrade:!0,slippage:r,clmmExPriceX64:[void 0]}}}async computePoolToPoolKeys({pools:e,clmmRpcData:t={},ammRpcData:n={}}){let o=new Set(e.filter(u=>u.version===6&&!t[u.id.toString()]).map(u=>u.id.toString()));if(o.size>0){let u=await this.scope.clmm.getRpcClmmPoolInfos({poolIds:Array.from(o)});Object.keys(u).forEach(c=>{t[c]=u[c]})}let i=new Set(e.filter(u=>u.version===4&&!n[u.id.toString()]).map(u=>u.id.toString()));if(i.size>0){let u=await this.scope.liquidity.getRpcPoolInfos(Array.from(i));Object.keys(u).forEach(c=>{n[c]=u[c]})}let r=new Set(e.filter(u=>u.version===4).map(u=>u.marketId)),a={};r.size>0&&(await qe(this.scope.connection,Array.from(r).map(c=>({pubkey:new ye.PublicKey(c)})))).forEach(c=>{if(!c.accountInfo)return;let d=gs.decode(c.accountInfo.data);a[c.pubkey.toBase58()]={marketId:c.pubkey.toString(),marketProgramId:c.accountInfo.owner.toString(),marketAuthority:_r.getAssociatedAuthority({programId:c.accountInfo.owner,marketId:c.pubkey}).publicKey.toString(),marketBaseVault:d.baseVault.toString(),marketQuoteVault:d.quoteVault.toString(),marketBids:d.bids.toString(),marketAsks:d.asks.toString(),marketEventQueue:d.eventQueue.toString()}});let s=[];return e.forEach(u=>{if(u.version===6){let c=t[u.id.toString()],d={programId:u.programId.toBase58(),id:u.id.toBase58(),mintA:u.mintA,mintB:u.mintB,openTime:String(u.startTime),vault:{A:c.vaultA.toBase58(),B:c.vaultB.toBase58()},config:E(N({},u.ammConfig),{id:u.ammConfig.id.toString(),defaultRange:0,defaultRangePoint:[]}),rewardInfos:[],observationId:u.observationId.toBase58(),exBitmapAccount:u.exBitmapAccount.toBase58()};s.push(d)}else if(u.version===4){let c=n[u.id.toString()],d=N({programId:u.programId,id:u.id,mintA:u.mintA,mintB:u.mintB,openTime:String(u.openTime),vault:{A:c.baseVault.toBase58(),B:c.quoteVault.toBase58()},authority:$a({programId:new ye.PublicKey(u.programId)}).publicKey.toString(),openOrders:c.openOrders.toBase58(),targetOrders:c.targetOrders.toBase58(),mintLp:u.lpMint},a[u.marketId]||{marketProgramId:c.marketProgramId.toBase58(),marketId:c.marketId.toBase58(),marketAuthority:ye.PublicKey.default.toBase58(),marketBaseVault:ye.PublicKey.default.toBase58(),marketQuoteVault:ye.PublicKey.default.toBase58(),marketBids:ye.PublicKey.default.toBase58(),marketAsks:ye.PublicKey.default.toBase58(),marketEventQueue:ye.PublicKey.default.toBase58()});s.push(d)}else u.version===7&&s.push({observationId:u.observationId.toBase58(),programId:u.programId.toBase58(),id:u.id.toBase58(),mintA:u.mintA,mintB:u.mintB,openTime:String(u.openTime),authority:go(u.programId).publicKey.toBase58(),vault:{A:u.vaultA.toBase58(),B:u.vaultB.toBase58()},mintLp:At({address:u.mintLp.toBase58(),programId:Pe.TOKEN_PROGRAM_ID.toBase58(),decimals:u.lpDecimals}),config:E(N({id:u.configId.toBase58()},u.configInfo),{protocolFeeRate:u.configInfo.protocolFeeRate.toNumber(),tradeFeeRate:u.configInfo.tradeFeeRate.toNumber(),fundFeeRate:u.configInfo.fundFeeRate.toNumber(),createPoolFee:u.configInfo.createPoolFee.toString()})})}),s}};var To=require("@solana/web3.js"),hd=require("@solana/spl-token"),Hc=ie(require("bn.js"));var Ht=class extends at{static getPdaPoolId(e,t){return re([Ht.SEED_CONFIG.pool.id,t.toBuffer()],e)}static getPdaOwnerId(e,t,n,o){return re([Ht.SEED_CONFIG.owner.id,t.toBuffer(),n.toBuffer(),Buffer.from(new Hc.default(o).toArray())],e)}static async getAllInfo({connection:e,programId:t,poolIds:n,wallet:o,chainTime:i}){if(n.length===0)return[];let r=n.map(c=>Ht.getPdaPoolId(t,c).publicKey),a=[];for(let c=0;c<Ht.VERSION_PROJECT.length;c++)a.push(...r.map(d=>Ht.getPdaOwnerId(t,d,o,c).publicKey));let s=await Lt(e,[...r,...a]),u=[];for(let c=0;c<s.length;c++){let d=Math.floor(c/n.length),p=c%n.length,m=r[p],f=a[c],y=s[p],b=s[n.length+c];if(!(y&&b)||y.data.length!==Ht.POOL_LAYOUT.span||b.data.length!==Ht.OWNER_LAYOUT.span)continue;let g=Ht.POOL_LAYOUT.decode(y.data),P=Ht.OWNER_LAYOUT.decode(b.data),k=g.openTime.toNumber(),I=g.endTime.toNumber(),A=P.tokenInfo.map(S=>S.debtAmount.gt(new Hc.default(0))).filter(S=>!S).length!==3,h=i>k&&i<I&&g.status===1,B=A&&h;u.push({programId:t,poolId:m,ammId:g.ammId,ownerAccountId:f,snapshotLpAmount:P.lpAmount,project:Ht.VERSION_PROJECT[d],openTime:k,endTime:I,canClaim:B,canClaimErrorType:A?h?void 0:"outOfOperationalTime":"alreadyClaimIt",tokenInfo:g.tokenInfo.map((S,K)=>({mintAddress:S.mintAddress,mintVault:S.mintVault,mintDecimals:S.mintDecimals,perLpLoss:S.perLpLoss,debtAmount:P.tokenInfo[K].debtAmount.add(P.tokenInfo[K].claimedAmount)}))})}return u}async makeClaimTransaction({poolInfo:e,ownerInfo:t,feePayer:n}){t.wallet||this.scope.checkOwner();let o=this.createTxBuilder(n),i=t.wallet||this.scope.ownerPubKey,r=[];for(let u of e.tokenInfo){let{account:c,instructionParams:d}=await this.scope.account.getOrCreateTokenAccount({mint:u.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:u.mintAddress.equals(Je.WSOL.mint),createInfo:{payer:i,amount:0},skipCloseAccount:!u.mintAddress.equals(Je.WSOL.mint),associatedOnly:u.mintAddress.equals(Je.WSOL.mint)?!1:t.associatedOnly});d&&o.addInstruction(d),r.push(c)}o.addInstruction({instructions:[Ht.makeClaimInstruction({programId:e.programId,poolInfo:e,ownerInfo:{wallet:i,ownerPda:e.ownerAccountId,claimAddress:r}})]});let{transaction:a,signers:s}=o.build();return[{transaction:a,signer:s}]}async makeClaimAllTransaction({poolInfos:e,ownerInfo:t,feePayer:n}){let o=this.createTxBuilder(n),i=t.wallet||this.scope.ownerPubKey,r={};for(let c of e){let d=[];for(let p of c.tokenInfo){let{account:m,instructionParams:f}=await this.scope.account.getOrCreateTokenAccount({mint:p.mintAddress,owner:this.scope.ownerPubKey,notUseTokenAccount:p.mintAddress.equals(Je.WSOL.mint),createInfo:{payer:i,amount:0},skipCloseAccount:!p.mintAddress.equals(Je.WSOL.mint),associatedOnly:p.mintAddress.equals(Je.WSOL.mint)?!1:t.associatedOnly});f&&o.addInstruction(f),m&&(r[p.mintAddress.toString()]=m,d.push(m))}o.addInstruction({instructions:[Ht.makeClaimInstruction({programId:c.programId,poolInfo:c,ownerInfo:{wallet:i,ownerPda:c.ownerAccountId,claimAddress:d}})]})}let{transaction:a,signers:s}=o.build(),u=o.allInstructions;return Vs(u,[i,...s.map(c=>c.publicKey)])?[{transaction:a,signer:s}]:[{transaction:new To.Transaction().add(...u.slice(0,o.AllTxData.instructions.length-1)),signer:s},{transaction:new To.Transaction().add(...u.slice(o.AllTxData.instructions.length-1)),signer:[]},{transaction:new To.Transaction().add(...o.AllTxData.endInstructions),signer:[]}]}static makeClaimInstruction({programId:e,poolInfo:t,ownerInfo:n}){let o=v([]),i=[{pubkey:n.wallet,isSigner:!0,isWritable:!0},{pubkey:t.poolId,isSigner:!1,isWritable:!0},{pubkey:n.ownerPda,isSigner:!1,isWritable:!0},...n.claimAddress.map(s=>({pubkey:s,isSigner:!1,isWritable:!0})),...t.tokenInfo.map(({mintVault:s})=>({pubkey:s,isSigner:!1,isWritable:!0})),{pubkey:hd.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1}],r=Buffer.alloc(o.span);o.encode({},r);let a=Buffer.from([10,66,208,184,161,6,191,98,...r]);return new To.TransactionInstruction({keys:i,programId:e,data:a})}},Bn=Ht;Bn.CLAIMED_NUM=3,Bn.POOL_LAYOUT=v([Be(8),V("bump"),V("status"),w("openTime"),w("endTime"),M("ammId"),j(v([V("mintDecimals"),M("mintAddress"),M("mintVault"),w("perLpLoss"),w("totalClaimedAmount")]),Ht.CLAIMED_NUM,"tokenInfo"),j(w(),10,"padding")]),Bn.OWNER_LAYOUT=v([Be(8),V("bump"),V("version"),M("poolId"),M("owner"),w("lpAmount"),j(v([M("mintAddress"),w("debtAmount"),w("claimedAmount")]),Ht.CLAIMED_NUM,"tokenInfo"),j(w(),4,"padding")]),Bn.DEFAULT_POOL_ID=["58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2","6UmmUiYoBjSrhakAobJw8BvkmJtDVxaeBtbt7rxWo1mg","AVs9TA4nWDzfPJE9gGVNJMVhcQy3V9PGazuz33BfG2RA","DVa7Qmb5ct9RCpaU7UTpSaf3GVMYz17vNVU67XpdCRut","7XawhbbxtsRcQA8KTkHT9f9nc6d69UwqCDh6U5EEbEmX","6a1CsrpeZubDjEJE9s1CMVheB6HWM5d7m1cj2jkhyXhj","EoNrn8iUhwgJySD1pHu8Qxm5gSQqLK3za4m8xzD2RuEb","AceAyRTWt4PyB2pHqf2qhDgNZDtKVNaxgL8Ru3V4aN1P","6tmFJbMk5yVHFcFy7X2K8RwHjKLr6KVFLYXpgpBNeAxB"].map(e=>new To.PublicKey(e)),Bn.SEED_CONFIG={pool:{id:Buffer.from("pool_seed","utf8")},owner:{id:Buffer.from("user_claim_seed","utf8")}},Bn.VERSION_PROJECT=[void 0,"Francium","Tulip","Larix"];var Qc=require("@solana/web3.js"),ln=require("@solana/spl-token");var Er=class extends at{constructor(t){super(t);this._tokenList=[];this._tokenMap=new Map;this._blackTokenMap=new Set;this._mintGroup={official:new Set,jup:new Set,extra:new Set};this._whiteMap=new Set;this._extraTokenList=[]}async load(t){this.checkDisabled();let{forceUpdate:n=!1,type:o="strict"}=t||{},{mintList:i,blacklist:r,whiteList:a}=await this.scope.fetchV3TokenList(n),s=await this.scope.fetchJupTokenList(n);this._tokenList=[],this._tokenMap=new Map,this._blackTokenMap=new Set(r),this._mintGroup={official:new Set,jup:new Set,extra:new Set},this._whiteMap=new Set(a),this._tokenMap.set(Sn.address,Sn),this._mintGroup.official.add(Sn.address),i.forEach(u=>{var c;this._blackTokenMap.has(u.address)||(this._tokenMap.set(u.address,E(N({},u),{type:"raydium",priority:2,programId:(c=u.programId)!=null?c:u.tags.includes("token-2022")?ln.TOKEN_2022_PROGRAM_ID.toBase58():ln.TOKEN_PROGRAM_ID.toBase58()})),this._mintGroup.official.add(u.address))}),s.forEach(u=>{var c;this._blackTokenMap.has(u.address)||this._tokenMap.has(u.address)||(this._tokenMap.set(u.address,E(N({},u),{type:"jupiter",priority:1,programId:(c=u.programId)!=null?c:u.tags.includes("token-2022")?ln.TOKEN_2022_PROGRAM_ID.toBase58():ln.TOKEN_PROGRAM_ID.toBase58(),tags:u.freezeAuthority?[...u.tags||[],"hasFreeze"]:u.tags})),this._mintGroup.jup.add(u.address))}),this._extraTokenList.forEach(u=>{this._blackTokenMap.has(u.address)||this._tokenMap.has(u.address)||(this._tokenMap.set(u.address,E(N({},u),{type:"extra",priority:1,programId:u.programId||u.tags.includes("token-2022")?ln.TOKEN_2022_PROGRAM_ID.toBase58():ln.TOKEN_PROGRAM_ID.toBase58()})),this._mintGroup.extra.add(u.address))}),this._tokenList=Array.from(this._tokenMap).map(u=>u[1])}get tokenList(){return this._tokenList}get tokenMap(){return this._tokenMap}get blackTokenMap(){return this._blackTokenMap}get mintGroup(){return this._mintGroup}get whiteListMap(){return this._whiteMap}async getTokenInfo(t){if(!t)throw new Error("please input mint");let n=t.toString(),o=this._tokenMap.get(n);if(o)return o;if(n.toLocaleUpperCase()==="SOL")return Sn;let i=(await this.scope.api.getTokenInfo([n]))[0];if(i)return this._mintGroup.extra.add(n),this._tokenMap.set(n,E(N({},i),{priority:2})),i;let r=await this.scope.connection.getAccountInfo(new Qc.PublicKey(n));if(!r)throw new Error(`mint address not found: ${n}`);let a=ln.MintLayout.decode(r.data),s=n.toString().substring(0,6),u=(0,ln.getTransferFeeConfig)((0,ln.unpackMint)(new Qc.PublicKey(t),r,r.owner)),c={chainId:101,address:n,programId:r.owner.toBase58(),logoURI:"",symbol:s,name:s,decimals:a.decimals,tags:[],extensions:u?{feeConfig:Nn(u)}:{},priority:0,type:"unknown"};return this._mintGroup.extra.add(n),this._tokenMap.set(n,c),c}};var Dr=class{constructor(e){this.rawBalances=new Map;let{connection:t,cluster:n,owner:o,api:i,defaultChainTime:r,defaultChainTimeOffset:a,apiCacheTime:s,blockhashCommitment:u="confirmed",loopMultiTxStatus:c}=e;this._connection=t,this.cluster=n||"mainnet",this._owner=o?new Cn(o):void 0,this._signAllTransactions=e.signAllTransactions,this.blockhashCommitment=u,this.loopMultiTxStatus=c,this.api=i,this._apiCacheTime=s||5*60*1e3,this.logger=Se("Raydium"),this.farm=new dr({scope:this,moduleName:"Raydium_Farm"}),this.account=new Zi({scope:this,moduleName:"Raydium_Account",tokenAccounts:e.tokenAccounts,tokenAccountRawInfos:e.tokenAccountRawInfos}),this.liquidity=new Tr({scope:this,moduleName:"Raydium_LiquidityV2"}),this.token=new Er({scope:this,moduleName:"Raydium_tokenV2"}),this.tradeV2=new Vr({scope:this,moduleName:"Raydium_tradeV2"}),this.clmm=new li({scope:this,moduleName:"Raydium_clmm"}),this.cpmm=new xr({scope:this,moduleName:"Raydium_cpmm"}),this.utils1216=new Bn({scope:this,moduleName:"Raydium_utils1216"}),this.marketV2=new Ii({scope:this,moduleName:"Raydium_marketV2"}),this.launchpad=new vr({scope:this,moduleName:"Raydium_lauchpad"}),this.availability={};let d=new Date().getTime();this.apiData={},a&&(this._chainTime={fetched:d,value:{chainTime:r||Date.now()-a,offset:a}})}static async load(e){var c;let t=(0,Id.merge)({cluster:"mainnet",owner:null,apiRequestInterval:3e5,apiRequestTimeout:1e4},e),{cluster:n,apiRequestTimeout:o,logCount:i,logRequests:r,urlConfigs:a}=t,s=new ia({cluster:n,timeout:o,urlConfigs:a,logCount:i,logRequests:r}),u=new Dr(E(N({},t),{api:s}));return await u.fetchAvailabilityStatus((c=e.disableFeatureCheck)!=null?c:!0),e.disableLoadToken||await u.token.load({type:e.jupTokenType}),u}get owner(){return this._owner}get ownerPubKey(){if(!this._owner)throw new Error(ra);return this._owner.publicKey}setOwner(e){return this._owner=e?new Cn(e):void 0,this.account.resetTokenAccounts(),this}get connection(){if(!this._connection)throw new Error(vl);return this._connection}setConnection(e){return this._connection=e,this}get signAllTransactions(){return this._signAllTransactions}setSignAllTransactions(e){return this._signAllTransactions=e,this}checkOwner(){if(!this.owner)throw console.error(ra),new Error(ra)}isCacheInvalidate(e){return new Date().getTime()-e>this._apiCacheTime}async fetchChainTime(){try{let e=await this.api.getChainTimeOffset();this._chainTime={fetched:Date.now(),value:{chainTime:Date.now()+e.offset*1e3,offset:e.offset*1e3}}}catch{this._chainTime=void 0}}async fetchV3TokenList(e){if(this.apiData.tokenList&&!this.isCacheInvalidate(this.apiData.tokenList.fetched)&&!e)return this.apiData.tokenList.data;try{let t=await this.api.getTokenList(),n={fetched:Date.now(),data:t};return this.apiData.tokenList=n,n.data}catch(t){return console.error(t),{mintList:[],blacklist:[],whiteList:[]}}}async fetchJupTokenList(e){if(this.cluster==="devnet")return[];let t=this.apiData.jupTokenList;if(t&&!this.isCacheInvalidate(t.fetched)&&!e)return t.data;try{let n=await this.api.getJupTokenList();return this.apiData.jupTokenList={fetched:Date.now(),data:n.map(o=>E(N({},o),{mintAuthority:o.mint_authority||void 0,freezeAuthority:o.freeze_authority||void 0}))},this.apiData.jupTokenList.data}catch(n){return console.error(n),[]}}get chainTimeData(){var e;return(e=this._chainTime)==null?void 0:e.value}async chainTimeOffset(){var e;return this._chainTime&&Date.now()-this._chainTime.fetched<=1e3*60*5?this._chainTime.value.offset:(await this.fetchChainTime(),((e=this._chainTime)==null?void 0:e.value.offset)||0)}async currentBlockChainTime(){var e;return this._chainTime&&Date.now()-this._chainTime.fetched<=1e3*60*5?this._chainTime.value.chainTime:(await this.fetchChainTime(),((e=this._chainTime)==null?void 0:e.value.chainTime)||Date.now())}async fetchEpochInfo(){return this._epochInfo&&Date.now()-this._epochInfo.fetched<=1e3*30?this._epochInfo.value:(this._epochInfo={fetched:Date.now(),value:await this.connection.getEpochInfo()},this._epochInfo.value)}async fetchAvailabilityStatus(e){if(e)return{};try{let t=await this.api.fetchAvailabilityStatus(),n=t.all===!1;return this.availability={all:t.all,swap:n?!1:t.swap,createConcentratedPosition:n?!1:t.createConcentratedPosition,addConcentratedPosition:n?!1:t.addConcentratedPosition,addStandardPosition:n?!1:t.addStandardPosition,removeConcentratedPosition:n?!1:t.removeConcentratedPosition,removeStandardPosition:n?!1:t.removeStandardPosition,addFarm:n?!1:t.addFarm,removeFarm:n?!1:t.removeFarm},t}catch{return{}}}};var Hf=l=>l;0&&(module.exports={AMM_CONFIG_SEED,AUTH_SEED,BIT_PRECISION,BN_NEGATIVE_ONE,BN_ONE,BN_ZERO,BondingCurveParam,CONFIG_SEED,CREATOR_FEE_VAULT_AUTH_SEED,Clmm,ClmmConfigLayout,ClmmInstrument,CollectFeeOn,ConstantProductCurve,CpmmConfigInfoLayout,CpmmCreatorFeeOn,CpmmFee,CpmmPermission,CpmmPoolInfoLayout,Curve,CurveBase,CurveCalculator,DEV_FARM_LOCK_MINT,DEV_FARM_LOCK_VAULT,DYNAMIC_CONFIG_INDEX,DYNAMIC_FEE_CONFIG_SEED,DYNAMIC_FEE_CONTROL_DENOMINATOR,DataElement,DynamicFeeConfigLayout,DynamicFeeInfo,DynamicFeeInfoLayout,EXTENSION_TICKARRAY_BITMAP_SIZE,FARM_LOCK_MINT,FARM_LOCK_VAULT,FARM_PROGRAM_TO_VERSION,FARM_VERSION_TO_LEDGER_LAYOUT,FARM_VERSION_TO_STATE_LAYOUT,FEE_RATE_DENOMINATOR,FeeOn,FixedPriceCurve,LIQUIDITY_FEES_DENOMINATOR,LIQUIDITY_FEES_NUMERATOR,LIQUIDITY_VERSION_TO_SERUM_VERSION,LIQUIDITY_VERSION_TO_STATE_LAYOUT,LOCK_LIQUIDITY_SEED,LOG_B_2_X32,LOG_B_P_ERR_MARGIN_LOWER_X64,LOG_B_P_ERR_MARGIN_UPPER_X64,LaunchConstantProductCurve,LaunchpadConfig,LaunchpadMintProgramBit,LaunchpadPool,LaunchpadPoolInitParam,LaunchpadVesting,LimitOrderLayout,LimitOrderMath,LimitOrderNonceLayout,LinearPriceCurve,LiquidityMathUtil,LockClPositionLayoutV2,LockPositionLayout,MAGIC_SQRT_10001,MARKET_STATE_LAYOUT_V2,MARKET_STATE_LAYOUT_V3,MARKET_VERSION_TO_STATE_LAYOUT,MAX_FEE_RATE,MAX_FEE_RATE_NUMERATOR,MAX_SQRT_PRICE_X64,MAX_TICK,MAX_TICK_SPACING,MIN_SQRT_PRICE_X64,MIN_TICK,Market,MathLaunch,OBSERVATION_NUM,OBSERVATION_UPDATE_DURATION_DEFAULT,OPERATION_SEED,OPERATION_SIZE_USIZE,ObservationItemLayout,ObservationLayout,OperationLayout,PERMISSION_SEED,PLATFORM_ALLOW_CONFIG_SEED,PLATFORM_FEE_VAULT_AUTH_SEED,PLATFORM_GLOBAL_ACCESS_SEED,PLATFORM_SEED,POOL_LOCK_ID_SEED,POOL_OBSERVATION_SEED,POOL_REWARD_VAULT_SEED,POOL_SEED,POOL_TICK_ARRAY_BITMAP_SEED,POOL_VAULT_SEED,POOL_VESTING_SEED,POSITION_SEED,PersonalPositionLayout,PlatformConfig,PlatformCurveParam,PoolFee,PoolInfoLayout,PoolStatusBitFlag,PoolStatusBitIndex,PoolUtil,PoolUtils,PositionRewardInfoLayout,PositionUtils,ProtocolPositionLayout,Q128,Q64,REDUCTION_FACTOR_DENOMINATOR,RESOLUTION,REWARD_NUM,Raydium,RewardInfoLayout,RewardState,RoundDirection,SERUM_PROGRAMID_TO_VERSION,SERUM_VERSION_TO_PROGRAMID,SOL_INFO,SPL_MINT_LAYOUT,SUPPORT_MINT_SEED,SqrtPriceMath,StableLayout,SwapMathUtil,SwapState,TICK_ARRAY_BITMAP_SIZE,TICK_ARRAY_SEED,TICK_ARRAY_SIZE,TICK_ARRAY_SIZE_USIZE,TICK_TO_SQRT_PRICE_FACTORS,TOKEN_WSOL,TickArrayBitmapExtensionLayout,TickArrayBitmapUtil,TickArrayLayout,TickArrayUtil,TickLayout,TickUtil,TradeDirection,TradeDirectionOpposite,U128_MAX,U256_MAX,U64_IGNORE_RANGE,U64_MAX,UpdateAmmConfigParam,UpdateOperationAccountParam,VOLATILITY_ACCUMULATOR_SCALE,VestingSchedule,Voter,VoterDepositEntry,VoterLockup,VoterRegistrar,VoterVotingMintConfig,WHITE_MINT_SIZE_USIZE,abs,addLiquidityLayout,anchorDataBuf,associatedLedgerAccountLayout,buyExactInInstruction,buyExactOutInstruction,calFarmRewardAmount,checkPoolToAmm,checkedAdd,checkedMul,checkedSub,claimCreatorFee,claimPlatformFee,claimPlatformFeeFromVault,claimVestedToken,clearBit,clmmComputeInfoToApiInfo,closeAccountInstruction,closePlatformAllowConfigIns,collectCpFeeInstruction,collectCreatorFeePermissionlessInInstruction,cpmmLockPositionInstruction,createAssociatedLedgerAccountInstruction,createPlatformAllowConfigIns,createPlatformConfig,createPlatformVestingAccountIns,createPoolFeeLayout,createPoolV4InstructionV2,createPoolV4Layout,createVestingAccount,createWSolAccountInstructions,decimalToX64,divRoundingUp,dwLayout,farmAddRewardLayout,farmLedgerLayoutV3_1,farmLedgerLayoutV3_2,farmLedgerLayoutV5_1,farmLedgerLayoutV5_2,farmLedgerLayoutV6_1,farmRewardInfoToConfig,farmRewardLayout,farmRewardRestartLayout,farmRewardTimeInfoLayout,farmStateV3Layout,farmStateV5Layout,farmStateV6Layout,fetchMultipleFarmInfoAndUpdate,fetchTickArrays,fixedSwapInLayout,fixedSwapOutLayout,formatLayout,fromSignedI128,generatePubKey,getAssociatedAuthority,getAssociatedConfigId,getAssociatedLedgerAccount,getAssociatedLedgerPoolAccount,getAssociatedOpenOrders,getAssociatedPoolKeys,getCollectFeeOnDescription,getCpLockPda,getCpmmPdaAmmConfigId,getCpmmPdaPoolId,getCreatePoolKeys,getDepositEntryIndex,getDxByDyBaseIn,getDyByDxBaseIn,getFarmLedgerLayout,getFarmStateLayout,getLaunchpadPoolMintAProgram,getLaunchpadPoolMintBProgram,getLaunchpadPoolMintProgram,getLiquidityAssociatedAuthority,getLiquidityAssociatedId,getOrderTick,getPdaAmmConfigId,getPdaCpiEvent,getPdaCreatorFeeVaultAuth,getPdaCreatorVault,getPdaDynamicFeeConfigAddress,getPdaExBitmapAccount,getPdaLaunchpadAuth,getPdaLaunchpadConfigId,getPdaLaunchpadPoolId,getPdaLaunchpadVaultId,getPdaLimitOrderAddress,getPdaLimitOrderNonceAddress,getPdaLockClPositionIdV2,getPdaLockPositionId,getPdaLpMint,getPdaMetadataKey,getPdaMintExAccount,getPdaMintExAccountCp,getPdaObservationAccount,getPdaObservationId,getPdaOperationAccount,getPdaPermission,getPdaPermissionId,getPdaPermissionedPoolId,getPdaPersonalPositionAddress,getPdaPlatformAllowConfig,getPdaPlatformConfigAccess,getPdaPlatformFeeVaultAuth,getPdaPlatformId,getPdaPlatformVault,getPdaPoolAuthority,getPdaPoolId,getPdaPoolRewardVaultId,getPdaPoolVaultId,getPdaProtocolPositionAddress,getPdaTickArrayAddress,getPdaVault,getPdaVestId,getRegistrarAddress,getStablePrice,getTokenOwnerRecordAddress,getVoterAddress,getVoterWeightRecordAddress,getVotingMintAuthority,getVotingTokenMint,governanceCreateTokenOwnerRecord,i32ToBytes,i32ToBytesBE,initPoolLayout,initTokenAccountInstruction,initialize,initializeMarket,initializeV2,initializeWithPermission,initializeWithToken2022,isBitSet,isValidFarmVersion,judgeFarmType,leastSignificantBit,liquidityStateV4Layout,liquidityStateV5Layout,makeAMMSwapInstruction,makeAMMSwapV2Instruction,makeAddLiquidityInstruction,makeAddNewRewardInstruction,makeCollectCreatorFeeInstruction,makeCpmmLockInstruction,makeCreateCpmmPoolInInstruction,makeCreateFarmInstruction,makeCreateMarketInstruction,makeCreatorWithdrawFarmRewardInstruction,makeDepositCpmmInInstruction,makeDepositInstructionV3,makeDepositInstructionV5,makeDepositInstructionV6,makeDepositTokenInstruction,makeDepositWithdrawInstruction,makeInitPoolInstructionV4,makeRestartRewardInstruction,makeSwapCpmmBaseInInstruction,makeSwapCpmmBaseOutInstruction,makeSwapFixedInInstruction,makeSwapFixedOutInstruction,makeSwapInstruction,makeTransferInstruction,makeWithdrawCpmmInInstruction,makeWithdrawInstructionV3,makeWithdrawInstructionV4,makeWithdrawInstructionV5,makeWithdrawInstructionV6,makeWithdrawTokenInstruction,mask,mockV3CreatePoolInfo,modelDataInfoLayout,mostSignificantBit,mulDivCeil,mulDivFloor,mulDivRound,mulFull,parseTokenAccountResp,parseTokenInfo,poolLpAuthority,poolTypeV6,realFarmStateV3Layout,realFarmStateV5Layout,realFarmV6Layout,removeLiquidityInstruction,removeLiquidityLayout,removePlatformCurveParamInstruction,route1Instruction,route2Instruction,routeInstruction,sellExactInInstruction,sellExactOut,setBit,simulatePoolInfoInstruction,solToWSolToken,splAccountLayout,swapBaseInAutoAccount,swapBaseInV2Instruction,swapBaseOutAutoAccount,swapBaseOutV2Instruction,swapInternal,toAmmComputePoolInfo,toApiV3Token,toFeeConfig,toLaunchpadMintProgramFlag,toSignedI128,toToken,toTokenAmount,toTokenInfo,toTransferFeeConfig,toggleBit,u128CheckedMul,u128SaturatingAdd,u128SaturatingSub,u16ToBytes,u16ToBytesBE,u256MulDivCeil,u256MulDivFloor,u64ToBytes,u8ToBytes,unionArr,updateFarmPoolInfo,updatePlatformConfig,updatePlatformCurveParamInstruction,usdMintBSet,validateFarmRewards,voterStakeRegistryCreateDepositEntry,voterStakeRegistryCreateVoter,voterStakeRegistryDeposit,voterStakeRegistryUpdateVoterWeightRecord,voterStakeRegistryWithdraw,wSolToSolToken,withdrawRewardLayout,wrappingSubU128,x64ToDecimal});
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
//# sourceMappingURL=index.js.map