import Debug from 'debug'; /* eslint-disable @typescript-eslint/no-non-null-assertion */ import _ from 'lodash'; import * as viem from 'viem'; import { ContractMap, DeploymentState, TransactionMap } from './'; import { BUILD_VERSION } from './constants'; import { ChainDefinition } from './definition'; import { ChainBuilderRuntime, Events } from './runtime'; import { BuildOptions, ChainArtifacts, ChainBuilderContext, PackageState, PreChainBuilderContext } from './types'; import { printChainDefinitionProblems } from './util'; const debug = Debug('cannon:builder'); const debugVerbose = Debug('cannon:verbose:builder'); // a step is considered failed if it takes longer than 5 minutes always const DEFAULT_STEP_TIMEOUT = 300000; export async function createInitialContext( def: ChainDefinition, pkg: any, chainId: number, opts: BuildOptions, defaultSigner: viem.Address = viem.zeroAddress ): Promise { const preCtx: PreChainBuilderContext = { package: pkg, timestamp: Math.floor(Date.now() / 1000), chainId, defaultSigner, overrideSettings: opts, }; return { ...preCtx, contracts: {}, txns: {}, imports: {}, settings: _.clone(opts), }; } export async function build( runtime: ChainBuilderRuntime, def: ChainDefinition, state: DeploymentState, initialCtx: ChainBuilderContext, skipPreflight?: true ): Promise { if (!skipPreflight) { debug('preflight'); const problems = def.checkAll(); if (problems) { throw new Error(`Your cannonfile is invalid: please resolve the following issues before building your project: ${printChainDefinitionProblems(problems)}`); } } debug('build', initialCtx.settings); // Use awaited imports to prevent import cycle within the builder module const { ActionKinds } = await import('./actions'); // sanity check the network await runtime.checkNetwork(); initialCtx.chainId = runtime.chainId; state = _.cloneDeep(state); const tainted = new Set(); const built = new Map(); const topologicalActions = def.topologicalActions; let ctx; const ref = def.getPackageRef(initialCtx); // whether or not source code is included in deployment artifacts or not is controlled by cannonfile config, so we set it here runtime.setPublicSourceCode(def.isPublicSourceCode()); try { if (runtime.snapshots) { debug('building by layer'); ctx = _.clone(initialCtx); for (const leaf of def.leaves) { await buildLayer(runtime, def, ctx, state, leaf, tainted, built); } } else { debug('building individual'); doActions: for (const n of topologicalActions) { debug(`check action ${n}`); if (runtime.isCancelled()) { debug('runtime cancelled'); break; } ctx = _.cloneDeep(initialCtx); const artifacts: ChainArtifacts = {}; let depsTainted = false; for (const dep of def.getDependencies(n)) { if (!built.has(dep)) { debug(`skip ${n} because previous operation incomplete`); runtime.emit(Events.SkipDeploy, n, new Error(`dependency operation not completed: ${dep}`), 0); continue doActions; } _.merge(artifacts, built.get(dep)); depsTainted = depsTainted || tainted.has(dep); } addOutputsToContext(ctx, artifacts); if (state[n]) { if (state[n].version > BUILD_VERSION) { throw new Error('incompatible (newer) build version. please update cannon.'); } // also add self artifacts here so that we can self-reference from inside the step debug('adding self artifacts to context', state[n].artifacts); addOutputsToContext(ctx, state[n].artifacts); runtime.updateProviderArtifacts(state[n].artifacts); } runtime.reportOperatingContext(n, ctx); try { const curHashes = await def.getState(n, runtime, ctx, depsTainted); debug('comparing states', state[n] ? state[n].hash : null, curHashes); if (!state[n] || (state[n].hash !== 'SKIP' && curHashes && !curHashes.includes(state[n].hash || ''))) { debug('run isolated', n); const newArtifacts = await runStep(runtime, { ref, currentLabel: n }, def.getConfig(n, ctx), ctx); if (!newArtifacts) { continue; } // some steps may be self introspective, causing a step to be giving the wrong hash initially. to counteract this, we recompute the hash addOutputsToContext(ctx, newArtifacts); const newStates = await def.getState(n, runtime, ctx, depsTainted); state[n] = { artifacts: newArtifacts, hash: newStates && newStates.length ? newStates[0] : null, version: BUILD_VERSION, }; tainted.add(n); } else { debug('skip isolated', n); } built.set(n, _.merge(artifacts, state[n].artifacts)); // if there is an error then this will ensure the stack trace is printed with the latest runtime.updateProviderArtifacts(state[n].artifacts); } catch (err: any) { debug('got error', err); if (runtime.allowPartialDeploy) { runtime.emit(Events.SkipDeploy, n, err, 0); continue; // will skip saving the build artifacts, which should block any future jobs from finishing } else { // fake emit the pre step execute so its easier to see what is going on const [type, label] = n.split('.') as [keyof typeof ActionKinds, string]; runtime.emit(Events.PreStepExecute, type, label, {}, 0); // make sure its possible to debug the original error debug('error', err); debugVerbose('context', JSON.stringify(ctx, null, 2)); throw err; } } } } } catch (err: any) { // make sure its possible to debug the original error debug('error', err); debugVerbose('context', JSON.stringify(ctx, null, 2)); throw err; } runtime.reportOperatingContext(null, null); return state; } export async function buildLayer( runtime: ChainBuilderRuntime, def: ChainDefinition, baseCtx: ChainBuilderContext, state: DeploymentState, cur: string, tainted: Set = new Set(), built: Map = new Map() ) { // Use awaited imports to prevent import cycle within the builder module const { ActionKinds } = await import('./actions'); const layers = def.getStateLayers(); const layer = layers[cur]; // if layer is already done if (built.has(cur)) { return; } debug('eval build layer name', cur); const ref = def.getPackageRef(baseCtx); // check all dependencies. If the dependency is not done, run the dep layer first let isCompleteLayer = true; for (const dep of layer.depends) { // this doesn't catch all cases of cycles but as a sanity check it works surprisingly well if (dep === cur) { throw new Error(`layer depends on itself: ${cur}`); } await buildLayer(runtime, def, baseCtx, state, dep, tainted, built); // if a prior layer had to be rebuilt, we must rebuild the current layer as well isCompleteLayer = isCompleteLayer && !tainted.has(dep); } // do all state layers match? if so, load the layer from cache and continue for (const action of layer.actions) { const ctx = _.cloneDeep(baseCtx); const depArtifacts: ChainArtifacts = {}; for (const dep of def.getDependencies(action)) { _.merge(depArtifacts, built.get(dep)); } addOutputsToContext(ctx, depArtifacts); if (state[action] && state[action].artifacts) { if (state[action].version > BUILD_VERSION) { throw new Error('incompatible (newer) build version. please update cannon.'); } // also add self artifacts here so that we can self-reference from inside the step addOutputsToContext(ctx, state[action].artifacts); } runtime.reportOperatingContext(action, ctx); try { const curHashes = await def.getState(action, runtime, ctx, false); if (isCompleteLayer) { debug('comparing layer states', state[action] ? state[action].hash : null, curHashes); if (!state[action] || (curHashes && !curHashes.includes(state[action].hash || ''))) { debug('operation', action, 'in layer needs to be rebuilt'); isCompleteLayer = false; break; } // in case we do not need to rebuild this layer we still need to set the built entry built.set(action, _.merge(depArtifacts, state[action].artifacts)); } } catch (err) { // make sure its possible to debug the original error debug('error', err); // fake emit the pre step execute so its easier to see what is going on const [type, label] = action.split('.') as [keyof typeof ActionKinds, string]; runtime.emit(Events.PreStepExecute, type, label, {}, 0); throw err; } } // if we get here, need to run a rebuild of layer if (!isCompleteLayer) { debug('run to complete layer', layer.actions, layer.depends); await runtime.clearNode(); for (const dep of layer.depends) { if (state[dep].chainDump) { // chain dump may not exist if the package is a little older await runtime.loadState(state[dep].chainDump!); } else { debug('warning: chain dump not recorded for layer:', dep); } } for (const action of layer.actions) { const ctx = _.cloneDeep(baseCtx); const depArtifacts: ChainArtifacts = {}; for (const dep of def.getDependencies(action)) { _.merge(depArtifacts, built.get(dep)); } addOutputsToContext(ctx, depArtifacts); // also add self artifacts here so that we can self-reference from inside the step if (state[action] && state[action].artifacts) { debug('adding self artifacts to context', state[action].artifacts); addOutputsToContext(ctx, state[action].artifacts); runtime.updateProviderArtifacts(state[action].artifacts); } debug('run action in layer', action); const newArtifacts = await runStep( runtime, { ref, currentLabel: action, }, def.getConfig(action, ctx), _.clone(ctx) ); if (!newArtifacts) { continue; } addOutputsToContext(ctx, newArtifacts); const newHashes = await def.getState(action, runtime, ctx, false); state[action] = { artifacts: newArtifacts, hash: newHashes && newHashes.length ? newHashes[0] : null, version: BUILD_VERSION, // add the chain dump later once all steps have been executed }; tainted.add(action); built.set(action, _.merge(depArtifacts, state[action].artifacts)); // if there is an error then this will ensure the stack trace is printed with the latest runtime.updateProviderArtifacts(state[action].artifacts); } // after all contexts are built, save all of them at the same time const chainDump = await runtime.dumpState(); for (const action of layer.actions) { if (!state[action]) { continue; } state[action].chainDump = chainDump; } } } export async function runStep(runtime: ChainBuilderRuntime, pkgState: PackageState, cfg: any, ctx: ChainBuilderContext) { // Use awaited imports to prevent import cycle within the builder module const { ActionKinds } = await import('./actions'); const [type, label] = pkgState.currentLabel.split('.') as [keyof typeof ActionKinds, string]; if (cfg && cfg.chains && !cfg.chains.includes(runtime.chainId)) { debug(`skipping step ${label} on chain ${runtime.chainId}`); return null; } runtime.emit(Events.PreStepExecute, type, label, cfg, 0); debugVerbose('ctx for operation', pkgState.currentLabel, ctx); const result = await viem.withTimeout( () => { return ActionKinds[type].exec(runtime, ctx, cfg as any, pkgState); }, { timeout: ActionKinds[type].timeout || DEFAULT_STEP_TIMEOUT, errorInstance: new Error('timed out without error'), } ); runtime.emit(Events.PostStepExecute, type, label, cfg, ctx, result, 0); return result; } export function getArtifacts(def: ChainDefinition, state: DeploymentState) { const artifacts: ChainArtifacts = {}; for (const step of def.topologicalActions) { if (state[step] && state[step].artifacts) { _.merge(artifacts, state[step].artifacts); } } return artifacts; } export async function getOutputs( runtime: ChainBuilderRuntime, def: ChainDefinition, state: DeploymentState ): Promise { const artifacts = getArtifacts(def, state); if (runtime.snapshots) { // need to load state as well. the states that we want to load are the "leaf" layers const layers = _.uniq(Object.values(def.getStateLayers())); layerSearch: for (const layer of layers) { for (const action of layer.actions) { if (layers.find((l) => l.depends.indexOf(action) !== -1)) { // this isnt a leaf continue layerSearch; } } if (state[layer.actions[0]]?.chainDump) { await runtime.loadState(state[layer.actions[0]].chainDump!); } else { debug(`warning: state dump not recorded for ${layer.actions[0]}`); } } } return artifacts; } // TODO: this func is dumb but I need to walk through this time period before I want to turn it into something of beauty export function addOutputsToContext(ctx: ChainBuilderContext, outputs: ChainArtifacts) { const imports = outputs.imports; for (const imp in imports) { ctx.imports[imp] = imports[imp]; } //helper function for recursively adding simplified imports notation function addSimplifiedAccessSyntax(ctx: ChainArtifacts) { const simplifiedAccessObject: ContractMap | { [v: string]: any } = {}; for (const contractName in ctx.contracts) { //also add simplified address syntax simplifiedAccessObject[contractName] = ctx.contracts[contractName]; } for (const importName in ctx.imports) { simplifiedAccessObject[importName] = addSimplifiedAccessSyntax(ctx.imports[importName]); } return simplifiedAccessObject; } const contracts = outputs.contracts as ContractMap; for (const contractName in contracts) { ctx.contracts[contractName] = contracts[contractName]; } const txns = outputs.txns as TransactionMap; for (const txn in txns) { ctx.txns[txn] = txns[txn]; } for (const n in outputs.settings) { ctx.settings[n] = outputs.settings[n]; } if (!ctx.extras) { ctx.extras = {}; } for (const n in outputs.extras) { ctx.extras[n] = outputs.extras[n]; } for (const override in ctx.overrideSettings) { ctx.settings[override] = ctx.overrideSettings[override]; } assignSettingsToExtras(ctx); ctx = Object.assign(ctx, addSimplifiedAccessSyntax(ctx)); } // backawrds compatibility, settings was called "extras". function assignSettingsToExtras(ctx: ChainBuilderContext) { if (ctx.settings) { ctx.extras = { ...(ctx.extras || {}), ...ctx.settings, }; } for (const importCtx of Object.values(ctx.imports || {})) { assignSettingsToExtras(importCtx as unknown as ChainBuilderContext); } }