@taquito/utils 18.0.0-RC.0 → 19.0.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.
@@ -9,899 +9,884 @@ import BigNumber from 'bignumber.js';
9
9
  import elliptic from 'elliptic';
10
10
  import toBuffer from 'typedarray-to-buffer';
11
11
 
12
- var Prefix;
13
- (function (Prefix) {
14
- Prefix["TZ1"] = "tz1";
15
- Prefix["TZ2"] = "tz2";
16
- Prefix["TZ3"] = "tz3";
17
- Prefix["TZ4"] = "tz4";
18
- Prefix["KT"] = "KT";
19
- Prefix["KT1"] = "KT1";
20
- Prefix["EDSK2"] = "edsk2";
21
- Prefix["SPSK"] = "spsk";
22
- Prefix["P2SK"] = "p2sk";
23
- Prefix["EDPK"] = "edpk";
24
- Prefix["SPPK"] = "sppk";
25
- Prefix["P2PK"] = "p2pk";
26
- Prefix["BLPK"] = "BLpk";
27
- Prefix["EDESK"] = "edesk";
28
- Prefix["SPESK"] = "spesk";
29
- Prefix["P2ESK"] = "p2esk";
30
- Prefix["EDSK"] = "edsk";
31
- Prefix["EDSIG"] = "edsig";
32
- Prefix["SPSIG"] = "spsig";
33
- Prefix["P2SIG"] = "p2sig";
34
- Prefix["SIG"] = "sig";
35
- Prefix["NET"] = "Net";
36
- Prefix["NCE"] = "nce";
37
- Prefix["B"] = "B";
38
- Prefix["O"] = "o";
39
- Prefix["LO"] = "Lo";
40
- Prefix["LLO"] = "LLo";
41
- Prefix["P"] = "P";
42
- Prefix["CO"] = "Co";
43
- Prefix["ID"] = "id";
44
- Prefix["EXPR"] = "expr";
45
- Prefix["TZ"] = "TZ";
46
- Prefix["VH"] = "vh";
47
- Prefix["SASK"] = "sask";
48
- Prefix["ZET1"] = "zet1";
49
- //rollups
50
- Prefix["TXI"] = "txi";
51
- Prefix["TXM"] = "txm";
52
- Prefix["TXC"] = "txc";
53
- Prefix["TXMR"] = "txmr";
54
- Prefix["TXRL"] = "txM";
55
- Prefix["TXW"] = "txw";
56
- Prefix["SR1"] = "sr1";
57
- Prefix["SRC1"] = "src1";
58
- })(Prefix || (Prefix = {}));
59
- const prefix = {
60
- [Prefix.TZ1]: new Uint8Array([6, 161, 159]),
61
- [Prefix.TZ2]: new Uint8Array([6, 161, 161]),
62
- [Prefix.TZ3]: new Uint8Array([6, 161, 164]),
63
- [Prefix.TZ4]: new Uint8Array([6, 161, 166]),
64
- [Prefix.KT]: new Uint8Array([2, 90, 121]),
65
- [Prefix.KT1]: new Uint8Array([2, 90, 121]),
66
- [Prefix.EDSK]: new Uint8Array([43, 246, 78, 7]),
67
- [Prefix.EDSK2]: new Uint8Array([13, 15, 58, 7]),
68
- [Prefix.SPSK]: new Uint8Array([17, 162, 224, 201]),
69
- [Prefix.P2SK]: new Uint8Array([16, 81, 238, 189]),
70
- [Prefix.EDPK]: new Uint8Array([13, 15, 37, 217]),
71
- [Prefix.SPPK]: new Uint8Array([3, 254, 226, 86]),
72
- [Prefix.P2PK]: new Uint8Array([3, 178, 139, 127]),
73
- [Prefix.BLPK]: new Uint8Array([6, 149, 135, 204]),
74
- [Prefix.EDESK]: new Uint8Array([7, 90, 60, 179, 41]),
75
- [Prefix.SPESK]: new Uint8Array([0x09, 0xed, 0xf1, 0xae, 0x96]),
76
- [Prefix.P2ESK]: new Uint8Array([0x09, 0x30, 0x39, 0x73, 0xab]),
77
- [Prefix.EDSIG]: new Uint8Array([9, 245, 205, 134, 18]),
78
- [Prefix.SPSIG]: new Uint8Array([13, 115, 101, 19, 63]),
79
- [Prefix.P2SIG]: new Uint8Array([54, 240, 44, 52]),
80
- [Prefix.SIG]: new Uint8Array([4, 130, 43]),
81
- [Prefix.NET]: new Uint8Array([87, 82, 0]),
82
- [Prefix.NCE]: new Uint8Array([69, 220, 169]),
83
- [Prefix.B]: new Uint8Array([1, 52]),
84
- [Prefix.O]: new Uint8Array([5, 116]),
85
- [Prefix.LO]: new Uint8Array([133, 233]),
86
- [Prefix.LLO]: new Uint8Array([29, 159, 109]),
87
- [Prefix.P]: new Uint8Array([2, 170]),
88
- [Prefix.CO]: new Uint8Array([79, 179]),
89
- [Prefix.ID]: new Uint8Array([153, 103]),
90
- [Prefix.EXPR]: new Uint8Array([13, 44, 64, 27]),
91
- // Legacy prefix
92
- [Prefix.TZ]: new Uint8Array([2, 90, 121]),
93
- [Prefix.VH]: new Uint8Array([1, 106, 242]),
94
- [Prefix.SASK]: new Uint8Array([11, 237, 20, 92]),
95
- [Prefix.ZET1]: new Uint8Array([18, 71, 40, 223]),
96
- [Prefix.TXI]: new Uint8Array([79, 148, 196]),
97
- [Prefix.TXM]: new Uint8Array([79, 149, 30]),
98
- [Prefix.TXC]: new Uint8Array([79, 148, 17]),
99
- [Prefix.TXMR]: new Uint8Array([18, 7, 206, 87]),
100
- [Prefix.TXRL]: new Uint8Array([79, 146, 82]),
101
- [Prefix.TXW]: new Uint8Array([79, 150, 72]),
102
- [Prefix.SR1]: new Uint8Array([6, 124, 117]),
103
- [Prefix.SRC1]: new Uint8Array([17, 165, 134, 138]),
104
- };
105
- const prefixLength = {
106
- [Prefix.TZ1]: 20,
107
- [Prefix.TZ2]: 20,
108
- [Prefix.TZ3]: 20,
109
- [Prefix.TZ4]: 20,
110
- [Prefix.KT]: 20,
111
- [Prefix.KT1]: 20,
112
- [Prefix.EDPK]: 32,
113
- [Prefix.SPPK]: 33,
114
- [Prefix.P2PK]: 33,
115
- //working with value in comment for base58.ml line 445 but not consistent with the three above
116
- [Prefix.BLPK]: 48,
117
- [Prefix.EDSIG]: 64,
118
- [Prefix.SPSIG]: 64,
119
- [Prefix.P2SIG]: 64,
120
- [Prefix.SIG]: 64,
121
- [Prefix.NET]: 4,
122
- [Prefix.B]: 32,
123
- [Prefix.P]: 32,
124
- [Prefix.O]: 32,
125
- [Prefix.VH]: 32,
126
- [Prefix.SASK]: 169,
127
- [Prefix.ZET1]: 43,
128
- [Prefix.TXI]: 32,
129
- [Prefix.TXM]: 32,
130
- [Prefix.TXC]: 32,
131
- [Prefix.TXMR]: 32,
132
- [Prefix.TXRL]: 32,
133
- [Prefix.TXW]: 32,
134
- [Prefix.SR1]: 20,
135
- [Prefix.SRC1]: 32,
12
+ var Prefix;
13
+ (function (Prefix) {
14
+ Prefix["TZ1"] = "tz1";
15
+ Prefix["TZ2"] = "tz2";
16
+ Prefix["TZ3"] = "tz3";
17
+ Prefix["TZ4"] = "tz4";
18
+ Prefix["KT"] = "KT";
19
+ Prefix["KT1"] = "KT1";
20
+ Prefix["EDSK2"] = "edsk2";
21
+ Prefix["SPSK"] = "spsk";
22
+ Prefix["P2SK"] = "p2sk";
23
+ Prefix["EDPK"] = "edpk";
24
+ Prefix["SPPK"] = "sppk";
25
+ Prefix["P2PK"] = "p2pk";
26
+ Prefix["BLPK"] = "BLpk";
27
+ Prefix["EDESK"] = "edesk";
28
+ Prefix["SPESK"] = "spesk";
29
+ Prefix["P2ESK"] = "p2esk";
30
+ Prefix["EDSK"] = "edsk";
31
+ Prefix["EDSIG"] = "edsig";
32
+ Prefix["SPSIG"] = "spsig";
33
+ Prefix["P2SIG"] = "p2sig";
34
+ Prefix["SIG"] = "sig";
35
+ Prefix["NET"] = "Net";
36
+ Prefix["NCE"] = "nce";
37
+ Prefix["B"] = "B";
38
+ Prefix["O"] = "o";
39
+ Prefix["LO"] = "Lo";
40
+ Prefix["LLO"] = "LLo";
41
+ Prefix["P"] = "P";
42
+ Prefix["CO"] = "Co";
43
+ Prefix["ID"] = "id";
44
+ Prefix["EXPR"] = "expr";
45
+ Prefix["TZ"] = "TZ";
46
+ Prefix["VH"] = "vh";
47
+ Prefix["SASK"] = "sask";
48
+ Prefix["ZET1"] = "zet1";
49
+ Prefix["SR1"] = "sr1";
50
+ Prefix["SRC1"] = "src1";
51
+ })(Prefix || (Prefix = {}));
52
+ const prefix = {
53
+ [Prefix.TZ1]: new Uint8Array([6, 161, 159]),
54
+ [Prefix.TZ2]: new Uint8Array([6, 161, 161]),
55
+ [Prefix.TZ3]: new Uint8Array([6, 161, 164]),
56
+ [Prefix.TZ4]: new Uint8Array([6, 161, 166]),
57
+ [Prefix.KT]: new Uint8Array([2, 90, 121]),
58
+ [Prefix.KT1]: new Uint8Array([2, 90, 121]),
59
+ [Prefix.EDSK]: new Uint8Array([43, 246, 78, 7]),
60
+ [Prefix.EDSK2]: new Uint8Array([13, 15, 58, 7]),
61
+ [Prefix.SPSK]: new Uint8Array([17, 162, 224, 201]),
62
+ [Prefix.P2SK]: new Uint8Array([16, 81, 238, 189]),
63
+ [Prefix.EDPK]: new Uint8Array([13, 15, 37, 217]),
64
+ [Prefix.SPPK]: new Uint8Array([3, 254, 226, 86]),
65
+ [Prefix.P2PK]: new Uint8Array([3, 178, 139, 127]),
66
+ [Prefix.BLPK]: new Uint8Array([6, 149, 135, 204]),
67
+ [Prefix.EDESK]: new Uint8Array([7, 90, 60, 179, 41]),
68
+ [Prefix.SPESK]: new Uint8Array([0x09, 0xed, 0xf1, 0xae, 0x96]),
69
+ [Prefix.P2ESK]: new Uint8Array([0x09, 0x30, 0x39, 0x73, 0xab]),
70
+ [Prefix.EDSIG]: new Uint8Array([9, 245, 205, 134, 18]),
71
+ [Prefix.SPSIG]: new Uint8Array([13, 115, 101, 19, 63]),
72
+ [Prefix.P2SIG]: new Uint8Array([54, 240, 44, 52]),
73
+ [Prefix.SIG]: new Uint8Array([4, 130, 43]),
74
+ [Prefix.NET]: new Uint8Array([87, 82, 0]),
75
+ [Prefix.NCE]: new Uint8Array([69, 220, 169]),
76
+ [Prefix.B]: new Uint8Array([1, 52]),
77
+ [Prefix.O]: new Uint8Array([5, 116]),
78
+ [Prefix.LO]: new Uint8Array([133, 233]),
79
+ [Prefix.LLO]: new Uint8Array([29, 159, 109]),
80
+ [Prefix.P]: new Uint8Array([2, 170]),
81
+ [Prefix.CO]: new Uint8Array([79, 179]),
82
+ [Prefix.ID]: new Uint8Array([153, 103]),
83
+ [Prefix.EXPR]: new Uint8Array([13, 44, 64, 27]),
84
+ // Legacy prefix
85
+ [Prefix.TZ]: new Uint8Array([2, 90, 121]),
86
+ [Prefix.VH]: new Uint8Array([1, 106, 242]),
87
+ [Prefix.SASK]: new Uint8Array([11, 237, 20, 92]),
88
+ [Prefix.ZET1]: new Uint8Array([18, 71, 40, 223]),
89
+ [Prefix.SR1]: new Uint8Array([6, 124, 117]),
90
+ [Prefix.SRC1]: new Uint8Array([17, 165, 134, 138]),
91
+ };
92
+ const prefixLength = {
93
+ [Prefix.TZ1]: 20,
94
+ [Prefix.TZ2]: 20,
95
+ [Prefix.TZ3]: 20,
96
+ [Prefix.TZ4]: 20,
97
+ [Prefix.KT]: 20,
98
+ [Prefix.KT1]: 20,
99
+ [Prefix.EDPK]: 32,
100
+ [Prefix.SPPK]: 33,
101
+ [Prefix.P2PK]: 33,
102
+ //working with value in comment for base58.ml line 445 but not consistent with the three above
103
+ [Prefix.BLPK]: 48,
104
+ [Prefix.EDSIG]: 64,
105
+ [Prefix.SPSIG]: 64,
106
+ [Prefix.P2SIG]: 64,
107
+ [Prefix.SIG]: 64,
108
+ [Prefix.NET]: 4,
109
+ [Prefix.B]: 32,
110
+ [Prefix.P]: 32,
111
+ [Prefix.O]: 32,
112
+ [Prefix.VH]: 32,
113
+ [Prefix.SASK]: 169,
114
+ [Prefix.ZET1]: 43,
115
+ [Prefix.SR1]: 20,
116
+ [Prefix.SRC1]: 32,
136
117
  };
137
118
 
138
- /**
139
- * @description Verify signature of a payload
140
- *
141
- * @param messageBytes The forged message including the magic byte (11 for block,
142
- * 12 for preendorsement/preattestation, 13 for endorsement/attestation, 3 for generic, 5 for the PACK format of michelson)
143
- * @param publicKey The public key to verify the signature against
144
- * @param signature The signature to verify
145
- * @returns A boolean indicating if the signature matches
146
- * @throws {@link InvalidPublicKeyError} | {@link InvalidSignatureError} | {@link InvalidMessageError}
147
- * @example
148
- * ```
149
- * const message = '03d0c10e3ed11d7c6e3357f6ef335bab9e8f2bd54d0ce20c482e241191a6e4b8ce6c01be917311d9ac46959750e405d57e268e2ed9e174a80794fbd504e12a4a000141eb3781afed2f69679ff2bbe1c5375950b0e40d00ff000000005e05050505050507070100000024747a32526773486e74516b72794670707352466261313652546656503539684b72654a4d07070100000024747a315a6672455263414c42776d4171776f6e525859565142445439426a4e6a42484a750001';
150
- * const pk = 'sppk7c7hkPj47yjYFEHX85q46sFJGw6RBrqoVSHwAJAT4e14KJwzoey';
151
- * const sig = 'spsig1cdLkp1RLgUHAp13aRFkZ6MQDPp7xCnjAExGL3MBSdMDmT6JgQSX8cufyDgJRM3sinFtiCzLbsyP6d365EHoNevxhT47nx'
152
- *
153
- * const response = verifySignature(message, pk, sig);
154
- * ```
155
- *
156
- */
157
- function verifySignature(messageBytes, publicKey, signature, watermark) {
158
- const pkPrefix = validatePkAndExtractPrefix(publicKey);
159
- const sigPrefix = validateSigAndExtractPrefix(signature);
160
- const decodedPublicKey = b58cdecode(publicKey, prefix[pkPrefix]);
161
- const decodedSig = b58cdecode(signature, prefix[sigPrefix]);
162
- let messageBuf = hex2buf(validateMessageNotEmpty(messageBytes));
163
- if (typeof watermark !== 'undefined') {
164
- messageBuf = mergebuf(watermark, messageBuf);
165
- }
166
- const bytesHash = hash(messageBuf, 32);
167
- if (pkPrefix === Prefix.EDPK) {
168
- return verifyEdSignature(decodedSig, bytesHash, decodedPublicKey);
169
- }
170
- else if (pkPrefix === Prefix.SPPK) {
171
- return verifySpSignature(decodedSig, bytesHash, decodedPublicKey);
172
- }
173
- else if (pkPrefix === Prefix.P2PK) {
174
- return verifyP2Signature(decodedSig, bytesHash, decodedPublicKey);
175
- }
176
- else {
177
- return false;
178
- }
179
- }
180
- function validateMessageNotEmpty(message) {
181
- if (message === '') {
182
- throw new InvalidMessageError(message, `can't be empty`);
183
- }
184
- return message;
185
- }
186
- function validatePkAndExtractPrefix(publicKey) {
187
- if (publicKey === '') {
188
- throw new InvalidPublicKeyError(publicKey, `can't be empty`);
189
- }
190
- const pkPrefix = publicKey.substring(0, 4);
191
- const publicKeyValidation = validatePublicKey(publicKey);
192
- if (publicKeyValidation !== ValidationResult.VALID) {
193
- throw new InvalidPublicKeyError(publicKey, invalidDetail(publicKeyValidation));
194
- }
195
- return pkPrefix;
196
- }
197
- function validateSigAndExtractPrefix(signature) {
198
- const signaturePrefix = signature.startsWith('sig')
199
- ? signature.substring(0, 3)
200
- : signature.substring(0, 5);
201
- const validation = validateSignature(signature);
202
- if (validation !== ValidationResult.VALID) {
203
- throw new InvalidSignatureError(signature, invalidDetail(validation));
204
- }
205
- return signaturePrefix;
206
- }
207
- function verifyEdSignature(decodedSig, bytesHash, decodedPublicKey) {
208
- try {
209
- return verify(decodedPublicKey, bytesHash, decodedSig);
210
- }
211
- catch (e) {
212
- return false;
213
- }
214
- }
215
- function verifySpSignature(decodedSig, bytesHash, decodedPublicKey) {
216
- const key = new elliptic.ec('secp256k1').keyFromPublic(decodedPublicKey);
217
- return verifySpOrP2Sig(decodedSig, bytesHash, key);
218
- }
219
- function verifyP2Signature(decodedSig, bytesHash, decodedPublicKey) {
220
- const key = new elliptic.ec('p256').keyFromPublic(decodedPublicKey);
221
- return verifySpOrP2Sig(decodedSig, bytesHash, key);
222
- }
223
- function verifySpOrP2Sig(decodedSig, bytesHash, key) {
224
- const hexSig = buf2hex(toBuffer(decodedSig));
225
- const match = hexSig.match(/([a-f\d]{64})/gi);
226
- if (match) {
227
- try {
228
- const [r, s] = match;
229
- return key.verify(bytesHash, { r, s });
230
- }
231
- catch (e) {
232
- return false;
233
- }
234
- }
235
- return false;
119
+ /**
120
+ * @description Verify signature of a payload
121
+ *
122
+ * @param messageBytes The forged message including the magic byte (11 for block,
123
+ * 12 for preattestation/preendorsement, 13 for attestation/endorsement, 3 for generic, 5 for the PACK format of michelson)
124
+ * @param publicKey The public key to verify the signature against
125
+ * @param signature The signature to verify
126
+ * @returns A boolean indicating if the signature matches
127
+ * @throws {@link InvalidPublicKeyError} | {@link InvalidSignatureError} | {@link InvalidMessageError}
128
+ * @example
129
+ * ```
130
+ * const message = '03d0c10e3ed11d7c6e3357f6ef335bab9e8f2bd54d0ce20c482e241191a6e4b8ce6c01be917311d9ac46959750e405d57e268e2ed9e174a80794fbd504e12a4a000141eb3781afed2f69679ff2bbe1c5375950b0e40d00ff000000005e05050505050507070100000024747a32526773486e74516b72794670707352466261313652546656503539684b72654a4d07070100000024747a315a6672455263414c42776d4171776f6e525859565142445439426a4e6a42484a750001';
131
+ * const pk = 'sppk7c7hkPj47yjYFEHX85q46sFJGw6RBrqoVSHwAJAT4e14KJwzoey';
132
+ * const sig = 'spsig1cdLkp1RLgUHAp13aRFkZ6MQDPp7xCnjAExGL3MBSdMDmT6JgQSX8cufyDgJRM3sinFtiCzLbsyP6d365EHoNevxhT47nx'
133
+ *
134
+ * const response = verifySignature(message, pk, sig);
135
+ * ```
136
+ *
137
+ */
138
+ function verifySignature(messageBytes, publicKey, signature, watermark) {
139
+ const pkPrefix = validatePkAndExtractPrefix(publicKey);
140
+ const sigPrefix = validateSigAndExtractPrefix(signature);
141
+ const decodedPublicKey = b58cdecode(publicKey, prefix[pkPrefix]);
142
+ const decodedSig = b58cdecode(signature, prefix[sigPrefix]);
143
+ let messageBuf = hex2buf(validateMessageNotEmpty(messageBytes));
144
+ if (typeof watermark !== 'undefined') {
145
+ messageBuf = mergebuf(watermark, messageBuf);
146
+ }
147
+ const bytesHash = hash(messageBuf, 32);
148
+ if (pkPrefix === Prefix.EDPK) {
149
+ return verifyEdSignature(decodedSig, bytesHash, decodedPublicKey);
150
+ }
151
+ else if (pkPrefix === Prefix.SPPK) {
152
+ return verifySpSignature(decodedSig, bytesHash, decodedPublicKey);
153
+ }
154
+ else if (pkPrefix === Prefix.P2PK) {
155
+ return verifyP2Signature(decodedSig, bytesHash, decodedPublicKey);
156
+ }
157
+ else {
158
+ return false;
159
+ }
160
+ }
161
+ function validateMessageNotEmpty(message) {
162
+ if (message === '') {
163
+ throw new InvalidMessageError(message, `can't be empty`);
164
+ }
165
+ return message;
166
+ }
167
+ function validatePkAndExtractPrefix(publicKey) {
168
+ if (publicKey === '') {
169
+ throw new InvalidPublicKeyError(publicKey, `can't be empty`);
170
+ }
171
+ const pkPrefix = publicKey.substring(0, 4);
172
+ const publicKeyValidation = validatePublicKey(publicKey);
173
+ if (publicKeyValidation !== ValidationResult.VALID) {
174
+ throw new InvalidPublicKeyError(publicKey, invalidDetail(publicKeyValidation));
175
+ }
176
+ return pkPrefix;
177
+ }
178
+ function validateSigAndExtractPrefix(signature) {
179
+ const signaturePrefix = signature.startsWith('sig')
180
+ ? signature.substring(0, 3)
181
+ : signature.substring(0, 5);
182
+ const validation = validateSignature(signature);
183
+ if (validation !== ValidationResult.VALID) {
184
+ throw new InvalidSignatureError(signature, invalidDetail(validation));
185
+ }
186
+ return signaturePrefix;
187
+ }
188
+ function verifyEdSignature(decodedSig, bytesHash, decodedPublicKey) {
189
+ try {
190
+ return verify(decodedPublicKey, bytesHash, decodedSig);
191
+ }
192
+ catch (e) {
193
+ return false;
194
+ }
195
+ }
196
+ function verifySpSignature(decodedSig, bytesHash, decodedPublicKey) {
197
+ const key = new elliptic.ec('secp256k1').keyFromPublic(decodedPublicKey);
198
+ return verifySpOrP2Sig(decodedSig, bytesHash, key);
199
+ }
200
+ function verifyP2Signature(decodedSig, bytesHash, decodedPublicKey) {
201
+ const key = new elliptic.ec('p256').keyFromPublic(decodedPublicKey);
202
+ return verifySpOrP2Sig(decodedSig, bytesHash, key);
203
+ }
204
+ function verifySpOrP2Sig(decodedSig, bytesHash, key) {
205
+ const hexSig = buf2hex(toBuffer(decodedSig));
206
+ const match = hexSig.match(/([a-f\d]{64})/gi);
207
+ if (match) {
208
+ try {
209
+ const [r, s] = match;
210
+ return key.verify(bytesHash, { r, s });
211
+ }
212
+ catch (e) {
213
+ return false;
214
+ }
215
+ }
216
+ return false;
236
217
  }
237
218
 
238
- /**
239
- * @category Error
240
- * @description Error that indicates invalid protocol hash being passed or used
241
- */
242
- class InvalidProtocolHashError extends ParameterValidationError {
243
- constructor(protocolHash, errorDetails) {
244
- super();
245
- this.protocolHash = protocolHash;
246
- this.errorDetails = errorDetails;
247
- this.name = 'InvalidProtocolHashError';
248
- this.name = 'InvalidProtocolHashError';
249
- this.message = `The protocol hash '${protocolHash}' is invalid`;
250
- errorDetails ? (this.message += `: ${errorDetails}`) : null;
251
- }
252
- }
253
- /**
254
- * @category Error
255
- * @description Error that indicates unable to convert data type from one to another
256
- */
257
- class ValueConversionError extends UnsupportedActionError {
258
- constructor(value, desiredType) {
259
- super();
260
- this.value = value;
261
- this.desiredType = desiredType;
262
- this.name = 'ValueConversionError';
263
- this.message = `Unable to convert ${value} to a ${desiredType}`;
264
- }
219
+ /**
220
+ * @category Error
221
+ * @description Error that indicates invalid protocol hash being passed or used
222
+ */
223
+ class InvalidProtocolHashError extends ParameterValidationError {
224
+ constructor(protocolHash, errorDetails) {
225
+ super();
226
+ this.protocolHash = protocolHash;
227
+ this.errorDetails = errorDetails;
228
+ this.name = 'InvalidProtocolHashError';
229
+ this.name = 'InvalidProtocolHashError';
230
+ this.message = `The protocol hash '${protocolHash}' is invalid`;
231
+ errorDetails ? (this.message += `: ${errorDetails}`) : null;
232
+ }
233
+ }
234
+ /**
235
+ * @category Error
236
+ * @description Error that indicates unable to convert data type from one to another
237
+ */
238
+ class ValueConversionError extends UnsupportedActionError {
239
+ constructor(value, desiredType) {
240
+ super();
241
+ this.value = value;
242
+ this.desiredType = desiredType;
243
+ this.name = 'ValueConversionError';
244
+ this.message = `Unable to convert ${value} to a ${desiredType}`;
245
+ }
265
246
  }
266
247
 
267
- var ValidationResult;
268
- (function (ValidationResult) {
269
- ValidationResult[ValidationResult["NO_PREFIX_MATCHED"] = 0] = "NO_PREFIX_MATCHED";
270
- ValidationResult[ValidationResult["INVALID_CHECKSUM"] = 1] = "INVALID_CHECKSUM";
271
- ValidationResult[ValidationResult["INVALID_LENGTH"] = 2] = "INVALID_LENGTH";
272
- ValidationResult[ValidationResult["VALID"] = 3] = "VALID";
273
- })(ValidationResult || (ValidationResult = {}));
274
- function isValidPrefix(value) {
275
- if (typeof value !== 'string') {
276
- return false;
277
- }
278
- return value in prefix;
279
- }
280
- /**
281
- * @description This function is called by the validation functions ([[validateAddress]], [[validateChain]], [[validateContractAddress]], [[validateKeyHash]], [[validateSignature]], [[validatePublicKey]]).
282
- * Verify if the value has the right prefix or return `NO_PREFIX_MATCHED`,
283
- * decode the value using base58 and return `INVALID_CHECKSUM` if it fails,
284
- * check if the length of the value matches the prefix type or return `INVALID_LENGTH`.
285
- * If all checks pass, return `VALID`.
286
- *
287
- * @param value Value to validate
288
- * @param prefixes prefix the value should have
289
- */
290
- function validatePrefixedValue(value, prefixes) {
291
- const match = new RegExp(`^(${prefixes.join('|')})`).exec(value);
292
- if (!match || match.length === 0) {
293
- return ValidationResult.NO_PREFIX_MATCHED;
294
- }
295
- const prefixKey = match[0];
296
- if (!isValidPrefix(prefixKey)) {
297
- return ValidationResult.NO_PREFIX_MATCHED;
298
- }
299
- // Check whether annotation exist before starting validation
300
- if (value.includes('%')) {
301
- value = value.split('%')[0];
302
- }
303
- const kt1Regex = /^(KT1\w{33})$/;
304
- if (!kt1Regex.test(value) && prefixKey === 'KT1') {
305
- return ValidationResult.INVALID_CHECKSUM;
306
- }
307
- // decodeUnsafe return undefined if decoding fail
308
- let decoded = bs58check.decodeUnsafe(value);
309
- if (!decoded) {
310
- return ValidationResult.INVALID_CHECKSUM;
311
- }
312
- decoded = decoded.slice(prefix[prefixKey].length);
313
- if (decoded.length !== prefixLength[prefixKey]) {
314
- return ValidationResult.INVALID_LENGTH;
315
- }
316
- return ValidationResult.VALID;
317
- }
318
- const implicitPrefix = [Prefix.TZ1, Prefix.TZ2, Prefix.TZ3, Prefix.TZ4];
319
- const contractPrefix = [Prefix.KT1];
320
- const signaturePrefix = [Prefix.EDSIG, Prefix.P2SIG, Prefix.SPSIG, Prefix.SIG];
321
- const pkPrefix = [Prefix.EDPK, Prefix.SPPK, Prefix.P2PK, Prefix.BLPK];
322
- const operationPrefix = [Prefix.O];
323
- const protocolPrefix = [Prefix.P];
324
- const blockPrefix = [Prefix.B];
325
- const smartRollupPrefix = [Prefix.SR1];
326
- /**
327
- * @description Used to check if an address or a contract address is valid.
328
- *
329
- * @returns
330
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
331
- *
332
- * @example
333
- * ```
334
- * import { validateAddress } from '@taquito/utils';
335
- * const pkh = 'tz1L9r8mWmRPndRhuvMCWESLGSVeFzQ9NAWx'
336
- * const validation = validateAddress(pkh)
337
- * console.log(validation)
338
- * // This example return 3 which correspond to VALID
339
- * ```
340
- */
341
- function validateAddress(value) {
342
- return validatePrefixedValue(value, [...implicitPrefix, ...contractPrefix, ...smartRollupPrefix]);
343
- }
344
- /**
345
- * @description Used to check if a chain id is valid.
346
- *
347
- * @returns
348
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
349
- *
350
- * @example
351
- * ```
352
- * import { validateChain } from '@taquito/utils';
353
- * const chainId = 'NetXdQprcVkpaWU'
354
- * const validation = validateChain(chainId)
355
- * console.log(validation)
356
- * // This example return 3 which correspond to VALID
357
- * ```
358
- */
359
- function validateChain(value) {
360
- return validatePrefixedValue(value, [Prefix.NET]);
361
- }
362
- /**
363
- * @description Used to check if a contract address is valid.
364
- *
365
- * @returns
366
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
367
- *
368
- * @example
369
- * ```
370
- * import { validateContractAddress } from '@taquito/utils';
371
- * const contractAddress = 'KT1JVErLYTgtY8uGGZ4mso2npTSxqVLDRVbC'
372
- * const validation = validateContractAddress(contractAddress)
373
- * console.log(validation)
374
- * // This example return 3 which correspond to VALID
375
- * ```
376
- */
377
- function validateContractAddress(value) {
378
- return validatePrefixedValue(value, contractPrefix);
379
- }
380
- /**
381
- * @description Used to check if a key hash is valid.
382
- *
383
- * @returns
384
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
385
- *
386
- * @example
387
- * ```
388
- * import { validateKeyHash } from '@taquito/utils';
389
- * const keyHashWithoutPrefix = '1L9r8mWmRPndRhuvMCWESLGSVeFzQ9NAWx'
390
- * const validation = validateKeyHash(keyHashWithoutPrefix)
391
- * console.log(validation)
392
- * // This example return 0 which correspond to NO_PREFIX_MATCHED
393
- * ```
394
- */
395
- function validateKeyHash(value) {
396
- return validatePrefixedValue(value, implicitPrefix);
397
- }
398
- /**
399
- * @description Used to check if a signature is valid.
400
- *
401
- * @returns
402
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
403
- *
404
- * @example
405
- * ```
406
- * import { validateSignature } from '@taquito/utils';
407
- * const signature = 'edsigtkpiSSschcaCt9pUVrpNPf7TTcgvgDEDD6NCEHMy8NNQJCGnMfLZzYoQj74yLjo9wx6MPVV29CvVzgi7qEcEUok3k7AuMg'
408
- * const validation = validateSignature(signature)
409
- * console.log(validation)
410
- * // This example return 3 which correspond to VALID
411
- * ```
412
- */
413
- function validateSignature(value) {
414
- return validatePrefixedValue(value, signaturePrefix);
415
- }
416
- /**
417
- * @description Used to check if a public key is valid.
418
- *
419
- * @returns
420
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
421
- *
422
- * @example
423
- * ```
424
- * import { validatePublicKey } from '@taquito/utils';
425
- * const publicKey = 'edpkvS5QFv7KRGfa3b87gg9DBpxSm3NpSwnjhUjNBQrRUUR66F7C9g'
426
- * const validation = validatePublicKey(publicKey)
427
- * console.log(validation)
428
- * // This example return 3 which correspond to VALID
429
- * ```
430
- */
431
- function validatePublicKey(value) {
432
- return validatePrefixedValue(value, pkPrefix);
433
- }
434
- /**
435
- * @description Used to check if an operation hash is valid.
436
- *
437
- * @returns
438
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
439
- *
440
- * @example
441
- * ```
442
- * import { validateOperation } from '@taquito/utils';
443
- * const operationHash = 'oo6JPEAy8VuMRGaFuMmLNFFGdJgiaKfnmT1CpHJfKP3Ye5ZahiP'
444
- * const validation = validateOperation(operationHash)
445
- * console.log(validation)
446
- * // This example return 3 which correspond to VALID
447
- * ```
448
- */
449
- function validateOperation(value) {
450
- return validatePrefixedValue(value, operationPrefix);
451
- }
452
- /**
453
- * @description Used to check if a protocol hash is valid.
454
- *
455
- * @returns
456
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
457
- *
458
- * @example
459
- * ```
460
- * import { validateProtocol } from '@taquito/utils';
461
- * const protocolHash = 'PtHangz2aRngywmSRGGvrcTyMbbdpWdpFKuS4uMWxg2RaH9i1qx'
462
- * const validation = validateProtocol(protocolHash)
463
- * console.log(validation)
464
- * // This example return 3 which correspond to VALID
465
- * ```
466
- */
467
- function validateProtocol(value) {
468
- return validatePrefixedValue(value, protocolPrefix);
469
- }
470
- /**
471
- * @description Used to check if a block hash is valid.
472
- *
473
- * @returns
474
- * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
475
- *
476
- * @example
477
- * ```
478
- * import { validateBlock } from '@taquito/utils';
479
- * const blockHash = 'PtHangz2aRngywmSRGGvrcTyMbbdpWdpFKuS4uMWxg2RaH9i1qx'
480
- * const validation = validateBlock(blockHash)
481
- * console.log(validation)
482
- * // This example return 3 which correspond to VALID
483
- * ```
484
- */
485
- function validateBlock(value) {
486
- return validatePrefixedValue(value, blockPrefix);
487
- }
488
- /**
489
- * @description Used to check if a spending key is valid.
490
- * @returns 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
491
- *
492
- */
493
- function validateSpendingKey(value) {
494
- return validatePrefixedValue(value, [Prefix.SASK]);
495
- }
496
- function invalidDetail(validation) {
497
- switch (validation) {
498
- case ValidationResult.NO_PREFIX_MATCHED:
499
- return 'with unsupported prefix';
500
- case ValidationResult.INVALID_CHECKSUM:
501
- return 'failed checksum';
502
- case ValidationResult.INVALID_LENGTH:
503
- return 'with incorrect length';
504
- default:
505
- return '';
506
- }
507
- }
508
- function validateSmartRollupAddress(value) {
509
- return validatePrefixedValue(value, [...smartRollupPrefix]);
248
+ var ValidationResult;
249
+ (function (ValidationResult) {
250
+ ValidationResult[ValidationResult["NO_PREFIX_MATCHED"] = 0] = "NO_PREFIX_MATCHED";
251
+ ValidationResult[ValidationResult["INVALID_CHECKSUM"] = 1] = "INVALID_CHECKSUM";
252
+ ValidationResult[ValidationResult["INVALID_LENGTH"] = 2] = "INVALID_LENGTH";
253
+ ValidationResult[ValidationResult["VALID"] = 3] = "VALID";
254
+ })(ValidationResult || (ValidationResult = {}));
255
+ function isValidPrefix(value) {
256
+ if (typeof value !== 'string') {
257
+ return false;
258
+ }
259
+ return value in prefix;
260
+ }
261
+ /**
262
+ * @description This function is called by the validation functions ([[validateAddress]], [[validateChain]], [[validateContractAddress]], [[validateKeyHash]], [[validateSignature]], [[validatePublicKey]]).
263
+ * Verify if the value has the right prefix or return `NO_PREFIX_MATCHED`,
264
+ * decode the value using base58 and return `INVALID_CHECKSUM` if it fails,
265
+ * check if the length of the value matches the prefix type or return `INVALID_LENGTH`.
266
+ * If all checks pass, return `VALID`.
267
+ *
268
+ * @param value Value to validate
269
+ * @param prefixes prefix the value should have
270
+ */
271
+ function validatePrefixedValue(value, prefixes) {
272
+ const match = new RegExp(`^(${prefixes.join('|')})`).exec(value);
273
+ if (!match || match.length === 0) {
274
+ return ValidationResult.NO_PREFIX_MATCHED;
275
+ }
276
+ const prefixKey = match[0];
277
+ if (!isValidPrefix(prefixKey)) {
278
+ return ValidationResult.NO_PREFIX_MATCHED;
279
+ }
280
+ // Check whether annotation exist before starting validation
281
+ if (value.includes('%')) {
282
+ value = value.split('%')[0];
283
+ }
284
+ const kt1Regex = /^(KT1\w{33})$/;
285
+ if (!kt1Regex.test(value) && prefixKey === 'KT1') {
286
+ return ValidationResult.INVALID_CHECKSUM;
287
+ }
288
+ // decodeUnsafe return undefined if decoding fail
289
+ let decoded = bs58check.decodeUnsafe(value);
290
+ if (!decoded) {
291
+ return ValidationResult.INVALID_CHECKSUM;
292
+ }
293
+ decoded = decoded.slice(prefix[prefixKey].length);
294
+ if (decoded.length !== prefixLength[prefixKey]) {
295
+ return ValidationResult.INVALID_LENGTH;
296
+ }
297
+ return ValidationResult.VALID;
298
+ }
299
+ const implicitPrefix = [Prefix.TZ1, Prefix.TZ2, Prefix.TZ3, Prefix.TZ4];
300
+ const contractPrefix = [Prefix.KT1];
301
+ const signaturePrefix = [Prefix.EDSIG, Prefix.P2SIG, Prefix.SPSIG, Prefix.SIG];
302
+ const pkPrefix = [Prefix.EDPK, Prefix.SPPK, Prefix.P2PK, Prefix.BLPK];
303
+ const operationPrefix = [Prefix.O];
304
+ const protocolPrefix = [Prefix.P];
305
+ const blockPrefix = [Prefix.B];
306
+ const smartRollupPrefix = [Prefix.SR1];
307
+ /**
308
+ * @description Used to check if an address or a contract address is valid.
309
+ *
310
+ * @returns
311
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
312
+ *
313
+ * @example
314
+ * ```
315
+ * import { validateAddress } from '@taquito/utils';
316
+ * const pkh = 'tz1L9r8mWmRPndRhuvMCWESLGSVeFzQ9NAWx'
317
+ * const validation = validateAddress(pkh)
318
+ * console.log(validation)
319
+ * // This example return 3 which correspond to VALID
320
+ * ```
321
+ */
322
+ function validateAddress(value) {
323
+ return validatePrefixedValue(value, [...implicitPrefix, ...contractPrefix, ...smartRollupPrefix]);
324
+ }
325
+ /**
326
+ * @description Used to check if a chain id is valid.
327
+ *
328
+ * @returns
329
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
330
+ *
331
+ * @example
332
+ * ```
333
+ * import { validateChain } from '@taquito/utils';
334
+ * const chainId = 'NetXdQprcVkpaWU'
335
+ * const validation = validateChain(chainId)
336
+ * console.log(validation)
337
+ * // This example return 3 which correspond to VALID
338
+ * ```
339
+ */
340
+ function validateChain(value) {
341
+ return validatePrefixedValue(value, [Prefix.NET]);
342
+ }
343
+ /**
344
+ * @description Used to check if a contract address is valid.
345
+ *
346
+ * @returns
347
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
348
+ *
349
+ * @example
350
+ * ```
351
+ * import { validateContractAddress } from '@taquito/utils';
352
+ * const contractAddress = 'KT1JVErLYTgtY8uGGZ4mso2npTSxqVLDRVbC'
353
+ * const validation = validateContractAddress(contractAddress)
354
+ * console.log(validation)
355
+ * // This example return 3 which correspond to VALID
356
+ * ```
357
+ */
358
+ function validateContractAddress(value) {
359
+ return validatePrefixedValue(value, contractPrefix);
360
+ }
361
+ /**
362
+ * @description Used to check if a key hash is valid.
363
+ *
364
+ * @returns
365
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
366
+ *
367
+ * @example
368
+ * ```
369
+ * import { validateKeyHash } from '@taquito/utils';
370
+ * const keyHashWithoutPrefix = '1L9r8mWmRPndRhuvMCWESLGSVeFzQ9NAWx'
371
+ * const validation = validateKeyHash(keyHashWithoutPrefix)
372
+ * console.log(validation)
373
+ * // This example return 0 which correspond to NO_PREFIX_MATCHED
374
+ * ```
375
+ */
376
+ function validateKeyHash(value) {
377
+ return validatePrefixedValue(value, implicitPrefix);
378
+ }
379
+ /**
380
+ * @description Used to check if a signature is valid.
381
+ *
382
+ * @returns
383
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
384
+ *
385
+ * @example
386
+ * ```
387
+ * import { validateSignature } from '@taquito/utils';
388
+ * const signature = 'edsigtkpiSSschcaCt9pUVrpNPf7TTcgvgDEDD6NCEHMy8NNQJCGnMfLZzYoQj74yLjo9wx6MPVV29CvVzgi7qEcEUok3k7AuMg'
389
+ * const validation = validateSignature(signature)
390
+ * console.log(validation)
391
+ * // This example return 3 which correspond to VALID
392
+ * ```
393
+ */
394
+ function validateSignature(value) {
395
+ return validatePrefixedValue(value, signaturePrefix);
396
+ }
397
+ /**
398
+ * @description Used to check if a public key is valid.
399
+ *
400
+ * @returns
401
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
402
+ *
403
+ * @example
404
+ * ```
405
+ * import { validatePublicKey } from '@taquito/utils';
406
+ * const publicKey = 'edpkvS5QFv7KRGfa3b87gg9DBpxSm3NpSwnjhUjNBQrRUUR66F7C9g'
407
+ * const validation = validatePublicKey(publicKey)
408
+ * console.log(validation)
409
+ * // This example return 3 which correspond to VALID
410
+ * ```
411
+ */
412
+ function validatePublicKey(value) {
413
+ return validatePrefixedValue(value, pkPrefix);
414
+ }
415
+ /**
416
+ * @description Used to check if an operation hash is valid.
417
+ *
418
+ * @returns
419
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
420
+ *
421
+ * @example
422
+ * ```
423
+ * import { validateOperation } from '@taquito/utils';
424
+ * const operationHash = 'oo6JPEAy8VuMRGaFuMmLNFFGdJgiaKfnmT1CpHJfKP3Ye5ZahiP'
425
+ * const validation = validateOperation(operationHash)
426
+ * console.log(validation)
427
+ * // This example return 3 which correspond to VALID
428
+ * ```
429
+ */
430
+ function validateOperation(value) {
431
+ return validatePrefixedValue(value, operationPrefix);
432
+ }
433
+ /**
434
+ * @description Used to check if a protocol hash is valid.
435
+ *
436
+ * @returns
437
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
438
+ *
439
+ * @example
440
+ * ```
441
+ * import { validateProtocol } from '@taquito/utils';
442
+ * const protocolHash = 'PtHangz2aRngywmSRGGvrcTyMbbdpWdpFKuS4uMWxg2RaH9i1qx'
443
+ * const validation = validateProtocol(protocolHash)
444
+ * console.log(validation)
445
+ * // This example return 3 which correspond to VALID
446
+ * ```
447
+ */
448
+ function validateProtocol(value) {
449
+ return validatePrefixedValue(value, protocolPrefix);
450
+ }
451
+ /**
452
+ * @description Used to check if a block hash is valid.
453
+ *
454
+ * @returns
455
+ * 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
456
+ *
457
+ * @example
458
+ * ```
459
+ * import { validateBlock } from '@taquito/utils';
460
+ * const blockHash = 'PtHangz2aRngywmSRGGvrcTyMbbdpWdpFKuS4uMWxg2RaH9i1qx'
461
+ * const validation = validateBlock(blockHash)
462
+ * console.log(validation)
463
+ * // This example return 3 which correspond to VALID
464
+ * ```
465
+ */
466
+ function validateBlock(value) {
467
+ return validatePrefixedValue(value, blockPrefix);
468
+ }
469
+ /**
470
+ * @description Used to check if a spending key is valid.
471
+ * @returns 0 (NO_PREFIX_MATCHED), 1 (INVALID_CHECKSUM), 2 (INVALID_LENGTH) or 3 (VALID).
472
+ *
473
+ */
474
+ function validateSpendingKey(value) {
475
+ return validatePrefixedValue(value, [Prefix.SASK]);
476
+ }
477
+ function invalidDetail(validation) {
478
+ switch (validation) {
479
+ case ValidationResult.NO_PREFIX_MATCHED:
480
+ return 'with unsupported prefix';
481
+ case ValidationResult.INVALID_CHECKSUM:
482
+ return 'failed checksum';
483
+ case ValidationResult.INVALID_LENGTH:
484
+ return 'with incorrect length';
485
+ default:
486
+ return '';
487
+ }
488
+ }
489
+ function validateSmartRollupAddress(value) {
490
+ return validatePrefixedValue(value, [...smartRollupPrefix]);
510
491
  }
511
492
 
512
- // IMPORTANT: THIS FILE IS AUTO GENERATED! DO NOT MANUALLY EDIT OR CHECKIN!
513
- const VERSION = {
514
- "commitHash": "21f25a09b87809102b0214544d2c5396eeb5872e",
515
- "version": "18.0.0-RC.0"
493
+ // IMPORTANT: THIS FILE IS AUTO GENERATED! DO NOT MANUALLY EDIT OR CHECKIN!
494
+ const VERSION = {
495
+ "commitHash": "801b9525f497845e778696ccac8df3a7b0f299d8",
496
+ "version": "19.0.0"
516
497
  };
517
498
 
518
- const TZ_DECIMALS = 6;
519
- const MTZ_DECIMALS = 3;
520
- function getDecimal(format) {
521
- switch (format) {
522
- case 'tz':
523
- return TZ_DECIMALS;
524
- case 'mtz':
525
- return MTZ_DECIMALS;
526
- case 'mutez':
527
- default:
528
- return 0;
529
- }
530
- }
531
- function format(from = 'mutez', to = 'mutez', amount) {
532
- const bigNum = new BigNumber(amount);
533
- if (bigNum.isNaN()) {
534
- return amount;
535
- }
536
- return bigNum
537
- .multipliedBy(Math.pow(10, getDecimal(from)))
538
- .dividedBy(Math.pow(10, getDecimal(to)));
499
+ const TZ_DECIMALS = 6;
500
+ const MTZ_DECIMALS = 3;
501
+ function getDecimal(format) {
502
+ switch (format) {
503
+ case 'tz':
504
+ return TZ_DECIMALS;
505
+ case 'mtz':
506
+ return MTZ_DECIMALS;
507
+ case 'mutez':
508
+ default:
509
+ return 0;
510
+ }
511
+ }
512
+ function format(from = 'mutez', to = 'mutez', amount) {
513
+ const bigNum = new BigNumber(amount);
514
+ if (bigNum.isNaN()) {
515
+ return amount;
516
+ }
517
+ return bigNum
518
+ .multipliedBy(Math.pow(10, getDecimal(from)))
519
+ .dividedBy(Math.pow(10, getDecimal(to)));
539
520
  }
540
521
 
541
- /**
542
- * @packageDocumentation
543
- * @module @taquito/utils
544
- */
545
- /**
546
- *
547
- * @description Hash a string using the BLAKE2b algorithm, base58 encode the hash obtained and appends the prefix 'expr' to it
548
- *
549
- * @param value Value in hex
550
- */
551
- function encodeExpr(value) {
552
- const blakeHash = blake.blake2b(hex2buf(value), undefined, 32);
553
- return b58cencode(blakeHash, prefix['expr']);
554
- }
555
- /**
556
- *
557
- * @description Return the operation hash of a signed operation
558
- * @param value Value in hex of a signed operation
559
- */
560
- function encodeOpHash(value) {
561
- const blakeHash = blake.blake2b(hex2buf(value), undefined, 32);
562
- return b58cencode(blakeHash, prefix.o);
563
- }
564
- /**
565
- *
566
- * @description Base58 encode a string or a Uint8Array and append a prefix to it
567
- *
568
- * @param value Value to base58 encode
569
- * @param prefix prefix to append to the encoded string
570
- */
571
- function b58cencode(value, prefix) {
572
- const payloadAr = typeof value === 'string' ? Uint8Array.from(Buffer.from(value, 'hex')) : value;
573
- const n = new Uint8Array(prefix.length + payloadAr.length);
574
- n.set(prefix);
575
- n.set(payloadAr, prefix.length);
576
- return bs58check.encode(Buffer.from(n.buffer));
577
- }
578
- /**
579
- *
580
- * @description Base58 decode a string and remove the prefix from it
581
- *
582
- * @param value Value to base58 decode
583
- * @param prefix prefix to remove from the decoded string
584
- */
585
- const b58cdecode = (enc, prefixArg) => bs58check.decode(enc).slice(prefixArg.length);
586
- /**
587
- *
588
- * @description Base58 decode a string with predefined prefix
589
- *
590
- * @param value Value to base58 decode
591
- */
592
- function b58decode(payload) {
593
- const buf = bs58check.decode(payload);
594
- const prefixMap = {
595
- [prefix.tz1.toString()]: '0000',
596
- [prefix.tz2.toString()]: '0001',
597
- [prefix.tz3.toString()]: '0002',
598
- };
599
- const pref = prefixMap[new Uint8Array(buf.slice(0, 3)).toString()];
600
- if (pref) {
601
- // tz addresses
602
- const hex = buf2hex(buf.slice(3));
603
- return pref + hex;
604
- }
605
- else {
606
- // other (kt addresses)
607
- return '01' + buf2hex(buf.slice(3, 42)) + '00';
608
- }
609
- }
610
- /**
611
- *
612
- * @description b58 decode a string without predefined prefix
613
- * @param value
614
- * @returns string of bytes
615
- */
616
- function b58decodeL2Address(payload) {
617
- const buf = bs58check.decode(payload);
618
- // tz4 address currently
619
- return buf2hex(buf.slice(3, 42));
620
- }
621
- /**
622
- *
623
- * @description Base58 encode an address using predefined prefix
624
- *
625
- * @param value Address to base58 encode (tz1, tz2, tz3 or KT1)
626
- */
627
- function encodePubKey(value) {
628
- if (value.substring(0, 2) === '00') {
629
- const pref = {
630
- '0000': prefix.tz1,
631
- '0001': prefix.tz2,
632
- '0002': prefix.tz3,
633
- };
634
- return b58cencode(value.substring(4), pref[value.substring(0, 4)]);
635
- }
636
- return b58cencode(value.substring(2, 42), prefix.KT);
637
- }
638
- /**
639
- *
640
- * @description Base58 encode an address without predefined prefix
641
- * @param value Address to base58 encode (tz4) hex dec
642
- * @returns return address
643
- */
644
- function encodeL2Address(value) {
645
- return b58cencode(value, prefix.tz4);
646
- }
647
- /**
648
- *
649
- * @description Base58 encode a key according to its prefix
650
- *
651
- * @param value Key to base58 encode
652
- */
653
- function encodeKey(value) {
654
- if (value[0] === '0') {
655
- const pref = {
656
- '00': new Uint8Array([13, 15, 37, 217]),
657
- '01': new Uint8Array([3, 254, 226, 86]),
658
- '02': new Uint8Array([3, 178, 139, 127]),
659
- };
660
- return b58cencode(value.substring(2), pref[value.substring(0, 2)]);
661
- }
662
- }
663
- /**
664
- *
665
- * @description Base58 encode a key hash according to its prefix
666
- *
667
- * @param value Key hash to base58 encode
668
- */
669
- function encodeKeyHash(value) {
670
- if (value[0] === '0') {
671
- const pref = {
672
- '00': new Uint8Array([6, 161, 159]),
673
- '01': new Uint8Array([6, 161, 161]),
674
- '02': new Uint8Array([6, 161, 164]),
675
- };
676
- return b58cencode(value.substring(2), pref[value.substring(0, 2)]);
677
- }
678
- }
679
- /**
680
- *
681
- * @description Convert an hex string to a Uint8Array
682
- *
683
- * @param hex Hex string to convert
684
- * @throws {@link ValueConversionError}
685
- */
686
- const hex2buf = (hex) => {
687
- if (hex.length % 2 !== 0) {
688
- throw new InvalidHexStringError(hex, `: Expecting even number of characters`);
689
- }
690
- const hexDigits = stripHexPrefix(hex);
691
- if (!hexDigits.match(/^([\da-f]{2})*$/gi)) {
692
- throw new InvalidHexStringError(hex, `: Only characters 0-9, a-f and A-F are expected. Optionally, it can be prefixed with '0x'`);
693
- }
694
- const out = new Uint8Array(hexDigits.length / 2);
695
- let j = 0;
696
- for (let i = 0; i < hexDigits.length; i += 2) {
697
- const v = parseInt(hexDigits.slice(i, i + 2), 16);
698
- if (Number.isNaN(v)) {
699
- throw new ValueConversionError(hex, 'Uint8Array');
700
- }
701
- out[j++] = v;
702
- }
703
- return out;
704
- };
705
- /**
706
- *
707
- * @description Merge 2 buffers together
708
- *
709
- * @param b1 First buffer
710
- * @param b2 Second buffer
711
- */
712
- const mergebuf = (b1, b2) => {
713
- const r = new Uint8Array(b1.length + b2.length);
714
- r.set(b1);
715
- r.set(b2, b1.length);
716
- return r;
717
- };
718
- /**
719
- *
720
- * @description Flatten a michelson json representation to an array
721
- *
722
- * @param s michelson json
723
- */
724
- const mic2arr = function me2(s) {
725
- let ret = [];
726
- if (Object.prototype.hasOwnProperty.call(s, 'prim')) {
727
- if (s.prim === 'Pair') {
728
- ret.push(me2(s.args[0]));
729
- ret = ret.concat(me2(s.args[1]));
730
- }
731
- else if (s.prim === 'Elt') {
732
- ret = {
733
- key: me2(s.args[0]),
734
- val: me2(s.args[1]),
735
- };
736
- }
737
- else if (s.prim === 'True') {
738
- ret = true;
739
- }
740
- else if (s.prim === 'False') {
741
- ret = false;
742
- }
743
- }
744
- else if (Array.isArray(s)) {
745
- const sc = s.length;
746
- for (let i = 0; i < sc; i++) {
747
- const n = me2(s[i]);
748
- if (typeof n.key !== 'undefined') {
749
- if (Array.isArray(ret)) {
750
- ret = {
751
- keys: [],
752
- vals: [],
753
- };
754
- }
755
- ret.keys.push(n.key);
756
- ret.vals.push(n.val);
757
- }
758
- else {
759
- ret.push(n);
760
- }
761
- }
762
- }
763
- else if (Object.prototype.hasOwnProperty.call(s, 'string')) {
764
- ret = s.string;
765
- }
766
- else if (Object.prototype.hasOwnProperty.call(s, 'int')) {
767
- ret = parseInt(s.int, 10);
768
- }
769
- else {
770
- ret = s;
771
- }
772
- return ret;
773
- };
774
- /**
775
- *
776
- * @description Convert a buffer to an hex string
777
- *
778
- * @param buffer Buffer to convert
779
- */
780
- const buf2hex = (buffer) => {
781
- const byteArray = new Uint8Array(buffer);
782
- const hexParts = [];
783
- byteArray.forEach((byte) => {
784
- const hex = byte.toString(16);
785
- const paddedHex = `00${hex}`.slice(-2);
786
- hexParts.push(paddedHex);
787
- });
788
- return hexParts.join('');
789
- };
790
- /**
791
- *
792
- * @description Gets Tezos address (PKH) from Public Key
793
- *
794
- * @param publicKey Public Key
795
- * @returns A string of the Tezos address (PKH) that was derived from the given Public Key
796
- */
797
- const getPkhfromPk = (publicKey) => {
798
- let encodingPrefix;
799
- let prefixLen;
800
- const keyPrefix = validatePkAndExtractPrefix(publicKey);
801
- const decoded = b58cdecode(publicKey, prefix[keyPrefix]);
802
- switch (keyPrefix) {
803
- case Prefix.EDPK:
804
- encodingPrefix = prefix[Prefix.TZ1];
805
- prefixLen = prefixLength[Prefix.TZ1];
806
- break;
807
- case Prefix.SPPK:
808
- encodingPrefix = prefix[Prefix.TZ2];
809
- prefixLen = prefixLength[Prefix.TZ2];
810
- break;
811
- case Prefix.P2PK:
812
- encodingPrefix = prefix[Prefix.TZ3];
813
- prefixLen = prefixLength[Prefix.TZ3];
814
- break;
815
- case Prefix.BLPK:
816
- encodingPrefix = prefix[Prefix.TZ4];
817
- prefixLen = prefixLength[Prefix.TZ4];
818
- }
819
- const hashed = hash(decoded, prefixLen);
820
- const result = b58cencode(hashed, encodingPrefix);
821
- return result;
822
- };
823
- /**
824
- *
825
- * @description Convert a string to bytes
826
- *
827
- * @param str String to convert
828
- */
829
- function char2Bytes(str) {
830
- return Buffer.from(str, 'utf8').toString('hex');
831
- }
832
- /**
833
- *
834
- * @description Convert bytes to a string
835
- *
836
- * @param str Bytes to convert
837
- */
838
- function bytes2Char(hex) {
839
- return Buffer.from(hex2buf(hex)).toString('utf8');
840
- }
841
- /**
842
- *
843
- * @description Convert hex string/UintArray/Buffer to bytes
844
- *
845
- * @param hex String value to convert to bytes
846
- */
847
- function hex2Bytes(hex) {
848
- const hexDigits = stripHexPrefix(hex);
849
- if (!hexDigits.match(/^(0x)?([\da-f]{2})*$/gi)) {
850
- throw new InvalidHexStringError(hex, `: Expecting even number of characters: 0-9, a-z, A-Z, optionally prefixed with 0x`);
851
- }
852
- return Buffer.from(hexDigits, 'hex');
853
- }
854
- /**
855
- *
856
- * @description Converts a number or Bignumber to hexadecimal string
857
- *
858
- * @param val The value that will be converted to a hexadecimal string value
859
- */
860
- function toHexBuf(val, bitLength = 8) {
861
- return Buffer.from(num2PaddedHex(val, bitLength), 'hex');
862
- }
863
- /**
864
- *
865
- * @description Converts a number or BigNumber to a padded hexadecimal string
866
- * @param val The value that will be converted into a padded hexadecimal string value
867
- * @param bitLength The length of bits
868
- *
869
- */
870
- function num2PaddedHex(val, bitLength = 8) {
871
- if (new BigNumber(val).isPositive()) {
872
- const nibbleLength = Math.ceil(bitLength / 4);
873
- const hex = val.toString(16);
874
- // check whether nibble (4 bits) length is higher or lowerthan the current hex string length
875
- let targetLength = hex.length >= nibbleLength ? hex.length : nibbleLength;
876
- // make sure the hex string target length is even
877
- targetLength = targetLength % 2 == 0 ? targetLength : targetLength + 1;
878
- return padHexWithZero(hex, targetLength);
879
- }
880
- else {
881
- const twosCompliment = new BigNumber(2)
882
- .pow(bitLength)
883
- .minus(new BigNumber(val).abs());
884
- return twosCompliment.toString(16);
885
- }
886
- }
887
- function padHexWithZero(hex, targetLength) {
888
- const padString = '0';
889
- if (hex.length >= targetLength) {
890
- return hex;
891
- }
892
- else {
893
- const padLength = targetLength - hex.length;
894
- return padString.repeat(padLength) + hex;
895
- }
896
- }
897
- /**
898
- *
899
- * @description Strips the first 2 characters of a hex string (0x)
900
- *
901
- * @param hex string to strip prefix from
902
- */
903
- function stripHexPrefix(hex) {
904
- return hex.startsWith('0x') ? hex.slice(2) : hex;
522
+ /**
523
+ * @packageDocumentation
524
+ * @module @taquito/utils
525
+ */
526
+ /*
527
+ * Some code in this file is originally from sotez and eztz
528
+ * Copyright (c) 2018 Andrew Kishino
529
+ * Copyright (c) 2017 Stephen Andrews
530
+ */
531
+ /**
532
+ *
533
+ * @description Hash a string using the BLAKE2b algorithm, base58 encode the hash obtained and appends the prefix 'expr' to it
534
+ *
535
+ * @param value Value in hex
536
+ */
537
+ function encodeExpr(value) {
538
+ const blakeHash = blake.blake2b(hex2buf(value), undefined, 32);
539
+ return b58cencode(blakeHash, prefix['expr']);
540
+ }
541
+ /**
542
+ *
543
+ * @description Return the operation hash of a signed operation
544
+ * @param value Value in hex of a signed operation
545
+ */
546
+ function encodeOpHash(value) {
547
+ const blakeHash = blake.blake2b(hex2buf(value), undefined, 32);
548
+ return b58cencode(blakeHash, prefix.o);
549
+ }
550
+ /**
551
+ *
552
+ * @description Base58 encode a string or a Uint8Array and append a prefix to it
553
+ *
554
+ * @param value Value to base58 encode
555
+ * @param prefix prefix to append to the encoded string
556
+ */
557
+ function b58cencode(value, prefix) {
558
+ const payloadAr = typeof value === 'string' ? Uint8Array.from(Buffer.from(value, 'hex')) : value;
559
+ const n = new Uint8Array(prefix.length + payloadAr.length);
560
+ n.set(prefix);
561
+ n.set(payloadAr, prefix.length);
562
+ return bs58check.encode(Buffer.from(n.buffer));
563
+ }
564
+ /**
565
+ *
566
+ * @description Base58 decode a string and remove the prefix from it
567
+ *
568
+ * @param value Value to base58 decode
569
+ * @param prefix prefix to remove from the decoded string
570
+ */
571
+ const b58cdecode = (enc, prefixArg) => bs58check.decode(enc).slice(prefixArg.length);
572
+ /**
573
+ *
574
+ * @description Base58 decode a string with predefined prefix
575
+ *
576
+ * @param value Value to base58 decode
577
+ */
578
+ function b58decode(payload) {
579
+ const buf = bs58check.decode(payload);
580
+ const prefixMap = {
581
+ [prefix.tz1.toString()]: '0000',
582
+ [prefix.tz2.toString()]: '0001',
583
+ [prefix.tz3.toString()]: '0002',
584
+ };
585
+ const pref = prefixMap[new Uint8Array(buf.slice(0, 3)).toString()];
586
+ if (pref) {
587
+ // tz addresses
588
+ const hex = buf2hex(buf.slice(3));
589
+ return pref + hex;
590
+ }
591
+ else {
592
+ // other (kt addresses)
593
+ return '01' + buf2hex(buf.slice(3, 42)) + '00';
594
+ }
595
+ }
596
+ /**
597
+ *
598
+ * @description b58 decode a string without predefined prefix
599
+ * @param value
600
+ * @returns string of bytes
601
+ */
602
+ function b58decodeL2Address(payload) {
603
+ const buf = bs58check.decode(payload);
604
+ // tz4 address currently
605
+ return buf2hex(buf.slice(3, 42));
606
+ }
607
+ /**
608
+ *
609
+ * @description Base58 encode an address using predefined prefix
610
+ *
611
+ * @param value Address to base58 encode (tz1, tz2, tz3 or KT1)
612
+ */
613
+ function encodePubKey(value) {
614
+ if (value.substring(0, 2) === '00') {
615
+ const pref = {
616
+ '0000': prefix.tz1,
617
+ '0001': prefix.tz2,
618
+ '0002': prefix.tz3,
619
+ };
620
+ return b58cencode(value.substring(4), pref[value.substring(0, 4)]);
621
+ }
622
+ return b58cencode(value.substring(2, 42), prefix.KT);
623
+ }
624
+ /**
625
+ *
626
+ * @description Base58 encode an address without predefined prefix
627
+ * @param value Address to base58 encode (tz4) hex dec
628
+ * @returns return address
629
+ */
630
+ function encodeL2Address(value) {
631
+ return b58cencode(value, prefix.tz4);
632
+ }
633
+ /**
634
+ *
635
+ * @description Base58 encode a key according to its prefix
636
+ *
637
+ * @param value Key to base58 encode
638
+ */
639
+ function encodeKey(value) {
640
+ if (value[0] === '0') {
641
+ const pref = {
642
+ '00': new Uint8Array([13, 15, 37, 217]),
643
+ '01': new Uint8Array([3, 254, 226, 86]),
644
+ '02': new Uint8Array([3, 178, 139, 127]),
645
+ };
646
+ return b58cencode(value.substring(2), pref[value.substring(0, 2)]);
647
+ }
648
+ }
649
+ /**
650
+ *
651
+ * @description Base58 encode a key hash according to its prefix
652
+ *
653
+ * @param value Key hash to base58 encode
654
+ */
655
+ function encodeKeyHash(value) {
656
+ if (value[0] === '0') {
657
+ const pref = {
658
+ '00': new Uint8Array([6, 161, 159]),
659
+ '01': new Uint8Array([6, 161, 161]),
660
+ '02': new Uint8Array([6, 161, 164]),
661
+ };
662
+ return b58cencode(value.substring(2), pref[value.substring(0, 2)]);
663
+ }
664
+ }
665
+ /**
666
+ *
667
+ * @description Convert an hex string to a Uint8Array
668
+ *
669
+ * @param hex Hex string to convert
670
+ * @throws {@link ValueConversionError}
671
+ */
672
+ const hex2buf = (hex) => {
673
+ if (hex.length % 2 !== 0) {
674
+ throw new InvalidHexStringError(hex, `: Expecting even number of characters`);
675
+ }
676
+ const hexDigits = stripHexPrefix(hex);
677
+ if (!hexDigits.match(/^([\da-f]{2})*$/gi)) {
678
+ throw new InvalidHexStringError(hex, `: Only characters 0-9, a-f and A-F are expected. Optionally, it can be prefixed with '0x'`);
679
+ }
680
+ const out = new Uint8Array(hexDigits.length / 2);
681
+ let j = 0;
682
+ for (let i = 0; i < hexDigits.length; i += 2) {
683
+ const v = parseInt(hexDigits.slice(i, i + 2), 16);
684
+ if (Number.isNaN(v)) {
685
+ throw new ValueConversionError(hex, 'Uint8Array');
686
+ }
687
+ out[j++] = v;
688
+ }
689
+ return out;
690
+ };
691
+ /**
692
+ *
693
+ * @description Merge 2 buffers together
694
+ *
695
+ * @param b1 First buffer
696
+ * @param b2 Second buffer
697
+ */
698
+ const mergebuf = (b1, b2) => {
699
+ const r = new Uint8Array(b1.length + b2.length);
700
+ r.set(b1);
701
+ r.set(b2, b1.length);
702
+ return r;
703
+ };
704
+ /**
705
+ *
706
+ * @description Flatten a michelson json representation to an array
707
+ *
708
+ * @param s michelson json
709
+ */
710
+ const mic2arr = function me2(s) {
711
+ let ret = [];
712
+ if (Object.prototype.hasOwnProperty.call(s, 'prim')) {
713
+ if (s.prim === 'Pair') {
714
+ ret.push(me2(s.args[0]));
715
+ ret = ret.concat(me2(s.args[1]));
716
+ }
717
+ else if (s.prim === 'Elt') {
718
+ ret = {
719
+ key: me2(s.args[0]),
720
+ val: me2(s.args[1]),
721
+ };
722
+ }
723
+ else if (s.prim === 'True') {
724
+ ret = true;
725
+ }
726
+ else if (s.prim === 'False') {
727
+ ret = false;
728
+ }
729
+ }
730
+ else if (Array.isArray(s)) {
731
+ const sc = s.length;
732
+ for (let i = 0; i < sc; i++) {
733
+ const n = me2(s[i]);
734
+ if (typeof n.key !== 'undefined') {
735
+ if (Array.isArray(ret)) {
736
+ ret = {
737
+ keys: [],
738
+ vals: [],
739
+ };
740
+ }
741
+ ret.keys.push(n.key);
742
+ ret.vals.push(n.val);
743
+ }
744
+ else {
745
+ ret.push(n);
746
+ }
747
+ }
748
+ }
749
+ else if (Object.prototype.hasOwnProperty.call(s, 'string')) {
750
+ ret = s.string;
751
+ }
752
+ else if (Object.prototype.hasOwnProperty.call(s, 'int')) {
753
+ ret = parseInt(s.int, 10);
754
+ }
755
+ else {
756
+ ret = s;
757
+ }
758
+ return ret;
759
+ };
760
+ /**
761
+ *
762
+ * @description Convert a Uint8Array to an hex string
763
+ *
764
+ * @param buffer Uint8Array to convert
765
+ */
766
+ const buf2hex = (buffer) => {
767
+ const hexParts = [];
768
+ buffer.forEach((byte) => {
769
+ const hex = byte.toString(16);
770
+ const paddedHex = `00${hex}`.slice(-2);
771
+ hexParts.push(paddedHex);
772
+ });
773
+ return hexParts.join('');
774
+ };
775
+ /**
776
+ *
777
+ * @description Gets Tezos address (PKH) from Public Key
778
+ *
779
+ * @param publicKey Public Key
780
+ * @returns A string of the Tezos address (PKH) that was derived from the given Public Key
781
+ */
782
+ const getPkhfromPk = (publicKey) => {
783
+ let encodingPrefix;
784
+ let prefixLen;
785
+ const keyPrefix = validatePkAndExtractPrefix(publicKey);
786
+ const decoded = b58cdecode(publicKey, prefix[keyPrefix]);
787
+ switch (keyPrefix) {
788
+ case Prefix.EDPK:
789
+ encodingPrefix = prefix[Prefix.TZ1];
790
+ prefixLen = prefixLength[Prefix.TZ1];
791
+ break;
792
+ case Prefix.SPPK:
793
+ encodingPrefix = prefix[Prefix.TZ2];
794
+ prefixLen = prefixLength[Prefix.TZ2];
795
+ break;
796
+ case Prefix.P2PK:
797
+ encodingPrefix = prefix[Prefix.TZ3];
798
+ prefixLen = prefixLength[Prefix.TZ3];
799
+ break;
800
+ case Prefix.BLPK:
801
+ encodingPrefix = prefix[Prefix.TZ4];
802
+ prefixLen = prefixLength[Prefix.TZ4];
803
+ }
804
+ const hashed = hash(decoded, prefixLen);
805
+ const result = b58cencode(hashed, encodingPrefix);
806
+ return result;
807
+ };
808
+ /**
809
+ *
810
+ * @description Convert a string to bytes
811
+ *
812
+ * @param str String to convert
813
+ */
814
+ function char2Bytes(str) {
815
+ return Buffer.from(str, 'utf8').toString('hex');
816
+ }
817
+ /**
818
+ *
819
+ * @description Convert bytes to a string
820
+ *
821
+ * @param str Bytes to convert
822
+ */
823
+ function bytes2Char(hex) {
824
+ return Buffer.from(hex2buf(hex)).toString('utf8');
825
+ }
826
+ /**
827
+ *
828
+ * @description Convert hex string/UintArray/Buffer to bytes
829
+ *
830
+ * @param hex String value to convert to bytes
831
+ */
832
+ function hex2Bytes(hex) {
833
+ const hexDigits = stripHexPrefix(hex);
834
+ if (!hexDigits.match(/^(0x)?([\da-f]{2})*$/gi)) {
835
+ throw new InvalidHexStringError(hex, `: Expecting even number of characters: 0-9, a-z, A-Z, optionally prefixed with 0x`);
836
+ }
837
+ return Buffer.from(hexDigits, 'hex');
838
+ }
839
+ /**
840
+ *
841
+ * @description Converts a number or Bignumber to hexadecimal string
842
+ *
843
+ * @param val The value that will be converted to a hexadecimal string value
844
+ */
845
+ function toHexBuf(val, bitLength = 8) {
846
+ return Buffer.from(num2PaddedHex(val, bitLength), 'hex');
847
+ }
848
+ /**
849
+ *
850
+ * @description Converts a number or BigNumber to a padded hexadecimal string
851
+ * @param val The value that will be converted into a padded hexadecimal string value
852
+ * @param bitLength The length of bits
853
+ *
854
+ */
855
+ function num2PaddedHex(val, bitLength = 8) {
856
+ if (new BigNumber(val).isPositive()) {
857
+ const nibbleLength = Math.ceil(bitLength / 4);
858
+ const hex = val.toString(16);
859
+ // check whether nibble (4 bits) length is higher or lower than the current hex string length
860
+ let targetLength = hex.length >= nibbleLength ? hex.length : nibbleLength;
861
+ // make sure the hex string target length is even
862
+ targetLength = targetLength % 2 == 0 ? targetLength : targetLength + 1;
863
+ return padHexWithZero(hex, targetLength);
864
+ }
865
+ else {
866
+ const twosCompliment = new BigNumber(2)
867
+ .pow(bitLength)
868
+ .minus(new BigNumber(val).abs());
869
+ return twosCompliment.toString(16);
870
+ }
871
+ }
872
+ function padHexWithZero(hex, targetLength) {
873
+ const padString = '0';
874
+ if (hex.length >= targetLength) {
875
+ return hex;
876
+ }
877
+ else {
878
+ const padLength = targetLength - hex.length;
879
+ return padString.repeat(padLength) + hex;
880
+ }
881
+ }
882
+ /**
883
+ *
884
+ * @description Strips the first 2 characters of a hex string (0x)
885
+ *
886
+ * @param hex string to strip prefix from
887
+ */
888
+ function stripHexPrefix(hex) {
889
+ return hex.startsWith('0x') ? hex.slice(2) : hex;
905
890
  }
906
891
 
907
892
  export { InvalidProtocolHashError, Prefix, VERSION, ValidationResult, ValueConversionError, b58cdecode, b58cencode, b58decode, b58decodeL2Address, buf2hex, bytes2Char, char2Bytes, encodeExpr, encodeKey, encodeKeyHash, encodeL2Address, encodeOpHash, encodePubKey, format, getPkhfromPk, hex2Bytes, hex2buf, invalidDetail, isValidPrefix, mergebuf, mic2arr, num2PaddedHex, prefix, prefixLength, stripHexPrefix, toHexBuf, validateAddress, validateBlock, validateChain, validateContractAddress, validateKeyHash, validateOperation, validatePkAndExtractPrefix, validateProtocol, validatePublicKey, validateSignature, validateSmartRollupAddress, validateSpendingKey, verifySignature };