buy.ts 7.6 KB

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