I am building a framework for ERC20 tokens.

Aim is to scan all events (Transfer and Approve) generated by ERC20 contract, for which I am using web3.js getPastEvents.

I have set the toBlock to web3.eth.getBlockNumber() i.e. latest block

Now, to avoid scanning unnecessary blocks, I have to set fromBlock option. Can someone explain how to get block's number of the block in which erc20 token was deployed?


There is no fast/elegant way to get the first transaction to an ethereum address/contract.

I will avoid scanning each block from the beginning.

What I will do is start from the top of the chain ( latest block) 10,000 blocks at a time and read all the events.

Once I get 0 events in the last 10,000 blocks I will stop.

That seems to be a working (not very elegant) solution.

  • 1
    Alternatively you can do a binary search on web3.eth.getCode to find the block it was created in.
    – natewelch_
    Jul 13 '18 at 21:35
  • Kindly elaborate, getcode return the compiled code of contract. How to parse the block number from it?
    – Karan
    Jul 14 '18 at 11:39
  • 1
    You can supply a block number to gerCode, so you can do a binary search on the results of that. If it returns bytecode, it's already been created. If it doesn't return bytecode then it hasn't been created yet.
    – natewelch_
    Jul 14 '18 at 12:05
  • Got it. in my method, I am storing the parsed events. If i run sequential/parallel queries for get code till the block where getCode returns nothing, net number of queries will be 2X (getCode + getAllEvents). your solution is better in terms of network data being returned, but for my use case it will make the script heavier..
    – Karan
    Jul 14 '18 at 13:03

If you are in the control of the smart contract, emit a 'Deployed' event in the constructor. Then scan for these events.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.