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

update simulation #470

Merged
merged 2 commits into from
Dec 19, 2024
Merged

update simulation #470

merged 2 commits into from
Dec 19, 2024

Conversation

wangjiulian
Copy link
Collaborator

@wangjiulian wangjiulian commented Dec 16, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced logic for generating pool creation fees to ensure it is always at least 1.
    • Improved handling of repeated request contexts in various simulation functions.
    • Updated token representation in genesis state to use the native token's symbol.
  • Bug Fixes

    • Added validation checks for repeated frequency based on the Repeated state in request contexts.
  • Refactor

    • Adjusted internal logic for handling repeated contexts across multiple simulation functions.

Copy link

coderabbitai bot commented Dec 16, 2024

Walkthrough

The pull request encompasses modifications across multiple modules, focusing on simulation and keeper logic. Changes include adjusting genesis state generation in the coinswap and token modules, refining request context handling in the service module's keeper and simulation operations, and introducing more nuanced logic for repeated contexts and parameter initialization. The modifications aim to enhance randomization, validation, and simulation capabilities across different components.

Changes

File Change Summary
modules/coinswap/simulation/genesis.go Updated RandomizedGenState to ensure poolCreationFee is always ≥ 1 by using r.Int63n(100)+1
modules/service/keeper/invocation.go Modified UpdateRequestContext to validate repeatedFreq only when Repeated state is true
modules/service/simulation/operations.go Enhanced simulation operations with more dynamic handling of repeated contexts and added conditional checks
modules/token/simulation/genesis.go Updated coin creation to use native token symbol instead of default bond denomination

Suggested Reviewers

  • dreamer-zq
  • mitch1024

Poem

🐰 In the realm of code, where rabbits roam free,
Simulations dance with newfound glee
Parameters tweaked, contexts refined
A hoppy journey of logic designed
Randomness blooms, with precision so bright! 🌟

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

@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

🧹 Nitpick comments (3)
modules/service/simulation/operations.go (3)

16-16: Fix import ordering using gci.

Please run gci with the following flags to maintain consistent import ordering:

gci --skip-generated -s standard -s default -s prefix(mods.irisnet.org) --custom-order
🧰 Tools
🪛 golangci-lint (1.62.2)

16-16: File is not gci-ed with --skip-generated -s standard -s default -s prefix(mods.irisnet.org) --custom-order

(gci)


993-998: Consider making repeated parameters configurable.

The current implementation uses fixed values (100 for frequency and 10 for total) when repeated is true. Consider making these values configurable or randomized for better simulation coverage.

 repeated := r.Intn(2) == 0
 var repeatedFrequency, repeatedTotal uint64
 if repeated {
-    repeatedFrequency = uint64(100)
-    repeatedTotal = uint64(10)
+    repeatedFrequency = uint64(simtypes.RandIntBetween(r, 50, 150))
+    repeatedTotal = uint64(simtypes.RandIntBetween(r, 5, 15))
 }

1499-1499: Fix comment formatting.

Add a space after // for consistent comment formatting.

-//if requestContext.Repeated {
+// if requestContext.Repeated {
🧰 Tools
🪛 golangci-lint (1.62.2)

1499-1499: commentFormatting: put a space between // and comment text

(gocritic)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1380d52 and 885e3be.

📒 Files selected for processing (4)
  • modules/coinswap/simulation/genesis.go (1 hunks)
  • modules/service/keeper/invocation.go (1 hunks)
  • modules/service/simulation/operations.go (4 hunks)
  • modules/token/simulation/genesis.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
modules/service/simulation/operations.go

16-16: File is not gci-ed with --skip-generated -s standard -s default -s prefix(mods.irisnet.org) --custom-order

(gci)


1499-1499: commentFormatting: put a space between // and comment text

(gocritic)

🔇 Additional comments (5)
modules/coinswap/simulation/genesis.go (1)

42-42: LGTM: Non-zero pool creation fee ensures valid simulation state.

The change ensures that poolCreationFee is always at least 1 by using r.Int63n(100)+1 instead of just r.Int63n(100). This is a good defensive programming practice that prevents potential issues with zero fees in simulations.

✅ Verification successful

Let me generate additional verification scripts to check the usage of pool creation fee in the actual code logic, not just in type definitions.


Let me try one more verification with a different approach to check the simulation and validation logic.


LGTM: Non-zero pool creation fee is validated and properly handled

The change to ensure non-zero pool creation fee is well-justified based on the codebase evidence:

  1. The Params.Validate() method in modules/coinswap/types/params.go explicitly requires positive pool creation fee:
if !p.PoolCreationFee.IsPositive() {
    return fmt.Errorf("poolCreationFee must be positive: %s", p.PoolCreationFee.String())
}
  1. The fee is actively used in business logic:
    • DeductPoolCreationFee in both coinswap and farm modules uses it for fee collection
    • It's used for tax calculations and burning mechanisms
    • The simulation operations check for sufficient balance against this fee

The simulation change to use r.Int63n(100)+1 aligns with these validation requirements and prevents potential simulation failures.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify that pool creation fee is used consistently across the codebase
rg -A 3 "pool.*creation.*fee" --type go

Length of output: 10876


Script:

#!/bin/bash
# Check for pool creation fee validation or usage in business logic
ast-grep --pattern 'func $$$($$$) {
  $$$
  pool.*creation.*fee
  $$$
}'

# Also check for any direct references to pool creation fee in test files
rg "pool.*creation.*fee.*" --type go --glob "*_test.go" -A 3

Length of output: 137


Script:

#!/bin/bash
# Check for pool creation fee validation in simulation and params
rg "poolCreationFee" --type go -B 2 -A 2

# Also check for any validation functions that might handle the fee
ast-grep --pattern 'func $$$Validate($$$) error {
  $$$
}'

Length of output: 9812

modules/token/simulation/genesis.go (1)

74-74: Verify GetNativeToken() safety in simulation context.

The change from sdk.DefaultBondDenom to v1.GetNativeToken().Symbol makes the simulation more accurate by using the actual native token symbol. However, we should ensure that GetNativeToken() is safe to call in all simulation contexts.

✅ Verification successful

Let me check the initialization of the Initialized and nativeToken variables to ensure thread safety.


Let me check the initialization of these variables using ripgrep instead.


Let me try a different approach to check the variable declarations.


Based on the code review, I can now provide the final response:

GetNativeToken() is safe to use in simulation context

The implementation shows that GetNativeToken() has proper initialization handling:

  • If not initialized, it sets default values including sdk.DefaultBondDenom as the symbol
  • The initialization is guarded by a boolean flag
  • The function always returns a valid Token struct with sensible defaults
  • The default values are hardcoded and do not depend on external state
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the implementation of GetNativeToken
ast-grep --pattern 'func GetNativeToken() $_ {
  $$$
}'

Length of output: 2284


Script:

#!/bin/bash
# Check the declaration of Initialized and nativeToken variables
ast-grep --pattern 'var $_ $_'

Length of output: 65646


Script:

#!/bin/bash
# Check the initialization of Initialized and nativeToken variables
rg -A 2 "var (Initialized|nativeToken)" modules/token/types/v1/genesis.go

Length of output: 75


Script:

#!/bin/bash
# Check the content of the genesis.go file
cat modules/token/types/v1/genesis.go

Length of output: 1765

modules/service/keeper/invocation.go (1)

239-247: LGTM: Improved validation logic for repeated requests.

The change correctly adds a conditional check to validate repeatedFreq only when requestContext.Repeated is true. This fixes a potential issue where the validation was being applied incorrectly to non-repeated requests. The error message is clear and the validation logic ensures that repeated frequency is not less than the timeout, which is essential for proper request scheduling.

modules/service/simulation/operations.go (2)

1164-1172: LGTM! Proper validation for repeated request contexts.

The added check ensures that only repeated request contexts can be paused, which is the correct business logic.


1499-1502: Verify the impact of commented repeated parameters.

The commented code previously initialized repeatedFrequency and repeatedTotal based on the request context's state. Verify if setting these to 0 by default is intentional and won't cause issues.

✅ Verification successful

The previous search showed that these parameters are used in request contexts, but we need to specifically check the validation rules and handling when they are set to 0 to determine if this is intentional and safe.


Based on the validation code found, I can now provide a definitive response about the commented repeated parameters:

Setting repeated parameters to 0 is intentional and safe

The validation code in modules/service/types/validation.go and handling in modules/service/keeper/invocation.go show that:

  1. When repeated flag is false:

    • repeatedFrequency is explicitly set to 0
    • repeatedTotal is explicitly set to 0
  2. When repeated flag is true:

    • repeatedFrequency defaults to timeout value if 0
    • repeatedTotal must be either greater than 0 or equal to -1 (validated)

The commented code is safely removed since the default 0 values align with the non-repeated request context behavior.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential issues with repeated parameters being 0

# Search for references to repeatedFrequency and repeatedTotal in request context handling
rg -A 5 'repeatedFrequency|repeatedTotal' --type go

# Search for validation of these parameters
ast-grep --pattern 'if $_ <= 0 {
  $$$
}'

Length of output: 65828


Script:

#!/bin/bash
# Search for validation and handling of repeated parameters
rg -A 5 'repeatedFrequency|repeatedTotal' --type go modules/service/types/validation.go modules/service/keeper/invocation.go

# Search for any tests related to repeated parameters
rg -A 5 'repeatedFrequency.*0|repeatedTotal.*0' --type go modules/service/simulation/operations_test.go modules/service/keeper/invocation_test.go

Length of output: 6764

🧰 Tools
🪛 golangci-lint (1.62.2)

1499-1499: commentFormatting: put a space between // and comment text

(gocritic)

Copy link

@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

🧹 Nitpick comments (2)
modules/service/simulation/operations.go (2)

16-16: Sort imports to comply with project's import conventions

The file is not formatted according to the gci import sorting tool. Please sort the imports to adhere to the project's conventions.

🧰 Tools
🪛 golangci-lint (1.62.2)

16-16: File is not gci-ed with --skip-generated -s standard -s default -s prefix(mods.irisnet.org) --custom-order

(gci)


1165-1172: Improve error message for clarity

The error message "requestContext non repeated" could be clearer if phrased as "request context is not repeated".

Apply this diff to improve the error message:

 if !requestContext.Repeated {
 	return simtypes.NoOpMsg(
 		types.ModuleName,
 		types.TypeMsgPauseRequestContext,
-		"requestContext non repeated",
+		"request context is not repeated",
 	), nil, nil
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 885e3be and 0ad41be.

📒 Files selected for processing (2)
  • modules/service/keeper/invocation.go (1 hunks)
  • modules/service/simulation/operations.go (3 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
modules/service/simulation/operations.go

16-16: File is not gci-ed with --skip-generated -s standard -s default -s prefix(mods.irisnet.org) --custom-order

(gci)

🔇 Additional comments (2)
modules/service/keeper/invocation.go (1)

Line range hint 239-244: Ensure consistent use of requestContext.Timeout in condition and error message

The condition compares repeatedFreq with uint64(timeout), while the error message refers to requestContext.Timeout. To avoid inconsistencies, consider using requestContext.Timeout in both the condition and the error message.

Apply this diff to fix the inconsistency:

-	if requestContext.Repeated && repeatedFreq < uint64(timeout) {
+	if requestContext.Repeated && repeatedFreq < uint64(requestContext.Timeout) {
 		return errorsmod.Wrapf(
 			types.ErrInvalidRepeatedFreq,
 			"repeated frequency [%d] must not be less than the timeout [%d]",
 			repeatedFreq,
-			requestContext.Timeout,
+			requestContext.Timeout,
 		)
 	}
modules/service/simulation/operations.go (1)

993-998: ⚠️ Potential issue

Ensure repeatedFrequency is not less than timeout to prevent validation errors

Currently, repeatedFrequency is set to 100, but timeout can be up to k.MaxRequestTimeout(ctx). If timeout exceeds 100, this will cause a validation error because repeatedFrequency must not be less than timeout. To avoid this issue, consider setting repeatedFrequency to be greater than or equal to timeout when repeated is true.

Apply this diff to fix the issue:

 if repeated {
-		repeatedFrequency = uint64(100)
+		repeatedFrequency = uint64(timeout)
 		repeatedTotal = uint64(10)
 	}

Likely invalid or redundant comment.

@mitch1024 mitch1024 merged commit 96f998e into main Dec 19, 2024
7 checks passed
@mitch1024 mitch1024 deleted the feature/up_simulate branch December 19, 2024 09:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants