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

adding gas limit #4

Merged
merged 6 commits into from
Oct 25, 2024
Merged

adding gas limit #4

merged 6 commits into from
Oct 25, 2024

Conversation

jlafiandra6
Copy link
Contributor

@jlafiandra6 jlafiandra6 commented Oct 25, 2024

Summary by CodeRabbit

  • New Features
    • Introduced transaction fee validation to enhance error handling for transaction submissions.
    • Added a limit for transaction fees, improving user experience by preventing high-cost transactions.
  • Bug Fixes
    • Updated error responses to inform users when transaction fees exceed the specified limit.
  • Chores
    • Added a new dependency to improve functionality within the project.

Copy link

coderabbitai bot commented Oct 25, 2024

Warning

Rate limit exceeded

@jlafiandra6 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 15 minutes and 24 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between 59c5b1c and a3a4cfe.

Walkthrough

The changes in this pull request primarily enhance transaction fee validation in the src/server.ts file. Two new constants, TX_GASPRICE_LIMIT and TX_BLOBPRICE_LIMIT, are introduced to retrieve their values from environment variables. An asynchronous function, feesTooHigh, is added to check if the gas costs for a transaction exceed these limits. The existing POST route handler is updated to invoke this function, returning a 400 error response if fees are too high. Overall, the control flow is modified to improve error handling without altering existing method signatures.

Changes

File Change Summary
src/server.ts Added constants TX_GASPRICE_LIMIT and TX_BLOBPRICE_LIMIT from environment variables; added function feesTooHigh for fee validation; updated POST route handler to include fee validation logic.
package.json Added new dependency "update": "^0.7.4" in dependencies section.

Poem

In the server's heart, a limit now lies,
To guard against fees that soar to the skies.
With a check in place, oh what a delight,
Transactions can dance, all fees kept in sight!
So hop along, dear friends, let’s send with cheer,
For the limits are set, and the path is now clear! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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 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.

src/server.ts Outdated Show resolved Hide resolved
src/server.ts Outdated Show resolved Hide resolved
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: 2

🧹 Outside diff range and nitpick comments (1)
src/server.ts (1)

Line range hint 20-86: Consider additional architectural improvements

While the basic gas limit functionality is implemented, consider these improvements:

  1. Add unit tests for the gas limit validation logic
  2. Implement monitoring/metrics to track when transactions hit limits
  3. Add startup configuration validation to ensure all required environment variables are properly set
  4. Consider making the limit configurable per transaction type (regular vs blob transactions)

Would you like help implementing any of these improvements? I can help with:

  1. Writing unit tests for the gas limit validation
  2. Adding configuration validation at startup
  3. Implementing basic metrics collection
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e286d2a and a659c01.

📒 Files selected for processing (1)
  • src/server.ts (3 hunks)
🧰 Additional context used
🪛 Biome
src/server.ts

[error] 40-40: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

🔇 Additional comments (1)
src/server.ts (1)

60-86: ⚠️ Potential issue

Improve gas calculation safety and efficiency

The current implementation has several concerns:

  1. No protection against BigInt overflow in calculations
  2. Redundant variable initializations
  3. Gas cost calculation might be incorrect (adding instead of using max)
  4. Missing function documentation

Consider this safer implementation:

+/**
+ * Validates if the transaction's total gas costs (including blob gas) are within limits
+ * @param transactionArgs The transaction parameters to validate
+ * @returns true if gas costs are within limits, false otherwise
+ */
 async function feesTooHigh(transactionArgs: TransactionArgs)  {
-  let maxFeePerGas = BigInt(0);
-  let maxPriorityFeePerGas = BigInt(0);
-  let maxFeePerBlobGas = BigInt(0);
-  if (transactionArgs.maxFeePerGas ){
-     maxFeePerGas = BigInt(transactionArgs.maxFeePerGas);
-  }  
-  if (transactionArgs.maxPriorityFeePerGas) {
-     maxPriorityFeePerGas = BigInt(transactionArgs.maxPriorityFeePerGas);
-  }
-  if (transactionArgs.maxFeePerBlobGas) {
-     maxFeePerBlobGas = BigInt(transactionArgs.maxFeePerBlobGas);
-  }
+  try {
+    const maxFeePerGas = BigInt(transactionArgs.maxFeePerGas || 0);
+    const maxPriorityFeePerGas = BigInt(transactionArgs.maxPriorityFeePerGas || 0);
+    const gas = BigInt(transactionArgs.gas);
 
-  var gasCost = BigInt(transactionArgs.gas) * (maxFeePerGas + maxPriorityFeePerGas);
-  if (gasCost > TX_LIMIT) {
-    return false;  
-  }
+    // Use max of the two fees instead of adding them
+    const effectiveGasPrice = maxFeePerGas > maxPriorityFeePerGas ? maxFeePerGas : maxPriorityFeePerGas;
+    const gasCost = gas * effectiveGasPrice;
+    
+    if (gasCost > TX_LIMIT) {
+      return false;
+    }
 
-  if (transactionArgs.blobVersionedHashes && transactionArgs.blobVersionedHashes.length > 0) {
-    var blobGasCost = BigInt(transactionArgs.gas) * maxFeePerBlobGas;
-    if (blobGasCost > TX_LIMIT) {
-      return false;
+    // Check blob gas costs if applicable
+    if (transactionArgs.blobVersionedHashes?.length > 0) {
+      const maxFeePerBlobGas = BigInt(transactionArgs.maxFeePerBlobGas || 0);
+      const blobGasCost = gas * maxFeePerBlobGas;
+      
+      if (blobGasCost > TX_LIMIT) {
+        return false;
+      }
     }
+    
+    return true;
+  } catch (error) {
+    console.error('Error calculating gas costs:', error);
+    return false;
   }
-  return true;
 }

Let's verify the gas calculation approach:

src/server.ts Outdated Show resolved Hide resolved
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: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a659c01 and 7736d52.

📒 Files selected for processing (1)
  • src/server.ts (3 hunks)
🧰 Additional context used
🪛 Biome
src/server.ts

[error] 44-44: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

src/server.ts Outdated Show resolved Hide resolved
src/server.ts Outdated Show resolved Hide resolved
src/server.ts Outdated Show resolved Hide resolved
src/server.ts Outdated Show resolved Hide resolved
Copy link
Member

@dshiell dshiell left a comment

Choose a reason for hiding this comment

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

lgtm, we can use hardcoded estimates for now and update once there is some gas oracle to pull gas prices from.

src/server.ts Show resolved Hide resolved
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7736d52 and a6cd114.

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

40-48: ⚠️ Potential issue

Fix switch case scoping and improve error handling

Previous review comments about switch case scoping and error response format are still valid. Additionally:

  1. Error message includes raw BigInt values which may cause JSON serialization issues
  2. Missing error logging as suggested in past reviews

Apply these fixes:

-      
-      if (TX_BLOBPRICE_LIMIT > 0 || TX_GASPRICE_LIMIT > 0) {
-        let areFeesTooHigh = await feesTooHigh(result.data);
-        if (areFeesTooHigh) {          
-          reply.code(400).send({error: `Fees too high TX_GAS_LIMIT|TX_BLOBPRICE_LIMIT [${TX_GASPRICE_LIMIT} |${TX_BLOBPRICE_LIMIT}] reached`});
-          return;
-        }
-      }
+      {
+        const areFeesTooHigh = await feesTooHigh(result.data);
+        if (areFeesTooHigh) {
+          console.error('Transaction rejected due to excessive fees');
+          reply.code(400).send({
+            error: 'Invalid request',
+            message: 'Transaction fees exceed the configured limits'
+          });
+          return;
+        }
+      }

64-94: 🛠️ Refactor suggestion

Improve gas cost validation implementation

Previous review comments about improving the implementation are still valid. The current implementation needs:

  1. Input validation
  2. More efficient variable initialization
  3. Gas limit validation
  4. Consistent use of const

Consider this improved implementation:

 async function feesTooHigh(transactionArgs: TransactionArgs)  {
-  let maxFeePerGas = BigInt(0);
-  let maxPriorityFeePerGas = BigInt(0);
-  let maxFeePerBlobGas = BigInt(0);
-
-  
-
-  if (transactionArgs.maxFeePerGas ){
-     maxFeePerGas = BigInt(transactionArgs.maxFeePerGas);
-  }  
-  if (transactionArgs.maxPriorityFeePerGas) {
-     maxPriorityFeePerGas = BigInt(transactionArgs.maxPriorityFeePerGas);
-  }
-  if (transactionArgs.maxFeePerBlobGas) {
-     maxFeePerBlobGas = BigInt(transactionArgs.maxFeePerBlobGas);
-  }
+  // Skip validation if both limits are disabled
+  if (TX_GASPRICE_LIMIT <= 0 && TX_BLOBPRICE_LIMIT <= 0) {
+    return false;
+  }
+
+  if (!transactionArgs.gas) {
+    throw new Error('Gas limit is required');
+  }
+
+  const maxFeePerGas = BigInt(transactionArgs.maxFeePerGas ?? 0);
+  const maxPriorityFeePerGas = BigInt(transactionArgs.maxPriorityFeePerGas ?? 0);
+  const maxFeePerBlobGas = BigInt(transactionArgs.maxFeePerBlobGas ?? 0);
+  const gasLimit = BigInt(transactionArgs.gas);

-  var gasPrice = (maxFeePerGas + maxPriorityFeePerGas);
-  if (gasPrice > TX_GASPRICE_LIMIT) {
-    console.error('Tx fees too high: %d > %d', gasPrice, TX_GASPRICE_LIMIT);
-    return true;  
-  }
+  // Only check gas price if limit is enabled
+  if (TX_GASPRICE_LIMIT > 0) {
+    const gasPrice = maxFeePerGas + maxPriorityFeePerGas;
+    if (gasPrice > TX_GASPRICE_LIMIT) {
+      console.error('Transaction gas price too high: %d > %d', gasPrice, TX_GASPRICE_LIMIT);
+      return true;
+    }
+  }

-  if (transactionArgs.blobVersionedHashes && transactionArgs.blobVersionedHashes.length > 0) {
-    if (maxFeePerBlobGas > TX_BLOBPRICE_LIMIT) {
-      console.error('Blob fees too high: %d > %d', maxFeePerBlobGas, TX_BLOBPRICE_LIMIT );
-      return true;
+  // Only check blob gas price if limit is enabled and blobs are present
+  if (TX_BLOBPRICE_LIMIT > 0 && transactionArgs.blobVersionedHashes?.length > 0) {
+    if (maxFeePerBlobGas > TX_BLOBPRICE_LIMIT) {
+      console.error('Blob gas price too high: %d > %d', maxFeePerBlobGas, TX_BLOBPRICE_LIMIT);
+      return true;
     }
   }
   return false;
 }

src/server.ts Show resolved Hide resolved
@jlafiandra6 jlafiandra6 merged commit a733f1a into main Oct 25, 2024
1 check 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