buy.ts 10 KB

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