buy.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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(
  60. 'RPC_WEBSOCKET_ENDPOINT',
  61. logger,
  62. );
  63. const solanaConnection = new Connection(RPC_ENDPOINT, {
  64. wsEndpoint: RPC_WEBSOCKET_ENDPOINT,
  65. });
  66. export type MinimalTokenAccountData = {
  67. mint: PublicKey;
  68. address: PublicKey;
  69. };
  70. let existingLiquidityPools: Set<string> = new Set<string>();
  71. let existingOpenBookMarkets: Set<string> = new Set<string>();
  72. let existingTokenAccounts: Map<string, MinimalTokenAccountData> = new Map<
  73. string,
  74. MinimalTokenAccountData
  75. >();
  76. let wallet: Keypair;
  77. let usdcTokenKey: PublicKey;
  78. const PRIVATE_KEY = retrieveEnvVariable('PRIVATE_KEY', logger);
  79. async function init(): Promise<void> {
  80. wallet = Keypair.fromSecretKey(bs58.decode(PRIVATE_KEY));
  81. logger.info(`Wallet Address: ${wallet.publicKey.toString()}`);
  82. const allLiquidityPools = await getAllAccountsV4(solanaConnection);
  83. existingLiquidityPools = new Set(
  84. allLiquidityPools.map((p) => p.id.toString()),
  85. );
  86. const allMarkets = await getAllMarketsV3(solanaConnection);
  87. existingOpenBookMarkets = new Set(allMarkets.map((p) => p.id.toString()));
  88. const tokenAccounts = await getTokenAccounts(
  89. solanaConnection,
  90. wallet.publicKey,
  91. );
  92. logger.info(`Total USDC markets ${existingOpenBookMarkets.size}`);
  93. logger.info(`Total USDC pools ${existingLiquidityPools.size}`);
  94. tokenAccounts.forEach((ta) => {
  95. existingTokenAccounts.set(ta.accountInfo.mint.toString(), <
  96. MinimalTokenAccountData
  97. >{
  98. mint: ta.accountInfo.mint,
  99. address: ta.pubkey,
  100. });
  101. });
  102. const token = tokenAccounts.find(
  103. (acc) => acc.accountInfo.mint.toString() === USDC_TOKEN_ID.toString(),
  104. )!;
  105. usdcTokenKey = token!.pubkey;
  106. }
  107. export async function processRaydiumPool(updatedAccountInfo: KeyedAccountInfo) {
  108. let accountData: LiquidityStateV4 | undefined;
  109. try {
  110. accountData = LIQUIDITY_STATE_LAYOUT_V4.decode(
  111. updatedAccountInfo.accountInfo.data,
  112. );
  113. await buy(updatedAccountInfo.accountId, accountData);
  114. } catch (e) {
  115. logger.error({ ...accountData, error: e }, `Failed to process pool`);
  116. }
  117. }
  118. export async function processOpenBookMarket(
  119. updatedAccountInfo: KeyedAccountInfo,
  120. ) {
  121. let accountData: any;
  122. try {
  123. accountData = MARKET_STATE_LAYOUT_V2.decode(
  124. updatedAccountInfo.accountInfo.data,
  125. );
  126. // to be competitive, we create token account before buying the token...
  127. if (existingTokenAccounts.has(accountData.baseMint.toString())) {
  128. return;
  129. }
  130. const destinationAccount = await getOrCreateAssociatedTokenAccount(
  131. solanaConnection,
  132. wallet,
  133. accountData.baseMint,
  134. wallet.publicKey,
  135. );
  136. existingTokenAccounts.set(accountData.baseMint.toString(), <
  137. MinimalTokenAccountData
  138. >{
  139. address: destinationAccount.address,
  140. mint: destinationAccount.mint,
  141. });
  142. logger.info(
  143. accountData,
  144. `Created destination account: ${destinationAccount.address}`,
  145. );
  146. } catch (e) {
  147. logger.error({ ...accountData, error: e }, `Failed to process market`);
  148. }
  149. }
  150. async function buy(accountId: PublicKey, accountData: any): Promise<void> {
  151. const [poolKeys, latestBlockhash] = await Promise.all([
  152. getAccountPoolKeysFromAccountDataV4(
  153. solanaConnection,
  154. accountId,
  155. accountData,
  156. ),
  157. solanaConnection.getLatestBlockhash({ commitment: 'processed' }),
  158. ]);
  159. const baseMint = poolKeys.baseMint.toString();
  160. const tokenAccountOut =
  161. existingTokenAccounts && existingTokenAccounts.get(baseMint)?.address;
  162. if (!tokenAccountOut) {
  163. logger.info(`No token account for ${baseMint}`);
  164. return;
  165. }
  166. const { innerTransaction, address } = Liquidity.makeSwapFixedInInstruction(
  167. {
  168. poolKeys,
  169. userKeys: {
  170. tokenAccountIn: usdcTokenKey,
  171. tokenAccountOut: tokenAccountOut,
  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. memcmp: {
  236. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'),
  237. bytes: '14421D35quxec7'
  238. },
  239. },
  240. ],
  241. );
  242. const openBookSubscriptionId = solanaConnection.onProgramAccountChange(
  243. OPENBOOK_PROGRAM_ID,
  244. async (updatedAccountInfo) => {
  245. const existing = existingOpenBookMarkets.has(
  246. updatedAccountInfo.accountId.toString(),
  247. );
  248. if (!existing) {
  249. existingOpenBookMarkets.add(updatedAccountInfo.accountId.toString());
  250. const _ = processOpenBookMarket(updatedAccountInfo);
  251. }
  252. },
  253. 'processed',
  254. [
  255. { dataSize: MARKET_STATE_LAYOUT_V2.span },
  256. {
  257. memcmp: {
  258. offset: MARKET_STATE_LAYOUT_V2.offsetOf('quoteMint'),
  259. bytes: USDC_TOKEN_ID.toBase58(),
  260. },
  261. },
  262. ],
  263. );
  264. logger.info(`Listening for raydium changes: ${raydiumSubscriptionId}`);
  265. logger.info(`Listening for open book changes: ${openBookSubscriptionId}`);
  266. };
  267. runListener();