@aztec/bot 0.0.1-commit.a89ec08 → 0.0.1-commit.aa0c64f

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 { NO_FROM } from '@aztec/aztec.js/account';
2
+ import { deriveSecretKeyFromSigningKey } from '@aztec/accounts/utils';
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,37 +7,42 @@ 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 { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
10
+ import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
11
11
  import { createEthereumChain } from '@aztec/ethereum/chain';
12
12
  import { createExtendedL1Client } from '@aztec/ethereum/client';
13
13
  import { RollupContract } from '@aztec/ethereum/contracts';
14
14
  import { Fr } from '@aztec/foundation/curves/bn254';
15
+ import { GrumpkinScalar } from '@aztec/foundation/curves/grumpkin';
15
16
  import { EthAddress } from '@aztec/foundation/eth-address';
16
- import { Timer } from '@aztec/foundation/timer';
17
17
  import { AMMContract } from '@aztec/noir-contracts.js/AMM';
18
18
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
19
19
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
20
20
  import { TestContract } from '@aztec/noir-test-contracts.js/Test';
21
- import { deriveSigningKey } from '@aztec/stdlib/keys';
22
21
  import { SupportedTokenContracts } from './config.js';
23
22
  import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
24
23
  import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
25
24
  const MINT_BALANCE = 1e12;
26
25
  const MIN_BALANCE = 1e3;
26
+ const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
27
27
  export class BotFactory {
28
28
  config;
29
29
  wallet;
30
30
  store;
31
31
  aztecNode;
32
32
  aztecNodeAdmin;
33
+ syncChainTip;
33
34
  log;
34
- constructor(config, wallet, store, aztecNode, aztecNodeAdmin){
35
+ /** Number of in-flight withNoMinTxsPerBlock calls; see that method for why they are counted. */ noMinTxsPerBlockDepth;
36
+ /** Set by the first withNoMinTxsPerBlock entrant; resolves to the minTxsPerBlock value to restore. */ savedMinTxsPerBlock;
37
+ constructor(config, wallet, store, aztecNode, aztecNodeAdmin, syncChainTip){
35
38
  this.config = config;
36
39
  this.wallet = wallet;
37
40
  this.store = store;
38
41
  this.aztecNode = aztecNode;
39
42
  this.aztecNodeAdmin = aztecNodeAdmin;
43
+ this.syncChainTip = syncChainTip;
40
44
  this.log = createLogger('bot');
45
+ this.noMinTxsPerBlockDepth = 0;
41
46
  // Set fee padding on the wallet so that all transactions during setup
42
47
  // (token deploy, minting, etc.) use the configured padding, not the default.
43
48
  this.wallet.setMinFeePadding(config.minFeePadding);
@@ -47,7 +52,8 @@ export class BotFactory {
47
52
  * deploying the token contract, and minting tokens if necessary.
48
53
  */ async setup() {
49
54
  const defaultAccountAddress = await this.setupAccount();
50
- const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
55
+ const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random(), GrumpkinScalar.random())).address;
56
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
51
57
  const token = await this.setupToken(defaultAccountAddress);
52
58
  await this.mintTokens(token, defaultAccountAddress);
53
59
  return {
@@ -60,11 +66,31 @@ export class BotFactory {
60
66
  }
61
67
  async setupAmm() {
62
68
  const defaultAccountAddress = await this.setupAccount();
63
- const token0 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
64
- const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
65
- const liquidityToken = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotLPToken', 'BOTLP');
66
- const amm = await this.setupAmmContract(defaultAccountAddress, this.config.tokenSalt, token0, token1, liquidityToken);
67
- await this.fundAmm(defaultAccountAddress, defaultAccountAddress, amm, token0, token1, liquidityToken);
69
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
70
+ const salt = this.config.tokenSalt;
71
+ // token0, token1 and the LP token are independent contracts with no shared state, so deploy them
72
+ // concurrently rather than one slot at a time.
73
+ const [token0, token1, liquidityToken] = await Promise.all([
74
+ this.setupTokenContract(defaultAccountAddress, salt, 'BotToken0', 'BOT0'),
75
+ this.setupTokenContract(defaultAccountAddress, salt, 'BotToken1', 'BOT1'),
76
+ this.setupTokenContract(defaultAccountAddress, salt, 'BotLPToken', 'BOTLP')
77
+ ]);
78
+ const ammDeploy = AMMContract.deploy(this.wallet, token0.address, token1.address, liquidityToken.address, {
79
+ salt,
80
+ universalDeploy: true
81
+ });
82
+ const ammAddress = (await ammDeploy.getInstance()).address;
83
+ // The AMM constructor only stores the (already-derived) token addresses, and set_minter only records
84
+ // the AMM address on the LP token: neither reads the other's on-chain state, so the AMM deploy, the
85
+ // LP-minter grant, and the token0/token1 mints are mutually independent and run concurrently.
86
+ const [amm] = await Promise.all([
87
+ this.deployAmmContract(defaultAccountAddress, ammDeploy),
88
+ this.grantLpTokenMinter(defaultAccountAddress, liquidityToken, ammAddress),
89
+ this.mintAmmLiquidity(defaultAccountAddress, token0, token1)
90
+ ]);
91
+ // add_liquidity spends the minted token0/token1 balances and mints LP tokens, so it must follow both
92
+ // the mints and the minter grant, and target the deployed AMM.
93
+ await this.addAmmLiquidity(defaultAccountAddress, defaultAccountAddress, amm, token0, token1, liquidityToken);
68
94
  this.log.info(`AMM initialized and funded`);
69
95
  return {
70
96
  wallet: this.wallet,
@@ -80,6 +106,7 @@ export class BotFactory {
80
106
  * seeding initial L1→L2 messages, and waiting for the first to be ready.
81
107
  */ async setupCrossChain() {
82
108
  const defaultAccountAddress = await this.setupAccount();
109
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
83
110
  // Create L1 client (same pattern as bridgeL1FeeJuice)
84
111
  const l1RpcUrls = this.config.l1RpcUrls;
85
112
  if (!l1RpcUrls?.length) {
@@ -95,23 +122,38 @@ export class BotFactory {
95
122
  // Fetch Rollup version (needed for Inbox L2Actor struct)
96
123
  const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
97
124
  const rollupVersion = await rollupContract.getVersion();
98
- // Deploy TestContract
99
- const contract = await this.setupTestContract(defaultAccountAddress);
125
+ // Derive the TestContract address up front (deterministic from the salt). Seeding L1→L2 messages only
126
+ // needs the L2 recipient address — the messages are queued on L1 and don't require the L2 contract to
127
+ // exist yet (they're consumed later, after setup completes) — so the deploy (an L2 tx paying from the
128
+ // standing balance funded above) and the L1 seeding run concurrently.
129
+ const testContractDeploy = TestContract.deploy(this.wallet, {
130
+ salt: this.config.tokenSalt,
131
+ universalDeploy: true
132
+ });
133
+ const contractAddress = (await testContractDeploy.getInstance()).address;
100
134
  // Recover any pending messages from store (clean up stale ones first)
101
135
  await this.store.cleanupOldPendingMessages();
102
136
  const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
103
- // Seed initial L1→L2 messages if pipeline is empty
137
+ // Seed initial L1→L2 messages if pipeline is empty. The seeds are sent one at a time: they share the
138
+ // bot's L1 account, so concurrent sends would race on the L1 nonce.
104
139
  const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
105
- for(let i = 0; i < seedCount; i++){
106
- await seedL1ToL2Message(l1Client, EthAddress.fromString(l1ContractAddresses.inboxAddress.toString()), contract.address, rollupVersion, this.store, this.log);
107
- }
140
+ const inboxAddress = EthAddress.fromString(l1ContractAddresses.inboxAddress.toString());
141
+ const [contract] = await Promise.all([
142
+ this.deployTestContract(defaultAccountAddress, testContractDeploy),
143
+ (async ()=>{
144
+ for(let i = 0; i < seedCount; i++){
145
+ await seedL1ToL2Message(l1Client, inboxAddress, contractAddress, rollupVersion, this.store, this.log);
146
+ }
147
+ })()
148
+ ]);
108
149
  // Block until at least one message is ready
109
150
  const allMessages = await this.store.getUnconsumedL1ToL2Messages();
110
151
  if (allMessages.length > 0) {
111
152
  this.log.info(`Waiting for first L1→L2 message to be ready...`);
112
153
  const firstMsg = allMessages[0];
113
154
  await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
114
- timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds
155
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
156
+ chainTip: this.syncChainTip
115
157
  });
116
158
  this.log.info(`First L1→L2 message is ready`);
117
159
  }
@@ -124,14 +166,10 @@ export class BotFactory {
124
166
  rollupVersion
125
167
  };
126
168
  }
127
- async setupTestContract(deployer) {
128
- const deployOpts = {
129
- from: deployer,
130
- contractAddressSalt: this.config.tokenSalt,
131
- universalDeploy: true
132
- };
133
- const deploy = TestContract.deploy(this.wallet);
134
- const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
169
+ async deployTestContract(deployer, deploy) {
170
+ const instance = await this.registerOrDeployContract('TestContract', deploy, {
171
+ from: deployer
172
+ });
135
173
  return TestContract.at(instance.address, this.wallet);
136
174
  }
137
175
  /**
@@ -147,75 +185,58 @@ export class BotFactory {
147
185
  return await this.setupTestAccount();
148
186
  }
149
187
  }
150
- async setupAccountWithPrivateKey(secret) {
151
- const salt = this.config.senderSalt ?? Fr.ONE;
152
- const signingKey = deriveSigningKey(secret);
153
- const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
154
- const metadata = await this.wallet.getContractMetadata(accountManager.address);
155
- if (metadata.initializationStatus === ContractInitializationStatus.INITIALIZED) {
156
- this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
157
- const timer = new Timer();
158
- const address = accountManager.address;
159
- this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
160
- await this.store.deleteBridgeClaim(address);
161
- return address;
162
- } else {
163
- const address = accountManager.address;
164
- this.log.info(`Deploying account at ${address}`);
165
- const claim = await this.getOrCreateBridgeClaim(address);
166
- const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
167
- const deployMethod = await accountManager.getDeployMethod();
168
- await this.withNoMinTxsPerBlock(async ()=>{
169
- const { txHash } = await deployMethod.send({
170
- from: NO_FROM,
171
- fee: {
172
- paymentMethod
173
- },
174
- wait: NO_WAIT
175
- });
176
- this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
177
- return waitForTx(this.aztecNode, txHash, {
178
- timeout: this.config.txMinedWaitSeconds
179
- });
180
- });
181
- this.log.info(`Account deployed at ${address}`);
182
- // Clean up the consumed bridge claim
183
- await this.store.deleteBridgeClaim(address);
184
- return accountManager.address;
185
- }
186
- }
187
- async setupTestAccount() {
188
+ /**
189
+ * Keyless fallback for tests and local dev: reuses the first genesis test account, whose address is
190
+ * pre-funded with fee juice via `initialFundedAccounts`. The test accounts are initializerless, so this
191
+ * must create an initializerless account for the address to match the funded one. Production bots set a
192
+ * sender private key and fund the resulting initializerless account from L1 instead; see
193
+ * setupAccountWithPrivateKey.
194
+ */ async setupTestAccount() {
188
195
  const [initialAccountData] = await getInitialTestAccountsData();
189
- const accountManager = await this.wallet.createSchnorrAccount(initialAccountData.secret, initialAccountData.salt, initialAccountData.signingKey);
196
+ const accountManager = await this.wallet.createSchnorrInitializerlessAccount(initialAccountData.secret, initialAccountData.salt, initialAccountData.signingKey);
197
+ return accountManager.address;
198
+ }
199
+ async setupAccountWithPrivateKey(privateKey) {
200
+ const salt = this.config.senderSalt ?? Fr.ONE;
201
+ const signingKey = GrumpkinScalar.fromBuffer(privateKey.toBuffer());
202
+ const secret = await deriveSecretKeyFromSigningKey(signingKey);
203
+ const accountManager = await this.wallet.createSchnorrInitializerlessAccount(secret, salt, signingKey);
190
204
  return accountManager.address;
191
205
  }
192
206
  /**
193
207
  * Checks if the token contract is deployed and deploys it if necessary.
194
- * @param wallet - Wallet to deploy the token contract from.
195
- * @returns The TokenContract instance.
208
+ * Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
209
+ * @param sender - Aztec address to deploy the token contract from.
210
+ * @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
211
+ * @returns The TokenContract or PrivateTokenContract instance.
196
212
  */ async setupToken(sender) {
197
213
  let deploy;
198
- let tokenInstance;
214
+ const salt = this.config.tokenSalt;
199
215
  const deployOpts = {
200
- from: sender,
201
- contractAddressSalt: this.config.tokenSalt,
202
- universalDeploy: true
216
+ from: sender
203
217
  };
204
218
  let token;
205
219
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
206
- deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
207
- tokenInstance = await deploy.getInstance(deployOpts);
208
- token = TokenContract.at(tokenInstance.address, this.wallet);
220
+ deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, {
221
+ salt,
222
+ universalDeploy: true
223
+ });
224
+ const instance = await deploy.getInstance();
225
+ token = TokenContract.at(instance.address, this.wallet);
209
226
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
210
227
  // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
211
228
  const tokenSecretKey = Fr.random();
212
229
  const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
213
- deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
230
+ deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
231
+ salt,
232
+ universalDeploy: true,
233
+ publicKeys: tokenPublicKeys
234
+ });
214
235
  deployOpts.skipInstancePublication = true;
215
236
  deployOpts.skipClassPublication = true;
216
237
  deployOpts.skipInitialization = false;
217
238
  // Register the contract with the secret key before deployment
218
- tokenInstance = await deploy.getInstance(deployOpts);
239
+ const tokenInstance = await deploy.getInstance();
219
240
  token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
220
241
  await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
221
242
  // The contract constructor initializes private storage vars that need the contract's own nullifier key.
@@ -225,81 +246,63 @@ export class BotFactory {
225
246
  } else {
226
247
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
227
248
  }
228
- const address = tokenInstance?.address ?? (await deploy.getInstance(deployOpts)).address;
229
- const metadata = await this.wallet.getContractMetadata(address);
230
- if (metadata.isContractPublished) {
231
- this.log.info(`Token at ${address.toString()} already deployed`);
232
- await deploy.register();
233
- } else {
234
- this.log.info(`Deploying token contract at ${address.toString()}`);
235
- const { txHash } = await deploy.send({
236
- ...deployOpts,
237
- wait: NO_WAIT
238
- });
239
- this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
240
- await this.withNoMinTxsPerBlock(async ()=>{
241
- await waitForTx(this.aztecNode, txHash, {
242
- timeout: this.config.txMinedWaitSeconds
243
- });
244
- return token;
245
- });
246
- }
249
+ await this.registerOrDeployContract('token', deploy, deployOpts);
247
250
  return token;
248
251
  }
249
252
  /**
250
253
  * Checks if the token contract is deployed and deploys it if necessary.
251
254
  * @param wallet - Wallet to deploy the token contract from.
252
255
  * @returns The TokenContract instance.
253
- */ async setupTokenContract(deployer, contractAddressSalt, name, ticker, decimals = 18) {
256
+ */ async setupTokenContract(deployer, salt, name, ticker, decimals = 18) {
254
257
  const deployOpts = {
255
- from: deployer,
256
- contractAddressSalt,
257
- universalDeploy: true
258
+ from: deployer
258
259
  };
259
- const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
260
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, {
261
+ salt,
262
+ universalDeploy: true
263
+ });
260
264
  const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
261
265
  return TokenContract.at(instance.address, this.wallet);
262
266
  }
263
- async setupAmmContract(deployer, contractAddressSalt, token0, token1, lpToken) {
264
- const deployOpts = {
265
- from: deployer,
266
- contractAddressSalt,
267
- universalDeploy: true
268
- };
269
- const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
270
- const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
267
+ async deployAmmContract(deployer, deploy) {
268
+ const instance = await this.registerOrDeployContract('AMM', deploy, {
269
+ from: deployer
270
+ });
271
271
  const amm = AMMContract.at(instance.address, this.wallet);
272
272
  this.log.info(`AMM deployed at ${amm.address}`);
273
- const { receipt: minterReceipt } = await lpToken.methods.set_minter(amm.address, true).send({
273
+ return amm;
274
+ }
275
+ /** Grants the AMM minting rights over the LP token. set_minter only records the address, so it does not
276
+ * require the AMM contract to be deployed first. */ async grantLpTokenMinter(deployer, lpToken, amm) {
277
+ const { receipt } = await lpToken.methods.set_minter(amm, true).send({
274
278
  from: deployer,
275
279
  wait: {
276
280
  timeout: this.config.txMinedWaitSeconds
277
281
  }
278
282
  });
279
- this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
280
- this.log.info(`Liquidity token initialized`);
281
- return amm;
283
+ this.log.info(`Set LP token minter to AMM txHash=${receipt.txHash.toString()}`);
282
284
  }
283
- async fundAmm(defaultAccountAddress, liquidityProvider, amm, token0, token1, lpToken) {
284
- const getPrivateBalances = ()=>Promise.all([
285
- token0.methods.balance_of_private(liquidityProvider).simulate({
286
- from: liquidityProvider
287
- }).then((r)=>r.result),
288
- token1.methods.balance_of_private(liquidityProvider).simulate({
289
- from: liquidityProvider
290
- }).then((r)=>r.result),
291
- lpToken.methods.balance_of_private(liquidityProvider).simulate({
292
- from: liquidityProvider
293
- }).then((r)=>r.result)
294
- ]);
285
+ async mintAmmLiquidity(minter, token0, token1) {
286
+ this.log.info(`Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1 for ${minter}`);
287
+ const mintBatch = new BatchCall(this.wallet, [
288
+ token0.methods.mint_to_private(minter, MINT_BALANCE),
289
+ token1.methods.mint_to_private(minter, MINT_BALANCE)
290
+ ]);
291
+ const { receipt } = await mintBatch.send({
292
+ from: minter,
293
+ wait: {
294
+ timeout: this.config.txMinedWaitSeconds
295
+ }
296
+ });
297
+ this.log.info(`Sent mint tx: ${receipt.txHash.toString()}`);
298
+ }
299
+ async addAmmLiquidity(defaultAccountAddress, liquidityProvider, amm, token0, token1, lpToken) {
295
300
  const authwitNonce = Fr.random();
296
301
  // keep some tokens for swapping
297
302
  const amount0Max = MINT_BALANCE / 2;
298
303
  const amount0Min = MINT_BALANCE / 4;
299
304
  const amount1Max = MINT_BALANCE / 2;
300
305
  const amount1Min = MINT_BALANCE / 4;
301
- const [t0Bal, t1Bal, lpBal] = await getPrivateBalances();
302
- this.log.info(`Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1. Current private balances of ${liquidityProvider}: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`);
303
306
  // Add authwitnesses for the transfers in AMM::add_liquidity function
304
307
  const token0Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
305
308
  caller: amm.address,
@@ -309,17 +312,7 @@ export class BotFactory {
309
312
  caller: amm.address,
310
313
  call: await token1.methods.transfer_to_public_and_prepare_private_balance_increase(liquidityProvider, amm.address, amount1Max, authwitNonce).getFunctionCall()
311
314
  });
312
- const { receipt: mintReceipt } = await new BatchCall(this.wallet, [
313
- token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
314
- token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE)
315
- ]).send({
316
- from: liquidityProvider,
317
- wait: {
318
- timeout: this.config.txMinedWaitSeconds
319
- }
320
- });
321
- this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
322
- const { receipt: addLiquidityReceipt } = await amm.methods.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce).send({
315
+ const { receipt } = await amm.methods.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce).send({
323
316
  from: liquidityProvider,
324
317
  authWitnesses: [
325
318
  token0Authwit,
@@ -329,37 +322,91 @@ export class BotFactory {
329
322
  timeout: this.config.txMinedWaitSeconds
330
323
  }
331
324
  });
332
- this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`);
325
+ this.log.info(`Sent tx to add liquidity to the AMM: ${receipt.txHash.toString()}`);
333
326
  this.log.info(`Liquidity added`);
334
- const [newT0Bal, newT1Bal, newLPBal] = await getPrivateBalances();
335
- this.log.info(`Updated private balances of ${defaultAccountAddress} after minting and funding AMM: token0=${newT0Bal}, token1=${newT1Bal}, lp=${newLPBal}`);
327
+ const [t0Bal, t1Bal, lpBal] = await Promise.all([
328
+ token0.methods.balance_of_private(liquidityProvider).simulate({
329
+ from: liquidityProvider
330
+ }).then((r)=>r.result),
331
+ token1.methods.balance_of_private(liquidityProvider).simulate({
332
+ from: liquidityProvider
333
+ }).then((r)=>r.result),
334
+ lpToken.methods.balance_of_private(liquidityProvider).simulate({
335
+ from: liquidityProvider
336
+ }).then((r)=>r.result)
337
+ ]);
338
+ this.log.info(`Updated private balances of ${defaultAccountAddress} after minting and funding AMM: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`);
336
339
  }
337
340
  async registerOrDeployContract(name, deploy, deployOpts) {
338
- const instance = await deploy.getInstance(deployOpts);
341
+ const instance = await deploy.getInstance();
339
342
  const address = instance.address;
340
343
  const metadata = await this.wallet.getContractMetadata(address);
341
344
  if (metadata.isContractPublished) {
342
345
  this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
343
346
  await deploy.register();
344
- } else {
345
- this.log.info(`Deploying contract ${name} at ${address.toString()}`);
347
+ return instance;
348
+ }
349
+ // Setup always runs ensureFeeJuiceBalance before any deploy, so the account pays from its standing
350
+ // balance here. No manual gas estimation: the embedded wallet simulates before sending and derives
351
+ // the gas limits and padded maxFeesPerGas itself.
352
+ this.log.info(`Deploying contract ${name} at ${address.toString()}`);
353
+ await this.withNoMinTxsPerBlock(async ()=>{
354
+ const { txHash } = await deploy.send({
355
+ ...deployOpts,
356
+ wait: NO_WAIT
357
+ });
358
+ this.log.info(`Sent contract ${name} deploy tx ${txHash.toString()}`);
359
+ return waitForTx(this.aztecNode, txHash, {
360
+ timeout: this.config.txMinedWaitSeconds
361
+ });
362
+ });
363
+ return instance;
364
+ }
365
+ /** True when the config allows bridging fee juice from L1 (fee_juice mode, an L1 RPC, and an L1 key). */ isL1BridgingConfigured() {
366
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
367
+ return this.config.feePaymentMethod === 'fee_juice' && !!this.config.l1RpcUrls?.length && !!mnemonicOrPrivateKey;
368
+ }
369
+ /**
370
+ * Ensures the account holds enough fee juice before any other setup step. The account starts empty
371
+ * (initializerless accounts have no deployment tx) and the runtime loop pays fees from this balance and
372
+ * never refuels itself, so every flow funds the account up front. Bridges claims from L1 and consumes
373
+ * each with a claim-only tx until the balance clears the threshold, working from a zero (fresh run) or
374
+ * drained (restart) balance. Each bridge mints a fixed amount well above the threshold, so this is a
375
+ * single bridge in practice. No-op when L1 bridging is not configured or the balance is already above
376
+ * the threshold.
377
+ */ async ensureFeeJuiceBalance(account) {
378
+ if (!this.isL1BridgingConfigured()) {
379
+ return;
380
+ }
381
+ let balance = await getFeeJuiceBalance(account, this.aztecNode);
382
+ if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
383
+ this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
384
+ return;
385
+ }
386
+ this.log.info(`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1`);
387
+ while(balance < FEE_JUICE_TOP_UP_THRESHOLD){
388
+ // Persist the claim before consuming it: if the top-up tx fails or the bot crashes mid-loop, the
389
+ // next run reuses the pending claim instead of bridging again (and wasting the bridged funds).
390
+ const claim = await this.getOrCreateBridgeClaim(account);
391
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
346
392
  await this.withNoMinTxsPerBlock(async ()=>{
347
- const { txHash } = await deploy.send({
348
- ...deployOpts,
393
+ const executionPayload = await paymentMethod.getExecutionPayload();
394
+ const { txHash } = await this.wallet.sendTx(executionPayload, {
395
+ from: account,
349
396
  wait: NO_WAIT
350
397
  });
351
- this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
398
+ this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
352
399
  return waitForTx(this.aztecNode, txHash, {
353
400
  timeout: this.config.txMinedWaitSeconds
354
401
  });
355
402
  });
403
+ await this.store.deleteBridgeClaim(account);
404
+ balance = await getFeeJuiceBalance(account, this.aztecNode);
405
+ this.log.info(`Fee juice balance after top-up: ${balance}`);
356
406
  }
357
- return instance;
407
+ this.log.info(`Fee juice top-up complete for ${account.toString()}`);
358
408
  }
359
- /**
360
- * Mints private and public tokens for the sender if their balance is below the minimum.
361
- * @param token - Token contract.
362
- */ async mintTokens(token, minter) {
409
+ async mintTokens(token, minter) {
363
410
  const isStandardToken = isStandardTokenContract(token);
364
411
  let privateBalance = 0n;
365
412
  let publicBalance = 0n;
@@ -385,8 +432,9 @@ export class BotFactory {
385
432
  const additionalScopes = isStandardToken ? undefined : [
386
433
  token.address
387
434
  ];
435
+ const mintBatch = new BatchCall(token.wallet, calls);
388
436
  await this.withNoMinTxsPerBlock(async ()=>{
389
- const { txHash } = await new BatchCall(token.wallet, calls).send({
437
+ const { txHash } = await mintBatch.send({
390
438
  from: minter,
391
439
  additionalScopes,
392
440
  wait: NO_WAIT
@@ -398,19 +446,18 @@ export class BotFactory {
398
446
  });
399
447
  }
400
448
  /**
401
- * Gets or creates a bridge claim for the recipient.
402
- * Checks if a claim already exists in the store and reuses it if valid.
403
- * Only creates a new bridge if fee juice balance is below threshold.
449
+ * Returns a usable bridge claim for the recipient, reusing a persisted one when its L1→L2 message is
450
+ * still available (resuming a top-up that failed or crashed before the claim was consumed) and bridging
451
+ * a fresh claim otherwise. The caller deletes the claim from the store once it has been consumed.
404
452
  */ async getOrCreateBridgeClaim(recipient) {
405
- // Check if we have an existing claim in the store
406
453
  const existingClaim = await this.store.getBridgeClaim(recipient);
407
454
  if (existingClaim) {
408
455
  this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
409
- // Check if the message is ready on L2
410
456
  try {
411
457
  const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
412
458
  await this.withNoMinTxsPerBlock(()=>waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
413
- timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds
459
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
460
+ chainTip: this.syncChainTip
414
461
  }));
415
462
  return existingClaim.claim;
416
463
  } catch (err) {
@@ -438,7 +485,8 @@ export class BotFactory {
438
485
  const mintAmount = await portal.getTokenManager().getMintAmount();
439
486
  const claim = await portal.bridgeTokensPublic(recipient, mintAmount, true);
440
487
  await this.withNoMinTxsPerBlock(()=>waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
441
- timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds
488
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
489
+ chainTip: this.syncChainTip
442
490
  }));
443
491
  this.log.info(`Created a claim for ${mintAmount} L1 fee juice to ${recipient}.`, claim);
444
492
  return claim;
@@ -448,18 +496,37 @@ export class BotFactory {
448
496
  this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
449
497
  return fn();
450
498
  }
451
- const { minTxsPerBlock } = await this.aztecNodeAdmin.getConfig();
452
- this.log.warn(`Setting sequencer minTxsPerBlock to 0 from ${minTxsPerBlock} to flush setup transactions`);
453
- await this.aztecNodeAdmin.setConfig({
454
- minTxsPerBlock: 0
455
- });
499
+ const aztecNodeAdmin = this.aztecNodeAdmin;
500
+ // Setup steps run concurrently, so this wrapper can be re-entered while another call is in flight.
501
+ // Reference-count the entrants: the first saves the current value and zeroes it, the last restores it.
502
+ // A naive save/zero/restore per call could interleave, with a late entrant reading the already-zeroed
503
+ // value and "restoring" 0 at the end.
504
+ if (this.noMinTxsPerBlockDepth++ === 0) {
505
+ this.savedMinTxsPerBlock = (async ()=>{
506
+ const { minTxsPerBlock } = await aztecNodeAdmin.getConfig();
507
+ this.log.warn(`Setting sequencer minTxsPerBlock to 0 from ${minTxsPerBlock} to flush setup transactions`);
508
+ await aztecNodeAdmin.setConfig({
509
+ minTxsPerBlock: 0
510
+ });
511
+ return {
512
+ minTxsPerBlock
513
+ };
514
+ })();
515
+ }
456
516
  try {
517
+ await this.savedMinTxsPerBlock;
457
518
  return await fn();
458
519
  } finally{
459
- this.log.warn(`Restoring sequencer minTxsPerBlock to ${minTxsPerBlock}`);
460
- await this.aztecNodeAdmin.setConfig({
461
- minTxsPerBlock
462
- });
520
+ if (--this.noMinTxsPerBlockDepth === 0) {
521
+ // If saving/zeroing itself failed there is nothing to restore.
522
+ const saved = await this.savedMinTxsPerBlock.catch(()=>undefined);
523
+ if (saved) {
524
+ this.log.warn(`Restoring sequencer minTxsPerBlock to ${saved.minTxsPerBlock}`);
525
+ await aztecNodeAdmin.setConfig({
526
+ minTxsPerBlock: saved.minTxsPerBlock
527
+ });
528
+ }
529
+ }
463
530
  }
464
531
  }
465
532
  }
@@ -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"}