-
Notifications
You must be signed in to change notification settings - Fork 39
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
base: v1.8-dev
Are you sure you want to change the base?
Conversation
WalkthroughThis 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 Changes
Suggested Labels
Suggested Reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 methodsWhile 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
📒 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
andset_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
andget_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
#[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() | ||
} | ||
} |
There was a problem hiding this comment.
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.
#[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() | |
} | |
} |
&"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) | ||
} | ||
} | ||
}, | ||
} |
There was a problem hiding this comment.
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:
- 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()))?,
- The
unwrap
calls onReflect::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.
There was a problem hiding this 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
📒 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.
There was a problem hiding this 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 issueCritical: Improve error handling in contested_document_resource_vote_poll.
The method contains multiple panic points that should be handled gracefully:
- Multiple
unwrap()
calls onReflect::set
operations could panicexpect()
call on bincode encoding could panicApply 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 nameget_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
📒 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.
There was a problem hiding this 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
📒 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
#[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()), | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix method name and optimize performance
There are two issues in this implementation:
- The method is declared as
get_revision
but implements entropy functionality, which will cause a compilation error due to the duplicate method name. - 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.
#[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()), | |
} | |
} |
There was a problem hiding this 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
📒 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.
fn entropy(&self) -> Vec<u8> { | ||
self.entropy() | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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(), | |
} | |
} |
There was a problem hiding this 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
📒 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:
-
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()
-
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")]
-
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
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?
How Has This Been Tested?
In the integration with Platform Explorer
Breaking Changes
No
Checklist:
For repository code-owners and collaborators only
Summary by CodeRabbit
Summary by CodeRabbit
New Features
Purchase
andUpdatePrice
for document transitions.MasternodeVoteTransition
with new methods and updated response structures.DocumentTransitionV0Methods
trait to include entropy retrieval.Bug Fixes
Documentation