@aztec/bot 0.0.1-commit.c2eed6949 → 0.0.1-commit.c52d6e7

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,5 +1,5 @@
1
1
  import { getInitialTestAccountsData } from '@aztec/accounts/testing';
2
- import { NO_FROM } from '@aztec/aztec.js/account';
2
+ import { deriveSecretKeyFromSigningKey } from '@aztec/accounts/utils';
3
3
  import { AztecAddress } from '@aztec/aztec.js/addresses';
4
4
  import {
5
5
  BatchCall,
@@ -16,22 +16,21 @@ import { deriveKeys } from '@aztec/aztec.js/keys';
16
16
  import { createLogger } from '@aztec/aztec.js/log';
17
17
  import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
18
18
  import { waitForTx } from '@aztec/aztec.js/node';
19
- import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
19
+ import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
20
20
  import { createEthereumChain } from '@aztec/ethereum/chain';
21
21
  import { createExtendedL1Client } from '@aztec/ethereum/client';
22
22
  import { RollupContract } from '@aztec/ethereum/contracts';
23
23
  import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
24
24
  import { Fr } from '@aztec/foundation/curves/bn254';
25
+ import { GrumpkinScalar } from '@aztec/foundation/curves/grumpkin';
25
26
  import { EthAddress } from '@aztec/foundation/eth-address';
26
- import { Timer } from '@aztec/foundation/timer';
27
27
  import { AMMContract } from '@aztec/noir-contracts.js/AMM';
28
28
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
29
29
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
30
30
  import { TestContract } from '@aztec/noir-test-contracts.js/Test';
31
+ import type { BlockTag } from '@aztec/stdlib/block';
31
32
  import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
32
- import { GasFees, GasSettings } from '@aztec/stdlib/gas';
33
33
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
34
- import { deriveSigningKey } from '@aztec/stdlib/keys';
35
34
  import { EmbeddedWallet } from '@aztec/wallets/embedded';
36
35
 
37
36
  import { type BotConfig, SupportedTokenContracts } from './config.js';
@@ -41,16 +40,23 @@ import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils
41
40
 
42
41
  const MINT_BALANCE = 1e12;
43
42
  const MIN_BALANCE = 1e3;
43
+ const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
44
44
 
45
45
  export class BotFactory {
46
46
  private log = createLogger('bot');
47
47
 
48
+ /** Number of in-flight withNoMinTxsPerBlock calls; see that method for why they are counted. */
49
+ private noMinTxsPerBlockDepth = 0;
50
+ /** Set by the first withNoMinTxsPerBlock entrant; resolves to the minTxsPerBlock value to restore. */
51
+ private savedMinTxsPerBlock?: Promise<{ minTxsPerBlock?: number }>;
52
+
48
53
  constructor(
49
54
  private readonly config: BotConfig,
50
55
  private readonly wallet: EmbeddedWallet,
51
56
  private readonly store: BotStore,
52
57
  private readonly aztecNode: AztecNode,
53
58
  private readonly aztecNodeAdmin?: AztecNodeAdmin,
59
+ private readonly syncChainTip?: BlockTag,
54
60
  ) {
55
61
  // Set fee padding on the wallet so that all transactions during setup
56
62
  // (token deploy, minting, etc.) use the configured padding, not the default.
@@ -69,7 +75,9 @@ export class BotFactory {
69
75
  recipient: AztecAddress;
70
76
  }> {
71
77
  const defaultAccountAddress = await this.setupAccount();
72
- const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
78
+ const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random(), GrumpkinScalar.random()))
79
+ .address;
80
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
73
81
  const token = await this.setupToken(defaultAccountAddress);
74
82
  await this.mintTokens(token, defaultAccountAddress);
75
83
  return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
@@ -84,23 +92,36 @@ export class BotFactory {
84
92
  node: AztecNode;
85
93
  }> {
86
94
  const defaultAccountAddress = await this.setupAccount();
87
- const token0 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
88
- const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
89
- const liquidityToken = await this.setupTokenContract(
90
- defaultAccountAddress,
91
- this.config.tokenSalt,
92
- 'BotLPToken',
93
- 'BOTLP',
94
- );
95
- const amm = await this.setupAmmContract(
96
- defaultAccountAddress,
97
- this.config.tokenSalt,
98
- token0,
99
- token1,
100
- liquidityToken,
101
- );
95
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
96
+
97
+ const salt = this.config.tokenSalt;
98
+
99
+ // token0, token1 and the LP token are independent contracts with no shared state, so deploy them
100
+ // concurrently rather than one slot at a time.
101
+ const [token0, token1, liquidityToken] = await Promise.all([
102
+ this.setupTokenContract(defaultAccountAddress, salt, 'BotToken0', 'BOT0'),
103
+ this.setupTokenContract(defaultAccountAddress, salt, 'BotToken1', 'BOT1'),
104
+ this.setupTokenContract(defaultAccountAddress, salt, 'BotLPToken', 'BOTLP'),
105
+ ]);
102
106
 
103
- await this.fundAmm(defaultAccountAddress, defaultAccountAddress, amm, token0, token1, liquidityToken);
107
+ const ammDeploy = AMMContract.deploy(this.wallet, token0.address, token1.address, liquidityToken.address, {
108
+ salt,
109
+ universalDeploy: true,
110
+ });
111
+ const ammAddress = (await ammDeploy.getInstance()).address;
112
+
113
+ // The AMM constructor only stores the (already-derived) token addresses, and set_minter only records
114
+ // the AMM address on the LP token: neither reads the other's on-chain state, so the AMM deploy, the
115
+ // LP-minter grant, and the token0/token1 mints are mutually independent and run concurrently.
116
+ const [amm] = await Promise.all([
117
+ this.deployAmmContract(defaultAccountAddress, ammDeploy),
118
+ this.grantLpTokenMinter(defaultAccountAddress, liquidityToken, ammAddress),
119
+ this.mintAmmLiquidity(defaultAccountAddress, token0, token1),
120
+ ]);
121
+
122
+ // add_liquidity spends the minted token0/token1 balances and mints LP tokens, so it must follow both
123
+ // the mints and the minter grant, and target the deployed AMM.
124
+ await this.addAmmLiquidity(defaultAccountAddress, defaultAccountAddress, amm, token0, token1, liquidityToken);
104
125
  this.log.info(`AMM initialized and funded`);
105
126
 
106
127
  return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
@@ -119,6 +140,7 @@ export class BotFactory {
119
140
  rollupVersion: bigint;
120
141
  }> {
121
142
  const defaultAccountAddress = await this.setupAccount();
143
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
122
144
 
123
145
  // Create L1 client (same pattern as bridgeL1FeeJuice)
124
146
  const l1RpcUrls = this.config.l1RpcUrls;
@@ -137,25 +159,32 @@ export class BotFactory {
137
159
  const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
138
160
  const rollupVersion = await rollupContract.getVersion();
139
161
 
140
- // Deploy TestContract
141
- const contract = await this.setupTestContract(defaultAccountAddress);
162
+ // Derive the TestContract address up front (deterministic from the salt). Seeding L1→L2 messages only
163
+ // needs the L2 recipient address — the messages are queued on L1 and don't require the L2 contract to
164
+ // exist yet (they're consumed later, after setup completes) — so the deploy (an L2 tx paying from the
165
+ // standing balance funded above) and the L1 seeding run concurrently.
166
+ const testContractDeploy = TestContract.deploy(this.wallet, {
167
+ salt: this.config.tokenSalt,
168
+ universalDeploy: true,
169
+ });
170
+ const contractAddress = (await testContractDeploy.getInstance()).address;
142
171
 
143
172
  // Recover any pending messages from store (clean up stale ones first)
144
173
  await this.store.cleanupOldPendingMessages();
145
174
  const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
146
175
 
147
- // Seed initial L1→L2 messages if pipeline is empty
176
+ // Seed initial L1→L2 messages if pipeline is empty. The seeds are sent one at a time: they share the
177
+ // bot's L1 account, so concurrent sends would race on the L1 nonce.
148
178
  const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
149
- for (let i = 0; i < seedCount; i++) {
150
- await seedL1ToL2Message(
151
- l1Client,
152
- EthAddress.fromString(l1ContractAddresses.inboxAddress.toString()),
153
- contract.address,
154
- rollupVersion,
155
- this.store,
156
- this.log,
157
- );
158
- }
179
+ const inboxAddress = EthAddress.fromString(l1ContractAddresses.inboxAddress.toString());
180
+ const [contract] = await Promise.all([
181
+ this.deployTestContract(defaultAccountAddress, testContractDeploy),
182
+ (async () => {
183
+ for (let i = 0; i < seedCount; i++) {
184
+ await seedL1ToL2Message(l1Client, inboxAddress, contractAddress, rollupVersion, this.store, this.log);
185
+ }
186
+ })(),
187
+ ]);
159
188
 
160
189
  // Block until at least one message is ready
161
190
  const allMessages = await this.store.getUnconsumedL1ToL2Messages();
@@ -164,6 +193,7 @@ export class BotFactory {
164
193
  const firstMsg = allMessages[0];
165
194
  await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
166
195
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
196
+ chainTip: this.syncChainTip,
167
197
  });
168
198
  this.log.info(`First L1→L2 message is ready`);
169
199
  }
@@ -178,14 +208,8 @@ export class BotFactory {
178
208
  };
179
209
  }
180
210
 
181
- private async setupTestContract(deployer: AztecAddress): Promise<TestContract> {
182
- const deployOpts: DeployOptions = {
183
- from: deployer,
184
- contractAddressSalt: this.config.tokenSalt,
185
- universalDeploy: true,
186
- };
187
- const deploy = TestContract.deploy(this.wallet);
188
- const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
211
+ private async deployTestContract(deployer: AztecAddress, deploy: DeployMethod<TestContract>): Promise<TestContract> {
212
+ const instance = await this.registerOrDeployContract('TestContract', deploy, { from: deployer });
189
213
  return TestContract.at(instance.address, this.wallet);
190
214
  }
191
215
 
@@ -204,55 +228,16 @@ export class BotFactory {
204
228
  }
205
229
  }
206
230
 
207
- private async setupAccountWithPrivateKey(secret: Fr) {
208
- const salt = this.config.senderSalt ?? Fr.ONE;
209
- const signingKey = deriveSigningKey(secret);
210
- const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
211
- const metadata = await this.wallet.getContractMetadata(accountManager.address);
212
- if (metadata.initializationStatus === ContractInitializationStatus.INITIALIZED) {
213
- this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
214
- const timer = new Timer();
215
- const address = accountManager.address;
216
- this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
217
- await this.store.deleteBridgeClaim(address);
218
- return address;
219
- } else {
220
- const address = accountManager.address;
221
- this.log.info(`Deploying account at ${address}`);
222
-
223
- const claim = await this.getOrCreateBridgeClaim(address);
224
-
225
- const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
226
- const deployMethod = await accountManager.getDeployMethod();
227
- const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
228
-
229
- const { estimatedGas } = await deployMethod.simulate({
230
- from: NO_FROM,
231
- fee: { estimateGas: true, paymentMethod },
232
- });
233
- const gasSettings = GasSettings.from({ ...estimatedGas!, maxFeesPerGas, maxPriorityFeesPerGas: GasFees.empty() });
234
-
235
- await this.withNoMinTxsPerBlock(async () => {
236
- const { txHash } = await deployMethod.send({
237
- from: NO_FROM,
238
- fee: { gasSettings, paymentMethod },
239
- wait: NO_WAIT,
240
- });
241
- this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`, { gasSettings });
242
- return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
243
- });
244
- this.log.info(`Account deployed at ${address}`);
245
-
246
- // Clean up the consumed bridge claim
247
- await this.store.deleteBridgeClaim(address);
248
-
249
- return accountManager.address;
250
- }
251
- }
252
-
231
+ /**
232
+ * Keyless fallback for tests and local dev: reuses the first genesis test account, whose address is
233
+ * pre-funded with fee juice via `initialFundedAccounts`. The test accounts are initializerless, so this
234
+ * must create an initializerless account for the address to match the funded one. Production bots set a
235
+ * sender private key and fund the resulting initializerless account from L1 instead; see
236
+ * setupAccountWithPrivateKey.
237
+ */
253
238
  private async setupTestAccount() {
254
239
  const [initialAccountData] = await getInitialTestAccountsData();
255
- const accountManager = await this.wallet.createSchnorrAccount(
240
+ const accountManager = await this.wallet.createSchnorrInitializerlessAccount(
256
241
  initialAccountData.secret,
257
242
  initialAccountData.salt,
258
243
  initialAccountData.signingKey,
@@ -260,35 +245,45 @@ export class BotFactory {
260
245
  return accountManager.address;
261
246
  }
262
247
 
248
+ private async setupAccountWithPrivateKey(privateKey: Fr) {
249
+ const salt = this.config.senderSalt ?? Fr.ONE;
250
+ const signingKey = GrumpkinScalar.fromBuffer(privateKey.toBuffer());
251
+ const secret = await deriveSecretKeyFromSigningKey(signingKey);
252
+ const accountManager = await this.wallet.createSchnorrInitializerlessAccount(secret, salt, signingKey);
253
+ return accountManager.address;
254
+ }
255
+
263
256
  /**
264
257
  * Checks if the token contract is deployed and deploys it if necessary.
265
- * @param wallet - Wallet to deploy the token contract from.
266
- * @returns The TokenContract instance.
258
+ * Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
259
+ * @param sender - Aztec address to deploy the token contract from.
260
+ * @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
261
+ * @returns The TokenContract or PrivateTokenContract instance.
267
262
  */
268
263
  private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
269
264
  let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
270
- let tokenInstance: ContractInstanceWithAddress | undefined;
271
- const deployOpts: DeployOptions = {
272
- from: sender,
273
- contractAddressSalt: this.config.tokenSalt,
274
- universalDeploy: true,
275
- };
265
+ const salt = this.config.tokenSalt;
266
+ const deployOpts: DeployOptions = { from: sender };
276
267
  let token: TokenContract | PrivateTokenContract;
277
268
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
278
- deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
279
- tokenInstance = await deploy.getInstance(deployOpts);
280
- token = TokenContract.at(tokenInstance.address, this.wallet);
269
+ deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
270
+ const instance = await deploy.getInstance();
271
+ token = TokenContract.at(instance.address, this.wallet);
281
272
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
282
273
  // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
283
274
  const tokenSecretKey = Fr.random();
284
275
  const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
285
- deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
276
+ deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
277
+ salt,
278
+ universalDeploy: true,
279
+ publicKeys: tokenPublicKeys,
280
+ });
286
281
  deployOpts.skipInstancePublication = true;
287
282
  deployOpts.skipClassPublication = true;
288
283
  deployOpts.skipInitialization = false;
289
284
 
290
285
  // Register the contract with the secret key before deployment
291
- tokenInstance = await deploy.getInstance(deployOpts);
286
+ const tokenInstance = await deploy.getInstance();
292
287
  token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
293
288
  await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
294
289
  // The contract constructor initializes private storage vars that need the contract's own nullifier key.
@@ -297,21 +292,7 @@ export class BotFactory {
297
292
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
298
293
  }
299
294
 
300
- const address = tokenInstance?.address ?? (await deploy.getInstance(deployOpts)).address;
301
- const metadata = await this.wallet.getContractMetadata(address);
302
- if (metadata.isContractPublished) {
303
- this.log.info(`Token at ${address.toString()} already deployed`);
304
- await deploy.register();
305
- } else {
306
- this.log.info(`Deploying token contract at ${address.toString()}`);
307
- const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true } });
308
- const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings: estimatedGas }, wait: NO_WAIT });
309
- this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`, { estimatedGas });
310
- await this.withNoMinTxsPerBlock(async () => {
311
- await waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
312
- return token;
313
- });
314
- }
295
+ await this.registerOrDeployContract('token', deploy, deployOpts);
315
296
  return token;
316
297
  }
317
298
 
@@ -322,49 +303,48 @@ export class BotFactory {
322
303
  */
323
304
  private async setupTokenContract(
324
305
  deployer: AztecAddress,
325
- contractAddressSalt: Fr,
306
+ salt: Fr,
326
307
  name: string,
327
308
  ticker: string,
328
309
  decimals = 18,
329
310
  ): Promise<TokenContract> {
330
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
331
- const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
311
+ const deployOpts: DeployOptions = { from: deployer };
312
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
332
313
  const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
333
314
  return TokenContract.at(instance.address, this.wallet);
334
315
  }
335
316
 
336
- private async setupAmmContract(
337
- deployer: AztecAddress,
338
- contractAddressSalt: Fr,
339
- token0: TokenContract,
340
- token1: TokenContract,
341
- lpToken: TokenContract,
342
- ): Promise<AMMContract> {
343
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
344
- const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
345
- const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
317
+ private async deployAmmContract(deployer: AztecAddress, deploy: DeployMethod<AMMContract>): Promise<AMMContract> {
318
+ const instance = await this.registerOrDeployContract('AMM', deploy, { from: deployer });
346
319
  const amm = AMMContract.at(instance.address, this.wallet);
347
-
348
320
  this.log.info(`AMM deployed at ${amm.address}`);
349
- const setMinterInteraction = lpToken.methods.set_minter(amm.address, true);
350
- const { estimatedGas: setMinterGas } = await setMinterInteraction.simulate({
351
- from: deployer,
352
- fee: { estimateGas: true },
353
- });
354
- const { receipt: minterReceipt } = await setMinterInteraction.send({
321
+ return amm;
322
+ }
323
+
324
+ /** Grants the AMM minting rights over the LP token. set_minter only records the address, so it does not
325
+ * require the AMM contract to be deployed first. */
326
+ private async grantLpTokenMinter(deployer: AztecAddress, lpToken: TokenContract, amm: AztecAddress): Promise<void> {
327
+ const { receipt } = await lpToken.methods.set_minter(amm, true).send({
355
328
  from: deployer,
356
- fee: { gasSettings: setMinterGas },
357
329
  wait: { timeout: this.config.txMinedWaitSeconds },
358
330
  });
359
- this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`, {
360
- estimatedGas: setMinterGas,
361
- });
362
- this.log.info(`Liquidity token initialized`);
331
+ this.log.info(`Set LP token minter to AMM txHash=${receipt.txHash.toString()}`);
332
+ }
363
333
 
364
- return amm;
334
+ private async mintAmmLiquidity(minter: AztecAddress, token0: TokenContract, token1: TokenContract): Promise<void> {
335
+ this.log.info(`Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1 for ${minter}`);
336
+ const mintBatch = new BatchCall(this.wallet, [
337
+ token0.methods.mint_to_private(minter, MINT_BALANCE),
338
+ token1.methods.mint_to_private(minter, MINT_BALANCE),
339
+ ]);
340
+ const { receipt } = await mintBatch.send({
341
+ from: minter,
342
+ wait: { timeout: this.config.txMinedWaitSeconds },
343
+ });
344
+ this.log.info(`Sent mint tx: ${receipt.txHash.toString()}`);
365
345
  }
366
346
 
367
- private async fundAmm(
347
+ private async addAmmLiquidity(
368
348
  defaultAccountAddress: AztecAddress,
369
349
  liquidityProvider: AztecAddress,
370
350
  amm: AMMContract,
@@ -372,22 +352,6 @@ export class BotFactory {
372
352
  token1: TokenContract,
373
353
  lpToken: TokenContract,
374
354
  ): Promise<void> {
375
- const getPrivateBalances = () =>
376
- Promise.all([
377
- token0.methods
378
- .balance_of_private(liquidityProvider)
379
- .simulate({ from: liquidityProvider })
380
- .then(r => r.result),
381
- token1.methods
382
- .balance_of_private(liquidityProvider)
383
- .simulate({ from: liquidityProvider })
384
- .then(r => r.result),
385
- lpToken.methods
386
- .balance_of_private(liquidityProvider)
387
- .simulate({ from: liquidityProvider })
388
- .then(r => r.result),
389
- ]);
390
-
391
355
  const authwitNonce = Fr.random();
392
356
 
393
357
  // keep some tokens for swapping
@@ -396,12 +360,6 @@ export class BotFactory {
396
360
  const amount1Max = MINT_BALANCE / 2;
397
361
  const amount1Min = MINT_BALANCE / 4;
398
362
 
399
- const [t0Bal, t1Bal, lpBal] = await getPrivateBalances();
400
-
401
- this.log.info(
402
- `Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1. Current private balances of ${liquidityProvider}: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`,
403
- );
404
-
405
363
  // Add authwitnesses for the transfers in AMM::add_liquidity function
406
364
  const token0Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
407
365
  caller: amm.address,
@@ -426,49 +384,33 @@ export class BotFactory {
426
384
  .getFunctionCall(),
427
385
  });
428
386
 
429
- const mintBatch = new BatchCall(this.wallet, [
430
- token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
431
- token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
432
- ]);
433
- const { estimatedGas: mintGas } = await mintBatch.simulate({
434
- from: liquidityProvider,
435
- fee: { estimateGas: true },
436
- });
437
- const { receipt: mintReceipt } = await mintBatch.send({
438
- from: liquidityProvider,
439
- fee: { gasSettings: mintGas },
440
- wait: { timeout: this.config.txMinedWaitSeconds },
441
- });
442
-
443
- this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`, { estimatedGas: mintGas });
444
-
445
- const addLiquidityInteraction = amm.methods.add_liquidity(
446
- amount0Max,
447
- amount1Max,
448
- amount0Min,
449
- amount1Min,
450
- authwitNonce,
451
- );
452
- const { estimatedGas: addLiquidityGas } = await addLiquidityInteraction.simulate({
453
- from: liquidityProvider,
454
- fee: { estimateGas: true },
455
- authWitnesses: [token0Authwit, token1Authwit],
456
- });
457
- const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
458
- from: liquidityProvider,
459
- fee: { gasSettings: addLiquidityGas },
460
- authWitnesses: [token0Authwit, token1Authwit],
461
- wait: { timeout: this.config.txMinedWaitSeconds },
462
- });
387
+ const { receipt } = await amm.methods
388
+ .add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce)
389
+ .send({
390
+ from: liquidityProvider,
391
+ authWitnesses: [token0Authwit, token1Authwit],
392
+ wait: { timeout: this.config.txMinedWaitSeconds },
393
+ });
463
394
 
464
- this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`, {
465
- estimatedGas: addLiquidityGas,
466
- });
395
+ this.log.info(`Sent tx to add liquidity to the AMM: ${receipt.txHash.toString()}`);
467
396
  this.log.info(`Liquidity added`);
468
397
 
469
- const [newT0Bal, newT1Bal, newLPBal] = await getPrivateBalances();
398
+ const [t0Bal, t1Bal, lpBal] = await Promise.all([
399
+ token0.methods
400
+ .balance_of_private(liquidityProvider)
401
+ .simulate({ from: liquidityProvider })
402
+ .then(r => r.result),
403
+ token1.methods
404
+ .balance_of_private(liquidityProvider)
405
+ .simulate({ from: liquidityProvider })
406
+ .then(r => r.result),
407
+ lpToken.methods
408
+ .balance_of_private(liquidityProvider)
409
+ .simulate({ from: liquidityProvider })
410
+ .then(r => r.result),
411
+ ]);
470
412
  this.log.info(
471
- `Updated private balances of ${defaultAccountAddress} after minting and funding AMM: token0=${newT0Bal}, token1=${newT1Bal}, lp=${newLPBal}`,
413
+ `Updated private balances of ${defaultAccountAddress} after minting and funding AMM: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`,
472
414
  );
473
415
  }
474
416
 
@@ -477,28 +419,75 @@ export class BotFactory {
477
419
  deploy: DeployMethod<T>,
478
420
  deployOpts: DeployOptions,
479
421
  ): Promise<ContractInstanceWithAddress> {
480
- const instance = await deploy.getInstance(deployOpts);
422
+ const instance = await deploy.getInstance();
481
423
  const address = instance.address;
482
424
  const metadata = await this.wallet.getContractMetadata(address);
483
425
  if (metadata.isContractPublished) {
484
426
  this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
485
427
  await deploy.register();
486
- } else {
487
- const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true } });
488
- this.log.info(`Deploying contract ${name} at ${address.toString()}`, { estimatedGas });
489
- await this.withNoMinTxsPerBlock(async () => {
490
- const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings: estimatedGas }, wait: NO_WAIT });
491
- this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
492
- return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
493
- });
428
+ return instance;
494
429
  }
430
+
431
+ // Setup always runs ensureFeeJuiceBalance before any deploy, so the account pays from its standing
432
+ // balance here. No manual gas estimation: the embedded wallet simulates before sending and derives
433
+ // the gas limits and padded maxFeesPerGas itself.
434
+ this.log.info(`Deploying contract ${name} at ${address.toString()}`);
435
+ await this.withNoMinTxsPerBlock(async () => {
436
+ const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
437
+ this.log.info(`Sent contract ${name} deploy tx ${txHash.toString()}`);
438
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
439
+ });
440
+
495
441
  return instance;
496
442
  }
497
443
 
444
+ /** True when the config allows bridging fee juice from L1 (fee_juice mode, an L1 RPC, and an L1 key). */
445
+ private isL1BridgingConfigured(): boolean {
446
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
447
+ return this.config.feePaymentMethod === 'fee_juice' && !!this.config.l1RpcUrls?.length && !!mnemonicOrPrivateKey;
448
+ }
449
+
498
450
  /**
499
- * Mints private and public tokens for the sender if their balance is below the minimum.
500
- * @param token - Token contract.
451
+ * Ensures the account holds enough fee juice before any other setup step. The account starts empty
452
+ * (initializerless accounts have no deployment tx) and the runtime loop pays fees from this balance and
453
+ * never refuels itself, so every flow funds the account up front. Bridges claims from L1 and consumes
454
+ * each with a claim-only tx until the balance clears the threshold, working from a zero (fresh run) or
455
+ * drained (restart) balance. Each bridge mints a fixed amount well above the threshold, so this is a
456
+ * single bridge in practice. No-op when L1 bridging is not configured or the balance is already above
457
+ * the threshold.
501
458
  */
459
+ private async ensureFeeJuiceBalance(account: AztecAddress): Promise<void> {
460
+ if (!this.isL1BridgingConfigured()) {
461
+ return;
462
+ }
463
+
464
+ let balance = await getFeeJuiceBalance(account, this.aztecNode);
465
+ if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
466
+ this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
467
+ return;
468
+ }
469
+
470
+ this.log.info(`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1`);
471
+
472
+ while (balance < FEE_JUICE_TOP_UP_THRESHOLD) {
473
+ // Persist the claim before consuming it: if the top-up tx fails or the bot crashes mid-loop, the
474
+ // next run reuses the pending claim instead of bridging again (and wasting the bridged funds).
475
+ const claim = await this.getOrCreateBridgeClaim(account);
476
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
477
+
478
+ await this.withNoMinTxsPerBlock(async () => {
479
+ const executionPayload = await paymentMethod.getExecutionPayload();
480
+ const { txHash } = await this.wallet.sendTx(executionPayload, { from: account, wait: NO_WAIT });
481
+ this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
482
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
483
+ });
484
+ await this.store.deleteBridgeClaim(account);
485
+ balance = await getFeeJuiceBalance(account, this.aztecNode);
486
+ this.log.info(`Fee juice balance after top-up: ${balance}`);
487
+ }
488
+ this.log.info(`Fee juice top-up complete for ${account.toString()}`);
489
+ }
490
+
502
491
  private async mintTokens(token: TokenContract | PrivateTokenContract, minter: AztecAddress) {
503
492
  const isStandardToken = isStandardTokenContract(token);
504
493
  let privateBalance = 0n;
@@ -532,36 +521,32 @@ export class BotFactory {
532
521
  // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
533
522
  const additionalScopes = isStandardToken ? undefined : [token.address];
534
523
  const mintBatch = new BatchCall(token.wallet, calls);
535
- const { estimatedGas } = await mintBatch.simulate({ from: minter, fee: { estimateGas: true }, additionalScopes });
536
524
  await this.withNoMinTxsPerBlock(async () => {
537
525
  const { txHash } = await mintBatch.send({
538
526
  from: minter,
539
527
  additionalScopes,
540
- fee: { gasSettings: estimatedGas },
541
528
  wait: NO_WAIT,
542
529
  });
543
- this.log.info(`Sent token mint tx with hash ${txHash.toString()}`, { estimatedGas });
530
+ this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
544
531
  return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
545
532
  });
546
533
  }
547
534
 
548
535
  /**
549
- * Gets or creates a bridge claim for the recipient.
550
- * Checks if a claim already exists in the store and reuses it if valid.
551
- * Only creates a new bridge if fee juice balance is below threshold.
536
+ * Returns a usable bridge claim for the recipient, reusing a persisted one when its L1→L2 message is
537
+ * still available (resuming a top-up that failed or crashed before the claim was consumed) and bridging
538
+ * a fresh claim otherwise. The caller deletes the claim from the store once it has been consumed.
552
539
  */
553
540
  private async getOrCreateBridgeClaim(recipient: AztecAddress): Promise<L2AmountClaim> {
554
- // Check if we have an existing claim in the store
555
541
  const existingClaim = await this.store.getBridgeClaim(recipient);
556
542
  if (existingClaim) {
557
543
  this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
558
-
559
- // Check if the message is ready on L2
560
544
  try {
561
545
  const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
562
546
  await this.withNoMinTxsPerBlock(() =>
563
547
  waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
564
548
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
549
+ chainTip: this.syncChainTip,
565
550
  }),
566
551
  );
567
552
  return existingClaim.claim;
@@ -573,7 +558,6 @@ export class BotFactory {
573
558
 
574
559
  const claim = await this.bridgeL1FeeJuice(recipient);
575
560
  await this.store.saveBridgeClaim(recipient, claim);
576
-
577
561
  return claim;
578
562
  }
579
563
 
@@ -600,6 +584,7 @@ export class BotFactory {
600
584
  await this.withNoMinTxsPerBlock(() =>
601
585
  waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
602
586
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
587
+ chainTip: this.syncChainTip,
603
588
  }),
604
589
  );
605
590
 
@@ -608,19 +593,36 @@ export class BotFactory {
608
593
  return claim as L2AmountClaim;
609
594
  }
610
595
 
611
- private async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
596
+ protected async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
612
597
  if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
613
598
  this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
614
599
  return fn();
615
600
  }
616
- const { minTxsPerBlock } = await this.aztecNodeAdmin.getConfig();
617
- this.log.warn(`Setting sequencer minTxsPerBlock to 0 from ${minTxsPerBlock} to flush setup transactions`);
618
- await this.aztecNodeAdmin.setConfig({ minTxsPerBlock: 0 });
601
+ const aztecNodeAdmin = this.aztecNodeAdmin;
602
+ // Setup steps run concurrently, so this wrapper can be re-entered while another call is in flight.
603
+ // Reference-count the entrants: the first saves the current value and zeroes it, the last restores it.
604
+ // A naive save/zero/restore per call could interleave, with a late entrant reading the already-zeroed
605
+ // value and "restoring" 0 at the end.
606
+ if (this.noMinTxsPerBlockDepth++ === 0) {
607
+ this.savedMinTxsPerBlock = (async () => {
608
+ const { minTxsPerBlock } = await aztecNodeAdmin.getConfig();
609
+ this.log.warn(`Setting sequencer minTxsPerBlock to 0 from ${minTxsPerBlock} to flush setup transactions`);
610
+ await aztecNodeAdmin.setConfig({ minTxsPerBlock: 0 });
611
+ return { minTxsPerBlock };
612
+ })();
613
+ }
619
614
  try {
615
+ await this.savedMinTxsPerBlock;
620
616
  return await fn();
621
617
  } finally {
622
- this.log.warn(`Restoring sequencer minTxsPerBlock to ${minTxsPerBlock}`);
623
- await this.aztecNodeAdmin.setConfig({ minTxsPerBlock });
618
+ if (--this.noMinTxsPerBlockDepth === 0) {
619
+ // If saving/zeroing itself failed there is nothing to restore.
620
+ const saved = await this.savedMinTxsPerBlock!.catch(() => undefined);
621
+ if (saved) {
622
+ this.log.warn(`Restoring sequencer minTxsPerBlock to ${saved.minTxsPerBlock}`);
623
+ await aztecNodeAdmin.setConfig({ minTxsPerBlock: saved.minTxsPerBlock });
624
+ }
625
+ }
624
626
  }
625
627
  }
626
628
  }