6

How to detect empty address that has initial value of 0x0000000000000000000000000000000000000000 in web3.js?

What I'm doing now is:

if (address !== '0x0000000000000000000000000000000000000000') {
   ...
}

Is there any simpler way to filter out empty addresses or a helper method in web3 that can create this value(like address(0) in Solidity)? It's quite bothering to count(or type) exact number of all that 0s.

TylerH
  • 20,799
  • 66
  • 75
  • 101
viz
  • 1,247
  • 16
  • 27
  • 8
    Maybe `web3.toBigNumber(address).isZero()`? – user94559 Apr 20 '18 at 14:49
  • @smarx Really nice to know that web3 depends on BigNumber library. Why couldn't I think this way.. brilliant. – viz Apr 21 '18 at 14:19
  • 1
    You could post it as an answer and I can mark it accepted. Seems like your suggestion is the best I can think of so far. – viz Apr 21 '18 at 14:24

2 Answers2

4

Aside from @smarx's way: web3.toBigNumber(address).isZero()

You can use a simple regex, which is shorter:

const emptyAddress = /^0x0+$/.test(address);
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
  • Nice one! I think `/^0x0{40}$/` may be clearer since an address in ethereum is 20 bytes – viz May 25 '18 at 19:54
  • 1
    Yeah I know, but if you use: `web3.toHex(0)` it will only give you `0x0`, who knows, if ethereum increase the address length, this code will still work ;) – Marcos Casagrande May 25 '18 at 19:55
  • 1
    Good catch. That would be a case where you generate an empty address in web3 side. Thanks. – viz May 25 '18 at 19:59
2

You could also use OpenZeppelin's Test Helpers.

They have a constant called ZERO_ADDRESS which equals to zero address you mentioned.

More Info Here

Usage

First, you need to install:

npm install @openzeppelin/test-helpers

In JS file:

const constants = require('@openzeppelin/test-helpers');

console.log(constants.ZERO_ADDRESS);
Pang
  • 9,564
  • 146
  • 81
  • 122
remedcu
  • 526
  • 1
  • 10
  • 31