@aztec/bot 0.0.1-commit.e558bd1c → 0.0.1-commit.e57c76e

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 +5 -5
  2. package/dest/amm_bot.d.ts.map +1 -1
  3. package/dest/amm_bot.js +24 -17
  4. package/dest/base_bot.d.ts +7 -7
  5. package/dest/base_bot.d.ts.map +1 -1
  6. package/dest/base_bot.js +21 -32
  7. package/dest/bot.d.ts +4 -4
  8. package/dest/bot.d.ts.map +1 -1
  9. package/dest/bot.js +5 -8
  10. package/dest/config.d.ts +47 -82
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +39 -12
  13. package/dest/cross_chain_bot.d.ts +54 -0
  14. package/dest/cross_chain_bot.d.ts.map +1 -0
  15. package/dest/cross_chain_bot.js +137 -0
  16. package/dest/factory.d.ts +25 -5
  17. package/dest/factory.d.ts.map +1 -1
  18. package/dest/factory.js +314 -88
  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 +3 -3
  29. package/dest/runner.d.ts.map +1 -1
  30. package/dest/runner.js +17 -1
  31. package/dest/store/bot_store.d.ts +30 -5
  32. package/dest/store/bot_store.d.ts.map +1 -1
  33. package/dest/store/bot_store.js +37 -6
  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 +17 -14
  38. package/src/amm_bot.ts +25 -20
  39. package/src/base_bot.ts +16 -33
  40. package/src/bot.ts +8 -10
  41. package/src/config.ts +44 -16
  42. package/src/cross_chain_bot.ts +204 -0
  43. package/src/factory.ts +358 -87
  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 +18 -5
  48. package/src/store/bot_store.ts +60 -5
  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 { NO_FROM } from '@aztec/aztec.js/account';
3
3
  import { AztecAddress } from '@aztec/aztec.js/addresses';
4
4
  import {
5
5
  BatchCall,
@@ -9,64 +9,78 @@ import {
9
9
  type DeployOptions,
10
10
  NO_WAIT,
11
11
  } from '@aztec/aztec.js/contracts';
12
- import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
13
12
  import type { L2AmountClaim } from '@aztec/aztec.js/ethereum';
13
+ import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
14
14
  import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
15
15
  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 { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
20
+ import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
19
21
  import { createEthereumChain } from '@aztec/ethereum/chain';
20
22
  import { createExtendedL1Client } from '@aztec/ethereum/client';
23
+ import { RollupContract } from '@aztec/ethereum/contracts';
24
+ import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
21
25
  import { Fr } from '@aztec/foundation/curves/bn254';
26
+ import { EthAddress } from '@aztec/foundation/eth-address';
22
27
  import { Timer } from '@aztec/foundation/timer';
23
28
  import { AMMContract } from '@aztec/noir-contracts.js/AMM';
24
29
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
25
30
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
31
+ import { TestContract } from '@aztec/noir-test-contracts.js/Test';
26
32
  import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
27
- import { GasSettings } from '@aztec/stdlib/gas';
33
+ import { GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
28
34
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
29
35
  import { deriveSigningKey } from '@aztec/stdlib/keys';
30
- import { TestWallet } from '@aztec/test-wallet/server';
36
+ import { EmbeddedWallet } from '@aztec/wallets/embedded';
31
37
 
32
38
  import { type BotConfig, SupportedTokenContracts } from './config.js';
39
+ import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
33
40
  import type { BotStore } from './store/index.js';
34
41
  import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
35
42
 
36
43
  const MINT_BALANCE = 1e12;
37
44
  const MIN_BALANCE = 1e3;
45
+ const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
46
+ const FEE_JUICE_TOP_UP_TARGET = 10_000n * 10n ** 18n;
38
47
 
39
48
  export class BotFactory {
40
49
  private log = createLogger('bot');
41
50
 
42
51
  constructor(
43
52
  private readonly config: BotConfig,
44
- private readonly wallet: TestWallet,
53
+ private readonly wallet: EmbeddedWallet,
45
54
  private readonly store: BotStore,
46
55
  private readonly aztecNode: AztecNode,
47
56
  private readonly aztecNodeAdmin?: AztecNodeAdmin,
48
- ) {}
57
+ ) {
58
+ // Set fee padding on the wallet so that all transactions during setup
59
+ // (token deploy, minting, etc.) use the configured padding, not the default.
60
+ this.wallet.setMinFeePadding(config.minFeePadding);
61
+ }
49
62
 
50
63
  /**
51
64
  * Initializes a new bot by setting up the sender account, registering the recipient,
52
65
  * deploying the token contract, and minting tokens if necessary.
53
66
  */
54
67
  public async setup(): Promise<{
55
- wallet: TestWallet;
68
+ wallet: EmbeddedWallet;
56
69
  defaultAccountAddress: AztecAddress;
57
70
  token: TokenContract | PrivateTokenContract;
58
71
  node: AztecNode;
59
72
  recipient: AztecAddress;
60
73
  }> {
61
74
  const defaultAccountAddress = await this.setupAccount();
62
- const recipient = (await this.wallet.createAccount()).address;
63
- const token = await this.setupToken(defaultAccountAddress);
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);
64
78
  await this.mintTokens(token, defaultAccountAddress);
65
79
  return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
66
80
  }
67
81
 
68
82
  public async setupAmm(): Promise<{
69
- wallet: TestWallet;
83
+ wallet: EmbeddedWallet;
70
84
  defaultAccountAddress: AztecAddress;
71
85
  amm: AMMContract;
72
86
  token0: TokenContract;
@@ -74,7 +88,13 @@ export class BotFactory {
74
88
  node: AztecNode;
75
89
  }> {
76
90
  const defaultAccountAddress = await this.setupAccount();
77
- const token0 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
91
+ const token0 = await this.setupTokenContractWithOptionalEarlyRefuel(
92
+ defaultAccountAddress,
93
+ this.config.tokenSalt,
94
+ 'BotToken0',
95
+ 'BOT0',
96
+ );
97
+ await this.ensureFeeJuiceBalance(defaultAccountAddress, token0);
78
98
  const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
79
99
  const liquidityToken = await this.setupTokenContract(
80
100
  defaultAccountAddress,
@@ -96,6 +116,85 @@ export class BotFactory {
96
116
  return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
97
117
  }
98
118
 
119
+ /**
120
+ * Initializes the cross-chain bot by deploying TestContract, creating an L1 client,
121
+ * seeding initial L1→L2 messages, and waiting for the first to be ready.
122
+ */
123
+ public async setupCrossChain(): Promise<{
124
+ wallet: EmbeddedWallet;
125
+ defaultAccountAddress: AztecAddress;
126
+ contract: TestContract;
127
+ node: AztecNode;
128
+ l1Client: ExtendedViemWalletClient;
129
+ rollupVersion: bigint;
130
+ }> {
131
+ const defaultAccountAddress = await this.setupAccount();
132
+
133
+ // Create L1 client (same pattern as bridgeL1FeeJuice)
134
+ const l1RpcUrls = this.config.l1RpcUrls;
135
+ if (!l1RpcUrls?.length) {
136
+ throw new Error('L1 RPC URLs required for cross-chain bot');
137
+ }
138
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
139
+ if (!mnemonicOrPrivateKey) {
140
+ throw new Error('L1 mnemonic or private key required for cross-chain bot');
141
+ }
142
+ const { l1ChainId, l1ContractAddresses } = await this.aztecNode.getNodeInfo();
143
+ const chain = createEthereumChain(l1RpcUrls, l1ChainId);
144
+ const l1Client = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
145
+
146
+ // Fetch Rollup version (needed for Inbox L2Actor struct)
147
+ const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
148
+ const rollupVersion = await rollupContract.getVersion();
149
+
150
+ // Deploy TestContract
151
+ const contract = await this.setupTestContract(defaultAccountAddress);
152
+
153
+ // Recover any pending messages from store (clean up stale ones first)
154
+ await this.store.cleanupOldPendingMessages();
155
+ const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
156
+
157
+ // Seed initial L1→L2 messages if pipeline is empty
158
+ 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
+ }
169
+
170
+ // Block until at least one message is ready
171
+ const allMessages = await this.store.getUnconsumedL1ToL2Messages();
172
+ if (allMessages.length > 0) {
173
+ this.log.info(`Waiting for first L1→L2 message to be ready...`);
174
+ const firstMsg = allMessages[0];
175
+ await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
176
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
177
+ });
178
+ this.log.info(`First L1→L2 message is ready`);
179
+ }
180
+
181
+ return {
182
+ wallet: this.wallet,
183
+ defaultAccountAddress,
184
+ contract,
185
+ node: this.aztecNode,
186
+ l1Client,
187
+ rollupVersion,
188
+ };
189
+ }
190
+
191
+ private async setupTestContract(deployer: AztecAddress): Promise<TestContract> {
192
+ const deployOpts: DeployOptions = { from: deployer };
193
+ const deploy = TestContract.deploy(this.wallet, { salt: this.config.tokenSalt, universalDeploy: true });
194
+ const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
195
+ return TestContract.at(instance.address, this.wallet);
196
+ }
197
+
99
198
  /**
100
199
  * Checks if the sender account contract is initialized, and initializes it if necessary.
101
200
  * @returns The sender wallet.
@@ -114,14 +213,9 @@ export class BotFactory {
114
213
  private async setupAccountWithPrivateKey(secret: Fr) {
115
214
  const salt = this.config.senderSalt ?? Fr.ONE;
116
215
  const signingKey = deriveSigningKey(secret);
117
- const accountData = {
118
- secret,
119
- salt,
120
- contract: new SchnorrAccountContract(signingKey!),
121
- };
122
- const accountManager = await this.wallet.createAccount(accountData);
216
+ const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
123
217
  const metadata = await this.wallet.getContractMetadata(accountManager.address);
124
- if (metadata.isContractInitialized) {
218
+ if (metadata.initializationStatus === ContractInitializationStatus.INITIALIZED) {
125
219
  this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
126
220
  const timer = new Timer();
127
221
  const address = accountManager.address;
@@ -136,13 +230,11 @@ export class BotFactory {
136
230
 
137
231
  const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
138
232
  const deployMethod = await accountManager.getDeployMethod();
139
- const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
140
- const gasSettings = GasSettings.default({ maxFeesPerGas });
141
233
 
142
234
  await this.withNoMinTxsPerBlock(async () => {
143
- const txHash = await deployMethod.send({
144
- from: AztecAddress.ZERO,
145
- fee: { gasSettings, paymentMethod },
235
+ const { txHash } = await deployMethod.send({
236
+ from: NO_FROM,
237
+ fee: { paymentMethod },
146
238
  wait: NO_WAIT,
147
239
  });
148
240
  this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
@@ -159,64 +251,112 @@ export class BotFactory {
159
251
 
160
252
  private async setupTestAccount() {
161
253
  const [initialAccountData] = await getInitialTestAccountsData();
162
- const accountData = {
163
- secret: initialAccountData.secret,
164
- salt: initialAccountData.salt,
165
- contract: new SchnorrAccountContract(initialAccountData.signingKey),
166
- };
167
- const accountManager = await this.wallet.createAccount(accountData);
254
+ const accountManager = await this.wallet.createSchnorrAccount(
255
+ initialAccountData.secret,
256
+ initialAccountData.salt,
257
+ initialAccountData.signingKey,
258
+ );
168
259
  return accountManager.address;
169
260
  }
170
261
 
262
+ /**
263
+ * Setup token and refuel first: if the token already exists (restart scenario),
264
+ * run ensureFeeJuiceBalance before any step that might need fee juice. When deploying,
265
+ * use a bridge claim if balance is below threshold.
266
+ */
267
+ private async setupTokenWithOptionalEarlyRefuel(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
268
+ const token = await this.getTokenInstance(sender);
269
+ const address = token.address;
270
+ const metadata = await this.wallet.getContractMetadata(address);
271
+ if (metadata.isContractPublished) {
272
+ this.log.info(`Token at ${address.toString()} already deployed, refueling before setup`);
273
+ await this.ensureFeeJuiceBalance(sender, token);
274
+ }
275
+ return this.setupToken(sender);
276
+ }
277
+
278
+ /**
279
+ * Setup token0 for AMM with refuel-first behaviour when token already exists.
280
+ */
281
+ private async setupTokenContractWithOptionalEarlyRefuel(
282
+ deployer: AztecAddress,
283
+ salt: Fr,
284
+ name: string,
285
+ ticker: string,
286
+ decimals = 18,
287
+ ): Promise<TokenContract> {
288
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
289
+ const instance = await deploy.getInstance();
290
+ const metadata = await this.wallet.getContractMetadata(instance.address);
291
+ if (metadata.isContractPublished) {
292
+ this.log.info(`Token ${name} at ${instance.address.toString()} already deployed, refueling before setup`);
293
+ const token = TokenContract.at(instance.address, this.wallet);
294
+ await this.ensureFeeJuiceBalance(deployer, token);
295
+ }
296
+ return this.setupTokenContract(deployer, salt, name, ticker, decimals);
297
+ }
298
+
299
+ private async getTokenInstance(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
300
+ const salt = this.config.tokenSalt;
301
+ if (this.config.contract === SupportedTokenContracts.TokenContract) {
302
+ const deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
303
+ const instance = await deploy.getInstance();
304
+ return TokenContract.at(instance.address, this.wallet);
305
+ }
306
+ if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
307
+ const tokenSecretKey = Fr.random();
308
+ const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
309
+ const deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
310
+ salt,
311
+ universalDeploy: true,
312
+ publicKeys: tokenPublicKeys,
313
+ });
314
+ const instance = await deploy.getInstance();
315
+ return PrivateTokenContract.at(instance.address, this.wallet);
316
+ }
317
+ throw new Error(`Unsupported token contract type: ${this.config.contract}`);
318
+ }
319
+
171
320
  /**
172
321
  * Checks if the token contract is deployed and deploys it if necessary.
173
- * @param wallet - Wallet to deploy the token contract from.
174
- * @returns The TokenContract instance.
322
+ * Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
323
+ * @param sender - Aztec address to deploy the token contract from.
324
+ * @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
325
+ * @returns The TokenContract or PrivateTokenContract instance.
175
326
  */
176
327
  private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
177
328
  let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
178
- let tokenInstance: ContractInstanceWithAddress | undefined;
179
- const deployOpts: DeployOptions = {
180
- from: sender,
181
- contractAddressSalt: this.config.tokenSalt,
182
- universalDeploy: true,
183
- };
329
+ const salt = this.config.tokenSalt;
330
+ const deployOpts: DeployOptions = { from: sender };
184
331
  let token: TokenContract | PrivateTokenContract;
185
332
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
186
- deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
187
- tokenInstance = await deploy.getInstance(deployOpts);
188
- token = TokenContract.at(tokenInstance.address, this.wallet);
333
+ deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
334
+ const instance = await deploy.getInstance();
335
+ token = TokenContract.at(instance.address, this.wallet);
189
336
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
190
337
  // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
191
338
  const tokenSecretKey = Fr.random();
192
339
  const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
193
- deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
340
+ deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
341
+ salt,
342
+ universalDeploy: true,
343
+ publicKeys: tokenPublicKeys,
344
+ });
194
345
  deployOpts.skipInstancePublication = true;
195
346
  deployOpts.skipClassPublication = true;
196
347
  deployOpts.skipInitialization = false;
197
348
 
198
349
  // Register the contract with the secret key before deployment
199
- tokenInstance = await deploy.getInstance(deployOpts);
350
+ const tokenInstance = await deploy.getInstance();
200
351
  token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
201
352
  await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
353
+ // The contract constructor initializes private storage vars that need the contract's own nullifier key.
354
+ deployOpts.additionalScopes = [tokenInstance.address];
202
355
  } else {
203
356
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
204
357
  }
205
358
 
206
- const address = tokenInstance?.address ?? (await deploy.getInstance(deployOpts)).address;
207
- const metadata = await this.wallet.getContractMetadata(address);
208
- if (metadata.isContractPublished) {
209
- this.log.info(`Token at ${address.toString()} already deployed`);
210
- await deploy.register();
211
- } else {
212
- this.log.info(`Deploying token contract at ${address.toString()}`);
213
- const txHash = await deploy.send({ ...deployOpts, wait: NO_WAIT });
214
- this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
215
- await this.withNoMinTxsPerBlock(async () => {
216
- await waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
217
- return token;
218
- });
219
- }
359
+ await this.registerOrDeployContract('token', deploy, deployOpts);
220
360
  return token;
221
361
  }
222
362
 
@@ -227,33 +367,38 @@ export class BotFactory {
227
367
  */
228
368
  private async setupTokenContract(
229
369
  deployer: AztecAddress,
230
- contractAddressSalt: Fr,
370
+ salt: Fr,
231
371
  name: string,
232
372
  ticker: string,
233
373
  decimals = 18,
234
374
  ): Promise<TokenContract> {
235
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
236
- const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
375
+ const deployOpts: DeployOptions = { from: deployer };
376
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
237
377
  const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
238
378
  return TokenContract.at(instance.address, this.wallet);
239
379
  }
240
380
 
241
381
  private async setupAmmContract(
242
382
  deployer: AztecAddress,
243
- contractAddressSalt: Fr,
383
+ salt: Fr,
244
384
  token0: TokenContract,
245
385
  token1: TokenContract,
246
386
  lpToken: TokenContract,
247
387
  ): Promise<AMMContract> {
248
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
249
- const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
388
+ const deployOpts: DeployOptions = { from: deployer };
389
+ const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address, {
390
+ salt,
391
+ universalDeploy: true,
392
+ });
250
393
  const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
251
394
  const amm = AMMContract.at(instance.address, this.wallet);
252
395
 
253
396
  this.log.info(`AMM deployed at ${amm.address}`);
254
- const minterReceipt = await lpToken.methods
255
- .set_minter(amm.address, true)
256
- .send({ from: deployer, wait: { timeout: this.config.txMinedWaitSeconds } });
397
+ const setMinterInteraction = lpToken.methods.set_minter(amm.address, true);
398
+ const { receipt: minterReceipt } = await setMinterInteraction.send({
399
+ from: deployer,
400
+ wait: { timeout: this.config.txMinedWaitSeconds },
401
+ });
257
402
  this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
258
403
  this.log.info(`Liquidity token initialized`);
259
404
 
@@ -270,9 +415,18 @@ export class BotFactory {
270
415
  ): Promise<void> {
271
416
  const getPrivateBalances = () =>
272
417
  Promise.all([
273
- token0.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
274
- token1.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
275
- lpToken.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
418
+ token0.methods
419
+ .balance_of_private(liquidityProvider)
420
+ .simulate({ from: liquidityProvider })
421
+ .then(r => r.result),
422
+ token1.methods
423
+ .balance_of_private(liquidityProvider)
424
+ .simulate({ from: liquidityProvider })
425
+ .then(r => r.result),
426
+ lpToken.methods
427
+ .balance_of_private(liquidityProvider)
428
+ .simulate({ from: liquidityProvider })
429
+ .then(r => r.result),
276
430
  ]);
277
431
 
278
432
  const authwitNonce = Fr.random();
@@ -313,20 +467,29 @@ export class BotFactory {
313
467
  .getFunctionCall(),
314
468
  });
315
469
 
316
- const mintReceipt = await new BatchCall(this.wallet, [
470
+ const mintBatch = new BatchCall(this.wallet, [
317
471
  token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
318
472
  token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
319
- ]).send({ from: liquidityProvider, wait: { timeout: this.config.txMinedWaitSeconds } });
473
+ ]);
474
+ const { receipt: mintReceipt } = await mintBatch.send({
475
+ from: liquidityProvider,
476
+ wait: { timeout: this.config.txMinedWaitSeconds },
477
+ });
320
478
 
321
479
  this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
322
480
 
323
- const addLiquidityReceipt = await amm.methods
324
- .add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce)
325
- .send({
326
- from: liquidityProvider,
327
- authWitnesses: [token0Authwit, token1Authwit],
328
- wait: { timeout: this.config.txMinedWaitSeconds },
329
- });
481
+ const addLiquidityInteraction = amm.methods.add_liquidity(
482
+ amount0Max,
483
+ amount1Max,
484
+ amount0Min,
485
+ amount1Min,
486
+ authwitNonce,
487
+ );
488
+ const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
489
+ from: liquidityProvider,
490
+ authWitnesses: [token0Authwit, token1Authwit],
491
+ wait: { timeout: this.config.txMinedWaitSeconds },
492
+ });
330
493
 
331
494
  this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`);
332
495
  this.log.info(`Liquidity added`);
@@ -342,19 +505,49 @@ export class BotFactory {
342
505
  deploy: DeployMethod<T>,
343
506
  deployOpts: DeployOptions,
344
507
  ): Promise<ContractInstanceWithAddress> {
345
- const instance = await deploy.getInstance(deployOpts);
508
+ const instance = await deploy.getInstance();
346
509
  const address = instance.address;
347
510
  const metadata = await this.wallet.getContractMetadata(address);
348
511
  if (metadata.isContractPublished) {
349
512
  this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
350
513
  await deploy.register();
351
514
  } else {
352
- this.log.info(`Deploying contract ${name} at ${address.toString()}`);
353
- await this.withNoMinTxsPerBlock(async () => {
354
- const txHash = await deploy.send({ ...deployOpts, wait: NO_WAIT });
355
- this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
356
- return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
357
- });
515
+ const sender = deployOpts.from === NO_FROM ? undefined : deployOpts.from;
516
+ const balance = sender ? await getFeeJuiceBalance(sender, this.aztecNode) : 0n;
517
+ const useClaim =
518
+ sender &&
519
+ balance < FEE_JUICE_TOP_UP_THRESHOLD &&
520
+ this.config.feePaymentMethod === 'fee_juice' &&
521
+ !!this.config.l1RpcUrls?.length;
522
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
523
+
524
+ if (useClaim && mnemonicOrPrivateKey) {
525
+ const claim = await this.getOrCreateBridgeClaim(sender!);
526
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(sender!, claim);
527
+ const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true, paymentMethod } });
528
+ const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
529
+ const gasSettings = GasSettings.from({
530
+ ...estimatedGas!,
531
+ maxFeesPerGas,
532
+ maxPriorityFeesPerGas: GasFees.empty(),
533
+ });
534
+ await this.withNoMinTxsPerBlock(async () => {
535
+ const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings, paymentMethod }, wait: NO_WAIT });
536
+ this.log.info(
537
+ `Sent contract ${name} deploy tx ${txHash.toString()} (using bridge claim, balance was ${balance})`,
538
+ );
539
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
540
+ });
541
+ await this.store.deleteBridgeClaim(sender!);
542
+ } else {
543
+ const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true } });
544
+ this.log.info(`Deploying contract ${name} at ${address.toString()}`, { estimatedGas });
545
+ await this.withNoMinTxsPerBlock(async () => {
546
+ const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings: estimatedGas }, wait: NO_WAIT });
547
+ this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
548
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
549
+ });
550
+ }
358
551
  }
359
552
  return instance;
360
553
  }
@@ -363,6 +556,66 @@ export class BotFactory {
363
556
  * Mints private and public tokens for the sender if their balance is below the minimum.
364
557
  * @param token - Token contract.
365
558
  */
559
+ /**
560
+ * Ensures the account has sufficient fee juice by bridging from L1 if balance is below threshold.
561
+ * Bridges repeatedly until balance reaches the target (10k FJ).
562
+ * Used on startup/restart to top up when the account has run out after previous runs.
563
+ */
564
+ private async ensureFeeJuiceBalance(
565
+ account: AztecAddress,
566
+ token: TokenContract | PrivateTokenContract,
567
+ ): Promise<void> {
568
+ const { feePaymentMethod, l1RpcUrls } = this.config;
569
+ if (feePaymentMethod !== 'fee_juice' || !l1RpcUrls?.length) {
570
+ return;
571
+ }
572
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
573
+ if (!mnemonicOrPrivateKey) {
574
+ return;
575
+ }
576
+
577
+ let balance = await getFeeJuiceBalance(account, this.aztecNode);
578
+ if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
579
+ this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
580
+ return;
581
+ }
582
+
583
+ this.log.info(
584
+ `Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1 until ${FEE_JUICE_TOP_UP_TARGET}`,
585
+ );
586
+ const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
587
+ const minimalInteraction = isStandardTokenContract(token)
588
+ ? token.methods.transfer_in_public(account, account, 0n, 0)
589
+ : token.methods.transfer(0n, account, account);
590
+
591
+ while (balance < FEE_JUICE_TOP_UP_TARGET) {
592
+ const claim = await this.bridgeL1FeeJuice(account);
593
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
594
+ const { estimatedGas } = await minimalInteraction.simulate({
595
+ from: account,
596
+ fee: { estimateGas: true, paymentMethod },
597
+ });
598
+ const gasSettings = GasSettings.from({
599
+ ...estimatedGas!,
600
+ maxFeesPerGas,
601
+ maxPriorityFeesPerGas: GasFees.empty(),
602
+ });
603
+
604
+ await this.withNoMinTxsPerBlock(async () => {
605
+ const { txHash } = await minimalInteraction.send({
606
+ from: account,
607
+ fee: { gasSettings, paymentMethod },
608
+ wait: NO_WAIT,
609
+ });
610
+ this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
611
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
612
+ });
613
+ balance = await getFeeJuiceBalance(account, this.aztecNode);
614
+ this.log.info(`Fee juice balance after top-up: ${balance}`);
615
+ }
616
+ this.log.info(`Fee juice top-up complete for ${account.toString()}`);
617
+ }
618
+
366
619
  private async mintTokens(token: TokenContract | PrivateTokenContract, minter: AztecAddress) {
367
620
  const isStandardToken = isStandardTokenContract(token);
368
621
  let privateBalance = 0n;
@@ -393,8 +646,15 @@ export class BotFactory {
393
646
  return;
394
647
  }
395
648
 
649
+ // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
650
+ const additionalScopes = isStandardToken ? undefined : [token.address];
651
+ const mintBatch = new BatchCall(token.wallet, calls);
396
652
  await this.withNoMinTxsPerBlock(async () => {
397
- const txHash = await new BatchCall(token.wallet, calls).send({ from: minter, wait: NO_WAIT });
653
+ const { txHash } = await mintBatch.send({
654
+ from: minter,
655
+ additionalScopes,
656
+ wait: NO_WAIT,
657
+ });
398
658
  this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
399
659
  return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
400
660
  });
@@ -417,7 +677,6 @@ export class BotFactory {
417
677
  await this.withNoMinTxsPerBlock(() =>
418
678
  waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
419
679
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
420
- forPublicConsumption: false,
421
680
  }),
422
681
  );
423
682
  return existingClaim.claim;
@@ -456,7 +715,6 @@ export class BotFactory {
456
715
  await this.withNoMinTxsPerBlock(() =>
457
716
  waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
458
717
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
459
- forPublicConsumption: false,
460
718
  }),
461
719
  );
462
720
 
@@ -465,6 +723,19 @@ export class BotFactory {
465
723
  return claim as L2AmountClaim;
466
724
  }
467
725
 
726
+ /** Returns worst-case min fees across predicted slots, with fallback to current min fees. */
727
+ private async getMinFees(): Promise<GasFees> {
728
+ try {
729
+ const predicted = await this.aztecNode.getPredictedMinFees(ManaUsageEstimate.Limit);
730
+ if (predicted.length === 0) {
731
+ return this.aztecNode.getCurrentMinFees();
732
+ }
733
+ return predicted.reduce((worst, fees) => (fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst));
734
+ } catch {
735
+ return this.aztecNode.getCurrentMinFees();
736
+ }
737
+ }
738
+
468
739
  private async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
469
740
  if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
470
741
  this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { Bot } from './bot.js';
2
2
  export { AmmBot } from './amm_bot.js';
3
+ export { CrossChainBot } from './cross_chain_bot.js';
3
4
  export { BotRunner } from './runner.js';
4
5
  export { BotStore } from './store/bot_store.js';
5
6
  export {