@aztec/ethereum 0.0.1-commit.6b90f3f5 → 0.0.1-commit.6c354eb4c

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.
Files changed (89) hide show
  1. package/dest/config.d.ts +1 -1
  2. package/dest/config.d.ts.map +1 -1
  3. package/dest/config.js +5 -3
  4. package/dest/contracts/empire_base.d.ts +3 -1
  5. package/dest/contracts/empire_base.d.ts.map +1 -1
  6. package/dest/contracts/empire_slashing_proposer.d.ts +3 -1
  7. package/dest/contracts/empire_slashing_proposer.d.ts.map +1 -1
  8. package/dest/contracts/empire_slashing_proposer.js +9 -0
  9. package/dest/contracts/fee_asset_price_oracle.d.ts +101 -0
  10. package/dest/contracts/fee_asset_price_oracle.d.ts.map +1 -0
  11. package/dest/contracts/fee_asset_price_oracle.js +651 -0
  12. package/dest/contracts/governance.js +3 -3
  13. package/dest/contracts/governance_proposer.d.ts +3 -1
  14. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  15. package/dest/contracts/governance_proposer.js +9 -0
  16. package/dest/contracts/index.d.ts +2 -1
  17. package/dest/contracts/index.d.ts.map +1 -1
  18. package/dest/contracts/index.js +1 -0
  19. package/dest/contracts/rollup.d.ts +6 -5
  20. package/dest/contracts/rollup.d.ts.map +1 -1
  21. package/dest/contracts/rollup.js +17 -5
  22. package/dest/deploy_aztec_l1_contracts.d.ts +2 -3
  23. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -1
  24. package/dest/deploy_aztec_l1_contracts.js +37 -22
  25. package/dest/deploy_l1_contract.js +3 -3
  26. package/dest/generated/l1-contracts-defaults.d.ts +1 -1
  27. package/dest/generated/l1-contracts-defaults.js +1 -1
  28. package/dest/l1_artifacts.d.ts +1051 -42
  29. package/dest/l1_artifacts.d.ts.map +1 -1
  30. package/dest/l1_tx_utils/config.d.ts +7 -1
  31. package/dest/l1_tx_utils/config.d.ts.map +1 -1
  32. package/dest/l1_tx_utils/config.js +14 -1
  33. package/dest/l1_tx_utils/factory.d.ts +18 -10
  34. package/dest/l1_tx_utils/factory.d.ts.map +1 -1
  35. package/dest/l1_tx_utils/factory.js +17 -7
  36. package/dest/l1_tx_utils/fee-strategies/p75_competitive.js +1 -1
  37. package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.js +1 -1
  38. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts +15 -15
  39. package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts.map +1 -1
  40. package/dest/l1_tx_utils/forwarder_l1_tx_utils.js +9 -15
  41. package/dest/l1_tx_utils/index-blobs.d.ts +3 -3
  42. package/dest/l1_tx_utils/index-blobs.d.ts.map +1 -1
  43. package/dest/l1_tx_utils/index-blobs.js +2 -2
  44. package/dest/l1_tx_utils/index.d.ts +2 -1
  45. package/dest/l1_tx_utils/index.d.ts.map +1 -1
  46. package/dest/l1_tx_utils/index.js +1 -0
  47. package/dest/l1_tx_utils/l1_tx_utils.d.ts +16 -7
  48. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -1
  49. package/dest/l1_tx_utils/l1_tx_utils.js +41 -36
  50. package/dest/l1_tx_utils/tx_delayer.d.ts +56 -0
  51. package/dest/l1_tx_utils/tx_delayer.d.ts.map +1 -0
  52. package/dest/{test → l1_tx_utils}/tx_delayer.js +62 -34
  53. package/dest/test/index.d.ts +1 -3
  54. package/dest/test/index.d.ts.map +1 -1
  55. package/dest/test/index.js +0 -2
  56. package/dest/test/upgrade_utils.js +2 -2
  57. package/package.json +5 -5
  58. package/src/config.ts +3 -2
  59. package/src/contracts/empire_base.ts +2 -0
  60. package/src/contracts/empire_slashing_proposer.ts +6 -0
  61. package/src/contracts/fee_asset_price_oracle.ts +280 -0
  62. package/src/contracts/governance.ts +3 -3
  63. package/src/contracts/governance_proposer.ts +6 -0
  64. package/src/contracts/index.ts +1 -0
  65. package/src/contracts/rollup.ts +31 -13
  66. package/src/deploy_aztec_l1_contracts.ts +60 -29
  67. package/src/deploy_l1_contract.ts +3 -3
  68. package/src/generated/l1-contracts-defaults.ts +1 -1
  69. package/src/l1_tx_utils/config.ts +20 -0
  70. package/src/l1_tx_utils/factory.ts +31 -31
  71. package/src/l1_tx_utils/fee-strategies/p75_competitive.ts +1 -1
  72. package/src/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.ts +1 -1
  73. package/src/l1_tx_utils/forwarder_l1_tx_utils.ts +43 -54
  74. package/src/l1_tx_utils/index-blobs.ts +2 -2
  75. package/src/l1_tx_utils/index.ts +1 -0
  76. package/src/l1_tx_utils/l1_tx_utils.ts +41 -26
  77. package/src/{test → l1_tx_utils}/tx_delayer.ts +78 -50
  78. package/src/test/index.ts +0 -2
  79. package/src/test/upgrade_utils.ts +2 -2
  80. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts +0 -26
  81. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.d.ts.map +0 -1
  82. package/dest/l1_tx_utils/l1_tx_utils_with_blobs.js +0 -26
  83. package/dest/test/delayed_tx_utils.d.ts +0 -13
  84. package/dest/test/delayed_tx_utils.d.ts.map +0 -1
  85. package/dest/test/delayed_tx_utils.js +0 -28
  86. package/dest/test/tx_delayer.d.ts +0 -36
  87. package/dest/test/tx_delayer.d.ts.map +0 -1
  88. package/src/l1_tx_utils/l1_tx_utils_with_blobs.ts +0 -77
  89. package/src/test/delayed_tx_utils.ts +0 -52
@@ -2,8 +2,7 @@ import { omit } from '@aztec/foundation/collection';
2
2
  import { createLogger } from '@aztec/foundation/log';
3
3
  import { retryUntil } from '@aztec/foundation/retry';
4
4
  import { inspect } from 'util';
5
- import { keccak256, parseTransaction, publicActions, serializeTransaction, walletActions } from 'viem';
6
- import { isExtendedClient } from '../types.js';
5
+ import { keccak256, parseTransaction, publicActions, recoverTransactionAddress, serializeTransaction, walletActions } from 'viem';
7
6
  const MAX_WAIT_TIME_SECONDS = 180;
8
7
  export function waitUntilBlock(client, blockNumber, logger, timeout) {
9
8
  const publicClient = 'getBlockNumber' in client && typeof client.getBlockNumber === 'function' ? client : client.extend(publicActions);
@@ -35,59 +34,78 @@ export function waitUntilL1Timestamp(client, timestamp, logger, timeout) {
35
34
  return currentTs >= BigInt(timestamp);
36
35
  }, `Wait until L1 timestamp ${timestamp}`, timeout ?? MAX_WAIT_TIME_SECONDS, 0.1);
37
36
  }
38
- class DelayerImpl {
37
+ /** Manages tx delaying for testing, intercepting sendRawTransaction calls to delay or cancel them. */ export class Delayer {
39
38
  dateProvider;
40
39
  logger;
41
- constructor(dateProvider, opts){
40
+ maxInclusionTimeIntoSlot;
41
+ ethereumSlotDuration;
42
+ nextWait;
43
+ sentTxHashes;
44
+ cancelledTxs;
45
+ constructor(dateProvider, opts, bindings){
42
46
  this.dateProvider = dateProvider;
43
- this.logger = createLogger('ethereum:tx_delayer');
44
47
  this.maxInclusionTimeIntoSlot = undefined;
45
48
  this.nextWait = undefined;
46
49
  this.sentTxHashes = [];
47
50
  this.cancelledTxs = [];
48
51
  this.ethereumSlotDuration = BigInt(opts.ethereumSlotDuration);
52
+ this.logger = createLogger('ethereum:tx_delayer', bindings);
49
53
  }
50
- maxInclusionTimeIntoSlot;
51
- ethereumSlotDuration;
52
- nextWait;
53
- sentTxHashes;
54
- cancelledTxs;
55
- getSentTxHashes() {
54
+ /** Returns the logger instance used by this delayer. */ getLogger() {
55
+ return this.logger;
56
+ }
57
+ /** Returns the hashes of all effectively sent txs. */ getSentTxHashes() {
56
58
  return this.sentTxHashes;
57
59
  }
58
- getCancelledTxs() {
60
+ /** Returns the raw hex for all cancelled txs. */ getCancelledTxs() {
59
61
  return this.cancelledTxs;
60
62
  }
61
- pauseNextTxUntilBlock(l1BlockNumber) {
63
+ /** Delays the next tx to be sent so it lands on the given L1 block number. */ pauseNextTxUntilBlock(l1BlockNumber) {
62
64
  this.nextWait = {
63
65
  l1BlockNumber: BigInt(l1BlockNumber)
64
66
  };
65
67
  }
66
- pauseNextTxUntilTimestamp(l1Timestamp) {
68
+ /** Delays the next tx to be sent so it lands on the given timestamp. */ pauseNextTxUntilTimestamp(l1Timestamp) {
67
69
  this.nextWait = {
68
70
  l1Timestamp: BigInt(l1Timestamp)
69
71
  };
70
72
  }
71
- cancelNextTx() {
73
+ /** Delays the next tx to be sent indefinitely. */ cancelNextTx() {
72
74
  this.nextWait = {
73
75
  indefinitely: true
74
76
  };
75
77
  }
76
- setMaxInclusionTimeIntoSlot(seconds) {
78
+ /**
79
+ * Sets max inclusion time into slot. If more than this many seconds have passed
80
+ * since the last L1 block was mined, then any tx will not be mined in the current
81
+ * L1 slot but will be deferred for the next one.
82
+ */ setMaxInclusionTimeIntoSlot(seconds) {
77
83
  this.maxInclusionTimeIntoSlot = seconds;
78
84
  }
79
85
  }
80
86
  /**
81
- * Returns a new client (without modifying the one passed in) with an injected tx delayer.
82
- * The delayer can be used to hold off the next tx to be sent until a given block number.
83
- * TODO(#10824): This doesn't play along well with blob txs for some reason.
84
- */ export function withDelayer(client, dateProvider, opts) {
85
- if (!isExtendedClient(client)) {
86
- throw new Error('withDelayer has to be instantiated with a wallet viem client.');
87
+ * Creates a new Delayer instance. Exposed so callers can create a single shared delayer
88
+ * and pass it to multiple `wrapClientWithDelayer` calls.
89
+ */ export function createDelayer(dateProvider, opts, bindings) {
90
+ return new Delayer(dateProvider, opts, bindings);
91
+ }
92
+ /** Tries to recover the sender address from a serialized signed transaction. */ async function tryRecoverSender(serializedTransaction) {
93
+ try {
94
+ return await recoverTransactionAddress({
95
+ serializedTransaction: serializedTransaction
96
+ });
97
+ } catch {
98
+ return undefined;
87
99
  }
88
- const logger = createLogger('ethereum:tx_delayer');
89
- const delayer = new DelayerImpl(dateProvider, opts);
90
- const extended = client// Tweak sendRawTransaction so it uses the delay defined in the delayer.
100
+ }
101
+ /**
102
+ * Wraps a viem client with tx delaying logic. Returns the wrapped client.
103
+ * The delayer intercepts sendRawTransaction calls and delays them based on the delayer's state.
104
+ */ export function wrapClientWithDelayer(client, delayer) {
105
+ const logger = delayer.getLogger();
106
+ // Cast to ExtendedViemWalletClient for the extend chain since it has sendRawTransaction.
107
+ // The sendRawTransaction override is applied to all clients regardless of type.
108
+ const withRawTx = client// Tweak sendRawTransaction so it uses the delay defined in the delayer.
91
109
  // Note that this will only work with local accounts (ie accounts for which we have the private key).
92
110
  // Transactions signed by the node will not be delayed since they use sendTransaction directly,
93
111
  // but we do not use them in our codebase at all.
@@ -97,6 +115,7 @@ class DelayerImpl {
97
115
  let txHash;
98
116
  const { serializedTransaction } = args[0];
99
117
  const publicClient = client;
118
+ const sender = await tryRecoverSender(serializedTransaction);
100
119
  if (delayer.nextWait !== undefined) {
101
120
  // Check if we have been instructed to delay the next tx.
102
121
  const waitUntil = delayer.nextWait;
@@ -105,13 +124,16 @@ class DelayerImpl {
105
124
  txHash = computeTxHash(serializedTransaction);
106
125
  // Cancel tx outright if instructed
107
126
  if ('indefinitely' in waitUntil && waitUntil.indefinitely) {
108
- logger.info(`Cancelling tx ${txHash}`);
127
+ logger.info(`Cancelling tx ${txHash}`, {
128
+ sender
129
+ });
109
130
  delayer.cancelledTxs.push(serializedTransaction);
110
131
  return Promise.resolve(txHash);
111
132
  }
112
133
  // Or wait until the desired block number or timestamp
113
134
  wait = 'l1BlockNumber' in waitUntil ? waitUntilBlock(publicClient, waitUntil.l1BlockNumber - 1n, logger) : 'l1Timestamp' in waitUntil ? waitUntilL1Timestamp(publicClient, waitUntil.l1Timestamp - delayer.ethereumSlotDuration, logger) : undefined;
114
135
  logger.info(`Delaying tx ${txHash} until ${inspect(waitUntil)}`, {
136
+ sender,
115
137
  argsLen: args.length,
116
138
  ...omit(parseTransaction(serializedTransaction), 'data', 'sidecars')
117
139
  });
@@ -124,6 +146,7 @@ class DelayerImpl {
124
146
  const now = delayer.dateProvider.now();
125
147
  txHash = computeTxHash(serializedTransaction);
126
148
  const logData = {
149
+ sender,
127
150
  ...omit(parseTransaction(serializedTransaction), 'data', 'sidecars'),
128
151
  lastBlockTimestamp,
129
152
  now,
@@ -150,29 +173,34 @@ class DelayerImpl {
150
173
  computedTxHash: txHash
151
174
  });
152
175
  }
153
- logger.info(`Sent previously delayed tx ${clientTxHash}`);
176
+ logger.info(`Sent previously delayed tx ${clientTxHash}`, {
177
+ sender
178
+ });
154
179
  delayer.sentTxHashes.push(clientTxHash);
155
180
  }).catch((err)=>logger.error(`Error sending tx after delay`, err));
156
181
  return Promise.resolve(txHash);
157
182
  } else {
158
183
  const txHash = await client.sendRawTransaction(...args);
159
- logger.debug(`Sent tx immediately ${txHash}`);
184
+ logger.debug(`Sent tx immediately ${txHash}`, {
185
+ sender
186
+ });
160
187
  delayer.sentTxHashes.push(txHash);
161
188
  return txHash;
162
189
  }
163
190
  }
164
- }))// Re-extend with sendTransaction so it uses the modified sendRawTransaction.
191
+ }));
192
+ // Only re-bind wallet actions (sendTransaction, writeContract, deployContract) for wallet clients.
193
+ // This is needed for tests that use wallet actions directly rather than sendRawTransaction.
194
+ const isWalletClient = 'account' in client && client.account !== undefined;
195
+ const extended = isWalletClient ? withRawTx// Re-extend with sendTransaction so it uses the modified sendRawTransaction.
165
196
  .extend((client)=>({
166
197
  sendTransaction: walletActions(client).sendTransaction
167
198
  }))// And with the actions that depend on the modified sendTransaction
168
199
  .extend((client)=>({
169
200
  writeContract: walletActions(client).writeContract,
170
201
  deployContract: walletActions(client).deployContract
171
- }));
172
- return {
173
- client: extended,
174
- delayer
175
- };
202
+ })) : withRawTx;
203
+ return extended;
176
204
  }
177
205
  /**
178
206
  * Compute the tx hash given the serialized tx. Note that if this is a blob tx, we need to
@@ -1,9 +1,7 @@
1
- export * from './delayed_tx_utils.js';
2
1
  export * from './eth_cheat_codes.js';
3
2
  export * from './eth_cheat_codes_with_state.js';
4
3
  export * from './start_anvil.js';
5
- export * from './tx_delayer.js';
6
4
  export * from './upgrade_utils.js';
7
5
  export * from './chain_monitor.js';
8
6
  export * from './rollup_cheat_codes.js';
9
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy90ZXN0L2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLGNBQWMsdUJBQXVCLENBQUM7QUFDdEMsY0FBYyxzQkFBc0IsQ0FBQztBQUNyQyxjQUFjLGlDQUFpQyxDQUFDO0FBQ2hELGNBQWMsa0JBQWtCLENBQUM7QUFDakMsY0FBYyxpQkFBaUIsQ0FBQztBQUNoQyxjQUFjLG9CQUFvQixDQUFDO0FBQ25DLGNBQWMsb0JBQW9CLENBQUM7QUFDbkMsY0FBYyx5QkFBeUIsQ0FBQyJ9
7
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy90ZXN0L2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLGNBQWMsc0JBQXNCLENBQUM7QUFDckMsY0FBYyxpQ0FBaUMsQ0FBQztBQUNoRCxjQUFjLGtCQUFrQixDQUFDO0FBQ2pDLGNBQWMsb0JBQW9CLENBQUM7QUFDbkMsY0FBYyxvQkFBb0IsQ0FBQztBQUNuQyxjQUFjLHlCQUF5QixDQUFDIn0=
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/test/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,iCAAiC,CAAC;AAChD,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,yBAAyB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/test/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,iCAAiC,CAAC;AAChD,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,yBAAyB,CAAC"}
@@ -1,8 +1,6 @@
1
- export * from './delayed_tx_utils.js';
2
1
  export * from './eth_cheat_codes.js';
3
2
  export * from './eth_cheat_codes_with_state.js';
4
3
  export * from './start_anvil.js';
5
- export * from './tx_delayer.js';
6
4
  export * from './upgrade_utils.js';
7
5
  export * from './chain_monitor.js';
8
6
  export * from './rollup_cheat_codes.js';
@@ -3,13 +3,13 @@ import { GovernanceAbi } from '@aztec/l1-artifacts/GovernanceAbi';
3
3
  import { TestERC20Abi as StakingAssetAbi } from '@aztec/l1-artifacts/TestERC20Abi';
4
4
  import { getContract } from 'viem';
5
5
  import { extractProposalIdFromLogs } from '../contracts/governance.js';
6
- import { createL1TxUtilsFromViemWallet } from '../l1_tx_utils/index.js';
6
+ import { createL1TxUtils } from '../l1_tx_utils/index.js';
7
7
  import { EthCheatCodes } from './eth_cheat_codes.js';
8
8
  export async function executeGovernanceProposal(proposalId, governance, voteAmount, privateKey, l1Client, rpcUrls, logger) {
9
9
  const proposal = await governance.read.getProposal([
10
10
  proposalId
11
11
  ]);
12
- const l1TxUtils = createL1TxUtilsFromViemWallet(l1Client);
12
+ const l1TxUtils = createL1TxUtils(l1Client);
13
13
  const waitL1Block = async ()=>{
14
14
  await l1TxUtils.sendAndMonitorTransaction({
15
15
  to: l1Client.account.address,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/ethereum",
3
- "version": "0.0.1-commit.6b90f3f5",
3
+ "version": "0.0.1-commit.6c354eb4c",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  "./account": "./dest/account.js",
@@ -50,10 +50,10 @@
50
50
  "../package.common.json"
51
51
  ],
52
52
  "dependencies": {
53
- "@aztec/blob-lib": "0.0.1-commit.6b90f3f5",
54
- "@aztec/constants": "0.0.1-commit.6b90f3f5",
55
- "@aztec/foundation": "0.0.1-commit.6b90f3f5",
56
- "@aztec/l1-artifacts": "0.0.1-commit.6b90f3f5",
53
+ "@aztec/blob-lib": "0.0.1-commit.6c354eb4c",
54
+ "@aztec/constants": "0.0.1-commit.6c354eb4c",
55
+ "@aztec/foundation": "0.0.1-commit.6c354eb4c",
56
+ "@aztec/l1-artifacts": "0.0.1-commit.6c354eb4c",
57
57
  "@viem/anvil": "^0.0.10",
58
58
  "dotenv": "^16.0.3",
59
59
  "lodash.chunk": "^4.2.0",
package/src/config.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  getConfigFromMappings,
7
7
  getDefaultConfig,
8
8
  numberConfigHelper,
9
+ omitConfigMappings,
9
10
  optionalNumberConfigHelper,
10
11
  } from '@aztec/foundation/config';
11
12
  import { EthAddress } from '@aztec/foundation/eth-address';
@@ -99,7 +100,7 @@ export const l1ContractsConfigMappings: ConfigMappingsType<L1ContractsConfig> =
99
100
  },
100
101
  aztecEpochDuration: {
101
102
  env: 'AZTEC_EPOCH_DURATION',
102
- description: `How many L2 slots an epoch lasts (maximum AZTEC_MAX_EPOCH_DURATION).`,
103
+ description: `How many L2 slots an epoch lasts (maximum MAX_CHECKPOINTS_PER_EPOCH).`,
103
104
  ...numberConfigHelper(l1ContractsDefaultEnv.AZTEC_EPOCH_DURATION),
104
105
  },
105
106
  aztecTargetCommitteeSize: {
@@ -238,7 +239,7 @@ export const l1ContractsConfigMappings: ConfigMappingsType<L1ContractsConfig> =
238
239
  description: 'The delay before a validator can exit the set',
239
240
  ...numberConfigHelper(l1ContractsDefaultEnv.AZTEC_EXIT_DELAY_SECONDS),
240
241
  },
241
- ...l1TxUtilsConfigMappings,
242
+ ...omitConfigMappings(l1TxUtilsConfigMappings, ['ethereumSlotDuration']),
242
243
  };
243
244
 
244
245
  /**
@@ -22,6 +22,8 @@ export interface IEmpireBase {
22
22
  signerAddress: Hex,
23
23
  signer: (msg: TypedDataDefinition) => Promise<Hex>,
24
24
  ): Promise<L1TxRequest>;
25
+ /** Checks if a payload was ever submitted to governance via submitRoundWinner. */
26
+ hasPayloadBeenProposed(payload: Hex, fromBlock: bigint): Promise<boolean>;
25
27
  }
26
28
 
27
29
  export function encodeSignal(payload: Hex): Hex {
@@ -126,6 +126,12 @@ export class EmpireSlashingProposerContract extends EventEmitter implements IEmp
126
126
  };
127
127
  }
128
128
 
129
+ /** Checks if a payload was ever submitted to governance via submitRoundWinner. */
130
+ public async hasPayloadBeenProposed(payload: Hex, fromBlock: bigint): Promise<boolean> {
131
+ const events = await this.proposer.getEvents.PayloadSubmitted({ payload }, { fromBlock, strict: true });
132
+ return events.length > 0;
133
+ }
134
+
129
135
  public listenToSubmittablePayloads(callback: (args: { payload: `0x${string}`; round: bigint }) => unknown) {
130
136
  return this.proposer.watchEvent.PayloadSubmittable(
131
137
  {},
@@ -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
+ }
@@ -14,7 +14,7 @@ import {
14
14
  } from 'viem';
15
15
 
16
16
  import type { L1ContractAddresses } from '../l1_contract_addresses.js';
17
- import { createL1TxUtilsFromViemWallet } from '../l1_tx_utils/index.js';
17
+ import { createL1TxUtils } from '../l1_tx_utils/index.js';
18
18
  import { type ExtendedViemWalletClient, type ViemClient, isExtendedClient } from '../types.js';
19
19
 
20
20
  export type L1GovernanceContractAddresses = Pick<
@@ -194,7 +194,7 @@ export class GovernanceContract extends ReadOnlyGovernanceContract {
194
194
  retries: number;
195
195
  logger: Logger;
196
196
  }) {
197
- const l1TxUtils = createL1TxUtilsFromViemWallet(this.client, { logger });
197
+ const l1TxUtils = createL1TxUtils(this.client, { logger });
198
198
  const retryDelaySeconds = 12;
199
199
 
200
200
  voteAmount = voteAmount ?? (await this.getPowerForProposal(proposalId));
@@ -252,7 +252,7 @@ export class GovernanceContract extends ReadOnlyGovernanceContract {
252
252
  retries: number;
253
253
  logger: Logger;
254
254
  }) {
255
- const l1TxUtils = createL1TxUtilsFromViemWallet(this.client, { logger });
255
+ const l1TxUtils = createL1TxUtils(this.client, { logger });
256
256
  const retryDelaySeconds = 12;
257
257
  let success = false;
258
258
  for (let i = 0; i < retries; i++) {
@@ -110,6 +110,12 @@ export class GovernanceProposerContract implements IEmpireBase {
110
110
  };
111
111
  }
112
112
 
113
+ /** Checks if a payload was ever submitted to governance via submitRoundWinner. */
114
+ public async hasPayloadBeenProposed(payload: Hex, fromBlock: bigint): Promise<boolean> {
115
+ const events = await this.proposer.getEvents.PayloadSubmitted({ payload }, { fromBlock, strict: true });
116
+ return events.length > 0;
117
+ }
118
+
113
119
  public async submitRoundWinner(
114
120
  round: bigint,
115
121
  l1TxUtils: L1TxUtils,
@@ -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';