feat: add labelhash parsing and normalization utilities#1688
feat: add labelhash parsing and normalization utilities#1688
Conversation
- Introduced `parse-labelhash.ts` with functions to normalize label hashes and encoded label hashes. - Added tests for label hash parsing in `parse-labelhash.test.ts`. - Updated `ens/index.ts` to export the new parsing functions. - Enhanced `EnsRainbowApiClient` to accept and normalize label hashes before processing requests.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
🦋 Changeset detectedLatest commit: 95621e8 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 |
📝 WalkthroughWalkthroughAdds label-hash parsing utilities and re-exports them; updates EnsRainbowApiClient.heal to accept and normalize a wider set of labelHash inputs (including bracket-encoded and odd-length hex), uses the normalized hash for cache keys and request URLs, and adds/updates tests for parsing and client-side validation/normalization. Changes
Sequence Diagram(s)sequenceDiagram
participant Client as EnsRainbowApiClient
participant Parser as parseLabelHashOrEncodedLabelHash
participant Cache as LocalCache
participant Network as Fetch/API
Client->>Parser: normalize(labelHashInput)
Parser-->>Client: normalizedLabelHash or throw Error
alt normalized
Client->>Cache: lookup(normalizedLabelHash)
Cache-->>Client: cachedResponse / miss
alt miss
Client->>Network: GET /heal/{normalizedLabelHash}
Network-->>Client: response
Client->>Cache: store(normalizedLabelHash, response)
Client-->>Client: return response
else cached
Client-->>Client: return cachedResponse
end
else invalid
Parser-->>Client: throws Error
Client-->>Client: return/throw HealBadRequestError
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes 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)
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 PR introduces label hash parsing and normalization utilities to make the ENSRainbow SDK more user-friendly by accepting various labelHash input formats and automatically normalizing them.
Changes:
- Added new parsing utilities (
parseLabelHash,parseEncodedLabelHash,parseLabelHashOrEncodedLabelHash) that normalize labelHash inputs by handling missing0xprefixes, uppercase hex characters, 63-char hex strings (odd-length padding), and bracket-enclosed encoded labelHashes - Updated
EnsRainbowApiClient.heal()to acceptLabelHash | EncodedLabelHash | stringand perform client-side normalization and validation before making network requests - Added comprehensive test coverage for all normalization scenarios and error cases
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/ensnode-sdk/src/ens/parse-labelhash.ts | New utility module implementing labelHash parsing and normalization logic with three main functions and a custom error class |
| packages/ensnode-sdk/src/ens/parse-labelhash.test.ts | Comprehensive test suite covering all normalization rules, edge cases, and error scenarios for the parsing utilities |
| packages/ensnode-sdk/src/ens/index.ts | Export statement added to expose the new parsing utilities from the ENS module |
| packages/ensrainbow-sdk/src/client.ts | Updated heal() method signature and implementation to accept flexible input formats, perform client-side normalization, and return errors for invalid inputs without making network calls |
| packages/ensrainbow-sdk/src/client.test.ts | Added test cases for the new normalization behavior including uppercase, missing prefix, and encoded labelHash formats, plus verification that invalid inputs don't trigger network requests |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/ensnode-sdk/src/ens/parse-labelhash.ts`:
- Around line 25-27: Remove the redundant `@returns` JSDoc tags in
packages/ensnode-sdk/src/ens/parse-labelhash.ts: for the JSDoc block around the
maybeLabelHash parameter (lines shown) and the other blocks at the indicated
locations (52-55, 73-76), delete the `@returns` lines that merely restate the
function summary so the docs are concise; keep the `@param` and `@throws` tags and
any `@returns` that add unique information, and ensure the remaining JSDoc text
still clearly describes the function behavior.
- Around line 8-13: Remove the custom InvalidLabelHashError class from
parse-labelhash.ts and replace any usages with plain Error instances: delete the
InvalidLabelHashError declaration and update all places that currently throw new
InvalidLabelHashError(...) (or reference that class) to throw new Error(...)
with the same message; ensure exports/imports are cleaned up so only plain Error
is used for parse failures (check functions like parseLabelHash or any callers
in this file/module and adjust their error handling accordingly).
ℹ️ Review info
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (5)
packages/ensnode-sdk/src/ens/index.tspackages/ensnode-sdk/src/ens/parse-labelhash.test.tspackages/ensnode-sdk/src/ens/parse-labelhash.tspackages/ensrainbow-sdk/src/client.test.tspackages/ensrainbow-sdk/src/client.ts
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/ensindexer/src/lib/graphnode-helpers.test.ts (1)
54-75:⚠️ Potential issue | 🟠 MajorThe "too short" test uses a valid labelHash and incorrectly mocks an API response.
The input
0x00ca5d0b4ef1129e04bfe7d35ac9def2f4f91daeb202cbe6e613f1dd17b2da0is 64 hex chars (valid), not too short. SinceparseLabelHash()validates client-side and the "too long" test correctly expects/Invalid labelHash length/i, either use an actually short input (e.g., 63 hex chars) or remove the API mock since client-side validation prevents the API call.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/ensindexer/src/lib/graphnode-helpers.test.ts` around lines 54 - 75, The test for "too short" labelHash is using a valid 64-hex input and incorrectly mocks fetch; update the test to trigger client-side validation by supplying an actually short labelHash (e.g., 63 hex characters) when calling labelByLabelHash so parseLabelHash runs and the fetch mock is not needed, or alternatively remove the fetch mock and assert that labelByLabelHash rejects with /Invalid labelHash length/i; reference labelByLabelHash and parseLabelHash to locate the validation path to fix.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/ensindexer/src/lib/graphnode-helpers.test.ts`:
- Around line 77-92: Update the test that calls labelByLabelHash to also assert
that fetch was invoked with the normalized (lowercased) labelHash: keep the
existing mock and call to labelByLabelHash, then after awaiting the result add
an assertion that fetch was called with a URL or request body containing the
lowercased version of the input hash (use the same uppercased input string but
compare against its lowercase form) to verify labelByLabelHash performs
normalization before making the API call.
- Around line 70-75: The test for labelByLabelHash currently asserts that an
invalid-length labelHash rejects but doesn't verify fetch wasn't invoked; after
awaiting the rejection for labelByLabelHash("0x...65chars..."), add an explicit
assertion that the network helper was not called (e.g.,
expect(fetch).not.toHaveBeenCalled() or the project's mocked fetch helper) to
confirm validation occurs client-side and no fetch occurred. Ensure the fetch
mock is reset/available in this test so the not-to-have-been-called assertion is
reliable.
- Around line 94-101: The test for labelByLabelHash (the "throws an error for an
invalid labelHash missing 0x prefix and too long" case) claims client-side
validation but doesn't assert that no network call was made; after the await
expect(...).rejects.toThrow(...) add an assertion that the fetch mock was not
invoked (e.g., expect(globalThis.fetch).not.toHaveBeenCalled() or
expect(fetch).not.toHaveBeenCalled()) to explicitly verify fetch was not called.
---
Outside diff comments:
In `@apps/ensindexer/src/lib/graphnode-helpers.test.ts`:
- Around line 54-75: The test for "too short" labelHash is using a valid 64-hex
input and incorrectly mocks fetch; update the test to trigger client-side
validation by supplying an actually short labelHash (e.g., 63 hex characters)
when calling labelByLabelHash so parseLabelHash runs and the fetch mock is not
needed, or alternatively remove the fetch mock and assert that labelByLabelHash
rejects with /Invalid labelHash length/i; reference labelByLabelHash and
parseLabelHash to locate the validation path to fix.
…ndling and normalization - Updated tests for `labelByLabelHash` to verify normalization of 63-char hex label hashes and proper error propagation for server responses. - Refactored `parse-labelhash` functions to throw generic errors instead of custom `InvalidLabelHashError`, simplifying error handling across tests and implementations. - Added additional test cases for empty strings and invalid formats in `parse-labelhash` tests.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Greptile SummaryAdds robust labelhash normalization utilities that gracefully handle missing
Confidence Score: 5/5
Important Files Changed
Flowchart%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[User calls heal with string] --> B{Input has brackets?}
B -->|Yes| C[parseEncodedLabelHash]
B -->|No| D[parseLabelHash]
C --> E[Extract content from brackets]
E --> D
D --> F{Has 0x prefix?}
F -->|No| G[Add 0x prefix]
F -->|Yes| H[Extract hex part]
G --> H
H --> I{Valid hex?}
I -->|No| J[Throw error: non-hex chars]
I -->|Yes| K{Odd length?}
K -->|Yes| L[Prepend 0 to hex part]
K -->|No| M{Length = 64?}
L --> M
M -->|No| N[Throw error: invalid length]
M -->|Yes| O[Lowercase and add 0x prefix]
O --> P[Return normalized LabelHash]
P --> Q[Check cache]
Q -->|Hit| R[Return cached result]
Q -->|Miss| S[Make API request with normalized hash]
S --> T[Cache and return result]
Last reviewed commit: 9a92b99 |
lightwalker-eth
left a comment
There was a problem hiding this comment.
@djstrong Looks nice! Thank you
Lite PR
Tip: Review docs on the ENSNode PR process
Summary
parseLabelHash,parseEncodedLabelHash, andparseLabelHashOrEncodedLabelHashutilities toensnode-sdkthat normalize labelhash inputs to a canonicalLabelHash(adds0xprefix if missing, normalizes uppercase to lowercase, pads odd-length hex, validates 32-byte length).EnsRainbowApiClient.heal()to acceptLabelHash | EncodedLabelHash | stringand normalize the input before making the API request; returns aHealBadRequestErrorif the input cannot be normalized.Why
0x, uppercase hex, bracket-enclosed encoded labelhash) gracefully.Testing
0xprefix, uppercase normalization, odd-length padding, bracket-enclosed format, and error cases (non-hex characters, wrong length, malformed brackets, empty string).EnsRainbowApiClienttests updated to cover the new normalization/error path.Notes for Reviewer (Optional)
parseLabelHashOrEncodedLabelHashis intentionally more lenient thanisEncodedLabelHash— it accepts[0xhash](non-canonical bracket format) in addition to[hash].HealBadRequestErrorrather than thrown exceptions, keeping theheal()return type consistent.Pre-Review Checklist (Blocking)