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

feat: TimeGate ADO #529

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

Conversation

mdjakovic0920
Copy link
Contributor

@mdjakovic0920 mdjakovic0920 commented Jul 26, 2024

Motivation

A request comes in, the ADO checks if the current time/date and if it’s before a specific time it returns the path ADO1, if it’s after that time, then ADO2.

Implementation

#[andr_instantiate]
#[cw_serde]
pub struct InstantiateMsg {
    pub gate_addresses: Vec<AndrAddr>,
    pub cycle_start_time: Option<Expiry>,
    pub time_interval: Option<u64>,
}

#[andr_exec]
#[cw_serde]
pub enum ExecuteMsg {
    UpdateCycleStartTime { cycle_start_time: Option<Expiry> },
    UpdateGateAddresses { new_gate_addresses: Vec<AndrAddr> },
    UpdateTimeInterval { time_interval: u64 },
}

#[andr_query]
#[cw_serde]
#[derive(QueryResponses)]
pub enum QueryMsg {
    #[returns(Addr)]
    GetCurrentAdoPath {},
    #[returns((Expiration, Milliseconds))]
    GetCycleStartTime {},
    #[returns(Vec<AndrAddr>)]
    GetGateAddresses {},
    #[returns(String)]
    GetTimeInterval {},
}

Testing

Unit test cases are added to codebase.

Version Changes

The version is set as 1.0.0

Summary by CodeRabbit

  • New Features

    • Introduced the Andromeda Time Gate module with capabilities for managing gate addresses and time.
    • Added functionalities for instantiation, execution, and querying related to gate management.
  • Testing Enhancements

    • Added comprehensive unit tests to validate the core functionalities of the Time Gate module.
    • Introduced mock testing utilities for simulated interactions with the contract.
  • Module Structure

    • Organized the code into distinct modules, enhancing maintainability and clarity, including new time management functionalities.
  • Data Integrity

    • Implemented validation logic for time data, ensuring accuracy and preventing invalid input.

Copy link
Contributor

coderabbitai bot commented Jul 26, 2024

Walkthrough

The Andromeda Time Gate module has been enhanced with a new smart contract for managing time gate functionalities, a structured API for instantiation and querying, and improved testing utilities. These updates facilitate efficient interactions within the Andromeda ecosystem and provide a robust framework for time-based operations.

Changes

Files Change Summary
contracts/modules/andromeda-time-gate/... Implemented a smart contract with instantiation, execution, and querying functions; added mock testing capabilities and structured state management.
packages/andromeda-modules/... Introduced a new time_gate module with essential structures and enumerations for managing gate functionalities.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Contract
    
    User->>Contract: Instantiate contract with gate settings
    Contract-->>User: Confirmation of instantiation
    User->>Contract: Set new gate time
    Contract-->>User: Confirmation of gate time update
    User->>Contract: Query current gate addresses
    Contract-->>User: Return current gate addresses
Loading

🐰 In the meadow, under the sun,
A time gate opens, oh what fun!
With new commands, we hop and play,
Making magic in a joyful way!
So let's celebrate, with hearts so light,
The Andromeda changes, a splendid sight! 🌼


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.
Early access features: disabled

We are currently testing the following features in early access:

  • Anthropic claude-3-5-sonnet for code reviews: Anthropic claims that the new Claude model has stronger code understanding and code generation capabilities than their previous models. Note: Our default code review model was also updated late last week. Please compare the quality of the reviews between the two models by toggling the early access feature.

Note:

  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.
  • Please join our Discord Community to provide feedback and report issues on the discussion post.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8a59083 and c6d5281.

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

4-4: Module declaration looks good.

The new module time_gate is correctly declared and aligns with the existing structure.

contracts/modules/andromeda-time-gate/src/lib.rs (4)

1-1: Module declaration looks good.

The module contract is correctly declared and aligns with the overall structure.


2-2: Module declaration looks good.

The module state is correctly declared and aligns with the overall structure.


3-4: Module declaration looks good.

The module testing is correctly declared and conditionally compiled for tests.


6-7: Module declaration looks good.

The module mock is correctly declared and conditionally compiled for non-WASM32 architectures with the testing feature.

contracts/modules/andromeda-time-gate/src/state.rs (3)

1-2: Imports look good.

The imports are correct and necessary for the functionality.


4-4: Constant declaration looks good.

The constant GATE_ADDRESSES is correctly declared as an Item with the key "gate_addresses".


5-5: Constant declaration looks good.

The constant GATE_TIME is correctly declared as an Item with the key "gate_time".

contracts/modules/andromeda-time-gate/Cargo.toml (6)

1-6: Package metadata looks good.

The package metadata is correctly defined.


7-9: Crate type definition looks good.

The crate type is correctly defined as both cdylib and rlib.


10-16: Feature flags look good.

The feature flags are correctly defined and useful for debugging and testing.


18-27: Dependencies look good.

The dependencies are correctly defined and appropriate for the project.


28-31: Target-specific dependencies look good.

The target-specific dependencies are correctly defined and appropriate for non-WASM targets.


32-33: Dev-dependencies look good.

The dev-dependencies are correctly defined and appropriate for development purposes.

contracts/modules/andromeda-time-gate/src/testing/mock.rs (8)

1-4: Imports look good.

The imports are correctly defined and appropriate for the mock implementations.


5-13: Additional imports look good.

The additional imports are correctly defined and appropriate for the mock implementations.


15-35: proper_initialization function looks good.

The function correctly initializes the mock dependencies and instantiates the contract.


37-45: set_gate_time function looks good.

The function correctly sets the gate time using the ExecuteMsg::SetGateTime message.


47-55: update_gate_addresses function looks good.

The function correctly updates the gate addresses using the ExecuteMsg::UpdateGateAddresses message.


57-63: query_gate_time function looks good.

The function correctly queries the gate time using the QueryMsg::GetGateTime message.


65-71: query_gate_addresses function looks good.

The function correctly queries the gate addresses using the QueryMsg::GetGateAddresses message.


73-79: query_path function looks good.

The function correctly queries the path using the QueryMsg::GetPathByCurrentTime message.

packages/andromeda-modules/src/time_gate.rs (5)

1-4: Imports look good.

The imports are correctly defined and appropriate for the "TimeGate ADO" feature.


5-10: InstantiateMsg struct looks good.

The struct correctly includes the necessary fields for instantiation.


12-21: ExecuteMsg enum looks good.

The enum correctly includes the necessary executable messages.


23-33: QueryMsg enum looks good.

The enum correctly includes the necessary query messages.


35-49: GateTime and GateAddresses structs look good.

The structs correctly include the necessary fields for date, time, and addresses.

contracts/modules/andromeda-time-gate/src/mock.rs (7)

1-11: LGTM! Imports and module attributes are appropriate.

The imports and module attributes are necessary for the mock implementation and are correctly used.


13-14: LGTM! Struct definition and macro usage are appropriate.

The struct MockTimeGate and the mock_ado macro are correctly used for the mock implementation.


16-38: LGTM! Instantiation method is correct.

The instantiate method correctly creates and instantiates the MockTimeGate contract.


40-53: LGTM! Execution method for setting gate time is correct.

The execute_set_gate_time method correctly handles the execution of the SetGateTime contract function.


55-68: LGTM! Execution method for updating gate addresses is correct.

The execute_update_gate_addresses method correctly handles the execution of the UpdateGateAddresses contract function.


70-86: LGTM! Query methods are correct.

The query_gate_time, query_gate_addresses, and query_path methods correctly handle querying the contract states.


89-106: LGTM! Helper functions are correct.

The helper functions mock_andromeda_time_gate and mock_time_gate_instantiate_msg are correctly implemented and necessary for the mock implementation.

contracts/modules/andromeda-time-gate/src/testing/tests.rs (5)

1-8: LGTM! Imports are appropriate.

The imports are necessary for the unit tests and are correctly used.


10-45: LGTM! Instantiation test is correct.

The test_instantiation function correctly verifies the instantiation of the TimeGate ADO and the initial state.


47-104: LGTM! Set gate time test is correct.

The test_set_gate_time function correctly verifies the execution of the SetGateTime function and the updated state.


106-148: LGTM! Update gate addresses test is correct.

The test_update_gate_addresses function correctly verifies the execution of the UpdateGateAddresses function and the updated state.


150-169: LGTM! Query path test is correct.

The test_query_path function correctly verifies the execution of the GetPathByCurrentTime query and the expected result.

contracts/modules/andromeda-time-gate/src/contract.rs (11)

1-18: LGTM! Imports and module attributes are appropriate.

The imports and module attributes are necessary for the contract implementation and are correctly used.


20-22: LGTM! Constant definitions are appropriate.

The constants for the contract name and version are necessary for versioning and are correctly defined.


24-52: LGTM! Instantiation function is correct.

The instantiate function correctly initializes the contract state and ensures the gate time is valid.


54-68: LGTM! Execution function is correct.

The execute function correctly routes the execution to the appropriate handler.


70-92: LGTM! Handle execute function is correct.

The handle_execute function correctly handles the execution of the provided message.


94-122: LGTM! Set gate time execution function is correct.

The execute_set_gate_time function correctly handles the execution of the SetGateTime contract function.


124-150: LGTM! Update gate addresses execution function is correct.

The execute_update_gate_addressess function correctly handles the execution of the UpdateGateAddresses contract function.


152-160: LGTM! Query function is correct.

The query function correctly routes the query to the appropriate handler.


162-165: LGTM! Get gate addresses query function is correct.

The get_gate_addresses function correctly handles querying the gate addresses.


167-170: LGTM! Get gate time query function is correct.

The get_gate_time function correctly handles querying the gate time.


199-202: LGTM! Migration function is correct.

The migrate function correctly handles the migration of the contract state.

packages/andromeda-modules/src/time_gate.rs Outdated Show resolved Hide resolved
contracts/modules/andromeda-time-gate/src/contract.rs Outdated Show resolved Hide resolved
@joemonem
Copy link
Contributor

Please address Code Rabbit's comments and replace .unwrap() with ? for safety

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 c6d5281 and dc7e5c0.

Files selected for processing (2)
  • contracts/modules/andromeda-time-gate/src/contract.rs (1 hunks)
  • packages/andromeda-modules/src/time_gate.rs (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • contracts/modules/andromeda-time-gate/src/contract.rs
  • packages/andromeda-modules/src/time_gate.rs

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 dc7e5c0 and d05ed41.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (9)
  • CHANGELOG.md (1 hunks)
  • DEADJOE (1 hunks)
  • contracts/modules/andromeda-time-gate/src/contract.rs (1 hunks)
  • contracts/modules/andromeda-time-gate/src/mock.rs (1 hunks)
  • contracts/modules/andromeda-time-gate/src/state.rs (1 hunks)
  • contracts/modules/andromeda-time-gate/src/testing/mock.rs (1 hunks)
  • contracts/modules/andromeda-time-gate/src/testing/mod.rs (1 hunks)
  • contracts/modules/andromeda-time-gate/src/testing/tests.rs (1 hunks)
  • packages/andromeda-modules/src/time_gate.rs (1 hunks)
Files skipped from review due to trivial changes (2)
  • DEADJOE
  • contracts/modules/andromeda-time-gate/src/testing/mod.rs
Files skipped from review as they are similar to previous changes (6)
  • contracts/modules/andromeda-time-gate/src/contract.rs
  • contracts/modules/andromeda-time-gate/src/mock.rs
  • contracts/modules/andromeda-time-gate/src/state.rs
  • contracts/modules/andromeda-time-gate/src/testing/mock.rs
  • contracts/modules/andromeda-time-gate/src/testing/tests.rs
  • packages/andromeda-modules/src/time_gate.rs
Additional comments not posted (1)
CHANGELOG.md (1)

19-19: Entry for "Time Gate ADO" looks good.

The entry is correctly formatted and consistent with the rest of the file.

@crnbarr93
Copy link
Contributor

Is there a way we can make this cycle through a vector of addresses? Say every hour it moves to the next address in the vector, when it reaches the end of the vector it cycles back to the start.

@mdjakovic0920
Copy link
Contributor Author

Is there a way we can make this cycle through a vector of addresses? Say every hour it moves to the next address in the vector, when it reaches the end of the vector it cycles back to the start.

It can be implemented.
I will do that soon.

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

Outside diff range, codebase verification and nitpick comments (3)
contracts/modules/andromeda-time-gate/src/mock.rs (2)

14-15: Consider adding documentation comments.

Adding documentation comments to MockTimeGate and its methods would improve code readability and maintainability by explaining their purpose and usage.

/// MockTimeGate is a mock implementation for testing the TimeGate contract.
pub struct MockTimeGate(Addr);

120-123: Add documentation for mock_andromeda_time_gate.

Adding a comment to describe the purpose of mock_andromeda_time_gate would improve code readability.

/// Creates a mock contract for the Andromeda Time Gate.
pub fn mock_andromeda_time_gate() -> Box<dyn Contract<Empty>> {
contracts/modules/andromeda-time-gate/src/contract.rs (1)

105-131: Add logging for update operations.

Consider adding logging for operations like execute_update_cycle_start_time to facilitate debugging and tracking contract state changes.

log::info!("Updating cycle start time to {:?}", cycle_start_time);
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d05ed41 and bae990c.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (6)
  • contracts/modules/andromeda-time-gate/src/contract.rs (1 hunks)
  • contracts/modules/andromeda-time-gate/src/mock.rs (1 hunks)
  • contracts/modules/andromeda-time-gate/src/state.rs (1 hunks)
  • contracts/modules/andromeda-time-gate/src/testing/mock.rs (1 hunks)
  • contracts/modules/andromeda-time-gate/src/testing/tests.rs (1 hunks)
  • packages/andromeda-modules/src/time_gate.rs (1 hunks)
Additional comments not posted (5)
contracts/modules/andromeda-time-gate/src/state.rs (1)

5-7: Verify the integration of storage items.

Ensure that GATE_ADDRESSES, CYCLE_START_TIME, and TIME_INTERVAL are correctly used within the contract logic to store and retrieve data as intended.

Verification successful

Storage Items Properly Integrated in Contract Logic

The storage items GATE_ADDRESSES, CYCLE_START_TIME, and TIME_INTERVAL are correctly used within the contract logic. They are imported into contract.rs and utilized for saving and retrieving data, indicating proper integration into the contract's functionality.

  • File: contracts/modules/andromeda-time-gate/src/contract.rs
  • Usage: Methods like save and load are used with these items, confirming their role in managing contract state.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of storage items in the codebase.

# Test: Search for the usage of each storage item. Expect: Proper integration within contract logic.
rg --type rust 'GATE_ADDRESSES|CYCLE_START_TIME|TIME_INTERVAL'

Length of output: 2518

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

95-95: Fix the error message for second validation.

The error message for the second validation should indicate "Second must be less than 60".

-  ContractError::InvalidParameter { error: Some("Wrong minute range".to_string())}
+  ContractError::InvalidParameter { error: Some("Second must be less than 60".to_string())}
contracts/modules/andromeda-time-gate/src/testing/mock.rs (1)

1-100: Verify test coverage for mock functions.

Ensure that the mock functions provided in this file are adequately covered by unit tests to validate their behavior.

Verification successful

Adequate Test Coverage for Mock Functions Verified

The mock functions in contracts/modules/andromeda-time-gate/src/testing/mock.rs are adequately covered by unit tests. The test file contracts/modules/andromeda-time-gate/src/testing/tests.rs contains multiple test functions and assertions that validate the behavior of these mock functions.

  • Test functions found: test_instantiation, test_update_cycle_start_time, test_update_gate_addresses, test_query_current_ado_path_not_started_yet, test_query_current_ado_path.
  • Assertions are present to ensure expected outcomes.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify test coverage for mock functions.

# Test: Search for test functions that utilize the mock functions. Expect: Adequate test coverage.
rg --type rust 'proper_initialization|update_cycle_start_time|update_gate_addresses|update_time_interval|query_cycle_start_time|query_gate_addresses|query_time_interval|query_current_ado_path'

Length of output: 7470


Script:

#!/bin/bash
# Description: Check for test functions and assertions involving mock functions.

# Search for test functions in the relevant test file
rg --type rust 'fn test_' contracts/modules/andromeda-time-gate/src/testing/tests.rs

# Search for assertions involving mock functions in the test file
rg --type rust 'assert' contracts/modules/andromeda-time-gate/src/testing/tests.rs

Length of output: 692

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

56-122: Ensure comprehensive error checking.

The test_update_cycle_start_time function checks for invalid parameters. Ensure that all possible error scenarios are covered, such as unauthorized access or invalid date formats.

// Verify unauthorized access
let unauthorized_info = mock_info("unauthorized_user", &[]);
let err = update_cycle_start_time(
    deps.as_mut(),
    CycleStartTime {
        year: 2023,
        month: 1,
        day: 1,
        hour: 0,
        minute: 0,
        second: 0,
    },
    unauthorized_info.sender.as_ref(),
)
.unwrap_err();
assert_eq!(err, ContractError::Unauthorized {});
contracts/modules/andromeda-time-gate/src/contract.rs (1)

211-257: Ensure correct time calculations in get_current_ado_path.

The function get_current_ado_path performs time calculations. Ensure that all edge cases, such as leap seconds or daylight saving time changes, are correctly handled.

// Verify calculations with edge cases

contracts/modules/andromeda-time-gate/src/testing/tests.rs Outdated Show resolved Hide resolved
contracts/modules/andromeda-time-gate/src/contract.rs Outdated Show resolved Hide resolved
contracts/modules/andromeda-time-gate/src/contract.rs Outdated Show resolved Hide resolved
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 bae990c and f7eb9a7.

Files selected for processing (2)
  • contracts/modules/andromeda-time-gate/src/contract.rs (1 hunks)
  • contracts/modules/andromeda-time-gate/src/testing/tests.rs (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • contracts/modules/andromeda-time-gate/src/contract.rs
  • contracts/modules/andromeda-time-gate/src/testing/tests.rs

@mdjakovic0920
Copy link
Contributor Author

Version 2.0.0

This version of Time Gate ADO returns the moved ado path of the vector each time. When it reaches the end of the vector, it loops back to the starting point.

@mdjakovic0920
Copy link
Contributor Author

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Aug 15, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

}

#[cw_serde]
pub struct CycleStartTime {
Copy link
Contributor

Choose a reason for hiding this comment

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

What's the reasoning for not using Timestamp or Expiry 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.

Of course, we can use Timestamp or Expiry.
By the way, I thought that it is a good way to use more visual methods via year, month, day... than only milliseconds.
If you want Timestamp or Expiry for this, I will do so.

Copy link
Contributor

Choose a reason for hiding this comment

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

For consistency let's use our Expiry type.

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 it.

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

Outside diff range, codebase verification and nitpick comments (3)
contracts/modules/andromeda-time-gate/src/testing/tests.rs (1)

150-214: LGTM with a suggestion!

The test functions test_query_current_ado_path_not_started_yet and test_query_current_ado_path cover the scenarios for querying the current ADO path. The test_query_current_ado_path function tests the scenario just after the cycle starts, which is great.

Consider adding an additional test case for the scenario just before the cycle starts to ensure the correct behavior:

#[test]
fn test_query_current_ado_path_just_before_start() {
    // ... (setup code)
    
    env.block.time = env.block.time.plus_seconds(5000099);
    let res = query_current_ado_path(deps.as_ref(), env.clone()).unwrap_err();
    assert_eq!(
        res,
        ContractError::CustomError {
            msg: "Cycle is not started yet".to_string()
        }
    );
}
contracts/modules/andromeda-time-gate/src/contract.rs (2)

30-68: Refactor to simplify the instantiate function.

Consider the following improvements:

  1. Remove the unused cycle_start_time_millisecons variable.
  2. Combine the cycle_start_time and cycle_start_time_millisecons variables into a single struct to simplify the code.

Apply this diff to implement the suggested changes:

 let (cycle_start_time, _) = get_and_validate_start_time(&env, msg.cycle_start_time)?;
 
-let cycle_start_time_millisecons = match msg.cycle_start_time.clone() {
-    None => Milliseconds::from_nanos(env.block.time.nanos()),
-    Some(start_time) => start_time.get_time(&env.block),
-};
-
 let time_interval_seconds = msg.time_interval.unwrap_or(DEFAULT_TIME_INTERVAL);
 
 GATE_ADDRESSES.save(deps.storage, &msg.gate_addresses)?;
-CYCLE_START_TIME.save(
-    deps.storage,
-    &(cycle_start_time, cycle_start_time_millisecons),
-)?;
+CYCLE_START_TIME.save(deps.storage, &cycle_start_time)?;
 TIME_INTERVAL.save(deps.storage, &time_interval_seconds)?;

232-260: Refactor to simplify the get_current_ado_path function.

Consider the following improvements:

  1. Remove the unused cycle_start_time_milliseconds variable.
  2. Replace the checked_mul, checked_sub, checked_div, and checked_rem functions with the standard arithmetic operators for better readability.

Apply this diff to implement the suggested changes:

 pub fn get_current_ado_path(deps: Deps, env: Env) -> Result<Addr, ContractError> {
     let storage = deps.storage;
-    let (cycle_start_time, cycle_start_time_milliseconds) = CYCLE_START_TIME.load(storage)?;
+    let cycle_start_time = CYCLE_START_TIME.load(storage)?;
     let gate_addresses = GATE_ADDRESSES.load(storage)?;
     let time_interval = TIME_INTERVAL.load(storage)?;
 
     ensure!(
         cycle_start_time.is_expired(&env.block),
         ContractError::CustomError {
             msg: "Cycle is not started yet".to_string()
         }
     );
 
     let current_time_nanos = env.block.time.nanos();
-    let cycle_start_nanos = cycle_start_time_milliseconds.nanos();
+    let cycle_start_nanos = cycle_start_time.nanos();
 
-    let time_interval_nanos = time_interval.checked_mul(1_000_000_000).unwrap();
+    let time_interval_nanos = time_interval * 1_000_000_000;
     let gate_length = gate_addresses.len() as u64;
-    let time_delta = current_time_nanos.checked_sub(cycle_start_nanos).unwrap();
-    let index = time_delta
-        .checked_div(time_interval_nanos)
-        .unwrap()
-        .checked_rem(gate_length)
-        .unwrap() as usize;
+    let time_delta = current_time_nanos - cycle_start_nanos;
+    let index = (time_delta / time_interval_nanos) % gate_length as usize;
     let current_ado_path = &gate_addresses[index];
     let result = current_ado_path.get_raw_address(&deps)?;
 
     Ok(result)
 }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f7eb9a7 and 365b107.

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-time-gate/Cargo.toml (1 hunks)
  • contracts/modules/andromeda-time-gate/src/contract.rs (1 hunks)
  • contracts/modules/andromeda-time-gate/src/state.rs (1 hunks)
  • contracts/modules/andromeda-time-gate/src/testing/mock.rs (1 hunks)
  • contracts/modules/andromeda-time-gate/src/testing/tests.rs (1 hunks)
  • packages/andromeda-modules/src/time_gate.rs (1 hunks)
Additional comments not posted (23)
contracts/modules/andromeda-time-gate/src/state.rs (3)

1-3: LGTM!

The code changes are approved.


5-5: LGTM!

The code changes are approved.


6-7: LGTM!

The code changes are approved.

contracts/modules/andromeda-time-gate/Cargo.toml (5)

1-5: LGTM!

The package section is correctly configured with appropriate package name, version, Rust edition, and minimum supported Rust version.


7-8: LGTM!

The lib section correctly sets the crate type to ["cdylib", "rlib"], which is appropriate for a Rust library that can be used as a native library and a WebAssembly module.


10-15: LGTM!

The features section is correctly configured with appropriate feature flags:

  • "backtraces" enables more explicit tests using cosmwasm-std/backtraces.
  • "library" disables all instantiate/execute/query exports.
  • "testing" enables "cw-multi-test" and "andromeda-testing" for testing purposes.

18-25: LGTM!

The dependencies section is correctly configured with appropriate workspace dependencies:

  • cosmwasm-std, cosmwasm-schema, cw-storage-plus, and cw-utils are standard CosmWasm dependencies.
  • andromeda-std and andromeda-modules are Andromeda-specific dependencies.

The empty features array for andromeda-std is also correct.


27-32: LGTM!

The target-specific dependencies and dev-dependencies sections are correctly configured:

  • The cw-multi-test and andromeda-testing dependencies are correctly marked as optional and only included for non-wasm32 targets.
  • The andromeda-app workspace dependency is correctly included in the dev-dependencies section.
packages/andromeda-modules/src/time_gate.rs (3)

12-16: LGTM!

The code changes are approved.


20-24: LGTM!

The code changes are approved.


29-38: LGTM!

The code changes are approved.

CHANGELOG.md (1)

19-19: LGTM!

The changelog entry for "Time Gate ADO" is consistent with the provided summary and follows the standard format. The pull request link is helpful for reference.

contracts/modules/andromeda-time-gate/src/testing/mock.rs (5)

19-42: LGTM!

The code changes are approved.


44-58: LGTM!

The code changes are approved.


60-70: LGTM!

The code changes are approved.


72-80: LGTM!

The code changes are approved.


82-94: Skipping the existing comment.

The existing comment on line 91 is still valid and applicable.

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

13-46: LGTM!

The test function test_instantiation covers the basic instantiation scenario and verifies the gate addresses, cycle start time, and time interval. The code changes are approved.


48-94: LGTM!

The test function test_update_cycle_start_time comprehensively covers the update scenarios for cycle start time and time interval. It also verifies the error handling for updating with the same cycle start time. The code changes are approved.


96-148: LGTM!

The test function test_update_gate_addresses covers the update scenarios for gate addresses and verifies the error handling for updating with the same gate addresses. The code changes are approved.

contracts/modules/andromeda-time-gate/src/contract.rs (3)

70-84: LGTM!

The code changes are approved.


204-213: LGTM!

The code changes are approved.


152-176: Fix typo in the comment.

The comment mentions execute_update_gate_addressess but the function name is execute_update_gate_addresses. Remove the extra 's' at the end of the 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.

3 participants