6

I am simply trying to avoid the error:

Error: invalid address

web3 throws this error when the address to a contract is not valid.
Is there a way to catch this error ? I am using web3 in a nodejs app.

  • 3
    Natively: web3.isAddress([addr]) – o0ragman0o May 25 '17 at 0:13
11

There is an isAddress() method from web3.utils, you need to use version one or following version (v1-beta, now default and latest via npm)

Example:

web3.utils.isAddress(address)


Solidity Docs link: http://web3js.readthedocs.io/en/1.0/web3-utils.html?highlight=isValidAddress#isaddress

1

The formula for creating addresses is detailed in this post:

How are ethereum addresses generated?

Start with the public key (64 bytes)

Take the Keccak-256 hash of the public key. You should now have a string that is 32 bytes. (note: SHA3-256 eventually became the standard, but Ethereum uses Keccak)

Take the last 20 bytes of this public key (Keccak-256). Or, in other words, drop the first 12 bytes. These 20 bytes are the address, or 40 characters. When prefixed with 0x it becomes 42 characters long.

Basically an ethereum address can be any 40 hex alphanumeric character string + a prepend of 0x .

If you are just looking to check that the string you've got follows the ethereum address pattern, you can write a JS script to check that the string conforms to the criteria above.

1

You can use following code to test whether the address is valid or not.

if(isAddress(address)){
    //code when address is correct
}
else{
    // code to be executed when address is incorrect
}


var isAddress = function (address) {
    // function isAddress(address) {
        if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) {
        // check if it has the basic requirements of an address
        return false;
    } else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) {
        // If it's all small caps or all all caps, return "true
        return true;
    } else {
        // Otherwise check each case
        return isChecksumAddress(address);
    }
}


var isChecksumAddress = function (address) {
    // Check each case
    address = address.replace('0x','');
    var addressHash = web3.sha3(address.toLowerCase());
    for (var i = 0; i < 40; i++ ) {
        // the nth letter should be uppercase if the nth digit of casemap is 1
        if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) {
            return false;
        }
    }
    return true;
}

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.