├── buy.ts ├── snipe-list.txt ├── constants └── constants.ts ├── listeners ├── index.ts └── listeners.ts ├── readme ├── wsol.png └── output.png ├── .prettierrc ├── helpers ├── promises.ts ├── index.ts ├── logger.ts ├── token.ts ├── wallet.ts ├── market.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 └── jito-rpc-transaction-executor.ts ├── filters ├── index.ts ├── burn.filter.ts ├── mutable.filter.ts ├── pool-size.filter.ts ├── renounced.filter.ts └── pool-filters.ts ├── package.json ├── .env.copy ├── LICENSE.md ├── .gitignore ├── README.md ├── index.ts ├── tsconfig.json └── bot.ts /buy.ts: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /snipe-list.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /constants/constants.ts: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /listeners/index.ts: -------------------------------------------------------------------------------- 1 | export * from './listeners'; 2 | -------------------------------------------------------------------------------- /readme/wsol.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oboshto/solana-sniper-bot/HEAD/readme/wsol.png -------------------------------------------------------------------------------- /readme/output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oboshto/solana-sniper-bot/HEAD/readme/output.png -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all", 4 | "printWidth": 120 5 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /transactions/index.ts: -------------------------------------------------------------------------------- 1 | export * from './default-transaction-executor'; 2 | export * from './transaction-executor.interface'; 3 | -------------------------------------------------------------------------------- /filters/index.ts: -------------------------------------------------------------------------------- 1 | export * from './burn.filter'; 2 | export * from './mutable.filter'; 3 | export * from './pool-filters'; 4 | export * from './pool-size.filter'; 5 | export * from './renounced.filter'; 6 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /transactions/transaction-executor.interface.ts: -------------------------------------------------------------------------------- 1 | import { BlockhashWithExpiryBlockHeight, Keypair, 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, error?: string }>; 9 | } 10 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 : `${poolKeys.baseMint} - 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 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "warp-solana-bot", 3 | "author": "Filip Dundjer", 4 | "homepage": "https://warp.id", 5 | "version": "2.0.1", 6 | "scripts": { 7 | "start": "ts-node index.ts", 8 | "tsc": "tsc --noEmit" 9 | }, 10 | "dependencies": { 11 | "@metaplex-foundation/mpl-token-metadata": "^3.2.1", 12 | "@raydium-io/raydium-sdk": "^1.3.1-beta.47", 13 | "@solana/spl-token": "^0.4.0", 14 | "@solana/web3.js": "^1.89.1", 15 | "async-mutex": "^0.5.0", 16 | "axios": "^1.6.8", 17 | "bigint-buffer": "^1.1.5", 18 | "bip39": "^3.1.0", 19 | "bn.js": "^5.2.1", 20 | "bs58": "^5.0.0", 21 | "dotenv": "^16.4.1", 22 | "ed25519-hd-key": "^1.3.0", 23 | "i": "^0.3.7", 24 | "jito-ts": "^3.0.1", 25 | "npm": "^10.5.2", 26 | "pino": "^8.18.0", 27 | "pino-pretty": "^10.3.1", 28 | "pino-std-serializers": "^6.2.2" 29 | }, 30 | "devDependencies": { 31 | "@types/bn.js": "^5.1.5", 32 | "prettier": "^3.2.4", 33 | "ts-node": "^10.9.2", 34 | "typescript": "^5.3.3" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /.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 or jito 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 or jito executor, fee below will be applied 20 | CUSTOM_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 | TRAILING_STOP=true 38 | SCALE_OUT=false 39 | SELL_SLIPPAGE=20 40 | SKIP_SELLING_IF_LOST_90PERCENT=true 41 | 42 | # Filters 43 | USE_SNIPE_LIST=false 44 | SNIPE_LIST_REFRESH_INTERVAL=30000 45 | FILTER_CHECK_DURATION=60000 46 | FILTER_CHECK_INTERVAL=2000 47 | CONSECUTIVE_FILTER_MATCHES=3 48 | CHECK_IF_MUTABLE=false 49 | CHECK_IF_MINT_IS_RENOUNCED=true 50 | CHECK_IF_FREEZABLE=false 51 | CHECK_IF_BURNED=true 52 | MIN_POOL_SIZE=5 53 | MAX_POOL_SIZE=50 54 | -------------------------------------------------------------------------------- /filters/mutable.filter.ts: -------------------------------------------------------------------------------- 1 | import { Filter, FilterResult } from './pool-filters'; 2 | import { Connection, PublicKey } from '@solana/web3.js'; 3 | import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; 4 | import { getPdaMetadataKey } from '@raydium-io/raydium-sdk'; 5 | import { getMetadataAccountDataSerializer, MetadataAccountData, MetadataAccountDataArgs } from '@metaplex-foundation/mpl-token-metadata'; 6 | import { Serializer } from '@metaplex-foundation/umi/serializers'; 7 | import { logger } from '../helpers'; 8 | 9 | export class MutableFilter implements Filter { 10 | constructor(private readonly connection: Connection, private readonly metadataSerializer: Serializer) {} 11 | 12 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 13 | try { 14 | const metadataPDA = getPdaMetadataKey(poolKeys.baseMint); 15 | const metadataAccount = await this.connection.getAccountInfo(metadataPDA.publicKey); 16 | if (!metadataAccount?.data) { 17 | return { ok: false, message: 'Mutable -> Failed to fetch account data' }; 18 | } 19 | const deserialize = this.metadataSerializer.deserialize(metadataAccount.data); 20 | const mutable = deserialize[0].isMutable; 21 | 22 | return { ok: !mutable, message: !mutable ? undefined : "Mutable -> Creator can change metadata" }; 23 | } catch (e: any) { 24 | logger.error({ mint: poolKeys.baseMint }, `Mutable -> Failed to check if metadata are mutable`); 25 | } 26 | 27 | return { ok: false, message: 'Mutable -> Failed to check if metadata are mutable' }; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /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 | 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | 15 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 16 | try { 17 | const response = await this.connection.getTokenAccountBalance(poolKeys.quoteVault, this.connection.commitment); 18 | const poolSize = new TokenAmount(this.quoteToken, response.value.amount, true); 19 | let inRange = true; 20 | 21 | if (!this.maxPoolSize?.isZero()) { 22 | inRange = poolSize.raw.lte(this.maxPoolSize.raw); 23 | 24 | if (!inRange) { 25 | return { ok: false, message: `${poolKeys.baseMint} - PoolSize -> Pool size ${poolSize.toFixed()} > ${this.maxPoolSize.toFixed()}` }; 26 | } 27 | } 28 | 29 | if (!this.minPoolSize?.isZero()) { 30 | inRange = poolSize.raw.gte(this.minPoolSize.raw); 31 | 32 | if (!inRange) { 33 | return { ok: false, message: `${poolKeys.baseMint} - PoolSize -> Pool size ${poolSize.toFixed()} < ${this.minPoolSize.toFixed()}` }; 34 | } 35 | } 36 | 37 | return { ok: inRange }; 38 | } catch (error) { 39 | logger.error(`${poolKeys.baseMint} - Failed to check pool size`); 40 | } 41 | 42 | return { ok: false, message: `${poolKeys.baseMint} - PoolSize -> Failed to check pool size` }; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /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 RenouncedFreezeFilter implements Filter { 8 | constructor(private readonly connection: Connection, private readonly checkRenounced: boolean, private readonly checkFreezable: boolean) {} 9 | 10 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 11 | const errorMessage = [ this.checkRenounced ? 'mint' : undefined, this.checkFreezable ? 'freeze' : undefined ].filter((e) => e !== undefined); 12 | try { 13 | const accountInfo = await this.connection.getAccountInfo(poolKeys.baseMint, this.connection.commitment); 14 | if (!accountInfo?.data) { 15 | return { ok: false, message: `${poolKeys.baseMint.toString()} - RenouncedFreeze -> Failed to fetch account data` }; 16 | } 17 | 18 | const deserialize = MintLayout.decode(accountInfo.data); 19 | const renounced = !this.checkRenounced || deserialize.mintAuthorityOption === 0; 20 | const freezable = !this.checkFreezable || deserialize.freezeAuthorityOption !== 0; 21 | 22 | const message = [ renounced ? undefined : 'mint', !freezable ? undefined : 'freeze' ].filter((e) => e !== undefined); 23 | const ok = renounced && !freezable; 24 | 25 | return { ok: ok, message: ok ? undefined : `${poolKeys.baseMint.toString()} - RenouncedFreeze -> Creator can ${message.join(' and ')} tokens` }; 26 | } catch (e) { 27 | logger.error({ mint: poolKeys.baseMint }, `${poolKeys.baseMint.toString()} - RenouncedFreeze -> Failed to check if creator can ${errorMessage.join(' and ')} tokens`); 28 | } 29 | 30 | return { ok: false, message: `${poolKeys.baseMint.toString()} - RenouncedFreeze -> Failed to check if creator can ${errorMessage.join(' and ')} tokens` }; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /filters/pool-filters.ts: -------------------------------------------------------------------------------- 1 | import { Connection } from '@solana/web3.js'; 2 | import { LiquidityPoolKeysV4, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 3 | import { getMetadataAccountDataSerializer } from '@metaplex-foundation/mpl-token-metadata'; 4 | import { BurnFilter } from './burn.filter'; 5 | import { MutableFilter } from './mutable.filter'; 6 | import { RenouncedFreezeFilter } from './renounced.filter'; 7 | import { PoolSizeFilter } from './pool-size.filter'; 8 | import { CHECK_IF_BURNED, CHECK_IF_FREEZABLE, CHECK_IF_MINT_IS_RENOUNCED, CHECK_IF_MUTABLE, logger } from '../helpers'; 9 | 10 | export interface Filter { 11 | execute(poolKeysV4: LiquidityPoolKeysV4): Promise; 12 | } 13 | 14 | export interface FilterResult { 15 | ok: boolean; 16 | message?: string; 17 | } 18 | 19 | export interface PoolFilterArgs { 20 | minPoolSize: TokenAmount; 21 | maxPoolSize: TokenAmount; 22 | quoteToken: Token; 23 | } 24 | 25 | export class PoolFilters { 26 | private readonly filters: Filter[] = []; 27 | 28 | constructor( 29 | readonly connection: Connection, 30 | readonly args: PoolFilterArgs, 31 | ) { 32 | if (CHECK_IF_BURNED) { 33 | this.filters.push(new BurnFilter(connection)); 34 | } 35 | 36 | if (CHECK_IF_MINT_IS_RENOUNCED || CHECK_IF_FREEZABLE) { 37 | this.filters.push(new RenouncedFreezeFilter(connection, CHECK_IF_MINT_IS_RENOUNCED, CHECK_IF_FREEZABLE)); 38 | } 39 | 40 | if (CHECK_IF_MUTABLE) { 41 | this.filters.push(new MutableFilter(connection, getMetadataAccountDataSerializer())); 42 | } 43 | 44 | if (!args.minPoolSize.isZero() || !args.maxPoolSize.isZero()) { 45 | this.filters.push(new PoolSizeFilter(connection, args.quoteToken, args.minPoolSize, args.maxPoolSize)); 46 | } 47 | } 48 | 49 | public async execute(poolKeys: LiquidityPoolKeysV4): Promise { 50 | if (this.filters.length === 0) { 51 | return true; 52 | } 53 | 54 | const result = await Promise.all(this.filters.map((f) => f.execute(poolKeys))); 55 | const pass = result.every((r) => r.ok); 56 | 57 | if (pass) { 58 | return true; 59 | } 60 | 61 | for (const filterResult of result.filter((r) => !r.ok)) { 62 | logger.trace(filterResult.message); 63 | } 64 | 65 | return false; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /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, error?: 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 CUSTOM_FEE = retrieveEnvVariable('CUSTOM_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 SCALE_OUT = retrieveEnvVariable('SCALE_OUT', logger) === 'true'; 50 | export const TRAILING_STOP = retrieveEnvVariable('TRAILING_STOP', logger) === 'true'; 51 | export const PRICE_CHECK_INTERVAL = Number(retrieveEnvVariable('PRICE_CHECK_INTERVAL', logger)); 52 | export const PRICE_CHECK_DURATION = Number(retrieveEnvVariable('PRICE_CHECK_DURATION', logger)); 53 | export const SELL_SLIPPAGE = Number(retrieveEnvVariable('SELL_SLIPPAGE', logger)); 54 | export const SKIP_SELLING_IF_LOST_90PERCENT = retrieveEnvVariable('SKIP_SELLING_IF_LOST_90PERCENT', logger) === 'true'; 55 | 56 | // Filters 57 | export const FILTER_CHECK_INTERVAL = Number(retrieveEnvVariable('FILTER_CHECK_INTERVAL', logger)); 58 | export const FILTER_CHECK_DURATION = Number(retrieveEnvVariable('FILTER_CHECK_DURATION', logger)); 59 | export const CONSECUTIVE_FILTER_MATCHES = Number(retrieveEnvVariable('CONSECUTIVE_FILTER_MATCHES', logger)); 60 | export const CHECK_IF_MUTABLE = retrieveEnvVariable('CHECK_IF_MUTABLE', logger) === 'true'; 61 | export const CHECK_IF_MINT_IS_RENOUNCED = retrieveEnvVariable('CHECK_IF_MINT_IS_RENOUNCED', logger) === 'true'; 62 | export const CHECK_IF_FREEZABLE = retrieveEnvVariable('CHECK_IF_FREEZABLE', logger) === 'true'; 63 | export const CHECK_IF_BURNED = retrieveEnvVariable('CHECK_IF_BURNED', logger) === 'true'; 64 | export const MIN_POOL_SIZE = retrieveEnvVariable('MIN_POOL_SIZE', logger); 65 | export const MAX_POOL_SIZE = retrieveEnvVariable('MAX_POOL_SIZE', logger); 66 | export const USE_SNIPE_LIST = retrieveEnvVariable('USE_SNIPE_LIST', logger) === 'true'; 67 | export const SNIPE_LIST_REFRESH_INTERVAL = Number(retrieveEnvVariable('SNIPE_LIST_REFRESH_INTERVAL', logger)); 68 | -------------------------------------------------------------------------------- /transactions/jito-rpc-transaction-executor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BlockhashWithExpiryBlockHeight, 3 | Keypair, 4 | PublicKey, 5 | SystemProgram, 6 | Connection, 7 | TransactionMessage, 8 | VersionedTransaction, 9 | } from '@solana/web3.js'; 10 | import { TransactionExecutor } from './transaction-executor.interface'; 11 | import { logger } from '../helpers'; 12 | import axios, { AxiosError } from 'axios'; 13 | import bs58 from 'bs58'; 14 | import { Currency, CurrencyAmount } from '@raydium-io/raydium-sdk'; 15 | 16 | export class JitoTransactionExecutor implements TransactionExecutor { 17 | // https://jito-labs.gitbook.io/mev/searcher-resources/json-rpc-api-reference/bundles/gettipaccounts 18 | private jitpTipAccounts = [ 19 | 'Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghXLvLkY', 20 | 'DttWaMuVvTiduZRnguLF7jNxTgiMBZ1hyAumKUiL2KRL', 21 | '96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5', 22 | '3AVi9Tg9Uo68tJfuvoKvqKNWKkC5wPdSSdeBnizKZ6jT', 23 | 'HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe', 24 | 'ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt6iGPaS49', 25 | 'ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt', 26 | 'DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh', 27 | ]; 28 | 29 | private JitoFeeWallet: PublicKey; 30 | 31 | constructor( 32 | private readonly jitoFee: string, 33 | private readonly connection: Connection, 34 | ) { 35 | this.JitoFeeWallet = this.getRandomValidatorKey(); 36 | } 37 | 38 | private getRandomValidatorKey(): PublicKey { 39 | const randomValidator = this.jitpTipAccounts[Math.floor(Math.random() * this.jitpTipAccounts.length)]; 40 | return new PublicKey(randomValidator); 41 | } 42 | 43 | public async executeAndConfirm( 44 | transaction: VersionedTransaction, 45 | payer: Keypair, 46 | latestBlockhash: BlockhashWithExpiryBlockHeight, 47 | ): Promise<{ confirmed: boolean; signature?: string }> { 48 | logger.debug('Starting Jito transaction execution...'); 49 | this.JitoFeeWallet = this.getRandomValidatorKey(); // Update wallet key each execution 50 | logger.trace(`Selected Jito fee wallet: ${this.JitoFeeWallet.toBase58()}`); 51 | 52 | try { 53 | const fee = new CurrencyAmount(Currency.SOL, this.jitoFee, false).raw.toNumber(); 54 | logger.trace(`Calculated fee: ${fee} lamports`); 55 | 56 | const jitTipTxFeeMessage = new TransactionMessage({ 57 | payerKey: payer.publicKey, 58 | recentBlockhash: latestBlockhash.blockhash, 59 | instructions: [ 60 | SystemProgram.transfer({ 61 | fromPubkey: payer.publicKey, 62 | toPubkey: this.JitoFeeWallet, 63 | lamports: fee, 64 | }), 65 | ], 66 | }).compileToV0Message(); 67 | 68 | const jitoFeeTx = new VersionedTransaction(jitTipTxFeeMessage); 69 | jitoFeeTx.sign([payer]); 70 | 71 | const jitoTxsignature = bs58.encode(jitoFeeTx.signatures[0]); 72 | 73 | // Serialize the transactions once here 74 | const serializedjitoFeeTx = bs58.encode(jitoFeeTx.serialize()); 75 | const serializedTransaction = bs58.encode(transaction.serialize()); 76 | const serializedTransactions = [serializedjitoFeeTx, serializedTransaction]; 77 | 78 | // https://jito-labs.gitbook.io/mev/searcher-resources/json-rpc-api-reference/url 79 | const endpoints = [ 80 | 'https://mainnet.block-engine.jito.wtf/api/v1/bundles', 81 | 'https://amsterdam.mainnet.block-engine.jito.wtf/api/v1/bundles', 82 | 'https://frankfurt.mainnet.block-engine.jito.wtf/api/v1/bundles', 83 | 'https://ny.mainnet.block-engine.jito.wtf/api/v1/bundles', 84 | 'https://tokyo.mainnet.block-engine.jito.wtf/api/v1/bundles', 85 | ]; 86 | 87 | const requests = endpoints.map((url) => 88 | axios.post(url, { 89 | jsonrpc: '2.0', 90 | id: 1, 91 | method: 'sendBundle', 92 | params: [serializedTransactions], 93 | }), 94 | ); 95 | 96 | logger.trace('Sending transactions to endpoints...'); 97 | const results = await Promise.all(requests.map((p) => p.catch((e) => e))); 98 | 99 | const successfulResults = results.filter((result) => !(result instanceof Error)); 100 | 101 | if (successfulResults.length > 0) { 102 | logger.trace(`At least one successful response`); 103 | logger.debug(`Confirming jito transaction...`); 104 | return await this.confirm(jitoTxsignature, latestBlockhash); 105 | } else { 106 | logger.debug(`No successful responses received for jito`); 107 | } 108 | 109 | return { confirmed: false }; 110 | } catch (error) { 111 | if (error instanceof AxiosError) { 112 | logger.trace({ error: error.response?.data }, 'Failed to execute jito transaction'); 113 | } 114 | logger.error('Error during transaction execution', error); 115 | return { confirmed: false }; 116 | } 117 | } 118 | 119 | private async confirm(signature: string, latestBlockhash: BlockhashWithExpiryBlockHeight) { 120 | const confirmation = await this.connection.confirmTransaction( 121 | { 122 | signature, 123 | lastValidBlockHeight: latestBlockhash.lastValidBlockHeight, 124 | blockhash: latestBlockhash.blockhash, 125 | }, 126 | this.connection.commitment, 127 | ); 128 | 129 | return { confirmed: !confirmation.value.err, signature }; 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Solana Trading Bot (Beta) 2 | 3 | ## Private Sniper Solution Available! 4 | 5 | If you are looking for a robust and private solution for sniping tokens on the Solana blockchain, I offer specialized services tailored to meet your needs. Please contact me directly to discuss: 6 | 7 | - [Discord](https://discordapp.com/users/600250420480442390) 8 | - [Telegram](https://t.me/yobebka) 9 | - [Jop Ultimate Bots channel](https://discord.gg/hmqBbT4ASW) 10 | 11 | The Solana Trading Bot is a software tool designed to automate the buying and selling of tokens on the Solana blockchain. 12 | It is configured to execute trades based on predefined parameters and strategies set by the user. 13 | 14 | The bot can monitor market conditions in real-time, such as pool burn, mint renounced and other factors, and it will execute trades when these conditions are fulfilled. 15 | 16 | ## Setup 17 | 18 | To run the script you need to: 19 | 20 | - Create a new empty Solana wallet 21 | - Transfer some SOL to it. 22 | - Convert some SOL to USDC or WSOL. 23 | - You need USDC or WSOL depending on the configuration set below. 24 | - Configure the script by updating `.env.copy` file (remove the .copy from the file name when done). 25 | - Check [Configuration](#configuration) section bellow 26 | - Install dependencies by typing: `npm install` 27 | - Run the script by typing: `npm run start` in terminal 28 | 29 | You should see the following output: 30 | ![output](readme/output.png) 31 | 32 | ### Configuration 33 | 34 | #### Wallet 35 | 36 | - `PRIVATE_KEY` - Your wallet's private key. 37 | 38 | #### Connection 39 | 40 | - `RPC_ENDPOINT` - HTTPS RPC endpoint for interacting with the Solana network. 41 | - `RPC_WEBSOCKET_ENDPOINT` - WebSocket RPC endpoint for real-time updates from the Solana network. 42 | - `COMMITMENT_LEVEL`- The commitment level of transactions (e.g., "finalized" for the highest level of security). 43 | 44 | #### Bot 45 | 46 | - `LOG_LEVEL` - Set logging level, e.g., `info`, `debug`, `trace`, etc. 47 | - `ONE_TOKEN_AT_A_TIME` - Set to `true` to process buying one token at a time. 48 | - `COMPUTE_UNIT_LIMIT` - Compute limit used to calculate fees. 49 | - `COMPUTE_UNIT_PRICE` - Compute price used to calculate fees. 50 | - `PRE_LOAD_EXISTING_MARKETS` - Bot will load all existing markets in memory on start. 51 | - This option should not be used with public RPC. 52 | - `CACHE_NEW_MARKETS` - Set to `true` to cache new markets. 53 | - This option should not be used with public RPC. 54 | - `TRANSACTION_EXECUTOR` - Set to `warp` to use warp infrastructure for executing transactions, or set it to jito to use JSON-RPC jito executer 55 | - For more details checkout [warp](#warp-transactions-beta) section 56 | - `CUSTOM_FEE` - If using warp or jito executors this value will be used for transaction fees instead of `COMPUTE_UNIT_LIMIT` and `COMPUTE_UNIT_LIMIT` 57 | - Minimum value is 0.0001 SOL, but we recommend using 0.006 SOL or above 58 | - On top of this fee, minimal solana network fee will be applied 59 | 60 | #### Buy 61 | 62 | - `QUOTE_MINT` - Which pools to snipe, USDC or WSOL. 63 | - `QUOTE_AMOUNT` - Amount used to buy each new token. 64 | - `AUTO_BUY_DELAY` - Delay in milliseconds before buying a token. 65 | - `MAX_BUY_RETRIES` - Maximum number of retries for buying a token. 66 | - `BUY_SLIPPAGE` - Slippage % 67 | 68 | #### Sell 69 | 70 | - `AUTO_SELL` - Set to `true` to enable automatic selling of tokens. 71 | - If you want to manually sell bought tokens, disable this option. 72 | - `MAX_SELL_RETRIES` - Maximum number of retries for selling a token. 73 | - `AUTO_SELL_DELAY` - Delay in milliseconds before auto-selling a token. 74 | - `PRICE_CHECK_INTERVAL` - Interval in milliseconds for checking the take profit and stop loss conditions. 75 | - Set to zero to disable take profit and stop loss. 76 | - `PRICE_CHECK_DURATION` - Time in milliseconds to wait for stop loss/take profit conditions. 77 | - If you don't reach profit or loss bot will auto sell after this time. 78 | - Set to zero to disable take profit and stop loss. 79 | - `TAKE_PROFIT` - Percentage profit at which to take profit. 80 | - Take profit is calculated based on quote mint. 81 | - `STOP_LOSS` - Percentage loss at which to stop the loss. 82 | - Stop loss is calculated based on quote mint. 83 | - `SELL_SLIPPAGE` - Slippage %. 84 | 85 | #### Snipe list 86 | 87 | - `USE_SNIPE_LIST` - Set to `true` to enable buying only tokens listed in `snipe-list.txt`. 88 | - Pool must not exist before the bot starts. 89 | - If token can be traded before bot starts nothing will happen. Bot will not buy the token. 90 | - `SNIPE_LIST_REFRESH_INTERVAL` - Interval in milliseconds to refresh the snipe list. 91 | - You can update snipe list while bot is running. It will pickup the new changes each time it does refresh. 92 | 93 | Note: When using snipe list filters below will be disabled. 94 | 95 | #### Filters 96 | 97 | - `FILTER_CHECK_INTERVAL` - Interval in milliseconds for checking if pool match the filters. 98 | - Set to zero to disable filters. 99 | - `FILTER_CHECK_DURATION` - Time in milliseconds to wait for pool to match the filters. 100 | - If pool doesn't match the filter buy will not happen. 101 | - Set to zero to disable filters. 102 | - `CONSECUTIVE_FILTER_MATCHES` - How many times in a row pool needs to match the filters. 103 | - 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 104 | - `CHECK_IF_MUTABLE` - Set to `true` to buy tokens only if their metadata are not mutable. 105 | - `CHECK_IF_MINT_IS_RENOUNCED` - Set to `true` to buy tokens only if their mint is renounced. 106 | - `CHECK_IF_FREEZABLE` - Set to `true` to buy tokens only if they are not freezable. 107 | - `CHECK_IF_BURNED` - Set to `true` to buy tokens only if their liquidity pool is burned. 108 | - `MIN_POOL_SIZE` - Bot will buy only if the pool size is greater than or equal the specified amount. 109 | - Set `0` to disable. 110 | - `MAX_POOL_SIZE` - Bot will buy only if the pool size is less than or equal the specified amount. 111 | - Set `0` to disable. 112 | 113 | ## Warp transactions (beta) 114 | 115 | In case you experience a lot of failed transactions or transaction performance is too slow, you can try using `warp` for executing transactions. 116 | Warp is hosted service that executes transactions using integrations with third party providers. 117 | 118 | Using warp for transactions supports the team behind this project. 119 | 120 | ### Security 121 | 122 | When using warp, transaction is sent to the hosted service. 123 | **Payload that is being sent will NOT contain your wallet private key**. Fee transaction is signed on your machine. 124 | Each request is processed by hosted service and sent to third party provider. 125 | **We don't store your transactions, nor we store your private key.** 126 | 127 | Note: Warp transactions are disabled by default. 128 | 129 | ### Fees 130 | 131 | When using warp for transactions, fee is distributed between developers of warp and third party providers. 132 | In case TX fails, no fee will be taken from your account. 133 | 134 | ## Common issues 135 | 136 | If you have an error which is not listed here, please create a new issue in this repository. 137 | To collect more information on an issue, please change `LOG_LEVEL` to `debug`. 138 | 139 | ### Unsupported RPC node 140 | 141 | - If you see following error in your log file: 142 | `Error: 410 Gone: {"jsonrpc":"2.0","error":{"code": 410, "message":"The RPC call or parameters have been disabled."}, "id": "986f3599-b2b7-47c4-b951-074c19842bad" }` 143 | it means your RPC node doesn't support methods needed to execute script. 144 | - FIX: Change your RPC node. You can use Helius or Quicknode. 145 | 146 | ### No token account 147 | 148 | - If you see following error in your log file: 149 | `Error: No SOL token account found in wallet: ` 150 | it means that wallet you provided doesn't have USDC/WSOL token account. 151 | - 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: 152 | 153 | ![wsol](readme/wsol.png) 154 | 155 | ## Contact 156 | 157 | [![](https://img.shields.io/discord/1201826085655023616?color=5865F2&logo=Discord&style=flat-square)](https://discord.gg/xYUETCA2aP) 158 | 159 | - If you want to leave a tip, you can send it to the following address: 160 | `D4zcora6XSv57nFNXBfkA5CMhu2GWrAXGQQ1CpAYG4FA` 161 | 162 | - If you need custom features or assistance, feel free to contact the admin team on discord for dedicated support. 163 | 164 | ## Disclaimer 165 | 166 | The Solana Trading Bot is provided as is, for learning purposes. 167 | Trading cryptocurrencies and tokens involves risk, and past performance is not indicative of future results. 168 | The use of this bot is at your own risk, and we are not responsible for any losses incurred while using the bot. 169 | -------------------------------------------------------------------------------- /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, RawAccount } 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_MUTABLE, 18 | CHECK_IF_MINT_IS_RENOUNCED, 19 | CHECK_IF_FREEZABLE, 20 | CHECK_IF_BURNED, 21 | QUOTE_MINT, 22 | MAX_POOL_SIZE, 23 | MIN_POOL_SIZE, 24 | QUOTE_AMOUNT, 25 | PRIVATE_KEY, 26 | USE_SNIPE_LIST, 27 | ONE_TOKEN_AT_A_TIME, 28 | AUTO_SELL_DELAY, 29 | MAX_SELL_RETRIES, 30 | AUTO_SELL, 31 | MAX_BUY_RETRIES, 32 | AUTO_BUY_DELAY, 33 | COMPUTE_UNIT_LIMIT, 34 | COMPUTE_UNIT_PRICE, 35 | CACHE_NEW_MARKETS, 36 | TAKE_PROFIT, 37 | STOP_LOSS, 38 | BUY_SLIPPAGE, 39 | SELL_SLIPPAGE, 40 | PRICE_CHECK_DURATION, 41 | PRICE_CHECK_INTERVAL, 42 | SNIPE_LIST_REFRESH_INTERVAL, 43 | TRANSACTION_EXECUTOR, 44 | CUSTOM_FEE, 45 | FILTER_CHECK_INTERVAL, 46 | FILTER_CHECK_DURATION, 47 | CONSECUTIVE_FILTER_MATCHES, SKIP_SELLING_IF_LOST_90PERCENT, TRAILING_STOP, 48 | } from './helpers'; 49 | import { version } from './package.json'; 50 | import { WarpTransactionExecutor } from './transactions/warp-transaction-executor'; 51 | import { JitoTransactionExecutor } from './transactions/jito-rpc-transaction-executor'; 52 | 53 | const connection = new Connection(RPC_ENDPOINT, { 54 | wsEndpoint: RPC_WEBSOCKET_ENDPOINT, 55 | commitment: COMMITMENT_LEVEL, 56 | }); 57 | 58 | function printDetails(wallet: Keypair, quoteToken: Token, bot: Bot) { 59 | logger.info(` 60 | .. :-===++++- 61 | .-==+++++++- =+++++++++- 62 | ..:::--===+=.=: .+++++++++++:=+++++++++: 63 | .==+++++++++++++++=:+++: .+++++++++++.=++++++++-. 64 | .-+++++++++++++++=:=++++- .+++++++++=:.=+++++-::-. 65 | -:+++++++++++++=:+++++++- .++++++++-:- =+++++=-: 66 | -:++++++=++++=:++++=++++= .++++++++++- =+++++: 67 | -:++++-:=++=:++++=:-+++++:+++++====--:::::::. 68 | ::=+-:::==:=+++=::-:--::::::::::---------::. 69 | ::-: .::::::::. --------:::.. 70 | :- .:.-:::. 71 | 72 | WARP DRIVE ACTIVATED 🚀🐟 73 | Made with ❤️ by humans. 74 | Version: ${version} 75 | `); 76 | 77 | const botConfig = bot.config; 78 | 79 | logger.info('------- CONFIGURATION START -------'); 80 | logger.info(`Wallet: ${wallet.publicKey.toString()}`); 81 | 82 | logger.info('- Bot -'); 83 | 84 | logger.info( 85 | `Using ${TRANSACTION_EXECUTOR} executer: ${bot.isWarp || bot.isJito || (TRANSACTION_EXECUTOR === 'default' ? true : false)}`, 86 | ); 87 | if (bot.isWarp || bot.isJito) { 88 | logger.info(`${TRANSACTION_EXECUTOR} fee: ${CUSTOM_FEE}`); 89 | } else { 90 | logger.info(`Compute Unit limit: ${botConfig.unitLimit}`); 91 | logger.info(`Compute Unit price (micro lamports): ${botConfig.unitPrice}`); 92 | } 93 | 94 | logger.info(`Single token at the time: ${botConfig.oneTokenAtATime}`); 95 | logger.info(`Pre load existing markets: ${PRE_LOAD_EXISTING_MARKETS}`); 96 | logger.info(`Cache new markets: ${CACHE_NEW_MARKETS}`); 97 | logger.info(`Log level: ${LOG_LEVEL}`); 98 | 99 | logger.info('- Buy -'); 100 | logger.info(`Buy amount: ${botConfig.quoteAmount.toFixed()} ${botConfig.quoteToken.name}`); 101 | logger.info(`Auto buy delay: ${botConfig.autoBuyDelay} ms`); 102 | logger.info(`Max buy retries: ${botConfig.maxBuyRetries}`); 103 | logger.info(`Buy amount (${quoteToken.symbol}): ${botConfig.quoteAmount.toFixed()}`); 104 | logger.info(`Buy slippage: ${botConfig.buySlippage}%`); 105 | 106 | logger.info('- Sell -'); 107 | logger.info(`Auto sell: ${AUTO_SELL}`); 108 | logger.info(`Auto sell delay: ${botConfig.autoSellDelay} ms`); 109 | logger.info(`Max sell retries: ${botConfig.maxSellRetries}`); 110 | logger.info(`Sell slippage: ${botConfig.sellSlippage}%`); 111 | logger.info(`Price check interval: ${botConfig.priceCheckInterval} ms`); 112 | logger.info(`Price check duration: ${botConfig.priceCheckDuration} ms`); 113 | logger.info(`Take profit: ${botConfig.takeProfit}%`); 114 | logger.info(`Stop loss: ${botConfig.stopLoss}%`); 115 | logger.info(`Skip selling on 90% lost: ${SKIP_SELLING_IF_LOST_90PERCENT}`); 116 | logger.info(`Trailing stop: ${TRAILING_STOP} (trailing ${STOP_LOSS}%)`); 117 | 118 | logger.info('- Snipe list -'); 119 | logger.info(`Snipe list: ${botConfig.useSnipeList}`); 120 | logger.info(`Snipe list refresh interval: ${SNIPE_LIST_REFRESH_INTERVAL} ms`); 121 | 122 | if (botConfig.useSnipeList) { 123 | logger.info('- Filters -'); 124 | logger.info(`Filters are disabled when snipe list is on`); 125 | } else { 126 | logger.info('- Filters -'); 127 | logger.info(`Filter check interval: ${botConfig.filterCheckInterval} ms`); 128 | logger.info(`Filter check duration: ${botConfig.filterCheckDuration} ms`); 129 | logger.info(`Consecutive filter matches: ${botConfig.consecutiveMatchCount}`); 130 | logger.info(`Check renounced: ${botConfig.checkRenounced}`); 131 | logger.info(`Check freezable: ${botConfig.checkFreezable}`); 132 | logger.info(`Check burned: ${botConfig.checkBurned}`); 133 | logger.info(`Min pool size: ${botConfig.minPoolSize.toFixed()}`); 134 | logger.info(`Max pool size: ${botConfig.maxPoolSize.toFixed()}`); 135 | } 136 | 137 | logger.info('------- CONFIGURATION END -------'); 138 | 139 | logger.info('Bot is running! Press CTRL + C to stop it.'); 140 | } 141 | 142 | const runListener = async () => { 143 | logger.level = LOG_LEVEL; 144 | logger.info('Bot is starting...'); 145 | 146 | const marketCache = new MarketCache(connection); 147 | const poolCache = new PoolCache(); 148 | let txExecutor: TransactionExecutor; 149 | 150 | switch (TRANSACTION_EXECUTOR) { 151 | case 'warp': { 152 | txExecutor = new WarpTransactionExecutor(CUSTOM_FEE); 153 | break; 154 | } 155 | case 'jito': { 156 | txExecutor = new JitoTransactionExecutor(CUSTOM_FEE, connection); 157 | break; 158 | } 159 | default: { 160 | txExecutor = new DefaultTransactionExecutor(connection); 161 | break; 162 | } 163 | } 164 | 165 | const wallet = getWallet(PRIVATE_KEY.trim()); 166 | const quoteToken = getToken(QUOTE_MINT); 167 | const botConfig = { 168 | wallet, 169 | quoteAta: getAssociatedTokenAddressSync(quoteToken.mint, wallet.publicKey), 170 | checkRenounced: CHECK_IF_MINT_IS_RENOUNCED, 171 | checkFreezable: CHECK_IF_FREEZABLE, 172 | checkBurned: CHECK_IF_BURNED, 173 | minPoolSize: new TokenAmount(quoteToken, MIN_POOL_SIZE, false), 174 | maxPoolSize: new TokenAmount(quoteToken, MAX_POOL_SIZE, false), 175 | quoteToken, 176 | quoteAmount: new TokenAmount(quoteToken, QUOTE_AMOUNT, false), 177 | oneTokenAtATime: ONE_TOKEN_AT_A_TIME, 178 | useSnipeList: USE_SNIPE_LIST, 179 | autoSell: AUTO_SELL, 180 | autoSellDelay: AUTO_SELL_DELAY, 181 | maxSellRetries: MAX_SELL_RETRIES, 182 | autoBuyDelay: AUTO_BUY_DELAY, 183 | maxBuyRetries: MAX_BUY_RETRIES, 184 | unitLimit: COMPUTE_UNIT_LIMIT, 185 | unitPrice: COMPUTE_UNIT_PRICE, 186 | takeProfit: TAKE_PROFIT, 187 | stopLoss: STOP_LOSS, 188 | buySlippage: BUY_SLIPPAGE, 189 | sellSlippage: SELL_SLIPPAGE, 190 | priceCheckInterval: PRICE_CHECK_INTERVAL, 191 | priceCheckDuration: PRICE_CHECK_DURATION, 192 | filterCheckInterval: FILTER_CHECK_INTERVAL, 193 | filterCheckDuration: FILTER_CHECK_DURATION, 194 | consecutiveMatchCount: CONSECUTIVE_FILTER_MATCHES, 195 | }; 196 | 197 | const bot = await new Bot(connection, marketCache, poolCache, txExecutor, botConfig); 198 | const valid = await bot.validate(); 199 | 200 | if (!valid) { 201 | logger.info('Bot is exiting...'); 202 | process.exit(1); 203 | } 204 | 205 | if (PRE_LOAD_EXISTING_MARKETS) { 206 | await marketCache.init({ quoteToken }); 207 | } 208 | 209 | const runTimestamp = Math.floor(new Date().getTime() / 1000); 210 | const listeners = new Listeners(connection); 211 | await listeners.start({ 212 | walletPublicKey: wallet.publicKey, 213 | quoteToken, 214 | autoSell: AUTO_SELL, 215 | cacheNewMarkets: CACHE_NEW_MARKETS, 216 | }); 217 | 218 | listeners.on('market', (updatedAccountInfo: KeyedAccountInfo) => { 219 | const marketState = MARKET_STATE_LAYOUT_V3.decode(updatedAccountInfo.accountInfo.data); 220 | marketCache.save(updatedAccountInfo.accountId.toString(), marketState); 221 | }); 222 | 223 | listeners.on('pool', async (updatedAccountInfo: KeyedAccountInfo) => { 224 | const poolState = LIQUIDITY_STATE_LAYOUT_V4.decode(updatedAccountInfo.accountInfo.data); 225 | const poolOpenTime = parseInt(poolState.poolOpenTime.toString()); 226 | const exists = await poolCache.get(poolState.baseMint.toString()); 227 | 228 | if (!exists && poolOpenTime > runTimestamp) { 229 | poolCache.save(updatedAccountInfo.accountId.toString(), poolState); 230 | await bot.buy(updatedAccountInfo.accountId, poolState); 231 | } 232 | }); 233 | 234 | listeners.on('wallet', async (updatedAccountInfo: KeyedAccountInfo) => { 235 | const accountData = AccountLayout.decode(updatedAccountInfo.accountInfo.data); 236 | 237 | if (accountData.mint.equals(quoteToken.mint)) { 238 | return; 239 | } 240 | 241 | await bot.sell(updatedAccountInfo.accountId, accountData as RawAccount); 242 | }); 243 | 244 | printDetails(wallet, quoteToken, bot); 245 | }; 246 | 247 | runListener(); 248 | -------------------------------------------------------------------------------- /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 { 18 | AmountSide, 19 | Liquidity, 20 | LiquidityPoolKeysV4, 21 | LiquidityStateV4, 22 | Percent, 23 | Price, 24 | Token, 25 | TokenAmount, 26 | } from '@raydium-io/raydium-sdk'; 27 | import { MarketCache, PoolCache, SnipeListCache } from './cache'; 28 | import { PoolFilters } from './filters'; 29 | import { TransactionExecutor } from './transactions'; 30 | import { 31 | createPoolKeys, 32 | logger, 33 | NETWORK, 34 | SKIP_SELLING_IF_LOST_90PERCENT, 35 | sleep, 36 | TRAILING_STOP, 37 | } from './helpers'; 38 | import { Mutex } from 'async-mutex'; 39 | import BN from 'bn.js'; 40 | import { WarpTransactionExecutor } from './transactions/warp-transaction-executor'; 41 | import { JitoTransactionExecutor } from './transactions/jito-rpc-transaction-executor'; 42 | 43 | interface TrailingStops { 44 | // mint address : highest token price (amount) 45 | [key: string]: TokenAmount; 46 | } 47 | 48 | interface ScaleOutTargets { 49 | [key: string]: { price: BN, amountToSell: TokenAmount, processing: boolean, sold: boolean }[]; 50 | } 51 | 52 | export interface BotConfig { 53 | wallet: Keypair; 54 | checkRenounced: boolean; 55 | checkFreezable: boolean; 56 | checkBurned: boolean; 57 | minPoolSize: TokenAmount; 58 | maxPoolSize: TokenAmount; 59 | quoteToken: Token; 60 | quoteAmount: TokenAmount; 61 | quoteAta: PublicKey; 62 | oneTokenAtATime: boolean; 63 | useSnipeList: boolean; 64 | autoSell: boolean; 65 | autoBuyDelay: number; 66 | autoSellDelay: number; 67 | maxBuyRetries: number; 68 | maxSellRetries: number; 69 | unitLimit: number; 70 | unitPrice: number; 71 | takeProfit: number; 72 | stopLoss: number; 73 | buySlippage: number; 74 | sellSlippage: number; 75 | priceCheckInterval: number; 76 | priceCheckDuration: number; 77 | filterCheckInterval: number; 78 | filterCheckDuration: number; 79 | consecutiveMatchCount: number; 80 | } 81 | 82 | export class Bot { 83 | private readonly poolFilters: PoolFilters; 84 | 85 | // snipe list 86 | private readonly snipeListCache?: SnipeListCache; 87 | 88 | // one token at the time 89 | private readonly mutex: Mutex; 90 | private sellExecutionCount = 0; 91 | public readonly isWarp: boolean = false; 92 | public readonly isJito: boolean = false; 93 | private readonly trailingStops: TrailingStops; 94 | // private readonly scaleOutTargets: ScaleOutTargets; 95 | 96 | constructor( 97 | private readonly connection: Connection, 98 | private readonly marketStorage: MarketCache, 99 | private readonly poolStorage: PoolCache, 100 | private readonly txExecutor: TransactionExecutor, 101 | readonly config: BotConfig, 102 | ) { 103 | this.isWarp = txExecutor instanceof WarpTransactionExecutor; 104 | this.isJito = txExecutor instanceof JitoTransactionExecutor; 105 | 106 | this.mutex = new Mutex(); 107 | this.poolFilters = new PoolFilters(connection, { 108 | quoteToken: this.config.quoteToken, 109 | minPoolSize: this.config.minPoolSize, 110 | maxPoolSize: this.config.maxPoolSize, 111 | }); 112 | 113 | if (this.config.useSnipeList) { 114 | this.snipeListCache = new SnipeListCache(); 115 | this.snipeListCache.init(); 116 | } 117 | 118 | this.trailingStops = {}; 119 | } 120 | 121 | async validate() { 122 | try { 123 | await getAccount(this.connection, this.config.quoteAta, this.connection.commitment); 124 | } catch (error) { 125 | logger.error( 126 | `${this.config.quoteToken.symbol} token account not found in wallet: ${this.config.wallet.publicKey.toString()}`, 127 | ); 128 | return false; 129 | } 130 | 131 | return true; 132 | } 133 | 134 | public async buy(accountId: PublicKey, poolState: LiquidityStateV4) { 135 | logger.trace({ mint: poolState.baseMint }, `Processing new pool...`); 136 | 137 | if (this.config.useSnipeList && !this.snipeListCache?.isInList(poolState.baseMint.toString())) { 138 | logger.debug({ mint: poolState.baseMint.toString() }, `Skipping buy because token is not in a snipe list`); 139 | return; 140 | } 141 | 142 | if (this.config.autoBuyDelay > 0) { 143 | logger.debug({ mint: poolState.baseMint }, `Waiting for ${this.config.autoBuyDelay} ms before buy`); 144 | await sleep(this.config.autoBuyDelay); 145 | } 146 | 147 | if (this.config.oneTokenAtATime) { 148 | if (this.mutex.isLocked() || this.sellExecutionCount > 0) { 149 | logger.debug( 150 | { mint: poolState.baseMint.toString() }, 151 | `Skipping buy because one token at a time is turned on and token is already being processed`, 152 | ); 153 | return; 154 | } 155 | 156 | await this.mutex.acquire(); 157 | } 158 | 159 | try { 160 | const [market, mintAta] = await Promise.all([ 161 | this.marketStorage.get(poolState.marketId.toString()), 162 | getAssociatedTokenAddress(poolState.baseMint, this.config.wallet.publicKey), 163 | ]); 164 | const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(accountId, poolState, market); 165 | 166 | if (!this.config.useSnipeList) { 167 | const match = await this.filterMatch(poolKeys); 168 | 169 | if (!match) { 170 | logger.trace({ mint: poolKeys.baseMint.toString() }, `Skipping buy because pool doesn't match filters`); 171 | return; 172 | } 173 | } 174 | 175 | for (let i = 0; i < this.config.maxBuyRetries; i++) { 176 | try { 177 | logger.info( 178 | { mint: poolState.baseMint.toString() }, 179 | `Send buy transaction attempt: ${i + 1}/${this.config.maxBuyRetries}`, 180 | ); 181 | const tokenOut = new Token(TOKEN_PROGRAM_ID, poolKeys.baseMint, poolKeys.baseDecimals); 182 | const result = await this.swap( 183 | poolKeys, 184 | this.config.quoteAta, 185 | mintAta, 186 | this.config.quoteToken, 187 | tokenOut, 188 | this.config.quoteAmount, 189 | this.config.buySlippage, 190 | this.config.wallet, 191 | 'buy', 192 | ); 193 | 194 | if (result.confirmed) { 195 | logger.info( 196 | { 197 | mint: poolState.baseMint.toString(), 198 | signature: result.signature, 199 | url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`, 200 | }, 201 | `Confirmed buy tx`, 202 | ); 203 | 204 | break; 205 | } 206 | 207 | logger.info( 208 | { 209 | mint: poolState.baseMint.toString(), 210 | signature: result.signature, 211 | error: result.error, 212 | }, 213 | `Error confirming buy tx`, 214 | ); 215 | } catch (error) { 216 | logger.debug({ mint: poolState.baseMint.toString(), error }, `Error confirming buy transaction`); 217 | } 218 | } 219 | } catch (error) { 220 | logger.error({ mint: poolState.baseMint.toString(), error }, `Failed to buy token`); 221 | } finally { 222 | if (this.config.oneTokenAtATime) { 223 | this.mutex.release(); 224 | } 225 | } 226 | } 227 | 228 | public async sell(accountId: PublicKey, rawAccount: RawAccount) { 229 | if (this.config.oneTokenAtATime) { 230 | this.sellExecutionCount++; 231 | } 232 | 233 | try { 234 | logger.trace({ mint: rawAccount.mint }, `Processing new token...`); 235 | 236 | const poolData = await this.poolStorage.get(rawAccount.mint.toString()); 237 | 238 | if (!poolData) { 239 | logger.trace({ mint: rawAccount.mint.toString() }, `Token pool data is not found, can't sell`); 240 | return; 241 | } 242 | 243 | const tokenIn = new Token(TOKEN_PROGRAM_ID, poolData.state.baseMint, poolData.state.baseDecimal.toNumber()); 244 | const tokenAmountIn = new TokenAmount(tokenIn, rawAccount.amount, true); 245 | 246 | logger.debug(`${rawAccount.mint.toString()} - top sell called. Amount: ${new TokenAmount(tokenIn, rawAccount.amount, true).toFixed()}`) 247 | 248 | if (tokenAmountIn.isZero()) { 249 | logger.info({ mint: rawAccount.mint.toString() }, `Empty balance, can't sell`); 250 | return; 251 | } 252 | 253 | if (this.config.autoSellDelay > 0) { 254 | logger.debug({ mint: rawAccount.mint }, `Waiting for ${this.config.autoSellDelay} ms before sell`); 255 | await sleep(this.config.autoSellDelay); 256 | } 257 | 258 | const market = await this.marketStorage.get(poolData.state.marketId.toString()); 259 | const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(new PublicKey(poolData.id), poolData.state, market); 260 | 261 | const price = new Price(tokenIn, tokenAmountIn.raw, this.config.quoteToken, this.config.quoteAmount.raw) 262 | logger.info(`${rawAccount.mint.toString()} - token price is ${price.toFixed()}`) 263 | logger.debug(`${rawAccount.mint.toString()} - set Scale Out values: +50% number price is: ${price.raw.mul(50).numerator.div(new BN(100)).toNumber()}`) 264 | logger.debug(`${rawAccount.mint.toString()} - set Scale Out values: +50% string price is: ${price.raw.mul(50).numerator.div(new BN(100)).toString(10)}`) 265 | 266 | 267 | if (TRAILING_STOP && !this.trailingStops[rawAccount.mint.toString()]) { 268 | this.trailingStops[rawAccount.mint.toString()] = this.config.quoteAmount 269 | } 270 | 271 | // if (SCALE_OUT && !this.scaleOutTargets[rawAccount.mint.toString()]) { 272 | // logger.debug(`${rawAccount.mint.toString()} - set Scale Out values: price is: ${price.toFixed()}`) 273 | // logger.debug(`${rawAccount.mint.toString()} - set Scale Out values: +30% number price is: ${price.raw.mul(30).numerator.div(new BN(100)).toNumber()}`) 274 | // logger.debug(`${rawAccount.mint.toString()} - set Scale Out values: +30% string price is: ${price.raw.mul(30).numerator.div(new BN(100)).toString(10)}`) 275 | // logger.debug(`${rawAccount.mint.toString()} - set Scale Out values: +50% number price is: ${price.raw.mul(50).numerator.div(new BN(100)).toNumber()}`) 276 | // logger.debug(`${rawAccount.mint.toString()} - set Scale Out values: +50% string price is: ${price.raw.mul(50).numerator.div(new BN(100)).toString(10)}`) 277 | // this.scaleOutTargets[rawAccount.mint.toString()] = [ 278 | // { 279 | // price: price.raw.mul(30).numerator.div(new BN(100)), 280 | // amountToSell: new TokenAmount(this.config.quoteToken, this.config.quoteAmount.mul(25).numerator.div(new BN(100)), true), 281 | // processing: false, 282 | // sold: false, 283 | // }, 284 | // ]; 285 | // } 286 | 287 | const shouldStopSelling = await this.priceMatch(tokenAmountIn, poolKeys); 288 | if (shouldStopSelling) { 289 | logger.info(`${rawAccount.mint} - received stop selling signal. Price dropped more than 90%`) 290 | this.sellExecutionCount--; 291 | return 292 | } 293 | 294 | for (let i = 0; i < this.config.maxSellRetries; i++) { 295 | try { 296 | logger.info( 297 | { mint: rawAccount.mint }, 298 | `Send sell transaction attempt: ${i + 1}/${this.config.maxSellRetries}`, 299 | ); 300 | 301 | // let scaleOutAmountIn = tokenAmountIn 302 | // if (SCALE_OUT) { 303 | // const activeScaleOutTarget = this.scaleOutTargets[rawAccount.mint.toString()].find(target => target.processing) 304 | // scaleOutAmountIn = activeScaleOutTarget.amountToSell 305 | // } 306 | 307 | const result = await this.swap( 308 | poolKeys, 309 | accountId, 310 | this.config.quoteAta, 311 | tokenIn, 312 | this.config.quoteToken, 313 | tokenAmountIn, // scaleOutAmountIn 314 | this.config.sellSlippage, 315 | this.config.wallet, 316 | 'sell', 317 | ); 318 | 319 | if (result.confirmed) { 320 | logger.info( 321 | { 322 | dex: `https://dexscreener.com/solana/${rawAccount.mint.toString()}?maker=${this.config.wallet.publicKey}`, 323 | mint: rawAccount.mint.toString(), 324 | signature: result.signature, 325 | url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`, 326 | }, 327 | `Confirmed sell tx`, 328 | ); 329 | 330 | // if (SCALE_OUT) { 331 | // const scaleOutTargets = this.scaleOutTargets[rawAccount.mint.toString()] 332 | // const activeScaleOutTarget = scaleOutTargets.find(target => target.processing) 333 | // activeScaleOutTarget.processing = false 334 | // activeScaleOutTarget.sold = true 335 | // 336 | // 337 | // if (scaleOutTargets.some(target => !target.sold)) { 338 | // logger.info(`${rawAccount.mint.toString()} - target of scale out is sold. Selling next target.`) 339 | // this.sell(accountId, rawAccount) 340 | // } 341 | // } 342 | break; 343 | } 344 | 345 | logger.info( 346 | { 347 | mint: rawAccount.mint.toString(), 348 | signature: result.signature, 349 | error: result.error, 350 | }, 351 | `Error confirming sell tx`, 352 | ); 353 | } catch (error) { 354 | logger.debug({ mint: rawAccount.mint.toString(), error }, `Error confirming sell transaction`); 355 | } 356 | } 357 | } catch (error) { 358 | logger.error({ mint: rawAccount.mint.toString(), error }, `Failed to sell token`); 359 | } finally { 360 | if (this.config.oneTokenAtATime) { 361 | this.sellExecutionCount--; 362 | } 363 | } 364 | } 365 | 366 | // noinspection JSUnusedLocalSymbols 367 | private async swap( 368 | poolKeys: LiquidityPoolKeysV4, 369 | ataIn: PublicKey, 370 | ataOut: PublicKey, 371 | tokenIn: Token, 372 | tokenOut: Token, 373 | amountIn: TokenAmount, 374 | slippage: number, 375 | wallet: Keypair, 376 | direction: 'buy' | 'sell', 377 | ) { 378 | const slippagePercent = new Percent(slippage, 100); 379 | const poolInfo = await Liquidity.fetchInfo({ 380 | connection: this.connection, 381 | poolKeys, 382 | }); 383 | 384 | const computedAmountOut = Liquidity.computeAmountOut({ 385 | poolKeys, 386 | poolInfo, 387 | amountIn, 388 | currencyOut: tokenOut, 389 | slippage: slippagePercent, 390 | }); 391 | 392 | const latestBlockhash = await this.connection.getLatestBlockhash(); 393 | const { innerTransaction } = Liquidity.makeSwapFixedInInstruction( 394 | { 395 | poolKeys: poolKeys, 396 | userKeys: { 397 | tokenAccountIn: ataIn, 398 | tokenAccountOut: ataOut, 399 | owner: wallet.publicKey, 400 | }, 401 | amountIn: amountIn.raw, 402 | minAmountOut: computedAmountOut.minAmountOut.raw, 403 | }, 404 | poolKeys.version, 405 | ); 406 | 407 | const messageV0 = new TransactionMessage({ 408 | payerKey: wallet.publicKey, 409 | recentBlockhash: latestBlockhash.blockhash, 410 | instructions: [ 411 | ...(this.isWarp || this.isJito 412 | ? [] 413 | : [ 414 | ComputeBudgetProgram.setComputeUnitPrice({ microLamports: this.config.unitPrice }), 415 | ComputeBudgetProgram.setComputeUnitLimit({ units: this.config.unitLimit }), 416 | ]), 417 | ...(direction === 'buy' 418 | ? [ 419 | createAssociatedTokenAccountIdempotentInstruction( 420 | wallet.publicKey, 421 | ataOut, 422 | wallet.publicKey, 423 | tokenOut.mint, 424 | ), 425 | ] 426 | : []), 427 | ...innerTransaction.instructions, 428 | ...(direction === 'sell' ? [createCloseAccountInstruction(ataIn, wallet.publicKey, wallet.publicKey)] : []), 429 | ], 430 | }).compileToV0Message(); 431 | 432 | const transaction = new VersionedTransaction(messageV0); 433 | transaction.sign([wallet, ...innerTransaction.signers]); 434 | 435 | return this.txExecutor.executeAndConfirm(transaction, wallet, latestBlockhash); 436 | } 437 | 438 | private async filterMatch(poolKeys: LiquidityPoolKeysV4) { 439 | if (this.config.filterCheckInterval === 0 || this.config.filterCheckDuration === 0) { 440 | return true; 441 | } 442 | 443 | const timesToCheck = this.config.filterCheckDuration / this.config.filterCheckInterval; 444 | let timesChecked = 0; 445 | let matchCount = 0; 446 | 447 | do { 448 | try { 449 | const shouldBuy = await this.poolFilters.execute(poolKeys); 450 | 451 | if (shouldBuy) { 452 | matchCount++; 453 | 454 | if (this.config.consecutiveMatchCount <= matchCount) { 455 | logger.debug( 456 | { mint: poolKeys.baseMint.toString() }, 457 | `Filter match ${matchCount}/${this.config.consecutiveMatchCount}`, 458 | ); 459 | return true; 460 | } 461 | } else { 462 | matchCount = 0; 463 | } 464 | 465 | await sleep(this.config.filterCheckInterval); 466 | } finally { 467 | timesChecked++; 468 | } 469 | } while (timesChecked < timesToCheck); 470 | 471 | return false; 472 | } 473 | 474 | private async priceMatch(amountIn: TokenAmount, poolKeys: LiquidityPoolKeysV4) { 475 | if (this.config.priceCheckDuration === 0 || this.config.priceCheckInterval === 0) { 476 | return; 477 | } 478 | 479 | const timesToCheck = this.config.priceCheckDuration / this.config.priceCheckInterval; 480 | const profitFraction = this.config.quoteAmount.mul(this.config.takeProfit).numerator.div(new BN(100)); 481 | const profitAmount = new TokenAmount(this.config.quoteToken, profitFraction, true); 482 | const takeProfit = this.config.quoteAmount.add(profitAmount); 483 | 484 | const lossFraction = this.config.quoteAmount.mul(this.config.stopLoss).numerator.div(new BN(100)); 485 | const lossAmount = new TokenAmount(this.config.quoteToken, lossFraction, true); 486 | const stopLoss = this.config.quoteAmount.subtract(lossAmount); 487 | const slippage = new Percent(this.config.sellSlippage, 100); 488 | let timesChecked = 0; 489 | 490 | do { 491 | try { 492 | const poolInfo = await Liquidity.fetchInfo({ 493 | connection: this.connection, 494 | poolKeys, 495 | }); 496 | 497 | const amountOut = Liquidity.computeAmountOut({ 498 | poolKeys, 499 | poolInfo, 500 | amountIn: amountIn, 501 | currencyOut: this.config.quoteToken, 502 | slippage, 503 | }).amountOut; 504 | 505 | const price = Liquidity.getRate(poolInfo) 506 | logger.debug(`${poolKeys.baseMint.toString()} - price is ${price.toFixed()}`) 507 | 508 | // if (SCALE_OUT) { 509 | // const targets = this.scaleOutTargets[poolKeys.baseMint.toString()]; 510 | // targets.forEach(target => { 511 | // if (!target.sold && amountOut.gt(this.config.quoteAmount)) { 512 | // const gainFraction = this.config.quoteAmount.mul(target.percentToSell).numerator.div(new BN(100)); 513 | // const gainAmount = new TokenAmount(this.config.quoteToken, gainFraction, true); 514 | // 515 | // // const trailingStopLoss = this.trailingStops[poolKeys.baseMint.toString()].subtract(trailingLossAmount); 516 | // 517 | // const amountToSell = this.config.quoteAmount.mul(new BN(target.percentToSell)); 518 | // target.processing = true; 519 | // break; 520 | // } 521 | // }); 522 | // } 523 | 524 | if (TRAILING_STOP) { 525 | if (this.trailingStops[poolKeys.baseMint.toString()].lt(amountOut)) { 526 | // new price higher than saved, update value 527 | logger.trace(`${poolKeys.baseMint.toString()} - Trailing stop price is higher than before, let's update trailing value. Set ${amountOut.toFixed()}`) 528 | this.trailingStops[poolKeys.baseMint.toString()] = amountOut as TokenAmount 529 | } 530 | 531 | const trailingLossFraction = this.trailingStops[poolKeys.baseMint.toString()].mul(this.config.stopLoss).numerator.div(new BN(100)); 532 | const trailingLossAmount = new TokenAmount(this.config.quoteToken, trailingLossFraction, true); 533 | const trailingStopLoss = this.trailingStops[poolKeys.baseMint.toString()].subtract(trailingLossAmount); 534 | 535 | logger.trace(`${poolKeys.baseMint.toString()} - Trailing stop loss value: ${trailingStopLoss.toFixed()}`) 536 | 537 | if (amountOut.lt(trailingStopLoss)) { 538 | logger.trace(`${poolKeys.baseMint.toString()} - Trailing stop loss triggered: ${amountOut.toFixed()} less than ${trailingStopLoss.toFixed()}`) 539 | 540 | delete this.trailingStops[poolKeys.baseMint.toString()] 541 | break; 542 | } 543 | } 544 | 545 | const priceIncrease = amountOut.sub(this.config.quoteAmount); 546 | const percentageIncrease = priceIncrease.mul(new BN(100)).div(this.config.quoteAmount); 547 | 548 | const formattedPercentageIncrease = percentageIncrease.toFixed(2); 549 | 550 | logger.debug(`${poolKeys.baseMint.toString()} - Current: ${amountOut.toFixed()} (${formattedPercentageIncrease}%) | Take profit: ${takeProfit.toFixed()} | Stop loss: ${stopLoss.toFixed()}`,); 551 | 552 | if (SKIP_SELLING_IF_LOST_90PERCENT) { 553 | const stopSellingFraction = this.config.quoteAmount.mul(90).numerator.div(new BN(100)); // 90% 554 | const stopSellingAmount = new TokenAmount(this.config.quoteToken, stopSellingFraction, true); 555 | if (amountOut.lt(stopSellingAmount)) { 556 | return true 557 | } 558 | } 559 | 560 | if (amountOut.lt(stopLoss)) { 561 | break; 562 | } 563 | 564 | if (amountOut.gt(takeProfit)) { 565 | break; 566 | } 567 | 568 | await sleep(this.config.priceCheckInterval); 569 | } catch (e) { 570 | logger.trace({ mint: poolKeys.baseMint.toString(), e }, `Failed to check token price`); 571 | } finally { 572 | timesChecked++; 573 | } 574 | } while (timesChecked < timesToCheck); 575 | } 576 | } 577 | --------------------------------------------------------------------------------