buy.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. // post to discord webhook
  137. // use embeds to show the token and the amount
  138. // {
  139. // "embeds": [
  140. // {
  141. // "title": "Meow!",
  142. // "color": 1127128
  143. // },
  144. // {
  145. // "title": "Meow-meow!",
  146. // "color": 14177041
  147. // }
  148. // ]
  149. // }
  150. let message = {
  151. embeds: [
  152. {
  153. title: `Script will buy all new tokens using ${QUOTE_MINT}. Amount that will be used to buy each token is: ${quoteAmount.toFixed().toString()}`,
  154. color: 1127128,
  155. },
  156. ],
  157. };
  158. // post it to discord
  159. const DISCORD_WEBHOOK = retrieveEnvVariable('DISCORD_WEBHOOK', logger);
  160. // use native fetch to post to discord
  161. fetch(DISCORD_WEBHOOK, {
  162. method: 'POST',
  163. headers: {
  164. 'Content-Type': 'application/json',
  165. },
  166. body: JSON.stringify(message),
  167. });
  168. // get all existing liquidity pools
  169. const allLiquidityPools = await getAllAccountsV4(
  170. solanaConnection,
  171. quoteToken.mint,
  172. commitment,
  173. );
  174. existingLiquidityPools = new Set(
  175. allLiquidityPools.map((p) => p.id.toString()),
  176. );
  177. // get all open-book markets
  178. const allMarkets = await getAllMarketsV3(
  179. solanaConnection,
  180. quoteToken.mint,
  181. commitment,
  182. );
  183. existingOpenBookMarkets = new Set(allMarkets.map((p) => p.id.toString()));
  184. logger.info(
  185. `Total ${quoteToken.symbol} markets ${existingOpenBookMarkets.size}`,
  186. );
  187. logger.info(
  188. `Total ${quoteToken.symbol} pools ${existingLiquidityPools.size}`,
  189. );
  190. // post to discord webhook
  191. message = {
  192. embeds: [
  193. {
  194. title: `Total ${quoteToken.symbol} markets ${existingOpenBookMarkets.size}`,
  195. color: 1127128,
  196. },
  197. {
  198. title: `Total ${quoteToken.symbol} pools ${existingLiquidityPools.size}`,
  199. color: 14177041,
  200. },
  201. ],
  202. };
  203. // post it to discord
  204. fetch(DISCORD_WEBHOOK, {
  205. method: 'POST',
  206. headers: {
  207. 'Content-Type': 'application/json',
  208. },
  209. body: JSON.stringify(message),
  210. });
  211. // check existing wallet for associated token account of quote mint
  212. const tokenAccounts = await getTokenAccounts(
  213. solanaConnection,
  214. wallet.publicKey,
  215. commitment,
  216. );
  217. for (const ta of tokenAccounts) {
  218. existingTokenAccounts.set(ta.accountInfo.mint.toString(), <
  219. MinimalTokenAccountData
  220. >{
  221. mint: ta.accountInfo.mint,
  222. address: ta.pubkey,
  223. });
  224. }
  225. const tokenAccount = tokenAccounts.find(
  226. (acc) => acc.accountInfo.mint.toString() === quoteToken.mint.toString(),
  227. )!;
  228. if (!tokenAccount) {
  229. throw new Error(
  230. `No ${quoteToken.symbol} token account found in wallet: ${wallet.publicKey}`,
  231. );
  232. }
  233. quoteTokenAssociatedAddress = tokenAccount.pubkey;
  234. // load tokens to snipe
  235. loadSnipeList();
  236. }
  237. export async function processRaydiumPool(updatedAccountInfo: KeyedAccountInfo) {
  238. let accountData: LiquidityStateV4 | undefined;
  239. try {
  240. accountData = LIQUIDITY_STATE_LAYOUT_V4.decode(
  241. updatedAccountInfo.accountInfo.data,
  242. );
  243. if (!shouldBuy(accountData.baseMint.toString())) {
  244. return;
  245. }
  246. await buy(updatedAccountInfo.accountId, accountData);
  247. } catch (e) {
  248. logger.error({ ...accountData, error: e }, `Failed to process pool`);
  249. }
  250. }
  251. export async function processOpenBookMarket(
  252. updatedAccountInfo: KeyedAccountInfo,
  253. ) {
  254. let accountData: MarketStateV3 | undefined;
  255. try {
  256. accountData = MARKET_STATE_LAYOUT_V3.decode(
  257. updatedAccountInfo.accountInfo.data,
  258. );
  259. // to be competitive, we collect market data before buying the token...
  260. if (existingTokenAccounts.has(accountData.baseMint.toString())) {
  261. return;
  262. }
  263. const ata = getAssociatedTokenAddressSync(
  264. accountData.baseMint,
  265. wallet.publicKey,
  266. );
  267. existingTokenAccounts.set(accountData.baseMint.toString(), <
  268. MinimalTokenAccountData
  269. >{
  270. address: ata,
  271. mint: accountData.baseMint,
  272. market: <MinimalMarketLayoutV3>{
  273. bids: accountData.bids,
  274. asks: accountData.asks,
  275. eventQueue: accountData.eventQueue,
  276. },
  277. });
  278. } catch (e) {
  279. logger.error({ ...accountData, error: e }, `Failed to process market`);
  280. }
  281. }
  282. async function buy(
  283. accountId: PublicKey,
  284. accountData: LiquidityStateV4,
  285. ): Promise<void> {
  286. const tokenAccount = existingTokenAccounts.get(
  287. accountData.baseMint.toString(),
  288. );
  289. if (!tokenAccount) {
  290. return;
  291. }
  292. tokenAccount.poolKeys = createPoolKeys(
  293. accountId,
  294. accountData,
  295. tokenAccount.market!,
  296. );
  297. const { innerTransaction, address } = Liquidity.makeSwapFixedInInstruction(
  298. {
  299. poolKeys: tokenAccount.poolKeys,
  300. userKeys: {
  301. tokenAccountIn: quoteTokenAssociatedAddress,
  302. tokenAccountOut: tokenAccount.address,
  303. owner: wallet.publicKey,
  304. },
  305. amountIn: quoteAmount.raw,
  306. minAmountOut: 0,
  307. },
  308. tokenAccount.poolKeys.version,
  309. );
  310. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  311. commitment: commitment,
  312. });
  313. const messageV0 = new TransactionMessage({
  314. payerKey: wallet.publicKey,
  315. recentBlockhash: latestBlockhash.blockhash,
  316. instructions: [
  317. ComputeBudgetProgram.setComputeUnitLimit({ units: 400000 }),
  318. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 30000 }),
  319. createAssociatedTokenAccountIdempotentInstruction(
  320. wallet.publicKey,
  321. tokenAccount.address,
  322. wallet.publicKey,
  323. accountData.baseMint,
  324. ),
  325. ...innerTransaction.instructions,
  326. ],
  327. }).compileToV0Message();
  328. const transaction = new VersionedTransaction(messageV0);
  329. transaction.sign([wallet, ...innerTransaction.signers]);
  330. const signature = await solanaConnection.sendRawTransaction(
  331. transaction.serialize(),
  332. {
  333. maxRetries: 20,
  334. preflightCommitment: commitment,
  335. },
  336. );
  337. logger.info(
  338. {
  339. mint: accountData.baseMint,
  340. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  341. },
  342. 'Buy',
  343. );
  344. // post to discord webhook
  345. const message = {
  346. embeds: [
  347. {
  348. title: `Bought token: ${accountData.baseMint.toBase58()}`,
  349. color: 1127128,
  350. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  351. },
  352. ],
  353. };
  354. const DISCORD_WEBHOOK = retrieveEnvVariable('DISCORD_WEBHOOK', logger);
  355. // use native fetch to post to discord
  356. fetch(DISCORD_WEBHOOK, {
  357. method: 'POST',
  358. headers: {
  359. 'Content-Type': 'application/json',
  360. },
  361. body: JSON.stringify(message),
  362. });
  363. }
  364. function loadSnipeList() {
  365. if (!USE_SNIPE_LIST) {
  366. return;
  367. }
  368. const count = snipeList.length;
  369. const data = fs.readFileSync(path.join(__dirname, 'snipe-list.txt'), 'utf-8');
  370. snipeList = data
  371. .split('\n')
  372. .map((a) => a.trim())
  373. .filter((a) => a);
  374. if (snipeList.length != count) {
  375. logger.info(`Loaded snipe list: ${snipeList.length}`);
  376. }
  377. }
  378. function shouldBuy(key: string): boolean {
  379. return USE_SNIPE_LIST ? snipeList.includes(key) : true;
  380. }
  381. const runListener = async () => {
  382. await init();
  383. const raydiumSubscriptionId = solanaConnection.onProgramAccountChange(
  384. RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
  385. async (updatedAccountInfo) => {
  386. const key = updatedAccountInfo.accountId.toString();
  387. const existing = existingLiquidityPools.has(key);
  388. if (!existing) {
  389. existingLiquidityPools.add(key);
  390. const _ = processRaydiumPool(updatedAccountInfo);
  391. }
  392. },
  393. commitment,
  394. [
  395. { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
  396. {
  397. memcmp: {
  398. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'),
  399. bytes: quoteToken.mint.toBase58(),
  400. },
  401. },
  402. {
  403. memcmp: {
  404. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'),
  405. bytes: OPENBOOK_PROGRAM_ID.toBase58(),
  406. },
  407. },
  408. {
  409. memcmp: {
  410. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'),
  411. bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]),
  412. },
  413. },
  414. ],
  415. );
  416. const openBookSubscriptionId = solanaConnection.onProgramAccountChange(
  417. OPENBOOK_PROGRAM_ID,
  418. async (updatedAccountInfo) => {
  419. const key = updatedAccountInfo.accountId.toString();
  420. const existing = existingOpenBookMarkets.has(key);
  421. if (!existing) {
  422. existingOpenBookMarkets.add(key);
  423. const _ = processOpenBookMarket(updatedAccountInfo);
  424. }
  425. },
  426. commitment,
  427. [
  428. { dataSize: MARKET_STATE_LAYOUT_V2.span },
  429. {
  430. memcmp: {
  431. offset: MARKET_STATE_LAYOUT_V2.offsetOf('quoteMint'),
  432. bytes: quoteToken.mint.toBase58(),
  433. },
  434. },
  435. ],
  436. );
  437. logger.info(`Listening for raydium changes: ${raydiumSubscriptionId}`);
  438. logger.info(`Listening for open book changes: ${openBookSubscriptionId}`);
  439. // post to discord webhook
  440. const message = {
  441. embeds: [
  442. {
  443. title: `Listening for raydium changes: ${raydiumSubscriptionId}`,
  444. color: 1127128,
  445. },
  446. {
  447. title: `Listening for open book changes: ${openBookSubscriptionId}`,
  448. color: 14177041,
  449. },
  450. ],
  451. };
  452. const DISCORD_WEBHOOK = retrieveEnvVariable('DISCORD_WEBHOOK', logger);
  453. // use native fetch to post to discord
  454. fetch(DISCORD_WEBHOOK, {
  455. method: 'POST',
  456. headers: {
  457. 'Content-Type': 'application/json',
  458. },
  459. body: JSON.stringify(message),
  460. });
  461. if (USE_SNIPE_LIST) {
  462. setInterval(loadSnipeList, SNIPE_LIST_REFRESH_INTERVAL);
  463. }
  464. };
  465. runListener();