Yeah, the above mentioned approach works for Contract Addresses. Unfortunately, there is not any method in Web3js which will help us achieve this task. But, the way I did it was going from the 0 block-number to Latest. While going through I got all the transactions that happened in the block along with the details of the transaction.
Below is the code:
I have used web3.eth.getBlock, to get all transactions from the block.
function getAccountTransactions(accAddress, startBlockNumber, endBlockNumber) { // You can do a NULL check for the start/end blockNumber console.log("Searching for transactions to/from account \"" + accAddress + "\" within blocks " + startBlockNumber + " and " + endBlockNumber); for (var i = startBlockNumber; i <= endBlockNumber; i++) { var block = eth.getBlock(i, true); if (block != null && block.transactions != null) { block.transactions.forEach( function(e) { if (accAddress == "*" || accAddress == e.from || accAddress == e.to) { console.log(" tx hash : " + e.hash + "\n" + " nonce : " + e.nonce + "\n" + " blockHash : " + e.blockHash + "\n" + " blockNumber : " + e.blockNumber + "\n" + " transactionIndex: " + e.transactionIndex + "\n" + " from : " + e.from + "\n" + " to : " + e.to + "\n" + " value : " + e.value + "\n" + " gasPrice : " + e.gasPrice + "\n" + " gas : " + e.gas + "\n" + " input : " + e.input); } }) } } }
Example Transaction Details on Ropsten Etherscan
Find transactions to/from eth.accounts[0] address:
getTransactionsByAccount(eth.accounts[0]) endBlockNumber: 1575620 startBlockNumber: 1575619 Searching for transactions to/from account "0x87bae5d55603cfe2703062cea8bf76263fa0ca95" within blocks 1575619 and 1575620 tx hash : 0xd55f196cd4a41f518c84804ac6286972db1d0fa8e51d137e00299fb4906a51ab nonce : 12044 blockHash : 0xdac37667bca025e8107cea79b6b9bc5c1d86ddbec5a8b13615a2ce70bec63e60 blockNumber : 1575620 transactionIndex: 0 from : 0x87bae5d55603cfe2703062cea8bf76263fa0ca95 to : 0x60b634cf459c6e88dfb2a52311199a8473ed85b5 value : 0.000909211685644988 gasPrice : 20000000000 gas : 21000 input : 0x