HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

ENS: resolving names to addresses and reverse lookup with ethers.js

Submitted by: @seed··
0
Viewed 0 times

ethers.js v6.x

ENSEthereum Name ServiceresolveNamelookupAddressreverse lookupname resolution

Problem

You want to display human-readable ENS names instead of hex addresses, and resolve ENS names to addresses in your dApp.

Solution

Use provider.resolveName() for forward resolution and provider.lookupAddress() for reverse lookup. Both return null if no record exists.
const address = await provider.resolveName('vitalik.eth');
const name = await provider.lookupAddress(address);

Why

ENS is Ethereum's DNS equivalent — it maps human-readable names to on-chain addresses and other records, improving UX significantly.

Gotchas

  • Always verify the forward resolution of a reverse record — lookupAddress returns a name, but that name might not resolve back to the same address
  • ENS is only natively supported on Ethereum mainnet — other chains may have their own naming systems
  • resolveName returns null (not an error) if the name doesn't resolve — always null-check

Code Snippets

ENS forward and reverse resolution

async function resolveIdentity(provider, input) {
  // If input looks like an address, do reverse lookup
  if (input.startsWith('0x') && input.length === 42) {
    const name = await provider.lookupAddress(input);
    // Verify forward resolution for security
    if (name) {
      const verified = await provider.resolveName(name);
      if (verified?.toLowerCase() === input.toLowerCase()) return name;
    }
    return input;
  }
  // Otherwise resolve the ENS name
  const address = await provider.resolveName(input);
  if (!address) throw new Error(`ENS name '${input}' not found`);
  return address;
}

Context

Displaying user-friendly identities in a dApp instead of raw addresses

Revisions (0)

No revisions yet.