@aztec/bot 0.0.1-commit.96dac018d → 0.0.1-commit.993d240

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/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
  }
@@ -178,12 +189,8 @@ export class BotFactory {
178
189
  }
179
190
 
180
191
  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);
192
+ const deployOpts: DeployOptions = { from: deployer };
193
+ const deploy = TestContract.deploy(this.wallet, { salt: this.config.tokenSalt, universalDeploy: true });
187
194
  const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
188
195
  return TestContract.at(instance.address, this.wallet);
189
196
  }
@@ -208,7 +215,7 @@ export class BotFactory {
208
215
  const signingKey = deriveSigningKey(secret);
209
216
  const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
210
217
  const metadata = await this.wallet.getContractMetadata(accountManager.address);
211
- if (metadata.isContractInitialized) {
218
+ if (metadata.initializationStatus === ContractInitializationStatus.INITIALIZED) {
212
219
  this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
213
220
  const timer = new Timer();
214
221
  const address = accountManager.address;
@@ -223,13 +230,11 @@ export class BotFactory {
223
230
 
224
231
  const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
225
232
  const deployMethod = await accountManager.getDeployMethod();
226
- const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
227
- const gasSettings = GasSettings.default({ maxFeesPerGas });
228
233
 
229
234
  await this.withNoMinTxsPerBlock(async () => {
230
- const txHash = await deployMethod.send({
231
- from: AztecAddress.ZERO,
232
- fee: { gasSettings, paymentMethod },
235
+ const { txHash } = await deployMethod.send({
236
+ from: NO_FROM,
237
+ fee: { paymentMethod },
233
238
  wait: NO_WAIT,
234
239
  });
235
240
  this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
@@ -254,35 +259,95 @@ export class BotFactory {
254
259
  return accountManager.address;
255
260
  }
256
261
 
262
+ /**
263
+ * Setup token and refuel first: if the token already exists (restart scenario),
264
+ * run ensureFeeJuiceBalance before any step that might need fee juice. When deploying,
265
+ * use a bridge claim if balance is below threshold.
266
+ */
267
+ private async setupTokenWithOptionalEarlyRefuel(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
268
+ const token = await this.getTokenInstance(sender);
269
+ const address = token.address;
270
+ const metadata = await this.wallet.getContractMetadata(address);
271
+ if (metadata.isContractPublished) {
272
+ this.log.info(`Token at ${address.toString()} already deployed, refueling before setup`);
273
+ await this.ensureFeeJuiceBalance(sender, token);
274
+ }
275
+ return this.setupToken(sender);
276
+ }
277
+
278
+ /**
279
+ * Setup token0 for AMM with refuel-first behaviour when token already exists.
280
+ */
281
+ private async setupTokenContractWithOptionalEarlyRefuel(
282
+ deployer: AztecAddress,
283
+ salt: Fr,
284
+ name: string,
285
+ ticker: string,
286
+ decimals = 18,
287
+ ): Promise<TokenContract> {
288
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
289
+ const instance = await deploy.getInstance();
290
+ const metadata = await this.wallet.getContractMetadata(instance.address);
291
+ if (metadata.isContractPublished) {
292
+ this.log.info(`Token ${name} at ${instance.address.toString()} already deployed, refueling before setup`);
293
+ const token = TokenContract.at(instance.address, this.wallet);
294
+ await this.ensureFeeJuiceBalance(deployer, token);
295
+ }
296
+ return this.setupTokenContract(deployer, salt, name, ticker, decimals);
297
+ }
298
+
299
+ private async getTokenInstance(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
300
+ const salt = this.config.tokenSalt;
301
+ if (this.config.contract === SupportedTokenContracts.TokenContract) {
302
+ const deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
303
+ const instance = await deploy.getInstance();
304
+ return TokenContract.at(instance.address, this.wallet);
305
+ }
306
+ if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
307
+ const tokenSecretKey = Fr.random();
308
+ const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
309
+ const deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
310
+ salt,
311
+ universalDeploy: true,
312
+ publicKeys: tokenPublicKeys,
313
+ });
314
+ const instance = await deploy.getInstance();
315
+ return PrivateTokenContract.at(instance.address, this.wallet);
316
+ }
317
+ throw new Error(`Unsupported token contract type: ${this.config.contract}`);
318
+ }
319
+
257
320
  /**
258
321
  * 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.
322
+ * Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
323
+ * @param sender - Aztec address to deploy the token contract from.
324
+ * @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
325
+ * @returns The TokenContract or PrivateTokenContract instance.
261
326
  */
262
327
  private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
263
328
  let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
264
- let tokenInstance: ContractInstanceWithAddress | undefined;
265
- const deployOpts: DeployOptions = {
266
- from: sender,
267
- contractAddressSalt: this.config.tokenSalt,
268
- universalDeploy: true,
269
- };
329
+ const salt = this.config.tokenSalt;
330
+ const deployOpts: DeployOptions = { from: sender };
270
331
  let token: TokenContract | PrivateTokenContract;
271
332
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
272
- deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
273
- tokenInstance = await deploy.getInstance(deployOpts);
274
- token = TokenContract.at(tokenInstance.address, this.wallet);
333
+ deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
334
+ const instance = await deploy.getInstance();
335
+ token = TokenContract.at(instance.address, this.wallet);
275
336
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
276
337
  // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
277
338
  const tokenSecretKey = Fr.random();
278
339
  const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
279
- deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
340
+ deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
341
+ salt,
342
+ universalDeploy: true,
343
+ publicKeys: tokenPublicKeys,
344
+ });
280
345
  deployOpts.skipInstancePublication = true;
281
346
  deployOpts.skipClassPublication = true;
282
347
  deployOpts.skipInitialization = false;
283
348
 
284
349
  // Register the contract with the secret key before deployment
285
- tokenInstance = await deploy.getInstance(deployOpts);
350
+ const tokenInstance = await deploy.getInstance();
286
351
  token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
287
352
  await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
288
353
  // The contract constructor initializes private storage vars that need the contract's own nullifier key.
@@ -291,20 +356,7 @@ export class BotFactory {
291
356
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
292
357
  }
293
358
 
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
- }
359
+ await this.registerOrDeployContract('token', deploy, deployOpts);
308
360
  return token;
309
361
  }
310
362
 
@@ -315,33 +367,38 @@ export class BotFactory {
315
367
  */
316
368
  private async setupTokenContract(
317
369
  deployer: AztecAddress,
318
- contractAddressSalt: Fr,
370
+ salt: Fr,
319
371
  name: string,
320
372
  ticker: string,
321
373
  decimals = 18,
322
374
  ): Promise<TokenContract> {
323
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
324
- const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
375
+ const deployOpts: DeployOptions = { from: deployer };
376
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
325
377
  const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
326
378
  return TokenContract.at(instance.address, this.wallet);
327
379
  }
328
380
 
329
381
  private async setupAmmContract(
330
382
  deployer: AztecAddress,
331
- contractAddressSalt: Fr,
383
+ salt: Fr,
332
384
  token0: TokenContract,
333
385
  token1: TokenContract,
334
386
  lpToken: TokenContract,
335
387
  ): Promise<AMMContract> {
336
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
337
- const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
388
+ const deployOpts: DeployOptions = { from: deployer };
389
+ const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address, {
390
+ salt,
391
+ universalDeploy: true,
392
+ });
338
393
  const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
339
394
  const amm = AMMContract.at(instance.address, this.wallet);
340
395
 
341
396
  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 } });
397
+ const setMinterInteraction = lpToken.methods.set_minter(amm.address, true);
398
+ const { receipt: minterReceipt } = await setMinterInteraction.send({
399
+ from: deployer,
400
+ wait: { timeout: this.config.txMinedWaitSeconds },
401
+ });
345
402
  this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
346
403
  this.log.info(`Liquidity token initialized`);
347
404
 
@@ -358,9 +415,18 @@ export class BotFactory {
358
415
  ): Promise<void> {
359
416
  const getPrivateBalances = () =>
360
417
  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 }),
418
+ token0.methods
419
+ .balance_of_private(liquidityProvider)
420
+ .simulate({ from: liquidityProvider })
421
+ .then(r => r.result),
422
+ token1.methods
423
+ .balance_of_private(liquidityProvider)
424
+ .simulate({ from: liquidityProvider })
425
+ .then(r => r.result),
426
+ lpToken.methods
427
+ .balance_of_private(liquidityProvider)
428
+ .simulate({ from: liquidityProvider })
429
+ .then(r => r.result),
364
430
  ]);
365
431
 
366
432
  const authwitNonce = Fr.random();
@@ -401,20 +467,29 @@ export class BotFactory {
401
467
  .getFunctionCall(),
402
468
  });
403
469
 
404
- const mintReceipt = await new BatchCall(this.wallet, [
470
+ const mintBatch = new BatchCall(this.wallet, [
405
471
  token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
406
472
  token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
407
- ]).send({ from: liquidityProvider, wait: { timeout: this.config.txMinedWaitSeconds } });
473
+ ]);
474
+ const { receipt: mintReceipt } = await mintBatch.send({
475
+ from: liquidityProvider,
476
+ wait: { timeout: this.config.txMinedWaitSeconds },
477
+ });
408
478
 
409
479
  this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
410
480
 
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
- });
481
+ const addLiquidityInteraction = amm.methods.add_liquidity(
482
+ amount0Max,
483
+ amount1Max,
484
+ amount0Min,
485
+ amount1Min,
486
+ authwitNonce,
487
+ );
488
+ const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
489
+ from: liquidityProvider,
490
+ authWitnesses: [token0Authwit, token1Authwit],
491
+ wait: { timeout: this.config.txMinedWaitSeconds },
492
+ });
418
493
 
419
494
  this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`);
420
495
  this.log.info(`Liquidity added`);
@@ -430,19 +505,49 @@ export class BotFactory {
430
505
  deploy: DeployMethod<T>,
431
506
  deployOpts: DeployOptions,
432
507
  ): Promise<ContractInstanceWithAddress> {
433
- const instance = await deploy.getInstance(deployOpts);
508
+ const instance = await deploy.getInstance();
434
509
  const address = instance.address;
435
510
  const metadata = await this.wallet.getContractMetadata(address);
436
511
  if (metadata.isContractPublished) {
437
512
  this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
438
513
  await deploy.register();
439
514
  } 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
- });
515
+ const sender = deployOpts.from === NO_FROM ? undefined : deployOpts.from;
516
+ const balance = sender ? await getFeeJuiceBalance(sender, this.aztecNode) : 0n;
517
+ const useClaim =
518
+ sender &&
519
+ balance < FEE_JUICE_TOP_UP_THRESHOLD &&
520
+ this.config.feePaymentMethod === 'fee_juice' &&
521
+ !!this.config.l1RpcUrls?.length;
522
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
523
+
524
+ if (useClaim && mnemonicOrPrivateKey) {
525
+ const claim = await this.getOrCreateBridgeClaim(sender!);
526
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(sender!, claim);
527
+ const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true, paymentMethod } });
528
+ const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
529
+ const gasSettings = GasSettings.from({
530
+ ...estimatedGas!,
531
+ maxFeesPerGas,
532
+ maxPriorityFeesPerGas: GasFees.empty(),
533
+ });
534
+ await this.withNoMinTxsPerBlock(async () => {
535
+ const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings, paymentMethod }, wait: NO_WAIT });
536
+ this.log.info(
537
+ `Sent contract ${name} deploy tx ${txHash.toString()} (using bridge claim, balance was ${balance})`,
538
+ );
539
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
540
+ });
541
+ await this.store.deleteBridgeClaim(sender!);
542
+ } else {
543
+ const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true } });
544
+ this.log.info(`Deploying contract ${name} at ${address.toString()}`, { estimatedGas });
545
+ await this.withNoMinTxsPerBlock(async () => {
546
+ const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings: estimatedGas }, wait: NO_WAIT });
547
+ this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
548
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
549
+ });
550
+ }
446
551
  }
447
552
  return instance;
448
553
  }
@@ -451,6 +556,66 @@ export class BotFactory {
451
556
  * Mints private and public tokens for the sender if their balance is below the minimum.
452
557
  * @param token - Token contract.
453
558
  */
559
+ /**
560
+ * Ensures the account has sufficient fee juice by bridging from L1 if balance is below threshold.
561
+ * Bridges repeatedly until balance reaches the target (10k FJ).
562
+ * Used on startup/restart to top up when the account has run out after previous runs.
563
+ */
564
+ private async ensureFeeJuiceBalance(
565
+ account: AztecAddress,
566
+ token: TokenContract | PrivateTokenContract,
567
+ ): Promise<void> {
568
+ const { feePaymentMethod, l1RpcUrls } = this.config;
569
+ if (feePaymentMethod !== 'fee_juice' || !l1RpcUrls?.length) {
570
+ return;
571
+ }
572
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
573
+ if (!mnemonicOrPrivateKey) {
574
+ return;
575
+ }
576
+
577
+ let balance = await getFeeJuiceBalance(account, this.aztecNode);
578
+ if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
579
+ this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
580
+ return;
581
+ }
582
+
583
+ this.log.info(
584
+ `Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1 until ${FEE_JUICE_TOP_UP_TARGET}`,
585
+ );
586
+ const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
587
+ const minimalInteraction = isStandardTokenContract(token)
588
+ ? token.methods.transfer_in_public(account, account, 0n, 0)
589
+ : token.methods.transfer(0n, account, account);
590
+
591
+ while (balance < FEE_JUICE_TOP_UP_TARGET) {
592
+ const claim = await this.bridgeL1FeeJuice(account);
593
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
594
+ const { estimatedGas } = await minimalInteraction.simulate({
595
+ from: account,
596
+ fee: { estimateGas: true, paymentMethod },
597
+ });
598
+ const gasSettings = GasSettings.from({
599
+ ...estimatedGas!,
600
+ maxFeesPerGas,
601
+ maxPriorityFeesPerGas: GasFees.empty(),
602
+ });
603
+
604
+ await this.withNoMinTxsPerBlock(async () => {
605
+ const { txHash } = await minimalInteraction.send({
606
+ from: account,
607
+ fee: { gasSettings, paymentMethod },
608
+ wait: NO_WAIT,
609
+ });
610
+ this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
611
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
612
+ });
613
+ balance = await getFeeJuiceBalance(account, this.aztecNode);
614
+ this.log.info(`Fee juice balance after top-up: ${balance}`);
615
+ }
616
+ this.log.info(`Fee juice top-up complete for ${account.toString()}`);
617
+ }
618
+
454
619
  private async mintTokens(token: TokenContract | PrivateTokenContract, minter: AztecAddress) {
455
620
  const isStandardToken = isStandardTokenContract(token);
456
621
  let privateBalance = 0n;
@@ -483,8 +648,13 @@ export class BotFactory {
483
648
 
484
649
  // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
485
650
  const additionalScopes = isStandardToken ? undefined : [token.address];
651
+ const mintBatch = new BatchCall(token.wallet, calls);
486
652
  await this.withNoMinTxsPerBlock(async () => {
487
- const txHash = await new BatchCall(token.wallet, calls).send({ from: minter, additionalScopes, wait: NO_WAIT });
653
+ const { txHash } = await mintBatch.send({
654
+ from: minter,
655
+ additionalScopes,
656
+ wait: NO_WAIT,
657
+ });
488
658
  this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
489
659
  return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
490
660
  });
@@ -507,7 +677,6 @@ export class BotFactory {
507
677
  await this.withNoMinTxsPerBlock(() =>
508
678
  waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
509
679
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
510
- forPublicConsumption: false,
511
680
  }),
512
681
  );
513
682
  return existingClaim.claim;
@@ -546,7 +715,6 @@ export class BotFactory {
546
715
  await this.withNoMinTxsPerBlock(() =>
547
716
  waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
548
717
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
549
- forPublicConsumption: false,
550
718
  }),
551
719
  );
552
720
 
@@ -555,6 +723,19 @@ export class BotFactory {
555
723
  return claim as L2AmountClaim;
556
724
  }
557
725
 
726
+ /** Returns worst-case min fees across predicted slots, with fallback to current min fees. */
727
+ private async getMinFees(): Promise<GasFees> {
728
+ try {
729
+ const predicted = await this.aztecNode.getPredictedMinFees(ManaUsageEstimate.Limit);
730
+ if (predicted.length === 0) {
731
+ return this.aztecNode.getCurrentMinFees();
732
+ }
733
+ return predicted.reduce((worst, fees) => (fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst));
734
+ } catch {
735
+ return this.aztecNode.getCurrentMinFees();
736
+ }
737
+ }
738
+
558
739
  private async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
559
740
  if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
560
741
  this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
package/src/interface.ts CHANGED
@@ -22,11 +22,11 @@ export interface BotRunnerApi {
22
22
  }
23
23
 
24
24
  export const BotRunnerApiSchema: ApiSchemaFor<BotRunnerApi> = {
25
- start: z.function().args().returns(z.void()),
26
- stop: z.function().args().returns(z.void()),
27
- run: z.function().args().returns(z.void()),
28
- setup: z.function().args().returns(z.void()),
29
- getInfo: z.function().args().returns(BotInfoSchema),
30
- getConfig: z.function().args().returns(BotConfigSchema),
31
- update: z.function().args(BotConfigSchema).returns(z.void()),
25
+ start: z.function({ input: z.tuple([]), output: z.void() }),
26
+ stop: z.function({ input: z.tuple([]), output: z.void() }),
27
+ run: z.function({ input: z.tuple([]), output: z.void() }),
28
+ setup: z.function({ input: z.tuple([]), output: z.void() }),
29
+ getInfo: z.function({ input: z.tuple([]), output: BotInfoSchema }),
30
+ getConfig: z.function({ input: z.tuple([]), output: BotConfigSchema }),
31
+ update: z.function({ input: z.tuple([BotConfigSchema]), output: z.void() }),
32
32
  };
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