@aztec/bot 0.0.1-commit.4d79d1f2d → 0.0.1-commit.5358163d3

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,209 @@
1
+ /**
2
+ * CrossChainBot exercises L2->L1 and L1->L2 messaging.
3
+ *
4
+ * createAndSendTx onTxMined
5
+ * ────────────────────────────────────── ──────────────────────────────
6
+ *
7
+ * 1. SEED (fire-and-forget) 3. VERIFY L2->L1
8
+ * if store has fewer pending messages Query getTxEffect, confirm
9
+ * than seedCount and no seed is the expected L2->L1 messages
10
+ * in-flight: appeared in tx effects.
11
+ * * kick off L1 inbox tx
12
+ * * store msg on completion
13
+ *
14
+ * 2. BUILD & SEND BATCH
15
+ * Always:
16
+ * N x create_l2_to_l1_message
17
+ * (random content, fixed
18
+ * L1 recipient)
19
+ * If a ready L1->L2 msg exists:
20
+ * 1 x consume_message_from_
21
+ * arbitrary_sender_public
22
+ * delete consumed msg from store
23
+ * Send batch tx (no wait)
24
+ *
25
+ */
26
+ import { AztecAddress } from '@aztec/aztec.js/addresses';
27
+ import { BatchCall, NO_WAIT } from '@aztec/aztec.js/contracts';
28
+ import { isL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
29
+ import { TxHash, TxReceipt } from '@aztec/aztec.js/tx';
30
+ import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
31
+ import { Fr } from '@aztec/foundation/curves/bn254';
32
+ import { EthAddress } from '@aztec/foundation/eth-address';
33
+ import type { TestContract } from '@aztec/noir-test-contracts.js/Test';
34
+ import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
35
+ import type { EmbeddedWallet } from '@aztec/wallets/embedded';
36
+
37
+ import { BaseBot } from './base_bot.js';
38
+ import type { BotConfig } from './config.js';
39
+ import { BotFactory } from './factory.js';
40
+ import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
41
+ import type { BotStore, PendingL1ToL2Message } from './store/index.js';
42
+
43
+ /** Stale message threshold: messages older than this are removed. */
44
+ const STALE_MESSAGE_THRESHOLD_MS = 2 * 60 * 60 * 1000; // 2 hours
45
+
46
+ /** Bot that exercises both L2→L1 and L1→L2 cross-chain messaging. */
47
+ export class CrossChainBot extends BaseBot {
48
+ private l2ToL1Sent = 0;
49
+ private l1ToL2Consumed = 0;
50
+ private pendingSeedPromise: Promise<void> | undefined;
51
+
52
+ protected constructor(
53
+ node: AztecNode,
54
+ wallet: EmbeddedWallet,
55
+ defaultAccountAddress: AztecAddress,
56
+ private readonly contract: TestContract,
57
+ private readonly l1Client: ExtendedViemWalletClient,
58
+ private readonly l1Recipient: EthAddress,
59
+ private readonly inboxAddress: EthAddress,
60
+ private readonly rollupVersion: bigint,
61
+ private readonly store: BotStore,
62
+ config: BotConfig,
63
+ ) {
64
+ super(node, wallet, defaultAccountAddress, config);
65
+ }
66
+
67
+ static async create(
68
+ config: BotConfig,
69
+ wallet: EmbeddedWallet,
70
+ aztecNode: AztecNode,
71
+ aztecNodeAdmin: AztecNodeAdmin | undefined,
72
+ store: BotStore,
73
+ ): Promise<CrossChainBot> {
74
+ if (config.followChain === 'NONE') {
75
+ throw new Error(`CrossChainBot requires followChain to be set (got NONE)`);
76
+ }
77
+ const factory = new BotFactory(config, wallet, store, aztecNode, aztecNodeAdmin);
78
+ const { defaultAccountAddress, contract, l1Client, rollupVersion } = await factory.setupCrossChain();
79
+ const l1Recipient = EthAddress.fromString(l1Client.account!.address);
80
+ const { l1ContractAddresses } = await aztecNode.getNodeInfo();
81
+ const inboxAddress = EthAddress.fromString(l1ContractAddresses.inboxAddress.toString());
82
+ return new CrossChainBot(
83
+ aztecNode,
84
+ wallet,
85
+ defaultAccountAddress,
86
+ contract,
87
+ l1Client,
88
+ l1Recipient,
89
+ inboxAddress,
90
+ rollupVersion,
91
+ store,
92
+ config,
93
+ );
94
+ }
95
+
96
+ protected async createAndSendTx(logCtx: object): Promise<TxHash> {
97
+ const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
98
+
99
+ // Send an L1→L2 message if we're below the threshold and not already seeding one
100
+ if (pendingMessages.length < this.config.l1ToL2SeedCount && !this.pendingSeedPromise) {
101
+ this.pendingSeedPromise = this.seedNewL1ToL2Message()
102
+ .catch(err => this.log.warn(`Failed to seed L1→L2 message: ${err}`, logCtx))
103
+ .finally(() => {
104
+ this.pendingSeedPromise = undefined;
105
+ });
106
+ }
107
+
108
+ // Build batch: always L2→L1, optionally consume L1→L2
109
+ const calls = [];
110
+
111
+ // L2→L1: create messages with random content
112
+ for (let i = 0; i < this.config.l2ToL1MessagesPerTx; i++) {
113
+ calls.push(
114
+ this.contract.methods.create_l2_to_l1_message_arbitrary_recipient_public(Fr.random(), this.l1Recipient),
115
+ );
116
+ }
117
+
118
+ // L1→L2: consume oldest ready message if available
119
+ const readyMsg = await this.getReadyL1ToL2Message(pendingMessages);
120
+ if (readyMsg) {
121
+ calls.push(
122
+ this.contract.methods.consume_message_from_arbitrary_sender_public(
123
+ Fr.fromHexString(readyMsg.content),
124
+ Fr.fromHexString(readyMsg.secret),
125
+ EthAddress.fromString(readyMsg.sender),
126
+ new Fr(BigInt(readyMsg.globalLeafIndex)),
127
+ ),
128
+ );
129
+ // Delete consumed message immediately so it works with FOLLOW_CHAIN=NONE
130
+ await this.store.deleteL1ToL2Message(readyMsg.msgHash);
131
+ this.l1ToL2Consumed++;
132
+ } else {
133
+ this.log.warn(`No ready L1→L2 message to consume`, {
134
+ ...logCtx,
135
+ pendingCount: pendingMessages.length,
136
+ });
137
+ }
138
+
139
+ const batch = new BatchCall(this.wallet, calls);
140
+ const opts = await this.getSendMethodOpts(batch);
141
+
142
+ this.log.verbose(`Sending cross-chain batch with ${calls.length} calls`, logCtx);
143
+ return batch.send({ ...opts, wait: NO_WAIT });
144
+ }
145
+
146
+ protected override async onTxMined(receipt: TxReceipt, logCtx: object): Promise<void> {
147
+ // Verify L2→L1 messages appeared in this tx's effects
148
+ const indexed = await this.node.getTxEffect(receipt.txHash);
149
+ if (indexed) {
150
+ const l2ToL1Msgs = indexed.data.l2ToL1Msgs.filter(m => !m.isZero());
151
+ if (l2ToL1Msgs.length >= this.config.l2ToL1MessagesPerTx) {
152
+ this.l2ToL1Sent += l2ToL1Msgs.length;
153
+ } else {
154
+ this.log.error(`Expected ${this.config.l2ToL1MessagesPerTx} L2→L1 messages but found ${l2ToL1Msgs.length}`, {
155
+ ...logCtx,
156
+ blockNumber: receipt.blockNumber,
157
+ txHash: receipt.txHash.toString(),
158
+ });
159
+ }
160
+ }
161
+
162
+ const pendingCount = (await this.store.getUnconsumedL1ToL2Messages()).length;
163
+ this.log.info(`CrossChainBot txs mined`, {
164
+ ...logCtx,
165
+ l2ToL1Sent: this.l2ToL1Sent,
166
+ l1ToL2Consumed: this.l1ToL2Consumed,
167
+ l1ToL2Pending: pendingCount,
168
+ });
169
+ }
170
+
171
+ /** Finds the oldest pending message that is ready for consumption. */
172
+ private async getReadyL1ToL2Message(
173
+ pendingMessages: PendingL1ToL2Message[],
174
+ ): Promise<PendingL1ToL2Message | undefined> {
175
+ const now = Date.now();
176
+ for (const msg of pendingMessages) {
177
+ const ready = await isL1ToL2MessageReady(this.node, Fr.fromHexString(msg.msgHash), {
178
+ // Use forPublicConsumption: false so we wait until blockNumber >= messageBlockNumber.
179
+ // With forPublicConsumption: true, the check returns true one block early (the sequencer
180
+ // includes L1→L2 messages before executing the block's txs), but gas estimation simulates
181
+ // against the current world state which doesn't yet have the message.
182
+ // See https://linear.app/aztec-labs/issue/A-548 for details.
183
+ forPublicConsumption: false,
184
+ });
185
+ if (ready) {
186
+ return msg;
187
+ }
188
+
189
+ // Time-based stale detection: if the message is old and still not ready, remove it
190
+ if (now - msg.timestamp > STALE_MESSAGE_THRESHOLD_MS) {
191
+ await this.store.deleteL1ToL2Message(msg.msgHash);
192
+ this.log.warn(`Removed stale L1→L2 message ${msg.msgHash}`);
193
+ }
194
+ }
195
+ return undefined;
196
+ }
197
+
198
+ /** Seeds a new L1→L2 message on L1 and stores it. */
199
+ private async seedNewL1ToL2Message(): Promise<void> {
200
+ await seedL1ToL2Message(
201
+ this.l1Client,
202
+ this.inboxAddress,
203
+ this.contract.address,
204
+ this.rollupVersion,
205
+ this.store,
206
+ this.log,
207
+ );
208
+ }
209
+ }
package/src/factory.ts CHANGED
@@ -8,8 +8,8 @@ import {
8
8
  type DeployOptions,
9
9
  NO_WAIT,
10
10
  } from '@aztec/aztec.js/contracts';
11
- import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
12
11
  import type { L2AmountClaim } from '@aztec/aztec.js/ethereum';
12
+ import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
13
13
  import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
14
14
  import { deriveKeys } from '@aztec/aztec.js/keys';
15
15
  import { createLogger } from '@aztec/aztec.js/log';
@@ -17,11 +17,15 @@ import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
17
17
  import { waitForTx } from '@aztec/aztec.js/node';
18
18
  import { createEthereumChain } from '@aztec/ethereum/chain';
19
19
  import { createExtendedL1Client } from '@aztec/ethereum/client';
20
+ import { RollupContract } from '@aztec/ethereum/contracts';
21
+ import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
20
22
  import { Fr } from '@aztec/foundation/curves/bn254';
23
+ import { EthAddress } from '@aztec/foundation/eth-address';
21
24
  import { Timer } from '@aztec/foundation/timer';
22
25
  import { AMMContract } from '@aztec/noir-contracts.js/AMM';
23
26
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
24
27
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
28
+ import { TestContract } from '@aztec/noir-test-contracts.js/Test';
25
29
  import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
26
30
  import { GasSettings } from '@aztec/stdlib/gas';
27
31
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
@@ -29,6 +33,7 @@ import { deriveSigningKey } from '@aztec/stdlib/keys';
29
33
  import { EmbeddedWallet } from '@aztec/wallets/embedded';
30
34
 
31
35
  import { type BotConfig, SupportedTokenContracts } from './config.js';
36
+ import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
32
37
  import type { BotStore } from './store/index.js';
33
38
  import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
34
39
 
@@ -44,7 +49,11 @@ export class BotFactory {
44
49
  private readonly store: BotStore,
45
50
  private readonly aztecNode: AztecNode,
46
51
  private readonly aztecNodeAdmin?: AztecNodeAdmin,
47
- ) {}
52
+ ) {
53
+ // Set fee padding on the wallet so that all transactions during setup
54
+ // (token deploy, minting, etc.) use the configured padding, not the default.
55
+ this.wallet.setMinFeePadding(config.minFeePadding);
56
+ }
48
57
 
49
58
  /**
50
59
  * Initializes a new bot by setting up the sender account, registering the recipient,
@@ -95,6 +104,94 @@ export class BotFactory {
95
104
  return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
96
105
  }
97
106
 
107
+ /**
108
+ * Initializes the cross-chain bot by deploying TestContract, creating an L1 client,
109
+ * seeding initial L1→L2 messages, and waiting for the first to be ready.
110
+ */
111
+ public async setupCrossChain(): Promise<{
112
+ wallet: EmbeddedWallet;
113
+ defaultAccountAddress: AztecAddress;
114
+ contract: TestContract;
115
+ node: AztecNode;
116
+ l1Client: ExtendedViemWalletClient;
117
+ rollupVersion: bigint;
118
+ }> {
119
+ const defaultAccountAddress = await this.setupAccount();
120
+
121
+ // Create L1 client (same pattern as bridgeL1FeeJuice)
122
+ const l1RpcUrls = this.config.l1RpcUrls;
123
+ if (!l1RpcUrls?.length) {
124
+ throw new Error('L1 RPC URLs required for cross-chain bot');
125
+ }
126
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
127
+ if (!mnemonicOrPrivateKey) {
128
+ throw new Error('L1 mnemonic or private key required for cross-chain bot');
129
+ }
130
+ const { l1ChainId, l1ContractAddresses } = await this.aztecNode.getNodeInfo();
131
+ const chain = createEthereumChain(l1RpcUrls, l1ChainId);
132
+ const l1Client = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
133
+
134
+ // Fetch Rollup version (needed for Inbox L2Actor struct)
135
+ const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
136
+ const rollupVersion = await rollupContract.getVersion();
137
+
138
+ // Deploy TestContract
139
+ const contract = await this.setupTestContract(defaultAccountAddress);
140
+
141
+ // Recover any pending messages from store (clean up stale ones first)
142
+ await this.store.cleanupOldPendingMessages();
143
+ const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
144
+
145
+ // Seed initial L1→L2 messages if pipeline is empty
146
+ const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
147
+ for (let i = 0; i < seedCount; i++) {
148
+ await seedL1ToL2Message(
149
+ l1Client,
150
+ EthAddress.fromString(l1ContractAddresses.inboxAddress.toString()),
151
+ contract.address,
152
+ rollupVersion,
153
+ this.store,
154
+ this.log,
155
+ );
156
+ }
157
+
158
+ // Block until at least one message is ready
159
+ const allMessages = await this.store.getUnconsumedL1ToL2Messages();
160
+ if (allMessages.length > 0) {
161
+ this.log.info(`Waiting for first L1→L2 message to be ready...`);
162
+ const firstMsg = allMessages[0];
163
+ await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
164
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
165
+ // Use forPublicConsumption: false so we wait until the message is in the current world
166
+ // state. With true, it returns one block early which causes gas estimation simulation to
167
+ // fail since it runs against the current state.
168
+ // See https://linear.app/aztec-labs/issue/A-548 for details.
169
+ forPublicConsumption: false,
170
+ });
171
+ this.log.info(`First L1→L2 message is ready`);
172
+ }
173
+
174
+ return {
175
+ wallet: this.wallet,
176
+ defaultAccountAddress,
177
+ contract,
178
+ node: this.aztecNode,
179
+ l1Client,
180
+ rollupVersion,
181
+ };
182
+ }
183
+
184
+ private async setupTestContract(deployer: AztecAddress): Promise<TestContract> {
185
+ const deployOpts: DeployOptions = {
186
+ from: deployer,
187
+ contractAddressSalt: this.config.tokenSalt,
188
+ universalDeploy: true,
189
+ };
190
+ const deploy = TestContract.deploy(this.wallet);
191
+ const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
192
+ return TestContract.at(instance.address, this.wallet);
193
+ }
194
+
98
195
  /**
99
196
  * Checks if the sender account contract is initialized, and initializes it if necessary.
100
197
  * @returns The sender wallet.
@@ -192,6 +289,8 @@ export class BotFactory {
192
289
  tokenInstance = await deploy.getInstance(deployOpts);
193
290
  token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
194
291
  await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
292
+ // The contract constructor initializes private storage vars that need the contract's own nullifier key.
293
+ deployOpts.additionalScopes = [tokenInstance.address];
195
294
  } else {
196
295
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
197
296
  }
@@ -386,8 +485,10 @@ export class BotFactory {
386
485
  return;
387
486
  }
388
487
 
488
+ // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
489
+ const additionalScopes = isStandardToken ? undefined : [token.address];
389
490
  await this.withNoMinTxsPerBlock(async () => {
390
- const txHash = await new BatchCall(token.wallet, calls).send({ from: minter, wait: NO_WAIT });
491
+ const txHash = await new BatchCall(token.wallet, calls).send({ from: minter, additionalScopes, wait: NO_WAIT });
391
492
  this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
392
493
  return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
393
494
  });
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { Bot } from './bot.js';
2
2
  export { AmmBot } from './amm_bot.js';
3
+ export { CrossChainBot } from './cross_chain_bot.js';
3
4
  export { BotRunner } from './runner.js';
4
5
  export { BotStore } from './store/bot_store.js';
5
6
  export {
@@ -0,0 +1,79 @@
1
+ import { generateClaimSecret } from '@aztec/aztec.js/ethereum';
2
+ import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
3
+ import { compactArray } from '@aztec/foundation/collection';
4
+ import { Fr } from '@aztec/foundation/curves/bn254';
5
+ import { EthAddress } from '@aztec/foundation/eth-address';
6
+ import type { Logger } from '@aztec/foundation/log';
7
+ import { InboxAbi } from '@aztec/l1-artifacts';
8
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
9
+
10
+ import { decodeEventLog, getContract } from 'viem';
11
+
12
+ import type { BotStore, PendingL1ToL2Message } from './store/index.js';
13
+
14
+ /** Sends an L1→L2 message via the Inbox contract and stores it. */
15
+ export async function seedL1ToL2Message(
16
+ l1Client: ExtendedViemWalletClient,
17
+ inboxAddress: EthAddress,
18
+ l2Recipient: AztecAddress,
19
+ rollupVersion: bigint,
20
+ store: BotStore,
21
+ log: Logger,
22
+ ): Promise<PendingL1ToL2Message> {
23
+ log.info('Seeding L1→L2 message');
24
+ const [secret, secretHash] = await generateClaimSecret(log);
25
+ const content = Fr.random();
26
+
27
+ const inbox = getContract({
28
+ address: inboxAddress.toString(),
29
+ abi: InboxAbi,
30
+ client: l1Client,
31
+ });
32
+
33
+ const txHash = await inbox.write.sendL2Message(
34
+ [{ actor: l2Recipient.toString(), version: rollupVersion }, content.toString(), secretHash.toString()],
35
+ { gas: 1_000_000n },
36
+ );
37
+ log.info(`L1→L2 message sent in tx ${txHash}`);
38
+
39
+ const txReceipt = await l1Client.waitForTransactionReceipt({ hash: txHash });
40
+ if (txReceipt.status !== 'success') {
41
+ throw new Error(`L1→L2 message tx failed: ${txHash}`);
42
+ }
43
+
44
+ // Extract MessageSent event
45
+ const messageSentLogs = compactArray(
46
+ txReceipt.logs
47
+ .filter(l => l.address.toLowerCase() === inboxAddress.toString().toLowerCase())
48
+ .map(l => {
49
+ try {
50
+ return decodeEventLog({ abi: InboxAbi, eventName: 'MessageSent', data: l.data, topics: l.topics });
51
+ } catch {
52
+ return undefined;
53
+ }
54
+ }),
55
+ );
56
+
57
+ if (messageSentLogs.length !== 1) {
58
+ throw new Error(`Expected 1 MessageSent event, got ${messageSentLogs.length}`);
59
+ }
60
+
61
+ const event = messageSentLogs[0];
62
+
63
+ const msgHash = event.args.hash;
64
+ const globalLeafIndex = event.args.index;
65
+
66
+ const msg: PendingL1ToL2Message = {
67
+ content: content.toString(),
68
+ secret: secret.toString(),
69
+ secretHash: secretHash.toString(),
70
+ msgHash,
71
+ sender: l1Client.account!.address,
72
+ globalLeafIndex: globalLeafIndex.toString(),
73
+ timestamp: Date.now(),
74
+ };
75
+
76
+ await store.savePendingL1ToL2Message(msg);
77
+ log.info(`Seeded L1→L2 message msgHash=${msg.msgHash}`);
78
+ return msg;
79
+ }
package/src/runner.ts CHANGED
@@ -10,6 +10,7 @@ import { AmmBot } from './amm_bot.js';
10
10
  import type { BaseBot } from './base_bot.js';
11
11
  import { Bot } from './bot.js';
12
12
  import type { BotConfig } from './config.js';
13
+ import { CrossChainBot } from './cross_chain_bot.js';
13
14
  import type { BotInfo, BotRunnerApi } from './interface.js';
14
15
  import { BotStore } from './store/index.js';
15
16
 
@@ -146,9 +147,21 @@ export class BotRunner implements BotRunnerApi, Traceable {
146
147
 
147
148
  async #createBot() {
148
149
  try {
149
- this.bot = this.config.ammTxs
150
- ? AmmBot.create(this.config, this.wallet, this.aztecNode, this.aztecNodeAdmin, this.store)
151
- : Bot.create(this.config, this.wallet, this.aztecNode, this.aztecNodeAdmin, this.store);
150
+ switch (this.config.botMode) {
151
+ case 'crosschain':
152
+ this.bot = CrossChainBot.create(this.config, this.wallet, this.aztecNode, this.aztecNodeAdmin, this.store);
153
+ break;
154
+ case 'amm':
155
+ this.bot = AmmBot.create(this.config, this.wallet, this.aztecNode, this.aztecNodeAdmin, this.store);
156
+ break;
157
+ case 'transfer':
158
+ this.bot = Bot.create(this.config, this.wallet, this.aztecNode, this.aztecNodeAdmin, this.store);
159
+ break;
160
+ default: {
161
+ const _exhaustive: never = this.config.botMode;
162
+ throw new Error(`Unsupported bot mode: [${_exhaustive}]`);
163
+ }
164
+ }
152
165
  await this.bot;
153
166
  } catch (err) {
154
167
  this.log.error(`Error setting up bot: ${err}`);
@@ -2,6 +2,7 @@ import { AztecAddress } from '@aztec/aztec.js/addresses';
2
2
  import type { L2AmountClaim } from '@aztec/aztec.js/ethereum';
3
3
  import { Fr } from '@aztec/foundation/curves/bn254';
4
4
  import { type Logger, createLogger } from '@aztec/foundation/log';
5
+ import { DateProvider } from '@aztec/foundation/timer';
5
6
  import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
6
7
 
7
8
  export interface BridgeClaimData {
@@ -10,18 +11,38 @@ export interface BridgeClaimData {
10
11
  recipient: string;
11
12
  }
12
13
 
14
+ export interface PendingL1ToL2Message {
15
+ /** Random content field sent in the message. */
16
+ content: string;
17
+ /** Secret for consuming the message. */
18
+ secret: string;
19
+ /** Hash of the secret. */
20
+ secretHash: string;
21
+ /** Hash of the L1→L2 message. */
22
+ msgHash: string;
23
+ /** L1 sender address (hex). */
24
+ sender: string;
25
+ /** Global leaf index in the L1→L2 message tree. */
26
+ globalLeafIndex: string;
27
+ /** Timestamp when the message was seeded. */
28
+ timestamp: number;
29
+ }
30
+
13
31
  /**
14
32
  * Simple data store for the bot to persist L1 bridge claims.
15
33
  */
16
34
  export class BotStore {
17
35
  public static readonly SCHEMA_VERSION = 1;
18
36
  private readonly bridgeClaims: AztecAsyncMap<string, string>;
37
+ private readonly pendingL1ToL2: AztecAsyncMap<string, string>;
19
38
 
20
39
  constructor(
21
40
  private readonly store: AztecAsyncKVStore,
22
41
  private readonly log: Logger = createLogger('bot:store'),
42
+ private readonly dateProvider: DateProvider = new DateProvider(),
23
43
  ) {
24
44
  this.bridgeClaims = store.openMap<string, string>('bridge_claims');
45
+ this.pendingL1ToL2 = store.openMap<string, string>('pending_l1_to_l2');
25
46
  }
26
47
 
27
48
  /**
@@ -39,7 +60,7 @@ export class BotStore {
39
60
 
40
61
  const data = {
41
62
  claim: serializableClaim,
42
- timestamp: Date.now(),
63
+ timestamp: this.dateProvider.now(),
43
64
  recipient: recipient.toString(),
44
65
  };
45
66
 
@@ -115,7 +136,7 @@ export class BotStore {
115
136
  * Cleans up old bridge claims (older than 24 hours).
116
137
  */
117
138
  public async cleanupOldClaims(maxAgeMs: number = 24 * 60 * 60 * 1000): Promise<number> {
118
- const now = Date.now();
139
+ const now = this.dateProvider.now();
119
140
  let cleanedCount = 0;
120
141
  const entries = this.bridgeClaims.entriesAsync();
121
142
 
@@ -131,9 +152,43 @@ export class BotStore {
131
152
  return cleanedCount;
132
153
  }
133
154
 
134
- /**
135
- * Closes the store.
136
- */
155
+ /** Saves a pending L1→L2 message keyed by msgHash. */
156
+ public async savePendingL1ToL2Message(msg: PendingL1ToL2Message): Promise<void> {
157
+ await this.pendingL1ToL2.set(msg.msgHash, JSON.stringify(msg));
158
+ this.log.info(`Saved pending L1→L2 message ${msg.msgHash}`);
159
+ }
160
+
161
+ /** Returns all unconsumed pending L1→L2 messages. */
162
+ public async getUnconsumedL1ToL2Messages(): Promise<PendingL1ToL2Message[]> {
163
+ const messages: PendingL1ToL2Message[] = [];
164
+ for await (const [_, data] of this.pendingL1ToL2.entriesAsync()) {
165
+ messages.push(JSON.parse(data));
166
+ }
167
+ return messages;
168
+ }
169
+
170
+ /** Deletes a consumed L1→L2 message from the store. */
171
+ public async deleteL1ToL2Message(msgHash: string): Promise<void> {
172
+ await this.pendingL1ToL2.delete(msgHash);
173
+ this.log.info(`Deleted consumed L1→L2 message ${msgHash}`);
174
+ }
175
+
176
+ /** Cleans up pending L1→L2 messages older than maxAgeMs. */
177
+ public async cleanupOldPendingMessages(maxAgeMs: number = 24 * 60 * 60 * 1000): Promise<number> {
178
+ const now = this.dateProvider.now();
179
+ let cleanedCount = 0;
180
+ for await (const [key, data] of this.pendingL1ToL2.entriesAsync()) {
181
+ const parsed = JSON.parse(data);
182
+ if (now - parsed.timestamp > maxAgeMs) {
183
+ await this.pendingL1ToL2.delete(key);
184
+ cleanedCount++;
185
+ this.log.info(`Cleaned up old pending L1→L2 message ${key}`);
186
+ }
187
+ }
188
+ return cleanedCount;
189
+ }
190
+
191
+ /** Closes the store. */
137
192
  public async close(): Promise<void> {
138
193
  await this.store.close();
139
194
  this.log.info('Closed bot data store');
@@ -1 +1 @@
1
- export { BotStore, type BridgeClaimData } from './bot_store.js';
1
+ export { BotStore, type BridgeClaimData, type PendingL1ToL2Message } from './bot_store.js';