@cofhe/sdk 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/acps/acp.ts +411 -0
  3. package/acps/index.ts +70 -0
  4. package/{permits → acps}/onchain-utils.ts +49 -24
  5. package/acps/sealing.ts +90 -0
  6. package/acps/signature.ts +89 -0
  7. package/acps/store.ts +172 -0
  8. package/acps/test/acp.test.ts +615 -0
  9. package/acps/test/localstorage.test.ts +105 -0
  10. package/acps/test/sealing.test.ts +77 -0
  11. package/acps/test/store.test.ts +88 -0
  12. package/acps/test/validation.test.ts +361 -0
  13. package/acps/test-utils.ts +32 -0
  14. package/acps/types.ts +252 -0
  15. package/acps/validation.ts +392 -0
  16. package/adapters/test/ethers5.test.ts +4 -1
  17. package/adapters/test/ethers6.test.ts +4 -1
  18. package/adapters/test/wagmi.test.ts +5 -2
  19. package/chains/chains/stagingCofhe.ts +21 -0
  20. package/chains/index.ts +3 -1
  21. package/chains/test/chains.test.ts +2 -1
  22. package/core/acps.ts +625 -0
  23. package/core/client.ts +136 -39
  24. package/core/clientTypes.ts +52 -41
  25. package/core/config.ts +66 -5
  26. package/core/debug.ts +72 -0
  27. package/core/decrypt/MockThresholdNetworkAbi.ts +20 -11
  28. package/core/decrypt/apiError.ts +104 -0
  29. package/core/decrypt/cofheMocksDecryptForTx.ts +11 -11
  30. package/core/decrypt/cofheMocksDecryptForView.ts +7 -7
  31. package/core/decrypt/decryptForTxBuilder.ts +102 -102
  32. package/core/decrypt/decryptForViewBuilder.ts +90 -90
  33. package/core/decrypt/submitRetry.ts +38 -30
  34. package/core/decrypt/tnDecryptV1.ts +5 -5
  35. package/core/decrypt/tnDecryptV2.ts +45 -34
  36. package/core/decrypt/tnSealOutputV1.ts +4 -3
  37. package/core/decrypt/tnSealOutputV2.ts +44 -31
  38. package/core/encrypt/cofheMocksZkVerifySign.ts +59 -74
  39. package/core/encrypt/encryptInputsBuilder.ts +86 -52
  40. package/core/encrypt/zkPackProveVerify.ts +25 -18
  41. package/core/error.ts +34 -6
  42. package/core/index.ts +14 -14
  43. package/core/test/acpDefaults.test.ts +52 -0
  44. package/core/test/acps.test.ts +596 -0
  45. package/core/test/apiError.test.ts +130 -0
  46. package/core/test/client.test.ts +22 -19
  47. package/core/test/config.test.ts +25 -5
  48. package/core/test/decrypt.test.ts +40 -35
  49. package/core/test/decryptBuilders.test.ts +68 -68
  50. package/core/test/decryptErrorCodes.test.ts +217 -0
  51. package/core/test/encryptInputsBuilder.test.ts +72 -41
  52. package/core/test/pollCallbacks.test.ts +89 -18
  53. package/core/test/stagingRedirect.ts +18 -0
  54. package/core/test/submitRetry.test.ts +182 -0
  55. package/core/types.ts +9 -69
  56. package/dist/acp-Wi6isVQI.d.cts +407 -0
  57. package/dist/acp-Wi6isVQI.d.ts +407 -0
  58. package/dist/acps.cjs +1081 -0
  59. package/dist/acps.d.cts +480 -0
  60. package/dist/acps.d.ts +480 -0
  61. package/dist/acps.js +2 -0
  62. package/dist/chains.cjs +14 -1
  63. package/dist/chains.d.cts +30 -1
  64. package/dist/chains.d.ts +30 -1
  65. package/dist/chains.js +1 -1
  66. package/dist/{chunk-PE5V5CCV.js → chunk-43USWPEH.js} +1000 -604
  67. package/dist/{chunk-MTRAXQXC.js → chunk-N6IDQRRU.js} +14 -2
  68. package/dist/chunk-Q7CBWGQX.js +1029 -0
  69. package/dist/{clientTypes-CyUvRRzA.d.ts → clientTypes-BN3nbzYM.d.ts} +342 -165
  70. package/dist/{clientTypes-BDy1qIBu.d.cts → clientTypes-CYZjFznO.d.cts} +342 -165
  71. package/dist/core.cjs +1431 -1026
  72. package/dist/core.d.cts +55 -10
  73. package/dist/core.d.ts +55 -10
  74. package/dist/core.js +3 -3
  75. package/dist/node.cjs +1356 -976
  76. package/dist/node.d.cts +2 -2
  77. package/dist/node.d.ts +2 -2
  78. package/dist/node.js +3 -3
  79. package/dist/web.cjs +1356 -976
  80. package/dist/web.d.cts +2 -2
  81. package/dist/web.d.ts +2 -2
  82. package/dist/web.js +3 -3
  83. package/node/test/inherited.test.ts +75 -65
  84. package/node/test/tfheinit.test.ts +23 -8
  85. package/package.json +6 -6
  86. package/web/test/client.web.test.ts +5 -1
  87. package/web/test/inherited.web.test.ts +75 -65
  88. package/web/test/tfheinit.web.test.ts +14 -5
  89. package/web/test/worker.config.web.test.ts +38 -23
  90. package/web/test/worker.output.web.test.ts +25 -24
  91. package/core/encrypt/encryptUtils.ts +0 -67
  92. package/core/permits.ts +0 -206
  93. package/core/test/permits.test.ts +0 -534
  94. package/dist/chunk-VB62WYPL.js +0 -978
  95. package/dist/permit-DnVMDT5h.d.cts +0 -376
  96. package/dist/permit-DnVMDT5h.d.ts +0 -376
  97. package/dist/permits.cjs +0 -1026
  98. package/dist/permits.d.cts +0 -353
  99. package/dist/permits.d.ts +0 -353
  100. package/dist/permits.js +0 -2
  101. package/permits/index.ts +0 -68
  102. package/permits/permit.ts +0 -385
  103. package/permits/sealing.ts +0 -131
  104. package/permits/signature.ts +0 -79
  105. package/permits/store.ts +0 -157
  106. package/permits/test/localstorage.test.ts +0 -113
  107. package/permits/test/permit.test.ts +0 -557
  108. package/permits/test/sealing.test.ts +0 -84
  109. package/permits/test/store.test.ts +0 -88
  110. package/permits/test/validation.test.ts +0 -361
  111. package/permits/test-utils.ts +0 -28
  112. package/permits/types.ts +0 -204
  113. package/permits/validation.ts +0 -327
  114. /package/{permits → acps}/utils.ts +0 -0
@@ -1,978 +0,0 @@
1
- import { TASK_MANAGER_ADDRESS } from './chunk-ESMZCFJY.js';
2
- import { isAddress, getAddress, zeroAddress, isHex, keccak256, toHex, BaseError, ContractFunctionRevertedError, decodeErrorResult, parseAbi } from 'viem';
3
- import nacl from 'tweetnacl';
4
- import { z } from 'zod';
5
- import { createStore } from 'zustand/vanilla';
6
- import { persist } from 'zustand/middleware';
7
- import { produce } from 'immer';
8
-
9
- // permits/utils.ts
10
- var fromHexString = (hexString) => {
11
- const cleanString = hexString.length % 2 === 1 ? `0${hexString}` : hexString;
12
- const arr = cleanString.replace(/^0x/, "").match(/.{1,2}/g);
13
- if (!arr)
14
- return new Uint8Array();
15
- return new Uint8Array(arr.map((byte) => parseInt(byte, 16)));
16
- };
17
- var toHexString = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
18
- function toBigInt(value) {
19
- if (typeof value === "string") {
20
- return BigInt(value);
21
- } else if (typeof value === "number") {
22
- return BigInt(value);
23
- } else if (typeof value === "object") {
24
- return BigInt("0x" + toHexString(value));
25
- } else {
26
- return value;
27
- }
28
- }
29
- function toBeArray(value) {
30
- const bigIntValue = typeof value === "number" ? BigInt(value) : value;
31
- const hex = bigIntValue.toString(16);
32
- const paddedHex = hex.length % 2 === 0 ? hex : "0" + hex;
33
- return fromHexString(paddedHex);
34
- }
35
- function isString(value) {
36
- if (typeof value !== "string") {
37
- throw new Error(`Expected value which is \`string\`, received value of type \`${typeof value}\`.`);
38
- }
39
- }
40
- function isNumber(value) {
41
- const is = typeof value === "number" && !Number.isNaN(value);
42
- if (!is) {
43
- throw new Error(`Expected value which is \`number\`, received value of type \`${typeof value}\`.`);
44
- }
45
- }
46
- function isBigIntOrNumber(value) {
47
- const is = typeof value === "bigint";
48
- if (!is) {
49
- try {
50
- isNumber(value);
51
- } catch (e) {
52
- throw new Error(`Value ${value} is not a number or bigint: ${typeof value}`);
53
- }
54
- }
55
- }
56
-
57
- // permits/sealing.ts
58
- var PRIVATE_KEY_LENGTH = 64;
59
- var PUBLIC_KEY_LENGTH = 64;
60
- var SealingKey = class _SealingKey {
61
- /**
62
- * The private key used for decryption.
63
- */
64
- privateKey;
65
- /**
66
- * The public key used for encryption.
67
- */
68
- publicKey;
69
- /**
70
- * Constructs a SealingKey instance with the given private and public keys.
71
- *
72
- * @param {string} privateKey - The private key used for decryption.
73
- * @param {string} publicKey - The public key used for encryption.
74
- * @throws Will throw an error if the provided keys lengths do not match
75
- * the required lengths for private and public keys.
76
- */
77
- constructor(privateKey, publicKey) {
78
- if (privateKey.length !== PRIVATE_KEY_LENGTH) {
79
- throw new Error(`Private key must be of length ${PRIVATE_KEY_LENGTH}`);
80
- }
81
- if (publicKey.length !== PUBLIC_KEY_LENGTH) {
82
- throw new Error(`Public key must be of length ${PUBLIC_KEY_LENGTH}`);
83
- }
84
- this.privateKey = privateKey;
85
- this.publicKey = publicKey;
86
- }
87
- unseal = (parsedData) => {
88
- const nonce = parsedData.nonce instanceof Uint8Array ? parsedData.nonce : new Uint8Array(parsedData.nonce);
89
- const ephemPublicKey = parsedData.public_key instanceof Uint8Array ? parsedData.public_key : new Uint8Array(parsedData.public_key);
90
- const dataToDecrypt = parsedData.data instanceof Uint8Array ? parsedData.data : new Uint8Array(parsedData.data);
91
- const privateKeyBytes = fromHexString(this.privateKey);
92
- const decryptedMessage = nacl.box.open(dataToDecrypt, nonce, ephemPublicKey, privateKeyBytes);
93
- if (!decryptedMessage) {
94
- throw new Error("Failed to decrypt message");
95
- }
96
- return toBigInt(decryptedMessage);
97
- };
98
- /**
99
- * Serializes the SealingKey to a JSON object.
100
- */
101
- serialize = () => {
102
- return {
103
- privateKey: this.privateKey,
104
- publicKey: this.publicKey
105
- };
106
- };
107
- /**
108
- * Deserializes the SealingKey from a JSON object.
109
- */
110
- static deserialize = (privateKey, publicKey) => {
111
- return new _SealingKey(privateKey, publicKey);
112
- };
113
- /**
114
- * Seals (encrypts) the provided message for a receiver with the specified public key.
115
- *
116
- * @param {bigint | number} value - The message to be encrypted.
117
- * @param {string} publicKey - The public key of the intended recipient.
118
- * @returns string - The encrypted message in hexadecimal format.
119
- * @static
120
- * @throws Will throw if the provided publicKey or value do not meet defined preconditions.
121
- */
122
- static seal = (value, publicKey) => {
123
- isString(publicKey);
124
- isBigIntOrNumber(value);
125
- const ephemeralKeyPair = nacl.box.keyPair();
126
- const nonce = nacl.randomBytes(nacl.box.nonceLength);
127
- const encryptedMessage = nacl.box(toBeArray(value), nonce, fromHexString(publicKey), ephemeralKeyPair.secretKey);
128
- return {
129
- data: encryptedMessage,
130
- public_key: ephemeralKeyPair.publicKey,
131
- nonce
132
- };
133
- };
134
- };
135
- var GenerateSealingKey = () => {
136
- const sodiumKeypair = nacl.box.keyPair();
137
- return new SealingKey(toHexString(sodiumKeypair.secretKey), toHexString(sodiumKeypair.publicKey));
138
- };
139
- var SerializedSealingPair = z.object({
140
- privateKey: z.string(),
141
- publicKey: z.string()
142
- });
143
- var addressSchema = z.string().refine((val) => isAddress(val), {
144
- error: "Invalid address"
145
- }).transform((val) => getAddress(val));
146
- var addressNotZeroSchema = addressSchema.refine((val) => val !== zeroAddress, {
147
- error: "Must not be zeroAddress"
148
- });
149
- var bytesSchema = z.custom(
150
- (val) => {
151
- return typeof val === "string" && isHex(val);
152
- },
153
- {
154
- message: "Invalid hex value"
155
- }
156
- );
157
- var bytesNotEmptySchema = bytesSchema.refine((val) => val !== "0x", {
158
- error: "Must not be empty"
159
- });
160
- var DEFAULT_EXPIRATION_FN = () => Math.round(Date.now() / 1e3) + 7 * 24 * 60 * 60;
161
- var zPermitWithDefaults = z.object({
162
- name: z.string().optional().default("Unnamed Permit"),
163
- type: z.enum(["self", "sharing", "recipient"]),
164
- issuer: addressNotZeroSchema,
165
- expiration: z.int().optional().default(DEFAULT_EXPIRATION_FN),
166
- recipient: addressSchema.optional().default(zeroAddress),
167
- validatorId: z.int().optional().default(0),
168
- validatorContract: addressSchema.optional().default(zeroAddress),
169
- issuerSignature: bytesSchema.optional().default("0x"),
170
- recipientSignature: bytesSchema.optional().default("0x")
171
- });
172
- var zPermitWithSealingPair = zPermitWithDefaults.extend({
173
- sealingPair: SerializedSealingPair.optional()
174
- });
175
- var ExternalValidatorRefinement = [
176
- (data) => data.validatorId !== 0 && data.validatorContract !== zeroAddress || data.validatorId === 0 && data.validatorContract === zeroAddress,
177
- {
178
- error: "Permit external validator :: validatorId and validatorContract must either both be set or both be unset.",
179
- path: ["validatorId", "validatorContract"]
180
- }
181
- ];
182
- var RecipientRefinement = [
183
- (data) => data.issuer !== data.recipient,
184
- {
185
- error: "Sharing permit :: issuer and recipient must not be the same",
186
- path: ["issuer", "recipient"]
187
- }
188
- ];
189
- var SelfPermitOptionsValidator = z.object({
190
- type: z.literal("self").optional().default("self"),
191
- issuer: addressNotZeroSchema,
192
- name: z.string().optional().default("Unnamed Permit"),
193
- expiration: z.int().optional().default(DEFAULT_EXPIRATION_FN),
194
- recipient: addressSchema.optional().default(zeroAddress),
195
- validatorId: z.int().optional().default(0),
196
- validatorContract: addressSchema.optional().default(zeroAddress),
197
- issuerSignature: bytesSchema.optional().default("0x"),
198
- recipientSignature: bytesSchema.optional().default("0x")
199
- }).refine(...ExternalValidatorRefinement);
200
- var SelfPermitValidator = zPermitWithSealingPair.refine((data) => data.type === "self", {
201
- error: "Type must be 'self'"
202
- }).refine((data) => data.recipient === zeroAddress, {
203
- error: "Recipient must be zeroAddress"
204
- }).refine((data) => data.issuerSignature !== "0x", {
205
- error: "IssuerSignature must be populated"
206
- }).refine((data) => data.recipientSignature === "0x", {
207
- error: "RecipientSignature must be empty"
208
- }).refine(...ExternalValidatorRefinement);
209
- var SharingPermitOptionsValidator = z.object({
210
- type: z.literal("sharing").optional().default("sharing"),
211
- issuer: addressNotZeroSchema,
212
- recipient: addressNotZeroSchema,
213
- name: z.string().optional().default("Unnamed Permit"),
214
- expiration: z.int().optional().default(DEFAULT_EXPIRATION_FN),
215
- validatorId: z.int().optional().default(0),
216
- validatorContract: addressSchema.optional().default(zeroAddress),
217
- issuerSignature: bytesSchema.optional().default("0x"),
218
- recipientSignature: bytesSchema.optional().default("0x")
219
- }).refine(...RecipientRefinement).refine(...ExternalValidatorRefinement);
220
- var SharingPermitValidator = zPermitWithSealingPair.refine((data) => data.type === "sharing", {
221
- error: "Type must be 'sharing'"
222
- }).refine((data) => data.recipient !== zeroAddress, {
223
- error: "Recipient must not be zeroAddress"
224
- }).refine((data) => data.issuerSignature !== "0x", {
225
- error: "IssuerSignature must be populated"
226
- }).refine((data) => data.recipientSignature === "0x", {
227
- error: "RecipientSignature must be empty"
228
- }).refine(...ExternalValidatorRefinement);
229
- var ImportPermitOptionsValidator = z.object({
230
- type: z.literal("recipient").optional().default("recipient"),
231
- issuer: addressNotZeroSchema,
232
- recipient: addressNotZeroSchema,
233
- name: z.string().optional().default("Unnamed Permit"),
234
- expiration: z.int(),
235
- validatorId: z.int().optional().default(0),
236
- validatorContract: addressSchema.optional().default(zeroAddress),
237
- issuerSignature: bytesNotEmptySchema,
238
- recipientSignature: bytesSchema.optional().default("0x")
239
- }).refine(...ExternalValidatorRefinement);
240
- var ImportPermitValidator = zPermitWithSealingPair.refine((data) => data.type === "recipient", {
241
- error: "Type must be 'recipient'"
242
- }).refine((data) => data.recipient !== zeroAddress, {
243
- error: "Recipient must not be zeroAddress"
244
- }).refine((data) => data.issuerSignature !== "0x", {
245
- error: "IssuerSignature must be populated"
246
- }).refine((data) => data.recipientSignature !== "0x", {
247
- error: "RecipientSignature must be populated"
248
- }).refine(...ExternalValidatorRefinement);
249
- var safeParseAndThrowFormatted = (schema, data, message) => {
250
- const result = schema.safeParse(data);
251
- if (!result.success) {
252
- throw new Error(`${message}: ${z.prettifyError(result.error)}`, { cause: result.error });
253
- }
254
- return result.data;
255
- };
256
- var validateSelfPermitOptions = (options) => {
257
- return safeParseAndThrowFormatted(SelfPermitOptionsValidator, options, "Invalid self permit options");
258
- };
259
- var validateSharingPermitOptions = (options) => {
260
- return safeParseAndThrowFormatted(SharingPermitOptionsValidator, options, "Invalid sharing permit options");
261
- };
262
- var validateImportPermitOptions = (options) => {
263
- return safeParseAndThrowFormatted(ImportPermitOptionsValidator, options, "Invalid import permit options");
264
- };
265
- var validateSelfPermit = (permit) => {
266
- return safeParseAndThrowFormatted(SelfPermitValidator, permit, "Invalid self permit");
267
- };
268
- var validateSharingPermit = (permit) => {
269
- return safeParseAndThrowFormatted(SharingPermitValidator, permit, "Invalid sharing permit");
270
- };
271
- var validateImportPermit = (permit) => {
272
- return safeParseAndThrowFormatted(ImportPermitValidator, permit, "Invalid import permit");
273
- };
274
- var ValidationUtils = {
275
- /**
276
- * Check if permit is expired
277
- */
278
- isExpired: (permit) => {
279
- return permit.expiration < Math.floor(Date.now() / 1e3);
280
- },
281
- /**
282
- * Check if permit is signed by the active party
283
- */
284
- isSigned: (permit) => {
285
- if (permit.type === "self" || permit.type === "sharing") {
286
- return permit.issuerSignature !== "0x";
287
- }
288
- if (permit.type === "recipient") {
289
- return permit.recipientSignature !== "0x";
290
- }
291
- return false;
292
- },
293
- /**
294
- * Checks that a permit is signed and not expired.
295
- */
296
- isSignedAndNotExpired: (permit) => {
297
- if (ValidationUtils.isExpired(permit)) {
298
- return { valid: false, error: "expired" };
299
- }
300
- if (!ValidationUtils.isSigned(permit)) {
301
- return { valid: false, error: "not-signed" };
302
- }
303
- return { valid: true, error: null };
304
- },
305
- /**
306
- * Asserts that a permit is signed and not expired.
307
- *
308
- * Throws `Error` with message:
309
- * - `Permit is expired`
310
- * - `Permit is not signed`
311
- */
312
- assertSignedAndNotExpired: (permit) => {
313
- const result = ValidationUtils.isSignedAndNotExpired(permit);
314
- if (result.valid)
315
- return;
316
- if (result.error === "expired") {
317
- throw new Error("Permit is expired");
318
- }
319
- if (result.error === "not-signed") {
320
- throw new Error("Permit is not signed");
321
- }
322
- throw new Error("Permit is invalid");
323
- },
324
- isValid: (permit) => {
325
- const schema = permit.type === "self" ? SelfPermitValidator : permit.type === "sharing" ? SharingPermitValidator : permit.type === "recipient" ? ImportPermitValidator : null;
326
- if (schema == null)
327
- return { valid: false, error: "invalid-schema" };
328
- const schemaResult = schema.safeParse(permit);
329
- if (!schemaResult.success)
330
- return { valid: false, error: "invalid-schema" };
331
- return ValidationUtils.isSignedAndNotExpired(permit);
332
- }
333
- };
334
-
335
- // permits/signature.ts
336
- var PermitSignatureAllFields = [
337
- { name: "issuer", type: "address" },
338
- { name: "expiration", type: "uint64" },
339
- { name: "recipient", type: "address" },
340
- { name: "validatorId", type: "uint256" },
341
- { name: "validatorContract", type: "address" },
342
- { name: "sealingKey", type: "bytes32" },
343
- { name: "issuerSignature", type: "bytes" }
344
- ];
345
- var SignatureTypes = {
346
- PermissionedV2IssuerSelf: [
347
- "issuer",
348
- "expiration",
349
- "recipient",
350
- "validatorId",
351
- "validatorContract",
352
- "sealingKey"
353
- ],
354
- PermissionedV2IssuerShared: [
355
- "issuer",
356
- "expiration",
357
- "recipient",
358
- "validatorId",
359
- "validatorContract"
360
- ],
361
- PermissionedV2Recipient: ["sealingKey", "issuerSignature"]
362
- };
363
- var getSignatureTypesAndMessage = (primaryType, fields, values) => {
364
- const types = {
365
- [primaryType]: PermitSignatureAllFields.filter((fieldType) => fields.includes(fieldType.name))
366
- };
367
- const message = {};
368
- fields.forEach((field) => {
369
- if (field in values) {
370
- message[field] = values[field];
371
- }
372
- });
373
- return { types, primaryType, message };
374
- };
375
- var SignatureUtils = {
376
- /**
377
- * Get signature parameters for a permit
378
- */
379
- getSignatureParams: (permit, primaryType) => {
380
- return getSignatureTypesAndMessage(primaryType, SignatureTypes[primaryType], permit);
381
- },
382
- /**
383
- * Determine the required signature type based on permit type
384
- */
385
- getPrimaryType: (permitType) => {
386
- if (permitType === "self")
387
- return "PermissionedV2IssuerSelf";
388
- if (permitType === "sharing")
389
- return "PermissionedV2IssuerShared";
390
- if (permitType === "recipient")
391
- return "PermissionedV2Recipient";
392
- throw new Error(`Unknown permit type: ${permitType}`);
393
- }
394
- };
395
- var getAclAddress = async (publicClient) => {
396
- const ACL_IFACE = "function acl() view returns (address)";
397
- const aclAbi = parseAbi([ACL_IFACE]);
398
- return await publicClient.readContract({
399
- address: TASK_MANAGER_ADDRESS,
400
- abi: aclAbi,
401
- functionName: "acl"
402
- });
403
- };
404
- var getAclEIP712Domain = async (publicClient) => {
405
- const aclAddress = await getAclAddress(publicClient);
406
- const EIP712_DOMAIN_IFACE = "function eip712Domain() public view returns (bytes1 fields, string name, string version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] extensions)";
407
- const domainAbi = parseAbi([EIP712_DOMAIN_IFACE]);
408
- const domain = await publicClient.readContract({
409
- address: aclAddress,
410
- abi: domainAbi,
411
- functionName: "eip712Domain"
412
- });
413
- const [_fields, name, version, chainId, verifyingContract, _salt, _extensions] = domain;
414
- return {
415
- name,
416
- version,
417
- chainId: Number(chainId),
418
- verifyingContract
419
- };
420
- };
421
- var checkPermitValidityOnChain = async (permission, publicClient) => {
422
- const aclAddress = await getAclAddress(publicClient);
423
- try {
424
- await publicClient.simulateContract({
425
- address: aclAddress,
426
- abi: checkPermitValidityAbi,
427
- functionName: "checkPermitValidity",
428
- args: [
429
- {
430
- issuer: permission.issuer,
431
- expiration: BigInt(permission.expiration),
432
- recipient: permission.recipient,
433
- validatorId: BigInt(permission.validatorId),
434
- validatorContract: permission.validatorContract,
435
- sealingKey: permission.sealingKey,
436
- issuerSignature: permission.issuerSignature,
437
- recipientSignature: permission.recipientSignature
438
- }
439
- ]
440
- });
441
- return true;
442
- } catch (err) {
443
- if (err instanceof BaseError) {
444
- const revertError = err.walk((err2) => err2 instanceof ContractFunctionRevertedError);
445
- if (revertError instanceof ContractFunctionRevertedError) {
446
- const errorName = revertError.data?.errorName ?? "";
447
- throw new Error(errorName);
448
- }
449
- }
450
- const customErrorName = extractCustomErrorFromDetails(err, checkPermitValidityAbi);
451
- if (customErrorName) {
452
- throw new Error(customErrorName);
453
- }
454
- const hhDetailsData = extractReturnData(err);
455
- if (hhDetailsData != null) {
456
- const decoded = decodeErrorResult({
457
- abi: checkPermitValidityAbi,
458
- data: hhDetailsData
459
- });
460
- throw new Error(decoded.errorName);
461
- }
462
- throw err;
463
- }
464
- };
465
- function extractCustomErrorFromDetails(err, abi) {
466
- const anyErr = err;
467
- const details = anyErr?.details ?? anyErr?.cause?.details;
468
- if (typeof details === "string") {
469
- const customErrorMatch = details.match(/reverted with custom error '(\w+)\(\)'/);
470
- if (customErrorMatch) {
471
- const errorName = customErrorMatch[1];
472
- const errorExists = abi.some((item) => item.type === "error" && item.name === errorName);
473
- if (errorExists) {
474
- return errorName;
475
- }
476
- }
477
- }
478
- return void 0;
479
- }
480
- function extractReturnData(err) {
481
- const anyErr = err;
482
- const s = anyErr?.details ?? anyErr?.cause?.details ?? anyErr?.shortMessage ?? anyErr?.message ?? String(err);
483
- return s.match(/return data:\s*(0x[a-fA-F0-9]+)/)?.[1];
484
- }
485
- var checkPermitValidityAbi = [
486
- {
487
- type: "function",
488
- name: "checkPermitValidity",
489
- inputs: [
490
- {
491
- name: "permission",
492
- type: "tuple",
493
- internalType: "struct Permission",
494
- components: [
495
- {
496
- name: "issuer",
497
- type: "address",
498
- internalType: "address"
499
- },
500
- {
501
- name: "expiration",
502
- type: "uint64",
503
- internalType: "uint64"
504
- },
505
- {
506
- name: "recipient",
507
- type: "address",
508
- internalType: "address"
509
- },
510
- {
511
- name: "validatorId",
512
- type: "uint256",
513
- internalType: "uint256"
514
- },
515
- {
516
- name: "validatorContract",
517
- type: "address",
518
- internalType: "address"
519
- },
520
- {
521
- name: "sealingKey",
522
- type: "bytes32",
523
- internalType: "bytes32"
524
- },
525
- {
526
- name: "issuerSignature",
527
- type: "bytes",
528
- internalType: "bytes"
529
- },
530
- {
531
- name: "recipientSignature",
532
- type: "bytes",
533
- internalType: "bytes"
534
- }
535
- ]
536
- }
537
- ],
538
- outputs: [
539
- {
540
- name: "",
541
- type: "bool",
542
- internalType: "bool"
543
- }
544
- ],
545
- stateMutability: "view"
546
- },
547
- {
548
- type: "error",
549
- name: "PermissionInvalid_Disabled",
550
- inputs: []
551
- },
552
- {
553
- type: "error",
554
- name: "PermissionInvalid_Expired",
555
- inputs: []
556
- },
557
- {
558
- type: "error",
559
- name: "PermissionInvalid_IssuerSignature",
560
- inputs: []
561
- },
562
- {
563
- type: "error",
564
- name: "PermissionInvalid_RecipientSignature",
565
- inputs: []
566
- }
567
- ];
568
-
569
- // permits/permit.ts
570
- var PermitUtils = {
571
- /**
572
- * Create a self permit for personal use
573
- */
574
- createSelf: (options) => {
575
- const validation = validateSelfPermitOptions(options);
576
- const sealingPair = GenerateSealingKey();
577
- const permit = {
578
- hash: PermitUtils.getHash(validation),
579
- ...validation,
580
- sealingPair,
581
- _signedDomain: void 0
582
- };
583
- return permit;
584
- },
585
- /**
586
- * Create a sharing permit to be shared with another user
587
- */
588
- createSharing: (options) => {
589
- const validation = validateSharingPermitOptions(options);
590
- const sealingPair = GenerateSealingKey();
591
- const permit = {
592
- hash: PermitUtils.getHash(validation),
593
- ...validation,
594
- sealingPair,
595
- _signedDomain: void 0
596
- };
597
- return permit;
598
- },
599
- /**
600
- * Import a shared permit from various input formats
601
- */
602
- importShared: (options) => {
603
- let parsedOptions;
604
- if (typeof options === "string") {
605
- try {
606
- parsedOptions = JSON.parse(options);
607
- } catch (error) {
608
- throw new Error(`Failed to parse JSON string: ${error}`);
609
- }
610
- } else if (typeof options === "object" && options !== null) {
611
- parsedOptions = options;
612
- } else {
613
- throw new Error("Invalid input type, expected ImportSharedPermitOptions, object, or string");
614
- }
615
- if (parsedOptions.type != null && parsedOptions.type !== "sharing") {
616
- throw new Error(`Invalid permit type <${parsedOptions.type}>, must be "sharing"`);
617
- }
618
- const validation = validateImportPermitOptions({ ...parsedOptions, type: "recipient" });
619
- const sealingPair = GenerateSealingKey();
620
- const permit = {
621
- hash: PermitUtils.getHash(validation),
622
- ...validation,
623
- sealingPair,
624
- _signedDomain: void 0
625
- };
626
- return permit;
627
- },
628
- /**
629
- * Sign a permit with the provided wallet client
630
- */
631
- sign: async (permit, publicClient, walletClient) => {
632
- if (walletClient == null || walletClient.account == null) {
633
- throw new Error(
634
- "Missing walletClient, you must pass in a `walletClient` for the connected user to create a permit signature"
635
- );
636
- }
637
- const primaryType = SignatureUtils.getPrimaryType(permit.type);
638
- const domain = await getAclEIP712Domain(publicClient);
639
- const { types, message } = SignatureUtils.getSignatureParams(PermitUtils.getPermission(permit, true), primaryType);
640
- const signature = await walletClient.signTypedData({
641
- domain,
642
- types,
643
- primaryType,
644
- message,
645
- account: walletClient.account
646
- });
647
- let updatedPermit;
648
- if (permit.type === "self" || permit.type === "sharing") {
649
- updatedPermit = {
650
- ...permit,
651
- issuerSignature: signature,
652
- _signedDomain: domain
653
- };
654
- } else {
655
- updatedPermit = {
656
- ...permit,
657
- recipientSignature: signature,
658
- _signedDomain: domain
659
- };
660
- }
661
- return updatedPermit;
662
- },
663
- /**
664
- * Create and sign a self permit in one operation
665
- */
666
- createSelfAndSign: async (options, publicClient, walletClient) => {
667
- const permit = PermitUtils.createSelf(options);
668
- return PermitUtils.sign(permit, publicClient, walletClient);
669
- },
670
- /**
671
- * Create and sign a sharing permit in one operation
672
- */
673
- createSharingAndSign: async (options, publicClient, walletClient) => {
674
- const permit = PermitUtils.createSharing(options);
675
- return PermitUtils.sign(permit, publicClient, walletClient);
676
- },
677
- /**
678
- * Import and sign a shared permit in one operation from various input formats
679
- */
680
- importSharedAndSign: async (options, publicClient, walletClient) => {
681
- const permit = PermitUtils.importShared(options);
682
- return PermitUtils.sign(permit, publicClient, walletClient);
683
- },
684
- /**
685
- * Deserialize a permit from serialized data
686
- */
687
- deserialize: (data) => {
688
- return {
689
- ...data,
690
- sealingPair: SealingKey.deserialize(data.sealingPair.privateKey, data.sealingPair.publicKey)
691
- };
692
- },
693
- /**
694
- * Serialize a permit for storage
695
- */
696
- serialize: (permit) => {
697
- return {
698
- hash: permit.hash,
699
- name: permit.name,
700
- type: permit.type,
701
- issuer: permit.issuer,
702
- expiration: permit.expiration,
703
- recipient: permit.recipient,
704
- validatorId: permit.validatorId,
705
- validatorContract: permit.validatorContract,
706
- issuerSignature: permit.issuerSignature,
707
- recipientSignature: permit.recipientSignature,
708
- _signedDomain: permit._signedDomain,
709
- sealingPair: permit.sealingPair.serialize()
710
- };
711
- },
712
- /**
713
- * Validate a permit (schema-level validation)
714
- */
715
- validateSchema: (permit) => {
716
- if (permit.type === "self") {
717
- return validateSelfPermit(permit);
718
- } else if (permit.type === "sharing") {
719
- return validateSharingPermit(permit);
720
- } else if (permit.type === "recipient") {
721
- return validateImportPermit(permit);
722
- } else {
723
- throw new Error("Invalid permit type");
724
- }
725
- },
726
- /**
727
- * Validate a permit (holistic validation).
728
- *
729
- * This validates:
730
- * - Permit schema (shape + invariants)
731
- * - Permit is signed
732
- * - Permit is not expired
733
- *
734
- * For schema-only validation, use `validateSchema(permit)`.
735
- */
736
- validate: (permit) => {
737
- const validated = PermitUtils.validateSchema(permit);
738
- ValidationUtils.assertSignedAndNotExpired(validated);
739
- return validated;
740
- },
741
- /**
742
- * Get the permission object from a permit (for use in contracts)
743
- */
744
- getPermission: (permit, skipValidation = false) => {
745
- if (!skipValidation) {
746
- PermitUtils.validateSchema(permit);
747
- }
748
- return {
749
- issuer: permit.issuer,
750
- expiration: permit.expiration,
751
- recipient: permit.recipient,
752
- validatorId: permit.validatorId,
753
- validatorContract: permit.validatorContract,
754
- sealingKey: `0x${permit.sealingPair.publicKey}`,
755
- issuerSignature: permit.issuerSignature,
756
- recipientSignature: permit.recipientSignature
757
- };
758
- },
759
- /**
760
- * Get a stable hash for the permit (used as key in storage)
761
- */
762
- getHash: (permit) => {
763
- const data = JSON.stringify({
764
- type: permit.type,
765
- issuer: permit.issuer,
766
- expiration: permit.expiration,
767
- recipient: permit.recipient,
768
- validatorId: permit.validatorId,
769
- validatorContract: permit.validatorContract
770
- });
771
- return keccak256(toHex(data));
772
- },
773
- /**
774
- * Export permit data for sharing (removes sensitive fields)
775
- */
776
- export: (permit) => {
777
- const cleanedPermit = {
778
- name: permit.name,
779
- type: permit.type,
780
- issuer: permit.issuer,
781
- expiration: permit.expiration
782
- };
783
- if (permit.recipient !== zeroAddress)
784
- cleanedPermit.recipient = permit.recipient;
785
- if (permit.validatorId !== 0)
786
- cleanedPermit.validatorId = permit.validatorId;
787
- if (permit.validatorContract !== zeroAddress)
788
- cleanedPermit.validatorContract = permit.validatorContract;
789
- if (permit.type === "sharing" && permit.issuerSignature !== "0x")
790
- cleanedPermit.issuerSignature = permit.issuerSignature;
791
- return JSON.stringify(cleanedPermit, void 0, 2);
792
- },
793
- /**
794
- * Unseal encrypted data using the permit's sealing key
795
- */
796
- unseal: (permit, ciphertext) => {
797
- return permit.sealingPair.unseal(ciphertext);
798
- },
799
- /**
800
- * Check if permit is expired
801
- */
802
- isExpired: (permit) => {
803
- return ValidationUtils.isExpired(permit);
804
- },
805
- /**
806
- * Check if permit is signed
807
- */
808
- isSigned: (permit) => {
809
- return ValidationUtils.isSigned(permit);
810
- },
811
- /**
812
- * Check if permit is signed and not expired
813
- */
814
- isSignedAndNotExpired: (permit) => {
815
- return ValidationUtils.isSignedAndNotExpired(permit);
816
- },
817
- /**
818
- * Assert that permit is signed and not expired
819
- */
820
- assertSignedAndNotExpired: (permit) => {
821
- return ValidationUtils.assertSignedAndNotExpired(permit);
822
- },
823
- isValid: (permit) => {
824
- return ValidationUtils.isValid(permit);
825
- },
826
- /**
827
- * Update permit name (returns new permit instance)
828
- */
829
- updateName: (permit, name) => {
830
- return { ...permit, name };
831
- },
832
- /**
833
- * Fetch EIP712 domain from the blockchain
834
- */
835
- fetchEIP712Domain: async (publicClient) => {
836
- return getAclEIP712Domain(publicClient);
837
- },
838
- /**
839
- * Check if permit's signed domain matches the provided domain
840
- */
841
- matchesDomain: (permit, domain) => {
842
- return permit._signedDomain?.name === domain.name && permit._signedDomain?.version === domain.version && permit._signedDomain?.verifyingContract === domain.verifyingContract && permit._signedDomain?.chainId === domain.chainId;
843
- },
844
- /**
845
- * Check if permit's signed domain is valid for the current chain
846
- */
847
- checkSignedDomainValid: async (permit, publicClient) => {
848
- if (permit._signedDomain == null)
849
- return false;
850
- const domain = await getAclEIP712Domain(publicClient);
851
- return PermitUtils.matchesDomain(permit, domain);
852
- },
853
- /**
854
- * Check if permit passes the on-chain validation
855
- */
856
- checkValidityOnChain: async (permit, publicClient) => {
857
- const permission = PermitUtils.getPermission(permit);
858
- return checkPermitValidityOnChain(permission, publicClient);
859
- }
860
- };
861
- var PERMIT_STORE_DEFAULTS = {
862
- permits: {},
863
- activePermitHash: {}
864
- };
865
- var _permitStore = createStore()(
866
- persist(() => PERMIT_STORE_DEFAULTS, { name: "cofhesdk-permits" })
867
- );
868
- var clearStaleStore = () => {
869
- const state = _permitStore.getState();
870
- const hasExpectedStructure = state && typeof state === "object" && "permits" in state && "activePermitHash" in state && typeof state.permits === "object" && typeof state.activePermitHash === "object";
871
- if (hasExpectedStructure)
872
- return;
873
- _permitStore.setState({ permits: {}, activePermitHash: {} });
874
- };
875
- var getPermit = (chainId, account, hash) => {
876
- clearStaleStore();
877
- if (chainId == null || account == null || hash == null)
878
- return;
879
- const savedPermit = _permitStore.getState().permits[chainId]?.[account]?.[hash];
880
- if (savedPermit == null)
881
- return;
882
- return PermitUtils.deserialize(savedPermit);
883
- };
884
- var getActivePermit = (chainId, account) => {
885
- clearStaleStore();
886
- if (chainId == null || account == null)
887
- return;
888
- const activePermitHash = _permitStore.getState().activePermitHash[chainId]?.[account];
889
- return getPermit(chainId, account, activePermitHash);
890
- };
891
- var getPermits = (chainId, account) => {
892
- clearStaleStore();
893
- if (chainId == null || account == null)
894
- return {};
895
- return Object.entries(_permitStore.getState().permits[chainId]?.[account] ?? {}).reduce(
896
- (acc, [hash, permit]) => {
897
- if (permit == void 0)
898
- return acc;
899
- return { ...acc, [hash]: PermitUtils.deserialize(permit) };
900
- },
901
- {}
902
- );
903
- };
904
- var setPermit = (chainId, account, permit) => {
905
- clearStaleStore();
906
- _permitStore.setState(
907
- produce((state) => {
908
- if (state.permits[chainId] == null)
909
- state.permits[chainId] = {};
910
- if (state.permits[chainId][account] == null)
911
- state.permits[chainId][account] = {};
912
- state.permits[chainId][account][permit.hash] = PermitUtils.serialize(permit);
913
- })
914
- );
915
- };
916
- var removePermit = (chainId, account, hash) => {
917
- clearStaleStore();
918
- _permitStore.setState(
919
- produce((state) => {
920
- if (state.permits[chainId] == null)
921
- state.permits[chainId] = {};
922
- if (state.activePermitHash[chainId] == null)
923
- state.activePermitHash[chainId] = {};
924
- const accountPermits = state.permits[chainId][account];
925
- if (accountPermits == null)
926
- return;
927
- if (accountPermits[hash] == null)
928
- return;
929
- if (state.activePermitHash[chainId][account] === hash) {
930
- state.activePermitHash[chainId][account] = void 0;
931
- }
932
- accountPermits[hash] = void 0;
933
- })
934
- );
935
- };
936
- var getActivePermitHash = (chainId, account) => {
937
- clearStaleStore();
938
- if (chainId == null || account == null)
939
- return void 0;
940
- return _permitStore.getState().activePermitHash[chainId]?.[account];
941
- };
942
- var setActivePermitHash = (chainId, account, hash) => {
943
- clearStaleStore();
944
- _permitStore.setState(
945
- produce((state) => {
946
- if (state.activePermitHash[chainId] == null)
947
- state.activePermitHash[chainId] = {};
948
- state.activePermitHash[chainId][account] = hash;
949
- })
950
- );
951
- };
952
- var removeActivePermitHash = (chainId, account) => {
953
- clearStaleStore();
954
- _permitStore.setState(
955
- produce((state) => {
956
- if (state.activePermitHash[chainId])
957
- state.activePermitHash[chainId][account] = void 0;
958
- })
959
- );
960
- };
961
- var resetStore = () => {
962
- clearStaleStore();
963
- _permitStore.setState({ permits: {}, activePermitHash: {} });
964
- };
965
- var permitStore = {
966
- store: _permitStore,
967
- getPermit,
968
- getActivePermit,
969
- getPermits,
970
- setPermit,
971
- removePermit,
972
- getActivePermitHash,
973
- setActivePermitHash,
974
- removeActivePermitHash,
975
- resetStore
976
- };
977
-
978
- export { GenerateSealingKey, ImportPermitOptionsValidator, ImportPermitValidator, PERMIT_STORE_DEFAULTS, PermitUtils, SealingKey, SelfPermitOptionsValidator, SelfPermitValidator, SharingPermitOptionsValidator, SharingPermitValidator, SignatureTypes, SignatureUtils, ValidationUtils, _permitStore, addressNotZeroSchema, addressSchema, bytesNotEmptySchema, bytesSchema, clearStaleStore, getActivePermit, getActivePermitHash, getPermit, getPermits, getSignatureTypesAndMessage, permitStore, removeActivePermitHash, removePermit, resetStore, setActivePermitHash, setPermit, validateImportPermit, validateImportPermitOptions, validateSelfPermit, validateSelfPermitOptions, validateSharingPermit, validateSharingPermitOptions };