{"id":"XE-0008","kind":"bounty","visibility":"public","source":"github","source_repo":"xeprotocol/xe","source_ref":"16","source_url":"https://github.com/xeprotocol/xe/issues/16","reporter_id":6,"title":"SDK bigint serializer converts matching memo strings into JSON numbers (Minor)","area":"sdk-docs-web","claimed_tier":"minor","assessed_tier":null,"verdict":null,"duplicate_of":null,"tracked":true,"internal_ref":"","internal_url":null,"status":"accepted","closed_reason":null,"github_state":"open","disclosed_at":null,"award_xe":null,"award_approved":false,"paid_ref":"","created_at":"2026-10-29T13:57:14.120043+00:00","updated_at":"2026-11-10T11:38:23.416078+00:00","source_created_at":"2026-10-23T13:09:04+00:00","told_at":"2026-11-10T00:15:50+00:00","status_changed_at":"2026-10-29T14:04:13.450394+00:00","url":"https://bounty.xe.network/XE-0008","body":"# SDK bigint serializer rewrites matching string values as JSON numbers\n\n**Suggested severity:** Minor / SDK correctness (bounty eligibility uncertain). This is not presented as a security vulnerability.\n\n## Summary\n\nstringifyWithBigInts converts BigInts to a string marker and then applies a global regular expression that removes quotes from every string matching that marker. A user-provided string such as \"__bigint__123\" is therefore emitted as JSON number 123. For a send memo, the SDK computes/signs the block using the original memo string, but serializes the request with a numeric memo; the node core.Block.Memo is a Go string, so this no longer represents the signed block and a strict JSON decoder cannot decode the number into that string field. This causes the user operation to fail before acceptance; no ledger corruption or funds impact demonstrated.\n\n## Affected version\n\nLocal checkout xeprotocol/sdk at e5e21f43ee93bba89af87f6f3b371e16e2af8c1c. Read-only remote git ls-remote reported current master HEAD d2740484e882c21856600149f282bdf51e63eecd; remote src/json.ts and test/unit/json.test.ts retain the same marker+regex implementation and no collision regression test.\n\n## Reproduction\n\nFrom SDK directory with dependencies/build (dist):\n\n    node --input-type=module - <<'JS'\n    import { XeClient } from './dist/client.js';\n    let captured;\n    const client = new XeClient({\n      url: 'http://127.0.0.1:1', retries: 0,\n      fetch: async (url, init) => {\n        captured = { url, body: init.body };\n        return new Response('{\"ok\":true}', { status: 200 });\n      },\n    });\n    await client.request('/blocks/send', {\n      method: 'POST',\n      body: { type: 'send', memo: '__bigint__123', amount: 123n },\n    });\n    console.log(captured.body);\n    console.log(typeof JSON.parse(captured.body).memo);\n    JS\n\nObserved output: {\"type\":\"send\",\"memo\":123,\"amount\":123} followed by number; expected memo is the string \"__bigint__123\". This exercises the actual XeClient.request JSON-body serialization path with an injected local mock fetch; no external network or wallet is used. Directly, stringifyWithBigInts({memo:'__bigint__-9'}) emits {\"memo\":-9} as well.\n\n## Impact and boundaries\n\nXe.send({memo:'__bigint__123', ...}) hashes/signs the string in canonical block representation, then maps that same string into wire.memo; JSON serialization changes it to a number. In the node, core.Block.Memo is declared Memo string (json:\"memo,omitempty\"), so decoding a number as a string is a type error. This is narrowly triggered failure of the caller's own operation, not remote denial of service, cross-account impact, signature forgery, or ledger corruption. Memo validation permits ordinary ASCII strings of this form within its size limit. No testnet transaction was sent.\n\n## Suggested fix and regression test\n\nAvoid a string sentinel in JSON output. Use a token-aware JSON encoder emitting BigInts as raw integer tokens while preserving strings, or another collision-proof traversal/serializer. Add tests for ordinary strings equal to __bigint__123 and __bigint__-9 (and marker-like text) alongside BigInts; assert memo remains a JSON string in captured /blocks/send request.\n\n## Duplicate check\n\nRead all 15 issue bodies returned by xeprotocol/xe issues API and compared source/tests at remote master. No report of this SDK serializer marker collision found. Issue #10/#11 concern core memo Unicode controls, not marker collision. Issue #13 concerns explorer uint64 rendering, distinct from SDK request serialization.\n\n## Bounty eligibility\n\nThe program includes SDK key handling and API. This appears to fit as an SDK data-integrity/correctness defect, but its narrow input-triggered, caller-local failure may be treated as a minor product bug or not rewarded. Request triage; do not claim security-tier impact.\n\n## Reporting details\n\nSubmitted for triage under https://test.network/bounty. Suggested Minor correctness issue only; eligibility and severity are the team’s decision. Reproduction was local against the SDK request path, not a live testnet transaction.\n\nTestnet XE address controlled for this investigation: `8d1e9ec24ed9b710dcddeaef4f8055c01af4744cbaafdaf4ebe630fed715d6fd`. Please coordinate a designated mainnet payout address before any genesis payout; this testnet address is not a claim of mainnet compatibility.\n","patch_refs":[],"thread":[{"id":5,"source":"github","source_ref":"6367979767","author":"Mewnzter","team":false,"body":"## Proposed remediation and regression coverage\n\nPrepared a local candidate patch against SDK master d2740484e882c21856600149f282bdf51e63eecd. Independent rerun:391/391 unit tests pass, typecheck and lint pass, git diff --check clean. This is a proposed fix, not a claim of upstream acceptance or reward eligibility.\n\nThe implementation uses one native JSON.stringify pass with provenance for emitted values, then rewrites only generated bigint value tokens. It preserves marker-like strings/property keys and native toJSON/getter invocation count. Regression cases include changing toJSON values, getter invocation count, escaping, nesting and the actual XeClient.request payload. An earlier double-serialization candidate was rejected during review.\n\nPatch below includes tests; please review API typing (string|undefined follows native JSON.stringify) and native JSON edge cases before adopting. No protocol/funds impact beyond original report is claimed.\n\n```diff\ndiff --git a/src/client.ts b/src/client.ts\nindex 1fb98d3..b80e3fb 100644\n--- a/src/client.ts\n+++ b/src/client.ts\n@@ -166,12 +166,11 @@ export class XeClient {\n     const timer = setTimeout(() => controller.abort(new Error(`timeout after ${this.#timeoutMs}ms`)), this.#timeoutMs)\n     let res: Response\n     try {\n+      const body = init?.body === undefined ? undefined : stringifyWithBigInts(init.body)\n       res = await this.#fetch(`${this.url}${path}`, {\n         method: init?.method ?? 'GET',\n         signal: controller.signal,\n-        ...(init?.body === undefined\n-          ? {}\n-          : { headers: { 'Content-Type': 'application/json' }, body: stringifyWithBigInts(init.body) }),\n+        ...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body }),\n       })\n     } catch (err) {\n       throw new XeTransportError(`${init?.method ?? 'GET'} ${path}: ${(err as Error).message}`, { cause: err })\ndiff --git a/src/json.ts b/src/json.ts\nindex b24e488..10ace97 100644\n--- a/src/json.ts\n+++ b/src/json.ts\n@@ -65,8 +65,8 @@ const UNSAFE_DIGITS = 16\n  * memo would corrupt real user data.\n  */\n function quoteLongIntegers(text: string): string {\n-  let out = ''\n   let i = 0\n+  let out = ''\n   let inString = false\n   while (i < text.length) {\n     const ch = text[i]!\n@@ -143,9 +143,99 @@ export function asBigInt(value: unknown, field: string): bigint {\n  * node expects these fields as JSON numbers, so they are emitted unquoted\n  * without ever passing through a Number.\n  */\n-export function stringifyWithBigInts(value: unknown): string {\n-  const marked = JSON.stringify(value, (_key, v: unknown) =>\n-    typeof v === 'bigint' ? `__bigint__${v.toString()}` : v,\n-  )\n-  return marked.replace(/\"__bigint__(-?\\d+)\"/g, '$1')\n+export function stringifyWithBigInts(value: unknown): string | undefined {\n+  // The replacer records which emitted string tokens came from BigInts. This\n+  // preserves native JSON.stringify's one-pass toJSON/getter behavior while\n+  // letting the scanner distinguish them from any caller string or key.\n+  const tokenKinds: Array<'bigint' | 'value' | 'object'> = []\n+  const marker = '__xe_bigint_token__'\n+  const marked = JSON.stringify(value, function (this: unknown, _key, v: unknown) {\n+    if (typeof v === 'bigint') {\n+      tokenKinds.push('bigint')\n+      return marker + v.toString()\n+    }\n+    if (v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {\n+      tokenKinds.push('value')\n+      return v\n+    }\n+    if (typeof v === 'undefined' || typeof v === 'function' || typeof v === 'symbol') {\n+      // JSON.stringify emits null for these in arrays, but omits object values.\n+      if (Array.isArray(this)) tokenKinds.push('value')\n+      return v\n+    }\n+    if (typeof v === 'object') {\n+      // Container values are ignored by the token scanner; boxed primitives\n+      // instead serialize as scalar tokens and consume this same provenance.\n+      tokenKinds.push('object')\n+      return v\n+    }\n+    return v\n+  })\n+  if (marked === undefined) return undefined\n+\n+  let tokenIndex = 0\n+  const stringEnd = (start: number): number => {\n+    let end = start + 1\n+    while (end < marked.length) {\n+      if (marked[end] === '\\\\') { end += 2; continue }\n+      if (marked[end] === '\"') return end + 1\n+      end++\n+    }\n+    throw new Error('stringifyWithBigInts: malformed JSON string token')\n+  }\n+  const takeValue = (): 'bigint' | 'value' | 'object' | undefined => tokenKinds[tokenIndex++]\n+  const rewrite = (start: number): { text: string; end: number } => {\n+    let pos = start\n+    const ch = marked[pos]\n+    if (ch === '{') {\n+      takeValue() // this source object produced a JSON container\n+      let text = '{'\n+      pos++\n+      if (marked[pos] === '}') return { text: text + '}', end: pos + 1 }\n+      while (true) {\n+        const keyEnd = stringEnd(pos)\n+        text += marked.slice(pos, keyEnd)\n+        pos = keyEnd\n+        text += ':'\n+        pos++\n+        const child = rewrite(pos)\n+        text += child.text\n+        pos = child.end\n+        if (marked[pos] === '}') return { text: text + '}', end: pos + 1 }\n+        text += ','\n+        pos++\n+      }\n+    }\n+    if (ch === '[') {\n+      takeValue() // this source array produced a JSON container\n+      let text = '['\n+      pos++\n+      if (marked[pos] === ']') return { text: text + ']', end: pos + 1 }\n+      while (true) {\n+        const child = rewrite(pos)\n+        text += child.text\n+        pos = child.end\n+        if (marked[pos] === ']') return { text: text + ']', end: pos + 1 }\n+        text += ','\n+        pos++\n+      }\n+    }\n+    if (ch === '\"') {\n+      const end = stringEnd(pos)\n+      const token = marked.slice(pos, end)\n+      const kind = takeValue()\n+      if (kind === 'bigint') {\n+        const decoded = JSON.parse(token) as string\n+        const digits = decoded.startsWith(marker) ? decoded.slice(marker.length) : ''\n+        if (!/^-?\\d+$/.test(digits)) throw new Error('stringifyWithBigInts: invalid bigint token')\n+        return { text: digits, end }\n+      }\n+      return { text: token, end }\n+    }\n+    let end = pos\n+    while (end < marked.length && marked[end] !== ',' && marked[end] !== '}' && marked[end] !== ']') end++\n+    takeValue()\n+    return { text: marked.slice(pos, end), end }\n+  }\n+  return rewrite(0).text\n }\ndiff --git a/test/unit/client.test.ts b/test/unit/client.test.ts\nindex 1a3202c..1ed6a83 100644\n--- a/test/unit/client.test.ts\n+++ b/test/unit/client.test.ts\n@@ -26,6 +26,17 @@ const client = (responses: Array<{ status: number; body: string }>, retries = 0)\n }\n \n describe('XeClient', () => {\n+  it('keeps a memo marker string intact in the submitted JSON body', async () => {\n+    let body = ''\n+    const fetch = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {\n+      body = String(init?.body)\n+      return new Response('{\"ok\":true}', { status: 200 })\n+    }) as unknown as typeof globalThis.fetch\n+    const c = new XeClient({ url: 'http://node.test', fetch, retries: 0 })\n+    await c.request('/blocks/send', { method: 'POST', body: { memo: '__bigint__123', amount: 123n } })\n+    expect(JSON.parse(body)).toEqual({ memo: '__bigint__123', amount: 123 })\n+  })\n+\n   it('strips a trailing slash from the base url', () => {\n     expect(new XeClient({ url: 'http://node.test/' }).url).toBe('http://node.test')\n   })\ndiff --git a/test/unit/json.test.ts b/test/unit/json.test.ts\nindex dedbe3f..710b4c7 100644\n--- a/test/unit/json.test.ts\n+++ b/test/unit/json.test.ts\n@@ -75,10 +75,58 @@ describe('lossless JSON', () => {\n \n     it('round-trips through the lossless parser', () => {\n       const out = stringifyWithBigInts({ amount: 18446744073709551615n })\n-      expect((parseLossless(out) as { amount: bigint }).amount).toBe(18446744073709551615n)\n+      expect((parseLossless(out!) as { amount: bigint }).amount).toBe(18446744073709551615n)\n     })\n \n-    it('leaves ordinary values untouched', () => {\n+\n+  it('calls toJSON and getters once without marker collisions', () => {\n+    let toJSONCalls = 0\n+    const changing = { toJSON() {\n+      toJSONCalls++\n+      return toJSONCalls === 1 ? { n: 1n } : { memo: '__xe_bigint_token_0__9' }\n+    } }\n+    let getterCalls = 0\n+    const withGetter = Object.defineProperty({}, 'memo', { enumerable: true, get() {\n+      getterCalls++\n+      return getterCalls === 1 ? 'first' : '__xe_bigint_token_0__9'\n+    } })\n+    expect(JSON.parse(stringifyWithBigInts(changing)!)).toEqual({ n: 1 })\n+    expect(JSON.parse(stringifyWithBigInts(withGetter)!)).toEqual({ memo: 'first' })\n+    expect(toJSONCalls).toBe(1)\n+    expect(getterCalls).toBe(1)\n+  })\n+\n+  it('preserves marker-like strings while encoding signed bigints', () => {\n+    const value = {\n+      memo: '__bigint__123', negative: '__bigint__-9',\n+      currentMarker: '__xe_bigint_token__123',\n+      escapedUnicode: '\\\\u005f_xe_bigint_token__123',\n+      key: { '__bigint__7': 'escaped' + String.fromCharCode(92, 34) + '__bigint__8', '__xe_bigint_token__123': 'key collision', '\\\\u005f__xe_bigint_token__123': 'escaped key' },\n+      nested: [1n, '__bigint__1', { amount: -9n, text: 'slash\\\\__bigint__6' }],\n+      mixed: [null, true, 2n],\n+    }\n+    const out = stringifyWithBigInts(value)\n+    expect(JSON.parse(out!)).toEqual({\n+      memo: '__bigint__123', negative: '__bigint__-9',\n+      currentMarker: '__xe_bigint_token__123',\n+      escapedUnicode: '\\\\u005f_xe_bigint_token__123',\n+      key: { '__bigint__7': 'escaped' + String.fromCharCode(92, 34) + '__bigint__8', '__xe_bigint_token__123': 'key collision', '\\\\u005f__xe_bigint_token__123': 'escaped key' },\n+      nested: [1, '__bigint__1', { amount: -9, text: 'slash\\\\__bigint__6' }],\n+      mixed: [null, true, 2],\n+    })\n+  })\n+\n+  it('matches JSON semantics for undefined, array holes, and boxed primitives', () => {\n+    const array: unknown[] = new Array(3)\n+    array[1] = undefined\n+    array[2] = () => {}\n+    expect(stringifyWithBigInts({ array, omitted: undefined, str: new String('boxed'), num: new Number(4) }))\n+      .toBe('{\"array\":[null,null,null],\"str\":\"boxed\",\"num\":4}')\n+    expect(stringifyWithBigInts(undefined as unknown)).toBeUndefined()\n+    expect(() => stringifyWithBigInts(Object(1n))).toThrow(TypeError)\n+  })\n+\n+  it('leaves ordinary values untouched', () => {\n       expect(stringifyWithBigInts({ a: 1, b: 'x', c: null })).toBe('{\"a\":1,\"b\":\"x\",\"c\":null}')\n     })\n   })\n\n```","created_at":"2026-10-23T15:05:02+00:00"},{"id":1577,"source":"github","source_ref":"6755094859","author":"XE desk","team":true,"body":"Read and accepted. It is tracked internally and the fix will land in a public PR; this issue is\nupdated when it does, and the tier and award follow the fix. The desk entry is https://bounty.xe.network/XE-0008.","created_at":"2026-11-10T00:15:50+00:00"}]}