@aztec/bot 0.0.1-commit.9ef841308 → 0.0.1-commit.a4600f49

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/bot.ts CHANGED
@@ -4,6 +4,7 @@ import { TxHash } from '@aztec/aztec.js/tx';
4
4
  import { times } from '@aztec/foundation/collection';
5
5
  import type { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
6
6
  import type { TokenContract } from '@aztec/noir-contracts.js/Token';
7
+ import type { BlockTag } from '@aztec/stdlib/block';
7
8
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
8
9
  import type { EmbeddedWallet } from '@aztec/wallets/embedded';
9
10
 
@@ -33,6 +34,7 @@ export class Bot extends BaseBot {
33
34
  aztecNode: AztecNode,
34
35
  aztecNodeAdmin: AztecNodeAdmin | undefined,
35
36
  store: BotStore,
37
+ syncChainTip?: BlockTag,
36
38
  ): Promise<Bot> {
37
39
  const { defaultAccountAddress, token, recipient } = await new BotFactory(
38
40
  config,
@@ -40,6 +42,7 @@ export class Bot extends BaseBot {
40
42
  store,
41
43
  aztecNode,
42
44
  aztecNodeAdmin,
45
+ syncChainTip,
43
46
  ).setup();
44
47
  return new Bot(aztecNode, wallet, defaultAccountAddress, token, recipient, config);
45
48
  }
package/src/config.ts CHANGED
@@ -2,6 +2,7 @@ import {
2
2
  type ConfigMappingsType,
3
3
  SecretValue,
4
4
  booleanConfigHelper,
5
+ floatConfigHelper,
5
6
  getConfigFromMappings,
6
7
  getDefaultConfig,
7
8
  numberConfigHelper,
@@ -103,7 +104,7 @@ export const BotConfigSchema = zodFor<BotConfig>()(
103
104
  privateTransfersPerTx: z.number().int().nonnegative(),
104
105
  publicTransfersPerTx: z.number().int().nonnegative(),
105
106
  feePaymentMethod: z.literal('fee_juice'),
106
- minFeePadding: z.number().int().nonnegative(),
107
+ minFeePadding: z.number().nonnegative(),
107
108
  noStart: z.boolean(),
108
109
  txMinedWaitSeconds: z.number(),
109
110
  followChain: z.enum(BotFollowChain),
@@ -204,7 +205,7 @@ export const botConfigMappings: ConfigMappingsType<BotConfig> = {
204
205
  minFeePadding: {
205
206
  env: 'BOT_MIN_FEE_PADDING',
206
207
  description: 'How much is the bot willing to overpay vs. the current base fee',
207
- ...numberConfigHelper(3),
208
+ ...floatConfigHelper(3),
208
209
  },
209
210
  noStart: {
210
211
  env: 'BOT_NO_START',
@@ -26,11 +26,12 @@
26
26
  import { AztecAddress } from '@aztec/aztec.js/addresses';
27
27
  import { BatchCall, NO_WAIT } from '@aztec/aztec.js/contracts';
28
28
  import { isL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
29
- import { TxHash, TxReceipt } from '@aztec/aztec.js/tx';
29
+ import type { TxHash, TxReceipt } from '@aztec/aztec.js/tx';
30
30
  import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
31
31
  import { Fr } from '@aztec/foundation/curves/bn254';
32
32
  import { EthAddress } from '@aztec/foundation/eth-address';
33
33
  import type { TestContract } from '@aztec/noir-test-contracts.js/Test';
34
+ import type { BlockTag } from '@aztec/stdlib/block';
34
35
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
35
36
  import type { EmbeddedWallet } from '@aztec/wallets/embedded';
36
37
 
@@ -60,6 +61,7 @@ export class CrossChainBot extends BaseBot {
60
61
  private readonly rollupVersion: bigint,
61
62
  private readonly store: BotStore,
62
63
  config: BotConfig,
64
+ private readonly syncChainTip?: BlockTag,
63
65
  ) {
64
66
  super(node, wallet, defaultAccountAddress, config);
65
67
  }
@@ -70,11 +72,12 @@ export class CrossChainBot extends BaseBot {
70
72
  aztecNode: AztecNode,
71
73
  aztecNodeAdmin: AztecNodeAdmin | undefined,
72
74
  store: BotStore,
75
+ syncChainTip?: BlockTag,
73
76
  ): Promise<CrossChainBot> {
74
77
  if (config.followChain === 'NONE') {
75
78
  throw new Error(`CrossChainBot requires followChain to be set (got NONE)`);
76
79
  }
77
- const factory = new BotFactory(config, wallet, store, aztecNode, aztecNodeAdmin);
80
+ const factory = new BotFactory(config, wallet, store, aztecNode, aztecNodeAdmin, syncChainTip);
78
81
  const { defaultAccountAddress, contract, l1Client, rollupVersion } = await factory.setupCrossChain();
79
82
  const l1Recipient = EthAddress.fromString(l1Client.account!.address);
80
83
  const { l1ContractAddresses } = await aztecNode.getNodeInfo();
@@ -90,6 +93,7 @@ export class CrossChainBot extends BaseBot {
90
93
  rollupVersion,
91
94
  store,
92
95
  config,
96
+ syncChainTip,
93
97
  );
94
98
  }
95
99
 
@@ -146,9 +150,10 @@ export class CrossChainBot extends BaseBot {
146
150
 
147
151
  protected override async onTxMined(receipt: TxReceipt, logCtx: object): Promise<void> {
148
152
  // Verify L2→L1 messages appeared in this tx's effects
149
- const indexed = await this.node.getTxEffect(receipt.txHash);
150
- if (indexed) {
151
- const l2ToL1Msgs = indexed.data.l2ToL1Msgs.filter(m => !m.isZero());
153
+ const minedReceipt = await this.node.getTxReceipt(receipt.txHash, { includeTxEffect: true });
154
+ const l2ToL1MsgsRaw = minedReceipt.txEffect?.l2ToL1Msgs;
155
+ if (l2ToL1MsgsRaw) {
156
+ const l2ToL1Msgs = l2ToL1MsgsRaw.filter(m => !m.isZero());
152
157
  if (l2ToL1Msgs.length >= this.config.l2ToL1MessagesPerTx) {
153
158
  this.l2ToL1Sent += l2ToL1Msgs.length;
154
159
  } else {
@@ -175,7 +180,7 @@ export class CrossChainBot extends BaseBot {
175
180
  ): Promise<PendingL1ToL2Message | undefined> {
176
181
  const now = Date.now();
177
182
  for (const msg of pendingMessages) {
178
- const ready = await isL1ToL2MessageReady(this.node, Fr.fromHexString(msg.msgHash));
183
+ const ready = await isL1ToL2MessageReady(this.node, Fr.fromHexString(msg.msgHash), this.syncChainTip);
179
184
  if (ready) {
180
185
  return msg;
181
186
  }
package/src/factory.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { getInitialTestAccountsData } from '@aztec/accounts/testing';
2
- import { NO_FROM } from '@aztec/aztec.js/account';
3
2
  import { AztecAddress } from '@aztec/aztec.js/addresses';
4
3
  import {
5
4
  BatchCall,
@@ -16,18 +15,18 @@ import { deriveKeys } from '@aztec/aztec.js/keys';
16
15
  import { createLogger } from '@aztec/aztec.js/log';
17
16
  import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
18
17
  import { waitForTx } from '@aztec/aztec.js/node';
19
- import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
18
+ import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
20
19
  import { createEthereumChain } from '@aztec/ethereum/chain';
21
20
  import { createExtendedL1Client } from '@aztec/ethereum/client';
22
21
  import { RollupContract } from '@aztec/ethereum/contracts';
23
22
  import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
24
23
  import { Fr } from '@aztec/foundation/curves/bn254';
25
24
  import { EthAddress } from '@aztec/foundation/eth-address';
26
- import { Timer } from '@aztec/foundation/timer';
27
25
  import { AMMContract } from '@aztec/noir-contracts.js/AMM';
28
26
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
29
27
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
30
28
  import { TestContract } from '@aztec/noir-test-contracts.js/Test';
29
+ import type { BlockTag } from '@aztec/stdlib/block';
31
30
  import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
32
31
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
33
32
  import { deriveSigningKey } from '@aztec/stdlib/keys';
@@ -40,6 +39,7 @@ import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils
40
39
 
41
40
  const MINT_BALANCE = 1e12;
42
41
  const MIN_BALANCE = 1e3;
42
+ const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
43
43
 
44
44
  export class BotFactory {
45
45
  private log = createLogger('bot');
@@ -50,6 +50,7 @@ export class BotFactory {
50
50
  private readonly store: BotStore,
51
51
  private readonly aztecNode: AztecNode,
52
52
  private readonly aztecNodeAdmin?: AztecNodeAdmin,
53
+ private readonly syncChainTip?: BlockTag,
53
54
  ) {
54
55
  // Set fee padding on the wallet so that all transactions during setup
55
56
  // (token deploy, minting, etc.) use the configured padding, not the default.
@@ -69,6 +70,7 @@ export class BotFactory {
69
70
  }> {
70
71
  const defaultAccountAddress = await this.setupAccount();
71
72
  const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
73
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
72
74
  const token = await this.setupToken(defaultAccountAddress);
73
75
  await this.mintTokens(token, defaultAccountAddress);
74
76
  return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
@@ -83,6 +85,7 @@ export class BotFactory {
83
85
  node: AztecNode;
84
86
  }> {
85
87
  const defaultAccountAddress = await this.setupAccount();
88
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
86
89
  const token0 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
87
90
  const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
88
91
  const liquidityToken = await this.setupTokenContract(
@@ -118,6 +121,7 @@ export class BotFactory {
118
121
  rollupVersion: bigint;
119
122
  }> {
120
123
  const defaultAccountAddress = await this.setupAccount();
124
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
121
125
 
122
126
  // Create L1 client (same pattern as bridgeL1FeeJuice)
123
127
  const l1RpcUrls = this.config.l1RpcUrls;
@@ -136,7 +140,7 @@ export class BotFactory {
136
140
  const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
137
141
  const rollupVersion = await rollupContract.getVersion();
138
142
 
139
- // Deploy TestContract
143
+ // Deploy TestContract (pays from the standing balance funded above).
140
144
  const contract = await this.setupTestContract(defaultAccountAddress);
141
145
 
142
146
  // Recover any pending messages from store (clean up stale ones first)
@@ -163,6 +167,7 @@ export class BotFactory {
163
167
  const firstMsg = allMessages[0];
164
168
  await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
165
169
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
170
+ chainTip: this.syncChainTip,
166
171
  });
167
172
  this.log.info(`First L1→L2 message is ready`);
168
173
  }
@@ -178,12 +183,8 @@ export class BotFactory {
178
183
  }
179
184
 
180
185
  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);
186
+ const deployOpts: DeployOptions = { from: deployer };
187
+ const deploy = TestContract.deploy(this.wallet, { salt: this.config.tokenSalt, universalDeploy: true });
187
188
  const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
188
189
  return TestContract.at(instance.address, this.wallet);
189
190
  }
@@ -203,48 +204,16 @@ export class BotFactory {
203
204
  }
204
205
  }
205
206
 
206
- private async setupAccountWithPrivateKey(secret: Fr) {
207
- const salt = this.config.senderSalt ?? Fr.ONE;
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.initializationStatus === ContractInitializationStatus.INITIALIZED) {
212
- this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
213
- const timer = new Timer();
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;
218
- } else {
219
- const address = accountManager.address;
220
- this.log.info(`Deploying account at ${address}`);
221
-
222
- const claim = await this.getOrCreateBridgeClaim(address);
223
-
224
- const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
225
- const deployMethod = await accountManager.getDeployMethod();
226
-
227
- await this.withNoMinTxsPerBlock(async () => {
228
- const { txHash } = await deployMethod.send({
229
- from: NO_FROM,
230
- fee: { paymentMethod },
231
- wait: NO_WAIT,
232
- });
233
- this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
234
- return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
235
- });
236
- this.log.info(`Account deployed at ${address}`);
237
-
238
- // Clean up the consumed bridge claim
239
- await this.store.deleteBridgeClaim(address);
240
-
241
- return accountManager.address;
242
- }
243
- }
244
-
207
+ /**
208
+ * Keyless fallback for tests and local dev: reuses the first genesis test account, whose address is
209
+ * pre-funded with fee juice via `initialFundedAccounts`. The test accounts are initializerless, so this
210
+ * must create an initializerless account for the address to match the funded one. Production bots set a
211
+ * sender private key and fund the resulting initializerless account from L1 instead; see
212
+ * setupAccountWithPrivateKey.
213
+ */
245
214
  private async setupTestAccount() {
246
215
  const [initialAccountData] = await getInitialTestAccountsData();
247
- const accountManager = await this.wallet.createSchnorrAccount(
216
+ const accountManager = await this.wallet.createSchnorrInitializerlessAccount(
248
217
  initialAccountData.secret,
249
218
  initialAccountData.salt,
250
219
  initialAccountData.signingKey,
@@ -252,35 +221,44 @@ export class BotFactory {
252
221
  return accountManager.address;
253
222
  }
254
223
 
224
+ private async setupAccountWithPrivateKey(secret: Fr) {
225
+ const salt = this.config.senderSalt ?? Fr.ONE;
226
+ const signingKey = deriveSigningKey(secret);
227
+ const accountManager = await this.wallet.createSchnorrInitializerlessAccount(secret, salt, signingKey);
228
+ return accountManager.address;
229
+ }
230
+
255
231
  /**
256
232
  * Checks if the token contract is deployed and deploys it if necessary.
257
- * @param wallet - Wallet to deploy the token contract from.
258
- * @returns The TokenContract instance.
233
+ * Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
234
+ * @param sender - Aztec address to deploy the token contract from.
235
+ * @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
236
+ * @returns The TokenContract or PrivateTokenContract instance.
259
237
  */
260
238
  private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
261
239
  let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
262
- let tokenInstance: ContractInstanceWithAddress | undefined;
263
- const deployOpts: DeployOptions = {
264
- from: sender,
265
- contractAddressSalt: this.config.tokenSalt,
266
- universalDeploy: true,
267
- };
240
+ const salt = this.config.tokenSalt;
241
+ const deployOpts: DeployOptions = { from: sender };
268
242
  let token: TokenContract | PrivateTokenContract;
269
243
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
270
- deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
271
- tokenInstance = await deploy.getInstance(deployOpts);
272
- token = TokenContract.at(tokenInstance.address, this.wallet);
244
+ deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
245
+ const instance = await deploy.getInstance();
246
+ token = TokenContract.at(instance.address, this.wallet);
273
247
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
274
248
  // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
275
249
  const tokenSecretKey = Fr.random();
276
250
  const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
277
- deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
251
+ deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
252
+ salt,
253
+ universalDeploy: true,
254
+ publicKeys: tokenPublicKeys,
255
+ });
278
256
  deployOpts.skipInstancePublication = true;
279
257
  deployOpts.skipClassPublication = true;
280
258
  deployOpts.skipInitialization = false;
281
259
 
282
260
  // Register the contract with the secret key before deployment
283
- tokenInstance = await deploy.getInstance(deployOpts);
261
+ const tokenInstance = await deploy.getInstance();
284
262
  token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
285
263
  await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
286
264
  // The contract constructor initializes private storage vars that need the contract's own nullifier key.
@@ -289,20 +267,7 @@ export class BotFactory {
289
267
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
290
268
  }
291
269
 
292
- const address = tokenInstance?.address ?? (await deploy.getInstance(deployOpts)).address;
293
- const metadata = await this.wallet.getContractMetadata(address);
294
- if (metadata.isContractPublished) {
295
- this.log.info(`Token at ${address.toString()} already deployed`);
296
- await deploy.register();
297
- } else {
298
- this.log.info(`Deploying token contract at ${address.toString()}`);
299
- const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
300
- this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
301
- await this.withNoMinTxsPerBlock(async () => {
302
- await waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
303
- return token;
304
- });
305
- }
270
+ await this.registerOrDeployContract('token', deploy, deployOpts);
306
271
  return token;
307
272
  }
308
273
 
@@ -313,26 +278,29 @@ export class BotFactory {
313
278
  */
314
279
  private async setupTokenContract(
315
280
  deployer: AztecAddress,
316
- contractAddressSalt: Fr,
281
+ salt: Fr,
317
282
  name: string,
318
283
  ticker: string,
319
284
  decimals = 18,
320
285
  ): Promise<TokenContract> {
321
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
322
- const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
286
+ const deployOpts: DeployOptions = { from: deployer };
287
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
323
288
  const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
324
289
  return TokenContract.at(instance.address, this.wallet);
325
290
  }
326
291
 
327
292
  private async setupAmmContract(
328
293
  deployer: AztecAddress,
329
- contractAddressSalt: Fr,
294
+ salt: Fr,
330
295
  token0: TokenContract,
331
296
  token1: TokenContract,
332
297
  lpToken: TokenContract,
333
298
  ): Promise<AMMContract> {
334
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
335
- const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
299
+ const deployOpts: DeployOptions = { from: deployer };
300
+ const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address, {
301
+ salt,
302
+ universalDeploy: true,
303
+ });
336
304
  const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
337
305
  const amm = AMMContract.at(instance.address, this.wallet);
338
306
 
@@ -448,27 +416,75 @@ export class BotFactory {
448
416
  deploy: DeployMethod<T>,
449
417
  deployOpts: DeployOptions,
450
418
  ): Promise<ContractInstanceWithAddress> {
451
- const instance = await deploy.getInstance(deployOpts);
419
+ const instance = await deploy.getInstance();
452
420
  const address = instance.address;
453
421
  const metadata = await this.wallet.getContractMetadata(address);
454
422
  if (metadata.isContractPublished) {
455
423
  this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
456
424
  await deploy.register();
457
- } else {
458
- this.log.info(`Deploying contract ${name} at ${address.toString()}`);
459
- await this.withNoMinTxsPerBlock(async () => {
460
- const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
461
- this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
462
- return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
463
- });
425
+ return instance;
464
426
  }
427
+
428
+ // Setup always runs ensureFeeJuiceBalance before any deploy, so the account pays from its standing
429
+ // balance here. No manual gas estimation: the embedded wallet simulates before sending and derives
430
+ // the gas limits and padded maxFeesPerGas itself.
431
+ this.log.info(`Deploying contract ${name} at ${address.toString()}`);
432
+ await this.withNoMinTxsPerBlock(async () => {
433
+ const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
434
+ this.log.info(`Sent contract ${name} deploy tx ${txHash.toString()}`);
435
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
436
+ });
437
+
465
438
  return instance;
466
439
  }
467
440
 
441
+ /** True when the config allows bridging fee juice from L1 (fee_juice mode, an L1 RPC, and an L1 key). */
442
+ private isL1BridgingConfigured(): boolean {
443
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
444
+ return this.config.feePaymentMethod === 'fee_juice' && !!this.config.l1RpcUrls?.length && !!mnemonicOrPrivateKey;
445
+ }
446
+
468
447
  /**
469
- * Mints private and public tokens for the sender if their balance is below the minimum.
470
- * @param token - Token contract.
448
+ * Ensures the account holds enough fee juice before any other setup step. The account starts empty
449
+ * (initializerless accounts have no deployment tx) and the runtime loop pays fees from this balance and
450
+ * never refuels itself, so every flow funds the account up front. Bridges claims from L1 and consumes
451
+ * each with a claim-only tx until the balance clears the threshold, working from a zero (fresh run) or
452
+ * drained (restart) balance. Each bridge mints a fixed amount well above the threshold, so this is a
453
+ * single bridge in practice. No-op when L1 bridging is not configured or the balance is already above
454
+ * the threshold.
471
455
  */
456
+ private async ensureFeeJuiceBalance(account: AztecAddress): Promise<void> {
457
+ if (!this.isL1BridgingConfigured()) {
458
+ return;
459
+ }
460
+
461
+ let balance = await getFeeJuiceBalance(account, this.aztecNode);
462
+ if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
463
+ this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
464
+ return;
465
+ }
466
+
467
+ this.log.info(`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1`);
468
+
469
+ while (balance < FEE_JUICE_TOP_UP_THRESHOLD) {
470
+ // Persist the claim before consuming it: if the top-up tx fails or the bot crashes mid-loop, the
471
+ // next run reuses the pending claim instead of bridging again (and wasting the bridged funds).
472
+ const claim = await this.getOrCreateBridgeClaim(account);
473
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
474
+
475
+ await this.withNoMinTxsPerBlock(async () => {
476
+ const executionPayload = await paymentMethod.getExecutionPayload();
477
+ const { txHash } = await this.wallet.sendTx(executionPayload, { from: account, wait: NO_WAIT });
478
+ this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
479
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
480
+ });
481
+ await this.store.deleteBridgeClaim(account);
482
+ balance = await getFeeJuiceBalance(account, this.aztecNode);
483
+ this.log.info(`Fee juice balance after top-up: ${balance}`);
484
+ }
485
+ this.log.info(`Fee juice top-up complete for ${account.toString()}`);
486
+ }
487
+
472
488
  private async mintTokens(token: TokenContract | PrivateTokenContract, minter: AztecAddress) {
473
489
  const isStandardToken = isStandardTokenContract(token);
474
490
  let privateBalance = 0n;
@@ -514,22 +530,20 @@ export class BotFactory {
514
530
  }
515
531
 
516
532
  /**
517
- * Gets or creates a bridge claim for the recipient.
518
- * Checks if a claim already exists in the store and reuses it if valid.
519
- * Only creates a new bridge if fee juice balance is below threshold.
533
+ * Returns a usable bridge claim for the recipient, reusing a persisted one when its L1→L2 message is
534
+ * still available (resuming a top-up that failed or crashed before the claim was consumed) and bridging
535
+ * a fresh claim otherwise. The caller deletes the claim from the store once it has been consumed.
520
536
  */
521
537
  private async getOrCreateBridgeClaim(recipient: AztecAddress): Promise<L2AmountClaim> {
522
- // Check if we have an existing claim in the store
523
538
  const existingClaim = await this.store.getBridgeClaim(recipient);
524
539
  if (existingClaim) {
525
540
  this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
526
-
527
- // Check if the message is ready on L2
528
541
  try {
529
542
  const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
530
543
  await this.withNoMinTxsPerBlock(() =>
531
544
  waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
532
545
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
546
+ chainTip: this.syncChainTip,
533
547
  }),
534
548
  );
535
549
  return existingClaim.claim;
@@ -541,7 +555,6 @@ export class BotFactory {
541
555
 
542
556
  const claim = await this.bridgeL1FeeJuice(recipient);
543
557
  await this.store.saveBridgeClaim(recipient, claim);
544
-
545
558
  return claim;
546
559
  }
547
560
 
@@ -568,6 +581,7 @@ export class BotFactory {
568
581
  await this.withNoMinTxsPerBlock(() =>
569
582
  waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
570
583
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
584
+ chainTip: this.syncChainTip,
571
585
  }),
572
586
  );
573
587
 
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/runner.ts CHANGED
@@ -2,6 +2,7 @@ import { createLogger } from '@aztec/aztec.js/log';
2
2
  import type { AztecNode } from '@aztec/aztec.js/node';
3
3
  import { omit } from '@aztec/foundation/collection';
4
4
  import { RunningPromise } from '@aztec/foundation/running-promise';
5
+ import type { BlockTag } from '@aztec/stdlib/block';
5
6
  import type { AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
6
7
  import { type TelemetryClient, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
7
8
  import type { EmbeddedWallet } from '@aztec/wallets/embedded';
@@ -30,6 +31,7 @@ export class BotRunner implements BotRunnerApi, Traceable {
30
31
  private readonly telemetry: TelemetryClient,
31
32
  private readonly aztecNodeAdmin: AztecNodeAdmin | undefined,
32
33
  private readonly store: BotStore,
34
+ private readonly syncChainTip?: BlockTag,
33
35
  ) {
34
36
  this.tracer = telemetry.getTracer('Bot');
35
37
 
@@ -149,13 +151,34 @@ export class BotRunner implements BotRunnerApi, Traceable {
149
151
  try {
150
152
  switch (this.config.botMode) {
151
153
  case 'crosschain':
152
- this.bot = CrossChainBot.create(this.config, this.wallet, this.aztecNode, this.aztecNodeAdmin, this.store);
154
+ this.bot = CrossChainBot.create(
155
+ this.config,
156
+ this.wallet,
157
+ this.aztecNode,
158
+ this.aztecNodeAdmin,
159
+ this.store,
160
+ this.syncChainTip,
161
+ );
153
162
  break;
154
163
  case 'amm':
155
- this.bot = AmmBot.create(this.config, this.wallet, this.aztecNode, this.aztecNodeAdmin, this.store);
164
+ this.bot = AmmBot.create(
165
+ this.config,
166
+ this.wallet,
167
+ this.aztecNode,
168
+ this.aztecNodeAdmin,
169
+ this.store,
170
+ this.syncChainTip,
171
+ );
156
172
  break;
157
173
  case 'transfer':
158
- this.bot = Bot.create(this.config, this.wallet, this.aztecNode, this.aztecNodeAdmin, this.store);
174
+ this.bot = Bot.create(
175
+ this.config,
176
+ this.wallet,
177
+ this.aztecNode,
178
+ this.aztecNodeAdmin,
179
+ this.store,
180
+ this.syncChainTip,
181
+ );
159
182
  break;
160
183
  default: {
161
184
  const _exhaustive: never = this.config.botMode;