EthereumAddress.fromHex constructor

EthereumAddress.fromHex(
  1. String hex, {
  2. bool enforceEip55 = false,
})

Parses an Ethereum address from the hexadecimal representation. The representation must have a length of 20 bytes (or 40 hexadecimal chars), and can optionally be prefixed with "0x".

If enforceEip55 is true or the address has both uppercase and lowercase chars, the address must be valid according to EIP 55.

Implementation

factory EthereumAddress.fromHex(String hex, {bool enforceEip55 = false}) {
  if (!_basicAddress.hasMatch(hex)) {
    throw ArgumentError.value(
      hex,
      'address',
      'Must be a hex string with a length of 40, optionally prefixed with "0x"',
    );
  }

  if (!enforceEip55 &&
      (hex.toUpperCase() == hex || hex.toLowerCase() == hex)) {
    return EthereumAddress(hexToBytes(hex));
  }

  // Validates as of EIP 55, https://ethereum.stackexchange.com/a/1379
  final address = strip0x(hex);
  final hash = bytesToHex(keccakAscii(address.toLowerCase()));
  for (var i = 0; i < 40; i++) {
    // the nth letter should be uppercase if the nth digit of casemap is 1
    final hashedPos = int.parse(hash[i], radix: 16);
    if ((hashedPos > 7 && address[i].toUpperCase() != address[i]) ||
        (hashedPos <= 7 && address[i].toLowerCase() != address[i])) {
      throw ArgumentError(
        'Address has invalid case-characters and is'
        'thus not EIP-55 conformant, rejecting. Address was: $hex',
      );
    }
  }

  return EthereumAddress(hexToBytes(hex));
}