@cofhe/sdk 0.1.0 → 0.2.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 (121) hide show
  1. package/CHANGELOG.md +62 -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 +36 -0
  9. package/adapters/index.test.ts +20 -0
  10. package/adapters/index.ts +5 -0
  11. package/adapters/smartWallet.ts +99 -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/localcofhe.ts +14 -0
  20. package/chains/chains/sepolia.ts +14 -0
  21. package/chains/chains.test.ts +50 -0
  22. package/chains/defineChain.ts +18 -0
  23. package/chains/index.ts +35 -0
  24. package/chains/types.ts +32 -0
  25. package/core/baseBuilder.ts +119 -0
  26. package/core/client.test.ts +315 -0
  27. package/core/client.ts +292 -0
  28. package/core/clientTypes.ts +108 -0
  29. package/core/config.test.ts +235 -0
  30. package/core/config.ts +220 -0
  31. package/core/decrypt/MockQueryDecrypterAbi.ts +129 -0
  32. package/core/decrypt/cofheMocksSealOutput.ts +57 -0
  33. package/core/decrypt/decryptHandleBuilder.ts +287 -0
  34. package/core/decrypt/decryptUtils.ts +28 -0
  35. package/core/decrypt/tnSealOutputV1.ts +59 -0
  36. package/core/decrypt/tnSealOutputV2.ts +298 -0
  37. package/core/encrypt/MockZkVerifierAbi.ts +106 -0
  38. package/core/encrypt/cofheMocksZkVerifySign.ts +284 -0
  39. package/core/encrypt/encryptInputsBuilder.test.ts +751 -0
  40. package/core/encrypt/encryptInputsBuilder.ts +560 -0
  41. package/core/encrypt/encryptUtils.ts +67 -0
  42. package/core/encrypt/zkPackProveVerify.ts +335 -0
  43. package/core/error.ts +168 -0
  44. package/core/fetchKeys.test.ts +195 -0
  45. package/core/fetchKeys.ts +144 -0
  46. package/core/index.ts +89 -0
  47. package/core/keyStore.test.ts +226 -0
  48. package/core/keyStore.ts +154 -0
  49. package/core/permits.test.ts +494 -0
  50. package/core/permits.ts +200 -0
  51. package/core/types.ts +398 -0
  52. package/core/utils.ts +130 -0
  53. package/dist/adapters.cjs +88 -0
  54. package/dist/adapters.d.cts +14576 -0
  55. package/dist/adapters.d.ts +14576 -0
  56. package/dist/adapters.js +83 -0
  57. package/dist/chains.cjs +114 -0
  58. package/dist/chains.d.cts +121 -0
  59. package/dist/chains.d.ts +121 -0
  60. package/dist/chains.js +1 -0
  61. package/dist/chunk-UGBVZNRT.js +818 -0
  62. package/dist/chunk-WEAZ25JO.js +105 -0
  63. package/dist/chunk-WGCRJCBR.js +2523 -0
  64. package/dist/clientTypes-5_1nwtUe.d.cts +914 -0
  65. package/dist/clientTypes-Es7fyi65.d.ts +914 -0
  66. package/dist/core.cjs +3414 -0
  67. package/dist/core.d.cts +111 -0
  68. package/dist/core.d.ts +111 -0
  69. package/dist/core.js +3 -0
  70. package/dist/node.cjs +3286 -0
  71. package/dist/node.d.cts +22 -0
  72. package/dist/node.d.ts +22 -0
  73. package/dist/node.js +91 -0
  74. package/dist/permit-fUSe6KKq.d.cts +349 -0
  75. package/dist/permit-fUSe6KKq.d.ts +349 -0
  76. package/dist/permits.cjs +871 -0
  77. package/dist/permits.d.cts +1045 -0
  78. package/dist/permits.d.ts +1045 -0
  79. package/dist/permits.js +1 -0
  80. package/dist/types-KImPrEIe.d.cts +48 -0
  81. package/dist/types-KImPrEIe.d.ts +48 -0
  82. package/dist/web.cjs +3478 -0
  83. package/dist/web.d.cts +38 -0
  84. package/dist/web.d.ts +38 -0
  85. package/dist/web.js +240 -0
  86. package/dist/zkProve.worker.cjs +93 -0
  87. package/dist/zkProve.worker.d.cts +2 -0
  88. package/dist/zkProve.worker.d.ts +2 -0
  89. package/dist/zkProve.worker.js +91 -0
  90. package/node/client.test.ts +147 -0
  91. package/node/config.test.ts +68 -0
  92. package/node/encryptInputs.test.ts +155 -0
  93. package/node/index.ts +97 -0
  94. package/node/storage.ts +51 -0
  95. package/package.json +27 -15
  96. package/permits/index.ts +68 -0
  97. package/permits/localstorage.test.ts +117 -0
  98. package/permits/permit.test.ts +477 -0
  99. package/permits/permit.ts +405 -0
  100. package/permits/sealing.test.ts +84 -0
  101. package/permits/sealing.ts +131 -0
  102. package/permits/signature.ts +79 -0
  103. package/permits/store.test.ts +128 -0
  104. package/permits/store.ts +166 -0
  105. package/permits/test-utils.ts +20 -0
  106. package/permits/types.ts +191 -0
  107. package/permits/utils.ts +62 -0
  108. package/permits/validation.test.ts +288 -0
  109. package/permits/validation.ts +369 -0
  110. package/web/client.web.test.ts +147 -0
  111. package/web/config.web.test.ts +69 -0
  112. package/web/encryptInputs.web.test.ts +172 -0
  113. package/web/index.ts +161 -0
  114. package/web/storage.ts +34 -0
  115. package/web/worker.builder.web.test.ts +148 -0
  116. package/web/worker.config.web.test.ts +329 -0
  117. package/web/worker.output.web.test.ts +84 -0
  118. package/web/workerManager.test.ts +80 -0
  119. package/web/workerManager.ts +214 -0
  120. package/web/workerManager.web.test.ts +114 -0
  121. package/web/zkProve.worker.ts +133 -0
package/core/types.ts ADDED
@@ -0,0 +1,398 @@
1
+ export type TfheInitializer = () => Promise<boolean>;
2
+
3
+ export interface IStorage {
4
+ getItem: (name: string) => Promise<any>;
5
+ setItem: (name: string, value: any) => Promise<void>;
6
+ removeItem: (name: string) => Promise<void>;
7
+ }
8
+
9
+ export type Primitive = null | undefined | string | number | boolean | symbol | bigint;
10
+ export type LiteralToPrimitive<T> = T extends number
11
+ ? number
12
+ : T extends bigint
13
+ ? bigint
14
+ : T extends string
15
+ ? string
16
+ : T extends boolean
17
+ ? boolean
18
+ : T extends symbol
19
+ ? symbol
20
+ : T extends null
21
+ ? null
22
+ : T extends undefined
23
+ ? undefined
24
+ : never;
25
+
26
+ // FHE TYPES
27
+
28
+ export const FheTypeValues = ['bool', 'uint8', 'uint16', 'uint32', 'uint64', 'uint128', 'address'] as const;
29
+ export type FheTypeValue = (typeof FheTypeValues)[number];
30
+
31
+ export enum FheTypes {
32
+ Bool = 0,
33
+ Uint4 = 1,
34
+ Uint8 = 2,
35
+ Uint16 = 3,
36
+ Uint32 = 4,
37
+ Uint64 = 5,
38
+ Uint128 = 6,
39
+ Uint160 = 7,
40
+ Uint256 = 8,
41
+ Uint512 = 9,
42
+ Uint1024 = 10,
43
+ Uint2048 = 11,
44
+ Uint2 = 12,
45
+ Uint6 = 13,
46
+ Uint10 = 14,
47
+ Uint12 = 15,
48
+ Uint14 = 16,
49
+ Int2 = 17,
50
+ Int4 = 18,
51
+ Int6 = 19,
52
+ Int8 = 20,
53
+ Int10 = 21,
54
+ Int12 = 22,
55
+ Int14 = 23,
56
+ Int16 = 24,
57
+ Int32 = 25,
58
+ Int64 = 26,
59
+ Int128 = 27,
60
+ Int160 = 28,
61
+ Int256 = 29,
62
+ }
63
+
64
+ export const FheTypeValueUtype = {
65
+ bool: FheTypes.Bool,
66
+ uint8: FheTypes.Uint8,
67
+ uint16: FheTypes.Uint16,
68
+ uint32: FheTypes.Uint32,
69
+ uint64: FheTypes.Uint64,
70
+ uint128: FheTypes.Uint128,
71
+ address: FheTypes.Uint160,
72
+ } as const satisfies Record<FheTypeValue, FheTypes>;
73
+ export type FheTypeValueUtypeMap<T extends FheTypeValue> = T extends keyof typeof FheTypeValueUtype
74
+ ? (typeof FheTypeValueUtype)[T]
75
+ : never;
76
+
77
+ /**
78
+ * List of All FHE uint types (excludes bool and address)
79
+ */
80
+ export const FheUintUTypes = [
81
+ FheTypes.Uint8,
82
+ FheTypes.Uint16,
83
+ FheTypes.Uint32,
84
+ FheTypes.Uint64,
85
+ FheTypes.Uint128,
86
+ // [U256-DISABLED]
87
+ // FheTypes.Uint256,
88
+ ] as const;
89
+ export type FheUintUTypesType = (typeof FheUintUTypes)[number];
90
+
91
+ /**
92
+ * List of All FHE types (uints, bool, and address)
93
+ */
94
+ export const FheAllUTypes = [
95
+ FheTypes.Bool,
96
+ FheTypes.Uint8,
97
+ FheTypes.Uint16,
98
+ FheTypes.Uint32,
99
+ FheTypes.Uint64,
100
+ FheTypes.Uint128,
101
+ // [U256-DISABLED]
102
+ // FheTypes.Uint256,
103
+ FheTypes.Uint160,
104
+ ] as const;
105
+ type FheAllUTypesType = (typeof FheAllUTypes)[number];
106
+
107
+ // ENCRYPT
108
+
109
+ export type EncryptedNumber = {
110
+ data: Uint8Array;
111
+ securityZone: number;
112
+ };
113
+
114
+ export type EncryptedItemInput<TSignature = string> = {
115
+ ctHash: bigint;
116
+ securityZone: number;
117
+ utype: FheTypes;
118
+ signature: TSignature;
119
+ };
120
+
121
+ export function assertCorrectEncryptedItemInput(
122
+ input: EncryptedItemInput
123
+ ): asserts input is EncryptedItemInput<`0x${string}`> {
124
+ if (!input.signature.startsWith('0x')) throw new Error('Signature must be a hex string starting with 0x');
125
+ }
126
+
127
+ export type EncryptedBoolInput = EncryptedItemInput & {
128
+ utype: FheTypes.Bool;
129
+ };
130
+ export type EncryptedUint8Input = EncryptedItemInput & {
131
+ utype: FheTypes.Uint8;
132
+ };
133
+ export type EncryptedUint16Input = EncryptedItemInput & {
134
+ utype: FheTypes.Uint16;
135
+ };
136
+ export type EncryptedUint32Input = EncryptedItemInput & {
137
+ utype: FheTypes.Uint32;
138
+ };
139
+ export type EncryptedUint64Input = EncryptedItemInput & {
140
+ utype: FheTypes.Uint64;
141
+ };
142
+ export type EncryptedUint128Input = EncryptedItemInput & {
143
+ utype: FheTypes.Uint128;
144
+ };
145
+ // [U256-DISABLED]
146
+ // export type EncryptedUint256Input = EncryptedItemInput & {
147
+ // utype: FheTypes.Uint256;
148
+ // };
149
+ export type EncryptedAddressInput = EncryptedItemInput & {
150
+ utype: FheTypes.Uint160;
151
+ };
152
+
153
+ export type EncryptableBase<U extends FheTypes, D> = {
154
+ data: D;
155
+ securityZone: number;
156
+ utype: U;
157
+ };
158
+
159
+ export type EncryptableBool = EncryptableBase<FheTypes.Bool, boolean>;
160
+ export type EncryptableUint8 = EncryptableBase<FheTypes.Uint8, string | bigint>;
161
+ export type EncryptableUint16 = EncryptableBase<FheTypes.Uint16, string | bigint>;
162
+ export type EncryptableUint32 = EncryptableBase<FheTypes.Uint32, string | bigint>;
163
+ export type EncryptableUint64 = EncryptableBase<FheTypes.Uint64, string | bigint>;
164
+ export type EncryptableUint128 = EncryptableBase<FheTypes.Uint128, string | bigint>;
165
+ // [U256-DISABLED]
166
+ // export type EncryptableUint256 = EncryptableBase<FheTypes.Uint256, string | bigint>;
167
+ export type EncryptableAddress = EncryptableBase<FheTypes.Uint160, string | bigint>;
168
+
169
+ /**
170
+ * Maps FheTypeValue to its corresponding Encryptable type
171
+ * If a new FheTypeValue is added, this type must be updated to include it
172
+ */
173
+ type EncryptableTypeMap = {
174
+ bool: EncryptableBool;
175
+ address: EncryptableAddress;
176
+ uint8: EncryptableUint8;
177
+ uint16: EncryptableUint16;
178
+ uint32: EncryptableUint32;
179
+ uint64: EncryptableUint64;
180
+ uint128: EncryptableUint128;
181
+ // [U256-DISABLED]
182
+ // uint256: EncryptableUint256;
183
+ };
184
+
185
+ /**
186
+ * Ensures all FheTypeValue keys are present as factory functions.
187
+ * TypeScript will error if EncryptableTypeMap is missing any FheTypeValue key.
188
+ */
189
+ type EncryptableFactories = {
190
+ [K in FheTypeValue]: (data: EncryptableTypeMap[K]['data'], securityZone?: number) => EncryptableTypeMap[K];
191
+ };
192
+
193
+ type EncryptableFactory = EncryptableFactories & {
194
+ create: {
195
+ (type: 'bool', data: EncryptableBool['data'], securityZone?: number): EncryptableBool;
196
+ (type: 'address', data: EncryptableAddress['data'], securityZone?: number): EncryptableAddress;
197
+ (type: 'uint8', data: EncryptableUint8['data'], securityZone?: number): EncryptableUint8;
198
+ (type: 'uint16', data: EncryptableUint16['data'], securityZone?: number): EncryptableUint16;
199
+ (type: 'uint32', data: EncryptableUint32['data'], securityZone?: number): EncryptableUint32;
200
+ (type: 'uint64', data: EncryptableUint64['data'], securityZone?: number): EncryptableUint64;
201
+ (type: 'uint128', data: EncryptableUint128['data'], securityZone?: number): EncryptableUint128;
202
+ // [U256-DISABLED]
203
+ // (type: 'uint256', data: EncryptableUint256['data'], securityZone?: number): EncryptableUint256;
204
+
205
+ (type: FheTypeValue, data: EncryptableItem['data'], securityZone?: number): EncryptableItem;
206
+ };
207
+ };
208
+
209
+ const EncryptableFactoriesImpl = {
210
+ bool: (data: EncryptableBool['data'], securityZone = 0) => ({ data, securityZone, utype: FheTypes.Bool }),
211
+ address: (data: EncryptableAddress['data'], securityZone = 0) => ({ data, securityZone, utype: FheTypes.Uint160 }),
212
+ uint8: (data: EncryptableUint8['data'], securityZone = 0) => ({ data, securityZone, utype: FheTypes.Uint8 }),
213
+ uint16: (data: EncryptableUint16['data'], securityZone = 0) => ({ data, securityZone, utype: FheTypes.Uint16 }),
214
+ uint32: (data: EncryptableUint32['data'], securityZone = 0) => ({ data, securityZone, utype: FheTypes.Uint32 }),
215
+ uint64: (data: EncryptableUint64['data'], securityZone = 0) => ({ data, securityZone, utype: FheTypes.Uint64 }),
216
+ uint128: (data: EncryptableUint128['data'], securityZone = 0) => ({ data, securityZone, utype: FheTypes.Uint128 }),
217
+ // [U256-DISABLED]
218
+ // uint256: (data: EncryptableUint256['data'], securityZone = 0) =>
219
+ // ({ data, securityZone, utype: FheTypes.Uint256 }) as EncryptableUint256,
220
+ } satisfies EncryptableFactories;
221
+
222
+ /* eslint-disable no-redeclare */
223
+ function createEncryptableByLiteral(
224
+ type: 'bool',
225
+ data: EncryptableBool['data'],
226
+ securityZone?: number
227
+ ): EncryptableBool;
228
+ function createEncryptableByLiteral(
229
+ type: 'address',
230
+ data: EncryptableAddress['data'],
231
+ securityZone?: number
232
+ ): EncryptableAddress;
233
+ function createEncryptableByLiteral(
234
+ type: 'uint8',
235
+ data: EncryptableUint8['data'],
236
+ securityZone?: number
237
+ ): EncryptableUint8;
238
+ function createEncryptableByLiteral(
239
+ type: 'uint16',
240
+ data: EncryptableUint16['data'],
241
+ securityZone?: number
242
+ ): EncryptableUint16;
243
+ function createEncryptableByLiteral(
244
+ type: 'uint32',
245
+ data: EncryptableUint32['data'],
246
+ securityZone?: number
247
+ ): EncryptableUint32;
248
+ function createEncryptableByLiteral(
249
+ type: 'uint64',
250
+ data: EncryptableUint64['data'],
251
+ securityZone?: number
252
+ ): EncryptableUint64;
253
+ function createEncryptableByLiteral(
254
+ type: 'uint128',
255
+ data: EncryptableUint128['data'],
256
+ securityZone?: number
257
+ ): EncryptableUint128;
258
+ function createEncryptableByLiteral(
259
+ type: FheTypeValue,
260
+ data: EncryptableItem['data'],
261
+ securityZone?: number
262
+ ): EncryptableItem;
263
+ function createEncryptableByLiteral(
264
+ type: FheTypeValue,
265
+ data: EncryptableItem['data'],
266
+ securityZone = 0
267
+ ): EncryptableItem {
268
+ switch (type) {
269
+ case 'bool': {
270
+ if (typeof data !== 'boolean') throw new Error('Bool encryptable data must be boolean');
271
+ return EncryptableFactoriesImpl.bool(data, securityZone);
272
+ }
273
+ case 'address':
274
+ case 'uint8':
275
+ case 'uint16':
276
+ case 'uint32':
277
+ case 'uint64':
278
+ case 'uint128': {
279
+ if (typeof data === 'boolean') throw new Error('Uint encryptable data must be string or bigint');
280
+ return EncryptableFactoriesImpl[type](data, securityZone);
281
+ }
282
+ default: {
283
+ // Exhaustiveness guard
284
+ const _exhaustive: never = type;
285
+ throw new Error(`Unsupported encryptable type: ${_exhaustive}`);
286
+ }
287
+ }
288
+ }
289
+ /* eslint-enable no-redeclare */
290
+
291
+ export const Encryptable = {
292
+ ...EncryptableFactoriesImpl,
293
+ create: createEncryptableByLiteral,
294
+ } satisfies EncryptableFactory;
295
+
296
+ export type EncryptableItem =
297
+ | EncryptableBool
298
+ | EncryptableUint8
299
+ | EncryptableUint16
300
+ | EncryptableUint32
301
+ | EncryptableUint64
302
+ | EncryptableUint128
303
+ // [U256-DISABLED]
304
+ // | EncryptableUint256
305
+ | EncryptableAddress;
306
+
307
+ export type EncryptableItemByFheType<T extends FheTypes> = T extends FheTypes.Bool
308
+ ? EncryptableBool
309
+ : T extends FheTypes.Uint8
310
+ ? EncryptableUint8
311
+ : T extends FheTypes.Uint16
312
+ ? EncryptableUint16
313
+ : T extends FheTypes.Uint32
314
+ ? EncryptableUint32
315
+ : T extends FheTypes.Uint64
316
+ ? EncryptableUint64
317
+ : T extends FheTypes.Uint128
318
+ ? EncryptableUint128
319
+ : // [U256-DISABLED]
320
+ // : T extends FheTypes.Uint256
321
+ // ? EncryptableUint256
322
+ T extends FheTypes.Uint160
323
+ ? EncryptableAddress
324
+ : never;
325
+
326
+ // COFHE Encrypt
327
+ export type EncryptableToEncryptedItemInputMap<E extends EncryptableItem> = E extends EncryptableBool
328
+ ? EncryptedBoolInput
329
+ : E extends EncryptableUint8
330
+ ? EncryptedUint8Input
331
+ : E extends EncryptableUint16
332
+ ? EncryptedUint16Input
333
+ : E extends EncryptableUint32
334
+ ? EncryptedUint32Input
335
+ : E extends EncryptableUint64
336
+ ? EncryptedUint64Input
337
+ : E extends EncryptableUint128
338
+ ? EncryptedUint128Input
339
+ : // [U256-DISABLED]
340
+ // : E extends EncryptableUint256
341
+ // ? EncryptedUint256Input
342
+ E extends EncryptableAddress
343
+ ? EncryptedAddressInput
344
+ : never;
345
+
346
+ export type EncryptedItemInputs<T> = T extends Primitive
347
+ ? LiteralToPrimitive<T>
348
+ : T extends EncryptableItem
349
+ ? EncryptableToEncryptedItemInputMap<T>
350
+ : {
351
+ [K in keyof T]: EncryptedItemInputs<T[K]>;
352
+ };
353
+
354
+ export function isEncryptableItem(value: unknown): value is EncryptableItem {
355
+ return (
356
+ // Is object and exists
357
+ typeof value === 'object' &&
358
+ value !== null &&
359
+ // Has securityZone
360
+ 'securityZone' in value &&
361
+ typeof value.securityZone === 'number' &&
362
+ // Has utype
363
+ 'utype' in value &&
364
+ FheAllUTypes.includes(value.utype as FheAllUTypesType) &&
365
+ // Has data
366
+ 'data' in value &&
367
+ ['string', 'number', 'bigint', 'boolean'].includes(typeof value.data)
368
+ );
369
+ }
370
+
371
+ export enum EncryptStep {
372
+ InitTfhe = 'initTfhe',
373
+ FetchKeys = 'fetchKeys',
374
+ Pack = 'pack',
375
+ Prove = 'prove',
376
+ Verify = 'verify',
377
+ }
378
+
379
+ export function isLastEncryptionStep(step: EncryptStep): boolean {
380
+ return step === EncryptStep.Verify;
381
+ }
382
+
383
+ export type EncryptStepCallbackContext = Record<string, any> & {
384
+ isStart: boolean;
385
+ isEnd: boolean;
386
+ duration: number;
387
+ };
388
+ export type EncryptStepCallbackFunction = (state: EncryptStep, context?: EncryptStepCallbackContext) => void;
389
+
390
+ // DECRYPT
391
+
392
+ export type UnsealedItem<U extends FheTypes> = U extends FheTypes.Bool
393
+ ? boolean
394
+ : U extends FheTypes.Uint160
395
+ ? string
396
+ : U extends FheUintUTypesType
397
+ ? bigint
398
+ : never;
package/core/utils.ts ADDED
@@ -0,0 +1,130 @@
1
+ import { type PublicClient, type WalletClient } from 'viem';
2
+ import { CofhesdkError, CofhesdkErrorCode } from './error.js';
3
+ import { Encryptable, FheTypes } from './types.js';
4
+
5
+ export const toHexString = (bytes: Uint8Array) =>
6
+ bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');
7
+
8
+ export const fromHexString = (hexString: string): Uint8Array => {
9
+ const cleanString = hexString.length % 2 === 1 ? `0${hexString}` : hexString;
10
+ const arr = cleanString.replace(/^0x/, '').match(/.{1,2}/g);
11
+ if (!arr) return new Uint8Array();
12
+ return new Uint8Array(arr.map((byte) => parseInt(byte, 16)));
13
+ };
14
+
15
+ export const toBigIntOrThrow = (value: bigint | string): bigint => {
16
+ if (typeof value === 'bigint') {
17
+ return value;
18
+ }
19
+
20
+ try {
21
+ return BigInt(value);
22
+ } catch (error) {
23
+ throw new Error('Invalid input: Unable to convert to bigint');
24
+ }
25
+ };
26
+
27
+ export const validateBigIntInRange = (value: bigint, max: bigint, min: bigint = 0n): void => {
28
+ if (typeof value !== 'bigint') {
29
+ throw new Error('Value must be of type bigint');
30
+ }
31
+
32
+ if (value > max || value < min) {
33
+ throw new Error(`Value out of range: ${max} - ${min}, try a different uint type`);
34
+ }
35
+ };
36
+
37
+ // Helper function to convert hex string to bytes
38
+ export const hexToBytes = (hex: string): Uint8Array => {
39
+ const bytes = new Uint8Array(hex.length / 2);
40
+ for (let i = 0; i < hex.length; i += 2) {
41
+ bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
42
+ }
43
+ return bytes;
44
+ };
45
+
46
+ export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
47
+
48
+ export async function getPublicClientChainID(publicClient: PublicClient) {
49
+ let chainId: number | null = null;
50
+ try {
51
+ chainId = publicClient.chain?.id ?? (await publicClient.getChainId());
52
+ } catch (e) {
53
+ throw new CofhesdkError({
54
+ code: CofhesdkErrorCode.PublicWalletGetChainIdFailed,
55
+ message: 'getting chain ID from public client failed',
56
+ cause: e instanceof Error ? e : undefined,
57
+ });
58
+ }
59
+ if (chainId === null) {
60
+ throw new CofhesdkError({
61
+ code: CofhesdkErrorCode.PublicWalletGetChainIdFailed,
62
+ message: 'chain ID from public client is null',
63
+ });
64
+ }
65
+ return chainId;
66
+ }
67
+
68
+ export async function getWalletClientAccount(walletClient: WalletClient) {
69
+ let address: `0x${string}` | undefined;
70
+ try {
71
+ address = walletClient.account?.address;
72
+ if (!address) {
73
+ address = (await walletClient.getAddresses())?.[0];
74
+ }
75
+ } catch (e) {
76
+ throw new CofhesdkError({
77
+ code: CofhesdkErrorCode.PublicWalletGetAddressesFailed,
78
+ message: 'getting address from wallet client failed',
79
+ cause: e instanceof Error ? e : undefined,
80
+ });
81
+ }
82
+ if (!address) {
83
+ throw new CofhesdkError({
84
+ code: CofhesdkErrorCode.PublicWalletGetAddressesFailed,
85
+ message: 'address from wallet client is null',
86
+ });
87
+ }
88
+ return address;
89
+ }
90
+
91
+ /**
92
+ * Converts FheTypes enum to string representation for serialization
93
+ * Used when passing data to Web Workers or other serialization contexts
94
+ */
95
+ export function fheTypeToString(utype: FheTypes): string {
96
+ switch (utype) {
97
+ case FheTypes.Bool:
98
+ return 'bool';
99
+ case FheTypes.Uint4:
100
+ return 'uint4';
101
+ case FheTypes.Uint8:
102
+ return 'uint8';
103
+ case FheTypes.Uint16:
104
+ return 'uint16';
105
+ case FheTypes.Uint32:
106
+ return 'uint32';
107
+ case FheTypes.Uint64:
108
+ return 'uint64';
109
+ case FheTypes.Uint128:
110
+ return 'uint128';
111
+ case FheTypes.Uint160:
112
+ return 'uint160';
113
+ case FheTypes.Uint256:
114
+ return 'uint256';
115
+ case FheTypes.Uint512:
116
+ return 'uint512';
117
+ case FheTypes.Uint1024:
118
+ return 'uint1024';
119
+ case FheTypes.Uint2048:
120
+ return 'uint2048';
121
+ case FheTypes.Uint2:
122
+ return 'uint2';
123
+ case FheTypes.Uint6:
124
+ return 'uint6';
125
+ case FheTypes.Uint10:
126
+ return 'uint10';
127
+ default:
128
+ throw new Error(`Unknown FheType: ${utype}`);
129
+ }
130
+ }
@@ -0,0 +1,88 @@
1
+ 'use strict';
2
+
3
+ var viem = require('viem');
4
+ var accounts = require('viem/accounts');
5
+
6
+ // adapters/ethers5.ts
7
+ async function Ethers5Adapter(provider, signer) {
8
+ const transport = provider && "send" in provider && typeof provider.send === "function" ? (
9
+ // @ts-ignore - ethers5 provider.send is not typed
10
+ viem.custom({ request: ({ method, params }) => provider.send(method, params ?? []) })
11
+ ) : (() => {
12
+ throw new Error("Provider does not support EIP-1193 interface");
13
+ })();
14
+ const address = await signer.getAddress();
15
+ let account;
16
+ if ("privateKey" in signer && typeof signer.privateKey === "string") {
17
+ account = accounts.privateKeyToAccount(signer.privateKey);
18
+ } else if (provider && typeof provider.send === "function") {
19
+ account = address;
20
+ } else {
21
+ throw new Error("Signer does not expose a private key and no injected wallet is available.");
22
+ }
23
+ const publicClient = viem.createPublicClient({ transport });
24
+ const walletClient = viem.createWalletClient({ transport, account });
25
+ return { publicClient, walletClient };
26
+ }
27
+ async function Ethers6Adapter(provider, signer) {
28
+ const transport = provider && "send" in provider && typeof provider.send === "function" ? (
29
+ // @ts-ignore - ethers6 provider.send is not typed
30
+ viem.custom({ request: ({ method, params }) => provider.send(method, params ?? []) })
31
+ ) : (() => {
32
+ throw new Error("Provider does not support EIP-1193 interface");
33
+ })();
34
+ const address = await signer.getAddress();
35
+ let account;
36
+ if ("privateKey" in signer && typeof signer.privateKey === "string") {
37
+ account = accounts.privateKeyToAccount(signer.privateKey);
38
+ } else if (provider && typeof provider.send === "function") {
39
+ account = address;
40
+ } else {
41
+ throw new Error("Signer does not expose a private key and no injected wallet is available.");
42
+ }
43
+ const publicClient = viem.createPublicClient({ transport });
44
+ const walletClient = viem.createWalletClient({ transport, account });
45
+ return { publicClient, walletClient };
46
+ }
47
+ async function WagmiAdapter(walletClient, publicClient) {
48
+ if (!walletClient) {
49
+ throw new Error("WalletClient is required");
50
+ }
51
+ if (!publicClient) {
52
+ throw new Error("PublicClient is required");
53
+ }
54
+ return {
55
+ publicClient,
56
+ walletClient
57
+ };
58
+ }
59
+ async function HardhatSignerAdapter(signer) {
60
+ const provider = signer.provider;
61
+ if (!provider) {
62
+ throw new Error("Signer must have a provider");
63
+ }
64
+ const transport = viem.custom({
65
+ request: async ({ method, params }) => {
66
+ if ("request" in provider && typeof provider.request === "function") {
67
+ return await provider.request({ method, params });
68
+ } else if ("send" in provider && typeof provider.send === "function") {
69
+ return await provider.send(
70
+ method,
71
+ params || []
72
+ );
73
+ } else {
74
+ throw new Error("Provider does not support EIP-1193 request method");
75
+ }
76
+ }
77
+ });
78
+ const address = await signer.getAddress();
79
+ const account = address;
80
+ const publicClient = viem.createPublicClient({ transport });
81
+ const walletClient = viem.createWalletClient({ transport, account });
82
+ return { publicClient, walletClient };
83
+ }
84
+
85
+ exports.Ethers5Adapter = Ethers5Adapter;
86
+ exports.Ethers6Adapter = Ethers6Adapter;
87
+ exports.HardhatSignerAdapter = HardhatSignerAdapter;
88
+ exports.WagmiAdapter = WagmiAdapter;