@aztec-labs/bot 6.0.0-nightly.20260829

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 (58) hide show
  1. package/README.md +3 -0
  2. package/dest/amm_bot.d.ts +33 -0
  3. package/dest/amm_bot.d.ts.map +1 -0
  4. package/dest/amm_bot.js +108 -0
  5. package/dest/base_bot.d.ts +21 -0
  6. package/dest/base_bot.d.ts.map +1 -0
  7. package/dest/base_bot.js +69 -0
  8. package/dest/bot.d.ts +29 -0
  9. package/dest/bot.d.ts.map +1 -0
  10. package/dest/bot.js +60 -0
  11. package/dest/config.d.ts +175 -0
  12. package/dest/config.d.ts.map +1 -0
  13. package/dest/config.js +241 -0
  14. package/dest/cross_chain_bot.d.ts +56 -0
  15. package/dest/cross_chain_bot.d.ts.map +1 -0
  16. package/dest/cross_chain_bot.js +138 -0
  17. package/dest/factory.d.ts +74 -0
  18. package/dest/factory.d.ts.map +1 -0
  19. package/dest/factory.js +532 -0
  20. package/dest/index.d.ts +9 -0
  21. package/dest/index.d.ts.map +1 -0
  22. package/dest/index.js +8 -0
  23. package/dest/interface.d.ts +19 -0
  24. package/dest/interface.d.ts.map +1 -0
  25. package/dest/interface.js +38 -0
  26. package/dest/l1_to_l2_seeding.d.ts +8 -0
  27. package/dest/l1_to_l2_seeding.d.ts.map +1 -0
  28. package/dest/l1_to_l2_seeding.js +63 -0
  29. package/dest/rpc.d.ts +4 -0
  30. package/dest/rpc.d.ts.map +1 -0
  31. package/dest/rpc.js +8 -0
  32. package/dest/runner.d.ts +54 -0
  33. package/dest/runner.d.ts.map +1 -0
  34. package/dest/runner.js +566 -0
  35. package/dest/store/bot_store.d.ts +69 -0
  36. package/dest/store/bot_store.d.ts.map +1 -0
  37. package/dest/store/bot_store.js +138 -0
  38. package/dest/store/index.d.ts +2 -0
  39. package/dest/store/index.d.ts.map +1 -0
  40. package/dest/store/index.js +1 -0
  41. package/dest/utils.d.ts +19 -0
  42. package/dest/utils.d.ts.map +1 -0
  43. package/dest/utils.js +29 -0
  44. package/package.json +95 -0
  45. package/src/amm_bot.ts +132 -0
  46. package/src/base_bot.ts +75 -0
  47. package/src/bot.ts +102 -0
  48. package/src/config.ts +316 -0
  49. package/src/cross_chain_bot.ts +208 -0
  50. package/src/factory.ts +628 -0
  51. package/src/index.ts +14 -0
  52. package/src/interface.ts +31 -0
  53. package/src/l1_to_l2_seeding.ts +79 -0
  54. package/src/rpc.ts +8 -0
  55. package/src/runner.ts +220 -0
  56. package/src/store/bot_store.ts +196 -0
  57. package/src/store/index.ts +1 -0
  58. package/src/utils.ts +38 -0
package/src/config.ts ADDED
@@ -0,0 +1,316 @@
1
+ import {
2
+ type ConfigMappingsType,
3
+ SecretValue,
4
+ booleanConfigHelper,
5
+ floatConfigHelper,
6
+ getConfigFromMappings,
7
+ getDefaultConfig,
8
+ numberConfigHelper,
9
+ optionalNumberConfigHelper,
10
+ pickConfigMappings,
11
+ secretFrConfigHelper,
12
+ secretStringConfigHelper,
13
+ } from '@aztec-labs/foundation/config';
14
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
15
+ import { getVKTreeRoot } from '@aztec-labs/noir-protocol-circuits-types/vk-tree';
16
+ import { protocolContractsHash } from '@aztec-labs/protocol-contracts';
17
+ import { type DataStoreConfig, dataConfigMappings } from '@aztec-labs/stdlib/kv-store';
18
+ import { schemas, zodFor } from '@aztec-labs/stdlib/schemas';
19
+ import type { ComponentsVersions } from '@aztec-labs/stdlib/versioning';
20
+ import { z } from 'zod';
21
+
22
+ const BotFollowChain = ['NONE', 'PROPOSED', 'CHECKPOINTED', 'PROVEN'] as const;
23
+ type BotFollowChain = (typeof BotFollowChain)[number];
24
+
25
+ const BotMode = ['transfer', 'amm', 'crosschain'] as const;
26
+ type BotMode = (typeof BotMode)[number];
27
+
28
+ export enum SupportedTokenContracts {
29
+ TokenContract = 'TokenContract',
30
+ PrivateTokenContract = 'PrivateTokenContract',
31
+ }
32
+
33
+ export type BotConfig = {
34
+ /** The URL to the Aztec node to check for tx pool status. */
35
+ nodeUrl: string | undefined;
36
+ /** The URL to the Aztec node admin API to force-flush txs if configured. */
37
+ nodeAdminUrl: string | undefined;
38
+ /** Url of the ethereum host. */
39
+ l1RpcUrls: string[] | undefined;
40
+ /** The mnemonic for the account to bridge fee juice from L1. */
41
+ l1Mnemonic: SecretValue<string> | undefined;
42
+ /** The private key for the account to bridge fee juice from L1. */
43
+ l1PrivateKey: SecretValue<string> | undefined;
44
+ /** How long to wait for L1 to L2 messages to become available on L2 */
45
+ l1ToL2MessageTimeoutSeconds: number;
46
+ /** Signing private key for the sender account. */
47
+ senderPrivateKey: SecretValue<Fr> | undefined;
48
+ /** Optional salt to use to instantiate the sender account */
49
+ senderSalt: Fr | undefined;
50
+ /** Salt for the token contract instantiation. */
51
+ tokenSalt: Fr;
52
+ /** Every how many seconds should a new tx be sent. */
53
+ txIntervalSeconds: number;
54
+ /** How many private token transfers are executed per tx. */
55
+ privateTransfersPerTx: number;
56
+ /** How many public token transfers are executed per tx. */
57
+ publicTransfersPerTx: number;
58
+ /** How to handle fee payments. */
59
+ feePaymentMethod: 'fee_juice';
60
+ /** 'How much is the bot willing to overpay vs. the current min fee' */
61
+ minFeePadding: number;
62
+ /** True to not automatically setup or start the bot on initialization. */
63
+ noStart: boolean;
64
+ /** How long to wait for a tx to be mined before reporting an error. */
65
+ txMinedWaitSeconds: number;
66
+ /** Whether to wait for txs to be proven, to be mined, or no wait at all. */
67
+ followChain: BotFollowChain;
68
+ /** Do not send a tx if the node's tx pool already has this many pending txs. */
69
+ maxPendingTxs: number;
70
+ /** Whether to flush after sending each 'setup' transaction */
71
+ flushSetupTransactions: boolean;
72
+ /** L2 gas limit for the tx (empty to let the bot's wallet estimate). */
73
+ l2GasLimit: number | undefined;
74
+ /** DA gas limit for the tx (empty to let the bot's wallet estimate). */
75
+ daGasLimit: number | undefined;
76
+ /** Token contract to use */
77
+ contract: SupportedTokenContracts;
78
+ /** The maximum number of consecutive errors before the bot shuts down */
79
+ maxConsecutiveErrors: number;
80
+ /** Stops the bot if service becomes unhealthy */
81
+ stopWhenUnhealthy: boolean;
82
+ /** Bot mode: transfer, amm, or crosschain. */
83
+ botMode: BotMode;
84
+ /** Number of L2→L1 messages per tx (crosschain mode). */
85
+ l2ToL1MessagesPerTx: number;
86
+ /** Max L1→L2 messages to keep in-flight (crosschain mode). */
87
+ l1ToL2SeedCount: number;
88
+ } & Pick<DataStoreConfig, 'dataDirectory' | 'dataStoreMapSizeKb'>;
89
+
90
+ export const BotConfigSchema = zodFor<BotConfig>()(
91
+ z
92
+ .object({
93
+ nodeUrl: z.string().optional(),
94
+ nodeAdminUrl: z.string().optional(),
95
+ l1RpcUrls: z.array(z.string()).optional(),
96
+ l1Mnemonic: schemas.SecretValue(z.string()).optional(),
97
+ l1PrivateKey: schemas.SecretValue(z.string()).optional(),
98
+ l1ToL2MessageTimeoutSeconds: z.number(),
99
+ senderPrivateKey: schemas.SecretValue(schemas.Fr).optional(),
100
+ senderSalt: schemas.Fr.optional(),
101
+ tokenSalt: schemas.Fr,
102
+ txIntervalSeconds: z.number(),
103
+ privateTransfersPerTx: z.number().int().nonnegative(),
104
+ publicTransfersPerTx: z.number().int().nonnegative(),
105
+ feePaymentMethod: z.literal('fee_juice'),
106
+ minFeePadding: z.number().nonnegative(),
107
+ noStart: z.boolean(),
108
+ txMinedWaitSeconds: z.number(),
109
+ followChain: z.enum(BotFollowChain),
110
+ maxPendingTxs: z.number().int().nonnegative(),
111
+ flushSetupTransactions: z.boolean(),
112
+ l2GasLimit: z.number().int().nonnegative().optional(),
113
+ daGasLimit: z.number().int().nonnegative().optional(),
114
+ contract: z.nativeEnum(SupportedTokenContracts),
115
+ maxConsecutiveErrors: z.number().int().nonnegative(),
116
+ stopWhenUnhealthy: z.boolean(),
117
+ botMode: z.enum(BotMode).default('transfer'),
118
+ l2ToL1MessagesPerTx: z.number().int().nonnegative().default(1),
119
+ l1ToL2SeedCount: z.number().int().nonnegative().default(1),
120
+ dataDirectory: z.string().optional(),
121
+ dataStoreMapSizeKb: z.number().optional(),
122
+ })
123
+ .transform(config => ({
124
+ nodeUrl: undefined,
125
+ nodeAdminUrl: undefined,
126
+ l1RpcUrls: undefined,
127
+ senderSalt: undefined,
128
+ l2GasLimit: undefined,
129
+ daGasLimit: undefined,
130
+ l1Mnemonic: undefined,
131
+ l1PrivateKey: undefined,
132
+ senderPrivateKey: undefined,
133
+ dataStoreMapSizeKb: 1_024 * 1_024,
134
+ ...config,
135
+ })),
136
+ );
137
+
138
+ export const botConfigMappings: ConfigMappingsType<BotConfig> = {
139
+ nodeUrl: {
140
+ env: 'AZTEC_NODE_URL',
141
+ description: 'The URL to the Aztec node to check for tx pool status.',
142
+ },
143
+ nodeAdminUrl: {
144
+ env: 'AZTEC_NODE_ADMIN_URL',
145
+ description: 'The URL to the Aztec node admin API to force-flush txs if configured.',
146
+ },
147
+ l1RpcUrls: {
148
+ env: 'ETHEREUM_HOSTS',
149
+ description: 'URL of the ethereum host.',
150
+ parseEnv: (val: string) => val.split(',').map(url => url.trim()),
151
+ },
152
+ l1Mnemonic: {
153
+ env: 'BOT_L1_MNEMONIC',
154
+ description: 'The mnemonic for the account to bridge fee juice from L1.',
155
+ ...secretStringConfigHelper(),
156
+ },
157
+ l1PrivateKey: {
158
+ env: 'BOT_L1_PRIVATE_KEY',
159
+ description: 'The private key for the account to bridge fee juice from L1.',
160
+ ...secretStringConfigHelper(),
161
+ },
162
+ l1ToL2MessageTimeoutSeconds: {
163
+ env: 'BOT_L1_TO_L2_TIMEOUT_SECONDS',
164
+ description: 'How long to wait for L1 to L2 messages to become available on L2',
165
+ ...numberConfigHelper(3600),
166
+ },
167
+ senderPrivateKey: {
168
+ env: 'BOT_PRIVATE_KEY',
169
+ description: 'Signing private key for the sender account.',
170
+ ...secretFrConfigHelper(),
171
+ },
172
+ senderSalt: {
173
+ env: 'BOT_ACCOUNT_SALT',
174
+ description: 'The salt to use to deploy the sender account.',
175
+ parseEnv: (val: string) => (val ? Fr.fromHexString(val) : undefined),
176
+ },
177
+ tokenSalt: {
178
+ env: 'BOT_TOKEN_SALT',
179
+ description: 'The salt to use to deploy the token contract.',
180
+ parseEnv: (val: string) => Fr.fromHexString(val),
181
+ defaultValue: Fr.fromHexString('1'),
182
+ },
183
+ txIntervalSeconds: {
184
+ env: 'BOT_TX_INTERVAL_SECONDS',
185
+ description: 'Every how many seconds should a new tx be sent.',
186
+ ...numberConfigHelper(60),
187
+ },
188
+ privateTransfersPerTx: {
189
+ env: 'BOT_PRIVATE_TRANSFERS_PER_TX',
190
+ description: 'How many private token transfers are executed per tx.',
191
+ ...numberConfigHelper(1),
192
+ },
193
+ publicTransfersPerTx: {
194
+ env: 'BOT_PUBLIC_TRANSFERS_PER_TX',
195
+ description: 'How many public token transfers are executed per tx.',
196
+ ...numberConfigHelper(1),
197
+ },
198
+ feePaymentMethod: {
199
+ env: 'BOT_FEE_PAYMENT_METHOD',
200
+ description: 'How to handle fee payments. (Options: fee_juice)',
201
+ parseEnv: val => (val as 'fee_juice') || undefined,
202
+ defaultValue: 'fee_juice',
203
+ },
204
+ minFeePadding: {
205
+ env: 'BOT_MIN_FEE_PADDING',
206
+ description: 'How much is the bot willing to overpay vs. the current base fee',
207
+ ...floatConfigHelper(3),
208
+ },
209
+ noStart: {
210
+ env: 'BOT_NO_START',
211
+ description: 'True to not automatically setup or start the bot on initialization.',
212
+ ...booleanConfigHelper(),
213
+ },
214
+ txMinedWaitSeconds: {
215
+ env: 'BOT_TX_MINED_WAIT_SECONDS',
216
+ description: 'How long to wait for a tx to be mined before reporting an error.',
217
+ ...numberConfigHelper(180),
218
+ },
219
+ followChain: {
220
+ env: 'BOT_FOLLOW_CHAIN',
221
+ description: 'Which chain the bot follows',
222
+ defaultValue: 'NONE',
223
+ parseEnv(val) {
224
+ const upper = val.toUpperCase();
225
+ if (upper === 'PENDING') {
226
+ return 'CHECKPOINTED';
227
+ }
228
+ if (!(BotFollowChain as readonly string[]).includes(upper)) {
229
+ throw new Error(`Invalid value for BOT_FOLLOW_CHAIN: ${val}`);
230
+ }
231
+ return upper as BotFollowChain;
232
+ },
233
+ },
234
+ maxPendingTxs: {
235
+ env: 'BOT_MAX_PENDING_TXS',
236
+ description: "Do not send a tx if the node's tx pool already has this many pending txs.",
237
+ ...numberConfigHelper(128),
238
+ },
239
+ flushSetupTransactions: {
240
+ env: 'BOT_FLUSH_SETUP_TRANSACTIONS',
241
+ description: 'Make a request for the sequencer to build a block after each setup transaction.',
242
+ ...booleanConfigHelper(false),
243
+ },
244
+ l2GasLimit: {
245
+ env: 'BOT_L2_GAS_LIMIT',
246
+ description: "L2 gas limit for the tx (empty to let the bot's wallet estimate).",
247
+ ...optionalNumberConfigHelper(),
248
+ },
249
+ daGasLimit: {
250
+ env: 'BOT_DA_GAS_LIMIT',
251
+ description: "DA gas limit for the tx (empty to let the bot's wallet estimate).",
252
+ ...optionalNumberConfigHelper(),
253
+ },
254
+ contract: {
255
+ env: 'BOT_TOKEN_CONTRACT',
256
+ description: 'Token contract to use',
257
+ defaultValue: SupportedTokenContracts.TokenContract,
258
+ parseEnv(val) {
259
+ if (!Object.values(SupportedTokenContracts).includes(val as any)) {
260
+ throw new Error(
261
+ `Invalid value for BOT_TOKEN_CONTRACT: ${val}. Valid values: ${Object.values(SupportedTokenContracts).join(
262
+ ', ',
263
+ )}`,
264
+ );
265
+ }
266
+ return val as SupportedTokenContracts;
267
+ },
268
+ },
269
+ maxConsecutiveErrors: {
270
+ env: 'BOT_MAX_CONSECUTIVE_ERRORS',
271
+ description: 'The maximum number of consecutive errors before the bot shuts down',
272
+ ...numberConfigHelper(0),
273
+ },
274
+ stopWhenUnhealthy: {
275
+ env: 'BOT_STOP_WHEN_UNHEALTHY',
276
+ description: 'Stops the bot if service becomes unhealthy',
277
+ ...booleanConfigHelper(false),
278
+ },
279
+ botMode: {
280
+ env: 'BOT_MODE',
281
+ description: 'Bot mode: transfer, amm, or crosschain',
282
+ defaultValue: 'transfer' as BotMode,
283
+ parseEnv(val: string) {
284
+ if (!(BotMode as readonly string[]).includes(val)) {
285
+ throw new Error(`Invalid value for BOT_MODE: ${val}`);
286
+ }
287
+ return val as BotMode;
288
+ },
289
+ },
290
+ l2ToL1MessagesPerTx: {
291
+ env: 'BOT_L2_TO_L1_MESSAGES_PER_TX',
292
+ description: 'Number of L2→L1 messages per tx (crosschain mode)',
293
+ ...numberConfigHelper(1),
294
+ },
295
+ l1ToL2SeedCount: {
296
+ env: 'BOT_L1_TO_L2_SEED_COUNT',
297
+ description: 'Max L1→L2 messages to keep in-flight (crosschain mode)',
298
+ ...numberConfigHelper(1),
299
+ },
300
+ ...pickConfigMappings(dataConfigMappings, ['dataStoreMapSizeKb', 'dataDirectory']),
301
+ };
302
+
303
+ export function getBotConfigFromEnv(): BotConfig {
304
+ return getConfigFromMappings<BotConfig>(botConfigMappings);
305
+ }
306
+
307
+ export function getBotDefaultConfig(): BotConfig {
308
+ return getDefaultConfig<BotConfig>(botConfigMappings);
309
+ }
310
+
311
+ export function getVersions(): Partial<ComponentsVersions> {
312
+ return {
313
+ l2ProtocolContractsHash: protocolContractsHash.toString(),
314
+ l2CircuitsVkTreeRoot: getVKTreeRoot().toString(),
315
+ };
316
+ }
@@ -0,0 +1,208 @@
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-labs/aztec.js/addresses';
27
+ import { BatchCall, NO_WAIT } from '@aztec-labs/aztec.js/contracts';
28
+ import { isL1ToL2MessageReady } from '@aztec-labs/aztec.js/messaging';
29
+ import type { TxHash, TxReceipt } from '@aztec-labs/aztec.js/tx';
30
+ import type { ExtendedViemWalletClient } from '@aztec-labs/ethereum/types';
31
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
32
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
33
+ import type { TestContract } from '@aztec-labs/noir-test-contracts.js/Test';
34
+ import type { BlockTag } from '@aztec-labs/stdlib/block';
35
+ import type { AztecNode, AztecNodeAdmin } from '@aztec-labs/stdlib/interfaces/client';
36
+ import type { EmbeddedWallet } from '@aztec-labs/wallets/embedded';
37
+
38
+ import { BaseBot } from './base_bot.js';
39
+ import type { BotConfig } from './config.js';
40
+ import { BotFactory } from './factory.js';
41
+ import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
42
+ import type { BotStore, PendingL1ToL2Message } from './store/index.js';
43
+
44
+ /** Stale message threshold: messages older than this are removed. */
45
+ const STALE_MESSAGE_THRESHOLD_MS = 2 * 60 * 60 * 1000; // 2 hours
46
+
47
+ /** Bot that exercises both L2→L1 and L1→L2 cross-chain messaging. */
48
+ export class CrossChainBot extends BaseBot {
49
+ private l2ToL1Sent = 0;
50
+ private l1ToL2Consumed = 0;
51
+ private pendingSeedPromise: Promise<void> | undefined;
52
+
53
+ protected constructor(
54
+ node: AztecNode,
55
+ wallet: EmbeddedWallet,
56
+ defaultAccountAddress: AztecAddress,
57
+ private readonly contract: TestContract,
58
+ private readonly l1Client: ExtendedViemWalletClient,
59
+ private readonly l1Recipient: EthAddress,
60
+ private readonly inboxAddress: EthAddress,
61
+ private readonly rollupVersion: bigint,
62
+ private readonly store: BotStore,
63
+ config: BotConfig,
64
+ private readonly syncChainTip?: BlockTag,
65
+ ) {
66
+ super(node, wallet, defaultAccountAddress, config);
67
+ }
68
+
69
+ static async create(
70
+ config: BotConfig,
71
+ wallet: EmbeddedWallet,
72
+ aztecNode: AztecNode,
73
+ aztecNodeAdmin: AztecNodeAdmin | undefined,
74
+ store: BotStore,
75
+ syncChainTip?: BlockTag,
76
+ ): Promise<CrossChainBot> {
77
+ if (config.followChain === 'NONE') {
78
+ throw new Error(`CrossChainBot requires followChain to be set (got NONE)`);
79
+ }
80
+ const factory = new BotFactory(config, wallet, store, aztecNode, aztecNodeAdmin, syncChainTip);
81
+ const { defaultAccountAddress, contract, l1Client, rollupVersion } = await factory.setupCrossChain();
82
+ const l1Recipient = EthAddress.fromString(l1Client.account!.address);
83
+ const { l1ContractAddresses } = await aztecNode.getNodeInfo();
84
+ const inboxAddress = EthAddress.fromString(l1ContractAddresses.inboxAddress.toString());
85
+ return new CrossChainBot(
86
+ aztecNode,
87
+ wallet,
88
+ defaultAccountAddress,
89
+ contract,
90
+ l1Client,
91
+ l1Recipient,
92
+ inboxAddress,
93
+ rollupVersion,
94
+ store,
95
+ config,
96
+ syncChainTip,
97
+ );
98
+ }
99
+
100
+ protected async createAndSendTx(logCtx: object): Promise<TxHash> {
101
+ const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
102
+
103
+ // Send an L1→L2 message if we're below the threshold and not already seeding one
104
+ if (pendingMessages.length < this.config.l1ToL2SeedCount && !this.pendingSeedPromise) {
105
+ this.pendingSeedPromise = this.seedNewL1ToL2Message()
106
+ .catch(err => this.log.warn(`Failed to seed L1→L2 message: ${err}`, logCtx))
107
+ .finally(() => {
108
+ this.pendingSeedPromise = undefined;
109
+ });
110
+ }
111
+
112
+ // Build batch: always L2→L1, optionally consume L1→L2
113
+ const calls = [];
114
+
115
+ // L2→L1: create messages with random content
116
+ for (let i = 0; i < this.config.l2ToL1MessagesPerTx; i++) {
117
+ calls.push(
118
+ this.contract.methods.create_l2_to_l1_message_arbitrary_recipient_public(Fr.random(), this.l1Recipient),
119
+ );
120
+ }
121
+
122
+ // L1→L2: consume oldest ready message if available
123
+ const readyMsg = await this.getReadyL1ToL2Message(pendingMessages);
124
+ if (readyMsg) {
125
+ calls.push(
126
+ this.contract.methods.consume_message_from_arbitrary_sender_public(
127
+ Fr.fromHexString(readyMsg.content),
128
+ Fr.fromHexString(readyMsg.secret),
129
+ EthAddress.fromString(readyMsg.sender),
130
+ new Fr(BigInt(readyMsg.globalLeafIndex)),
131
+ ),
132
+ );
133
+ // Delete consumed message immediately so it works with FOLLOW_CHAIN=NONE
134
+ await this.store.deleteL1ToL2Message(readyMsg.msgHash);
135
+ this.l1ToL2Consumed++;
136
+ } else {
137
+ this.log.warn(`No ready L1→L2 message to consume`, {
138
+ ...logCtx,
139
+ pendingCount: pendingMessages.length,
140
+ });
141
+ }
142
+
143
+ const batch = new BatchCall(this.wallet, calls);
144
+ const opts = this.getSendMethodOpts();
145
+
146
+ this.log.verbose(`Sending cross-chain batch with ${calls.length} calls`, logCtx);
147
+ const { txHash } = await batch.send({ ...opts, wait: NO_WAIT });
148
+ return txHash;
149
+ }
150
+
151
+ protected override async onTxMined(receipt: TxReceipt, logCtx: object): Promise<void> {
152
+ // Verify L2→L1 messages appeared in this tx's effects
153
+ const minedReceipt = await this.node.getTxReceipt(receipt.txHash, { includeTxEffect: true });
154
+ const l2ToL1MsgsRaw = minedReceipt.txEffect?.l2ToL1Msgs;
155
+ if (l2ToL1MsgsRaw) {
156
+ const l2ToL1Msgs = l2ToL1MsgsRaw.filter(m => !m.isZero());
157
+ if (l2ToL1Msgs.length >= this.config.l2ToL1MessagesPerTx) {
158
+ this.l2ToL1Sent += l2ToL1Msgs.length;
159
+ } else {
160
+ this.log.error(`Expected ${this.config.l2ToL1MessagesPerTx} L2→L1 messages but found ${l2ToL1Msgs.length}`, {
161
+ ...logCtx,
162
+ blockNumber: receipt.blockNumber,
163
+ txHash: receipt.txHash.toString(),
164
+ });
165
+ }
166
+ }
167
+
168
+ const pendingCount = (await this.store.getUnconsumedL1ToL2Messages()).length;
169
+ this.log.info(`CrossChainBot txs mined`, {
170
+ ...logCtx,
171
+ l2ToL1Sent: this.l2ToL1Sent,
172
+ l1ToL2Consumed: this.l1ToL2Consumed,
173
+ l1ToL2Pending: pendingCount,
174
+ });
175
+ }
176
+
177
+ /** Finds the oldest pending message that is ready for consumption. */
178
+ private async getReadyL1ToL2Message(
179
+ pendingMessages: PendingL1ToL2Message[],
180
+ ): Promise<PendingL1ToL2Message | undefined> {
181
+ const now = Date.now();
182
+ for (const msg of pendingMessages) {
183
+ const ready = await isL1ToL2MessageReady(this.node, Fr.fromHexString(msg.msgHash), this.syncChainTip);
184
+ if (ready) {
185
+ return msg;
186
+ }
187
+
188
+ // Time-based stale detection: if the message is old and still not ready, remove it
189
+ if (now - msg.timestamp > STALE_MESSAGE_THRESHOLD_MS) {
190
+ await this.store.deleteL1ToL2Message(msg.msgHash);
191
+ this.log.warn(`Removed stale L1→L2 message ${msg.msgHash}`);
192
+ }
193
+ }
194
+ return undefined;
195
+ }
196
+
197
+ /** Seeds a new L1→L2 message on L1 and stores it. */
198
+ private async seedNewL1ToL2Message(): Promise<void> {
199
+ await seedL1ToL2Message(
200
+ this.l1Client,
201
+ this.inboxAddress,
202
+ this.contract.address,
203
+ this.rollupVersion,
204
+ this.store,
205
+ this.log,
206
+ );
207
+ }
208
+ }