buy.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. import {
  2. BigNumberish,
  3. Liquidity,
  4. LIQUIDITY_STATE_LAYOUT_V4,
  5. LiquidityPoolKeys,
  6. LiquidityStateV4,
  7. MARKET_STATE_LAYOUT_V3,
  8. MarketStateV3,
  9. Token,
  10. TokenAmount,
  11. } from '@raydium-io/raydium-sdk';
  12. import {
  13. AccountLayout,
  14. createAssociatedTokenAccountIdempotentInstruction,
  15. createCloseAccountInstruction,
  16. getAssociatedTokenAddressSync,
  17. TOKEN_PROGRAM_ID,
  18. } from '@solana/spl-token';
  19. import {
  20. Keypair,
  21. Connection,
  22. PublicKey,
  23. ComputeBudgetProgram,
  24. KeyedAccountInfo,
  25. TransactionMessage,
  26. VersionedTransaction,
  27. Commitment,
  28. } from '@solana/web3.js';
  29. import { getTokenAccounts, RAYDIUM_LIQUIDITY_PROGRAM_ID_V4, OPENBOOK_PROGRAM_ID, createPoolKeys } from './liquidity';
  30. import { retrieveEnvVariable } from './utils';
  31. import { getMinimalMarketV3, MinimalMarketLayoutV3 } from './market';
  32. import { MintLayout } from './types';
  33. import pino from 'pino';
  34. import bs58 from 'bs58';
  35. import * as fs from 'fs';
  36. import * as path from 'path';
  37. import BN from 'bn.js';
  38. const transport = pino.transport({
  39. target: 'pino-pretty',
  40. });
  41. export const logger = pino(
  42. {
  43. level: 'info',
  44. redact: ['poolKeys'],
  45. serializers: {
  46. error: pino.stdSerializers.err,
  47. },
  48. base: undefined,
  49. },
  50. transport,
  51. );
  52. const network = 'mainnet-beta';
  53. const RPC_ENDPOINT = retrieveEnvVariable('RPC_ENDPOINT', logger);
  54. const RPC_WEBSOCKET_ENDPOINT = retrieveEnvVariable('RPC_WEBSOCKET_ENDPOINT', logger);
  55. const LOG_LEVEL = retrieveEnvVariable('LOG_LEVEL', logger);
  56. const solanaConnection = new Connection(RPC_ENDPOINT, {
  57. wsEndpoint: RPC_WEBSOCKET_ENDPOINT,
  58. });
  59. export type MinimalTokenAccountData = {
  60. mint: PublicKey;
  61. address: PublicKey;
  62. poolKeys?: LiquidityPoolKeys;
  63. market?: MinimalMarketLayoutV3;
  64. };
  65. let existingLiquidityPools: Set<string> = new Set<string>();
  66. let existingOpenBookMarkets: Set<string> = new Set<string>();
  67. let existingTokenAccounts: Map<string, MinimalTokenAccountData> = new Map<string, MinimalTokenAccountData>();
  68. let wallet: Keypair;
  69. let quoteToken: Token;
  70. let quoteTokenAssociatedAddress: PublicKey;
  71. let quoteAmount: TokenAmount;
  72. let commitment: Commitment = retrieveEnvVariable('COMMITMENT_LEVEL', logger) as Commitment;
  73. const CHECK_IF_MINT_IS_RENOUNCED = retrieveEnvVariable('CHECK_IF_MINT_IS_RENOUNCED', logger) === 'true';
  74. const USE_SNIPE_LIST = retrieveEnvVariable('USE_SNIPE_LIST', logger) === 'true';
  75. const SNIPE_LIST_REFRESH_INTERVAL = Number(retrieveEnvVariable('SNIPE_LIST_REFRESH_INTERVAL', logger));
  76. const AUTO_SELL = retrieveEnvVariable('AUTO_SELL', logger) === 'true';
  77. const MAX_SELL_RETRIES = Number(retrieveEnvVariable('MAX_SELL_RETRIES', logger));
  78. const AUTO_SELL_DELAY = Number(retrieveEnvVariable('AUTO_SELL_DELAY', logger));
  79. let snipeList: string[] = [];
  80. async function init(): Promise<void> {
  81. logger.level = LOG_LEVEL;
  82. // get wallet
  83. const PRIVATE_KEY = retrieveEnvVariable('PRIVATE_KEY', logger);
  84. wallet = Keypair.fromSecretKey(bs58.decode(PRIVATE_KEY));
  85. logger.info(`Wallet Address: ${wallet.publicKey}`);
  86. // get quote mint and amount
  87. const QUOTE_MINT = retrieveEnvVariable('QUOTE_MINT', logger);
  88. const QUOTE_AMOUNT = retrieveEnvVariable('QUOTE_AMOUNT', logger);
  89. switch (QUOTE_MINT) {
  90. case 'WSOL': {
  91. quoteToken = Token.WSOL;
  92. quoteAmount = new TokenAmount(Token.WSOL, QUOTE_AMOUNT, false);
  93. break;
  94. }
  95. case 'USDC': {
  96. quoteToken = new Token(
  97. TOKEN_PROGRAM_ID,
  98. new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),
  99. 6,
  100. 'USDC',
  101. 'USDC',
  102. );
  103. quoteAmount = new TokenAmount(quoteToken, QUOTE_AMOUNT, false);
  104. break;
  105. }
  106. default: {
  107. throw new Error(`Unsupported quote mint "${QUOTE_MINT}". Supported values are USDC and WSOL`);
  108. }
  109. }
  110. logger.info(
  111. `Script will buy all new tokens using ${QUOTE_MINT}. Amount that will be used to buy each token is: ${quoteAmount.toFixed().toString()}`,
  112. );
  113. // check existing wallet for associated token account of quote mint
  114. const tokenAccounts = await getTokenAccounts(solanaConnection, wallet.publicKey, commitment);
  115. for (const ta of tokenAccounts) {
  116. existingTokenAccounts.set(ta.accountInfo.mint.toString(), <MinimalTokenAccountData>{
  117. mint: ta.accountInfo.mint,
  118. address: ta.pubkey,
  119. });
  120. }
  121. const tokenAccount = tokenAccounts.find((acc) => acc.accountInfo.mint.toString() === quoteToken.mint.toString())!;
  122. if (!tokenAccount) {
  123. throw new Error(`No ${quoteToken.symbol} token account found in wallet: ${wallet.publicKey}`);
  124. }
  125. quoteTokenAssociatedAddress = tokenAccount.pubkey;
  126. // load tokens to snipe
  127. loadSnipeList();
  128. }
  129. function saveTokenAccount(mint: PublicKey, accountData: MinimalMarketLayoutV3) {
  130. const ata = getAssociatedTokenAddressSync(mint, wallet.publicKey);
  131. const tokenAccount = <MinimalTokenAccountData>{
  132. address: ata,
  133. mint: mint,
  134. market: <MinimalMarketLayoutV3>{
  135. bids: accountData.bids,
  136. asks: accountData.asks,
  137. eventQueue: accountData.eventQueue,
  138. },
  139. };
  140. existingTokenAccounts.set(mint.toString(), tokenAccount);
  141. return tokenAccount;
  142. }
  143. export async function processRaydiumPool(id: PublicKey, poolState: LiquidityStateV4) {
  144. if (!shouldBuy(poolState.baseMint.toString())) {
  145. return;
  146. }
  147. let poolSize = new BN(poolState.swapQuoteInAmount);
  148. poolSize = poolSize.div(new BN(10 ** quoteToken.decimals));
  149. const MIN_POOL_SIZE = new BN(retrieveEnvVariable('MIN_POOL_SIZE', logger));
  150. logger.info(
  151. `Processing pool: ${id.toString()} with ${poolSize.toString()} ${quoteToken.symbol} in liquidity`,
  152. );
  153. if (poolSize.lt(new BN(MIN_POOL_SIZE))) {
  154. logger.warn(
  155. {
  156. mint: poolState.baseMint,
  157. pooled: poolSize.toString() + ' ' + quoteToken.symbol,
  158. },
  159. `Skipping pool, smaller than ${MIN_POOL_SIZE} ${quoteToken.symbol}`,
  160. `Swap quote in amount: ${poolSize.toString()}`
  161. );
  162. return;
  163. }
  164. if (CHECK_IF_MINT_IS_RENOUNCED) {
  165. const mintOption = await checkMintable(poolState.baseMint);
  166. if (mintOption !== true) {
  167. logger.warn({ mint: poolState.baseMint }, 'Skipping, owner can mint tokens!');
  168. return;
  169. }
  170. }
  171. await buy(id, poolState);
  172. }
  173. export async function checkMintable(vault: PublicKey): Promise<boolean | undefined> {
  174. try {
  175. let { data } = (await solanaConnection.getAccountInfo(vault)) || {};
  176. if (!data) {
  177. return;
  178. }
  179. const deserialize = MintLayout.decode(data);
  180. return deserialize.mintAuthorityOption === 0;
  181. } catch (e) {
  182. logger.debug(e);
  183. logger.error({ mint: vault }, `Failed to check if mint is renounced`);
  184. }
  185. }
  186. export async function processOpenBookMarket(updatedAccountInfo: KeyedAccountInfo) {
  187. let accountData: MarketStateV3 | undefined;
  188. try {
  189. accountData = MARKET_STATE_LAYOUT_V3.decode(updatedAccountInfo.accountInfo.data);
  190. // to be competitive, we collect market data before buying the token...
  191. if (existingTokenAccounts.has(accountData.baseMint.toString())) {
  192. return;
  193. }
  194. saveTokenAccount(accountData.baseMint, accountData);
  195. } catch (e) {
  196. logger.debug(e);
  197. logger.error({ mint: accountData?.baseMint }, `Failed to process market`);
  198. }
  199. }
  200. async function buy(accountId: PublicKey, accountData: LiquidityStateV4): Promise<void> {
  201. try {
  202. let tokenAccount = existingTokenAccounts.get(accountData.baseMint.toString());
  203. if (!tokenAccount) {
  204. // it's possible that we didn't have time to fetch open book data
  205. const market = await getMinimalMarketV3(solanaConnection, accountData.marketId, commitment);
  206. tokenAccount = saveTokenAccount(accountData.baseMint, market);
  207. }
  208. tokenAccount.poolKeys = createPoolKeys(accountId, accountData, tokenAccount.market!);
  209. const { innerTransaction } = Liquidity.makeSwapFixedInInstruction(
  210. {
  211. poolKeys: tokenAccount.poolKeys,
  212. userKeys: {
  213. tokenAccountIn: quoteTokenAssociatedAddress,
  214. tokenAccountOut: tokenAccount.address,
  215. owner: wallet.publicKey,
  216. },
  217. amountIn: quoteAmount.raw,
  218. minAmountOut: 0,
  219. },
  220. tokenAccount.poolKeys.version,
  221. );
  222. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  223. commitment: commitment,
  224. });
  225. const messageV0 = new TransactionMessage({
  226. payerKey: wallet.publicKey,
  227. recentBlockhash: latestBlockhash.blockhash,
  228. instructions: [
  229. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 421197 }),
  230. ComputeBudgetProgram.setComputeUnitLimit({ units: 101337 }),
  231. createAssociatedTokenAccountIdempotentInstruction(
  232. wallet.publicKey,
  233. tokenAccount.address,
  234. wallet.publicKey,
  235. accountData.baseMint,
  236. ),
  237. ...innerTransaction.instructions,
  238. ],
  239. }).compileToV0Message();
  240. const transaction = new VersionedTransaction(messageV0);
  241. transaction.sign([wallet, ...innerTransaction.signers]);
  242. const signature = await solanaConnection.sendRawTransaction(transaction.serialize(), {
  243. preflightCommitment: commitment,
  244. });
  245. logger.info({ mint: accountData.baseMint, signature }, `Sent buy tx`);
  246. const confirmation = await solanaConnection.confirmTransaction(
  247. {
  248. signature,
  249. lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
  250. blockhash: latestBlockhash.blockhash,
  251. },
  252. commitment,
  253. );
  254. if (!confirmation.value.err) {
  255. logger.info(
  256. {
  257. mint: accountData.baseMint,
  258. signature,
  259. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  260. },
  261. `Confirmed buy tx`,
  262. );
  263. } else {
  264. logger.debug(confirmation.value.err);
  265. logger.info({ mint: accountData.baseMint, signature }, `Error confirming buy tx`);
  266. }
  267. } catch (e) {
  268. logger.debug(e);
  269. logger.error({ mint: accountData.baseMint }, `Failed to buy token`);
  270. }
  271. }
  272. async function sell(accountId: PublicKey, mint: PublicKey, amount: BigNumberish): Promise<void> {
  273. let sold = false;
  274. let retries = 0;
  275. if (AUTO_SELL_DELAY > 0) {
  276. await new Promise((resolve) => setTimeout(resolve, AUTO_SELL_DELAY));
  277. }
  278. do {
  279. try {
  280. const tokenAccount = existingTokenAccounts.get(mint.toString());
  281. if (!tokenAccount) {
  282. return;
  283. }
  284. if (!tokenAccount.poolKeys) {
  285. logger.warn({ mint }, 'No pool keys found');
  286. return;
  287. }
  288. if (amount === 0) {
  289. logger.info(
  290. {
  291. mint: tokenAccount.mint,
  292. },
  293. `Empty balance, can't sell`,
  294. );
  295. return;
  296. }
  297. const { innerTransaction } = Liquidity.makeSwapFixedInInstruction(
  298. {
  299. poolKeys: tokenAccount.poolKeys!,
  300. userKeys: {
  301. tokenAccountOut: quoteTokenAssociatedAddress,
  302. tokenAccountIn: tokenAccount.address,
  303. owner: wallet.publicKey,
  304. },
  305. amountIn: amount,
  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.setComputeUnitPrice({ microLamports: 421197 }),
  318. ComputeBudgetProgram.setComputeUnitLimit({ units: 101337 }),
  319. ...innerTransaction.instructions,
  320. createCloseAccountInstruction(tokenAccount.address, wallet.publicKey, wallet.publicKey),
  321. ],
  322. }).compileToV0Message();
  323. const transaction = new VersionedTransaction(messageV0);
  324. transaction.sign([wallet, ...innerTransaction.signers]);
  325. const signature = await solanaConnection.sendRawTransaction(transaction.serialize(), {
  326. preflightCommitment: commitment,
  327. });
  328. logger.info({ mint, signature }, `Sent sell tx`);
  329. const confirmation = await solanaConnection.confirmTransaction(
  330. {
  331. signature,
  332. lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
  333. blockhash: latestBlockhash.blockhash,
  334. },
  335. commitment,
  336. );
  337. if (confirmation.value.err) {
  338. logger.debug(confirmation.value.err);
  339. logger.info({ mint, signature }, `Error confirming sell tx`);
  340. continue;
  341. }
  342. logger.info(
  343. {
  344. dex: `https://dexscreener.com/solana/${mint}?maker=${wallet.publicKey}`,
  345. mint,
  346. signature,
  347. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  348. },
  349. `Confirmed sell tx`,
  350. );
  351. sold = true;
  352. } catch (e: any) {
  353. // wait for a bit before retrying
  354. await new Promise((resolve) => setTimeout(resolve, 100));
  355. retries++;
  356. logger.debug(e);
  357. logger.error({ mint }, `Failed to sell token, retry: ${retries}/${MAX_SELL_RETRIES}`);
  358. }
  359. } while (!sold && retries < MAX_SELL_RETRIES);
  360. }
  361. function loadSnipeList() {
  362. if (!USE_SNIPE_LIST) {
  363. return;
  364. }
  365. const count = snipeList.length;
  366. const data = fs.readFileSync(path.join(__dirname, 'snipe-list.txt'), 'utf-8');
  367. snipeList = data
  368. .split('\n')
  369. .map((a) => a.trim())
  370. .filter((a) => a);
  371. if (snipeList.length != count) {
  372. logger.info(`Loaded snipe list: ${snipeList.length}`);
  373. }
  374. }
  375. function shouldBuy(key: string): boolean {
  376. return USE_SNIPE_LIST ? snipeList.includes(key) : true;
  377. }
  378. const runListener = async () => {
  379. await init();
  380. const runTimestamp = Math.floor(new Date().getTime() / 1000);
  381. const raydiumSubscriptionId = solanaConnection.onProgramAccountChange(
  382. RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
  383. async (updatedAccountInfo) => {
  384. const key = updatedAccountInfo.accountId.toString();
  385. const poolState = LIQUIDITY_STATE_LAYOUT_V4.decode(updatedAccountInfo.accountInfo.data);
  386. const poolOpenTime = parseInt(poolState.poolOpenTime.toString());
  387. const existing = existingLiquidityPools.has(key);
  388. if (poolOpenTime > runTimestamp && !existing) {
  389. existingLiquidityPools.add(key);
  390. const _ = processRaydiumPool(updatedAccountInfo.accountId, poolState);
  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_V3.span },
  429. {
  430. memcmp: {
  431. offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'),
  432. bytes: quoteToken.mint.toBase58(),
  433. },
  434. },
  435. ],
  436. );
  437. if (AUTO_SELL) {
  438. const walletSubscriptionId = solanaConnection.onProgramAccountChange(
  439. TOKEN_PROGRAM_ID,
  440. async (updatedAccountInfo) => {
  441. const accountData = AccountLayout.decode(updatedAccountInfo.accountInfo!.data);
  442. if (updatedAccountInfo.accountId.equals(quoteTokenAssociatedAddress)) {
  443. return;
  444. }
  445. const _ = sell(updatedAccountInfo.accountId, accountData.mint, accountData.amount);
  446. },
  447. commitment,
  448. [
  449. {
  450. dataSize: 165,
  451. },
  452. {
  453. memcmp: {
  454. offset: 32,
  455. bytes: wallet.publicKey.toBase58(),
  456. },
  457. },
  458. ],
  459. );
  460. logger.info(`Listening for wallet changes: ${walletSubscriptionId}`);
  461. }
  462. logger.info(`Listening for raydium changes: ${raydiumSubscriptionId}`);
  463. logger.info(`Listening for open book changes: ${openBookSubscriptionId}`);
  464. if (USE_SNIPE_LIST) {
  465. setInterval(loadSnipeList, SNIPE_LIST_REFRESH_INTERVAL);
  466. }
  467. };
  468. runListener();