Skip to content

refactor: build time enhancements#414

Merged
onahprosper merged 8 commits intomainfrom
refactor--reducing-production-buildtime-and-possible-runtime-enhancements
Mar 27, 2026
Merged

refactor: build time enhancements#414
onahprosper merged 8 commits intomainfrom
refactor--reducing-production-buildtime-and-possible-runtime-enhancements

Conversation

@Dprof-in-tech
Copy link
Copy Markdown
Collaborator

@Dprof-in-tech Dprof-in-tech commented Mar 11, 2026

Description

This pull request refactors how components are imported throughout the codebase to favor direct imports from source files instead of barrel (index.ts) files. This change aims to improve tree-shaking, reduce bundle size, and prevent unnecessary code from being pulled into the module graph. Additionally, it introduces a more lightweight, edge-compatible JWT verification for Privy authentication in the middleware, and makes minor configuration and dependency updates.

The most important changes include:

Component Import Refactoring:

  • Refactored all component imports across the app to use direct file imports (e.g., import { Navbar } from "./Navbar") instead of importing from the index.ts barrel file. This affects many files such as AppLayout.tsx, MobileDropdown.tsx, WalletDetails.tsx, TransactionForm.tsx, TransactionPreview.tsx, privacy-client.tsx, terms-client.tsx, and others. [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]
  • Added a comment to app/components/index.ts recommending direct imports from source files to avoid pulling in the full module graph.

Middleware and Authentication Improvements:

  • Replaced custom Privy JWT verification in middleware.ts with an inline, edge-compatible implementation using the jose library and remote JWKS, removing dependencies on heavier SDKs. Also inlined a helper to fetch wallet addresses from Privy user IDs. [1] [2]

Configuration and Dependency Updates:

  • Updated next.config.mjs to optimize package imports for hugeicons-react and react-icons in addition to existing packages.
  • Moved cypress from dependencies to devDependencies in package.json. [1] [2]

References

Testing

Regression tests done and transfer is working, swap is working, everything looks exactly the same and works how it should and has been working.

  • This change adds test coverage for new/changed/fixed functionality

Checklist

  • I have added documentation and tests for new/changed functionality in this PR
  • All active GitHub checks for tests, formatting, and security are passing
  • The correct base branch is being used, if not main

By submitting a PR, I agree to Paycrest's Contributor Code of Conduct and Contribution Guide.

Summary by CodeRabbit

  • Refactor

    • Switched many component imports to explicit per-module imports for more reliable module resolution.
    • Reworked authorization middleware: new JWT verification and user-wallet resolution flow with updated error handling and telemetry.
  • Chores

    • Moved Cypress to development dependencies.
    • Expanded package-import optimization to include additional icon libraries.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 11, 2026

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Refactors many barrel imports to direct module imports, moves style exports to Styles, replaces middleware JWT verification with an inline jose-based Privy JWT + wallet lookup flow, and moves Cypress to devDependencies.

Changes

Cohort / File(s) Summary
App layout & core components
app/components/AppLayout.tsx, app/layout.tsx, app/page.tsx
Switched from barrel imports to direct module imports (AppLayout now default from AppLayout, Preloader imported directly); only import sources changed.
Component import refactor
app/components/MobileDropdown.tsx, app/components/WalletDetails.tsx, app/privacy-policy/privacy-client.tsx, app/terms/terms-client.tsx
Replaced aggregated ./components/./index imports with per-file imports (e.g., FundWalletForm, TransferForm, CookieConsent).
Style imports
app/not-found-client.tsx, app/pages/TransactionForm.tsx, app/pages/TransactionPreview.tsx
Moved style/class imports to .../components/Styles and updated import sites for primaryBtnClasses, secondaryBtnClasses, etc.
Components index note
app/components/index.ts
Added top-level comment recommending direct imports to avoid pulling the full module graph.
Edge middleware: Privy JWT & wallet lookup
middleware.ts
Replaced previous verifyJWT flow with inline verifyPrivyJWT using jose + remote JWKS; added inline Privy user fetch with Basic auth and 3s timeout, wallet selection logic, and adjusted header/error handling while keeping exported middleware/config unchanged.
Build/config & deps
next.config.mjs, package.json
Added hugeicons-react and react-icons to optimized package imports; moved cypress from dependencies to devDependencies.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant Middleware as Edge Middleware
    participant Jose as jose verifier
    participant JWKS as Privy JWKS Endpoint
    participant PrivyAPI as Privy User API
    participant Upstream as Upstream Service

    Client->>Middleware: HTTP request w/ Authorization: Bearer <token>
    Middleware->>Jose: verifyPrivyJWT(token)
    Jose->>JWKS: Fetch JWKS (remote)
    JWKS-->>Jose: JWKS keys
    Jose-->>Middleware: Verified payload (sub => privyUserId)
    Middleware->>PrivyAPI: GET /users/{privyUserId} (Basic auth, 3s timeout)
    PrivyAPI-->>Middleware: User data (embedded wallets)
    Middleware->>Middleware: Select wallet (embedded first, eip155:1 fallback)
    Middleware->>Upstream: Forward request with wallet & user headers
    Upstream-->>Client: Response
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly Related PRs

Suggested labels

enhancement

Suggested reviewers

  • chibie
  • 5ran6

Poem

🐰 I hopped through barrels, found each file's door,
Swapped paths to single files, imports lean once more.
I guard JWTs with jose, fetch wallets in a breeze,
Set headers, pass requests, then vanish with ease.
A rabbit's cheer for tidy code and clearer scores.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title "refactor: build time enhancements" accurately summarizes the main change—optimizing imports and middleware for better tree-shaking and reduced bundle size.
Description check ✅ Passed The description covers the main changes (component import refactoring, middleware improvements, config updates) with clear explanations and references. Testing mentions regression tests but acknowledges new tests weren't added; most checklist items remain unchecked as expected for a refactoring PR.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor--reducing-production-buildtime-and-possible-runtime-enhancements

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
app/components/index.ts (1)

1-1: Good documentation for the import convention.

The comment clearly communicates the preferred import pattern. For stronger enforcement, consider adding an ESLint rule (e.g., no-restricted-imports) to warn when importing from this barrel file in new code.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/components/index.ts` at line 1, Add an ESLint rule to prevent new code
from importing this barrel file: configure the no-restricted-imports rule in
your ESLint config to disallow imports from "app/components" (or the exact
barrel module specifier used) and include a custom message recommending direct
imports from source files; update rules in the top-level ESLint config (or the
relevant override that applies to the project files) and run linting to verify
the rule flags existing/new imports referencing the barrel so developers are
warned to import individual component source paths instead.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@middleware.ts`:
- Around line 21-29: The Privy user lookup in getWalletAddressFromPrivyUserId
uses fetch without a timeout and can hang; wrap the fetch with an
AbortController, start a timer (e.g., 1–3s) that calls controller.abort(), pass
controller.signal to fetch, clear the timer on success, and catch the
abort/timeout error to return/throw a controlled 502-style error (or a specific
TimeoutError) so the middleware fails fast instead of waiting for the platform
timeout.
- Around line 12-18: The verifyPrivyJWT function currently calls
createRemoteJWKSet(new URL(PRIVY_JWKS_URL)) on every invocation which bypasses
the resolver's cache; hoist the JWKS resolver to module scope (e.g., create a
single privyJwks = createRemoteJWKSet(new URL(PRIVY_JWKS_URL)) constant) and
have verifyPrivyJWT call jwtVerify(token, privyJwks, ...), ensuring the resolver
is instantiated once and reused across requests; keep the existing issuer and
algorithms options (PRIVY_JWT_ISSUER, ["ES256"]) when calling jwtVerify.

---

Nitpick comments:
In `@app/components/index.ts`:
- Line 1: Add an ESLint rule to prevent new code from importing this barrel
file: configure the no-restricted-imports rule in your ESLint config to disallow
imports from "app/components" (or the exact barrel module specifier used) and
include a custom message recommending direct imports from source files; update
rules in the top-level ESLint config (or the relevant override that applies to
the project files) and run linting to verify the rule flags existing/new imports
referencing the barrel so developers are warned to import individual component
source paths instead.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3c9bec30-832f-4f0f-a8f3-98bbcfe661a4

📥 Commits

Reviewing files that changed from the base of the PR and between ef44bca and 7e09cb3.

📒 Files selected for processing (14)
  • app/components/AppLayout.tsx
  • app/components/MobileDropdown.tsx
  • app/components/WalletDetails.tsx
  • app/components/index.ts
  • app/layout.tsx
  • app/not-found-client.tsx
  • app/page.tsx
  • app/pages/TransactionForm.tsx
  • app/pages/TransactionPreview.tsx
  • app/privacy-policy/privacy-client.tsx
  • app/terms/terms-client.tsx
  • middleware.ts
  • next.config.mjs
  • package.json

Comment thread middleware.ts
Comment thread middleware.ts Outdated
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

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 `@middleware.ts`:
- Around line 6-16: The middleware currently hardcodes PRIVY_JWT_ISSUER
("privy.io") and builds PRIVY_JWKS_URL from NEXT_PUBLIC_PRIVY_APP_ID, creating a
divergence from server-side config; update middleware to import and use the same
server-side config values (issuer and jwks URL) used in app/lib/config.ts
instead of hardcoded values, initialize
PRIVY_APP_ID/PRIVY_APP_SECRET/PRIVY_JWKS_URL/PRIVY_JWT_ISSUER from that config,
ensure PRIVY_JWKS is created from the imported JWKS URL and verifyPrivyJWT uses
those, and add fail-fast checks that throw or log and stop initialization if any
required config value is missing.
- Around line 40-49: Define a minimal TypeScript response type for the Privy
REST API (e.g., PrivyUserResponse with linked_accounts?: PrivyAccount[] and
PrivyAccount having type: string, connector_type?: string, chain_id?: string —
using the snake_case property names the API returns), replace the any usage by
casting res.json() to that type (const user = await res.json() as
PrivyUserResponse) and type accounts accordingly, and then use the typed
accounts.find logic to locate wallet; if the same wallet-priority logic exists
in app/lib/privy.ts (lines ~20-46), import and reuse that helper (e.g.,
getPreferredWallet/findPreferredWallet) instead of duplicating the selection
logic.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9f50e632-8eda-42f2-b164-fa3c11b5c3d6

📥 Commits

Reviewing files that changed from the base of the PR and between 7e09cb3 and 59fd5c1.

📒 Files selected for processing (1)
  • middleware.ts

Comment thread middleware.ts Outdated
Comment thread middleware.ts Outdated
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

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 `@middleware.ts`:
- Around line 48-54: Update the fetch call that looks up users to point to
Privy's primary REST host: change the URL in the fetch invocation that uses
userId (the current `fetch("https://auth.privy.io/api/v1/users/${userId}",
...)`) to `https://api.privy.io/v1/users/${userId}` while leaving the existing
headers (Authorization using PRIVY_APP_ID and PRIVY_APP_SECRET via btoa, and
"privy-app-id") and the signal (controller.signal) intact; locate this in
middleware.ts where the fetch, userId, PRIVY_APP_ID and PRIVY_APP_SECRET are
referenced and replace only the host/path portion of the URL.
- Around line 33-37: The verifyPrivyJWT function currently only checks issuer
and algorithm; update it to validate the token's audience against our Privy app
ID by either passing an audience option to jwtVerify or asserting payload.aud
equals the PRIVY_APP_ID constant after verification. Locate the verifyPrivyJWT
function and add the audience check using the PRIVY_APP_ID (or equivalent
constant), returning or throwing if the audience does not match, while keeping
existing issuer (PRIVY_JWT_ISSUER), algorithm (ES256) and JWKS (PRIVY_JWKS)
checks.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c0e8eebb-8db6-47f3-9fbc-3c6348d0b8da

📥 Commits

Reviewing files that changed from the base of the PR and between 59fd5c1 and 0512252.

📒 Files selected for processing (1)
  • middleware.ts

Comment thread middleware.ts
Comment thread middleware.ts
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

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 `@middleware.ts`:
- Around line 6-16: The middleware currently throws during module initialization
if PRIVY_APP_ID or PRIVY_APP_SECRET are missing (symbols: PRIVY_APP_ID,
PRIVY_APP_SECRET in middleware.ts), which breaks startup in environments that
only set NEXT_PUBLIC_PRIVY_APP_ID; change the code to avoid throwing at import
time: read process.env.PRIVY_APP_ID || process.env.NEXT_PUBLIC_PRIVY_APP_ID into
a local variable and keep PRIVY_APP_SECRET optional, remove the top-level throw,
and move the validation into the middleware handler (or gracefully
early-return/skip middleware logic) so missing secrets do not crash the process
at module load but are enforced where the middleware actually runs.
- Line 49: The URL is built by interpolating userId directly into the Privy API
path (see the fetch call that uses `userId`), which can produce malformed URLs
when `userId` contains reserved characters; encode the userId with
encodeURIComponent before inserting it into the fetch URL (i.e., replace the raw
`userId` interpolation in the fetch call with an encoded version) and ensure the
encoded value is used consistently wherever the Privy path is constructed.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0e5d86af-eef2-42e2-80db-d7ef64811e3f

📥 Commits

Reviewing files that changed from the base of the PR and between 0512252 and 9b296d4.

📒 Files selected for processing (5)
  • app/components/MobileDropdown.tsx
  • app/components/WalletDetails.tsx
  • app/pages/TransactionForm.tsx
  • app/pages/TransactionPreview.tsx
  • middleware.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/components/WalletDetails.tsx

Comment thread middleware.ts Outdated
Comment thread middleware.ts
Comment thread middleware.ts Outdated
@onahprosper onahprosper merged commit 8466a1b into main Mar 27, 2026
1 check passed
@onahprosper onahprosper deleted the refactor--reducing-production-buildtime-and-possible-runtime-enhancements branch March 27, 2026 11:37
onahprosper added a commit that referenced this pull request Apr 8, 2026
* fix: update migration modal visibility logic

* refactor: enhance SUPPORTED_CHAINS structure and improve RPC URL handling

* Updated the SUPPORTED_CHAINS object to include network names for better clarity.
* Refactored the parseRpcUrl function to utilize the new networkName property for retrieving RPC URLs, improving error handling for unsupported chains.

* feat(settings): add theme switch to desktop dropdown

Add the existing theme switch to the desktop settings dropdown so users can change theme without relying on the footer. The new section keeps the footer control as a secondary entry point and aligns the dropdown styling with the existing menu items.

* refactor: build time enhancements (#414)

* refactor: build time enhancements

* refactor: optimize JWT verification and enhance user ID fetching with timeout handling

* fixes

* feat: add audience parameter to JWT verification for enhanced security

* change variable

---------

Co-authored-by: chibie <chibuotu@gmail.com>
Co-authored-by: Prosper <40717516+onahprosper@users.noreply.github.com>

* chore: update pnpm-lock.yaml to restore cypress dependency and adjust package versions

* Reintroduced cypress dependency with version 15.7.1.
* Minor adjustments to package versions and dependencies for consistency.

* Merge pull request #432 from jeremy0x/main

feat: default balance view to highest-value network after login

* refactor: enhance error handling across components (#426)

* refactor: enhance error handling across components

* fix: improve error handling in TransactionPreview component

* fix

* refactor: remove liquidity error handling from errorMessages and TransactionForm

* fix: enhance error handling for network switching in MobileDropdown and NetworksDropdown components

* feat: integrate Sentry for client error reporting

---------

Co-authored-by: Prosper <40717516+onahprosper@users.noreply.github.com>

* fix: users can use external wallet as main wallet through privy (#428)

* fix: users can use external wallet as main wallet through privy

* fixes

---------

Co-authored-by: Prosper <40717516+onahprosper@users.noreply.github.com>

* feat(networks): Scroll and Celo support, token API alignment, and SEO updates (#446)

* feat(networks): add Scroll and Celo, align tokens and docs

* feat(currency): enable MWK receive currency

---------

Co-authored-by: Isaac Onyemaechi <amaechiisaac450@gmail.com>
Co-authored-by: jeremy0x <aworetanjeremiah@gmail.com>
Co-authored-by: chibie <chibuotu@gmail.com>
Co-authored-by: Francis Ocholi <5raan6@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants