Skip to content

Conversation

thephez
Copy link
Collaborator

@thephez thephez commented Aug 27, 2025

Issue being fixed or feature implemented

This PR adds almost comprehensive testing for WASM SDK state transitions, covering document operations, identity operations, and token-related functionalities. The test suite validates all state transition types through the browser-based WASM SDK interface.

What was done?

  • Implemented Playwright-based automated tests for all WASM SDK state transitions
  • Added support for environment variables to handle sensitive test data (private keys, identity IDs, etc.)
  • Created test infrastructure for document lifecycle operations (create, replace, delete, transfer, purchase)
  • Added identity operation tests (credit transfers, withdrawals, identity create, topup, update not supported)
  • Implemented token state transition tests (all except emergency action)
  • Fixed various bugs in document transitions including BigInt handling and field type processing
  • Improved test execution with parallel and sequential run configurations

How Has This Been Tested?

  • All tests run against testnet environment using real identities and contracts
  • Environment variables protect sensitive test data
  • Each tested state transition type has been validated with actual blockchain operations

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

  • New Features

    • Renamed Token "Destroy Frozen" input to “Frozen Identity ID”.
    • Price handling updated to support 64-bit values for document/token operations.
    • Added interactive state-transition UI flows and dynamic document support in the test harness.
  • Bug Fixes

    • More reliable document transfer/purchase/price-update flows and extended query wait timeout.
  • Tests

    • Comprehensive state-transition test suite, new validators, parameter injection, multiselect handling, and CI-aware parallel/sequential Playwright runs.
    • Test data can be loaded from environment variables.
  • Chores

    • Added dotenv, .env example, and updated ignore rules for sensitive test env files.

Copy link
Contributor

coderabbitai bot commented Aug 27, 2025

Walkthrough

Renames a Token Destroy Frozen input (identityId → frozenIdentityId) and updates UI calls and price handling; adds dotenv support, fixtures, helpers, and extensive Playwright state-transition tests and page automation; extends document revision handling in Rust document transitions; adjusts Playwright project concurrency and test timeouts.

Changes

Cohort / File(s) Summary
API param rename + UI wiring
packages/wasm-sdk/api-definitions.json, packages/wasm-sdk/index.html
Token Destroy Frozen input renamed from identityIdfrozenIdentityId; UI now passes values.frozenIdentityId. Price args changed to use BigInt(...) where applicable.
State-transition tests & harness
packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js, packages/wasm-sdk/test/ui-automation/tests/query-execution.spec.js
Adds comprehensive state-transition test suite, new validators (including identities contract-keys validator), and integrates state-transition flows into tests.
Page automation & injector utilities
packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js, packages/wasm-sdk/test/ui-automation/utils/parameter-injector.js, packages/wasm-sdk/test/ui-automation/utils/base-test.js
Adds WasmSdkPage state-transition API (setup, fill, execute, auth helpers, document schema/dynamic fields), ParameterInjector state-transition injection, expands input-discovery and multiselect handling, and extends query wait timeout to 85s.
Test fixtures, env, deps & ignore
packages/wasm-sdk/test/ui-automation/fixtures/test-data.js, packages/wasm-sdk/test/ui-automation/.env.example, packages/wasm-sdk/test/ui-automation/package.json, packages/wasm-sdk/test/ui-automation/.gitignore
Adds dotenv loading and dependency, .env.example, ignores test/ui-automation/.env, expands testData.stateTransitionParameters, exports new getters (getStateTransitionParameters, getAllStateTransitionParameters), and updates identity key query params (keyRequestTypepurposes).
Playwright project config
packages/wasm-sdk/test/ui-automation/playwright.config.js
Moves concurrency to per-project settings: adds parallel-tests project and conditionally included sequential-tests project; removes top-level fullyParallel/workers.
Rust document transitions
packages/wasm-sdk/src/state_transitions/documents/mod.rs
Introduces get_next_revision helper; document_transfer, document_purchase, and document_set_price build new DocumentV0 with revision+1 and use specialized transition constructors; document_delete requires an existing revision.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor TestRunner as Playwright Runner
  participant Page as WasmSdkPage
  participant UI as WASM SDK UI
  participant SDK as WASM SDK
  participant Net as Platform

  TestRunner->>Page: setupStateTransition(category,type,params)
  Page->>UI: select "Transitions", set category/type
  Page->>UI: fill parameters (auth, ids, dynamic doc fields)
  alt document needs schema
    Page->>UI: fetchDocumentSchema()/loadExistingDocument()
    UI-->>Page: schema/fields
  end
  Page->>UI: execute transition
  UI->>SDK: build and submit transition
  SDK->>Net: broadcast/process
  Net-->>SDK: result
  SDK-->>UI: result
  UI-->>Page: result/status
  Page-->>TestRunner: assertion data/logs
Loading
sequenceDiagram
  autonumber
  participant Caller as Caller
  participant Docs as Documents Module
  participant Builder as Transition Builder
  participant Net as Platform

  Caller->>Docs: document_set_price(document, price)
  Docs->>Docs: get_next_revision(document) -> rev+1
  Docs->>Docs: clone to DocumentV0 with revision=rev+1
  Docs->>Builder: new_document_update_price_transition_from_document(updated_doc, BigInt(price))
  Builder-->>Docs: transition
  Docs->>Net: submit transition
  Net-->>Docs: ack/result
  Docs-->>Caller: result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • QuantumExplorer
  • ktechmidas

Poem

I nibble keys and tweak the test,
Revisions hop to pass the quest.
BigInt carrots, env tucked tight,
Frozen IDs hugged just right.
Hoppity hops — transitions bright! 🥕🐇


📜 Recent 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 a02db31 and ac0ddac.

📒 Files selected for processing (1)
  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js
⏰ 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). (2)
  • GitHub Check: Build JS packages / Build JS
  • GitHub Check: build-wasm-sdk
✨ 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-test-state-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
Copy link
Collaborator Author

thephez commented Aug 27, 2025

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Aug 27, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/wasm-sdk/index.html (1)

3187-3195: Pass the required keyId into the sdk.tokenDirectPurchase call

The UI schema in api-definitions.json declares keyId as a required input for tokenDirectPurchase, and the form will collect values.keyId. However, the handler in index.html never passes it through. This will lead to a runtime mismatch between the UI and the SDK call.

• Location: packages/wasm-sdk/index.html, around lines 3187–3195
• Action: Insert the keyId argument (as a number) before privateKey in the call

Proposed diff:

-          result = await sdk.tokenDirectPurchase(
-            values.contractId,
-            Number(values.tokenPosition),
-            values.amount,
-            identityId,
-            values.totalAgreedPrice || null,
-            privateKey
-          );
+          result = await sdk.tokenDirectPurchase(
+            values.contractId,
+            Number(values.tokenPosition),
+            values.amount,
+            identityId,
+            values.totalAgreedPrice || null,
+            Number(values.keyId),
+            privateKey
+          );
packages/wasm-sdk/src/state_transitions/contracts/mod.rs (1)

246-260: Add safety checks: ensure updated contract owner and ID match the target

Before building the transition, explicitly assert that the updated JSON still refers to the same contract and owner to fail-fast on mismatches, rather than relying on deeper validation errors.

         let updated_contract = DataContract::from_json(
             updates_json,
             true, // validate
             sdk.version(),
         )
         .map_err(|e| JsValue::from_str(&format!("Failed to create updated contract from JSON: {}", e)))?;
 
+        // Sanity checks: prevent accidental retargeting
+        if updated_contract.id() != contract_identifier {
+            return Err(JsValue::from_str("Updated contract ID does not match target contractId")));
+        }
+        if updated_contract.owner_id() != owner_identifier {
+            return Err(JsValue::from_str("Updated contract ownerId does not match provided ownerId")));
+        }
+
         // Verify the version was incremented
         if updated_contract.version() <= existing_contract.version() {
packages/wasm-sdk/test/ui-automation/fixtures/test-data.js (1)

109-116: Typo: use identityIds (not identitiesIds).

The API and your other payloads use identityIds. This typo will break the UI injector or backend validation.

Apply this diff:

-            identitiesIds: [
+            identityIds: [
🧹 Nitpick comments (27)
packages/wasm-sdk/.gitignore (1)

5-6: Good call: ignore sensitive test env file

Adds clear comment and ignores test/ui-automation/.env. Consider adding a sanitized .env.example to document required vars.

I can draft a minimal .env.example if you want.

packages/wasm-sdk/test/ui-automation/utils/base-test.js (1)

225-226: Make loading timeout configurable to reduce future flakiness

85s is reasonable for transitions; make it env-configurable so CI or local runs can tune without code changes.

-      // State transitions can take longer than queries, so use longer timeout
-      await this.page.locator('#statusBanner.loading').waitFor({ state: 'hidden', timeout: 85000 });
+      // State transitions can take longer than queries; allow override via env
+      const timeoutMs = Number(process.env.WASM_SDK_LOADING_TIMEOUT_MS || 85000);
+      await this.page.locator('#statusBanner.loading').waitFor({ state: 'hidden', timeout: timeoutMs });
packages/wasm-sdk/test/ui-automation/package.json (1)

27-30: Verify dotenv version and placement

  • Ensure dotenv ^17.2.1 supports Node >=18 in your env; otherwise pin to a known-good major (e.g., ^16).
  • Since this package is test-only and private, dotenv could live in devDependencies for cleanliness.

Would you like me to adjust and pin based on your current Node/CI matrix?

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

2896-2920: Remove duplicate query branches (dead/unreachable code)

getFinalizedEpochInfos, getEvonodesProposedEpochBlocksByIds, and getEvonodesProposedEpochBlocksByRange are implemented earlier with proof handling; this later block duplicates them and is unreachable. Drop it to reduce maintenance overhead.

-        // Epoch/Block queries
-        else if (queryType === 'getFinalizedEpochInfos') {
-          result = await get_finalized_epoch_infos(
-            sdk,
-            values.startEpoch,
-            values.count,
-            values.ascending
-          );
-          // Result is already a JS object from serde_wasm_bindgen
-        } else if (queryType === 'getEvonodesProposedEpochBlocksByIds') {
-          result = await get_evonodes_proposed_epoch_blocks_by_ids(
-            sdk,
-            values.epoch,
-            values.ids
-          );
-          // Result is already a JS object from serde_wasm_bindgen
-        } else if (queryType === 'getEvonodesProposedEpochBlocksByRange') {
-          result = await get_evonodes_proposed_epoch_blocks_by_range(
-            sdk,
-            values.epoch,
-            values.limit,
-            values.startAfter,
-            values.orderAscending
-          );
-          // Result is already a JS object from serde_wasm_bindgen
-        }
packages/wasm-sdk/api-definitions.json (1)

1875-1879: Reconcile keyId requirement with implementation

tokenDirectPurchase declares keyId as required here, but index.html doesn’t use it. Either make it optional or remove it, or update the implementation to consume it.

If you choose to make it optional here:

-            {
-              "name": "keyId",
-              "type": "number",
-              "label": "Key ID (for signing)",
-              "required": true
-            }
+            {
+              "name": "keyId",
+              "type": "number",
+              "label": "Key ID (for signing)",
+              "required": false
+            }
packages/wasm-sdk/test/ui-automation/playwright.config.js (2)

40-47: Workers=1 disables parallelism despite fullyParallel=true

With workers set to 1 on CI, tests won’t run in parallel even if fullyParallel is true. If that’s intended to reduce flakiness, all good; otherwise consider allowing >1 workers on CI.

-      fullyParallel: true,
-      workers: process.env.CI ? 1 : undefined,
+      fullyParallel: true,
+      // Increase CI workers cautiously if flakiness is acceptable
+      workers: process.env.CI ? 2 : undefined,

55-69: CI gating for slow sequential tests: add an opt-in env to exercise them in CI when needed

Sometimes we want to run sequential state-transition tests on CI ad hoc. Consider adding an env gate (e.g., RUN_SEQ=1) to include the project on demand.

-    ...(process.env.CI ? [] : [{
+    ...((process.env.CI && !process.env.RUN_SEQ) ? [] : [{
       name: 'sequential-tests',
packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js (6)

158-164: Alternative selectors can over-match; prefer targeted mapping first

These generic selectors may fill the wrong field on complex pages. Prefer ParameterInjector’s mapping first, then fall back here.


177-197: Last-resort label matching: consider failing fast on required fields

Silent skip can hide misconfigurations. Optionally throw when a required param is missing (behind a flag) to catch regressions early.


238-299: Reduce flakiness in array input handling by waiting on DOM condition instead of sleep

Replace fixed wait with a count-based wait for new input fields.

-        await addButton.click();
-        await this.page.waitForTimeout(500); // Wait for new input to appear
+        const beforeCount = await currentInputs.count();
+        await addButton.click();
+        await this.page.waitForFunction(
+          (sel, prev) => document.querySelectorAll(sel).length > prev,
+          currentInputs.selector,
+          beforeCount,
+          { timeout: 3000 }
+        );

691-717: Avoid arbitrary sleep when fetching document schema

You already wait for the container to be visible; drop the fixed 3s delay to speed up and deflake.

-    // Wait for schema to load and fields to be generated
-    await this.page.waitForTimeout(3000);
-
     // Check if dynamic fields container is visible
     const dynamicFieldsContainer = this.page.locator('#dynamic_documentFields');
     await dynamicFieldsContainer.waitFor({ state: 'visible', timeout: 15000 });

579-606: Autofill documentFields when present

If parameters include documentFields, fetch schema and fill them here to keep ParameterInjector simple.

   async fillStateTransitionParameters(parameters) {
     // Handle state transition specific parameters
     for (const [key, value] of Object.entries(parameters)) {
       if (key === 'assetLockProof') {
         await this.fillAssetLockProof(value);
       } else if (key === 'privateKey') {
         await this.fillPrivateKey(value);
       } else if (key === 'identityId') {
         await this.fillIdentityId(value);
       } else if (key === 'seedPhrase') {
         await this.fillSeedPhrase(value);
       } else if (key === 'identityIndex') {
         await this.fillIdentityIndex(value);
       } else if (key === 'keySelectionMode') {
         // Skip keySelectionMode for now - only needed for identity create
         console.log('Skipping keySelectionMode field (identity create only)');
       } else if (key === 'documentFields') {
-        // Handle document fields - these need to be filled after schema fetch
-        console.log('Document fields will be handled after schema fetch');
+        try {
+          await this.fetchDocumentSchema();
+          await this.fillDocumentFields(value);
+        } catch (e) {
+          console.warn('Failed to auto-fill document fields:', e.message);
+        }
       } else if (key === 'description') {
         // Skip description field - it's just for documentation
         console.log('Skipping description field (documentation only)');
       } else {
         // Use the general parameter filling method for other parameters
         await this.fillParameterByName(key, value);
       }
     }
   }

768-781: Auth helpers: optionally throw when inputs are expected but hidden

If auth inputs are required for a transition, consider failing fast when they’re not visible to catch UI regressions earlier.

packages/wasm-sdk/test/ui-automation/tests/query-execution.spec.js (1)

198-218: Validator LGTM; make it resilient to object-shaped responses

Some endpoints return an object keyed by identityId instead of an array. Accept both shapes to avoid brittle tests.

 function validateIdentitiesContractKeysResult(resultStr) {
   expect(() => JSON.parse(resultStr)).not.toThrow();
-  const contractKeysData = JSON.parse(resultStr);
-  expect(contractKeysData).toBeDefined();
-  expect(Array.isArray(contractKeysData)).toBe(true);
-  
-  contractKeysData.forEach(identityResult => {
+  const parsed = JSON.parse(resultStr);
+  expect(parsed).toBeDefined();
+  const list = Array.isArray(parsed)
+    ? parsed
+    : (parsed && typeof parsed === 'object' ? Object.entries(parsed).map(([identityId, keys]) => ({ identityId, keys })) : []);
+  expect(Array.isArray(list)).toBe(true);
+
+  list.forEach(identityResult => {
     expect(identityResult).toHaveProperty('identityId');
     expect(identityResult).toHaveProperty('keys');
     expect(Array.isArray(identityResult.keys)).toBe(true);
     
     identityResult.keys.forEach(key => {
       expect(key).toHaveProperty('keyId');
       expect(key).toHaveProperty('purpose');
       expect(key).toHaveProperty('keyType');
       expect(key).toHaveProperty('publicKeyData');
       expect(key).toHaveProperty('securityLevel');
     });
   });
 }
packages/wasm-sdk/test/ui-automation/utils/parameter-injector.js (2)

1-1: Expose only used imports

If getStateTransitionParameters isn’t used, consider removing it to keep the surface clean.


39-62: Auto-handle documentFields and support deep overrides

Shallow spreads won’t merge nested objects like documentFields. Also, filling documentFields here reduces duplication.

   async injectStateTransitionParameters(category, transitionType, network = 'testnet', customParams = {}) {
     try {
       // Get base parameters from test data
       const allParameters = getAllStateTransitionParameters(category, transitionType, network);
       
       if (allParameters.length === 0) {
         console.warn(`⚠️  No state transition test parameters found for ${category}.${transitionType} on ${network}`);
         return false;
       }
       
-      const baseParameters = allParameters[0];
-      
-      // Merge base parameters with custom overrides
-      const parameters = { ...baseParameters, ...customParams };
+      const baseParameters = allParameters[0];
+      const parameters = deepMerge(baseParameters, customParams);
       
       console.log(`📝 Injecting state transition parameters for ${category}.${transitionType}:`, parameters);
 
-      await this.page.fillStateTransitionParameters(parameters);
+      await this.page.fillStateTransitionParameters(parameters);
+      if (parameters.documentFields) {
+        await this.page.fetchDocumentSchema();
+        await this.page.fillDocumentFields(parameters.documentFields);
+      }
       return true;
     } catch (error) {
       console.error(`❌ Failed to inject state transition parameters for ${category}.${transitionType}:`, error.message);
       return false;
     }
   }
+
+// Simple deepMerge helper (outside the class)
+function deepMerge(target, source) {
+  if (Array.isArray(target) || Array.isArray(source)) return source ?? target;
+  if (typeof target === 'object' && typeof source === 'object') {
+    const out = { ...target };
+    for (const [k, v] of Object.entries(source)) {
+      out[k] = k in target ? deepMerge(target[k], v) : v;
+    }
+    return out;
+  }
+  return source ?? target;
+}
packages/wasm-sdk/test/ui-automation/fixtures/test-data.js (3)

115-115: Consider numeric purposes instead of strings.

Protocol key purposes are numeric (0: auth, 3: transfer). Using strings may coerce implicitly but is brittle.

Apply this diff:

-            purposes: ["0", "3"] // Authentication and Transfer
+            purposes: [0, 3] // Authentication and Transfer

If the UI expects strings, keep as-is. Otherwise prefer numbers.


552-559: Clarify comments vs. actual usage of contractId.

Comments say “will be created by dataContractCreate test” but the test data uses a fixed contractId. Either wire the dynamic ID from the create step or update the comments to reflect using a pre-existing contract.

Apply this diff to align comments:

-            contractId: "5kMgvQ9foEQ9TzDhz5jvbJ9Lhv5qqBpUeYEezHNEa6Ti", // Use simple note contract (will be created by dataContractCreate test)
+            contractId: "5kMgvQ9foEQ9TzDhz5jvbJ9Lhv5qqBpUeYEezHNEa6Ti", // Use existing simple note contract on testnet

Repeat the same comment change for documentReplace/documentDelete/documentTransfer/documentPurchase/documentSetPrice entries.

Also applies to: 578-586, 592-601, 607-614, 619-626, 632-640, 645-653


499-793: Good breadth of state-transition fixtures; add .env.example and mask secrets in logs.

The env-backed keys are appropriate. Add a test/ui-automation/.env.example and ensure logs never print privateKey/seedPhrase.

I can add .env.example, update .gitignore, and wrap any debug logging with masking helpers if you want.

packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js (8)

31-42: Make the “Missing response message” handling generic or skip early.

The message mentions “Withdrawal” but this helper is used for many transitions. Either generalize the text or move skipping logic into the specific tests to avoid confusion.

Apply this diff to generalize:

-  // Check for withdrawal-specific minimum amount error
-  if (!result.success && result.result && result.result.includes('Missing response message')) {
-    console.error('⚠️  Withdrawal may have failed due to insufficient amount. Minimum withdrawal is ~190,000 credits.');
-    console.error('Full error:', result.result);
-  }
+  // Known flaky platform response seen across some transitions
+  if (!result.success && result.result && result.result.includes('Missing response message')) {
+    console.error('⚠️  Platform returned "Missing response message" for this transition.');
+    console.error('Full response:', result.result);
+  }

955-976: Guard against absent amount in tokenDestroyFrozen, or rely on fixture fix.

Spec reads testParams.amount which was missing in fixtures. If you don’t add it, guard here to avoid “undefined” in logs.

Apply if you decide not to add amount in fixtures:

-      validateTokenDestroyFrozenResult(result.result, testParams.frozenIdentityId, testParams.amount);
+      const expectedAmount = testParams.amount ?? 'unspecified';
+      validateTokenDestroyFrozenResult(result.result, testParams.frozenIdentityId, expectedAmount);

1212-1219: Avoid brittle “exact match” assertions for transition type lists.

UI options may grow; asserting exact length increases flakiness. Prefer subset checks.

Apply this diff:

-      // Verify exact match - contains all expected and no unexpected ones
-      expect(categories).toHaveLength(expectedCategories.length);
-      expectedCategories.forEach(expectedCategory => {
-        expect(categories).toContain(expectedCategory);
-      });
+      // Verify required categories are present (allow extras)
+      expectedCategories.forEach(expectedCategory => {
+        expect(categories).toContain(expectedCategory);
+      });

Similarly for identity transition types:

-      expect(transitionTypes).toHaveLength(expectedTransitionTypes.length);
-      expectedTransitionTypes.forEach(expectedType => {
-        expect(transitionTypes).toContain(expectedType);
-      });
+      expectedTransitionTypes.forEach(expectedType => {
+        expect(transitionTypes).toContain(expectedType);
+      });

Also applies to: 1238-1245


1278-1296: Loosen exact-match assertions for document/token/voting transition types.

Same rationale: assert required items are present; don’t enforce exact length.

Apply analogous diffs as suggested for identity lists in these three blocks.

Also applies to: 1298-1327, 1329-1351


1013-1016: Use runtime skip idiom inside tests.

Within a running test, prefer test.skip('reason') instead of test.skip(true, 'reason') for readability.

Apply this diff:

-        test.skip(true, 'Platform returned "Missing response message". Probably no tokens available to claim.');
+        test.skip('Platform returned "Missing response message". Probably no tokens available to claim.');

And:

-        test.skip(true, 'Platform returned "Missing response message". Possibly insufficient credits or tokens not available for purchase.');
+        test.skip('Platform returned "Missing response message". Possibly insufficient credits or tokens not available for purchase.');

Also applies to: 1065-1068


466-511: Data contract update called out as flaky — add retries or mark flaky.

Tests frequently fail per your comment. Use test.retry(2) or test.fixme() until underlying flakiness is addressed to stabilize CI.

Example:

-    test('should create data contract and then update it with author field', async () => {
+    test.describe.configure({ retries: 2 });
+    test('should create data contract and then update it with author field', async () => {

Or mark the update step with test.info().annotations.push({ type: 'flaky', description: 'Investigating intermittent failures' }).


245-255: DRY parsing helpers (optional).

Multiple validators duplicate JSON.parse + shape checks. Extract a tiny parseJson(resultStr) helper to reduce repetition.

I can send a compact refactor if desired.

Also applies to: 265-275, 283-295, 301-311, 319-329, 336-346, 348-358, 360-370, 372-382, 384-394


513-521: Use the state‐transition–specific auth helper in your tests

I confirmed that WasmSdkPage implements both hasAuthenticationInputs() (a generic check) and hasStateTransitionAuthInputs() (which additionally verifies the assetLockProofGroup). While your current tests will pass, it’s clearer and more comprehensive to use the state-transition helper in your state-transition specs.

Please update the following ranges in
packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js:

• Lines 513–521 (Data Contract tests)
• Lines 765–773 (Document tests)
• Lines 1105–1113 (Token tests)

Example diff:

-      const hasAuthInputs = await wasmSdkPage.hasAuthenticationInputs();
+      const hasAuthInputs = await wasmSdkPage.hasStateTransitionAuthInputs();
📜 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 76ed4a3 and 8eb6cb5.

⛔ Files ignored due to path filters (1)
  • packages/wasm-sdk/test/ui-automation/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (12)
  • packages/wasm-sdk/.gitignore (1 hunks)
  • packages/wasm-sdk/api-definitions.json (1 hunks)
  • packages/wasm-sdk/index.html (1 hunks)
  • packages/wasm-sdk/src/state_transitions/contracts/mod.rs (2 hunks)
  • packages/wasm-sdk/test/ui-automation/fixtures/test-data.js (4 hunks)
  • packages/wasm-sdk/test/ui-automation/package.json (1 hunks)
  • packages/wasm-sdk/test/ui-automation/playwright.config.js (2 hunks)
  • packages/wasm-sdk/test/ui-automation/tests/query-execution.spec.js (2 hunks)
  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js (1 hunks)
  • packages/wasm-sdk/test/ui-automation/utils/base-test.js (1 hunks)
  • packages/wasm-sdk/test/ui-automation/utils/parameter-injector.js (3 hunks)
  • packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js (4 hunks)
🧰 Additional context used
🧠 Learnings (7)
📚 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/.gitignore
  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js
📚 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/ui-automation/utils/base-test.js
  • packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js
  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js
  • packages/wasm-sdk/test/ui-automation/fixtures/test-data.js
📚 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/api-definitions.json
  • packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js
  • packages/wasm-sdk/test/ui-automation/fixtures/test-data.js
📚 Learning: 2025-08-05T13:55:39.147Z
Learnt from: thephez
PR: dashpay/platform#2718
File: packages/wasm-sdk/index.html:0-0
Timestamp: 2025-08-05T13:55:39.147Z
Learning: The get_identity_keys_with_proof_info function in the Rust WASM bindings does not support the "search" key request type and lacks the searchPurposeMap parameter. When proof mode is enabled with keyRequestType === 'search', the implementation falls back to the non-proof version (get_identity_keys) to maintain functionality.

Applied to files:

  • packages/wasm-sdk/test/ui-automation/tests/query-execution.spec.js
📚 Learning: 2024-10-03T11:51:06.980Z
Learnt from: shumkov
PR: dashpay/platform#2201
File: packages/rs-platform-version/src/version/v2.rs:1186-1188
Timestamp: 2024-10-03T11:51:06.980Z
Learning: In the `IdentityTransitionVersions` structure within `packages/rs-platform-version/src/version/v2.rs`, the field `credit_withdrawal` does not need the `identity_` prefix since it is already encompassed within identity state transitions.

Applied to files:

  • packages/wasm-sdk/src/state_transitions/contracts/mod.rs
📚 Learning: 2025-07-31T18:15:51.813Z
Learnt from: thephez
PR: dashpay/platform#2715
File: packages/wasm-sdk/test/ui-automation/run-ui-tests.sh:6-286
Timestamp: 2025-07-31T18:15:51.813Z
Learning: In packages/wasm-sdk/test/ui-automation/run-ui-tests.sh, the script doesn't require cleanup handling because it relies on Playwright's built-in webServer configuration to manage the HTTP server lifecycle automatically. The script only runs foreground processes through npm/Playwright commands.

Applied to files:

  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js
  • packages/wasm-sdk/test/ui-automation/playwright.config.js
📚 Learning: 2025-07-31T18:15:51.813Z
Learnt from: thephez
PR: dashpay/platform#2715
File: packages/wasm-sdk/test/ui-automation/run-ui-tests.sh:6-286
Timestamp: 2025-07-31T18:15:51.813Z
Learning: In packages/wasm-sdk/test/ui-automation/run-ui-tests.sh, the script correctly relies on Playwright's built-in webServer configuration to manage the HTTP server lifecycle automatically. The script doesn't spawn any background processes and doesn't need cleanup handling because Playwright handles server start/stop automatically before and after test execution.

Applied to files:

  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js
  • packages/wasm-sdk/test/ui-automation/playwright.config.js
⏰ 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). (1)
  • GitHub Check: build-wasm-sdk
🔇 Additional comments (8)
packages/wasm-sdk/index.html (1)

3245-3251: Param rename wired correctly for tokenDestroyFrozen

Passing values.frozenIdentityId matches the updated API/input name. Good alignment with api-definitions.json.

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

2076-2081: Rename to frozenIdentityId looks correct

Matches the UI callsite change in index.html; keeps label/requirements intact.

packages/wasm-sdk/src/state_transitions/contracts/mod.rs (2)

286-286: Confirm nonce type compatibility
DataContractUpdateTransition::new_from_data_contract is defined in the external dash_sdk crate, and we couldn’t locate its signature locally. Please manually verify that the type returned by

sdk.get_identity_contract_nonce(...)
    .await

matches the nonce parameter expected by

DataContractUpdateTransition::new_from_data_contract(,
    identity_contract_nonce,)

(e.g. both are plain u64, or both use the same wrapper type). If they differ, add an explicit conversion (for example, .into() or as u64) to avoid silent truncation.


262-267: Per-contract nonce API signature confirmed
I’ve verified that get_identity_contract_nonce in packages/rs-sdk/src/sdk.rs still accepts (identity_id: Identifier, contract_id: Identifier, bool, Option<…>) and that the call in packages/wasm-sdk/src/state_transitions/contracts/mod.rs:262-267 correctly matches this signature. The DataContractUpdateTransition::new_from_data_contract method likewise remains a three-parameter constructor and is invoked properly. No changes are required.

packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js (1)

123-134: Nice UX: multi-checkbox handling for purposes

This improves stability for purpose arrays.

packages/wasm-sdk/test/ui-automation/tests/query-execution.spec.js (1)

1292-1292: Test matrix update aligns with new validator

Adding getIdentitiesContractKeys with the specialized validator is correct.

packages/wasm-sdk/test/ui-automation/utils/parameter-injector.js (1)

10-11: Surface testData on the injector: LGTM

Exposing testData is convenient for ad-hoc assertions in tests.

packages/wasm-sdk/test/ui-automation/fixtures/test-data.js (1)

6-8: Env loading location looks good.

Loading dotenv from test/ui-automation/.env via a relative path is correct for this fixture layout.

Base automatically changed from wasm-sdk-fix-tests to v2.1-dev August 28, 2025 07:29
thephez and others added 25 commits August 28, 2025 09:42
Add Playwright basics and include 2 working tests (contract create and update).
…te test

- Refactor validation functions to reduce code duplication
- Add parseContractResponse helper for common JSON parsing
- Consolidate create and update validation into single function
- Add executeStateTransitionWithCustomParams for parameterized tests
- Add comprehensive create+update test with dynamic contract ID handling
- Support custom parameter overrides in parameter injector

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

Co-Authored-By: Claude <[email protected]>
…tion type validation

- Enable skipped UI state and navigation test suite
- Add filterPlaceholderOptions helper to clean dropdown arrays
- Expand transition categories test with complete expected list validation
- Add comprehensive tests for all transition types across categories
- Validate exact matches for identity, data contract, document, token, and voting transitions
- Ensure UI populates all expected state transition types correctly

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

Co-Authored-By: Claude <[email protected]>
…ey test

- Enable error handling for state transitions test suite
- Fix invalid private key test to use data contract create instead of document create
- Update test parameters to match data contract schema requirements
- Remove skipped network switching test suite
- Add proper newline at end of file

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

Co-Authored-By: Claude <[email protected]>
…mic schema handling

- Enable document state transition test suite
- Add document create test data with note contract parameters
- Implement dynamic document schema fetching and field population
- Add comprehensive document creation result validation
- Enhance ParameterInjector with testData access for document fields
- Add WasmSdkPage methods for document schema and field handling
- Structure test with proper steps for schema fetch, field fill, and execution

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

Co-Authored-By: Claude <[email protected]>
…th create+replace+delete

- Add validateDocumentReplaceResult and validateDocumentDeleteResult functions
- Add test data for documentReplace and documentDelete operations
- Replace standalone replace/delete tests with comprehensive lifecycle test
- Implement document loading for replace operations via loadExistingDocument
- Add dynamic document ID tracking across create/replace/delete phases
- Add timestamp-based message updates for replace validation
- Structure test with proper step reporting for each phase
- Set extended timeout for multi-step document operations

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

Co-Authored-By: Claude <[email protected]>
…sfer, purchase, and pricing

- Add test data for documentTransfer with two-identity workflow support
- Add test data for documentPurchase with buyer/seller identity handling
- Add test data for documentSetPrice with pricing functionality
- Add skipped placeholder tests for document transfer, set price, and purchase operations
- Include TODO comments explaining implementation requirements for each test
- Structure test data with placeholder fields for dynamic ID assignment

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

Co-Authored-By: Claude <[email protected]>
…document

- Enable document replace test by using known persistent testnet document ID
- Replace placeholder document ID with actual testnet document: Dy19ZeYPpqbEDcpsPcLwkviY5GZqT7yJL2EY4YfxTYjn
- Implement proper document replace workflow with existing document loading
- Add timestamp-based message updates for replace validation
- Use validateDocumentReplaceResult with expected document ID verification
- Structure test with proper steps for parameter injection, document loading, and execution

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

Co-Authored-By: Claude <[email protected]>
- Add validateIdentityCreditTransferResult function for transfer validation
- Add test data for identityCreditTransfer with sender/recipient IDs and amount
- Implement identity credit transfer test with proper parameter injection
- Add authentication input visibility test for identity transitions
- Structure identity state transition test suite with proper validation

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

Co-Authored-By: Claude <[email protected]>
Add comprehensive test for identity credit withdrawal functionality with proper validation and error handling for minimum amount requirements.

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

Co-Authored-By: Claude <[email protected]>
- Add dotenv dependency for secure test credential management
- Configure environment variable loading in test-data.js
- Add .env file to .gitignore to prevent credential exposure
- Replace hardcoded private keys with environment variable placeholders
- Support secure handling of test credentials across all state transitions

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

Co-Authored-By: Claude <[email protected]>
…tate transitions

- Add missing identity test data for identityCreate and identityTopUp operations
- Ensure all state transition test data uses environment variable pattern
- Complete dotenv integration for secure credential management across all operations
- Add missing privateKey fields using process.env.TEST_PRIVATE_KEY_* pattern

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

Co-Authored-By: Claude <[email protected]>
- Add token test data for mint, transfer, and burn operations
- Add validation helpers for token state transitions
- Add Token State Transitions test suite with 4 tests
- Update validation to handle actual network response format ({})
- Use existing test infrastructure and credentials

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

Co-Authored-By: Claude <[email protected]>
Add comprehensive test coverage for token freeze/unfreeze operations including test data fixtures, validation helpers, and complete test cases.

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

Co-Authored-By: Claude <[email protected]>
…x parameter naming

Add test data fixture for destroying frozen tokens and fix parameter name from identityId to frozenIdentityId in API definitions and implementation for clarity.

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

Co-Authored-By: Claude <[email protected]>
Add test coverage for token claim and set price for direct purchase state transitions with validation functions and test data fixtures.

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

Co-Authored-By: Claude <[email protected]>
Add test coverage for identity credit withdrawal with minimum amount validation and proper error handling for below-threshold amounts.

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

Co-Authored-By: Claude <[email protected]>
- Add test data for tokenDirectPurchase with 1 token at 10 credits
- Add validateTokenDirectPurchaseResult validation function
- Add test case with error handling for insufficient credits
- Reduce token price from 1000 to 10 credits for easier testing

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

Co-Authored-By: Claude <[email protected]>
Split test configuration into parallel and sequential projects to optimize
test execution while preventing race conditions in state transitions.

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

Co-Authored-By: Claude <[email protected]>
Test are very slow due to rs-sdk bug. They are also complicated because they require a funded identity to work
- Remove invalid keyRequestType field from test data
- Add purposes field with Authentication and Transfer key types
- Enhance parameter injector to handle multiselect checkboxes
- Fix validation to expect array of identity results instead of single object

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

Co-Authored-By: Claude <[email protected]>
@thephez thephez force-pushed the wasm-sdk-test-state-transitions branch from 8eb6cb5 to d4fdf1a Compare August 28, 2025 13:46
thephez and others added 8 commits August 28, 2025 10:11
…zen test

The tokenDestroyFrozen operation destroys all frozen tokens for an identity,
not a specific amount. Updated test validation to reflect this behavior.

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

Co-Authored-By: Claude <[email protected]>
Replace blindly calling toString() with proper type checking:
- Handle null/undefined as empty string to prevent errors
- Use JSON.stringify for objects/arrays instead of "[object Object]"
- Keep toString() for primitives (numbers, booleans, etc.)

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

Co-Authored-By: Claude <[email protected]>
…NFT contract

- Switch from placeholder note contract to actual NFT contract (HdRFTcxgwPSVgzdy6MTYutDLJdbpfLMXwuBaYLYKMVHv)
- Use real trading card document ID (EypPkQLgT6Jijht7NYs4jmK5TGzkNd1Z4WrQdH1hND59) instead of placeholders
- Configure secondary identity as buyer/recipient (HJDxtN6FJF3U3T9TMLWCqudfJ5VRkaUrxTsRp36djXAG)
- Add validation helpers for transfer, purchase, and set price operations
- Update test workflow to complete marketplace cycle: set price → purchase → transfer

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

Co-Authored-By: Claude <[email protected]>
- 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]>
…flow

- Update transfer test data to use secondary identity as owner (after purchase)
- Configure transfer recipient as primary identity
- Enable previously skipped transfer test step to complete marketplace workflow

🤖 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
@thephez thephez changed the title test(wasm-sdk): add tests for many state transitions test(wasm-sdk): add ui tests for almost all state transitions Aug 28, 2025
@thephez
Copy link
Collaborator Author

thephez commented Aug 28, 2025

Example of a test run (some tests skipped due to their functionality being subsumed in other tests):

image

View on Platform Explorer:
image

@thephez thephez marked this pull request as ready for review August 28, 2025 21:20
@thephez thephez marked this pull request as draft August 28, 2025 21:22
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: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/wasm-sdk/test/ui-automation/utils/parameter-injector.js (1)

26-29: Don’t log secrets — redact before logging.

Logging parameters prints privateKey/seedPhrase to CI logs.

Apply:

-      console.log(`📝 Injecting parameters for ${category}.${queryType}:`, parameters);
+      console.log(
+        `📝 Injecting parameters for ${category}.${queryType}:`,
+        redact(parameters)
+      );

Add helper near top (after requires):

+const SECRET_KEYS = new Set(['privateKey', 'seedPhrase', 'assetLockProof']);
+function redact(obj) {
+  return JSON.parse(
+    JSON.stringify(obj, (k, v) => (SECRET_KEYS.has(k) ? '***redacted***' : v))
+  );
+}
packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js (1)

241-293: Scope array input handling to the nearest container; avoid clicking unrelated “Add” buttons.

Current selectors are page-wide and may target wrong controls.

-      const arrayContainerInputs = this.page.locator('.array-input-container input[type="text"]');
+      const container = baseElement.locator('xpath=ancestor::*[contains(@class,"array-input-container")][1]');
+      const containerExists = await container.count() > 0;
+      const arrayContainerInputs = containerExists
+        ? container.locator('input[type="text"]')
+        : this.page.locator('.array-input-container input[type="text"]');
@@
-      const addButton = this.page.locator('button:has-text("+ Add Item"), button.add-array-item, button:has-text("Add Item"), button:has-text("Add"), button:has-text("add")').first();
+      const addButton = (containerExists ? container : this.page)
+        .locator('button:has-text("+ Add Item"), button.add-array-item, button:has-text("Add Item"), button:has-text("Add")')
+        .first();
@@
-        const currentArrayInputs = this.page.locator('.array-input-container input[type="text"]');
+        const currentArrayInputs = containerExists
+          ? container.locator('input[type="text"]')
+          : this.page.locator('.array-input-container input[type="text"]');
packages/wasm-sdk/src/state_transitions/documents/mod.rs (1)

1177-1177: Avoid precision loss: return price as JS BigInt, not f64

Serializing u64 credits as f64 loses precision beyond 2^53-1. Given this PR addresses BigInt handling, return BigInt values in JS.

Apply:

-                    ("pricePaid", JsValue::from_f64(price as f64)),
+                    ("pricePaid", js_sys::BigInt::new(&JsValue::from_str(&price.to_string())).into()),
-                ("price", JsValue::from_f64(price as f64)),
+                ("price", js_sys::BigInt::new(&JsValue::from_str(&price.to_string())).into()),

Also applies to: 1334-1334

♻️ Duplicate comments (1)
packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js (1)

722-737: JSON-stringifying complex document field values — resolved.

This fixes the “[object Object]” issue flagged earlier.

🧹 Nitpick comments (8)
packages/wasm-sdk/test/ui-automation/utils/parameter-injector.js (1)

176-185: Avoid mutating selector mapping during fallback build.

Push mutates the mapping array across iterations. Build a new array instead.

-    const possibleSelectors = fieldMapping[paramName] || [];
-    // Add generic fallback selectors
-    possibleSelectors.push(
-      `#${paramName}`,
-      `[name="${paramName}"]`,
-      `input[placeholder*="${paramName}" i]`,
-      `label:has-text("${paramName}") + input`,
-      `label:has-text("${paramName}") + select`,
-      `label:has-text("${paramName}") + textarea`
-    );
+    const possibleSelectors = [
+      ...(fieldMapping[paramName] || []),
+      `#${paramName}`,
+      `[name="${paramName}"]`,
+      `input[placeholder*="${paramName}" i]`,
+      `label:has-text("${paramName}") + input`,
+      `label:has-text("${paramName}") + select`,
+      `label:has-text("${paramName}") + textarea`,
+    ];
packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js (4)

1321-1337: Relax exact-match assertions for categories to reduce brittleness.

Future categories will break the test unnecessarily.

-      expect(categories).toHaveLength(expectedCategories.length);
-      expectedCategories.forEach(expectedCategory => {
-        expect(categories).toContain(expectedCategory);
-      });
+      expectedCategories.forEach((c) => expect(categories).toContain(c));
+      expect(categories.length).toBeGreaterThanOrEqual(expectedCategories.length);

1356-1363: Apply the same relaxed assertion pattern to transition types.

-      expect(transitionTypes).toHaveLength(expectedTransitionTypes.length);
-      expectedTransitionTypes.forEach(expectedType => {
-        expect(transitionTypes).toContain(expectedType);
-      });
+      expectedTransitionTypes.forEach((t) => expect(transitionTypes).toContain(t));
+      expect(transitionTypes.length).toBeGreaterThanOrEqual(expectedTransitionTypes.length);

Also applies to: 1379-1386, 1408-1414, 1439-1445, 1462-1468


541-585: Flaky “create then update” contract flow — add resiliency.

Platform propagation can lag; add retry/polling or mark slow.

I can add an expect.poll on the update step or introduce test.retry(2). Want a patch?


30-42: Basic validator should skip known transient-platform failures.

Currently logs “Missing response message” but still asserts success.

Consider early-returning a skip from here (via a callback) when transient platform responses are detected.

packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js (1)

158-197: Selector fallback is solid; consider getByLabel for robustness.

Playwright’s page.getByLabel(paramName) is often more resilient than CSS label traversal.

packages/wasm-sdk/src/state_transitions/documents/mod.rs (2)

1063-1063: Prefix unused parameters to silence warnings

key_id is unused in these bindings. Prefix with underscore for clarity and to avoid warnings.

Apply:

-        key_id: u32,
+        _key_id: u32,

Also applies to: 1230-1230


938-938: Don’t expect on user input in WASM bindings

expect("Document ID was provided") will panic the WASM module. Return a JS error instead.

Apply:

-        let doc_id = doc_id.expect("Document ID was provided");
+        let doc_id = doc_id.ok_or_else(|| JsValue::from_str("Document ID is required"))?;
📜 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 8eb6cb5 and bc5be83.

⛔ Files ignored due to path filters (1)
  • packages/wasm-sdk/test/ui-automation/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (13)
  • packages/wasm-sdk/.gitignore (1 hunks)
  • packages/wasm-sdk/api-definitions.json (1 hunks)
  • packages/wasm-sdk/index.html (3 hunks)
  • packages/wasm-sdk/src/state_transitions/documents/mod.rs (6 hunks)
  • packages/wasm-sdk/test/ui-automation/.env.example (1 hunks)
  • packages/wasm-sdk/test/ui-automation/fixtures/test-data.js (4 hunks)
  • packages/wasm-sdk/test/ui-automation/package.json (1 hunks)
  • packages/wasm-sdk/test/ui-automation/playwright.config.js (2 hunks)
  • packages/wasm-sdk/test/ui-automation/tests/query-execution.spec.js (2 hunks)
  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js (1 hunks)
  • packages/wasm-sdk/test/ui-automation/utils/base-test.js (1 hunks)
  • packages/wasm-sdk/test/ui-automation/utils/parameter-injector.js (3 hunks)
  • packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/wasm-sdk/test/ui-automation/package.json
  • packages/wasm-sdk/test/ui-automation/fixtures/test-data.js
  • packages/wasm-sdk/.gitignore
  • packages/wasm-sdk/test/ui-automation/utils/base-test.js
  • packages/wasm-sdk/test/ui-automation/tests/query-execution.spec.js
  • packages/wasm-sdk/api-definitions.json
  • packages/wasm-sdk/index.html
  • packages/wasm-sdk/test/ui-automation/playwright.config.js
🧰 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 (9)
📓 Common learnings
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: thephez
PR: dashpay/platform#2715
File: packages/wasm-sdk/test/ui-automation/run-ui-tests.sh:6-286
Timestamp: 2025-07-31T18:15:51.813Z
Learning: In packages/wasm-sdk/test/ui-automation/run-ui-tests.sh, the script doesn't require cleanup handling because it relies on Playwright's built-in webServer configuration to manage the HTTP server lifecycle automatically. The script only runs foreground processes through npm/Playwright commands.
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'
Learnt from: thephez
PR: dashpay/platform#2715
File: packages/wasm-sdk/test/ui-automation/run-ui-tests.sh:6-286
Timestamp: 2025-07-31T18:15:51.813Z
Learning: In packages/wasm-sdk/test/ui-automation/run-ui-tests.sh, the script correctly relies on Playwright's built-in webServer configuration to manage the HTTP server lifecycle automatically. The script doesn't spawn any background processes and doesn't need cleanup handling because Playwright handles server start/stop automatically before and after test execution.
📚 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/test/ui-automation/.env.example
📚 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/ui-automation/.env.example
  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js
📚 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/ui-automation/.env.example
📚 Learning: 2024-10-08T13:28:03.529Z
Learnt from: QuantumExplorer
PR: dashpay/platform#2227
File: packages/rs-drive-abci/src/platform_types/platform_state/mod.rs:141-141
Timestamp: 2024-10-08T13:28:03.529Z
Learning: When converting `PlatformStateV0` to `PlatformStateForSavingV1` in `packages/rs-drive-abci/src/platform_types/platform_state/mod.rs`, only version `0` needs to be handled in the match on `platform_state_for_saving_structure_default` because the changes are retroactive.

Applied to files:

  • packages/wasm-sdk/src/state_transitions/documents/mod.rs
📚 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: Documents and data contracts should use state transitions for updates

Applied to files:

  • packages/wasm-sdk/src/state_transitions/documents/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/**/index.html : When adding new queries or state transitions, update the definitions in index.html.

Applied to files:

  • packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js
  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js
📚 Learning: 2025-07-31T18:15:51.813Z
Learnt from: thephez
PR: dashpay/platform#2715
File: packages/wasm-sdk/test/ui-automation/run-ui-tests.sh:6-286
Timestamp: 2025-07-31T18:15:51.813Z
Learning: In packages/wasm-sdk/test/ui-automation/run-ui-tests.sh, the script doesn't require cleanup handling because it relies on Playwright's built-in webServer configuration to manage the HTTP server lifecycle automatically. The script only runs foreground processes through npm/Playwright commands.

Applied to files:

  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js
📚 Learning: 2025-07-31T18:15:51.813Z
Learnt from: thephez
PR: dashpay/platform#2715
File: packages/wasm-sdk/test/ui-automation/run-ui-tests.sh:6-286
Timestamp: 2025-07-31T18:15:51.813Z
Learning: In packages/wasm-sdk/test/ui-automation/run-ui-tests.sh, the script correctly relies on Playwright's built-in webServer configuration to manage the HTTP server lifecycle automatically. The script doesn't spawn any background processes and doesn't need cleanup handling because Playwright handles server start/stop automatically before and after test execution.

Applied to files:

  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js
🧬 Code graph analysis (3)
packages/wasm-sdk/test/ui-automation/utils/parameter-injector.js (1)
packages/wasm-sdk/test/ui-automation/fixtures/test-data.js (1)
  • testData (9-808)
packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js (2)
packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js (4)
  • success (17-17)
  • success (483-483)
  • result (20-20)
  • result (486-486)
packages/wasm-sdk/test/ui-automation/tests/query-execution.spec.js (2)
  • success (27-27)
  • result (30-30)
packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js (3)
packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js (2)
  • require (1-1)
  • require (2-2)
packages/wasm-sdk/test/ui-automation/utils/parameter-injector.js (1)
  • require (1-1)
packages/wasm-sdk/test/ui-automation/utils/base-test.js (1)
  • require (1-1)
🪛 dotenv-linter (3.3.0)
packages/wasm-sdk/test/ui-automation/.env.example

[warning] 6-6: [UnorderedKey] The TEST_PRIVATE_KEY_CONTRACT key should go before the TEST_PRIVATE_KEY_TRANSFER key

(UnorderedKey)


[warning] 9-9: [ValueWithoutQuotes] This value needs to be surrounded in quotes

(ValueWithoutQuotes)

🪛 Gitleaks (8.27.2)
packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js

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

(generic-api-key)

⏰ 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). (1)
  • GitHub Check: Build JS packages / Build JS
🔇 Additional comments (4)
packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js (2)

122-134: Good special-casing for checkbox arrays (purposes).


557-574: State-transition setup/fill/execute flow — LGTM.

API fits tests and keeps auth/material fields separated.

Also applies to: 579-606, 662-673

packages/wasm-sdk/src/state_transitions/documents/mod.rs (2)

1112-1131: LGTM: revision bump + specialized purchase transition

Creating a copied document with revision = current + 1 and using the dedicated purchase transition is correct and consistent with replacement semantics.

Also applies to: 1149-1149


1269-1271: Do not change the price or matching_key arguments
The new_document_update_price_transition_from_document signature is

fn new_document_update_price_transition_from_document<S: Signer>(,
    price: Credits,
    identity_public_key: &IdentityPublicKey,)

Here Credits is just a u64 alias and identity_public_key must be borrowed. The existing call

… price,  
&matching_key,  

already matches; casting or dropping & is unnecessary or incorrect.

Likely an incorrect or invalid review comment.

thephez and others added 4 commits September 1, 2025 08:27
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]>
Replace realistic-looking private key in state transition test with clearly
invalid base58 string to prevent secret scanner alerts while maintaining
test functionality.

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

Co-Authored-By: Claude <[email protected]>
Remove actual parameter values from console.log statements in parameter
injector to prevent logging of sensitive fields like privateKey while
maintaining operation visibility for debugging.

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

Co-Authored-By: Claude <[email protected]>
@thephez thephez marked this pull request as ready for review September 2, 2025 14:24
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/test/ui-automation/.env.example (1)

8-12: Secondary key and quoted seed phrase look good.

The missing secondary key and quoting issue from earlier feedback are resolved.

🧹 Nitpick comments (6)
packages/wasm-sdk/test/ui-automation/.env.example (1)

5-10: Reorder keys to satisfy dotenv-linter UnorderedKey warnings.

Alphabetize the TEST_PRIVATE_KEY_* entries so CONTRACT comes first and SECONDARY precedes TRANSFER.

 # Private keys for state transitions (DON'T STORE in production)
-TEST_PRIVATE_KEY_IDENTITY_1=YOUR_IDENTITY_PRIVATE_KEY_HERE
-TEST_PRIVATE_KEY_TRANSFER=YOUR_TRANSFER_PRIVATE_KEY_HERE
-TEST_PRIVATE_KEY_CONTRACT=YOUR_CONTRACT_PRIVATE_KEY_HERE
+TEST_PRIVATE_KEY_CONTRACT=YOUR_CONTRACT_PRIVATE_KEY_HERE
+TEST_PRIVATE_KEY_IDENTITY_1=YOUR_IDENTITY_PRIVATE_KEY_HERE
 # Secondary private key (used by some document/token transitions)
-TEST_PRIVATE_KEY_SECONDARY=YOUR_TEST_PRIVATE_KEY_SECONDARY
+TEST_PRIVATE_KEY_SECONDARY=YOUR_TEST_PRIVATE_KEY_SECONDARY
+TEST_PRIVATE_KEY_TRANSFER=YOUR_TRANSFER_PRIVATE_KEY_HERE
packages/wasm-sdk/src/state_transitions/documents/mod.rs (3)

553-572: Derive next revision from the fetched document, not user input.

Using a caller-supplied revision risks stale/incorrect values and can overflow. Fetch the document, verify the provided revision matches (optional), then compute the next revision via get_next_revision().

-        // Create the document using the DocumentV0 constructor
-        let platform_version = sdk.version();
-        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),
+        // Fetch current doc to validate and compute next revision
+        use dash_sdk::platform::DocumentQuery;
+        let query = DocumentQuery::new_with_data_contract_id(&sdk, contract_id, &document_type)
+            .await
+            .map_err(|e| JsValue::from_str(&format!("Failed to create document query: {}", e)))?
+            .with_document_id(&doc_id);
+        let existing_doc = dash_sdk::platform::Document::fetch(&sdk, query)
+            .await
+            .map_err(|e| JsValue::from_str(&format!("Failed to fetch document: {}", e)))?
+            .ok_or_else(|| JsValue::from_str("Document not found"))?;
+        if let Some(current) = existing_doc.revision() {
+            if current != revision {
+                return Err(JsValue::from_str("Provided revision does not match current document revision"));
+            }
+        }
+        let next_revision = Self::get_next_revision(&existing_doc)?;
+
+        // Create the replacement document using the next revision
+        let platform_version = sdk.version();
+        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(next_revision),
             created_at: None,
             updated_at: None,
             transferred_at: None,
             created_at_block_height: None,
             updated_at_block_height: None,
             transferred_at_block_height: None,
             created_at_core_block_height: None,
             updated_at_core_block_height: None,
             transferred_at_core_block_height: None,
         });

978-997: Consistent next-revision copies look good; consider JS BigInt for price fields in results.

The transfer/purchase/price paths correctly build V0 copies with incremented revisions. Minor: when returning price/pricePaid to JS, using f64 may lose precision for large values. Consider emitting BigInt (e.g., via js_sys::BigInt) or stringifying, if you expect large credit amounts.

Also applies to: 1122-1141, 1279-1297


948-952: Avoid panic on missing document ID.

Use an error instead of expect, to return a JS error rather than aborting.

-        let doc_id = doc_id.expect("Document ID was provided");
+        let doc_id = doc_id.ok_or_else(|| JsValue::from_str("Document ID is required"))?;
packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js (2)

448-468: Deflake purchase assertions: handle both proof-result paths.

Backend may return success without the updated doc. Make message and documentUpdated assertions tolerant to both outcomes.

 function validateDocumentPurchaseResult(resultStr, expectedDocumentId, expectedBuyerId, expectedPrice) {
   expect(() => JSON.parse(resultStr)).not.toThrow();
   const purchaseResponse = JSON.parse(resultStr);
   expect(purchaseResponse).toBeDefined();
   expect(purchaseResponse).toBeInstanceOf(Object);

   // Validate the response structure for document purchase
   expect(purchaseResponse.type).toBe('DocumentPurchased');
   expect(purchaseResponse.documentId).toBe(expectedDocumentId);
   expect(purchaseResponse.status).toBe('success');
   expect(purchaseResponse.newOwnerId).toBe(expectedBuyerId);
   expect(purchaseResponse.pricePaid).toBe(expectedPrice);
-  expect(purchaseResponse.message).toBe('Document purchased successfully');
-  expect(purchaseResponse.documentUpdated).toBe(true);
-  expect(purchaseResponse.revision).toBeDefined();
-  expect(typeof purchaseResponse.revision).toBe('number');
+  expect(purchaseResponse.message.toLowerCase()).toMatch(/purchased|processed/);
+  if ('documentUpdated' in purchaseResponse) {
+    expect(purchaseResponse.documentUpdated).toBe(true);
+    if ('revision' in purchaseResponse) {
+      expect(typeof purchaseResponse.revision).toBe('number');
+    }
+  }

   console.log(`✅ Confirmed purchase of document: ${expectedDocumentId} by ${expectedBuyerId} for ${expectedPrice} credits`);

   return purchaseResponse;
 }

754-775: Remove hard-coded recipient identity; use test data.

Avoid baking IDs into tests to ease environment portability.

-        const transferResult = await executeStateTransitionWithCustomParams(
+        const { recipientId } =
+          parameterInjector.testData.stateTransitionParameters.document.documentTransfer.testnet[0];
+        const transferResult = await executeStateTransitionWithCustomParams(
           wasmSdkPage,
           parameterInjector,
           'document',
           'documentTransfer',
           'testnet',
           {
-            recipientId: "7XcruVSsGQVSgTcmPewaE4tXLutnW1F6PXxwMbo8GYQC" // Transfer back to primary identity
+            recipientId // Transfer back to primary identity from fixtures
           }
         );
@@
-          "7XcruVSsGQVSgTcmPewaE4tXLutnW1F6PXxwMbo8GYQC" // Primary identity as recipient
+          recipientId
📜 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 bc5be83 and a02db31.

📒 Files selected for processing (4)
  • packages/wasm-sdk/src/state_transitions/documents/mod.rs (8 hunks)
  • packages/wasm-sdk/test/ui-automation/.env.example (1 hunks)
  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js (1 hunks)
  • packages/wasm-sdk/test/ui-automation/utils/parameter-injector.js (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/wasm-sdk/test/ui-automation/utils/parameter-injector.js
🧰 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 (9)
📚 Learning: 2025-09-02T13:30:17.696Z
Learnt from: thephez
PR: dashpay/platform#2739
File: packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js:1-171
Timestamp: 2025-09-02T13:30:17.696Z
Learning: In packages/wasm-sdk/index.html, state transition definitions are loaded dynamically from api-definitions.json rather than being hardcoded in the HTML file. The UI loads transition categories, types, inputs, and labels from this JSON configuration file.

Applied to files:

  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js
📚 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/ui-automation/tests/state-transitions.spec.js
📚 Learning: 2025-09-02T13:30:17.696Z
Learnt from: thephez
PR: dashpay/platform#2739
File: packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js:1-171
Timestamp: 2025-09-02T13:30:17.696Z
Learning: In packages/wasm-sdk/index.html, state transition definitions are loaded dynamically from api-definitions.json via the loadApiDefinitions() function that fetches './api-definitions.json'. The UI doesn't have hardcoded transition definitions - instead it populates categories, types, inputs, and labels from this JSON configuration file at runtime.

Applied to files:

  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js
📚 Learning: 2025-07-31T18:15:51.813Z
Learnt from: thephez
PR: dashpay/platform#2715
File: packages/wasm-sdk/test/ui-automation/run-ui-tests.sh:6-286
Timestamp: 2025-07-31T18:15:51.813Z
Learning: In packages/wasm-sdk/test/ui-automation/run-ui-tests.sh, the script doesn't require cleanup handling because it relies on Playwright's built-in webServer configuration to manage the HTTP server lifecycle automatically. The script only runs foreground processes through npm/Playwright commands.

Applied to files:

  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js
📚 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/ui-automation/tests/state-transitions.spec.js
  • packages/wasm-sdk/test/ui-automation/.env.example
📚 Learning: 2025-07-31T18:15:51.813Z
Learnt from: thephez
PR: dashpay/platform#2715
File: packages/wasm-sdk/test/ui-automation/run-ui-tests.sh:6-286
Timestamp: 2025-07-31T18:15:51.813Z
Learning: In packages/wasm-sdk/test/ui-automation/run-ui-tests.sh, the script correctly relies on Playwright's built-in webServer configuration to manage the HTTP server lifecycle automatically. The script doesn't spawn any background processes and doesn't need cleanup handling because Playwright handles server start/stop automatically before and after test execution.

Applied to files:

  • packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js
📚 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/test/ui-automation/tests/state-transitions.spec.js
  • packages/wasm-sdk/test/ui-automation/.env.example
📚 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/ui-automation/.env.example
📚 Learning: 2024-10-30T11:19:59.163Z
Learnt from: lklimek
PR: dashpay/platform#2277
File: packages/rs-sdk/tests/fetch/config.rs:233-233
Timestamp: 2024-10-30T11:19:59.163Z
Learning: In the Rust SDK's `rs-sdk/tests` integration tests (e.g., in `packages/rs-sdk/tests/fetch/config.rs`), we cannot create objects during tests because there is no support for object creation in this context. Therefore, hardcoded values for test identities must be used.

Applied to files:

  • packages/wasm-sdk/test/ui-automation/.env.example
🧬 Code graph analysis (1)
packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js (2)
packages/wasm-sdk/test/ui-automation/utils/parameter-injector.js (1)
  • require (1-1)
packages/wasm-sdk/test/ui-automation/utils/wasm-sdk-page.js (2)
  • require (1-1)
  • require (2-2)
🪛 dotenv-linter (3.3.0)
packages/wasm-sdk/test/ui-automation/.env.example

[warning] 7-7: [UnorderedKey] The TEST_PRIVATE_KEY_CONTRACT key should go before the TEST_PRIVATE_KEY_IDENTITY_1 key

(UnorderedKey)


[warning] 9-9: [UnorderedKey] The TEST_PRIVATE_KEY_SECONDARY key should go before the TEST_PRIVATE_KEY_TRANSFER key

(UnorderedKey)

⏰ 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). (2)
  • GitHub Check: Build JS packages / Build JS
  • GitHub Check: Rust crates security audit
🔇 Additional comments (3)
packages/wasm-sdk/src/state_transitions/documents/mod.rs (2)

189-196: Good helper: centralizes safe revision math.

Checked add with clear errors is correct and avoids overflow/panic paths.


847-849: Good: require existing revision for deletion.

Using the actual current revision (not defaulting to 0) prevents invalid deletes.

packages/wasm-sdk/test/ui-automation/tests/state-transitions.spec.js (1)

780-881: End-to-end document create→replace→delete flow: solid coverage.

Good, deterministic sequence with dynamic ID propagation and schema-driven field filling.

Replace hard-coded primary identity ID with dynamic reference from test data
to improve test maintainability and consistency.

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

Co-Authored-By: Claude <[email protected]>
@QuantumExplorer QuantumExplorer merged commit 77f4855 into v2.1-dev Sep 3, 2025
18 of 22 checks passed
@QuantumExplorer QuantumExplorer deleted the wasm-sdk-test-state-transitions branch September 3, 2025 16:14
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