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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dest/amm_bot.d.ts +7 -7
  2. package/dest/amm_bot.d.ts.map +1 -1
  3. package/dest/amm_bot.js +30 -19
  4. package/dest/base_bot.d.ts +8 -8
  5. package/dest/base_bot.d.ts.map +1 -1
  6. package/dest/base_bot.js +26 -37
  7. package/dest/bot.d.ts +7 -6
  8. package/dest/bot.d.ts.map +1 -1
  9. package/dest/bot.js +11 -11
  10. package/dest/config.d.ts +55 -91
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +48 -21
  13. package/dest/cross_chain_bot.d.ts +56 -0
  14. package/dest/cross_chain_bot.d.ts.map +1 -0
  15. package/dest/cross_chain_bot.js +138 -0
  16. package/dest/factory.d.ts +34 -14
  17. package/dest/factory.d.ts.map +1 -1
  18. package/dest/factory.js +335 -177
  19. package/dest/index.d.ts +2 -1
  20. package/dest/index.d.ts.map +1 -1
  21. package/dest/index.js +1 -0
  22. package/dest/interface.d.ts +2 -6
  23. package/dest/interface.d.ts.map +1 -1
  24. package/dest/interface.js +30 -7
  25. package/dest/l1_to_l2_seeding.d.ts +8 -0
  26. package/dest/l1_to_l2_seeding.d.ts.map +1 -0
  27. package/dest/l1_to_l2_seeding.js +63 -0
  28. package/dest/runner.d.ts +4 -3
  29. package/dest/runner.d.ts.map +1 -1
  30. package/dest/runner.js +432 -32
  31. package/dest/store/bot_store.d.ts +31 -6
  32. package/dest/store/bot_store.d.ts.map +1 -1
  33. package/dest/store/bot_store.js +38 -7
  34. package/dest/store/index.d.ts +2 -2
  35. package/dest/store/index.d.ts.map +1 -1
  36. package/dest/utils.js +3 -3
  37. package/package.json +18 -15
  38. package/src/amm_bot.ts +30 -22
  39. package/src/base_bot.ts +23 -44
  40. package/src/bot.ts +14 -12
  41. package/src/config.ts +96 -65
  42. package/src/cross_chain_bot.ts +208 -0
  43. package/src/factory.ts +354 -174
  44. package/src/index.ts +1 -0
  45. package/src/interface.ts +7 -7
  46. package/src/l1_to_l2_seeding.ts +79 -0
  47. package/src/runner.ts +41 -5
  48. package/src/store/bot_store.ts +61 -6
  49. package/src/store/index.ts +1 -1
  50. package/src/utils.ts +3 -3
package/dest/factory.js CHANGED
@@ -1,44 +1,59 @@
1
- import { SchnorrAccountContract } from '@aztec/accounts/schnorr';
2
1
  import { getInitialTestAccountsData } from '@aztec/accounts/testing';
3
- import { AztecAddress } from '@aztec/aztec.js/addresses';
4
- import { BatchCall } from '@aztec/aztec.js/contracts';
2
+ import { deriveSecretKeyFromSigningKey } from '@aztec/accounts/utils';
3
+ import { BatchCall, NO_WAIT } from '@aztec/aztec.js/contracts';
5
4
  import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
6
5
  import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
6
+ 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
- import { createEthereumChain, createExtendedL1Client } from '@aztec/ethereum';
10
- import { Fr } from '@aztec/foundation/fields';
11
- import { Timer } from '@aztec/foundation/timer';
9
+ import { waitForTx } from '@aztec/aztec.js/node';
10
+ import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
11
+ import { createEthereumChain } from '@aztec/ethereum/chain';
12
+ import { createExtendedL1Client } from '@aztec/ethereum/client';
13
+ import { RollupContract } from '@aztec/ethereum/contracts';
14
+ import { Fr } from '@aztec/foundation/curves/bn254';
15
+ import { GrumpkinScalar } from '@aztec/foundation/curves/grumpkin';
16
+ import { EthAddress } from '@aztec/foundation/eth-address';
12
17
  import { AMMContract } from '@aztec/noir-contracts.js/AMM';
13
18
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
14
19
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
15
- import { GasSettings } from '@aztec/stdlib/gas';
16
- import { deriveSigningKey } from '@aztec/stdlib/keys';
20
+ import { TestContract } from '@aztec/noir-test-contracts.js/Test';
17
21
  import { SupportedTokenContracts } from './config.js';
22
+ import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
18
23
  import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
19
24
  const MINT_BALANCE = 1e12;
20
25
  const MIN_BALANCE = 1e3;
26
+ const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
21
27
  export class BotFactory {
22
28
  config;
23
29
  wallet;
24
30
  store;
25
31
  aztecNode;
26
32
  aztecNodeAdmin;
33
+ syncChainTip;
27
34
  log;
28
- 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){
29
38
  this.config = config;
30
39
  this.wallet = wallet;
31
40
  this.store = store;
32
41
  this.aztecNode = aztecNode;
33
42
  this.aztecNodeAdmin = aztecNodeAdmin;
43
+ this.syncChainTip = syncChainTip;
34
44
  this.log = createLogger('bot');
45
+ this.noMinTxsPerBlockDepth = 0;
46
+ // Set fee padding on the wallet so that all transactions during setup
47
+ // (token deploy, minting, etc.) use the configured padding, not the default.
48
+ this.wallet.setMinFeePadding(config.minFeePadding);
35
49
  }
36
50
  /**
37
51
  * Initializes a new bot by setting up the sender account, registering the recipient,
38
52
  * deploying the token contract, and minting tokens if necessary.
39
53
  */ async setup() {
40
- const recipient = (await this.wallet.createAccount()).address;
41
54
  const defaultAccountAddress = await this.setupAccount();
55
+ const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random(), GrumpkinScalar.random())).address;
56
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
42
57
  const token = await this.setupToken(defaultAccountAddress);
43
58
  await this.mintTokens(token, defaultAccountAddress);
44
59
  return {
@@ -51,11 +66,31 @@ export class BotFactory {
51
66
  }
52
67
  async setupAmm() {
53
68
  const defaultAccountAddress = await this.setupAccount();
54
- const token0 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
55
- const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
56
- const liquidityToken = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotLPToken', 'BOTLP');
57
- const amm = await this.setupAmmContract(defaultAccountAddress, this.config.tokenSalt, token0, token1, liquidityToken);
58
- 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);
59
94
  this.log.info(`AMM initialized and funded`);
60
95
  return {
61
96
  wallet: this.wallet,
@@ -67,6 +102,77 @@ export class BotFactory {
67
102
  };
68
103
  }
69
104
  /**
105
+ * Initializes the cross-chain bot by deploying TestContract, creating an L1 client,
106
+ * seeding initial L1→L2 messages, and waiting for the first to be ready.
107
+ */ async setupCrossChain() {
108
+ const defaultAccountAddress = await this.setupAccount();
109
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
110
+ // Create L1 client (same pattern as bridgeL1FeeJuice)
111
+ const l1RpcUrls = this.config.l1RpcUrls;
112
+ if (!l1RpcUrls?.length) {
113
+ throw new Error('L1 RPC URLs required for cross-chain bot');
114
+ }
115
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
116
+ if (!mnemonicOrPrivateKey) {
117
+ throw new Error('L1 mnemonic or private key required for cross-chain bot');
118
+ }
119
+ const { l1ChainId, l1ContractAddresses } = await this.aztecNode.getNodeInfo();
120
+ const chain = createEthereumChain(l1RpcUrls, l1ChainId);
121
+ const l1Client = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
122
+ // Fetch Rollup version (needed for Inbox L2Actor struct)
123
+ const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
124
+ const rollupVersion = await rollupContract.getVersion();
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;
134
+ // Recover any pending messages from store (clean up stale ones first)
135
+ await this.store.cleanupOldPendingMessages();
136
+ const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
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.
139
+ const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
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
+ ]);
149
+ // Block until at least one message is ready
150
+ const allMessages = await this.store.getUnconsumedL1ToL2Messages();
151
+ if (allMessages.length > 0) {
152
+ this.log.info(`Waiting for first L1→L2 message to be ready...`);
153
+ const firstMsg = allMessages[0];
154
+ await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
155
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
156
+ chainTip: this.syncChainTip
157
+ });
158
+ this.log.info(`First L1→L2 message is ready`);
159
+ }
160
+ return {
161
+ wallet: this.wallet,
162
+ defaultAccountAddress,
163
+ contract,
164
+ node: this.aztecNode,
165
+ l1Client,
166
+ rollupVersion
167
+ };
168
+ }
169
+ async deployTestContract(deployer, deploy) {
170
+ const instance = await this.registerOrDeployContract('TestContract', deploy, {
171
+ from: deployer
172
+ });
173
+ return TestContract.at(instance.address, this.wallet);
174
+ }
175
+ /**
70
176
  * Checks if the sender account contract is initialized, and initializes it if necessary.
71
177
  * @returns The sender wallet.
72
178
  */ async setupAccount() {
@@ -79,148 +185,124 @@ export class BotFactory {
79
185
  return await this.setupTestAccount();
80
186
  }
81
187
  }
82
- async setupAccountWithPrivateKey(secret) {
83
- const salt = this.config.senderSalt ?? Fr.ONE;
84
- const signingKey = deriveSigningKey(secret);
85
- const accountData = {
86
- secret,
87
- salt,
88
- contract: new SchnorrAccountContract(signingKey)
89
- };
90
- const accountManager = await this.wallet.createAccount(accountData);
91
- const isInit = (await this.wallet.getContractMetadata(accountManager.address)).isContractInitialized;
92
- if (isInit) {
93
- this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
94
- const timer = new Timer();
95
- const address = accountManager.address;
96
- this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
97
- await this.store.deleteBridgeClaim(address);
98
- return address;
99
- } else {
100
- const address = accountManager.address;
101
- this.log.info(`Deploying account at ${address}`);
102
- const claim = await this.getOrCreateBridgeClaim(address);
103
- const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
104
- const deployMethod = await accountManager.getDeployMethod();
105
- const maxFeesPerGas = (await this.aztecNode.getCurrentBaseFees()).mul(1 + this.config.baseFeePadding);
106
- const gasSettings = GasSettings.default({
107
- maxFeesPerGas
108
- });
109
- const sentTx = deployMethod.send({
110
- from: AztecAddress.ZERO,
111
- fee: {
112
- gasSettings,
113
- paymentMethod
114
- }
115
- });
116
- const txHash = await sentTx.getTxHash();
117
- this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
118
- await this.withNoMinTxsPerBlock(()=>sentTx.wait({
119
- timeout: this.config.txMinedWaitSeconds
120
- }));
121
- this.log.info(`Account deployed at ${address}`);
122
- // Clean up the consumed bridge claim
123
- await this.store.deleteBridgeClaim(address);
124
- return accountManager.address;
125
- }
126
- }
127
- 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() {
128
195
  const [initialAccountData] = await getInitialTestAccountsData();
129
- const accountData = {
130
- secret: initialAccountData.secret,
131
- salt: initialAccountData.salt,
132
- contract: new SchnorrAccountContract(initialAccountData.signingKey)
133
- };
134
- const accountManager = await this.wallet.createAccount(accountData);
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);
135
204
  return accountManager.address;
136
205
  }
137
206
  /**
138
207
  * Checks if the token contract is deployed and deploys it if necessary.
139
- * @param wallet - Wallet to deploy the token contract from.
140
- * @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.
141
212
  */ async setupToken(sender) {
142
213
  let deploy;
214
+ const salt = this.config.tokenSalt;
143
215
  const deployOpts = {
144
- from: sender,
145
- contractAddressSalt: this.config.tokenSalt,
146
- universalDeploy: true
216
+ from: sender
147
217
  };
218
+ let token;
148
219
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
149
- deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
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);
150
226
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
151
- deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender);
227
+ // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
228
+ const tokenSecretKey = Fr.random();
229
+ const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
230
+ deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
231
+ salt,
232
+ universalDeploy: true,
233
+ publicKeys: tokenPublicKeys
234
+ });
152
235
  deployOpts.skipInstancePublication = true;
153
236
  deployOpts.skipClassPublication = true;
154
237
  deployOpts.skipInitialization = false;
238
+ // Register the contract with the secret key before deployment
239
+ const tokenInstance = await deploy.getInstance();
240
+ token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
241
+ await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
242
+ // The contract constructor initializes private storage vars that need the contract's own nullifier key.
243
+ deployOpts.additionalScopes = [
244
+ tokenInstance.address
245
+ ];
155
246
  } else {
156
247
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
157
248
  }
158
- const address = (await deploy.getInstance(deployOpts)).address;
159
- if ((await this.wallet.getContractMetadata(address)).isContractPublished) {
160
- this.log.info(`Token at ${address.toString()} already deployed`);
161
- return deploy.register();
162
- } else {
163
- this.log.info(`Deploying token contract at ${address.toString()}`);
164
- const sentTx = deploy.send(deployOpts);
165
- const txHash = await sentTx.getTxHash();
166
- this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
167
- return this.withNoMinTxsPerBlock(()=>sentTx.deployed({
168
- timeout: this.config.txMinedWaitSeconds
169
- }));
170
- }
249
+ await this.registerOrDeployContract('token', deploy, deployOpts);
250
+ return token;
171
251
  }
172
252
  /**
173
253
  * Checks if the token contract is deployed and deploys it if necessary.
174
254
  * @param wallet - Wallet to deploy the token contract from.
175
255
  * @returns The TokenContract instance.
176
- */ setupTokenContract(deployer, contractAddressSalt, name, ticker, decimals = 18) {
256
+ */ async setupTokenContract(deployer, salt, name, ticker, decimals = 18) {
177
257
  const deployOpts = {
178
- from: deployer,
179
- contractAddressSalt,
180
- universalDeploy: true
258
+ from: deployer
181
259
  };
182
- const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
183
- return this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
184
- }
185
- async setupAmmContract(deployer, contractAddressSalt, token0, token1, lpToken) {
186
- const deployOpts = {
187
- from: deployer,
188
- contractAddressSalt,
260
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, {
261
+ salt,
189
262
  universalDeploy: true
190
- };
191
- const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
192
- const amm = await this.registerOrDeployContract('AMM', deploy, deployOpts);
193
- this.log.info(`AMM deployed at ${amm.address}`);
194
- const minterTx = lpToken.methods.set_minter(amm.address, true).send({
195
- from: deployer
196
263
  });
197
- this.log.info(`Set LP token minter to AMM txHash=${(await minterTx.getTxHash()).toString()}`);
198
- await minterTx.wait({
199
- timeout: this.config.txMinedWaitSeconds
264
+ const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
265
+ return TokenContract.at(instance.address, this.wallet);
266
+ }
267
+ async deployAmmContract(deployer, deploy) {
268
+ const instance = await this.registerOrDeployContract('AMM', deploy, {
269
+ from: deployer
200
270
  });
201
- this.log.info(`Liquidity token initialized`);
271
+ const amm = AMMContract.at(instance.address, this.wallet);
272
+ this.log.info(`AMM deployed at ${amm.address}`);
202
273
  return amm;
203
274
  }
204
- async fundAmm(defaultAccountAddress, liquidityProvider, amm, token0, token1, lpToken) {
205
- const getPrivateBalances = ()=>Promise.all([
206
- token0.methods.balance_of_private(liquidityProvider).simulate({
207
- from: liquidityProvider
208
- }),
209
- token1.methods.balance_of_private(liquidityProvider).simulate({
210
- from: liquidityProvider
211
- }),
212
- lpToken.methods.balance_of_private(liquidityProvider).simulate({
213
- from: liquidityProvider
214
- })
215
- ]);
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({
278
+ from: deployer,
279
+ wait: {
280
+ timeout: this.config.txMinedWaitSeconds
281
+ }
282
+ });
283
+ this.log.info(`Set LP token minter to AMM txHash=${receipt.txHash.toString()}`);
284
+ }
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) {
216
300
  const authwitNonce = Fr.random();
217
301
  // keep some tokens for swapping
218
302
  const amount0Max = MINT_BALANCE / 2;
219
303
  const amount0Min = MINT_BALANCE / 4;
220
304
  const amount1Max = MINT_BALANCE / 2;
221
305
  const amount1Min = MINT_BALANCE / 4;
222
- const [t0Bal, t1Bal, lpBal] = await getPrivateBalances();
223
- this.log.info(`Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1. Current private balances of ${liquidityProvider}: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`);
224
306
  // Add authwitnesses for the transfers in AMM::add_liquidity function
225
307
  const token0Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
226
308
  caller: amm.address,
@@ -230,50 +312,101 @@ export class BotFactory {
230
312
  caller: amm.address,
231
313
  call: await token1.methods.transfer_to_public_and_prepare_private_balance_increase(liquidityProvider, amm.address, amount1Max, authwitNonce).getFunctionCall()
232
314
  });
233
- const mintTx = new BatchCall(this.wallet, [
234
- token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
235
- token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE)
236
- ]).send({
237
- from: liquidityProvider
238
- });
239
- this.log.info(`Sent mint tx: ${(await mintTx.getTxHash()).toString()}`);
240
- await mintTx.wait({
241
- timeout: this.config.txMinedWaitSeconds
242
- });
243
- const addLiquidityTx = amm.methods.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce).send({
315
+ const { receipt } = await amm.methods.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce).send({
244
316
  from: liquidityProvider,
245
317
  authWitnesses: [
246
318
  token0Authwit,
247
319
  token1Authwit
248
- ]
249
- });
250
- this.log.info(`Sent tx to add liquidity to the AMM: ${(await addLiquidityTx.getTxHash()).toString()}`);
251
- await addLiquidityTx.wait({
252
- timeout: this.config.txMinedWaitSeconds
320
+ ],
321
+ wait: {
322
+ timeout: this.config.txMinedWaitSeconds
323
+ }
253
324
  });
325
+ this.log.info(`Sent tx to add liquidity to the AMM: ${receipt.txHash.toString()}`);
254
326
  this.log.info(`Liquidity added`);
255
- const [newT0Bal, newT1Bal, newLPBal] = await getPrivateBalances();
256
- 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}`);
257
339
  }
258
340
  async registerOrDeployContract(name, deploy, deployOpts) {
259
- const address = (await deploy.getInstance(deployOpts)).address;
260
- if ((await this.wallet.getContractMetadata(address)).isContractPublished) {
341
+ const instance = await deploy.getInstance();
342
+ const address = instance.address;
343
+ const metadata = await this.wallet.getContractMetadata(address);
344
+ if (metadata.isContractPublished) {
261
345
  this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
262
- return deploy.register();
263
- } else {
264
- this.log.info(`Deploying contract ${name} at ${address.toString()}`);
265
- const sentTx = deploy.send(deployOpts);
266
- const txHash = await sentTx.getTxHash();
267
- this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
268
- return this.withNoMinTxsPerBlock(()=>sentTx.deployed({
269
- timeout: this.config.txMinedWaitSeconds
270
- }));
346
+ await deploy.register();
347
+ return instance;
271
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;
272
368
  }
273
369
  /**
274
- * Mints private and public tokens for the sender if their balance is below the minimum.
275
- * @param token - Token contract.
276
- */ async mintTokens(token, minter) {
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);
392
+ await this.withNoMinTxsPerBlock(async ()=>{
393
+ const executionPayload = await paymentMethod.getExecutionPayload();
394
+ const { txHash } = await this.wallet.sendTx(executionPayload, {
395
+ from: account,
396
+ wait: NO_WAIT
397
+ });
398
+ this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
399
+ return waitForTx(this.aztecNode, txHash, {
400
+ timeout: this.config.txMinedWaitSeconds
401
+ });
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}`);
406
+ }
407
+ this.log.info(`Fee juice top-up complete for ${account.toString()}`);
408
+ }
409
+ async mintTokens(token, minter) {
277
410
  const isStandardToken = isStandardTokenContract(token);
278
411
  let privateBalance = 0n;
279
412
  let publicBalance = 0n;
@@ -295,30 +428,36 @@ export class BotFactory {
295
428
  this.log.info(`Skipping minting as ${minter.toString()} has enough tokens`);
296
429
  return;
297
430
  }
298
- const sentTx = new BatchCall(token.wallet, calls).send({
299
- from: minter
300
- });
301
- const txHash = await sentTx.getTxHash();
302
- this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
303
- await this.withNoMinTxsPerBlock(()=>sentTx.wait({
431
+ // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
432
+ const additionalScopes = isStandardToken ? undefined : [
433
+ token.address
434
+ ];
435
+ const mintBatch = new BatchCall(token.wallet, calls);
436
+ await this.withNoMinTxsPerBlock(async ()=>{
437
+ const { txHash } = await mintBatch.send({
438
+ from: minter,
439
+ additionalScopes,
440
+ wait: NO_WAIT
441
+ });
442
+ this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
443
+ return waitForTx(this.aztecNode, txHash, {
304
444
  timeout: this.config.txMinedWaitSeconds
305
- }));
445
+ });
446
+ });
306
447
  }
307
448
  /**
308
- * Gets or creates a bridge claim for the recipient.
309
- * Checks if a claim already exists in the store and reuses it if valid.
310
- * 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.
311
452
  */ async getOrCreateBridgeClaim(recipient) {
312
- // Check if we have an existing claim in the store
313
453
  const existingClaim = await this.store.getBridgeClaim(recipient);
314
454
  if (existingClaim) {
315
455
  this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
316
- // Check if the message is ready on L2
317
456
  try {
318
457
  const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
319
458
  await this.withNoMinTxsPerBlock(()=>waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
320
459
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
321
- forPublicConsumption: false
460
+ chainTip: this.syncChainTip
322
461
  }));
323
462
  return existingClaim.claim;
324
463
  } catch (err) {
@@ -347,7 +486,7 @@ export class BotFactory {
347
486
  const claim = await portal.bridgeTokensPublic(recipient, mintAmount, true);
348
487
  await this.withNoMinTxsPerBlock(()=>waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
349
488
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
350
- forPublicConsumption: false
489
+ chainTip: this.syncChainTip
351
490
  }));
352
491
  this.log.info(`Created a claim for ${mintAmount} L1 fee juice to ${recipient}.`, claim);
353
492
  return claim;
@@ -357,18 +496,37 @@ export class BotFactory {
357
496
  this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
358
497
  return fn();
359
498
  }
360
- const { minTxsPerBlock } = await this.aztecNodeAdmin.getConfig();
361
- this.log.warn(`Setting sequencer minTxsPerBlock to 0 from ${minTxsPerBlock} to flush setup transactions`);
362
- await this.aztecNodeAdmin.setConfig({
363
- minTxsPerBlock: 0
364
- });
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
+ }
365
516
  try {
517
+ await this.savedMinTxsPerBlock;
366
518
  return await fn();
367
519
  } finally{
368
- this.log.warn(`Restoring sequencer minTxsPerBlock to ${minTxsPerBlock}`);
369
- await this.aztecNodeAdmin.setConfig({
370
- minTxsPerBlock
371
- });
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
+ }
372
530
  }
373
531
  }
374
532
  }