Skip to content
This repository was archived by the owner on Aug 5, 2026. It is now read-only.
Draft
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions examples/ensnode-react-example/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 NameHash

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
20 changes: 20 additions & 0 deletions examples/ensnode-react-example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# ensnode-react Example

A minimal React app demonstrating how to use `@ensnode/ensnode-react` to resolve
an address' Mainnet Primary Name (via `usePrimaryName`).

By default it connects to the NameHash-hosted alpha ENSNode at
`https://api.alpha.ensnode.io`.

## Usage

```bash
pnpm install
pnpm -F @ensnode/ensnode-react-example dev
```

To point at a different ENSNode, set `VITE_ENSNODE_URL`:

```bash
VITE_ENSNODE_URL=http://localhost:4334 pnpm -F @ensnode/ensnode-react-example dev
```
12 changes: 12 additions & 0 deletions examples/ensnode-react-example/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ensnode-react Example</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
28 changes: 28 additions & 0 deletions examples/ensnode-react-example/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "@ensnode/ensnode-react-example",
"private": true,
"version": "0.0.1",
"license": "MIT",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"typecheck": "tsgo --noEmit"
},
"dependencies": {
"@ensnode/datasources": "workspace:*",
"@ensnode/ensnode-react": "workspace:*",
"@ensnode/ensnode-sdk": "workspace:*",
"enssdk": "workspace:*",
"react": "catalog:",
"react-dom": "catalog:"
},
"devDependencies": {
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"@vitejs/plugin-react": "^4.5.2",
"typescript": "catalog:",
"vite": "catalog:"
}
}
36 changes: 36 additions & 0 deletions examples/ensnode-react-example/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { StrictMode } from "react";

import { createEnsNodeProviderOptions, EnsNodeProvider } from "@ensnode/ensnode-react";

import { IndexingStatusBadge } from "./components/IndexingStatusBadge";
import { RequireActiveConnection } from "./components/RequireActiveConnection";
import { ENSNODE_URL, EXPECTED_NAMESPACE } from "./config";
import { PrimaryNameView } from "./PrimaryNameView";

const options = createEnsNodeProviderOptions({ url: ENSNODE_URL });

export function App() {
return (
<StrictMode>
<EnsNodeProvider options={options}>
<main>
<header>
<h1>
<code>ensnode-react</code> Example App
</h1>
<p>
Configured ENSNode: <code>{ENSNODE_URL.href}</code>
<br />
Expected ENS namespace: <code>{EXPECTED_NAMESPACE}</code>
</p>
<IndexingStatusBadge />
</header>

<RequireActiveConnection>
<PrimaryNameView />
</RequireActiveConnection>
</main>
</EnsNodeProvider>
</StrictMode>
);
}
145 changes: 145 additions & 0 deletions examples/ensnode-react-example/src/PrimaryNameView.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import {
DEFAULT_EVM_CHAIN_ID,
type DefaultableChainId,
type NormalizedAddress,
toNormalizedAddress,
} from "enssdk";
import { useId, useMemo, useState } from "react";

import {
DatasourceNames,
type ENSNamespaceId,
getENSRootChain,
maybeGetDatasource,
} from "@ensnode/datasources";
import { usePrimaryName } from "@ensnode/ensnode-react";

import { EXPECTED_NAMESPACE } from "./config";

const DEFAULT_INPUT = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"; // vitalik.eth
const DEFAULT_ADDRESS: NormalizedAddress = toNormalizedAddress(DEFAULT_INPUT);

const REVERSE_RESOLVER_DATASOURCES = [
DatasourceNames.ReverseResolverBase,
DatasourceNames.ReverseResolverLinea,
DatasourceNames.ReverseResolverOptimism,
DatasourceNames.ReverseResolverArbitrum,
DatasourceNames.ReverseResolverScroll,
] as const;

interface ChainOption {
id: DefaultableChainId;
label: string;
}

/**
* Builds the ENSIP-19 chain options for the picker:
* default EVM chain (0), the ENS root chain, then any reverse-resolver chains
* exposed by the active namespace. Matches the composition in
* `apps/ensadmin/src/app/inspect/primary-name/page.tsx`.
*/
function getENSIP19ChainOptions(namespace: ENSNamespaceId): ChainOption[] {
const root = getENSRootChain(namespace);
const options: ChainOption[] = [
{ id: DEFAULT_EVM_CHAIN_ID, label: "Default EVM Chain Address (ENSIP-19)" },
{ id: root.id, label: `${root.name} — ENS Root` },
];

const seen = new Set<number>([DEFAULT_EVM_CHAIN_ID, root.id]);
for (const name of REVERSE_RESOLVER_DATASOURCES) {
const ds = maybeGetDatasource(namespace, name);
if (!ds || seen.has(ds.chain.id)) continue;
seen.add(ds.chain.id);
options.push({ id: ds.chain.id, label: ds.chain.name });
}

return options;
}

export function PrimaryNameView() {
const addressInputId = useId();
const chainSelectId = useId();

const chainOptions = useMemo(() => getENSIP19ChainOptions(EXPECTED_NAMESPACE), []);

const [address, setAddress] = useState<NormalizedAddress>(DEFAULT_ADDRESS);
const [chainId, setChainId] = useState<DefaultableChainId>(
getENSRootChain(EXPECTED_NAMESPACE).id,
);
const [input, setInput] = useState<string>(DEFAULT_INPUT);
const [inputError, setInputError] = useState<string | null>(null);

const { data, isLoading, error } = usePrimaryName({
address,
chainId,
accelerate: true,
});

const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
try {
setAddress(toNormalizedAddress(input.trim()));
setInputError(null);
} catch (err) {
setInputError(err instanceof Error ? err.message : "Invalid EVM address.");
}
};

return (
<section>
<h2>Primary Name</h2>
<p>
Resolves the ENSIP-19 Primary Name for an address on a selected chain using{" "}
<code>usePrimaryName</code>. Because ENSIP-19 is multichain, pick which chain's primary name
you want to read.
</p>

<form onSubmit={handleSubmit}>
<div>
<label htmlFor={addressInputId}>EVM Address</label>
<input
id={addressInputId}
type="text"
value={input}
onChange={(event) => setInput(event.target.value)}
placeholder="0x…"
aria-invalid={inputError !== null}
aria-describedby={inputError ? `${addressInputId}-error` : undefined}
style={{ width: "28rem" }}
/>
</div>

<div>
<label htmlFor={chainSelectId}>ENSIP-19 Chain</label>
<select
id={chainSelectId}
value={chainId}
onChange={(event) => setChainId(Number(event.target.value) as DefaultableChainId)}
>
{chainOptions.map((option) => (
<option key={option.id} value={option.id}>
{option.id} ({option.label})
</option>
))}
</select>
</div>

<button type="submit">Resolve</button>

{inputError && (
<p id={`${addressInputId}-error`} role="alert">
{inputError}
</p>
)}
</form>

{isLoading && <p>Loading…</p>}
{error && <p>Error: {error.message}</p>}
{data && (
<p>
Primary Name: <strong>{data.name ?? "(none)"}</strong>
</p>
)}
</section>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type { Duration, UnixTimestamp } from "enssdk";

import { useIndexingStatus } from "@ensnode/ensnode-react";
import { EnsApiIndexingStatusResponseCodes } from "@ensnode/ensnode-sdk";

function formatWorstCaseDistance(distance: Duration): string {
if (distance <= 60) return `${distance}s behind`;
if (distance <= 60 * 60) return `${Math.round(distance / 60)}m behind`;
if (distance <= 60 * 60 * 24) return `${Math.round(distance / (60 * 60))}h behind`;
return `${Math.round(distance / (60 * 60 * 24))}d behind`;
}

function formatSnapshotAge(snapshotTime: UnixTimestamp, now: UnixTimestamp): string {
const age = Math.max(0, now - snapshotTime);
if (age < 60) return `${age}s ago`;
if (age < 60 * 60) return `${Math.round(age / 60)}m ago`;
return `${Math.round(age / (60 * 60))}h ago`;
}

/**
* Compact indexing-status indicator inspired by the ENSAdmin `ProjectionInfo` info-icon.
*
* Polls the connected ENSNode's `/api/indexing-status` endpoint (via
* `useIndexingStatus`) and renders the worst-case projection distance plus
* snapshot freshness so consumers can see at a glance how far behind realtime
* the connected ENSNode is.
*/
export function IndexingStatusBadge() {
const { data, isLoading, error } = useIndexingStatus();

if (isLoading) {
return <output aria-live="polite">Indexing status: loading…</output>;
}

if (error) {
return <output aria-live="polite">Indexing status: unavailable</output>;
}

if (!data || data.responseCode !== EnsApiIndexingStatusResponseCodes.Ok) {
return <output aria-live="polite">Indexing status: unavailable</output>;
}

const { projectedAt, worstCaseDistance, snapshot } = data.realtimeProjection;

return (
<output
aria-live="polite"
title={`Snapshot captured ${formatSnapshotAge(snapshot.snapshotTime, projectedAt)}`}
>
Indexing status: {formatWorstCaseDistance(worstCaseDistance)} (snapshot{" "}
{formatSnapshotAge(snapshot.snapshotTime, projectedAt)})
</output>
);
}
Loading
Loading