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

Matrix ADO #539

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

Matrix ADO #539

wants to merge 5 commits into from

Conversation

mdjakovic0920
Copy link
Contributor

@mdjakovic0920 mdjakovic0920 commented Aug 19, 2024

Motivation

Currently, the primitive ADO can store the only single data of Uint128, Decimal, Coin, Addr, String, Bool, Binary.
This ADO allows to store the matrix as a data-storage. The matrix is implemented to allow add, subtract and multiply methods.

Implementation

  • Instantiation
#[andr_instantiate]
#[cw_serde]
pub struct InstantiateMsg {
    pub restriction: MatrixRestriction,
}
  • Execution
#[andr_exec]
#[cw_serde]
pub enum ExecuteMsg {
    StoreMatrix { key: Option<String>, data: Matrix },
    DeleteMatrix { key: Option<String> },
    UpdateRestriction { restriction: MatrixRestriction },
}
  • Query
#[andr_query]
#[cw_serde]
#[derive(QueryResponses)]
pub enum QueryMsg {
    #[returns(GetMatrixResponse)]
    GetMatrix { key: Option<String> },
    #[returns(Vec<String>)]
    AllKeys {},
    #[returns(Vec<String>)]
    OwnerKeys { owner: AndrAddr },
}

  • Matrix Implementation
#[cw_serde]
pub struct Matrix(pub Vec<Vec<i64>>);

impl Matrix {
    pub fn validate_matrix(&self) -> Result<(), ContractError> {
        let row_length = self.0.first().map_or(0, |row| row.len());
        if !self.0.iter().all(|row| row.len() == row_length) {
            return Err(ContractError::CustomError {
                msg: "All rows in the matrix must have the same number of columns".to_string(),
            });
        }
        Ok(())
    }

    pub fn validate_add_sub(&self, other: &Matrix) -> Result<(), ContractError> {
        if self.0.len() != other.0.len() || self.0[0].len() != other.0[0].len() {
            return Err(ContractError::CustomError {
                msg: "Can not add or sub this matrix".to_string(),
            });
        }
        Ok(())
    }

    pub fn validate_mul(&self, other: &Matrix) -> Result<(), ContractError> {
        if self.0[0].len() != other.0.len() {
            return Err(ContractError::CustomError {
                msg: "Can not multiply this matrix".to_string(),
            });
        }
        Ok(())
    }

    pub fn add(&self, other: &Matrix) -> Result<Matrix, ContractError> {
        self.validate_add_sub(other)?;

        let matrix_data = self
            .0
            .iter()
            .zip(&other.0)
            .map(|(row_a, row_b)| {
                row_a
                    .iter()
                    .zip(row_b)
                    .map(|(a, b)| a.checked_add(*b).unwrap())
                    .collect()
            })
            .collect();

        Ok(Matrix(matrix_data))
    }

    pub fn sub(&self, other: &Matrix) -> Result<Matrix, ContractError> {
        self.validate_add_sub(other)?;

        let matrix_data = self
            .0
            .iter()
            .zip(&other.0)
            .map(|(row_a, row_b)| {
                row_a
                    .iter()
                    .zip(row_b)
                    .map(|(a, b)| a.checked_sub(*b).unwrap())
                    .collect()
            })
            .collect();

        Ok(Matrix(matrix_data))
    }

    #[allow(clippy::needless_range_loop)]
    pub fn mul(&self, other: &Matrix) -> Result<Matrix, ContractError> {
        self.validate_mul(other)?;

        let rows = self.0.len();
        let cols = other.0[0].len();
        let mut data = vec![vec![0_i64; cols]; rows];

        for i in 0..rows {
            for j in 0..cols {
                for k in 0..self.0[0].len() {
                    data[i][j] += self.0[i][k].checked_mul(other.0[k][j]).unwrap();
                }
            }
        }

        Ok(Matrix(data))
    }
}

Testing

Unite test cases are added to this version.

Version Changes

Version is set as 1.0.0

Summary by CodeRabbit

  • New Features

    • Introduced command aliases for simplified development tasks in the Andromeda matrix project.
    • Added functionality for smart contract management of a data storage matrix, including instantiation, execution, querying, and migration features.
    • Implemented a robust matrix operations module with methods for validation and mathematical operations.
    • Added a new entry for "Matrix ADO" in the CHANGELOG to document this feature.
  • Bug Fixes

    • Enhanced tax handling logic in matrix storage to ensure compliance with financial regulations.
  • Tests

    • Established a comprehensive suite of unit tests covering matrix lifecycle operations including initialization, storage, access control, and querying.
  • Documentation

    • Expanded the public API documentation to include the new matrix module and its functionalities.

Copy link
Contributor

coderabbitai bot commented Aug 19, 2024

Walkthrough

The recent changes to the andromeda-matrix project introduce a new module for matrix operations, enhance testing capabilities, and streamline development processes. A new .cargo/config file simplifies command usage, while Cargo.toml organizes project metadata and dependencies. Multiple modules and mock implementations support matrix functionalities and testing, ensuring robust error handling and validation. Comprehensive unit tests fortify the contract's logic, improving the overall development experience within the Andromeda ecosystem.

Changes

Files Change Summary
contracts/data-storage/andromeda-matrix/.cargo/config Added command aliases for building with WebAssembly, running unit tests, and executing schema generation examples, improving development efficiency.
contracts/data-storage/andromeda-matrix/Cargo.toml Defined project metadata, dependencies, and features, facilitating effective dependency management and preventing certain artifacts from publication.
contracts/data-storage/andromeda-matrix/examples/schema.rs, contracts/data-storage/andromeda-matrix/src/contract.rs Introduced a schema.rs for API schema generation and a contract.rs for managing data storage matrix operations, including instantiation and querying functionalities.
contracts/data-storage/andromeda-matrix/src/lib.rs, contracts/data-storage/andromeda-matrix/src/state.rs Organized core functionalities and state management into modules, enhancing modularity and clarity in the project structure.
contracts/data-storage/andromeda-matrix/src/mock.rs, contracts/data-storage/andromeda-matrix/src/testing/mock.rs Provided mock implementations for testing contract functionalities in a non-WASM environment, facilitating simulation of contract interactions.
contracts/data-storage/andromeda-matrix/src/testing/mod.rs, contracts/data-storage/andromeda-matrix/src/testing/tests.rs Established a modular structure for the testing suite, including comprehensive unit tests for matrix storage functionalities, ensuring robust validation of core logic.
packages/andromeda-data-storage/src/lib.rs, packages/andromeda-data-storage/src/matrix.rs Introduced a new public matrix module with structures and error handling for matrix operations, including validation methods for arithmetic.

Sequence Diagram(s)

sequenceDiagram
    participant Developer
    participant CLI
    participant WebAssembly
    participant Contract
    participant State
    participant Mock

    Developer->>CLI: Run command (e.g., build)
    CLI->>WebAssembly: Compile project
    WebAssembly-->>CLI: Return compiled code
    CLI->>Contract: Execute matrix operation
    Contract->>State: Query/modify data
    State-->>Contract: Return data
    Contract-->>CLI: Return response
    CLI-->>Developer: Show results
Loading

🐰 In fields of code so bright and new,
Changes leap like rabbits, it's true!
With tests and mocks to play around,
In Andromeda's realm, joy is found.
Let's hop with glee, our work's begun,
A matrix of dreams, oh what fun! 🌟

Tip

We have updated our review workflow to use the Anthropic's Claude family of models. Please share any feedback in the discussion post on our Discord.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7e301a3 and 904308a.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (12)
  • contracts/data-storage/andromeda-matrix/.cargo/config (1 hunks)
  • contracts/data-storage/andromeda-matrix/Cargo.toml (1 hunks)
  • contracts/data-storage/andromeda-matrix/examples/schema.rs (1 hunks)
  • contracts/data-storage/andromeda-matrix/src/contract.rs (1 hunks)
  • contracts/data-storage/andromeda-matrix/src/lib.rs (1 hunks)
  • contracts/data-storage/andromeda-matrix/src/mock.rs (1 hunks)
  • contracts/data-storage/andromeda-matrix/src/state.rs (1 hunks)
  • contracts/data-storage/andromeda-matrix/src/testing/mock.rs (1 hunks)
  • contracts/data-storage/andromeda-matrix/src/testing/mod.rs (1 hunks)
  • contracts/data-storage/andromeda-matrix/src/testing/tests.rs (1 hunks)
  • packages/andromeda-data-storage/src/lib.rs (1 hunks)
  • packages/andromeda-data-storage/src/matrix.rs (1 hunks)
Files skipped from review due to trivial changes (3)
  • contracts/data-storage/andromeda-matrix/.cargo/config
  • contracts/data-storage/andromeda-matrix/Cargo.toml
  • contracts/data-storage/andromeda-matrix/src/testing/mod.rs
Additional comments not posted (58)
packages/andromeda-data-storage/src/lib.rs (1)

1-1: Approved: Addition of matrix module.

The addition of the matrix module expands the public API of the library, aligning with the PR objectives to introduce matrix operations.

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

1-8: Approved: Module organization.

The module structure is well-organized, separating concerns for contract logic, state management, mocking, and testing, which enhances maintainability and readability.

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

1-10: Approved: Use of cosmwasm_schema for API schema generation.

The use of cosmwasm_schema to generate API schema for instantiate, query, and execute messages ensures consistency and correctness in message formats.

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

1-9: Approved: Storage setup for matrices and restrictions.

The storage setup using cw_storage_plus is appropriate for managing matrices, key ownership, and restrictions, aligning with the PR objectives.

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

1-76: Approved: Mock implementations for testing.

The mock implementations facilitate testing by simulating contract execution and queries, which is crucial for ensuring the reliability and correctness of matrix operations.

contracts/data-storage/andromeda-matrix/src/mock.rs (16)

19-20: LGTM!

The MockMatrix struct and its use of the mock_ado! macro are well-implemented for testing purposes.


22-43: LGTM!

The instantiate method correctly handles the instantiation of the MockMatrix contract.


45-59: LGTM!

The execute_store_matrix method is well-implemented, handling both the presence and absence of funds appropriately.


61-69: LGTM!

The execute_add_rate method is correctly implemented for adding a rate to the contract.


71-78: LGTM!

The execute_update_restriction method is correctly implemented for updating matrix restrictions.


80-87: LGTM!

The execute_delete_matrix method is correctly implemented for deleting a matrix.


89-93: LGTM!

The query_matrix method is correctly implemented for querying a matrix by key.


95-99: LGTM!

The query_all_keys method is correctly implemented for retrieving all keys.


101-105: LGTM!

The query_owner_keys method is correctly implemented for retrieving keys owned by a specific address.


108-111: LGTM!

The mock_andromeda_matrix function is correctly implemented for creating a contract wrapper for testing.


113-123: LGTM!

The mock_matrix_instantiate_msg function is correctly implemented for constructing an instantiation message.


125-127: LGTM!

The mock_store_matrix_msg function is correctly implemented for constructing a store matrix execution message.


129-131: LGTM!

The mock_update_restriction_msg function is correctly implemented for constructing an update restriction execution message.


133-135: LGTM!

The mock_delete_matrix_msg function is correctly implemented for constructing a delete matrix execution message.


137-139: LGTM!

The mock_set_rate_msg function is correctly implemented for constructing a set rate execution message.


141-143: LGTM!

The mock_matrix_get_matrix function is correctly implemented for constructing a get matrix query message.

packages/andromeda-data-storage/src/matrix.rs (13)

6-8: LGTM!

The InstantiateMsg struct is correctly defined for initializing matrix restrictions.


11-15: LGTM!

The MatrixRestriction enum is well-defined for controlling matrix access.


19-23: LGTM!

The ExecuteMsg enum is correctly defined for matrix execution operations.


28-35: LGTM!

The QueryMsg enum is correctly defined for matrix query operations.


38-41: LGTM!

The GetMatrixResponse struct is correctly defined for returning matrix query results.


44-44: LGTM!

The Matrix struct is correctly defined for representing a matrix.


46-55: LGTM!

The validate_matrix method is correctly implemented to ensure consistent row lengths.


57-64: LGTM!

The validate_add_sub method is correctly implemented to check matrix compatibility for addition and subtraction.


66-73: LGTM!

The validate_mul method is correctly implemented to check matrix compatibility for multiplication.


75-92: LGTM!

The add method is correctly implemented for performing matrix addition with validation and safe addition using checked_add.


94-111: LGTM!

The sub method is correctly implemented for performing matrix subtraction with validation and safe subtraction using checked_sub.


113-130: LGTM!

The mul method is correctly implemented for performing matrix multiplication with validation and safe multiplication using checked_mul.


133-229: LGTM!

The tests module is comprehensive and effectively covers various scenarios for matrix validation and operations.

contracts/data-storage/andromeda-matrix/src/contract.rs (13)

31-53: LGTM!

The instantiate function is correctly implemented for initializing the contract with matrix restrictions.


55-69: LGTM!

The execute function is correctly implemented for handling execution messages and supporting AMP messages.


71-79: LGTM!

The query function is correctly implemented for handling query messages and supporting ADO queries.


81-84: LGTM!

The migrate function is correctly implemented for handling contract migration.


86-112: LGTM!

The handle_execute function is correctly implemented for processing execution messages and delegating to specific handlers.


116-130: LGTM!

The update_restriction function is correctly implemented for updating matrix access restrictions with proper authorization checks.


132-176: LGTM!

The store_matrix function is correctly implemented for storing a matrix with validation, tax handling, and storage updates.


179-194: LGTM!

The delete_matrix function is correctly implemented for removing a matrix with proper authorization checks.


197-207: LGTM!

The get_matrix function is correctly implemented for retrieving a matrix by key.


209-215: LGTM!

The all_keys function is correctly implemented for retrieving all matrix keys.


217-225: LGTM!

The owner_keys function is correctly implemented for retrieving matrix keys owned by a specific address.


235-250: LGTM!

The has_key_permission function is correctly implemented for checking key permissions based on matrix restrictions.


252-290: LGTM!

The tax_store_matrix function is correctly implemented for handling tax calculations and refunds when storing a matrix.

contracts/data-storage/andromeda-matrix/src/testing/tests.rs (11)

20-23: LGTM!

The test_instantiation function is correctly implemented to verify the contract's initialization process.


25-60: LGTM!

The test_store_and_update_matrix_with_key function is correctly implemented to verify storing and updating a matrix with a key.


62-193: LGTM!

The test_store_matrix_with_tax function is correctly implemented to verify tax handling during matrix storage.


197-225: LGTM!

The test_store_and_update_matrix_without_key function is correctly implemented to verify operations without specifying a key.


227-240: LGTM!

The test_store_matrix_invalid function is correctly implemented to verify error handling for invalid matrices.


242-256: LGTM!

The test_delete_matrix function is correctly implemented to verify matrix deletion with and without keys.


258-283: LGTM!

The test_restriction_private function is correctly implemented to verify operations under private restrictions.


285-311: LGTM!

The test_restriction_public function is correctly implemented to verify operations under public restrictions.


313-364: LGTM!

The test_restriction_restricted function is correctly implemented to verify operations under restricted access.


366-380: LGTM!

The test_query_all_key function is correctly implemented to verify the retrieval of all matrix keys.


382-438: LGTM!

The test_query_owner_keys function is correctly implemented to verify the retrieval of keys owned by specific addresses.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 904308a and 925cf69.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (2)
  • CHANGELOG.md (1 hunks)
  • packages/andromeda-data-storage/src/lib.rs (1 hunks)
Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
Additional comments not posted (1)
packages/andromeda-data-storage/src/lib.rs (1)

3-3: LGTM!

The new module declaration for matrix is correctly placed and declared as public, which is consistent with the other module declarations. The addition of this module is a positive change that enhances the library's capabilities by providing a dedicated module for matrix operations or related functionalities.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant