@lightprotocol/compressed-token 0.1.2 → 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.
@@ -1,4404 +0,0 @@
1
- import { getIndexOrAdd, bn, padOutputStateMerkleTrees, useWallet, confirmConfig, defaultStaticAccountsStruct, toArray, LightSystemProgram, sumUpLamports, validateSufficientBalance, validateSameOwner, dedupeSigner, buildAndSignTx, sendAndConfirmTx, defaultTestStateTreeAccounts } from '@lightprotocol/stateless.js';
2
- import { utils, AnchorProvider, setProvider, Program } from '@coral-xyz/anchor';
3
- import { PublicKey, TransactionInstruction, Keypair, Connection, SystemProgram, ComputeBudgetProgram } from '@solana/web3.js';
4
- import require$$0, { Buffer as Buffer$1 } from 'buffer';
5
- import require$$0$2 from 'fs';
6
- import require$$0$1 from 'path';
7
-
8
- const IDL = {
9
- version: '0.3.0',
10
- name: 'light_compressed_token',
11
- constants: [
12
- {
13
- name: 'PROGRAM_ID',
14
- type: 'string',
15
- value: '"9sixVEthz2kMSKfeApZXHwuboT6DZuT6crAYJTciUCqE"',
16
- },
17
- ],
18
- instructions: [
19
- {
20
- name: 'createMint',
21
- docs: [
22
- 'This instruction expects a mint account to be created in a separate token program instruction',
23
- 'with token authority as mint authority.',
24
- 'This instruction creates a token pool account for that mint owned by token authority.',
25
- ],
26
- accounts: [
27
- {
28
- name: 'feePayer',
29
- isMut: true,
30
- isSigner: true,
31
- },
32
- {
33
- name: 'authority',
34
- isMut: true,
35
- isSigner: true,
36
- },
37
- {
38
- name: 'tokenPoolPda',
39
- isMut: true,
40
- isSigner: false,
41
- },
42
- {
43
- name: 'systemProgram',
44
- isMut: false,
45
- isSigner: false,
46
- },
47
- {
48
- name: 'mint',
49
- isMut: true,
50
- isSigner: false,
51
- },
52
- {
53
- name: 'mintAuthorityPda',
54
- isMut: true,
55
- isSigner: false,
56
- },
57
- {
58
- name: 'tokenProgram',
59
- isMut: false,
60
- isSigner: false,
61
- },
62
- {
63
- name: 'cpiAuthorityPda',
64
- isMut: false,
65
- isSigner: false,
66
- },
67
- ],
68
- args: [],
69
- },
70
- {
71
- name: 'mintTo',
72
- accounts: [
73
- {
74
- name: 'feePayer',
75
- isMut: true,
76
- isSigner: true,
77
- },
78
- {
79
- name: 'authority',
80
- isMut: true,
81
- isSigner: true,
82
- },
83
- {
84
- name: 'mintAuthorityPda',
85
- isMut: true,
86
- isSigner: false,
87
- },
88
- {
89
- name: 'mint',
90
- isMut: true,
91
- isSigner: false,
92
- },
93
- {
94
- name: 'tokenPoolPda',
95
- isMut: true,
96
- isSigner: false,
97
- },
98
- {
99
- name: 'tokenProgram',
100
- isMut: false,
101
- isSigner: false,
102
- },
103
- {
104
- name: 'compressedPdaProgram',
105
- isMut: false,
106
- isSigner: false,
107
- },
108
- {
109
- name: 'registeredProgramPda',
110
- isMut: true,
111
- isSigner: false,
112
- },
113
- {
114
- name: 'noopProgram',
115
- isMut: false,
116
- isSigner: false,
117
- },
118
- {
119
- name: 'accountCompressionAuthority',
120
- isMut: true,
121
- isSigner: false,
122
- },
123
- {
124
- name: 'accountCompressionProgram',
125
- isMut: false,
126
- isSigner: false,
127
- },
128
- {
129
- name: 'merkleTree',
130
- isMut: true,
131
- isSigner: false,
132
- },
133
- {
134
- name: 'selfProgram',
135
- isMut: false,
136
- isSigner: false,
137
- },
138
- ],
139
- args: [
140
- {
141
- name: 'publicKeys',
142
- type: {
143
- vec: 'publicKey',
144
- },
145
- },
146
- {
147
- name: 'amounts',
148
- type: {
149
- vec: 'u64',
150
- },
151
- },
152
- ],
153
- },
154
- {
155
- name: 'transfer',
156
- accounts: [
157
- {
158
- name: 'feePayer',
159
- isMut: false,
160
- isSigner: true,
161
- },
162
- {
163
- name: 'authority',
164
- isMut: false,
165
- isSigner: true,
166
- },
167
- {
168
- name: 'cpiAuthorityPda',
169
- isMut: false,
170
- isSigner: false,
171
- },
172
- {
173
- name: 'compressedPdaProgram',
174
- isMut: false,
175
- isSigner: false,
176
- },
177
- {
178
- name: 'registeredProgramPda',
179
- isMut: false,
180
- isSigner: false,
181
- },
182
- {
183
- name: 'noopProgram',
184
- isMut: false,
185
- isSigner: false,
186
- },
187
- {
188
- name: 'accountCompressionAuthority',
189
- isMut: false,
190
- isSigner: false,
191
- },
192
- {
193
- name: 'accountCompressionProgram',
194
- isMut: false,
195
- isSigner: false,
196
- },
197
- {
198
- name: 'selfProgram',
199
- isMut: false,
200
- isSigner: false,
201
- },
202
- {
203
- name: 'tokenPoolPda',
204
- isMut: true,
205
- isSigner: false,
206
- isOptional: true,
207
- },
208
- {
209
- name: 'decompressTokenAccount',
210
- isMut: true,
211
- isSigner: false,
212
- isOptional: true,
213
- },
214
- {
215
- name: 'tokenProgram',
216
- isMut: false,
217
- isSigner: false,
218
- isOptional: true,
219
- },
220
- ],
221
- args: [
222
- {
223
- name: 'inputs',
224
- type: 'bytes',
225
- },
226
- {
227
- name: 'cpiContext',
228
- type: {
229
- option: {
230
- defined: 'CompressedCpiContext',
231
- },
232
- },
233
- },
234
- ],
235
- },
236
- ],
237
- types: [
238
- {
239
- name: 'CompressedAccountWithMerkleContext',
240
- type: {
241
- kind: 'struct',
242
- fields: [
243
- {
244
- name: 'compressedAccount',
245
- type: {
246
- defined: 'CompressedAccount',
247
- },
248
- },
249
- {
250
- name: 'merkleTreePubkeyIndex',
251
- type: 'u8',
252
- },
253
- {
254
- name: 'nullifierQueuePubkeyIndex',
255
- type: 'u8',
256
- },
257
- {
258
- name: 'leafIndex',
259
- type: 'u32',
260
- },
261
- ],
262
- },
263
- },
264
- {
265
- name: 'MerkleContext',
266
- type: {
267
- kind: 'struct',
268
- fields: [
269
- {
270
- name: 'merkleTreePubkey',
271
- type: 'publicKey',
272
- },
273
- {
274
- name: 'nullifierQueuePubkey',
275
- type: 'publicKey',
276
- },
277
- {
278
- name: 'leafIndex',
279
- type: 'u32',
280
- },
281
- ],
282
- },
283
- },
284
- {
285
- name: 'PackedMerkleContext',
286
- type: {
287
- kind: 'struct',
288
- fields: [
289
- {
290
- name: 'merkleTreePubkeyIndex',
291
- type: 'u8',
292
- },
293
- {
294
- name: 'nullifierQueuePubkeyIndex',
295
- type: 'u8',
296
- },
297
- {
298
- name: 'leafIndex',
299
- type: 'u32',
300
- },
301
- ],
302
- },
303
- },
304
- {
305
- name: 'CompressedAccount',
306
- type: {
307
- kind: 'struct',
308
- fields: [
309
- {
310
- name: 'owner',
311
- type: 'publicKey',
312
- },
313
- {
314
- name: 'lamports',
315
- type: 'u64',
316
- },
317
- {
318
- name: 'address',
319
- type: {
320
- option: {
321
- array: ['u8', 32],
322
- },
323
- },
324
- },
325
- {
326
- name: 'data',
327
- type: {
328
- option: {
329
- defined: 'CompressedAccountData',
330
- },
331
- },
332
- },
333
- ],
334
- },
335
- },
336
- {
337
- name: 'CompressedAccountData',
338
- type: {
339
- kind: 'struct',
340
- fields: [
341
- {
342
- name: 'discriminator',
343
- type: {
344
- array: ['u8', 8],
345
- },
346
- },
347
- {
348
- name: 'data',
349
- type: 'bytes',
350
- },
351
- {
352
- name: 'dataHash',
353
- type: {
354
- array: ['u8', 32],
355
- },
356
- },
357
- ],
358
- },
359
- },
360
- {
361
- name: 'CompressedCpiContext',
362
- docs: ['To spend multiple compressed'],
363
- type: {
364
- kind: 'struct',
365
- fields: [
366
- {
367
- name: 'cpiSignatureAccountIndex',
368
- docs: [
369
- 'index of the output state Merkle tree that will be used to store cpi signatures',
370
- 'The transaction will fail if this index is not consistent in your transaction.',
371
- ],
372
- type: 'u8',
373
- },
374
- {
375
- name: 'execute',
376
- docs: [
377
- 'The final cpi of your program needs to set execute to true.',
378
- 'Execute compressed transaction will verify the proof and execute the transaction if this is true.',
379
- 'If this is false the transaction will be stored in the cpi signature account.',
380
- ],
381
- type: 'bool',
382
- },
383
- ],
384
- },
385
- },
386
- {
387
- name: 'PublicTransactionEvent',
388
- type: {
389
- kind: 'struct',
390
- fields: [
391
- {
392
- name: 'inputCompressedAccountHashes',
393
- type: {
394
- vec: {
395
- array: ['u8', 32],
396
- },
397
- },
398
- },
399
- {
400
- name: 'outputCompressedAccountHashes',
401
- type: {
402
- vec: {
403
- array: ['u8', 32],
404
- },
405
- },
406
- },
407
- {
408
- name: 'inputCompressedAccounts',
409
- type: {
410
- vec: {
411
- defined: 'CompressedAccountWithMerkleContext',
412
- },
413
- },
414
- },
415
- {
416
- name: 'outputCompressedAccounts',
417
- type: {
418
- vec: {
419
- defined: 'CompressedAccount',
420
- },
421
- },
422
- },
423
- {
424
- name: 'outputStateMerkleTreeAccountIndices',
425
- type: 'bytes',
426
- },
427
- {
428
- name: 'outputLeafIndices',
429
- type: {
430
- vec: 'u32',
431
- },
432
- },
433
- {
434
- name: 'relayFee',
435
- type: {
436
- option: 'u64',
437
- },
438
- },
439
- {
440
- name: 'isCompress',
441
- type: 'bool',
442
- },
443
- {
444
- name: 'compressionLamports',
445
- type: {
446
- option: 'u64',
447
- },
448
- },
449
- {
450
- name: 'pubkeyArray',
451
- type: {
452
- vec: 'publicKey',
453
- },
454
- },
455
- {
456
- name: 'message',
457
- type: {
458
- option: 'bytes',
459
- },
460
- },
461
- ],
462
- },
463
- },
464
- {
465
- name: 'InstructionDataTransfer',
466
- type: {
467
- kind: 'struct',
468
- fields: [
469
- {
470
- name: 'proof',
471
- type: {
472
- option: {
473
- defined: 'CompressedProof',
474
- },
475
- },
476
- },
477
- {
478
- name: 'newAddressParams',
479
- type: {
480
- vec: {
481
- defined: 'NewAddressParamsPacked',
482
- },
483
- },
484
- },
485
- {
486
- name: 'inputRootIndices',
487
- type: {
488
- vec: 'u16',
489
- },
490
- },
491
- {
492
- name: 'inputCompressedAccountsWithMerkleContext',
493
- type: {
494
- vec: {
495
- defined: 'CompressedAccountWithMerkleContext',
496
- },
497
- },
498
- },
499
- {
500
- name: 'outputCompressedAccounts',
501
- type: {
502
- vec: {
503
- defined: 'CompressedAccount',
504
- },
505
- },
506
- },
507
- {
508
- name: 'outputStateMerkleTreeAccountIndices',
509
- docs: [
510
- 'The indices of the accounts in the output state merkle tree.',
511
- ],
512
- type: 'bytes',
513
- },
514
- {
515
- name: 'relayFee',
516
- type: {
517
- option: 'u64',
518
- },
519
- },
520
- {
521
- name: 'compressionLamports',
522
- type: {
523
- option: 'u64',
524
- },
525
- },
526
- {
527
- name: 'isCompress',
528
- type: 'bool',
529
- },
530
- {
531
- name: 'signerSeeds',
532
- type: {
533
- option: {
534
- vec: 'bytes',
535
- },
536
- },
537
- },
538
- ],
539
- },
540
- },
541
- {
542
- name: 'NewAddressParamsPacked',
543
- type: {
544
- kind: 'struct',
545
- fields: [
546
- {
547
- name: 'seed',
548
- type: {
549
- array: ['u8', 32],
550
- },
551
- },
552
- {
553
- name: 'addressQueueAccountIndex',
554
- type: 'u8',
555
- },
556
- {
557
- name: 'addressMerkleTreeAccountIndex',
558
- type: 'u8',
559
- },
560
- {
561
- name: 'addressMerkleTreeRootIndex',
562
- type: 'u16',
563
- },
564
- ],
565
- },
566
- },
567
- {
568
- name: 'NewAddressParams',
569
- type: {
570
- kind: 'struct',
571
- fields: [
572
- {
573
- name: 'seed',
574
- type: {
575
- array: ['u8', 32],
576
- },
577
- },
578
- {
579
- name: 'addressQueuePubkey',
580
- type: 'publicKey',
581
- },
582
- {
583
- name: 'addressMerkleTreePubkey',
584
- type: 'publicKey',
585
- },
586
- {
587
- name: 'addressMerkleTreeRootIndex',
588
- type: 'u16',
589
- },
590
- ],
591
- },
592
- },
593
- {
594
- name: 'CompressedProof',
595
- type: {
596
- kind: 'struct',
597
- fields: [
598
- {
599
- name: 'a',
600
- type: {
601
- array: ['u8', 32],
602
- },
603
- },
604
- {
605
- name: 'b',
606
- type: {
607
- array: ['u8', 64],
608
- },
609
- },
610
- {
611
- name: 'c',
612
- type: {
613
- array: ['u8', 32],
614
- },
615
- },
616
- ],
617
- },
618
- },
619
- {
620
- name: 'InputTokenDataWithContext',
621
- type: {
622
- kind: 'struct',
623
- fields: [
624
- {
625
- name: 'amount',
626
- type: 'u64',
627
- },
628
- {
629
- name: 'delegateIndex',
630
- type: {
631
- option: 'u8',
632
- },
633
- },
634
- {
635
- name: 'delegatedAmount',
636
- type: {
637
- option: 'u64',
638
- },
639
- },
640
- {
641
- name: 'isNative',
642
- type: {
643
- option: 'u64',
644
- },
645
- },
646
- {
647
- name: 'merkleTreePubkeyIndex',
648
- type: 'u8',
649
- },
650
- {
651
- name: 'nullifierQueuePubkeyIndex',
652
- type: 'u8',
653
- },
654
- {
655
- name: 'leafIndex',
656
- type: 'u32',
657
- },
658
- ],
659
- },
660
- },
661
- {
662
- name: 'CompressedTokenInstructionDataTransfer',
663
- type: {
664
- kind: 'struct',
665
- fields: [
666
- {
667
- name: 'proof',
668
- type: {
669
- option: {
670
- defined: 'CompressedProof',
671
- },
672
- },
673
- },
674
- {
675
- name: 'rootIndices',
676
- type: {
677
- vec: 'u16',
678
- },
679
- },
680
- {
681
- name: 'mint',
682
- type: 'publicKey',
683
- },
684
- {
685
- name: 'signerIsDelegate',
686
- type: 'bool',
687
- },
688
- {
689
- name: 'inputTokenDataWithContext',
690
- type: {
691
- vec: {
692
- defined: 'InputTokenDataWithContext',
693
- },
694
- },
695
- },
696
- {
697
- name: 'outputCompressedAccounts',
698
- type: {
699
- vec: {
700
- defined: 'TokenTransferOutputData',
701
- },
702
- },
703
- },
704
- {
705
- name: 'outputStateMerkleTreeAccountIndices',
706
- type: 'bytes',
707
- },
708
- {
709
- name: 'isCompress',
710
- type: 'bool',
711
- },
712
- {
713
- name: 'compressionAmount',
714
- type: {
715
- option: 'u64',
716
- },
717
- },
718
- ],
719
- },
720
- },
721
- {
722
- name: 'TokenTransferOutputData',
723
- type: {
724
- kind: 'struct',
725
- fields: [
726
- {
727
- name: 'owner',
728
- type: 'publicKey',
729
- },
730
- {
731
- name: 'amount',
732
- type: 'u64',
733
- },
734
- {
735
- name: 'lamports',
736
- type: {
737
- option: 'u64',
738
- },
739
- },
740
- ],
741
- },
742
- },
743
- {
744
- name: 'TokenData',
745
- type: {
746
- kind: 'struct',
747
- fields: [
748
- {
749
- name: 'mint',
750
- docs: ['The mint associated with this account'],
751
- type: 'publicKey',
752
- },
753
- {
754
- name: 'owner',
755
- docs: ['The owner of this account.'],
756
- type: 'publicKey',
757
- },
758
- {
759
- name: 'amount',
760
- docs: ['The amount of tokens this account holds.'],
761
- type: 'u64',
762
- },
763
- {
764
- name: 'delegate',
765
- docs: [
766
- 'If `delegate` is `Some` then `delegated_amount` represents',
767
- 'the amount authorized by the delegate',
768
- ],
769
- type: {
770
- option: 'publicKey',
771
- },
772
- },
773
- {
774
- name: 'state',
775
- docs: ["The account's state"],
776
- type: {
777
- defined: 'AccountState',
778
- },
779
- },
780
- {
781
- name: 'isNative',
782
- docs: [
783
- 'If is_some, this is a native token, and the value logs the rent-exempt',
784
- 'reserve. An Account is required to be rent-exempt, so the value is',
785
- 'used by the Processor to ensure that wrapped SOL accounts do not',
786
- 'drop below this threshold.',
787
- ],
788
- type: {
789
- option: 'u64',
790
- },
791
- },
792
- {
793
- name: 'delegatedAmount',
794
- docs: ['The amount delegated'],
795
- type: 'u64',
796
- },
797
- ],
798
- },
799
- },
800
- {
801
- name: 'TokenDataClient',
802
- type: {
803
- kind: 'struct',
804
- fields: [
805
- {
806
- name: 'mint',
807
- docs: ['The mint associated with this account'],
808
- type: 'publicKey',
809
- },
810
- {
811
- name: 'owner',
812
- docs: ['The owner of this account.'],
813
- type: 'publicKey',
814
- },
815
- {
816
- name: 'amount',
817
- docs: ['The amount of tokens this account holds.'],
818
- type: 'u64',
819
- },
820
- {
821
- name: 'delegate',
822
- docs: [
823
- 'If `delegate` is `Some` then `delegated_amount` represents',
824
- 'the amount authorized by the delegate',
825
- ],
826
- type: {
827
- option: 'publicKey',
828
- },
829
- },
830
- {
831
- name: 'state',
832
- docs: ["The account's state"],
833
- type: 'u8',
834
- },
835
- {
836
- name: 'isNative',
837
- docs: [
838
- 'If is_some, this is a native token, and the value logs the rent-exempt',
839
- 'reserve. An Account is required to be rent-exempt, so the value is',
840
- 'used by the Processor to ensure that wrapped SOL accounts do not',
841
- 'drop below this threshold.',
842
- ],
843
- type: {
844
- option: 'u64',
845
- },
846
- },
847
- {
848
- name: 'delegatedAmount',
849
- docs: ['The amount delegated'],
850
- type: 'u64',
851
- },
852
- ],
853
- },
854
- },
855
- {
856
- name: 'AccountState',
857
- type: {
858
- kind: 'enum',
859
- variants: [
860
- {
861
- name: 'Uninitialized',
862
- },
863
- {
864
- name: 'Initialized',
865
- },
866
- {
867
- name: 'Frozen',
868
- },
869
- ],
870
- },
871
- },
872
- {
873
- name: 'ErrorCode',
874
- type: {
875
- kind: 'enum',
876
- variants: [
877
- {
878
- name: 'PublicKeyAmountMissmatch',
879
- },
880
- {
881
- name: 'MissingNewAuthorityPda',
882
- },
883
- {
884
- name: 'SignerCheckFailed',
885
- },
886
- {
887
- name: 'MintCheckFailed',
888
- },
889
- {
890
- name: 'ComputeInputSumFailed',
891
- },
892
- {
893
- name: 'ComputeOutputSumFailed',
894
- },
895
- {
896
- name: 'ComputeCompressSumFailed',
897
- },
898
- {
899
- name: 'ComputeDecompressSumFailed',
900
- },
901
- {
902
- name: 'SumCheckFailed',
903
- },
904
- {
905
- name: 'DecompressRecipientUndefinedForDecompress',
906
- },
907
- {
908
- name: 'CompressedPdaUndefinedForDecompress',
909
- },
910
- {
911
- name: 'DeCompressAmountUndefinedForDecompress',
912
- },
913
- {
914
- name: 'CompressedPdaUndefinedForCompress',
915
- },
916
- {
917
- name: 'DeCompressAmountUndefinedForCompress',
918
- },
919
- {
920
- name: 'DelegateUndefined',
921
- },
922
- ],
923
- },
924
- },
925
- ],
926
- errors: [
927
- {
928
- code: 6000,
929
- name: 'SignerCheckFailed',
930
- msg: 'Signer check failed',
931
- },
932
- {
933
- code: 6001,
934
- name: 'CreateTransferInstructionFailed',
935
- msg: 'Create transfer instruction failed',
936
- },
937
- ],
938
- };
939
-
940
- // TODO: include owner and lamports in packing.
941
- /**
942
- * Packs Compressed Token Accounts.
943
- */
944
- function packCompressedTokenAccounts(params) {
945
- const { inputCompressedTokenAccounts, outputCompressedAccountsLength, outputStateTrees, remainingAccounts = [], } = params;
946
- const _remainingAccounts = remainingAccounts.slice();
947
- let delegateIndex = null;
948
- if (inputCompressedTokenAccounts.length > 0 &&
949
- inputCompressedTokenAccounts[0].parsed.delegate) {
950
- delegateIndex = getIndexOrAdd(_remainingAccounts, inputCompressedTokenAccounts[0].parsed.delegate);
951
- }
952
- /// TODO: move pubkeyArray to remainingAccounts
953
- /// Currently just packs 'delegate' to pubkeyArray
954
- const packedInputTokenData = [];
955
- /// pack inputs
956
- inputCompressedTokenAccounts.forEach((account) => {
957
- const merkleTreePubkeyIndex = getIndexOrAdd(_remainingAccounts, account.compressedAccount.merkleTree);
958
- const nullifierQueuePubkeyIndex = getIndexOrAdd(_remainingAccounts, account.compressedAccount.nullifierQueue);
959
- packedInputTokenData.push({
960
- amount: account.parsed.amount,
961
- delegateIndex,
962
- delegatedAmount: account.parsed.delegatedAmount.eq(bn(0))
963
- ? null
964
- : account.parsed.delegatedAmount,
965
- isNative: account.parsed.isNative,
966
- merkleTreePubkeyIndex,
967
- nullifierQueuePubkeyIndex,
968
- leafIndex: account.compressedAccount.leafIndex,
969
- });
970
- });
971
- /// pack output state trees
972
- const paddedOutputStateMerkleTrees = padOutputStateMerkleTrees(outputStateTrees, outputCompressedAccountsLength, inputCompressedTokenAccounts.map(acc => acc.compressedAccount));
973
- const outputStateMerkleTreeIndices = [];
974
- paddedOutputStateMerkleTrees.forEach(account => {
975
- const indexMerkleTree = getIndexOrAdd(_remainingAccounts, account);
976
- outputStateMerkleTreeIndices.push(indexMerkleTree);
977
- });
978
- // to meta
979
- const remainingAccountMetas = _remainingAccounts.map((account) => ({
980
- pubkey: account,
981
- isWritable: true,
982
- isSigner: false,
983
- }));
984
- return {
985
- inputTokenDataWithContext: packedInputTokenData,
986
- outputStateMerkleTreeIndices,
987
- remainingAccountMetas,
988
- };
989
- }
990
-
991
- const POOL_SEED = Buffer.from('pool');
992
- const CPI_AUTHORITY_SEED = Buffer.from('cpi_authority');
993
- const MINT_AUTHORITY_SEED = utils.bytes.utf8.encode('mint_authority_pda');
994
- const SPL_TOKEN_MINT_RENT_EXEMPT_BALANCE = 1461600;
995
-
996
- /** Address of the SPL Token program */
997
- const TOKEN_PROGRAM_ID = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
998
- /** Address of the SPL Token 2022 program */
999
- new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');
1000
- /** Address of the SPL Associated Token Account program */
1001
- new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');
1002
- /** Address of the special mint for wrapped native SOL in spl-token */
1003
- new PublicKey('So11111111111111111111111111111111111111112');
1004
- /** Address of the special mint for wrapped native SOL in spl-token-2022 */
1005
- new PublicKey('9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP');
1006
-
1007
- var Layout$1 = {};
1008
-
1009
- /* The MIT License (MIT)
1010
- *
1011
- * Copyright 2015-2018 Peter A. Bigot
1012
- *
1013
- * Permission is hereby granted, free of charge, to any person obtaining a copy
1014
- * of this software and associated documentation files (the "Software"), to deal
1015
- * in the Software without restriction, including without limitation the rights
1016
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1017
- * copies of the Software, and to permit persons to whom the Software is
1018
- * furnished to do so, subject to the following conditions:
1019
- *
1020
- * The above copyright notice and this permission notice shall be included in
1021
- * all copies or substantial portions of the Software.
1022
- *
1023
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1024
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1025
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1026
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1027
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1028
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
1029
- * THE SOFTWARE.
1030
- */
1031
- Object.defineProperty(Layout$1, "__esModule", { value: true });
1032
- Layout$1.s16 = Layout$1.s8 = Layout$1.nu64be = Layout$1.u48be = Layout$1.u40be = Layout$1.u32be = Layout$1.u24be = Layout$1.u16be = Layout$1.nu64 = Layout$1.u48 = Layout$1.u40 = u32 = Layout$1.u32 = Layout$1.u24 = Layout$1.u16 = u8 = Layout$1.u8 = Layout$1.offset = Layout$1.greedy = Layout$1.Constant = Layout$1.UTF8 = Layout$1.CString = Layout$1.Blob = Layout$1.Boolean = Layout$1.BitField = Layout$1.BitStructure = Layout$1.VariantLayout = Layout$1.Union = Layout$1.UnionLayoutDiscriminator = Layout$1.UnionDiscriminator = Layout$1.Structure = Layout$1.Sequence = Layout$1.DoubleBE = Layout$1.Double = Layout$1.FloatBE = Layout$1.Float = Layout$1.NearInt64BE = Layout$1.NearInt64 = Layout$1.NearUInt64BE = Layout$1.NearUInt64 = Layout$1.IntBE = Layout$1.Int = Layout$1.UIntBE = Layout$1.UInt = Layout$1.OffsetLayout = Layout$1.GreedyCount = Layout$1.ExternalLayout = Layout$1.bindConstructorLayout = Layout$1.nameWithProperty = Layout$1.Layout = Layout$1.uint8ArrayToBuffer = Layout$1.checkUint8Array = void 0;
1033
- Layout$1.constant = Layout$1.utf8 = Layout$1.cstr = blob = Layout$1.blob = Layout$1.unionLayoutDiscriminator = Layout$1.union = Layout$1.seq = Layout$1.bits = struct = Layout$1.struct = Layout$1.f64be = Layout$1.f64 = Layout$1.f32be = Layout$1.f32 = Layout$1.ns64be = Layout$1.s48be = Layout$1.s40be = Layout$1.s32be = Layout$1.s24be = Layout$1.s16be = Layout$1.ns64 = Layout$1.s48 = Layout$1.s40 = Layout$1.s32 = Layout$1.s24 = void 0;
1034
- const buffer_1 = require$$0;
1035
- /* Check if a value is a Uint8Array.
1036
- *
1037
- * @ignore */
1038
- function checkUint8Array(b) {
1039
- if (!(b instanceof Uint8Array)) {
1040
- throw new TypeError('b must be a Uint8Array');
1041
- }
1042
- }
1043
- Layout$1.checkUint8Array = checkUint8Array;
1044
- /* Create a Buffer instance from a Uint8Array.
1045
- *
1046
- * @ignore */
1047
- function uint8ArrayToBuffer(b) {
1048
- checkUint8Array(b);
1049
- return buffer_1.Buffer.from(b.buffer, b.byteOffset, b.length);
1050
- }
1051
- Layout$1.uint8ArrayToBuffer = uint8ArrayToBuffer;
1052
- /**
1053
- * Base class for layout objects.
1054
- *
1055
- * **NOTE** This is an abstract base class; you can create instances
1056
- * if it amuses you, but they won't support the {@link
1057
- * Layout#encode|encode} or {@link Layout#decode|decode} functions.
1058
- *
1059
- * @param {Number} span - Initializer for {@link Layout#span|span}. The
1060
- * parameter must be an integer; a negative value signifies that the
1061
- * span is {@link Layout#getSpan|value-specific}.
1062
- *
1063
- * @param {string} [property] - Initializer for {@link
1064
- * Layout#property|property}.
1065
- *
1066
- * @abstract
1067
- */
1068
- class Layout {
1069
- constructor(span, property) {
1070
- if (!Number.isInteger(span)) {
1071
- throw new TypeError('span must be an integer');
1072
- }
1073
- /** The span of the layout in bytes.
1074
- *
1075
- * Positive values are generally expected.
1076
- *
1077
- * Zero will only appear in {@link Constant}s and in {@link
1078
- * Sequence}s where the {@link Sequence#count|count} is zero.
1079
- *
1080
- * A negative value indicates that the span is value-specific, and
1081
- * must be obtained using {@link Layout#getSpan|getSpan}. */
1082
- this.span = span;
1083
- /** The property name used when this layout is represented in an
1084
- * Object.
1085
- *
1086
- * Used only for layouts that {@link Layout#decode|decode} to Object
1087
- * instances. If left undefined the span of the unnamed layout will
1088
- * be treated as padding: it will not be mutated by {@link
1089
- * Layout#encode|encode} nor represented as a property in the
1090
- * decoded Object. */
1091
- this.property = property;
1092
- }
1093
- /** Function to create an Object into which decoded properties will
1094
- * be written.
1095
- *
1096
- * Used only for layouts that {@link Layout#decode|decode} to Object
1097
- * instances, which means:
1098
- * * {@link Structure}
1099
- * * {@link Union}
1100
- * * {@link VariantLayout}
1101
- * * {@link BitStructure}
1102
- *
1103
- * If left undefined the JavaScript representation of these layouts
1104
- * will be Object instances.
1105
- *
1106
- * See {@link bindConstructorLayout}.
1107
- */
1108
- makeDestinationObject() {
1109
- return {};
1110
- }
1111
- /**
1112
- * Calculate the span of a specific instance of a layout.
1113
- *
1114
- * @param {Uint8Array} b - the buffer that contains an encoded instance.
1115
- *
1116
- * @param {Number} [offset] - the offset at which the encoded instance
1117
- * starts. If absent a zero offset is inferred.
1118
- *
1119
- * @return {Number} - the number of bytes covered by the layout
1120
- * instance. If this method is not overridden in a subclass the
1121
- * definition-time constant {@link Layout#span|span} will be
1122
- * returned.
1123
- *
1124
- * @throws {RangeError} - if the length of the value cannot be
1125
- * determined.
1126
- */
1127
- getSpan(b, offset) {
1128
- if (0 > this.span) {
1129
- throw new RangeError('indeterminate span');
1130
- }
1131
- return this.span;
1132
- }
1133
- /**
1134
- * Replicate the layout using a new property.
1135
- *
1136
- * This function must be used to get a structurally-equivalent layout
1137
- * with a different name since all {@link Layout} instances are
1138
- * immutable.
1139
- *
1140
- * **NOTE** This is a shallow copy. All fields except {@link
1141
- * Layout#property|property} are strictly equal to the origin layout.
1142
- *
1143
- * @param {String} property - the value for {@link
1144
- * Layout#property|property} in the replica.
1145
- *
1146
- * @returns {Layout} - the copy with {@link Layout#property|property}
1147
- * set to `property`.
1148
- */
1149
- replicate(property) {
1150
- const rv = Object.create(this.constructor.prototype);
1151
- Object.assign(rv, this);
1152
- rv.property = property;
1153
- return rv;
1154
- }
1155
- /**
1156
- * Create an object from layout properties and an array of values.
1157
- *
1158
- * **NOTE** This function returns `undefined` if invoked on a layout
1159
- * that does not return its value as an Object. Objects are
1160
- * returned for things that are a {@link Structure}, which includes
1161
- * {@link VariantLayout|variant layouts} if they are structures, and
1162
- * excludes {@link Union}s. If you want this feature for a union
1163
- * you must use {@link Union.getVariant|getVariant} to select the
1164
- * desired layout.
1165
- *
1166
- * @param {Array} values - an array of values that correspond to the
1167
- * default order for properties. As with {@link Layout#decode|decode}
1168
- * layout elements that have no property name are skipped when
1169
- * iterating over the array values. Only the top-level properties are
1170
- * assigned; arguments are not assigned to properties of contained
1171
- * layouts. Any unused values are ignored.
1172
- *
1173
- * @return {(Object|undefined)}
1174
- */
1175
- fromArray(values) {
1176
- return undefined;
1177
- }
1178
- }
1179
- Layout$1.Layout = Layout;
1180
- /* Provide text that carries a name (such as for a function that will
1181
- * be throwing an error) annotated with the property of a given layout
1182
- * (such as one for which the value was unacceptable).
1183
- *
1184
- * @ignore */
1185
- function nameWithProperty(name, lo) {
1186
- if (lo.property) {
1187
- return name + '[' + lo.property + ']';
1188
- }
1189
- return name;
1190
- }
1191
- Layout$1.nameWithProperty = nameWithProperty;
1192
- /**
1193
- * Augment a class so that instances can be encoded/decoded using a
1194
- * given layout.
1195
- *
1196
- * Calling this function couples `Class` with `layout` in several ways:
1197
- *
1198
- * * `Class.layout_` becomes a static member property equal to `layout`;
1199
- * * `layout.boundConstructor_` becomes a static member property equal
1200
- * to `Class`;
1201
- * * The {@link Layout#makeDestinationObject|makeDestinationObject()}
1202
- * property of `layout` is set to a function that returns a `new
1203
- * Class()`;
1204
- * * `Class.decode(b, offset)` becomes a static member function that
1205
- * delegates to {@link Layout#decode|layout.decode}. The
1206
- * synthesized function may be captured and extended.
1207
- * * `Class.prototype.encode(b, offset)` provides an instance member
1208
- * function that delegates to {@link Layout#encode|layout.encode}
1209
- * with `src` set to `this`. The synthesized function may be
1210
- * captured and extended, but when the extension is invoked `this`
1211
- * must be explicitly bound to the instance.
1212
- *
1213
- * @param {class} Class - a JavaScript class with a nullary
1214
- * constructor.
1215
- *
1216
- * @param {Layout} layout - the {@link Layout} instance used to encode
1217
- * instances of `Class`.
1218
- */
1219
- // `Class` must be a constructor Function, but the assignment of a `layout_` property to it makes it difficult to type
1220
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
1221
- function bindConstructorLayout(Class, layout) {
1222
- if ('function' !== typeof Class) {
1223
- throw new TypeError('Class must be constructor');
1224
- }
1225
- if (Object.prototype.hasOwnProperty.call(Class, 'layout_')) {
1226
- throw new Error('Class is already bound to a layout');
1227
- }
1228
- if (!(layout && (layout instanceof Layout))) {
1229
- throw new TypeError('layout must be a Layout');
1230
- }
1231
- if (Object.prototype.hasOwnProperty.call(layout, 'boundConstructor_')) {
1232
- throw new Error('layout is already bound to a constructor');
1233
- }
1234
- Class.layout_ = layout;
1235
- layout.boundConstructor_ = Class;
1236
- layout.makeDestinationObject = (() => new Class());
1237
- Object.defineProperty(Class.prototype, 'encode', {
1238
- value(b, offset) {
1239
- return layout.encode(this, b, offset);
1240
- },
1241
- writable: true,
1242
- });
1243
- Object.defineProperty(Class, 'decode', {
1244
- value(b, offset) {
1245
- return layout.decode(b, offset);
1246
- },
1247
- writable: true,
1248
- });
1249
- }
1250
- Layout$1.bindConstructorLayout = bindConstructorLayout;
1251
- /**
1252
- * An object that behaves like a layout but does not consume space
1253
- * within its containing layout.
1254
- *
1255
- * This is primarily used to obtain metadata about a member, such as a
1256
- * {@link OffsetLayout} that can provide data about a {@link
1257
- * Layout#getSpan|value-specific span}.
1258
- *
1259
- * **NOTE** This is an abstract base class; you can create instances
1260
- * if it amuses you, but they won't support {@link
1261
- * ExternalLayout#isCount|isCount} or other {@link Layout} functions.
1262
- *
1263
- * @param {Number} span - initializer for {@link Layout#span|span}.
1264
- * The parameter can range from 1 through 6.
1265
- *
1266
- * @param {string} [property] - initializer for {@link
1267
- * Layout#property|property}.
1268
- *
1269
- * @abstract
1270
- * @augments {Layout}
1271
- */
1272
- class ExternalLayout extends Layout {
1273
- /**
1274
- * Return `true` iff the external layout decodes to an unsigned
1275
- * integer layout.
1276
- *
1277
- * In that case it can be used as the source of {@link
1278
- * Sequence#count|Sequence counts}, {@link Blob#length|Blob lengths},
1279
- * or as {@link UnionLayoutDiscriminator#layout|external union
1280
- * discriminators}.
1281
- *
1282
- * @abstract
1283
- */
1284
- isCount() {
1285
- throw new Error('ExternalLayout is abstract');
1286
- }
1287
- }
1288
- Layout$1.ExternalLayout = ExternalLayout;
1289
- /**
1290
- * An {@link ExternalLayout} that determines its {@link
1291
- * Layout#decode|value} based on offset into and length of the buffer
1292
- * on which it is invoked.
1293
- *
1294
- * *Factory*: {@link module:Layout.greedy|greedy}
1295
- *
1296
- * @param {Number} [elementSpan] - initializer for {@link
1297
- * GreedyCount#elementSpan|elementSpan}.
1298
- *
1299
- * @param {string} [property] - initializer for {@link
1300
- * Layout#property|property}.
1301
- *
1302
- * @augments {ExternalLayout}
1303
- */
1304
- class GreedyCount extends ExternalLayout {
1305
- constructor(elementSpan = 1, property) {
1306
- if ((!Number.isInteger(elementSpan)) || (0 >= elementSpan)) {
1307
- throw new TypeError('elementSpan must be a (positive) integer');
1308
- }
1309
- super(-1, property);
1310
- /** The layout for individual elements of the sequence. The value
1311
- * must be a positive integer. If not provided, the value will be
1312
- * 1. */
1313
- this.elementSpan = elementSpan;
1314
- }
1315
- /** @override */
1316
- isCount() {
1317
- return true;
1318
- }
1319
- /** @override */
1320
- decode(b, offset = 0) {
1321
- checkUint8Array(b);
1322
- const rem = b.length - offset;
1323
- return Math.floor(rem / this.elementSpan);
1324
- }
1325
- /** @override */
1326
- encode(src, b, offset) {
1327
- return 0;
1328
- }
1329
- }
1330
- Layout$1.GreedyCount = GreedyCount;
1331
- /**
1332
- * An {@link ExternalLayout} that supports accessing a {@link Layout}
1333
- * at a fixed offset from the start of another Layout. The offset may
1334
- * be before, within, or after the base layout.
1335
- *
1336
- * *Factory*: {@link module:Layout.offset|offset}
1337
- *
1338
- * @param {Layout} layout - initializer for {@link
1339
- * OffsetLayout#layout|layout}, modulo `property`.
1340
- *
1341
- * @param {Number} [offset] - Initializes {@link
1342
- * OffsetLayout#offset|offset}. Defaults to zero.
1343
- *
1344
- * @param {string} [property] - Optional new property name for a
1345
- * {@link Layout#replicate| replica} of `layout` to be used as {@link
1346
- * OffsetLayout#layout|layout}. If not provided the `layout` is used
1347
- * unchanged.
1348
- *
1349
- * @augments {Layout}
1350
- */
1351
- class OffsetLayout extends ExternalLayout {
1352
- constructor(layout, offset = 0, property) {
1353
- if (!(layout instanceof Layout)) {
1354
- throw new TypeError('layout must be a Layout');
1355
- }
1356
- if (!Number.isInteger(offset)) {
1357
- throw new TypeError('offset must be integer or undefined');
1358
- }
1359
- super(layout.span, property || layout.property);
1360
- /** The subordinated layout. */
1361
- this.layout = layout;
1362
- /** The location of {@link OffsetLayout#layout} relative to the
1363
- * start of another layout.
1364
- *
1365
- * The value may be positive or negative, but an error will thrown
1366
- * if at the point of use it goes outside the span of the Uint8Array
1367
- * being accessed. */
1368
- this.offset = offset;
1369
- }
1370
- /** @override */
1371
- isCount() {
1372
- return ((this.layout instanceof UInt)
1373
- || (this.layout instanceof UIntBE));
1374
- }
1375
- /** @override */
1376
- decode(b, offset = 0) {
1377
- return this.layout.decode(b, offset + this.offset);
1378
- }
1379
- /** @override */
1380
- encode(src, b, offset = 0) {
1381
- return this.layout.encode(src, b, offset + this.offset);
1382
- }
1383
- }
1384
- Layout$1.OffsetLayout = OffsetLayout;
1385
- /**
1386
- * Represent an unsigned integer in little-endian format.
1387
- *
1388
- * *Factory*: {@link module:Layout.u8|u8}, {@link
1389
- * module:Layout.u16|u16}, {@link module:Layout.u24|u24}, {@link
1390
- * module:Layout.u32|u32}, {@link module:Layout.u40|u40}, {@link
1391
- * module:Layout.u48|u48}
1392
- *
1393
- * @param {Number} span - initializer for {@link Layout#span|span}.
1394
- * The parameter can range from 1 through 6.
1395
- *
1396
- * @param {string} [property] - initializer for {@link
1397
- * Layout#property|property}.
1398
- *
1399
- * @augments {Layout}
1400
- */
1401
- class UInt extends Layout {
1402
- constructor(span, property) {
1403
- super(span, property);
1404
- if (6 < this.span) {
1405
- throw new RangeError('span must not exceed 6 bytes');
1406
- }
1407
- }
1408
- /** @override */
1409
- decode(b, offset = 0) {
1410
- return uint8ArrayToBuffer(b).readUIntLE(offset, this.span);
1411
- }
1412
- /** @override */
1413
- encode(src, b, offset = 0) {
1414
- uint8ArrayToBuffer(b).writeUIntLE(src, offset, this.span);
1415
- return this.span;
1416
- }
1417
- }
1418
- Layout$1.UInt = UInt;
1419
- /**
1420
- * Represent an unsigned integer in big-endian format.
1421
- *
1422
- * *Factory*: {@link module:Layout.u8be|u8be}, {@link
1423
- * module:Layout.u16be|u16be}, {@link module:Layout.u24be|u24be},
1424
- * {@link module:Layout.u32be|u32be}, {@link
1425
- * module:Layout.u40be|u40be}, {@link module:Layout.u48be|u48be}
1426
- *
1427
- * @param {Number} span - initializer for {@link Layout#span|span}.
1428
- * The parameter can range from 1 through 6.
1429
- *
1430
- * @param {string} [property] - initializer for {@link
1431
- * Layout#property|property}.
1432
- *
1433
- * @augments {Layout}
1434
- */
1435
- class UIntBE extends Layout {
1436
- constructor(span, property) {
1437
- super(span, property);
1438
- if (6 < this.span) {
1439
- throw new RangeError('span must not exceed 6 bytes');
1440
- }
1441
- }
1442
- /** @override */
1443
- decode(b, offset = 0) {
1444
- return uint8ArrayToBuffer(b).readUIntBE(offset, this.span);
1445
- }
1446
- /** @override */
1447
- encode(src, b, offset = 0) {
1448
- uint8ArrayToBuffer(b).writeUIntBE(src, offset, this.span);
1449
- return this.span;
1450
- }
1451
- }
1452
- Layout$1.UIntBE = UIntBE;
1453
- /**
1454
- * Represent a signed integer in little-endian format.
1455
- *
1456
- * *Factory*: {@link module:Layout.s8|s8}, {@link
1457
- * module:Layout.s16|s16}, {@link module:Layout.s24|s24}, {@link
1458
- * module:Layout.s32|s32}, {@link module:Layout.s40|s40}, {@link
1459
- * module:Layout.s48|s48}
1460
- *
1461
- * @param {Number} span - initializer for {@link Layout#span|span}.
1462
- * The parameter can range from 1 through 6.
1463
- *
1464
- * @param {string} [property] - initializer for {@link
1465
- * Layout#property|property}.
1466
- *
1467
- * @augments {Layout}
1468
- */
1469
- class Int extends Layout {
1470
- constructor(span, property) {
1471
- super(span, property);
1472
- if (6 < this.span) {
1473
- throw new RangeError('span must not exceed 6 bytes');
1474
- }
1475
- }
1476
- /** @override */
1477
- decode(b, offset = 0) {
1478
- return uint8ArrayToBuffer(b).readIntLE(offset, this.span);
1479
- }
1480
- /** @override */
1481
- encode(src, b, offset = 0) {
1482
- uint8ArrayToBuffer(b).writeIntLE(src, offset, this.span);
1483
- return this.span;
1484
- }
1485
- }
1486
- Layout$1.Int = Int;
1487
- /**
1488
- * Represent a signed integer in big-endian format.
1489
- *
1490
- * *Factory*: {@link module:Layout.s8be|s8be}, {@link
1491
- * module:Layout.s16be|s16be}, {@link module:Layout.s24be|s24be},
1492
- * {@link module:Layout.s32be|s32be}, {@link
1493
- * module:Layout.s40be|s40be}, {@link module:Layout.s48be|s48be}
1494
- *
1495
- * @param {Number} span - initializer for {@link Layout#span|span}.
1496
- * The parameter can range from 1 through 6.
1497
- *
1498
- * @param {string} [property] - initializer for {@link
1499
- * Layout#property|property}.
1500
- *
1501
- * @augments {Layout}
1502
- */
1503
- class IntBE extends Layout {
1504
- constructor(span, property) {
1505
- super(span, property);
1506
- if (6 < this.span) {
1507
- throw new RangeError('span must not exceed 6 bytes');
1508
- }
1509
- }
1510
- /** @override */
1511
- decode(b, offset = 0) {
1512
- return uint8ArrayToBuffer(b).readIntBE(offset, this.span);
1513
- }
1514
- /** @override */
1515
- encode(src, b, offset = 0) {
1516
- uint8ArrayToBuffer(b).writeIntBE(src, offset, this.span);
1517
- return this.span;
1518
- }
1519
- }
1520
- Layout$1.IntBE = IntBE;
1521
- const V2E32 = Math.pow(2, 32);
1522
- /* True modulus high and low 32-bit words, where low word is always
1523
- * non-negative. */
1524
- function divmodInt64(src) {
1525
- const hi32 = Math.floor(src / V2E32);
1526
- const lo32 = src - (hi32 * V2E32);
1527
- return { hi32, lo32 };
1528
- }
1529
- /* Reconstruct Number from quotient and non-negative remainder */
1530
- function roundedInt64(hi32, lo32) {
1531
- return hi32 * V2E32 + lo32;
1532
- }
1533
- /**
1534
- * Represent an unsigned 64-bit integer in little-endian format when
1535
- * encoded and as a near integral JavaScript Number when decoded.
1536
- *
1537
- * *Factory*: {@link module:Layout.nu64|nu64}
1538
- *
1539
- * **NOTE** Values with magnitude greater than 2^52 may not decode to
1540
- * the exact value of the encoded representation.
1541
- *
1542
- * @augments {Layout}
1543
- */
1544
- class NearUInt64 extends Layout {
1545
- constructor(property) {
1546
- super(8, property);
1547
- }
1548
- /** @override */
1549
- decode(b, offset = 0) {
1550
- const buffer = uint8ArrayToBuffer(b);
1551
- const lo32 = buffer.readUInt32LE(offset);
1552
- const hi32 = buffer.readUInt32LE(offset + 4);
1553
- return roundedInt64(hi32, lo32);
1554
- }
1555
- /** @override */
1556
- encode(src, b, offset = 0) {
1557
- const split = divmodInt64(src);
1558
- const buffer = uint8ArrayToBuffer(b);
1559
- buffer.writeUInt32LE(split.lo32, offset);
1560
- buffer.writeUInt32LE(split.hi32, offset + 4);
1561
- return 8;
1562
- }
1563
- }
1564
- Layout$1.NearUInt64 = NearUInt64;
1565
- /**
1566
- * Represent an unsigned 64-bit integer in big-endian format when
1567
- * encoded and as a near integral JavaScript Number when decoded.
1568
- *
1569
- * *Factory*: {@link module:Layout.nu64be|nu64be}
1570
- *
1571
- * **NOTE** Values with magnitude greater than 2^52 may not decode to
1572
- * the exact value of the encoded representation.
1573
- *
1574
- * @augments {Layout}
1575
- */
1576
- class NearUInt64BE extends Layout {
1577
- constructor(property) {
1578
- super(8, property);
1579
- }
1580
- /** @override */
1581
- decode(b, offset = 0) {
1582
- const buffer = uint8ArrayToBuffer(b);
1583
- const hi32 = buffer.readUInt32BE(offset);
1584
- const lo32 = buffer.readUInt32BE(offset + 4);
1585
- return roundedInt64(hi32, lo32);
1586
- }
1587
- /** @override */
1588
- encode(src, b, offset = 0) {
1589
- const split = divmodInt64(src);
1590
- const buffer = uint8ArrayToBuffer(b);
1591
- buffer.writeUInt32BE(split.hi32, offset);
1592
- buffer.writeUInt32BE(split.lo32, offset + 4);
1593
- return 8;
1594
- }
1595
- }
1596
- Layout$1.NearUInt64BE = NearUInt64BE;
1597
- /**
1598
- * Represent a signed 64-bit integer in little-endian format when
1599
- * encoded and as a near integral JavaScript Number when decoded.
1600
- *
1601
- * *Factory*: {@link module:Layout.ns64|ns64}
1602
- *
1603
- * **NOTE** Values with magnitude greater than 2^52 may not decode to
1604
- * the exact value of the encoded representation.
1605
- *
1606
- * @augments {Layout}
1607
- */
1608
- class NearInt64 extends Layout {
1609
- constructor(property) {
1610
- super(8, property);
1611
- }
1612
- /** @override */
1613
- decode(b, offset = 0) {
1614
- const buffer = uint8ArrayToBuffer(b);
1615
- const lo32 = buffer.readUInt32LE(offset);
1616
- const hi32 = buffer.readInt32LE(offset + 4);
1617
- return roundedInt64(hi32, lo32);
1618
- }
1619
- /** @override */
1620
- encode(src, b, offset = 0) {
1621
- const split = divmodInt64(src);
1622
- const buffer = uint8ArrayToBuffer(b);
1623
- buffer.writeUInt32LE(split.lo32, offset);
1624
- buffer.writeInt32LE(split.hi32, offset + 4);
1625
- return 8;
1626
- }
1627
- }
1628
- Layout$1.NearInt64 = NearInt64;
1629
- /**
1630
- * Represent a signed 64-bit integer in big-endian format when
1631
- * encoded and as a near integral JavaScript Number when decoded.
1632
- *
1633
- * *Factory*: {@link module:Layout.ns64be|ns64be}
1634
- *
1635
- * **NOTE** Values with magnitude greater than 2^52 may not decode to
1636
- * the exact value of the encoded representation.
1637
- *
1638
- * @augments {Layout}
1639
- */
1640
- class NearInt64BE extends Layout {
1641
- constructor(property) {
1642
- super(8, property);
1643
- }
1644
- /** @override */
1645
- decode(b, offset = 0) {
1646
- const buffer = uint8ArrayToBuffer(b);
1647
- const hi32 = buffer.readInt32BE(offset);
1648
- const lo32 = buffer.readUInt32BE(offset + 4);
1649
- return roundedInt64(hi32, lo32);
1650
- }
1651
- /** @override */
1652
- encode(src, b, offset = 0) {
1653
- const split = divmodInt64(src);
1654
- const buffer = uint8ArrayToBuffer(b);
1655
- buffer.writeInt32BE(split.hi32, offset);
1656
- buffer.writeUInt32BE(split.lo32, offset + 4);
1657
- return 8;
1658
- }
1659
- }
1660
- Layout$1.NearInt64BE = NearInt64BE;
1661
- /**
1662
- * Represent a 32-bit floating point number in little-endian format.
1663
- *
1664
- * *Factory*: {@link module:Layout.f32|f32}
1665
- *
1666
- * @param {string} [property] - initializer for {@link
1667
- * Layout#property|property}.
1668
- *
1669
- * @augments {Layout}
1670
- */
1671
- class Float extends Layout {
1672
- constructor(property) {
1673
- super(4, property);
1674
- }
1675
- /** @override */
1676
- decode(b, offset = 0) {
1677
- return uint8ArrayToBuffer(b).readFloatLE(offset);
1678
- }
1679
- /** @override */
1680
- encode(src, b, offset = 0) {
1681
- uint8ArrayToBuffer(b).writeFloatLE(src, offset);
1682
- return 4;
1683
- }
1684
- }
1685
- Layout$1.Float = Float;
1686
- /**
1687
- * Represent a 32-bit floating point number in big-endian format.
1688
- *
1689
- * *Factory*: {@link module:Layout.f32be|f32be}
1690
- *
1691
- * @param {string} [property] - initializer for {@link
1692
- * Layout#property|property}.
1693
- *
1694
- * @augments {Layout}
1695
- */
1696
- class FloatBE extends Layout {
1697
- constructor(property) {
1698
- super(4, property);
1699
- }
1700
- /** @override */
1701
- decode(b, offset = 0) {
1702
- return uint8ArrayToBuffer(b).readFloatBE(offset);
1703
- }
1704
- /** @override */
1705
- encode(src, b, offset = 0) {
1706
- uint8ArrayToBuffer(b).writeFloatBE(src, offset);
1707
- return 4;
1708
- }
1709
- }
1710
- Layout$1.FloatBE = FloatBE;
1711
- /**
1712
- * Represent a 64-bit floating point number in little-endian format.
1713
- *
1714
- * *Factory*: {@link module:Layout.f64|f64}
1715
- *
1716
- * @param {string} [property] - initializer for {@link
1717
- * Layout#property|property}.
1718
- *
1719
- * @augments {Layout}
1720
- */
1721
- class Double extends Layout {
1722
- constructor(property) {
1723
- super(8, property);
1724
- }
1725
- /** @override */
1726
- decode(b, offset = 0) {
1727
- return uint8ArrayToBuffer(b).readDoubleLE(offset);
1728
- }
1729
- /** @override */
1730
- encode(src, b, offset = 0) {
1731
- uint8ArrayToBuffer(b).writeDoubleLE(src, offset);
1732
- return 8;
1733
- }
1734
- }
1735
- Layout$1.Double = Double;
1736
- /**
1737
- * Represent a 64-bit floating point number in big-endian format.
1738
- *
1739
- * *Factory*: {@link module:Layout.f64be|f64be}
1740
- *
1741
- * @param {string} [property] - initializer for {@link
1742
- * Layout#property|property}.
1743
- *
1744
- * @augments {Layout}
1745
- */
1746
- class DoubleBE extends Layout {
1747
- constructor(property) {
1748
- super(8, property);
1749
- }
1750
- /** @override */
1751
- decode(b, offset = 0) {
1752
- return uint8ArrayToBuffer(b).readDoubleBE(offset);
1753
- }
1754
- /** @override */
1755
- encode(src, b, offset = 0) {
1756
- uint8ArrayToBuffer(b).writeDoubleBE(src, offset);
1757
- return 8;
1758
- }
1759
- }
1760
- Layout$1.DoubleBE = DoubleBE;
1761
- /**
1762
- * Represent a contiguous sequence of a specific layout as an Array.
1763
- *
1764
- * *Factory*: {@link module:Layout.seq|seq}
1765
- *
1766
- * @param {Layout} elementLayout - initializer for {@link
1767
- * Sequence#elementLayout|elementLayout}.
1768
- *
1769
- * @param {(Number|ExternalLayout)} count - initializer for {@link
1770
- * Sequence#count|count}. The parameter must be either a positive
1771
- * integer or an instance of {@link ExternalLayout}.
1772
- *
1773
- * @param {string} [property] - initializer for {@link
1774
- * Layout#property|property}.
1775
- *
1776
- * @augments {Layout}
1777
- */
1778
- class Sequence extends Layout {
1779
- constructor(elementLayout, count, property) {
1780
- if (!(elementLayout instanceof Layout)) {
1781
- throw new TypeError('elementLayout must be a Layout');
1782
- }
1783
- if (!(((count instanceof ExternalLayout) && count.isCount())
1784
- || (Number.isInteger(count) && (0 <= count)))) {
1785
- throw new TypeError('count must be non-negative integer '
1786
- + 'or an unsigned integer ExternalLayout');
1787
- }
1788
- let span = -1;
1789
- if ((!(count instanceof ExternalLayout))
1790
- && (0 < elementLayout.span)) {
1791
- span = count * elementLayout.span;
1792
- }
1793
- super(span, property);
1794
- /** The layout for individual elements of the sequence. */
1795
- this.elementLayout = elementLayout;
1796
- /** The number of elements in the sequence.
1797
- *
1798
- * This will be either a non-negative integer or an instance of
1799
- * {@link ExternalLayout} for which {@link
1800
- * ExternalLayout#isCount|isCount()} is `true`. */
1801
- this.count = count;
1802
- }
1803
- /** @override */
1804
- getSpan(b, offset = 0) {
1805
- if (0 <= this.span) {
1806
- return this.span;
1807
- }
1808
- let span = 0;
1809
- let count = this.count;
1810
- if (count instanceof ExternalLayout) {
1811
- count = count.decode(b, offset);
1812
- }
1813
- if (0 < this.elementLayout.span) {
1814
- span = count * this.elementLayout.span;
1815
- }
1816
- else {
1817
- let idx = 0;
1818
- while (idx < count) {
1819
- span += this.elementLayout.getSpan(b, offset + span);
1820
- ++idx;
1821
- }
1822
- }
1823
- return span;
1824
- }
1825
- /** @override */
1826
- decode(b, offset = 0) {
1827
- const rv = [];
1828
- let i = 0;
1829
- let count = this.count;
1830
- if (count instanceof ExternalLayout) {
1831
- count = count.decode(b, offset);
1832
- }
1833
- while (i < count) {
1834
- rv.push(this.elementLayout.decode(b, offset));
1835
- offset += this.elementLayout.getSpan(b, offset);
1836
- i += 1;
1837
- }
1838
- return rv;
1839
- }
1840
- /** Implement {@link Layout#encode|encode} for {@link Sequence}.
1841
- *
1842
- * **NOTE** If `src` is shorter than {@link Sequence#count|count} then
1843
- * the unused space in the buffer is left unchanged. If `src` is
1844
- * longer than {@link Sequence#count|count} the unneeded elements are
1845
- * ignored.
1846
- *
1847
- * **NOTE** If {@link Layout#count|count} is an instance of {@link
1848
- * ExternalLayout} then the length of `src` will be encoded as the
1849
- * count after `src` is encoded. */
1850
- encode(src, b, offset = 0) {
1851
- const elo = this.elementLayout;
1852
- const span = src.reduce((span, v) => {
1853
- return span + elo.encode(v, b, offset + span);
1854
- }, 0);
1855
- if (this.count instanceof ExternalLayout) {
1856
- this.count.encode(src.length, b, offset);
1857
- }
1858
- return span;
1859
- }
1860
- }
1861
- Layout$1.Sequence = Sequence;
1862
- /**
1863
- * Represent a contiguous sequence of arbitrary layout elements as an
1864
- * Object.
1865
- *
1866
- * *Factory*: {@link module:Layout.struct|struct}
1867
- *
1868
- * **NOTE** The {@link Layout#span|span} of the structure is variable
1869
- * if any layout in {@link Structure#fields|fields} has a variable
1870
- * span. When {@link Layout#encode|encoding} we must have a value for
1871
- * all variable-length fields, or we wouldn't be able to figure out
1872
- * how much space to use for storage. We can only identify the value
1873
- * for a field when it has a {@link Layout#property|property}. As
1874
- * such, although a structure may contain both unnamed fields and
1875
- * variable-length fields, it cannot contain an unnamed
1876
- * variable-length field.
1877
- *
1878
- * @param {Layout[]} fields - initializer for {@link
1879
- * Structure#fields|fields}. An error is raised if this contains a
1880
- * variable-length field for which a {@link Layout#property|property}
1881
- * is not defined.
1882
- *
1883
- * @param {string} [property] - initializer for {@link
1884
- * Layout#property|property}.
1885
- *
1886
- * @param {Boolean} [decodePrefixes] - initializer for {@link
1887
- * Structure#decodePrefixes|property}.
1888
- *
1889
- * @throws {Error} - if `fields` contains an unnamed variable-length
1890
- * layout.
1891
- *
1892
- * @augments {Layout}
1893
- */
1894
- class Structure extends Layout {
1895
- constructor(fields, property, decodePrefixes) {
1896
- if (!(Array.isArray(fields)
1897
- && fields.reduce((acc, v) => acc && (v instanceof Layout), true))) {
1898
- throw new TypeError('fields must be array of Layout instances');
1899
- }
1900
- if (('boolean' === typeof property)
1901
- && (undefined === decodePrefixes)) {
1902
- decodePrefixes = property;
1903
- property = undefined;
1904
- }
1905
- /* Verify absence of unnamed variable-length fields. */
1906
- for (const fd of fields) {
1907
- if ((0 > fd.span)
1908
- && (undefined === fd.property)) {
1909
- throw new Error('fields cannot contain unnamed variable-length layout');
1910
- }
1911
- }
1912
- let span = -1;
1913
- try {
1914
- span = fields.reduce((span, fd) => span + fd.getSpan(), 0);
1915
- }
1916
- catch (e) {
1917
- // ignore error
1918
- }
1919
- super(span, property);
1920
- /** The sequence of {@link Layout} values that comprise the
1921
- * structure.
1922
- *
1923
- * The individual elements need not be the same type, and may be
1924
- * either scalar or aggregate layouts. If a member layout leaves
1925
- * its {@link Layout#property|property} undefined the
1926
- * corresponding region of the buffer associated with the element
1927
- * will not be mutated.
1928
- *
1929
- * @type {Layout[]} */
1930
- this.fields = fields;
1931
- /** Control behavior of {@link Layout#decode|decode()} given short
1932
- * buffers.
1933
- *
1934
- * In some situations a structure many be extended with additional
1935
- * fields over time, with older installations providing only a
1936
- * prefix of the full structure. If this property is `true`
1937
- * decoding will accept those buffers and leave subsequent fields
1938
- * undefined, as long as the buffer ends at a field boundary.
1939
- * Defaults to `false`. */
1940
- this.decodePrefixes = !!decodePrefixes;
1941
- }
1942
- /** @override */
1943
- getSpan(b, offset = 0) {
1944
- if (0 <= this.span) {
1945
- return this.span;
1946
- }
1947
- let span = 0;
1948
- try {
1949
- span = this.fields.reduce((span, fd) => {
1950
- const fsp = fd.getSpan(b, offset);
1951
- offset += fsp;
1952
- return span + fsp;
1953
- }, 0);
1954
- }
1955
- catch (e) {
1956
- throw new RangeError('indeterminate span');
1957
- }
1958
- return span;
1959
- }
1960
- /** @override */
1961
- decode(b, offset = 0) {
1962
- checkUint8Array(b);
1963
- const dest = this.makeDestinationObject();
1964
- for (const fd of this.fields) {
1965
- if (undefined !== fd.property) {
1966
- dest[fd.property] = fd.decode(b, offset);
1967
- }
1968
- offset += fd.getSpan(b, offset);
1969
- if (this.decodePrefixes
1970
- && (b.length === offset)) {
1971
- break;
1972
- }
1973
- }
1974
- return dest;
1975
- }
1976
- /** Implement {@link Layout#encode|encode} for {@link Structure}.
1977
- *
1978
- * If `src` is missing a property for a member with a defined {@link
1979
- * Layout#property|property} the corresponding region of the buffer is
1980
- * left unmodified. */
1981
- encode(src, b, offset = 0) {
1982
- const firstOffset = offset;
1983
- let lastOffset = 0;
1984
- let lastWrote = 0;
1985
- for (const fd of this.fields) {
1986
- let span = fd.span;
1987
- lastWrote = (0 < span) ? span : 0;
1988
- if (undefined !== fd.property) {
1989
- const fv = src[fd.property];
1990
- if (undefined !== fv) {
1991
- lastWrote = fd.encode(fv, b, offset);
1992
- if (0 > span) {
1993
- /* Read the as-encoded span, which is not necessarily the
1994
- * same as what we wrote. */
1995
- span = fd.getSpan(b, offset);
1996
- }
1997
- }
1998
- }
1999
- lastOffset = offset;
2000
- offset += span;
2001
- }
2002
- /* Use (lastOffset + lastWrote) instead of offset because the last
2003
- * item may have had a dynamic length and we don't want to include
2004
- * the padding between it and the end of the space reserved for
2005
- * it. */
2006
- return (lastOffset + lastWrote) - firstOffset;
2007
- }
2008
- /** @override */
2009
- fromArray(values) {
2010
- const dest = this.makeDestinationObject();
2011
- for (const fd of this.fields) {
2012
- if ((undefined !== fd.property)
2013
- && (0 < values.length)) {
2014
- dest[fd.property] = values.shift();
2015
- }
2016
- }
2017
- return dest;
2018
- }
2019
- /**
2020
- * Get access to the layout of a given property.
2021
- *
2022
- * @param {String} property - the structure member of interest.
2023
- *
2024
- * @return {Layout} - the layout associated with `property`, or
2025
- * undefined if there is no such property.
2026
- */
2027
- layoutFor(property) {
2028
- if ('string' !== typeof property) {
2029
- throw new TypeError('property must be string');
2030
- }
2031
- for (const fd of this.fields) {
2032
- if (fd.property === property) {
2033
- return fd;
2034
- }
2035
- }
2036
- return undefined;
2037
- }
2038
- /**
2039
- * Get the offset of a structure member.
2040
- *
2041
- * @param {String} property - the structure member of interest.
2042
- *
2043
- * @return {Number} - the offset in bytes to the start of `property`
2044
- * within the structure, or undefined if `property` is not a field
2045
- * within the structure. If the property is a member but follows a
2046
- * variable-length structure member a negative number will be
2047
- * returned.
2048
- */
2049
- offsetOf(property) {
2050
- if ('string' !== typeof property) {
2051
- throw new TypeError('property must be string');
2052
- }
2053
- let offset = 0;
2054
- for (const fd of this.fields) {
2055
- if (fd.property === property) {
2056
- return offset;
2057
- }
2058
- if (0 > fd.span) {
2059
- offset = -1;
2060
- }
2061
- else if (0 <= offset) {
2062
- offset += fd.span;
2063
- }
2064
- }
2065
- return undefined;
2066
- }
2067
- }
2068
- Layout$1.Structure = Structure;
2069
- /**
2070
- * An object that can provide a {@link
2071
- * Union#discriminator|discriminator} API for {@link Union}.
2072
- *
2073
- * **NOTE** This is an abstract base class; you can create instances
2074
- * if it amuses you, but they won't support the {@link
2075
- * UnionDiscriminator#encode|encode} or {@link
2076
- * UnionDiscriminator#decode|decode} functions.
2077
- *
2078
- * @param {string} [property] - Default for {@link
2079
- * UnionDiscriminator#property|property}.
2080
- *
2081
- * @abstract
2082
- */
2083
- class UnionDiscriminator {
2084
- constructor(property) {
2085
- /** The {@link Layout#property|property} to be used when the
2086
- * discriminator is referenced in isolation (generally when {@link
2087
- * Union#decode|Union decode} cannot delegate to a specific
2088
- * variant). */
2089
- this.property = property;
2090
- }
2091
- /** Analog to {@link Layout#decode|Layout decode} for union discriminators.
2092
- *
2093
- * The implementation of this method need not reference the buffer if
2094
- * variant information is available through other means. */
2095
- decode(b, offset) {
2096
- throw new Error('UnionDiscriminator is abstract');
2097
- }
2098
- /** Analog to {@link Layout#decode|Layout encode} for union discriminators.
2099
- *
2100
- * The implementation of this method need not store the value if
2101
- * variant information is maintained through other means. */
2102
- encode(src, b, offset) {
2103
- throw new Error('UnionDiscriminator is abstract');
2104
- }
2105
- }
2106
- Layout$1.UnionDiscriminator = UnionDiscriminator;
2107
- /**
2108
- * An object that can provide a {@link
2109
- * UnionDiscriminator|discriminator API} for {@link Union} using an
2110
- * unsigned integral {@link Layout} instance located either inside or
2111
- * outside the union.
2112
- *
2113
- * @param {ExternalLayout} layout - initializes {@link
2114
- * UnionLayoutDiscriminator#layout|layout}. Must satisfy {@link
2115
- * ExternalLayout#isCount|isCount()}.
2116
- *
2117
- * @param {string} [property] - Default for {@link
2118
- * UnionDiscriminator#property|property}, superseding the property
2119
- * from `layout`, but defaulting to `variant` if neither `property`
2120
- * nor layout provide a property name.
2121
- *
2122
- * @augments {UnionDiscriminator}
2123
- */
2124
- class UnionLayoutDiscriminator extends UnionDiscriminator {
2125
- constructor(layout, property) {
2126
- if (!((layout instanceof ExternalLayout)
2127
- && layout.isCount())) {
2128
- throw new TypeError('layout must be an unsigned integer ExternalLayout');
2129
- }
2130
- super(property || layout.property || 'variant');
2131
- /** The {@link ExternalLayout} used to access the discriminator
2132
- * value. */
2133
- this.layout = layout;
2134
- }
2135
- /** Delegate decoding to {@link UnionLayoutDiscriminator#layout|layout}. */
2136
- decode(b, offset) {
2137
- return this.layout.decode(b, offset);
2138
- }
2139
- /** Delegate encoding to {@link UnionLayoutDiscriminator#layout|layout}. */
2140
- encode(src, b, offset) {
2141
- return this.layout.encode(src, b, offset);
2142
- }
2143
- }
2144
- Layout$1.UnionLayoutDiscriminator = UnionLayoutDiscriminator;
2145
- /**
2146
- * Represent any number of span-compatible layouts.
2147
- *
2148
- * *Factory*: {@link module:Layout.union|union}
2149
- *
2150
- * If the union has a {@link Union#defaultLayout|default layout} that
2151
- * layout must have a non-negative {@link Layout#span|span}. The span
2152
- * of a fixed-span union includes its {@link
2153
- * Union#discriminator|discriminator} if the variant is a {@link
2154
- * Union#usesPrefixDiscriminator|prefix of the union}, plus the span
2155
- * of its {@link Union#defaultLayout|default layout}.
2156
- *
2157
- * If the union does not have a default layout then the encoded span
2158
- * of the union depends on the encoded span of its variant (which may
2159
- * be fixed or variable).
2160
- *
2161
- * {@link VariantLayout#layout|Variant layout}s are added through
2162
- * {@link Union#addVariant|addVariant}. If the union has a default
2163
- * layout, the span of the {@link VariantLayout#layout|layout
2164
- * contained by the variant} must not exceed the span of the {@link
2165
- * Union#defaultLayout|default layout} (minus the span of a {@link
2166
- * Union#usesPrefixDiscriminator|prefix disriminator}, if used). The
2167
- * span of the variant will equal the span of the union itself.
2168
- *
2169
- * The variant for a buffer can only be identified from the {@link
2170
- * Union#discriminator|discriminator} {@link
2171
- * UnionDiscriminator#property|property} (in the case of the {@link
2172
- * Union#defaultLayout|default layout}), or by using {@link
2173
- * Union#getVariant|getVariant} and examining the resulting {@link
2174
- * VariantLayout} instance.
2175
- *
2176
- * A variant compatible with a JavaScript object can be identified
2177
- * using {@link Union#getSourceVariant|getSourceVariant}.
2178
- *
2179
- * @param {(UnionDiscriminator|ExternalLayout|Layout)} discr - How to
2180
- * identify the layout used to interpret the union contents. The
2181
- * parameter must be an instance of {@link UnionDiscriminator}, an
2182
- * {@link ExternalLayout} that satisfies {@link
2183
- * ExternalLayout#isCount|isCount()}, or {@link UInt} (or {@link
2184
- * UIntBE}). When a non-external layout element is passed the layout
2185
- * appears at the start of the union. In all cases the (synthesized)
2186
- * {@link UnionDiscriminator} instance is recorded as {@link
2187
- * Union#discriminator|discriminator}.
2188
- *
2189
- * @param {(Layout|null)} defaultLayout - initializer for {@link
2190
- * Union#defaultLayout|defaultLayout}. If absent defaults to `null`.
2191
- * If `null` there is no default layout: the union has data-dependent
2192
- * length and attempts to decode or encode unrecognized variants will
2193
- * throw an exception. A {@link Layout} instance must have a
2194
- * non-negative {@link Layout#span|span}, and if it lacks a {@link
2195
- * Layout#property|property} the {@link
2196
- * Union#defaultLayout|defaultLayout} will be a {@link
2197
- * Layout#replicate|replica} with property `content`.
2198
- *
2199
- * @param {string} [property] - initializer for {@link
2200
- * Layout#property|property}.
2201
- *
2202
- * @augments {Layout}
2203
- */
2204
- class Union extends Layout {
2205
- constructor(discr, defaultLayout, property) {
2206
- let discriminator;
2207
- if ((discr instanceof UInt)
2208
- || (discr instanceof UIntBE)) {
2209
- discriminator = new UnionLayoutDiscriminator(new OffsetLayout(discr));
2210
- }
2211
- else if ((discr instanceof ExternalLayout)
2212
- && discr.isCount()) {
2213
- discriminator = new UnionLayoutDiscriminator(discr);
2214
- }
2215
- else if (!(discr instanceof UnionDiscriminator)) {
2216
- throw new TypeError('discr must be a UnionDiscriminator '
2217
- + 'or an unsigned integer layout');
2218
- }
2219
- else {
2220
- discriminator = discr;
2221
- }
2222
- if (undefined === defaultLayout) {
2223
- defaultLayout = null;
2224
- }
2225
- if (!((null === defaultLayout)
2226
- || (defaultLayout instanceof Layout))) {
2227
- throw new TypeError('defaultLayout must be null or a Layout');
2228
- }
2229
- if (null !== defaultLayout) {
2230
- if (0 > defaultLayout.span) {
2231
- throw new Error('defaultLayout must have constant span');
2232
- }
2233
- if (undefined === defaultLayout.property) {
2234
- defaultLayout = defaultLayout.replicate('content');
2235
- }
2236
- }
2237
- /* The union span can be estimated only if there's a default
2238
- * layout. The union spans its default layout, plus any prefix
2239
- * variant layout. By construction both layouts, if present, have
2240
- * non-negative span. */
2241
- let span = -1;
2242
- if (defaultLayout) {
2243
- span = defaultLayout.span;
2244
- if ((0 <= span) && ((discr instanceof UInt)
2245
- || (discr instanceof UIntBE))) {
2246
- span += discriminator.layout.span;
2247
- }
2248
- }
2249
- super(span, property);
2250
- /** The interface for the discriminator value in isolation.
2251
- *
2252
- * This a {@link UnionDiscriminator} either passed to the
2253
- * constructor or synthesized from the `discr` constructor
2254
- * argument. {@link
2255
- * Union#usesPrefixDiscriminator|usesPrefixDiscriminator} will be
2256
- * `true` iff the `discr` parameter was a non-offset {@link
2257
- * Layout} instance. */
2258
- this.discriminator = discriminator;
2259
- /** `true` if the {@link Union#discriminator|discriminator} is the
2260
- * first field in the union.
2261
- *
2262
- * If `false` the discriminator is obtained from somewhere
2263
- * else. */
2264
- this.usesPrefixDiscriminator = (discr instanceof UInt)
2265
- || (discr instanceof UIntBE);
2266
- /** The layout for non-discriminator content when the value of the
2267
- * discriminator is not recognized.
2268
- *
2269
- * This is the value passed to the constructor. It is
2270
- * structurally equivalent to the second component of {@link
2271
- * Union#layout|layout} but may have a different property
2272
- * name. */
2273
- this.defaultLayout = defaultLayout;
2274
- /** A registry of allowed variants.
2275
- *
2276
- * The keys are unsigned integers which should be compatible with
2277
- * {@link Union.discriminator|discriminator}. The property value
2278
- * is the corresponding {@link VariantLayout} instances assigned
2279
- * to this union by {@link Union#addVariant|addVariant}.
2280
- *
2281
- * **NOTE** The registry remains mutable so that variants can be
2282
- * {@link Union#addVariant|added} at any time. Users should not
2283
- * manipulate the content of this property. */
2284
- this.registry = {};
2285
- /* Private variable used when invoking getSourceVariant */
2286
- let boundGetSourceVariant = this.defaultGetSourceVariant.bind(this);
2287
- /** Function to infer the variant selected by a source object.
2288
- *
2289
- * Defaults to {@link
2290
- * Union#defaultGetSourceVariant|defaultGetSourceVariant} but may
2291
- * be overridden using {@link
2292
- * Union#configGetSourceVariant|configGetSourceVariant}.
2293
- *
2294
- * @param {Object} src - as with {@link
2295
- * Union#defaultGetSourceVariant|defaultGetSourceVariant}.
2296
- *
2297
- * @returns {(undefined|VariantLayout)} The default variant
2298
- * (`undefined`) or first registered variant that uses a property
2299
- * available in `src`. */
2300
- this.getSourceVariant = function (src) {
2301
- return boundGetSourceVariant(src);
2302
- };
2303
- /** Function to override the implementation of {@link
2304
- * Union#getSourceVariant|getSourceVariant}.
2305
- *
2306
- * Use this if the desired variant cannot be identified using the
2307
- * algorithm of {@link
2308
- * Union#defaultGetSourceVariant|defaultGetSourceVariant}.
2309
- *
2310
- * **NOTE** The provided function will be invoked bound to this
2311
- * Union instance, providing local access to {@link
2312
- * Union#registry|registry}.
2313
- *
2314
- * @param {Function} gsv - a function that follows the API of
2315
- * {@link Union#defaultGetSourceVariant|defaultGetSourceVariant}. */
2316
- this.configGetSourceVariant = function (gsv) {
2317
- boundGetSourceVariant = gsv.bind(this);
2318
- };
2319
- }
2320
- /** @override */
2321
- getSpan(b, offset = 0) {
2322
- if (0 <= this.span) {
2323
- return this.span;
2324
- }
2325
- /* Default layouts always have non-negative span, so we don't have
2326
- * one and we have to recognize the variant which will in turn
2327
- * determine the span. */
2328
- const vlo = this.getVariant(b, offset);
2329
- if (!vlo) {
2330
- throw new Error('unable to determine span for unrecognized variant');
2331
- }
2332
- return vlo.getSpan(b, offset);
2333
- }
2334
- /**
2335
- * Method to infer a registered Union variant compatible with `src`.
2336
- *
2337
- * The first satisfied rule in the following sequence defines the
2338
- * return value:
2339
- * * If `src` has properties matching the Union discriminator and
2340
- * the default layout, `undefined` is returned regardless of the
2341
- * value of the discriminator property (this ensures the default
2342
- * layout will be used);
2343
- * * If `src` has a property matching the Union discriminator, the
2344
- * value of the discriminator identifies a registered variant, and
2345
- * either (a) the variant has no layout, or (b) `src` has the
2346
- * variant's property, then the variant is returned (because the
2347
- * source satisfies the constraints of the variant it identifies);
2348
- * * If `src` does not have a property matching the Union
2349
- * discriminator, but does have a property matching a registered
2350
- * variant, then the variant is returned (because the source
2351
- * matches a variant without an explicit conflict);
2352
- * * An error is thrown (because we either can't identify a variant,
2353
- * or we were explicitly told the variant but can't satisfy it).
2354
- *
2355
- * @param {Object} src - an object presumed to be compatible with
2356
- * the content of the Union.
2357
- *
2358
- * @return {(undefined|VariantLayout)} - as described above.
2359
- *
2360
- * @throws {Error} - if `src` cannot be associated with a default or
2361
- * registered variant.
2362
- */
2363
- defaultGetSourceVariant(src) {
2364
- if (Object.prototype.hasOwnProperty.call(src, this.discriminator.property)) {
2365
- if (this.defaultLayout && this.defaultLayout.property
2366
- && Object.prototype.hasOwnProperty.call(src, this.defaultLayout.property)) {
2367
- return undefined;
2368
- }
2369
- const vlo = this.registry[src[this.discriminator.property]];
2370
- if (vlo
2371
- && ((!vlo.layout)
2372
- || (vlo.property && Object.prototype.hasOwnProperty.call(src, vlo.property)))) {
2373
- return vlo;
2374
- }
2375
- }
2376
- else {
2377
- for (const tag in this.registry) {
2378
- const vlo = this.registry[tag];
2379
- if (vlo.property && Object.prototype.hasOwnProperty.call(src, vlo.property)) {
2380
- return vlo;
2381
- }
2382
- }
2383
- }
2384
- throw new Error('unable to infer src variant');
2385
- }
2386
- /** Implement {@link Layout#decode|decode} for {@link Union}.
2387
- *
2388
- * If the variant is {@link Union#addVariant|registered} the return
2389
- * value is an instance of that variant, with no explicit
2390
- * discriminator. Otherwise the {@link Union#defaultLayout|default
2391
- * layout} is used to decode the content. */
2392
- decode(b, offset = 0) {
2393
- let dest;
2394
- const dlo = this.discriminator;
2395
- const discr = dlo.decode(b, offset);
2396
- const clo = this.registry[discr];
2397
- if (undefined === clo) {
2398
- const defaultLayout = this.defaultLayout;
2399
- let contentOffset = 0;
2400
- if (this.usesPrefixDiscriminator) {
2401
- contentOffset = dlo.layout.span;
2402
- }
2403
- dest = this.makeDestinationObject();
2404
- dest[dlo.property] = discr;
2405
- // defaultLayout.property can be undefined, but this is allowed by buffer-layout
2406
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2407
- dest[defaultLayout.property] = defaultLayout.decode(b, offset + contentOffset);
2408
- }
2409
- else {
2410
- dest = clo.decode(b, offset);
2411
- }
2412
- return dest;
2413
- }
2414
- /** Implement {@link Layout#encode|encode} for {@link Union}.
2415
- *
2416
- * This API assumes the `src` object is consistent with the union's
2417
- * {@link Union#defaultLayout|default layout}. To encode variants
2418
- * use the appropriate variant-specific {@link VariantLayout#encode}
2419
- * method. */
2420
- encode(src, b, offset = 0) {
2421
- const vlo = this.getSourceVariant(src);
2422
- if (undefined === vlo) {
2423
- const dlo = this.discriminator;
2424
- // this.defaultLayout is not undefined when vlo is undefined
2425
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2426
- const clo = this.defaultLayout;
2427
- let contentOffset = 0;
2428
- if (this.usesPrefixDiscriminator) {
2429
- contentOffset = dlo.layout.span;
2430
- }
2431
- dlo.encode(src[dlo.property], b, offset);
2432
- // clo.property is not undefined when vlo is undefined
2433
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2434
- return contentOffset + clo.encode(src[clo.property], b, offset + contentOffset);
2435
- }
2436
- return vlo.encode(src, b, offset);
2437
- }
2438
- /** Register a new variant structure within a union. The newly
2439
- * created variant is returned.
2440
- *
2441
- * @param {Number} variant - initializer for {@link
2442
- * VariantLayout#variant|variant}.
2443
- *
2444
- * @param {Layout} layout - initializer for {@link
2445
- * VariantLayout#layout|layout}.
2446
- *
2447
- * @param {String} property - initializer for {@link
2448
- * Layout#property|property}.
2449
- *
2450
- * @return {VariantLayout} */
2451
- addVariant(variant, layout, property) {
2452
- const rv = new VariantLayout(this, variant, layout, property);
2453
- this.registry[variant] = rv;
2454
- return rv;
2455
- }
2456
- /**
2457
- * Get the layout associated with a registered variant.
2458
- *
2459
- * If `vb` does not produce a registered variant the function returns
2460
- * `undefined`.
2461
- *
2462
- * @param {(Number|Uint8Array)} vb - either the variant number, or a
2463
- * buffer from which the discriminator is to be read.
2464
- *
2465
- * @param {Number} offset - offset into `vb` for the start of the
2466
- * union. Used only when `vb` is an instance of {Uint8Array}.
2467
- *
2468
- * @return {({VariantLayout}|undefined)}
2469
- */
2470
- getVariant(vb, offset = 0) {
2471
- let variant;
2472
- if (vb instanceof Uint8Array) {
2473
- variant = this.discriminator.decode(vb, offset);
2474
- }
2475
- else {
2476
- variant = vb;
2477
- }
2478
- return this.registry[variant];
2479
- }
2480
- }
2481
- Layout$1.Union = Union;
2482
- /**
2483
- * Represent a specific variant within a containing union.
2484
- *
2485
- * **NOTE** The {@link Layout#span|span} of the variant may include
2486
- * the span of the {@link Union#discriminator|discriminator} used to
2487
- * identify it, but values read and written using the variant strictly
2488
- * conform to the content of {@link VariantLayout#layout|layout}.
2489
- *
2490
- * **NOTE** User code should not invoke this constructor directly. Use
2491
- * the union {@link Union#addVariant|addVariant} helper method.
2492
- *
2493
- * @param {Union} union - initializer for {@link
2494
- * VariantLayout#union|union}.
2495
- *
2496
- * @param {Number} variant - initializer for {@link
2497
- * VariantLayout#variant|variant}.
2498
- *
2499
- * @param {Layout} [layout] - initializer for {@link
2500
- * VariantLayout#layout|layout}. If absent the variant carries no
2501
- * data.
2502
- *
2503
- * @param {String} [property] - initializer for {@link
2504
- * Layout#property|property}. Unlike many other layouts, variant
2505
- * layouts normally include a property name so they can be identified
2506
- * within their containing {@link Union}. The property identifier may
2507
- * be absent only if `layout` is is absent.
2508
- *
2509
- * @augments {Layout}
2510
- */
2511
- class VariantLayout extends Layout {
2512
- constructor(union, variant, layout, property) {
2513
- if (!(union instanceof Union)) {
2514
- throw new TypeError('union must be a Union');
2515
- }
2516
- if ((!Number.isInteger(variant)) || (0 > variant)) {
2517
- throw new TypeError('variant must be a (non-negative) integer');
2518
- }
2519
- if (('string' === typeof layout)
2520
- && (undefined === property)) {
2521
- property = layout;
2522
- layout = null;
2523
- }
2524
- if (layout) {
2525
- if (!(layout instanceof Layout)) {
2526
- throw new TypeError('layout must be a Layout');
2527
- }
2528
- if ((null !== union.defaultLayout)
2529
- && (0 <= layout.span)
2530
- && (layout.span > union.defaultLayout.span)) {
2531
- throw new Error('variant span exceeds span of containing union');
2532
- }
2533
- if ('string' !== typeof property) {
2534
- throw new TypeError('variant must have a String property');
2535
- }
2536
- }
2537
- let span = union.span;
2538
- if (0 > union.span) {
2539
- span = layout ? layout.span : 0;
2540
- if ((0 <= span) && union.usesPrefixDiscriminator) {
2541
- span += union.discriminator.layout.span;
2542
- }
2543
- }
2544
- super(span, property);
2545
- /** The {@link Union} to which this variant belongs. */
2546
- this.union = union;
2547
- /** The unsigned integral value identifying this variant within
2548
- * the {@link Union#discriminator|discriminator} of the containing
2549
- * union. */
2550
- this.variant = variant;
2551
- /** The {@link Layout} to be used when reading/writing the
2552
- * non-discriminator part of the {@link
2553
- * VariantLayout#union|union}. If `null` the variant carries no
2554
- * data. */
2555
- this.layout = layout || null;
2556
- }
2557
- /** @override */
2558
- getSpan(b, offset = 0) {
2559
- if (0 <= this.span) {
2560
- /* Will be equal to the containing union span if that is not
2561
- * variable. */
2562
- return this.span;
2563
- }
2564
- let contentOffset = 0;
2565
- if (this.union.usesPrefixDiscriminator) {
2566
- contentOffset = this.union.discriminator.layout.span;
2567
- }
2568
- /* Span is defined solely by the variant (and prefix discriminator) */
2569
- let span = 0;
2570
- if (this.layout) {
2571
- span = this.layout.getSpan(b, offset + contentOffset);
2572
- }
2573
- return contentOffset + span;
2574
- }
2575
- /** @override */
2576
- decode(b, offset = 0) {
2577
- const dest = this.makeDestinationObject();
2578
- if (this !== this.union.getVariant(b, offset)) {
2579
- throw new Error('variant mismatch');
2580
- }
2581
- let contentOffset = 0;
2582
- if (this.union.usesPrefixDiscriminator) {
2583
- contentOffset = this.union.discriminator.layout.span;
2584
- }
2585
- if (this.layout) {
2586
- dest[this.property] = this.layout.decode(b, offset + contentOffset);
2587
- }
2588
- else if (this.property) {
2589
- dest[this.property] = true;
2590
- }
2591
- else if (this.union.usesPrefixDiscriminator) {
2592
- dest[this.union.discriminator.property] = this.variant;
2593
- }
2594
- return dest;
2595
- }
2596
- /** @override */
2597
- encode(src, b, offset = 0) {
2598
- let contentOffset = 0;
2599
- if (this.union.usesPrefixDiscriminator) {
2600
- contentOffset = this.union.discriminator.layout.span;
2601
- }
2602
- if (this.layout
2603
- && (!Object.prototype.hasOwnProperty.call(src, this.property))) {
2604
- throw new TypeError('variant lacks property ' + this.property);
2605
- }
2606
- this.union.discriminator.encode(this.variant, b, offset);
2607
- let span = contentOffset;
2608
- if (this.layout) {
2609
- this.layout.encode(src[this.property], b, offset + contentOffset);
2610
- span += this.layout.getSpan(b, offset + contentOffset);
2611
- if ((0 <= this.union.span)
2612
- && (span > this.union.span)) {
2613
- throw new Error('encoded variant overruns containing union');
2614
- }
2615
- }
2616
- return span;
2617
- }
2618
- /** Delegate {@link Layout#fromArray|fromArray} to {@link
2619
- * VariantLayout#layout|layout}. */
2620
- fromArray(values) {
2621
- if (this.layout) {
2622
- return this.layout.fromArray(values);
2623
- }
2624
- return undefined;
2625
- }
2626
- }
2627
- Layout$1.VariantLayout = VariantLayout;
2628
- /** JavaScript chose to define bitwise operations as operating on
2629
- * signed 32-bit values in 2's complement form, meaning any integer
2630
- * with bit 31 set is going to look negative. For right shifts that's
2631
- * not a problem, because `>>>` is a logical shift, but for every
2632
- * other bitwise operator we have to compensate for possible negative
2633
- * results. */
2634
- function fixBitwiseResult(v) {
2635
- if (0 > v) {
2636
- v += 0x100000000;
2637
- }
2638
- return v;
2639
- }
2640
- /**
2641
- * Contain a sequence of bit fields as an unsigned integer.
2642
- *
2643
- * *Factory*: {@link module:Layout.bits|bits}
2644
- *
2645
- * This is a container element; within it there are {@link BitField}
2646
- * instances that provide the extracted properties. The container
2647
- * simply defines the aggregate representation and its bit ordering.
2648
- * The representation is an object containing properties with numeric
2649
- * or {@link Boolean} values.
2650
- *
2651
- * {@link BitField}s are added with the {@link
2652
- * BitStructure#addField|addField} and {@link
2653
- * BitStructure#addBoolean|addBoolean} methods.
2654
-
2655
- * @param {Layout} word - initializer for {@link
2656
- * BitStructure#word|word}. The parameter must be an instance of
2657
- * {@link UInt} (or {@link UIntBE}) that is no more than 4 bytes wide.
2658
- *
2659
- * @param {bool} [msb] - `true` if the bit numbering starts at the
2660
- * most significant bit of the containing word; `false` (default) if
2661
- * it starts at the least significant bit of the containing word. If
2662
- * the parameter at this position is a string and `property` is
2663
- * `undefined` the value of this argument will instead be used as the
2664
- * value of `property`.
2665
- *
2666
- * @param {string} [property] - initializer for {@link
2667
- * Layout#property|property}.
2668
- *
2669
- * @augments {Layout}
2670
- */
2671
- class BitStructure extends Layout {
2672
- constructor(word, msb, property) {
2673
- if (!((word instanceof UInt)
2674
- || (word instanceof UIntBE))) {
2675
- throw new TypeError('word must be a UInt or UIntBE layout');
2676
- }
2677
- if (('string' === typeof msb)
2678
- && (undefined === property)) {
2679
- property = msb;
2680
- msb = false;
2681
- }
2682
- if (4 < word.span) {
2683
- throw new RangeError('word cannot exceed 32 bits');
2684
- }
2685
- super(word.span, property);
2686
- /** The layout used for the packed value. {@link BitField}
2687
- * instances are packed sequentially depending on {@link
2688
- * BitStructure#msb|msb}. */
2689
- this.word = word;
2690
- /** Whether the bit sequences are packed starting at the most
2691
- * significant bit growing down (`true`), or the least significant
2692
- * bit growing up (`false`).
2693
- *
2694
- * **NOTE** Regardless of this value, the least significant bit of
2695
- * any {@link BitField} value is the least significant bit of the
2696
- * corresponding section of the packed value. */
2697
- this.msb = !!msb;
2698
- /** The sequence of {@link BitField} layouts that comprise the
2699
- * packed structure.
2700
- *
2701
- * **NOTE** The array remains mutable to allow fields to be {@link
2702
- * BitStructure#addField|added} after construction. Users should
2703
- * not manipulate the content of this property.*/
2704
- this.fields = [];
2705
- /* Storage for the value. Capture a variable instead of using an
2706
- * instance property because we don't want anything to change the
2707
- * value without going through the mutator. */
2708
- let value = 0;
2709
- this._packedSetValue = function (v) {
2710
- value = fixBitwiseResult(v);
2711
- return this;
2712
- };
2713
- this._packedGetValue = function () {
2714
- return value;
2715
- };
2716
- }
2717
- /** @override */
2718
- decode(b, offset = 0) {
2719
- const dest = this.makeDestinationObject();
2720
- const value = this.word.decode(b, offset);
2721
- this._packedSetValue(value);
2722
- for (const fd of this.fields) {
2723
- if (undefined !== fd.property) {
2724
- dest[fd.property] = fd.decode(b);
2725
- }
2726
- }
2727
- return dest;
2728
- }
2729
- /** Implement {@link Layout#encode|encode} for {@link BitStructure}.
2730
- *
2731
- * If `src` is missing a property for a member with a defined {@link
2732
- * Layout#property|property} the corresponding region of the packed
2733
- * value is left unmodified. Unused bits are also left unmodified. */
2734
- encode(src, b, offset = 0) {
2735
- const value = this.word.decode(b, offset);
2736
- this._packedSetValue(value);
2737
- for (const fd of this.fields) {
2738
- if (undefined !== fd.property) {
2739
- const fv = src[fd.property];
2740
- if (undefined !== fv) {
2741
- fd.encode(fv);
2742
- }
2743
- }
2744
- }
2745
- return this.word.encode(this._packedGetValue(), b, offset);
2746
- }
2747
- /** Register a new bitfield with a containing bit structure. The
2748
- * resulting bitfield is returned.
2749
- *
2750
- * @param {Number} bits - initializer for {@link BitField#bits|bits}.
2751
- *
2752
- * @param {string} property - initializer for {@link
2753
- * Layout#property|property}.
2754
- *
2755
- * @return {BitField} */
2756
- addField(bits, property) {
2757
- const bf = new BitField(this, bits, property);
2758
- this.fields.push(bf);
2759
- return bf;
2760
- }
2761
- /** As with {@link BitStructure#addField|addField} for single-bit
2762
- * fields with `boolean` value representation.
2763
- *
2764
- * @param {string} property - initializer for {@link
2765
- * Layout#property|property}.
2766
- *
2767
- * @return {Boolean} */
2768
- // `Boolean` conflicts with the native primitive type
2769
- // eslint-disable-next-line @typescript-eslint/ban-types
2770
- addBoolean(property) {
2771
- // This is my Boolean, not the Javascript one.
2772
- const bf = new Boolean(this, property);
2773
- this.fields.push(bf);
2774
- return bf;
2775
- }
2776
- /**
2777
- * Get access to the bit field for a given property.
2778
- *
2779
- * @param {String} property - the bit field of interest.
2780
- *
2781
- * @return {BitField} - the field associated with `property`, or
2782
- * undefined if there is no such property.
2783
- */
2784
- fieldFor(property) {
2785
- if ('string' !== typeof property) {
2786
- throw new TypeError('property must be string');
2787
- }
2788
- for (const fd of this.fields) {
2789
- if (fd.property === property) {
2790
- return fd;
2791
- }
2792
- }
2793
- return undefined;
2794
- }
2795
- }
2796
- Layout$1.BitStructure = BitStructure;
2797
- /**
2798
- * Represent a sequence of bits within a {@link BitStructure}.
2799
- *
2800
- * All bit field values are represented as unsigned integers.
2801
- *
2802
- * **NOTE** User code should not invoke this constructor directly.
2803
- * Use the container {@link BitStructure#addField|addField} helper
2804
- * method.
2805
- *
2806
- * **NOTE** BitField instances are not instances of {@link Layout}
2807
- * since {@link Layout#span|span} measures 8-bit units.
2808
- *
2809
- * @param {BitStructure} container - initializer for {@link
2810
- * BitField#container|container}.
2811
- *
2812
- * @param {Number} bits - initializer for {@link BitField#bits|bits}.
2813
- *
2814
- * @param {string} [property] - initializer for {@link
2815
- * Layout#property|property}.
2816
- */
2817
- class BitField {
2818
- constructor(container, bits, property) {
2819
- if (!(container instanceof BitStructure)) {
2820
- throw new TypeError('container must be a BitStructure');
2821
- }
2822
- if ((!Number.isInteger(bits)) || (0 >= bits)) {
2823
- throw new TypeError('bits must be positive integer');
2824
- }
2825
- const totalBits = 8 * container.span;
2826
- const usedBits = container.fields.reduce((sum, fd) => sum + fd.bits, 0);
2827
- if ((bits + usedBits) > totalBits) {
2828
- throw new Error('bits too long for span remainder ('
2829
- + (totalBits - usedBits) + ' of '
2830
- + totalBits + ' remain)');
2831
- }
2832
- /** The {@link BitStructure} instance to which this bit field
2833
- * belongs. */
2834
- this.container = container;
2835
- /** The span of this value in bits. */
2836
- this.bits = bits;
2837
- /** A mask of {@link BitField#bits|bits} bits isolating value bits
2838
- * that fit within the field.
2839
- *
2840
- * That is, it masks a value that has not yet been shifted into
2841
- * position within its containing packed integer. */
2842
- this.valueMask = (1 << bits) - 1;
2843
- if (32 === bits) { // shifted value out of range
2844
- this.valueMask = 0xFFFFFFFF;
2845
- }
2846
- /** The offset of the value within the containing packed unsigned
2847
- * integer. The least significant bit of the packed value is at
2848
- * offset zero, regardless of bit ordering used. */
2849
- this.start = usedBits;
2850
- if (this.container.msb) {
2851
- this.start = totalBits - usedBits - bits;
2852
- }
2853
- /** A mask of {@link BitField#bits|bits} isolating the field value
2854
- * within the containing packed unsigned integer. */
2855
- this.wordMask = fixBitwiseResult(this.valueMask << this.start);
2856
- /** The property name used when this bitfield is represented in an
2857
- * Object.
2858
- *
2859
- * Intended to be functionally equivalent to {@link
2860
- * Layout#property}.
2861
- *
2862
- * If left undefined the corresponding span of bits will be
2863
- * treated as padding: it will not be mutated by {@link
2864
- * Layout#encode|encode} nor represented as a property in the
2865
- * decoded Object. */
2866
- this.property = property;
2867
- }
2868
- /** Store a value into the corresponding subsequence of the containing
2869
- * bit field. */
2870
- decode(b, offset) {
2871
- const word = this.container._packedGetValue();
2872
- const wordValue = fixBitwiseResult(word & this.wordMask);
2873
- const value = wordValue >>> this.start;
2874
- return value;
2875
- }
2876
- /** Store a value into the corresponding subsequence of the containing
2877
- * bit field.
2878
- *
2879
- * **NOTE** This is not a specialization of {@link
2880
- * Layout#encode|Layout.encode} and there is no return value. */
2881
- encode(value) {
2882
- if ('number' !== typeof value
2883
- || !Number.isInteger(value)
2884
- || (value !== fixBitwiseResult(value & this.valueMask))) {
2885
- throw new TypeError(nameWithProperty('BitField.encode', this)
2886
- + ' value must be integer not exceeding ' + this.valueMask);
2887
- }
2888
- const word = this.container._packedGetValue();
2889
- const wordValue = fixBitwiseResult(value << this.start);
2890
- this.container._packedSetValue(fixBitwiseResult(word & ~this.wordMask)
2891
- | wordValue);
2892
- }
2893
- }
2894
- Layout$1.BitField = BitField;
2895
- /**
2896
- * Represent a single bit within a {@link BitStructure} as a
2897
- * JavaScript boolean.
2898
- *
2899
- * **NOTE** User code should not invoke this constructor directly.
2900
- * Use the container {@link BitStructure#addBoolean|addBoolean} helper
2901
- * method.
2902
- *
2903
- * @param {BitStructure} container - initializer for {@link
2904
- * BitField#container|container}.
2905
- *
2906
- * @param {string} [property] - initializer for {@link
2907
- * Layout#property|property}.
2908
- *
2909
- * @augments {BitField}
2910
- */
2911
- /* eslint-disable no-extend-native */
2912
- class Boolean extends BitField {
2913
- constructor(container, property) {
2914
- super(container, 1, property);
2915
- }
2916
- /** Override {@link BitField#decode|decode} for {@link Boolean|Boolean}.
2917
- *
2918
- * @returns {boolean} */
2919
- decode(b, offset) {
2920
- return !!super.decode(b, offset);
2921
- }
2922
- /** @override */
2923
- encode(value) {
2924
- if ('boolean' === typeof value) {
2925
- // BitField requires integer values
2926
- value = +value;
2927
- }
2928
- super.encode(value);
2929
- }
2930
- }
2931
- Layout$1.Boolean = Boolean;
2932
- /* eslint-enable no-extend-native */
2933
- /**
2934
- * Contain a fixed-length block of arbitrary data, represented as a
2935
- * Uint8Array.
2936
- *
2937
- * *Factory*: {@link module:Layout.blob|blob}
2938
- *
2939
- * @param {(Number|ExternalLayout)} length - initializes {@link
2940
- * Blob#length|length}.
2941
- *
2942
- * @param {String} [property] - initializer for {@link
2943
- * Layout#property|property}.
2944
- *
2945
- * @augments {Layout}
2946
- */
2947
- class Blob extends Layout {
2948
- constructor(length, property) {
2949
- if (!(((length instanceof ExternalLayout) && length.isCount())
2950
- || (Number.isInteger(length) && (0 <= length)))) {
2951
- throw new TypeError('length must be positive integer '
2952
- + 'or an unsigned integer ExternalLayout');
2953
- }
2954
- let span = -1;
2955
- if (!(length instanceof ExternalLayout)) {
2956
- span = length;
2957
- }
2958
- super(span, property);
2959
- /** The number of bytes in the blob.
2960
- *
2961
- * This may be a non-negative integer, or an instance of {@link
2962
- * ExternalLayout} that satisfies {@link
2963
- * ExternalLayout#isCount|isCount()}. */
2964
- this.length = length;
2965
- }
2966
- /** @override */
2967
- getSpan(b, offset) {
2968
- let span = this.span;
2969
- if (0 > span) {
2970
- span = this.length.decode(b, offset);
2971
- }
2972
- return span;
2973
- }
2974
- /** @override */
2975
- decode(b, offset = 0) {
2976
- let span = this.span;
2977
- if (0 > span) {
2978
- span = this.length.decode(b, offset);
2979
- }
2980
- return uint8ArrayToBuffer(b).slice(offset, offset + span);
2981
- }
2982
- /** Implement {@link Layout#encode|encode} for {@link Blob}.
2983
- *
2984
- * **NOTE** If {@link Layout#count|count} is an instance of {@link
2985
- * ExternalLayout} then the length of `src` will be encoded as the
2986
- * count after `src` is encoded. */
2987
- encode(src, b, offset) {
2988
- let span = this.length;
2989
- if (this.length instanceof ExternalLayout) {
2990
- span = src.length;
2991
- }
2992
- if (!(src instanceof Uint8Array && span === src.length)) {
2993
- throw new TypeError(nameWithProperty('Blob.encode', this)
2994
- + ' requires (length ' + span + ') Uint8Array as src');
2995
- }
2996
- if ((offset + span) > b.length) {
2997
- throw new RangeError('encoding overruns Uint8Array');
2998
- }
2999
- const srcBuffer = uint8ArrayToBuffer(src);
3000
- uint8ArrayToBuffer(b).write(srcBuffer.toString('hex'), offset, span, 'hex');
3001
- if (this.length instanceof ExternalLayout) {
3002
- this.length.encode(span, b, offset);
3003
- }
3004
- return span;
3005
- }
3006
- }
3007
- Layout$1.Blob = Blob;
3008
- /**
3009
- * Contain a `NUL`-terminated UTF8 string.
3010
- *
3011
- * *Factory*: {@link module:Layout.cstr|cstr}
3012
- *
3013
- * **NOTE** Any UTF8 string that incorporates a zero-valued byte will
3014
- * not be correctly decoded by this layout.
3015
- *
3016
- * @param {String} [property] - initializer for {@link
3017
- * Layout#property|property}.
3018
- *
3019
- * @augments {Layout}
3020
- */
3021
- class CString extends Layout {
3022
- constructor(property) {
3023
- super(-1, property);
3024
- }
3025
- /** @override */
3026
- getSpan(b, offset = 0) {
3027
- checkUint8Array(b);
3028
- let idx = offset;
3029
- while ((idx < b.length) && (0 !== b[idx])) {
3030
- idx += 1;
3031
- }
3032
- return 1 + idx - offset;
3033
- }
3034
- /** @override */
3035
- decode(b, offset = 0) {
3036
- const span = this.getSpan(b, offset);
3037
- return uint8ArrayToBuffer(b).slice(offset, offset + span - 1).toString('utf-8');
3038
- }
3039
- /** @override */
3040
- encode(src, b, offset = 0) {
3041
- /* Must force this to a string, lest it be a number and the
3042
- * "utf8-encoding" below actually allocate a buffer of length
3043
- * src */
3044
- if ('string' !== typeof src) {
3045
- src = String(src);
3046
- }
3047
- const srcb = buffer_1.Buffer.from(src, 'utf8');
3048
- const span = srcb.length;
3049
- if ((offset + span) > b.length) {
3050
- throw new RangeError('encoding overruns Buffer');
3051
- }
3052
- const buffer = uint8ArrayToBuffer(b);
3053
- srcb.copy(buffer, offset);
3054
- buffer[offset + span] = 0;
3055
- return span + 1;
3056
- }
3057
- }
3058
- Layout$1.CString = CString;
3059
- /**
3060
- * Contain a UTF8 string with implicit length.
3061
- *
3062
- * *Factory*: {@link module:Layout.utf8|utf8}
3063
- *
3064
- * **NOTE** Because the length is implicit in the size of the buffer
3065
- * this layout should be used only in isolation, or in a situation
3066
- * where the length can be expressed by operating on a slice of the
3067
- * containing buffer.
3068
- *
3069
- * @param {Number} [maxSpan] - the maximum length allowed for encoded
3070
- * string content. If not provided there is no bound on the allowed
3071
- * content.
3072
- *
3073
- * @param {String} [property] - initializer for {@link
3074
- * Layout#property|property}.
3075
- *
3076
- * @augments {Layout}
3077
- */
3078
- class UTF8 extends Layout {
3079
- constructor(maxSpan, property) {
3080
- if (('string' === typeof maxSpan) && (undefined === property)) {
3081
- property = maxSpan;
3082
- maxSpan = undefined;
3083
- }
3084
- if (undefined === maxSpan) {
3085
- maxSpan = -1;
3086
- }
3087
- else if (!Number.isInteger(maxSpan)) {
3088
- throw new TypeError('maxSpan must be an integer');
3089
- }
3090
- super(-1, property);
3091
- /** The maximum span of the layout in bytes.
3092
- *
3093
- * Positive values are generally expected. Zero is abnormal.
3094
- * Attempts to encode or decode a value that exceeds this length
3095
- * will throw a `RangeError`.
3096
- *
3097
- * A negative value indicates that there is no bound on the length
3098
- * of the content. */
3099
- this.maxSpan = maxSpan;
3100
- }
3101
- /** @override */
3102
- getSpan(b, offset = 0) {
3103
- checkUint8Array(b);
3104
- return b.length - offset;
3105
- }
3106
- /** @override */
3107
- decode(b, offset = 0) {
3108
- const span = this.getSpan(b, offset);
3109
- if ((0 <= this.maxSpan)
3110
- && (this.maxSpan < span)) {
3111
- throw new RangeError('text length exceeds maxSpan');
3112
- }
3113
- return uint8ArrayToBuffer(b).slice(offset, offset + span).toString('utf-8');
3114
- }
3115
- /** @override */
3116
- encode(src, b, offset = 0) {
3117
- /* Must force this to a string, lest it be a number and the
3118
- * "utf8-encoding" below actually allocate a buffer of length
3119
- * src */
3120
- if ('string' !== typeof src) {
3121
- src = String(src);
3122
- }
3123
- const srcb = buffer_1.Buffer.from(src, 'utf8');
3124
- const span = srcb.length;
3125
- if ((0 <= this.maxSpan)
3126
- && (this.maxSpan < span)) {
3127
- throw new RangeError('text length exceeds maxSpan');
3128
- }
3129
- if ((offset + span) > b.length) {
3130
- throw new RangeError('encoding overruns Buffer');
3131
- }
3132
- srcb.copy(uint8ArrayToBuffer(b), offset);
3133
- return span;
3134
- }
3135
- }
3136
- Layout$1.UTF8 = UTF8;
3137
- /**
3138
- * Contain a constant value.
3139
- *
3140
- * This layout may be used in cases where a JavaScript value can be
3141
- * inferred without an expression in the binary encoding. An example
3142
- * would be a {@link VariantLayout|variant layout} where the content
3143
- * is implied by the union {@link Union#discriminator|discriminator}.
3144
- *
3145
- * @param {Object|Number|String} value - initializer for {@link
3146
- * Constant#value|value}. If the value is an object (or array) and
3147
- * the application intends the object to remain unchanged regardless
3148
- * of what is done to values decoded by this layout, the value should
3149
- * be frozen prior passing it to this constructor.
3150
- *
3151
- * @param {String} [property] - initializer for {@link
3152
- * Layout#property|property}.
3153
- *
3154
- * @augments {Layout}
3155
- */
3156
- class Constant extends Layout {
3157
- constructor(value, property) {
3158
- super(0, property);
3159
- /** The value produced by this constant when the layout is {@link
3160
- * Constant#decode|decoded}.
3161
- *
3162
- * Any JavaScript value including `null` and `undefined` is
3163
- * permitted.
3164
- *
3165
- * **WARNING** If `value` passed in the constructor was not
3166
- * frozen, it is possible for users of decoded values to change
3167
- * the content of the value. */
3168
- this.value = value;
3169
- }
3170
- /** @override */
3171
- decode(b, offset) {
3172
- return this.value;
3173
- }
3174
- /** @override */
3175
- encode(src, b, offset) {
3176
- /* Constants take no space */
3177
- return 0;
3178
- }
3179
- }
3180
- Layout$1.Constant = Constant;
3181
- /** Factory for {@link GreedyCount}. */
3182
- Layout$1.greedy = ((elementSpan, property) => new GreedyCount(elementSpan, property));
3183
- /** Factory for {@link OffsetLayout}. */
3184
- Layout$1.offset = ((layout, offset, property) => new OffsetLayout(layout, offset, property));
3185
- /** Factory for {@link UInt|unsigned int layouts} spanning one
3186
- * byte. */
3187
- var u8 = Layout$1.u8 = ((property) => new UInt(1, property));
3188
- /** Factory for {@link UInt|little-endian unsigned int layouts}
3189
- * spanning two bytes. */
3190
- Layout$1.u16 = ((property) => new UInt(2, property));
3191
- /** Factory for {@link UInt|little-endian unsigned int layouts}
3192
- * spanning three bytes. */
3193
- Layout$1.u24 = ((property) => new UInt(3, property));
3194
- /** Factory for {@link UInt|little-endian unsigned int layouts}
3195
- * spanning four bytes. */
3196
- var u32 = Layout$1.u32 = ((property) => new UInt(4, property));
3197
- /** Factory for {@link UInt|little-endian unsigned int layouts}
3198
- * spanning five bytes. */
3199
- Layout$1.u40 = ((property) => new UInt(5, property));
3200
- /** Factory for {@link UInt|little-endian unsigned int layouts}
3201
- * spanning six bytes. */
3202
- Layout$1.u48 = ((property) => new UInt(6, property));
3203
- /** Factory for {@link NearUInt64|little-endian unsigned int
3204
- * layouts} interpreted as Numbers. */
3205
- Layout$1.nu64 = ((property) => new NearUInt64(property));
3206
- /** Factory for {@link UInt|big-endian unsigned int layouts}
3207
- * spanning two bytes. */
3208
- Layout$1.u16be = ((property) => new UIntBE(2, property));
3209
- /** Factory for {@link UInt|big-endian unsigned int layouts}
3210
- * spanning three bytes. */
3211
- Layout$1.u24be = ((property) => new UIntBE(3, property));
3212
- /** Factory for {@link UInt|big-endian unsigned int layouts}
3213
- * spanning four bytes. */
3214
- Layout$1.u32be = ((property) => new UIntBE(4, property));
3215
- /** Factory for {@link UInt|big-endian unsigned int layouts}
3216
- * spanning five bytes. */
3217
- Layout$1.u40be = ((property) => new UIntBE(5, property));
3218
- /** Factory for {@link UInt|big-endian unsigned int layouts}
3219
- * spanning six bytes. */
3220
- Layout$1.u48be = ((property) => new UIntBE(6, property));
3221
- /** Factory for {@link NearUInt64BE|big-endian unsigned int
3222
- * layouts} interpreted as Numbers. */
3223
- Layout$1.nu64be = ((property) => new NearUInt64BE(property));
3224
- /** Factory for {@link Int|signed int layouts} spanning one
3225
- * byte. */
3226
- Layout$1.s8 = ((property) => new Int(1, property));
3227
- /** Factory for {@link Int|little-endian signed int layouts}
3228
- * spanning two bytes. */
3229
- Layout$1.s16 = ((property) => new Int(2, property));
3230
- /** Factory for {@link Int|little-endian signed int layouts}
3231
- * spanning three bytes. */
3232
- Layout$1.s24 = ((property) => new Int(3, property));
3233
- /** Factory for {@link Int|little-endian signed int layouts}
3234
- * spanning four bytes. */
3235
- Layout$1.s32 = ((property) => new Int(4, property));
3236
- /** Factory for {@link Int|little-endian signed int layouts}
3237
- * spanning five bytes. */
3238
- Layout$1.s40 = ((property) => new Int(5, property));
3239
- /** Factory for {@link Int|little-endian signed int layouts}
3240
- * spanning six bytes. */
3241
- Layout$1.s48 = ((property) => new Int(6, property));
3242
- /** Factory for {@link NearInt64|little-endian signed int layouts}
3243
- * interpreted as Numbers. */
3244
- Layout$1.ns64 = ((property) => new NearInt64(property));
3245
- /** Factory for {@link Int|big-endian signed int layouts}
3246
- * spanning two bytes. */
3247
- Layout$1.s16be = ((property) => new IntBE(2, property));
3248
- /** Factory for {@link Int|big-endian signed int layouts}
3249
- * spanning three bytes. */
3250
- Layout$1.s24be = ((property) => new IntBE(3, property));
3251
- /** Factory for {@link Int|big-endian signed int layouts}
3252
- * spanning four bytes. */
3253
- Layout$1.s32be = ((property) => new IntBE(4, property));
3254
- /** Factory for {@link Int|big-endian signed int layouts}
3255
- * spanning five bytes. */
3256
- Layout$1.s40be = ((property) => new IntBE(5, property));
3257
- /** Factory for {@link Int|big-endian signed int layouts}
3258
- * spanning six bytes. */
3259
- Layout$1.s48be = ((property) => new IntBE(6, property));
3260
- /** Factory for {@link NearInt64BE|big-endian signed int layouts}
3261
- * interpreted as Numbers. */
3262
- Layout$1.ns64be = ((property) => new NearInt64BE(property));
3263
- /** Factory for {@link Float|little-endian 32-bit floating point} values. */
3264
- Layout$1.f32 = ((property) => new Float(property));
3265
- /** Factory for {@link FloatBE|big-endian 32-bit floating point} values. */
3266
- Layout$1.f32be = ((property) => new FloatBE(property));
3267
- /** Factory for {@link Double|little-endian 64-bit floating point} values. */
3268
- Layout$1.f64 = ((property) => new Double(property));
3269
- /** Factory for {@link DoubleBE|big-endian 64-bit floating point} values. */
3270
- Layout$1.f64be = ((property) => new DoubleBE(property));
3271
- /** Factory for {@link Structure} values. */
3272
- var struct = Layout$1.struct = ((fields, property, decodePrefixes) => new Structure(fields, property, decodePrefixes));
3273
- /** Factory for {@link BitStructure} values. */
3274
- Layout$1.bits = ((word, msb, property) => new BitStructure(word, msb, property));
3275
- /** Factory for {@link Sequence} values. */
3276
- Layout$1.seq = ((elementLayout, count, property) => new Sequence(elementLayout, count, property));
3277
- /** Factory for {@link Union} values. */
3278
- Layout$1.union = ((discr, defaultLayout, property) => new Union(discr, defaultLayout, property));
3279
- /** Factory for {@link UnionLayoutDiscriminator} values. */
3280
- Layout$1.unionLayoutDiscriminator = ((layout, property) => new UnionLayoutDiscriminator(layout, property));
3281
- /** Factory for {@link Blob} values. */
3282
- var blob = Layout$1.blob = ((length, property) => new Blob(length, property));
3283
- /** Factory for {@link CString} values. */
3284
- Layout$1.cstr = ((property) => new CString(property));
3285
- /** Factory for {@link UTF8} values. */
3286
- Layout$1.utf8 = ((maxSpan, property) => new UTF8(maxSpan, property));
3287
- /** Factory for {@link Constant} values. */
3288
- Layout$1.constant = ((value, property) => new Constant(value, property));
3289
-
3290
- const encodeDecode = (layout) => {
3291
- const decode = layout.decode.bind(layout);
3292
- const encode = layout.encode.bind(layout);
3293
- return { decode, encode };
3294
- };
3295
-
3296
- var node = {};
3297
-
3298
- function commonjsRequire(path) {
3299
- throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
3300
- }
3301
-
3302
- var bindings = {exports: {}};
3303
-
3304
- var fileUriToPath_1;
3305
- var hasRequiredFileUriToPath;
3306
-
3307
- function requireFileUriToPath () {
3308
- if (hasRequiredFileUriToPath) return fileUriToPath_1;
3309
- hasRequiredFileUriToPath = 1;
3310
- /**
3311
- * Module dependencies.
3312
- */
3313
-
3314
- var sep = require$$0$1.sep || '/';
3315
-
3316
- /**
3317
- * Module exports.
3318
- */
3319
-
3320
- fileUriToPath_1 = fileUriToPath;
3321
-
3322
- /**
3323
- * File URI to Path function.
3324
- *
3325
- * @param {String} uri
3326
- * @return {String} path
3327
- * @api public
3328
- */
3329
-
3330
- function fileUriToPath (uri) {
3331
- if ('string' != typeof uri ||
3332
- uri.length <= 7 ||
3333
- 'file://' != uri.substring(0, 7)) {
3334
- throw new TypeError('must pass in a file:// URI to convert to a file path');
3335
- }
3336
-
3337
- var rest = decodeURI(uri.substring(7));
3338
- var firstSlash = rest.indexOf('/');
3339
- var host = rest.substring(0, firstSlash);
3340
- var path = rest.substring(firstSlash + 1);
3341
-
3342
- // 2. Scheme Definition
3343
- // As a special case, <host> can be the string "localhost" or the empty
3344
- // string; this is interpreted as "the machine from which the URL is
3345
- // being interpreted".
3346
- if ('localhost' == host) host = '';
3347
-
3348
- if (host) {
3349
- host = sep + sep + host;
3350
- }
3351
-
3352
- // 3.2 Drives, drive letters, mount points, file system root
3353
- // Drive letters are mapped into the top of a file URI in various ways,
3354
- // depending on the implementation; some applications substitute
3355
- // vertical bar ("|") for the colon after the drive letter, yielding
3356
- // "file:///c|/tmp/test.txt". In some cases, the colon is left
3357
- // unchanged, as in "file:///c:/tmp/test.txt". In other cases, the
3358
- // colon is simply omitted, as in "file:///c/tmp/test.txt".
3359
- path = path.replace(/^(.+)\|/, '$1:');
3360
-
3361
- // for Windows, we need to invert the path separators from what a URI uses
3362
- if (sep == '\\') {
3363
- path = path.replace(/\//g, '\\');
3364
- }
3365
-
3366
- if (/^.+\:/.test(path)) ; else {
3367
- // unix path…
3368
- path = sep + path;
3369
- }
3370
-
3371
- return host + path;
3372
- }
3373
- return fileUriToPath_1;
3374
- }
3375
-
3376
- /**
3377
- * Module dependencies.
3378
- */
3379
-
3380
- var hasRequiredBindings;
3381
-
3382
- function requireBindings () {
3383
- if (hasRequiredBindings) return bindings.exports;
3384
- hasRequiredBindings = 1;
3385
- (function (module, exports) {
3386
- var fs = require$$0$2,
3387
- path = require$$0$1,
3388
- fileURLToPath = requireFileUriToPath(),
3389
- join = path.join,
3390
- dirname = path.dirname,
3391
- exists =
3392
- (fs.accessSync &&
3393
- function(path) {
3394
- try {
3395
- fs.accessSync(path);
3396
- } catch (e) {
3397
- return false;
3398
- }
3399
- return true;
3400
- }) ||
3401
- fs.existsSync ||
3402
- path.existsSync,
3403
- defaults = {
3404
- arrow: process.env.NODE_BINDINGS_ARROW || ' → ',
3405
- compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled',
3406
- platform: process.platform,
3407
- arch: process.arch,
3408
- nodePreGyp:
3409
- 'node-v' +
3410
- process.versions.modules +
3411
- '-' +
3412
- process.platform +
3413
- '-' +
3414
- process.arch,
3415
- version: process.versions.node,
3416
- bindings: 'bindings.node',
3417
- try: [
3418
- // node-gyp's linked version in the "build" dir
3419
- ['module_root', 'build', 'bindings'],
3420
- // node-waf and gyp_addon (a.k.a node-gyp)
3421
- ['module_root', 'build', 'Debug', 'bindings'],
3422
- ['module_root', 'build', 'Release', 'bindings'],
3423
- // Debug files, for development (legacy behavior, remove for node v0.9)
3424
- ['module_root', 'out', 'Debug', 'bindings'],
3425
- ['module_root', 'Debug', 'bindings'],
3426
- // Release files, but manually compiled (legacy behavior, remove for node v0.9)
3427
- ['module_root', 'out', 'Release', 'bindings'],
3428
- ['module_root', 'Release', 'bindings'],
3429
- // Legacy from node-waf, node <= 0.4.x
3430
- ['module_root', 'build', 'default', 'bindings'],
3431
- // Production "Release" buildtype binary (meh...)
3432
- ['module_root', 'compiled', 'version', 'platform', 'arch', 'bindings'],
3433
- // node-qbs builds
3434
- ['module_root', 'addon-build', 'release', 'install-root', 'bindings'],
3435
- ['module_root', 'addon-build', 'debug', 'install-root', 'bindings'],
3436
- ['module_root', 'addon-build', 'default', 'install-root', 'bindings'],
3437
- // node-pre-gyp path ./lib/binding/{node_abi}-{platform}-{arch}
3438
- ['module_root', 'lib', 'binding', 'nodePreGyp', 'bindings']
3439
- ]
3440
- };
3441
-
3442
- /**
3443
- * The main `bindings()` function loads the compiled bindings for a given module.
3444
- * It uses V8's Error API to determine the parent filename that this function is
3445
- * being invoked from, which is then used to find the root directory.
3446
- */
3447
-
3448
- function bindings(opts) {
3449
- // Argument surgery
3450
- if (typeof opts == 'string') {
3451
- opts = { bindings: opts };
3452
- } else if (!opts) {
3453
- opts = {};
3454
- }
3455
-
3456
- // maps `defaults` onto `opts` object
3457
- Object.keys(defaults).map(function(i) {
3458
- if (!(i in opts)) opts[i] = defaults[i];
3459
- });
3460
-
3461
- // Get the module root
3462
- if (!opts.module_root) {
3463
- opts.module_root = exports.getRoot(exports.getFileName());
3464
- }
3465
-
3466
- // Ensure the given bindings name ends with .node
3467
- if (path.extname(opts.bindings) != '.node') {
3468
- opts.bindings += '.node';
3469
- }
3470
-
3471
- // https://github.com/webpack/webpack/issues/4175#issuecomment-342931035
3472
- var requireFunc =
3473
- typeof __webpack_require__ === 'function'
3474
- ? __non_webpack_require__
3475
- : commonjsRequire;
3476
-
3477
- var tries = [],
3478
- i = 0,
3479
- l = opts.try.length,
3480
- n,
3481
- b,
3482
- err;
3483
-
3484
- for (; i < l; i++) {
3485
- n = join.apply(
3486
- null,
3487
- opts.try[i].map(function(p) {
3488
- return opts[p] || p;
3489
- })
3490
- );
3491
- tries.push(n);
3492
- try {
3493
- b = opts.path ? requireFunc.resolve(n) : requireFunc(n);
3494
- if (!opts.path) {
3495
- b.path = n;
3496
- }
3497
- return b;
3498
- } catch (e) {
3499
- if (e.code !== 'MODULE_NOT_FOUND' &&
3500
- e.code !== 'QUALIFIED_PATH_RESOLUTION_FAILED' &&
3501
- !/not find/i.test(e.message)) {
3502
- throw e;
3503
- }
3504
- }
3505
- }
3506
-
3507
- err = new Error(
3508
- 'Could not locate the bindings file. Tried:\n' +
3509
- tries
3510
- .map(function(a) {
3511
- return opts.arrow + a;
3512
- })
3513
- .join('\n')
3514
- );
3515
- err.tries = tries;
3516
- throw err;
3517
- }
3518
- module.exports = exports = bindings;
3519
-
3520
- /**
3521
- * Gets the filename of the JavaScript file that invokes this function.
3522
- * Used to help find the root directory of a module.
3523
- * Optionally accepts an filename argument to skip when searching for the invoking filename
3524
- */
3525
-
3526
- exports.getFileName = function getFileName(calling_file) {
3527
- var origPST = Error.prepareStackTrace,
3528
- origSTL = Error.stackTraceLimit,
3529
- dummy = {},
3530
- fileName;
3531
-
3532
- Error.stackTraceLimit = 10;
3533
-
3534
- Error.prepareStackTrace = function(e, st) {
3535
- for (var i = 0, l = st.length; i < l; i++) {
3536
- fileName = st[i].getFileName();
3537
- if (fileName !== __filename) {
3538
- if (calling_file) {
3539
- if (fileName !== calling_file) {
3540
- return;
3541
- }
3542
- } else {
3543
- return;
3544
- }
3545
- }
3546
- }
3547
- };
3548
-
3549
- // run the 'prepareStackTrace' function above
3550
- Error.captureStackTrace(dummy);
3551
- dummy.stack;
3552
-
3553
- // cleanup
3554
- Error.prepareStackTrace = origPST;
3555
- Error.stackTraceLimit = origSTL;
3556
-
3557
- // handle filename that starts with "file://"
3558
- var fileSchema = 'file://';
3559
- if (fileName.indexOf(fileSchema) === 0) {
3560
- fileName = fileURLToPath(fileName);
3561
- }
3562
-
3563
- return fileName;
3564
- };
3565
-
3566
- /**
3567
- * Gets the root directory of a module, given an arbitrary filename
3568
- * somewhere in the module tree. The "root directory" is the directory
3569
- * containing the `package.json` file.
3570
- *
3571
- * In: /home/nate/node-native-module/lib/index.js
3572
- * Out: /home/nate/node-native-module
3573
- */
3574
-
3575
- exports.getRoot = function getRoot(file) {
3576
- var dir = dirname(file),
3577
- prev;
3578
- while (true) {
3579
- if (dir === '.') {
3580
- // Avoids an infinite loop in rare cases, like the REPL
3581
- dir = process.cwd();
3582
- }
3583
- if (
3584
- exists(join(dir, 'package.json')) ||
3585
- exists(join(dir, 'node_modules'))
3586
- ) {
3587
- // Found the 'package.json' file or 'node_modules' dir; we're done
3588
- return dir;
3589
- }
3590
- if (prev === dir) {
3591
- // Got to the top
3592
- throw new Error(
3593
- 'Could not find module root given file: "' +
3594
- file +
3595
- '". Do you have a `package.json` file? '
3596
- );
3597
- }
3598
- // Try the parent dir next
3599
- prev = dir;
3600
- dir = join(dir, '..');
3601
- }
3602
- };
3603
- } (bindings, bindings.exports));
3604
- return bindings.exports;
3605
- }
3606
-
3607
- Object.defineProperty(node, "__esModule", { value: true });
3608
- let converter;
3609
- {
3610
- try {
3611
- converter = requireBindings()('bigint_buffer');
3612
- }
3613
- catch (e) {
3614
- console.warn('bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?)');
3615
- }
3616
- }
3617
- /**
3618
- * Convert a little-endian buffer into a BigInt.
3619
- * @param buf The little-endian buffer to convert
3620
- * @returns A BigInt with the little-endian representation of buf.
3621
- */
3622
- function toBigIntLE(buf) {
3623
- if (converter === undefined) {
3624
- const reversed = Buffer.from(buf);
3625
- reversed.reverse();
3626
- const hex = reversed.toString('hex');
3627
- if (hex.length === 0) {
3628
- return BigInt(0);
3629
- }
3630
- return BigInt(`0x${hex}`);
3631
- }
3632
- return converter.toBigInt(buf, false);
3633
- }
3634
- var toBigIntLE_1 = node.toBigIntLE = toBigIntLE;
3635
- /**
3636
- * Convert a big-endian buffer into a BigInt
3637
- * @param buf The big-endian buffer to convert.
3638
- * @returns A BigInt with the big-endian representation of buf.
3639
- */
3640
- function toBigIntBE(buf) {
3641
- if (converter === undefined) {
3642
- const hex = buf.toString('hex');
3643
- if (hex.length === 0) {
3644
- return BigInt(0);
3645
- }
3646
- return BigInt(`0x${hex}`);
3647
- }
3648
- return converter.toBigInt(buf, true);
3649
- }
3650
- node.toBigIntBE = toBigIntBE;
3651
- /**
3652
- * Convert a BigInt to a little-endian buffer.
3653
- * @param num The BigInt to convert.
3654
- * @param width The number of bytes that the resulting buffer should be.
3655
- * @returns A little-endian buffer representation of num.
3656
- */
3657
- function toBufferLE(num, width) {
3658
- if (converter === undefined) {
3659
- const hex = num.toString(16);
3660
- const buffer = Buffer.from(hex.padStart(width * 2, '0').slice(0, width * 2), 'hex');
3661
- buffer.reverse();
3662
- return buffer;
3663
- }
3664
- // Allocation is done here, since it is slower using napi in C
3665
- return converter.fromBigInt(num, Buffer.allocUnsafe(width), false);
3666
- }
3667
- var toBufferLE_1 = node.toBufferLE = toBufferLE;
3668
- /**
3669
- * Convert a BigInt to a big-endian buffer.
3670
- * @param num The BigInt to convert.
3671
- * @param width The number of bytes that the resulting buffer should be.
3672
- * @returns A big-endian buffer representation of num.
3673
- */
3674
- function toBufferBE(num, width) {
3675
- if (converter === undefined) {
3676
- const hex = num.toString(16);
3677
- return Buffer.from(hex.padStart(width * 2, '0').slice(0, width * 2), 'hex');
3678
- }
3679
- return converter.fromBigInt(num, Buffer.allocUnsafe(width), true);
3680
- }
3681
- node.toBufferBE = toBufferBE;
3682
-
3683
- const bigInt = (length) => (property) => {
3684
- const layout = blob(length, property);
3685
- const { encode, decode } = encodeDecode(layout);
3686
- const bigIntLayout = layout;
3687
- bigIntLayout.decode = (buffer, offset) => {
3688
- const src = decode(buffer, offset);
3689
- return toBigIntLE_1(Buffer.from(src));
3690
- };
3691
- bigIntLayout.encode = (bigInt, buffer, offset) => {
3692
- const src = toBufferLE_1(bigInt, length);
3693
- return encode(src, buffer, offset);
3694
- };
3695
- return bigIntLayout;
3696
- };
3697
- const u64 = bigInt(8);
3698
-
3699
- const bool = (property) => {
3700
- const layout = u8(property);
3701
- const { encode, decode } = encodeDecode(layout);
3702
- const boolLayout = layout;
3703
- boolLayout.decode = (buffer, offset) => {
3704
- const src = decode(buffer, offset);
3705
- return !!src;
3706
- };
3707
- boolLayout.encode = (bool, buffer, offset) => {
3708
- const src = Number(bool);
3709
- return encode(src, buffer, offset);
3710
- };
3711
- return boolLayout;
3712
- };
3713
-
3714
- const publicKey = (property) => {
3715
- const layout = blob(32, property);
3716
- const { encode, decode } = encodeDecode(layout);
3717
- const publicKeyLayout = layout;
3718
- publicKeyLayout.decode = (buffer, offset) => {
3719
- const src = decode(buffer, offset);
3720
- return new PublicKey(src);
3721
- };
3722
- publicKeyLayout.encode = (publicKey, buffer, offset) => {
3723
- const src = publicKey.toBuffer();
3724
- return encode(src, buffer, offset);
3725
- };
3726
- return publicKeyLayout;
3727
- };
3728
-
3729
- /** Instructions defined by the program */
3730
- var TokenInstruction;
3731
- (function (TokenInstruction) {
3732
- TokenInstruction[TokenInstruction["InitializeMint"] = 0] = "InitializeMint";
3733
- TokenInstruction[TokenInstruction["InitializeAccount"] = 1] = "InitializeAccount";
3734
- TokenInstruction[TokenInstruction["InitializeMultisig"] = 2] = "InitializeMultisig";
3735
- TokenInstruction[TokenInstruction["Transfer"] = 3] = "Transfer";
3736
- TokenInstruction[TokenInstruction["Approve"] = 4] = "Approve";
3737
- TokenInstruction[TokenInstruction["Revoke"] = 5] = "Revoke";
3738
- TokenInstruction[TokenInstruction["SetAuthority"] = 6] = "SetAuthority";
3739
- TokenInstruction[TokenInstruction["MintTo"] = 7] = "MintTo";
3740
- TokenInstruction[TokenInstruction["Burn"] = 8] = "Burn";
3741
- TokenInstruction[TokenInstruction["CloseAccount"] = 9] = "CloseAccount";
3742
- TokenInstruction[TokenInstruction["FreezeAccount"] = 10] = "FreezeAccount";
3743
- TokenInstruction[TokenInstruction["ThawAccount"] = 11] = "ThawAccount";
3744
- TokenInstruction[TokenInstruction["TransferChecked"] = 12] = "TransferChecked";
3745
- TokenInstruction[TokenInstruction["ApproveChecked"] = 13] = "ApproveChecked";
3746
- TokenInstruction[TokenInstruction["MintToChecked"] = 14] = "MintToChecked";
3747
- TokenInstruction[TokenInstruction["BurnChecked"] = 15] = "BurnChecked";
3748
- TokenInstruction[TokenInstruction["InitializeAccount2"] = 16] = "InitializeAccount2";
3749
- TokenInstruction[TokenInstruction["SyncNative"] = 17] = "SyncNative";
3750
- TokenInstruction[TokenInstruction["InitializeAccount3"] = 18] = "InitializeAccount3";
3751
- TokenInstruction[TokenInstruction["InitializeMultisig2"] = 19] = "InitializeMultisig2";
3752
- TokenInstruction[TokenInstruction["InitializeMint2"] = 20] = "InitializeMint2";
3753
- TokenInstruction[TokenInstruction["GetAccountDataSize"] = 21] = "GetAccountDataSize";
3754
- TokenInstruction[TokenInstruction["InitializeImmutableOwner"] = 22] = "InitializeImmutableOwner";
3755
- TokenInstruction[TokenInstruction["AmountToUiAmount"] = 23] = "AmountToUiAmount";
3756
- TokenInstruction[TokenInstruction["UiAmountToAmount"] = 24] = "UiAmountToAmount";
3757
- TokenInstruction[TokenInstruction["InitializeMintCloseAuthority"] = 25] = "InitializeMintCloseAuthority";
3758
- TokenInstruction[TokenInstruction["TransferFeeExtension"] = 26] = "TransferFeeExtension";
3759
- TokenInstruction[TokenInstruction["ConfidentialTransferExtension"] = 27] = "ConfidentialTransferExtension";
3760
- TokenInstruction[TokenInstruction["DefaultAccountStateExtension"] = 28] = "DefaultAccountStateExtension";
3761
- TokenInstruction[TokenInstruction["Reallocate"] = 29] = "Reallocate";
3762
- TokenInstruction[TokenInstruction["MemoTransferExtension"] = 30] = "MemoTransferExtension";
3763
- TokenInstruction[TokenInstruction["CreateNativeMint"] = 31] = "CreateNativeMint";
3764
- TokenInstruction[TokenInstruction["InitializeNonTransferableMint"] = 32] = "InitializeNonTransferableMint";
3765
- TokenInstruction[TokenInstruction["InterestBearingMintExtension"] = 33] = "InterestBearingMintExtension";
3766
- TokenInstruction[TokenInstruction["CpiGuardExtension"] = 34] = "CpiGuardExtension";
3767
- TokenInstruction[TokenInstruction["InitializePermanentDelegate"] = 35] = "InitializePermanentDelegate";
3768
- })(TokenInstruction || (TokenInstruction = {}));
3769
-
3770
- /** @internal */
3771
- function addSigners(keys, ownerOrAuthority, multiSigners) {
3772
- if (multiSigners.length) {
3773
- keys.push({ pubkey: ownerOrAuthority, isSigner: false, isWritable: false });
3774
- for (const signer of multiSigners) {
3775
- keys.push({
3776
- pubkey: signer instanceof PublicKey ? signer : signer.publicKey,
3777
- isSigner: true,
3778
- isWritable: false,
3779
- });
3780
- }
3781
- }
3782
- else {
3783
- keys.push({ pubkey: ownerOrAuthority, isSigner: true, isWritable: false });
3784
- }
3785
- return keys;
3786
- }
3787
-
3788
- /** TODO: docs */
3789
- const approveInstructionData = struct([u8('instruction'), u64('amount')]);
3790
- /**
3791
- * Construct an Approve instruction
3792
- *
3793
- * @param account Account to set the delegate for
3794
- * @param delegate Account authorized to transfer tokens from the account
3795
- * @param owner Owner of the account
3796
- * @param amount Maximum number of tokens the delegate may transfer
3797
- * @param multiSigners Signing accounts if `owner` is a multisig
3798
- * @param programId SPL Token program account
3799
- *
3800
- * @return Instruction to add to a transaction
3801
- */
3802
- function createApproveInstruction(account, delegate, owner, amount, multiSigners = [], programId = TOKEN_PROGRAM_ID) {
3803
- const keys = addSigners([
3804
- { pubkey: account, isSigner: false, isWritable: true },
3805
- { pubkey: delegate, isSigner: false, isWritable: false },
3806
- ], owner, multiSigners);
3807
- const data = Buffer.alloc(approveInstructionData.span);
3808
- approveInstructionData.encode({
3809
- instruction: TokenInstruction.Approve,
3810
- amount: BigInt(amount),
3811
- }, data);
3812
- return new TransactionInstruction({ keys, programId, data });
3813
- }
3814
-
3815
- /** Buffer layout for de/serializing a mint */
3816
- const MintLayout = struct([
3817
- u32('mintAuthorityOption'),
3818
- publicKey('mintAuthority'),
3819
- u64('supply'),
3820
- u8('decimals'),
3821
- bool('isInitialized'),
3822
- u32('freezeAuthorityOption'),
3823
- publicKey('freezeAuthority'),
3824
- ]);
3825
- /** Byte length of a mint */
3826
- const MINT_SIZE = MintLayout.span;
3827
-
3828
- /** TODO: docs */
3829
- const initializeMint2InstructionData = struct([
3830
- u8('instruction'),
3831
- u8('decimals'),
3832
- publicKey('mintAuthority'),
3833
- u8('freezeAuthorityOption'),
3834
- publicKey('freezeAuthority'),
3835
- ]);
3836
- /**
3837
- * Construct an InitializeMint2 instruction
3838
- *
3839
- * @param mint Token mint account
3840
- * @param decimals Number of decimals in token account amounts
3841
- * @param mintAuthority Minting authority
3842
- * @param freezeAuthority Optional authority that can freeze token accounts
3843
- * @param programId SPL Token program account
3844
- *
3845
- * @return Instruction to add to a transaction
3846
- */
3847
- function createInitializeMint2Instruction(mint, decimals, mintAuthority, freezeAuthority, programId = TOKEN_PROGRAM_ID) {
3848
- const keys = [{ pubkey: mint, isSigner: false, isWritable: true }];
3849
- const data = Buffer.alloc(initializeMint2InstructionData.span);
3850
- initializeMint2InstructionData.encode({
3851
- instruction: TokenInstruction.InitializeMint2,
3852
- decimals,
3853
- mintAuthority,
3854
- freezeAuthorityOption: freezeAuthority ? 1 : 0,
3855
- freezeAuthority: freezeAuthority || new PublicKey(0),
3856
- }, data);
3857
- return new TransactionInstruction({ keys, programId, data });
3858
- }
3859
-
3860
- const sumUpTokenAmount = (accounts) => {
3861
- return accounts.reduce((acc, account) => acc.add(account.parsed.amount), bn(0));
3862
- };
3863
- const validateSameTokenOwner = (accounts) => {
3864
- const owner = accounts[0].parsed.owner;
3865
- accounts.forEach(acc => {
3866
- if (!acc.parsed.owner.equals(owner)) {
3867
- throw new Error('Token accounts must be owned by the same owner');
3868
- }
3869
- });
3870
- };
3871
- const parseInputTokenData = (inputCompressedTokenAccounts) => {
3872
- const mint = inputCompressedTokenAccounts[0].parsed.mint;
3873
- const currentOwner = inputCompressedTokenAccounts[0].parsed.owner;
3874
- const delegate = inputCompressedTokenAccounts[0].parsed.delegate;
3875
- return { mint, currentOwner, delegate };
3876
- };
3877
- function createTransferOutputState(inputCompressedTokenAccounts, toAddress, amount) {
3878
- amount = bn(amount);
3879
- const inputAmount = sumUpTokenAmount(inputCompressedTokenAccounts);
3880
- const inputLamports = sumUpLamports(inputCompressedTokenAccounts.map(acc => acc.compressedAccount));
3881
- const changeAmount = inputAmount.sub(amount);
3882
- validateSufficientBalance(changeAmount);
3883
- if (changeAmount.eq(bn(0)) && inputLamports.eq(bn(0))) {
3884
- return [
3885
- {
3886
- owner: toAddress,
3887
- amount,
3888
- lamports: inputLamports,
3889
- },
3890
- ];
3891
- }
3892
- /// validates token program
3893
- validateSameOwner(inputCompressedTokenAccounts.map(acc => acc.compressedAccount));
3894
- validateSameTokenOwner(inputCompressedTokenAccounts);
3895
- const outputCompressedAccounts = [
3896
- {
3897
- owner: inputCompressedTokenAccounts[0].parsed.owner,
3898
- amount: changeAmount,
3899
- lamports: inputLamports,
3900
- },
3901
- {
3902
- owner: toAddress,
3903
- amount,
3904
- lamports: bn(0),
3905
- },
3906
- ];
3907
- return outputCompressedAccounts;
3908
- }
3909
- function createDecompressOutputState(inputCompressedTokenAccounts, amount) {
3910
- amount = bn(amount);
3911
- const inputLamports = sumUpLamports(inputCompressedTokenAccounts.map(acc => acc.compressedAccount));
3912
- const inputAmount = sumUpTokenAmount(inputCompressedTokenAccounts);
3913
- const changeAmount = inputAmount.sub(amount);
3914
- validateSufficientBalance(changeAmount);
3915
- /// lamports gets decompressed
3916
- if (changeAmount.eq(bn(0)) && inputLamports.eq(bn(0))) {
3917
- return [];
3918
- }
3919
- validateSameOwner(inputCompressedTokenAccounts.map(acc => acc.compressedAccount));
3920
- validateSameTokenOwner(inputCompressedTokenAccounts);
3921
- const tokenTransferOutputs = [
3922
- {
3923
- owner: inputCompressedTokenAccounts[0].parsed.owner,
3924
- amount: changeAmount,
3925
- lamports: inputLamports,
3926
- },
3927
- ];
3928
- return tokenTransferOutputs;
3929
- }
3930
- class CompressedTokenProgram {
3931
- /**
3932
- * @internal
3933
- */
3934
- constructor() { }
3935
- /**
3936
- * Public key that identifies the CompressedPda program
3937
- */
3938
- static programId = new PublicKey(
3939
- // TODO: can add check to ensure its consistent with the idl
3940
- '9sixVEthz2kMSKfeApZXHwuboT6DZuT6crAYJTciUCqE');
3941
- static _program = null;
3942
- static get program() {
3943
- if (!this._program) {
3944
- this.initializeProgram();
3945
- }
3946
- return this._program;
3947
- }
3948
- /**
3949
- * Initializes the program statically if not already initialized.
3950
- */
3951
- static initializeProgram() {
3952
- if (!this._program) {
3953
- /// We can use a mock connection because we're using the program only for
3954
- /// serde and building instructions, not for interacting with the network.
3955
- const mockKeypair = Keypair.generate();
3956
- const mockConnection = new Connection('http://127.0.0.1:8899', 'confirmed');
3957
- const mockProvider = new AnchorProvider(mockConnection, useWallet(mockKeypair), confirmConfig);
3958
- setProvider(mockProvider);
3959
- this._program = new Program(IDL, this.programId, mockProvider);
3960
- }
3961
- }
3962
- /** @internal */
3963
- static deriveMintAuthorityPda = (authority, mint) => {
3964
- const [pubkey] = PublicKey.findProgramAddressSync([MINT_AUTHORITY_SEED, authority.toBuffer(), mint.toBuffer()], this.programId);
3965
- return pubkey;
3966
- };
3967
- /** @internal */
3968
- static deriveTokenPoolPda(mint) {
3969
- const seeds = [POOL_SEED, mint.toBuffer()];
3970
- const [address, _] = PublicKey.findProgramAddressSync(seeds, this.programId);
3971
- return address;
3972
- }
3973
- /** @internal */
3974
- static get deriveCpiAuthorityPda() {
3975
- const [address, _] = PublicKey.findProgramAddressSync([CPI_AUTHORITY_SEED], this.programId);
3976
- return address;
3977
- }
3978
- static async createMint(params) {
3979
- const { mint, authority, feePayer, rentExemptBalance } = params;
3980
- const createMintAccountInstruction = SystemProgram.createAccount({
3981
- fromPubkey: feePayer,
3982
- lamports: rentExemptBalance,
3983
- newAccountPubkey: mint,
3984
- programId: TOKEN_PROGRAM_ID,
3985
- space: MINT_SIZE,
3986
- });
3987
- const mintAuthorityPda = this.deriveMintAuthorityPda(authority, mint);
3988
- const initializeMintInstruction = createInitializeMint2Instruction(mint, params.decimals, mintAuthorityPda, params.freezeAuthority, TOKEN_PROGRAM_ID);
3989
- const fundAuthorityPdaInstruction = SystemProgram.transfer({
3990
- fromPubkey: feePayer,
3991
- toPubkey: mintAuthorityPda,
3992
- lamports: rentExemptBalance, // TODO: check that this is the right PDA size
3993
- });
3994
- const tokenPoolPda = this.deriveTokenPoolPda(mint);
3995
- const ix = await this.program.methods
3996
- .createMint()
3997
- .accounts({
3998
- mint,
3999
- feePayer,
4000
- authority,
4001
- tokenPoolPda,
4002
- systemProgram: SystemProgram.programId,
4003
- mintAuthorityPda,
4004
- tokenProgram: TOKEN_PROGRAM_ID,
4005
- cpiAuthorityPda: this.deriveCpiAuthorityPda,
4006
- })
4007
- .instruction();
4008
- return [
4009
- createMintAccountInstruction,
4010
- initializeMintInstruction,
4011
- fundAuthorityPdaInstruction,
4012
- ix,
4013
- ];
4014
- }
4015
- static async mintTo(params) {
4016
- const systemKeys = defaultStaticAccountsStruct();
4017
- const { mint, feePayer, authority, merkleTree, toPubkey, amount } = params;
4018
- const tokenPoolPda = this.deriveTokenPoolPda(mint);
4019
- const mintAuthorityPda = this.deriveMintAuthorityPda(authority, mint);
4020
- const amounts = toArray(amount).map(amount => bn(amount));
4021
- const toPubkeys = toArray(toPubkey);
4022
- const ix = await this.program.methods
4023
- .mintTo(toPubkeys, amounts)
4024
- .accounts({
4025
- feePayer,
4026
- authority,
4027
- mintAuthorityPda,
4028
- mint,
4029
- tokenPoolPda,
4030
- tokenProgram: TOKEN_PROGRAM_ID,
4031
- compressedPdaProgram: LightSystemProgram.programId,
4032
- registeredProgramPda: systemKeys.registeredProgramPda,
4033
- noopProgram: systemKeys.noopProgram,
4034
- accountCompressionAuthority: systemKeys.accountCompressionAuthority,
4035
- accountCompressionProgram: systemKeys.accountCompressionProgram,
4036
- merkleTree,
4037
- selfProgram: this.programId,
4038
- })
4039
- .instruction();
4040
- return ix;
4041
- }
4042
- static async transfer(params) {
4043
- const { payer, inputCompressedTokenAccounts, recentInputStateRootIndices, recentValidityProof, amount, outputStateTrees, toAddress, } = params;
4044
- const outputCompressedAccounts = createTransferOutputState(inputCompressedTokenAccounts, toAddress, amount);
4045
- /// Pack
4046
- const { inputTokenDataWithContext, outputStateMerkleTreeIndices, remainingAccountMetas, } = packCompressedTokenAccounts({
4047
- inputCompressedTokenAccounts,
4048
- outputCompressedAccountsLength: outputCompressedAccounts.length,
4049
- outputStateTrees,
4050
- });
4051
- const { mint, currentOwner } = parseInputTokenData(inputCompressedTokenAccounts);
4052
- const data = {
4053
- proof: recentValidityProof,
4054
- rootIndices: recentInputStateRootIndices,
4055
- mint,
4056
- signerIsDelegate: false, // TODO: implement
4057
- inputTokenDataWithContext,
4058
- outputCompressedAccounts,
4059
- outputStateMerkleTreeAccountIndices: Buffer$1.from(outputStateMerkleTreeIndices),
4060
- compressionAmount: null,
4061
- isCompress: false,
4062
- };
4063
- const encodedData = this.program.coder.types.encode('CompressedTokenInstructionDataTransfer', data);
4064
- const { accountCompressionAuthority, noopProgram, registeredProgramPda, accountCompressionProgram, } = defaultStaticAccountsStruct();
4065
- const instruction = await this.program.methods
4066
- .transfer(encodedData, null)
4067
- .accounts({
4068
- feePayer: payer,
4069
- authority: currentOwner,
4070
- cpiAuthorityPda: this.deriveCpiAuthorityPda,
4071
- compressedPdaProgram: LightSystemProgram.programId,
4072
- registeredProgramPda: registeredProgramPda,
4073
- noopProgram: noopProgram,
4074
- accountCompressionAuthority: accountCompressionAuthority,
4075
- accountCompressionProgram: accountCompressionProgram,
4076
- selfProgram: this.programId,
4077
- tokenPoolPda: null,
4078
- decompressTokenAccount: null,
4079
- tokenProgram: null,
4080
- })
4081
- .remainingAccounts(remainingAccountMetas)
4082
- .instruction();
4083
- return [
4084
- ComputeBudgetProgram.setComputeUnitLimit({ units: 1000000 }),
4085
- instruction,
4086
- ];
4087
- }
4088
- static async compress(params) {
4089
- const { payer, owner, source, toAddress, mint, outputStateTree } = params;
4090
- const amount = bn(params.amount);
4091
- const outputCompressedAccounts = [
4092
- {
4093
- owner: toAddress,
4094
- amount,
4095
- lamports: bn(0),
4096
- },
4097
- ];
4098
- /// Pack
4099
- const { inputTokenDataWithContext, outputStateMerkleTreeIndices, remainingAccountMetas, } = packCompressedTokenAccounts({
4100
- inputCompressedTokenAccounts: [],
4101
- outputCompressedAccountsLength: outputCompressedAccounts.length,
4102
- outputStateTrees: [outputStateTree],
4103
- });
4104
- const data = {
4105
- proof: null,
4106
- rootIndices: [],
4107
- mint,
4108
- signerIsDelegate: false, // TODO: implement
4109
- inputTokenDataWithContext,
4110
- outputCompressedAccounts,
4111
- outputStateMerkleTreeAccountIndices: Buffer$1.from(outputStateMerkleTreeIndices),
4112
- compressionAmount: amount,
4113
- isCompress: true,
4114
- };
4115
- const encodedData = this.program.coder.types.encode('CompressedTokenInstructionDataTransfer', data);
4116
- const { accountCompressionAuthority, noopProgram, registeredProgramPda, accountCompressionProgram, } = defaultStaticAccountsStruct();
4117
- /// TODO: add support for multiSigners
4118
- /// TODO: validate that we don't need approveChecked
4119
- const approveInstruction = createApproveInstruction(source, this.deriveCpiAuthorityPda, owner, BigInt(amount.toString()));
4120
- const instruction = await this.program.methods
4121
- .transfer(encodedData, null)
4122
- .accounts({
4123
- feePayer: payer,
4124
- authority: owner,
4125
- cpiAuthorityPda: this.deriveCpiAuthorityPda,
4126
- compressedPdaProgram: LightSystemProgram.programId,
4127
- registeredProgramPda: registeredProgramPda,
4128
- noopProgram: noopProgram,
4129
- accountCompressionAuthority: accountCompressionAuthority,
4130
- accountCompressionProgram: accountCompressionProgram,
4131
- selfProgram: this.programId,
4132
- tokenPoolPda: this.deriveTokenPoolPda(mint),
4133
- decompressTokenAccount: source, // token
4134
- tokenProgram: TOKEN_PROGRAM_ID,
4135
- })
4136
- .remainingAccounts(remainingAccountMetas)
4137
- .instruction();
4138
- return [
4139
- ComputeBudgetProgram.setComputeUnitLimit({ units: 1000000 }),
4140
- approveInstruction,
4141
- instruction,
4142
- ];
4143
- }
4144
- static async decompress(params) {
4145
- const { payer, inputCompressedTokenAccounts, toAddress, outputStateTree, recentValidityProof, recentInputStateRootIndices, } = params;
4146
- const amount = bn(params.amount);
4147
- const tokenTransferOutputs = createDecompressOutputState(inputCompressedTokenAccounts, amount);
4148
- /// Pack
4149
- const { inputTokenDataWithContext, outputStateMerkleTreeIndices, remainingAccountMetas, } = packCompressedTokenAccounts({
4150
- inputCompressedTokenAccounts,
4151
- outputCompressedAccountsLength: tokenTransferOutputs.length,
4152
- outputStateTrees: [outputStateTree],
4153
- });
4154
- const { mint, currentOwner } = parseInputTokenData(inputCompressedTokenAccounts);
4155
- const data = {
4156
- proof: recentValidityProof,
4157
- rootIndices: recentInputStateRootIndices,
4158
- mint,
4159
- signerIsDelegate: false, // TODO: implement
4160
- inputTokenDataWithContext,
4161
- outputCompressedAccounts: tokenTransferOutputs,
4162
- outputStateMerkleTreeAccountIndices: Buffer$1.from(outputStateMerkleTreeIndices),
4163
- compressionAmount: amount,
4164
- isCompress: false,
4165
- };
4166
- const encodedData = this.program.coder.types.encode('CompressedTokenInstructionDataTransfer', data);
4167
- const { accountCompressionAuthority, noopProgram, registeredProgramPda, accountCompressionProgram, } = defaultStaticAccountsStruct();
4168
- const instruction = await this.program.methods
4169
- .transfer(encodedData, null)
4170
- .accounts({
4171
- feePayer: payer,
4172
- authority: currentOwner,
4173
- cpiAuthorityPda: this.deriveCpiAuthorityPda,
4174
- compressedPdaProgram: LightSystemProgram.programId,
4175
- registeredProgramPda: registeredProgramPda,
4176
- noopProgram: noopProgram,
4177
- accountCompressionAuthority: accountCompressionAuthority,
4178
- accountCompressionProgram: accountCompressionProgram,
4179
- selfProgram: this.programId,
4180
- tokenPoolPda: this.deriveTokenPoolPda(mint),
4181
- decompressTokenAccount: toAddress, // token
4182
- tokenProgram: TOKEN_PROGRAM_ID,
4183
- })
4184
- .remainingAccounts(remainingAccountMetas)
4185
- .instruction();
4186
- return [
4187
- ComputeBudgetProgram.setComputeUnitLimit({ units: 1000000 }),
4188
- instruction,
4189
- ];
4190
- }
4191
- }
4192
-
4193
- /**
4194
- * Compress SPL tokens
4195
- *
4196
- * @param rpc Rpc connection to use
4197
- * @param payer Payer of the transaction fees
4198
- * @param mint Mint of the compressed token
4199
- * @param amount Number of tokens to transfer
4200
- * @param owner Owner of the compressed tokens.
4201
- * @param sourceTokenAccount Source (associated) token account
4202
- * @param toAddress Destination address of the recipient
4203
- * @param merkleTree State tree account that the compressed tokens
4204
- * should be inserted into. Defaults to a default
4205
- * state tree account.
4206
- * @param confirmOptions Options for confirming the transaction
4207
- *
4208
- *
4209
- * @return Signature of the confirmed transaction
4210
- */
4211
- async function compress(rpc, payer, mint, amount, owner, sourceTokenAccount, toAddress, merkleTree = defaultTestStateTreeAccounts().merkleTree, confirmOptions) {
4212
- amount = bn(amount);
4213
- const ixs = await CompressedTokenProgram.compress({
4214
- payer: payer.publicKey,
4215
- owner: owner.publicKey,
4216
- source: sourceTokenAccount,
4217
- toAddress,
4218
- amount,
4219
- mint,
4220
- outputStateTree: merkleTree,
4221
- });
4222
- const blockhashCtx = await rpc.getLatestBlockhash();
4223
- const additionalSigners = dedupeSigner(payer, [owner]);
4224
- const signedTx = buildAndSignTx(ixs, payer, blockhashCtx.blockhash, additionalSigners);
4225
- const txId = await sendAndConfirmTx(rpc, signedTx, confirmOptions, blockhashCtx);
4226
- return txId;
4227
- }
4228
-
4229
- /**
4230
- * Transfer compressed tokens from one owner to another
4231
- *
4232
- * @param rpc Rpc to use
4233
- * @param payer Payer of the transaction fees
4234
- * @param mint Mint of the compressed token
4235
- * @param amount Number of tokens to transfer
4236
- * @param owner Owner of the compressed tokens
4237
- * @param toAddress Destination address of the recipient
4238
- * @param merkleTree State tree account that the compressed tokens should be
4239
- * inserted into. Defaults to the default state tree account.
4240
- * @param confirmOptions Options for confirming the transaction
4241
- *
4242
- *
4243
- * @return Signature of the confirmed transaction
4244
- */
4245
- async function transfer(rpc, payer, mint, amount, owner, toAddress,
4246
- /// TODO: allow multiple
4247
- merkleTree = defaultTestStateTreeAccounts().merkleTree, confirmOptions) {
4248
- amount = bn(amount);
4249
- const compressedTokenAccounts = await rpc.getCompressedTokenAccountsByOwner(owner.publicKey, {
4250
- mint,
4251
- });
4252
- const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(compressedTokenAccounts, amount);
4253
- const proof = await rpc.getValidityProof(inputAccounts.map(account => bn(account.compressedAccount.hash)));
4254
- const ixs = await CompressedTokenProgram.transfer({
4255
- payer: payer.publicKey,
4256
- inputCompressedTokenAccounts: inputAccounts,
4257
- toAddress,
4258
- amount,
4259
- recentInputStateRootIndices: proof.rootIndices,
4260
- recentValidityProof: proof.compressedProof,
4261
- outputStateTrees: merkleTree,
4262
- });
4263
- const { blockhash } = await rpc.getLatestBlockhash();
4264
- const additionalSigners = dedupeSigner(payer, [owner]);
4265
- const signedTx = buildAndSignTx(ixs, payer, blockhash, additionalSigners);
4266
- const txId = await sendAndConfirmTx(rpc, signedTx, confirmOptions);
4267
- return txId;
4268
- }
4269
- /**
4270
- * Selects the minimal number of compressed token accounts for a transfer.
4271
- *
4272
- * 1. Sorts the accounts by amount in descending order
4273
- * 2. Accumulates the amount until it is greater than or equal to the transfer
4274
- * amount
4275
- */
4276
- function selectMinCompressedTokenAccountsForTransfer(accounts, transferAmount) {
4277
- let accumulatedAmount = bn(0);
4278
- let accumulatedLamports = bn(0);
4279
- const selectedAccounts = [];
4280
- accounts.sort((a, b) => b.parsed.amount.cmp(a.parsed.amount));
4281
- for (const account of accounts) {
4282
- if (accumulatedAmount.gte(bn(transferAmount)))
4283
- break;
4284
- accumulatedAmount = accumulatedAmount.add(account.parsed.amount);
4285
- accumulatedLamports = accumulatedLamports.add(account.compressedAccount.lamports);
4286
- selectedAccounts.push(account);
4287
- }
4288
- if (accumulatedAmount.lt(bn(transferAmount))) {
4289
- throw new Error(`Not enough balance for transfer. Required: ${transferAmount.toString()}, available: ${accumulatedAmount.toString()}`);
4290
- }
4291
- return [
4292
- selectedAccounts,
4293
- accumulatedAmount,
4294
- accumulatedLamports.lt(bn(0)) ? accumulatedLamports : null,
4295
- ];
4296
- }
4297
-
4298
- /**
4299
- * Decompress compressed tokens
4300
- *
4301
- * @param rpc Rpc to use
4302
- * @param payer Payer of the transaction fees
4303
- * @param mint Mint of the compressed token
4304
- * @param amount Number of tokens to transfer
4305
- * @param owner Owner of the compressed tokens
4306
- * @param toAddress Destination **uncompressed** (associated) token account
4307
- * address.
4308
- * @param merkleTree State tree account that any change compressed tokens should be
4309
- * inserted into. Defaults to a default state tree
4310
- * account.
4311
- * @param confirmOptions Options for confirming the transaction
4312
- *
4313
- *
4314
- * @return Signature of the confirmed transaction
4315
- */
4316
- async function decompress(rpc, payer, mint, amount, owner, toAddress,
4317
- /// TODO: allow multiple
4318
- merkleTree = defaultTestStateTreeAccounts().merkleTree, confirmOptions) {
4319
- amount = bn(amount);
4320
- const compressedTokenAccounts = await rpc.getCompressedTokenAccountsByOwner(owner.publicKey, {
4321
- mint,
4322
- });
4323
- /// TODO: consider using a different selection algorithm
4324
- const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(compressedTokenAccounts, amount);
4325
- const proof = await rpc.getValidityProof(inputAccounts.map(account => bn(account.compressedAccount.hash)));
4326
- const ixs = await CompressedTokenProgram.decompress({
4327
- payer: payer.publicKey,
4328
- inputCompressedTokenAccounts: inputAccounts,
4329
- toAddress, // TODO: add explicit check that it is a token account
4330
- amount,
4331
- outputStateTree: merkleTree,
4332
- recentInputStateRootIndices: proof.rootIndices,
4333
- recentValidityProof: proof.compressedProof,
4334
- });
4335
- const { blockhash } = await rpc.getLatestBlockhash();
4336
- const additionalSigners = dedupeSigner(payer, [owner]);
4337
- const signedTx = buildAndSignTx(ixs, payer, blockhash, additionalSigners);
4338
- const txId = await sendAndConfirmTx(rpc, signedTx, confirmOptions);
4339
- return txId;
4340
- }
4341
-
4342
- /**
4343
- * Create and initialize a new compressed token mint
4344
- *
4345
- * @param rpc RPC to use
4346
- * @param payer Payer of the transaction and initialization fees
4347
- * @param mintAuthority Account or multisig that will control minting. Is signer.
4348
- * @param decimals Location of the decimal place
4349
- * @param keypair Optional keypair, defaulting to a new random one
4350
- * @param confirmOptions Options for confirming the transaction
4351
- *
4352
- * @return Address of the new mint and the transaction signature
4353
- */
4354
- async function createMint(rpc, payer, mintAuthority, decimals, keypair = Keypair.generate(), confirmOptions) {
4355
- const rentExemptBalance = await rpc.getMinimumBalanceForRentExemption(MINT_SIZE);
4356
- const ixs = await CompressedTokenProgram.createMint({
4357
- feePayer: payer.publicKey,
4358
- mint: keypair.publicKey,
4359
- decimals,
4360
- authority: mintAuthority.publicKey,
4361
- freezeAuthority: null, // TODO: add feature
4362
- rentExemptBalance,
4363
- });
4364
- const { blockhash } = await rpc.getLatestBlockhash();
4365
- const additionalSigners = dedupeSigner(payer, [mintAuthority, keypair]);
4366
- const tx = buildAndSignTx(ixs, payer, blockhash, additionalSigners);
4367
- const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);
4368
- return { mint: keypair.publicKey, transactionSignature: txId };
4369
- }
4370
-
4371
- /**
4372
- * Mint compressed tokens to a solana address
4373
- *
4374
- * @param rpc Rpc to use
4375
- * @param payer Payer of the transaction fees
4376
- * @param mint Mint for the account
4377
- * @param destination Address of the account to mint to
4378
- * @param authority Minting authority
4379
- * @param amount Amount to mint
4380
- * @param merkleTree State tree account that the compressed tokens should be
4381
- * part of. Defaults to the default state tree account.
4382
- * @param confirmOptions Options for confirming the transaction
4383
- *
4384
- * @return Signature of the confirmed transaction
4385
- */
4386
- async function mintTo(rpc, payer, mint, destination, authority, amount, merkleTree = defaultTestStateTreeAccounts().merkleTree, // DEFAULT IF NOT PROVIDED
4387
- confirmOptions) {
4388
- const additionalSigners = dedupeSigner(payer, [authority]);
4389
- const ix = await CompressedTokenProgram.mintTo({
4390
- feePayer: payer.publicKey,
4391
- mint,
4392
- authority: authority.publicKey,
4393
- amount: amount,
4394
- toPubkey: destination,
4395
- merkleTree,
4396
- });
4397
- const { blockhash } = await rpc.getLatestBlockhash();
4398
- const tx = buildAndSignTx([ComputeBudgetProgram.setComputeUnitLimit({ units: 1000000 }), ix], payer, blockhash, additionalSigners);
4399
- const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);
4400
- return txId;
4401
- }
4402
-
4403
- export { CPI_AUTHORITY_SEED, CompressedTokenProgram, IDL, MINT_AUTHORITY_SEED, POOL_SEED, SPL_TOKEN_MINT_RENT_EXEMPT_BALANCE, compress, createDecompressOutputState, createMint, createTransferOutputState, decompress, mintTo, packCompressedTokenAccounts, parseInputTokenData, selectMinCompressedTokenAccountsForTransfer, sumUpTokenAmount, transfer, validateSameTokenOwner };
4404
- //# sourceMappingURL=index.js.map