Repository: snipe-it-com/solana-sniper-bot Branch: master Commit: 4c9304ace338 Files: 34 Total size: 79.8 KB Directory structure: gitextract_8z8bgifv/ ├── .gitignore ├── .prettierrc ├── LICENSE.md ├── README.md ├── bot.ts ├── cache/ │ ├── index.ts │ ├── market.cache.ts │ ├── pool.cache.ts │ └── snipe-list.cache.ts ├── filters/ │ ├── burn.filter.ts │ ├── index.ts │ ├── mutable.filter.ts │ ├── pool-filters.ts │ ├── pool-size.filter.ts │ └── renounced.filter.ts ├── helpers/ │ ├── constants.ts │ ├── index.ts │ ├── liquidity.ts │ ├── logger.ts │ ├── market.ts │ ├── promises.ts │ ├── token.ts │ └── wallet.ts ├── index.ts ├── listeners/ │ ├── index.ts │ └── listeners.ts ├── package.json ├── snipe-list.txt ├── transactions/ │ ├── default-transaction-executor.ts │ ├── index.ts │ ├── jito-rpc-transaction-executor.ts │ ├── transaction-executor.interface.ts │ └── warp-transaction-executor.ts └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* .pnpm-debug.log* # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage *.lcov # nyc test coverage .nyc_output # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # Snowpack dependency directory (https://snowpack.dev/) web_modules/ # TypeScript cache *.tsbuildinfo # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Optional stylelint cache .stylelintcache # Microbundle cache .rpt2_cache/ .rts2_cache_cjs/ .rts2_cache_es/ .rts2_cache_umd/ # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variable files .env .env.development.local .env.test.local .env.production.local .env.local # parcel-bundler cache (https://parceljs.org/) .cache .parcel-cache # Next.js build output .next out # Nuxt.js build / generate output .nuxt dist # Gatsby files .cache/ # Comment in the public line in if your project uses Gatsby and not Next.js # https://nextjs.org/blog/next-9-1#public-directory-support # public # vuepress build output .vuepress/dist # vuepress v2.x temp and cache directory .temp .cache # Docusaurus cache and generated files .docusaurus # Serverless directories .serverless/ # FuseBox cache .fusebox/ # DynamoDB Local files .dynamodb/ # TernJS port file .tern-port # Stores VSCode versions used for testing VSCode extensions .vscode-test # PNPM pnpm-lock.yaml # yarn v2 .yarn/cache .yarn/unplugged .yarn/build-state.yml .yarn/install-state.gz .pnp.* # JetBrains .idea # Visual Studio Code *.code-workspace ================================================ FILE: .prettierrc ================================================ { "singleQuote": true, "trailingComma": "all", "printWidth": 120 } ================================================ FILE: LICENSE.md ================================================ Microsoft Public License (Ms-PL) This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ================================================ FILE: README.md ================================================ # Solana Trading Bot (Beta) The Solana Trading Bot is a software tool designed to automate the buying and selling of tokens on the Solana blockchain. It is configured to execute trades based on predefined parameters and strategies set by the user. The bot can monitor market conditions in real-time, such as pool burn, mint renounced and other factors, and it will execute trades when these conditions are fulfilled. ## Setup To run the script you need to: - Create a new empty Solana wallet - Transfer some SOL to it. - Convert some SOL to USDC or WSOL. - You need USDC or WSOL depending on the configuration set below. - Configure the script by updating `.env.copy` file (remove the .copy from the file name when done). - Check [Configuration](#configuration) section bellow - Install dependencies by typing: `npm install` - Run the script by typing: `npm run start` in terminal You should see the following output: ![output](readme/output.png) ### Configuration #### Wallet - `PRIVATE_KEY` - Your wallet's private key. #### Connection - `RPC_ENDPOINT` - HTTPS RPC endpoint for interacting with the Solana network. - `RPC_WEBSOCKET_ENDPOINT` - WebSocket RPC endpoint for real-time updates from the Solana network. - `COMMITMENT_LEVEL`- The commitment level of transactions (e.g., "finalized" for the highest level of security). #### Bot - `LOG_LEVEL` - Set logging level, e.g., `info`, `debug`, `trace`, etc. - `ONE_TOKEN_AT_A_TIME` - Set to `true` to process buying one token at a time. - `COMPUTE_UNIT_LIMIT` - Compute limit used to calculate fees. - `COMPUTE_UNIT_PRICE` - Compute price used to calculate fees. - `PRE_LOAD_EXISTING_MARKETS` - Bot will load all existing markets in memory on start. - This option should not be used with public RPC. - `CACHE_NEW_MARKETS` - Set to `true` to cache new markets. - This option should not be used with public RPC. - `TRANSACTION_EXECUTOR` - Set to `warp` to use warp infrastructure for executing transactions, or set it to jito to use JSON-RPC jito executer - For more details checkout [warp](#warp-transactions-beta) section - `CUSTOM_FEE` - If using warp or jito executors this value will be used for transaction fees instead of `COMPUTE_UNIT_LIMIT` and `COMPUTE_UNIT_LIMIT` - Minimum value is 0.0001 SOL, but we recommend using 0.006 SOL or above - On top of this fee, minimal solana network fee will be applied #### Buy - `QUOTE_MINT` - Which pools to snipe, USDC or WSOL. - `QUOTE_AMOUNT` - Amount used to buy each new token. - `AUTO_BUY_DELAY` - Delay in milliseconds before buying a token. - `MAX_BUY_RETRIES` - Maximum number of retries for buying a token. - `BUY_SLIPPAGE` - Slippage % #### Sell - `AUTO_SELL` - Set to `true` to enable automatic selling of tokens. - If you want to manually sell bought tokens, disable this option. - `MAX_SELL_RETRIES` - Maximum number of retries for selling a token. - `AUTO_SELL_DELAY` - Delay in milliseconds before auto-selling a token. - `PRICE_CHECK_INTERVAL` - Interval in milliseconds for checking the take profit and stop loss conditions. - Set to zero to disable take profit and stop loss. - `PRICE_CHECK_DURATION` - Time in milliseconds to wait for stop loss/take profit conditions. - If you don't reach profit or loss bot will auto sell after this time. - Set to zero to disable take profit and stop loss. - `TAKE_PROFIT` - Percentage profit at which to take profit. - Take profit is calculated based on quote mint. - `STOP_LOSS` - Percentage loss at which to stop the loss. - Stop loss is calculated based on quote mint. - `SELL_SLIPPAGE` - Slippage %. #### Snipe list - `USE_SNIPE_LIST` - Set to `true` to enable buying only tokens listed in `snipe-list.txt`. - Pool must not exist before the bot starts. - If token can be traded before bot starts nothing will happen. Bot will not buy the token. - `SNIPE_LIST_REFRESH_INTERVAL` - Interval in milliseconds to refresh the snipe list. - You can update snipe list while bot is running. It will pickup the new changes each time it does refresh. Note: When using snipe list filters below will be disabled. #### Filters - `FILTER_CHECK_INTERVAL` - Interval in milliseconds for checking if pool match the filters. - Set to zero to disable filters. - `FILTER_CHECK_DURATION` - Time in milliseconds to wait for pool to match the filters. - If pool doesn't match the filter buy will not happen. - Set to zero to disable filters. - `CONSECUTIVE_FILTER_MATCHES` - How many times in a row pool needs to match the filters. - This is useful because when pool is burned (and rugged), other filters may not report the same behavior. eg. pool size may still have old value - `CHECK_IF_MUTABLE` - Set to `true` to buy tokens only if their metadata are not mutable. - `CHECK_IF_SOCIALS` - Set to `true` to buy tokens only if they have at least 1 social. - `CHECK_IF_MINT_IS_RENOUNCED` - Set to `true` to buy tokens only if their mint is renounced. - `CHECK_IF_FREEZABLE` - Set to `true` to buy tokens only if they are not freezable. - `CHECK_IF_BURNED` - Set to `true` to buy tokens only if their liquidity pool is burned. - `MIN_POOL_SIZE` - Bot will buy only if the pool size is greater than or equal the specified amount. - Set `0` to disable. - `MAX_POOL_SIZE` - Bot will buy only if the pool size is less than or equal the specified amount. - Set `0` to disable. ## Warp transactions (beta) In case you experience a lot of failed transactions or transaction performance is too slow, you can try using `warp` for executing transactions. Warp is hosted service that executes transactions using integrations with third party providers. Using warp for transactions supports the team behind this project. ### Security When using warp, transaction is sent to the hosted service. **Payload that is being sent will NOT contain your wallet private key**. Fee transaction is signed on your machine. Each request is processed by hosted service and sent to third party provider. **We don't store your transactions, nor we store your private key.** Note: Warp transactions are disabled by default. ### Fees When using warp for transactions, fee is distributed between developers of warp and third party providers. In case TX fails, no fee will be taken from your account. ## Common issues If you have an error which is not listed here, please create a new issue in this repository. To collect more information on an issue, please change `LOG_LEVEL` to `debug`. ### Unsupported RPC node - If you see following error in your log file: `Error: 410 Gone: {"jsonrpc":"2.0","error":{"code": 410, "message":"The RPC call or parameters have been disabled."}, "id": "986f3599-b2b7-47c4-b951-074c19842bad" }` it means your RPC node doesn't support methods needed to execute script. - FIX: Change your RPC node. You can use Helius or Quicknode. ### No token account - If you see following error in your log file: `Error: No SOL token account found in wallet: ` it means that wallet you provided doesn't have USDC/WSOL token account. - FIX: Go to dex and swap some SOL to USDC/WSOL. For example when you swap sol to wsol you should see it in wallet as shown below: ![wsol](readme/wsol.png) ## Contact [![](https://img.shields.io/discord/1201826085655023616?color=5865F2&logo=Discord&style=flat-square)](https://discord.gg/xYUETCA2aP) - If you want to leave a tip, you can send it to the following address: `7gm6BPQrSBaTAYaJheuRevBNXcmKsgbkfBCVSjBnt9aP` - If you need custom features or assistance, feel free to contact the admin team on discord for dedicated support. ## Disclaimer The Solana Trading Bot is provided as is, for learning purposes. Trading cryptocurrencies and tokens involves risk, and past performance is not indicative of future results. The use of this bot is at your own risk, and we are not responsible for any losses incurred while using the bot. ================================================ FILE: bot.ts ================================================ import { ComputeBudgetProgram, Connection, Keypair, PublicKey, TransactionMessage, VersionedTransaction, } from '@solana/web3.js'; import { createAssociatedTokenAccountIdempotentInstruction, createCloseAccountInstruction, getAccount, getAssociatedTokenAddress, RawAccount, TOKEN_PROGRAM_ID, } from '@solana/spl-token'; import { Liquidity, LiquidityPoolKeysV4, LiquidityStateV4, Percent, Token, TokenAmount } from '@raydium-io/raydium-sdk'; import { MarketCache, PoolCache, SnipeListCache } from './cache'; import { PoolFilters } from './filters'; import { TransactionExecutor } from './transactions'; import { createPoolKeys, logger, NETWORK, sleep } from './helpers'; import { Mutex } from 'async-mutex'; import BN from 'bn.js'; import { WarpTransactionExecutor } from './transactions/warp-transaction-executor'; import { JitoTransactionExecutor } from './transactions/jito-rpc-transaction-executor'; export interface BotConfig { wallet: Keypair; checkRenounced: boolean; checkFreezable: boolean; checkBurned: boolean; minPoolSize: TokenAmount; maxPoolSize: TokenAmount; quoteToken: Token; quoteAmount: TokenAmount; quoteAta: PublicKey; oneTokenAtATime: boolean; useSnipeList: boolean; autoSell: boolean; autoBuyDelay: number; autoSellDelay: number; maxBuyRetries: number; maxSellRetries: number; unitLimit: number; unitPrice: number; takeProfit: number; stopLoss: number; buySlippage: number; sellSlippage: number; priceCheckInterval: number; priceCheckDuration: number; filterCheckInterval: number; filterCheckDuration: number; consecutiveMatchCount: number; } export class Bot { private readonly poolFilters: PoolFilters; // snipe list private readonly snipeListCache?: SnipeListCache; // one token at the time private readonly mutex: Mutex; private sellExecutionCount = 0; public readonly isWarp: boolean = false; public readonly isJito: boolean = false; constructor( private readonly connection: Connection, private readonly marketStorage: MarketCache, private readonly poolStorage: PoolCache, private readonly txExecutor: TransactionExecutor, readonly config: BotConfig, ) { this.isWarp = txExecutor instanceof WarpTransactionExecutor; this.isJito = txExecutor instanceof JitoTransactionExecutor; this.mutex = new Mutex(); this.poolFilters = new PoolFilters(connection, { quoteToken: this.config.quoteToken, minPoolSize: this.config.minPoolSize, maxPoolSize: this.config.maxPoolSize, }); if (this.config.useSnipeList) { this.snipeListCache = new SnipeListCache(); this.snipeListCache.init(); } } async validate() { try { await getAccount(this.connection, this.config.quoteAta, this.connection.commitment); } catch (error) { logger.error( `${this.config.quoteToken.symbol} token account not found in wallet: ${this.config.wallet.publicKey.toString()}`, ); return false; } return true; } public async buy(accountId: PublicKey, poolState: LiquidityStateV4) { logger.trace({ mint: poolState.baseMint }, `Processing new pool...`); if (this.config.useSnipeList && !this.snipeListCache?.isInList(poolState.baseMint.toString())) { logger.debug({ mint: poolState.baseMint.toString() }, `Skipping buy because token is not in a snipe list`); return; } if (this.config.autoBuyDelay > 0) { logger.debug({ mint: poolState.baseMint }, `Waiting for ${this.config.autoBuyDelay} ms before buy`); await sleep(this.config.autoBuyDelay); } if (this.config.oneTokenAtATime) { if (this.mutex.isLocked() || this.sellExecutionCount > 0) { logger.debug( { mint: poolState.baseMint.toString() }, `Skipping buy because one token at a time is turned on and token is already being processed`, ); return; } await this.mutex.acquire(); } try { const [market, mintAta] = await Promise.all([ this.marketStorage.get(poolState.marketId.toString()), getAssociatedTokenAddress(poolState.baseMint, this.config.wallet.publicKey), ]); const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(accountId, poolState, market); if (!this.config.useSnipeList) { const match = await this.filterMatch(poolKeys); if (!match) { logger.trace({ mint: poolKeys.baseMint.toString() }, `Skipping buy because pool doesn't match filters`); return; } } for (let i = 0; i < this.config.maxBuyRetries; i++) { try { logger.info( { mint: poolState.baseMint.toString() }, `Send buy transaction attempt: ${i + 1}/${this.config.maxBuyRetries}`, ); const tokenOut = new Token(TOKEN_PROGRAM_ID, poolKeys.baseMint, poolKeys.baseDecimals); const result = await this.swap( poolKeys, this.config.quoteAta, mintAta, this.config.quoteToken, tokenOut, this.config.quoteAmount, this.config.buySlippage, this.config.wallet, 'buy', ); if (result.confirmed) { logger.info( { mint: poolState.baseMint.toString(), signature: result.signature, url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`, }, `Confirmed buy tx`, ); break; } logger.info( { mint: poolState.baseMint.toString(), signature: result.signature, error: result.error, }, `Error confirming buy tx`, ); } catch (error) { logger.debug({ mint: poolState.baseMint.toString(), error }, `Error confirming buy transaction`); } } } catch (error) { logger.error({ mint: poolState.baseMint.toString(), error }, `Failed to buy token`); } finally { if (this.config.oneTokenAtATime) { this.mutex.release(); } } } public async sell(accountId: PublicKey, rawAccount: RawAccount) { if (this.config.oneTokenAtATime) { this.sellExecutionCount++; } try { logger.trace({ mint: rawAccount.mint }, `Processing new token...`); const poolData = await this.poolStorage.get(rawAccount.mint.toString()); if (!poolData) { logger.trace({ mint: rawAccount.mint.toString() }, `Token pool data is not found, can't sell`); return; } const tokenIn = new Token(TOKEN_PROGRAM_ID, poolData.state.baseMint, poolData.state.baseDecimal.toNumber()); const tokenAmountIn = new TokenAmount(tokenIn, rawAccount.amount, true); if (tokenAmountIn.isZero()) { logger.info({ mint: rawAccount.mint.toString() }, `Empty balance, can't sell`); return; } if (this.config.autoSellDelay > 0) { logger.debug({ mint: rawAccount.mint }, `Waiting for ${this.config.autoSellDelay} ms before sell`); await sleep(this.config.autoSellDelay); } const market = await this.marketStorage.get(poolData.state.marketId.toString()); const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(new PublicKey(poolData.id), poolData.state, market); await this.priceMatch(tokenAmountIn, poolKeys); for (let i = 0; i < this.config.maxSellRetries; i++) { try { logger.info( { mint: rawAccount.mint }, `Send sell transaction attempt: ${i + 1}/${this.config.maxSellRetries}`, ); const result = await this.swap( poolKeys, accountId, this.config.quoteAta, tokenIn, this.config.quoteToken, tokenAmountIn, this.config.sellSlippage, this.config.wallet, 'sell', ); if (result.confirmed) { logger.info( { dex: `https://dexscreener.com/solana/${rawAccount.mint.toString()}?maker=${this.config.wallet.publicKey}`, mint: rawAccount.mint.toString(), signature: result.signature, url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`, }, `Confirmed sell tx`, ); break; } logger.info( { mint: rawAccount.mint.toString(), signature: result.signature, error: result.error, }, `Error confirming sell tx`, ); } catch (error) { logger.debug({ mint: rawAccount.mint.toString(), error }, `Error confirming sell transaction`); } } } catch (error) { logger.error({ mint: rawAccount.mint.toString(), error }, `Failed to sell token`); } finally { if (this.config.oneTokenAtATime) { this.sellExecutionCount--; } } } // noinspection JSUnusedLocalSymbols private async swap( poolKeys: LiquidityPoolKeysV4, ataIn: PublicKey, ataOut: PublicKey, tokenIn: Token, tokenOut: Token, amountIn: TokenAmount, slippage: number, wallet: Keypair, direction: 'buy' | 'sell', ) { const slippagePercent = new Percent(slippage, 100); const poolInfo = await Liquidity.fetchInfo({ connection: this.connection, poolKeys, }); const computedAmountOut = Liquidity.computeAmountOut({ poolKeys, poolInfo, amountIn, currencyOut: tokenOut, slippage: slippagePercent, }); const latestBlockhash = await this.connection.getLatestBlockhash(); const { innerTransaction } = Liquidity.makeSwapFixedInInstruction( { poolKeys: poolKeys, userKeys: { tokenAccountIn: ataIn, tokenAccountOut: ataOut, owner: wallet.publicKey, }, amountIn: amountIn.raw, minAmountOut: computedAmountOut.minAmountOut.raw, }, poolKeys.version, ); const messageV0 = new TransactionMessage({ payerKey: wallet.publicKey, recentBlockhash: latestBlockhash.blockhash, instructions: [ ...(this.isWarp || this.isJito ? [] : [ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: this.config.unitPrice }), ComputeBudgetProgram.setComputeUnitLimit({ units: this.config.unitLimit }), ]), ...(direction === 'buy' ? [ createAssociatedTokenAccountIdempotentInstruction( wallet.publicKey, ataOut, wallet.publicKey, tokenOut.mint, ), ] : []), ...innerTransaction.instructions, ...(direction === 'sell' ? [createCloseAccountInstruction(ataIn, wallet.publicKey, wallet.publicKey)] : []), ], }).compileToV0Message(); const transaction = new VersionedTransaction(messageV0); transaction.sign([wallet, ...innerTransaction.signers]); return this.txExecutor.executeAndConfirm(transaction, wallet, latestBlockhash); } private async filterMatch(poolKeys: LiquidityPoolKeysV4) { if (this.config.filterCheckInterval === 0 || this.config.filterCheckDuration === 0) { return true; } const timesToCheck = this.config.filterCheckDuration / this.config.filterCheckInterval; let timesChecked = 0; let matchCount = 0; do { try { const shouldBuy = await this.poolFilters.execute(poolKeys); if (shouldBuy) { matchCount++; if (this.config.consecutiveMatchCount <= matchCount) { logger.debug( { mint: poolKeys.baseMint.toString() }, `Filter match ${matchCount}/${this.config.consecutiveMatchCount}`, ); return true; } } else { matchCount = 0; } await sleep(this.config.filterCheckInterval); } finally { timesChecked++; } } while (timesChecked < timesToCheck); return false; } private async priceMatch(amountIn: TokenAmount, poolKeys: LiquidityPoolKeysV4) { if (this.config.priceCheckDuration === 0 || this.config.priceCheckInterval === 0) { return; } const timesToCheck = this.config.priceCheckDuration / this.config.priceCheckInterval; const profitFraction = this.config.quoteAmount.mul(this.config.takeProfit).numerator.div(new BN(100)); const profitAmount = new TokenAmount(this.config.quoteToken, profitFraction, true); const takeProfit = this.config.quoteAmount.add(profitAmount); const lossFraction = this.config.quoteAmount.mul(this.config.stopLoss).numerator.div(new BN(100)); const lossAmount = new TokenAmount(this.config.quoteToken, lossFraction, true); const stopLoss = this.config.quoteAmount.subtract(lossAmount); const slippage = new Percent(this.config.sellSlippage, 100); let timesChecked = 0; do { try { const poolInfo = await Liquidity.fetchInfo({ connection: this.connection, poolKeys, }); const amountOut = Liquidity.computeAmountOut({ poolKeys, poolInfo, amountIn: amountIn, currencyOut: this.config.quoteToken, slippage, }).amountOut; logger.debug( { mint: poolKeys.baseMint.toString() }, `Take profit: ${takeProfit.toFixed()} | Stop loss: ${stopLoss.toFixed()} | Current: ${amountOut.toFixed()}`, ); if (amountOut.lt(stopLoss)) { break; } if (amountOut.gt(takeProfit)) { break; } await sleep(this.config.priceCheckInterval); } catch (e) { logger.trace({ mint: poolKeys.baseMint.toString(), e }, `Failed to check token price`); } finally { timesChecked++; } } while (timesChecked < timesToCheck); } } ================================================ FILE: cache/index.ts ================================================ export * from './market.cache'; export * from './pool.cache'; export * from './snipe-list.cache'; ================================================ FILE: cache/market.cache.ts ================================================ import { Connection, PublicKey } from '@solana/web3.js'; import { getMinimalMarketV3, logger, MINIMAL_MARKET_STATE_LAYOUT_V3, MinimalMarketLayoutV3 } from '../helpers'; import { MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from '@raydium-io/raydium-sdk'; export class MarketCache { private readonly keys: Map = new Map(); constructor(private readonly connection: Connection) {} async init(config: { quoteToken: Token }) { logger.debug({}, `Fetching all existing ${config.quoteToken.symbol} markets...`); const accounts = await this.connection.getProgramAccounts(MAINNET_PROGRAM_ID.OPENBOOK_MARKET, { commitment: this.connection.commitment, dataSlice: { offset: MARKET_STATE_LAYOUT_V3.offsetOf('eventQueue'), length: MINIMAL_MARKET_STATE_LAYOUT_V3.span, }, filters: [ { dataSize: MARKET_STATE_LAYOUT_V3.span }, { memcmp: { offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'), bytes: config.quoteToken.mint.toBase58(), }, }, ], }); for (const account of accounts) { const market = MINIMAL_MARKET_STATE_LAYOUT_V3.decode(account.account.data); this.keys.set(account.pubkey.toString(), market); } logger.debug({}, `Cached ${this.keys.size} markets`); } public save(marketId: string, keys: MinimalMarketLayoutV3) { if (!this.keys.has(marketId)) { logger.trace({}, `Caching new market: ${marketId}`); this.keys.set(marketId, keys); } } public async get(marketId: string): Promise { if (this.keys.has(marketId)) { return this.keys.get(marketId)!; } logger.trace({}, `Fetching new market keys for ${marketId}`); const market = await this.fetch(marketId); this.keys.set(marketId, market); return market; } private fetch(marketId: string): Promise { return getMinimalMarketV3(this.connection, new PublicKey(marketId), this.connection.commitment); } } ================================================ FILE: cache/pool.cache.ts ================================================ import { LiquidityStateV4 } from '@raydium-io/raydium-sdk'; import { logger } from '../helpers'; export class PoolCache { private readonly keys: Map = new Map< string, { id: string; state: LiquidityStateV4 } >(); public save(id: string, state: LiquidityStateV4) { if (!this.keys.has(state.baseMint.toString())) { logger.trace(`Caching new pool for mint: ${state.baseMint.toString()}`); this.keys.set(state.baseMint.toString(), { id, state }); } } public async get(mint: string): Promise<{ id: string; state: LiquidityStateV4 }> { return this.keys.get(mint)!; } } ================================================ FILE: cache/snipe-list.cache.ts ================================================ import fs from 'fs'; import path from 'path'; import { logger, SNIPE_LIST_REFRESH_INTERVAL } from '../helpers'; export class SnipeListCache { private snipeList: string[] = []; private fileLocation = path.join(__dirname, '../snipe-list.txt'); constructor() { setInterval(() => this.loadSnipeList(), SNIPE_LIST_REFRESH_INTERVAL); } public init() { this.loadSnipeList(); } public isInList(mint: string) { return this.snipeList.includes(mint); } private loadSnipeList() { logger.trace(`Refreshing snipe list...`); const count = this.snipeList.length; const data = fs.readFileSync(this.fileLocation, 'utf-8'); this.snipeList = data .split('\n') .map((a) => a.trim()) .filter((a) => a); if (this.snipeList.length != count) { logger.info(`Loaded snipe list: ${this.snipeList.length}`); } } } ================================================ FILE: filters/burn.filter.ts ================================================ import { Filter, FilterResult } from './pool-filters'; import { Connection } from '@solana/web3.js'; import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; import { logger } from '../helpers'; export class BurnFilter implements Filter { constructor(private readonly connection: Connection) {} async execute(poolKeys: LiquidityPoolKeysV4): Promise { try { const amount = await this.connection.getTokenSupply(poolKeys.lpMint, this.connection.commitment); const burned = amount.value.uiAmount === 0; return { ok: burned, message: burned ? undefined : "Burned -> Creator didn't burn LP" }; } catch (e: any) { if (e.code == -32602) { return { ok: true }; } logger.error({ mint: poolKeys.baseMint }, `Failed to check if LP is burned`); } return { ok: false, message: 'Failed to check if LP is burned' }; } } ================================================ FILE: filters/index.ts ================================================ export * from './burn.filter'; export * from './mutable.filter'; export * from './pool-filters'; export * from './pool-size.filter'; export * from './renounced.filter'; ================================================ FILE: filters/mutable.filter.ts ================================================ import { Filter, FilterResult } from './pool-filters'; import { Connection } from '@solana/web3.js'; import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; import { getPdaMetadataKey } from '@raydium-io/raydium-sdk'; import { MetadataAccountData, MetadataAccountDataArgs } from '@metaplex-foundation/mpl-token-metadata'; import { Serializer } from '@metaplex-foundation/umi/serializers'; import { logger } from '../helpers'; export class MutableFilter implements Filter { private readonly errorMessage: string[] = []; constructor( private readonly connection: Connection, private readonly metadataSerializer: Serializer, private readonly checkMutable: boolean, private readonly checkSocials: boolean, ) { if (this.checkMutable) { this.errorMessage.push('mutable'); } if (this.checkSocials) { this.errorMessage.push('socials'); } } async execute(poolKeys: LiquidityPoolKeysV4): Promise { try { const metadataPDA = getPdaMetadataKey(poolKeys.baseMint); const metadataAccount = await this.connection.getAccountInfo(metadataPDA.publicKey, this.connection.commitment); if (!metadataAccount?.data) { return { ok: false, message: 'Mutable -> Failed to fetch account data' }; } const deserialize = this.metadataSerializer.deserialize(metadataAccount.data); const mutable = !this.checkMutable || deserialize[0].isMutable; const hasSocials = !this.checkSocials || (await this.hasSocials(deserialize[0])); const ok = !mutable && hasSocials; const message: string[] = []; if (mutable) { message.push('metadata can be changed'); } if (!hasSocials) { message.push('has no socials'); } return { ok: ok, message: ok ? undefined : `MutableSocials -> Token ${message.join(' and ')}` }; } catch (e) { logger.error({ mint: poolKeys.baseMint }, `MutableSocials -> Failed to check ${this.errorMessage.join(' and ')}`); } return { ok: false, message: `MutableSocials -> Failed to check ${this.errorMessage.join(' and ')}`, }; } private async hasSocials(metadata: MetadataAccountData) { const response = await fetch(metadata.uri); const data = await response.json(); return Object.values(data?.extensions ?? {}).some((value: any) => value !== null && value.length > 0); } } ================================================ FILE: filters/pool-filters.ts ================================================ import { Connection } from '@solana/web3.js'; import { LiquidityPoolKeysV4, Token, TokenAmount } from '@raydium-io/raydium-sdk'; import { getMetadataAccountDataSerializer } from '@metaplex-foundation/mpl-token-metadata'; import { BurnFilter } from './burn.filter'; import { MutableFilter } from './mutable.filter'; import { RenouncedFreezeFilter } from './renounced.filter'; import { PoolSizeFilter } from './pool-size.filter'; import { CHECK_IF_BURNED, CHECK_IF_FREEZABLE, CHECK_IF_MINT_IS_RENOUNCED, CHECK_IF_MUTABLE, CHECK_IF_SOCIALS, logger } from '../helpers'; export interface Filter { execute(poolKeysV4: LiquidityPoolKeysV4): Promise; } export interface FilterResult { ok: boolean; message?: string; } export interface PoolFilterArgs { minPoolSize: TokenAmount; maxPoolSize: TokenAmount; quoteToken: Token; } export class PoolFilters { private readonly filters: Filter[] = []; constructor( readonly connection: Connection, readonly args: PoolFilterArgs, ) { if (CHECK_IF_BURNED) { this.filters.push(new BurnFilter(connection)); } if (CHECK_IF_MINT_IS_RENOUNCED || CHECK_IF_FREEZABLE) { this.filters.push(new RenouncedFreezeFilter(connection, CHECK_IF_MINT_IS_RENOUNCED, CHECK_IF_FREEZABLE)); } if (CHECK_IF_MUTABLE || CHECK_IF_SOCIALS) { this.filters.push(new MutableFilter(connection, getMetadataAccountDataSerializer(), CHECK_IF_MUTABLE, CHECK_IF_SOCIALS)); } if (!args.minPoolSize.isZero() || !args.maxPoolSize.isZero()) { this.filters.push(new PoolSizeFilter(connection, args.quoteToken, args.minPoolSize, args.maxPoolSize)); } } public async execute(poolKeys: LiquidityPoolKeysV4): Promise { if (this.filters.length === 0) { return true; } const result = await Promise.all(this.filters.map((f) => f.execute(poolKeys))); const pass = result.every((r) => r.ok); if (pass) { return true; } for (const filterResult of result.filter((r) => !r.ok)) { logger.trace(filterResult.message); } return false; } } ================================================ FILE: filters/pool-size.filter.ts ================================================ import { Filter, FilterResult } from './pool-filters'; import { LiquidityPoolKeysV4, Token, TokenAmount } from '@raydium-io/raydium-sdk'; import { Connection } from '@solana/web3.js'; import { logger } from '../helpers'; export class PoolSizeFilter implements Filter { constructor( private readonly connection: Connection, private readonly quoteToken: Token, private readonly minPoolSize: TokenAmount, private readonly maxPoolSize: TokenAmount, ) {} async execute(poolKeys: LiquidityPoolKeysV4): Promise { try { const response = await this.connection.getTokenAccountBalance(poolKeys.quoteVault, this.connection.commitment); const poolSize = new TokenAmount(this.quoteToken, response.value.amount, true); let inRange = true; if (!this.maxPoolSize?.isZero()) { inRange = poolSize.raw.lte(this.maxPoolSize.raw); if (!inRange) { return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} > ${this.maxPoolSize.toFixed()}` }; } } if (!this.minPoolSize?.isZero()) { inRange = poolSize.raw.gte(this.minPoolSize.raw); if (!inRange) { return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} < ${this.minPoolSize.toFixed()}` }; } } return { ok: inRange }; } catch (error) { logger.error({ mint: poolKeys.baseMint }, `Failed to check pool size`); } return { ok: false, message: 'PoolSize -> Failed to check pool size' }; } } ================================================ FILE: filters/renounced.filter.ts ================================================ import { Filter, FilterResult } from './pool-filters'; import { MintLayout } from '@solana/spl-token'; import { Connection } from '@solana/web3.js'; import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; import { logger } from '../helpers'; export class RenouncedFreezeFilter implements Filter { private readonly errorMessage: string[] = []; constructor( private readonly connection: Connection, private readonly checkRenounced: boolean, private readonly checkFreezable: boolean, ) { if (this.checkRenounced) { this.errorMessage.push('mint'); } if (this.checkFreezable) { this.errorMessage.push('freeze'); } } async execute(poolKeys: LiquidityPoolKeysV4): Promise { try { const accountInfo = await this.connection.getAccountInfo(poolKeys.baseMint, this.connection.commitment); if (!accountInfo?.data) { return { ok: false, message: 'RenouncedFreeze -> Failed to fetch account data' }; } const deserialize = MintLayout.decode(accountInfo.data); const renounced = !this.checkRenounced || deserialize.mintAuthorityOption === 0; const freezable = !this.checkFreezable || deserialize.freezeAuthorityOption !== 0; const ok = renounced && !freezable; const message: string[] = []; if (!renounced) { message.push('mint'); } if (freezable) { message.push('freeze'); } return { ok: ok, message: ok ? undefined : `RenouncedFreeze -> Creator can ${message.join(' and ')} tokens` }; } catch (e) { logger.error( { mint: poolKeys.baseMint }, `RenouncedFreeze -> Failed to check if creator can ${this.errorMessage.join(' and ')} tokens`, ); } return { ok: false, message: `RenouncedFreeze -> Failed to check if creator can ${this.errorMessage.join(' and ')} tokens`, }; } } ================================================ FILE: helpers/constants.ts ================================================ import { Logger } from 'pino'; import dotenv from 'dotenv'; import { Commitment } from '@solana/web3.js'; import { logger } from './logger'; dotenv.config(); const retrieveEnvVariable = (variableName: string, logger: Logger) => { const variable = process.env[variableName] || ''; if (!variable) { logger.error(`${variableName} is not set`); process.exit(1); } return variable; }; // Wallet export const PRIVATE_KEY = retrieveEnvVariable('PRIVATE_KEY', logger); // Connection export const NETWORK = 'mainnet-beta'; export const COMMITMENT_LEVEL: Commitment = retrieveEnvVariable('COMMITMENT_LEVEL', logger) as Commitment; export const RPC_ENDPOINT = retrieveEnvVariable('RPC_ENDPOINT', logger); export const RPC_WEBSOCKET_ENDPOINT = retrieveEnvVariable('RPC_WEBSOCKET_ENDPOINT', logger); // Bot export const LOG_LEVEL = retrieveEnvVariable('LOG_LEVEL', logger); export const ONE_TOKEN_AT_A_TIME = retrieveEnvVariable('ONE_TOKEN_AT_A_TIME', logger) === 'true'; export const COMPUTE_UNIT_LIMIT = Number(retrieveEnvVariable('COMPUTE_UNIT_LIMIT', logger)); export const COMPUTE_UNIT_PRICE = Number(retrieveEnvVariable('COMPUTE_UNIT_PRICE', logger)); export const PRE_LOAD_EXISTING_MARKETS = retrieveEnvVariable('PRE_LOAD_EXISTING_MARKETS', logger) === 'true'; export const CACHE_NEW_MARKETS = retrieveEnvVariable('CACHE_NEW_MARKETS', logger) === 'true'; export const TRANSACTION_EXECUTOR = retrieveEnvVariable('TRANSACTION_EXECUTOR', logger); export const CUSTOM_FEE = retrieveEnvVariable('CUSTOM_FEE', logger); // Buy export const AUTO_BUY_DELAY = Number(retrieveEnvVariable('AUTO_BUY_DELAY', logger)); export const QUOTE_MINT = retrieveEnvVariable('QUOTE_MINT', logger); export const QUOTE_AMOUNT = retrieveEnvVariable('QUOTE_AMOUNT', logger); export const MAX_BUY_RETRIES = Number(retrieveEnvVariable('MAX_BUY_RETRIES', logger)); export const BUY_SLIPPAGE = Number(retrieveEnvVariable('BUY_SLIPPAGE', logger)); // Sell export const AUTO_SELL = retrieveEnvVariable('AUTO_SELL', logger) === 'true'; export const AUTO_SELL_DELAY = Number(retrieveEnvVariable('AUTO_SELL_DELAY', logger)); export const MAX_SELL_RETRIES = Number(retrieveEnvVariable('MAX_SELL_RETRIES', logger)); export const TAKE_PROFIT = Number(retrieveEnvVariable('TAKE_PROFIT', logger)); export const STOP_LOSS = Number(retrieveEnvVariable('STOP_LOSS', logger)); export const PRICE_CHECK_INTERVAL = Number(retrieveEnvVariable('PRICE_CHECK_INTERVAL', logger)); export const PRICE_CHECK_DURATION = Number(retrieveEnvVariable('PRICE_CHECK_DURATION', logger)); export const SELL_SLIPPAGE = Number(retrieveEnvVariable('SELL_SLIPPAGE', logger)); // Filters export const FILTER_CHECK_INTERVAL = Number(retrieveEnvVariable('FILTER_CHECK_INTERVAL', logger)); export const FILTER_CHECK_DURATION = Number(retrieveEnvVariable('FILTER_CHECK_DURATION', logger)); export const CONSECUTIVE_FILTER_MATCHES = Number(retrieveEnvVariable('CONSECUTIVE_FILTER_MATCHES', logger)); export const CHECK_IF_MUTABLE = retrieveEnvVariable('CHECK_IF_MUTABLE', logger) === 'true'; export const CHECK_IF_SOCIALS = retrieveEnvVariable('CHECK_IF_SOCIALS', logger) === 'true'; export const CHECK_IF_MINT_IS_RENOUNCED = retrieveEnvVariable('CHECK_IF_MINT_IS_RENOUNCED', logger) === 'true'; export const CHECK_IF_FREEZABLE = retrieveEnvVariable('CHECK_IF_FREEZABLE', logger) === 'true'; export const CHECK_IF_BURNED = retrieveEnvVariable('CHECK_IF_BURNED', logger) === 'true'; export const MIN_POOL_SIZE = retrieveEnvVariable('MIN_POOL_SIZE', logger); export const MAX_POOL_SIZE = retrieveEnvVariable('MAX_POOL_SIZE', logger); export const USE_SNIPE_LIST = retrieveEnvVariable('USE_SNIPE_LIST', logger) === 'true'; export const SNIPE_LIST_REFRESH_INTERVAL = Number(retrieveEnvVariable('SNIPE_LIST_REFRESH_INTERVAL', logger)); ================================================ FILE: helpers/index.ts ================================================ export * from './market'; export * from './liquidity'; export * from './logger'; export * from './constants'; export * from './token'; export * from './wallet'; export * from './promises' ================================================ FILE: helpers/liquidity.ts ================================================ import { PublicKey } from '@solana/web3.js'; import { Liquidity, LiquidityPoolKeys, LiquidityStateV4, MAINNET_PROGRAM_ID, Market } from '@raydium-io/raydium-sdk'; import { MinimalMarketLayoutV3 } from './market'; export function createPoolKeys( id: PublicKey, accountData: LiquidityStateV4, minimalMarketLayoutV3: MinimalMarketLayoutV3, ): LiquidityPoolKeys { return { id, baseMint: accountData.baseMint, quoteMint: accountData.quoteMint, lpMint: accountData.lpMint, baseDecimals: accountData.baseDecimal.toNumber(), quoteDecimals: accountData.quoteDecimal.toNumber(), lpDecimals: 5, version: 4, programId: MAINNET_PROGRAM_ID.AmmV4, authority: Liquidity.getAssociatedAuthority({ programId: MAINNET_PROGRAM_ID.AmmV4, }).publicKey, openOrders: accountData.openOrders, targetOrders: accountData.targetOrders, baseVault: accountData.baseVault, quoteVault: accountData.quoteVault, marketVersion: 3, marketProgramId: accountData.marketProgramId, marketId: accountData.marketId, marketAuthority: Market.getAssociatedAuthority({ programId: accountData.marketProgramId, marketId: accountData.marketId, }).publicKey, marketBaseVault: accountData.baseVault, marketQuoteVault: accountData.quoteVault, marketBids: minimalMarketLayoutV3.bids, marketAsks: minimalMarketLayoutV3.asks, marketEventQueue: minimalMarketLayoutV3.eventQueue, withdrawQueue: accountData.withdrawQueue, lpVault: accountData.lpVault, lookupTableAccount: PublicKey.default, }; } ================================================ FILE: helpers/logger.ts ================================================ import pino from 'pino'; const transport = pino.transport({ target: 'pino-pretty', }); export const logger = pino( { level: 'info', redact: ['poolKeys'], serializers: { error: pino.stdSerializers.err, }, base: undefined, }, transport, ); ================================================ FILE: helpers/market.ts ================================================ import { Commitment, Connection, PublicKey } from '@solana/web3.js'; import { GetStructureSchema, MARKET_STATE_LAYOUT_V3, publicKey, struct } from '@raydium-io/raydium-sdk'; export const MINIMAL_MARKET_STATE_LAYOUT_V3 = struct([publicKey('eventQueue'), publicKey('bids'), publicKey('asks')]); export type MinimalMarketStateLayoutV3 = typeof MINIMAL_MARKET_STATE_LAYOUT_V3; export type MinimalMarketLayoutV3 = GetStructureSchema; export async function getMinimalMarketV3( connection: Connection, marketId: PublicKey, commitment?: Commitment, ): Promise { const marketInfo = await connection.getAccountInfo(marketId, { commitment, dataSlice: { offset: MARKET_STATE_LAYOUT_V3.offsetOf('eventQueue'), length: 32 * 3, }, }); return MINIMAL_MARKET_STATE_LAYOUT_V3.decode(marketInfo!.data); } ================================================ FILE: helpers/promises.ts ================================================ export const sleep = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms)); ================================================ FILE: helpers/token.ts ================================================ import { Token } from '@raydium-io/raydium-sdk'; import { TOKEN_PROGRAM_ID } from '@solana/spl-token'; import { PublicKey } from '@solana/web3.js'; export function getToken(token: string) { switch (token) { case 'WSOL': { return Token.WSOL; } case 'USDC': { return new Token( TOKEN_PROGRAM_ID, new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), 6, 'USDC', 'USDC', ); } default: { throw new Error(`Unsupported quote mint "${token}". Supported values are USDC and WSOL`); } } } ================================================ FILE: helpers/wallet.ts ================================================ import { Keypair } from '@solana/web3.js'; import bs58 from 'bs58'; import { mnemonicToSeedSync } from 'bip39'; import { derivePath } from 'ed25519-hd-key'; export function getWallet(wallet: string): Keypair { // most likely someone pasted the private key in binary format if (wallet.startsWith('[')) { const raw = new Uint8Array(JSON.parse(wallet)) return Keypair.fromSecretKey(raw); } // most likely someone pasted mnemonic if (wallet.split(' ').length > 1) { const seed = mnemonicToSeedSync(wallet, ''); const path = `m/44'/501'/0'/0'`; // we assume it's first path return Keypair.fromSeed(derivePath(path, seed.toString('hex')).key); } // most likely someone pasted base58 encoded private key return Keypair.fromSecretKey(bs58.decode(wallet)); } ================================================ FILE: index.ts ================================================ import { MarketCache, PoolCache } from './cache'; import { Listeners } from './listeners'; import { Connection, KeyedAccountInfo, Keypair } from '@solana/web3.js'; import { LIQUIDITY_STATE_LAYOUT_V4, MARKET_STATE_LAYOUT_V3, Token, TokenAmount } from '@raydium-io/raydium-sdk'; import { AccountLayout, getAssociatedTokenAddressSync } from '@solana/spl-token'; import { Bot, BotConfig } from './bot'; import { DefaultTransactionExecutor, TransactionExecutor } from './transactions'; import { getToken, getWallet, logger, COMMITMENT_LEVEL, RPC_ENDPOINT, RPC_WEBSOCKET_ENDPOINT, PRE_LOAD_EXISTING_MARKETS, LOG_LEVEL, CHECK_IF_MUTABLE, CHECK_IF_MINT_IS_RENOUNCED, CHECK_IF_FREEZABLE, CHECK_IF_BURNED, QUOTE_MINT, MAX_POOL_SIZE, MIN_POOL_SIZE, QUOTE_AMOUNT, PRIVATE_KEY, USE_SNIPE_LIST, ONE_TOKEN_AT_A_TIME, AUTO_SELL_DELAY, MAX_SELL_RETRIES, AUTO_SELL, MAX_BUY_RETRIES, AUTO_BUY_DELAY, COMPUTE_UNIT_LIMIT, COMPUTE_UNIT_PRICE, CACHE_NEW_MARKETS, TAKE_PROFIT, STOP_LOSS, BUY_SLIPPAGE, SELL_SLIPPAGE, PRICE_CHECK_DURATION, PRICE_CHECK_INTERVAL, SNIPE_LIST_REFRESH_INTERVAL, TRANSACTION_EXECUTOR, CUSTOM_FEE, FILTER_CHECK_INTERVAL, FILTER_CHECK_DURATION, CONSECUTIVE_FILTER_MATCHES, } from './helpers'; import { version } from './package.json'; import { WarpTransactionExecutor } from './transactions/warp-transaction-executor'; import { JitoTransactionExecutor } from './transactions/jito-rpc-transaction-executor'; const connection = new Connection(RPC_ENDPOINT, { wsEndpoint: RPC_WEBSOCKET_ENDPOINT, commitment: COMMITMENT_LEVEL, }); function printDetails(wallet: Keypair, quoteToken: Token, bot: Bot) { logger.info(` .. :-===++++- .-==+++++++- =+++++++++- ..:::--===+=.=: .+++++++++++:=+++++++++: .==+++++++++++++++=:+++: .+++++++++++.=++++++++-. .-+++++++++++++++=:=++++- .+++++++++=:.=+++++-::-. -:+++++++++++++=:+++++++- .++++++++-:- =+++++=-: -:++++++=++++=:++++=++++= .++++++++++- =+++++: -:++++-:=++=:++++=:-+++++:+++++====--:::::::. ::=+-:::==:=+++=::-:--::::::::::---------::. ::-: .::::::::. --------:::.. :- .:.-:::. WARP DRIVE ACTIVATED 🚀🐟 Made with ❤️ by humans. Version: ${version} `); const botConfig = bot.config; logger.info('------- CONFIGURATION START -------'); logger.info(`Wallet: ${wallet.publicKey.toString()}`); logger.info('- Bot -'); logger.info( `Using ${TRANSACTION_EXECUTOR} executer: ${bot.isWarp || bot.isJito || (TRANSACTION_EXECUTOR === 'default' ? true : false)}`, ); if (bot.isWarp || bot.isJito) { logger.info(`${TRANSACTION_EXECUTOR} fee: ${CUSTOM_FEE}`); } else { logger.info(`Compute Unit limit: ${botConfig.unitLimit}`); logger.info(`Compute Unit price (micro lamports): ${botConfig.unitPrice}`); } logger.info(`Single token at the time: ${botConfig.oneTokenAtATime}`); logger.info(`Pre load existing markets: ${PRE_LOAD_EXISTING_MARKETS}`); logger.info(`Cache new markets: ${CACHE_NEW_MARKETS}`); logger.info(`Log level: ${LOG_LEVEL}`); logger.info('- Buy -'); logger.info(`Buy amount: ${botConfig.quoteAmount.toFixed()} ${botConfig.quoteToken.name}`); logger.info(`Auto buy delay: ${botConfig.autoBuyDelay} ms`); logger.info(`Max buy retries: ${botConfig.maxBuyRetries}`); logger.info(`Buy amount (${quoteToken.symbol}): ${botConfig.quoteAmount.toFixed()}`); logger.info(`Buy slippage: ${botConfig.buySlippage}%`); logger.info('- Sell -'); logger.info(`Auto sell: ${AUTO_SELL}`); logger.info(`Auto sell delay: ${botConfig.autoSellDelay} ms`); logger.info(`Max sell retries: ${botConfig.maxSellRetries}`); logger.info(`Sell slippage: ${botConfig.sellSlippage}%`); logger.info(`Price check interval: ${botConfig.priceCheckInterval} ms`); logger.info(`Price check duration: ${botConfig.priceCheckDuration} ms`); logger.info(`Take profit: ${botConfig.takeProfit}%`); logger.info(`Stop loss: ${botConfig.stopLoss}%`); logger.info('- Snipe list -'); logger.info(`Snipe list: ${botConfig.useSnipeList}`); logger.info(`Snipe list refresh interval: ${SNIPE_LIST_REFRESH_INTERVAL} ms`); if (botConfig.useSnipeList) { logger.info('- Filters -'); logger.info(`Filters are disabled when snipe list is on`); } else { logger.info('- Filters -'); logger.info(`Filter check interval: ${botConfig.filterCheckInterval} ms`); logger.info(`Filter check duration: ${botConfig.filterCheckDuration} ms`); logger.info(`Consecutive filter matches: ${botConfig.consecutiveMatchCount}`); logger.info(`Check renounced: ${botConfig.checkRenounced}`); logger.info(`Check freezable: ${botConfig.checkFreezable}`); logger.info(`Check burned: ${botConfig.checkBurned}`); logger.info(`Min pool size: ${botConfig.minPoolSize.toFixed()}`); logger.info(`Max pool size: ${botConfig.maxPoolSize.toFixed()}`); } logger.info('------- CONFIGURATION END -------'); logger.info('Bot is running! Press CTRL + C to stop it.'); } const runListener = async () => { logger.level = LOG_LEVEL; logger.info('Bot is starting...'); const marketCache = new MarketCache(connection); const poolCache = new PoolCache(); let txExecutor: TransactionExecutor; switch (TRANSACTION_EXECUTOR) { case 'warp': { txExecutor = new WarpTransactionExecutor(CUSTOM_FEE); break; } case 'jito': { txExecutor = new JitoTransactionExecutor(CUSTOM_FEE, connection); break; } default: { txExecutor = new DefaultTransactionExecutor(connection); break; } } const wallet = getWallet(PRIVATE_KEY.trim()); const quoteToken = getToken(QUOTE_MINT); const botConfig = { wallet, quoteAta: getAssociatedTokenAddressSync(quoteToken.mint, wallet.publicKey), checkRenounced: CHECK_IF_MINT_IS_RENOUNCED, checkFreezable: CHECK_IF_FREEZABLE, checkBurned: CHECK_IF_BURNED, minPoolSize: new TokenAmount(quoteToken, MIN_POOL_SIZE, false), maxPoolSize: new TokenAmount(quoteToken, MAX_POOL_SIZE, false), quoteToken, quoteAmount: new TokenAmount(quoteToken, QUOTE_AMOUNT, false), oneTokenAtATime: ONE_TOKEN_AT_A_TIME, useSnipeList: USE_SNIPE_LIST, autoSell: AUTO_SELL, autoSellDelay: AUTO_SELL_DELAY, maxSellRetries: MAX_SELL_RETRIES, autoBuyDelay: AUTO_BUY_DELAY, maxBuyRetries: MAX_BUY_RETRIES, unitLimit: COMPUTE_UNIT_LIMIT, unitPrice: COMPUTE_UNIT_PRICE, takeProfit: TAKE_PROFIT, stopLoss: STOP_LOSS, buySlippage: BUY_SLIPPAGE, sellSlippage: SELL_SLIPPAGE, priceCheckInterval: PRICE_CHECK_INTERVAL, priceCheckDuration: PRICE_CHECK_DURATION, filterCheckInterval: FILTER_CHECK_INTERVAL, filterCheckDuration: FILTER_CHECK_DURATION, consecutiveMatchCount: CONSECUTIVE_FILTER_MATCHES, }; const bot = new Bot(connection, marketCache, poolCache, txExecutor, botConfig); const valid = await bot.validate(); if (!valid) { logger.info('Bot is exiting...'); process.exit(1); } if (PRE_LOAD_EXISTING_MARKETS) { await marketCache.init({ quoteToken }); } const runTimestamp = Math.floor(new Date().getTime() / 1000); const listeners = new Listeners(connection); await listeners.start({ walletPublicKey: wallet.publicKey, quoteToken, autoSell: AUTO_SELL, cacheNewMarkets: CACHE_NEW_MARKETS, }); listeners.on('market', (updatedAccountInfo: KeyedAccountInfo) => { const marketState = MARKET_STATE_LAYOUT_V3.decode(updatedAccountInfo.accountInfo.data); marketCache.save(updatedAccountInfo.accountId.toString(), marketState); }); listeners.on('pool', async (updatedAccountInfo: KeyedAccountInfo) => { const poolState = LIQUIDITY_STATE_LAYOUT_V4.decode(updatedAccountInfo.accountInfo.data); const poolOpenTime = parseInt(poolState.poolOpenTime.toString()); const exists = await poolCache.get(poolState.baseMint.toString()); if (!exists && poolOpenTime > runTimestamp) { poolCache.save(updatedAccountInfo.accountId.toString(), poolState); await bot.buy(updatedAccountInfo.accountId, poolState); } }); listeners.on('wallet', async (updatedAccountInfo: KeyedAccountInfo) => { const accountData = AccountLayout.decode(updatedAccountInfo.accountInfo.data); if (accountData.mint.equals(quoteToken.mint)) { return; } await bot.sell(updatedAccountInfo.accountId, accountData); }); printDetails(wallet, quoteToken, bot); }; runListener(); ================================================ FILE: listeners/index.ts ================================================ export * from './listeners'; ================================================ FILE: listeners/listeners.ts ================================================ import { LIQUIDITY_STATE_LAYOUT_V4, MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from '@raydium-io/raydium-sdk'; import bs58 from 'bs58'; import { Connection, PublicKey } from '@solana/web3.js'; import { TOKEN_PROGRAM_ID } from '@solana/spl-token'; import { EventEmitter } from 'events'; export class Listeners extends EventEmitter { private subscriptions: number[] = []; constructor(private readonly connection: Connection) { super(); } public async start(config: { walletPublicKey: PublicKey; quoteToken: Token; autoSell: boolean; cacheNewMarkets: boolean; }) { if (config.cacheNewMarkets) { const openBookSubscription = await this.subscribeToOpenBookMarkets(config); this.subscriptions.push(openBookSubscription); } const raydiumSubscription = await this.subscribeToRaydiumPools(config); this.subscriptions.push(raydiumSubscription); if (config.autoSell) { const walletSubscription = await this.subscribeToWalletChanges(config); this.subscriptions.push(walletSubscription); } } private async subscribeToOpenBookMarkets(config: { quoteToken: Token }) { return this.connection.onProgramAccountChange( MAINNET_PROGRAM_ID.OPENBOOK_MARKET, async (updatedAccountInfo) => { this.emit('market', updatedAccountInfo); }, this.connection.commitment, [ { dataSize: MARKET_STATE_LAYOUT_V3.span }, { memcmp: { offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'), bytes: config.quoteToken.mint.toBase58(), }, }, ], ); } private async subscribeToRaydiumPools(config: { quoteToken: Token }) { return this.connection.onProgramAccountChange( MAINNET_PROGRAM_ID.AmmV4, async (updatedAccountInfo) => { this.emit('pool', updatedAccountInfo); }, this.connection.commitment, [ { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span }, { memcmp: { offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'), bytes: config.quoteToken.mint.toBase58(), }, }, { memcmp: { offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'), bytes: MAINNET_PROGRAM_ID.OPENBOOK_MARKET.toBase58(), }, }, { memcmp: { offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'), bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]), }, }, ], ); } private async subscribeToWalletChanges(config: { walletPublicKey: PublicKey }) { return this.connection.onProgramAccountChange( TOKEN_PROGRAM_ID, async (updatedAccountInfo) => { this.emit('wallet', updatedAccountInfo); }, this.connection.commitment, [ { dataSize: 165, }, { memcmp: { offset: 32, bytes: config.walletPublicKey.toBase58(), }, }, ], ); } public async stop() { for (let i = this.subscriptions.length; i >= 0; --i) { const subscription = this.subscriptions[i]; await this.connection.removeAccountChangeListener(subscription); this.subscriptions.splice(i, 1); } } } ================================================ FILE: package.json ================================================ { "name": "warp-solana-bot", "author": "Filip Dundjer", "homepage": "https://warp.id", "version": "2.0.1", "scripts": { "start": "ts-node index.ts", "tsc": "tsc --noEmit" }, "dependencies": { "@metaplex-foundation/mpl-token-metadata": "^3.2.1", "@raydium-io/raydium-sdk": "^1.3.1-beta.47", "@solana/spl-token": "^0.4.0", "@solana/web3.js": "^1.89.1", "async-mutex": "^0.5.0", "axios": "^1.6.8", "bigint-buffer": "^1.1.5", "bip39": "^3.1.0", "bn.js": "^5.2.1", "bs58": "^5.0.0", "dotenv": "^16.4.1", "ed25519-hd-key": "^1.3.0", "i": "^0.3.7", "npm": "^10.5.2", "pino": "^8.18.0", "pino-pretty": "^10.3.1", "pino-std-serializers": "^6.2.2" }, "devDependencies": { "@types/bn.js": "^5.1.5", "prettier": "^3.2.4", "ts-node": "^10.9.2", "typescript": "^5.3.3" } } ================================================ FILE: snipe-list.txt ================================================ ================================================ FILE: transactions/default-transaction-executor.ts ================================================ import { BlockhashWithExpiryBlockHeight, Connection, Keypair, Transaction, VersionedTransaction, } from '@solana/web3.js'; import { TransactionExecutor } from './transaction-executor.interface'; import { logger } from '../helpers'; export class DefaultTransactionExecutor implements TransactionExecutor { constructor(private readonly connection: Connection) {} public async executeAndConfirm( transaction: VersionedTransaction, payer: Keypair, latestBlockhash: BlockhashWithExpiryBlockHeight, ): Promise<{ confirmed: boolean; signature?: string, error?: string }> { logger.debug('Executing transaction...'); const signature = await this.execute(transaction); logger.debug({ signature }, 'Confirming transaction...'); return this.confirm(signature, latestBlockhash); } private async execute(transaction: Transaction | VersionedTransaction) { return this.connection.sendRawTransaction(transaction.serialize(), { preflightCommitment: this.connection.commitment, }); } private async confirm(signature: string, latestBlockhash: BlockhashWithExpiryBlockHeight) { const confirmation = await this.connection.confirmTransaction( { signature, lastValidBlockHeight: latestBlockhash.lastValidBlockHeight, blockhash: latestBlockhash.blockhash, }, this.connection.commitment, ); return { confirmed: !confirmation.value.err, signature }; } } ================================================ FILE: transactions/index.ts ================================================ export * from './default-transaction-executor'; export * from './transaction-executor.interface'; ================================================ FILE: transactions/jito-rpc-transaction-executor.ts ================================================ import { BlockhashWithExpiryBlockHeight, Keypair, PublicKey, SystemProgram, Connection, TransactionMessage, VersionedTransaction, } from '@solana/web3.js'; import { TransactionExecutor } from './transaction-executor.interface'; import { logger } from '../helpers'; import axios, { AxiosError } from 'axios'; import bs58 from 'bs58'; import { Currency, CurrencyAmount } from '@raydium-io/raydium-sdk'; export class JitoTransactionExecutor implements TransactionExecutor { // https://jito-labs.gitbook.io/mev/searcher-resources/json-rpc-api-reference/bundles/gettipaccounts private jitpTipAccounts = [ 'Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghXLvLkY', 'DttWaMuVvTiduZRnguLF7jNxTgiMBZ1hyAumKUiL2KRL', '96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5', '3AVi9Tg9Uo68tJfuvoKvqKNWKkC5wPdSSdeBnizKZ6jT', 'HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe', 'ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt6iGPaS49', 'ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt', 'DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh', ]; private JitoFeeWallet: PublicKey; constructor( private readonly jitoFee: string, private readonly connection: Connection, ) { this.JitoFeeWallet = this.getRandomValidatorKey(); } private getRandomValidatorKey(): PublicKey { const randomValidator = this.jitpTipAccounts[Math.floor(Math.random() * this.jitpTipAccounts.length)]; return new PublicKey(randomValidator); } public async executeAndConfirm( transaction: VersionedTransaction, payer: Keypair, latestBlockhash: BlockhashWithExpiryBlockHeight, ): Promise<{ confirmed: boolean; signature?: string; error?: string }> { logger.debug('Starting Jito transaction execution...'); this.JitoFeeWallet = this.getRandomValidatorKey(); // Update wallet key each execution logger.trace(`Selected Jito fee wallet: ${this.JitoFeeWallet.toBase58()}`); try { const fee = new CurrencyAmount(Currency.SOL, this.jitoFee, false).raw.toNumber(); logger.trace(`Calculated fee: ${fee} lamports`); const jitTipTxFeeMessage = new TransactionMessage({ payerKey: payer.publicKey, recentBlockhash: latestBlockhash.blockhash, instructions: [ SystemProgram.transfer({ fromPubkey: payer.publicKey, toPubkey: this.JitoFeeWallet, lamports: fee, }), ], }).compileToV0Message(); const jitoFeeTx = new VersionedTransaction(jitTipTxFeeMessage); jitoFeeTx.sign([payer]); const jitoTxsignature = bs58.encode(jitoFeeTx.signatures[0]); // Serialize the transactions once here const serializedjitoFeeTx = bs58.encode(jitoFeeTx.serialize()); const serializedTransaction = bs58.encode(transaction.serialize()); const serializedTransactions = [serializedjitoFeeTx, serializedTransaction]; // https://jito-labs.gitbook.io/mev/searcher-resources/json-rpc-api-reference/url const endpoints = [ 'https://mainnet.block-engine.jito.wtf/api/v1/bundles', 'https://amsterdam.mainnet.block-engine.jito.wtf/api/v1/bundles', 'https://frankfurt.mainnet.block-engine.jito.wtf/api/v1/bundles', 'https://ny.mainnet.block-engine.jito.wtf/api/v1/bundles', 'https://tokyo.mainnet.block-engine.jito.wtf/api/v1/bundles', ]; const requests = endpoints.map((url) => axios.post(url, { jsonrpc: '2.0', id: 1, method: 'sendBundle', params: [serializedTransactions], }), ); logger.trace('Sending transactions to endpoints...'); const results = await Promise.all(requests.map((p) => p.catch((e) => e))); const successfulResults = results.filter((result) => !(result instanceof Error)); if (successfulResults.length > 0) { logger.trace(`At least one successful response`); logger.debug(`Confirming jito transaction...`); return await this.confirm(jitoTxsignature, latestBlockhash); } else { logger.debug(`No successful responses received for jito`); } return { confirmed: false }; } catch (error) { if (error instanceof AxiosError) { logger.trace({ error: error.response?.data }, 'Failed to execute jito transaction'); } logger.error('Error during transaction execution', error); return { confirmed: false }; } } private async confirm(signature: string, latestBlockhash: BlockhashWithExpiryBlockHeight) { const confirmation = await this.connection.confirmTransaction( { signature, lastValidBlockHeight: latestBlockhash.lastValidBlockHeight, blockhash: latestBlockhash.blockhash, }, this.connection.commitment, ); return { confirmed: !confirmation.value.err, signature }; } } ================================================ FILE: transactions/transaction-executor.interface.ts ================================================ import { BlockhashWithExpiryBlockHeight, Keypair, VersionedTransaction } from '@solana/web3.js'; export interface TransactionExecutor { executeAndConfirm( transaction: VersionedTransaction, payer: Keypair, latestBlockHash: BlockhashWithExpiryBlockHeight, ): Promise<{ confirmed: boolean; signature?: string, error?: string }>; } ================================================ FILE: transactions/warp-transaction-executor.ts ================================================ import { BlockhashWithExpiryBlockHeight, Keypair, PublicKey, SystemProgram, TransactionMessage, VersionedTransaction, } from '@solana/web3.js'; import { TransactionExecutor } from './transaction-executor.interface'; import { logger } from '../helpers'; import axios, { AxiosError } from 'axios'; import bs58 from 'bs58'; import { Currency, CurrencyAmount } from '@raydium-io/raydium-sdk'; export class WarpTransactionExecutor implements TransactionExecutor { private readonly warpFeeWallet = new PublicKey('WARPzUMPnycu9eeCZ95rcAUxorqpBqHndfV3ZP5FSyS'); constructor(private readonly warpFee: string) {} public async executeAndConfirm( transaction: VersionedTransaction, payer: Keypair, latestBlockhash: BlockhashWithExpiryBlockHeight, ): Promise<{ confirmed: boolean; signature?: string; error?: string }> { logger.debug('Executing transaction...'); try { const fee = new CurrencyAmount(Currency.SOL, this.warpFee, false).raw.toNumber(); const warpFeeMessage = new TransactionMessage({ payerKey: payer.publicKey, recentBlockhash: latestBlockhash.blockhash, instructions: [ SystemProgram.transfer({ fromPubkey: payer.publicKey, toPubkey: this.warpFeeWallet, lamports: fee, }), ], }).compileToV0Message(); const warpFeeTx = new VersionedTransaction(warpFeeMessage); warpFeeTx.sign([payer]); const response = await axios.post<{ confirmed: boolean; signature: string; error?: string }>( 'https://tx.warp.id/transaction/execute', { transactions: [bs58.encode(warpFeeTx.serialize()), bs58.encode(transaction.serialize())], latestBlockhash, }, { timeout: 100000, }, ); return response.data; } catch (error) { if (error instanceof AxiosError) { logger.trace({ error: error.response?.data }, 'Failed to execute warp transaction'); } } return { confirmed: false }; } } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { /* Visit https://aka.ms/tsconfig to read more about this file */ /* Projects */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ /* Language and Environment */ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ // "jsx": "preserve", /* Specify what JSX code is generated. */ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ /* Modules */ "module": "commonjs", /* Specify what module code is generated. */ // "rootDir": "./", /* Specify the root folder within your source files. */ // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ // "types": [], /* Specify type package names to be included without being referenced in a source file. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ "resolveJsonModule": true, /* Enable importing .json files. */ // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ /* JavaScript Support */ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ /* Emit */ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ // "declarationMap": true, /* Create sourcemaps for d.ts files. */ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ // "outDir": "./", /* Specify an output folder for all emitted files. */ // "removeComments": true, /* Disable emitting comments. */ // "noEmit": true, /* Disable emitting files from a compilation. */ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ // "newLine": "crlf", /* Set the newline character for emitting files. */ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ /* Interop Constraints */ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ /* Type Checking */ "strict": true, /* Enable all strict type-checking options. */ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ /* Completeness */ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ "skipLibCheck": true /* Skip type checking all .d.ts files. */ } }