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(wasm-dpp): add extra methods for state transitions #2401

Open
wants to merge 21 commits into
base: v1.8-dev
Choose a base branch
from

Conversation

pshenmic
Copy link
Collaborator

@pshenmic pshenmic commented Dec 18, 2024

Issue being fixed or feature implemented

WASM bindings were missing some methods for data in the state transitions, such like identityContractNonce, userFeeIncrease, signaturePublicKeyId, prefundingVotingBalance, vote choice and such, that we use to show on the Platform Explorer (specific transaction page). We did that in the our own fork for now (which is already live in production), and with this PR I'm merging changes in the main platform dev branch.

What was done?

  • Added missing document transition action types (purchase, updatePrice)
  • Added userFeeIncrease, signature and signaturePublicKeyId in the data contract's state transitions
  • Added prefundingVotingBalance and userFeeIncrease in the documents batch
  • Added nonce, userFeeIncrease, and signaturePublicKeyId in the Identity's state transitions
  • Added userFeeIncrease, identityContractNonce and vote choice in the masternode vote state transitions

How Has This Been Tested?

In the integration with Platform Explorer

Breaking Changes

No

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

Summary by CodeRabbit

  • New Features

    • Added new enum variants Purchase and UpdatePrice for document transitions.
    • Introduced methods for managing user fee increases and identity contract nonces across various transition types.
    • Enhanced document transition functionality with methods for retrieving and setting identity contract nonce and prefunded voting balance.
    • Added methods for retrieving signature public key IDs across multiple transition types.
    • Improved functionality for MasternodeVoteTransition with new methods and updated response structures.
    • Introduced methods for retrieving entropy from various document transitions.
    • Updated DocumentTransitionV0Methods trait to include entropy retrieval.
  • Bug Fixes

    • Improved error handling for unknown action types in document transitions.
  • Documentation

    • Updated method signatures for clarity and consistency across the codebase.

@pshenmic pshenmic added the js-sdk JS Dash SDK related label Dec 18, 2024
@pshenmic pshenmic self-assigned this Dec 18, 2024
Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

Walkthrough

This pull request introduces a comprehensive set of enhancements across multiple Rust and WebAssembly files, focusing on expanding the functionality of various state transition structs. The changes primarily involve adding new methods for managing user fee increases, identity contract nonces, and signature-related operations across different transition types in the Dash Platform Protocol (DPP) implementation. Additionally, new variants for the DocumentTransitionActionType enum are introduced.

Changes

File Path Change Summary
packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/action_type.rs Added Purchase and UpdatePrice variants to DocumentTransitionActionType enum
packages/wasm-dpp/src/data_contract/state_transition/data_contract_create_transition/mod.rs Added methods for user fee increase and signature handling in DataContractCreateTransitionWasm
packages/wasm-dpp/src/data_contract/state_transition/data_contract_update_transition/mod.rs Added methods for user fee increase and signature handling in DataContractUpdateTransitionWasm
packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_create_transition.rs Added methods for identity contract nonce and prefunded voting balance in DocumentCreateTransitionWasm
packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_delete_transition.rs Added methods for identity contract nonce in DocumentDeleteTransitionWasm
packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_replace_transition.rs Added methods for identity contract nonce in DocumentReplaceTransitionWasm
packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs Added methods for document data retrieval and prefunded voting balance in DocumentTransitionWasm
packages/wasm-dpp/src/document/state_transition/document_batch_transition/mod.rs Added methods for user fee increase in DocumentsBatchTransitionWasm
packages/wasm-dpp/src/identity/state_transition/identity_create_transition/identity_create_transition.rs Added methods for user fee increase in IdentityCreateTransitionWasm
packages/wasm-dpp/src/identity/state_transition/identity_credit_transfer_transition/transition.rs Added methods for user fee increase and identity nonce in IdentityCreditTransferTransitionWasm
packages/wasm-dpp/src/identity/state_transition/identity_credit_withdrawal_transition/transition.rs Added methods for user fee increase and identity nonce in IdentityCreditWithdrawalTransitionWasm
packages/wasm-dpp/src/identity/state_transition/identity_topup_transition/identity_topup_transition.rs Added methods for user fee increase in IdentityTopUpTransitionWasm
packages/wasm-dpp/src/identity/state_transition/identity_update_transition/identity_update_transition.rs Added methods for user fee increase and identity nonce in IdentityUpdateTransitionWasm
packages/wasm-dpp/src/voting/state_transition/masternode_vote_transition/mod.rs Added methods for user fee increase and identity nonce, modified contested_document_resource_vote_poll method in MasternodeVoteTransitionWasm
packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/mod.rs Updated DocumentTransitionV0Methods trait by removing get_document_type and adding entropy method

Suggested Labels

enhancement

Suggested Reviewers

  • QuantumExplorer
  • shumkov
  • lklimek

Poem

🐰 Hop, hop, through the code we go,
Transitions dancing, methods in a row
User fees rise, nonces take flight
WebAssembly bindings shining bright!
A rabbit's dance of protocol delight 🌟


📜 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 e21ae53 and 2c94941.

📒 Files selected for processing (1)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs

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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
packages/wasm-dpp/src/identity/state_transition/identity_credit_withdrawal_transition/transition.rs (1)

149-157: Consider renaming methods for consistency.

The getter and setter methods have inconsistent naming:

  • Getter: get_identity_nonce
  • Setter: set_identity_contract_nonce

Consider using consistent naming:

-    pub fn get_identity_nonce(&self) -> u64 {
+    pub fn get_identity_contract_nonce(&self) -> u64 {
packages/wasm-dpp/src/identity/state_transition/identity_topup_transition/identity_topup_transition.rs (1)

118-126: Consider adding documentation for the user fee methods

While the implementation is correct and consistent with other transition types, consider adding documentation to explain:

  • The purpose of user fee increases
  • Valid range for the fee increase value
  • Impact on transaction processing
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 37d5732 and 5901158.

📒 Files selected for processing (14)
  • packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs (1 hunks)
  • packages/wasm-dpp/src/data_contract/state_transition/data_contract_create_transition/mod.rs (1 hunks)
  • packages/wasm-dpp/src/data_contract/state_transition/data_contract_update_transition/mod.rs (1 hunks)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_create_transition.rs (2 hunks)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_delete_transition.rs (1 hunks)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_replace_transition.rs (1 hunks)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs (3 hunks)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/mod.rs (1 hunks)
  • packages/wasm-dpp/src/identity/state_transition/identity_create_transition/identity_create_transition.rs (1 hunks)
  • packages/wasm-dpp/src/identity/state_transition/identity_credit_transfer_transition/transition.rs (2 hunks)
  • packages/wasm-dpp/src/identity/state_transition/identity_credit_withdrawal_transition/transition.rs (2 hunks)
  • packages/wasm-dpp/src/identity/state_transition/identity_topup_transition/identity_topup_transition.rs (1 hunks)
  • packages/wasm-dpp/src/identity/state_transition/identity_update_transition/identity_update_transition.rs (2 hunks)
  • packages/wasm-dpp/src/voting/state_transition/masternode_vote_transition/mod.rs (8 hunks)
👮 Files not reviewed due to content moderation or server errors (5)
  • packages/wasm-dpp/src/data_contract/state_transition/data_contract_create_transition/mod.rs
  • packages/wasm-dpp/src/data_contract/state_transition/data_contract_update_transition/mod.rs
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_replace_transition.rs
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_create_transition.rs
  • packages/wasm-dpp/src/identity/state_transition/identity_create_transition/identity_create_transition.rs
🔇 Additional comments (16)
packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs (1)

42-43: LGTM! New action types properly implemented.

The new Purchase and UpdatePrice variants are correctly added to the TryFrom implementation, maintaining consistency with the existing pattern.

packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_delete_transition.rs (2)

76-79: LGTM! Identity contract nonce getter properly implemented.

The getter method correctly exposes the nonce value from the base transition.


81-88: LGTM! Identity contract nonce setter properly implemented.

The setter method correctly handles the base transition modification with proper cloning.

packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs (1)

106-130: LGTM! Prefunded voting balance handling properly implemented.

The implementation correctly handles the prefunded voting balance, including proper null handling and JS object creation.

packages/wasm-dpp/src/identity/state_transition/identity_credit_transfer_transition/transition.rs (3)

102-110: LGTM! User fee increase methods are well implemented.

The getter and setter for user fee increase are properly implemented with correct type conversion.


112-120: LGTM! Identity nonce methods are properly implemented.

The getter and setter for identity nonce maintain consistency with the inner implementation.


341-344: LGTM! Signature public key ID getter is correctly implemented.

The method properly exposes the inner signature public key ID.

packages/wasm-dpp/src/voting/state_transition/masternode_vote_transition/mod.rs (2)

73-81: LGTM! User fee methods are well-implemented.

The implementation follows the established pattern across other transition types and handles types appropriately.


83-86: LGTM! Identity nonce getter is correctly implemented.

The method properly exposes the underlying nonce value, aligning with the PR objectives.

packages/wasm-dpp/src/identity/state_transition/identity_credit_withdrawal_transition/transition.rs (2)

139-147: LGTM! User fee methods are consistently implemented.

The implementation aligns with other transition types and handles types appropriately.


423-426: LGTM! Signature public key ID getter is properly implemented.

The method follows the established pattern and correctly exposes the underlying ID.

packages/wasm-dpp/src/identity/state_transition/identity_update_transition/identity_update_transition.rs (3)

172-180: LGTM: Well-implemented user fee methods.

The implementation is consistent with other transition types and follows Rust conventions.


182-190: LGTM: Properly implemented nonce management methods.

The implementation correctly handles the identity contract nonce with appropriate type conversions.


435-438: LGTM: Signature public key ID getter implementation.

The method correctly retrieves the signature public key ID.

packages/wasm-dpp/src/document/state_transition/document_batch_transition/mod.rs (1)

101-109: LGTM! Clean implementation of user fee management methods.

The implementation follows best practices with:

  • Appropriate type safety using u16 for fee values
  • Consistent naming conventions
  • Clean integration with the existing WASM bindings architecture
packages/wasm-dpp/src/identity/state_transition/identity_topup_transition/identity_topup_transition.rs (1)

Line range hint 85-126: Verify consistent implementation across all transition types

The implementation of user fee and signature methods looks consistent across the reviewed files. Let's verify this pattern is followed in all transition types.

✅ Verification successful

Implementation is consistent across all transition types

The verification results show that both user fee increase and signature methods are consistently implemented across all state transition types:

  • User fee increase methods (get_user_fee_increase and set_user_fee_increase) are uniformly implemented in:

    • Identity transitions (Create, Update, Topup, Credit Transfer, Credit Withdrawal)
    • Document transitions (Batch)
    • Data Contract transitions (Create, Update)
    • Masternode Vote transitions
  • Signature methods (get_signature and get_signature_public_key_id) follow the same pattern across:

    • Identity transitions
    • Document transitions
    • Data Contract transitions
    • Masternode Vote transitions

All implementations maintain consistent return types and parameter types, with proper WASM bindings.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent implementation of user fee methods across all transition types

# Search for user fee increase methods
echo "Checking user fee increase methods implementation..."
rg -A 2 "fn (get|set)_user_fee_increase" packages/wasm-dpp/src/

# Search for signature-related methods
echo "Checking signature-related methods implementation..."
rg -A 2 "fn get_signature(_public_key_id)?" packages/wasm-dpp/src/

Length of output: 14190

Comment on lines +47 to +63
#[wasm_bindgen(js_name=getData)]
pub fn get_data(&self) -> JsValue {
match &self.0 {
DocumentTransition::Create(document_create_transition) => {
let json_value = document_create_transition.data().to_json_value().unwrap();
json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible()).unwrap()
}
DocumentTransition::Replace(document_replace_transition) => {
let json_value = document_replace_transition.data().to_json_value().unwrap();
json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible()).unwrap()
}
DocumentTransition::Delete(document_delete_transition) => JsValue::null(),
DocumentTransition::Transfer(document_transfer_transition) => JsValue::null(),
DocumentTransition::UpdatePrice(document_update_price_transition) => JsValue::null(),
DocumentTransition::Purchase(document_purchase_transition) => JsValue::null()
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for JSON conversion.

While the implementation is generally good, the unwrap calls on JSON conversion could lead to runtime panics.

Consider handling potential conversion errors:

     pub fn get_data(&self) -> JsValue {
         match &self.0 {
             DocumentTransition::Create(document_create_transition) => {
-                let json_value = document_create_transition.data().to_json_value().unwrap();
-                json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible()).unwrap()
+                document_create_transition.data()
+                    .to_json_value()
+                    .and_then(|json_value| 
+                        json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible())
+                    )
+                    .unwrap_or(JsValue::null())
             }
             DocumentTransition::Replace(document_replace_transition) => {
-                let json_value = document_replace_transition.data().to_json_value().unwrap();
-                json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible()).unwrap()
+                document_replace_transition.data()
+                    .to_json_value()
+                    .and_then(|json_value| 
+                        json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible())
+                    )
+                    .unwrap_or(JsValue::null())
             }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#[wasm_bindgen(js_name=getData)]
pub fn get_data(&self) -> JsValue {
match &self.0 {
DocumentTransition::Create(document_create_transition) => {
let json_value = document_create_transition.data().to_json_value().unwrap();
json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible()).unwrap()
}
DocumentTransition::Replace(document_replace_transition) => {
let json_value = document_replace_transition.data().to_json_value().unwrap();
json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible()).unwrap()
}
DocumentTransition::Delete(document_delete_transition) => JsValue::null(),
DocumentTransition::Transfer(document_transfer_transition) => JsValue::null(),
DocumentTransition::UpdatePrice(document_update_price_transition) => JsValue::null(),
DocumentTransition::Purchase(document_purchase_transition) => JsValue::null()
}
}
#[wasm_bindgen(js_name=getData)]
pub fn get_data(&self) -> JsValue {
match &self.0 {
DocumentTransition::Create(document_create_transition) => {
document_create_transition.data()
.to_json_value()
.and_then(|json_value|
json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible())
)
.unwrap_or(JsValue::null())
}
DocumentTransition::Replace(document_replace_transition) => {
document_replace_transition.data()
.to_json_value()
.and_then(|json_value|
json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible())
)
.unwrap_or(JsValue::null())
}
DocumentTransition::Delete(document_delete_transition) => JsValue::null(),
DocumentTransition::Transfer(document_transfer_transition) => JsValue::null(),
DocumentTransition::UpdatePrice(document_update_price_transition) => JsValue::null(),
DocumentTransition::Purchase(document_purchase_transition) => JsValue::null()
}
}

Comment on lines 238 to 303
&"documentTypeName".into(),
&contested_document_resource_vote_poll
.document_type_name
.clone()
.into(),
)
.unwrap();
Reflect::set(
&js_object,
&"indexName".into(),
&contested_document_resource_vote_poll
.index_name
.clone()
.into(),
)
.unwrap();

let config = bincode::config::standard()
.with_big_endian()
.with_no_limit();

let serialized_index_values = contested_document_resource_vote_poll
.index_values
.iter()
.map(|value| {
JsValue::from(Buffer::from_bytes_owned(
bincode::encode_to_vec(value, config)
.expect("expected to encode value in path"),
))
});

let js_array = Array::from_iter(serialized_index_values);

Reflect::set(&js_object, &"indexValues".into(), &js_array.into()).unwrap();

Some(js_object)
Vote::ResourceVote(vote) => {
let js_object = Object::new();

Reflect::set(
&js_object,
&"choice".into(),
&vote
.resource_vote_choice()
.clone()
.to_string()
.into(),
).unwrap();

match vote.vote_poll() {
VotePoll::ContestedDocumentResourceVotePoll(
contested_document_resource_vote_poll,
) => {
let contract_id = IdentifierWrapper::from(
contested_document_resource_vote_poll.contract_id.clone(),
);

Reflect::set(&js_object, &"contractId".into(), &contract_id.into()).unwrap();
Reflect::set(
&js_object,
&"documentTypeName".into(),
&contested_document_resource_vote_poll
.document_type_name
.clone()
.into(),
)
.unwrap();
Reflect::set(
&js_object,
&"indexName".into(),
&contested_document_resource_vote_poll
.index_name
.clone()
.into(),
)
.unwrap();

let config = bincode::config::standard()
.with_big_endian()
.with_no_limit();

let serialized_index_values = contested_document_resource_vote_poll
.index_values
.iter()
.map(|value| {
JsValue::from(Buffer::from_bytes_owned(
bincode::encode_to_vec(value, config)
.expect("expected to encode value in path"),
))
});

let js_array = Array::from_iter(serialized_index_values);

Reflect::set(&js_object, &"indexValues".into(), &js_array.into()).unwrap();

Some(js_object)
}
}
},
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding error handling for bincode operations.

The implementation of contested_document_resource_vote_poll could be improved:

  1. The expect call on line 292 could panic. Consider proper error handling:
-                                    bincode::encode_to_vec(value, config)
-                                        .expect("expected to encode value in path"),
+                                    bincode::encode_to_vec(value, config)
+                                        .map_err(|e| JsError::new(&e.to_string()))?,
  1. The unwrap calls on Reflect::set should handle potential errors:
-                        ).unwrap();
+                        ).map_err(|e| JsError::new("Failed to set choice"))?;

Committable suggestion skipped: line range outside the PR's diff.

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 (1)
packages/wasm-dpp/src/voting/state_transition/masternode_vote_transition/mod.rs (1)

228-231: Consider validating user fee boundaries.
Setting the user fee increase directly from user input may require logical checks (e.g., non-negative values or max limits). If your business rules allow any u16, this is fine; otherwise, consider validating.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5901158 and ec0c4d5.

📒 Files selected for processing (1)
  • packages/wasm-dpp/src/voting/state_transition/masternode_vote_transition/mod.rs (4 hunks)
🔇 Additional comments (6)
packages/wasm-dpp/src/voting/state_transition/masternode_vote_transition/mod.rs (6)

136-136: Check error propagation strategy.
The use of '.with_js_error()?' is acceptable; consider whether additional context is needed (e.g., logging or descriptive error messages) for more precise debugging. Otherwise, this usage looks correct.


223-226: Confirm safe integer range for user fee increase.
Casting to u16 may lead to data truncation if the underlying type has a larger range. Verify that the internal logic never exceeds u16.


233-236: No implementation issues found here.
The method cleanly returns the nonce, matching the intended usage.


241-303: Avoid panics in bincode encoding and Reflect calls.
This block uses '.expect(...)' (line 292) and '.unwrap()' multiple times. If encoding or JavaScript reflection fails, it may cause runtime panics. Here’s a recommended approach, mirroring previous feedback:

Use '.map_err(|e| JsError::new(&e.to_string()))?' instead of '.expect(...)' and safely handle Reflect errors:

- .expect("expected to encode value in path")
+ .map_err(|e| JsError::new(&e.to_string()))?

- ).unwrap();
+ ).map_err(|e| JsError::new("Failed to set choice"))?;

322-322: No issues identified with error return.
The error message is explicit enough.


381-381: No further comments — end of class.
Closing brace appears to match all opened blocks.

@pshenmic pshenmic added this to the v1.8.0 milestone Dec 18, 2024
shumkov
shumkov previously approved these changes Dec 19, 2024
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

♻️ Duplicate comments (1)
packages/wasm-dpp/src/voting/state_transition/masternode_vote_transition/mod.rs (1)

241-301: ⚠️ Potential issue

Critical: Improve error handling in contested_document_resource_vote_poll.

The method contains multiple panic points that should be handled gracefully:

  1. Multiple unwrap() calls on Reflect::set operations could panic
  2. expect() call on bincode encoding could panic

Apply this diff to handle errors properly:

     pub fn contested_document_resource_vote_poll(&self) -> Option<Object> {
         match self.0.vote() {
             Vote::ResourceVote(vote) => {
-                let js_object = Object::new();
+                let result = (|| -> Result<Object, JsValue> {
+                    let js_object = Object::new();
 
-                Reflect::set(
-                    &js_object,
-                    &"choice".into(),
-                    &vote
-                        .resource_vote_choice()
-                        .clone()
-                        .to_string()
-                        .into(),
-                ).unwrap();
+                    Reflect::set(
+                        &js_object,
+                        &"choice".into(),
+                        &vote
+                            .resource_vote_choice()
+                            .clone()
+                            .to_string()
+                            .into(),
+                    )?;

                    // ... similar changes for other Reflect::set calls ...

-                    bincode::encode_to_vec(value, config)
-                        .expect("expected to encode value in path"),
+                    bincode::encode_to_vec(value, config)
+                        .map_err(|e| JsError::new(&format!("Failed to encode value: {}", e)))?,

                    Ok(js_object)
+                })();
+                
+                match result {
+                    Ok(obj) => Some(obj),
+                    Err(e) => {
+                        // Consider logging the error here
+                        None
+                    }
+                }
             },
         }
     }
🧹 Nitpick comments (3)
packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_delete_transition.rs (1)

81-93: LGTM! Consider optimizing base clone.

The implementation of get/set identity_contract_nonce methods is correct. However, for performance optimization, consider if the base clone in set_identity_contract_nonce could be avoided by directly modifying the nonce if the base structure has interior mutability.

packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_replace_transition.rs (1)

99-102: LGTM! Consider trait extraction for common transition methods.

The implementations are correct and maintain consistency with DocumentDeleteTransitionWasm. To improve code reuse and maintainability, consider extracting these common methods (get_entropy, get/set_identity_contract_nonce) into a shared trait that can be implemented by both transition types.

Example trait extraction:

trait TransitionNonceAndEntropy {
    fn get_entropy(&self) -> Vec<u8>;
    fn get_identity_contract_nonce(&self) -> u64;
    fn set_identity_contract_nonce(&mut self, nonce: u64);
}

impl TransitionNonceAndEntropy for DocumentReplaceTransitionWasm {
    // Implement methods here
}

impl TransitionNonceAndEntropy for DocumentDeleteTransitionWasm {
    // Implement methods here
}

Also applies to: 197-209

packages/wasm-dpp/src/voting/state_transition/masternode_vote_transition/mod.rs (1)

233-236: Consider aligning method names for consistency.

The JavaScript method name getIdentityContractNonce doesn't match its Rust implementation name get_identity_nonce. Consider renaming the Rust method to match the JavaScript name for better maintainability.

-    pub fn get_identity_nonce(&self) -> u64 {
+    pub fn get_identity_contract_nonce(&self) -> u64 {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ec0c4d5 and bab0359.

📒 Files selected for processing (6)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_create_transition.rs (2 hunks)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_delete_transition.rs (1 hunks)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_replace_transition.rs (2 hunks)
  • packages/wasm-dpp/src/identity/state_transition/identity_credit_transfer_transition/transition.rs (2 hunks)
  • packages/wasm-dpp/src/identity/state_transition/identity_credit_withdrawal_transition/transition.rs (2 hunks)
  • packages/wasm-dpp/src/voting/state_transition/masternode_vote_transition/mod.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/wasm-dpp/src/identity/state_transition/identity_credit_withdrawal_transition/transition.rs
  • packages/wasm-dpp/src/identity/state_transition/identity_credit_transfer_transition/transition.rs
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_create_transition.rs
🔇 Additional comments (2)
packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_delete_transition.rs (1)

71-74: LGTM! Clean entropy getter implementation.

The implementation safely exposes the inner entropy as a Vec.

packages/wasm-dpp/src/voting/state_transition/masternode_vote_transition/mod.rs (1)

223-231: LGTM: User fee increase methods are well-implemented.

The getter and setter methods for user fee increase are properly implemented with appropriate type conversions for the WASM boundary.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bab0359 and 701d1b5.

📒 Files selected for processing (1)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs (4 hunks)
🔇 Additional comments (4)
packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs (4)

20-21: LGTM: Required imports added correctly

The new imports are necessary for JSON conversion and document replace transition functionality.


47-63: Add error handling for JSON conversion.

The unwrap calls on JSON conversion could lead to runtime panics.


47-63: LGTM: Comprehensive handling of all document transition types

The method correctly implements data retrieval for all document transition variants, supporting the Platform Explorer's display requirements. The null returns for Delete, Transfer, UpdatePrice, and Purchase transitions are appropriate as these types don't carry additional data.


117-141: LGTM: Well-implemented prefunded voting balance retrieval

The implementation:

  • Properly handles error cases using Result
  • Correctly processes Create transitions with prefunded balance
  • Returns null for other transition types
  • Creates a clean JS object structure for the Platform Explorer

Comment on lines 90 to 100
#[wasm_bindgen(js_name=getEntropy)]
pub fn get_revision(&self) -> Vec<u8> {
match self.0.clone() {
DocumentTransition::Create(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::Replace(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::Delete(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::Transfer(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::UpdatePrice(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::Purchase(document_transition) => Vec::from(document_transition.entropy()),
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix method name and optimize performance

There are two issues in this implementation:

  1. The method is declared as get_revision but implements entropy functionality, which will cause a compilation error due to the duplicate method name.
  2. The implementation unnecessarily clones the entire transition.

Apply this fix:

-    pub fn get_revision(&self) -> Vec<u8> {
-        match self.0.clone() {
+    pub fn get_entropy(&self) -> Vec<u8> {
+        match &self.0 {
             DocumentTransition::Create(document_transition) => Vec::from(document_transition.entropy()),
             DocumentTransition::Replace(document_transition) => Vec::from(document_transition.entropy()),
             DocumentTransition::Delete(document_transition) => Vec::from(document_transition.entropy()),
             DocumentTransition::Transfer(document_transition) => Vec::from(document_transition.entropy()),
             DocumentTransition::UpdatePrice(document_transition) => Vec::from(document_transition.entropy()),
             DocumentTransition::Purchase(document_transition) => Vec::from(document_transition.entropy()),
         }
     }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#[wasm_bindgen(js_name=getEntropy)]
pub fn get_revision(&self) -> Vec<u8> {
match self.0.clone() {
DocumentTransition::Create(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::Replace(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::Delete(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::Transfer(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::UpdatePrice(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::Purchase(document_transition) => Vec::from(document_transition.entropy()),
}
}
#[wasm_bindgen(js_name=getEntropy)]
pub fn get_entropy(&self) -> Vec<u8> {
match &self.0 {
DocumentTransition::Create(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::Replace(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::Delete(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::Transfer(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::UpdatePrice(document_transition) => Vec::from(document_transition.entropy()),
DocumentTransition::Purchase(document_transition) => Vec::from(document_transition.entropy()),
}
}

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 701d1b5 and d77e1aa.

📒 Files selected for processing (2)
  • packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/mod.rs (2 hunks)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs (4 hunks)
🔇 Additional comments (4)
packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/mod.rs (1)

47-48: Clarify usage of new entropy method in trait
The newly introduced entropy(&self) -> Vec<u8> method changes the trait’s API. Ensure that all implementers correctly handle entropy retrieval. Confirm that external consumers of DocumentTransitionV0Methods have migrated to the new function and are no longer calling the removed get_document_type() function.

Would you like a shell script to search the entire codebase for references to “get_document_type” or do you plan to remove them manually?

packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs (3)

47-63: Avoid panics by handling JSON conversion errors
This code uses multiple unwrap() calls on to_json_value() and serialize(), which can cause runtime panics if these operations fail.

For example, you can adopt optional handling or return an error:

- let json_value = document_create_transition.data().to_json_value().unwrap();
- json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible()).unwrap()
+ let json_value_result = document_create_transition
+     .data()
+     .to_json_value()
+     .and_then(|json_value| {
+         json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible())
+     });
+ match json_value_result {
+     Ok(val) => val,
+     Err(_) => JsValue::null(), // Or return a JsValue::from_str("error") or similar
+ }

90-93: Cross-verify the get_entropy method
This new method delegates to the trait’s entropy() function, which currently has a recursion bug in the Rust file. After fixing the recursion issue there, ensure that the correct entropy is returned here to avoid misbehavior or runtime errors.


110-134: Validate numeric edge cases in prefunded voting balance
The new method get_prefunded_voting_balance looks correct for standard usage. However, confirm that edge cases (e.g., extremely large or negative values, if any) are handled properly. Any negative balance scenario might require special logic if supported or expected by the protocol.

Comment on lines 171 to 173
fn entropy(&self) -> Vec<u8> {
self.entropy()
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential infinite recursion
Inside fn entropy(&self) -> Vec<u8>, calling self.entropy() will recursively invoke itself, leading to a stack overflow. Instead, delegate to the underlying transition’s entropy. For example, you might call self.base().entropy() or a variant-specific method.

 fn entropy(&self) -> Vec<u8> {
-    self.entropy()
+    match self {
+        DocumentTransition::Create(t) => t.entropy(),
+        DocumentTransition::Replace(t) => t.entropy(),
+        DocumentTransition::Delete(t) => t.entropy(),
+        DocumentTransition::Transfer(t) => t.entropy(),
+        DocumentTransition::UpdatePrice(t) => t.entropy(),
+        DocumentTransition::Purchase(t) => t.entropy(),
+    }
 }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fn entropy(&self) -> Vec<u8> {
self.entropy()
}
fn entropy(&self) -> Vec<u8> {
match self {
DocumentTransition::Create(t) => t.entropy(),
DocumentTransition::Replace(t) => t.entropy(),
DocumentTransition::Delete(t) => t.entropy(),
DocumentTransition::Transfer(t) => t.entropy(),
DocumentTransition::UpdatePrice(t) => t.entropy(),
DocumentTransition::Purchase(t) => t.entropy(),
}
}

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 (1)
packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs (1)

110-134: Consider a more concise implementation.

While the implementation is correct, it could be simplified for better readability.

Consider this more concise version:

     pub fn get_prefunded_voting_balance(&self) -> Result<JsValue, JsValue> {
         match &self.0 {
             DocumentTransition::Create(create_transition) => {
-                let prefunded_voting_balance = create_transition.prefunded_voting_balance().clone();
-
-                if prefunded_voting_balance.is_none() {
-                    return Ok(JsValue::null())
-                }
-
-                let (index_name, credits) = prefunded_voting_balance.unwrap();
-
-                let js_object = js_sys::Object::new();
-
-                js_sys::Reflect::set(
-                    &js_object,
-                    &JsValue::from_str(&index_name),
-                    &JsValue::from(credits),
-                )?;
-
-                Ok(JsValue::from(js_object))
+                Ok(create_transition
+                    .prefunded_voting_balance()
+                    .map(|(index_name, credits)| {
+                        let obj = js_sys::Object::new();
+                        js_sys::Reflect::set(
+                            &obj,
+                            &JsValue::from_str(&index_name),
+                            &JsValue::from(credits),
+                        ).unwrap_or_default();
+                        obj.into()
+                    })
+                    .unwrap_or_else(|| JsValue::null()))
             }
             _ => Ok(JsValue::null()),
         }
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d77e1aa and e21ae53.

📒 Files selected for processing (2)
  • packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/mod.rs (2 hunks)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs (4 hunks)
🔇 Additional comments (5)
packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs (3)

20-21: LGTM: Required imports added for new functionality.

The new imports support JSON conversion and document replace transition methods.


47-63: Add error handling for JSON conversion.

The unwrap calls on JSON conversion could lead to runtime panics.


90-93: LGTM: Clean implementation of entropy getter.

The method correctly delegates to the inner entropy implementation.

packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/mod.rs (2)

47-48: LGTM: Clean trait method declaration.

The entropy method is well-documented and follows Rust trait conventions.


171-180: Verify intended entropy behavior.

The implementation only returns entropy for Create transitions and None for all others. Please verify if this is the intended behavior.

✅ Verification successful

Based on the search results, I can now provide a definitive response about the intended entropy behavior:

Entropy is correctly implemented for document transitions

The implementation that returns entropy only for Create transitions and None for all others is the intended behavior. This is evidenced by:

  1. The presence of test cases specifically checking entropy reuse for document creation:

    • test_document_creation_should_fail_if_reusing_entropy()
    • test_document_creation_on_contested_unique_index_should_fail_if_reusing_entropy()
  2. The error message in the codebase that specifically ties entropy to document creation:

    #[error("Document {document_id} is already present in a contest, entropy might be being reused")]
  3. The usage pattern in the codebase shows that entropy is only used during document creation for generating unique document IDs and preventing duplicates, which explains why it's only needed for Create transitions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for entropy usage in the codebase to verify the expected behavior
echo "Searching for entropy usage in transitions..."
rg -A 5 "entropy\(\)" --type rust

# Search for tests related to entropy
echo "Searching for entropy-related tests..."
rg -A 5 "test.*entropy" --type rust

Length of output: 29689

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js-sdk JS Dash SDK related
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants