Skip to content

Commit 03185cb

Browse files
authored
Fix Uint64BE encoding/decoding on browsers (#965)
Inspired by https://github.com/solana-labs/buffer-layout/blob/master/src/Layout.ts
1 parent 49fbd2f commit 03185cb

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

governance/xc_admin/packages/xc_admin_common/src/governance_payload/BufferLayoutExt.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,21 @@ export class UInt64BE extends Layout<bigint> {
55
super(span, property);
66
}
77

8+
// Note: we can not use read/writeBigUInt64BE because it is not supported in the browsers
89
override decode(b: Uint8Array, offset?: number): bigint {
910
let o = offset ?? 0;
10-
return Buffer.from(b.slice(o, o + this.span)).readBigUInt64BE();
11+
const buffer = Buffer.from(b.slice(o, o + this.span));
12+
const hi32 = buffer.readUInt32BE();
13+
const lo32 = buffer.readUInt32BE(4);
14+
return BigInt(lo32) + (BigInt(hi32) << BigInt(32));
1115
}
1216

1317
override encode(src: bigint, b: Uint8Array, offset?: number): number {
1418
const buffer = Buffer.alloc(this.span);
15-
buffer.writeBigUint64BE(src);
19+
const hi32 = Number(src >> BigInt(32));
20+
const lo32 = Number(src & BigInt(0xffffffff));
21+
buffer.writeUInt32BE(hi32, 0);
22+
buffer.writeUInt32BE(lo32, 4);
1623
b.set(buffer, offset);
1724
return this.span;
1825
}

0 commit comments

Comments
 (0)