├── snipe-list.txt ├── src ├── listeners │ ├── index.ts │ └── listeners.ts ├── helpers │ ├── promises.ts │ ├── index.ts │ ├── logger.ts │ ├── token.ts │ ├── wallet.ts │ ├── market.ts │ ├── config.ts │ ├── liquidity.ts │ └── constants.ts ├── cache │ ├── index.ts │ ├── pool.cache.ts │ ├── snipe-list.cache.ts │ └── market.cache.ts ├── transactions │ ├── index.ts │ ├── transaction-executor.interface.ts │ ├── default-transaction-executor.ts │ └── warp-transaction-executor.ts ├── filters │ ├── index.ts │ ├── burn.filter.ts │ ├── renounced.filter.ts │ ├── pool-size.filter.ts │ └── pool-filters.ts ├── index.ts └── bot.ts ├── docs ├── output.png ├── wsol.png ├── readme │ ├── wsol.png │ └── output.png └── install.md ├── .prettierrc ├── cache ├── index.ts ├── pool.cache.ts ├── snipe-list.cache.ts └── market.cache.ts ├── README.md ├── package.json ├── .env.copy ├── LICENSE.md ├── .gitignore ├── tsconfig.json └── bot.ts /snipe-list.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/listeners/index.ts: -------------------------------------------------------------------------------- 1 | export * from './listeners'; 2 | -------------------------------------------------------------------------------- /docs/output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenBotDev/oldbot/HEAD/docs/output.png -------------------------------------------------------------------------------- /docs/wsol.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenBotDev/oldbot/HEAD/docs/wsol.png -------------------------------------------------------------------------------- /docs/readme/wsol.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenBotDev/oldbot/HEAD/docs/readme/wsol.png -------------------------------------------------------------------------------- /docs/readme/output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenBotDev/oldbot/HEAD/docs/readme/output.png -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all", 4 | "printWidth": 120 5 | } -------------------------------------------------------------------------------- /src/helpers/promises.ts: -------------------------------------------------------------------------------- 1 | export const sleep = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms)); 2 | -------------------------------------------------------------------------------- /cache/index.ts: -------------------------------------------------------------------------------- 1 | export * from './market.cache'; 2 | export * from './pool.cache'; 3 | export * from './snipe-list.cache'; 4 | -------------------------------------------------------------------------------- /src/cache/index.ts: -------------------------------------------------------------------------------- 1 | export * from './market.cache'; 2 | export * from './pool.cache'; 3 | export * from './snipe-list.cache'; 4 | -------------------------------------------------------------------------------- /src/transactions/index.ts: -------------------------------------------------------------------------------- 1 | export * from './default-transaction-executor'; 2 | export * from './transaction-executor.interface'; 3 | -------------------------------------------------------------------------------- /src/filters/index.ts: -------------------------------------------------------------------------------- 1 | export * from './burn.filter'; 2 | export * from './pool-filters'; 3 | export * from './pool-size.filter'; 4 | export * from './renounced.filter'; 5 | -------------------------------------------------------------------------------- /src/helpers/index.ts: -------------------------------------------------------------------------------- 1 | export * from './market'; 2 | export * from './liquidity'; 3 | export * from './logger'; 4 | export * from './constants'; 5 | export * from './token'; 6 | export * from './wallet'; 7 | export * from './promises' 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # openbot 2 | 3 | Sniperbot on Solana 4 | 5 | Roadmap 6 | 7 | * web frontend 8 | * improve time of buy from launch 9 | * improve buy/sell round trip time 10 | * advanced selling condition Trailing/Stop 11 | * reliable 12 | * analytics on server 13 | 14 | [install](install.md) -------------------------------------------------------------------------------- /src/helpers/logger.ts: -------------------------------------------------------------------------------- 1 | import pino from 'pino'; 2 | 3 | const transport = pino.transport({ 4 | target: 'pino-pretty', 5 | }); 6 | 7 | export const logger = pino( 8 | { 9 | level: 'info', 10 | redact: ['poolKeys'], 11 | serializers: { 12 | error: pino.stdSerializers.err, 13 | }, 14 | base: undefined, 15 | }, 16 | transport, 17 | ); 18 | -------------------------------------------------------------------------------- /src/transactions/transaction-executor.interface.ts: -------------------------------------------------------------------------------- 1 | import { BlockhashWithExpiryBlockHeight, Keypair, MessageV0, Signer, VersionedTransaction } from '@solana/web3.js'; 2 | 3 | export interface TransactionExecutor { 4 | executeAndConfirm( 5 | transaction: VersionedTransaction, 6 | payer: Keypair, 7 | latestBlockHash: BlockhashWithExpiryBlockHeight, 8 | ): Promise<{ confirmed: boolean; signature?: string }>; 9 | } 10 | -------------------------------------------------------------------------------- /src/helpers/token.ts: -------------------------------------------------------------------------------- 1 | import { Token } from '@raydium-io/raydium-sdk'; 2 | import { TOKEN_PROGRAM_ID } from '@solana/spl-token'; 3 | import { PublicKey } from '@solana/web3.js'; 4 | 5 | export function getToken(token: string) { 6 | switch (token) { 7 | case 'WSOL': { 8 | return Token.WSOL; 9 | } 10 | case 'USDC': { 11 | return new Token( 12 | TOKEN_PROGRAM_ID, 13 | new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), 14 | 6, 15 | 'USDC', 16 | 'USDC', 17 | ); 18 | } 19 | default: { 20 | throw new Error(`Unsupported quote mint "${token}". Supported values are USDC and WSOL`); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /cache/pool.cache.ts: -------------------------------------------------------------------------------- 1 | import { LiquidityStateV4 } from '@raydium-io/raydium-sdk'; 2 | import { logger } from '../helpers'; 3 | 4 | export class PoolCache { 5 | private readonly keys: Map = new Map< 6 | string, 7 | { id: string; state: LiquidityStateV4 } 8 | >(); 9 | 10 | public save(id: string, state: LiquidityStateV4) { 11 | if (!this.keys.has(state.baseMint.toString())) { 12 | logger.trace(`Caching new pool for mint: ${state.baseMint.toString()}`); 13 | this.keys.set(state.baseMint.toString(), { id, state }); 14 | } 15 | } 16 | 17 | public async get(mint: string): Promise<{ id: string; state: LiquidityStateV4 }> { 18 | return this.keys.get(mint)!; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/cache/pool.cache.ts: -------------------------------------------------------------------------------- 1 | import { LiquidityStateV4 } from '@raydium-io/raydium-sdk'; 2 | import { logger } from '../helpers'; 3 | 4 | export class PoolCache { 5 | private readonly keys: Map = new Map< 6 | string, 7 | { id: string; state: LiquidityStateV4 } 8 | >(); 9 | 10 | public save(id: string, state: LiquidityStateV4) { 11 | if (!this.keys.has(state.baseMint.toString())) { 12 | logger.trace(`Caching new pool for mint: ${state.baseMint.toString()}`); 13 | this.keys.set(state.baseMint.toString(), { id, state }); 14 | } 15 | } 16 | 17 | public async get(mint: string): Promise<{ id: string; state: LiquidityStateV4 }> { 18 | return this.keys.get(mint)!; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/helpers/wallet.ts: -------------------------------------------------------------------------------- 1 | import { Keypair } from '@solana/web3.js'; 2 | import bs58 from 'bs58'; 3 | import { mnemonicToSeedSync } from 'bip39'; 4 | import { derivePath } from 'ed25519-hd-key'; 5 | 6 | export function getWallet(wallet: string): Keypair { 7 | // most likely someone pasted the private key in binary format 8 | if (wallet.startsWith('[')) { 9 | return Keypair.fromSecretKey(JSON.parse(wallet)); 10 | } 11 | 12 | // most likely someone pasted mnemonic 13 | if (wallet.split(' ').length > 1) { 14 | const seed = mnemonicToSeedSync(wallet, ''); 15 | const path = `m/44'/501'/0'/0'`; // we assume it's first path 16 | return Keypair.fromSeed(derivePath(path, seed.toString('hex')).key); 17 | } 18 | 19 | // most likely someone pasted base58 encoded private key 20 | return Keypair.fromSecretKey(bs58.decode(wallet)); 21 | } 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "openbot", 3 | "author": "openbot", 4 | "version": "2.0.0", 5 | "scripts": { 6 | "start": "ts-node src/index.ts", 7 | "tsc": "tsc --noEmit" 8 | }, 9 | "dependencies": { 10 | "@raydium-io/raydium-sdk": "^1.3.1-beta.47", 11 | "@solana/spl-token": "^0.4.0", 12 | "@solana/web3.js": "^1.89.1", 13 | "async-mutex": "^0.5.0", 14 | "axios": "^1.6.8", 15 | "bigint-buffer": "^1.1.5", 16 | "bip39": "^3.1.0", 17 | "bn.js": "^5.2.1", 18 | "bs58": "^5.0.0", 19 | "dotenv": "^16.4.1", 20 | "ed25519-hd-key": "^1.3.0", 21 | "i": "^0.3.7", 22 | "npm": "^10.5.2", 23 | "pino": "^8.18.0", 24 | "pino-pretty": "^10.3.1", 25 | "pino-std-serializers": "^6.2.2" 26 | }, 27 | "devDependencies": { 28 | "@types/bn.js": "^5.1.5", 29 | "prettier": "^3.2.4", 30 | "ts-node": "^10.9.2", 31 | "typescript": "^5.3.3" 32 | } 33 | } -------------------------------------------------------------------------------- /src/helpers/market.ts: -------------------------------------------------------------------------------- 1 | import { Commitment, Connection, PublicKey } from '@solana/web3.js'; 2 | import { GetStructureSchema, MARKET_STATE_LAYOUT_V3, publicKey, struct } from '@raydium-io/raydium-sdk'; 3 | 4 | export const MINIMAL_MARKET_STATE_LAYOUT_V3 = struct([publicKey('eventQueue'), publicKey('bids'), publicKey('asks')]); 5 | export type MinimalMarketStateLayoutV3 = typeof MINIMAL_MARKET_STATE_LAYOUT_V3; 6 | export type MinimalMarketLayoutV3 = GetStructureSchema; 7 | 8 | export async function getMinimalMarketV3( 9 | connection: Connection, 10 | marketId: PublicKey, 11 | commitment?: Commitment, 12 | ): Promise { 13 | const marketInfo = await connection.getAccountInfo(marketId, { 14 | commitment, 15 | dataSlice: { 16 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('eventQueue'), 17 | length: 32 * 3, 18 | }, 19 | }); 20 | 21 | return MINIMAL_MARKET_STATE_LAYOUT_V3.decode(marketInfo!.data); 22 | } 23 | -------------------------------------------------------------------------------- /src/filters/burn.filter.ts: -------------------------------------------------------------------------------- 1 | import { Filter, FilterResult } from './pool-filters'; 2 | import { Connection } from '@solana/web3.js'; 3 | import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; 4 | import { logger } from '../helpers'; 5 | 6 | export class BurnFilter implements Filter { 7 | constructor(private readonly connection: Connection) {} 8 | 9 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 10 | try { 11 | const amount = await this.connection.getTokenSupply(poolKeys.lpMint, this.connection.commitment); 12 | const burned = amount.value.uiAmount === 0; 13 | return { ok: burned, message: burned ? undefined : "Burned -> Creator didn't burn LP" }; 14 | } catch (e: any) { 15 | if (e.code == -32602) { 16 | return { ok: true }; 17 | } 18 | 19 | logger.error({ mint: poolKeys.baseMint }, `Failed to check if LP is burned`); 20 | } 21 | 22 | return { ok: false, message: 'Failed to check if LP is burned' }; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /cache/snipe-list.cache.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | import { logger, SNIPE_LIST_REFRESH_INTERVAL } from '../helpers'; 4 | 5 | export class SnipeListCache { 6 | private snipeList: string[] = []; 7 | private fileLocation = path.join(__dirname, '../snipe-list.txt'); 8 | 9 | constructor() { 10 | setInterval(() => this.loadSnipeList(), SNIPE_LIST_REFRESH_INTERVAL); 11 | } 12 | 13 | public init() { 14 | this.loadSnipeList(); 15 | } 16 | 17 | public isInList(mint: string) { 18 | return this.snipeList.includes(mint); 19 | } 20 | 21 | private loadSnipeList() { 22 | logger.trace(`Refreshing snipe list...`); 23 | 24 | const count = this.snipeList.length; 25 | const data = fs.readFileSync(this.fileLocation, 'utf-8'); 26 | this.snipeList = data 27 | .split('\n') 28 | .map((a) => a.trim()) 29 | .filter((a) => a); 30 | 31 | if (this.snipeList.length != count) { 32 | logger.info(`Loaded snipe list: ${this.snipeList.length}`); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/cache/snipe-list.cache.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | import { logger, SNIPE_LIST_REFRESH_INTERVAL } from '../helpers'; 4 | 5 | export class SnipeListCache { 6 | private snipeList: string[] = []; 7 | private fileLocation = path.join(__dirname, '../snipe-list.txt'); 8 | 9 | constructor() { 10 | setInterval(() => this.loadSnipeList(), SNIPE_LIST_REFRESH_INTERVAL); 11 | } 12 | 13 | public init() { 14 | this.loadSnipeList(); 15 | } 16 | 17 | public isInList(mint: string) { 18 | return this.snipeList.includes(mint); 19 | } 20 | 21 | private loadSnipeList() { 22 | logger.trace(`Refreshing snipe list...`); 23 | 24 | const count = this.snipeList.length; 25 | const data = fs.readFileSync(this.fileLocation, 'utf-8'); 26 | this.snipeList = data 27 | .split('\n') 28 | .map((a) => a.trim()) 29 | .filter((a) => a); 30 | 31 | if (this.snipeList.length != count) { 32 | logger.info(`Loaded snipe list: ${this.snipeList.length}`); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /.env.copy: -------------------------------------------------------------------------------- 1 | # Wallet 2 | PRIVATE_KEY= 3 | 4 | # Connection 5 | RPC_ENDPOINT=https://api.mainnet-beta.solana.com 6 | RPC_WEBSOCKET_ENDPOINT=wss://api.mainnet-beta.solana.com 7 | COMMITMENT_LEVEL=confirmed 8 | 9 | # Bot 10 | LOG_LEVEL=trace 11 | ONE_TOKEN_AT_A_TIME=true 12 | PRE_LOAD_EXISTING_MARKETS=false 13 | CACHE_NEW_MARKETS=false 14 | # default or warp 15 | TRANSACTION_EXECUTOR=default 16 | # if using default executor fee below will be applied 17 | COMPUTE_UNIT_LIMIT=101337 18 | COMPUTE_UNIT_PRICE=421197 19 | # if using warp executor fee below will be applied 20 | WARP_FEE=0.006 21 | 22 | # Buy 23 | QUOTE_MINT=WSOL 24 | QUOTE_AMOUNT=0.001 25 | AUTO_BUY_DELAY=0 26 | MAX_BUY_RETRIES=10 27 | BUY_SLIPPAGE=20 28 | 29 | # Sell 30 | AUTO_SELL=true 31 | MAX_SELL_RETRIES=10 32 | AUTO_SELL_DELAY=0 33 | PRICE_CHECK_INTERVAL=2000 34 | PRICE_CHECK_DURATION=600000 35 | TAKE_PROFIT=40 36 | STOP_LOSS=20 37 | SELL_SLIPPAGE=20 38 | 39 | # Filters 40 | USE_SNIPE_LIST=false 41 | SNIPE_LIST_REFRESH_INTERVAL=30000 42 | FILTER_CHECK_DURATION=60000 43 | FILTER_CHECK_INTERVAL=2000 44 | CONSECUTIVE_FILTER_MATCHES=3 45 | CHECK_IF_MINT_IS_RENOUNCED=true 46 | CHECK_IF_BURNED=true 47 | MIN_POOL_SIZE=5 48 | MAX_POOL_SIZE=50 49 | -------------------------------------------------------------------------------- /src/filters/renounced.filter.ts: -------------------------------------------------------------------------------- 1 | import { Filter, FilterResult } from './pool-filters'; 2 | import { MintLayout } from '@solana/spl-token'; 3 | import { Connection } from '@solana/web3.js'; 4 | import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; 5 | import { logger } from '../helpers'; 6 | 7 | export class RenouncedFilter implements Filter { 8 | constructor(private readonly connection: Connection) {} 9 | 10 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 11 | try { 12 | const accountInfo = await this.connection.getAccountInfo(poolKeys.baseMint, this.connection.commitment); 13 | if (!accountInfo?.data) { 14 | return { ok: false, message: 'Renounced -> Failed to fetch account data' }; 15 | } 16 | 17 | const deserialize = MintLayout.decode(accountInfo.data); 18 | const renounced = deserialize.mintAuthorityOption === 0; 19 | return { ok: renounced, message: renounced ? undefined : 'Renounced -> Creator can mint more tokens' }; 20 | } catch (e) { 21 | logger.error({ mint: poolKeys.baseMint }, `Failed to check if mint is renounced`); 22 | } 23 | 24 | return { ok: false, message: 'Renounced -> Failed to check if mint is renounced' }; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/helpers/config.ts: -------------------------------------------------------------------------------- 1 | import { readFileSync } from 'fs'; 2 | import { Commitment, Connection } from '@solana/web3.js'; 3 | import pino from 'pino'; 4 | var toml = require('toml'); 5 | 6 | const configPath = './settings.toml'; 7 | const rawConfig = readFileSync(configPath, 'utf-8'); 8 | 9 | function isConfig(obj: any): obj is Config { 10 | return 'wallet' in obj && typeof obj.wallet.PRIVATE_KEY === 'string'; 11 | // Add further checks for other properties as necessary 12 | } 13 | 14 | interface Config { 15 | wallet: { 16 | PRIVATE_KEY: string; 17 | }; 18 | // connection: { 19 | // commitment: Commitment; 20 | // rpcEndpoint: string; 21 | // rpcWebsocketEndpoint: string; 22 | // }; 23 | // bot: { 24 | // logLevel: string; 25 | // }; 26 | } 27 | 28 | try { 29 | var data = toml.parse(rawConfig); 30 | console.dir(data); 31 | 32 | //console.log(settings); // Check what the parsed object looks like 33 | 34 | 35 | } catch (error) { 36 | console.error("Failed to parse TOML:", error); 37 | } 38 | 39 | // Setup logger 40 | //const logger = pino({ level: settings.bot.logLevel }); 41 | 42 | // Config object with assertions for necessary validation 43 | const config = { 44 | //privateKey: settings.wallet.PRIVATE_KEY, 45 | // network: 'mainnet-beta' as const, 46 | // commitment: settings.connection.commitment as Commitment, 47 | // rpcEndpoint: settings.connection.rpcEndpoint, 48 | // rpcWebsocketEndpoint: settings.connection.rpcWebsocketEndpoint, 49 | 50 | // Add other configurations as needed, validating each one if necessary 51 | }; -------------------------------------------------------------------------------- /src/transactions/default-transaction-executor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BlockhashWithExpiryBlockHeight, 3 | Connection, 4 | Keypair, 5 | Transaction, 6 | VersionedTransaction, 7 | } from '@solana/web3.js'; 8 | import { TransactionExecutor } from './transaction-executor.interface'; 9 | import { logger } from '../helpers'; 10 | 11 | export class DefaultTransactionExecutor implements TransactionExecutor { 12 | constructor(private readonly connection: Connection) {} 13 | 14 | public async executeAndConfirm( 15 | transaction: VersionedTransaction, 16 | payer: Keypair, 17 | latestBlockhash: BlockhashWithExpiryBlockHeight, 18 | ): Promise<{ confirmed: boolean; signature?: string }> { 19 | logger.debug('Executing transaction...'); 20 | const signature = await this.execute(transaction); 21 | 22 | logger.debug({ signature }, 'Confirming transaction...'); 23 | return this.confirm(signature, latestBlockhash); 24 | } 25 | 26 | private async execute(transaction: Transaction | VersionedTransaction) { 27 | return this.connection.sendRawTransaction(transaction.serialize(), { 28 | preflightCommitment: this.connection.commitment, 29 | }); 30 | } 31 | 32 | private async confirm(signature: string, latestBlockhash: BlockhashWithExpiryBlockHeight) { 33 | const confirmation = await this.connection.confirmTransaction( 34 | { 35 | signature, 36 | lastValidBlockHeight: latestBlockhash.lastValidBlockHeight, 37 | blockhash: latestBlockhash.blockhash, 38 | }, 39 | this.connection.commitment, 40 | ); 41 | 42 | return { confirmed: !confirmation.value.err, signature }; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/filters/pool-size.filter.ts: -------------------------------------------------------------------------------- 1 | import { Filter, FilterResult } from './pool-filters'; 2 | import { LiquidityPoolKeysV4, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 3 | import { Connection } from '@solana/web3.js'; 4 | import { logger } from '../helpers'; 5 | 6 | export class PoolSizeFilter implements Filter { 7 | constructor( 8 | private readonly connection: Connection, 9 | private readonly quoteToken: Token, 10 | private readonly minPoolSize: TokenAmount, 11 | private readonly maxPoolSize: TokenAmount, 12 | ) {} 13 | 14 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 15 | try { 16 | const response = await this.connection.getTokenAccountBalance(poolKeys.quoteVault, this.connection.commitment); 17 | const poolSize = new TokenAmount(this.quoteToken, response.value.amount, true); 18 | let inRange = true; 19 | 20 | if (!this.maxPoolSize?.isZero()) { 21 | inRange = poolSize.raw.lte(this.maxPoolSize.raw); 22 | 23 | if (!inRange) { 24 | return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} > ${this.maxPoolSize.toFixed()}` }; 25 | } 26 | } 27 | 28 | if (!this.minPoolSize?.isZero()) { 29 | inRange = poolSize.raw.gte(this.minPoolSize.raw); 30 | 31 | if (!inRange) { 32 | return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} < ${this.minPoolSize.toFixed()}` }; 33 | } 34 | } 35 | 36 | return { ok: inRange }; 37 | } catch (error) { 38 | logger.error({ mint: poolKeys.baseMint }, `Failed to check pool size`); 39 | } 40 | 41 | return { ok: false, message: 'PoolSize -> Failed to check pool size' }; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/helpers/liquidity.ts: -------------------------------------------------------------------------------- 1 | import { PublicKey } from '@solana/web3.js'; 2 | import { Liquidity, LiquidityPoolKeys, LiquidityStateV4, MAINNET_PROGRAM_ID, Market } from '@raydium-io/raydium-sdk'; 3 | import { MinimalMarketLayoutV3 } from './market'; 4 | 5 | export function createPoolKeys( 6 | id: PublicKey, 7 | accountData: LiquidityStateV4, 8 | minimalMarketLayoutV3: MinimalMarketLayoutV3, 9 | ): LiquidityPoolKeys { 10 | return { 11 | id, 12 | baseMint: accountData.baseMint, 13 | quoteMint: accountData.quoteMint, 14 | lpMint: accountData.lpMint, 15 | baseDecimals: accountData.baseDecimal.toNumber(), 16 | quoteDecimals: accountData.quoteDecimal.toNumber(), 17 | lpDecimals: 5, 18 | version: 4, 19 | programId: MAINNET_PROGRAM_ID.AmmV4, 20 | authority: Liquidity.getAssociatedAuthority({ 21 | programId: MAINNET_PROGRAM_ID.AmmV4, 22 | }).publicKey, 23 | openOrders: accountData.openOrders, 24 | targetOrders: accountData.targetOrders, 25 | baseVault: accountData.baseVault, 26 | quoteVault: accountData.quoteVault, 27 | marketVersion: 3, 28 | marketProgramId: accountData.marketProgramId, 29 | marketId: accountData.marketId, 30 | marketAuthority: Market.getAssociatedAuthority({ 31 | programId: accountData.marketProgramId, 32 | marketId: accountData.marketId, 33 | }).publicKey, 34 | marketBaseVault: accountData.baseVault, 35 | marketQuoteVault: accountData.quoteVault, 36 | marketBids: minimalMarketLayoutV3.bids, 37 | marketAsks: minimalMarketLayoutV3.asks, 38 | marketEventQueue: minimalMarketLayoutV3.eventQueue, 39 | withdrawQueue: accountData.withdrawQueue, 40 | lpVault: accountData.lpVault, 41 | lookupTableAccount: PublicKey.default, 42 | }; 43 | } 44 | -------------------------------------------------------------------------------- /src/filters/pool-filters.ts: -------------------------------------------------------------------------------- 1 | import { Connection } from '@solana/web3.js'; 2 | import { LiquidityPoolKeysV4, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 3 | import { BurnFilter } from './burn.filter'; 4 | import { RenouncedFilter } from './renounced.filter'; 5 | import { PoolSizeFilter } from './pool-size.filter'; 6 | import { CHECK_IF_BURNED, CHECK_IF_MINT_IS_RENOUNCED, logger } from '../helpers'; 7 | 8 | export interface Filter { 9 | execute(poolKeysV4: LiquidityPoolKeysV4): Promise; 10 | } 11 | 12 | export interface FilterResult { 13 | ok: boolean; 14 | message?: string; 15 | } 16 | 17 | export interface PoolFilterArgs { 18 | minPoolSize: TokenAmount; 19 | maxPoolSize: TokenAmount; 20 | quoteToken: Token; 21 | } 22 | 23 | export class PoolFilters { 24 | private readonly filters: Filter[] = []; 25 | 26 | constructor( 27 | readonly connection: Connection, 28 | readonly args: PoolFilterArgs, 29 | ) { 30 | if (CHECK_IF_BURNED) { 31 | this.filters.push(new BurnFilter(connection)); 32 | } 33 | 34 | if (CHECK_IF_MINT_IS_RENOUNCED) { 35 | this.filters.push(new RenouncedFilter(connection)); 36 | } 37 | 38 | if (!args.minPoolSize.isZero() || !args.maxPoolSize.isZero()) { 39 | this.filters.push(new PoolSizeFilter(connection, args.quoteToken, args.minPoolSize, args.maxPoolSize)); 40 | } 41 | } 42 | 43 | public async execute(poolKeys: LiquidityPoolKeysV4): Promise { 44 | if (this.filters.length === 0) { 45 | return true; 46 | } 47 | 48 | const result = await Promise.all(this.filters.map((f) => f.execute(poolKeys))); 49 | const pass = result.every((r) => r.ok); 50 | 51 | if (pass) { 52 | return true; 53 | } 54 | 55 | for (const filterResult of result.filter((r) => !r.ok)) { 56 | logger.trace(filterResult.message); 57 | } 58 | 59 | return false; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/transactions/warp-transaction-executor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BlockhashWithExpiryBlockHeight, 3 | Keypair, 4 | PublicKey, 5 | SystemProgram, 6 | TransactionMessage, 7 | VersionedTransaction, 8 | } from '@solana/web3.js'; 9 | import { TransactionExecutor } from './transaction-executor.interface'; 10 | import { logger } from '../helpers'; 11 | import axios, { AxiosError } from 'axios'; 12 | import bs58 from 'bs58'; 13 | import { Currency, CurrencyAmount } from '@raydium-io/raydium-sdk'; 14 | 15 | export class WarpTransactionExecutor implements TransactionExecutor { 16 | private readonly warpFeeWallet = new PublicKey('WARPzUMPnycu9eeCZ95rcAUxorqpBqHndfV3ZP5FSyS'); 17 | 18 | constructor(private readonly warpFee: string) {} 19 | 20 | public async executeAndConfirm( 21 | transaction: VersionedTransaction, 22 | payer: Keypair, 23 | latestBlockhash: BlockhashWithExpiryBlockHeight, 24 | ): Promise<{ confirmed: boolean; signature?: string }> { 25 | logger.debug('Executing transaction...'); 26 | 27 | try { 28 | const fee = new CurrencyAmount(Currency.SOL, this.warpFee, false).raw.toNumber(); 29 | const warpFeeMessage = new TransactionMessage({ 30 | payerKey: payer.publicKey, 31 | recentBlockhash: latestBlockhash.blockhash, 32 | instructions: [ 33 | SystemProgram.transfer({ 34 | fromPubkey: payer.publicKey, 35 | toPubkey: this.warpFeeWallet, 36 | lamports: fee, 37 | }), 38 | ], 39 | }).compileToV0Message(); 40 | 41 | const warpFeeTx = new VersionedTransaction(warpFeeMessage); 42 | warpFeeTx.sign([payer]); 43 | 44 | const response = await axios.post<{ confirmed: boolean; signature: string }>( 45 | 'https://tx.warp.id/transaction/execute', 46 | { 47 | transactions: [bs58.encode(warpFeeTx.serialize()), bs58.encode(transaction.serialize())], 48 | latestBlockhash, 49 | }, 50 | { 51 | timeout: 100000, 52 | }, 53 | ); 54 | 55 | return response.data; 56 | } catch (error) { 57 | if (error instanceof AxiosError) { 58 | logger.trace({ error: error.response?.data }, 'Failed to execute warp transaction'); 59 | } 60 | } 61 | 62 | return { confirmed: false }; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /cache/market.cache.ts: -------------------------------------------------------------------------------- 1 | import { Connection, PublicKey } from '@solana/web3.js'; 2 | import { getMinimalMarketV3, logger, MINIMAL_MARKET_STATE_LAYOUT_V3, MinimalMarketLayoutV3 } from '../helpers'; 3 | import { MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from '@raydium-io/raydium-sdk'; 4 | 5 | export class MarketCache { 6 | private readonly keys: Map = new Map(); 7 | constructor(private readonly connection: Connection) {} 8 | 9 | async init(config: { quoteToken: Token }) { 10 | logger.debug({}, `Fetching all existing ${config.quoteToken.symbol} markets...`); 11 | 12 | const accounts = await this.connection.getProgramAccounts(MAINNET_PROGRAM_ID.OPENBOOK_MARKET, { 13 | commitment: this.connection.commitment, 14 | dataSlice: { 15 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('eventQueue'), 16 | length: MINIMAL_MARKET_STATE_LAYOUT_V3.span, 17 | }, 18 | filters: [ 19 | { dataSize: MARKET_STATE_LAYOUT_V3.span }, 20 | { 21 | memcmp: { 22 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'), 23 | bytes: config.quoteToken.mint.toBase58(), 24 | }, 25 | }, 26 | ], 27 | }); 28 | 29 | for (const account of accounts) { 30 | const market = MINIMAL_MARKET_STATE_LAYOUT_V3.decode(account.account.data); 31 | this.keys.set(account.pubkey.toString(), market); 32 | } 33 | 34 | logger.debug({}, `Cached ${this.keys.size} markets`); 35 | } 36 | 37 | public save(marketId: string, keys: MinimalMarketLayoutV3) { 38 | if (!this.keys.has(marketId)) { 39 | logger.trace({}, `Caching new market: ${marketId}`); 40 | this.keys.set(marketId, keys); 41 | } 42 | } 43 | 44 | public async get(marketId: string): Promise { 45 | if (this.keys.has(marketId)) { 46 | return this.keys.get(marketId)!; 47 | } 48 | 49 | logger.trace({}, `Fetching new market keys for ${marketId}`); 50 | const market = await this.fetch(marketId); 51 | this.keys.set(marketId, market); 52 | return market; 53 | } 54 | 55 | private fetch(marketId: string): Promise { 56 | return getMinimalMarketV3(this.connection, new PublicKey(marketId), this.connection.commitment); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/cache/market.cache.ts: -------------------------------------------------------------------------------- 1 | import { Connection, PublicKey } from '@solana/web3.js'; 2 | import { getMinimalMarketV3, logger, MINIMAL_MARKET_STATE_LAYOUT_V3, MinimalMarketLayoutV3 } from '../helpers'; 3 | import { MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from '@raydium-io/raydium-sdk'; 4 | 5 | export class MarketCache { 6 | private readonly keys: Map = new Map(); 7 | constructor(private readonly connection: Connection) {} 8 | 9 | async init(config: { quoteToken: Token }) { 10 | logger.debug({}, `Fetching all existing ${config.quoteToken.symbol} markets...`); 11 | 12 | const accounts = await this.connection.getProgramAccounts(MAINNET_PROGRAM_ID.OPENBOOK_MARKET, { 13 | commitment: this.connection.commitment, 14 | dataSlice: { 15 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('eventQueue'), 16 | length: MINIMAL_MARKET_STATE_LAYOUT_V3.span, 17 | }, 18 | filters: [ 19 | { dataSize: MARKET_STATE_LAYOUT_V3.span }, 20 | { 21 | memcmp: { 22 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'), 23 | bytes: config.quoteToken.mint.toBase58(), 24 | }, 25 | }, 26 | ], 27 | }); 28 | 29 | for (const account of accounts) { 30 | const market = MINIMAL_MARKET_STATE_LAYOUT_V3.decode(account.account.data); 31 | this.keys.set(account.pubkey.toString(), market); 32 | } 33 | 34 | logger.debug({}, `Cached ${this.keys.size} markets`); 35 | } 36 | 37 | public save(marketId: string, keys: MinimalMarketLayoutV3) { 38 | if (!this.keys.has(marketId)) { 39 | logger.trace({}, `Caching new market: ${marketId}`); 40 | this.keys.set(marketId, keys); 41 | } 42 | } 43 | 44 | public async get(marketId: string): Promise { 45 | if (this.keys.has(marketId)) { 46 | return this.keys.get(marketId)!; 47 | } 48 | 49 | logger.trace({}, `Fetching new market keys for ${marketId}`); 50 | const market = await this.fetch(marketId); 51 | this.keys.set(marketId, market); 52 | return market; 53 | } 54 | 55 | private fetch(marketId: string): Promise { 56 | return getMinimalMarketV3(this.connection, new PublicKey(marketId), this.connection.commitment); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Microsoft Public License (Ms-PL) 2 | 3 | This license governs use of the accompanying software. If you use the software, you 4 | accept this license. If you do not accept the license, do not use the software. 5 | 6 | 1. Definitions 7 | The terms "reproduce," "reproduction," "derivative works," and "distribution" have the 8 | same meaning here as under U.S. copyright law. 9 | A "contribution" is the original software, or any additions or changes to the software. 10 | A "contributor" is any person that distributes its contribution under this license. 11 | "Licensed patents" are a contributor's patent claims that read directly on its contribution. 12 | 13 | 2. Grant of Rights 14 | (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. 15 | (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. 16 | 17 | 3. Conditions and Limitations 18 | (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. 19 | (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. 20 | (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. 21 | (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. 22 | (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. -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | 125 | # PNPM 126 | pnpm-lock.yaml 127 | 128 | # yarn v2 129 | .yarn/cache 130 | .yarn/unplugged 131 | .yarn/build-state.yml 132 | .yarn/install-state.gz 133 | .pnp.* 134 | 135 | # JetBrains 136 | .idea 137 | 138 | # Visual Studio Code 139 | *.code-workspace 140 | -------------------------------------------------------------------------------- /src/helpers/constants.ts: -------------------------------------------------------------------------------- 1 | import { Logger } from 'pino'; 2 | import dotenv from 'dotenv'; 3 | import { Commitment } from '@solana/web3.js'; 4 | import { logger } from './logger'; 5 | 6 | dotenv.config(); 7 | 8 | const retrieveEnvVariable = (variableName: string, logger: Logger) => { 9 | const variable = process.env[variableName] || ''; 10 | if (!variable) { 11 | logger.error(`${variableName} is not set`); 12 | process.exit(1); 13 | } 14 | return variable; 15 | }; 16 | 17 | // Wallet 18 | export const PRIVATE_KEY = retrieveEnvVariable('PRIVATE_KEY', logger); 19 | 20 | // Connection 21 | export const NETWORK = 'mainnet-beta'; 22 | export const COMMITMENT_LEVEL: Commitment = retrieveEnvVariable('COMMITMENT_LEVEL', logger) as Commitment; 23 | export const RPC_ENDPOINT = retrieveEnvVariable('RPC_ENDPOINT', logger); 24 | export const RPC_WEBSOCKET_ENDPOINT = retrieveEnvVariable('RPC_WEBSOCKET_ENDPOINT', logger); 25 | 26 | // Bot 27 | export const LOG_LEVEL = retrieveEnvVariable('LOG_LEVEL', logger); 28 | export const ONE_TOKEN_AT_A_TIME = retrieveEnvVariable('ONE_TOKEN_AT_A_TIME', logger) === 'true'; 29 | export const COMPUTE_UNIT_LIMIT = Number(retrieveEnvVariable('COMPUTE_UNIT_LIMIT', logger)); 30 | export const COMPUTE_UNIT_PRICE = Number(retrieveEnvVariable('COMPUTE_UNIT_PRICE', logger)); 31 | export const PRE_LOAD_EXISTING_MARKETS = retrieveEnvVariable('PRE_LOAD_EXISTING_MARKETS', logger) === 'true'; 32 | export const CACHE_NEW_MARKETS = retrieveEnvVariable('CACHE_NEW_MARKETS', logger) === 'true'; 33 | export const TRANSACTION_EXECUTOR = retrieveEnvVariable('TRANSACTION_EXECUTOR', logger); 34 | export const WARP_FEE = retrieveEnvVariable('WARP_FEE', logger); 35 | 36 | // Buy 37 | export const AUTO_BUY_DELAY = Number(retrieveEnvVariable('AUTO_BUY_DELAY', logger)); 38 | export const QUOTE_MINT = retrieveEnvVariable('QUOTE_MINT', logger); 39 | export const QUOTE_AMOUNT = retrieveEnvVariable('QUOTE_AMOUNT', logger); 40 | export const MAX_BUY_RETRIES = Number(retrieveEnvVariable('MAX_BUY_RETRIES', logger)); 41 | export const BUY_SLIPPAGE = Number(retrieveEnvVariable('BUY_SLIPPAGE', logger)); 42 | 43 | // Sell 44 | export const AUTO_SELL = retrieveEnvVariable('AUTO_SELL', logger) === 'true'; 45 | export const AUTO_SELL_DELAY = Number(retrieveEnvVariable('AUTO_SELL_DELAY', logger)); 46 | export const MAX_SELL_RETRIES = Number(retrieveEnvVariable('MAX_SELL_RETRIES', logger)); 47 | export const TAKE_PROFIT = Number(retrieveEnvVariable('TAKE_PROFIT', logger)); 48 | export const STOP_LOSS = Number(retrieveEnvVariable('STOP_LOSS', logger)); 49 | export const PRICE_CHECK_INTERVAL = Number(retrieveEnvVariable('PRICE_CHECK_INTERVAL', logger)); 50 | export const PRICE_CHECK_DURATION = Number(retrieveEnvVariable('PRICE_CHECK_DURATION', logger)); 51 | export const SELL_SLIPPAGE = Number(retrieveEnvVariable('SELL_SLIPPAGE', logger)); 52 | 53 | // Filters 54 | export const FILTER_CHECK_INTERVAL = Number(retrieveEnvVariable('FILTER_CHECK_INTERVAL', logger)); 55 | export const FILTER_CHECK_DURATION = Number(retrieveEnvVariable('FILTER_CHECK_DURATION', logger)); 56 | export const CONSECUTIVE_FILTER_MATCHES = Number(retrieveEnvVariable('CONSECUTIVE_FILTER_MATCHES', logger)); 57 | export const CHECK_IF_MINT_IS_RENOUNCED = retrieveEnvVariable('CHECK_IF_MINT_IS_RENOUNCED', logger) === 'true'; 58 | export const CHECK_IF_BURNED = retrieveEnvVariable('CHECK_IF_BURNED', logger) === 'true'; 59 | export const MIN_POOL_SIZE = retrieveEnvVariable('MIN_POOL_SIZE', logger); 60 | export const MAX_POOL_SIZE = retrieveEnvVariable('MAX_POOL_SIZE', logger); 61 | export const USE_SNIPE_LIST = retrieveEnvVariable('USE_SNIPE_LIST', logger) === 'true'; 62 | export const SNIPE_LIST_REFRESH_INTERVAL = Number(retrieveEnvVariable('SNIPE_LIST_REFRESH_INTERVAL', logger)); 63 | -------------------------------------------------------------------------------- /src/listeners/listeners.ts: -------------------------------------------------------------------------------- 1 | import { LIQUIDITY_STATE_LAYOUT_V4, MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from '@raydium-io/raydium-sdk'; 2 | import bs58 from 'bs58'; 3 | import { Connection, PublicKey } from '@solana/web3.js'; 4 | import { TOKEN_PROGRAM_ID } from '@solana/spl-token'; 5 | import { EventEmitter } from 'events'; 6 | 7 | export class Listeners extends EventEmitter { 8 | private subscriptions: number[] = []; 9 | 10 | constructor(private readonly connection: Connection) { 11 | super(); 12 | } 13 | 14 | public async start(config: { 15 | walletPublicKey: PublicKey; 16 | quoteToken: Token; 17 | autoSell: boolean; 18 | cacheNewMarkets: boolean; 19 | }) { 20 | if (config.cacheNewMarkets) { 21 | const openBookSubscription = await this.subscribeToOpenBookMarkets(config); 22 | this.subscriptions.push(openBookSubscription); 23 | } 24 | 25 | const raydiumSubscription = await this.subscribeToRaydiumPools(config); 26 | this.subscriptions.push(raydiumSubscription); 27 | 28 | if (config.autoSell) { 29 | const walletSubscription = await this.subscribeToWalletChanges(config); 30 | this.subscriptions.push(walletSubscription); 31 | } 32 | } 33 | 34 | private async subscribeToOpenBookMarkets(config: { quoteToken: Token }) { 35 | return this.connection.onProgramAccountChange( 36 | MAINNET_PROGRAM_ID.OPENBOOK_MARKET, 37 | async (updatedAccountInfo) => { 38 | this.emit('market', updatedAccountInfo); 39 | }, 40 | this.connection.commitment, 41 | [ 42 | { dataSize: MARKET_STATE_LAYOUT_V3.span }, 43 | { 44 | memcmp: { 45 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'), 46 | bytes: config.quoteToken.mint.toBase58(), 47 | }, 48 | }, 49 | ], 50 | ); 51 | } 52 | 53 | private async subscribeToRaydiumPools(config: { quoteToken: Token }) { 54 | return this.connection.onProgramAccountChange( 55 | MAINNET_PROGRAM_ID.AmmV4, 56 | async (updatedAccountInfo) => { 57 | this.emit('pool', updatedAccountInfo); 58 | }, 59 | this.connection.commitment, 60 | [ 61 | { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span }, 62 | { 63 | memcmp: { 64 | offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'), 65 | bytes: config.quoteToken.mint.toBase58(), 66 | }, 67 | }, 68 | { 69 | memcmp: { 70 | offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'), 71 | bytes: MAINNET_PROGRAM_ID.OPENBOOK_MARKET.toBase58(), 72 | }, 73 | }, 74 | { 75 | memcmp: { 76 | offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'), 77 | bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]), 78 | }, 79 | }, 80 | ], 81 | ); 82 | } 83 | 84 | private async subscribeToWalletChanges(config: { walletPublicKey: PublicKey }) { 85 | return this.connection.onProgramAccountChange( 86 | TOKEN_PROGRAM_ID, 87 | async (updatedAccountInfo) => { 88 | this.emit('wallet', updatedAccountInfo); 89 | }, 90 | this.connection.commitment, 91 | [ 92 | { 93 | dataSize: 165, 94 | }, 95 | { 96 | memcmp: { 97 | offset: 32, 98 | bytes: config.walletPublicKey.toBase58(), 99 | }, 100 | }, 101 | ], 102 | ); 103 | } 104 | 105 | public async stop() { 106 | for (let i = this.subscriptions.length; i >= 0; --i) { 107 | const subscription = this.subscriptions[i]; 108 | await this.connection.removeAccountChangeListener(subscription); 109 | this.subscriptions.splice(i, 1); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /docs/install.md: -------------------------------------------------------------------------------- 1 | ## install 2 | 3 | ``` 4 | sudo apt update -y 5 | curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - 6 | echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list 7 | sudo apt update -y 8 | sudo apt install yarn -y 9 | git clone git@github.com:OpenBotDev/sniperbot.git && cd sniperbot 10 | yarn install 11 | cp .env.copy .env 12 | ``` 13 | 14 | ## run 15 | 16 | ```yarn run bot``` 17 | 18 | 19 | ## Setup 20 | To run the script you need to: 21 | - Create a new empty Solana wallet 22 | - Transfer some SOL to it. 23 | - Convert some SOL to USDC or WSOL. 24 | - You need USDC or WSOL depending on the configuration set below. 25 | - Configure the script by updating `.env.copy` file (remove the .copy from the file name when done). 26 | - Check [Configuration](#configuration) section bellow 27 | - Install dependencies by typing: `npm install` 28 | - Run the script by typing: `npm run start` in terminal 29 | 30 | You should see the following output: 31 | ![output](output.png) 32 | 33 | ### Configuration 34 | 35 | #### Wallet 36 | - `PRIVATE_KEY` - Your wallet's private key. 37 | 38 | #### Connection 39 | - `RPC_ENDPOINT` - HTTPS RPC endpoint for interacting with the Solana network. 40 | - `RPC_WEBSOCKET_ENDPOINT` - WebSocket RPC endpoint for real-time updates from the Solana network. 41 | - `COMMITMENT_LEVEL`- The commitment level of transactions (e.g., "finalized" for the highest level of security). 42 | 43 | #### Bot 44 | - `LOG_LEVEL` - Set logging level, e.g., `info`, `debug`, `trace`, etc. 45 | - `ONE_TOKEN_AT_A_TIME` - Set to `true` to process buying one token at a time. 46 | - `COMPUTE_UNIT_LIMIT` - Compute limit used to calculate fees. 47 | - `COMPUTE_UNIT_PRICE` - Compute price used to calculate fees. 48 | - `PRE_LOAD_EXISTING_MARKETS` - Bot will load all existing markets in memory on start. 49 | - This option should not be used with public RPC. 50 | - `CACHE_NEW_MARKETS` - Set to `true` to cache new markets. 51 | - This option should not be used with public RPC. 52 | - `TRANSACTION_EXECUTOR` - Set to `warp` to use warp infrastructure for executing transactions 53 | - For more details checkout [warp](#warp-transactions-beta) section 54 | - `WARP_FEE` - If using warp executor this value will be used for transaction fees instead of `COMPUTE_UNIT_LIMIT` and `COMPUTE_UNIT_LIMIT` 55 | - Minimum value is 0.0001 SOL, but we recommend using 0.006 SOL or above 56 | - On top of this fee, minimal solana network fee will be applied 57 | 58 | #### Buy 59 | - `QUOTE_MINT` - Which pools to snipe, USDC or WSOL. 60 | - `QUOTE_AMOUNT` - Amount used to buy each new token. 61 | - `AUTO_BUY_DELAY` - Delay in milliseconds before buying a token. 62 | - `MAX_BUY_RETRIES` - Maximum number of retries for buying a token. 63 | - `BUY_SLIPPAGE` - Slippage % 64 | 65 | #### Sell 66 | - `AUTO_SELL` - Set to `true` to enable automatic selling of tokens. 67 | - If you want to manually sell bought tokens, disable this option. 68 | - `MAX_SELL_RETRIES` - Maximum number of retries for selling a token. 69 | - `AUTO_SELL_DELAY` - Delay in milliseconds before auto-selling a token. 70 | - `PRICE_CHECK_INTERVAL` - Interval in milliseconds for checking the take profit and stop loss conditions. 71 | - Set to zero to disable take profit and stop loss. 72 | - `PRICE_CHECK_DURATION` - Time in milliseconds to wait for stop loss/take profit conditions. 73 | - If you don't reach profit or loss bot will auto sell after this time. 74 | - Set to zero to disable take profit and stop loss. 75 | - `TAKE_PROFIT` - Percentage profit at which to take profit. 76 | - Take profit is calculated based on quote mint. 77 | - `STOP_LOSS` - Percentage loss at which to stop the loss. 78 | - Stop loss is calculated based on quote mint. 79 | - `SELL_SLIPPAGE` - Slippage %. 80 | 81 | #### Filters 82 | - `FILTER_CHECK_INTERVAL` - Interval in milliseconds for checking if pool match the filters. 83 | - Set to zero to disable filters. 84 | - `FILTER_CHECK_DURATION` - Time in milliseconds to wait for pool to match the filters. 85 | - If pool doesn't match the filter buy will not happen. 86 | - Set to zero to disable filters. 87 | - `CONSECUTIVE_FILTER_MATCHES` - How many times in a row pool needs to match the filters. 88 | - 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 89 | - `USE_SNIPE_LIST` - Set to `true` to enable buying only tokens listed in `snipe-list.txt`. 90 | - Pool must not exist before the script starts. 91 | - `SNIPE_LIST_REFRESH_INTERVAL` - Interval in milliseconds to refresh the snipe list. 92 | - `CHECK_IF_MINT_IS_RENOUNCED` - Set to `true` to buy tokens only if their mint is renounced. 93 | - `CHECK_IF_BURNED` - Set to `true` to buy tokens only if their liquidity pool is burned. 94 | - `MIN_POOL_SIZE` - Bot will buy only if the pool size is greater than or equal the specified amount. 95 | - Set `0` to disable. 96 | - `MAX_POOL_SIZE` - Bot will buy only if the pool size is less than or equal the specified amount. 97 | - Set `0` to disable. 98 | 99 | ## Warp transactions (beta) 100 | In case you experience a lot of failed transactions or transaction performance is too slow, you can try using `warp` for executing transactions. 101 | Warp is hosted service that executes transactions using integrations with third party providers. 102 | 103 | Using warp for transactions supports the team behind this project. 104 | 105 | ### Security 106 | When using warp, transaction is sent to the hosted service. 107 | **Payload that is being sent will NOT contain your wallet private key**. Fee transaction is signed on your machine. 108 | Each request is processed by hosted service and sent to third party provider. 109 | **We don't store your transactions, nor we store your private key.** 110 | 111 | Note: Warp transactions are disabled by default. 112 | 113 | ### Fees 114 | When using warp for transactions, fee is distributed between developers of warp and third party providers. 115 | In case TX fails, no fee will be taken from your account. 116 | 117 | ## Common issues 118 | If you have an error which is not listed here, please create a new issue in this repository. 119 | To collect more information on an issue, please change `LOG_LEVEL` to `debug`. 120 | 121 | ### Unsupported RPC node 122 | - If you see following error in your log file: 123 | `Error: 410 Gone: {"jsonrpc":"2.0","error":{"code": 410, "message":"The RPC call or parameters have been disabled."}, "id": "986f3599-b2b7-47c4-b951-074c19842bad" }` 124 | it means your RPC node doesn't support methods needed to execute script. 125 | - FIX: Change your RPC node. You can use Helius or Quicknode. 126 | 127 | ### No token account 128 | - If you see following error in your log file: 129 | `Error: No SOL token account found in wallet: ` 130 | it means that wallet you provided doesn't have USDC/WSOL token account. 131 | - 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: 132 | 133 | ![wsol](wsol.png) -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { MarketCache, PoolCache } from './cache'; 2 | import { Listeners } from './listeners'; 3 | import { Connection, KeyedAccountInfo, Keypair } from '@solana/web3.js'; 4 | import { LIQUIDITY_STATE_LAYOUT_V4, MARKET_STATE_LAYOUT_V3, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 5 | import { AccountLayout, getAssociatedTokenAddressSync } from '@solana/spl-token'; 6 | import { Bot, BotConfig } from './bot'; 7 | import { DefaultTransactionExecutor, TransactionExecutor } from './transactions'; 8 | import { 9 | getToken, 10 | getWallet, 11 | logger, 12 | COMMITMENT_LEVEL, 13 | RPC_ENDPOINT, 14 | RPC_WEBSOCKET_ENDPOINT, 15 | PRE_LOAD_EXISTING_MARKETS, 16 | LOG_LEVEL, 17 | CHECK_IF_MINT_IS_RENOUNCED, 18 | CHECK_IF_BURNED, 19 | QUOTE_MINT, 20 | MAX_POOL_SIZE, 21 | MIN_POOL_SIZE, 22 | QUOTE_AMOUNT, 23 | PRIVATE_KEY, 24 | USE_SNIPE_LIST, 25 | ONE_TOKEN_AT_A_TIME, 26 | AUTO_SELL_DELAY, 27 | MAX_SELL_RETRIES, 28 | AUTO_SELL, 29 | MAX_BUY_RETRIES, 30 | AUTO_BUY_DELAY, 31 | COMPUTE_UNIT_LIMIT, 32 | COMPUTE_UNIT_PRICE, 33 | CACHE_NEW_MARKETS, 34 | TAKE_PROFIT, 35 | STOP_LOSS, 36 | BUY_SLIPPAGE, 37 | SELL_SLIPPAGE, 38 | PRICE_CHECK_DURATION, 39 | PRICE_CHECK_INTERVAL, 40 | SNIPE_LIST_REFRESH_INTERVAL, 41 | TRANSACTION_EXECUTOR, 42 | WARP_FEE, 43 | FILTER_CHECK_INTERVAL, 44 | FILTER_CHECK_DURATION, 45 | CONSECUTIVE_FILTER_MATCHES, 46 | } from './helpers'; 47 | import { WarpTransactionExecutor } from './transactions/warp-transaction-executor'; 48 | 49 | const connection = new Connection(RPC_ENDPOINT, { 50 | wsEndpoint: RPC_WEBSOCKET_ENDPOINT, 51 | commitment: COMMITMENT_LEVEL, 52 | }); 53 | 54 | //TODO settings.toml 55 | function printDetails(wallet: Keypair, quoteToken: Token, bot: Bot) { 56 | logger.info(`start`); 57 | 58 | const botConfig = bot.config; 59 | 60 | logger.info('------- CONFIGURATION START -------'); 61 | logger.info(`Wallet: ${wallet.publicKey.toString()}`); 62 | 63 | logger.info('- Bot -'); 64 | 65 | logger.info(`Using warp: ${bot.isWarp}`); 66 | if (bot.isWarp) { 67 | logger.info(`Warp fee: ${WARP_FEE}`); 68 | } else { 69 | logger.info(`Compute Unit limit: ${botConfig.unitLimit}`); 70 | logger.info(`Compute Unit price (micro lamports): ${botConfig.unitPrice}`); 71 | } 72 | 73 | logger.info(`Single token at the time: ${botConfig.oneTokenAtATime}`); 74 | logger.info(`Pre load existing markets: ${PRE_LOAD_EXISTING_MARKETS}`); 75 | logger.info(`Cache new markets: ${CACHE_NEW_MARKETS}`); 76 | logger.info(`Log level: ${LOG_LEVEL}`); 77 | 78 | logger.info('- Buy -'); 79 | logger.info(`Buy amount: ${botConfig.quoteAmount.toFixed()} ${botConfig.quoteToken.name}`); 80 | logger.info(`Auto buy delay: ${botConfig.autoBuyDelay} ms`); 81 | logger.info(`Max buy retries: ${botConfig.maxBuyRetries}`); 82 | logger.info(`Buy amount (${quoteToken.symbol}): ${botConfig.quoteAmount.toFixed()}`); 83 | logger.info(`Buy slippage: ${botConfig.buySlippage}%`); 84 | 85 | logger.info('- Sell -'); 86 | logger.info(`Auto sell: ${AUTO_SELL}`); 87 | logger.info(`Auto sell delay: ${botConfig.autoSellDelay} ms`); 88 | logger.info(`Max sell retries: ${botConfig.maxSellRetries}`); 89 | logger.info(`Sell slippage: ${botConfig.sellSlippage}%`); 90 | logger.info(`Price check interval: ${botConfig.priceCheckInterval} ms`); 91 | logger.info(`Price check duration: ${botConfig.priceCheckDuration} ms`); 92 | logger.info(`Take profit: ${botConfig.takeProfit}%`); 93 | logger.info(`Stop loss: ${botConfig.stopLoss}%`); 94 | 95 | logger.info('- Filters -'); 96 | logger.info(`Snipe list: ${botConfig.useSnipeList}`); 97 | logger.info(`Snipe list refresh interval: ${SNIPE_LIST_REFRESH_INTERVAL} ms`); 98 | logger.info(`Filter check interval: ${botConfig.filterCheckInterval} ms`); 99 | logger.info(`Filter check duration: ${botConfig.filterCheckDuration} ms`); 100 | logger.info(`Consecutive filter matches: ${botConfig.consecutiveMatchCount} ms`); 101 | logger.info(`Check renounced: ${botConfig.checkRenounced}`); 102 | logger.info(`Check burned: ${botConfig.checkBurned}`); 103 | logger.info(`Min pool size: ${botConfig.minPoolSize.toFixed()}`); 104 | logger.info(`Max pool size: ${botConfig.maxPoolSize.toFixed()}`); 105 | 106 | logger.info('------- CONFIGURATION END -------'); 107 | 108 | logger.info('Bot is running! Press CTRL + C to stop it.'); 109 | } 110 | 111 | const runListener = async () => { 112 | logger.level = LOG_LEVEL; 113 | logger.info('Bot is starting...'); 114 | 115 | const marketCache = new MarketCache(connection); 116 | const poolCache = new PoolCache(); 117 | let txExecutor: TransactionExecutor; 118 | 119 | switch (TRANSACTION_EXECUTOR) { 120 | case 'warp': { 121 | txExecutor = new WarpTransactionExecutor(WARP_FEE); 122 | break; 123 | } 124 | default: { 125 | txExecutor = new DefaultTransactionExecutor(connection); 126 | break; 127 | } 128 | } 129 | 130 | const wallet = getWallet(PRIVATE_KEY.trim()); 131 | const quoteToken = getToken(QUOTE_MINT); 132 | const botConfig = { 133 | wallet, 134 | quoteAta: getAssociatedTokenAddressSync(quoteToken.mint, wallet.publicKey), 135 | checkRenounced: CHECK_IF_MINT_IS_RENOUNCED, 136 | checkBurned: CHECK_IF_BURNED, 137 | minPoolSize: new TokenAmount(quoteToken, MIN_POOL_SIZE, false), 138 | maxPoolSize: new TokenAmount(quoteToken, MAX_POOL_SIZE, false), 139 | quoteToken, 140 | quoteAmount: new TokenAmount(quoteToken, QUOTE_AMOUNT, false), 141 | oneTokenAtATime: ONE_TOKEN_AT_A_TIME, 142 | useSnipeList: USE_SNIPE_LIST, 143 | autoSell: AUTO_SELL, 144 | autoSellDelay: AUTO_SELL_DELAY, 145 | maxSellRetries: MAX_SELL_RETRIES, 146 | autoBuyDelay: AUTO_BUY_DELAY, 147 | maxBuyRetries: MAX_BUY_RETRIES, 148 | unitLimit: COMPUTE_UNIT_LIMIT, 149 | unitPrice: COMPUTE_UNIT_PRICE, 150 | takeProfit: TAKE_PROFIT, 151 | stopLoss: STOP_LOSS, 152 | buySlippage: BUY_SLIPPAGE, 153 | sellSlippage: SELL_SLIPPAGE, 154 | priceCheckInterval: PRICE_CHECK_INTERVAL, 155 | priceCheckDuration: PRICE_CHECK_DURATION, 156 | filterCheckInterval: FILTER_CHECK_INTERVAL, 157 | filterCheckDuration: FILTER_CHECK_DURATION, 158 | consecutiveMatchCount: CONSECUTIVE_FILTER_MATCHES, 159 | }; 160 | 161 | const bot = new Bot(connection, marketCache, poolCache, txExecutor, botConfig); 162 | const valid = await bot.validate(); 163 | 164 | if (!valid) { 165 | logger.info('Bot is exiting...'); 166 | process.exit(1); 167 | } 168 | 169 | if (PRE_LOAD_EXISTING_MARKETS) { 170 | await marketCache.init({ quoteToken }); 171 | } 172 | 173 | const runTimestamp = Math.floor(new Date().getTime() / 1000); 174 | const listeners = new Listeners(connection); 175 | await listeners.start({ 176 | walletPublicKey: wallet.publicKey, 177 | quoteToken, 178 | autoSell: AUTO_SELL, 179 | cacheNewMarkets: CACHE_NEW_MARKETS, 180 | }); 181 | 182 | listeners.on('market', (updatedAccountInfo: KeyedAccountInfo) => { 183 | const marketState = MARKET_STATE_LAYOUT_V3.decode(updatedAccountInfo.accountInfo.data); 184 | marketCache.save(updatedAccountInfo.accountId.toString(), marketState); 185 | }); 186 | 187 | listeners.on('pool', async (updatedAccountInfo: KeyedAccountInfo) => { 188 | const poolState = LIQUIDITY_STATE_LAYOUT_V4.decode(updatedAccountInfo.accountInfo.data); 189 | const poolOpenTime = parseInt(poolState.poolOpenTime.toString()); 190 | const exists = await poolCache.get(poolState.baseMint.toString()); 191 | 192 | if (!exists && poolOpenTime > runTimestamp) { 193 | poolCache.save(updatedAccountInfo.accountId.toString(), poolState); 194 | await bot.buy(updatedAccountInfo.accountId, poolState); 195 | } 196 | }); 197 | 198 | listeners.on('wallet', async (updatedAccountInfo: KeyedAccountInfo) => { 199 | const accountData = AccountLayout.decode(updatedAccountInfo.accountInfo.data); 200 | 201 | if (accountData.mint.equals(quoteToken.mint)) { 202 | return; 203 | } 204 | 205 | await bot.sell(updatedAccountInfo.accountId, accountData); 206 | }); 207 | 208 | printDetails(wallet, quoteToken, bot); 209 | }; 210 | 211 | runListener(); 212 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "commonjs", /* Specify what module code is generated. */ 29 | // "rootDir": "./", /* Specify the root folder within your source files. */ 30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ 39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ 40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ 41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ 42 | "resolveJsonModule": true, /* Enable importing .json files. */ 43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ 44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 45 | 46 | /* JavaScript Support */ 47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 50 | 51 | /* Emit */ 52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 57 | // "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. */ 58 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 59 | // "removeComments": true, /* Disable emitting comments. */ 60 | // "noEmit": true, /* Disable emitting files from a compilation. */ 61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 68 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 75 | 76 | /* Interop Constraints */ 77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 78 | // "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. */ 79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ 81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 83 | 84 | /* Type Checking */ 85 | "strict": true, /* Enable all strict type-checking options. */ 86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 104 | 105 | /* Completeness */ 106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /bot.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ComputeBudgetProgram, 3 | Connection, 4 | Keypair, 5 | PublicKey, 6 | TransactionMessage, 7 | VersionedTransaction, 8 | } from '@solana/web3.js'; 9 | import { 10 | createAssociatedTokenAccountIdempotentInstruction, 11 | createCloseAccountInstruction, 12 | getAccount, 13 | getAssociatedTokenAddress, 14 | RawAccount, 15 | TOKEN_PROGRAM_ID, 16 | } from '@solana/spl-token'; 17 | import { Liquidity, LiquidityPoolKeysV4, LiquidityStateV4, Percent, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 18 | import { MarketCache, PoolCache, SnipeListCache } from './cache'; 19 | import { PoolFilters } from './filters'; 20 | import { TransactionExecutor } from './transactions'; 21 | import { createPoolKeys, logger, NETWORK, sleep } from './helpers'; 22 | import { Mutex } from 'async-mutex'; 23 | import BN from 'bn.js'; 24 | import { WarpTransactionExecutor } from './transactions/warp-transaction-executor'; 25 | 26 | export interface BotConfig { 27 | wallet: Keypair; 28 | checkRenounced: boolean; 29 | checkBurned: boolean; 30 | minPoolSize: TokenAmount; 31 | maxPoolSize: TokenAmount; 32 | quoteToken: Token; 33 | quoteAmount: TokenAmount; 34 | quoteAta: PublicKey; 35 | oneTokenAtATime: boolean; 36 | useSnipeList: boolean; 37 | autoSell: boolean; 38 | autoBuyDelay: number; 39 | autoSellDelay: number; 40 | maxBuyRetries: number; 41 | maxSellRetries: number; 42 | unitLimit: number; 43 | unitPrice: number; 44 | takeProfit: number; 45 | stopLoss: number; 46 | buySlippage: number; 47 | sellSlippage: number; 48 | priceCheckInterval: number; 49 | priceCheckDuration: number; 50 | filterCheckInterval: number; 51 | filterCheckDuration: number; 52 | consecutiveMatchCount: number; 53 | } 54 | 55 | export class Bot { 56 | private readonly poolFilters: PoolFilters; 57 | 58 | // snipe list 59 | private readonly snipeListCache?: SnipeListCache; 60 | 61 | // one token at the time 62 | private readonly mutex: Mutex; 63 | private sellExecutionCount = 0; 64 | public readonly isWarp: boolean = false; 65 | 66 | constructor( 67 | private readonly connection: Connection, 68 | private readonly marketStorage: MarketCache, 69 | private readonly poolStorage: PoolCache, 70 | private readonly txExecutor: TransactionExecutor, 71 | readonly config: BotConfig, 72 | ) { 73 | this.isWarp = txExecutor instanceof WarpTransactionExecutor; 74 | 75 | this.mutex = new Mutex(); 76 | this.poolFilters = new PoolFilters(connection, { 77 | quoteToken: this.config.quoteToken, 78 | minPoolSize: this.config.minPoolSize, 79 | maxPoolSize: this.config.maxPoolSize, 80 | }); 81 | 82 | if (this.config.useSnipeList) { 83 | this.snipeListCache = new SnipeListCache(); 84 | this.snipeListCache.init(); 85 | } 86 | } 87 | 88 | async validate() { 89 | try { 90 | await getAccount(this.connection, this.config.quoteAta, this.connection.commitment); 91 | } catch (error) { 92 | logger.error( 93 | `${this.config.quoteToken.symbol} token account not found in wallet: ${this.config.wallet.publicKey.toString()}`, 94 | ); 95 | return false; 96 | } 97 | 98 | return true; 99 | } 100 | 101 | public async buy(accountId: PublicKey, poolState: LiquidityStateV4) { 102 | logger.trace({ mint: poolState.baseMint }, `Processing buy...`); 103 | 104 | if (this.config.useSnipeList && !this.snipeListCache?.isInList(poolState.baseMint.toString())) { 105 | logger.debug({ mint: poolState.baseMint.toString() }, `Skipping buy because token is not in a snipe list`); 106 | return; 107 | } 108 | 109 | if (this.config.autoBuyDelay > 0) { 110 | logger.debug({ mint: poolState.baseMint }, `Waiting for ${this.config.autoBuyDelay} ms before buy`); 111 | await sleep(this.config.autoBuyDelay); 112 | } 113 | 114 | if (this.config.oneTokenAtATime) { 115 | if (this.mutex.isLocked() || this.sellExecutionCount > 0) { 116 | logger.debug( 117 | { mint: poolState.baseMint.toString() }, 118 | `Skipping buy because one token at a time is turned on and token is already being processed`, 119 | ); 120 | return; 121 | } 122 | 123 | await this.mutex.acquire(); 124 | } 125 | 126 | try { 127 | const [market, mintAta] = await Promise.all([ 128 | this.marketStorage.get(poolState.marketId.toString()), 129 | getAssociatedTokenAddress(poolState.baseMint, this.config.wallet.publicKey), 130 | ]); 131 | const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(accountId, poolState, market); 132 | 133 | const match = await this.filterMatch(poolKeys); 134 | 135 | if (!match) { 136 | logger.trace({ mint: poolKeys.baseMint.toString() }, `Skipping buy because pool doesn't match filters`); 137 | return; 138 | } 139 | 140 | for (let i = 0; i < this.config.maxBuyRetries; i++) { 141 | try { 142 | logger.info( 143 | { mint: poolState.baseMint.toString() }, 144 | `Send buy transaction attempt: ${i + 1}/${this.config.maxBuyRetries}`, 145 | ); 146 | const tokenOut = new Token(TOKEN_PROGRAM_ID, poolKeys.baseMint, poolKeys.baseDecimals); 147 | const result = await this.swap( 148 | poolKeys, 149 | this.config.quoteAta, 150 | mintAta, 151 | this.config.quoteToken, 152 | tokenOut, 153 | this.config.quoteAmount, 154 | this.config.buySlippage, 155 | this.config.wallet, 156 | 'buy', 157 | ); 158 | 159 | if (result.confirmed) { 160 | logger.info( 161 | { 162 | mint: poolState.baseMint.toString(), 163 | signature: result.signature, 164 | url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`, 165 | }, 166 | `Confirmed buy tx`, 167 | ); 168 | 169 | break; 170 | } 171 | 172 | logger.debug( 173 | { 174 | mint: poolState.baseMint.toString(), 175 | signature: result.signature, 176 | }, 177 | `Error confirming buy tx`, 178 | ); 179 | } catch (error) { 180 | logger.debug({ mint: poolState.baseMint.toString(), error }, `Error confirming buy transaction`); 181 | } 182 | } 183 | } catch (error) { 184 | logger.error({ mint: poolState.baseMint.toString(), error }, `Failed to buy token`); 185 | } finally { 186 | if (this.config.oneTokenAtATime) { 187 | this.mutex.release(); 188 | } 189 | } 190 | } 191 | 192 | public async sell(accountId: PublicKey, rawAccount: RawAccount) { 193 | if (this.config.oneTokenAtATime) { 194 | this.sellExecutionCount++; 195 | } 196 | 197 | try { 198 | logger.trace({ mint: rawAccount.mint }, `Processing sell...`); 199 | 200 | const poolData = await this.poolStorage.get(rawAccount.mint.toString()); 201 | 202 | if (!poolData) { 203 | logger.trace({ mint: rawAccount.mint.toString() }, `Token pool data is not found, can't sell`); 204 | return; 205 | } 206 | 207 | const tokenIn = new Token(TOKEN_PROGRAM_ID, poolData.state.baseMint, poolData.state.baseDecimal.toNumber()); 208 | const tokenAmountIn = new TokenAmount(tokenIn, rawAccount.amount, true); 209 | 210 | if (tokenAmountIn.isZero()) { 211 | logger.info({ mint: rawAccount.mint.toString() }, `Empty balance, can't sell`); 212 | return; 213 | } 214 | 215 | if (this.config.autoSellDelay > 0) { 216 | logger.debug({ mint: rawAccount.mint }, `Waiting for ${this.config.autoSellDelay} ms before sell`); 217 | await sleep(this.config.autoSellDelay); 218 | } 219 | 220 | const market = await this.marketStorage.get(poolData.state.marketId.toString()); 221 | const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(new PublicKey(poolData.id), poolData.state, market); 222 | 223 | await this.priceMatch(tokenAmountIn, poolKeys); 224 | 225 | for (let i = 0; i < this.config.maxSellRetries; i++) { 226 | try { 227 | logger.info( 228 | { mint: rawAccount.mint }, 229 | `Send sell transaction attempt: ${i + 1}/${this.config.maxSellRetries}`, 230 | ); 231 | 232 | const result = await this.swap( 233 | poolKeys, 234 | accountId, 235 | this.config.quoteAta, 236 | tokenIn, 237 | this.config.quoteToken, 238 | tokenAmountIn, 239 | this.config.sellSlippage, 240 | this.config.wallet, 241 | 'sell', 242 | ); 243 | 244 | if (result.confirmed) { 245 | logger.info( 246 | { 247 | dex: `https://dexscreener.com/solana/${rawAccount.mint.toString()}?maker=${this.config.wallet.publicKey}`, 248 | mint: rawAccount.mint.toString(), 249 | signature: result.signature, 250 | url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`, 251 | }, 252 | `Confirmed sell tx`, 253 | ); 254 | break; 255 | } 256 | 257 | logger.info( 258 | { 259 | mint: rawAccount.mint.toString(), 260 | signature: result.signature, 261 | }, 262 | `Error confirming sell tx`, 263 | ); 264 | } catch (error) { 265 | logger.debug({ mint: rawAccount.mint.toString(), error }, `Error confirming sell transaction`); 266 | } 267 | } 268 | } catch (error) { 269 | logger.debug({ mint: rawAccount.mint.toString(), error }, `Failed to sell token`); 270 | } finally { 271 | if (this.config.oneTokenAtATime) { 272 | this.sellExecutionCount--; 273 | } 274 | } 275 | } 276 | 277 | private async swap( 278 | poolKeys: LiquidityPoolKeysV4, 279 | ataIn: PublicKey, 280 | ataOut: PublicKey, 281 | tokenIn: Token, 282 | tokenOut: Token, 283 | amountIn: TokenAmount, 284 | slippage: number, 285 | wallet: Keypair, 286 | direction: 'buy' | 'sell', 287 | ) { 288 | const slippagePercent = new Percent(slippage, 100); 289 | const poolInfo = await Liquidity.fetchInfo({ 290 | connection: this.connection, 291 | poolKeys, 292 | }); 293 | 294 | const computedAmountOut = Liquidity.computeAmountOut({ 295 | poolKeys, 296 | poolInfo, 297 | amountIn, 298 | currencyOut: tokenOut, 299 | slippage: slippagePercent, 300 | }); 301 | 302 | const latestBlockhash = await this.connection.getLatestBlockhash(); 303 | const { innerTransaction } = Liquidity.makeSwapFixedInInstruction( 304 | { 305 | poolKeys: poolKeys, 306 | userKeys: { 307 | tokenAccountIn: ataIn, 308 | tokenAccountOut: ataOut, 309 | owner: wallet.publicKey, 310 | }, 311 | amountIn: amountIn.raw, 312 | minAmountOut: computedAmountOut.minAmountOut.raw, 313 | }, 314 | poolKeys.version, 315 | ); 316 | 317 | const messageV0 = new TransactionMessage({ 318 | payerKey: wallet.publicKey, 319 | recentBlockhash: latestBlockhash.blockhash, 320 | instructions: [ 321 | ...(this.isWarp 322 | ? [] 323 | : [ 324 | ComputeBudgetProgram.setComputeUnitPrice({ microLamports: this.config.unitPrice }), 325 | ComputeBudgetProgram.setComputeUnitLimit({ units: this.config.unitLimit }), 326 | ]), 327 | ...(direction === 'buy' 328 | ? [ 329 | createAssociatedTokenAccountIdempotentInstruction( 330 | wallet.publicKey, 331 | ataOut, 332 | wallet.publicKey, 333 | tokenOut.mint, 334 | ), 335 | ] 336 | : []), 337 | ...innerTransaction.instructions, 338 | ...(direction === 'sell' ? [createCloseAccountInstruction(ataIn, wallet.publicKey, wallet.publicKey)] : []), 339 | ], 340 | }).compileToV0Message(); 341 | 342 | const transaction = new VersionedTransaction(messageV0); 343 | transaction.sign([wallet, ...innerTransaction.signers]); 344 | 345 | return this.txExecutor.executeAndConfirm(transaction, wallet, latestBlockhash); 346 | } 347 | 348 | private async filterMatch(poolKeys: LiquidityPoolKeysV4) { 349 | if (this.config.filterCheckInterval === 0 || this.config.filterCheckDuration === 0) { 350 | return; 351 | } 352 | 353 | const timesToCheck = this.config.filterCheckDuration / this.config.filterCheckInterval; 354 | let timesChecked = 0; 355 | let matchCount = 0; 356 | 357 | do { 358 | try { 359 | const shouldBuy = await this.poolFilters.execute(poolKeys); 360 | 361 | if (shouldBuy) { 362 | matchCount++; 363 | 364 | if (this.config.consecutiveMatchCount <= matchCount) { 365 | logger.debug( 366 | { mint: poolKeys.baseMint.toString() }, 367 | `Filter match ${matchCount}/${this.config.consecutiveMatchCount}`, 368 | ); 369 | return true; 370 | } 371 | } else { 372 | matchCount = 0; 373 | } 374 | 375 | await sleep(this.config.filterCheckInterval); 376 | } finally { 377 | timesChecked++; 378 | } 379 | } while (timesChecked < timesToCheck); 380 | 381 | return false; 382 | } 383 | 384 | private async priceMatch(amountIn: TokenAmount, poolKeys: LiquidityPoolKeysV4) { 385 | if (this.config.priceCheckDuration === 0 || this.config.priceCheckInterval === 0) { 386 | return; 387 | } 388 | 389 | const timesToCheck = this.config.priceCheckDuration / this.config.priceCheckInterval; 390 | const profitFraction = this.config.quoteAmount.mul(this.config.takeProfit).numerator.div(new BN(100)); 391 | const profitAmount = new TokenAmount(this.config.quoteToken, profitFraction, true); 392 | const takeProfit = this.config.quoteAmount.add(profitAmount); 393 | 394 | const lossFraction = this.config.quoteAmount.mul(this.config.stopLoss).numerator.div(new BN(100)); 395 | const lossAmount = new TokenAmount(this.config.quoteToken, lossFraction, true); 396 | const stopLoss = this.config.quoteAmount.subtract(lossAmount); 397 | const slippage = new Percent(this.config.sellSlippage, 100); 398 | let timesChecked = 0; 399 | 400 | do { 401 | try { 402 | const poolInfo = await Liquidity.fetchInfo({ 403 | connection: this.connection, 404 | poolKeys, 405 | }); 406 | 407 | const amountOut = Liquidity.computeAmountOut({ 408 | poolKeys, 409 | poolInfo, 410 | amountIn: amountIn, 411 | currencyOut: this.config.quoteToken, 412 | slippage, 413 | }).amountOut; 414 | 415 | logger.debug( 416 | { mint: poolKeys.baseMint.toString() }, 417 | `Take profit: ${takeProfit.toFixed()} | Stop loss: ${stopLoss.toFixed()} | Current: ${amountOut.toFixed()}`, 418 | ); 419 | 420 | if (amountOut.lt(stopLoss)) { 421 | break; 422 | } 423 | 424 | if (amountOut.gt(takeProfit)) { 425 | break; 426 | } 427 | 428 | await sleep(this.config.priceCheckInterval); 429 | } catch (e) { 430 | logger.trace({ mint: poolKeys.baseMint.toString(), e }, `Failed to check token price`); 431 | } finally { 432 | timesChecked++; 433 | } 434 | } while (timesChecked < timesToCheck); 435 | } 436 | } 437 | -------------------------------------------------------------------------------- /src/bot.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ComputeBudgetProgram, 3 | Connection, 4 | Keypair, 5 | PublicKey, 6 | TransactionMessage, 7 | VersionedTransaction, 8 | } from '@solana/web3.js'; 9 | import { 10 | createAssociatedTokenAccountIdempotentInstruction, 11 | createCloseAccountInstruction, 12 | getAccount, 13 | getAssociatedTokenAddress, 14 | RawAccount, 15 | TOKEN_PROGRAM_ID, 16 | } from '@solana/spl-token'; 17 | import { Liquidity, LiquidityPoolKeysV4, LiquidityStateV4, Percent, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 18 | import { MarketCache, PoolCache, SnipeListCache } from './cache'; 19 | import { PoolFilters } from './filters'; 20 | import { TransactionExecutor } from './transactions'; 21 | import { createPoolKeys, logger, NETWORK, sleep } from './helpers'; 22 | import { Mutex } from 'async-mutex'; 23 | import BN from 'bn.js'; 24 | import { WarpTransactionExecutor } from './transactions/warp-transaction-executor'; 25 | 26 | export interface BotConfig { 27 | wallet: Keypair; 28 | checkRenounced: boolean; 29 | checkBurned: boolean; 30 | minPoolSize: TokenAmount; 31 | maxPoolSize: TokenAmount; 32 | quoteToken: Token; 33 | quoteAmount: TokenAmount; 34 | quoteAta: PublicKey; 35 | oneTokenAtATime: boolean; 36 | useSnipeList: boolean; 37 | autoSell: boolean; 38 | autoBuyDelay: number; 39 | autoSellDelay: number; 40 | maxBuyRetries: number; 41 | maxSellRetries: number; 42 | unitLimit: number; 43 | unitPrice: number; 44 | takeProfit: number; 45 | stopLoss: number; 46 | buySlippage: number; 47 | sellSlippage: number; 48 | priceCheckInterval: number; 49 | priceCheckDuration: number; 50 | filterCheckInterval: number; 51 | filterCheckDuration: number; 52 | consecutiveMatchCount: number; 53 | } 54 | 55 | export class Bot { 56 | private readonly poolFilters: PoolFilters; 57 | 58 | // snipe list 59 | private readonly snipeListCache?: SnipeListCache; 60 | 61 | // one token at the time 62 | private readonly mutex: Mutex; 63 | private sellExecutionCount = 0; 64 | public readonly isWarp: boolean = false; 65 | 66 | constructor( 67 | private readonly connection: Connection, 68 | private readonly marketStorage: MarketCache, 69 | private readonly poolStorage: PoolCache, 70 | private readonly txExecutor: TransactionExecutor, 71 | readonly config: BotConfig, 72 | ) { 73 | this.isWarp = txExecutor instanceof WarpTransactionExecutor; 74 | 75 | this.mutex = new Mutex(); 76 | this.poolFilters = new PoolFilters(connection, { 77 | quoteToken: this.config.quoteToken, 78 | minPoolSize: this.config.minPoolSize, 79 | maxPoolSize: this.config.maxPoolSize, 80 | }); 81 | 82 | if (this.config.useSnipeList) { 83 | this.snipeListCache = new SnipeListCache(); 84 | this.snipeListCache.init(); 85 | } 86 | } 87 | 88 | async validate() { 89 | try { 90 | await getAccount(this.connection, this.config.quoteAta, this.connection.commitment); 91 | } catch (error) { 92 | logger.error( 93 | `${this.config.quoteToken.symbol} token account not found in wallet: ${this.config.wallet.publicKey.toString()}`, 94 | ); 95 | return false; 96 | } 97 | 98 | return true; 99 | } 100 | 101 | public async buy(accountId: PublicKey, poolState: LiquidityStateV4) { 102 | logger.trace({ mint: poolState.baseMint }, `Processing buy...`); 103 | 104 | if (this.config.useSnipeList && !this.snipeListCache?.isInList(poolState.baseMint.toString())) { 105 | logger.debug({ mint: poolState.baseMint.toString() }, `Skipping buy because token is not in a snipe list`); 106 | return; 107 | } 108 | 109 | if (this.config.autoBuyDelay > 0) { 110 | logger.debug({ mint: poolState.baseMint }, `Waiting for ${this.config.autoBuyDelay} ms before buy`); 111 | await sleep(this.config.autoBuyDelay); 112 | } 113 | 114 | if (this.config.oneTokenAtATime) { 115 | if (this.mutex.isLocked() || this.sellExecutionCount > 0) { 116 | logger.debug( 117 | { mint: poolState.baseMint.toString() }, 118 | `Skipping buy because one token at a time is turned on and token is already being processed`, 119 | ); 120 | return; 121 | } 122 | 123 | await this.mutex.acquire(); 124 | } 125 | 126 | try { 127 | const [market, mintAta] = await Promise.all([ 128 | this.marketStorage.get(poolState.marketId.toString()), 129 | getAssociatedTokenAddress(poolState.baseMint, this.config.wallet.publicKey), 130 | ]); 131 | const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(accountId, poolState, market); 132 | 133 | const match = await this.filterMatch(poolKeys); 134 | 135 | if (!match) { 136 | logger.trace({ mint: poolKeys.baseMint.toString() }, `Skipping buy because pool doesn't match filters`); 137 | return; 138 | } 139 | 140 | for (let i = 0; i < this.config.maxBuyRetries; i++) { 141 | try { 142 | logger.info( 143 | { mint: poolState.baseMint.toString() }, 144 | `Send buy transaction attempt: ${i + 1}/${this.config.maxBuyRetries}`, 145 | ); 146 | const tokenOut = new Token(TOKEN_PROGRAM_ID, poolKeys.baseMint, poolKeys.baseDecimals); 147 | const result = await this.swap( 148 | poolKeys, 149 | this.config.quoteAta, 150 | mintAta, 151 | this.config.quoteToken, 152 | tokenOut, 153 | this.config.quoteAmount, 154 | this.config.buySlippage, 155 | this.config.wallet, 156 | 'buy', 157 | ); 158 | 159 | if (result.confirmed) { 160 | logger.info( 161 | { 162 | mint: poolState.baseMint.toString(), 163 | signature: result.signature, 164 | url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`, 165 | }, 166 | `Confirmed buy tx`, 167 | ); 168 | 169 | break; 170 | } 171 | 172 | logger.debug( 173 | { 174 | mint: poolState.baseMint.toString(), 175 | signature: result.signature, 176 | }, 177 | `Error confirming buy tx`, 178 | ); 179 | } catch (error) { 180 | logger.debug({ mint: poolState.baseMint.toString(), error }, `Error confirming buy transaction`); 181 | } 182 | } 183 | } catch (error) { 184 | logger.error({ mint: poolState.baseMint.toString(), error }, `Failed to buy token`); 185 | } finally { 186 | if (this.config.oneTokenAtATime) { 187 | this.mutex.release(); 188 | } 189 | } 190 | } 191 | 192 | public async sell(accountId: PublicKey, rawAccount: RawAccount) { 193 | if (this.config.oneTokenAtATime) { 194 | this.sellExecutionCount++; 195 | } 196 | 197 | try { 198 | logger.trace({ mint: rawAccount.mint }, `Processing sell...`); 199 | 200 | const poolData = await this.poolStorage.get(rawAccount.mint.toString()); 201 | 202 | if (!poolData) { 203 | logger.trace({ mint: rawAccount.mint.toString() }, `Token pool data is not found, can't sell`); 204 | return; 205 | } 206 | 207 | const tokenIn = new Token(TOKEN_PROGRAM_ID, poolData.state.baseMint, poolData.state.baseDecimal.toNumber()); 208 | const tokenAmountIn = new TokenAmount(tokenIn, rawAccount.amount, true); 209 | 210 | if (tokenAmountIn.isZero()) { 211 | logger.info({ mint: rawAccount.mint.toString() }, `Empty balance, can't sell`); 212 | return; 213 | } 214 | 215 | if (this.config.autoSellDelay > 0) { 216 | logger.debug({ mint: rawAccount.mint }, `Waiting for ${this.config.autoSellDelay} ms before sell`); 217 | await sleep(this.config.autoSellDelay); 218 | } 219 | 220 | const market = await this.marketStorage.get(poolData.state.marketId.toString()); 221 | const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(new PublicKey(poolData.id), poolData.state, market); 222 | 223 | await this.priceMatch(tokenAmountIn, poolKeys); 224 | 225 | for (let i = 0; i < this.config.maxSellRetries; i++) { 226 | try { 227 | logger.info( 228 | { mint: rawAccount.mint }, 229 | `Send sell transaction attempt: ${i + 1}/${this.config.maxSellRetries}`, 230 | ); 231 | 232 | const result = await this.swap( 233 | poolKeys, 234 | accountId, 235 | this.config.quoteAta, 236 | tokenIn, 237 | this.config.quoteToken, 238 | tokenAmountIn, 239 | this.config.sellSlippage, 240 | this.config.wallet, 241 | 'sell', 242 | ); 243 | 244 | if (result.confirmed) { 245 | logger.info( 246 | { 247 | dex: `https://dexscreener.com/solana/${rawAccount.mint.toString()}?maker=${this.config.wallet.publicKey}`, 248 | mint: rawAccount.mint.toString(), 249 | signature: result.signature, 250 | url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`, 251 | }, 252 | `Confirmed sell tx`, 253 | ); 254 | break; 255 | } 256 | 257 | logger.info( 258 | { 259 | mint: rawAccount.mint.toString(), 260 | signature: result.signature, 261 | }, 262 | `Error confirming sell tx`, 263 | ); 264 | } catch (error) { 265 | logger.debug({ mint: rawAccount.mint.toString(), error }, `Error confirming sell transaction`); 266 | } 267 | } 268 | } catch (error) { 269 | logger.debug({ mint: rawAccount.mint.toString(), error }, `Failed to sell token`); 270 | } finally { 271 | if (this.config.oneTokenAtATime) { 272 | this.sellExecutionCount--; 273 | } 274 | } 275 | } 276 | 277 | private async swap( 278 | poolKeys: LiquidityPoolKeysV4, 279 | ataIn: PublicKey, 280 | ataOut: PublicKey, 281 | tokenIn: Token, 282 | tokenOut: Token, 283 | amountIn: TokenAmount, 284 | slippage: number, 285 | wallet: Keypair, 286 | direction: 'buy' | 'sell', 287 | ) { 288 | const slippagePercent = new Percent(slippage, 100); 289 | const poolInfo = await Liquidity.fetchInfo({ 290 | connection: this.connection, 291 | poolKeys, 292 | }); 293 | 294 | const computedAmountOut = Liquidity.computeAmountOut({ 295 | poolKeys, 296 | poolInfo, 297 | amountIn, 298 | currencyOut: tokenOut, 299 | slippage: slippagePercent, 300 | }); 301 | 302 | const latestBlockhash = await this.connection.getLatestBlockhash(); 303 | const { innerTransaction } = Liquidity.makeSwapFixedInInstruction( 304 | { 305 | poolKeys: poolKeys, 306 | userKeys: { 307 | tokenAccountIn: ataIn, 308 | tokenAccountOut: ataOut, 309 | owner: wallet.publicKey, 310 | }, 311 | amountIn: amountIn.raw, 312 | minAmountOut: computedAmountOut.minAmountOut.raw, 313 | }, 314 | poolKeys.version, 315 | ); 316 | 317 | const messageV0 = new TransactionMessage({ 318 | payerKey: wallet.publicKey, 319 | recentBlockhash: latestBlockhash.blockhash, 320 | instructions: [ 321 | ...(this.isWarp 322 | ? [] 323 | : [ 324 | ComputeBudgetProgram.setComputeUnitPrice({ microLamports: this.config.unitPrice }), 325 | ComputeBudgetProgram.setComputeUnitLimit({ units: this.config.unitLimit }), 326 | ]), 327 | ...(direction === 'buy' 328 | ? [ 329 | createAssociatedTokenAccountIdempotentInstruction( 330 | wallet.publicKey, 331 | ataOut, 332 | wallet.publicKey, 333 | tokenOut.mint, 334 | ), 335 | ] 336 | : []), 337 | ...innerTransaction.instructions, 338 | ...(direction === 'sell' ? [createCloseAccountInstruction(ataIn, wallet.publicKey, wallet.publicKey)] : []), 339 | ], 340 | }).compileToV0Message(); 341 | 342 | const transaction = new VersionedTransaction(messageV0); 343 | transaction.sign([wallet, ...innerTransaction.signers]); 344 | 345 | return this.txExecutor.executeAndConfirm(transaction, wallet, latestBlockhash); 346 | } 347 | 348 | private async filterMatch(poolKeys: LiquidityPoolKeysV4) { 349 | if (this.config.filterCheckInterval === 0 || this.config.filterCheckDuration === 0) { 350 | return; 351 | } 352 | 353 | const timesToCheck = this.config.filterCheckDuration / this.config.filterCheckInterval; 354 | let timesChecked = 0; 355 | let matchCount = 0; 356 | 357 | do { 358 | try { 359 | const shouldBuy = await this.poolFilters.execute(poolKeys); 360 | 361 | if (shouldBuy) { 362 | matchCount++; 363 | 364 | if (this.config.consecutiveMatchCount <= matchCount) { 365 | logger.debug( 366 | { mint: poolKeys.baseMint.toString() }, 367 | `Filter match ${matchCount}/${this.config.consecutiveMatchCount}`, 368 | ); 369 | return true; 370 | } 371 | } else { 372 | matchCount = 0; 373 | } 374 | 375 | await sleep(this.config.filterCheckInterval); 376 | } finally { 377 | timesChecked++; 378 | } 379 | } while (timesChecked < timesToCheck); 380 | 381 | return false; 382 | } 383 | 384 | private async priceMatch(amountIn: TokenAmount, poolKeys: LiquidityPoolKeysV4) { 385 | if (this.config.priceCheckDuration === 0 || this.config.priceCheckInterval === 0) { 386 | return; 387 | } 388 | 389 | const timesToCheck = this.config.priceCheckDuration / this.config.priceCheckInterval; 390 | const profitFraction = this.config.quoteAmount.mul(this.config.takeProfit).numerator.div(new BN(100)); 391 | const profitAmount = new TokenAmount(this.config.quoteToken, profitFraction, true); 392 | const takeProfit = this.config.quoteAmount.add(profitAmount); 393 | 394 | const lossFraction = this.config.quoteAmount.mul(this.config.stopLoss).numerator.div(new BN(100)); 395 | const lossAmount = new TokenAmount(this.config.quoteToken, lossFraction, true); 396 | const stopLoss = this.config.quoteAmount.subtract(lossAmount); 397 | const slippage = new Percent(this.config.sellSlippage, 100); 398 | let timesChecked = 0; 399 | 400 | do { 401 | try { 402 | const poolInfo = await Liquidity.fetchInfo({ 403 | connection: this.connection, 404 | poolKeys, 405 | }); 406 | 407 | const amountOut = Liquidity.computeAmountOut({ 408 | poolKeys, 409 | poolInfo, 410 | amountIn: amountIn, 411 | currencyOut: this.config.quoteToken, 412 | slippage, 413 | }).amountOut; 414 | 415 | logger.debug( 416 | { mint: poolKeys.baseMint.toString() }, 417 | `Take profit: ${takeProfit.toFixed()} | Stop loss: ${stopLoss.toFixed()} | Current: ${amountOut.toFixed()}`, 418 | ); 419 | 420 | if (amountOut.lt(stopLoss)) { 421 | break; 422 | } 423 | 424 | if (amountOut.gt(takeProfit)) { 425 | break; 426 | } 427 | 428 | await sleep(this.config.priceCheckInterval); 429 | } catch (e) { 430 | logger.trace({ mint: poolKeys.baseMint.toString(), e }, `Failed to check token price`); 431 | } finally { 432 | timesChecked++; 433 | } 434 | } while (timesChecked < timesToCheck); 435 | } 436 | } 437 | --------------------------------------------------------------------------------