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

Chore(hardhat)/hardhat ether version update #1620

Open
wants to merge 18 commits into
base: dev
Choose a base branch
from

Conversation

Anmol-Dhiman
Copy link
Contributor

@Anmol-Dhiman Anmol-Dhiman commented Jun 19, 2024

PR-Codex overview

This PR updates various parts of the codebase to use ethers v6, fix styling in components, and improve contract deployment scripts.

Detailed summary

  • Updated ethers imports and usage to version 6.
  • Fixed styling in Timestamp component.
  • Refactored contract deployment scripts for consistency and efficiency.

The following files were skipped due to too many changes: contracts/deploy/utils/getContractOrDeploy.ts, contracts/deploy/utils/deployTokens.ts, contracts/deploy/01-foreign-gateway-on-ethereum.ts, contracts/deploy/upgrade-kleros-core.ts, contracts/deploy/fix1148.ts, contracts/deploy/03-vea-mock.ts, contracts/deploy/01-foreign-gateway-on-gnosis.ts, contracts/test/proxy/index.ts, contracts/deploy/00-home-chain-arbitration.ts, contracts/test/rng/index.ts, contracts/scripts/simulations/utils.ts, contracts/deploy/00-home-chain-arbitration-neo.ts, contracts/deploy/00-home-chain-arbitration-university.ts, contracts/scripts/populateCourts.ts, contracts/test/arbitration/index.ts, contracts/test/integration/index.ts, contracts/test/evidence/index.ts, contracts/test/arbitration/staking.ts, contracts/scripts/simulations/tasks.ts, contracts/test/arbitration/draw.ts, contracts/scripts/keeperBot.ts, contracts/test/arbitration/staking-neo.ts, yarn.lock

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • Refactor

    • Updated various scripts and deployment files to replace AddressZero with ZeroAddress for consistency.
    • Modified import statements and function calls to improve code clarity and alignment with the latest ethers library version.
    • Enhanced event handling and logging mechanisms across deployment scripts.
  • Chores

    • Updated dependencies in package.json to their latest versions for better performance and security.
    • Adjusted test command specification in GitHub Actions workflow for contracts testing.

Copy link
Contributor

coderabbitai bot commented Jun 19, 2024

Walkthrough

The changes involve updating multiple deployment and utility scripts to align with the newer versions of Hardhat and Ethers.js libraries. This includes adjustments to import statements, function calls, and variable assignments to be compatible with the breaking changes introduced in Ethers v6. Various parts of the deployment workflow have been modified to address these updates while ensuring the functionality and integration tests, especially related to Solidity coverage, continue to work correctly.

Changes

Files/Directories Change Summaries
All Deploy Scripts Replaced AddressZero with ZeroAddress, updated function call arguments, and modified import statements for updated ethers functions.
.../00-home-chain-arbitration-neo.ts Updated variable assignments, function arguments, and imports to use new Ethers methodology.
.../00-home-chain-arbitration-university.ts Similar updates as above for specific use cases and arguments.
.../00-home-chain-arbitration.ts Applied relevant updates to argument handling and function calls.
.../00-home-chain-pnk-faucet.ts Modified usage of parseUnits function to align with new ethers structure.
.../01-foreign-gateway-on-ethereum.ts Updated import and function call patterns, renamed certain imports.
.../01-foreign-gateway-on-gnosis.ts Changed import statements, adjusted usage of BigNumber and function calls.
.../02-home-gateway-to-ethereum.ts Replaced AddressZero with ZeroAddress in specific deployment steps.
.../03-vea-mock.ts Updated import and variable usage to match the new ethers utilities.
.../04-foreign-arbitrable.ts Adjusted imports for parseUnits and BigNumber; updated function usages accordingly.
.../04-klerosliquid-to-v2-gnosis.ts Modified import patterns; updated constant definitions involving BigNumber.
.../05-arbitrable-dispute-template.ts Added EventLog import and modified event handling logic in deployment process.
.../fix1148.ts Updated function arguments and variable initializations to use ZeroAddress and new ethers methods.
.../upgrade-kleros-core.ts Replaced BigNumber with toBigInt in certain calculations; updated variable usage.
.../utils/deployTokens.ts Modified imports, parameter types, and variable usage to new ethers methods.
.../utils/getContractOrDeploy.ts Refined contract retrieval and deployment logic; updated to new ethers import.
.../utils/index.ts Replaced parseUnits function usage to align with new ether structure.
.../utils/klerosCoreHelper.ts Included toBigInt import and altered some conditional statements.
.../package.json Updated various package versions to latest releases compatible with Ethers v6.
.../scripts/deploy.ts Changed deployment transaction handling and logging statement adjustments.
.../scripts/disputeCreatorBot.ts Updated function calls and event handling logic.
.../scripts/getCourtsV1.ts Replaced AddressZero with ZeroAddress and updated number extraction methods.
.../scripts/getPoliciesV1.ts Updated constant declaration to use ZeroAddress from ethers.
.../scripts/keeperBot.ts Modified imports and function call methodologies to adapt new ethers standards.
.github/.../contracts-testing.yml Adjusted test command syntax within contracts testing workflow script.

Possibly related issues

  • Upgrade hardhat, hardhat-deploy, ethers #1606: The updates align with the request to upgrade Hardhat-related packages and ensure compatibility with Ethers v6, addressing breaking changes in ./contracts/deploy and ./contracts/scripts.

Poem

In the land of code so bright,
Packages evolved to newer might,
Ethers v6 brings subtle cheer,
Hardhat's updates make it clear,
Scripts now dance to a brand new tune,
Keeping bugs far at bay, like the moon,
CodeRabbit cheers, "Deploy and test away!" 🌕🌟


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

netlify bot commented Jun 19, 2024

Deploy Preview for kleros-v2-neo failed. Why did it fail? →

Name Link
🔨 Latest commit b1e4632
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-neo/deploys/667bbf0aa886b1000804f661

Copy link

netlify bot commented Jun 19, 2024

Deploy Preview for kleros-v2 failed. Why did it fail? →

Name Link
🔨 Latest commit b1e4632
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2/deploys/667bbf0a0637900008fc1571

Copy link

netlify bot commented Jun 19, 2024

Deploy Preview for kleros-v2-university failed. Why did it fail? →

Name Link
🔨 Latest commit b1e4632
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-university/deploys/667bbf0a5527b90008cf19e0

@Anmol-Dhiman Anmol-Dhiman self-assigned this Jun 19, 2024
@Anmol-Dhiman Anmol-Dhiman linked an issue Jun 19, 2024 that may be closed by this pull request
@Anmol-Dhiman Anmol-Dhiman marked this pull request as draft June 19, 2024 11:00
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: 13

Outside diff range and nitpick comments (4)
contracts/deploy/utils/index.ts (1)

Line range hint 13-13: Correct enum initialization.

Enum members should be initialized with literal values. Current initialization might cause confusion or unexpected behavior during runtime.

- export enum HardhatChain {
-   HARDHAT = 31337,
- }
+ export enum HardhatChain {
+   HARDHAT = "31337",
+ }

- export enum ForeignChains {
-   GNOSIS_MAINNET = 100,
-   GNOSIS_CHIADO = 10200,
- }
+ export enum ForeignChains {
+   GNOSIS_MAINNET = "100",
+   GNOSIS_CHIADO = "10200",
+ }

Also applies to: 21-21

contracts/scripts/populateCourts.ts (1)

Line range hint 186-206: Ensure proper condition checks in parameter updates

The conditions for updating court parameters seem to have a logical error. Use direct comparison instead of negation for clarity and correctness.

- if (!courtPresent.minStake === court.minStake) {
+ if (courtPresent.minStake !== court.minStake) {
- if (!courtPresent.alpha === court.alpha) {
+ if (courtPresent.alpha !== court.alpha) {
- if (!courtPresent.feeForJuror === court.feeForJuror) {
+ if (courtPresent.feeForJuror !== court.feeForJuror) {
- if (!courtPresent.jurorsForCourtJump === court.jurorsForCourtJump) {
+ if (courtPresent.jurorsForCourtJump !== court.jurorsForCourtJump) {
contracts/scripts/simulations/tasks.ts (1)

Line range hint 308-320: Validate the appealchoice parameter for fundAppeal.

The appealchoice is being used as a number, but there is no validation to check if it is within the expected range (0 or 1). Adding a check can prevent incorrect values from being used, which might lead to errors in the contract calls.

+ if (![0, 1].includes(appealchoice)) {
+   throw new Error('Invalid appeal choice. Must be 0 or 1.');
+ }
contracts/scripts/keeperBot.ts (1)

Line range hint 156-166: Refactor to simplify the RNG status check logic.

The else clauses in the RNG readiness checks are unnecessary because each if and else if block ends with a return statement. Removing these else clauses can simplify the code and enhance readability.

-  } else {
+  }
-  } else {
+  }

Also applies to: 169-180

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3da67bd and b558f6e.

Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
Files selected for processing (30)
  • contracts/deploy/00-home-chain-arbitration-neo.ts (6 hunks)
  • contracts/deploy/00-home-chain-arbitration-university.ts (6 hunks)
  • contracts/deploy/00-home-chain-arbitration.ts (5 hunks)
  • contracts/deploy/00-home-chain-pnk-faucet.ts (2 hunks)
  • contracts/deploy/01-foreign-gateway-on-ethereum.ts (3 hunks)
  • contracts/deploy/01-foreign-gateway-on-gnosis.ts (3 hunks)
  • contracts/deploy/02-home-gateway-to-ethereum.ts (1 hunks)
  • contracts/deploy/03-vea-mock.ts (4 hunks)
  • contracts/deploy/04-foreign-arbitrable.ts (3 hunks)
  • contracts/deploy/04-klerosliquid-to-v2-gnosis.ts (2 hunks)
  • contracts/deploy/05-arbitrable-dispute-template.ts (2 hunks)
  • contracts/deploy/fix1148.ts (2 hunks)
  • contracts/deploy/upgrade-kleros-core.ts (3 hunks)
  • contracts/deploy/utils/deployTokens.ts (2 hunks)
  • contracts/deploy/utils/getContractOrDeploy.ts (2 hunks)
  • contracts/deploy/utils/index.ts (1 hunks)
  • contracts/deploy/utils/klerosCoreHelper.ts (2 hunks)
  • contracts/package.json (2 hunks)
  • contracts/scripts/deploy.ts (1 hunks)
  • contracts/scripts/disputeCreatorBot.ts (3 hunks)
  • contracts/scripts/getCourtsV1.ts (3 hunks)
  • contracts/scripts/getPoliciesV1.ts (1 hunks)
  • contracts/scripts/keeperBot.ts (20 hunks)
  • contracts/scripts/populateCourts.ts (7 hunks)
  • contracts/scripts/simulations/tasks.ts (22 hunks)
  • contracts/scripts/simulations/utils.ts (6 hunks)
  • contracts/scripts/viemTest.ts (1 hunks)
  • contracts/src/arbitration/arbitrables/ArbitrableExample.sol (1 hunks)
  • contracts/test/rng/index.ts (1 hunks)
  • web/src/components/EvidenceCard.tsx (2 hunks)
Files not reviewed due to errors (1)
  • contracts/deploy/upgrade-kleros-core.ts (no review received)
Files skipped from review due to trivial changes (4)
  • contracts/deploy/00-home-chain-arbitration.ts
  • contracts/deploy/fix1148.ts
  • contracts/scripts/viemTest.ts
  • web/src/components/EvidenceCard.tsx
Additional context used
Biome
contracts/deploy/utils/index.ts

[error] 13-13: The enum member should be initialized with a literal value such as a number or a string. (lint/style/useLiteralEnumMembers)


[error] 21-21: The enum member should be initialized with a literal value such as a number or a string. (lint/style/useLiteralEnumMembers)

contracts/scripts/simulations/utils.ts

[error] 66-69: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 85-87: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 92-92: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 102-102: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.

contracts/scripts/populateCourts.ts

[error] 73-75: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.

contracts/scripts/keeperBot.ts

[error] 162-165: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 166-180: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 173-176: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 177-180: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)


[error] 567-567: Shouldn't redeclare 'dispute'. Consider to delete it or rename it. (lint/suspicious/noRedeclare)

'dispute' is defined here:


[error] 592-592: Shouldn't redeclare 'dispute'. Consider to delete it or rename it. (lint/suspicious/noRedeclare)

'dispute' is defined here:

Additional comments not posted (62)
contracts/deploy/utils/klerosCoreHelper.ts (2)

2-2: Update to modern type imports and usage.

The use of BigNumberish and toBigInt from ethers is appropriate and aligns with the updated standards for handling numeric types in Solidity and JavaScript interoperation.


16-16: Ensure correctness in comparison and type conversion.

The comparison pnkRate.rateInEth === toBigInt(rateInEth) might lead to unexpected behavior if pnkRate.rateInEth is not already a BigInt. Consider verifying the type before comparison or ensuring that both sides of the comparison are of the same type.

contracts/scripts/deploy.ts (2)

20-20: Ensure proper use of deploymentTransaction.

The use of deploymentTransaction() is correct as per the PR's objectives. Ensure that this method is adequately documented in the project's documentation to avoid confusion with the previously used deployed().


22-22: Verify the property for deployment address.

The target property used in the log statement is not standard for Ethers.js Contract objects. Typically, the address is accessed via address. Verify if target is a custom implementation specific to this project.

contracts/deploy/utils/getContractOrDeploy.ts (1)

4-4: Good use of type generics and error handling.

The use of generics with getContractOrNull<Contract> and proper logging in case of deployment or retrieval issues is a good practice. This ensures type safety and provides clear debug information during the deployment process.
[APROVED]

Also applies to: 10-10, 14-14, 26-26, 30-30

contracts/deploy/00-home-chain-pnk-faucet.ts (1)

Line range hint 11-27: Consistency Check Recommended for Token Amounts

The updated usage of parseUnits for defining token amounts in deployment scripts is noted. Please ensure that similar changes are consistently applied across all relevant deployment scripts to maintain uniformity.

Verification successful

Consistency Check Recommended for Token Amounts

The updated usage of parseUnits for defining token amounts in deployment scripts is noted. The verification script confirmed that parseUnits is consistently used across the deployment scripts.

  • contracts/deploy/04-klerosliquid-to-v2-gnosis.ts
  • contracts/deploy/04-foreign-arbitrable.ts
  • contracts/deploy/01-foreign-gateway-on-gnosis.ts
  • contracts/deploy/00-home-chain-pnk-faucet.ts
  • contracts/deploy/utils/index.ts
  • contracts/deploy/utils/deployTokens.ts
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify consistent usage of `parseUnits` across all deployment scripts.
# Test: Search for inconsistent usage of `parseUnits`. Expect: No occurrences of old method.
rg --type python "parseUnits" "contracts/deploy/"

Length of output: 78



Script:

#!/bin/bash
# Description: Verify consistent usage of `parseUnits` across all deployment scripts.
# Test: Search for inconsistent usage of `parseUnits`. Expect: No occurrences of old method.
rg --type typescript "parseUnits" "contracts/deploy/"

Length of output: 86



Script:

#!/bin/bash
# Description: Verify consistent usage of `parseUnits` across all deployment scripts.
# Test: Search for inconsistent usage of `parseUnits`. Expect: No occurrences of old method.
rg --type ts "parseUnits" "contracts/deploy/"

Length of output: 1080

contracts/scripts/getPoliciesV1.ts (1)

21-21: Standardization of Zero Address Usage

The replacement of AddressZero with ZeroAddress is noted and aligns with the PR's goal of updating constants for better consistency. Ensure that this change is uniformly applied in all scripts where applicable.

Verification successful

Standardization of Zero Address Usage Verified

The replacement of AddressZero with ZeroAddress has been uniformly applied across all scripts.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify uniform application of `ZeroAddress` across all scripts.
# Test: Search for old `AddressZero`. Expect: No occurrences.
rg --type python "AddressZero" "contracts/scripts/"

Length of output: 80



Script:

#!/bin/bash
# Description: Verify uniform application of `ZeroAddress` across all scripts.
# Test: Search for old `AddressZero`. Expect: No occurrences.
rg --type ts "AddressZero" "contracts/scripts/"

Length of output: 45

contracts/deploy/05-arbitrable-dispute-template.ts (1)

4-4: Good Practice: Import and Usage of EventLog

The import of EventLog and its use in log handling is a positive change, enhancing readability and maintainability of event processing. Verify that EventLog is appropriately used in all places where event logs are processed.

Also applies to: 36-37

Verification successful

The search results confirm that EventLog is imported and used correctly for type checking in the identified file.

  • import { EventLog } from "ethers";
  • if (event instanceof EventLog) console.log("event: %O", event.args);

This indicates that EventLog is being used properly to handle event logs.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify correct usage of `EventLog` in event handling across the deployment scripts.
# Test: Search for event handling without `EventLog`. Expect: No occurrences.
rg --type python "logs" "contracts/deploy/"

Length of output: 72



Script:

#!/bin/bash
# Description: Verify correct usage of `EventLog` in event handling across the deployment scripts.
# Test: Search for event handling without `EventLog`. Expect: No occurrences.
rg --type typescript "logs" "contracts/deploy/"

Length of output: 80



Script:

#!/bin/bash
# Description: Verify correct usage of `EventLog` in event handling across the deployment scripts.
# Test: Search for event handling without `EventLog`. Expect: No occurrences.
rg "logs" "contracts/deploy/" --glob "*.ts"

Length of output: 125



Script:

#!/bin/bash
# Description: Verify correct usage of `EventLog` in `contracts/deploy/05-arbitrable-dispute-template.ts`.
# Test: Search for `EventLog` usage in the identified file.
rg "EventLog" "contracts/deploy/05-arbitrable-dispute-template.ts"

Length of output: 172

contracts/test/rng/index.ts (1)

3-3: Enhanced Handling of Large Numbers with toBigInt

The introduction of toBigInt and its usage in test assertions is a significant improvement for handling large numbers, aligning with the PR's objectives. Ensure that tests effectively cover scenarios involving large number operations.

Also applies to: 8-8, 17-23, 36-43

Verification successful

Enhanced Handling of Large Numbers with toBigInt

The introduction of toBigInt and its usage in test assertions is a significant improvement for handling large numbers, aligning with the PR's objectives. The search results confirm that toBigInt is used effectively in the test file contracts/test/rng/index.ts. Ensure that tests effectively cover scenarios involving large number operations.

  • contracts/test/rng/index.ts: Usage of toBigInt confirmed.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify effective handling of large numbers in tests.
# Test: Search for tests handling large numbers without `toBigInt`. Expect: No occurrences.
rg --type python "BigInt" "contracts/test/"

Length of output: 72



Script:

#!/bin/bash
# Description: Verify effective handling of large numbers in tests.
# Test: Search for tests handling large numbers without `toBigInt`. Expect: No occurrences.
rg --type ts "BigInt" "contracts/test/"

Length of output: 191

contracts/deploy/02-home-gateway-to-ethereum.ts (1)

35-35: Good use of ethers.ZeroAddress for clarity.

The replacement of ethers.constants.AddressZero with ethers.ZeroAddress is a good practice for clarity and consistency in referencing the zero address in smart contracts.

contracts/scripts/getCourtsV1.ts (2)

40-40: Updated usage of ZeroAddress.

Replacing hre.ethers.constants.AddressZero with hre.ethers.ZeroAddress aligns with the PR's objectives to standardize the use of the zero address across the codebase.


61-61: Map function usage on BigNumber array.

Ensure that the mapping function correctly handles the conversion from BigNumber to number, as direct mapping may lead to errors or unexpected behavior.

contracts/deploy/utils/deployTokens.ts (4)

11-11: Proper use of bigint for handling large numbers.

Using bigint for faucetFundingAmount is appropriate given the context of handling potentially large numbers in token operations.


38-38: Consistent use of bigint in function arguments.

Maintaining the use of bigint for faucetFundingAmount in function arguments ensures consistency and prevents type mismatches.


52-52: Logic to fund the faucet.

The logic to fund the faucet based on the balance conditions is correctly implemented. However, ensure that the division operation on bigint is handled correctly in JavaScript.


43-43: Check the usage of .target property.

The use of .target property on erc20 object is unusual. Please verify if this is a valid property of the erc20 contract or if it should be .address.

contracts/deploy/04-foreign-arbitrable.ts (2)

3-3: Update: Import simplification for parseUnits.

The import statement for parseUnits has been simplified from ethers/lib/utils to just ethers, which is more concise and aligns with the latest best practices following the ethers library update.


15-15: Refactor: Use BigNumber.from for constants.

The definition of ONE_GWEI now uses BigNumber.from(parseUnits("1", "gwei")), which is a more explicit and type-safe way of defining constants in the context of Ethereum transactions. This change ensures better handling of big number operations, aligning with the latest ethers library practices.

contracts/deploy/01-foreign-gateway-on-ethereum.ts (4)

10-10: Refactor: Simplified deployment logic.

The removal of deploy from the destructured deployments object indicates a shift towards using execute for deployment transactions, which aligns with the updated deployment strategy in the codebase.


11-11: Addition: New utility functions for byte manipulation.

The introduction of zeroPadValue and toBeHex functions from the ethers library is intended to handle byte manipulation more efficiently, particularly useful in blockchain contexts where data often needs to be in specific byte-aligned formats.


22-22: Update: Standardized provider instantiation.

Using ethers.JsonRpcProvider directly with the network URL standardizes the way network providers are instantiated across different deployment scripts, ensuring consistency and reducing the risk of errors in network interactions.


32-32: Refactor: Improved byte handling for chain IDs.

The use of zeroPadValue to handle the chain ID as a byte32 value is crucial for interactions with smart contracts that expect fixed-length byte arrays. This change ensures that the data is correctly formatted for such interactions.

contracts/deploy/01-foreign-gateway-on-gnosis.ts (5)

1-1: Update: Import simplification for parseUnits.

The import statement for parseUnits has been simplified from the specific module to just ethers, which is consistent with the latest best practices and simplifies the codebase.


10-10: Refactor: Use BigNumber.from for constants.

The definition of ONE_GWEI now uses BigNumber.from(parseUnits("1", "gwei")), ensuring type safety and clarity in how constants are defined, particularly for gas pricing in Ethereum-based transactions.


15-15: Addition: New utility functions for byte manipulation.

The introduction of zeroPadValue and toBeHex functions from the ethers library is intended to handle byte manipulation more efficiently, particularly useful in blockchain contexts where data often needs to be in specific byte-aligned formats.


26-26: Update: Standardized provider instantiation.

Using ethers.JsonRpcProvider directly with the network URL standardizes the way network providers are instantiated across different deployment scripts, ensuring consistency and reducing the risk of errors in network interactions.


36-36: Refactor: Improved byte handling for chain IDs.

The use of zeroPadValue to handle the chain ID as a byte32 value is crucial for interactions with smart contracts that expect fixed-length byte arrays. This change ensures that the data is correctly formatted for such interactions.

contracts/deploy/03-vea-mock.ts (2)

14-14: Update: Addition of utility functions for byte manipulation.

The introduction of zeroPadValue and toBeHex functions from the ethers library is intended to handle byte manipulation more efficiently, particularly useful in blockchain contexts where data often needs to be in specific byte-aligned formats.


32-32: Refactor: Improved byte handling for chain IDs.

The use of zeroPadValue to handle the chain ID as a byte32 value is crucial for interactions with smart contracts that expect fixed-length byte arrays. This change ensures that the data is correctly formatted for such interactions.

contracts/deploy/00-home-chain-arbitration-university.ts (4)

14-14: Updated constant for zero address

The change from AddressZero to ZeroAddress follows the updated naming convention in the ethers library, enhancing consistency with the library's standards.


28-28: Ensure correct usage of ZeroAddress in deployment arguments

The replacement of AddressZero with ZeroAddress in deployment arguments is correct and aligns with the updated ethers library. However, ensure that ZeroAddress is appropriately handled in all contexts where it's used, particularly in functions expecting a non-null address.


53-54: Review initialization parameters for consistency

The use of ZeroAddress for the uninitialized address parameter is standard practice, but it's crucial to confirm that this aligns with the contract's expectations, especially in terms of security and functionality.

Verification successful

The search results indicate that ZeroAddress is defined and used in several places within the codebase, including the file contracts/deploy/00-home-chain-arbitration-university.ts. Specifically, it is imported from hre.ethers and used as an argument in contract initializations.

  • contracts/deploy/00-home-chain-arbitration-university.ts:
    • Line 53: args: [deployer, ZeroAddress],
    • Line 54: ZeroAddress,

Given that ZeroAddress is consistently used across multiple deployment scripts and is imported from hre.ethers, it aligns with the standard practice of using a zero address for uninitialized parameters. This indicates that its usage is consistent and likely aligns with the contract's expectations for security and functionality.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that ZeroAddress is correctly used in contract initializations.

# Test: Search for contract initializations using ZeroAddress and review their handling.
ast-grep --lang solidity --pattern $'contract $_ {
  constructor($_, $_, ZeroAddress) {
    $$$
  }
  $$$
}'

Length of output: 226



Script:

#!/bin/bash
# Description: Verify that ZeroAddress is correctly used in contract initializations.

# Test: Search for contract initializations using ZeroAddress and review their handling.
rg 'constructor\([^)]*ZeroAddress[^)]*\)' -t solidity

Length of output: 88



Script:

#!/bin/bash
# Description: Verify that ZeroAddress is correctly used in contract initializations.

# Test: Search for contract initializations using ZeroAddress in Solidity files.
rg 'constructor\([^)]*ZeroAddress[^)]*\)' --glob '*.sol'

Length of output: 58



Script:

#!/bin/bash
# Description: Verify that ZeroAddress is correctly used in the codebase.

# Test: Search for any usage of ZeroAddress in Solidity files.
rg 'ZeroAddress' --glob '*.sol'

Length of output: 31



Script:

#!/bin/bash
# Description: Search for the definition or declaration of ZeroAddress in the codebase.

# Test: Search for the definition or declaration of ZeroAddress.
rg 'ZeroAddress'

Length of output: 1713


90-90: Verify correct parameter passing in deployment function

The deployment function's arguments are correctly structured. Ensure that the core.target and disputeTemplateRegistry.target are valid and that the contract addresses are correctly fetched and used.

Verification successful

The verification process confirms that the core and disputeTemplateRegistry variables are correctly defined and assigned contract addresses in the codebase. Specifically:

  • core is assigned using ethers.getContract or KlerosCore__factory.connect to fetch the contract address.
  • disputeTemplateRegistry is assigned using getContractOrDeployUpgradable or deployUpgradable to fetch or deploy the contract.

These definitions ensure that the contract addresses passed to the deployment function are valid.

  • contracts/deploy/00-home-chain-arbitration-university.ts
  • contracts/deploy/00-home-chain-arbitration-neo.ts
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the validity of contract addresses used in deployment arguments.

# Test: Check that the contract addresses passed to deployment functions are valid.
rg --type python $'deploy("DisputeResolverUniversity", {args: [core.target, disputeTemplateRegistry.target]})'

Length of output: 321



Script:

#!/bin/bash
# Description: Verify the validity of contract addresses used in deployment arguments.

# Test: Check that the contract addresses passed to deployment functions are valid.
rg --type js 'deploy("DisputeResolverUniversity", {args: \[core.target, disputeTemplateRegistry.target\]})'

Length of output: 321



Script:

#!/bin/bash
# Description: Verify the validity of contract addresses used in deployment arguments.

# Test: Check that the contract addresses passed to deployment functions are valid.
rg --type ts 'deploy("DisputeResolverUniversity", {args: [core.target, disputeTemplateRegistry.target]})'

Length of output: 317



Script:

#!/bin/bash
# Description: Verify the validity of contract addresses used in deployment arguments.

# Test: Check that the contract addresses passed to deployment functions are valid.
rg --type ts 'deploy("DisputeResolverUniversity", {args: [core.target, disputeTemplateRegistry.target]})'

Length of output: 317


Script:

#!/bin/bash
# Description: Verify the existence of core.target and disputeTemplateRegistry.target in the codebase.

# Test: Search for the definitions of core.target and disputeTemplateRegistry.target.
rg --type ts 'core.target'
rg --type ts 'disputeTemplateRegistry.target'

Length of output: 514



Script:

#!/bin/bash
# Description: Verify the definitions of core and disputeTemplateRegistry to ensure they are valid contract addresses.

# Test: Search for the definitions of core and disputeTemplateRegistry.
rg --type ts 'const core =' 
rg --type ts 'const disputeTemplateRegistry =' 

Length of output: 2256

contracts/package.json (5)

64-65: Updated dependencies for Hardhat and Ethers

The updates to @nomicfoundation/hardhat-ethers and @nomicfoundation/hardhat-chai-matchers are aligned with the changes in the Hardhat environment, which should help in maintaining compatibility and leveraging new features.


68-69: TypeChain and Ethers library updates

The update to @typechain/ethers-v6 is crucial for ensuring compatibility with the latest version of ethers, which has been updated to 6.10.0. This ensures that generated type bindings are accurate and up-to-date.


81-81: Updated Hardhat version

The update to Hardhat version 2.19.0 introduces new features and potentially breaking changes. It's important to run integration tests to ensure that existing deployment scripts and tasks are still functioning as expected.


78-78: Significant version update for Ethers

Updating ethers to version 6.10.0 is a major change that impacts how the library is used throughout the project. Ensure that all uses of ethers are tested to confirm compatibility with the new version.


83-84: Updated Hardhat deployment plugins

The updates to hardhat-deploy and hardhat-deploy-ethers are important for maintaining compatibility and optimizing deployment scripts. Confirm that these plugins are correctly configured and that deployments are functioning as expected.

contracts/deploy/04-klerosliquid-to-v2-gnosis.ts (4)

1-1: Updated import paths for parseUnits and parseEther

The direct import from ethers instead of ethers/lib/utils simplifies the import paths and aligns with the latest library standards. This is a good practice for maintaining code clarity and reducing potential issues with path resolution.


6-6: Explicit import of BigNumber from @ethersproject/bignumber

Importing BigNumber directly from @ethersproject/bignumber ensures that the correct version is used, which is crucial for consistency and avoiding potential conflicts with multiple versions of the same class.


12-12: Correct usage of BigNumber.from for unit conversion

The use of BigNumber.from to wrap the result of parseUnits is correct and ensures that the value is treated as a BigNumber, which is necessary for accurate calculations and method calls expecting a BigNumber type.


44-44: Ensure ZeroAddress is appropriately used

The use of ZeroAddress for the RNG address in the deployment script should be double-checked to ensure it is intended and that the contract handles it correctly, especially in scenarios where a valid address is expected.

contracts/scripts/simulations/utils.ts (7)

8-10: Updated imports for simulation utilities

The addition of EvidenceModule, ArbitrableExample, and RandomizerMock to the imports ensures that all necessary contracts are available for simulation scripts. This is essential for comprehensive testing and development.


12-12: Adoption of toBigInt for handling large numbers

The use of toBigInt alongside ethers in simulations is appropriate for handling large numerical values accurately. This change aligns with best practices in handling big numbers in JavaScript and Solidity.


29-30: Correct instantiation of new contract types

The instantiation of ArbitrableExample and EvidenceModule ensures that the scripts have access to the latest contract interfaces, which is crucial for correct interaction patterns and data retrieval.


40-40: Comprehensive return of contract instances

The function getContracts now returns a more comprehensive list of contract instances, which facilitates easier access and manipulation of these contracts within the simulation scripts.


61-61: Enhanced random number generation checking

The detailed checks for the readiness of the random number generator are crucial for ensuring that the simulations behave as expected under various conditions. This robustness in handling RNG states is beneficial for accurate testing.


84-84: Simplified fee calculation for local networks

The simplification in the fee calculation for local networks by directly returning a fixed ether value is practical for testing environments. It avoids unnecessary complexity in test setups.


154-154: Accurate calculation of remaining period duration

The calculation of the remaining duration until a new period in the arbitration process uses toBigInt for precision. This is crucial for timing-related operations, ensuring that transitions occur exactly as scheduled.

contracts/deploy/00-home-chain-arbitration-neo.ts (5)

14-14: Update constant usage to match ethers v6

The change from AddressZero to ZeroAddress aligns with the updated ethers library conventions, ensuring consistency across the codebase.


46-46: Ensure deployment arguments are updated

The deployment arguments have been correctly updated to use the new ZeroAddress constant. This change is crucial to prevent potential issues with uninitialized addresses in smart contracts.


86-86: Review the use of ZeroAddress in contract deployment

Using ZeroAddress here ensures that the contract deployment script aligns with the latest best practices for address initialization, preventing misuse of uninitialized addresses.


122-122: Validate contract deployment arguments

The deployment arguments for DisputeResolverNeo should be closely reviewed to ensure they are correct and align with the expected types and values.

Verification successful

The deployment arguments for DisputeResolverNeo in the 00-home-chain-arbitration-neo.ts file are as follows:

const resolver = await deploy("DisputeResolverNeo", {
  from: deployer,
  contract: "DisputeResolver",
  args: [core.target, disputeTemplateRegistry.target],
  log: true,
});

The arguments appear to be correctly structured, with core.target and disputeTemplateRegistry.target being passed as the args array. If these values align with the expected types and values for the DisputeResolverNeo contract, then the deployment arguments are correct.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the deployment arguments for DisputeResolverNeo.

# Test: Check the deployment arguments in the contract.
rg --type python $'deploy\\("DisputeResolverNeo", .*\\)'

Length of output: 86



Script:

#!/bin/bash
# Description: Verify the deployment arguments for DisputeResolverNeo in the TypeScript file.

# Test: Check the deployment arguments in the contract.
rg 'deploy\("DisputeResolverNeo", .*\)' contracts/deploy/00-home-chain-arbitration-neo.ts

Length of output: 91



Script:

#!/bin/bash
# Description: Broaden the search to find any deploy function calls in the TypeScript file.

# Test: Check for any deploy function calls in the contract.
rg 'deploy\(' contracts/deploy/00-home-chain-arbitration-neo.ts

Length of output: 121



Script:

#!/bin/bash
# Description: Extract and inspect the arguments passed to the deploy function call for DisputeResolverNeo.

# Test: Extract the complete deploy function call and its arguments.
rg -A 5 'deploy\("DisputeResolverNeo", \{' contracts/deploy/00-home-chain-arbitration-neo.ts

Length of output: 281


108-108: Check the change in currency rate handling

The code attempts to change currency rates, which is a sensitive operation. Ensure that the logic here is robust and error handling is adequate to prevent issues during deployment.

Verification successful

The changeCurrencyRate function calls are indeed wrapped in try-catch blocks, ensuring proper error handling. The code logs an error message if the currency rate change fails.

  • contracts/deploy/00-home-chain-arbitration.ts
  • contracts/deploy/00-home-chain-arbitration-university.ts
  • contracts/deploy/00-home-chain-arbitration-neo.ts

These try-catch blocks and error logging mechanisms are in place, confirming that the logic is robust and error handling is adequate.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Check for proper error handling in currency rate changes.

# Test: Search for error handling patterns. Expect: Proper try-catch usage.
rg --type python $'try {\\s+await changeCurrencyRate\\(.*\\);} catch (e) {\\s+console.error\\("failed to change currency rates:", e\\);\\s+}'

Length of output: 337



Script:

#!/bin/bash
# Description: Check for proper error handling in currency rate changes.

# Test: Search for error handling patterns. Expect: Proper try-catch usage.
rg --type typescript $'try {\\s+await changeCurrencyRate\\(.*\\);\\s*} catch \\(e\\) {\\s+console\\.error\\("failed to change currency rates:", e\\);\\s*}'

Length of output: 353



Script:

#!/bin/bash
# Description: Check for proper error handling in currency rate changes.

# Test: Search for proper error handling patterns around `changeCurrencyRate` function calls.

# Correct the regex pattern to avoid parse errors.
rg --type typescript 'try\s*{\s*await changeCurrencyRate\(.*\);\s*}\s*catch\s*\(e\)\s*{\s*console\.error\("failed to change currency rates:", e\);\s*}'

Length of output: 371



Script:

#!/bin/bash
# Description: Check for proper error handling in currency rate changes.

# Test: Search for proper error handling patterns around `changeCurrencyRate` function calls.

# Correct the regex pattern to avoid parse errors.
rg --type typescript 'try\s*\{\s*await changeCurrencyRate\(.*\);\s*\}\s*catch\s*\(e\)\s*\{\s*console\.error\("failed to change currency rates:", e\);\s*\}'

Length of output: 192



Script:

#!/bin/bash
# Description: Check for proper error handling in currency rate changes.

# Test: Search for proper error handling patterns around `changeCurrencyRate` function calls.

# Correct the file type and regex pattern to avoid parse errors.
rg --type ts 'try\s*\{\s*await changeCurrencyRate\(.*\);\s*\}\s*catch\s*\(e\)\s*\{\s*console\.error\("failed to change currency rates:", e\);\s*\}'

Length of output: 149



Script:

#!/bin/bash
# Description: Search for `changeCurrencyRate` function calls and inspect their context for error handling.

# Search for `changeCurrencyRate` function calls in TypeScript files.
rg 'changeCurrencyRate\(' --type ts --context 5

Length of output: 3382

contracts/scripts/disputeCreatorBot.ts (2)

46-46: Check the arbitration cost calculation

The script now uses a method call to arbitrationCost with extraData to calculate costs. This is a crucial change for ensuring the correct calculation of dispute costs.


61-61: Update handling of big integers

The update to use ethers.toBigInt for handling large numbers is a significant improvement, aligning with best practices for handling big integers in Solidity.

contracts/src/arbitration/arbitrables/ArbitrableExample.sol (1)

40-40: Ensure proper access control

The addition of the onlyByGovernor modifier enhances security by restricting certain functions to the governor address only. This is a critical update for maintaining the integrity of contract operations.

contracts/scripts/populateCourts.ts (2)

41-43: Validate constants conversion to BigInt

The conversion of constants to BigInt is crucial for handling large numbers accurately in the script. Ensure these conversions are correctly implemented to prevent potential calculation errors.


101-102: Check the conversion of USD to ETH for court parameters

The conversion logic for court parameters from USD to ETH values is vital for accurate court setup. Ensure the calculations are correct and consider edge cases where conversions might fail.

Verification successful

The conversion logic for court parameters from USD to ETH values appears to be correctly implemented in the script. The truncateWei and toBigInt functions are used to handle the conversion, ensuring precision.

  • File: contracts/scripts/populateCourts.ts
    • Lines:
      minStake: truncateWei(toBigInt(court.minStake) / toBigInt(ETH_USD)),
      feeForJuror: truncateWei(toBigInt(court.feeForJuror) / toBigInt(ETH_USD)),
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the calculation logic for converting USD to ETH.

# Test: Check the conversion functions in the script.
rg --type python $'truncateWei\\(toBigInt\\(.*\\) / toBigInt\\(ETH_USD\\)\\)'

Length of output: 103



Script:

#!/bin/bash
# Description: Verify the calculation logic for converting USD to ETH.

# Test: Check the conversion functions in the TypeScript script.
rg --type typescript $'truncateWei\\(toBigInt\\(.*\\) / toBigInt\\(ETH_USD\\)\\)'

Length of output: 111



Script:

#!/bin/bash
# Description: Verify the calculation logic for converting USD to ETH.

# Find all TypeScript files and check the conversion functions in them.
fd --extension ts --exec rg 'truncateWei\(toBigInt\(.*\) / toBigInt\(ETH_USD\)\)' {}

Length of output: 244

contracts/scripts/simulations/tasks.ts (3)

38-41: Ensure consistent usage of ethers utility functions.

In line 40, you are using ethers.parseEther which is consistent with the updated import paths mentioned in the PR summary. However, make sure all instances in the file are updated similarly for consistency.


364-377: Clarify the use of BigNumberish and AddressLike types.

The explicit type definitions and conversions are good for clarity. However, ensure that these types are used consistently throughout the file and match the expected types in the smart contract functions.


415-415: Verify the parameters for the relay function.

The use of randomizerRng.target and ethers.randomBytes(32) should be verified to ensure they meet the expected parameter types and values for the relay function in randomizerMock.

Verification successful

The relay function in RandomizerMock.sol has the following signature:

function relay(RandomizerRNG _rng, uint256 _id, bytes32 _value) external {

The parameters used in the code snippet:

await randomizerMock.connect(wallet).relay(randomizerRng.target, 0, ethers.randomBytes(32));

match the expected types: RandomizerRNG, uint256, and bytes32.

  • randomizerRng.target should be of type RandomizerRNG.
  • 0 is a valid uint256.
  • ethers.randomBytes(32) generates a bytes32.

Based on the function signature, the parameters used are correct.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the parameter types for the `relay` function.

# Test: Check the function signature in the ABI.
cat contracts/RandomizerMock.json | jq '.abi[] | select(.name == "relay")'

Length of output: 138



Script:

#!/bin/bash
# Locate the ABI file for `randomizerMock`.
fd 'RandomizerMock' --type f

Length of output: 70



Script:

#!/bin/bash
# Search for the `relay` function implementation in `RandomizerMock.sol`.
ast-grep --lang solidity --pattern 'function relay($_, $_, $_) $_' contracts/src/rng/mock/RandomizerMock.sol

Length of output: 227



Script:

#!/bin/bash
# Search for the `relay` function implementation in `RandomizerMock.sol`.
rg 'function relay' contracts/src/rng/mock/RandomizerMock.sol

Length of output: 142

contracts/scripts/keeperBot.ts Outdated Show resolved Hide resolved
contracts/scripts/simulations/tasks.ts Show resolved Hide resolved
contracts/scripts/simulations/tasks.ts Outdated Show resolved Hide resolved
contracts/scripts/simulations/tasks.ts Outdated Show resolved Hide resolved
contracts/deploy/utils/index.ts Show resolved Hide resolved
contracts/scripts/getCourtsV1.ts Show resolved Hide resolved
contracts/deploy/04-foreign-arbitrable.ts Show resolved Hide resolved
contracts/deploy/03-vea-mock.ts Show resolved Hide resolved
contracts/deploy/03-vea-mock.ts 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)
contracts/test/integration/index.ts (1)

Line range hint 28-34: Remove const keyword from enum declarations as per TypeScript best practices.

Using const with enums can lead to issues when the code is bundled or if 'isolatedModules' mode is used. Convert these to regular enums to avoid potential runtime errors.

-  const enum Period {
+  enum Period {
    evidence,
    commit,
    vote,
    appeal,
    execution,
  }

-  const enum Phase {
+  enum Phase {
    staking,
    generating,
    drawing,
  }

Also applies to: 36-40

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b558f6e and 6d486ce.

Files selected for processing (2)
  • contracts/test/integration/index.ts (10 hunks)
  • contracts/test/proxy/index.ts (2 hunks)
Additional context used
Biome
contracts/test/integration/index.ts

[error] 28-34: The enum declaration should not be const (lint/suspicious/noConstEnum)

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.


[error] 36-40: The enum declaration should not be const (lint/suspicious/noConstEnum)

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.

Additional comments not posted (2)
contracts/test/integration/index.ts (1)

4-4: Update import statement to align with new ethers library structure.

The import for toBigInt and BytesLike from ethers directly might not align with the new library structure. Consider using destructuring from the specific module or package if ethers has restructured its exports in the latest version.

contracts/test/proxy/index.ts (1)

71-71: Ensure proper use of .target property in upgradability tests.

The use of .target property on contract instances is crucial for correctly referencing the address in the context of proxy contracts. Verify that all instances where .target is used are consistent and correct.

Also applies to: 77-79, 86-86, 96-96, 102-104

Verification successful

The review comment concerns the proper use of the .target property in upgradability tests. The search results show multiple instances of .target being used in the contracts/test/proxy/index.ts file, as well as in other test and script files. This indicates that .target is indeed being used consistently across the codebase.

  • Files with .target usage:
    • contracts/test/proxy/index.ts: Lines 71, 77, 86, 96, 102
    • contracts/test/integration/index.ts
    • contracts/scripts/simulations/utils.ts
    • contracts/scripts/utils/logger.ts
    • contracts/scripts/keeperBot.ts
    • contracts/scripts/disputeCreatorBot.ts
    • contracts/scripts/deploy.ts
    • contracts/scripts/simulations/tasks.ts
    • contracts/scripts/disputeRelayerBot.ts
    • contracts/deploy/00-home-chain-arbitration.ts
    • contracts/deploy/00-home-chain-arbitration-neo.ts
    • contracts/deploy/00-home-chain-arbitration-university.ts
    • contracts/deploy/utils/deployTokens.ts
    • contracts/deployments/mainnet.viem.ts

Given the extensive and consistent use of .target across various files, it appears that the property is correctly and consistently referenced.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify correct usage of `.target` property in contract instances.

# Test: Search for `.target` usage in the entire test directory to ensure consistency.
rg --type typescript ".target" tests/

Length of output: 72



Script:

#!/bin/bash
# Description: Verify correct usage of `.target` property in contract instances.

# Test: Search for `.target` usage in the entire test directory to ensure consistency.
rg --type ts ".target" tests/

Length of output: 76



Script:

#!/bin/bash
# Description: Verify correct usage of `.target` property in contract instances.

# Test: Search for `.target` usage in the entire repository to ensure consistency.
rg --type ts ".target"

Length of output: 9625

contracts/test/integration/index.ts Outdated Show resolved Hide resolved
contracts/test/integration/index.ts 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: 3

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 6d486ce and d6b5531.

Files selected for processing (1)
  • contracts/test/evidence/index.ts (9 hunks)
Additional comments not posted (10)
contracts/test/evidence/index.ts (10)

3-3: Update to import statements approved.

The import changes are aligned with the PR's objective to update the usage of the ethers library.


29-32: Conversion to BigInt and arithmetic operations are correctly implemented.

The use of toBigInt for constants and arithmetic operations is consistent with the PR's goal of transitioning from BigNumber to BigInt. This should ensure that the calculations are handled as integers rather than floating-point operations, which is appropriate for currency and other exact-value computations.
[APROVED]


41-43: Correct typing for contract instances.

The explicit typing for arbitrator, evidenceModule, and disputeTemplateRegistry as specific contract types from the typechain is a good practice for TypeScript, ensuring that method calls on these instances are type-checked at compile time.


56-58: Ensure correct target property usage in contract interactions.

The use of the .target property for contract addresses in the deployment script is correct and aligns with the updated ethers library usage. This ensures that the contract addresses are correctly referenced.


91-96: Correct calculation and comparison of template IDs using BigInt.

The calculations involving BigInt for dispute template IDs and the subsequent checks are correct and align with the updated practices of handling large numbers in JavaScript.


104-104: Proper handling of contract data retrieval with BigInt.

The retrieval and comparison of arbitratorExtraData using BigInt is correctly implemented, ensuring that large numerical data is handled accurately.


174-174: Ensure correct handling of insufficient funds.

The check for insufficient funds using BigInt subtraction is correctly implemented. This is crucial for financial transactions where precise calculations are necessary.


186-186: Use of BigInt in hashing functions is appropriate.

The use of BigInt in conjunction with hashing functions ensures that large numbers are correctly handled during the generation of unique identifiers.


251-256: Event handling and assertions are correct.

The handling of dispute events and the assertions to check the correctness of the data are implemented properly. The usage of BigInt for comparisons ensures accuracy in the assertions.


89-89: Use of BigInt in index calculations is correct but needs verification.

The use of BigInt for manipulating indices is technically correct, but it's unusual and could lead to errors if not handled properly everywhere it's used. Verification is recommended to ensure that all related code handles BigInt correctly, especially in index calculations.

contracts/test/evidence/index.ts 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: 3

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d6b5531 and d1c5961.

Files selected for processing (5)
  • contracts/deploy/00-home-chain-arbitration-neo.ts (6 hunks)
  • contracts/test/arbitration/draw.ts (13 hunks)
  • contracts/test/arbitration/index.ts (2 hunks)
  • contracts/test/arbitration/staking-neo.ts (29 hunks)
  • contracts/test/arbitration/staking.ts (15 hunks)
Files not reviewed due to errors (1)
  • contracts/test/arbitration/staking.ts (no review received)
Files skipped from review as they are similar to previous changes (1)
  • contracts/deploy/00-home-chain-arbitration-neo.ts
Additional context used
Biome
contracts/test/arbitration/draw.ts

[error] 23-29: The enum declaration should not be const (lint/suspicious/noConstEnum)

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.


[error] 31-34: The enum declaration should not be const (lint/suspicious/noConstEnum)

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.


[error] 36-40: The enum declaration should not be const (lint/suspicious/noConstEnum)

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.

Additional comments not posted (30)
contracts/test/arbitration/index.ts (6)

3-3: Adjust import statement for better clarity.

The import of toBigInt is added to handle big number operations directly. This is a good practice for handling large numerical values in Solidity, ensuring precision and avoiding overflow issues.


9-9: Initialization of contract instances is clear and concise.

The variables core and disputeKit are clearly defined and initialized. This setup is essential for the subsequent tests, ensuring that the necessary contracts are available and properly configured.


35-39: Correct handling of boolean values in assertions.

The test checks if the dispute kit is enabled correctly by asserting the _enable property is true. This is a straightforward and effective way to verify the functionality.


43-43: Ensure proper error handling in dispute creation.

The test expects the createDispute function to revert with a specific error message. This is crucial for ensuring that unauthorized access is handled correctly.


49-54: Validate big number comparisons using toBigInt.

Using toBigInt for comparisons in tests is a robust method to handle large numbers, ensuring that the tests remain accurate even with high values.


17-20: Ensure consistency in event property access.

The tests rely on event properties like _disputeKitID and _disputeKitAddress. Ensure these property names accurately reflect the event definitions in the smart contracts to avoid runtime errors.

Also applies to: 24-32

contracts/test/arbitration/draw.ts (15)

3-3: Update import statements to include new utilities and types.

The addition of toBigInt, ContractTransactionResponse, and HDNodeWallet from ethers is appropriate, considering the operations performed in the tests. This ensures proper types are used for transactions and wallet interactions.


20-21: Use of toBigInt for defining constants is appropriate.

Defining constants like ONE_TENTH_ETH and ONE_THOUSAND_PNK using toBigInt ensures that the tests handle large numbers accurately, which is crucial for blockchain applications.


44-51: Initialization of multiple contract instances is clear.

The variables for different contracts such as disputeKit, pnk, core, etc., are well-defined. This setup is essential for the tests, ensuring that all required contracts are available and properly configured.


56-56: Correct usage of ethers utilities.

The use of ethers.AbiCoder.defaultAbiCoder() is correct and necessary for encoding and decoding data within the tests. This utility facilitates interactions with smart contracts by handling ABI encoding.


74-74: Ensure deterministic behavior in tests with custom RNG setup.

Setting up a deterministic RNG (IncrementalNG) for the tests is a good practice. It ensures that the random aspects of the test environment are controlled, leading to more predictable and reliable test outcomes.

Also applies to: 77-82


104-105: Define types for custom test functions.

Defining custom types like SetStake and ExpectFromDraw for test functions is a good practice. It enhances code readability and maintainability by clearly specifying the expected function signatures.


113-113: Ensure proper handling of transactions and balances in tests.

The tests involve multiple transactions and balance checks. It's important to ensure that these are handled correctly to avoid flaky tests and ensure that the test conditions are met.

Also applies to: 115-115, 124-124, 126-126, 128-128, 129-129, 131-131


137-140: Validate complex interactions and data encoding in dispute creation.

The tests involve complex interactions and data encoding when creating disputes and relaying them. Ensuring that these interactions are correctly implemented is crucial for the integrity of the tests.

Also applies to: 142-142, 144-144, 146-150, 152-152, 154-154


195-195: Ensure correct stake handling and juror balance checks in tests.

The tests involve setting stakes, drawing jurors, and checking their balances. It's crucial to ensure that these operations are handled correctly to maintain the integrity of the test scenarios.

Also applies to: 196-196, 199-201, 206-207, 218-218, 222-224, 228-229


236-236: Validate the unstaking logic and balance checks.

The tests involve unstaking jurors and checking their balances. Ensuring that the unstaking logic and the balance checks are implemented correctly is crucial for the accuracy of the tests.

Also applies to: 238-238


264-264: Check for proper handling of stake setting and drawing expectations in tests.

The tests involve setting stakes and expecting certain outcomes from the drawing process. Ensuring that these are handled correctly is essential for the validity of the test scenarios.

Also applies to: 265-265, 268-269, 274-274


300-300: Validate stake setting, drawing, and balance checks in subcourt scenarios.

The tests involve setting stakes in subcourts, drawing jurors, and checking their balances. It's important to ensure that these operations are correctly implemented to maintain the integrity of the test scenarios.

Also applies to: 301-301, 304-305, 309-309, 321-322, 327-329


335-335: Check the unstaking logic and balance checks in subcourt scenarios.

The tests involve unstaking jurors in subcourt scenarios and checking their balances. Ensuring that these operations are correctly implemented is crucial for the accuracy of the tests.

Also applies to: 337-337


186-186: Check the implementation of draw counting logic.

The function countDraws is used to tally the draws based on block numbers. It's important to ensure that this function is implemented correctly to provide accurate test results.

Verification successful

The countDraws function is implemented correctly.

The function countDraws is defined to tally the draws based on block numbers, and it correctly handles the block number filtering and counting logic. The implementation details are as follows:

  • The function queries the Draw events for a specific block number.
  • It then reduces the draws to a tally of addresses and their respective draw counts.

Locations in the codebase:

  • contracts/test/arbitration/draw.ts, lines 186-192
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the implementation of the `countDraws` function.

# Test: Check the source code for `countDraws`. Expect: Correct implementation and handling of block numbers.
rg --type py "countDraws" -A 10

Length of output: 31



Script:

#!/bin/bash
# Description: Verify the implementation of the `countDraws` function in TypeScript files.

# Test: Check the source code for `countDraws`. Expect: Correct implementation and handling of block numbers.
rg --type ts "countDraws" -A 10

Length of output: 3966


84-84: Check for correct parameters and method calls in court creation.

The test setup involves creating a court with specific parameters. It's crucial to ensure that these parameters and the method calls are correct and align with the smart contract's expectations.

Also applies to: 87-98

Verification successful

Check for correct parameters and method calls in court creation.

The parameters used in the createCourt method call within contracts/test/arbitration/draw.ts align with the smart contract's method definition.

  • Smart Contract Parameters:

    • uint96 _parent
    • bool _hiddenVotes
    • uint256 _minStake
    • uint256 _alpha
    • uint256 _feeForJuror
    • uint256 _jurorsForCourtJump
    • uint256[4] memory _timesPerPeriod
    • bytes memory _sortitionExtraData
    • uint256[] memory _supportedDisputeKits
  • Test File Parameters:

    • 1 (parent)
    • false (hiddenVotes)
    • minStake
    • alpha
    • feeForJuror
    • 256 (jurorsForCourtJump)
    • [0, 0, 0, 10] (timesPerPeriod)
    • ethers.toBeHex(5) (sortitionExtraData)
    • [1] (supportedDisputeKits)

The parameters and method calls appear to be correctly aligned with the smart contract's expectations.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the parameters and method calls in court creation match the smart contract.

# Test: Search for the `createCourt` method in the smart contract. Expect: Correct parameters and usage.
rg --type py "createCourt" -A 10

Length of output: 32



Script:

#!/bin/bash
# Locate all smart contract files, typically in Solidity (.sol) or Vyper (.vy) format
fd --type f -e sol -e vy

# Search for the `createCourt` method in the located smart contract files
fd --type f -e sol -e vy --exec rg "createCourt" -A 10

Length of output: 4066



Script:

#!/bin/bash
# Search for `createCourt` method calls in the test file to verify the parameters.
rg "createCourt" contracts/test/arbitration/draw.ts -A 10

Length of output: 358

contracts/test/arbitration/staking-neo.ts (9)

135-135: Good practice: Explicit whitelisting

The line await core.changeArbitrableWhitelist(resolver.target, false); explicitly handles the whitelisting of arbitrable addresses. This is a good security practice as it ensures that only specific contracts are allowed to interact, reducing the surface for unauthorized actions.


149-149: Correct implementation of feature toggling

The line await core.changeArbitrableWhitelist(resolver.target, true); correctly implements the feature toggling by enabling the arbitrable address. This is crucial for testing both the enabled and disabled states of features in smart contracts.


166-166: Security check on staking eligibility

The method call core.connect(juror).setStake(1, PNK(1000)) properly checks for eligibility before allowing a stake operation. This is an important security measure to ensure that only eligible accounts can perform staking.


245-245: Validation of staking limits

The repeated checks for staking limits using to.be.revertedWithCustomError(core, "StakingMoreThanMaxStakePerJuror") are crucial for ensuring that staking operations do not exceed predefined limits, which is fundamental for maintaining the integrity and balance of the staking mechanism.

Also applies to: 257-257, 269-269


298-298: Proper handling of max total staked validation

The use of custom error StakingMoreThanMaxTotalStaked helps in enforcing the staking caps at the protocol level, which is essential for controlling the total staked amount within the system and preventing overflows or misuse.

Also applies to: 321-321, 333-333


376-376: Check for staking during pause

The attempt to stake with core.setStake(1, PNK(500)); while the system is paused and its subsequent prevention with a custom error WhenNotPausedOnly demonstrates robust handling of state-dependent operations, ensuring that no critical actions occur during paused states.


735-735: Correct implementation of court creation and unstaking

The method core.createCourt followed by multiple core.setStake and a series of core.passPeriod calls culminating in core.execute to unstake from all courts is a comprehensive demonstration of the contract's capabilities to manage court dynamics effectively.


111-111: Potential issue with random number generation

The method randomizer.relay(rng.target, 0, ethers.randomBytes(32)); uses ethers.randomBytes(32) which generates pseudo-random bytes. For blockchain and smart contract applications, especially those involving randomness in a production environment, ensure that the source of randomness is secure and fits the use case to prevent potential attacks or predictability.


400-400: Complex operation sequence well-handled

The sequence of operations starting from creating a court, approving PNK, setting stakes, and creating disputes, followed by phase transitions, is complex but appears to be handled correctly. Ensure comprehensive testing to cover all these intertwined operations.

Also applies to: 402-402, 405-405, 407-407

Verification successful

Comprehensive tests for complex operations

The functions createCourt, setStake, and createDispute are indeed covered in multiple test files, ensuring that the complex sequence of operations is thoroughly tested.

  • contracts/test/arbitration/staking.ts
  • contracts/test/arbitration/staking-neo.ts
  • contracts/test/arbitration/draw.ts

These files include the necessary tests for the operations mentioned.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Ensure comprehensive tests cover the complex sequence of operations related to court creation, staking, and dispute management.
rg --type py "test" | grep "createCourt" | grep "setStake" | grep "createDispute"

Length of output: 75



Script:

#!/bin/bash
# Searching for test files that include the function `createCourt`
rg --type ts "createCourt"

# Searching for test files that include the function `setStake`
rg --type ts "setStake"

# Searching for test files that include the function `createDispute`
rg --type ts "createDispute"

Length of output: 18992

contracts/test/arbitration/staking-neo.ts Show resolved Hide resolved
contracts/test/arbitration/staking-neo.ts Show resolved Hide resolved
contracts/test/arbitration/index.ts Show resolved Hide resolved
@kleros kleros deleted a comment from coderabbitai bot Jun 21, 2024
@kleros kleros deleted a comment from coderabbitai bot Jun 21, 2024
@Anmol-Dhiman Anmol-Dhiman marked this pull request as ready for review June 21, 2024 16:38
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d1c5961 and df6132e.

Files selected for processing (3)
  • contracts/test/arbitration/draw.ts (13 hunks)
  • contracts/test/evidence/index.ts (9 hunks)
  • contracts/test/integration/index.ts (10 hunks)
Files not reviewed due to errors (1)
  • contracts/test/arbitration/draw.ts (no review received)
Files skipped from review as they are similar to previous changes (1)
  • contracts/test/evidence/index.ts
Additional context used
Biome
contracts/test/integration/index.ts

[error] 28-34: The enum declaration should not be const (lint/suspicious/noConstEnum)

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.


[error] 36-40: The enum declaration should not be const (lint/suspicious/noConstEnum)

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.

contracts/test/arbitration/draw.ts

[error] 23-29: The enum declaration should not be const (lint/suspicious/noConstEnum)

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.


[error] 31-34: The enum declaration should not be const (lint/suspicious/noConstEnum)

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.


[error] 36-40: The enum declaration should not be const (lint/suspicious/noConstEnum)

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.

Additional comments not posted (11)
contracts/test/integration/index.ts (11)

4-4: Update to newer import style.

The import of toBigInt from ethers is correctly updated to reflect the newer version of the library. This aligns with the PR's objective to update usage patterns according to the newer ethers version.


22-25: Consider using BigInt literals for clarity and simplicity.

Instead of using toBigInt(10) ** toBigInt(17), you can use the BigInt literal directly for better readability, e.g., 1e17n.


43-52: Correct variable declaration syntax.

The contract instances such as RandomizerRNG, PNK, etc., are declared with commas, which might be a typo. They should be declared with semicolons to separate the declarations.
[DUPLICATE_comment]


73-73: Arithmetic operation on BigInt values.

The multiplication of ONE_TENTH_ETH by toBigInt(3) is a valid operation using BigInt, ensuring that large number calculations are handled correctly.


105-105: Usage of custom types for function parameters.

Defining types like SetStake and ExpectFromDraw enhances code readability and maintainability by making the function signatures more descriptive.


110-110: Proper usage of ABI decoding.

The use of abiCoder.decode to extract the dispute ID from the transaction return value is correctly implemented and aligns with best practices for handling encoded data in Ethereum.


127-127: Error handling for null values.

Good implementation of error handling for potentially null values, which prevents runtime errors in scenarios where blockchain queries might fail unexpectedly.

Also applies to: 129-129


140-140: Complex object construction for transaction parameters.

The detailed setup of transaction parameters within the relayCreateDispute function call is well-structured, ensuring that all necessary data is correctly packaged and sent to the blockchain.

Also applies to: 142-142, 144-144


163-163: Dynamic block mining to simulate network conditions.

The mineBlocks function, which dynamically mines a number of blocks based on the RNG lookahead, is a practical approach to simulate network conditions and ensure the contract's behavior is tested under realistic scenarios.


197-198: Event emission assertions in tests.

The assertions to check that specific events are emitted with expected parameters are crucial for verifying the correct behavior of the contract during operations that affect state.


209-209: Logging function for debugging.

The logJurorBalance function, which formats and logs the juror's balance, is useful for debugging and ensuring that the contract's state changes are visible and traceable.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between df6132e and acbdccd.

Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
Files selected for processing (1)
  • web/src/components/EvidenceCard.tsx (1 hunks)
Additional comments not posted (1)
web/src/components/EvidenceCard.tsx (1)

105-105: Approved change from styled.label to styled.p for semantic correctness.

The change enhances the semantic correctness and accessibility of the component. Ensure that this change does not affect the intended styling due to different default styles of label and p tags.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 21, 2024
Copy link

codeclimate bot commented Jun 26, 2024

Code Climate has analyzed commit b1e4632 and detected 40 issues on this pull request.

Here's the issue category breakdown:

Category Count
Complexity 3
Duplication 28
Style 9

View more on Code Climate.

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

Outside diff range and nitpick comments (3)
contracts/test/integration/index.ts (1)

Line range hint 28-34: Convert const enum to regular enum.

Using const enum can lead to issues with bundlers and is incompatible with the 'isolatedModules' mode. Convert these to regular enums to avoid potential issues.

- const enum Period {
+ enum Period {
    evidence,
    commit,
    vote,
    appeal,
    execution,
- }
+ }

- const enum Phase {
+ enum Phase {
    staking,
    generating,
    drawing,
- }
+ }

Also applies to: 36-40

contracts/scripts/keeperBot.ts (2)

Line range hint 31-42: Ensure robust error handling in getContracts function.

The function getContracts retrieves several contracts but does not handle potential errors that might occur during these operations. Consider adding try-catch blocks to handle and log any errors that might occur during contract retrieval:

+ try {
    const core = (await ethers.getContract("KlerosCore")) as KlerosCore;
    ...
+ } catch (error) {
+   logger.error(error, "Failed to retrieve contracts");
+   throw error; // Rethrow or handle as needed
+ }

This change ensures that any issues during contract retrieval do not silently fail and affect the script's operation.


Line range hint 156-180: Remove unnecessary else clauses to simplify control flow.

The function isRngReady uses multiple else clauses that are unnecessary since each if condition returns early. This can simplify the control flow and reduce the complexity of the function:

  if (currentRng === randomizerRng.target) {
    ...
    return true;
- } else if (currentRng === blockHashRNG.target) {
+ } if (currentRng === blockHashRNG.target) {
    ...
    return true;
- } else {
+ }
  logger.error("Unknown RNG at ", currentRng);
  return false;

Removing these else clauses makes the code cleaner and easier to read.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between acbdccd and 97755ae.

Files selected for processing (6)
  • contracts/deploy/00-home-chain-arbitration-university.ts (6 hunks)
  • contracts/deploy/03-vea-mock.ts (4 hunks)
  • contracts/package.json (3 hunks)
  • contracts/scripts/keeperBot.ts (20 hunks)
  • contracts/scripts/simulations/tasks.ts (22 hunks)
  • contracts/test/integration/index.ts (10 hunks)
Files skipped from review due to trivial changes (1)
  • contracts/deploy/03-vea-mock.ts
Files skipped from review as they are similar to previous changes (2)
  • contracts/deploy/00-home-chain-arbitration-university.ts
  • contracts/package.json
Additional context used
Biome
contracts/test/integration/index.ts

[error] 28-34: The enum declaration should not be const (lint/suspicious/noConstEnum)

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.


[error] 36-40: The enum declaration should not be const (lint/suspicious/noConstEnum)

Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values.
See TypeScript Docs for more details.
Safe fix: Turn the const enum into a regular enum.

contracts/scripts/keeperBot.ts

[error] 162-165: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 166-180: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 173-176: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 177-180: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)


[error] 592-592: Shouldn't redeclare 'dispute'. Consider to delete it or rename it. (lint/suspicious/noRedeclare)

'dispute' is defined here:

Additional comments not posted (14)
contracts/test/integration/index.ts (4)

4-4: Update to use toBigInt from ethers.

This change aligns with the PR objectives to use updated ethers methods consistently.


22-25: Consider using BigInt literals for clarity and simplicity.

Instead of using toBigInt(10) ** toBigInt(17), you can use the BigInt literal directly for better readability, e.g., 1e17n.


43-52: Ensure correct typing for contract instances.

The contract instances such as RandomizerRNG, PNK, etc., are declared with commas, which might be a typo. They should be declared with semicolons to separate the declarations.


73-73: Review complex transaction and event handling logic.

The transaction handling and event emission logic are complex and involve multiple smart contracts. Ensure that all interactions are correctly implemented according to the updated ethers methods and constants.

Also applies to: 76-76, 85-85, 99-99, 105-105, 108-108, 110-110, 114-114, 118-118, 120-120, 124-124, 126-126, 127-127, 129-129, 132-132, 133-133, 138-138, 140-140, 142-142, 144-144, 153-153, 163-163, 166-166, 173-173, 177-177, 179-179, 197-197, 198-198, 209-209

contracts/scripts/simulations/tasks.ts (7)

38-41: LGTM! Approval process logic is correctly implemented.


80-88: Well-structured task for court creation.
The use of toBigInt and explicit type casting ensures type safety and clarity in the function's operation.


175-175: Good logging for phase transitions.
This helps in tracking the changes effectively, which is crucial for debugging and operational monitoring.


214-214: Effective logging for juror drawing.
The before and after logs provide clear visibility into the operation's impact, aiding in debugging and verification.


235-235: Clear logging for period transitions.
This helps in effectively monitoring the changes, which is crucial for operational transparency.


257-258: Proper use of hashing and hex conversion for commits.
The use of ethers.solidityPackedKeccak256 and toBeHex ensures compatibility with Solidity's hashing and provides a clear hexadecimal output.


Line range hint 308-320: Effective handling of network-specific conditions in funding appeals.
The conditional logic for handling local networks by mining blocks ensures smooth operation in different environments.

contracts/scripts/keeperBot.ts (3)

5-5: Consider consolidating type imports from ethers for consistency.

While reviewing the import statements, I noticed that types like BigNumberish are imported directly from ethers. It's good practice to maintain consistency in how types are imported, especially in a file that might be using multiple types from ethers.


241-248: Ensure high gas limits are justified in drawJurors.

The function drawJurors uses a high gas limit for transactions. It's important to ensure that such high limits are justified and documented:

- const HIGH_GAS_LIMIT = { gasLimit: 50_000_000 }; // 50M gas
+ const HIGH_GAS_LIMIT = { gasLimit: 50_000_000 }; // 50M gas, used for drawing jurors due to complex calculations

Adding a comment explaining the reason for the high gas limit helps maintain clarity and justifies the use of resources.


355-378: Verify calculations and error handling in executeDelayedStakes.

The executeDelayedStakes function calculates the number of stakes to execute and attempts to handle them. It's crucial to verify that the calculations are correct and that potential errors are handled properly:

  const delayedStakesRemaining = toBigInt(1) + (await sortition.delayedStakeWriteIndex()) - (await sortition.delayedStakeReadIndex());
  const delayedStakes = delayedStakesRemaining < MAX_DELAYED_STAKES_ITERATIONS ? delayedStakesRemaining : toBigInt(MAX_DELAYED_STAKES_ITERATIONS);

  if (delayedStakes === toBigInt(0)) {
    logger.info("No delayed stakes to execute");
    return true;
  }
  logger.info(`Executing ${delayedStakes} delayed stakes, ${delayedStakesRemaining} remaining`);
  try {
    await sortition.executeDelayedStakes.staticCall(delayedStakes);
  } catch (e) {
    logger.error(`executeDelayedStakes: will fail because of ${JSON.stringify(e)}`);
    return false;
  }

Ensure that the calculations for delayedStakesRemaining and delayedStakes are correct and consider adding more detailed error handling to improve troubleshooting.

contracts/scripts/simulations/tasks.ts Show resolved Hide resolved
contracts/scripts/simulations/tasks.ts Show resolved Hide resolved
contracts/scripts/keeperBot.ts Show resolved Hide resolved
contracts/scripts/simulations/tasks.ts Show resolved Hide resolved
contracts/scripts/keeperBot.ts Show resolved Hide resolved
Copy link

sonarcloud bot commented Jun 26, 2024

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 97755ae and b1e4632.

Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
Files selected for processing (1)
  • .github/workflows/contracts-testing.yml (1 hunks)
Additional comments not posted (1)
.github/workflows/contracts-testing.yml (1)

77-77: Approved change in test command syntax.

Switching from double to single quotes in the test command is a good practice in shell environments to avoid unexpected parsing of special characters or variables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Upgrade hardhat, hardhat-deploy, ethers
1 participant