buy.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import {
  2. Liquidity,
  3. LIQUIDITY_STATE_LAYOUT_V4,
  4. LiquidityStateV4,
  5. MARKET_STATE_LAYOUT_V2,
  6. } from '@raydium-io/raydium-sdk';
  7. import { getOrCreateAssociatedTokenAccount } from '@solana/spl-token';
  8. import {
  9. Keypair,
  10. Connection,
  11. PublicKey,
  12. ComputeBudgetProgram,
  13. KeyedAccountInfo,
  14. TransactionMessage,
  15. VersionedTransaction,
  16. } from '@solana/web3.js';
  17. import {
  18. getAllAccountsV4,
  19. getTokenAccounts,
  20. getAccountPoolKeysFromAccountDataV4,
  21. RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
  22. OPENBOOK_PROGRAM_ID,
  23. } from './liquidity';
  24. import { retry } from './utils';
  25. import { USDC_AMOUNT, USDC_TOKEN_ID } from './common';
  26. import { getAllMarketsV3 } from './market';
  27. import pino from 'pino';
  28. import dotenv from 'dotenv';
  29. import bs58 from "bs58";
  30. dotenv.config();
  31. const transport = pino.transport({
  32. targets: [
  33. /*
  34. {
  35. level: 'trace',
  36. target: 'pino/file',
  37. options: {
  38. destination: 'buy.log',
  39. },
  40. },
  41. */
  42. {
  43. level: 'trace',
  44. target: 'pino-pretty',
  45. options: {},
  46. },
  47. ],
  48. });
  49. export const logger = pino(
  50. {
  51. redact: ['poolKeys'],
  52. serializers: {
  53. error: pino.stdSerializers.err
  54. },
  55. base: undefined,
  56. },
  57. transport,
  58. );
  59. const network = 'mainnet-beta';
  60. const solanaConnection = new Connection(
  61. 'ENTER RPC ENDPOINT HERE',
  62. {
  63. wsEndpoint:
  64. 'ENTER RPC WEBSOCKET ENDPOINT HERE',
  65. },
  66. );
  67. export type MinimalTokenAccountData = {
  68. mint: PublicKey;
  69. address: PublicKey;
  70. };
  71. let existingLiquidityPools: Set<string> = new Set<string>();
  72. let existingOpenBookMarkets: Set<string> = new Set<string>();
  73. let existingTokenAccounts: Map<string, MinimalTokenAccountData> = new Map<
  74. string,
  75. MinimalTokenAccountData
  76. >();
  77. let wallet: Keypair;
  78. let usdcTokenKey: PublicKey;
  79. const PRIVATE_KEY: string = process.env.PRIVATE_KEY || '';
  80. async function init(): Promise<void> {
  81. if (!PRIVATE_KEY) {
  82. console.error('PRIVATE_KEY is not set');
  83. process.exit(1);
  84. }
  85. wallet = Keypair.fromSecretKey(bs58.decode(PRIVATE_KEY));
  86. logger.info(`Wallet Address: ${wallet.publicKey.toString()}`);
  87. const allLiquidityPools = await getAllAccountsV4(solanaConnection);
  88. existingLiquidityPools = new Set(
  89. allLiquidityPools.map((p) => p.id.toString()),
  90. );
  91. const allMarkets = await getAllMarketsV3(solanaConnection);
  92. existingOpenBookMarkets = new Set(allMarkets.map((p) => p.id.toString()));
  93. const tokenAccounts = await getTokenAccounts(
  94. solanaConnection,
  95. wallet.publicKey,
  96. );
  97. logger.info(`Total USDC markets ${existingOpenBookMarkets.size}`);
  98. logger.info(`Total USDC pools ${existingLiquidityPools.size}`);
  99. tokenAccounts.forEach((ta) => {
  100. existingTokenAccounts.set(ta.accountInfo.mint.toString(), <
  101. MinimalTokenAccountData
  102. >{
  103. mint: ta.accountInfo.mint,
  104. address: ta.pubkey,
  105. });
  106. });
  107. const token = tokenAccounts.find(
  108. (acc) => acc.accountInfo.mint.toString() === USDC_TOKEN_ID.toString(),
  109. )!;
  110. usdcTokenKey = token!.pubkey;
  111. }
  112. export async function processRaydiumPool(updatedAccountInfo: KeyedAccountInfo) {
  113. let accountData: LiquidityStateV4 | undefined;
  114. try {
  115. accountData = LIQUIDITY_STATE_LAYOUT_V4.decode(
  116. updatedAccountInfo.accountInfo.data,
  117. );
  118. await buy(updatedAccountInfo.accountId, accountData);
  119. } catch (e) {
  120. logger.error({ ...accountData, error: e }, `Failed to process pool`);
  121. }
  122. }
  123. export async function processOpenBookMarket(
  124. updatedAccountInfo: KeyedAccountInfo,
  125. ) {
  126. let accountData: any;
  127. try {
  128. accountData = MARKET_STATE_LAYOUT_V2.decode(
  129. updatedAccountInfo.accountInfo.data,
  130. );
  131. // to be competitive, we create token account before buying the token...
  132. if (existingTokenAccounts.has(accountData.baseMint.toString())) {
  133. return;
  134. }
  135. const destinationAccount = await getOrCreateAssociatedTokenAccount(
  136. solanaConnection,
  137. wallet,
  138. accountData.baseMint,
  139. wallet.publicKey,
  140. );
  141. existingTokenAccounts.set(accountData.baseMint.toString(), <
  142. MinimalTokenAccountData
  143. >{
  144. address: destinationAccount.address,
  145. mint: destinationAccount.mint,
  146. });
  147. logger.info(
  148. accountData,
  149. `Created destination account: ${destinationAccount.address}`,
  150. );
  151. } catch (e) {
  152. logger.error({ ...accountData, error: e }, `Failed to process market`);
  153. }
  154. }
  155. async function buy(accountId: PublicKey, accountData: any): Promise<void> {
  156. const [poolKeys, latestBlockhash] = await Promise.all([
  157. getAccountPoolKeysFromAccountDataV4(
  158. solanaConnection,
  159. accountId,
  160. accountData,
  161. ),
  162. solanaConnection.getLatestBlockhash({ commitment: 'processed' }),
  163. ]);
  164. const { innerTransaction, address } = Liquidity.makeSwapFixedInInstruction(
  165. {
  166. poolKeys,
  167. userKeys: {
  168. tokenAccountIn: usdcTokenKey,
  169. tokenAccountOut: existingTokenAccounts.get(
  170. poolKeys.baseMint.toString(),
  171. )!.address,
  172. owner: wallet.publicKey,
  173. },
  174. amountIn: USDC_AMOUNT * 1000000,
  175. minAmountOut: 0,
  176. },
  177. poolKeys.version,
  178. );
  179. const messageV0 = new TransactionMessage({
  180. payerKey: wallet.publicKey,
  181. recentBlockhash: latestBlockhash.blockhash,
  182. instructions: [
  183. ComputeBudgetProgram.setComputeUnitLimit({ units: 400000 }),
  184. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 30000 }),
  185. ...innerTransaction.instructions,
  186. ],
  187. }).compileToV0Message();
  188. const transaction = new VersionedTransaction(messageV0);
  189. transaction.sign([wallet, ...innerTransaction.signers]);
  190. const rawTransaction = transaction.serialize();
  191. const signature = await retry(
  192. () =>
  193. solanaConnection.sendRawTransaction(rawTransaction, {
  194. skipPreflight: true,
  195. }),
  196. { retryIntervalMs: 10, retries: 50 }, // TODO handle retries more efficiently
  197. );
  198. logger.info(
  199. {
  200. ...accountData,
  201. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  202. },
  203. 'Buy',
  204. );
  205. }
  206. const runListener = async () => {
  207. await init();
  208. const raydiumSubscriptionId = solanaConnection.onProgramAccountChange(
  209. RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
  210. async (updatedAccountInfo) => {
  211. const existing = existingLiquidityPools.has(
  212. updatedAccountInfo.accountId.toString(),
  213. );
  214. if (!existing) {
  215. existingLiquidityPools.add(updatedAccountInfo.accountId.toString());
  216. const _ = processRaydiumPool(updatedAccountInfo);
  217. }
  218. },
  219. 'processed',
  220. [
  221. { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
  222. {
  223. memcmp: {
  224. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'),
  225. bytes: USDC_TOKEN_ID.toBase58(),
  226. },
  227. },
  228. {
  229. memcmp: {
  230. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'),
  231. bytes: OPENBOOK_PROGRAM_ID.toBase58(),
  232. },
  233. },
  234. ],
  235. );
  236. const openBookSubscriptionId = solanaConnection.onProgramAccountChange(
  237. OPENBOOK_PROGRAM_ID,
  238. async (updatedAccountInfo) => {
  239. const existing = existingOpenBookMarkets.has(
  240. updatedAccountInfo.accountId.toString(),
  241. );
  242. if (!existing) {
  243. existingOpenBookMarkets.add(updatedAccountInfo.accountId.toString());
  244. const _ = processOpenBookMarket(updatedAccountInfo);
  245. }
  246. },
  247. 'processed',
  248. [
  249. { dataSize: MARKET_STATE_LAYOUT_V2.span },
  250. {
  251. memcmp: {
  252. offset: MARKET_STATE_LAYOUT_V2.offsetOf('quoteMint'),
  253. bytes: USDC_TOKEN_ID.toBase58(),
  254. },
  255. },
  256. ],
  257. );
  258. logger.info(`Listening for raydium changes: ${raydiumSubscriptionId}`);
  259. logger.info(`Listening for open book changes: ${openBookSubscriptionId}`);
  260. };
  261. runListener();