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): stringimport { 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): Heximport { 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): stringimport { 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 | nullimport { Name } from "@ensforge/sdk"
Name.getParent("sub.alice.eth") // "alice.eth"
Name.getParent("eth") // nullErrors:
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): booleanimport { Name } from "@ensforge/sdk"
Name.isValid("alice.eth") // true
Name.isValid("bad name") // falseName.labelhash
Keccak-256 hash of one label, normalizing it first. Encoded labels return their hash.
function labelhash(label: string): Heximport { 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): Heximport { 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.
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): Parsedimport { 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): bigintimport { 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| Field | Type | Description |
|---|---|---|
labels | readonly string[] | Normalized labels, leftmost first. |
label | string | Leftmost label, e.g. nick for nick.eth. Empty for the root name. |
tld | string | Top-level domain, e.g. eth. Empty for the root name. |
parent | string | null | Parent name, or null for top-level names and the root. |
is2ld | boolean | Whether the name is a second-level name such as nick.eth. |
isSubname | boolean | Whether 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 | nullimport { CoinType } from "@ensforge/sdk"
const shown = CoinType.decodeAddress(CoinType.from("eth"), data)Errors:
InvalidInputError(INVALID_COIN_TYPE) when no codec exists for the coin.InvalidInputError(INVALID_ADDRESS) when the bytes are not an address of the coin.
CoinType.encodeAddress
Encodes an address as the bytes stored in an ENS address record.
function encodeAddress(coinType: bigint, address: string): HexEVM 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.
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): bigintimport { CoinType } from "@ensforge/sdk"
CoinType.from("btc") // 0n
CoinType.from({ chainId: 8453 }) // 2147492101n (Base)Errors:
InvalidInputError(INVALID_COIN_TYPE) for unknown symbols or negative values.
CoinType.fromChainId
ENSIP-11 coin type of an EVM chain. Ethereum mainnet is 60.
function fromChainId(chainId: number): bigintimport { CoinType } from "@ensforge/sdk"
CoinType.fromChainId(8453) // 2147492101n (Base)Errors:
InvalidInputError(INVALID_COIN_TYPE) whenchainIdis not a valid chain ID.
CoinType.isEvm
Whether a coin type is an EVM chain (Ethereum mainnet or ENSIP-11).
function isEvm(coinType: bigint): booleanimport { CoinType } from "@ensforge/sdk"
CoinType.isEvm(CoinType.from("eth")) // true
CoinType.isEvm(CoinType.from("btc")) // falseCoinType.toChainId
EVM chain ID of a coin type, or null for non-EVM coins.
function toChainId(coinType: bigint): number | nullimport { CoinType } from "@ensforge/sdk"
CoinType.toChainId(2147492101n) // 8453CoinType.toSymbol
Symbol of a coin type, such as btc, or null when unknown.
function toSymbol(coinType: bigint): string | nullimport { 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 | nullimport { 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): Heximport { ContentHash } from "@ensforge/sdk"
ContentHash.encode("ipfs://bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi")Errors:
InvalidInputError(INVALID_CONTENT_HASH) for unsupported schemes or values.
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): stringimport { 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| Field | Type | Description |
|---|---|---|
protocol | Protocol | |
value | string | The identifier without scheme, e.g. a CID. |
uri | string | protocol://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): bigintimport { Duration } from "@ensforge/sdk"
await ens.registration.renew({ names: "alice.eth", duration: Duration.days(30) })Errors:
InvalidInputError(INVALID_DURATION) for negative or fractional values.
Duration.years
n 365-day years in seconds, as ENS registrars count them.
function years(n: number | bigint): bigintimport { Duration } from "@ensforge/sdk"
await ens.registration.register({ names: "alice.eth", duration: Duration.years(1) })Errors:
InvalidInputError(INVALID_DURATION) for negative or fractional values.
Fuse
Fuse.decode
Every fuse in mask, by name.
function decode(mask: number): Decodedimport { 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[]): numberimport { Fuse } from "@ensforge/sdk"
const mask = Fuse.from(["cannotUnwrap", "cannotSetResolver"])Errors:
InvalidInputError(INVALID_RECORD_VALUE) for unknown fuse names.
Fuse.has
Whether name is burned in mask.
function has(mask: number, name: Name): booleanimport { 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`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[]): bigintimport { Role } from "@ensforge/sdk"
Role.from(["setText", "setAddr"])Errors:
InvalidInputError(INVALID_ROLES) for unknown role names.
Role.has
Whether bitmap has every role in names.
function has(bitmap: bigint, names: Name | readonly Name[]): booleanimport { Role } from "@ensforge/sdk"
const bitmap = Role.from(["setText", "setAddr"])
Role.has(bitmap, "setText") // true
Role.has(bitmap, ["setText", "setAddr"]) // trueErrors:
InvalidInputError(INVALID_ROLES) for unknown role names.
Role.registry
Registry role bits from contracts-v2 v1.0.1 (canTransfer is 1n << 28n).
const registry: typeof Roles.registryimport { Role } from "@ensforge/sdk"
const canRenew = Role.registry.renewRole.resolver
PermissionedResolver role bits from contracts-v2 v1.0.1.
const resolver: typeof Roles.resolverimport { Role } from "@ensforge/sdk"
const canSetText = Role.resolver.setTextRole.toNames
Names of the roles set in bitmap for a registry or resolver.
function toNames(bitmap: bigint, target: Target): readonly Name[]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> = {}): DescriptionUse in UI error handlers instead of showing error.message, which is written for developers.
- Accepts any value; non-ensforge errors go through
Errors.fromCausefirst. - Packages that extend ensforge, such as
@ensforge/hca, add copy for their own codes; a code without copy gets the genericUNEXPECTEDcopy. - Override copy per code with
messages, for example to translate.
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}` })
}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): EnsforgeErrorUse 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
contextmerged in. - viem errors are matched along their
causechain; contract reverts are decoded against every ENS contract error, unwrappingResolverErrorand the mainnetResolutionError. - Anything else becomes
InternalError(UNEXPECTED) with the original ascause.
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)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 AnyErrorErrors.setConfig
Changes global error settings, e.g. to point docsUrl at a self-hosted docs mirror.
function setConfig(config: Partial<Config>): voidErrors.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| Option | Type | Default | Description |
|---|---|---|---|
docsOrigin (required) | string | Origin 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>| Option | Type | Default | Description |
|---|---|---|---|
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"; };| Field | Type | Description |
|---|---|---|
title | string | |
message | string | |
action (optional) | string | |
code | Code | (string & {}) | A code of Errors.Code, or of a package that extends ensforge (e.g. HcaError). |
retryable | boolean | |
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, orConfigError(WALLET_NOT_CONFIGURED), when the wallet cannot sign.UserRejectedErrorwhen 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.TransactionErrorwhen a transaction reverts, conflicts or is not mined in time.- A
viaroute can also fail with its own package's errors (e.g.HcaError).
Was this page helpful?