-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathutils.js
More file actions
338 lines (313 loc) · 9.83 KB
/
utils.js
File metadata and controls
338 lines (313 loc) · 9.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import dotenv from 'dotenv';
import fs from 'fs';
import { ethers } from 'ethers';
import {
encryptionBitsFromFheTypeName,
FhevmHandle,
isFheTypeName,
isChecksummedAddress,
} from '../lib/internal.js';
import { FHETestAddresses } from './commands/test/fheTest.js';
export function logCLI(message, { json, verbose } = {}) {
if (json === true) {
if (verbose === true) {
process.stderr.write(message + '\n');
}
} else {
console.log(message);
}
}
export const throwError = (error, cause) => {
if (cause) {
console.error(`Error: ${error} with cause: ${cause}`);
} else {
console.error(`Error: ${error}`);
}
process.exit(1);
};
export function getEnv(envName, envFile) {
if (envName === 'MNEMONIC' || envName === 'ZAMA_FHEVM_API_KEY') {
envFile = '.env';
}
if (!envFile) {
throwError(`Missing env filename`);
}
if (!fs.existsSync(envFile)) {
throwError(`Missing env file ${envFile}`);
}
const parsedEnv = dotenv.parse(fs.readFileSync(envFile));
return process.env[envName] ?? parsedEnv[envName];
}
export function parseHandles(handles) {
const fhevmHandles = [];
for (let i = 0; i < handles.length; ++i) {
if (handles[i].indexOf(' ') >= 0) {
const list = handles[i].split(' ');
for (let j = 0; j < list.length; ++j) {
fhevmHandles.push(FhevmHandle.fromBytes32Hex(list[j]));
}
} else {
fhevmHandles.push(FhevmHandle.fromBytes32Hex(handles[i]));
}
}
return fhevmHandles;
}
export function createWallet({ mnemonic, path, basePath, index, wordlist }) {
basePath = basePath || "m/44'/60'/0'/0/";
index = index || 0;
const hdNode = ethers.HDNodeWallet.fromPhrase(
mnemonic,
undefined, // password
path || `${basePath}${index}`,
wordlist,
);
return { wallet: hdNode, address: hdNode.address };
}
export function addCommonOptions(command) {
return command
.option('--contract-address <contract address>', 'address of the contract')
.option('--user-address <user address>', 'address of the account')
.option(
'--network <testnet|devnet|mainnet>',
'network name, must be "testnet", "devnet" or "mainnet"',
)
.option('--acl <ACL contract address>', 'ACL contract address')
.option(
'--kms-verifier <KMSVerifier contract address>',
'KMSVerifier contract address',
)
.option(
'--input-verifier <InputVerifier contract address>',
'InputVerifier contract address',
)
.option(
'--gateway-input-verification <Gateway input verification contract address>',
'Gateway input verification contract address',
)
.option(
'--gateway-decryption-verification <Gateway decryption verification contract address>',
'Gateway decryption verification contract address',
)
.option('--chain <chain ID>', 'The chain ID')
.option('--gateway-chain <gateway chain ID>', 'The gateway chain ID')
.option('--rpc-url <rpc url>', 'The rpc url')
.option('--relayer-url <relayer url>', 'The relayer url')
.option('--mnemonic <word list>', 'Mnemonic word list')
.option('--clear-cache', 'Clear the FHEVM public key cache')
.option('--json', 'Ouput in JSON format')
.option('--verbose', 'Verbose output')
.option('--timeout <duration in ms>', 'Timeout in milliseconds');
}
/**
* @param {object} options - Command line options
* @returns {{
* config: {
* name: 'testnet' | 'devnet' | 'mainnet',
* walletAddress: string,
* userAddress: string,
* contractAddress: string,
* fhevmInstanceConfig: {
* aclContractAddress: string,
* kmsContractAddress: string,
* inputVerifierContractAddress: string,
* verifyingContractAddressDecryption: string,
* verifyingContractAddressInputVerification: string,
* chainId: number,
* gatewayChainId: number,
* network: string,
* relayerUrl: string,
* },
* },
* wallet: import('ethers').HDNodeWallet | undefined,
* signer: import('ethers').HDNodeWallet | undefined,
* provider: import('ethers').JsonRpcProvider,
* }}
*/
export function parseCommonOptions(options) {
const name = options?.network ?? 'devnet';
if (name !== 'testnet' && name !== 'devnet' && name !== 'mainnet') {
throwError(`Invalid network name '${name}'.`);
}
let rpcUrl = options?.rpcUrl;
if (!rpcUrl) {
rpcUrl = getEnv('RPC_URL', `.env.${name}`);
}
if (!rpcUrl) {
throwError(`Missing Rpc Url.`);
}
let relayerUrl = options?.relayerUrl;
if (!relayerUrl) {
relayerUrl = getEnv('RELAYER_URL', `.env.${name}`);
}
if (!relayerUrl) {
throwError(`Missing relayer Url.`);
}
if (!relayerUrl.endsWith('/v2')) {
relayerUrl = relayerUrl + '/v2';
}
let contractAddress = options?.contractAddress;
if (!contractAddress) {
contractAddress = getEnv('CONTRACT_ADDRESS', `.env.${name}`);
}
if (!contractAddress) {
contractAddress = FHETestAddresses[name];
}
if (!isChecksummedAddress(contractAddress)) {
throwError(`Invalid contract address '${contractAddress}'.`);
}
let userAddress = options?.userAddress;
if (userAddress && !isChecksummedAddress(userAddress)) {
userAddress = getEnv('USER_ADDRESS', `.env.${name}`);
}
let aclContractAddress = options?.acl;
if (!aclContractAddress) {
aclContractAddress = getEnv('ACL_CONTRACT_ADDRESS', `.env.${name}`);
}
if (!isChecksummedAddress(aclContractAddress)) {
throwError(`Invalid ACL address '${aclContractAddress}'.`);
}
let kmsContractAddress = options?.kmsVerifier;
if (!kmsContractAddress) {
kmsContractAddress = getEnv(
'KMS_VERIFIER_CONTRACT_ADDRESS',
`.env.${name}`,
);
}
if (!isChecksummedAddress(kmsContractAddress)) {
throwError(`Invalid KMSVerifier address '${kmsContractAddress}'.`);
}
let inputVerifierContractAddress = options?.inputVerifier;
if (!inputVerifierContractAddress) {
inputVerifierContractAddress = getEnv(
'INPUT_VERIFIER_CONTRACT_ADDRESS',
`.env.${name}`,
);
}
if (!isChecksummedAddress(inputVerifierContractAddress)) {
throwError(
`Invalid InputVerifier address '${inputVerifierContractAddress}'.`,
);
}
let verifyingContractAddressInputVerification =
options?.gatewayInputVerification;
if (!verifyingContractAddressInputVerification) {
verifyingContractAddressInputVerification = getEnv(
'INPUT_VERIFICATION_ADDRESS',
`.env.${name}`,
);
}
if (!isChecksummedAddress(kmsContractAddress)) {
throwError(`Invalid KMSVerifier address '${kmsContractAddress}'.`);
}
let verifyingContractAddressDecryption =
options?.gatewayDecryptionVerification;
if (!verifyingContractAddressDecryption) {
verifyingContractAddressDecryption = getEnv(
'DECRYPTION_ADDRESS',
`.env.${name}`,
);
}
if (!isChecksummedAddress(kmsContractAddress)) {
throwError(`Invalid KMSVerifier address '${kmsContractAddress}'.`);
}
//
let chainId = options?.chain;
if (!chainId) {
chainId = getEnv('CHAIN_ID', `.env.${name}`);
}
chainId = Number.parseInt(chainId);
if (Number.isNaN(chainId)) {
throwError(`Invalid chain ID '${chainId}'.`);
}
let gatewayChainId = options?.gatewayChain;
if (!gatewayChainId) {
gatewayChainId = getEnv('CHAIN_ID_GATEWAY', `.env.${name}`);
}
gatewayChainId = Number.parseInt(gatewayChainId);
if (Number.isNaN(gatewayChainId)) {
throwError(`Invalid gateway chain ID '${gatewayChainId}'.`);
}
const mnemonic = options?.mnemonic ?? getEnv('MNEMONIC');
const zamaFhevmApiKey =
options?.zamaFhevmApiKey ?? getEnv('ZAMA_FHEVM_API_KEY');
const provider = new ethers.JsonRpcProvider(rpcUrl);
const walletResult = mnemonic ? createWallet({ mnemonic }) : undefined;
const wallet = walletResult?.wallet;
const signer = wallet?.connect(provider);
const config = {
name: name,
walletAddress: wallet?.address,
userAddress: userAddress ?? wallet?.address,
contractAddress,
fhevmInstanceConfig: {
aclContractAddress,
kmsContractAddress,
inputVerifierContractAddress,
verifyingContractAddressDecryption,
verifyingContractAddressInputVerification,
chainId,
gatewayChainId,
network: rpcUrl,
relayerUrl,
},
};
return { config, provider, wallet, signer, zamaFhevmApiKey };
}
export function valueColumnTypeListToFheTypedValues(list) {
return list.map((str) => {
const [valueStr, fheTypeName] = str.split(':');
if (!isFheTypeName(fheTypeName)) {
throwError(`Invalid FheType name: ${fheTypeName}`);
}
let value;
if (fheTypeName === 'ebool') {
value = valueStr === 'true' ? true : false;
} else if (fheTypeName === 'eaddress') {
value = valueStr;
} else if (
fheTypeName === 'euint8' ||
fheTypeName === 'euint16' ||
fheTypeName === 'euint32'
) {
value = Number(valueStr);
} else {
value = BigInt(valueStr);
if (value <= BigInt(Number.MAX_SAFE_INTEGER)) {
value = Number(value);
}
}
return { fheType: fheTypeName, value };
});
}
export function fheTypedValuesToBuilderFunctionWithArg(fheTypedValues) {
return fheTypedValues.map((pair) => {
const { value, fheType } = pair;
if (!isFheTypeName(fheType)) {
throwError(`Invalid FheType name: ${fheType}`);
}
let funcName;
if (fheType === 'ebool') {
funcName = 'addBool';
} else if (fheType === 'eaddress') {
funcName = 'addAddress';
} else {
const bits = encryptionBitsFromFheTypeName(fheType);
funcName = `add${bits}`;
}
return { funcName, arg: value };
});
}
export function jsonParseFheTypedValues(text) {
return JSON.parse(text, (key, value) => {
if (value === 'true' || value === true) {
return true;
}
if (value === 'false' || value === true) {
return false;
}
if (typeof value === 'string' && value.startsWith('0x')) {
return value;
}
return BigInt(value);
});
}