Get the ENS name from an Ethereum address in your web3 dApp

Get the ENS name from an Ethereum address in your web3 dApp

In my previous tutorial, I explained how you can allow users to connect to your web3 dApp with their Ethereum address using Metamask. Now, let's take a little step further! You might have heard of Ethereum Name Service (ENS). That's all the .eth domains. The goal is to turn an ineffable blockchain address like: 0x390F8E93D55C0cF882286ec40CC2D13Ca0938708 into a neat human-readable name, in my case benjaminazoulay.eth. And your ENS name could 100% be used as your username on web3 site! We just need to learn how to get a ENS name from the address you got with web3.js.

It's not yet possible to do this using the web3.js library (I was also very disappointed). Fortunately we can use the ensjs library instead, which you can get with npm:

npm i @ensdomains/ensjs

For this tutorial, you can use any framework. I am using Nuxt.js like in my previous tutorial.

First things first, don't forget to import the library:

import ENS, { getEnsAddress } from '@ensdomains/ensjs'

The code snippet to get the ENS name from the address is simply:

const ens = new ENS({ provider: window.ethereum, ensAddress: getEnsAddress('1') });
let name = await ens.getName(coinbase)
const ensName = name.name

Here window.ethereum is the Ethereum provider and coinbase is the user's Ethereum address we got from web3.js. The getName() method returns an object looking like { name: 'name.eth' } so we grab that 'name' attribute. That attribute is null by default so if the user didn't set a ENS domain as reverse record, name will be null.

Inserted into the whole web3 connection methods, it looks like this:

async initWeb3 () {
      // Check for web3 provider
      if (typeof window.ethereum !== 'undefined') {
        try {
          const instance = new Web3(window.ethereum)
          console.log("instance", instance)
          // Get necessary info on your node
          const networkId = await instance.eth.net.getId();
          const coinbase = await instance.eth.getCoinbase();
          const balance = await instance.eth.getBalance(coinbase);
          // ENS
          const ens = new ENS({ provider: window.ethereum, ensAddress: getEnsAddress('1') });
          let name = await ens.getName(coinbase)
          const ensName = name.name
          // Save it to store
          this.registerWeb3Instance({
            networkId,
            coinbase,
            balance,
            ensName
          });
          this.metamaskMessage = '';
          this.onClose();
        } catch (error) {
          // User denied account access
          console.error('User denied web3 access', error);
          this.metamaskMessage = 'Please connect to your Ethereum address on Metamask before connecting to this website';
          return;
        }        
      }
      // No web3 provider
      else {
        console.error('No web3 provider detected');
        this.metamaskMessage = "No web3 provider detected. Did you install the Metamask extension on this browser?";
        return;
      }
    }

Don't forget to update the store mutation registerWeb3Instance:

registerWeb3Instance (state, payload) {
        console.log('registerWeb3instance Mutation being executed', payload)
        state.web3 = true
        let result = payload
        let web3Copy = {
          networkId: null,
          coinbase: null,
          balance: null,
          username: null,
        }
        web3Copy.coinbase = result.coinbase
        web3Copy.networkId = result.networkId
        web3Copy.balance = parseInt(result.balance, 10)
        web3Copy.username = result.ensName
        state.user = web3Copy
      },

And that's it, you can display the ENS name with user.username!

Again don't forget to check out my tutorial on how to connect to a Nuxt dApp with Metamask to get the full picture!

You can leave me a little tip if this tutorial helped you:

ETH - benjaminazoulay.eth

BTC - bc1q2sf9deqxcyveslk6efrrxga7ch3n7wr97klfs6

BCH - bitcoincash:qqqm7g4cewyrk2gexklqshjactr3w6mkm5c6v6qtjr