Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions deployments/core/deploy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1547,6 +1547,8 @@ function pendingSourceDeployment({
vi.spyOn(Reconcile, 'preflightEarnDeployment').mockResolvedValue(undefined)
vi.spyOn(Reconcile, 'verifyEarnDeploymentState').mockResolvedValue({})
vi.spyOn(Inspection, 'inspectEarnDeployment').mockResolvedValue({})
// Router code identity has its own tests; these routers run today's build.
vi.spyOn(Provenance, 'replacedComponents').mockResolvedValue(new Set())
vi.spyOn(Provenance, 'captureDeploymentSource').mockImplementation((options) => ({
...record.source,
contractVerification: options.contractVerification,
Expand Down
17 changes: 15 additions & 2 deletions deployments/core/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ import {
import {
captureDeploymentSource,
earliestDeploymentBlock,
replacedComponents,
runtimeCodeHashes,
verifyDeploymentProvenance,
} from './provenance.js'
Expand Down Expand Up @@ -174,6 +175,13 @@ async function deployEarnProfileLocked(options: LifecycleOptions): Promise<EarnD
const reconciling = committed
? changedIntentComponents(committed.componentDeploymentIntentHashes, profile)
: new Set<IntentComponent>()
// Immutable periphery built from other code than this checkout's is replaced like changed intent.
const replaced = committed
? await replacedComponents(client, profile, committed, (contract) =>
compiledRuntimeCode(options.root, contract, options.environment),
)
: new Set<IntentComponent>()
Comment on lines +185 to +193

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium: First-deployment resume keeps a router built from an older checkout

The PR now decides router replacement by comparing compiled code and freezes the router intent hashes. However, the cached-output code check runs only when a committed record exists. An interrupted first deployment therefore resumes with a router built by an older checkout.

Full finding

The PR now decides router replacement by comparing compiled code and freezes the router intent hashes. However, the cached-output code check runs only when a committed record exists. An interrupted first deployment therefore resumes with a router built by an older checkout. On hosted chains, record building then fails. On other chains, the record publishes the stale router.

Valid? React with 👍 / 👎.

Comment on lines +185 to +193

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs review · unverified: Missing code in disposable cache blocks a valid committed deployment

A formerly mined replacement address can remain in pending outputs after a chain rollback that leaves the committed address intact. If the operator resumes on the committed build with unchanged intent, committed state should override that cache, as it did before this PR.

Full finding

A formerly mined replacement address can remain in pending outputs after a chain rollback that leaves the committed address intact. If the operator resumes on the committed build with unchanged intent, committed state should override that cache, as it did before this PR. Instead, the new cache scan runs before restoration and sends the obsolete cached address to the strict provenance helper. An empty getCode response throws, preventing the valid committed address from being restored. The command continues to fail while the cache remains, without broadcasting or charging additional transaction fees; moving the cache aside recovers the valid committed path. The precondition is a lost cached replacement and surviving committed state; no ability for an unprivileged party to cause that chain state was established. Check only cache entries eligible to be retained, or classify a definite empty-code response as stale for cached addresses only. Keep RPC failures and missing committed code fatal.

Valid? React with 👍 / 👎.

for (const component of replaced) reconciling.add(component)
Comment on lines +178 to +184

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 pre-existing, not blocking: After merging, any router bytecode change makes the next Deploy run silently swap in a new router. The superseded router keeps its Zone Portal role and PropAMM pool admission, and nobody is told. replacedComponents drops the old earnRouter/zoneRouter and re-runs only the grant steps for the new address. No step revokes the old router's roles or flags it for revocation. Fix: when a replaced component's old router still holds Portal roles or pool admission, report it as a blocker or handoff that names the old address (or emit its revoke calls), so replacement never leaves two privileged routers.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

Trigger: a source, compiler (solar.lock) or metadata-only change to SingleZoneEarnRouter or ZoneRouterFactory/ZoneRouter, then a broadcast Deploy run. At deploy.ts:178-184, replacedComponents (provenance.ts:47-70) flags zone or zoneRouterFactory/zoneRouter. restorePendingDeployment (pending.ts:184-200) then drops the old address. The new router is deployed. Steps such as authorize-router (pool admission, earn/zone-router/steps.ts:134-147) and register-zone-gateway (chain/zone.ts:340) check and grant only the new earnRouter. There is no revoke step for the replaced router. The old immutable, ownerless router therefore stays admitted on the pool and the Portal, and the run reports complete. On the base branch this only happened when someone deliberately bumped routerContractRelease/zoneRouterContractRelease, a reviewed event where an operator could also revoke. Now it happens automatically and more often, so privileged routers pile up unnoticed.

Verification: Pre-existing, made wider by this change. deploy.ts:178-184 adds what replacedComponents returns to reconciling, and pending.ts retained drops the recorded earnRouter/zoneRouter address. authorize-router (earn/zone-router/steps.ts:133-163) then admits only the new address, and no step revokes or reports the old router.

syncFoundryOutputs(options.root, options.profilePath)
Comment on lines +185 to 194

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium (trigger unconfirmed) · unverified: Stale Foundry checkpoints bypass router build reconciliation

On a profile with a committed record, stop after Forge broadcasts an intermediate SingleZoneEarnRouter replacement and writes latestOutputs, but before the lifecycle records the action. Resume from another checkout with a different router build and the same profile. The new cache probe reads only outputs and runs before external staging synchronization; restoration also preserves latestOutputs unchanged.

Full finding

On a profile with a committed record, stop after Forge broadcasts an intermediate SingleZoneEarnRouter replacement and writes latestOutputs, but before the lifecycle records the action. Resume from another checkout with a different router build and the same profile. The new cache probe reads only outputs and runs before external staging synchronization; restoration also preserves latestOutputs unchanged. Reconciliation then overlays the older address from latestOutputs and accepts its bindings before considering a new broadcast. If the old successful receipt is recoverable on a hosted chain, the current initcode check rejects it and retries hit the same checkpoint rather than deploying the current build. On a non-hosted chain that creation check is skipped, so the old build can be reused. This requires an interrupted operator deployment and an intervening build change; no unprivileged trigger or affected live deployment was established. On hosted chains the interruption blocks progress without further transaction spend on each retry; the ordinary successful path needs a replacement broadcast. Synchronize staging first, classify mined latestOutputs independently of materialized outputs, and remove definitively stale checkpoint entries before recovery while preserving current-build checkpoints and receipt validation.

Valid? React with 👍 / 👎.

let pending: PendingDeployment
if (committed) {
Expand All @@ -189,7 +197,7 @@ async function deployEarnProfileLocked(options: LifecycleOptions): Promise<EarnD
committed.source.factoryDeploymentId,
)
}
pending = restorePendingDeployment(options.profilePath, profile, committed)
pending = restorePendingDeployment(options.profilePath, profile, committed, replaced)
} else {
pending = loadPendingDeployment(options.profilePath, profile)
}
Expand Down Expand Up @@ -257,6 +265,7 @@ async function deployEarnProfileLocked(options: LifecycleOptions): Promise<EarnD
const candidate = await buildDeploymentRecord(client, {
pending: deployed.pending,
committed,
replaced,
rpcUrl: options.rpcUrl,
environment: options.environment,
profile,
Expand Down Expand Up @@ -447,6 +456,7 @@ async function buildDeploymentRecord(
options: {
pending: PendingDeployment
committed: EarnDeploymentRecord | undefined
replaced: ReadonlySet<IntentComponent>
rpcUrl: string
environment: NodeJS.ProcessEnv
profile: EarnDeploymentProfile
Expand All @@ -468,7 +478,10 @@ async function buildDeploymentRecord(
) as EarnDeploymentRecord['actions']
const previous = options.committed
const changed = previous
? changedIntentComponents(previous.componentDeploymentIntentHashes, profile)
? new Set([
...changedIntentComponents(previous.componentDeploymentIntentHashes, profile),
...options.replaced,
])
: undefined
// Carry proof with its creator's unchanged intent, address, and action, not with consumers that may change independently.
const contracts = Object.fromEntries(
Expand Down
12 changes: 7 additions & 5 deletions deployments/core/pending.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
deploymentAddressComponents,
deploymentAddressKeys,
type DeploymentAddressKey,
type IntentComponent,
} from './components.js'
import {
parseCompletedAction,
Expand Down Expand Up @@ -169,6 +170,8 @@ export function restorePendingDeployment(
EarnDeploymentRecord,
'addresses' | 'actions' | 'componentDeploymentIntentHashes'
>,
// Components whose recorded contracts are replaced although their intent is unchanged.
replaced: ReadonlySet<IntentComponent> = new Set(),
): PendingDeployment {
let cached: PendingDeployment
try {
Expand All @@ -178,10 +181,9 @@ export function restorePendingDeployment(
}
const currentComponents = componentDeploymentIntentHashes(profile)
const recordedComponents = committed.componentDeploymentIntentHashes
const componentMatches = (id: EarnDeploymentActionId) =>
deploymentStep(id).intent.every(
(component) => recordedComponents[component] === currentComponents[component],
)
const retained = (component: IntentComponent) =>
!replaced.has(component) && recordedComponents[component] === currentComponents[component]
const componentMatches = (id: EarnDeploymentActionId) => deploymentStep(id).intent.every(retained)
const committedDeploymentActions = Object.fromEntries(
deploymentActions(profile).flatMap((action) =>
committed.actions[action.id] && componentMatches(action.id)
Expand All @@ -191,7 +193,7 @@ export function restorePendingDeployment(
) as PendingDeployment['actions']
const addressComponentMatches = (key: DeploymentAddressKey) => {
const component = deploymentAddressComponents[key]
return component !== undefined && recordedComponents[component] === currentComponents[component]
return component !== undefined && retained(component)
}
const committedAddresses = Object.fromEntries(
Object.entries(committed.addresses).filter(([key]) =>
Comment on lines 200 to 201

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Operators who resume from a leftover pending file can get the old router reused, and the record republished with it, even though its code differs from the build. retained only filters the committed record's addresses and actions. cached.outputs and cached.actions from deployment.pending.json are merged back unfiltered at pending.ts:205-206. Fix: also drop cached outputs keyed to a replaced component (via deploymentAddressComponents) and cached actions whose step intent includes one. Keep cached entries for a router already redeployed in this replacement. The old release bump changed deploymentIntentHash, which discarded the cache.

Why this was flagged

A pending file with the same intent hash survives any run that called restorePendingDeployment (pending.ts:208 saves committed addresses such as earnRouter/zoneRouter into outputs) and then stopped before removePendingDeployment (deploy.ts:372). If the router source or compiler later changes, replacedComponents marks zone or zoneRouter. restorePendingDeployment then leaves out only the committed address. cached.outputs.earnRouter and cached.actions['deploy-router'] still survive through the spreads at lines 205-206. reconcile.ts:147 calls step.satisfied with pending.outputs, finds the old router deployed and bound, and does not redeploy it. On base, bumping routerContractRelease changed the pending header's deploymentIntentHash. That made loadPendingDeployment throw, so the catch at line 179 reset the cache and nothing stale was kept. No safeguard here covers cached state for replaced components, because the intent hash no longer changes.

Verification: Trigger: a deployment.pending.json with the same intent hash is still on disk when the router code changes. retained (pending.ts:184-186) only filters committed.actions and committed.addresses. pending.ts:205-206 still merges cached.outputs and cached.actions back unfiltered. Code replacement leaves the intent hash the same, so the stale cache now loads.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The latest push brings this issue back at deployments/core/pending.ts:206-221:

🔴 Operators who resume a paused router replacement after another router code change keep the first replacement, which is also stale. Hosted chains then hit a creation mismatch on every run; other chains silently record it. replacedAddress and staleReplacedAction treat any cached address or action that differs from the committed one as a current replacement (pending.ts:211, 218-221). They never check its code against this build. Fix: decide staleness of cached outputs by code identity, for example by running the replacedComponents check on the cached addresses too, and drop the dependent actions. A replacement that matches the build must still resume.

Why this was flagged

Router change A lands and Deploy deploys router A. The run then stops at a handoff or is interrupted before the record is rebuilt, so deployment.pending.json holds earnRouter/zoneRouter = A and the matching deploy-router action. Change B (source or solar.lock) lands before the resume. Because A !== C, replacedAddress (pending.ts:206-213) keeps A, and the deep-compare at 218-221 keeps A's action. reconcile.ts:147 step.satisfied accepts A and skips redeploying. On hosted chains, buildDeploymentRecord then calls assertStepCreation (creation.ts:76-88). It compares A's creation code with B's compiled bytecode and throws. Every rerun restores A again, so the deployment stays stuck until the operator deletes the pending file by hand. On the base branch, the release bump for B changed deploymentIntentHash, so loadPendingDeployment threw and the catch at pending.ts:180 reset the cache.

Verification: A is not C, so earnRouter = A and its deploy-router action survive in cachedOutputs/cachedActions. Nothing checks A's code against B. Every run fails the same way until an operator deletes deployment.pending.json by hand. Under base, the documented procedure for B was a release bump. That changed the intent hash, so loadPendingDeployment failed and the cache was reset.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The latest push brings this issue back at deployments/core/pending.ts:202-223:

🔴 An operator resuming after an interrupted router deploy can still get a router built from superseded code adopted, because only outputs and actions are screened for stale code. ...cached at pending.ts:223 carries latestOutputs through unfiltered, and staleCached never checks it. reconcile.ts:229-237 then adopts those recovered outputs once satisfied passes. Fix: give latestOutputs the same stale-code screen as cached outputs. Either drop its keys for staleCached components, or run replacedComponents over {...outputs, ...latestOutputs} in deploy.ts so recovery cannot bring back an old-build router. [also at: deployments/core/pending.ts:225 - An operator resuming an interrupted Earn router deploy after a further code change can still have the stale router adopted and recorded as current.; deployments/core/deploy.ts:193 - An operator resuming an interrupted first deployment after router code changes gets the stale router recorded as current.]

Why this was flagged

Trigger: the router is being replaced, and a Forge run writes latestOutputs but is interrupted before completeAction strips them (pending.ts:305). Then the router source or compiler changes again before the next Deploy. On that run, replaced flags the component from the committed router. staleCached is computed only from cachedPendingOutputs(...).outputs (deploy.ts:186-193, 780-786), which has no router key, so it comes back empty. restorePendingDeployment keeps latestOutputs via ...cached (pending.ts:223). In reconcile.ts:229-237, readActionOutputs reads latestOutputs, step.satisfied passes for the old-build router, and the step adopts and completes it. On local chains nothing else checks this, so the record is published with a router that is not this checkout's build. On hosted chains assertStepCreation (creation.ts:84) rejects the creation bytes instead, and every run fails until the operator removes the pending file by hand.

Verification: cachedPendingOutputs (deploy.ts:780-786) returns only loadPendingDeployment(...).outputs, and staleCached is computed from that alone (deploy.ts:186-193). latestOutputs comes through ...cached (pending.ts:223) unchanged. reconcile.ts:229-233 reads latestOutputs and adopts the step if step.satisfied passes. On the base, a release bump changed deploymentIntentHash and the whole cache was reset.

Expand Down
36 changes: 35 additions & 1 deletion deployments/core/provenance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ import {
type DeploymentSource,
type EarnDeploymentRecord,
} from './record.js'
import { runtimeCodeHash } from './releases.js'
import type { IntentComponent } from './components.js'
import {
normalizeImmutableReferences,
runtimeCodeHash,
type CompiledRuntimeCode,
} from './releases.js'
import { tempoVerifierUrl } from './verify.js'
import { deploymentSteps } from '../modules/index.js'
import {
Expand All @@ -35,6 +40,35 @@ export async function runtimeCodeHashes(
) as EarnDeploymentRecord['runtimeCodeHashes']
}

/**
* Intent components whose recorded replaceable contracts no longer run this checkout's build,
* compared with immutable slots zeroed; reconciliation replaces them like a changed intent.
*/
export async function replacedComponents(
client: Pick<PublicClient, 'getCode'>,
profile: EarnDeploymentProfile,
record: Pick<EarnDeploymentRecord, 'addresses'>,
compile: (contract: string) => CompiledRuntimeCode,
) {
const replaced = new Set<IntentComponent>()
for (const step of deploymentSteps) {
if (step.execution !== 'foundry' || !step.enabled(profile)) continue
const source = step.source
const recorded = source && record.addresses[source.output]
if (!source?.replaceOnCodeChange?.(profile) || !recorded) continue
const { bytecode, references } = compile(source.contract)
const deployed = await runtimeCodeHash(
client,
recorded,
`addresses.${source.output}`,
references,
)
if (deployed !== keccak256(normalizeImmutableReferences(bytecode, references)))
for (const component of step.intent) replaced.add(component)
}
return replaced
}

/**
* The block of the earliest receipt among the actions' transactions, every one of which must have
* succeeded; `undefined` when the actions carry none.
Expand Down
12 changes: 2 additions & 10 deletions deployments/modules/earn/zone-router/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,6 @@ export type ZoneRouterFields = { zone: ZoneRouterIntent | null }
/** The Zone identity a deployment record targets; sequencers are live state, not identity. */
export type ZoneTarget = Omit<ZoneIdentity, 'sequencers'>

// Bump when the immutable router implementation changes, invalidating pending activation too.
const routerContractRelease = 2

type ZoneProfile = SliceProfile<ZoneRouterFields>

/** Recorded Zone identity addresses, discovered from the canonical Factory rather than deployed. */
Expand Down Expand Up @@ -132,10 +129,10 @@ export const zoneRouterProfile = {
return { zone }
},
deploymentIntent: (profile: ZoneProfile) =>
profile.zone ? { zone: profile.zone, ...routerReleaseIntent() } : { zone: null },
profile.zone ? { zone: profile.zone } : { zone: null },
components: {
zone: (profile: ZoneProfile, deployment: string) =>
profile.zone ? { deployment, zone: profile.zone, ...routerReleaseIntent() } : null,
profile.zone ? { deployment, zone: profile.zone } : null,
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
},
externalAddresses: zoneIdentityAddresses,
addresses: { earnRouter: 'zone' },
Expand Down Expand Up @@ -217,8 +214,3 @@ function nonzeroBytes32(value: unknown, path: string): Hex {
throw new Error(`${path} must be a nonzero 32-byte hex string`)
return value.toLowerCase() as Hex
}

/** Release 1 retains existing record hashes; subsequent releases invalidate both router intents. */
export function routerReleaseIntent(release: number = routerContractRelease) {
return release === 1 ? {} : { routerContractRelease: release }
}
38 changes: 16 additions & 22 deletions deployments/modules/earn/zone-router/steps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@ import { zonePortalAbi } from '../../../abis/index.js'
import { zoneFactoryAddress, zoneMessengerAddress } from '../../../chain/zone.js'
import { parseEarnDeploymentProfile } from '../../../core/profile.js'
import { presentEarnDeploymentPlan } from '../../../core/plan.js'
import {
zoneRouterModeProfile,
routerReleaseIntent as modeReleaseIntent,
} from '../../zone-router/profile.js'
import { zoneRouterProfile, routerReleaseIntent } from './profile.js'
import { zoneRouterModeProfile } from '../../zone-router/profile.js'
import { deployZoneRouter, deployZoneRouterFactory } from '../../zone-router/steps.js'
import { zoneRouterProfile } from './profile.js'
import {
canAdministerZone,
deployRouter,
enableZoneTokens,
registerZoneGateway,
zoneAdministrator,
Expand Down Expand Up @@ -289,31 +288,26 @@ describe('preflightRouterRoute', () => {
})
})

describe('router release intent', () => {
test('puts the current release in the intent so a bump redeploys the routers', () => {
describe('router code identity', () => {
test('keeps router intent to the profile and replaces routers by their compiled code', () => {
expect(zoneRouterModeProfile.deploymentIntent(profile)).toEqual({
zoneRouter: profile.zoneRouter,
zoneRouterContractRelease: 2,
})
expect(zoneRouterModeProfile.components.zoneRouter(profile, 'deployment')).toHaveProperty(
expect(zoneRouterModeProfile.components.zoneRouter(profile, 'deployment')).not.toHaveProperty(
'contractRelease',
2,
)
expect(zoneRouterProfile.deploymentIntent(profile)).toEqual({
zone: profile.zone,
routerContractRelease: 2,
})
expect(zoneRouterProfile.deploymentIntent(profile)).toEqual({ zone: profile.zone })
expect(zoneRouterProfile.components.zone(profile, 'deployment')).toEqual({
deployment: 'deployment',
zone: profile.zone,
routerContractRelease: 2,
})
// Release 1 adds nothing, so records written before releases existed keep their hash.
expect(modeReleaseIntent(1)).toEqual({})
expect(routerReleaseIntent(1)).toEqual({})
expect(modeReleaseIntent(2)).toEqual({ zoneRouterContractRelease: 2 })
expect(routerReleaseIntent(2)).toEqual({ routerContractRelease: 2 })
expect(modeReleaseIntent(3)).not.toEqual(modeReleaseIntent(2))
expect(routerReleaseIntent(3)).not.toEqual(routerReleaseIntent(2))
expect(deployRouter.source?.replaceOnCodeChange?.(profile)).toBe(true)
expect(deployZoneRouterFactory.source?.replaceOnCodeChange?.(profile)).toBe(true)
expect(deployZoneRouter.source?.replaceOnCodeChange?.(profile)).toBe(true)
const namedFactory = {
...profile,
zoneRouter: { ...profile.zoneRouter!, factory: address('f') },
}
expect(deployZoneRouter.source?.replaceOnCodeChange?.(namedFactory)).toBe(false)
})
})
2 changes: 2 additions & 0 deletions deployments/modules/earn/zone-router/steps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ export const deployRouter = defineFoundryStep({
output: 'earnRouter',
contract: 'src/earn/router/SingleZoneEarnRouter.sol:SingleZoneEarnRouter',
accessMember: true,
// The router is immutable, so a router built from other code is replaced, not reused.
replaceOnCodeChange: () => true,
constructorArgs(profile, outputs) {
const { zoneId, earnVault, privateAsset, route } = routerArgs(profile, outputs)
return encodeAbiParameters(
Expand Down
5 changes: 5 additions & 0 deletions deployments/modules/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,11 @@ export type FoundryStep<Id extends string = string> = BaseStep<Id, typeof deploy
constructorArgs(profile: EarnDeploymentProfile, outputs: Record<string, Address>): Hex
/** Set when the contract moves EarnShare or the asset, so a protected EarnShare must whitelist it. */
accessMember?: AccessMember
/**
* Whether the contract is immutable periphery identified by this checkout's build: when its
* recorded runtime differs, reconciliation replaces it as if the step's intent had changed.
*/
replaceOnCodeChange?(profile: EarnDeploymentProfile): boolean
}
}

Expand Down
63 changes: 56 additions & 7 deletions deployments/modules/zone-router/compatibility.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ import { zoneRouterAbi } from '../../abis/index.js'
import { pendingDeploymentPath } from '../../core/bundle.js'
import { planEarnDeployment } from '../../core/plan.js'
import { restorePendingDeployment } from '../../core/pending.js'
import { replacedComponents } from '../../core/provenance.js'
import { componentDeploymentIntentHashes, parseEarnDeploymentProfile } from '../../core/profile.js'
import { prepareLifecycleStep } from '../../core/reconcile.js'
import type { ChainClient } from '../module.js'
import { zoneRouterModeModule } from './index.js'
import { zoneRouterMode, zoneRouterModeProfile } from './profile.js'
import { zoneRouterMode } from './profile.js'
import { deployZoneRouter } from './steps.js'

const rpc = vi.hoisted(() => ({ client: undefined as ChainClient | undefined }))
Expand Down Expand Up @@ -101,12 +102,6 @@ describe('retained Zone router ABI compatibility', () => {
actions: { 'deploy-zone-router-factory': completed, 'deploy-zone-router': completed },
}
const before = structuredClone(committed)
expect(zoneRouterModeProfile.components.zoneRouter(profile, 'deployment')).toMatchObject({
contractRelease: 2,
})
expect(
zoneRouterModeProfile.components.zoneRouterFactory(profile, 'deployment'),
).toMatchObject({ contractRelease: 2 })
const restored = restorePendingDeployment(profilePath, profile, committed)
expect(restored.outputs.zoneRouter).toBe(outputs.zoneRouter)
expect(restored.outputs.zoneRouterFactory).toBe(outputs.zoneRouterFactory)
Expand Down Expand Up @@ -135,6 +130,60 @@ describe('retained Zone router ABI compatibility', () => {
})
})

describe('router code identity', () => {
// Runtime bytes with one immutable byte at offset 1, which differs per deployment.
const compiled = { bytecode: '0x60aa60bb' as const, references: [{ start: 1, length: 1 }] }
const compile = () => ({ ...compiled, referenceGroups: [compiled.references] })
const deployedAt = (code: Record<string, string>) =>
({ getCode: async ({ address }: { address: Address }) => code[address] }) as never

test('keeps routers whose runtime matches the build apart from immutables', async () => {
const client = deployedAt({
[outputs.zoneRouterFactory]: '0x60ff60bb',
[outputs.zoneRouter]: '0x601160bb',
})
expect(await replacedComponents(client, profile, { addresses: outputs }, compile)).toEqual(
new Set(),
)
})

test('replaces a router built from other code with the components its deployment depends on', async () => {
const client = deployedAt({
[outputs.zoneRouterFactory]: '0x60ff60bb',
[outputs.zoneRouter]: '0x601160cc',
})
expect(await replacedComponents(client, profile, { addresses: outputs }, compile)).toEqual(
new Set(['zoneRouterFactory', 'zoneRouter']),
)
})

test('restores neither the address nor the actions of a replaced component', () => {
const root = mkdtempSync(join(tmpdir(), 'zone-router-replaced-'))
try {
const completed = {
completedAt: '2026-01-01T00:00:00.000Z',
verification: 'chain' as const,
transactions: [`0x${'a'.repeat(64)}` as const],
}
const restored = restorePendingDeployment(
join(root, 'profile.json'),
profile,
{
componentDeploymentIntentHashes: componentDeploymentIntentHashes(profile),
addresses: outputs,
actions: { 'deploy-zone-router-factory': completed, 'deploy-zone-router': completed },
},
new Set(['zoneRouter']),
)
expect(restored.outputs.zoneRouter).toBeUndefined()
expect(restored.outputs.zoneRouterFactory).toBe(outputs.zoneRouterFactory)
expect(restored.actions).toEqual({ 'deploy-zone-router-factory': completed })
} finally {
rmSync(root, { recursive: true, force: true })
}
})
})

/** The historical Earn ABI has settlers(), not spenders(), with otherwise matching bindings. */
function chain(error?: Error) {
const mode = zoneRouterMode(profile, outputs)
Expand Down
16 changes: 2 additions & 14 deletions deployments/modules/zone-router/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,6 @@ export type ZoneRouterFields = { zoneRouter: ZoneRouterIntent | null }

type RouterProfile = SliceProfile<ZoneRouterFields>

// Immutable router and factory have no upgrade path. Bump when either's deployed runtime changes so
// reconciliation deploys a new factory and router instead of reusing the recorded ones.
const zoneRouterContractRelease = 2

/**
* The `zoneRouter` slice: a `ZoneRouter` mode from `zone-router/`, the `ZoneRouterFactory` that deploys it
* unless the profile names one, and the Portal of the Zone it serves. Each is optional periphery, so
Expand All @@ -79,16 +75,13 @@ export const zoneRouterModeProfile = {
profile.zoneRouter ? { zoneRouter: profile.zoneRouter } : {},
// Absent, it adds nothing, so profiles without a router keep their deployment intent hash.
deploymentIntent: (profile: RouterProfile) =>
profile.zoneRouter ? { zoneRouter: profile.zoneRouter, ...routerReleaseIntent() } : {},
profile.zoneRouter ? { zoneRouter: profile.zoneRouter } : {},
components: {
zoneRouterFactory: (profile: RouterProfile, deployment: string) =>
profile.zoneRouter && profile.zoneRouter.factory === undefined
? { contractRelease: zoneRouterContractRelease, deployment }
: null,
profile.zoneRouter && profile.zoneRouter.factory === undefined ? { deployment } : null,
zoneRouter: (profile: RouterProfile, deployment: string) =>
profile.zoneRouter
? {
contractRelease: zoneRouterContractRelease,
deployment,
earnVault: profile.zoneRouter.earn ? 'derived' : null,
zoneRouter: profile.zoneRouter,
Expand Down Expand Up @@ -203,8 +196,3 @@ function parseEarn(value: Record<string, unknown>, path: string): ZoneRouterEarn
customerId: value.customerId.toLowerCase() as Hex,
}
}

/** Release 1 retains existing record hashes; every later release changes the pending identity. */
export function routerReleaseIntent(release: number = zoneRouterContractRelease) {
return release === 1 ? {} : { zoneRouterContractRelease: release }
}
Loading