buy.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. import BN from 'bn.js';
  39. const transport = pino.transport({
  40. targets: [
  41. // {
  42. // level: 'trace',
  43. // target: 'pino/file',
  44. // options: {
  45. // destination: 'buy.log',
  46. // },
  47. // },
  48. {
  49. level: 'trace',
  50. target: 'pino-pretty',
  51. options: {},
  52. },
  53. ],
  54. });
  55. export const logger = pino(
  56. {
  57. redact: ['poolKeys'],
  58. serializers: {
  59. error: pino.stdSerializers.err,
  60. },
  61. base: undefined,
  62. },
  63. transport,
  64. );
  65. const network = 'mainnet-beta';
  66. const RPC_ENDPOINT = retrieveEnvVariable('RPC_ENDPOINT', logger);
  67. const RPC_WEBSOCKET_ENDPOINT = retrieveEnvVariable(
  68. 'RPC_WEBSOCKET_ENDPOINT',
  69. logger,
  70. );
  71. const solanaConnection = new Connection(RPC_ENDPOINT, {
  72. wsEndpoint: RPC_WEBSOCKET_ENDPOINT,
  73. });
  74. export type MinimalTokenAccountData = {
  75. mint: PublicKey;
  76. address: PublicKey;
  77. poolKeys?: LiquidityPoolKeys;
  78. market?: MinimalMarketLayoutV3;
  79. };
  80. let existingLiquidityPools: Set<string> = new Set<string>();
  81. let existingOpenBookMarkets: Set<string> = new Set<string>();
  82. let existingTokenAccounts: Map<string, MinimalTokenAccountData> = new Map<
  83. string,
  84. MinimalTokenAccountData
  85. >();
  86. let wallet: Keypair;
  87. let quoteToken: Token;
  88. let quoteTokenAssociatedAddress: PublicKey;
  89. let quoteAmount: TokenAmount;
  90. let commitment: Commitment = retrieveEnvVariable(
  91. 'COMMITMENT_LEVEL',
  92. logger,
  93. ) as Commitment;
  94. const USE_SNIPE_LIST = retrieveEnvVariable('USE_SNIPE_LIST', logger) === 'true';
  95. const SNIPE_LIST_REFRESH_INTERVAL = Number(
  96. retrieveEnvVariable('SNIPE_LIST_REFRESH_INTERVAL', logger),
  97. );
  98. let snipeList: string[] = [];
  99. async function init(): Promise<void> {
  100. // get wallet
  101. const PRIVATE_KEY = retrieveEnvVariable('PRIVATE_KEY', logger);
  102. wallet = Keypair.fromSecretKey(bs58.decode(PRIVATE_KEY));
  103. logger.info(`Wallet Address: ${wallet.publicKey}`);
  104. // get quote mint and amount
  105. const QUOTE_MINT = retrieveEnvVariable('QUOTE_MINT', logger);
  106. const QUOTE_AMOUNT = retrieveEnvVariable('QUOTE_AMOUNT', logger);
  107. switch (QUOTE_MINT) {
  108. case 'WSOL': {
  109. quoteToken = Token.WSOL;
  110. quoteAmount = new TokenAmount(Token.WSOL, QUOTE_AMOUNT, false);
  111. break;
  112. }
  113. case 'USDC': {
  114. quoteToken = new Token(
  115. TOKEN_PROGRAM_ID,
  116. new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),
  117. 6,
  118. 'USDC',
  119. 'USDC',
  120. );
  121. quoteAmount = new TokenAmount(quoteToken, QUOTE_AMOUNT, false);
  122. break;
  123. }
  124. default: {
  125. throw new Error(
  126. `Unsupported quote mint "${QUOTE_MINT}". Supported values are USDC and WSOL`,
  127. );
  128. }
  129. }
  130. logger.info(
  131. `Script will buy all new tokens using ${QUOTE_MINT}. Amount that will be used to buy each token is: ${quoteAmount.toFixed().toString()}`,
  132. );
  133. // check existing wallet for associated token account of quote mint
  134. const tokenAccounts = await getTokenAccounts(
  135. solanaConnection,
  136. wallet.publicKey,
  137. commitment,
  138. );
  139. for (const ta of tokenAccounts) {
  140. existingTokenAccounts.set(ta.accountInfo.mint.toString(), <
  141. MinimalTokenAccountData
  142. >{
  143. mint: ta.accountInfo.mint,
  144. address: ta.pubkey,
  145. });
  146. }
  147. const tokenAccount = tokenAccounts.find(
  148. (acc) => acc.accountInfo.mint.toString() === quoteToken.mint.toString(),
  149. )!;
  150. if (!tokenAccount) {
  151. throw new Error(
  152. `No ${quoteToken.symbol} token account found in wallet: ${wallet.publicKey}`,
  153. );
  154. }
  155. quoteTokenAssociatedAddress = tokenAccount.pubkey;
  156. // load tokens to snipe
  157. loadSnipeList();
  158. }
  159. function saveTokenAccount(mint: PublicKey, accountData: MinimalMarketLayoutV3) {
  160. const ata = getAssociatedTokenAddressSync(mint, wallet.publicKey);
  161. const tokenAccount = <MinimalTokenAccountData>{
  162. address: ata,
  163. mint: mint,
  164. market: <MinimalMarketLayoutV3>{
  165. bids: accountData.bids,
  166. asks: accountData.asks,
  167. eventQueue: accountData.eventQueue,
  168. },
  169. };
  170. existingTokenAccounts.set(mint.toString(), tokenAccount);
  171. return tokenAccount;
  172. }
  173. export async function processRaydiumPool(
  174. id: PublicKey,
  175. poolState: LiquidityStateV4,
  176. ) {
  177. try {
  178. if (!shouldBuy(poolState.baseMint.toString())) {
  179. return;
  180. }
  181. await buy(id, poolState);
  182. } catch (e) {
  183. logger.error({ ...poolState, 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. saveTokenAccount(accountData.baseMint, accountData);
  199. } catch (e) {
  200. logger.error({ ...accountData, error: e }, `Failed to process market`);
  201. }
  202. }
  203. async function buy(
  204. accountId: PublicKey,
  205. accountData: LiquidityStateV4,
  206. ): Promise<void> {
  207. let tokenAccount = existingTokenAccounts.get(accountData.baseMint.toString());
  208. if (!tokenAccount) {
  209. // it's possible that we didn't have time to fetch open book data
  210. const market = await getMinimalMarketV3(
  211. solanaConnection,
  212. accountData.marketId,
  213. commitment,
  214. );
  215. tokenAccount = saveTokenAccount(accountData.baseMint, market);
  216. }
  217. tokenAccount.poolKeys = createPoolKeys(
  218. accountId,
  219. accountData,
  220. tokenAccount.market!,
  221. );
  222. const { innerTransaction, address } = Liquidity.makeSwapFixedInInstruction(
  223. {
  224. poolKeys: tokenAccount.poolKeys,
  225. userKeys: {
  226. tokenAccountIn: quoteTokenAssociatedAddress,
  227. tokenAccountOut: tokenAccount.address,
  228. owner: wallet.publicKey,
  229. },
  230. amountIn: quoteAmount.raw,
  231. minAmountOut: 0,
  232. },
  233. tokenAccount.poolKeys.version,
  234. );
  235. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  236. commitment: commitment,
  237. });
  238. const messageV0 = new TransactionMessage({
  239. payerKey: wallet.publicKey,
  240. recentBlockhash: latestBlockhash.blockhash,
  241. instructions: [
  242. ComputeBudgetProgram.setComputeUnitLimit({ units: 400000 }),
  243. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 30000 }),
  244. createAssociatedTokenAccountIdempotentInstruction(
  245. wallet.publicKey,
  246. tokenAccount.address,
  247. wallet.publicKey,
  248. accountData.baseMint,
  249. ),
  250. ...innerTransaction.instructions,
  251. ],
  252. }).compileToV0Message();
  253. const transaction = new VersionedTransaction(messageV0);
  254. transaction.sign([wallet, ...innerTransaction.signers]);
  255. const signature = await solanaConnection.sendRawTransaction(
  256. transaction.serialize(),
  257. {
  258. maxRetries: 20,
  259. preflightCommitment: commitment,
  260. },
  261. );
  262. logger.info(
  263. {
  264. mint: accountData.baseMint,
  265. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  266. },
  267. 'Buy',
  268. );
  269. // post to discord webhook
  270. const message = {
  271. embeds: [
  272. {
  273. title: `Bought token: ${accountData.baseMint.toBase58()}`,
  274. color: 1127128,
  275. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  276. },
  277. ],
  278. };
  279. const DISCORD_WEBHOOK = retrieveEnvVariable('DISCORD_WEBHOOK', logger);
  280. // use native fetch to post to discord
  281. fetch(DISCORD_WEBHOOK, {
  282. method: 'POST',
  283. headers: {
  284. 'Content-Type': 'application/json',
  285. },
  286. body: JSON.stringify(message),
  287. });
  288. }
  289. const maxRetries = 60;
  290. async function sell(
  291. accountId: PublicKey,
  292. accountData: LiquidityStateV4,
  293. ): Promise<void> {
  294. const tokenAccount = existingTokenAccounts.get(
  295. accountData.baseMint.toString(),
  296. );
  297. if (!tokenAccount) {
  298. return;
  299. }
  300. let retries = 0;
  301. let balanceFound = false;
  302. while (retries < maxRetries) {
  303. try {
  304. const balanceResponse = (await solanaConnection.getTokenAccountBalance(tokenAccount.address)).value.amount;
  305. if (balanceResponse !== null && Number(balanceResponse) > 0 && !balanceFound) {
  306. balanceFound = true;
  307. console.log("Token balance: ", balanceResponse);
  308. // send to discord
  309. const tokenBalanceMessage = {
  310. embeds: [
  311. {
  312. title: `Token balance: ${balanceResponse}`,
  313. color: 1127128,
  314. },
  315. ],
  316. };
  317. const DISCORD_WEBHOOK = retrieveEnvVariable('DISCORD_WEBHOOK', logger);
  318. // use native fetch to post to discord
  319. fetch(DISCORD_WEBHOOK, {
  320. method: 'POST',
  321. headers: {
  322. 'Content-Type': 'application/json',
  323. },
  324. body: JSON.stringify(tokenBalanceMessage),
  325. });
  326. tokenAccount.poolKeys = createPoolKeys(
  327. accountId,
  328. accountData,
  329. tokenAccount.market!,
  330. );
  331. const { innerTransaction, address } = Liquidity.makeSwapFixedInInstruction(
  332. {
  333. poolKeys: tokenAccount.poolKeys,
  334. userKeys: {
  335. tokenAccountIn: tokenAccount.address,
  336. tokenAccountOut: quoteTokenAssociatedAddress,
  337. owner: wallet.publicKey,
  338. },
  339. amountIn: new BN(balanceResponse),
  340. minAmountOut: 0,
  341. },
  342. tokenAccount.poolKeys.version,
  343. );
  344. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  345. commitment: commitment,
  346. });
  347. const messageV0 = new TransactionMessage({
  348. payerKey: wallet.publicKey,
  349. recentBlockhash: latestBlockhash.blockhash,
  350. instructions: [
  351. ComputeBudgetProgram.setComputeUnitLimit({ units: 400000 }),
  352. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 200000 }),
  353. createAssociatedTokenAccountIdempotentInstruction(
  354. wallet.publicKey,
  355. tokenAccount.address,
  356. wallet.publicKey,
  357. accountData.baseMint,
  358. ),
  359. ...innerTransaction.instructions,
  360. ],
  361. }).compileToV0Message();
  362. const transaction = new VersionedTransaction(messageV0);
  363. transaction.sign([wallet, ...innerTransaction.signers]);
  364. const signature = await solanaConnection.sendRawTransaction(
  365. transaction.serialize(),
  366. {
  367. maxRetries: 5,
  368. preflightCommitment: commitment,
  369. },
  370. );
  371. logger.info(
  372. {
  373. mint: accountData.baseMint,
  374. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  375. },
  376. 'sell',
  377. );
  378. // post to discord webhook
  379. const sellMessage = {
  380. embeds: [
  381. {
  382. title: `Sold token: ${accountData.baseMint.toBase58()}`,
  383. color: 1127128,
  384. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  385. },
  386. ],
  387. };
  388. // const DISCORD_WEBHOOK = retrieveEnvVariable('DISCORD_WEBHOOK', logger);
  389. // use native fetch to post to discord
  390. fetch(DISCORD_WEBHOOK, {
  391. method: 'POST',
  392. headers: {
  393. 'Content-Type': 'application/json',
  394. },
  395. body: JSON.stringify(sellMessage),
  396. });
  397. break;
  398. }
  399. } catch (error) {
  400. }
  401. retries++;
  402. await new Promise((resolve) => setTimeout(resolve, 1000));
  403. }
  404. }
  405. function loadSnipeList() {
  406. if (!USE_SNIPE_LIST) {
  407. return;
  408. }
  409. const count = snipeList.length;
  410. const data = fs.readFileSync(path.join(__dirname, 'snipe-list.txt'), 'utf-8');
  411. snipeList = data
  412. .split('\n')
  413. .map((a) => a.trim())
  414. .filter((a) => a);
  415. if (snipeList.length != count) {
  416. logger.info(`Loaded snipe list: ${snipeList.length}`);
  417. }
  418. }
  419. function shouldBuy(key: string): boolean {
  420. return USE_SNIPE_LIST ? snipeList.includes(key) : true;
  421. }
  422. const runListener = async () => {
  423. await init();
  424. const runTimestamp = Math.floor(new Date().getTime() / 1000);
  425. const raydiumSubscriptionId = solanaConnection.onProgramAccountChange(
  426. RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
  427. async (updatedAccountInfo) => {
  428. const key = updatedAccountInfo.accountId.toString();
  429. const poolState = LIQUIDITY_STATE_LAYOUT_V4.decode(
  430. updatedAccountInfo.accountInfo.data,
  431. );
  432. const poolOpenTime = parseInt(poolState.poolOpenTime.toString());
  433. const existing = existingLiquidityPools.has(key);
  434. if (poolOpenTime > runTimestamp && !existing) {
  435. existingLiquidityPools.add(key);
  436. const _ = processRaydiumPool(updatedAccountInfo.accountId, poolState);
  437. }
  438. },
  439. commitment,
  440. [
  441. { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
  442. {
  443. memcmp: {
  444. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'),
  445. bytes: quoteToken.mint.toBase58(),
  446. },
  447. },
  448. {
  449. memcmp: {
  450. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'),
  451. bytes: OPENBOOK_PROGRAM_ID.toBase58(),
  452. },
  453. },
  454. {
  455. memcmp: {
  456. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'),
  457. bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]),
  458. },
  459. },
  460. ],
  461. );
  462. const openBookSubscriptionId = solanaConnection.onProgramAccountChange(
  463. OPENBOOK_PROGRAM_ID,
  464. async (updatedAccountInfo) => {
  465. const key = updatedAccountInfo.accountId.toString();
  466. const existing = existingOpenBookMarkets.has(key);
  467. if (!existing) {
  468. existingOpenBookMarkets.add(key);
  469. const _ = processOpenBookMarket(updatedAccountInfo);
  470. }
  471. },
  472. commitment,
  473. [
  474. { dataSize: MARKET_STATE_LAYOUT_V3.span },
  475. {
  476. memcmp: {
  477. offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'),
  478. bytes: quoteToken.mint.toBase58(),
  479. },
  480. },
  481. ],
  482. );
  483. logger.info(`Listening for raydium changes: ${raydiumSubscriptionId}`);
  484. logger.info(`Listening for open book changes: ${openBookSubscriptionId}`);
  485. // post to discord webhook
  486. const message = {
  487. embeds: [
  488. {
  489. title: `Listening for raydium changes: ${raydiumSubscriptionId}`,
  490. color: 1127128,
  491. },
  492. {
  493. title: `Listening for open book changes: ${openBookSubscriptionId}`,
  494. color: 14177041,
  495. },
  496. ],
  497. };
  498. const DISCORD_WEBHOOK = retrieveEnvVariable('DISCORD_WEBHOOK', logger);
  499. // use native fetch to post to discord
  500. fetch(DISCORD_WEBHOOK, {
  501. method: 'POST',
  502. headers: {
  503. 'Content-Type': 'application/json',
  504. },
  505. body: JSON.stringify(message),
  506. });
  507. if (USE_SNIPE_LIST) {
  508. setInterval(loadSnipeList, SNIPE_LIST_REFRESH_INTERVAL);
  509. }
  510. };
  511. runListener();