@aztec/bot 0.0.1-commit.b655e406 → 0.0.1-commit.b8a057fa

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 (52) 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 +63 -99
  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 +23 -27
  17. package/dest/factory.d.ts.map +1 -1
  18. package/dest/factory.js +252 -141
  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/rpc.d.ts +1 -1
  29. package/dest/runner.d.ts +4 -3
  30. package/dest/runner.d.ts.map +1 -1
  31. package/dest/runner.js +432 -32
  32. package/dest/store/bot_store.d.ts +30 -5
  33. package/dest/store/bot_store.d.ts.map +1 -1
  34. package/dest/store/bot_store.js +38 -7
  35. package/dest/store/index.d.ts +2 -2
  36. package/dest/store/index.d.ts.map +1 -1
  37. package/dest/utils.d.ts +1 -1
  38. package/dest/utils.js +3 -3
  39. package/package.json +20 -16
  40. package/src/amm_bot.ts +30 -22
  41. package/src/base_bot.ts +23 -44
  42. package/src/bot.ts +14 -12
  43. package/src/config.ts +96 -65
  44. package/src/cross_chain_bot.ts +208 -0
  45. package/src/factory.ts +302 -129
  46. package/src/index.ts +1 -0
  47. package/src/interface.ts +7 -7
  48. package/src/l1_to_l2_seeding.ts +79 -0
  49. package/src/runner.ts +41 -5
  50. package/src/store/bot_store.ts +61 -6
  51. package/src/store/index.ts +1 -1
  52. package/src/utils.ts +3 -3
package/dest/factory.js CHANGED
@@ -1,44 +1,55 @@
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 { BatchCall, NO_WAIT } from '@aztec/aztec.js/contracts';
5
3
  import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
6
4
  import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
5
+ import { deriveKeys } from '@aztec/aztec.js/keys';
7
6
  import { createLogger } from '@aztec/aztec.js/log';
8
7
  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';
8
+ import { waitForTx } from '@aztec/aztec.js/node';
9
+ import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
10
+ import { createEthereumChain } from '@aztec/ethereum/chain';
11
+ import { createExtendedL1Client } from '@aztec/ethereum/client';
12
+ import { RollupContract } from '@aztec/ethereum/contracts';
13
+ import { Fr } from '@aztec/foundation/curves/bn254';
14
+ import { EthAddress } from '@aztec/foundation/eth-address';
12
15
  import { AMMContract } from '@aztec/noir-contracts.js/AMM';
13
16
  import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
14
17
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
15
- import { GasSettings } from '@aztec/stdlib/gas';
18
+ import { TestContract } from '@aztec/noir-test-contracts.js/Test';
16
19
  import { deriveSigningKey } from '@aztec/stdlib/keys';
17
20
  import { SupportedTokenContracts } from './config.js';
21
+ import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
18
22
  import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
19
23
  const MINT_BALANCE = 1e12;
20
24
  const MIN_BALANCE = 1e3;
25
+ const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
21
26
  export class BotFactory {
22
27
  config;
23
28
  wallet;
24
29
  store;
25
30
  aztecNode;
26
31
  aztecNodeAdmin;
32
+ syncChainTip;
27
33
  log;
28
- constructor(config, wallet, store, aztecNode, aztecNodeAdmin){
34
+ constructor(config, wallet, store, aztecNode, aztecNodeAdmin, syncChainTip){
29
35
  this.config = config;
30
36
  this.wallet = wallet;
31
37
  this.store = store;
32
38
  this.aztecNode = aztecNode;
33
39
  this.aztecNodeAdmin = aztecNodeAdmin;
40
+ this.syncChainTip = syncChainTip;
34
41
  this.log = createLogger('bot');
42
+ // Set fee padding on the wallet so that all transactions during setup
43
+ // (token deploy, minting, etc.) use the configured padding, not the default.
44
+ this.wallet.setMinFeePadding(config.minFeePadding);
35
45
  }
36
46
  /**
37
47
  * Initializes a new bot by setting up the sender account, registering the recipient,
38
48
  * deploying the token contract, and minting tokens if necessary.
39
49
  */ async setup() {
40
- const recipient = (await this.wallet.createAccount()).address;
41
50
  const defaultAccountAddress = await this.setupAccount();
51
+ const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
52
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
42
53
  const token = await this.setupToken(defaultAccountAddress);
43
54
  await this.mintTokens(token, defaultAccountAddress);
44
55
  return {
@@ -51,6 +62,7 @@ export class BotFactory {
51
62
  }
52
63
  async setupAmm() {
53
64
  const defaultAccountAddress = await this.setupAccount();
65
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
54
66
  const token0 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
55
67
  const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
56
68
  const liquidityToken = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotLPToken', 'BOTLP');
@@ -67,6 +79,68 @@ export class BotFactory {
67
79
  };
68
80
  }
69
81
  /**
82
+ * Initializes the cross-chain bot by deploying TestContract, creating an L1 client,
83
+ * seeding initial L1→L2 messages, and waiting for the first to be ready.
84
+ */ async setupCrossChain() {
85
+ const defaultAccountAddress = await this.setupAccount();
86
+ await this.ensureFeeJuiceBalance(defaultAccountAddress);
87
+ // Create L1 client (same pattern as bridgeL1FeeJuice)
88
+ const l1RpcUrls = this.config.l1RpcUrls;
89
+ if (!l1RpcUrls?.length) {
90
+ throw new Error('L1 RPC URLs required for cross-chain bot');
91
+ }
92
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
93
+ if (!mnemonicOrPrivateKey) {
94
+ throw new Error('L1 mnemonic or private key required for cross-chain bot');
95
+ }
96
+ const { l1ChainId, l1ContractAddresses } = await this.aztecNode.getNodeInfo();
97
+ const chain = createEthereumChain(l1RpcUrls, l1ChainId);
98
+ const l1Client = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
99
+ // Fetch Rollup version (needed for Inbox L2Actor struct)
100
+ const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
101
+ const rollupVersion = await rollupContract.getVersion();
102
+ // Deploy TestContract (pays from the standing balance funded above).
103
+ const contract = await this.setupTestContract(defaultAccountAddress);
104
+ // Recover any pending messages from store (clean up stale ones first)
105
+ await this.store.cleanupOldPendingMessages();
106
+ const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
107
+ // Seed initial L1→L2 messages if pipeline is empty
108
+ const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
109
+ for(let i = 0; i < seedCount; i++){
110
+ await seedL1ToL2Message(l1Client, EthAddress.fromString(l1ContractAddresses.inboxAddress.toString()), contract.address, rollupVersion, this.store, this.log);
111
+ }
112
+ // Block until at least one message is ready
113
+ const allMessages = await this.store.getUnconsumedL1ToL2Messages();
114
+ if (allMessages.length > 0) {
115
+ this.log.info(`Waiting for first L1→L2 message to be ready...`);
116
+ const firstMsg = allMessages[0];
117
+ await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
118
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
119
+ chainTip: this.syncChainTip
120
+ });
121
+ this.log.info(`First L1→L2 message is ready`);
122
+ }
123
+ return {
124
+ wallet: this.wallet,
125
+ defaultAccountAddress,
126
+ contract,
127
+ node: this.aztecNode,
128
+ l1Client,
129
+ rollupVersion
130
+ };
131
+ }
132
+ async setupTestContract(deployer) {
133
+ const deployOpts = {
134
+ from: deployer
135
+ };
136
+ const deploy = TestContract.deploy(this.wallet, {
137
+ salt: this.config.tokenSalt,
138
+ universalDeploy: true
139
+ });
140
+ const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
141
+ return TestContract.at(instance.address, this.wallet);
142
+ }
143
+ /**
70
144
  * Checks if the sender account contract is initialized, and initializes it if necessary.
71
145
  * @returns The sender wallet.
72
146
  */ async setupAccount() {
@@ -79,125 +153,103 @@ export class BotFactory {
79
153
  return await this.setupTestAccount();
80
154
  }
81
155
  }
156
+ /**
157
+ * Keyless fallback for tests and local dev: reuses the first genesis test account, whose address is
158
+ * pre-funded with fee juice via `initialFundedAccounts`. The test accounts are initializerless, so this
159
+ * must create an initializerless account for the address to match the funded one. Production bots set a
160
+ * sender private key and fund the resulting initializerless account from L1 instead; see
161
+ * setupAccountWithPrivateKey.
162
+ */ async setupTestAccount() {
163
+ const [initialAccountData] = await getInitialTestAccountsData();
164
+ const accountManager = await this.wallet.createSchnorrInitializerlessAccount(initialAccountData.secret, initialAccountData.salt, initialAccountData.signingKey);
165
+ return accountManager.address;
166
+ }
82
167
  async setupAccountWithPrivateKey(secret) {
83
168
  const salt = this.config.senderSalt ?? Fr.ONE;
84
169
  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() {
128
- 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);
170
+ const accountManager = await this.wallet.createSchnorrInitializerlessAccount(secret, salt, signingKey);
135
171
  return accountManager.address;
136
172
  }
137
173
  /**
138
174
  * 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.
175
+ * Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
176
+ * @param sender - Aztec address to deploy the token contract from.
177
+ * @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
178
+ * @returns The TokenContract or PrivateTokenContract instance.
141
179
  */ async setupToken(sender) {
142
180
  let deploy;
181
+ const salt = this.config.tokenSalt;
143
182
  const deployOpts = {
144
- from: sender,
145
- contractAddressSalt: this.config.tokenSalt,
146
- universalDeploy: true
183
+ from: sender
147
184
  };
185
+ let token;
148
186
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
149
- deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
187
+ deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, {
188
+ salt,
189
+ universalDeploy: true
190
+ });
191
+ const instance = await deploy.getInstance();
192
+ token = TokenContract.at(instance.address, this.wallet);
150
193
  } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
151
- deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender);
194
+ // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
195
+ const tokenSecretKey = Fr.random();
196
+ const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
197
+ deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
198
+ salt,
199
+ universalDeploy: true,
200
+ publicKeys: tokenPublicKeys
201
+ });
152
202
  deployOpts.skipInstancePublication = true;
153
203
  deployOpts.skipClassPublication = true;
154
204
  deployOpts.skipInitialization = false;
205
+ // Register the contract with the secret key before deployment
206
+ const tokenInstance = await deploy.getInstance();
207
+ token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
208
+ await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
209
+ // The contract constructor initializes private storage vars that need the contract's own nullifier key.
210
+ deployOpts.additionalScopes = [
211
+ tokenInstance.address
212
+ ];
155
213
  } else {
156
214
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
157
215
  }
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
- }
216
+ await this.registerOrDeployContract('token', deploy, deployOpts);
217
+ return token;
171
218
  }
172
219
  /**
173
220
  * Checks if the token contract is deployed and deploys it if necessary.
174
221
  * @param wallet - Wallet to deploy the token contract from.
175
222
  * @returns The TokenContract instance.
176
- */ setupTokenContract(deployer, contractAddressSalt, name, ticker, decimals = 18) {
223
+ */ async setupTokenContract(deployer, salt, name, ticker, decimals = 18) {
177
224
  const deployOpts = {
178
- from: deployer,
179
- contractAddressSalt,
180
- universalDeploy: true
225
+ from: deployer
181
226
  };
182
- const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
183
- return this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
227
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, {
228
+ salt,
229
+ universalDeploy: true
230
+ });
231
+ const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
232
+ return TokenContract.at(instance.address, this.wallet);
184
233
  }
185
- async setupAmmContract(deployer, contractAddressSalt, token0, token1, lpToken) {
234
+ async setupAmmContract(deployer, salt, token0, token1, lpToken) {
186
235
  const deployOpts = {
187
- from: deployer,
188
- contractAddressSalt,
189
- 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
236
  from: deployer
237
+ };
238
+ const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address, {
239
+ salt,
240
+ universalDeploy: true
196
241
  });
197
- this.log.info(`Set LP token minter to AMM txHash=${(await minterTx.getTxHash()).toString()}`);
198
- await minterTx.wait({
199
- timeout: this.config.txMinedWaitSeconds
242
+ const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
243
+ const amm = AMMContract.at(instance.address, this.wallet);
244
+ this.log.info(`AMM deployed at ${amm.address}`);
245
+ const setMinterInteraction = lpToken.methods.set_minter(amm.address, true);
246
+ const { receipt: minterReceipt } = await setMinterInteraction.send({
247
+ from: deployer,
248
+ wait: {
249
+ timeout: this.config.txMinedWaitSeconds
250
+ }
200
251
  });
252
+ this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
201
253
  this.log.info(`Liquidity token initialized`);
202
254
  return amm;
203
255
  }
@@ -205,13 +257,13 @@ export class BotFactory {
205
257
  const getPrivateBalances = ()=>Promise.all([
206
258
  token0.methods.balance_of_private(liquidityProvider).simulate({
207
259
  from: liquidityProvider
208
- }),
260
+ }).then((r)=>r.result),
209
261
  token1.methods.balance_of_private(liquidityProvider).simulate({
210
262
  from: liquidityProvider
211
- }),
263
+ }).then((r)=>r.result),
212
264
  lpToken.methods.balance_of_private(liquidityProvider).simulate({
213
265
  from: liquidityProvider
214
- })
266
+ }).then((r)=>r.result)
215
267
  ]);
216
268
  const authwitNonce = Fr.random();
217
269
  // keep some tokens for swapping
@@ -230,50 +282,103 @@ export class BotFactory {
230
282
  caller: amm.address,
231
283
  call: await token1.methods.transfer_to_public_and_prepare_private_balance_increase(liquidityProvider, amm.address, amount1Max, authwitNonce).getFunctionCall()
232
284
  });
233
- const mintTx = new BatchCall(this.wallet, [
285
+ const mintBatch = new BatchCall(this.wallet, [
234
286
  token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
235
287
  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
288
+ ]);
289
+ const { receipt: mintReceipt } = await mintBatch.send({
290
+ from: liquidityProvider,
291
+ wait: {
292
+ timeout: this.config.txMinedWaitSeconds
293
+ }
242
294
  });
243
- const addLiquidityTx = amm.methods.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce).send({
295
+ this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
296
+ const addLiquidityInteraction = amm.methods.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce);
297
+ const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
244
298
  from: liquidityProvider,
245
299
  authWitnesses: [
246
300
  token0Authwit,
247
301
  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
302
+ ],
303
+ wait: {
304
+ timeout: this.config.txMinedWaitSeconds
305
+ }
253
306
  });
307
+ this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`);
254
308
  this.log.info(`Liquidity added`);
255
309
  const [newT0Bal, newT1Bal, newLPBal] = await getPrivateBalances();
256
310
  this.log.info(`Updated private balances of ${defaultAccountAddress} after minting and funding AMM: token0=${newT0Bal}, token1=${newT1Bal}, lp=${newLPBal}`);
257
311
  }
258
312
  async registerOrDeployContract(name, deploy, deployOpts) {
259
- const address = (await deploy.getInstance(deployOpts)).address;
260
- if ((await this.wallet.getContractMetadata(address)).isContractPublished) {
313
+ const instance = await deploy.getInstance();
314
+ const address = instance.address;
315
+ const metadata = await this.wallet.getContractMetadata(address);
316
+ if (metadata.isContractPublished) {
261
317
  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
- }));
318
+ await deploy.register();
319
+ return instance;
271
320
  }
321
+ // Setup always runs ensureFeeJuiceBalance before any deploy, so the account pays from its standing
322
+ // balance here. No manual gas estimation: the embedded wallet simulates before sending and derives
323
+ // the gas limits and padded maxFeesPerGas itself.
324
+ this.log.info(`Deploying contract ${name} at ${address.toString()}`);
325
+ await this.withNoMinTxsPerBlock(async ()=>{
326
+ const { txHash } = await deploy.send({
327
+ ...deployOpts,
328
+ wait: NO_WAIT
329
+ });
330
+ this.log.info(`Sent contract ${name} deploy tx ${txHash.toString()}`);
331
+ return waitForTx(this.aztecNode, txHash, {
332
+ timeout: this.config.txMinedWaitSeconds
333
+ });
334
+ });
335
+ return instance;
336
+ }
337
+ /** True when the config allows bridging fee juice from L1 (fee_juice mode, an L1 RPC, and an L1 key). */ isL1BridgingConfigured() {
338
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
339
+ return this.config.feePaymentMethod === 'fee_juice' && !!this.config.l1RpcUrls?.length && !!mnemonicOrPrivateKey;
272
340
  }
273
341
  /**
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) {
342
+ * Ensures the account holds enough fee juice before any other setup step. The account starts empty
343
+ * (initializerless accounts have no deployment tx) and the runtime loop pays fees from this balance and
344
+ * never refuels itself, so every flow funds the account up front. Bridges claims from L1 and consumes
345
+ * each with a claim-only tx until the balance clears the threshold, working from a zero (fresh run) or
346
+ * drained (restart) balance. Each bridge mints a fixed amount well above the threshold, so this is a
347
+ * single bridge in practice. No-op when L1 bridging is not configured or the balance is already above
348
+ * the threshold.
349
+ */ async ensureFeeJuiceBalance(account) {
350
+ if (!this.isL1BridgingConfigured()) {
351
+ return;
352
+ }
353
+ let balance = await getFeeJuiceBalance(account, this.aztecNode);
354
+ if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
355
+ this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
356
+ return;
357
+ }
358
+ this.log.info(`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1`);
359
+ while(balance < FEE_JUICE_TOP_UP_THRESHOLD){
360
+ // Persist the claim before consuming it: if the top-up tx fails or the bot crashes mid-loop, the
361
+ // next run reuses the pending claim instead of bridging again (and wasting the bridged funds).
362
+ const claim = await this.getOrCreateBridgeClaim(account);
363
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
364
+ await this.withNoMinTxsPerBlock(async ()=>{
365
+ const executionPayload = await paymentMethod.getExecutionPayload();
366
+ const { txHash } = await this.wallet.sendTx(executionPayload, {
367
+ from: account,
368
+ wait: NO_WAIT
369
+ });
370
+ this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
371
+ return waitForTx(this.aztecNode, txHash, {
372
+ timeout: this.config.txMinedWaitSeconds
373
+ });
374
+ });
375
+ await this.store.deleteBridgeClaim(account);
376
+ balance = await getFeeJuiceBalance(account, this.aztecNode);
377
+ this.log.info(`Fee juice balance after top-up: ${balance}`);
378
+ }
379
+ this.log.info(`Fee juice top-up complete for ${account.toString()}`);
380
+ }
381
+ async mintTokens(token, minter) {
277
382
  const isStandardToken = isStandardTokenContract(token);
278
383
  let privateBalance = 0n;
279
384
  let publicBalance = 0n;
@@ -295,30 +400,36 @@ export class BotFactory {
295
400
  this.log.info(`Skipping minting as ${minter.toString()} has enough tokens`);
296
401
  return;
297
402
  }
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({
403
+ // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
404
+ const additionalScopes = isStandardToken ? undefined : [
405
+ token.address
406
+ ];
407
+ const mintBatch = new BatchCall(token.wallet, calls);
408
+ await this.withNoMinTxsPerBlock(async ()=>{
409
+ const { txHash } = await mintBatch.send({
410
+ from: minter,
411
+ additionalScopes,
412
+ wait: NO_WAIT
413
+ });
414
+ this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
415
+ return waitForTx(this.aztecNode, txHash, {
304
416
  timeout: this.config.txMinedWaitSeconds
305
- }));
417
+ });
418
+ });
306
419
  }
307
420
  /**
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.
421
+ * Returns a usable bridge claim for the recipient, reusing a persisted one when its L1→L2 message is
422
+ * still available (resuming a top-up that failed or crashed before the claim was consumed) and bridging
423
+ * a fresh claim otherwise. The caller deletes the claim from the store once it has been consumed.
311
424
  */ async getOrCreateBridgeClaim(recipient) {
312
- // Check if we have an existing claim in the store
313
425
  const existingClaim = await this.store.getBridgeClaim(recipient);
314
426
  if (existingClaim) {
315
427
  this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
316
- // Check if the message is ready on L2
317
428
  try {
318
429
  const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
319
430
  await this.withNoMinTxsPerBlock(()=>waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
320
431
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
321
- forPublicConsumption: false
432
+ chainTip: this.syncChainTip
322
433
  }));
323
434
  return existingClaim.claim;
324
435
  } catch (err) {
@@ -347,7 +458,7 @@ export class BotFactory {
347
458
  const claim = await portal.bridgeTokensPublic(recipient, mintAmount, true);
348
459
  await this.withNoMinTxsPerBlock(()=>waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
349
460
  timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
350
- forPublicConsumption: false
461
+ chainTip: this.syncChainTip
351
462
  }));
352
463
  this.log.info(`Created a claim for ${mintAmount} L1 fee juice to ${recipient}.`, claim);
353
464
  return claim;
package/dest/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  export { Bot } from './bot.js';
2
2
  export { AmmBot } from './amm_bot.js';
3
+ export { CrossChainBot } from './cross_chain_bot.js';
3
4
  export { BotRunner } from './runner.js';
4
5
  export { BotStore } from './store/bot_store.js';
5
6
  export { type BotConfig, getBotConfigFromEnv, getBotDefaultConfig, botConfigMappings, SupportedTokenContracts, } from './config.js';
6
7
  export { getBotRunnerApiHandler } from './rpc.js';
7
8
  export * from './interface.js';
8
- //# sourceMappingURL=index.d.ts.map
9
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUUsR0FBRyxFQUFFLE1BQU0sVUFBVSxDQUFDO0FBQy9CLE9BQU8sRUFBRSxNQUFNLEVBQUUsTUFBTSxjQUFjLENBQUM7QUFDdEMsT0FBTyxFQUFFLGFBQWEsRUFBRSxNQUFNLHNCQUFzQixDQUFDO0FBQ3JELE9BQU8sRUFBRSxTQUFTLEVBQUUsTUFBTSxhQUFhLENBQUM7QUFDeEMsT0FBTyxFQUFFLFFBQVEsRUFBRSxNQUFNLHNCQUFzQixDQUFDO0FBQ2hELE9BQU8sRUFDTCxLQUFLLFNBQVMsRUFDZCxtQkFBbUIsRUFDbkIsbUJBQW1CLEVBQ25CLGlCQUFpQixFQUNqQix1QkFBdUIsR0FDeEIsTUFBTSxhQUFhLENBQUM7QUFDckIsT0FBTyxFQUFFLHNCQUFzQixFQUFFLE1BQU0sVUFBVSxDQUFDO0FBQ2xELGNBQWMsZ0JBQWdCLENBQUMifQ==
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EACL,KAAK,SAAS,EACd,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAClD,cAAc,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EACL,KAAK,SAAS,EACd,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAClD,cAAc,gBAAgB,CAAC"}
package/dest/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { Bot } from './bot.js';
2
2
  export { AmmBot } from './amm_bot.js';
3
+ export { CrossChainBot } from './cross_chain_bot.js';
3
4
  export { BotRunner } from './runner.js';
4
5
  export { BotStore } from './store/bot_store.js';
5
6
  export { getBotConfigFromEnv, getBotDefaultConfig, botConfigMappings, SupportedTokenContracts } from './config.js';
@@ -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=interface.d.ts.map
19
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW50ZXJmYWNlLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvaW50ZXJmYWNlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sRUFBRSxZQUFZLEVBQUUsTUFBTSwyQkFBMkIsQ0FBQztBQUN6RCxPQUFPLEtBQUssRUFBRSxZQUFZLEVBQUUsTUFBTSx1QkFBdUIsQ0FBQztBQUUxRCxPQUFPLEVBQUUsQ0FBQyxFQUFFLE1BQU0sS0FBSyxDQUFDO0FBRXhCLE9BQU8sRUFBRSxLQUFLLFNBQVMsRUFBbUIsTUFBTSxhQUFhLENBQUM7QUFFOUQsZUFBTyxNQUFNLGFBQWE7O2lC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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
  };
@@ -0,0 +1,8 @@
1
+ import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
2
+ import { EthAddress } from '@aztec/foundation/eth-address';
3
+ import type { Logger } from '@aztec/foundation/log';
4
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
5
+ import type { BotStore, PendingL1ToL2Message } from './store/index.js';
6
+ /** Sends an L1→L2 message via the Inbox contract and stores it. */
7
+ export declare function seedL1ToL2Message(l1Client: ExtendedViemWalletClient, inboxAddress: EthAddress, l2Recipient: AztecAddress, rollupVersion: bigint, store: BotStore, log: Logger): Promise<PendingL1ToL2Message>;
8
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibDFfdG9fbDJfc2VlZGluZy5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2wxX3RvX2wyX3NlZWRpbmcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsT0FBTyxLQUFLLEVBQUUsd0JBQXdCLEVBQUUsTUFBTSx1QkFBdUIsQ0FBQztBQUd0RSxPQUFPLEVBQUUsVUFBVSxFQUFFLE1BQU0sK0JBQStCLENBQUM7QUFDM0QsT0FBTyxLQUFLLEVBQUUsTUFBTSxFQUFFLE1BQU0sdUJBQXVCLENBQUM7QUFFcEQsT0FBTyxLQUFLLEVBQUUsWUFBWSxFQUFFLE1BQU0sNkJBQTZCLENBQUM7QUFJaEUsT0FBTyxLQUFLLEVBQUUsUUFBUSxFQUFFLG9CQUFvQixFQUFFLE1BQU0sa0JBQWtCLENBQUM7QUFFdkUscUVBQW1FO0FBQ25FLHdCQUFzQixpQkFBaUIsQ0FDckMsUUFBUSxFQUFFLHdCQUF3QixFQUNsQyxZQUFZLEVBQUUsVUFBVSxFQUN4QixXQUFXLEVBQUUsWUFBWSxFQUN6QixhQUFhLEVBQUUsTUFBTSxFQUNyQixLQUFLLEVBQUUsUUFBUSxFQUNmLEdBQUcsRUFBRSxNQUFNLEdBQ1YsT0FBTyxDQUFDLG9CQUFvQixDQUFDLENBeUQvQiJ9