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

Merged
merged 24 commits into from
Nov 5, 2024

Conversation

Anmol-Dhiman
Copy link
Contributor

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

PR-Codex overview

This PR focuses on updating the codebase to improve compatibility with the latest version of ethers, enhancing type safety, and making various optimizations across multiple scripts and contracts.

Detailed summary

  • Updated ethers version and related utility functions.
  • Changed AddressZero to ZeroAddress in multiple files for consistency.
  • Improved type safety by ensuring contract calls use target instead of address.
  • Adjusted parsing and handling of units to use bigint.
  • Enhanced logging and error messages for better clarity.
  • Refactored contract deployment scripts for streamlined execution.
  • Modified event handling to ensure compatibility with new ethers features.
  • Updated test cases to reflect changes in contract interactions and assertions.

The following files were skipped due to too many changes: contracts/test/arbitration/ruler.ts, contracts/test/evidence/index.ts, contracts/test/arbitration/staking.ts, contracts/scripts/simulations/tasks.ts, contracts/scripts/keeperBot.ts, contracts/test/arbitration/draw.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

  • New Features

    • Enhanced handling of numerical values using native JavaScript bigint across various scripts and tests.
    • Improved clarity and consistency in contract interactions by replacing address references with target references.
    • Added support for importing JSON files as modules in the TypeScript configuration.
  • Bug Fixes

    • Refined error handling mechanisms to capture and log errors during contract calls.
  • Documentation

    • Updated comments and logging statements to reflect changes in transaction hash retrieval and numerical handling.
  • Chores

    • Upgraded various dependencies in package.json for improved functionality and security.
    • Enhanced type safety by explicitly defining variable types across multiple files.

Copy link
Contributor

coderabbitai bot commented Jun 19, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes across multiple files primarily focus on transitioning from BigNumber to native JavaScript bigint for numerical operations, enhancing type safety and consistency. Import statements have been updated to reflect this transition, and various functions have been modified to accommodate the new types. Additionally, several deployment scripts and test files have been adjusted to improve clarity and maintainability, including changes in how contract addresses are referenced and how errors are handled. The workflow for contracts testing has also been updated to use newer action versions.

Changes

File Path Change Summary
contracts/scripts/keeperBot.ts Updated import statements to include toBigInt, BigNumberish, and getNumber. Replaced BigNumber comparisons with new methods. Refined error handling and logging.
contracts/package.json Updated @kleros/kleros-v2-contracts to version 0.4.1 and upgraded several devDependencies.
contracts/test/arbitration/draw.ts Transitioned from BigNumber to bigint, updated variable types, and improved error handling. Adjusted logic for balance checks and transaction handling.
contracts/test/integration/index.ts Modified integration tests to use bigint, updated variable types, and changed method calls for contract interactions. Added error handling checks.
contracts/test/rng/index.ts Removed BigNumber, introduced abiCoder, and updated test logic to utilize bigint.
kleros-sdk/package.json Updated @reality.eth/reality-eth-lib dependency version from ^3.2.43 to ^3.2.44.
contracts/deploy/00-home-chain-arbitration-ruler.ts Updated deployment logic to use bigint and changed how contract addresses are referenced. Refactored changeCurrencyRate function.
contracts/deploy/utils/klerosCoreHelper.ts Updated changeCurrencyRate function to accept KlerosCoreRuler type and modified rate comparison logic.
contracts/test/arbitration/ruler.ts Enhanced type safety by updating variable types and improving event handling.
contracts/test/evidence/index.ts Transitioned to bigint, updated function signatures, and improved error handling for event logs.
.github/workflows/contracts-testing.yml Updated action versions and modified test command syntax.
contracts/deploy/upgrade-kleros-core.ts Replaced BigNumber with bigint for several variables and updated method calls for hexadecimal conversions.
contracts/deploy/utils/deployTokens.ts Changed faucetFundingAmount from BigNumber to bigint in deployment functions.
contracts/scripts/populateCourts.ts Transitioned to bigint, updated function parameters, and improved comparisons in the main action.
contracts/scripts/simulations/tasks.ts Updated import statements and transitioned to using bigint for various parameters in simulation tasks.
contracts/scripts/simulations/utils.ts Modified contract interaction methods and numerical calculations to use bigint.
contracts/test/arbitration/index.ts Enhanced type safety and updated event handling to reference .target instead of .address.
contracts/test/arbitration/staking-neo.ts Updated variable types and improved error handling for contract interactions.
contracts/test/arbitration/staking.ts Enhanced type safety and streamlined arithmetic operations using bigint.
contracts/tsconfig.json Added resolveJsonModule option to compilerOptions to enable JSON imports.

Poem

In the land of code, where bunnies hop,
We’ve made our numbers big, no need to stop!
With bigint in hand, we leap with glee,
Errors are caught, as clear as can be!
So let’s celebrate this fine upgrade,
Hopping through scripts, our joy won’t fade! 🐰✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9c01a4c and 8c91784.

📒 Files selected for processing (3)
  • contracts/test/arbitration/draw.ts (12 hunks)
  • contracts/test/integration/index.ts (9 hunks)
  • contracts/test/rng/index.ts (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 or @coderabbitai title 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

netlify bot commented Jun 19, 2024

Deploy Preview for kleros-v2-neo ready!

Name Link
🔨 Latest commit 8c91784
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-neo/deploys/672a0e37a6e4930008970a28
😎 Deploy Preview https://deploy-preview-1620--kleros-v2-neo.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

netlify bot commented Jun 19, 2024

Deploy Preview for kleros-v2-testnet ready!

Name Link
🔨 Latest commit 8c91784
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet/deploys/672a0e372c8e7800083c808d
😎 Deploy Preview https://deploy-preview-1620--kleros-v2-testnet.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

netlify bot commented Jun 19, 2024

Deploy Preview for kleros-v2-university ready!

Name Link
🔨 Latest commit 8c91784
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-university/deploys/672a0e37aecc9f000822b483
😎 Deploy Preview https://deploy-preview-1620--kleros-v2-university.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@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

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

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.

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

@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: 1

🧹 Outside diff range and nitpick comments (5)
contracts/scripts/keeperBot.ts (5)

195-197: Refactor gas estimation logic to reduce duplication

The gas estimation pattern is repeated across multiple functions. Consider creating a helper function to encapsulate this logic, enhancing maintainability and reducing code duplication.

For example:

async function estimateGasWithBuffer(estimateFunction: () => Promise<BigNumberish>, bufferPercentage = 50): Promise<BigNumberish> {
  const estimatedGas = await estimateFunction();
  return (toBigInt(estimatedGas) * toBigInt(100 + bufferPercentage)) / toBigInt(100);
}

Usage:

const gas = await estimateGasWithBuffer(() => sortition.passPhase.estimateGas());

Also applies to: 224-226, 288-290, 376-378


329-337: Simplify gas calculation using BigNumber arithmetic

The gas calculation can be made more readable by leveraging BigNumber methods. This ensures accurate calculations and improves code clarity.

Refactored example:

const estimatedGas = await kit.withdrawFeesAndRewards.estimateGas(
  disputeId,
  contribution.contributor.id,
  roundId,
  contribution.choice
);
const gas = estimatedGas.mul(150).div(100); // 50% extra gas

443-444: Simplify the block timestamp retrieval

The getBlockTime function can be simplified since block.timestamp should always be defined. This enhances readability.

Refactored code:

const getBlockTime = async () => {
  const block = await ethers.provider.getBlock("latest");
  return block.timestamp;
};

Line range hint 532-548: Prevent potential infinite loop in juror drawing

In the do...while loop starting at line 537, there's a risk of an infinite loop if numberOfMissingJurors does not decrease. Ensure numberOfMissingJurors is updated correctly within the loop.

Verify that getMissingJurors(dispute) correctly calculates the remaining jurors after each iteration and that the loop will eventually terminate.


652-652: Review repeated logging statements for current phase

The logging statement at line 652 is similar to previous logs. Ensure that this repetition is intentional and provides value.

If the phase has not changed since the last log, consider removing or updating the message to reflect any changes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b1e4632 and 434ccea.

📒 Files selected for processing (1)
  • contracts/scripts/keeperBot.ts (20 hunks)
🔇 Additional comments (7)
contracts/scripts/keeperBot.ts (7)

5-5: Import statement updated correctly for ethers v6

The import statement correctly includes toBigInt, BigNumberish, and getNumber from "ethers", aligning with ethers v6 usage.


156-157: Ensure accurate comparison of contract addresses

In the conditional statements at lines 156 and 166, currentRng is compared with randomizerRng.target and blockHashRNG.target. Verify that the properties being compared are of the same type and correctly represent contract addresses.

Ensure that currentRng, randomizerRng.target, and blockHashRNG.target are all normalized to the same format (e.g., lowercase strings) before comparison to prevent any mismatches due to case sensitivity.

Also applies to: 166-169


212-212: Handle potential issues with staticCall in passPeriod

The use of await core.passPeriod.staticCall(dispute.id); simulates the call but does not actually advance the period. Ensure this is the intended behavior and adjust if necessary.

If the goal is to check whether the call would succeed before actually executing it, consider handling the simulation results appropriately. Otherwise, replace staticCall with a direct call to perform the action.


355-361: Verify BigInt arithmetic in delayed stakes calculation

Ensure that the arithmetic operations involving delayedStakesRemaining and delayedStakes correctly handle BigInt values to prevent type errors.

Confirm that all variables involved are of type BigInt and operations like subtraction and comparison are valid.


465-473: Ensure correct phase enumeration mapping

In the functions isPhaseStaking, isPhaseGenerating, and isPhaseDrawing, verify that the phase index obtained from getNumber(await sortition.phase()) correctly maps to the PHASES array.

Ensure that the phases are in the correct order in the PHASES array and that there are no off-by-one errors.


397-403: Check consistency in arithmetic operations with BigInt

At lines 401-403, mixed arithmetic operations involve coherentCount, repartitions, and drawnJurors.length. Ensure that all operands are correctly converted to BigInt before performing calculations.

Explicitly convert drawnJurors.length and repartitions to BigInt if necessary:

const drawnJurorsLength = toBigInt(drawnJurors.length);
const repartitionsNumber = toBigInt(getNumber(repartitions));

592-592: Avoid redeclaring the variable dispute in loops

The variable dispute is redeclared in multiple loops within the same scope. This can cause confusion and potential errors. Consider renaming the variable or using block scoping (e.g., let instead of var).

Copy link

netlify bot commented Nov 4, 2024

Deploy Preview for kleros-v2-testnet-devtools ready!

Name Link
🔨 Latest commit 8c91784
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet-devtools/deploys/672a0e37c6730600085367b3
😎 Deploy Preview https://deploy-preview-1620--kleros-v2-testnet-devtools.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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

🧹 Outside diff range and nitpick comments (6)
contracts/test/rng/index.ts (1)

17-23: LGTM: Test updates properly implement new ethers patterns.

The changes correctly:

  • Update to the new staticCall syntax
  • Use toBigInt for safe large number handling

Consider adding a comment explaining the significance of testing with 2^255 to improve test documentation:

+  // Test with a very large number (2^255) to ensure proper handling of edge cases
   await rng.receiveRandomness(toBigInt(2) ** toBigInt(255));
contracts/package.json (1)

64-69: Consider documenting migration steps.

The upgrade from ethers v5 to v6 and related ecosystem changes may require updates in consuming projects.

Consider adding a MIGRATION.md file documenting:

  1. Steps to handle the ethers v6 migration
  2. Changes needed for hardhat plugin updates
  3. TypeChain type generation adjustments

Also applies to: 78-78, 81-81, 83-84, 87-88, 95-95

contracts/test/integration/index.ts (2)

73-73: Consider extracting magic numbers into named constants.

While the calculations are correct, the readability could be improved by extracting the multipliers into named constants.

+ const ARBITRATION_COST_MULTIPLIER = toBigInt(3);
+ const INITIAL_STAKE_MULTIPLIER = toBigInt(100);
+ const REDUCED_STAKE_MULTIPLIER = toBigInt(5);
+ const FINAL_STAKE_MULTIPLIER = toBigInt(4);

- const arbitrationCost = ONE_TENTH_ETH * toBigInt(3);
+ const arbitrationCost = ONE_TENTH_ETH * ARBITRATION_COST_MULTIPLIER;

- await pnk.approve(core.target, ONE_THOUSAND_PNK * toBigInt(100));
+ await pnk.approve(core.target, ONE_THOUSAND_PNK * INITIAL_STAKE_MULTIPLIER);

- await core.setStake(1, ONE_HUNDRED_PNK * toBigInt(5));
+ await core.setStake(1, ONE_HUNDRED_PNK * REDUCED_STAKE_MULTIPLIER);

- await core.setStake(1, ONE_THOUSAND_PNK * toBigInt(4));
+ await core.setStake(1, ONE_THOUSAND_PNK * FINAL_STAKE_MULTIPLIER);

Also applies to: 76-76, 85-87, 99-101


138-144: Extract hardcoded chain ID into a constant.

The hardcoded chain ID should be defined as a constant at the top of the file.

+ const CHAIN_ID = 31337;

  ["relayCreateDispute((bytes32,uint256,address,uint256,uint256,uint256,string,uint256,bytes))"](
    {
      foreignBlockHash: ethers.toBeHex(lastBlock.hash),
-     foreignChainID: 31337,
+     foreignChainID: CHAIN_ID,
      foreignArbitrable: arbitrable.target,
      foreignDisputeID: disputeId,
contracts/test/arbitration/draw.ts (2)

20-21: Simplify constant definitions using BigInt literals for clarity.

You can directly use BigInt literals for defining constants, which enhances readability and reduces unnecessary function calls.

Apply this diff to improve the code:

-      const ONE_TENTH_ETH = toBigInt(10) ** toBigInt(17);
-      const ONE_THOUSAND_PNK = toBigInt(10) ** toBigInt(21);
+      const ONE_TENTH_ETH = 10n ** 17n;
+      const ONE_THOUSAND_PNK = 10n ** 21n;

74-74: Ensure consistent calculation of childCourtMinStake and minStake.

The calculations for childCourtMinStake and minStake appear to be identical. Consider defining a single constant to avoid duplication and potential inconsistencies.

Apply this suggestion:

+      const THREE_HUNDRED_PNK = 10n ** 20n * 3n; // 300 PNK
       childCourtMinStake = THREE_HUNDRED_PNK;
       // ...
       const minStake = THREE_HUNDRED_PNK; // 300 PNK

Also applies to: 87-87

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 434ccea and f7b7ac8.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (6)
  • contracts/package.json (2 hunks)
  • contracts/scripts/keeperBot.ts (20 hunks)
  • contracts/test/arbitration/draw.ts (13 hunks)
  • contracts/test/integration/index.ts (10 hunks)
  • contracts/test/rng/index.ts (1 hunks)
  • kleros-sdk/package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • contracts/scripts/keeperBot.ts
🔇 Additional comments (7)
kleros-sdk/package.json (1)

38-38: LGTM! Verify changelog for breaking changes.

The minor version bump from 3.2.30 to 3.2.44 looks good. Since this aligns with the codebase's transition to newer numerical handling methods, this update is appropriate.

Let's verify the package's stability and recent activity:

✅ Verification successful

Package update is safe and actively maintained

The version bump from 3.2.30 to 3.2.44 is safe as:

  • Package shows consistent maintenance with regular patch releases
  • Latest version 3.2.44 was released recently (Oct 31, 2024)
  • No deprecation warnings found
  • All updates are patch-level changes within 3.2.x, indicating backward compatibility
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check package information and recent activity
# Expected results: Package should be actively maintained with recent updates

# Check npm package info
echo "Checking package info for @reality.eth/reality-eth-lib"
npm view @reality.eth/reality-eth-lib time --json | jq 'to_entries | .[] | select(.key|startswith("3.2.")) | {version: .key, date: .value}' 

# Check for deprecation notices
echo "Checking for any deprecation warnings"
npm view @reality.eth/reality-eth-lib deprecated

Length of output: 3474

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

3-3: LGTM: Import and initialization changes align with ethers update.

The changes properly modernize the ethers usage by:

  • Importing toBigInt for BigNumber handling
  • Using the new ABI coder initialization pattern

Also applies to: 8-8

contracts/test/integration/index.ts (3)

4-4: LGTM: Import change aligns with ethers upgrade.

The addition of toBigInt import is consistent with the PR's objective of updating the codebase to use newer ethers functionality.


173-179: LGTM: Round info assertions are correct.

The assertions are well-structured and the use of ethers.ZeroAddress aligns with the PR's objective of updating ethers constants.


209-209: LGTM: Logging function updated correctly.

The update to use ethers.formatUnits is consistent with the ethers upgrade and maintains clear logging output.

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

137-137: Confirm correct overload usage for function invocation.

Using arbitrable["createDispute(string)"] assumes the contract has an overloaded function. Verify that this is necessary and that the signature matches exactly. If there's only one createDispute function, you can call it directly.


113-113: Validate arithmetic operations with bigint.

Ensure that arithmetic operations involving bigint are correctly handled, as mixing number and bigint can lead to errors.

Run the following script to check for any instances where number types are mixed with bigint:

✅ Verification successful

Let me try a different search pattern to find arithmetic operations with bigint:


Let me check the specific line in question and its context:


Let me check what ONE_TENTH_ETH is defined as:


The arithmetic operations with bigint are correctly handled.

The code is safe because:

  • ONE_TENTH_ETH is defined as toBigInt(10) ** toBigInt(17), so it's already a bigint
  • The multiplication ONE_TENTH_ETH * toBigInt(3) involves two bigint values
  • All numeric values are properly converted to bigint using the toBigInt() function
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find instances where `number` types are used with `bigint`.

# Search for arithmetic operations mixing numbers and bigints.
rg --pcre2 "(toBigInt\([^)]+\)|\d+n)\s*[\+\-\*/]\s*\d+" -A 2

Length of output: 22412


Script:

#!/bin/bash
# Search for arithmetic operations with toBigInt
ast-grep --pattern 'toBigInt($_) * $_'

Length of output: 293


Script:

#!/bin/bash
# Get context around the line with ONE_TENTH_ETH
rg -A 2 -B 2 "ONE_TENTH_ETH \* toBigInt" 

Length of output: 763


Script:

#!/bin/bash
# Find the definition of ONE_TENTH_ETH
rg "ONE_TENTH_ETH\s*=" --type ts

Length of output: 213

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (7)
contracts/deploy/utils/klerosCoreHelper.ts (1)

16-19: Consider adding input validation for toBigInt conversion

While the change to toBigInt improves type safety, consider adding validation to handle potential conversion errors.

 if (pnkRate.rateInEth !== toBigInt(rateInEth) || pnkRate.rateDecimals !== rateDecimals) {
+  try {
+    const convertedRate = toBigInt(rateInEth);
+    if (pnkRate.rateInEth !== convertedRate || pnkRate.rateDecimals !== rateDecimals) {
+      console.log(`core.changeCurrencyRates(${erc20}, ${rateInEth}, ${rateDecimals})`);
+      await core.changeCurrencyRates(erc20, rateInEth, rateDecimals);
+    }
+  } catch (error) {
+    throw new Error(`Invalid rateInEth value for conversion: ${rateInEth}`);
+  }
-  console.log(`core.changeCurrencyRates(${erc20}, ${rateInEth}, ${rateDecimals})`);
-  await core.changeCurrencyRates(erc20, rateInEth, rateDecimals);
 }
contracts/test/rng/index.ts (2)

18-24: LGTM! Consider adding test documentation.

The updates to use .staticCall and toBigInt improve type safety. Consider adding a comment explaining the purpose of testing with 2 ** 255.

+  // Test with a very large number (2^255) to ensure proper handling of edge cases
   await rng.receiveRandomness(toBigInt(2) ** toBigInt(255));

27-48: Consider adding more test cases for better coverage.

The BlockHashRNG tests could benefit from additional cases:

  • Error handling for invalid block numbers
  • Edge cases with block numbers at uint256 boundaries
  • Cases with specific known block hashes

Would you like me to provide example test cases?

contracts/deploy/00-home-chain-arbitration-ruler.ts (2)

26-26: Consider defining fee constant with clear units.

While the BigInt literal is correct, consider improving readability by defining it as a named constant with clear units:

-const feeForJuror = 10n ** 17n;
+const FEE_FOR_JUROR_ETH = 0.1n;  // 0.1 ETH
+const feeForJuror = FEE_FOR_JUROR_ETH * 10n ** 18n;

37-44: Consider improving error handling specificity.

While the error handling is present, it could be more specific to handle different types of errors appropriately:

 try {
   await changeCurrencyRate(core, await pnk.getAddress(), true, 12225583, 12);
   await changeCurrencyRate(core, await dai.getAddress(), true, 60327783, 11);
   await changeCurrencyRate(core, await weth.getAddress(), true, 1, 1);
 } catch (e) {
-  console.error("failed to change currency rates:", e);
+  if (e instanceof Error) {
+    console.error(`Failed to change currency rates: ${e.message}`);
+    // Consider handling specific error types (e.g., ContractError)
+  } else {
+    console.error("Failed to change currency rates: Unknown error");
+  }
 }
contracts/test/evidence/index.ts (2)

32-35: Consider improving readability of BigInt calculations.

While the calculations are correct, the nested toBigInt calls make the code harder to read. Consider extracting intermediate values:

-  const totalCost = (toBigInt(arbitrationFee) * toBigInt(toBigInt(totalCostMultiplier))) / toBigInt(MULTIPLIER_DIVISOR);
-  const minRequiredDeposit = (totalCost * toBigInt(toBigInt(initialDepositMultiplier))) / toBigInt(MULTIPLIER_DIVISOR);
+  const totalCostMultiplierBig = toBigInt(totalCostMultiplier);
+  const initialDepositMultiplierBig = toBigInt(initialDepositMultiplier);
+  const totalCost = (toBigInt(arbitrationFee) * totalCostMultiplierBig) / MULTIPLIER_DIVISOR;
+  const minRequiredDeposit = (totalCost * initialDepositMultiplierBig) / MULTIPLIER_DIVISOR;

155-155: Consider improving error message for null receipt checks.

While the null checks are good, the error message could be more descriptive to aid in debugging.

-  if (receipt === null) throw new Error("Receipt is null");
+  if (receipt === null) throw new Error("Transaction receipt not found. The transaction may have failed or not been mined yet.");

Also applies to: 264-264

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f7b7ac8 and 0b88e87.

📒 Files selected for processing (8)
  • contracts/deploy/00-home-chain-arbitration-ruler.ts (3 hunks)
  • contracts/deploy/utils/klerosCoreHelper.ts (2 hunks)
  • contracts/package.json (2 hunks)
  • contracts/test/arbitration/ruler.ts (4 hunks)
  • contracts/test/evidence/index.ts (8 hunks)
  • contracts/test/rng/index.ts (1 hunks)
  • kleros-sdk/package.json (1 hunks)
  • web/src/components/EvidenceCard.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • kleros-sdk/package.json
🔇 Additional comments (19)
contracts/deploy/utils/klerosCoreHelper.ts (2)

1-2: LGTM! Import changes align with type improvements

The updated imports properly support the new type handling approach using toBigInt and BigNumberish from ethers.


5-5: Verify KlerosCoreRuler usage across the codebase

The addition of KlerosCoreRuler type looks good, but let's verify its usage.

✅ Verification successful

Based on the results, I can now generate the final response as the verification is complete. The results show that:

  1. KlerosCoreRuler is properly used across the codebase, particularly in:
    • Contract deployments (00-home-chain-arbitration-ruler.ts)
    • Tests (test/arbitration/ruler.ts)
    • Web development tools and components
  2. The changeCurrencyRate function is consistently used with KlerosCoreRuler in the same way as with other core variants, with identical currency rate configurations.

KlerosCoreRuler type addition is properly integrated

The type addition is correctly implemented and used consistently throughout the codebase. The changeCurrencyRate function is properly utilized with KlerosCoreRuler, following the same pattern as other core variants (Neo, University).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify KlerosCoreRuler usage and ensure consistent typing
# Expected: Find instances where KlerosCoreRuler is used with changeCurrencyRate

# Search for KlerosCoreRuler usage
echo "Checking KlerosCoreRuler usage:"
rg -p "KlerosCoreRuler" --type ts

# Search for changeCurrencyRate function calls
echo -e "\nChecking changeCurrencyRate calls:"
rg -p "changeCurrencyRate\(" --type ts -A 3

Length of output: 4723

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

3-3: LGTM! Good improvements to the ethers usage.

The changes align with modern ethers patterns:

  • Using toBigInt for better type safety
  • Extracting abiCoder as a reusable constant

Also applies to: 7-7


39-39: LGTM! Good updates to the ABI decoding pattern.

The changes to use abiCoder and ethers.getBytes align with modern ethers patterns.

Note: The critical issue with reversed test assertions mentioned in the past review comments still needs to be addressed.

Also applies to: 46-46

contracts/deploy/00-home-chain-arbitration-ruler.ts (3)

3-3: LGTM! Import changes align with modern ethers practices.

The updates to import statements properly reflect the transition from BigNumber to native BigInt and improve type safety with KlerosCoreRuler.

Also applies to: 7-7


28-36: LGTM! Contract deployment uses modern ethers patterns.

The update to use .target instead of .address aligns with current best practices for contract references.


55-55: LGTM! Consistent use of .target for contract references.

The update maintains consistency with modern ethers patterns for contract address references.

web/src/components/EvidenceCard.tsx (1)

92-94: Improved semantic HTML structure.

Good change! Using styled.p instead of styled.label is more semantically correct as the timestamp is displaying information rather than labeling a form control. This improves accessibility without affecting the visual styling.

contracts/package.json (3)

91-92: Verify hardhat plugin compatibility.

The updates to hardhat plugins look good:

These versions should be compatible with hardhat 2.22.15.

Also applies to: 99-99


82-82: Verify ethers v6 migration completeness.

The upgrade from ethers v5 to v6 (6.13.4) is significant. Based on the PR objectives, ensure all instances of:

  • ethers.constants.AddressZero are replaced with ethers.ZeroAddress
  • Contract interactions use .target instead of .address
  • Numerical handling uses toBigInt instead of BigNumber
#!/bin/bash
# Description: Verify ethers v6 migration completeness

# Test 1: Check for remaining AddressZero usage
echo "Checking for old AddressZero usage..."
rg "AddressZero" --type ts

# Test 2: Check for old .address usage in contract interactions
echo "Checking for .address usage..."
rg "\.address" --type ts -A 2

# Test 3: Check for remaining BigNumber usage
echo "Checking for BigNumber usage..."
rg "BigNumber" --type ts

Also applies to: 85-88


68-73: Verify compatibility between updated dependencies.

The updates to core dependencies look good, but please ensure compatibility between:

These versions should work together seamlessly for the ethers v6 migration.

✅ Verification successful

The previous results show extensive usage of ethers throughout the codebase, but we need to verify the specific versions and configurations to ensure compatibility between the updated dependencies. Let's check the actual imports and configurations.


Based on the results, I can now provide a final response:

Dependencies are correctly configured for ethers v6 migration

The codebase shows proper configuration and usage of the updated dependencies:

  • All ethers imports are using v6 patterns (toBigInt, parseEther, etc.)
  • No legacy @ethersproject/* imports found in application code
  • Hardhat config uses @nomicfoundation/hardhat-chai-matchers and @typechain/hardhat with correct versions
  • No v5-specific patterns like ethers.constants or ethers.utils found

The dependencies in package.json are compatible:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify potential compatibility issues after dependency updates

# Test 1: Check for remaining ethers v5 patterns that need updating
echo "Checking for v5 patterns that might need updates..."
rg "ethers\.(constants|utils|BigNumber|provider|Contract)\." --type ts

# Test 2: Check for old hardhat-ethers patterns
echo "Checking for old hardhat-ethers patterns..."
rg "import.*@nomiclabs/hardhat-ethers" --type ts

# Test 3: Check typechain generated files for v6 compatibility
echo "Checking typechain generated files..."
rg "import.*@ethersproject/" typechain-types/

Length of output: 52827


Script:

#!/bin/bash
# Check for ethers v6 specific imports and patterns
echo "Checking for ethers v6 specific imports..."
rg "import.*ethers" --type ts

# Check for typechain imports
echo "Checking for typechain imports..."
rg "import.*@typechain/" --type ts

# Check hardhat config for ethers plugin configuration
echo "Checking hardhat config..."
cat contracts/hardhat.config.ts

Length of output: 14273

contracts/test/arbitration/ruler.ts (4)

3-3: LGTM! Import and type safety improvements.

The changes improve type safety by using HardhatEthersSigner type and follow modern ethers.js practices with specific named imports.

Also applies to: 10-10


24-26: LGTM! Test setup modernization.

The changes appropriately update the test setup to use modern ethers.js patterns:

  • Using the new ABI encoding method
  • Simplified contract deployment
  • Updated parseEther usage

Also applies to: 31-31, 35-35


Line range hint 161-169: LGTM! Helper function improvements.

The deployContracts function has been appropriately simplified while maintaining type safety through explicit type assertions.


45-45: Verify consistent usage of updated ethers patterns.

The changes correctly implement ethers v6 patterns:

  • Using BigInt literals
  • Using ZeroAddress constant
  • Using .target instead of .address for contract references

However, let's verify that all contract address references have been updated consistently.

Also applies to: 56-56, 58-157

✅ Verification successful

Based on the search results, I can now generate the final response:

All contract address references have been correctly updated in test files

The search results confirm that the remaining .address references in the test files (contracts/test/arbitration/ruler.ts) are used appropriately for:

  • Event argument checks (e.g., dev.address in event assertions)
  • Balance and transfer operations
  • Contract deployment and initialization

The changes to use .target instead of .address for contract instances are consistently applied where needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining .address references that might have been missed
rg '\.address' --type ts

Length of output: 22543

contracts/test/evidence/index.ts (4)

3-5: LGTM! Type safety improvements are well implemented.

The migration to proper TypeScript types and the updated event handling logic align well with ethers.js v6 best practices. The getEmittedEvent function's type safety improvements will help catch potential issues at compile time.

Also applies to: 13-17


37-42: LGTM! Proper type annotations added.

The explicit type annotations for signers and evidenceID improve code clarity and type safety.


70-72: LGTM! Proper usage of contract.target instead of contract.address.

The change to use .target instead of .address aligns with ethers.js v6 best practices for accessing contract addresses.


226-259: Reusing existing comment about BigInt calculations monitoring.

Referring to the previous review comment about monitoring complex BigInt calculations in the moderation logic.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
.github/workflows/contracts-testing.yml (3)

43-45: Consider pinning Node.js version more specifically

While the update to actions/setup-node@v4 is good, consider pinning the Node.js version more specifically (e.g., 18.18.0) to ensure consistent builds across environments.

-        node-version: 18.x   
+        node-version: 18.18.0
🧰 Tools
🪛 yamllint

[error] 45-45: trailing spaces

(trailing-spaces)


77-78: Consider improving command readability

While the command is functionally correct, consider breaking it into multiple lines for better readability.

-        yarn hardhat coverage --solcoverjs ./.solcover.js --temp artifacts --testfiles './test/**/*.ts' --show-stack-traces
+        yarn hardhat coverage \
+          --solcoverjs ./.solcover.js \
+          --temp artifacts \
+          --testfiles './test/**/*.ts' \
+          --show-stack-traces

45-48: Remove trailing spaces

Remove trailing spaces from the following lines:

  • Line 45: After 18.x
  • Line 46: Empty line
  • Line 48: Empty line
🧰 Tools
🪛 yamllint

[error] 45-45: trailing spaces

(trailing-spaces)


[error] 46-46: trailing spaces

(trailing-spaces)


[error] 48-48: trailing spaces

(trailing-spaces)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0b88e87 and 205a708.

📒 Files selected for processing (1)
  • .github/workflows/contracts-testing.yml (3 hunks)
🧰 Additional context used
🪛 yamllint
.github/workflows/contracts-testing.yml

[error] 45-45: trailing spaces

(trailing-spaces)


[error] 46-46: trailing spaces

(trailing-spaces)


[error] 48-48: trailing spaces

(trailing-spaces)

🔇 Additional comments (4)
.github/workflows/contracts-testing.yml (4)

Line range hint 27-40: LGTM! Security improvement with version update

Good update from commit hash to semantic version for the security hardening runner. The egress policy is well-configured with specific allowed endpoints, following security best practices.

🧰 Tools
🪛 yamllint

[warning] 26-26: wrong indentation: expected 6 but found 4

(indentation)


47-47: LGTM! Version update

Good update to use the latest major version of checkout action.


Line range hint 50-60: LGTM! Cache configuration

Good update to use the latest major version of cache action while maintaining the robust caching strategy.

🧰 Tools
🪛 yamllint

[error] 45-45: trailing spaces

(trailing-spaces)


[error] 46-46: trailing spaces

(trailing-spaces)


[error] 48-48: trailing spaces

(trailing-spaces)


81-84: LGTM! Version update

Good update to use the latest major version of upload-artifact action.

🧰 Tools
🪛 yamllint

[error] 82-82: trailing spaces

(trailing-spaces)


[error] 83-83: trailing spaces

(trailing-spaces)

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 5, 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: 3

🧹 Outside diff range and nitpick comments (12)
contracts/deploy/utils/deployTokens.ts (1)

37-51: LGTM: Proper migration to ethers v6 patterns.

The changes correctly implement:

  • bigint parameter typing
  • .target usage instead of .address
  • Native bigint comparisons
  • Proper balance threshold check

Consider extracting the 20% threshold to a named constant for better readability:

+ const FAUCET_REFILL_THRESHOLD = 5n; // 20% threshold
- if (deployerBalance >= faucetFundingAmount && faucetBalance < faucetFundingAmount / 5n) {
+ if (deployerBalance >= faucetFundingAmount && faucetBalance < faucetFundingAmount / FAUCET_REFILL_THRESHOLD) {
contracts/deploy/00-home-chain-arbitration-ruler.ts (2)

25-25: Consider adding a comment explaining the fee value.

The bigint notation is correct and aligns with the migration from BigNumber. However, it might be helpful to add a comment explaining that this represents 0.1 ETH.

-  const feeForJuror = 10n ** 17n;
+  // 0.1 ETH in wei
+  const feeForJuror = 10n ** 17n;

36-41: Consider enhancing error handling with specific error types.

The contract interactions are correctly updated to use the latest ethers patterns. However, the error handling could be more specific.

  try {
    await changeCurrencyRate(core, await pnk.getAddress(), true, 12225583, 12);
    await changeCurrencyRate(core, await dai.getAddress(), true, 60327783, 11);
    await changeCurrencyRate(core, await weth.getAddress(), true, 1, 1);
-  } catch (e) {
-    console.error("failed to change currency rates:", e);
+  } catch (e: unknown) {
+    if (e instanceof Error) {
+      console.error("Failed to change currency rates:", e.message);
+    } else {
+      console.error("Failed to change currency rates with unknown error:", e);
+    }
+    throw e; // Re-throw to ensure deployment fails on error
   }
contracts/test/arbitration/index.ts (1)

43-54: Consider enhancing error message assertion

While the test correctly verifies access control, consider using a constant for the error message to maintain consistency across tests.

+const ERROR_KLEROS_CORE_ONLY = "Access not allowed: KlerosCore only.";

-    await expect(disputeKit.connect(deployer).createDispute(0, 0, ethers.toBeHex(3), "0x00")).to.be.revertedWith(
-      "Access not allowed: KlerosCore only."
+    await expect(disputeKit.connect(deployer).createDispute(0, 0, ethers.toBeHex(3), "0x00")).to.be.revertedWith(
+      ERROR_KLEROS_CORE_ONLY
     );
contracts/scripts/simulations/utils.ts (2)

84-84: Consider documenting the test-only nature of this value.

The change to parseEther is appropriate, but consider adding a comment explaining why we use a fixed 1 ETH value in local testing.

  if (isNetworkLocal(hre)) {
+   // Use 1 ETH as a simplified fee for local testing
    return hre.ethers.parseEther("1");
  } else {

154-154: Consider adding validation for negative duration edge case.

While the type conversion is correct, consider adding validation to ensure the calculation doesn't result in unexpected behavior with negative values.

-  const remainingDuration = ethers.getNumber(lastPeriodChange + periodDuration - toBigInt(now));
+  const calculatedDuration = lastPeriodChange + periodDuration - toBigInt(now);
+  const remainingDuration = ethers.getNumber(calculatedDuration < 0n ? 0n : calculatedDuration);
contracts/scripts/populateCourts.ts (2)

97-108: Add input validation to prevent potential issues.

While the bigint arithmetic is correct, consider adding input validation to prevent potential issues with negative values or zero.

-const truncateWei = (x: bigint) => (x / TEN_THOUSAND_GWEI) * TEN_THOUSAND_GWEI;
+const truncateWei = (x: bigint) => {
+  if (x < 0n) throw new Error("Negative values not supported");
+  return (x / TEN_THOUSAND_GWEI) * TEN_THOUSAND_GWEI;
+};

262-262: Document the hardcoded value in toBeHex.

The comment "Not accessible on-chain..." provides some context, but consider adding more detailed documentation about why the value 5 is used and what it represents.

-            ethers.toBeHex(5), // Not accessible on-chain, but has always been set to the same value so far.
+            ethers.toBeHex(5), // Represents the default sortition sum tree K value. Not accessible on-chain, but has been consistently set to 5 across all court implementations.
contracts/test/arbitration/draw.ts (3)

53-53: Add documentation for the RANDOM constant.

Consider adding a comment explaining the significance and derivation of this magic number, as it's used for deterministic testing.


87-89: Consider using named constants for better readability.

The magic numbers could be more self-documenting. Consider defining constants like:

-    const minStake = 3n * 10n ** 20n; // 300 PNK
-    const alpha = 10000n;
-    const feeForJuror = 10n * 17n;
+    const MIN_STAKE_PNK = 3n * 10n ** 20n; // 300 PNK
+    const ALPHA_PARTS_PER_10000 = 10000n;
+    const JUROR_FEE_WEI = 10n * 17n;

104-105: Consider using a test helper class for better organization.

The test helper types and functions could be moved to a separate test utility file for better maintainability and reuse across test files.

Example structure:

// test/helpers/draw.helper.ts
export class DrawTestHelper {
  static async setStake(wallet: HDNodeWallet, ...args): Promise<void>;
  static async expectFromDraw(drawTx: Promise<ContractTransactionResponse>, ...args): Promise<void>;
  // ... other helper methods
}
contracts/test/arbitration/staking.ts (1)

45-45: Consider using typed contract interactions consistently.

While the updates to use .target are correct, consider using typed function calls consistently throughout the tests.

For example, replace:

-await core["createDispute(uint256,bytes)"](2, extraData, { value: arbitrationCost });
+await core.createDispute(2, extraData, { value: arbitrationCost });

This improves type safety and readability while maintaining the same functionality.

Also applies to: 87-87, 304-304, 391-391, 397-397, 407-407

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 205a708 and 7fbcdc4.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (15)
  • contracts/deploy/00-home-chain-arbitration-ruler.ts (3 hunks)
  • contracts/deploy/upgrade-kleros-core.ts (3 hunks)
  • contracts/deploy/utils/deployTokens.ts (2 hunks)
  • contracts/package.json (2 hunks)
  • contracts/scripts/populateCourts.ts (8 hunks)
  • contracts/scripts/simulations/tasks.ts (22 hunks)
  • contracts/scripts/simulations/utils.ts (6 hunks)
  • contracts/test/arbitration/draw.ts (13 hunks)
  • contracts/test/arbitration/index.ts (2 hunks)
  • contracts/test/arbitration/staking-neo.ts (28 hunks)
  • contracts/test/arbitration/staking.ts (15 hunks)
  • contracts/test/evidence/index.ts (7 hunks)
  • contracts/test/integration/index.ts (9 hunks)
  • contracts/test/rng/index.ts (1 hunks)
  • contracts/tsconfig.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • contracts/package.json
  • contracts/test/evidence/index.ts
🧰 Additional context used
📓 Learnings (2)
contracts/test/arbitration/draw.ts (2)
Learnt from: jaybuidl
PR: kleros/kleros-v2#1620
File: contracts/test/arbitration/draw.ts:84-84
Timestamp: 2024-11-05T11:32:11.238Z
Learning: In TypeScript code using ethers.js version 6, `contract.target` should be used instead of `contract.address` to access a contract's address.
Learnt from: jaybuidl
PR: kleros/kleros-v2#1620
File: contracts/test/arbitration/draw.ts:98-98
Timestamp: 2024-11-05T11:32:29.452Z
Learning: In Ethers v6, `ethers.toBeHex` is the correct method to convert numbers to hex strings.
contracts/test/integration/index.ts (1)
Learnt from: jaybuidl
PR: kleros/kleros-v2#1620
File: contracts/test/integration/index.ts:104-109
Timestamp: 2024-11-05T11:31:03.535Z
Learning: In Ethereum, you cannot obtain a function's return value from event logs or the transaction receipt; return values are not included in logs or receipts.
🔇 Additional comments (82)
contracts/tsconfig.json (1)

3-5: LGTM! The addition of resolveJsonModule aligns with type safety goals.

This change enables proper TypeScript type checking for JSON imports, which is particularly useful for handling contract ABIs and configuration files.

Let's verify the JSON imports in the codebase:

✅ Verification successful

LGTM! The addition of resolveJsonModule is well-justified by actual JSON imports

The codebase shows extensive use of JSON imports across multiple TypeScript files, particularly for:

  • Contract artifacts from @kleros/kleros-v2-contracts
  • Configuration files for courts and policies
  • Test fixtures and templates
  • Git information

This confirms that enabling resolveJsonModule is necessary for proper type checking of these imports.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for JSON imports that will be affected by this configuration change

# Search for JSON imports in TypeScript files
echo "Checking for JSON imports that will benefit from type checking:"
rg -t ts 'import.*from.*\.json'

Length of output: 2921

contracts/deploy/upgrade-kleros-core.ts (3)

18-20: Please verify the feeForJuror calculation.

While the conversion to bigint is correct, the feeForJuror calculation 10n * 17n results in 170, which seems unusually low. Should this perhaps be using exponentiation like minStake?

Let's check how feeForJuror is calculated in other files:

#!/bin/bash
# Search for feeForJuror calculations in other files
rg -B 2 -A 2 "feeForJuror.*=.*" contracts/

34-34: Verify the sortition module configuration value.

The value 5 is being used as "Extra data for sortition module". Please confirm if this default K value is still appropriate after the ethers upgrade.

Let's check for other instances of this configuration:

#!/bin/bash
# Search for other sortition module configurations
rg -B 5 -A 5 "toBeHex.*\(5\)|hexlify.*\(5\)" contracts/

8-8: LGTM! Correct usage of ZeroAddress from ethers v6.

The change from AddressZero to ZeroAddress aligns with ethers v6 breaking changes.

Let's verify if there are any other ethers v5 constants still being used:

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

6-6: LGTM: Updated to ethers v6 AbiCoder initialization.

The change from ethers.utils.defaultAbiCoder to ethers.AbiCoder.defaultAbiCoder() correctly aligns with the ethers v6 API.


9-9: LGTM: Enhanced type safety with explicit typing.

Adding explicit IncrementalNG type improves code clarity and type checking.


17-23: LGTM: Updated to ethers v6 syntax and native BigInt.

The changes correctly implement:

  • Updated staticCall syntax (replacing callStatic)
  • Native BigInt usage with 2n ** 255n (replacing BigNumber)

28-28: LGTM: Updated to ethers v6 syntax with proper typing.

The changes correctly implement:

  • Explicit typing for better type safety
  • Updated AbiCoder usage with ethers.getBytes
  • Properly aligned test assertions with test descriptions

Also applies to: 38-39, 45-46


36-36: Verify block number assumptions in tests.

The test cases use specific block numbers (5 and 9876543210) to test past and future scenarios. Let's verify these assumptions are reliable across different test environments.

Also applies to: 43-43

✅ Verification successful

Let me gather more specific information about the block number usage in the RNG tests.


Let me check the BlockHashRNG contract implementation to understand how it uses block numbers.


Let me try to find the contract in a different way.


Let me try one last search without file type restriction.


Based on the contract implementation and test file analysis, I can now provide the final response:

Block number test assumptions are appropriate and well-designed

The test cases use block numbers 5 (past) and 9876543210 (future) to verify the BlockHashRNG contract's behavior, which is correct because:

  • The small number (5) ensures it's always in the past, testing the normal case where blockhash is available
  • The large number (9876543210) is guaranteed to be in the future for any realistic test environment, properly testing the future block case
  • The contract's implementation properly handles both cases, returning 0 for future blocks and using fallback mechanisms for past blocks
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify if the block numbers used in tests are appropriate
# for testing past vs future scenarios

# Get current block number
echo "Current block number:"
cast block-number 2>/dev/null || echo "Error: cast not available"

# Search for other block number usages in tests
echo -e "\nOther block number usages in tests:"
rg -n "block.*number" --type ts

Length of output: 1332


Script:

#!/bin/bash
# Get the full context of the RNG test file to understand block number usage
cat contracts/test/rng/index.ts

Length of output: 1942


Script:

#!/bin/bash
# Find and show the BlockHashRNG contract implementation
fd -e sol BlockHashRNG.sol -x cat {}

Length of output: 40


Script:

#!/bin/bash
# Find BlockHashRNG contract using ripgrep
rg -l "contract BlockHashRNG" --type solidity

Length of output: 80


Script:

#!/bin/bash
# Find BlockHashRNG contract implementation
fd BlockHashRNG -x cat {}

Length of output: 21811

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

1-1: LGTM: Import update aligns with ethers v6.

The change to import Contract directly from 'ethers' follows the recommended practice for the latest ethers version.


10-10: LGTM: Proper bigint conversion with parseUnits.

The change from BigNumber to bigint with parseUnits maintains precision while improving type safety.

Let's verify that all callers of this function have been updated to handle bigint:

✅ Verification successful

Let me verify the function signature and implementation to ensure the callers don't need updates.


Let me try a different pattern to find the function implementation.


Let me try one last search pattern to locate the function.


The bigint change is safe and properly handled

The function implementation shows that faucetFundingAmount is correctly used as bigint throughout the codebase:

  • It's passed directly to the deployFaucet function which expects bigint
  • Used in bigint arithmetic operations (faucetFundingAmount / 5n)
  • All callers found earlier only pass the default value, letting parseUnits handle the conversion
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for calls to deployERC20AndFaucet to ensure they're using bigint
rg -l "deployERC20AndFaucet" | xargs rg -A 3 "deployERC20AndFaucet\("

Length of output: 2410


Script:

#!/bin/bash
# Check the function signature and implementation
ast-grep --pattern 'async function deployERC20AndFaucet($_) {
  $$$
}'

Length of output: 72


Script:

#!/bin/bash
# Find the deployERC20AndFaucet function implementation
rg -A 20 "export async function deployERC20AndFaucet"

Length of output: 55


Script:

#!/bin/bash
# Find the deployERC20AndFaucet function in the utils directory
cat contracts/deploy/utils/deployTokens.ts

Length of output: 2011

contracts/deploy/00-home-chain-arbitration-ruler.ts (2)

6-6: LGTM! Import changes align with ethers update.

The new imports properly support the transition to the latest ethers version and improve type safety through TypeScript types.

Also applies to: 8-8


54-54: LGTM! Consistent use of .target property.

The deployment arguments correctly use the .target property for contract addresses.

contracts/test/arbitration/index.ts (4)

4-4: LGTM: Type safety improvements

The added type annotations and import of HardhatEthersSigner enhance type safety, aligning with the PR objectives.

Also applies to: 8-9


13-13: LGTM: Simplified contract deployment

The deployment setup has been streamlined by removing the unnecessary deployer parameter.


17-20: LGTM: Updated event assertions

The event assertions correctly use the new .target property instead of .address, aligning with the latest ethers version.


Line range hint 63-70: LGTM: Clear contract deployment setup

The deployment function correctly uses type assertions and fixture loading.

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

8-10: LGTM: Import changes align with contract updates.

The new imports correctly reflect the transition to updated contract types.


29-30: LGTM: Contract retrieval properly configured.

The new contract retrievals are correctly typed and properly integrated into the return object.

Also applies to: 40-40


61-61: Verify consistent usage of .target across the codebase.

The change from .address to .target is correct for the updated ethers version. Let's verify this pattern is consistently applied.

✅ Verification successful

Let me analyze the results and generate additional verification scripts to get a complete picture.

The previous results show many instances of .address usage, but we need to see the .target usage to understand if there's a consistent pattern or if some instances of .address should actually be .target. This will help determine if there are any inconsistencies in the ethers.js v6 migration.


Based on the search results, I can now generate the final response since I have enough information to make a determination about the usage of .address vs .target.

Review of .address vs .target usage shows correct patterns

The codebase shows a clear and correct pattern in the usage of .address and .target:

  • .target is used when interacting with contract instances (e.g., core.target, disputeKit.target)
  • .address is used appropriately for:
    • EOA addresses (e.g., wallet.address, deployer.address)
    • Storage/state variables (e.g., klerosCoreAddress)
    • Configuration and deployment records
    • Direct address comparisons

The change from .address to .target in the reviewed line is correct and consistent with the codebase's patterns for ethers.js v6 usage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining .address usage that might need updating
rg -g '*.ts' '\.address' contracts/

Length of output: 18930


Script:

#!/bin/bash
# Search for .target usage to compare with .address
rg -g '*.ts' '\.target' contracts/

Length of output: 9843

contracts/test/integration/index.ts (8)

21-25: LGTM! Well-defined constants using BigInt literals.

The constants are clearly defined using BigInt literals (n suffix) which aligns with the migration from BigNumber to native bigint.


41-51: LGTM! Contract instance declarations are properly typed.


72-72: LGTM! Stake operations and balance checks are properly updated.

The code correctly uses BigInt operations for calculations and properly accesses contract addresses using .target.

Also applies to: 75-75, 84-84, 86-86, 98-98, 100-100


104-109: LGTM! Correct approach for obtaining dispute ID.

The code appropriately uses debug_traceTransaction to obtain the return value, as it cannot be obtained from event logs.


113-113: LGTM! Robust error handling for block-related operations.

The code properly checks for null values and throws descriptive errors, improving error handling reliability.

Also applies to: 117-117, 119-119, 123-133


137-137: LGTM! Relayer transaction setup is properly configured.

The code correctly uses ethers v6 syntax for data encoding and properly accesses contract addresses.

Also applies to: 139-139, 141-141, 143-143, 152-152


162-165: LGTM! Phase transitions and RNG handling are correct.

The code properly handles phase transitions and random number generation using appropriate ethers v6 methods.


172-172: LGTM! Final assertions and logging are properly updated.

The code correctly:

  • Uses BigInt for token calculations
  • Uses ZeroAddress instead of deprecated AddressZero
  • Uses updated formatUnits method for logging

Also applies to: 176-178, 196-197, 208-208

contracts/scripts/populateCourts.ts (3)

3-3: LGTM! Import changes align with ethers update.

The updated import statement correctly brings in the new ethers utilities for numeric conversions.


41-43: LGTM! Constants properly defined using bigint literals.

The constants are correctly defined using the n suffix for bigint literals, which is the recommended approach for large numeric values in modern JavaScript/TypeScript.


216-216: Verify number conversion safety.

The toNumber() conversion could potentially lose precision for very large numbers. Consider adding a range check or using a safer conversion method if large values are possible.

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

141-145: 🛠️ Refactor suggestion

Improve transaction receipt error handling.

The current implementation has multiple separate null checks. Consider consolidating them and using more descriptive error messages:

-    if (tx.blockNumber === null) throw new Error("tx.blockNumber is null");
-    const trace = await network.provider.send("debug_traceTransaction", [tx.hash]);
-    const [disputeId] = abiCoder.decode(["uint"], ethers.getBytes(`${trace.returnValue}`));
-    const lastBlock = await ethers.provider.getBlock(tx.blockNumber - 1);
-    if (lastBlock?.hash === null || lastBlock?.hash === undefined) throw new Error("lastBlock is null || undefined");
+    const receipt = await tx.wait();
+    if (!receipt.blockNumber) {
+      throw new Error("Transaction was not mined: missing block number");
+    }
+    const trace = await network.provider.send("debug_traceTransaction", [tx.hash]);
+    const [disputeId] = abiCoder.decode(["uint"], ethers.getBytes(`${trace.returnValue}`));
+    const lastBlock = await ethers.provider.getBlock(receipt.blockNumber - 1);
+    if (!lastBlock?.hash) {
+      throw new Error("Failed to retrieve previous block hash");
+    }

Likely invalid or redundant comment.

contracts/test/arbitration/staking.ts (4)

9-15: LGTM! Helper functions and encoding updated to latest ethers practices.

The changes improve type safety and readability by:

  • Using ethers.parseUnits for consistent unit conversion
  • Using defaultAbiCoder for type-safe parameter encoding

17-22: LGTM! Enhanced type safety with explicit type annotations.

Added proper TypeScript type annotations for all contract instances, improving code maintainability and IDE support.


42-43: LGTM! Updated numerical operations to use native bigint.

Replaced BigNumber operations with native JavaScript bigint arithmetic using the n suffix, which:

  • Improves code readability
  • Reduces dependency on external BigNumber implementations
  • Provides native type safety

Also applies to: 388-389


128-129: LGTM! Updated to use latest ethers ZeroAddress constant.

Consistently updated all zero address checks to use ethers.ZeroAddress instead of the deprecated AddressZero.

Also applies to: 191-192, 255-255, 278-279, 344-344, 370-371

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

33-36: LGTM: Improved type safety in extraData encoding.

The update to use ethers.AbiCoder.defaultAbiCoder().encode() with explicit type definitions enhances type safety and readability.


38-48: Enhanced type safety with explicit type definitions.

Good addition of explicit type definitions using HardhatEthersSigner for better type safety and code maintainability.


400-409: LGTM: Improved numerical handling with bigint.

The update to use bigint for calculations (e.g., ETH(0.1) * 3n) improves type safety and prevents potential numerical precision issues.


469-470: LGTM: Consistent usage of ethers.ZeroAddress.

The update from AddressZero to ethers.ZeroAddress is consistently applied across all delayed stakes clearing operations, aligning with the latest ethers library conventions.

Also applies to: 534-535, 623-624, 717-718


735-737: LGTM: Updated contract interaction patterns.

The contract creation and interaction patterns have been properly updated to use the latest ethers conventions, maintaining the same functionality while improving code consistency.


Line range hint 1-748: Verify consistent usage of updated ethers patterns.

The file has been updated to use the latest ethers patterns. Let's verify that all contract interactions follow the new conventions.

✅ Verification successful

Let me modify the search patterns to avoid using look-around assertions and verify the ethers patterns.


Based on the search results, I can see that there are still instances of .address being used in the code, while the file also uses the newer .target pattern. This inconsistency should be addressed. Let me verify if these .address usages are for signers (where it's correct) or for contract instances (where it should be .target).


Based on the context gathered, I can now provide the final verification response:

All ethers patterns are correctly used in this file

The usage of .address and .target is consistent with the latest ethers patterns:

  • .address is correctly used only for signers/wallets (e.g., juror.address, guardian.address)
  • .target is correctly used for contract instances (e.g., core.target, resolver.target)
  • Other ethers patterns like parseUnits and ZeroAddress are also properly used
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that old ethers patterns are not used

# Check for any remaining instances of old patterns
echo "Checking for old ethers patterns..."
rg -l 'AddressZero|utils\.parseUnits|\.address(?!\.set)' contracts/test/arbitration/

# Check for consistent usage of new patterns
echo "Checking for consistent usage of new patterns..."
rg -l 'ZeroAddress|parseUnits(?!.*utils)|\.target' contracts/test/arbitration/

Length of output: 914


Script:

#!/bin/bash
# Check for old ethers patterns
echo "Checking for old ethers patterns..."
rg 'AddressZero|utils\.parseUnits|\.address' contracts/test/arbitration/staking-neo.ts

# Check for new ethers patterns
echo "Checking for new ethers patterns..."
rg 'ZeroAddress|parseUnits|\.target' contracts/test/arbitration/staking-neo.ts

Length of output: 4075


Script:

#!/bin/bash
# Get more context around .address usage
echo "Checking context of .address usage..."
rg -B 2 -A 2 '\.address' contracts/test/arbitration/staking-neo.ts

Length of output: 4175

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

2-2: ****
Consider importing only needed modules.

You are importing BigNumberish and AddressLike but they are not used in the visible code. If they are used in the remainder of the file, this is fine; otherwise, consider removing unnecessary imports to keep the code clean and efficient.


38-41: LGTM!

The changes to the approvePNKFunctionArgs type and the usage of ethers.parseEther are correct and consistent with the updated ethers library.


63-63: LGTM!

The change to use bigint for the setStakeFunctionArgs type is correct and consistent with the updated ethers library.


80-88: LGTM!

The changes to use native bigint for numeric values like minStake, alpha, feeForJuror, and jurorsForCourtJump are correct and consistent with the updated ethers library. The usage of ethers.toBeHex for sortitionSumTreeK is also appropriate.


106-106: LGTM!

The change to use tx?.hash instead of tx?.transactionHash is correct and consistent with the updated structure of transaction objects in the ethers library.


109-109: LGTM!

The change to use tx?.blockNumber instead of tx.blockNumber is correct and consistent with the updated structure of transaction objects in the ethers library.


137-137: ****
Ensure type safety for evidenceGroupID.

The conversion of a random byte array to a bigint using toBigInt might not always result in a valid numeric value. This could lead to unpredictability in evidenceGroupID. Consider adding error handling or validations.


142-142: LGTM!

The change to use "createDispute(string)" instead of the previously encoded arbitratorExtraData is correct and consistent with the updated method signature for creating disputes.


151-151: LGTM!

The change to use logs[logs.length - 1]?.args?._disputeID instead of logs[logs.length - 1].args._disputeID is correct and consistent with the updated structure of event logs in the ethers library.


175-175: LGTM!

The change to use tx?.hash instead of tx.transactionHash is correct and consistent with the updated structure of transaction objects in the ethers library.


189-189: ****
Consider adding a maximum retry limit.

To prevent potential infinite loops, consider implementing a maximum number of retries for the RNG readiness check.


214-214: LGTM!

The change to use tx?.hash instead of tx.transactionHash is correct and consistent with the updated structure of transaction objects in the ethers library.


235-235: LGTM!

The change to use tx?.hash instead of tx.transactionHash is correct and consistent with the updated structure of transaction objects in the ethers library.


257-258: LGTM!

The change to use ethers.solidityPackedKeccak256 with the correct argument types and the usage of ethers.toBeHex for the commit hash are appropriate and consistent with the updated ethers library.


308-308: LGTM!

The change to use BigNumberish for the value property in the fundAppealFunctionArgs type is correct and consistent with the updated ethers library.


320-320: LGTM!

The change to use fundAppealTx?.hash instead of fundAppealTx.transactionHash is correct and consistent with the updated structure of transaction objects in the ethers library.


338-338: LGTM!

The change to use executeTx?.hash instead of executeTx.transactionHash is correct and consistent with the updated structure of transaction objects in the ethers library.


341-341: LGTM!

The change to use executeRulingTx?.hash instead of executeRulingTx.transactionHash is correct and consistent with the updated structure of transaction objects in the ethers library.


364-372: LGTM!

The changes to use typed variables for the parameters passed to the withdrawFeesAndRewards function are correct and consistent with the updated type definitions in the ethers library. The usage of BigNumberish and AddressLike types ensures type safety and clarity.


375-375: LGTM!

The change to use the typed variables _disputeId, _beneficiary, _coreRoundId, and _choice as arguments for the withdrawFeesAndRewards function is correct and consistent with the updated type definitions.


377-377: LGTM!

The change to use withdrawTx?.hash instead of withdrawTx.transactionHash is correct and consistent with the updated structure of transaction objects in the ethers library.


415-415: LGTM!

The change to use ethers.randomBytes(32) instead of a hardcoded value for the relay function is correct and consistent with the updated ethers library.


438-439: LGTM!

The change to use ethers.parseEther for parsing the pnkperwallet amount is correct and consistent with the updated ethers library.


458-458: LGTM!

The change to use evidenceModule instead of disputeKitClassic for submitting evidence is correct and consistent with the updated contract being interacted with.


464-465: LGTM!

The change to use tx?.hash instead of tx.transactionHash is correct and consistent with the updated structure of transaction objects in the ethers library.


479-479: LGTM!

The usage of hre.run to execute the simulate:split-pnk task with the correct arguments is appropriate and consistent with the task definition.


482-482: LGTM!

The usage of hre.run to execute the simulate:stake-five-jurors task with the correct arguments is appropriate and consistent with the task definition.


489-489: LGTM!

The usage of hre.run to execute the simulate:create-dispute task with the correct arguments is appropriate and consistent with the task definition.


495-495: LGTM!

The change to use ethers.parseEther for parsing the feeforjuror amount is correct and consistent with the updated ethers library.


500-500: LGTM!

The change to use ethers.getNumber for converting the minStakingTime to a number is correct and consistent with the updated ethers library.


503-503: LGTM!

The usage of hre.run to execute the simulate:to-freezing-and-generating-phase task with the correct arguments is appropriate and consistent with the task definition.


507-507: LGTM!

The usage of hre.run to execute the simulate:wait-for-rng task is appropriate and consistent with the task definition.


513-513: LGTM!

The usage of hre.run to execute the simulate:pass-phase-draw-unfreeze task with the correct arguments is appropriate and consistent with the task definition.


520-520: LGTM!

The usage of hre.run to execute the simulate:submit-evidence task with the correct arguments is appropriate and consistent with the task definition.


528-528: LGTM!

The usage of hre.run to execute the simulate:pass-period task with the correct arguments is appropriate and consistent with the task definition.


536-536: LGTM!

The usage of hre.run to execute the simulate:cast-vote task with the correct arguments is appropriate and consistent with the task definition.


546-546: LGTM!

The usage of hre.run to execute the simulate:pass-period task with the correct arguments is appropriate and consistent with the task definition.


550-550: LGTM!

The usage of hre.run to execute the simulate:fund-appeal task with the correct arguments is appropriate and consistent with the task definition.


559-559: LGTM!

The usage of hre.run to execute the simulate:pass-period task with the correct arguments is appropriate and consistent with the task definition.


563-563: LGTM!

The usage of hre.run to execute the simulate:execute-ruling task with the correct arguments is appropriate and consistent with the task definition.

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 5, 2024
@jaybuidl jaybuidl force-pushed the chore(hardhat)/hardhat-ether-version-update branch from 7fbcdc4 to 8c91784 Compare November 5, 2024 12:23
@jaybuidl jaybuidl enabled auto-merge November 5, 2024 12:24
Copy link

codeclimate bot commented Nov 5, 2024

Code Climate has analyzed commit 8c91784 and detected 59 issues on this pull request.

Here's the issue category breakdown:

Category Count
Complexity 3
Duplication 48
Style 8

View more on Code Climate.

Copy link

sonarqubecloud bot commented Nov 5, 2024

@jaybuidl jaybuidl added this pull request to the merge queue Nov 5, 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

🧹 Outside diff range and nitpick comments (4)
contracts/test/integration/index.ts (2)

75-75: Consider extracting repeated stake and balance check pattern.

The stake operations and balance checks follow a consistent pattern. Consider creating a helper function to reduce code duplication.

async function setStakeAndVerifyBalance(amount: bigint) {
  await core.setStake(1, amount);
  const balance = await sortitionModule.getJurorBalance(deployer, 1);
  expect(balance.totalStaked).to.equal(amount);
  expect(balance.totalLocked).to.equal(0);
  logJurorBalance(balance);
}

Also applies to: 84-84, 86-86, 98-98, 100-100


196-197: Consider adding more specific event parameter checks.

While the event assertions are correct, consider adding more specific checks for the event parameters using withArgs to ensure the exact values are emitted.

expect(tx4)
  .to.emit(core, "Ruling")
  .withArgs(
    homeGateway.target,
    0,  // disputeID
    0   // ruling
  );
contracts/test/arbitration/draw.ts (2)

141-145: Consider consolidating transaction receipt handling.

The transaction receipt and block number checks could be simplified by using the receipt from tx.wait().

Consider this refactor:

-    await tx.wait();
-    if (tx.blockNumber === null) throw new Error("tx.blockNumber is null");
-    const trace = await network.provider.send("debug_traceTransaction", [tx.hash]);
-    const [disputeId] = abiCoder.decode(["uint"], ethers.getBytes(`${trace.returnValue}`));
-    const lastBlock = await ethers.provider.getBlock(tx.blockNumber - 1);
+    const receipt = await tx.wait();
+    if (!receipt) throw new Error("Failed to get transaction receipt");
+    const trace = await network.provider.send("debug_traceTransaction", [tx.hash]);
+    const [disputeId] = abiCoder.decode(["uint"], ethers.getBytes(`${trace.returnValue}`));
+    const lastBlock = await ethers.provider.getBlock(receipt.blockNumber - 1);

207-208: Consider adding more descriptive logging.

The console logs for draw iterations could be more informative to aid in debugging.

Consider this enhancement:

-    console.log((await core.getRoundInfo(0, 0)).drawIterations);
+    console.log(`Draw iterations for round 0: ${(await core.getRoundInfo(0, 0)).drawIterations}`);

Also applies to: 270-271, 306-307, 368-369

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7fbcdc4 and 8c91784.

📒 Files selected for processing (3)
  • contracts/test/arbitration/draw.ts (12 hunks)
  • contracts/test/integration/index.ts (9 hunks)
  • contracts/test/rng/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • contracts/test/rng/index.ts
🧰 Additional context used
📓 Learnings (2)
contracts/test/arbitration/draw.ts (2)
Learnt from: jaybuidl
PR: kleros/kleros-v2#1620
File: contracts/test/arbitration/draw.ts:84-84
Timestamp: 2024-11-05T11:32:11.238Z
Learning: In TypeScript code using ethers.js version 6, `contract.target` should be used instead of `contract.address` to access a contract's address.
Learnt from: jaybuidl
PR: kleros/kleros-v2#1620
File: contracts/test/arbitration/draw.ts:98-98
Timestamp: 2024-11-05T11:32:29.452Z
Learning: In Ethers v6, `ethers.toBeHex` is the correct method to convert numbers to hex strings.
contracts/test/integration/index.ts (1)
Learnt from: jaybuidl
PR: kleros/kleros-v2#1620
File: contracts/test/integration/index.ts:104-109
Timestamp: 2024-11-05T11:31:03.535Z
Learning: In Ethereum, you cannot obtain a function's return value from event logs or the transaction receipt; return values are not included in logs or receipts.
🔇 Additional comments (11)
contracts/test/integration/index.ts (5)

21-24: LGTM! Well-defined BigInt constants.

The constants are properly defined using BigInt literals, which is the recommended approach for handling large numbers in modern JavaScript/TypeScript.


41-51: LGTM! Contract instances are properly typed.

The declarations now use semicolons and have proper TypeScript types.


104-109: LGTM! Correct approach for obtaining return value.

Using debug_traceTransaction is the appropriate way to obtain the function's return value, as it cannot be retrieved from event logs or transaction receipts.


123-133: LGTM! Robust error handling for block operations.

The error handling has been improved with proper null checks and descriptive error messages, replacing the abrupt process.exit().


137-143: LGTM! Consistent use of .target for contract addresses.

The code correctly uses the .target property instead of .address for contract references, following the updated ethers pattern.

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

3-3: LGTM! Import changes align with ethers v6 migration.

The imports have been correctly updated to use toBigInt instead of BigNumber, and proper types from ethers v6 are imported.

Also applies to: 11-11


20-21: LGTM! Constants properly defined using bigint literals.

The migration from BigNumber to native bigint is correctly implemented using the n suffix for bigint literals.

Also applies to: 53-53


42-52: LGTM! Variable declarations properly typed.

Variable declarations are properly typed, including the explicit bigint type for stake-related variables.


77-84: LGTM! Contract deployment and RNG setup properly implemented.

The deployment of IncrementalNG and subsequent RNG setup are correctly implemented. The use of rng.target is correct as per ethers v6 API.


196-202: LGTM! Balance checks properly updated to use bigint.

The balance checks and assertions have been correctly updated to use bigint values and operations. The use of toBigInt for conversions is appropriate.

Also applies to: 224-226, 230-232, 323-324, 329-331, 385-387, 391-393


212-212: LGTM! Consistent null checks for transaction receipts.

The null checks for transaction receipts are consistently implemented across all test cases.

Also applies to: 311-311, 373-373

Merged via the queue into dev with commit 3b864e0 Nov 5, 2024
23 of 27 checks passed
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (16)
contracts/deploy/utils/deployTokens.ts (1)

37-51: Consider adding error handling for token transfers.

The changes correctly implement:

  • Transition to bigint types
  • Usage of .target instead of .address
  • Native bigint operations

However, the token transfer could benefit from additional error handling.

Consider adding try-catch and event logging:

-    await erc20.transfer(faucet.target, faucetFundingAmount);
+    try {
+      const tx = await erc20.transfer(faucet.target, faucetFundingAmount);
+      await tx.wait();
+      console.log(`Successfully funded ${ticker}Faucet with ${faucetFundingAmount}`);
+    } catch (error) {
+      console.error(`Failed to fund ${ticker}Faucet:`, error);
+      throw error;
+    }
contracts/deploy/00-home-chain-arbitration-ruler.ts (1)

36-41: Consider documenting the currency rate parameters.

While the implementation is correct, the magic numbers in changeCurrencyRate calls (e.g., 12225583, 12) would benefit from comments explaining their significance and calculation.

-    await changeCurrencyRate(core, await pnk.getAddress(), true, 12225583, 11);
+    // Rate: 1 PNK = 0.012225583 USD (12 decimals precision)
+    await changeCurrencyRate(core, await pnk.getAddress(), true, 12225583, 11);
contracts/test/arbitration/index.ts (1)

17-33: Consider extracting magic numbers into constants

The test assertions look good, but consider extracting magic numbers (e.g., 256, 10000) into named constants for better maintainability and readability.

Example:

const JURORS_FOR_COURT_JUMP = 256;
const ALPHA = 10000;
const DEFAULT_TIMES_PER_PERIOD = [0, 0, 0, 10];

Also applies to: 35-39

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

154-154: Consider adding type annotations for improved type safety.

The calculation update correctly uses toBigInt and ethers.getNumber, but could benefit from explicit type annotations.

Consider adding type annotations:

-  const remainingDuration = ethers.getNumber(lastPeriodChange + periodDuration - toBigInt(now));
+  const remainingDuration: number = ethers.getNumber(lastPeriodChange + periodDuration - toBigInt(now));
contracts/scripts/populateCourts.ts (2)

97-108: Consider documenting magic numbers in parametersProductionToDev.

While the bigint conversion is correct, consider documenting the reasoning behind the hardcoded values:

  • Division by 10000n in minStake calculation
  • Using 0.00001 ether for feeForJuror
  • Using [120, 120, 120, 240] for timesPerPeriod

Line range hint 216-225: Consider enhancing error handling and logging.

For a deployment script, consider:

  1. Using a proper logging library with levels (debug/info/warn/error)
  2. Adding try-catch blocks around core operations
  3. Implementing a proper rollback mechanism for failed court updates
contracts/test/evidence/index.ts (2)

13-17: Consider improving type safety of the event handling.

The eventName parameter is typed as any. Consider using a more specific type to improve type safety.

-function getEmittedEvent(eventName: any, receipt: ContractTransactionReceipt): EventLog {
+function getEmittedEvent(eventName: string, receipt: ContractTransactionReceipt): EventLog {

155-155: Consider improving error messages for receipt validation.

The error message for null receipts could be more descriptive to aid in debugging.

-if (receipt === null) throw new Error("Receipt is null");
+if (receipt === null) throw new Error("Transaction receipt not found. The transaction may have failed or not been mined yet.");

Also applies to: 264-264

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

218-218: Standardize null checks across test cases.

The test cases use inconsistent patterns for null checks. Standardize them for better maintainability.

Apply these diffs:

-      if (tx?.blockNumber === undefined) throw new Error("txBlockNumber is null");
+      if (!tx?.blockNumber) throw new Error("Failed to get transaction block number");

-      if (tx === null) throw new Error("tx is null");
+      if (!tx) throw new Error("Failed to get transaction receipt");

-      if (tx === null) throw new Error("tx is null");
+      if (!tx) throw new Error("Failed to get transaction receipt");

Also applies to: 309-309, 371-371

contracts/test/arbitration/staking.ts (2)

42-43: Consider improving bigint arithmetic readability

While the bigint arithmetic is correct, consider extracting magic numbers into named constants for better readability.

+const MIN_JURORS = 3n;
+const ARBITRATION_COST_PER_JUROR = ETH(0.1);
-const arbitrationCost = ETH(0.1) * 3n;
+const arbitrationCost = ARBITRATION_COST_PER_JUROR * MIN_JURORS;

Also applies to: 388-389


128-129: Consider extracting repeated assertions into helper functions

The test file contains multiple identical assertions for checking delayed stakes. Consider extracting these into a helper function to reduce duplication and improve maintainability.

const assertDelayedStakesCleared = async (indices: number[]) => {
  for (const index of indices) {
    expect(await sortition.delayedStakes(index)).to.be.deep.equal([
      ethers.ZeroAddress,
      0,
      0,
      false
    ]);
  }
};

Usage:

-expect(await sortition.delayedStakes(1)).to.be.deep.equal([ethers.ZeroAddress, 0, 0, false]);
-expect(await sortition.delayedStakes(2)).to.be.deep.equal([ethers.ZeroAddress, 0, 0, false]);
+await assertDelayedStakesCleared([1, 2]);

Also applies to: 191-192, 278-279, 370-371

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

111-111: Consider adding error handling for RNG relay

The randomizer.relay() call could benefit from try-catch error handling to gracefully handle potential RNG failures.

-    await randomizer.relay(rng.target, 0, ethers.randomBytes(32));
+    try {
+      await randomizer.relay(rng.target, 0, ethers.randomBytes(32));
+    } catch (error) {
+      console.error('RNG relay failed:', error);
+      throw error;
+    }

469-470: Consider using more descriptive test assertions

The assertions checking for ethers.ZeroAddress could benefit from more descriptive comments explaining the expected state. Current comments like "the 1st delayed stake got deleted" could be more specific about why the address should be zero.

-  expect(await sortition.delayedStakes(1)).to.be.deep.equal([ethers.ZeroAddress, 0, 0, false]); // the 1st delayed stake got deleted
+  expect(await sortition.delayedStakes(1)).to.be.deep.equal([ethers.ZeroAddress, 0, 0, false]); // Verify stake is cleared: address should be zero, amounts zero, and not transferred

Also applies to: 534-535, 600-601, 623-624, 691-692, 717-718


735-735: Consider adding more assertions for inactive juror state

The test for inactive juror could benefit from additional assertions to verify the complete state after unstaking, such as checking balances and stake amounts.

 await core.execute(0, 0, 1); // 1 iteration should unstake from both courts
 expect(await sortition.getJurorCourtIDs(deployer)).to.be.deep.equal([]);
+// Add assertions to verify complete unstaking
+expect(await sortition.getJurorBalance(deployer, 1)).to.be.deep.equal([0, 0, 0, 0]);
+expect(await sortition.getJurorBalance(deployer, 2)).to.be.deep.equal([0, 0, 0, 0]);
contracts/scripts/simulations/tasks.ts (2)

86-86: Simplify type annotation for timesPerPeriod

The explicit annotation of each element as BigNumberish can be simplified for better readability.

Consider this refactor:

-const timesPerPeriod = [300, 300, 300, 300] as [BigNumberish, BigNumberish, BigNumberish, BigNumberish];
+const timesPerPeriod: BigNumberish[] = [300, 300, 300, 300];

Line range hint 479-563: Consider adding error handling and logging

The simulation tasks involve multiple asynchronous operations that could fail. Adding try-catch blocks and logging around each task run can help with debugging and improve robustness.

Example enhancement:

 console.log("split pnk.....");
+try {
   await hre.run("simulate:split-pnk", { walletindex: operator.toString(), pnkperwallet: stake.toString() });
+} catch (e) {
+  console.error("Error in simulate:split-pnk:", e);
+}

 console.log("stake five jurors....");
+try {
   await hre.run("simulate:stake-five-jurors", {
     walletindexes: "0,1,2,3,4",
     pnkamounts: `${stake},${stake},${stake},${stake},${stake}`,
     courtid: courtId,
   });
+} catch (e) {
+  console.error("Error in simulate:stake-five-jurors:", e);
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 205a708 and 9c01a4c.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (15)
  • contracts/deploy/00-home-chain-arbitration-ruler.ts (3 hunks)
  • contracts/deploy/upgrade-kleros-core.ts (3 hunks)
  • contracts/deploy/utils/deployTokens.ts (2 hunks)
  • contracts/package.json (2 hunks)
  • contracts/scripts/populateCourts.ts (8 hunks)
  • contracts/scripts/simulations/tasks.ts (22 hunks)
  • contracts/scripts/simulations/utils.ts (6 hunks)
  • contracts/test/arbitration/draw.ts (13 hunks)
  • contracts/test/arbitration/index.ts (2 hunks)
  • contracts/test/arbitration/staking-neo.ts (28 hunks)
  • contracts/test/arbitration/staking.ts (15 hunks)
  • contracts/test/evidence/index.ts (7 hunks)
  • contracts/test/integration/index.ts (9 hunks)
  • contracts/test/rng/index.ts (1 hunks)
  • contracts/tsconfig.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • contracts/package.json
🔇 Additional comments (47)
contracts/tsconfig.json (1)

3-5: LGTM! The addition of resolveJsonModule enhances type safety.

This change appropriately enables TypeScript to handle JSON imports with full type checking, which is beneficial for working with contract artifacts and configuration files.

Let's verify the base configuration to ensure no conflicts:

✅ Verification successful

✅ The resolveJsonModule configuration is correctly added and doesn't conflict with base configs

After verifying the base configurations, we can confirm that:

  • The base18.json doesn't set resolveJsonModule
  • The addition in contracts/tsconfig.json is a valid extension of the base config
  • This change properly enables JSON module imports with type checking
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if resolveJsonModule is already set in the base configuration
# Expect: No conflicts with base configuration

# Test: Check the base configuration
cat node_modules/@kleros/kleros-v2-tsconfig/base18.json | grep -A 5 "resolveJsonModule"

Length of output: 171


Script:

#!/bin/bash
# Let's first check if the base config file exists and its location
fd -t f "base18.json"

# Also check the content of the tsconfig.json to see the exact extends path
cat contracts/tsconfig.json

Length of output: 408


Script:

#!/bin/bash
# Check the content of the base configuration file
cat tsconfig/base18.json

Length of output: 164

contracts/deploy/upgrade-kleros-core.ts (2)

8-8: LGTM: Updated to use new ethers.js constant.

The change from ethers.constants.AddressZero to ethers.ZeroAddress aligns with the latest ethers.js conventions.


29-36: LGTM with verification needed.

The updates to use ZeroAddress and toBeHex follow the latest ethers.js conventions. However, given this is a critical contract upgrade, please verify:

  1. The argument order matches the contract constructor
  2. The argument types are correct, especially the arrays containing both bigint and number values

Let's verify the contract constructor signature:

✅ Verification successful

Argument order and types verified successfully

The provided arguments in upgrade-kleros-core.ts match the initialize function signature in KlerosCore.sol:

  1. ZeroAddress matches _governor (address)
  2. disputeKit.address matches _disputeKit (IDisputeKit)
  3. false matches _hiddenVotes (bool)
  4. [minStake, alpha, feeForJuror, 256] matches _courtParameters (uint256[4])
  5. [0, 0, 0, 10] matches _timesPerPeriod (uint256[4])
  6. ethers.toBeHex(5) matches _sortitionExtraData (bytes)
  7. sortitionModule.address matches _sortitionModuleAddress (ISortitionModule)

The array types containing both bigint and number values are safe as they are all converted to uint256 when passed to the contract.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find and display the KlerosCore contract constructor
ast-grep --pattern 'contract KlerosCore {
  $$$
  constructor($$$) {
    $$$
  }
  $$$
}'

Length of output: 91


Script:

#!/bin/bash
# Let's try to find the KlerosCore contract file first
fd "KlerosCore" --type f

# Then we can read its content
rg "constructor" -A 20 -B 5 --type solidity

Length of output: 1592


Script:

#!/bin/bash
# Let's read the content of the KlerosCore contract
cat contracts/src/arbitration/KlerosCore.sol

# Also check the base contract as it might contain the constructor
cat contracts/src/arbitration/KlerosCoreBase.sol

Length of output: 56058

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

6-6: LGTM: Using recommended ethers v6 AbiCoder initialization.

The change correctly uses the new recommended way to access the default ABI coder in ethers v6.


9-9: LGTM: Excellent modernization of test code.

The changes demonstrate several improvements:

  1. Added proper type annotation for better type safety
  2. Updated to use .staticCall as per ethers v6
  3. Adopted native bigint syntax for large numbers

Also applies to: 17-23


38-46: ⚠️ Potential issue

Critical: Test assertions are still reversed.

The test assertions continue to contradict their descriptions:

  1. "Should return a non-zero number" test expects zero
  2. "Should return zero" test expects non-zero

This issue was previously identified and needs to be addressed.

Apply this fix:

  it("Should return a non-zero number for a block number in the past", async () => {
    const tx = await rng.receiveRandomness(9876543210);
    const trace = await network.provider.send("debug_traceTransaction", [tx.hash]);
    const [rn] = abiCoder.decode(["uint"], ethers.getBytes(`${trace.returnValue}`));
-   expect(rn).to.equal(0);
+   expect(rn).to.not.equal(0);
  });

  it("Should return zero for a block number in the future", async () => {
    const tx = await rng.receiveRandomness(5);
    const trace = await network.provider.send("debug_traceTransaction", [tx.hash]);
    const [rn] = abiCoder.decode(["uint"], ethers.getBytes(`${trace.returnValue}`));
-   expect(rn).to.not.equal(0);
+   expect(rn).to.equal(0);
  });
contracts/deploy/utils/deployTokens.ts (1)

1-1: LGTM! Import updated correctly for newer ethers version.

The direct import from 'ethers' follows the recommended practice for the latest version.

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

6-6: LGTM! Import changes enhance type safety and modularity.

The addition of explicit contract type imports and the separation of currency rate logic into a helper module align well with the PR's objectives.

Also applies to: 8-8


27-35: LGTM! Contract deployment changes follow best practices.

The use of .target instead of .address and the structured array parameters maintain type safety and follow consistent patterns.


54-54: LGTM! Consistent use of .target property.

The deployment arguments correctly use .target for both contract references, maintaining consistency throughout the codebase.


25-25: Verify the bigint conversion maintains the same value.

The transition from BigNumber to native bigint looks correct, but please verify that 10n ** 17n maintains the same value as the previous implementation.

contracts/test/arbitration/index.ts (4)

4-4: LGTM: Type safety improvements

The addition of explicit type annotations enhances code clarity and type safety.

Also applies to: 8-9


13-13: LGTM: Simplified contract deployment

The removal of the redundant deployer parameter streamlines the deployment process.


Line range hint 63-70: LGTM: Return type annotation added

The explicit return type annotation improves type safety. Note that there's an existing review comment about adding error handling to this function.


43-43: Consider adding edge case tests

The basic dispute creation test looks good, but consider adding test cases for:

  • Maximum number of choices
  • Empty choice bytes
  • Invalid choice values

Also applies to: 49-49, 54-54

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

8-10: LGTM: Import changes align with PR objectives.

The new imports support the transition to updated ethers types and contract interactions.

Also applies to: 12-12


84-84: LGTM: Updated to use parseEther per ethers v6.

The change from utils.parseUnits to parseEther aligns with ethers v6 API changes.


29-30: LGTM: Contract retrieval changes are consistent.

The changes to contract retrievals align with the updated imports and maintain consistency with the existing pattern.

Also applies to: 40-40

✅ Verification successful

LGTM: Contract retrieval changes are verified and consistent

The verification confirms that both ArbitrableExample and EvidenceModule contracts exist in the codebase:

  • contracts/src/arbitration/arbitrables/ArbitrableExample.sol
  • contracts/src/arbitration/evidence/EvidenceModule.sol

Both contracts are properly deployed and have corresponding artifacts in multiple deployment environments, including:

  • contracts/deployments/arbitrumSepolia/ArbitrableExample.json
  • contracts/deployments/arbitrumSepolia/EvidenceModule.json
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the contract names in deployment artifacts
fd -e json -t f . contracts/deployments -x jq -r 'select(.contractName != null) | .contractName' {} \; | sort -u | grep -E 'ArbitrableExample|EvidenceModule'

Length of output: 162


Script:

#!/bin/bash
# Let's verify the contract names and their usage in the codebase
# First check the contract definitions
fd -e sol . contracts/src -x echo "File: {}" \; -x grep -l "contract.*\(ArbitrableExample\|EvidenceModule\)" {} \;

# Then check the imports and usage in TypeScript files
fd -e ts . contracts -x echo "File: {}" \; -x grep -l "\(ArbitrableExample\|EvidenceModule\)" {} \;

# Check for contract artifacts in any JSON files
fd -e json . contracts -x echo "File: {}" \; -x grep -l "\(ArbitrableExample\|EvidenceModule\)" {} \;

Length of output: 22752

contracts/test/integration/index.ts (4)

41-51: LGTM! Well-structured contract instance declarations.

The variable declarations are now properly typed and follow TypeScript best practices with appropriate semicolon separators.


72-75: LGTM! Proper BigInt arithmetic implementation.

The calculations for arbitration costs and stakes correctly use BigInt arithmetic with the n suffix, ensuring precise numerical operations without potential precision loss.

Also applies to: 84-86, 98-100


162-165: LGTM! Robust phase transition handling.

The code properly verifies each phase transition with appropriate assertions and RNG integration. The use of ethers.getNumber() for RNG lookahead and the sequential phase transitions (Staking -> Generating -> Drawing) are well implemented.


196-197: LGTM! Proper cross-chain ruling verification.

The test correctly verifies ruling propagation across chains by checking event emissions on both the home and foreign gateways. The comment about dispute ID counting differences between gateways is particularly helpful for maintainability.

contracts/scripts/populateCourts.ts (3)

3-3: LGTM! Import changes align with ethers update.

The updated imports properly reflect the transition to newer ethers patterns while maintaining type compatibility.


41-43: LGTM! Constants properly updated to use bigint literals.

The constants have been correctly updated to use native bigint literals, maintaining their original functionality while aligning with the new type system.


238-238: ⚠️ Potential issue

Add array bounds checking for timesPerPeriod access.

The direct array access court.timesPerPeriod[0,1,2,3] assumes the array always has exactly 4 elements. Consider adding validation:

if (court.timesPerPeriod.length !== 4) {
  throw new Error(`Court ${court.id} must have exactly 4 time periods`);
}

Also applies to: 262-262

contracts/test/evidence/index.ts (5)

3-5: LGTM: Import statements correctly updated for ethers v6.

The new imports properly handle the updated type system in ethers v6, improving type safety.


37-42: LGTM: Proper type annotations for signers.

The explicit HardhatEthersSigner types improve type safety and code clarity.


231-231: LGTM: Complex moderation logic with BigInt calculations.

The moderation deposit calculations using BigInt are correctly implemented. The progression of paid fees and required deposits is handled properly.

#!/bin/bash
# Verify consistent BigInt arithmetic across moderation logic
rg "paidFees\[.*\] \* 2" "contracts/test/"

Also applies to: 238-238, 245-245, 252-252, 259-259


70-72: LGTM: Proper usage of .target instead of .address for contract references.

The change from .address to .target aligns with ethers v6 best practices.

#!/bin/bash
# Verify consistent usage of .target across test files
rg "\.address(?!.*getAddress)" "contracts/test/"

21-21: LGTM: Proper BigInt usage for financial calculations.

The conversion to BigInt maintains precision for financial calculations. The calculations for totalCost and minRequiredDeposit are correctly implemented.

Also applies to: 23-23, 29-35

✅ Verification successful

Let me search for different patterns to verify the consistent usage of BigInt across test files. The previous command might have had syntax issues, so I'm breaking it down into more specific searches.


BigInt usage is consistent and properly implemented across test files

The verification shows consistent usage of BigInt literals (with 'n' suffix) across the test files, particularly in:

  • Financial calculations (fees, deposits, stakes)
  • Token amounts (ETH and PNK denominations)
  • Mathematical operations

The arbitrationFee value of 1000n is consistent with other BigInt usage patterns in the codebase, especially in the test files where similar financial values are handled. No instances of potentially problematic BigNumber or ethers.utils number handling were found that could conflict with this implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify consistent BigInt usage across test files
rg -l "BigNumber|ethers\.utils" "contracts/test/"

Length of output: 286


Script:

#!/bin/bash
# Search for BigNumber imports and usage
rg "BigNumber" "contracts/test/"

# Search for ethers.utils usage
rg "ethers\.utils" "contracts/test/"

# Search for other bigint literals
rg "\d+n\b" "contracts/test/"

# Search for potential numeric calculations
rg "(\.mul|\.div|\.add|\.sub)\(" "contracts/test/"

Length of output: 5982

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

3-3: LGTM! Well-structured type imports and bigint constants.

The transition to native bigint and proper type imports enhances type safety and readability.

Also applies to: 20-21, 53-53


84-84: Previous review comments are still applicable.

The issues with using .target and ethers.toBeHex have been previously identified and the suggested fixes are still valid.

Also applies to: 98-98


154-154: 🛠️ Refactor suggestion

Use proper hex string construction for extraData.

String concatenation for hex data is error-prone and should be replaced with proper hex string construction.

Apply this diff:

-          extraData: `0x000000000000000000000000000000000000000000000000000000000000000${createDisputeCourtId}0000000000000000000000000000000000000000000000000000000000000003`,
+          extraData: ethers.concat([
+            ethers.zeroPadValue(ethers.toBeHex(createDisputeCourtId), 31),
+            ethers.zeroPadValue(ethers.toBeHex(3), 32)
+          ]),

Likely invalid or redundant comment.


140-144: 🛠️ Refactor suggestion

Improve transaction confirmation and error handling.

The current error handling could be enhanced for better reliability and debugging:

  1. Wait for transaction confirmation before accessing blockNumber
  2. Provide more descriptive error messages

Apply this diff:

-    if (tx.blockNumber === null) throw new Error("tx.blockNumber is null");
-    const trace = await network.provider.send("debug_traceTransaction", [tx.hash]);
-    const [disputeId] = abiCoder.decode(["uint"], ethers.getBytes(`${trace.returnValue}`));
-    const lastBlock = await ethers.provider.getBlock(tx.blockNumber - 1);
-    if (lastBlock?.hash === null || lastBlock?.hash === undefined) throw new Error("lastBlock is null || undefined");
+    const receipt = await tx.wait();
+    if (!receipt) throw new Error("Transaction failed to be mined");
+    const trace = await network.provider.send("debug_traceTransaction", [tx.hash]);
+    const [disputeId] = abiCoder.decode(["uint"], ethers.getBytes(trace.returnValue));
+    const lastBlock = await ethers.provider.getBlock(receipt.blockNumber - 1);
+    if (!lastBlock?.hash) throw new Error("Failed to retrieve previous block hash");

Likely invalid or redundant comment.

contracts/test/arbitration/staking.ts (3)

9-15: LGTM! Updates align with latest ethers.js practices

The changes correctly implement the latest ethers.js patterns:

  • Direct usage of parseUnits from ethers
  • Proper parameter encoding using the default ABI coder

17-22: LGTM! Enhanced type safety with explicit annotations

The addition of explicit type annotations improves code clarity and type safety.


51-51: LGTM! Updated contract interaction patterns

The changes correctly implement the latest ethers.js contract interaction patterns using bracket notation for overloaded functions.

Also applies to: 397-397

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

12-12: LGTM: Type safety improvements

Good addition of HardhatEthersSigner type and proper type annotations for the signer variables. This enhances type safety and code maintainability.

Also applies to: 38-40


33-36: LGTM: Improved ABI encoding

Good use of ethers.AbiCoder.defaultAbiCoder().encode() for extraData. This is more explicit and type-safe than using hardcoded strings.


135-135: LGTM: Consistent use of .target property

Good migration from .address to .target for contract references, maintaining consistency with the latest ethers.js practices.

Also applies to: 149-149, 156-156

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

2-3: Approved: Necessary imports for updated ethers usage

The addition of toBigInt, BigNumberish, and AddressLike imports is appropriate for utilizing the latest features of the ethers library and enhances type safety throughout the script.


38-41: Approved: Correct argument types for approve function

Using AddressLike and BigNumberish for approvePNKFunctionArgs aligns with the expected types in the approve function of the pnk contract. This ensures type safety and consistency.


257-258: Approved: Correct usage of solidityPackedKeccak256

The solidityPackedKeccak256 function correctly matches the types ["uint256", "string", "string"] with the variables [choice, justification, salt]. This resolves previous concerns about type mismatches.


438-439: Approved: Correct parsing of PNK amount

Parsing the pnkperwallet amount using ethers.parseEther ensures the correct conversion to BigInt for transfers.


458-465: Approved: Updating evidence submission to use evidenceModule

Switching from disputeKitClassic to evidenceModule for submitting evidence aligns with the updated contract interactions and enhances code clarity.


63-63: ⚠️ Potential issue

Ensure courtid is of a numeric type

The courtid parameter is typed as string, but the setStake function likely expects a BigNumberish type. Consider parsing courtid to a numeric type to match the expected input.

Apply this diff to fix the type inconsistency:

- const setStakeFunctionArgs: [string, bigint] = [courtid, ethers.parseEther(pnkamount.toString())];
+ const setStakeFunctionArgs: [BigNumberish, bigint] = [BigInt(courtid), ethers.parseEther(pnkamount.toString())];

Likely invalid or redundant comment.


137-137: Ensure proper conversion for evidenceGroupID

Converting random bytes directly to a BigInt may lead to unintended values or errors. Consider using a hashing function or ensuring the bytes represent a valid number.

Run the following script to verify the value of evidenceGroupID:

✅ Verification successful

Let me analyze the codebase further to understand the usage of evidenceGroupID.


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

Converting random bytes to BigInt is safe and appropriate for evidenceGroupID

The usage of toBigInt(ethers.randomBytes(32)) is a secure way to generate a random identifier because:

  1. The ethers.randomBytes(32) generates a cryptographically secure 32-byte (256-bit) random value
  2. Converting these bytes to BigInt creates a valid numeric identifier that can be safely used as an evidence group ID
  3. The evidence system in the contracts accepts and expects numeric IDs in string format
  4. This pattern is used only for generating unique identifiers, not for cryptographic operations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the generated evidenceGroupID is a valid bigint.

# Test: Attempt to convert random bytes to bigint and check for errors.
node -e "
const { toBigInt, randomBytes } = require('ethers');
try {
  const evidenceGroupID = toBigInt(randomBytes(32)).toString();
  console.log('evidenceGroupID:', evidenceGroupID);
} catch (error) {
  console.error('Error converting evidenceGroupID:', error);
}"

Length of output: 1051


Script:

#!/bin/bash
# Search for usage of evidenceGroupID in the codebase
rg "evidenceGroupID" -A 3 -B 3

# Check the imports and context around the evidenceGroupID generation
rg -A 10 -B 10 "toBigInt\(ethers\.randomBytes"

# Look for similar patterns of random ID generation
ast-grep --pattern 'toBigInt(ethers.randomBytes($_))'

Length of output: 227847

const alpha = 10000;
const feeForJuror = BigNumber.from(10).pow(17);
const feeForJuror = 10n * 17n;
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 5, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Incorrect fee calculation.

The current calculation 10n * 17n results in 170, which is significantly different from the intended 10^17. This could lead to severely incorrect fee amounts.

Apply this fix:

-    const feeForJuror = 10n * 17n;
+    const feeForJuror = 10n ** 17n;
📝 Committable suggestion

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

Suggested change
const feeForJuror = 10n * 17n;
const feeForJuror = 10n ** 17n;

Copy link
Member

Choose a reason for hiding this comment

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

Good find

Copy link
Contributor

Choose a reason for hiding this comment

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

@jaybuidl, glad I could help!


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

import { getContractOrDeploy } from "./getContractOrDeploy";
import { isMainnet } from ".";

export const deployERC20AndFaucet = async (
hre: HardhatRuntimeEnvironment,
deployer: string,
ticker: string,
faucetFundingAmount: BigNumber = hre.ethers.utils.parseUnits("100000")
faucetFundingAmount: bigint = hre.ethers.parseUnits("100000")
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Inconsistent usage of parseUnits with BigNumber found

Several files still use BigNumber.from(parseUnits()) which is inconsistent with the migration to bigint:

  • contracts/deploy/01-foreign-gateway-on-gnosis.ts: ONE_GWEI = BigNumber.from(parseUnits("1", "gwei"))
  • contracts/deploy/04-klerosliquid-to-v2-gnosis.ts: ONE_GWEI = BigNumber.from(parseUnits("1", "gwei"))
  • contracts/deploy/04-foreign-arbitrable.ts: ONE_GWEI = BigNumber.from(parseUnits("1", "gwei"))

These instances should be updated to use bigint directly without wrapping in BigNumber.from().

🔗 Analysis chain

Verify parseUnits usage across the codebase.

The type change to bigint and use of parseUnits is correct. However, let's verify that all parseUnits calls are consistently handled.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent parseUnits usage with bigint
# Look for any parseUnits calls that might still be using BigNumber

# Search for parseUnits usage
rg "parseUnits" --type typescript

# Search for potential BigNumber type annotations near parseUnits
rg "parseUnits.*BigNumber" --type typescript

Length of output: 150


Script:

#!/bin/bash
# Search for parseUnits usage without file type restriction
rg "parseUnits"

# Search for BigNumber type annotations near parseUnits
rg -B2 -A2 "parseUnits"

Length of output: 7459

@@ -54,7 +58,7 @@ export const getWallet = async (hre: any, walletIndex: number) => {

export const isRngReady = async (wallet, hre) => {
const { randomizerRng, disputeKitClassic } = await getContracts(hre);
const requesterID = await randomizerRng.connect(wallet).requesterToID(disputeKitClassic.address);
const requesterID = await randomizerRng.connect(wallet).requesterToID(disputeKitClassic.target);
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Let me analyze the results and generate a final response.

Remaining .address usages need to be updated to .target

The codebase still contains instances where .address should be updated to .target when dealing with contract instances, particularly in:

  • contracts/scripts/console-init.ts: const requesterID = await rng.requesterToID(disputeKit.address);

Note: Other .address usages are correct as they refer to:

  • Wallet/signer addresses (e.g., wallet.address, deployer.address)
  • Deployment addresses (e.g., deployment.address)
  • Contract addresses stored in configuration (e.g., disputeKitClassicConfig.address)
🔗 Analysis chain

LGTM: Updated to use .target instead of .address per ethers v6.

The change from .address to .target aligns with ethers v6 breaking changes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any remaining .address usage that should be .target
rg "\.address" contracts/ --type ts

Length of output: 18930

@@ -307,7 +305,7 @@ task("simulate:fund-appeal", "Funds an appeal on a dispute")
const { disputeid, walletindex, appealchoice } = taskArgs;
const { wallet } = await getWallet(hre, walletindex);

const fundAppealFunctionArgs: [number, number, { value: BigNumber }] = [
const fundAppealFunctionArgs: [number, number, { value: BigNumberish }] = [
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure consistent types for function arguments

The fundAppealFunctionArgs uses number types, but the fundAppeal function may expect BigNumberish. Consider ensuring all numeric IDs are of a consistent type.

Apply this diff to align types:

-const fundAppealFunctionArgs: [number, number, { value: BigNumberish }] = [
+const fundAppealFunctionArgs: [BigNumberish, BigNumberish, { value: BigNumberish }] = [
  disputeid,
  appealchoice,
  { value: await getAppealCost(hre, disputeid) },
];
📝 Committable suggestion

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

Suggested change
const fundAppealFunctionArgs: [number, number, { value: BigNumberish }] = [
const fundAppealFunctionArgs: [BigNumberish, BigNumberish, { value: BigNumberish }] = [

Comment on lines +80 to +84
const parent = 1n;
const minStake = 2n * 10n ** 20n;
const alpha = 10000n;
const feeForJuror = 10n * 17n;
const jurorsForCourtJump = 3n;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct calculation of numeric constants using BigInt

There are issues with the calculations of minStake, feeForJuror, and potentially other constants. Multiplying 10n * 17n results in 170n, which may not be the intended value. Use exponentiation to achieve the correct values.

Apply this diff to correct the calculations:

 const parent = 1n;
-const minStake = 2n * 10n ** 20n;
+const minStake = 2n * 10n ** 18n;
 const alpha = 10000n;
-const feeForJuror = 10n * 17n;
+const feeForJuror = 10n ** 17n;
 const jurorsForCourtJump = 3n;
📝 Committable suggestion

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

Suggested change
const parent = 1n;
const minStake = 2n * 10n ** 20n;
const alpha = 10000n;
const feeForJuror = 10n * 17n;
const jurorsForCourtJump = 3n;
const parent = 1n;
const minStake = 2n * 10n ** 18n;
const alpha = 10000n;
const feeForJuror = 10n ** 17n;
const jurorsForCourtJump = 3n;

Comment on lines +364 to +372
// disputeid, beneficiary, getRoundId(taskArgs, hre, disputeid), choice
// toBigInt(disputeid),
// await ethers.getAddress(beneficiary),
// getRoundId(taskArgs, hre, disputeid),
// choice
const _disputeId: BigNumberish = disputeid;
const _beneficiary: AddressLike = beneficiary;
const _coreRoundId: BigNumberish = await getRoundId(taskArgs, hre, disputeid);
const _choice: BigNumberish = choice;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure correct types for withdrawal function arguments

The variables _disputeId, _coreRoundId, and _choice are typed as BigNumberish, but their values come from string. Ensure these strings are converted to BigInt or appropriate BigNumberish types.

Apply this diff to fix the type conversions:

const _disputeId: BigNumberish = disputeid;
const _beneficiary: AddressLike = beneficiary;
-const _coreRoundId: BigNumberish = await getRoundId(taskArgs, hre, disputeid);
-const _choice: BigNumberish = choice;
+const _coreRoundId: BigNumberish = BigInt(await getRoundId(taskArgs, hre, disputeid));
+const _choice: BigNumberish = BigInt(choice);
📝 Committable suggestion

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

Suggested change
// disputeid, beneficiary, getRoundId(taskArgs, hre, disputeid), choice
// toBigInt(disputeid),
// await ethers.getAddress(beneficiary),
// getRoundId(taskArgs, hre, disputeid),
// choice
const _disputeId: BigNumberish = disputeid;
const _beneficiary: AddressLike = beneficiary;
const _coreRoundId: BigNumberish = await getRoundId(taskArgs, hre, disputeid);
const _choice: BigNumberish = choice;
// disputeid, beneficiary, getRoundId(taskArgs, hre, disputeid), choice
// toBigInt(disputeid),
// await ethers.getAddress(beneficiary),
// getRoundId(taskArgs, hre, disputeid),
// choice
const _disputeId: BigNumberish = disputeid;
const _beneficiary: AddressLike = beneficiary;
const _coreRoundId: BigNumberish = BigInt(await getRoundId(taskArgs, hre, disputeid));
const _choice: BigNumberish = BigInt(choice);

@jaybuidl jaybuidl deleted the chore(hardhat)/hardhat-ether-version-update branch November 6, 2024 05:46
@jaybuidl jaybuidl added the Type: Toolchain ⚒️ Build tools configuration, CI/CD label Jan 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Package: Contracts Court smart contracts Type: Maintenance 🚧 Type: Toolchain ⚒️ Build tools configuration, CI/CD
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Upgrade hardhat, hardhat-deploy, ethers
2 participants