Documentation for agents: an index at /llms.txt, every docs page in one file at /llms-full.txt, and Markdown for any docs page by adding .md to its URL.

Skip to Content
ensforgeSDK

Utilities

Look up the name, coin type, content hash, duration, fuse, role and error helpers that @ensforge/sdk exports besides its actions.

Helpers exported from @ensforge/sdk (and the same from @ensforge/sdk/effect).

Name

Name.dnsDecode

Name from its DNS wire-format encoding, as returned by ENSv2 registries and the Universal Resolver. The labels are returned as stored, without normalizing them.

function dnsDecode(data: Hex): string
Decoding a canonical name
import { Name } from "@ensforge/sdk"

Name.dnsDecode(Name.dnsEncode("nick.eth")) // "nick.eth"

Errors:

  • InvalidInputError (INVALID_NAME) when the bytes are not a DNS-encoded name, or a label contains a dot.

Name.dnsEncode

DNS wire-format encoding of a name, as the Universal Resolver and ENSv2 registries expect.

function dnsEncode(name: string): Hex
Encoding a name for a resolver call
import { Name } from "@ensforge/sdk"

const dnsName = Name.dnsEncode("alice.eth")

Errors:

  • InvalidInputError (INVALID_NAME) when the name cannot be normalized.

Name.fromLabelhash

Encoded label for a labelhash whose plain label is unknown: [af2c…].

function fromLabelhash(hash: Hex): string
Showing an unknown label
import { Name } from "@ensforge/sdk"

const label = Name.fromLabelhash(Name.labelhash("alice"))

Name.getParent

Parent of a name, or null for top-level names and the root.

function getParent(name: string): string | null
Finding the parent
import { Name } from "@ensforge/sdk"

Name.getParent("sub.alice.eth") // "alice.eth"
Name.getParent("eth")           // null

Errors:

  • InvalidInputError (INVALID_NAME) when the name cannot be normalized.

Name.isValid

Whether name normalizes without error. It may still differ from its normalized form.

function isValid(name: string): boolean
Validating user input
import { Name } from "@ensforge/sdk"

Name.isValid("alice.eth") // true
Name.isValid("bad name")  // false

Name.labelhash

Keccak-256 hash of one label, normalizing it first. Encoded labels return their hash.

function labelhash(label: string): Hex
Hashing a label
import { Name } from "@ensforge/sdk"

const hash = Name.labelhash("alice")

Errors:

  • InvalidInputError (INVALID_NAME) when the label is empty, contains a dot or cannot be normalized.

Name.namehash

ENS node (EIP-137 namehash) of a name, normalizing it first.

function namehash(name: string): Hex
Computing a node
import { Name } from "@ensforge/sdk"

const node = Name.namehash("alice.eth")

Errors:

  • InvalidInputError (INVALID_NAME) when the name cannot be normalized.

Name.normalize

Normalizes an ENS name (ENSIP-15).

function normalize(name: string): string
  • "" is the root name and is returned as-is.
  • Uses viem's ENSIP-15 normalizer (ENSIP-15 rejects alternative full stops such as 。).
  • Encoded labels such as [af2c…] (64 hex digits) are kept, so names from indexers round-trip.
Normalizing user input
import { Name } from "@ensforge/sdk"

Name.normalize("Nick.ETH") // "nick.eth"

Errors:

  • InvalidInputError (INVALID_NAME) when a label cannot be normalized.

Name.parse

Splits a name into its labels, TLD and parent after normalizing it.

function parse(name: string): Parsed
Parsing a subname
import { Name } from "@ensforge/sdk"

Name.parse("pay.nick.eth")
// { labels: ["pay", "nick", "eth"], label: "pay", tld: "eth", parent: "nick.eth", is2ld: false, isSubname: true }

Errors:

  • InvalidInputError (INVALID_NAME) when the name cannot be normalized.

Name.toTokenId

ENSv1 .eth registrar token ID of a second-level name: the labelhash of its first label as a number. ENSv2 token IDs change over time; read them with name.getTokenId.

function toTokenId(name: string): bigint
Finding an ENSv1 token ID
import { Name } from "@ensforge/sdk"

const tokenId = Name.toTokenId("alice.eth")

Errors:

  • InvalidInputError (INVALID_NAME) when the name cannot be normalized.

Name.Parsed

Parts of a name.

type Parsed
FieldTypeDescription
labelsreadonly string[]Normalized labels, leftmost first.
labelstringLeftmost label, e.g. nick for nick.eth. Empty for the root name.
tldstringTop-level domain, e.g. eth. Empty for the root name.
parentstring | nullParent name, or null for top-level names and the root.
is2ldbooleanWhether the name is a second-level name such as nick.eth.
isSubnamebooleanWhether the name has two or more levels below its TLD, such as pay.nick.eth.

CoinType

CoinType.decodeAddress

Decodes the bytes of an ENS address record into a display address, or null when empty (or the zero address, for EVM coins).

function decodeAddress(coinType: bigint, data: Hex): string | null
Decoding an address record
import { CoinType } from "@ensforge/sdk"

const shown = CoinType.decodeAddress(CoinType.from("eth"), data)

Errors:

CoinType.encodeAddress

Encodes an address as the bytes stored in an ENS address record.

function encodeAddress(coinType: bigint, address: string): Hex

EVM addresses are stored as 20 raw bytes for any EVM coin type, including chains the codec library does not list. Other coins use @ensdomains/address-encoder.

Encoding an address record
import { CoinType } from "@ensforge/sdk"

const bytes = CoinType.encodeAddress(CoinType.from("eth"), address)

Errors:

  • InvalidInputError (INVALID_ADDRESS) when the address is invalid for the coin.

CoinType.from

Resolves any coin input to its numeric coin type.

function from(input: Input): bigint
Coin types
import { CoinType } from "@ensforge/sdk"

CoinType.from("btc")             // 0n
CoinType.from({ chainId: 8453 }) // 2147492101n (Base)

Errors:

CoinType.fromChainId

ENSIP-11 coin type of an EVM chain. Ethereum mainnet is 60.

function fromChainId(chainId: number): bigint
Coin type of a chain
import { CoinType } from "@ensforge/sdk"

CoinType.fromChainId(8453) // 2147492101n (Base)

Errors:

CoinType.isEvm

Whether a coin type is an EVM chain (Ethereum mainnet or ENSIP-11).

function isEvm(coinType: bigint): boolean
Telling EVM coins apart
import { CoinType } from "@ensforge/sdk"

CoinType.isEvm(CoinType.from("eth")) // true
CoinType.isEvm(CoinType.from("btc")) // false

CoinType.toChainId

EVM chain ID of a coin type, or null for non-EVM coins.

function toChainId(coinType: bigint): number | null
Recovering a chain ID
import { CoinType } from "@ensforge/sdk"

CoinType.toChainId(2147492101n) // 8453

CoinType.toSymbol

Symbol of a coin type, such as btc, or null when unknown.

function toSymbol(coinType: bigint): string | null
Naming a coin type
import { CoinType } from "@ensforge/sdk"

CoinType.toSymbol(0n) // "btc"

CoinType.Input

What identifies a coin: a symbol ("btc"), an EVM chain ({ chainId: 8453 }) or a numeric coin type.

type Input = string | bigint | { readonly chainId: number };

ContentHash

ContentHash.decode

Decodes the bytes of an ENS contenthash record, or returns null when empty.

function decode(data: Hex): Decoded | null
Decoding a content hash
import { ContentHash } from "@ensforge/sdk"

const decoded = ContentHash.decode(data)
decoded?.uri // "ipfs://…"

Errors:

  • InvalidInputError (INVALID_CONTENT_HASH) when the bytes are malformed or use an unsupported codec.

ContentHash.encode

Encodes a content URI as the bytes stored in an ENS contenthash record (ENSIP-7).

function encode(uri: string): Hex
Encoding an IPFS link
import { ContentHash } from "@ensforge/sdk"

ContentHash.encode("ipfs://bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi")

Errors:

ContentHash.toGatewayUrl

HTTP URL for a content URI through a gateway: ipfs:// and ipns:// through gateways.ipfs, ar:// through gateways.arweave and bzz:// through gateways.swarm. Unset gateways are the public defaults (https://ipfs.io, https://arweave.net, https://api.gateway.ethswarm.org). URIs without a gateway (onion://, sia://, anything else) are returned as-is.

function toGatewayUrl(uri: string, gateways?: Gateways | undefined): string
Using the client's gateways
import { ContentHash } from "@ensforge/sdk"

const contentHash = await ens.record.getContentHash({ name: "vitalik.eth" })
const url = contentHash && ContentHash.toGatewayUrl(contentHash.uri, ens.config.gateways)

ContentHash.Decoded

A decoded content hash.

type Decoded
FieldTypeDescription
protocolProtocol
valuestringThe identifier without scheme, e.g. a CID.
uristringprotocol://value.

ContentHash.Protocol

URI scheme of a supported content hash, e.g. ipfs in ipfs://bafy….

type Protocol = keyof typeof schemes;

Duration

Duration.days

n days in seconds.

function days(n: number | bigint): bigint
Extending by a month
import { Duration } from "@ensforge/sdk"

await ens.registration.renew({ names: "alice.eth", duration: Duration.days(30) })

Errors:

Duration.years

n 365-day years in seconds, as ENS registrars count them.

function years(n: number | bigint): bigint
A one-year registration
import { Duration } from "@ensforge/sdk"

await ens.registration.register({ names: "alice.eth", duration: Duration.years(1) })

Errors:

Fuse

Fuse.decode

Every fuse in mask, by name.

function decode(mask: number): Decoded
Reading a fuse mask
import { Fuse } from "@ensforge/sdk"

const { cannotUnwrap, cannotTransfer } = Fuse.decode(Fuse.from(["cannotUnwrap"]))

Fuse.from

Fuse mask with every fuse in names burned.

function from(names: readonly Name[]): number
Building a fuse mask
import { Fuse } from "@ensforge/sdk"

const mask = Fuse.from(["cannotUnwrap", "cannotSetResolver"])

Errors:

Fuse.has

Whether name is burned in mask.

function has(mask: number, name: Name): boolean
Checking one fuse
import { Fuse } from "@ensforge/sdk"

const locked = Fuse.has(Fuse.from(["cannotUnwrap"]), "cannotUnwrap")

Fuse.Decoded

Every fuse with whether it is burned.

type Decoded = { readonly [name in Name]: boolean };

Fuse.Name

An ENSv1 NameWrapper fuse name.

type Name = keyof typeof fuses;

Role

Role.admin

Admin role that grants and revokes name, e.g. setResolver → setResolverAdmin.

function admin<const name extends Name>(name: name): `${name}Admin`
Granting a role with its admin
import { Role } from "@ensforge/sdk"

const bitmap = Role.from(["setText", Role.admin("setText")])

Role.from

Bitmap with every role in names set.

function from(names: readonly Name[]): bigint
Building a bitmap
import { Role } from "@ensforge/sdk"

Role.from(["setText", "setAddr"])

Errors:

Role.has

Whether bitmap has every role in names.

function has(bitmap: bigint, names: Name | readonly Name[]): boolean
Checking roles
import { Role } from "@ensforge/sdk"

const bitmap = Role.from(["setText", "setAddr"])
Role.has(bitmap, "setText")                // true
Role.has(bitmap, ["setText", "setAddr"])  // true

Errors:

Role.registry

Registry role bits from contracts-v2 v1.0.1 (canTransfer is 1n << 28n).

const registry: typeof Roles.registry
Reading a registry role
import { Role } from "@ensforge/sdk"

const canRenew = Role.registry.renew

Role.resolver

PermissionedResolver role bits from contracts-v2 v1.0.1.

const resolver: typeof Roles.resolver
Reading a resolver role
import { Role } from "@ensforge/sdk"

const canSetText = Role.resolver.setText

Role.toNames

Names of the roles set in bitmap for a registry or resolver.

function toNames(bitmap: bigint, target: Target): readonly Name[]
Listing roles
import { Role } from "@ensforge/sdk"

Role.toNames(Role.from(["setText"]), "resolver") // ["setText"]

Role.Name

A registry or resolver role name.

type Name = keyof typeof registry | keyof typeof resolver;

Role.Target

Which contract a role bitmap belongs to. Registry and resolver roles share bit positions.

type Target = "registry" | "resolver";

Errors

Errors.describe

Turns any thrown value into a title, message and suggested action that are safe to show users.

function describe<error extends EnsforgeError = AnyError>(value: unknown, options: DescribeOptions<error> = {}): Description

Use in UI error handlers instead of showing error.message, which is written for developers.

  • Accepts any value; non-ensforge errors go through Errors.fromCause first.
  • Packages that extend ensforge, such as @ensforge/hca, add copy for their own codes; a code without copy gets the generic UNEXPECTED copy.
  • Override copy per code with messages, for example to translate.
Showing an error toast
import { Errors } from "@ensforge/sdk"

try {
  await ens.record.set({ name: "alice.eth", texts: { url: "https://alice.dev" } })
} catch (error) {
  const { title, message, action } = Errors.describe(error)
  toast({ title, description: action === undefined ? message : `${message} ${action}` })
}
Translating one code
import { Errors } from "@ensforge/sdk"

Errors.describe(error, {
  messages: { NAME_NOT_AVAILABLE: (e) => ({ title: "Nombre no disponible", message: `${e.context.name} ya está registrado.` }) },
})

Errors.fromCause

Translates any thrown value into an ensforge error and adds context.

function fromCause(cause: unknown, context?: EnsforgeError.Context): EnsforgeError

Use when calling viem directly next to ensforge actions, to get the same error classes, codes and Errors.describe messages. Every ensforge action already does this.

  • ensforge errors are returned as-is, with context merged in.
  • viem errors are matched along their cause chain; contract reverts are decoded against every ENS contract error, unwrapping ResolverError and the mainnet ResolutionError.
  • Anything else becomes InternalError (UNEXPECTED) with the original as cause.
Translating a viem error
import { Errors } from "@ensforge/sdk"

try {
  await walletClient.writeContract(request)
} catch (cause) {
  const error = Errors.fromCause(cause, { operation: "custom.write" })
  toast(Errors.describe(error).title)
}

Errors.hasCode

Returns a type guard that matches ensforge errors with one of codes.

function hasCode<const codes extends readonly Code[]>(...codes: codes)
Branching on a code
import { Errors } from "@ensforge/sdk"

if (Errors.hasCode("NAME_NOT_AVAILABLE", "NAME_RESERVED")(error)) suggestAlternatives()

Errors.is

Whether value is an ensforge error. Uses a brand instead of instanceof, so it also works when two copies of @ensforge/sdk are installed.

function is(value: unknown): value is AnyError

Errors.setConfig

Changes global error settings, e.g. to point docsUrl at a self-hosted docs mirror.

function setConfig(config: Partial<Config>): void

Errors.AnyError

Every error class ensforge throws.

type AnyError = | Classes.CommitmentError | Classes.ConfigError | Classes.ContractRevertError | Classes.DnsError | Classes.GatewayError | Classes.IndexerError | Classes.InsufficientFundsError | Classes.InternalError | Classes.InvalidInputError | Classes.MigrationError | Classes.NameStateError | Classes.NetworkError | Classes.NotFoundError | Classes.PlanError | Classes.TransactionError | Classes.UnauthorizedError | Classes.UnsupportedError | Classes.UserRejectedError | Classes.WalletError;

Errors.Code

Every error code. Codes are stable: renaming or removing one is a breaking change.

type Code = AnyError["code"];

Errors.CommonError

Errors every action can fail with, besides the ones its @throws documents: a misconfigured client or a contract missing on the chain (ConfigError, CONTRACT_NOT_DEPLOYED), a failing RPC (NetworkError), a contract call reverting with an error ensforge does not map (ContractRevertError), and anything ensforge could not translate (InternalError UNEXPECTED).

type CommonError = | Classes.ConfigError | Classes.ContractRevertError | Classes.InternalError | Classes.NetworkError;

Errors.Config

Global error settings.

type Config
OptionTypeDefaultDescription
docsOrigin (required)stringOrigin of the documentation site used in docsUrl. @default "https://ensforge.com"

Errors.DescribeOptions

Options for describe. error is the union of error classes whose codes messages may override: every sdk error by default; add a package's class to override its codes too, e.g. DescribeOptions<Errors.AnyError | HcaError>.

type DescribeOptions<error extends EnsforgeError = AnyError>
OptionTypeDefaultDescription
messages{ readonly [code in EnsforgeError["code"]]?: ( EnsforgeError: EnsforgeError extends { readonly code: infer codes } ? code extends codes ? EnsforgeError : never : never, ) => Partial<Copy>; }Replacement copy by code, e.g. translations. Missing fields fall back to the English copy.

Errors.Description

User-facing description of an error.

type Description = Copy & { /** A code of `Errors.Code`, or of a package that extends ensforge (e.g. `HcaError`). */ readonly code: Code | (string & {}); readonly retryable: boolean; /** `info`: expected outcome; `warning`: temporary, retry later; `error`: needs attention. */ readonly severity: "info" | "warning" | "error"; };
FieldTypeDescription
titlestring
messagestring
action (optional)string
codeCode | (string & {})A code of Errors.Code, or of a package that extends ensforge (e.g. HcaError).
retryableboolean
severity"info" | "warning" | "error"info: expected outcome; warning: temporary, retry later; error: needs attention.

Errors.ErrorOf

The error class that can carry code, e.g. ErrorOf<"MISSING_ROLES"> is UnauthorizedError.

type ErrorOf<code extends Code> = AnyError extends infer error ? error extends { readonly code: infer codes } ? code extends codes ? error : never : never : never;

Errors.WriteError

Errors every write can fail with, besides the ones its @throws documents: CommonError and the errors of signing and sending, also on .prepare, .simulate, .estimateGas and the …Sync form.

type WriteError = | CommonError | Classes.InsufficientFundsError | Classes.TransactionError | Classes.UnsupportedError | Classes.UserRejectedError | Classes.WalletError;
  • WalletError, or ConfigError (WALLET_NOT_CONFIGURED), when the wallet cannot sign.
  • UserRejectedError when the wallet's user declines.
  • InsufficientFundsError (INSUFFICIENT_ETH) when the account cannot pay for gas or the ETH the call sends.
  • UnsupportedError (WALLET_BATCH_UNSUPPORTED) when the wallet cannot send a batch.
  • TransactionError when a transaction reverts, conflicts or is not mined in time.
  • A via route can also fail with its own package's errors (e.g. HcaError).

Was this page helpful?