Skip to content

Conversation

thephez
Copy link
Collaborator

@thephez thephez commented Aug 20, 2025

Issue being fixed or feature implemented

The WASM SDK test suite was experiencing multiple failures across different test files, revealing some CI/CD pipeline
issues. Additionally, the CI workflows for WASM SDK needed optimization to reduce redundancy and improve efficiency. WASM SDK was being built twice before (in both build and test workflows) every time CI ran. This eliminates the duplicate run and saves ~5 minutes.

What was done?

  • Fixed failing tests across multiple test files:

    • Corrected DPNS test expectations to match actual contract specifications (homograph conversion for o/i/l only)
    • Fixed incorrect function names and parameters in document-queries tests
    • Temporarily disable waitforstatetransition test that consumed the majority of test time with little benefit
    • Added missing index_values parameter to contested resource vote state tests
    • Resolved utilities-simple test failures
  • Optimized CI/CD workflows:

    • Consolidated separate build and test workflows into a single streamlined pipeline
    • Implemented sparse checkout to reduce repository clone size and time
    • Eliminated duplicate builds by using artifact sharing between jobs
    • Added test results summary to GitHub job output for better visibility
    • Prevented stale test reports from being uploaded

How Has This Been Tested?

  • Tests now pass successfully in CI
  • Test suite runs automatically on push and pull request
  • Confirmed CI workflow optimizations reduce build time and resource usage
  • Example CI run on this PR

Breaking Changes

None - all changes are to tests and CI infrastructure only.

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

    • Added prefetch of trusted quorums (testnet) and enabled composite-key lookups for contested-resource voting.
  • Refactor

    • Renamed and consolidated several WASM SDK APIs; adjusted document-query ordering and filters.
  • Tests

    • Updated tests to preserve special/non‑Latin characters, prefer existence/existence-checks over risky re-entry, broadened error handling and added presence-check sweeps.
  • Chores

    • Consolidated CI into a single build-and-test workflow with concurrency, artifact verification, Node.js v20 support, multi-arch tooling support; removed legacy test workflow and ignored generated HTML reports.

thephez and others added 14 commits August 20, 2025 10:13
- Fix homograph conversion tests to expect only o/i/l conversion
- Remove invalid tests for uppercase and numeric usernames
- Fix network error handling for WASM non-trusted mode
- All tests now align with actual DPNS contract validation rules

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

Co-Authored-By: Claude <noreply@anthropic.com>
…source_vote_state test

The get_contested_resource_vote_state function requires an index_values parameter
but the test was calling it without this parameter, causing it to fail with
"Cannot read properties of null (reading 'length')".

Fixed by adding [TEST_PARENT_DOMAIN, TEST_LABEL] as the index_values parameter,
matching the pattern used in other contested resource tests and UI automation.

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

Co-Authored-By: Claude <noreply@anthropic.com>
…t.mjs

- Fix incorrect function names: get_single_document → get_document, data_contract_fetch_history → get_data_contract_history, get_epoch_info → get_epochs_info
- Fix function parameters: remove extra prove parameter, add required count parameter
- Add quorum prefetching to resolve epoch query authentication issues
- Use better test data from test-data.js with contracts that have actual history
- Fix query structure: use indexed properties for orderBy, add required orderBy for range queries
- Switch to existing contracts: use Dashpay contract and contract with history

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

Co-Authored-By: Claude <noreply@anthropic.com>
- Fix testSerialization test to use 'simple' instead of 'string' parameter
- Fix start function test to avoid panic by checking existence only
- All utility tests now pass (12/12)

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

Co-Authored-By: Claude <noreply@anthropic.com>
Consolidate multiple test execution steps into single comprehensive test suite runner for cleaner CI workflow.

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

Co-Authored-By: Claude <noreply@anthropic.com>
- Change triggers from pull_request/push to workflow_run after Build WASM SDK
- Replace build steps with artifact download from build workflow
- Remove duplicate build artifact upload (already handled by build workflow)
- Rename job from build-and-test-wasm-sdk to test-wasm-sdk
- Add manual workflow_dispatch with build run ID option
- Simplify environment variables (remove Rust-specific vars)

This cuts CI time roughly in half and ensures tests run on the same build
used by other workflows, improving consistency and reducing resource usage.

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

Co-Authored-By: Claude <noreply@anthropic.com>
- Add test-report.html to .gitignore to prevent committing generated reports
- Remove committed test-report.html file from repository
- Update GitHub Action to only upload test report if file was actually generated
- Use hashFiles condition to check if report exists before upload

This ensures CI artifacts only contain fresh test reports from actual runs,
following CI/CD best practices where artifacts should be generated not committed.

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

Co-Authored-By: Claude <noreply@anthropic.com>
Ensures tests run against the correct commit SHA when triggered by workflow_run events.

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

Co-Authored-By: Claude <noreply@anthropic.com>
Merge separate WASM SDK build and test workflows to eliminate complexity
and improve CI efficiency. The consolidated workflow now handles both
building and testing in sequential jobs with proper artifact passing.

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

Co-Authored-By: Claude <noreply@anthropic.com>
…ted steps

Consolidate protoc and clang installation into single step and use sparse
checkout for test job to improve efficiency and reduce checkout time.

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

Co-Authored-By: Claude <noreply@anthropic.com>
Capture test output and generate formatted summary in GitHub step summary
for improved visibility of test results in CI workflow runs.

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

Co-Authored-By: Claude <noreply@anthropic.com>
@thephez thephez added this to the v2.1 milestone Aug 20, 2025
Copy link
Contributor

coderabbitai bot commented Aug 20, 2025

Walkthrough

Workflow renamed to "Build and Test WASM SDK", adds concurrency and CI env, consolidates system dependency installation, introduces a separate test-wasm-sdk job that downloads build artifacts, runs tests, and uploads summaries; legacy standalone tests workflow and a committed HTML test report were removed; multiple WASM SDK tests updated for renamed/added APIs and signatures.

Changes

Cohort / File(s) Summary of changes
CI workflow (build & test)
.github/workflows/wasm-sdk-build.yml
Renamed workflow; added concurrency and env: CI: true; consolidated system dependency install (protoc, clang, llvm); improved wasm-opt arch handling; changed build verification step text; added test-wasm-sdk job that sparse-checkouts tests, downloads build artifacts, verifies files, sets up Node 20, runs tests, generates job summary, and uploads test report artifact.
Removed CI workflow
.github/workflows/wasm-sdk-tests.yml
Deleted the standalone WASM SDK tests workflow that previously ran Rust toolchain/wasm build, tests, and uploaded artifacts.
WASM SDK tests & API surface
packages/wasm-sdk/test/*.test.mjs (e.g., document-queries.test.mjs, dpns.test.mjs, utilities-simple.test.mjs, voting-contested-resources.test.mjs)
Tests updated to reflect API renames/additions: added prefetch_trusted_quorums_testnet; renamed get_single_document→get_document, get_epoch_info→get_epochs_info, data_contract_fetch_history→get_data_contract_history; changed query filters/orderBy; DPNS homograph/validation expectations adjusted; presence-checks for start/prefetch utilities added; get_contested_resource_vote_state signature extended with index_values.
Artifacts and ignores
packages/wasm-sdk/.gitignore, packages/wasm-sdk/test/test-report.html
Added test/test-report.html to .gitignore; deleted the committed static packages/wasm-sdk/test/test-report.html report.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as Developer/Trigger
  participant GH as GitHub Actions
  participant Build as build-wasm-sdk Job
  participant Art as Artifact Storage
  participant Test as test-wasm-sdk Job

  Dev->>GH: Push/PR triggers "Build and Test WASM SDK"
  GH->>Build: Start build-wasm-sdk
  Build->>Build: Install system deps (protoc, clang, llvm), install wasm-opt (arch-aware)
  Build->>Build: Build WASM SDK, verify pkg files
  Build->>Art: Upload build artifacts (pkg/*)
  GH-->>Test: Start test-wasm-sdk (needs: build-wasm-sdk)
  Test->>Test: Sparse-checkout packages/wasm-sdk/test
  Test->>Art: Download build artifacts
  Test->>Test: Verify files, Setup Node 20, install deps
  Test->>Test: Run test suite, capture output
  Test->>GH: Publish job summary (always)
  Test->>Art: Upload test-report.html (if present)
Loading
sequenceDiagram
  autonumber
  participant Tests as Test Runner
  participant SDK as wasmSdk
  participant Net as Network

  Tests->>SDK: prefetch_trusted_quorums_testnet()
  SDK->>Net: Request trusted quorum data (testnet)
  Net-->>SDK: Quorum data or offline error
  Tests->>SDK: get_document(...), get_epochs_info(epoch,count), get_data_contract_history(...)
  SDK->>Net: Execute queries with updated params
  Net-->>SDK: Results or expected offline response
  SDK-->>Tests: Return data/errors handled by tests
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • QuantumExplorer
  • pauldelucia
  • shumkov

Poem

I nibble on the CI log, hop and hum,
Builds compile, then tests begin to drum.
Quorums prefetched, epochs called by name,
Index-values added — a tiny game.
Artifacts tucked, report removed—I've had my crumb. 🐇

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 wasm-sdk-fix-tests

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

Caution

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

⚠️ Outside diff range comments (2)
.github/workflows/wasm-sdk-build.yml (2)

82-118: Pin wasm-opt to a known version and parse JSON with jq

Pulling “latest” on every run reduces reproducibility and can introduce breakage. Also prefer jq over grep -oP to parse JSON.

       - name: Install wasm-opt
         run: |
           if ! command -v wasm-opt &> /dev/null; then
-            echo "Installing wasm-opt from GitHub releases..."
-            # Get the latest release version
-            WASM_OPT_VERSION=$(curl -s https://api.github.com/repos/WebAssembly/binaryen/releases/latest | grep -oP '"tag_name": "\K[^"]+')
+            echo "Installing wasm-opt from GitHub releases..."
+            # Pin version via env with fallback. Example: version_115
+            : "${BINARYEN_VERSION:=version_115}"
+            WASM_OPT_VERSION="${BINARYEN_VERSION}"
             echo "Installing wasm-opt version: $WASM_OPT_VERSION"
 
             # Detect architecture
             ARCH=$(uname -m)
             if [ "$ARCH" = "x86_64" ]; then
               BINARYEN_ARCH="x86_64"
             elif [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then
               BINARYEN_ARCH="aarch64"
             else
               echo "Unsupported architecture: $ARCH"
               exit 1
             fi
             
             echo "Detected architecture: $ARCH, using binaryen arch: $BINARYEN_ARCH"
             
             # Download and extract binaryen
             curl -L "https://github.com/WebAssembly/binaryen/releases/download/${WASM_OPT_VERSION}/binaryen-${WASM_OPT_VERSION}-${BINARYEN_ARCH}-linux.tar.gz" -o /tmp/binaryen.tar.gz
             tar -xzf /tmp/binaryen.tar.gz -C /tmp

Optionally set BINARYEN_VERSION in the job env for easy bumps:

 env:
   CARGO_TERM_COLOR: always
   RUSTFLAGS: "-C lto=off"
   CARGO_PROFILE_RELEASE_LTO: false
   CI: true
+  BINARYEN_VERSION: version_115

1-245: Trailing whitespace across the workflow YAML

yaml-lint flags trailing spaces on multiple lines (e.g., Lines 56, 148, 156, 162, 168, 172, 177, 186, 188, 193, 200, 206, 213, 221, 225, 234, 237). Please strip trailing whitespace to keep CI lint green.

Quick fix (run locally):

#!/bin/bash
sed -i 's/[[:space:]]\+$//' .github/workflows/wasm-sdk-build.yml

If you want an automated guard, I can add an EditorConfig rule and a lint job. Want me to open a follow-up?

🧹 Nitpick comments (22)
packages/wasm-sdk/.gitignore (1)

2-3: Ignore test-output.log produced by CI test step

Your workflow writes packages/wasm-sdk/test-output.log (tee in the “Run comprehensive test suite” step). It’s easy to accidentally commit locally. Recommend ignoring it here.

Apply:

 playwright-report/
 test-results/
 test/test-report.html
+test-output.log
.github/workflows/wasm-sdk-build.yml (9)

48-60: Ensure unzip is available before using it to extract protoc

The step relies on unzip but doesn’t guarantee it’s installed. ubuntu-latest usually has it, but pinning is safer for reproducible builds.

-      - name: Install system dependencies (protoc, clang, llvm)
+      - name: Install system dependencies (protoc, clang, llvm, unzip)
         run: |
           # Install protoc
           curl -Lo /tmp/protoc.zip \
             "https://github.com/protocolbuffers/protobuf/releases/download/v27.3/protoc-27.3-linux-x86_64.zip"
-          unzip -o /tmp/protoc.zip -d ${HOME}/.local
+          sudo apt-get update -qq
+          sudo apt-get install -y -qq unzip
+          unzip -o /tmp/protoc.zip -d ${HOME}/.local
           echo "${HOME}/.local/bin" >> $GITHUB_PATH
           export PATH="${PATH}:${HOME}/.local/bin"
           
           # Install clang and llvm
-          sudo apt update -qq
+          sudo apt-get update -qq
           sudo apt install -qq --yes clang llvm

138-144: Artifact retention: confirm intended 7 days

Retention at 7 days is fine for PR iteration; if you rely on reproducing past CI issues, consider 14–30 days. Otherwise LGTM.

Would you like me to submit a tiny follow-up to bump retention to 14 days?


145-156: Sparse checkout scope is minimal and good; consider including helper scripts if referenced

You run node test/run-all-tests.mjs. Since the sparse checkout includes only packages/wasm-sdk/test, this is correct. If future tests import shared helpers outside test/, they’ll be missing. Keep an eye on that.

To proactively avoid future breakage, you can extend sparse-checkout to also include packages/wasm-sdk/pkg (though artifacts populate it) and any test utils directory if introduced later.


169-185: Artifact verification is robust; add a size sanity check for wasm outputs

You already check presence. Adding a minimal size check (<1 KiB indicates a bad download) can catch truncated artifacts.

           for file in "${required_files[@]}"; do
             if [ ! -f "$file" ]; then
               echo "❌ Missing required file: $file"
               exit 1
             else
               echo "✅ Found: $file"
+              if [ "$(stat -c%s "$file")" -lt 1024 ]; then
+                echo "❌ $file seems too small; possible corruption"
+                exit 1
+              fi
             fi
           done

190-200: Cache npm dependencies for tests to speed CI

Enable Node cache to avoid reinstalling packages on each run.

       - name: Setup Node.js
         uses: actions/setup-node@v4
         with:
-          node-version: '20'
+          node-version: '20'
+          cache: 'npm'
+          cache-dependency-path: packages/wasm-sdk/test/package-lock.json

201-206: Surface test exit code explicitly (cosmetic)

The script already exits non-zero on failure. To keep logs concise, you can pipefail to ensure tee doesn’t mask non-zero exit visibility in the same shell.

-          node test/run-all-tests.mjs | tee test-output.log
+          set -o pipefail
+          node test/run-all-tests.mjs | tee test-output.log

207-237: Job summary parsing depends on specific strings; guard for format drift

If test/run-all-tests.mjs changes its summary format, your grep patterns will return 0 and show “0 tests”. Consider a fallback that counts “✅ ” lines.

             if [ -f test-output.log ]; then
               # Extract overall summary
               total_tests=$(grep -o "Total Tests: [0-9]*" test-output.log | grep -o "[0-9]*" || echo "0")
               total_passed=$(grep -o "Passed: [0-9]*" test-output.log | grep -o "[0-9]*" || echo "0")
               total_failed=$(grep -o "Failed: [0-9]*" test-output.log | grep -o "[0-9]*" || echo "0")
               total_time=$(grep -o "Time: [0-9]*\.[0-9]*s" test-output.log | grep -o "[0-9]*\.[0-9]*" || echo "0.00")
+              # Fallback if summary lines not found
+              if [ "$total_tests" = "0" ] && [ "$total_passed" = "0" ] && [ "$total_failed" = "0" ]; then
+                total_passed=$(grep -c '^✅ ' test-output.log || echo "0")
+                total_failed=$(grep -c '^❌ ' test-output.log || echo "0")
+                total_tests=$(( total_passed + total_failed ))
+              fi

238-244: Use files.exists() expression instead of hashFiles for clarity

hashFiles works but computes a hash; files.exists() is simpler and avoids hashing a potentially large HTML report (if it grows).

-      - name: Upload test report
-        if: always() && hashFiles('packages/wasm-sdk/test/test-report.html') != ''
+      - name: Upload test report
+        if: always() && files.exists('packages/wasm-sdk/test/test-report.html')
         uses: actions/upload-artifact@v4

3-27: Optional: add concurrency to avoid duplicate runs on push+PR

This prevents wasting runners when both push and PR trigger simultaneously.

 name: Build and Test WASM SDK
 
 on:
@@
   workflow_dispatch:
 
+concurrency:
+  group: ${{ github.workflow }}-${{ github.ref }}
+  cancel-in-progress: true
+
 env:
packages/wasm-sdk/test/dpns.test.mjs (3)

92-99: Explicitly assert that non-ASCII homographs are preserved (and add a mixed-case variant)

Good coverage for Cyrillic е. Add a mixed-case input to confirm lowercasing occurs without ASCII substitution.

 await test('dpns_convert_to_homograph_safe - unicode homographs', () => {
   // Only o,i,l are converted to 0,1,1 - other Unicode characters are preserved
   const result = wasmSdk.dpns_convert_to_homograph_safe("tеst"); // е is Cyrillic
   // Cyrillic 'е' should remain as-is, only lowercased
   if (result !== "tеst") { // Should be the same (just lowercased)
     throw new Error(`Expected Cyrillic to be preserved (lowercased), got "${result}"`);
   }
 });
+
+await test('dpns_convert_to_homograph_safe - unicode homograph with uppercase', () => {
+  const result = wasmSdk.dpns_convert_to_homograph_safe("Tеst"); // Latin T + Cyrillic е
+  if (result !== "tеst") {
+    throw new Error(`Expected only ASCII chars lowercased, got "${result}"`);
+  }
+});

220-223: Account for trusted-only mode error consistently across network tests

Nice catch including “Non-trusted mode is not supported in WASM”. Consider centralizing expected error checks to reduce duplication across network tests.

Idea: a helper:

function isExpectedOfflineOrModeError(err) {
  const m = err?.message || '';
  return m.includes('network') || m.includes('connection') || m.includes('Non-trusted mode is not supported in WASM');
}

Then reuse in all try/catch blocks for network-required calls.


337-342: Edge case: add an input containing only ASCII homographs to verify substitutions still happen

You test only-specials preserved; add an all-homograph string like "illoo" to ensure substitutions still trigger in edge-only inputs.

packages/wasm-sdk/test/utilities-simple.test.mjs (2)

109-116: Strengthen testSerialization assertions to verify shape/content

Good to assert non-null object. If the shape is known, validate keys to catch structural regressions.

-        const result = sdk.testSerialization('simple');
+        const result = sdk.testSerialization('simple');
         console.log(`   Result type: ${typeof result}, value:`, result);
 
-        // Should return a proper serialized object
-        if (typeof result !== 'object' || result === null) {
+        // Should return a proper serialized object with expected keys
+        if (typeof result !== 'object' || result === null) {
             throw new Error(`Expected object result, got ${typeof result}`);
         }
+        const requiredKeys = ['type', 'bytes', 'hex'];
+        for (const k of requiredKeys) {
+          if (!(k in result)) {
+            throw new Error(`Missing key "${k}" in serialization result`);
+          }
+        }

If the exact keys differ, share the canonical struct and I’ll align the assertions.


260-274: Document why start() shouldn’t be invoked twice (link to source or panic reason)

The explanation is helpful. Consider linking to the code (or quote the panic message) that enforces single initialization, so future readers understand the constraint.

Optionally, add a negative test that confirms the second call throws (wrapped and ignored), to lock the behavior:

// Optional: ensure double-start panics (WASM already called start during init)
try { await wasmSdk.start(); throw new Error('start() should have panicked'); } catch (_) {}

Only if running it won’t abort the process in this environment.

packages/wasm-sdk/test/voting-contested-resources.test.mjs (1)

60-71: Prefetch quorums before building trusted SDK is great; add fallback to continue tests offline

You already catch prefetch failures. Consider gating trusted builder creation if prefetch fails hard in some environments.

 try {
   await wasmSdk.prefetch_trusted_quorums_testnet();
   console.log('Quorums prefetched successfully');
 } catch (error) {
   console.log('Warning: Could not prefetch quorums:', error.message);
 }
 
-// Use trusted builder as required for WASM
-const builder = wasmSdk.WasmSdkBuilder.new_testnet_trusted();
-const sdk = await builder.build();
+// Use trusted builder as required for WASM
+let sdk;
+try {
+  const builder = wasmSdk.WasmSdkBuilder.new_testnet_trusted();
+  sdk = await builder.build();
+} catch (e) {
+  console.log('Warning: Could not build trusted SDK:', e.message);
+}

Then guard subsequent tests with if (sdk) { … } to keep the suite informative offline.

packages/wasm-sdk/test/document-queries.test.mjs (6)

127-142: Fix misleading inline comment for orderBy

The code orders by normalizedParentDomainName asc, but the trailing comment still says “creation time descending”.

-            orderBy,  // order by creation time descending
+            orderBy,  // order by normalizedParentDomainName asc

186-201: Tighten the negative test pattern for get_document

Current pattern works, but consider making the expectation explicit to reduce accidental passes when non-related failures occur.

 await test('get_document - by specific ID', async () => {
   try {
     // This would need a real document ID
-    const result = await wasmSdk.get_document(
+    await wasmSdk.get_document(
       sdk,
       DPNS_CONTRACT,
       "domain",
       "invalidDocumentId"
     );
-    throw new Error('Should have failed with invalid ID');
+    throw new Error('Expected get_document to fail with invalid ID');
   } catch (error) {
-    if (error.message.includes('Should have failed')) {
+    if (String(error?.message || error).includes('Expected get_document')) {
       throw error;
     }
     console.log('   Expected error with invalid document ID');
   }
 });

Optionally, introduce a small helper (outside this hunk) to assert rejection with a message regex to standardize negative assertions.


53-58: Hardcoded IDs: centralize and annotate to avoid false-positive secret scans

  • Centralize the Dashpay contract ID (used later) next to the other constants to avoid duplication.
  • Gitleaks flagged line 56 as a “Generic API Key.” These are public testnet contract IDs, not secrets—add an inline allow annotation to prevent churn.
 // DOCUMENTED TEST VALUES FROM docs.html and test-data.js
 const TEST_IDENTITY = '5DbLwAxGBzUzo81VewMUwn4b5P4bpv9FNFybi25XB5Bk';
 const DPNS_CONTRACT = 'GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec';
-const TOKEN_CONTRACT = 'H7FRpZJqZK933r9CzZMsCuf1BM34NT5P2wSJyjDkprqy';
+// gitleaks:allow - public testnet contract ID (non-secret)
+const TOKEN_CONTRACT = 'H7FRpZJqZK933r9CzZMsCuf1BM34NT5P2wSJyjDkprqy';
 const CONTRACT_WITH_HISTORY = 'HLY575cNazmc5824FxqaEMEBuzFeE4a98GDRNKbyJqCM';
+const DASHPAY_CONTRACT = 'ALybvzfcCwMs7sinDwmtumw17NneuW7RgFtFHgjKmF3A';
 
 console.log('Test Values:');
 console.log(`- Identity: ${TEST_IDENTITY}`);
 console.log(`- DPNS Contract: ${DPNS_CONTRACT}`);
 console.log(`- Token Contract: ${TOKEN_CONTRACT}`);
 console.log(`- Contract with History: ${CONTRACT_WITH_HISTORY}`);
+console.log(`- Dashpay Contract: ${DASHPAY_CONTRACT}`);

To verify your repo’s gitleaks config supports the inline annotation, or else add a repo-level .gitleaksignore entry.

Also applies to: 63-63


222-226: Avoid repeating literal Dashpay ID; use the centralized constant

Use DASHPAY_CONTRACT for consistency and easier maintenance.

 await test('data_contract_fetch - Dashpay contract', async () => {
   try {
-    // Use Dashpay contract which should exist
-    const result = await wasmSdk.data_contract_fetch(sdk, 'ALybvzfcCwMs7sinDwmtumw17NneuW7RgFtFHgjKmF3A');
+    // Use Dashpay contract which should exist
+    const result = await wasmSdk.data_contract_fetch(sdk, DASHPAY_CONTRACT);
     console.log(`   Contract fetched: ${result?.id || 'N/A'}`);
   } catch (error) {

255-261: Also reuse the centralized Dashpay constant in get_data_contracts

Keeps IDs DRY across tests.

 const result = await wasmSdk.get_data_contracts(
   sdk,
-  [DPNS_CONTRACT, 'ALybvzfcCwMs7sinDwmtumw17NneuW7RgFtFHgjKmF3A']
+  [DPNS_CONTRACT, DASHPAY_CONTRACT]
 );

275-292: Don’t mask unrelated errors in the “token documents” test

Catching everything will pass even on real regressions. Narrow the “expected” set to network/offline and schema/document-type errors; rethrow others.

 } catch (error) {
-  // Token queries might fail if contract doesn't have 'token' document type
-  console.log('   Expected error (token contract may not have token document type)');
+  const msg = String(error?.message || error);
+  if (msg.includes('network') || msg.includes('connection') || msg.toLowerCase().includes('document type')) {
+    console.log('   Expected error (token contract may not have token document type or offline)');
+  } else {
+    throw error;
+  }
 }
📜 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 cfd9b57 and 9f52983.

📒 Files selected for processing (8)
  • .github/workflows/wasm-sdk-build.yml (4 hunks)
  • .github/workflows/wasm-sdk-tests.yml (0 hunks)
  • packages/wasm-sdk/.gitignore (1 hunks)
  • packages/wasm-sdk/test/document-queries.test.mjs (10 hunks)
  • packages/wasm-sdk/test/dpns.test.mjs (3 hunks)
  • packages/wasm-sdk/test/test-report.html (0 hunks)
  • packages/wasm-sdk/test/utilities-simple.test.mjs (2 hunks)
  • packages/wasm-sdk/test/voting-contested-resources.test.mjs (1 hunks)
💤 Files with no reviewable changes (2)
  • packages/wasm-sdk/test/test-report.html
  • .github/workflows/wasm-sdk-tests.yml
🧰 Additional context used
🧠 Learnings (9)
📓 Common learnings
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 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.
📚 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/utilities-simple.test.mjs
  • .github/workflows/wasm-sdk-build.yml
📚 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/.gitignore
  • packages/wasm-sdk/test/voting-contested-resources.test.mjs
  • packages/wasm-sdk/test/document-queries.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/utilities-simple.test.mjs
📚 Learning: 2024-11-06T07:27:01.722Z
Learnt from: shumkov
PR: dashpay/platform#2314
File: packages/wallet-contract/test/bootstrap.js:14-16
Timestamp: 2024-11-06T07:27:01.722Z
Learning: In `packages/wallet-contract/test/bootstrap.js`, for Mocha tests in Node.js, async functions like `loadWasmDpp` can be assigned directly to `beforeAll` without wrapping them in another async function.

Applied to files:

  • packages/wasm-sdk/test/utilities-simple.test.mjs
  • packages/wasm-sdk/test/document-queries.test.mjs
📚 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/build.sh : Build the WASM SDK by running './build.sh' in 'packages/wasm-sdk'

Applied to files:

  • .github/workflows/wasm-sdk-build.yml
📚 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/test/document-queries.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 : 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/test/document-queries.test.mjs
📚 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/document-queries.test.mjs
🪛 YAMLlint (1.37.1)
.github/workflows/wasm-sdk-build.yml

[error] 56-56: trailing spaces

(trailing-spaces)


[error] 148-148: trailing spaces

(trailing-spaces)


[error] 156-156: trailing spaces

(trailing-spaces)


[error] 162-162: trailing spaces

(trailing-spaces)


[error] 168-168: trailing spaces

(trailing-spaces)


[error] 172-172: trailing spaces

(trailing-spaces)


[error] 177-177: trailing spaces

(trailing-spaces)


[error] 186-186: trailing spaces

(trailing-spaces)


[error] 188-188: trailing spaces

(trailing-spaces)


[error] 193-193: trailing spaces

(trailing-spaces)


[error] 200-200: trailing spaces

(trailing-spaces)


[error] 206-206: trailing spaces

(trailing-spaces)


[error] 213-213: trailing spaces

(trailing-spaces)


[error] 221-221: trailing spaces

(trailing-spaces)


[error] 225-225: trailing spaces

(trailing-spaces)


[error] 234-234: trailing spaces

(trailing-spaces)


[error] 237-237: trailing spaces

(trailing-spaces)

🪛 Gitleaks (8.27.2)
packages/wasm-sdk/test/document-queries.test.mjs

56-56: 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). (4)
  • GitHub Check: Build Docker images (Drive, drive, drive-abci) / Build Drive image
  • GitHub Check: Build JS packages / Build JS
  • GitHub Check: build-wasm-sdk
  • GitHub Check: Rust crates security audit
🔇 Additional comments (5)
packages/wasm-sdk/test/voting-contested-resources.test.mjs (1)

108-114: LGTM: Added index_values to match updated signature

The added [TEST_PARENT_DOMAIN, TEST_LABEL] aligns with the new wasmSdk.get_contested_resource_vote_state signature; error handling remains consistent.

packages/wasm-sdk/test/document-queries.test.mjs (4)

100-103: Good switch to parent-domain filtering for DPNS

Using normalizedParentDomainName == "dash" aligns with DPNS indexing and increases hit probability. LGTM.

Also applies to: 115-115


154-165: Correctly providing orderBy with range predicates

Supplying orderBy for a startsWith range plus equality predicate matches the SDK’s query requirements and typical index rules. Nice.

Also applies to: 171-171


326-329: Correct update to get_epochs_info signature

Calling get_epochs_info(sdk, 1, 1) matches the new API. With the prefetch guard above, this should behave reliably online.


236-244: Confirm optional parameter mapping for get_data_contract_history; prefer undefined over null

JS binding for the final startAtMs parameter comes from Rust’s Option<u64> and, in the generated TypeScript definitions, will be emitted as an optional argument (e.g. startAtMs?: number). Passing null may not satisfy the TS signature—which expects number | undefined—and can lead to type‐check errors in TS code. Using undefined is both idiomatic for optional parameters and matches the JS→Rust mapping of Noneundefined.

• Please verify the generated signatures in your pkg/wasm_sdk.js and pkg/wasm_sdk.d.ts (or equivalent) for:

export function get_data_contract_history(
  sdk: WasmSdk,
  id: string,
  limit?: number,
  offset?: number,
  startAtMs?: number,
): Promise<unknown>;

• If confirmed, update the call site in packages/wasm-sdk/test/document-queries.test.mjs accordingly:

 const result = await wasmSdk.get_data_contract_history(
   sdk,
   CONTRACT_WITH_HISTORY,
   10,        // limit
   0,         // offset
-  null       // start at ms
+  undefined  // startAtMs
 );

thephez and others added 5 commits August 21, 2025 09:08
Add try-catch around prefetch_trusted_quorums_testnet() to handle
cases where network is unavailable during testing.

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

Co-Authored-By: Claude <noreply@anthropic.com>
Add test case for ASCII character conversions (I,l,i->1, o->0)
in dpns_convert_to_homograph_safe function.

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

Co-Authored-By: Claude <noreply@anthropic.com>
Extract hardcoded Dashpay contract ID to constant and improve test
comments for better readability.

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

Co-Authored-By: Claude <noreply@anthropic.com>
Prevent multiple concurrent builds of the same ref to reduce
resource usage and avoid conflicts.

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

Co-Authored-By: Claude <noreply@anthropic.com>
Normalize trailing whitespace and indentation for better consistency
and cleaner git diffs.

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

Co-Authored-By: Claude <noreply@anthropic.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

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

⚠️ Outside diff range comments (1)
.github/workflows/wasm-sdk-build.yml (1)

86-122: Harden wasm-opt installer step and reuse the corrected extraction path

Add set -euo pipefail and rely on the corrected directory path; otherwise silent failures can slip by.

-      - name: Install wasm-opt
-        run: |
+      - name: Install wasm-opt
+        shell: bash
+        run: |
+          set -euo pipefail
           if ! command -v wasm-opt &> /dev/null; then
             echo "Installing wasm-opt from GitHub releases..."
             # Get the latest release version
             WASM_OPT_VERSION=$(curl -s https://api.github.com/repos/WebAssembly/binaryen/releases/latest | grep -oP '"tag_name": "\K[^"]+')
             echo "Installing wasm-opt version: $WASM_OPT_VERSION"
@@
             # Download and extract binaryen
             curl -L "https://github.com/WebAssembly/binaryen/releases/download/${WASM_OPT_VERSION}/binaryen-${WASM_OPT_VERSION}-${BINARYEN_ARCH}-linux.tar.gz" -o /tmp/binaryen.tar.gz
             tar -xzf /tmp/binaryen.tar.gz -C /tmp
@@
-            sudo mv /tmp/binaryen-${WASM_OPT_VERSION}/bin/wasm-opt /usr/local/bin/
+            sudo mv "/tmp/binaryen-${WASM_OPT_VERSION}-${BINARYEN_ARCH}-linux/bin/wasm-opt" /usr/local/bin/
             sudo chmod +x /usr/local/bin/wasm-opt
@@
-            rm -rf /tmp/binaryen.tar.gz /tmp/binaryen-${WASM_OPT_VERSION}
+            rm -rf "/tmp/binaryen.tar.gz" "/tmp/binaryen-${WASM_OPT_VERSION}-${BINARYEN_ARCH}-linux"
♻️ Duplicate comments (1)
packages/wasm-sdk/test/document-queries.test.mjs (1)

67-73: Wrapped prefetch in try/catch — exactly what we asked for earlier

Thanks for adopting the offline-safe prefetch. This prevents the script from aborting outside the test harness when offline.

🧹 Nitpick comments (9)
packages/wasm-sdk/test/dpns.test.mjs (3)

84-91: Clarify comment: letters are lowercased; special characters are preserved unchanged

The phrase “other special chars are lowercased but preserved” is misleading—special characters aren’t lowercased. Suggest clarifying that only ASCII letters are lowercased and non-homograph characters (including special chars) are preserved.

-  // Only homograph characters (o,i,l) are converted, other special chars are lowercased but preserved
+  // Only homograph characters (o, i, l) are converted; other characters:
+  // - ASCII letters are lowercased
+  // - non-letters (e.g., punctuation) are preserved unchanged

92-99: Nice: added explicit ASCII homograph mapping test

This directly guards the contract rule (o → 0; i/l → 1) and prevents regressions. Consider adding a quick idempotency follow-up (digits 0/1 remain as-is) to tighten coverage.

 await test('dpns_convert_to_homograph_safe - ASCII homograph conversions (o,i,l)', () => {
   const input = "IlIooLi"; // mix of I,l,i,o
   const result = wasmSdk.dpns_convert_to_homograph_safe(input);
   // Expect: I->i->1, l->1, I->i->1, o->0, o->0, L->l->1, i->1 = "1110011"
   if (result !== "1110011") {
     throw new Error(`Expected "1110011" for "${input}", got "${result}"`);
   }
 });
+
+await test('dpns_convert_to_homograph_safe - digits unchanged (idempotency)', () => {
+  const input = "i10lO";
+  const result = wasmSdk.dpns_convert_to_homograph_safe(input);
+  // i->1, 1->1, 0->0, l->1, O->o->0 => "11010"
+  if (result !== "11010") {
+    throw new Error(`Expected "11010" for "${input}", got "${result}"`);
+  }
+});

229-232: Broadened expected-error path is helpful for offline CI

Catching “Non-trusted mode is not supported in WASM” avoids spurious failures for networked ops. You might centralize this as a tiny helper to DRY up error checks across tests.

+const isNetworkOrTrustedModeError = (e) => {
+  const m = String(e?.message || e);
+  return m.includes('network') || m.includes('connection') || m.includes('Non-trusted mode is not supported in WASM');
+};
 ...
-      if (error.message.includes('network') || error.message.includes('connection') || 
-          error.message.includes('Non-trusted mode is not supported in WASM')) {
+      if (isNetworkOrTrustedModeError(error)) {
         console.log('   Expected error (network or non-trusted mode)');
       } else {
         throw error;
       }
packages/wasm-sdk/test/document-queries.test.mjs (4)

53-59: Static-analysis false positive: constants are public IDs, not secrets

Gitleaks may flag these base58 strings as a “generic API key,” but they’re documented public testnet identifiers (contract IDs), not credentials. Consider annotating or allowlisting to reduce noise (e.g., a .gitleaks.toml rule scoped to test files or a short comment).

 const DPNS_CONTRACT = 'GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec';
-const TOKEN_CONTRACT = 'H7FRpZJqZK933r9CzZMsCuf1BM34NT5P2wSJyjDkprqy';
+const TOKEN_CONTRACT = 'H7FRpZJqZK933r9CzZMsCuf1BM34NT5P2wSJyjDkprqy'; // Public testnet contract ID (non-secret)
 const CONTRACT_WITH_HISTORY = 'HLY575cNazmc5824FxqaEMEBuzFeE4a98GDRNKbyJqCM';
 const DASHPAY_CONTRACT = 'ALybvzfcCwMs7sinDwmtumw17NneuW7RgFtFHgjKmF3A';

104-122: Where on normalizedParentDomainName looks correct; optional: add stable orderBy

Querying under .dash is sensible. For determinism across runs/backends, you can add a simple orderBy (e.g., normalizedParentDomainName asc, normalizedLabel asc) even when the test only logs counts.

-  const result = await wasmSdk.get_documents(
+  const orderBy = JSON.stringify([
+    ["normalizedParentDomainName", "asc"],
+    ["normalizedLabel", "asc"]
+  ]);
+  const result = await wasmSdk.get_documents(
     sdk,
     DPNS_CONTRACT,
     "domain",
     whereClause,
-    null,  // no order by
+    orderBy,
     10,    // limit
     null,  // no start after
     null   // no start at
   );

332-335: Epoch info: updated API and signature

Using get_epochs_info(sdk, startEpoch, count) fits the new surface. Consider asserting basic shape (array or object with expected keys) when network is available, but logging is OK for offline-tolerant runs.


96-101: DRY up offline error handling across catch blocks

There’s repeated string matching for “network/connection” across many tests. A tiny helper reduces duplication and future drift.

+const isNetworkError = (e) => {
+  const m = String(e?.message || e);
+  return m.includes('network') || m.includes('connection');
+};
 ...
-  if (error.message.includes('network') || error.message.includes('connection')) {
+  if (isNetworkError(error)) {
     console.log('   Expected network error (offline)');
   } else {
     throw error;
   }

Also applies to: 150-156, 184-190, 220-226, 248-258, 288-298, 316-324, 336-343

.github/workflows/wasm-sdk-build.yml (2)

149-160: Speed up tests: cache npm deps for the test job

setup-node can cache npm based on the test package-lock to avoid reinstalling deps every run.

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
+         cache: 'npm'
+         cache-dependency-path: packages/wasm-sdk/test/package-lock.json

Also applies to: 193-204


65-76: Shell robustness: prefer explicit shell + strict mode on multi-line steps

Multi-line run steps benefit from shell: bash and set -euo pipefail to stop on first error and avoid using unset vars. Consider applying to all larger run blocks (install tools, build, verify, test, summary).

Also applies to: 123-141, 167-192, 205-210, 242-249

📜 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 9f52983 and 1aa3c33.

📒 Files selected for processing (3)
  • .github/workflows/wasm-sdk-build.yml (6 hunks)
  • packages/wasm-sdk/test/document-queries.test.mjs (10 hunks)
  • packages/wasm-sdk/test/dpns.test.mjs (3 hunks)
🧰 Additional context used
🧠 Learnings (10)
📓 Common learnings
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/build.sh : Build the WASM SDK by running './build.sh' in 'packages/wasm-sdk'
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 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/generate_docs.py : Keep documentation for the WASM SDK in sync by running 'python3 generate_docs.py' in 'packages/wasm-sdk'
📚 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/test/document-queries.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 : 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/test/document-queries.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/**/index.html : When adding new queries or state transitions, update the definitions in index.html.

Applied to files:

  • packages/wasm-sdk/test/document-queries.test.mjs
📚 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/document-queries.test.mjs
  • .github/workflows/wasm-sdk-build.yml
📚 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/document-queries.test.mjs
📚 Learning: 2025-08-14T15:03:56.681Z
Learnt from: thephez
PR: dashpay/platform#2726
File: packages/wasm-sdk/check_documentation.py:69-76
Timestamp: 2025-08-14T15:03:56.681Z
Learning: In packages/wasm-sdk/api-definitions.json, the structure is nested by categories: { "queries": { "categoryName": { "label": "...", "queries": { "actualQueryName": {...} } } } }. The check_documentation.py script correctly iterates over categories and then accesses the nested 'queries'/'transitions' objects within each category to collect the actual query/transition names.

Applied to files:

  • packages/wasm-sdk/test/document-queries.test.mjs
📚 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/document-queries.test.mjs
📚 Learning: 2024-11-06T07:27:01.722Z
Learnt from: shumkov
PR: dashpay/platform#2314
File: packages/wallet-contract/test/bootstrap.js:14-16
Timestamp: 2024-11-06T07:27:01.722Z
Learning: In `packages/wallet-contract/test/bootstrap.js`, for Mocha tests in Node.js, async functions like `loadWasmDpp` can be assigned directly to `beforeAll` without wrapping them in another async function.

Applied to files:

  • packages/wasm-sdk/test/document-queries.test.mjs
📚 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/build.sh : Build the WASM SDK by running './build.sh' in 'packages/wasm-sdk'

Applied to files:

  • .github/workflows/wasm-sdk-build.yml
🧬 Code graph analysis (2)
packages/wasm-sdk/test/document-queries.test.mjs (3)
packages/wasm-sdk/test/voting-contested-resources.test.mjs (3)
  • TEST_IDENTITY (55-55)
  • DPNS_CONTRACT (54-54)
  • sdk (71-71)
packages/wasm-sdk/test/identity-queries.test.mjs (4)
  • TEST_IDENTITY (54-54)
  • DPNS_CONTRACT (55-55)
  • TOKEN_CONTRACT (56-56)
  • sdk (74-74)
packages/wasm-sdk/test/state-transitions.test.mjs (3)
  • TEST_IDENTITY (59-59)
  • DPNS_CONTRACT (60-60)
  • TOKEN_CONTRACT (61-61)
packages/wasm-sdk/test/dpns.test.mjs (1)
packages/wasm-sdk/test/dashpay-contact-keys.test.mjs (2)
  • wasmSdk (22-22)
  • test (48-57)
🪛 Gitleaks (8.27.2)
packages/wasm-sdk/test/document-queries.test.mjs

56-56: 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). (3)
  • GitHub Check: Build JS packages / Build JS
  • GitHub Check: Rust crates security audit
  • GitHub Check: build-wasm-sdk
🔇 Additional comments (8)
packages/wasm-sdk/test/dpns.test.mjs (2)

101-106: Unicode preservation test reads well

Good assertion that Cyrillic е (U+0435) is preserved and not mistaken for ASCII 'e'. This aligns the test with the spec update (only o/i/l conversions).


346-351: Edge-case expectation aligns with spec change

Confirming that only homograph chars are transformed while “@#$%” are preserved is correct per the new DPNS rules.

packages/wasm-sdk/test/document-queries.test.mjs (6)

131-149: Good: orderBy uses an indexed field

Using normalizedParentDomainName asc should be index-backed on DPNS.domain, reducing the chance of “requires index” errors and ensuring stable ordering.


166-171: Correct: range query paired with matching orderBy

Providing orderBy on (normalizedParentDomainName, normalizedLabel) aligns with typical composite indexing for prefix/range operations.


192-208: Negative path for get_document

Exercising the invalid-ID branch is useful; the test rethrows only if it didn’t fail as expected. LGTM.


228-232: Added Dashpay contract fetch

Targets a known contract to avoid false negatives. Looks good.


242-250: Updated history API usage looks consistent

Switched to get_data_contract_history(sdk, id, limit, offset, startAtMs). Parameters and semantics align with the renamed API.


265-267: Fetching multiple contracts in one call

Passing an array from JS to Vec in WASM is a common pattern here. Good coverage.

…rily

Comment out the test due to long timeout with invalid hash and need
for a real state transition hash to properly test the function.

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

Co-Authored-By: Claude <noreply@anthropic.com>
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

🧹 Nitpick comments (2)
packages/wasm-sdk/test/utilities-simple.test.mjs (2)

113-116: Tighten result validation to catch shape/serialization regressions.

Guard against arrays and ensure the object is JSON-serializable. This will surface subtle breaking changes early without being brittle to the exact schema.

Apply this diff:

-        // Should return a proper serialized object
-        if (typeof result !== 'object' || result === null) {
-            throw new Error(`Expected object result, got ${typeof result}`);
-        }
+        // Should return a proper serialized, plain object (not array)
+        if (typeof result !== 'object' || result === null || Array.isArray(result)) {
+            throw new Error(`Expected plain object result, got ${Array.isArray(result) ? 'array' : typeof result}`);
+        }
+        // Ensure it can be serialized (no circular refs or unsupported types)
+        try {
+            JSON.stringify(result);
+        } catch (e) {
+            throw new Error('Result not JSON-serializable');
+        }

217-246: Replace commented-out test with env-gated execution to retain coverage without slowing CI.

Instead of a long commented block, gate the test by an environment variable (e.g., WASM_ST_HASH). This keeps the code live, documents intent, and allows opt-in runs locally or in targeted CI jobs without incurring the 80s timeout in default pipelines.

Apply this diff to enable conditional execution:

-// TODO: Enable this test once we have a valid state transition hash to test with
-// This test is currently disabled because:
-// 1. Using an invalid hash (all zeros) only tests the error path, not success path
-// 2. It takes 80+ seconds to timeout with invalid hash, slowing down test suite
-// 3. It has Rust ownership issues that prevent proper execution
-// 4. To be valuable, we need a real state transition hash to verify the function
-//    correctly retrieves and parses state transition results
-
-/*
-await test('wait_for_state_transition_result - with valid hash', async () => {
-    const builder = wasmSdk.WasmSdkBuilder.new_testnet();
-    const sdk = await builder.build();
-    
-    // TODO: Replace with actual valid state transition hash from a real transaction
-    const validHash = "REPLACE_WITH_ACTUAL_VALID_STATE_TRANSITION_HASH";
-    
-    try {
-        const result = await wasmSdk.wait_for_state_transition_result(sdk, validHash);
-        
-        // Verify result structure
-        if (!result || typeof result !== 'object') {
-            throw new Error('Expected valid result object');
-        }
-        
-        // TODO: Add more specific validation based on expected response structure
-        
-    } finally {
-        sdk.free();
-    }
-});
-*/
+// Optional: enable with `WASM_ST_HASH=<hex>` to validate success path without slowing CI
+const ST_HASH = process.env.WASM_ST_HASH;
+if (ST_HASH) {
+    await test('wait_for_state_transition_result - with valid hash (env-gated)', async () => {
+        const builder = wasmSdk.WasmSdkBuilder.new_testnet();
+        const sdk = await builder.build();
+        try {
+            const result = await wasmSdk.wait_for_state_transition_result(sdk, ST_HASH);
+            if (!result || typeof result !== 'object') {
+                throw new Error('Expected valid result object');
+            }
+            // TODO: Add schema assertions once response contract is finalized
+        } finally {
+            sdk.free();
+        }
+    });
+} else {
+    console.log('   Skipping wait_for_state_transition_result test (set WASM_ST_HASH to enable)');
+}

If you want, I can add a minimal CI matrix job that sets WASM_ST_HASH from a workflow input/secret for ad-hoc validations.

📜 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 1aa3c33 and 76ed4a3.

📒 Files selected for processing (1)
  • packages/wasm-sdk/test/utilities-simple.test.mjs (3 hunks)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
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/build.sh : Build the WASM SDK by running './build.sh' in 'packages/wasm-sdk'
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 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/generate_docs.py : Keep documentation for the WASM SDK in sync by running 'python3 generate_docs.py' in 'packages/wasm-sdk'
📚 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/utilities-simple.test.mjs
📚 Learning: 2024-11-06T07:27:01.722Z
Learnt from: shumkov
PR: dashpay/platform#2314
File: packages/wallet-contract/test/bootstrap.js:14-16
Timestamp: 2024-11-06T07:27:01.722Z
Learning: In `packages/wallet-contract/test/bootstrap.js`, for Mocha tests in Node.js, async functions like `loadWasmDpp` can be assigned directly to `beforeAll` without wrapping them in another async function.

Applied to files:

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

Applied to files:

  • packages/wasm-sdk/test/utilities-simple.test.mjs
🧬 Code graph analysis (1)
packages/wasm-sdk/test/utilities-simple.test.mjs (2)
packages/wasm-sdk/test/sdk-init-simple.test.mjs (1)
  • sdk (81-81)
packages/wasm-sdk/test/dashpay-contact-keys.test.mjs (1)
  • test (48-57)
⏰ 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: Rust crates security audit
  • GitHub Check: Build JS packages / Build JS
  • GitHub Check: build-wasm-sdk
🔇 Additional comments (2)
packages/wasm-sdk/test/utilities-simple.test.mjs (2)

109-116: Good pivot to 'simple' and runtime validation for testSerialization.

Switching the arg to 'simple' and asserting a non-null object matches the updated API semantics and prevents silent regressions from falsy returns.


269-283: Smart: existence check for start() avoids double-init panics while still asserting the public API.

This balances safety with coverage given wasm-bindgen’s auto-start behavior on init.

@thephez thephez requested a review from pauldelucia August 21, 2025 17:09
@thephez
Copy link
Collaborator Author

thephez commented Aug 22, 2025

@QuantumExplorer this one should be ready to go 🚀

@QuantumExplorer QuantumExplorer merged commit 958ff1d into v2.1-dev Aug 28, 2025
30 of 38 checks passed
@QuantumExplorer QuantumExplorer deleted the wasm-sdk-fix-tests branch August 28, 2025 07:29
lklimek pushed a commit that referenced this pull request Sep 1, 2025
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