when i use a ENS name ,can't resolve it

Viewed 30

I'm trying to write my first etherjs code,get eth balance from viatalik.eth:

const balance = await provider.getBalance('vitalik.eth');

but it's failed:

Error: ENS name not configured (operation="resolveName(\"vitalik.eth\")", code=UNSUPPORTED_OPERATION, version=providers/5.7.1)
    at Logger.makeError (d:\sunflowerCode\etherjs\node_modules\@ethersproject\logger\lib\index.js:238:21)
    at Logger.throwError (d:\sunflowerCode\etherjs\node_modules\@ethersproject\logger\lib\index.js:247:20)
    at FallbackProvider.<anonymous> (d:\sunflowerCode\etherjs\node_modules\@ethersproject\providers\lib\base-provider.js:1980:36)
    at step (d:\sunflowerCode\etherjs\node_modules\@ethersproject\providers\lib\base-provider.js:48:23)
    at Object.next (d:\sunflowerCode\etherjs\node_modules\@ethersproject\providers\lib\base-provider.js:29:53)
    at fulfilled (d:\sunflowerCode\etherjs\node_modules\@ethersproject\providers\lib\base-provider.js:20:58)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  reason: 'ENS name not configured',
  code: 'UNSUPPORTED_OPERATION',
  operation: 'resolveName("vitalik.eth")'
}
1 Answers

Ethers is able to connect to multiple providers and switch between them. So the getDefaultProvider() function only retrieves the default one.

You can specify the provider RPC URL (see example below) that is already connected to some network (e.g. the mainnet). Or you can connect to a wallet API (e.g. MetaMask in a frontend app), then your app uses the currently selected network of the wallet. If you didn't specify any provider or wallet API, ethers then tries to connect to your local node at http://127.0.0.1:8545 by default.

If your local node is not available or is not connected to the mainnet, it cannot retrieve the mainnet ENS records.

So the solution is to connect to a mainnet provider (or to a wallet that is connected to a mainnet provider), and then you can query the ENS.

const ethers = require("ethers");
const provider = new ethers.providers.JsonRpcProvider("https://mainnet.infura.io/v3/<your_api_key>");
const balance = await provider.getBalance('vitalik.eth');
console.log(balance.toString()); // outputs `1183955717666208782618` at the moment

Docs: https://docs.ethers.io/v5/getting-started/#getting-started--connecting

Related