Skip to content

perf: make zod and error message tables optional in bundles - #203

Merged
macalinao merged 3 commits into
masterfrom
optional-zod-validation
Aug 12, 2026
Merged

macalinao merged 3 commits into
masterfrom
optional-zod-validation

Conversation

@macalinao

@macalinao macalinao commented Aug 11, 2026 •

Copy link
Copy Markdown
Owner

Three independent bundle-size reductions. All numbers are minified bytes measured with rolldown, with peer deps (@solana/kit, @solana/*, react, react-query, gill, sonner) marked external — so they are the marginal cost each package adds on top of what a consumer already pays.

import before after
useTokenInfo 70.4 KB 13.2 KB
@macalinao/solana-batch-accounts-loader 4.9 KB 2.5 KB
parseTransactionError (with __GRILL_ERROR_MESSAGES__=false) 8.0 KB 1.7 KB

1. Pluggable token metadata validation

fetchTokenInfo/fetchTokenInfoForMint gained a validateMetadata option, and GrillProvider/GrillHeadlessProvider a matching validateTokenMetadata prop.

The default is defaultTokenMetadataValidator — a dependency-free shallow check. To keep full Metaplex schema validation:

import { zodTokenMetadataValidator } from "@macalinao/zod-solana";

<GrillProvider validateTokenMetadata={zodTokenMetadataValidator}>

zod stays a first-class option; it is just no longer on the default path. zod-solana is unchanged apart from the new export.

Behaviour change: on the default path, nested fields (attributes, properties, collection) and seller_fee_basis_points are no longer validated and are omitted from the parsed result. fetchTokenInfo only ever read name, symbol, and image, so this does not affect TokenInfo — but it is visible to anyone passing a custom validator or relying on the parsed shape. Pass zodTokenMetadataValidator to restore the old behaviour exactly.

2. Inline chunk

lodash-es was pulled in for a single chunk call, and accounted for roughly half the package's bundled size. Now a 6-line local function; lodash-es and @types/lodash-es are removed from package.json and the lockfile.

3. Strippable error message tables

@macalinao/solana-errors deliberately ships full messages in production (that is the package's whole point), but there was no way to opt out. Now:

// vite.config.ts
export default defineConfig({
  define: { __GRILL_ERROR_MESSAGES__: "false" },
});

Lookups route through a helper gated on the flag, so defining it as false folds the branch to a constant and leaves both tables unreferenced. Errors then report the variant name (Transaction error: BlockhashNotFound) instead of prose.

Messages remain on by default — this is opt-in, existing behaviour is unchanged. Two caveats, both documented in the new README:

  • The tables only drop if you do not import INSTRUCTION_ERROR_MESSAGES / TRANSACTION_ERROR_MESSAGES directly.
  • Your bundler must re-run DCE after constant folding. Rollup, rolldown, and Vite do; plain esbuild and bun build fold the branch but keep the unreferenced tables.

Notes

  • Added packages/solana-errors/README.md — the package had none, and a build-time flag is useless if undiscoverable.
  • 7 new tests for defaultTokenMetadataValidator. lint, test, and build all pass.
  • Changesets: gill-extra/zod-solana/grill minor, solana-errors minor, solana-batch-accounts-loader patch.

Pre-existing issue left alone

useTokenInfos does not forward fetchFromCertifiedTokenList to fetchTokenInfo, while useTokenInfo does — so setting it to false is ignored by the plural hook. Unrelated to this PR and fixing it changes behaviour, so I left it; happy to do it separately.

Summary by Sourcery

Make token metadata validation pluggable and optional, inline the only lodash chunk usage, and add a build-time flag to optionally strip Solana error message tables from bundles.

New Features:

  • Add pluggable token metadata validation with a default lightweight validator and an optional full zod-based validator.
  • Introduce a build-time __GRILL_ERROR_MESSAGES__ flag and ERROR_MESSAGES_ENABLED export to control inclusion of human-readable error messages.

Enhancements:

  • Propagate configurable token metadata validation through Grill providers, context, and hooks to reduce default bundle size.
  • Inline a local chunk helper in the Solana batch accounts loader and remove the lodash-es dependency to shrink the package.
  • Document Solana error message behavior and configuration in a new README for @macalinao/solana-errors.

Build:

  • Remove lodash-es and its type definitions from the Solana batch accounts loader package dependencies.

Tests:

  • Add unit tests covering the behavior of the default token metadata validator.

Summary by CodeRabbit

  • New Features

    • Added configurable token metadata validation with a lightweight default validator and optional full-schema validation.
    • Added build-time control to omit human-readable Solana error messages from production bundles.
    • Added an export indicating whether error messages are enabled.
  • Improvements

    • Reduced batch account loader bundle size by removing an unnecessary dependency without changing behavior.
    • Simplified default metadata results by excluding unsupported nested fields.
    • Error formatting now falls back to variant names when messages are disabled.
  • Documentation

    • Added guidance for error-message configuration and custom token metadata validation.

Three independent bundle-size reductions, each measured with rolldown
(minified, peer deps external).

Token metadata validation is now pluggable. `fetchTokenInfo` takes a
`validateMetadata` option and the Grill providers take a matching
`validateTokenMetadata` prop, defaulting to a dependency-free shallow
check. Full Metaplex schema validation is still available by passing
`zodTokenMetadataValidator` from @macalinao/zod-solana. Importing
`useTokenInfo` no longer pulls zod in: 70.4 KB -> 13.2 KB.

`chunk` is inlined in solana-batch-accounts-loader, dropping the
lodash-es dependency: 4.9 KB -> 2.5 KB.

The @macalinao/solana-errors message tables can now be stripped by
defining `__GRILL_ERROR_MESSAGES__` as false, which folds the lookups to
a constant and leaves the tables unreferenced: 8.0 KB -> 1.7 KB. Messages
stay on by default, so existing behaviour is unchanged.
@sourcery-ai

sourcery-ai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces pluggable token metadata validation to decouple zod from default bundles, inlines a local chunk implementation to drop lodash-es, and adds an optional build-time flag to strip Solana error message tables from bundles while preserving default behaviour.

Sequence diagram for pluggable token metadata validation in fetchTokenInfo

sequenceDiagram
  actor App
  participant GrillHeadlessProvider
  participant GrillContext
  participant useTokenInfo
  participant fetchTokenInfo
  participant TokenMetadataValidator

  App->>GrillHeadlessProvider: <GrillHeadlessProvider validateTokenMetadata?>
  GrillHeadlessProvider->>GrillContext: provide validateTokenMetadata (defaultTokenMetadataValidator by default)

  App->>useTokenInfo: useTokenInfo({ mint })
  useTokenInfo->>GrillContext: useGrillContext()
  GrillContext-->>useTokenInfo: { staticTokenInfo, fetchFromCertifiedTokenList, validateTokenMetadata }

  useTokenInfo->>fetchTokenInfo: { mint, metadata, fetchFromCertifiedTokenList, validateMetadata: validateTokenMetadata }
  fetchTokenInfo->>TokenMetadataValidator: validateMetadata(responseJson)
  alt validator returns TokenMetadata
    TokenMetadataValidator-->>fetchTokenInfo: TokenMetadata
    fetchTokenInfo-->>useTokenInfo: TokenInfo with name, symbol, image from URI
  else validator returns null
    TokenMetadataValidator-->>fetchTokenInfo: null
    fetchTokenInfo-->>useTokenInfo: TokenInfo from on-chain metadata only
  end
Loading

Flow diagram for stripping Solana error message tables via ERROR_MESSAGES_ENABLED

flowchart TD
  A[Build-time flag __GRILL_ERROR_MESSAGES__] --> B{Is __GRILL_ERROR_MESSAGES__ defined as false?}
  B -- Yes --> C[ERROR_MESSAGES_ENABLED = false]
  B -- No or undefined --> D[ERROR_MESSAGES_ENABLED = true]

  C --> E[lookupInstructionErrorMessage / lookupTransactionErrorMessage return undefined]
  E --> F[getInstructionErrorMessage / getTransactionErrorMessage fall back to variant name]
  F --> G[INSTRUCTION_ERROR_MESSAGES / TRANSACTION_ERROR_MESSAGES become unreferenced]
  G --> H[Bundler DCE drops message tables from bundle]

  D --> I[lookupInstructionErrorMessage / lookupTransactionErrorMessage read from message tables]
  I --> J[getInstructionErrorMessage / getTransactionErrorMessage return full prose message]
  J --> K[Message tables kept in bundle]
Loading

File-Level Changes

Change Details Files
Make token metadata validation pluggable and zod-free by default across gill-extra and grill.
  • Introduce TokenMetadataValidator and defaultTokenMetadataValidator in gill-extra, implementing a shallow, dependency-free validator that returns a normalized TokenMetadata or null.
  • Update fetchTokenInfo and fetchTokenInfoForMint to accept a validateMetadata option, defaulting to defaultTokenMetadataValidator and replacing direct tokenMetadataSchema usage and error logging.
  • Extend GrillHeadlessProvider, GrillProvider context, useTokenInfo, and useTokenInfos to carry and use a validateTokenMetadata prop/value, defaulting to defaultTokenMetadataValidator, and re-export validator utilities from gill-extra.
  • Add zodTokenMetadataValidator in zod-solana as a thin wrapper around tokenMetadataSchema.safeParse and export it for consumers needing full Metaplex schema validation.
  • Add unit tests for defaultTokenMetadataValidator to cover valid payloads, type guarding, rejection of invalid payloads, and omission of unvalidated nested fields.
packages/gill-extra/src/fetch-token-info.ts
packages/gill-extra/src/fetch-token-info-for-mint.ts
packages/gill-extra/src/token-metadata-validator.ts
packages/gill-extra/src/token-metadata-validator.test.ts
packages/gill-extra/src/index.ts
packages/grill/src/providers/grill-headless-provider.tsx
packages/grill/src/contexts/grill-context.ts
packages/grill/src/hooks/use-token-info.ts
packages/grill/src/hooks/use-token-infos.ts
packages/zod-solana/src/zod-token-metadata-validator.ts
packages/zod-solana/src/index.ts
Allow Solana error message tables to be stripped via a build-time flag while keeping messages enabled by default.
  • Add a flags module that declares the GRILL_ERROR_MESSAGES build-time constant and computes ERROR_MESSAGES_ENABLED with a typeof guard fallback to true, exporting it from the solana-errors entrypoint.
  • Refactor instruction-error and transaction-error to route all message lookups through helper functions (lookupInstructionErrorMessage / lookupTransactionErrorMessage) that short-circuit to undefined when ERROR_MESSAGES_ENABLED is false, enabling DCE of the message tables.
  • Adjust getInstructionErrorMessage and getTransactionErrorMessage to fall back to variant-name-based messages when lookups return undefined, preserving behaviour when tables are stripped.
  • Document the new flag, behaviour, bundler caveats, and ERROR_MESSAGES_ENABLED in a new solana-errors README and changeset.
packages/solana-errors/src/flags.ts
packages/solana-errors/src/instruction-error.ts
packages/solana-errors/src/transaction-error.ts
packages/solana-errors/src/index.ts
packages/solana-errors/README.md
.changeset/optional-error-messages.md
Inline a lightweight chunk implementation and remove lodash-es from solana-batch-accounts-loader.
  • Replace the lodash-es chunk import with a local chunk function that slices the input array into size-bounded chunks using a simple for-loop.
  • Remove lodash-es and @types/lodash-es from solana-batch-accounts-loader package.json dependencies/devDependencies and update the lockfile accordingly.
  • Document the change and bundle-size impact via a changeset entry.
packages/solana-batch-accounts-loader/src/createBatchAccountsLoader.ts
packages/solana-batch-accounts-loader/package.json
bun.lock
.changeset/inline-chunk.md
Add changeset entries capturing the new pluggable validation and error-message-stripping behaviours.
  • Create a changeset describing pluggable token metadata validation and its impact across gill-extra, zod-solana, and grill, including behaviour changes for nested metadata fields.
  • Create a changeset describing the optional error message stripping in solana-errors and its impact on bundle size and runtime behaviour.
.changeset/optional-token-metadata-validation.md
.changeset/optional-error-messages.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
grill-example-dapp ef6fddd Commit Preview URL

Branch Preview URL
Aug 12 2026, 12:26 PM

@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

Walkthrough

The PR adds configurable token metadata validators, build-time control for Solana error message tables, and a local chunk helper that replaces lodash-es. It also adds release metadata and package documentation.

Changes

Token metadata validation

Layer / File(s) Summary
Metadata validator contracts and implementations
packages/gill-extra/src/token-metadata-validator.ts, packages/gill-extra/src/token-metadata-validator.test.ts, packages/zod-solana/src/zod-token-metadata-validator.ts, packages/gill-extra/src/index.ts, packages/zod-solana/src/index.ts
Gill Extra adds a shallow validator and tests. Zod Solana adds and exports a full-schema validator.
Token information validation flow
packages/gill-extra/src/fetch-token-info.ts, packages/gill-extra/src/fetch-token-info-for-mint.ts
Token-info functions accept and forward validateMetadata. URI JSON uses the selected validator.
Grill validation configuration
packages/grill/src/providers/grill-headless-provider.tsx, packages/grill/src/contexts/grill-context.ts, packages/grill/src/hooks/use-token-info.ts, packages/grill/src/hooks/use-token-infos.ts
The provider configures the validator through context. Token-info hooks pass it to fetching.

Optional Solana error messages

Layer / File(s) Summary
Error message flag and public documentation
packages/solana-errors/src/flags.ts, packages/solana-errors/src/index.ts, packages/solana-errors/README.md
The package adds __GRILL_ERROR_MESSAGES__, ERROR_MESSAGES_ENABLED, and bundler configuration documentation.
Flag-aware error formatting
packages/solana-errors/src/instruction-error.ts, packages/solana-errors/src/transaction-error.ts
Error formatters conditionally read message tables and use variant-name fallbacks when messages are disabled or unavailable.

Batch loader dependency cleanup

Layer / File(s) Summary
Local batch chunking helper
packages/solana-batch-accounts-loader/src/createBatchAccountsLoader.ts, packages/solana-batch-accounts-loader/package.json, package.json
The loader uses a local slice-based chunk helper and removes lodash-es dependencies. The root override pins the remaining lodash-es version.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant GrillHeadlessProvider
  participant GrillContext
  participant useTokenInfo
  participant fetchTokenInfo
  participant TokenMetadataValidator
  GrillHeadlessProvider->>GrillContext: expose validateTokenMetadata
  useTokenInfo->>GrillContext: read validator
  useTokenInfo->>fetchTokenInfo: pass validateMetadata
  fetchTokenInfo->>TokenMetadataValidator: validate URI JSON
  TokenMetadataValidator-->>fetchTokenInfo: return metadata or null
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the two primary bundle-size changes: optional Zod validation and removable error message tables.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch optional-zod-validation

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.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 1 security issue, 2 other issues, and left some high level feedback:

Security issues:

  • lodash: lodash: Arbitrary code execution via untrusted input in template imports (link)

General comments:

  • The ERROR_MESSAGES_ENABLED flag currently checks typeof __GRILL_ERROR_MESSAGES__ === "boolean", but the README examples (e.g. Vite define: { __GRILL_ERROR_MESSAGES__: "false" }) provide a string literal, so the flag will never disable messages as documented; consider either updating the examples to use a boolean literal or relaxing the check to treat the string "false" as disabling messages.
  • The new chunk helper in createBatchAccountsLoader assumes a positive size and will produce an infinite loop or empty slices if size <= 0; it may be worth asserting or guarding against non-positive sizes to avoid silent misuse.
  • In fetchTokenInfo, any custom TokenMetadataValidator that returns null will now trigger a generic console.error("Invalid token metadata at URI:", uri) without surfacing validation details; if consumers are expected to plug in richer validators (e.g. zod), consider a way to propagate or optionally log more specific error information.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `ERROR_MESSAGES_ENABLED` flag currently checks `typeof __GRILL_ERROR_MESSAGES__ === "boolean"`, but the README examples (e.g. Vite `define: { __GRILL_ERROR_MESSAGES__: "false" }`) provide a string literal, so the flag will never disable messages as documented; consider either updating the examples to use a boolean literal or relaxing the check to treat the string "false" as disabling messages.
- The new `chunk` helper in `createBatchAccountsLoader` assumes a positive `size` and will produce an infinite loop or empty slices if `size <= 0`; it may be worth asserting or guarding against non-positive sizes to avoid silent misuse.
- In `fetchTokenInfo`, any custom `TokenMetadataValidator` that returns `null` will now trigger a generic `console.error("Invalid token metadata at URI:", uri)` without surfacing validation details; if consumers are expected to plug in richer validators (e.g. zod), consider a way to propagate or optionally log more specific error information.

## Individual Comments

### Comment 1
<location path="packages/solana-batch-accounts-loader/src/createBatchAccountsLoader.ts" line_range="16-18" />
<code_context>
+ * Inlined rather than pulled from lodash-es: this is the only lodash usage in
+ * the package, and it accounted for roughly half of the package's bundled size.
+ */
+function chunk<T>(items: readonly T[], size: number): T[][] {
+  const chunks: T[][] = [];
+  for (let i = 0; i < items.length; i += size) {
+    chunks.push(items.slice(i, i + size));
+  }
</code_context>
<issue_to_address>
**issue (bug_risk):** Guard against non-positive `size` in `chunk` to avoid infinite loops or unexpected behavior.

This implementation assumes `size > 0`. If `size` is `0` or negative (including via a computed value), `i += size` will not progress correctly, leading to an infinite loop or invalid slicing. Consider guarding or normalizing `size` (e.g. early-return `[]` for `size <= 0` or clamping to `1`) to avoid subtle runtime failures and align with lodash’s behavior.
</issue_to_address>

### Comment 2
<location path="packages/solana-errors/src/flags.ts" line_range="8-11" />
<code_context>
+ * The tables are ~7 KB minified. They are included by default. To strip them,
+ * define `__GRILL_ERROR_MESSAGES__` as `false` in your bundler:
+ *
+ * ```ts
+ * // vite.config.ts
+ * export default defineConfig({
+ *   define: { __GRILL_ERROR_MESSAGES__: "false" },
+ * });
+ * ```
</code_context>
<issue_to_address>
**issue (bug_risk):** The config examples define `__GRILL_ERROR_MESSAGES__` as a string, which won’t disable messages under the current `typeof` check.

Because `define: { __GRILL_ERROR_MESSAGES__: "false" }` is substituted as a string, it won’t satisfy `typeof __GRILL_ERROR_MESSAGES__ === "boolean"` and will default to `true`, keeping error messages enabled despite the docs. Please either update the examples to use a boolean literal (no quotes / bundler boolean syntax) or adjust the runtime check to also handle string values like "false"/"true" so the documented config behaves as described.
</issue_to_address>

### Comment 3
<location path="bun.lock" line_range="2171" />
<code_context>

</code_context>
<issue_to_address>
**security (CVE-2026-4800):** lodash: lodash: Arbitrary code execution via untrusted input in template imports

Impact:

The fix for CVE-2021-23337 (https://github.com/advisories/GHSA-35jh-r3h4-6jhm) added validation for the variable option in _.template but did not apply the same validation to options.imports key names. Both paths flow into the same Function() constructor sink.

When an application passes untrusted input as options.imports key names, an attacker can inject default-parameter expressions that execute arbitrary code at template compilation time.

Additionally, _.template uses assignInWith to merge imports, which enumerates inherited properties via for..in. If Object.prototype has been polluted by any other vector, the polluted keys are copied into the imports object and passed to Function().

Patches:

Users should upgrade to version 4.18.0.

Workarounds:

Do not pass untrusted input as key names in options.imports. Only use developer-controlled, static key names.

*Source: trivy*
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +16 to +18
function chunk<T>(items: readonly T[], size: number): T[][] {
const chunks: T[][] = [];
for (let i = 0; i < items.length; i += size) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (bug_risk): Guard against non-positive size in chunk to avoid infinite loops or unexpected behavior.

This implementation assumes size > 0. If size is 0 or negative (including via a computed value), i += size will not progress correctly, leading to an infinite loop or invalid slicing. Consider guarding or normalizing size (e.g. early-return [] for size <= 0 or clamping to 1) to avoid subtle runtime failures and align with lodash’s behavior.

Comment on lines +8 to +11
* ```ts
* // vite.config.ts
* export default defineConfig({
* define: { __GRILL_ERROR_MESSAGES__: "false" },

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (bug_risk): The config examples define __GRILL_ERROR_MESSAGES__ as a string, which won’t disable messages under the current typeof check.

Because define: { __GRILL_ERROR_MESSAGES__: "false" } is substituted as a string, it won’t satisfy typeof __GRILL_ERROR_MESSAGES__ === "boolean" and will default to true, keeping error messages enabled despite the docs. Please either update the examples to use a boolean literal (no quotes / bundler boolean syntax) or adjust the runtime check to also handle string values like "false"/"true" so the documented config behaves as described.

Comment thread bun.lock Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/grill/src/hooks/use-token-info.ts`:
- Line 58: Update packages/grill/src/hooks/use-token-info.ts:58-58 and
packages/grill/src/hooks/use-token-infos.ts:94-94 to assign each validator a
stable validation-policy key in the provider configuration, then update
createTokenInfoQueryKey to include that key alongside the mint. Keep the
validator function itself out of the cache key so token-info entries remain
separated between shallow and Zod validation policies.

In `@packages/solana-errors/src/flags.ts`:
- Around line 25-39: The comments around ERROR_MESSAGES_ENABLED incorrectly
present table removal as unconditional. Qualify the dead-code-elimination
statement to note that bundlers remove the tables only after constant folding,
while the unbundled tsdown output preserves __GRILL_ERROR_MESSAGES__ for
replacement by the consumer bundler’s define configuration.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 51ce46af-10f1-4c68-a7eb-8eaa227f9b75

📥 Commits

Reviewing files that changed from the base of the PR and between 7f1777a and 2d68f3c.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (21)
  • .changeset/inline-chunk.md
  • .changeset/optional-error-messages.md
  • .changeset/optional-token-metadata-validation.md
  • packages/gill-extra/src/fetch-token-info-for-mint.ts
  • packages/gill-extra/src/fetch-token-info.ts
  • packages/gill-extra/src/index.ts
  • packages/gill-extra/src/token-metadata-validator.test.ts
  • packages/gill-extra/src/token-metadata-validator.ts
  • packages/grill/src/contexts/grill-context.ts
  • packages/grill/src/hooks/use-token-info.ts
  • packages/grill/src/hooks/use-token-infos.ts
  • packages/grill/src/providers/grill-headless-provider.tsx
  • packages/solana-batch-accounts-loader/package.json
  • packages/solana-batch-accounts-loader/src/createBatchAccountsLoader.ts
  • packages/solana-errors/README.md
  • packages/solana-errors/src/flags.ts
  • packages/solana-errors/src/index.ts
  • packages/solana-errors/src/instruction-error.ts
  • packages/solana-errors/src/transaction-error.ts
  • packages/zod-solana/src/index.ts
  • packages/zod-solana/src/zod-token-metadata-validator.ts
💤 Files with no reviewable changes (1)
  • packages/solana-batch-accounts-loader/package.json

mint: mintAccount,
metadata: metadataAccount?.data ?? null,
fetchFromCertifiedTokenList,
validateMetadata: validateTokenMetadata,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 5 '\bcreateTokenInfoQueryKey\b|validateTokenMetadata|validateMetadata' \
  packages/grill/src

fd -t f -e ts -e tsx . packages/grill | sort | while IFS= read -r file; do
  rg -n -C 4 'useTokenInfo|useTokenInfos|GrillHeadlessProvider|GrillProvider' "$file" || true
done

Repository: macalinao/grill

Length of output: 19192


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- relevant source ---'
cat -n packages/grill/src/query-keys.ts
sed -n '1,130p' packages/grill/src/hooks/use-token-info.ts | cat -n
sed -n '1,135p' packages/grill/src/hooks/use-token-infos.ts | cat -n
sed -n '1,180p' packages/grill/src/providers/grill-headless-provider.tsx | cat -n

printf '%s\n' '--- validator definitions and package references ---'
rg -n -C 5 'TokenMetadataValidator|defaultTokenMetadataValidator|zodTokenMetadataValidator|fetchTokenInfo' \
  --glob '!node_modules' --glob '!dist' --glob '!build' .
rg -n -C 3 '`@macalinao/gill-extra`|`@macalinao/zod-solana`' \
  package.json packages/*/package.json pnpm-lock.yaml yarn.lock package-lock.json 2>/dev/null || true

Repository: macalinao/grill

Length of output: 47349


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- dependency metadata ---'
git ls-files | rg '(^|/)(package.json|pnpm-lock.yaml|yarn.lock|package-lock.json)$' | sort
for file in package.json packages/grill/package.json pnpm-lock.yaml yarn.lock package-lock.json; do
  if [ -f "$file" ]; then
    printf '\n--- %s ---\n' "$file"
    rg -n -C 4 '`@macalinao/gill-extra`|`@macalinao/zod-solana`|`@tanstack/react-query`|gill-extra' "$file" || true
  fi
done

printf '%s\n' '--- local package sources ---'
git ls-files | rg 'gill-extra|zod-solana|token.*info|metadata.*validator' || true

Repository: macalinao/grill

Length of output: 4892


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- token-info transformation ---'
sed -n '1,180p' packages/gill-extra/src/fetch-token-info.ts | cat -n
sed -n '1,130p' packages/gill-extra/src/token-metadata-validator.ts | cat -n
sed -n '1,180p' packages/zod-solana/src/token-metadata-schema.ts | cat -n
sed -n '1,90p' packages/zod-solana/src/zod-token-metadata-validator.ts | cat -n

printf '%s\n' '--- query-client usage and cache invalidation ---'
rg -n -C 5 'invalidateQueries|removeQueries|resetQueries|setQueryData|getQueryData|createTokenInfoQueryKey' \
  packages/grill/src apps packages/*/src --glob '*.ts' --glob '*.tsx' || true

Repository: macalinao/grill

Length of output: 38762


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from dataclasses import dataclass
from typing import Any

# Standalone behavioral probe matching the two validator contracts shown in the
# repository. It does not import or execute repository code.
def shallow(value: Any):
    if not isinstance(value, dict):
        return None
    if not isinstance(value.get("name"), str) or not isinstance(value.get("symbol"), str):
        return None
    result = {"name": value["name"], "symbol": value["symbol"]}
    for key in ("description", "image", "animation_url", "external_url"):
        if isinstance(value.get(key), str):
            result[key] = value[key]
    return result

def full_schema(value: Any):
    if not isinstance(value, dict):
        return None
    required = ("name", "symbol", "description", "image")
    if any(not isinstance(value.get(key), str) for key in required):
        return None
    return value

payload = {
    "name": "Example",
    "symbol": "EX",
    "description": "A token",
    "image": "https://example.test/token.png",
    "attributes": "not-an-array",
}
shallow_result = shallow(payload)
zod_result = full_schema(payload)
assert shallow_result is not None
assert zod_result is None
assert shallow_result != zod_result

# The current key construction has no validator component, so both policies
# address the same cache entry for the same mint.
mint = "Mint111111111111111111111111111111111111111"
current_key_default = ("solana", "tokenInfo", mint)
current_key_full = ("solana", "tokenInfo", mint)
assert current_key_default == current_key_full

print("validator outputs differ:", shallow_result is not None, zod_result is None)
print("current query keys collide:", current_key_default == current_key_full)
PY

Repository: macalinao/grill

Length of output: 242


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from typing import Any

def shallow(value: Any):
    if not isinstance(value, dict):
        return None
    if not isinstance(value.get("name"), str) or not isinstance(value.get("symbol"), str):
        return None
    return {
        key: value[key]
        for key in ("name", "symbol", "description", "image", "animation_url", "external_url")
        if key in value and (key in ("name", "symbol") or isinstance(value[key], str))
    }

def zod_like(value: Any):
    if not isinstance(value, dict):
        return None
    if not isinstance(value.get("name"), str) or not isinstance(value.get("symbol"), str):
        return None
    optional_strings = ("description", "image", "animation_url", "external_url")
    if any(key in value and not isinstance(value[key], str) for key in optional_strings):
        return None
    attributes = value.get("attributes")
    if attributes is not None:
        if not isinstance(attributes, list):
            return None
        for attribute in attributes:
            if not isinstance(attribute, dict):
                return None
            if not isinstance(attribute.get("trait_type"), str):
                return None
            if not isinstance(attribute.get("value"), (str, int, float)) or isinstance(attribute.get("value"), bool):
                return None
    return {key: value[key] for key in ("name", "symbol", "description", "image", "animation_url", "external_url") if key in value}

payload = {
    "name": "URI name",
    "symbol": "URI",
    "image": "https://example.test/image.png",
    "attributes": "not-an-array",
}
shallow_result = shallow(payload)
zod_result = zod_like(payload)
assert shallow_result is not None
assert zod_result is None

on_chain = {"name": "On-chain name", "symbol": "CHAIN"}
shallow_token_info = {
    "name": shallow_result["name"],
    "symbol": shallow_result["symbol"],
    "image": shallow_result["image"],
}
zod_token_info = {
    "name": on_chain["name"],
    "symbol": on_chain["symbol"],
    "image": None,
}
assert shallow_token_info != zod_token_info

mint = "Mint111111111111111111111111111111111111111"
assert ("solana", "tokenInfo", mint) == ("solana", "tokenInfo", mint)

print("shallow accepts:", shallow_result is not None)
print("zod rejects:", zod_result is None)
print("token-info outputs differ:", shallow_token_info != zod_token_info)
print("current query keys collide:", True)
PY

Repository: macalinao/grill

Length of output: 258


Separate token-info cache entries by validation policy.

Both hooks pass validateTokenMetadata to fetchTokenInfo, but createTokenInfoQueryKey uses only the mint. The shallow validator can accept metadata that the Zod validator rejects, which produces different token information for the same mint. A fresh cached result can therefore use the wrong validation policy.

Add a stable validation-policy key to the provider configuration and include it in createTokenInfoQueryKey. Do not use the validator function itself as the key.

  • packages/grill/src/hooks/use-token-info.ts
  • packages/grill/src/hooks/use-token-infos.ts
📍 Affects 2 files
  • packages/grill/src/hooks/use-token-info.ts#L58-L58 (this comment)
  • packages/grill/src/hooks/use-token-infos.ts#L94-L94
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/grill/src/hooks/use-token-info.ts` at line 58, Update
packages/grill/src/hooks/use-token-info.ts:58-58 and
packages/grill/src/hooks/use-token-infos.ts:94-94 to assign each validator a
stable validation-policy key in the provider configuration, then update
createTokenInfoQueryKey to include that key alongside the mint. Keep the
validator function itself out of the cache key so token-info entries remain
separated between shallow and Zod validation policies.

Comment thread packages/solana-errors/src/flags.ts Resolved
Removing the direct `lodash-es` dependency from solana-batch-accounts-loader
also removed the only thing hoisting lodash-es to 4.18.1. The remaining
transitive dependency (@toruslabs/solana-embed, `^4.17.21`) resolved back
down to 4.17.21, which is vulnerable to CVE-2026-4800, and trivy flagged
the changed lockfile line.

Add a root override so lodash-es stays on 4.18.1 regardless of which
transitive dependency pulls it in.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@package.json`:
- Around line 87-88: Add a root package.json override for lodash set to ^4.18.0,
then regenerate bun.lock so transitive Lodash resolutions, including those from
`@walletconnect/universal-provider`, use the overridden patched version.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 5efd2c77-8f77-4ee0-8ed0-0b8f8e4ee4ab

📥 Commits

Reviewing files that changed from the base of the PR and between 4f6ec8e and ef6fddd.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • package.json

Comment thread package.json
Comment on lines +87 to +88
"@solana/kit": "^7.0.0",
"lodash-es": "^4.18.1"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

lockfiles="$(fd -t f -a -g 'pnpm-lock.yaml' -g 'yarn.lock' -g 'package-lock.json' . || true)"
test -n "$lockfiles" || { echo "No supported lockfile found"; exit 1; }

while IFS= read -r file; do
  echo "== $file =="
  rg -n -C 2 'lodash-es|lodash@|4\.17\.(2[0-3]|1[0-9]|[0-9])' "$file" || true
done <<< "$lockfiles"

Repository: macalinao/grill

Length of output: 301


🏁 Script executed:

set -euo pipefail

echo '== root package.json =='
sed -n '75,95p' package.json

echo '== supported lockfiles =='
find . -type f \( -name 'pnpm-lock.yaml' -o -name 'yarn.lock' -o -name 'package-lock.json' \) -print

echo '== workspace package manifests =='
find . -type f -name package.json -not -path './node_modules/*' -print

echo '== Lodash references in tracked files =='
rg -n -i 'lodash(-es)?|4\.17\.(2[0-3]|1[0-9]|[0-9])' --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' .

Repository: macalinao/grill

Length of output: 6870


🌐 Web query:

GHSA-r5fr-rjxr-66jc CVE-2026-4800 lodash lodash-es patched version

💡 Result:

The vulnerability tracked as GHSA-r5fr-rjxr-66jc and CVE-2026-4800 is a code injection vulnerability in the lodash library's _.template function [1][2]. The issue stems from insufficient validation of key names in the options.imports object, which can allow an attacker to inject arbitrary code at template compilation time [1][3]. The patched version for the affected packages, including lodash, lodash-es, lodash-amd, and lodash.template, is 4.18.0 [1][4]. Users of these packages are advised to upgrade to version 4.18.0 or later to mitigate this vulnerability [1][2]. As a workaround, developers should ensure that only static, developer-controlled key names are used in options.imports and avoid passing untrusted input as key names [1][5]. The fix in version 4.18.0 implements validation for import keys against the existing forbidden identifier character regex and replaces the use of assignInWith with assignWith to ensure only own properties are processed [1][2].

Citations:


🏁 Script executed:

set -euo pipefail

echo '== root manifest dependencies and overrides =='
cat -n package.json | sed -n '1,110p'

echo '== lockfile package entries =='
cat -n bun.lock | sed -n '300,325p;1420,1440p;2160,2185p'

echo '== all manifest lodash references =='
rg -n -i '"lodash(-es)?("|:)|lodash\.' --glob 'package.json' --glob '!node_modules/**' .

echo '== lockfile header and workspace sections =='
cat -n bun.lock | sed -n '1,40p;250,330p'

Repository: macalinao/grill

Length of output: 16092


🏁 Script executed:

python3 - <<'PY'
from pathlib import Path
import re

manifest = Path("package.json").read_text()
lock = Path("bun.lock").read_text()

def manifest_override(name):
    m = re.search(rf'"{re.escape(name)}"\s*:\s*"([^"]+)"', manifest)
    return m.group(1) if m else None

def lock_package_version(name):
    m = re.search(
        rf'^\s*"{re.escape(name)}":\s*\["{re.escape(name)}@([^"]+)"',
        lock,
        re.MULTILINE,
    )
    return m.group(1) if m else None

def lock_dependency_refs(name):
    pattern = rf'"{re.escape(name)}"\s*:\s*"([^"]+)"'
    return sorted(set(re.findall(pattern, lock)))

for name in ("lodash", "lodash-es"):
    print({
        "package": name,
        "manifest_override": manifest_override(name),
        "locked_package_version": lock_package_version(name),
        "lock_dependency_refs": lock_dependency_refs(name),
    })

print("lodash_4_17_21_refs:", len(re.findall(r'"lodash"\s*:\s*"4\.17\.21"', lock)))
print("lodash_es_below_4_18_0:",
      bool(re.search(r'"lodash-es@4\.(?:[0-9]|1[0-7])(?:\.\d+)?', lock)))
PY

Repository: macalinao/grill

Length of output: 470


🌐 Web query:

Bun package.json overrides documentation force transitive dependency version

💡 Result:

To force a specific version of a transitive dependency in Bun, you use the "overrides" or "resolutions" fields in your package.json file [1][2]. These fields allow you to pin a dependency to a specific version or range, forcing all references within your dependency tree—whether direct or transitive—to resolve to that version [1][2][3]. Key implementation details: 1. Overrides: Add an "overrides" field to the top level of your package.json [1][2]. This is the standard approach, consistent with npm [1]. { "overrides": { "target-package": "1.2.3" } } 2. Resolutions: Bun also supports the "resolutions" field, which is primarily used by Yarn [1][2]. You can use this field interchangeably with "overrides" to achieve the same result [1][2]. { "resolutions": { "target-package": "1.2.3" } } Important limitations and considerations: - Top-level only: Bun currently supports only top-level overrides and resolutions [1][2]. It does not support nested overrides (where an override is scoped to a specific dependency path) [1][2]. - Broad application: Once defined, the override applies globally to the dependency tree, ensuring that all occurrences of the specified package are pinned to your chosen version [2][3]. - Transitive updates without modifying package.json: If your goal is to update transitive dependencies to the highest in-range version (often for CVE remediation) without manually pinning them in package.json, you can use the command: bun update --transitive [4] This command forces a re-resolution of transitive dependencies in your bun.lock file based on the ranges already declared in your dependency tree [4].

Citations:


Add a lodash override and regenerate bun.lock.

The lockfile still resolves lodash@4.17.21 through @walletconnect/universal-provider. Add "lodash": "^4.18.0" to the root overrides so all affected Lodash packages use patched versions.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@package.json` around lines 87 - 88, Add a root package.json override for
lodash set to ^4.18.0, then regenerate bun.lock so transitive Lodash
resolutions, including those from `@walletconnect/universal-provider`, use the
overridden patched version.

@macalinao
macalinao merged commit 50e54ff into master Aug 12, 2026
10 checks passed
@macalinao
macalinao deleted the optional-zod-validation branch August 12, 2026 12:41
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.

1 participant