Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fetch gas prices from chain if empty #113

Merged
merged 2 commits into from
Mar 4, 2025
Merged

Fetch gas prices from chain if empty #113

merged 2 commits into from
Mar 4, 2025

Conversation

joon9823
Copy link
Collaborator

@joon9823 joon9823 commented Mar 4, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new method for asynchronously retrieving gas prices, enhancing dynamic fee estimation.
    • Updated fee estimation logic to ensure gas prices are fetched and applied when not preconfigured.
  • Chores

    • Updated the package version from "0.2.31" to "0.2.32".

@joon9823 joon9823 requested a review from ALPAC-4 March 4, 2025 07:29
Copy link

coderabbitai bot commented Mar 4, 2025

Walkthrough

This update bumps the package version from "0.2.31" to "0.2.32" in package.json. Additionally, a new asynchronous method gasPrices has been added to the RESTClient class, which attempts to fetch gas prices from two APIs—first from the opchild API and then from the move API if needed. The corresponding import statements were adjusted to include Coin, and a default constant was removed. Lastly, the TxAPI class now includes a conditional check in its fee estimation logic to ensure gas prices are obtained via the new method if they are undefined.

Changes

File(s) Change Summary
package.json Updated version from "0.2.31" to "0.2.32".
.../RESTClient.ts Added new async gasPrices method to fetch gas prices with fallback logic, updated imports to include Coin, and removed the default gas prices constant.
.../TxAPI.ts Introduced a conditional check in estimateFee to set gas prices via gasPrices() if not already defined.

Sequence Diagram(s)

sequenceDiagram
    participant TxAPI
    participant RESTClient
    participant OpchildAPI as opchild API
    participant MoveAPI as move API

    TxAPI->>RESTClient: Call gasPrices()
    RESTClient->>OpchildAPI: Request gas prices
    OpchildAPI-->>RESTClient: Return gas price or error
    alt Opchild API success
        RESTClient-->>TxAPI: Return gas price string
    else Opchild API failure
        RESTClient->>MoveAPI: Request gas prices
        MoveAPI-->>RESTClient: Return gas price details
        RESTClient-->>TxAPI: Return formatted coin string
    end
Loading

Poem

I'm a bunny coding in the digital glen,
Hopping over bugs and chasms again.
Gas prices fetched like carrots in a row,
With API magic that makes our code glow.
Version bumped and errors now at bay—
Happy hops in code all day!
🐇💻

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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.

Copy link

github-actions bot commented Mar 4, 2025

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

OpenSSF Scorecard

PackageVersionScoreDetails

Scanned Files

Copy link

@coderabbitai coderabbitai bot left a comment

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

302-304: Defensive improvement: Add fallback for undefined gas prices.

Your new code ensures gas prices are fetched from the chain if none are configured, which is great. However, there's a potential edge case where this.rest.gasPrices() might return undefined based on its implementation, and this case isn't explicitly handled here.

Consider adding additional fallback logic:

 if (!this.rest.config.gasPrices) {
-  this.rest.config.gasPrices = await this.rest.gasPrices()
+  const fetchedGasPrices = await this.rest.gasPrices()
+  this.rest.config.gasPrices = fetchedGasPrices || '0uinit' // Provide a default value if fetch fails
 }
src/client/rest/RESTClient.ts (2)

166-181: Add JSDoc documentation and error logging.

The implementation of the gasPrices method is well-structured with proper fallback logic. However, it could benefit from JSDoc documentation and error logging to assist with debugging.

Add documentation and error logging:

+/**
+ * Retrieves gas prices from the chain.
+ * First attempts to fetch from opchild parameters, then falls back to move parameters.
+ * @returns {Promise<Coins.Input | undefined>} The gas prices as a string or undefined if both fetches fail
+ */
 public async gasPrices(): Promise<Coins.Input | undefined> {
   try {
     const opchildParams = await this.opchild.parameters()
     return opchildParams.min_gas_prices.toString() || '0uinit'
-  } catch {
+  } catch (error) {
+    console.debug('Failed to fetch gas prices from opchild API, falling back to move API', error)
     try {
       const moveParams = await this.move.parameters()
       return new Coin(
         moveParams.base_denom,
         moveParams.base_min_gas_price
       ).toString()
-    } catch {
+    } catch (error) {
+      console.debug('Failed to fetch gas prices from move API', error)
       return undefined
     }
   }
 }

166-181: Consider implementing a caching mechanism.

The current implementation fetches gas prices every time they're needed. Given that gas prices don't change frequently, you might want to implement a simple caching mechanism with an expiration period to reduce API calls.

Here's a potential implementation:

+private gasPricesCache: {
+  value: Coins.Input | undefined;
+  timestamp: number;
+} | null = null;
+
+private readonly CACHE_EXPIRY_MS = 60000; // 1 minute cache
+
 public async gasPrices(): Promise<Coins.Input | undefined> {
+  // Return cached value if it exists and hasn't expired
+  if (
+    this.gasPricesCache &&
+    Date.now() - this.gasPricesCache.timestamp < this.CACHE_EXPIRY_MS
+  ) {
+    return this.gasPricesCache.value;
+  }
+
   try {
     const opchildParams = await this.opchild.parameters()
-    return opchildParams.min_gas_prices.toString() || '0uinit'
+    const result = opchildParams.min_gas_prices.toString() || '0uinit';
+    // Update cache
+    this.gasPricesCache = {
+      value: result,
+      timestamp: Date.now()
+    };
+    return result;
   } catch {
     try {
       const moveParams = await this.move.parameters()
-      return new Coin(
+      const result = new Coin(
         moveParams.base_denom,
         moveParams.base_min_gas_price
       ).toString()
+      // Update cache
+      this.gasPricesCache = {
+        value: result,
+        timestamp: Date.now()
+      };
+      return result;
     } catch {
+      // Update cache with undefined to prevent repeated failed calls
+      this.gasPricesCache = {
+        value: undefined,
+        timestamp: Date.now()
+      };
       return undefined
     }
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5153434 and a6d90ea.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • package.json (1 hunks)
  • src/client/rest/RESTClient.ts (2 hunks)
  • src/client/rest/api/TxAPI.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • package.json
🔇 Additional comments (1)
src/client/rest/RESTClient.ts (1)

35-35: LGTM: Import addition for Coin.

The addition of the Coin import is appropriate for the new functionality.

Copy link
Contributor

@ALPAC-4 ALPAC-4 left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/client/rest/RESTClient.ts (1)

166-181: ⚠️ Potential issue

Gas Price Validation Required

The current implementation doesn't validate that the retrieved gas prices are valid before returning them. This could lead to invalid fee estimations downstream.

Consider implementing these improvements:

  1. Validate that the values from both APIs adhere to expected coin format
  2. Ensure numeric components are valid and denominations are allowed values
  3. Add proper validation before returning values
public async gasPrices(): Promise<Coins.Input | undefined> {
  try {
    const opchildParams = await this.opchild.parameters()
-   return opchildParams.min_gas_prices.toArray()[0]?.toString() ?? '0uinit'
+   const gasPrice = opchildParams.min_gas_prices.toArray()[0]
+   // Validate gas price before returning
+   if (gasPrice && this.isValidCoin(gasPrice)) {
+     return gasPrice.toString()
+   }
+   return '0uinit'
  } catch {
    try {
      const moveParams = await this.move.parameters()
-     return new Coin(
+     const gasPrice = new Coin(
        moveParams.base_denom,
        moveParams.base_min_gas_price
-     ).toString()
+     )
+     // Validate gas price before returning
+     if (this.isValidCoin(gasPrice)) {
+       return gasPrice.toString()
+     }
+     return '0uinit'
    } catch {
      return undefined
    }
  }
}

// Add a validation helper method
private isValidCoin(coin: Coin): boolean {
  // Implement validation logic:
  // 1. Check if amount is a valid number and > 0
  // 2. Verify denomination is in the allowed list
  // 3. Ensure the format meets expected standards
  return coin && 
         typeof coin.amount === 'string' && 
         /^\d+$/.test(coin.amount) && 
         typeof coin.denom === 'string' && 
         coin.denom.length > 0;
}
🧹 Nitpick comments (2)
src/client/rest/RESTClient.ts (2)

166-181: Consider adding logging for error cases

The implementation silently catches errors without logging them, which could make troubleshooting issues in production difficult.

public async gasPrices(): Promise<Coins.Input | undefined> {
  try {
    const opchildParams = await this.opchild.parameters()
    return opchildParams.min_gas_prices.toArray()[0]?.toString() ?? '0uinit'
-  } catch {
+  } catch (error) {
+    console.debug('Failed to fetch gas prices from opchild API:', error)
    try {
      const moveParams = await this.move.parameters()
      return new Coin(
        moveParams.base_denom,
        moveParams.base_min_gas_price
      ).toString()
-    } catch {
+    } catch (error) {
+      console.debug('Failed to fetch gas prices from move API:', error)
      return undefined
    }
  }
}

166-181: Consider implementing a retry mechanism with backoff

Network requests to fetch gas prices might fail temporarily. Adding a retry mechanism would improve reliability.

You could implement a simple retry mechanism with exponential backoff for both API calls:

+ private async retryWithBackoff<T>(
+   fn: () => Promise<T>,
+   maxRetries = 3,
+   initialDelay = 300
+ ): Promise<T> {
+   let retries = 0;
+   let delay = initialDelay;
+   
+   while (retries < maxRetries) {
+     try {
+       return await fn();
+     } catch (error) {
+       retries++;
+       if (retries >= maxRetries) throw error;
+       
+       await new Promise(resolve => setTimeout(resolve, delay));
+       delay *= 2; // Exponential backoff
+     }
+   }
+   
+   throw new Error('Max retries reached');
+ }

public async gasPrices(): Promise<Coins.Input | undefined> {
  try {
-   const opchildParams = await this.opchild.parameters()
+   const opchildParams = await this.retryWithBackoff(() => this.opchild.parameters())
    return opchildParams.min_gas_prices.toArray()[0]?.toString() ?? '0uinit'
  } catch (error) {
    try {
-     const moveParams = await this.move.parameters()
+     const moveParams = await this.retryWithBackoff(() => this.move.parameters())
      return new Coin(
        moveParams.base_denom,
        moveParams.base_min_gas_price
      ).toString()
    } catch {
      return undefined
    }
  }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a6d90ea and bc6a6f3.

📒 Files selected for processing (1)
  • src/client/rest/RESTClient.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
src/client/rest/RESTClient.ts (3)

35-35: Added Coin import to support new gas price fetching functionality.

The updated import includes Coin class which is now used in the new gasPrices method to construct a coin object with denomination and amount.


173-176:

✅ Verification successful

Verify that moveParams.base_denom and moveParams.base_min_gas_price are valid

The code assumes that these parameters will always be available and in the expected format.


🏁 Script executed:

#!/bin/bash
# Check how move.parameters() is structured and verify the fields we're accessing

echo "Checking the move.parameters() structure:"
rg -A 10 -B 10 "parameters\(\)" --glob="**/MoveAPI.ts"

echo "Searching for usages of base_denom and base_min_gas_price:"
rg "base_denom|base_min_gas_price" --glob="*.ts" | grep -v "node_modules"

Length of output: 4970


Validation of moveParams Fields is Confirmed

The investigation confirms that both base_denom and base_min_gas_price are defined as string fields in src/core/move/MoveParams.ts and are consistently referenced elsewhere (e.g., in the REST client and other modules). Their use in constructing a new Coin appears valid under the current data contracts. No additional changes are required unless you plan to add runtime validation for extra safety.


169-169: 🛠️ Refactor suggestion

Add fallback mechanism for empty min_gas_prices array

The current implementation might return undefined if the min_gas_prices array is empty, which could cause issues downstream.

- return opchildParams.min_gas_prices.toArray()[0]?.toString() ?? '0uinit'
+ const gasPricesArray = opchildParams.min_gas_prices.toArray();
+ if (gasPricesArray.length > 0) {
+   return gasPricesArray[0].toString();
+ }
+ return '0uinit'; // Explicit fallback

Likely an incorrect or invalid review comment.

@joon9823 joon9823 merged commit 7d4334b into main Mar 4, 2025
4 checks passed
@joon9823 joon9823 deleted the feat/gas-prices branch March 4, 2025 07:53
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