@aztec-labs/aztec 6.0.0-rc.3 → 6.0.0-rc.4

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 (81) hide show
  1. package/dest/cli/admin_api_key_store.d.ts +2 -1
  2. package/dest/cli/admin_api_key_store.d.ts.map +1 -1
  3. package/dest/cli/admin_api_key_store.js +1 -0
  4. package/dest/cli/aztec_start_options.d.ts +2 -1
  5. package/dest/cli/aztec_start_options.d.ts.map +1 -1
  6. package/dest/cli/aztec_start_options.js +3 -2
  7. package/dest/cli/cli.d.ts +1 -1
  8. package/dest/cli/cli.d.ts.map +1 -1
  9. package/dest/cli/cli.js +2 -1
  10. package/dest/cli/cmds/compile.d.ts +1 -1
  11. package/dest/cli/cmds/compile.d.ts.map +1 -1
  12. package/dest/cli/cmds/compile.js +4 -3
  13. package/dest/cli/cmds/migrate_ha_db.d.ts +1 -1
  14. package/dest/cli/cmds/migrate_ha_db.d.ts.map +1 -1
  15. package/dest/cli/cmds/migrate_ha_db.js +3 -2
  16. package/dest/cli/cmds/profile_flamegraph.d.ts +1 -1
  17. package/dest/cli/cmds/profile_flamegraph.d.ts.map +1 -1
  18. package/dest/cli/cmds/profile_flamegraph.js +3 -2
  19. package/dest/cli/cmds/profile_gates.d.ts +1 -1
  20. package/dest/cli/cmds/profile_gates.d.ts.map +1 -1
  21. package/dest/cli/cmds/profile_gates.js +2 -1
  22. package/dest/cli/cmds/prover.d.ts +1 -1
  23. package/dest/cli/cmds/prover.d.ts.map +1 -1
  24. package/dest/cli/cmds/prover.js +3 -2
  25. package/dest/cli/cmds/start_node.d.ts +1 -1
  26. package/dest/cli/cmds/start_node.d.ts.map +1 -1
  27. package/dest/cli/cmds/start_node.js +1 -0
  28. package/dest/cli/cmds/utils/collect_crate_dirs.d.ts +1 -1
  29. package/dest/cli/cmds/utils/collect_crate_dirs.d.ts.map +1 -1
  30. package/dest/cli/cmds/utils/collect_crate_dirs.js +2 -1
  31. package/dest/cli/util.d.ts +2 -2
  32. package/dest/cli/util.d.ts.map +1 -1
  33. package/dest/cli/util.js +2 -26
  34. package/dest/deploy/bridging.d.ts +84 -0
  35. package/dest/deploy/bridging.d.ts.map +1 -0
  36. package/dest/deploy/bridging.js +121 -0
  37. package/dest/deploy/fees.d.ts +127 -0
  38. package/dest/deploy/fees.d.ts.map +1 -0
  39. package/dest/deploy/fees.js +309 -0
  40. package/dest/deploy/graph.d.ts +40 -0
  41. package/dest/deploy/graph.d.ts.map +1 -0
  42. package/dest/deploy/graph.js +120 -0
  43. package/dest/deploy/index.d.ts +19 -0
  44. package/dest/deploy/index.d.ts.map +1 -0
  45. package/dest/deploy/index.js +15 -0
  46. package/dest/deploy/reporter.d.ts +108 -0
  47. package/dest/deploy/reporter.d.ts.map +1 -0
  48. package/dest/deploy/reporter.js +78 -0
  49. package/dest/deploy/runner.d.ts +8 -0
  50. package/dest/deploy/runner.d.ts.map +1 -0
  51. package/dest/deploy/runner.js +993 -0
  52. package/dest/deploy/state.d.ts +19 -0
  53. package/dest/deploy/state.d.ts.map +1 -0
  54. package/dest/deploy/state.js +59 -0
  55. package/dest/deploy/types.d.ts +268 -0
  56. package/dest/deploy/types.d.ts.map +1 -0
  57. package/dest/deploy/types.js +9 -0
  58. package/dest/local-network/local-network.d.ts +1 -1
  59. package/dest/local-network/local-network.d.ts.map +1 -1
  60. package/dest/local-network/local-network.js +1 -0
  61. package/package.json +35 -32
  62. package/src/cli/admin_api_key_store.ts +1 -0
  63. package/src/cli/aztec_start_options.ts +7 -4
  64. package/src/cli/cli.ts +2 -1
  65. package/src/cli/cmds/compile.ts +4 -3
  66. package/src/cli/cmds/migrate_ha_db.ts +3 -2
  67. package/src/cli/cmds/profile_flamegraph.ts +3 -2
  68. package/src/cli/cmds/profile_gates.ts +2 -1
  69. package/src/cli/cmds/prover.ts +3 -2
  70. package/src/cli/cmds/start_node.ts +1 -0
  71. package/src/cli/cmds/utils/collect_crate_dirs.ts +2 -1
  72. package/src/cli/util.ts +3 -30
  73. package/src/deploy/bridging.ts +190 -0
  74. package/src/deploy/fees.ts +361 -0
  75. package/src/deploy/graph.ts +137 -0
  76. package/src/deploy/index.ts +41 -0
  77. package/src/deploy/reporter.ts +187 -0
  78. package/src/deploy/runner.ts +1057 -0
  79. package/src/deploy/state.ts +66 -0
  80. package/src/deploy/types.ts +290 -0
  81. package/src/local-network/local-network.ts +1 -0
@@ -1,5 +1,6 @@
1
1
  import { findBbBinary } from '@aztec-foundation/bb.js';
2
2
 
3
+ import { getEnv } from '@aztec-labs/foundation/config/env';
3
4
  import type { LogFn } from '@aztec-labs/foundation/log';
4
5
  import { readFile, rename, rm, writeFile } from 'fs/promises';
5
6
  import { basename, dirname, join } from 'path';
@@ -33,8 +34,8 @@ export async function profileFlamegraph(artifactPath: string, functionName: stri
33
34
  try {
34
35
  await writeFile(functionArtifact, makeFunctionArtifact(artifact, func));
35
36
 
36
- const profiler = process.env.PROFILER_PATH ?? 'noir-profiler';
37
- const bb = process.env.BB ?? findBbBinary() ?? 'bb';
37
+ const profiler = getEnv().PROFILER_PATH ?? 'noir-profiler';
38
+ const bb = getEnv().BB ?? findBbBinary() ?? 'bb';
38
39
 
39
40
  await run(profiler, [
40
41
  'gates',
@@ -1,6 +1,7 @@
1
1
  import { findBbBinary } from '@aztec-foundation/bb.js';
2
2
 
3
3
  import { asyncPool } from '@aztec-labs/foundation/async-pool';
4
+ import { getEnv } from '@aztec-labs/foundation/config/env';
4
5
  import type { LogFn } from '@aztec-labs/foundation/log';
5
6
  import { execFile as execFileCb } from 'child_process';
6
7
  import { rm } from 'fs/promises';
@@ -34,7 +35,7 @@ async function getGateCount(bb: string, artifactPath: string): Promise<number> {
34
35
 
35
36
  /** Profiles all compiled artifacts in a target directory and prints gate counts. */
36
37
  export async function profileGates(targetDir: string, json: boolean, log: LogFn): Promise<void> {
37
- const bb = process.env.BB ?? findBbBinary() ?? 'bb';
38
+ const bb = getEnv().BB ?? findBbBinary() ?? 'bb';
38
39
  const { artifacts, tmpDir } = await discoverArtifacts(targetDir);
39
40
 
40
41
  if (artifacts.length === 0) {
@@ -1,3 +1,4 @@
1
+ import { getEnv } from '@aztec-labs/foundation/config/env';
1
2
  import { jsonStringify } from '@aztec-labs/foundation/json-rpc';
2
3
  import type { LogFn } from '@aztec-labs/foundation/log';
3
4
  import { createProverNodeAdminClient } from '@aztec-labs/stdlib/interfaces/server';
@@ -19,7 +20,7 @@ export function injectProverCommand(program: Command, log: LogFn): Command {
19
20
  .description('Schedules proving for the given epoch')
20
21
  .requiredOption('--epoch <n>', 'Epoch number to prove', parseEpoch)
21
22
  .requiredOption('--admin-url <url>', 'URL of the prover node admin JSON-RPC endpoint')
22
- .option('--api-key <key>', 'Admin API key', process.env.AZTEC_ADMIN_API_KEY)
23
+ .option('--api-key <key>', 'Admin API key', getEnv().AZTEC_ADMIN_API_KEY)
23
24
  .action(async options => {
24
25
  const client = createProverNodeAdminClient(options.adminUrl, {}, undefined, options.apiKey);
25
26
  const jobId = await client.startProof(options.epoch);
@@ -30,7 +31,7 @@ export function injectProverCommand(program: Command, log: LogFn): Command {
30
31
  .command('get-jobs')
31
32
  .description('Lists the prover node proving jobs')
32
33
  .requiredOption('--admin-url <url>', 'URL of the prover node admin JSON-RPC endpoint')
33
- .option('--api-key <key>', 'Admin API key', process.env.AZTEC_ADMIN_API_KEY)
34
+ .option('--api-key <key>', 'Admin API key', getEnv().AZTEC_ADMIN_API_KEY)
34
35
  .action(async options => {
35
36
  const client = createProverNodeAdminClient(options.adminUrl, {}, undefined, options.apiKey);
36
37
  const jobs = await client.getJobs();
@@ -106,6 +106,7 @@ export async function startNode(
106
106
  nodeConfig.rollupVersion,
107
107
  );
108
108
 
109
+ // eslint-disable-next-line no-restricted-properties -- sets a variable of the Node.js process
109
110
  process.env.ROLLUP_CONTRACT_ADDRESS ??= addresses.rollupAddress.toString();
110
111
 
111
112
  if (!Fr.fromHexString(config.genesisArchiveTreeRoot).equals(genesisArchiveRoot)) {
@@ -1,3 +1,4 @@
1
+ import { getEnv } from '@aztec-labs/foundation/config/env';
1
2
  import TOML from '@iarna/toml';
2
3
  import { existsSync } from 'fs';
3
4
  import { mkdir, readFile, stat } from 'fs/promises';
@@ -93,7 +94,7 @@ export function nargoGitDepPath(gitUrl: string, tag: string): string {
93
94
  const url = new URL(gitUrl);
94
95
  const domain = url.hostname;
95
96
  const repoPath = url.pathname.replace(/^\//, '');
96
- return join(process.env.HOME ?? homedir(), 'nargo', domain, repoPath, tag);
97
+ return join(getEnv().HOME ?? homedir(), 'nargo', domain, repoPath, tag);
97
98
  }
98
99
 
99
100
  /**
package/src/cli/util.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { AztecNodeConfig } from '@aztec-labs/aztec-node';
2
2
  import type { AccountManager } from '@aztec-labs/aztec.js/wallet';
3
- import type { ConfigMappingsType } from '@aztec-labs/foundation/config';
3
+ import { type ConfigMappingsType, getValueFromEnvWithFallback } from '@aztec-labs/foundation/config';
4
4
  import { jsonStringify } from '@aztec-labs/foundation/json-rpc';
5
5
  import type { LogFn } from '@aztec-labs/foundation/log';
6
6
  import type { ProverConfig } from '@aztec-labs/stdlib/interfaces/server';
@@ -143,35 +143,8 @@ export function formatHelpLine(
143
143
  return `${chalk.cyan(paddedOption)}${chalk.yellow(paddedDefault)}${chalk.green(envVar)}`;
144
144
  }
145
145
 
146
- const getDefaultOrEnvValue = (opt: AztecStartOption) => {
147
- let val;
148
-
149
- // if the option is set in the environment, use that
150
- if (opt.env) {
151
- val = process.env[opt.env];
152
- }
153
-
154
- // if we have fallback env vars, check those
155
- if (!val && opt.fallback && opt.fallback.length > 0) {
156
- for (const fallback of opt.fallback) {
157
- val = process.env[fallback];
158
- if (val) {
159
- break;
160
- }
161
- }
162
- }
163
-
164
- // if we have a value, optionally parse it and return
165
- if (val) {
166
- if (opt.parseVal) {
167
- return opt.parseVal(val);
168
- }
169
- return val;
170
- } else if (opt.defaultValue !== undefined) {
171
- return opt.defaultValue;
172
- }
173
- return undefined;
174
- };
146
+ const getDefaultOrEnvValue = (opt: AztecStartOption) =>
147
+ getValueFromEnvWithFallback(opt.env, opt.parseVal, opt.defaultValue, opt.fallback, opt.deprecatedFallback);
175
148
 
176
149
  // Function to add options dynamically
177
150
  export const addOptions = (cmd: Command, options: AztecStartOption[]) => {
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Fee-juice bridging for the `fee-juice` deploy policy: bridge Fee Juice from L1
3
+ * ({@link bridgeFeeJuice}) and wait for the L1→L2 message to become available
4
+ * ({@link waitForL1ToL2Message}). Fee Juice only — this is not a generic L1→L2 asset bridge.
5
+ * Node-only (pulls in `@aztec-labs/aztec.js/ethereum` + viem).
6
+ *
7
+ * Nothing here sends the L2 claim tx — the caller feeds the returned claim into
8
+ * `FeeJuicePaymentMethodWithClaim` so the claim lands inside whatever tx the recipient is already
9
+ * sending.
10
+ */
11
+ import type { AztecAddress } from '@aztec-labs/aztec.js/addresses';
12
+ import { L1FeeJuicePortalManager } from '@aztec-labs/aztec.js/ethereum';
13
+ import { isL1ToL2MessageReady } from '@aztec-labs/aztec.js/messaging';
14
+ import type { AztecNode } from '@aztec-labs/aztec.js/node';
15
+ import { createEthereumChain } from '@aztec-labs/ethereum/chain';
16
+ import { createExtendedL1Client } from '@aztec-labs/ethereum/client';
17
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
18
+ import { createLogger } from '@aztec-labs/foundation/log';
19
+ import { retryUntil } from '@aztec-labs/foundation/retry';
20
+ import { type AztecNodeDebug, createAztecNodeDebugClient } from '@aztec-labs/stdlib/interfaces/client';
21
+ import type { Hex } from 'viem';
22
+ import { generatePrivateKey } from 'viem/accounts';
23
+
24
+ const logger = createLogger('deploy:bridging');
25
+
26
+ /** Wait between availability checks in `warp` mode — each iteration also warps the clock forward. */
27
+ const WARP_POLL_INTERVAL_MS = 1000;
28
+ /** Wait between availability checks in `poll` mode (a real network; nothing to do but wait). */
29
+ const POLL_INTERVAL_MS = 5_000;
30
+ /** Throttle for the "still waiting" progress log in the poll loop. */
31
+ const POLL_LOG_INTERVAL_MS = 30_000;
32
+
33
+ /** Local vs. remote L1→L2 message advancement: warp cheats time forward, poll just waits. */
34
+ export type BridgeTimingMode = 'warp' | 'poll';
35
+
36
+ /** The claim produced by bridging: exactly the shape `FeeJuicePaymentMethodWithClaim` expects. */
37
+ export type FeeJuiceClaim = Awaited<ReturnType<L1FeeJuicePortalManager['bridgeTokensPublic']>>;
38
+
39
+ /**
40
+ * Decides how the L1 signer funds a bridge: mint from the fee-asset faucet handler, or transfer
41
+ * its existing Fee Juice. Pure — exercised directly by unit tests.
42
+ *
43
+ * - Balance covers the requested amount → transfer it (no mint, even when a faucet exists).
44
+ * - Balance short of the amount + faucet available → mint (the faucet path bridges the handler's
45
+ * own mint amount and ignores `amount`).
46
+ * - Balance short + no faucet → throw, reporting the shortfall.
47
+ * - No `amount` requested → the faucet is required (there is nothing to size a transfer by).
48
+ */
49
+ export function pickBridgeRoute(opts: { hasFaucet: boolean; l1Balance: bigint; amount?: bigint }): {
50
+ useFaucet: boolean;
51
+ amount?: bigint;
52
+ } {
53
+ const { hasFaucet, l1Balance, amount } = opts;
54
+ if (amount === undefined) {
55
+ if (!hasFaucet) {
56
+ throw new Error('bridgeFeeJuice: `amount` is required when no fee-asset faucet is available.');
57
+ }
58
+ return { useFaucet: true };
59
+ }
60
+ if (l1Balance >= amount) {
61
+ return { useFaucet: false, amount };
62
+ }
63
+ if (hasFaucet) {
64
+ return { useFaucet: true };
65
+ }
66
+ throw new Error(
67
+ `L1 signer holds ${l1Balance} wei of Fee Juice but ${amount} was requested, and no fee-asset faucet is ` +
68
+ `available to mint the difference.`,
69
+ );
70
+ }
71
+
72
+ export interface BridgeFeeJuiceParams {
73
+ node: AztecNode;
74
+ l1RpcUrl: string;
75
+ l1ChainId: number;
76
+ recipient: AztecAddress;
77
+ /** Desired amount in wei. Optional only when a faucet exists (whose `mintAmount()` then wins). */
78
+ amount?: bigint;
79
+ /** L1 private key signing the bridge tx. When omitted, a fresh ephemeral key is generated. */
80
+ l1PrivateKey?: Hex;
81
+ }
82
+
83
+ /**
84
+ * Bridges fee juice to an L2 recipient, minting from the faucet handler or transferring the
85
+ * signer's balance per {@link pickBridgeRoute}. Returns the claim; the L1→L2 message it references
86
+ * becomes available later — see {@link waitForL1ToL2Message}.
87
+ */
88
+ export async function bridgeFeeJuice(params: BridgeFeeJuiceParams): Promise<FeeJuiceClaim> {
89
+ const { node, l1RpcUrl, l1ChainId, recipient } = params;
90
+
91
+ const l1PrivateKey: Hex = params.l1PrivateKey ?? generatePrivateKey();
92
+ const chain = createEthereumChain([l1RpcUrl], l1ChainId);
93
+ const l1Client = createExtendedL1Client(chain.rpcUrls, l1PrivateKey, chain.chainInfo);
94
+ const portalManager = await L1FeeJuicePortalManager.new(node, l1Client, logger);
95
+
96
+ const tokenManager = portalManager.getTokenManager();
97
+ const route = pickBridgeRoute({
98
+ hasFaucet: tokenManager.handlerAddress !== undefined,
99
+ l1Balance: await tokenManager.getL1TokenBalance(l1Client.account.address),
100
+ amount: params.amount,
101
+ });
102
+ return await portalManager.bridgeTokensPublic(recipient, route.amount, route.useFaucet);
103
+ }
104
+
105
+ export interface WaitForClaimParams {
106
+ node: AztecNode;
107
+ messageHash: Fr;
108
+ /**
109
+ * On `warp` (local) we cheat L1+L2 time forward via the node debug API until the message shows as
110
+ * available; on `poll` (every other network) we just check periodically.
111
+ */
112
+ mode: BridgeTimingMode;
113
+ /** Timeout before giving up (default 30 min for poll, 2 min for warp). */
114
+ timeoutMs?: number;
115
+ /** Warp-only: options for reaching the node's debug API. */
116
+ warpOpts?: { nodeUrl?: string };
117
+ }
118
+
119
+ /** Waits until an L1→L2 message is available on the node (warping time forward in `warp` mode). */
120
+ export async function waitForL1ToL2Message(params: WaitForClaimParams): Promise<void> {
121
+ const { node, messageHash, mode } = params;
122
+
123
+ if (mode === 'warp') {
124
+ await warpToL1ToL2Message(node, messageHash, {
125
+ ...params.warpOpts,
126
+ timeoutMs: params.timeoutMs ?? 120_000,
127
+ });
128
+ return;
129
+ }
130
+
131
+ const timeoutMs = params.timeoutMs ?? 30 * 60_000;
132
+ const startedAt = Date.now();
133
+ let lastLog = startedAt;
134
+ await retryUntil(
135
+ async () => {
136
+ if (await isL1ToL2MessageReady(node, messageHash)) {
137
+ return true;
138
+ }
139
+ if (Date.now() - lastLog > POLL_LOG_INTERVAL_MS) {
140
+ lastLog = Date.now();
141
+ logger.info('Still waiting for L1→L2 message to become available', {
142
+ messageHash: messageHash.toString(),
143
+ elapsedMs: Date.now() - startedAt,
144
+ timeoutMs,
145
+ });
146
+ }
147
+ return undefined;
148
+ },
149
+ `L1→L2 message ${messageHash.toString()}`,
150
+ timeoutMs / 1000,
151
+ POLL_INTERVAL_MS / 1000,
152
+ );
153
+ }
154
+
155
+ /**
156
+ * Local-network helper: advances L1 + L2 time via the node debug API until the given L1→L2 message
157
+ * shows up as available, warping by one L2 slot (read from the node's rollup constants) per check.
158
+ * An in-process node (e.g. a test fixture's `AztecNodeService`) implements the debug interface
159
+ * directly; a remote node is reached via its debug RPC at `nodeUrl` — `warpL2TimeAtLeastBy` needs
160
+ * `AztecNode & AztecNodeDebug` (it reads the current L1 timestamp via the regular API before
161
+ * warping), and both clients target the same URL and expose their methods as own properties on the
162
+ * rpc proxy, so a shallow merge is safe.
163
+ */
164
+ export async function warpToL1ToL2Message(
165
+ node: AztecNode,
166
+ messageHash: Fr,
167
+ opts: { nodeUrl?: string; timeoutMs?: number } = {},
168
+ ): Promise<void> {
169
+ const nodeUrl = opts.nodeUrl ?? 'http://localhost:8080';
170
+ const timeoutMs = opts.timeoutMs ?? 120_000;
171
+
172
+ const fullNode =
173
+ typeof (node as Partial<AztecNodeDebug>).warpL2TimeAtLeastBy === 'function'
174
+ ? (node as AztecNode & AztecNodeDebug)
175
+ : (Object.assign({}, node, createAztecNodeDebugClient(nodeUrl)) as AztecNode & AztecNodeDebug);
176
+ const { slotDuration } = await node.getL1Constants();
177
+
178
+ await retryUntil(
179
+ async () => {
180
+ if (await isL1ToL2MessageReady(node, messageHash)) {
181
+ return true;
182
+ }
183
+ await fullNode.warpL2TimeAtLeastBy(slotDuration);
184
+ return undefined;
185
+ },
186
+ `L1→L2 message ${messageHash.toString()} (warping)`,
187
+ timeoutMs / 1000,
188
+ WARP_POLL_INTERVAL_MS / 1000,
189
+ );
190
+ }
@@ -0,0 +1,361 @@
1
+ /**
2
+ * Fee handling for the deploy framework. Each account pays per its own {@link FeePolicy} — which
3
+ * may override the spec-wide default:
4
+ *
5
+ * - `sponsored` → a SponsoredFPC pays (the local-network default). All sponsored accounts share
6
+ * one payment method.
7
+ * - `fee-juice` → the account pays from its own Fee Juice; if below `threshold` with work to do,
8
+ * bridge `fundAmount` from L1. The bridge claim is single-use: the first paying tx claims it
9
+ * (`FeeJuicePaymentMethodWithClaim`) and the rest spend the balance. Pending claims are persisted
10
+ * (see ./state.ts) so a crash between bridge and claim resumes.
11
+ * - `payment-method` → a caller-supplied payment method (e.g. a deployed FPC) pays every tx, with
12
+ * its own gas settings.
13
+ */
14
+ import type { AztecAddress } from '@aztec-labs/aztec.js/addresses';
15
+ import {
16
+ FeeJuicePaymentMethodWithClaim,
17
+ type FeePaymentMethod,
18
+ SponsoredFeePaymentMethod,
19
+ } from '@aztec-labs/aztec.js/fee';
20
+ import { Fr } from '@aztec-labs/aztec.js/fields';
21
+ import type { AztecNode } from '@aztec-labs/aztec.js/node';
22
+ import { FeeJuiceContract } from '@aztec-labs/aztec.js/protocol';
23
+ import type { Wallet } from '@aztec-labs/aztec.js/wallet';
24
+ import type { GasFees } from '@aztec-labs/stdlib/gas';
25
+ import type { Hex } from 'viem';
26
+
27
+ import { registerDeployedSponsoredFPCInWalletAndGetAddress } from '../local-network/sponsored_fpc.js';
28
+ import { bridgeFeeJuice, waitForL1ToL2Message } from './bridging.js';
29
+ import type { AccountFunding, DeployReporter } from './reporter.js';
30
+ import type { DeployState } from './state.js';
31
+ import type { FeePolicy } from './types.js';
32
+
33
+ /** Anvil's first pre-funded dev key — used as the local-network L1 funder. Published, non-secret. */
34
+ const ANVIL_DEV_KEY: Hex = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80';
35
+ const DEFAULT_LOCAL_L1_RPC_URL = 'http://localhost:8545';
36
+ const DEFAULT_LOCAL_L1_CHAIN_ID = 31337;
37
+
38
+ /** The `fee` field of a send-options object. */
39
+ export interface SendFee {
40
+ paymentMethod?: FeePaymentMethod;
41
+ gasSettings?: { maxFeesPerGas: GasFees };
42
+ }
43
+
44
+ /**
45
+ * Sane fee defaults: local pays via SponsoredFPC; every other network pays from bridged Fee Juice.
46
+ * The threshold/fundAmount pair trades off L1 round-trips (too low → frequent re-bridges) against
47
+ * stranding Fee Juice, which is non-transferable, on the account (too high).
48
+ */
49
+ export function defaultFeePolicy(local: boolean): FeePolicy {
50
+ if (local) {
51
+ return { kind: 'sponsored' };
52
+ }
53
+ return {
54
+ kind: 'fee-juice',
55
+ threshold: 100n * 10n ** 18n, // 100 FJ
56
+ fundAmount: 1000n * 10n ** 18n, // 1000 FJ (non-faucet fallback amount)
57
+ };
58
+ }
59
+
60
+ /** The public Fee Juice balance of `address` (any address — contract or account), read via `from`. */
61
+ export async function publicFeeJuiceBalance(
62
+ wallet: Wallet,
63
+ address: AztecAddress,
64
+ from: AztecAddress,
65
+ ): Promise<bigint> {
66
+ const { result } = await FeeJuiceContract.at(wallet).methods.balance_of_public(address).simulate({ from });
67
+ return BigInt(result.toString());
68
+ }
69
+
70
+ /**
71
+ * Resolves an account's funding posture under `policy` — what the plan reports and what
72
+ * {@link prepareFeeSession} acts on. `idle` accounts (no pending work) are never funded; sponsored
73
+ * accounts never read a balance; fee-juice accounts are `funded` iff their balance clears the
74
+ * threshold, else `not-funded` (a bridge will top them up).
75
+ */
76
+ export async function accountFunding(
77
+ policy: FeePolicy,
78
+ wallet: Wallet,
79
+ account: AztecAddress,
80
+ hasWork: boolean,
81
+ ): Promise<AccountFunding> {
82
+ if (!hasWork) {
83
+ return { kind: 'idle' };
84
+ }
85
+ if (policy.kind === 'sponsored') {
86
+ return { kind: 'sponsored' };
87
+ }
88
+ if (policy.kind === 'payment-method') {
89
+ return { kind: 'payment-method' };
90
+ }
91
+ const balance = await publicFeeJuiceBalance(wallet, account, account);
92
+ return balance >= policy.threshold
93
+ ? { kind: 'funded', balance }
94
+ : { kind: 'not-funded', balance, fundAmount: policy.fundAmount };
95
+ }
96
+
97
+ /**
98
+ * Resolves the L1 connection + funder for a bridge from caller-supplied config, defaulting to anvil
99
+ * on local. The funder key falls back to anvil's dev key on local (its faucet `mint` is owner-gated,
100
+ * so an ephemeral key is rejected there); elsewhere an omitted key means an ephemeral key + the
101
+ * public faucet. Deliberately no env fallback — the framework never reads the environment.
102
+ */
103
+ function resolveL1Config(
104
+ local: boolean,
105
+ cfg: { l1RpcUrl?: string; l1ChainId?: number; l1FunderKey?: Hex },
106
+ ): { l1RpcUrl: string; l1ChainId: number; l1PrivateKey?: Hex } {
107
+ const l1RpcUrl = cfg.l1RpcUrl ?? (local ? DEFAULT_LOCAL_L1_RPC_URL : undefined);
108
+ const l1ChainId = cfg.l1ChainId ?? (local ? DEFAULT_LOCAL_L1_CHAIN_ID : undefined);
109
+ if (l1RpcUrl === undefined || l1ChainId === undefined) {
110
+ throw new Error('Bridging on a non-local network requires `l1RpcUrl` and `l1ChainId` (no hardcoded defaults).');
111
+ }
112
+ return { l1RpcUrl, l1ChainId, l1PrivateKey: cfg.l1FunderKey ?? (local ? ANVIL_DEV_KEY : undefined) };
113
+ }
114
+
115
+ /** What {@link obtainFeeJuiceClaim} needs to produce a consumable claim for a recipient. */
116
+ export interface ObtainFeeJuiceClaimOpts {
117
+ /** Whether the target is a local (anvil) network — drives warp-vs-poll + L1 defaults. */
118
+ local: boolean;
119
+ node: AztecNode;
120
+ /** The node's URL — reaches its debug API for local time-warping while the bridge settles. */
121
+ nodeUrl?: string;
122
+ recipient: AztecAddress;
123
+ /** Amount to bridge (wei). */
124
+ amount: bigint;
125
+ /** L1 connection + funder, defaulted per {@link resolveL1Config}. */
126
+ l1: { l1FunderKey?: Hex; l1RpcUrl?: string; l1ChainId?: number };
127
+ state: DeployState;
128
+ persist: () => void;
129
+ reporter: DeployReporter;
130
+ }
131
+
132
+ /**
133
+ * A single-use Fee Juice claim for `recipient` (used by `fund` steps): resumes the persisted claim
134
+ * when present, else bridges `amount` from L1 and waits for the L1→L2 message. The claim persists
135
+ * before the wait, so a crash mid-wait resumes it instead of stranding the bridged funds. The
136
+ * caller consumes it (e.g. via `FeeJuice.claim`) and calls `onConsumed` once that tx mines.
137
+ */
138
+ export async function obtainFeeJuiceClaim(opts: ObtainFeeJuiceClaimOpts): Promise<{
139
+ claimAmount: bigint;
140
+ claimSecret: Fr;
141
+ messageLeafIndex: bigint;
142
+ /** Drops the persisted resume entry — call once the consuming tx mines. */
143
+ onConsumed: () => void;
144
+ }> {
145
+ const { local, node, nodeUrl, recipient, state, persist, reporter } = opts;
146
+ // Prefixed so a recipient that is also an auto-funded sender doesn't collide with its account claim.
147
+ const key = `fund:${recipient.toString()}`;
148
+ let claim: { claimAmount: bigint; claimSecret: Fr; messageLeafIndex: bigint };
149
+ const stored = state.pendingClaims[key];
150
+ if (stored) {
151
+ reporter.onBridge?.({ recipient, amount: BigInt(stored.claimAmount), reused: true });
152
+ claim = {
153
+ claimAmount: BigInt(stored.claimAmount),
154
+ claimSecret: Fr.fromString(stored.claimSecret),
155
+ messageLeafIndex: BigInt(stored.messageLeafIndex),
156
+ };
157
+ } else {
158
+ reporter.onBridge?.({ recipient, amount: opts.amount, reused: false });
159
+ const { l1RpcUrl, l1ChainId, l1PrivateKey } = resolveL1Config(local, opts.l1);
160
+ const bridged = await bridgeFeeJuice({ node, recipient, l1RpcUrl, l1ChainId, amount: opts.amount, l1PrivateKey });
161
+ state.pendingClaims[key] = {
162
+ claimAmount: bridged.claimAmount.toString(),
163
+ claimSecret: bridged.claimSecret.toString(),
164
+ messageLeafIndex: bridged.messageLeafIndex.toString(),
165
+ };
166
+ persist();
167
+ await waitForL1ToL2Message({
168
+ node,
169
+ messageHash: Fr.fromHexString(bridged.messageHash),
170
+ mode: local ? 'warp' : 'poll',
171
+ ...(nodeUrl ? { warpOpts: { nodeUrl } } : {}),
172
+ });
173
+ claim = {
174
+ claimAmount: bridged.claimAmount,
175
+ claimSecret: bridged.claimSecret,
176
+ messageLeafIndex: bridged.messageLeafIndex,
177
+ };
178
+ }
179
+ return {
180
+ ...claim,
181
+ onConsumed: () => {
182
+ delete state.pendingClaims[key];
183
+ persist();
184
+ },
185
+ };
186
+ }
187
+
188
+ /** Per-account fee dispensing for one run, prepared by {@link prepareFeeSession}. */
189
+ export interface FeeSession {
190
+ /**
191
+ * Fee options for the next tx from `account`, plus `onConsumed` to call after it lands (clears a
192
+ * one-time bridge claim from persisted state). Subsequent calls pay from balance.
193
+ */
194
+ next(account: AztecAddress): { fee: SendFee; onConsumed: () => void };
195
+ /**
196
+ * Whether `account`'s next tx will carry its one-time bridge claim. The runner serializes such an
197
+ * account's first tx: the claim must mine before its balance-paying txs fan out.
198
+ */
199
+ hasPendingClaim(account: AztecAddress): boolean;
200
+ /**
201
+ * How many calls `account`'s next fee payment adds to its tx (0 when it pays from balance, 1 for
202
+ * an FPC or a pending claim) — the runner sizes action batches to leave room for them.
203
+ */
204
+ feeCallCount(account: AztecAddress): Promise<number>;
205
+ }
206
+
207
+ /** What {@link prepareFeeSession} needs to fund a run's working accounts. */
208
+ export interface PrepareFeeSessionOpts {
209
+ /** Whether the target is a local (anvil) network — drives warp-vs-poll + L1 defaults. */
210
+ local: boolean;
211
+ node: AztecNode;
212
+ /** The node's URL — reaches its debug API for local time-warping while a bridge settles. */
213
+ nodeUrl?: string;
214
+ wallet: Wallet;
215
+ /**
216
+ * Working accounts (those with pending work) with their resolved {@link FeePolicy} + funding (from
217
+ * {@link accountFunding}) — so this function doesn't re-read balances.
218
+ */
219
+ accounts: { address: AztecAddress; policy: FeePolicy; funding: AccountFunding }[];
220
+ state: DeployState;
221
+ persist: () => void;
222
+ reporter: DeployReporter;
223
+ }
224
+
225
+ /**
226
+ * Resolves fees ahead of execution, per account: registers the shared SponsoredFPC or a payment
227
+ * method's contract, or tops up a fee-juice account via a bridge (reusing a persisted pending claim
228
+ * when present). Returns a {@link FeeSession} that dispenses the right fee per tx, by sending account.
229
+ */
230
+ export async function prepareFeeSession(opts: PrepareFeeSessionOpts): Promise<FeeSession> {
231
+ const { local, node, nodeUrl, wallet, accounts, state, persist, reporter } = opts;
232
+
233
+ // Shared sponsored payment method: register the SponsoredFPC + read gas once, if anyone uses it.
234
+ let sponsoredFee: SendFee | undefined;
235
+ if (accounts.some(a => a.policy.kind === 'sponsored')) {
236
+ const sponsoredFPCAddress = await registerDeployedSponsoredFPCInWalletAndGetAddress(wallet);
237
+ sponsoredFee = {
238
+ paymentMethod: new SponsoredFeePaymentMethod(sponsoredFPCAddress),
239
+ // 10x headroom because this one quote is reused for every tx in the run (the wallet's default would re-quote
240
+ // per tx at 1.5x min): congestion pricing can push the min fee well past the starting quote over a run of
241
+ // parallel layers. Overstating the cap is free — txs pay the going rate, not the cap, and the FPC pays anyway.
242
+ gasSettings: { maxFeesPerGas: (await node.getCurrentMinFees()).mul(10) },
243
+ };
244
+ }
245
+
246
+ // The run's PXE is fresh, so register each paying contract. No gasSettings override: an FPC may
247
+ // have committed to its own.
248
+ const paymentMethods = new Map<string, FeePaymentMethod>();
249
+ for (const { address, policy } of accounts) {
250
+ if (policy.kind !== 'payment-method') {
251
+ continue;
252
+ }
253
+ await wallet.registerContract(policy.instance, policy.artifact);
254
+ paymentMethods.set(address.toString(), policy.paymentMethod);
255
+ }
256
+
257
+ // Bridge fee-juice top-ups. The L1 sends stay sequential — a shared funder key would collide on
258
+ // nonces — but the L1→L2 availability waits (the minutes-long part on a real network) run
259
+ // concurrently afterwards. Warp-mode waits run inline instead: warping manipulates global time,
260
+ // so concurrent warps would fight. Each claim persists as soon as it exists on L1, so a crash
261
+ // mid-wait resumes it instead of stranding the bridged funds; a resumed claim skips the wait (by
262
+ // resume time the message is available on any live network).
263
+ const claims = new Map<string, FeeJuicePaymentMethodWithClaim>();
264
+ const messageWaits: Promise<void>[] = [];
265
+ for (const { address, policy, funding } of accounts) {
266
+ if (policy.kind !== 'fee-juice' || funding.kind === 'funded') {
267
+ continue;
268
+ }
269
+ const key = address.toString();
270
+ let stored = state.pendingClaims[key];
271
+ if (stored) {
272
+ reporter.onBridge?.({ recipient: address, amount: BigInt(stored.claimAmount), reused: true });
273
+ } else {
274
+ reporter.onBridge?.({ recipient: address, amount: policy.fundAmount, reused: false });
275
+ // Local defaults to anvil; a non-local network must supply L1 connection details.
276
+ const { l1RpcUrl, l1ChainId, l1PrivateKey } = resolveL1Config(local, policy);
277
+ const bridged = await bridgeFeeJuice({
278
+ node,
279
+ recipient: address,
280
+ l1RpcUrl,
281
+ l1ChainId,
282
+ amount: policy.fundAmount,
283
+ l1PrivateKey,
284
+ });
285
+ stored = {
286
+ claimAmount: bridged.claimAmount.toString(),
287
+ claimSecret: bridged.claimSecret.toString(),
288
+ messageLeafIndex: bridged.messageLeafIndex.toString(),
289
+ };
290
+ state.pendingClaims[key] = stored;
291
+ persist();
292
+ const wait = waitForL1ToL2Message({
293
+ node,
294
+ messageHash: Fr.fromHexString(bridged.messageHash),
295
+ mode: local ? 'warp' : 'poll',
296
+ ...(nodeUrl ? { warpOpts: { nodeUrl } } : {}),
297
+ });
298
+ if (local) {
299
+ await wait;
300
+ } else {
301
+ messageWaits.push(wait);
302
+ }
303
+ }
304
+ claims.set(
305
+ key,
306
+ new FeeJuicePaymentMethodWithClaim(address, {
307
+ claimAmount: BigInt(stored.claimAmount),
308
+ claimSecret: Fr.fromString(stored.claimSecret),
309
+ messageLeafIndex: BigInt(stored.messageLeafIndex),
310
+ }),
311
+ );
312
+ }
313
+ await Promise.all(messageWaits);
314
+
315
+ // Per-account dispenser state. A claim is single-use: the first `next()` for its account carries
316
+ // it, and `onConsumed` (invoked by the runner once that tx mines) drops the persisted resume entry.
317
+ const sessions = new Map<
318
+ string,
319
+ { sponsored: boolean; paymentMethod?: FeePaymentMethod; claim?: FeeJuicePaymentMethodWithClaim }
320
+ >();
321
+ for (const { address, policy } of accounts) {
322
+ const key = address.toString();
323
+ sessions.set(key, {
324
+ sponsored: policy.kind === 'sponsored',
325
+ paymentMethod: paymentMethods.get(key),
326
+ claim: claims.get(key),
327
+ });
328
+ }
329
+
330
+ return {
331
+ next: account => {
332
+ const key = account.toString();
333
+ const session = sessions.get(key);
334
+ if (session?.sponsored) {
335
+ return { fee: sponsoredFee ?? {}, onConsumed: () => {} };
336
+ }
337
+ if (session?.paymentMethod) {
338
+ return { fee: { paymentMethod: session.paymentMethod }, onConsumed: () => {} };
339
+ }
340
+ if (session?.claim) {
341
+ const claim = session.claim;
342
+ session.claim = undefined; // single-use: only this first tx carries it
343
+ return {
344
+ fee: { paymentMethod: claim },
345
+ onConsumed: () => {
346
+ // claim is now spent on-chain; drop its resume entry
347
+ delete state.pendingClaims[key];
348
+ persist();
349
+ },
350
+ };
351
+ }
352
+ return { fee: {}, onConsumed: () => {} }; // later txs (or already-funded): pay from the account's balance
353
+ },
354
+ hasPendingClaim: account => sessions.get(account.toString())?.claim !== undefined,
355
+ feeCallCount: async account => {
356
+ const session = sessions.get(account.toString());
357
+ const method = session?.sponsored ? sponsoredFee?.paymentMethod : (session?.paymentMethod ?? session?.claim);
358
+ return method ? (await method.getExecutionPayload()).calls.length : 0;
359
+ },
360
+ };
361
+ }