@aztec/bot 0.0.1-commit.fffb133c → 0.0.1-dev

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 +4 -4
  2. package/dest/amm_bot.d.ts.map +1 -1
  3. package/dest/amm_bot.js +24 -17
  4. package/dest/base_bot.d.ts +6 -6
  5. package/dest/base_bot.d.ts.map +1 -1
  6. package/dest/base_bot.js +21 -32
  7. package/dest/bot.d.ts +4 -4
  8. package/dest/bot.d.ts.map +1 -1
  9. package/dest/bot.js +5 -8
  10. package/dest/config.d.ts +32 -16
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +38 -10
  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 +20 -5
  17. package/dest/factory.d.ts.map +1 -1
  18. package/dest/factory.js +126 -60
  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 +17 -1
  28. package/dest/store/bot_store.d.ts +30 -5
  29. package/dest/store/bot_store.d.ts.map +1 -1
  30. package/dest/store/bot_store.js +37 -6
  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 +16 -13
  35. package/src/amm_bot.ts +24 -19
  36. package/src/base_bot.ts +15 -33
  37. package/src/bot.ts +8 -10
  38. package/src/config.ts +43 -14
  39. package/src/cross_chain_bot.ts +203 -0
  40. package/src/factory.ts +158 -59
  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 +60 -5
  45. package/src/store/index.ts +1 -1
  46. package/src/utils.ts +3 -3
package/src/factory.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { SchnorrAccountContract } from '@aztec/accounts/schnorr';
2
1
  import { getInitialTestAccountsData } from '@aztec/accounts/testing';
2
+ import { NO_FROM } from '@aztec/aztec.js/account';
3
3
  import { AztecAddress } from '@aztec/aztec.js/addresses';
4
4
  import {
5
5
  BatchCall,
@@ -9,27 +9,32 @@ import {
9
9
  type DeployOptions,
10
10
  NO_WAIT,
11
11
  } from '@aztec/aztec.js/contracts';
12
- import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
13
12
  import type { L2AmountClaim } from '@aztec/aztec.js/ethereum';
13
+ import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
14
14
  import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
15
15
  import { deriveKeys } from '@aztec/aztec.js/keys';
16
16
  import { createLogger } from '@aztec/aztec.js/log';
17
17
  import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
18
18
  import { waitForTx } from '@aztec/aztec.js/node';
19
+ import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
19
20
  import { createEthereumChain } from '@aztec/ethereum/chain';
20
21
  import { createExtendedL1Client } from '@aztec/ethereum/client';
22
+ import { RollupContract } from '@aztec/ethereum/contracts';
23
+ import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
21
24
  import { Fr } from '@aztec/foundation/curves/bn254';
25
+ import { EthAddress } from '@aztec/foundation/eth-address';
22
26
  import { Timer } from '@aztec/foundation/timer';
23
27
  import { AMMContract } from '@aztec/noir-contracts.js/AMM';
24
28
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
25
29
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
30
+ import { TestContract } from '@aztec/noir-test-contracts.js/Test';
26
31
  import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
27
- import { GasSettings } from '@aztec/stdlib/gas';
28
32
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
29
33
  import { deriveSigningKey } from '@aztec/stdlib/keys';
30
- import { TestWallet } from '@aztec/test-wallet/server';
34
+ import { EmbeddedWallet } from '@aztec/wallets/embedded';
31
35
 
32
36
  import { type BotConfig, SupportedTokenContracts } from './config.js';
37
+ import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
33
38
  import type { BotStore } from './store/index.js';
34
39
  import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
35
40
 
@@ -41,32 +46,36 @@ export class BotFactory {
41
46
 
42
47
  constructor(
43
48
  private readonly config: BotConfig,
44
- private readonly wallet: TestWallet,
49
+ private readonly wallet: EmbeddedWallet,
45
50
  private readonly store: BotStore,
46
51
  private readonly aztecNode: AztecNode,
47
52
  private readonly aztecNodeAdmin?: AztecNodeAdmin,
48
- ) {}
53
+ ) {
54
+ // Set fee padding on the wallet so that all transactions during setup
55
+ // (token deploy, minting, etc.) use the configured padding, not the default.
56
+ this.wallet.setMinFeePadding(config.minFeePadding);
57
+ }
49
58
 
50
59
  /**
51
60
  * Initializes a new bot by setting up the sender account, registering the recipient,
52
61
  * deploying the token contract, and minting tokens if necessary.
53
62
  */
54
63
  public async setup(): Promise<{
55
- wallet: TestWallet;
64
+ wallet: EmbeddedWallet;
56
65
  defaultAccountAddress: AztecAddress;
57
66
  token: TokenContract | PrivateTokenContract;
58
67
  node: AztecNode;
59
68
  recipient: AztecAddress;
60
69
  }> {
61
70
  const defaultAccountAddress = await this.setupAccount();
62
- const recipient = (await this.wallet.createAccount()).address;
71
+ const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
63
72
  const token = await this.setupToken(defaultAccountAddress);
64
73
  await this.mintTokens(token, defaultAccountAddress);
65
74
  return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
66
75
  }
67
76
 
68
77
  public async setupAmm(): Promise<{
69
- wallet: TestWallet;
78
+ wallet: EmbeddedWallet;
70
79
  defaultAccountAddress: AztecAddress;
71
80
  amm: AMMContract;
72
81
  token0: TokenContract;
@@ -96,6 +105,85 @@ export class BotFactory {
96
105
  return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
97
106
  }
98
107
 
108
+ /**
109
+ * Initializes the cross-chain bot by deploying TestContract, creating an L1 client,
110
+ * seeding initial L1→L2 messages, and waiting for the first to be ready.
111
+ */
112
+ public async setupCrossChain(): Promise<{
113
+ wallet: EmbeddedWallet;
114
+ defaultAccountAddress: AztecAddress;
115
+ contract: TestContract;
116
+ node: AztecNode;
117
+ l1Client: ExtendedViemWalletClient;
118
+ rollupVersion: bigint;
119
+ }> {
120
+ const defaultAccountAddress = await this.setupAccount();
121
+
122
+ // Create L1 client (same pattern as bridgeL1FeeJuice)
123
+ const l1RpcUrls = this.config.l1RpcUrls;
124
+ if (!l1RpcUrls?.length) {
125
+ throw new Error('L1 RPC URLs required for cross-chain bot');
126
+ }
127
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
128
+ if (!mnemonicOrPrivateKey) {
129
+ throw new Error('L1 mnemonic or private key required for cross-chain bot');
130
+ }
131
+ const { l1ChainId, l1ContractAddresses } = await this.aztecNode.getNodeInfo();
132
+ const chain = createEthereumChain(l1RpcUrls, l1ChainId);
133
+ const l1Client = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
134
+
135
+ // Fetch Rollup version (needed for Inbox L2Actor struct)
136
+ const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
137
+ const rollupVersion = await rollupContract.getVersion();
138
+
139
+ // Deploy TestContract
140
+ const contract = await this.setupTestContract(defaultAccountAddress);
141
+
142
+ // Recover any pending messages from store (clean up stale ones first)
143
+ await this.store.cleanupOldPendingMessages();
144
+ const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
145
+
146
+ // Seed initial L1→L2 messages if pipeline is empty
147
+ const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
148
+ for (let i = 0; i < seedCount; i++) {
149
+ await seedL1ToL2Message(
150
+ l1Client,
151
+ EthAddress.fromString(l1ContractAddresses.inboxAddress.toString()),
152
+ contract.address,
153
+ rollupVersion,
154
+ this.store,
155
+ this.log,
156
+ );
157
+ }
158
+
159
+ // Block until at least one message is ready
160
+ const allMessages = await this.store.getUnconsumedL1ToL2Messages();
161
+ if (allMessages.length > 0) {
162
+ this.log.info(`Waiting for first L1→L2 message to be ready...`);
163
+ const firstMsg = allMessages[0];
164
+ await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
165
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
166
+ });
167
+ this.log.info(`First L1→L2 message is ready`);
168
+ }
169
+
170
+ return {
171
+ wallet: this.wallet,
172
+ defaultAccountAddress,
173
+ contract,
174
+ node: this.aztecNode,
175
+ l1Client,
176
+ rollupVersion,
177
+ };
178
+ }
179
+
180
+ private async setupTestContract(deployer: AztecAddress): Promise<TestContract> {
181
+ const deployOpts: DeployOptions = { from: deployer };
182
+ const deploy = TestContract.deploy(this.wallet, { salt: this.config.tokenSalt, universalDeploy: true });
183
+ const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
184
+ return TestContract.at(instance.address, this.wallet);
185
+ }
186
+
99
187
  /**
100
188
  * Checks if the sender account contract is initialized, and initializes it if necessary.
101
189
  * @returns The sender wallet.
@@ -114,14 +202,9 @@ export class BotFactory {
114
202
  private async setupAccountWithPrivateKey(secret: Fr) {
115
203
  const salt = this.config.senderSalt ?? Fr.ONE;
116
204
  const signingKey = deriveSigningKey(secret);
117
- const accountData = {
118
- secret,
119
- salt,
120
- contract: new SchnorrAccountContract(signingKey!),
121
- };
122
- const accountManager = await this.wallet.createAccount(accountData);
205
+ const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
123
206
  const metadata = await this.wallet.getContractMetadata(accountManager.address);
124
- if (metadata.isContractInitialized) {
207
+ if (metadata.initializationStatus === ContractInitializationStatus.INITIALIZED) {
125
208
  this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
126
209
  const timer = new Timer();
127
210
  const address = accountManager.address;
@@ -136,13 +219,11 @@ export class BotFactory {
136
219
 
137
220
  const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
138
221
  const deployMethod = await accountManager.getDeployMethod();
139
- const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
140
- const gasSettings = GasSettings.default({ maxFeesPerGas });
141
222
 
142
223
  await this.withNoMinTxsPerBlock(async () => {
143
- const txHash = await deployMethod.send({
144
- from: AztecAddress.ZERO,
145
- fee: { gasSettings, paymentMethod },
224
+ const { txHash } = await deployMethod.send({
225
+ from: NO_FROM,
226
+ fee: { paymentMethod },
146
227
  wait: NO_WAIT,
147
228
  });
148
229
  this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
@@ -159,12 +240,11 @@ export class BotFactory {
159
240
 
160
241
  private async setupTestAccount() {
161
242
  const [initialAccountData] = await getInitialTestAccountsData();
162
- const accountData = {
163
- secret: initialAccountData.secret,
164
- salt: initialAccountData.salt,
165
- contract: new SchnorrAccountContract(initialAccountData.signingKey),
166
- };
167
- const accountManager = await this.wallet.createAccount(accountData);
243
+ const accountManager = await this.wallet.createSchnorrAccount(
244
+ initialAccountData.secret,
245
+ initialAccountData.salt,
246
+ initialAccountData.signingKey,
247
+ );
168
248
  return accountManager.address;
169
249
  }
170
250
 
@@ -175,42 +255,45 @@ export class BotFactory {
175
255
  */
176
256
  private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
177
257
  let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
178
- let tokenInstance: ContractInstanceWithAddress | undefined;
179
- const deployOpts: DeployOptions = {
180
- from: sender,
181
- contractAddressSalt: this.config.tokenSalt,
182
- universalDeploy: true,
183
- };
258
+ const salt = this.config.tokenSalt;
259
+ const deployOpts: DeployOptions = { from: sender };
184
260
  let token: TokenContract | PrivateTokenContract;
261
+ let instance: ContractInstanceWithAddress;
185
262
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
186
- deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
187
- tokenInstance = await deploy.getInstance(deployOpts);
188
- token = TokenContract.at(tokenInstance.address, this.wallet);
263
+ deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
264
+ instance = await deploy.getInstance();
265
+ token = TokenContract.at(instance.address, this.wallet);
189
266
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
190
267
  // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
191
268
  const tokenSecretKey = Fr.random();
192
269
  const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
193
- deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
270
+ deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
271
+ salt,
272
+ universalDeploy: true,
273
+ publicKeys: tokenPublicKeys,
274
+ });
194
275
  deployOpts.skipInstancePublication = true;
195
276
  deployOpts.skipClassPublication = true;
196
277
  deployOpts.skipInitialization = false;
197
278
 
198
279
  // Register the contract with the secret key before deployment
199
- tokenInstance = await deploy.getInstance(deployOpts);
200
- token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
201
- await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
280
+ instance = await deploy.getInstance();
281
+ token = PrivateTokenContract.at(instance.address, this.wallet);
282
+ await this.wallet.registerContract(instance, PrivateTokenContract.artifact, tokenSecretKey);
283
+ // The contract constructor initializes private storage vars that need the contract's own nullifier key.
284
+ deployOpts.additionalScopes = [instance.address];
202
285
  } else {
203
286
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
204
287
  }
205
288
 
206
- const address = tokenInstance?.address ?? (await deploy.getInstance(deployOpts)).address;
289
+ const address = instance.address;
207
290
  const metadata = await this.wallet.getContractMetadata(address);
208
291
  if (metadata.isContractPublished) {
209
292
  this.log.info(`Token at ${address.toString()} already deployed`);
210
293
  await deploy.register();
211
294
  } else {
212
295
  this.log.info(`Deploying token contract at ${address.toString()}`);
213
- const txHash = await deploy.send({ ...deployOpts, wait: NO_WAIT });
296
+ const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
214
297
  this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
215
298
  await this.withNoMinTxsPerBlock(async () => {
216
299
  await waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
@@ -227,31 +310,34 @@ export class BotFactory {
227
310
  */
228
311
  private async setupTokenContract(
229
312
  deployer: AztecAddress,
230
- contractAddressSalt: Fr,
313
+ salt: Fr,
231
314
  name: string,
232
315
  ticker: string,
233
316
  decimals = 18,
234
317
  ): Promise<TokenContract> {
235
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
236
- const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
318
+ const deployOpts: DeployOptions = { from: deployer };
319
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
237
320
  const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
238
321
  return TokenContract.at(instance.address, this.wallet);
239
322
  }
240
323
 
241
324
  private async setupAmmContract(
242
325
  deployer: AztecAddress,
243
- contractAddressSalt: Fr,
326
+ salt: Fr,
244
327
  token0: TokenContract,
245
328
  token1: TokenContract,
246
329
  lpToken: TokenContract,
247
330
  ): Promise<AMMContract> {
248
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
249
- const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
331
+ const deployOpts: DeployOptions = { from: deployer };
332
+ const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address, {
333
+ salt,
334
+ universalDeploy: true,
335
+ });
250
336
  const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
251
337
  const amm = AMMContract.at(instance.address, this.wallet);
252
338
 
253
339
  this.log.info(`AMM deployed at ${amm.address}`);
254
- const minterReceipt = await lpToken.methods
340
+ const { receipt: minterReceipt } = await lpToken.methods
255
341
  .set_minter(amm.address, true)
256
342
  .send({ from: deployer, wait: { timeout: this.config.txMinedWaitSeconds } });
257
343
  this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
@@ -270,9 +356,18 @@ export class BotFactory {
270
356
  ): Promise<void> {
271
357
  const getPrivateBalances = () =>
272
358
  Promise.all([
273
- token0.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
274
- token1.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
275
- lpToken.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
359
+ token0.methods
360
+ .balance_of_private(liquidityProvider)
361
+ .simulate({ from: liquidityProvider })
362
+ .then(r => r.result),
363
+ token1.methods
364
+ .balance_of_private(liquidityProvider)
365
+ .simulate({ from: liquidityProvider })
366
+ .then(r => r.result),
367
+ lpToken.methods
368
+ .balance_of_private(liquidityProvider)
369
+ .simulate({ from: liquidityProvider })
370
+ .then(r => r.result),
276
371
  ]);
277
372
 
278
373
  const authwitNonce = Fr.random();
@@ -313,14 +408,14 @@ export class BotFactory {
313
408
  .getFunctionCall(),
314
409
  });
315
410
 
316
- const mintReceipt = await new BatchCall(this.wallet, [
411
+ const { receipt: mintReceipt } = await new BatchCall(this.wallet, [
317
412
  token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
318
413
  token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
319
414
  ]).send({ from: liquidityProvider, wait: { timeout: this.config.txMinedWaitSeconds } });
320
415
 
321
416
  this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
322
417
 
323
- const addLiquidityReceipt = await amm.methods
418
+ const { receipt: addLiquidityReceipt } = await amm.methods
324
419
  .add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce)
325
420
  .send({
326
421
  from: liquidityProvider,
@@ -342,7 +437,7 @@ export class BotFactory {
342
437
  deploy: DeployMethod<T>,
343
438
  deployOpts: DeployOptions,
344
439
  ): Promise<ContractInstanceWithAddress> {
345
- const instance = await deploy.getInstance(deployOpts);
440
+ const instance = await deploy.getInstance();
346
441
  const address = instance.address;
347
442
  const metadata = await this.wallet.getContractMetadata(address);
348
443
  if (metadata.isContractPublished) {
@@ -351,7 +446,7 @@ export class BotFactory {
351
446
  } else {
352
447
  this.log.info(`Deploying contract ${name} at ${address.toString()}`);
353
448
  await this.withNoMinTxsPerBlock(async () => {
354
- const txHash = await deploy.send({ ...deployOpts, wait: NO_WAIT });
449
+ const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
355
450
  this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
356
451
  return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
357
452
  });
@@ -393,8 +488,14 @@ export class BotFactory {
393
488
  return;
394
489
  }
395
490
 
491
+ // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
492
+ const additionalScopes = isStandardToken ? undefined : [token.address];
396
493
  await this.withNoMinTxsPerBlock(async () => {
397
- const txHash = await new BatchCall(token.wallet, calls).send({ from: minter, wait: NO_WAIT });
494
+ const { txHash } = await new BatchCall(token.wallet, calls).send({
495
+ from: minter,
496
+ additionalScopes,
497
+ wait: NO_WAIT,
498
+ });
398
499
  this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
399
500
  return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
400
501
  });
@@ -417,7 +518,6 @@ export class BotFactory {
417
518
  await this.withNoMinTxsPerBlock(() =>
418
519
  waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
419
520
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
420
- forPublicConsumption: false,
421
521
  }),
422
522
  );
423
523
  return existingClaim.claim;
@@ -456,7 +556,6 @@ export class BotFactory {
456
556
  await this.withNoMinTxsPerBlock(() =>
457
557
  waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
458
558
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
459
- forPublicConsumption: false,
460
559
  }),
461
560
  );
462
561
 
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
@@ -4,12 +4,13 @@ import { omit } from '@aztec/foundation/collection';
4
4
  import { RunningPromise } from '@aztec/foundation/running-promise';
5
5
  import type { AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
6
6
  import { type TelemetryClient, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
7
- import type { TestWallet } from '@aztec/test-wallet/server';
7
+ import type { EmbeddedWallet } from '@aztec/wallets/embedded';
8
8
 
9
9
  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
 
@@ -24,7 +25,7 @@ export class BotRunner implements BotRunnerApi, Traceable {
24
25
 
25
26
  public constructor(
26
27
  private config: BotConfig,
27
- private readonly wallet: TestWallet,
28
+ private readonly wallet: EmbeddedWallet,
28
29
  private readonly aztecNode: AztecNode,
29
30
  private readonly telemetry: TelemetryClient,
30
31
  private readonly aztecNodeAdmin: AztecNodeAdmin | undefined,
@@ -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';