Skip to content

Instantly share code, notes, and snippets.

@DanielVF
Created August 1, 2018 02:35
Show Gist options
  • Save DanielVF/86a44234fc9f3e4bff7f6ed69b02f132 to your computer and use it in GitHub Desktop.
Save DanielVF/86a44234fc9f3e4bff7f6ed69b02f132 to your computer and use it in GitHub Desktop.
Origin helper for debugging events
// Example usage:
//
// console.table(await debugEvents(origin.contractService, {fromBlock:175, topics:[]}))
//
async function debugEvents(contractService, options){
const web3 = contractService.web3
// Lookup table for contracts from bytecode
const contractNames = {}
const bytecodeToName = {}
const signatureToEvent = {}
// For each origin contract, make a lookup for its bytecode and events.
Object.entries(contractService).forEach((x)=>{
const name = x[0]
const contract = x[1]
if(contract.bytecode == undefined){ return }
// bytecode - remove initialization code, and a little more.
const endBytecodeStart = contract.bytecode.length - 500
const endBytecode = contract.bytecode.substring(endBytecodeStart)
bytecodeToName[endBytecode] = name
contract.abi.filter((x)=>x.type=="event").forEach((eventAbi)=>{
const signature = web3.eth.abi.encodeEventSignature(eventAbi)
signatureToEvent[signature] = eventAbi
})
})
// Get an origin contract name from an address
async function getContractName(address){
if(contractNames[address] !== undefined){
return contractNames[address]
}
const bytecode = await web3.eth.getCode(address)
const endBytecode = bytecode.substring(bytecode.length - 500)
if(bytecodeToName[endBytecode] !== undefined){
contractNames[address] = bytecodeToName[endBytecode]
return bytecodeToName[endBytecode]
}
contractNames[address] == "Other "+bytecode.length
return contractNames[address]
}
// Fetch all logs
const logs = await web3.eth.getPastLogs(options)
// Prefetch all contract bytecode, exactly one time per contract address.
await (async()=>{
let addresses = {}
logs.forEach((x)=>addresses[x.address]=true)
await Promise.all( Object.entries(addresses).map(async (x)=> {
return await getContractName(x[0])}
))
})
// Generate the output
return await Promise.all(logs.map(async (log)=>{
const contractType = await getContractName(log.address)
let eventAbi = signatureToEvent[log.topics[0]]
let row = {
'contractType': contractType,
'eventType': eventAbi!=undefined?eventAbi.name:undefined,
'blockNumber': log.blockNumber,
'transactionIndex': log.transactionIndex,
'logIndex': log.logIndex,
'transactionHash': log.transactionHash,
'address': log.address
}
if(eventAbi!=undefined){
const topics = eventAbi.anonymous
? log.topics
: log.topics.slice(1)
const decoded = web3.eth.abi.decodeLog(eventAbi.inputs, log.data, topics)
eventAbi.inputs.forEach((input)=>{
row[input.name] = decoded[input.name]
})
}
return row
}))
}
@DanielVF
Copy link
Author

DanielVF commented Aug 1, 2018

Here it is in action

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment