buy.ts 16 KB

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