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(sdk): implement document transfers in WASM DPP #2406

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

Conversation

pshenmic
Copy link
Collaborator

@pshenmic pshenmic commented Dec 24, 2024

Issue being fixed or feature implemented

WASM DPP package is missing few document transitions implementation, one of it is a document transfer. Adding new method binding in the wasm dpp will allow developers to create such transactions from the Web

What was done?

  • Added createTransferStateTransition method to ExtendedDocumentWasm
  • Added document transfer method in the JS Dash SDK
  • Fixed DPP incorrect error revision mismatch message

How Has This Been Tested?

In the testnet

https://testnet.platform-explorer.com/transaction/42175A63E25A316B5E0666317A3FF36A407EDDBA01D844982F68A6D10CBBFAF7

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

  • New Features

    • Introduced a transferDocument method for document management.
    • Added a new transfer function for transferring documents.
    • Enhanced broadcast function with an optional keyIndex parameter.
    • Implemented a create_transfer_state_transition method for document state transitions.
    • Added a DocumentTransferTransitionWasm structure for WebAssembly compatibility.
    • Introduced a new module for document transfer transitions.
  • Bug Fixes

    • Corrected revision validation logic in document batch transitions.
  • Documentation

    • Updated documentation for the new transfer function and keyIndex parameter.

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

coderabbitai bot commented Dec 24, 2024

Warning

Rate limit exceeded

@pshenmic has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 21 minutes and 34 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 1f0f7c6 and 2131f00.

📒 Files selected for processing (1)
  • packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts (1 hunks)

Walkthrough

This pull request introduces a new method, transferDocument, to the Platform class in the Dash SDK, enhancing document management capabilities. The changes include the addition of the transfer function in the documents interface, updates to the broadcast function, and the introduction of document transfer transitions across various components, including Rust and WebAssembly. The modifications ensure that document transfers are effectively handled within the platform, allowing for improved functionality in document state transitions.

Changes

File Change Summary
packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts Added transferDocument method and updated Records interface to include transfer function.
packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts Added optional keyIndex parameter to broadcast function.
packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts Implemented new transfer function for document transfers.
packages/rs-dpp/src/document/document_factory/v0/mod.rs Added support for document transfer transitions and enhanced error handling.
packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/transformer/v0/mod.rs Updated revision checking and validation logic.
packages/wasm-dpp/src/document/extended_document.rs Added create_transfer_state_transition method.
packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs Created Wasm-compatible DocumentTransferTransitionWasm structure with conversion implementations.
packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs Added new module for document_transfer_transition.

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • shumkov
  • QuantumExplorer
  • lklimek

Poem

🐰 Hop, hop, document dance!
Transfers gliding with grace
From sender to receiver's embrace
Code weaves magic, blockchain's new chance
SDK evolves with rabbit's advance! 🚀


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: 3

🧹 Nitpick comments (4)
packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts (1)

14-34: Handle potential errors during the broadcast
This function signs and broadcasts the state transition without error handling (e.g., try/catch). If the broadcast fails, the user may not be alerted.

Consider wrapping the call to broadcastStateTransition in a try/catch block or returning a structured error, for example:

try {
  await broadcastStateTransition(this, documentsBatchTransition);
} catch (e) {
  this.logger.error('[Document#transfer] Broadcast failed:', e);
  throw e;
}
packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts (1)

24-24: Optional usage of keyIndex
The function signature expects a number, although the code uses keyIndex ?? 1 as a fallback. If you intend to allow undefined to set a default, consider making the parameter optional in TypeScript.

-export default async function broadcast(
-  this: Platform,
-  documents: { ... },
-  identity: any,
-  keyIndex : number,
+export default async function broadcast(
+  this: Platform,
+  documents: { ... },
+  identity: any,
+  keyIndex?: number,
) {
packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts (1)

62-62: Refine function typing in Records interface
Using Function as a type is discouraged. Instead, define the function signature explicitly to reduce ambiguity and potential bugs.

interface Records {
  broadcast: (documents: any, identity: any, keyIndex?: number) => Promise<any>,
  create: (/* define type signatures */) => Promise<any>,
-  transfer: Function,
+  transfer: (document: ExtendedDocument, receiver: Identity, sender: Identity) => Promise<any>,
  get: (/* define type signatures */) => any,
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 62-62: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)

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

22-256: Consider removing or fully implementing the commented-out methods.
Leaving large code blocks commented out can lead to confusion and code bloat. If they are needed in the future, consider adding a TODO comment explaining the plan and timeline. Otherwise, removing them reduces code noise.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cfd9c4d and 8f79b69.

📒 Files selected for processing (10)
  • packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts (3 hunks)
  • packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts (2 hunks)
  • packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts (1 hunks)
  • packages/rs-dpp/src/document/document_factory/v0/mod.rs (3 hunks)
  • packages/rs-dpp/src/document/specialized_document_factory/v0/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/transformer/v0/mod.rs (1 hunks)
  • packages/wasm-dpp/src/document/extended_document.rs (3 hunks)
  • packages/wasm-dpp/src/document/factory.rs (3 hunks)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs (1 hunks)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts

[error] 62-62: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)

🔇 Additional comments (17)
packages/rs-dpp/src/document/document_factory/v0/mod.rs (2)

35-35: Import statement looks correct
No issues found with this import.


527-613: ⚠️ Potential issue

Potential ownership logic issue in document transfers
Line 552 assigns document.owner_id() to recipient_owner_id, suggesting the document remains under the same owner by default. This may not achieve the actual transfer of ownership unless the document's owner is explicitly overwritten somewhere else.

Consider verifying or updating the code to ensure a genuine transfer to the new owner. For instance:

- let recipient_owner_id = document.owner_id();
+ // Retrieve the intended recipient's ID from a separate source or function parameter
+ let recipient_owner_id = new_owner_id;

Likely invalid or redundant comment.

packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts (3)

14-14: New keyIndex parameter recognized
The documentation for keyIndex is clear and consistent with usage.


21-21: Additional 'delete' property
Adding this property for deleted documents is consistent.


57-57: Signing with keyIndex
Using keyIndex ?? 1 ensures the default behavior remains the same.

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

2-2: New document_transfer_transition module imported
No issues found. This aligns with the newly introduced transition logic.

packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts (2)

12-12: Import of transferDocument
Import statement is consistent and matches usage in this file.


170-170: Binding the new transferDocument method
Binding appears correct and ensures the documents.transfer method is available.

packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs (4)

1-2: Good use of wasm-bindgen for bridging Rust to JS.
No issues spotted.


4-8: Well-defined struct for WASM bridging.
The DocumentTransferTransitionWasm struct straightforwardly wraps DocumentTransferTransition, enabling seamless integration with JavaScript.


10-14: Symmetrical type conversion from Rust to WASM.
The From<DocumentTransferTransition> for DocumentTransferTransitionWasm is clear and concise.


16-20: Symmetrical type conversion from WASM to Rust.
This complementary conversion ensures consistency.

packages/wasm-dpp/src/document/factory.rs (3)

35-35: New field supports Transfer transitions.
Adding transfer: Vec<ExtendedDocumentWasm> cleanly parallels existing transition vectors (create, replace, etc.).


59-63: Extend transition handling with a dedicated transfer list.
add_transition_transfer follows the same pattern as other add methods, ensuring consistency.


287-287: Document extraction for 'transfer' is consistent with other transitions.
The extended logic for extracting transfer documents aligns well with create, replace, delete.

Also applies to: 292-292

packages/wasm-dpp/src/document/extended_document.rs (1)

1-1: New imports for transfer transitions.
Imports for DocumentTransferTransition and DocumentsBatchTransitionWasm ensure the new feature is properly integrated.

Also applies to: 5-5, 17-18, 25-25

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

723-723: Looks correct!

This change correctly ensures that the original document’s revision is incremented by one. The logic aligns well with the documented requirement to check that transition_revision == previous_revision + 1.

Comment on lines 266 to 284
DocumentTransitionActionType::Transfer => Self::document_transfer_transitions(
documents
.into_iter()
.map(|(document, document_type, _)| (document, document_type))
.collect(),
nonce_counter,
platform_version,
),
DocumentTransitionActionType::Purchase => {
Err(ProtocolError::InvalidStateTransitionType(
"action type not accounted for Transfer".to_string(),
))
}
DocumentTransitionActionType::UpdatePrice => Err(ProtocolError::InvalidStateTransitionType(
"action type not accounted for UpdatePrice".to_string(),
)),
DocumentTransitionActionType::IgnoreWhileBumpingRevision => Err(ProtocolError::InvalidStateTransitionType(
"action type not accounted for IgnoreWhileBumpingRevision".to_string(),
))
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

Mismatch in error message for Purchase action
When DocumentTransitionActionType::Purchase is encountered, the error message incorrectly states "action type not accounted for Transfer" instead of referring to "Purchase." This might confuse developers or users.

Consider applying the following fix:

-                DocumentTransitionActionType::Purchase => {
-                    Err(ProtocolError::InvalidStateTransitionType(
-                        "action type not accounted for Transfer".to_string(),
-                    ))
-                }
+                DocumentTransitionActionType::Purchase => {
+                    Err(ProtocolError::InvalidStateTransitionType(
+                        "action type not accounted for Purchase".to_string(),
+                    ))
+                }
📝 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
DocumentTransitionActionType::Transfer => Self::document_transfer_transitions(
documents
.into_iter()
.map(|(document, document_type, _)| (document, document_type))
.collect(),
nonce_counter,
platform_version,
),
DocumentTransitionActionType::Purchase => {
Err(ProtocolError::InvalidStateTransitionType(
"action type not accounted for Transfer".to_string(),
))
}
DocumentTransitionActionType::UpdatePrice => Err(ProtocolError::InvalidStateTransitionType(
"action type not accounted for UpdatePrice".to_string(),
)),
DocumentTransitionActionType::IgnoreWhileBumpingRevision => Err(ProtocolError::InvalidStateTransitionType(
"action type not accounted for IgnoreWhileBumpingRevision".to_string(),
))
DocumentTransitionActionType::Transfer => Self::document_transfer_transitions(
documents
.into_iter()
.map(|(document, document_type, _)| (document, document_type))
.collect(),
nonce_counter,
platform_version,
),
DocumentTransitionActionType::Purchase => {
Err(ProtocolError::InvalidStateTransitionType(
"action type not accounted for Purchase".to_string(),
))
}
DocumentTransitionActionType::UpdatePrice => Err(ProtocolError::InvalidStateTransitionType(
"action type not accounted for UpdatePrice".to_string(),
)),
DocumentTransitionActionType::IgnoreWhileBumpingRevision => Err(ProtocolError::InvalidStateTransitionType(
"action type not accounted for IgnoreWhileBumpingRevision".to_string(),
))

Comment on lines +239 to +264
#[wasm_bindgen(js_name=createTransferStateTransition)]
pub fn create_transfer_state_transition(&mut self, recipient: IdentifierWrapper, identity_contract_nonce: IdentityNonce) -> DocumentsBatchTransitionWasm {
let mut cloned_document = self.0.document().clone();

cloned_document.set_revision(Some(cloned_document.revision().unwrap() + 1));

let transfer_transition = DocumentTransferTransition::from_document(
cloned_document,
self.0.document_type().unwrap(),
identity_contract_nonce,
recipient.into(),
PlatformVersion::latest(),
None,
None,
).unwrap();

let documents_batch_transition: DocumentsBatchTransition = DocumentsBatchTransitionV0 {
owner_id: self.0.owner_id(),
transitions: vec![transfer_transition.into()],
user_fee_increase: Default::default(),
signature_public_key_id: Default::default(),
signature: Default::default(),
}.into();

documents_batch_transition.into()
}
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

Check for None revision before incrementing.
The method does not verify cloned_document.revision() is Some before computing unwrap() + 1. If a document is missing a revision, this will panic. To prevent runtime errors, handle the case of None:

     let mut cloned_document = self.0.document().clone();

-    cloned_document.set_revision(Some(cloned_document.revision().unwrap() + 1));
+    if let Some(current_revision) = cloned_document.revision() {
+        cloned_document.set_revision(Some(current_revision + 1));
+    } else {
+        // Decide how to handle the absence of a revision, e.g., return an error or set a default revision
+        return Err(JsValue::from_str("Document is missing a revision"));
+    }

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

Comment on lines 273 to 288
DocumentTransitionActionType::Transfer => {
Err(ProtocolError::InvalidStateTransitionType(
"action type not accounted for Transfer".to_string(),
))
},
DocumentTransitionActionType::Purchase => {
Err(ProtocolError::InvalidStateTransitionType(
"action type not accounted for Purchase".to_string(),
))
}
DocumentTransitionActionType::UpdatePrice => Err(ProtocolError::InvalidStateTransitionType(
"action type not accounted for UpdatePrice".to_string(),
)),
DocumentTransitionActionType::IgnoreWhileBumpingRevision => Err(ProtocolError::InvalidStateTransitionType(
"action type not accounted for IgnoreWhileBumpingRevision".to_string(),
))
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

Missing Transfer transition support.
Although transfer transitions are defined elsewhere, here the code returns “action type not accounted for Transfer” as an error. This creates an inconsistency with other segments that do implement transfer logic. Consider implementing the logic or removing the partial references.

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/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts (2)

5-13: Update JSDoc to match the actual parameters

The JSDoc parameters don't match the function's actual parameters. The typeLocator and data parameters are documented but not used, while document, receiver, and sender parameters are missing from the documentation.

Update the JSDoc to:

 /**
  * Transfer document in the platform
  *
  * @param {Platform} this - bound instance class
- * @param {string} typeLocator - type locator
- * @param identity - identity
- * @param {Object} [data] - options
+ * @param {ExtendedDocument} document - document to transfer
+ * @param {Identity} receiver - receiver identity
+ * @param {Identity} sender - sender identity
  * @returns {StateTransition}
  */

14-19: Improve type safety by specifying the return type

The function's return type Promise<any> is too broad and could lead to type-safety issues.

-): Promise<any> {
+): Promise<StateTransition> {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f79b69 and e8defe8.

📒 Files selected for processing (4)
  • packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts (1 hunks)
  • packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts (1 hunks)
  • packages/rs-dpp/src/document/document_factory/v0/mod.rs (1 hunks)
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts
  • packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs
🔇 Additional comments (1)
packages/rs-dpp/src/document/document_factory/v0/mod.rs (1)

35-35: LGTM!

The addition of the DocumentTransferTransition import is necessary for implementing the document transfer functionality.

Comment on lines 20 to 21
this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()}
from ${sender.getId().toString} to {${receiver.getId().toString()}`);
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 template literal syntax error in debug message

The debug message has a syntax error in the template literal - missing closing curly brace and using a method reference instead of a method call.

-  this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()}
- from ${sender.getId().toString} to {${receiver.getId().toString()}`);
+  this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()} from ${sender.getId().toString()} to ${receiver.getId().toString()}`);
📝 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
this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()}
from ${sender.getId().toString} to {${receiver.getId().toString()}`);
this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()} from ${sender.getId().toString()} to ${receiver.getId().toString()}`);

Comment on lines +22 to +32
await this.initialize();

const identityContractNonce = await this.nonceManager
.bumpIdentityContractNonce(sender.getId(), document.getDataContractId());

const documentsBatchTransition = document
.createTransferStateTransition(receiver.getId(), BigInt(identityContractNonce));

await signStateTransition(this, documentsBatchTransition, sender, 1);

await broadcastStateTransition(this, documentsBatchTransition);
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 external calls

The function makes several external calls without proper error handling, which could lead to unhandled rejections.

+  try {
     await this.initialize();
 
     const identityContractNonce = await this.nonceManager
       .bumpIdentityContractNonce(sender.getId(), document.getDataContractId());
 
     const documentsBatchTransition = document
       .createTransferStateTransition(receiver.getId(), BigInt(identityContractNonce));
 
     await signStateTransition(this, documentsBatchTransition, sender, 1);
 
     await broadcastStateTransition(this, documentsBatchTransition);
+    return documentsBatchTransition;
+  } catch (error) {
+    this.logger.error('[Document#transfer] Failed to transfer document:', error);
+    throw error;
+  }
📝 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
await this.initialize();
const identityContractNonce = await this.nonceManager
.bumpIdentityContractNonce(sender.getId(), document.getDataContractId());
const documentsBatchTransition = document
.createTransferStateTransition(receiver.getId(), BigInt(identityContractNonce));
await signStateTransition(this, documentsBatchTransition, sender, 1);
await broadcastStateTransition(this, documentsBatchTransition);
try {
await this.initialize();
const identityContractNonce = await this.nonceManager
.bumpIdentityContractNonce(sender.getId(), document.getDataContractId());
const documentsBatchTransition = document
.createTransferStateTransition(receiver.getId(), BigInt(identityContractNonce));
await signStateTransition(this, documentsBatchTransition, sender, 1);
await broadcastStateTransition(this, documentsBatchTransition);
return documentsBatchTransition;
} catch (error) {
this.logger.error('[Document#transfer] Failed to transfer document:', error);
throw error;
}

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

♻️ Duplicate comments (2)
packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts (2)

20-20: ⚠️ Potential issue

Fix template literal syntax error in debug message

The debug message has a syntax error in the template literal - missing closing curly brace and using a method reference instead of a method call.

-  this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()} from ${sender.getId().toString} to {${receiver.getId().toString()}`);
+  this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()} from ${sender.getId().toString()} to ${receiver.getId().toString()}`);

21-31: ⚠️ Potential issue

Add error handling for external calls

The function makes several external calls without proper error handling, which could lead to unhandled rejections.

+  try {
     await this.initialize();
 
     const identityContractNonce = await this.nonceManager
       .bumpIdentityContractNonce(sender.getId(), document.getDataContractId());
 
     const documentsBatchTransition = document
       .createTransferStateTransition(receiver.getId(), BigInt(identityContractNonce));
 
     await signStateTransition(this, documentsBatchTransition, sender, 1);
 
     await broadcastStateTransition(this, documentsBatchTransition);
+    return documentsBatchTransition;
+  } catch (error) {
+    this.logger.error('[Document#transfer] Failed to transfer document:', error);
+    throw error;
+  }
🧹 Nitpick comments (2)
packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts (2)

5-13: Update JSDoc to match implementation

The JSDoc comments need to be updated to accurately reflect the function signature and return type:

  • Parameter list doesn't match implementation (typeLocator vs actual parameters)
  • Return type annotation shows StateTransition but function returns Promise<any>
 /**
  * Transfer document in the platform
  *
- * @param {Platform} this - bound instance class
- * @param {string} typeLocator - type locator
- * @param identity - identity
- * @param {Object} [data] - options
- * @returns {StateTransition}
+ * @param {Platform} this - Platform instance
+ * @param {ExtendedDocument} document - Document to transfer
+ * @param {Identity} receiver - Receiver's identity
+ * @param {Identity} sender - Sender's identity
+ * @returns {Promise<any>} The broadcast state transition
  */

14-19: Improve type safety by using specific return type

The return type Promise<any> is too generic. Consider using the specific state transition type from the WASM DPP package.

 export async function transfer(
   this: Platform,
   document: ExtendedDocument,
   receiver: Identity,
   sender: Identity,
-): Promise<any> {
+): Promise<DocumentsBatchTransition> {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e8defe8 and 1f0f7c6.

📒 Files selected for processing (1)
  • packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts (1 hunks)
🔇 Additional comments (1)
packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts (1)

34-34: LGTM!

The default export is correctly implemented.

Comment on lines +14 to +31
export async function transfer(
this: Platform,
document: ExtendedDocument,
receiver: Identity,
sender: Identity,
): Promise<any> {
this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()} from ${sender.getId().toString} to {${receiver.getId().toString()}`);
await this.initialize();

const identityContractNonce = await this.nonceManager
.bumpIdentityContractNonce(sender.getId(), document.getDataContractId());

const documentsBatchTransition = document
.createTransferStateTransition(receiver.getId(), BigInt(identityContractNonce));

await signStateTransition(this, documentsBatchTransition, sender, 1);

await broadcastStateTransition(this, documentsBatchTransition);
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 input validation for required parameters

The function should validate its input parameters before proceeding with the transfer operation.

 export async function transfer(
   this: Platform,
   document: ExtendedDocument,
   receiver: Identity,
   sender: Identity,
 ): Promise<any> {
+  if (!document || !receiver || !sender) {
+    throw new Error('Document, receiver, and sender are required parameters');
+  }
+
+  if (sender.getId().equals(receiver.getId())) {
+    throw new Error('Sender and receiver cannot be the same identity');
+  }
+
   this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()}...
📝 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
export async function transfer(
this: Platform,
document: ExtendedDocument,
receiver: Identity,
sender: Identity,
): Promise<any> {
this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()} from ${sender.getId().toString} to {${receiver.getId().toString()}`);
await this.initialize();
const identityContractNonce = await this.nonceManager
.bumpIdentityContractNonce(sender.getId(), document.getDataContractId());
const documentsBatchTransition = document
.createTransferStateTransition(receiver.getId(), BigInt(identityContractNonce));
await signStateTransition(this, documentsBatchTransition, sender, 1);
await broadcastStateTransition(this, documentsBatchTransition);
export async function transfer(
this: Platform,
document: ExtendedDocument,
receiver: Identity,
sender: Identity,
): Promise<any> {
if (!document || !receiver || !sender) {
throw new Error('Document, receiver, and sender are required parameters');
}
if (sender.getId().equals(receiver.getId())) {
throw new Error('Sender and receiver cannot be the same identity');
}
this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()} from ${sender.getId().toString} to {${receiver.getId().toString()}`);
await this.initialize();
const identityContractNonce = await this.nonceManager
.bumpIdentityContractNonce(sender.getId(), document.getDataContractId());
const documentsBatchTransition = document
.createTransferStateTransition(receiver.getId(), BigInt(identityContractNonce));
await signStateTransition(this, documentsBatchTransition, sender, 1);
await broadcastStateTransition(this, documentsBatchTransition);

@pshenmic pshenmic added this to the v1.8.0 milestone Dec 24, 2024
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.

1 participant