Skip to content

feat: format in genlayer js to convert to an object - #107

Merged
cristiam86 merged 4 commits into
mainfrom
dxp-427-format-in-genlayer-js-to-convert-to-an-object
Sep 4, 2025
Merged

cristiam86 merged 4 commits into
mainfrom
dxp-427-format-in-genlayer-js-to-convert-to-an-object

Conversation

@epsjunior

@epsjunior epsjunior commented Aug 21, 2025 •

Copy link
Copy Markdown
Contributor

What

  • Added deep JSON-safe conversion utility to handle decoded contract returns:
    • Map → plain object
    • bigint → number if safe, otherwise decimal string
    • Uint8Array → 0x-hex string
    • CalldataAddress → 0x-hex string
    • Recursive handling for nested arrays/objects/maps and cycle protection
  • Added jsonSafeReturn?: boolean option to readContract (default false) to return decoded results as JSON-safe objects
  • Updated types to expose jsonSafeReturn in GenLayerClient.readContract signature

Why

  • Contract reads can return complex structures (Maps, bigints, nested objects) that break JSON parsing and standard console logging
  • The CLI uses Node’s inspect for logs; we also need an option to return a JSON-safe object for programmatic consumption
  • Preserves backward compatibility by keeping the default behavior unchanged

Testing done

  • Manually tested using Rally’s project by calling get_submissions
  • Manually tested with wizard_of_coin and football_prediction_market contracts
  • Verified:
    • Nested Maps and arrays convert correctly into plain objects
    • BigInts convert to number when within Number.MAX_SAFE_INTEGER, otherwise to string
    • Uint8Array and CalldataAddress render as 0x-prefixed hex
    • Default behavior (without jsonSafeReturn) remains unchanged

Decisions made

  • BigInt conversion: number if abs(value) <= Number.MAX_SAFE_INTEGER, else decimal string for safety
  • Map conversion: to plain object for better ergonomics and JSON serialization
  • Byte-like values (Uint8Array) and addresses (CalldataAddress) standardized to 0x-hex strings
  • Cycle handling: break potential reference cycles with a WeakSet and return null when a cycle is detected
  • API shape: opt-in via jsonSafeReturn with default false to avoid breaking changes

Checks

  • I have tested this code
  • I have reviewed my own PR
  • I have created an issue for this PR
  • I have set a descriptive PR title compliant with conventional commits

Reviewing tips

  • Focus on:
    • src/contracts/actions.ts: new jsonSafeReturn option and application post-decode
    • src/utils/jsonifier.ts: toJsonSafeDeep implementation and conversion rules
    • src/types/clients.ts: updated readContract signature
  • Pay extra attention to bigint and Map conversions and the cycle handling logic

User facing release notes

  • Added jsonSafeReturn option to readContract. When enabled, decoded contract results are returned as JSON-safe objects:
    • Map → plain object
    • bigint → number (if safe) or string
    • Uint8Array/CalldataAddress → 0x-hex strings
    • Works recursively for nested structures
  • Default behavior remains unchanged; enable with:
    const result = await client.readContract({
      address,
      functionName: "myFn",
      jsonSafeReturn: true,
    });

Summary by CodeRabbit

  • New Features
    • Added an optional jsonSafeReturn flag to readContract. When enabled, results are returned in a JSON-safe format (e.g., large integers and binary data are converted to serializable values), reducing serialization errors with complex or nested data.
    • Backward compatible: default behavior unchanged unless jsonSafeReturn is explicitly set to true.
    • Deep serialization now handles arrays, maps, addresses, binary blobs and detects cycles to avoid infinite recursion.

@coderabbitai

coderabbitai Bot commented Aug 21, 2025 •

Copy link
Copy Markdown

Walkthrough

Adds an optional jsonSafeReturn flag to readContract (runtime) and GenLayerClient types; when true, readContract post-processes decoded results with a new toJsonSafeDeep utility that produces JSON-serializable, cycle-safe representations of calldata-related structures.

Changes

Cohort / File(s) Summary of changes
readContract JSON-safe option
src/contracts/actions.ts
Adds optional jsonSafeReturn?: boolean to readContract args; conditionally passes decoded results through toJsonSafeDeep; adds import for toJsonSafeDeep.
Client type surface update
src/types/clients.ts
Extends GenLayerClient.readContract args with jsonSafeReturn?: boolean (alongside existing rawReturn and transactionHashVariant).
JSON serialization utility
src/utils/jsonifier.ts
Adds toJsonSafeDeep<T extends CalldataEncodable>(value: T): any with deep, cycle-safe conversion rules (bigint handling, Uint8Array/address hex, arrays, maps, plain objects); uses WeakSet to detect cycles and returns null for cycles.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant Contracts as contracts.readContract
  participant Decoder
  participant Jsonifier as toJsonSafeDeep

  Caller->>Contracts: readContract(args { ..., jsonSafeReturn? })
  Contracts->>Decoder: decode(result)
  Decoder-->>Contracts: decodedValue

  alt jsonSafeReturn = true
    Contracts->>Jsonifier: toJsonSafeDeep(decodedValue)
    Jsonifier-->>Contracts: jsonSafeValue
    Contracts-->>Caller: jsonSafeValue
  else jsonSafeReturn = false
    Contracts-->>Caller: decodedValue
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • cristiam86

Poem

A nibble of flags, a byte turned neat,
I hop through calldata with JSON feet.
Bigints tamed, hex strings gleam,
Cycles vanish—no endless stream.
Flip the flag—results shine sweet. 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4708402 and 44e8daa.

📒 Files selected for processing (2)
  • src/contracts/actions.ts (4 hunks)
  • src/types/clients.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/contracts/actions.ts
  • src/types/clients.ts
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dxp-427-format-in-genlayer-js-to-convert-to-an-object

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@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

🧹 Nitpick comments (8)
src/utils/jsonifier.ts (5)

52-59: Fix doc drift: Map conversion comment contradicts implementation. Consider exporting a JsonSafe type.

  • The comment says “Map: to Array<[key, value]>”, but the code below converts Maps to plain objects. Please align the comment with the actual behavior to avoid confusion for maintainers.
  • Also, consider exporting a JsonSafe type so downstream APIs can reflect the shape when jsonSafeReturn is enabled.

Apply this doc-only change:

-// - Map: to Array<[key, value]> preserving order
+// - Map: to a plain object preserving iteration order (keys coerced to strings)

Optionally add a JsonSafe type (see related suggestions in types/clients.ts and actions.ts comments).


68-78: Use Number.MAX_SAFE_INTEGER for readability.

Functionally correct, but this small change improves clarity and avoids magic numbers.

-    const maxSafe = 9007199254740991n; // Number.MAX_SAFE_INTEGER
+    const maxSafe = BigInt(Number.MAX_SAFE_INTEGER);

92-95: Prefer Array.isArray over instanceof Array for cross-realm safety.

Minor robustness improvement when values may originate from different realms.

-    if (value instanceof Array) {
+    if (Array.isArray(value)) {
       return value.map((v) => _toJsonSafeDeep(v as CalldataEncodable, seen));
     }

63-87: Cycle handling returns null; consider an explicit marker for debugging.

Returning null is safe, but makes it hard to distinguish between “value was null” and “value replaced due to cycle.” Consider returning a sentinel string like "<cycle>" or augmenting with an optional callback hook to observe cycle drops. Not blocking.


117-118: Fallback can leak unsupported types into consumers.

If a non-CalldataEncodable sneaks through, returning it “as-is” may reintroduce non-JSON-safe values. Consider either throwing, or stringifying unknown instances as a conservative fallback.

Example conservative fallback:

-  return value as any;
+  try {
+    return JSON.parse(JSON.stringify(value));
+  } catch {
+    return String(value);
+  }
src/contracts/actions.ts (2)

45-56: Clarify interaction between rawReturn and jsonSafeReturn; consider typing it.

  • Behavior: when rawReturn is true, the method returns the raw hex and ignores jsonSafeReturn. This is sensible; please document this precedence.
  • Typing: current signature doesn’t reflect the JSON-safe return shape when jsonSafeReturn is true; downstream TypeScript users won’t get helpful types.

Would you like me to update the public docs/JSDoc to state that jsonSafeReturn is ignored when rawReturn is true?

Type-level suggestion is provided in a follow-up comment for both this file and src/types/clients.ts.


82-88: Reflect JSON-safe return type and drop as any casts.

Leverage a conditional type parameter for jsonSafeReturn so callers get accurate types when opting in.

Apply this diff to align the function signature and returns. This matches a complementary change in src/types/clients.ts.

-    readContract: async <RawReturn extends boolean | undefined>(args: {
+    readContract: async <
+      RawReturn extends boolean | undefined,
+      JsonSafeFlag extends boolean | undefined = undefined
+    >(args: {
       account?: Account;
       address: Address;
       functionName: string;
       args?: CalldataEncodable[];
       kwargs?: Map<string, CalldataEncodable> | {[key: string]: CalldataEncodable};
       rawReturn?: RawReturn;
-      jsonSafeReturn?: boolean;
+      jsonSafeReturn?: JsonSafeFlag;
       leaderOnly?: boolean;
       transactionHashVariant?: TransactionHashVariant;
-    }): Promise<RawReturn extends true ? `0x${string}` : CalldataEncodable> => {
+    }): Promise<
+      RawReturn extends true
+        ? `0x${string}`
+        : JsonSafeFlag extends true
+          ? import("@/types/json").JsonSafe
+          : CalldataEncodable
+    > => {
@@
-      const decoded = calldata.decode(resultBinary) as any;
+      const decoded = calldata.decode(resultBinary) as CalldataEncodable;
       if (!jsonSafeReturn) {
         return decoded;
       }
       // If jsonSafeReturn is requested, convert to JSON-safe recursively
-      return toJsonSafeDeep(decoded) as any;
+      return toJsonSafeDeep(decoded);

Note: you’ll need to add a type-only import for JsonSafe:

import type { JsonSafe } from "@/types/json";
src/types/clients.ts (1)

49-49: Update the readContract type to encode JSON-safe return shape.

Right now, the return type is always CalldataEncodable when rawReturn is false, but the value is transformed when jsonSafeReturn is true. Encode this in the type so consumers get accurate intellisense.

Apply this diff to refine the generics and the return type:

-    readContract: <RawReturn extends boolean | undefined>(args: {
+    readContract: <
+      RawReturn extends boolean | undefined,
+      JsonSafeFlag extends boolean | undefined = undefined
+    >(args: {
       account?: Account;
       address: Address;
       functionName: string;
       args?: CalldataEncodable[];
       kwargs?: Map<string, CalldataEncodable> | {[key: string]: CalldataEncodable};
       rawReturn?: RawReturn;
-      jsonSafeReturn?: boolean;
+      jsonSafeReturn?: JsonSafeFlag;
       transactionHashVariant?: TransactionHashVariant;
-    }) => Promise<RawReturn extends true ? `0x${string}` : CalldataEncodable>;
+    }) => Promise<
+      RawReturn extends true
+        ? `0x${string}`
+        : JsonSafeFlag extends true
+          ? import("@/types/json").JsonSafe
+          : CalldataEncodable
+    >;

Additionally, add a type-only import for JsonSafe and define it in a dedicated types module to avoid creating a types ↔ utils circular dependency:

// at the top (outside of this diff hunk)
import type { JsonSafe } from "@/types/json";

Create src/types/json.ts with:

export type JsonSafe =
  | null
  | boolean
  | number
  | string
  | { [k: string]: JsonSafe }
  | JsonSafe[];
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 0c4024b and 4708402.

📒 Files selected for processing (3)
  • src/contracts/actions.ts (4 hunks)
  • src/types/clients.ts (1 hunks)
  • src/utils/jsonifier.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/contracts/actions.ts (2)
src/abi/index.ts (1)
  • calldata (4-4)
src/utils/jsonifier.ts (1)
  • toJsonSafeDeep (59-61)
🔇 Additional comments (4)
src/utils/jsonifier.ts (3)

2-4: Correct runtime import for class used with instanceof.

Importing CalldataAddress as a value (not type-only) is necessary since it’s used with instanceof. Looks good.


104-106: LGTM on CalldataAddress handling.

Returning 0x-hex from CalldataAddress.bytes aligns with the JSON-safe intent and is consistent with Uint8Array handling.


96-103: I’ve prepared a quick script to verify the Map‐handling code and see how CalldataEncodable is defined (to confirm whether Map keys can only be strings). Once we have those outputs, we can confirm if prototype-pollution safeguards and key‐coercion are needed or if string-only keys are already enforced.

Looking forward to the results.

src/contracts/actions.ts (1)

14-14: Import of toJsonSafeDeep is correct and scoped.

Dependency added only where needed. Good separation of concerns.

Comment thread src/utils/jsonifier.ts
@epsjunior
epsjunior requested a review from cristiam86 September 3, 2025 18:08
@cristiam86
cristiam86 merged commit 3ca4076 into main Sep 4, 2025
2 checks passed
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.

2 participants