The provided code snippet is a TypeScript implementation for monitoring and tracking new liquidity pools created on the Raydium decentralized exchange (DEX) on the Solana blockchain. Below is an explanation of its key components and functionality:
Overview
The script uses Solana's Web3.js library to establish a connection to the blockchain and listens for specific program logs emitted by the Raydium program. When a new liquidity pool is initialized (via the initialize2 instruction), the script fetches the associated token accounts and displays their metadata.
Key Components
Dependencies and Constants:
@solana/web3.js: Used to interact with the Solana blockchain.
@solana/spl-token: Provides utilities for working with SPL tokens.
RAYDIUM_PUBLIC_KEY: The public key of the Raydium program.
HTTP_URL and WSS_URL: QuickNode HTTP and WebSocket endpoints for connecting to the Solana cluster.
Connection Setup:
typescript
const connection = new Connection(HTTP_URL, { wsEndpoint: WSS_URL });
This establishes a connection to the Solana blockchain using QuickNode's endpoints.
Listening for Logs:
The startConnection function listens for logs emitted by the Raydium program:
typescript
connection.onLogs(
programAddress,
({ logs, err, signature }) => {
if (err) return;
if (logs && logs.some(log => log.includes(searchInstruction))) {
console.log("Signature for 'initialize2':", `https://explorer.solana.com/tx/${signature}`);
fetchRaydiumMints(signature, connection);
}
},
"finalized"
);
It filters logs to identify transactions containing the initialize2 instruction, which is used to create new liquidity pools.
When such a log is found, it triggers the fetchRaydiumMints function.
User
Build final script version using all above. From begin to end. Provide me also how to install and usage.
Assistant
Final Script: Raydium Liquidity Pool Tracker
Below is the complete script to track new liquidity pools created on the Raydium DEX on the Solana blockchain. It uses Solana Web3.js and QuickNode for blockchain interaction.
Script
typescript
Fetching Token Accounts:
The fetchRaydiumMints function retrieves the token accounts involved in the transaction:
The script connects to the Solana blockchain using QuickNode endpoints.
It listens for logs from the Raydium program that include the initialize2 instruction.
When a matching log is found, it fetches the transaction details and identifies the token accounts for the new liquidity pool.
The script retrieves and displays metadata for the tokens in the pool.
Use Cases
Real-Time Monitoring: Developers can use this script to monitor new liquidity pools on Raydium in real-time.
DeFi Analytics: The metadata fetched can be used for analytics or to display information in a DeFi dashboard.
Liquidity Pool Tracking: Helps identify new pools for investment or research purposes.
Prerequisites
Node.js (version 18.16 or higher).
QuickNode account with Solana Mainnet endpoints.
Basic knowledge of Solana and DeFi concepts.
This script is a robust starting point for building applications that track and analyze liquidity pools on Raydium. For further customization, developers can integrate additional APIs or extend the functionality to include more detailed analytics.
import { Connection, PublicKey } from '@solana/web3.js';
import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
// Constants
const RAYDIUM_PUBLIC_KEY = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
const HTTP_URL = "YOUR_QUICKNODE_HTTP_ENDPOINT"; // Replace with your QuickNode HTTP endpoint
const WSS_URL = "YOUR_QUICKNODE_WSS_ENDPOINT"; // Replace with your QuickNode WebSocket endpoint
const RAYDIUM = new PublicKey(RAYDIUM_PUBLIC_KEY);
const INSTRUCTION_NAME = "initialize2";
// Establish connection
const connection = new Connection(HTTP_URL, {
wsEndpoint: WSS_URL
});
// Start monitoring logs for new liquidity pools
async function startConnection(connection: Connection, programAddress: PublicKey, searchInstruction: string): Promise<void> {
console.log("Monitoring logs for program:", programAddress.toString());
connection.onLogs(
programAddress,
({ logs, err, signature }) => {
if (err) return;
if (logs && logs.some(log => log.includes(searchInstruction))) {
console.log("Signature for 'initialize2':", `https://explorer.solana.com/tx/${signature}`);
fetchRaydiumMints(signature, connection);
}
},
"finalized"
);
}
// Fetch token accounts from the transaction
async function fetchRaydiumMints(txId: string, connection: Connection) {
try {
const tx = await connection.getParsedTransaction(txId, {
maxSupportedTransactionVersion: 0,
commitment: 'confirmed'
});
//@ts-ignore
const accounts = (tx?.transaction.message.instructions).find(ix => ix.programId.toBase58() === RAYDIUM_PUBLIC_KEY).accounts as PublicKey[];
if (!accounts) {
console.log("No accounts found in the transaction.");
return;
}
const tokenAIndex = 8;
const tokenBIndex = 9;
const tokenAAccount = accounts[tokenAIndex];
const tokenBAccount = accounts[tokenBIndex];
console.log("New LP Found");
await displayTokenMetadata(tokenAAccount, connection, "A");
await displayTokenMetadata(tokenBAccount, connection, "B");
} catch (error) {
console.log("Error fetching transaction:", txId, error);
return;
}
}
// Retrieve token metadata
async function getTokenMetadata(tokenAccount: PublicKey, connection: Connection): Promise<any> {
const accountInfo = await connection.getAccountInfo(tokenAccount);
if (!accountInfo) {
console.error(`Token account not found: ${tokenAccount.toBase58()}`);
return null;
}
const tokenInfo = await connection.getTokenAccountBalance(tokenAccount);
const mint = tokenInfo.value.mint;
const mintAccountInfo = await connection.getAccountInfo(new PublicKey(mint));
if (!mintAccountInfo) {
console.error(`Mint account not found: ${mint}`);
return null;
}
const tokenMetadata = await connection.getParsedAccountInfo(new PublicKey(mint), 'confirmed');
return tokenMetadata?.value?.data?.parsed?.info;
}
// Display token metadata
async function displayTokenMetadata(tokenAccount: PublicKey, connection: Connection, tokenLabel: string) {
const metadata = await getTokenMetadata(tokenAccount, connection);
if (metadata) {
console.log(`\nToken ${tokenLabel} Metadata:`);
console.log(`Mint: ${metadata.mint}`);
console.log(`Name: ${metadata.tokenName}`);
console.log(`Symbol: ${metadata.tokenSymbol}`);
console.log(`Decimals: ${metadata.decimals}`);
} else {
console.log(`Could not fetch metadata for Token ${tokenLabel}`);
}
}
// Start the tracker
startConnection(connection, RAYDIUM, INSTRUCTION_NAME).catch(console.error);
Installation and Setup
Install Node.js:
Ensure you have Node.js (version 18.16 or higher) installed. Download it from the official Node.js website.
Set Up the Project:
Create a new project directory and initialize it:
bash
mkdir raydium-lp-tracker
cd raydium-lp-tracker
npm init -y
Install Dependencies:
Install the required libraries:
Create the Script:
Save the provided script in a file named tracker.ts.
Set Up QuickNode Endpoints:
Replace YOUR_QUICKNODE_HTTP_ENDPOINT and YOUR_QUICKNODE_WSS_ENDPOINT in the script with your QuickNode HTTP and WebSocket endpoints.
Compile TypeScript:
If you want to compile the script to JavaScript, run:
bash
npx tsc tracker.ts
Usage
Run the Script:
Use ts-node to execute the script:
bash
npx ts-node tracker.ts
Monitor Output:
The script will listen for new liquidity pools created on Raydium.
When a new pool is detected, it will log the transaction signature and token metadata.
Example Output:
code
Monitoring logs for program: 675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8
Signature for 'initialize2': https://explorer.solana.com/tx/EXAMPLE_SIGNATURE
New LP Found
Token A Metadata:
Mint: EXAMPLE_MINT_A
Name: Example Token A
Symbol: EXA
Decimals: 6
Token B Metadata:
Mint: EXAMPLE_MINT_B
Name: Example Token B
Symbol: EXB
Decimals: 6
Notes
Ensure your QuickNode account has sufficient credits for WebSocket usage.
The script is designed for educational purposes and can be extended for production use by adding error handling, logging, and additional features.