Filter out empty address in web3.js
Asked Answered
K

2

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.

Kordofanian answered 20/4, 2018 at 8:42 Comment(3)
Maybe web3.toBigNumber(address).isZero()? – Natelson
@smarx Really nice to know that web3 depends on BigNumber library. Why couldn't I think this way.. brilliant. – Kordofanian
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. – Kordofanian
R
4

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

You can use a simple regex, which is shorter:

const emptyAddress = /^0x0+$/.test(address);
Ralline answered 25/5, 2018 at 1:56 Comment(3)
Nice one! I think /^0x0{40}$/ may be clearer since an address in ethereum is 20 bytes 😎 – Kordofanian
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 ;) – Ralline
Good catch. That would be a case where you generate an empty address in web3 side. Thanks. – Kordofanian
T
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);
Transpadane answered 15/10, 2020 at 4:20 Comment(1)
Shouldn't it be const {constants} = require('@openzeppelin/test-helpers');? – Darrin

© 2022 - 2024 β€” McMap. All rights reserved.