@fleet-sdk/serializer 0.4.0 → 0.5.0

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.
package/dist/index.mjs CHANGED
@@ -1,62 +1,51 @@
1
- import { ensureBigInt, _0n, _128n, isEmpty, assert, first, last, isDefined, some, isUndefined, byteSizeOf, _1n, _7n, _127n, _63n } from '@fleet-sdk/common';
2
- import { hex } from '@fleet-sdk/crypto';
1
+ import { ensureBigInt, _0n, _128n, isEmpty, assert, first, last, isUndefined, isDefined, some, byteSizeOf, _7n, _1n, _63n, _127n } from '@fleet-sdk/common';
2
+ import { ensureBytes, hex, blake2b256 } from '@fleet-sdk/crypto';
3
3
 
4
- // src/coders/sigmaReader.ts
4
+ // src/coders/sigmaByteReader.ts
5
5
  function hexToBigInt(hex6) {
6
- if (hex6.length % 2) {
7
- hex6 = "0" + hex6;
8
- }
9
- const value = BigInt("0x" + hex6);
10
- const highByte = parseInt(hex6.slice(0, 2), 16);
11
- if (128 & highByte) {
12
- return -_bitNegate(value);
13
- }
6
+ const value = BigInt(hex6.length % 2 ? `0x0${hex6}` : `0x${hex6}`);
7
+ const highByte = Number.parseInt(hex6.slice(0, 2), 16);
8
+ if (128 & highByte) return -negateAndMask(value);
14
9
  return value;
15
10
  }
16
11
  function bigIntToHex(value) {
17
12
  const positive = value >= _0n;
18
- if (!positive) {
19
- value = _bitNegate(value);
20
- }
21
- let hex6 = value.toString(16);
22
- if (hex6.length % 2) {
23
- hex6 = "0" + hex6;
24
- }
25
- if (positive && 128 & parseInt(hex6.slice(0, 2), 16)) {
26
- hex6 = "00" + hex6;
13
+ let hex6 = (positive ? value : negateAndMask(value)).toString(16);
14
+ if (hex6.length % 2) hex6 = `0${hex6}`;
15
+ if (positive && 128 & Number.parseInt(hex6.slice(0, 2), 16)) {
16
+ return `00${hex6}`;
27
17
  }
28
18
  return hex6;
29
19
  }
30
- function _bitNegate(value) {
31
- const negative = value < _0n;
32
- if (negative) {
33
- value = -value;
34
- }
35
- const bits = value.toString(2);
36
- let bitLen = bits.length;
37
- const mod = bitLen % 8;
20
+ function negateAndMask(value) {
21
+ let val = value;
22
+ const negative = val < _0n;
23
+ if (negative) val = -val;
24
+ const bits = val.toString(2);
25
+ let len = bits.length;
26
+ const mod = len % 8;
38
27
  if (mod > 0) {
39
- bitLen += 8 - mod;
28
+ len += 8 - mod;
40
29
  } else if (negative && first(bits) === "1" && bits.indexOf("1", 1) !== -1) {
41
- bitLen += 8;
30
+ len += 8;
42
31
  }
43
- const mask = (1n << BigInt(bitLen)) - 1n;
44
- return (~value & mask) + 1n;
32
+ const mask = (1n << BigInt(len)) - 1n;
33
+ return (~val & mask) + 1n;
45
34
  }
46
35
  function writeVLQ(writer, value) {
47
- if (value === 0) {
48
- return writer.write(0);
49
- } else if (value < 0) {
50
- throw new RangeError("Variable Length Quantity not supported for negative numbers.");
36
+ if (value === 0) return writer.write(0);
37
+ if (value < 0) {
38
+ throw new RangeError(
39
+ "Variable Length Quantity not supported for negative numbers."
40
+ );
51
41
  }
42
+ let val = value;
52
43
  do {
53
- let lower7bits = value & 127;
54
- value >>= 7;
55
- if (value > 0) {
56
- lower7bits |= 128;
57
- }
44
+ let lower7bits = val & 127;
45
+ val >>= 7;
46
+ if (val > 0) lower7bits |= 128;
58
47
  writer.write(lower7bits);
59
- } while (value > 0);
48
+ } while (val > 0);
60
49
  return writer;
61
50
  }
62
51
  function readVLQ(reader) {
@@ -70,29 +59,27 @@ function readVLQ(reader) {
70
59
  lower7bits = reader.readByte();
71
60
  value |= (lower7bits & 127) << shift;
72
61
  shift += 7;
73
- } while ((lower7bits & 128) != 0);
62
+ } while ((lower7bits & 128) !== 0);
74
63
  return value;
75
64
  }
76
65
  function writeBigVLQ(writer, value) {
77
- if (value === _0n) {
78
- return writer.write(0);
79
- } else if (value < _0n) {
80
- throw new RangeError("Variable Length Quantity not supported for negative numbers");
66
+ if (value === _0n) return writer.write(0);
67
+ if (value < _0n) {
68
+ throw new RangeError(
69
+ "Variable Length Quantity not supported for negative numbers"
70
+ );
81
71
  }
72
+ let val = value;
82
73
  do {
83
- let lower7bits = Number(value & _127n);
84
- value >>= _7n;
85
- if (value > 0) {
86
- lower7bits |= 128;
87
- }
74
+ let lower7bits = Number(val & _127n);
75
+ val >>= _7n;
76
+ if (val > 0) lower7bits |= 128;
88
77
  writer.write(lower7bits);
89
- } while (value > 0);
78
+ } while (val > 0);
90
79
  return writer;
91
80
  }
92
81
  function readBigVLQ(reader) {
93
- if (reader.isEmpty) {
94
- return _0n;
95
- }
82
+ if (reader.isEmpty) return _0n;
96
83
  let value = _0n;
97
84
  let shift = _0n;
98
85
  let lower7bits = _0n;
@@ -100,23 +87,24 @@ function readBigVLQ(reader) {
100
87
  lower7bits = BigInt(reader.readByte());
101
88
  value |= (lower7bits & _127n) << shift;
102
89
  shift += _7n;
103
- } while ((lower7bits & _128n) != _0n);
90
+ } while ((lower7bits & _128n) !== _0n);
104
91
  return value;
105
92
  }
106
93
  function estimateVLQSize(value) {
107
94
  let size = 0;
108
- if (typeof value === "number") {
95
+ let val = value;
96
+ if (typeof val === "number") {
109
97
  do {
110
98
  size++;
111
- value = Math.floor(value / 128);
112
- } while (value > 0);
99
+ val = Math.floor(val / 128);
100
+ } while (val > 0);
113
101
  return size;
114
102
  }
115
- value = ensureBigInt(value);
103
+ val = ensureBigInt(val);
116
104
  do {
117
105
  size++;
118
- value /= _128n;
119
- } while (value > _0n);
106
+ val /= _128n;
107
+ } while (val > _0n);
120
108
  return size;
121
109
  }
122
110
  function zigZagEncode(input) {
@@ -132,19 +120,15 @@ function zigZagDecodeBigInt(input) {
132
120
  return input >> _1n ^ -(input & _1n);
133
121
  }
134
122
 
135
- // src/coders/sigmaReader.ts
136
- var SigmaReader = class {
123
+ // src/coders/sigmaByteReader.ts
124
+ var SigmaByteReader = class {
137
125
  #bytes;
138
126
  #cursor;
139
127
  get isEmpty() {
140
128
  return isEmpty(this.#bytes);
141
129
  }
142
130
  constructor(bytes) {
143
- if (typeof bytes === "string") {
144
- this.#bytes = hex.decode(bytes);
145
- } else {
146
- this.#bytes = bytes;
147
- }
131
+ this.#bytes = ensureBytes(bytes);
148
132
  this.#cursor = 0;
149
133
  }
150
134
  readBoolean() {
@@ -156,14 +140,12 @@ var SigmaReader = class {
156
140
  for (let i = 0; i < length; i++) {
157
141
  const bit = this.#bytes[this.#cursor] >> bitOffset++ & 1;
158
142
  bits[i] = bit === 1;
159
- if (bitOffset == 8) {
143
+ if (bitOffset === 8) {
160
144
  bitOffset = 0;
161
145
  this.#cursor++;
162
146
  }
163
147
  }
164
- if (bitOffset > 0) {
165
- this.#cursor++;
166
- }
148
+ if (bitOffset > 0) this.#cursor++;
167
149
  return bits;
168
150
  }
169
151
  readByte() {
@@ -179,8 +161,7 @@ var SigmaReader = class {
179
161
  return Number(zigZagDecode(readVLQ(this)));
180
162
  }
181
163
  readInt() {
182
- const int = this.readLong();
183
- return Number(int);
164
+ return Number(this.readLong());
184
165
  }
185
166
  readLong() {
186
167
  return zigZagDecodeBigInt(readBigVLQ(this));
@@ -190,14 +171,14 @@ var SigmaReader = class {
190
171
  return hexToBigInt(hex.encode(this.readBytes(len)));
191
172
  }
192
173
  };
193
- var SigmaWriter = class {
174
+ var SigmaByteWriter = class {
194
175
  #bytes;
195
176
  #cursor;
196
177
  get length() {
197
178
  return this.#cursor;
198
179
  }
199
- constructor(maxLength) {
200
- this.#bytes = new Uint8Array(maxLength);
180
+ constructor(length) {
181
+ this.#bytes = new Uint8Array(length);
201
182
  this.#cursor = 0;
202
183
  }
203
184
  writeBoolean(value) {
@@ -242,26 +223,27 @@ var SigmaWriter = class {
242
223
  } else {
243
224
  this.#bytes[this.#cursor] &= ~(1 << bitOffset++);
244
225
  }
245
- if (bitOffset == 8) {
226
+ if (bitOffset === 8) {
246
227
  bitOffset = 0;
247
228
  this.#cursor++;
248
229
  }
249
230
  }
250
- if (bitOffset > 0) {
251
- this.#cursor++;
252
- }
231
+ if (bitOffset > 0) this.#cursor++;
253
232
  return this;
254
233
  }
255
234
  writeBigInt(value) {
256
235
  const hex6 = bigIntToHex(value);
257
- this.writeVLQ(hex6.length / 2);
258
- this.writeHex(hex6);
259
- return this;
236
+ return this.writeVLQ(hex6.length / 2).writeHex(hex6);
260
237
  }
261
- toHex() {
262
- return hex.encode(this.toBytes());
238
+ writeChecksum(length = 4, hashFn = blake2b256) {
239
+ const hash = hashFn(this.toBytes());
240
+ return this.writeBytes(length ? hash.subarray(0, length) : hash);
241
+ }
242
+ encode(coder) {
243
+ return coder.encode(this.toBytes());
263
244
  }
264
245
  toBytes() {
246
+ if (this.#cursor === this.#bytes.length) return this.#bytes;
265
247
  return this.#bytes.subarray(0, this.#cursor);
266
248
  }
267
249
  };
@@ -393,7 +375,7 @@ var constructorCode = Object.freeze({
393
375
  });
394
376
  var MAX_PRIMITIVE_TYPE_CODE = 11;
395
377
  var PRIMITIVE_TYPE_RANGE = MAX_PRIMITIVE_TYPE_CODE + 1;
396
- var typeCodeOf = (constructor) => PRIMITIVE_TYPE_RANGE * constructor;
378
+ var typeCodeOf = (ctor) => PRIMITIVE_TYPE_RANGE * ctor;
397
379
  var collDescriptor = Object.freeze({
398
380
  code: typeCodeOf(constructorCode.simpleColl),
399
381
  embeddable: false,
@@ -486,8 +468,7 @@ function monoProxy(ctor, cache, forceConstruction) {
486
468
  return new Proxy(ctor, {
487
469
  apply: (target, _, args) => {
488
470
  const instance = cache ?? new target();
489
- if (!forceConstruction && isEmpty(args))
490
- return instance;
471
+ if (!forceConstruction && isEmpty(args)) return instance;
491
472
  return new SConstant(instance, ...args);
492
473
  }
493
474
  });
@@ -499,41 +480,56 @@ function genericProxy(ctor, handler) {
499
480
  }
500
481
  var SByte = monoProxy(SByteType, descriptors.byte);
501
482
  var SBool = monoProxy(SBoolType, descriptors.bool);
502
- var SShort = monoProxy(SShortType, descriptors.short);
483
+ var SShort = monoProxy(
484
+ SShortType,
485
+ descriptors.short
486
+ );
503
487
  var SInt = monoProxy(SIntType, descriptors.int);
504
- var SLong = monoProxy(SLongType, descriptors.long);
505
- var SBigInt = monoProxy(SBigIntType, descriptors.bigInt);
506
- var SGroupElement = monoProxy(
507
- SGroupElementType,
508
- descriptors.groupElement
488
+ var SLong = monoProxy(
489
+ SLongType,
490
+ descriptors.long
491
+ );
492
+ var SBigInt = monoProxy(
493
+ SBigIntType,
494
+ descriptors.bigInt
509
495
  );
496
+ var SGroupElement = monoProxy(SGroupElementType, descriptors.groupElement);
510
497
  var SSigmaProp = monoProxy(
511
498
  SSigmaPropType,
512
499
  descriptors.sigmaProp
513
500
  );
514
501
  var SUnit = monoProxy(SUnitType, void 0, true);
515
- var SColl = genericProxy(SCollType, (target, _, args) => {
516
- const [type, elements] = args;
517
- const elementsType = type();
518
- if (!elements)
519
- return () => new target(elementsType);
520
- return new SConstant(new target(elementsType), elements);
521
- });
522
- var SPair = genericProxy(STupleType, (target, _, args) => {
523
- const [left, right] = args;
524
- if (typeof left === "function" && typeof right === "function") {
525
- return () => new target([left(), right()]);
526
- } else if (left instanceof SConstant && right instanceof SConstant) {
527
- return new SConstant(new target([left.type, right.type]), [left.data, right.data]);
528
- }
529
- throw new Error("Invalid tuple declaration.");
530
- });
502
+ var SColl = genericProxy(
503
+ SCollType,
504
+ (target, _, args) => {
505
+ const [type, elements] = args;
506
+ const elementsType = type();
507
+ if (!elements) return () => new target(elementsType);
508
+ return new SConstant(new target(elementsType), elements);
509
+ }
510
+ );
511
+ var SPair = genericProxy(
512
+ STupleType,
513
+ (target, _, args) => {
514
+ const [left, right] = args;
515
+ if (typeof left === "function" && typeof right === "function") {
516
+ return () => new target([left(), right()]);
517
+ }
518
+ if (left instanceof SConstant && right instanceof SConstant) {
519
+ return new SConstant(new target([left.type, right.type]), [
520
+ left.data,
521
+ right.data
522
+ ]);
523
+ }
524
+ throw new Error("Invalid tuple declaration.");
525
+ }
526
+ );
531
527
 
532
528
  // src/serializers/dataSerializer.ts
533
529
  var GROUP_ELEMENT_LENGTH = 33;
534
530
  var PROVE_DLOG_OP = 205;
535
- var DataSerializer = class _DataSerializer {
536
- static serialize(data, type, writer) {
531
+ var dataSerializer = {
532
+ serialize(data, type, writer) {
537
533
  if (type.embeddable) {
538
534
  switch (type.code) {
539
535
  case descriptors.bool.code:
@@ -546,27 +542,33 @@ var DataSerializer = class _DataSerializer {
546
542
  return writer.writeInt(data);
547
543
  case descriptors.long.code:
548
544
  return writer.writeLong(data);
549
- case descriptors.bigInt.code: {
545
+ case descriptors.bigInt.code:
550
546
  return writer.writeBigInt(data);
551
- }
552
547
  case descriptors.groupElement.code:
553
548
  return writer.writeBytes(data);
554
549
  case descriptors.sigmaProp.code: {
555
550
  const node = data;
556
551
  if (node.type === descriptors.groupElement) {
557
552
  writer.write(PROVE_DLOG_OP);
558
- return _DataSerializer.serialize(node.data, node.type, writer);
559
- } else {
560
- throw Error("Serialization error: SigmaProp operation not implemented.");
553
+ return dataSerializer.serialize(node.data, node.type, writer);
561
554
  }
555
+ throw Error(
556
+ "Serialization error: SigmaProp operation not implemented."
557
+ );
562
558
  }
563
559
  }
564
- } else if (isColl(type)) {
560
+ }
561
+ if (isColl(type)) {
565
562
  if (type.elementsType.code === descriptors.byte.code) {
566
- const isUint8Array = data instanceof Uint8Array;
567
- assert(isUint8Array, `SColl[Byte] expected an UInt8Array, got ${typeof data}.`);
563
+ assert(
564
+ data instanceof Uint8Array,
565
+ `SColl[Byte] expected an UInt8Array, got ${typeof data}.`
566
+ );
568
567
  } else {
569
- assert(Array.isArray(data), `SColl expected an array, got ${typeof data}.`);
568
+ assert(
569
+ Array.isArray(data),
570
+ `SColl expected an array, got ${typeof data}.`
571
+ );
570
572
  }
571
573
  writer.writeVLQ(data.length);
572
574
  switch (type.elementsType.code) {
@@ -578,27 +580,29 @@ var DataSerializer = class _DataSerializer {
578
580
  }
579
581
  default: {
580
582
  for (let i = 0; i < data.length; i++) {
581
- _DataSerializer.serialize(data[i], type.elementsType, writer);
583
+ dataSerializer.serialize(data[i], type.elementsType, writer);
582
584
  }
583
585
  return writer;
584
586
  }
585
587
  }
586
- } else if (isTuple(type)) {
588
+ }
589
+ if (isTuple(type)) {
587
590
  assert(
588
591
  Array.isArray(data),
589
592
  `STupleType serialization expected an array, got ${typeof data}.`
590
593
  );
591
594
  const len = type.elementsType.length;
592
595
  for (let i = 0; i < len; i++) {
593
- _DataSerializer.serialize(data[i], type.elementsType[i], writer);
596
+ dataSerializer.serialize(data[i], type.elementsType[i], writer);
594
597
  }
595
598
  return writer;
596
- } else if (type.code === descriptors.unit.code) {
597
- return writer;
598
599
  }
599
- throw Error(`Serialization error: '0x${type.code.toString(16)}' type not implemented.`);
600
- }
601
- static deserialize(type, reader) {
600
+ if (type.code === descriptors.unit.code) return writer;
601
+ throw Error(
602
+ `Serialization error: '0x${type.code.toString(16)}' type not implemented.`
603
+ );
604
+ },
605
+ deserialize(type, reader) {
602
606
  if (type.embeddable) {
603
607
  switch (type.code) {
604
608
  case descriptors.bool.code:
@@ -642,29 +646,36 @@ var DataSerializer = class _DataSerializer {
642
646
  }
643
647
  }
644
648
  case descriptors.tuple.code: {
645
- return type.elementsType.map((t) => this.deserialize(t, reader));
649
+ return type.elementsType.map(
650
+ (t) => this.deserialize(t, reader)
651
+ );
646
652
  }
647
- case descriptors.unit.code: {
653
+ case descriptors.unit.code:
648
654
  return void 0;
649
- }
650
655
  }
651
656
  }
652
- throw new Error(`Parsing error: '0x${type.code.toString(16)}' type not implemented.`);
657
+ throw new Error(
658
+ `Parsing error: '0x${type.code.toString(16)}' type not implemented.`
659
+ );
653
660
  }
654
661
  };
655
- var TypeSerializer = class {
656
- static serialize(type, writer) {
662
+ var typeSerializer = {
663
+ serialize(type, writer) {
657
664
  if (type.embeddable) {
658
665
  writer.write(type.code);
659
666
  } else if (type.code === descriptors.unit.code) {
660
667
  writer.write(type.code);
661
668
  } else if (isColl(type)) {
662
669
  if (type.elementsType.embeddable) {
663
- writer.write(descriptors.coll.simpleCollTypeCode + type.elementsType.code);
670
+ writer.write(
671
+ descriptors.coll.simpleCollTypeCode + type.elementsType.code
672
+ );
664
673
  } else if (isColl(type.elementsType)) {
665
674
  const nestedColl = type.elementsType;
666
675
  if (nestedColl.elementsType.embeddable) {
667
- writer.write(descriptors.coll.nestedCollTypeCode + nestedColl.elementsType.code);
676
+ writer.write(
677
+ descriptors.coll.nestedCollTypeCode + nestedColl.elementsType.code
678
+ );
668
679
  } else {
669
680
  writer.write(descriptors.coll.simpleCollTypeCode);
670
681
  this.serialize(nestedColl, writer);
@@ -703,7 +714,10 @@ var TypeSerializer = class {
703
714
  break;
704
715
  default: {
705
716
  const len = type.elementsType.length;
706
- assert(len >= 2 && len <= 255, "Invalid type: tuples must have between 2 and 255 items.");
717
+ assert(
718
+ len >= 2 && len <= 255,
719
+ "Invalid type: tuples must have between 2 and 255 items."
720
+ );
707
721
  writer.write(descriptors.tuple.genericTupleTypeCode);
708
722
  writer.writeVLQ(len);
709
723
  }
@@ -714,10 +728,13 @@ var TypeSerializer = class {
714
728
  } else {
715
729
  throw new Error("Serialization error: type not implemented.");
716
730
  }
717
- }
718
- static deserialize(r) {
731
+ },
732
+ deserialize(r) {
719
733
  const byte = r.readByte();
720
- assert(byte > 0, `Parsing Error: Unexpected type code '0x${byte.toString(16)}'`);
734
+ assert(
735
+ byte > 0,
736
+ `Parsing Error: Unexpected type code '0x${byte.toString(16)}'`
737
+ );
721
738
  if (byte < descriptors.tuple.genericTupleTypeCode) {
722
739
  const ctorCode = Math.floor(byte / PRIMITIVE_TYPE_RANGE);
723
740
  const embdCode = Math.floor(byte % PRIMITIVE_TYPE_RANGE);
@@ -741,23 +758,27 @@ var TypeSerializer = class {
741
758
  return new STupleType(internal);
742
759
  }
743
760
  case constructorCode.symmetricPair: {
744
- const internal = embdCode === 0 ? [this.deserialize(r), this.deserialize(r), this.deserialize(r), this.deserialize(r)] : [getPrimitiveType(embdCode), getPrimitiveType(embdCode)];
761
+ const internal = embdCode === 0 ? [
762
+ this.deserialize(r),
763
+ this.deserialize(r),
764
+ this.deserialize(r),
765
+ this.deserialize(r)
766
+ ] : [getPrimitiveType(embdCode), getPrimitiveType(embdCode)];
745
767
  return new STupleType(internal);
746
768
  }
747
769
  }
748
- } else {
749
- switch (byte) {
750
- case descriptors.tuple.genericTupleTypeCode: {
751
- const len = r.readVlq();
752
- const wrapped = new Array(len);
753
- for (let i = 0; i < len; i++) {
754
- wrapped[i] = this.deserialize(r);
755
- }
756
- return new STupleType(wrapped);
757
- }
758
- case descriptors.unit.code: {
759
- return descriptors.unit;
770
+ }
771
+ switch (byte) {
772
+ case descriptors.tuple.genericTupleTypeCode: {
773
+ const len = r.readVlq();
774
+ const wrapped = new Array(len);
775
+ for (let i = 0; i < len; i++) {
776
+ wrapped[i] = this.deserialize(r);
760
777
  }
778
+ return new STupleType(wrapped);
779
+ }
780
+ case descriptors.unit.code: {
781
+ return descriptors.unit;
761
782
  }
762
783
  }
763
784
  throw new Error("Not implemented.");
@@ -775,9 +796,9 @@ var SConstant = class _SConstant {
775
796
  }
776
797
  static from(bytes) {
777
798
  assert(bytes.length > 0, "Empty constant bytes.");
778
- const reader = new SigmaReader(bytes);
779
- const type = TypeSerializer.deserialize(reader);
780
- const data = DataSerializer.deserialize(type, reader);
799
+ const reader = new SigmaByteReader(bytes);
800
+ const type = typeSerializer.deserialize(reader);
801
+ const data = dataSerializer.deserialize(type, reader);
781
802
  return new _SConstant(type, data);
782
803
  }
783
804
  get type() {
@@ -787,20 +808,24 @@ var SConstant = class _SConstant {
787
808
  return this.#data;
788
809
  }
789
810
  toBytes() {
790
- const writer = new SigmaWriter(MAX_CONSTANT_LENGTH);
791
- TypeSerializer.serialize(this.type, writer);
792
- DataSerializer.serialize(this.data, this.type, writer);
811
+ const writer = new SigmaByteWriter(MAX_CONSTANT_LENGTH);
812
+ typeSerializer.serialize(this.type, writer);
813
+ dataSerializer.serialize(this.data, this.type, writer);
793
814
  return writer.toBytes();
794
815
  }
795
816
  toHex() {
796
817
  return hex.encode(this.toBytes());
797
818
  }
798
819
  };
820
+ function decode(value, coder) {
821
+ if (isUndefined(value)) return;
822
+ const data = parse(value, "safe");
823
+ if (isUndefined(data)) return;
824
+ return coder ? coder(data) : data;
825
+ }
799
826
  function parse(constant, mode = "strict") {
800
- if (mode === "strict")
801
- return SConstant.from(constant ?? "").data;
802
- if (!constant)
803
- return;
827
+ if (mode === "strict") return SConstant.from(constant ?? "").data;
828
+ if (!constant) return;
804
829
  try {
805
830
  return SConstant.from(constant).data;
806
831
  } catch {
@@ -808,23 +833,15 @@ function parse(constant, mode = "strict") {
808
833
  }
809
834
  }
810
835
  var MAX_UINT16_VALUE = 65535;
811
- function serializeBox(box, writer, distinctTokenIds) {
812
- if (!writer) {
813
- writer = new SigmaWriter(5e4);
814
- }
836
+ function serializeBox(box, writer = new SigmaByteWriter(5e4), distinctTokenIds) {
815
837
  writer.writeBigVLQ(ensureBigInt(box.value));
816
838
  writer.writeHex(box.ergoTree);
817
839
  writer.writeVLQ(box.creationHeight);
818
840
  writeTokens(writer, box.assets, distinctTokenIds);
819
841
  writeRegisters(writer, box.additionalRegisters);
820
- if (isDefined(distinctTokenIds)) {
821
- return writer;
822
- } else {
823
- if (!isBox(box)) {
824
- throw new Error("Invalid box type.");
825
- }
826
- return writer.writeHex(box.transactionId).writeVLQ(box.index);
827
- }
842
+ if (isDefined(distinctTokenIds)) return writer;
843
+ if (!isBox(box)) throw new Error("Invalid box type.");
844
+ return writer.writeHex(box.transactionId).writeVLQ(box.index);
828
845
  }
829
846
  function isBox(box) {
830
847
  const castedBox = box;
@@ -841,26 +858,22 @@ function writeTokens(writer, tokens, tokenIds) {
841
858
  (token) => writer.writeVLQ(tokenIds.indexOf(token.tokenId)).writeBigVLQ(ensureBigInt(token.amount))
842
859
  );
843
860
  } else {
844
- tokens.map((token) => writer.writeHex(token.tokenId).writeBigVLQ(ensureBigInt(token.amount)));
861
+ tokens.map(
862
+ (token) => writer.writeHex(token.tokenId).writeBigVLQ(ensureBigInt(token.amount))
863
+ );
845
864
  }
846
865
  }
847
866
  function writeRegisters(writer, registers) {
848
867
  const keys = Object.keys(registers).sort();
849
868
  let length = 0;
850
869
  for (const key of keys) {
851
- if (registers[key]) {
852
- length++;
853
- }
870
+ if (registers[key]) length++;
854
871
  }
855
872
  writer.writeVLQ(length);
856
- if (length == 0) {
857
- return;
858
- }
873
+ if (length === 0) return;
859
874
  for (const key of keys) {
860
875
  const register = registers[key];
861
- if (isDefined(register)) {
862
- writer.writeHex(register);
863
- }
876
+ if (isDefined(register)) writer.writeHex(register);
864
877
  }
865
878
  }
866
879
  function estimateBoxSize(box, withValue) {
@@ -872,10 +885,9 @@ function estimateBoxSize(box, withValue) {
872
885
  size += byteSizeOf(box.ergoTree);
873
886
  size += estimateVLQSize(box.creationHeight);
874
887
  size += estimateVLQSize(box.assets.length);
875
- size += box.assets.reduce(
876
- (acc, curr) => acc += byteSizeOf(curr.tokenId) + estimateVLQSize(curr.amount),
877
- 0
878
- );
888
+ for (const asset of box.assets) {
889
+ size += byteSizeOf(asset.tokenId) + estimateVLQSize(asset.amount);
890
+ }
879
891
  let registersLength = 0;
880
892
  for (const key in box.additionalRegisters) {
881
893
  const register = box.additionalRegisters[key];
@@ -890,7 +902,7 @@ function estimateBoxSize(box, withValue) {
890
902
  return size;
891
903
  }
892
904
  function serializeTransaction(transaction) {
893
- const writer = new SigmaWriter(1e5);
905
+ const writer = new SigmaByteWriter(1e5);
894
906
  writer.writeVLQ(transaction.inputs.length);
895
907
  transaction.inputs.map((input) => writeInput(writer, input));
896
908
  writer.writeVLQ(transaction.dataInputs.length);
@@ -899,7 +911,9 @@ function serializeTransaction(transaction) {
899
911
  writer.writeVLQ(distinctTokenIds.length);
900
912
  distinctTokenIds.map((tokenId) => writer.writeHex(tokenId));
901
913
  writer.writeVLQ(transaction.outputs.length);
902
- transaction.outputs.map((output) => serializeBox(output, writer, distinctTokenIds));
914
+ transaction.outputs.map(
915
+ (output) => serializeBox(output, writer, distinctTokenIds)
916
+ );
903
917
  return writer;
904
918
  }
905
919
  function writeInput(writer, input) {
@@ -917,9 +931,7 @@ function writeExtension(writer, extension) {
917
931
  }
918
932
  }
919
933
  writer.writeVLQ(length);
920
- if (length == 0) {
921
- return;
922
- }
934
+ if (length === 0) return;
923
935
  for (const key of keys) {
924
936
  const ext = extension[key];
925
937
  if (isDefined(ext)) {
@@ -929,10 +941,12 @@ function writeExtension(writer, extension) {
929
941
  }
930
942
  function getDistinctTokenIds(outputs) {
931
943
  const tokenIds = /* @__PURE__ */ new Set();
932
- outputs.flatMap((output) => output.assets.map((asset) => tokenIds.add(asset.tokenId)));
944
+ outputs.flatMap(
945
+ (output) => output.assets.map((asset) => tokenIds.add(asset.tokenId))
946
+ );
933
947
  return Array.from(tokenIds);
934
948
  }
935
949
 
936
- export { DataSerializer, SBigInt, SBigIntType, SBool, SBoolType, SByte, SByteType, SColl, SCollType, SConstant, SGenericType, SGroupElement, SGroupElementType, SInt, SIntType, SLong, SLongType, SMonomorphicType, SPair, SPrimitiveType, SShort, SShortType, SSigmaProp, SSigmaPropType, STupleType, SType, SUnit, SUnitType, TypeSerializer, estimateBoxSize, estimateVLQSize, isColl, isTuple, parse, serializeBox, serializeTransaction };
950
+ export { SBigInt, SBigIntType, SBool, SBoolType, SByte, SByteType, SColl, SCollType, SConstant, SGenericType, SGroupElement, SGroupElementType, SInt, SIntType, SLong, SLongType, SMonomorphicType, SPair, SPrimitiveType, SShort, SShortType, SSigmaProp, SSigmaPropType, STupleType, SType, SUnit, SUnitType, SigmaByteReader, SigmaByteWriter, dataSerializer, decode, estimateBoxSize, estimateVLQSize, isColl, isTuple, parse, serializeBox, serializeTransaction, typeSerializer };
937
951
  //# sourceMappingURL=out.js.map
938
952
  //# sourceMappingURL=index.mjs.map