buy.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. import {
  2. BigNumberish,
  3. Liquidity,
  4. LIQUIDITY_STATE_LAYOUT_V4,
  5. LiquidityPoolKeys,
  6. LiquidityStateV4,
  7. MARKET_STATE_LAYOUT_V3,
  8. MarketStateV3,
  9. Token,
  10. TokenAmount,
  11. } from '@raydium-io/raydium-sdk';
  12. import {
  13. AccountLayout,
  14. createAssociatedTokenAccountIdempotentInstruction,
  15. createCloseAccountInstruction,
  16. getAssociatedTokenAddressSync,
  17. TOKEN_PROGRAM_ID,
  18. } from '@solana/spl-token';
  19. import {
  20. Keypair,
  21. Connection,
  22. PublicKey,
  23. ComputeBudgetProgram,
  24. KeyedAccountInfo,
  25. TransactionMessage,
  26. VersionedTransaction,
  27. } from '@solana/web3.js';
  28. import { getTokenAccounts, RAYDIUM_LIQUIDITY_PROGRAM_ID_V4, OPENBOOK_PROGRAM_ID, createPoolKeys } from './liquidity';
  29. import { logger } from './utils';
  30. import { getMinimalMarketV3, MinimalMarketLayoutV3 } from './market';
  31. import { MintLayout } from './types';
  32. import bs58 from 'bs58';
  33. import * as fs from 'fs';
  34. import * as path from 'path';
  35. import {
  36. AUTO_SELL,
  37. AUTO_SELL_DELAY,
  38. CHECK_IF_MINT_IS_RENOUNCED,
  39. COMMITMENT_LEVEL,
  40. LOG_LEVEL,
  41. MAX_SELL_RETRIES,
  42. NETWORK,
  43. PRIVATE_KEY,
  44. QUOTE_AMOUNT,
  45. QUOTE_MINT,
  46. RPC_ENDPOINT,
  47. RPC_WEBSOCKET_ENDPOINT,
  48. SNIPE_LIST_REFRESH_INTERVAL,
  49. USE_SNIPE_LIST,
  50. MIN_POOL_SIZE,
  51. MAX_POOL_SIZE,
  52. ONE_TOKEN_AT_A_TIME,
  53. } from './constants';
  54. const solanaConnection = new Connection(RPC_ENDPOINT, {
  55. wsEndpoint: RPC_WEBSOCKET_ENDPOINT,
  56. });
  57. export interface MinimalTokenAccountData {
  58. mint: PublicKey;
  59. address: PublicKey;
  60. poolKeys?: LiquidityPoolKeys;
  61. market?: MinimalMarketLayoutV3;
  62. }
  63. const existingLiquidityPools: Set<string> = new Set<string>();
  64. const existingOpenBookMarkets: Set<string> = new Set<string>();
  65. const existingTokenAccounts: Map<string, MinimalTokenAccountData> = new Map<string, MinimalTokenAccountData>();
  66. let wallet: Keypair;
  67. let quoteToken: Token;
  68. let quoteTokenAssociatedAddress: PublicKey;
  69. let quoteAmount: TokenAmount;
  70. let quoteMinPoolSizeAmount: TokenAmount;
  71. let quoteMaxPoolSizeAmount: TokenAmount;
  72. let processingToken: Boolean = false;
  73. let snipeList: string[] = [];
  74. async function init(): Promise<void> {
  75. logger.level = LOG_LEVEL;
  76. // get wallet
  77. wallet = Keypair.fromSecretKey(bs58.decode(PRIVATE_KEY));
  78. logger.info(`Wallet Address: ${wallet.publicKey}`);
  79. // get quote mint and amount
  80. switch (QUOTE_MINT) {
  81. case 'WSOL': {
  82. quoteToken = Token.WSOL;
  83. quoteAmount = new TokenAmount(Token.WSOL, QUOTE_AMOUNT, false);
  84. quoteMinPoolSizeAmount = new TokenAmount(quoteToken, MIN_POOL_SIZE, false);
  85. quoteMaxPoolSizeAmount = new TokenAmount(quoteToken, MAX_POOL_SIZE, false);
  86. break;
  87. }
  88. case 'USDC': {
  89. quoteToken = new Token(
  90. TOKEN_PROGRAM_ID,
  91. new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),
  92. 6,
  93. 'USDC',
  94. 'USDC',
  95. );
  96. quoteAmount = new TokenAmount(quoteToken, QUOTE_AMOUNT, false);
  97. quoteMinPoolSizeAmount = new TokenAmount(quoteToken, MIN_POOL_SIZE, false);
  98. quoteMaxPoolSizeAmount = new TokenAmount(quoteToken, MAX_POOL_SIZE, false);
  99. break;
  100. }
  101. default: {
  102. throw new Error(`Unsupported quote mint "${QUOTE_MINT}". Supported values are USDC and WSOL`);
  103. }
  104. }
  105. logger.info(`Snipe list: ${USE_SNIPE_LIST}`);
  106. logger.info(`Check mint renounced: ${CHECK_IF_MINT_IS_RENOUNCED}`);
  107. logger.info(
  108. `Min pool size: ${quoteMinPoolSizeAmount.isZero() ? 'false' : quoteMinPoolSizeAmount.toFixed()} ${quoteToken.symbol}`,
  109. );
  110. logger.info(
  111. `Max pool size: ${quoteMaxPoolSizeAmount.isZero() ? 'false' : quoteMaxPoolSizeAmount.toFixed()} ${quoteToken.symbol}`,
  112. );
  113. logger.info(`One token at a time: ${ONE_TOKEN_AT_A_TIME}`);
  114. logger.info(`Buy amount: ${quoteAmount.toFixed()} ${quoteToken.symbol}`);
  115. logger.info(`Auto sell: ${AUTO_SELL}`);
  116. logger.info(`Sell delay: ${AUTO_SELL_DELAY === 0 ? 'false' : AUTO_SELL_DELAY}`);
  117. // check existing wallet for associated token account of quote mint
  118. const tokenAccounts = await getTokenAccounts(solanaConnection, wallet.publicKey, COMMITMENT_LEVEL);
  119. for (const ta of tokenAccounts) {
  120. existingTokenAccounts.set(ta.accountInfo.mint.toString(), <MinimalTokenAccountData>{
  121. mint: ta.accountInfo.mint,
  122. address: ta.pubkey,
  123. });
  124. }
  125. const tokenAccount = tokenAccounts.find((acc) => acc.accountInfo.mint.toString() === quoteToken.mint.toString())!;
  126. if (!tokenAccount) {
  127. throw new Error(`No ${quoteToken.symbol} token account found in wallet: ${wallet.publicKey}`);
  128. }
  129. quoteTokenAssociatedAddress = tokenAccount.pubkey;
  130. // load tokens to snipe
  131. loadSnipeList();
  132. }
  133. function saveTokenAccount(mint: PublicKey, accountData: MinimalMarketLayoutV3) {
  134. const ata = getAssociatedTokenAddressSync(mint, wallet.publicKey);
  135. const tokenAccount = <MinimalTokenAccountData>{
  136. address: ata,
  137. mint: mint,
  138. market: <MinimalMarketLayoutV3>{
  139. bids: accountData.bids,
  140. asks: accountData.asks,
  141. eventQueue: accountData.eventQueue,
  142. },
  143. };
  144. existingTokenAccounts.set(mint.toString(), tokenAccount);
  145. return tokenAccount;
  146. }
  147. export async function processRaydiumPool(id: PublicKey, poolState: LiquidityStateV4) {
  148. if (!shouldBuy(poolState.baseMint.toString())) {
  149. return;
  150. }
  151. if (!quoteMinPoolSizeAmount.isZero()) {
  152. const poolSize = new TokenAmount(quoteToken, poolState.swapQuoteInAmount, true);
  153. logger.info(`Processing pool: ${id.toString()} with ${poolSize.toFixed()} ${quoteToken.symbol} in liquidity`);
  154. if (poolSize.lt(quoteMinPoolSizeAmount)) {
  155. logger.warn(
  156. {
  157. mint: poolState.baseMint,
  158. pooled: `${poolSize.toFixed()} ${quoteToken.symbol}`,
  159. },
  160. `Skipping pool, smaller than ${quoteMinPoolSizeAmount.toFixed()} ${quoteToken.symbol}`,
  161. `Swap quote in amount: ${poolSize.toFixed()}`,
  162. );
  163. logger.info(`-------------------🤖🔧------------------- \n`);
  164. return;
  165. }
  166. }
  167. if (!quoteMaxPoolSizeAmount.isZero()) {
  168. const poolSize = new TokenAmount(quoteToken, poolState.swapQuoteInAmount, true);
  169. if (poolSize.gt(quoteMaxPoolSizeAmount)) {
  170. logger.warn(
  171. {
  172. mint: poolState.baseMint,
  173. pooled: `${poolSize.toFixed()} ${quoteToken.symbol}`,
  174. },
  175. `Skipping pool, bigger than ${quoteMaxPoolSizeAmount.toFixed()} ${quoteToken.symbol}`,
  176. `Swap quote in amount: ${poolSize.toFixed()}`,
  177. );
  178. logger.info(`-------------------🤖🔧------------------- \n`);
  179. return;
  180. }
  181. }
  182. if (CHECK_IF_MINT_IS_RENOUNCED) {
  183. const mintOption = await checkMintable(poolState.baseMint);
  184. if (mintOption !== true) {
  185. logger.warn({ mint: poolState.baseMint }, 'Skipping, owner can mint tokens!');
  186. return;
  187. }
  188. }
  189. await buy(id, poolState);
  190. }
  191. export async function checkMintable(vault: PublicKey): Promise<boolean | undefined> {
  192. try {
  193. let { data } = (await solanaConnection.getAccountInfo(vault)) || {};
  194. if (!data) {
  195. return;
  196. }
  197. const deserialize = MintLayout.decode(data);
  198. return deserialize.mintAuthorityOption === 0;
  199. } catch (e) {
  200. logger.debug(e);
  201. logger.error({ mint: vault }, `Failed to check if mint is renounced`);
  202. }
  203. }
  204. export async function processOpenBookMarket(updatedAccountInfo: KeyedAccountInfo) {
  205. let accountData: MarketStateV3 | undefined;
  206. try {
  207. accountData = MARKET_STATE_LAYOUT_V3.decode(updatedAccountInfo.accountInfo.data);
  208. // to be competitive, we collect market data before buying the token...
  209. if (existingTokenAccounts.has(accountData.baseMint.toString())) {
  210. return;
  211. }
  212. saveTokenAccount(accountData.baseMint, accountData);
  213. } catch (e) {
  214. logger.debug(e);
  215. logger.error({ mint: accountData?.baseMint }, `Failed to process market`);
  216. }
  217. }
  218. async function buy(accountId: PublicKey, accountData: LiquidityStateV4): Promise<void> {
  219. try {
  220. let tokenAccount = existingTokenAccounts.get(accountData.baseMint.toString());
  221. if (!tokenAccount) {
  222. // it's possible that we didn't have time to fetch open book data
  223. const market = await getMinimalMarketV3(solanaConnection, accountData.marketId, COMMITMENT_LEVEL);
  224. tokenAccount = saveTokenAccount(accountData.baseMint, market);
  225. }
  226. tokenAccount.poolKeys = createPoolKeys(accountId, accountData, tokenAccount.market!);
  227. const { innerTransaction } = Liquidity.makeSwapFixedInInstruction(
  228. {
  229. poolKeys: tokenAccount.poolKeys,
  230. userKeys: {
  231. tokenAccountIn: quoteTokenAssociatedAddress,
  232. tokenAccountOut: tokenAccount.address,
  233. owner: wallet.publicKey,
  234. },
  235. amountIn: quoteAmount.raw,
  236. minAmountOut: 0,
  237. },
  238. tokenAccount.poolKeys.version,
  239. );
  240. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  241. commitment: COMMITMENT_LEVEL,
  242. });
  243. const messageV0 = new TransactionMessage({
  244. payerKey: wallet.publicKey,
  245. recentBlockhash: latestBlockhash.blockhash,
  246. instructions: [
  247. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 421197 }),
  248. ComputeBudgetProgram.setComputeUnitLimit({ units: 101337 }),
  249. createAssociatedTokenAccountIdempotentInstruction(
  250. wallet.publicKey,
  251. tokenAccount.address,
  252. wallet.publicKey,
  253. accountData.baseMint,
  254. ),
  255. ...innerTransaction.instructions,
  256. ],
  257. }).compileToV0Message();
  258. const transaction = new VersionedTransaction(messageV0);
  259. transaction.sign([wallet, ...innerTransaction.signers]);
  260. const signature = await solanaConnection.sendRawTransaction(transaction.serialize(), {
  261. preflightCommitment: COMMITMENT_LEVEL,
  262. });
  263. logger.info({ mint: accountData.baseMint, signature }, `Sent buy tx`);
  264. processingToken = true;
  265. const confirmation = await solanaConnection.confirmTransaction(
  266. {
  267. signature,
  268. lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
  269. blockhash: latestBlockhash.blockhash,
  270. },
  271. COMMITMENT_LEVEL,
  272. );
  273. if (!confirmation.value.err) {
  274. logger.info(`-------------------🟢------------------- `);
  275. logger.info(
  276. {
  277. mint: accountData.baseMint,
  278. signature,
  279. url: `https://solscan.io/tx/${signature}?cluster=${NETWORK}`,
  280. },
  281. `Confirmed buy tx`,
  282. );
  283. } else {
  284. logger.debug(confirmation.value.err);
  285. logger.info({ mint: accountData.baseMint, signature }, `Error confirming buy tx`);
  286. }
  287. } catch (e) {
  288. logger.debug(e);
  289. processingToken = false;
  290. logger.error({ mint: accountData.baseMint }, `Failed to buy token`);
  291. }
  292. }
  293. async function sell(accountId: PublicKey, mint: PublicKey, amount: BigNumberish): Promise<void> {
  294. let sold = false;
  295. let retries = 0;
  296. if (AUTO_SELL_DELAY > 0) {
  297. await new Promise((resolve) => setTimeout(resolve, AUTO_SELL_DELAY));
  298. }
  299. do {
  300. try {
  301. const tokenAccount = existingTokenAccounts.get(mint.toString());
  302. if (!tokenAccount) {
  303. return;
  304. }
  305. if (!tokenAccount.poolKeys) {
  306. logger.warn({ mint }, 'No pool keys found');
  307. return;
  308. }
  309. if (amount === 0) {
  310. logger.info(
  311. {
  312. mint: tokenAccount.mint,
  313. },
  314. `Empty balance, can't sell`,
  315. );
  316. return;
  317. }
  318. const { innerTransaction } = Liquidity.makeSwapFixedInInstruction(
  319. {
  320. poolKeys: tokenAccount.poolKeys!,
  321. userKeys: {
  322. tokenAccountOut: quoteTokenAssociatedAddress,
  323. tokenAccountIn: tokenAccount.address,
  324. owner: wallet.publicKey,
  325. },
  326. amountIn: amount,
  327. minAmountOut: 0,
  328. },
  329. tokenAccount.poolKeys!.version,
  330. );
  331. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  332. commitment: COMMITMENT_LEVEL,
  333. });
  334. const messageV0 = new TransactionMessage({
  335. payerKey: wallet.publicKey,
  336. recentBlockhash: latestBlockhash.blockhash,
  337. instructions: [
  338. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 421197 }),
  339. ComputeBudgetProgram.setComputeUnitLimit({ units: 101337 }),
  340. ...innerTransaction.instructions,
  341. createCloseAccountInstruction(tokenAccount.address, wallet.publicKey, wallet.publicKey),
  342. ],
  343. }).compileToV0Message();
  344. const transaction = new VersionedTransaction(messageV0);
  345. transaction.sign([wallet, ...innerTransaction.signers]);
  346. const signature = await solanaConnection.sendRawTransaction(transaction.serialize(), {
  347. preflightCommitment: COMMITMENT_LEVEL,
  348. });
  349. logger.info({ mint, signature }, `Sent sell tx`);
  350. const confirmation = await solanaConnection.confirmTransaction(
  351. {
  352. signature,
  353. lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
  354. blockhash: latestBlockhash.blockhash,
  355. },
  356. COMMITMENT_LEVEL,
  357. );
  358. if (confirmation.value.err) {
  359. logger.debug(confirmation.value.err);
  360. logger.info({ mint, signature }, `Error confirming sell tx`);
  361. continue;
  362. }
  363. logger.info(`-------------------🔴------------------- `);
  364. logger.info(
  365. {
  366. dex: `https://dexscreener.com/solana/${mint}?maker=${wallet.publicKey}`,
  367. mint,
  368. signature,
  369. url: `https://solscan.io/tx/${signature}?cluster=${NETWORK}`,
  370. },
  371. `Confirmed sell tx`,
  372. );
  373. sold = true;
  374. processingToken = false;
  375. } catch (e: any) {
  376. // wait for a bit before retrying
  377. await new Promise((resolve) => setTimeout(resolve, 100));
  378. retries++;
  379. logger.debug(e);
  380. logger.error({ mint }, `Failed to sell token, retry: ${retries}/${MAX_SELL_RETRIES}`);
  381. }
  382. } while (!sold && retries < MAX_SELL_RETRIES);
  383. processingToken = false;
  384. }
  385. function loadSnipeList() {
  386. if (!USE_SNIPE_LIST) {
  387. return;
  388. }
  389. const count = snipeList.length;
  390. const data = fs.readFileSync(path.join(__dirname, 'snipe-list.txt'), 'utf-8');
  391. snipeList = data
  392. .split('\n')
  393. .map((a) => a.trim())
  394. .filter((a) => a);
  395. if (snipeList.length != count) {
  396. logger.info(`Loaded snipe list: ${snipeList.length}`);
  397. }
  398. }
  399. function shouldBuy(key: string): boolean {
  400. logger.info(`-------------------🤖🔧------------------- `);
  401. logger.info(`Processing token: ${processingToken}`)
  402. return USE_SNIPE_LIST ? snipeList.includes(key) : ONE_TOKEN_AT_A_TIME ? !processingToken : true
  403. }
  404. const runListener = async () => {
  405. await init();
  406. const runTimestamp = Math.floor(new Date().getTime() / 1000);
  407. const raydiumSubscriptionId = solanaConnection.onProgramAccountChange(
  408. RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
  409. async (updatedAccountInfo) => {
  410. const key = updatedAccountInfo.accountId.toString();
  411. const poolState = LIQUIDITY_STATE_LAYOUT_V4.decode(updatedAccountInfo.accountInfo.data);
  412. const poolOpenTime = parseInt(poolState.poolOpenTime.toString());
  413. const existing = existingLiquidityPools.has(key);
  414. if (poolOpenTime > runTimestamp && !existing) {
  415. existingLiquidityPools.add(key);
  416. const _ = processRaydiumPool(updatedAccountInfo.accountId, poolState);
  417. }
  418. },
  419. COMMITMENT_LEVEL,
  420. [
  421. { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
  422. {
  423. memcmp: {
  424. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'),
  425. bytes: quoteToken.mint.toBase58(),
  426. },
  427. },
  428. {
  429. memcmp: {
  430. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'),
  431. bytes: OPENBOOK_PROGRAM_ID.toBase58(),
  432. },
  433. },
  434. {
  435. memcmp: {
  436. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'),
  437. bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]),
  438. },
  439. },
  440. ],
  441. );
  442. const openBookSubscriptionId = solanaConnection.onProgramAccountChange(
  443. OPENBOOK_PROGRAM_ID,
  444. async (updatedAccountInfo) => {
  445. const key = updatedAccountInfo.accountId.toString();
  446. const existing = existingOpenBookMarkets.has(key);
  447. if (!existing) {
  448. existingOpenBookMarkets.add(key);
  449. const _ = processOpenBookMarket(updatedAccountInfo);
  450. }
  451. },
  452. COMMITMENT_LEVEL,
  453. [
  454. { dataSize: MARKET_STATE_LAYOUT_V3.span },
  455. {
  456. memcmp: {
  457. offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'),
  458. bytes: quoteToken.mint.toBase58(),
  459. },
  460. },
  461. ],
  462. );
  463. if (AUTO_SELL) {
  464. const walletSubscriptionId = solanaConnection.onProgramAccountChange(
  465. TOKEN_PROGRAM_ID,
  466. async (updatedAccountInfo) => {
  467. const accountData = AccountLayout.decode(updatedAccountInfo.accountInfo!.data);
  468. if (updatedAccountInfo.accountId.equals(quoteTokenAssociatedAddress)) {
  469. return;
  470. }
  471. const _ = sell(updatedAccountInfo.accountId, accountData.mint, accountData.amount);
  472. },
  473. COMMITMENT_LEVEL,
  474. [
  475. {
  476. dataSize: 165,
  477. },
  478. {
  479. memcmp: {
  480. offset: 32,
  481. bytes: wallet.publicKey.toBase58(),
  482. },
  483. },
  484. ],
  485. );
  486. logger.info(`Listening for wallet changes: ${walletSubscriptionId}`);
  487. }
  488. logger.info(`Listening for raydium changes: ${raydiumSubscriptionId}`);
  489. logger.info(`Listening for open book changes: ${openBookSubscriptionId}`);
  490. logger.info('------------------- 🚀 ---------------------');
  491. logger.info('Bot is running! Press CTRL + C to stop it.');
  492. logger.info('------------------- 🚀 ---------------------');
  493. if (USE_SNIPE_LIST) {
  494. setInterval(loadSnipeList, SNIPE_LIST_REFRESH_INTERVAL);
  495. }
  496. };
  497. runListener();