buy.ts 10 KB

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