Skip to content

fix(client): disable viem transport retries (retryCount=0) to avoid d… - #110

Merged
epsjunior merged 1 commit into
mainfrom
dxp-626-fix-genlayer-js-retry-request-behavior
Sep 2, 2025
Merged

epsjunior merged 1 commit into
mainfrom
dxp-626-fix-genlayer-js-retry-request-behavior

Conversation

@epsjunior

@epsjunior epsjunior commented Sep 2, 2025 •

Copy link
Copy Markdown
Contributor

What

  • Disabled viem retries in custom transport by setting retryCount: 0 and retryDelay: 0 in createClient.

Why

  • Prevent multiple identical RPC calls and repeated error logs on failures.
  • Make errors deterministic and easier to debug for users.

Testing done

  • Called readContract on a failing method and observed a single request and single error.
  • Sanity-checked successful calls still return as expected.

Decisions made

  • Disabled retries globally at the transport level to ensure single-attempt behavior.

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/client/client.ts, particularly the custom(getCustomTransportConfig(config), { retryCount: 0, retryDelay: 0 }) change.

User facing release notes

  • Requests are no longer retried by default; failures return immediately, reducing duplicate RPC calls and repeated error logs.

Summary by CodeRabbit

  • Bug Fixes
    • Disabled automatic retries for network transport, so errors surface immediately rather than after delayed retry attempts.
    • Improves responsiveness in failure scenarios and reduces chances of duplicate requests or rate-limit triggers.
    • No impact on successful requests; overall behavior remains the same aside from faster failure feedback.

@coderabbitai

coderabbitai Bot commented Sep 2, 2025 •

Copy link
Copy Markdown

Walkthrough

The client transport initialization in src/client/client.ts now passes explicit retry options to Viem’s custom transport, setting retryCount: 0 and retryDelay: 0. This disables automatic retries on transport calls. No other logic or public/exported signatures were changed.

Changes

Cohort / File(s) Summary
Transport retry configuration
src/client/client.ts
Added second argument to custom(getCustomTransportConfig(config), { retryCount: 0, retryDelay: 0 }) to disable automatic transport retries; no other logic changed.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App as App
  participant Client as Client (Viem)
  participant Transport as Custom Transport
  participant RPC as RPC Provider

  App->>Client: createClient(config)
  Client->>Transport: custom(getCustomTransportConfig(config), {retryCount:0, retryDelay:0})
  note right of Transport: Retries disabled

  App->>Client: request()
  Client->>Transport: send()
  Transport->>RPC: HTTP/JSON-RPC call
  alt RPC error
    RPC-->>Transport: error response
    note right of Transport: No automatic retry
    Transport-->>Client: propagate error
    Client-->>App: error
  else RPC success
    RPC-->>Transport: result
    Transport-->>Client: result
    Client-->>App: result
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

I hop through code with whiskers bright,
Flipping retries off tonight—
One clean call, no second try,
Quick as a blink, the packets fly.
Burrow secure, the logs are tight,
Carrot-commits ship pure delight.

✨ 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-626-fix-genlayer-js-retry-request-behavior

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 (3)
src/client/client.ts (3)

86-90: Endpoint override not respected by transport (uses config.chain instead of effective chain).

fetch reads from config.chain.rpcUrls..., but you mutate chainConfig (and may set endpoint) separately. If config.chain is undefined or not the same object, the transport will ignore the override or throw “Chain is not set.”

Apply this minimal fix so the transport sees the effective chain:

   const chainConfig = config.chain || localnet;
   if (config.endpoint) {
     chainConfig.rpcUrls.default.http = [config.endpoint];
   }
 
-  const customTransport = custom(getCustomTransportConfig(config), {retryCount: 0, retryDelay: 0});
+  const effectiveConfig = { ...config, chain: chainConfig };
+  const customTransport = custom(getCustomTransportConfig(effectiveConfig), { retryCount: 0, retryDelay: 0 });

Also applies to: 56-58


35-51: Provider routing triggers when no account AND no provider → throws instead of falling back to RPC.

isAddress is true when account is undefined, so all eth_* methods try window.ethereum and throw if absent. Gate on provider existence and tighten the address check.

-const isAddress = typeof config.account !== "object";
+const isAddress = typeof config.account === "string";
+const provider =
+  config.provider ||
+  (typeof window !== "undefined" ? (window as any).ethereum : undefined);

-if (method.startsWith("eth_") && isAddress) {
+if (provider && method.startsWith("eth_") && isAddress) {
-  const provider = config.provider || window.ethereum;
-  if (!provider) {
-    throw new Error('No wallet provider available');
-  }
   return await provider.request({method, params});
 } else {

56-80: Add a request timeout and check response.ok (hang risk; unclear failures).

Without a timeout, calls may hang indefinitely; also response.ok isn’t checked. Mirror viem’s http default timeout (~10s) and surface HTTP errors. (viem.sh)

-        try {
-          const response = await fetch(config.chain.rpcUrls.default.http[0], {
+        try {
+          const ac = new AbortController();
+          const timer = setTimeout(() => ac.abort(new Error("RPC request timeout")), 10_000);
+          const response = await fetch(config.chain.rpcUrls.default.http[0], {
             method: "POST",
             headers: {
               "Content-Type": "application/json",
             },
             body: JSON.stringify({
               jsonrpc: "2.0",
               id: Date.now(),
               method,
               params,
             }),
-          });
+            signal: ac.signal,
+          });
+          clearTimeout(timer);
 
-          const data = await response.json();
+          if (!response.ok) {
+            throw new Error(`HTTP ${response.status} ${response.statusText}`);
+          }
+          const data = await response.json();
🧹 Nitpick comments (2)
src/client/client.ts (2)

63-67: Use a stable JSON-RPC id (minor).

Date.now() can collide under high concurrency. Use a monotonic counter.

-              id: Date.now(),
+              id: ++jsonRpcId, // define `let jsonRpcId = 0;` once above

124-127: Background init now has zero retries—confirm desired UX.

With retries disabled, a transient failure during initializeConsensusSmartContract() will fail once and log. Consider a one-time delayed retry or user-level surface if initialization is required.

📜 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 2b8d7e3.

📒 Files selected for processing (1)
  • src/client/client.ts (1 hunks)
🔇 Additional comments (1)
src/client/client.ts (1)

92-92: Disables viem retries correctly.

Passing { retryCount: 0, retryDelay: 0 } to custom(...) is the supported way to turn off transport-level retries. Looks good. (viem.sh)

@epsjunior
epsjunior merged commit dc2d623 into main Sep 2, 2025
dohernandez added a commit that referenced this pull request Oct 19, 2026
Keep what Phase 2 needs and follow the existing chain-preset pattern:

- testnetBradbury: Phase 2 addresses, refreshed ConsensusMain/ConsensusData
  ABIs and the new RPC/explorer URLs. ABIs keep the file's existing key order
  and narrow-ABI style; Appeals.canAppeal gains its decision-id argument.
- createClient: an endpoint override copies the chain instead of mutating the
  shared preset.
- check:chains: Bradbury reads a pinned copy of genlayer-consensus
  deployments/bradbury-phase-2.json and the explorer-verified ABIs through a
  CHAINS entry, instead of name checks in the loop.

Removed:
- genesisHash/addressManager chain fields and the identity check in the
  transport. It added ~15 RPC calls on first use and before every broadcast,
  and failed every CLI custom network based on testnet-bradbury. The SDK
  already resolves AddressManager on chain from ConsensusMain.
- the 429 retry loop in the transport. Unrelated to Phase 2 and it partly
  reverses #110; it belongs in its own PR if wanted.
- check:bradbury script, its node:test checks (not run anywhere) and the
  README section that described the removed behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dohernandez added a commit that referenced this pull request Oct 19, 2026
The Bradbury Phase 2 public RPC answers HTTP 429 once a burst passes about
five concurrent calls, so getEpochInfo and getValidatorInfo failed on most
runs. Retry reads up to three times, honouring Retry-After. Writes are never
retried, so a transaction cannot be broadcast twice (#110).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dohernandez added a commit that referenced this pull request Oct 19, 2026
* fix: target Bradbury Phase 2 and verify RPC network identity

* fix: retry throttled RPC reads without repeating broadcasts

* fix: resolve deployment contracts through AddressManager

* fix: reduce Bradbury Phase 2 change to the chain preset

Keep what Phase 2 needs and follow the existing chain-preset pattern:

- testnetBradbury: Phase 2 addresses, refreshed ConsensusMain/ConsensusData
  ABIs and the new RPC/explorer URLs. ABIs keep the file's existing key order
  and narrow-ABI style; Appeals.canAppeal gains its decision-id argument.
- createClient: an endpoint override copies the chain instead of mutating the
  shared preset.
- check:chains: Bradbury reads a pinned copy of genlayer-consensus
  deployments/bradbury-phase-2.json and the explorer-verified ABIs through a
  CHAINS entry, instead of name checks in the loop.

Removed:
- genesisHash/addressManager chain fields and the identity check in the
  transport. It added ~15 RPC calls on first use and before every broadcast,
  and failed every CLI custom network based on testnet-bradbury. The SDK
  already resolves AddressManager on chain from ConsensusMain.
- the 429 retry loop in the transport. Unrelated to Phase 2 and it partly
  reverses #110; it belongs in its own PR if wanted.
- check:bradbury script, its node:test checks (not run anywhere) and the
  README section that described the removed behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(client): retry rate-limited RPC reads

The Bradbury Phase 2 public RPC answers HTTP 429 once a burst passes about
five concurrent calls, so getEpochInfo and getValidatorInfo failed on most
runs. Retry reads up to three times, honouring Retry-After. Writes are never
retried, so a transaction cannot be broadcast twice (#110).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Darien Hernandez <dohernandez@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants