UNPKG

agsola-react-ens-address

Version:
60 lines (49 loc) 1.3 kB
import { getAddress } from 'viem' import { normalize } from '@ensdomains/eth-ens-namehash' export const ETH_ADDRESS_TYPE = { name: 'name', address: 'address', error: 'error' } export function isAddress(address) { try { getAddress(address) } catch (e) { return false } return true } function isEncodedLabelhash(hash) { return hash.startsWith('[') && hash.endsWith(']') && hash.length === 66 } function validateName(name) { const nameArray = name.split('.') const hasEmptyLabels = nameArray.some((label) => label.length == 0) if (hasEmptyLabels) throw new Error('Domain cannot have empty labels') const normalizedArray = nameArray.map((label) => { if (label === '[root]') { return label } else { return isEncodedLabelhash(label) ? label : normalize(label) } }) try { return normalizedArray.join('.') } catch (e) { throw e } } export function getEthAddressType(address) { if (!address) return ETH_ADDRESS_TYPE.error if (isAddress(address)) { return ETH_ADDRESS_TYPE.address } try { const validated = validateName(address) //console.log("validaname", validated) return ETH_ADDRESS_TYPE.name } catch (e) { //console.error("no valida el name", address) return ETH_ADDRESS_TYPE.error } }