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