Advice on accessing user transaction history

Hi,
I have a question about navigating transaction histories…

Lets say I have a smart contract that performs certain transactions for a user. These transactions might involve certain actions do do x,y,z.

Now lets say that user signs into my dapp and identifies themself with their eth address using metamask.

Lets say that I want my Dapp to display in a webpage all the transaction history of the user. Lets assume there are hundreds of transactions… maybe thousands.

So should I use web3 to somehow ‘trawl’ the eth blockchain (which might include paging many chunks) to find all the transactions for the user ? (and if so what functions do this?)

or

Should my smart contract really keep an internal mapping of of each users list of transactions e.g. mapping(address => SomeStructRepresentingTransaction[]) userTrans; and just have web3 access this (via a helper function in the smart contract)?

@filip

appreciate any advice
thanks

Hi @Emmett

If you want to retrieve transaction made by an address on a given contract you should retrieve events.
A good contract, emits a ‘transfer’ event every time a transaction is completed, then listen for past events with web3 (the documentation explains it perfectly: https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#getpastevents).

Happy coding,
Dani

1 Like

aha, interesting, so even if the events have happened way back in the past it looks like I can still page them by using the various fromBlock and filter options.

I had previously thought that events could only be consumed as they happened in real time…

thank you! :slight_smile:

1 Like

I was thinking some more on this… if I sent everything in events and then later these events were to be used to display ‘histories’… then isnt it true that my contract would not really need to store any mappings of (address=>SomeAction[]) “actions” ?

Wouldn’t that mean that events could contain fake info that may not even relate to any real transaction.

Or is the idea to also include the transaction hash in each event?