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. solanaConnection,
  139. quoteToken.mint,
  140. commitment,
  141. );
  142. existingLiquidityPools = new Set(
  143. allLiquidityPools.map((p) => p.id.toString()),
  144. );
  145. // get all open-book markets
  146. const allMarkets = await getAllMarketsV3(
  147. solanaConnection,
  148. quoteToken.mint,
  149. commitment,
  150. );
  151. existingOpenBookMarkets = new Set(allMarkets.map((p) => p.id.toString()));
  152. logger.info(
  153. `Total ${quoteToken.symbol} markets ${existingOpenBookMarkets.size}`,
  154. );
  155. logger.info(
  156. `Total ${quoteToken.symbol} pools ${existingLiquidityPools.size}`,
  157. );
  158. // check existing wallet for associated token account of quote mint
  159. const tokenAccounts = await getTokenAccounts(
  160. solanaConnection,
  161. wallet.publicKey,
  162. commitment,
  163. );
  164. for (const ta of tokenAccounts) {
  165. existingTokenAccounts.set(ta.accountInfo.mint.toString(), <
  166. MinimalTokenAccountData
  167. >{
  168. mint: ta.accountInfo.mint,
  169. address: ta.pubkey,
  170. });
  171. }
  172. const tokenAccount = tokenAccounts.find(
  173. (acc) => acc.accountInfo.mint.toString() === quoteToken.mint.toString(),
  174. )!;
  175. if (!tokenAccount) {
  176. throw new Error(
  177. `No ${quoteToken.symbol} token account found in wallet: ${wallet.publicKey}`,
  178. );
  179. }
  180. quoteTokenAssociatedAddress = tokenAccount.pubkey;
  181. // load tokens to snipe
  182. loadSnipeList();
  183. }
  184. export async function processRaydiumPool(updatedAccountInfo: KeyedAccountInfo) {
  185. let accountData: LiquidityStateV4 | undefined;
  186. try {
  187. accountData = LIQUIDITY_STATE_LAYOUT_V4.decode(
  188. updatedAccountInfo.accountInfo.data,
  189. );
  190. if (!shouldBuy(accountData.baseMint.toString())) {
  191. return;
  192. }
  193. await buy(updatedAccountInfo.accountId, accountData);
  194. } catch (e) {
  195. logger.error({ ...accountData, error: e }, `Failed to process pool`);
  196. }
  197. }
  198. export async function processOpenBookMarket(
  199. updatedAccountInfo: KeyedAccountInfo,
  200. ) {
  201. let accountData: MarketStateV3 | undefined;
  202. try {
  203. accountData = MARKET_STATE_LAYOUT_V3.decode(
  204. updatedAccountInfo.accountInfo.data,
  205. );
  206. // to be competitive, we collect market data before buying the token...
  207. if (existingTokenAccounts.has(accountData.baseMint.toString())) {
  208. return;
  209. }
  210. const ata = getAssociatedTokenAddressSync(
  211. accountData.baseMint,
  212. wallet.publicKey,
  213. );
  214. existingTokenAccounts.set(accountData.baseMint.toString(), <
  215. MinimalTokenAccountData
  216. >{
  217. address: ata,
  218. mint: accountData.baseMint,
  219. market: <MinimalMarketLayoutV3>{
  220. bids: accountData.bids,
  221. asks: accountData.asks,
  222. eventQueue: accountData.eventQueue,
  223. },
  224. });
  225. } catch (e) {
  226. logger.error({ ...accountData, error: e }, `Failed to process market`);
  227. }
  228. }
  229. async function buy(
  230. accountId: PublicKey,
  231. accountData: LiquidityStateV4,
  232. ): Promise<void> {
  233. const tokenAccount = existingTokenAccounts.get(
  234. accountData.baseMint.toString(),
  235. );
  236. if (!tokenAccount) {
  237. return;
  238. }
  239. tokenAccount.poolKeys = createPoolKeys(
  240. accountId,
  241. accountData,
  242. tokenAccount.market!,
  243. );
  244. const { innerTransaction, address } = Liquidity.makeSwapFixedInInstruction(
  245. {
  246. poolKeys: tokenAccount.poolKeys,
  247. userKeys: {
  248. tokenAccountIn: quoteTokenAssociatedAddress,
  249. tokenAccountOut: tokenAccount.address,
  250. owner: wallet.publicKey,
  251. },
  252. amountIn: quoteAmount.raw,
  253. minAmountOut: 0,
  254. },
  255. tokenAccount.poolKeys.version,
  256. );
  257. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  258. commitment: commitment,
  259. });
  260. const messageV0 = new TransactionMessage({
  261. payerKey: wallet.publicKey,
  262. recentBlockhash: latestBlockhash.blockhash,
  263. instructions: [
  264. ComputeBudgetProgram.setComputeUnitLimit({ units: 400000 }),
  265. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 30000 }),
  266. createAssociatedTokenAccountIdempotentInstruction(
  267. wallet.publicKey,
  268. tokenAccount.address,
  269. wallet.publicKey,
  270. accountData.baseMint,
  271. ),
  272. ...innerTransaction.instructions,
  273. ],
  274. }).compileToV0Message();
  275. const transaction = new VersionedTransaction(messageV0);
  276. transaction.sign([wallet, ...innerTransaction.signers]);
  277. const signature = await solanaConnection.sendRawTransaction(
  278. transaction.serialize(),
  279. {
  280. maxRetries: 5,
  281. preflightCommitment: commitment,
  282. },
  283. );
  284. logger.info(
  285. {
  286. mint: accountData.baseMint,
  287. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  288. },
  289. 'Buy',
  290. );
  291. }
  292. function loadSnipeList() {
  293. if (!USE_SNIPE_LIST) {
  294. return;
  295. }
  296. const count = snipeList.length;
  297. const data = fs.readFileSync(path.join(__dirname, 'snipe-list.txt'), 'utf-8');
  298. snipeList = data
  299. .split('\n')
  300. .map((a) => a.trim())
  301. .filter((a) => a);
  302. if (snipeList.length != count) {
  303. logger.info(`Loaded snipe list: ${snipeList.length}`);
  304. }
  305. }
  306. function shouldBuy(key: string): boolean {
  307. return USE_SNIPE_LIST ? snipeList.includes(key) : true;
  308. }
  309. const runListener = async () => {
  310. await init();
  311. const raydiumSubscriptionId = solanaConnection.onProgramAccountChange(
  312. RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
  313. async (updatedAccountInfo) => {
  314. const key = updatedAccountInfo.accountId.toString();
  315. const existing = existingLiquidityPools.has(key);
  316. if (!existing) {
  317. existingLiquidityPools.add(key);
  318. const _ = processRaydiumPool(updatedAccountInfo);
  319. }
  320. },
  321. commitment,
  322. [
  323. { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
  324. {
  325. memcmp: {
  326. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'),
  327. bytes: quoteToken.mint.toBase58(),
  328. },
  329. },
  330. {
  331. memcmp: {
  332. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'),
  333. bytes: OPENBOOK_PROGRAM_ID.toBase58(),
  334. },
  335. },
  336. {
  337. memcmp: {
  338. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'),
  339. bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]),
  340. },
  341. },
  342. ],
  343. );
  344. const openBookSubscriptionId = solanaConnection.onProgramAccountChange(
  345. OPENBOOK_PROGRAM_ID,
  346. async (updatedAccountInfo) => {
  347. const key = updatedAccountInfo.accountId.toString();
  348. const existing = existingOpenBookMarkets.has(key);
  349. if (!existing) {
  350. existingOpenBookMarkets.add(key);
  351. const _ = processOpenBookMarket(updatedAccountInfo);
  352. }
  353. },
  354. commitment,
  355. [
  356. { dataSize: MARKET_STATE_LAYOUT_V2.span },
  357. {
  358. memcmp: {
  359. offset: MARKET_STATE_LAYOUT_V2.offsetOf('quoteMint'),
  360. bytes: quoteToken.mint.toBase58(),
  361. },
  362. },
  363. ],
  364. );
  365. logger.info(`Listening for raydium changes: ${raydiumSubscriptionId}`);
  366. logger.info(`Listening for open book changes: ${openBookSubscriptionId}`);
  367. if (USE_SNIPE_LIST) {
  368. setInterval(loadSnipeList, SNIPE_LIST_REFRESH_INTERVAL);
  369. }
  370. };
  371. runListener();