I'm developing a Node.js script using Web3 to analyze swap transactions on the Binance Smart Chain (BSC). My goal is to determine, for a given transaction, which token was sold and which token was bought—using only the wallet address involved.
Currently, I rely on analyzing the Transfer
logs to calculate the net token transfer for each token. However, in many swap transactions the net effect per token is zero. This is because one token is sent out from the wallet and another token is received in the same transaction, making the individual net transfers appear as zero.
Below is a simplified version of my code:
const { Web3 } = require('web3');
const web3 = new Web3('/');
const toBN = (value) => Web3.utils.toBigInt(value);
const transferEventSig = Web3.utils.sha3("Transfer(address,address,uint256)");
const minABI = [
{
constant: true,
inputs: [],
name: "symbol",
outputs: [{ name: "", type: "string" }],
type: "function"
},
{
constant: true,
inputs: [],
name: "decimals",
outputs: [{ name: "", type: "uint8" }],
type: "function"
}
];
async function getTokenInfo(tokenAddress) {
try {
const contract = new web3.eth.Contract(minABI, tokenAddress);
const symbol = await contract.methods.symbol().call();
const decimals = await contract.methods.decimals().call();
return { symbol, decimals };
} catch (err) {
return { symbol: "Unknown", decimals: "?" };
}
}
async function analyzeTransaction(txHash) {
try {
const tx = await web3.eth.getTransaction(txHash);
const receipt = await web3.eth.getTransactionReceipt(txHash);
if (!tx || !receipt) {
console.log("❌ Transaction not found.");
return;
}
console.log("