buy.ts 11 KB

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