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

Prepare submission proxy deployment #2316

Merged
merged 4 commits into from
Nov 13, 2024

Conversation

nick-bisonai
Copy link
Collaborator

Description

It'll be merged once both testnet and mainnet has been deployed

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

Checklist before requesting a review

  • I have performed a self-review of my code.
  • If it is a core feature, I have added thorough tests.

Deployment

  • Should publish npm package
  • Should publish Docker image

@nick-bisonai nick-bisonai self-assigned this Nov 12, 2024
@nick-bisonai nick-bisonai requested a review from a team as a code owner November 12, 2024 07:09
Copy link
Contributor

coderabbitai bot commented Nov 12, 2024

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (13)
  • contracts/v0.2/addresses/cypress/SubmissionProxy.json is excluded by !**/*.json
  • contracts/v0.2/addresses/others-addresses.json is excluded by !**/*.json
  • contracts/v0.2/deployments/Feed.s.sol/8217/run-1731479392.json is excluded by !**/*.json
  • contracts/v0.2/deployments/Feed.s.sol/8217/run-1731479399.json is excluded by !**/*.json
  • contracts/v0.2/deployments/Feed.s.sol/8217/run-1731479400.json is excluded by !**/*.json
  • contracts/v0.2/deployments/Feed.s.sol/8217/run-1731479406.json is excluded by !**/*.json
  • contracts/v0.2/deployments/Feed.s.sol/8217/run-latest.json is excluded by !**/*.json
  • contracts/v0.2/deployments/SubmissionProxy.s.sol/8217/run-1731479144.json is excluded by !**/*.json
  • contracts/v0.2/deployments/SubmissionProxy.s.sol/8217/run-1731479150.json is excluded by !**/*.json
  • contracts/v0.2/deployments/SubmissionProxy.s.sol/8217/run-latest.json is excluded by !**/*.json
  • contracts/v0.2/migration/cypress/Feed/20241112155823_update.json is excluded by !**/*.json
  • contracts/v0.2/migration/cypress/Feed/migration.lock is excluded by !**/*.lock, !**/*.lock
  • contracts/v0.2/migration/cypress/SubmissionProxy/migration.lock is excluded by !**/*.lock, !**/*.lock

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces a new Python script, prepare-submission-proxy-migration.py, designed to prepare and save migration data for blockchain contracts. It features two primary functions: prepareForSubmissionProxy for organizing deployment information and oracles, and prepareForFeed for compiling feed addresses. The script utilizes the argparse library for command-line argument parsing, supports error handling for invalid inputs, and ensures unique JSON file generation with timestamps. It also creates necessary directories for file storage, facilitating structured migration data preparation for specified contract types.

Changes

File Path Change Summary
contracts/v0.2/script/prepare-submission-proxy-migration.py - Added prepareForSubmissionProxy(data, network) function for deployment data preparation.
- Added prepareForFeed(data, network) function for feed address compilation.
- Added main() function to handle command-line arguments and execution flow.

Possibly related PRs

  • (Contract) SubmissionProxy update #1890: The changes in the SubmissionProxy contract are directly related to the main PR as both involve modifications to the submission process and error handling within the SubmissionProxy contract.
  • Update contract #2314: This PR updates the SubmissionProxy contract with new functions and error handling that align with the changes made in the main PR, particularly regarding submission validation and error management.
  • Review of superseded feature #2315: This PR reviews the changes made in PR Update contract #2314, which are relevant to the main PR's focus on enhancing the SubmissionProxy contract's functionality.

🐇 In the land of code where the rabbits play,
A script was born to save the day.
With functions to gather, prepare, and send,
Migration data, our new best friend!
Timestamps and paths, all neatly aligned,
In the world of contracts, our progress defined! 🌟


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
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 (1)
contracts/v0.2/script/prepare-submission-proxy-migration.py (1)

1-75: Consider adding documentation for migration process

As this script is part of a larger contract migration system, consider:

  1. Adding a module docstring explaining the script's role in the migration process
  2. Documenting the expected format of input data and generated migration files
  3. Adding examples of usage in the documentation

This will help other developers understand how to use the script correctly in the deployment workflow.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0b8ff1f and 57c7e92.

⛔ Files ignored due to path filters (15)
  • contracts/v0.2/addresses/baobab/SubmissionProxy.json is excluded by !**/*.json
  • contracts/v0.2/addresses/others-addresses.json is excluded by !**/*.json
  • contracts/v0.2/deployments/Feed.s.sol/1001/run-1731394623.json is excluded by !**/*.json
  • contracts/v0.2/deployments/Feed.s.sol/1001/run-1731394630.json is excluded by !**/*.json
  • contracts/v0.2/deployments/Feed.s.sol/1001/run-1731394636.json is excluded by !**/*.json
  • contracts/v0.2/deployments/Feed.s.sol/1001/run-latest.json is excluded by !**/*.json
  • contracts/v0.2/deployments/SubmissionProxy.s.sol/1001/run-1731394146.json is excluded by !**/*.json
  • contracts/v0.2/deployments/SubmissionProxy.s.sol/1001/run-1731394152.json is excluded by !**/*.json
  • contracts/v0.2/deployments/SubmissionProxy.s.sol/1001/run-latest.json is excluded by !**/*.json
  • contracts/v0.2/migration/baobab/Feed/20241112155555_update.json is excluded by !**/*.json
  • contracts/v0.2/migration/baobab/Feed/migration.lock is excluded by !**/*.lock, !**/*.lock
  • contracts/v0.2/migration/baobab/SubmissionProxy/20241112153831_update.json is excluded by !**/*.json
  • contracts/v0.2/migration/baobab/SubmissionProxy/migration.lock is excluded by !**/*.lock, !**/*.lock
  • contracts/v0.2/migration/cypress/Feed/20241112155823_update.json is excluded by !**/*.json
  • contracts/v0.2/migration/cypress/SubmissionProxy/20241112154038_update.json is excluded by !**/*.json
📒 Files selected for processing (1)
  • contracts/v0.2/script/prepare-submission-proxy-migration.py (1 hunks)
🔇 Additional comments (2)
contracts/v0.2/script/prepare-submission-proxy-migration.py (2)

74-75: LGTM!

The entry point implementation follows the standard Python pattern.


29-42: ⚠️ Potential issue

Add type hints and handle empty submitter field

The function lacks type hints and the empty submitter field could cause issues downstream.

-def prepareForFeed(data, network):
+def prepareForFeed(data: dict, network: str) -> dict:
+    """Prepare feed migration data.
+    
+    Args:
+        data: Dictionary containing network data
+        network: Target network name
+        
+    Returns:
+        Dictionary containing submitter and feed addresses
+        
+    Raises:
+        KeyError: If required keys are missing in the data
+    """
     entries = []
     for _, networks in data.items():
+        if not isinstance(networks, dict):
+            raise ValueError(f"Invalid network data structure")
         for key, item in networks.items():
             if key == network:
+                if "feed" not in item:
+                    raise KeyError(f"Missing 'feed' key in {network}")
                 entries.append(item["feed"])
+    
+    if not entries:
+        raise ValueError(f"No feed addresses found for network {network}")
+        
     result = {
         "updateSubmitter": {
-            "submitter": "",
+            "submitter": None,  # TODO: This needs to be set to a valid address
             "feedAddresses": entries
         }
     }
     return result

Let's verify if the submitter address is required:

import os
from datetime import datetime

file_path = "./addresses/datafeeds-addresses.json"
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve path handling for better portability

The hardcoded file path with forward slashes might cause issues on Windows systems. Consider using os.path.join() for platform-independent path handling.

-file_path = "./addresses/datafeeds-addresses.json"
+file_path = os.path.join("addresses", "datafeeds-addresses.json")

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +8 to +28
def prepareForSubmissionProxy(data, network):
entries = []
for symbol, networks in data.items():
name = symbol
for key, item in networks.items():
if key == network:
entries.append({
"name": name,
"address": item["feed"]
})

result = {
"deploy": {},
"addOracle": {
"oracles": []
},
"updateFeed": entries
}

return result

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

Add type hints and error handling

The function lacks type hints and proper error handling for malformed input data. Also, some fields in the result dictionary are empty.

-def prepareForSubmissionProxy(data, network):
+def prepareForSubmissionProxy(data: dict, network: str) -> dict:
+    """Prepare submission proxy migration data.
+    
+    Args:
+        data: Dictionary containing network data
+        network: Target network name
+        
+    Returns:
+        Dictionary containing deployment and oracle information
+        
+    Raises:
+        KeyError: If required keys are missing in the data
+    """
     entries = []
     for symbol, networks in data.items():
+        if not isinstance(networks, dict):
+            raise ValueError(f"Invalid network data for symbol {symbol}")
         name = symbol
         for key, item in networks.items():
             if key == network:
+                if "feed" not in item:
+                    raise KeyError(f"Missing 'feed' key for {symbol} in {network}")
                 entries.append({
                     "name": name,
                     "address": item["feed"]
                 })

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +43 to +72
def main():
with open(file_path, "r") as f:
data = json.load(f)

parser = argparse.ArgumentParser(description="parse args")
parser.add_argument('--network', type=str, default="baobab")
parser.add_argument('--contract', type=str, default="SubmissionProxy")

args = parser.parse_args()
network = args.network
contract = args.contract

if contract == "SubmissionProxy":
result = prepareForSubmissionProxy(data, network)
elif contract == "Feed":
result = prepareForFeed(data, network)
else:
raise ValueError("Invalid contract name")

timestamp = datetime.now().strftime('%Y%m%d%H%M%S')

# Create the file path with the timestamp
write_file_path = f"./migration/{network}/{contract}/{timestamp}_update.json"

# Ensure the directories exist
os.makedirs(os.path.dirname(write_file_path), exist_ok=True)

with open(write_file_path, 'w') as file:
json.dump(result, file, indent=2)

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

Add network validation and improve error handling

The function needs network validation and better error handling for file operations.

 def main():
-    with open(file_path, "r") as f:
-        data = json.load(f)
+    try:
+        with open(file_path, "r") as f:
+            data = json.load(f)
+    except FileNotFoundError:
+        raise FileNotFoundError(f"Data file not found: {file_path}")
+    except json.JSONDecodeError:
+        raise ValueError(f"Invalid JSON format in {file_path}")

     parser = argparse.ArgumentParser(description="parse args")
-    parser.add_argument('--network', type=str, default="baobab")
+    parser.add_argument('--network', type=str, default="baobab",
+                      choices=['baobab', 'cypress'],  # Add all valid networks
+                      help="Target network for migration")
     parser.add_argument('--contract', type=str, default="SubmissionProxy")

     args = parser.parse_args()
     network = args.network
     contract = args.contract

+    valid_contracts = ["SubmissionProxy", "Feed"]
+    if contract not in valid_contracts:
+        raise ValueError(f"Invalid contract name. Must be one of: {valid_contracts}")

     if contract == "SubmissionProxy":
         result = prepareForSubmissionProxy(data, network)
     elif contract == "Feed":
         result = prepareForFeed(data, network)
-    else:
-        raise ValueError("Invalid contract name")

     timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
     write_file_path = f"./migration/{network}/{contract}/{timestamp}_update.json"

     os.makedirs(os.path.dirname(write_file_path), exist_ok=True)

-    with open(write_file_path, 'w') as file:
-        json.dump(result, file, indent=2)
+    try:
+        with open(write_file_path, 'w') as file:
+            json.dump(result, file, indent=2)
+    except IOError as e:
+        raise IOError(f"Failed to write migration file: {e}")
📝 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
def main():
with open(file_path, "r") as f:
data = json.load(f)
parser = argparse.ArgumentParser(description="parse args")
parser.add_argument('--network', type=str, default="baobab")
parser.add_argument('--contract', type=str, default="SubmissionProxy")
args = parser.parse_args()
network = args.network
contract = args.contract
if contract == "SubmissionProxy":
result = prepareForSubmissionProxy(data, network)
elif contract == "Feed":
result = prepareForFeed(data, network)
else:
raise ValueError("Invalid contract name")
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
# Create the file path with the timestamp
write_file_path = f"./migration/{network}/{contract}/{timestamp}_update.json"
# Ensure the directories exist
os.makedirs(os.path.dirname(write_file_path), exist_ok=True)
with open(write_file_path, 'w') as file:
json.dump(result, file, indent=2)
def main():
try:
with open(file_path, "r") as f:
data = json.load(f)
except FileNotFoundError:
raise FileNotFoundError(f"Data file not found: {file_path}")
except json.JSONDecodeError:
raise ValueError(f"Invalid JSON format in {file_path}")
parser = argparse.ArgumentParser(description="parse args")
parser.add_argument('--network', type=str, default="baobab",
choices=['baobab', 'cypress'], # Add all valid networks
help="Target network for migration")
parser.add_argument('--contract', type=str, default="SubmissionProxy")
args = parser.parse_args()
network = args.network
contract = args.contract
valid_contracts = ["SubmissionProxy", "Feed"]
if contract not in valid_contracts:
raise ValueError(f"Invalid contract name. Must be one of: {valid_contracts}")
if contract == "SubmissionProxy":
result = prepareForSubmissionProxy(data, network)
elif contract == "Feed":
result = prepareForFeed(data, network)
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
write_file_path = f"./migration/{network}/{contract}/{timestamp}_update.json"
os.makedirs(os.path.dirname(write_file_path), exist_ok=True)
try:
with open(write_file_path, 'w') as file:
json.dump(result, file, indent=2)
except IOError as e:
raise IOError(f"Failed to write migration file: {e}")

@nick-bisonai nick-bisonai merged commit 39f9f92 into master Nov 13, 2024
1 check passed
@nick-bisonai nick-bisonai deleted the feat/prepare-submission-proxy-deployment branch November 13, 2024 06:44
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.

1 participant