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: validate token name localizations #2468

Open
wants to merge 4 commits into
base: v2.0-dev
Choose a base branch
from

Conversation

shumkov
Copy link
Member

@shumkov shumkov commented Feb 18, 2025

Issue being fixed or feature implemented

Currently, you can create a token without name. Also, there is no standard locatization defined.

What was done?

  • Ensure that default (en) localization is present

How Has This Been Tested?

Updated existing tests

Breaking Changes

It's a breaking change for the v2.0-dev branch

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

Summary by CodeRabbit

  • New Features

    • Enhanced token localization with support for singular and plural forms based on language preferences, including a reliable fallback to English.
    • Added new error handling for missing default localization scenarios.
  • Chores

    • Introduced robust validation to ensure required default localization is present.
    • Reorganized internal components to streamline localization access and improve error reporting.
    • Added localization details in the token definition JSON for improved clarity and structure.

Copy link
Contributor

coderabbitai bot commented Feb 18, 2025

Walkthrough

This change introduces localization support and validation for token configurations in the data contract module. A new accessor module (with a v0 submodule) and methods to retrieve singular and plural localized token names are added. Validation methods have been implemented to check that the English localization exists. Additionally, corresponding error types to represent a missing default localization have been introduced and integrated into the overall error handling flow. The platform version information is updated with a new field to account for localization validation in both state transitions and consensus error processing.

Changes

Files Change Summary
packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/accessors/{mod.rs, v0/mod.rs} Added new module v0 and implemented the TokenConfigurationConventionV0Getters trait with methods for retrieving singular and plural token names based on language codes.
packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/methods/{mod.rs, validate_localizations/mod.rs, validate_localizations/v0/mod.rs} Introduced a new module for localization validation; added methods validate_localizations (delegating to validate_localizations_v0 for version 0) and validate_localizations_v0 to check for an English localization.
packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/{mod.rs, v0/mod.rs} Updated main token configuration modules to include new modules, constants (ENGLISH_ISO_639), structure fields, and trait implementations for localization support.
packages/rs-dpp/src/errors/consensus/basic/{basic_error.rs, token/missing_default_localization.rs, token/mod.rs} Added a new error variant and error struct (MissingDefaultLocalizationError) to handle missing English localization errors.
packages/wasm-dpp/src/errors/consensus/consensus_error.rs Integrated the new MissingDefaultLocalizationError into the WebAssembly error mapping.
packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_create/advanced_structure/v0/mod.rs Added validation logic to check token configuration localizations during data contract creation state transition.
packages/rs-platform-version/src/version/dpp_versions/dpp_validation_versions/{mod.rs, v1.rs, v2.rs} Added a new field validate_localizations to the data contract validation versions, initializing it in version constants.

Possibly related PRs

  • test: fix token history contract tests #2470 – The changes in the main PR are related to the implementation of the TokenConfigurationConventionV0Getters trait and its methods, which are also defined in the retrieved PR's context, indicating a focus on localization functionality.
  • feat(platform)!: enhance token configuration and validation mechanisms #2439 – The changes in the main PR are related to the implementation of the TokenConfigurationConventionV0Getters trait, which includes methods that directly interact with the TokenConfigurationConvention struct, while the retrieved PR modifies the max_supply method within the same trait for the TokenConfiguration struct, indicating a direct connection at the code level.
  • feat: integrate wallet contract #2345 – The changes in the main PR are related to the retrieved PR as both involve the implementation of methods for handling token configurations and localizations, specifically through the TokenConfigurationConventionV0Getters trait and its methods.

Suggested reviewers

  • QuantumExplorer
  • lklimek

Poem

I'm a bunny on the run,
Hopping through code in the light of fun.
New localizations, validations galore,
Ensuring tokens speak in languages and more!
Carrots and code, a whimsical blend,
Celebrating changes from start to end.
Hop on, coder—let's have a brilliant trend!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 47ceb41 and 3596620.

📒 Files selected for processing (1)
  • packages/rs-drive-abci/tests/supporting_files/contract/basic-token/basic-token.json (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (14)
  • GitHub Check: Rust packages (drive) / Linting
  • GitHub Check: Rust packages (drive) / Formatting
  • GitHub Check: Rust packages (dpp) / Tests
  • GitHub Check: Rust packages (dpp) / Check each feature
  • GitHub Check: Rust packages (dpp) / Linting
  • GitHub Check: Rust packages (dash-sdk) / Unused dependencies
  • GitHub Check: Rust packages (dash-sdk) / Tests
  • GitHub Check: Rust packages (dash-sdk) / Check each feature
  • GitHub Check: Rust packages (dash-sdk) / Linting
  • GitHub Check: Rust packages (dapi-grpc) / Tests
  • GitHub Check: Rust packages (dapi-grpc) / Check each feature
  • GitHub Check: Rust packages (dapi-grpc) / Unused dependencies
  • GitHub Check: Rust packages (dapi-grpc) / Linting
  • GitHub Check: Build JS packages / Build JS
🔇 Additional comments (2)
packages/rs-drive-abci/tests/supporting_files/contract/basic-token/basic-token.json (2)

12-18: Proper Addition of Default Localization Data

The new "localizations" object is correctly added under the "conventions" section. The inclusion of the default English ("en") localization with the specified properties ("shouldCapitalize": false, "pluralForm": "tests", and "singularForm": "test") meets the PR objective of ensuring that every token has a valid default localization.


26-27: Ensuring Proper File Formatting

The addition of the trailing newline at the end of the file improves consistency and adheres to POSIX standards for file formatting.


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.

@shumkov shumkov self-assigned this Feb 18, 2025
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

🧹 Nitpick comments (4)
packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/accessors/v0/mod.rs (1)

1-7: LGTM! Consider enhancing the documentation.

The trait is well-designed with clear method signatures and consistent naming patterns. The methods appropriately handle both singular and plural forms with default language fallback.

Consider adding documentation to clarify:

  • What is the default language code?
  • What happens when the requested language code is not found?
 /// Accessor trait for getters of `TokenConfigurationConventionV0`
 pub trait TokenConfigurationConventionV0Getters {
-    /// Returns the localized token name in singular form
+    /// Returns the localized token name in singular form.
+    /// If the requested language code is not found, falls back to English ('en').
     fn singular_form_by_language_code_or_default(&self, language_code: &str) -> &str;
-    /// Returns the localized token name in plural form
+    /// Returns the localized token name in plural form.
+    /// If the requested language code is not found, falls back to English ('en').
     fn plural_form_by_language_code_or_default(&self, language_code: &str) -> &str;
 }
packages/rs-dpp/src/errors/consensus/basic/token/missing_default_localization.rs (1)

1-24: LGTM! Consider adding documentation.

The error type is well-designed with appropriate trait implementations and clear error message.

Consider adding documentation to explain the error's purpose and when it's raised:

+/// Error raised when a token configuration is missing the required English ('en') localization.
+/// This error occurs during validation of token configurations to ensure that a default localization
+/// is always available.
 #[derive(
     Error, Debug, Clone, PartialEq, Eq, Encode, Decode, PlatformSerialize, PlatformDeserialize,
 )]
 #[error("Missing english ('en') localization which is using by default")]
 #[platform_serialize(unversioned)]
 pub struct MissingDefaultLocalizationError {}
packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/methods/validate_localizations/mod.rs (1)

9-26: LGTM! Consider adding documentation.

The method is well-structured with proper version handling and error management.

Consider adding documentation to explain the method's purpose and return values:

+    /// Validates the localizations of a token configuration based on the platform version.
+    ///
+    /// # Arguments
+    /// * `platform_version` - The platform version to determine which validation rules to apply
+    ///
+    /// # Returns
+    /// * `Ok(SimpleConsensusValidationResult)` - The validation result
+    /// * `Err(ProtocolError)` - If the platform version is not supported
     pub fn validate_localizations(
         &self,
         platform_version: &PlatformVersion,
     ) -> Result<SimpleConsensusValidationResult, ProtocolError> {
packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/methods/validate_localizations/v0/mod.rs (1)

5-22: Consider enhancing the error message.

The implementation correctly validates the presence of English localization. However, consider adding a more descriptive error message to help users understand why English localization is required.

-                MissingDefaultLocalizationError::new().into(),
+                MissingDefaultLocalizationError::new()
+                    .with_message("English (en) localization is required as the default language")
+                    .into(),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ddf4e67 and ed471fb.

📒 Files selected for processing (15)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/accessors/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/accessors/v0/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/methods/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/methods/validate_localizations/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/methods/validate_localizations/v0/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/v0/mod.rs (3 hunks)
  • packages/rs-dpp/src/errors/consensus/basic/basic_error.rs (2 hunks)
  • packages/rs-dpp/src/errors/consensus/basic/token/missing_default_localization.rs (1 hunks)
  • packages/rs-dpp/src/errors/consensus/basic/token/mod.rs (2 hunks)
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_create/advanced_structure/v0/mod.rs (1 hunks)
  • packages/rs-platform-version/src/version/dpp_versions/dpp_validation_versions/mod.rs (1 hunks)
  • packages/rs-platform-version/src/version/dpp_versions/dpp_validation_versions/v1.rs (1 hunks)
  • packages/rs-platform-version/src/version/dpp_versions/dpp_validation_versions/v2.rs (1 hunks)
  • packages/wasm-dpp/src/errors/consensus/consensus_error.rs (2 hunks)
✅ Files skipped from review due to trivial changes (2)
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/methods/mod.rs
  • packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/mod.rs
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Build Docker images (Drive, drive, drive-abci) / Build Drive image
  • GitHub Check: Build Docker images (DAPI, dapi, dapi) / Build DAPI image
  • GitHub Check: Build JS packages / Build JS
  • GitHub Check: Rust crates security audit
🔇 Additional comments (13)
packages/rs-dpp/src/errors/consensus/basic/token/mod.rs (1)

7-7: LGTM!

The new module and its public export are correctly added in alphabetical order, maintaining the file's organization.

Also applies to: 16-16

packages/rs-dpp/src/data_contract/associated_token/token_configuration_convention/methods/validate_localizations/v0/mod.rs (1)

1-4: LGTM!

The imports are correctly organized and include all necessary dependencies.

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

1-8: LGTM!

The module structure and imports are well-organized, with clear separation of concerns.


9-25:

❓ Verification inconclusive

Consider handling potential panic cases.

The implementation correctly delegates to v0 methods, but consider handling cases where the requested language code doesn't exist to prevent potential panics.

Could you provide the implementation of singular_form_by_language_code_or_default and plural_form_by_language_code_or_default from the v0 module to ensure they handle missing language codes gracefully?


🏁 Script executed:

#!/bin/bash
# Description: Check implementation of getter methods in v0 module
ast-grep --pattern $'impl TokenConfigurationConventionV0 {
  $$$
  fn singular_form_by_language_code_or_default($$$) {
    $$$
  }
  $$$
  fn plural_form_by_language_code_or_default($$$) {
    $$$
  }
  $$$
}'

Length of output: 210


Manual Verification Required for v0 Getter Implementations

The current delegation in the TokenConfigurationConventionV0Getters implementation passes calls directly to the v0 methods without any additional safeguard. However, we couldn’t confirm from an automated search whether the underlying implementations of singular_form_by_language_code_or_default and plural_form_by_language_code_or_default in the v0 module handle cases of missing language codes gracefully.

Please manually verify that in the v0 module:

  • When an unknown language_code is provided, the implementations either return a proper default value without panicking or have explicit error handling.
  • If no such handling exists, consider refactoring these methods to ensure they do not trigger panics when the requested language code is missing.
packages/rs-platform-version/src/version/dpp_versions/dpp_validation_versions/v2.rs (1)

22-22: LGTM!

The addition of validate_localizations field with initial version 0 is consistent across v1 and v2, correctly reflecting the introduction of localization validation as a breaking change.

packages/rs-platform-version/src/version/dpp_versions/dpp_validation_versions/v1.rs (1)

22-22: LGTM!

The addition of validate_localizations field with initial version 0 is consistent across v1 and v2, correctly reflecting the introduction of localization validation as a breaking change.

packages/rs-platform-version/src/version/dpp_versions/dpp_validation_versions/mod.rs (1)

24-24: LGTM!

The new field validate_localizations is correctly added to the DataContractValidationVersions struct, following the same pattern as other validation fields.

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

26-26: LGTM!

The constant ENGLISH_ISO_639 is well-named and uses the standard ISO 639 language code.


33-36: LGTM!

The localizations field is well-designed with:

  • Ordered storage using BTreeMap
  • Clear documentation specifying ISO 639 2-chars language code requirement
  • Default attribute for serde

63-77: LGTM!

The implementation of TokenConfigurationConventionV0Getters is efficient and idiomatic:

  • Uses references to avoid unnecessary cloning
  • Properly handles missing language codes by defaulting to English
  • Uses map and unwrap_or_else for clean error handling
packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_create/advanced_structure/v0/mod.rs (1)

121-133: LGTM!

The localization validation is well-integrated:

  • Follows the existing pattern of validation checks
  • Properly handles validation errors through ConsensusValidationResult
  • Correctly integrates with the bump identity nonce action
packages/rs-dpp/src/errors/consensus/basic/basic_error.rs (1)

473-474: LGTM!

The MissingDefaultLocalizationError variant is well-integrated:

  • Follows the existing pattern of error variants
  • Uses transparent error propagation
  • Is placed at a logical position in the enum
packages/wasm-dpp/src/errors/consensus/consensus_error.rs (1)

69-69: LGTM! Error handling for token localization validation is properly implemented.

The addition of MissingDefaultLocalizationError is well-integrated into the error handling system and aligns with the PR's objective to enforce token name localization requirements. The implementation follows the established error handling patterns and is correctly placed within the token-related error section.

Also applies to: 693-695

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: In review / testing
Development

Successfully merging this pull request may close these issues.

1 participant