buy.ts 14 KB

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