@aztec/ethereum 0.0.1-commit.8afd444 → 0.0.1-commit.8f9871590

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.
@@ -0,0 +1,280 @@
1
+ import { memoize } from '@aztec/foundation/decorators';
2
+ import { EthAddress } from '@aztec/foundation/eth-address';
3
+ import { type Logger, createLogger } from '@aztec/foundation/log';
4
+
5
+ import { type Hex, encodeAbiParameters, getContract, keccak256, parseAbiParameters } from 'viem';
6
+
7
+ import type { ViemClient } from '../types.js';
8
+ import { RollupContract } from './rollup.js';
9
+
10
+ /** Maximum price modifier per checkpoint in basis points. ±100 bps = ±1% */
11
+ export const MAX_FEE_ASSET_PRICE_MODIFIER_BPS = 100n;
12
+
13
+ /**
14
+ * Validates that a fee asset price modifier is within the allowed range.
15
+ * Validators should call this before attesting to a checkpoint proposal.
16
+ *
17
+ * @param modifier - The fee asset price modifier in basis points
18
+ * @returns true if the modifier is valid (between -100 and +100 bps)
19
+ */
20
+ export function validateFeeAssetPriceModifier(modifier: bigint): boolean {
21
+ return modifier >= -MAX_FEE_ASSET_PRICE_MODIFIER_BPS && modifier <= MAX_FEE_ASSET_PRICE_MODIFIER_BPS;
22
+ }
23
+
24
+ /**
25
+ * Oracle for computing fee asset price modifiers based on Uniswap V4 pool prices.
26
+ * Only active on Ethereum mainnet - returns 0 on other chains.
27
+ */
28
+ export class FeeAssetPriceOracle {
29
+ constructor(
30
+ private client: ViemClient,
31
+ private readonly rollupContract: RollupContract,
32
+ private log: Logger = createLogger('fee-asset-price-oracle'),
33
+ ) {}
34
+
35
+ @memoize
36
+ async getUniswapOracle(): Promise<UniswapPriceOracle | undefined> {
37
+ const code = await this.client.getCode({ address: STATE_VIEW_ADDRESS.toString() });
38
+ if (code === undefined || code === '0x') {
39
+ this.log.warn('Uniswap V4 StateView contract not found, skipping fee asset price oracle');
40
+ return undefined;
41
+ }
42
+ this.log.info('Uniswap V4 StateView contract found, initializing fee asset price oracle');
43
+ const oracle = new UniswapPriceOracle(this.client, this.log);
44
+
45
+ try {
46
+ if (!(await oracle.isPoolInitialized())) {
47
+ this.log.warn('Uniswap V4 pool not initialized, skipping fee asset price oracle');
48
+ return undefined;
49
+ }
50
+ } catch (err) {
51
+ this.log.warn(`Failed to check if Uniswap V4 pool is initialized: ${err}`);
52
+ return undefined;
53
+ }
54
+
55
+ return oracle;
56
+ }
57
+
58
+ /**
59
+ * Computes the fee asset price modifier to be used in the next checkpoint proposal.
60
+ *
61
+ * The modifier adjusts the on-chain fee asset price toward the oracle price,
62
+ * clamped to ±1% (±100 basis points) per checkpoint.
63
+ *
64
+ * Returns 0 if not on mainnet or if the oracle query fails.
65
+ *
66
+ * @returns The price modifier in basis points (positive to increase price, negative to decrease)
67
+ */
68
+ async computePriceModifier(): Promise<bigint> {
69
+ const uniswapOracle = await this.getUniswapOracle();
70
+ if (!uniswapOracle) {
71
+ return 0n;
72
+ }
73
+
74
+ try {
75
+ // Get current on-chain price (ETH per fee asset, E12)
76
+ const currentPriceE12 = await this.rollupContract.getEthPerFeeAsset();
77
+
78
+ // Get oracle price (median of last N blocks, ETH per fee asset, E12)
79
+ const oraclePriceE12 = await uniswapOracle.getMeanEthPerFeeAssetE12();
80
+
81
+ // Compute modifier in basis points
82
+ const modifier = this.computePriceModifierBps(currentPriceE12, oraclePriceE12);
83
+
84
+ this.log.debug('Computed price modifier', {
85
+ currentPriceE12: currentPriceE12.toString(),
86
+ oraclePriceE12: oraclePriceE12.toString(),
87
+ modifierBps: modifier.toString(),
88
+ });
89
+
90
+ return modifier;
91
+ } catch (err) {
92
+ this.log.warn(`Failed to compute price modifier, using 0: ${err}`);
93
+ return 0n;
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Gets the current oracle price (ETH per fee asset, scaled by 1e12).
99
+ * Returns undefined if not on mainnet or if the oracle query fails.
100
+ */
101
+ async getOraclePrice(): Promise<bigint | undefined> {
102
+ const uniswapOracle = await this.getUniswapOracle();
103
+ if (!uniswapOracle) {
104
+ return undefined;
105
+ }
106
+
107
+ try {
108
+ return await uniswapOracle.getMeanEthPerFeeAssetE12();
109
+ } catch (err) {
110
+ this.log.warn(`Failed to get oracle price: ${err}`);
111
+ return undefined;
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Computes the basis points modifier needed to move from current price toward target price.
117
+ *
118
+ * @param currentPrice - Current ETH per fee asset (E12 scale)
119
+ * @param targetPrice - Target ETH per fee asset (E12 scale)
120
+ * @returns Basis points modifier clamped to ±100 (±1%)
121
+ */
122
+ computePriceModifierBps(currentPrice: bigint, targetPrice: bigint): bigint {
123
+ if (currentPrice === 0n) {
124
+ return MAX_FEE_ASSET_PRICE_MODIFIER_BPS;
125
+ }
126
+
127
+ // Calculate percentage difference in basis points
128
+ // modifierBps = ((targetPrice - currentPrice) / currentPrice) * 10000
129
+ const diff = targetPrice - currentPrice;
130
+ const rawModifierBps = (diff * 10_000n) / currentPrice;
131
+
132
+ // Clamp to ±MAX_FEE_ASSET_PRICE_MODIFIER_BPS
133
+ if (rawModifierBps > MAX_FEE_ASSET_PRICE_MODIFIER_BPS) {
134
+ return MAX_FEE_ASSET_PRICE_MODIFIER_BPS;
135
+ }
136
+ if (rawModifierBps < -MAX_FEE_ASSET_PRICE_MODIFIER_BPS) {
137
+ return -MAX_FEE_ASSET_PRICE_MODIFIER_BPS;
138
+ }
139
+ return rawModifierBps;
140
+ }
141
+ }
142
+
143
+ /** Mainnet Uniswap V4 StateView contract address */
144
+ export const STATE_VIEW_ADDRESS = EthAddress.fromString('0x7ffe42c4a5deea5b0fec41c94c136cf115597227');
145
+
146
+ const PRECISION_Q192 = 10n ** 12n * 2n ** 192n;
147
+
148
+ /**
149
+ * Converts Uniswap's sqrtPriceX96 directly to ETH per FeeAsset (E12).
150
+ *
151
+ * For an ETH/FeeAsset pool where ETH is currency0 and FeeAsset is currency1:
152
+ * - Uniswap's sqrtPriceX96 = sqrt(FeeAsset/ETH) * 2^96
153
+ * - We need: ETH/FeeAsset with 1e12 precision
154
+ *
155
+ * Math:
156
+ * price = (sqrtPriceX96 / 2^96)^2 = sqrtPriceX96^2 / 2^192 (FeeAsset per ETH)
157
+ * ethPerFeeAsset = 1 / price = 2^192 / sqrtPriceX96^2
158
+ * ethPerFeeAssetE12 = ethPerFeeAsset * 1e12 = 1e12 * 2^192 / sqrtPriceX96^2
159
+ */
160
+ export function sqrtPriceX96ToEthPerFeeAssetE12(sqrtPriceX96: bigint): bigint {
161
+ if (sqrtPriceX96 === 0n) {
162
+ throw new Error('Cannot convert zero sqrtPriceX96');
163
+ }
164
+ return PRECISION_Q192 / (sqrtPriceX96 * sqrtPriceX96);
165
+ }
166
+ /**
167
+ * Uniswap V4 StateView ABI - only the functions we need
168
+ */
169
+ const StateViewAbi = [
170
+ {
171
+ type: 'function',
172
+ name: 'getSlot0',
173
+ inputs: [{ name: 'poolId', type: 'bytes32', internalType: 'PoolId' }],
174
+ outputs: [
175
+ { name: 'sqrtPriceX96', type: 'uint160', internalType: 'uint160' },
176
+ { name: 'tick', type: 'int24', internalType: 'int24' },
177
+ { name: 'protocolFee', type: 'uint24', internalType: 'uint24' },
178
+ { name: 'lpFee', type: 'uint24', internalType: 'uint24' },
179
+ ],
180
+ stateMutability: 'view',
181
+ },
182
+ ] as const;
183
+
184
+ /**
185
+ * Client for querying the ETH/FeeAsset price from Uniswap V4.
186
+ * Returns prices in ETH per FeeAsset format (E12) to match the rollup contract.
187
+ */
188
+ class UniswapPriceOracle {
189
+ private readonly stateView;
190
+ private readonly poolId: Hex;
191
+ private readonly log: Logger;
192
+
193
+ constructor(
194
+ private readonly client: ViemClient,
195
+ log?: Logger,
196
+ ) {
197
+ this.log = log ?? createLogger('uniswap-price-oracle');
198
+ this.stateView = getContract({
199
+ address: STATE_VIEW_ADDRESS.toString(),
200
+ abi: StateViewAbi,
201
+ client,
202
+ });
203
+ this.poolId = this.computePoolId();
204
+ this.log.debug(`Initialized UniswapPriceOracle with poolId: ${this.poolId}`);
205
+ }
206
+
207
+ /**
208
+ * Computes the PoolId from the pool configuration by hashing its components.
209
+ * PoolId = keccak256(abi.encode(currency0, currency1, fee, tickSpacing, hooks))
210
+ * For mainnet, the value is expected to be: 0xce2899b16743cfd5a954d8122d5e07f410305b1aebee39fd73d9f3b9ebf10c2f
211
+ * Derived anyway to make it simpler to change if needed.
212
+ */
213
+ @memoize
214
+ computePoolId(): Hex {
215
+ /** ETH/FeeAsset pool configuration (hardcoded for mainnet) */
216
+ const encoded = encodeAbiParameters(parseAbiParameters('address, address, uint24, int24, address'), [
217
+ EthAddress.ZERO.toString(),
218
+ EthAddress.fromString('0xA27EC0006e59f245217Ff08CD52A7E8b169E62D2').toString(),
219
+ 500, // 0.05%
220
+ 10,
221
+ EthAddress.fromString('0xd53006d1e3110fD319a79AEEc4c527a0d265E080').toString(),
222
+ ]);
223
+ return keccak256(encoded);
224
+ }
225
+
226
+ async isPoolInitialized(): Promise<boolean> {
227
+ const [sqrtPriceX96] = await this.stateView.read.getSlot0([this.poolId], undefined);
228
+ return sqrtPriceX96 !== 0n;
229
+ }
230
+
231
+ /**
232
+ * Gets the price as ETH per FeeAsset, scaled by 1e12.
233
+ * This is the format expected by the rollup contract.
234
+ *
235
+ * @param blockNumber - Optional block number to query at (defaults to latest)
236
+ */
237
+ async getEthPerFeeAssetE12(blockNumber?: bigint): Promise<bigint> {
238
+ const [sqrtPriceX96] = await this.stateView.read.getSlot0(
239
+ [this.poolId],
240
+ blockNumber !== undefined ? { blockNumber } : undefined,
241
+ );
242
+ return sqrtPriceX96ToEthPerFeeAssetE12(sqrtPriceX96);
243
+ }
244
+
245
+ /**
246
+ * Gets the median price over the last N blocks as ETH per FeeAsset (E12).
247
+ * Using median helps protect against single-block manipulation.
248
+ *
249
+ * @param numBlocks - Number of recent blocks to sample (default: 5)
250
+ * @returns Median price as ETH per FeeAsset, scaled by 1e12
251
+ */
252
+ async getMeanEthPerFeeAssetE12(numBlocks: number = 5): Promise<bigint> {
253
+ const currentBlock = await this.client.getBlockNumber();
254
+ const prices: bigint[] = [];
255
+
256
+ for (let i = 0; i < numBlocks; i++) {
257
+ const blockNumber = currentBlock - BigInt(i);
258
+ if (blockNumber < 0n) {
259
+ break;
260
+ }
261
+
262
+ try {
263
+ const price = await this.getEthPerFeeAssetE12(blockNumber);
264
+ prices.push(price);
265
+ } catch (err) {
266
+ this.log.warn(`Failed to get price at block ${blockNumber}: ${err}`);
267
+ // Continue with fewer samples
268
+ }
269
+ }
270
+
271
+ const filteredPrices = prices.filter(price => price !== 0n);
272
+
273
+ if (filteredPrices.length === 0) {
274
+ throw new Error('Failed to get any price samples from Uniswap oracle');
275
+ }
276
+
277
+ const mean = filteredPrices.reduce((a, b) => a + b, 0n) / BigInt(filteredPrices.length);
278
+ return mean;
279
+ }
280
+ }
@@ -1,6 +1,7 @@
1
1
  export * from './empire_base.js';
2
2
  export * from './errors.js';
3
3
  export * from './fee_asset_handler.js';
4
+ export * from './fee_asset_price_oracle.js';
4
5
  export * from './fee_juice.js';
5
6
  export * from './governance.js';
6
7
  export * from './governance_proposer.js';
@@ -391,20 +391,24 @@ export class RollupContract {
391
391
  slotDuration: number;
392
392
  epochDuration: number;
393
393
  proofSubmissionEpochs: number;
394
+ targetCommitteeSize: number;
394
395
  }> {
395
- const [l1StartBlock, l1GenesisTime, slotDuration, epochDuration, proofSubmissionEpochs] = await Promise.all([
396
- this.getL1StartBlock(),
397
- this.getL1GenesisTime(),
398
- this.getSlotDuration(),
399
- this.getEpochDuration(),
400
- this.getProofSubmissionEpochs(),
401
- ]);
396
+ const [l1StartBlock, l1GenesisTime, slotDuration, epochDuration, proofSubmissionEpochs, targetCommitteeSize] =
397
+ await Promise.all([
398
+ this.getL1StartBlock(),
399
+ this.getL1GenesisTime(),
400
+ this.getSlotDuration(),
401
+ this.getEpochDuration(),
402
+ this.getProofSubmissionEpochs(),
403
+ this.getTargetCommitteeSize(),
404
+ ]);
402
405
  return {
403
406
  l1StartBlock,
404
407
  l1GenesisTime,
405
408
  slotDuration,
406
409
  epochDuration: Number(epochDuration),
407
410
  proofSubmissionEpochs: Number(proofSubmissionEpochs),
411
+ targetCommitteeSize,
408
412
  };
409
413
  }
410
414
 
@@ -31,9 +31,9 @@ const logger = createLogger('ethereum:deploy_aztec_l1_contracts');
31
31
  const JSON_DEPLOY_RESULT_PREFIX = 'JSON DEPLOY RESULT:';
32
32
 
33
33
  /**
34
- * Runs a process with the given command, arguments, and environment.
35
- * If the process outputs a line starting with JSON_DEPLOY_RESULT_PREFIX,
36
- * the JSON is parsed and returned.
34
+ * Runs a process and parses JSON deploy results from stdout.
35
+ * Lines starting with JSON_DEPLOY_RESULT_PREFIX are parsed and returned.
36
+ * All other stdout goes to logger.info, stderr goes to logger.warn.
37
37
  */
38
38
  function runProcess<T>(
39
39
  command: string,
@@ -49,26 +49,41 @@ function runProcess<T>(
49
49
  });
50
50
 
51
51
  let result: T | undefined;
52
+ let parseError: Error | undefined;
53
+ let settled = false;
52
54
 
53
55
  readline.createInterface({ input: proc.stdout }).on('line', line => {
54
56
  const trimmedLine = line.trim();
55
57
  if (trimmedLine.startsWith(JSON_DEPLOY_RESULT_PREFIX)) {
56
58
  const jsonStr = trimmedLine.slice(JSON_DEPLOY_RESULT_PREFIX.length).trim();
57
- // TODO(AD): should this be a zod parse?
58
- result = JSON.parse(jsonStr);
59
+ try {
60
+ result = JSON.parse(jsonStr);
61
+ } catch {
62
+ parseError = new Error(`Failed to parse deploy result JSON: ${jsonStr.slice(0, 200)}`);
63
+ }
59
64
  } else {
60
65
  logger.info(line);
61
66
  }
62
67
  });
63
- readline.createInterface({ input: proc.stderr }).on('line', logger.error.bind(logger));
68
+ readline.createInterface({ input: proc.stderr }).on('line', logger.warn.bind(logger));
64
69
 
65
70
  proc.on('error', error => {
71
+ if (settled) {
72
+ return;
73
+ }
74
+ settled = true;
66
75
  reject(new Error(`Failed to spawn ${command}: ${error.message}`));
67
76
  });
68
77
 
69
78
  proc.on('close', code => {
79
+ if (settled) {
80
+ return;
81
+ }
82
+ settled = true;
70
83
  if (code !== 0) {
71
- reject(new Error(`${command} exited with code ${code}. See logs for details.\n`));
84
+ reject(new Error(`${command} exited with code ${code}`));
85
+ } else if (parseError) {
86
+ reject(parseError);
72
87
  } else {
73
88
  resolve(result);
74
89
  }
@@ -321,11 +336,8 @@ export async function deployAztecL1Contracts(
321
336
  );
322
337
  }
323
338
 
324
- // From heuristic testing. More caused issues with anvil.
325
- const MAGIC_ANVIL_BATCH_SIZE = 8;
326
- // Anvil seems to stall with unbounded batch size. Otherwise no max batch size is desirable.
339
+ const scriptPath = join(getL1ContractsPath(), 'scripts', 'forge_broadcast.js');
327
340
  const forgeArgs = [
328
- 'script',
329
341
  FORGE_SCRIPT,
330
342
  '--sig',
331
343
  'run()',
@@ -333,9 +345,6 @@ export async function deployAztecL1Contracts(
333
345
  privateKey,
334
346
  '--rpc-url',
335
347
  rpcUrl,
336
- '--broadcast',
337
- '--batch-size',
338
- MAGIC_ANVIL_BATCH_SIZE.toString(),
339
348
  ...(shouldVerify ? ['--verify'] : []),
340
349
  ];
341
350
  const forgeEnv = {
@@ -344,7 +353,12 @@ export async function deployAztecL1Contracts(
344
353
  FOUNDRY_PROFILE: chainId === mainnet.id ? 'production' : undefined,
345
354
  ...getDeployAztecL1ContractsEnvVars(args),
346
355
  };
347
- const result = await runProcess<ForgeL1ContractsDeployResult>('forge', forgeArgs, forgeEnv, l1ContractsPath);
356
+ const result = await runProcess<ForgeL1ContractsDeployResult>(
357
+ process.execPath,
358
+ [scriptPath, ...forgeArgs],
359
+ forgeEnv,
360
+ l1ContractsPath,
361
+ );
348
362
  if (!result) {
349
363
  throw new Error('Forge script did not output deployment result');
350
364
  }
@@ -587,17 +601,8 @@ export const deployRollupForUpgrade = async (
587
601
  const FORGE_SCRIPT = 'script/deploy/DeployRollupForUpgrade.s.sol';
588
602
  await maybeForgeForceProductionBuild(l1ContractsPath, FORGE_SCRIPT, chainId);
589
603
 
590
- const forgeArgs = [
591
- 'script',
592
- FORGE_SCRIPT,
593
- '--sig',
594
- 'run()',
595
- '--private-key',
596
- privateKey,
597
- '--rpc-url',
598
- rpcUrl,
599
- '--broadcast',
600
- ];
604
+ const scriptPath = join(getL1ContractsPath(), 'scripts', 'forge_broadcast.js');
605
+ const forgeArgs = [FORGE_SCRIPT, '--sig', 'run()', '--private-key', privateKey, '--rpc-url', rpcUrl];
601
606
  const forgeEnv = {
602
607
  FOUNDRY_PROFILE: chainId === mainnet.id ? 'production' : undefined,
603
608
  // Env vars required by l1-contracts/script/deploy/RollupConfiguration.sol.
@@ -606,7 +611,12 @@ export const deployRollupForUpgrade = async (
606
611
  ...getDeployRollupForUpgradeEnvVars(args),
607
612
  };
608
613
 
609
- const result = await runProcess<ForgeRollupUpgradeResult>('forge', forgeArgs, forgeEnv, l1ContractsPath);
614
+ const result = await runProcess<ForgeRollupUpgradeResult>(
615
+ process.execPath,
616
+ [scriptPath, ...forgeArgs],
617
+ forgeEnv,
618
+ l1ContractsPath,
619
+ );
610
620
  if (!result) {
611
621
  throw new Error('Forge script did not output deployment result');
612
622
  }
@@ -134,7 +134,7 @@ export const P75AllTxsPriorityFeeStrategy: PriorityFeeStrategy = {
134
134
  // Sanity check: cap competitive fee at 100x network estimate to avoid using unrealistic fees
135
135
  const maxReasonableFee = networkEstimate * 100n;
136
136
  if (competitiveFee > maxReasonableFee && networkEstimate > 0n) {
137
- logger?.warn('Competitive fee exceeds sanity cap, using capped value', {
137
+ logger?.debug('Competitive fee exceeds sanity cap, using capped value', {
138
138
  competitiveFee: formatGwei(competitiveFee),
139
139
  networkEstimate: formatGwei(networkEstimate),
140
140
  cappedTo: formatGwei(maxReasonableFee),
@@ -207,7 +207,7 @@ export const P75BlobTxsOnlyPriorityFeeStrategy: PriorityFeeStrategy = {
207
207
 
208
208
  // Debug: Log suspicious fees from history
209
209
  if (medianHistoricalFee > 100n * WEI_CONST) {
210
- logger?.warn('Suspicious high fee in history', {
210
+ logger?.debug('Suspicious high fee in history', {
211
211
  historicalMedian: formatGwei(medianHistoricalFee),
212
212
  allP75Fees: percentile75Fees.map(f => formatGwei(f)),
213
213
  });