Skip to content

fix(sdk): outdated platfrom version in JS SDK - #3046

Merged
QuantumExplorer merged 2 commits into
v3.1-devfrom
refactor/sdk/platform-version
Feb 9, 2026
Merged

QuantumExplorer merged 2 commits into
v3.1-devfrom
refactor/sdk/platform-version

Conversation

@shumkov

@shumkov shumkov commented Feb 3, 2026 •

Copy link
Copy Markdown
Collaborator

Issue being fixed or feature implemented

PlatformVersionWasm was a manually-maintained enum (V1–V10) that required 6 separate code changes every time a new platform version was added in Rust. It was already out of sync — Rust had V1–V12 while WASM only had V1–V10.

What was done?

Replaced PlatformVersionWasm enum with a u32 wrapper struct that automatically adapts to any number of platform versions without code changes:

  • Struct wrapping u32 — constructor validates via PlatformVersion::get(), so only valid versions are accepted
  • Static methods — latest(), first(), current() delegate to PlatformVersion statics instead of hardcoding values
  • Default — uses PlatformVersion::desired() (current protocol version) instead of hardcoded 1
  • Instance detection — uses impl_wasm_type_info! macro and to_wasm() pattern consistent with other WASM types
  • Input validation — uses try_to_u32() for numeric input (handles NaN, Infinity, fractional values)
  • Removed — parse_version_string() helper, string handling in TryFrom, unused From<PlatformVersionWasm> for String
  • TypeScript type — PlatformVersionLike simplified to PlatformVersion | number (removed string)
  • Tests updated — all 4 test files use new PlatformVersion(1) instead of PlatformVersion.PLATFORM_V1, explicit version passed where comparing against v1 fixtures

How Has This Been Tested?

  • cargo fmt -p wasm-dpp2 -- --check — clean
  • cargo clippy -p wasm-dpp2 --target wasm32-unknown-unknown — clean
  • cargo check -p wasm-dpp2 --target wasm32-unknown-unknown — compiles
  • cargo check -p wasm-sdk --target wasm32-unknown-unknown — compiles
  • yarn workspace dash build — compiles
  • Full WASM build (build.sh + bundle.cjs) — success
  • yarn workspace @dashevo/wasm-dpp2 test — 718 passing, 0 failing

Breaking Changes

  • PlatformVersion.PLATFORM_V1, PlatformVersion.PLATFORM_V2, etc. no longer exist. Use new PlatformVersion(1), new PlatformVersion(2), etc.
  • PlatformVersionLike no longer accepts string — only PlatformVersion | number
  • Default platform version when omitted is now current (desired) instead of 1

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

  • Refactor

    • Restructured PlatformVersionWasm API from enum-based design to struct-based with new constructors and static methods for accessing latest, first, and current platform versions.
    • Updated version specification to use numeric format.
  • Tests

    • Updated test cases to align with new PlatformVersion API.

@github-actions github-actions Bot added this to the v3.1.0 milestone Feb 3, 2026
@shumkov shumkov self-assigned this Feb 3, 2026
@coderabbitai

coderabbitai Bot commented Feb 3, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@shumkov has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 8 minutes and 52 seconds before requesting another review.

⌛ How to resolve this issue?

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

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

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

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

Please see our FAQ for further information.

📝 Walkthrough

Walkthrough

The PlatformVersionWasm API is refactored from an enum-based design to a struct-based approach with a single version: u32 field, adding a validation constructor and static accessor methods. Test files are updated to use the new constructor syntax instead of enum constants.

Changes

Cohort / File(s) Summary
Core API Refactoring
packages/wasm-dpp2/src/version.rs
Replaced PlatformVersionWasm enum with a struct containing a version field; added constructor with validation, static methods (latest/first/current), and getter; updated conversion logic from JsValue to handle undefined/null defaults and raw number parsing.
Test Updates
packages/wasm-dpp2/tests/unit/DataContract.spec.ts, packages/wasm-dpp2/tests/unit/DataContractCreateStateTransition.spec.ts, packages/wasm-dpp2/tests/unit/DataContractUpdateStateTransition.spec.ts, packages/wasm-dpp2/tests/unit/Document.spec.ts
Replaced PlatformVersion.PLATFORM_V1 constant usages with new PlatformVersion(1) constructor calls across test method invocations and assertions.

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 From enums old to structs so new,
A version born with fields so true,
Constructors validate with care,
The tests hop forth, their constants bare,
Refactored paths both clean and bright!

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title mentions 'outdated platform version' but the PR is primarily about replacing an enum-based PlatformVersionWasm with a u32-wrapping struct that dynamically adapts to Rust versions—a structural refactoring, not fixing outdated versions. Consider revising the title to reflect the main change, e.g., 'refactor(sdk): replace PlatformVersionWasm enum with dynamic u32 struct' or 'fix(sdk): make PlatformVersionWasm adapt to Rust platform versions automatically'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/sdk/platform-version

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@shumkov shumkov moved this to In review / testing in Platform team Feb 3, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@packages/wasm-dpp2/src/version.rs`:
- Around line 45-51: Change the wasm constructor signature for
PlatformVersionWasm::new to accept a JsValue and validate it with try_to_u32
(reusing the same checks as TryFrom<&JsValue>) before proceeding: call
try_to_u32 on the incoming JsValue, map any conversion error to
WasmDppError::invalid_argument, then call PlatformVersion::get with the
resulting u32 and preserve the existing PlatformVersion::get error mapping;
update references to the constructor accordingly so the PlatformVersionWasm {
version } is created only after the validated u32 is obtained.
🧹 Nitpick comments (1)
packages/wasm-dpp2/src/version.rs (1)

91-110: Consider rejecting string inputs to match the new PlatformVersionLike contract.

PlatformVersionLike no longer includes strings, but try_to_u32 still accepts numeric strings. If you want runtime behavior to match the TS declaration, explicitly reject strings before try_to_u32.

♻️ Suggested guard
     if value.is_undefined() || value.is_null() {
         return Ok(Self::default());
     }

     // Detect PlatformVersionWasm instance via to_wasm
     if let Ok(wasm_ref) = value.to_wasm::<PlatformVersionWasm>("PlatformVersion") {
         return Ok(wasm_ref.clone());
     }
+
+    if value.as_string().is_some() {
+        return Err(WasmDppError::invalid_argument(
+            "'platformVersion' must be a number",
+        ));
+    }

     // Otherwise treat as raw number
     let version = try_to_u32(value, "platformVersion")?;

Comment on lines +45 to +51
#[wasm_bindgen(constructor)]
pub fn new(version: u32) -> Result<PlatformVersionWasm, WasmDppError> {
PlatformVersion::get(version).map_err(|_| {
WasmDppError::invalid_argument(format!("unknown platform version: {}", version))
})?;
Ok(PlatformVersionWasm { version })
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

wasm-bindgen JavaScript number conversion u32 truncation fractional

💡 Result:

In wasm-bindgen, passing a JavaScript Number into a Rust u32 parameter works like this: (rustwasm.github.io)

  • If the JS value is NaN, Infinity, or -Infinity → Rust receives 0.
  • Otherwise, the JS number is truncated toward zero (fractional part dropped, like Math.trunc).
  • Then it’s converted to u32; if it’s out of range, it wraps modulo 2³² (same behavior as new Uint32Array([value])[0]).

Examples (JS → Rust u32):

  • 1.999 → 1
  • -1.999 → 4294967295 (because Math.trunc(-1.999) === -1, then wrap)
  • 4294967296 → 0

Citations:


🏁 Script executed:

# Search for try_to_u32 function in the codebase
rg "try_to_u32" --type rust -B2 -A5

Repository: dashpay/platform

Length of output: 20722


🏁 Script executed:

# Search for TryFrom implementation with JsValue for PlatformVersionWasm
rg "TryFrom.*JsValue" --type rust -B3 -A10

Repository: dashpay/platform

Length of output: 50374


🏁 Script executed:

# Check the actual file to understand current implementation and related code
cat -n packages/wasm-dpp2/src/version.rs | head -80

Repository: dashpay/platform

Length of output: 3013


🏁 Script executed:

# Search for other constructors in wasm files to see if there's a pattern
rg "#\[wasm_bindgen\(constructor\)\]" --type rust -B2 -A8 -m 10

Repository: dashpay/platform

Length of output: 50373


Use JsValue and try_to_u32 in the constructor for consistent input validation.

The constructor currently accepts a bare u32, which allows wasm-bindgen to silently truncate fractional numbers (e.g., 1.999 → 1) and convert NaN/Infinity to 0 without validation. This bypasses the NaN/Infinity/fractional checks that try_to_u32 enforces and that the TryFrom<&JsValue> implementation already applies. Change the constructor to accept JsValue and validate via try_to_u32 to keep behavior consistent with the trait implementation.

🔧 Suggested fix
-    pub fn new(version: u32) -> Result<PlatformVersionWasm, WasmDppError> {
-        PlatformVersion::get(version).map_err(|_| {
-            WasmDppError::invalid_argument(format!("unknown platform version: {}", version))
-        })?;
-        Ok(PlatformVersionWasm { version })
-    }
+    pub fn new(version: JsValue) -> Result<PlatformVersionWasm, WasmDppError> {
+        let version = try_to_u32(&version, "platformVersion")?;
+        PlatformVersion::get(version).map_err(|_| {
+            WasmDppError::invalid_argument(format!("unknown platform version: {}", version))
+        })?;
+        Ok(PlatformVersionWasm { version })
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#[wasm_bindgen(constructor)]
pub fn new(version: u32) -> Result<PlatformVersionWasm, WasmDppError> {
PlatformVersion::get(version).map_err(|_| {
WasmDppError::invalid_argument(format!("unknown platform version: {}", version))
})?;
Ok(PlatformVersionWasm { version })
}
#[wasm_bindgen(constructor)]
pub fn new(version: JsValue) -> Result<PlatformVersionWasm, WasmDppError> {
let version = try_to_u32(&version, "platformVersion")?;
PlatformVersion::get(version).map_err(|_| {
WasmDppError::invalid_argument(format!("unknown platform version: {}", version))
})?;
Ok(PlatformVersionWasm { version })
}
🤖 Prompt for AI Agents
In `@packages/wasm-dpp2/src/version.rs` around lines 45 - 51, Change the wasm
constructor signature for PlatformVersionWasm::new to accept a JsValue and
validate it with try_to_u32 (reusing the same checks as TryFrom<&JsValue>)
before proceeding: call try_to_u32 on the incoming JsValue, map any conversion
error to WasmDppError::invalid_argument, then call PlatformVersion::get with the
resulting u32 and preserve the existing PlatformVersion::get error mapping;
update references to the constructor accordingly so the PlatformVersionWasm {
version } is created only after the validated u32 is obtained.

@QuantumExplorer
QuantumExplorer merged commit 9cf964f into v3.1-dev Feb 9, 2026
1 check passed
@QuantumExplorer
QuantumExplorer deleted the refactor/sdk/platform-version branch February 9, 2026 00:24
@github-project-automation github-project-automation Bot moved this from In review / testing to Done in Platform team Feb 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

2 participants