@frequency-chain/ethereum-utils 0.0.0-fe548b

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.
@@ -0,0 +1,512 @@
1
+ import { assert, isHexString, isValidUint16, isValidUint32, isValidUint64String } from './utils.js';
2
+ import { reverseUnifiedAddressToEthereumAddress } from './address.js';
3
+ import { ethers } from 'ethers';
4
+ import { u8aToHex } from '@polkadot/util';
5
+ import { ADD_KEY_DATA_DEFINITION, ADD_PROVIDER_DEFINITION, AUTHORIZED_KEY_DATA_DEFINITION, CLAIM_HANDLE_PAYLOAD_DEFINITION, EIP712_DOMAIN_MAINNET, EIP712_DOMAIN_DEFINITION, ITEMIZED_SIGNATURE_PAYLOAD_DEFINITION_V2, PAGINATED_DELETE_SIGNATURE_PAYLOAD_DEFINITION_V2, PAGINATED_UPSERT_SIGNATURE_PAYLOAD_DEFINITION_V2, PASSKEY_PUBLIC_KEY_DEFINITION, SIWF_SIGNED_REQUEST_PAYLOAD_DEFINITION, EIP712_DOMAIN_TESTNET, RECOVERY_COMMITMENT_PAYLOAD_DEFINITION, } from './signature.definitions.js';
6
+ /**
7
+ * Signing EIP-712 or ERC-191 compatible signature based on payload
8
+ * @param secretKey
9
+ * @param payload
10
+ * @param chain
11
+ */
12
+ export async function sign(secretKey, payload, chain) {
13
+ const signatureType = getSignatureType(payload.type);
14
+ const normalizedPayload = normalizePayload(payload);
15
+ const wallet = new ethers.Wallet(secretKey);
16
+ let signature;
17
+ switch (signatureType) {
18
+ case 'EIP-712':
19
+ // TODO: use correct contract address for different payloads
20
+ signature = await wallet.signTypedData(chain === 'Mainnet-Frequency' ? EIP712_DOMAIN_MAINNET : EIP712_DOMAIN_TESTNET, getTypesFor(payload.type), normalizedPayload);
21
+ break;
22
+ case 'EIP-191':
23
+ signature = await wallet.signMessage(payload.message);
24
+ break;
25
+ default:
26
+ throw new Error(`Unsupported signature type : ${signatureType}`);
27
+ }
28
+ return { Ecdsa: signature };
29
+ }
30
+ /**
31
+ * Verify EIP-712 and ERC-191 signatures based on payload
32
+ * @param ethereumAddress
33
+ * @param signature
34
+ * @param payload
35
+ * @param chain
36
+ */
37
+ export function verifySignature(ethereumAddress, signature, payload, chain) {
38
+ const signatureType = getSignatureType(payload.type);
39
+ const normalizedPayload = normalizePayload(payload);
40
+ let recoveredAddress;
41
+ switch (signatureType) {
42
+ case 'EIP-712':
43
+ // TODO: use correct contract address for different payloads
44
+ recoveredAddress = ethers.verifyTypedData(chain === 'Mainnet-Frequency' ? EIP712_DOMAIN_MAINNET : EIP712_DOMAIN_TESTNET, getTypesFor(payload.type), normalizedPayload, signature);
45
+ break;
46
+ case 'EIP-191':
47
+ recoveredAddress = ethers.verifyMessage(payload.message, signature);
48
+ break;
49
+ default:
50
+ throw new Error(`Unsupported signature type : ${signatureType}`);
51
+ }
52
+ return recoveredAddress.toLowerCase() === ethereumAddress.toLowerCase();
53
+ }
54
+ function normalizePayload(payload) {
55
+ const clonedPayload = Object.assign({}, payload);
56
+ switch (clonedPayload.type) {
57
+ case 'PaginatedUpsertSignaturePayloadV2':
58
+ case 'PaginatedDeleteSignaturePayloadV2':
59
+ case 'ItemizedSignaturePayloadV2':
60
+ case 'PasskeyPublicKey':
61
+ case 'ClaimHandlePayload':
62
+ case 'AddProvider':
63
+ case 'RecoveryCommitmentPayload':
64
+ case 'SiwfLoginRequestPayload':
65
+ break;
66
+ case 'AddKeyData':
67
+ // convert to 20 bytes ethereum address for signature
68
+ if (clonedPayload.newPublicKey.length !== 42) {
69
+ clonedPayload.newPublicKey = reverseUnifiedAddressToEthereumAddress(payload.newPublicKey);
70
+ }
71
+ clonedPayload.newPublicKey = clonedPayload.newPublicKey.toLowerCase();
72
+ break;
73
+ case 'AuthorizedKeyData':
74
+ // convert to 20 bytes ethereum address for signature
75
+ if (clonedPayload.authorizedPublicKey.length !== 42) {
76
+ clonedPayload.authorizedPublicKey = reverseUnifiedAddressToEthereumAddress(payload.authorizedPublicKey);
77
+ }
78
+ clonedPayload.authorizedPublicKey = clonedPayload.authorizedPublicKey.toLowerCase();
79
+ break;
80
+ case 'SiwfSignedRequestPayload':
81
+ if (clonedPayload.userIdentifierAdminUrl == null) {
82
+ clonedPayload.userIdentifierAdminUrl = '';
83
+ }
84
+ break;
85
+ default:
86
+ throw new Error(`Unsupported payload type: ${JSON.stringify(payload)}`);
87
+ }
88
+ // Remove the type field
89
+ const { type, ...payloadWithoutType } = clonedPayload;
90
+ return payloadWithoutType;
91
+ }
92
+ function getTypesFor(payloadType) {
93
+ const PAYLOAD_TYPE_DEFINITIONS = {
94
+ PaginatedUpsertSignaturePayloadV2: PAGINATED_UPSERT_SIGNATURE_PAYLOAD_DEFINITION_V2,
95
+ PaginatedDeleteSignaturePayloadV2: PAGINATED_DELETE_SIGNATURE_PAYLOAD_DEFINITION_V2,
96
+ ItemizedSignaturePayloadV2: ITEMIZED_SIGNATURE_PAYLOAD_DEFINITION_V2,
97
+ PasskeyPublicKey: PASSKEY_PUBLIC_KEY_DEFINITION,
98
+ ClaimHandlePayload: CLAIM_HANDLE_PAYLOAD_DEFINITION,
99
+ AddKeyData: ADD_KEY_DATA_DEFINITION,
100
+ AuthorizedKeyData: AUTHORIZED_KEY_DATA_DEFINITION,
101
+ AddProvider: ADD_PROVIDER_DEFINITION,
102
+ RecoveryCommitmentPayload: RECOVERY_COMMITMENT_PAYLOAD_DEFINITION,
103
+ // offchain signatures
104
+ SiwfSignedRequestPayload: SIWF_SIGNED_REQUEST_PAYLOAD_DEFINITION,
105
+ };
106
+ const definition = PAYLOAD_TYPE_DEFINITIONS[payloadType];
107
+ if (!definition) {
108
+ throw new Error(`Unsupported payload type: ${payloadType}`);
109
+ }
110
+ return definition;
111
+ }
112
+ function getSignatureType(payloadType) {
113
+ if (payloadType === 'SiwfLoginRequestPayload') {
114
+ return 'EIP-191';
115
+ }
116
+ return 'EIP-712';
117
+ }
118
+ /**
119
+ * Build an AddKeyData payload for signature.
120
+ *
121
+ * @param msaId MSA ID (uint64) to add the key
122
+ * @param newPublicKey 32 bytes public key to add in hex or Uint8Array
123
+ * @param expirationBlock Block number after which this payload is invalid
124
+ */
125
+ export function createAddKeyData(msaId, newPublicKey, expirationBlock) {
126
+ const parsedMsaId = typeof msaId === 'string' ? msaId : `${msaId}`;
127
+ const parsedNewPublicKey = typeof newPublicKey === 'object' ? u8aToHex(newPublicKey) : newPublicKey;
128
+ assert(isValidUint64String(parsedMsaId), 'msaId should be a valid uint64');
129
+ assert(isValidUint32(expirationBlock), 'expiration should be a valid uint32');
130
+ assert(isHexString(parsedNewPublicKey), 'newPublicKey should be valid hex');
131
+ return {
132
+ type: 'AddKeyData',
133
+ msaId: parsedMsaId,
134
+ expiration: expirationBlock,
135
+ newPublicKey: parsedNewPublicKey,
136
+ };
137
+ }
138
+ /**
139
+ * Build an AuthorizedKeyData payload for signature.
140
+ *
141
+ * @param msaId MSA ID (uint64) to add the key
142
+ * @param authorizedPublicKey 32 bytes public key to authorize in hex or Uint8Array
143
+ * @param expirationBlock Block number after which this payload is invalid
144
+ */
145
+ export function createAuthorizedKeyData(msaId, newPublicKey, expirationBlock) {
146
+ const parsedMsaId = typeof msaId === 'string' ? msaId : `${msaId}`;
147
+ const parsedNewPublicKey = typeof newPublicKey === 'object' ? u8aToHex(newPublicKey) : newPublicKey;
148
+ assert(isValidUint64String(parsedMsaId), 'msaId should be a valid uint64');
149
+ assert(isValidUint32(expirationBlock), 'expiration should be a valid uint32');
150
+ assert(isHexString(parsedNewPublicKey), 'newPublicKey should be valid hex');
151
+ return {
152
+ type: 'AuthorizedKeyData',
153
+ msaId: parsedMsaId,
154
+ expiration: expirationBlock,
155
+ authorizedPublicKey: parsedNewPublicKey,
156
+ };
157
+ }
158
+ /**
159
+ * Build an AddProvider payload for signature.
160
+ *
161
+ * @param authorizedMsaId MSA ID (uint64) that will be granted provider rights
162
+ * @param schemaIds One or more schema IDs (uint16) the provider may use
163
+ * @param expirationBlock Block number after which this payload is invalid
164
+ */
165
+ export function createAddProvider(authorizedMsaId, schemaIds, expirationBlock) {
166
+ assert(isValidUint64String(authorizedMsaId), 'authorizedMsaId should be a valid uint64');
167
+ assert(isValidUint32(expirationBlock), 'expiration should be a valid uint32');
168
+ schemaIds.forEach((schemaId) => {
169
+ assert(isValidUint16(schemaId), 'schemaId should be a valid uint16');
170
+ });
171
+ return {
172
+ type: 'AddProvider',
173
+ authorizedMsaId: authorizedMsaId.toString(),
174
+ schemaIds,
175
+ expiration: expirationBlock,
176
+ };
177
+ }
178
+ /**
179
+ * Build a RecoveryCommitmentPayload for signature.
180
+ *
181
+ * @param recoveryCommitment The recovery commitment data as a HexString
182
+ * @param expirationBlock Block number after which this payload is invalid
183
+ */
184
+ export function createRecoveryCommitmentPayload(recoveryCommitment, expirationBlock) {
185
+ assert(isHexString(recoveryCommitment), 'recoveryCommitment should be a valid hex string');
186
+ assert(isValidUint32(expirationBlock), 'expiration should be a valid uint32');
187
+ return {
188
+ type: 'RecoveryCommitmentPayload',
189
+ recoveryCommitment: recoveryCommitment,
190
+ expiration: expirationBlock,
191
+ };
192
+ }
193
+ /**
194
+ * Build a ClaimHandlePayload for signature.
195
+ *
196
+ * @param handle The handle the user wishes to claim
197
+ * @param expirationBlock Block number after which this payload is invalid
198
+ */
199
+ export function createClaimHandlePayload(handle, expirationBlock) {
200
+ assert(handle.length > 0, 'handle should be a valid string');
201
+ assert(isValidUint32(expirationBlock), 'expiration should be a valid uint32');
202
+ return {
203
+ type: 'ClaimHandlePayload',
204
+ handle,
205
+ expiration: expirationBlock,
206
+ };
207
+ }
208
+ /**
209
+ * Build a PasskeyPublicKey payload for signature.
210
+ *
211
+ * @param publicKey The passkey’s public key (hex string or raw bytes)
212
+ */
213
+ export function createPasskeyPublicKey(publicKey) {
214
+ const parsedNewPublicKey = typeof publicKey === 'object' ? u8aToHex(publicKey) : publicKey;
215
+ assert(isHexString(parsedNewPublicKey), 'publicKey should be valid hex');
216
+ return {
217
+ type: 'PasskeyPublicKey',
218
+ publicKey: parsedNewPublicKey,
219
+ };
220
+ }
221
+ export function createItemizedAddAction(data) {
222
+ const parsedData = typeof data === 'object' ? u8aToHex(data) : data;
223
+ assert(isHexString(parsedData), 'itemized data should be valid hex');
224
+ return { actionType: 'Add', data, index: 0 };
225
+ }
226
+ export function createItemizedDeleteAction(index) {
227
+ assert(isValidUint16(index), 'itemized index should be a valid uint16');
228
+ return { actionType: 'Delete', data: '0x', index };
229
+ }
230
+ /**
231
+ * Build an ItemizedSignaturePayloadV2 for signing.
232
+ *
233
+ * @param schemaId uint16 schema identifier
234
+ * @param targetHash uint32 page hash
235
+ * @param expiration uint32 expiration block
236
+ * @param actions Array of Add/Delete itemized actions
237
+ */
238
+ export function createItemizedSignaturePayloadV2(schemaId, targetHash, expiration, actions) {
239
+ assert(isValidUint16(schemaId), 'schemaId should be a valid uint16');
240
+ assert(isValidUint32(targetHash), 'targetHash should be a valid uint32');
241
+ assert(isValidUint32(expiration), 'expiration should be a valid uint32');
242
+ assert(actions.length > 0, 'At least one action is required for ItemizedSignaturePayloadV2');
243
+ return {
244
+ type: 'ItemizedSignaturePayloadV2',
245
+ schemaId,
246
+ targetHash,
247
+ expiration,
248
+ actions,
249
+ };
250
+ }
251
+ /**
252
+ * Build a PaginatedDeleteSignaturePayloadV2 for signing.
253
+ *
254
+ * @param schemaId uint16 schema identifier
255
+ * @param pageId uint16 page identifier
256
+ * @param targetHash uint32 page hash
257
+ * @param expiration uint32 expiration block
258
+ */
259
+ export function createPaginatedDeleteSignaturePayloadV2(schemaId, pageId, targetHash, expiration) {
260
+ assert(isValidUint16(schemaId), 'schemaId should be a valid uint16');
261
+ assert(isValidUint16(pageId), 'pageId should be a valid uint16');
262
+ assert(isValidUint32(targetHash), 'targetHash should be a valid uint32');
263
+ assert(isValidUint32(expiration), 'expiration should be a valid uint32');
264
+ return {
265
+ type: 'PaginatedDeleteSignaturePayloadV2',
266
+ schemaId,
267
+ pageId,
268
+ targetHash,
269
+ expiration,
270
+ };
271
+ }
272
+ /**
273
+ * Build a PaginatedUpsertSignaturePayloadV2 for signing.
274
+ *
275
+ * @param schemaId uint16 schema identifier
276
+ * @param pageId uint16 page identifier
277
+ * @param targetHash uint32 page hash
278
+ * @param expiration uint32 expiration block
279
+ * @param payload HexString or Uint8Array data to upsert
280
+ */
281
+ export function createPaginatedUpsertSignaturePayloadV2(schemaId, pageId, targetHash, expiration, payload) {
282
+ const parsedPayload = typeof payload === 'object' ? u8aToHex(payload) : payload;
283
+ assert(isValidUint16(schemaId), 'schemaId should be a valid uint16');
284
+ assert(isValidUint16(pageId), 'pageId should be a valid uint16');
285
+ assert(isValidUint32(targetHash), 'targetHash should be a valid uint32');
286
+ assert(isValidUint32(expiration), 'expiration should be a valid uint32');
287
+ assert(isHexString(parsedPayload), 'payload should be valid hex');
288
+ return {
289
+ type: 'PaginatedUpsertSignaturePayloadV2',
290
+ schemaId,
291
+ pageId,
292
+ targetHash,
293
+ expiration,
294
+ payload: parsedPayload,
295
+ };
296
+ }
297
+ /**
298
+ * Build an SiwfSignedRequestPayload payload for signature.
299
+ *
300
+ * @param callback Callback URL for login
301
+ * @param permissions One or more schema IDs (uint16) the provider may use
302
+ * @param userIdentifierAdminUrl Only used for custom integration situations.
303
+ */
304
+ export function createSiwfSignedRequestPayload(callback, permissions, userIdentifierAdminUrl) {
305
+ permissions.forEach((schemaId) => {
306
+ assert(isValidUint16(schemaId), 'permission should be a valid uint16');
307
+ });
308
+ return {
309
+ type: 'SiwfSignedRequestPayload',
310
+ callback: callback,
311
+ permissions,
312
+ userIdentifierAdminUrl,
313
+ };
314
+ }
315
+ /**
316
+ * Build an SiwfLoginRequestPayload payload for signature.
317
+ *
318
+ * @param message login message
319
+ */
320
+ export function createSiwfLoginRequestPayload(message) {
321
+ return {
322
+ type: 'SiwfLoginRequestPayload',
323
+ message,
324
+ };
325
+ }
326
+ /**
327
+ * Returns the EIP-712 browser request for a AddKeyData for signing.
328
+ *
329
+ * @param msaId MSA ID (uint64) to add the key
330
+ * @param newPublicKey 32 bytes public key to add in hex or Uint8Array
331
+ * @param expirationBlock Block number after which this payload is invalid
332
+ * @param domain
333
+ */
334
+ export function getEip712BrowserRequestAddKeyData(msaId, newPublicKey, expirationBlock, domain = EIP712_DOMAIN_MAINNET) {
335
+ const message = createAddKeyData(msaId, newPublicKey, expirationBlock);
336
+ const normalized = normalizePayload(message);
337
+ return createEip712Payload(ADD_KEY_DATA_DEFINITION, message.type, domain, normalized);
338
+ }
339
+ /**
340
+ * Returns the EIP-712 browser request for a AuthorizedKeyData for signing.
341
+ *
342
+ * @param msaId MSA ID (uint64) to add the key
343
+ * @param authorizedPublicKey 32 bytes public key to add in hex or Uint8Array
344
+ * @param expirationBlock Block number after which this payload is invalid
345
+ * @param domain
346
+ */
347
+ export function getEip712BrowserRequestAuthorizedKeyData(msaId, authorizedPublicKey, expirationBlock, domain = EIP712_DOMAIN_MAINNET) {
348
+ const message = createAuthorizedKeyData(msaId, authorizedPublicKey, expirationBlock);
349
+ const normalized = normalizePayload(message);
350
+ return createEip712Payload(AUTHORIZED_KEY_DATA_DEFINITION, message.type, domain, normalized);
351
+ }
352
+ /**
353
+ * Returns the EIP-712 browser request for a AddProvider for signing.
354
+ *
355
+ * @param authorizedMsaId MSA ID (uint64) that will be granted provider rights
356
+ * @param schemaIds One or more schema IDs (uint16) the provider may use
357
+ * @param expirationBlock Block number after which this payload is invalid
358
+ * @param domain
359
+ */
360
+ export function getEip712BrowserRequestAddProvider(authorizedMsaId, schemaIds, expirationBlock, domain = EIP712_DOMAIN_MAINNET) {
361
+ const message = createAddProvider(authorizedMsaId, schemaIds, expirationBlock);
362
+ const normalized = normalizePayload(message);
363
+ return createEip712Payload(ADD_PROVIDER_DEFINITION, message.type, domain, normalized);
364
+ }
365
+ /**
366
+ * Returns the EIP-712 browser request for a RecoveryCommitmentPayload for signing.
367
+ *
368
+ * @param recoveryCommitment The recovery commitment data as a Uint8Array
369
+ * @param expirationBlock Block number after which this payload is invalid
370
+ * @param domain
371
+ */
372
+ export function getEip712BrowserRequestRecoveryCommitmentPayload(recoveryCommitment, expirationBlock, domain = EIP712_DOMAIN_MAINNET) {
373
+ const message = createRecoveryCommitmentPayload(recoveryCommitment, expirationBlock);
374
+ const normalized = normalizePayload(message);
375
+ return createEip712Payload(RECOVERY_COMMITMENT_PAYLOAD_DEFINITION, message.type, domain, normalized);
376
+ }
377
+ /**
378
+ * Returns the EIP-712 browser request for a PaginatedUpsertSignaturePayloadV2 for signing.
379
+ *
380
+ * @param schemaId uint16 schema identifier
381
+ * @param pageId uint16 page identifier
382
+ * @param targetHash uint32 page hash
383
+ * @param expiration uint32 expiration block
384
+ * @param payload HexString or Uint8Array data to upsert
385
+ * @param domain
386
+ */
387
+ export function getEip712BrowserRequestPaginatedUpsertSignaturePayloadV2(schemaId, pageId, targetHash, expiration, payload, domain = EIP712_DOMAIN_MAINNET) {
388
+ const message = createPaginatedUpsertSignaturePayloadV2(schemaId, pageId, targetHash, expiration, payload);
389
+ const normalized = normalizePayload(message);
390
+ return createEip712Payload(PAGINATED_UPSERT_SIGNATURE_PAYLOAD_DEFINITION_V2, message.type, domain, normalized);
391
+ }
392
+ /**
393
+ * Returns the EIP-712 browser request for a PaginatedDeleteSignaturePayloadV2 for signing.
394
+ *
395
+ * @param schemaId uint16 schema identifier
396
+ * @param pageId uint16 page identifier
397
+ * @param targetHash uint32 page hash
398
+ * @param expiration uint32 expiration block
399
+ * @param domain
400
+ */
401
+ export function getEip712BrowserRequestPaginatedDeleteSignaturePayloadV2(schemaId, pageId, targetHash, expiration, domain = EIP712_DOMAIN_MAINNET) {
402
+ const message = createPaginatedDeleteSignaturePayloadV2(schemaId, pageId, targetHash, expiration);
403
+ const normalized = normalizePayload(message);
404
+ return createEip712Payload(PAGINATED_DELETE_SIGNATURE_PAYLOAD_DEFINITION_V2, message.type, domain, normalized);
405
+ }
406
+ /**
407
+ * Returns the EIP-712 browser request for a ItemizedSignaturePayloadV2 for signing.
408
+ *
409
+ * @param schemaId uint16 schema identifier
410
+ * @param targetHash uint32 page hash
411
+ * @param expiration uint32 expiration block
412
+ * @param actions Array of Add/Delete itemized actions
413
+ * @param domain
414
+ */
415
+ export function getEip712BrowserRequestItemizedSignaturePayloadV2(schemaId, targetHash, expiration, actions, domain = EIP712_DOMAIN_MAINNET) {
416
+ const message = createItemizedSignaturePayloadV2(schemaId, targetHash, expiration, actions);
417
+ const normalized = normalizePayload(message);
418
+ return createEip712Payload(ITEMIZED_SIGNATURE_PAYLOAD_DEFINITION_V2, message.type, domain, normalized);
419
+ }
420
+ /**
421
+ * Returns the EIP-712 browser request for a ClaimHandlePayload for signing.
422
+ *
423
+ * @param handle The handle the user wishes to claim
424
+ * @param expirationBlock Block number after which this payload is invalid
425
+ * @param domain
426
+ */
427
+ export function getEip712BrowserRequestClaimHandlePayload(handle, expirationBlock, domain = EIP712_DOMAIN_MAINNET) {
428
+ const message = createClaimHandlePayload(handle, expirationBlock);
429
+ const normalized = normalizePayload(message);
430
+ return createEip712Payload(CLAIM_HANDLE_PAYLOAD_DEFINITION, message.type, domain, normalized);
431
+ }
432
+ /**
433
+ * Returns the EIP-712 browser request for a PasskeyPublicKey for signing.
434
+ *
435
+ * @param publicKey The passkey’s public key (hex string or raw bytes)
436
+ * @param domain
437
+ */
438
+ export function getEip712BrowserRequestPasskeyPublicKey(publicKey, domain = EIP712_DOMAIN_MAINNET) {
439
+ const message = createPasskeyPublicKey(publicKey);
440
+ const normalized = normalizePayload(message);
441
+ return createEip712Payload(PASSKEY_PUBLIC_KEY_DEFINITION, message.type, domain, normalized);
442
+ }
443
+ /**
444
+ * Returns the EIP-712 browser request for a SiwfSignedRequestPayload for signing.
445
+ *
446
+ * @param callback Callback URL for login
447
+ * @param permissions One or more schema IDs (uint16) the provider may use
448
+ * @param userIdentifierAdminUrl Only used for custom integration situations.
449
+ * @param domain
450
+ */
451
+ export function getEip712BrowserRequestSiwfSignedRequestPayload(callback, permissions, userIdentifierAdminUrl, domain = EIP712_DOMAIN_MAINNET) {
452
+ const message = createSiwfSignedRequestPayload(callback, permissions, userIdentifierAdminUrl);
453
+ const normalized = normalizePayload(message);
454
+ return createEip712Payload(SIWF_SIGNED_REQUEST_PAYLOAD_DEFINITION, message.type, domain, normalized);
455
+ }
456
+ function createEip712Payload(typeDefinition, primaryType, domain, message) {
457
+ return {
458
+ types: {
459
+ ...EIP712_DOMAIN_DEFINITION,
460
+ ...typeDefinition,
461
+ },
462
+ primaryType,
463
+ domain,
464
+ message,
465
+ };
466
+ }
467
+ /**
468
+ * Returns An ethereum compatible signature for the extrinsic
469
+ * @param ethereumPair
470
+ */
471
+ export function getEthereumRegularSigner(ethereumPair) {
472
+ return {
473
+ signRaw: async (payload) => {
474
+ const sig = ethereumPair.sign(payload.data);
475
+ const prefixedSignature = new Uint8Array(sig.length + 1);
476
+ prefixedSignature[0] = 2;
477
+ prefixedSignature.set(sig, 1);
478
+ const hex = u8aToHex(prefixedSignature);
479
+ return {
480
+ signature: hex,
481
+ };
482
+ },
483
+ };
484
+ }
485
+ /**
486
+ * This custom signer can get used to mimic EIP-191 message signing. By replacing the `ethereumPair.sign` with
487
+ * any wallet call we can sign any extrinsic with any wallet
488
+ * @param ethereumPair
489
+ */
490
+ export function getEthereumMessageSigner(ethereumPair) {
491
+ return {
492
+ signRaw: async (payload) => {
493
+ const sig = ethereumPair.sign(prefixEthereumTags(payload.data));
494
+ const prefixedSignature = new Uint8Array(sig.length + 1);
495
+ prefixedSignature[0] = 2;
496
+ prefixedSignature.set(sig, 1);
497
+ const hex = u8aToHex(prefixedSignature);
498
+ return {
499
+ signature: hex,
500
+ };
501
+ },
502
+ };
503
+ }
504
+ /**
505
+ * prefixing with the EIP-191 for personal_sign messages (this gets wrapped automatically in Metamask)
506
+ * @param hexPayload
507
+ */
508
+ function prefixEthereumTags(hexPayload) {
509
+ const wrapped = `\x19Ethereum Signed Message:\n${hexPayload.length}${hexPayload}`;
510
+ const buffer = Buffer.from(wrapped, 'utf-8');
511
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.length);
512
+ }
package/esm/utils.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Validate that a number is a valid uint16 (0 to 65535)
3
+ */
4
+ export function isValidUint16(value) {
5
+ return Number.isInteger(value) && value >= 0 && value <= 65535;
6
+ }
7
+ /**
8
+ * Validate that a number is a valid uint32 (0 to 4294967295)
9
+ */
10
+ export function isValidUint32(value) {
11
+ return Number.isInteger(value) && value >= 0 && value <= 4294967295;
12
+ }
13
+ /**
14
+ * Validate that a number is a valid uint64 (0 to 18446744073709551615n)
15
+ */
16
+ export function isValidUint64String(value) {
17
+ const bigIntValue = typeof value === 'string' ? BigInt(value) : value;
18
+ return bigIntValue >= 0 && bigIntValue <= 18446744073709551615n;
19
+ }
20
+ /**
21
+ * Validate that a string is a valid hex string
22
+ */
23
+ export function isHexString(value) {
24
+ // Check if string starts with '0x' and contains only hex characters
25
+ const hexRegex = /^0[xX][0-9a-fA-F]*$/;
26
+ const isHex = hexRegex.test(value);
27
+ return isHex && value.length % 2 === 0;
28
+ }
29
+ /**
30
+ * Universal assert function
31
+ * @param condition
32
+ * @param message
33
+ */
34
+ export function assert(condition, message) {
35
+ if (!condition) {
36
+ throw new Error(message || ' Assertion failed');
37
+ }
38
+ }
package/index.d.ts ADDED
@@ -0,0 +1,115 @@
1
+ import * as payloads from './payloads.js';
2
+ export * from './payloads.js';
3
+ export * from './signature.js';
4
+ export * from './signature.definitions.js';
5
+ export * from './address.js';
6
+ declare const _default: {
7
+ sign(secretKey: payloads.HexString, payload: payloads.SupportedPayload, chain: payloads.ChainType): Promise<payloads.EcdsaSignature>;
8
+ verifySignature(ethereumAddress: payloads.HexString, signature: payloads.HexString, payload: payloads.SupportedPayload, chain: payloads.ChainType): boolean;
9
+ createAddKeyData(msaId: string | bigint, newPublicKey: payloads.HexString | Uint8Array, expirationBlock: number): payloads.AddKeyData;
10
+ createAuthorizedKeyData(msaId: string | bigint, newPublicKey: payloads.HexString | Uint8Array, expirationBlock: number): payloads.AuthorizedKeyData;
11
+ createAddProvider(authorizedMsaId: string | bigint, schemaIds: number[], expirationBlock: number): payloads.AddProvider;
12
+ createRecoveryCommitmentPayload(recoveryCommitment: payloads.HexString, expirationBlock: number): payloads.RecoveryCommitmentPayload;
13
+ createClaimHandlePayload(handle: string, expirationBlock: number): payloads.ClaimHandlePayload;
14
+ createPasskeyPublicKey(publicKey: payloads.HexString | Uint8Array): payloads.PasskeyPublicKey;
15
+ createItemizedAddAction(data: payloads.HexString | Uint8Array): payloads.AddItemizedAction;
16
+ createItemizedDeleteAction(index: number): payloads.DeleteItemizedAction;
17
+ createItemizedSignaturePayloadV2(schemaId: number, targetHash: number, expiration: number, actions: payloads.ItemizedAction[]): payloads.ItemizedSignaturePayloadV2;
18
+ createPaginatedDeleteSignaturePayloadV2(schemaId: number, pageId: number, targetHash: number, expiration: number): payloads.PaginatedDeleteSignaturePayloadV2;
19
+ createPaginatedUpsertSignaturePayloadV2(schemaId: number, pageId: number, targetHash: number, expiration: number, payload: payloads.HexString | Uint8Array): payloads.PaginatedUpsertSignaturePayloadV2;
20
+ createSiwfSignedRequestPayload(callback: string, permissions: number[], userIdentifierAdminUrl?: string): payloads.SiwfSignedRequestPayload;
21
+ createSiwfLoginRequestPayload(message: string): payloads.SiwfLoginRequestPayload;
22
+ getEip712BrowserRequestAddKeyData(msaId: string | bigint, newPublicKey: payloads.HexString | Uint8Array, expirationBlock: number, domain?: payloads.EipDomainPayload): unknown;
23
+ getEip712BrowserRequestAuthorizedKeyData(msaId: string | bigint, authorizedPublicKey: payloads.HexString | Uint8Array, expirationBlock: number, domain?: payloads.EipDomainPayload): unknown;
24
+ getEip712BrowserRequestAddProvider(authorizedMsaId: string | bigint, schemaIds: number[], expirationBlock: number, domain?: payloads.EipDomainPayload): unknown;
25
+ getEip712BrowserRequestRecoveryCommitmentPayload(recoveryCommitment: payloads.HexString, expirationBlock: number, domain?: payloads.EipDomainPayload): unknown;
26
+ getEip712BrowserRequestPaginatedUpsertSignaturePayloadV2(schemaId: number, pageId: number, targetHash: number, expiration: number, payload: payloads.HexString | Uint8Array, domain?: payloads.EipDomainPayload): unknown;
27
+ getEip712BrowserRequestPaginatedDeleteSignaturePayloadV2(schemaId: number, pageId: number, targetHash: number, expiration: number, domain?: payloads.EipDomainPayload): unknown;
28
+ getEip712BrowserRequestItemizedSignaturePayloadV2(schemaId: number, targetHash: number, expiration: number, actions: payloads.ItemizedAction[], domain?: payloads.EipDomainPayload): unknown;
29
+ getEip712BrowserRequestClaimHandlePayload(handle: string, expirationBlock: number, domain?: payloads.EipDomainPayload): unknown;
30
+ getEip712BrowserRequestPasskeyPublicKey(publicKey: payloads.HexString | Uint8Array, domain?: payloads.EipDomainPayload): unknown;
31
+ getEip712BrowserRequestSiwfSignedRequestPayload(callback: string, permissions: number[], userIdentifierAdminUrl?: string, domain?: payloads.EipDomainPayload): unknown;
32
+ getEthereumRegularSigner(ethereumPair: import("@polkadot/keyring/types.js").KeyringPair): import("@polkadot/types/types/extrinsic.js").Signer;
33
+ getEthereumMessageSigner(ethereumPair: import("@polkadot/keyring/types.js").KeyringPair): import("@polkadot/types/types/extrinsic.js").Signer;
34
+ EIP712_DOMAIN_DEFINITION: {
35
+ EIP712Domain: {
36
+ name: string;
37
+ type: string;
38
+ }[];
39
+ };
40
+ EIP712_DOMAIN_MAINNET: payloads.EipDomainPayload;
41
+ EIP712_DOMAIN_TESTNET: payloads.EipDomainPayload;
42
+ ADD_PROVIDER_DEFINITION: {
43
+ AddProvider: {
44
+ name: string;
45
+ type: string;
46
+ }[];
47
+ };
48
+ ADD_KEY_DATA_DEFINITION: {
49
+ AddKeyData: {
50
+ name: string;
51
+ type: string;
52
+ }[];
53
+ };
54
+ AUTHORIZED_KEY_DATA_DEFINITION: {
55
+ AuthorizedKeyData: {
56
+ name: string;
57
+ type: string;
58
+ }[];
59
+ };
60
+ RECOVERY_COMMITMENT_PAYLOAD_DEFINITION: {
61
+ RecoveryCommitmentPayload: {
62
+ name: string;
63
+ type: string;
64
+ }[];
65
+ };
66
+ CLAIM_HANDLE_PAYLOAD_DEFINITION: {
67
+ ClaimHandlePayload: {
68
+ name: string;
69
+ type: string;
70
+ }[];
71
+ };
72
+ PASSKEY_PUBLIC_KEY_DEFINITION: {
73
+ PasskeyPublicKey: {
74
+ name: string;
75
+ type: string;
76
+ }[];
77
+ };
78
+ PAGINATED_DELETE_SIGNATURE_PAYLOAD_DEFINITION_V2: {
79
+ PaginatedDeleteSignaturePayloadV2: {
80
+ name: string;
81
+ type: string;
82
+ }[];
83
+ };
84
+ PAGINATED_UPSERT_SIGNATURE_PAYLOAD_DEFINITION_V2: {
85
+ PaginatedUpsertSignaturePayloadV2: {
86
+ name: string;
87
+ type: string;
88
+ }[];
89
+ };
90
+ ITEMIZED_SIGNATURE_PAYLOAD_DEFINITION_V2: {
91
+ ItemizedSignaturePayloadV2: {
92
+ name: string;
93
+ type: string;
94
+ }[];
95
+ ItemAction: {
96
+ name: string;
97
+ type: string;
98
+ }[];
99
+ };
100
+ SIWF_SIGNED_REQUEST_PAYLOAD_DEFINITION: {
101
+ SiwfSignedRequestPayload: {
102
+ name: string;
103
+ type: string;
104
+ }[];
105
+ };
106
+ createRandomKey(): payloads.EthereumKeyPair;
107
+ ethereumAddressToKeyringPair(ethereumAddress: import("@polkadot/types/interfaces/types.js").H160): import("@polkadot/keyring/types.js").KeyringPair;
108
+ getUnifiedAddress(pair: import("@polkadot/keyring/types.js").KeyringPair): string;
109
+ getUnifiedPublicKey(pair: import("@polkadot/keyring/types.js").KeyringPair): Uint8Array;
110
+ reverseUnifiedAddressToEthereumAddress(unifiedAddress: payloads.HexString): payloads.HexString;
111
+ getSS58AccountFromEthereumAccount(accountId20Hex: string): string;
112
+ getKeyringPairFromSecp256k1PrivateKey(secretKey: Uint8Array): import("@polkadot/keyring/types.js").KeyringPair;
113
+ getAccountId20MultiAddress(pair: import("@polkadot/keyring/types.js").KeyringPair): payloads.Address20MultiAddress;
114
+ };
115
+ export default _default;