buy.ts 15 KB

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