@aztec/bot 0.0.1-commit.4d3c002 → 0.0.1-commit.4d9804df

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,
@@ -17,22 +17,20 @@ 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
19
  import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
20
- import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
21
20
  import { createEthereumChain } from '@aztec/ethereum/chain';
22
21
  import { createExtendedL1Client } from '@aztec/ethereum/client';
23
22
  import { RollupContract } from '@aztec/ethereum/contracts';
24
23
  import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
25
24
  import { Fr } from '@aztec/foundation/curves/bn254';
25
+ import { GrumpkinScalar } from '@aztec/foundation/curves/grumpkin';
26
26
  import { EthAddress } from '@aztec/foundation/eth-address';
27
- import { Timer } from '@aztec/foundation/timer';
28
27
  import { AMMContract } from '@aztec/noir-contracts.js/AMM';
29
28
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
30
29
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
31
30
  import { TestContract } from '@aztec/noir-test-contracts.js/Test';
31
+ import type { BlockTag } from '@aztec/stdlib/block';
32
32
  import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
33
- import { GasFees, GasSettings } from '@aztec/stdlib/gas';
34
33
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
35
- import { deriveSigningKey } from '@aztec/stdlib/keys';
36
34
  import { EmbeddedWallet } from '@aztec/wallets/embedded';
37
35
 
38
36
  import { type BotConfig, SupportedTokenContracts } from './config.js';
@@ -43,17 +41,22 @@ import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils
43
41
  const MINT_BALANCE = 1e12;
44
42
  const MIN_BALANCE = 1e3;
45
43
  const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
46
- const FEE_JUICE_TOP_UP_TARGET = 10_000n * 10n ** 18n;
47
44
 
48
45
  export class BotFactory {
49
46
  private log = createLogger('bot');
50
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
+
51
53
  constructor(
52
54
  private readonly config: BotConfig,
53
55
  private readonly wallet: EmbeddedWallet,
54
56
  private readonly store: BotStore,
55
57
  private readonly aztecNode: AztecNode,
56
58
  private readonly aztecNodeAdmin?: AztecNodeAdmin,
59
+ private readonly syncChainTip?: BlockTag,
57
60
  ) {
58
61
  // Set fee padding on the wallet so that all transactions during setup
59
62
  // (token deploy, minting, etc.) use the configured padding, not the default.
@@ -72,9 +75,10 @@ export class BotFactory {
72
75
  recipient: AztecAddress;
73
76
  }> {
74
77
  const defaultAccountAddress = await this.setupAccount();
75
- const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
76
- const token = await this.setupTokenWithOptionalEarlyRefuel(defaultAccountAddress);
77
- await this.ensureFeeJuiceBalance(defaultAccountAddress, token);
78
+ const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random(), GrumpkinScalar.random()))
79
+ .address;
80
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
81
+ const token = await this.setupToken(defaultAccountAddress);
78
82
  await this.mintTokens(token, defaultAccountAddress);
79
83
  return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
80
84
  }
@@ -88,29 +92,36 @@ export class BotFactory {
88
92
  node: AztecNode;
89
93
  }> {
90
94
  const defaultAccountAddress = await this.setupAccount();
91
- const token0 = await this.setupTokenContractWithOptionalEarlyRefuel(
92
- defaultAccountAddress,
93
- this.config.tokenSalt,
94
- 'BotToken0',
95
- 'BOT0',
96
- );
97
- await this.ensureFeeJuiceBalance(defaultAccountAddress, token0);
98
- const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
99
- const liquidityToken = await this.setupTokenContract(
100
- defaultAccountAddress,
101
- this.config.tokenSalt,
102
- 'BotLPToken',
103
- 'BOTLP',
104
- );
105
- const amm = await this.setupAmmContract(
106
- defaultAccountAddress,
107
- this.config.tokenSalt,
108
- token0,
109
- token1,
110
- liquidityToken,
111
- );
95
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
96
+
97
+ const salt = this.config.tokenSalt;
112
98
 
113
- await this.fundAmm(defaultAccountAddress, defaultAccountAddress, amm, token0, token1, liquidityToken);
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
+ ]);
106
+
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);
114
125
  this.log.info(`AMM initialized and funded`);
115
126
 
116
127
  return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
@@ -129,6 +140,7 @@ export class BotFactory {
129
140
  rollupVersion: bigint;
130
141
  }> {
131
142
  const defaultAccountAddress = await this.setupAccount();
143
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
132
144
 
133
145
  // Create L1 client (same pattern as bridgeL1FeeJuice)
134
146
  const l1RpcUrls = this.config.l1RpcUrls;
@@ -147,25 +159,32 @@ export class BotFactory {
147
159
  const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
148
160
  const rollupVersion = await rollupContract.getVersion();
149
161
 
150
- // Deploy TestContract
151
- 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;
152
171
 
153
172
  // Recover any pending messages from store (clean up stale ones first)
154
173
  await this.store.cleanupOldPendingMessages();
155
174
  const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
156
175
 
157
- // 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.
158
178
  const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
159
- for (let i = 0; i < seedCount; i++) {
160
- await seedL1ToL2Message(
161
- l1Client,
162
- EthAddress.fromString(l1ContractAddresses.inboxAddress.toString()),
163
- contract.address,
164
- rollupVersion,
165
- this.store,
166
- this.log,
167
- );
168
- }
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
+ ]);
169
188
 
170
189
  // Block until at least one message is ready
171
190
  const allMessages = await this.store.getUnconsumedL1ToL2Messages();
@@ -174,6 +193,7 @@ export class BotFactory {
174
193
  const firstMsg = allMessages[0];
175
194
  await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
176
195
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
196
+ chainTip: this.syncChainTip,
177
197
  });
178
198
  this.log.info(`First L1→L2 message is ready`);
179
199
  }
@@ -188,14 +208,8 @@ export class BotFactory {
188
208
  };
189
209
  }
190
210
 
191
- private async setupTestContract(deployer: AztecAddress): Promise<TestContract> {
192
- const deployOpts: DeployOptions = {
193
- from: deployer,
194
- contractAddressSalt: this.config.tokenSalt,
195
- universalDeploy: true,
196
- };
197
- const deploy = TestContract.deploy(this.wallet);
198
- 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 });
199
213
  return TestContract.at(instance.address, this.wallet);
200
214
  }
201
215
 
@@ -214,48 +228,16 @@ export class BotFactory {
214
228
  }
215
229
  }
216
230
 
217
- private async setupAccountWithPrivateKey(secret: Fr) {
218
- const salt = this.config.senderSalt ?? Fr.ONE;
219
- const signingKey = deriveSigningKey(secret);
220
- const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
221
- const metadata = await this.wallet.getContractMetadata(accountManager.address);
222
- if (metadata.initializationStatus === ContractInitializationStatus.INITIALIZED) {
223
- this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
224
- const timer = new Timer();
225
- const address = accountManager.address;
226
- this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
227
- await this.store.deleteBridgeClaim(address);
228
- return address;
229
- } else {
230
- const address = accountManager.address;
231
- this.log.info(`Deploying account at ${address}`);
232
-
233
- const claim = await this.getOrCreateBridgeClaim(address);
234
-
235
- const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
236
- const deployMethod = await accountManager.getDeployMethod();
237
-
238
- await this.withNoMinTxsPerBlock(async () => {
239
- const { txHash } = await deployMethod.send({
240
- from: NO_FROM,
241
- fee: { paymentMethod },
242
- wait: NO_WAIT,
243
- });
244
- this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
245
- return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
246
- });
247
- this.log.info(`Account deployed at ${address}`);
248
-
249
- // Clean up the consumed bridge claim
250
- await this.store.deleteBridgeClaim(address);
251
-
252
- return accountManager.address;
253
- }
254
- }
255
-
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
+ */
256
238
  private async setupTestAccount() {
257
239
  const [initialAccountData] = await getInitialTestAccountsData();
258
- const accountManager = await this.wallet.createSchnorrAccount(
240
+ const accountManager = await this.wallet.createSchnorrInitializerlessAccount(
259
241
  initialAccountData.secret,
260
242
  initialAccountData.salt,
261
243
  initialAccountData.signingKey,
@@ -263,68 +245,12 @@ export class BotFactory {
263
245
  return accountManager.address;
264
246
  }
265
247
 
266
- /**
267
- * Setup token and refuel first: if the token already exists (restart scenario),
268
- * run ensureFeeJuiceBalance before any step that might need fee juice. When deploying,
269
- * use a bridge claim if balance is below threshold.
270
- */
271
- private async setupTokenWithOptionalEarlyRefuel(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
272
- const token = await this.getTokenInstance(sender);
273
- const address = token.address;
274
- const metadata = await this.wallet.getContractMetadata(address);
275
- if (metadata.isContractPublished) {
276
- this.log.info(`Token at ${address.toString()} already deployed, refueling before setup`);
277
- await this.ensureFeeJuiceBalance(sender, token);
278
- }
279
- return this.setupToken(sender);
280
- }
281
-
282
- /**
283
- * Setup token0 for AMM with refuel-first behaviour when token already exists.
284
- */
285
- private async setupTokenContractWithOptionalEarlyRefuel(
286
- deployer: AztecAddress,
287
- contractAddressSalt: Fr,
288
- name: string,
289
- ticker: string,
290
- decimals = 18,
291
- ): Promise<TokenContract> {
292
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
293
- const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
294
- const instance = await deploy.getInstance(deployOpts);
295
- const metadata = await this.wallet.getContractMetadata(instance.address);
296
- if (metadata.isContractPublished) {
297
- this.log.info(`Token ${name} at ${instance.address.toString()} already deployed, refueling before setup`);
298
- const token = TokenContract.at(instance.address, this.wallet);
299
- await this.ensureFeeJuiceBalance(deployer, token);
300
- }
301
- return this.setupTokenContract(deployer, contractAddressSalt, name, ticker, decimals);
302
- }
303
-
304
- private async getTokenInstance(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
305
- const deployOpts: DeployOptions = {
306
- from: sender,
307
- contractAddressSalt: this.config.tokenSalt,
308
- universalDeploy: true,
309
- };
310
- if (this.config.contract === SupportedTokenContracts.TokenContract) {
311
- const deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
312
- const instance = await deploy.getInstance(deployOpts);
313
- return TokenContract.at(instance.address, this.wallet);
314
- }
315
- if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
316
- const tokenSecretKey = Fr.random();
317
- const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
318
- const deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
319
- const instance = await deploy.getInstance({
320
- ...deployOpts,
321
- skipInstancePublication: true,
322
- skipClassPublication: true,
323
- skipInitialization: false,
324
- });
325
- return PrivateTokenContract.at(instance.address, this.wallet);
326
- }
327
- throw new Error(`Unsupported token contract type: ${this.config.contract}`);
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;
328
254
  }
329
255
 
330
256
  /**
@@ -336,27 +262,28 @@ export class BotFactory {
336
262
  */
337
263
  private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
338
264
  let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
339
- const deployOpts: DeployOptions = {
340
- from: sender,
341
- contractAddressSalt: this.config.tokenSalt,
342
- universalDeploy: true,
343
- };
265
+ const salt = this.config.tokenSalt;
266
+ const deployOpts: DeployOptions = { from: sender };
344
267
  let token: TokenContract | PrivateTokenContract;
345
268
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
346
- deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
347
- const instance = await deploy.getInstance(deployOpts);
269
+ deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
270
+ const instance = await deploy.getInstance();
348
271
  token = TokenContract.at(instance.address, this.wallet);
349
272
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
350
273
  // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
351
274
  const tokenSecretKey = Fr.random();
352
275
  const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
353
- 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
+ });
354
281
  deployOpts.skipInstancePublication = true;
355
282
  deployOpts.skipClassPublication = true;
356
283
  deployOpts.skipInitialization = false;
357
284
 
358
285
  // Register the contract with the secret key before deployment
359
- const tokenInstance = await deploy.getInstance(deployOpts);
286
+ const tokenInstance = await deploy.getInstance();
360
287
  token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
361
288
  await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
362
289
  // The contract constructor initializes private storage vars that need the contract's own nullifier key.
@@ -376,42 +303,48 @@ export class BotFactory {
376
303
  */
377
304
  private async setupTokenContract(
378
305
  deployer: AztecAddress,
379
- contractAddressSalt: Fr,
306
+ salt: Fr,
380
307
  name: string,
381
308
  ticker: string,
382
309
  decimals = 18,
383
310
  ): Promise<TokenContract> {
384
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
385
- 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 });
386
313
  const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
387
314
  return TokenContract.at(instance.address, this.wallet);
388
315
  }
389
316
 
390
- private async setupAmmContract(
391
- deployer: AztecAddress,
392
- contractAddressSalt: Fr,
393
- token0: TokenContract,
394
- token1: TokenContract,
395
- lpToken: TokenContract,
396
- ): Promise<AMMContract> {
397
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
398
- const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
399
- 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 });
400
319
  const amm = AMMContract.at(instance.address, this.wallet);
401
-
402
320
  this.log.info(`AMM deployed at ${amm.address}`);
403
- const setMinterInteraction = lpToken.methods.set_minter(amm.address, true);
404
- 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({
405
328
  from: deployer,
406
329
  wait: { timeout: this.config.txMinedWaitSeconds },
407
330
  });
408
- this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
409
- this.log.info(`Liquidity token initialized`);
331
+ this.log.info(`Set LP token minter to AMM txHash=${receipt.txHash.toString()}`);
332
+ }
410
333
 
411
- 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()}`);
412
345
  }
413
346
 
414
- private async fundAmm(
347
+ private async addAmmLiquidity(
415
348
  defaultAccountAddress: AztecAddress,
416
349
  liquidityProvider: AztecAddress,
417
350
  amm: AMMContract,
@@ -419,22 +352,6 @@ export class BotFactory {
419
352
  token1: TokenContract,
420
353
  lpToken: TokenContract,
421
354
  ): Promise<void> {
422
- const getPrivateBalances = () =>
423
- Promise.all([
424
- token0.methods
425
- .balance_of_private(liquidityProvider)
426
- .simulate({ from: liquidityProvider })
427
- .then(r => r.result),
428
- token1.methods
429
- .balance_of_private(liquidityProvider)
430
- .simulate({ from: liquidityProvider })
431
- .then(r => r.result),
432
- lpToken.methods
433
- .balance_of_private(liquidityProvider)
434
- .simulate({ from: liquidityProvider })
435
- .then(r => r.result),
436
- ]);
437
-
438
355
  const authwitNonce = Fr.random();
439
356
 
440
357
  // keep some tokens for swapping
@@ -443,12 +360,6 @@ export class BotFactory {
443
360
  const amount1Max = MINT_BALANCE / 2;
444
361
  const amount1Min = MINT_BALANCE / 4;
445
362
 
446
- const [t0Bal, t1Bal, lpBal] = await getPrivateBalances();
447
-
448
- this.log.info(
449
- `Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1. Current private balances of ${liquidityProvider}: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`,
450
- );
451
-
452
363
  // Add authwitnesses for the transfers in AMM::add_liquidity function
453
364
  const token0Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
454
365
  caller: amm.address,
@@ -473,36 +384,33 @@ export class BotFactory {
473
384
  .getFunctionCall(),
474
385
  });
475
386
 
476
- const mintBatch = new BatchCall(this.wallet, [
477
- token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
478
- token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
479
- ]);
480
- const { receipt: mintReceipt } = await mintBatch.send({
481
- from: liquidityProvider,
482
- wait: { timeout: this.config.txMinedWaitSeconds },
483
- });
484
-
485
- this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
486
-
487
- const addLiquidityInteraction = amm.methods.add_liquidity(
488
- amount0Max,
489
- amount1Max,
490
- amount0Min,
491
- amount1Min,
492
- authwitNonce,
493
- );
494
- const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
495
- from: liquidityProvider,
496
- authWitnesses: [token0Authwit, token1Authwit],
497
- wait: { timeout: this.config.txMinedWaitSeconds },
498
- });
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
+ });
499
394
 
500
- this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`);
395
+ this.log.info(`Sent tx to add liquidity to the AMM: ${receipt.txHash.toString()}`);
501
396
  this.log.info(`Liquidity added`);
502
397
 
503
- 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
+ ]);
504
412
  this.log.info(
505
- `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}`,
506
414
  );
507
415
  }
508
416
 
@@ -511,72 +419,45 @@ export class BotFactory {
511
419
  deploy: DeployMethod<T>,
512
420
  deployOpts: DeployOptions,
513
421
  ): Promise<ContractInstanceWithAddress> {
514
- const instance = await deploy.getInstance(deployOpts);
422
+ const instance = await deploy.getInstance();
515
423
  const address = instance.address;
516
424
  const metadata = await this.wallet.getContractMetadata(address);
517
425
  if (metadata.isContractPublished) {
518
426
  this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
519
427
  await deploy.register();
520
- } else {
521
- const sender = deployOpts.from === NO_FROM ? undefined : deployOpts.from;
522
- const balance = sender ? await getFeeJuiceBalance(sender, this.aztecNode) : 0n;
523
- const useClaim =
524
- sender &&
525
- balance < FEE_JUICE_TOP_UP_THRESHOLD &&
526
- this.config.feePaymentMethod === 'fee_juice' &&
527
- !!this.config.l1RpcUrls?.length;
528
- const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
529
-
530
- if (useClaim && mnemonicOrPrivateKey) {
531
- const claim = await this.getOrCreateBridgeClaim(sender!);
532
- const paymentMethod = new FeeJuicePaymentMethodWithClaim(sender!, claim);
533
- const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true, paymentMethod } });
534
- const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
535
- const gasSettings = GasSettings.from({
536
- ...estimatedGas!,
537
- maxFeesPerGas,
538
- maxPriorityFeesPerGas: GasFees.empty(),
539
- });
540
- await this.withNoMinTxsPerBlock(async () => {
541
- const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings, paymentMethod }, wait: NO_WAIT });
542
- this.log.info(
543
- `Sent contract ${name} deploy tx ${txHash.toString()} (using bridge claim, balance was ${balance})`,
544
- );
545
- return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
546
- });
547
- await this.store.deleteBridgeClaim(sender!);
548
- } else {
549
- const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true } });
550
- this.log.info(`Deploying contract ${name} at ${address.toString()}`, { estimatedGas });
551
- await this.withNoMinTxsPerBlock(async () => {
552
- const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings: estimatedGas }, wait: NO_WAIT });
553
- this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
554
- return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
555
- });
556
- }
428
+ return instance;
557
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
+
558
441
  return instance;
559
442
  }
560
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
+
561
450
  /**
562
- * Mints private and public tokens for the sender if their balance is below the minimum.
563
- * @param token - Token contract.
564
- */
565
- /**
566
- * Ensures the account has sufficient fee juice by bridging from L1 if balance is below threshold.
567
- * Bridges repeatedly until balance reaches the target (10k FJ).
568
- * Used on startup/restart to top up when the account has run out after previous runs.
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.
569
458
  */
570
- private async ensureFeeJuiceBalance(
571
- account: AztecAddress,
572
- token: TokenContract | PrivateTokenContract,
573
- ): Promise<void> {
574
- const { feePaymentMethod, l1RpcUrls } = this.config;
575
- if (feePaymentMethod !== 'fee_juice' || !l1RpcUrls?.length) {
576
- return;
577
- }
578
- const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
579
- if (!mnemonicOrPrivateKey) {
459
+ private async ensureFeeJuiceBalance(account: AztecAddress): Promise<void> {
460
+ if (!this.isL1BridgingConfigured()) {
580
461
  return;
581
462
  }
582
463
 
@@ -586,36 +467,21 @@ export class BotFactory {
586
467
  return;
587
468
  }
588
469
 
589
- this.log.info(
590
- `Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1 until ${FEE_JUICE_TOP_UP_TARGET}`,
591
- );
592
- const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
593
- const minimalInteraction = isStandardTokenContract(token)
594
- ? token.methods.transfer_in_public(account, account, 0n, 0)
595
- : token.methods.transfer(0n, account, account);
470
+ this.log.info(`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1`);
596
471
 
597
- while (balance < FEE_JUICE_TOP_UP_TARGET) {
598
- const claim = await this.bridgeL1FeeJuice(account);
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);
599
476
  const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
600
- const { estimatedGas } = await minimalInteraction.simulate({
601
- from: account,
602
- fee: { estimateGas: true, paymentMethod },
603
- });
604
- const gasSettings = GasSettings.from({
605
- ...estimatedGas!,
606
- maxFeesPerGas,
607
- maxPriorityFeesPerGas: GasFees.empty(),
608
- });
609
477
 
610
478
  await this.withNoMinTxsPerBlock(async () => {
611
- const { txHash } = await minimalInteraction.send({
612
- from: account,
613
- fee: { gasSettings, paymentMethod },
614
- wait: NO_WAIT,
615
- });
479
+ const executionPayload = await paymentMethod.getExecutionPayload();
480
+ const { txHash } = await this.wallet.sendTx(executionPayload, { from: account, wait: NO_WAIT });
616
481
  this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
617
482
  return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
618
483
  });
484
+ await this.store.deleteBridgeClaim(account);
619
485
  balance = await getFeeJuiceBalance(account, this.aztecNode);
620
486
  this.log.info(`Fee juice balance after top-up: ${balance}`);
621
487
  }
@@ -667,22 +533,20 @@ export class BotFactory {
667
533
  }
668
534
 
669
535
  /**
670
- * Gets or creates a bridge claim for the recipient.
671
- * Checks if a claim already exists in the store and reuses it if valid.
672
- * 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.
673
539
  */
674
540
  private async getOrCreateBridgeClaim(recipient: AztecAddress): Promise<L2AmountClaim> {
675
- // Check if we have an existing claim in the store
676
541
  const existingClaim = await this.store.getBridgeClaim(recipient);
677
542
  if (existingClaim) {
678
543
  this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
679
-
680
- // Check if the message is ready on L2
681
544
  try {
682
545
  const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
683
546
  await this.withNoMinTxsPerBlock(() =>
684
547
  waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
685
548
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
549
+ chainTip: this.syncChainTip,
686
550
  }),
687
551
  );
688
552
  return existingClaim.claim;
@@ -694,7 +558,6 @@ export class BotFactory {
694
558
 
695
559
  const claim = await this.bridgeL1FeeJuice(recipient);
696
560
  await this.store.saveBridgeClaim(recipient, claim);
697
-
698
561
  return claim;
699
562
  }
700
563
 
@@ -721,6 +584,7 @@ export class BotFactory {
721
584
  await this.withNoMinTxsPerBlock(() =>
722
585
  waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
723
586
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
587
+ chainTip: this.syncChainTip,
724
588
  }),
725
589
  );
726
590
 
@@ -729,19 +593,36 @@ export class BotFactory {
729
593
  return claim as L2AmountClaim;
730
594
  }
731
595
 
732
- private async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
596
+ protected async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
733
597
  if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
734
598
  this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
735
599
  return fn();
736
600
  }
737
- const { minTxsPerBlock } = await this.aztecNodeAdmin.getConfig();
738
- this.log.warn(`Setting sequencer minTxsPerBlock to 0 from ${minTxsPerBlock} to flush setup transactions`);
739
- 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
+ }
740
614
  try {
615
+ await this.savedMinTxsPerBlock;
741
616
  return await fn();
742
617
  } finally {
743
- this.log.warn(`Restoring sequencer minTxsPerBlock to ${minTxsPerBlock}`);
744
- 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
+ }
745
626
  }
746
627
  }
747
628
  }