buy.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. return;
  157. }
  158. }
  159. if (CHECK_IF_MINT_IS_RENOUNCED) {
  160. const mintOption = await checkMintable(poolState.baseMint);
  161. if (mintOption !== true) {
  162. logger.warn({ mint: poolState.baseMint }, 'Skipping, owner can mint tokens!');
  163. return;
  164. }
  165. }
  166. await buy(id, poolState);
  167. }
  168. export async function checkMintable(vault: PublicKey): Promise<boolean | undefined> {
  169. try {
  170. let { data } = (await solanaConnection.getAccountInfo(vault)) || {};
  171. if (!data) {
  172. return;
  173. }
  174. const deserialize = MintLayout.decode(data);
  175. return deserialize.mintAuthorityOption === 0;
  176. } catch (e) {
  177. logger.debug(e);
  178. logger.error({ mint: vault }, `Failed to check if mint is renounced`);
  179. }
  180. }
  181. export async function processOpenBookMarket(updatedAccountInfo: KeyedAccountInfo) {
  182. let accountData: MarketStateV3 | undefined;
  183. try {
  184. accountData = MARKET_STATE_LAYOUT_V3.decode(updatedAccountInfo.accountInfo.data);
  185. // to be competitive, we collect market data before buying the token...
  186. if (existingTokenAccounts.has(accountData.baseMint.toString())) {
  187. return;
  188. }
  189. saveTokenAccount(accountData.baseMint, accountData);
  190. } catch (e) {
  191. logger.debug(e);
  192. logger.error({ mint: accountData?.baseMint }, `Failed to process market`);
  193. }
  194. }
  195. async function buy(accountId: PublicKey, accountData: LiquidityStateV4): Promise<void> {
  196. try {
  197. let tokenAccount = existingTokenAccounts.get(accountData.baseMint.toString());
  198. if (!tokenAccount) {
  199. // it's possible that we didn't have time to fetch open book data
  200. const market = await getMinimalMarketV3(solanaConnection, accountData.marketId, COMMITMENT_LEVEL);
  201. tokenAccount = saveTokenAccount(accountData.baseMint, market);
  202. }
  203. tokenAccount.poolKeys = createPoolKeys(accountId, accountData, tokenAccount.market!);
  204. const { innerTransaction } = Liquidity.makeSwapFixedInInstruction(
  205. {
  206. poolKeys: tokenAccount.poolKeys,
  207. userKeys: {
  208. tokenAccountIn: quoteTokenAssociatedAddress,
  209. tokenAccountOut: tokenAccount.address,
  210. owner: wallet.publicKey,
  211. },
  212. amountIn: quoteAmount.raw,
  213. minAmountOut: 0,
  214. },
  215. tokenAccount.poolKeys.version,
  216. );
  217. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  218. commitment: COMMITMENT_LEVEL,
  219. });
  220. const messageV0 = new TransactionMessage({
  221. payerKey: wallet.publicKey,
  222. recentBlockhash: latestBlockhash.blockhash,
  223. instructions: [
  224. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 421197 }),
  225. ComputeBudgetProgram.setComputeUnitLimit({ units: 101337 }),
  226. createAssociatedTokenAccountIdempotentInstruction(
  227. wallet.publicKey,
  228. tokenAccount.address,
  229. wallet.publicKey,
  230. accountData.baseMint,
  231. ),
  232. ...innerTransaction.instructions,
  233. ],
  234. }).compileToV0Message();
  235. const transaction = new VersionedTransaction(messageV0);
  236. transaction.sign([wallet, ...innerTransaction.signers]);
  237. const signature = await solanaConnection.sendRawTransaction(transaction.serialize(), {
  238. preflightCommitment: COMMITMENT_LEVEL,
  239. });
  240. logger.info({ mint: accountData.baseMint, signature }, `Sent buy tx`);
  241. processingToken = true;
  242. const confirmation = await solanaConnection.confirmTransaction(
  243. {
  244. signature,
  245. lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
  246. blockhash: latestBlockhash.blockhash,
  247. },
  248. COMMITMENT_LEVEL,
  249. );
  250. if (!confirmation.value.err) {
  251. logger.info(
  252. {
  253. mint: accountData.baseMint,
  254. signature,
  255. url: `https://solscan.io/tx/${signature}?cluster=${NETWORK}`,
  256. },
  257. `Confirmed buy tx`,
  258. );
  259. } else {
  260. logger.debug(confirmation.value.err);
  261. logger.info({ mint: accountData.baseMint, signature }, `Error confirming buy tx`);
  262. }
  263. } catch (e) {
  264. logger.debug(e);
  265. processingToken = false;
  266. logger.error({ mint: accountData.baseMint }, `Failed to buy token`);
  267. }
  268. }
  269. async function sell(accountId: PublicKey, mint: PublicKey, amount: BigNumberish): Promise<void> {
  270. let sold = false;
  271. let retries = 0;
  272. if (AUTO_SELL_DELAY > 0) {
  273. await new Promise((resolve) => setTimeout(resolve, AUTO_SELL_DELAY));
  274. }
  275. do {
  276. try {
  277. const tokenAccount = existingTokenAccounts.get(mint.toString());
  278. if (!tokenAccount) {
  279. return;
  280. }
  281. if (!tokenAccount.poolKeys) {
  282. logger.warn({ mint }, 'No pool keys found');
  283. return;
  284. }
  285. if (amount === 0) {
  286. logger.info(
  287. {
  288. mint: tokenAccount.mint,
  289. },
  290. `Empty balance, can't sell`,
  291. );
  292. return;
  293. }
  294. const { innerTransaction } = Liquidity.makeSwapFixedInInstruction(
  295. {
  296. poolKeys: tokenAccount.poolKeys!,
  297. userKeys: {
  298. tokenAccountOut: quoteTokenAssociatedAddress,
  299. tokenAccountIn: tokenAccount.address,
  300. owner: wallet.publicKey,
  301. },
  302. amountIn: amount,
  303. minAmountOut: 0,
  304. },
  305. tokenAccount.poolKeys!.version,
  306. );
  307. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  308. commitment: COMMITMENT_LEVEL,
  309. });
  310. const messageV0 = new TransactionMessage({
  311. payerKey: wallet.publicKey,
  312. recentBlockhash: latestBlockhash.blockhash,
  313. instructions: [
  314. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 421197 }),
  315. ComputeBudgetProgram.setComputeUnitLimit({ units: 101337 }),
  316. ...innerTransaction.instructions,
  317. createCloseAccountInstruction(tokenAccount.address, wallet.publicKey, wallet.publicKey),
  318. ],
  319. }).compileToV0Message();
  320. const transaction = new VersionedTransaction(messageV0);
  321. transaction.sign([wallet, ...innerTransaction.signers]);
  322. const signature = await solanaConnection.sendRawTransaction(transaction.serialize(), {
  323. preflightCommitment: COMMITMENT_LEVEL,
  324. });
  325. logger.info({ mint, signature }, `Sent sell tx`);
  326. const confirmation = await solanaConnection.confirmTransaction(
  327. {
  328. signature,
  329. lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
  330. blockhash: latestBlockhash.blockhash,
  331. },
  332. COMMITMENT_LEVEL,
  333. );
  334. if (confirmation.value.err) {
  335. logger.debug(confirmation.value.err);
  336. logger.info({ mint, signature }, `Error confirming sell tx`);
  337. continue;
  338. }
  339. logger.info(
  340. {
  341. dex: `https://dexscreener.com/solana/${mint}?maker=${wallet.publicKey}`,
  342. mint,
  343. signature,
  344. url: `https://solscan.io/tx/${signature}?cluster=${NETWORK}`,
  345. },
  346. `Confirmed sell tx`,
  347. );
  348. sold = true;
  349. processingToken = false;
  350. } catch (e: any) {
  351. // wait for a bit before retrying
  352. await new Promise((resolve) => setTimeout(resolve, 100));
  353. retries++;
  354. logger.debug(e);
  355. logger.error({ mint }, `Failed to sell token, retry: ${retries}/${MAX_SELL_RETRIES}`);
  356. }
  357. } while (!sold && retries < MAX_SELL_RETRIES);
  358. processingToken = false;
  359. }
  360. function loadSnipeList() {
  361. if (!USE_SNIPE_LIST) {
  362. return;
  363. }
  364. const count = snipeList.length;
  365. const data = fs.readFileSync(path.join(__dirname, 'snipe-list.txt'), 'utf-8');
  366. snipeList = data
  367. .split('\n')
  368. .map((a) => a.trim())
  369. .filter((a) => a);
  370. if (snipeList.length != count) {
  371. logger.info(`Loaded snipe list: ${snipeList.length}`);
  372. }
  373. }
  374. function shouldBuy(key: string): boolean {
  375. logger.info(processingToken, 'Is processing token buy')
  376. return USE_SNIPE_LIST ? snipeList.includes(key) : ONE_TOKEN_AT_A_TIME ? !processingToken : true
  377. }
  378. const runListener = async () => {
  379. await init();
  380. const runTimestamp = Math.floor(new Date().getTime() / 1000);
  381. const raydiumSubscriptionId = solanaConnection.onProgramAccountChange(
  382. RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
  383. async (updatedAccountInfo) => {
  384. const key = updatedAccountInfo.accountId.toString();
  385. const poolState = LIQUIDITY_STATE_LAYOUT_V4.decode(updatedAccountInfo.accountInfo.data);
  386. const poolOpenTime = parseInt(poolState.poolOpenTime.toString());
  387. const existing = existingLiquidityPools.has(key);
  388. if (poolOpenTime > runTimestamp && !existing) {
  389. existingLiquidityPools.add(key);
  390. const _ = processRaydiumPool(updatedAccountInfo.accountId, poolState);
  391. }
  392. },
  393. COMMITMENT_LEVEL,
  394. [
  395. { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
  396. {
  397. memcmp: {
  398. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'),
  399. bytes: quoteToken.mint.toBase58(),
  400. },
  401. },
  402. {
  403. memcmp: {
  404. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'),
  405. bytes: OPENBOOK_PROGRAM_ID.toBase58(),
  406. },
  407. },
  408. {
  409. memcmp: {
  410. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'),
  411. bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]),
  412. },
  413. },
  414. ],
  415. );
  416. const openBookSubscriptionId = solanaConnection.onProgramAccountChange(
  417. OPENBOOK_PROGRAM_ID,
  418. async (updatedAccountInfo) => {
  419. const key = updatedAccountInfo.accountId.toString();
  420. const existing = existingOpenBookMarkets.has(key);
  421. if (!existing) {
  422. existingOpenBookMarkets.add(key);
  423. const _ = processOpenBookMarket(updatedAccountInfo);
  424. }
  425. },
  426. COMMITMENT_LEVEL,
  427. [
  428. { dataSize: MARKET_STATE_LAYOUT_V3.span },
  429. {
  430. memcmp: {
  431. offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'),
  432. bytes: quoteToken.mint.toBase58(),
  433. },
  434. },
  435. ],
  436. );
  437. if (AUTO_SELL) {
  438. const walletSubscriptionId = solanaConnection.onProgramAccountChange(
  439. TOKEN_PROGRAM_ID,
  440. async (updatedAccountInfo) => {
  441. const accountData = AccountLayout.decode(updatedAccountInfo.accountInfo!.data);
  442. if (updatedAccountInfo.accountId.equals(quoteTokenAssociatedAddress)) {
  443. return;
  444. }
  445. const _ = sell(updatedAccountInfo.accountId, accountData.mint, accountData.amount);
  446. },
  447. COMMITMENT_LEVEL,
  448. [
  449. {
  450. dataSize: 165,
  451. },
  452. {
  453. memcmp: {
  454. offset: 32,
  455. bytes: wallet.publicKey.toBase58(),
  456. },
  457. },
  458. ],
  459. );
  460. logger.info(`Listening for wallet changes: ${walletSubscriptionId}`);
  461. }
  462. logger.info(`Listening for raydium changes: ${raydiumSubscriptionId}`);
  463. logger.info(`Listening for open book changes: ${openBookSubscriptionId}`);
  464. logger.info('------------------- 🚀 ---------------------');
  465. logger.info('Bot is running! Press CTRL + C to stop it.');
  466. logger.info('------------------- 🚀 ---------------------');
  467. if (USE_SNIPE_LIST) {
  468. setInterval(loadSnipeList, SNIPE_LIST_REFRESH_INTERVAL);
  469. }
  470. };
  471. runListener();