Skip to content

Commit eb2103c

Browse files
authored
feat: public data tree overrides for simulation (#22830)
Extends `SimulationOverrides` with a `publicStorage` field, plumbed through `.simulate({ overrides })` on aztec.js → wallet → PXE → `AztecNode.simulatePublicCalls`. Each entry writes a `(contract, slot, value)` into the public-data tree of the ephemeral world-state fork before the tx runs; real chain state is untouched. ```typescript const result = await contract.methods.read_balance(account).simulate({ overrides: { publicStorage: [{ contract: contract.address, slot: BALANCE_SLOT, value: new Fr(1_000_000n) }], }, }); ``` ## Test plan - Unit tests in `aztec-node/src/aztec-node/public_data_overrides.test.ts`. - E2E `e2e_avm_simulator` `publicDataOverrides` describe block. - `migration_notes.md` and `how_to_test.md` updated.
1 parent 5f305cc commit eb2103c

18 files changed

Lines changed: 301 additions & 19 deletions

File tree

docs/docs-developers/docs/aztec-js/how_to_test.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,22 @@ Test that invalid operations revert as expected:
6767

6868
Use `.simulate()` to test reverts without spending gas. The simulation will throw if the transaction would fail onchain.
6969

70+
## Simulating with overrides
71+
72+
`.simulate()` accepts an `overrides` option that injects values into the simulator's (ephemeral) world-state fork and contract DB before the call runs. The override is scoped to that single simulation and thrown away afterwards.
73+
74+
Override a public-storage slot:
75+
76+
```typescript
77+
const result = await contract.methods.read_balance(account).simulate({
78+
overrides: {
79+
publicStorage: [{ contract: contract.address, slot: BALANCE_SLOT, value: new Fr(1_000_000n) }],
80+
},
81+
});
82+
```
83+
84+
Use this to set up state preconditions, reproduce production bugs against pinned storage, or exercise rare value branches without orchestrating the contract calls that produce them.
85+
7086
## Further reading
7187

7288
- [How to read contract data](./how_to_read_data.md)

docs/docs-developers/docs/resources/migration_notes.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,27 @@ If you set `Noir: Nargo Path` in the VS Code Noir extension to `$HOME/.aztec/cur
164164
+ overrides = { contracts: { [addr.toString()]: { instance: { ...instance, currentContractClassId: stubClassId } } } };
165165
```
166166

167+
### [Aztec.js] `simulate` accepts `overrides` for testing "what if storage value was X?"
168+
169+
`Contract.methods.foo(...).simulate(...)` now accepts an `overrides` option that injects values into the simulator's (ephemeral) world-state fork and contract DB before the call runs. The supported field is `publicStorage`, which writes a `(contract, slot, value)` into the public-data tree as if a previous tx had set it. Overrides are thrown away after simulation completes.
170+
171+
```typescript
172+
const result = await contract.methods.read_balance(account).simulate({
173+
overrides: {
174+
publicStorage: [{ contract: contract.address, slot: BALANCE_SLOT, value: new Fr(1_000_000n) }],
175+
},
176+
});
177+
```
178+
179+
The same option flows through `wallet.simulateTx` and eventually to `simulatePublicCalls` RPC on `AztecNode`.
180+
181+
Direct callers of the `SimulationOverrides` constructor must switch from a positional `contracts` argument to an options bag:
182+
183+
```diff
184+
- new SimulationOverrides(contracts);
185+
+ new SimulationOverrides({ contracts });
186+
```
187+
167188
### [PXE] `proveTx` takes an options bag
168189

169190
`PXE.proveTx` used to accept `scopes` as a positional argument; it now takes an options bag consistent with `simulateTx` and `profileTx`, and adds an optional `senderForTags` field. Update direct callers:
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import { Fr } from '@aztec/foundation/curves/bn254';
2+
import { PublicDataWrite } from '@aztec/stdlib/avm';
3+
import { AztecAddress } from '@aztec/stdlib/aztec-address';
4+
import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
5+
import type { MerkleTreeWriteOperations } from '@aztec/stdlib/interfaces/server';
6+
import { MerkleTreeId } from '@aztec/stdlib/trees';
7+
8+
import { type MockProxy, mock } from 'jest-mock-extended';
9+
10+
import { applyPublicDataOverrides } from './public_data_overrides.js';
11+
12+
describe('applyPublicDataOverrides', () => {
13+
let fork: MockProxy<MerkleTreeWriteOperations>;
14+
15+
beforeEach(() => {
16+
fork = mock<MerkleTreeWriteOperations>();
17+
fork.sequentialInsert.mockResolvedValue({ lowLeavesWitnesses: [], insertionWitnesses: [] } as any);
18+
});
19+
20+
it('does nothing when overrides is undefined', async () => {
21+
await applyPublicDataOverrides(fork, undefined);
22+
expect(fork.sequentialInsert).not.toHaveBeenCalled();
23+
});
24+
25+
it('does nothing when overrides is empty', async () => {
26+
await applyPublicDataOverrides(fork, []);
27+
expect(fork.sequentialInsert).not.toHaveBeenCalled();
28+
});
29+
30+
it('inserts a single override at the correct leaf slot', async () => {
31+
const contract = await AztecAddress.random();
32+
const slot = Fr.random();
33+
const value = Fr.random();
34+
35+
await applyPublicDataOverrides(fork, [{ contract, slot, value }]);
36+
37+
const expectedLeafSlot = await computePublicDataTreeLeafSlot(contract, slot);
38+
const expectedWrite = new PublicDataWrite(expectedLeafSlot, value);
39+
40+
expect(fork.sequentialInsert).toHaveBeenCalledTimes(1);
41+
expect(fork.sequentialInsert).toHaveBeenCalledWith(MerkleTreeId.PUBLIC_DATA_TREE, [expectedWrite.toBuffer()]);
42+
});
43+
44+
it('inserts multiple overrides in a single batch call', async () => {
45+
const contract = await AztecAddress.random();
46+
const overrides = [
47+
{ contract, slot: Fr.random(), value: Fr.random() },
48+
{ contract, slot: Fr.random(), value: Fr.random() },
49+
];
50+
51+
await applyPublicDataOverrides(fork, overrides);
52+
53+
const expectedWrites = await Promise.all(
54+
overrides.map(async o => {
55+
const leafSlot = await computePublicDataTreeLeafSlot(o.contract, o.slot);
56+
return new PublicDataWrite(leafSlot, o.value);
57+
}),
58+
);
59+
60+
expect(fork.sequentialInsert).toHaveBeenCalledTimes(1);
61+
expect(fork.sequentialInsert).toHaveBeenCalledWith(
62+
MerkleTreeId.PUBLIC_DATA_TREE,
63+
expectedWrites.map(w => w.toBuffer()),
64+
);
65+
});
66+
67+
it('passes duplicate (contract, slot) writes through — last write wins via tree semantics', async () => {
68+
const contract = await AztecAddress.random();
69+
const slot = Fr.random();
70+
const firstValue = Fr.random();
71+
const secondValue = Fr.random();
72+
73+
await applyPublicDataOverrides(fork, [
74+
{ contract, slot, value: firstValue },
75+
{ contract, slot, value: secondValue },
76+
]);
77+
78+
// Both writes are passed to sequentialInsert; the tree handles last-wins ordering.
79+
expect(fork.sequentialInsert).toHaveBeenCalledTimes(1);
80+
const [treeId, leaves] = fork.sequentialInsert.mock.calls[0] as [MerkleTreeId, Buffer[]];
81+
expect(treeId).toBe(MerkleTreeId.PUBLIC_DATA_TREE);
82+
expect(leaves).toHaveLength(2);
83+
});
84+
});
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { PublicDataWrite } from '@aztec/stdlib/avm';
2+
import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
3+
import type { PublicStorageOverride } from '@aztec/stdlib/interfaces/client';
4+
import type { MerkleTreeWriteOperations } from '@aztec/stdlib/interfaces/server';
5+
import { MerkleTreeId } from '@aztec/stdlib/trees';
6+
7+
/**
8+
* Injects public-state overrides into an (ephemeral) world-state fork before simulation.
9+
*
10+
* Each override is written via the same `sequentialInsert` path the public processor
11+
* uses during real transaction execution, so low-leaf updates and root coherence are
12+
* handled identically for both simulation and proof generation.
13+
*
14+
* Writes never reach committed world state — the fork is thrown away after simulation.
15+
*/
16+
export async function applyPublicDataOverrides(
17+
fork: MerkleTreeWriteOperations,
18+
publicStorage: PublicStorageOverride[] | undefined,
19+
): Promise<void> {
20+
if (!publicStorage?.length) {
21+
return;
22+
}
23+
24+
const writes = await Promise.all(
25+
publicStorage.map(async o => {
26+
const leafSlot = await computePublicDataTreeLeafSlot(o.contract, o.slot);
27+
return new PublicDataWrite(leafSlot, o.value);
28+
}),
29+
);
30+
31+
await fork.sequentialInsert(
32+
MerkleTreeId.PUBLIC_DATA_TREE,
33+
writes.map(w => w.toBuffer()),
34+
);
35+
}

yarn-project/aztec-node/src/aztec-node/server.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ import {
106106
type GlobalVariableBuilder as GlobalVariableBuilderInterface,
107107
type IndexedTxEffect,
108108
PublicSimulationOutput,
109+
type SimulationOverrides,
109110
Tx,
110111
type TxHash,
111112
TxReceipt,
@@ -146,6 +147,7 @@ import {
146147
} from './block_response_helpers.js';
147148
import { type AztecNodeConfig, createKeyStoreForValidator } from './config.js';
148149
import { NodeMetrics } from './node_metrics.js';
150+
import { applyPublicDataOverrides } from './public_data_overrides.js';
149151

150152
/**
151153
* The aztec node.
@@ -1440,11 +1442,17 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
14401442
/**
14411443
* Simulates the public part of a transaction with the current state.
14421444
* @param tx - The transaction to simulate.
1445+
* @param skipFeeEnforcement - If true, fee enforcement is skipped.
1446+
* @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
14431447
**/
14441448
@trackSpan('AztecNodeService.simulatePublicCalls', (tx: Tx) => ({
14451449
[Attributes.TX_HASH]: tx.getTxHash().toString(),
14461450
}))
1447-
public async simulatePublicCalls(tx: Tx, skipFeeEnforcement = false): Promise<PublicSimulationOutput> {
1451+
public async simulatePublicCalls(
1452+
tx: Tx,
1453+
skipFeeEnforcement = false,
1454+
overrides?: SimulationOverrides,
1455+
): Promise<PublicSimulationOutput> {
14481456
// Check total gas limit for simulation
14491457
const gasSettings = tx.data.constants.txContext.gasSettings;
14501458
const txGasLimit = gasSettings.gasLimits.l2Gas;
@@ -1489,6 +1497,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
14891497
await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
14901498
const merkleTreeFork = await this.worldStateSynchronizer.fork();
14911499
try {
1500+
await applyPublicDataOverrides(merkleTreeFork, overrides?.publicStorage);
14921501
const config = PublicSimulatorConfig.from({
14931502
skipFeeEnforcement,
14941503
collectDebugLogs: true,

yarn-project/aztec.js/src/api/wallet.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,4 +78,7 @@ export { AccountManager } from '../wallet/account_manager.js';
7878

7979
export { TxSimulationResultWithAppOffset } from '../wallet/tx_simulation_result_with_app_offset.js';
8080

81+
export { type PublicStorageOverride, PublicStorageOverrideSchema } from '@aztec/stdlib/interfaces/client';
82+
export { SimulationOverrides } from '@aztec/stdlib/tx';
83+
8184
export { type DeployAccountOptions, DeployAccountMethod } from '../wallet/deploy_account_method.js';

yarn-project/aztec.js/src/contract/interaction_options.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
type Capsule,
88
OFFCHAIN_MESSAGE_IDENTIFIER,
99
type OffchainEffect,
10+
type SimulationOverrides,
1011
type SimulationStats,
1112
type TxHash,
1213
type TxReceipt,
@@ -157,6 +158,8 @@ export type SimulateInteractionOptions = Omit<SendInteractionOptions, 'fee'> & {
157158
/** Whether to include metadata such as performance statistics (e.g. timing information of the different circuits and oracles) and gas estimation
158159
* in the simulation result, in addition to the return value and offchain effects */
159160
includeMetadata?: boolean;
161+
/** Pre-simulation overrides applied to the ephemeral fork and contract DB (publicStorage writes, contract instance overrides). */
162+
overrides?: SimulationOverrides;
160163
};
161164

162165
/**

yarn-project/aztec.js/src/wallet/wallet.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import type { ExecutionPayload, InTx } from '@aztec/stdlib/tx';
1919
import {
2020
Capsule,
2121
HashedValues,
22+
SimulationOverrides,
2223
TxHash,
2324
TxProfileResult,
2425
TxReceipt,
@@ -335,6 +336,7 @@ export const SimulateOptionsSchema = z.object({
335336
skipFeeEnforcement: optional(z.boolean()),
336337
includeMetadata: optional(z.boolean()),
337338
additionalScopes: optional(z.array(schemas.AztecAddress)),
339+
overrides: optional(SimulationOverrides.schema),
338340
});
339341

340342
export const ProfileOptionsSchema = SimulateOptionsSchema.extend({

yarn-project/end-to-end/src/e2e_avm_simulator.test.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { AztecAddress } from '@aztec/aztec.js/addresses';
22
import { BatchCall, type ContractInstanceWithAddress } from '@aztec/aztec.js/contracts';
33
import { Fr } from '@aztec/aztec.js/fields';
4+
import type { AztecNode } from '@aztec/aztec.js/node';
45
import { TxExecutionResult } from '@aztec/aztec.js/tx';
6+
import type { PublicStorageOverride } from '@aztec/aztec.js/wallet';
57
import type { Wallet } from '@aztec/aztec.js/wallet';
68
import { AvmInitializerTestContract } from '@aztec/noir-test-contracts.js/AvmInitializerTest';
79
import { AvmTestContract } from '@aztec/noir-test-contracts.js/AvmTest';
@@ -16,13 +18,15 @@ describe('e2e_avm_simulator', () => {
1618
jest.setTimeout(TIMEOUT);
1719

1820
let wallet: Wallet;
21+
let aztecNode: AztecNode;
1922
let defaultAccountAddress: AztecAddress;
2023
let teardown: () => Promise<void>;
2124

2225
beforeAll(async () => {
2326
({
2427
teardown,
2528
wallet,
29+
aztecNode,
2630
accounts: [defaultAccountAddress],
2731
} = await setup(1));
2832
await ensureAccountContractsPublished(wallet, [defaultAccountAddress]);
@@ -251,6 +255,51 @@ describe('e2e_avm_simulator', () => {
251255
});
252256
});
253257

258+
describe('publicDataOverrides', () => {
259+
// AvmTestContract: `single` is the first storage variable and lives at raw slot 1.
260+
const SINGLE_SLOT = new Fr(1n);
261+
let avmContract: AvmTestContract;
262+
263+
beforeEach(async () => {
264+
({ contract: avmContract } = await AvmTestContract.deploy(wallet).send({ from: defaultAccountAddress }));
265+
});
266+
267+
it('simulated read of an unwritten slot returns the override; real storage is untouched', async () => {
268+
const overrideValue = new Fr(0xdeadbeefn);
269+
const publicStorage: PublicStorageOverride[] = [
270+
{ contract: avmContract.address, slot: SINGLE_SLOT, value: overrideValue },
271+
];
272+
273+
const simResult = await avmContract.methods
274+
.read_storage_single()
275+
.simulate({ from: defaultAccountAddress, overrides: { publicStorage } });
276+
expect(simResult.result).toEqual(overrideValue.toBigInt());
277+
278+
// Real state is untouched — the slot was never written.
279+
const realValue = await aztecNode.getPublicStorageAt('latest', avmContract.address, SINGLE_SLOT);
280+
expect(realValue.toBigInt()).toEqual(0n);
281+
});
282+
283+
it('simulated read returns the override when a slot was previously written by a real tx', async () => {
284+
const realValue = new Fr(100n);
285+
await avmContract.methods.set_storage_single(realValue).send({ from: defaultAccountAddress });
286+
287+
const overrideValue = new Fr(999n);
288+
const publicStorage: PublicStorageOverride[] = [
289+
{ contract: avmContract.address, slot: SINGLE_SLOT, value: overrideValue },
290+
];
291+
292+
const simResult = await avmContract.methods
293+
.read_storage_single()
294+
.simulate({ from: defaultAccountAddress, overrides: { publicStorage } });
295+
expect(simResult.result).toEqual(overrideValue.toBigInt());
296+
297+
// Real storage still holds the original written value.
298+
const storedValue = await aztecNode.getPublicStorageAt('latest', avmContract.address, SINGLE_SLOT);
299+
expect(storedValue.toBigInt()).toEqual(realValue.toBigInt());
300+
});
301+
});
302+
254303
describe('AvmInitializerTestContract', () => {
255304
let avmContract: AvmInitializerTestContract;
256305

yarn-project/end-to-end/src/test-wallet/test_wallet.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -287,11 +287,14 @@ export class TestWallet extends BaseWallet {
287287
: executionPayload;
288288
const chainInfo = await this.getChainInfo();
289289

290-
let overrides: SimulationOverrides | undefined;
290+
let overrides = opts.overrides;
291291
let txRequest: TxExecutionRequest;
292292
if (useOverride) {
293293
const accountOverrides = await this.buildAccountOverrides(scopes);
294-
overrides = new SimulationOverrides(accountOverrides);
294+
overrides = new SimulationOverrides({
295+
publicStorage: overrides?.publicStorage,
296+
contracts: { ...overrides?.contracts, ...accountOverrides },
297+
});
295298
}
296299

297300
if (from === NO_FROM) {

0 commit comments

Comments
 (0)