Asymptix/vue-tronlink

View on GitHub
src/utils/Address.js

Summary

Maintainability
A
25 mins
Test Coverage
/**
 * Address validation functions
 * source: https://ethereum.stackexchange.com/a/1379/7804
 */
const Address = {

  /**
   * Checks if the given string is an address
   *
   * @method isAddress
   * @param {String} address the given HEX adress
   * @return {Boolean}
   */
  isHexAddress(address) {
    if (!/^(0x)?[0-9a-f]{42}$/i.test(address)) {
      // check if it has the basic requirements of an address
      return false
    } else if (/^(0x)?[0-9a-f]{42}$/.test(address) || /^(0x)?[0-9A-F]{42}$/.test(address)) {
      // If it's all small caps or all all caps, return true
      return true
    } else {
      // Otherwise check each case
      return this.isChecksumHexAddress(address)
    }
  },

  /**
   * Checks if the given string is a checksummed address
   *
   * @method isChecksumAddress
   * @param {String} address the given HEX adress
   * @return {Boolean}
   */
  isChecksumHexAddress(address) {
    // Check each case
    address = address.replace("0x", "")
    var addressHash = 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
  }

}

export default Address