buy.ts 13 KB

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