Skip to content

feat: improve how cli shows transactions receipts - #250

Merged
epsjunior merged 4 commits into
mainfrom
dxp-608-improve-how-cli-shows-transactions-receipts
Sep 3, 2025
Merged

epsjunior merged 4 commits into
mainfrom
dxp-608-improve-how-cli-shows-transactions-receipts

Conversation

@epsjunior

@epsjunior epsjunior commented Sep 1, 2025 •

Copy link
Copy Markdown
Contributor

Summary

Adds --stdout and --stderr options to the receipt command, allowing users to print only the program’s stdout or stderr (or both) from a transaction’s receipt. Default behavior remains unchanged and prints the full receipt object.

Changes

🚀 New Features

  • Selective Output: New --stdout and --stderr flags for genlayer receipt <txId>
  • Dual Output: Using both flags prints both streams together
  • Default Behavior Preserved: No flags prints the full receipt as before

🔧 Implementation Details

  • ReceiptAction: Updated to accept stdout/stderr options and print:
    • result.consensus_data.leader_receipt[0].genvm_result.stdout
    • result.consensus_data.leader_receipt[0].genvm_result.stderr
  • CLI Registration: Exposed --stdout and --stderr in the receipt command
  • Messaging: Clear success messages for each mode:
    • “Transaction stdout retrieved successfully”
    • “Transaction stderr retrieved successfully”
    • “Transaction stdout and stderr”
    • Default: “Transaction receipt retrieved successfully”

📁 File Structure

src/
└── commands/
    └── transactions/
        ├── receipt.ts      # Add stdout/stderr handling
        └── index.ts        # Expose --stdout and --stderr flags

tests/
├── actions/
│   └── receipt.test.ts     # Add tests for stdout/stderr selection and messages
└── commands/
    └── receipt.test.ts     # Ensure CLI parses and forwards new flags

🏗️ Command Architecture

  • Command: genlayer receipt <txId>
  • Options:
    • --status <status> (default: FINALIZED)
    • --retries <retries> (default: 100)
    • --interval <ms> (default: 5000)
    • --rpc <rpcUrl>
    • --stdout (print only stdout)
    • --stderr (print only stderr)
  • Action Pattern: Follows BaseAction spinner and logging conventions
  • Client Management: Reuses existing client initialization and consensus contract setup

🧪 Testing

  • Action Tests (tests/actions/receipt.test.ts):

    • Default/full receipt behavior
    • stdout-only behavior and success message
    • stderr-only behavior and success message
    • stdout+stderr behavior with combined output
    • Status validation (valid and invalid)
    • Custom RPC handling and error handling
  • Command Tests (tests/commands/receipt.test.ts):

    • Default option invocation
    • Custom options parsing
    • Unknown option handling
    • Parsing --stdout, --stderr, and both flags together

🔧 Usage

# Full receipt (default)
genlayer receipt 0xabc...

# Stdout only
genlayer receipt 0xabc... --stdout

# Stderr only
genlayer receipt 0xabc... --stderr

# Both
genlayer receipt 0xabc... --stdout --stderr

✨ Code Quality

  • Consistent Patterns: Aligns with existing BaseAction and spinner usage
  • Type Safety: Typed flags in ReceiptParams and ReceiptOptions
  • Maintainable: Minimal, focused changes with tests

🔗 Dependencies

  • Reuses BaseAction and existing genlayer-js client initialization
  • No new external dependencies

🛡️ Backward Compatibility

  • No Breaking Changes: Default printing of full receipt preserved
  • Opt-in Flags: New flags only affect behavior when explicitly provided

📚 Documentation Updates

  • Add notes for --stdout and --stderr to the receipt command in README (follow-up doc tweak)

  • Implemented PR description for the new receipt flags and tests.

Summary by CodeRabbit

  • New Features

    • Added --stdout and --stderr flags to the transaction receipt command, enabling selective output of only stdout, only stderr, or both. When flags are used, only the requested data is printed; without flags, the full receipt is shown as before.
  • Tests

    • Expanded test coverage to validate flag parsing and output behavior for stdout-only, stderr-only, and combined scenarios, ensuring accurate messages and outputs.

… receipts

- Add stdout/stderr flags to ReceiptParams and handling in ReceiptAction
- Print consensus_data.leader_receipt[0].genvm_result.stdout/stderr when requested
- Keep default behavior to print full receipt when no flags are provided
- Update success messages for clarity
- Expose new flags for selective output
- Preserve default behavior without flags
…ss messages

- Add tests for stdout-only, stderr-only, and both flags
- Adjust structure to consensus_data.leader_receipt[0].genvm_result
- Verify updated succeedSpinner messages
- Verify options forwarded to ReceiptAction.receipt
- Add tests for both flags and individually
@coderabbitai

coderabbitai Bot commented Sep 1, 2025 •

Copy link
Copy Markdown

Walkthrough

Adds --stdout and --stderr flags to the transactions receipt command, threads them through ReceiptOptions/ReceiptParams, and updates ReceiptAction.receipt to conditionally print only stdout, only stderr, or both from the transaction receipt. Extends tests to cover flag parsing and output behavior. No other commands changed.

Changes

Cohort / File(s) Summary of changes
CLI flags for receipt
src/commands/transactions/index.ts
Introduces boolean flags --stdout and --stderr for receipt <txId>; passes them through the options object. Updates public ReceiptOptions accordingly.
Receipt action behavior
src/commands/transactions/receipt.ts
Extends ReceiptParams with stdout? and stderr?. Updates ReceiptAction.receipt to extract and print only requested stdout/stderr from genvm_result; prints both when both flags set; preserves default full-receipt output when no flags provided.
Action tests
tests/actions/receipt.test.ts
Adds three tests validating printing behavior for stdout-only, stderr-only, and both, using mocked receipt and spinner assertions.
Command tests
tests/commands/receipt.test.ts
Adds three tests ensuring CLI parses --stdout/--stderr and calls ReceiptAction.receipt with expected flags and defaults.

Sequence Diagram(s)

sequenceDiagram
  participant U as User
  participant CLI as transactions receipt
  participant RA as ReceiptAction
  participant RPC as Chain RPC
  participant OUT as Output/Spinner

  U->>CLI: receipt <txId> [--stdout] [--stderr]
  CLI->>RA: receipt({ txId, status, retries, interval, rpc, stdout?, stderr? })
  RA->>RPC: waitForTransactionReceipt(txId, { status, retries, interval, rpc })
  RPC-->>RA: receipt { ... genvm_result: { stdout, stderr } ... }

  alt stdout or stderr flagged
    RA->>OUT: print selected field(s)
    RA-->>CLI: return
  else no flags
    RA->>OUT: print full receipt
  end

  CLI-->>U: display output
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • cristiam86
  • danielrc888

Poem

I twitch my ears at flags so neat,
A nibble of stdout, a stderr treat.
Hops through receipts, select and show,
Only what you asked to know.
With whiskered logs and gentle cheer,
Your transaction’s tale is crystal clear. 🐇✨

✨ 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-608-improve-how-cli-shows-transactions-receipts

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/commands/transactions/receipt.ts (1)

21-34: Fix type-safety: validateTransactionStatus expects string but caller passes string | TransactionStatus.
This can fail type-checking and is easy to harden.

Use a union-safe call:

-      let validatedStatus = this.validateTransactionStatus(status);
+      const validatedStatus =
+        typeof status === "string" ? this.validateTransactionStatus(status) : status;

Optionally, also widen the helper’s signature to accept string | TransactionStatus and early-return when already valid.

Also applies to: 50-54

🧹 Nitpick comments (6)
src/commands/transactions/receipt.ts (1)

63-82: Stream-only output logic works; tighten edge handling and reduce repetition.

  • If either stream is absent, you’ll print undefined. Consider explicit fallbacks or a clearer message.
  • Minor DRY: compute message/payload once, then single succeedSpinner/return.

Apply this small refactor:

-      // If specific output flags are provided, print only those fields
-      if (stdout || stderr) {
-        const stdoutValue = (result as any)?.consensus_data?.leader_receipt[0]?.genvm_result?.stdout;
-        const stderrValue = (result as any)?.consensus_data?.leader_receipt[0]?.genvm_result?.stderr;
-
-        if (stdout && stderr) {
-          this.succeedSpinner("Transaction stdout and stderr", { stdout: stdoutValue, stderr: stderrValue });
-          return;
-        }
-
-        if (stdout) {
-          this.succeedSpinner("Transaction stdout retrieved successfully", stdoutValue);
-          return;
-        }
-
-        if (stderr) {
-          this.succeedSpinner("Transaction stderr retrieved successfully", stderrValue);
-          return;
-        }
-      }
+      // If specific output flags are provided, print only those fields
+      if (stdout || stderr) {
+        const receipt = (result as any)?.consensus_data?.leader_receipt?.[0]?.genvm_result ?? {};
+        const stdoutValue = receipt.stdout ?? "";
+        const stderrValue = receipt.stderr ?? "";
+
+        const both = stdout && stderr;
+        const msg = both
+          ? "Transaction stdout and stderr"
+          : stdout
+            ? "Transaction stdout retrieved successfully"
+            : "Transaction stderr retrieved successfully";
+        const payload = both ? { stdout: stdoutValue, stderr: stderrValue } : (stdout ? stdoutValue : stderrValue);
+        this.succeedSpinner(msg, payload);
+        return;
+      }
src/commands/transactions/index.ts (1)

21-22: LGTM: new flags exposed.
Consider clarifying in the help text that flags can be combined.

-    .option("--stdout", "Print only stdout from the receipt")
-    .option("--stderr", "Print only stderr from the receipt")
+    .option("--stdout", "Print stdout from the receipt (can be combined with --stderr)")
+    .option("--stderr", "Print stderr from the receipt (can be combined with --stdout)")
tests/commands/receipt.test.ts (1)

109-141: LGTM: CLI parses new flags correctly.
Optional: add one case combining flags with custom options to ensure no regression in parsing precedence.

tests/actions/receipt.test.ts (3)

173-200: Assert no extra default-print call when using --stdout.
Strengthen test by verifying only one success call.

     expect(receiptAction["succeedSpinner"]).toHaveBeenCalledWith(
       "Transaction stdout retrieved successfully",
       "program stdout",
     );
+    expect(receiptAction["succeedSpinner"]).toHaveBeenCalledTimes(1);

202-229: Assert no extra default-print call when using --stderr.
Same rationale as above.

     expect(receiptAction["succeedSpinner"]).toHaveBeenCalledWith(
       "Transaction stderr retrieved successfully",
       "program stderr",
     );
+    expect(receiptAction["succeedSpinner"]).toHaveBeenCalledTimes(1);

231-259: Assert no extra default-print call when using both flags; add missing-field case.

  • Ensure only one success call here as well.
  • Consider an additional test where stdout/stderr are missing to confirm graceful handling (after code change above).
     expect(receiptAction["succeedSpinner"]).toHaveBeenCalledWith(
       "Transaction stdout and stderr",
       { stdout: "program stdout", stderr: "program stderr" },
     );
+    expect(receiptAction["succeedSpinner"]).toHaveBeenCalledTimes(1);
📜 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 b2f0e99 and a3aeaab.

📒 Files selected for processing (4)
  • src/commands/transactions/index.ts (1 hunks)
  • src/commands/transactions/receipt.ts (3 hunks)
  • tests/actions/receipt.test.ts (1 hunks)
  • tests/commands/receipt.test.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
tests/actions/receipt.test.ts (1)
src/commands/transactions/receipt.ts (1)
  • ReceiptParams (4-12)
tests/commands/receipt.test.ts (1)
src/commands/transactions/receipt.ts (1)
  • ReceiptAction (16-90)
🔇 Additional comments (2)
src/commands/transactions/receipt.ts (2)

10-11: LGTM: typed flags added to params.
Matches CLI surface; no issues.


42-44: LGTM: flags threaded into action.
Parameters are passed through correctly.

@epsjunior
epsjunior merged commit 610831a into main Sep 3, 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