@aztec/bot 0.0.1-commit.d3ec352c → 0.0.1-commit.d58ff9d0

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.
Files changed (50) hide show
  1. package/dest/amm_bot.d.ts +7 -7
  2. package/dest/amm_bot.d.ts.map +1 -1
  3. package/dest/amm_bot.js +30 -19
  4. package/dest/base_bot.d.ts +8 -8
  5. package/dest/base_bot.d.ts.map +1 -1
  6. package/dest/base_bot.js +26 -37
  7. package/dest/bot.d.ts +7 -6
  8. package/dest/bot.d.ts.map +1 -1
  9. package/dest/bot.js +11 -11
  10. package/dest/config.d.ts +55 -91
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +48 -21
  13. package/dest/cross_chain_bot.d.ts +56 -0
  14. package/dest/cross_chain_bot.d.ts.map +1 -0
  15. package/dest/cross_chain_bot.js +138 -0
  16. package/dest/factory.d.ts +34 -14
  17. package/dest/factory.d.ts.map +1 -1
  18. package/dest/factory.js +335 -177
  19. package/dest/index.d.ts +2 -1
  20. package/dest/index.d.ts.map +1 -1
  21. package/dest/index.js +1 -0
  22. package/dest/interface.d.ts +2 -6
  23. package/dest/interface.d.ts.map +1 -1
  24. package/dest/interface.js +30 -7
  25. package/dest/l1_to_l2_seeding.d.ts +8 -0
  26. package/dest/l1_to_l2_seeding.d.ts.map +1 -0
  27. package/dest/l1_to_l2_seeding.js +63 -0
  28. package/dest/runner.d.ts +4 -3
  29. package/dest/runner.d.ts.map +1 -1
  30. package/dest/runner.js +432 -32
  31. package/dest/store/bot_store.d.ts +31 -6
  32. package/dest/store/bot_store.d.ts.map +1 -1
  33. package/dest/store/bot_store.js +38 -7
  34. package/dest/store/index.d.ts +2 -2
  35. package/dest/store/index.d.ts.map +1 -1
  36. package/dest/utils.js +3 -3
  37. package/package.json +18 -15
  38. package/src/amm_bot.ts +30 -22
  39. package/src/base_bot.ts +23 -44
  40. package/src/bot.ts +14 -12
  41. package/src/config.ts +96 -65
  42. package/src/cross_chain_bot.ts +208 -0
  43. package/src/factory.ts +354 -174
  44. package/src/index.ts +1 -0
  45. package/src/interface.ts +7 -7
  46. package/src/l1_to_l2_seeding.ts +79 -0
  47. package/src/runner.ts +41 -5
  48. package/src/store/bot_store.ts +61 -6
  49. package/src/store/index.ts +1 -1
  50. package/src/utils.ts +3 -3
package/src/factory.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { SchnorrAccountContract } from '@aztec/accounts/schnorr';
2
1
  import { getInitialTestAccountsData } from '@aztec/accounts/testing';
2
+ import { deriveSecretKeyFromSigningKey } from '@aztec/accounts/utils';
3
3
  import { AztecAddress } from '@aztec/aztec.js/addresses';
4
4
  import {
5
5
  BatchCall,
@@ -7,61 +7,84 @@ import {
7
7
  ContractFunctionInteraction,
8
8
  type DeployMethod,
9
9
  type DeployOptions,
10
+ NO_WAIT,
10
11
  } from '@aztec/aztec.js/contracts';
11
- import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
12
12
  import type { L2AmountClaim } from '@aztec/aztec.js/ethereum';
13
+ import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
13
14
  import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
15
+ import { deriveKeys } from '@aztec/aztec.js/keys';
14
16
  import { createLogger } from '@aztec/aztec.js/log';
15
17
  import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
16
- import { createEthereumChain, createExtendedL1Client } from '@aztec/ethereum';
17
- import { Fr } from '@aztec/foundation/fields';
18
- import { Timer } from '@aztec/foundation/timer';
18
+ import { waitForTx } from '@aztec/aztec.js/node';
19
+ import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
20
+ import { createEthereumChain } from '@aztec/ethereum/chain';
21
+ import { createExtendedL1Client } from '@aztec/ethereum/client';
22
+ import { RollupContract } from '@aztec/ethereum/contracts';
23
+ import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
24
+ import { Fr } from '@aztec/foundation/curves/bn254';
25
+ import { GrumpkinScalar } from '@aztec/foundation/curves/grumpkin';
26
+ import { EthAddress } from '@aztec/foundation/eth-address';
19
27
  import { AMMContract } from '@aztec/noir-contracts.js/AMM';
20
28
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
21
29
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
22
- import { GasSettings } from '@aztec/stdlib/gas';
30
+ import { TestContract } from '@aztec/noir-test-contracts.js/Test';
31
+ import type { BlockTag } from '@aztec/stdlib/block';
32
+ import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
23
33
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
24
- import { deriveSigningKey } from '@aztec/stdlib/keys';
25
- import { TestWallet } from '@aztec/test-wallet/server';
34
+ import { EmbeddedWallet } from '@aztec/wallets/embedded';
26
35
 
27
36
  import { type BotConfig, SupportedTokenContracts } from './config.js';
37
+ import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
28
38
  import type { BotStore } from './store/index.js';
29
39
  import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
30
40
 
31
41
  const MINT_BALANCE = 1e12;
32
42
  const MIN_BALANCE = 1e3;
43
+ const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
33
44
 
34
45
  export class BotFactory {
35
46
  private log = createLogger('bot');
36
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
+
37
53
  constructor(
38
54
  private readonly config: BotConfig,
39
- private readonly wallet: TestWallet,
55
+ private readonly wallet: EmbeddedWallet,
40
56
  private readonly store: BotStore,
41
57
  private readonly aztecNode: AztecNode,
42
58
  private readonly aztecNodeAdmin?: AztecNodeAdmin,
43
- ) {}
59
+ private readonly syncChainTip?: BlockTag,
60
+ ) {
61
+ // Set fee padding on the wallet so that all transactions during setup
62
+ // (token deploy, minting, etc.) use the configured padding, not the default.
63
+ this.wallet.setMinFeePadding(config.minFeePadding);
64
+ }
44
65
 
45
66
  /**
46
67
  * Initializes a new bot by setting up the sender account, registering the recipient,
47
68
  * deploying the token contract, and minting tokens if necessary.
48
69
  */
49
70
  public async setup(): Promise<{
50
- wallet: TestWallet;
71
+ wallet: EmbeddedWallet;
51
72
  defaultAccountAddress: AztecAddress;
52
73
  token: TokenContract | PrivateTokenContract;
53
74
  node: AztecNode;
54
75
  recipient: AztecAddress;
55
76
  }> {
56
- const recipient = (await this.wallet.createAccount()).address;
57
77
  const defaultAccountAddress = await this.setupAccount();
78
+ const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random(), GrumpkinScalar.random()))
79
+ .address;
80
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
58
81
  const token = await this.setupToken(defaultAccountAddress);
59
82
  await this.mintTokens(token, defaultAccountAddress);
60
83
  return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
61
84
  }
62
85
 
63
86
  public async setupAmm(): Promise<{
64
- wallet: TestWallet;
87
+ wallet: EmbeddedWallet;
65
88
  defaultAccountAddress: AztecAddress;
66
89
  amm: AMMContract;
67
90
  token0: TokenContract;
@@ -69,28 +92,127 @@ export class BotFactory {
69
92
  node: AztecNode;
70
93
  }> {
71
94
  const defaultAccountAddress = await this.setupAccount();
72
- const token0 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
73
- const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
74
- const liquidityToken = await this.setupTokenContract(
75
- defaultAccountAddress,
76
- this.config.tokenSalt,
77
- 'BotLPToken',
78
- 'BOTLP',
79
- );
80
- const amm = await this.setupAmmContract(
81
- defaultAccountAddress,
82
- this.config.tokenSalt,
83
- token0,
84
- token1,
85
- liquidityToken,
86
- );
95
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
96
+
97
+ const salt = this.config.tokenSalt;
87
98
 
88
- 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);
89
125
  this.log.info(`AMM initialized and funded`);
90
126
 
91
127
  return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
92
128
  }
93
129
 
130
+ /**
131
+ * Initializes the cross-chain bot by deploying TestContract, creating an L1 client,
132
+ * seeding initial L1→L2 messages, and waiting for the first to be ready.
133
+ */
134
+ public async setupCrossChain(): Promise<{
135
+ wallet: EmbeddedWallet;
136
+ defaultAccountAddress: AztecAddress;
137
+ contract: TestContract;
138
+ node: AztecNode;
139
+ l1Client: ExtendedViemWalletClient;
140
+ rollupVersion: bigint;
141
+ }> {
142
+ const defaultAccountAddress = await this.setupAccount();
143
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
144
+
145
+ // Create L1 client (same pattern as bridgeL1FeeJuice)
146
+ const l1RpcUrls = this.config.l1RpcUrls;
147
+ if (!l1RpcUrls?.length) {
148
+ throw new Error('L1 RPC URLs required for cross-chain bot');
149
+ }
150
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
151
+ if (!mnemonicOrPrivateKey) {
152
+ throw new Error('L1 mnemonic or private key required for cross-chain bot');
153
+ }
154
+ const { l1ChainId, l1ContractAddresses } = await this.aztecNode.getNodeInfo();
155
+ const chain = createEthereumChain(l1RpcUrls, l1ChainId);
156
+ const l1Client = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
157
+
158
+ // Fetch Rollup version (needed for Inbox L2Actor struct)
159
+ const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
160
+ const rollupVersion = await rollupContract.getVersion();
161
+
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;
171
+
172
+ // Recover any pending messages from store (clean up stale ones first)
173
+ await this.store.cleanupOldPendingMessages();
174
+ const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
175
+
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.
178
+ const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
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
+ ]);
188
+
189
+ // Block until at least one message is ready
190
+ const allMessages = await this.store.getUnconsumedL1ToL2Messages();
191
+ if (allMessages.length > 0) {
192
+ this.log.info(`Waiting for first L1→L2 message to be ready...`);
193
+ const firstMsg = allMessages[0];
194
+ await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
195
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
196
+ chainTip: this.syncChainTip,
197
+ });
198
+ this.log.info(`First L1→L2 message is ready`);
199
+ }
200
+
201
+ return {
202
+ wallet: this.wallet,
203
+ defaultAccountAddress,
204
+ contract,
205
+ node: this.aztecNode,
206
+ l1Client,
207
+ rollupVersion,
208
+ };
209
+ }
210
+
211
+ private async deployTestContract(deployer: AztecAddress, deploy: DeployMethod<TestContract>): Promise<TestContract> {
212
+ const instance = await this.registerOrDeployContract('TestContract', deploy, { from: deployer });
213
+ return TestContract.at(instance.address, this.wallet);
214
+ }
215
+
94
216
  /**
95
217
  * Checks if the sender account contract is initialized, and initializes it if necessary.
96
218
  * @returns The sender wallet.
@@ -106,91 +228,72 @@ export class BotFactory {
106
228
  }
107
229
  }
108
230
 
109
- private async setupAccountWithPrivateKey(secret: Fr) {
110
- const salt = this.config.senderSalt ?? Fr.ONE;
111
- const signingKey = deriveSigningKey(secret);
112
- const accountData = {
113
- secret,
114
- salt,
115
- contract: new SchnorrAccountContract(signingKey!),
116
- };
117
- const accountManager = await this.wallet.createAccount(accountData);
118
- const isInit = (await this.wallet.getContractMetadata(accountManager.address)).isContractInitialized;
119
- if (isInit) {
120
- this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
121
- const timer = new Timer();
122
- const address = accountManager.address;
123
- this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
124
- await this.store.deleteBridgeClaim(address);
125
- return address;
126
- } else {
127
- const address = accountManager.address;
128
- this.log.info(`Deploying account at ${address}`);
129
-
130
- const claim = await this.getOrCreateBridgeClaim(address);
131
-
132
- const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
133
- const deployMethod = await accountManager.getDeployMethod();
134
- const maxFeesPerGas = (await this.aztecNode.getCurrentBaseFees()).mul(1 + this.config.baseFeePadding);
135
- const gasSettings = GasSettings.default({ maxFeesPerGas });
136
- const sentTx = deployMethod.send({ from: AztecAddress.ZERO, fee: { gasSettings, paymentMethod } });
137
- const txHash = await sentTx.getTxHash();
138
- this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
139
- await this.withNoMinTxsPerBlock(() => sentTx.wait({ timeout: this.config.txMinedWaitSeconds }));
140
- this.log.info(`Account deployed at ${address}`);
141
-
142
- // Clean up the consumed bridge claim
143
- await this.store.deleteBridgeClaim(address);
144
-
145
- return accountManager.address;
146
- }
147
- }
148
-
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
+ */
149
238
  private async setupTestAccount() {
150
239
  const [initialAccountData] = await getInitialTestAccountsData();
151
- const accountData = {
152
- secret: initialAccountData.secret,
153
- salt: initialAccountData.salt,
154
- contract: new SchnorrAccountContract(initialAccountData.signingKey),
155
- };
156
- const accountManager = await this.wallet.createAccount(accountData);
240
+ const accountManager = await this.wallet.createSchnorrInitializerlessAccount(
241
+ initialAccountData.secret,
242
+ initialAccountData.salt,
243
+ initialAccountData.signingKey,
244
+ );
245
+ return accountManager.address;
246
+ }
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);
157
253
  return accountManager.address;
158
254
  }
159
255
 
160
256
  /**
161
257
  * Checks if the token contract is deployed and deploys it if necessary.
162
- * @param wallet - Wallet to deploy the token contract from.
163
- * @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.
164
262
  */
165
263
  private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
166
264
  let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
167
- const deployOpts: DeployOptions = {
168
- from: sender,
169
- contractAddressSalt: this.config.tokenSalt,
170
- universalDeploy: true,
171
- };
265
+ const salt = this.config.tokenSalt;
266
+ const deployOpts: DeployOptions = { from: sender };
267
+ let token: TokenContract | PrivateTokenContract;
172
268
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
173
- deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
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);
174
272
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
175
- deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender);
273
+ // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
274
+ const tokenSecretKey = Fr.random();
275
+ const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
276
+ deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
277
+ salt,
278
+ universalDeploy: true,
279
+ publicKeys: tokenPublicKeys,
280
+ });
176
281
  deployOpts.skipInstancePublication = true;
177
282
  deployOpts.skipClassPublication = true;
178
283
  deployOpts.skipInitialization = false;
284
+
285
+ // Register the contract with the secret key before deployment
286
+ const tokenInstance = await deploy.getInstance();
287
+ token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
288
+ await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
289
+ // The contract constructor initializes private storage vars that need the contract's own nullifier key.
290
+ deployOpts.additionalScopes = [tokenInstance.address];
179
291
  } else {
180
292
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
181
293
  }
182
294
 
183
- const address = (await deploy.getInstance(deployOpts)).address;
184
- if ((await this.wallet.getContractMetadata(address)).isContractPublished) {
185
- this.log.info(`Token at ${address.toString()} already deployed`);
186
- return deploy.register();
187
- } else {
188
- this.log.info(`Deploying token contract at ${address.toString()}`);
189
- const sentTx = deploy.send(deployOpts);
190
- const txHash = await sentTx.getTxHash();
191
- this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
192
- return this.withNoMinTxsPerBlock(() => sentTx.deployed({ timeout: this.config.txMinedWaitSeconds }));
193
- }
295
+ await this.registerOrDeployContract('token', deploy, deployOpts);
296
+ return token;
194
297
  }
195
298
 
196
299
  /**
@@ -198,39 +301,50 @@ export class BotFactory {
198
301
  * @param wallet - Wallet to deploy the token contract from.
199
302
  * @returns The TokenContract instance.
200
303
  */
201
- private setupTokenContract(
304
+ private async setupTokenContract(
202
305
  deployer: AztecAddress,
203
- contractAddressSalt: Fr,
306
+ salt: Fr,
204
307
  name: string,
205
308
  ticker: string,
206
309
  decimals = 18,
207
310
  ): Promise<TokenContract> {
208
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
209
- const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
210
- return this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
311
+ const deployOpts: DeployOptions = { from: deployer };
312
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
313
+ const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
314
+ return TokenContract.at(instance.address, this.wallet);
211
315
  }
212
316
 
213
- private async setupAmmContract(
214
- deployer: AztecAddress,
215
- contractAddressSalt: Fr,
216
- token0: TokenContract,
217
- token1: TokenContract,
218
- lpToken: TokenContract,
219
- ): Promise<AMMContract> {
220
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
221
- const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
222
- const amm = await this.registerOrDeployContract('AMM', deploy, deployOpts);
223
-
317
+ private async deployAmmContract(deployer: AztecAddress, deploy: DeployMethod<AMMContract>): Promise<AMMContract> {
318
+ const instance = await this.registerOrDeployContract('AMM', deploy, { from: deployer });
319
+ const amm = AMMContract.at(instance.address, this.wallet);
224
320
  this.log.info(`AMM deployed at ${amm.address}`);
225
- const minterTx = lpToken.methods.set_minter(amm.address, true).send({ from: deployer });
226
- this.log.info(`Set LP token minter to AMM txHash=${(await minterTx.getTxHash()).toString()}`);
227
- await minterTx.wait({ timeout: this.config.txMinedWaitSeconds });
228
- this.log.info(`Liquidity token initialized`);
229
-
230
321
  return amm;
231
322
  }
232
323
 
233
- private async fundAmm(
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({
328
+ from: deployer,
329
+ wait: { timeout: this.config.txMinedWaitSeconds },
330
+ });
331
+ this.log.info(`Set LP token minter to AMM txHash=${receipt.txHash.toString()}`);
332
+ }
333
+
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()}`);
345
+ }
346
+
347
+ private async addAmmLiquidity(
234
348
  defaultAccountAddress: AztecAddress,
235
349
  liquidityProvider: AztecAddress,
236
350
  amm: AMMContract,
@@ -238,13 +352,6 @@ export class BotFactory {
238
352
  token1: TokenContract,
239
353
  lpToken: TokenContract,
240
354
  ): Promise<void> {
241
- const getPrivateBalances = () =>
242
- Promise.all([
243
- token0.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
244
- token1.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
245
- lpToken.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
246
- ]);
247
-
248
355
  const authwitNonce = Fr.random();
249
356
 
250
357
  // keep some tokens for swapping
@@ -253,12 +360,6 @@ export class BotFactory {
253
360
  const amount1Max = MINT_BALANCE / 2;
254
361
  const amount1Min = MINT_BALANCE / 4;
255
362
 
256
- const [t0Bal, t1Bal, lpBal] = await getPrivateBalances();
257
-
258
- this.log.info(
259
- `Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1. Current private balances of ${liquidityProvider}: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`,
260
- );
261
-
262
363
  // Add authwitnesses for the transfers in AMM::add_liquidity function
263
364
  const token0Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
264
365
  caller: amm.address,
@@ -283,28 +384,33 @@ export class BotFactory {
283
384
  .getFunctionCall(),
284
385
  });
285
386
 
286
- const mintTx = new BatchCall(this.wallet, [
287
- token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
288
- token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
289
- ]).send({ from: liquidityProvider });
290
-
291
- this.log.info(`Sent mint tx: ${(await mintTx.getTxHash()).toString()}`);
292
- await mintTx.wait({ timeout: this.config.txMinedWaitSeconds });
293
-
294
- const addLiquidityTx = amm.methods
387
+ const { receipt } = await amm.methods
295
388
  .add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce)
296
389
  .send({
297
390
  from: liquidityProvider,
298
391
  authWitnesses: [token0Authwit, token1Authwit],
392
+ wait: { timeout: this.config.txMinedWaitSeconds },
299
393
  });
300
394
 
301
- this.log.info(`Sent tx to add liquidity to the AMM: ${(await addLiquidityTx.getTxHash()).toString()}`);
302
- await addLiquidityTx.wait({ timeout: this.config.txMinedWaitSeconds });
395
+ this.log.info(`Sent tx to add liquidity to the AMM: ${receipt.txHash.toString()}`);
303
396
  this.log.info(`Liquidity added`);
304
397
 
305
- 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
+ ]);
306
412
  this.log.info(
307
- `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}`,
308
414
  );
309
415
  }
310
416
 
@@ -312,24 +418,76 @@ export class BotFactory {
312
418
  name: string,
313
419
  deploy: DeployMethod<T>,
314
420
  deployOpts: DeployOptions,
315
- ): Promise<T> {
316
- const address = (await deploy.getInstance(deployOpts)).address;
317
- if ((await this.wallet.getContractMetadata(address)).isContractPublished) {
421
+ ): Promise<ContractInstanceWithAddress> {
422
+ const instance = await deploy.getInstance();
423
+ const address = instance.address;
424
+ const metadata = await this.wallet.getContractMetadata(address);
425
+ if (metadata.isContractPublished) {
318
426
  this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
319
- return deploy.register();
320
- } else {
321
- this.log.info(`Deploying contract ${name} at ${address.toString()}`);
322
- const sentTx = deploy.send(deployOpts);
323
- const txHash = await sentTx.getTxHash();
324
- this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
325
- return this.withNoMinTxsPerBlock(() => sentTx.deployed({ timeout: this.config.txMinedWaitSeconds }));
427
+ await deploy.register();
428
+ return instance;
326
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
+
441
+ return instance;
442
+ }
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;
327
448
  }
328
449
 
329
450
  /**
330
- * Mints private and public tokens for the sender if their balance is below the minimum.
331
- * @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.
332
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
+
333
491
  private async mintTokens(token: TokenContract | PrivateTokenContract, minter: AztecAddress) {
334
492
  const isStandardToken = isStandardTokenContract(token);
335
493
  let privateBalance = 0n;
@@ -359,30 +517,36 @@ export class BotFactory {
359
517
  this.log.info(`Skipping minting as ${minter.toString()} has enough tokens`);
360
518
  return;
361
519
  }
362
- const sentTx = new BatchCall(token.wallet, calls).send({ from: minter });
363
- const txHash = await sentTx.getTxHash();
364
- this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
365
- await this.withNoMinTxsPerBlock(() => sentTx.wait({ timeout: this.config.txMinedWaitSeconds }));
520
+
521
+ // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
522
+ const additionalScopes = isStandardToken ? undefined : [token.address];
523
+ const mintBatch = new BatchCall(token.wallet, calls);
524
+ await this.withNoMinTxsPerBlock(async () => {
525
+ const { txHash } = await mintBatch.send({
526
+ from: minter,
527
+ additionalScopes,
528
+ wait: NO_WAIT,
529
+ });
530
+ this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
531
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
532
+ });
366
533
  }
367
534
 
368
535
  /**
369
- * Gets or creates a bridge claim for the recipient.
370
- * Checks if a claim already exists in the store and reuses it if valid.
371
- * 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.
372
539
  */
373
540
  private async getOrCreateBridgeClaim(recipient: AztecAddress): Promise<L2AmountClaim> {
374
- // Check if we have an existing claim in the store
375
541
  const existingClaim = await this.store.getBridgeClaim(recipient);
376
542
  if (existingClaim) {
377
543
  this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
378
-
379
- // Check if the message is ready on L2
380
544
  try {
381
545
  const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
382
546
  await this.withNoMinTxsPerBlock(() =>
383
547
  waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
384
548
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
385
- forPublicConsumption: false,
549
+ chainTip: this.syncChainTip,
386
550
  }),
387
551
  );
388
552
  return existingClaim.claim;
@@ -394,7 +558,6 @@ export class BotFactory {
394
558
 
395
559
  const claim = await this.bridgeL1FeeJuice(recipient);
396
560
  await this.store.saveBridgeClaim(recipient, claim);
397
-
398
561
  return claim;
399
562
  }
400
563
 
@@ -421,7 +584,7 @@ export class BotFactory {
421
584
  await this.withNoMinTxsPerBlock(() =>
422
585
  waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
423
586
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
424
- forPublicConsumption: false,
587
+ chainTip: this.syncChainTip,
425
588
  }),
426
589
  );
427
590
 
@@ -430,19 +593,36 @@ export class BotFactory {
430
593
  return claim as L2AmountClaim;
431
594
  }
432
595
 
433
- private async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
596
+ protected async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
434
597
  if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
435
598
  this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
436
599
  return fn();
437
600
  }
438
- const { minTxsPerBlock } = await this.aztecNodeAdmin.getConfig();
439
- this.log.warn(`Setting sequencer minTxsPerBlock to 0 from ${minTxsPerBlock} to flush setup transactions`);
440
- 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
+ }
441
614
  try {
615
+ await this.savedMinTxsPerBlock;
442
616
  return await fn();
443
617
  } finally {
444
- this.log.warn(`Restoring sequencer minTxsPerBlock to ${minTxsPerBlock}`);
445
- 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
+ }
446
626
  }
447
627
  }
448
628
  }