# ENS names (Ens)

ENS names, from the @ethect/core/ens entry point. A name to an address and back, text records and avatars.

ENS names: a name to an address and back, text records and avatars. The import is
`@ethect/core/ens`, an entry point of its own, and [the layer](https://ethect.dev/reference/ens/layer/) takes a
transport of its own, to a mainnet node: ENS lives on mainnet, whatever chain your app reads.
A lookup that finds nothing gives `Option.none`: it is not a failure.

```ts
import { Effect, Layer, Option } from "effect";
import { FetchHttpClient } from "effect/http";
import { Transport } from "@ethect/core";
import { Ens } from "@ethect/core/ens";

// A mainnet node, for the names alone.
const Names = Ens.layer().pipe(
  Layer.provide(Transport.http("https://ethereum-rpc.publicnode.com")),
  Layer.provide(FetchHttpClient.layer), // for offchain names and avatars
);

const program = Effect.gen(function* () {
  const address = yield* Ens.address("vitalik.eth"); // Option<Address>
  if (Option.isNone(address)) return "no address";
  const name = yield* Ens.name(address.value); // Option<string>, checked to point back
  const url = yield* Ens.text("vitalik.eth", "url");
  const avatar = yield* Ens.avatar("vitalik.eth"); // a URL an <img> can load
  return { address: address.value, name, url, avatar };
});

const found = await program.pipe(Effect.provide(Names), Effect.runPromise);
```

| Export | Kind | Description |
| --- | --- | --- |
| [`Ens.layer(options?)`](https://ethect.dev/reference/ens/layer/) | layer | ENS through its Universal Resolver, on the chain of the transport it is given. It needs an `HttpClient`, for offchain names and avatars. |
| [`Ens.address(name, options?)`](https://ethect.dev/reference/ens/address/) | function | The address a name points to. |
| [`Ens.name(address, options?)`](https://ethect.dev/reference/ens/name/) | function | The primary name of an address, checked to point back to it. |
| [`Ens.text(name, key)`](https://ethect.dev/reference/ens/text/) | function | A text record of a name. |
| [`Ens.avatar(name)`](https://ethect.dev/reference/ens/avatar/) | function | The avatar of a name, as a URL. |
| [`Ens.Ens`](#the-service) | service | A naming system: the four lookups. |
| [`Ens.Error`](#failures) | error | A name that cannot be asked about, a resolver that misbehaves, or a gateway that fails. |

## A name is normalised first

`Vitalik.ETH` and `vitalik.eth` are one name, and a name made to look like another must be
refused. Every lookup that takes a name normalises it before it is hashed, by the rules of
[ENSIP-15](https://docs.ens.domains/ensip/15). You pass the name as it was typed.

| Typed | Read as |
| --- | --- |
| `Vitalik.ETH` | `vitalik.eth` |
| an emoji with the selector that asks for one | the same emoji, without the selector |
| `vitаlik.eth`, with a Cyrillic `а` | refused: `illegal mixture: Latin + Cyrillic "а" {430}` |
| `a_b.eth` | refused: `underscore allowed only at start` |

- **The rules are ported**, not a dependency: the algorithm of the reference implementation,
  `@adraffy/ens-normalize`, with its tables for Unicode 17. It passes the 38,613 names of the
  validation set of ENSIP-15.
- **The Unicode tables are the library's own.** `String.prototype.normalize` is not used: its
  Unicode version is the one of the runtime, and a name must read the same in every browser.
- **A name that is refused fails** with an `EnsError` whose reason is `"InvalidName"`. Its
  message is `Not a valid name: `, then the reason in the words of the reference
  implementation. Nothing is sent.

## No answer is not a failure

A lookup gives an `Option`. `EnsError` is for what went wrong, never for what is not there.

| What happens | The lookup gives |
| --- | --- |
| the name has no resolver, or its resolver has no such record | `Option.none` |
| the record is empty, or the zero address | `Option.none` |
| the resolver of the name reverts | `Option.none` |
| a gateway of an offchain name refuses the lookup, with a 4xx | `Option.none` |
| the primary name of an address does not point back to it | `Option.none` |
| the name does not normalise | `EnsError`, `"InvalidName"` |
| the chain asked for is no chain id | `EnsError`, `"Resolver"` |
| a gateway of an offchain name does not answer | `EnsError`, `"Gateway"` |
| the Universal Resolver reverts, or an answer does not decode | `EnsError`, `"Resolver"` |
| the node does not answer | [`TransportError`](https://ethect.dev/reference/errors/transport-error/) or [`RpcError`](https://ethect.dev/reference/errors/rpc-error/) |

The first five are what viem gives `null` for. A resolver has no other way to say "not here"
than to revert, and a gateway than to answer 404: Coinbase's answers 404 for a `cb.id` name
nobody took. A gateway that is down is another matter, and is a failure here: the name may
well have an address.

## Failures

`Ens.Error` is a tagged error: its `_tag` is `"EnsError"`, and its `reason` says which kind.

```ts
import { Effect, Option } from "effect";
import { Ens } from "@ethect/core/ens";

// A form that takes a name: what to show for each outcome.
const recipient = (typed: string) =>
  Ens.address(typed).pipe(
    Effect.map(Option.match({ onNone: () => "This name has no address", onSome: String })),
    Effect.catchTag("EnsError", (error) =>
      Effect.succeed(
        error.reason === "InvalidName" ? `Not a name: ${error.message}` : "Try again later",
      ),
    ),
  );
```

| `reason` | When | `message` |
| --- | --- | --- |
| `"InvalidName"` | the name does not normalise | `Not a valid name: `, then the reason ENSIP-15 gives |
| `"Gateway"` | a server an offchain name sent the lookup to did not answer | which gateway, and what it did |
| `"Resolver"` | a contract reverted where it may not, answered what does not decode, or asked for a lookup it may not ask for | what it did |
| `"Resolver"` | what is asked for cannot be asked of a resolver: a `chainId` that is no chain id | what was given |

## Offchain names

A name may keep its records outside mainnet: on another chain, or in a database. Its resolver
then reverts with `OffchainLookup` ([EIP-3668](https://eips.ethereum.org/EIPS/eip-3668)): it
names servers to ask, called gateways, and the function to call back with their answer. Every
lookup follows this. `jesse.base.eth` resolves the same way `vitalik.eth` does.

**A gateway is a server someone else chose**: the owner of the name's resolver. What it is
sent:

| Sent | Not sent |
| --- | --- |
| the address of the contract that asks | the URL of your node |
| the call that contract wants answered: it holds the name, and the record asked for | your account, unless it is the address being looked up |
| what an HTTP request always carries: your IP address, and what your `HttpClient` adds to every request | a trace header: the ones Effect's client writes by default are turned off for these requests |

The request is a `GET` of the gateway's URL with `{sender}` and `{data}` replaced, or a `POST`
of `{ "data", "sender" }` as JSON when the URL has no `{data}`.

And it is bounded:

| Bound | Value |
| --- | --- |
| scheme of a gateway's URL | `https` only |
| lookups a read follows one after the other | 4 |
| requests one lookup makes, whatever it is told to ask | 256, and 16 at a time |
| time a gateway has to answer, its body included | 10 seconds |
| bytes read from gateways, all their answers of one lookup together | 10 MiB |

- **The Universal Resolver batches the lookups of the resolvers it asks.** The batch is not sent
  to a batch gateway: each query is asked of its own gateway from your program, as viem does.
  No server in between sees them all.
- **The gateways are asked in the order the contract gave them.** A 5xx, an answer that is not
  hex, a timeout or an answer too large goes on to the next. A 4xx stops there: the gateway
  refused.
- **A refusal is an answer.** The Universal Resolver is told, and says the name has no record:
  the lookup gives none. A gateway that did not answer at all fails the lookup, with which
  gateway and why.
- **The client you give is the one the gateways are asked with.** Give the names a plain one: a
  client that adds a key to every request for your node's sake would add it for the gateways.

### On a server: redirects

The `https` bound is on the URL a resolver names. A gateway can answer that request with a
redirect to anywhere, an address of your own network included, and whether it is followed is
up to the `HttpClient` you give: `FetchHttpClient` follows it. A program that resolves names
someone else typed, on a server, gives the names a client that does not:

```ts
import { Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { Transport } from "@ethect/core";
import { Ens } from "@ethect/core/ens";

const Client = FetchHttpClient.layer.pipe(
  Layer.provide(Layer.succeed(FetchHttpClient.RequestInit)({ redirect: "error" })),
);

const Names = Ens.layer().pipe(
  Layer.provide(Transport.http("https://ethereum-rpc.publicnode.com")),
  Layer.provide(Client),
);
```

A gateway that redirects then gives no answer, as one that is down: the next is asked, and the
lookup fails with an `EnsError` `"Gateway"` when none answers. A client that refuses private
addresses does the same job, and lets a redirect to a public address through. In a browser
the page's own rules apply, and there is nothing to do.

## What your bundle holds

The entry point is separate from `@ethect/core` so that an application that resolves no name
ships nothing of it. The tables of ENSIP-15 are the largest part.

| An application that | Ships, minified, beside `effect` |
| --- | --- |
| imports nothing from `@ethect/core/ens` | none of it |
| uses the four lookups and the layer | 80 kB, 43 kB compressed |
| of which normalisation: the tables, 27 kB, and the algorithm | 35 kB, 25 kB compressed |
| already reads contracts, and adds the names | 48 kB more |

The rest is what any read of a contract ships: the ABI codec, and the reader that merges reads.
The tables are read the first time a name is normalised, not when the module loads.

## The service

`Ens.Ens` is a service with the four lookups. `Ens.layer` provides ENS. A test, or another
naming system, provides its own.

```ts
import { Effect, Layer, Option } from "effect";
import { Address } from "@ethect/core";
import { Ens } from "@ethect/core/ens";

// In a test: one name, and no node.
const Fixed = Layer.succeed(Ens.Ens)({
  address: (name) => Effect.succeed(name === "alice.eth" ? Option.some(Address.zero) : Option.none()),
  name: () => Effect.succeedNone,
  text: () => Effect.succeedNone,
  avatar: () => Effect.succeedNone,
});

const found = Ens.address("alice.eth").pipe(Effect.provide(Fixed));
```

A name is never accepted where an address is expected: resolving one is a step you write.
