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 7 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 packages/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 packages/ensnode-react/example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# ensnode-react Example

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's super logical to put the ensnode-react-example inside examples/ensnode-react-example/ within the monorepo.

The context we have right now though is an unusual one. This ensnode-react-example app is important for us to ship right now for the purpose of internally refining how ensnode-react works so that we can make a plan for how best to integrate it into enskit. But at this time I don't think we want to be promoting the ensnode-react package. Therefore we also don't want to be promoting any example apps for ensnode-react.

I don't feel good about putting this app inside the root examples directory at this time. Could you please share your advice on a temporary alternative? For example, I'm thinking we stick it under docs temporarily.

These are all temporary steps, but everything we're doing here right now is very important. We need to have a maximally clear narrative to promote for how to integrate with ENSNode and that answer is enskit not ensnode-react. We therefore should take some special actions here now.

We also need to promote enskit integrations now and not later after we figure out how we want to integrate ensnode-react into enskit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lightwalker-eth I'd suggest we move it from the root examples directory, but place it inside the ensnode-react folder. Having it inside a docs folder just feels weird.

Once merged, and we work to remove ensnode-react, we can move the example to the correct folder once later when we come to delete the package.

wdyt


A minimal React app demonstrating how to use `@ensnode/ensnode-react` to resolve

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please see my other comments with key ideas that should be included here for the key goals of this example app:

  1. The bigger comment I shared several lines above in this file.
  2. The bigger comment I shared in examples/ensnode-react-example/src/App.tsx

I want to see this example app being an absolute A+ flawless bulletproof example of how an example app should manage the connection details with an ENSNode instance. This includes negotiating the connection itself, and the related validation and graceful / specialized error handling for that. It also includes maintaining an ongoing indexing status projection.

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
```
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
12 changes: 12 additions & 0 deletions packages/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 packages/ensnode-react/example/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "@ensnode/ensnode-react-example",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@notrab Can you please take the lead to wire up Vercel so that this example app can automatically get all the Vercel stuff working?

"private": true,
"version": "0.0.1",
"license": "MIT",
Comment on lines +1 to +5
"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:*",
Comment thread
notrab marked this conversation as resolved.
"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 packages/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>
);
}
147 changes: 147 additions & 0 deletions packages/ensnode-react/example/src/PrimaryNameView.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import {
type ChainId,
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;
}
Comment on lines +31 to +34

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Replace interface ChainOption with a type alias and document invariant once.

This should use a type alias per repo TS/TSX rules; keep any invariant documentation on that alias only.

Proposed change
-interface ChainOption {
-  id: DefaultableChainId;
-  label: string;
-}
+type ChainOption = {
+  /** ENSIP-19 chain selector value (defaultable or concrete chain id). */
+  id: DefaultableChainId;
+  label: string;
+};

As per coding guidelines, "**/*.{ts,tsx}: Use type aliases to document invariants; each invariant MUST be documented exactly once on its type alias".

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
interface ChainOption {
id: DefaultableChainId;
label: string;
}
type ChainOption = {
/** ENSIP-19 chain selector value (defaultable or concrete chain id). */
id: DefaultableChainId;
label: string;
};
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ensnode-react/example/src/PrimaryNameView.tsx` around lines 31 - 34,
Replace the interface declaration "interface ChainOption" with a type alias
"type ChainOption = { id: DefaultableChainId; label: string }" and move any
invariant documentation comments (the single-source-of-truth invariant text)
onto that type alias; ensure DefaultableChainId remains referenced as the id
type and remove the now-redundant interface declaration so the invariant is
documented exactly once on the alias.


/**
* 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`.
*/
// TODO: candidate for promotion to `@ensnode/datasources` (no React) duplicates the chain composition in `apps/ensadmin/src/app/inspect/primary-name/page.tsx` + `apps/ensadmin/src/lib/get-ensip19-supported-chain-ids.ts`.
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<ChainId>([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 {
Comment on lines +80 to +82
setAddress(toNormalizedAddress(input.trim()));
setInputError(null);
} catch (err) {
setInputError(err instanceof Error ? err.message : "Invalid EVM address.");
Comment on lines +78 to +86

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To investiate; FormEvent deprecated?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To investiate; FormEvent deprecated?

}
};

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))}
>
{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