@aztec/bot 0.0.1-commit.fcb71a6 → 0.0.1-commit.ff7989d6c

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 (44) 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 +5 -1
  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 +14 -15
  7. package/dest/bot.d.ts +6 -6
  8. package/dest/bot.d.ts.map +1 -1
  9. package/dest/bot.js +7 -4
  10. package/dest/config.d.ts +37 -21
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +39 -11
  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 +140 -0
  16. package/dest/factory.d.ts +20 -10
  17. package/dest/factory.d.ts.map +1 -1
  18. package/dest/factory.js +162 -71
  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 +37 -6
  31. package/dest/store/index.d.ts +2 -2
  32. package/dest/store/index.d.ts.map +1 -1
  33. package/package.json +17 -14
  34. package/src/amm_bot.ts +7 -7
  35. package/src/base_bot.ts +13 -27
  36. package/src/bot.ts +9 -8
  37. package/src/config.ts +44 -15
  38. package/src/cross_chain_bot.ts +209 -0
  39. package/src/factory.ts +170 -56
  40. package/src/index.ts +1 -0
  41. package/src/l1_to_l2_seeding.ts +79 -0
  42. package/src/runner.ts +18 -5
  43. package/src/store/bot_store.ts +60 -5
  44. package/src/store/index.ts +1 -1
@@ -1,16 +1,21 @@
1
1
  import { Fr } from '@aztec/foundation/curves/bn254';
2
2
  import { createLogger } from '@aztec/foundation/log';
3
+ import { DateProvider } from '@aztec/foundation/timer';
3
4
  /**
4
5
  * Simple data store for the bot to persist L1 bridge claims.
5
6
  */ export class BotStore {
6
7
  store;
7
8
  log;
9
+ dateProvider;
8
10
  static SCHEMA_VERSION = 1;
9
11
  bridgeClaims;
10
- constructor(store, log = createLogger('bot:store')){
12
+ pendingL1ToL2;
13
+ constructor(store, log = createLogger('bot:store'), dateProvider = new DateProvider()){
11
14
  this.store = store;
12
15
  this.log = log;
16
+ this.dateProvider = dateProvider;
13
17
  this.bridgeClaims = store.openMap('bridge_claims');
18
+ this.pendingL1ToL2 = store.openMap('pending_l1_to_l2');
14
19
  }
15
20
  /**
16
21
  * Saves a bridge claim for a recipient.
@@ -25,7 +30,7 @@ import { createLogger } from '@aztec/foundation/log';
25
30
  };
26
31
  const data = {
27
32
  claim: serializableClaim,
28
- timestamp: Date.now(),
33
+ timestamp: this.dateProvider.now(),
29
34
  recipient: recipient.toString()
30
35
  };
31
36
  await this.bridgeClaims.set(recipient.toString(), JSON.stringify(data));
@@ -85,7 +90,7 @@ import { createLogger } from '@aztec/foundation/log';
85
90
  /**
86
91
  * Cleans up old bridge claims (older than 24 hours).
87
92
  */ async cleanupOldClaims(maxAgeMs = 24 * 60 * 60 * 1000) {
88
- const now = Date.now();
93
+ const now = this.dateProvider.now();
89
94
  let cleanedCount = 0;
90
95
  const entries = this.bridgeClaims.entriesAsync();
91
96
  for await (const [key, data] of entries){
@@ -98,9 +103,35 @@ import { createLogger } from '@aztec/foundation/log';
98
103
  }
99
104
  return cleanedCount;
100
105
  }
101
- /**
102
- * Closes the store.
103
- */ async close() {
106
+ /** Saves a pending L1→L2 message keyed by msgHash. */ async savePendingL1ToL2Message(msg) {
107
+ await this.pendingL1ToL2.set(msg.msgHash, JSON.stringify(msg));
108
+ this.log.info(`Saved pending L1→L2 message ${msg.msgHash}`);
109
+ }
110
+ /** Returns all unconsumed pending L1→L2 messages. */ async getUnconsumedL1ToL2Messages() {
111
+ const messages = [];
112
+ for await (const [_, data] of this.pendingL1ToL2.entriesAsync()){
113
+ messages.push(JSON.parse(data));
114
+ }
115
+ return messages;
116
+ }
117
+ /** Deletes a consumed L1→L2 message from the store. */ async deleteL1ToL2Message(msgHash) {
118
+ await this.pendingL1ToL2.delete(msgHash);
119
+ this.log.info(`Deleted consumed L1→L2 message ${msgHash}`);
120
+ }
121
+ /** Cleans up pending L1→L2 messages older than maxAgeMs. */ async cleanupOldPendingMessages(maxAgeMs = 24 * 60 * 60 * 1000) {
122
+ const now = this.dateProvider.now();
123
+ let cleanedCount = 0;
124
+ for await (const [key, data] of this.pendingL1ToL2.entriesAsync()){
125
+ const parsed = JSON.parse(data);
126
+ if (now - parsed.timestamp > maxAgeMs) {
127
+ await this.pendingL1ToL2.delete(key);
128
+ cleanedCount++;
129
+ this.log.info(`Cleaned up old pending L1→L2 message ${key}`);
130
+ }
131
+ }
132
+ return cleanedCount;
133
+ }
134
+ /** Closes the store. */ async close() {
104
135
  await this.store.close();
105
136
  this.log.info('Closed bot data store');
106
137
  }
@@ -1,2 +1,2 @@
1
- export { BotStore, type BridgeClaimData } from './bot_store.js';
2
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9zdG9yZS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUUsUUFBUSxFQUFFLEtBQUssZUFBZSxFQUFFLE1BQU0sZ0JBQWdCLENBQUMifQ==
1
+ export { BotStore, type BridgeClaimData, type PendingL1ToL2Message } from './bot_store.js';
2
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9zdG9yZS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUUsUUFBUSxFQUFFLEtBQUssZUFBZSxFQUFFLEtBQUssb0JBQW9CLEVBQUUsTUFBTSxnQkFBZ0IsQ0FBQyJ9
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/store/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,KAAK,eAAe,EAAE,MAAM,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/store/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,KAAK,eAAe,EAAE,KAAK,oBAAoB,EAAE,MAAM,gBAAgB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/bot",
3
- "version": "0.0.1-commit.fcb71a6",
3
+ "version": "0.0.1-commit.ff7989d6c",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./dest/index.js",
@@ -54,20 +54,23 @@
54
54
  ]
55
55
  },
56
56
  "dependencies": {
57
- "@aztec/accounts": "0.0.1-commit.fcb71a6",
58
- "@aztec/aztec.js": "0.0.1-commit.fcb71a6",
59
- "@aztec/entrypoints": "0.0.1-commit.fcb71a6",
60
- "@aztec/ethereum": "0.0.1-commit.fcb71a6",
61
- "@aztec/foundation": "0.0.1-commit.fcb71a6",
62
- "@aztec/kv-store": "0.0.1-commit.fcb71a6",
63
- "@aztec/noir-contracts.js": "0.0.1-commit.fcb71a6",
64
- "@aztec/noir-protocol-circuits-types": "0.0.1-commit.fcb71a6",
65
- "@aztec/protocol-contracts": "0.0.1-commit.fcb71a6",
66
- "@aztec/stdlib": "0.0.1-commit.fcb71a6",
67
- "@aztec/telemetry-client": "0.0.1-commit.fcb71a6",
68
- "@aztec/test-wallet": "0.0.1-commit.fcb71a6",
57
+ "@aztec/accounts": "0.0.1-commit.ff7989d6c",
58
+ "@aztec/aztec.js": "0.0.1-commit.ff7989d6c",
59
+ "@aztec/entrypoints": "0.0.1-commit.ff7989d6c",
60
+ "@aztec/ethereum": "0.0.1-commit.ff7989d6c",
61
+ "@aztec/foundation": "0.0.1-commit.ff7989d6c",
62
+ "@aztec/kv-store": "0.0.1-commit.ff7989d6c",
63
+ "@aztec/l1-artifacts": "0.0.1-commit.ff7989d6c",
64
+ "@aztec/noir-contracts.js": "0.0.1-commit.ff7989d6c",
65
+ "@aztec/noir-protocol-circuits-types": "0.0.1-commit.ff7989d6c",
66
+ "@aztec/noir-test-contracts.js": "0.0.1-commit.ff7989d6c",
67
+ "@aztec/protocol-contracts": "0.0.1-commit.ff7989d6c",
68
+ "@aztec/stdlib": "0.0.1-commit.ff7989d6c",
69
+ "@aztec/telemetry-client": "0.0.1-commit.ff7989d6c",
70
+ "@aztec/wallets": "0.0.1-commit.ff7989d6c",
69
71
  "source-map-support": "^0.5.21",
70
72
  "tslib": "^2.4.0",
73
+ "viem": "npm:@aztec/viem@2.38.2",
71
74
  "zod": "^3.23.8"
72
75
  },
73
76
  "devDependencies": {
@@ -75,7 +78,7 @@
75
78
  "@types/jest": "^30.0.0",
76
79
  "@types/node": "^22.15.17",
77
80
  "@types/source-map-support": "^0.5.10",
78
- "@typescript/native-preview": "7.0.0-dev.20251126.1",
81
+ "@typescript/native-preview": "7.0.0-dev.20260113.1",
79
82
  "jest": "^30.0.0",
80
83
  "jest-mock-extended": "^4.0.0",
81
84
  "ts-node": "^10.9.1",
package/src/amm_bot.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { AztecAddress } from '@aztec/aztec.js/addresses';
2
- import { SentTx } from '@aztec/aztec.js/contracts';
2
+ import { NO_WAIT } from '@aztec/aztec.js/contracts';
3
3
  import { Fr } from '@aztec/aztec.js/fields';
4
- import { TxReceipt } from '@aztec/aztec.js/tx';
4
+ import { TxHash, TxReceipt } from '@aztec/aztec.js/tx';
5
5
  import { jsonStringify } from '@aztec/foundation/json-rpc';
6
6
  import type { AMMContract } from '@aztec/noir-contracts.js/AMM';
7
7
  import type { TokenContract } from '@aztec/noir-contracts.js/Token';
8
8
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
9
- import type { TestWallet } from '@aztec/test-wallet/server';
9
+ import type { EmbeddedWallet } from '@aztec/wallets/embedded';
10
10
 
11
11
  import { BaseBot } from './base_bot.js';
12
12
  import type { BotConfig } from './config.js';
@@ -21,7 +21,7 @@ type Balances = { token0: bigint; token1: bigint };
21
21
  export class AmmBot extends BaseBot {
22
22
  protected constructor(
23
23
  node: AztecNode,
24
- wallet: TestWallet,
24
+ wallet: EmbeddedWallet,
25
25
  defaultAccountAddress: AztecAddress,
26
26
  public readonly amm: AMMContract,
27
27
  public readonly token0: TokenContract,
@@ -33,7 +33,7 @@ export class AmmBot extends BaseBot {
33
33
 
34
34
  static async create(
35
35
  config: BotConfig,
36
- wallet: TestWallet,
36
+ wallet: EmbeddedWallet,
37
37
  aztecNode: AztecNode,
38
38
  aztecNodeAdmin: AztecNodeAdmin | undefined,
39
39
  store: BotStore,
@@ -48,7 +48,7 @@ export class AmmBot extends BaseBot {
48
48
  return new AmmBot(aztecNode, wallet, defaultAccountAddress, amm, token0, token1, config);
49
49
  }
50
50
 
51
- protected async createAndSendTx(logCtx: object): Promise<SentTx> {
51
+ protected async createAndSendTx(logCtx: object): Promise<TxHash> {
52
52
  const { feePaymentMethod } = this.config;
53
53
  const { wallet, amm, token0, token1 } = this;
54
54
 
@@ -89,7 +89,7 @@ export class AmmBot extends BaseBot {
89
89
 
90
90
  this.log.verbose(`Sending transaction`, logCtx);
91
91
  this.log.info(`Tx. Balances: ${jsonStringify(balances)}`, { ...logCtx, balances });
92
- return swapExactTokensInteraction.send(opts);
92
+ return swapExactTokensInteraction.send({ ...opts, wait: NO_WAIT });
93
93
  }
94
94
 
95
95
  protected override async onTxMined(receipt: TxReceipt, logCtx: object): Promise<void> {
package/src/base_bot.ts CHANGED
@@ -1,16 +1,11 @@
1
1
  import { AztecAddress } from '@aztec/aztec.js/addresses';
2
- import {
3
- BatchCall,
4
- ContractFunctionInteraction,
5
- type SendInteractionOptions,
6
- SentTx,
7
- waitForProven,
8
- } from '@aztec/aztec.js/contracts';
2
+ import { BatchCall, ContractFunctionInteraction, type SendInteractionOptions } from '@aztec/aztec.js/contracts';
9
3
  import { createLogger } from '@aztec/aztec.js/log';
10
- import { TxHash, TxReceipt } from '@aztec/aztec.js/tx';
4
+ import { waitForTx } from '@aztec/aztec.js/node';
5
+ import { TxHash, TxReceipt, TxStatus } from '@aztec/aztec.js/tx';
11
6
  import { Gas } from '@aztec/stdlib/gas';
12
7
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
13
- import type { TestWallet } from '@aztec/test-wallet/server';
8
+ import type { EmbeddedWallet } from '@aztec/wallets/embedded';
14
9
 
15
10
  import type { BotConfig } from './config.js';
16
11
 
@@ -22,36 +17,27 @@ export abstract class BaseBot {
22
17
 
23
18
  protected constructor(
24
19
  public readonly node: AztecNode,
25
- public readonly wallet: TestWallet,
20
+ public readonly wallet: EmbeddedWallet,
26
21
  public readonly defaultAccountAddress: AztecAddress,
27
22
  public config: BotConfig,
28
23
  ) {}
29
24
 
30
25
  public async run(): Promise<TxReceipt | TxHash> {
31
26
  this.attempts++;
32
- const logCtx = { runId: Date.now() * 1000 + Math.floor(Math.random() * 1000) };
33
27
  const { followChain, txMinedWaitSeconds } = this.config;
28
+ const logCtx = { runId: Date.now() * 1000 + Math.floor(Math.random() * 1000), followChain, txMinedWaitSeconds };
34
29
 
35
30
  this.log.verbose(`Creating tx`, logCtx);
36
- const tx = await this.createAndSendTx(logCtx);
37
-
38
- const txHash = await tx.getTxHash();
31
+ const txHash = await this.createAndSendTx(logCtx);
39
32
 
40
33
  if (followChain === 'NONE') {
41
34
  this.log.info(`Transaction ${txHash.toString()} sent, not waiting for it to be mined`);
42
35
  return txHash;
43
36
  }
44
37
 
45
- this.log.verbose(
46
- `Awaiting tx ${txHash.toString()} to be on the ${followChain} chain (timeout ${txMinedWaitSeconds}s)`,
47
- logCtx,
48
- );
49
- const receipt = await tx.wait({
50
- timeout: txMinedWaitSeconds,
51
- });
52
- if (followChain === 'PROVEN') {
53
- await waitForProven(this.node, receipt, { provenTimeout: txMinedWaitSeconds });
54
- }
38
+ const waitForStatus = TxStatus[followChain];
39
+ this.log.verbose(`Awaiting tx ${txHash.toString()} to be on the ${followChain} chain`, logCtx);
40
+ const receipt = await waitForTx(this.node, txHash, { timeout: txMinedWaitSeconds, waitForStatus });
55
41
  this.successes++;
56
42
  this.log.info(
57
43
  `Tx #${this.attempts} ${receipt.txHash} successfully mined in block ${receipt.blockNumber} (stats: ${this.successes}/${this.attempts} success)`,
@@ -63,7 +49,7 @@ export abstract class BaseBot {
63
49
  return receipt;
64
50
  }
65
51
 
66
- protected abstract createAndSendTx(logCtx: object): Promise<SentTx>;
52
+ protected abstract createAndSendTx(logCtx: object): Promise<TxHash>;
67
53
 
68
54
  protected onTxMined(_receipt: TxReceipt, _logCtx: object): Promise<void> {
69
55
  // no-op
@@ -73,9 +59,9 @@ export abstract class BaseBot {
73
59
  protected async getSendMethodOpts(
74
60
  interaction: ContractFunctionInteraction | BatchCall,
75
61
  ): Promise<SendInteractionOptions> {
76
- const { l2GasLimit, daGasLimit, baseFeePadding } = this.config;
62
+ const { l2GasLimit, daGasLimit, minFeePadding } = this.config;
77
63
 
78
- this.wallet.setBaseFeePadding(baseFeePadding);
64
+ this.wallet.setMinFeePadding(minFeePadding);
79
65
 
80
66
  let gasSettings;
81
67
  if (l2GasLimit !== undefined && l2GasLimit > 0 && daGasLimit !== undefined && daGasLimit > 0) {
package/src/bot.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import type { AztecAddress } from '@aztec/aztec.js/addresses';
2
- import { BatchCall, SentTx } from '@aztec/aztec.js/contracts';
2
+ import { BatchCall, NO_WAIT } from '@aztec/aztec.js/contracts';
3
+ import { TxHash } from '@aztec/aztec.js/tx';
3
4
  import { times } from '@aztec/foundation/collection';
4
5
  import type { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
5
6
  import type { TokenContract } from '@aztec/noir-contracts.js/Token';
6
7
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
7
- import type { TestWallet } from '@aztec/test-wallet/server';
8
+ import type { EmbeddedWallet } from '@aztec/wallets/embedded';
8
9
 
9
10
  import { BaseBot } from './base_bot.js';
10
11
  import type { BotConfig } from './config.js';
@@ -17,7 +18,7 @@ const TRANSFER_AMOUNT = 1;
17
18
  export class Bot extends BaseBot {
18
19
  protected constructor(
19
20
  node: AztecNode,
20
- wallet: TestWallet,
21
+ wallet: EmbeddedWallet,
21
22
  defaultAccountAddress: AztecAddress,
22
23
  public readonly token: TokenContract | PrivateTokenContract,
23
24
  public readonly recipient: AztecAddress,
@@ -28,7 +29,7 @@ export class Bot extends BaseBot {
28
29
 
29
30
  static async create(
30
31
  config: BotConfig,
31
- wallet: TestWallet,
32
+ wallet: EmbeddedWallet,
32
33
  aztecNode: AztecNode,
33
34
  aztecNodeAdmin: AztecNodeAdmin | undefined,
34
35
  store: BotStore,
@@ -48,7 +49,7 @@ export class Bot extends BaseBot {
48
49
  this.config = { ...this.config, ...config };
49
50
  }
50
51
 
51
- protected async createAndSendTx(logCtx: object): Promise<SentTx> {
52
+ protected async createAndSendTx(logCtx: object): Promise<TxHash> {
52
53
  const { privateTransfersPerTx, publicTransfersPerTx, feePaymentMethod } = this.config;
53
54
  const { token, recipient, wallet } = this;
54
55
 
@@ -75,14 +76,14 @@ export class Bot extends BaseBot {
75
76
  await batch.simulate({ from: this.defaultAccountAddress });
76
77
 
77
78
  this.log.verbose(`Sending transaction`, logCtx);
78
- return batch.send(opts);
79
+ return batch.send({ ...opts, wait: NO_WAIT });
79
80
  }
80
81
 
81
82
  public async getBalances() {
82
83
  if (isStandardTokenContract(this.token)) {
83
84
  return {
84
85
  sender: await getBalances(this.token, this.defaultAccountAddress),
85
- recipient: await getBalances(this.token, this.recipient, this.defaultAccountAddress),
86
+ recipient: await getBalances(this.token, this.recipient),
86
87
  };
87
88
  } else {
88
89
  return {
@@ -91,7 +92,7 @@ export class Bot extends BaseBot {
91
92
  publicBalance: 0n,
92
93
  },
93
94
  recipient: {
94
- privateBalance: await getPrivateBalance(this.token, this.recipient, this.defaultAccountAddress),
95
+ privateBalance: await getPrivateBalance(this.token, this.recipient),
95
96
  publicBalance: 0n,
96
97
  },
97
98
  };
package/src/config.ts CHANGED
@@ -19,9 +19,12 @@ 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. */
@@ -76,8 +79,12 @@ 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
90
  export const BotConfigSchema = zodFor<BotConfig>()(
@@ -96,7 +103,7 @@ export const BotConfigSchema = zodFor<BotConfig>()(
96
103
  privateTransfersPerTx: z.number().int().nonnegative(),
97
104
  publicTransfersPerTx: z.number().int().nonnegative(),
98
105
  feePaymentMethod: z.literal('fee_juice'),
99
- baseFeePadding: z.number().int().nonnegative(),
106
+ minFeePadding: z.number().int().nonnegative(),
100
107
  noStart: z.boolean(),
101
108
  txMinedWaitSeconds: z.number(),
102
109
  followChain: z.enum(BotFollowChain),
@@ -107,7 +114,9 @@ export const BotConfigSchema = zodFor<BotConfig>()(
107
114
  contract: z.nativeEnum(SupportedTokenContracts),
108
115
  maxConsecutiveErrors: z.number().int().nonnegative(),
109
116
  stopWhenUnhealthy: z.boolean(),
110
- ammTxs: z.boolean().default(false),
117
+ botMode: z.enum(BotMode).default('transfer'),
118
+ l2ToL1MessagesPerTx: z.number().int().nonnegative().default(1),
119
+ l1ToL2SeedCount: z.number().int().nonnegative().default(1),
111
120
  dataDirectory: z.string().optional(),
112
121
  dataStoreMapSizeKb: z.number().optional(),
113
122
  })
@@ -193,8 +202,8 @@ export const botConfigMappings: ConfigMappingsType<BotConfig> = {
193
202
  parseEnv: val => (val as 'fee_juice') || undefined,
194
203
  defaultValue: 'fee_juice',
195
204
  },
196
- baseFeePadding: {
197
- env: 'BOT_BASE_FEE_PADDING',
205
+ minFeePadding: {
206
+ env: 'BOT_MIN_FEE_PADDING',
198
207
  description: 'How much is the bot willing to overpay vs. the current base fee',
199
208
  ...numberConfigHelper(3),
200
209
  },
@@ -213,10 +222,14 @@ export const botConfigMappings: ConfigMappingsType<BotConfig> = {
213
222
  description: 'Which chain the bot follows',
214
223
  defaultValue: 'NONE',
215
224
  parseEnv(val) {
216
- if (!(BotFollowChain as readonly string[]).includes(val.toUpperCase())) {
225
+ const upper = val.toUpperCase();
226
+ if (upper === 'PENDING') {
227
+ return 'CHECKPOINTED';
228
+ }
229
+ if (!(BotFollowChain as readonly string[]).includes(upper)) {
217
230
  throw new Error(`Invalid value for BOT_FOLLOW_CHAIN: ${val}`);
218
231
  }
219
- return val as BotFollowChain;
232
+ return upper as BotFollowChain;
220
233
  },
221
234
  },
222
235
  maxPendingTxs: {
@@ -264,10 +277,26 @@ export const botConfigMappings: ConfigMappingsType<BotConfig> = {
264
277
  description: 'Stops the bot if service becomes unhealthy',
265
278
  ...booleanConfigHelper(false),
266
279
  },
267
- ammTxs: {
268
- env: 'BOT_AMM_TXS',
269
- description: 'Deploy an AMM and send swaps to it',
270
- ...booleanConfigHelper(false),
280
+ botMode: {
281
+ env: 'BOT_MODE',
282
+ description: 'Bot mode: transfer, amm, or crosschain',
283
+ defaultValue: 'transfer' as BotMode,
284
+ parseEnv(val: string) {
285
+ if (!(BotMode as readonly string[]).includes(val)) {
286
+ throw new Error(`Invalid value for BOT_MODE: ${val}`);
287
+ }
288
+ return val as BotMode;
289
+ },
290
+ },
291
+ l2ToL1MessagesPerTx: {
292
+ env: 'BOT_L2_TO_L1_MESSAGES_PER_TX',
293
+ description: 'Number of L2→L1 messages per tx (crosschain mode)',
294
+ ...numberConfigHelper(1),
295
+ },
296
+ l1ToL2SeedCount: {
297
+ env: 'BOT_L1_TO_L2_SEED_COUNT',
298
+ description: 'Max L1→L2 messages to keep in-flight (crosschain mode)',
299
+ ...numberConfigHelper(1),
271
300
  },
272
301
  ...pickConfigMappings(dataConfigMappings, ['dataStoreMapSizeKb', 'dataDirectory']),
273
302
  };
@@ -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
+ }