Skip to main content
edited tags
Link
Source Link

How to detect buy transactions on solana with websocket

I need to detect buy transactions on Solana, how can I do this? Does anyone have an example of how it could work? I created something, but without success so far, my biggest difficulty is identifying a buy transaction.

async function watchForBuys(params: any) {
    try {
        const connection = new Connection('https://solana-mainnet.core.chainstack.com/myapikey', 'confirmed');

        const socket = new WebSocket(params.websocketUrl);
        socket.on('open', () => {
            console.log('WebSocket open');
            socket.send(JSON.stringify({
                jsonrpc: '2.0',
                id: 1,
                method: 'logsSubscribe',
                params: [{ "mentions": [params.address] }, { "commitment": 'confirmed' }]
            }));
        });

        socket.on('message', async (data) => {
            const jsonData = JSON.parse(data.toString());
            if (jsonData.method === 'logsNotification') {
                const { result } = jsonData.params;
                if (result && result.value) {
                    //console.log("result", result)

                    const transaction: any = await connection.getTransaction(result.value.signature, {
                        //commitment: 'confirmed'
                        "maxSupportedTransactionVersion": 0
                    });

                    //console.log("transaction", transaction)

                    if (transaction) {
                        const isBuyTransaction = isBuyTransactionForToken(transaction.meta.logMessages, params.address);

                        console.log("isBuyTransaction", isBuyTransaction)
                        /* if (isBuyTransaction) {
                            const buyer = getTransactionParticipant(transaction, 'buyer');
                            const seller = getTransactionParticipant(transaction, 'seller');
                            const value = getTransactionValue(transaction);

                            console.log('Buyer:', buyer);
                            console.log('Seller:', seller);
                            console.log('Amount:', value);
                        } */
                    } else {
                        console.error('Transaction not valid.');
                    }
                }
            }
        });

        socket.on('close', (event) => {
            console.log('WebSocket close:', event);
        });
    } catch (error: any) {
        console.error('Error:', error.message);
    }
}

function isBuyTransactionForToken(logs: any, tokenAddress: any) {
    return logs.some((log: string | string[]) => log.includes('Instruction: Transfer') && log.includes(tokenAddress));
}

function getTransactionParticipant(transaction: any, role: any) {

}

function getTransactionValue(transaction: any) {
    
}