@aztec/aztec 0.0.1-commit.f146247c → 0.0.1-commit.f224bb98b

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/dest/bin/index.js +7 -3
  2. package/dest/cli/admin_api_key_store.d.ts +45 -0
  3. package/dest/cli/admin_api_key_store.d.ts.map +1 -0
  4. package/dest/cli/admin_api_key_store.js +98 -0
  5. package/dest/cli/aztec_start_action.d.ts +1 -1
  6. package/dest/cli/aztec_start_action.d.ts.map +1 -1
  7. package/dest/cli/aztec_start_action.js +51 -13
  8. package/dest/cli/aztec_start_options.d.ts +1 -1
  9. package/dest/cli/aztec_start_options.d.ts.map +1 -1
  10. package/dest/cli/aztec_start_options.js +25 -9
  11. package/dest/cli/cli.d.ts +1 -1
  12. package/dest/cli/cli.d.ts.map +1 -1
  13. package/dest/cli/cli.js +3 -4
  14. package/dest/cli/cmds/compile.d.ts +4 -0
  15. package/dest/cli/cmds/compile.d.ts.map +1 -0
  16. package/dest/cli/cmds/compile.js +165 -0
  17. package/dest/cli/cmds/profile.d.ts +4 -0
  18. package/dest/cli/cmds/profile.d.ts.map +1 -0
  19. package/dest/cli/cmds/profile.js +8 -0
  20. package/dest/cli/cmds/profile_flamegraph.d.ts +4 -0
  21. package/dest/cli/cmds/profile_flamegraph.d.ts.map +1 -0
  22. package/dest/cli/cmds/profile_flamegraph.js +51 -0
  23. package/dest/cli/cmds/profile_gates.d.ts +4 -0
  24. package/dest/cli/cmds/profile_gates.d.ts.map +1 -0
  25. package/dest/cli/cmds/profile_gates.js +57 -0
  26. package/dest/cli/cmds/profile_utils.d.ts +18 -0
  27. package/dest/cli/cmds/profile_utils.d.ts.map +1 -0
  28. package/dest/cli/cmds/profile_utils.js +50 -0
  29. package/dest/cli/cmds/standby.d.ts +27 -0
  30. package/dest/cli/cmds/standby.d.ts.map +1 -0
  31. package/dest/cli/cmds/standby.js +78 -0
  32. package/dest/cli/cmds/start_archiver.d.ts +2 -2
  33. package/dest/cli/cmds/start_archiver.d.ts.map +1 -1
  34. package/dest/cli/cmds/start_archiver.js +1 -1
  35. package/dest/cli/cmds/start_bot.d.ts +3 -3
  36. package/dest/cli/cmds/start_bot.d.ts.map +1 -1
  37. package/dest/cli/cmds/start_bot.js +9 -5
  38. package/dest/cli/cmds/start_node.d.ts +3 -2
  39. package/dest/cli/cmds/start_node.d.ts.map +1 -1
  40. package/dest/cli/cmds/start_node.js +77 -27
  41. package/dest/cli/cmds/start_prover_agent.js +2 -2
  42. package/dest/cli/cmds/start_prover_broker.d.ts +1 -1
  43. package/dest/cli/cmds/start_prover_broker.d.ts.map +1 -1
  44. package/dest/cli/cmds/start_prover_broker.js +8 -8
  45. package/dest/cli/cmds/utils/artifacts.d.ts +21 -0
  46. package/dest/cli/cmds/utils/artifacts.d.ts.map +1 -0
  47. package/dest/cli/cmds/utils/artifacts.js +24 -0
  48. package/dest/cli/cmds/utils/needs_recompile.d.ts +10 -0
  49. package/dest/cli/cmds/utils/needs_recompile.d.ts.map +1 -0
  50. package/dest/cli/cmds/utils/needs_recompile.js +124 -0
  51. package/dest/cli/cmds/utils/spawn.d.ts +3 -0
  52. package/dest/cli/cmds/utils/spawn.d.ts.map +1 -0
  53. package/dest/cli/cmds/utils/spawn.js +16 -0
  54. package/dest/cli/util.d.ts +7 -18
  55. package/dest/cli/util.d.ts.map +1 -1
  56. package/dest/cli/util.js +50 -86
  57. package/dest/examples/token.js +6 -6
  58. package/dest/local-network/banana_fpc.js +1 -1
  59. package/dest/local-network/local-network.d.ts +4 -2
  60. package/dest/local-network/local-network.d.ts.map +1 -1
  61. package/dest/local-network/local-network.js +50 -18
  62. package/dest/testing/anvil_test_watcher.d.ts +9 -1
  63. package/dest/testing/anvil_test_watcher.d.ts.map +1 -1
  64. package/dest/testing/anvil_test_watcher.js +52 -15
  65. package/dest/testing/index.d.ts +2 -1
  66. package/dest/testing/index.d.ts.map +1 -1
  67. package/dest/testing/index.js +1 -0
  68. package/dest/testing/token_allowed_setup.d.ts +7 -0
  69. package/dest/testing/token_allowed_setup.d.ts.map +1 -0
  70. package/dest/testing/token_allowed_setup.js +20 -0
  71. package/package.json +35 -34
  72. package/scripts/add_crate.sh +102 -0
  73. package/scripts/aztec.sh +11 -5
  74. package/scripts/init.sh +23 -19
  75. package/scripts/new.sh +48 -24
  76. package/scripts/setup_workspace.sh +68 -0
  77. package/src/bin/index.ts +7 -3
  78. package/src/cli/admin_api_key_store.ts +128 -0
  79. package/src/cli/aztec_start_action.ts +55 -9
  80. package/src/cli/aztec_start_options.ts +27 -8
  81. package/src/cli/cli.ts +3 -4
  82. package/src/cli/cmds/compile.ts +190 -0
  83. package/src/cli/cmds/profile.ts +25 -0
  84. package/src/cli/cmds/profile_flamegraph.ts +63 -0
  85. package/src/cli/cmds/profile_gates.ts +67 -0
  86. package/src/cli/cmds/profile_utils.ts +58 -0
  87. package/src/cli/cmds/standby.ts +111 -0
  88. package/src/cli/cmds/start_archiver.ts +1 -1
  89. package/src/cli/cmds/start_bot.ts +8 -5
  90. package/src/cli/cmds/start_node.ts +76 -33
  91. package/src/cli/cmds/start_prover_agent.ts +2 -2
  92. package/src/cli/cmds/start_prover_broker.ts +12 -15
  93. package/src/cli/cmds/utils/artifacts.ts +44 -0
  94. package/src/cli/cmds/utils/needs_recompile.ts +139 -0
  95. package/src/cli/cmds/utils/spawn.ts +16 -0
  96. package/src/cli/util.ts +57 -95
  97. package/src/examples/token.ts +8 -6
  98. package/src/local-network/banana_fpc.ts +1 -1
  99. package/src/local-network/local-network.ts +54 -17
  100. package/src/testing/anvil_test_watcher.ts +59 -15
  101. package/src/testing/index.ts +1 -0
  102. package/src/testing/token_allowed_setup.ts +19 -0
  103. package/dest/cli/cmds/start_prover_node.d.ts +0 -7
  104. package/dest/cli/cmds/start_prover_node.d.ts.map +0 -1
  105. package/dest/cli/cmds/start_prover_node.js +0 -108
  106. package/dest/cli/release_version.d.ts +0 -2
  107. package/dest/cli/release_version.d.ts.map +0 -1
  108. package/dest/cli/release_version.js +0 -14
  109. package/scripts/compile.sh +0 -44
  110. package/scripts/extract_function.js +0 -47
  111. package/scripts/flamegraph.sh +0 -59
  112. package/scripts/setup_project.sh +0 -31
  113. package/src/cli/cmds/start_prover_node.ts +0 -124
  114. package/src/cli/release_version.ts +0 -21
@@ -1,30 +1,34 @@
1
- import { getInitialTestAccountsData } from '@aztec/accounts/testing';
2
1
  import { type AztecNodeConfig, aztecNodeConfigMappings, getConfigEnvVars } from '@aztec/aztec-node';
3
2
  import { Fr } from '@aztec/aztec.js/fields';
4
- import { getSponsoredFPCAddress } from '@aztec/cli/cli-utils';
5
3
  import { getL1Config } from '@aztec/cli/config';
6
4
  import { getPublicClient } from '@aztec/ethereum/client';
7
- import { SecretValue } from '@aztec/foundation/config';
5
+ import { getGenesisStateConfigEnvVars } from '@aztec/ethereum/config';
6
+ import { type NetworkNames, SecretValue } from '@aztec/foundation/config';
8
7
  import type { NamespacedApiHandlers } from '@aztec/foundation/json-rpc/server';
8
+ import { Agent, makeUndiciFetch } from '@aztec/foundation/json-rpc/undici';
9
9
  import type { LogFn } from '@aztec/foundation/log';
10
+ import { ProvingJobConsumerSchema, createProvingJobBrokerClient } from '@aztec/prover-client/broker';
10
11
  import { type CliPXEOptions, type PXEConfig, allPxeConfigMappings } from '@aztec/pxe/config';
11
12
  import { AztecNodeAdminApiSchema, AztecNodeApiSchema } from '@aztec/stdlib/interfaces/client';
12
- import { P2PApiSchema } from '@aztec/stdlib/interfaces/server';
13
+ import { P2PApiSchema, ProverNodeApiSchema, type ProvingJobBroker } from '@aztec/stdlib/interfaces/server';
13
14
  import {
14
15
  type TelemetryClientConfig,
15
16
  initTelemetryClient,
17
+ makeTracedFetch,
16
18
  telemetryClientConfigMappings,
17
19
  } from '@aztec/telemetry-client';
18
- import { TestWallet } from '@aztec/test-wallet/server';
19
- import { getGenesisValues } from '@aztec/world-state/testing';
20
+ import { EmbeddedWallet } from '@aztec/wallets/embedded';
20
21
 
21
22
  import { createAztecNode } from '../../local-network/index.js';
22
23
  import {
23
24
  extractNamespacedOptions,
24
25
  extractRelevantOptions,
25
26
  preloadCrsDataForVerifying,
26
- setupUpdateMonitor,
27
+ setupVersionChecker,
27
28
  } from '../util.js';
29
+ import { getVersions } from '../versioning.js';
30
+ import { computeExpectedGenesisRoot, waitForCompatibleRollup } from './standby.js';
31
+ import { startProverBroker } from './start_prover_broker.js';
28
32
 
29
33
  export async function startNode(
30
34
  options: any,
@@ -32,6 +36,7 @@ export async function startNode(
32
36
  services: NamespacedApiHandlers,
33
37
  adminServices: NamespacedApiHandlers,
34
38
  userLog: LogFn,
39
+ networkName: NetworkNames,
35
40
  ): Promise<{ config: AztecNodeConfig }> {
36
41
  // All options set from environment variables
37
42
  const configFromEnvVars = getConfigEnvVars();
@@ -45,22 +50,38 @@ export async function startNode(
45
50
  ...relevantOptions,
46
51
  };
47
52
 
53
+ // Prover node configuration and broker setup
54
+ // REFACTOR: Move the broker setup out of here and into the prover-node factory
55
+ let broker: ProvingJobBroker | undefined = undefined;
48
56
  if (options.proverNode) {
49
- userLog(`Running a Prover Node within a Node is not yet supported`);
50
- process.exit(1);
57
+ nodeConfig.enableProverNode = true;
58
+ if (nodeConfig.proverAgentCount === 0) {
59
+ userLog(
60
+ `Running prover node without local prover agent. Connect prover agents or pass --proverAgent.proverAgentCount`,
61
+ );
62
+ }
63
+ if (nodeConfig.proverBrokerUrl) {
64
+ // at 1TPS we'd enqueue ~1k chonk verifier proofs and ~1k AVM proofs immediately
65
+ // set a lower connection limit such that we don't overload the server
66
+ // Keep retrying up to 30s
67
+ const fetch = makeTracedFetch(
68
+ [1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3],
69
+ false,
70
+ makeUndiciFetch(new Agent({ connections: 100 })),
71
+ );
72
+ broker = createProvingJobBrokerClient(nodeConfig.proverBrokerUrl, getVersions(nodeConfig), fetch);
73
+ } else if (options.proverBroker) {
74
+ ({ broker } = await startProverBroker(options, signalHandlers, services, userLog));
75
+ } else {
76
+ userLog(`--prover-broker-url or --prover-broker is required to start a Prover Node`);
77
+ process.exit(1);
78
+ }
51
79
  }
52
80
 
53
81
  await preloadCrsDataForVerifying(nodeConfig, userLog);
54
82
 
55
- const testAccounts = nodeConfig.testAccounts ? (await getInitialTestAccountsData()).map(a => a.address) : [];
56
- const sponsoredFPCAccounts = nodeConfig.sponsoredFPC ? [await getSponsoredFPCAddress()] : [];
57
- const initialFundedAccounts = testAccounts.concat(sponsoredFPCAccounts);
58
-
59
- userLog(`Initial funded accounts: ${initialFundedAccounts.map(a => a.toString()).join(', ')}`);
60
-
61
- const { genesisArchiveRoot, prefilledPublicData } = await getGenesisValues(initialFundedAccounts);
62
-
63
- userLog(`Genesis archive root: ${genesisArchiveRoot.toString()}`);
83
+ const genesisConfig = getGenesisStateConfigEnvVars();
84
+ const { genesisArchiveRoot, prefilledPublicData } = await computeExpectedGenesisRoot(genesisConfig, userLog);
64
85
 
65
86
  const followsCanonicalRollup =
66
87
  typeof nodeConfig.rollupVersion !== 'number' || (nodeConfig.rollupVersion as unknown as string) === 'canonical';
@@ -68,6 +89,11 @@ export async function startNode(
68
89
  if (!nodeConfig.l1Contracts.registryAddress || nodeConfig.l1Contracts.registryAddress.isZero()) {
69
90
  throw new Error('L1 registry address is required to start Aztec Node');
70
91
  }
92
+
93
+ // Wait for a compatible rollup before proceeding with full L1 config fetch.
94
+ // This prevents crashes when the canonical rollup hasn't been upgraded yet.
95
+ await waitForCompatibleRollup(nodeConfig, genesisArchiveRoot, options.port, userLog);
96
+
71
97
  const { addresses, config } = await getL1Config(
72
98
  nodeConfig.l1Contracts.registryAddress,
73
99
  nodeConfig.l1RpcUrls,
@@ -101,12 +127,17 @@ export async function startNode(
101
127
  ...extractNamespacedOptions(options, 'sequencer'),
102
128
  };
103
129
  // If no publisher private keys have been given, use the first validator key
104
- if (sequencerConfig.publisherPrivateKeys === undefined || !sequencerConfig.publisherPrivateKeys.length) {
130
+ if (
131
+ sequencerConfig.sequencerPublisherPrivateKeys === undefined ||
132
+ !sequencerConfig.sequencerPublisherPrivateKeys.length
133
+ ) {
105
134
  if (sequencerConfig.validatorPrivateKeys?.getValue().length) {
106
- sequencerConfig.publisherPrivateKeys = [new SecretValue(sequencerConfig.validatorPrivateKeys.getValue()[0])];
135
+ sequencerConfig.sequencerPublisherPrivateKeys = [
136
+ new SecretValue(sequencerConfig.validatorPrivateKeys.getValue()[0]),
137
+ ];
107
138
  }
108
139
  }
109
- nodeConfig.publisherPrivateKeys = sequencerConfig.publisherPrivateKeys;
140
+ nodeConfig.sequencerPublisherPrivateKeys = sequencerConfig.sequencerPublisherPrivateKeys;
110
141
  }
111
142
 
112
143
  if (nodeConfig.p2pEnabled) {
@@ -120,13 +151,22 @@ export async function startNode(
120
151
  const telemetry = await initTelemetryClient(telemetryConfig);
121
152
 
122
153
  // Create and start Aztec Node
123
- const node = await createAztecNode(nodeConfig, { telemetry }, { prefilledPublicData });
154
+ const node = await createAztecNode(nodeConfig, { telemetry, proverBroker: broker }, { prefilledPublicData });
124
155
 
125
156
  // Add node and p2p to services list
126
157
  services.node = [node, AztecNodeApiSchema];
127
158
  services.p2p = [node.getP2P(), P2PApiSchema];
128
159
  adminServices.nodeAdmin = [node, AztecNodeAdminApiSchema];
129
160
 
161
+ // Register prover-node services if the prover node subsystem is running
162
+ const proverNode = node.getProverNode();
163
+ if (proverNode) {
164
+ services.prover = [proverNode, ProverNodeApiSchema];
165
+ if (!nodeConfig.proverBrokerUrl) {
166
+ services.provingJobSource = [proverNode.getProver().getProvingJobSource(), ProvingJobConsumerSchema];
167
+ }
168
+ }
169
+
130
170
  // Add node stop function to signal handlers
131
171
  signalHandlers.push(node.stop.bind(node));
132
172
 
@@ -135,21 +175,24 @@ export async function startNode(
135
175
  const { addBot } = await import('./start_bot.js');
136
176
 
137
177
  const pxeConfig = extractRelevantOptions<PXEConfig & CliPXEOptions>(options, allPxeConfigMappings, 'pxe');
138
- const wallet = await TestWallet.create(node, pxeConfig);
178
+ const wallet = await EmbeddedWallet.create(node, { pxeConfig });
139
179
 
140
180
  await addBot(options, signalHandlers, services, wallet, node, telemetry, undefined);
141
181
  }
142
182
 
143
- if (nodeConfig.autoUpdate !== 'disabled' && nodeConfig.autoUpdateUrl) {
144
- await setupUpdateMonitor(
145
- nodeConfig.autoUpdate,
146
- new URL(nodeConfig.autoUpdateUrl),
147
- followsCanonicalRollup,
148
- getPublicClient(nodeConfig!),
149
- nodeConfig.l1Contracts.registryAddress,
150
- signalHandlers,
151
- async config => node.setConfig((await AztecNodeAdminApiSchema.setConfig.parameters().parseAsync([config]))[0]),
152
- );
183
+ if (nodeConfig.enableVersionCheck && networkName !== 'local') {
184
+ const cacheDir = process.env.DATA_DIRECTORY ? `${process.env.DATA_DIRECTORY}/cache` : undefined;
185
+ try {
186
+ await setupVersionChecker(
187
+ networkName,
188
+ followsCanonicalRollup,
189
+ getPublicClient(nodeConfig!),
190
+ signalHandlers,
191
+ cacheDir,
192
+ );
193
+ } catch {
194
+ /* no-op */
195
+ }
153
196
  }
154
197
 
155
198
  return { config: nodeConfig };
@@ -4,9 +4,9 @@ import { Agent, makeUndiciFetch } from '@aztec/foundation/json-rpc/undici';
4
4
  import type { LogFn } from '@aztec/foundation/log';
5
5
  import { buildServerCircuitProver } from '@aztec/prover-client';
6
6
  import {
7
- InlineProofStore,
8
7
  type ProverAgentConfig,
9
8
  ProvingAgent,
9
+ createProofStore,
10
10
  createProvingJobBrokerClient,
11
11
  proverAgentConfigMappings,
12
12
  } from '@aztec/prover-client/broker';
@@ -55,7 +55,7 @@ export async function startProverAgent(
55
55
 
56
56
  const telemetry = await initTelemetryClient(extractRelevantOptions(options, telemetryClientConfigMappings, 'tel'));
57
57
  const prover = await buildServerCircuitProver(config, telemetry);
58
- const proofStore = new InlineProofStore();
58
+ const proofStore = await createProofStore(config.proofStore);
59
59
  const agents = times(
60
60
  config.proverAgentCount,
61
61
  () => new ProvingAgent(broker, proofStore, prover, config.proverAgentProofTypes, config.proverAgentPollIntervalMs),
@@ -1,10 +1,11 @@
1
1
  import { getL1Config } from '@aztec/cli/config';
2
- import { getPublicClient } from '@aztec/ethereum/client';
2
+ import { getGenesisStateConfigEnvVars } from '@aztec/ethereum/config';
3
3
  import type { NamespacedApiHandlers } from '@aztec/foundation/json-rpc/server';
4
4
  import type { LogFn } from '@aztec/foundation/log';
5
5
  import {
6
6
  type ProverBrokerConfig,
7
7
  ProvingJobBrokerSchema,
8
+ ProvingJobBrokerSchemaWithDebug,
8
9
  createAndStartProvingBroker,
9
10
  proverBrokerConfigMappings,
10
11
  } from '@aztec/prover-client/broker';
@@ -12,7 +13,8 @@ import { getProverNodeBrokerConfigFromEnv } from '@aztec/prover-node';
12
13
  import type { ProvingJobBroker } from '@aztec/stdlib/interfaces/server';
13
14
  import { getConfigEnvVars as getTelemetryClientConfig, initTelemetryClient } from '@aztec/telemetry-client';
14
15
 
15
- import { extractRelevantOptions, setupUpdateMonitor } from '../util.js';
16
+ import { extractRelevantOptions } from '../util.js';
17
+ import { computeExpectedGenesisRoot, waitForCompatibleRollup } from './standby.js';
16
18
 
17
19
  export async function startProverBroker(
18
20
  options: any,
@@ -34,7 +36,10 @@ export async function startProverBroker(
34
36
  throw new Error('L1 registry address is required to start Aztec Node without --deploy-aztec-contracts option');
35
37
  }
36
38
 
37
- const followsCanonicalRollup = typeof config.rollupVersion !== 'number';
39
+ const genesisConfig = getGenesisStateConfigEnvVars();
40
+ const { genesisArchiveRoot } = await computeExpectedGenesisRoot(genesisConfig, userLog);
41
+ await waitForCompatibleRollup(config, genesisArchiveRoot, options.port, userLog);
42
+
38
43
  const { addresses, config: rollupConfig } = await getL1Config(
39
44
  config.l1Contracts.registryAddress,
40
45
  config.l1RpcUrls,
@@ -48,18 +53,10 @@ export async function startProverBroker(
48
53
  const client = await initTelemetryClient(getTelemetryClientConfig());
49
54
  const broker = await createAndStartProvingBroker(config, client);
50
55
 
51
- if (options.autoUpdate !== 'disabled' && options.autoUpdateUrl) {
52
- await setupUpdateMonitor(
53
- options.autoUpdate,
54
- new URL(options.autoUpdateUrl),
55
- followsCanonicalRollup,
56
- getPublicClient(config),
57
- config.l1Contracts.registryAddress,
58
- signalHandlers,
59
- );
60
- }
61
-
62
- services.proverBroker = [broker, ProvingJobBrokerSchema];
56
+ services.proverBroker = [
57
+ broker,
58
+ config.proverBrokerDebugReplayEnabled ? ProvingJobBrokerSchemaWithDebug : ProvingJobBrokerSchema,
59
+ ];
63
60
  signalHandlers.push(() => broker.stop());
64
61
 
65
62
  return { broker, config };
@@ -0,0 +1,44 @@
1
+ import { readFile, readdir } from 'fs/promises';
2
+ import { join } from 'path';
3
+
4
+ export interface CompiledArtifact {
5
+ noir_version: string;
6
+ file_map: unknown;
7
+ functions: ContractFunction[];
8
+ bytecode?: string;
9
+ }
10
+
11
+ export interface ContractFunction {
12
+ name: string;
13
+ abi: unknown;
14
+ bytecode: string;
15
+ debug_symbols: unknown;
16
+ is_unconstrained?: boolean;
17
+ }
18
+
19
+ export interface ArtifactFile {
20
+ name: string;
21
+ filePath: string;
22
+ content: CompiledArtifact;
23
+ }
24
+
25
+ /** Reads all JSON artifact files from a target directory and returns their parsed contents. */
26
+ export async function readArtifactFiles(targetDir: string): Promise<ArtifactFile[]> {
27
+ let entries: string[];
28
+ try {
29
+ entries = (await readdir(targetDir)).filter(f => f.endsWith('.json'));
30
+ } catch (err: any) {
31
+ if (err?.code === 'ENOENT') {
32
+ throw new Error(`Target directory '${targetDir}' does not exist. Compile first with 'aztec compile'.`);
33
+ }
34
+ throw err;
35
+ }
36
+
37
+ const artifacts: ArtifactFile[] = [];
38
+ for (const file of entries) {
39
+ const filePath = join(targetDir, file);
40
+ const content = JSON.parse(await readFile(filePath, 'utf-8')) as CompiledArtifact;
41
+ artifacts.push({ name: file.replace('.json', ''), filePath, content });
42
+ }
43
+ return artifacts;
44
+ }
@@ -0,0 +1,139 @@
1
+ import TOML from '@iarna/toml';
2
+ import { readFile, readdir, stat } from 'fs/promises';
3
+ import { join, resolve } from 'path';
4
+
5
+ /**
6
+ * Returns true if recompilation is needed: either no artifacts exist in target/ or any .nr or Nargo.toml source file
7
+ * (including path-based dependencies) is newer than the oldest artifact. We compare against the oldest artifact so
8
+ * that a source change between the oldest and newest compilation (e.g. in a multi-contract workspace) still triggers
9
+ * a recompile.
10
+ *
11
+ * Note: The above implies that if there is a random json file in the target dir we would be always recompiling.
12
+ */
13
+ export async function needsRecompile(): Promise<boolean> {
14
+ const oldestArtifactMs = await getOldestArtifactModificationTime('target');
15
+ if (oldestArtifactMs === undefined) {
16
+ return true;
17
+ }
18
+
19
+ const crateDirs = await collectCrateDirs('.');
20
+ return hasNewerSourceFile(crateDirs, oldestArtifactMs);
21
+ }
22
+
23
+ /**
24
+ * Returns the last modification time (timestamp in ms) of the oldest .json artifact in targetDir, or undefined if
25
+ * none exist.
26
+ */
27
+ async function getOldestArtifactModificationTime(targetDir: string): Promise<number | undefined> {
28
+ let entries: string[];
29
+ try {
30
+ entries = (await readdir(targetDir)).filter(f => f.endsWith('.json'));
31
+ } catch (err: any) {
32
+ if (err?.code === 'ENOENT') {
33
+ return undefined;
34
+ }
35
+ throw err;
36
+ }
37
+
38
+ if (entries.length === 0) {
39
+ return undefined;
40
+ }
41
+
42
+ let oldest = Infinity;
43
+ for (const entry of entries) {
44
+ const s = await stat(join(targetDir, entry));
45
+ if (s.mtimeMs < oldest) {
46
+ oldest = s.mtimeMs;
47
+ }
48
+ }
49
+ return oldest;
50
+ }
51
+
52
+ /**
53
+ * Recursively collects crate directories starting from startCrateDir by following path-based dependencies declared in
54
+ * Nargo.toml files. Git-based deps are ignored (they only change when Nargo.toml itself is modified since the deps are
55
+ * tagged).
56
+ */
57
+ async function collectCrateDirs(startCrateDir: string): Promise<string[]> {
58
+ // We have a set of visited dirs we check against when entering a new dir because we could stumble upon a directory
59
+ // multiple times in case multiple deps shared a dep (e.g. dep A and dep B both sharing dep C).
60
+ const visited = new Set<string>();
61
+
62
+ async function visit(crateDir: string): Promise<void> {
63
+ const absDir = resolve(crateDir);
64
+ if (visited.has(absDir)) {
65
+ return;
66
+ }
67
+ visited.add(absDir);
68
+
69
+ // Every dep is its own crate and every crate needs to have Nargo.toml defined in the root so we try to load it and
70
+ // error out if it's not the case.
71
+ const tomlPath = join(absDir, 'Nargo.toml');
72
+ const content = await readFile(tomlPath, 'utf-8').catch(() => {
73
+ throw new Error(`Incorrectly defined dependency. Nargo.toml not found in ${absDir}`);
74
+ });
75
+
76
+ // We parse and iterate over the dependencies
77
+ const parsed = TOML.parse(content) as Record<string, any>;
78
+ const deps = (parsed.dependencies as Record<string, any>) ?? {};
79
+ for (const dep of Object.values(deps)) {
80
+ if (dep && typeof dep === 'object' && typeof dep.path === 'string') {
81
+ const depPath = resolve(absDir, dep.path);
82
+ const s = await stat(depPath);
83
+ if (!s.isDirectory()) {
84
+ throw new Error(
85
+ `Dependency path "${dep.path}" in ${tomlPath} resolves to ${depPath} which is not a directory`,
86
+ );
87
+ }
88
+ await visit(depPath);
89
+ }
90
+ }
91
+ }
92
+
93
+ await visit(startCrateDir);
94
+ return [...visited];
95
+ }
96
+
97
+ /**
98
+ * Walks crate dirs looking for .nr and Nargo.toml files newer than thresholdMs. Short-circuits on the first match.
99
+ */
100
+ async function hasNewerSourceFile(crateDirs: string[], thresholdMs: number): Promise<boolean> {
101
+ // Returns true if it find a new file than thresholdMs, false otherwise
102
+ async function walkForNewer(dir: string): Promise<boolean> {
103
+ let entries;
104
+ try {
105
+ entries = await readdir(dir, { withFileTypes: true });
106
+ } catch {
107
+ return false;
108
+ }
109
+
110
+ // We iterate over the entries in the dir
111
+ for (const entry of entries) {
112
+ const fullPath = join(dir, entry.name);
113
+ if (entry.isDirectory()) {
114
+ // If the entry is a dir and it's not called `target` we recursively enter it
115
+ if (entry.name === 'target') {
116
+ continue;
117
+ }
118
+ if (await walkForNewer(fullPath)) {
119
+ return true;
120
+ }
121
+ } else if (entry.name === 'Nargo.toml' || entry.name.endsWith('.nr')) {
122
+ // The entry is a Nargo.toml file or *.nr file so we check the timestamp
123
+ const s = await stat(fullPath);
124
+ if (s.mtimeMs > thresholdMs) {
125
+ return true;
126
+ }
127
+ }
128
+ }
129
+ return false;
130
+ }
131
+
132
+ // We search through the crate dirs
133
+ for (const dir of crateDirs) {
134
+ if (await walkForNewer(dir)) {
135
+ return true;
136
+ }
137
+ }
138
+ return false;
139
+ }
@@ -0,0 +1,16 @@
1
+ import { spawn } from 'child_process';
2
+
3
+ /** Spawns a command with inherited stdio and rejects on non-zero exit. */
4
+ export function run(cmd: string, args: string[]): Promise<void> {
5
+ return new Promise((resolve, reject) => {
6
+ const child = spawn(cmd, args, { stdio: 'inherit' });
7
+ child.on('error', reject);
8
+ child.on('close', code => {
9
+ if (code !== 0) {
10
+ reject(new Error(`${cmd} exited with code ${code}`));
11
+ } else {
12
+ resolve();
13
+ }
14
+ });
15
+ });
16
+ }