buy.ts 7.3 KB

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