@aztec/bot 0.0.1-commit.dbf9cec → 0.0.1-commit.ddcf04837

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.
package/src/config.ts CHANGED
@@ -11,9 +11,9 @@ import {
11
11
  secretStringConfigHelper,
12
12
  } from '@aztec/foundation/config';
13
13
  import { Fr } from '@aztec/foundation/curves/bn254';
14
- import { type DataStoreConfig, dataConfigMappings } from '@aztec/kv-store/config';
15
14
  import { getVKTreeRoot } from '@aztec/noir-protocol-circuits-types/vk-tree';
16
15
  import { protocolContractsHash } from '@aztec/protocol-contracts';
16
+ import { type DataStoreConfig, dataConfigMappings } from '@aztec/stdlib/kv-store';
17
17
  import { schemas, zodFor } from '@aztec/stdlib/schemas';
18
18
  import type { ComponentsVersions } from '@aztec/stdlib/versioning';
19
19
 
@@ -69,9 +69,9 @@ export type BotConfig = {
69
69
  maxPendingTxs: number;
70
70
  /** Whether to flush after sending each 'setup' transaction */
71
71
  flushSetupTransactions: boolean;
72
- /** L2 gas limit for the tx (empty to have the bot trigger an estimate gas). */
72
+ /** L2 gas limit for the tx (empty to let the bot's wallet estimate). */
73
73
  l2GasLimit: number | undefined;
74
- /** DA gas limit for the tx (empty to have the bot trigger an estimate gas). */
74
+ /** DA gas limit for the tx (empty to let the bot's wallet estimate). */
75
75
  daGasLimit: number | undefined;
76
76
  /** Token contract to use */
77
77
  contract: SupportedTokenContracts;
@@ -130,7 +130,6 @@ export const BotConfigSchema = zodFor<BotConfig>()(
130
130
  l1Mnemonic: undefined,
131
131
  l1PrivateKey: undefined,
132
132
  senderPrivateKey: undefined,
133
- dataDirectory: undefined,
134
133
  dataStoreMapSizeKb: 1_024 * 1_024,
135
134
  ...config,
136
135
  })),
@@ -244,12 +243,12 @@ export const botConfigMappings: ConfigMappingsType<BotConfig> = {
244
243
  },
245
244
  l2GasLimit: {
246
245
  env: 'BOT_L2_GAS_LIMIT',
247
- description: 'L2 gas limit for the tx (empty to have the bot trigger an estimate gas).',
246
+ description: "L2 gas limit for the tx (empty to let the bot's wallet estimate).",
248
247
  ...optionalNumberConfigHelper(),
249
248
  },
250
249
  daGasLimit: {
251
250
  env: 'BOT_DA_GAS_LIMIT',
252
- description: 'DA gas limit for the tx (empty to have the bot trigger an estimate gas).',
251
+ description: "DA gas limit for the tx (empty to let the bot's wallet estimate).",
253
252
  ...optionalNumberConfigHelper(),
254
253
  },
255
254
  contract: {
@@ -137,10 +137,11 @@ export class CrossChainBot extends BaseBot {
137
137
  }
138
138
 
139
139
  const batch = new BatchCall(this.wallet, calls);
140
- const opts = await this.getSendMethodOpts(batch);
140
+ const opts = this.getSendMethodOpts();
141
141
 
142
142
  this.log.verbose(`Sending cross-chain batch with ${calls.length} calls`, logCtx);
143
- return batch.send({ ...opts, wait: NO_WAIT });
143
+ const { txHash } = await batch.send({ ...opts, wait: NO_WAIT });
144
+ return txHash;
144
145
  }
145
146
 
146
147
  protected override async onTxMined(receipt: TxReceipt, logCtx: object): Promise<void> {
@@ -174,14 +175,7 @@ export class CrossChainBot extends BaseBot {
174
175
  ): Promise<PendingL1ToL2Message | undefined> {
175
176
  const now = Date.now();
176
177
  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
- });
178
+ const ready = await isL1ToL2MessageReady(this.node, Fr.fromHexString(msg.msgHash));
185
179
  if (ready) {
186
180
  return msg;
187
181
  }
package/src/factory.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { getInitialTestAccountsData } from '@aztec/accounts/testing';
2
+ import { NO_FROM } from '@aztec/aztec.js/account';
2
3
  import { AztecAddress } from '@aztec/aztec.js/addresses';
3
4
  import {
4
5
  BatchCall,
@@ -15,6 +16,8 @@ import { deriveKeys } from '@aztec/aztec.js/keys';
15
16
  import { createLogger } from '@aztec/aztec.js/log';
16
17
  import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
17
18
  import { waitForTx } from '@aztec/aztec.js/node';
19
+ import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
20
+ import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
18
21
  import { createEthereumChain } from '@aztec/ethereum/chain';
19
22
  import { createExtendedL1Client } from '@aztec/ethereum/client';
20
23
  import { RollupContract } from '@aztec/ethereum/contracts';
@@ -27,7 +30,7 @@ import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
27
30
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
28
31
  import { TestContract } from '@aztec/noir-test-contracts.js/Test';
29
32
  import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
30
- import { GasSettings } from '@aztec/stdlib/gas';
33
+ import { GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
31
34
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
32
35
  import { deriveSigningKey } from '@aztec/stdlib/keys';
33
36
  import { EmbeddedWallet } from '@aztec/wallets/embedded';
@@ -39,6 +42,8 @@ import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils
39
42
 
40
43
  const MINT_BALANCE = 1e12;
41
44
  const MIN_BALANCE = 1e3;
45
+ const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
46
+ const FEE_JUICE_TOP_UP_TARGET = 10_000n * 10n ** 18n;
42
47
 
43
48
  export class BotFactory {
44
49
  private log = createLogger('bot');
@@ -49,7 +54,11 @@ export class BotFactory {
49
54
  private readonly store: BotStore,
50
55
  private readonly aztecNode: AztecNode,
51
56
  private readonly aztecNodeAdmin?: AztecNodeAdmin,
52
- ) {}
57
+ ) {
58
+ // Set fee padding on the wallet so that all transactions during setup
59
+ // (token deploy, minting, etc.) use the configured padding, not the default.
60
+ this.wallet.setMinFeePadding(config.minFeePadding);
61
+ }
53
62
 
54
63
  /**
55
64
  * Initializes a new bot by setting up the sender account, registering the recipient,
@@ -64,7 +73,8 @@ export class BotFactory {
64
73
  }> {
65
74
  const defaultAccountAddress = await this.setupAccount();
66
75
  const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
67
- const token = await this.setupToken(defaultAccountAddress);
76
+ const token = await this.setupTokenWithOptionalEarlyRefuel(defaultAccountAddress);
77
+ await this.ensureFeeJuiceBalance(defaultAccountAddress, token);
68
78
  await this.mintTokens(token, defaultAccountAddress);
69
79
  return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
70
80
  }
@@ -78,7 +88,13 @@ export class BotFactory {
78
88
  node: AztecNode;
79
89
  }> {
80
90
  const defaultAccountAddress = await this.setupAccount();
81
- const token0 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
91
+ const token0 = await this.setupTokenContractWithOptionalEarlyRefuel(
92
+ defaultAccountAddress,
93
+ this.config.tokenSalt,
94
+ 'BotToken0',
95
+ 'BOT0',
96
+ );
97
+ await this.ensureFeeJuiceBalance(defaultAccountAddress, token0);
82
98
  const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
83
99
  const liquidityToken = await this.setupTokenContract(
84
100
  defaultAccountAddress,
@@ -158,11 +174,6 @@ export class BotFactory {
158
174
  const firstMsg = allMessages[0];
159
175
  await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
160
176
  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
177
  });
167
178
  this.log.info(`First L1→L2 message is ready`);
168
179
  }
@@ -208,7 +219,7 @@ export class BotFactory {
208
219
  const signingKey = deriveSigningKey(secret);
209
220
  const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
210
221
  const metadata = await this.wallet.getContractMetadata(accountManager.address);
211
- if (metadata.isContractInitialized) {
222
+ if (metadata.initializationStatus === ContractInitializationStatus.INITIALIZED) {
212
223
  this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
213
224
  const timer = new Timer();
214
225
  const address = accountManager.address;
@@ -223,13 +234,11 @@ export class BotFactory {
223
234
 
224
235
  const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
225
236
  const deployMethod = await accountManager.getDeployMethod();
226
- const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
227
- const gasSettings = GasSettings.default({ maxFeesPerGas });
228
237
 
229
238
  await this.withNoMinTxsPerBlock(async () => {
230
- const txHash = await deployMethod.send({
231
- from: AztecAddress.ZERO,
232
- fee: { gasSettings, paymentMethod },
239
+ const { txHash } = await deployMethod.send({
240
+ from: NO_FROM,
241
+ fee: { paymentMethod },
233
242
  wait: NO_WAIT,
234
243
  });
235
244
  this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
@@ -254,14 +263,79 @@ export class BotFactory {
254
263
  return accountManager.address;
255
264
  }
256
265
 
266
+ /**
267
+ * Setup token and refuel first: if the token already exists (restart scenario),
268
+ * run ensureFeeJuiceBalance before any step that might need fee juice. When deploying,
269
+ * use a bridge claim if balance is below threshold.
270
+ */
271
+ private async setupTokenWithOptionalEarlyRefuel(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
272
+ const token = await this.getTokenInstance(sender);
273
+ const address = token.address;
274
+ const metadata = await this.wallet.getContractMetadata(address);
275
+ if (metadata.isContractPublished) {
276
+ this.log.info(`Token at ${address.toString()} already deployed, refueling before setup`);
277
+ await this.ensureFeeJuiceBalance(sender, token);
278
+ }
279
+ return this.setupToken(sender);
280
+ }
281
+
282
+ /**
283
+ * Setup token0 for AMM with refuel-first behaviour when token already exists.
284
+ */
285
+ private async setupTokenContractWithOptionalEarlyRefuel(
286
+ deployer: AztecAddress,
287
+ contractAddressSalt: Fr,
288
+ name: string,
289
+ ticker: string,
290
+ decimals = 18,
291
+ ): Promise<TokenContract> {
292
+ const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
293
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
294
+ const instance = await deploy.getInstance(deployOpts);
295
+ const metadata = await this.wallet.getContractMetadata(instance.address);
296
+ if (metadata.isContractPublished) {
297
+ this.log.info(`Token ${name} at ${instance.address.toString()} already deployed, refueling before setup`);
298
+ const token = TokenContract.at(instance.address, this.wallet);
299
+ await this.ensureFeeJuiceBalance(deployer, token);
300
+ }
301
+ return this.setupTokenContract(deployer, contractAddressSalt, name, ticker, decimals);
302
+ }
303
+
304
+ private async getTokenInstance(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
305
+ const deployOpts: DeployOptions = {
306
+ from: sender,
307
+ contractAddressSalt: this.config.tokenSalt,
308
+ universalDeploy: true,
309
+ };
310
+ if (this.config.contract === SupportedTokenContracts.TokenContract) {
311
+ const deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
312
+ const instance = await deploy.getInstance(deployOpts);
313
+ return TokenContract.at(instance.address, this.wallet);
314
+ }
315
+ if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
316
+ const tokenSecretKey = Fr.random();
317
+ const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
318
+ const deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
319
+ const instance = await deploy.getInstance({
320
+ ...deployOpts,
321
+ skipInstancePublication: true,
322
+ skipClassPublication: true,
323
+ skipInitialization: false,
324
+ });
325
+ return PrivateTokenContract.at(instance.address, this.wallet);
326
+ }
327
+ throw new Error(`Unsupported token contract type: ${this.config.contract}`);
328
+ }
329
+
257
330
  /**
258
331
  * Checks if the token contract is deployed and deploys it if necessary.
259
- * @param wallet - Wallet to deploy the token contract from.
260
- * @returns The TokenContract instance.
332
+ * Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
333
+ * @param sender - Aztec address to deploy the token contract from.
334
+ * @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
335
+ * @returns The TokenContract or PrivateTokenContract instance.
261
336
  */
262
337
  private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
263
338
  let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
264
- let tokenInstance: ContractInstanceWithAddress | undefined;
265
339
  const deployOpts: DeployOptions = {
266
340
  from: sender,
267
341
  contractAddressSalt: this.config.tokenSalt,
@@ -270,8 +344,8 @@ export class BotFactory {
270
344
  let token: TokenContract | PrivateTokenContract;
271
345
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
272
346
  deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
273
- tokenInstance = await deploy.getInstance(deployOpts);
274
- token = TokenContract.at(tokenInstance.address, this.wallet);
347
+ const instance = await deploy.getInstance(deployOpts);
348
+ token = TokenContract.at(instance.address, this.wallet);
275
349
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
276
350
  // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
277
351
  const tokenSecretKey = Fr.random();
@@ -282,7 +356,7 @@ export class BotFactory {
282
356
  deployOpts.skipInitialization = false;
283
357
 
284
358
  // Register the contract with the secret key before deployment
285
- tokenInstance = await deploy.getInstance(deployOpts);
359
+ const tokenInstance = await deploy.getInstance(deployOpts);
286
360
  token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
287
361
  await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
288
362
  // The contract constructor initializes private storage vars that need the contract's own nullifier key.
@@ -291,20 +365,7 @@ export class BotFactory {
291
365
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
292
366
  }
293
367
 
294
- const address = tokenInstance?.address ?? (await deploy.getInstance(deployOpts)).address;
295
- const metadata = await this.wallet.getContractMetadata(address);
296
- if (metadata.isContractPublished) {
297
- this.log.info(`Token at ${address.toString()} already deployed`);
298
- await deploy.register();
299
- } else {
300
- this.log.info(`Deploying token contract at ${address.toString()}`);
301
- const txHash = await deploy.send({ ...deployOpts, wait: NO_WAIT });
302
- this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
303
- await this.withNoMinTxsPerBlock(async () => {
304
- await waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
305
- return token;
306
- });
307
- }
368
+ await this.registerOrDeployContract('token', deploy, deployOpts);
308
369
  return token;
309
370
  }
310
371
 
@@ -339,9 +400,11 @@ export class BotFactory {
339
400
  const amm = AMMContract.at(instance.address, this.wallet);
340
401
 
341
402
  this.log.info(`AMM deployed at ${amm.address}`);
342
- const minterReceipt = await lpToken.methods
343
- .set_minter(amm.address, true)
344
- .send({ from: deployer, wait: { timeout: this.config.txMinedWaitSeconds } });
403
+ const setMinterInteraction = lpToken.methods.set_minter(amm.address, true);
404
+ const { receipt: minterReceipt } = await setMinterInteraction.send({
405
+ from: deployer,
406
+ wait: { timeout: this.config.txMinedWaitSeconds },
407
+ });
345
408
  this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
346
409
  this.log.info(`Liquidity token initialized`);
347
410
 
@@ -358,9 +421,18 @@ export class BotFactory {
358
421
  ): Promise<void> {
359
422
  const getPrivateBalances = () =>
360
423
  Promise.all([
361
- token0.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
362
- token1.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
363
- lpToken.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
424
+ token0.methods
425
+ .balance_of_private(liquidityProvider)
426
+ .simulate({ from: liquidityProvider })
427
+ .then(r => r.result),
428
+ token1.methods
429
+ .balance_of_private(liquidityProvider)
430
+ .simulate({ from: liquidityProvider })
431
+ .then(r => r.result),
432
+ lpToken.methods
433
+ .balance_of_private(liquidityProvider)
434
+ .simulate({ from: liquidityProvider })
435
+ .then(r => r.result),
364
436
  ]);
365
437
 
366
438
  const authwitNonce = Fr.random();
@@ -401,20 +473,29 @@ export class BotFactory {
401
473
  .getFunctionCall(),
402
474
  });
403
475
 
404
- const mintReceipt = await new BatchCall(this.wallet, [
476
+ const mintBatch = new BatchCall(this.wallet, [
405
477
  token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
406
478
  token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
407
- ]).send({ from: liquidityProvider, wait: { timeout: this.config.txMinedWaitSeconds } });
479
+ ]);
480
+ const { receipt: mintReceipt } = await mintBatch.send({
481
+ from: liquidityProvider,
482
+ wait: { timeout: this.config.txMinedWaitSeconds },
483
+ });
408
484
 
409
485
  this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
410
486
 
411
- const addLiquidityReceipt = await amm.methods
412
- .add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce)
413
- .send({
414
- from: liquidityProvider,
415
- authWitnesses: [token0Authwit, token1Authwit],
416
- wait: { timeout: this.config.txMinedWaitSeconds },
417
- });
487
+ const addLiquidityInteraction = amm.methods.add_liquidity(
488
+ amount0Max,
489
+ amount1Max,
490
+ amount0Min,
491
+ amount1Min,
492
+ authwitNonce,
493
+ );
494
+ const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
495
+ from: liquidityProvider,
496
+ authWitnesses: [token0Authwit, token1Authwit],
497
+ wait: { timeout: this.config.txMinedWaitSeconds },
498
+ });
418
499
 
419
500
  this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`);
420
501
  this.log.info(`Liquidity added`);
@@ -437,12 +518,42 @@ export class BotFactory {
437
518
  this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
438
519
  await deploy.register();
439
520
  } else {
440
- this.log.info(`Deploying contract ${name} at ${address.toString()}`);
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
- });
521
+ const sender = deployOpts.from === NO_FROM ? undefined : deployOpts.from;
522
+ const balance = sender ? await getFeeJuiceBalance(sender, this.aztecNode) : 0n;
523
+ const useClaim =
524
+ sender &&
525
+ balance < FEE_JUICE_TOP_UP_THRESHOLD &&
526
+ this.config.feePaymentMethod === 'fee_juice' &&
527
+ !!this.config.l1RpcUrls?.length;
528
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
529
+
530
+ if (useClaim && mnemonicOrPrivateKey) {
531
+ const claim = await this.getOrCreateBridgeClaim(sender!);
532
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(sender!, claim);
533
+ const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true, paymentMethod } });
534
+ const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
535
+ const gasSettings = GasSettings.from({
536
+ ...estimatedGas!,
537
+ maxFeesPerGas,
538
+ maxPriorityFeesPerGas: GasFees.empty(),
539
+ });
540
+ await this.withNoMinTxsPerBlock(async () => {
541
+ const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings, paymentMethod }, wait: NO_WAIT });
542
+ this.log.info(
543
+ `Sent contract ${name} deploy tx ${txHash.toString()} (using bridge claim, balance was ${balance})`,
544
+ );
545
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
546
+ });
547
+ await this.store.deleteBridgeClaim(sender!);
548
+ } else {
549
+ const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true } });
550
+ this.log.info(`Deploying contract ${name} at ${address.toString()}`, { estimatedGas });
551
+ await this.withNoMinTxsPerBlock(async () => {
552
+ const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings: estimatedGas }, wait: NO_WAIT });
553
+ this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
554
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
555
+ });
556
+ }
446
557
  }
447
558
  return instance;
448
559
  }
@@ -451,6 +562,66 @@ export class BotFactory {
451
562
  * Mints private and public tokens for the sender if their balance is below the minimum.
452
563
  * @param token - Token contract.
453
564
  */
565
+ /**
566
+ * Ensures the account has sufficient fee juice by bridging from L1 if balance is below threshold.
567
+ * Bridges repeatedly until balance reaches the target (10k FJ).
568
+ * Used on startup/restart to top up when the account has run out after previous runs.
569
+ */
570
+ private async ensureFeeJuiceBalance(
571
+ account: AztecAddress,
572
+ token: TokenContract | PrivateTokenContract,
573
+ ): Promise<void> {
574
+ const { feePaymentMethod, l1RpcUrls } = this.config;
575
+ if (feePaymentMethod !== 'fee_juice' || !l1RpcUrls?.length) {
576
+ return;
577
+ }
578
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
579
+ if (!mnemonicOrPrivateKey) {
580
+ return;
581
+ }
582
+
583
+ let balance = await getFeeJuiceBalance(account, this.aztecNode);
584
+ if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
585
+ this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
586
+ return;
587
+ }
588
+
589
+ this.log.info(
590
+ `Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1 until ${FEE_JUICE_TOP_UP_TARGET}`,
591
+ );
592
+ const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
593
+ const minimalInteraction = isStandardTokenContract(token)
594
+ ? token.methods.transfer_in_public(account, account, 0n, 0)
595
+ : token.methods.transfer(0n, account, account);
596
+
597
+ while (balance < FEE_JUICE_TOP_UP_TARGET) {
598
+ const claim = await this.bridgeL1FeeJuice(account);
599
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
600
+ const { estimatedGas } = await minimalInteraction.simulate({
601
+ from: account,
602
+ fee: { estimateGas: true, paymentMethod },
603
+ });
604
+ const gasSettings = GasSettings.from({
605
+ ...estimatedGas!,
606
+ maxFeesPerGas,
607
+ maxPriorityFeesPerGas: GasFees.empty(),
608
+ });
609
+
610
+ await this.withNoMinTxsPerBlock(async () => {
611
+ const { txHash } = await minimalInteraction.send({
612
+ from: account,
613
+ fee: { gasSettings, paymentMethod },
614
+ wait: NO_WAIT,
615
+ });
616
+ this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
617
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
618
+ });
619
+ balance = await getFeeJuiceBalance(account, this.aztecNode);
620
+ this.log.info(`Fee juice balance after top-up: ${balance}`);
621
+ }
622
+ this.log.info(`Fee juice top-up complete for ${account.toString()}`);
623
+ }
624
+
454
625
  private async mintTokens(token: TokenContract | PrivateTokenContract, minter: AztecAddress) {
455
626
  const isStandardToken = isStandardTokenContract(token);
456
627
  let privateBalance = 0n;
@@ -483,8 +654,13 @@ export class BotFactory {
483
654
 
484
655
  // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
485
656
  const additionalScopes = isStandardToken ? undefined : [token.address];
657
+ const mintBatch = new BatchCall(token.wallet, calls);
486
658
  await this.withNoMinTxsPerBlock(async () => {
487
- const txHash = await new BatchCall(token.wallet, calls).send({ from: minter, additionalScopes, wait: NO_WAIT });
659
+ const { txHash } = await mintBatch.send({
660
+ from: minter,
661
+ additionalScopes,
662
+ wait: NO_WAIT,
663
+ });
488
664
  this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
489
665
  return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
490
666
  });
@@ -507,7 +683,6 @@ export class BotFactory {
507
683
  await this.withNoMinTxsPerBlock(() =>
508
684
  waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
509
685
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
510
- forPublicConsumption: false,
511
686
  }),
512
687
  );
513
688
  return existingClaim.claim;
@@ -546,7 +721,6 @@ export class BotFactory {
546
721
  await this.withNoMinTxsPerBlock(() =>
547
722
  waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
548
723
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
549
- forPublicConsumption: false,
550
724
  }),
551
725
  );
552
726
 
@@ -555,6 +729,19 @@ export class BotFactory {
555
729
  return claim as L2AmountClaim;
556
730
  }
557
731
 
732
+ /** Returns worst-case min fees across predicted slots, with fallback to current min fees. */
733
+ private async getMinFees(): Promise<GasFees> {
734
+ try {
735
+ const predicted = await this.aztecNode.getPredictedMinFees(ManaUsageEstimate.Limit);
736
+ if (predicted.length === 0) {
737
+ return this.aztecNode.getCurrentMinFees();
738
+ }
739
+ return predicted.reduce((worst, fees) => (fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst));
740
+ } catch {
741
+ return this.aztecNode.getCurrentMinFees();
742
+ }
743
+ }
744
+
558
745
  private async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
559
746
  if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
560
747
  this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
package/src/utils.ts CHANGED
@@ -15,8 +15,8 @@ export async function getBalances(
15
15
  who: AztecAddress,
16
16
  from?: AztecAddress,
17
17
  ): Promise<{ privateBalance: bigint; publicBalance: bigint }> {
18
- const privateBalance = await token.methods.balance_of_private(who).simulate({ from: from ?? who });
19
- const publicBalance = await token.methods.balance_of_public(who).simulate({ from: from ?? who });
18
+ const { result: privateBalance } = await token.methods.balance_of_private(who).simulate({ from: from ?? who });
19
+ const { result: publicBalance } = await token.methods.balance_of_public(who).simulate({ from: from ?? who });
20
20
  return { privateBalance, publicBalance };
21
21
  }
22
22
 
@@ -25,7 +25,7 @@ export async function getPrivateBalance(
25
25
  who: AztecAddress,
26
26
  from?: AztecAddress,
27
27
  ): Promise<bigint> {
28
- const privateBalance = await token.methods.get_balance(who).simulate({ from: from ?? who });
28
+ const { result: privateBalance } = await token.methods.get_balance(who).simulate({ from: from ?? who });
29
29
  return privateBalance;
30
30
  }
31
31