buy.ts 10 KB

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