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

Improve UnwrapOrRevert interface #493

Conversation

kpob
Copy link
Contributor

@kpob kpob commented Jun 18, 2024

  • Add Revertible trait
  • unwrap_or_revert accepts revertible - reduces ContractEnv cloning

Summary by CodeRabbit

  • New Features

    • Introduced a new Revertible trait with a revert method to handle contract execution reversals.
  • Bug Fixes

    • Enhanced error handling across multiple modules by refactoring the use of unwrap_or_revert methods to improve reliability.
  • Refactor

    • Updated method calls to remove references to &self.env() and instead use self for better consistency and cleaner code.
    • Consolidated import statements for improved code maintainability.
  • Documentation

    • Adjusted public entity declarations to reflect the new Revertible trait and associated method changes.

* Add Revertible trait
* unwrap_or_revert accepts revertible - reduces ContractEnv cloning
@kpob kpob linked an issue Jun 18, 2024 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Jun 18, 2024

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

Commits

Files that changed from the base of the PR and between e3c4d00 and 43c4ecd.

Files selected for processing (2)
  • core/src/mapping.rs (4 hunks)
  • core/src/var.rs (5 hunks)
 ______________________________________________________________________________________________________________________________________________
< Eliminate effects between unrelated things. Design components that are self-contained, independent, and have a single, well-defined purpose. >
 ----------------------------------------------------------------------------------------------------------------------------------------------
  \
   \   (\__/)
       (•ㅅ•)
       /   づ

Walkthrough

The codebase was primarily refactored to introduce a new Revertible trait, which centralizes error handling and contract reversion across various components. The changes include implementing Revertible for different modules and adjusting method calls to use this trait, improving code readability and maintainability by reducing the necessity to pass environment references directly in error scenarios.

Changes

Files/Groups Change Summary
core/src/contract_env.rs Added Revertible trait implementations for ContractEnv and ExecutionEnv; modified method call syntax.
core/src/list.rs Introduced Revertible trait; updated replace and get_previous methods to use self.env directly.
core/src/mapping.rs Added Revertible trait for Mapping; refactored add and subtract methods to handle overflow reversion.
core/src/module.rs Introduced Revertible trait with implementations for Rc<ContractEnv> and T: Module; updated imports.
core/src/named_keys.rs Modified key handling methods to adapt to new Revertible trait; updated method signatures.
core/src/sequence.rs Implemented Revertible trait for Sequence<T>; updated imports.
core/src/unwrap_or_revert.rs Updated UnwrapOrRevert trait to use Revertible; refactored methods for Result and Option.
core/src/var.rs Added Revertible trait for Var<T>; consolidated casper_types imports.
examples/src/features/cross_calls.rs Refactored unwrap_or_revert calls to use self instead of &self.env().
examples/src/features/livenet.rs Modified pop_from_stack to use self instead of &self.env().
examples/src/features/module_nesting.rs Updated unwrap_or_revert method call argument from self.env() to self.
modules/src/cep18/storage.rs Refactored unwrap_or_revert calls to use self instead of &self.env() in add and sub functions.
modules/src/cep18_token.rs Modified unwrap_or_revert_with calls in three locations to pass self instead of &self.env().
modules/src/cep78/metadata.rs Removed self.env() in unwrap_or_revert call; used self directly in Metadata implementation.
modules/src/cep78/reverse_lookup.rs Refactored unwrap_or_revert calls to use self instead of &self.env() in ReverseLookup implementation.
modules/src/cep78/token.rs Updated unwrap_or_revert call to use self instead of self.__env in Cep78 implementation.
modules/src/wrapped_native.rs Modified unwrap_or_revert call parameter for handling token amounts in WrappedNativeToken.

Poem

In fields of code where logic thrives,
The Revertible trait now arrives,
Error handling, sharp and clear,
With self ensuring no more fear.
Bugs and chaos now take flight,
Harmony restored, all systems tight.
📜✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

Benchmark report

Action Details Gas diff
Wasm Deploy Filename: Benchmark.wasm 🔴 +0.162050115 CSPR (0.10%)
Contract Call Entry point: set_variable 🟢 -0.00007555 CSPR (0.05%)
Contract Call Entry point: set_mapping 🟢 -0.00007555 CSPR (0.05%)

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5d2ea53 and e3c4d00.

Files selected for processing (17)
  • core/src/contract_env.rs (4 hunks)
  • core/src/list.rs (4 hunks)
  • core/src/mapping.rs (4 hunks)
  • core/src/module.rs (2 hunks)
  • core/src/named_keys.rs (3 hunks)
  • core/src/sequence.rs (3 hunks)
  • core/src/unwrap_or_revert.rs (1 hunks)
  • core/src/var.rs (5 hunks)
  • examples/src/features/cross_calls.rs (1 hunks)
  • examples/src/features/livenet.rs (1 hunks)
  • examples/src/features/module_nesting.rs (1 hunks)
  • modules/src/cep18/storage.rs (2 hunks)
  • modules/src/cep18_token.rs (3 hunks)
  • modules/src/cep78/metadata.rs (2 hunks)
  • modules/src/cep78/reverse_lookup.rs (2 hunks)
  • modules/src/cep78/token.rs (1 hunks)
  • modules/src/wrapped_native.rs (1 hunks)
Files skipped from review due to trivial changes (1)
  • modules/src/cep78/token.rs
Additional comments not posted (31)
core/src/unwrap_or_revert.rs (2)

9-9: The changes to unwrap_or_revert_with effectively integrate the Revertible trait, enhancing the flexibility and reusability of error handling across different contexts.

Also applies to: 16-17, 26-27


12-12: The update to unwrap_or_revert effectively utilizes the Revertible trait, simplifying the interface and reducing dependencies on specific environment instances.

Also applies to: 20-21, 30-31

examples/src/features/cross_calls.rs (1)

21-21: The modification to use self directly in the unwrap_or_revert call streamlines the interaction with the Revertible trait, enhancing code clarity and error handling consistency.

examples/src/features/livenet.rs (1)

43-43: The update to the unwrap_or_revert call in pop_from_stack to use self instead of &self.env() aligns with the new Revertible trait usage, enhancing code simplicity and reducing unnecessary references.

core/src/sequence.rs (1)

25-31: The implementation of the Revertible trait for Sequence<T> is correctly done, utilizing the existing env.revert method to handle errors, which maintains consistency and leverages existing functionality.

core/src/var.rs (5)

4-10: Consolidation of imports enhances readability and maintainability.


20-24: Implementation of Revertible for Var<T> correctly delegates the revert action to ContractEnv. This aligns with the PR's goal of reducing the need for cloning ContractEnv.


60-60: The use of self directly in unwrap_or_revert_with is a good application of the new Revertible trait, reducing the need for passing ContractEnv explicitly.


87-87: Using self in unwrap_or_revert within the add method follows the new trait's design and improves code clarity by removing unnecessary references.


100-100: Similarly, the subtract method's use of self with unwrap_or_revert is consistent and correct, adhering to the new interface design.

modules/src/cep18/storage.rs (2)

55-55: The updated unwrap_or_revert usage in Cep18BalancesStorage.add method is a direct application of the Revertible trait, which simplifies the error handling by eliminating the explicit reference to ContractEnv.


64-64: In Cep18BalancesStorage.subtract, the use of self with unwrap_or_revert_with is correctly implemented and aligns with the new trait's design to simplify and standardize error handling.

core/src/module.rs (2)

9-9: Inclusion of OdraError in the import statement is necessary for the new Revertible trait implementation.


30-46: The introduction of the Revertible trait and its implementation for Rc<ContractEnv> and T: Module are central to this PR's objectives. The implementation correctly uses the environment's revert method, which should ensure consistent error handling across modules.

core/src/mapping.rs (3)

6-12: The updated imports and inclusion of Revertible in the import list are necessary for the new functionality introduced in this file.


33-37: Implementation of Revertible for Mapping<K, V> correctly delegates the revert responsibility to ContractEnv, which is consistent with the trait's usage in other parts of the codebase.


Line range hint 93-113: The use of self in unwrap_or_revert within the add and subtract methods of Mapping<K, V> is correctly implemented. It leverages the Revertible trait to handle errors directly, enhancing code clarity and reducing dependencies.

core/src/named_keys.rs (2)

19-19: Change aligns with PR objectives to utilize Revertible for error handling. Consider adding documentation on how Revertible is used here for clarity.


72-88: Refactoring to use Revertible in the key method enhances error handling. Ensure that base64::prelude::Engine and BASE64_STANDARD are the most efficient choices for this task.

examples/src/features/module_nesting.rs (1)

64-64: Change to use self directly in unwrap_or_revert aligns with PR objectives to reduce ContractEnv cloning. Check all related method calls across the codebase for consistency.

modules/src/wrapped_native.rs (1)

31-31: Change to use self directly in unwrap_or_revert aligns with PR objectives. Consider adding a comment explaining why self is used here for future maintainers.

core/src/list.rs (1)

Line range hint 80-95: Refactoring to use Revertible in replace and pop methods simplifies error handling. Verify the behavior with unit tests to ensure correct functionality.

Verification successful

The search results indicate that there are indeed unit tests covering both the replace and pop methods in the codebase. Therefore, the refactoring to use the Revertible trait for error handling in these methods should be verified through these existing tests.

  • replace method is tested in fn test_replace().
  • pop method is tested in fn test_pop().

These tests will ensure that the new error handling paths are correctly implemented.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Ensure unit tests cover the new error handling paths in `replace` and `pop` methods.

# Test: Search for unit tests related to `replace` and `pop`.
rg --type rust $'List.*(replace|pop).*test'

Length of output: 44



Script:

#!/bin/bash
# Description: Search for direct usage of `replace` and `pop` methods in test files.

# Find all test files and search for `replace` method.
fd --type f --extension rs --exec rg 'replace' {}

# Find all test files and search for `pop` method.
fd --type f --extension rs --exec rg 'pop' {}

Length of output: 2099

modules/src/cep78/reverse_lookup.rs (2)

90-90: Update to use unwrap_or_revert with self-reference is consistent with PR goals.


239-239: Ensure the error handling logic with unwrap_or_revert is tested thoroughly as it directly impacts the robustness of the contract.

core/src/contract_env.rs (2)

6-6: The import of Revertible is aligned with the PR's objective to enhance error handling by leveraging the new trait.


309-314: Proper error handling in get_named_arg method is crucial. Ensure that the deserialization errors are correctly converted to OdraError and tested.

modules/src/cep78/metadata.rs (2)

103-103: The use of unwrap_or_revert here is appropriate to ensure that the contract fails early if the JSON schema is invalid. This aligns with the PR’s goals of robust error handling.


304-304: Ensure that the custom validated metadata schema parsing is covered by unit tests to prevent runtime errors.

Verification successful

Ensure that the custom validated metadata schema parsing is covered by unit tests to prevent runtime errors.

  • The CustomMetadataSchema is referenced in modules/src/cep78/tests/mod.rs, indicating that it is indeed covered by tests.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify unit tests cover JSON schema parsing in `metadata.rs`.

# Test: Search for tests covering JSON schema parsing in `metadata.rs`.
rg --type rust 'test' -A 20 modules/src/cep78/metadata.rs | rg 'from_str::<CustomMetadataSchema>'

Length of output: 97



Script:

#!/bin/bash
# Description: Check for unit tests in `metadata.rs`.

# Search for unit test definitions in `metadata.rs`.
rg --type rust '#\[cfg\(test\)\]' -A 10 modules/src/cep78/metadata.rs

Length of output: 71



Script:

#!/bin/bash
# Description: Check for unit tests in the broader codebase.

# Search for unit test definitions across the codebase.
rg --type rust '#\[cfg\(test\)\]' -A 10

Length of output: 51831



Script:

#!/bin/bash
# Description: Check for `CustomMetadataSchema` usage in test files.

# Search for `CustomMetadataSchema` in test files.
rg 'CustomMetadataSchema' --type rust --glob 'tests/**/*.rs'

Length of output: 209



Script:

#!/bin/bash
# Description: Check for `CustomMetadataSchema` usage in all Rust files.

# Search for `CustomMetadataSchema` in all Rust files.
rg 'CustomMetadataSchema' --type rust

Length of output: 992

modules/src/cep18_token.rs (3)

99-99: The update to use unwrap_or_revert_with with self-reference improves the readability and consistency of error handling across the contract.


237-237: Using unwrap_or_revert_with for handling insufficient allowance errors ensures that the contract's behavior is predictable and secure. This is crucial for maintaining trust in the token's operations.


257-257: The use of unwrap_or_revert_with in the mint function aligns with the PR’s objectives and ensures that only authorized users can mint new tokens.

core/src/contract_env.rs Show resolved Hide resolved
core/src/contract_env.rs Show resolved Hide resolved
core/src/named_keys.rs Show resolved Hide resolved
Comment on lines +42 to +46
impl<T> Revertible for List<T> {
fn revert<E: Into<OdraError>>(&self, e: E) -> ! {
self.env.revert(e)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The recent shell script results indicate that there are no direct tests for the revert method associated with List and no specific references to List in the test files. However, the revert method is widely used across the codebase, suggesting its importance in error handling.

To ensure the robustness of the List implementation, it is crucial to add unit tests specifically targeting the revert method to cover possible error scenarios.

  • Ensure unit tests cover scenarios where List::revert might be triggered.
  • Add specific tests for the revert method in List to ensure its functionality and reliability.
Analysis chain

Implementation of Revertible for List enhances error handling. Ensure unit tests cover scenarios where revert might be triggered.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify unit tests cover the new `revert` method in `List`.

# Test: Search for unit tests related to `List` and `revert`.
rg --type rust $'List.*revert.*test'

Length of output: 37



Script:

#!/bin/bash
# Description: Check for any usage of the `revert` method for `List` in the codebase.

# Search for the usage of the `revert` method in the codebase.
rg --type rust 'List.*\.revert\('

Length of output: 35


Script:

#!/bin/bash
# Description: Check for any existing tests for the `List` structure.

# Search for tests related to the `List` structure.
rg --type rust 'List.*test'

Length of output: 29



Script:

#!/bin/bash
# Description: Check for any usage of the `revert` method for `List` in the codebase.

# Search for the usage of the `revert` method in the codebase.
rg --type rust 'revert\('

Length of output: 22307


Script:

#!/bin/bash
# Description: Check for any existing tests for the `List` structure.

# List all test files to manually inspect for any tests related to `List`.
fd --type f --extension rs --exec rg --files-with-matches 'test'

Length of output: 4054

core/src/mapping.rs Outdated Show resolved Hide resolved
Copy link

Benchmark report

Action Details Gas diff
Wasm Deploy Filename: Benchmark.wasm 🔴 +0.162050115 CSPR (0.10%)
Contract Call Entry point: set_variable 🟢 -0.00007555 CSPR (0.05%)
Contract Call Entry point: set_mapping 🟢 -0.00007555 CSPR (0.05%)

@kpob kpob merged commit e611f32 into release/1.2.0 Jun 27, 2024
4 checks passed
@kpob kpob deleted the feature/unwrap_or_revert_with-should-accept-module-as-argument branch June 27, 2024 10:07
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.

unwrap_or_revert_with should accept module as argument
3 participants