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

Create delisting gov proposal script #2722

Merged
merged 2 commits into from
Feb 14, 2025

Conversation

chenyaoy
Copy link
Contributor

@chenyaoy chenyaoy commented Feb 14, 2025

Changelist

[Describe or list the changes made in this PR]

Test Plan

[Describe how this PR was tested (if applicable)]

Author/Reviewer Checklist

  • If this PR has changes that result in a different app state given the same prior state and transaction list, manually add the state-breaking label.
  • If the PR has breaking postgres changes to the indexer add the indexer-postgres-breaking label.
  • If this PR isn't state-breaking but has changes that modify behavior in PrepareProposal or ProcessProposal, manually add the label proposal-breaking.
  • If this PR is one of many that implement a specific feature, manually label them all feature:[feature-name].
  • If you wish to for mergify-bot to automatically create a PR to backport your change to a release branch, manually add the label backport/[branch-name].
  • Manually add any of the following labels: refactor, chore, bug.

Summary by CodeRabbit

  • New Features
    • Introduced functionality to automate the creation of delisting proposals within our decentralized finance platform. This update streamlines the process by integrating real-time market data retrieval and efficiently updating the statuses of specific trading pairs.

@chenyaoy chenyaoy requested a review from a team as a code owner February 14, 2025 19:34
Copy link
Contributor

coderabbitai bot commented Feb 14, 2025

Walkthrough

A new Python script is introduced to automate the creation of a delisting proposal within a decentralized finance context. The script fetches market data via HTTP requests, applies helper functions to derive mappings for trading pairs, and then constructs a proposal with messages to update market status and disable tickers. Finally, the proposal is printed in JSON format. The file includes the main orchestration function and two helper functions for data extraction.

Changes

File Change Summary
protocol/.../create_delisting_proposal.py Introduces a new script for creating delisting proposals. Adds main() for orchestration, and helper functions get_ticker_to_perpetual_id() and get_perpetual_id_to_clob_pair() to manage market data retrieval and mapping extraction.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant M as main()
    participant H1 as get_ticker_to_perpetual_id()
    participant H2 as get_perpetual_id_to_clob_pair()
    participant MD as Market Data API

    U->>M: Execute script
    M->>MD: HTTP GET market data
    MD-->>M: Return market data
    M->>H1: Retrieve ticker-perpetual mapping
    H1-->>M: Return mapping
    M->>H2: Retrieve perpetual-CLOB pair mapping
    H2-->>M: Return mapping
    M->>M: Loop through tickers for delisting
    M->>M: Append proposal update messages
    M->>U: Output complete proposal in JSON
Loading

Poem

Oh, I'm a clever little bunny,
Hopping through code in the sunny,
With markets visited and tickers undone,
Crafting proposals one by one.
QR codes and JSON, all's fun!
Leap high, dear code, and run!
🐇🌟

✨ 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 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: 4

🧹 Nitpick comments (4)
protocol/scripts/governance/create_delisting_proposal.py (4)

1-2: Add error handling for requests import.

Consider adding error handling for the requests import and specify the minimum required version.

 import json
+try:
   import requests
+except ImportError:
+    raise ImportError(
+        "The 'requests' package is required. "
+        "Please install it via 'pip install requests>=2.31.0'"
+    )

5-8: Consider making URLs configurable.

The hardcoded URLs limit the script's flexibility across different environments.

Consider:

  1. Moving URLs to a configuration file
  2. Adding environment variables support
  3. Adding command-line arguments for URL override
+import os
+from typing import Final
+
-MAINNET_URL_BASE = "https://dydx-ops-rest.kingnodes.com"
+MAINNET_URL_BASE: Final = os.getenv(
+    "DYDX_API_URL",
+    "https://dydx-ops-rest.kingnodes.com"
+)

73-74: Add logging configuration.

Configure logging to help with debugging and monitoring.

 if __name__ == '__main__':
+    logging.basicConfig(
+        level=logging.INFO,
+        format='%(asctime)s - %(levelname)s - %(message)s'
+    )
     main()

1-74: Add unit tests for governance operations.

Given that this script handles critical governance operations for delisting markets, it's essential to have comprehensive test coverage.

Consider adding:

  1. Unit tests for helper functions
  2. Integration tests with mock API responses
  3. Test cases for error scenarios
  4. Validation of proposal structure
  5. End-to-end tests with a test environment

Would you like me to help create a test suite for this script?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a601005 and 3f16352.

📒 Files selected for processing (1)
  • protocol/scripts/governance/create_delisting_proposal.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: unit-end-to-end-and-integration
  • GitHub Check: test-race
  • GitHub Check: test-coverage-upload
  • GitHub Check: build
  • GitHub Check: liveness-test
  • GitHub Check: golangci-lint
  • GitHub Check: benchmark
  • GitHub Check: check-sample-pregenesis-up-to-date
  • GitHub Check: container-tests
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
  • GitHub Check: Summary

# Create clob delisting proposal message
clob_delisting_message = {}
clob_delisting_message["@type"] = "/dydxprotocol.clob.MsgUpdateClobPair"
clob_delisting_message["authority"] = "dydx10d07y265gmmuvt4z0w9aw880jnsr700jnmapky"
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

Move hardcoded authority address to configuration.

The authority address is hardcoded which makes the script less maintainable and could lead to errors if the address changes.

+import os
+from typing import Final
+
+AUTHORITY_ADDRESS: Final = os.getenv(
+    "DYDX_AUTHORITY_ADDRESS",
+    "dydx10d07y265gmmuvt4z0w9aw880jnsr700jnmapky"
+)
+
-        clob_delisting_message["authority"] = "dydx10d07y265gmmuvt4z0w9aw880jnsr700jnmapky"
+        clob_delisting_message["authority"] = AUTHORITY_ADDRESS

-    marketmap_disable_message["authority"] = "dydx10d07y265gmmuvt4z0w9aw880jnsr700jnmapky"
+    marketmap_disable_message["authority"] = AUTHORITY_ADDRESS

Also applies to: 51-51

Comment on lines +14 to +18
def main():
marketmap_data = requests.get(MARKETMAP_URL).json()
perpetuals_data = requests.get(PERPETUALS_URL).json()
clob_data = requests.get(CLOB_URL).json()

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

Add error handling for HTTP requests.

The script doesn't handle potential HTTP request failures or invalid JSON responses.

Add proper error handling:

+import logging
+from typing import Any, Dict
+
+def fetch_data(url: str) -> Dict[str, Any]:
+    try:
+        response = requests.get(url, timeout=30)
+        response.raise_for_status()
+        return response.json()
+    except requests.exceptions.RequestException as e:
+        logging.error(f"Failed to fetch data from {url}: {e}")
+        raise
+    except ValueError as e:
+        logging.error(f"Invalid JSON response from {url}: {e}")
+        raise
+
 def main():
-    marketmap_data = requests.get(MARKETMAP_URL).json()
-    perpetuals_data = requests.get(PERPETUALS_URL).json()
-    clob_data = requests.get(CLOB_URL).json()
+    validate_tickers()
+    marketmap_data = fetch_data(MARKETMAP_URL)
+    perpetuals_data = fetch_data(PERPETUALS_URL)
+    clob_data = fetch_data(CLOB_URL)
📝 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():
marketmap_data = requests.get(MARKETMAP_URL).json()
perpetuals_data = requests.get(PERPETUALS_URL).json()
clob_data = requests.get(CLOB_URL).json()
import logging
from typing import Any, Dict
import requests # assuming requests is not already imported elsewhere
def fetch_data(url: str) -> Dict[str, Any]:
try:
response = requests.get(url, timeout=30)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
logging.error(f"Failed to fetch data from {url}: {e}")
raise
except ValueError as e:
logging.error(f"Invalid JSON response from {url}: {e}")
raise
def main():
validate_tickers()
marketmap_data = fetch_data(MARKETMAP_URL)
perpetuals_data = fetch_data(PERPETUALS_URL)
clob_data = fetch_data(CLOB_URL)

Comment on lines +58 to +71
def get_ticker_to_perpetual_id(perpetuals_data):
ticker_to_perpetual_id = {}
for data in perpetuals_data["perpetual"]:
ticker = data["params"]["ticker"]
perpetual_id = data["params"]["id"]
ticker_to_perpetual_id[ticker] = perpetual_id
return ticker_to_perpetual_id

def get_perpetual_id_to_clob_pair(clob_data):
perpetual_id_to_clob_pair = {}
for data in clob_data["clob_pair"]:
perpetual_id = data["perpetual_clob_metadata"]["perpetual_id"]
perpetual_id_to_clob_pair[perpetual_id] = data
return perpetual_id_to_clob_pair
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 input validation to helper functions.

The helper functions lack type hints and input validation which could lead to runtime errors.

-def get_ticker_to_perpetual_id(perpetuals_data):
+from typing import Dict
+
+def get_ticker_to_perpetual_id(perpetuals_data: Dict[str, Any]) -> Dict[str, str]:
+    if not isinstance(perpetuals_data, dict) or "perpetual" not in perpetuals_data:
+        raise ValueError("Invalid perpetuals data structure")
+
     ticker_to_perpetual_id = {}
     for data in perpetuals_data["perpetual"]:
+        if not isinstance(data, dict) or "params" not in data:
+            logging.warning(f"Skipping invalid perpetual data: {data}")
+            continue
         ticker = data["params"]["ticker"]
         perpetual_id = data["params"]["id"]
         ticker_to_perpetual_id[ticker] = perpetual_id
     return ticker_to_perpetual_id

-def get_perpetual_id_to_clob_pair(clob_data):
+def get_perpetual_id_to_clob_pair(clob_data: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
+    if not isinstance(clob_data, dict) or "clob_pair" not in clob_data:
+        raise ValueError("Invalid CLOB data structure")
+
     perpetual_id_to_clob_pair = {}
     for data in clob_data["clob_pair"]:
+        if not isinstance(data, dict) or "perpetual_clob_metadata" not in data:
+            logging.warning(f"Skipping invalid CLOB pair data: {data}")
+            continue
         perpetual_id = data["perpetual_clob_metadata"]["perpetual_id"]
         perpetual_id_to_clob_pair[perpetual_id] = data
     return perpetual_id_to_clob_pair
📝 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 get_ticker_to_perpetual_id(perpetuals_data):
ticker_to_perpetual_id = {}
for data in perpetuals_data["perpetual"]:
ticker = data["params"]["ticker"]
perpetual_id = data["params"]["id"]
ticker_to_perpetual_id[ticker] = perpetual_id
return ticker_to_perpetual_id
def get_perpetual_id_to_clob_pair(clob_data):
perpetual_id_to_clob_pair = {}
for data in clob_data["clob_pair"]:
perpetual_id = data["perpetual_clob_metadata"]["perpetual_id"]
perpetual_id_to_clob_pair[perpetual_id] = data
return perpetual_id_to_clob_pair
from typing import Dict, Any
import logging
def get_ticker_to_perpetual_id(perpetuals_data: Dict[str, Any]) -> Dict[str, str]:
if not isinstance(perpetuals_data, dict) or "perpetual" not in perpetuals_data:
raise ValueError("Invalid perpetuals data structure")
ticker_to_perpetual_id = {}
for data in perpetuals_data["perpetual"]:
if not isinstance(data, dict) or "params" not in data:
logging.warning(f"Skipping invalid perpetual data: {data}")
continue
ticker = data["params"]["ticker"]
perpetual_id = data["params"]["id"]
ticker_to_perpetual_id[ticker] = perpetual_id
return ticker_to_perpetual_id
def get_perpetual_id_to_clob_pair(clob_data: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
if not isinstance(clob_data, dict) or "clob_pair" not in clob_data:
raise ValueError("Invalid CLOB data structure")
perpetual_id_to_clob_pair = {}
for data in clob_data["clob_pair"]:
if not isinstance(data, dict) or "perpetual_clob_metadata" not in data:
logging.warning(f"Skipping invalid CLOB pair data: {data}")
continue
perpetual_id = data["perpetual_clob_metadata"]["perpetual_id"]
perpetual_id_to_clob_pair[perpetual_id] = data
return perpetual_id_to_clob_pair


DELISTED_CLOB_STATUS = "STATUS_FINAL_SETTLEMENT"

TICKERS_TO_DELIST = [] # should be in BASE-QUOTE format (ex. PAIN-USD)
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

Validate TICKERS_TO_DELIST is not empty.

An empty TICKERS_TO_DELIST list could lead to creating an invalid proposal.

Add validation at the start of the main function:

 TICKERS_TO_DELIST = [] # should be in BASE-QUOTE format (ex. PAIN-USD)
+
+def validate_tickers():
+    if not TICKERS_TO_DELIST:
+        raise ValueError(
+            "TICKERS_TO_DELIST cannot be empty. "
+            "Please specify tickers in BASE-QUOTE format (ex. PAIN-USD)"
+        )

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

@chenyaoy chenyaoy merged commit a5b8e76 into main Feb 14, 2025
21 checks passed
@chenyaoy chenyaoy deleted the chenyao/create-delisting-gov-proposal-script branch February 14, 2025 21:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging this pull request may close these issues.

2 participants