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