Skip to content

Instantly share code, notes, and snippets.

@BlockmanCodes
Created August 21, 2023 23:13
Show Gist options
  • Save BlockmanCodes/c9bd0129c71db5e3c18e327a307f367b to your computer and use it in GitHub Desktop.
Save BlockmanCodes/c9bd0129c71db5e3c18e327a307f367b to your computer and use it in GitHub Desktop.
EthersJS: query, filter, and decode event logs
require('dotenv').config()
const ethers = require("ethers")
// ie: -> Flash(address,address,uint256,uint256,uint256,uint256)
const getEventSignature = (eventName, abi) => {
const eventAbi = abi.find((entry) => entry.name === eventName);
const types = eventAbi.inputs.map((input) => input.type);
return `${eventName}(${types.join(',')})`;
}
const main = async () => {
const provider = new ethers.providers.JsonRpcProvider(process.env.INFURA_URL)
const USDC_ETH_V3 = '0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640';
const contractAbi = [
{
"anonymous": false,
"inputs": [
{"indexed": true, "internalType": "address", "name": "sender", "type": "address"},
{"indexed": true, "internalType": "address", "name": "recipient", "type": "address"},
{"indexed": false, "internalType": "int256", "name": "amount0", "type": "int256"},
{"indexed": false, "internalType": "int256", "name": "amount1", "type": "int256"},
{"indexed": false, "internalType": "uint160", "name": "sqrtPriceX96", "type": "uint160"},
{"indexed": false, "internalType": "uint128", "name": "liquidity", "type": "uint128"},
{"indexed": false, "internalType": "int24", "name": "tick", "type": "int24"}
],
"name": "Swap",
"type": "event"
},
]
const eventSignature = getEventSignature('Swap', contractAbi)
console.log('-------------')
console.log(eventSignature)
console.log('-------------')
const filter = {
address: USDC_ETH_V3,
topics: [
ethers.utils.id(eventSignature),
],
fromBlock: 17957558,
toBlock: 17957658,
};
const result = await provider.getLogs(filter)
const contractInterface = new ethers.utils.Interface(contractAbi);
result.forEach((log, idx) => {
const decodedLog = contractInterface.decodeEventLog('Swap', log.data, log.topics);
console.log('--------------', idx)
console.log('sender: ', decodedLog.sender)
console.log('recipient: ', decodedLog.recipient)
console.log('amount0: ', decodedLog.amount0.toString())
console.log('amount1: ', decodedLog.amount1.toString())
console.log('sqrtPriceX96:', decodedLog.sqrtPriceX96.toString())
console.log('liquidity: ', decodedLog.liquidity.toString())
console.log('tick: ', decodedLog.tick)
console.log('--------------')
});
}
/*
node scripts/04_getLogsAndDecode.js
*/
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment