buy.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 USE_SNIPE_LIST = retrieveEnvVariable('USE_SNIPE_LIST', logger) === 'true';
  97. const SNIPE_LIST_REFRESH_INTERVAL = Number(
  98. retrieveEnvVariable('SNIPE_LIST_REFRESH_INTERVAL', logger),
  99. );
  100. let snipeList: string[] = [];
  101. async function init(): Promise<void> {
  102. // get wallet
  103. const PRIVATE_KEY = retrieveEnvVariable('PRIVATE_KEY', logger);
  104. wallet = Keypair.fromSecretKey(bs58.decode(PRIVATE_KEY));
  105. logger.info(`Wallet Address: ${wallet.publicKey}`);
  106. // get quote mint and amount
  107. const QUOTE_MINT = retrieveEnvVariable('QUOTE_MINT', logger);
  108. const QUOTE_AMOUNT = retrieveEnvVariable('QUOTE_AMOUNT', logger);
  109. switch (QUOTE_MINT) {
  110. case 'WSOL': {
  111. quoteToken = Token.WSOL;
  112. quoteAmount = new TokenAmount(Token.WSOL, QUOTE_AMOUNT, false);
  113. break;
  114. }
  115. case 'USDC': {
  116. quoteToken = new Token(
  117. TOKEN_PROGRAM_ID,
  118. new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),
  119. 6,
  120. 'USDC',
  121. 'USDC',
  122. );
  123. quoteAmount = new TokenAmount(quoteToken, QUOTE_AMOUNT, false);
  124. break;
  125. }
  126. default: {
  127. throw new Error(
  128. `Unsupported quote mint "${QUOTE_MINT}". Supported values are USDC and WSOL`,
  129. );
  130. }
  131. }
  132. logger.info(
  133. `Script will buy all new tokens using ${QUOTE_MINT}. Amount that will be used to buy each token is: ${quoteAmount.toFixed().toString()}`,
  134. );
  135. // check existing wallet for associated token account of quote mint
  136. const tokenAccounts = await getTokenAccounts(
  137. solanaConnection,
  138. wallet.publicKey,
  139. commitment,
  140. );
  141. for (const ta of tokenAccounts) {
  142. existingTokenAccounts.set(ta.accountInfo.mint.toString(), <
  143. MinimalTokenAccountData
  144. >{
  145. mint: ta.accountInfo.mint,
  146. address: ta.pubkey,
  147. });
  148. }
  149. const tokenAccount = tokenAccounts.find(
  150. (acc) => acc.accountInfo.mint.toString() === quoteToken.mint.toString(),
  151. )!;
  152. if (!tokenAccount) {
  153. throw new Error(
  154. `No ${quoteToken.symbol} token account found in wallet: ${wallet.publicKey}`,
  155. );
  156. }
  157. quoteTokenAssociatedAddress = tokenAccount.pubkey;
  158. // load tokens to snipe
  159. loadSnipeList();
  160. }
  161. function saveTokenAccount(mint: PublicKey, accountData: MinimalMarketLayoutV3) {
  162. const ata = getAssociatedTokenAddressSync(mint, wallet.publicKey);
  163. const tokenAccount = <MinimalTokenAccountData>{
  164. address: ata,
  165. mint: mint,
  166. market: <MinimalMarketLayoutV3>{
  167. bids: accountData.bids,
  168. asks: accountData.asks,
  169. eventQueue: accountData.eventQueue,
  170. },
  171. };
  172. existingTokenAccounts.set(mint.toString(), tokenAccount);
  173. return tokenAccount;
  174. }
  175. export async function processRaydiumPool(
  176. id: PublicKey,
  177. poolState: LiquidityStateV4,
  178. ) {
  179. try {
  180. if (!shouldBuy(poolState.baseMint.toString())) {
  181. return;
  182. }
  183. const mintable = await checkMintable(poolState.baseMint)
  184. if(mintable) {
  185. console.log('Mintable check passed, proceding with buy');
  186. await buy(id, poolState);
  187. } else {
  188. console.log('Skipping, owner can mint tokens!')
  189. }
  190. } catch (e) {
  191. logger.error({ ...poolState, error: e }, `Failed to process pool`);
  192. }
  193. }
  194. export async function checkMintable(vault: PublicKey) {
  195. try {
  196. let { data } = (await solanaConnection.getAccountInfo(vault)) || {};
  197. if (!data) {
  198. return;
  199. }
  200. // Deserialize Data.
  201. const deserialize = MintLayout.decode(data)
  202. const mintoption = deserialize.mintAuthorityOption
  203. if (mintoption === 0) {
  204. return true;
  205. } else {
  206. return false;
  207. }
  208. } catch {
  209. return null;
  210. }
  211. }
  212. export async function processOpenBookMarket(
  213. updatedAccountInfo: KeyedAccountInfo,
  214. ) {
  215. let accountData: MarketStateV3 | undefined;
  216. try {
  217. accountData = MARKET_STATE_LAYOUT_V3.decode(
  218. updatedAccountInfo.accountInfo.data,
  219. );
  220. // to be competitive, we collect market data before buying the token...
  221. if (existingTokenAccounts.has(accountData.baseMint.toString())) {
  222. return;
  223. }
  224. saveTokenAccount(accountData.baseMint, accountData);
  225. } catch (e) {
  226. logger.error({ ...accountData, error: e }, `Failed to process market`);
  227. }
  228. }
  229. async function buy(
  230. accountId: PublicKey,
  231. accountData: LiquidityStateV4,
  232. ): Promise<void> {
  233. let tokenAccount = existingTokenAccounts.get(accountData.baseMint.toString());
  234. if (!tokenAccount) {
  235. // it's possible that we didn't have time to fetch open book data
  236. const market = await getMinimalMarketV3(
  237. solanaConnection,
  238. accountData.marketId,
  239. commitment,
  240. );
  241. tokenAccount = saveTokenAccount(accountData.baseMint, market);
  242. }
  243. tokenAccount.poolKeys = createPoolKeys(
  244. accountId,
  245. accountData,
  246. tokenAccount.market!,
  247. );
  248. const { innerTransaction, address } = Liquidity.makeSwapFixedInInstruction(
  249. {
  250. poolKeys: tokenAccount.poolKeys,
  251. userKeys: {
  252. tokenAccountIn: quoteTokenAssociatedAddress,
  253. tokenAccountOut: tokenAccount.address,
  254. owner: wallet.publicKey,
  255. },
  256. amountIn: quoteAmount.raw,
  257. minAmountOut: 0,
  258. },
  259. tokenAccount.poolKeys.version,
  260. );
  261. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  262. commitment: commitment,
  263. });
  264. const messageV0 = new TransactionMessage({
  265. payerKey: wallet.publicKey,
  266. recentBlockhash: latestBlockhash.blockhash,
  267. instructions: [
  268. ComputeBudgetProgram.setComputeUnitLimit({ units: 400000 }),
  269. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 30000 }),
  270. createAssociatedTokenAccountIdempotentInstruction(
  271. wallet.publicKey,
  272. tokenAccount.address,
  273. wallet.publicKey,
  274. accountData.baseMint,
  275. ),
  276. ...innerTransaction.instructions,
  277. ],
  278. }).compileToV0Message();
  279. const transaction = new VersionedTransaction(messageV0);
  280. transaction.sign([wallet, ...innerTransaction.signers]);
  281. const signature = await solanaConnection.sendRawTransaction(
  282. transaction.serialize(),
  283. {
  284. maxRetries: 20,
  285. preflightCommitment: commitment,
  286. },
  287. );
  288. logger.info(
  289. {
  290. mint: accountData.baseMint,
  291. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  292. dexURL: `https://dexscreener.com/solana/${accountData.baseMint}?maker=${wallet.publicKey}`
  293. },
  294. 'Buy',
  295. );
  296. }
  297. function loadSnipeList() {
  298. if (!USE_SNIPE_LIST) {
  299. return;
  300. }
  301. const count = snipeList.length;
  302. const data = fs.readFileSync(path.join(__dirname, 'snipe-list.txt'), 'utf-8');
  303. snipeList = data
  304. .split('\n')
  305. .map((a) => a.trim())
  306. .filter((a) => a);
  307. if (snipeList.length != count) {
  308. logger.info(`Loaded snipe list: ${snipeList.length}`);
  309. }
  310. }
  311. function shouldBuy(key: string): boolean {
  312. return USE_SNIPE_LIST ? snipeList.includes(key) : true;
  313. }
  314. const runListener = async () => {
  315. await init();
  316. const runTimestamp = Math.floor(new Date().getTime() / 1000);
  317. const raydiumSubscriptionId = solanaConnection.onProgramAccountChange(
  318. RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
  319. async (updatedAccountInfo) => {
  320. const key = updatedAccountInfo.accountId.toString();
  321. const poolState = LIQUIDITY_STATE_LAYOUT_V4.decode(
  322. updatedAccountInfo.accountInfo.data,
  323. );
  324. const poolOpenTime = parseInt(poolState.poolOpenTime.toString());
  325. const existing = existingLiquidityPools.has(key);
  326. if (poolOpenTime > runTimestamp && !existing) {
  327. existingLiquidityPools.add(key);
  328. const _ = processRaydiumPool(updatedAccountInfo.accountId, poolState);
  329. }
  330. },
  331. commitment,
  332. [
  333. { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
  334. {
  335. memcmp: {
  336. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'),
  337. bytes: quoteToken.mint.toBase58(),
  338. },
  339. },
  340. {
  341. memcmp: {
  342. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'),
  343. bytes: OPENBOOK_PROGRAM_ID.toBase58(),
  344. },
  345. },
  346. {
  347. memcmp: {
  348. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'),
  349. bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]),
  350. },
  351. },
  352. ],
  353. );
  354. const openBookSubscriptionId = solanaConnection.onProgramAccountChange(
  355. OPENBOOK_PROGRAM_ID,
  356. async (updatedAccountInfo) => {
  357. const key = updatedAccountInfo.accountId.toString();
  358. const existing = existingOpenBookMarkets.has(key);
  359. if (!existing) {
  360. existingOpenBookMarkets.add(key);
  361. const _ = processOpenBookMarket(updatedAccountInfo);
  362. }
  363. },
  364. commitment,
  365. [
  366. { dataSize: MARKET_STATE_LAYOUT_V3.span },
  367. {
  368. memcmp: {
  369. offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'),
  370. bytes: quoteToken.mint.toBase58(),
  371. },
  372. },
  373. ],
  374. );
  375. logger.info(`Listening for raydium changes: ${raydiumSubscriptionId}`);
  376. logger.info(`Listening for open book changes: ${openBookSubscriptionId}`);
  377. if (USE_SNIPE_LIST) {
  378. setInterval(loadSnipeList, SNIPE_LIST_REFRESH_INTERVAL);
  379. }
  380. };
  381. runListener();