I want to retrieve information on last 5-10 transaction hash created by a specific function in my smart contract. Is there any way I can get historical transaction hash ?
3 Answers
Finding all (or the last 5) transactions corresponding with a particular function call translates to: find transactions going to a specific address and then check the first bytes of the callData
to match the function signature. The function signature is calculated as e.g. bytes3(sha3("myFunction(uint256,string,address)"))
. This is what you have to look for.
The usual libraries (e.g. web3.js) or APIs dont provide this out of the box. But you could go with e.g. this etherscan API http://api.etherscan.io/api?module=account&action=txlist&address=0x807Aa96410f7cfF5614fD8DB6CbFa82d86B7029d&sort=asc
Let's suppose you store the returned JSON object in ob
, then you could extract the tx hashes of the transactions which led to a call of the function with the signature 0xdf78c1dd
via
ob.result.forEach(function(element){
if(element.input.startsWith("0xdf78c1dd"))
console.log("txHash: " + element.hash);
})
This repo (https://github.com/Great-Hill-Corporation/quickBlocks) has a tool called 'ethslurp' which will deliver that data directly to the command line. You give it an Ethereum address, it returns all regular transactions to that address. I am affiliated with this project, but it does exactly what you want.
You could log an event from the function in your contract that you're interested in, then query for the logs to get the transaction information you need. The logs include a transaction hash parameter, which you can then use to pull back more information on each transaction.
The event type you create will have a topic it corresponds with, you can query for a topic at a specific address, and get back all the logs. You can even give it ranges of blocks you want to look in: for example if you know you've checked all the blocks before #1000, then you can query just for the events that have happened since block 1000. If you don't want to keep track of when you last checked, you can use the filters feature of full nodes to keep track of logs since you last queried.