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(dpp): token distribution model #2447

Merged
merged 5 commits into from
Jan 27, 2025

Conversation

QuantumExplorer
Copy link
Member

@QuantumExplorer QuantumExplorer commented Jan 27, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added advanced token distribution capabilities with support for:
      • Perpetual distribution
      • Pre-programmed distribution
      • Flexible distribution rules
    • Enhanced token configuration management with more granular control over token minting and distribution
  • Improvements

    • Refactored token distribution logic to provide more structured and modular approach
    • Introduced new distribution function types for complex token emission strategies
    • Improved token configuration update validation
  • Technical Updates

    • Added new traits and methods for managing token distribution rules
    • Implemented serialization and deserialization support for new token distribution structures

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

Copy link
Contributor

coderabbitai bot commented Jan 27, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces a comprehensive overhaul of the token distribution system in the Dash Platform Protocol (DPP) Rust implementation. The changes focus on restructuring how token configurations, distributions, and rules are managed. A new TokenDistributionRules concept is introduced, replacing previous methods of handling token destination identities and minting rules. The modifications span multiple modules, adding support for perpetual and pre-programmed token distributions, and introducing more flexible and granular control over token-related operations.

Changes

File Path Change Summary
packages/rs-dpp/Cargo.toml Added ordered-float dependency with serde feature
packages/rs-dpp/src/data_contract/associated_token/mod.rs Added new modules for token distribution rules, perpetual distribution, and pre-programmed distribution
packages/rs-dpp/src/data_contract/associated_token/token_configuration/* Refactored token configuration accessors and methods to use new distribution_rules
packages/rs-dpp/src/lib.rs Added type aliases for EpochInterval, BlockHeightInterval, and TimestampMillisInterval
packages/rs-drive-abci/* Updated import statements and removed UnauthorizedTokenActionError in various token-related modules

Sequence Diagram

sequenceDiagram
    participant TokenConfig as Token Configuration
    participant DistributionRules as Distribution Rules
    participant MintTransition as Token Mint Transition

    TokenConfig->>DistributionRules: Get distribution rules
    DistributionRules-->>TokenConfig: Return rules
    MintTransition->>DistributionRules: Check new tokens destination
    DistributionRules-->>MintTransition: Provide destination identity
    MintTransition->>MintTransition: Validate and process token mint
Loading

Possibly related PRs

Poem

🐰 Tokens dance on rabbit's stage,
Distribution rules now turn the page,
Perpetual flows and programmed might,
Token logic shines so bright!
A new framework hops with glee 🌈


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@QuantumExplorer
Copy link
Member Author

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jan 27, 2025

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/mod.rs (1)

Line range hint 1-11800: Security considerations

The code has several important security features but could benefit from additional safeguards:

  1. Token Operations:

    • Verify all token operations have proper authorization checks
    • Add rate limiting for token operations
    • Consider adding emergency pause functionality
  2. Group Management:

    • Add timeouts for group operations
    • Implement quorum requirements for critical operations
    • Add member removal capabilities
  3. Configuration Updates:

    • Add delays for critical configuration changes
    • Implement multi-sig requirements for high-risk operations

Consider implementing these additional security measures to enhance the token distribution model's security.

🧹 Nitpick comments (27)
packages/rs-dpp/src/data_contract/associated_token/token_perpetual_distribution/distribution_function/mod.rs (1)

88-109: Exponential function usage is well explained.
No immediate issues, though in calling code, consider limiting large exponents to evade numeric overflow.

packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/mod.rs (5)

10205-10205: Fix line indentation

The line is incorrectly indented compared to surrounding code.

+        use dpp::data_contract::associated_token::token_distribution_rules::accessors::v0::TokenDistributionRulesV0Setters;

10978-10984: Simplify chained method calls

The code has multiple chained method calls that can be simplified for better readability.

- token_configuration
-     .distribution_rules_mut()
-     .set_minting_allow_choosing_destination(false);
- token_configuration
-     .distribution_rules_mut()
-     .set_new_tokens_destination_identity(Some(identity.id()));
+ let rules = token_configuration.distribution_rules_mut();
+ rules.set_minting_allow_choosing_destination(false);
+ rules.set_new_tokens_destination_identity(Some(identity.id()));

11081-11084: Simplify chained method calls

Similar to above, the chained method calls can be simplified.

- token_configuration
-     .distribution_rules_mut()
-     .set_minting_allow_choosing_destination(false);
- token_configuration
-     .distribution_rules_mut()
-     .set_new_tokens_destination_identity(Some(identity.id()));
+ let rules = token_configuration.distribution_rules_mut();
+ rules.set_minting_allow_choosing_destination(false);
+ rules.set_new_tokens_destination_identity(Some(identity.id()));

11181-11184: Simplify chained method calls

Similar to above, the chained method calls can be simplified.

- token_configuration
-     .distribution_rules_mut()
-     .set_minting_allow_choosing_destination(false);
- token_configuration
-     .distribution_rules_mut()
-     .set_new_tokens_destination_identity(Some(identity.id()));
+ let rules = token_configuration.distribution_rules_mut();
+ rules.set_minting_allow_choosing_destination(false);
+ rules.set_new_tokens_destination_identity(Some(identity.id()));

Line range hint 1-11800: Overall architecture feedback

The implementation demonstrates a robust token distribution model with several key strengths:

  1. Comprehensive test coverage for various token operations
  2. Strong validation of token operations
  3. Support for group-based authorization
  4. Proper handling of token freezing/unfreezing
  5. Well-implemented token configuration updates

However, there are some areas that could be improved:

  1. Error Handling:

    • Consider adding more specific error types for token operations
    • Add error context information for better debugging
  2. Documentation:

    • Add documentation for complex token operations
    • Document the group authorization model
  3. Code Organization:

    • Consider splitting large test modules into smaller files
    • Extract common test setup code into helper functions
packages/rs-dpp/src/data_contract/associated_token/token_distribution_rules/mod.rs (1)

18-26: Consider adding documentation for the Display implementation.

While the implementation is correct, adding documentation would help explain the formatting choices and make it clear that it delegates to the inner type's Display implementation.

+/// Implements Display for TokenDistributionRules by delegating to the inner type's
+/// Display implementation. This ensures consistent formatting across versions.
 impl fmt::Display for TokenDistributionRules {
packages/rs-dpp/src/data_contract/associated_token/token_perpetual_distribution/mod.rs (2)

10-15: LGTM! Consider adding documentation.

The enum is well-structured with proper versioning. Consider adding documentation to explain the purpose of TokenPerpetualDistribution and why it needs PartialOrd.

+/// Represents perpetual token distribution rules with versioning support.
+/// Implements PartialOrd to allow comparison of distribution configurations.
 #[derive(Serialize, Deserialize, Encode, Decode, Debug, Clone, PartialEq, Eq, PartialOrd, From)]

17-25: Consider creating a macro for versioned enum pattern.

This Display implementation is identical to TokenDistributionRules. Consider creating a macro to reduce boilerplate for versioned enums.

/// Example macro (to be placed in a common utility module):
macro_rules! impl_versioned_display {
    ($type:ident) => {
        impl fmt::Display for $type {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                match self {
                    Self::V0(v0) => write!(f, "{}", v0)
                }
            }
        }
    };
}

// Usage:
impl_versioned_display!(TokenPerpetualDistribution);
packages/rs-dpp/src/data_contract/associated_token/token_pre_programmed_distribution/v0/mod.rs (1)

10-14: Add documentation and consider performance implications.

The nested BTreeMap structure is well-chosen for ordered timestamps, but consider:

  1. Adding documentation to explain the structure and its performance characteristics
  2. For large datasets, consider implementing methods to efficiently batch process distributions
+/// Represents pre-programmed token distributions organized by timestamps.
+/// Uses BTreeMap for ordered access with O(log n) complexity.
+/// - Outer map: Timestamp -> Distribution map
+/// - Inner map: Identifier -> Token amount for each recipient
 #[derive(Serialize, Deserialize, Decode, Encode, Debug, Clone, PartialEq, Eq)]
 #[serde(rename_all = "camelCase")]
 pub struct TokenPreProgrammedDistributionV0 {
+    /// Nested map structure for timestamp-based token distributions.
+    /// Performance note: Operations have O(log n) complexity where n is the number of timestamps.
     pub distributions: BTreeMap<TimestampMillis, BTreeMap<Identifier, TokenAmount>>,
 }
packages/rs-dpp/src/lib.rs (1)

82-83: Add documentation for interval types.

While the type aliases are well-chosen, they would benefit from documentation explaining:

  1. The purpose and use case for each interval type
  2. Any constraints or valid value ranges
  3. The relationship between these intervals
+    /// Represents an interval in epochs. Valid values are non-zero positive integers.
     pub type EpochInterval = u16;

+    /// Represents an interval in block heights. Must be greater than zero.
     pub type BlockHeightInterval = u64;

+    /// Represents a time interval in milliseconds. Must be greater than zero.
     pub type TimestampMillisInterval = u64;

Also applies to: 86-87, 91-92

packages/rs-dpp/src/data_contract/associated_token/token_perpetual_distribution/v0/mod.rs (2)

11-27: Consider enhancing enum documentation with examples.

The enum variants are well-documented with basic descriptions. Consider adding examples for each variant to illustrate typical usage scenarios and parameter values.

 #[derive(Serialize, Deserialize, Decode, Encode, Debug, Clone, PartialEq, Eq, PartialOrd)]
 pub enum RewardDistributionType {
-    /// A fixed amount of tokens is emitted every n blocks
+    /// A fixed amount of tokens is emitted every n blocks
+    /// Example: BlockFixed(100, 1000) // Emit 1000 tokens every 100 blocks
     BlockFixed(BlockHeightInterval, TokenAmount),

38-70: Consider optimizing string formatting in Display implementation.

The current implementation creates intermediate String allocations for None cases. Consider using references to static strings to reduce allocations.

-                None => "None".to_string(),
+                None => "None",
packages/rs-dpp/src/data_contract/associated_token/token_distribution_rules/v0/mod.rs (1)

48-79: Consider optimizing string formatting in Display implementation.

Similar to the previous file, the implementation creates unnecessary String allocations for None cases.

-                None => "None".to_string(),
+                None => "None",
packages/rs-dpp/src/data_contract/change_control_rules/mod.rs (1)

130-138: Consider adding documentation for the Display implementation.

The Display implementation is correct but would benefit from documentation explaining the string format produced by the v0 implementation.

Apply this diff to add documentation:

+/// Implements Display for ChangeControlRules by delegating to the inner type's Display implementation.
+/// The string format follows the format defined by the v0 implementation.
 impl fmt::Display for ChangeControlRules {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self {
             ChangeControlRules::V0(v0) => {
                 write!(f, "{}", v0) //just pass through
             }
         }
     }
 }
packages/rs-dpp/src/data_contract/associated_token/token_distribution_rules/v0/accessors.rs (1)

1-114: LGTM! Consider adding examples to documentation.

The implementation is well-structured with clear separation of concerns between getters and setters. The code follows Rust best practices and provides comprehensive access to distribution rules.

Consider adding usage examples to the documentation for complex scenarios, such as:

// Example: Setting up perpetual distribution
let mut rules = TokenDistributionRulesV0::default();
rules.set_perpetual_distribution(Some(TokenPerpetualDistribution::new(...)));
rules.set_perpetual_distribution_rules(ChangeControlRules::new(...));
packages/rs-dpp/src/data_contract/change_control_rules/v0/mod.rs (1)

163-181: LGTM! Consider adding Display implementation tests.

The Display implementation is well-structured and properly formats all fields. The output format is clear and readable.

Consider adding tests to verify the Display implementation:

#[test]
fn test_change_control_rules_display() {
    let rules = ChangeControlRulesV0 {
        authorized_to_make_change: AuthorizedActionTakers::NoOne,
        admin_action_takers: AuthorizedActionTakers::NoOne,
        changing_authorized_action_takers_to_no_one_allowed: true,
        changing_admin_action_takers_to_no_one_allowed: false,
        self_changing_admin_action_takers_allowed: true,
    };
    let expected = "ChangeControlRulesV0 {\n  authorized_to_make_change: NoOne,\n  ...}";
    assert!(rules.to_string().starts_with(expected));
}
packages/rs-dpp/src/data_contract/associated_token/token_distribution_rules/accessors/mod.rs (1)

98-158: Consider adding validation in setters.

While the setter implementation is clean, consider adding validation logic to ensure the rules being set are consistent with the token's configuration.

For example, you could add validation in set_perpetual_distribution:

 fn set_perpetual_distribution(
     &mut self,
     perpetual_distribution: Option<TokenPerpetualDistribution>,
 ) {
+    // Validate the distribution configuration
+    if let Some(dist) = &perpetual_distribution {
+        // Add validation logic here
+    }
     match self {
         TokenDistributionRules::V0(v0) => v0.set_perpetual_distribution(perpetual_distribution),
     }
 }
packages/rs-dpp/src/data_contract/associated_token/token_configuration/accessors/mod.rs (1)

72-82: Good architectural decision to consolidate distribution rules.

The addition of distribution_rules and distribution_rules_mut methods provides a cleaner interface for managing token distribution configurations. This change improves modularity and maintainability.

Consider documenting the migration path for existing implementations that might be using the removed identity management methods.

packages/rs-dpp/src/data_contract/associated_token/token_configuration/v0/accessors.rs (2)

130-138: Thorough implementation of group position collection.

The code properly integrates distribution rules into the group position collection process. However, consider extracting the group position collection logic into a separate method for better maintainability.

Consider refactoring to:

 fn all_used_group_positions(&self) -> BTreeSet<GroupContractPosition> {
     let mut group_positions = BTreeSet::new();
+    self.collect_distribution_rule_positions(&mut group_positions);
+    // ... rest of the implementation
 }
+
+fn collect_distribution_rule_positions(&self, positions: &mut BTreeSet<GroupContractPosition>) {
+    add_from_change_control_rules(
+        self.distribution_rules.new_tokens_destination_identity_rules(),
+    );
+    add_from_change_control_rules(
+        self.distribution_rules.minting_allow_choosing_destination_rules(),
+    );
+    add_from_change_control_rules(self.distribution_rules.perpetual_distribution_rules());
+}

180-182: Consider adding debug assertions for distribution rules.

The setter for distribution rules could benefit from debug assertions to catch potential issues early in development.

 fn set_distribution_rules(&mut self, rules: TokenDistributionRules) {
+    debug_assert!(matches!(rules, TokenDistributionRules::V0(_)), 
+        "Attempting to set non-V0 distribution rules on V0 configuration");
     self.distribution_rules = rules;
 }
packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/mod.rs (1)

1306-1524: Well-structured test cases for token immutability.

The test suite comprehensively covers token immutability requirements:

  1. Preventing token removal
  2. Preventing token modification
  3. Proper error handling and validation

The tests are well-organized with clear setup, execution, and verification phases.

However, consider adding the following test cases for completeness:

  1. Attempting to modify multiple tokens simultaneously
  2. Edge cases with token positions (e.g., non-existent positions)
packages/rs-dpp/src/data_contract/associated_token/token_pre_programmed_distribution/mod.rs (1)

16-24: Consider enhancing the Display implementation.

While the current implementation is functional, consider adding version information to the display output for better debugging.

 impl fmt::Display for TokenPreProgrammedDistribution {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self {
             TokenPreProgrammedDistribution::V0(v0) => {
-                write!(f, "{}", v0) //just pass through
+                write!(f, "V0({})", v0)
             }
         }
     }
 }
packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_mint_transition_action/state_v0/mod.rs (4)

Line range hint 95-103: Improve error message specificity.

The error message for corrupted drive state could be more informative by including the context of the operation.

-                        "token {} total supply not found",
+                        "token {} total supply not found during mint validation",

Line range hint 61-91: Consider extracting supply validation logic.

The max supply validation logic is complex enough to warrant its own method. This would improve readability and make the code more maintainable.

impl TokenMintTransitionAction {
    fn validate_max_supply(
        &self,
        token_total_supply: u64,
        max_supply: u64,
    ) -> Result<SimpleConsensusValidationResult, Error> {
        match token_total_supply.checked_add(self.mint_amount()) {
            Some(total_supply_after_mint) if total_supply_after_mint <= max_supply => {
                Ok(SimpleConsensusValidationResult::new())
            }
            _ => Ok(SimpleConsensusValidationResult::new_with_error(
                ConsensusError::StateError(StateError::TokenMintPastMaxSupplyError(
                    TokenMintPastMaxSupplyError::new(
                        self.token_id(),
                        self.mint_amount(),
                        token_total_supply,
                        max_supply,
                    ),
                )),
            )),
        }
    }
}

Line range hint 106-132: Extract recipient validation to a helper function.

The recipient validation logic could be moved to a separate method to improve code organization and reusability.

impl TokenMintTransitionAction {
    fn validate_recipient(
        &self,
        platform: &PlatformStateRef,
        owner_id: Identifier,
        transaction: TransactionArg,
        execution_context: &mut StateTransitionExecutionContext,
        platform_version: &PlatformVersion,
    ) -> Result<SimpleConsensusValidationResult, Error> {
        let recipient = self.identity_balance_holder_id();
        if recipient == owner_id {
            return Ok(SimpleConsensusValidationResult::new());
        }

        let balance = platform.drive.fetch_identity_balance(
            recipient.to_buffer(),
            transaction,
            platform_version,
        )?;
        execution_context.add_operation(ValidationOperation::RetrieveIdentity(
            RetrieveIdentityInfo::only_balance(),
        ));

        match balance {
            Some(_) => Ok(SimpleConsensusValidationResult::new()),
            None => Ok(SimpleConsensusValidationResult::new_with_error(
                ConsensusError::StateError(StateError::RecipientIdentityDoesNotExistError(
                    RecipientIdentityDoesNotExistError::new(recipient),
                )),
            )),
        }
    }
}

Line range hint 32-145: Consider adding const assertions for numeric limits.

The implementation handles overflow checks well but could benefit from const assertions to validate numeric limits at compile time.

Add the following at the module level:

const _: () = assert!(std::u64::MAX > 1_000_000_000_000, "u64 must be large enough to handle token amounts");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e735313 and 39ffaba.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (40)
  • packages/rs-dpp/Cargo.toml (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration/accessors/mod.rs (3 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration/accessors/v0/mod.rs (3 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration/methods/apply_token_configuration_item/v0/mod.rs (2 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration/methods/authorized_action_takers_for_configuration_item/v0/mod.rs (2 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration/methods/can_apply_token_configuration_item/v0/mod.rs (5 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration/methods/validate_token_configuration_update/v0/mod.rs (4 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration/v0/accessors.rs (4 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration/v0/mod.rs (4 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration_item.rs (4 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_distribution_rules/accessors/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_distribution_rules/accessors/v0/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_distribution_rules/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_distribution_rules/v0/accessors.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_distribution_rules/v0/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_perpetual_distribution/distribution_function/encode.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_perpetual_distribution/distribution_function/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_perpetual_distribution/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_perpetual_distribution/v0/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_pre_programmed_distribution/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_pre_programmed_distribution/v0/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/change_control_rules/mod.rs (2 hunks)
  • packages/rs-dpp/src/data_contract/change_control_rules/v0/mod.rs (2 hunks)
  • packages/rs-dpp/src/lib.rs (1 hunks)
  • packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/batched_transition/token_mint_transition/v0/v0_methods.rs (2 hunks)
  • packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/batched_transition/token_transition.rs (2 hunks)
  • packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/v1/v0_methods.rs (0 hunks)
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_burn_transition_action/state_v0/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_destroy_frozen_funds_transition_action/state_v0/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_emergency_action_transition_action/state_v0/mod.rs (0 hunks)
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_freeze_transition_action/state_v0/mod.rs (0 hunks)
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_mint_transition_action/state_v0/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_unfreeze_transition_action/state_v0/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/mod.rs (7 hunks)
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/mod.rs (2 hunks)
  • packages/rs-drive-abci/tests/strategy_tests/token_tests.rs (3 hunks)
  • packages/rs-drive/src/drive/contract/insert/insert_contract/v1/mod.rs (2 hunks)
  • packages/rs-drive/src/drive/tokens/estimated_costs/for_token_balances/v0/mod.rs (0 hunks)
  • packages/rs-drive/src/state_transition_action/batch/batched_transition/token_transition/token_mint_transition_action/v0/transformer.rs (5 hunks)
💤 Files with no reviewable changes (4)
  • packages/rs-drive/src/drive/tokens/estimated_costs/for_token_balances/v0/mod.rs
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_freeze_transition_action/state_v0/mod.rs
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_emergency_action_transition_action/state_v0/mod.rs
  • packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/v1/v0_methods.rs
✅ Files skipped from review due to trivial changes (1)
  • packages/rs-dpp/src/data_contract/associated_token/mod.rs
🧰 Additional context used
📓 Learnings (1)
packages/rs-dpp/src/data_contract/associated_token/token_configuration/v0/mod.rs (1)
Learnt from: QuantumExplorer
PR: dashpay/platform#2432
File: packages/rs-dpp/src/data_contract/associated_token/token_configuration/v0/mod.rs:222-225
Timestamp: 2025-01-20T16:20:59.791Z
Learning: In the Dash Platform codebase, TokenAmount from crate::balances::credits is compatible with u64 when used for token base supply.
🔇 Additional comments (64)
packages/rs-dpp/src/data_contract/associated_token/token_configuration/methods/apply_token_configuration_item/v0/mod.rs (10)

3-5: Imports look consistent.
These imports seamlessly integrate TokenDistributionRulesV0Getters and TokenDistributionRulesV0Setters into the existing token configuration flows with no obvious issues.


42-43: No concerns with direct setter usage.
Calling set_new_tokens_destination_identity here is straightforward. Ensure that any specialized validation of the identity is done upstream if necessary.


48-49: Authorized action takers updated properly.
Using new_tokens_destination_identity_rules_mut() is consistent with the modular approach to distribution rules.


53-54: Admin action takers updated properly.
This closely mirrors patterns used in previous blocks.


58-59: Allow choosing destination is set correctly.
Again, no functional or style issues are evident.


64-65: Control group assignment is consistent.
Matches earlier patterns for control group modifications.


71-73: Admin group setters are consistent with design.
No issues.


75-78: Perpetual distribution inclusion is logically consistent.
Calling set_perpetual_distribution integrates well with the rest of the distribution rules.


79-83: Perpetual distribution control group matches pattern.
No concerns.


84-86: Perpetual distribution admin group also follows pattern.
Assigning admin action takers remains consistent and readable.

packages/rs-dpp/src/data_contract/associated_token/token_perpetual_distribution/distribution_function/mod.rs (8)

1-5: Imports and module structure are appropriate.
Using ordered_float::NotNan helps ensure safe handling of floating-point values for distribution logic.


8-28: Excellent documentation for LinearInteger.
The doc comments clearly explain usage, formula, and examples. This is highly maintainable.


29-49: Clear extension for LinearFloat.
Floating-point slope adds flexibility, and NotNan<f64> is a good safeguard.


50-70: PolynomialInteger variant is clearly documented.
Consider verifying input domain constraints for exponents (n >= 1) in calling code to avoid edge cases.


71-87: PolynomialFloat extends polynomial curves to fractional powers.
Be mindful of complex number edges if n < 0. Possibly enforce domain constraints at a higher layer.


110-130: Logarithmic function is functionally comprehensive.
Logs require positive x. Ensure domain checks in upstream logic.


131-143: Stepwise approach offers advanced schedule control.
The vector-based approach is flexible. Confirm step intervals align with block or epoch definitions.


145-196: Display implementation is thorough.
Formatting each variant fosters clearer logs and error messages. This is a clean and well-structured approach.

packages/rs-dpp/src/data_contract/associated_token/token_perpetual_distribution/distribution_function/encode.rs (4)

1-5: Imports are correct for serialization.
No concerns regarding re-exports or side-effects.


6-54: Encode trait implementation is consistent and thorough.
Assigning a variant index is straightforward, and using into_inner() for NotNan is suitably handled.


56-120: Decode trait implementation effectively guards against NaN.
Returning a decode error on invalid floats is essential for robust domain handling.


122-179: BorrowDecode trait supports efficient decoding.
Mirroring the Decode logic while preserving references is a nice optimization. This matches Rust best practices for reducing copies.

packages/rs-dpp/src/data_contract/associated_token/token_distribution_rules/mod.rs (1)

8-13: LGTM! Well-structured versioned enum.

The TokenDistributionRules enum is well-designed with proper versioning support through serde tags and follows semantic versioning conventions.

packages/rs-dpp/src/data_contract/associated_token/token_pre_programmed_distribution/v0/mod.rs (1)

17-28: LGTM! Well-formatted Display implementation.

The Display implementation provides clear, hierarchical formatting of the distribution data.

packages/rs-dpp/src/data_contract/associated_token/token_distribution_rules/accessors/v0/mod.rs (1)

6-73: Well-structured accessor traits with comprehensive documentation!

The traits provide a clean and well-documented interface for managing token distribution rules. The separation of getters and setters, consistent method naming, and appropriate use of mutability demonstrate good design practices.

packages/rs-dpp/src/data_contract/associated_token/token_distribution_rules/v0/mod.rs (1)

38-46: Verify if the default change control rules are too restrictive.

The default implementation sets all permissions to NoOne and disables all changes. This might be too restrictive for typical use cases and could lead to tokens being permanently locked down.

Consider if a more permissive default would be more appropriate, or if this is intentionally restrictive for security reasons.

packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/batched_transition/token_mint_transition/v0/v0_methods.rs (1)

85-91: Clean integration with the new token distribution rules!

The changes effectively integrate the new distribution rules architecture while maintaining proper error handling and type safety.

packages/rs-dpp/src/data_contract/associated_token/token_configuration/accessors/v0/mod.rs (3)

3-3: LGTM! Import added for new TokenDistributionRules type.

The import aligns with the new distribution rules functionality being introduced.


31-35: LGTM! New getter methods for distribution rules.

The addition of both immutable and mutable accessors for distribution rules follows Rust's best practices for encapsulation.


80-81: LGTM! Setter method for distribution rules.

The setter method complements the getter methods, providing a complete interface for managing distribution rules.

packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_unfreeze_transition_action/state_v0/mod.rs (1)

4-4: Verify error handling after UnauthorizedTokenActionError removal.

The removal of UnauthorizedTokenActionError import suggests a change in error handling strategy. Please ensure that unauthorized actions are still properly handled, possibly through a different mechanism.

packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_burn_transition_action/state_v0/mod.rs (1)

4-4: Verify error handling consistency across token actions.

The removal of UnauthorizedTokenActionError import aligns with the changes in token_unfreeze_transition_action. Please ensure that error handling is consistent across all token actions.

✅ Verification successful

Error handling is consistent across token actions

The removal of UnauthorizedTokenActionError import aligns with the codebase's error handling patterns. The verification shows consistent error handling across all token actions, including token burn and unfreeze transitions, with proper use of ConsensusError::StateError wrapper and standardized error types.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for error handling patterns in token action files
fd -e rs "token.*transition_action" -x rg -A 5 "ConsensusError::StateError"

# Search for validation patterns in token action files
fd -e rs "token.*transition_action" -x ast-grep --pattern 'validate_group_action($$$)'

Length of output: 164


Script:

#!/bin/bash
# Search for error-related imports in token action files
fd "token.*transition_action.*\.rs$" -x rg -l "use.*Error"

# Search for specific error patterns in token files
fd "token.*transition_action.*\.rs$" -x rg -B 2 -A 2 "Error::"

# Search for validate methods and their implementations
ast-grep --pattern 'fn validate($$$) -> Result<$$$> {
  $$$
}'

Length of output: 8825


Script:

#!/bin/bash
# Search for token-related error types and their usage
fd -e rs -p ".*token.*transition_action.*" packages/rs-drive-abci/src/execution/validation/state_transition -x rg -l "Error"

# Search for specific error handling in token action files
fd -e rs -p ".*token.*transition_action.*" packages/rs-drive-abci/src/execution/validation/state_transition -x rg -B 2 -A 2 "IdentityDoesNotHaveEnoughTokenBalanceError|UnauthorizedTokenActionError"

# Look for validation methods in token action files
fd -e rs -p ".*token.*transition_action.*" packages/rs-drive-abci/src/execution/validation/state_transition -x ast-grep --pattern 'fn validate($$$) -> Result<$$$, $$$> {
  $$$
}'

Length of output: 8972

packages/rs-dpp/src/data_contract/change_control_rules/mod.rs (1)

14-14: LGTM! Import added for Display trait implementation.

The import is required for implementing the Display trait.

packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_destroy_frozen_funds_transition_action/state_v0/mod.rs (1)

4-4: LGTM! Verify error handling after UnauthorizedTokenActionError removal.

The removal of UnauthorizedTokenActionError aligns with the shift to token distribution rules for authorization. The remaining error handling through IdentityTokenAccountNotFrozenError is sufficient.

Let's verify that UnauthorizedTokenActionError is not used elsewhere in the codebase:

✅ Verification successful

Verified: UnauthorizedTokenActionError removal is correct for frozen funds destruction

The error removal is specific to frozen funds destruction validation, where authorization is now handled through token distribution rules. The error remains in use for other token-related validations where needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of UnauthorizedTokenActionError
rg "UnauthorizedTokenActionError"

Length of output: 6535

packages/rs-dpp/src/data_contract/associated_token/token_configuration/methods/authorized_action_takers_for_configuration_item/v0/mod.rs (2)

25-27: Consistent shift to admin_action_takers for authorization.

The change from authorized_to_make_change_action_takers() to admin_action_takers() across multiple configuration items improves consistency in authorization handling.

Also applies to: 35-37, 86-88, 92-94, 98-100, 104-106, 118-120


41-55: Well-integrated perpetual distribution authorization.

The new cases for perpetual distribution properly integrate with the existing authorization framework, maintaining consistency with other configuration items.

packages/rs-dpp/src/data_contract/associated_token/token_distribution_rules/accessors/mod.rs (1)

12-96: Well-structured implementation of TokenDistributionRulesV0Getters.

The implementation provides a comprehensive and well-documented API for accessing token distribution rules. The pattern matching ensures type safety and proper handling of the V0 variant.

packages/rs-drive/src/drive/contract/insert/insert_contract/v1/mod.rs (1)

223-225: LGTM!

The code correctly retrieves the destination identity from the distribution rules, with a sensible fallback to the contract owner ID.

packages/rs-dpp/src/data_contract/associated_token/token_configuration_item.rs (3)

40-42: LGTM!

The new variants follow a consistent pattern and use appropriate types for managing perpetual distribution configuration.


73-94: LGTM!

The indices are correctly assigned and maintain sequential ordering after adding the new variants.


124-134: LGTM!

The Display implementation for the new variants is consistent with the existing pattern.

packages/rs-dpp/src/data_contract/associated_token/token_configuration/v0/mod.rs (4)

6-7: LGTM!

The imports are correctly versioned and follow the module hierarchy.


38-39: LGTM!

The new field is well-documented and uses the appropriate type for managing token distribution rules.


92-100: LGTM!

The Display implementation correctly includes the new field with consistent formatting.


140-169: LGTM!

The initialization follows the "most restrictive" pattern consistently, with appropriate default values for all sub-fields.

packages/rs-dpp/src/data_contract/associated_token/token_configuration/methods/can_apply_token_configuration_item/v0/mod.rs (3)

79-104: LGTM!

The permission checks for perpetual distribution changes follow the established pattern and correctly access the rules through the distribution_rules field.


106-107: LGTM!

The access path for new tokens destination identity rules is consistently updated to use the distribution_rules field.

Also applies to: 112-113, 123-124


135-136: LGTM!

The access path for minting allow choosing destination rules is consistently updated to use the distribution_rules field.

Also applies to: 141-142, 154-155

packages/rs-drive-abci/tests/strategy_tests/token_tests.rs (2)

8-11: LGTM: Import changes align with the new token distribution model.

The imports have been updated to include both TokenConfigurationV0Getters and TokenConfigurationV0Setters, along with the new TokenDistributionRulesV0Setters. This reflects the architectural change of moving token distribution logic into a dedicated module.


76-78: LGTM: Token configuration updates follow the new distribution rules pattern.

The token configuration is now accessed through the distribution rules, which is consistent with the architectural changes. The same pattern is correctly applied in both test functions.

Also applies to: 226-228

packages/rs-dpp/src/data_contract/associated_token/token_configuration/methods/validate_token_configuration_update/v0/mod.rs (3)

4-4: LGTM: New import for distribution rules accessors.

The addition of TokenDistributionRulesV0Getters import aligns with the architectural changes.


87-108: LGTM: Distribution rules validation follows consistent patterns.

The validation logic for new_tokens_destination_identity and minting_allow_choosing_destination has been updated to use the distribution rules accessors while maintaining the same validation patterns and error handling.

Also applies to: 123-144


158-186: LGTM: New perpetual distribution validation added.

The new validation for perpetual distribution follows the same pattern as other validations, maintaining consistency in error handling and validation logic.

packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/batched_transition/token_transition.rs (2)

Line range hint 8-11: LGTM: Import changes align with the new token distribution model.

The addition of TokenDistributionRulesV0Getters import is consistent with the architectural changes.


348-348: LGTM: Token configuration access updated to use distribution rules.

The access to new_tokens_destination_identity has been updated to use the distribution rules accessors while maintaining the same error handling and message.

packages/rs-drive/src/state_transition_action/batch/batched_transition/token_transition/token_mint_transition_action/v0/transformer.rs (2)

15-15: LGTM: Import changes align with the new token distribution model.

The addition of TokenDistributionRulesV0Getters import is consistent with the architectural changes.


121-122: LGTM: Token configuration access consistently updated across both methods.

The access to token configuration has been updated to use distribution rules accessors in both methods while maintaining the same validation and error handling logic.

Also applies to: 153-156, 298-299, 330-333

packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/mod.rs (1)

1180-1183: LGTM! Clean import organization.

The new imports are well-organized and specifically scoped for token-related functionality.

packages/rs-dpp/src/data_contract/associated_token/token_pre_programmed_distribution/mod.rs (2)

1-8: LGTM! Well-organized imports and module structure.

The imports are clean and the module organization follows Rust conventions.


9-14: Well-implemented versioned enum with proper derive macros.

The TokenPreProgrammedDistribution enum is well-designed with:

  • Proper serialization/deserialization support
  • Version tagging for forward compatibility
  • Clean derive implementations
packages/rs-dpp/Cargo.toml (1)

17-17: Verify the ordered-float version compatibility.

The addition of ordered-float with serde support is appropriate. However, please verify that version 4.6.0 is compatible with the rest of the ecosystem.

✅ Verification successful

ordered-float v4.6.0 is properly integrated and compatible

The dependency is well-integrated within the rs-dpp package, using the NotNan type appropriately for mathematical operations in distribution functions. The serde feature is correctly utilized for serialization, and there are no compatibility issues with other dependencies.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential compatibility issues with ordered-float
cargo tree --package ordered-float
cargo tree --package serde | grep ordered-float

Length of output: 278


Script:

#!/bin/bash
# Search for ordered-float in all Cargo.toml files
echo "=== Checking ordered-float in Cargo.toml files ==="
rg "ordered-float.*=" -A 2 -B 2 "Cargo.toml$"

echo -e "\n=== Checking ordered-float usage in Rust files ==="
rg "ordered_float::" -A 2 -B 2 "\.rs$"

echo -e "\n=== Checking specific ordered-float types usage ==="
rg "NotNan|OrderedFloat" "\.rs$"

Length of output: 612


Script:

#!/bin/bash
# Find and examine all Cargo.toml files in the packages directory
echo "=== Checking ordered-float in Cargo.toml files ==="
fd Cargo.toml packages/ -x cat {} | grep -A 2 -B 2 "ordered-float"

echo -e "\n=== Checking Rust files for ordered-float usage ==="
fd .rs$ packages/ -x rg -l "use.*ordered_float|NotNan|OrderedFloat" {}

Length of output: 755


Script:

#!/bin/bash
echo "=== Checking ordered-float usage patterns ==="
rg -A 3 -B 3 "ordered_float|NotNan|OrderedFloat" packages/rs-dpp/src/data_contract/associated_token/token_perpetual_distribution/distribution_function/

Length of output: 19030

packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_mint_transition_action/state_v0/mod.rs (3)

Line range hint 22-31: LGTM! Well-structured trait definition.

The trait is well-defined with appropriate visibility modifiers and follows Rust naming conventions.


Line range hint 32-145: Overall implementation is robust and secure.

The token minting validation implementation is thorough, covering all necessary checks including authorization, supply limits, and recipient validation. The code uses safe arithmetic operations and proper error handling. While functional, it could benefit from the suggested refactoring to improve maintainability.


5-5: Verify the removal of UnauthorizedTokenActionError.

The removal of UnauthorizedTokenActionError import suggests a change in error handling for unauthorized actions. Let's verify that authorization errors are properly handled elsewhere.

✅ Verification successful

Verified: UnauthorizedTokenActionError import removal is safe

The authorization checks are properly handled through the base class's validate_group_action() method, which is called via self.base().validate_group_action(). The removal of this import is part of a clean refactoring that centralizes authorization handling in the base implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for UnauthorizedTokenActionError usage and its potential replacement
echo "Searching for UnauthorizedTokenActionError usage:"
rg "UnauthorizedTokenActionError" -A 5

echo -e "\nSearching for potential new authorization error types:"
ast-grep --pattern 'struct $name:ident {
  $$$
}' | rg -A 5 ".*Error.*Token.*Auth|.*Token.*Auth.*Error"

Length of output: 22772


Script:

#!/bin/bash
# Check if mint operations are validated through the base class
echo "Checking token mint validation inheritance:"
ast-grep --pattern 'impl $_ for TokenMintTransitionActionStateV0 {
  $$$
}'

echo -e "\nChecking base class validation usage:"
rg -A 5 "validate_authorization|check_authorization" packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_mint_transition_action/state_v0/

Length of output: 472


Script:

#!/bin/bash
# Get the complete content of the mint transition action file
echo "Checking mint transition action implementation:"
cat packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/token_mint_transition_action/state_v0/mod.rs

echo -e "\nChecking for trait implementations:"
rg -B 2 -A 5 "trait.*TokenMintTransitionAction|trait.*TokenBaseTransitionAction" packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/token/

Length of output: 16762

@QuantumExplorer QuantumExplorer merged commit 6d5af88 into v2.0-tokens-dev Jan 27, 2025
3 checks passed
@QuantumExplorer QuantumExplorer deleted the feat/token_distribution branch January 27, 2025 09:59
@thephez thephez added this to the v2.0.0 milestone Jan 28, 2025
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