@aztec/bot 0.0.1-fake-ceab37513c → 0.0.2-commit.217f559981

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 (54) hide show
  1. package/dest/amm_bot.d.ts +9 -10
  2. package/dest/amm_bot.d.ts.map +1 -1
  3. package/dest/amm_bot.js +27 -20
  4. package/dest/base_bot.d.ts +12 -9
  5. package/dest/base_bot.d.ts.map +1 -1
  6. package/dest/base_bot.js +28 -29
  7. package/dest/bot.d.ts +9 -10
  8. package/dest/bot.d.ts.map +1 -1
  9. package/dest/bot.js +12 -10
  10. package/dest/config.d.ts +82 -63
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +61 -31
  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 +27 -34
  17. package/dest/factory.d.ts.map +1 -1
  18. package/dest/factory.js +271 -151
  19. package/dest/index.d.ts +3 -1
  20. package/dest/index.d.ts.map +1 -1
  21. package/dest/index.js +2 -0
  22. package/dest/interface.d.ts +2 -2
  23. package/dest/interface.d.ts.map +1 -1
  24. package/dest/interface.js +1 -1
  25. package/dest/l1_to_l2_seeding.d.ts +8 -0
  26. package/dest/l1_to_l2_seeding.d.ts.map +1 -0
  27. package/dest/l1_to_l2_seeding.js +63 -0
  28. package/dest/rpc.d.ts +1 -1
  29. package/dest/runner.d.ts +12 -13
  30. package/dest/runner.d.ts.map +1 -1
  31. package/dest/runner.js +445 -61
  32. package/dest/store/bot_store.d.ts +69 -0
  33. package/dest/store/bot_store.d.ts.map +1 -0
  34. package/dest/store/bot_store.js +138 -0
  35. package/dest/store/index.d.ts +2 -0
  36. package/dest/store/index.d.ts.map +1 -0
  37. package/dest/store/index.js +1 -0
  38. package/dest/utils.d.ts +4 -4
  39. package/dest/utils.d.ts.map +1 -1
  40. package/dest/utils.js +5 -5
  41. package/package.json +19 -13
  42. package/src/amm_bot.ts +40 -32
  43. package/src/base_bot.ts +27 -39
  44. package/src/bot.ts +25 -13
  45. package/src/config.ts +101 -72
  46. package/src/cross_chain_bot.ts +209 -0
  47. package/src/factory.ts +313 -177
  48. package/src/index.ts +2 -0
  49. package/src/interface.ts +1 -1
  50. package/src/l1_to_l2_seeding.ts +79 -0
  51. package/src/runner.ts +33 -24
  52. package/src/store/bot_store.ts +196 -0
  53. package/src/store/index.ts +1 -0
  54. package/src/utils.ts +10 -5
package/src/factory.ts CHANGED
@@ -1,122 +1,191 @@
1
- import { getSchnorrAccount } from '@aztec/accounts/schnorr';
2
- import { getDeployedTestAccountsWallets, getInitialTestAccounts } from '@aztec/accounts/testing';
1
+ import { getInitialTestAccountsData } from '@aztec/accounts/testing';
2
+ import { AztecAddress } from '@aztec/aztec.js/addresses';
3
3
  import {
4
- type AccountWallet,
5
- AztecAddress,
6
4
  BatchCall,
7
5
  ContractBase,
8
6
  ContractFunctionInteraction,
9
7
  type DeployMethod,
10
8
  type DeployOptions,
11
- FeeJuicePaymentMethodWithClaim,
12
- L1FeeJuicePortalManager,
13
- type PXE,
14
- createLogger,
15
- createPXEClient,
16
- waitForL1ToL2MessageReady,
17
- } from '@aztec/aztec.js';
18
- import { createEthereumChain, createExtendedL1Client } from '@aztec/ethereum';
19
- import { Fr } from '@aztec/foundation/fields';
9
+ NO_WAIT,
10
+ } from '@aztec/aztec.js/contracts';
11
+ import type { L2AmountClaim } from '@aztec/aztec.js/ethereum';
12
+ import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
13
+ import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
14
+ import { deriveKeys } from '@aztec/aztec.js/keys';
15
+ import { createLogger } from '@aztec/aztec.js/log';
16
+ import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
17
+ import { waitForTx } from '@aztec/aztec.js/node';
18
+ import { createEthereumChain } from '@aztec/ethereum/chain';
19
+ import { createExtendedL1Client } from '@aztec/ethereum/client';
20
+ import { RollupContract } from '@aztec/ethereum/contracts';
21
+ import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
22
+ import { Fr } from '@aztec/foundation/curves/bn254';
23
+ import { EthAddress } from '@aztec/foundation/eth-address';
20
24
  import { Timer } from '@aztec/foundation/timer';
21
25
  import { AMMContract } from '@aztec/noir-contracts.js/AMM';
22
26
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
23
27
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
28
+ import { TestContract } from '@aztec/noir-test-contracts.js/Test';
29
+ import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
30
+ import { GasSettings } from '@aztec/stdlib/gas';
24
31
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
25
32
  import { deriveSigningKey } from '@aztec/stdlib/keys';
26
- import { makeTracedFetch } from '@aztec/telemetry-client';
33
+ import { EmbeddedWallet } from '@aztec/wallets/embedded';
27
34
 
28
- import { type BotConfig, SupportedTokenContracts, getVersions } from './config.js';
35
+ import { type BotConfig, SupportedTokenContracts } from './config.js';
36
+ import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
37
+ import type { BotStore } from './store/index.js';
29
38
  import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
30
39
 
31
40
  const MINT_BALANCE = 1e12;
32
41
  const MIN_BALANCE = 1e3;
33
42
 
34
43
  export class BotFactory {
35
- private pxe: PXE;
36
- private node?: AztecNode;
37
- private nodeAdmin?: AztecNodeAdmin;
38
44
  private log = createLogger('bot');
39
45
 
40
46
  constructor(
41
47
  private readonly config: BotConfig,
42
- dependencies: { pxe?: PXE; nodeAdmin?: AztecNodeAdmin; node?: AztecNode },
43
- ) {
44
- if (config.flushSetupTransactions && !dependencies.nodeAdmin) {
45
- throw new Error(
46
- `Either a node admin client or node admin url must be provided if transaction flushing is requested`,
47
- );
48
- }
49
- if (config.senderPrivateKey && config.senderPrivateKey.getValue() && !dependencies.node) {
50
- throw new Error(
51
- `Either a node client or node url must be provided for bridging L1 fee juice to deploy an account with private key`,
52
- );
53
- }
54
- if (!dependencies.pxe && !config.pxeUrl) {
55
- throw new Error(`Either a PXE client or a PXE URL must be provided`);
56
- }
57
-
58
- this.node = dependencies.node;
59
- this.nodeAdmin = dependencies.nodeAdmin;
60
-
61
- if (dependencies.pxe) {
62
- this.log.info(`Using local PXE`);
63
- this.pxe = dependencies.pxe;
64
- return;
65
- }
66
- this.log.info(`Using remote PXE at ${config.pxeUrl!}`);
67
- this.pxe = createPXEClient(config.pxeUrl!, getVersions(), makeTracedFetch([1, 2, 3], false));
68
- }
48
+ private readonly wallet: EmbeddedWallet,
49
+ private readonly store: BotStore,
50
+ private readonly aztecNode: AztecNode,
51
+ private readonly aztecNodeAdmin?: AztecNodeAdmin,
52
+ ) {}
69
53
 
70
54
  /**
71
55
  * Initializes a new bot by setting up the sender account, registering the recipient,
72
56
  * deploying the token contract, and minting tokens if necessary.
73
57
  */
74
- public async setup() {
75
- const recipient = await this.registerRecipient();
76
- const wallet = await this.setupAccount();
77
- const defaultAccountAddress = wallet.getAddress();
78
- const token = await this.setupToken(wallet, defaultAccountAddress);
58
+ public async setup(): Promise<{
59
+ wallet: EmbeddedWallet;
60
+ defaultAccountAddress: AztecAddress;
61
+ token: TokenContract | PrivateTokenContract;
62
+ node: AztecNode;
63
+ recipient: AztecAddress;
64
+ }> {
65
+ const defaultAccountAddress = await this.setupAccount();
66
+ const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
67
+ const token = await this.setupToken(defaultAccountAddress);
79
68
  await this.mintTokens(token, defaultAccountAddress);
80
- return { wallet, defaultAccountAddress, token, pxe: this.pxe, recipient };
69
+ return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
81
70
  }
82
71
 
83
- public async setupAmm() {
84
- const wallet = await this.setupAccount();
85
- const defaultAccountAddress = wallet.getAddress();
86
- const token0 = await this.setupTokenContract(
87
- wallet,
88
- wallet.getAddress(),
89
- this.config.tokenSalt,
90
- 'BotToken0',
91
- 'BOT0',
92
- );
93
- const token1 = await this.setupTokenContract(
94
- wallet,
95
- wallet.getAddress(),
96
- this.config.tokenSalt,
97
- 'BotToken1',
98
- 'BOT1',
99
- );
72
+ public async setupAmm(): Promise<{
73
+ wallet: EmbeddedWallet;
74
+ defaultAccountAddress: AztecAddress;
75
+ amm: AMMContract;
76
+ token0: TokenContract;
77
+ token1: TokenContract;
78
+ node: AztecNode;
79
+ }> {
80
+ const defaultAccountAddress = await this.setupAccount();
81
+ const token0 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
82
+ const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
100
83
  const liquidityToken = await this.setupTokenContract(
101
- wallet,
102
- wallet.getAddress(),
84
+ defaultAccountAddress,
103
85
  this.config.tokenSalt,
104
86
  'BotLPToken',
105
87
  'BOTLP',
106
88
  );
107
89
  const amm = await this.setupAmmContract(
108
- wallet,
109
- wallet.getAddress(),
90
+ defaultAccountAddress,
110
91
  this.config.tokenSalt,
111
92
  token0,
112
93
  token1,
113
94
  liquidityToken,
114
95
  );
115
96
 
116
- await this.fundAmm(wallet, wallet.getAddress(), amm, token0, token1, liquidityToken);
97
+ await this.fundAmm(defaultAccountAddress, defaultAccountAddress, amm, token0, token1, liquidityToken);
117
98
  this.log.info(`AMM initialized and funded`);
118
99
 
119
- return { wallet, defaultAccountAddress, amm, token0, token1, pxe: this.pxe };
100
+ return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
101
+ }
102
+
103
+ /**
104
+ * Initializes the cross-chain bot by deploying TestContract, creating an L1 client,
105
+ * seeding initial L1→L2 messages, and waiting for the first to be ready.
106
+ */
107
+ public async setupCrossChain(): Promise<{
108
+ wallet: EmbeddedWallet;
109
+ defaultAccountAddress: AztecAddress;
110
+ contract: TestContract;
111
+ node: AztecNode;
112
+ l1Client: ExtendedViemWalletClient;
113
+ rollupVersion: bigint;
114
+ }> {
115
+ const defaultAccountAddress = await this.setupAccount();
116
+
117
+ // Create L1 client (same pattern as bridgeL1FeeJuice)
118
+ const l1RpcUrls = this.config.l1RpcUrls;
119
+ if (!l1RpcUrls?.length) {
120
+ throw new Error('L1 RPC URLs required for cross-chain bot');
121
+ }
122
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
123
+ if (!mnemonicOrPrivateKey) {
124
+ throw new Error('L1 mnemonic or private key required for cross-chain bot');
125
+ }
126
+ const { l1ChainId, l1ContractAddresses } = await this.aztecNode.getNodeInfo();
127
+ const chain = createEthereumChain(l1RpcUrls, l1ChainId);
128
+ const l1Client = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
129
+
130
+ // Fetch Rollup version (needed for Inbox L2Actor struct)
131
+ const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
132
+ const rollupVersion = await rollupContract.getVersion();
133
+
134
+ // Deploy TestContract
135
+ const contract = await this.setupTestContract(defaultAccountAddress);
136
+
137
+ // Recover any pending messages from store (clean up stale ones first)
138
+ await this.store.cleanupOldPendingMessages();
139
+ const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
140
+
141
+ // Seed initial L1→L2 messages if pipeline is empty
142
+ const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
143
+ for (let i = 0; i < seedCount; i++) {
144
+ await seedL1ToL2Message(
145
+ l1Client,
146
+ EthAddress.fromString(l1ContractAddresses.inboxAddress.toString()),
147
+ contract.address,
148
+ rollupVersion,
149
+ this.store,
150
+ this.log,
151
+ );
152
+ }
153
+
154
+ // Block until at least one message is ready
155
+ const allMessages = await this.store.getUnconsumedL1ToL2Messages();
156
+ if (allMessages.length > 0) {
157
+ this.log.info(`Waiting for first L1→L2 message to be ready...`);
158
+ const firstMsg = allMessages[0];
159
+ await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
160
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
161
+ // Use forPublicConsumption: false so we wait until the message is in the current world
162
+ // state. With true, it returns one block early which causes gas estimation simulation to
163
+ // fail since it runs against the current state.
164
+ // See https://linear.app/aztec-labs/issue/A-548 for details.
165
+ forPublicConsumption: false,
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);
120
189
  }
121
190
 
122
191
  /**
@@ -126,62 +195,63 @@ export class BotFactory {
126
195
  private async setupAccount() {
127
196
  const privateKey = this.config.senderPrivateKey?.getValue();
128
197
  if (privateKey) {
198
+ this.log.info(`Setting up account with provided private key`);
129
199
  return await this.setupAccountWithPrivateKey(privateKey);
130
200
  } else {
201
+ this.log.info(`Setting up test account`);
131
202
  return await this.setupTestAccount();
132
203
  }
133
204
  }
134
205
 
135
- private async setupAccountWithPrivateKey(privateKey: Fr) {
206
+ private async setupAccountWithPrivateKey(secret: Fr) {
136
207
  const salt = this.config.senderSalt ?? Fr.ONE;
137
- const signingKey = deriveSigningKey(privateKey);
138
- const account = await getSchnorrAccount(this.pxe, privateKey, signingKey, salt);
139
- const isInit = (await this.pxe.getContractMetadata(account.getAddress())).isContractInitialized;
140
- if (isInit) {
141
- this.log.info(`Account at ${account.getAddress().toString()} already initialized`);
208
+ const signingKey = deriveSigningKey(secret);
209
+ const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
210
+ const metadata = await this.wallet.getContractMetadata(accountManager.address);
211
+ if (metadata.isContractInitialized) {
212
+ this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
142
213
  const timer = new Timer();
143
- const wallet = await account.register();
144
- this.log.info(`Account at ${account.getAddress()} registered. duration=${timer.ms()}`);
145
- return wallet;
214
+ const address = accountManager.address;
215
+ this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
216
+ await this.store.deleteBridgeClaim(address);
217
+ return address;
146
218
  } else {
147
- const address = account.getAddress();
219
+ const address = accountManager.address;
148
220
  this.log.info(`Deploying account at ${address}`);
149
221
 
150
- const claim = await this.bridgeL1FeeJuice(address);
151
-
152
- // docs:start:claim_and_deploy
153
- const wallet = await account.getWallet();
154
- const paymentMethod = new FeeJuicePaymentMethodWithClaim(wallet, claim);
155
- const sentTx = account.deploy({ fee: { paymentMethod } });
156
- const txHash = await sentTx.getTxHash();
157
- // docs:end:claim_and_deploy
158
- this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
159
- await this.withNoMinTxsPerBlock(() => sentTx.wait({ timeout: this.config.txMinedWaitSeconds }));
222
+ const claim = await this.getOrCreateBridgeClaim(address);
223
+
224
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
225
+ const deployMethod = await accountManager.getDeployMethod();
226
+ const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
227
+ const gasSettings = GasSettings.default({ maxFeesPerGas });
228
+
229
+ await this.withNoMinTxsPerBlock(async () => {
230
+ const txHash = await deployMethod.send({
231
+ from: AztecAddress.ZERO,
232
+ fee: { gasSettings, paymentMethod },
233
+ wait: NO_WAIT,
234
+ });
235
+ this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
236
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
237
+ });
160
238
  this.log.info(`Account deployed at ${address}`);
161
- return wallet;
162
- }
163
- }
164
239
 
165
- private async setupTestAccount() {
166
- let [wallet] = await getDeployedTestAccountsWallets(this.pxe);
167
- if (wallet) {
168
- this.log.info(`Using funded test account: ${wallet.getAddress()}`);
169
- } else {
170
- this.log.info('Registering funded test account');
171
- const [account] = await getInitialTestAccounts();
172
- const manager = await getSchnorrAccount(this.pxe, account.secret, account.signingKey, account.salt);
173
- wallet = await manager.register();
174
- this.log.info(`Funded test account registered: ${wallet.getAddress()}`);
240
+ // Clean up the consumed bridge claim
241
+ await this.store.deleteBridgeClaim(address);
242
+
243
+ return accountManager.address;
175
244
  }
176
- return wallet;
177
245
  }
178
246
 
179
- /**
180
- * Registers the recipient for txs in the pxe.
181
- */
182
- private async registerRecipient() {
183
- const recipient = await this.pxe.registerAccount(this.config.recipientEncryptionSecret.getValue(), Fr.ONE);
184
- return recipient.address;
247
+ private async setupTestAccount() {
248
+ const [initialAccountData] = await getInitialTestAccountsData();
249
+ const accountManager = await this.wallet.createSchnorrAccount(
250
+ initialAccountData.secret,
251
+ initialAccountData.salt,
252
+ initialAccountData.signingKey,
253
+ );
254
+ return accountManager.address;
185
255
  }
186
256
 
187
257
  /**
@@ -189,35 +259,53 @@ export class BotFactory {
189
259
  * @param wallet - Wallet to deploy the token contract from.
190
260
  * @returns The TokenContract instance.
191
261
  */
192
- private async setupToken(wallet: AccountWallet, sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
262
+ private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
193
263
  let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
264
+ let tokenInstance: ContractInstanceWithAddress | undefined;
194
265
  const deployOpts: DeployOptions = {
195
266
  from: sender,
196
267
  contractAddressSalt: this.config.tokenSalt,
197
268
  universalDeploy: true,
198
269
  };
270
+ let token: TokenContract | PrivateTokenContract;
199
271
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
200
- deploy = TokenContract.deploy(wallet, sender, 'BotToken', 'BOT', 18);
272
+ deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
273
+ tokenInstance = await deploy.getInstance(deployOpts);
274
+ token = TokenContract.at(tokenInstance.address, this.wallet);
201
275
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
202
- deploy = PrivateTokenContract.deploy(wallet, MINT_BALANCE, sender);
276
+ // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
277
+ const tokenSecretKey = Fr.random();
278
+ const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
279
+ deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
203
280
  deployOpts.skipInstancePublication = true;
204
281
  deployOpts.skipClassPublication = true;
205
282
  deployOpts.skipInitialization = false;
283
+
284
+ // Register the contract with the secret key before deployment
285
+ tokenInstance = await deploy.getInstance(deployOpts);
286
+ token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
287
+ await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
288
+ // The contract constructor initializes private storage vars that need the contract's own nullifier key.
289
+ deployOpts.additionalScopes = [tokenInstance.address];
206
290
  } else {
207
291
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
208
292
  }
209
293
 
210
- const address = (await deploy.getInstance(deployOpts)).address;
211
- if ((await this.pxe.getContractMetadata(address)).isContractPublished) {
294
+ const address = tokenInstance?.address ?? (await deploy.getInstance(deployOpts)).address;
295
+ const metadata = await this.wallet.getContractMetadata(address);
296
+ if (metadata.isContractPublished) {
212
297
  this.log.info(`Token at ${address.toString()} already deployed`);
213
- return deploy.register();
298
+ await deploy.register();
214
299
  } else {
215
300
  this.log.info(`Deploying token contract at ${address.toString()}`);
216
- const sentTx = deploy.send(deployOpts);
217
- const txHash = await sentTx.getTxHash();
301
+ const txHash = await deploy.send({ ...deployOpts, wait: NO_WAIT });
218
302
  this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
219
- return this.withNoMinTxsPerBlock(() => sentTx.deployed({ timeout: this.config.txMinedWaitSeconds }));
303
+ await this.withNoMinTxsPerBlock(async () => {
304
+ await waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
305
+ return token;
306
+ });
220
307
  }
308
+ return token;
221
309
  }
222
310
 
223
311
  /**
@@ -225,8 +313,7 @@ export class BotFactory {
225
313
  * @param wallet - Wallet to deploy the token contract from.
226
314
  * @returns The TokenContract instance.
227
315
  */
228
- private setupTokenContract(
229
- wallet: AccountWallet,
316
+ private async setupTokenContract(
230
317
  deployer: AztecAddress,
231
318
  contractAddressSalt: Fr,
232
319
  name: string,
@@ -234,12 +321,12 @@ export class BotFactory {
234
321
  decimals = 18,
235
322
  ): Promise<TokenContract> {
236
323
  const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
237
- const deploy = TokenContract.deploy(wallet, deployer, name, ticker, decimals);
238
- return this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
324
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
325
+ const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
326
+ return TokenContract.at(instance.address, this.wallet);
239
327
  }
240
328
 
241
329
  private async setupAmmContract(
242
- wallet: AccountWallet,
243
330
  deployer: AztecAddress,
244
331
  contractAddressSalt: Fr,
245
332
  token0: TokenContract,
@@ -247,20 +334,22 @@ export class BotFactory {
247
334
  lpToken: TokenContract,
248
335
  ): Promise<AMMContract> {
249
336
  const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
250
- const deploy = AMMContract.deploy(wallet, token0.address, token1.address, lpToken.address);
251
- const amm = await this.registerOrDeployContract('AMM', deploy, deployOpts);
337
+ const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
338
+ const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
339
+ const amm = AMMContract.at(instance.address, this.wallet);
252
340
 
253
341
  this.log.info(`AMM deployed at ${amm.address}`);
254
- const minterTx = lpToken.methods.set_minter(amm.address, true).send({ from: deployer });
255
- this.log.info(`Set LP token minter to AMM txHash=${(await minterTx.getTxHash()).toString()}`);
256
- await minterTx.wait({ timeout: this.config.txMinedWaitSeconds });
342
+ const minterReceipt = await lpToken.methods
343
+ .set_minter(amm.address, true)
344
+ .send({ from: deployer, wait: { timeout: this.config.txMinedWaitSeconds } });
345
+ this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
257
346
  this.log.info(`Liquidity token initialized`);
258
347
 
259
348
  return amm;
260
349
  }
261
350
 
262
351
  private async fundAmm(
263
- wallet: AccountWallet,
352
+ defaultAccountAddress: AztecAddress,
264
353
  liquidityProvider: AztecAddress,
265
354
  amm: AMMContract,
266
355
  token0: TokenContract,
@@ -289,47 +378,50 @@ export class BotFactory {
289
378
  );
290
379
 
291
380
  // Add authwitnesses for the transfers in AMM::add_liquidity function
292
- const token0Authwit = await wallet.createAuthWit({
381
+ const token0Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
293
382
  caller: amm.address,
294
- action: token0.methods.transfer_to_public_and_prepare_private_balance_increase(
295
- liquidityProvider,
296
- amm.address,
297
- amount0Max,
298
- authwitNonce,
299
- ),
383
+ call: await token0.methods
384
+ .transfer_to_public_and_prepare_private_balance_increase(
385
+ liquidityProvider,
386
+ amm.address,
387
+ amount0Max,
388
+ authwitNonce,
389
+ )
390
+ .getFunctionCall(),
300
391
  });
301
- const token1Authwit = await wallet.createAuthWit({
392
+ const token1Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
302
393
  caller: amm.address,
303
- action: token1.methods.transfer_to_public_and_prepare_private_balance_increase(
304
- liquidityProvider,
305
- amm.address,
306
- amount1Max,
307
- authwitNonce,
308
- ),
394
+ call: await token1.methods
395
+ .transfer_to_public_and_prepare_private_balance_increase(
396
+ liquidityProvider,
397
+ amm.address,
398
+ amount1Max,
399
+ authwitNonce,
400
+ )
401
+ .getFunctionCall(),
309
402
  });
310
403
 
311
- const mintTx = new BatchCall(wallet, [
404
+ const mintReceipt = await new BatchCall(this.wallet, [
312
405
  token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
313
406
  token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
314
- ]).send({ from: liquidityProvider });
407
+ ]).send({ from: liquidityProvider, wait: { timeout: this.config.txMinedWaitSeconds } });
315
408
 
316
- this.log.info(`Sent mint tx: ${(await mintTx.getTxHash()).toString()}`);
317
- await mintTx.wait({ timeout: this.config.txMinedWaitSeconds });
409
+ this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
318
410
 
319
- const addLiquidityTx = amm.methods
411
+ const addLiquidityReceipt = await amm.methods
320
412
  .add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce)
321
413
  .send({
322
414
  from: liquidityProvider,
323
415
  authWitnesses: [token0Authwit, token1Authwit],
416
+ wait: { timeout: this.config.txMinedWaitSeconds },
324
417
  });
325
418
 
326
- this.log.info(`Sent tx to add liquidity to the AMM: ${(await addLiquidityTx.getTxHash()).toString()}`);
327
- await addLiquidityTx.wait({ timeout: this.config.txMinedWaitSeconds });
419
+ this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`);
328
420
  this.log.info(`Liquidity added`);
329
421
 
330
422
  const [newT0Bal, newT1Bal, newLPBal] = await getPrivateBalances();
331
423
  this.log.info(
332
- `Updated private balances of ${wallet.getAddress()} after minting and funding AMM: token0=${newT0Bal}, token1=${newT1Bal}, lp=${newLPBal}`,
424
+ `Updated private balances of ${defaultAccountAddress} after minting and funding AMM: token0=${newT0Bal}, token1=${newT1Bal}, lp=${newLPBal}`,
333
425
  );
334
426
  }
335
427
 
@@ -337,18 +429,22 @@ export class BotFactory {
337
429
  name: string,
338
430
  deploy: DeployMethod<T>,
339
431
  deployOpts: DeployOptions,
340
- ): Promise<T> {
341
- const address = (await deploy.getInstance(deployOpts)).address;
342
- if ((await this.pxe.getContractMetadata(address)).isContractPublished) {
432
+ ): Promise<ContractInstanceWithAddress> {
433
+ const instance = await deploy.getInstance(deployOpts);
434
+ const address = instance.address;
435
+ const metadata = await this.wallet.getContractMetadata(address);
436
+ if (metadata.isContractPublished) {
343
437
  this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
344
- return deploy.register();
438
+ await deploy.register();
345
439
  } else {
346
440
  this.log.info(`Deploying contract ${name} at ${address.toString()}`);
347
- const sentTx = deploy.send(deployOpts);
348
- const txHash = await sentTx.getTxHash();
349
- this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
350
- return this.withNoMinTxsPerBlock(() => sentTx.deployed({ timeout: this.config.txMinedWaitSeconds }));
441
+ await this.withNoMinTxsPerBlock(async () => {
442
+ const txHash = await deploy.send({ ...deployOpts, wait: NO_WAIT });
443
+ this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
444
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
445
+ });
351
446
  }
447
+ return instance;
352
448
  }
353
449
 
354
450
  /**
@@ -384,13 +480,50 @@ export class BotFactory {
384
480
  this.log.info(`Skipping minting as ${minter.toString()} has enough tokens`);
385
481
  return;
386
482
  }
387
- const sentTx = new BatchCall(token.wallet, calls).send({ from: minter });
388
- const txHash = await sentTx.getTxHash();
389
- this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
390
- await this.withNoMinTxsPerBlock(() => sentTx.wait({ timeout: this.config.txMinedWaitSeconds }));
483
+
484
+ // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
485
+ const additionalScopes = isStandardToken ? undefined : [token.address];
486
+ await this.withNoMinTxsPerBlock(async () => {
487
+ const txHash = await new BatchCall(token.wallet, calls).send({ from: minter, additionalScopes, wait: NO_WAIT });
488
+ this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
489
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
490
+ });
491
+ }
492
+
493
+ /**
494
+ * Gets or creates a bridge claim for the recipient.
495
+ * Checks if a claim already exists in the store and reuses it if valid.
496
+ * Only creates a new bridge if fee juice balance is below threshold.
497
+ */
498
+ private async getOrCreateBridgeClaim(recipient: AztecAddress): Promise<L2AmountClaim> {
499
+ // Check if we have an existing claim in the store
500
+ const existingClaim = await this.store.getBridgeClaim(recipient);
501
+ if (existingClaim) {
502
+ this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
503
+
504
+ // Check if the message is ready on L2
505
+ try {
506
+ const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
507
+ await this.withNoMinTxsPerBlock(() =>
508
+ waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
509
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
510
+ forPublicConsumption: false,
511
+ }),
512
+ );
513
+ return existingClaim.claim;
514
+ } catch (err) {
515
+ this.log.warn(`Failed to verify existing claim, creating new one: ${err}`);
516
+ await this.store.deleteBridgeClaim(recipient);
517
+ }
518
+ }
519
+
520
+ const claim = await this.bridgeL1FeeJuice(recipient);
521
+ await this.store.saveBridgeClaim(recipient, claim);
522
+
523
+ return claim;
391
524
  }
392
525
 
393
- private async bridgeL1FeeJuice(recipient: AztecAddress) {
526
+ private async bridgeL1FeeJuice(recipient: AztecAddress): Promise<L2AmountClaim> {
394
527
  const l1RpcUrls = this.config.l1RpcUrls;
395
528
  if (!l1RpcUrls?.length) {
396
529
  throw new Error('L1 Rpc url is required to bridge the fee juice to fund the deployment of the account.');
@@ -402,16 +535,16 @@ export class BotFactory {
402
535
  );
403
536
  }
404
537
 
405
- const { l1ChainId } = await this.pxe.getNodeInfo();
538
+ const { l1ChainId } = await this.aztecNode.getNodeInfo();
406
539
  const chain = createEthereumChain(l1RpcUrls, l1ChainId);
407
540
  const extendedClient = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
408
541
 
409
- const portal = await L1FeeJuicePortalManager.new(this.pxe, extendedClient, this.log);
542
+ const portal = await L1FeeJuicePortalManager.new(this.aztecNode, extendedClient, this.log);
410
543
  const mintAmount = await portal.getTokenManager().getMintAmount();
411
544
  const claim = await portal.bridgeTokensPublic(recipient, mintAmount, true /* mint */);
412
545
 
413
546
  await this.withNoMinTxsPerBlock(() =>
414
- waitForL1ToL2MessageReady(this.pxe, Fr.fromHexString(claim.messageHash), {
547
+ waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
415
548
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
416
549
  forPublicConsumption: false,
417
550
  }),
@@ -419,19 +552,22 @@ export class BotFactory {
419
552
 
420
553
  this.log.info(`Created a claim for ${mintAmount} L1 fee juice to ${recipient}.`, claim);
421
554
 
422
- return claim;
555
+ return claim as L2AmountClaim;
423
556
  }
424
557
 
425
558
  private async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
426
- if (!this.nodeAdmin || !this.config.flushSetupTransactions) {
559
+ if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
560
+ this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
427
561
  return fn();
428
562
  }
429
- const { minTxsPerBlock } = await this.nodeAdmin.getConfig();
430
- await this.nodeAdmin.setConfig({ minTxsPerBlock: 0 });
563
+ const { minTxsPerBlock } = await this.aztecNodeAdmin.getConfig();
564
+ this.log.warn(`Setting sequencer minTxsPerBlock to 0 from ${minTxsPerBlock} to flush setup transactions`);
565
+ await this.aztecNodeAdmin.setConfig({ minTxsPerBlock: 0 });
431
566
  try {
432
567
  return await fn();
433
568
  } finally {
434
- await this.nodeAdmin.setConfig({ minTxsPerBlock });
569
+ this.log.warn(`Restoring sequencer minTxsPerBlock to ${minTxsPerBlock}`);
570
+ await this.aztecNodeAdmin.setConfig({ minTxsPerBlock });
435
571
  }
436
572
  }
437
573
  }