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

perf: change parameter types of hasOracle, isOracleOnline, chainName to bytes32 #898

Merged
merged 2 commits into from
Jan 15, 2025

Conversation

zakir-code
Copy link
Contributor

@zakir-code zakir-code commented Jan 15, 2025

Summary by CodeRabbit

  • Breaking Changes

    • Updated chain identifier type from string to bytes32 across multiple contracts and interfaces.
    • Removed bytes32ToString function from BridgeFeeOracle contract.
  • Code Improvements

    • Simplified oracle-related method signatures.
    • Enhanced type consistency for chain identifiers.
    • Improved parameter naming in precompile methods.
  • Deprecation

    • Deprecated direct usage of CrosschainTestABI and CrosschainTestBin.

Copy link

coderabbitai bot commented Jan 15, 2025

Walkthrough

This pull request introduces significant changes to the crosschain and bridge fee oracle infrastructure, primarily focusing on modifying how chain identifiers are handled. The changes involve transitioning from string-based chain representations to byte32 (fixed-size byte array) representations across multiple contracts, interfaces, and implementation files. The most notable modifications include removing the Bytes32ToString function, updating function signatures, and adjusting how chain names are processed and stored.

Changes

File Change Summary
contract/bridge_fee_oracle.sol.go Removed Bytes32ToString function and updated ABI/binary representations.
contract/crosschain.go Changed Chain field type from string to common.Hash in HasOracleArgs and IsOracleOnlineArgs.
contract/icrosschain.sol.go Updated method signatures to use bytes32 for chain parameters.
precompiles/crosschain/has_oracle.go Modified Run method to handle byte32 chain representations and renamed parameter for clarity.
precompiles/crosschain/is_oracle_online.go Modified Run method to handle byte32 chain representations and renamed parameter for clarity.
precompiles/crosschain/has_oracle_test.go Updated test cases to use MustStrToByte32 for Chain assignments.
precompiles/crosschain/is_oracle_online_test.go Updated test cases to use MustStrToByte32 for Chain assignments.
solidity/contracts/bridge/BridgeFeeOracle.sol Removed bytes32ToString function and updated isOnline function logic.
solidity/contracts/bridge/IBridgeOracle.sol Changed _chain parameter type from string to bytes32 in hasOracle and isOracleOnline functions.
solidity/contracts/test/BridgeFeeQuoteTest.sol Changed mapping key and function parameter types from string to bytes32.
solidity/contracts/test/CrosschainTest.sol Changed _chain parameter type from string to bytes32 in hasOracle and isOracleOnline functions.
tests/contract/crosschain_test.sol.go Updated method signatures to accept bytes32 for _chain parameter.
solidity/test/bridge_fee_quote.ts Modified setOracle method call to use encoded chainName.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Contract
    participant Router
    
    Client->>Contract: Call hasOracle(bytes32 chain, address)
    Contract->>Router: Verify chain route
    Router-->>Contract: Return route status
    Contract-->>Client: Return oracle presence
Loading

Possibly related PRs

  • refactor: crosschain bridge call #443: Changes in this PR involve modifications to the ABI and function signatures related to cross-chain operations, which may connect with the removal of the Bytes32ToString function in the main PR as both involve handling data types and contract interactions.
  • refactor: bridgecall interface #502: This PR updates the ICrossChain interface, including changes to function signatures that may relate to the modifications in the main PR regarding the handling of data types and contract methods.
  • refactor: move crosschain precompile to crosschain #569: The changes in this PR involve moving cross-chain precompile logic, which may relate to the structural changes in the main PR regarding the BridgeFeeOracle contract and its methods.

Poem

🐰 In bytes we trust, no strings attached,
A crosschain dance, precisely matched!
From strings to bytes32, we leap with glee,
Optimizing routes, setting data free!
Hop, hop, hooray for type precision! 🚀


📜 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 d6c155c and b750b02.

📒 Files selected for processing (1)
  • contract/crosschain.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • contract/crosschain.go
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Summary

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
precompiles/crosschain/has_oracle.go (1)

45-49: Update error message to use string representation.

The error message should use the string representation of the chain for better readability.

-    return nil, fmt.Errorf("chain not support: %s", args.Chain)
+    return nil, fmt.Errorf("chain not support: %s", chainName)
precompiles/crosschain/is_oracle_online.go (1)

45-49: Update error message to use string representation.

The error message should use the string representation of the chain for better readability.

-    return nil, fmt.Errorf("chain not support: %s", args.Chain)
+    return nil, fmt.Errorf("chain not support: %s", chainName)
precompiles/crosschain/is_oracle_online_test.go (2)

33-33: Verify error handling for MustStrToByte32.

The test uses contract.MustStrToByte32 which likely panics on conversion failure. Consider:

  1. Adding test cases for chain names that would fail conversion
  2. Using a non-panicking version for better error handling

Consider adding these test cases:

{
    name: "chain name too long",
    malleate: func() (contract.IsOracleOnlineArgs, error) {
        longChainName := strings.Repeat("a", 33) // 33 bytes
        return contract.IsOracleOnlineArgs{
            Chain:           contract.MustStrToByte32(longChainName),
            ExternalAddress: helpers.GenHexAddress(),
        }, fmt.Errorf("chain name too long")
    },
    result: false,
},
{
    name: "chain name with special characters",
    malleate: func() (contract.IsOracleOnlineArgs, error) {
        return contract.IsOracleOnlineArgs{
            Chain:           contract.MustStrToByte32("chain\x00name"),
            ExternalAddress: helpers.GenHexAddress(),
        }, fmt.Errorf("invalid characters in chain name")
    },
    result: false,
}

Also applies to: 44-44, 54-54, 64-64


Line range hint 1-89: Consider adding test coverage for bytes32 padding.

The test suite would benefit from explicit verification of how chain names are padded to 32 bytes, especially for:

  1. Names shorter than 32 bytes
  2. Names exactly 32 bytes
  3. UTF-8 encoded names
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fab07e5 and d6c155c.

📒 Files selected for processing (13)
  • contract/bridge_fee_oracle.sol.go (1 hunks)
  • contract/crosschain.go (1 hunks)
  • contract/icrosschain.sol.go (4 hunks)
  • precompiles/crosschain/has_oracle.go (1 hunks)
  • precompiles/crosschain/has_oracle_test.go (3 hunks)
  • precompiles/crosschain/is_oracle_online.go (1 hunks)
  • precompiles/crosschain/is_oracle_online_test.go (4 hunks)
  • solidity/contracts/bridge/BridgeFeeOracle.sol (1 hunks)
  • solidity/contracts/bridge/IBridgeOracle.sol (1 hunks)
  • solidity/contracts/test/BridgeFeeQuoteTest.sol (1 hunks)
  • solidity/contracts/test/CrosschainTest.sol (2 hunks)
  • solidity/test/bridge_fee_quote.ts (1 hunks)
  • tests/contract/crosschain_test.sol.go (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Summary
🔇 Additional comments (20)
tests/contract/crosschain_test.sol.go (5)

34-35: Updated ABI and Bin to reflect contract changes

The ABI and Bin fields in CrosschainTestMetaData have been updated to match the modified contract methods, specifically changing parameter types from string to bytes32. This ensures that the Go bindings accurately represent the updated Solidity contract interface.


Line range hint 267-275: Updated HasOracle method to accept [32]byte for _chain

The HasOracle method in CrosschainTestCaller now correctly accepts _chain as a [32]byte type, aligning with the updated Solidity function that uses bytes32. This change ensures type consistency between the Go bindings and the Solidity contract.


284-294: Updated HasOracle method in CrosschainTestSession to use [32]byte

The HasOracle method in CrosschainTestSession has been updated to accept _chain as [32]byte, matching the contract changes. This ensures that sessions utilizing this method are consistent with the new parameter type.


Line range hint 298-309: Updated IsOracleOnline method to accept [32]byte for _chain

The IsOracleOnline method in CrosschainTestCaller now accepts _chain as [32]byte, ensuring consistency with the updated Solidity contract and maintaining type safety in the Go bindings.


315-318: Updated IsOracleOnline in CrosschainTestSession to use [32]byte

The IsOracleOnline method in CrosschainTestSession has been updated to accept _chain as [32]byte, aligning with the contract's interface changes.

solidity/contracts/bridge/IBridgeOracle.sol (2)

14-16: Updated _chain parameter type to bytes32 in isOracleOnline

The _chain parameter in isOracleOnline has been updated from string memory to bytes32. Verify that all implementations and callers of this interface method have been updated to use bytes32 for the _chain parameter.

Please run the script provided in the previous comment to ensure consistency across all implementations.


9-11: Updated _chain parameter type to bytes32 in hasOracle

The _chain parameter in hasOracle has been changed from string memory to bytes32, enhancing efficiency and consistency in handling chain identifiers. Ensure that all implementations of IBridgeOracle and any contracts invoking this function have updated their implementations and calls accordingly.

Run the following script to verify that all implementations of IBridgeOracle have updated the _chain parameter to bytes32:

solidity/contracts/test/BridgeFeeQuoteTest.sol (4)

12-12: Changed mapping key type to bytes32 for oracleStatus

The mapping oracleStatus now uses bytes32 as the key type for _chainName, improving efficiency and consistency in representing chain identifiers. Ensure that any code interacting with this mapping is updated to use bytes32 keys.


15-19: Updated _chainName parameter to bytes32 in setOracle

The _chainName parameter in setOracle has been changed from string memory to bytes32. This change enhances performance but may require updates to any code calling this function to ensure the correct data type is passed.

As a reminder, ensure that any calls to setOracle are updated to pass bytes32 for _chainName.


23-27: Updated _chainName parameter to bytes32 in hasOracle

The _chainName parameter in hasOracle has been updated to bytes32. Verify that any code calling this function uses bytes32 for the chain name to maintain consistency.


Line range hint 30-34: Updated _chainName parameter to bytes32 in isOracleOnline

The _chainName parameter in isOracleOnline now uses bytes32 instead of string memory. Ensure that callers of this function have been updated accordingly to pass the correct parameter type.

contract/crosschain.go (1)

95-95: LGTM! Type changes align with PR objective.

The change from string to common.Hash for the Chain field in both structs is consistent with the PR's goal of using bytes32 for chain identifiers.

Also applies to: 107-107

precompiles/crosschain/has_oracle.go (1)

38-38: LGTM! Parameter rename improves clarity.

Renaming the parameter from contract to vmContract helps avoid confusion with the package name.

precompiles/crosschain/has_oracle_test.go (1)

33-33: LGTM! Test cases properly updated.

The test cases have been correctly updated to use contract.MustStrToByte32 for converting chain names to bytes32, maintaining consistency with the new type system.

Also applies to: 43-43, 53-53

solidity/contracts/test/CrosschainTest.sol (2)

Line range hint 105-111: LGTM! Parameter type change looks good.

The change from string to bytes32 for the _chain parameter aligns with the performance improvement goal.


Line range hint 116-122: LGTM! Parameter type change looks good.

The change from string to bytes32 for the _chain parameter aligns with the performance improvement goal.

solidity/contracts/bridge/BridgeFeeOracle.sol (1)

69-71: LGTM! Direct bytes32 usage improves performance.

The removal of string conversion and direct usage of bytes32 for chain names reduces gas costs while maintaining the same functionality.

Also applies to: 74-75

solidity/test/bridge_fee_quote.ts (1)

38-38: LGTM! Test correctly uses encoded bytes32.

The test has been properly updated to use the encoded chain name, maintaining test coverage for the new parameter type.

contract/icrosschain.sol.go (1)

214-217: LGTM! Generated bindings correctly reflect the interface changes.

The Go bindings have been properly updated to match the Solidity contract changes:

  • Function signatures updated to use [32]byte instead of string
  • Method IDs updated to reflect the new parameter types
  • Documentation updated to match the changes

Also applies to: 231-234, 238-241, 245-248, 262-265, 269-272

contract/bridge_fee_oracle.sol.go (1)

34-34: Verify the impact of removing Bytes32ToString function.

The ABI shows that chain name parameters are now using bytes32 instead of string. While this change can improve gas efficiency by avoiding dynamic memory allocation for strings, ensure that:

  1. All chain names fit within 32 bytes
  2. Proper conversion utilities are available for external systems interacting with these bytes32 parameters
✅ Verification successful

Chain names are compatible with bytes32 format

All chain names found in the codebase are well under 32 bytes in length. The contract includes built-in validation (ChainNameInvalid error) and the codebase has consistent error handling for invalid chain names. The change from string to bytes32 is safe.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if any chain names in the codebase exceed 32 bytes
rg -l '[^"]*"[^"]{33,}".*chain' | while read -r file; do
  echo "File with potentially long chain names: $file"
  rg '[^"]*"[^"]{33,}".*chain' "$file"
done

Length of output: 34846


Script:

#!/bin/bash
# Search for chain name string literals and constants
rg -g '!*.pb.go' -g '!*.pulsar.go' -g '!*.md' -g '!*.json' '"[^"]*chain[^"]*"' --no-filename | sort -u

# Also check for chain name constants
ast-grep --pattern 'const $_ = $chain_name' 

Length of output: 44878

contract/crosschain.go Outdated Show resolved Hide resolved
@zakir-code zakir-code merged commit e704368 into main Jan 15, 2025
17 checks passed
@zakir-code zakir-code deleted the todd/precompiles-chain branch January 15, 2025 09:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants