harb/kraiken-lib/src/subgraph.ts
openhands 6eacfe1975 fix: \uint256ToBytesLittleEndian\ silently truncates above 2³²−1 (#294)
Expand the output buffer from 4 bytes to 32 bytes and iterate all 32
positions, so values ≥ 2³² are encoded correctly instead of silently
dropped. Update tests to assert 32-byte output and add coverage for
2³², 2¹²⁸, and max uint256 roundtrips.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-27 06:42:59 +00:00

17 lines
440 B
TypeScript

export function bytesToUint256LittleEndian(bytes: Uint8Array): bigint {
let value: bigint = 0n;
for (let i = bytes.length - 1; i >= 0; i--) {
value = (value << 8n) | BigInt(bytes[i]);
}
return value;
}
export function uint256ToBytesLittleEndian(value: bigint): Uint8Array {
const bytes = new Uint8Array(32);
for (let i = 0; i < 32; i++) {
bytes[i] = Number((value >> (8n * BigInt(i))) & 0xffn);
}
return bytes;
}