@fleet-sdk/serializer 0.2.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.js ADDED
@@ -0,0 +1,974 @@
1
+ 'use strict';
2
+
3
+ var common = require('@fleet-sdk/common');
4
+ var crypto = require('@fleet-sdk/crypto');
5
+
6
+ // src/coders/sigmaReader.ts
7
+ function hexToBigInt(hex6) {
8
+ if (hex6.length % 2) {
9
+ hex6 = "0" + hex6;
10
+ }
11
+ const value = BigInt("0x" + hex6);
12
+ const highByte = parseInt(hex6.slice(0, 2), 16);
13
+ if (128 & highByte) {
14
+ return -_bitNegate(value);
15
+ }
16
+ return value;
17
+ }
18
+ function bigIntToHex(value) {
19
+ const positive = value >= common._0n;
20
+ if (!positive) {
21
+ value = _bitNegate(value);
22
+ }
23
+ let hex6 = value.toString(16);
24
+ if (hex6.length % 2) {
25
+ hex6 = "0" + hex6;
26
+ }
27
+ if (positive && 128 & parseInt(hex6.slice(0, 2), 16)) {
28
+ hex6 = "00" + hex6;
29
+ }
30
+ return hex6;
31
+ }
32
+ function _bitNegate(value) {
33
+ const negative = value < common._0n;
34
+ if (negative) {
35
+ value = -value;
36
+ }
37
+ const bits = value.toString(2);
38
+ let bitLen = bits.length;
39
+ const mod = bitLen % 8;
40
+ if (mod > 0) {
41
+ bitLen += 8 - mod;
42
+ } else if (negative && common.first(bits) === "1" && bits.indexOf("1", 1) !== -1) {
43
+ bitLen += 8;
44
+ }
45
+ const mask = (1n << BigInt(bitLen)) - 1n;
46
+ return (~value & mask) + 1n;
47
+ }
48
+ function writeVLQ(writer, value) {
49
+ if (value === 0) {
50
+ return writer.write(0);
51
+ } else if (value < 0) {
52
+ throw new RangeError("Variable Length Quantity not supported for negative numbers.");
53
+ }
54
+ do {
55
+ let lower7bits = value & 127;
56
+ value >>= 7;
57
+ if (value > 0) {
58
+ lower7bits |= 128;
59
+ }
60
+ writer.write(lower7bits);
61
+ } while (value > 0);
62
+ return writer;
63
+ }
64
+ function readVLQ(reader) {
65
+ if (reader.isEmpty) {
66
+ return 0;
67
+ }
68
+ let value = 0;
69
+ let shift = 0;
70
+ let lower7bits = 0;
71
+ do {
72
+ lower7bits = reader.readByte();
73
+ value |= (lower7bits & 127) << shift;
74
+ shift += 7;
75
+ } while ((lower7bits & 128) != 0);
76
+ return value;
77
+ }
78
+ function writeBigVLQ(writer, value) {
79
+ if (value === common._0n) {
80
+ return writer.write(0);
81
+ } else if (value < common._0n) {
82
+ throw new RangeError("Variable Length Quantity not supported for negative numbers");
83
+ }
84
+ do {
85
+ let lower7bits = Number(value & common._127n);
86
+ value >>= common._7n;
87
+ if (value > 0) {
88
+ lower7bits |= 128;
89
+ }
90
+ writer.write(lower7bits);
91
+ } while (value > 0);
92
+ return writer;
93
+ }
94
+ function readBigVLQ(reader) {
95
+ if (reader.isEmpty) {
96
+ return common._0n;
97
+ }
98
+ let value = common._0n;
99
+ let shift = common._0n;
100
+ let lower7bits = common._0n;
101
+ do {
102
+ lower7bits = BigInt(reader.readByte());
103
+ value |= (lower7bits & common._127n) << shift;
104
+ shift += common._7n;
105
+ } while ((lower7bits & common._128n) != common._0n);
106
+ return value;
107
+ }
108
+ function estimateVLQSize(value) {
109
+ let size = 0;
110
+ if (typeof value === "number") {
111
+ do {
112
+ size++;
113
+ value = Math.floor(value / 128);
114
+ } while (value > 0);
115
+ return size;
116
+ }
117
+ value = common.ensureBigInt(value);
118
+ do {
119
+ size++;
120
+ value /= common._128n;
121
+ } while (value > common._0n);
122
+ return size;
123
+ }
124
+ function zigZagEncode(input) {
125
+ return input << 1 ^ input >> 63;
126
+ }
127
+ function zigZagDecode(input) {
128
+ return input >> 1 ^ -(input & 1);
129
+ }
130
+ function zigZagEncodeBigInt(input) {
131
+ return input << common._1n ^ input >> common._63n;
132
+ }
133
+ function zigZagDecodeBigInt(input) {
134
+ return input >> common._1n ^ -(input & common._1n);
135
+ }
136
+
137
+ // src/coders/sigmaReader.ts
138
+ var SigmaReader = class {
139
+ #bytes;
140
+ #cursor;
141
+ get isEmpty() {
142
+ return common.isEmpty(this.#bytes);
143
+ }
144
+ constructor(bytes) {
145
+ if (typeof bytes === "string") {
146
+ this.#bytes = crypto.hex.decode(bytes);
147
+ } else {
148
+ this.#bytes = bytes;
149
+ }
150
+ this.#cursor = 0;
151
+ }
152
+ readBoolean() {
153
+ return this.readByte() === 1;
154
+ }
155
+ readBits(length) {
156
+ const bits = new Array(length);
157
+ let bitOffset = 0;
158
+ for (let i = 0; i < length; i++) {
159
+ const bit = this.#bytes[this.#cursor] >> bitOffset++ & 1;
160
+ bits[i] = bit === 1;
161
+ if (bitOffset == 8) {
162
+ bitOffset = 0;
163
+ this.#cursor++;
164
+ }
165
+ }
166
+ if (bitOffset > 0) {
167
+ this.#cursor++;
168
+ }
169
+ return bits;
170
+ }
171
+ readByte() {
172
+ return this.#bytes[this.#cursor++];
173
+ }
174
+ readBytes(length) {
175
+ return this.#bytes.subarray(this.#cursor, this.#cursor += length);
176
+ }
177
+ readVlq() {
178
+ return readVLQ(this);
179
+ }
180
+ readShort() {
181
+ return Number(zigZagDecode(readVLQ(this)));
182
+ }
183
+ readInt() {
184
+ const int = this.readLong();
185
+ return Number(int);
186
+ }
187
+ readLong() {
188
+ return zigZagDecodeBigInt(readBigVLQ(this));
189
+ }
190
+ readBigInt() {
191
+ const len = readVLQ(this);
192
+ return hexToBigInt(crypto.hex.encode(this.readBytes(len)));
193
+ }
194
+ };
195
+ var SigmaWriter = class {
196
+ #bytes;
197
+ #cursor;
198
+ get length() {
199
+ return this.#cursor;
200
+ }
201
+ constructor(maxLength) {
202
+ this.#bytes = new Uint8Array(maxLength);
203
+ this.#cursor = 0;
204
+ }
205
+ writeBoolean(value) {
206
+ this.write(value === true ? 1 : 0);
207
+ return this;
208
+ }
209
+ writeVLQ(value) {
210
+ return writeVLQ(this, value);
211
+ }
212
+ writeBigVLQ(value) {
213
+ return writeBigVLQ(this, value);
214
+ }
215
+ writeShort(value) {
216
+ this.writeVLQ(zigZagEncode(value));
217
+ return this;
218
+ }
219
+ writeInt(value) {
220
+ this.writeLong(BigInt(value));
221
+ return this;
222
+ }
223
+ writeLong(value) {
224
+ this.writeBigVLQ(zigZagEncodeBigInt(value));
225
+ return this;
226
+ }
227
+ write(byte) {
228
+ this.#bytes[this.#cursor++] = byte;
229
+ return this;
230
+ }
231
+ writeBytes(bytes) {
232
+ this.#bytes.set(bytes, this.#cursor);
233
+ this.#cursor += bytes.length;
234
+ return this;
235
+ }
236
+ writeHex(bytesHex) {
237
+ return this.writeBytes(crypto.hex.decode(bytesHex));
238
+ }
239
+ writeBits(bits) {
240
+ let bitOffset = 0;
241
+ for (let i = 0; i < bits.length; i++) {
242
+ if (bits[i]) {
243
+ this.#bytes[this.#cursor] |= 1 << bitOffset++;
244
+ } else {
245
+ this.#bytes[this.#cursor] &= ~(1 << bitOffset++);
246
+ }
247
+ if (bitOffset == 8) {
248
+ bitOffset = 0;
249
+ this.#cursor++;
250
+ }
251
+ }
252
+ if (bitOffset > 0) {
253
+ this.#cursor++;
254
+ }
255
+ return this;
256
+ }
257
+ writeBigInt(value) {
258
+ const hex6 = bigIntToHex(value);
259
+ this.writeVLQ(hex6.length / 2);
260
+ this.writeHex(hex6);
261
+ return this;
262
+ }
263
+ toHex() {
264
+ return crypto.hex.encode(this.toBytes());
265
+ }
266
+ toBytes() {
267
+ return this.#bytes.subarray(0, this.#cursor);
268
+ }
269
+ };
270
+
271
+ // src/types/base.ts
272
+ var SType = class {
273
+ coerce(data) {
274
+ return data;
275
+ }
276
+ };
277
+ var SMonomorphicType = class extends SType {
278
+ get embeddable() {
279
+ return false;
280
+ }
281
+ };
282
+ var SPrimitiveType = class extends SMonomorphicType {
283
+ get embeddable() {
284
+ return true;
285
+ }
286
+ };
287
+ var SGenericType = class extends SType {
288
+ #internalType;
289
+ constructor(type) {
290
+ super();
291
+ this.#internalType = type;
292
+ }
293
+ get elementsType() {
294
+ return this.#internalType;
295
+ }
296
+ get embeddable() {
297
+ return false;
298
+ }
299
+ };
300
+ var SBoolType = class extends SPrimitiveType {
301
+ get code() {
302
+ return 1;
303
+ }
304
+ toString() {
305
+ return "SBool";
306
+ }
307
+ };
308
+ var SByteType = class extends SPrimitiveType {
309
+ get code() {
310
+ return 2;
311
+ }
312
+ toString() {
313
+ return "SByte";
314
+ }
315
+ };
316
+ var SShortType = class extends SPrimitiveType {
317
+ get code() {
318
+ return 3;
319
+ }
320
+ toString() {
321
+ return "SShort";
322
+ }
323
+ };
324
+ var SIntType = class extends SPrimitiveType {
325
+ get code() {
326
+ return 4;
327
+ }
328
+ toString() {
329
+ return "SInt";
330
+ }
331
+ };
332
+ var SLongType = class extends SPrimitiveType {
333
+ get code() {
334
+ return 5;
335
+ }
336
+ coerce(data) {
337
+ return common.ensureBigInt(data);
338
+ }
339
+ toString() {
340
+ return "SLong";
341
+ }
342
+ };
343
+ var SBigIntType = class extends SPrimitiveType {
344
+ get code() {
345
+ return 6;
346
+ }
347
+ coerce(data) {
348
+ return common.ensureBigInt(data);
349
+ }
350
+ toString() {
351
+ return "SBigInt";
352
+ }
353
+ };
354
+ var SGroupElementType = class extends SPrimitiveType {
355
+ get code() {
356
+ return 7;
357
+ }
358
+ coerce(data) {
359
+ return typeof data === "string" ? crypto.hex.decode(data) : data;
360
+ }
361
+ toString() {
362
+ return "SGroupElement";
363
+ }
364
+ };
365
+ var SSigmaPropType = class extends SPrimitiveType {
366
+ get code() {
367
+ return 8;
368
+ }
369
+ toString() {
370
+ return "SSigmaProp";
371
+ }
372
+ };
373
+
374
+ // src/types/monomorphics.ts
375
+ var SUnitType = class extends SMonomorphicType {
376
+ get code() {
377
+ return 98;
378
+ }
379
+ toString() {
380
+ return "SUnit";
381
+ }
382
+ };
383
+
384
+ // src/types/descriptors.ts
385
+ var constructorCode = Object.freeze({
386
+ embeddable: 0,
387
+ simpleColl: 1,
388
+ nestedColl: 2,
389
+ option: 3,
390
+ optionCollection: 4,
391
+ pairOne: 5,
392
+ pairTwo: 6,
393
+ symmetricPair: 7,
394
+ genericTuple: 8
395
+ });
396
+ var MAX_PRIMITIVE_TYPE_CODE = 11;
397
+ var PRIMITIVE_TYPE_RANGE = MAX_PRIMITIVE_TYPE_CODE + 1;
398
+ var typeCodeOf = (constructor) => PRIMITIVE_TYPE_RANGE * constructor;
399
+ var collDescriptor = Object.freeze({
400
+ code: typeCodeOf(constructorCode.simpleColl),
401
+ embeddable: false,
402
+ simpleCollTypeCode: typeCodeOf(constructorCode.simpleColl),
403
+ nestedCollTypeCode: typeCodeOf(constructorCode.nestedColl)
404
+ });
405
+ var tupleDescriptor = Object.freeze({
406
+ code: typeCodeOf(constructorCode.pairOne),
407
+ embeddable: false,
408
+ pairOneTypeCode: typeCodeOf(constructorCode.pairOne),
409
+ pairTwoTypeCode: typeCodeOf(constructorCode.pairTwo),
410
+ tripleTypeCode: typeCodeOf(constructorCode.pairTwo),
411
+ symmetricPairTypeCode: typeCodeOf(constructorCode.symmetricPair),
412
+ quadrupleTypeCode: typeCodeOf(constructorCode.symmetricPair),
413
+ genericTupleTypeCode: typeCodeOf(constructorCode.genericTuple)
414
+ });
415
+ var descriptors = {
416
+ bool: new SBoolType(),
417
+ byte: new SByteType(),
418
+ short: new SShortType(),
419
+ int: new SIntType(),
420
+ long: new SLongType(),
421
+ bigInt: new SBigIntType(),
422
+ groupElement: new SGroupElementType(),
423
+ sigmaProp: new SSigmaPropType(),
424
+ unit: new SUnitType(),
425
+ coll: collDescriptor,
426
+ tuple: tupleDescriptor
427
+ };
428
+ function isColl(type) {
429
+ return type.code >= descriptors.coll.simpleCollTypeCode && type.code <= descriptors.coll.nestedCollTypeCode + MAX_PRIMITIVE_TYPE_CODE;
430
+ }
431
+ function isTuple(type) {
432
+ return type.code >= descriptors.tuple.pairOneTypeCode && type.code <= descriptors.tuple.genericTupleTypeCode;
433
+ }
434
+ function getPrimitiveType(typeCode) {
435
+ switch (typeCode) {
436
+ case descriptors.bool.code:
437
+ return descriptors.bool;
438
+ case descriptors.byte.code:
439
+ return descriptors.byte;
440
+ case descriptors.short.code:
441
+ return descriptors.short;
442
+ case descriptors.int.code:
443
+ return descriptors.int;
444
+ case descriptors.long.code:
445
+ return descriptors.long;
446
+ case descriptors.bigInt.code:
447
+ return descriptors.bigInt;
448
+ case descriptors.groupElement.code:
449
+ return descriptors.groupElement;
450
+ case descriptors.sigmaProp.code:
451
+ return descriptors.sigmaProp;
452
+ default:
453
+ throw new Error(
454
+ `The type code '0x${typeCode.toString(16)}' is not a valid primitive type code.`
455
+ );
456
+ }
457
+ }
458
+ var SCollType = class extends SGenericType {
459
+ get code() {
460
+ return descriptors.coll.code;
461
+ }
462
+ coerce(elements) {
463
+ if (this.elementsType.code === descriptors.byte.code && !(elements instanceof Uint8Array)) {
464
+ return typeof elements === "string" ? crypto.hex.decode(elements) : Uint8Array.from(elements);
465
+ }
466
+ return elements.map((el) => this.elementsType.coerce(el));
467
+ }
468
+ toString() {
469
+ return `SColl[${this.elementsType.toString()}]`;
470
+ }
471
+ };
472
+ var STupleType = class extends SGenericType {
473
+ get code() {
474
+ return descriptors.tuple.code;
475
+ }
476
+ coerce(elements) {
477
+ const output = new Array(elements.length);
478
+ for (let i = 0; i < elements.length; i++) {
479
+ output[i] = this.elementsType[i].coerce(elements[i]);
480
+ }
481
+ return output;
482
+ }
483
+ toString() {
484
+ return `(${this.elementsType.map((el) => el.toString()).join(", ")})`;
485
+ }
486
+ };
487
+ function monoProxy(ctor, cache, forceConstruction) {
488
+ return new Proxy(ctor, {
489
+ apply: (target, _, args) => {
490
+ const instance = cache ?? new target();
491
+ if (!forceConstruction && common.isEmpty(args))
492
+ return instance;
493
+ return new SConstant(instance, ...args);
494
+ }
495
+ });
496
+ }
497
+ function genericProxy(ctor, handler) {
498
+ return new Proxy(ctor, {
499
+ apply: handler
500
+ });
501
+ }
502
+ var SByte = monoProxy(SByteType, descriptors.byte);
503
+ var SBool = monoProxy(SBoolType, descriptors.bool);
504
+ var SShort = monoProxy(SShortType, descriptors.short);
505
+ var SInt = monoProxy(SIntType, descriptors.int);
506
+ var SLong = monoProxy(SLongType, descriptors.long);
507
+ var SBigInt = monoProxy(SBigIntType, descriptors.bigInt);
508
+ var SGroupElement = monoProxy(
509
+ SGroupElementType,
510
+ descriptors.groupElement
511
+ );
512
+ var SSigmaProp = monoProxy(
513
+ SSigmaPropType,
514
+ descriptors.sigmaProp
515
+ );
516
+ var SUnit = monoProxy(SUnitType, void 0, true);
517
+ var SColl = genericProxy(SCollType, (target, _, args) => {
518
+ const [type, elements] = args;
519
+ const elementsType = type();
520
+ if (!elements)
521
+ return () => new target(elementsType);
522
+ return new SConstant(new target(elementsType), elements);
523
+ });
524
+ var SPair = genericProxy(STupleType, (target, _, args) => {
525
+ const [left, right] = args;
526
+ if (typeof left === "function" && typeof right === "function") {
527
+ return () => new target([left(), right()]);
528
+ } else if (left instanceof SConstant && right instanceof SConstant) {
529
+ return new SConstant(new target([left.type, right.type]), [left.data, right.data]);
530
+ }
531
+ throw new Error("Invalid tuple declaration.");
532
+ });
533
+
534
+ // src/serializers/dataSerializer.ts
535
+ var GROUP_ELEMENT_LENGTH = 33;
536
+ var PROVE_DLOG_OP = 205;
537
+ var DataSerializer = class _DataSerializer {
538
+ static serialize(data, type, writer) {
539
+ if (type.embeddable) {
540
+ switch (type.code) {
541
+ case descriptors.bool.code:
542
+ return writer.writeBoolean(data);
543
+ case descriptors.byte.code:
544
+ return writer.write(data);
545
+ case descriptors.short.code:
546
+ return writer.writeShort(data);
547
+ case descriptors.int.code:
548
+ return writer.writeInt(data);
549
+ case descriptors.long.code:
550
+ return writer.writeLong(data);
551
+ case descriptors.bigInt.code: {
552
+ return writer.writeBigInt(data);
553
+ }
554
+ case descriptors.groupElement.code:
555
+ return writer.writeBytes(data);
556
+ case descriptors.sigmaProp.code: {
557
+ const node = data;
558
+ if (node.type === descriptors.groupElement) {
559
+ writer.write(PROVE_DLOG_OP);
560
+ return _DataSerializer.serialize(node.data, node.type, writer);
561
+ } else {
562
+ throw Error("Serialization error: SigmaProp operation not implemented.");
563
+ }
564
+ }
565
+ }
566
+ } else if (isColl(type)) {
567
+ if (type.elementsType.code === descriptors.byte.code) {
568
+ const isUint8Array = data instanceof Uint8Array;
569
+ common.assert(isUint8Array, `SColl[Byte] expected an UInt8Array, got ${typeof data}.`);
570
+ } else {
571
+ common.assert(Array.isArray(data), `SColl expected an array, got ${typeof data}.`);
572
+ }
573
+ writer.writeVLQ(data.length);
574
+ switch (type.elementsType.code) {
575
+ case descriptors.bool.code: {
576
+ return writer.writeBits(data);
577
+ }
578
+ case descriptors.byte.code: {
579
+ return writer.writeBytes(data);
580
+ }
581
+ default: {
582
+ for (let i = 0; i < data.length; i++) {
583
+ _DataSerializer.serialize(data[i], type.elementsType, writer);
584
+ }
585
+ return writer;
586
+ }
587
+ }
588
+ } else if (isTuple(type)) {
589
+ common.assert(
590
+ Array.isArray(data),
591
+ `STupleType serialization expected an array, got ${typeof data}.`
592
+ );
593
+ const len = type.elementsType.length;
594
+ for (let i = 0; i < len; i++) {
595
+ _DataSerializer.serialize(data[i], type.elementsType[i], writer);
596
+ }
597
+ return writer;
598
+ } else if (type.code === descriptors.unit.code) {
599
+ return writer;
600
+ }
601
+ throw Error(`Serialization error: '0x${type.code.toString(16)}' type not implemented.`);
602
+ }
603
+ static deserialize(type, reader) {
604
+ if (type.embeddable) {
605
+ switch (type.code) {
606
+ case descriptors.bool.code:
607
+ return reader.readBoolean();
608
+ case descriptors.byte.code:
609
+ return reader.readByte();
610
+ case descriptors.short.code:
611
+ return reader.readShort();
612
+ case descriptors.int.code:
613
+ return reader.readInt();
614
+ case descriptors.long.code:
615
+ return reader.readLong();
616
+ case descriptors.bigInt.code:
617
+ return reader.readBigInt();
618
+ case descriptors.groupElement.code:
619
+ return reader.readBytes(GROUP_ELEMENT_LENGTH);
620
+ case descriptors.sigmaProp.code: {
621
+ if (reader.readByte() === PROVE_DLOG_OP) {
622
+ return this.deserialize(descriptors.groupElement, reader);
623
+ }
624
+ break;
625
+ }
626
+ }
627
+ } else {
628
+ switch (type.code) {
629
+ case descriptors.coll.code: {
630
+ const length = reader.readVlq();
631
+ const embeddedType = type.elementsType;
632
+ switch (embeddedType.code) {
633
+ case descriptors.bool.code:
634
+ return reader.readBits(length);
635
+ case descriptors.byte.code:
636
+ return reader.readBytes(length);
637
+ default: {
638
+ const elements = new Array(length);
639
+ for (let i = 0; i < length; i++) {
640
+ elements[i] = this.deserialize(embeddedType, reader);
641
+ }
642
+ return elements;
643
+ }
644
+ }
645
+ }
646
+ case descriptors.tuple.code: {
647
+ return type.elementsType.map((t) => this.deserialize(t, reader));
648
+ }
649
+ case descriptors.unit.code: {
650
+ return void 0;
651
+ }
652
+ }
653
+ }
654
+ throw new Error(`Parsing error: '0x${type.code.toString(16)}' type not implemented.`);
655
+ }
656
+ };
657
+ var TypeSerializer = class {
658
+ static serialize(type, writer) {
659
+ if (type.embeddable) {
660
+ writer.write(type.code);
661
+ } else if (type.code === descriptors.unit.code) {
662
+ writer.write(type.code);
663
+ } else if (isColl(type)) {
664
+ if (type.elementsType.embeddable) {
665
+ writer.write(descriptors.coll.simpleCollTypeCode + type.elementsType.code);
666
+ } else if (isColl(type.elementsType)) {
667
+ const nestedColl = type.elementsType;
668
+ if (nestedColl.elementsType.embeddable) {
669
+ writer.write(descriptors.coll.nestedCollTypeCode + nestedColl.elementsType.code);
670
+ } else {
671
+ writer.write(descriptors.coll.simpleCollTypeCode);
672
+ this.serialize(nestedColl, writer);
673
+ }
674
+ } else {
675
+ writer.write(descriptors.coll.simpleCollTypeCode);
676
+ this.serialize(type.elementsType, writer);
677
+ }
678
+ } else if (isTuple(type)) {
679
+ switch (type.elementsType.length) {
680
+ case 2: {
681
+ const left = common.first(type.elementsType);
682
+ const right = common.last(type.elementsType);
683
+ if (left.embeddable) {
684
+ if (left.code === right.code) {
685
+ writer.write(descriptors.tuple.symmetricPairTypeCode + left.code);
686
+ } else {
687
+ writer.write(descriptors.tuple.pairOneTypeCode + left.code);
688
+ this.serialize(right, writer);
689
+ }
690
+ } else if (right.embeddable) {
691
+ writer.write(descriptors.tuple.pairTwoTypeCode + right.code);
692
+ this.serialize(left, writer);
693
+ } else {
694
+ writer.write(descriptors.tuple.pairOneTypeCode);
695
+ this.serialize(left, writer);
696
+ this.serialize(right, writer);
697
+ }
698
+ return;
699
+ }
700
+ case 3:
701
+ writer.write(descriptors.tuple.tripleTypeCode);
702
+ break;
703
+ case 4:
704
+ writer.write(descriptors.tuple.quadrupleTypeCode);
705
+ break;
706
+ default: {
707
+ const len = type.elementsType.length;
708
+ common.assert(len >= 2 && len <= 255, "Invalid type: tuples must have between 2 and 255 items.");
709
+ writer.write(descriptors.tuple.genericTupleTypeCode);
710
+ writer.writeVLQ(len);
711
+ }
712
+ }
713
+ for (let i = 0; i < type.elementsType.length; i++) {
714
+ this.serialize(type.elementsType[i], writer);
715
+ }
716
+ } else {
717
+ throw new Error("Serialization error: type not implemented.");
718
+ }
719
+ }
720
+ static deserialize(r) {
721
+ const byte = r.readByte();
722
+ common.assert(byte > 0, `Parsing Error: Unexpected type code '0x${byte.toString(16)}'`);
723
+ if (byte < descriptors.tuple.genericTupleTypeCode) {
724
+ const ctorCode = Math.floor(byte / PRIMITIVE_TYPE_RANGE);
725
+ const embdCode = Math.floor(byte % PRIMITIVE_TYPE_RANGE);
726
+ switch (ctorCode) {
727
+ case constructorCode.embeddable: {
728
+ return getPrimitiveType(embdCode);
729
+ }
730
+ case constructorCode.simpleColl: {
731
+ const internal = embdCode === 0 ? this.deserialize(r) : getPrimitiveType(embdCode);
732
+ return new SCollType(internal);
733
+ }
734
+ case constructorCode.nestedColl: {
735
+ return new SCollType(new SCollType(getPrimitiveType(embdCode)));
736
+ }
737
+ case constructorCode.pairOne: {
738
+ const internal = embdCode === 0 ? [this.deserialize(r), this.deserialize(r)] : [getPrimitiveType(embdCode), this.deserialize(r)];
739
+ return new STupleType(internal);
740
+ }
741
+ case constructorCode.pairTwo: {
742
+ const internal = embdCode === 0 ? [this.deserialize(r), this.deserialize(r), this.deserialize(r)] : [this.deserialize(r), getPrimitiveType(embdCode)];
743
+ return new STupleType(internal);
744
+ }
745
+ case constructorCode.symmetricPair: {
746
+ const internal = embdCode === 0 ? [this.deserialize(r), this.deserialize(r), this.deserialize(r), this.deserialize(r)] : [getPrimitiveType(embdCode), getPrimitiveType(embdCode)];
747
+ return new STupleType(internal);
748
+ }
749
+ }
750
+ } else {
751
+ switch (byte) {
752
+ case descriptors.tuple.genericTupleTypeCode: {
753
+ const len = r.readVlq();
754
+ const wrapped = new Array(len);
755
+ for (let i = 0; i < len; i++) {
756
+ wrapped[i] = this.deserialize(r);
757
+ }
758
+ return new STupleType(wrapped);
759
+ }
760
+ case descriptors.unit.code: {
761
+ return descriptors.unit;
762
+ }
763
+ }
764
+ }
765
+ throw new Error("Not implemented.");
766
+ }
767
+ };
768
+
769
+ // src/sigmaConstant.ts
770
+ var MAX_CONSTANT_LENGTH = 4096;
771
+ var SConstant = class _SConstant {
772
+ #type;
773
+ #data;
774
+ constructor(type, data) {
775
+ this.#type = type;
776
+ this.#data = type.coerce(data);
777
+ }
778
+ static from(bytes) {
779
+ const reader = new SigmaReader(bytes);
780
+ const type = TypeSerializer.deserialize(reader);
781
+ const data = DataSerializer.deserialize(type, reader);
782
+ return new _SConstant(type, data);
783
+ }
784
+ get type() {
785
+ return this.#type;
786
+ }
787
+ get data() {
788
+ return this.#data;
789
+ }
790
+ toBytes() {
791
+ const writer = new SigmaWriter(MAX_CONSTANT_LENGTH);
792
+ TypeSerializer.serialize(this.type, writer);
793
+ DataSerializer.serialize(this.data, this.type, writer);
794
+ return writer.toBytes();
795
+ }
796
+ toHex() {
797
+ return crypto.hex.encode(this.toBytes());
798
+ }
799
+ };
800
+ function parse(bytes, mode = "strict") {
801
+ if (mode === "strict")
802
+ return SConstant.from(bytes).data;
803
+ if (!bytes)
804
+ return;
805
+ try {
806
+ return SConstant.from(bytes).data;
807
+ } catch {
808
+ return;
809
+ }
810
+ }
811
+ var MAX_UINT16_VALUE = 65535;
812
+ function serializeBox(box, writer, distinctTokenIds) {
813
+ if (!writer) {
814
+ writer = new SigmaWriter(5e4);
815
+ }
816
+ writer.writeBigVLQ(common.ensureBigInt(box.value));
817
+ writer.writeHex(box.ergoTree);
818
+ writer.writeVLQ(box.creationHeight);
819
+ writeTokens(writer, box.assets, distinctTokenIds);
820
+ writeRegisters(writer, box.additionalRegisters);
821
+ if (common.isDefined(distinctTokenIds)) {
822
+ return writer;
823
+ } else {
824
+ if (!isBox(box)) {
825
+ throw new Error("Invalid box type.");
826
+ }
827
+ return writer.writeHex(box.transactionId).writeVLQ(box.index);
828
+ }
829
+ }
830
+ function isBox(box) {
831
+ const castedBox = box;
832
+ return common.isDefined(castedBox.transactionId) && common.isDefined(castedBox.index);
833
+ }
834
+ function writeTokens(writer, tokens, tokenIds) {
835
+ if (common.isEmpty(tokens)) {
836
+ writer.write(0);
837
+ return;
838
+ }
839
+ writer.writeVLQ(tokens.length);
840
+ if (common.some(tokenIds)) {
841
+ tokens.map(
842
+ (token) => writer.writeVLQ(tokenIds.indexOf(token.tokenId)).writeBigVLQ(common.ensureBigInt(token.amount))
843
+ );
844
+ } else {
845
+ tokens.map((token) => writer.writeHex(token.tokenId).writeBigVLQ(common.ensureBigInt(token.amount)));
846
+ }
847
+ }
848
+ function writeRegisters(writer, registers) {
849
+ const keys = Object.keys(registers).sort();
850
+ let length = 0;
851
+ for (const key of keys) {
852
+ if (registers[key]) {
853
+ length++;
854
+ }
855
+ }
856
+ writer.writeVLQ(length);
857
+ if (length == 0) {
858
+ return;
859
+ }
860
+ for (const key of keys) {
861
+ const register = registers[key];
862
+ if (common.isDefined(register)) {
863
+ writer.writeHex(register);
864
+ }
865
+ }
866
+ }
867
+ function estimateBoxSize(box, withValue) {
868
+ if (common.isUndefined(box.creationHeight)) {
869
+ throw new Error("Box size estimation error: creation height is undefined.");
870
+ }
871
+ let size = 0;
872
+ size += estimateVLQSize(common.isDefined(withValue) ? withValue : box.value);
873
+ size += common.byteSizeOf(box.ergoTree);
874
+ size += estimateVLQSize(box.creationHeight);
875
+ size += estimateVLQSize(box.assets.length);
876
+ size += box.assets.reduce(
877
+ (acc, curr) => acc += common.byteSizeOf(curr.tokenId) + estimateVLQSize(curr.amount),
878
+ 0
879
+ );
880
+ let registersLength = 0;
881
+ for (const key in box.additionalRegisters) {
882
+ const register = box.additionalRegisters[key];
883
+ if (register) {
884
+ size += common.byteSizeOf(register);
885
+ registersLength++;
886
+ }
887
+ }
888
+ size += estimateVLQSize(registersLength);
889
+ size += 32;
890
+ size += estimateVLQSize(isBox(box) ? box.index : MAX_UINT16_VALUE);
891
+ return size;
892
+ }
893
+ function serializeTransaction(transaction) {
894
+ const writer = new SigmaWriter(1e5);
895
+ writer.writeVLQ(transaction.inputs.length);
896
+ transaction.inputs.map((input) => writeInput(writer, input));
897
+ writer.writeVLQ(transaction.dataInputs.length);
898
+ transaction.dataInputs.map((dataInput) => writer.writeHex(dataInput.boxId));
899
+ const distinctTokenIds = getDistinctTokenIds(transaction.outputs);
900
+ writer.writeVLQ(distinctTokenIds.length);
901
+ distinctTokenIds.map((tokenId) => writer.writeHex(tokenId));
902
+ writer.writeVLQ(transaction.outputs.length);
903
+ transaction.outputs.map((output) => serializeBox(output, writer, distinctTokenIds));
904
+ return writer;
905
+ }
906
+ function writeInput(writer, input) {
907
+ writer.writeHex(input.boxId);
908
+ writer.write(0);
909
+ writeExtension(writer, input.extension);
910
+ }
911
+ function writeExtension(writer, extension) {
912
+ const keys = Object.keys(extension);
913
+ let length = 0;
914
+ for (const key of keys) {
915
+ const ext = extension[key];
916
+ if (common.isDefined(ext)) {
917
+ length++;
918
+ }
919
+ }
920
+ writer.writeVLQ(length);
921
+ if (length == 0) {
922
+ return;
923
+ }
924
+ for (const key of keys) {
925
+ const ext = extension[key];
926
+ if (common.isDefined(ext)) {
927
+ writer.writeVLQ(Number(key)).writeHex(ext);
928
+ }
929
+ }
930
+ }
931
+ function getDistinctTokenIds(outputs) {
932
+ const tokenIds = /* @__PURE__ */ new Set();
933
+ outputs.flatMap((output) => output.assets.map((asset) => tokenIds.add(asset.tokenId)));
934
+ return Array.from(tokenIds);
935
+ }
936
+
937
+ exports.DataSerializer = DataSerializer;
938
+ exports.SBigInt = SBigInt;
939
+ exports.SBigIntType = SBigIntType;
940
+ exports.SBool = SBool;
941
+ exports.SBoolType = SBoolType;
942
+ exports.SByte = SByte;
943
+ exports.SByteType = SByteType;
944
+ exports.SColl = SColl;
945
+ exports.SCollType = SCollType;
946
+ exports.SConstant = SConstant;
947
+ exports.SGenericType = SGenericType;
948
+ exports.SGroupElement = SGroupElement;
949
+ exports.SGroupElementType = SGroupElementType;
950
+ exports.SInt = SInt;
951
+ exports.SIntType = SIntType;
952
+ exports.SLong = SLong;
953
+ exports.SLongType = SLongType;
954
+ exports.SMonomorphicType = SMonomorphicType;
955
+ exports.SPair = SPair;
956
+ exports.SPrimitiveType = SPrimitiveType;
957
+ exports.SShort = SShort;
958
+ exports.SShortType = SShortType;
959
+ exports.SSigmaProp = SSigmaProp;
960
+ exports.SSigmaPropType = SSigmaPropType;
961
+ exports.STupleType = STupleType;
962
+ exports.SType = SType;
963
+ exports.SUnit = SUnit;
964
+ exports.SUnitType = SUnitType;
965
+ exports.TypeSerializer = TypeSerializer;
966
+ exports.estimateBoxSize = estimateBoxSize;
967
+ exports.estimateVLQSize = estimateVLQSize;
968
+ exports.isColl = isColl;
969
+ exports.isTuple = isTuple;
970
+ exports.parse = parse;
971
+ exports.serializeBox = serializeBox;
972
+ exports.serializeTransaction = serializeTransaction;
973
+ //# sourceMappingURL=out.js.map
974
+ //# sourceMappingURL=index.js.map