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: add validation for multi message execution wasm #2092

Merged
merged 5 commits into from
Oct 30, 2024
Merged

Conversation

matthiasmatt
Copy link
Contributor

@matthiasmatt matthiasmatt commented Oct 24, 2024

Purpose / Abstract

Summary by CodeRabbit

  • New Features

    • Added validation for WASM multi-message execution.
    • Improved handling of ERC20 metadata during FunToken creation.
    • Enhanced gas fee calculations and consumption management within ERC20 contract execution.
    • Implemented foundry support and templates for Nibiru EVM development.
  • Bug Fixes

    • Addressed state consistency issues in precompile execution.
    • Enhanced error message clarity and improved handling of invalid inputs.
  • Documentation

    • Updated changelog format for better clarity and organization of changes.

@matthiasmatt matthiasmatt requested a review from a team as a code owner October 24, 2024 12:17
Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

Walkthrough

The pull request includes updates to the CHANGELOG.md for the Nibiru project, detailing new features, improvements, and bug fixes, particularly in the EVM module. Key enhancements include validation for WASM multi-message execution and better handling of ERC20 metadata during FunToken creation. Modifications to the executeMulti method in x/evm/precompile/wasm.go improve validation processes for contract calls. The testing framework in x/evm/precompile/wasm_test.go is enhanced with new types and test methods to ensure robust validation of contract interactions.

Changes

File Change Summary
CHANGELOG.md Added new features including validation for WASM multi-message execution, foundry support, improved ERC20 metadata handling during FunToken creation, and better gas consumption management.
x/evm/precompile/wasm.go Refactored executeMulti method to implement a validation step for multiple contract calls before execution, enhancing error handling and reporting.
x/evm/precompile/wasm_test.go Introduced WasmExecuteMsg type and new test methods (TestExecuteMultiValidation, TestExecuteMultiPartialExecution) to validate multi-message execution scenarios, ensuring robust error handling and state management.

Possibly related PRs

Suggested labels

x: evm

Suggested reviewers

  • onikonychev
  • k-yang

Poem

In the land of code where bunnies play,
New features hop in, brightening the day.
With validation and events in tow,
Our EVM dances, putting on a show!
Bugs are squashed, and clarity's found,
In this rabbit's world, joy knows no bound! 🐇✨


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

codecov bot commented Oct 24, 2024

Codecov Report

Attention: Patch coverage is 75.00000% with 2 lines in your changes missing coverage. Please review.

Project coverage is 64.58%. Comparing base (9d0dbd5) to head (ae0f2d0).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
x/evm/precompile/wasm.go 75.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2092      +/-   ##
==========================================
+ Coverage   64.52%   64.58%   +0.06%     
==========================================
  Files         271      271              
  Lines       21235    21237       +2     
==========================================
+ Hits        13701    13716      +15     
+ Misses       6584     6574      -10     
+ Partials      950      947       -3     
Files with missing lines Coverage Δ
x/evm/statedb/statedb.go 91.02% <ø> (-0.09%) ⬇️
x/evm/precompile/wasm.go 61.01% <75.00%> (+8.69%) ⬆️

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 (2)
CHANGELOG.md (1)

139-139: Consider expanding the changelog entry to be more descriptive.

The current entry "feat(evm): add validation for wasm multi message execution" could be more informative about:

Consider expanding it to something like:

- - [#2092](https://github.com/NibiruChain/nibiru/pull/2092) - feat(evm): add validation for wasm multi message execution
+ - [#2092](https://github.com/NibiruChain/nibiru/pull/2092) - feat(evm): add validation for wasm multi message execution. Implements enhanced validation checks for multiple contract calls in response to Code423n4 issue #34, improving the security and reliability of contract interactions.
x/evm/precompile/wasm.go (1)

334-342: Consider executing all messages even if some executions fail

In the execution loop, the function returns immediately when an execution error occurs. Executing all messages and collecting errors can provide a complete set of execution results to the caller.

Here's a potential modification:

 var responses [][]byte
+var executionErrors []error

 // Execute all messages after validation
 for _, msg := range validatedMsgs {
     respBz, e := p.Wasm.Execute(ctx, msg.contract, callerBech32, msg.msgArgs, msg.funds)
     if e != nil {
-        err = fmt.Errorf("execute failed for contract %s: %w", msg.contract.String(), e)
-        return
+        executionErrors = append(executionErrors, fmt.Errorf("execute failed for contract %s: %w", msg.contract.String(), e))
+        continue
     }
     responses = append(responses, respBz)
 }

+if len(executionErrors) > 0 {
+    err = fmt.Errorf("execution errors occurred: %v", executionErrors)
+    return
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between dd27f4b and 0b68c73.

📒 Files selected for processing (3)
  • CHANGELOG.md (1 hunks)
  • x/evm/precompile/wasm.go (2 hunks)
  • x/evm/precompile/wasm_test.go (2 hunks)
🔇 Additional comments (2)
CHANGELOG.md (1)

Line range hint 1-1207: LGTM! Well-structured changelog.

The changelog follows proper semantic versioning, has clear categorization of changes, and maintains consistent formatting throughout.

x/evm/precompile/wasm_test.go (1)

731-773: LGTM: The TestExecuteMultiPartialExecution function correctly verifies no state change on validation failure

The test effectively ensures that no state changes occur if any message in the batch fails validation, maintaining the integrity of the system as expected.

Comment on lines 309 to 329
// Validate each message using parseExecuteArgs
for _, msg := range wasmExecMsgs {
// Create args array in the format expected by parseExecuteArgs
singleMsgArgs := []any{
msg.ContractAddr,
msg.MsgArgs,
msg.Funds,
}

contract, msgArgs, funds, e := p.parseExecuteArgs(singleMsgArgs)
if e != nil {
err = fmt.Errorf("Execute failed: %w", e)
err = fmt.Errorf("validation failed for contract %s: %w", msg.ContractAddr, e)
return
}
var funds sdk.Coins
for _, fund := range m.Funds {
funds = append(funds, sdk.Coin{
Denom: fund.Denom,
Amount: sdk.NewIntFromBigInt(fund.Amount),
})
}
respBz, e := p.Wasm.Execute(ctx, wasmContract, callerBech32, m.MsgArgs, funds)

validatedMsgs = append(validatedMsgs, validatedMsg{
contract: contract,
msgArgs: msgArgs,
funds: funds,
})
}
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

Enhance validation by collecting all errors before returning

Currently, the validation loop returns upon encountering the first error. Collecting all validation errors before returning could provide more comprehensive feedback to the caller.

You might modify the code as follows:

 var validationErrors []error

 for _, msg := range wasmExecMsgs {
     // Create args array in the format expected by parseExecuteArgs
     singleMsgArgs := []any{
         msg.ContractAddr,
         msg.MsgArgs,
         msg.Funds,
     }

     contract, msgArgs, funds, e := p.parseExecuteArgs(singleMsgArgs)
     if e != nil {
-        err = fmt.Errorf("validation failed for contract %s: %w", msg.ContractAddr, e)
-        return
+        validationErrors = append(validationErrors, fmt.Errorf("validation failed for contract %s: %w", msg.ContractAddr, e))
         continue
     }

     validatedMsgs = append(validatedMsgs, validatedMsg{
         contract: contract,
         msgArgs:  msgArgs,
         funds:    funds,
     })
 }

+if len(validationErrors) > 0 {
+    err = fmt.Errorf("validation errors occurred: %v", validationErrors)
+    return
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Validate each message using parseExecuteArgs
for _, msg := range wasmExecMsgs {
// Create args array in the format expected by parseExecuteArgs
singleMsgArgs := []any{
msg.ContractAddr,
msg.MsgArgs,
msg.Funds,
}
contract, msgArgs, funds, e := p.parseExecuteArgs(singleMsgArgs)
if e != nil {
err = fmt.Errorf("Execute failed: %w", e)
err = fmt.Errorf("validation failed for contract %s: %w", msg.ContractAddr, e)
return
}
var funds sdk.Coins
for _, fund := range m.Funds {
funds = append(funds, sdk.Coin{
Denom: fund.Denom,
Amount: sdk.NewIntFromBigInt(fund.Amount),
})
}
respBz, e := p.Wasm.Execute(ctx, wasmContract, callerBech32, m.MsgArgs, funds)
validatedMsgs = append(validatedMsgs, validatedMsg{
contract: contract,
msgArgs: msgArgs,
funds: funds,
})
}
// Validate each message using parseExecuteArgs
var validationErrors []error
for _, msg := range wasmExecMsgs {
// Create args array in the format expected by parseExecuteArgs
singleMsgArgs := []any{
msg.ContractAddr,
msg.MsgArgs,
msg.Funds,
}
contract, msgArgs, funds, e := p.parseExecuteArgs(singleMsgArgs)
if e != nil {
validationErrors = append(validationErrors, fmt.Errorf("validation failed for contract %s: %w", msg.ContractAddr, e))
continue
}
validatedMsgs = append(validatedMsgs, validatedMsg{
contract: contract,
msgArgs: msgArgs,
funds: funds,
})
}
if len(validationErrors) > 0 {
err = fmt.Errorf("validation errors occurred: %v", validationErrors)
return
}

Comment on lines 719 to 721
s.Require().Error(err)
s.Require().Contains(err.Error(), tc.wantError)
s.Require().Nil(ethTxResp)
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

Improve error assertions by checking error types instead of error messages

Comparing error messages using substrings can be brittle and may lead to fragile tests. Consider checking for specific error types or using error wrapping to make your tests more robust and maintainable.

x/evm/precompile/wasm_test.go Show resolved Hide resolved
Copy link
Member

@Unique-Divine Unique-Divine left a comment

Choose a reason for hiding this comment

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

The issue describes validation specifically for the m.MsgArgs field, which should only be a few line change, not 200+. The validate basic call is for the JSON arguments

You can remove most of this code and type the msgArgs from raw bytes to the type from Wasm validate that

msgArgsCopy := wasm.RawContractMessage(msgArgs)
if e := msgArgsCopy.ValidateBasic(); e != nil {
    err = ErrArgTypeValidation(e.Error(), args[argIdx])
    return
}

Copy link
Member

Choose a reason for hiding this comment

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

Test cases look good

@matthiasmatt matthiasmatt enabled auto-merge (squash) October 28, 2024 17:41
@matthiasmatt matthiasmatt disabled auto-merge October 29, 2024 14:06
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: 6

🧹 Outside diff range and nitpick comments (1)
CHANGELOG.md (1)

159-159: Add more details about the validation changes.

While the entry correctly references PR #2092, it would be helpful to expand on what specific validation was added for wasm multi message execution to help users understand the security implications.

Consider expanding the entry to something like:

-- [#2092](https://github.com/NibiruChain/nibiru/pull/2092) - feat(evm): add validation for wasm multi message execution
++ [#2092](https://github.com/NibiruChain/nibiru/pull/2092) - feat(evm): add validation for wasm multi message execution to ensure message integrity and prevent potential security vulnerabilities
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0b68c73 and 5174c5e.

📒 Files selected for processing (3)
  • CHANGELOG.md (1 hunks)
  • x/evm/precompile/wasm.go (2 hunks)
  • x/evm/precompile/wasm_test.go (2 hunks)
🧰 Additional context used
🪛 GitHub Check: unit-tests
x/evm/precompile/wasm_test.go

[failure] 334-334:
undefined: SetupWasmContracts


[failure] 442-442:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 463-463:
undefined: SetupWasmContracts


[failure] 467-467:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)


[failure] 490-490:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 500-500:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)

🪛 GitHub Check: integration-tests
x/evm/precompile/wasm_test.go

[failure] 334-334:
undefined: SetupWasmContracts


[failure] 442-442:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 463-463:
undefined: SetupWasmContracts


[failure] 467-467:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)


[failure] 490-490:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 500-500:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)

🪛 GitHub Check: lint
x/evm/precompile/wasm_test.go

[failure] 334-334:
undefined: SetupWasmContracts


[failure] 442-442:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 463-463:
undefined: SetupWasmContracts


[failure] 467-467:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)


[failure] 490-490:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 500-500:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState) (typecheck)

🔇 Additional comments (5)
x/evm/precompile/wasm_test.go (3)

318-322: Existing comment about reusing WasmExecuteMsg type is still valid


324-457: Well-structured test cases for multi-message validation

The test cases comprehensively cover various validation scenarios including:

  • Valid single and multiple messages
  • Invalid contract addresses
  • Malformed message arguments
  • Invalid funds
  • Partial validation failures

This ensures robust validation of the multi-message execution feature.

🧰 Tools
🪛 GitHub Check: unit-tests

[failure] 334-334:
undefined: SetupWasmContracts


[failure] 442-442:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values

🪛 GitHub Check: integration-tests

[failure] 334-334:
undefined: SetupWasmContracts


[failure] 442-442:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values

🪛 GitHub Check: lint

[failure] 334-334:
undefined: SetupWasmContracts


[failure] 442-442:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


459-501: Well-designed test for partial execution validation

The test effectively verifies that the system maintains atomicity during multi-message execution by ensuring no state changes occur when any message in the batch fails validation.

🧰 Tools
🪛 GitHub Check: unit-tests

[failure] 463-463:
undefined: SetupWasmContracts


[failure] 467-467:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)


[failure] 490-490:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 500-500:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)

🪛 GitHub Check: integration-tests

[failure] 463-463:
undefined: SetupWasmContracts


[failure] 467-467:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)


[failure] 490-490:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 500-500:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)

🪛 GitHub Check: lint

[failure] 463-463:
undefined: SetupWasmContracts


[failure] 467-467:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)


[failure] 490-490:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 500-500:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState) (typecheck)

CHANGELOG.md (1)

151-158: LGTM!

The changelog entries for PRs #2073-#2089 are properly formatted and provide clear descriptions of the changes made.

x/evm/precompile/wasm.go (1)

289-308: The previous suggestion to collect all validation errors is still applicable

As per the previous review comment, the current implementation returns upon encountering the first validation error. Collecting all validation errors before returning could provide more comprehensive feedback to the caller.

x/evm/precompile/wasm_test.go Outdated Show resolved Hide resolved
x/evm/precompile/wasm_test.go Outdated Show resolved Hide resolved
x/evm/precompile/wasm_test.go Outdated Show resolved Hide resolved
x/evm/precompile/wasm_test.go Outdated Show resolved Hide resolved
x/evm/precompile/wasm_test.go Outdated Show resolved Hide resolved
x/evm/precompile/wasm.go Outdated Show resolved Hide resolved
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: 2

🧹 Outside diff range and nitpick comments (1)
x/evm/precompile/wasm_test.go (1)

324-501: Consider adding edge cases to the test suite

While the current test coverage is good, consider adding these edge cases:

  1. Maximum message batch size validation
  2. Empty message batch validation
  3. Duplicate contract calls within the same batch
  4. Gas limit exhaustion scenarios
🧰 Tools
🪛 GitHub Check: unit-tests

[failure] 334-334:
undefined: SetupWasmContracts


[failure] 442-442:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 463-463:
undefined: SetupWasmContracts


[failure] 467-467:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)


[failure] 490-490:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 500-500:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)

🪛 GitHub Check: lint

[failure] 334-334:
undefined: SetupWasmContracts


[failure] 442-442:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 463-463:
undefined: SetupWasmContracts


[failure] 467-467:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)


[failure] 490-490:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 500-500:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState) (typecheck)

🪛 GitHub Check: integration-tests

[failure] 334-334:
undefined: SetupWasmContracts


[failure] 442-442:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 463-463:
undefined: SetupWasmContracts


[failure] 467-467:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)


[failure] 490-490:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 500-500:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5174c5e and 4985ff6.

📒 Files selected for processing (3)
  • CHANGELOG.md (1 hunks)
  • x/evm/precompile/wasm.go (2 hunks)
  • x/evm/precompile/wasm_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.md
🧰 Additional context used
🪛 GitHub Check: unit-tests
x/evm/precompile/wasm_test.go

[failure] 334-334:
undefined: SetupWasmContracts


[failure] 442-442:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 463-463:
undefined: SetupWasmContracts


[failure] 467-467:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)


[failure] 490-490:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 500-500:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)

🪛 GitHub Check: lint
x/evm/precompile/wasm_test.go

[failure] 334-334:
undefined: SetupWasmContracts


[failure] 442-442:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 463-463:
undefined: SetupWasmContracts


[failure] 467-467:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)


[failure] 490-490:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 500-500:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState) (typecheck)

🪛 GitHub Check: integration-tests
x/evm/precompile/wasm_test.go

[failure] 334-334:
undefined: SetupWasmContracts


[failure] 442-442:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 463-463:
undefined: SetupWasmContracts


[failure] 467-467:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)


[failure] 490-490:
assignment mismatch: 2 variables but deps.EvmKeeper.CallContractWithInput returns 3 values


[failure] 500-500:
s.assertWasmCounterState undefined (type *WasmSuite has no field or method assertWasmCounterState)

🔇 Additional comments (4)
x/evm/precompile/wasm.go (3)

277-285: LGTM! Well-structured validation setup.

The validatedMsg struct design and slice pre-allocation demonstrate good practices for performance and maintainability.


286-306: Consider collecting all validation errors.

The current implementation returns on the first validation error. As suggested in the past review, collecting all validation errors before returning could provide more comprehensive feedback to the caller.


311-320: LGTM! Correct handling of execution errors.

The current implementation, which returns on the first execution error, is the right approach. This ensures atomic execution of the batch - either all messages succeed, or none of them are executed, maintaining state consistency.

Note: While collecting all validation errors (as suggested earlier) would be helpful, collecting execution errors would be inappropriate as it could lead to partial state changes.

x/evm/precompile/wasm_test.go (1)

318-322: Consider reusing the existing WasmExecuteMsg type

This type definition appears to be duplicated. A similar type already exists in the precompile package.

x/evm/precompile/wasm_test.go Outdated Show resolved Hide resolved
x/evm/precompile/wasm_test.go Outdated Show resolved Hide resolved
@Unique-Divine Unique-Divine enabled auto-merge (squash) October 30, 2024 14:03
@Unique-Divine Unique-Divine merged commit 7b7beb7 into main Oct 30, 2024
13 checks passed
@Unique-Divine Unique-Divine deleted the mat/audit-34 branch October 30, 2024 14:09
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)
x/evm/precompile/wasm.go (1)

Line range hint 279-301: Consider collecting all validation errors before execution

Currently, the function returns on the first validation error. For better UX, consider collecting all validation errors before execution, especially since this is a batch operation. This would help users fix all issues at once rather than discovering them one by one.

Here's a suggested implementation:

 var responses [][]byte
+var validationErrors []error
 
 for i, m := range wasmExecMsgs {
     wasmContract, e := sdk.AccAddressFromBech32(m.ContractAddr)
     if e != nil {
-        err = fmt.Errorf("Execute failed at index %d: %w", i, e)
-        return
+        validationErrors = append(validationErrors, fmt.Errorf("validation failed at index %d: invalid contract address: %w", i, e))
+        continue
     }
     
     msgArgsCopy := wasm.RawContractMessage(m.MsgArgs)
     if e := msgArgsCopy.ValidateBasic(); e != nil {
-        err = fmt.Errorf("Execute failed at index %d: error parsing msg args: %w", i, e)
-        return
+        validationErrors = append(validationErrors, fmt.Errorf("validation failed at index %d: invalid message args: %w", i, e))
+        continue
     }
+    
+    // Store validated messages for execution
+    validatedMsgs = append(validatedMsgs, struct {
+        contract sdk.AccAddress
+        msgArgs  []byte
+        funds    sdk.Coins
+    }{
+        contract: wasmContract,
+        msgArgs:  m.MsgArgs,
+        funds:    funds,
+    })
 }

+if len(validationErrors) > 0 {
+    return nil, fmt.Errorf("validation errors: %v", validationErrors)
+}

+// Execute all validated messages
+for i, msg := range validatedMsgs {
     var funds sdk.Coins
     for _, fund := range m.Funds {
         funds = append(funds, sdk.Coin{
             Denom:  fund.Denom,
             Amount: sdk.NewIntFromBigInt(fund.Amount),
         })
     }
     respBz, e := p.Wasm.Execute(ctx, msg.contract, callerBech32, msg.msgArgs, msg.funds)
     if e != nil {
         err = fmt.Errorf("Execute failed at index %d: %w", i, e)
         return
     }
     responses = append(responses, respBz)
 }

This approach:

  1. Collects all validation errors before execution
  2. Separates validation from execution
  3. Provides comprehensive feedback about all validation issues
  4. Maintains the current execution behavior (fail-fast on execution errors)
x/evm/precompile/wasm_test.go (2)

350-432: Consider adding test case for empty message array

The test cases are comprehensive but missing validation for an empty array of messages. This edge case should be handled explicitly.

Add this test case to the array:

 testCases := []struct {
     name        string
     executeMsgs []WasmExecuteMsg
     wantError   string
 }{
+    {
+        name:        "invalid - empty message array",
+        executeMsgs: []WasmExecuteMsg{},
+        wantError:   "empty message array",
+    },
     // ... existing test cases ...
 }

457-498: Enhance partial execution test coverage

The test effectively verifies that state remains unchanged when the second message fails, but consider adding more scenarios:

  1. First message fails
  2. Last message fails in a larger batch
  3. Middle message fails in a larger batch

This would provide more confidence in the rollback behavior across different positions in the message array.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4985ff6 and ae0f2d0.

📒 Files selected for processing (4)
  • CHANGELOG.md (1 hunks)
  • x/evm/precompile/wasm.go (3 hunks)
  • x/evm/precompile/wasm_test.go (2 hunks)
  • x/evm/statedb/statedb.go (0 hunks)
💤 Files with no reviewable changes (1)
  • x/evm/statedb/statedb.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.md
🔇 Additional comments (3)
x/evm/precompile/wasm.go (2)

13-13: LGTM: Required import for WASM message validation

The addition of the WASM types import is necessary to support the new validation feature using RawContractMessage.


279-288: LGTM: Enhanced validation for multi-message execution

The added validation improves the robustness of the system by:

  1. Validating contract addresses before execution
  2. Ensuring message arguments are properly formatted using ValidateBasic()
  3. Providing clear error messages with index information for debugging

This aligns well with the PR objectives of adding validation for multi-message execution.

x/evm/precompile/wasm_test.go (1)

324-498: Implementation looks solid! 👍

The test implementation is well-structured and provides good coverage of the multi-message execution validation:

  • Comprehensive validation scenarios
  • Clear test case organization
  • Proper error handling verification
  • State change validation

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.

3 participants