buy.ts 7.3 KB

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