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

Graph ADO (version 1.1.0) and Point ADO #576

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

Conversation

mdjakovic0920
Copy link
Contributor

@mdjakovic0920 mdjakovic0920 commented Oct 9, 2024

1. Graph ADO

Motivation

The purpose of this ADO is to store X-Y coordinates into specific map.
The map bounds or limits to where points can be stored. And also it contains decimals and allow/disallow negative numbers.

At version 1.1.0
store_user_coordinate method is added.
This function references the user coordinate from Point ADO.

Implementation

#[andr_instantiate]
#[cw_serde]
pub struct InstantiateMsg {
    pub map_info: MapInfo,
}

#[cw_serde]
pub struct MapInfo {
    pub map_size: MapSize,
    pub allow_negative: bool,
    pub map_decimal: u16,
}

#[cw_serde]
pub struct MapSize {
    pub x_width: u64,
    pub y_width: u64,
    pub z_width: Option<u64>,
}

#[andr_exec]
#[cw_serde]
pub enum ExecuteMsg {
    UpdateMap {
        map_info: MapInfo,
    },
    StoreCoordinate {
        coordinate: Coordinate,
        is_timestamp_allowed: bool,
    },
    StoreUserCoordinate {
        user_location_paths: Vec<AndrAddr>,
    },
    DeleteUserCoordinate {
        user: AndrAddr,
    },
}

#[cw_serde]
pub struct Coordinate {
    pub x_coordinate: f64,
    pub y_coordinate: f64,
    pub z_coordinate: Option<f64>,
}

#[andr_query]
#[cw_serde]
#[derive(QueryResponses)]
pub enum QueryMsg {
    #[returns(GetMapInfoResponse)]
    GetMapInfo {},
    #[returns(GetMaxPointNumberResponse)]
    GetMaxPointNumber {},
    #[returns(GetAllPointsResponse)]
    GetAllPoints {},
    #[returns(CoordinateInfo)]
    GetUserCoordinate { user: AndrAddr },
}

#[cw_serde]
pub struct GetMapInfoResponse {
    pub map_info: MapInfo,
}

#[cw_serde]
pub struct GetMaxPointNumberResponse {
    pub max_point_number: u128,
}

#[cw_serde]
pub struct GetAllPointsResponse {
    pub points: Vec<(CoordinateInfo, StoredDate)>,
}

#[cw_serde]
pub struct CoordinateInfo {
    pub x: String,
    pub y: String,
    pub z: Option<String>,
}

#[cw_serde]
pub struct StoredDate {
    pub timestamp: Option<u64>,
}

2. Point ADO

Motivation

The purpose of this ADO is to store x, y, z coordinate.

Implementation

#[andr_instantiate]
#[cw_serde]
pub struct InstantiateMsg {
    pub restriction: PointRestriction,
}

#[andr_exec]
#[cw_serde]
pub enum ExecuteMsg {
    SetPoint { point: PointCoordinate },
    DeletePoint {},
    UpdateRestriction { restriction: PointRestriction },
}

#[cw_serde]
pub enum PointRestriction {
    Private,
    Public,
    Restricted,
}

#[cw_serde]
pub struct PointCoordinate {
    pub x_coordinate: String,
    pub y_coordinate: String,
    pub z_coordinate: Option<String>,
}

impl PointCoordinate {
    pub fn from_f64(x_coordinate: f64, y_coordinate: f64, z_coordinate: Option<f64>) -> Self {
        let z_coordinate: Option<String> = z_coordinate.map(|z| z.to_string());

        Self {
            x_coordinate: x_coordinate.to_string(),
            y_coordinate: y_coordinate.to_string(),
            z_coordinate,
        }
    }
    pub fn validate(&self) -> Result<(), ContractError> {
        let x_coordinate = self.x_coordinate.parse::<f64>();
        if x_coordinate.is_err() {
            return Err(ContractError::ParsingError {
                err: "x_coordinate: can not parse to f64".to_string(),
            });
        }

        let y_coordinate = self.y_coordinate.parse::<f64>();
        if y_coordinate.is_err() {
            return Err(ContractError::ParsingError {
                err: "y_coordinate: can not parse to f64".to_string(),
            });
        }

        match &self.z_coordinate {
            None => (),
            Some(z) => {
                let z_coordinate = z.parse::<f64>();
                if z_coordinate.is_err() {
                    return Err(ContractError::ParsingError {
                        err: "z_coordinate: can not parse to f64".to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

#[andr_query]
#[cw_serde]
#[derive(QueryResponses)]
pub enum QueryMsg {
    #[returns(PointCoordinate)]
    GetPoint {},
    #[returns(GetDataOwnerResponse)]
    GetDataOwner {},
}

#[cw_serde]
pub struct GetDataOwnerResponse {
    pub owner: AndrAddr,
}

Summary by CodeRabbit

  • New Features

    • Introduced Validator Staking ADO, Asset enum, and ADOBaseVersion query.
    • Enhanced staking functionality with reward token management.
    • Added new ADOs including Conditional Splitter, Graph ADO, String Storage, Boolean Storage, Counter, and Date Time ADOs.
    • Updated Marketplace with authorized CW721 addresses and BuyNow option for auctions.
    • Implemented denom validation in IBC Registry ADO.
    • Established a comprehensive framework for managing map data within the Andromeda data storage.
  • Bug Fixes

    • Resolved issues with zero send messages, lock time calculations, and AMPPkt origin verification.
    • Addressed permissioning limitations and precision issues in vesting claim batch method.
  • Documentation

    • Updated CHANGELOG.md to reflect notable changes and new features.
  • Tests

    • Added comprehensive unit tests for various functionalities in the Andromeda data storage modules.

mdjakovic0920 and others added 30 commits July 24, 2024 22:30
Copy link
Contributor

coderabbitai bot commented Oct 9, 2024

Walkthrough

The pull request introduces extensive updates to the Andromeda data storage project, including new modules for managing maps and coordinates, enhancements to existing ADOs, and improvements to the permissioning system. It features the addition of various ADOs, enums, and queries, alongside a comprehensive smart contract implementation for the Andromeda Graph module. Testing utilities and mock implementations have been added to support robust testing. The changes also address multiple bugs and refine existing functionalities, contributing to a more efficient framework for data management.

Changes

File Path Change Summary
CHANGELOG.md Updated to document new features like Validator Staking ADO, Asset enum, ADOBaseVersion query, Conditional Splitter, and various ADOs. Enhanced staking and auction features.
contracts/data-storage/andromeda-graph/src/contract.rs New smart contract implementation with functions for instantiation, execution, querying, and migration, including various execution and query functions for managing maps.
contracts/data-storage/andromeda-graph/src/testing/mock.rs New mock functions and types for testing, providing methods for initialization and interaction with the contract.
packages/andromeda-data-storage/src/graph.rs New data structures and message types for managing map-related functionalities, including InstantiateMsg, MapInfo, and various query and execution messages.

Possibly related PRs

Suggested labels

ci: skip-changelog

Suggested reviewers

  • crnbarr93
  • joemonem
  • SlayerAnsh

Poem

In the garden of code, we hop and play,
New features sprout, brightening the day.
With mocks and tests, we dance with delight,
Building a world where data takes flight! 🐇✨
So let’s cheer for the changes, both big and small,
In the realm of Andromeda, we’re having a ball!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 414ec59 and 03953be.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • CHANGELOG.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.md

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

🧹 Outside diff range and nitpick comments (24)
contracts/data-storage/andromeda-point/.cargo/config (1)

1-4: LGTM! Consider adding optimization flags for WASM builds.

The Cargo aliases are well-defined and will streamline common development tasks. They cover essential operations: building for WebAssembly, running unit tests, and generating the schema.

For the wasm alias, consider adding optimization flags to ensure the smallest possible binary size, which is crucial for smart contracts. You could modify it as follows:

-wasm = "build --release --target wasm32-unknown-unknown"
+wasm = "build --release --target wasm32-unknown-unknown --no-default-features --features producer"

This change removes default features and adds a hypothetical "producer" feature, which is a common pattern in smart contract projects to minimize the contract size.

contracts/data-storage/andromeda-graph/src/lib.rs (2)

1-2: LGTM! Consider adding module-level documentation.

The public modules contract and state align well with the PR objectives for introducing the Graph ADO. This modular structure promotes better organization and separation of concerns.

Consider adding module-level documentation comments (//!) for these public modules to provide a brief overview of their purposes and contents. This would enhance the codebase's maintainability and make it easier for other developers to understand the project structure.


4-5: LGTM! Consider adding a brief comment explaining the conditional compilation.

The conditional compilation for the mock module is well-structured, ensuring it's only included for testing purposes and not in WebAssembly builds. This aligns with best practices for separating test code from production code.

Consider adding a brief comment above the #[cfg] attribute to explain why this module is conditionally compiled. For example:

// Mock module for testing, excluded from WebAssembly builds
#[cfg(all(not(target_arch = "wasm32"), feature = "testing"))]
pub mod mock;

This would provide quick context for other developers reviewing or working on the code.

contracts/data-storage/andromeda-graph/examples/schema.rs (2)

3-10: LGTM: Main function correctly generates the API schema.

The main function effectively uses the write_api! macro to generate the API schema for the Andromeda data storage graph. It correctly specifies the message types for instantiation, querying, and execution.

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

 fn main() {
     write_api! {
         instantiate: InstantiateMsg,
         query: QueryMsg,
         execute: ExecuteMsg,
-
     }
 }

1-10: Overall assessment: Well-structured schema generation for Graph ADO.

This file effectively sets up the schema generation for the Graph ADO, which is a key component introduced in this PR. It correctly imports the necessary types and uses the write_api! macro to define the API schema. The implementation aligns well with CosmWasm conventions and the PR objectives.

As the project grows, consider maintaining a consistent schema generation approach across all ADOs to ensure uniformity and ease of maintenance.

contracts/data-storage/andromeda-point/src/state.rs (2)

5-7: LGTM: Constants are well-defined and cover necessary state items.

The constants DATA, DATA_OWNER, and RESTRICTION are appropriately defined using cw_storage_plus::Item for efficient state management. They cover the essential aspects of the Point ADO: coordinate data, ownership, and access restrictions.

For consistency, consider using all uppercase for the string identifiers:

-pub const DATA: Item<PointCoordinate> = Item::new("data");
-pub const DATA_OWNER: Item<Addr> = Item::new("data_owner");
-pub const RESTRICTION: Item<PointRestriction> = Item::new("restriction");
+pub const DATA: Item<PointCoordinate> = Item::new("DATA");
+pub const DATA_OWNER: Item<Addr> = Item::new("DATA_OWNER");
+pub const RESTRICTION: Item<PointRestriction> = Item::new("RESTRICTION");

This aligns with the common convention of using uppercase for constant values and improves readability.


1-7: Overall implementation is solid and aligns with PR objectives.

This state.rs file effectively sets up the core state management for the Point ADO, as described in the PR objectives. It defines storage for three-dimensional coordinates (DATA), ownership (DATA_OWNER), and access restrictions (RESTRICTION), which align perfectly with the Point ADO requirements.

The use of cw_storage_plus::Item for state management is a good practice in CosmWasm contract development, ensuring efficient and type-safe storage operations.

As the project grows, consider creating a separate types.rs file for PointCoordinate and PointRestriction if they're not already in one. This can improve modularity and make it easier to reuse these types across different parts of the project.

contracts/data-storage/andromeda-graph/Cargo.toml (1)

18-23: LGTM! Features are well-defined, but consider adding more documentation.

The features section is well-structured and provides useful options for development and testing. The "backtraces" and "testing" features are clear in their purpose.

However, the "library" feature's purpose might not be immediately clear to all developers. Consider adding a brief comment or documentation explaining when and why one might want to use this feature.

contracts/data-storage/andromeda-point/src/testing/mock.rs (4)

18-29: LGTM: proper_initialization function is well-implemented.

The function correctly sets up the mock environment and instantiates the contract. It's a good practice to return both the mock dependencies and the message info for further testing.

Consider adding a brief comment explaining the purpose of this function at the beginning, e.g.:

/// Initializes the mock environment and instantiates the contract with the given PointRestriction.
/// Returns the mock dependencies and message info for further testing.
pub fn proper_initialization(restriction: PointRestriction) -> (MockDeps, MessageInfo) {
    // ... (existing implementation)
}

31-37: LGTM: query_point function is correctly implemented.

The function properly queries the contract and handles both success and error cases.

Consider simplifying the error handling by using the ? operator instead of pattern matching:

pub fn query_point(deps: Deps) -> Result<PointCoordinate, ContractError> {
    let res = query(deps, mock_env(), QueryMsg::GetPoint {})?;
    Ok(from_json(res)?)
}

This change would make the function more concise and idiomatic Rust.


39-62: LGTM: set_point and set_point_with_funds functions are well-implemented.

Both functions correctly create and execute the SetPoint message, with set_point_with_funds providing the additional functionality of including funds.

Consider using a single function with an optional funds parameter to reduce code duplication:

pub fn set_point(
    deps: DepsMut<'_>,
    point: &PointCoordinate,
    sender: &str,
    funds: Option<Coin>,
) -> Result<Response, ContractError> {
    let msg = ExecuteMsg::SetPoint {
        point: point.clone(),
    };
    let info = match funds {
        Some(coin) => mock_info(sender, &[coin]),
        None => mock_info(sender, &[]),
    };
    execute(deps, mock_env(), info, msg)
}

This change would combine the functionality of both functions, making the code more maintainable.


1-68: Overall, the mock testing utilities are well-implemented and comprehensive.

This file provides a solid foundation for testing the Andromeda data storage contract. The functions cover initialization, querying, setting, and deleting points, which should allow for thorough testing of the contract's functionality.

Consider adding the following to further enhance the testing capabilities:

  1. A function to query multiple points or all points stored in the contract.
  2. Functions to test edge cases, such as setting points with invalid coordinates or attempting operations with insufficient permissions.
  3. Helper functions to assert the state of the contract after various operations.

These additions would make the testing suite even more robust and comprehensive.

CHANGELOG.md (1)

19-19: LGTM! Consider adding a brief description of the Graph ADO.

The addition of the Graph ADO is well-documented and consistent with the changelog format. It aligns with the PR objectives mentioned earlier.

To provide more context for future readers, consider adding a brief description of the Graph ADO's purpose. For example:

- Added Graph ADO [(#526)](https://github.com/andromedaprotocol/andromeda-core/pull/526)
+ Added Graph ADO for storing and managing X-Y coordinates [(#526)](https://github.com/andromedaprotocol/andromeda-core/pull/526)
packages/std/src/testing/mock_querier.rs (2)

Line range hint 309-313: LGTM! Consider using a match arm for better readability.

The addition of the new case for code ID 5 is correct and aligns with the introduction of the Point ADO. To improve code readability and maintainability, consider refactoring this part of the method to use a match expression instead of multiple if-else statements.

Here's a suggested refactor:

-            ADODBQueryMsg::ADOType { code_id } => match code_id {
-                5 => SystemResult::Ok(ContractResult::Ok(to_json_binary(&"point").unwrap())),
-                3 => SystemResult::Ok(ContractResult::Ok(to_json_binary(&"app-contract").unwrap())),
-                1 => SystemResult::Ok(ContractResult::Ok(to_json_binary(&"ADOType").unwrap())),
-                _ => SystemResult::Ok(ContractResult::Err("Invalid Code ID".to_string())),
-            },
+            ADODBQueryMsg::ADOType { code_id } => {
+                let ado_type = match code_id {
+                    5 => "point",
+                    3 => "app-contract",
+                    1 => "ADOType",
+                    _ => return SystemResult::Ok(ContractResult::Err("Invalid Code ID".to_string())),
+                };
+                SystemResult::Ok(ContractResult::Ok(to_json_binary(&ado_type).unwrap()))
+            },

This refactoring improves readability and reduces code duplication.


513-514: LGTM! Consider using a constant for consistency.

The addition of the new case for key "5" is correct and consistent with the changes in the handle_adodb_query method. To improve code consistency and maintainability, consider using a constant for the "point" ADO type.

Here's a suggested improvement:

+const POINT_ADO_TYPE: &str = "point";

 // In the handle_adodb_query method
-                5 => SystemResult::Ok(ContractResult::Ok(to_json_binary(&"point").unwrap())),
+                5 => SystemResult::Ok(ContractResult::Ok(to_json_binary(&POINT_ADO_TYPE).unwrap())),

 // In the handle_adodb_raw_query method
-                    SystemResult::Ok(ContractResult::Ok(to_json_binary("point").unwrap()))
+                    SystemResult::Ok(ContractResult::Ok(to_json_binary(POINT_ADO_TYPE).unwrap()))

This change improves consistency and makes it easier to update the ADO type name if needed in the future.

contracts/data-storage/andromeda-point/src/query.rs (2)

16-16: Reconsider the Redundant Use of is_operator

The final return statement Ok(is_operator || allowed) includes is_operator even though it's already considered in the allowed variable for the Private restriction case. This redundancy might not affect functionality but could be simplified for clarity.

If is_operator is intended to be separately checked regardless of the restriction type, consider adding a comment to clarify this intention. Otherwise, you might simplify the return statement if appropriate.


24-29: Simplify the Conversion from Addr to AndrAddr

In the get_data_owner function, you're converting owner from Addr to AndrAddr using AndrAddr::from_string(owner). Since owner is already an Addr, you can simplify this conversion by using AndrAddr::from(owner), which avoids unnecessary string allocation and improves efficiency.

Apply this diff to make the change:

- owner: AndrAddr::from_string(owner),
+ owner: AndrAddr::from(owner),

This change makes the code more concise and leverages the implemented From<Addr> trait for AndrAddr.

contracts/data-storage/andromeda-point/src/contract.rs (1)

42-42: Add a comment for clarity when saving restriction

For improved readability, consider adding a comment above RESTRICTION.save(...) to explain that the restriction setting is being saved to storage.

packages/andromeda-data-storage/src/point.rs (1)

45-47: Fix grammatical error in error messages

The error messages use "can not parse to f64", which should be "cannot parse to f64".

Apply this diff to correct the error messages:

- err: "x_coordinate: can not parse to f64".to_string(),
+ err: "x_coordinate: cannot parse to f64".to_string(),

Make similar changes for the y_coordinate and z_coordinate error messages in both the implementation and test assertions.

Also applies to: 62-64, 121-121, 134-134, 147-147

contracts/data-storage/andromeda-graph/src/contract.rs (5)

247-250: Simplify boolean match to an if statement.

Using match on a boolean value is unnecessary and can be simplified for readability. Replace the match statement with an if expression:

let timestamp = if is_timestamp_allowed {
    Some(ctx.env.block.time.nanos())
} else {
    None
};

382-382: Consistency in passing dependencies to get_raw_address.

In this line, get_raw_address is called with &deps:

let user_addr = user.get_raw_address(&deps)?;

For consistency with other parts of the code, consider using &deps.as_ref():

let user_addr = user.get_raw_address(&deps.as_ref())?;

332-332: Consistency in passing dependencies to get_raw_address.

Similar to a previous comment, ensure consistent use of &ctx.deps.as_ref() when calling get_raw_address:

let user_addr = user.get_raw_address(&ctx.deps.as_ref())?;

If &ctx.deps suffices, ensure it's used consistently throughout the code.


247-250: Improve readability by simplifying match on boolean to if-else.

The match on is_timestamp_allowed can be simplified:

let timestamp = if is_timestamp_allowed {
    Some(ctx.env.block.time.nanos())
} else {
    None
};

This reduces complexity and aligns with common Rust practices.


176-185: Clarify error message for Z-axis validation.

The error message in the ensure! macro could be confusing:

error: Some(if is_z_allowed {
    "Z-axis is allowed".to_string()
} else {
    "Z-axis is not allowed".to_string()
})

Consider rephrasing to indicate the actual issue, such as "Z-coordinate provided but Z-axis is not allowed" or "Z-coordinate is required when Z-axis is allowed."

Example:

ensure!(
    z_coordinate.is_some() == is_z_allowed,
    ContractError::InvalidParameter {
        error: Some(if is_z_allowed {
            "Z-coordinate is required when Z-axis is allowed.".to_string()
        } else {
            "Z-coordinate should not be provided when Z-axis is not allowed.".to_string()
        })
    }
);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5e0b537 and a6578ca.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (28)
  • CHANGELOG.md (1 hunks)
  • contracts/data-storage/andromeda-graph/.cargo/config (1 hunks)
  • contracts/data-storage/andromeda-graph/Cargo.toml (1 hunks)
  • contracts/data-storage/andromeda-graph/examples/schema.rs (1 hunks)
  • contracts/data-storage/andromeda-graph/src/contract.rs (1 hunks)
  • contracts/data-storage/andromeda-graph/src/lib.rs (1 hunks)
  • contracts/data-storage/andromeda-graph/src/mock.rs (1 hunks)
  • contracts/data-storage/andromeda-graph/src/state.rs (1 hunks)
  • contracts/data-storage/andromeda-graph/src/testing/mock.rs (1 hunks)
  • contracts/data-storage/andromeda-graph/src/testing/mock_querier.rs (1 hunks)
  • contracts/data-storage/andromeda-graph/src/testing/mod.rs (1 hunks)
  • contracts/data-storage/andromeda-graph/src/testing/tests.rs (1 hunks)
  • contracts/data-storage/andromeda-point/.cargo/config (1 hunks)
  • contracts/data-storage/andromeda-point/Cargo.toml (1 hunks)
  • contracts/data-storage/andromeda-point/examples/schema.rs (1 hunks)
  • contracts/data-storage/andromeda-point/src/contract.rs (1 hunks)
  • contracts/data-storage/andromeda-point/src/execute.rs (1 hunks)
  • contracts/data-storage/andromeda-point/src/lib.rs (1 hunks)
  • contracts/data-storage/andromeda-point/src/mock.rs (1 hunks)
  • contracts/data-storage/andromeda-point/src/query.rs (1 hunks)
  • contracts/data-storage/andromeda-point/src/state.rs (1 hunks)
  • contracts/data-storage/andromeda-point/src/testing/mock.rs (1 hunks)
  • contracts/data-storage/andromeda-point/src/testing/mod.rs (1 hunks)
  • contracts/data-storage/andromeda-point/src/testing/tests.rs (1 hunks)
  • packages/andromeda-data-storage/src/graph.rs (1 hunks)
  • packages/andromeda-data-storage/src/lib.rs (1 hunks)
  • packages/andromeda-data-storage/src/point.rs (1 hunks)
  • packages/std/src/testing/mock_querier.rs (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • contracts/data-storage/andromeda-point/src/testing/mod.rs
🧰 Additional context used
🔇 Additional comments (57)
contracts/data-storage/andromeda-graph/src/testing/mod.rs (1)

1-3: Excellent test structure implementation!

The addition of these three modules (mock, mock_querier, and tests) demonstrates a well-organized approach to testing the Andromeda graph data storage system. This structure facilitates:

  1. Isolation of components during testing through mock implementations.
  2. Controlled testing of query-related functionalities with a dedicated mock querier.
  3. Clear separation of actual tests from mock implementations.

This setup will contribute to more robust and maintainable tests, which is crucial for the long-term health of the project.

packages/andromeda-data-storage/src/lib.rs (1)

3-4: LGTM! New modules added as expected.

The addition of graph and point modules aligns with the PR objectives to introduce Graph ADO and Point ADO. These changes enhance the functionality of the Andromeda protocol by enabling the storage and management of spatial data.

To ensure the new modules are properly implemented, let's verify their existence and basic structure:

Don't forget to update any relevant documentation (e.g., README.md, API docs) to reflect these new modules and their functionalities.

✅ Verification successful

Verified! The graph and point modules are properly implemented and align with the PR objectives to introduce Graph ADO and Point ADO functionalities.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and basic structure of new modules

# Check if the graph.rs file exists
echo "Checking graph.rs:"
fd --type f "graph.rs" packages/andromeda-data-storage/src

# Check if the point.rs file exists
echo "Checking point.rs:"
fd --type f "point.rs" packages/andromeda-data-storage/src

# Display the contents of graph.rs
echo "Contents of graph.rs:"
cat packages/andromeda-data-storage/src/graph.rs

# Display the contents of point.rs
echo "Contents of point.rs:"
cat packages/andromeda-data-storage/src/point.rs

Length of output: 6337

contracts/data-storage/andromeda-graph/.cargo/config (1)

1-4: LGTM! These Cargo aliases will streamline development tasks.

The introduction of these Cargo aliases is a great addition to the project. They provide convenient shortcuts for common development tasks:

  1. wasm: Compiles the project for WebAssembly in release mode, which is essential for smart contract deployment.
  2. unit-test: Runs unit tests for the library, facilitating quick testing during development.
  3. schema: Generates the contract's message schema, which is a best practice in CosmWasm development.

These aliases will improve developer productivity and maintain consistency in build and test processes across the team.

contracts/data-storage/andromeda-point/.cargo/config (1)

4-4: Verify the existence of the "schema" example.

The schema alias assumes there's an example named "schema" in your project. Please ensure this example exists and is correctly implemented.

contracts/data-storage/andromeda-graph/src/lib.rs (2)

7-8: LGTM! Well-structured test module.

The conditional compilation for the testing module is correctly set up. It ensures that test code is only included when running tests, which is a standard practice in Rust. The module being private (mod instead of pub mod) correctly indicates that it's for internal testing only.

This structure promotes better organization of test code and ensures it's not included in production builds, which is excellent for maintaining a clean and efficient codebase.


1-8: Overall, excellent structure and organization.

The lib.rs file is well-structured and follows Rust best practices. It effectively sets up the main modules for the Graph ADO (contract and state) while properly handling test and mock code through conditional compilation. This aligns perfectly with the PR objectives and promotes good code organization.

The minor suggestions for documentation improvements will further enhance the code's readability and maintainability, but the current implementation is solid and ready for integration.

contracts/data-storage/andromeda-point/src/lib.rs (7)

1-1: LGTM: Public contract module declaration.

The public declaration of the contract module is appropriate. This module likely contains the main entry points for the smart contract, which need to be accessible from outside the crate.


2-2: LGTM: Private execute module declaration.

The private declaration of the execute module is appropriate. This module likely contains internal implementation details for contract execution, which should be encapsulated within the crate.


3-4: LGTM: Conditional mock module for testing.

The mock module is appropriately declared as public and conditionally compiled. This setup ensures:

  1. The module is only available for testing purposes.
  2. It's not included in the final WASM binary, optimizing contract size.
  3. It can be used in integration tests or other crates during testing.

This approach aligns with best practices for separating test code from production code in Rust smart contracts.


5-5: LGTM: Private query module declaration.

The private declaration of the query module is appropriate. This module likely contains internal implementation details for contract queries, which should be encapsulated within the crate.


6-6: LGTM: Private state module declaration.

The private declaration of the state module is appropriate. This module likely contains internal state management logic, which should be encapsulated within the crate to prevent direct manipulation of contract state from outside.


8-9: LGTM: Conditional testing module for unit tests.

The testing module is appropriately declared as private and conditionally compiled only for test builds. This setup ensures:

  1. The module is only available during testing.
  2. It's not included in the final binary, optimizing contract size.
  3. It's used only within this crate for unit tests.

This approach aligns with best practices for organizing test code in Rust projects.


1-9: Well-structured module organization for the andromeda-point project.

The overall structure of this file is well-organized and follows Rust best practices for smart contract development:

  1. Clear separation of concerns with distinct modules for contract, execute, query, and state.
  2. Appropriate use of public and private module declarations.
  3. Effective use of conditional compilation for testing-related modules (mock and testing).

This structure provides several benefits:

  • Improved code organization and readability.
  • Clear boundaries between different components of the smart contract.
  • Efficient separation of production and test code.
  • Potential for better performance and smaller contract size in production builds.

Great job on setting up a solid foundation for the andromeda-point project!

contracts/data-storage/andromeda-graph/examples/schema.rs (1)

1-2: LGTM: Imports are correct and follow best practices.

The imports are appropriate for the schema generation task. Using specific imports enhances code readability and maintainability.

contracts/data-storage/andromeda-point/examples/schema.rs (3)

1-2: LGTM: Imports are correct and follow best practices.

The imports are appropriate for generating the schema. Good job on using specific imports rather than wildcard imports, which enhances code readability and maintainability.


3-10: LGTM: Schema generation is correctly implemented.

The main function correctly uses the write_api! macro to generate the schema for the Andromeda Point ADO. It includes all necessary message types (InstantiateMsg, QueryMsg, ExecuteMsg) as required for a complete CosmWasm contract interface.


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

This file effectively sets up the schema generation for the Andromeda Point ADO. It follows CosmWasm best practices and provides a clear, concise implementation. The code is well-organized and serves its intended purpose without any unnecessary complexity.

contracts/data-storage/andromeda-point/src/state.rs (1)

1-3: LGTM: Imports are appropriate and well-structured.

The imports cover all necessary types for the state management of the Andromeda Point module. They include custom types from the project (PointCoordinate, PointRestriction), standard CosmWasm types (Addr), and storage management utilities (Item).

contracts/data-storage/andromeda-graph/src/state.rs (2)

1-4: LGTM: Imports are appropriate and well-organized.

The imports are correctly chosen for the functionality being implemented. They include necessary types from the andromeda_data_storage crate for both graph and point modules, the Addr type from cosmwasm_std for blockchain addresses, and storage primitives from cw_storage_plus.


6-9: LGTM: Well-designed constants for graph data storage.

The constants are appropriately defined using cw_storage_plus primitives:

  • MAP_INFO: Stores a single MapInfo item, suitable for map metadata.
  • TOTAL_POINTS_NUMBER: Keeps track of the total number of points as a single u128 value.
  • USER_COORDINATE: Maps Addr to PointCoordinate, efficiently storing user-specific coordinates.

These definitions align well with the PR objectives of introducing Graph ADO for storing X-Y coordinates within specified map boundaries.

contracts/data-storage/andromeda-graph/Cargo.toml (4)

1-13: LGTM! Package metadata is well-defined.

The package metadata is appropriately set up for the new andromeda-graph project. The exclusion of build artifacts from publication is a good practice.

Note: The minimum Rust version is set to 1.75.0, which is quite recent. Ensure that this aligns with your project's compatibility requirements and development environment.


15-16: LGTM! Library configuration is correct.

The library is correctly configured to build both a cdylib (for WebAssembly) and an rlib (for Rust library usage). This setup allows for maximum flexibility in how the library can be used.


25-33: LGTM! Dependencies are well-defined and use workspace-level version management.

The dependencies section includes all necessary libraries for a CosmWasm-based project in the Andromeda ecosystem. The use of workspace-level version management (workspace = true) for all dependencies is an excellent practice, ensuring consistency across the project and simplifying version updates.


35-37: LGTM! Conditional dependencies are correctly configured.

The conditional dependencies for non-wasm32 targets are well-defined. Including cw-multi-test and andromeda-testing as optional dependencies for non-WebAssembly builds is a good practice. This setup allows these testing dependencies to be included only when necessary, likely controlled by the "testing" feature defined earlier.

contracts/data-storage/andromeda-point/Cargo.toml (6)

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

The package metadata is appropriately set up for a new package. The Rust edition (2021) and version (1.75.0) are up-to-date, and the version number (1.0.0) follows semantic versioning conventions.


8-12: LGTM: Appropriate files excluded from package.

The exclude section correctly omits build artifacts ("contract.wasm" and "hash.txt") from the package. This is a good practice to keep the package size small and avoid including non-source files. The comment provides helpful context for why these files are excluded.


16-17: LGTM: Appropriate library configuration for a CosmWasm contract.

The [lib] section correctly specifies both "cdylib" and "rlib" crate types. This configuration is standard for CosmWasm contracts, allowing the crate to be compiled to WebAssembly (cdylib) and used as a dependency by other crates (rlib).


19-24: LGTM: Well-defined features with clear purposes.

The [features] section is well-structured with clear purposes for each feature:

  • "backtraces" for improved debugging
  • "library" for disabling exports when needed
  • "testing" for including test-specific dependencies

The comments provide helpful context for the "backtraces" and "library" features, enhancing maintainability.


26-39: LGTM: Dependencies are well-structured and appropriate.

The dependencies are well-organized and suitable for a CosmWasm contract:

  • Main dependencies use workspace versions, ensuring consistency across the project.
  • Includes standard CosmWasm libraries and Andromeda-specific crates.
  • Target-specific dependencies for non-wasm32 architectures are correctly configured for testing purposes.

The use of workspace versions and the separation of test dependencies demonstrate good practices in dependency management.


1-39: Excellent Cargo.toml configuration for the andromeda-point package.

This Cargo.toml file is well-structured and follows best practices for CosmWasm contract development. It includes:

  • Appropriate package metadata
  • Correct exclusion of build artifacts
  • Standard library configuration for WebAssembly compilation
  • Well-defined features for various use cases
  • Properly organized dependencies using workspace versions

The file demonstrates good organization and attention to detail, which will contribute to the maintainability and usability of the andromeda-point package.

contracts/data-storage/andromeda-point/src/testing/mock.rs (2)

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

The imports cover all necessary modules for mock testing, and the MockDeps type alias is correctly defined.


64-68: LGTM: delete_point function is correctly implemented.

The function properly creates and executes the DeletePoint message, following the same pattern as the other execution functions in this file.

CHANGELOG.md (2)

Line range hint 1-85: Excellent changelog structure and content.

The changelog is well-organized, comprehensive, and follows best practices:

  • Clear sections for Added, Changed, Fixed, and Removed items
  • Consistent formatting with pull request links
  • Covers a wide range of changes, aligning with the PR objectives and AI-generated summary

This structure effectively communicates the project's evolution and will be valuable for users and developers.


Line range hint 1-85: Verify the status of the Point ADO mentioned in the PR objectives.

The PR objectives mentioned introducing both Graph ADO and Point ADO, but the changelog only includes the Graph ADO. Could you please clarify:

  1. Is the Point ADO part of this PR?
  2. If yes, should it be added to the changelog?
  3. If no, is it planned for a future PR?

This verification will ensure that the changelog accurately reflects all significant changes in this PR.

packages/std/src/testing/mock_querier.rs (1)

Line range hint 1-554: Overall, the changes look good and align with the PR objectives.

The additions to both handle_adodb_query and handle_adodb_raw_query methods successfully implement support for the new Point ADO. The changes are consistent with the existing patterns in the file and enhance the mock querier's capabilities for testing purposes.

Consider implementing the suggested refactoring and consistency improvements to further enhance the code quality. These changes will make the code more readable, maintainable, and consistent across the file.

contracts/data-storage/andromeda-point/src/query.rs (2)

1-4: Imports are Appropriate and Necessary

The imported modules and crates are appropriate for the functionality provided in this file and are necessary for the code to compile and run correctly.


19-22: get_point Function is Correct and Effective

The get_point function correctly retrieves the PointCoordinate from storage and properly handles any errors that may occur during the loading process.

packages/andromeda-data-storage/src/graph.rs (1)

61-61: Verify if users can have multiple coordinates

The GetUserCoordinate query returns a single CoordinateInfo, suggesting each user can have only one coordinate. If users are allowed to have multiple coordinates, consider returning a list of coordinates. This ensures the query response accurately reflects the data model.

Run the following script to check for multiple coordinate storage:

✅ Verification successful

Verification Successful: Users Cannot Have Multiple Coordinates

After reviewing the storage methods, it is confirmed that users can only have one coordinate.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify if users can store multiple coordinates

# Test: Search for usage of user coordinate storage methods
# Expect: Identify methods that store multiple coordinates per user
rg --type rust -A 5 $'StoreUserCoordinate' | rg 'Vec<Coordinate>' || echo "No multiple coordinates found"

Length of output: 133

contracts/data-storage/andromeda-point/src/contract.rs (5)

22-44: instantiate function is correctly implemented

The instantiate function properly initializes the contract using ADOContract and saves the restriction to storage. Parameters are correctly handled, and error propagation is appropriate.


46-60: execute function handles message routing appropriately

The execute function correctly creates an ExecuteContext and routes messages. It delegates ExecuteMsg::AMPReceive to ADOContract::execute_amp_receive and handles other messages with handle_execute.


62-69: query function correctly routes queries

The query function properly handles GetPoint and GetDataOwner queries and delegates other queries to ADOContract::query.


71-74: migrate function implementation is appropriate

The migrate function correctly delegates to ADOContract::migrate, ensuring proper contract migration with the updated name and version.


55-59: Verify all ExecuteMsg variants are handled

Please ensure that all variants of ExecuteMsg are properly handled in your execution logic. Missing handlers for certain variants could lead to unhandled messages and potential errors.

You can run the following script to verify that all ExecuteMsg variants are accounted for:

contracts/data-storage/andromeda-point/src/mock.rs (1)

1-111: Well-structured mock implementation for testing

The MockPoint struct and its associated methods provide a comprehensive mock setup for testing the Andromeda Point contract. The use of helper functions and the mock_ado! macro enhances modularity and code clarity.

packages/andromeda-data-storage/src/point.rs (1)

87-151: Good test coverage for validate method

The unit tests thoroughly cover both valid and invalid cases for the validate method, ensuring its correctness.

contracts/data-storage/andromeda-point/src/execute.rs (1)

128-150: Verify the correctness of tax amount calculation and refund logic

Ensure that the calculation of tax_amount, refund, and after_tax_payment correctly handles all possible scenarios, including when the sent funds are less than the tax amount. Incorrect handling might result in arithmetic errors or unintended behavior.

Run the following script to check for potential arithmetic errors:

Review any warnings related to integer arithmetic to ensure safe operations.

✅ Verification successful

Tax amount calculation and refund logic are correctly handled, with no unchecked arithmetic operations found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for unchecked arithmetic operations that might panic.

# Test: Use cargo clippy to identify potential issues. Expect: No warnings about unchecked arithmetic.
cargo clippy -- -A clippy::integer_arithmetic

Length of output: 120


Script:

#!/bin/bash
# Description: Search for unchecked arithmetic operations that might panic in execute.rs

# Using ast-grep to find arithmetic operations not using checked methods
ast-grep --lang rust --pattern '$_ * $_' --file contracts/data-storage/andromeda-point/src/execute.rs
ast-grep --lang rust --pattern '$_ + $_' --file contracts/data-storage/andromeda-point/src/execute.rs
ast-grep --lang rust --pattern '$_ - $_' --file contracts/data-storage/andromeda-point/src/execute.rs
ast-grep --lang rust --pattern '$_ / $_' --file contracts/data-storage/andromeda-point/src/execute.rs

Length of output: 1191


Script:

#!/bin/bash
# Description: Search for unchecked arithmetic operations that might panic in execute.rs

# Using ast-grep to find arithmetic operations not using checked methods
ast-grep --lang rust --pattern '$_ * $_' contracts/data-storage/andromeda-point/src/execute.rs
ast-grep --lang rust --pattern '$_ + $_' contracts/data-storage/andromeda-point/src/execute.rs
ast-grep --lang rust --pattern '$_ - $_' contracts/data-storage/andromeda-point/src/execute.rs
ast-grep --lang rust --pattern '$_ / $_' contracts/data-storage/andromeda-point/src/execute.rs

Length of output: 387

contracts/data-storage/andromeda-point/src/testing/tests.rs (10)

1-18: Approved: Import statements are correct

The import statements correctly include all necessary modules and dependencies.


20-23: Approved: test_instantiation function is properly implemented

The test for contract instantiation verifies that the contract initializes correctly with a specified point restriction.


25-43: Approved: test_set_and_update_point function correctly tests point setting and updating

The test function properly sets an initial point, verifies it, updates it, and verifies the update.


45-139: Approved: test_set_point_with_tax function accurately tests tax handling

The test cases cover scenarios with exact payment, insufficient funds, and overpayment, ensuring proper handling of taxes and refunds.


141-145: Approved: TestHandlePointCoordinate struct is appropriately defined

The struct correctly represents test cases for invalid point coordinates.


147-195: Approved: test_set_point_invalid function effectively tests invalid coordinates

The test function validates that invalid point coordinates result in the expected parsing errors.


197-204: Approved: test_delete_point function correctly tests point deletion

The test ensures that points can be deleted and that querying a deleted point results in an error.


206-229: Approved: test_restriction_private function properly tests private restriction behavior

The test verifies that only the owner can set or delete points when the restriction is private.


231-256: Approved: test_restriction_public function correctly tests public restriction behavior

The test confirms that any user can set or delete points when the restriction is public.


303-327: Approved: test_query_data_owner function accurately tests data owner querying

The test verifies that the contract correctly identifies the data owner and handles unauthorized deletion attempts.

contracts/data-storage/andromeda-graph/src/testing/tests.rs (1)

354-375: Verify that updating the map clears stored points

When update_map is called, all previously stored coordinates are cleared, and max_point_number is reset to zero. Verify that this is the intended behavior, as it may result in data loss if not handled properly.

Run the following script to check if update_map implementation intentionally clears stored points:

This script searches for calls to POINTS.clear or resetting MAX_POINT_NUMBER within the update_map function.


let is_z_allowed = z_length.is_some();

let x_coordinate = ((coordinate.x_coordinate * 10_f64.powf(map_decimal as f64)) as i64) as f64
Copy link
Contributor

Choose a reason for hiding this comment

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

Any risk of underflow causing a panic here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Resolved like this:

let scale = 10_f64.powf(map_decimal as f64);
    let x_coordinate = (coordinate.x_coordinate * scale)
        .min(i64::MAX as f64) // Ensuring it doesn't exceed i64 bounds
        .max(i64::MIN as f64); // Ensuring it doesn't underflow
    let x_coordinate = (x_coordinate as i64) as f64 / scale;

    let y_coordinate = (coordinate.y_coordinate * scale)
        .min(i64::MAX as f64) // Ensuring it doesn't exceed i64 bounds
        .max(i64::MIN as f64); // Ensuring it doesn't underflow
    let y_coordinate = (y_coordinate as i64) as f64 / scale;

    let z_coordinate = coordinate.z_coordinate.map(|z| {
        let z_scaled = (z * scale)
            .min(i64::MAX as f64) // Clamp the value to prevent overflow
            .max(i64::MIN as f64); // Clamp the value to prevent underflow
        (z_scaled as i64) as f64 / scale
    });

pub fn execute_update_map(
ctx: ExecuteContext,
map_info: MapInfo,
action: String,
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm not sure this parameter is necessary. The action is static so can be hardcoded in the attributes.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Removed this parameter.

ctx: ExecuteContext,
coordinate: Coordinate,
is_timestamp_allowed: bool,
action: String,
Copy link
Contributor

Choose a reason for hiding this comment

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

Same as above.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Removed this parameter.

pub fn execute_store_user_coordinate(
ctx: ExecuteContext,
user_location_paths: Vec<AndrAddr>,
action: String,
Copy link
Contributor

Choose a reason for hiding this comment

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

Same as above.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Removed this parameter.

pub fn execute_delete_user_coordinate(
ctx: ExecuteContext,
user: AndrAddr,
action: String,
Copy link
Contributor

Choose a reason for hiding this comment

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

Same as above.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Removed this parameter.

let mut res: Vec<(CoordinateInfo, StoredDate)> = Vec::new();

for point in 1..=max_point_number {
let coordinate = MAP_POINT_INFO.load(storage, &point)?;
Copy link
Contributor

Choose a reason for hiding this comment

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

This can error if a point is removed. Maybe use may_load and only append Option values that have a Some value.

Copy link
Contributor

Choose a reason for hiding this comment

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

This is also unpaginated so has a potential DOS vector if too many points are added.

Copy link
Contributor

Choose a reason for hiding this comment

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

Using a paginated range value may actually be a better approach.

Copy link
Contributor Author

@mdjakovic0920 mdjakovic0920 Oct 14, 2024

Choose a reason for hiding this comment

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

Resolved like this:

pub fn get_all_points(
    storage: &dyn Storage,
    start: Option<u128>,
    limit: Option<u32>,
) -> Result<GetAllPointsResponse, ContractError> {
    let max_point_number = TOTAL_POINTS_NUMBER.load(storage)?;

    // Set default values for pagination
    let start_point = start.unwrap_or(1); // Start from 1 if no start provided
    let limit = limit.unwrap_or(100); // Default limit to 100 points

    let mut res: Vec<(CoordinateInfo, StoredDate)> = Vec::new();

    // Iterate with pagination
    for point in start_point..=max_point_number {
        if res.len() >= limit as usize {
            break; // Stop when limit is reached
        }

        // Use `may_load` to handle cases where the point may not exist
        if let Some(coordinate) = MAP_POINT_INFO.may_load(storage, &point)? {
            res.push(coordinate);
        }
    }

    Ok(GetAllPointsResponse { points: res })
}

Comment on lines +81 to +84
match res {
Ok(res) => Ok(from_json(res)?),
Err(err) => Err(err),
}
Copy link
Contributor

Choose a reason for hiding this comment

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

This is a nit but I think is a nice change

Comment on lines +25 to +30
#[cw_serde]
pub struct PointCoordinate {
pub x_coordinate: String,
pub y_coordinate: String,
pub z_coordinate: Option<String>,
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Is there a reason we don't use f64 here?

@crnbarr93 crnbarr93 mentioned this pull request Oct 11, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (1)
packages/andromeda-data-storage/src/graph.rs (1)

11-23: LGTM: MapInfo and MapSize structures are well-defined

The MapInfo and MapSize structures provide necessary information for map configuration. The use of Option<u64> for z_width allows for both 2D and 3D maps, which is a good design choice.

Consider adding documentation comments to explain the purpose of each field, especially allow_negative and map_decimal, to improve code readability and maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a6578ca and 414ec59.

📒 Files selected for processing (5)
  • CHANGELOG.md (1 hunks)
  • contracts/data-storage/andromeda-graph/src/contract.rs (1 hunks)
  • contracts/data-storage/andromeda-graph/src/testing/mock.rs (1 hunks)
  • contracts/data-storage/andromeda-graph/src/testing/tests.rs (1 hunks)
  • packages/andromeda-data-storage/src/graph.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • CHANGELOG.md
  • contracts/data-storage/andromeda-graph/src/contract.rs
  • contracts/data-storage/andromeda-graph/src/testing/tests.rs
🧰 Additional context used
🔇 Additional comments (7)
packages/andromeda-data-storage/src/graph.rs (3)

1-9: LGTM: Imports and InstantiateMsg structure look good

The imports are appropriate for the functionality being implemented, and the InstantiateMsg structure is well-defined, following the expected pattern for CosmWasm contract instantiation.


50-80: LGTM: QueryMsg and response structures are well-defined

The QueryMsg enum and associated response structures (GetMapInfoResponse, GetMaxPointNumberResponse, and GetAllPointsResponse) are well-defined and cover the necessary query operations for the Graph ADO. The use of #[returns(...)] attributes is correct and helpful for schema generation.


1-92: Overall assessment: Well-structured Graph ADO with room for improvements

The Graph ADO implementation in this file is well-structured and covers essential functionalities for managing map-related data. The use of appropriate CosmWasm and Andromeda standard libraries demonstrates good adherence to best practices.

Key points from the review:

  1. Imports and basic structures are well-defined.
  2. Suggested improvements for naming consistency in Coordinate and ExecuteMsg.
  3. Recommendation to align data types between Coordinate and CoordinateInfo.
  4. Suggestion to use Timestamp type for better time representation.
  5. Consider adding documentation comments to improve code readability.

Implementing these suggestions will enhance the consistency, usability, and maintainability of the Graph ADO. Great work overall!

contracts/data-storage/andromeda-graph/src/testing/mock.rs (4)

10-10: ⚠️ Potential issue

Replace from_json with from_binary in imports

The from_json function is not provided by cosmwasm_std; instead, you should use from_binary to deserialize Binary responses from queries.

Apply this diff to correct the import:

 use cosmwasm_std::{
-    from_json,
+    from_binary,
     testing::{mock_env, mock_info, MockApi, MockStorage},
     Deps, DepsMut, MessageInfo, OwnedDeps, Response,
 };
⛔ Skipped due to learnings
Learnt from: crnbarr93
PR: andromedaprotocol/andromeda-core#576
File: contracts/data-storage/andromeda-graph/src/testing/mock_querier.rs:93-110
Timestamp: 2024-10-11T10:52:10.088Z
Learning: In the Rust file `contracts/data-storage/andromeda-graph/src/testing/mock_querier.rs`, panics caused by `unwrap()` are acceptable because the code is only used for testing.

107-113: ⚠️ Potential issue

Use from_binary instead of from_json in query_user_coordinate

In the query_user_coordinate function, replace from_json with from_binary to correctly deserialize the query response.

Apply this diff to correct the function:

 pub fn query_user_coordinate(deps: Deps, user: AndrAddr) -> Result<CoordinateInfo, ContractError> {
     let res = query(deps, mock_env(), QueryMsg::GetUserCoordinate { user });
     match res {
-        Ok(res) => Ok(from_json(res)?),
+        Ok(res) => Ok(from_binary(&res)?),
         Err(err) => Err(err),
     }
 }

Likely invalid or redundant comment.


87-93: ⚠️ Potential issue

Use from_binary instead of from_json in query_max_point_number

In the query_max_point_number function, replace from_json with from_binary to correctly deserialize the query response.

Apply this diff to correct the function:

 pub fn query_max_point_number(deps: Deps) -> Result<GetMaxPointNumberResponse, ContractError> {
     let res = query(deps, mock_env(), QueryMsg::GetMaxPointNumber {});
     match res {
-        Ok(res) => Ok(from_json(res)?),
+        Ok(res) => Ok(from_binary(&res)?),
         Err(err) => Err(err),
     }
 }

Likely invalid or redundant comment.


79-85: ⚠️ Potential issue

Use from_binary instead of from_json in query_map_info

In the query_map_info function, replace from_json with from_binary to correctly deserialize the query response.

Apply this diff to fix the deserialization:

 pub fn query_map_info(deps: Deps) -> Result<GetMapInfoResponse, ContractError> {
     let res = query(deps, mock_env(), QueryMsg::GetMapInfo {});
     match res {
-        Ok(res) => Ok(from_json(res)?),
+        Ok(res) => Ok(from_binary(&res)?),
         Err(err) => Err(err),
     }
 }

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