Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
930a910
checkpoint: initial draft from claude
shrugs Feb 1, 2026
0a03e2a
checkpoint: DRY find-domains a bit more
shrugs Feb 1, 2026
cdfa7cc
Merge branch 'main' into feat/domain-ordering
shrugs Feb 2, 2026
523a98c
fix: address PR review feedback for domain ordering
shrugs Feb 2, 2026
3ab13bf
docs(changeset): ENSv2 GraphQL API: Introduces order criteria for Dom…
shrugs Feb 2, 2026
992a7fe
fix: address PR bot review feedback for domain ordering
shrugs Feb 3, 2026
3ebdb64
docs: update findDomains algorithm comment to match implementation
shrugs Feb 3, 2026
55c09e6
refactor: simplify cursorFilter to accept DomainCursor object
shrugs Feb 3, 2026
5652b14
docs: add note about Drizzle tuple comparison limitation
shrugs Feb 4, 2026
ee9498c
fix: refactor resolver into shared helper
shrugs Feb 4, 2026
7132c0f
style: wrap long comment line
shrugs Feb 6, 2026
fefb300
feat: add debug logging of generated SQL in find-domains-resolver
shrugs Feb 6, 2026
e458e5d
refactor: locations and fix bigint cursor encoding
shrugs Feb 6, 2026
19670c8
fix: cursor pagination bugs with NULL values and direction mismatch
shrugs Feb 6, 2026
932fbc0
fix: domain-cursor encoding using superjson
shrugs Feb 10, 2026
eeb2b22
tell all agents to shut the fuck up
shrugs Feb 10, 2026
9885464
Merge branch 'main' into feat/domain-ordering
shrugs Feb 10, 2026
25d6f65
Merge branch 'main' into feat/domain-ordering
shrugs Feb 10, 2026
f4d5625
fix bot nits
shrugs Feb 10, 2026
d941511
fix: use head label for NAME ordering instead of leaf label
shrugs Feb 10, 2026
eb05617
fix: explicit casts in cursor tuple comparison and catch malformed cu…
shrugs Feb 10, 2026
151b542
fit bot nits
shrugs Feb 10, 2026
b584e51
fix: cast bigint correctly
shrugs Feb 10, 2026
551cd5e
fix: headLabel is never null
shrugs Feb 10, 2026
a3ab5af
tests: add some unit tests
shrugs Feb 10, 2026
618d7a8
feat: make top-level domain search a non-testing method
shrugs Feb 10, 2026
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
5 changes: 5 additions & 0 deletions .changeset/whole-ways-grin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ensapi": minor
---

ENSv2 GraphQL API: Introduces order criteria for Domain methods, i.e. `Account.domains(order: { by: NAME, dir: ASC })`. The supported Order criteria are `NAME`, `REGISTRATION_TIMESTAMP`, and `REGISTRATION_EXPIRY` in either `ASC` or `DESC` orders, defaulting to `NAME` and `ASC`.
1 change: 1 addition & 0 deletions apps/ensapi/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"pg-connection-string": "catalog:",
"pino": "catalog:",
"ponder-enrich-gql-docs-middleware": "^0.1.3",
"superjson": "^2.2.6",
"viem": "catalog:",
"zod": "catalog:"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { describe, expect, it } from "vitest";

import type { DomainId } from "@ensnode/ensnode-sdk";

import { DomainCursor } from "./domain-cursor";

describe("DomainCursor", () => {
describe("roundtrip encode/decode", () => {
it("roundtrips with a string value (NAME ordering)", () => {
const cursor: DomainCursor = {
id: "0xabc" as DomainId,
by: "NAME",
dir: "ASC",
value: "example",
};
expect(DomainCursor.decode(DomainCursor.encode(cursor))).toEqual(cursor);
});

it("roundtrips with a bigint value (REGISTRATION_TIMESTAMP ordering)", () => {
const cursor: DomainCursor = {
id: "0xabc" as DomainId,
by: "REGISTRATION_TIMESTAMP",
dir: "DESC",
value: 1234567890n,
};
expect(DomainCursor.decode(DomainCursor.encode(cursor))).toEqual(cursor);
});

it("roundtrips with a bigint value (REGISTRATION_EXPIRY ordering)", () => {
const cursor: DomainCursor = {
id: "0xdef" as DomainId,
by: "REGISTRATION_EXPIRY",
dir: "ASC",
value: 9999999999n,
};
expect(DomainCursor.decode(DomainCursor.encode(cursor))).toEqual(cursor);
});

it("roundtrips with a null value", () => {
const cursor: DomainCursor = {
id: "0xabc" as DomainId,
by: "REGISTRATION_TIMESTAMP",
dir: "ASC",
value: null,
};
expect(DomainCursor.decode(DomainCursor.encode(cursor))).toEqual(cursor);
});
});

describe("decode error handling", () => {
it("throws on garbage input", () => {
expect(() => DomainCursor.decode("not-valid-base64!!!")).toThrow("Invalid cursor");
});

it("throws on valid base64 but invalid json", () => {
const notJson = Buffer.from("not json", "utf8").toString("base64");
expect(() => DomainCursor.decode(notJson)).toThrow("Invalid cursor");
});

it("throws on empty string", () => {
expect(() => DomainCursor.decode("")).toThrow("Invalid cursor");
});
});
});
56 changes: 56 additions & 0 deletions apps/ensapi/src/graphql-api/lib/find-domains/domain-cursor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import superjson from "superjson";

import type { DomainId } from "@ensnode/ensnode-sdk";

import type { DomainOrderValue } from "@/graphql-api/lib/find-domains/types";
import type { DomainsOrderBy } from "@/graphql-api/schema/domain";
import type { OrderDirection } from "@/graphql-api/schema/order-direction";

/**
* Composite Domain cursor for keyset pagination.
* Includes the order column value to enable proper tuple comparison without subqueries.
*
* @dev A composite cursor is required to support stable pagination over the set, regardless of which
* column and which direction the set is ordered.
*/
export interface DomainCursor {
/**
* Stable identifier for tiebreaks.
*/
id: DomainId;

/**
* The criteria by which the set is ordered. One of NAME, REGISTRATION_TIMESTAMP, or REGISTRATION_EXPIRY.
*/
by: typeof DomainsOrderBy.$inferType;

/**
* The direction in which the set is ordered, either ASC or DESC.
*/
dir: typeof OrderDirection.$inferType;

Comment on lines +22 to +31
Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

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

DomainsOrderBy/OrderDirection are imported as type-only, but the DomainCursor interface uses typeof DomainsOrderBy.$inferType and typeof OrderDirection.$inferType (requires value-space access). This should be changed to use DomainsOrderByValue / OrderDirectionValue types, or import the enum refs as values.

Copilot uses AI. Check for mistakes.
/**
* The value of the sort column for this Domain in the set.
*/
value: DomainOrderValue;
}

/**
* Encoding/Decoding helper for Composite DomainCursors.
*
* @dev it's base64'd (super)json
*/
export const DomainCursor = {
encode: (cursor: DomainCursor) =>
Buffer.from(superjson.stringify(cursor), "utf8").toString("base64"),
// TODO: in the future, validate the cursor format matches DomainCursor
decode: (cursor: string): DomainCursor => {
try {
return superjson.parse<DomainCursor>(Buffer.from(cursor, "base64").toString("utf8"));
} catch {
throw new Error(
"Invalid cursor: failed to decode cursor. The cursor may be malformed or from an incompatible query.",
);
}
},
};
Original file line number Diff line number Diff line change
@@ -1,146 +1,9 @@
import { and, eq, like, Param, sql } from "drizzle-orm";
import { alias, unionAll } from "drizzle-orm/pg-core";
import type { Address } from "viem";
import { Param, sql } from "drizzle-orm";

import * as schema from "@ensnode/ensnode-schema";
import {
type DomainId,
type ENSv1DomainId,
type ENSv2DomainId,
interpretedLabelsToLabelHashPath,
type LabelHashPath,
type Name,
parsePartialInterpretedName,
} from "@ensnode/ensnode-sdk";
import type { ENSv1DomainId, ENSv2DomainId, LabelHashPath } from "@ensnode/ensnode-sdk";

import { db } from "@/lib/db";
import { makeLogger } from "@/lib/logger";
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

kept in find-domains.ts


const logger = makeLogger("find-domains");

const MAX_DEPTH = 16;

interface DomainFilter {
name?: Name | undefined | null;
owner?: Address | undefined | null;
}

/**
* Find Domains by Canonical Name.
*
* @throws if neither `name` or `owner` are provided
* @throws if `name` is provided but is not a valid Partial InterpretedName
*
* ## Terminology:
*
* - a 'Canonical Domain' is a Domain connected to either the ENSv1 Root or the ENSv2 Root. All ENSv1
* Domains are Canonical Domains, but an ENSv2 Domain may not be Canonical, for example if it exists
* in a disjoint nametree or its Registry does not declare a Canonical Domain.
* - a 'Partial InterpretedName' is a partial InterpretedName (ex: 'examp', 'example.', 'sub1.sub2.paren')
*
* ## Background:
*
* Materializing the set of Canonical Names in ENSv2 is non-trivial and more or less impossible
* within the confines of Ponder's cache semantics. Additionally retroactive label healing (due to
* new labels being discovered on-chain) is likely impossible within those constraints as well. If we
* were to implement a naive cache-unfriendly version of canonical name materialization, indexing time
* would increase dramatically.
*
* The overall user story we're trying to support is 'autocomplete' or 'search (my) domains'. More
* specifically, given a partial InterpretedName as input (ex: 'examp', 'example.', 'sub1.sub2.paren'),
* produce a set of Domains addressable by the provided partial InterpretedName.
*
* While complicated to do so, it is more correct to perform this calculation at query-time rather
* than at index-time, given the constraints above.
*
* ## Algorithm
*
* 1. parse Partial InterpretedName into concrete path and partial fragment
* i.e. for a `name` like "sub1.sub2.paren":
* - concrete = ["sub1", "sub2"]
* - partial = 'paren'
* 2. validate inputs
* 3. for both v1Domains and v2Domains
* a. construct a subquery that filters the set of Domains to those with the specific concrete path
* b. if provided, filter the head domains of that path by `partial`
* c. if provided, filter the leaf domains of that path by `owner`
* 4. construct a union of the two result sets and return
*/
export function findDomains({ name, owner }: DomainFilter) {
// NOTE: if name is not provided, parse empty string to simplify control-flow, validity checked below
// NOTE: throws if name is not a Partial InterpretedName
const { concrete, partial } = parsePartialInterpretedName(name || "");

// validate depth to prevent arbitrary recursion in CTEs
if (concrete.length > MAX_DEPTH) {
throw new Error(`Invariant(findDomains): Name depth exceeds maximum of ${MAX_DEPTH} labels.`);
}

logger.debug({ input: { name, owner, concrete, partial } });

// a name input is valid if it was parsed to something other than just empty string
const validName = concrete.length > 0 || partial !== "";
const validOwner = !!owner;

// Invariant: one of name or owner must be provided
// TODO: maybe this should be zod...
if (!validName && !validOwner) {
throw new Error(`Invariant(findDomains): One of 'name' or 'owner' must be provided.`);
}

const labelHashPath = interpretedLabelsToLabelHashPath(concrete);

// compose subquery by concrete LabelHashPath
const v1DomainsByLabelHashPathQuery = v1DomainsByLabelHashPath(labelHashPath);
const v2DomainsByLabelHashPathQuery = v2DomainsByLabelHashPath(labelHashPath);

// alias for the head domains (to get its labelHash for partial matching)
const v1HeadDomain = alias(schema.v1Domain, "v1HeadDomain");
const v2HeadDomain = alias(schema.v2Domain, "v2HeadDomain");

// join on leafId (the autocomplete result), filter by owner and partial
const v1Domains = db
.select({ id: sql<DomainId>`${schema.v1Domain.id}`.as("id") })
.from(schema.v1Domain)
.innerJoin(
v1DomainsByLabelHashPathQuery,
eq(schema.v1Domain.id, v1DomainsByLabelHashPathQuery.leafId),
)
.innerJoin(v1HeadDomain, eq(v1HeadDomain.id, v1DomainsByLabelHashPathQuery.headId))
.leftJoin(schema.label, eq(schema.label.labelHash, v1HeadDomain.labelHash))
.where(
and(
owner ? eq(schema.v1Domain.ownerId, owner) : undefined,
// TODO: determine if it's necessary to additionally escape user input for LIKE operator
// Note: if label is NULL (unlabeled domain), LIKE returns NULL and filters out the row.
// This is intentional - we can't match partial text against unknown labels.
partial ? like(schema.label.interpreted, `${partial}%`) : undefined,
),
);

// join on leafId (the autocomplete result), filter by owner and partial
const v2Domains = db
.select({ id: sql<DomainId>`${schema.v2Domain.id}`.as("id") })
.from(schema.v2Domain)
.innerJoin(
v2DomainsByLabelHashPathQuery,
eq(schema.v2Domain.id, v2DomainsByLabelHashPathQuery.leafId),
)
.innerJoin(v2HeadDomain, eq(v2HeadDomain.id, v2DomainsByLabelHashPathQuery.headId))
.leftJoin(schema.label, eq(schema.label.labelHash, v2HeadDomain.labelHash))
.where(
and(
owner ? eq(schema.v2Domain.ownerId, owner) : undefined,
// TODO: determine if it's necessary to additionally escape user input for LIKE operator
// Note: if label is NULL (unlabeled domain), LIKE returns NULL and filters out the row.
// This is intentional - we can't match partial text against unknown labels.
partial ? like(schema.label.interpreted, `${partial}%`) : undefined,
),
);

// union the two subqueries and return
return db.$with("domains").as(unionAll(v1Domains, v2Domains));
}

/**
* Compose a query for v1Domains that have the specified children path.
Expand All @@ -157,7 +20,7 @@ export function findDomains({ name, owner }: DomainFilter) {
* Algorithm: Start from the deepest child (leaf) and traverse UP to find the head.
* This is more efficient than starting from all domains and traversing down.
*/
function v1DomainsByLabelHashPath(labelHashPath: LabelHashPath) {
export function v1DomainsByLabelHashPath(labelHashPath: LabelHashPath) {
// If no concrete path, return all domains (leaf = head = self)
// Postgres will optimize this simple subquery when joined
if (labelHashPath.length === 0) {
Expand Down Expand Up @@ -232,7 +95,7 @@ function v1DomainsByLabelHashPath(labelHashPath: LabelHashPath) {
* Algorithm: Start from the deepest child (leaf) and traverse UP via registryCanonicalDomain.
* For v2, parent relationship is: domain.registryId -> registryCanonicalDomain -> parent domainId
*/
function v2DomainsByLabelHashPath(labelHashPath: LabelHashPath) {
export function v2DomainsByLabelHashPath(labelHashPath: LabelHashPath) {
// If no concrete path, return all domains (leaf = head = self)
// Postgres will optimize this simple subquery when joined
if (labelHashPath.length === 0) {
Expand Down
Loading