Skip to content

WASM JSON serialization rejects valid u64 values above Number.MAX_SAFE_INTEGER #3786

Open

Description

@thephez

Expected Behavior

Document.toJSON() should serialize any document accepted by Platform state.

For u64-sized document fields, including system fields such as $price, $revision, credit amounts, and user-defined integer fields, toJSON() should emit JSON-safe strings when values exceed JavaScript’s safe integer range. This matches the current DocumentJSON TypeScript documentation, which states that u64 fields are stringified because JSON does not support BigInt.

Current Behavior

Document.toJSON() throws when a numeric document field contains a value greater than Number.MAX_SAFE_INTEGER.

Observed error:

WasmDppError: Failed to convert JSON to JsValue: Error: 1000000000000000000 can't be represented as a JavaScript number

The query itself succeeds and returns Document handles. The failure happens only when calling .toJSON() on the document containing the large value.

This means one valid document can break callers that iterate query results and serialize each document.

Possible Solution

The likely failure path is:

  • DocumentWasm::to_json() calls self.document.to_json(...)
  • it merges wrapper metadata into the resulting serde_json::Value
  • it then calls serialization::json_to_js_value(...)
  • json_to_js_value() uses serde_wasm_bindgen::Serializer::json_compatible()
  • unsafe integer-sized serde_json::Number values are converted toward JS Number and rejected

Before converting serde_json::Value to JsValue, normalize integer numbers that cannot be safely represented as JavaScript numbers into strings. This would align Document.toJSON() with the existing DocumentJSON contract.

A regression test should cover Document.toJSON() with a document property or $price value such as "1000000000000000000" / 1_000_000_000_000_000_000 and assert that toJSON() does not throw and returns the value as a string.

Steps to Reproduce

Save this as repro-toJSON-overflow.mjs:

/**
 * Standalone repro for @dashevo/evo-sdk Document.toJSON() throwing on numeric
 * fields larger than Number.MAX_SAFE_INTEGER.
 *
 * Confirmed against evo-sdk 3.1.0-dev.6 and 4.0.0-beta.2.
 *
 * Setup (already on testnet):
 *   - Contract 5hK6SMfN4m2vU1t9qhvngUUQjsXeMNwr8MZdFeGBH8Aa
 *   - Document DAFsGgv4LW9biqVwqQ66TrJpRkUYV1oveY1BQDEU6RyD has
 *     $price = 1_000_000_000_000_000_000 credits (10 M DASH).
 *     Platform accepted the state transition; Platform Explorer renders it.
 *
 * Install (only dependency):
 *   npm install @dashevo/[email protected]
 *
 * Run:
 *   node repro-toJSON-overflow.mjs
 *
 * Expected: PASS for every document except the one above, which throws
 * WasmDppError. Exits 1 if any document throws.
 */

import { EvoSDK } from "@dashevo/evo-sdk";

const CONTRACT_ID = "CkAX4amndy33YxCyQ3op4QmWofsiW9TukoMh2nvHQk9B";
const DOCUMENT_TYPE = "card";

// Platform version must match what the network is currently running.
// Bump this if the network has moved on; see Platform Explorer for the
// current protocolVersion.
const sdk = EvoSDK.testnetTrusted({ version: 11 });
await sdk.connect();

const results = await sdk.documents.query({
  dataContractId: CONTRACT_ID,
  documentTypeName: DOCUMENT_TYPE,
  limit: 100,
});

// sdk.documents.query returns a Map<id, Document> in the Node bindings,
// an array in some others, or a plain object keyed by id — handle all three.
const entries =
  results instanceof Map
    ? [...results.entries()]
    : Array.isArray(results)
      ? results.map((d) => [null, d])
      : Object.entries(results ?? {});

let okCount = 0;
let failCount = 0;
let firstFailure = null;

for (const [id, doc] of entries) {
  try {
    doc.toJSON();
    okCount += 1;
  } catch (err) {
    failCount += 1;
    if (!firstFailure) firstFailure = { id, err };
    console.log(`FAIL  ${id}  ${err?.message ?? err}`);
  }
}

console.log(`\nSummary: ${okCount} ok, ${failCount} failed.`);

if (firstFailure) {
  console.log(`\nFailure detail:`);
  console.log(`  document id: ${firstFailure.id}`);
  console.log(`  error class: ${firstFailure.err?.constructor?.name}`);
  console.log(`  error message: ${firstFailure.err?.message}`);
}

process.exit(failCount > 0 ? 1 : 0);

Then run:

npm install @dashevo/[email protected]
node repro-toJSON-overflow.mjs

The script should report failing documents including: 4KUPbv72npj6vGHet7sjHtV7TQxkdxpoBwavHfVBLZAR.

Context

$price is a u64 credit amount. Valid Platform state can exceed JavaScript’s safe integer range, so SDK consumers can receive valid documents that cannot be serialized through Document.toJSON().

This affects application code that lists documents, renders search results, or serializes query responses. A single valid document with a large u64 field can crash the whole serialization loop unless each .toJSON() call is individually wrapped in try/catch.

Platform Explorer and other SDK paths can represent the same value correctly as a string, so this appears isolated to the WASM Document.toJSON() conversion boundary.

Your Environment

  • Version used: confirmed in @dashevo/evo-sdk 3.1.0-dev.6 and 4.0.0-beta.2
  • Network: testnet
  • Environment name and version: Node.js SDK consumer
  • Operating System and version: not OS-specific

Activity

  1. added
    bug
    on Jun 2, 2026
  2. thephez commented on Jun 2, 2026

    @thephez
    CollaboratorAuthor

    Workaround: per-field getters on the Document WASM handle don't go through the broken serializer.

    Individual getters still work on docs whose toJSON() throws, and return native types directly (BigInt for u64 fields).

    Probe against the testnet doc that's triggering this ($price = 1e18 credits):

    Per-field getters:
      id                   Identifier("DAFsGgv4...")
      ownerId              Identifier("C3csSgWJ...")
      revision             bigint(5)
    
    properties:
      $price               bigint(1000000000000000000)
      attack               bigint(6)
      defense              bigint(1)
      name                 string("Shadow Fox")
    
    toJSON() baseline:
      WasmDppError: Failed to convert JSON to JsValue: Error: 1000000000000000000 can't be represented as a JavaScript number
    

    So app code can fall back to hand-assembling the document from doc.id / doc.ownerId / doc.properties when toJSON() throws — no data loss.

    Suggests the root cause is scoped to the bulk JSON converter behind Document.toJSON(); the per-field bindings already emit BigInt for u64. A fix that uses the same approach there (e.g. serde_wasm_bindgen::Serializer::new().serialize_large_numbers_as_bigints(true)) should resolve it.

    Example script showing this ```js /** * Probe showing that individual getters on a Document WASM handle still * work when Document.toJSON() throws (#3786). * * Install: * npm install @dashevo/[email protected] * * Run: * node repro-toJSON-getters-probe.mjs */

    import { EvoSDK } from "@dashevo/evo-sdk";

    const CONTRACT_ID = "CkAX4amndy33YxCyQ3op4QmWofsiW9TukoMh2nvHQk9B";
    const DOCUMENT_TYPE = "card";
    const BAD_DOC_ID = "F8zkqfFcrgNXGgA76vtGiitbWDHVnbisxvejrxqhNAW5";

    const sdk = EvoSDK.testnetTrusted({ version: 11 });
    await sdk.connect();

    const results = await sdk.documents.query({
    dataContractId: CONTRACT_ID,
    documentTypeName: DOCUMENT_TYPE,
    limit: 100,
    });

    const entries =
    results instanceof Map
    ? [...results.entries()]
    : Array.isArray(results)
    ? results.map((d) => [null, d])
    : Object.entries(results ?? {});

    const badDoc = entries.find(([id]) => id === BAD_DOC_ID)?.[1];
    if (!badDoc) {
    console.error(Could not find bad doc ${BAD_DOC_ID} in results.);
    process.exit(2);
    }

    function describe(value) {
    if (value == null) return String(value);
    const t = typeof value;
    if (t === "bigint") return bigint(${value});
    if (t === "number") return number(${value});
    if (t === "string") return string("${value}");
    if (value.constructor?.name && typeof value.toString === "function") {
    try {
    return ${value.constructor.name}("${value.toString()}");
    } catch {
    return ${value.constructor.name}(<toString threw>);
    }
    }
    return t;
    }

    console.log(Document ${BAD_DOC_ID}\n);

    console.log(Per-field getters:);
    for (const field of [
    "id",
    "ownerId",
    "dataContractId",
    "documentTypeName",
    "revision",
    ]) {
    console.log( ${field.padEnd(20)} ${describe(badDoc[field])});
    }

    console.log(\nproperties:);
    const props = badDoc.properties;
    for (const k of Object.keys(props)) {
    console.log( ${k.padEnd(20)} ${describe(props[k])});
    }

    console.log(\ntoJSON() baseline:);
    try {
    badDoc.toJSON();
    console.log( unexpectedly succeeded);
    } catch (e) {
    console.log( ${e?.constructor?.name}: ${e?.message});
    }

    </details>
    
  3. thephez commented on Oct 6, 2026

    @thephez
    CollaboratorAuthor

    Status update against v5.0-dev: this is only partly fixed.

    #3573 added #[json_safe_fields] to DocumentV0, so typed system fields such as $revision and the block heights should now be written as strings when they're above Number.MAX_SAFE_INTEGER.

    The case in this issue isn't covered. $price and user-defined integer properties live in the #[serde(flatten)] properties map, which the macro skips. Value::U64 still serializes as a plain number. DocumentWasm::to_json still finishes with serde_wasm_bindgen::Serializer::json_compatible(), which rejects unsafe integers. So a document with a $price around 1e18 should still throw in toJSON(). That's based on reading the code; I haven't re-run the repro. There's also no toJSON regression test with a large value yet.

    Leaving open for the properties map case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions