buy.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. let poolKeys = existingTokenAccounts.get(poolState.baseMint.toString())!.poolKeys;
  189. await sell(id, poolState, poolKeys as LiquidityPoolKeys);
  190. }
  191. } catch (e) {
  192. logger.error({ ...poolState, error: e }, `Failed to process pool`);
  193. }
  194. }
  195. export async function processOpenBookMarket(
  196. updatedAccountInfo: KeyedAccountInfo,
  197. ) {
  198. let accountData: MarketStateV3 | undefined;
  199. try {
  200. accountData = MARKET_STATE_LAYOUT_V3.decode(
  201. updatedAccountInfo.accountInfo.data,
  202. );
  203. // to be competitive, we collect market data before buying the token...
  204. if (existingTokenAccounts.has(accountData.baseMint.toString())) {
  205. return;
  206. }
  207. saveTokenAccount(accountData.baseMint, accountData);
  208. } catch (e) {
  209. logger.error({ ...accountData, error: e }, `Failed to process market`);
  210. }
  211. }
  212. async function buy(
  213. accountId: PublicKey,
  214. accountData: LiquidityStateV4,
  215. ): Promise<void> {
  216. let tokenAccount = existingTokenAccounts.get(accountData.baseMint.toString());
  217. if (!tokenAccount) {
  218. // it's possible that we didn't have time to fetch open book data
  219. const market = await getMinimalMarketV3(
  220. solanaConnection,
  221. accountData.marketId,
  222. commitment,
  223. );
  224. tokenAccount = saveTokenAccount(accountData.baseMint, market);
  225. }
  226. tokenAccount.poolKeys = createPoolKeys(
  227. accountId,
  228. accountData,
  229. tokenAccount.market!,
  230. );
  231. const { innerTransaction, address } = Liquidity.makeSwapFixedInInstruction(
  232. {
  233. poolKeys: tokenAccount.poolKeys,
  234. userKeys: {
  235. tokenAccountIn: quoteTokenAssociatedAddress,
  236. tokenAccountOut: tokenAccount.address,
  237. owner: wallet.publicKey,
  238. },
  239. amountIn: quoteAmount.raw,
  240. minAmountOut: 0,
  241. },
  242. tokenAccount.poolKeys.version,
  243. );
  244. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  245. commitment: commitment,
  246. });
  247. const messageV0 = new TransactionMessage({
  248. payerKey: wallet.publicKey,
  249. recentBlockhash: latestBlockhash.blockhash,
  250. instructions: [
  251. ComputeBudgetProgram.setComputeUnitLimit({ units: 400000 }),
  252. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 30000 }),
  253. createAssociatedTokenAccountIdempotentInstruction(
  254. wallet.publicKey,
  255. tokenAccount.address,
  256. wallet.publicKey,
  257. accountData.baseMint,
  258. ),
  259. ...innerTransaction.instructions,
  260. ],
  261. }).compileToV0Message();
  262. const transaction = new VersionedTransaction(messageV0);
  263. transaction.sign([wallet, ...innerTransaction.signers]);
  264. const signature = await solanaConnection.sendRawTransaction(
  265. transaction.serialize(),
  266. {
  267. maxRetries: 20,
  268. preflightCommitment: commitment,
  269. },
  270. );
  271. logger.info(
  272. {
  273. mint: accountData.baseMint,
  274. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  275. },
  276. 'Buy',
  277. );
  278. }
  279. const maxRetries = 60;
  280. async function sell(
  281. accountId: PublicKey,
  282. accountData: LiquidityStateV4,
  283. poolKeys: LiquidityPoolKeys,
  284. ): Promise<void> {
  285. const tokenAccount = existingTokenAccounts.get(
  286. accountData.baseMint.toString(),
  287. );
  288. if (!tokenAccount) {
  289. return;
  290. }
  291. let retries = 0;
  292. let balanceFound = false;
  293. while (retries < maxRetries) {
  294. try {
  295. const balanceResponse = (await solanaConnection.getTokenAccountBalance(tokenAccount.address)).value.amount;
  296. if (balanceResponse !== null && Number(balanceResponse) > 0 && !balanceFound) {
  297. balanceFound = true;
  298. const { innerTransaction, address } = Liquidity.makeSwapFixedInInstruction(
  299. {
  300. poolKeys: poolKeys,
  301. userKeys: {
  302. tokenAccountIn: tokenAccount.address,
  303. tokenAccountOut: quoteTokenAssociatedAddress,
  304. owner: wallet.publicKey,
  305. },
  306. amountIn: new BN(balanceResponse),
  307. minAmountOut: 0,
  308. },
  309. poolKeys.version,
  310. );
  311. const latestBlockhash = await solanaConnection.getLatestBlockhash({
  312. commitment: commitment,
  313. });
  314. const messageV0 = new TransactionMessage({
  315. payerKey: wallet.publicKey,
  316. recentBlockhash: latestBlockhash.blockhash,
  317. instructions: [
  318. ComputeBudgetProgram.setComputeUnitLimit({ units: 400000 }),
  319. ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 200000 }),
  320. ...innerTransaction.instructions,
  321. ],
  322. }).compileToV0Message();
  323. const transaction = new VersionedTransaction(messageV0);
  324. transaction.sign([wallet, ...innerTransaction.signers]);
  325. const signature = await solanaConnection.sendRawTransaction(
  326. transaction.serialize(),
  327. {
  328. maxRetries: 5,
  329. preflightCommitment: commitment,
  330. },
  331. );
  332. logger.info(
  333. {
  334. mint: accountData.baseMint,
  335. url: `https://solscan.io/tx/${signature}?cluster=${network}`,
  336. },
  337. 'sell',
  338. );
  339. break;
  340. }
  341. } catch (error) {
  342. // logger.error(`Error while selling: ${error}`);
  343. }
  344. retries++;
  345. await new Promise((resolve) => setTimeout(resolve, 1000));
  346. }
  347. }
  348. function loadSnipeList() {
  349. if (!USE_SNIPE_LIST) {
  350. return;
  351. }
  352. const count = snipeList.length;
  353. const data = fs.readFileSync(path.join(__dirname, 'snipe-list.txt'), 'utf-8');
  354. snipeList = data
  355. .split('\n')
  356. .map((a) => a.trim())
  357. .filter((a) => a);
  358. if (snipeList.length != count) {
  359. logger.info(`Loaded snipe list: ${snipeList.length}`);
  360. }
  361. }
  362. function shouldBuy(key: string): boolean {
  363. return USE_SNIPE_LIST ? snipeList.includes(key) : true;
  364. }
  365. const runListener = async () => {
  366. await init();
  367. const runTimestamp = Math.floor(new Date().getTime() / 1000);
  368. const raydiumSubscriptionId = solanaConnection.onProgramAccountChange(
  369. RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
  370. async (updatedAccountInfo) => {
  371. const key = updatedAccountInfo.accountId.toString();
  372. const poolState = LIQUIDITY_STATE_LAYOUT_V4.decode(
  373. updatedAccountInfo.accountInfo.data,
  374. );
  375. const poolOpenTime = parseInt(poolState.poolOpenTime.toString());
  376. const existing = existingLiquidityPools.has(key);
  377. if (poolOpenTime > runTimestamp && !existing) {
  378. existingLiquidityPools.add(key);
  379. const _ = processRaydiumPool(updatedAccountInfo.accountId, poolState);
  380. }
  381. },
  382. commitment,
  383. [
  384. { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
  385. {
  386. memcmp: {
  387. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'),
  388. bytes: quoteToken.mint.toBase58(),
  389. },
  390. },
  391. {
  392. memcmp: {
  393. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'),
  394. bytes: OPENBOOK_PROGRAM_ID.toBase58(),
  395. },
  396. },
  397. {
  398. memcmp: {
  399. offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'),
  400. bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]),
  401. },
  402. },
  403. ],
  404. );
  405. const openBookSubscriptionId = solanaConnection.onProgramAccountChange(
  406. OPENBOOK_PROGRAM_ID,
  407. async (updatedAccountInfo) => {
  408. const key = updatedAccountInfo.accountId.toString();
  409. const existing = existingOpenBookMarkets.has(key);
  410. if (!existing) {
  411. existingOpenBookMarkets.add(key);
  412. const _ = processOpenBookMarket(updatedAccountInfo);
  413. }
  414. },
  415. commitment,
  416. [
  417. { dataSize: MARKET_STATE_LAYOUT_V3.span },
  418. {
  419. memcmp: {
  420. offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'),
  421. bytes: quoteToken.mint.toBase58(),
  422. },
  423. },
  424. ],
  425. );
  426. logger.info(`Listening for raydium changes: ${raydiumSubscriptionId}`);
  427. logger.info(`Listening for open book changes: ${openBookSubscriptionId}`);
  428. if (USE_SNIPE_LIST) {
  429. setInterval(loadSnipeList, SNIPE_LIST_REFRESH_INTERVAL);
  430. }
  431. };
  432. runListener();