bot.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. Liquidity,
  19. LiquidityPoolKeysV4,
  20. LiquidityStateV4,
  21. Percent,
  22. Token,
  23. TokenAmount,
  24. } from '@raydium-io/raydium-sdk';
  25. import { MarketCache, PoolCache, SnipeListCache } from './cache';
  26. import { PoolFilters } from './filters';
  27. import { TransactionExecutor } from './transactions';
  28. import { createPoolKeys, logger, NETWORK, sleep } from './helpers';
  29. import { Mutex } from 'async-mutex';
  30. import BN from 'bn.js';
  31. export interface BotConfig {
  32. wallet: Keypair;
  33. checkRenounced: boolean;
  34. checkBurned: boolean;
  35. minPoolSize: TokenAmount;
  36. maxPoolSize: TokenAmount;
  37. quoteToken: Token;
  38. quoteAmount: TokenAmount;
  39. quoteAta: PublicKey;
  40. oneTokenAtATime: boolean;
  41. useSnipeList: boolean;
  42. autoSell: boolean;
  43. autoBuyDelay: number;
  44. autoSellDelay: number;
  45. maxBuyRetries: number;
  46. maxSellRetries: number;
  47. unitLimit: number;
  48. unitPrice: number;
  49. takeProfit: number;
  50. stopLoss: number;
  51. buySlippage: number;
  52. sellSlippage: number;
  53. priceCheckInterval: number;
  54. priceCheckDuration: number;
  55. }
  56. export class Bot {
  57. private readonly poolFilters: PoolFilters;
  58. // snipe list
  59. private readonly snipeListCache?: SnipeListCache;
  60. // one token at the time
  61. private readonly mutex: Mutex;
  62. private sellExecutionCount = 0;
  63. constructor(
  64. private readonly connection: Connection,
  65. private readonly marketStorage: MarketCache,
  66. private readonly poolStorage: PoolCache,
  67. private readonly txExecutor: TransactionExecutor,
  68. private readonly config: BotConfig,
  69. ) {
  70. this.mutex = new Mutex();
  71. this.poolFilters = new PoolFilters(connection, {
  72. quoteToken: this.config.quoteToken,
  73. minPoolSize: this.config.minPoolSize,
  74. maxPoolSize: this.config.maxPoolSize,
  75. });
  76. if (this.config.useSnipeList) {
  77. this.snipeListCache = new SnipeListCache();
  78. this.snipeListCache.init();
  79. }
  80. }
  81. async validate() {
  82. try {
  83. await getAccount(this.connection, this.config.quoteAta, this.connection.commitment);
  84. } catch (error) {
  85. logger.error(
  86. `${this.config.quoteToken.symbol} token account not found in wallet: ${this.config.wallet.publicKey.toString()}`,
  87. );
  88. return false;
  89. }
  90. return true;
  91. }
  92. public async buy(accountId: PublicKey, poolState: LiquidityStateV4) {
  93. logger.trace({ mint: poolState.baseMint }, `Processing buy...`);
  94. if (this.config.useSnipeList && !this.snipeListCache?.isInList(poolState.baseMint.toString())) {
  95. logger.debug({ mint: poolState.baseMint.toString() }, `Skipping buy because token is not in a snipe list`);
  96. return;
  97. }
  98. if (this.config.autoBuyDelay > 0) {
  99. logger.debug({ mint: poolState.baseMint }, `Waiting for ${this.config.autoBuyDelay} ms before buy`);
  100. await sleep(this.config.autoBuyDelay);
  101. }
  102. if (this.config.oneTokenAtATime) {
  103. if (this.mutex.isLocked() || this.sellExecutionCount > 0) {
  104. logger.debug(
  105. { mint: poolState.baseMint.toString() },
  106. `Skipping buy because one token at a time is turned on and token is already being processed`,
  107. );
  108. return;
  109. }
  110. await this.mutex.acquire();
  111. }
  112. try {
  113. const shouldBuy = await this.poolFilters.execute(poolState);
  114. if (!shouldBuy) {
  115. logger.debug({ mint: poolState.baseMint.toString() }, `Skipping buy because pool doesn't match filters`);
  116. return;
  117. }
  118. for (let i = 0; i < this.config.maxBuyRetries; i++) {
  119. try {
  120. const [market, mintAta] = await Promise.all([
  121. this.marketStorage.get(poolState.marketId.toString()),
  122. getAssociatedTokenAddress(poolState.baseMint, this.config.wallet.publicKey),
  123. ]);
  124. const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(accountId, poolState, market);
  125. logger.info(
  126. { mint: poolState.baseMint.toString() },
  127. `Send buy transaction attempt: ${i + 1}/${this.config.maxBuyRetries}`,
  128. );
  129. const tokenOut = new Token(TOKEN_PROGRAM_ID, poolKeys.baseMint, poolKeys.baseDecimals);
  130. const result = await this.swap(
  131. poolKeys,
  132. this.config.quoteAta,
  133. mintAta,
  134. this.config.quoteToken,
  135. tokenOut,
  136. this.config.quoteAmount,
  137. this.config.buySlippage,
  138. this.config.wallet,
  139. 'buy',
  140. );
  141. if (result.confirmed) {
  142. logger.info(
  143. {
  144. mint: poolState.baseMint.toString(),
  145. signature: result.signature,
  146. url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`,
  147. },
  148. `Confirmed buy tx`,
  149. );
  150. break;
  151. }
  152. logger.debug(
  153. {
  154. mint: poolState.baseMint.toString(),
  155. signature: result.signature,
  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. for (let i = 0; i < this.config.maxSellRetries; i++) {
  193. try {
  194. const market = await this.marketStorage.get(poolData.state.marketId.toString());
  195. const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(new PublicKey(poolData.id), poolData.state, market);
  196. await this.priceMatch(tokenAmountIn, poolKeys);
  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. },
  229. `Error confirming sell tx`,
  230. );
  231. } catch (error) {
  232. logger.debug({ mint: rawAccount.mint.toString(), error }, `Error confirming sell transaction`);
  233. }
  234. }
  235. } catch (error) {
  236. logger.debug({ mint: rawAccount.mint.toString(), error }, `Failed to sell token`);
  237. } finally {
  238. if (this.config.oneTokenAtATime) {
  239. this.sellExecutionCount--;
  240. }
  241. }
  242. }
  243. private async swap(
  244. poolKeys: LiquidityPoolKeysV4,
  245. ataIn: PublicKey,
  246. ataOut: PublicKey,
  247. tokenIn: Token,
  248. tokenOut: Token,
  249. amountIn: TokenAmount,
  250. slippage: number,
  251. wallet: Keypair,
  252. direction: 'buy' | 'sell',
  253. ) {
  254. const slippagePercent = new Percent(slippage, 100);
  255. const poolInfo = await Liquidity.fetchInfo({
  256. connection: this.connection,
  257. poolKeys,
  258. });
  259. const computedAmountOut = Liquidity.computeAmountOut({
  260. poolKeys,
  261. poolInfo,
  262. amountIn,
  263. currencyOut: tokenOut,
  264. slippage: slippagePercent,
  265. });
  266. const latestBlockhash = await this.connection.getLatestBlockhash();
  267. const { innerTransaction } = Liquidity.makeSwapFixedInInstruction(
  268. {
  269. poolKeys: poolKeys,
  270. userKeys: {
  271. tokenAccountIn: ataIn,
  272. tokenAccountOut: ataOut,
  273. owner: wallet.publicKey,
  274. },
  275. amountIn: amountIn.raw,
  276. minAmountOut: computedAmountOut.minAmountOut.raw,
  277. },
  278. poolKeys.version,
  279. );
  280. const messageV0 = new TransactionMessage({
  281. payerKey: wallet.publicKey,
  282. recentBlockhash: latestBlockhash.blockhash,
  283. instructions: [
  284. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: this.config.unitPrice }),
  285. ComputeBudgetProgram.setComputeUnitLimit({ units: this.config.unitLimit }),
  286. ...(direction === 'buy'
  287. ? [
  288. createAssociatedTokenAccountIdempotentInstruction(
  289. wallet.publicKey,
  290. ataOut,
  291. wallet.publicKey,
  292. tokenOut.mint,
  293. ),
  294. ]
  295. : []),
  296. ...innerTransaction.instructions,
  297. ...(direction === 'sell' ? [createCloseAccountInstruction(ataIn, wallet.publicKey, wallet.publicKey)] : []),
  298. ],
  299. }).compileToV0Message();
  300. const transaction = new VersionedTransaction(messageV0);
  301. transaction.sign([wallet, ...innerTransaction.signers]);
  302. return this.txExecutor.executeAndConfirm(transaction, latestBlockhash);
  303. }
  304. private async priceMatch(amountIn: TokenAmount, poolKeys: LiquidityPoolKeysV4) {
  305. const profitFraction = this.config.quoteAmount.mul(this.config.takeProfit).numerator.div(new BN(100));
  306. const profitAmount = new TokenAmount(this.config.quoteToken, profitFraction, true);
  307. const takeProfit = this.config.quoteAmount.add(profitAmount);
  308. const lossFraction = this.config.quoteAmount.mul(this.config.stopLoss).numerator.div(new BN(100));
  309. const lossAmount = new TokenAmount(this.config.quoteToken, lossFraction, true);
  310. const stopLoss = this.config.quoteAmount.subtract(lossAmount);
  311. const slippage = new Percent(this.config.sellSlippage, 100);
  312. const timesToCheck = this.config.priceCheckDuration / this.config.priceCheckInterval;
  313. let timesChecked = 0;
  314. do {
  315. try {
  316. const poolInfo = await Liquidity.fetchInfo({
  317. connection: this.connection,
  318. poolKeys,
  319. });
  320. const amountOut = Liquidity.computeAmountOut({
  321. poolKeys,
  322. poolInfo,
  323. amountIn: amountIn,
  324. currencyOut: this.config.quoteToken,
  325. slippage,
  326. }).amountOut;
  327. logger.debug(
  328. { mint: poolKeys.baseMint.toString() },
  329. `Take profit: ${takeProfit.toFixed()} | Stop loss: ${stopLoss.toFixed()} | Current: ${amountOut.toFixed()}`,
  330. );
  331. if (amountOut.lt(stopLoss)){
  332. break;
  333. }
  334. if (amountOut.gt(takeProfit)){
  335. break;
  336. }
  337. await sleep(this.config.priceCheckInterval);
  338. } catch (e) {
  339. logger.trace({ mint: poolKeys.baseMint.toString(), e }, `Failed to check token price`);
  340. } finally {
  341. timesChecked++;
  342. }
  343. } while (timesChecked < timesToCheck);
  344. }
  345. }