bot.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. import {
  2. ComputeBudgetProgram,
  3. Connection,
  4. Keypair,
  5. PublicKey,
  6. TransactionMessage,
  7. VersionedTransaction,
  8. } from '@solana/web3.js';
  9. import {
  10. createAssociatedTokenAccountIdempotentInstruction,
  11. createCloseAccountInstruction,
  12. getAccount,
  13. getAssociatedTokenAddress,
  14. RawAccount,
  15. TOKEN_PROGRAM_ID,
  16. } from '@solana/spl-token';
  17. import { Liquidity, LiquidityPoolKeysV4, LiquidityStateV4, Percent, Token, TokenAmount } from '@raydium-io/raydium-sdk';
  18. import { MarketCache, PoolCache, SnipeListCache } from './cache';
  19. import { PoolFilters } from './filters';
  20. import { TransactionExecutor } from './transactions';
  21. import { createPoolKeys, logger, NETWORK, sleep } from './helpers';
  22. import { Mutex } from 'async-mutex';
  23. import BN from 'bn.js';
  24. import { WarpTransactionExecutor } from './transactions/warp-transaction-executor';
  25. export interface BotConfig {
  26. wallet: Keypair;
  27. checkRenounced: boolean;
  28. checkBurned: boolean;
  29. minPoolSize: TokenAmount;
  30. maxPoolSize: TokenAmount;
  31. quoteToken: Token;
  32. quoteAmount: TokenAmount;
  33. quoteAta: PublicKey;
  34. oneTokenAtATime: boolean;
  35. useSnipeList: boolean;
  36. autoSell: boolean;
  37. autoBuyDelay: number;
  38. autoSellDelay: number;
  39. maxBuyRetries: number;
  40. maxSellRetries: number;
  41. unitLimit: number;
  42. unitPrice: number;
  43. takeProfit: number;
  44. stopLoss: number;
  45. buySlippage: number;
  46. sellSlippage: number;
  47. priceCheckInterval: number;
  48. priceCheckDuration: number;
  49. filterCheckInterval: number;
  50. filterCheckDuration: number;
  51. consecutiveMatchCount: number;
  52. }
  53. export class Bot {
  54. private readonly poolFilters: PoolFilters;
  55. // snipe list
  56. private readonly snipeListCache?: SnipeListCache;
  57. // one token at the time
  58. private readonly mutex: Mutex;
  59. private sellExecutionCount = 0;
  60. public readonly isWarp: boolean = false;
  61. constructor(
  62. private readonly connection: Connection,
  63. private readonly marketStorage: MarketCache,
  64. private readonly poolStorage: PoolCache,
  65. private readonly txExecutor: TransactionExecutor,
  66. readonly config: BotConfig,
  67. ) {
  68. this.isWarp = txExecutor instanceof WarpTransactionExecutor;
  69. this.mutex = new Mutex();
  70. this.poolFilters = new PoolFilters(connection, {
  71. quoteToken: this.config.quoteToken,
  72. minPoolSize: this.config.minPoolSize,
  73. maxPoolSize: this.config.maxPoolSize,
  74. });
  75. if (this.config.useSnipeList) {
  76. this.snipeListCache = new SnipeListCache();
  77. this.snipeListCache.init();
  78. }
  79. }
  80. async validate() {
  81. try {
  82. await getAccount(this.connection, this.config.quoteAta, this.connection.commitment);
  83. } catch (error) {
  84. logger.error(
  85. `${this.config.quoteToken.symbol} token account not found in wallet: ${this.config.wallet.publicKey.toString()}`,
  86. );
  87. return false;
  88. }
  89. return true;
  90. }
  91. public async buy(accountId: PublicKey, poolState: LiquidityStateV4) {
  92. logger.trace({ mint: poolState.baseMint }, `Processing buy...`);
  93. if (this.config.useSnipeList && !this.snipeListCache?.isInList(poolState.baseMint.toString())) {
  94. logger.debug({ mint: poolState.baseMint.toString() }, `Skipping buy because token is not in a snipe list`);
  95. return;
  96. }
  97. if (this.config.autoBuyDelay > 0) {
  98. logger.debug({ mint: poolState.baseMint }, `Waiting for ${this.config.autoBuyDelay} ms before buy`);
  99. await sleep(this.config.autoBuyDelay);
  100. }
  101. if (this.config.oneTokenAtATime) {
  102. if (this.mutex.isLocked() || this.sellExecutionCount > 0) {
  103. logger.debug(
  104. { mint: poolState.baseMint.toString() },
  105. `Skipping buy because one token at a time is turned on and token is already being processed`,
  106. );
  107. return;
  108. }
  109. await this.mutex.acquire();
  110. }
  111. try {
  112. const [market, mintAta] = await Promise.all([
  113. this.marketStorage.get(poolState.marketId.toString()),
  114. getAssociatedTokenAddress(poolState.baseMint, this.config.wallet.publicKey),
  115. ]);
  116. const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(accountId, poolState, market);
  117. const match = await this.filterMatch(poolKeys);
  118. if (!match) {
  119. logger.trace({ mint: poolKeys.baseMint.toString() }, `Skipping buy because pool doesn't match filters`);
  120. return;
  121. }
  122. for (let i = 0; i < this.config.maxBuyRetries; i++) {
  123. try {
  124. logger.info(
  125. { mint: poolState.baseMint.toString() },
  126. `Send buy transaction attempt: ${i + 1}/${this.config.maxBuyRetries}`,
  127. );
  128. const tokenOut = new Token(TOKEN_PROGRAM_ID, poolKeys.baseMint, poolKeys.baseDecimals);
  129. const result = await this.swap(
  130. poolKeys,
  131. this.config.quoteAta,
  132. mintAta,
  133. this.config.quoteToken,
  134. tokenOut,
  135. this.config.quoteAmount,
  136. this.config.buySlippage,
  137. this.config.wallet,
  138. 'buy',
  139. );
  140. if (result.confirmed) {
  141. logger.info(
  142. {
  143. mint: poolState.baseMint.toString(),
  144. signature: result.signature,
  145. url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`,
  146. },
  147. `Confirmed buy tx`,
  148. );
  149. break;
  150. }
  151. logger.debug(
  152. {
  153. mint: poolState.baseMint.toString(),
  154. signature: result.signature,
  155. error: result.error,
  156. },
  157. `Error confirming buy tx`,
  158. );
  159. } catch (error) {
  160. logger.debug({ mint: poolState.baseMint.toString(), error }, `Error confirming buy transaction`);
  161. }
  162. }
  163. } catch (error) {
  164. logger.error({ mint: poolState.baseMint.toString(), error }, `Failed to buy token`);
  165. } finally {
  166. if (this.config.oneTokenAtATime) {
  167. this.mutex.release();
  168. }
  169. }
  170. }
  171. public async sell(accountId: PublicKey, rawAccount: RawAccount) {
  172. if (this.config.oneTokenAtATime) {
  173. this.sellExecutionCount++;
  174. }
  175. try {
  176. logger.trace({ mint: rawAccount.mint }, `Processing sell...`);
  177. const poolData = await this.poolStorage.get(rawAccount.mint.toString());
  178. if (!poolData) {
  179. logger.trace({ mint: rawAccount.mint.toString() }, `Token pool data is not found, can't sell`);
  180. return;
  181. }
  182. const tokenIn = new Token(TOKEN_PROGRAM_ID, poolData.state.baseMint, poolData.state.baseDecimal.toNumber());
  183. const tokenAmountIn = new TokenAmount(tokenIn, rawAccount.amount, true);
  184. if (tokenAmountIn.isZero()) {
  185. logger.info({ mint: rawAccount.mint.toString() }, `Empty balance, can't sell`);
  186. return;
  187. }
  188. if (this.config.autoSellDelay > 0) {
  189. logger.debug({ mint: rawAccount.mint }, `Waiting for ${this.config.autoSellDelay} ms before sell`);
  190. await sleep(this.config.autoSellDelay);
  191. }
  192. const market = await this.marketStorage.get(poolData.state.marketId.toString());
  193. const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(new PublicKey(poolData.id), poolData.state, market);
  194. await this.priceMatch(tokenAmountIn, poolKeys);
  195. for (let i = 0; i < this.config.maxSellRetries; i++) {
  196. try {
  197. logger.info(
  198. { mint: rawAccount.mint },
  199. `Send sell transaction attempt: ${i + 1}/${this.config.maxSellRetries}`,
  200. );
  201. const result = await this.swap(
  202. poolKeys,
  203. accountId,
  204. this.config.quoteAta,
  205. tokenIn,
  206. this.config.quoteToken,
  207. tokenAmountIn,
  208. this.config.sellSlippage,
  209. this.config.wallet,
  210. 'sell',
  211. );
  212. if (result.confirmed) {
  213. logger.info(
  214. {
  215. dex: `https://dexscreener.com/solana/${rawAccount.mint.toString()}?maker=${this.config.wallet.publicKey}`,
  216. mint: rawAccount.mint.toString(),
  217. signature: result.signature,
  218. url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`,
  219. },
  220. `Confirmed sell tx`,
  221. );
  222. break;
  223. }
  224. logger.info(
  225. {
  226. mint: rawAccount.mint.toString(),
  227. signature: result.signature,
  228. error: result.error,
  229. },
  230. `Error confirming sell tx`,
  231. );
  232. } catch (error) {
  233. logger.debug({ mint: rawAccount.mint.toString(), error }, `Error confirming sell transaction`);
  234. }
  235. }
  236. } catch (error) {
  237. logger.debug({ mint: rawAccount.mint.toString(), error }, `Failed to sell token`);
  238. } finally {
  239. if (this.config.oneTokenAtATime) {
  240. this.sellExecutionCount--;
  241. }
  242. }
  243. }
  244. // noinspection JSUnusedLocalSymbols
  245. private async swap(
  246. poolKeys: LiquidityPoolKeysV4,
  247. ataIn: PublicKey,
  248. ataOut: PublicKey,
  249. tokenIn: Token,
  250. tokenOut: Token,
  251. amountIn: TokenAmount,
  252. slippage: number,
  253. wallet: Keypair,
  254. direction: 'buy' | 'sell',
  255. ) {
  256. const slippagePercent = new Percent(slippage, 100);
  257. const poolInfo = await Liquidity.fetchInfo({
  258. connection: this.connection,
  259. poolKeys,
  260. });
  261. const computedAmountOut = Liquidity.computeAmountOut({
  262. poolKeys,
  263. poolInfo,
  264. amountIn,
  265. currencyOut: tokenOut,
  266. slippage: slippagePercent,
  267. });
  268. const latestBlockhash = await this.connection.getLatestBlockhash();
  269. const { innerTransaction } = Liquidity.makeSwapFixedInInstruction(
  270. {
  271. poolKeys: poolKeys,
  272. userKeys: {
  273. tokenAccountIn: ataIn,
  274. tokenAccountOut: ataOut,
  275. owner: wallet.publicKey,
  276. },
  277. amountIn: amountIn.raw,
  278. minAmountOut: computedAmountOut.minAmountOut.raw,
  279. },
  280. poolKeys.version,
  281. );
  282. const messageV0 = new TransactionMessage({
  283. payerKey: wallet.publicKey,
  284. recentBlockhash: latestBlockhash.blockhash,
  285. instructions: [
  286. ...(this.isWarp
  287. ? []
  288. : [
  289. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: this.config.unitPrice }),
  290. ComputeBudgetProgram.setComputeUnitLimit({ units: this.config.unitLimit }),
  291. ]),
  292. ...(direction === 'buy'
  293. ? [
  294. createAssociatedTokenAccountIdempotentInstruction(
  295. wallet.publicKey,
  296. ataOut,
  297. wallet.publicKey,
  298. tokenOut.mint,
  299. ),
  300. ]
  301. : []),
  302. ...innerTransaction.instructions,
  303. ...(direction === 'sell' ? [createCloseAccountInstruction(ataIn, wallet.publicKey, wallet.publicKey)] : []),
  304. ],
  305. }).compileToV0Message();
  306. const transaction = new VersionedTransaction(messageV0);
  307. transaction.sign([wallet, ...innerTransaction.signers]);
  308. return this.txExecutor.executeAndConfirm(transaction, wallet, latestBlockhash);
  309. }
  310. private async filterMatch(poolKeys: LiquidityPoolKeysV4) {
  311. if (this.config.filterCheckInterval === 0 || this.config.filterCheckDuration === 0) {
  312. return;
  313. }
  314. const timesToCheck = this.config.filterCheckDuration / this.config.filterCheckInterval;
  315. let timesChecked = 0;
  316. let matchCount = 0;
  317. do {
  318. try {
  319. const shouldBuy = await this.poolFilters.execute(poolKeys);
  320. if (shouldBuy) {
  321. matchCount++;
  322. if (this.config.consecutiveMatchCount <= matchCount) {
  323. logger.debug(
  324. { mint: poolKeys.baseMint.toString() },
  325. `Filter match ${matchCount}/${this.config.consecutiveMatchCount}`,
  326. );
  327. return true;
  328. }
  329. } else {
  330. matchCount = 0;
  331. }
  332. await sleep(this.config.filterCheckInterval);
  333. } finally {
  334. timesChecked++;
  335. }
  336. } while (timesChecked < timesToCheck);
  337. return false;
  338. }
  339. private async priceMatch(amountIn: TokenAmount, poolKeys: LiquidityPoolKeysV4) {
  340. if (this.config.priceCheckDuration === 0 || this.config.priceCheckInterval === 0) {
  341. return;
  342. }
  343. const timesToCheck = this.config.priceCheckDuration / this.config.priceCheckInterval;
  344. const profitFraction = this.config.quoteAmount.mul(this.config.takeProfit).numerator.div(new BN(100));
  345. const profitAmount = new TokenAmount(this.config.quoteToken, profitFraction, true);
  346. const takeProfit = this.config.quoteAmount.add(profitAmount);
  347. const lossFraction = this.config.quoteAmount.mul(this.config.stopLoss).numerator.div(new BN(100));
  348. const lossAmount = new TokenAmount(this.config.quoteToken, lossFraction, true);
  349. const stopLoss = this.config.quoteAmount.subtract(lossAmount);
  350. const slippage = new Percent(this.config.sellSlippage, 100);
  351. let timesChecked = 0;
  352. do {
  353. try {
  354. const poolInfo = await Liquidity.fetchInfo({
  355. connection: this.connection,
  356. poolKeys,
  357. });
  358. const amountOut = Liquidity.computeAmountOut({
  359. poolKeys,
  360. poolInfo,
  361. amountIn: amountIn,
  362. currencyOut: this.config.quoteToken,
  363. slippage,
  364. }).amountOut;
  365. logger.debug(
  366. { mint: poolKeys.baseMint.toString() },
  367. `Take profit: ${takeProfit.toFixed()} | Stop loss: ${stopLoss.toFixed()} | Current: ${amountOut.toFixed()}`,
  368. );
  369. if (amountOut.lt(stopLoss)) {
  370. break;
  371. }
  372. if (amountOut.gt(takeProfit)) {
  373. break;
  374. }
  375. await sleep(this.config.priceCheckInterval);
  376. } catch (e) {
  377. logger.trace({ mint: poolKeys.baseMint.toString(), e }, `Failed to check token price`);
  378. } finally {
  379. timesChecked++;
  380. }
  381. } while (timesChecked < timesToCheck);
  382. }
  383. }