@ckb-ccc/core 0.1.0-alpha.5 → 0.1.0-alpha.7

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/barrel.d.ts +1 -0
  3. package/dist/barrel.d.ts.map +1 -1
  4. package/dist/barrel.js +1 -0
  5. package/dist/ckb/transaction.d.ts.map +1 -1
  6. package/dist/ckb/transaction.js +9 -7
  7. package/dist/molecule/codec.d.ts +118 -0
  8. package/dist/molecule/codec.d.ts.map +1 -0
  9. package/dist/molecule/codec.js +446 -0
  10. package/dist/molecule/index.d.ts +3 -0
  11. package/dist/molecule/index.d.ts.map +1 -0
  12. package/dist/molecule/index.js +2 -0
  13. package/dist/molecule/predefined.d.ts +52 -0
  14. package/dist/molecule/predefined.d.ts.map +1 -0
  15. package/dist/molecule/predefined.js +95 -0
  16. package/dist.commonjs/barrel.d.ts +1 -0
  17. package/dist.commonjs/barrel.d.ts.map +1 -1
  18. package/dist.commonjs/barrel.js +14 -0
  19. package/dist.commonjs/ckb/transaction.d.ts.map +1 -1
  20. package/dist.commonjs/ckb/transaction.js +7 -5
  21. package/dist.commonjs/molecule/codec.d.ts +118 -0
  22. package/dist.commonjs/molecule/codec.d.ts.map +1 -0
  23. package/dist.commonjs/molecule/codec.js +461 -0
  24. package/dist.commonjs/molecule/index.d.ts +3 -0
  25. package/dist.commonjs/molecule/index.d.ts.map +1 -0
  26. package/dist.commonjs/molecule/index.js +18 -0
  27. package/dist.commonjs/molecule/predefined.d.ts +52 -0
  28. package/dist.commonjs/molecule/predefined.d.ts.map +1 -0
  29. package/dist.commonjs/molecule/predefined.js +121 -0
  30. package/package.json +1 -1
  31. package/src/barrel.ts +1 -0
  32. package/src/ckb/transaction.ts +9 -12
  33. package/src/molecule/codec.ts +610 -0
  34. package/src/molecule/index.ts +2 -0
  35. package/src/molecule/predefined.ts +114 -0
@@ -0,0 +1,610 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+
3
+ import { Bytes, bytesConcat, bytesFrom, BytesLike } from "../bytes/index.js";
4
+ import {
5
+ Num,
6
+ numBeFromBytes,
7
+ numBeToBytes,
8
+ numFromBytes,
9
+ NumLike,
10
+ numToBytes,
11
+ } from "../num/index.js";
12
+
13
+ export type CodecLike<Encodable, Decoded = Encodable> = {
14
+ readonly encode: (encodable: Encodable) => Bytes;
15
+ readonly decode: (decodable: BytesLike) => Decoded;
16
+ readonly byteLength?: number;
17
+ };
18
+ export class Codec<Encodable, Decoded = Encodable> {
19
+ constructor(
20
+ public readonly encode: (encodable: Encodable) => Bytes,
21
+ public readonly decode: (decodable: BytesLike) => Decoded,
22
+ public readonly byteLength?: number, // if provided, treat codec as fixed length
23
+ ) {}
24
+
25
+ static from<Encodable, Decoded = Encodable>({
26
+ encode,
27
+ decode,
28
+ byteLength,
29
+ }: CodecLike<Encodable, Decoded>): Codec<Encodable, Decoded> {
30
+ return new Codec(encode, decode, byteLength);
31
+ }
32
+
33
+ map<NewEncodable = Encodable, NewDecoded = Decoded>({
34
+ inMap,
35
+ outMap,
36
+ }: {
37
+ inMap?: (encodable: NewEncodable) => Encodable;
38
+ outMap?: (decoded: Decoded) => NewDecoded;
39
+ }): Codec<NewEncodable, NewDecoded> {
40
+ return Codec.from({
41
+ byteLength: this.byteLength,
42
+ encode: (encodable) =>
43
+ this.encode((inMap ? inMap(encodable) : encodable) as Encodable),
44
+ decode: (buffer) =>
45
+ (outMap
46
+ ? outMap(this.decode(buffer))
47
+ : this.decode(buffer)) as NewDecoded,
48
+ });
49
+ }
50
+ }
51
+
52
+ export type EncodableType<T extends CodecLike<any, any>> =
53
+ T extends CodecLike<infer Encodable, unknown> ? Encodable : never;
54
+ export type DecodedType<T extends CodecLike<any, any>> =
55
+ T extends CodecLike<any, infer Decoded> ? Decoded : never;
56
+
57
+ function uint32To(numLike: NumLike) {
58
+ return numToBytes(numLike, 4);
59
+ }
60
+
61
+ function uint32From(bytesLike: BytesLike) {
62
+ return Number(numFromBytes(bytesLike));
63
+ }
64
+
65
+ /**
66
+ * Vector with fixed size item codec
67
+ * @param itemCodec fixed-size vector item codec
68
+ */
69
+ export function fixedItemVec<Encodable, Decoded>(
70
+ itemCodec: CodecLike<Encodable, Decoded>,
71
+ ): Codec<Array<Encodable>, Array<Decoded>> {
72
+ const itemByteLength = itemCodec.byteLength;
73
+ if (itemByteLength === undefined) {
74
+ throw new Error("fixedItemVec: itemCodec requires a byte length");
75
+ }
76
+
77
+ return Codec.from({
78
+ encode(userDefinedItems) {
79
+ try {
80
+ return userDefinedItems.reduce(
81
+ (concatted, item) => bytesConcat(concatted, itemCodec.encode(item)),
82
+ uint32To(userDefinedItems.length),
83
+ );
84
+ } catch (e: unknown) {
85
+ throw new Error(`fixedItemVec(${e?.toString()})`);
86
+ }
87
+ },
88
+ decode(buffer) {
89
+ const value = bytesFrom(buffer);
90
+ if (value.byteLength < 4) {
91
+ throw new Error(
92
+ `fixedItemVec: too short buffer, expected at least 4 bytes, but got ${value.byteLength}`,
93
+ );
94
+ }
95
+ const itemCount = uint32From(value.slice(0, 4));
96
+ const byteLength = 4 + itemCount * itemByteLength;
97
+ if (value.byteLength !== byteLength) {
98
+ throw new Error(
99
+ `fixedItemVec: invalid buffer size, expected ${byteLength}, but got ${value.byteLength}`,
100
+ );
101
+ }
102
+
103
+ try {
104
+ const decodedArray: Array<Decoded> = [];
105
+ for (let offset = 0; offset < byteLength; offset += itemByteLength) {
106
+ decodedArray.push(
107
+ itemCodec.decode(value.slice(offset, offset + itemByteLength)),
108
+ );
109
+ }
110
+ return decodedArray;
111
+ } catch (e) {
112
+ throw new Error(`fixedItemVec(${e?.toString()})`);
113
+ }
114
+ },
115
+ });
116
+ }
117
+
118
+ /**
119
+ * Vector with dynamic size item codec, you can create a recursive vector with this function
120
+ * @param itemCodec the vector item codec. It can be fixed-size or dynamic-size.
121
+ */
122
+ export function dynItemVec<Encodable, Decoded>(
123
+ itemCodec: CodecLike<Encodable, Decoded>,
124
+ ): Codec<Array<Encodable>, Array<Decoded>> {
125
+ return Codec.from({
126
+ encode(userDefinedItems) {
127
+ try {
128
+ const encoded = userDefinedItems.reduce(
129
+ ({ offset, header, body }, item) => {
130
+ const encodedItem = itemCodec.encode(item);
131
+ const packedHeader = uint32To(offset);
132
+ return {
133
+ header: bytesConcat(header, packedHeader),
134
+ body: bytesConcat(body, encodedItem),
135
+ offset: offset + bytesFrom(encodedItem).byteLength,
136
+ };
137
+ },
138
+ {
139
+ header: bytesFrom([]),
140
+ body: bytesFrom([]),
141
+ offset: 4 + userDefinedItems.length * 4,
142
+ },
143
+ );
144
+ const packedTotalSize = uint32To(
145
+ encoded.header.byteLength + encoded.body.byteLength + 4,
146
+ );
147
+ return bytesConcat(packedTotalSize, encoded.header, encoded.body);
148
+ } catch (e) {
149
+ throw new Error(`dynItemVec(${e?.toString()})`);
150
+ }
151
+ },
152
+ decode(buffer) {
153
+ const value = bytesFrom(buffer);
154
+ const byteLength = uint32From(value.slice(0, 4));
155
+ if (byteLength !== value.byteLength) {
156
+ throw new Error(
157
+ `dynItemVec: invalid buffer size, expected ${byteLength}, but got ${value.byteLength}`,
158
+ );
159
+ }
160
+ if (value.byteLength < 4) {
161
+ throw new Error(
162
+ `fixedItemVec: too short buffer, expected at least 4 bytes, but got ${value.byteLength}`,
163
+ );
164
+ }
165
+
166
+ const offset = uint32From(value.slice(4, 8));
167
+ const itemCount = (offset - 4) / 4;
168
+ const offsets = Array.from(new Array(itemCount), (_, index) =>
169
+ uint32From(value.slice(4 + index * 4, 8 + index * 4)),
170
+ );
171
+ offsets.push(byteLength);
172
+ try {
173
+ const decodedArray: Array<Decoded> = [];
174
+ for (let index = 0; index < offsets.length - 1; index++) {
175
+ const start = offsets[index];
176
+ const end = offsets[index + 1];
177
+ const itemBuffer = value.slice(start, end);
178
+ decodedArray.push(itemCodec.decode(itemBuffer));
179
+ }
180
+ return decodedArray;
181
+ } catch (e) {
182
+ throw new Error(`dynItemVec(${e?.toString()})`);
183
+ }
184
+ },
185
+ });
186
+ }
187
+
188
+ /**
189
+ * General vector codec, if `itemCodec` is fixed size type, it will create a fixvec codec, otherwise a dynvec codec will be created.
190
+ * @param itemCodec
191
+ */
192
+ export function vector<Encodable, Decoded>(
193
+ itemCodec: CodecLike<Encodable, Decoded>,
194
+ ): Codec<Array<Encodable>, Array<Decoded>> {
195
+ if (itemCodec.byteLength !== undefined) {
196
+ return fixedItemVec(itemCodec);
197
+ }
198
+ return dynItemVec(itemCodec);
199
+ }
200
+
201
+ /**
202
+ * Option is a dynamic-size type.
203
+ * Serializing an option depends on whether it is empty or not:
204
+ * - if it's empty, there is zero bytes (the size is 0).
205
+ * - if it's not empty, just serialize the inner item (the size is same as the inner item's size).
206
+ * @param innerCodec
207
+ */
208
+ export function option<Encodable, Decoded>(
209
+ innerCodec: CodecLike<Encodable, Decoded>,
210
+ ): Codec<Encodable | undefined | null, Decoded | undefined> {
211
+ return Codec.from({
212
+ encode(userDefinedOrNull) {
213
+ if (!userDefinedOrNull) {
214
+ return bytesFrom([]);
215
+ }
216
+ try {
217
+ return innerCodec.encode(userDefinedOrNull);
218
+ } catch (e) {
219
+ throw new Error(`option(${e?.toString()})`);
220
+ }
221
+ },
222
+ decode(buffer) {
223
+ const value = bytesFrom(buffer);
224
+ if (value.byteLength === 0) {
225
+ return undefined;
226
+ }
227
+ try {
228
+ return innerCodec.decode(buffer);
229
+ } catch (e) {
230
+ throw new Error(`option(${e?.toString()})`);
231
+ }
232
+ },
233
+ });
234
+ }
235
+
236
+ /**
237
+ * Wrap the encoded value with a fixed-length buffer
238
+ * @param codec
239
+ */
240
+ export function byteVec<Encodable, Decoded>(
241
+ codec: CodecLike<Encodable, Decoded>,
242
+ ): Codec<Encodable, Decoded> {
243
+ return Codec.from({
244
+ encode(userDefined) {
245
+ try {
246
+ const payload = bytesFrom(codec.encode(userDefined));
247
+ const byteLength = uint32To(payload.byteLength);
248
+ return bytesConcat(byteLength, payload);
249
+ } catch (e) {
250
+ throw new Error(`byteVec(${e?.toString()})`);
251
+ }
252
+ },
253
+ decode(buffer) {
254
+ const value = bytesFrom(buffer);
255
+ if (value.byteLength < 4) {
256
+ throw new Error(
257
+ `byteVec: too short buffer, expected at least 4 bytes, but got ${value.byteLength}`,
258
+ );
259
+ }
260
+ const byteLength = uint32From(value.slice(0, 4));
261
+ if (byteLength !== value.byteLength - 4) {
262
+ throw new Error(
263
+ `byteVec: invalid buffer size, expected ${byteLength}, but got ${value.byteLength}`,
264
+ );
265
+ }
266
+ try {
267
+ return codec.decode(value.slice(4));
268
+ } catch (e: unknown) {
269
+ throw new Error(`byteVec(${e?.toString()})`);
270
+ }
271
+ },
272
+ });
273
+ }
274
+
275
+ export type EncodableRecordOptionalKeys<
276
+ T extends Record<string, CodecLike<any, any>>,
277
+ > = {
278
+ [K in keyof T]: Extract<EncodableType<T[K]>, undefined> extends never
279
+ ? never
280
+ : K;
281
+ }[keyof T];
282
+ export type EncodableRecord<T extends Record<string, CodecLike<any, any>>> = {
283
+ [key in keyof Pick<T, EncodableRecordOptionalKeys<T>>]+?: EncodableType<
284
+ T[key]
285
+ >;
286
+ } & {
287
+ [key in keyof Omit<T, EncodableRecordOptionalKeys<T>>]: EncodableType<T[key]>;
288
+ };
289
+
290
+ export type DecodedRecordOptionalKeys<
291
+ T extends Record<string, CodecLike<any, any>>,
292
+ > = {
293
+ [K in keyof T]: Extract<DecodedType<T[K]>, undefined> extends never
294
+ ? never
295
+ : K;
296
+ }[keyof T];
297
+ export type DecodedRecord<T extends Record<string, CodecLike<any, any>>> = {
298
+ [key in keyof Pick<T, DecodedRecordOptionalKeys<T>>]+?: DecodedType<T[key]>;
299
+ } & {
300
+ [key in keyof Omit<T, DecodedRecordOptionalKeys<T>>]: DecodedType<T[key]>;
301
+ };
302
+
303
+ /**
304
+ * Table is a dynamic-size type. It can be considered as a dynvec but the length is fixed.
305
+ * @param codecLayout
306
+ */
307
+ export function table<
308
+ T extends Record<string, CodecLike<any, any>>,
309
+ Encodable extends EncodableRecord<T>,
310
+ Decoded extends DecodedRecord<T>,
311
+ >(codecLayout: T): Codec<Encodable, Decoded> {
312
+ const keys = Object.keys(codecLayout);
313
+
314
+ return Codec.from({
315
+ encode(object) {
316
+ const headerLength = 4 + keys.length * 4;
317
+
318
+ const { header, body } = keys.reduce(
319
+ (result, key) => {
320
+ try {
321
+ const encodedItem = codecLayout[key].encode((object as any)[key]);
322
+ const packedOffset = uint32To(result.offset);
323
+ return {
324
+ header: bytesConcat(result.header, packedOffset),
325
+ body: bytesConcat(result.body, encodedItem),
326
+ offset: result.offset + bytesFrom(encodedItem).byteLength,
327
+ };
328
+ } catch (e: unknown) {
329
+ throw new Error(`table.${key}(${e?.toString()})`);
330
+ }
331
+ },
332
+ {
333
+ header: bytesFrom([]),
334
+ body: bytesFrom([]),
335
+ offset: headerLength,
336
+ },
337
+ );
338
+ const packedTotalSize = uint32To(header.byteLength + body.byteLength + 4);
339
+ return bytesConcat(packedTotalSize, header, body);
340
+ },
341
+ decode(buffer) {
342
+ const value = bytesFrom(buffer);
343
+ const byteLength = uint32From(value.slice(0, 4));
344
+ if (byteLength !== value.byteLength) {
345
+ throw new Error(
346
+ `table: invalid buffer size, expected ${byteLength}, but got ${value.byteLength}`,
347
+ );
348
+ }
349
+ if (byteLength <= 4) {
350
+ throw new Error("table: empty buffer");
351
+ }
352
+ const offsets = keys.map((_, index) =>
353
+ uint32From(value.slice(4 + index * 4, 8 + index * 4)),
354
+ );
355
+ offsets.push(byteLength);
356
+ const object = {};
357
+ for (let i = 0; i < offsets.length - 1; i++) {
358
+ const start = offsets[i];
359
+ const end = offsets[i + 1];
360
+ const field = keys[i];
361
+ const codec = codecLayout[field];
362
+ const payload = value.slice(start, end);
363
+ try {
364
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
365
+ Object.assign(object, { [field]: codec.decode(payload) });
366
+ } catch (e: unknown) {
367
+ throw new Error(`table.${field}(${e?.toString()})`);
368
+ }
369
+ }
370
+ return object as Decoded;
371
+ },
372
+ });
373
+ }
374
+
375
+ type UnionEncodable<
376
+ T extends Record<string, CodecLike<any, any>>,
377
+ K extends keyof T = keyof T,
378
+ > = K extends unknown
379
+ ? {
380
+ type: K;
381
+ value: EncodableType<T[K]>;
382
+ }
383
+ : never;
384
+ type UnionDecoded<
385
+ T extends Record<string, CodecLike<any, any>>,
386
+ K extends keyof T = keyof T,
387
+ > = K extends unknown
388
+ ? {
389
+ type: K;
390
+ value: DecodedType<T[K]>;
391
+ }
392
+ : never;
393
+
394
+ /**
395
+ * Union is a dynamic-size type.
396
+ * Serializing a union has two steps:
397
+ * - Serialize an item type id in bytes as a 32 bit unsigned integer in little-endian. The item type id is the index of the inner items, and it's starting at 0.
398
+ * - Serialize the inner item.
399
+ * @param codecLayout the union item record
400
+ * @param fields the custom item type id record
401
+ * @example
402
+ * // without custom id
403
+ * union({ cafe: Uint8, bee: Uint8 })
404
+ * // with custom id
405
+ * union({ cafe: Uint8, bee: Uint8 }, { cafe: 0xcafe, bee: 0xbee })
406
+ */
407
+ export function union<T extends Record<string, CodecLike<any, any>>>(
408
+ codecLayout: T,
409
+ fields?: Record<keyof T, number | undefined | null>,
410
+ ): Codec<UnionEncodable<T>, UnionDecoded<T>> {
411
+ const keys = Object.keys(codecLayout);
412
+
413
+ return Codec.from({
414
+ encode({ type, value }) {
415
+ const typeStr = type.toString();
416
+ const codec = codecLayout[typeStr];
417
+ if (!codec) {
418
+ throw new Error(
419
+ `union: invalid type, expected ${keys.toString()}, but got ${typeStr}`,
420
+ );
421
+ }
422
+ const fieldId = fields ? (fields[typeStr] ?? -1) : keys.indexOf(typeStr);
423
+ if (fieldId < 0) {
424
+ throw new Error(`union: invalid field id ${fieldId} of ${typeStr}`);
425
+ }
426
+ const header = uint32To(fieldId);
427
+ try {
428
+ const body = codec.encode(value);
429
+ return bytesConcat(header, body);
430
+ } catch (e: unknown) {
431
+ throw new Error(`union.(${typeStr})(${e?.toString()})`);
432
+ }
433
+ },
434
+ decode(buffer) {
435
+ const value = bytesFrom(buffer);
436
+ const fieldIndex = uint32From(value.slice(0, 4));
437
+ const keys = Object.keys(codecLayout);
438
+
439
+ const field = (() => {
440
+ if (!fields) {
441
+ return keys[fieldIndex];
442
+ }
443
+ const entry = Object.entries(fields).find(
444
+ ([, id]) => id === fieldIndex,
445
+ );
446
+ return entry?.[0];
447
+ })();
448
+
449
+ if (!field) {
450
+ if (!fields) {
451
+ throw new Error(
452
+ `union: unknown union field index ${fieldIndex}, only ${keys.toString()} are allowed`,
453
+ );
454
+ }
455
+ const fieldKeys = Object.keys(fields);
456
+ throw new Error(
457
+ `union: unknown union field index ${fieldIndex}, only ${fieldKeys.toString()} and ${keys.toString()} are allowed`,
458
+ );
459
+ }
460
+
461
+ return {
462
+ type: field,
463
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
464
+ value: codecLayout[field].decode(value.slice(4)),
465
+ } as UnionDecoded<T>;
466
+ },
467
+ });
468
+ }
469
+
470
+ /**
471
+ * Struct is a fixed-size type: all fields in struct are fixed-size and it has a fixed quantity of fields.
472
+ * The size of a struct is the sum of all fields' size.
473
+ * @param codecLayout a object contains all fields' codec
474
+ */
475
+ export function struct<
476
+ T extends Record<string, CodecLike<any, any>>,
477
+ Encodable extends EncodableRecord<T>,
478
+ Decoded extends DecodedRecord<T>,
479
+ >(codecLayout: T): Codec<Encodable, Decoded> {
480
+ const codecArray = Object.values(codecLayout);
481
+ if (codecArray.some((codec) => codec.byteLength === undefined)) {
482
+ throw new Error("struct: all fields must be fixed-size");
483
+ }
484
+
485
+ const keys = Object.keys(codecLayout);
486
+
487
+ return Codec.from({
488
+ byteLength: codecArray.reduce((sum, codec) => sum + codec.byteLength!, 0),
489
+ encode(object) {
490
+ return keys.reduce((result, key) => {
491
+ try {
492
+ const encodedItem = codecLayout[key].encode((object as any)[key]);
493
+ return bytesConcat(result, encodedItem);
494
+ } catch (e: unknown) {
495
+ throw new Error(`struct.${key}(${e?.toString()})`);
496
+ }
497
+ }, bytesFrom([]));
498
+ },
499
+ decode(buffer) {
500
+ const value = bytesFrom(buffer);
501
+ const object = {};
502
+ let offset = 0;
503
+ Object.entries(codecLayout).forEach(([key, codec]) => {
504
+ const payload = value.slice(offset, offset + codec.byteLength!);
505
+ try {
506
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
507
+ Object.assign(object, { [key]: codec.decode(payload) });
508
+ } catch (e: unknown) {
509
+ throw new Error(`struct.${key}(${(e as Error).toString()})`);
510
+ }
511
+ offset = offset + codec.byteLength!;
512
+ });
513
+ return object as Decoded;
514
+ },
515
+ });
516
+ }
517
+
518
+ /**
519
+ * The array is a fixed-size type: it has a fixed-size inner type and a fixed length.
520
+ * The size of an array is the size of inner type times the length.
521
+ * @param itemCodec the fixed-size array item codec
522
+ * @param itemCount
523
+ */
524
+ export function array<Encodable, Decoded>(
525
+ itemCodec: CodecLike<Encodable, Decoded>,
526
+ itemCount: number,
527
+ ): Codec<Array<Encodable>, Array<Decoded>> {
528
+ if (itemCodec.byteLength === undefined) {
529
+ throw new Error("array: itemCodec requires a byte length");
530
+ }
531
+ const byteLength = itemCodec.byteLength * itemCount;
532
+
533
+ return Codec.from({
534
+ byteLength,
535
+ encode(items) {
536
+ try {
537
+ return items.reduce(
538
+ (concatted, item) => bytesConcat(concatted, itemCodec.encode(item)),
539
+ bytesFrom([]),
540
+ );
541
+ } catch (e: unknown) {
542
+ throw new Error(`array(${e?.toString()})`);
543
+ }
544
+ },
545
+ decode(buffer) {
546
+ const value = bytesFrom(buffer);
547
+ if (value.byteLength != byteLength) {
548
+ throw new Error(
549
+ `array: invalid buffer size, expected ${byteLength}, but got ${value.byteLength}`,
550
+ );
551
+ }
552
+ try {
553
+ const result: Array<Decoded> = [];
554
+ for (let i = 0; i < value.byteLength; i += itemCodec.byteLength!) {
555
+ result.push(
556
+ itemCodec.decode(value.slice(i, i + itemCodec.byteLength!)),
557
+ );
558
+ }
559
+ return result;
560
+ } catch (e: unknown) {
561
+ throw new Error(`array(${e?.toString()})`);
562
+ }
563
+ },
564
+ });
565
+ }
566
+
567
+ /**
568
+ * Create a codec to deal with fixed LE or BE bytes.
569
+ * @param byteLength
570
+ * @param littleEndian
571
+ */
572
+ export function uint(
573
+ byteLength: number,
574
+ littleEndian = false,
575
+ ): Codec<NumLike, Num> {
576
+ return Codec.from({
577
+ byteLength,
578
+ encode: (numLike) => {
579
+ if (littleEndian) {
580
+ return numToBytes(numLike, byteLength);
581
+ } else {
582
+ return numBeToBytes(numLike, byteLength);
583
+ }
584
+ },
585
+ decode: (buffer) => {
586
+ if (littleEndian) {
587
+ return numFromBytes(buffer);
588
+ } else {
589
+ return numBeFromBytes(buffer);
590
+ }
591
+ },
592
+ });
593
+ }
594
+
595
+ /**
596
+ * Create a codec to deal with fixed LE or BE bytes.
597
+ * @param byteLength
598
+ * @param littleEndian
599
+ */
600
+ export function uintNumber(
601
+ byteLength: number,
602
+ littleEndian = false,
603
+ ): Codec<NumLike, number> {
604
+ if (byteLength > 4) {
605
+ throw new Error("uintNumber: byteLength must be less than or equal to 4");
606
+ }
607
+ return uint(byteLength, littleEndian).map({
608
+ outMap: (num) => Number(num),
609
+ });
610
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./codec.js";
2
+ export * from "./predefined.js";