@aztec/bot 0.0.1-commit.a072138 → 0.0.1-commit.a4600f49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dest/amm_bot.d.ts +6 -5
  2. package/dest/amm_bot.d.ts.map +1 -1
  3. package/dest/amm_bot.js +26 -19
  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 +5 -4
  8. package/dest/bot.d.ts.map +1 -1
  9. package/dest/bot.js +7 -10
  10. package/dest/config.d.ts +47 -82
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +42 -15
  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 +25 -6
  17. package/dest/factory.d.ts.map +1 -1
  18. package/dest/factory.js +201 -124
  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 +20 -2
  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 +28 -20
  39. package/src/base_bot.ts +16 -33
  40. package/src/bot.ts +11 -10
  41. package/src/config.ts +47 -18
  42. package/src/cross_chain_bot.ts +208 -0
  43. package/src/factory.ts +254 -129
  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 +60 -5
  49. package/src/store/index.ts +1 -1
  50. package/src/utils.ts +3 -3
package/src/factory.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { SchnorrAccountContract } from '@aztec/accounts/schnorr';
2
1
  import { getInitialTestAccountsData } from '@aztec/accounts/testing';
3
2
  import { AztecAddress } from '@aztec/aztec.js/addresses';
4
3
  import {
@@ -9,64 +8,76 @@ import {
9
8
  type DeployOptions,
10
9
  NO_WAIT,
11
10
  } from '@aztec/aztec.js/contracts';
12
- import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
13
11
  import type { L2AmountClaim } from '@aztec/aztec.js/ethereum';
12
+ import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
14
13
  import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
15
14
  import { deriveKeys } from '@aztec/aztec.js/keys';
16
15
  import { createLogger } from '@aztec/aztec.js/log';
17
16
  import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
18
17
  import { waitForTx } from '@aztec/aztec.js/node';
18
+ import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
19
19
  import { createEthereumChain } from '@aztec/ethereum/chain';
20
20
  import { createExtendedL1Client } from '@aztec/ethereum/client';
21
+ import { RollupContract } from '@aztec/ethereum/contracts';
22
+ import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
21
23
  import { Fr } from '@aztec/foundation/curves/bn254';
22
- import { Timer } from '@aztec/foundation/timer';
24
+ import { EthAddress } from '@aztec/foundation/eth-address';
23
25
  import { AMMContract } from '@aztec/noir-contracts.js/AMM';
24
26
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
25
27
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
28
+ import { TestContract } from '@aztec/noir-test-contracts.js/Test';
29
+ import type { BlockTag } from '@aztec/stdlib/block';
26
30
  import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
27
- import { GasSettings } from '@aztec/stdlib/gas';
28
31
  import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
29
32
  import { deriveSigningKey } from '@aztec/stdlib/keys';
30
- import { TestWallet } from '@aztec/test-wallet/server';
33
+ import { EmbeddedWallet } from '@aztec/wallets/embedded';
31
34
 
32
35
  import { type BotConfig, SupportedTokenContracts } from './config.js';
36
+ import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
33
37
  import type { BotStore } from './store/index.js';
34
38
  import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
35
39
 
36
40
  const MINT_BALANCE = 1e12;
37
41
  const MIN_BALANCE = 1e3;
42
+ const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
38
43
 
39
44
  export class BotFactory {
40
45
  private log = createLogger('bot');
41
46
 
42
47
  constructor(
43
48
  private readonly config: BotConfig,
44
- private readonly wallet: TestWallet,
49
+ private readonly wallet: EmbeddedWallet,
45
50
  private readonly store: BotStore,
46
51
  private readonly aztecNode: AztecNode,
47
52
  private readonly aztecNodeAdmin?: AztecNodeAdmin,
48
- ) {}
53
+ private readonly syncChainTip?: BlockTag,
54
+ ) {
55
+ // Set fee padding on the wallet so that all transactions during setup
56
+ // (token deploy, minting, etc.) use the configured padding, not the default.
57
+ this.wallet.setMinFeePadding(config.minFeePadding);
58
+ }
49
59
 
50
60
  /**
51
61
  * Initializes a new bot by setting up the sender account, registering the recipient,
52
62
  * deploying the token contract, and minting tokens if necessary.
53
63
  */
54
64
  public async setup(): Promise<{
55
- wallet: TestWallet;
65
+ wallet: EmbeddedWallet;
56
66
  defaultAccountAddress: AztecAddress;
57
67
  token: TokenContract | PrivateTokenContract;
58
68
  node: AztecNode;
59
69
  recipient: AztecAddress;
60
70
  }> {
61
71
  const defaultAccountAddress = await this.setupAccount();
62
- const recipient = (await this.wallet.createAccount()).address;
72
+ const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
73
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
63
74
  const token = await this.setupToken(defaultAccountAddress);
64
75
  await this.mintTokens(token, defaultAccountAddress);
65
76
  return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
66
77
  }
67
78
 
68
79
  public async setupAmm(): Promise<{
69
- wallet: TestWallet;
80
+ wallet: EmbeddedWallet;
70
81
  defaultAccountAddress: AztecAddress;
71
82
  amm: AMMContract;
72
83
  token0: TokenContract;
@@ -74,6 +85,7 @@ export class BotFactory {
74
85
  node: AztecNode;
75
86
  }> {
76
87
  const defaultAccountAddress = await this.setupAccount();
88
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
77
89
  const token0 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
78
90
  const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
79
91
  const liquidityToken = await this.setupTokenContract(
@@ -96,6 +108,87 @@ export class BotFactory {
96
108
  return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
97
109
  }
98
110
 
111
+ /**
112
+ * Initializes the cross-chain bot by deploying TestContract, creating an L1 client,
113
+ * seeding initial L1→L2 messages, and waiting for the first to be ready.
114
+ */
115
+ public async setupCrossChain(): Promise<{
116
+ wallet: EmbeddedWallet;
117
+ defaultAccountAddress: AztecAddress;
118
+ contract: TestContract;
119
+ node: AztecNode;
120
+ l1Client: ExtendedViemWalletClient;
121
+ rollupVersion: bigint;
122
+ }> {
123
+ const defaultAccountAddress = await this.setupAccount();
124
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
125
+
126
+ // Create L1 client (same pattern as bridgeL1FeeJuice)
127
+ const l1RpcUrls = this.config.l1RpcUrls;
128
+ if (!l1RpcUrls?.length) {
129
+ throw new Error('L1 RPC URLs required for cross-chain bot');
130
+ }
131
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
132
+ if (!mnemonicOrPrivateKey) {
133
+ throw new Error('L1 mnemonic or private key required for cross-chain bot');
134
+ }
135
+ const { l1ChainId, l1ContractAddresses } = await this.aztecNode.getNodeInfo();
136
+ const chain = createEthereumChain(l1RpcUrls, l1ChainId);
137
+ const l1Client = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
138
+
139
+ // Fetch Rollup version (needed for Inbox L2Actor struct)
140
+ const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
141
+ const rollupVersion = await rollupContract.getVersion();
142
+
143
+ // Deploy TestContract (pays from the standing balance funded above).
144
+ const contract = await this.setupTestContract(defaultAccountAddress);
145
+
146
+ // Recover any pending messages from store (clean up stale ones first)
147
+ await this.store.cleanupOldPendingMessages();
148
+ const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
149
+
150
+ // Seed initial L1→L2 messages if pipeline is empty
151
+ const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
152
+ for (let i = 0; i < seedCount; i++) {
153
+ await seedL1ToL2Message(
154
+ l1Client,
155
+ EthAddress.fromString(l1ContractAddresses.inboxAddress.toString()),
156
+ contract.address,
157
+ rollupVersion,
158
+ this.store,
159
+ this.log,
160
+ );
161
+ }
162
+
163
+ // Block until at least one message is ready
164
+ const allMessages = await this.store.getUnconsumedL1ToL2Messages();
165
+ if (allMessages.length > 0) {
166
+ this.log.info(`Waiting for first L1→L2 message to be ready...`);
167
+ const firstMsg = allMessages[0];
168
+ await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
169
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
170
+ chainTip: this.syncChainTip,
171
+ });
172
+ this.log.info(`First L1→L2 message is ready`);
173
+ }
174
+
175
+ return {
176
+ wallet: this.wallet,
177
+ defaultAccountAddress,
178
+ contract,
179
+ node: this.aztecNode,
180
+ l1Client,
181
+ rollupVersion,
182
+ };
183
+ }
184
+
185
+ private async setupTestContract(deployer: AztecAddress): Promise<TestContract> {
186
+ const deployOpts: DeployOptions = { from: deployer };
187
+ const deploy = TestContract.deploy(this.wallet, { salt: this.config.tokenSalt, universalDeploy: true });
188
+ const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
189
+ return TestContract.at(instance.address, this.wallet);
190
+ }
191
+
99
192
  /**
100
193
  * Checks if the sender account contract is initialized, and initializes it if necessary.
101
194
  * @returns The sender wallet.
@@ -111,112 +204,70 @@ export class BotFactory {
111
204
  }
112
205
  }
113
206
 
207
+ /**
208
+ * Keyless fallback for tests and local dev: reuses the first genesis test account, whose address is
209
+ * pre-funded with fee juice via `initialFundedAccounts`. The test accounts are initializerless, so this
210
+ * must create an initializerless account for the address to match the funded one. Production bots set a
211
+ * sender private key and fund the resulting initializerless account from L1 instead; see
212
+ * setupAccountWithPrivateKey.
213
+ */
214
+ private async setupTestAccount() {
215
+ const [initialAccountData] = await getInitialTestAccountsData();
216
+ const accountManager = await this.wallet.createSchnorrInitializerlessAccount(
217
+ initialAccountData.secret,
218
+ initialAccountData.salt,
219
+ initialAccountData.signingKey,
220
+ );
221
+ return accountManager.address;
222
+ }
223
+
114
224
  private async setupAccountWithPrivateKey(secret: Fr) {
115
225
  const salt = this.config.senderSalt ?? Fr.ONE;
116
226
  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);
123
- const metadata = await this.wallet.getContractMetadata(accountManager.address);
124
- if (metadata.isContractInitialized) {
125
- this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
126
- const timer = new Timer();
127
- const address = accountManager.address;
128
- this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
129
- await this.store.deleteBridgeClaim(address);
130
- return address;
131
- } else {
132
- const address = accountManager.address;
133
- this.log.info(`Deploying account at ${address}`);
134
-
135
- const claim = await this.getOrCreateBridgeClaim(address);
136
-
137
- const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
138
- const deployMethod = await accountManager.getDeployMethod();
139
- const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
140
- const gasSettings = GasSettings.default({ maxFeesPerGas });
141
-
142
- await this.withNoMinTxsPerBlock(async () => {
143
- const txHash = await deployMethod.send({
144
- from: AztecAddress.ZERO,
145
- fee: { gasSettings, paymentMethod },
146
- wait: NO_WAIT,
147
- });
148
- this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
149
- return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
150
- });
151
- this.log.info(`Account deployed at ${address}`);
152
-
153
- // Clean up the consumed bridge claim
154
- await this.store.deleteBridgeClaim(address);
155
-
156
- return accountManager.address;
157
- }
158
- }
159
-
160
- private async setupTestAccount() {
161
- 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);
227
+ const accountManager = await this.wallet.createSchnorrInitializerlessAccount(secret, salt, signingKey);
168
228
  return accountManager.address;
169
229
  }
170
230
 
171
231
  /**
172
232
  * 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.
233
+ * Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
234
+ * @param sender - Aztec address to deploy the token contract from.
235
+ * @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
236
+ * @returns The TokenContract or PrivateTokenContract instance.
175
237
  */
176
238
  private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
177
239
  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
- };
240
+ const salt = this.config.tokenSalt;
241
+ const deployOpts: DeployOptions = { from: sender };
184
242
  let token: TokenContract | PrivateTokenContract;
185
243
  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);
244
+ deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
245
+ const instance = await deploy.getInstance();
246
+ token = TokenContract.at(instance.address, this.wallet);
189
247
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
190
248
  // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
191
249
  const tokenSecretKey = Fr.random();
192
250
  const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
193
- deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
251
+ deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
252
+ salt,
253
+ universalDeploy: true,
254
+ publicKeys: tokenPublicKeys,
255
+ });
194
256
  deployOpts.skipInstancePublication = true;
195
257
  deployOpts.skipClassPublication = true;
196
258
  deployOpts.skipInitialization = false;
197
259
 
198
260
  // Register the contract with the secret key before deployment
199
- tokenInstance = await deploy.getInstance(deployOpts);
261
+ const tokenInstance = await deploy.getInstance();
200
262
  token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
201
263
  await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
264
+ // The contract constructor initializes private storage vars that need the contract's own nullifier key.
265
+ deployOpts.additionalScopes = [tokenInstance.address];
202
266
  } else {
203
267
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
204
268
  }
205
269
 
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
- }
270
+ await this.registerOrDeployContract('token', deploy, deployOpts);
220
271
  return token;
221
272
  }
222
273
 
@@ -227,33 +278,38 @@ export class BotFactory {
227
278
  */
228
279
  private async setupTokenContract(
229
280
  deployer: AztecAddress,
230
- contractAddressSalt: Fr,
281
+ salt: Fr,
231
282
  name: string,
232
283
  ticker: string,
233
284
  decimals = 18,
234
285
  ): Promise<TokenContract> {
235
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
236
- const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
286
+ const deployOpts: DeployOptions = { from: deployer };
287
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
237
288
  const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
238
289
  return TokenContract.at(instance.address, this.wallet);
239
290
  }
240
291
 
241
292
  private async setupAmmContract(
242
293
  deployer: AztecAddress,
243
- contractAddressSalt: Fr,
294
+ salt: Fr,
244
295
  token0: TokenContract,
245
296
  token1: TokenContract,
246
297
  lpToken: TokenContract,
247
298
  ): Promise<AMMContract> {
248
- const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
249
- const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
299
+ const deployOpts: DeployOptions = { from: deployer };
300
+ const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address, {
301
+ salt,
302
+ universalDeploy: true,
303
+ });
250
304
  const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
251
305
  const amm = AMMContract.at(instance.address, this.wallet);
252
306
 
253
307
  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 } });
308
+ const setMinterInteraction = lpToken.methods.set_minter(amm.address, true);
309
+ const { receipt: minterReceipt } = await setMinterInteraction.send({
310
+ from: deployer,
311
+ wait: { timeout: this.config.txMinedWaitSeconds },
312
+ });
257
313
  this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
258
314
  this.log.info(`Liquidity token initialized`);
259
315
 
@@ -270,9 +326,18 @@ export class BotFactory {
270
326
  ): Promise<void> {
271
327
  const getPrivateBalances = () =>
272
328
  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 }),
329
+ token0.methods
330
+ .balance_of_private(liquidityProvider)
331
+ .simulate({ from: liquidityProvider })
332
+ .then(r => r.result),
333
+ token1.methods
334
+ .balance_of_private(liquidityProvider)
335
+ .simulate({ from: liquidityProvider })
336
+ .then(r => r.result),
337
+ lpToken.methods
338
+ .balance_of_private(liquidityProvider)
339
+ .simulate({ from: liquidityProvider })
340
+ .then(r => r.result),
276
341
  ]);
277
342
 
278
343
  const authwitNonce = Fr.random();
@@ -313,20 +378,29 @@ export class BotFactory {
313
378
  .getFunctionCall(),
314
379
  });
315
380
 
316
- const mintReceipt = await new BatchCall(this.wallet, [
381
+ const mintBatch = new BatchCall(this.wallet, [
317
382
  token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
318
383
  token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
319
- ]).send({ from: liquidityProvider, wait: { timeout: this.config.txMinedWaitSeconds } });
384
+ ]);
385
+ const { receipt: mintReceipt } = await mintBatch.send({
386
+ from: liquidityProvider,
387
+ wait: { timeout: this.config.txMinedWaitSeconds },
388
+ });
320
389
 
321
390
  this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
322
391
 
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
- });
392
+ const addLiquidityInteraction = amm.methods.add_liquidity(
393
+ amount0Max,
394
+ amount1Max,
395
+ amount0Min,
396
+ amount1Min,
397
+ authwitNonce,
398
+ );
399
+ const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
400
+ from: liquidityProvider,
401
+ authWitnesses: [token0Authwit, token1Authwit],
402
+ wait: { timeout: this.config.txMinedWaitSeconds },
403
+ });
330
404
 
331
405
  this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`);
332
406
  this.log.info(`Liquidity added`);
@@ -342,27 +416,75 @@ export class BotFactory {
342
416
  deploy: DeployMethod<T>,
343
417
  deployOpts: DeployOptions,
344
418
  ): Promise<ContractInstanceWithAddress> {
345
- const instance = await deploy.getInstance(deployOpts);
419
+ const instance = await deploy.getInstance();
346
420
  const address = instance.address;
347
421
  const metadata = await this.wallet.getContractMetadata(address);
348
422
  if (metadata.isContractPublished) {
349
423
  this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
350
424
  await deploy.register();
351
- } 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
- });
425
+ return instance;
358
426
  }
427
+
428
+ // Setup always runs ensureFeeJuiceBalance before any deploy, so the account pays from its standing
429
+ // balance here. No manual gas estimation: the embedded wallet simulates before sending and derives
430
+ // the gas limits and padded maxFeesPerGas itself.
431
+ this.log.info(`Deploying contract ${name} at ${address.toString()}`);
432
+ await this.withNoMinTxsPerBlock(async () => {
433
+ const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
434
+ this.log.info(`Sent contract ${name} deploy tx ${txHash.toString()}`);
435
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
436
+ });
437
+
359
438
  return instance;
360
439
  }
361
440
 
441
+ /** True when the config allows bridging fee juice from L1 (fee_juice mode, an L1 RPC, and an L1 key). */
442
+ private isL1BridgingConfigured(): boolean {
443
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
444
+ return this.config.feePaymentMethod === 'fee_juice' && !!this.config.l1RpcUrls?.length && !!mnemonicOrPrivateKey;
445
+ }
446
+
362
447
  /**
363
- * Mints private and public tokens for the sender if their balance is below the minimum.
364
- * @param token - Token contract.
448
+ * Ensures the account holds enough fee juice before any other setup step. The account starts empty
449
+ * (initializerless accounts have no deployment tx) and the runtime loop pays fees from this balance and
450
+ * never refuels itself, so every flow funds the account up front. Bridges claims from L1 and consumes
451
+ * each with a claim-only tx until the balance clears the threshold, working from a zero (fresh run) or
452
+ * drained (restart) balance. Each bridge mints a fixed amount well above the threshold, so this is a
453
+ * single bridge in practice. No-op when L1 bridging is not configured or the balance is already above
454
+ * the threshold.
365
455
  */
456
+ private async ensureFeeJuiceBalance(account: AztecAddress): Promise<void> {
457
+ if (!this.isL1BridgingConfigured()) {
458
+ return;
459
+ }
460
+
461
+ let balance = await getFeeJuiceBalance(account, this.aztecNode);
462
+ if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
463
+ this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
464
+ return;
465
+ }
466
+
467
+ this.log.info(`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1`);
468
+
469
+ while (balance < FEE_JUICE_TOP_UP_THRESHOLD) {
470
+ // Persist the claim before consuming it: if the top-up tx fails or the bot crashes mid-loop, the
471
+ // next run reuses the pending claim instead of bridging again (and wasting the bridged funds).
472
+ const claim = await this.getOrCreateBridgeClaim(account);
473
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
474
+
475
+ await this.withNoMinTxsPerBlock(async () => {
476
+ const executionPayload = await paymentMethod.getExecutionPayload();
477
+ const { txHash } = await this.wallet.sendTx(executionPayload, { from: account, wait: NO_WAIT });
478
+ this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
479
+ return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
480
+ });
481
+ await this.store.deleteBridgeClaim(account);
482
+ balance = await getFeeJuiceBalance(account, this.aztecNode);
483
+ this.log.info(`Fee juice balance after top-up: ${balance}`);
484
+ }
485
+ this.log.info(`Fee juice top-up complete for ${account.toString()}`);
486
+ }
487
+
366
488
  private async mintTokens(token: TokenContract | PrivateTokenContract, minter: AztecAddress) {
367
489
  const isStandardToken = isStandardTokenContract(token);
368
490
  let privateBalance = 0n;
@@ -393,31 +515,35 @@ export class BotFactory {
393
515
  return;
394
516
  }
395
517
 
518
+ // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
519
+ const additionalScopes = isStandardToken ? undefined : [token.address];
520
+ const mintBatch = new BatchCall(token.wallet, calls);
396
521
  await this.withNoMinTxsPerBlock(async () => {
397
- const txHash = await new BatchCall(token.wallet, calls).send({ from: minter, wait: NO_WAIT });
522
+ const { txHash } = await mintBatch.send({
523
+ from: minter,
524
+ additionalScopes,
525
+ wait: NO_WAIT,
526
+ });
398
527
  this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
399
528
  return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
400
529
  });
401
530
  }
402
531
 
403
532
  /**
404
- * Gets or creates a bridge claim for the recipient.
405
- * Checks if a claim already exists in the store and reuses it if valid.
406
- * Only creates a new bridge if fee juice balance is below threshold.
533
+ * Returns a usable bridge claim for the recipient, reusing a persisted one when its L1→L2 message is
534
+ * still available (resuming a top-up that failed or crashed before the claim was consumed) and bridging
535
+ * a fresh claim otherwise. The caller deletes the claim from the store once it has been consumed.
407
536
  */
408
537
  private async getOrCreateBridgeClaim(recipient: AztecAddress): Promise<L2AmountClaim> {
409
- // Check if we have an existing claim in the store
410
538
  const existingClaim = await this.store.getBridgeClaim(recipient);
411
539
  if (existingClaim) {
412
540
  this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
413
-
414
- // Check if the message is ready on L2
415
541
  try {
416
542
  const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
417
543
  await this.withNoMinTxsPerBlock(() =>
418
544
  waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
419
545
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
420
- forPublicConsumption: false,
546
+ chainTip: this.syncChainTip,
421
547
  }),
422
548
  );
423
549
  return existingClaim.claim;
@@ -429,7 +555,6 @@ export class BotFactory {
429
555
 
430
556
  const claim = await this.bridgeL1FeeJuice(recipient);
431
557
  await this.store.saveBridgeClaim(recipient, claim);
432
-
433
558
  return claim;
434
559
  }
435
560
 
@@ -456,7 +581,7 @@ export class BotFactory {
456
581
  await this.withNoMinTxsPerBlock(() =>
457
582
  waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
458
583
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
459
- forPublicConsumption: false,
584
+ chainTip: this.syncChainTip,
460
585
  }),
461
586
  );
462
587
 
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 {
package/src/interface.ts CHANGED
@@ -22,11 +22,11 @@ export interface BotRunnerApi {
22
22
  }
23
23
 
24
24
  export const BotRunnerApiSchema: ApiSchemaFor<BotRunnerApi> = {
25
- start: z.function().args().returns(z.void()),
26
- stop: z.function().args().returns(z.void()),
27
- run: z.function().args().returns(z.void()),
28
- setup: z.function().args().returns(z.void()),
29
- getInfo: z.function().args().returns(BotInfoSchema),
30
- getConfig: z.function().args().returns(BotConfigSchema),
31
- update: z.function().args(BotConfigSchema).returns(z.void()),
25
+ start: z.function({ input: z.tuple([]), output: z.void() }),
26
+ stop: z.function({ input: z.tuple([]), output: z.void() }),
27
+ run: z.function({ input: z.tuple([]), output: z.void() }),
28
+ setup: z.function({ input: z.tuple([]), output: z.void() }),
29
+ getInfo: z.function({ input: z.tuple([]), output: BotInfoSchema }),
30
+ getConfig: z.function({ input: z.tuple([]), output: BotConfigSchema }),
31
+ update: z.function({ input: z.tuple([BotConfigSchema]), output: z.void() }),
32
32
  };