-
Notifications
You must be signed in to change notification settings - Fork 597
Expand file tree
/
Copy pathaztec.ts
More file actions
297 lines (270 loc) · 10.6 KB
/
aztec.ts
File metadata and controls
297 lines (270 loc) · 10.6 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
import { EthAddress, type PXE } from '@aztec/aztec.js';
import {
type ContractArtifact,
type FunctionAbi,
FunctionType,
getAllFunctionAbis,
loadContractArtifact,
} from '@aztec/aztec.js/abi';
import {
type DeployL1ContractsReturnType,
type L1ContractsConfig,
type Operator,
RollupContract,
} from '@aztec/ethereum';
import { SecretValue } from '@aztec/foundation/config';
import { Fr } from '@aztec/foundation/fields';
import type { LogFn, Logger } from '@aztec/foundation/log';
import type { NoirPackageConfig } from '@aztec/foundation/noir';
import { protocolContractTreeRoot } from '@aztec/protocol-contracts';
import TOML from '@iarna/toml';
import { readFile } from 'fs/promises';
import { gtr, ltr, satisfies, valid } from 'semver';
import { encodeArgs } from './encoding.js';
/**
* Helper to get an ABI function or throw error if it doesn't exist.
* @param artifact - Contract's build artifact in JSON format.
* @param fnName - Function name to be found.
* @returns The function's ABI.
*/
export function getFunctionAbi(artifact: ContractArtifact, fnName: string): FunctionAbi {
const fn = getAllFunctionAbis(artifact).find(({ name }) => name === fnName);
if (!fn) {
throw Error(`Function ${fnName} not found in contract ABI.`);
}
return fn;
}
/**
* Function to execute the 'deployRollupContracts' command.
* @param rpcUrls - The RPC URL of the ethereum node.
* @param chainId - The chain ID of the L1 host.
* @param privateKey - The private key to be used in contract deployment.
* @param mnemonic - The mnemonic to be used in contract deployment.
*/
export async function deployAztecContracts(
rpcUrls: string[],
chainId: number,
privateKey: string | undefined,
mnemonic: string,
mnemonicIndex: number,
salt: number | undefined,
initialValidators: Operator[],
genesisArchiveRoot: Fr,
feeJuicePortalInitialBalance: bigint,
acceleratedTestDeployments: boolean,
config: L1ContractsConfig,
existingToken: EthAddress | undefined,
realVerifier: boolean,
createVerificationJson: string | false,
debugLogger: Logger,
): Promise<DeployL1ContractsReturnType> {
const { createEthereumChain, deployL1Contracts } = await import('@aztec/ethereum');
const { mnemonicToAccount, privateKeyToAccount } = await import('viem/accounts');
const account = !privateKey
? mnemonicToAccount(mnemonic!, { addressIndex: mnemonicIndex })
: privateKeyToAccount(addLeadingHex(privateKey));
const chain = createEthereumChain(rpcUrls, chainId);
const { getVKTreeRoot } = await import('@aztec/noir-protocol-circuits-types/vk-tree');
const result = await deployL1Contracts(
chain.rpcUrls,
account,
chain.chainInfo,
debugLogger,
{
vkTreeRoot: getVKTreeRoot(),
protocolContractTreeRoot,
genesisArchiveRoot,
salt,
initialValidators,
acceleratedTestDeployments,
feeJuicePortalInitialBalance,
realVerifier,
existingTokenAddress: existingToken,
...config,
},
config,
createVerificationJson,
);
return result;
}
export async function deployNewRollupContracts(
registryAddress: EthAddress,
rpcUrls: string[],
chainId: number,
privateKey: string | undefined,
mnemonic: string,
mnemonicIndex: number,
salt: number | undefined,
initialValidators: Operator[],
genesisArchiveRoot: Fr,
feeJuicePortalInitialBalance: bigint,
config: L1ContractsConfig,
realVerifier: boolean,
logger: Logger,
): Promise<{ rollup: RollupContract; slashFactoryAddress: EthAddress }> {
const { createEthereumChain, deployRollupForUpgrade, createExtendedL1Client } = await import('@aztec/ethereum');
const { mnemonicToAccount, privateKeyToAccount } = await import('viem/accounts');
const { getVKTreeRoot } = await import('@aztec/noir-protocol-circuits-types/vk-tree');
const account = !privateKey
? mnemonicToAccount(mnemonic!, { addressIndex: mnemonicIndex })
: privateKeyToAccount(addLeadingHex(privateKey));
const chain = createEthereumChain(rpcUrls, chainId);
const client = createExtendedL1Client(rpcUrls, account, chain.chainInfo, undefined, mnemonicIndex);
if (!initialValidators || initialValidators.length === 0) {
// initialize the new rollup with Amin's validator address.
const aminAddressString = '0x3b218d0F26d15B36C715cB06c949210a0d630637';
const amin = EthAddress.fromString(aminAddressString);
initialValidators = [
{
attester: amin,
withdrawer: amin,
// No secrets here. The actual keys are not currently used.
bn254SecretKey: new SecretValue(Fr.fromHexString(aminAddressString).toBigInt()),
},
];
logger.info('Initializing new rollup with old attesters', { initialValidators });
}
const { rollup, slashFactoryAddress } = await deployRollupForUpgrade(
client,
{
salt,
vkTreeRoot: getVKTreeRoot(),
protocolContractTreeRoot,
genesisArchiveRoot,
initialValidators,
feeJuicePortalInitialBalance,
realVerifier,
...config,
},
registryAddress,
logger,
config,
);
return { rollup, slashFactoryAddress };
}
/**
* Gets all contracts available in \@aztec/noir-contracts.js.
* @returns The contract names.
*/
export async function getExampleContractNames(): Promise<string[]> {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - Importing noir-contracts.js even in devDeps results in a circular dependency error. Need to ignore because this line doesn't cause an error in a dev environment
const { ContractNames } = await import('@aztec/noir-contracts.js');
return ContractNames;
}
/**
* Reads a file and converts it to an Aztec Contract ABI.
* @param fileDir - The directory of the compiled contract ABI.
* @returns The parsed contract artifact.
*/
export async function getContractArtifact(fileDir: string, log: LogFn) {
// first check if it's a noir-contracts example
const allNames = await getExampleContractNames();
const contractName = fileDir.replace(/Contract(Artifact)?$/, '');
if (allNames.includes(contractName)) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - Importing noir-contracts.js even in devDeps results in a circular dependency error. Need to ignore because this line doesn't cause an error in a dev environment
const imported = await import(`@aztec/noir-contracts.js/${contractName}`);
const artifact = imported[`${contractName}ContractArtifact`] as ContractArtifact;
if (!artifact) {
throw Error(`Could not import ${contractName}ContractArtifact from @aztec/noir-contracts.js/${contractName}`);
}
return artifact;
}
let contents: string;
try {
contents = await readFile(fileDir, 'utf8');
} catch {
throw Error(`Contract ${fileDir} not found`);
}
try {
return loadContractArtifact(JSON.parse(contents));
} catch (err) {
log('Invalid file used. Please try again.');
throw err;
}
}
/**
* Performs necessary checks, conversions & operations to call a contract fn from the CLI.
* @param contractFile - Directory of the compiled contract ABI.
* @param functionName - Name of the function to be called.
* @param _functionArgs - Arguments to call the function with.
* @param log - Logger instance that will output to the CLI
* @returns Formatted contract address, function arguments and caller's aztec address.
*/
export async function prepTx(contractFile: string, functionName: string, _functionArgs: string[], log: LogFn) {
const contractArtifact = await getContractArtifact(contractFile, log);
const functionArtifact = getFunctionAbi(contractArtifact, functionName);
const functionArgs = encodeArgs(_functionArgs, functionArtifact.parameters);
const isPrivate = functionArtifact.functionType === FunctionType.PRIVATE;
return { functionArgs, contractArtifact, isPrivate };
}
/**
* Removes the leading 0x from a hex string. If no leading 0x is found the string is returned unchanged.
* @param hex - A hex string
* @returns A new string with leading 0x removed
*/
export const stripLeadingHex = (hex: string): string => {
if (hex.length > 2 && hex.startsWith('0x')) {
return hex.substring(2);
}
return hex;
};
/**
* Adds a leading 0x to a hex string. If a leading 0x is already present the string is returned unchanged.
* @param hex - A hex string
* @returns A new string with leading 0x added
*/
export const addLeadingHex = (hex: string): `0x${string}` => {
if (hex.length > 2 && hex.startsWith('0x')) {
return hex as `0x${string}`;
}
return `0x${hex}`;
};
/*
* Pretty prints Nargo.toml contents to a string
* @param config - Nargo.toml contents
* @returns The Nargo.toml contents as a string
*/
export function prettyPrintNargoToml(config: NoirPackageConfig): string {
const withoutDependencies = Object.fromEntries(Object.entries(config).filter(([key]) => key !== 'dependencies'));
const partialToml = TOML.stringify(withoutDependencies);
const dependenciesToml = Object.entries(config.dependencies).map(([name, dep]) => {
const depToml = TOML.stringify.value(dep);
return `${name} = ${depToml}`;
});
return partialToml + '\n[dependencies]\n' + dependenciesToml.join('\n') + '\n';
}
/** Mismatch between server and client versions. */
class VersionMismatchError extends Error {}
/**
* Checks that Private eXecution Environment (PXE) version matches the expected one by this CLI. Throws if not.
* @param pxe - PXE client.
* @param expectedVersionRange - Expected version by CLI.
*/
export async function checkServerVersion(pxe: PXE, expectedVersionRange: string) {
const serverName = 'Aztec Node';
const { nodeVersion } = await pxe.getNodeInfo();
if (!nodeVersion) {
throw new VersionMismatchError(`Couldn't determine ${serverName} version. You may run into issues.`);
}
if (!nodeVersion || !valid(nodeVersion)) {
throw new VersionMismatchError(
`Missing or invalid version identifier for ${serverName} (${nodeVersion ?? 'empty'}).`,
);
} else if (!satisfies(nodeVersion, expectedVersionRange)) {
if (gtr(nodeVersion, expectedVersionRange)) {
throw new VersionMismatchError(
`${serverName} is running version ${nodeVersion} which is newer than the expected by this CLI (${expectedVersionRange}). Consider upgrading your CLI to a newer version.`,
);
} else if (ltr(nodeVersion, expectedVersionRange)) {
throw new VersionMismatchError(
`${serverName} is running version ${nodeVersion} which is older than the expected by this CLI (${expectedVersionRange}). Consider upgrading your ${serverName} to a newer version.`,
);
} else {
throw new VersionMismatchError(
`${serverName} is running version ${nodeVersion} which does not match the expected by this CLI (${expectedVersionRange}).`,
);
}
}
}