Skip to content

Conversation

@thephez
Copy link
Collaborator

@thephez thephez commented Aug 28, 2025

Issue being fixed or feature implemented

Fixes issues with document state transitions in the WASM SDK where document revisions were not being properly incremented for transfer, purchase, and price update operations, causing validation failures on the platform.

What was done?

  • Fixed document transfer transitions to properly increment the document revision before creating the transition
  • Improved document purchase transitions to use a new document instance with incremented revision
  • Updated price update transitions to use the dedicated update_price method instead of generic replacement
  • Ensured all document-modifying transitions correctly handle revision increments to maintain state consistency

There may be a better way to do this, but it's how I was able to get wasm-sdk to produce transitions that actually work.

How Has This Been Tested?

  • Tested document transfer transitions with proper revision increments
  • Verified transitions create valid state changes

Breaking Changes

None

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

  • Bug Fixes

    • Improved reliability of document updates by correctly bumping revisions during transfers, purchases, and price changes.
    • Clearer error handling for missing or overflowing revisions, reducing ambiguous failures.
    • Removed unnecessary randomness in price updates, decreasing unexpected behavior.
  • Refactor

    • Standardized creation of document transitions to consistently use incremented revisions, improving stability and reducing transition conflicts.

thephez and others added 2 commits August 28, 2025 17:00
- Use dedicated price update transition method instead of generic replacement
- Properly increment document revision for purchase and price updates
- Create separate document instances with updated revisions for each operation
- Fix transition creation to use appropriate specialized methods

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
When creating document transfer transitions, the code now properly increments
the document's revision number before creating the transition. This ensures
the transfer transition uses revision + 1 instead of the current revision,
which is required for proper state transition validation on the platform.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
@thephez thephez added this to the v2.1 milestone Aug 28, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 28, 2025

Walkthrough

Refactors document transition flows to compute a next revision, construct a new DocumentV0 with revision = current_revision + 1, and pass that document into dedicated BatchTransition constructors for transfer, purchase, and price-update flows; removes in-place document mutations and entropy generation for price updates.

Changes

Cohort / File(s) Summary
Revision-bump transition refactor
packages/wasm-sdk/src/state_transitions/documents/mod.rs
Add private helper to compute next revision (errors: "Document revision is missing" and "Document revision overflow"); replace in-place document mutations across transfer, purchase (including price validation), and set_price flows by creating new DocumentV0 with incremented revision and using BatchTransition::new_*_from_document constructors; remove entropy generation for price updates.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant Docs as Document logic
  participant Builder as StateTransitionBuilder
  participant Batch as BatchTransition

  rect rgba(200,235,255,0.18)
    note over Caller,Docs: Transfer / Purchase / Set Price flows
    Caller->>Docs: fetch current document
    Docs->>Docs: get_next_revision(document)
    Docs->>Docs: create new DocumentV0 (revision = current + 1)
    Docs->>Builder: build transition from new document
    alt Transfer
      Builder->>Batch: new_document_transfer_transition_from_document(new_doc)
    else Purchase
      Builder->>Batch: new_document_purchase_transition_from_document(new_doc)
    else Set Price
      Builder->>Batch: new_document_update_price_transition_from_document(new_doc)
    end
    Batch-->>Caller: transition ready
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested reviewers

  • QuantumExplorer
  • pauldelucia

Poem

A hop, a nudge — the revision grows by one,
I craft a fresh page when the old is done.
No in-place scratches, no entropy fuss,
Transitions march forward — neat, not muss.
Carrot-tipped pen, I stamp: revision run. 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch wasm-sdk-fix-nft-transitions

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@thephez thephez requested a review from pauldelucia August 28, 2025 21:09
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 (2)
packages/wasm-sdk/src/state_transitions/documents/mod.rs (2)

1305-1318: Be explicit about Credits type for forward-compat
Passing u64 relies on Credits being a type alias; cast explicitly to avoid a future break if Credits becomes a newtype.

Apply:

-            price,
+            price as Credits,

968-987: DRY the “clone-and-bump revision” pattern
This block repeats across transfer, purchase, and price-set. Extract a helper to reduce duplication and ensure consistent safety checks.

Example:

fn clone_with_bumped_revision(src: &Document) -> Result<Document, JsValue> {
    let cur = src.revision().ok_or_else(|| JsValue::from_str("Document revision is required"))?;
    let next = cur.checked_add(1).ok_or_else(|| JsValue::from_str("Document revision overflow"))?;
    Ok(Document::V0(DocumentV0 {
        id: src.id(),
        owner_id: src.owner_id(),
        properties: src.properties().clone(),
        revision: Some(next),
        created_at: src.created_at(),
        updated_at: src.updated_at(),
        transferred_at: src.transferred_at(),
        created_at_block_height: src.created_at_block_height(),
        updated_at_block_height: src.updated_at_block_height(),
        transferred_at_block_height: src.transferred_at_block_height(),
        created_at_core_block_height: src.created_at_core_block_height(),
        updated_at_core_block_height: src.updated_at_core_block_height(),
        transferred_at_core_block_height: src.transferred_at_core_block_height(),
    }))
}

Then call it where needed.

Also applies to: 1112-1131, 1273-1287

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 23125f8 and 4c72075.

📒 Files selected for processing (1)
  • packages/wasm-sdk/src/state_transitions/documents/mod.rs (6 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
packages/wasm-sdk/src/**/*.rs

📄 CodeRabbit inference engine (packages/wasm-sdk/CLAUDE.md)

packages/wasm-sdk/src/**/*.rs: When implementing WASM SDK functionality, always refer to AI_REFERENCE.md first for accurate method signatures and examples.
For WASM builds, fix 'time not implemented on this platform' errors by using js_sys::Date::now().
Token functions are methods on WasmSdk, not standalone functions; avoid importing them as standalone.
The WASM SDK now fully supports where and orderBy clauses for document queries; use the specified JSON array formats and supported operators.

Files:

  • packages/wasm-sdk/src/state_transitions/documents/mod.rs
🧠 Learnings (1)
📓 Common learnings
Learnt from: CR
PR: dashpay/platform#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:05.082Z
Learning: Documents and data contracts should use state transitions for updates
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Build JS packages / Build JS
  • GitHub Check: Rust crates security audit
  • GitHub Check: build-wasm-sdk

Replace unsafe revision defaulting with explicit error handling in document
state transitions. Add helper method for safe revision increment with overflow
protection. Affects transfer, purchase, delete, and price update operations.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
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-sdk/src/state_transitions/documents/mod.rs (1)

1194-1196: Avoid unwrap_or(0) when reporting revision in result

Even for UI, defaulting to 0 can mask issues. Push the revision only if present.

Apply:

-                        additional_fields.push(("documentUpdated", JsValue::from_bool(true)));
-                        additional_fields.push(("revision", JsValue::from_f64(doc.revision().unwrap_or(0) as f64)));
+                        additional_fields.push(("documentUpdated", JsValue::from_bool(true)));
+                        if let Some(rev) = doc.revision() {
+                            additional_fields.push(("revision", JsValue::from_f64(rev as f64)));
+                        }
🧹 Nitpick comments (3)
packages/wasm-sdk/src/state_transitions/documents/mod.rs (3)

188-196: Safe revision bump helper is solid; minor nit on error context

Centralizing the checked increment is great. Consider adding optional operation context (e.g., "transfer"/"purchase"/"price update") to the error to aid debugging, or let callers augment it.


1316-1321: Nit: pass matching_key by reference consistently

Elsewhere you pass a borrowed key directly (matching_key). Here you pass &matching_key (an extra reference). Both compile due to auto-deref, but consistency helps.

Apply:

-            price,
-            &matching_key,
+            price,
+            matching_key,

554-571: Optional: guard replace-path increment with checked_add for parity

document_replace still does revision + 1. For parity with other flows and to avoid silent overflow in release builds, use checked_add.

Apply:

-        // Create the document using the DocumentV0 constructor
-        let platform_version = sdk.version();
+        // Create the document using the DocumentV0 constructor
+        let platform_version = sdk.version();
+        let next_revision = revision
+            .checked_add(1)
+            .ok_or_else(|| JsValue::from_str("Document revision overflow"))?;
         let document = Document::V0(DocumentV0 {
             id: doc_id,
             owner_id: owner_identifier,
             properties: document_data_platform_value
                 .into_btree_string_map()
                 .map_err(|e| JsValue::from_str(&format!("Failed to convert document data: {}", e)))?,
-            revision: Some(revision + 1),
+            revision: Some(next_revision),
             created_at: None,
             updated_at: None,
             transferred_at: None,
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4c72075 and a2e615f.

📒 Files selected for processing (1)
  • packages/wasm-sdk/src/state_transitions/documents/mod.rs (8 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
packages/wasm-sdk/src/**/*.rs

📄 CodeRabbit inference engine (packages/wasm-sdk/CLAUDE.md)

packages/wasm-sdk/src/**/*.rs: When implementing WASM SDK functionality, always refer to AI_REFERENCE.md first for accurate method signatures and examples.
For WASM builds, fix 'time not implemented on this platform' errors by using js_sys::Date::now().
Token functions are methods on WasmSdk, not standalone functions; avoid importing them as standalone.
The WASM SDK now fully supports where and orderBy clauses for document queries; use the specified JSON array formats and supported operators.

Files:

  • packages/wasm-sdk/src/state_transitions/documents/mod.rs
🧠 Learnings (1)
📓 Common learnings
Learnt from: CR
PR: dashpay/platform#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:05.082Z
Learning: Documents and data contracts should use state transitions for updates
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Build JS packages / Build JS
  • GitHub Check: Rust crates security audit
  • GitHub Check: build-wasm-sdk
🔇 Additional comments (6)
packages/wasm-sdk/src/state_transitions/documents/mod.rs (6)

847-849: Delete uses actual current revision (no silent default)

Correct to require Some(revision) without incrementing for deletion transitions.


978-996: Transfer: correct use of next revision and derived doc

Good: next_revision via helper and passing a cloned properties map. Please confirm that any sale-related fields (like $price) are handled by the transfer transition (cleared if needed) to avoid stale metadata on the new owner.


1015-1017: Transfer transition now uses revised document

Looks correct and consistent with the API.


1122-1140: Purchase: safe bump + derived doc — verify platform-side field updates

Good: next_revision and keeping owner_id as the current owner while the transition applies the change. Please verify DPP clears $price and updates ownership in the transition to prevent property drift.


1159-1161: Purchase transition call uses revised document

Looks good.


1279-1297: Price update: consistent safe bump and derived doc

Good refactor toward dedicated update flow using a new document with incremented revision.

@QuantumExplorer QuantumExplorer merged commit 82c65ca into v2.1-dev Sep 3, 2025
17 of 21 checks passed
@QuantumExplorer QuantumExplorer deleted the wasm-sdk-fix-nft-transitions branch September 3, 2025 16:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants