buy.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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 { MintLayout } from './types';
  35. import pino from 'pino';
  36. import bs58 from 'bs58';
  37. import * as fs from 'fs';
  38. import * as path from 'path';
  39. const transport = pino.transport({
  40. targets: [
  41. /*
  42. {
  43. level: 'trace',
  44. target: 'pino/file',
  45. options: {
  46. destination: 'buy.log',
  47. },
  48. },
  49. */
  50. {
  51. level: 'trace',
  52. target: 'pino-pretty',
  53. options: {},
  54. },
  55. ],
  56. });
  57. export const logger = pino(
  58. {
  59. redact: ['poolKeys'],
  60. serializers: {
  61. error: pino.stdSerializers.err,
  62. },
  63. base: undefined,
  64. },
  65. transport,
  66. );
  67. const network = 'mainnet-beta';
  68. const RPC_ENDPOINT = retrieveEnvVariable('RPC_ENDPOINT', logger);
  69. const RPC_WEBSOCKET_ENDPOINT = retrieveEnvVariable(
  70. 'RPC_WEBSOCKET_ENDPOINT',
  71. logger,
  72. );
  73. const solanaConnection = new Connection(RPC_ENDPOINT, {
  74. wsEndpoint: RPC_WEBSOCKET_ENDPOINT,
  75. });
  76. export type MinimalTokenAccountData = {
  77. mint: PublicKey;
  78. address: PublicKey;
  79. poolKeys?: LiquidityPoolKeys;
  80. market?: MinimalMarketLayoutV3;
  81. };
  82. let existingLiquidityPools: Set<string> = new Set<string>();
  83. let existingOpenBookMarkets: Set<string> = new Set<string>();
  84. let existingTokenAccounts: Map<string, MinimalTokenAccountData> = new Map<
  85. string,
  86. MinimalTokenAccountData
  87. >();
  88. let wallet: Keypair;
  89. let quoteToken: Token;
  90. let quoteTokenAssociatedAddress: PublicKey;
  91. let quoteAmount: TokenAmount;
  92. let commitment: Commitment = retrieveEnvVariable(
  93. 'COMMITMENT_LEVEL',
  94. logger,
  95. ) as Commitment;
  96. const CHECK_IF_MINT_IS_RENOUNCED = retrieveEnvVariable('CHECK_IF_MINT_IS_RENOUNCED', logger) === 'true';
  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. // check existing wallet for associated token account of quote mint
  137. const tokenAccounts = await getTokenAccounts(
  138. solanaConnection,
  139. wallet.publicKey,
  140. commitment,
  141. );
  142. for (const ta of tokenAccounts) {
  143. existingTokenAccounts.set(ta.accountInfo.mint.toString(), <
  144. MinimalTokenAccountData
  145. >{
  146. mint: ta.accountInfo.mint,
  147. address: ta.pubkey,
  148. });
  149. }
  150. const tokenAccount = tokenAccounts.find(
  151. (acc) => acc.accountInfo.mint.toString() === quoteToken.mint.toString(),
  152. )!;
  153. if (!tokenAccount) {
  154. throw new Error(
  155. `No ${quoteToken.symbol} token account found in wallet: ${wallet.publicKey}`,
  156. );
  157. }
  158. quoteTokenAssociatedAddress = tokenAccount.pubkey;
  159. // load tokens to snipe
  160. loadSnipeList();
  161. }
  162. function saveTokenAccount(mint: PublicKey, accountData: MinimalMarketLayoutV3) {
  163. const ata = getAssociatedTokenAddressSync(mint, wallet.publicKey);
  164. const tokenAccount = <MinimalTokenAccountData>{
  165. address: ata,
  166. mint: mint,
  167. market: <MinimalMarketLayoutV3>{
  168. bids: accountData.bids,
  169. asks: accountData.asks,
  170. eventQueue: accountData.eventQueue,
  171. },
  172. };
  173. existingTokenAccounts.set(mint.toString(), tokenAccount);
  174. return tokenAccount;
  175. }
  176. export async function processRaydiumPool(
  177. id: PublicKey,
  178. poolState: LiquidityStateV4,
  179. ) {
  180. try {
  181. if (!shouldBuy(poolState.baseMint.toString())) {
  182. return;
  183. }
  184. if (CHECK_IF_MINT_IS_RENOUNCED) {
  185. const mintOption = await checkMintable(poolState.baseMint);
  186. if (mintOption !== true) {
  187. logger.warn({ ...poolState, }, 'Skipping, owner can mint tokens!');
  188. return;
  189. }
  190. }
  191. await buy(id, poolState);
  192. } catch (e) {
  193. logger.error({ ...poolState, error: e }, `Failed to process pool`);
  194. }
  195. }
  196. export async function checkMintable(vault: PublicKey): Promise<boolean | undefined> {
  197. try {
  198. let { data } = (await solanaConnection.getAccountInfo(vault)) || {};
  199. if (!data) {
  200. return;
  201. }
  202. const deserialize = MintLayout.decode(data), mintAuthorityOption = deserialize.mintAuthorityOption;
  203. return mintAuthorityOption === 0;
  204. } catch (e) {
  205. logger.error({ mint: vault, error: e }, `Failed to check if mint is renounced`);
  206. }
  207. }
  208. export async function processOpenBookMarket(
  209. updatedAccountInfo: KeyedAccountInfo,
  210. ) {
  211. let accountData: MarketStateV3 | undefined;
  212. try {
  213. accountData = MARKET_STATE_LAYOUT_V3.decode(
  214. updatedAccountInfo.accountInfo.data,
  215. );
  216. // to be competitive, we collect market data before buying the token...
  217. if (existingTokenAccounts.has(accountData.baseMint.toString())) {
  218. return;
  219. }
  220. saveTokenAccount(accountData.baseMint, accountData);
  221. } catch (e) {
  222. logger.error({ ...accountData, error: e }, `Failed to process market`);
  223. }
  224. }
  225. async function buy(
  226. accountId: PublicKey,
  227. accountData: LiquidityStateV4,
  228. ): Promise<void> {
  229. let tokenAccount = existingTokenAccounts.get(accountData.baseMint.toString());
  230. if (!tokenAccount) {
  231. // it's possible that we didn't have time to fetch open book data
  232. const market = await getMinimalMarketV3(
  233. solanaConnection,
  234. accountData.marketId,
  235. commitment,
  236. );
  237. tokenAccount = saveTokenAccount(accountData.baseMint, market);
  238. }
  239. tokenAccount.poolKeys = createPoolKeys(
  240. accountId,
  241. accountData,
  242. tokenAccount.market!,
  243. );
  244. const { innerTransaction, address } = Liquidity.makeSwapFixedInInstruction(
  245. {
  246. poolKeys: tokenAccount.poolKeys,
  247. userKeys: {
  248. tokenAccountIn: quoteTokenAssociatedAddress,
  249. tokenAccountOut: tokenAccount.address,
  250. owner: wallet.publicKey,
  251. },
  252. amountIn: quoteAmount.raw,
  253. minAmountOut: 0,
  254. },
  255. tokenAccount.poolKeys.version,
  256. );
  257. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  258. commitment: commitment,
  259. });
  260. const messageV0 = new TransactionMessage({
  261. payerKey: wallet.publicKey,
  262. recentBlockhash: latestBlockhash.blockhash,
  263. instructions: [
  264. ComputeBudgetProgram.setComputeUnitLimit({ units: 400000 }),
  265. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 30000 }),
  266. createAssociatedTokenAccountIdempotentInstruction(
  267. wallet.publicKey,
  268. tokenAccount.address,
  269. wallet.publicKey,
  270. accountData.baseMint,
  271. ),
  272. ...innerTransaction.instructions,
  273. ],
  274. }).compileToV0Message();
  275. const transaction = new VersionedTransaction(messageV0);
  276. transaction.sign([wallet, ...innerTransaction.signers]);
  277. const signature = await solanaConnection.sendRawTransaction(
  278. transaction.serialize(),
  279. {
  280. maxRetries: 20,
  281. preflightCommitment: commitment,
  282. },
  283. );
  284. logger.info(
  285. {
  286. mint: accountData.baseMint,
  287. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  288. dexURL: `https://dexscreener.com/solana/${accountData.baseMint}?maker=${wallet.publicKey}`,
  289. },
  290. 'Buy',
  291. );
  292. }
  293. function loadSnipeList() {
  294. if (!USE_SNIPE_LIST) {
  295. return;
  296. }
  297. const count = snipeList.length;
  298. const data = fs.readFileSync(path.join(__dirname, 'snipe-list.txt'), 'utf-8');
  299. snipeList = data
  300. .split('\n')
  301. .map((a) => a.trim())
  302. .filter((a) => a);
  303. if (snipeList.length != count) {
  304. logger.info(`Loaded snipe list: ${snipeList.length}`);
  305. }
  306. }
  307. function shouldBuy(key: string): boolean {
  308. return USE_SNIPE_LIST ? snipeList.includes(key) : true;
  309. }
  310. const runListener = async () => {
  311. await init();
  312. const runTimestamp = Math.floor(new Date().getTime() / 1000);
  313. const raydiumSubscriptionId = solanaConnection.onProgramAccountChange(
  314. RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
  315. async (updatedAccountInfo) => {
  316. const key = updatedAccountInfo.accountId.toString();
  317. const poolState = LIQUIDITY_STATE_LAYOUT_V4.decode(
  318. updatedAccountInfo.accountInfo.data,
  319. );
  320. const poolOpenTime = parseInt(poolState.poolOpenTime.toString());
  321. const existing = existingLiquidityPools.has(key);
  322. if (poolOpenTime > runTimestamp && !existing) {
  323. existingLiquidityPools.add(key);
  324. const _ = processRaydiumPool(updatedAccountInfo.accountId, poolState);
  325. }
  326. },
  327. commitment,
  328. [
  329. { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
  330. {
  331. memcmp: {
  332. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'),
  333. bytes: quoteToken.mint.toBase58(),
  334. },
  335. },
  336. {
  337. memcmp: {
  338. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'),
  339. bytes: OPENBOOK_PROGRAM_ID.toBase58(),
  340. },
  341. },
  342. {
  343. memcmp: {
  344. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'),
  345. bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]),
  346. },
  347. },
  348. ],
  349. );
  350. const openBookSubscriptionId = solanaConnection.onProgramAccountChange(
  351. OPENBOOK_PROGRAM_ID,
  352. async (updatedAccountInfo) => {
  353. const key = updatedAccountInfo.accountId.toString();
  354. const existing = existingOpenBookMarkets.has(key);
  355. if (!existing) {
  356. existingOpenBookMarkets.add(key);
  357. const _ = processOpenBookMarket(updatedAccountInfo);
  358. }
  359. },
  360. commitment,
  361. [
  362. { dataSize: MARKET_STATE_LAYOUT_V3.span },
  363. {
  364. memcmp: {
  365. offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'),
  366. bytes: quoteToken.mint.toBase58(),
  367. },
  368. },
  369. ],
  370. );
  371. logger.info(`Listening for raydium changes: ${raydiumSubscriptionId}`);
  372. logger.info(`Listening for open book changes: ${openBookSubscriptionId}`);
  373. if (USE_SNIPE_LIST) {
  374. setInterval(loadSnipeList, SNIPE_LIST_REFRESH_INTERVAL);
  375. }
  376. };
  377. runListener();