buy.ts 13 KB

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