Skip to content

feat: expose encode and decode methods - #102

Merged
epsjunior merged 6 commits into
mainfrom
dxp-120-feat-expose-encode-and-decode-methods
Jul 30, 2025
Merged

epsjunior merged 6 commits into
mainfrom
dxp-120-feat-expose-encode-and-decode-methods

Conversation

@epsjunior

@epsjunior epsjunior commented Jul 24, 2025 •

Copy link
Copy Markdown
Contributor

Expose Encode and Decode Methods for Developer Use

Summary

This PR exposes key encode and decode methods at the root of the GenLayer JS library, making them directly accessible for developers. The refactor clarifies the separation between low-level serialization and high-level transaction decoding, centralizes calldata construction, and improves the public API for discoverability and ease of use. The decision to use direct named exports over namespace exports is based on best practices for developer ergonomics and clarity.

Changes

🚀 New Features

  • Public API Exposure:
    • Exposed the following high-level transaction utilities at the package root:
      • decodeInputData
      • decodeTransaction
      • simplifyTransactionReceipt
      • decodeLocalnetTransaction
  • Centralized Calldata Construction:
    • Moved and exported makeCalldataObject from src/abi/calldata/encoder.ts, making it available for all internal and external usage.

🏗️ Implementation Details

  • Separation of Concerns:
    • Low-level serialization remains in src/abi/transactions.ts and is not exposed at the top level.
    • High-level transaction decoding and transformation is handled in src/transactions/decoders.ts and is now part of the public API.
    • Calldata encoding/decoding logic is kept in src/abi/calldata/encoder.ts and decoder.ts.
  • Export Strategy Decision:
    • After careful consideration, we chose to export high-level transaction utilities as direct named exports rather than under a namespace (e.g., transactions.decodeTransaction).
    • Rationale:
      • Direct named exports are more ergonomic and idiomatic for most JavaScript/TypeScript libraries.
      • They provide a flat, discoverable API surface, making it easier for developers to import only what they need.
      • Namespace exports are more appropriate for very large or highly modular APIs, which is not the case here.

📁 File Structure

src/
├── abi/
│   └── calldata/
│       └── encoder.ts         # makeCalldataObject exported here
│   └── transactions.ts        # Low-level serialization (hex, RLP)
├── transactions/
│   └── decoders.ts            # High-level transaction decoding/simplification
│   └── actions.ts             # Uses centralized decoders and calldata helpers
├── contracts/
│   └── actions.ts             # Imports makeCalldataObject from abi/calldata/encoder
└── index.ts                   # Exposes all public API methods

🧪 Testing

  • Regression Testing: All existing tests pass, ensuring no breaking changes.
  • Type Safety: All exports are fully typed for TypeScript consumers.

🔧 Usage

// Direct, ergonomic imports for developers:
import { decodeTransaction, decodeInputData, makeCalldataObject } from "genlayer-js";

✨ Code Quality

  • Single Source of Truth: No duplicate logic for calldata object construction.
  • Clear API Surface: All public functions are exported from src/index.ts for ergonomic imports.
  • TypeScript Integration: All utilities are fully typed and maintain type safety.

🎯 Export Strategy Features

  • Direct Named Exports: Chosen for simplicity, discoverability, and alignment with JS/TS ecosystem best practices.
  • Namespace Exports Considered: Not used, as the API surface is not large enough to warrant grouping, and direct exports are more ergonomic for consumers.

🛡️ Backward Compatibility

  • No Breaking Changes: All existing imports and usage patterns continue to work.
  • Improved Discoverability: Developers can now find and use transaction and calldata utilities more easily.

Testing: ✅ All tests pass
Type Safety: ✅ Full TypeScript integration
Documentation: ✅ Public API is clear and discoverable
Architecture: ✅ Follows modular, domain-driven structure
User Experience: ✅ Developers can now use encode/decode methods directly


Summary by CodeRabbit

  • New Features
    • Added utilities for decoding and simplifying blockchain transactions, including functions to decode input data, transactions, and receipts.
    • Introduced support for decoding localnet transactions with user-friendly JSON output.
  • Refactor
    • Centralized calldata object construction for contract calls, ensuring only non-empty fields are included.
    • Consolidated transaction decoding and simplification logic into dedicated utilities, improving maintainability.
  • Chores
    • Updated exports to make new decoder utilities available from the main entry point.

@coderabbitai

coderabbitai Bot commented Jul 24, 2025 •

Copy link
Copy Markdown

Walkthrough

A new utility for constructing calldata objects was added and adopted across contract action methods, centralizing logic previously duplicated locally. Decoder and simplification logic for transactions was refactored into a dedicated module, with related functions now re-exported from the main entry point. Internal decoding implementations and unused imports were removed for modularity.

Changes

File(s) Change Summary
src/abi/calldata/encoder.ts Added makeCalldataObject function for constructing calldata objects with non-empty fields only.
src/contracts/actions.ts Removed local makeCalldataObject; updated usages to import from calldata encoder module.
src/index.ts Re-exported decoder utilities (decodeInputData, etc.) from ./transactions/decoders.
src/transactions/actions.ts Removed internal decoding/simplification logic; replaced with imports from ./decoders. Cleaned up imports.
src/transactions/decoders.ts New module: implements transaction decoding, input data decoding, receipt simplification, and localnet decoding.

Sequence Diagram(s)

sequenceDiagram
    participant ContractActions
    participant CalldataEncoder
    ContractActions->>CalldataEncoder: makeCalldataObject(method, args, kwargs)
    CalldataEncoder-->>ContractActions: {method, args, kwargs} (non-empty only)
Loading
sequenceDiagram
    participant TransactionActions
    participant Decoders
    TransactionActions->>Decoders: decodeTransaction(tx)
    Decoders-->>TransactionActions: Decoded transaction object

    TransactionActions->>Decoders: simplifyTransactionReceipt(tx)
    Decoders-->>TransactionActions: Simplified receipt
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

In the warren, code hops anew,
Calldata packed—now neat and true.
Decoders leap to their own domain,
Receipts are trimmed, no extra strain.
With every hop, the modules grow,
Rabbits cheer—modularity in tow!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-07-24T17_12_25_277Z-debug-0.log

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ 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-120-feat-expose-encode-and-decode-methods

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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai 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

Documentation and Community

  • 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: 0

🧹 Nitpick comments (3)
src/abi/calldata/encoder.ts (1)

167-170: Consider using a more idiomatic approach for checking object emptiness.

The current implementation works correctly but could be more readable.

Consider using Object.keys(kwargs).length > 0 instead:

    } else {
-     let hasVal = false;
-     for (const _k in kwargs) {
-       hasVal = true;
-       break;
-     }
-     if (hasVal) {
+     if (Object.keys(kwargs).length > 0) {
        ret["kwargs"] = kwargs;
      }
    }
src/transactions/decoders.ts (2)

59-73: Consider using a proper logging mechanism instead of console methods.

Direct console usage in library code can clutter user applications and lacks configurability.

Consider accepting an optional logger parameter or using a logging library that can be configured by consumers:

-      console.warn(
-        "[decodeInputData] WRITE: Unexpected RLP array length:",
-        rlpDecodedArray.length,
-        rlpDecodedArray,
-      );
+      // Use a configurable logger or allow consumers to handle unexpected cases
+      // logger?.warn("[decodeInputData] WRITE: Unexpected RLP array length:", rlpDecodedArray.length);

213-216: Consider extracting the inclusion logic for better readability.

The condition for determining whether to include a value is complex and spans multiple lines.

Consider extracting this logic into a helper function:

-        const shouldInclude = simplifiedValue !== undefined && 
-          !(typeof simplifiedValue === "object" && simplifiedValue !== null && Object.keys(simplifiedValue).length === 0);
-        
-        if (shouldInclude || simplifiedValue === 0) {
+        const shouldIncludeValue = (value: any): boolean => {
+          if (value === undefined) return false;
+          if (value === 0) return true; // Special case for numeric 0
+          if (typeof value === "object" && value !== null && Object.keys(value).length === 0) return false;
+          return true;
+        };
+        
+        if (shouldIncludeValue(simplifiedValue)) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 598cc23 and 5dc0d81.

📒 Files selected for processing (5)
  • src/abi/calldata/encoder.ts (1 hunks)
  • src/contracts/actions.ts (3 hunks)
  • src/index.ts (1 hunks)
  • src/transactions/actions.ts (4 hunks)
  • src/transactions/decoders.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/abi/calldata/encoder.ts (1)
src/types/calldata.ts (1)
  • CalldataEncodable (13-23)
src/transactions/actions.ts (2)
src/index.ts (3)
  • decodeLocalnetTransaction (8-8)
  • simplifyTransactionReceipt (7-7)
  • decodeTransaction (6-6)
src/types/transactions.ts (1)
  • GenLayerTransaction (142-256)
src/contracts/actions.ts (1)
src/abi/index.ts (1)
  • calldata (4-4)
🔇 Additional comments (7)
src/abi/calldata/encoder.ts (1)

144-178: Well-implemented calldata construction utility!

The function correctly centralizes calldata object construction with proper handling of optional parameters and empty field omission. This aligns perfectly with the PR's goal of exposing key utilities.

src/contracts/actions.ts (1)

57-57: Correct adoption of centralized calldata construction.

All three usages properly integrate the new calldata.makeCalldataObject function:

  • readContract and writeContract correctly pass the function name
  • deployContract appropriately passes undefined for the method parameter when calling constructors

The refactoring successfully eliminates code duplication.

Also applies to: 101-101, 137-137

src/index.ts (1)

4-9: Clean exposure of decoder functions at package root.

The named exports provide an ergonomic API surface that aligns with JavaScript/TypeScript best practices. This successfully achieves the PR's goal of making transaction utilities easily discoverable.

src/transactions/actions.ts (1)

14-14: Proper delegation to centralized decoder module.

The refactoring successfully moves complex decoding logic to a dedicated module while maintaining the same API contracts. All decoder function calls are correctly placed based on chain type and transaction requirements.

Also applies to: 48-48, 51-51, 80-80, 91-91

src/transactions/decoders.ts (3)

77-119: Comprehensive transaction decoding implementation.

The function thoroughly handles all transaction fields with proper type conversions and status/result mapping. The consistent string conversion for numeric fields ensures API stability.


232-276: Well-structured localnet transaction decoder.

The function properly handles all localnet-specific fields with appropriate error handling for individual field decoding failures. The preservation of original base64 data alongside decoded values is a good practice.


1-276: Excellent modularization of transaction decoding logic!

This new module successfully centralizes and encapsulates all transaction decoding and simplification logic with:

  • Clear separation of concerns between different decoder functions
  • Comprehensive error handling
  • Well-documented behavior
  • Cross-language compatibility through field mappings

The refactoring achieves the PR's goals of improving API discoverability and maintainability.

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