buy.ts 10 KB

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