@aztec/bot 0.0.1-commit.7b97ef96e → 0.0.1-commit.7cbc774

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dest/factory.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { getInitialTestAccountsData } from '@aztec/accounts/testing';
2
- import { AztecAddress } from '@aztec/aztec.js/addresses';
2
+ import { NO_FROM } from '@aztec/aztec.js/account';
3
3
  import { BatchCall, NO_WAIT } from '@aztec/aztec.js/contracts';
4
4
  import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
5
5
  import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
@@ -7,6 +7,8 @@ import { deriveKeys } from '@aztec/aztec.js/keys';
7
7
  import { createLogger } from '@aztec/aztec.js/log';
8
8
  import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
9
9
  import { waitForTx } from '@aztec/aztec.js/node';
10
+ import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
11
+ import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
10
12
  import { createEthereumChain } from '@aztec/ethereum/chain';
11
13
  import { createExtendedL1Client } from '@aztec/ethereum/client';
12
14
  import { RollupContract } from '@aztec/ethereum/contracts';
@@ -17,13 +19,15 @@ import { AMMContract } from '@aztec/noir-contracts.js/AMM';
17
19
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
18
20
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
19
21
  import { TestContract } from '@aztec/noir-test-contracts.js/Test';
20
- import { GasSettings } from '@aztec/stdlib/gas';
22
+ import { GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
21
23
  import { deriveSigningKey } from '@aztec/stdlib/keys';
22
24
  import { SupportedTokenContracts } from './config.js';
23
25
  import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
24
26
  import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
25
27
  const MINT_BALANCE = 1e12;
26
28
  const MIN_BALANCE = 1e3;
29
+ const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
30
+ const FEE_JUICE_TOP_UP_TARGET = 10_000n * 10n ** 18n;
27
31
  export class BotFactory {
28
32
  config;
29
33
  wallet;
@@ -38,6 +42,9 @@ export class BotFactory {
38
42
  this.aztecNode = aztecNode;
39
43
  this.aztecNodeAdmin = aztecNodeAdmin;
40
44
  this.log = createLogger('bot');
45
+ // Set fee padding on the wallet so that all transactions during setup
46
+ // (token deploy, minting, etc.) use the configured padding, not the default.
47
+ this.wallet.setMinFeePadding(config.minFeePadding);
41
48
  }
42
49
  /**
43
50
  * Initializes a new bot by setting up the sender account, registering the recipient,
@@ -45,7 +52,8 @@ export class BotFactory {
45
52
  */ async setup() {
46
53
  const defaultAccountAddress = await this.setupAccount();
47
54
  const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
48
- const token = await this.setupToken(defaultAccountAddress);
55
+ const token = await this.setupTokenWithOptionalEarlyRefuel(defaultAccountAddress);
56
+ await this.ensureFeeJuiceBalance(defaultAccountAddress, token);
49
57
  await this.mintTokens(token, defaultAccountAddress);
50
58
  return {
51
59
  wallet: this.wallet,
@@ -57,7 +65,8 @@ export class BotFactory {
57
65
  }
58
66
  async setupAmm() {
59
67
  const defaultAccountAddress = await this.setupAccount();
60
- const token0 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
68
+ const token0 = await this.setupTokenContractWithOptionalEarlyRefuel(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
69
+ await this.ensureFeeJuiceBalance(defaultAccountAddress, token0);
61
70
  const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
62
71
  const liquidityToken = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotLPToken', 'BOTLP');
63
72
  const amm = await this.setupAmmContract(defaultAccountAddress, this.config.tokenSalt, token0, token1, liquidityToken);
@@ -108,12 +117,7 @@ export class BotFactory {
108
117
  this.log.info(`Waiting for first L1→L2 message to be ready...`);
109
118
  const firstMsg = allMessages[0];
110
119
  await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
111
- timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
112
- // Use forPublicConsumption: false so we wait until the message is in the current world
113
- // state. With true, it returns one block early which causes gas estimation simulation to
114
- // fail since it runs against the current state.
115
- // See https://linear.app/aztec-labs/issue/A-548 for details.
116
- forPublicConsumption: false
120
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds
117
121
  });
118
122
  this.log.info(`First L1→L2 message is ready`);
119
123
  }
@@ -128,11 +132,12 @@ export class BotFactory {
128
132
  }
129
133
  async setupTestContract(deployer) {
130
134
  const deployOpts = {
131
- from: deployer,
132
- contractAddressSalt: this.config.tokenSalt,
133
- universalDeploy: true
135
+ from: deployer
134
136
  };
135
- const deploy = TestContract.deploy(this.wallet);
137
+ const deploy = TestContract.deploy(this.wallet, {
138
+ salt: this.config.tokenSalt,
139
+ universalDeploy: true
140
+ });
136
141
  const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
137
142
  return TestContract.at(instance.address, this.wallet);
138
143
  }
@@ -154,7 +159,7 @@ export class BotFactory {
154
159
  const signingKey = deriveSigningKey(secret);
155
160
  const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
156
161
  const metadata = await this.wallet.getContractMetadata(accountManager.address);
157
- if (metadata.isContractInitialized) {
162
+ if (metadata.initializationStatus === ContractInitializationStatus.INITIALIZED) {
158
163
  this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
159
164
  const timer = new Timer();
160
165
  const address = accountManager.address;
@@ -167,15 +172,10 @@ export class BotFactory {
167
172
  const claim = await this.getOrCreateBridgeClaim(address);
168
173
  const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
169
174
  const deployMethod = await accountManager.getDeployMethod();
170
- const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
171
- const gasSettings = GasSettings.default({
172
- maxFeesPerGas
173
- });
174
175
  await this.withNoMinTxsPerBlock(async ()=>{
175
- const txHash = await deployMethod.send({
176
- from: AztecAddress.ZERO,
176
+ const { txHash } = await deployMethod.send({
177
+ from: NO_FROM,
177
178
  fee: {
178
- gasSettings,
179
179
  paymentMethod
180
180
  },
181
181
  wait: NO_WAIT
@@ -197,32 +197,92 @@ export class BotFactory {
197
197
  return accountManager.address;
198
198
  }
199
199
  /**
200
+ * Setup token and refuel first: if the token already exists (restart scenario),
201
+ * run ensureFeeJuiceBalance before any step that might need fee juice. When deploying,
202
+ * use a bridge claim if balance is below threshold.
203
+ */ async setupTokenWithOptionalEarlyRefuel(sender) {
204
+ const token = await this.getTokenInstance(sender);
205
+ const address = token.address;
206
+ const metadata = await this.wallet.getContractMetadata(address);
207
+ if (metadata.isContractPublished) {
208
+ this.log.info(`Token at ${address.toString()} already deployed, refueling before setup`);
209
+ await this.ensureFeeJuiceBalance(sender, token);
210
+ }
211
+ return this.setupToken(sender);
212
+ }
213
+ /**
214
+ * Setup token0 for AMM with refuel-first behaviour when token already exists.
215
+ */ async setupTokenContractWithOptionalEarlyRefuel(deployer, salt, name, ticker, decimals = 18) {
216
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, {
217
+ salt,
218
+ universalDeploy: true
219
+ });
220
+ const instance = await deploy.getInstance();
221
+ const metadata = await this.wallet.getContractMetadata(instance.address);
222
+ if (metadata.isContractPublished) {
223
+ this.log.info(`Token ${name} at ${instance.address.toString()} already deployed, refueling before setup`);
224
+ const token = TokenContract.at(instance.address, this.wallet);
225
+ await this.ensureFeeJuiceBalance(deployer, token);
226
+ }
227
+ return this.setupTokenContract(deployer, salt, name, ticker, decimals);
228
+ }
229
+ async getTokenInstance(sender) {
230
+ const salt = this.config.tokenSalt;
231
+ if (this.config.contract === SupportedTokenContracts.TokenContract) {
232
+ const deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, {
233
+ salt,
234
+ universalDeploy: true
235
+ });
236
+ const instance = await deploy.getInstance();
237
+ return TokenContract.at(instance.address, this.wallet);
238
+ }
239
+ if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
240
+ const tokenSecretKey = Fr.random();
241
+ const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
242
+ const deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
243
+ salt,
244
+ universalDeploy: true,
245
+ publicKeys: tokenPublicKeys
246
+ });
247
+ const instance = await deploy.getInstance();
248
+ return PrivateTokenContract.at(instance.address, this.wallet);
249
+ }
250
+ throw new Error(`Unsupported token contract type: ${this.config.contract}`);
251
+ }
252
+ /**
200
253
  * Checks if the token contract is deployed and deploys it if necessary.
201
- * @param wallet - Wallet to deploy the token contract from.
202
- * @returns The TokenContract instance.
254
+ * Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
255
+ * @param sender - Aztec address to deploy the token contract from.
256
+ * @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
257
+ * @returns The TokenContract or PrivateTokenContract instance.
203
258
  */ async setupToken(sender) {
204
259
  let deploy;
205
- let tokenInstance;
260
+ const salt = this.config.tokenSalt;
206
261
  const deployOpts = {
207
- from: sender,
208
- contractAddressSalt: this.config.tokenSalt,
209
- universalDeploy: true
262
+ from: sender
210
263
  };
211
264
  let token;
212
265
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
213
- deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
214
- tokenInstance = await deploy.getInstance(deployOpts);
215
- token = TokenContract.at(tokenInstance.address, this.wallet);
266
+ deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, {
267
+ salt,
268
+ universalDeploy: true
269
+ });
270
+ const instance = await deploy.getInstance();
271
+ token = TokenContract.at(instance.address, this.wallet);
216
272
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
217
273
  // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
218
274
  const tokenSecretKey = Fr.random();
219
275
  const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
220
- deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
276
+ deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
277
+ salt,
278
+ universalDeploy: true,
279
+ publicKeys: tokenPublicKeys
280
+ });
221
281
  deployOpts.skipInstancePublication = true;
222
282
  deployOpts.skipClassPublication = true;
223
283
  deployOpts.skipInitialization = false;
224
284
  // Register the contract with the secret key before deployment
225
- tokenInstance = await deploy.getInstance(deployOpts);
285
+ const tokenInstance = await deploy.getInstance();
226
286
  token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
227
287
  await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
228
288
  // The contract constructor initializes private storage vars that need the contract's own nullifier key.
@@ -232,52 +292,37 @@ export class BotFactory {
232
292
  } else {
233
293
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
234
294
  }
235
- const address = tokenInstance?.address ?? (await deploy.getInstance(deployOpts)).address;
236
- const metadata = await this.wallet.getContractMetadata(address);
237
- if (metadata.isContractPublished) {
238
- this.log.info(`Token at ${address.toString()} already deployed`);
239
- await deploy.register();
240
- } else {
241
- this.log.info(`Deploying token contract at ${address.toString()}`);
242
- const txHash = await deploy.send({
243
- ...deployOpts,
244
- wait: NO_WAIT
245
- });
246
- this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
247
- await this.withNoMinTxsPerBlock(async ()=>{
248
- await waitForTx(this.aztecNode, txHash, {
249
- timeout: this.config.txMinedWaitSeconds
250
- });
251
- return token;
252
- });
253
- }
295
+ await this.registerOrDeployContract('token', deploy, deployOpts);
254
296
  return token;
255
297
  }
256
298
  /**
257
299
  * Checks if the token contract is deployed and deploys it if necessary.
258
300
  * @param wallet - Wallet to deploy the token contract from.
259
301
  * @returns The TokenContract instance.
260
- */ async setupTokenContract(deployer, contractAddressSalt, name, ticker, decimals = 18) {
302
+ */ async setupTokenContract(deployer, salt, name, ticker, decimals = 18) {
261
303
  const deployOpts = {
262
- from: deployer,
263
- contractAddressSalt,
264
- universalDeploy: true
304
+ from: deployer
265
305
  };
266
- const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
306
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, {
307
+ salt,
308
+ universalDeploy: true
309
+ });
267
310
  const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
268
311
  return TokenContract.at(instance.address, this.wallet);
269
312
  }
270
- async setupAmmContract(deployer, contractAddressSalt, token0, token1, lpToken) {
313
+ async setupAmmContract(deployer, salt, token0, token1, lpToken) {
271
314
  const deployOpts = {
272
- from: deployer,
273
- contractAddressSalt,
274
- universalDeploy: true
315
+ from: deployer
275
316
  };
276
- const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
317
+ const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address, {
318
+ salt,
319
+ universalDeploy: true
320
+ });
277
321
  const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
278
322
  const amm = AMMContract.at(instance.address, this.wallet);
279
323
  this.log.info(`AMM deployed at ${amm.address}`);
280
- const minterReceipt = await lpToken.methods.set_minter(amm.address, true).send({
324
+ const setMinterInteraction = lpToken.methods.set_minter(amm.address, true);
325
+ const { receipt: minterReceipt } = await setMinterInteraction.send({
281
326
  from: deployer,
282
327
  wait: {
283
328
  timeout: this.config.txMinedWaitSeconds
@@ -291,13 +336,13 @@ export class BotFactory {
291
336
  const getPrivateBalances = ()=>Promise.all([
292
337
  token0.methods.balance_of_private(liquidityProvider).simulate({
293
338
  from: liquidityProvider
294
- }),
339
+ }).then((r)=>r.result),
295
340
  token1.methods.balance_of_private(liquidityProvider).simulate({
296
341
  from: liquidityProvider
297
- }),
342
+ }).then((r)=>r.result),
298
343
  lpToken.methods.balance_of_private(liquidityProvider).simulate({
299
344
  from: liquidityProvider
300
- })
345
+ }).then((r)=>r.result)
301
346
  ]);
302
347
  const authwitNonce = Fr.random();
303
348
  // keep some tokens for swapping
@@ -316,17 +361,19 @@ export class BotFactory {
316
361
  caller: amm.address,
317
362
  call: await token1.methods.transfer_to_public_and_prepare_private_balance_increase(liquidityProvider, amm.address, amount1Max, authwitNonce).getFunctionCall()
318
363
  });
319
- const mintReceipt = await new BatchCall(this.wallet, [
364
+ const mintBatch = new BatchCall(this.wallet, [
320
365
  token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
321
366
  token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE)
322
- ]).send({
367
+ ]);
368
+ const { receipt: mintReceipt } = await mintBatch.send({
323
369
  from: liquidityProvider,
324
370
  wait: {
325
371
  timeout: this.config.txMinedWaitSeconds
326
372
  }
327
373
  });
328
374
  this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
329
- const addLiquidityReceipt = await amm.methods.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce).send({
375
+ const addLiquidityInteraction = amm.methods.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce);
376
+ const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
330
377
  from: liquidityProvider,
331
378
  authWitnesses: [
332
379
  token0Authwit,
@@ -342,31 +389,134 @@ export class BotFactory {
342
389
  this.log.info(`Updated private balances of ${defaultAccountAddress} after minting and funding AMM: token0=${newT0Bal}, token1=${newT1Bal}, lp=${newLPBal}`);
343
390
  }
344
391
  async registerOrDeployContract(name, deploy, deployOpts) {
345
- const instance = await deploy.getInstance(deployOpts);
392
+ const instance = await deploy.getInstance();
346
393
  const address = instance.address;
347
394
  const metadata = await this.wallet.getContractMetadata(address);
348
395
  if (metadata.isContractPublished) {
349
396
  this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
350
397
  await deploy.register();
351
398
  } else {
352
- this.log.info(`Deploying contract ${name} at ${address.toString()}`);
353
- await this.withNoMinTxsPerBlock(async ()=>{
354
- const txHash = await deploy.send({
399
+ const sender = deployOpts.from === NO_FROM ? undefined : deployOpts.from;
400
+ const balance = sender ? await getFeeJuiceBalance(sender, this.aztecNode) : 0n;
401
+ const useClaim = sender && balance < FEE_JUICE_TOP_UP_THRESHOLD && this.config.feePaymentMethod === 'fee_juice' && !!this.config.l1RpcUrls?.length;
402
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
403
+ if (useClaim && mnemonicOrPrivateKey) {
404
+ const claim = await this.getOrCreateBridgeClaim(sender);
405
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(sender, claim);
406
+ const { estimatedGas } = await deploy.simulate({
355
407
  ...deployOpts,
356
- wait: NO_WAIT
408
+ fee: {
409
+ estimateGas: true,
410
+ paymentMethod
411
+ }
357
412
  });
358
- this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
359
- return waitForTx(this.aztecNode, txHash, {
360
- timeout: this.config.txMinedWaitSeconds
413
+ const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
414
+ const gasSettings = GasSettings.from({
415
+ ...estimatedGas,
416
+ maxFeesPerGas,
417
+ maxPriorityFeesPerGas: GasFees.empty()
361
418
  });
362
- });
419
+ await this.withNoMinTxsPerBlock(async ()=>{
420
+ const { txHash } = await deploy.send({
421
+ ...deployOpts,
422
+ fee: {
423
+ gasSettings,
424
+ paymentMethod
425
+ },
426
+ wait: NO_WAIT
427
+ });
428
+ this.log.info(`Sent contract ${name} deploy tx ${txHash.toString()} (using bridge claim, balance was ${balance})`);
429
+ return waitForTx(this.aztecNode, txHash, {
430
+ timeout: this.config.txMinedWaitSeconds
431
+ });
432
+ });
433
+ await this.store.deleteBridgeClaim(sender);
434
+ } else {
435
+ const { estimatedGas } = await deploy.simulate({
436
+ ...deployOpts,
437
+ fee: {
438
+ estimateGas: true
439
+ }
440
+ });
441
+ this.log.info(`Deploying contract ${name} at ${address.toString()}`, {
442
+ estimatedGas
443
+ });
444
+ await this.withNoMinTxsPerBlock(async ()=>{
445
+ const { txHash } = await deploy.send({
446
+ ...deployOpts,
447
+ fee: {
448
+ gasSettings: estimatedGas
449
+ },
450
+ wait: NO_WAIT
451
+ });
452
+ this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
453
+ return waitForTx(this.aztecNode, txHash, {
454
+ timeout: this.config.txMinedWaitSeconds
455
+ });
456
+ });
457
+ }
363
458
  }
364
459
  return instance;
365
460
  }
366
461
  /**
367
462
  * Mints private and public tokens for the sender if their balance is below the minimum.
368
463
  * @param token - Token contract.
369
- */ async mintTokens(token, minter) {
464
+ */ /**
465
+ * Ensures the account has sufficient fee juice by bridging from L1 if balance is below threshold.
466
+ * Bridges repeatedly until balance reaches the target (10k FJ).
467
+ * Used on startup/restart to top up when the account has run out after previous runs.
468
+ */ async ensureFeeJuiceBalance(account, token) {
469
+ const { feePaymentMethod, l1RpcUrls } = this.config;
470
+ if (feePaymentMethod !== 'fee_juice' || !l1RpcUrls?.length) {
471
+ return;
472
+ }
473
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
474
+ if (!mnemonicOrPrivateKey) {
475
+ return;
476
+ }
477
+ let balance = await getFeeJuiceBalance(account, this.aztecNode);
478
+ if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
479
+ this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
480
+ return;
481
+ }
482
+ this.log.info(`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1 until ${FEE_JUICE_TOP_UP_TARGET}`);
483
+ const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
484
+ const minimalInteraction = isStandardTokenContract(token) ? token.methods.transfer_in_public(account, account, 0n, 0) : token.methods.transfer(0n, account, account);
485
+ while(balance < FEE_JUICE_TOP_UP_TARGET){
486
+ const claim = await this.bridgeL1FeeJuice(account);
487
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
488
+ const { estimatedGas } = await minimalInteraction.simulate({
489
+ from: account,
490
+ fee: {
491
+ estimateGas: true,
492
+ paymentMethod
493
+ }
494
+ });
495
+ const gasSettings = GasSettings.from({
496
+ ...estimatedGas,
497
+ maxFeesPerGas,
498
+ maxPriorityFeesPerGas: GasFees.empty()
499
+ });
500
+ await this.withNoMinTxsPerBlock(async ()=>{
501
+ const { txHash } = await minimalInteraction.send({
502
+ from: account,
503
+ fee: {
504
+ gasSettings,
505
+ paymentMethod
506
+ },
507
+ wait: NO_WAIT
508
+ });
509
+ this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
510
+ return waitForTx(this.aztecNode, txHash, {
511
+ timeout: this.config.txMinedWaitSeconds
512
+ });
513
+ });
514
+ balance = await getFeeJuiceBalance(account, this.aztecNode);
515
+ this.log.info(`Fee juice balance after top-up: ${balance}`);
516
+ }
517
+ this.log.info(`Fee juice top-up complete for ${account.toString()}`);
518
+ }
519
+ async mintTokens(token, minter) {
370
520
  const isStandardToken = isStandardTokenContract(token);
371
521
  let privateBalance = 0n;
372
522
  let publicBalance = 0n;
@@ -392,8 +542,9 @@ export class BotFactory {
392
542
  const additionalScopes = isStandardToken ? undefined : [
393
543
  token.address
394
544
  ];
545
+ const mintBatch = new BatchCall(token.wallet, calls);
395
546
  await this.withNoMinTxsPerBlock(async ()=>{
396
- const txHash = await new BatchCall(token.wallet, calls).send({
547
+ const { txHash } = await mintBatch.send({
397
548
  from: minter,
398
549
  additionalScopes,
399
550
  wait: NO_WAIT
@@ -417,8 +568,7 @@ export class BotFactory {
417
568
  try {
418
569
  const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
419
570
  await this.withNoMinTxsPerBlock(()=>waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
420
- timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
421
- forPublicConsumption: false
571
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds
422
572
  }));
423
573
  return existingClaim.claim;
424
574
  } catch (err) {
@@ -446,12 +596,22 @@ export class BotFactory {
446
596
  const mintAmount = await portal.getTokenManager().getMintAmount();
447
597
  const claim = await portal.bridgeTokensPublic(recipient, mintAmount, true);
448
598
  await this.withNoMinTxsPerBlock(()=>waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
449
- timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
450
- forPublicConsumption: false
599
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds
451
600
  }));
452
601
  this.log.info(`Created a claim for ${mintAmount} L1 fee juice to ${recipient}.`, claim);
453
602
  return claim;
454
603
  }
604
+ /** Returns worst-case min fees across predicted slots, with fallback to current min fees. */ async getMinFees() {
605
+ try {
606
+ const predicted = await this.aztecNode.getPredictedMinFees(ManaUsageEstimate.Limit);
607
+ if (predicted.length === 0) {
608
+ return this.aztecNode.getCurrentMinFees();
609
+ }
610
+ return predicted.reduce((worst, fees)=>fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst);
611
+ } catch {
612
+ return this.aztecNode.getCurrentMinFees();
613
+ }
614
+ }
455
615
  async withNoMinTxsPerBlock(fn) {
456
616
  if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
457
617
  this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
@@ -4,11 +4,7 @@ import { z } from 'zod';
4
4
  import { type BotConfig } from './config.js';
5
5
  export declare const BotInfoSchema: z.ZodObject<{
6
6
  botAddress: import("@aztec/stdlib/schemas").ZodFor<AztecAddress>;
7
- }, "strip", z.ZodTypeAny, {
8
- botAddress: AztecAddress;
9
- }, {
10
- botAddress?: any;
11
- }>;
7
+ }, z.core.$strip>;
12
8
  export type BotInfo = z.infer<typeof BotInfoSchema>;
13
9
  export interface BotRunnerApi {
14
10
  start(): Promise<void>;
@@ -20,4 +16,4 @@ export interface BotRunnerApi {
20
16
  update(config: BotConfig): Promise<void>;
21
17
  }
22
18
  export declare const BotRunnerApiSchema: ApiSchemaFor<BotRunnerApi>;
23
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW50ZXJmYWNlLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvaW50ZXJmYWNlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sRUFBRSxZQUFZLEVBQUUsTUFBTSwyQkFBMkIsQ0FBQztBQUN6RCxPQUFPLEtBQUssRUFBRSxZQUFZLEVBQUUsTUFBTSx1QkFBdUIsQ0FBQztBQUUxRCxPQUFPLEVBQUUsQ0FBQyxFQUFFLE1BQU0sS0FBSyxDQUFDO0FBRXhCLE9BQU8sRUFBRSxLQUFLLFNBQVMsRUFBbUIsTUFBTSxhQUFhLENBQUM7QUFFOUQsZUFBTyxNQUFNLGFBQWE7Ozs7OztFQUV4QixDQUFDO0FBRUgsTUFBTSxNQUFNLE9BQU8sR0FBRyxDQUFDLENBQUMsS0FBSyxDQUFDLE9BQU8sYUFBYSxDQUFDLENBQUM7QUFFcEQsTUFBTSxXQUFXLFlBQVk7SUFDM0IsS0FBSyxJQUFJLE9BQU8sQ0FBQyxJQUFJLENBQUMsQ0FBQztJQUN2QixJQUFJLElBQUksT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQ3RCLEdBQUcsSUFBSSxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUM7SUFDckIsS0FBSyxJQUFJLE9BQU8sQ0FBQyxJQUFJLENBQUMsQ0FBQztJQUN2QixTQUFTLElBQUksT0FBTyxDQUFDLFNBQVMsQ0FBQyxDQUFDO0lBQ2hDLE9BQU8sSUFBSSxPQUFPLENBQUMsT0FBTyxDQUFDLENBQUM7SUFDNUIsTUFBTSxDQUFDLE1BQU0sRUFBRSxTQUFTLEdBQUcsT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDO0NBQzFDO0FBRUQsZUFBTyxNQUFNLGtCQUFrQixFQUFFLFlBQVksQ0FBQyxZQUFZLENBUXpELENBQUMifQ==
19
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW50ZXJmYWNlLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvaW50ZXJmYWNlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sRUFBRSxZQUFZLEVBQUUsTUFBTSwyQkFBMkIsQ0FBQztBQUN6RCxPQUFPLEtBQUssRUFBRSxZQUFZLEVBQUUsTUFBTSx1QkFBdUIsQ0FBQztBQUUxRCxPQUFPLEVBQUUsQ0FBQyxFQUFFLE1BQU0sS0FBSyxDQUFDO0FBRXhCLE9BQU8sRUFBRSxLQUFLLFNBQVMsRUFBbUIsTUFBTSxhQUFhLENBQUM7QUFFOUQsZUFBTyxNQUFNLGFBQWE7O2lCQUV4QixDQUFDO0FBRUgsTUFBTSxNQUFNLE9BQU8sR0FBRyxDQUFDLENBQUMsS0FBSyxDQUFDLE9BQU8sYUFBYSxDQUFDLENBQUM7QUFFcEQsTUFBTSxXQUFXLFlBQVk7SUFDM0IsS0FBSyxJQUFJLE9BQU8sQ0FBQyxJQUFJLENBQUMsQ0FBQztJQUN2QixJQUFJLElBQUksT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQ3RCLEdBQUcsSUFBSSxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUM7SUFDckIsS0FBSyxJQUFJLE9BQU8sQ0FBQyxJQUFJLENBQUMsQ0FBQztJQUN2QixTQUFTLElBQUksT0FBTyxDQUFDLFNBQVMsQ0FBQyxDQUFDO0lBQ2hDLE9BQU8sSUFBSSxPQUFPLENBQUMsT0FBTyxDQUFDLENBQUM7SUFDNUIsTUFBTSxDQUFDLE1BQU0sRUFBRSxTQUFTLEdBQUcsT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDO0NBQzFDO0FBRUQsZUFBTyxNQUFNLGtCQUFrQixFQUFFLFlBQVksQ0FBQyxZQUFZLENBUXpELENBQUMifQ==
@@ -1 +1 @@
1
- {"version":3,"file":"interface.d.ts","sourceRoot":"","sources":["../src/interface.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE1D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,KAAK,SAAS,EAAmB,MAAM,aAAa,CAAC;AAE9D,eAAO,MAAM,aAAa;;;;;;EAExB,CAAC;AAEH,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC;AAEpD,MAAM,WAAW,YAAY;IAC3B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACtB,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACrB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,SAAS,IAAI,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IAC5B,MAAM,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1C;AAED,eAAO,MAAM,kBAAkB,EAAE,YAAY,CAAC,YAAY,CAQzD,CAAC"}
1
+ {"version":3,"file":"interface.d.ts","sourceRoot":"","sources":["../src/interface.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE1D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,KAAK,SAAS,EAAmB,MAAM,aAAa,CAAC;AAE9D,eAAO,MAAM,aAAa;;iBAExB,CAAC;AAEH,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC;AAEpD,MAAM,WAAW,YAAY;IAC3B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACtB,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACrB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,SAAS,IAAI,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IAC5B,MAAM,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1C;AAED,eAAO,MAAM,kBAAkB,EAAE,YAAY,CAAC,YAAY,CAQzD,CAAC"}
package/dest/interface.js CHANGED
@@ -5,11 +5,34 @@ export const BotInfoSchema = z.object({
5
5
  botAddress: AztecAddress.schema
6
6
  });
7
7
  export const BotRunnerApiSchema = {
8
- start: z.function().args().returns(z.void()),
9
- stop: z.function().args().returns(z.void()),
10
- run: z.function().args().returns(z.void()),
11
- setup: z.function().args().returns(z.void()),
12
- getInfo: z.function().args().returns(BotInfoSchema),
13
- getConfig: z.function().args().returns(BotConfigSchema),
14
- update: z.function().args(BotConfigSchema).returns(z.void())
8
+ start: z.function({
9
+ input: z.tuple([]),
10
+ output: z.void()
11
+ }),
12
+ stop: z.function({
13
+ input: z.tuple([]),
14
+ output: z.void()
15
+ }),
16
+ run: z.function({
17
+ input: z.tuple([]),
18
+ output: z.void()
19
+ }),
20
+ setup: z.function({
21
+ input: z.tuple([]),
22
+ output: z.void()
23
+ }),
24
+ getInfo: z.function({
25
+ input: z.tuple([]),
26
+ output: BotInfoSchema
27
+ }),
28
+ getConfig: z.function({
29
+ input: z.tuple([]),
30
+ output: BotConfigSchema
31
+ }),
32
+ update: z.function({
33
+ input: z.tuple([
34
+ BotConfigSchema
35
+ ]),
36
+ output: z.void()
37
+ })
15
38
  };
package/dest/utils.js CHANGED
@@ -4,10 +4,10 @@
4
4
  * @param who - Address to get the balance for.
5
5
  * @returns - Private and public token balances as bigints.
6
6
  */ export async function getBalances(token, who, from) {
7
- const privateBalance = await token.methods.balance_of_private(who).simulate({
7
+ const { result: privateBalance } = await token.methods.balance_of_private(who).simulate({
8
8
  from: from ?? who
9
9
  });
10
- const publicBalance = await token.methods.balance_of_public(who).simulate({
10
+ const { result: publicBalance } = await token.methods.balance_of_public(who).simulate({
11
11
  from: from ?? who
12
12
  });
13
13
  return {
@@ -16,7 +16,7 @@
16
16
  };
17
17
  }
18
18
  export async function getPrivateBalance(token, who, from) {
19
- const privateBalance = await token.methods.get_balance(who).simulate({
19
+ const { result: privateBalance } = await token.methods.get_balance(who).simulate({
20
20
  from: from ?? who
21
21
  });
22
22
  return privateBalance;