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: calling precompile through sc with sc state update #2853

Merged
merged 5 commits into from
Sep 10, 2024

Conversation

skosito
Copy link
Contributor

@skosito skosito commented Sep 9, 2024

Description

If stake precompile function is called through smart contract with some state changes on smart contract side, bank module state is not updated properly, it is overwritten, and bank balance is not reduced. In that case state on stateDB should manually be updated, so it is propagated to bank module update.

This PR adds counter in TestStaking.sol which is updated before and after stake call, and extends e2e test to verify that bank balance is reduced after stake method is executed. Also, adds one more function that stakes and reverts, to check that state on cosmos side is not updated.

How Has This Been Tested?

  • Tested CCTX in localnet
  • Tested in development environment
  • Go unit tests
  • Go integration tests
  • Tested via GitHub Actions

Summary by CodeRabbit

  • New Features

    • Introduced new functions for staking operations: stakeAndRevert and stakeWithStateUpdate.
    • Added a view function counter to retrieve the current counter value.
    • Enhanced state tracking capabilities within the staking contract.
  • Bug Fixes

    • Improved test validations for staking scenarios, ensuring accurate state management during reverts.
  • Documentation

    • Updated contract interface documentation to reflect new functions and their parameters.

@skosito skosito linked an issue Sep 9, 2024 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Sep 9, 2024

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Walkthrough

The pull request introduces several enhancements to the TestStaking contract, including the addition of new functions for staking operations and a counter for state tracking. The changes span multiple files, including ABI definitions, Go bindings, and Solidity contract implementations, facilitating improved interaction with the staking logic. Notably, new functions stakeAndRevert and stakeWithStateUpdate are introduced, along with a view function counter. These modifications aim to expand the contract's interface and improve testing capabilities.

Changes

File Path Change Summary
e2e/contracts/teststaking/TestStaking.abi Added functions: counter(), stakeAndRevert(address, string, uint256), stakeWithStateUpdate(address, string, uint256)
e2e/contracts/teststaking/TestStaking.go Added Go bindings for new functions: Counter(), StakeAndRevert(), StakeWithStateUpdate().
e2e/contracts/teststaking/TestStaking.json Updated ABI with new functions: counter, stakeAndRevert, stakeWithStateUpdate.
e2e/contracts/teststaking/TestStaking.sol Introduced public state variable counter and added functions stakeWithStateUpdate and stakeAndRevert with onlyOwner restriction.
e2e/e2etests/test_precompiles_staking_through_contract.go Added stakeAmount variable and introduced StakeAndRevert method for testing revert scenarios.
precompiles/staking/staking.go Modified Stake method to include evm *vm.EVM parameter for better state management.
precompiles/staking/staking_test.go Updated tests to include mockEVM parameter for simulating EVM interactions.

Possibly related issues

  • Extend staking precompile e2e tests #2851: The addition of e2e tests for smart contract reverts and state changes aligns with the objectives of extending staking precompile e2e tests as outlined in this issue.

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

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

codecov bot commented Sep 9, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 66.91%. Comparing base (9df6938) to head (e74b406).
Report is 1 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           develop    #2853   +/-   ##
========================================
  Coverage    66.90%   66.91%           
========================================
  Files          370      370           
  Lines        20977    20980    +3     
========================================
+ Hits         14035    14038    +3     
  Misses        6302     6302           
  Partials       640      640           
Files with missing lines Coverage Δ
precompiles/staking/staking.go 96.18% <100.00%> (+0.04%) ⬆️

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, codebase verification and nitpick comments (2)
precompiles/staking/staking.go (1)

Line range hint 185-241: LGTM! The changes handle state updates correctly when Stake is called through a smart contract.

The modifications to the Stake function are well-structured and ensure that the state is updated consistently when the function is invoked through a smart contract. Manually reducing the balance of the staker in the state database is a good approach to maintain consistency between the EVM state and the bank module.

To further improve the code, consider the following suggestions:

  1. Add a comment explaining the purpose of the if contract.CallerAddress != evm.Origin check and the manual balance reduction. This will enhance code readability and maintainability.

  2. Consider extracting the manual balance reduction logic into a separate function to improve code modularity and reusability. This function can be reused in other precompile functions that require similar state updates.

  3. Add error handling for the stateDB.SubBalance operation to gracefully handle any potential errors that may occur during the balance reduction.

These suggestions aim to enhance the overall quality and maintainability of the code.

e2e/contracts/teststaking/TestStaking.sol (1)

82-87: LGTM, but consider an optimization.

The stakeWithStateUpdate function is correctly implemented and can effectively track state changes when staking.

However, consider optimizing the function by using the ++ operator for incrementing the counter. This will make the code more concise and gas-efficient.

Apply this diff to optimize the function:

-    counter = counter + 1;
+    counter++;
     bool success = staking.stake(staker, validator, amount);
-    counter = counter + 1;
+    counter++;
Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d210011 and eb5b380.

Files ignored due to path filters (1)
  • e2e/contracts/teststaking/TestStaking.bin is excluded by !**/*.bin
Files selected for processing (7)
  • e2e/contracts/teststaking/TestStaking.abi (2 hunks)
  • e2e/contracts/teststaking/TestStaking.go (3 hunks)
  • e2e/contracts/teststaking/TestStaking.json (3 hunks)
  • e2e/contracts/teststaking/TestStaking.sol (2 hunks)
  • e2e/e2etests/test_precompiles_staking_through_contract.go (2 hunks)
  • precompiles/staking/staking.go (3 hunks)
  • precompiles/staking/staking_test.go (16 hunks)
Additional context used
Path-based instructions (4)
e2e/e2etests/test_precompiles_staking_through_contract.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

precompiles/staking/staking.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

e2e/contracts/teststaking/TestStaking.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

precompiles/staking/staking_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

Additional comments not posted (21)
e2e/contracts/teststaking/TestStaking.json (3)

18-30: LGTM! The counter function is a valid addition to the contract.

The counter function is correctly defined as a view function, which aligns with its purpose of retrieving a value without modifying the contract state. The function signature and return type are properly specified, adhering to the Solidity syntax.

The addition of this function enhances the contract's functionality by providing a convenient way to retrieve a counter value, which can be useful for tracking certain metrics or state variables.


160-188: LGTM! The stakeAndRevert function is a valid addition to the contract.

The stakeAndRevert function is correctly defined as a non-payable function, which aligns with its purpose of performing a staking operation without accepting Ether. The function signature, input parameters, and return type are properly specified, adhering to the Solidity syntax.

The purpose of the function is clear from its name, suggesting that it performs a staking operation and then reverts the transaction. This functionality can be useful for testing or simulating staking scenarios where a revert is expected, enhancing the contract's testability and robustness.


189-217: LGTM! The stakeWithStateUpdate function is a valid addition to the contract.

The stakeWithStateUpdate function is correctly defined as a non-payable function, which aligns with its purpose of performing a staking operation without accepting Ether. The function signature, input parameters, and return type are properly specified, adhering to the Solidity syntax.

The purpose of the function is clear from its name, suggesting that it performs a staking operation and updates the contract state accordingly. This functionality ensures that the staking process is properly reflected in the contract's state variables, maintaining consistency and accuracy.

The addition of this function enhances the contract's staking capabilities by providing a way to perform staking while ensuring that the contract state is properly updated.

e2e/contracts/teststaking/TestStaking.go (4)

213-228: LGTM! The Counter function in the TestStakingCaller interface is correctly implemented.

The Counter function is properly defined in the TestStakingCaller interface, which is used for read-only operations. The function signature and return types are correctly specified, adhering to the Go syntax and the contract's ABI.

The function uses the Call method of the contract instance to invoke the counter function, passing the necessary input parameters. The returned value is appropriately converted to *big.Int using abi.ConvertType, ensuring type safety.

The addition of this function in the TestStakingCaller interface allows for convenient retrieval of the counter value from the contract.


230-235: LGTM! The Counter function in the TestStakingSession interface is correctly implemented.

The Counter function is properly defined in the TestStakingSession interface, which is used for read-only operations with a pre-configured session. The function signature and return types are correctly specified, adhering to the Go syntax and the contract's ABI.

The function uses the Counter function from the TestStakingCaller interface to retrieve the counter value, leveraging the pre-configured session options.

The addition of this function in the TestStakingSession interface provides a convenient way to retrieve the counter value within a session context.


237-242: LGTM! The Counter function in the TestStakingCallerSession interface is correctly implemented.

The Counter function is properly defined in the TestStakingCallerSession interface, which is used for read-only operations with a pre-configured caller session. The function signature and return types are correctly specified, adhering to the Go syntax and the contract's ABI.

The function uses the Counter function from the TestStakingCaller interface to retrieve the counter value, leveraging the pre-configured caller session options.

The addition of this function in the TestStakingCallerSession interface provides a convenient way to retrieve the counter value within a caller session context.


369-374: LGTM! The StakeAndRevert function in the TestStakingTransactor interface is correctly implemented.

The StakeAndRevert function is properly defined in the TestStakingTransactor interface, which is used for write operations. The function signature and input parameters are correctly specified, adhering to the Go syntax and the contract's ABI.

The function uses the Transact method of the contract instance to invoke the stakeAndRevert function, passing the necessary input parameters such as staker, validator, and amount. The function returns a transaction object and an error, allowing for proper error handling.

The addition of this function in the TestStakingTransactor interface enables the execution of the stakeAndRevert function on the contract.

precompiles/staking/staking_test.go (3)

379-380: LGTM!

The changes to the setup function are approved. Returning the mockEVM and mockVMContract instances enhances the test setup by allowing for more controlled and isolated testing of the staking precompile interactions with the EVM.


398-398: LGTM!

The changes to the Test_Stake function are approved. Passing the mockEVM instance to the Stake method calls improves the test coverage by simulating the EVM interactions during staking. The changes are consistent across all test cases.

Also applies to: 424-424, 451-451, 478-478


821-821: LGTM!

The changes to the Test_MoveStake function are approved. Passing the mockEVM instance to the Stake method calls improves the test coverage by simulating the EVM interactions during staking. The changes are consistent across all test cases.

Also applies to: 847-847, 866-866, 892-892, 911-911, 937-937, 956-956, 982-982, 1001-1001, 1027-1027, 1155-1155

e2e/contracts/teststaking/TestStaking.sol (2)

55-56: LGTM!

The counter state variable is correctly declared and initialized. It can be effectively used to track state changes within the contract.


89-94: LGTM!

The stakeAndRevert function is correctly implemented and serves as an effective test case to demonstrate state changes followed by a revert. It ensures that the contract's state remains unaffected when a staking operation is not finalized.

e2e/contracts/teststaking/TestStaking.abi (3)

17-29: LGTM!

The counter function declaration is correct and aligns with the corresponding state variable in the TestStaking contract. It allows retrieving the current value of the counter without modifying the contract's state.


159-187: LGTM!

The stakeAndRevert function declaration is correct and aligns with the corresponding function in the TestStaking contract. It allows for staking to a validator and subsequently reverting the transaction within the same function call.


188-216: LGTM!

The stakeWithStateUpdate function declaration is correct and aligns with the corresponding function in the TestStaking contract. It allows for staking to a validator while updating the contract's state by incrementing the counter variable.

e2e/e2etests/test_precompiles_staking_through_contract.go (6)

63-64: LGTM!

Introducing the stakeAmount variable enhances code readability and maintainability by avoiding the use of a hardcoded value directly in the WithdrawWZETA function call. This change makes the code more expressive and easier to understand.


68-75: LGTM!

The added code block for querying the bank balance before staking operations is a valuable addition. It ensures that the initial state is validated against the expected stakeAmount. The code is clean, expressive, and adheres to the best practices for interacting with the bank module using the BankClient and QueryBalanceRequest.


76-80: LGTM!

The new test case for the StakeAndRevert function is a valuable addition to the test suite. It verifies the behavior of the contract when a stake is made but not finalized, ensuring that the state remains unaffected. The code is clean and adheres to the best practices for interacting with the contract and waiting for the transaction receipt using utils.MustWaitForTxReceipt.


81-98: LGTM!

The added code block for checking the bank balance and contract state after the StakeAndRevert function call is a crucial addition to the test suite. It thoroughly validates that the state remains unaffected by the reverted staking operation. The code is clean, expressive, and adheres to the best practices for querying balances using the BankClient and interacting with the contract functions Counter and GetShares. The assertions provide a robust verification of the expected behavior.


99-111: LGTM!

The new test case for the Stake function without smart contract state update is a valuable addition to the test suite. It verifies that the staking operation is performed correctly and the bank balance is updated accordingly. The code is clean and adheres to the best practices for interacting with the contract, waiting for the transaction receipt, and querying the bank balance. The assertions provide a solid validation of the expected behavior.


112-134: LGTM!

The new test case for the StakeWithStateUpdate function is a critical addition to the test suite. It thoroughly verifies that the staking operation updates the contract state correctly, including the bank balance and the counter variable. The code is clean, expressive, and adheres to the best practices for interacting with the contract, waiting for the transaction receipt, and querying the

precompiles/staking/staking.go Outdated Show resolved Hide resolved
@skosito skosito added this pull request to the merge queue Sep 10, 2024
Merged via the queue into develop with commit d335f2d Sep 10, 2024
30 checks passed
@skosito skosito deleted the extend-staking-precompile-e2e-tests branch September 10, 2024 10:35
@coderabbitai coderabbitai bot mentioned this pull request Sep 17, 2024
15 tasks
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.

Extend staking precompile e2e tests
3 participants