buy.ts 15 KB

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