Is there any easy way to parse transaction logs in order to get information about: who sent the token who received the token what token has been transferred what was the price for that
?
Yes. Use web3 getPastEvents filtering the Transfer event.
https://web3js.readthedocs.io/en/v1.7.3/web3-eth-contract.html#getpastevents
Dev Advocate at Chainstack.
You can use a simple script to fetch and decode logs using ethers.js.
Here is an example to fetch the Transfer
event from the BAYC
collection:
const ethers = require('ethers');
// Initialize connection to the node.
const nodeUrl = "CHAINSTACK_NODE_URL";
const provider = new ethers.JsonRpcProvider(nodeUrl);
// Import and parse ABI for ERC-721 standard.
const abi = [
// Importing the 'Transfer' event part of the ABI for ERC-721.
"event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)"
];
// Create contract instance using an ERC-721 contract address and ABI.
// Replace this address with your desired ERC-721 token contract address.
const address = '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D';
const contract = new ethers.Contract(address, abi, provider)
async function getLogs() {
const range = 500; // Define the range of blocks you're interested in.
const latestBlock = await provider.getBlockNumber();
const from = latestBlock - range;
// queryFilter to get 'Transfer' event logs.
const transferEvents = await contract.queryFilter('Transfer', from, latestBlock);
return transferEvents;
}
async function main() {
const logs = await getLogs();
// Parse and log the details of each transfer.
for (let object of logs) {
console.log(`Transaction hash: ${object.transactionHash}`);
console.log(`From: ${object.args.from}`);
console.log(`To: ${object.args.to}`);
console.log(`Token ID transferred: ${object.args.tokenId.toString()} \n`);
}
}
main();
This will parse and decode the following fields:
And will give you a similar log:
Transaction hash: 0xdb662be3d9916db892036e37b5e02ed137261034e8db182271682ac1992c3220
From: 0x4Ec2F9588B7BD0f4976651d2B6c7315d6B866f15
To: 0xde02FFFb824720E25674a604BaF2277f21c66a0F
Token ID transferred: 4500
To fetch the price is a bit more complex. You could use the debug_traceTransaction method on the transaction hash to see all the internal steps and find out how much ETH was exchanged for the NFT.