@tezos-x/octez.js-michel-codec 0.9.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.
Files changed (41) hide show
  1. package/README.md +174 -0
  2. package/dist/lib/base58.js +255 -0
  3. package/dist/lib/binary.js +1272 -0
  4. package/dist/lib/errors.js +90 -0
  5. package/dist/lib/formatters.js +60 -0
  6. package/dist/lib/global-constants.js +12 -0
  7. package/dist/lib/macros.js +548 -0
  8. package/dist/lib/micheline-emitter.js +132 -0
  9. package/dist/lib/micheline-parser.js +403 -0
  10. package/dist/lib/micheline.js +5 -0
  11. package/dist/lib/michelson-contract.js +93 -0
  12. package/dist/lib/michelson-typecheck.js +1752 -0
  13. package/dist/lib/michelson-types.js +83 -0
  14. package/dist/lib/michelson-validator.js +835 -0
  15. package/dist/lib/octez.js-michel-codec.js +38 -0
  16. package/dist/lib/scan.js +128 -0
  17. package/dist/lib/utils.js +321 -0
  18. package/dist/lib/version.js +8 -0
  19. package/dist/octez.js-michel-codec.es6.js +5790 -0
  20. package/dist/octez.js-michel-codec.es6.js.map +1 -0
  21. package/dist/octez.js-michel-codec.umd.js +5854 -0
  22. package/dist/octez.js-michel-codec.umd.js.map +1 -0
  23. package/dist/types/base58.d.ts +13 -0
  24. package/dist/types/binary.d.ts +127 -0
  25. package/dist/types/errors.d.ts +57 -0
  26. package/dist/types/formatters.d.ts +6 -0
  27. package/dist/types/global-constants.d.ts +3 -0
  28. package/dist/types/macros.d.ts +13 -0
  29. package/dist/types/micheline-emitter.d.ts +17 -0
  30. package/dist/types/micheline-parser.d.ts +130 -0
  31. package/dist/types/micheline.d.ts +44 -0
  32. package/dist/types/michelson-contract.d.ts +24 -0
  33. package/dist/types/michelson-typecheck.d.ts +38 -0
  34. package/dist/types/michelson-types.d.ts +147 -0
  35. package/dist/types/michelson-validator.d.ts +66 -0
  36. package/dist/types/octez.js-michel-codec.d.ts +16 -0
  37. package/dist/types/scan.d.ts +26 -0
  38. package/dist/types/utils.d.ts +77 -0
  39. package/dist/types/version.d.ts +4 -0
  40. package/package.json +94 -0
  41. package/signature.json +315 -0
@@ -0,0 +1,1272 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.packData = packData;
4
+ exports.packDataBytes = packDataBytes;
5
+ exports.unpackData = unpackData;
6
+ exports.unpackDataBytes = unpackDataBytes;
7
+ exports.decodeAddressBytes = decodeAddressBytes;
8
+ exports.decodePublicKeyHashBytes = decodePublicKeyHashBytes;
9
+ exports.decodePublicKeyBytes = decodePublicKeyBytes;
10
+ const michelson_validator_1 = require("./michelson-validator");
11
+ const utils_1 = require("./utils");
12
+ // The order is important!
13
+ // The position represent the encoding value.
14
+ const primitives = [
15
+ 'parameter',
16
+ 'storage',
17
+ 'code',
18
+ 'False',
19
+ 'Elt',
20
+ 'Left',
21
+ 'None',
22
+ 'Pair',
23
+ 'Right',
24
+ 'Some',
25
+ 'True',
26
+ 'Unit',
27
+ 'PACK',
28
+ 'UNPACK',
29
+ 'BLAKE2B',
30
+ 'SHA256',
31
+ 'SHA512',
32
+ 'ABS',
33
+ 'ADD',
34
+ 'AMOUNT',
35
+ 'AND',
36
+ 'BALANCE',
37
+ 'CAR',
38
+ 'CDR',
39
+ 'CHECK_SIGNATURE',
40
+ 'COMPARE',
41
+ 'CONCAT',
42
+ 'CONS',
43
+ 'CREATE_ACCOUNT',
44
+ 'CREATE_CONTRACT',
45
+ 'IMPLICIT_ACCOUNT',
46
+ 'DIP',
47
+ 'DROP',
48
+ 'DUP',
49
+ 'EDIV',
50
+ 'EMPTY_MAP',
51
+ 'EMPTY_SET',
52
+ 'EQ',
53
+ 'EXEC',
54
+ 'FAILWITH',
55
+ 'GE',
56
+ 'GET',
57
+ 'GT',
58
+ 'HASH_KEY',
59
+ 'IF',
60
+ 'IF_CONS',
61
+ 'IF_LEFT',
62
+ 'IF_NONE',
63
+ 'INT',
64
+ 'LAMBDA',
65
+ 'LE',
66
+ 'LEFT',
67
+ 'LOOP',
68
+ 'LSL',
69
+ 'LSR',
70
+ 'LT',
71
+ 'MAP',
72
+ 'MEM',
73
+ 'MUL',
74
+ 'NEG',
75
+ 'NEQ',
76
+ 'NIL',
77
+ 'NONE',
78
+ 'NOT',
79
+ 'NOW',
80
+ 'OR',
81
+ 'PAIR',
82
+ 'PUSH',
83
+ 'RIGHT',
84
+ 'SIZE',
85
+ 'SOME',
86
+ 'SOURCE',
87
+ 'SENDER',
88
+ 'SELF',
89
+ 'STEPS_TO_QUOTA',
90
+ 'SUB',
91
+ 'SWAP',
92
+ 'TRANSFER_TOKENS',
93
+ 'SET_DELEGATE',
94
+ 'UNIT',
95
+ 'UPDATE',
96
+ 'XOR',
97
+ 'ITER',
98
+ 'LOOP_LEFT',
99
+ 'ADDRESS',
100
+ 'CONTRACT',
101
+ 'ISNAT',
102
+ 'CAST',
103
+ 'RENAME',
104
+ 'bool',
105
+ 'contract',
106
+ 'int',
107
+ 'key',
108
+ 'key_hash',
109
+ 'lambda',
110
+ 'list',
111
+ 'map',
112
+ 'big_map',
113
+ 'nat',
114
+ 'option',
115
+ 'or',
116
+ 'pair',
117
+ 'set',
118
+ 'signature',
119
+ 'string',
120
+ 'bytes',
121
+ 'mutez',
122
+ 'timestamp',
123
+ 'unit',
124
+ 'operation',
125
+ 'address',
126
+ 'SLICE',
127
+ 'DIG',
128
+ 'DUG',
129
+ 'EMPTY_BIG_MAP',
130
+ 'APPLY',
131
+ 'chain_id',
132
+ 'CHAIN_ID',
133
+ 'LEVEL',
134
+ 'SELF_ADDRESS',
135
+ 'never',
136
+ 'NEVER',
137
+ 'UNPAIR',
138
+ 'VOTING_POWER',
139
+ 'TOTAL_VOTING_POWER',
140
+ 'KECCAK',
141
+ 'SHA3',
142
+ 'PAIRING_CHECK',
143
+ 'bls12_381_g1',
144
+ 'bls12_381_g2',
145
+ 'bls12_381_fr',
146
+ 'sapling_state',
147
+ 'sapling_transaction_deprecated',
148
+ 'SAPLING_EMPTY_STATE',
149
+ 'SAPLING_VERIFY_UPDATE',
150
+ 'ticket',
151
+ 'TICKET_DEPRECATED',
152
+ 'READ_TICKET',
153
+ 'SPLIT_TICKET',
154
+ 'JOIN_TICKETS',
155
+ 'GET_AND_UPDATE',
156
+ 'chest',
157
+ 'chest_key',
158
+ 'OPEN_CHEST',
159
+ 'VIEW',
160
+ 'view',
161
+ 'constant',
162
+ 'SUB_MUTEZ',
163
+ 'tx_rollup_l2_address',
164
+ 'MIN_BLOCK_TIME',
165
+ 'sapling_transaction',
166
+ 'EMIT',
167
+ 'Lambda_rec',
168
+ 'LAMBDA_REC',
169
+ 'TICKET',
170
+ 'BYTES',
171
+ 'NAT',
172
+ 'Ticket',
173
+ 'IS_IMPLICIT_ACCOUNT',
174
+ 'INDEX_ADDRESS',
175
+ 'GET_ADDRESS_INDEX',
176
+ ];
177
+ const primTags = Object.assign({}, ...primitives.map((v, i) => ({ [v]: i })));
178
+ var Tag;
179
+ (function (Tag) {
180
+ Tag[Tag["Int"] = 0] = "Int";
181
+ Tag[Tag["String"] = 1] = "String";
182
+ Tag[Tag["Sequence"] = 2] = "Sequence";
183
+ Tag[Tag["Prim0"] = 3] = "Prim0";
184
+ Tag[Tag["Prim0Annot"] = 4] = "Prim0Annot";
185
+ Tag[Tag["Prim1"] = 5] = "Prim1";
186
+ Tag[Tag["Prim1Annot"] = 6] = "Prim1Annot";
187
+ Tag[Tag["Prim2"] = 7] = "Prim2";
188
+ Tag[Tag["Prim2Annot"] = 8] = "Prim2Annot";
189
+ Tag[Tag["Prim"] = 9] = "Prim";
190
+ Tag[Tag["Bytes"] = 10] = "Bytes";
191
+ })(Tag || (Tag = {}));
192
+ class Writer {
193
+ constructor() {
194
+ this.buffer = [];
195
+ }
196
+ get length() {
197
+ return this.buffer.length;
198
+ }
199
+ writeBytes(val) {
200
+ this.buffer.push(...val.map((v) => v & 0xff));
201
+ }
202
+ writeUint8(val) {
203
+ const v = val | 0;
204
+ this.buffer.push(v & 0xff);
205
+ }
206
+ writeUint16(val) {
207
+ const v = val | 0;
208
+ this.buffer.push((v >> 8) & 0xff);
209
+ this.buffer.push(v & 0xff);
210
+ }
211
+ writeUint32(val) {
212
+ const v = val | 0;
213
+ this.buffer.push((v >> 24) & 0xff);
214
+ this.buffer.push((v >> 16) & 0xff);
215
+ this.buffer.push((v >> 8) & 0xff);
216
+ this.buffer.push(v & 0xff);
217
+ }
218
+ writeInt8(val) {
219
+ this.writeUint8(val);
220
+ }
221
+ writeInt16(val) {
222
+ this.writeUint16(val);
223
+ }
224
+ writeInt32(val) {
225
+ this.writeUint32(val);
226
+ }
227
+ }
228
+ const boundsErr = new Error('bounds out of range');
229
+ class Reader {
230
+ constructor(buffer, idx = 0, cap = buffer.length) {
231
+ this.buffer = buffer;
232
+ this.idx = idx;
233
+ this.cap = cap;
234
+ }
235
+ /** Remaining length */
236
+ get length() {
237
+ return this.cap - this.idx;
238
+ }
239
+ readBytes(len) {
240
+ if (this.cap - this.idx < len) {
241
+ throw boundsErr;
242
+ }
243
+ const ret = this.buffer.slice(this.idx, this.idx + len);
244
+ this.idx += len;
245
+ return ret;
246
+ }
247
+ reader(len) {
248
+ if (this.cap - this.idx < len) {
249
+ throw boundsErr;
250
+ }
251
+ const ret = new Reader(this.buffer, this.idx, this.idx + len);
252
+ this.idx += len;
253
+ return ret;
254
+ }
255
+ copy() {
256
+ return new Reader(this.buffer, this.idx, this.cap);
257
+ }
258
+ readUint8() {
259
+ if (this.cap - this.idx < 1) {
260
+ throw boundsErr;
261
+ }
262
+ return this.buffer[this.idx++] >>> 0;
263
+ }
264
+ readUint16() {
265
+ if (this.cap - this.idx < 2) {
266
+ throw boundsErr;
267
+ }
268
+ const x0 = this.buffer[this.idx++];
269
+ const x1 = this.buffer[this.idx++];
270
+ return ((x0 << 8) | x1) >>> 0;
271
+ }
272
+ readUint32() {
273
+ if (this.cap - this.idx < 4) {
274
+ throw boundsErr;
275
+ }
276
+ const x0 = this.buffer[this.idx++];
277
+ const x1 = this.buffer[this.idx++];
278
+ const x2 = this.buffer[this.idx++];
279
+ const x3 = this.buffer[this.idx++];
280
+ return ((x0 << 24) | (x1 << 16) | (x2 << 8) | x3) >>> 0;
281
+ }
282
+ readInt8() {
283
+ if (this.cap - this.idx < 1) {
284
+ throw boundsErr;
285
+ }
286
+ const x = this.buffer[this.idx++];
287
+ return (x << 24) >> 24;
288
+ }
289
+ readInt16() {
290
+ if (this.cap - this.idx < 2) {
291
+ throw boundsErr;
292
+ }
293
+ const x0 = this.buffer[this.idx++];
294
+ const x1 = this.buffer[this.idx++];
295
+ return (((x0 << 8) | x1) << 16) >> 16;
296
+ }
297
+ readInt32() {
298
+ if (this.cap - this.idx < 4) {
299
+ throw boundsErr;
300
+ }
301
+ const x0 = this.buffer[this.idx++];
302
+ const x1 = this.buffer[this.idx++];
303
+ const x2 = this.buffer[this.idx++];
304
+ const x3 = this.buffer[this.idx++];
305
+ return (x0 << 24) | (x1 << 16) | (x2 << 8) | x3;
306
+ }
307
+ }
308
+ var ContractID;
309
+ (function (ContractID) {
310
+ ContractID[ContractID["Implicit"] = 0] = "Implicit";
311
+ ContractID[ContractID["Originated"] = 1] = "Originated";
312
+ })(ContractID || (ContractID = {}));
313
+ var PublicKeyHashID;
314
+ (function (PublicKeyHashID) {
315
+ PublicKeyHashID[PublicKeyHashID["ED25519"] = 0] = "ED25519";
316
+ PublicKeyHashID[PublicKeyHashID["SECP256K1"] = 1] = "SECP256K1";
317
+ PublicKeyHashID[PublicKeyHashID["P256"] = 2] = "P256";
318
+ })(PublicKeyHashID || (PublicKeyHashID = {}));
319
+ function readPublicKeyHash(rd) {
320
+ let type;
321
+ const tag = rd.readUint8();
322
+ switch (tag) {
323
+ case PublicKeyHashID.ED25519:
324
+ type = 'ED25519PublicKeyHash';
325
+ break;
326
+ case PublicKeyHashID.SECP256K1:
327
+ type = 'SECP256K1PublicKeyHash';
328
+ break;
329
+ case PublicKeyHashID.P256:
330
+ type = 'P256PublicKeyHash';
331
+ break;
332
+ default:
333
+ throw new Error(`unknown public key hash tag: ${tag}`);
334
+ }
335
+ return { type, hash: rd.readBytes(20) };
336
+ }
337
+ function readAddress(rd) {
338
+ let address;
339
+ const tag = rd.readUint8();
340
+ switch (tag) {
341
+ case ContractID.Implicit:
342
+ address = readPublicKeyHash(rd);
343
+ break;
344
+ case ContractID.Originated:
345
+ address = {
346
+ type: 'ContractHash',
347
+ hash: rd.readBytes(20),
348
+ };
349
+ rd.readBytes(1);
350
+ break;
351
+ default:
352
+ throw new Error(`unknown address tag: ${tag}`);
353
+ }
354
+ if (rd.length !== 0) {
355
+ // entry point
356
+ const dec = new TextDecoder();
357
+ address.entryPoint = dec.decode(new Uint8Array(rd.readBytes(rd.length)));
358
+ }
359
+ return address;
360
+ }
361
+ function writePublicKeyHash(a, w) {
362
+ let tag;
363
+ switch (a.type) {
364
+ case 'ED25519PublicKeyHash':
365
+ tag = PublicKeyHashID.ED25519;
366
+ break;
367
+ case 'SECP256K1PublicKeyHash':
368
+ tag = PublicKeyHashID.SECP256K1;
369
+ break;
370
+ case 'P256PublicKeyHash':
371
+ tag = PublicKeyHashID.P256;
372
+ break;
373
+ default:
374
+ throw new Error(`unexpected address type: ${a.type}`);
375
+ }
376
+ w.writeUint8(tag);
377
+ w.writeBytes(Array.from(a.hash));
378
+ }
379
+ function writeAddress(a, w) {
380
+ if (a.type === 'ContractHash') {
381
+ w.writeUint8(ContractID.Originated);
382
+ w.writeBytes(Array.from(a.hash));
383
+ w.writeUint8(0);
384
+ }
385
+ else {
386
+ w.writeUint8(ContractID.Implicit);
387
+ writePublicKeyHash(a, w);
388
+ }
389
+ if (a.entryPoint !== undefined && a.entryPoint !== '' && a.entryPoint !== 'default') {
390
+ const enc = new TextEncoder();
391
+ const bytes = enc.encode(a.entryPoint);
392
+ w.writeBytes(Array.from(bytes));
393
+ }
394
+ }
395
+ var PublicKeyID;
396
+ (function (PublicKeyID) {
397
+ PublicKeyID[PublicKeyID["ED25519"] = 0] = "ED25519";
398
+ PublicKeyID[PublicKeyID["SECP256K1"] = 1] = "SECP256K1";
399
+ PublicKeyID[PublicKeyID["P256"] = 2] = "P256";
400
+ })(PublicKeyID || (PublicKeyID = {}));
401
+ function readPublicKey(rd) {
402
+ let ln;
403
+ let type;
404
+ const tag = rd.readUint8();
405
+ switch (tag) {
406
+ case PublicKeyID.ED25519:
407
+ type = 'ED25519PublicKey';
408
+ ln = 32;
409
+ break;
410
+ case PublicKeyID.SECP256K1:
411
+ type = 'SECP256K1PublicKey';
412
+ ln = 33;
413
+ break;
414
+ case PublicKeyID.P256:
415
+ type = 'P256PublicKey';
416
+ ln = 33;
417
+ break;
418
+ default:
419
+ throw new Error(`unknown public key tag: ${tag}`);
420
+ }
421
+ return { type, publicKey: rd.readBytes(ln) };
422
+ }
423
+ function writePublicKey(pk, w) {
424
+ let tag;
425
+ switch (pk.type) {
426
+ case 'ED25519PublicKey':
427
+ tag = PublicKeyID.ED25519;
428
+ break;
429
+ case 'SECP256K1PublicKey':
430
+ tag = PublicKeyID.SECP256K1;
431
+ break;
432
+ case 'P256PublicKey':
433
+ tag = PublicKeyID.P256;
434
+ break;
435
+ default:
436
+ throw new Error(`unexpected public key type: ${pk.type}`);
437
+ }
438
+ w.writeUint8(tag);
439
+ w.writeBytes(Array.from(pk.publicKey));
440
+ }
441
+ function writeExpr(expr, wr, tf) {
442
+ var _a, _b;
443
+ const [e, args] = tf(expr);
444
+ if (Array.isArray(e)) {
445
+ const w = new Writer();
446
+ for (const v of e) {
447
+ const a = args.next();
448
+ if (a.done) {
449
+ throw new Error('REPORT ME: iterator is done');
450
+ }
451
+ writeExpr(v, w, a.value);
452
+ }
453
+ wr.writeUint8(Tag.Sequence);
454
+ wr.writeUint32(w.length);
455
+ wr.writeBytes(w.buffer);
456
+ return;
457
+ }
458
+ if ('string' in e) {
459
+ const enc = new TextEncoder();
460
+ const bytes = enc.encode(e.string);
461
+ wr.writeUint8(Tag.String);
462
+ wr.writeUint32(bytes.length);
463
+ wr.writeBytes(Array.from(bytes));
464
+ return;
465
+ }
466
+ if ('int' in e) {
467
+ wr.writeUint8(Tag.Int);
468
+ let val = BigInt(e.int);
469
+ const sign = val < 0;
470
+ if (sign) {
471
+ val = -val;
472
+ }
473
+ let i = 0;
474
+ do {
475
+ const bits = i === 0 ? BigInt(6) : BigInt(7);
476
+ let byte = val & ((BigInt(1) << bits) - BigInt(1));
477
+ val >>= bits;
478
+ if (val) {
479
+ byte |= BigInt(0x80);
480
+ }
481
+ if (i === 0 && sign) {
482
+ byte |= BigInt(0x40);
483
+ }
484
+ wr.writeUint8(Number(byte));
485
+ i++;
486
+ } while (val);
487
+ return;
488
+ }
489
+ if ('bytes' in e) {
490
+ const bytes = (0, utils_1.parseHex)(e.bytes);
491
+ wr.writeUint8(Tag.Bytes);
492
+ wr.writeUint32(bytes.length);
493
+ wr.writeBytes(bytes);
494
+ return;
495
+ }
496
+ const prim = primTags[e.prim];
497
+ if (prim === undefined) {
498
+ throw new TypeError(`Can't encode primary: ${e.prim}`);
499
+ }
500
+ const tag = (((_a = e.args) === null || _a === void 0 ? void 0 : _a.length) || 0) < 3
501
+ ? Tag.Prim0 +
502
+ (((_b = e.args) === null || _b === void 0 ? void 0 : _b.length) || 0) * 2 +
503
+ (e.annots === undefined || e.annots.length === 0 ? 0 : 1)
504
+ : Tag.Prim;
505
+ wr.writeUint8(tag);
506
+ wr.writeUint8(prim);
507
+ if (e.args !== undefined) {
508
+ if (e.args.length < 3) {
509
+ for (const v of e.args) {
510
+ const a = args.next();
511
+ if (a.done) {
512
+ throw new Error('REPORT ME: iterator is done');
513
+ }
514
+ writeExpr(v, wr, a.value);
515
+ }
516
+ }
517
+ else {
518
+ const w = new Writer();
519
+ for (const v of e.args) {
520
+ const a = args.next();
521
+ if (a.done) {
522
+ throw new Error('REPORT ME: iterator is done');
523
+ }
524
+ writeExpr(v, w, a.value);
525
+ }
526
+ wr.writeUint32(w.length);
527
+ wr.writeBytes(w.buffer);
528
+ }
529
+ }
530
+ if (e.annots !== undefined && e.annots.length !== 0) {
531
+ const enc = new TextEncoder();
532
+ const bytes = enc.encode(e.annots.join(' '));
533
+ wr.writeUint32(bytes.length);
534
+ wr.writeBytes(Array.from(bytes));
535
+ }
536
+ else if (e.args !== undefined && e.args.length >= 3) {
537
+ wr.writeUint32(0);
538
+ }
539
+ }
540
+ function readExpr(rd, tf) {
541
+ function* passThrough() {
542
+ while (true) {
543
+ yield readPassThrough;
544
+ }
545
+ }
546
+ const [args, tr] = tf;
547
+ const tag = rd.readUint8();
548
+ switch (tag) {
549
+ case Tag.Int: {
550
+ const buf = [];
551
+ let byte;
552
+ do {
553
+ byte = rd.readInt8();
554
+ buf.push(byte);
555
+ } while ((byte & 0x80) !== 0);
556
+ let val = BigInt(0);
557
+ let sign = false;
558
+ for (let i = buf.length - 1; i >= 0; i--) {
559
+ const bits = i === 0 ? BigInt(6) : BigInt(7);
560
+ const byte = BigInt(buf[i]);
561
+ val <<= bits;
562
+ val |= byte & ((BigInt(1) << bits) - BigInt(1));
563
+ if (i === 0) {
564
+ sign = !!(byte & BigInt(0x40));
565
+ }
566
+ }
567
+ if (sign) {
568
+ val = -val;
569
+ }
570
+ return tr({ int: String(val) });
571
+ }
572
+ case Tag.String: {
573
+ const length = rd.readUint32();
574
+ const bytes = rd.readBytes(length);
575
+ const dec = new TextDecoder();
576
+ return tr({ string: dec.decode(new Uint8Array(bytes)) });
577
+ }
578
+ case Tag.Bytes: {
579
+ const length = rd.readUint32();
580
+ const bytes = rd.readBytes(length);
581
+ const hex = (0, utils_1.hexBytes)(Array.from(bytes));
582
+ return tr({ bytes: hex });
583
+ }
584
+ case Tag.Sequence: {
585
+ const length = rd.readUint32();
586
+ let res = [];
587
+ let savedrd = rd.copy();
588
+ // make two passes
589
+ let it = passThrough();
590
+ for (let n = 0; n < 2; n++) {
591
+ const r = savedrd.reader(length);
592
+ res = [];
593
+ while (r.length > 0) {
594
+ const a = it.next();
595
+ if (a.done) {
596
+ throw new Error('REPORT ME: iterator is done');
597
+ }
598
+ res.push(readExpr(r, a.value));
599
+ }
600
+ // make a second pass with injected side effects
601
+ it = args(res);
602
+ savedrd = rd;
603
+ }
604
+ return tr(res);
605
+ }
606
+ default: {
607
+ if (tag > 9) {
608
+ throw new Error(`Unknown tag: ${tag}`);
609
+ }
610
+ const p = rd.readUint8();
611
+ if (p >= primitives.length) {
612
+ throw new Error(`Unknown primitive tag: ${p}`);
613
+ }
614
+ const prim = primitives[p];
615
+ const argn = (tag - 3) >> 1;
616
+ let res = { prim };
617
+ // make two passes
618
+ let it = passThrough();
619
+ let savedrd = rd.copy();
620
+ for (let n = 0; n < 2; n++) {
621
+ res = { prim };
622
+ if (argn < 3) {
623
+ for (let i = 0; i < argn; i++) {
624
+ const a = it.next();
625
+ if (a.done) {
626
+ throw new Error('REPORT ME: iterator is done');
627
+ }
628
+ res.args = res.args || [];
629
+ res.args.push(readExpr(savedrd, a.value));
630
+ }
631
+ }
632
+ else {
633
+ res.args = res.args || [];
634
+ const length = savedrd.readUint32();
635
+ const r = savedrd.reader(length);
636
+ while (r.length > 0) {
637
+ const a = it.next();
638
+ if (a.done) {
639
+ throw new Error('REPORT ME: iterator is done');
640
+ }
641
+ res.args.push(readExpr(r, a.value));
642
+ }
643
+ }
644
+ // make a second pass with injected side effects
645
+ it = args(res);
646
+ savedrd = rd;
647
+ }
648
+ if (((tag - 3) & 1) === 1 || argn === 3) {
649
+ // read annotations
650
+ const length = rd.readUint32();
651
+ if (length !== 0) {
652
+ const bytes = rd.readBytes(length);
653
+ const dec = new TextDecoder();
654
+ res.annots = dec.decode(new Uint8Array(bytes)).split(' ');
655
+ }
656
+ }
657
+ return tr(res);
658
+ }
659
+ }
660
+ }
661
+ const isOrData = (e) => 'prim' in e && (e.prim === 'Left' || e.prim === 'Right');
662
+ const isOptionData = (e) => 'prim' in e && (e.prim === 'Some' || e.prim === 'None');
663
+ const getWriteTransformFunc = (t) => {
664
+ if ((0, utils_1.isPairType)(t)) {
665
+ return (d) => {
666
+ if (!(0, utils_1.isPairData)(d)) {
667
+ throw new utils_1.MichelsonTypeError(t, `pair expected: ${JSON.stringify(d)}`, d);
668
+ }
669
+ (0, michelson_validator_1.assertDataListIfAny)(d);
670
+ // combs aren't used in pack format
671
+ const tc = (0, utils_1.unpackComb)('pair', t);
672
+ const dc = (0, utils_1.unpackComb)('Pair', d);
673
+ return [
674
+ dc,
675
+ (function* () {
676
+ for (const a of tc.args) {
677
+ yield getWriteTransformFunc(a);
678
+ }
679
+ })(),
680
+ ];
681
+ };
682
+ }
683
+ switch (t.prim) {
684
+ case 'or':
685
+ return (d) => {
686
+ if (!isOrData(d)) {
687
+ throw new utils_1.MichelsonTypeError(t, `or expected: ${JSON.stringify(d)}`, d);
688
+ }
689
+ return [
690
+ d,
691
+ (function* () {
692
+ yield getWriteTransformFunc(t.args[d.prim === 'Left' ? 0 : 1]);
693
+ })(),
694
+ ];
695
+ };
696
+ case 'option':
697
+ return (d) => {
698
+ if (!isOptionData(d)) {
699
+ throw new utils_1.MichelsonTypeError(t, `option expected: ${JSON.stringify(d)}`, d);
700
+ }
701
+ return [
702
+ d,
703
+ (function* () {
704
+ const dd = d;
705
+ // TODO: refactor and remove ts-ignore
706
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
707
+ // @ts-ignore
708
+ if (dd.prim === 'Some') {
709
+ yield getWriteTransformFunc(t.args[0]);
710
+ }
711
+ })(),
712
+ ];
713
+ };
714
+ case 'list':
715
+ case 'set':
716
+ return (d) => {
717
+ if (!Array.isArray(d)) {
718
+ throw new utils_1.MichelsonTypeError(t, `${t.prim} expected: ${JSON.stringify(d)}`, d);
719
+ }
720
+ return [
721
+ d,
722
+ (function* () {
723
+ for (const _v of d) {
724
+ yield getWriteTransformFunc(t.args[0]);
725
+ }
726
+ })(),
727
+ ];
728
+ };
729
+ case 'map':
730
+ return (d) => {
731
+ if (!Array.isArray(d)) {
732
+ throw new utils_1.MichelsonTypeError(t, `map expected: ${JSON.stringify(d)}`, d);
733
+ }
734
+ return [
735
+ d,
736
+ (function* () {
737
+ for (const _elt of d) {
738
+ yield (elt) => {
739
+ if (!('prim' in elt) || elt.prim !== 'Elt') {
740
+ throw new utils_1.MichelsonTypeError(t, `map element expected: ${JSON.stringify(elt)}`, elt);
741
+ }
742
+ return [
743
+ elt,
744
+ (function* () {
745
+ for (const a of t.args) {
746
+ yield getWriteTransformFunc(a);
747
+ }
748
+ })(),
749
+ ];
750
+ };
751
+ }
752
+ })(),
753
+ ];
754
+ };
755
+ case 'chain_id':
756
+ return (d) => {
757
+ if (!('bytes' in d) && !('string' in d)) {
758
+ throw new utils_1.MichelsonTypeError(t, `chain id expected: ${JSON.stringify(d)}`, d);
759
+ }
760
+ let bytes;
761
+ if ('string' in d) {
762
+ const id = (0, utils_1.checkDecodeTezosID)(d.string, 'ChainID');
763
+ if (id === null) {
764
+ throw new utils_1.MichelsonTypeError(t, `chain id base58 expected: ${d.string}`, d);
765
+ }
766
+ bytes = { bytes: (0, utils_1.hexBytes)(id[1]) };
767
+ }
768
+ else {
769
+ bytes = d;
770
+ }
771
+ return [bytes, [][Symbol.iterator]()];
772
+ };
773
+ case 'signature':
774
+ return (d) => {
775
+ if (!('bytes' in d) && !('string' in d)) {
776
+ throw new utils_1.MichelsonTypeError(t, `signature expected: ${JSON.stringify(d)}`, d);
777
+ }
778
+ let bytes;
779
+ if ('string' in d) {
780
+ const sig = (0, utils_1.checkDecodeTezosID)(d.string, 'ED25519Signature', 'SECP256K1Signature', 'P256Signature', 'GenericSignature');
781
+ if (sig === null) {
782
+ throw new utils_1.MichelsonTypeError(t, `signature base58 expected: ${d.string}`, d);
783
+ }
784
+ bytes = { bytes: (0, utils_1.hexBytes)(sig[1]) };
785
+ }
786
+ else {
787
+ bytes = d;
788
+ }
789
+ return [bytes, [][Symbol.iterator]()];
790
+ };
791
+ case 'key_hash':
792
+ return (d) => {
793
+ if (!('bytes' in d) && !('string' in d)) {
794
+ throw new utils_1.MichelsonTypeError(t, `key hash expected: ${JSON.stringify(d)}`, d);
795
+ }
796
+ let bytes;
797
+ if ('string' in d) {
798
+ const pkh = (0, utils_1.checkDecodeTezosID)(d.string, 'ED25519PublicKeyHash', 'SECP256K1PublicKeyHash', 'P256PublicKeyHash');
799
+ if (pkh === null) {
800
+ throw new utils_1.MichelsonTypeError(t, `key hash base58 expected: ${d.string}`, d);
801
+ }
802
+ const w = new Writer();
803
+ writePublicKeyHash({ type: pkh[0], hash: pkh[1] }, w);
804
+ bytes = { bytes: (0, utils_1.hexBytes)(w.buffer) };
805
+ }
806
+ else {
807
+ bytes = d;
808
+ }
809
+ return [bytes, [][Symbol.iterator]()];
810
+ };
811
+ case 'key':
812
+ return (d) => {
813
+ if (!('bytes' in d) && !('string' in d)) {
814
+ throw new utils_1.MichelsonTypeError(t, `public key expected: ${JSON.stringify(d)}`, d);
815
+ }
816
+ let bytes;
817
+ if ('string' in d) {
818
+ const key = (0, utils_1.checkDecodeTezosID)(d.string, 'ED25519PublicKey', 'SECP256K1PublicKey', 'P256PublicKey');
819
+ if (key === null) {
820
+ throw new utils_1.MichelsonTypeError(t, `public key base58 expected: ${d.string}`, d);
821
+ }
822
+ const w = new Writer();
823
+ writePublicKey({ type: key[0], publicKey: key[1] }, w);
824
+ bytes = { bytes: (0, utils_1.hexBytes)(w.buffer) };
825
+ }
826
+ else {
827
+ bytes = d;
828
+ }
829
+ return [bytes, [][Symbol.iterator]()];
830
+ };
831
+ case 'address':
832
+ return (d) => {
833
+ if (!('bytes' in d) && !('string' in d)) {
834
+ throw new utils_1.MichelsonTypeError(t, `address expected: ${JSON.stringify(d)}`, d);
835
+ }
836
+ let bytes;
837
+ if ('string' in d) {
838
+ const s = d.string.split('%');
839
+ const address = (0, utils_1.checkDecodeTezosID)(s[0], 'ED25519PublicKeyHash', 'SECP256K1PublicKeyHash', 'P256PublicKeyHash', 'ContractHash');
840
+ if (address === null) {
841
+ throw new utils_1.MichelsonTypeError(t, `address base58 expected: ${d.string}`, d);
842
+ }
843
+ const w = new Writer();
844
+ writeAddress({ type: address[0], hash: address[1], entryPoint: s.length > 1 ? s[1] : undefined }, w);
845
+ bytes = { bytes: (0, utils_1.hexBytes)(w.buffer) };
846
+ }
847
+ else {
848
+ bytes = d;
849
+ }
850
+ return [bytes, [][Symbol.iterator]()];
851
+ };
852
+ case 'timestamp':
853
+ return (d) => {
854
+ if (!('string' in d) && !('int' in d)) {
855
+ throw new utils_1.MichelsonTypeError(t, `timestamp expected: ${JSON.stringify(d)}`, d);
856
+ }
857
+ let int;
858
+ if ('string' in d) {
859
+ const p = (0, utils_1.parseDate)(d);
860
+ if (p === null) {
861
+ throw new utils_1.MichelsonTypeError(t, `can't parse date: ${d.string}`, d);
862
+ }
863
+ int = { int: String(Math.floor(p.getTime() / 1000)) };
864
+ }
865
+ else {
866
+ int = d;
867
+ }
868
+ return [int, [][Symbol.iterator]()];
869
+ };
870
+ default:
871
+ return writePassThrough;
872
+ }
873
+ };
874
+ const isPushInstruction = (e) => 'prim' in e && e.prim === 'PUSH';
875
+ const writePassThrough = (e) => {
876
+ if (isPushInstruction(e)) {
877
+ (0, michelson_validator_1.assertMichelsonInstruction)(e);
878
+ // capture inlined type definition
879
+ return [
880
+ e,
881
+ (function* () {
882
+ yield writePassThrough;
883
+ yield getWriteTransformFunc(e.args[0]);
884
+ })(),
885
+ ];
886
+ }
887
+ return [
888
+ e,
889
+ (function* () {
890
+ while (true) {
891
+ yield writePassThrough;
892
+ }
893
+ })(),
894
+ ];
895
+ };
896
+ /**
897
+ * Serializes any value of packable type to its optimized binary representation
898
+ * identical to the one used by PACK and UNPACK Michelson instructions.
899
+ * Without a type definition (not recommended) the data will be encoded as a binary form of a generic Michelson expression.
900
+ * Type definition allows some types like `timestamp` and `address` and other base58 representable types to be encoded to
901
+ * corresponding optimized binary forms borrowed from the Tezos protocol
902
+ *
903
+ * ```typescript
904
+ * const data: MichelsonData = {
905
+ * string: "KT1RvkwF4F7pz1gCoxkyZrG1RkrxQy3gmFTv%foo"
906
+ * };
907
+ *
908
+ * const typ: MichelsonType = {
909
+ * prim: "address"
910
+ * };
911
+ *
912
+ * const packed = packData(data, typ);
913
+ *
914
+ * // 050a0000001901be41ee922ddd2cf33201e49d32da0afec571dce300666f6f
915
+ * ```
916
+ *
917
+ * Without a type definition the base58 encoded address will be treated as a string
918
+ * ```typescript
919
+ * const data: MichelsonData = {
920
+ * string: "KT1RvkwF4F7pz1gCoxkyZrG1RkrxQy3gmFTv%foo"
921
+ * };
922
+ *
923
+ * const packed = packData(data);
924
+ *
925
+ * // 0501000000284b543152766b7746344637707a3167436f786b795a724731526b7278517933676d46547625666f6f
926
+ * ```
927
+ * @param d Data object
928
+ * @param t Optional type definition
929
+ * @returns Binary representation as numeric array
930
+ */
931
+ function packData(d, t) {
932
+ const w = new Writer();
933
+ w.writeUint8(5);
934
+ writeExpr(d, w, t !== undefined ? getWriteTransformFunc(t) : writePassThrough);
935
+ return w.buffer;
936
+ }
937
+ /**
938
+ * Serializes any value of packable type to its optimized binary representation
939
+ * identical to the one used by PACK and UNPACK Michelson instructions.
940
+ * Same as {@link packData} but returns a `bytes` Michelson data literal instead of an array
941
+ *
942
+ * ```typescript
943
+ * const data: MichelsonData = {
944
+ * string: "2019-09-26T10:59:51Z"
945
+ * };
946
+ *
947
+ * const typ: MichelsonType = {
948
+ * prim: "timestamp"
949
+ * };
950
+ *
951
+ * const packed = packDataBytes(data, typ);
952
+ *
953
+ * // { bytes: "0500a7e8e4d80b" }
954
+ * ```
955
+ * @param d Data object
956
+ * @param t Optional type definition
957
+ * @returns Binary representation as a bytes literal
958
+ */
959
+ function packDataBytes(d, t) {
960
+ return { bytes: (0, utils_1.hexBytes)(packData(d, t)) };
961
+ }
962
+ const getReadTransformFuncs = (t) => {
963
+ if ((0, utils_1.isPairType)(t)) {
964
+ return [
965
+ (d) => {
966
+ if (!(0, utils_1.isPairData)(d)) {
967
+ throw new utils_1.MichelsonTypeError(t, `pair expected: ${JSON.stringify(d)}`, d);
968
+ }
969
+ const tc = (0, utils_1.unpackComb)('pair', t);
970
+ return (function* () {
971
+ for (const a of tc.args) {
972
+ yield getReadTransformFuncs(a);
973
+ }
974
+ })();
975
+ },
976
+ (d) => d,
977
+ ];
978
+ }
979
+ switch (t.prim) {
980
+ case 'or':
981
+ return [
982
+ (d) => {
983
+ if (!isOrData(d)) {
984
+ throw new utils_1.MichelsonTypeError(t, `or expected: ${JSON.stringify(d)}`, d);
985
+ }
986
+ return (function* () {
987
+ yield getReadTransformFuncs(t.args[d.prim === 'Left' ? 0 : 1]);
988
+ })();
989
+ },
990
+ (d) => d,
991
+ ];
992
+ case 'option':
993
+ return [
994
+ (d) => {
995
+ if (!isOptionData(d)) {
996
+ throw new utils_1.MichelsonTypeError(t, `option expected: ${JSON.stringify(d)}`, d);
997
+ }
998
+ return (function* () {
999
+ // TODO: refactor and remove ts-ignore
1000
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1001
+ // @ts-ignore
1002
+ if (d.prim === 'Some') {
1003
+ yield getReadTransformFuncs(t.args[0]);
1004
+ }
1005
+ })();
1006
+ },
1007
+ (d) => d,
1008
+ ];
1009
+ case 'list':
1010
+ case 'set':
1011
+ return [
1012
+ (d) => {
1013
+ if (!Array.isArray(d)) {
1014
+ throw new utils_1.MichelsonTypeError(t, `${t.prim} expected: ${JSON.stringify(d)}`, d);
1015
+ }
1016
+ return (function* () {
1017
+ while (true) {
1018
+ yield getReadTransformFuncs(t.args[0]);
1019
+ }
1020
+ })();
1021
+ },
1022
+ (d) => d,
1023
+ ];
1024
+ case 'map':
1025
+ return [
1026
+ (d) => {
1027
+ if (!Array.isArray(d)) {
1028
+ throw new utils_1.MichelsonTypeError(t, `map expected: ${JSON.stringify(d)}`, d);
1029
+ }
1030
+ return (function* () {
1031
+ while (true) {
1032
+ yield [
1033
+ (elt) => {
1034
+ if (!('prim' in elt) || elt.prim !== 'Elt') {
1035
+ throw new utils_1.MichelsonTypeError(t, `map element expected: ${JSON.stringify(elt)}`, elt);
1036
+ }
1037
+ return (function* () {
1038
+ for (const a of t.args) {
1039
+ yield getReadTransformFuncs(a);
1040
+ }
1041
+ })();
1042
+ },
1043
+ (elt) => elt,
1044
+ ];
1045
+ }
1046
+ })();
1047
+ },
1048
+ (d) => d,
1049
+ ];
1050
+ case 'chain_id':
1051
+ return [
1052
+ () => [][Symbol.iterator](),
1053
+ (d) => {
1054
+ if (!('bytes' in d) && !('string' in d)) {
1055
+ throw new utils_1.MichelsonTypeError(t, `chain id expected: ${JSON.stringify(d)}`, d);
1056
+ }
1057
+ if ('string' in d) {
1058
+ return d;
1059
+ }
1060
+ const bytes = (0, utils_1.parseBytes)(d.bytes);
1061
+ if (bytes === null) {
1062
+ throw new utils_1.MichelsonTypeError(t, `can't parse bytes: ${d.bytes}`, d);
1063
+ }
1064
+ return { string: (0, utils_1.encodeTezosID)('ChainID', bytes) };
1065
+ },
1066
+ ];
1067
+ case 'signature':
1068
+ return [
1069
+ () => [][Symbol.iterator](),
1070
+ (d) => {
1071
+ if (!('bytes' in d) && !('string' in d)) {
1072
+ throw new utils_1.MichelsonTypeError(t, `signature expected: ${JSON.stringify(d)}`, d);
1073
+ }
1074
+ if ('string' in d) {
1075
+ return d;
1076
+ }
1077
+ const bytes = (0, utils_1.parseBytes)(d.bytes);
1078
+ if (bytes === null) {
1079
+ throw new utils_1.MichelsonTypeError(t, `can't parse bytes: ${d.bytes}`, d);
1080
+ }
1081
+ return { string: (0, utils_1.encodeTezosID)('GenericSignature', bytes) };
1082
+ },
1083
+ ];
1084
+ case 'key_hash':
1085
+ return [
1086
+ () => [][Symbol.iterator](),
1087
+ (d) => {
1088
+ if (!('bytes' in d) && !('string' in d)) {
1089
+ throw new utils_1.MichelsonTypeError(t, `key hash expected: ${JSON.stringify(d)}`, d);
1090
+ }
1091
+ if ('string' in d) {
1092
+ return d;
1093
+ }
1094
+ const bytes = (0, utils_1.parseBytes)(d.bytes);
1095
+ if (bytes === null) {
1096
+ throw new utils_1.MichelsonTypeError(t, `can't parse bytes: ${d.bytes}`, d);
1097
+ }
1098
+ const rd = new Reader(new Uint8Array(bytes));
1099
+ const addr = readPublicKeyHash(rd);
1100
+ return {
1101
+ string: (0, utils_1.encodeTezosID)(addr.type, addr.hash) + (addr.entryPoint ? '%' + addr.entryPoint : ''),
1102
+ };
1103
+ },
1104
+ ];
1105
+ case 'key':
1106
+ return [
1107
+ () => [][Symbol.iterator](),
1108
+ (d) => {
1109
+ if (!('bytes' in d) && !('string' in d)) {
1110
+ throw new utils_1.MichelsonTypeError(t, `public key expected: ${JSON.stringify(d)}`, d);
1111
+ }
1112
+ if ('string' in d) {
1113
+ return d;
1114
+ }
1115
+ const bytes = (0, utils_1.parseBytes)(d.bytes);
1116
+ if (bytes === null) {
1117
+ throw new utils_1.MichelsonTypeError(t, `can't parse bytes: ${d.bytes}`, d);
1118
+ }
1119
+ const rd = new Reader(new Uint8Array(bytes));
1120
+ const pk = readPublicKey(rd);
1121
+ return { string: (0, utils_1.encodeTezosID)(pk.type, pk.publicKey) };
1122
+ },
1123
+ ];
1124
+ case 'address':
1125
+ return [
1126
+ () => [][Symbol.iterator](),
1127
+ (d) => {
1128
+ if (!('bytes' in d) && !('string' in d)) {
1129
+ throw new utils_1.MichelsonTypeError(t, `address expected: ${JSON.stringify(d)}`, d);
1130
+ }
1131
+ if ('string' in d) {
1132
+ return d;
1133
+ }
1134
+ const bytes = (0, utils_1.parseBytes)(d.bytes);
1135
+ if (bytes === null) {
1136
+ throw new utils_1.MichelsonTypeError(t, `can't parse bytes: ${d.bytes}`, d);
1137
+ }
1138
+ const rd = new Reader(new Uint8Array(bytes));
1139
+ const addr = readAddress(rd);
1140
+ return {
1141
+ string: (0, utils_1.encodeTezosID)(addr.type, addr.hash) + (addr.entryPoint ? '%' + addr.entryPoint : ''),
1142
+ };
1143
+ },
1144
+ ];
1145
+ case 'timestamp':
1146
+ return [
1147
+ () => [][Symbol.iterator](),
1148
+ (d) => {
1149
+ if (!('int' in d) && !('string' in d)) {
1150
+ throw new utils_1.MichelsonTypeError(t, `address expected: ${JSON.stringify(d)}`, d);
1151
+ }
1152
+ if ('string' in d) {
1153
+ return d;
1154
+ }
1155
+ const date = new Date(parseInt(d.int, 10) * 1000);
1156
+ return { string: date.toISOString().slice(0, 19) + 'Z' };
1157
+ },
1158
+ ];
1159
+ default:
1160
+ return readPassThrough;
1161
+ }
1162
+ };
1163
+ const readPassThrough = [
1164
+ (e) => {
1165
+ if (isPushInstruction(e)) {
1166
+ (0, michelson_validator_1.assertMichelsonInstruction)(e);
1167
+ // capture inlined type definition
1168
+ return (function* () {
1169
+ yield readPassThrough;
1170
+ yield getReadTransformFuncs(e.args[0]);
1171
+ })();
1172
+ }
1173
+ return (function* () {
1174
+ while (true) {
1175
+ yield readPassThrough;
1176
+ }
1177
+ })();
1178
+ },
1179
+ (e) => e,
1180
+ ];
1181
+ /**
1182
+ * Deserialize a byte array into the corresponding Michelson value.
1183
+ * Without a type definition (not recommended) the binary data will be treated as a binary form of a generic Michelson expression and returned as is.
1184
+ * Type definition allows some types like `timestamp` and `address` and other types usually encoded in optimized binary forms to be transformed
1185
+ * back to their string representations like base58 and ISO timestamps.
1186
+ *
1187
+ * ```typescript
1188
+ * const src = [0x05, 0x00, 0xa7, 0xe8, 0xe4, 0xd8, 0x0b];
1189
+ *
1190
+ * const typ: MichelsonType = {
1191
+ * prim: "timestamp"
1192
+ * };
1193
+ *
1194
+ * const data = unpackData(src, typ);
1195
+ *
1196
+ * // { string: "2019-09-26T10:59:51Z" }
1197
+ * ```
1198
+ *
1199
+ * Same binary data without a type definition
1200
+ * ```typescript
1201
+ * const src = [0x05, 0x00, 0xa7, 0xe8, 0xe4, 0xd8, 0x0b];
1202
+ *
1203
+ * const data = unpackData(src);
1204
+ *
1205
+ * // { int: "1569495591" }
1206
+ * ```
1207
+ * @param src Byte array
1208
+ * @param t Optional type definition
1209
+ * @returns Deserialized data
1210
+ */
1211
+ function unpackData(src, t) {
1212
+ const r = new Reader(src);
1213
+ if (r.readUint8() !== 5) {
1214
+ throw new Error('incorrect packed data magic number');
1215
+ }
1216
+ const ex = readExpr(r, t !== undefined ? getReadTransformFuncs(t) : readPassThrough);
1217
+ if ((0, michelson_validator_1.assertMichelsonData)(ex)) {
1218
+ return ex;
1219
+ }
1220
+ throw new Error(); // never
1221
+ }
1222
+ /**
1223
+ * Deserialize a byte array into the corresponding Michelson value.
1224
+ * Same as {@link unpackData} but takes a `bytes` Michelson data literal instead of an array
1225
+ *
1226
+ * ```typescript
1227
+ * const src = { bytes: "0500a7e8e4d80b" };
1228
+ *
1229
+ * const typ: MichelsonType = {
1230
+ * prim: "timestamp"
1231
+ * };
1232
+ *
1233
+ * const data = unpackDataBytes(src, typ);
1234
+ *
1235
+ * // { string: "2019-09-26T10:59:51Z" }
1236
+ * ```
1237
+ * @param src Bytes object
1238
+ * @param t Optional type definition
1239
+ * @returns Deserialized data
1240
+ */
1241
+ function unpackDataBytes(src, t) {
1242
+ const bytes = (0, utils_1.parseBytes)(src.bytes);
1243
+ if (bytes === null) {
1244
+ throw new Error(`can't parse bytes: "${src.bytes}"`);
1245
+ }
1246
+ return unpackData(bytes, t);
1247
+ }
1248
+ // helper functions also used by validator
1249
+ function decodeAddressBytes(b) {
1250
+ const bytes = (0, utils_1.parseBytes)(b.bytes);
1251
+ if (bytes === null) {
1252
+ throw new Error(`can't parse bytes: "${b.bytes}"`);
1253
+ }
1254
+ const rd = new Reader(new Uint8Array(bytes));
1255
+ return readAddress(rd);
1256
+ }
1257
+ function decodePublicKeyHashBytes(b) {
1258
+ const bytes = (0, utils_1.parseBytes)(b.bytes);
1259
+ if (bytes === null) {
1260
+ throw new Error(`can't parse bytes: "${b.bytes}"`);
1261
+ }
1262
+ const rd = new Reader(new Uint8Array(bytes));
1263
+ return readPublicKeyHash(rd);
1264
+ }
1265
+ function decodePublicKeyBytes(b) {
1266
+ const bytes = (0, utils_1.parseBytes)(b.bytes);
1267
+ if (bytes === null) {
1268
+ throw new Error(`can't parse bytes: "${b.bytes}"`);
1269
+ }
1270
+ const rd = new Reader(new Uint8Array(bytes));
1271
+ return readPublicKey(rd);
1272
+ }