@aztec/aztec 0.0.1-commit.f504929 → 0.0.1-commit.f5a9928

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 (165) hide show
  1. package/dest/bin/index.js +4 -2
  2. package/dest/cli/aztec_start_action.d.ts +1 -1
  3. package/dest/cli/aztec_start_action.d.ts.map +1 -1
  4. package/dest/cli/aztec_start_action.js +42 -33
  5. package/dest/cli/aztec_start_options.d.ts +2 -2
  6. package/dest/cli/aztec_start_options.d.ts.map +1 -1
  7. package/dest/cli/aztec_start_options.js +22 -18
  8. package/dest/cli/cmds/compile.d.ts +1 -1
  9. package/dest/cli/cmds/compile.d.ts.map +1 -1
  10. package/dest/cli/cmds/compile.js +35 -21
  11. package/dest/cli/cmds/profile.d.ts +1 -1
  12. package/dest/cli/cmds/profile.d.ts.map +1 -1
  13. package/dest/cli/cmds/profile.js +1 -1
  14. package/dest/cli/cmds/profile_flamegraph.d.ts +1 -1
  15. package/dest/cli/cmds/profile_flamegraph.d.ts.map +1 -1
  16. package/dest/cli/cmds/profile_flamegraph.js +2 -1
  17. package/dest/cli/cmds/profile_gates.d.ts +2 -2
  18. package/dest/cli/cmds/profile_gates.d.ts.map +1 -1
  19. package/dest/cli/cmds/profile_gates.js +23 -4
  20. package/dest/cli/cmds/prover.d.ts +4 -0
  21. package/dest/cli/cmds/prover.d.ts.map +1 -0
  22. package/dest/cli/cmds/prover.js +24 -0
  23. package/dest/cli/cmds/standby.d.ts +56 -0
  24. package/dest/cli/cmds/standby.d.ts.map +1 -0
  25. package/dest/cli/cmds/standby.js +140 -0
  26. package/dest/cli/cmds/start_bot.d.ts +1 -1
  27. package/dest/cli/cmds/start_bot.d.ts.map +1 -1
  28. package/dest/cli/cmds/start_bot.js +8 -4
  29. package/dest/cli/cmds/start_node.d.ts +3 -2
  30. package/dest/cli/cmds/start_node.d.ts.map +1 -1
  31. package/dest/cli/cmds/start_node.js +36 -112
  32. package/dest/cli/cmds/start_prover_agent.d.ts +1 -1
  33. package/dest/cli/cmds/start_prover_agent.d.ts.map +1 -1
  34. package/dest/cli/cmds/start_prover_agent.js +5 -17
  35. package/dest/cli/cmds/start_prover_broker.d.ts +1 -1
  36. package/dest/cli/cmds/start_prover_broker.d.ts.map +1 -1
  37. package/dest/cli/cmds/start_prover_broker.js +22 -13
  38. package/dest/cli/cmds/start_txe.d.ts +2 -2
  39. package/dest/cli/cmds/start_txe.d.ts.map +1 -1
  40. package/dest/cli/cmds/start_txe.js +6 -5
  41. package/dest/cli/cmds/utils/artifacts.d.ts +6 -1
  42. package/dest/cli/cmds/utils/artifacts.d.ts.map +1 -1
  43. package/dest/cli/cmds/utils/collect_crate_dirs.d.ts +21 -0
  44. package/dest/cli/cmds/utils/collect_crate_dirs.d.ts.map +1 -0
  45. package/dest/cli/cmds/utils/collect_crate_dirs.js +114 -0
  46. package/dest/cli/cmds/utils/needs_recompile.d.ts +10 -0
  47. package/dest/cli/cmds/utils/needs_recompile.d.ts.map +1 -0
  48. package/dest/cli/cmds/utils/needs_recompile.js +90 -0
  49. package/dest/cli/cmds/utils/warn_if_aztec_version_mismatch.d.ts +4 -0
  50. package/dest/cli/cmds/utils/warn_if_aztec_version_mismatch.d.ts.map +1 -0
  51. package/dest/cli/cmds/utils/warn_if_aztec_version_mismatch.js +61 -0
  52. package/dest/cli/util.d.ts +9 -6
  53. package/dest/cli/util.d.ts.map +1 -1
  54. package/dest/cli/util.js +26 -94
  55. package/dest/deploy/bridging.d.ts +84 -0
  56. package/dest/deploy/bridging.d.ts.map +1 -0
  57. package/dest/deploy/bridging.js +121 -0
  58. package/dest/deploy/fees.d.ts +120 -0
  59. package/dest/deploy/fees.d.ts.map +1 -0
  60. package/dest/deploy/fees.js +278 -0
  61. package/dest/deploy/graph.d.ts +40 -0
  62. package/dest/deploy/graph.d.ts.map +1 -0
  63. package/dest/deploy/graph.js +120 -0
  64. package/dest/deploy/index.d.ts +19 -0
  65. package/dest/deploy/index.d.ts.map +1 -0
  66. package/dest/deploy/index.js +15 -0
  67. package/dest/deploy/reporter.d.ts +106 -0
  68. package/dest/deploy/reporter.d.ts.map +1 -0
  69. package/dest/deploy/reporter.js +76 -0
  70. package/dest/deploy/runner.d.ts +8 -0
  71. package/dest/deploy/runner.d.ts.map +1 -0
  72. package/dest/deploy/runner.js +886 -0
  73. package/dest/deploy/state.d.ts +19 -0
  74. package/dest/deploy/state.d.ts.map +1 -0
  75. package/dest/deploy/state.js +59 -0
  76. package/dest/deploy/types.d.ts +233 -0
  77. package/dest/deploy/types.d.ts.map +1 -0
  78. package/dest/deploy/types.js +9 -0
  79. package/dest/examples/token.js +3 -3
  80. package/dest/local-network/auth_registry.d.ts +5 -0
  81. package/dest/local-network/auth_registry.d.ts.map +1 -0
  82. package/dest/local-network/auth_registry.js +17 -0
  83. package/dest/local-network/banana_fpc.d.ts +3 -2
  84. package/dest/local-network/banana_fpc.d.ts.map +1 -1
  85. package/dest/local-network/banana_fpc.js +11 -7
  86. package/dest/local-network/local-network.d.ts +10 -32
  87. package/dest/local-network/local-network.d.ts.map +1 -1
  88. package/dest/local-network/local-network.js +60 -73
  89. package/dest/testing/cheat_codes.d.ts +17 -23
  90. package/dest/testing/cheat_codes.d.ts.map +1 -1
  91. package/dest/testing/cheat_codes.js +17 -43
  92. package/dest/testing/epoch_test_settler.d.ts +2 -2
  93. package/dest/testing/epoch_test_settler.d.ts.map +1 -1
  94. package/dest/testing/epoch_test_settler.js +6 -26
  95. package/dest/testing/index.d.ts +3 -2
  96. package/dest/testing/index.d.ts.map +1 -1
  97. package/dest/testing/index.js +2 -1
  98. package/dest/testing/local-network.d.ts +51 -0
  99. package/dest/testing/local-network.d.ts.map +1 -0
  100. package/dest/testing/local-network.js +60 -0
  101. package/dest/testing/token_allowed_setup.d.ts +12 -0
  102. package/dest/testing/token_allowed_setup.d.ts.map +1 -0
  103. package/dest/testing/token_allowed_setup.js +24 -0
  104. package/package.json +38 -35
  105. package/scripts/add_crate.sh +11 -60
  106. package/scripts/aztec.sh +9 -2
  107. package/scripts/init.sh +5 -5
  108. package/scripts/new.sh +2 -2
  109. package/scripts/setup_workspace.sh +3 -2
  110. package/scripts/templates/blank/contract/Nargo.toml +6 -0
  111. package/scripts/templates/blank/contract/src/main.nr +10 -0
  112. package/scripts/templates/blank/test/Nargo.toml +7 -0
  113. package/scripts/templates/blank/test/src/lib.nr +11 -0
  114. package/scripts/templates/counter/contract/Nargo.toml +7 -0
  115. package/scripts/templates/counter/contract/src/main.nr +48 -0
  116. package/scripts/templates/counter/test/Nargo.toml +7 -0
  117. package/scripts/templates/counter/test/src/lib.nr +32 -0
  118. package/src/bin/index.ts +4 -2
  119. package/src/cli/aztec_start_action.ts +44 -27
  120. package/src/cli/aztec_start_options.ts +28 -25
  121. package/src/cli/cmds/compile.ts +41 -20
  122. package/src/cli/cmds/profile.ts +2 -1
  123. package/src/cli/cmds/profile_flamegraph.ts +2 -1
  124. package/src/cli/cmds/profile_gates.ts +22 -5
  125. package/src/cli/cmds/prover.ts +42 -0
  126. package/src/cli/cmds/standby.ts +184 -0
  127. package/src/cli/cmds/start_bot.ts +9 -6
  128. package/src/cli/cmds/start_node.ts +46 -131
  129. package/src/cli/cmds/start_prover_agent.ts +5 -8
  130. package/src/cli/cmds/start_prover_broker.ts +23 -24
  131. package/src/cli/cmds/start_txe.ts +7 -5
  132. package/src/cli/cmds/utils/artifacts.ts +5 -0
  133. package/src/cli/cmds/utils/collect_crate_dirs.ts +118 -0
  134. package/src/cli/cmds/utils/needs_recompile.ts +98 -0
  135. package/src/cli/cmds/utils/warn_if_aztec_version_mismatch.ts +76 -0
  136. package/src/cli/util.ts +26 -100
  137. package/src/deploy/bridging.ts +191 -0
  138. package/src/deploy/fees.ts +322 -0
  139. package/src/deploy/graph.ts +137 -0
  140. package/src/deploy/index.ts +41 -0
  141. package/src/deploy/reporter.ts +184 -0
  142. package/src/deploy/runner.ts +936 -0
  143. package/src/deploy/state.ts +66 -0
  144. package/src/deploy/types.ts +244 -0
  145. package/src/examples/token.ts +11 -3
  146. package/src/local-network/auth_registry.ts +19 -0
  147. package/src/local-network/banana_fpc.ts +12 -8
  148. package/src/local-network/local-network.ts +67 -83
  149. package/src/testing/cheat_codes.ts +18 -49
  150. package/src/testing/epoch_test_settler.ts +8 -32
  151. package/src/testing/index.ts +2 -1
  152. package/src/testing/local-network.ts +97 -0
  153. package/src/testing/token_allowed_setup.ts +26 -0
  154. package/dest/cli/cmds/start_archiver.d.ts +0 -9
  155. package/dest/cli/cmds/start_archiver.d.ts.map +0 -1
  156. package/dest/cli/cmds/start_archiver.js +0 -48
  157. package/dest/cli/release_version.d.ts +0 -2
  158. package/dest/cli/release_version.d.ts.map +0 -1
  159. package/dest/cli/release_version.js +0 -14
  160. package/dest/testing/anvil_test_watcher.d.ts +0 -42
  161. package/dest/testing/anvil_test_watcher.d.ts.map +0 -1
  162. package/dest/testing/anvil_test_watcher.js +0 -181
  163. package/src/cli/cmds/start_archiver.ts +0 -50
  164. package/src/cli/release_version.ts +0 -21
  165. package/src/testing/anvil_test_watcher.ts +0 -210
@@ -0,0 +1,322 @@
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
+ */
12
+ import type { AztecAddress } from '@aztec/aztec.js/addresses';
13
+ import { FeeJuicePaymentMethodWithClaim, type FeePaymentMethod, SponsoredFeePaymentMethod } from '@aztec/aztec.js/fee';
14
+ import { Fr } from '@aztec/aztec.js/fields';
15
+ import type { AztecNode } from '@aztec/aztec.js/node';
16
+ import { FeeJuiceContract } from '@aztec/aztec.js/protocol';
17
+ import type { Wallet } from '@aztec/aztec.js/wallet';
18
+ import type { GasFees } from '@aztec/stdlib/gas';
19
+
20
+ import type { Hex } from 'viem';
21
+
22
+ import { registerDeployedSponsoredFPCInWalletAndGetAddress } from '../local-network/sponsored_fpc.js';
23
+ import { bridgeFeeJuice, waitForL1ToL2Message } from './bridging.js';
24
+ import type { AccountFunding, DeployReporter } from './reporter.js';
25
+ import type { DeployState } from './state.js';
26
+ import type { FeePolicy } from './types.js';
27
+
28
+ /** Anvil's first pre-funded dev key — used as the local-network L1 funder. Published, non-secret. */
29
+ const ANVIL_DEV_KEY: Hex = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80';
30
+ const DEFAULT_LOCAL_L1_RPC_URL = 'http://localhost:8545';
31
+ const DEFAULT_LOCAL_L1_CHAIN_ID = 31337;
32
+
33
+ /** The `fee` field of a send-options object. */
34
+ export interface SendFee {
35
+ paymentMethod?: FeePaymentMethod;
36
+ gasSettings?: { maxFeesPerGas: GasFees };
37
+ }
38
+
39
+ /**
40
+ * Sane fee defaults: local pays via SponsoredFPC; every other network pays from bridged Fee Juice.
41
+ * The threshold/fundAmount pair trades off L1 round-trips (too low → frequent re-bridges) against
42
+ * stranding Fee Juice, which is non-transferable, on the account (too high).
43
+ */
44
+ export function defaultFeePolicy(local: boolean): FeePolicy {
45
+ if (local) {
46
+ return { kind: 'sponsored' };
47
+ }
48
+ return {
49
+ kind: 'fee-juice',
50
+ threshold: 100n * 10n ** 18n, // 100 FJ
51
+ fundAmount: 1000n * 10n ** 18n, // 1000 FJ (non-faucet fallback amount)
52
+ };
53
+ }
54
+
55
+ /** The public Fee Juice balance of `address` (any address — contract or account), read via `from`. */
56
+ export async function publicFeeJuiceBalance(
57
+ wallet: Wallet,
58
+ address: AztecAddress,
59
+ from: AztecAddress,
60
+ ): Promise<bigint> {
61
+ const { result } = await FeeJuiceContract.at(wallet).methods.balance_of_public(address).simulate({ from });
62
+ return BigInt(result.toString());
63
+ }
64
+
65
+ /**
66
+ * Resolves an account's funding posture under `policy` — what the plan reports and what
67
+ * {@link prepareFeeSession} acts on. `idle` accounts (no pending work) are never funded; sponsored
68
+ * accounts never read a balance; fee-juice accounts are `funded` iff their balance clears the
69
+ * threshold, else `not-funded` (a bridge will top them up).
70
+ */
71
+ export async function accountFunding(
72
+ policy: FeePolicy,
73
+ wallet: Wallet,
74
+ account: AztecAddress,
75
+ hasWork: boolean,
76
+ ): Promise<AccountFunding> {
77
+ if (!hasWork) {
78
+ return { kind: 'idle' };
79
+ }
80
+ if (policy.kind === 'sponsored') {
81
+ return { kind: 'sponsored' };
82
+ }
83
+ const balance = await publicFeeJuiceBalance(wallet, account, account);
84
+ return balance >= policy.threshold
85
+ ? { kind: 'funded', balance }
86
+ : { kind: 'not-funded', balance, fundAmount: policy.fundAmount };
87
+ }
88
+
89
+ /**
90
+ * Resolves the L1 connection + funder for a bridge from caller-supplied config, defaulting to anvil
91
+ * on local. The funder key falls back to anvil's dev key on local (its faucet `mint` is owner-gated,
92
+ * so an ephemeral key is rejected there); elsewhere an omitted key means an ephemeral key + the
93
+ * public faucet. Deliberately no env fallback — the framework never reads the environment.
94
+ */
95
+ function resolveL1Config(
96
+ local: boolean,
97
+ cfg: { l1RpcUrl?: string; l1ChainId?: number; l1FunderKey?: Hex },
98
+ ): { l1RpcUrl: string; l1ChainId: number; l1PrivateKey?: Hex } {
99
+ const l1RpcUrl = cfg.l1RpcUrl ?? (local ? DEFAULT_LOCAL_L1_RPC_URL : undefined);
100
+ const l1ChainId = cfg.l1ChainId ?? (local ? DEFAULT_LOCAL_L1_CHAIN_ID : undefined);
101
+ if (l1RpcUrl === undefined || l1ChainId === undefined) {
102
+ throw new Error('Bridging on a non-local network requires `l1RpcUrl` and `l1ChainId` (no hardcoded defaults).');
103
+ }
104
+ return { l1RpcUrl, l1ChainId, l1PrivateKey: cfg.l1FunderKey ?? (local ? ANVIL_DEV_KEY : undefined) };
105
+ }
106
+
107
+ /** What {@link obtainFeeJuiceClaim} needs to produce a consumable claim for a recipient. */
108
+ export interface ObtainFeeJuiceClaimOpts {
109
+ /** Whether the target is a local (anvil) network — drives warp-vs-poll + L1 defaults. */
110
+ local: boolean;
111
+ node: AztecNode;
112
+ /** The node's URL — reaches its debug API for local time-warping while the bridge settles. */
113
+ nodeUrl?: string;
114
+ recipient: AztecAddress;
115
+ /** Amount to bridge (wei). */
116
+ amount: bigint;
117
+ /** L1 connection + funder, defaulted per {@link resolveL1Config}. */
118
+ l1: { l1FunderKey?: Hex; l1RpcUrl?: string; l1ChainId?: number };
119
+ state: DeployState;
120
+ persist: () => void;
121
+ reporter: DeployReporter;
122
+ }
123
+
124
+ /**
125
+ * A single-use Fee Juice claim for `recipient` (used by `fund` steps): resumes the persisted claim
126
+ * when present, else bridges `amount` from L1 and waits for the L1→L2 message. The claim persists
127
+ * before the wait, so a crash mid-wait resumes it instead of stranding the bridged funds. The
128
+ * caller consumes it (e.g. via `FeeJuice.claim`) and calls `onConsumed` once that tx mines.
129
+ */
130
+ export async function obtainFeeJuiceClaim(opts: ObtainFeeJuiceClaimOpts): Promise<{
131
+ claimAmount: bigint;
132
+ claimSecret: Fr;
133
+ messageLeafIndex: bigint;
134
+ /** Drops the persisted resume entry — call once the consuming tx mines. */
135
+ onConsumed: () => void;
136
+ }> {
137
+ const { local, node, nodeUrl, recipient, state, persist, reporter } = opts;
138
+ // Prefixed so a recipient that is also an auto-funded sender doesn't collide with its account claim.
139
+ const key = `fund:${recipient.toString()}`;
140
+ let claim: { claimAmount: bigint; claimSecret: Fr; messageLeafIndex: bigint };
141
+ const stored = state.pendingClaims[key];
142
+ if (stored) {
143
+ reporter.onBridge?.({ recipient, amount: BigInt(stored.claimAmount), reused: true });
144
+ claim = {
145
+ claimAmount: BigInt(stored.claimAmount),
146
+ claimSecret: Fr.fromString(stored.claimSecret),
147
+ messageLeafIndex: BigInt(stored.messageLeafIndex),
148
+ };
149
+ } else {
150
+ reporter.onBridge?.({ recipient, amount: opts.amount, reused: false });
151
+ const { l1RpcUrl, l1ChainId, l1PrivateKey } = resolveL1Config(local, opts.l1);
152
+ const bridged = await bridgeFeeJuice({ node, recipient, l1RpcUrl, l1ChainId, amount: opts.amount, l1PrivateKey });
153
+ state.pendingClaims[key] = {
154
+ claimAmount: bridged.claimAmount.toString(),
155
+ claimSecret: bridged.claimSecret.toString(),
156
+ messageLeafIndex: bridged.messageLeafIndex.toString(),
157
+ };
158
+ persist();
159
+ await waitForL1ToL2Message({
160
+ node,
161
+ messageHash: Fr.fromHexString(bridged.messageHash),
162
+ mode: local ? 'warp' : 'poll',
163
+ ...(nodeUrl ? { warpOpts: { nodeUrl } } : {}),
164
+ });
165
+ claim = {
166
+ claimAmount: bridged.claimAmount,
167
+ claimSecret: bridged.claimSecret,
168
+ messageLeafIndex: bridged.messageLeafIndex,
169
+ };
170
+ }
171
+ return {
172
+ ...claim,
173
+ onConsumed: () => {
174
+ delete state.pendingClaims[key];
175
+ persist();
176
+ },
177
+ };
178
+ }
179
+
180
+ /** Per-account fee dispensing for one run, prepared by {@link prepareFeeSession}. */
181
+ export interface FeeSession {
182
+ /**
183
+ * Fee options for the next tx from `account`, plus `onConsumed` to call after it lands (clears a
184
+ * one-time bridge claim from persisted state). Subsequent calls pay from balance.
185
+ */
186
+ next(account: AztecAddress): { fee: SendFee; onConsumed: () => void };
187
+ /**
188
+ * Whether `account`'s next tx will carry its one-time bridge claim. The runner serializes such an
189
+ * account's first tx: the claim must mine before its balance-paying txs fan out.
190
+ */
191
+ hasPendingClaim(account: AztecAddress): boolean;
192
+ }
193
+
194
+ /** What {@link prepareFeeSession} needs to fund a run's working accounts. */
195
+ export interface PrepareFeeSessionOpts {
196
+ /** Whether the target is a local (anvil) network — drives warp-vs-poll + L1 defaults. */
197
+ local: boolean;
198
+ node: AztecNode;
199
+ /** The node's URL — reaches its debug API for local time-warping while a bridge settles. */
200
+ nodeUrl?: string;
201
+ wallet: Wallet;
202
+ /**
203
+ * Working accounts (those with pending work) with their resolved {@link FeePolicy} + funding (from
204
+ * {@link accountFunding}) — so this function doesn't re-read balances.
205
+ */
206
+ accounts: { address: AztecAddress; policy: FeePolicy; funding: AccountFunding }[];
207
+ state: DeployState;
208
+ persist: () => void;
209
+ reporter: DeployReporter;
210
+ }
211
+
212
+ /**
213
+ * Resolves fees ahead of execution, per account: registers the shared SponsoredFPC (for sponsored
214
+ * accounts), or tops up a fee-juice account via a bridge (reusing a persisted pending claim when
215
+ * present). Returns a {@link FeeSession} that dispenses the right fee per tx, by sending account.
216
+ */
217
+ export async function prepareFeeSession(opts: PrepareFeeSessionOpts): Promise<FeeSession> {
218
+ const { local, node, nodeUrl, wallet, accounts, state, persist, reporter } = opts;
219
+
220
+ // Shared sponsored payment method: register the SponsoredFPC + read gas once, if anyone uses it.
221
+ let sponsoredFee: SendFee | undefined;
222
+ if (accounts.some(a => a.policy.kind === 'sponsored')) {
223
+ const sponsoredFPCAddress = await registerDeployedSponsoredFPCInWalletAndGetAddress(wallet);
224
+ sponsoredFee = {
225
+ paymentMethod: new SponsoredFeePaymentMethod(sponsoredFPCAddress),
226
+ // 10x headroom because this one quote is reused for every tx in the run (the wallet's default would re-quote
227
+ // per tx at 1.5x min): congestion pricing can push the min fee well past the starting quote over a run of
228
+ // parallel layers. Overstating the cap is free — txs pay the going rate, not the cap, and the FPC pays anyway.
229
+ gasSettings: { maxFeesPerGas: (await node.getCurrentMinFees()).mul(10) },
230
+ };
231
+ }
232
+
233
+ // Bridge fee-juice top-ups. The L1 sends stay sequential — a shared funder key would collide on
234
+ // nonces — but the L1→L2 availability waits (the minutes-long part on a real network) run
235
+ // concurrently afterwards. Warp-mode waits run inline instead: warping manipulates global time,
236
+ // so concurrent warps would fight. Each claim persists as soon as it exists on L1, so a crash
237
+ // mid-wait resumes it instead of stranding the bridged funds; a resumed claim skips the wait (by
238
+ // resume time the message is available on any live network).
239
+ const claims = new Map<string, FeeJuicePaymentMethodWithClaim>();
240
+ const messageWaits: Promise<void>[] = [];
241
+ for (const { address, policy, funding } of accounts) {
242
+ if (policy.kind !== 'fee-juice' || funding.kind === 'funded') {
243
+ continue;
244
+ }
245
+ const key = address.toString();
246
+ let stored = state.pendingClaims[key];
247
+ if (stored) {
248
+ reporter.onBridge?.({ recipient: address, amount: BigInt(stored.claimAmount), reused: true });
249
+ } else {
250
+ reporter.onBridge?.({ recipient: address, amount: policy.fundAmount, reused: false });
251
+ // Local defaults to anvil; a non-local network must supply L1 connection details.
252
+ const { l1ChainId, l1RpcUrl, l1PrivateKey } = resolveL1Config(local, policy);
253
+ const bridged = await bridgeFeeJuice({
254
+ node,
255
+ recipient: address,
256
+ l1RpcUrl,
257
+ l1ChainId,
258
+ amount: policy.fundAmount,
259
+ l1PrivateKey,
260
+ });
261
+ stored = {
262
+ claimAmount: bridged.claimAmount.toString(),
263
+ claimSecret: bridged.claimSecret.toString(),
264
+ messageLeafIndex: bridged.messageLeafIndex.toString(),
265
+ };
266
+ state.pendingClaims[key] = stored;
267
+ persist();
268
+ const wait = waitForL1ToL2Message({
269
+ node,
270
+ messageHash: Fr.fromHexString(bridged.messageHash),
271
+ mode: local ? 'warp' : 'poll',
272
+ ...(nodeUrl ? { warpOpts: { nodeUrl } } : {}),
273
+ });
274
+ if (local) {
275
+ await wait;
276
+ } else {
277
+ messageWaits.push(wait);
278
+ }
279
+ }
280
+ claims.set(
281
+ key,
282
+ new FeeJuicePaymentMethodWithClaim(address, {
283
+ claimAmount: BigInt(stored.claimAmount),
284
+ claimSecret: Fr.fromString(stored.claimSecret),
285
+ messageLeafIndex: BigInt(stored.messageLeafIndex),
286
+ }),
287
+ );
288
+ }
289
+ await Promise.all(messageWaits);
290
+
291
+ // Per-account dispenser state. A claim is single-use: the first `next()` for its account carries
292
+ // it, and `onConsumed` (invoked by the runner once that tx mines) drops the persisted resume entry.
293
+ const sessions = new Map<string, { sponsored: boolean; claim?: FeeJuicePaymentMethodWithClaim }>();
294
+ for (const { address, policy } of accounts) {
295
+ const key = address.toString();
296
+ sessions.set(key, { sponsored: policy.kind === 'sponsored', claim: claims.get(key) });
297
+ }
298
+
299
+ return {
300
+ next: account => {
301
+ const key = account.toString();
302
+ const session = sessions.get(key);
303
+ if (session?.sponsored) {
304
+ return { fee: sponsoredFee ?? {}, onConsumed: () => {} };
305
+ }
306
+ if (session?.claim) {
307
+ const claim = session.claim;
308
+ session.claim = undefined; // single-use: only this first tx carries it
309
+ return {
310
+ fee: { paymentMethod: claim },
311
+ onConsumed: () => {
312
+ // claim is now spent on-chain; drop its resume entry
313
+ delete state.pendingClaims[key];
314
+ persist();
315
+ },
316
+ };
317
+ }
318
+ return { fee: {}, onConsumed: () => {} }; // later txs (or already-funded): pay from the account's balance
319
+ },
320
+ hasPendingClaim: account => sessions.get(account.toString())?.claim !== undefined,
321
+ };
322
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Dependency-graph utilities for the deploy framework: topological layering (which steps
3
+ * can run together) and a pretty-printer for the resulting plan.
4
+ */
5
+
6
+ /**
7
+ * Group `nodes` into dependency layers (Kahn's algorithm). Each layer contains nodes whose
8
+ * dependencies all sit in earlier layers, so a layer's nodes are mutually independent and
9
+ * may run in parallel. Dependencies pointing outside `nodes` (e.g. already-satisfied work)
10
+ * are treated as satisfied. Throws on a cycle.
11
+ */
12
+ export function topologicalLayers(nodes: string[], dependencies: Map<string, string[]>): string[][] {
13
+ const remaining = new Set(nodes);
14
+ const layers: string[][] = [];
15
+ while (remaining.size > 0) {
16
+ // A node is ready when every dependency already sits in an earlier layer (i.e. is no longer in `remaining`).
17
+ const layer = [...remaining].filter(node =>
18
+ (dependencies.get(node) ?? []).every(dependency => !remaining.has(dependency)),
19
+ );
20
+ if (layer.length === 0) {
21
+ throw new Error(`Dependency cycle among: ${[...remaining].join(', ')}`);
22
+ }
23
+ for (const node of layer) {
24
+ remaining.delete(node);
25
+ }
26
+ layers.push(layer);
27
+ }
28
+ return layers;
29
+ }
30
+
31
+ /**
32
+ * Like {@link topologicalLayers}, but nodes for which `floatLate(node)` is true are scheduled as
33
+ * LATE as their dependents allow (ALAP) instead of as early as possible. Used to push batchable
34
+ * actions into the latest layer they can share, so same-account actions in adjacent layers coalesce
35
+ * into one tx. Fixed nodes (e.g. contract publishes, which unblock dependents and don't batch) keep
36
+ * their earliest layer; the relative order — and so the critical-path length — is unchanged. Throws
37
+ * on a cycle (via {@link topologicalLayers}).
38
+ */
39
+ export function scheduleLayers(
40
+ nodes: string[],
41
+ dependencies: Map<string, string[]>,
42
+ floatLate: (node: string) => boolean,
43
+ ): string[][] {
44
+ const asap = topologicalLayers(nodes, dependencies);
45
+ if (asap.length === 0) {
46
+ return [];
47
+ }
48
+ const lastLayer = asap.length - 1;
49
+
50
+ const nodeSet = new Set(nodes);
51
+ const layerOf = new Map<string, number>();
52
+ for (const [index, layer] of asap.entries()) {
53
+ for (const node of layer) {
54
+ layerOf.set(node, index);
55
+ }
56
+ }
57
+
58
+ // Reverse adjacency: which in-set nodes depend on each node.
59
+ const dependents = new Map<string, string[]>();
60
+ for (const node of nodes) {
61
+ for (const dependency of dependencies.get(node) ?? []) {
62
+ if (!nodeSet.has(dependency)) {
63
+ continue;
64
+ }
65
+ const list = dependents.get(dependency);
66
+ if (list) {
67
+ list.push(node);
68
+ } else {
69
+ dependents.set(dependency, [node]);
70
+ }
71
+ }
72
+ }
73
+
74
+ // Push floating nodes as late as possible, visiting in reverse topological order (the flattened
75
+ // ASAP order reversed) so every node is placed after all of its dependents are placed.
76
+ for (const node of asap.flat().reverse()) {
77
+ if (!floatLate(node)) {
78
+ continue;
79
+ }
80
+ const deps = dependents.get(node) ?? [];
81
+ const latest = deps.length === 0 ? lastLayer : Math.min(...deps.map(d => layerOf.get(d)!)) - 1;
82
+ layerOf.set(node, Math.max(layerOf.get(node)!, latest));
83
+ }
84
+
85
+ const layers: string[][] = Array.from({ length: asap.length }, () => []);
86
+ for (const node of nodes) {
87
+ layers[layerOf.get(node)!].push(node);
88
+ }
89
+ return layers.filter(layer => layer.length > 0);
90
+ }
91
+
92
+ /** One node in the printed plan. */
93
+ export interface PlanRow {
94
+ /** e.g. "goCoin" */
95
+ name: string;
96
+ /** short tag, e.g. "Token · publishes class" */
97
+ tag?: string;
98
+ /** dependency names to show as `← a, b` */
99
+ dependencies?: string[];
100
+ }
101
+
102
+ /**
103
+ * Render a titled flat list of plan rows (no layer grouping). Use for the declared-contracts
104
+ * overview, whose `← ...` arrows are constructor-arg references — not an execution order.
105
+ */
106
+ export function formatList(title: string, rows: PlanRow[]): string {
107
+ if (rows.length === 0) {
108
+ return `${title}: (none)`;
109
+ }
110
+ const lines = [`${title}:`];
111
+ for (const row of rows) {
112
+ const dependencies = row.dependencies && row.dependencies.length ? ` ← ${row.dependencies.join(', ')}` : '';
113
+ const tag = row.tag ? ` [${row.tag}]` : '';
114
+ lines.push(` ${row.name}${tag}${dependencies}`);
115
+ }
116
+ return lines.join('\n');
117
+ }
118
+
119
+ /**
120
+ * Render a titled, layer-grouped section of the plan as an indented tree. Each layer's txs are
121
+ * submitted in parallel.
122
+ */
123
+ export function formatLayers(title: string, layers: PlanRow[][]): string {
124
+ if (layers.length === 0) {
125
+ return `${title}: (none)`;
126
+ }
127
+ const lines = [`${title}:`];
128
+ for (const [index, layer] of layers.entries()) {
129
+ lines.push(` layer ${index + 1}${layer.length > 1 ? ' (parallel)' : ''}`);
130
+ for (const row of layer) {
131
+ const dependencies = row.dependencies && row.dependencies.length ? ` ← ${row.dependencies.join(', ')}` : '';
132
+ const tag = row.tag ? ` [${row.tag}]` : '';
133
+ lines.push(` ${row.name}${tag}${dependencies}`);
134
+ }
135
+ }
136
+ return lines.join('\n');
137
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * A minimal, declarative deployment framework for Aztec.
3
+ *
4
+ * Describe the accounts you send from and a graph of steps — contracts that must end up on-chain
5
+ * (deterministic addresses, interdependencies via `initializerArgs`) and the txs to send — plus how
6
+ * fees are paid; then {@link runDeployment} resolves, takes an on-chain inventory, funds, and
7
+ * executes only what's missing in dependency order — idempotently and resumably. The framework
8
+ * never reads the environment; callers pipe in secrets and config.
9
+ *
10
+ * Node-only: pulls in the PXE-backed `EmbeddedWallet`, `@aztec/noir-contracts.js`, and (for the
11
+ * `fee-juice` policy) L1 bridging — none browser-safe. Lives under the `@aztec/aztec/deploy` subpath
12
+ * so it stays out of any browser bundle.
13
+ */
14
+ export { runDeployment } from './runner.js';
15
+ export { defaultFeePolicy } from './fees.js';
16
+ export { consoleReporter } from './reporter.js';
17
+ export type {
18
+ DeployReporter,
19
+ DeployPlan,
20
+ DeployPlanAccount,
21
+ DeployPlanStep,
22
+ AccountFunding,
23
+ DeploySummary,
24
+ DeployUnitInfo,
25
+ DeployUnitResult,
26
+ DeployUnitKind,
27
+ BridgeEvent,
28
+ } from './reporter.js';
29
+ export type {
30
+ DeploymentSpec,
31
+ AccountSpec,
32
+ ContractStep,
33
+ ActionStep,
34
+ FundStep,
35
+ StepSpec,
36
+ Steps,
37
+ GeneratedContractClass,
38
+ FeePolicy,
39
+ Resolver,
40
+ Ctx,
41
+ } from './types.js';
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Observability for the deploy framework. {@link runDeployment} emits structured lifecycle events
3
+ * to a {@link DeployReporter} instead of writing to the console directly, so callers control where
4
+ * the signal goes: the default ({@link consoleReporter}) renders human-readably to **stderr** —
5
+ * keeping stdout clear for the deploy scripts' `export KEY=VAL` lines, which an orchestrator evals —
6
+ * while e2e, a progress UI, or structured CI logging can inject their own reporter and consume the
7
+ * events as data. Every hook is optional; an empty `{}` is a valid (silent) reporter.
8
+ */
9
+ import type { AztecAddress } from '@aztec/aztec.js/addresses';
10
+ import type { TxHash } from '@aztec/stdlib/tx';
11
+
12
+ import { formatLayers, formatList } from './graph.js';
13
+
14
+ /** What a unit did: publish a contract, send an action's tx, or fund an address with Fee Juice. */
15
+ export type DeployUnitKind = 'publish' | 'action' | 'fund';
16
+
17
+ /** Identity of one execution unit (a single tx), as reported by the unit lifecycle hooks. */
18
+ export interface DeployUnitInfo {
19
+ /** Human label, e.g. `publish goCoin`, `action mintGoCoin`. */
20
+ label: string;
21
+ kind: DeployUnitKind;
22
+ /** The account that sends and pays for this tx. */
23
+ account: AztecAddress;
24
+ }
25
+
26
+ /** What a unit produced once its tx settled. Fields beyond `durationMs` come from the receipt. */
27
+ export interface DeployUnitResult {
28
+ txHash?: TxHash;
29
+ blockNumber?: number;
30
+ feePaid?: bigint;
31
+ status?: string;
32
+ durationMs: number;
33
+ }
34
+
35
+ /** An account's funding posture for this run, as resolved at planning time. */
36
+ export type AccountFunding =
37
+ | { kind: 'idle' } // no pending work this run, so funding is moot
38
+ | { kind: 'sponsored' } // a SponsoredFPC pays
39
+ | { kind: 'funded'; balance: bigint } // pays from its own Fee Juice
40
+ | { kind: 'not-funded'; balance: bigint; fundAmount: bigint }; // will bridge before paying
41
+
42
+ export interface DeployPlanAccount {
43
+ alias: string;
44
+ address: AztecAddress;
45
+ funding: AccountFunding;
46
+ }
47
+
48
+ export interface DeployPlanStep {
49
+ id: string;
50
+ kind: 'contract' | 'action' | 'fund';
51
+ /**
52
+ * Status at the start of the run: a contract is `published` / `to publish` (public) or
53
+ * `registered` (private); an action is `done` / `to run`; a fund step is `funded` / `to fund`.
54
+ */
55
+ status: 'published' | 'to publish' | 'registered' | 'done' | 'to run' | 'funded' | 'to fund';
56
+ /** Steps it depends on (constructor-arg refs and explicit `dependsOn`). */
57
+ dependsOn: string[];
58
+ }
59
+
60
+ export interface DeployPlan {
61
+ /** Human label for the target (e.g. `local`, or a caller-chosen name). */
62
+ label: string;
63
+ accounts: DeployPlanAccount[];
64
+ steps: DeployPlanStep[];
65
+ /** Execution layers (step ids) — what will actually run, in dependency order. A layer runs parallel. */
66
+ layers: string[][];
67
+ }
68
+
69
+ export interface DeploySummary {
70
+ label: string;
71
+ contracts: { alias: string; address: AztecAddress; status: 'published' | 'registered' }[];
72
+ accounts: { alias: string; address: AztecAddress }[];
73
+ }
74
+
75
+ export interface BridgeEvent {
76
+ recipient: AztecAddress;
77
+ amount: bigint;
78
+ /** True when resuming a persisted claim instead of bridging anew. */
79
+ reused: boolean;
80
+ }
81
+
82
+ /** Lifecycle hooks the framework emits during a run. All optional — implement only what you need. */
83
+ export interface DeployReporter {
84
+ /** The resolved plan, before execution. */
85
+ onPlan?(plan: DeployPlan): void;
86
+ /** Everything is already on-chain; nothing will be sent. */
87
+ onNothingToDo?(label: string): void;
88
+ /** An account's Fee Juice is being topped up (or a persisted claim is being resumed). */
89
+ onBridge?(event: BridgeEvent): void;
90
+ /** A unit's tx is about to be sent. */
91
+ onUnitStart?(unit: DeployUnitInfo): void;
92
+ /** A unit's tx settled successfully. */
93
+ onUnitSettled?(unit: DeployUnitInfo, result: DeployUnitResult): void;
94
+ /** A unit's tx threw; the run will abort after this. */
95
+ onUnitError?(unit: DeployUnitInfo, error: unknown): void;
96
+ /** The run finished; `summary` holds the final resolved state. */
97
+ onComplete?(summary: DeploySummary): void;
98
+ }
99
+
100
+ const MS_PER_SECOND = 1000;
101
+ const WEI_PER_FEE_JUICE = 10n ** 18n;
102
+ const seconds = (ms: number): string => `${(ms / MS_PER_SECOND).toFixed(1)}s`;
103
+ const feeJuice = (wei: bigint): string => `${wei / WEI_PER_FEE_JUICE} FJ`;
104
+
105
+ function describeFunding(f: AccountFunding): string {
106
+ switch (f.kind) {
107
+ case 'idle':
108
+ return 'idle (no work)';
109
+ case 'sponsored':
110
+ return 'sponsored';
111
+ case 'funded':
112
+ return `funded (${feeJuice(f.balance)})`;
113
+ case 'not-funded':
114
+ return `not funded (${feeJuice(f.balance)}) → will bridge ${feeJuice(f.fundAmount)}`;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * The default reporter: renders events human-readably to **stderr**. Stderr (not stdout) so the
120
+ * traces survive an orchestrator that captures stdout for the scripts' `export` lines.
121
+ */
122
+ export function consoleReporter(): DeployReporter {
123
+ const log = (line: string): void => void process.stderr.write(`${line}\n`);
124
+ return {
125
+ onPlan(plan) {
126
+ log(`\n── Plan (${plan.label}) ──`);
127
+ log(
128
+ formatList(
129
+ 'accounts',
130
+ plan.accounts.map(a => ({ name: a.alias, tag: describeFunding(a.funding) })),
131
+ ),
132
+ );
133
+ log(
134
+ formatList(
135
+ 'steps',
136
+ plan.steps.map(s => ({
137
+ name: s.id,
138
+ tag: `${s.kind} · ${s.status}`,
139
+ dependencies: s.dependsOn,
140
+ })),
141
+ ),
142
+ );
143
+ log(
144
+ formatLayers(
145
+ 'execution layers',
146
+ plan.layers.map(layer => layer.map(name => ({ name }))),
147
+ ),
148
+ );
149
+ },
150
+ onNothingToDo(label) {
151
+ log(`\nNothing to do on ${label} — everything is already on-chain.`);
152
+ },
153
+ onBridge({ recipient, amount, reused }) {
154
+ log(
155
+ reused
156
+ ? `Reusing a pending bridge claim for ${recipient} (resuming a top-up).`
157
+ : `Bridging ${amount} Fee Juice to ${recipient} (this can take a few minutes)...`,
158
+ );
159
+ },
160
+ onUnitStart(unit) {
161
+ log(`→ ${unit.label}...`);
162
+ },
163
+ onUnitSettled(unit, result) {
164
+ const bits = [
165
+ result.txHash ? `tx ${result.txHash.toString().slice(0, 10)}…` : undefined,
166
+ result.blockNumber != null ? `block ${result.blockNumber}` : undefined,
167
+ seconds(result.durationMs),
168
+ ].filter(Boolean);
169
+ log(`✓ ${unit.label} ${bits.join(' ')}`);
170
+ },
171
+ onUnitError(unit, error) {
172
+ log(`✗ ${unit.label} failed: ${error instanceof Error ? error.message : String(error)}`);
173
+ },
174
+ onComplete(summary) {
175
+ log(`\n── Deployed to ${summary.label} ──`);
176
+ for (const c of summary.contracts) {
177
+ log(` ${c.alias.padEnd(16)} ${c.address} (${c.status})`);
178
+ }
179
+ for (const a of summary.accounts) {
180
+ log(` account ${a.alias}: ${a.address}`);
181
+ }
182
+ },
183
+ };
184
+ }