Skip to content

Conversation

pauldelucia
Copy link
Member

@pauldelucia pauldelucia commented Aug 18, 2025

Issue being fixed or feature implemented

We had four token transitions unimplemented in the wasm-sdk

What was done?

Implement in Rust and the HTML UI

How Has This Been Tested?

Added tests but haven't confirmed they work yet using the UI.

Breaking Changes

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

    • Token ops: Transfer, Freeze, Unfreeze, Destroy Frozen added with optional Public Note and recipient/target identity parameters.
    • Identity: Credit Transfer and Credit Withdrawal transitions added.
  • Refactor

    • Parameter renames/shape changes: token contract referenced by position, amounts treated as text, identity-related fields clarified and standardized.
  • Documentation

    • Updated examples, parameter names, and per-transition examples; docs include a hidden test runner UI, offline caching, and smoother anchor scrolling.
  • Tests

    • New token transition test suite and README.

Copy link
Contributor

coderabbitai bot commented Aug 18, 2025

Walkthrough

Documentation and API definitions updated to use per-transition sdk_params and new parameter names/types; docs UI and examples adjusted; WASM SDK Rust token state transitions (transfer, freeze, unfreeze, destroy-frozen) implemented and accept an optional public_note; tests and doc-generation logic updated; docs_manifest timestamp bumped.

Changes

Cohort / File(s) Summary of changes
Docs & Reference
packages/wasm-sdk/AI_REFERENCE.md, packages/wasm-sdk/docs.html, packages/wasm-sdk/docs.css
Reformat identity examples (assetLockProof → Asset Lock Proof, assetLockProofPrivateKey, publicKeys), convert examples to identityHex/privateKeyHex param-block style, rename token fields (e.g., tokenIdtokenPosition), add optional publicNote across many token transitions, add client-side test runner UI and small CSS tweaks.
API Definitions & Manifest
packages/wasm-sdk/api-definitions.json, packages/wasm-sdk/docs_manifest.json
Add per-transition sdk_params and sdk_example for identity create/top-up; rename and type-change token inputs (tokenPosition, amount types to text/number as noted); add publicNote optional input across many token endpoints; update docs_manifest generated_at timestamp.
Web Demo / UI Integration
packages/wasm-sdk/index.html
Add demo branches for tokenTransfer, tokenFreeze, tokenUnfreeze, tokenDestroyFrozen; wire new params (tokenPosition, publicNote, etc.) into executeStateTransition and render JSON results.
Rust: Token State Transitions
packages/wasm-sdk/src/state_transitions/tokens/mod.rs
Implement token transfer, freeze, unfreeze, and destroy-frozen flows (previously stubs); add public_note: Option<String> to public function signatures; parse/validate parameters, resolve identities/contracts, derive signer, construct and sign transitions (include public_note), broadcast and format results; add helpers and doc comments.
Docs Generation Logic
packages/wasm-sdk/generate_docs.py
Prefer per-transition sdk_params over legacy inputs, add params_to_use selector, render descriptions/examples accordingly, allow per-transition sdk_example, and update generate_transition_example signature to accept an optional transition.
Tests & Test Docs
packages/wasm-sdk/test/token-transitions.test.mjs, packages/wasm-sdk/test/README_TOKEN_TESTS.md
Add integration test script for token transitions exercising invalid-input and permission paths; add README describing tests, run instructions, and expected behaviors.

Sequence Diagram(s)

sequenceDiagram
  participant UI as Docs/Web Demo
  participant SDK as WASM SDK (JS)
  participant Core as WASM Rust Tokens
  participant Node as Platform

  UI->>SDK: executeStateTransition(tokenTransfer, params)
  SDK->>Core: token_transfer(contractId, tokenPosition, amount, senderId, recipientId, privKey, publicNote?)
  Core->>Core: Validate inputs, resolve identities & contract, compute tokenId
  Core->>Core: Build & sign batch transition (include public_note if provided)
  Core->>Node: Broadcast transition
  Node-->>Core: Proof / result
  Core-->>SDK: Formatted result
  SDK-->>UI: Render JSON outcome
Loading
sequenceDiagram
  participant UI as Docs/Web Demo
  participant SDK as WASM SDK (JS)
  participant Core as WASM Rust Tokens
  participant Node as Platform

  UI->>SDK: executeStateTransition(tokenFreeze/Unfreeze/DestroyFrozen, params)
  SDK->>Core: token_freeze/unfreeze/destroy_frozen(..., publicNote?)
  Core->>Core: Validate identities, map tokenPosition → tokenId
  Core->>Core: Build & sign batch transition (with public_note)
  Core->>Node: Broadcast
  Node-->>Core: Result
  Core-->>SDK: Result
  SDK-->>UI: Display outcome
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • ktechmidas
  • shumkov

Poem

Hop hop, I stamp my tiny paw,
Notes go public, tokens thaw.
Seeds now sprout where proofs once lay,
Freeze, unfreeze, and send away.
I twitch my whiskers — code hops through! 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/implement-missing-token-transitions-wasm-sdk

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 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.

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

🔭 Outside diff range comments (2)
packages/wasm-sdk/docs.html (1)

2662-2690: Fix Token Transfer example: method name, parameter names, and types should match the API.

  • Method name should be camelCase tokenTransfer (consistent with other transitions), not token_transfer.
  • Use tokenPosition (number) instead of tokenId.
  • Amount input is documented as text; pass a string in the example.
  • Include the optional publicNote parameter positionally if the SDK signature exposes it.

Apply the following patch to the example block:

-                <div class="example-code">const result = await sdk.token_transfer(
+                <div class="example-code">const result = await sdk.tokenTransfer(
     identityHex,
     contractId,
-    tokenId,
-    1000000, // amount
+    tokenPosition,
+    "1000000", // amount as string
     recipientId,
+    /* publicNote */ null,
     privateKeyHex
 );</div>

Also applies to: 2695-2702

packages/wasm-sdk/api-definitions.json (1)

1182-2149: Docs & Reference Examples Out of Sync with API Definitions

The UI and SDK use camel-case tokenTransfer(...) with a tokenPosition parameter and optional publicNote, but several docs and auto-generated examples still show:

  • Snake-case calls (sdk.token_transfer)
  • A tokenId parameter in place of tokenPosition
  • Missing optional publicNote and privateKey args
  • Examples in AI_REFERENCE.md, docs.html, and generate_docs.py that don’t match the API definitions or index.html execution paths

Please update the following to match the canonical transitions in api-definitions.json and index.html:

• Replace all sdk.token_transfer(...) examples with sdk.tokenTransfer(contractId, tokenPosition, amount, senderId, recipientId, privateKey, publicNote)
• Change tokenIdtokenPosition in examples for token transfers and pricing
• Include the optional publicNote (and privateKey) parameters where applicable
• Ensure generate_docs.py and AI_REFERENCE.md examples use camelCase and the correct parameter order

🧹 Nitpick comments (15)
packages/wasm-sdk/src/state_transitions/tokens/mod.rs (7)

58-86: Fetching and trusted-context caching is sensible; avoid unwrap() to prevent panics in WASM

The fetch+cache logic is solid. Small polish: replace lock().unwrap() with a non-panicking guard to avoid poisoning/panics in the browser environment.

Apply this minimal change pattern:

- if let Some(ref context) = *crate::sdk::TESTNET_TRUSTED_CONTEXT.lock().unwrap() {
+ if let Ok(guard) = crate::sdk::TESTNET_TRUSTED_CONTEXT.lock() {
+   if let Some(ref context) = *guard {
      context.add_known_contract(data_contract.clone());
- }
+   }
+ }

Do the same for MAINNET_TRUSTED_CONTEXT.


90-126: Reasonable JS result formatter for token proof results

Covers the common token-related proof variants and returns structured JSON. For future-proofing, consider logging the variant on the unexpected path to aid debugging.


337-345: Parsing sender/amount via helper is fine; consider validating recipient presence earlier

You parse sender/amount and then recipient separately. That’s fine. If you want earlier UX errors, consider checking for empty recipient_id on the JS side too (optional).


353-369: Key lookup and signer creation pattern repeated across transitions; extract a helper

The identity fetch -> key match -> signer creation sequence is duplicated across transfer/freeze/unfreeze/destroy. Extracting a small helper will reduce duplication and centralize error text.

Example helper (outside selected ranges, for illustration):

impl WasmSdk {
    async fn signer_ctx(
        &self,
        actor_id: Identifier,
        contract_id: Identifier,
        private_key_wif: &str,
    ) -> Result<(dash_sdk::platform::Identity, IdentityPublicKey, simple_signer::SingleKeySigner, u64), JsValue> {
        let sdk = self.inner_clone();
        let identity = dash_sdk::platform::Identity::fetch(&sdk, actor_id)
            .await
            .map_err(|e| JsValue::from_str(&format!("Failed to fetch identity: {}", e)))?
            .ok_or_else(|| JsValue::from_str("Identity not found"))?;
        let (_, key) = crate::sdk::WasmSdk::find_authentication_key(&identity, private_key_wif)?;
        let signer = crate::sdk::WasmSdk::create_signer_from_wif(private_key_wif, sdk.network)?;
        let nonce = sdk
            .get_identity_contract_nonce(actor_id, contract_id, true, None)
            .await
            .map_err(|e| JsValue::from_str(&format!("Failed to fetch nonce: {}", e)))?;
        Ok((identity, key, signer, nonce))
    }
}

Then reuse in each transition.


433-446: Avoid parsing a dummy amount "0" for non-amount ops

Using "0" to satisfy parse_token_params works but is semantically odd. Consider a variant of parse_token_params that doesn’t require amount when not needed.


525-538: Same note as freeze: avoid the "0" amount workaround

See comment on Lines 433-446; consider a parse path not requiring amount.


617-631: Same parse concern: prefer a non-amount helper for non-amount ops

Repeating the suggestion to avoid the "0" amount sentinel.

packages/wasm-sdk/index.html (1)

3209-3253: UI wiring for the 4 token transitions matches SDK signatures; minor naming nit

All four branches pass the correct arguments, including tokenPosition as Number(...) and optional publicNote. One nit: in tokenDestroyFrozen you reuse values.identityId for the target identity while identityId (auth) is also in scope. Consider renaming the dynamic input to targetIdentityId (or identityToDestroy) to avoid confusion.

If you adopt the rename in api-definitions.json, update this block accordingly:

-            values.identityId, // identity whose frozen tokens to destroy
+            values.targetIdentityId, // identity whose frozen tokens to destroy
packages/wasm-sdk/AI_REFERENCE.md (3)

760-767: AI_REFERENCE should document SDK method parameters, not UI form fields

Listing seedPhrase/generateSeedButton/keyPreview as parameters in AI_REFERENCE blurs the line between SDK API and UI inputs. Consider moving UI-only inputs to docs.html and keeping AI_REFERENCE focused on actual SDK call signatures.


776-783: TopUp parameters unclear vs. actual flow (asset lock proof)

The UI and code still use asset lock proof for identityTopUp in index.html, but this section lists only identityId. Please align AI_REFERENCE with the actual SDK method signature/requirements or clearly note UI-only behavior.

Would you like me to propose a corrected parameter section for identityTopUp based on the current SDK?


1140-1148: Destroy Frozen parameters updated; consider clarifying target identity label

The term identityId here refers to the target whose frozen tokens are destroyed. Consider labeling it targetIdentityId for clarity (and to avoid confusion with the authenticated identity).

Provide a matching update to the example invocation if you adopt the rename.

packages/wasm-sdk/docs.html (3)

1985-1985: Identity Create example likely incorrect: remove identityHex and reflect seed-based inputs.

The example shows sdk.identityCreate(identityHex, /* params */, privateKeyHex), but identity creation derives an identity from seed phrase and index; it does not take an existing identityHex. Please update the example to reflect the real signature/order used by the SDK (seedPhrase, identityIndex, maybe keySelectionMode/addPublicKeys, plus signing key material if applicable).

Would you like me to propose a concrete example after confirming the exact signature from AI_REFERENCE.md?


2769-2793: Token Destroy Frozen: label/inputs are correct; minor grammar tweak suggested.

The rename and the addition of publicNote are correct. The label “Identity ID whose frozen tokens to destroy” is a bit awkward. Suggest:

  • “Identity ID to destroy frozen tokens for”
  • or “Identity ID whose frozen tokens will be destroyed”

If you prefer the first option, here’s a localized diff for this doc snippet:

-                    <span class="param-name">Identity ID whose frozen tokens to destroy</span>
+                    <span class="param-name">Identity ID to destroy frozen tokens for</span>

1-349: Optional: guard “eval-like” example execution with minimal sanitization.

Examples are executed via new Function using DOM text. While this is a docs page, a minimal check against accidental script tags or inline HTML in code blocks would reduce risk if content is ever user-modifiable.

Also applies to: 2878-3096

packages/wasm-sdk/api-definitions.json (1)

2013-2041: Token Destroy Frozen: rename and inputs look correct; grammar nit on identity label.

The label rename to “Token Destroy Frozen” and adding publicNote are correct. Consider improving the identity label phrasing:

-              "label": "Identity ID whose frozen tokens to destroy",
+              "label": "Identity ID to destroy frozen tokens for",
📜 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 bcdda30 and 8164265.

📒 Files selected for processing (6)
  • packages/wasm-sdk/AI_REFERENCE.md (3 hunks)
  • packages/wasm-sdk/api-definitions.json (6 hunks)
  • packages/wasm-sdk/docs.html (10 hunks)
  • packages/wasm-sdk/docs_manifest.json (1 hunks)
  • packages/wasm-sdk/index.html (1 hunks)
  • packages/wasm-sdk/src/state_transitions/tokens/mod.rs (8 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
packages/wasm-sdk/index.html

📄 CodeRabbit Inference Engine (CLAUDE.md)

Test the WASM SDK using the web interface at 'index.html' in 'packages/wasm-sdk'

Files:

  • packages/wasm-sdk/index.html
packages/wasm-sdk/**/index.html

📄 CodeRabbit Inference Engine (packages/wasm-sdk/CLAUDE.md)

packages/wasm-sdk/**/index.html: When adding new queries or state transitions, update the definitions in index.html.
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/index.html
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/tokens/mod.rs
🧠 Learnings (10)
📚 Learning: 2025-07-23T08:31:42.268Z
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/**/index.html : When adding new queries or state transitions, update the definitions in index.html.

Applied to files:

  • packages/wasm-sdk/docs_manifest.json
  • packages/wasm-sdk/index.html
  • packages/wasm-sdk/docs.html
📚 Learning: 2025-07-23T08:31:42.268Z
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/src/**/*.rs : For WASM builds, fix 'time not implemented on this platform' errors by using js_sys::Date::now().

Applied to files:

  • packages/wasm-sdk/docs_manifest.json
📚 Learning: 2025-07-23T08:31:42.268Z
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/**/index.html : The WASM SDK now fully supports where and orderBy clauses for document queries; use the specified JSON array formats and supported operators.

Applied to files:

  • packages/wasm-sdk/docs_manifest.json
  • packages/wasm-sdk/index.html
  • packages/wasm-sdk/docs.html
📚 Learning: 2025-07-23T08:31:42.268Z
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/**/generate_docs.py : When adding new queries or state transitions, run python3 generate_docs.py to regenerate documentation.

Applied to files:

  • packages/wasm-sdk/docs_manifest.json
📚 Learning: 2025-07-23T08:31:05.082Z
Learnt from: CR
PR: dashpay/platform#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:05.082Z
Learning: Applies to packages/wasm-sdk/generate_docs.py : Keep documentation for the WASM SDK in sync by running 'python3 generate_docs.py' in 'packages/wasm-sdk'

Applied to files:

  • packages/wasm-sdk/docs_manifest.json
📚 Learning: 2025-07-28T20:00:08.502Z
Learnt from: QuantumExplorer
PR: dashpay/platform#2711
File: packages/wasm-sdk/AI_REFERENCE.md:771-783
Timestamp: 2025-07-28T20:00:08.502Z
Learning: In packages/wasm-sdk/AI_REFERENCE.md, the documentation correctly shows the actual SDK method signatures (including identityCreate and identityTopUp with their full parameter lists), which may differ from the UI inputs shown in fixed_definitions.json. The UI may collect fewer parameters from users while handling additional requirements internally.

Applied to files:

  • packages/wasm-sdk/index.html
  • packages/wasm-sdk/docs.html
  • packages/wasm-sdk/AI_REFERENCE.md
  • packages/wasm-sdk/api-definitions.json
📚 Learning: 2025-07-23T08:31:42.268Z
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/src/**/*.rs : Token functions are methods on WasmSdk, not standalone functions; avoid importing them as standalone.

Applied to files:

  • packages/wasm-sdk/index.html
  • packages/wasm-sdk/src/state_transitions/tokens/mod.rs
📚 Learning: 2025-07-23T08:31:42.268Z
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/src/**/*.rs : When implementing WASM SDK functionality, always refer to AI_REFERENCE.md first for accurate method signatures and examples.

Applied to files:

  • packages/wasm-sdk/src/state_transitions/tokens/mod.rs
  • packages/wasm-sdk/AI_REFERENCE.md
📚 Learning: 2025-07-28T20:00:24.323Z
Learnt from: QuantumExplorer
PR: dashpay/platform#2711
File: packages/wasm-sdk/docs.html:2359-2383
Timestamp: 2025-07-28T20:00:24.323Z
Learning: In packages/wasm-sdk/docs.html, QuantumExplorer confirmed that placeholder private keys in documentation examples are acceptable as they are not real keys, though field name accuracy for the SDK API should still be maintained.

Applied to files:

  • packages/wasm-sdk/docs.html
  • packages/wasm-sdk/AI_REFERENCE.md
📚 Learning: 2025-07-23T08:31:05.082Z
Learnt from: CR
PR: dashpay/platform#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:05.082Z
Learning: Applies to packages/wasm-sdk/index.html : Test the WASM SDK using the web interface at 'index.html' in 'packages/wasm-sdk'

Applied to files:

  • packages/wasm-sdk/docs.html
⏰ 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). (4)
  • GitHub Check: Build JS packages / Build JS
  • GitHub Check: Rust crates security audit
  • GitHub Check: build-and-test-wasm-sdk
  • GitHub Check: build-wasm-sdk
🔇 Additional comments (26)
packages/wasm-sdk/docs_manifest.json (1)

2-2: Manifest and docs generator sync verified

The generated_at timestamp bump is correct, and a quick grep confirms that the new token transitions (tokenTransfer, tokenFreeze, tokenUnfreeze, tokenDestroyFrozen) and publicNote params are present in both packages/wasm-sdk/api-definitions.json and packages/wasm-sdk/docs_manifest.json. No further action needed.

packages/wasm-sdk/src/state_transitions/tokens/mod.rs (11)

29-55: Good parameter parsing helper; clear error messages

The helper cleanly parses contract/identity/recipient and token amount, with specific error strings. Using Base58 for identifiers matches the UI inputs.


326-335: JS signature and parameters for tokenTransfer are correct (incl. optional public_note)

Matches the wasm_bindgen(js_name = tokenTransfer) export and threads public_note as Option.


371-395: Transition construction arguments match API evolution (tokenPosition, public_note, notes placeholders)

The call to new_token_transfer_transition appears aligned with the updated DPP API: token_id, sender, contract_id, token_position, amount, recipient, public_note, and note placeholders. Looks good.


421-429: tokenFreeze signature is correct (identity_to_freeze + public_note)

WASM export name and parameter list match the documented API changes.


472-486: Freeze transition wiring looks correct

Correctly uses frozen_identity_id, public_note, and per-contract nonce; consistent with other transitions.


513-521: tokenUnfreeze signature is correct and consistent with docs

Matches identity_to_unfreeze and public_note.


565-579: Unfreeze transition construction is aligned; LGTM

Parameters passed align with DPP expectations; error mapping is consistent.


605-613: tokenDestroyFrozen signature threads public_note; naming is clear on caller vs target identity

Good separation of destroyer_id (actor) and identity_id (target whose funds are destroyed).


656-670: Destroy-frozen transition wiring is sound

Correct token_id derivation, actor/target identities, and public_note threading. Error messages are specific and helpful.


129-221: Context: unchanged mint/burn appear aligned with new patterns

Mint/Burn incorporate public_note and use the same helper patterns, consistent with the four newly implemented transitions.

Also applies to: 237-308


286-298: All wasm_bindgen exports match UI calls

I’ve confirmed that in packages/wasm-sdk/src/state_transitions/tokens/mod.rs the following js_name values…

• tokenTransfer
• tokenFreeze
• tokenUnfreeze
• tokenDestroyFrozen

…are all defined on their respective methods, and each is invoked exactly as sdk.tokenTransfer(), sdk.tokenFreeze(), sdk.tokenUnfreeze(), and sdk.tokenDestroyFrozen() in index.html. No discrepancies found.

packages/wasm-sdk/AI_REFERENCE.md (4)

768-771: Example is generic enough; OK as a placeholder

Example invocation uses a param block placeholder. Fine if paired with a proper parameter table elsewhere that matches the actual SDK signature.


790-790: Updated example for addPublicKeys looks good

Using ECDSA_HASH160/AUTHENTICATION is consistent with recent conventions.


1112-1124: Freeze parameters updated correctly (identityToFreeze, tokenPosition, publicNote)

This section matches the implemented Rust/JS signatures.


1127-1138: Unfreeze parameters updated correctly (identityToUnfreeze, tokenPosition, publicNote)

Consistent with code changes.

packages/wasm-sdk/docs.html (5)

468-468: TOC entry rename looks good.

Sidebar item updated to “Token Destroy Frozen,” matching the new section id and label.


1955-1979: Seed-based Identity Create UI parameters: good addition; consider tightening example consistency.

The parameter set (Seed Phrase, Generate New Seed, Identity Index, Key Selection Mode, Keys preview) aligns with the seed-based flow. However, ensure downstream examples accurately reflect the actual SDK signature for identity creation (see comment on Line 1985).


2706-2729: Freeze transition text and inputs align with new API.

Description, tokenPosition as number, identityToFreeze, and optional Public Note look consistent with api-definitions and the Rust signatures.


2738-2761: Unfreeze transition text and inputs align with new API.

Description, tokenPosition as number, identityToUnfreeze, and optional Public Note look consistent with api-definitions and the Rust signatures.


2695-2702: Add consistency note: include publicNote positional argument as shown in parameters.

The parameters list includes Public Note (optional). The example now includes it (after the previous patch). Ensure this ordering matches the SDK signature used in index.html to avoid user confusion.

packages/wasm-sdk/api-definitions.json (5)

1918-1951: Token Transfer inputs updated correctly; ensure UI/SDK usage matches.

  • Description now “Transfer tokens between identities.”
  • tokenPosition switched to number; amount to text.
  • Optional publicNote added.

These changes align with the PR goals and Rust signatures. Please verify index.html collects/sends these in this order.


1954-1981: Token Freeze inputs and naming are consistent with new conventions.

  • tokenPosition as number.
  • identityToFreeze naming is clearer.
  • optional publicNote added.

Looks good.


1984-2011: Token Unfreeze inputs align with Freeze: consistency achieved.

  • tokenPosition as number.
  • identityToUnfreeze naming.
  • optional publicNote.

All consistent across Freeze/Unfreeze.


1656-1673: Public Note additions across token operations are consistent.

Adding publicNote (optional) to Burn, Mint, and Claim maintains a uniform UX for annotating transitions.

Also applies to: 1692-1709, 1728-1749


1927-1935: Confirm tokenPosition type changes are reflected in the UI validators.

All four transitions now expect tokenPosition as a number. Ensure any client-side validation or parsing expects numbers and that index.html casts appropriately before calling into the SDK.

Also applies to: 1963-1971, 1993-2001, 2023-2031

Comment on lines +1091 to 1099
*Transfer tokens between identities*

Parameters (in addition to identity/key):
- `contractId` (text, required) - Data Contract ID
- `tokenId` (text, required) - Token Contract Position
- `amount` (number, required) - Amount to Transfer
- `tokenPosition` (number, required) - Token Contract Position
- `amount` (text, required) - Amount to Transfer
- `recipientId` (text, required) - Recipient Identity ID
- `publicNote` (text, optional) - Public Note

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

Token Transfer params are correct; fix the example below (uses old tokenId and method name)

The parameter table shows tokenPosition and publicNote, but the example still uses token_transfer and tokenId. Update the example to match the exported JS name and parameters.

Apply this diff:

-```javascript
-const result = await sdk.token_transfer(
-    identityHex,
-    contractId,
-    tokenId,
-    1000000, // amount
-    recipientId,
-    privateKeyHex
-);
-```
+```javascript
+const result = await sdk.tokenTransfer(
+  contractId,          // data contract ID (base58)
+  tokenPosition,       // number
+  "1000000",           // amount as text
+  identityHex,         // sender identity (auth)
+  recipientId,         // recipient identity (base58)
+  privateKeyHex,       // signing key
+  /* publicNote? */     // optional
+);
+```
🤖 Prompt for AI Agents
packages/wasm-sdk/AI_REFERENCE.md around lines 1091-1099: the example uses the
old token_transfer name and tokenId param but the docs list tokenPosition and
publicNote; update the example to call sdk.tokenTransfer with the new parameter
order: contractId, tokenPosition (number), amount as a string, identityHex
(sender auth), recipientId, privateKeyHex (signing key), and optionally
publicNote; replace the old snippet entirely with a JavaScript fenced example
reflecting these arguments and types.

Copy link
Collaborator

Choose a reason for hiding this comment

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

I think we shouldn't put all these ai generated files in the repo. Imo, they clutter it and will almost immediately be outdated.

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

🧹 Nitpick comments (10)
packages/wasm-sdk/test/token-transitions.test.mjs (6)

23-30: Guard WASM init with clearer error reporting

If pkg/wasm_sdk_bg.wasm is missing (e.g., build not run), the script will throw a low-signal error. Wrap init in try/catch to fail fast with guidance.

 console.log('Initializing WASM SDK...');
-const wasmPath = join(__dirname, '../pkg/wasm_sdk_bg.wasm');
-const wasmBuffer = readFileSync(wasmPath);
-await init(wasmBuffer);
+try {
+  const wasmPath = join(__dirname, '../pkg/wasm_sdk_bg.wasm');
+  const wasmBuffer = readFileSync(wasmPath);
+  await init(wasmBuffer);
+} catch (e) {
+  console.error('Failed to initialize WASM. Did you run ./build.sh to generate pkg/?');
+  throw e;
+}

55-60: Confirm Node runtime has fetch or polyfill it

prefetch_trusted_quorums_testnet likely uses fetch; Node < 18 won’t have it by default. You’re swallowing errors here (fine), but subsequent tests that rely on network may error differently on Node < 18. Ensure CI uses Node >= 18 or add a lightweight polyfill.

Would you like me to add a guarded undici-based polyfill snippet that activates only when fetch is missing?


65-71: Avoid committing real-looking private keys; allow env override

Even if this is a dummy WIF, let tests read from an env var to prevent accidental secret leakage patterns.

-const TEST_PRIVATE_KEY = 'KycRvJNvCVapwvvpRLWz76qXFAbXFfAqhG9FouVjUmDVZ6UtZfGa'; // Dummy key for testing
+// Prefer providing TEST_PRIVATE_KEY via environment; falls back to a non-funded dummy key.
+const TEST_PRIVATE_KEY = process.env.TEST_PRIVATE_KEY
+  || 'KycRvJNvCVapwvvpRLWz76qXFAbXFfAqhG9FouVjUmDVZ6UtZfGa';

141-159: Clarify variable naming for freeze target

You’re passing TEST_RECIPIENT_ID as the identity to freeze. To reduce ambiguity between transfer “recipient” and “identity to freeze,” consider a dedicated name (e.g., TEST_TARGET_IDENTITY).

If helpful, I can generate a small refactor to introduce an alias constant and update the call sites.


330-344: Method availability check is good; consider arity sanity checks

Presence checks are good. Optionally, assert minimal arity to catch signature regressions, while acknowledging minified wrappers can obscure .length.

Example:

  • if (sdk.tokenTransfer.length < 6) throw new Error('tokenTransfer signature changed unexpectedly');

35-45: Reduce repetitive try/catch boilerplate

The repeated “expect failure” pattern can be centralized for readability and consistency.

 let failed = 0;
 
 async function test(name, fn) {
   try {
     await fn();
     console.log(`✅ ${name}`);
     passed++;
   } catch (error) {
     console.log(`❌ ${name}`);
     console.log(`   ${error.message}`);
     failed++;
   }
 }
+
+// Optional helper for expected-failure cases
+async function expectFailure(name, invoke) {
+  await test(name, async () => {
+    try {
+      await invoke();
+      throw new Error('Should fail');
+    } catch (error) {
+      if (error && typeof error.message === 'string' && error.message.includes('Should fail')) {
+        throw error;
+      }
+      // Expected failure path
+    }
+  });
+}

You can then replace repetitive blocks with:

  • await expectFailure('tokenTransfer - should validate parameters', () => sdk.tokenTransfer(...));
packages/wasm-sdk/test/README_TOKEN_TESTS.md (4)

3-5: Add prerequisites (Node >= 18, built pkg) for smoother runs

Explicitly stating Node version and build artifacts helps avoid init/fetch errors when running tests.

 ## Overview
 This directory contains tests for the token state transitions in the WASM SDK.
 
+## Prerequisites
+- Node.js 18+ (global fetch and webcrypto available)
+- Run `./build.sh` first to generate `packages/wasm-sdk/pkg/` artifacts

16-22: Tighten wording and list formatting

Minor editorial pass for clarity and style.

-### token-transitions.test.mjs
-New test file that tests the four newly implemented token transitions:
-- Tests parameter validation
-- Tests error handling for invalid inputs
-- Tests permission requirements
-- Verifies all methods are available on the SDK instance
+### token-transitions.test.mjs
+This file exercises the four newly implemented token transitions:
+- Validates parameter handling
+- Verifies error paths for invalid inputs
+- Checks permission requirements
+- Confirms methods exist on the SDK instance

49-57: Clarify expected outcomes; note network access assumption

Tweak phrasing and call out the Node 18/fetch requirement so “attempt to connect” expectations are clear.

-Most tests will fail with permission/identity errors, which is expected behavior since we're testing without real funded identities. The important validations are:
+Most tests will fail with permission/identity errors when run without funded/authorized identities. This is expected. The important validations are:
@@
-4. The methods attempt to connect to the network (even if they fail due to permissions)
+4. The methods attempt to connect to the network (requires Node 18+ for global fetch), even if they later fail due to permissions

58-64: Align README with AI_REFERENCE signatures and docs generation process

Given prior learnings, ensure AI_REFERENCE.md reflects the final method signatures and regenerate docs if needed.

Would you like me to update AI_REFERENCE.md with the new signatures and draft a quick step to run packages/wasm-sdk/generate_docs.py so docs.html matches the current API?

📜 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 8164265 and a1ee9cf.

📒 Files selected for processing (2)
  • packages/wasm-sdk/test/README_TOKEN_TESTS.md (1 hunks)
  • packages/wasm-sdk/test/token-transitions.test.mjs (1 hunks)
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: QuantumExplorer
PR: dashpay/platform#2711
File: packages/wasm-sdk/AI_REFERENCE.md:771-783
Timestamp: 2025-07-28T20:00:08.502Z
Learning: In packages/wasm-sdk/AI_REFERENCE.md, the documentation correctly shows the actual SDK method signatures (including identityCreate and identityTopUp with their full parameter lists), which may differ from the UI inputs shown in fixed_definitions.json. The UI may collect fewer parameters from users while handling additional requirements internally.
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/src/**/*.rs : When implementing WASM SDK functionality, always refer to AI_REFERENCE.md first for accurate method signatures and examples.
📚 Learning: 2025-07-23T08:31:42.268Z
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/**/index.html : When adding new queries or state transitions, update the definitions in index.html.

Applied to files:

  • packages/wasm-sdk/test/README_TOKEN_TESTS.md
  • packages/wasm-sdk/test/token-transitions.test.mjs
📚 Learning: 2025-07-28T20:00:08.502Z
Learnt from: QuantumExplorer
PR: dashpay/platform#2711
File: packages/wasm-sdk/AI_REFERENCE.md:771-783
Timestamp: 2025-07-28T20:00:08.502Z
Learning: In packages/wasm-sdk/AI_REFERENCE.md, the documentation correctly shows the actual SDK method signatures (including identityCreate and identityTopUp with their full parameter lists), which may differ from the UI inputs shown in fixed_definitions.json. The UI may collect fewer parameters from users while handling additional requirements internally.

Applied to files:

  • packages/wasm-sdk/test/README_TOKEN_TESTS.md
📚 Learning: 2025-07-23T08:31:05.082Z
Learnt from: CR
PR: dashpay/platform#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:05.082Z
Learning: Applies to packages/wasm-sdk/index.html : Test the WASM SDK using the web interface at 'index.html' in 'packages/wasm-sdk'

Applied to files:

  • packages/wasm-sdk/test/README_TOKEN_TESTS.md
  • packages/wasm-sdk/test/token-transitions.test.mjs
📚 Learning: 2025-07-23T08:31:42.268Z
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/src/**/*.rs : Token functions are methods on WasmSdk, not standalone functions; avoid importing them as standalone.

Applied to files:

  • packages/wasm-sdk/test/README_TOKEN_TESTS.md
  • packages/wasm-sdk/test/token-transitions.test.mjs
📚 Learning: 2025-07-23T08:31:42.268Z
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/**/generate_docs.py : When adding new queries or state transitions, run python3 generate_docs.py to regenerate documentation.

Applied to files:

  • packages/wasm-sdk/test/README_TOKEN_TESTS.md
🪛 LanguageTool
packages/wasm-sdk/test/README_TOKEN_TESTS.md

[grammar] ~3-~3: There might be a mistake here.
Context: # Token Transition Tests ## Overview This directory contains tests for the to...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ... ## New Token Transitions (Implemented) The following token transitions have bee...

(QB_NEW_EN)


[grammar] ~9-~9: There might be a mistake here.
Context: ...r** - Transfer tokens between identities 2. tokenFreeze - Freeze tokens for a spec...

(QB_NEW_EN)


[grammar] ~10-~10: There might be a mistake here.
Context: ... - Freeze tokens for a specific identity 3. tokenUnfreeze - Unfreeze tokens for a ...

(QB_NEW_EN)


[grammar] ~11-~11: There might be a mistake here.
Context: ... Unfreeze tokens for a specific identity 4. tokenDestroyFrozen - Destroy frozen to...

(QB_NEW_EN)


[grammar] ~16-~16: There might be a mistake here.
Context: ...st Files ### token-transitions.test.mjs New test file that tests the four newly ...

(QB_NEW_EN)


[grammar] ~17-~17: There might be a mistake here.
Context: ...our newly implemented token transitions: - Tests parameter validation - Tests error...

(QB_NEW_EN)


[grammar] ~18-~18: There might be a mistake here.
Context: ...ransitions: - Tests parameter validation - Tests error handling for invalid inputs ...

(QB_NEW_EN)


[grammar] ~19-~19: There might be a mistake here.
Context: ... Tests error handling for invalid inputs - Tests permission requirements - Verifies...

(QB_NEW_EN)


[grammar] ~20-~20: There might be a mistake here.
Context: ...d inputs - Tests permission requirements - Verifies all methods are available on th...

(QB_NEW_EN)


[grammar] ~23-~23: There might be a mistake here.
Context: ...tate-transitions.test.mjs (Needs Update) The existing state transitions test file...

(QB_NEW_EN)

⏰ 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: build-wasm-sdk
  • GitHub Check: build-and-test-wasm-sdk
🔇 Additional comments (3)
packages/wasm-sdk/test/token-transitions.test.mjs (3)

14-20: Good polyfill for Node’s WebCrypto

Setting global.crypto to webcrypto when absent makes the WASM SDK happy under Node. Solid.


62-64: Correct use of method-based SDK API

Using WasmSdkBuilder.new_testnet_trusted().build() and invoking methods on the sdk instance aligns with our API style (“methods on WasmSdk, not standalone functions”).


96-107: Use undefined instead of null for optional string parameters

Wasm-bindgen represents Option<String> as string | undefined in JS. Passing null will trigger a conversion error before your validation logic runs. Please update the public note arguments in these calls:

  • packages/wasm-sdk/test/token-transitions.test.mjs: Line 106 (tokenTransfer)
  • packages/wasm-sdk/test/token-transitions.test.mjs: Line 170 (tokenFreeze)
  • packages/wasm-sdk/test/token-transitions.test.mjs: Line 233 (tokenUnfreeze)
  • packages/wasm-sdk/test/token-transitions.test.mjs: Line 296 (tokenDestroyFrozen)
-            null
+            undefined

Comment on lines +23 to +34
### state-transitions.test.mjs (Needs Update)
The existing state transitions test file contains an outdated test for `token_transfer` (line 307-325) that uses the old function signature:
```javascript
// OLD (no longer exists)
await wasmSdk.token_transfer(sdk, mnemonic, identity, contract, recipient, amount, keyIndex)

// NEW (implemented)
await sdk.tokenTransfer(contractId, position, amount, senderId, recipientId, privateKey, publicNote)
```

This test should be updated or removed since the old function no longer exists.

Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Search and update legacy API references (token_transfer → tokenTransfer)

Good callout. Let’s proactively locate any lingering usage to prevent confusion.

If matches appear, migrate to the new instance methods:

  • sdk.tokenTransfer(contractId, position, amount, senderId, recipientId, privateKey, publicNote)
  • sdk.tokenFreeze(contractId, position, identityToFreeze, authorityIdentityId, privateKey, publicNote)
  • sdk.tokenUnfreeze(contractId, position, identityToUnfreeze, authorityIdentityId, privateKey, publicNote)
  • sdk.tokenDestroyFrozen(contractId, position, identityToDestroy, authorityIdentityId, privateKey, publicNote)

🏁 Script executed:

#!/bin/bash
# Find old snake_case references across the repo and show context
rg -n -C2 -g '!*node_modules*' -P '\btoken_(transfer|freeze|unfreeze|destroy_frozen)\s*\('

Length of output: 8537


Update legacy snake_case token_ → camelCase token in tests and docs**

We’ve found remaining references to the removed token_transfer (and related) snake_case APIs. Please update all occurrences to use the new camelCase signatures:

• packages/wasm-sdk/test/README_TOKEN_TESTS.md (line 27)
• packages/wasm-sdk/test/state-transitions.test.mjs (line 307)
• packages/wasm-sdk/docs.html (example at line 2695)
• packages/wasm-sdk/AI_REFERENCE.md (line 1102)
• packages/wasm-sdk/generate_docs.py (templates at lines 338 & 1702)

Recommended diff for README_TOKEN_TESTS.md:

--- a/packages/wasm-sdk/test/README_TOKEN_TESTS.md
+++ b/packages/wasm-sdk/test/README_TOKEN_TESTS.md
@@ -24,7 +24,7 @@
 // OLD (no longer exists)
-await wasmSdk.token_transfer(sdk, mnemonic, identity, contract, recipient, amount, keyIndex)
+await sdk.tokenTransfer(contractId, position, amount, senderId, recipientId, privateKey, publicNote)

 // NEW (implemented)

And similarly, in state-transitions.test.mjs:

--- a/packages/wasm-sdk/test/state-transitions.test.mjs
+++ b/packages/wasm-sdk/test/state-transitions.test.mjs
@@ -306,7 +306,7 @@
 test('token_transfer - requires token balance', async () => {
-  const result = await wasmSdk.token_transfer(sdk, TEST_MNEMONIC, TEST_IDENTITY, TEST_CONTRACT, TEST_RECIPIENT, TEST_AMOUNT, TEST_KEY_INDEX);
+  const result = await sdk.tokenTransfer(TEST_CONTRACT_ID, TEST_POSITION, TEST_AMOUNT, TEST_SENDER_ID, TEST_RECIPIENT_ID, TEST_PRIVATE_KEY, TEST_PUBLIC_NOTE);

Also update all codegen templates in generate_docs.py and the example in AI_REFERENCE.md and the generated docs.html to emit sdk.tokenTransfer(…), sdk.tokenFreeze(…), sdk.tokenUnfreeze(…), and sdk.tokenDestroyFrozen(…) instead of snake_case.

📝 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
### state-transitions.test.mjs (Needs Update)
The existing state transitions test file contains an outdated test for `token_transfer` (line 307-325) that uses the old function signature:
```javascript
// OLD (no longer exists)
await wasmSdk.token_transfer(sdk, mnemonic, identity, contract, recipient, amount, keyIndex)
// NEW (implemented)
await sdk.tokenTransfer(contractId, position, amount, senderId, recipientId, privateKey, publicNote)
```
This test should be updated or removed since the old function no longer exists.
### state-transitions.test.mjs (Needs Update)
The existing state transitions test file contains an outdated test for `token_transfer` (line 307-325) that uses the old function signature:
🧰 Tools
🪛 LanguageTool

[grammar] ~23-~23: There might be a mistake here.
Context: ...tate-transitions.test.mjs (Needs Update) The existing state transitions test file...

(QB_NEW_EN)

🤖 Prompt for AI Agents
packages/wasm-sdk/test/README_TOKEN_TESTS.md around lines 23-34: the README
contains an outdated snake_case example calling token_transfer; replace that
example with the new camelCase signature and parameter order: call
sdk.tokenTransfer(contractId, position, amount, senderId, recipientId,
privateKey, publicNote) and map the original variables accordingly (contract →
contractId, mnemonic/identity/keyIndex → privateKey/publicNote or senderId as
appropriate), update any accompanying argument descriptions to match the new
names and order, and run a quick grep for other snake_case token_* references
and update them similarly (state-transitions.test.mjs, docs.html,
AI_REFERENCE.md, generate_docs.py templates) so examples and generated docs
consistently use tokenTransfer/tokenFreeze/tokenUnfreeze/tokenDestroyFrozen.

Copy link
Collaborator

@thephez thephez left a comment

Choose a reason for hiding this comment

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

Slightly-tested. Saw each of the four sts work via the UI at least once on testnet. See my PR (#2730) to this PR for some doc-related fixes.

@thephez thephez mentioned this pull request Aug 18, 2025
6 tasks
Co-authored-by: Claude <noreply@anthropic.com>
@QuantumExplorer QuantumExplorer changed the title feat(wasm-sdk): implement four missing token transitions feat(sdk): implement four missing token transitions Aug 19, 2025
@QuantumExplorer QuantumExplorer changed the title feat(sdk): implement four missing token transitions feat(wasm-sdk): implement four missing token transitions Aug 19, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (2)
packages/wasm-sdk/generate_docs.py (2)

656-665: Keep CSS changes in the generator to avoid being overwritten

docs.css is generated by this function. The manual change added white-space: pre-wrap and overflow-x: auto to .example-code in packages/wasm-sdk/docs.css, but this function doesn’t include them. They will be lost on the next docs generation.

Apply this diff to mirror the CSS changes:

 .example-code {
     background-color: #2c3e50;
     color: #ecf0f1;
     padding: 10px;
     border-radius: 3px;
     font-family: monospace;
     font-size: 0.9em;
     margin-bottom: 10px;
     position: relative;
+    white-space: pre-wrap;
+    overflow-x: auto;
 }

Optionally add:

+    overflow-wrap: anywhere; /* wraps long base58/hex strings */

1725-1733: Update token_transfer examples and docs to use the new camelCase tokenTransfer signature

The SDK’s tokenTransfer method now expects:
(identityHex: string, dataContractId: string, tokenPosition: number, amount: string, recipientId: string, privateKeyHex: string, publicNote?: string)

Please update all outdated references (“token_transfer” + numeric amount + “tokenId”) across the SDK’s docs, tests, generators, and fixtures:

• generate_docs.py
– lines 346–353 and 1725–1733
• packages/wasm-sdk/docs.html & index.html example snippets
• packages/wasm-sdk/test/README_TOKEN_TESTS.md (old token_transfer test)
• packages/wasm-sdk/test/state-transitions.test.mjs (lines 307–311)
• UI automation: utils/parameter-injector.js (change tokenId→tokenPosition) and test-data.js fixtures
• packages/wasm-sdk/AI_REFERENCE.md (lines 1134–1139)
• api-definitions.json inputs for tokenTransfer

Example diff for generate_docs.py:

-            elif trans_key == 'tokenTransfer':
-                md_content += '''const result = await sdk.token_transfer(
-    identityHex,
-    contractId,
-    tokenId,
-    1000000, // amount
-    recipientId,
-    privateKeyHex
-);'''
+            elif trans_key == 'tokenTransfer':
+                md_content += '''const result = await sdk.tokenTransfer(
+    identityHex,
+    contractId,
+    tokenPosition,    // number
+    "1000000",        // amount as string
+    recipientId,
+    privateKeyHex,
+    /* publicNote? */ // optional
+);'''

Run a global search-and-replace for token_transfer and tokenId in packages/wasm-sdk to catch all remaining instances.

♻️ Duplicate comments (1)
packages/wasm-sdk/AI_REFERENCE.md (1)

1123-1142: Token Transfer example uses old name and params; update to new signature

Use camelCase method name and new parameter list (tokenPosition, amount as string, optional publicNote). This was flagged previously as well.

-```javascript
-const result = await sdk.token_transfer(
-    identityHex,
-    contractId,
-    tokenId,
-    1000000, // amount
-    recipientId,
-    privateKeyHex
-);
-```
+```javascript
+const result = await sdk.tokenTransfer(
+  identityHex,
+  contractId,        // data contract ID (base58)
+  tokenPosition,     // number
+  "1000000",         // amount as text
+  recipientId,       // recipient identity (base58)
+  privateKeyHex,     // signing key
+  /* publicNote? */  // optional
+);
+```
🧹 Nitpick comments (5)
packages/wasm-sdk/docs.css (1)

273-275: Good wrap support; add overflow-wrap for long base58/hex

Long unbroken tokens (base58/hex) won’t wrap with pre-wrap alone. Add overflow-wrap to prevent overflow while keeping horizontal scroll as a fallback.

 .example-code {
@@
-    white-space: pre-wrap;
-    overflow-x: auto;
+    white-space: pre-wrap;
+    overflow-x: auto;
+    overflow-wrap: anywhere; /* helps wrap long base58/hex strings */
 }

Note: generate_docs.py writes docs.css on every docs generation. Mirror this change in generate_docs_css() to avoid it being overwritten. See my comment in generate_docs.py.

packages/wasm-sdk/generate_docs.py (3)

245-257: Clarify header when showing SDK params

Minor UX nit: when showing sdk_params, consider labeling the section “Parameters (SDK)” to differentiate from UI inputs.

-            <div class="parameters">
-                <h5>Parameters:</h5>
+            <div class="parameters">
+                <h5>{'Parameters (SDK)' if operation.get('sdk_params') else 'Parameters:'}</h5>

If you’d prefer not to embed logic into the string literal, compute the header text before building the block.


319-331: Escape option labels/values to avoid HTML injection in docs

You escape descriptions and placeholders, but options are concatenated without escaping. Defensive fix below.

-    if param.get('options'):
-        html_content += '                    <br><small>Options: '
-        opts = [f'{opt.get("label", opt.get("value"))}' for opt in param.get('options', [])]
-        html_content += ', '.join(opts)
-        html_content += '</small>\n'
+    if param.get('options'):
+        html_content += '                    <br><small>Options: '
+        opts = [html_lib.escape(str(opt.get("label", opt.get("value")))) for opt in param.get('options', [])]
+        html_content += ', '.join(opts)
+        html_content += '</small>\n'

1710-1716: Remove unnecessary f-prefix on a static string (ruff F541)

This avoids a linter warning for “f-string without any placeholders”.

-            md_content += f"\nExample:\n```javascript\n"
+            md_content += "\nExample:\n```javascript\n"
packages/wasm-sdk/api-definitions.json (1)

1693-1721: Consider adding sdk_example snippets for token transitions

Optional: provide sdk_example blocks for tokenTransfer, tokenFreeze, tokenUnfreeze, tokenDestroyFrozen to ensure both HTML and AI ref show authoritative examples without relying on generator fallbacks.

Also applies to: 1740-1758

📜 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 a1ee9cf and b8a7ba5.

📒 Files selected for processing (6)
  • packages/wasm-sdk/AI_REFERENCE.md (5 hunks)
  • packages/wasm-sdk/api-definitions.json (8 hunks)
  • packages/wasm-sdk/docs.css (1 hunks)
  • packages/wasm-sdk/docs.html (9 hunks)
  • packages/wasm-sdk/docs_manifest.json (1 hunks)
  • packages/wasm-sdk/generate_docs.py (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/wasm-sdk/docs_manifest.json
  • packages/wasm-sdk/docs.html
🧰 Additional context used
📓 Path-based instructions (2)
packages/wasm-sdk/generate_docs.py

📄 CodeRabbit Inference Engine (CLAUDE.md)

Keep documentation for the WASM SDK in sync by running 'python3 generate_docs.py' in 'packages/wasm-sdk'

Files:

  • packages/wasm-sdk/generate_docs.py
packages/wasm-sdk/**/generate_docs.py

📄 CodeRabbit Inference Engine (packages/wasm-sdk/CLAUDE.md)

When adding new queries or state transitions, run python3 generate_docs.py to regenerate documentation.

Files:

  • packages/wasm-sdk/generate_docs.py
🧠 Learnings (8)
📓 Common learnings
Learnt from: QuantumExplorer
PR: dashpay/platform#2711
File: packages/wasm-sdk/AI_REFERENCE.md:771-783
Timestamp: 2025-07-28T20:00:08.502Z
Learning: In packages/wasm-sdk/AI_REFERENCE.md, the documentation correctly shows the actual SDK method signatures (including identityCreate and identityTopUp with their full parameter lists), which may differ from the UI inputs shown in fixed_definitions.json. The UI may collect fewer parameters from users while handling additional requirements internally.
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/**/index.html : When adding new queries or state transitions, update the definitions in index.html.
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/**/generate_docs.py : When adding new queries or state transitions, run python3 generate_docs.py to regenerate documentation.
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/src/**/*.rs : When implementing WASM SDK functionality, always refer to AI_REFERENCE.md first for accurate method signatures and examples.
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/src/**/*.rs : Token functions are methods on WasmSdk, not standalone functions; avoid importing them as standalone.
📚 Learning: 2025-07-23T08:31:42.268Z
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/**/index.html : When adding new queries or state transitions, update the definitions in index.html.

Applied to files:

  • packages/wasm-sdk/docs.css
  • packages/wasm-sdk/generate_docs.py
📚 Learning: 2025-07-23T08:31:05.082Z
Learnt from: CR
PR: dashpay/platform#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:05.082Z
Learning: Applies to packages/wasm-sdk/index.html : Test the WASM SDK using the web interface at 'index.html' in 'packages/wasm-sdk'

Applied to files:

  • packages/wasm-sdk/docs.css
📚 Learning: 2025-07-23T08:31:42.268Z
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/src/**/*.rs : When implementing WASM SDK functionality, always refer to AI_REFERENCE.md first for accurate method signatures and examples.

Applied to files:

  • packages/wasm-sdk/docs.css
  • packages/wasm-sdk/AI_REFERENCE.md
📚 Learning: 2025-07-23T08:31:42.268Z
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/**/index.html : The WASM SDK now fully supports where and orderBy clauses for document queries; use the specified JSON array formats and supported operators.

Applied to files:

  • packages/wasm-sdk/docs.css
📚 Learning: 2025-07-28T20:00:08.502Z
Learnt from: QuantumExplorer
PR: dashpay/platform#2711
File: packages/wasm-sdk/AI_REFERENCE.md:771-783
Timestamp: 2025-07-28T20:00:08.502Z
Learning: In packages/wasm-sdk/AI_REFERENCE.md, the documentation correctly shows the actual SDK method signatures (including identityCreate and identityTopUp with their full parameter lists), which may differ from the UI inputs shown in fixed_definitions.json. The UI may collect fewer parameters from users while handling additional requirements internally.

Applied to files:

  • packages/wasm-sdk/AI_REFERENCE.md
  • packages/wasm-sdk/generate_docs.py
  • packages/wasm-sdk/api-definitions.json
📚 Learning: 2025-07-23T08:31:42.268Z
Learnt from: CR
PR: dashpay/platform#0
File: packages/wasm-sdk/CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:42.268Z
Learning: Applies to packages/wasm-sdk/**/generate_docs.py : When adding new queries or state transitions, run python3 generate_docs.py to regenerate documentation.

Applied to files:

  • packages/wasm-sdk/generate_docs.py
📚 Learning: 2025-07-23T08:31:05.082Z
Learnt from: CR
PR: dashpay/platform#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-23T08:31:05.082Z
Learning: Applies to packages/wasm-sdk/generate_docs.py : Keep documentation for the WASM SDK in sync by running 'python3 generate_docs.py' in 'packages/wasm-sdk'

Applied to files:

  • packages/wasm-sdk/generate_docs.py
🪛 Gitleaks (8.27.2)
packages/wasm-sdk/AI_REFERENCE.md

812-812: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🪛 Ruff (0.12.2)
packages/wasm-sdk/generate_docs.py

1710-1710: f-string without any placeholders

Remove extraneous f prefix

(F541)

⏰ 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). (4)
  • GitHub Check: Build JS packages / Build JS
  • GitHub Check: Rust crates security audit
  • GitHub Check: build-and-test-wasm-sdk
  • GitHub Check: build-wasm-sdk
🔇 Additional comments (8)
packages/wasm-sdk/generate_docs.py (3)

248-257: Correctly preferring sdk_params over inputs

Using sdk_params when present (with inputs as fallback) is the right approach and aligns HTML with the AI reference.


333-338: Nice: per-transition example override

Allowing transition.sdk_example to override the generic example is a clean, extensible design.


1683-1695: AI Reference: correct to use sdk_params for transitions

Reusing the same sdk_params preference in the Markdown generator keeps both outputs consistent. Good.

packages/wasm-sdk/api-definitions.json (5)

1238-1262: SDK params for identityCreate look good

The sdk_params block is clear and matches what the generator expects. Example provided is helpful.


1966-1997: Token Transfer definition updates are correct

Switch to tokenPosition (number), amount as text, and add publicNote is consistent with the WASM changes and resolves big-number issues in JS.


2002-2027: Token Freeze: renamed identity param + publicNote

identityToFreeze and optional publicNote are clear improvements.


2032-2057: Token Unfreeze: renamed identity param + publicNote

Consistent with freeze; looks good.


2061-2086: Token Destroy Frozen: clearer label + publicNote

The label and params align with intended behavior.

Comment on lines +812 to 813
const assetLockProofPrivateKey = "XFfpaSbZq52HPy3WWve1dXsZMiU1bQn8vQd34HNXkSZThevBWRn1"; // WIF format

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

Replace realistic-looking WIF with obvious placeholder

This sample key trips secret scanners (Gitleaks flagged it). Use a clearly fake placeholder to avoid CI noise and security confusion.

-const assetLockProofPrivateKey = "XFfpaSbZq52HPy3WWve1dXsZMiU1bQn8vQd34HNXkSZThevBWRn1"; // WIF format
+const assetLockProofPrivateKey = "WIF_PRIVATE_KEY_EXAMPLE"; // WIF format (example)
📝 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
const assetLockProofPrivateKey = "XFfpaSbZq52HPy3WWve1dXsZMiU1bQn8vQd34HNXkSZThevBWRn1"; // WIF format
const assetLockProofPrivateKey = "WIF_PRIVATE_KEY_EXAMPLE"; // WIF format (example)
🧰 Tools
🪛 Gitleaks (8.27.2)

812-812: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🤖 Prompt for AI Agents
In packages/wasm-sdk/AI_REFERENCE.md around lines 812 to 813, the example uses a
realistic-looking WIF private key which triggers secret scanners; replace the
current value with an obvious non-secret placeholder string (e.g.
REPLACE_WITH_WIF_PRIVATE_KEY or <WIF_PRIVATE_KEY_PLACEHOLDER>) and add a short
inline note that it is a dummy value to prevent CI secret detections.

Comment on lines +1278 to 1301
{
"name": "identityId",
"type": "string",
"label": "Identity ID",
"required": true,
"description": "Base58 format identity ID"
},
{
"name": "assetLockProof",
"type": "string",
"label": "Asset Lock Proof",
"required": true,
"description": "Hex-encoded JSON asset lock proof"
},
{
"name": "assetLockProofPrivateKey",
"type": "string",
"label": "Asset Lock Proof Private Key",
"required": true,
"description": "WIF format private key"
}
],
"sdk_example": "const identityId = \"5DbLwAxGBzUzo81VewMUwn4b5P4bpv9FNFybi25XB5Bk\"; // base58\nconst assetLockProof = \"a9147d3b... (hex-encoded)\";\nconst assetLockProofPrivateKey = \"XFfpaSbZq52HPy3WWve1dXsZMiU1bQn8vQd34HNXkSZThevBWRn1\"; // WIF format\n\nconst result = await sdk.identityTopUp(identityId, assetLockProof, assetLockProofPrivateKey);"
},
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

Mask realistic-looking WIF in sdk_example to appease scanners

Replace the sample WIF with an obvious placeholder to prevent false positives.

-const assetLockProofPrivateKey = "XFfpaSbZq52HPy3WWve1dXsZMiU1bQn8vQd34HNXkSZThevBWRn1"; // WIF format
+const assetLockProofPrivateKey = "WIF_PRIVATE_KEY_EXAMPLE"; // WIF format (example)
🤖 Prompt for AI Agents
In packages/wasm-sdk/api-definitions.json around lines 1278 to 1301, the
sdk_example contains a realistic-looking WIF sample which can trigger secret
scanners; replace that concrete WIF string with an obvious placeholder (e.g.
"WIF_PRIVATE_KEY" or "WIF_PLACEHOLDER") so the example remains clear but cannot
be mistaken for a real secret, and update any surrounding inline comment to
indicate it is a placeholder.

@QuantumExplorer QuantumExplorer merged commit 5ab180e into v2.1-dev Aug 19, 2025
22 of 24 checks passed
@QuantumExplorer QuantumExplorer deleted the feat/implement-missing-token-transitions-wasm-sdk branch August 19, 2025 01:52
@coderabbitai coderabbitai bot mentioned this pull request Sep 16, 2025
9 tasks
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.

3 participants