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

feat(ethereum-storage): custom gas limit #1495

Merged
merged 3 commits into from
Dec 4, 2024
Merged

Conversation

alexandre-abrioux
Copy link
Member

@alexandre-abrioux alexandre-abrioux commented Nov 28, 2024

Description of the changes

In this PR I propose adding a gasLimit option to our EthereumTransactionSubmitter class. This would allow builders to configure a gas limit for submitted transactions, in order to improve:

  1. Security: If a bug is introduced in the RequestOpenHashSubmitter smart contract (low probability but could happen during an update for instance), funds on the submission wallet could be drained. This option would prevent that.
  2. Performance and cost: Estimating the gas limit is a costly operation as it requires a call to the underlying RPC provider. It currently represents 1/6 of the costs spent by the EthereumTransactionSubmitter when using Alchemy. Setting this option would cancel that cost and slightly improve performance (one less network call).

Summary by CodeRabbit

  • New Features

    • Introduced an optional gasLimit property for transaction submissions, allowing users to specify a gas limit.
  • Bug Fixes

    • Enhanced transaction submission tests to ensure proper handling of default and custom gas limits.

Copy link
Contributor

coderabbitai bot commented Nov 28, 2024

Walkthrough

The changes in this pull request introduce a new optional property, gasLimit, to the SubmitterProps type and the EthereumTransactionSubmitter class in the ethereum-tx-submitter.ts file. This property allows users to specify a gas limit for transaction submissions. The prepareSubmit method is updated to include the gasLimit in the transaction request object. Additionally, two new test cases are added to verify the behavior of the gas limit handling during transaction submissions.

Changes

File Path Change Summary
packages/ethereum-storage/src/ethereum-tx-submitter.ts - Added optional property gasLimit?: BigNumber; to SubmitterProps.
- Added private member variable `private readonly gasLimit: BigNumber
packages/ethereum-storage/test/ethereum-tx-submitter.test.ts - Added test case: "should not use gas limit by default".
- Added test case: "can use a custom gas limit".

Possibly related PRs

Suggested reviewers

  • PaulvanMotman
  • kevindavee
  • yomarion
  • aimensahnoun
  • sstefdev
  • leoslr
  • MantisClone

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.

Copy link
Contributor

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

🧹 Outside diff range and nitpick comments (4)
packages/ethereum-storage/test/ethereum-tx-submitter.test.ts (2)

61-72: LGTM! Consider documenting the gas limit value.

The test correctly verifies custom gas limit functionality. However, consider adding a comment explaining why 1000000 was chosen as the test value.

 it('can use a custom gas limit', async () => {
+  // Using 1M gas as a reasonable upper limit for testing
+  const TEST_GAS_LIMIT = 1000000;
   const txSubmitterWithGasLimit = new EthereumTransactionSubmitter({
     network: 'private',
     signer,
-    gasLimit: BigNumber.from(1000000),
+    gasLimit: BigNumber.from(TEST_GAS_LIMIT),
   });
   const sendTransactionSpy = jest.spyOn(signer, 'sendTransaction');
   await txSubmitterWithGasLimit.submit('hash', 1);
   expect(sendTransactionSpy).toHaveBeenCalledWith(
-    expect.objectContaining({ gasLimit: BigNumber.from(1000000) }),
+    expect.objectContaining({ gasLimit: BigNumber.from(TEST_GAS_LIMIT) }),
   );
 });

72-72: Consider adding tests for edge cases.

To ensure robust gas limit handling, consider adding tests for:

  1. Invalid gas limits (negative values, zero)
  2. Extremely large gas limits
  3. Gas limit updates after initialization (if supported)

Example test structure:

it('should reject invalid gas limits', async () => {
  expect(() => 
    new EthereumTransactionSubmitter({
      network: 'private',
      signer,
      gasLimit: BigNumber.from(0)
    })
  ).toThrow();
});

it('should handle maximum allowed gas limit', async () => {
  const MAX_GAS = BigNumber.from('15000000'); // Ethereum block gas limit
  const txSubmitter = new EthereumTransactionSubmitter({
    network: 'private',
    signer,
    gasLimit: MAX_GAS
  });
  // ... test implementation
});
packages/ethereum-storage/src/ethereum-tx-submitter.ts (2)

53-53: Consider adding validation for gasLimit.

While the implementation is correct, consider adding validation to ensure the gasLimit is a reasonable value (not too low or too high) to prevent potential issues with transaction failures.

constructor({
  network,
  signer,
  logger,
  gasPriceMin,
  gasPriceMax,
  gasPriceMultiplier,
  gasLimit,
  debugProvider,
}: SubmitterProps) {
+ if (gasLimit && gasLimit.lt(BigNumber.from(21000))) {
+   throw new Error('Gas limit must be at least 21000');
+ }
  // ... existing code ...
  this.gasLimit = gasLimit;
  // ... existing code ...
}

Also applies to: 70-70


Line range hint 25-113: Consider adding monitoring and documentation for gas usage patterns.

The addition of custom gas limits is a good security and performance enhancement. Consider:

  1. Adding metrics/monitoring for gas usage patterns to help users optimize their gas limits
  2. Documenting recommended gas limits for common operations in the README
  3. Adding warning logs when gas usage approaches the custom limit

This will help users make informed decisions about setting appropriate gas limits.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d54df7f and 329c3b4.

📒 Files selected for processing (2)
  • packages/ethereum-storage/src/ethereum-tx-submitter.ts (6 hunks)
  • packages/ethereum-storage/test/ethereum-tx-submitter.test.ts (1 hunks)
🔇 Additional comments (4)
packages/ethereum-storage/test/ethereum-tx-submitter.test.ts (1)

53-59: LGTM! Well-structured test for default behavior.

The test effectively verifies that gas limit remains undefined when not explicitly set, following good testing practices with clear setup and assertions.

packages/ethereum-storage/src/ethereum-tx-submitter.ts (3)

25-29: LGTM! Well-documented type definition.

The gasLimit property is properly typed as an optional BigNumber with clear documentation explaining both scenarios when it's set or unset.


44-44: LGTM! Properly encapsulated property.

The gasLimit property is correctly defined as private and readonly, maintaining proper encapsulation.


107-113: Verify gas estimation fallback behavior.

When gasLimit is undefined, the transaction will use the network's default gas estimation. Ensure this is sufficient for all possible transaction scenarios, especially for complex operations.

✅ Verification successful

Based on the search results, I can now generate the final response:

Gas limit handling is properly implemented with fallback behavior

The implementation correctly handles both cases:

  • When gasLimit is undefined, it's omitted from the transaction request, allowing the network's default gas estimation
  • When specified, the custom gasLimit is used, as verified in the test cases

The code is safe because:

  • The transaction will be automatically estimated by the provider when no gas limit is specified
  • Tests confirm both scenarios work: with and without gas limit (ethereum-storage/test/ethereum-tx-submitter.test.ts)
  • The contract interaction is a simple hash submission, which has predictable gas costs
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for submitHash function implementations to analyze gas requirements
ast-grep --pattern 'function submitHash($$$) {
  $$$
}'

# Search for existing gas usage patterns
rg -A 5 'gasLimit' 

Length of output: 12857

@alexandre-abrioux alexandre-abrioux enabled auto-merge (squash) December 4, 2024 10:07
@alexandre-abrioux alexandre-abrioux merged commit cf4c125 into master Dec 4, 2024
27 checks passed
@alexandre-abrioux alexandre-abrioux deleted the feat/gas-limit branch December 4, 2024 10:15
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.

4 participants