buy.ts 6.9 KB

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