@aztec/bot 0.0.1-commit.5476d83 → 0.0.1-commit.5914bae

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 +42 -27
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +45 -17
  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 -10
  17. package/dest/factory.d.ts.map +1 -1
  18. package/dest/factory.js +178 -87
  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 -63
  39. package/src/cross_chain_bot.ts +203 -0
  40. package/src/factory.ts +202 -68
  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
@@ -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
+ }
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,
@@ -7,24 +7,34 @@ import {
7
7
  ContractFunctionInteraction,
8
8
  type DeployMethod,
9
9
  type DeployOptions,
10
+ NO_WAIT,
10
11
  } from '@aztec/aztec.js/contracts';
11
- import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
12
12
  import type { L2AmountClaim } from '@aztec/aztec.js/ethereum';
13
+ import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
13
14
  import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
15
+ import { deriveKeys } from '@aztec/aztec.js/keys';
14
16
  import { createLogger } from '@aztec/aztec.js/log';
15
17
  import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
16
- import { createEthereumChain, createExtendedL1Client } from '@aztec/ethereum';
17
- import { Fr } from '@aztec/foundation/fields';
18
+ import { waitForTx } from '@aztec/aztec.js/node';
19
+ import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
20
+ import { createEthereumChain } from '@aztec/ethereum/chain';
21
+ import { createExtendedL1Client } from '@aztec/ethereum/client';
22
+ import { RollupContract } from '@aztec/ethereum/contracts';
23
+ import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
24
+ import { Fr } from '@aztec/foundation/curves/bn254';
25
+ import { EthAddress } from '@aztec/foundation/eth-address';
18
26
  import { Timer } from '@aztec/foundation/timer';
19
27
  import { AMMContract } from '@aztec/noir-contracts.js/AMM';
20
28
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
21
29
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
22
- import { GasSettings } from '@aztec/stdlib/gas';
30
+ import { TestContract } from '@aztec/noir-test-contracts.js/Test';
31
+ import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
23
32
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
24
33
  import { deriveSigningKey } from '@aztec/stdlib/keys';
25
- import { TestWallet } from '@aztec/test-wallet/server';
34
+ import { EmbeddedWallet } from '@aztec/wallets/embedded';
26
35
 
27
36
  import { type BotConfig, SupportedTokenContracts } from './config.js';
37
+ import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
28
38
  import type { BotStore } from './store/index.js';
29
39
  import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
30
40
 
@@ -36,32 +46,36 @@ export class BotFactory {
36
46
 
37
47
  constructor(
38
48
  private readonly config: BotConfig,
39
- private readonly wallet: TestWallet,
49
+ private readonly wallet: EmbeddedWallet,
40
50
  private readonly store: BotStore,
41
51
  private readonly aztecNode: AztecNode,
42
52
  private readonly aztecNodeAdmin?: AztecNodeAdmin,
43
- ) {}
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
+ }
44
58
 
45
59
  /**
46
60
  * Initializes a new bot by setting up the sender account, registering the recipient,
47
61
  * deploying the token contract, and minting tokens if necessary.
48
62
  */
49
63
  public async setup(): Promise<{
50
- wallet: TestWallet;
64
+ wallet: EmbeddedWallet;
51
65
  defaultAccountAddress: AztecAddress;
52
66
  token: TokenContract | PrivateTokenContract;
53
67
  node: AztecNode;
54
68
  recipient: AztecAddress;
55
69
  }> {
56
- const recipient = (await this.wallet.createAccount()).address;
57
70
  const defaultAccountAddress = await this.setupAccount();
71
+ const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
58
72
  const token = await this.setupToken(defaultAccountAddress);
59
73
  await this.mintTokens(token, defaultAccountAddress);
60
74
  return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
61
75
  }
62
76
 
63
77
  public async setupAmm(): Promise<{
64
- wallet: TestWallet;
78
+ wallet: EmbeddedWallet;
65
79
  defaultAccountAddress: AztecAddress;
66
80
  amm: AMMContract;
67
81
  token0: TokenContract;
@@ -91,6 +105,89 @@ export class BotFactory {
91
105
  return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
92
106
  }
93
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 = {
182
+ from: deployer,
183
+ contractAddressSalt: this.config.tokenSalt,
184
+ universalDeploy: true,
185
+ };
186
+ const deploy = TestContract.deploy(this.wallet);
187
+ const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
188
+ return TestContract.at(instance.address, this.wallet);
189
+ }
190
+
94
191
  /**
95
192
  * Checks if the sender account contract is initialized, and initializes it if necessary.
96
193
  * @returns The sender wallet.
@@ -109,14 +206,9 @@ export class BotFactory {
109
206
  private async setupAccountWithPrivateKey(secret: Fr) {
110
207
  const salt = this.config.senderSalt ?? Fr.ONE;
111
208
  const signingKey = deriveSigningKey(secret);
112
- const accountData = {
113
- secret,
114
- salt,
115
- contract: new SchnorrAccountContract(signingKey!),
116
- };
117
- const accountManager = await this.wallet.createAccount(accountData);
118
- const isInit = (await this.wallet.getContractMetadata(accountManager.address)).isContractInitialized;
119
- if (isInit) {
209
+ const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
210
+ const metadata = await this.wallet.getContractMetadata(accountManager.address);
211
+ if (metadata.initializationStatus === ContractInitializationStatus.INITIALIZED) {
120
212
  this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
121
213
  const timer = new Timer();
122
214
  const address = accountManager.address;
@@ -131,12 +223,16 @@ export class BotFactory {
131
223
 
132
224
  const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
133
225
  const deployMethod = await accountManager.getDeployMethod();
134
- const maxFeesPerGas = (await this.aztecNode.getCurrentBaseFees()).mul(1 + this.config.baseFeePadding);
135
- const gasSettings = GasSettings.default({ maxFeesPerGas });
136
- const sentTx = deployMethod.send({ from: AztecAddress.ZERO, fee: { gasSettings, paymentMethod } });
137
- const txHash = await sentTx.getTxHash();
138
- this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
139
- await this.withNoMinTxsPerBlock(() => sentTx.wait({ timeout: this.config.txMinedWaitSeconds }));
226
+
227
+ await this.withNoMinTxsPerBlock(async () => {
228
+ const { txHash } = await deployMethod.send({
229
+ from: NO_FROM,
230
+ fee: { paymentMethod },
231
+ wait: NO_WAIT,
232
+ });
233
+ this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
234
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
235
+ });
140
236
  this.log.info(`Account deployed at ${address}`);
141
237
 
142
238
  // Clean up the consumed bridge claim
@@ -148,12 +244,11 @@ export class BotFactory {
148
244
 
149
245
  private async setupTestAccount() {
150
246
  const [initialAccountData] = await getInitialTestAccountsData();
151
- const accountData = {
152
- secret: initialAccountData.secret,
153
- salt: initialAccountData.salt,
154
- contract: new SchnorrAccountContract(initialAccountData.signingKey),
155
- };
156
- const accountManager = await this.wallet.createAccount(accountData);
247
+ const accountManager = await this.wallet.createSchnorrAccount(
248
+ initialAccountData.secret,
249
+ initialAccountData.salt,
250
+ initialAccountData.signingKey,
251
+ );
157
252
  return accountManager.address;
158
253
  }
159
254
 
@@ -164,33 +259,51 @@ export class BotFactory {
164
259
  */
165
260
  private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
166
261
  let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
262
+ let tokenInstance: ContractInstanceWithAddress | undefined;
167
263
  const deployOpts: DeployOptions = {
168
264
  from: sender,
169
265
  contractAddressSalt: this.config.tokenSalt,
170
266
  universalDeploy: true,
171
267
  };
268
+ let token: TokenContract | PrivateTokenContract;
172
269
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
173
270
  deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
271
+ tokenInstance = await deploy.getInstance(deployOpts);
272
+ token = TokenContract.at(tokenInstance.address, this.wallet);
174
273
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
175
- deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender);
274
+ // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
275
+ const tokenSecretKey = Fr.random();
276
+ const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
277
+ deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
176
278
  deployOpts.skipInstancePublication = true;
177
279
  deployOpts.skipClassPublication = true;
178
280
  deployOpts.skipInitialization = false;
281
+
282
+ // Register the contract with the secret key before deployment
283
+ tokenInstance = await deploy.getInstance(deployOpts);
284
+ token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
285
+ await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
286
+ // The contract constructor initializes private storage vars that need the contract's own nullifier key.
287
+ deployOpts.additionalScopes = [tokenInstance.address];
179
288
  } else {
180
289
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
181
290
  }
182
291
 
183
- const address = (await deploy.getInstance(deployOpts)).address;
184
- if ((await this.wallet.getContractMetadata(address)).isContractPublished) {
292
+ const address = tokenInstance?.address ?? (await deploy.getInstance(deployOpts)).address;
293
+ const metadata = await this.wallet.getContractMetadata(address);
294
+ if (metadata.isContractPublished) {
185
295
  this.log.info(`Token at ${address.toString()} already deployed`);
186
- return deploy.register();
296
+ await deploy.register();
187
297
  } else {
188
298
  this.log.info(`Deploying token contract at ${address.toString()}`);
189
- const sentTx = deploy.send(deployOpts);
190
- const txHash = await sentTx.getTxHash();
299
+ const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
191
300
  this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
192
- return this.withNoMinTxsPerBlock(() => sentTx.deployed({ timeout: this.config.txMinedWaitSeconds }));
301
+ await this.withNoMinTxsPerBlock(async () => {
302
+ await waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
303
+ return token;
304
+ });
193
305
  }
306
+ return token;
194
307
  }
195
308
 
196
309
  /**
@@ -198,7 +311,7 @@ export class BotFactory {
198
311
  * @param wallet - Wallet to deploy the token contract from.
199
312
  * @returns The TokenContract instance.
200
313
  */
201
- private setupTokenContract(
314
+ private async setupTokenContract(
202
315
  deployer: AztecAddress,
203
316
  contractAddressSalt: Fr,
204
317
  name: string,
@@ -207,7 +320,8 @@ export class BotFactory {
207
320
  ): Promise<TokenContract> {
208
321
  const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
209
322
  const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
210
- return this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
323
+ const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
324
+ return TokenContract.at(instance.address, this.wallet);
211
325
  }
212
326
 
213
327
  private async setupAmmContract(
@@ -219,12 +333,14 @@ export class BotFactory {
219
333
  ): Promise<AMMContract> {
220
334
  const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
221
335
  const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
222
- const amm = await this.registerOrDeployContract('AMM', deploy, deployOpts);
336
+ const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
337
+ const amm = AMMContract.at(instance.address, this.wallet);
223
338
 
224
339
  this.log.info(`AMM deployed at ${amm.address}`);
225
- const minterTx = lpToken.methods.set_minter(amm.address, true).send({ from: deployer });
226
- this.log.info(`Set LP token minter to AMM txHash=${(await minterTx.getTxHash()).toString()}`);
227
- await minterTx.wait({ timeout: this.config.txMinedWaitSeconds });
340
+ const { receipt: minterReceipt } = await lpToken.methods
341
+ .set_minter(amm.address, true)
342
+ .send({ from: deployer, wait: { timeout: this.config.txMinedWaitSeconds } });
343
+ this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
228
344
  this.log.info(`Liquidity token initialized`);
229
345
 
230
346
  return amm;
@@ -240,9 +356,18 @@ export class BotFactory {
240
356
  ): Promise<void> {
241
357
  const getPrivateBalances = () =>
242
358
  Promise.all([
243
- token0.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
244
- token1.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
245
- 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),
246
371
  ]);
247
372
 
248
373
  const authwitNonce = Fr.random();
@@ -283,23 +408,22 @@ export class BotFactory {
283
408
  .getFunctionCall(),
284
409
  });
285
410
 
286
- const mintTx = new BatchCall(this.wallet, [
411
+ const { receipt: mintReceipt } = await new BatchCall(this.wallet, [
287
412
  token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
288
413
  token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
289
- ]).send({ from: liquidityProvider });
414
+ ]).send({ from: liquidityProvider, wait: { timeout: this.config.txMinedWaitSeconds } });
290
415
 
291
- this.log.info(`Sent mint tx: ${(await mintTx.getTxHash()).toString()}`);
292
- await mintTx.wait({ timeout: this.config.txMinedWaitSeconds });
416
+ this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
293
417
 
294
- const addLiquidityTx = amm.methods
418
+ const { receipt: addLiquidityReceipt } = await amm.methods
295
419
  .add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce)
296
420
  .send({
297
421
  from: liquidityProvider,
298
422
  authWitnesses: [token0Authwit, token1Authwit],
423
+ wait: { timeout: this.config.txMinedWaitSeconds },
299
424
  });
300
425
 
301
- this.log.info(`Sent tx to add liquidity to the AMM: ${(await addLiquidityTx.getTxHash()).toString()}`);
302
- await addLiquidityTx.wait({ timeout: this.config.txMinedWaitSeconds });
426
+ this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`);
303
427
  this.log.info(`Liquidity added`);
304
428
 
305
429
  const [newT0Bal, newT1Bal, newLPBal] = await getPrivateBalances();
@@ -312,18 +436,22 @@ export class BotFactory {
312
436
  name: string,
313
437
  deploy: DeployMethod<T>,
314
438
  deployOpts: DeployOptions,
315
- ): Promise<T> {
316
- const address = (await deploy.getInstance(deployOpts)).address;
317
- if ((await this.wallet.getContractMetadata(address)).isContractPublished) {
439
+ ): Promise<ContractInstanceWithAddress> {
440
+ const instance = await deploy.getInstance(deployOpts);
441
+ const address = instance.address;
442
+ const metadata = await this.wallet.getContractMetadata(address);
443
+ if (metadata.isContractPublished) {
318
444
  this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
319
- return deploy.register();
445
+ await deploy.register();
320
446
  } else {
321
447
  this.log.info(`Deploying contract ${name} at ${address.toString()}`);
322
- const sentTx = deploy.send(deployOpts);
323
- const txHash = await sentTx.getTxHash();
324
- this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
325
- return this.withNoMinTxsPerBlock(() => sentTx.deployed({ timeout: this.config.txMinedWaitSeconds }));
448
+ await this.withNoMinTxsPerBlock(async () => {
449
+ const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
450
+ this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
451
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
452
+ });
326
453
  }
454
+ return instance;
327
455
  }
328
456
 
329
457
  /**
@@ -359,10 +487,18 @@ export class BotFactory {
359
487
  this.log.info(`Skipping minting as ${minter.toString()} has enough tokens`);
360
488
  return;
361
489
  }
362
- const sentTx = new BatchCall(token.wallet, calls).send({ from: minter });
363
- const txHash = await sentTx.getTxHash();
364
- this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
365
- await this.withNoMinTxsPerBlock(() => sentTx.wait({ timeout: this.config.txMinedWaitSeconds }));
490
+
491
+ // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
492
+ const additionalScopes = isStandardToken ? undefined : [token.address];
493
+ await this.withNoMinTxsPerBlock(async () => {
494
+ const { txHash } = await new BatchCall(token.wallet, calls).send({
495
+ from: minter,
496
+ additionalScopes,
497
+ wait: NO_WAIT,
498
+ });
499
+ this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
500
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
501
+ });
366
502
  }
367
503
 
368
504
  /**
@@ -382,7 +518,6 @@ export class BotFactory {
382
518
  await this.withNoMinTxsPerBlock(() =>
383
519
  waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
384
520
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
385
- forPublicConsumption: false,
386
521
  }),
387
522
  );
388
523
  return existingClaim.claim;
@@ -421,7 +556,6 @@ export class BotFactory {
421
556
  await this.withNoMinTxsPerBlock(() =>
422
557
  waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
423
558
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
424
- forPublicConsumption: false,
425
559
  }),
426
560
  );
427
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 {