Conversation
🦋 Changeset detectedLatest commit: a1522a2 The changes in this PR will be included in the next version bump. This PR includes changesets to release 19 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
The latest updates on your projects. Learn more about Vercel for GitHub. 3 Skipped Deployments
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughReplaces date-based ENS Holiday Awards config with a referral-program-editions model: loads an edition config set (custom URL or defaults), initializes per-edition leaderboard caches, updates v1 APIs and SDK types/serializers to be edition-aware, and adds utilities (parseTimestamp, SWRCache errorTtl). Changes
Sequence DiagramsequenceDiagram
actor Client
participant ConfigLoader as Config Loader
participant EditionCache as Edition Config Cache
participant PerEditionCaches as Per-Edition Caches
participant API as ENSAnalytics API
Client->>ConfigLoader: App startup
ConfigLoader->>EditionCache: Load edition config set (custom URL or defaults)
EditionCache-->>ConfigLoader: ReferralProgramEditionConfigSet
ConfigLoader->>PerEditionCaches: initialize caches per edition
PerEditionCaches-->>ConfigLoader: caches ready
Client->>API: GET /v1/ensanalytics/referral-leaderboard?edition=2025-12&page=1
API->>EditionCache: validate edition exists
API->>PerEditionCaches: read cache for edition "2025-12"
PerEditionCaches-->>API: ReferrerLeaderboard | Error
API-->>Client: paginated leaderboard (per-edition)
Client->>API: GET /v1/ensanalytics/referrer/0x123?editions=2025-12,2026-03
API->>PerEditionCaches: read caches for editions
PerEditionCaches-->>API: per-edition metrics map
API-->>Client: ReferrerMetricsEditionsResponse (aggregated)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
This pull request refactors the ENS referral program system from supporting a single program period to supporting multiple concurrent and sequential "cycles". Each cycle represents a distinct referral program period with its own rules, leaderboard, and award distribution.
Changes:
- Introduces a cycle-based architecture with
ReferralProgramCycletype andReferralProgramCycleSetmap structure - Updates API endpoints to require cycle ID parameter:
/v1/ensanalytics/referral-leaderboard?cycle=<id>and/v1/ensanalytics/referral-leaderboard/<address>(now returns data for all cycles) - Replaces single cache with per-cycle independent caches to allow individual cycle failures without affecting others
- Removes hardcoded ENS Holiday Awards configuration from environment variables, replacing with optional
CUSTOM_REFERRAL_PROGRAM_CYCLESURL - Adds Cycle 2 (March 2026) as a second default cycle alongside Cycle 1 (ENS Holiday Awards December 2025)
Reviewed changes
Copilot reviewed 25 out of 25 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/ensnode-sdk/src/shared/config/environments.ts | Replaces EnsHolidayAwardsEnvironment with ReferralProgramCyclesEnvironment |
| packages/ens-referrals/src/v1/rules.ts | Removes hardcoded ENS Holiday Awards constants |
| packages/ens-referrals/src/v1/cycle.ts | Adds new cycle type definitions and type guards |
| packages/ens-referrals/src/v1/cycle-defaults.ts | Defines default cycles (Cycle 1 and Cycle 2) with configuration |
| packages/ens-referrals/src/v1/index.ts | Exports new cycle types |
| packages/ens-referrals/src/v1/client.ts | Updates SDK client to require cycle parameter for leaderboard queries |
| packages/ens-referrals/src/v1/api/*.ts | Updates API types to support all-cycles responses and cycle-specific requests |
| apps/ensapi/src/handlers/ensanalytics-api-v1.ts | Updates API handlers to support cycle parameter and multi-cycle responses |
| apps/ensapi/src/handlers/ensanalytics-api-v1.test.ts | Updates tests to work with new cycle-based cache structure |
| apps/ensapi/src/cache/referral-leaderboard-cycles.cache.ts | New cache implementation with per-cycle independent caches |
| apps/ensapi/src/cache/referrer-leaderboard.cache-v1.ts | Deleted - replaced by cycle-based cache |
| apps/ensapi/src/config/*.ts | Updates configuration loading to support custom cycle URLs |
| apps/ensapi/.env.local.example | Updates environment variable documentation |
| .changeset/clever-laws-count.md | Empty changeset file |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Actionable comments posted: 10
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/ens-referrals/src/v1/api/types.ts (1)
74-124:⚠️ Potential issue | 🟠 MajorBreaking public type renames—add compatibility aliases or ensure a major version bump.
Downstream TypeScript consumers using the oldReferrerDetailResponse*exports will break. Consider re‑exporting deprecated aliases or explicitly bumping the package major version and documenting the migration.🧩 Optional compatibility aliases
+/** `@deprecated` Use ReferrerDetailAllCyclesResponseCodes */ +export const ReferrerDetailResponseCodes = ReferrerDetailAllCyclesResponseCodes; +/** `@deprecated` Use ReferrerDetailAllCyclesResponseCode */ +export type ReferrerDetailResponseCode = ReferrerDetailAllCyclesResponseCode; +/** `@deprecated` Use ReferrerDetailAllCyclesResponseOk */ +export type ReferrerDetailResponseOk = ReferrerDetailAllCyclesResponseOk; +/** `@deprecated` Use ReferrerDetailAllCyclesResponseError */ +export type ReferrerDetailResponseError = ReferrerDetailAllCyclesResponseError; +/** `@deprecated` Use ReferrerDetailAllCyclesResponse */ +export type ReferrerDetailResponse = ReferrerDetailAllCyclesResponse;
🤖 Fix all issues with AI agents
In `@apps/ensapi/.env.local.example`:
- Around line 115-138: Update the env example comment for
CUSTOM_REFERRAL_PROGRAM_CYCLES to state that supplying a URL will completely
replace the default referral cycle set (i.e., it overrides defaults), and
instruct operators to include every cycle they want active in their hosted JSON;
reference the env variable name CUSTOM_REFERRAL_PROGRAM_CYCLES and the example
JSON structure in the comment so readers know to add any default cycles they
still want when providing a custom file.
In `@apps/ensapi/src/handlers/ensanalytics-api-v1.ts`:
- Around line 185-198: The handler currently fail-fast when any cycle
cache.read() returns an Error; to support partial-success change the response to
allow per-cycle results and errors by updating the
ReferrerDetailAllCyclesResponse/ReferrerDetailAllCyclesData types to map cycleId
-> { data?: ReferrerDetail; error?: string }, then modify the loop over
referralLeaderboardCyclesCaches to collect each cycle's result into
allCyclesData[cycleId] using getReferrerDetail(referrer, leaderboard) on success
or an error string on failure (using cycleCache.read()), and finally return a
200 with the aggregated per-cycle data (and optionally an overall status field)
instead of returning 500 on the first failure so clients can consume available
cycles while seeing which cycles failed.
In `@packages/ens-referrals/src/v1/api/deserialize.ts`:
- Around line 235-244: The type error comes from building `data` via
`Object.entries(maybeResponse.data)` which TypeScript widens to `Record<string,
...>`; fix by ensuring the final object is explicitly typed as
`ReferrerDetailAllCyclesResponse` — replace the assignment to `deserialized`
with an explicit cast: set `deserialized = { responseCode: "ok", data } as
ReferrerDetailAllCyclesResponse`; alternatively, build `data` with a typed
reducer (e.g., reduce to `Record<ReferralProgramCycleId, ReferrerDetail>` or
`ReferrerDetailAllCyclesData`) so the resulting `data` has the correct key type
before assigning to `deserialized` (use `deserializeReferrerDetail` inside the
reducer).
In `@packages/ens-referrals/src/v1/api/serialize.ts`:
- Around line 154-160: The switch in serializeReferrerDetail over ReferrerDetail
isn't exhaustive and can return undefined if a new detail.type is added; update
serializeReferrerDetail to include a default branch that asserts exhaustiveness
(e.g., call an assertNever/assertUnreachable helper or assign detail to a
never-typed variable and throw) so the compiler errors on new union members and
at runtime you throw a clear error; keep existing branches that call
serializeReferrerDetailRanked and serializeReferrerDetailUnranked and reference
ReferrerDetail/SerializedReferrerDetail in the assertion.
- Around line 201-218: The switch over response.responseCode
(ReferrerDetailAllCyclesResponseCodes) is not exhaustive and the serializedData
is unsafely asserted with {} as SerializedReferrerDetailAllCyclesData; update
the case for Ok to build the record in a type-safe way (e.g., const
serializedData: Partial<SerializedReferrerDetailAllCyclesData> = {}; for (const
[cycleId, detail] of Object.entries(response.data)) { serializedData[cycleId as
ReferralProgramCycleId] = serializeReferrerDetail(detail); } and return data:
serializedData as SerializedReferrerDetailAllCyclesData), and add a default (or
never) branch after the known cases that throws an error like throw new
Error(`Unhandled ReferrerDetailAllCyclesResponseCodes:
${response.responseCode}`) to enforce exhaustiveness for
ReferrerDetailAllCyclesResponseCodes.
In `@packages/ens-referrals/src/v1/api/zod-schemas.ts`:
- Around line 281-306: In makeReferralProgramCycleSetSchema, the refine
currently only checks that each value parses as a ReferralProgramCycle but
doesn't ensure the Map key equals the cycle's id; update the validate loop in
makeReferralProgramCycleSetSchema to parse each value with
makeReferralProgramCycleSchema(`${valueLabel}[${key}]`), extract the parsed
cycle.id, and return false if typeof key !== "string" or parsedCycle.id !== key
(so keys must match the cycle.id). Also update the refine error message to
indicate keys must equal the nested cycle.id for integrity.
In `@packages/ens-referrals/src/v1/client.ts`:
- Around line 220-229: The example accesses response.data["cycle-1"] without
guarding for undefined which can cause unsafe access; update the example around
the getReferrerDetail response handling (check response.responseCode ===
ReferrerDetailAllCyclesResponseCodes.Ok) to first confirm the key exists (e.g.,
verify response.data["cycle-1"] is truthy) before reading its .type and
.referrer, and adjust the branching that inspects ReferrerDetailTypeIds.Ranked
to handle the case where cycle1Detail is undefined so callers see the safer
pattern.
- Around line 99-104: The JSDoc example in client.ts references a non-existent
rules.cycleId; update the example to use an existing serialized field from
serializeReferralProgramRules (e.g., rules.subregistryId or
rules.startTime/endTime/totalAwardPoolValue) or, if you intended to show the
requested cycle id, reference the request parameter (e.g., the cycleId variable
used to call the client) instead; modify the example console.log lines in the
example block near the response handling to use one of those valid identifiers
so the docs match serializeReferralProgramRules and the request parameters.
In `@packages/ens-referrals/src/v1/cycle-defaults.ts`:
- Around line 45-55: The START_DATE and END_DATE constants in cycle-defaults.ts
are using incorrect Unix timestamps for the documented UTC dates; update
START_DATE (currently 1772524800) to 1772323200 and END_DATE (currently
1775116799) to 1775001599 so the cycle properly covers 2026-03-01T00:00:00Z
through 2026-03-31T23:59:59Z; edit the START_DATE and END_DATE values (the
symbols START_DATE and END_DATE) to the corrected integers and keep the
UnixTimestamp type assertions.
In `@packages/ens-referrals/src/v1/cycle.ts`:
- Around line 42-43: The type guard isPredefinedCycleId currently narrows to
ReferralProgramCycleId which is effectively any string; change its return type
to the concrete union of predefined IDs (e.g. value is typeof
ALL_REFERRAL_PROGRAM_CYCLE_IDS[number] or a named
PredefinedReferralProgramCycleId union) and keep the runtime check using
ALL_REFERRAL_PROGRAM_CYCLE_IDS.includes(value as any) so callers get stronger
compile-time narrowing while preserving the existing runtime behavior; update
the function signature only (isPredefinedCycleId) to reference the more precise
union type (or create a named union) and leave ALL_REFERRAL_PROGRAM_CYCLE_IDS
usage unchanged.
| export const isPredefinedCycleId = (value: string): value is ReferralProgramCycleId => | ||
| ALL_REFERRAL_PROGRAM_CYCLE_IDS.includes(value as ReferralProgramCycleId); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider a more precise return type for the type guard.
The type guard narrows to ReferralProgramCycleId, but since that type includes string & {}, any string technically satisfies it. For better type safety, consider narrowing to just the predefined union:
♻️ Suggested refinement
-export const isPredefinedCycleId = (value: string): value is ReferralProgramCycleId =>
+export const isPredefinedCycleId = (value: string): value is (typeof ReferralProgramCycleIds)[keyof typeof ReferralProgramCycleIds] =>
ALL_REFERRAL_PROGRAM_CYCLE_IDS.includes(value as ReferralProgramCycleId);The current implementation works correctly at runtime, and the JSDoc clearly documents the behavior, so this is optional.
📝 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.
| export const isPredefinedCycleId = (value: string): value is ReferralProgramCycleId => | |
| ALL_REFERRAL_PROGRAM_CYCLE_IDS.includes(value as ReferralProgramCycleId); | |
| export const isPredefinedCycleId = (value: string): value is (typeof ReferralProgramCycleIds)[keyof typeof ReferralProgramCycleIds] => | |
| ALL_REFERRAL_PROGRAM_CYCLE_IDS.includes(value as ReferralProgramCycleId); |
🤖 Prompt for AI Agents
In `@packages/ens-referrals/src/v1/cycle.ts` around lines 42 - 43, The type guard
isPredefinedCycleId currently narrows to ReferralProgramCycleId which is
effectively any string; change its return type to the concrete union of
predefined IDs (e.g. value is typeof ALL_REFERRAL_PROGRAM_CYCLE_IDS[number] or a
named PredefinedReferralProgramCycleId union) and keep the runtime check using
ALL_REFERRAL_PROGRAM_CYCLE_IDS.includes(value as any) so callers get stronger
compile-time narrowing while preserving the existing runtime behavior; update
the function signature only (isPredefinedCycleId) to reference the more precise
union type (or create a named union) and leave ALL_REFERRAL_PROGRAM_CYCLE_IDS
usage unchanged.
|
Deployment failed with the following error: |
|
Deployment failed with the following error: |
|
Deployment failed with the following error: |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 25 out of 25 changed files in this pull request and generated 10 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| async function loadReferralProgramCycleSet( | ||
| customCyclesUrl: string | undefined, | ||
| namespace: ENSNamespaceId, | ||
| ): Promise<ReferralProgramCycleSet> { | ||
| const subregistryId = getEthnamesSubregistryId(namespace); | ||
|
|
||
| if (!customCyclesUrl) { | ||
| logger.info("Using default referral program cycle set"); | ||
| return getReferralProgramCycleSet(subregistryId.address); | ||
| } | ||
|
|
||
| // Validate URL format | ||
| try { | ||
| new URL(customCyclesUrl); | ||
| } catch { | ||
| throw new Error(`CUSTOM_REFERRAL_PROGRAM_CYCLES is not a valid URL: ${customCyclesUrl}`); | ||
| } | ||
|
|
||
| // Fetch and validate | ||
| logger.info(`Fetching custom referral program cycles from: ${customCyclesUrl}`); | ||
| const response = await fetch(customCyclesUrl); | ||
| if (!response.ok) { | ||
| throw new Error( | ||
| `Failed to fetch custom referral program cycles from ${customCyclesUrl}: ${response.status} ${response.statusText}`, | ||
| ); | ||
| } | ||
|
|
||
| const json = await response.json(); | ||
| const schema = makeCustomReferralProgramCyclesSchema("CUSTOM_REFERRAL_PROGRAM_CYCLES"); | ||
| const validated = schema.parse(json); | ||
|
|
||
| // Convert array to Map, check for duplicates | ||
| const cycleSet: ReferralProgramCycleSet = new Map(); | ||
| for (const cycleObj of validated) { | ||
| const cycle = cycleObj as ReferralProgramCycle; | ||
| const cycleId = cycle.id; | ||
| if (cycleSet.has(cycleId)) { | ||
| throw new Error(`Duplicate cycle ID in CUSTOM_REFERRAL_PROGRAM_CYCLES: ${cycle.id}`); | ||
| } | ||
| cycleSet.set(cycleId, cycle); | ||
| } | ||
|
|
||
| logger.info(`Loaded ${cycleSet.size} custom referral program cycles`); | ||
| return cycleSet; | ||
| } |
There was a problem hiding this comment.
The loadReferralProgramCycleSet function performs a network request during application startup (via buildConfigFromEnvironment). If the custom cycles URL is unreachable, slow to respond, or returns invalid data, this will block application startup.
Consider adding:
- A timeout for the fetch operation to prevent hanging
- Retry logic with exponential backoff for transient network failures
- Better error context in the exception messages to help with debugging
- Optional: A fallback mechanism to use default cycles if custom cycles fail to load (with appropriate logging)
This would improve resilience during deployment and prevent startup failures due to temporary network issues.
| // Check all caches and fail immediately if any cache failed | ||
| for (const [cycleId, cycleCache] of c.var.referralLeaderboardCyclesCaches) { | ||
| const leaderboard = await cycleCache.read(); | ||
| if (leaderboard instanceof Error) { | ||
| return c.json( | ||
| serializeReferrerDetailAllCyclesResponse({ | ||
| responseCode: ReferrerDetailAllCyclesResponseCodes.Error, | ||
| error: "Internal Server Error", | ||
| errorMessage: `Referrer leaderboard data for cycle ${cycleId} has not been successfully cached yet.`, | ||
| } satisfies ReferrerDetailAllCyclesResponse), | ||
| 500, | ||
| ); | ||
| } | ||
| allCyclesData[cycleId] = getReferrerDetail(referrer, leaderboard); | ||
| } |
There was a problem hiding this comment.
The fail-fast approach means that if any single cycle fails to load, the entire request returns an error. This could be problematic from a user experience perspective - if cycle-1 is working but cycle-2 fails, users cannot access cycle-1 data either.
Consider implementing a more resilient approach where:
- Successfully loaded cycles are returned in the response
- Failed cycles are indicated with an error status or omitted with a warning
- The response includes information about which cycles loaded successfully vs. which failed
This would provide better availability and user experience, especially during partial outages or when one cycle has data issues.
| for (const [cycleId, cycleCache] of c.var.referralLeaderboardCyclesCaches) { | ||
| const leaderboard = await cycleCache.read(); | ||
| if (leaderboard instanceof Error) { | ||
| return c.json( | ||
| serializeReferrerDetailAllCyclesResponse({ | ||
| responseCode: ReferrerDetailAllCyclesResponseCodes.Error, | ||
| error: "Internal Server Error", | ||
| errorMessage: `Referrer leaderboard data for cycle ${cycleId} has not been successfully cached yet.`, | ||
| } satisfies ReferrerDetailAllCyclesResponse), | ||
| 500, | ||
| ); | ||
| } | ||
| allCyclesData[cycleId] = getReferrerDetail(referrer, leaderboard); | ||
| } |
There was a problem hiding this comment.
The code iterates over c.var.referralLeaderboardCyclesCaches using a for-of loop with .entries(). JavaScript Maps preserve insertion order, but the iteration order matters here because the first cycle that fails will determine the error response.
If the goal is to fail fast on any cycle failure, consider:
- Documenting the specific iteration order behavior (e.g., "cycles are checked in the order they were configured")
- Or explicitly sorting the cycles to ensure a predictable error reporting order
- Or collecting all failures and reporting them together
The current implementation may result in non-deterministic error reporting if the Map insertion order isn't guaranteed by the configuration loading code.
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/ens-referrals/src/v1/rules.ts (1)
81-101: 🧹 Nitpick | 🔵 TrivialConsider an options-object pattern for
buildReferralProgramRules.With 6 positional parameters, call sites are becoming harder to read (easy to swap
startTime/endTimeor other same-typed args). An options object would improve clarity and reduce positional mistakes.♻️ Example refactor
-export const buildReferralProgramRules = ( - totalAwardPoolValue: PriceUsdc, - maxQualifiedReferrers: number, - startTime: UnixTimestamp, - endTime: UnixTimestamp, - subregistryId: AccountId, - rulesUrl: URL, -): ReferralProgramRules => { - const result = { - totalAwardPoolValue, - maxQualifiedReferrers, - startTime, - endTime, - subregistryId, - rulesUrl, - } satisfies ReferralProgramRules; +export const buildReferralProgramRules = ( + options: ReferralProgramRules, +): ReferralProgramRules => { + validateReferralProgramRules(options); + return options; +};This leverages the existing
ReferralProgramRulesinterface directly, eliminating redundancy between the parameter list and the interface definition.packages/ens-referrals/src/v1/api/serialize.ts (1)
189-202: 🧹 Nitpick | 🔵 TrivialMissing exhaustiveness check in
serializeReferrerLeaderboardPageResponse.The new serializers (
serializeReferrerMetricsEditionsResponse,serializeReferralProgramEditionConfigSetResponse) includedefault: neverexhaustiveness checks, but this existing serializer does not. For consistency and the same compile-time safety guarantees, consider adding one here too.♻️ Proposed fix
case ReferrerLeaderboardPageResponseCodes.Error: return response; + + default: { + const _exhaustiveCheck: never = response; + throw new Error( + `Unknown response code: ${(_exhaustiveCheck as ReferrerLeaderboardPageResponse).responseCode}`, + ); + } }
🤖 Fix all issues with AI agents
In @.changeset/clever-laws-count.md:
- Line 6: The single-line changeset description in
.changeset/clever-laws-count.md is dense; split it into a short header plus 3–4
bullet points for clarity — one bullet for referral program editions support
with example edition names (ENS Holiday Awards December 2025, March 2026), one
for "pre-configured edition definitions", one for the ENSAnalytics API v1 change
(mention edition-based leaderboard queries), and one for adding edition
configuration to the environment schema; keep tense consistent and wrap the
bullets under the existing changeset summary line.
In `@apps/ensapi/src/cache/referral-leaderboard-editions.cache.ts`:
- Around line 54-107: The serialized rules JSON is being logged at info level
inside createEditionLeaderboardBuilder, producing multi-line output every cache
rebuild; change the detailed dump that calls logger.info with
serializeReferralProgramRules to logger.debug while keeping the summary
success/info logs (the initial logger.info describing "Building referrer
leaderboard..." and the final logger.info with leaderboard.referrers.size)
unchanged so only the verbose rules dump is demoted to debug.
In `@apps/ensapi/src/config/config.schema.test.ts`:
- Around line 86-100: Add a negative test in config.schema.test.ts that sets
CUSTOM_REFERRAL_PROGRAM_EDITIONS to an invalid string (e.g., "not-a-url") and
asserts that buildConfigFromEnvironment fails validation; specifically call
buildConfigFromEnvironment with the modified env and verify it either throws a
validation error or triggers the same process.exit(1) behavior used in other
config error-path tests (reuse the existing process.exit mock/assert pattern),
referencing CUSTOM_REFERRAL_PROGRAM_EDITIONS and
config.customReferralProgramEditionConfigSetUrl to ensure the invalid URL path
is covered.
In `@apps/ensapi/src/handlers/ensanalytics-api-v1.test.ts`:
- Around line 882-905: The test mocks
editionSetMiddleware.referralProgramEditionConfigSetMiddleware but not
editionsCachesMiddleware.referralProgramEditionCachesMiddleware, causing
reliance on prior test state; add an explicit mock for
editionsCachesMiddleware.referralProgramEditionCachesMiddleware in this test
that calls next() (and, if necessary, sets any context keys the real middleware
would) so the middleware chain proceeds and the route handler executes reliably
without leaking state from other tests.
In `@packages/ens-referrals/src/v1/api/zod-schemas.ts`:
- Around line 280-289: The default valueLabel for
makeReferrerMetricsEditionsResponseOkSchema and
makeReferrerMetricsEditionsResponseErrorSchema is inconsistent (both use
"ReferrerMetricsEditionsResponse"); update the default valueLabel parameter in
makeReferrerMetricsEditionsResponseOkSchema to
"ReferrerMetricsEditionsResponseOk" and in
makeReferrerMetricsEditionsResponseErrorSchema to
"ReferrerMetricsEditionsResponseError" so error messages match the Ok/Error
schema pair naming convention used elsewhere (locate these functions by name to
make the change).
In `@packages/ens-referrals/src/v1/edition-defaults.ts`:
- Around line 39-51: The inline placeholder rules URL used when constructing
edition2 via buildReferralProgramRules (the new
URL("https://ensawards.org/ens-holiday-awards-rules") argument) must be tracked
and validated: extract that literal into a named constant (e.g.,
PLACEHOLDER_RULES_URL) and replace the inline URL in the
ReferralProgramEditionConfig for edition2, then add a small validation in the
editions loader/initialization code (where editions are assembled or exported)
to detect if any edition.ruleUrl === PLACEHOLDER_RULES_URL and either throw a
build/validation error or emit a clear log/error that blocks release; ensure you
reference edition2 and buildReferralProgramRules so the check runs whenever
editions are registered.
In `@packages/ens-referrals/src/v1/edition.ts`:
- Line 17: ReferralProgramEditionSlug is currently a plain string so arbitrary
strings can be passed; change it to a branded/opaque type (e.g., type
ReferralProgramEditionSlug = string & { readonly __brand: unique symbol }) and
use a single factory/validator function (or the existing Zod parse function) to
produce/return the branded type so callers must explicitly obtain the branded
value; update any functions or parameters that currently accept raw strings
(references to ReferralProgramEditionSlug) to require the branded type so
accidental misuse is caught at compile time.
In `@packages/ensnode-sdk/src/shared/cache/swr-cache.ts`:
- Around line 158-167: Update the stale inline comment above the TTL check to
reference the computed effective TTL instead of just "ttl": change the comment
near the effectiveTtl calculation and the following check in swr-cache.ts
(around this.cache.updatedAt, durationBetween, getUnixTime, effectiveTtl, and
this.revalidate) to say something like "if effective TTL expired, revalidate in
background" so the comment matches the branching logic that uses errorTtl when
this.cache.result is an Error.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@apps/ensapi/src/handlers/ensanalytics-api-v1.test.ts`:
- Around line 664-723: Add a new test (or extend the existing one) that requests
only unknown edition slugs (e.g.,
app.request(`/referrer/${referrer}?editions=foo,bar`)) to ensure the handler
returns 404 and the same error payload shape; reuse the same mocks
(mockEditionsCaches, mockEditionConfigSet) and assertions via
deserializeReferrerMetricsEditionsResponse and
ReferrerMetricsEditionsResponseCodes.Error to check response.error contains "Not
Found", response.errorMessage lists the unknown slugs ("foo,bar") and still
includes the valid editions list ("2025-12, 2026-03").
In `@packages/ens-referrals/src/v1/api/zod-schemas.ts`:
- Around line 248-264: The uniqueness refine in
makeReferrerMetricsEditionsArraySchema currently checks uniqueness by creating a
Set and comparing its size to editions.length; to align with
makeReferralProgramEditionConfigSetArraySchema and be more efficient, replace
that check with an early-return loop that iterates editions, uses a Set.has()
check to detect duplicates and returns false immediately on first duplicate
(otherwise adds to the Set and returns true at end); update the refine predicate
and keep the same error message `${valueLabel} must not contain duplicate
edition slugs`.
| it("returns 404 error when unknown edition slug is requested", async () => { | ||
| // Arrange: mock cache map with configured editions | ||
| const mockEditionsCaches = new Map<ReferralProgramEditionSlug, SWRCache<ReferrerLeaderboard>>( | ||
| [ | ||
| [ | ||
| "2025-12", | ||
| { | ||
| read: async () => populatedReferrerLeaderboard, | ||
| } as SWRCache<ReferrerLeaderboard>, | ||
| ], | ||
| [ | ||
| "2026-03", | ||
| { | ||
| read: async () => populatedReferrerLeaderboard, | ||
| } as SWRCache<ReferrerLeaderboard>, | ||
| ], | ||
| ], | ||
| ); | ||
|
|
||
| // Mock edition set middleware to provide a mock edition set | ||
| const mockEditionConfigSet = new Map([ | ||
| ["2025-12", { slug: "2025-12", displayName: "Edition 1", rules: {} as any }], | ||
| ["2026-03", { slug: "2026-03", displayName: "Edition 2", rules: {} as any }], | ||
| ]); | ||
| vi.mocked(editionSetMiddleware.referralProgramEditionConfigSetMiddleware).mockImplementation( | ||
| async (c, next) => { | ||
| c.set("referralProgramEditionConfigSet", mockEditionConfigSet); | ||
| return await next(); | ||
| }, | ||
| ); | ||
|
|
||
| // Mock caches middleware to provide the mock caches | ||
| vi.mocked( | ||
| editionsCachesMiddleware.referralLeaderboardEditionsCachesMiddleware, | ||
| ).mockImplementation(async (c, next) => { | ||
| c.set("referralLeaderboardEditionsCaches", mockEditionsCaches); | ||
| return await next(); | ||
| }); | ||
|
|
||
| // Arrange: use any referrer address | ||
| const referrer = "0x538e35b2888ed5bc58cf2825d76cf6265aa4e31e"; | ||
|
|
||
| // Act: send test request with one valid and one invalid edition | ||
| const httpResponse = await app.request( | ||
| `/referrer/${referrer}?editions=2025-12,invalid-edition`, | ||
| ); | ||
| const responseData = await httpResponse.json(); | ||
| const response = deserializeReferrerMetricsEditionsResponse(responseData); | ||
|
|
||
| // Assert: response is 404 error with list of valid editions | ||
| expect(httpResponse.status).toBe(404); | ||
| expect(response.responseCode).toBe(ReferrerMetricsEditionsResponseCodes.Error); | ||
| if (response.responseCode === ReferrerMetricsEditionsResponseCodes.Error) { | ||
| expect(response.error).toBe("Not Found"); | ||
| expect(response.errorMessage).toContain("invalid-edition"); | ||
| expect(response.errorMessage).toBe( | ||
| "Unknown edition(s): invalid-edition. Valid editions: 2025-12, 2026-03", | ||
| ); | ||
| } | ||
| }); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider testing with all unknown editions in addition to a mixed valid/invalid request.
This test sends editions=2025-12,invalid-edition (one valid, one invalid) and asserts 404. It would strengthen coverage to also test the case where all requested editions are unknown (e.g., editions=foo,bar), to confirm the same 404 behavior and that the valid-editions list is still returned correctly.
🤖 Prompt for AI Agents
In `@apps/ensapi/src/handlers/ensanalytics-api-v1.test.ts` around lines 664 - 723,
Add a new test (or extend the existing one) that requests only unknown edition
slugs (e.g., app.request(`/referrer/${referrer}?editions=foo,bar`)) to ensure
the handler returns 404 and the same error payload shape; reuse the same mocks
(mockEditionsCaches, mockEditionConfigSet) and assertions via
deserializeReferrerMetricsEditionsResponse and
ReferrerMetricsEditionsResponseCodes.Error to check response.error contains "Not
Found", response.errorMessage lists the unknown slugs ("foo,bar") and still
includes the valid editions list ("2025-12, 2026-03").
| export const makeReferrerMetricsEditionsArraySchema = ( | ||
| valueLabel: string = "ReferrerMetricsEditionsArray", | ||
| ) => | ||
| z | ||
| .array(makeReferralProgramEditionSlugSchema(`${valueLabel}[edition]`)) | ||
| .min(1, `${valueLabel} must contain at least 1 edition`) | ||
| .max( | ||
| MAX_EDITIONS_PER_REQUEST, | ||
| `${valueLabel} must not contain more than ${MAX_EDITIONS_PER_REQUEST} editions`, | ||
| ) | ||
| .refine( | ||
| (editions) => { | ||
| const uniqueEditions = new Set(editions); | ||
| return uniqueEditions.size === editions.length; | ||
| }, | ||
| { message: `${valueLabel} must not contain duplicate edition slugs` }, | ||
| ); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Minor inconsistency in uniqueness check pattern.
This schema uses a Set size comparison for uniqueness (line 260–261), while makeReferralProgramEditionConfigSetArraySchema (lines 336–342) uses an early-return loop with Set.has(). Both are correct, but the early-return pattern is slightly more efficient for large arrays and provides a more consistent codebase.
Consider aligning both to the same pattern:
♻️ Suggested alignment
.refine(
(editions) => {
- const uniqueEditions = new Set(editions);
- return uniqueEditions.size === editions.length;
+ const seen = new Set<string>();
+ for (const edition of editions) {
+ if (seen.has(edition)) return false;
+ seen.add(edition);
+ }
+ return true;
},
{ message: `${valueLabel} must not contain duplicate edition slugs` },
);📝 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.
| export const makeReferrerMetricsEditionsArraySchema = ( | |
| valueLabel: string = "ReferrerMetricsEditionsArray", | |
| ) => | |
| z | |
| .array(makeReferralProgramEditionSlugSchema(`${valueLabel}[edition]`)) | |
| .min(1, `${valueLabel} must contain at least 1 edition`) | |
| .max( | |
| MAX_EDITIONS_PER_REQUEST, | |
| `${valueLabel} must not contain more than ${MAX_EDITIONS_PER_REQUEST} editions`, | |
| ) | |
| .refine( | |
| (editions) => { | |
| const uniqueEditions = new Set(editions); | |
| return uniqueEditions.size === editions.length; | |
| }, | |
| { message: `${valueLabel} must not contain duplicate edition slugs` }, | |
| ); | |
| export const makeReferrerMetricsEditionsArraySchema = ( | |
| valueLabel: string = "ReferrerMetricsEditionsArray", | |
| ) => | |
| z | |
| .array(makeReferralProgramEditionSlugSchema(`${valueLabel}[edition]`)) | |
| .min(1, `${valueLabel} must contain at least 1 edition`) | |
| .max( | |
| MAX_EDITIONS_PER_REQUEST, | |
| `${valueLabel} must not contain more than ${MAX_EDITIONS_PER_REQUEST} editions`, | |
| ) | |
| .refine( | |
| (editions) => { | |
| const seen = new Set<string>(); | |
| for (const edition of editions) { | |
| if (seen.has(edition)) return false; | |
| seen.add(edition); | |
| } | |
| return true; | |
| }, | |
| { message: `${valueLabel} must not contain duplicate edition slugs` }, | |
| ); |
🤖 Prompt for AI Agents
In `@packages/ens-referrals/src/v1/api/zod-schemas.ts` around lines 248 - 264, The
uniqueness refine in makeReferrerMetricsEditionsArraySchema currently checks
uniqueness by creating a Set and comparing its size to editions.length; to align
with makeReferralProgramEditionConfigSetArraySchema and be more efficient,
replace that check with an early-return loop that iterates editions, uses a
Set.has() check to detect duplicates and returns false immediately on first
duplicate (otherwise adds to the Set and returns true at end); update the refine
predicate and keep the same error message `${valueLabel} must not contain
duplicate edition slugs`.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 37 out of 37 changed files in this pull request and generated 4 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
apps/ensapi/.env.local.example
Outdated
| # For the complete schema definition, see makeReferralProgramEditionConfigSetArraySchema in @namehash/ens-referrals/v1 | ||
| # | ||
| # Fetching Behavior: | ||
| # - Fetched proactively at ENSApi startup (before accepting requests) |
There was a problem hiding this comment.
The env docs claim the edition config set JSON is fetched at startup “before accepting requests”, but SWRCache proactivelyInitialize: true triggers an async revalidate without awaiting it. The server can start serving requests before the fetch completes, so the docs should reflect that (or the bootstrap code should await initialization if that behavior is required).
| # - Fetched proactively at ENSApi startup (before accepting requests) | |
| # - Fetched proactively when ENSApi starts up (non-blocking; ENSApi may begin accepting requests before load completes) |
There was a problem hiding this comment.
@Goader Yes this feedback from Copilot matches my understanding. We may proactively initialize an attempt to fetch, but as I understand we don't block while waiting for successful fetching to complete.
Is that fair?
lightwalker-eth
left a comment
There was a problem hiding this comment.
@Goader Really awesome work here! Very happy 🚀 Looks great! Shared some small suggestions please take the lead to merge when ready 👍
| parseTimestamp("2026-03-01T00:00:00Z"), | ||
| parseTimestamp("2026-03-31T23:59:59Z"), | ||
| subregistryId, | ||
| // note: this will be replaced with dedicated March 2026 rules URL once published |
There was a problem hiding this comment.
| // note: this will be replaced with dedicated March 2026 rules URL once published | |
| // TODO: replace this with the dedicated March 2026 rules URL once published |
apps/ensapi/.env.local.example
Outdated
| # For the complete schema definition, see makeReferralProgramEditionConfigSetArraySchema in @namehash/ens-referrals/v1 | ||
| # | ||
| # Fetching Behavior: | ||
| # - Fetched proactively at ENSApi startup (before accepting requests) |
There was a problem hiding this comment.
@Goader Yes this feedback from Copilot matches my understanding. We may proactively initialize an attempt to fetch, but as I understand we don't block while waiting for successful fetching to complete.
Is that fair?
| * | ||
| * @invariant Must contain only lowercase letters (a-z), digits (0-9), and hyphens (-). | ||
| * Must not start or end with a hyphen. Pattern: `^[a-z0-9]+(-[a-z0-9]+)*$` |
There was a problem hiding this comment.
| * | |
| * @invariant Must contain only lowercase letters (a-z), digits (0-9), and hyphens (-). | |
| * Must not start or end with a hyphen. Pattern: `^[a-z0-9]+(-[a-z0-9]+)*$` |
You did a great job of documenting this invariant on the definition of ReferralProgramEditionSlug. Therefore no need to duplicate that documentation here.
| * | ||
| * Used to store and look up all configured referral program editions. | ||
| */ | ||
| export type ReferralProgramEditionConfigSet = Map< |
There was a problem hiding this comment.
Let's document / enforce an invariant here that for each key / value pair in this map, key is equal to value.slug.
|
|
||
| const editionConfigs = deserializeReferralProgramEditionConfigSetArray(json); | ||
|
|
||
| return new Map(editionConfigs.map((editionConfig) => [editionConfig.slug, editionConfig])); |
There was a problem hiding this comment.
The creation of this Map should move into the deserialize utility function.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@packages/ens-referrals/src/v1/edition.ts`:
- Around line 80-85: buildReferralProgramEditionConfigSet silently drops earlier
configs when multiple ReferralProgramEditionConfig items share the same slug;
before converting configs to a Map, scan the incoming configs array in
buildReferralProgramEditionConfigSet to detect duplicate config.slug values, and
if any duplicates are found throw a clear Error (or ValidationError) listing the
duplicate slug(s); only after duplicates are ruled out construct the Map and
call validateReferralProgramEditionConfigSet as currently done.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 37 out of 37 changed files in this pull request and generated 4 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| const edition1: ReferralProgramEditionConfig = { | ||
| slug: "2025-12", | ||
| displayName: "ENS Holiday Awards", | ||
| rules: buildReferralProgramRules( | ||
| parseUsdc("10000"), | ||
| 10, | ||
| parseTimestamp("2025-12-01T00:00:00Z"), | ||
| parseTimestamp("2025-12-31T23:59:59Z"), | ||
| subregistryId, | ||
| new URL("https://ensawards.org/ens-holiday-awards-rules"), | ||
| ), | ||
| }; | ||
|
|
||
| const edition2: ReferralProgramEditionConfig = { | ||
| slug: "2026-03", | ||
| displayName: "March 2026", |
There was a problem hiding this comment.
The PR description and linked issue describe predefined cycle IDs like cycle-1 / cycle-2, but the default identifiers here are date-based slugs (2025-12, 2026-03). Please confirm the intended public identifier scheme and align defaults/types/docs accordingly to avoid breaking downstream expectations.
| # Custom Referral Program Edition Config Set Definition (optional) | ||
| # URL that returns JSON for a custom referral program edition config set. | ||
| # If not set, the default edition config set for the namespace is used. | ||
| # | ||
| # JSON Structure: | ||
| # The JSON must be an array of edition config objects (SerializedReferralProgramEditionConfig[]). | ||
| # For the complete schema definition, see makeReferralProgramEditionConfigSetArraySchema in @namehash/ens-referrals/v1 | ||
| # | ||
| # Fetching Behavior: | ||
| # - Fetched proactively when ENSApi starts up (non-blocking; ENSApi may begin accepting requests before load completes) | ||
| # - Once successfully loaded, cached indefinitely (never expires or revalidates) | ||
| # - On load failure: | ||
| # * Error is logged | ||
| # * ENSApi continues running | ||
| # * Failed state is cached for 1 minute, then retried on subsequent requests | ||
| # * API requests receive error responses until successful load | ||
| # | ||
| # Configuration Notes: | ||
| # - Setting CUSTOM_REFERRAL_PROGRAM_EDITIONS completely replaces the default edition config set | ||
| # - Include all edition configs you want active in the JSON | ||
| # - Array must contain at least one edition config | ||
| # - All edition slugs must be unique | ||
| # | ||
| # CUSTOM_REFERRAL_PROGRAM_EDITIONS=https://example.com/custom-editions.json |
There was a problem hiding this comment.
This documentation introduces CUSTOM_REFERRAL_PROGRAM_EDITIONS, but the PR description calls the env var CUSTOM_REFERRAL_PROGRAM_CYCLES and describes cycle IDs (cycle-1, cycle-2). Please reconcile the naming (env var + terminology + examples) so operators configure the correct variable and consumers understand the identifier format.
| const referrerLeaderboardPageQuerySchema = z.object({ | ||
| edition: makeReferralProgramEditionSlugSchema("edition"), | ||
| page: z |
There was a problem hiding this comment.
The v1 leaderboard route is documented in this PR as using a cycle query parameter, but the handler currently requires edition (and the request/SDK types are named ReferralProgramEdition*). Please standardize the public API contract (choose either cycle or edition) and update the handler/query schema + client/types/docs consistently so consumers don’t send the wrong parameter.
| app | ||
| .get( | ||
| "/referrer/:referrer", | ||
| describeRoute({ | ||
| tags: ["ENSAwards"], | ||
| summary: "Get Referrer Detail for Editions (v1)", | ||
| description: `Returns detailed information for a specific referrer for the requested editions. Requires 1-${MAX_EDITIONS_PER_REQUEST} distinct edition slugs. All requested editions must be recognized and have cached data, or the request fails.`, |
There was a problem hiding this comment.
This endpoint is implemented as /referrer/:referrer, but the PR description/issue call out a renamed route like /referral-leaderboard/:referrer (to pair with /referral-leaderboard). Consider aligning the route path naming so the v1 API surface is consistent and matches the documented contract (and update the SDK/client paths accordingly).
ENS Referrals API v1: Multi-Cycle Support
closes: #1522
Reviewer Focus (Read This First)
What reviewers should focus on
ReferralProgramCycleIdtype allows both predefined IDs (cycle-1,cycle-2) with autocomplete AND custom cycle IDs loaded from JSON (usingstring & {}trick for extensibility)apps/ensapi/src/config/config.schema.ts-loadReferralProgramCycleSet()with URL fetching and validationProblem & Motivation
Why this exists
What Changed (Concrete)
What actually changed
1. New Data Models (
packages/ens-referrals/src/v1/)cycle.ts- Core type definitions:ReferralProgramCycleIdsobject withCycle1: "cycle-1"andCycle2: "cycle-2"ReferralProgramCycleIdtype (extensible to custom IDs)ReferralProgramCycleinterface withid,displayName,rules,rulesUrlReferralProgramCycleSettype asMap<ReferralProgramCycleId, ReferralProgramCycle>cycle-defaults.ts- Default cycle definitions:getReferralProgramCycleSet()function returning pre-built Map with cycle-1 and cycle-2api/zod-schemas.ts- Comprehensive validation:makeReferralProgramCycleIdSchema()- validates cycle IDsmakeReferralProgramCycleSchema()- validates complete cycle objectsmakeCustomReferralProgramCyclesSchema()- validates JSON array format with duplicate ID checksmakeReferralProgramCycleSetSchema()- validates Map structureapi/types.ts- New response types:ReferrerDetailAllCyclesData- Record of cycle ID to referrer detailsReferrerDetailAllCyclesResponse- Discriminated union for OK/Error2. Configuration System (
apps/ensapi/)Environment variable (
packages/ensnode-sdk/src/shared/config/environments.ts):CUSTOM_REFERRAL_PROGRAM_CYCLES?: stringtoReferralProgramCyclesEnvironmentConfig schema (
apps/ensapi/src/config/config.schema.ts):loadReferralProgramCycleSet()async function:EnsApiConfigSchemato includereferralProgramCycleSetfieldbuildConfigFromEnvironment()to call loaderEnvironment documentation (
apps/ensapi/.env.local.example):CUSTOM_REFERRAL_PROGRAM_CYCLESENS_HOLIDAY_AWARDS_STARTandENS_HOLIDAY_AWARDS_END(no longer needed)3. Multi-Cycle Cache Architecture (
apps/ensapi/src/cache/)referral-leaderboard-cycles.cache.ts- New cache implementation:ReferralLeaderboardCyclesCacheMaptype:Map<ReferralProgramCycleId, SWRCache<ReferrerLeaderboard>>initializeCyclesCaches()creates independent SWRCache for each configured cycleV1 Middleware (
apps/ensapi/src/middleware/referrer-leaderboard.middleware-v1.ts):referralLeaderboardCyclesCachesto downstream handlers4. V1 API Routes (
apps/ensapi/src/handlers/ensanalytics-api-v1.ts)GET /v1/ensanalytics/referral-leaderboard(renamed from/referrers):cyclequery parameterGET /v1/ensanalytics/referral-leaderboard/:referrer(renamed from/referrers/:referrer):ReferrerDetailAllCyclesDatainstead of singleReferrerDetailDesign & Planning
How this approach was chosen
Self-Review
What you caught yourself
ENS_HOLIDAY_AWARDS_START/ENDenv vars from ensapi config, now depends on the referral program cycle custom jsonCross-Codebase Alignment
Related code you checked
ReferralProgram,ENS_HOLIDAY_AWARDS,referrerLeaderboard,SWRCache,cycle,v1,v0Downstream & Consumer Impact
Who this affects and how
v0 unaffected, v1 is allowed to work with multiple cycles
.env.local.exampledocumentation, same with the clientTesting Evidence
How this was validated
Scope Reductions
What you intentionally didn't do
Did not do partial success response for referrer details (all cycles) - if one cycle fails, return 500.
Risk Analysis
How this could go wrong
Low risk - v0 affected very little (only env vars, which were not used in production either way and defaulted to constants, which are now the only source of truth).
V1 is not used by any downstream consumer yet.
Pre-Review Checklist (Blocking)