buy.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. import {
  2. Liquidity,
  3. LIQUIDITY_STATE_LAYOUT_V4,
  4. LiquidityPoolKeys,
  5. LiquidityStateV4,
  6. MARKET_STATE_LAYOUT_V2,
  7. MARKET_STATE_LAYOUT_V3,
  8. MarketStateV3,
  9. Token,
  10. TokenAmount,
  11. } from '@raydium-io/raydium-sdk';
  12. import {
  13. createAssociatedTokenAccountIdempotentInstruction,
  14. getAssociatedTokenAddressSync,
  15. TOKEN_PROGRAM_ID,
  16. } from '@solana/spl-token';
  17. import {
  18. Keypair,
  19. Connection,
  20. PublicKey,
  21. ComputeBudgetProgram,
  22. KeyedAccountInfo,
  23. TransactionMessage,
  24. VersionedTransaction,
  25. Commitment,
  26. } from '@solana/web3.js';
  27. import {
  28. getAllAccountsV4,
  29. getTokenAccounts,
  30. RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
  31. OPENBOOK_PROGRAM_ID,
  32. createPoolKeys,
  33. } from './liquidity';
  34. import { retrieveEnvVariable } from './utils';
  35. import { getAllMarketsV3, MinimalMarketLayoutV3 } from './market';
  36. import pino from 'pino';
  37. import bs58 from 'bs58';
  38. import * as fs from 'fs';
  39. import * as path from 'path';
  40. const transport = pino.transport({
  41. targets: [
  42. /*
  43. {
  44. level: 'trace',
  45. target: 'pino/file',
  46. options: {
  47. destination: 'buy.log',
  48. },
  49. },
  50. */
  51. {
  52. level: 'trace',
  53. target: 'pino-pretty',
  54. options: {},
  55. },
  56. ],
  57. });
  58. export const logger = pino(
  59. {
  60. redact: ['poolKeys'],
  61. serializers: {
  62. error: pino.stdSerializers.err,
  63. },
  64. base: undefined,
  65. },
  66. transport,
  67. );
  68. const network = 'mainnet-beta';
  69. const RPC_ENDPOINT = retrieveEnvVariable('RPC_ENDPOINT', logger);
  70. const RPC_WEBSOCKET_ENDPOINT = retrieveEnvVariable(
  71. 'RPC_WEBSOCKET_ENDPOINT',
  72. logger,
  73. );
  74. const solanaConnection = new Connection(RPC_ENDPOINT, {
  75. wsEndpoint: RPC_WEBSOCKET_ENDPOINT,
  76. });
  77. export type MinimalTokenAccountData = {
  78. mint: PublicKey;
  79. address: PublicKey;
  80. poolKeys?: LiquidityPoolKeys;
  81. market?: MinimalMarketLayoutV3;
  82. };
  83. let existingLiquidityPools: Set<string> = new Set<string>();
  84. let existingOpenBookMarkets: Set<string> = new Set<string>();
  85. let existingTokenAccounts: Map<string, MinimalTokenAccountData> = new Map<
  86. string,
  87. MinimalTokenAccountData
  88. >();
  89. let wallet: Keypair;
  90. let quoteToken: Token;
  91. let quoteTokenAssociatedAddress: PublicKey;
  92. let quoteAmount: TokenAmount;
  93. let commitment: Commitment = retrieveEnvVariable(
  94. 'COMMITMENT_LEVEL',
  95. logger,
  96. ) as Commitment;
  97. const USE_SNIPE_LIST = retrieveEnvVariable('USE_SNIPE_LIST', logger) === 'true';
  98. const SNIPE_LIST_REFRESH_INTERVAL = Number(
  99. retrieveEnvVariable('SNIPE_LIST_REFRESH_INTERVAL', logger),
  100. );
  101. let snipeList: string[] = [];
  102. async function init(): Promise<void> {
  103. // get wallet
  104. const PRIVATE_KEY = retrieveEnvVariable('PRIVATE_KEY', logger);
  105. wallet = Keypair.fromSecretKey(bs58.decode(PRIVATE_KEY));
  106. logger.info(`Wallet Address: ${wallet.publicKey}`);
  107. // get quote mint and amount
  108. const QUOTE_MINT = retrieveEnvVariable('QUOTE_MINT', logger);
  109. const QUOTE_AMOUNT = retrieveEnvVariable('QUOTE_AMOUNT', logger);
  110. switch (QUOTE_MINT) {
  111. case 'WSOL': {
  112. quoteToken = Token.WSOL;
  113. quoteAmount = new TokenAmount(Token.WSOL, QUOTE_AMOUNT, false);
  114. break;
  115. }
  116. case 'USDC': {
  117. quoteToken = new Token(
  118. TOKEN_PROGRAM_ID,
  119. new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),
  120. 6,
  121. 'USDC',
  122. 'USDC',
  123. );
  124. quoteAmount = new TokenAmount(quoteToken, QUOTE_AMOUNT, false);
  125. break;
  126. }
  127. default: {
  128. throw new Error(
  129. `Unsupported quote mint "${QUOTE_MINT}". Supported values are USDC and WSOL`,
  130. );
  131. }
  132. }
  133. logger.info(
  134. `Script will buy all new tokens using ${QUOTE_MINT}. Amount that will be used to buy each token is: ${quoteAmount.toFixed().toString()}`,
  135. );
  136. // get all existing liquidity pools
  137. const allLiquidityPools = await getAllAccountsV4(
  138. quoteToken.mint,
  139. );
  140. existingLiquidityPools = new Set(
  141. allLiquidityPools.map((p) => p.id.toString()),
  142. );
  143. // get all open-book markets
  144. const allMarkets = await getAllMarketsV3();
  145. existingOpenBookMarkets = new Set(allMarkets.map((p) => p.id.toString()));
  146. logger.info(
  147. `Total ${quoteToken.symbol} markets ${existingOpenBookMarkets.size}`,
  148. );
  149. logger.info(
  150. `Total ${quoteToken.symbol} pools ${existingLiquidityPools.size}`,
  151. );
  152. const tokenAccounts = await getTokenAccounts(
  153. solanaConnection,
  154. wallet.publicKey,
  155. commitment,
  156. );
  157. // check existing wallet for associated token account of quote mint
  158. const tokenAccounts = await getTokenAccounts(
  159. solanaConnection,
  160. wallet.publicKey,
  161. commitment,
  162. );
  163. for (const ta of tokenAccounts) {
  164. existingTokenAccounts.set(ta.accountInfo.mint.toString(), <
  165. MinimalTokenAccountData
  166. >{
  167. mint: ta.accountInfo.mint,
  168. address: ta.pubkey,
  169. });
  170. }
  171. const tokenAccount = tokenAccounts.find(
  172. (acc) => acc.accountInfo.mint.toString() === quoteToken.mint.toString(),
  173. )!;
  174. if (!tokenAccount) {
  175. throw new Error(
  176. `No ${quoteToken.symbol} token account found in wallet: ${wallet.publicKey}`,
  177. );
  178. }
  179. quoteTokenAssociatedAddress = tokenAccount.pubkey;
  180. // load tokens to snipe
  181. loadSnipeList();
  182. }
  183. export async function processRaydiumPool(updatedAccountInfo: KeyedAccountInfo) {
  184. let accountData: LiquidityStateV4 | undefined;
  185. try {
  186. accountData = LIQUIDITY_STATE_LAYOUT_V4.decode(
  187. updatedAccountInfo.accountInfo.data,
  188. );
  189. if (!shouldBuy(accountData.baseMint.toString())) {
  190. return;
  191. }
  192. await buy(updatedAccountInfo.accountId, accountData);
  193. } catch (e) {
  194. logger.error({ ...accountData, error: e }, `Failed to process pool`);
  195. }
  196. }
  197. export async function processOpenBookMarket(
  198. updatedAccountInfo: KeyedAccountInfo,
  199. ) {
  200. let accountData: MarketStateV3 | undefined;
  201. try {
  202. accountData = MARKET_STATE_LAYOUT_V3.decode(
  203. updatedAccountInfo.accountInfo.data,
  204. );
  205. // to be competitive, we collect market data before buying the token...
  206. if (existingTokenAccounts.has(accountData.baseMint.toString())) {
  207. return;
  208. }
  209. const ata = getAssociatedTokenAddressSync(
  210. accountData.baseMint,
  211. wallet.publicKey,
  212. );
  213. existingTokenAccounts.set(accountData.baseMint.toString(), <
  214. MinimalTokenAccountData
  215. >{
  216. address: ata,
  217. mint: accountData.baseMint,
  218. market: <MinimalMarketLayoutV3>{
  219. bids: accountData.bids,
  220. asks: accountData.asks,
  221. eventQueue: accountData.eventQueue,
  222. },
  223. });
  224. } catch (e) {
  225. logger.error({ ...accountData, error: e }, `Failed to process market`);
  226. }
  227. }
  228. async function buy(
  229. accountId: PublicKey,
  230. accountData: LiquidityStateV4,
  231. ): Promise<void> {
  232. const tokenAccount = existingTokenAccounts.get(
  233. accountData.baseMint.toString(),
  234. );
  235. if (!tokenAccount) {
  236. return;
  237. }
  238. tokenAccount.poolKeys = createPoolKeys(
  239. accountId,
  240. accountData,
  241. tokenAccount.market!,
  242. );
  243. const { innerTransaction, address } = Liquidity.makeSwapFixedInInstruction(
  244. {
  245. poolKeys: tokenAccount.poolKeys,
  246. userKeys: {
  247. tokenAccountIn: quoteTokenAssociatedAddress,
  248. tokenAccountOut: tokenAccount.address,
  249. owner: wallet.publicKey,
  250. },
  251. amountIn: quoteAmount.raw,
  252. minAmountOut: 0,
  253. },
  254. tokenAccount.poolKeys.version,
  255. );
  256. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  257. commitment: commitment,
  258. });
  259. const messageV0 = new TransactionMessage({
  260. payerKey: wallet.publicKey,
  261. recentBlockhash: latestBlockhash.blockhash,
  262. instructions: [
  263. ComputeBudgetProgram.setComputeUnitLimit({ units: 400000 }),
  264. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 30000 }),
  265. createAssociatedTokenAccountIdempotentInstruction(
  266. wallet.publicKey,
  267. tokenAccount.address,
  268. wallet.publicKey,
  269. accountData.baseMint,
  270. ),
  271. ...innerTransaction.instructions,
  272. ],
  273. }).compileToV0Message();
  274. const transaction = new VersionedTransaction(messageV0);
  275. transaction.sign([wallet, ...innerTransaction.signers]);
  276. const signature = await solanaConnection.sendRawTransaction(
  277. transaction.serialize(),
  278. {
  279. maxRetries: 20,
  280. preflightCommitment: commitment,
  281. },
  282. );
  283. logger.info(
  284. {
  285. mint: accountData.baseMint,
  286. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  287. },
  288. 'Buy',
  289. );
  290. }
  291. function loadSnipeList() {
  292. if (!USE_SNIPE_LIST) {
  293. return;
  294. }
  295. const count = snipeList.length;
  296. const data = fs.readFileSync(path.join(__dirname, 'snipe-list.txt'), 'utf-8');
  297. snipeList = data
  298. .split('\n')
  299. .map((a) => a.trim())
  300. .filter((a) => a);
  301. if (snipeList.length != count) {
  302. logger.info(`Loaded snipe list: ${snipeList.length}`);
  303. }
  304. }
  305. function shouldBuy(key: string): boolean {
  306. return USE_SNIPE_LIST ? snipeList.includes(key) : true;
  307. }
  308. const runListener = async () => {
  309. await init();
  310. const raydiumSubscriptionId = solanaConnection.onProgramAccountChange(
  311. RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
  312. async (updatedAccountInfo) => {
  313. const key = updatedAccountInfo.accountId.toString();
  314. const existing = existingLiquidityPools.has(key);
  315. if (!existing) {
  316. existingLiquidityPools.add(key);
  317. const _ = processRaydiumPool(updatedAccountInfo);
  318. }
  319. },
  320. commitment,
  321. [
  322. { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
  323. {
  324. memcmp: {
  325. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'),
  326. bytes: quoteToken.mint.toBase58(),
  327. },
  328. },
  329. {
  330. memcmp: {
  331. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'),
  332. bytes: OPENBOOK_PROGRAM_ID.toBase58(),
  333. },
  334. },
  335. {
  336. memcmp: {
  337. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'),
  338. bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]),
  339. },
  340. },
  341. ],
  342. );
  343. const openBookSubscriptionId = solanaConnection.onProgramAccountChange(
  344. OPENBOOK_PROGRAM_ID,
  345. async (updatedAccountInfo) => {
  346. const key = updatedAccountInfo.accountId.toString();
  347. const existing = existingOpenBookMarkets.has(key);
  348. if (!existing) {
  349. existingOpenBookMarkets.add(key);
  350. const _ = processOpenBookMarket(updatedAccountInfo);
  351. }
  352. },
  353. commitment,
  354. [
  355. { dataSize: MARKET_STATE_LAYOUT_V2.span },
  356. {
  357. memcmp: {
  358. offset: MARKET_STATE_LAYOUT_V2.offsetOf('quoteMint'),
  359. bytes: quoteToken.mint.toBase58(),
  360. },
  361. },
  362. ],
  363. );
  364. logger.info(`Listening for raydium changes: ${raydiumSubscriptionId}`);
  365. logger.info(`Listening for open book changes: ${openBookSubscriptionId}`);
  366. if (USE_SNIPE_LIST) {
  367. setInterval(loadSnipeList, SNIPE_LIST_REFRESH_INTERVAL);
  368. }
  369. };
  370. runListener();