Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions js/stateless.js/src/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,13 +289,22 @@ export function createRpc(
* @returns {string} - The preprocessed JSON string with numbers wrapped as strings
*/
export function wrapBigNumbersAsStrings(text: string): string {
return text.replace(/(":\s*)(-?\d+)(\s*[},])/g, (match, p1, p2, p3) => {
const num = Number(p2);
return text.replace(/-?\d+(?=\s*[,}\]])/g, (match, offset) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid rewriting numbers inside JSON strings

Because this regex scans the raw JSON text without tracking whether the match is inside a quoted string, it can now rewrite string contents when an unsafe-looking number is preceded by :, [, or , and followed by ], }, or , within that string. For example, a valid RPC string field like {"logs":["Program log: [9007199254740992]"]} becomes invalid JSON after wrapping, so JSON.parse(wrappedJsonString) will throw for responses containing such log/error/message text.

Useful? React with 👍 / 👎.

let prefixIndex = offset - 1;
while (prefixIndex >= 0 && /\s/.test(text[prefixIndex])) {
prefixIndex--;
}

if (prefixIndex < 0 || !':[,'.includes(text[prefixIndex])) {
return match;
}

const num = Number(match);
if (
!Number.isNaN(num) &&
(num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER)
) {
return `${p1}"${p2}"${p3}`;
return `"${match}"`;
}
return match;
});
Expand Down
9 changes: 9 additions & 0 deletions js/stateless.js/tests/e2e/safe-conversion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,15 @@ describe('safely convert json response', async () => {
});
});

it('wraps unsafe numbers inside arrays', () => {
const input = '{"values": [1, 9007199254740992, -9007199254740993]}';
const output = wrapBigNumbersAsStrings(input);

expect(output).to.equal(
'{"values": [1, "9007199254740992", "-9007199254740993"]}',
);
});

it('should convert unsafe integer responses safely', async () => {
const rawResponse = `{
"jsonrpc": "2.0",
Expand Down