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

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
@@ -0,0 +1,993 @@
1
+ /**
2
+ * The deployment engine: turns a declarative {@link DeploymentSpec} into one dependency graph of
3
+ * steps (contracts + actions), runs only what's missing, and is safe to re-run.
4
+ *
5
+ * resolve accounts → resolve deterministic addresses → inventory → plan → fund → execute → output
6
+ *
7
+ * Each phase is a method on {@link DeploymentRun}, which holds the state the phases share;
8
+ * {@link runDeployment} strings them together in the order above.
9
+ *
10
+ * - Deterministic contracts (addresses are a pure function of class/deployer/salt/args) resolve
11
+ * UPFRONT, so the plan knows their addresses before anything is sent.
12
+ * - Deferred contracts (args read runtime state) resolve at INVENTORY TIME when the state their
13
+ * args read already exists (the re-run case, which is what makes re-runs no-ops), and otherwise
14
+ * AT EXECUTION TIME, once their `dependsOn` has run.
15
+ * - Steps execute in topological layers over the single graph, so an action can precede a contract
16
+ * it sets up. Within a layer, contract publishes are individual txs and same-account actions batch
17
+ * into BatchCalls sized to leave room for the fee payment's calls (the entrypoint's limit
18
+ * counts those too). The one-time fee-juice claim per account is
19
+ * consumed + mined by that account's first tx before the rest fan out.
20
+ * - Fund steps provision arbitrary addresses (contracts or accounts that never send) with bridged
21
+ * Fee Juice: bridge at execution time, then an L2 claim tx from the step's `from` account. Their
22
+ * claims persist between bridge and claim, so a crashed run resumes instead of re-bridging.
23
+ */ import { AztecAddress } from '@aztec-labs/aztec.js/addresses';
24
+ import { BatchCall, DeployMethod } from '@aztec-labs/aztec.js/contracts';
25
+ import { Fr } from '@aztec-labs/aztec.js/fields';
26
+ import { createAztecNodeClient } from '@aztec-labs/aztec.js/node';
27
+ import { FeeJuiceContract } from '@aztec-labs/aztec.js/protocol';
28
+ import { APP_MAX_CALLS } from '@aztec-labs/entrypoints/encoding';
29
+ import { chunk, compactArray } from '@aztec-labs/foundation/collection';
30
+ import { getPXEConfig } from '@aztec-labs/pxe/server';
31
+ import { getContractClassFromArtifact, getContractInstanceFromInstantiationParams } from '@aztec-labs/stdlib/contract';
32
+ import { deriveKeys, deriveMasterMessageSigningSecretKey } from '@aztec-labs/stdlib/keys';
33
+ import { EmbeddedWallet } from '@aztec-labs/wallets/embedded';
34
+ import { join } from 'node:path';
35
+ import { accountFunding, defaultFeePolicy, obtainFeeJuiceClaim, prepareFeeSession, publicFeeJuiceBalance } from './fees.js';
36
+ import { scheduleLayers, topologicalLayers } from './graph.js';
37
+ import { consoleReporter } from './reporter.js';
38
+ import { loadState, saveState } from './state.js';
39
+ /** A step's inventory check (an action's gate, a fund step's balance, a deferred contract's args) waits on itself. */ class GateCycleError extends Error {
40
+ constructor(message){
41
+ super(message);
42
+ this.name = 'GateCycleError';
43
+ }
44
+ }
45
+ function getOrThrow(map, alias, kind) {
46
+ const value = map.get(alias);
47
+ if (value === undefined) {
48
+ throw new Error(`Unknown ${kind} "${alias}".`);
49
+ }
50
+ return value;
51
+ }
52
+ function isDeferred(step) {
53
+ return step.deferredInitializerArgs != null;
54
+ }
55
+ /** The account that sends (and pays for) a contract step's publish tx. */ function contractSender(step) {
56
+ return step.universal ? step.from : step.deployer;
57
+ }
58
+ /**
59
+ * The contract aliases a pure resolver callback looks up, extracted by dry-running it against a
60
+ * resolver that records each `contract(alias)` lookup instead of resolving it. The callback's return
61
+ * value is discarded and the ZERO addresses never leave this function — which is what requires such
62
+ * callbacks to be pure: they run here with fake addresses and again later with real ones.
63
+ */ function referencedContracts(run) {
64
+ const references = new Set();
65
+ run({
66
+ account: ()=>AztecAddress.ZERO,
67
+ contract: (alias)=>{
68
+ references.add(alias);
69
+ return AztecAddress.ZERO;
70
+ }
71
+ });
72
+ return [
73
+ ...references
74
+ ];
75
+ }
76
+ /**
77
+ * Runs a {@link DeploymentSpec}: resolves accounts and deterministic addresses, inventories what's
78
+ * already on-chain, reports the plan, funds the working accounts, and executes the missing steps in
79
+ * dependency layers. Idempotent — a re-run sends nothing when everything is already in place.
80
+ */ export async function runDeployment(spec) {
81
+ const run = await DeploymentRun.create(spec);
82
+ await run.resolveDeterministicContracts();
83
+ await run.takeInventory();
84
+ const plan = await run.reportPlan();
85
+ if (run.hasNothingToDo()) {
86
+ run.reportNothingToDo();
87
+ await run.writeOutputs();
88
+ return;
89
+ }
90
+ const feeSession = await run.prepareFees(plan);
91
+ await run.executeLayers(feeSession);
92
+ await run.writeOutputs();
93
+ run.reportSummary();
94
+ }
95
+ /**
96
+ * One deployment run: the state shared across phases, with one method per phase. Build with
97
+ * {@link DeploymentRun.create}, then call the phase methods in the order {@link runDeployment}
98
+ * does — each phase reads state the earlier ones populated.
99
+ */ class DeploymentRun {
100
+ spec;
101
+ node;
102
+ wallet;
103
+ local;
104
+ label;
105
+ reporter;
106
+ stateDirectory;
107
+ state;
108
+ defaultSalt;
109
+ globalPolicy;
110
+ // The steps map partitioned by kind once, so lookups are typed without casts.
111
+ steps;
112
+ contractSteps;
113
+ actionSteps;
114
+ fundSteps;
115
+ /** Contract→contract address deps, auto-derived from deterministic `initializerArgs`. */ contractRefs;
116
+ // Populated as accounts resolve, contracts resolve (upfront, at inventory, or deferred at
117
+ // execution), and txs land.
118
+ accountAddresses;
119
+ policyByAddress;
120
+ contractAddresses;
121
+ contractInstances;
122
+ deployMethods;
123
+ classIds;
124
+ publishedThisRun;
125
+ classesPublishedThisRun;
126
+ publishedCache;
127
+ gateCache;
128
+ deferredCache;
129
+ fundGateCache;
130
+ /** Which pending inventory checks each in-flight check is waiting on — see {@link memoizedCheck}. */ waitingOn;
131
+ // Populated by the resolve / inventory / plan phases.
132
+ resolveOrder;
133
+ actionsToRun;
134
+ fundsToRun;
135
+ execAliases;
136
+ layers;
137
+ resolver;
138
+ ctx;
139
+ /** Set only when the spec gave a URL — a connected node serves the debug API for warping itself. */ nodeUrl;
140
+ constructor(spec, node, wallet){
141
+ this.spec = spec;
142
+ this.node = node;
143
+ this.wallet = wallet;
144
+ this.contractSteps = new Map();
145
+ this.actionSteps = new Map();
146
+ this.fundSteps = new Map();
147
+ this.accountAddresses = new Map();
148
+ this.policyByAddress = new Map();
149
+ this.contractAddresses = new Map();
150
+ this.contractInstances = new Map();
151
+ this.deployMethods = new Map();
152
+ this.classIds = new Map();
153
+ this.publishedThisRun = new Set();
154
+ this.classesPublishedThisRun = new Set();
155
+ this.publishedCache = new Map();
156
+ this.gateCache = new Map();
157
+ this.deferredCache = new Map();
158
+ this.fundGateCache = new Map();
159
+ this.waitingOn = new Map();
160
+ this.resolveOrder = [];
161
+ this.actionsToRun = new Set();
162
+ this.fundsToRun = new Set();
163
+ this.execAliases = [];
164
+ this.layers = [];
165
+ this.nodeUrl = typeof spec.node === 'string' ? spec.node : undefined;
166
+ this.local = spec.local ?? false;
167
+ this.label = spec.label ?? (this.local ? 'local' : 'network');
168
+ this.reporter = spec.reporter ?? consoleReporter();
169
+ this.stateDirectory = spec.stateDir ?? join(process.cwd(), '.deploy-state');
170
+ this.state = loadState(this.stateDirectory);
171
+ this.defaultSalt = spec.salt ?? new Fr(0);
172
+ this.globalPolicy = spec.fees ?? defaultFeePolicy(this.local);
173
+ this.steps = new Map(Object.entries(spec.steps));
174
+ for (const [alias, step] of this.steps){
175
+ if (step.kind === 'contract') {
176
+ this.contractSteps.set(alias, step);
177
+ } else if (step.kind === 'action') {
178
+ this.actionSteps.set(alias, step);
179
+ } else {
180
+ this.fundSteps.set(alias, step);
181
+ }
182
+ }
183
+ this.contractRefs = this.recordContractRefs();
184
+ this.resolver = {
185
+ account: (alias)=>getOrThrow(this.accountAddresses, alias, 'account'),
186
+ contract: (alias)=>getOrThrow(this.contractAddresses, alias, 'contract')
187
+ };
188
+ this.ctx = {
189
+ ...this.resolver,
190
+ instance: (alias)=>getOrThrow(this.contractInstances, alias, 'contract instance'),
191
+ done: (id)=>this.done(id, undefined),
192
+ ran: (id)=>this.ran(id, undefined),
193
+ wallet,
194
+ node
195
+ };
196
+ }
197
+ /** Validates the spec, connects the node + ephemeral wallet, then resolves accounts and class ids. */ static async create(spec) {
198
+ DeploymentRun.validateSpec(spec);
199
+ const node = typeof spec.node === 'string' ? createAztecNodeClient(spec.node) : spec.node;
200
+ const wallet = await EmbeddedWallet.create(node, {
201
+ ephemeral: true,
202
+ pxeConfig: {
203
+ ...getPXEConfig(),
204
+ proverEnabled: !(spec.local ?? false)
205
+ }
206
+ });
207
+ const run = new DeploymentRun(spec, node, wallet);
208
+ await run.resolveAccounts();
209
+ await run.computeClassIds();
210
+ return run;
211
+ }
212
+ /** Static spec validation — everything that can be rejected before touching the network. */ static validateSpec(spec) {
213
+ if (!spec.node) {
214
+ throw new Error('runDeployment requires a `node` on the spec — a JSON-RPC URL or a connected node.');
215
+ }
216
+ const steps = Object.entries(spec.steps);
217
+ const aliases = new Set(steps.map(([alias])=>alias));
218
+ for (const [alias, step] of steps){
219
+ for (const dependency of step.dependsOn ?? []){
220
+ if (!aliases.has(dependency)) {
221
+ throw new Error(`Unknown step "${dependency}" in dependsOn of "${alias}".`);
222
+ }
223
+ }
224
+ if (step.kind === 'fund' && step.amount <= 0n) {
225
+ throw new Error(`Fund step "${alias}" must bridge a positive amount.`);
226
+ }
227
+ if (step.kind !== 'contract') {
228
+ continue;
229
+ }
230
+ if (step.initializerArgs && step.deferredInitializerArgs) {
231
+ throw new Error(`Contract "${alias}" declares both initializerArgs and deferredInitializerArgs — pick one.`);
232
+ }
233
+ if (!isDeferred(step)) {
234
+ continue;
235
+ }
236
+ if (step.mode === 'register') {
237
+ throw new Error(`Contract "${alias}" is register-mode with deferred args — registration has no tx to defer.`);
238
+ }
239
+ if (step.dependsOn == null) {
240
+ throw new Error(`Contract "${alias}" has deferred args but no dependsOn. Declare the steps whose effects the args read,` + ` or an explicit empty array if they only read pre-existing state.`);
241
+ }
242
+ }
243
+ // A declared cycle never becomes ready, and inventory only notices it when the checks involved
244
+ // happen to consult each other — so reject it before touching the network.
245
+ topologicalLayers([
246
+ ...aliases
247
+ ], new Map(steps.map(([alias, step])=>[
248
+ alias,
249
+ step.dependsOn ?? []
250
+ ])));
251
+ }
252
+ /** Resolves every deterministic contract upfront, layer by layer in constructor-arg dependency order. */ async resolveDeterministicContracts() {
253
+ const deterministicAliases = [
254
+ ...this.contractSteps
255
+ ].filter(([, step])=>!isDeferred(step)).map(([alias])=>alias);
256
+ const layers = topologicalLayers(deterministicAliases, this.contractRefs);
257
+ this.resolveOrder = layers.flat();
258
+ for (const layer of layers){
259
+ await Promise.all(layer.map((alias)=>{
260
+ const step = getOrThrow(this.contractSteps, alias, 'contract');
261
+ return this.resolveContract(alias, step, step.initializerArgs?.(this.resolver) ?? []);
262
+ }));
263
+ }
264
+ }
265
+ /** Inventory: which steps still need doing? */ async takeInventory() {
266
+ // Deterministic publishes missing on-chain. The checks are independent node reads, so they run
267
+ // concurrently.
268
+ const missing = await Promise.all(this.resolveOrder.map(async (alias)=>{
269
+ const step = getOrThrow(this.contractSteps, alias, 'contract');
270
+ return step.mode === 'publish' && !await this.isPublished(alias) ? alias : undefined;
271
+ }));
272
+ for (const alias of compactArray(missing)){
273
+ this.publishedThisRun.add(alias);
274
+ }
275
+ // The remaining checks consult each other (a deferred contract waits on the steps it declares, a
276
+ // gate on the contracts it reads, `ctx.done`/`ctx.ran` on any step), so each is evaluated on
277
+ // demand and memoized: whichever check reaches a step first decides it, and every later one
278
+ // reuses that answer. These loops only make sure every step is decided, in any order.
279
+ // Deferred contracts. On a re-run the state their args read is already on-chain, so the address
280
+ // derives and publication is checked like any other contract (which is what makes re-runs
281
+ // no-ops); otherwise the contract publishes this run and re-resolves at execution time.
282
+ for (const [alias, step] of this.contractSteps){
283
+ if (isDeferred(step) && await this.deferredPublishes(alias, undefined)) {
284
+ this.publishedThisRun.add(alias);
285
+ }
286
+ }
287
+ // Fund gates: recipients whose public Fee Juice balance is below the step's threshold.
288
+ for (const alias of this.fundSteps.keys()){
289
+ if (!await this.fundGate(alias, undefined)) {
290
+ this.fundsToRun.add(alias);
291
+ }
292
+ }
293
+ // Action gates.
294
+ for (const alias of this.actionSteps.keys()){
295
+ if (!await this.actionGate(alias, undefined)) {
296
+ this.actionsToRun.add(alias);
297
+ }
298
+ }
299
+ this.execAliases = [
300
+ ...[
301
+ ...this.contractSteps.keys()
302
+ ].filter((alias)=>this.publishedThisRun.has(alias)),
303
+ ...[
304
+ ...this.fundSteps.keys()
305
+ ].filter((alias)=>this.fundsToRun.has(alias)),
306
+ ...[
307
+ ...this.actionSteps.keys()
308
+ ].filter((alias)=>this.actionsToRun.has(alias))
309
+ ];
310
+ }
311
+ /**
312
+ * Builds the plan — account funding postures, per-step statuses, and the execution layers — and
313
+ * reports it (the default reporter renders it to stderr). The fund phase consumes its accounts.
314
+ */ async reportPlan() {
315
+ const accountUsedBy = new Set();
316
+ for (const alias of this.execAliases){
317
+ const step = getOrThrow(this.steps, alias, 'step');
318
+ const address = step.kind === 'contract' ? contractSender(step)(this.resolver) : step.from(this.resolver);
319
+ accountUsedBy.add(address.toString());
320
+ }
321
+ const stepStatus = (alias, step)=>{
322
+ if (step.kind === 'action') {
323
+ return this.actionsToRun.has(alias) ? 'to run' : 'done';
324
+ }
325
+ if (step.kind === 'fund') {
326
+ return this.fundsToRun.has(alias) ? 'to fund' : 'funded';
327
+ }
328
+ if (step.mode === 'register') {
329
+ return 'registered';
330
+ }
331
+ return this.publishedThisRun.has(alias) ? 'to publish' : 'published';
332
+ };
333
+ this.layers = this.buildLayers();
334
+ const plan = {
335
+ label: this.label,
336
+ accounts: await Promise.all(Object.keys(this.spec.accounts).map(async (alias)=>{
337
+ const address = getOrThrow(this.accountAddresses, alias, 'account');
338
+ const policy = getOrThrow(this.policyByAddress, address.toString(), 'policy');
339
+ return {
340
+ alias,
341
+ address,
342
+ funding: await accountFunding(policy, this.wallet, address, accountUsedBy.has(address.toString()))
343
+ };
344
+ })),
345
+ steps: [
346
+ ...this.steps
347
+ ].map(([id, step])=>({
348
+ id,
349
+ kind: step.kind,
350
+ status: stepStatus(id, step),
351
+ dependsOn: [
352
+ ...this.contractRefs.get(id) ?? [],
353
+ ...step.dependsOn ?? []
354
+ ]
355
+ })),
356
+ layers: this.layers
357
+ };
358
+ this.reporter.onPlan?.(plan);
359
+ return plan;
360
+ }
361
+ hasNothingToDo() {
362
+ return this.execAliases.length === 0;
363
+ }
364
+ reportNothingToDo() {
365
+ this.reporter.onNothingToDo?.(this.label);
366
+ }
367
+ /**
368
+ * Fund phase: prepares each working account's fee session per its resolved policy + funding
369
+ * (bridging Fee Juice when needed). The session owns all claim state — see
370
+ * {@link FeeSession.hasPendingClaim}.
371
+ */ prepareFees(plan) {
372
+ return prepareFeeSession({
373
+ local: this.local,
374
+ node: this.node,
375
+ nodeUrl: this.nodeUrl,
376
+ wallet: this.wallet,
377
+ state: this.state,
378
+ persist: ()=>this.persist(),
379
+ reporter: this.reporter,
380
+ accounts: plan.accounts.filter((a)=>a.funding.kind !== 'idle').map((a)=>({
381
+ address: a.address,
382
+ policy: getOrThrow(this.policyByAddress, a.address.toString(), 'policy'),
383
+ funding: a.funding
384
+ }))
385
+ });
386
+ }
387
+ /** Executes the layers in order: publishes as individual txs, same-account actions batched. */ async executeLayers(feeSession) {
388
+ for (const layer of this.layers){
389
+ await this.runLayer([
390
+ ...this.publishUnits(layer),
391
+ ...this.fundUnits(layer),
392
+ ...await this.actionUnits(layer, feeSession)
393
+ ], feeSession);
394
+ }
395
+ }
396
+ /** Persists resolved addresses and runs the spec's `output` hook against the final ctx. */ async writeOutputs() {
397
+ for (const [alias, address] of this.contractAddresses){
398
+ this.state.addresses[alias] = address.toString();
399
+ }
400
+ this.persist();
401
+ await this.spec.output?.(this.ctx);
402
+ }
403
+ reportSummary() {
404
+ const summary = {
405
+ label: this.label,
406
+ contracts: [
407
+ ...this.contractAddresses
408
+ ].map(([alias, address])=>({
409
+ alias,
410
+ address,
411
+ status: getOrThrow(this.contractSteps, alias, 'contract').mode === 'register' ? 'registered' : 'published'
412
+ })),
413
+ accounts: [
414
+ ...this.accountAddresses
415
+ ].map(([alias, address])=>({
416
+ alias,
417
+ address
418
+ }))
419
+ };
420
+ this.reporter.onComplete?.(summary);
421
+ }
422
+ /** Accounts are initializerless (no deploy tx). Per-account salt + fee policy override the spec. */ async resolveAccounts() {
423
+ await Promise.all(Object.entries(this.spec.accounts).map(async ([alias, account])=>{
424
+ const derived = await this.wallet.createSchnorrInitializerlessAccount(account.secret, account.salt ?? this.defaultSalt, deriveMasterMessageSigningSecretKey(account.secret));
425
+ this.accountAddresses.set(alias, derived.address);
426
+ this.policyByAddress.set(derived.address.toString(), account.fees ?? this.globalPolicy);
427
+ }));
428
+ }
429
+ /**
430
+ * Class ids come from the ARTIFACT (not the instance/args), so they're known upfront for every
431
+ * contract — deferred ones included. This lets class-publish ordering cover all same-class
432
+ * contracts, so exactly one publishes the class and the rest are ordered after it (no race).
433
+ * Steps sharing a generated contract class share the artifact object, so the id is computed once
434
+ * per artifact identity — hashing it is CPU-heavy.
435
+ */ async computeClassIds() {
436
+ const idByArtifact = new Map();
437
+ await Promise.all([
438
+ ...this.contractSteps
439
+ ].map(async ([alias, step])=>{
440
+ if (step.mode !== 'publish') {
441
+ return;
442
+ }
443
+ let id = idByArtifact.get(step.contract.artifact);
444
+ if (!id) {
445
+ id = getContractClassFromArtifact(step.contract.artifact).then((contractClass)=>contractClass.id);
446
+ idByArtifact.set(step.contract.artifact, id);
447
+ }
448
+ this.classIds.set(alias, await id);
449
+ }));
450
+ }
451
+ /** Contract→contract address deps, auto-derived from each deterministic `initializerArgs`. */ recordContractRefs() {
452
+ const contractRefs = new Map();
453
+ for (const [alias, step] of this.contractSteps){
454
+ contractRefs.set(alias, step.initializerArgs ? referencedContracts(step.initializerArgs) : []);
455
+ }
456
+ return contractRefs;
457
+ }
458
+ /**
459
+ * Publishes/registers a contract from already-computed initializer args (used upfront for
460
+ * deterministic contracts, and at inventory or execution time for deferred ones). Both modes
461
+ * derive the address from the full instantiation params — deployer (unless universal) and
462
+ * secret-derived public keys included — so a registered contract lands on the same address
463
+ * publishing it would.
464
+ */ async resolveContract(alias, step, args) {
465
+ this.publishedCache.delete(alias); // re-resolution may change the address
466
+ const salt = step.salt ?? this.defaultSalt;
467
+ const publicKeys = step.secret ? (await deriveKeys(step.secret)).publicKeys : undefined;
468
+ if (step.mode === 'publish') {
469
+ const deployMethod = DeployMethod.create(this.wallet, {
470
+ artifact: step.contract.artifact,
471
+ postDeployCtor: (instance, boundWallet)=>step.contract.at(instance.address, boundWallet),
472
+ args,
473
+ ...step.initializer ? {
474
+ constructorNameOrArtifact: step.initializer
475
+ } : {}
476
+ }, {
477
+ ...step.universal ? {
478
+ universalDeploy: true
479
+ } : {
480
+ deployer: step.deployer(this.resolver)
481
+ },
482
+ salt,
483
+ ...publicKeys ? {
484
+ publicKeys
485
+ } : {}
486
+ });
487
+ const instance = await deployMethod.getInstance();
488
+ this.contractAddresses.set(alias, instance.address);
489
+ this.contractInstances.set(alias, step.contract.at(instance.address, this.wallet));
490
+ this.deployMethods.set(alias, deployMethod);
491
+ await this.wallet.registerContract(instance, step.contract.artifact, step.secret);
492
+ } else {
493
+ const instance = await getContractInstanceFromInstantiationParams(step.contract.artifact, {
494
+ salt,
495
+ ...step.universal ? {} : {
496
+ deployer: step.deployer(this.resolver)
497
+ },
498
+ ...publicKeys ? {
499
+ publicKeys
500
+ } : {},
501
+ ...args.length ? {
502
+ constructorArgs: args
503
+ } : {},
504
+ ...step.initializer ? {
505
+ constructorArtifact: step.initializer
506
+ } : {}
507
+ });
508
+ this.contractAddresses.set(alias, instance.address);
509
+ this.contractInstances.set(alias, step.contract.at(instance.address, this.wallet));
510
+ await this.wallet.registerContract(instance, step.contract.artifact, step.secret);
511
+ }
512
+ }
513
+ /**
514
+ * Whether a deferred contract publishes this run, decided once per run. It resolves from current
515
+ * on-chain state only once every step it declares is in place, actions included: its args read
516
+ * their effects, so resolving earlier would derive the address from state that does not exist
517
+ * yet. It has no work left when the args resolve AND the instance is already published.
518
+ */ deferredPublishes(alias, waiter) {
519
+ const step = getOrThrow(this.contractSteps, alias, 'contract');
520
+ return this.memoizedCheck(this.deferredCache, alias, waiter, async ()=>{
521
+ if (!await this.dependenciesReady(alias, {
522
+ contractsOnly: false
523
+ })) {
524
+ return true;
525
+ }
526
+ await this.resolveDeferred(alias, step, {
527
+ inventory: true
528
+ });
529
+ return !await this.isPublished(alias);
530
+ });
531
+ }
532
+ /**
533
+ * Evaluates the inventory check for `alias` at most once per run, on behalf of `waiter` — the check
534
+ * awaiting it, or undefined at the top level. Checks consult each other, possibly from parallel
535
+ * branches of one gate, so a check still in flight is shared, and only a wait that would close a
536
+ * loop in the waiting-on graph is a cycle: it throws {@link GateCycleError} instead of deadlocking.
537
+ */ memoizedCheck(cache, alias, waiter, evaluate) {
538
+ if (waiter === undefined) {
539
+ return this.getOrEvaluate(cache, alias, evaluate);
540
+ }
541
+ if (this.waitsOn(alias, waiter)) {
542
+ return Promise.reject(new GateCycleError(`Cyclic dependency: "${waiter}" and "${alias}" wait on each other.`));
543
+ }
544
+ // Recorded before evaluating: the evaluation can reach back to `waiter` synchronously.
545
+ let edges = this.waitingOn.get(waiter);
546
+ if (!edges) {
547
+ edges = new Set();
548
+ this.waitingOn.set(waiter, edges);
549
+ }
550
+ edges.add(alias);
551
+ return this.getOrEvaluate(cache, alias, evaluate).finally(()=>edges.delete(alias));
552
+ }
553
+ getOrEvaluate(cache, alias, evaluate) {
554
+ let pending = cache.get(alias);
555
+ if (!pending) {
556
+ pending = evaluate();
557
+ cache.set(alias, pending);
558
+ }
559
+ return pending;
560
+ }
561
+ /** Whether check `from` is (transitively) waiting on check `to` — or is it. */ waitsOn(from, to) {
562
+ const seen = new Set();
563
+ const stack = [
564
+ from
565
+ ];
566
+ while(stack.length > 0){
567
+ const current = stack.pop();
568
+ if (current === to) {
569
+ return true;
570
+ }
571
+ if (!seen.has(current)) {
572
+ seen.add(current);
573
+ stack.push(...this.waitingOn.get(current) ?? []);
574
+ }
575
+ }
576
+ return false;
577
+ }
578
+ /** Resolves a deferred contract's address from its args, read against the current state. */ async resolveDeferred(alias, step, { inventory }) {
579
+ const args = await this.runRecorded(alias, `Deferred initializer args for contract "${alias}"`, {
580
+ inventory
581
+ }, (ctx)=>step.deferredInitializerArgs(ctx));
582
+ await this.resolveContract(alias, step, args);
583
+ }
584
+ /**
585
+ * Whether the steps `alias` declares as dependencies are all in place: a contract published or
586
+ * registered per its mode, a fund step above its threshold, an action already done. With
587
+ * `contractsOnly`, contracts alone — a gate exists to observe whether the actions and funds it
588
+ * follows landed, so it must still run once the contracts it reads are there.
589
+ */ async dependenciesReady(alias, { contractsOnly }) {
590
+ const step = getOrThrow(this.steps, alias, 'step');
591
+ for (const dependency of [
592
+ ...this.contractRefs.get(alias) ?? [],
593
+ ...step.dependsOn ?? []
594
+ ]){
595
+ if (contractsOnly && getOrThrow(this.steps, dependency, 'step').kind !== 'contract') {
596
+ continue;
597
+ }
598
+ if (!await this.done(dependency, alias)) {
599
+ return false;
600
+ }
601
+ }
602
+ return true;
603
+ }
604
+ /**
605
+ * Runs a user callback against a ctx that records every contract alias it looks up, then requires
606
+ * those to be declared in the step's `dependsOn` — an undeclared read is state nothing checked was
607
+ * in place. The check runs even when the callback throws, so a callback that catches its own
608
+ * errors (the usual shape for a getter that reverts when unset) can't hide one — nor a
609
+ * {@link GateCycleError} from a step it consults. With `inventory`,
610
+ * the callback is part of `alias`'s inventory check, so the steps it consults are waited on by
611
+ * that check (see {@link memoizedCheck}); at execution time every check is already decided.
612
+ */ async runRecorded(alias, description, { inventory }, run) {
613
+ const references = new Set();
614
+ const waiter = inventory ? alias : undefined;
615
+ let cycle;
616
+ const surfaceCycle = (status)=>status.catch((error)=>{
617
+ if (error instanceof GateCycleError) {
618
+ cycle ??= error;
619
+ }
620
+ throw error;
621
+ });
622
+ const ctx = {
623
+ ...this.ctx,
624
+ done: (id)=>surfaceCycle(this.done(id, waiter)),
625
+ ran: (id)=>surfaceCycle(this.ran(id, waiter)),
626
+ contract: (reference)=>{
627
+ references.add(reference);
628
+ return this.resolver.contract(reference);
629
+ },
630
+ instance: (reference)=>{
631
+ references.add(reference);
632
+ return getOrThrow(this.contractInstances, reference, 'contract instance');
633
+ }
634
+ };
635
+ let result;
636
+ try {
637
+ result = await run(ctx);
638
+ } catch (error) {
639
+ this.assertReferencesDeclared(alias, description, references, error);
640
+ throw cycle ?? error;
641
+ }
642
+ this.assertReferencesDeclared(alias, description, references);
643
+ if (cycle) {
644
+ throw cycle;
645
+ }
646
+ return result;
647
+ }
648
+ /**
649
+ * Rejects contract aliases the callback read but the step doesn't declare. `cause` carries the
650
+ * error the callback threw, since an undeclared read is the likeliest reason it did.
651
+ */ assertReferencesDeclared(alias, description, references, cause) {
652
+ const step = getOrThrow(this.steps, alias, 'step');
653
+ const declared = new Set([
654
+ ...this.contractRefs.get(alias) ?? [],
655
+ ...step.dependsOn ?? []
656
+ ]);
657
+ const undeclared = [
658
+ ...references
659
+ ].filter((reference)=>!declared.has(reference));
660
+ if (undeclared.length > 0) {
661
+ throw new Error(`${description} reads ${undeclared.map((reference)=>`"${reference}"`).join(', ')} but does not declare it in` + ` dependsOn. Declare every step it reads, so it only runs once they are in place.`, {
662
+ cause
663
+ });
664
+ }
665
+ }
666
+ /** Whether the alias's resolved instance is published on-chain. Memoized — one node read per address. */ isPublished(alias) {
667
+ const address = this.contractAddresses.get(alias);
668
+ if (!address) {
669
+ return Promise.resolve(false); // deferred & not yet resolved
670
+ }
671
+ let cached = this.publishedCache.get(alias);
672
+ if (!cached) {
673
+ cached = this.wallet.getContractMetadata(address).then((metadata)=>metadata.isContractPublished);
674
+ this.publishedCache.set(alias, cached);
675
+ }
676
+ return cached;
677
+ }
678
+ /**
679
+ * A fund step's idempotency gate: whether the recipient's public Fee Juice balance already
680
+ * clears the step's threshold. A recipient this run has yet to put in place holds nothing, so the
681
+ * balance is read only once the contracts its selector references are there. Memoized per run.
682
+ */ fundGate(alias, waiter) {
683
+ const step = getOrThrow(this.fundSteps, alias, 'fund step');
684
+ return this.memoizedCheck(this.fundGateCache, alias, waiter, async ()=>{
685
+ for (const reference of referencedContracts(step.recipient)){
686
+ if (!await this.done(reference, alias)) {
687
+ return false;
688
+ }
689
+ }
690
+ const recipient = step.recipient(this.resolver);
691
+ return await publicFeeJuiceBalance(this.wallet, recipient, step.from(this.resolver)) >= step.threshold;
692
+ });
693
+ }
694
+ /**
695
+ * An action's `done` gate, memoized per run. Invoked only once the contracts the action declares
696
+ * are in place: until then the action cannot have run, and the gate would read state that does not
697
+ * exist. Gates may consult other steps via `ctx.done`.
698
+ */ actionGate(alias, waiter) {
699
+ const step = this.actionSteps.get(alias);
700
+ if (!step) {
701
+ throw new Error(`Unknown action "${alias}".`);
702
+ }
703
+ return this.memoizedCheck(this.gateCache, alias, waiter, async ()=>{
704
+ if (!await this.dependenciesReady(alias, {
705
+ contractsOnly: true
706
+ })) {
707
+ return false;
708
+ }
709
+ return this.runRecorded(alias, `Idempotency gate for action "${alias}"`, {
710
+ inventory: true
711
+ }, (ctx)=>step.done(ctx));
712
+ });
713
+ }
714
+ /** `ctx.done`: whether step `id` is already satisfied this run — mode-aware. `waiter` is the check asking. */ done(id, waiter) {
715
+ const step = this.steps.get(id);
716
+ if (!step) {
717
+ throw new Error(`Unknown step "${id}".`);
718
+ }
719
+ if (step.kind === 'action') {
720
+ return this.actionGate(id, waiter);
721
+ }
722
+ if (step.kind === 'fund') {
723
+ return this.fundGate(id, waiter);
724
+ }
725
+ if (step.mode === 'register') {
726
+ return Promise.resolve(this.contractAddresses.has(id)); // registered in the PXE
727
+ }
728
+ if (isDeferred(step)) {
729
+ // Its address only exists once it resolves; publication itself is read live, so a publish
730
+ // later in this run still shows.
731
+ return this.deferredPublishes(id, waiter).then(()=>this.isPublished(id));
732
+ }
733
+ return this.isPublished(id);
734
+ }
735
+ /** `ctx.ran`: whether step `id` did (or will do) work this run — mode-aware. `waiter` is the check asking. */ async ran(id, waiter) {
736
+ const step = this.steps.get(id);
737
+ if (!step) {
738
+ throw new Error(`Unknown step "${id}".`);
739
+ }
740
+ if (step.kind === 'action') {
741
+ return !await this.actionGate(id, waiter);
742
+ }
743
+ if (step.kind === 'fund') {
744
+ return !await this.fundGate(id, waiter);
745
+ }
746
+ if (step.mode === 'register') {
747
+ return this.contractAddresses.has(id); // (re)registered this run
748
+ }
749
+ return isDeferred(step) ? this.deferredPublishes(id, waiter) : this.publishedThisRun.has(id);
750
+ }
751
+ /**
752
+ * Builds the execution graph over the steps that run and groups it into layers. Exactly one
753
+ * contract per class publishes it; every other same-class contract — deterministic or deferred —
754
+ * is ordered after it. The publisher is the class's first contract in `dependsOn` order, so the
755
+ * ordering can't run against a dependency (a same-class contract declared earlier but depending on
756
+ * a later one would otherwise close a cycle).
757
+ */ buildLayers() {
758
+ const dependsOn = new Map(this.execAliases.map((alias)=>[
759
+ alias,
760
+ getOrThrow(this.steps, alias, 'step').dependsOn ?? []
761
+ ]));
762
+ const publisherByClass = new Map();
763
+ for (const alias of topologicalLayers(this.execAliases, dependsOn).flat()){
764
+ const step = this.contractSteps.get(alias);
765
+ if (step?.mode !== 'publish') {
766
+ continue;
767
+ }
768
+ const classId = getOrThrow(this.classIds, alias, 'class id').toString();
769
+ if (!publisherByClass.has(classId)) {
770
+ publisherByClass.set(classId, alias);
771
+ }
772
+ }
773
+ const execDeps = new Map();
774
+ for (const alias of this.execAliases){
775
+ const step = getOrThrow(this.steps, alias, 'step');
776
+ // Constructor address refs (contractRefs) do NOT order publishes — addresses are deterministic,
777
+ // so a contract can publish in parallel with the ones it references. Only `dependsOn` (an action
778
+ // it follows / runtime state a deferred contract reads) and shared-class publication order here.
779
+ const deps = new Set(step.dependsOn ?? []);
780
+ if (step.kind === 'contract' && step.mode === 'publish') {
781
+ const classId = this.classIds.get(alias)?.toString();
782
+ const publisher = classId ? publisherByClass.get(classId) : undefined;
783
+ if (publisher && publisher !== alias) {
784
+ deps.add(publisher);
785
+ }
786
+ }
787
+ execDeps.set(alias, [
788
+ ...deps
789
+ ]);
790
+ }
791
+ // Actions float as late as their dependents allow, so same-account actions coalesce into one
792
+ // batched tx; contract publishes stay early (they unblock dependents and aren't batched).
793
+ return scheduleLayers(this.execAliases, execDeps, (id)=>getOrThrow(this.steps, id, 'step').kind === 'action');
794
+ }
795
+ /** A layer's contract publishes — one tx each (deferred contracts resolve their address first). */ publishUnits(layer) {
796
+ const units = [];
797
+ for (const alias of layer.filter((a)=>this.contractSteps.has(a))){
798
+ const step = getOrThrow(this.contractSteps, alias, 'contract');
799
+ const account = contractSender(step)(this.resolver);
800
+ units.push({
801
+ label: `publish ${alias}`,
802
+ kind: 'publish',
803
+ account,
804
+ send: async (fee)=>{
805
+ if (isDeferred(step)) {
806
+ // Re-resolve with post-`dependsOn` state: the inventory attempt was skipped or ran
807
+ // before this run's earlier layers landed.
808
+ await this.resolveDeferred(alias, step, {
809
+ inventory: false
810
+ });
811
+ }
812
+ const classId = getOrThrow(this.classIds, alias, 'class id');
813
+ const deployMethod = getOrThrow(this.deployMethods, alias, 'deploy method');
814
+ const classKey = classId.toString();
815
+ const alreadyRegistered = this.classesPublishedThisRun.has(classKey) || (await this.wallet.getContractClassMetadata(classId)).isContractClassPubliclyRegistered;
816
+ this.classesPublishedThisRun.add(classKey);
817
+ const sent = await deployMethod.send({
818
+ from: account,
819
+ fee,
820
+ wait: {
821
+ timeout: 120
822
+ },
823
+ skipClassPublication: alreadyRegistered
824
+ });
825
+ this.publishedCache.set(alias, Promise.resolve(true));
826
+ return sent;
827
+ }
828
+ });
829
+ }
830
+ return units;
831
+ }
832
+ /**
833
+ * A layer's fund steps — one unit each: obtain the recipient's claim (resume the persisted one,
834
+ * or bridge from L1 and wait for the message), then send the L2 `FeeJuice.claim` tx from the
835
+ * step's `from` account.
836
+ */ fundUnits(layer) {
837
+ const units = [];
838
+ for (const alias of layer.filter((a)=>this.fundSteps.has(a))){
839
+ const step = getOrThrow(this.fundSteps, alias, 'fund step');
840
+ const account = step.from(this.resolver);
841
+ units.push({
842
+ label: `fund ${alias}`,
843
+ kind: 'fund',
844
+ account,
845
+ send: async (fee)=>{
846
+ const recipient = step.recipient(this.resolver);
847
+ const claim = await obtainFeeJuiceClaim({
848
+ local: this.local,
849
+ node: this.node,
850
+ nodeUrl: this.nodeUrl,
851
+ recipient,
852
+ amount: step.amount,
853
+ l1: {
854
+ l1FunderKey: step.l1FunderKey,
855
+ l1RpcUrl: step.l1RpcUrl,
856
+ l1ChainId: step.l1ChainId
857
+ },
858
+ state: this.state,
859
+ persist: ()=>this.persist(),
860
+ reporter: this.reporter
861
+ });
862
+ const sent = await FeeJuiceContract.at(this.wallet).methods.claim(recipient, claim.claimAmount, claim.claimSecret, claim.messageLeafIndex).send({
863
+ from: account,
864
+ fee,
865
+ wait: {
866
+ timeout: 120
867
+ }
868
+ });
869
+ claim.onConsumed();
870
+ return sent;
871
+ }
872
+ });
873
+ }
874
+ return units;
875
+ }
876
+ /**
877
+ * A layer's actions, batching independent same-account actions into BatchCalls sized to leave
878
+ * room for the account's fee payment calls — the entrypoint's call limit counts those too.
879
+ */ async actionUnits(layer, feeSession) {
880
+ const actionsByAccount = new Map();
881
+ for (const alias of layer.filter((a)=>this.actionSteps.has(a))){
882
+ const account = getOrThrow(this.actionSteps, alias, 'action').from(this.resolver);
883
+ const group = actionsByAccount.get(account.toString());
884
+ if (group) {
885
+ group.aliases.push(alias);
886
+ } else {
887
+ actionsByAccount.set(account.toString(), {
888
+ account,
889
+ aliases: [
890
+ alias
891
+ ]
892
+ });
893
+ }
894
+ }
895
+ const units = [];
896
+ for (const { account, aliases } of actionsByAccount.values()){
897
+ for (const batch of chunk(aliases, APP_MAX_CALLS - await feeSession.feeCallCount(account))){
898
+ units.push({
899
+ label: batch.length === 1 ? `action ${batch[0]}` : `batch [${batch.join(', ')}]`,
900
+ kind: 'action',
901
+ account,
902
+ send: async (fee)=>{
903
+ const interactions = await Promise.all(batch.map((alias)=>this.runRecorded(alias, `Call for action "${alias}"`, {
904
+ inventory: false
905
+ }, (ctx)=>getOrThrow(this.actionSteps, alias, 'action').call(ctx))));
906
+ const sendOptions = {
907
+ from: account,
908
+ fee,
909
+ wait: {
910
+ timeout: 120
911
+ }
912
+ };
913
+ return interactions.length === 1 ? interactions[0].send(sendOptions) : new BatchCall(this.wallet, interactions).send(sendOptions);
914
+ }
915
+ });
916
+ }
917
+ }
918
+ return units;
919
+ }
920
+ async runLayer(units, feeSession) {
921
+ if (units.length === 0) {
922
+ return;
923
+ }
924
+ // Per-account claim serialization: the first paying tx of each claim-holding account must mine
925
+ // (consuming + spending the claim) before that account's balance-payers fan out. The fee
926
+ // session owns the claim state; consuming the claim flips `hasPendingClaim` for later layers.
927
+ const claimFirst = [];
928
+ const rest = [];
929
+ const seen = new Set();
930
+ for (const unit of units){
931
+ const key = unit.account.toString();
932
+ if (feeSession.hasPendingClaim(unit.account) && !seen.has(key)) {
933
+ seen.add(key);
934
+ claimFirst.push(unit);
935
+ } else {
936
+ rest.push(unit);
937
+ }
938
+ }
939
+ for (const unit of claimFirst){
940
+ await this.runUnit(unit, feeSession);
941
+ }
942
+ // Fund units run sequentially relative to each other: their send closures submit L1 bridge
943
+ // txs, and two bridges signed by the same funder key would race on nonces.
944
+ const fundRest = rest.filter((unit)=>unit.kind === 'fund');
945
+ const parallelRest = rest.filter((unit)=>unit.kind !== 'fund');
946
+ const runParallel = ()=>Promise.all(parallelRest.map((unit)=>this.runUnit(unit, feeSession)));
947
+ const runFunds = async ()=>{
948
+ for (const unit of fundRest){
949
+ await this.runUnit(unit, feeSession);
950
+ }
951
+ };
952
+ if (this.local) {
953
+ // Locally a fund unit warps L2 time, building blocks under any tx still in flight. A tx anchored to the genesis
954
+ // block is only valid in block 1, so a warp that lands first leaves it unincludable.
955
+ await runParallel();
956
+ await runFunds();
957
+ } else {
958
+ await Promise.all([
959
+ runParallel(),
960
+ runFunds()
961
+ ]);
962
+ }
963
+ }
964
+ async runUnit(unit, feeSession) {
965
+ const info = {
966
+ label: unit.label,
967
+ kind: unit.kind,
968
+ account: unit.account
969
+ };
970
+ this.reporter.onUnitStart?.(info);
971
+ const { fee, onConsumed } = feeSession.next(unit.account);
972
+ const startedAt = Date.now();
973
+ let result;
974
+ try {
975
+ result = await unit.send(fee);
976
+ } catch (error) {
977
+ this.reporter.onUnitError?.(info, error);
978
+ throw error;
979
+ }
980
+ const receipt = result?.receipt;
981
+ this.reporter.onUnitSettled?.(info, {
982
+ txHash: receipt?.txHash,
983
+ blockNumber: receipt?.blockNumber != null ? Number(receipt.blockNumber) : undefined,
984
+ feePaid: receipt?.transactionFee,
985
+ status: receipt?.status != null ? String(receipt.status) : undefined,
986
+ durationMs: Date.now() - startedAt
987
+ });
988
+ onConsumed();
989
+ }
990
+ persist() {
991
+ saveState(this.stateDirectory, this.state);
992
+ }
993
+ }