@aztec/bot 0.0.1-commit.5daedc8 → 0.0.1-commit.6201a7b05

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 (46) hide show
  1. package/dest/amm_bot.d.ts +6 -7
  2. package/dest/amm_bot.d.ts.map +1 -1
  3. package/dest/amm_bot.js +28 -17
  4. package/dest/base_bot.d.ts +7 -7
  5. package/dest/base_bot.d.ts.map +1 -1
  6. package/dest/base_bot.js +26 -37
  7. package/dest/bot.d.ts +6 -6
  8. package/dest/bot.d.ts.map +1 -1
  9. package/dest/bot.js +9 -9
  10. package/dest/config.d.ts +44 -29
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +46 -19
  13. package/dest/cross_chain_bot.d.ts +54 -0
  14. package/dest/cross_chain_bot.d.ts.map +1 -0
  15. package/dest/cross_chain_bot.js +134 -0
  16. package/dest/factory.d.ts +25 -10
  17. package/dest/factory.d.ts.map +1 -1
  18. package/dest/factory.js +356 -101
  19. package/dest/index.d.ts +2 -1
  20. package/dest/index.d.ts.map +1 -1
  21. package/dest/index.js +1 -0
  22. package/dest/l1_to_l2_seeding.d.ts +8 -0
  23. package/dest/l1_to_l2_seeding.d.ts.map +1 -0
  24. package/dest/l1_to_l2_seeding.js +63 -0
  25. package/dest/runner.d.ts +3 -3
  26. package/dest/runner.d.ts.map +1 -1
  27. package/dest/runner.js +429 -31
  28. package/dest/store/bot_store.d.ts +31 -6
  29. package/dest/store/bot_store.d.ts.map +1 -1
  30. package/dest/store/bot_store.js +38 -7
  31. package/dest/store/index.d.ts +2 -2
  32. package/dest/store/index.d.ts.map +1 -1
  33. package/dest/utils.js +3 -3
  34. package/package.json +19 -16
  35. package/src/amm_bot.ts +27 -22
  36. package/src/base_bot.ts +22 -44
  37. package/src/bot.ts +11 -12
  38. package/src/config.ts +94 -64
  39. package/src/cross_chain_bot.ts +203 -0
  40. package/src/factory.ts +395 -83
  41. package/src/index.ts +1 -0
  42. package/src/l1_to_l2_seeding.ts +79 -0
  43. package/src/runner.ts +18 -5
  44. package/src/store/bot_store.ts +61 -6
  45. package/src/store/index.ts +1 -1
  46. package/src/utils.ts +3 -3
package/src/config.ts CHANGED
@@ -10,18 +10,21 @@ import {
10
10
  secretFrConfigHelper,
11
11
  secretStringConfigHelper,
12
12
  } from '@aztec/foundation/config';
13
- import { Fr } from '@aztec/foundation/fields';
14
- import { type DataStoreConfig, dataConfigMappings } from '@aztec/kv-store/config';
13
+ import { Fr } from '@aztec/foundation/curves/bn254';
15
14
  import { getVKTreeRoot } from '@aztec/noir-protocol-circuits-types/vk-tree';
16
15
  import { protocolContractsHash } from '@aztec/protocol-contracts';
17
- import { type ZodFor, schemas } from '@aztec/stdlib/schemas';
16
+ import { type DataStoreConfig, dataConfigMappings } from '@aztec/stdlib/kv-store';
17
+ import { schemas, zodFor } from '@aztec/stdlib/schemas';
18
18
  import type { ComponentsVersions } from '@aztec/stdlib/versioning';
19
19
 
20
20
  import { z } from 'zod';
21
21
 
22
- const BotFollowChain = ['NONE', 'PENDING', 'PROVEN'] as const;
22
+ const BotFollowChain = ['NONE', 'PROPOSED', 'CHECKPOINTED', 'PROVEN'] as const;
23
23
  type BotFollowChain = (typeof BotFollowChain)[number];
24
24
 
25
+ const BotMode = ['transfer', 'amm', 'crosschain'] as const;
26
+ type BotMode = (typeof BotMode)[number];
27
+
25
28
  export enum SupportedTokenContracts {
26
29
  TokenContract = 'TokenContract',
27
30
  PrivateTokenContract = 'PrivateTokenContract',
@@ -54,8 +57,8 @@ export type BotConfig = {
54
57
  publicTransfersPerTx: number;
55
58
  /** How to handle fee payments. */
56
59
  feePaymentMethod: 'fee_juice';
57
- /** 'How much is the bot willing to overpay vs. the current base fee' */
58
- baseFeePadding: number;
60
+ /** 'How much is the bot willing to overpay vs. the current min fee' */
61
+ minFeePadding: number;
59
62
  /** True to not automatically setup or start the bot on initialization. */
60
63
  noStart: boolean;
61
64
  /** How long to wait for a tx to be mined before reporting an error. */
@@ -66,9 +69,9 @@ export type BotConfig = {
66
69
  maxPendingTxs: number;
67
70
  /** Whether to flush after sending each 'setup' transaction */
68
71
  flushSetupTransactions: boolean;
69
- /** L2 gas limit for the tx (empty to have the bot trigger an estimate gas). */
72
+ /** L2 gas limit for the tx (empty to let the bot's wallet estimate). */
70
73
  l2GasLimit: number | undefined;
71
- /** DA gas limit for the tx (empty to have the bot trigger an estimate gas). */
74
+ /** DA gas limit for the tx (empty to let the bot's wallet estimate). */
72
75
  daGasLimit: number | undefined;
73
76
  /** Token contract to use */
74
77
  contract: SupportedTokenContracts;
@@ -76,54 +79,61 @@ export type BotConfig = {
76
79
  maxConsecutiveErrors: number;
77
80
  /** Stops the bot if service becomes unhealthy */
78
81
  stopWhenUnhealthy: boolean;
79
- /** Deploy an AMM contract and do swaps instead of transfers */
80
- ammTxs: 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;
81
88
  } & Pick<DataStoreConfig, 'dataDirectory' | 'dataStoreMapSizeKb'>;
82
89
 
83
- export const BotConfigSchema = z
84
- .object({
85
- nodeUrl: z.string().optional(),
86
- nodeAdminUrl: z.string().optional(),
87
- l1RpcUrls: z.array(z.string()).optional(),
88
- l1Mnemonic: schemas.SecretValue(z.string()).optional(),
89
- l1PrivateKey: schemas.SecretValue(z.string()).optional(),
90
- l1ToL2MessageTimeoutSeconds: z.number(),
91
- senderPrivateKey: schemas.SecretValue(schemas.Fr).optional(),
92
- senderSalt: schemas.Fr.optional(),
93
- tokenSalt: schemas.Fr,
94
- txIntervalSeconds: z.number(),
95
- privateTransfersPerTx: z.number().int().nonnegative(),
96
- publicTransfersPerTx: z.number().int().nonnegative(),
97
- feePaymentMethod: z.literal('fee_juice'),
98
- baseFeePadding: z.number().int().nonnegative(),
99
- noStart: z.boolean(),
100
- txMinedWaitSeconds: z.number(),
101
- followChain: z.enum(BotFollowChain),
102
- maxPendingTxs: z.number().int().nonnegative(),
103
- flushSetupTransactions: z.boolean(),
104
- l2GasLimit: z.number().int().nonnegative().optional(),
105
- daGasLimit: z.number().int().nonnegative().optional(),
106
- contract: z.nativeEnum(SupportedTokenContracts),
107
- maxConsecutiveErrors: z.number().int().nonnegative(),
108
- stopWhenUnhealthy: z.boolean(),
109
- ammTxs: z.boolean().default(false),
110
- dataDirectory: z.string().optional(),
111
- dataStoreMapSizeKb: z.number().optional(),
112
- })
113
- .transform(config => ({
114
- nodeUrl: undefined,
115
- nodeAdminUrl: undefined,
116
- l1RpcUrls: undefined,
117
- senderSalt: undefined,
118
- l2GasLimit: undefined,
119
- daGasLimit: undefined,
120
- l1Mnemonic: undefined,
121
- l1PrivateKey: undefined,
122
- senderPrivateKey: undefined,
123
- dataDirectory: undefined,
124
- dataStoreMapSizeKb: 1_024 * 1_024,
125
- ...config,
126
- })) satisfies ZodFor<BotConfig>;
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().int().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
+ );
127
137
 
128
138
  export const botConfigMappings: ConfigMappingsType<BotConfig> = {
129
139
  nodeUrl: {
@@ -191,8 +201,8 @@ export const botConfigMappings: ConfigMappingsType<BotConfig> = {
191
201
  parseEnv: val => (val as 'fee_juice') || undefined,
192
202
  defaultValue: 'fee_juice',
193
203
  },
194
- baseFeePadding: {
195
- env: 'BOT_BASE_FEE_PADDING',
204
+ minFeePadding: {
205
+ env: 'BOT_MIN_FEE_PADDING',
196
206
  description: 'How much is the bot willing to overpay vs. the current base fee',
197
207
  ...numberConfigHelper(3),
198
208
  },
@@ -211,10 +221,14 @@ export const botConfigMappings: ConfigMappingsType<BotConfig> = {
211
221
  description: 'Which chain the bot follows',
212
222
  defaultValue: 'NONE',
213
223
  parseEnv(val) {
214
- if (!(BotFollowChain as readonly string[]).includes(val.toUpperCase())) {
224
+ const upper = val.toUpperCase();
225
+ if (upper === 'PENDING') {
226
+ return 'CHECKPOINTED';
227
+ }
228
+ if (!(BotFollowChain as readonly string[]).includes(upper)) {
215
229
  throw new Error(`Invalid value for BOT_FOLLOW_CHAIN: ${val}`);
216
230
  }
217
- return val as BotFollowChain;
231
+ return upper as BotFollowChain;
218
232
  },
219
233
  },
220
234
  maxPendingTxs: {
@@ -229,12 +243,12 @@ export const botConfigMappings: ConfigMappingsType<BotConfig> = {
229
243
  },
230
244
  l2GasLimit: {
231
245
  env: 'BOT_L2_GAS_LIMIT',
232
- description: 'L2 gas limit for the tx (empty to have the bot trigger an estimate gas).',
246
+ description: "L2 gas limit for the tx (empty to let the bot's wallet estimate).",
233
247
  ...optionalNumberConfigHelper(),
234
248
  },
235
249
  daGasLimit: {
236
250
  env: 'BOT_DA_GAS_LIMIT',
237
- description: 'DA gas limit for the tx (empty to have the bot trigger an estimate gas).',
251
+ description: "DA gas limit for the tx (empty to let the bot's wallet estimate).",
238
252
  ...optionalNumberConfigHelper(),
239
253
  },
240
254
  contract: {
@@ -262,10 +276,26 @@ export const botConfigMappings: ConfigMappingsType<BotConfig> = {
262
276
  description: 'Stops the bot if service becomes unhealthy',
263
277
  ...booleanConfigHelper(false),
264
278
  },
265
- ammTxs: {
266
- env: 'BOT_AMM_TXS',
267
- description: 'Deploy an AMM and send swaps to it',
268
- ...booleanConfigHelper(false),
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),
269
299
  },
270
300
  ...pickConfigMappings(dataConfigMappings, ['dataStoreMapSizeKb', 'dataDirectory']),
271
301
  };
@@ -0,0 +1,203 @@
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 = this.getSendMethodOpts();
141
+
142
+ this.log.verbose(`Sending cross-chain batch with ${calls.length} calls`, logCtx);
143
+ const { txHash } = await batch.send({ ...opts, wait: NO_WAIT });
144
+ return txHash;
145
+ }
146
+
147
+ protected override async onTxMined(receipt: TxReceipt, logCtx: object): Promise<void> {
148
+ // Verify L2→L1 messages appeared in this tx's effects
149
+ const indexed = await this.node.getTxEffect(receipt.txHash);
150
+ if (indexed) {
151
+ const l2ToL1Msgs = indexed.data.l2ToL1Msgs.filter(m => !m.isZero());
152
+ if (l2ToL1Msgs.length >= this.config.l2ToL1MessagesPerTx) {
153
+ this.l2ToL1Sent += l2ToL1Msgs.length;
154
+ } else {
155
+ this.log.error(`Expected ${this.config.l2ToL1MessagesPerTx} L2→L1 messages but found ${l2ToL1Msgs.length}`, {
156
+ ...logCtx,
157
+ blockNumber: receipt.blockNumber,
158
+ txHash: receipt.txHash.toString(),
159
+ });
160
+ }
161
+ }
162
+
163
+ const pendingCount = (await this.store.getUnconsumedL1ToL2Messages()).length;
164
+ this.log.info(`CrossChainBot txs mined`, {
165
+ ...logCtx,
166
+ l2ToL1Sent: this.l2ToL1Sent,
167
+ l1ToL2Consumed: this.l1ToL2Consumed,
168
+ l1ToL2Pending: pendingCount,
169
+ });
170
+ }
171
+
172
+ /** Finds the oldest pending message that is ready for consumption. */
173
+ private async getReadyL1ToL2Message(
174
+ pendingMessages: PendingL1ToL2Message[],
175
+ ): Promise<PendingL1ToL2Message | undefined> {
176
+ const now = Date.now();
177
+ for (const msg of pendingMessages) {
178
+ const ready = await isL1ToL2MessageReady(this.node, Fr.fromHexString(msg.msgHash));
179
+ if (ready) {
180
+ return msg;
181
+ }
182
+
183
+ // Time-based stale detection: if the message is old and still not ready, remove it
184
+ if (now - msg.timestamp > STALE_MESSAGE_THRESHOLD_MS) {
185
+ await this.store.deleteL1ToL2Message(msg.msgHash);
186
+ this.log.warn(`Removed stale L1→L2 message ${msg.msgHash}`);
187
+ }
188
+ }
189
+ return undefined;
190
+ }
191
+
192
+ /** Seeds a new L1→L2 message on L1 and stores it. */
193
+ private async seedNewL1ToL2Message(): Promise<void> {
194
+ await seedL1ToL2Message(
195
+ this.l1Client,
196
+ this.inboxAddress,
197
+ this.contract.address,
198
+ this.rollupVersion,
199
+ this.store,
200
+ this.log,
201
+ );
202
+ }
203
+ }