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

epic: new protobufs, revive nibi-stargate-perp, and cleanup #100

Merged
merged 22 commits into from
Dec 4, 2023

Conversation

Unique-Divine
Copy link
Member

@Unique-Divine Unique-Divine commented Dec 4, 2023

Context

Commit Log

  • feat(scripts-proto-clean): handlers for nibiru proto cleaning + more tests
  • chore(deps): update Cargo.lock
  • feat(nibiru-std): new protobuf types
  • chore(deps-nibi-stargate): update deps to workspace
  • chore(nibiru-std): rm bindings
  • feat(nibiru-std): add prost::Name impls for new protobuf types
  • feat(nibi-stargate-perp): revive perp bindings contract using CosmosMsg::Stargate
  • refactor(nusd-valuator): run tidy
  • fix(core-shifter): use new types + clean up tests
  • fix(core-controller): use new types + clean up tests [deprecated temp]
  • feat(core-shifter): use cw-ownable, set_contract_version, better perission abstraction
  • refactor(core-shifter)!: make CanExecute logic more concise + tests
  • refactor(contracts): mv core-controller to packages to prevent contract build
  • refactor(core-shifter): make tests more concise and easy to follow
  • chore(artifacts): build all contracts
  • chore(nibiru-std): impl NibiruStargateMsg and NibiruStargateQuery: cosmos bank, cosmos auth
  • chore(nibiru-std): impl NibiruStargateMsg and NibiruStargateQuery: cosmos gov
  • feat(nibiru-std-proto): add pub mod definitions for many modules
  • feat(nibiru-std): trait impls for feat(wasm): Create a Rust package to call module TxMsgs with CosmosMsg::StargateMsg nibiru#1580
  • refactor: remove unnecessary imports of nibiru-macro
  • fix(nibiru-std): fix build by deleting prost::OneOf type in cosmos.staking
  • ci: add codecov.yml

Summary by CodeRabbit

  • Documentation

    • Updated Codecov configuration to adjust coverage settings and pull request comment behavior.
    • Added and updated checksums for WebAssembly files.
    • Removed, updated, and added various WebAssembly files to reflect the latest changes.
    • Introduced new error handling capabilities with the ContractError type.
    • Added new modules and refactored message handling in smart contracts.
    • Streamlined build and execution processes with new aliases in configuration files.
    • Enhanced testing utilities and added new test cases.
    • Expanded and reorganized protobuf message definitions and type URLs.
    • Adjusted import logic and added new conditions in script files for cleaning protobuf modules.
  • Refactor

    • Removed custom message handling and simplified imports in smart contract modules.
    • Reorganized module structure and expanded functionality within the cosmos package.
    • Updated constants and implemented new message names for transaction and query types.
  • Style

    • Formatted prost message definitions by adjusting the tag attribute formatting.
  • Tests

    • Added integration test functions and updated test modules to reflect changes in smart contract logic.
  • Chores

    • Added comments and documentation related to testing utilities for Nibiru smart contracts.
  • Bug Fixes

    • Addressed issues with deprecation handling in message enums and added relevant notes.

@Unique-Divine Unique-Divine added type: bug/fix A pull request that fixes someting (pull) OR a ticket that highlights a bug (issue). type: enhancement New feature or request epic Project or large task that groups multiple tickets and PRs labels Dec 4, 2023
Copy link
Contributor

coderabbitai bot commented Dec 4, 2023

Walkthrough

The changes encompass a broad restructuring and enhancement of the codebase, including updates to configuration files, WebAssembly artifacts, contract logic, error handling, and protobuf message definitions. The modifications aim to refine coverage settings, improve contract functionality, and align message handling with the CosmosMsg::StargateMsg format.

Changes

File Pattern Change Summary
.github/codecov.yml Adjusted coverage settings and added comment behavior configuration.
artifacts/... Updated and added WebAssembly files.
contracts/.../src/contract.rs Updated contract initialization, execution, and query handling.
contracts/.../src/error.rs Added new ContractError type with variants for error handling.
contracts/.../src/lib.rs Added new modules for error handling and testing.
contracts/.../src/msgs.rs Renamed structs and updated message types for contract execution.
contracts/.../src/state.rs Renamed Whitelist to Permissions and updated related functionality.
contracts/.../src/testing.rs Introduced test helper functions and constants.
contracts/nusd-valuator/... Added aliases for build and run commands, and moved the testing module.
nibiru-std/src/bindings/... Removed modules and updated message handling.
nibiru-std/src/proto/... Added sub-modules, updated protobuf message definitions, and added constants.
packages/core-controller/... Introduced build and run command aliases and updated contract execution logic.
scripts/proto_clean.rs Added new static variable and updated file filtering logic.

Assessment against linked issues

Objective Addressed Explanation
Allow update/transfer of shifter admin rights (#49) No specific changes related to admin rights transfer were identified in the provided diffs.
Create a Rust package to call module TxMsgs with CosmosMsg::StargateMsg (#1580)
Remove Wasm Route in wasmbindings as it is not used (#1642)

Related issues

Poem

In the realm of code, where rabbits hop,
Changes abound, nonstop.
From contracts to tests, with care,
A rabbit's touch, none can compare. 🐇💻✨


Tips

Chat with CodeRabbit Bot (@coderabbitai)

  • If you reply to a review comment from CodeRabbit, the bot will automatically respond.
  • To engage with CodeRabbit bot directly around the specific lines of code in the PR, mention @coderabbitai in your review comment
  • Note: Review comments are made on code diffs or files, not on the PR overview.
  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Note: For conversation with the bot, please use the review comments on code diffs or files.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

@Unique-Divine Unique-Divine added the ci GitHub actions or other continuous integration changes label Dec 4, 2023
Copy link

codecov bot commented Dec 4, 2023

Codecov Report

Merging #100 (535007e) into main (3a4a97f) will increase coverage by 4.89%.
Report is 31 commits behind head on main.
The diff coverage is 89.88%.

Additional details and impacted files
Files Coverage Δ
contracts/core-cw3-flex-msig/src/error.rs 100.00% <100.00%> (ø)
contracts/core-cw3-flex-msig/src/state.rs 100.00% <100.00%> (ø)
contracts/core-token-vesting/src/contract.rs 96.55% <100.00%> (ø)
contracts/core-token-vesting/src/errors.rs 100.00% <ø> (ø)
contracts/core-token-vesting/src/msg.rs 94.57% <100.00%> (ø)
contracts/core-token-vesting/src/state.rs 100.00% <ø> (ø)
contracts/core-token-vesting/src/testing.rs 98.91% <100.00%> (ø)
contracts/incentives/src/msgs.rs 100.00% <100.00%> (ø)
contracts/incentives/src/testing.rs 100.00% <100.00%> (ø)
contracts/lockup/src/contract.rs 81.41% <100.00%> (ø)
... and 35 more

... and 1 file with indirect coverage changes

@Unique-Divine Unique-Divine merged commit d966563 into main Dec 4, 2023
5 checks passed
@Unique-Divine Unique-Divine deleted the realu/new-pb branch December 4, 2023 08:38
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.

Review Status

Actionable comments generated: 16

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between cc1fa0d and 535007e.
Files ignored due to filter (18)
  • Cargo.lock
  • Cargo.toml
  • artifacts/bindings_perp.wasm
  • artifacts/cw3_flex_multisig.wasm
  • artifacts/incentives.wasm
  • artifacts/lockup.wasm
  • artifacts/nibi_stargate.wasm
  • artifacts/nibi_stargate_perp.wasm
  • artifacts/nusd_valuator.wasm
  • artifacts/pricefeed.wasm
  • artifacts/shifter.wasm
  • artifacts/token_vesting.wasm
  • contracts/core-shifter/Cargo.toml
  • contracts/nibi-stargate-perp/Cargo.toml
  • contracts/nibi-stargate/Cargo.toml
  • nibiru-std/Cargo.toml
  • packages/core-controller/Cargo.lock
  • packages/core-controller/Cargo.toml
Files selected for processing (39)
  • .github/codecov.yml (1 hunks)
  • artifacts/checksums.txt (1 hunks)
  • artifacts/checksums_intermediate.txt (1 hunks)
  • contracts/core-shifter/src/contract.rs (4 hunks)
  • contracts/core-shifter/src/error.rs (1 hunks)
  • contracts/core-shifter/src/lib.rs (1 hunks)
  • contracts/core-shifter/src/msgs.rs (1 hunks)
  • contracts/core-shifter/src/state.rs (1 hunks)
  • contracts/core-shifter/src/testing.rs (1 hunks)
  • contracts/nibi-stargate-perp/src/contract.rs (1 hunks)
  • contracts/nibi-stargate-perp/src/integration_test.rs (1 hunks)
  • contracts/nibi-stargate-perp/src/lib.rs (1 hunks)
  • contracts/nibi-stargate-perp/src/msg.rs (1 hunks)
  • contracts/nibi-stargate-perp/src/state.rs (1 hunks)
  • contracts/nusd-valuator/.cargo/config (1 hunks)
  • contracts/nusd-valuator/src/lib.rs (1 hunks)
  • contracts/nusd-valuator/src/msgs.rs (3 hunks)
  • contracts/nusd-valuator/src/queries.rs (1 hunks)
  • contracts/nusd-valuator/src/testing.rs (1 hunks)
  • nibiru-std/src/bindings/mod.rs (1 hunks)
  • nibiru-std/src/bindings/msg.rs (2 hunks)
  • nibiru-std/src/lib.rs (1 hunks)
  • nibiru-std/src/proto/buf/cosmos.bank.v1beta1.rs (17 hunks)
  • nibiru-std/src/proto/buf/cosmos.crypto.keyring.v1.rs (1 hunks)
  • nibiru-std/src/proto/buf/cosmos.staking.v1beta1.rs (21 hunks)
  • nibiru-std/src/proto/buf/nibiru.epochs.v1.rs (1 hunks)
  • nibiru-std/src/proto/buf/nibiru.inflation.v1.rs (2 hunks)
  • nibiru-std/src/proto/buf/nibiru.oracle.v1.rs (14 hunks)
  • nibiru-std/src/proto/buf/nibiru.perp.v2.rs (8 hunks)
  • nibiru-std/src/proto/buf/nibiru.spot.v1.rs (4 hunks)
  • nibiru-std/src/proto/buf/nibiru.tokenfactory.v1.rs (7 hunks)
  • nibiru-std/src/proto/mod.rs (3 hunks)
  • nibiru-std/src/proto/type_url_cosmos.rs (2 hunks)
  • nibiru-std/src/proto/type_url_nibiru.rs (6 hunks)
  • nibiru-std/src/tutil/mod.rs (1 hunks)
  • packages/core-controller/.cargo/config (1 hunks)
  • packages/core-controller/src/contract.rs (9 hunks)
  • packages/core-controller/src/msgs.rs (3 hunks)
  • scripts/proto_clean.rs (6 hunks)
Files not summarized due to errors (2)
  • nibiru-std/src/proto/buf/cosmos.staking.v1beta1.rs: Error: Message exceeds token limit
  • nibiru-std/src/proto/buf/nibiru.perp.v2.rs: Error: Message exceeds token limit
Files not reviewed due to errors (1)
  • nibiru-std/src/proto/buf/cosmos.staking.v1beta1.rs (Error: Message exceeds token limit)
Files skipped from review due to trivial changes (9)
  • artifacts/checksums_intermediate.txt
  • contracts/nusd-valuator/.cargo/config
  • contracts/nusd-valuator/src/testing.rs
  • nibiru-std/src/proto/buf/nibiru.oracle.v1.rs
  • nibiru-std/src/proto/buf/nibiru.spot.v1.rs
  • nibiru-std/src/proto/buf/nibiru.tokenfactory.v1.rs
  • nibiru-std/src/proto/type_url_nibiru.rs
  • nibiru-std/src/tutil/mod.rs
  • packages/core-controller/.cargo/config
Additional comments: 74
.github/codecov.yml (1)
  • 3-20: The changes to the codecov.yml file reflect updates to the coverage range, precision, and how coverage status and comments are handled. These changes are consistent with the PR objectives to update configuration settings.
artifacts/checksums.txt (1)
  • 1-10: The checksums for the WebAssembly bytecode artifacts have been updated, which is consistent with the PR objectives of building new bytecode artifacts for updated contracts. However, the summary mentions the removal of bindings_perp.wasm, which is not reflected in the provided hunk. Please verify if bindings_perp.wasm has been removed from the codebase.
contracts/core-shifter/src/contract.rs (6)
  • 1-6: The import changes align with the PR objectives and summary, removing outdated constructs and using updated modules.

  • 20-33: The instantiate function has been updated to set the contract version and initialize permissions, which is consistent with the PR objectives and summary.

  • 36-112: The execute function has been refactored to handle different message types, including ShiftSwapInvariant, ShiftPegMultiplier, EditOpers, and UpdateOwnership. This is in line with the PR objectives and summary.

  • 115-124: The execute_update_ownership function uses cw_ownable::Action, which is part of the cw-ownable package mentioned in the PR objectives. This should have been highlighted in the summary.

  • 126-152: The CanExecute struct has been refactored to handle ownership and operator permissions, which is consistent with the PR objectives and summary.

  • 155-178: The query function has been updated to handle different query messages, which is consistent with the PR objectives and summary.

contracts/core-shifter/src/error.rs (1)
  • 1-15: The changes to the ContractError enum are well-aligned with the PR objectives and follow Rust's idiomatic error handling practices.
contracts/core-shifter/src/lib.rs (1)
  • 1-6: The addition of the error module is consistent with the PR objectives of improving error handling within the core-shifter contract. The testing module is correctly included only during testing, which is standard practice and should not affect production code.
contracts/core-shifter/src/msgs.rs (5)
  • 8-10: The renaming of the admin field to owner in the InitMsg struct aligns with the PR objectives and the summary provided.

  • 15-24: The changes to the ExecuteMsg enum, including the addition of ShiftSwapInvariant, ShiftPegMultiplier, and EditOpers variants, are consistent with the PR objectives and the summary.

  • 27-34: The introduction of the operator_perms module and the Action enum with AddOper and RemoveOper variants is in line with the PR objectives and the summary.

  • 40-47: The updates to the QueryMsg enum, including the addition of HasPerms and Perms variants, match the PR objectives and the summary.

  • 50-60: The HasPermsResponse and PermsResponse structs have been updated to align with the new permissions model, which is consistent with the PR objectives and the summary.

contracts/core-shifter/src/state.rs (1)
  • 59-127: The test cases have been appropriately updated to test the new functionality of the Permissions struct. This ensures that the changes are verified and working as intended. It's good to see comprehensive testing around the new features.
contracts/core-shifter/src/testing.rs (1)
  • 17-33: The changes to the setup_contract function align with the PR objectives of refactoring for cleaner code and improved maintainability.
contracts/nibi-stargate-perp/src/contract.rs (4)
  • 42-86: The query function is not implemented and contains a todo!() macro. Ensure that this is intentional and that the function will be implemented before the contract is used in a production environment.

  • 163-163: There are TODO comments within the execute function related to testing the ExecuteMsg::MultiLiquidate variant. Ensure that these tests are implemented before the contract is used in a production environment.

  • 180-180: There are TODO comments within the execute function related to testing the ExecuteMsg::DonateToInsuranceFund variant. Ensure that these tests are implemented before the contract is used in a production environment.

  • 280-295: The query_contract_balance function correctly handles the case where the query result is None by returning a default AllBalanceResponse. This is a safe and appropriate fallback.

contracts/nibi-stargate-perp/src/integration_test.rs (2)
  • 10-11: The TODO comment on line 10 suggests a test should be added to ensure the WASM file exists. Verify if this has been addressed and remove the comment if it is no longer relevant.

  • 1-53: Ensure that the integration tests cover the new functionality mentioned in the PR objectives, such as the use of CosmosMsg::Stargate for message passing.

contracts/nibi-stargate-perp/src/lib.rs (1)
  • 1-3: The hunk shows the module structure of the nibi-stargate-perp contract. To ensure the PR objectives are met, the implementation details within these modules would need to be reviewed, particularly the use of CosmosMsg::Stargate for message passing as mentioned in the PR objectives and summary.
contracts/nibi-stargate-perp/src/msg.rs (5)
  • 6-10: The InitMsg struct is correctly defined with an optional admin field, aligning with the common pattern for smart contract instantiation messages.

  • 16-54: The ExecuteMsg enum is well-defined, covering a range of contract operations such as market orders, position management, and insurance fund interactions. This aligns with the PR objectives of updating the nibi-stargate-perp contract.

  • 56-60: The LiquidationArgs struct is appropriately defined for specifying arguments for liquidation operations.

  • 66-91: The QueryMsg enum is well-structured, providing a clear interface for querying contract state, such as sudoers, markets, positions, module accounts, and oracle prices.

  • 93-96: The SudoersQueryResponse struct is correctly defined to encapsulate the response for a sudoers query.

contracts/nibi-stargate-perp/src/state.rs (1)
  • 1-94: The Sudoers struct and its methods, along with the associated tests, are correctly implemented and cover the required functionality. The use of HashSet for managing unique members and the comprehensive tests for the Sudoers methods, including storage operations, follow best practices and are well-structured.
contracts/nusd-valuator/src/lib.rs (1)
  • 13-14: The summary states that the testing module has been moved outside of the conditional compilation directive #[cfg(test)], but the hunk shows that it is still within the directive. This discrepancy should be addressed to ensure accurate documentation.
contracts/nusd-valuator/src/msgs.rs (3)
  • 26-30: The summary states that RedeemableChoices has been changed to return BTreeSet<cw::Coin> instead of BTreeSet<Coin>, but the hunk shows that it already returns BTreeSet<cw::Coin>. Please verify if the summary is accurate or if the change was made in a previous commit.

  • 18-20: The summary indicates that the type of to_denom in the Redeemable variant was changed to cw::Uint128, but the hunk shows it is still a String. Please verify if the summary is accurate or if the change was made in a previous commit.

  • 12-13: The summary states that the type of from_coins in the Mintable variant was changed to BTreeSet<cw::Coin>, but the hunk shows it is still BTreeSet<String>. Please verify if the summary is accurate or if the change was made in a previous commit.

contracts/nusd-valuator/src/queries.rs (2)
  • 68-71: The summary stating only the addition of a newline at the end of the file is incorrect. The hunk shows a logical change in the query_redeemable_choices function, which collects the results of query_redeemable calls into a vector. This change should be reflected in the summary.

  • 68-71: The code in the hunk appears to be correct and does not exhibit any issues with the key areas of review.

nibiru-std/src/bindings/mod.rs (1)
  • 7-9: The hunk shows the current state of the bindings/mod.rs file, which includes the msg module. There is no evidence in the hunk of the removal of the querier, query, and state modules, but this is consistent with the PR objectives and the summary provided. No action is required based on this hunk.
nibiru-std/src/bindings/msg.rs (1)
  • 1-5: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [1-44]

The changes in nibiru-std/src/bindings/msg.rs align with the PR objectives and the provided summary. The removal of custom message handling and the simplification of message routing are reflected in the code. The NibiruMsg enum is now used for message handling, and the LiquidationArgs struct is correctly defined.

nibiru-std/src/lib.rs (2)
  • 9-9: The addition of the tutil module should be documented in the PR summary or objectives if it introduces new functionality or changes existing behavior.

  • 12-12: The update of the VERSION_NIBIRU constant is in line with the PR objective of publishing a new version of the nibiru-std crate. Ensure that this version update is reflected wherever necessary across the codebase.

nibiru-std/src/proto/buf/cosmos.bank.v1beta1.rs (1)
  • 73-152: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [6-500]

The formatting changes to the tag attributes in the prost message definitions are consistent and do not alter the functionality or logic of the code. These changes should not affect the serialization or deserialization of the protobuf messages as the tag numbers remain unchanged.

nibiru-std/src/proto/buf/cosmos.crypto.keyring.v1.rs (1)
  • 28-32: The update to the path field in the Ledger struct from super::super::super::hd::v1::Bip44Params to crate::proto::cosmos::crypto::hd::v1::Bip44Params is consistent with the PR objectives and summary. Ensure that all references to this field are updated accordingly across the codebase to reflect the new module path.
nibiru-std/src/proto/buf/nibiru.epochs.v1.rs (1)
  • 54-60: The renaming of the structs QueryEpochInfosRequest and QueryEpochInfosResponse is consistent with the summary provided and the PR objectives. Ensure that all references to these structs in the codebase are updated to reflect the new names.
nibiru-std/src/proto/buf/nibiru.inflation.v1.rs (2)
  • 7-35: The formatting changes in the InflationDistribution and GenesisState structs are consistent with the PR objectives of cleaning up the codebase. These changes do not alter the functionality or the structure of the data.

  • 39-61: The addition of new fields periods_per_year and max_period to the Params struct aligns with the PR objectives of updating the codebase. Ensure that all relevant parts of the code that interact with the Params struct are updated to handle these new fields.

nibiru-std/src/proto/buf/nibiru.perp.v2.rs (8)
  • 4-58: The Market struct definition appears to be correctly defined with appropriate field types and comments explaining each field.

  • 4-152: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [150-177]

The Direction enum and its associated methods are correctly implemented and follow Rust's conventions for enums and associated functions.

  • 215-250: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [215-271]

The PositionChangedEvent struct definition appears to be correctly defined with appropriate field types and comments explaining each field.

  • 276-341: The PositionLiquidatedEvent and LiquidationFailedEvent struct definitions appear to be correctly defined with appropriate field types and comments explaining each field.

  • 363-369: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [345-368]

The LiquidationFailedReason enum and its associated methods are correctly implemented and follow Rust's conventions for enums and associated functions.

  • 388-399: The AmmUpdatedEvent struct definition appears to be correctly defined with appropriate field types and comments explaining each field.

  • 409-769: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [409-945]

The MarketUpdatedEvent struct and other related structs and messages for the genesis state and various events are correctly defined with appropriate field types and comments explaining each field.

  • 772-981: The message structs such as MsgMarketOrder, MsgMarketOrderResponse, MsgClosePosition, MsgClosePositionResponse, MsgPartialClose, MsgPartialCloseResponse, and others are correctly defined with appropriate field types and comments explaining each field.
nibiru-std/src/proto/mod.rs (1)
  • 79-223: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [28-106]

The addition of multiple sub-modules within the cosmos module is consistent with the summary provided. This expansion aligns with the PR objectives of restructuring and expanding the nibiru-std crate's functionality.

nibiru-std/src/proto/type_url_cosmos.rs (2)
  • 6-32: The addition of constants for package names and implementations of the Name trait for various message types in the cosmos.bank.v1beta1 package aligns with the PR objectives and summary provided.

  • 53-157: The implementation of the Name trait for various message types in the cosmos.auth.v1beta1 and cosmos.gov.v1 packages aligns with the PR objectives and summary provided.

packages/core-controller/src/contract.rs (7)
  • 1-7: The changes to the imports and module usage appear to be correct and there are no unused imports or missing dependencies.

  • 139-145: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [135-145]

The implementation of AddMember correctly adds a member to the whitelist and saves it.

  • 151-157: The implementation of RemoveMember correctly removes a member from the whitelist and saves it.

  • 166-172: The implementation of ChangeAdmin correctly changes the admin in the whitelist and saves it.

  • 315-324: The test case for adding a member correctly checks the response attributes and the state of the whitelist after the operation.

  • 386-395: The test case for removing a member correctly checks the response attributes and the state of the whitelist after the operation.

  • 450-459: The test case for changing the admin correctly checks the response attributes and the state of the whitelist after the operation.

packages/core-controller/src/msgs.rs (6)
  • 1-1: The use of #![allow(deprecated)] is consistent with the PR objectives to mark certain enum variants as deprecated.

  • 16-16: The deprecation note on SetMarketEnabled is consistent with the PR objectives to deprecate certain functionalities in favor of MsgServer implementations.

  • 22-22: The deprecation note on InsuranceFundWithdraw is consistent with the PR objectives to deprecate certain functionalities in favor of MsgServer implementations.

  • 26-26: The deprecation note on EditOracleParams is consistent with the PR objectives to deprecate certain functionalities in favor of MsgServer implementations.

  • 39-39: The deprecation note on CreateMarket is consistent with the PR objectives to deprecate certain functionalities in favor of MsgServer implementations.

  • 13-29: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [13-42]

The changes to the ExecuteMsg enum, including the addition of deprecation notes, align with the PR objectives and the summary provided.

scripts/proto_clean.rs (5)
  • 15-15: The addition of PROTO_PATH aligns with the PR objectives to introduce updates and improvements.

  • 23-29: The updated file filtering logic to include "nibiru" prefixed files is consistent with the PR objectives.

  • 106-122: The updates to the super_import_to_clean function reflect the PR objectives to modify conditions and prefixes for submodule imports.

  • 130-155: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [131-195]

The addition of functions and data structures in the proto_submodules module supports the modified import logic, aligning with the PR objectives.

  • 224-241: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [199-241]

The new test cases added to the tests module are appropriate for validating the updated import logic, consistent with the PR objectives.

Comment on lines +35 to +52
// #[test]
// fn query_reserves() {
// let mut deps = mock_instance(WASM, &[]);
// let sender = String::from("sender");
// let info = mock_info(&sender, &coins(1000, "unibi"));
// let inst_msg = InitMsg {};
// let result: Response =
// instantiate(&mut deps, mock_env(), info, inst_msg).unwrap();
// assert_eq!(result.messages.len(), 0);

// let pair = String::from("ueth:unusd");
// let query_msg = NibiruQuery::Reserves { pair };
// let raw_resp = query(&mut deps, mock_env(), query_msg);
// assert!(raw_resp.is_err(), "err: {}", raw_resp.unwrap_err());
// let resp: ReservesResponse =
// from_slice(&raw_resp.unwrap(), DESERIALIZATION_LIMIT).unwrap();
// assert_eq!(resp.pair, pair)
// }
Copy link
Contributor

Choose a reason for hiding this comment

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

The commented-out test code from lines 35-52 should be completed or removed if it's not intended to be used. Leaving commented-out code can lead to confusion and clutter in the codebase.


pub const TEST_OWNER: &str = "owner";

pub fn setup_contract(// accepted_denoms: Vec<String>,
Copy link
Contributor

Choose a reason for hiding this comment

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

The commented-out parameter // accepted_denoms: Vec<String>, should be removed if it's not used anywhere in the codebase.

- pub fn setup_contract(// accepted_denoms: Vec<String>,
+ pub fn setup_contract(

Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
pub fn setup_contract(// accepted_denoms: Vec<String>,
pub fn setup_contract(

Comment on lines +1 to +57
use std::collections::BTreeSet;

use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Api, Storage};
use cw_storage_plus::Item;

pub const WHITELIST: Item<Whitelist> = Item::new("whitelist");
use crate::error::ContractError;

pub const OPERATORS: Item<BTreeSet<String>> = Item::new("operators");

#[cw_serde]
pub struct Whitelist {
pub members: HashSet<String>,
pub admin: String,
pub struct Permissions {
pub owner: Option<String>,
pub operators: BTreeSet<String>,
}

impl Whitelist {
impl Permissions {
pub fn has(&self, addr: impl AsRef<str>) -> bool {
let addr = addr.as_ref();
self.members.contains(addr) || self.admin == addr
self.operators.contains(addr) || self.is_owner(addr)
}

pub fn is_admin(&self, addr: impl AsRef<str>) -> bool {
pub fn is_owner(&self, addr: impl AsRef<str>) -> bool {
let addr = addr.as_ref();
self.admin == addr
if let Some(owner) = &self.owner {
owner == addr
} else {
false
}
}

pub fn is_member(&self, addr: impl AsRef<str>) -> bool {
pub fn is_operator(&self, addr: impl AsRef<str>) -> bool {
let addr = addr.as_ref();
self.members.contains(addr)
self.operators.contains(addr)
}

pub fn load(storage: &dyn Storage) -> Result<Self, ContractError> {
let owner = cw_ownable::get_ownership(storage)?.owner;
let opers = OPERATORS.load(storage)?;
Ok(Permissions {
owner: owner.map(|addr| addr.into_string()),
operators: opers,
})
}
}

/// Set the given address as the contract owner and initialize the
/// 'OPERATORS' and 'OWNERSHIP' state. This function is only intended to be used only
/// during contract instantiation.
pub fn instantiate_perms(
owner: Option<&str>,
storage: &mut dyn Storage,
api: &dyn Api,
) -> Result<(), ContractError> {
cw_ownable::initialize_owner(storage, api, owner)?;
Ok(OPERATORS.save(storage, &BTreeSet::default())?)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The changes to the Permissions struct and the addition of new functions such as is_owner, is_operator, load, and instantiate_perms align with the PR objectives of implementing a cleaner permissions abstraction using cw-ownable. The tests have been updated accordingly to reflect these changes. However, it's important to note that the switch from HashSet to BTreeSet for the operators field may have performance implications due to the ordered nature of BTreeSet, which should be considered if performance is a critical factor.

@@ -81,36 +79,145 @@ pub mod cosmos {
}
}

/// Defines base data structures like Coin, DecCoin, IntProto, and
/// DecProto. These types implement custo method signatures required by
Copy link
Contributor

Choose a reason for hiding this comment

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

Typographical error.

- /// DecProto. These types implement custo method signatures required by
+ /// DecProto. These types implement custom method signatures required by

Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
/// DecProto. These types implement custo method signatures required by
/// DecProto. These types implement custom method signatures required by

Comment on lines 1 to 233
}
}
}

#[cfg(test)]
mod tests {
pub mod tests {
use super::*;
use crate::{
msgs::{ExecuteMsg, InitMsg},
state::WHITELIST,
state::OPERATORS,
testing::{self as t, TestResult},
};

use cosmwasm_std::{coins, testing, Addr};
use std::collections::HashSet;
use cosmwasm_std::{coins, testing};
use std::collections::BTreeSet;

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[test]
fn test_instantiate() {
fn test_instantiate() -> TestResult {
let mut deps = testing::mock_dependencies();
let msg = InitMsg {
admin: "admin".to_string(),
owner: "admin".to_string(),
};
let info: MessageInfo =
testing::mock_info("addr0000", &coins(2, "token"));

let result =
instantiate(deps.as_mut(), testing::mock_env(), info, msg).unwrap();
let result = instantiate(deps.as_mut(), testing::mock_env(), info, msg)?;

assert_eq!(result.messages.len(), 0);
Ok(())
}

#[test]
fn test_has_admin_power() {
let admin = Addr::unchecked("admin");
let msg = &InitMsg {
admin: admin.to_string(),
};

fn test_has_admin_power() -> TestResult {
let sender = "not-admin";
let mut deps = testing::mock_dependencies();
let msg_info = testing::mock_info(sender, &coins(2, "token"));
instantiate(deps.as_mut(), testing::mock_env(), msg_info, msg.clone())
.unwrap();
let whitelist = WHITELIST.load(&deps.storage).unwrap();
let has: bool = whitelist.is_admin(sender);
assert!(!has);

let sender = "admin";
let mut deps = testing::mock_dependencies();
let msg_info = testing::mock_info(sender, &coins(2, "token"));
instantiate(deps.as_mut(), testing::mock_env(), msg_info, msg.clone())
.unwrap();
let whitelist = WHITELIST.load(&deps.storage).unwrap();
let has: bool = whitelist.is_admin(sender);
let (deps, _env, _info) = t::setup_contract()?;
let perms = Permissions::load(&deps.storage)?;
let not_has: bool = !perms.is_owner(sender);
assert!(not_has);
let sender = t::TEST_OWNER;
let has: bool = perms.is_owner(sender);
assert!(has);
Ok(())
}

#[test]
fn test_execute_unauthorized() {
let mut deps = testing::mock_dependencies();
let admin = Addr::unchecked("admin");

let msg = InitMsg {
admin: admin.as_str().to_string(),
};
let msg_info = testing::mock_info("addr0000", &coins(2, "token"));
instantiate(deps.as_mut(), testing::mock_env(), msg_info, msg).unwrap();

let execute_msg = ExecuteMsg::AddMember {
address: "addr0001".to_string(),
};
fn test_exec_unauthorized() -> TestResult {
let (mut deps, _env, _info) = t::setup_contract()?;
let execute_msg =
ExecuteMsg::EditOpers(operator_perms::Action::AddOper {
address: "addr0001".to_string(),
});
let unauthorized_info = testing::mock_info("unauthorized", &[]);
let result = execute(
deps.as_mut(),
Copy link
Contributor

Choose a reason for hiding this comment

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

Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [180-358]

The test cases have been updated to reflect the changes in the contract logic and functionality. However, the test_exec_change_admin function is marked as a TODO and does not contain any test logic. This should be implemented to ensure the execute_update_ownership function works as expected.

    // TODO: Implement test logic for change owner functionality
    #[test]
    fn test_exec_change_admin() -> TestResult {
        // Test logic should be added here
        Ok(())
    }

Comment on lines 113 to 135
validator_fee_ratio,
} => {
check_member(check)?;
let cw_msg = ContractExecMsg {
route: NibiruRoute::Oracle,
msg: Some(ExecuteMsg::EditOracleParams {
vote_period,
vote_threshold,
reward_band,
whitelist,
slash_fraction,
slash_window,
min_valid_per_window,
twap_lookback_window,
min_voters,
validator_fee_ratio,
}),
todo!();
let _cw_msg = ExecuteMsg::EditOracleParams {
vote_period,
vote_threshold,
reward_band,
whitelist,
slash_fraction,
slash_window,
min_valid_per_window,
twap_lookback_window,
min_voters,
validator_fee_ratio,
};
let res = Response::new()
.add_message(cw_msg)
.add_attributes(vec![attr("action", "edit_oracle")]);
Ok(res)
// let res = Response::new()
// .add_message(cw_msg)
// .add_attributes(vec![attr("action", "edit_oracle")]);
// Ok(res)
}

ExecuteMsg::AddMember { address } => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [104-130]

Incomplete functionality due to todo!() macro and commented-out code. This should be completed or removed before merging.

Comment on lines +20 to +40
#[entry_point]
pub fn instantiate(
deps: DepsMut,
_env: Env,
info: MessageInfo,
msg: InitMsg,
) -> StdResult<Response> {
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
let admin: String = match msg.admin {
Some(msg_admin) => msg_admin,
None => info.sender.to_string(),
};
let sudoers = Sudoers {
members: vec![admin.clone()].into_iter().collect(),
admin,
};
SUDOERS.save(deps.storage, &sudoers)?;
Ok(Response::new()
.add_attribute("action", "instantiate")
.add_attribute("owner", info.sender))
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The instantiate function should return Result<Response, ContractError> as per the PR objectives, but it currently returns StdResult<Response>. This needs to be updated to align with the new error handling strategy.

Comment on lines +88 to +241
can_execute.check_member()?;
let cosmos_msg: CosmosMsg = nibiru::perp::MsgAddMargin {
sender: contract_addr,
pair,
margin: Some(margin.into()),
}
.into_stargate_msg();
Ok(Response::new().add_message(cosmos_msg))
}

ExecuteMsg::RemoveMargin { pair, margin } => {
can_execute.check_member()?;
let cosmos_msg: CosmosMsg = nibiru::perp::MsgRemoveMargin {
sender: contract_addr,
pair,
margin: Some(margin.into()),
}
.into_stargate_msg();
Ok(Response::new().add_message(cosmos_msg))
}

// TODO:test ExecuteMsg::MultiLiquidate
ExecuteMsg::MultiLiquidate { liquidations } => {
can_execute.check_member()?;
let cosmos_msg: CosmosMsg = nibiru::perp::MsgMultiLiquidate {
sender: contract_addr,
liquidations: liquidations
.iter()
.map(|la| nibiru::perp::msg_multi_liquidate::Liquidation {
pair: la.pair.clone(),
trader: la.trader.clone(),
})
.collect(),
}
.into_stargate_msg();
Ok(Response::new().add_message(cosmos_msg))
}

// TODO:test ExecuteMsg::DonateToInsuranceFund
ExecuteMsg::DonateToInsuranceFund { donation } => {
can_execute.check_member()?;
let cosmos_msg: CosmosMsg = nibiru::perp::MsgDonateToEcosystemFund {
sender: contract_addr,
donation: Some(donation.into()),
}
.into_stargate_msg();
Ok(Response::new().add_message(cosmos_msg))
}

ExecuteMsg::Claim {
funds,
claim_all,
to,
} => {
can_execute.check_admin()?;
let event_key = "execute_claim";
if let Some(claim_all_value) = claim_all {
if !claim_all_value {
return Err(StdError::generic_err(
"setting 'claim_all' to false causes an error: "
.to_string()
+ "try removing claim_all as an argument entirely.",
));
}
let contract_address = env_ctx.contract.address;
let balances = query_contract_balance(
contract_address.to_string(),
deps.as_ref(),
)?;

// Send all funds to the specified recipient.
let transfer_msg = BankMsg::Send {
to_address: to.clone(),
amount: balances.amount,
};
Ok(Response::new().add_message(transfer_msg).add_attribute(
event_key,
format!("successfully claimed to {}", to),
))
} else if let Some(funds_value) = funds {
// Send all funds to the specified recipient.
let transfer_msg = BankMsg::Send {
to_address: to.clone(),
amount: vec![funds_value],
};
return Ok(Response::new()
.add_message(transfer_msg)
.add_attribute(
event_key,
format!("successfully claimed to {}", to),
));
} else {
return Err(StdError::generic_err(
"either the 'funds' or 'claim_all' arguments must be specified"));
}
} // TODO test: add member
// TODO test: remove member
// TODO test: change admin
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The execute function should return Result<Response, ContractError> as per the PR objectives, but it currently returns StdResult<Response>. This needs to be updated to align with the new error handling strategy.

Comment on lines +191 to +237
ExecuteMsg::Claim {
funds,
claim_all,
to,
} => {
can_execute.check_admin()?;
let event_key = "execute_claim";
if let Some(claim_all_value) = claim_all {
if !claim_all_value {
return Err(StdError::generic_err(
"setting 'claim_all' to false causes an error: "
.to_string()
+ "try removing claim_all as an argument entirely.",
));
}
let contract_address = env_ctx.contract.address;
let balances = query_contract_balance(
contract_address.to_string(),
deps.as_ref(),
)?;

// Send all funds to the specified recipient.
let transfer_msg = BankMsg::Send {
to_address: to.clone(),
amount: balances.amount,
};
Ok(Response::new().add_message(transfer_msg).add_attribute(
event_key,
format!("successfully claimed to {}", to),
))
} else if let Some(funds_value) = funds {
// Send all funds to the specified recipient.
let transfer_msg = BankMsg::Send {
to_address: to.clone(),
amount: vec![funds_value],
};
return Ok(Response::new()
.add_message(transfer_msg)
.add_attribute(
event_key,
format!("successfully claimed to {}", to),
));
} else {
return Err(StdError::generic_err(
"either the 'funds' or 'claim_all' arguments must be specified"));
}
} // TODO test: add member
Copy link
Contributor

Choose a reason for hiding this comment

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

The ExecuteMsg::Claim variant in the execute function contains a condition that errors out if claim_all is set to false. This seems unnecessary as the claim_all field is a bool and should be able to handle both true and false values. Consider revising this logic to allow for both possibilities.

Comment on lines +271 to +278
fn check_can_execute(deps: Deps, sender: &str) -> StdResult<CanExecute> {
let sudoers = SUDOERS.load(deps.storage).unwrap();
Ok(CanExecute {
is_admin: sudoers.is_admin(sender),
is_member: sudoers.is_member(sender),
sender: sender.into(),
})
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The check_can_execute function unwraps the result of SUDOERS.load without handling the potential error. This could lead to a panic if the load fails. It's better to handle the error and return a ContractError if the load is unsuccessful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ci GitHub actions or other continuous integration changes epic Project or large task that groups multiple tickets and PRs type: bug/fix A pull request that fixes someting (pull) OR a ticket that highlights a bug (issue). type: enhancement New feature or request
Projects
None yet
1 participant