@cofhe/sdk 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/adapters/ethers5.test.ts +174 -0
  3. package/adapters/ethers5.ts +36 -0
  4. package/adapters/ethers6.test.ts +169 -0
  5. package/adapters/ethers6.ts +36 -0
  6. package/adapters/hardhat-node.ts +167 -0
  7. package/adapters/hardhat.hh2.test.ts +159 -0
  8. package/adapters/hardhat.ts +37 -0
  9. package/adapters/index.test.ts +25 -0
  10. package/adapters/index.ts +5 -0
  11. package/adapters/smartWallet.ts +91 -0
  12. package/adapters/test-utils.ts +53 -0
  13. package/adapters/types.ts +6 -0
  14. package/adapters/wagmi.test.ts +156 -0
  15. package/adapters/wagmi.ts +17 -0
  16. package/chains/chains/arbSepolia.ts +14 -0
  17. package/chains/chains/baseSepolia.ts +14 -0
  18. package/chains/chains/hardhat.ts +15 -0
  19. package/chains/chains/sepolia.ts +14 -0
  20. package/chains/chains.test.ts +49 -0
  21. package/chains/defineChain.ts +18 -0
  22. package/chains/index.ts +33 -0
  23. package/chains/types.ts +32 -0
  24. package/core/baseBuilder.ts +138 -0
  25. package/core/client.test.ts +298 -0
  26. package/core/client.ts +308 -0
  27. package/core/config.test.ts +224 -0
  28. package/core/config.ts +213 -0
  29. package/core/decrypt/MockQueryDecrypterAbi.ts +129 -0
  30. package/core/decrypt/cofheMocksSealOutput.ts +57 -0
  31. package/core/decrypt/decryptHandleBuilder.ts +281 -0
  32. package/core/decrypt/decryptUtils.ts +28 -0
  33. package/core/decrypt/tnSealOutput.ts +59 -0
  34. package/core/encrypt/MockZkVerifierAbi.ts +106 -0
  35. package/core/encrypt/cofheMocksZkVerifySign.ts +278 -0
  36. package/core/encrypt/encryptInputsBuilder.test.ts +735 -0
  37. package/core/encrypt/encryptInputsBuilder.ts +512 -0
  38. package/core/encrypt/encryptUtils.ts +64 -0
  39. package/core/encrypt/zkPackProveVerify.ts +273 -0
  40. package/core/error.ts +170 -0
  41. package/core/fetchKeys.test.ts +212 -0
  42. package/core/fetchKeys.ts +170 -0
  43. package/core/index.ts +77 -0
  44. package/core/keyStore.test.ts +226 -0
  45. package/core/keyStore.ts +127 -0
  46. package/core/permits.test.ts +242 -0
  47. package/core/permits.ts +136 -0
  48. package/core/result.test.ts +180 -0
  49. package/core/result.ts +67 -0
  50. package/core/test-utils.ts +45 -0
  51. package/core/types.ts +352 -0
  52. package/core/utils.ts +88 -0
  53. package/dist/adapters.cjs +88 -0
  54. package/dist/adapters.d.cts +14558 -0
  55. package/dist/adapters.d.ts +14558 -0
  56. package/dist/adapters.js +83 -0
  57. package/dist/chains.cjs +101 -0
  58. package/dist/chains.d.cts +99 -0
  59. package/dist/chains.d.ts +99 -0
  60. package/dist/chains.js +1 -0
  61. package/dist/chunk-GZCQQYVI.js +93 -0
  62. package/dist/chunk-KFGPTJ6X.js +2295 -0
  63. package/dist/chunk-LU7BMUUT.js +804 -0
  64. package/dist/core.cjs +3174 -0
  65. package/dist/core.d.cts +16 -0
  66. package/dist/core.d.ts +16 -0
  67. package/dist/core.js +3 -0
  68. package/dist/node.cjs +3090 -0
  69. package/dist/node.d.cts +22 -0
  70. package/dist/node.d.ts +22 -0
  71. package/dist/node.js +90 -0
  72. package/dist/permit-S9CnI6MF.d.cts +333 -0
  73. package/dist/permit-S9CnI6MF.d.ts +333 -0
  74. package/dist/permits.cjs +856 -0
  75. package/dist/permits.d.cts +1056 -0
  76. package/dist/permits.d.ts +1056 -0
  77. package/dist/permits.js +1 -0
  78. package/dist/types-KImPrEIe.d.cts +48 -0
  79. package/dist/types-KImPrEIe.d.ts +48 -0
  80. package/dist/types-PhwGgQvs.d.ts +953 -0
  81. package/dist/types-bB7wLj0q.d.cts +953 -0
  82. package/dist/web.cjs +3067 -0
  83. package/dist/web.d.cts +22 -0
  84. package/dist/web.d.ts +22 -0
  85. package/dist/web.js +64 -0
  86. package/node/client.test.ts +152 -0
  87. package/node/config.test.ts +68 -0
  88. package/node/encryptInputs.test.ts +175 -0
  89. package/node/index.ts +96 -0
  90. package/node/storage.ts +51 -0
  91. package/package.json +15 -3
  92. package/permits/index.ts +67 -0
  93. package/permits/localstorage.test.ts +118 -0
  94. package/permits/permit.test.ts +474 -0
  95. package/permits/permit.ts +396 -0
  96. package/permits/sealing.test.ts +84 -0
  97. package/permits/sealing.ts +131 -0
  98. package/permits/signature.ts +79 -0
  99. package/permits/store.test.ts +128 -0
  100. package/permits/store.ts +168 -0
  101. package/permits/test-utils.ts +20 -0
  102. package/permits/types.ts +174 -0
  103. package/permits/utils.ts +63 -0
  104. package/permits/validation.test.ts +288 -0
  105. package/permits/validation.ts +349 -0
  106. package/web/client.web.test.ts +152 -0
  107. package/web/config.web.test.ts +71 -0
  108. package/web/encryptInputs.web.test.ts +195 -0
  109. package/web/index.ts +97 -0
  110. package/web/storage.ts +20 -0
@@ -0,0 +1,396 @@
1
+ import { keccak256, toHex, zeroAddress, parseAbi, type PublicClient, type WalletClient } from 'viem';
2
+ import {
3
+ type Permit,
4
+ type CreateSelfPermitOptions,
5
+ type CreateSharingPermitOptions,
6
+ type ImportSharedPermitOptions,
7
+ type SerializedPermit,
8
+ type EIP712Domain,
9
+ type Permission,
10
+ type EthEncryptedData,
11
+ } from './types.js';
12
+ import {
13
+ validateSelfPermitOptions,
14
+ validateSharingPermitOptions,
15
+ validateImportPermitOptions,
16
+ validateSelfPermit,
17
+ validateSharingPermit,
18
+ validateImportPermit,
19
+ ValidationUtils,
20
+ } from './validation.js';
21
+ import { SignatureUtils } from './signature.js';
22
+ import { GenerateSealingKey, SealingKey } from './sealing.js';
23
+
24
+ /**
25
+ * Main Permit utilities - functional approach for React compatibility
26
+ */
27
+ export const PermitUtils = {
28
+ /**
29
+ * Create a self permit for personal use
30
+ */
31
+ createSelf: async (options: CreateSelfPermitOptions): Promise<Permit> => {
32
+ const validation = validateSelfPermitOptions(options);
33
+
34
+ if (!validation.success) {
35
+ throw new Error(
36
+ 'PermitUtils :: createSelf :: Parsing SelfPermitOptions failed ' + JSON.stringify(validation.error, null, 2)
37
+ );
38
+ }
39
+
40
+ // Always generate a new sealing key - users cannot provide their own
41
+ const sealingPair = await GenerateSealingKey();
42
+
43
+ return {
44
+ ...validation.data,
45
+ sealingPair,
46
+ _signedDomain: undefined,
47
+ };
48
+ },
49
+
50
+ /**
51
+ * Create a sharing permit to be shared with another user
52
+ */
53
+ createSharing: async (options: CreateSharingPermitOptions): Promise<Permit> => {
54
+ const validation = validateSharingPermitOptions(options);
55
+
56
+ if (!validation.success) {
57
+ throw new Error(
58
+ 'PermitUtils :: createSharing :: Parsing SharingPermitOptions failed ' +
59
+ JSON.stringify(validation.error, null, 2)
60
+ );
61
+ }
62
+
63
+ // Always generate a new sealing key - users cannot provide their own
64
+ const sealingPair = await GenerateSealingKey();
65
+
66
+ return {
67
+ ...validation.data,
68
+ sealingPair,
69
+ _signedDomain: undefined,
70
+ };
71
+ },
72
+
73
+ /**
74
+ * Import a shared permit from various input formats
75
+ */
76
+ importShared: async (options: ImportSharedPermitOptions | any | string): Promise<Permit> => {
77
+ let parsedOptions: ImportSharedPermitOptions;
78
+
79
+ // Handle different input types
80
+ if (typeof options === 'string') {
81
+ // Parse JSON string
82
+ try {
83
+ parsedOptions = JSON.parse(options);
84
+ } catch (error) {
85
+ throw new Error(`PermitUtils :: importShared :: Failed to parse JSON string: ${error}`);
86
+ }
87
+ } else if (typeof options === 'object' && options !== null) {
88
+ // Handle both ImportSharedPermitOptions and any object
89
+ parsedOptions = options;
90
+ } else {
91
+ throw new Error(
92
+ 'PermitUtils :: importShared :: Invalid input type, expected ImportSharedPermitOptions, object, or string'
93
+ );
94
+ }
95
+
96
+ // Validate type if provided
97
+ if (parsedOptions.type != null && parsedOptions.type !== 'sharing') {
98
+ throw new Error(`PermitUtils :: importShared :: Invalid permit type <${parsedOptions.type}>, must be "sharing"`);
99
+ }
100
+
101
+ const validation = validateImportPermitOptions({ ...parsedOptions, type: 'recipient' });
102
+
103
+ if (!validation.success) {
104
+ throw new Error(
105
+ 'PermitUtils :: importShared :: Parsing ImportPermitOptions failed ' + JSON.stringify(validation.error, null, 2)
106
+ );
107
+ }
108
+
109
+ // Always generate a new sealing key - users cannot provide their own
110
+ const sealingPair = await GenerateSealingKey();
111
+
112
+ return {
113
+ ...validation.data,
114
+ sealingPair,
115
+ _signedDomain: undefined,
116
+ };
117
+ },
118
+
119
+ /**
120
+ * Sign a permit with the provided wallet client
121
+ */
122
+ sign: async (permit: Permit, publicClient: PublicClient, walletClient: WalletClient): Promise<Permit> => {
123
+ if (walletClient == null || walletClient.account == null) {
124
+ throw new Error(
125
+ 'PermitUtils :: sign - walletClient undefined, you must pass in a `walletClient` for the connected user to create a permit signature'
126
+ );
127
+ }
128
+
129
+ const primaryType = SignatureUtils.getPrimaryType(permit.type);
130
+ const domain = await PermitUtils.fetchEIP712Domain(publicClient);
131
+ const { types, message } = SignatureUtils.getSignatureParams(PermitUtils.getPermission(permit, true), primaryType);
132
+
133
+ const signature = await walletClient.signTypedData({
134
+ domain,
135
+ types,
136
+ primaryType,
137
+ message,
138
+ account: walletClient.account,
139
+ });
140
+
141
+ let updatedPermit: Permit;
142
+ if (permit.type === 'self' || permit.type === 'sharing') {
143
+ updatedPermit = {
144
+ ...permit,
145
+ issuerSignature: signature,
146
+ _signedDomain: domain,
147
+ };
148
+ } else {
149
+ updatedPermit = {
150
+ ...permit,
151
+ recipientSignature: signature,
152
+ _signedDomain: domain,
153
+ };
154
+ }
155
+
156
+ return updatedPermit;
157
+ },
158
+
159
+ /**
160
+ * Create and sign a self permit in one operation
161
+ */
162
+ createSelfAndSign: async (
163
+ options: CreateSelfPermitOptions,
164
+ publicClient: PublicClient,
165
+ walletClient: WalletClient
166
+ ): Promise<Permit> => {
167
+ const permit = await PermitUtils.createSelf(options);
168
+ return PermitUtils.sign(permit, publicClient, walletClient);
169
+ },
170
+
171
+ /**
172
+ * Create and sign a sharing permit in one operation
173
+ */
174
+ createSharingAndSign: async (
175
+ options: CreateSharingPermitOptions,
176
+ publicClient: PublicClient,
177
+ walletClient: WalletClient
178
+ ): Promise<Permit> => {
179
+ const permit = await PermitUtils.createSharing(options);
180
+ return PermitUtils.sign(permit, publicClient, walletClient);
181
+ },
182
+
183
+ /**
184
+ * Import and sign a shared permit in one operation from various input formats
185
+ */
186
+ importSharedAndSign: async (
187
+ options: ImportSharedPermitOptions | any | string,
188
+ publicClient: PublicClient,
189
+ walletClient: WalletClient
190
+ ): Promise<Permit> => {
191
+ const permit = await PermitUtils.importShared(options);
192
+ return PermitUtils.sign(permit, publicClient, walletClient);
193
+ },
194
+
195
+ /**
196
+ * Deserialize a permit from serialized data
197
+ */
198
+ deserialize: (data: SerializedPermit): Permit => {
199
+ return {
200
+ ...data,
201
+ sealingPair: SealingKey.deserialize(data.sealingPair.privateKey, data.sealingPair.publicKey),
202
+ };
203
+ },
204
+
205
+ /**
206
+ * Serialize a permit for storage
207
+ */
208
+ serialize: (permit: Permit): SerializedPermit => {
209
+ return {
210
+ name: permit.name,
211
+ type: permit.type,
212
+ issuer: permit.issuer,
213
+ expiration: permit.expiration,
214
+ recipient: permit.recipient,
215
+ validatorId: permit.validatorId,
216
+ validatorContract: permit.validatorContract,
217
+ issuerSignature: permit.issuerSignature,
218
+ recipientSignature: permit.recipientSignature,
219
+ _signedDomain: permit._signedDomain,
220
+ sealingPair: permit.sealingPair.serialize(),
221
+ };
222
+ },
223
+
224
+ /**
225
+ * Validate a permit
226
+ */
227
+ validate: (permit: Permit) => {
228
+ if (permit.type === 'self') {
229
+ return validateSelfPermit(permit);
230
+ } else if (permit.type === 'sharing') {
231
+ return validateSharingPermit(permit);
232
+ } else if (permit.type === 'recipient') {
233
+ return validateImportPermit(permit);
234
+ } else {
235
+ throw new Error('PermitUtils :: validate :: Invalid permit type');
236
+ }
237
+ },
238
+
239
+ /**
240
+ * Get the permission object from a permit (for use in contracts)
241
+ */
242
+ getPermission: (permit: Permit, skipValidation = false): Permission => {
243
+ if (!skipValidation) {
244
+ const validationResult = PermitUtils.validate(permit);
245
+
246
+ if (!validationResult.success) {
247
+ throw new Error(
248
+ `PermitUtils :: getPermission :: permit validation failed - ${JSON.stringify(validationResult.error, null, 2)} ${JSON.stringify(permit, null, 2)}`
249
+ );
250
+ }
251
+ }
252
+
253
+ return {
254
+ issuer: permit.issuer,
255
+ expiration: permit.expiration,
256
+ recipient: permit.recipient,
257
+ validatorId: permit.validatorId,
258
+ validatorContract: permit.validatorContract,
259
+ sealingKey: `0x${permit.sealingPair.publicKey}`,
260
+ issuerSignature: permit.issuerSignature,
261
+ recipientSignature: permit.recipientSignature,
262
+ };
263
+ },
264
+
265
+ /**
266
+ * Get a stable hash for the permit (used as key in storage)
267
+ */
268
+ getHash: (permit: Permit): string => {
269
+ const data = JSON.stringify({
270
+ type: permit.type,
271
+ issuer: permit.issuer,
272
+ expiration: permit.expiration,
273
+ recipient: permit.recipient,
274
+ validatorId: permit.validatorId,
275
+ validatorContract: permit.validatorContract,
276
+ });
277
+ return keccak256(toHex(data));
278
+ },
279
+
280
+ /**
281
+ * Export permit data for sharing (removes sensitive fields)
282
+ */
283
+ export: (permit: Permit): string => {
284
+ const cleanedPermit: Record<string, unknown> = {
285
+ name: permit.name,
286
+ type: permit.type,
287
+ issuer: permit.issuer,
288
+ expiration: permit.expiration,
289
+ };
290
+
291
+ if (permit.recipient !== zeroAddress) cleanedPermit.recipient = permit.recipient;
292
+ if (permit.validatorId !== 0) cleanedPermit.validatorId = permit.validatorId;
293
+ if (permit.validatorContract !== zeroAddress) cleanedPermit.validatorContract = permit.validatorContract;
294
+ if (permit.type === 'sharing' && permit.issuerSignature !== '0x')
295
+ cleanedPermit.issuerSignature = permit.issuerSignature;
296
+
297
+ return JSON.stringify(cleanedPermit, undefined, 2);
298
+ },
299
+
300
+ /**
301
+ * Unseal encrypted data using the permit's sealing key
302
+ */
303
+ unseal: (permit: Permit, ciphertext: EthEncryptedData): bigint => {
304
+ return permit.sealingPair.unseal(ciphertext);
305
+ },
306
+
307
+ /**
308
+ * Check if permit is expired
309
+ */
310
+ isExpired: (permit: Permit): boolean => {
311
+ return ValidationUtils.isExpired(permit);
312
+ },
313
+
314
+ /**
315
+ * Check if permit is signed
316
+ */
317
+ isSigned: (permit: Permit): boolean => {
318
+ return ValidationUtils.isSigned(permit);
319
+ },
320
+
321
+ /**
322
+ * Check if permit is valid
323
+ */
324
+ isValid: (permit: Permit) => {
325
+ return ValidationUtils.isValid(permit);
326
+ },
327
+
328
+ /**
329
+ * Update permit name (returns new permit instance)
330
+ */
331
+ updateName: (permit: Permit, name: string): Permit => {
332
+ return { ...permit, name };
333
+ },
334
+
335
+ /**
336
+ * Fetch EIP712 domain from the blockchain
337
+ */
338
+ fetchEIP712Domain: async (publicClient: PublicClient): Promise<EIP712Domain> => {
339
+ // Hardcoded constants from the original implementation
340
+ const TASK_MANAGER_ADDRESS = '0xeA30c4B8b44078Bbf8a6ef5b9f1eC1626C7848D9';
341
+ const ACL_IFACE = 'function acl() view returns (address)';
342
+ const EIP712_DOMAIN_IFACE =
343
+ 'function eip712Domain() public view returns (bytes1 fields, string name, string version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] extensions)';
344
+
345
+ // Parse the ABI for the ACL function
346
+ const aclAbi = parseAbi([ACL_IFACE]);
347
+
348
+ // Get the ACL address
349
+ const aclAddress = (await publicClient.readContract({
350
+ address: TASK_MANAGER_ADDRESS as `0x${string}`,
351
+ abi: aclAbi,
352
+ functionName: 'acl',
353
+ })) as `0x${string}`;
354
+
355
+ // Parse the ABI for the EIP712 domain function
356
+ const domainAbi = parseAbi([EIP712_DOMAIN_IFACE]);
357
+
358
+ // Get the EIP712 domain
359
+ const domain = await publicClient.readContract({
360
+ address: aclAddress,
361
+ abi: domainAbi,
362
+ functionName: 'eip712Domain',
363
+ });
364
+
365
+ // eslint-disable-next-line no-unused-vars
366
+ const [_fields, name, version, chainId, verifyingContract, _salt, _extensions] = domain;
367
+
368
+ return {
369
+ name,
370
+ version,
371
+ chainId: Number(chainId),
372
+ verifyingContract,
373
+ };
374
+ },
375
+
376
+ /**
377
+ * Check if permit's signed domain matches the provided domain
378
+ */
379
+ matchesDomain: (permit: Permit, domain: EIP712Domain): boolean => {
380
+ return (
381
+ permit._signedDomain?.name === domain.name &&
382
+ permit._signedDomain?.version === domain.version &&
383
+ permit._signedDomain?.verifyingContract === domain.verifyingContract &&
384
+ permit._signedDomain?.chainId === domain.chainId
385
+ );
386
+ },
387
+
388
+ /**
389
+ * Check if permit's signed domain is valid for the current chain
390
+ */
391
+ checkSignedDomainValid: async (permit: Permit, publicClient: PublicClient): Promise<boolean> => {
392
+ if (permit._signedDomain == null) return false;
393
+ const domain = await PermitUtils.fetchEIP712Domain(publicClient);
394
+ return PermitUtils.matchesDomain(permit, domain);
395
+ },
396
+ };
@@ -0,0 +1,84 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { SealingKey, GenerateSealingKey } from './index.js';
3
+
4
+ describe('SealingKey', () => {
5
+ it('should create a SealingKey with valid keys', () => {
6
+ const privateKey = 'a'.repeat(64);
7
+ const publicKey = 'b'.repeat(64);
8
+
9
+ const sealingKey = new SealingKey(privateKey, publicKey);
10
+
11
+ expect(sealingKey.privateKey).toBe(privateKey);
12
+ expect(sealingKey.publicKey).toBe(publicKey);
13
+ });
14
+
15
+ it('should throw error for invalid private key length', () => {
16
+ const privateKey = 'a'.repeat(32); // Too short
17
+ const publicKey = 'b'.repeat(64);
18
+
19
+ expect(() => {
20
+ new SealingKey(privateKey, publicKey);
21
+ }).toThrow('Private key must be of length 64');
22
+ });
23
+
24
+ it('should throw error for invalid public key length', () => {
25
+ const privateKey = 'a'.repeat(64);
26
+ const publicKey = 'b'.repeat(32); // Too short
27
+
28
+ expect(() => {
29
+ new SealingKey(privateKey, publicKey);
30
+ }).toThrow('Public key must be of length 64');
31
+ });
32
+
33
+ it('should seal and unseal data correctly', () => {
34
+ const publicKey = 'b'.repeat(64);
35
+ const value = BigInt(12345);
36
+
37
+ // Seal the data
38
+ const encryptedData = SealingKey.seal(value, publicKey);
39
+
40
+ expect(encryptedData).toHaveProperty('data');
41
+ expect(encryptedData).toHaveProperty('public_key');
42
+ expect(encryptedData).toHaveProperty('nonce');
43
+ expect(encryptedData.data).toBeInstanceOf(Uint8Array);
44
+ expect(encryptedData.public_key).toBeInstanceOf(Uint8Array);
45
+ expect(encryptedData.nonce).toBeInstanceOf(Uint8Array);
46
+ });
47
+
48
+ it('should throw error for invalid public key in seal', () => {
49
+ const value = BigInt(12345);
50
+ const invalidPublicKey = 'invalid';
51
+
52
+ expect(() => {
53
+ SealingKey.seal(value, invalidPublicKey);
54
+ }).toThrow('bad public key size');
55
+ });
56
+
57
+ it('should throw error for invalid value in seal', () => {
58
+ const publicKey = 'b'.repeat(64);
59
+ const invalidValue = 'not a number';
60
+
61
+ expect(() => {
62
+ // @ts-expect-error - invalid value
63
+ SealingKey.seal(invalidValue, publicKey);
64
+ }).toThrow('Value not a number is not a number or bigint: string');
65
+ });
66
+ });
67
+
68
+ describe('GenerateSealingKey', () => {
69
+ it('should generate a valid SealingKey', async () => {
70
+ const sealingKey = await GenerateSealingKey();
71
+
72
+ expect(sealingKey).toBeInstanceOf(SealingKey);
73
+ expect(sealingKey.privateKey).toHaveLength(64);
74
+ expect(sealingKey.publicKey).toHaveLength(64);
75
+ });
76
+
77
+ it('should generate different keys on each call', async () => {
78
+ const key1 = await GenerateSealingKey();
79
+ const key2 = await GenerateSealingKey();
80
+
81
+ expect(key1.privateKey).not.toBe(key2.privateKey);
82
+ expect(key1.publicKey).not.toBe(key2.publicKey);
83
+ });
84
+ });
@@ -0,0 +1,131 @@
1
+ import * as nacl from 'tweetnacl';
2
+ import { fromHexString, toBeArray, toBigInt, toHexString, isBigIntOrNumber, isString } from './utils.js';
3
+
4
+ const PRIVATE_KEY_LENGTH = 64;
5
+ const PUBLIC_KEY_LENGTH = 64;
6
+
7
+ export type EthEncryptedData = {
8
+ data: Uint8Array;
9
+ public_key: Uint8Array;
10
+ nonce: Uint8Array;
11
+ };
12
+
13
+ /**
14
+ * A class representing a SealingKey which provides cryptographic sealing (encryption)
15
+ * and unsealing (decryption) capabilities.
16
+ */
17
+ export class SealingKey {
18
+ /**
19
+ * The private key used for decryption.
20
+ */
21
+ privateKey: string;
22
+ /**
23
+ * The public key used for encryption.
24
+ */
25
+ publicKey: string;
26
+
27
+ /**
28
+ * Constructs a SealingKey instance with the given private and public keys.
29
+ *
30
+ * @param {string} privateKey - The private key used for decryption.
31
+ * @param {string} publicKey - The public key used for encryption.
32
+ * @throws Will throw an error if the provided keys lengths do not match
33
+ * the required lengths for private and public keys.
34
+ */
35
+ constructor(privateKey: string, publicKey: string) {
36
+ if (privateKey.length !== PRIVATE_KEY_LENGTH) {
37
+ throw new Error(`Private key must be of length ${PRIVATE_KEY_LENGTH}`);
38
+ }
39
+
40
+ if (publicKey.length !== PUBLIC_KEY_LENGTH) {
41
+ throw new Error(`Public key must be of length ${PUBLIC_KEY_LENGTH}`);
42
+ }
43
+
44
+ this.privateKey = privateKey;
45
+ this.publicKey = publicKey;
46
+ }
47
+
48
+ unseal = (parsedData: EthEncryptedData): bigint => {
49
+ // Ensure all parameters are Uint8Array
50
+ const nonce = parsedData.nonce instanceof Uint8Array ? parsedData.nonce : new Uint8Array(parsedData.nonce);
51
+
52
+ const ephemPublicKey =
53
+ parsedData.public_key instanceof Uint8Array ? parsedData.public_key : new Uint8Array(parsedData.public_key);
54
+
55
+ const dataToDecrypt = parsedData.data instanceof Uint8Array ? parsedData.data : new Uint8Array(parsedData.data);
56
+
57
+ // Make sure the private key is also a Uint8Array
58
+ const privateKeyBytes = fromHexString(this.privateKey);
59
+
60
+ // Debug information
61
+ // console.log("nonce length:", nonce.length);
62
+ // console.log("ephemPublicKey length:", ephemPublicKey.length);
63
+ // console.log("privateKeyBytes length:", privateKeyBytes.length);
64
+ // console.log("dataToDecrypt length:", dataToDecrypt.length);
65
+
66
+ // call the nacl box function to decrypt the data
67
+ const decryptedMessage = nacl.box.open(dataToDecrypt, nonce, ephemPublicKey, privateKeyBytes);
68
+
69
+ if (!decryptedMessage) {
70
+ throw new Error('Failed to decrypt message');
71
+ }
72
+
73
+ return toBigInt(decryptedMessage);
74
+ };
75
+
76
+ /**
77
+ * Serializes the SealingKey to a JSON object.
78
+ */
79
+ serialize = () => {
80
+ return {
81
+ privateKey: this.privateKey,
82
+ publicKey: this.publicKey,
83
+ };
84
+ };
85
+
86
+ /**
87
+ * Deserializes the SealingKey from a JSON object.
88
+ */
89
+ static deserialize = (privateKey: string, publicKey: string): SealingKey => {
90
+ return new SealingKey(privateKey, publicKey);
91
+ };
92
+
93
+ /**
94
+ * Seals (encrypts) the provided message for a receiver with the specified public key.
95
+ *
96
+ * @param {bigint | number} value - The message to be encrypted.
97
+ * @param {string} publicKey - The public key of the intended recipient.
98
+ * @returns string - The encrypted message in hexadecimal format.
99
+ * @static
100
+ * @throws Will throw if the provided publicKey or value do not meet defined preconditions.
101
+ */
102
+ static seal = (value: bigint | number, publicKey: string): EthEncryptedData => {
103
+ isString(publicKey);
104
+ isBigIntOrNumber(value);
105
+
106
+ // generate ephemeral keypair
107
+ const ephemeralKeyPair = nacl.box.keyPair();
108
+
109
+ const nonce = nacl.randomBytes(nacl.box.nonceLength);
110
+
111
+ const encryptedMessage = nacl.box(toBeArray(value), nonce, fromHexString(publicKey), ephemeralKeyPair.secretKey);
112
+
113
+ return {
114
+ data: encryptedMessage,
115
+ public_key: ephemeralKeyPair.publicKey,
116
+ nonce: nonce,
117
+ };
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Asynchronously generates a new SealingKey.
123
+ * This function uses the 'nacl' library to create a new public/private key pair for sealing purposes.
124
+ * A sealing key is used to encrypt data such that it can only be unsealed (decrypted) by the owner of the corresponding private key.
125
+ * @returns {Promise<SealingKey>} - A promise that resolves to a new SealingKey object containing the hexadecimal strings of the public and private keys.
126
+ */
127
+ export const GenerateSealingKey = async (): Promise<SealingKey> => {
128
+ const sodiumKeypair = nacl.box.keyPair();
129
+
130
+ return new SealingKey(toHexString(sodiumKeypair.secretKey), toHexString(sodiumKeypair.publicKey));
131
+ };
@@ -0,0 +1,79 @@
1
+ import { type EIP712Message, type EIP712Types, type Permission, type PermitSignaturePrimaryType } from './types.js';
2
+
3
+ const PermitSignatureAllFields = [
4
+ { name: 'issuer', type: 'address' },
5
+ { name: 'expiration', type: 'uint64' },
6
+ { name: 'recipient', type: 'address' },
7
+ { name: 'validatorId', type: 'uint256' },
8
+ { name: 'validatorContract', type: 'address' },
9
+ { name: 'sealingKey', type: 'bytes32' },
10
+ { name: 'issuerSignature', type: 'bytes' },
11
+ ] as const;
12
+
13
+ type PermitSignatureFieldOption = (typeof PermitSignatureAllFields)[number]['name'];
14
+
15
+ export const SignatureTypes = {
16
+ PermissionedV2IssuerSelf: [
17
+ 'issuer',
18
+ 'expiration',
19
+ 'recipient',
20
+ 'validatorId',
21
+ 'validatorContract',
22
+ 'sealingKey',
23
+ ] satisfies PermitSignatureFieldOption[],
24
+ PermissionedV2IssuerShared: [
25
+ 'issuer',
26
+ 'expiration',
27
+ 'recipient',
28
+ 'validatorId',
29
+ 'validatorContract',
30
+ ] satisfies PermitSignatureFieldOption[],
31
+ PermissionedV2Recipient: ['sealingKey', 'issuerSignature'] satisfies PermitSignatureFieldOption[],
32
+ } as const;
33
+
34
+ /**
35
+ * Get signature types and message for EIP712 signing
36
+ */
37
+ export const getSignatureTypesAndMessage = <T extends PermitSignatureFieldOption>(
38
+ primaryType: PermitSignaturePrimaryType,
39
+ fields: T[] | readonly T[],
40
+ values: Pick<Permission, T> & Partial<Permission>
41
+ ): { types: EIP712Types; primaryType: string; message: EIP712Message } => {
42
+ const types = {
43
+ [primaryType]: PermitSignatureAllFields.filter((fieldType) => fields.includes(fieldType.name as T)),
44
+ };
45
+
46
+ const message: Record<T, string | string[] | number | number[]> = {} as Record<
47
+ T,
48
+ string | string[] | number | number[]
49
+ >;
50
+ fields.forEach((field) => {
51
+ if (field in values) {
52
+ message[field] = values[field];
53
+ }
54
+ });
55
+
56
+ return { types, primaryType, message: message as EIP712Message };
57
+ };
58
+
59
+ /**
60
+ * Signature utilities for permit operations
61
+ */
62
+ export const SignatureUtils = {
63
+ /**
64
+ * Get signature parameters for a permit
65
+ */
66
+ getSignatureParams: (permit: Permission, primaryType: PermitSignaturePrimaryType) => {
67
+ return getSignatureTypesAndMessage(primaryType, SignatureTypes[primaryType], permit);
68
+ },
69
+
70
+ /**
71
+ * Determine the required signature type based on permit type
72
+ */
73
+ getPrimaryType: (permitType: 'self' | 'sharing' | 'recipient'): PermitSignaturePrimaryType => {
74
+ if (permitType === 'self') return 'PermissionedV2IssuerSelf';
75
+ if (permitType === 'sharing') return 'PermissionedV2IssuerShared';
76
+ if (permitType === 'recipient') return 'PermissionedV2Recipient';
77
+ throw new Error(`Unknown permit type: ${permitType}`);
78
+ },
79
+ };