@layerzerolabs/common-encoding-utils 0.2.63 → 0.2.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Growable byte codec backed by `ArrayBuffer` + `DataView`.
3
+ *
4
+ * Low-level building block for constructing byte payloads deterministically.
5
+ * Higher-level concerns (e.g. hashing, ABI encoding, function signatures) should
6
+ * live in wrappers/subclasses.
7
+ */
8
+
9
+ function uMax(bits: number): bigint {
10
+ if (!Number.isInteger(bits) || bits < 0) {
11
+ throw new RangeError(`ByteCodec: invalid bit width: ${bits}`);
12
+ }
13
+ // (2^bits) - 1, as bigint
14
+ return bits === 0 ? 0n : (1n << BigInt(bits)) - 1n;
15
+ }
16
+
17
+ // TODO: add tests for this class — currently has zero test coverage
18
+ export class ByteCodec {
19
+ // Start with a small-ish initial capacity to avoid frequent reallocations for
20
+ // common short payloads (e.g. function selector + a few fixed-width fields),
21
+ // while still staying tiny in memory terms. Buffer grows by doubling as needed.
22
+ #buf = new ArrayBuffer(128);
23
+ #view = new DataView(this.#buf);
24
+ #cursor = 0;
25
+
26
+ static readonly #ZERO = 0n;
27
+ static readonly #U8_MAX = uMax(8);
28
+ static readonly #U16_MAX = uMax(16);
29
+ static readonly #U32_MAX = uMax(32);
30
+ static readonly #U64_MAX = uMax(64);
31
+ static readonly #U128_MAX = uMax(128);
32
+ static readonly #U256_MAX = uMax(256);
33
+
34
+ static #outOfRange(targetLength: number, value: bigint): RangeError {
35
+ return new RangeError(`ByteCodec: value out of range for u${targetLength * 8}: ${value}`);
36
+ }
37
+
38
+ /**
39
+ * Read helpers (big-endian). These are intentionally small/low-level so other
40
+ * packages can share a single implementation for parsing encoded payloads.
41
+ */
42
+ static readU16be(buf: Uint8Array, offset: number): number {
43
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
44
+ return view.getUint16(offset, false);
45
+ }
46
+
47
+ static readU8(buf: Uint8Array, offset: number): number {
48
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
49
+ return view.getUint8(offset);
50
+ }
51
+
52
+ static readU32be(buf: Uint8Array, offset: number): number {
53
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
54
+ return view.getUint32(offset, false);
55
+ }
56
+
57
+ static readU128be(buf: Uint8Array, offset: number): bigint {
58
+ return ByteCodec.readUNbe(buf, offset, 16);
59
+ }
60
+
61
+ static readUNbe(buf: Uint8Array, offset: number, length: number): bigint {
62
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
63
+
64
+ let out = 0n;
65
+ const end = offset + length;
66
+
67
+ // Fast path: read 8 bytes at a time
68
+ let cursor = offset;
69
+ while (cursor + 8 <= end) {
70
+ out = (out << 64n) | view.getBigUint64(cursor, false);
71
+ cursor += 8;
72
+ }
73
+
74
+ // Tail: 0..7 bytes
75
+ while (cursor < end) {
76
+ out = (out << 8n) | BigInt(view.getUint8(cursor));
77
+ cursor += 1;
78
+ }
79
+
80
+ return out;
81
+ }
82
+
83
+ static readBytes32(buf: Uint8Array, offset: number): Uint8Array {
84
+ if (offset + 32 > buf.length) throw new RangeError(`ByteCodec: out of bounds at ${offset}`);
85
+ return buf.slice(offset, offset + 32);
86
+ }
87
+
88
+ /**
89
+ * Left-pad `bytes` to `targetLength` using `padByte` (default 0x00).
90
+ *
91
+ * Commonly used to mimic Solidity's `bytes32(bytesN)`-style left zero padding.
92
+ */
93
+ static leftPad(bytes: Uint8Array, targetLength: number, padByte = 0): Uint8Array {
94
+ if (!Number.isInteger(targetLength) || targetLength < 0) {
95
+ throw new RangeError(`ByteCodec: invalid length: target=${targetLength}`);
96
+ }
97
+ if (!Number.isInteger(padByte) || padByte < 0 || padByte > 255) {
98
+ throw new RangeError(`ByteCodec: invalid pad byte: ${padByte}`);
99
+ }
100
+ if (bytes.length > targetLength) {
101
+ throw new RangeError(
102
+ `ByteCodec: bytes length ${bytes.length} exceeds target ${targetLength}`,
103
+ );
104
+ }
105
+
106
+ const out = new Uint8Array(targetLength);
107
+ if (padByte !== 0) out.fill(padByte);
108
+ out.set(bytes, targetLength - bytes.length);
109
+ return out;
110
+ }
111
+
112
+ /**
113
+ * Cast an unsigned big-endian integer in `bytes` into a fixed-width uint (by bytes),
114
+ * reverting on overflow.
115
+ *
116
+ * This mirrors Solidity-style safe casts like `SafeCast.toUint128(uint256)`:
117
+ * - if `bytes.length > targetLength`, the high (bytes.length - targetLength) bytes must be all zero
118
+ * - returns the low `targetLength` bytes as the result
119
+ *
120
+ * Examples:
121
+ * - cast bytes32 -> u128: castUNbe(bytes32, 16)
122
+ * - cast bytesN -> u64: castUNbe(bytesN, 8)
123
+ */
124
+ static castUNbe(bytes: Uint8Array, targetLength: number): bigint {
125
+ if (!Number.isInteger(targetLength) || targetLength < 0) {
126
+ throw new RangeError(`ByteCodec: invalid length: target=${targetLength}`);
127
+ }
128
+
129
+ const len = bytes.length;
130
+ if (len <= targetLength) return ByteCodec.readUNbe(bytes, 0, len);
131
+
132
+ // Overflow check: any excess high bytes must be 0x00.
133
+ const excess = len - targetLength;
134
+ for (let i = 0; i < excess; i++) {
135
+ if (bytes[i] !== 0)
136
+ throw ByteCodec.#outOfRange(targetLength, ByteCodec.readUNbe(bytes, 0, len));
137
+ }
138
+
139
+ return ByteCodec.readUNbe(bytes, excess, targetLength);
140
+ }
141
+
142
+ static castU8be(bytes: Uint8Array): bigint {
143
+ return ByteCodec.castUNbe(bytes, 1);
144
+ }
145
+
146
+ static castU16be(bytes: Uint8Array): bigint {
147
+ return ByteCodec.castUNbe(bytes, 2);
148
+ }
149
+
150
+ static castU32be(bytes: Uint8Array): bigint {
151
+ return ByteCodec.castUNbe(bytes, 4);
152
+ }
153
+
154
+ static castU64be(bytes: Uint8Array): bigint {
155
+ return ByteCodec.castUNbe(bytes, 8);
156
+ }
157
+
158
+ static castU128be(bytes: Uint8Array): bigint {
159
+ return ByteCodec.castUNbe(bytes, 16);
160
+ }
161
+
162
+ protected ensureCapacity(additionalBytes: number): void {
163
+ const needed = this.#cursor + additionalBytes;
164
+ if (needed <= this.#buf.byteLength) return;
165
+
166
+ let nextCap = this.#buf.byteLength;
167
+ while (nextCap < needed) nextCap *= 2;
168
+
169
+ // Grow by allocating a new ArrayBuffer and copying the written prefix
170
+ // [0..cursor) into it. We then swap the backing buffer+view.
171
+ const next = new ArrayBuffer(nextCap);
172
+ new Uint8Array(next).set(new Uint8Array(this.#buf, 0, this.#cursor));
173
+ this.#buf = next;
174
+ this.#view = new DataView(this.#buf);
175
+ }
176
+
177
+ bytes(b: Uint8Array): this {
178
+ this.ensureCapacity(b.length);
179
+ new Uint8Array(this.#buf, this.#cursor, b.length).set(b);
180
+ this.#cursor += b.length;
181
+ return this;
182
+ }
183
+
184
+ bytes32(b: Uint8Array): this {
185
+ return this.bytes(ByteCodec.leftPad(b, 32));
186
+ }
187
+
188
+ bool(b: boolean): this {
189
+ return this.u8(b ? 1n : ByteCodec.#ZERO);
190
+ }
191
+
192
+ u8(v: bigint): this {
193
+ if (v < ByteCodec.#ZERO || v > ByteCodec.#U8_MAX)
194
+ throw new RangeError(`ByteCodec: value out of range for u8: ${v}`);
195
+ this.ensureCapacity(1);
196
+ this.#view.setUint8(this.#cursor, Number(v));
197
+ this.#cursor += 1;
198
+ return this;
199
+ }
200
+
201
+ u16be(v: bigint): this {
202
+ if (v < ByteCodec.#ZERO || v > ByteCodec.#U16_MAX)
203
+ throw new RangeError(`ByteCodec: value out of range for u16: ${v}`);
204
+ this.ensureCapacity(2);
205
+ this.#view.setUint16(this.#cursor, Number(v), false);
206
+ this.#cursor += 2;
207
+ return this;
208
+ }
209
+
210
+ u32be(v: bigint): this {
211
+ if (v < ByteCodec.#ZERO || v > ByteCodec.#U32_MAX) {
212
+ throw new RangeError(`ByteCodec: value out of range for u32: ${v}`);
213
+ }
214
+ this.ensureCapacity(4);
215
+ this.#view.setUint32(this.#cursor, Number(v), false);
216
+ this.#cursor += 4;
217
+ return this;
218
+ }
219
+
220
+ u64be(v: bigint): this {
221
+ if (v < ByteCodec.#ZERO || v > ByteCodec.#U64_MAX) {
222
+ throw new RangeError(`ByteCodec: value out of range for u64: ${v}`);
223
+ }
224
+ this.ensureCapacity(8);
225
+ this.#view.setBigUint64(this.#cursor, v, false);
226
+ this.#cursor += 8;
227
+ return this;
228
+ }
229
+
230
+ u128be(v: bigint): this {
231
+ if (v < ByteCodec.#ZERO || v > ByteCodec.#U128_MAX) {
232
+ throw new RangeError(`ByteCodec: value out of range for u128: ${v}`);
233
+ }
234
+ this.ensureCapacity(16);
235
+ const hi = (v >> 64n) & ByteCodec.#U64_MAX;
236
+ const lo = v & ByteCodec.#U64_MAX;
237
+ this.#view.setBigUint64(this.#cursor, hi, false);
238
+ this.#view.setBigUint64(this.#cursor + 8, lo, false);
239
+ this.#cursor += 16;
240
+ return this;
241
+ }
242
+
243
+ u256be(v: bigint): this {
244
+ if (v < ByteCodec.#ZERO || v > ByteCodec.#U256_MAX) {
245
+ throw new RangeError(`ByteCodec: value out of range for u256: ${v}`);
246
+ }
247
+ this.ensureCapacity(32);
248
+ const w0 = (v >> 192n) & ByteCodec.#U64_MAX;
249
+ const w1 = (v >> 128n) & ByteCodec.#U64_MAX;
250
+ const w2 = (v >> 64n) & ByteCodec.#U64_MAX;
251
+ const w3 = v & ByteCodec.#U64_MAX;
252
+ this.#view.setBigUint64(this.#cursor, w0, false);
253
+ this.#view.setBigUint64(this.#cursor + 8, w1, false);
254
+ this.#view.setBigUint64(this.#cursor + 16, w2, false);
255
+ this.#view.setBigUint64(this.#cursor + 24, w3, false);
256
+ this.#cursor += 32;
257
+ return this;
258
+ }
259
+ /**
260
+ * Returns a copy of the accumulated bytes (no shared backing buffer).
261
+ */
262
+ toBytes(): Uint8Array {
263
+ return new Uint8Array(this.#buf, 0, this.#cursor).slice();
264
+ }
265
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export * from './byte-codec';
2
+
1
3
  export type HexString = `0x${string}`;
2
4
 
3
5
  const base58regex = /^[A-HJ-NP-Za-km-z1-9]*$/;
@@ -94,7 +96,9 @@ export function hexToBytes(hex: string): Uint8Array {
94
96
  }
95
97
 
96
98
  export function bytesToHex(bytes: Uint8Array | ArrayBuffer): string {
97
- return Buffer.from(bytes).toString('hex');
99
+ return Buffer.from(bytes instanceof ArrayBuffer ? new Uint8Array(bytes) : bytes).toString(
100
+ 'hex',
101
+ );
98
102
  }
99
103
 
100
104
  /**
@@ -106,7 +110,13 @@ export function bytesToHexPrefixed(bytes: Uint8Array | ArrayBuffer): HexString {
106
110
  }
107
111
 
108
112
  export function bytesToBase64(bytes: Uint8Array | ArrayBuffer): string {
109
- return Buffer.from(bytes).toString('base64');
113
+ return Buffer.from(bytes instanceof ArrayBuffer ? new Uint8Array(bytes) : bytes).toString(
114
+ 'base64',
115
+ );
116
+ }
117
+
118
+ export function base64ToBytes(base64: string): Uint8Array {
119
+ return Uint8Array.from(Buffer.from(base64, 'base64'));
110
120
  }
111
121
 
112
122
  export function hexToBase64(hexString: string): string {