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

Distance ADO #570

Open
wants to merge 10 commits into
base: development
Choose a base branch
from
Open

Distance ADO #570

wants to merge 10 commits into from

Conversation

mdjakovic0920
Copy link
Contributor

@mdjakovic0920 mdjakovic0920 commented Sep 24, 2024

Motivation

The purpose of this ADO is to calculate the distance between 2 points on Graph.

Implementation

#[andr_instantiate]
#[cw_serde]
pub struct InstantiateMsg {}

#[andr_exec]
#[cw_serde]
pub enum ExecuteMsg {}

#[andr_query]
#[cw_serde]
#[derive(QueryResponses)]
pub enum QueryMsg {
    #[returns(String)]
    GetDistanceBetween2Points {
        point_1: Coordinate,
        point_2: Coordinate,
        decimal: u16,
    },
    #[returns(String)]
    GetManhattanDistance {
        point_1: Coordinate,
        point_2: Coordinate,
        decimal: u16,
    },
}

Testing

Unit test cases are added.

Version Changes

The version is set as 1.0.0

Summary by CodeRabbit

  • New Features

    • Introduced a new module for distance calculations within the Andromeda framework.
    • Added API schemas for smart contracts, facilitating interaction with distance-related functionalities.
    • Implemented smart contract functionalities for calculating distances in three-dimensional space.
    • Enhanced staking functionality to allow token management during unstaking.
    • Updated auction system to include a minimum raise requirement.
    • Added new entities such as the Validator Staking ADO, Asset enum, and various storage ADOs.
  • Bug Fixes

    • Resolved issues with lock time calculations in Splitter and Conditional Splitter.
    • Fixed precision issues in the vesting claim batch method.
  • Tests

    • Added comprehensive test cases for validating distance calculations and contract instantiation.
  • Documentation

    • Updated metadata and configuration files to support new features and modules.
    • Updated the changelog to reflect notable changes and new entities.

Copy link
Contributor

coderabbitai bot commented Sep 24, 2024

Walkthrough

The changes introduce a new Andromeda Distance module, which includes updates to the CHANGELOG.md and the addition of several Rust source files implementing smart contract functionalities. This module enables distance calculations in three-dimensional space, handles smart contract messages, and provides a structured API schema. It also enhances testing utilities and mock implementations to ensure functionality validation.

Changes

File Path Change Summary
CHANGELOG.md Updated to document new features including various ADOs (e.g., Validator Staking ADO), enums (Asset, Expiry), and enhancements to staking functionality. Noted changes in the auction and permissioning systems.
contracts/modules/andromeda-distance/src/contract.rs Implemented a smart contract for distance calculations, defining entry points for instantiation, execution, querying, and migration.
contracts/modules/andromeda-distance/src/mock.rs Introduced a mock implementation for testing, including methods for instantiating the contract and querying distances.
contracts/modules/andromeda-distance/src/testing/mock.rs Added testing utilities for contract instantiation and querying distances with mock dependencies.
contracts/modules/andromeda-distance/src/testing/tests.rs Created a test module with functions to verify contract instantiation and distance calculations.
packages/andromeda-modules/src/distance.rs Added a module for handling distance-related operations, defining structures for messages and coordinates.
packages/andromeda-modules/src/lib.rs Introduced the distance module to the Andromeda modules library, expanding its functionality.

Possibly related PRs

  • feat: Conditional Splitter ADO #441: The main PR includes the addition of the Conditional Splitter, which is also mentioned in the retrieved PR, indicating a direct connection in terms of functionality related to splitting funds.
  • feat: Set Amount Splitter #507: The main PR discusses the introduction of a Set Amount Splitter, which aligns with the changes in the retrieved PR that also focus on splitting mechanisms, enhancing the overall functionality of fund distribution.
  • feat: add single boolean storage to andromeda-data-storage #513: The main PR mentions the addition of a Boolean Storage ADO, which is directly referenced in the retrieved PR, indicating a shared focus on enhancing data storage capabilities.
  • feat: curve ADO #515: The main PR includes the addition of the Curve ADO, which is also highlighted in the retrieved PR, showing a direct relationship in terms of new features being introduced.
  • [IBC / Release 1] feat: IBC Registry #566: The main PR discusses the introduction of the IBC Registry ADO, which is also the focus of the retrieved PR, indicating a strong connection in terms of new components being added to the project.

Suggested labels

ci: skip-changelog

Suggested reviewers

  • joemonem
  • crnbarr93

Poem

🐰 In the land of code, where rabbits play,
New distances measured, in a smart contract way.
With schemas defined and tests all around,
The Andromeda module leaps, with joy it’s found!
Hops of precision, in three dimensions wide,
A world of distance, where we take great pride! 🌟


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

Outside diff range and nitpick comments (16)
contracts/modules/andromeda-distance/src/testing/mod.rs (1)

1-2: LGTM! Consider adding documentation comments.

The structure of the testing module looks good. It follows best practices by separating mock implementations and actual tests into different modules.

Consider adding documentation comments to provide more context about the purpose of each module. For example:

/// Mock implementations for testing purposes
mod mock;

/// Test cases for the andromeda-distance module
mod tests;

This will improve code clarity and make it easier for other developers to understand the purpose of each module at a glance.

contracts/modules/andromeda-distance/.cargo/config (1)

1-4: LGTM! Consider adding a clippy alias for linting.

The Cargo configuration looks good and aligns well with the project's objectives. The aliases provided will streamline the development workflow for WebAssembly compilation, unit testing, and schema generation.

Consider adding a clippy alias for running the Rust linter. This can help maintain code quality and catch potential issues early. You can add the following line:

clippy = "clippy -- -D warnings"

This will run Clippy with all warnings treated as errors, ensuring a high standard of code quality.

contracts/modules/andromeda-distance/src/lib.rs (3)

2-3: LGTM: Testing module declaration with a minor suggestion.

The conditional compilation of the testing module is appropriate for isolating test code. This aligns with the PR objectives mentioning the addition of unit test cases.

Consider adding a brief doc comment explaining the purpose of this module:

/// Module containing test utilities and helpers for the Andromeda distance functionality.
#[cfg(test)]
pub mod testing;

5-6: LGTM: Mock module declaration with a minor suggestion.

The conditional compilation of the mock module is well-structured, ensuring it's only included in non-WebAssembly builds with the "testing" feature enabled. This setup allows for effective mocking during tests without affecting the production WebAssembly build.

Consider adding a brief doc comment explaining the purpose of this module:

/// Module containing mock implementations for testing the Andromeda distance functionality.
#[cfg(all(not(target_arch = "wasm32"), feature = "testing"))]
pub mod mock;

1-6: Overall structure looks good, with a minor suggestion.

The file structure is clean and well-organized, properly separating the main contract logic from testing and mocking utilities. This aligns well with the PR objectives of implementing distance calculation functionality and adding unit tests.

Consider adding a module-level doc comment at the beginning of the file to provide an overview of the Andromeda distance functionality:

//! Andromeda Distance Module
//!
//! This module provides functionality for calculating distances between points
//! in a three-dimensional space, as part of the Andromeda protocol.

pub mod contract;
// ... (rest of the file)

This addition would improve the overall documentation and make it easier for other developers to understand the purpose of this module at a glance.

contracts/modules/andromeda-distance/examples/schema.rs (1)

4-9: LGTM: Correct API schema generation with a minor suggestion.

The write_api! macro is correctly used to generate the API schema for the Andromeda Distance module. It includes all necessary message types (InstantiateMsg, QueryMsg, and ExecuteMsg) as mentioned in the PR objectives.

Consider removing the blank line (line 8) within the write_api! macro for better code consistency:

 write_api! {
     instantiate: InstantiateMsg,
     query: QueryMsg,
     execute: ExecuteMsg,
-
 }
packages/andromeda-modules/src/distance.rs (4)

4-6: LGTM: InstantiateMsg is correctly defined, but consider future extensibility.

The InstantiateMsg struct is correctly defined and uses appropriate attributes. Its empty state suggests that no initialization parameters are currently required for this module.

Consider adding a comment explaining why InstantiateMsg is empty and how it might be extended in the future if initialization parameters become necessary. This can help maintain the code's clarity as the project evolves.


12-22: QueryMsg structure is good, but consider type safety and clarity improvements.

The QueryMsg enum is well-structured for a distance calculation module. However, there are a few points to consider:

  1. Returning a String for the distance calculation might not be the most type-safe or efficient approach.
  2. The purpose of the decimal parameter is not immediately clear from the context.

Consider the following improvements:

  1. Instead of returning a String, use a more specific type for the distance result. For example:

    #[returns(f64)]
    GetDistanceBetween2Points { ... }

    This ensures type safety and avoids unnecessary string conversions.

  2. Rename the decimal parameter to clarify its purpose, e.g., precision or decimal_places. Also, consider adding a comment explaining how this parameter affects the calculation.

  3. If the decimal parameter is used for formatting the output, consider separating the formatting concern from the calculation. You could return a f64 and handle formatting elsewhere.

Example:

#[returns(f64)]
GetDistanceBetween2Points {
    point_1: Coordinate,
    point_2: Coordinate,
    precision: u16, // Number of decimal places for internal calculation precision
}

These changes would improve the API's clarity and type safety.


24-29: LGTM: Coordinate struct is well-designed, consider adding documentation.

The Coordinate struct is well-designed to support both 2D and 3D coordinates. The use of f64 for coordinate values provides good precision for most use cases.

Consider the following minor improvements:

  1. Add documentation comments to the struct and its fields to explain their purpose and any constraints. For example:

    /// Represents a point in 2D or 3D space
    #[cw_serde]
    pub struct Coordinate {
        /// X-coordinate value
        pub x_coordinate: f64,
        /// Y-coordinate value
        pub y_coordinate: f64,
        /// Optional Z-coordinate value. If None, represents a 2D point
        pub z_coordinate: Option<f64>,
    }
  2. Consider adding a constructor method or associated functions for creating 2D and 3D coordinates. This can improve usability and make the intention clearer when creating coordinates. For example:

    impl Coordinate {
        pub fn new_2d(x: f64, y: f64) -> Self {
            Self {
                x_coordinate: x,
                y_coordinate: y,
                z_coordinate: None,
            }
        }
    
        pub fn new_3d(x: f64, y: f64, z: f64) -> Self {
            Self {
                x_coordinate: x,
                y_coordinate: y,
                z_coordinate: Some(z),
            }
        }
    }

These additions would enhance the struct's usability and self-documentation.


1-29: Overall, the distance module provides a solid foundation, with room for minor improvements.

The distance.rs file establishes a good structure for a distance calculation module within the Andromeda framework. Here's a summary of the main points:

  1. The use of custom attributes and Cosmos SDK utilities is appropriate and consistent.
  2. The Coordinate struct is well-designed to support both 2D and 3D coordinates.
  3. The QueryMsg enum provides a clear interface for distance calculations.

Areas for improvement:

  1. Consider adding execution messages to ExecuteMsg or provide clarification on why it's empty.
  2. Improve type safety in QueryMsg by returning a more specific type than String for distance results.
  3. Enhance documentation, especially for the Coordinate struct and its usage.
  4. Clarify the purpose of the decimal parameter in the GetDistanceBetween2Points query.

Addressing these points will further improve the module's clarity, usability, and maintainability.

contracts/modules/andromeda-distance/src/testing/mock.rs (1)

17-28: LGTM: Well-structured initialization function with a minor suggestion.

The proper_initialization function is well-implemented, following good practices for CosmWasm contract testing. It correctly sets up the mock environment, initializes the contract, and verifies that no messages are returned upon instantiation.

Consider adding a comment explaining the purpose of this function and what it returns. This would improve the readability and maintainability of the test code. For example:

/// Sets up a properly initialized mock environment for testing.
/// Returns a tuple containing the mock dependencies and message info.
pub fn proper_initialization() -> (MockDeps, MessageInfo) {
    // ... (existing implementation)
}
contracts/modules/andromeda-distance/src/testing/tests.rs (1)

11-63: LGTM: Comprehensive test cases for distance calculations.

The test function covers various scenarios for distance calculations, including 2D and 3D coordinates, as well as larger distances. This provides good coverage of the query_distance function's capabilities.

Suggestions for potential improvements:

  1. Consider adding a test case for very small distances to ensure precision for nearby points.
  2. Add a test case where z-coordinate is provided for one point but not the other, to ensure proper handling of mixed dimensionality.
  3. Consider testing with negative z-coordinates as well.
  4. Add comments explaining the expected results for better readability.

Here's an example of how you could add these improvements:

// Test case for very small distances
let query_res = query_distance(
    deps.as_ref(),
    Coordinate {
        x_coordinate: 0.0001_f64,
        y_coordinate: 0.0001_f64,
        z_coordinate: None,
    },
    Coordinate {
        x_coordinate: 0_f64,
        y_coordinate: 0_f64,
        z_coordinate: None,
    },
    5,
)
.unwrap();
// Expected result: sqrt(0.0001^2 + 0.0001^2) ≈ 0.00014142
assert_eq!(query_res, "0.00014".to_string());

// Test case for mixed dimensionality
let query_res = query_distance(
    deps.as_ref(),
    Coordinate {
        x_coordinate: 1_f64,
        y_coordinate: 1_f64,
        z_coordinate: Some(1_f64),
    },
    Coordinate {
        x_coordinate: 0_f64,
        y_coordinate: 0_f64,
        z_coordinate: None,
    },
    5,
)
.unwrap();
// Expected result: sqrt(1^2 + 1^2 + 1^2) ≈ 1.73205
assert_eq!(query_res, "1.73205".to_string());

// Test case with negative z-coordinate
let query_res = query_distance(
    deps.as_ref(),
    Coordinate {
        x_coordinate: 1_f64,
        y_coordinate: 1_f64,
        z_coordinate: Some(-1_f64),
    },
    Coordinate {
        x_coordinate: 0_f64,
        y_coordinate: 0_f64,
        z_coordinate: Some(1_f64),
    },
    5,
)
.unwrap();
// Expected result: sqrt(1^2 + 1^2 + 2^2) ≈ 2.44949
assert_eq!(query_res, "2.44949".to_string());
contracts/modules/andromeda-distance/src/mock.rs (4)

12-13: LGTM: Well-structured MockDistance definition.

The MockDistance struct and its trait implementation using the mock_ado! macro are well-defined.

Consider adding a brief doc comment to explain the purpose of the MockDistance struct:

/// Represents a mock implementation of the Distance contract for testing purposes.
pub struct MockDistance(Addr);

15-35: LGTM: Well-implemented instantiate method.

The instantiate method correctly sets up a new contract instance using the provided parameters.

Consider improving error handling by propagating the error instead of using unwrap():

pub fn instantiate(
    code_id: u64,
    sender: Addr,
    app: &mut MockApp,
    kernel_address: String,
    owner: Option<String>,
) -> Result<MockDistance, anyhow::Error> {
    let msg = mock_distance_instantiate_msg(kernel_address, owner);
    let addr = app
        .instantiate_contract(
            code_id,
            sender.clone(),
            &msg,
            &[],
            "Distance Contract",
            Some(sender.to_string()),
        )?;
    Ok(MockDistance(Addr::unchecked(addr)))
}

This change would allow callers to handle potential errors more gracefully.


37-51: LGTM: Well-implemented query_distance method.

The query_distance method correctly constructs the query message and executes it.

Consider using a more specific return type instead of String to improve type safety:

pub fn query_distance(
    &self,
    app: &mut MockApp,
    point_1: Coordinate,
    point_2: Coordinate,
    decimal: u16,
) -> Result<f64, StdError> {
    let msg = QueryMsg::GetDistanceBetween2Points {
        point_1,
        point_2,
        decimal,
    };
    let res: String = self.query(app, msg);
    res.parse::<f64>().map_err(StdError::parse_err)
}

This change would ensure that the returned value is a valid floating-point number and make it easier for callers to use the result directly in calculations.


54-67: LGTM: Well-implemented utility functions.

The mock_andromeda_distance and mock_distance_instantiate_msg functions are correctly implemented for their purposes.

Consider adding brief doc comments to explain the purpose of these utility functions:

/// Creates a mock Contract implementation for the Andromeda Distance module.
pub fn mock_andromeda_distance() -> Box<dyn Contract<Empty>> {
    // ... (existing implementation)
}

/// Creates an InstantiateMsg for the Andromeda Distance module with the given parameters.
pub fn mock_distance_instantiate_msg(
    kernel_address: String,
    owner: Option<String>,
) -> InstantiateMsg {
    // ... (existing implementation)
}

These comments would improve the code's self-documentation and make it easier for other developers to understand and use these functions.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ee4434e and 0ed1ce2.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (11)
  • contracts/modules/andromeda-distance/.cargo/config (1 hunks)
  • contracts/modules/andromeda-distance/Cargo.toml (1 hunks)
  • contracts/modules/andromeda-distance/examples/schema.rs (1 hunks)
  • contracts/modules/andromeda-distance/src/contract.rs (1 hunks)
  • contracts/modules/andromeda-distance/src/lib.rs (1 hunks)
  • contracts/modules/andromeda-distance/src/mock.rs (1 hunks)
  • contracts/modules/andromeda-distance/src/testing/mock.rs (1 hunks)
  • contracts/modules/andromeda-distance/src/testing/mod.rs (1 hunks)
  • contracts/modules/andromeda-distance/src/testing/tests.rs (1 hunks)
  • packages/andromeda-modules/src/distance.rs (1 hunks)
  • packages/andromeda-modules/src/lib.rs (1 hunks)
Additional comments not posted (21)
packages/andromeda-modules/src/lib.rs (1)

3-3: LGTM! Verify module implementation.

The addition of the distance module aligns with the PR objectives for implementing distance calculation functionality. The module is correctly declared as public and placed in alphabetical order.

To ensure the module is properly implemented, please run the following verification script:

This script will help verify the existence of the distance.rs file, check its basic structure, and look for potential naming conflicts with other modules.

Verification successful

Action Required: Re-verify Potential Naming Conflicts in the distance Module

The initial verification script encountered an error while checking for potential naming conflicts. Please run the updated verification script below to ensure there are no naming conflicts with the distance module.

This updated script corrects the previous error by properly excluding distance.rs when searching for the term "distance" to identify any potential naming conflicts with other modules.


Action Required: Re-verify Potential Naming Conflicts in the distance Module with Corrected Script

The previous verification script encountered an error while excluding distance.rs. Please run the updated verification script below, which correctly excludes the distance.rs file using the --glob flag with a negation pattern.

This updated script uses the --glob flag with the negation pattern !packages/andromeda-modules/src/distance.rs to properly exclude the distance.rs file when searching for the term "distance" across the codebase. This should eliminate the previous error and accurately check for any naming conflicts with other modules.


Verification Successful: No Naming Conflicts Found in the distance Module

The distance module has been successfully added with the correct structure and placement. No naming conflicts were detected in the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and basic structure of the distance module

# Test 1: Check if the distance.rs file exists
echo "Checking for distance.rs file..."
fd --type f "^distance\.rs$" packages/andromeda-modules/src

# Test 2: Verify basic structure of the distance module
echo "Verifying basic structure of the distance module..."
rg --type rust "^(pub )?(struct|enum|fn) \w+" packages/andromeda-modules/src/distance.rs

# Test 3: Check for potential naming conflicts
echo "Checking for potential naming conflicts..."
rg --type rust "\bdistance\b" packages/andromeda-modules/src --files-without-match distance.rs

Length of output: 940


Script:

#!/bin/bash
# Description: Verify the existence and basic structure of the distance module, and check for potential naming conflicts

# Test 1: Check if the distance.rs file exists
echo "Checking for distance.rs file..."
fd --type f "^distance\.rs$" packages/andromeda-modules/src

# Test 2: Verify basic structure of the distance module
echo "Verifying basic structure of the distance module..."
rg --type rust "^(pub )?(struct|enum|fn) \w+" packages/andromeda-modules/src/distance.rs

# Test 3: Check for potential naming conflicts excluding distance.rs
echo "Checking for potential naming conflicts excluding distance.rs..."
rg --type rust "\bdistance\b" packages/andromeda-modules/src --ignore 'distance.rs'

Length of output: 909


Script:

#!/bin/bash
# Description: Verify the existence and basic structure of the distance module, and check for potential naming conflicts

# Test 1: Check if the distance.rs file exists
echo "Checking for distance.rs file..."
fd --type f "^distance\.rs$" packages/andromeda-modules/src

# Test 2: Verify basic structure of the distance module
echo "Verifying basic structure of the distance module..."
rg --type rust "^(pub )?(struct|enum|fn) \w+" packages/andromeda-modules/src/distance.rs

# Test 3: Check for potential naming conflicts excluding distance.rs
echo "Checking for potential naming conflicts excluding distance.rs..."
rg --type rust "\bdistance\b" packages/andromeda-modules/src --glob '!packages/andromeda-modules/src/distance.rs'

Length of output: 889

contracts/modules/andromeda-distance/src/lib.rs (1)

1-1: LGTM: Main contract module declaration.

The public declaration of the contract module is appropriate. This module will likely contain the core logic for the Andromeda distance functionality, as described in the PR objectives.

contracts/modules/andromeda-distance/examples/schema.rs (3)

1-2: LGTM: Appropriate imports for schema generation.

The import statements are correct and necessary for the file's purpose. They bring in the required message types from the andromeda_modules::distance module and the write_api macro from cosmwasm_schema for generating the API schema.


3-3: LGTM: Correct main function declaration.

The main function is correctly declared as the entry point for the schema generation script. It doesn't take any parameters or return a value, which is appropriate for this use case.


1-10: Overall assessment: Well-structured and correct schema generation.

This file correctly implements the API schema generation for the Andromeda Distance module. It aligns well with the PR objectives, defining the necessary message types (InstantiateMsg, QueryMsg, and ExecuteMsg) as mentioned. The code is concise, focused, and follows best practices for CosmWasm schema generation.

packages/andromeda-modules/src/distance.rs (1)

1-2: LGTM: Imports are appropriate and concise.

The import statements are well-structured and import only the necessary components from the Andromeda framework and Cosmos SDK. This promotes clean and efficient code organization.

contracts/modules/andromeda-distance/Cargo.toml (6)

1-5: LGTM: Package metadata is well-defined.

The package metadata is correctly specified:

  • The name "andromeda-distance" follows the convention for Andromeda modules.
  • The version (1.0.0) matches the PR objectives.
  • The Rust edition (2021) is up-to-date.
  • The Rust version (1.75.0) is specific and recent.

7-8: LGTM: Library configuration is correct for a CosmWasm smart contract.

The crate-type is correctly set to both "cdylib" and "rlib":

  • "cdylib" is used for creating a dynamic library, which is necessary for WebAssembly smart contracts.
  • "rlib" allows the crate to be used as a dependency by other Rust crates, enabling code reuse.

10-15: LGTM: Features are well-defined and appropriate.

The features section is correctly configured:

  • The "backtraces" feature is properly tied to "cosmwasm-std/backtraces" for explicit tests.
  • The "library" feature is correctly defined to disable exports when needed.
  • The "testing" feature appropriately depends on "cw-multi-test" and "andromeda-testing".

18-29: LGTM: Dependencies are correctly specified and organized.

The dependencies section is well-structured:

  • Workspace-level versions are used, ensuring consistency across the project.
  • All necessary libraries for a CosmWasm smart contract in the Andromeda ecosystem are included.
  • Target-specific dependencies for non-WASM32 targets are correctly marked as optional.

31-32: LGTM: Dev-dependencies are appropriately specified.

The dev-dependencies section is concise and correct:

  • The "andromeda-app" dependency is properly sourced from the workspace.
  • It's appropriate to have fewer dev-dependencies, as many testing dependencies are already included in the main dependencies section.

1-32: Overall assessment: Cargo.toml is well-structured and complete.

The Cargo.toml file for the andromeda-distance package is correctly configured and aligns well with the PR objectives. It includes all necessary sections:

  • Package metadata with correct name, version, and Rust specifications.
  • Library configuration suitable for a CosmWasm smart contract.
  • Well-defined features for various use cases.
  • Comprehensive list of dependencies, including workspace-level versions.
  • Appropriate dev-dependencies.

The file structure and content demonstrate good practices for an Andromeda module.

contracts/modules/andromeda-distance/src/testing/mock.rs (2)

1-15: LGTM: Imports and type definitions are appropriate.

The imports and type definitions are well-structured and appropriate for a testing module in the Andromeda ecosystem. The use of MockDeps as a type alias is a good practice for CosmWasm contract testing.


1-49: Overall, well-structured testing module with minor improvement suggestions.

This file provides essential testing utilities for the Andromeda distance module. It includes mock setup, contract initialization, and a query function for distance calculation. The structure and implementation are generally good, following CosmWasm testing practices.

Key points:

  1. Proper mock environment setup in proper_initialization.
  2. Convenient query_distance function for testing the main functionality.

The suggested improvements (adding comments, enhancing error handling, and improving type safety) will further increase the robustness and maintainability of this testing module.

contracts/modules/andromeda-distance/src/testing/tests.rs (2)

1-2: LGTM: Imports are appropriate for the tests.

The import statements correctly bring in the necessary components from the mock module and the andromeda_modules crate, which are essential for the tests in this file.


4-7: LGTM: Test function verifies proper initialization.

The test_instantiation function correctly calls the proper_initialization function to verify the module's initialization. This is a good basic test to ensure the module sets up correctly.

contracts/modules/andromeda-distance/src/mock.rs (1)

1-10: LGTM: Appropriate attributes and imports.

The conditional compilation attribute and imports are well-structured and appropriate for a mock implementation used in testing.

contracts/modules/andromeda-distance/src/contract.rs (4)

17-39: Initialization logic in instantiate function looks good

The instantiate function correctly initializes the contract using ADOContract, setting up the necessary contract metadata and ensuring proper configuration.


67-69: Ensure all execute messages are properly handled

The handle_execute function matches on msg but only has a catch-all case delegating to ADOContract::execute. This might lead to unhandled messages if new variants are added to ExecuteMsg in the future.

Consider explicitly matching on all variants of ExecuteMsg to ensure that all execute messages are properly handled and to make the code more maintainable.


85-86: Ensure all query messages are properly handled

In the query function, the catch-all case delegates to ADOContract::query. Similar to execute, this might lead to unhandled messages if new variants are added to QueryMsg.

Consider explicitly matching on all variants of QueryMsg to ensure comprehensive handling of query messages.


107-110: Migration logic in migrate function is properly handled

The migrate function correctly delegates migration to ADOContract, ensuring that contract upgrades are managed appropriately.

packages/andromeda-modules/src/distance.rs Show resolved Hide resolved
contracts/modules/andromeda-distance/src/testing/tests.rs Outdated Show resolved Hide resolved
contracts/modules/andromeda-distance/src/contract.rs Outdated Show resolved Hide resolved
contracts/modules/andromeda-distance/src/contract.rs Outdated Show resolved Hide resolved
}
}

pub fn get_distance(
Copy link
Contributor

Choose a reason for hiding this comment

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

Adding a Manhattan distance query could be useful as well!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sounds great.
I added Manhattan Distance Query.

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)
CHANGELOG.md (3)

27-27: LGTM! Consider adding more details about the IBC Distance ADO.

The new entry is correctly formatted and placed in the "Added" section of the changelog. It accurately reflects the addition of the IBC Distance ADO as mentioned in the PR objectives.

To provide more context for users, consider expanding the entry with a brief description of the IBC Distance ADO's purpose or key features. For example:

- Added IBC Distance ADO [(#570)](https://github.com/andromedaprotocol/andromeda-core/pull/570)
+ Added IBC Distance ADO for calculating distances between points in a three-dimensional space [(#570)](https://github.com/andromedaprotocol/andromeda-core/pull/570)

Line range hint 1-70: Consider adding a version number for the unreleased changes.

The changelog is well-structured and follows the Keep a Changelog format. However, to improve version management and provide more context for users, consider adding a version number for the unreleased changes.

You could update the "Unreleased" header to include the expected version number. For example:

- ## Unreleased
+ ## [Unreleased] - 1.x.x

Replace "1.x.x" with the appropriate version number based on your versioning strategy and the nature of the changes (e.g., 1.1.0 for new features, 1.0.1 for bug fixes, etc.).


27-27: Align the changelog entry with the PR objectives.

While the current entry correctly mentions the addition of the IBC Distance ADO, it doesn't fully capture the specific functionality described in the PR objectives.

Consider updating the changelog entry to more closely reflect the PR objectives. For example:

- Added IBC Distance ADO [(#570)](https://github.com/andromedaprotocol/andromeda-core/pull/570)
+ Added IBC Distance ADO for calculating distances between points in a three-dimensional space, including structures for coordinates and query messages [(#570)](https://github.com/andromedaprotocol/andromeda-core/pull/570)

This change would provide users with a clearer understanding of the new functionality introduced by this ADO.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d7c3ff6 and c062147.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • CHANGELOG.md (1 hunks)
🧰 Additional context used
🔇 Additional comments (1)
CHANGELOG.md (1)

Line range hint 1-70: LGTM! Changelog update is appropriate with minor suggestions for improvement.

The addition of the IBC Distance ADO to the changelog is correct and follows the established format. The suggestions provided in the previous comments will help improve clarity and version management:

  1. Consider adding more details about the IBC Distance ADO's functionality.
  2. Add a version number for the unreleased changes.
  3. Align the changelog entry more closely with the PR objectives.

These minor improvements will enhance the changelog's usefulness for users and contributors.

Copy link
Contributor

@crnbarr93 crnbarr93 left a comment

Choose a reason for hiding this comment

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

This could be a great addition to the map/point ADOs added in #576!

Maybe being able to calculate the distance between two points using the Point ADO or some points on the Graph ADO?

CHANGELOG.md Outdated Show resolved Hide resolved
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I added Manhattan Distance Query

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

🧹 Outside diff range and nitpick comments (3)
contracts/modules/andromeda-distance/src/testing/mock.rs (1)

17-28: LGTM: Well-structured initialization function with a minor suggestion.

The proper_initialization function provides a solid setup for testing. It correctly initializes mock dependencies, creates necessary messages, and asserts the result of instantiation.

Consider adding a comment explaining why owner is set to None in the InstantiateMsg. This would improve code clarity and prevent potential confusion in the future.

contracts/modules/andromeda-distance/src/testing/tests.rs (1)

10-121: Consider adding edge case tests.

While the current test cases cover a good range of scenarios, consider adding tests for edge cases to further improve robustness.

Some suggestions for additional test cases:

  1. Test with very large coordinate values to check for potential overflow issues.
  2. Test with very small coordinate differences to ensure precision in near-zero distances.
  3. Test with negative z-coordinates for 3D points.
  4. Test with the maximum allowed decimal places to ensure correct rounding behavior.

Example:

// Test with very large coordinates
let query_res = query_distance(
    deps.as_ref(),
    Coordinate {
        x_coordinate: 1e15,
        y_coordinate: 1e15,
        z_coordinate: None,
    },
    Coordinate {
        x_coordinate: 1e15 + 1.0,
        y_coordinate: 1e15 + 1.0,
        z_coordinate: None,
    },
    5,
)
.unwrap();
assert_approx_eq(&query_res, "1.41421", 1e-5);
contracts/modules/andromeda-distance/src/mock.rs (1)

16-35: Add documentation comments to public methods

To enhance code readability and maintainability, consider adding documentation comments (///) to the public methods and functions, explaining their purpose, parameters, and return values.

Also applies to: 37-51, 53-67, 75-83

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c062147 and f866e48.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • CHANGELOG.md (1 hunks)
  • contracts/modules/andromeda-distance/src/contract.rs (1 hunks)
  • contracts/modules/andromeda-distance/src/mock.rs (1 hunks)
  • contracts/modules/andromeda-distance/src/testing/mock.rs (1 hunks)
  • contracts/modules/andromeda-distance/src/testing/tests.rs (1 hunks)
  • packages/andromeda-modules/src/distance.rs (1 hunks)
  • packages/andromeda-modules/src/lib.rs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/andromeda-modules/src/lib.rs
🧰 Additional context used
🔇 Additional comments (8)
contracts/modules/andromeda-distance/src/testing/mock.rs (2)

1-15: LGTM: Imports and type alias are well-structured.

The imports cover all necessary modules for testing, and the MockDeps type alias enhances code readability.


30-49: Skipping comment generation.

The existing review comment from the previous review is still valid and addresses the issues in this function.

contracts/modules/andromeda-distance/src/testing/tests.rs (3)

1-3: LGTM: Imports are appropriate and concise.

The import statements are well-structured and import the necessary components for the tests. They cover the mock functions, the Coordinate struct, and the ContractError enum, which are all used in the subsequent test functions.


5-8: LGTM: Initialization test is concise and focused.

The test_instantiation function effectively tests the proper initialization of the module. It's a simple yet crucial test that ensures the basic setup of the contract is correct.


10-121: LGTM: Comprehensive test coverage for distance calculations.

The test_query_distance function provides thorough testing for both query_distance and query_manhattan_distance functions. It covers various scenarios including 2D and 3D coordinates, and includes error handling tests. The function name appropriately reflects its purpose, addressing the previous review comment.

CHANGELOG.md (1)

28-28: LGTM! Changelog entry correctly added.

The new changelog entry for the Distance ADO is well-formatted and properly placed in the "Added" section. It follows the suggestion from the previous review and aligns with the PR objectives.

packages/andromeda-modules/src/distance.rs (1)

37-41: ⚠️ Potential issue

Verify the usage of the DistanceType enum

The DistanceType enum is defined but not used within this module. Verify whether it is intended for future use or if it can be removed to clean up the code.

Run the following script to check for usages of DistanceType in the codebase:

✅ Verification successful

The DistanceType enum is actively used in other modules and serves its intended purpose. No removal is necessary.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for usages of `DistanceType` outside its definition.

# Test: Find all occurrences of `DistanceType` excluding its own definition. Expect: Identifying if it's used elsewhere.
rg --type rust 'DistanceType' | grep -v 'pub enum DistanceType'

Length of output: 758

contracts/modules/andromeda-distance/src/mock.rs (1)

13-13: ⚠️ Potential issue

Missing import of ExecuteMsg

The macro mock_ado! is invoked with ExecuteMsg and QueryMsg, but ExecuteMsg is not imported in this file. This will lead to a compilation error.

Apply this diff to fix the missing import:

+ use andromeda_modules::distance::ExecuteMsg;

Likely invalid or redundant comment.

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