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

🐛 Fix: stateOverrides persisting after call is finished #1481

Conversation

roninjin10
Copy link
Collaborator

@roninjin10 roninjin10 commented Oct 13, 2024

Description

Concise description of proposed changes

Testing

Explain the quality checks that have been done on the code changes

Additional Information

Your ENS/address:

Summary by CodeRabbit

  • Bug Fixes

    • Resolved an issue with state overrides not resetting after call completion, restoring expected system behavior.
    • Enhanced error handling for block retrieval processes.
  • New Features

    • Introduced a new asynchronous function to manage state overrides for clients, improving validation before script execution.
    • Added structured error handling for state override processes.

Copy link

vercel bot commented Oct 13, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Updated (UTC)
tevm-monorepo-tevm ⬜️ Ignored (Inspect) Oct 17, 2024 1:53am

Copy link

changeset-bot bot commented Oct 13, 2024

🦋 Changeset detected

Latest commit: d591949

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 10 packages
Name Type
@tevm/actions Patch
@tevm/cli Patch
@tevm/ethers Patch
@tevm/viem Patch
@tevm/decorators Patch
@tevm/memory-client Patch
@tevm/server Patch
tevm Patch
@tevm/http-client Patch
tevm-run Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@roninjin10 roninjin10 marked this pull request as ready for review October 13, 2024 23:42
Copy link
Contributor

coderabbitai bot commented Oct 13, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

This changeset introduces a patch to the @tevm/actions package, specifically targeting a bug related to state overrides. It adds a new asynchronous function, handleStateOverrides, to manage state overrides for a client and parameters. The callHandler function is updated to incorporate this new function, adding validation for state overrides. Additionally, the callHandlerOpts function is simplified by removing state override logic and improving error handling for block retrieval.

Changes

File Path Change Summary
packages/actions/src/Call/handleStateOverrides.js Added: async function handleStateOverrides(client, stateOverrideSet) to manage state overrides.
packages/actions/src/Call/callHandler.js Updated: callHandler function to integrate handleStateOverrides and add validation for state overrides.
packages/actions/src/Call/callHandlerOpts.js Simplified: Removed state override handling logic and enhanced error handling for block retrieval.
packages/actions/src/Call/callHandlerOpts.spec.ts Removed: Test cases for handling state overrides in callHandlerOpts.
packages/actions/src/Call/callProcedure.spec.ts Updated: Minor modification with a console.log statement for debugging in the test suite.

Possibly related PRs

🐇 In the meadow, where bunnies play,
A patch was made to save the day.
State overrides now come and go,
With fixes swift, our code will flow.
Hopping high, we celebrate,
For smoother scripts, we can't wait! 🐰✨


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
Collaborator Author

roninjin10 commented Oct 13, 2024

This stack of pull requests is managed by Graphite. Learn more about stacking.

Join @roninjin10 and the rest of your teammates on Graphite Graphite

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

🧹 Outside diff range and nitpick comments (1)
.changeset/smart-mice-dream.md (1)

1-5: LGTM! Consider adding more details to the description.

The changeset file is correctly formatted and provides the essential information about the patch. The description accurately reflects the bug fix mentioned in the PR objectives.

To improve clarity, consider expanding the description slightly to include the impact of the fix. For example:

- Fixed bug with state overrides persisting after the call was finished
+ Fixed bug with state overrides persisting after the call was finished, ensuring correct state management and preventing unintended side effects in subsequent operations

This additional context can help other developers and users better understand the significance of the change.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7248dbf and ef96bfb.

📒 Files selected for processing (4)
  • .changeset/smart-mice-dream.md (1 hunks)
  • packages/actions/src/Call/callHandler.js (2 hunks)
  • packages/actions/src/Call/callHandlerOpts.js (0 hunks)
  • packages/actions/src/Call/handleStateOverrides.js (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/actions/src/Call/callHandlerOpts.js
🧰 Additional context used
🔇 Additional comments (2)
packages/actions/src/Call/callHandler.js (2)

14-14: Import handleStateOverrides module

The import statement correctly brings in the handleStateOverrides function from ./handleStateOverrides.js.


128-138: Ensure stateOverrides are properly applied to the VM instance

The addition of handleStateOverrides integrates state override handling into the call flow. However, please verify that handleStateOverrides correctly applies the state overrides to the VM instance before executing the call. This ensures that any state modifications are effective during EVM execution.

Comment on lines 15 to 39
export async function handleStateOverrides(client, params) {
if (params.stateOverrideSet) {
for (const [address, state] of Object.entries(params.stateOverrideSet)) {
const res = await setAccountHandler(client)({
address: /** @type import('@tevm/utils').Address*/ (address),
...(state.nonce !== undefined ? { nonce: state.nonce } : {}),
...(state.balance !== undefined ? { balance: state.balance } : {}),
...(state.code !== undefined ? { deployedBytecode: state.code } : {}),
...(state.state !== undefined ? { state: state.state } : {}),
...(state.stateDiff !== undefined ? { stateDiff: state.stateDiff } : {}),
throwOnFail: false,
})
if (res.errors?.length) {
return {
errors: [
new InvalidParamsError('Invalid state override', {
cause: /** @type {Error} */ (res.errors.length === 1 ? res.errors[0] : new AggregateError(res.errors)),
}),
],
}
}
}
}
return {};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add unit tests for handleStateOverrides

Unit tests are essential to ensure that the new handleStateOverrides function behaves correctly under various scenarios, including handling valid and invalid state overrides and correctly propagating errors.

Would you like assistance in creating unit tests for this function or opening a GitHub issue to track this task?

return {
errors: [
new InvalidParamsError('Invalid state override', {
cause: /** @type {Error} */ (res.errors.length === 1 ? res.errors[0] : new AggregateError(res.errors)),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure compatibility of AggregateError with target environments

The use of AggregateError is supported in Node.js 15.0.0 and above. If the project needs to support older Node.js versions, consider an alternative method for aggregating errors to maintain compatibility.

Comment on lines +30 to +34
new InvalidParamsError('Invalid state override', {
cause: /** @type {Error} */ (res.errors.length === 1 ? res.errors[0] : new AggregateError(res.errors)),
}),
],
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Include the address in error messages for better debugging

Including the address that caused the error can aid in quickly identifying problematic state overrides during debugging.

Apply this diff to modify the error message:

-						new InvalidParamsError('Invalid state override', {
+						new InvalidParamsError(`Invalid state override for address ${address}`, {

Committable suggestion was skipped due to low confidence.

@roninjin10 roninjin10 force-pushed the 10-13-_bug_fix_stateoverrides_persisting_after_call_is_finished branch from 2fa1bf1 to a3518b7 Compare October 14, 2024 03:14
@roninjin10 roninjin10 force-pushed the 10-13-_bug_fix_stateoverrides_persisting_after_call_is_finished branch from a3518b7 to 6d4f6a0 Compare October 14, 2024 03:19
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 (3)
packages/actions/src/Call/handleStateOverrides.js (1)

15-19: Consider removing the console.log statement

The console.log statement on line 18 appears to be used for debugging purposes. Consider removing it before merging this PR to production, or replacing it with a more appropriate logging mechanism if the information is necessary for production environments.

packages/actions/src/Call/callProcedure.spec.ts (1)

77-77: Consider removing the console.log statement or use a more appropriate debugging method.

While adding a console.log statement can be helpful for debugging, it's generally not recommended to leave them in the final code, even in test files. This can clutter the test output and potentially hide important information.

Instead, consider the following options:

  1. If this log is temporary for debugging, remove it before merging the PR.
  2. If the information is crucial, use a proper assertion to check the error condition.
  3. If you need to keep the logging for future debugging, consider using a debug library that can be easily enabled/disabled.

Here's a suggestion to replace the console.log with an assertion:

- console.log(response.error)
+ expect(response.error).toBeUndefined()

This way, you're explicitly checking that there's no error, which seems to be the intent of the following line.

packages/actions/src/Call/callHandlerOpts.spec.ts (1)

Line range hint 214-228: LGTM: New test case for block overrides without blobBaseFee.

The addition of this test case improves coverage for block override scenarios, specifically when blobBaseFee is not provided. This is a valuable test to ensure correct behavior in such cases.

Consider adding an assertion to verify that the blobBaseFee is not present in the blockOverrideSet object, to make the test's intention clearer:

expect(blockOverrideSet).not.toHaveProperty('blobBaseFee');
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6d4f6a0 and f03d6c8.

📒 Files selected for processing (4)
  • packages/actions/src/Call/callHandler.js (2 hunks)
  • packages/actions/src/Call/callHandlerOpts.spec.ts (1 hunks)
  • packages/actions/src/Call/callProcedure.spec.ts (1 hunks)
  • packages/actions/src/Call/handleStateOverrides.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/actions/src/Call/callHandler.js
🧰 Additional context used
🔇 Additional comments (12)
packages/actions/src/Call/handleStateOverrides.js (8)

1-2: LGTM: Import statements are appropriate

The import statements are correctly importing the necessary dependencies for the function.


4-7: LGTM: HandleStateOverridesError typedef is well-defined

The typedef for HandleStateOverridesError is correctly defined as an alias for InvalidParamsError and appropriately marked as @internal.


9-14: LGTM: JSDoc for handleStateOverrides is comprehensive

The JSDoc for the handleStateOverrides function is well-written, accurately describing the function's parameters and return type.


19-27: LGTM: Effective use of optional chaining and error handling

This section of the function effectively uses optional chaining to include properties conditionally. Setting throwOnFail to false allows for custom error handling, which is implemented in the subsequent code block. The type casting of address ensures type safety.


28-40: LGTM: Robust error handling implementation

The error handling logic in this section is well-implemented. It correctly differentiates between single and multiple errors, using AggregateError when appropriate. The function returns the expected objects based on the presence or absence of errors.


32-32: Ensure AggregateError compatibility

As mentioned in a previous review, the use of AggregateError is supported in Node.js 15.0.0 and above. If this project needs to support older Node.js versions, consider implementing a fallback mechanism for environments where AggregateError is not available.

To check the current Node.js version requirements for this project, you can run:

#!/bin/bash
# Check for Node.js version specification in package.json
jq '.engines.node' package.json

# Check for .nvmrc file
cat .nvmrc 2>/dev/null || echo ".nvmrc not found"

# Check for any other files that might specify Node.js version
fd -t f '(\.node-version|\.tool-versions|\.node-version-file)$'

15-40: Add unit tests for handleStateOverrides function

As mentioned in a previous review, it's crucial to add unit tests for the handleStateOverrides function. These tests should cover various scenarios, including:

  1. Handling valid state overrides
  2. Handling invalid state overrides
  3. Correct error propagation
  4. Edge cases (e.g., empty stateOverrideSet, all possible combinations of state properties)

Adding these tests will ensure the function behaves correctly under different conditions and make future maintenance easier.

Would you like assistance in creating unit tests for this function or opening a GitHub issue to track this task?


1-40: Overall assessment: Well-implemented with minor improvements needed

The handleStateOverrides function is well-structured and implements robust error handling. It makes good use of TypeScript features and follows best practices for handling optional parameters and complex objects.

Key points:

  1. Consider removing or replacing the console.log statement (line 18).
  2. Ensure AggregateError compatibility with the project's target Node.js versions.
  3. Add comprehensive unit tests to cover various scenarios and edge cases.

These minor improvements will enhance the function's reliability and maintainability.

packages/actions/src/Call/callProcedure.spec.ts (1)

Line range hint 1-231: Comprehensive test coverage for callProcedure function.

The test suite for the callProcedure function is well-structured and covers a wide range of scenarios:

  1. Basic call
  2. Call with state override
  3. Call with block override
  4. Call with tracing enabled
  5. Error handling

This comprehensive coverage ensures that the callProcedure function is thoroughly tested across various use cases, which is crucial for maintaining the reliability of the @tevm/actions package.

packages/actions/src/Call/callHandlerOpts.spec.ts (3)

3-3: LGTM: Import statement updated correctly.

The import statement has been updated to include bytesToHex from '@tevm/utils', which is likely used in the updated tests. This change is consistent with the modifications in the test cases.


Line range hint 1-265: Overall assessment of test suite changes.

The changes to this test suite have both positive and potentially concerning aspects:

  1. Positive: Addition of a new test case for block overrides without blobBaseFee, improving coverage in that area.
  2. Concern: Removal of two state override tests, potentially reducing coverage for state override scenarios.

While the test suite still covers a wide range of scenarios for the callHandlerOpts function, the removal of state override tests warrants further investigation.

To ensure that we maintain comprehensive test coverage, please:

  1. Confirm whether the state override functionality has been moved, removed, or refactored.
  2. If the functionality still exists, consider adding equivalent tests in the appropriate location.
  3. If the functionality has been removed, update the documentation to reflect this change.

You can use the following script to search for any remaining state override functionality in the codebase:

#!/bin/bash
# Search for state override related code and tests
echo "Searching for state override related code:"
rg --type typescript "stateOverride" ./packages
echo "Searching for state override related tests:"
rg --type typescript "state override" ./packages --glob "*spec.ts"

Based on the results, we can determine the next steps for maintaining or updating our test coverage.


Line range hint 1-265: Clarify the removal of state override tests.

Two test cases related to state overrides have been removed:

  1. "should handle state overrides correctly"
  2. "should handle invalid state overrides"

This reduction in test coverage for state override scenarios could potentially leave the callHandlerOpts function vulnerable to regressions or bugs related to state handling.

Could you please clarify the reason for removing these tests? If the state override functionality has been moved or refactored, consider adding equivalent tests in the appropriate location to maintain comprehensive test coverage.

To verify the current state of state override handling, you can run the following script:

✅ Verification successful

State override test coverage remains intact.

The removal of the two test cases in callHandlerOpts.spec.ts does not reduce overall test coverage for state overrides, as related tests are present in other modules:

  • ./packages/memory-client/src/test/viem/call.spec.ts
  • ./packages/decorators/src/eip1193/JsonRpcSchemaPublic.ts
  • ./packages/actions/src/Contract/validateContractParams.spec.ts
  • ./packages/actions/src/Call/zCallParams.spec.ts
  • ./packages/actions/src/Call/validateCallParams.spec.ts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for state override related code in the codebase
echo "Searching for state override related code:"
rg --type typescript "stateOverride" ./packages
echo "Searching for state override related tests:"
rg --type typescript "state override" ./packages --glob "*spec.ts"

Length of output: 472


Script:

#!/bin/bash
# Search for state override related code in the codebase
echo "Searching for state override related code:"
rg --type typescript "stateOverride" ./packages

echo "Searching for state override related tests:"
rg --type typescript "stateOverride" ./packages --glob "*spec.ts"

Length of output: 375


Script:

#!/bin/bash
# Search for state override related code in the codebase using 'ts' as the type
echo "Searching for state override related code:"
rg --type ts "stateOverride" ./packages

echo "Searching for state override related tests:"
rg --type ts "stateOverride" ./packages --glob "*spec.ts"

Length of output: 3499

@roninjin10 roninjin10 mentioned this pull request Oct 17, 2024
1 task
@roninjin10 roninjin10 merged commit d501679 into main Oct 17, 2024
9 checks passed
@roninjin10 roninjin10 deleted the 10-13-_bug_fix_stateoverrides_persisting_after_call_is_finished branch October 17, 2024 01:56
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.

1 participant