@aztec/bot 0.0.0-test.1 → 0.0.1-commit.017a351

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 (57) hide show
  1. package/dest/amm_bot.d.ts +32 -0
  2. package/dest/amm_bot.d.ts.map +1 -0
  3. package/dest/amm_bot.js +108 -0
  4. package/dest/base_bot.d.ts +21 -0
  5. package/dest/base_bot.d.ts.map +1 -0
  6. package/dest/base_bot.js +69 -0
  7. package/dest/bot.d.ts +13 -18
  8. package/dest/bot.d.ts.map +1 -1
  9. package/dest/bot.js +23 -85
  10. package/dest/config.d.ts +88 -99
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +91 -41
  13. package/dest/cross_chain_bot.d.ts +54 -0
  14. package/dest/cross_chain_bot.d.ts.map +1 -0
  15. package/dest/cross_chain_bot.js +137 -0
  16. package/dest/factory.d.ts +48 -29
  17. package/dest/factory.d.ts.map +1 -1
  18. package/dest/factory.js +549 -144
  19. package/dest/index.d.ts +5 -2
  20. package/dest/index.d.ts.map +1 -1
  21. package/dest/index.js +4 -1
  22. package/dest/interface.d.ts +8 -1
  23. package/dest/interface.d.ts.map +1 -1
  24. package/dest/interface.js +34 -6
  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 -7
  29. package/dest/rpc.d.ts.map +1 -1
  30. package/dest/rpc.js +0 -11
  31. package/dest/runner.d.ts +15 -11
  32. package/dest/runner.d.ts.map +1 -1
  33. package/dest/runner.js +457 -51
  34. package/dest/store/bot_store.d.ts +69 -0
  35. package/dest/store/bot_store.d.ts.map +1 -0
  36. package/dest/store/bot_store.js +138 -0
  37. package/dest/store/index.d.ts +2 -0
  38. package/dest/store/index.d.ts.map +1 -0
  39. package/dest/store/index.js +1 -0
  40. package/dest/utils.d.ts +8 -5
  41. package/dest/utils.d.ts.map +1 -1
  42. package/dest/utils.js +14 -5
  43. package/package.json +31 -24
  44. package/src/amm_bot.ts +129 -0
  45. package/src/base_bot.ts +75 -0
  46. package/src/bot.ts +51 -103
  47. package/src/config.ts +133 -75
  48. package/src/cross_chain_bot.ts +204 -0
  49. package/src/factory.ts +644 -149
  50. package/src/index.ts +4 -1
  51. package/src/interface.ts +15 -6
  52. package/src/l1_to_l2_seeding.ts +79 -0
  53. package/src/rpc.ts +0 -13
  54. package/src/runner.ts +51 -21
  55. package/src/store/bot_store.ts +196 -0
  56. package/src/store/index.ts +1 -0
  57. package/src/utils.ts +17 -6
package/dest/factory.js CHANGED
@@ -1,229 +1,634 @@
1
- import { getSchnorrAccount } from '@aztec/accounts/schnorr';
2
- import { getDeployedTestAccountsWallets, getInitialTestAccounts } from '@aztec/accounts/testing';
3
- import { BatchCall, FeeJuicePaymentMethodWithClaim, L1FeeJuicePortalManager, createLogger, createPXEClient, retryUntil } from '@aztec/aztec.js';
4
- import { createEthereumChain, createL1Clients } from '@aztec/ethereum';
5
- import { Fr } from '@aztec/foundation/fields';
6
- import { EasyPrivateTokenContract } from '@aztec/noir-contracts.js/EasyPrivateToken';
1
+ import { getInitialTestAccountsData } from '@aztec/accounts/testing';
2
+ import { NO_FROM } from '@aztec/aztec.js/account';
3
+ import { BatchCall, NO_WAIT } from '@aztec/aztec.js/contracts';
4
+ import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
5
+ import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
6
+ import { deriveKeys } from '@aztec/aztec.js/keys';
7
+ import { createLogger } from '@aztec/aztec.js/log';
8
+ import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
9
+ import { waitForTx } from '@aztec/aztec.js/node';
10
+ import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
11
+ import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
12
+ import { createEthereumChain } from '@aztec/ethereum/chain';
13
+ import { createExtendedL1Client } from '@aztec/ethereum/client';
14
+ import { RollupContract } from '@aztec/ethereum/contracts';
15
+ import { Fr } from '@aztec/foundation/curves/bn254';
16
+ import { EthAddress } from '@aztec/foundation/eth-address';
17
+ import { Timer } from '@aztec/foundation/timer';
18
+ import { AMMContract } from '@aztec/noir-contracts.js/AMM';
19
+ import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
7
20
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
21
+ import { TestContract } from '@aztec/noir-test-contracts.js/Test';
22
+ import { GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
8
23
  import { deriveSigningKey } from '@aztec/stdlib/keys';
9
- import { makeTracedFetch } from '@aztec/telemetry-client';
10
- import { SupportedTokenContracts, getVersions } from './config.js';
24
+ import { SupportedTokenContracts } from './config.js';
25
+ import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
11
26
  import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
12
27
  const MINT_BALANCE = 1e12;
13
28
  const MIN_BALANCE = 1e3;
29
+ const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
30
+ const FEE_JUICE_TOP_UP_TARGET = 10_000n * 10n ** 18n;
14
31
  export class BotFactory {
15
32
  config;
16
- pxe;
17
- node;
33
+ wallet;
34
+ store;
35
+ aztecNode;
36
+ aztecNodeAdmin;
18
37
  log;
19
- constructor(config, dependencies = {}){
38
+ constructor(config, wallet, store, aztecNode, aztecNodeAdmin){
20
39
  this.config = config;
40
+ this.wallet = wallet;
41
+ this.store = store;
42
+ this.aztecNode = aztecNode;
43
+ this.aztecNodeAdmin = aztecNodeAdmin;
21
44
  this.log = createLogger('bot');
22
- if (config.flushSetupTransactions && !dependencies.node) {
23
- throw new Error(`Either a node client or node url must be provided if transaction flushing is requested`);
24
- }
25
- if (config.senderPrivateKey && !dependencies.node) {
26
- throw new Error(`Either a node client or node url must be provided for bridging L1 fee juice to deploy an account with private key`);
27
- }
28
- if (!dependencies.pxe && !config.pxeUrl) {
29
- throw new Error(`Either a PXE client or a PXE URL must be provided`);
30
- }
31
- this.node = dependencies.node;
32
- if (dependencies.pxe) {
33
- this.log.info(`Using local PXE`);
34
- this.pxe = dependencies.pxe;
35
- return;
36
- }
37
- this.log.info(`Using remote PXE at ${config.pxeUrl}`);
38
- this.pxe = createPXEClient(config.pxeUrl, getVersions(), makeTracedFetch([
39
- 1,
40
- 2,
41
- 3
42
- ], false));
45
+ // Set fee padding on the wallet so that all transactions during setup
46
+ // (token deploy, minting, etc.) use the configured padding, not the default.
47
+ this.wallet.setMinFeePadding(config.minFeePadding);
43
48
  }
44
49
  /**
45
50
  * Initializes a new bot by setting up the sender account, registering the recipient,
46
51
  * deploying the token contract, and minting tokens if necessary.
47
52
  */ async setup() {
48
- const recipient = await this.registerRecipient();
49
- const wallet = await this.setupAccount();
50
- const token = await this.setupToken(wallet);
51
- await this.mintTokens(token);
53
+ const defaultAccountAddress = await this.setupAccount();
54
+ const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
55
+ const token = await this.setupTokenWithOptionalEarlyRefuel(defaultAccountAddress);
56
+ await this.ensureFeeJuiceBalance(defaultAccountAddress, token);
57
+ await this.mintTokens(token, defaultAccountAddress);
52
58
  return {
53
- wallet,
59
+ wallet: this.wallet,
60
+ defaultAccountAddress,
54
61
  token,
55
- pxe: this.pxe,
62
+ node: this.aztecNode,
56
63
  recipient
57
64
  };
58
65
  }
66
+ async setupAmm() {
67
+ const defaultAccountAddress = await this.setupAccount();
68
+ const token0 = await this.setupTokenContractWithOptionalEarlyRefuel(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
69
+ await this.ensureFeeJuiceBalance(defaultAccountAddress, token0);
70
+ const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
71
+ const liquidityToken = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotLPToken', 'BOTLP');
72
+ const amm = await this.setupAmmContract(defaultAccountAddress, this.config.tokenSalt, token0, token1, liquidityToken);
73
+ await this.fundAmm(defaultAccountAddress, defaultAccountAddress, amm, token0, token1, liquidityToken);
74
+ this.log.info(`AMM initialized and funded`);
75
+ return {
76
+ wallet: this.wallet,
77
+ defaultAccountAddress,
78
+ amm,
79
+ token0,
80
+ token1,
81
+ node: this.aztecNode
82
+ };
83
+ }
84
+ /**
85
+ * Initializes the cross-chain bot by deploying TestContract, creating an L1 client,
86
+ * seeding initial L1→L2 messages, and waiting for the first to be ready.
87
+ */ async setupCrossChain() {
88
+ const defaultAccountAddress = await this.setupAccount();
89
+ // Create L1 client (same pattern as bridgeL1FeeJuice)
90
+ const l1RpcUrls = this.config.l1RpcUrls;
91
+ if (!l1RpcUrls?.length) {
92
+ throw new Error('L1 RPC URLs required for cross-chain bot');
93
+ }
94
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
95
+ if (!mnemonicOrPrivateKey) {
96
+ throw new Error('L1 mnemonic or private key required for cross-chain bot');
97
+ }
98
+ const { l1ChainId, l1ContractAddresses } = await this.aztecNode.getNodeInfo();
99
+ const chain = createEthereumChain(l1RpcUrls, l1ChainId);
100
+ const l1Client = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
101
+ // Fetch Rollup version (needed for Inbox L2Actor struct)
102
+ const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
103
+ const rollupVersion = await rollupContract.getVersion();
104
+ // Deploy TestContract
105
+ const contract = await this.setupTestContract(defaultAccountAddress);
106
+ // Recover any pending messages from store (clean up stale ones first)
107
+ await this.store.cleanupOldPendingMessages();
108
+ const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
109
+ // Seed initial L1→L2 messages if pipeline is empty
110
+ const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
111
+ for(let i = 0; i < seedCount; i++){
112
+ await seedL1ToL2Message(l1Client, EthAddress.fromString(l1ContractAddresses.inboxAddress.toString()), contract.address, rollupVersion, this.store, this.log);
113
+ }
114
+ // Block until at least one message is ready
115
+ const allMessages = await this.store.getUnconsumedL1ToL2Messages();
116
+ if (allMessages.length > 0) {
117
+ this.log.info(`Waiting for first L1→L2 message to be ready...`);
118
+ const firstMsg = allMessages[0];
119
+ await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
120
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds
121
+ });
122
+ this.log.info(`First L1→L2 message is ready`);
123
+ }
124
+ return {
125
+ wallet: this.wallet,
126
+ defaultAccountAddress,
127
+ contract,
128
+ node: this.aztecNode,
129
+ l1Client,
130
+ rollupVersion
131
+ };
132
+ }
133
+ async setupTestContract(deployer) {
134
+ const deployOpts = {
135
+ from: deployer
136
+ };
137
+ const deploy = TestContract.deploy(this.wallet, {
138
+ salt: this.config.tokenSalt,
139
+ universalDeploy: true
140
+ });
141
+ const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
142
+ return TestContract.at(instance.address, this.wallet);
143
+ }
59
144
  /**
60
145
  * Checks if the sender account contract is initialized, and initializes it if necessary.
61
146
  * @returns The sender wallet.
62
147
  */ async setupAccount() {
63
- if (this.config.senderPrivateKey) {
64
- return await this.setupAccountWithPrivateKey(this.config.senderPrivateKey);
148
+ const privateKey = this.config.senderPrivateKey?.getValue();
149
+ if (privateKey) {
150
+ this.log.info(`Setting up account with provided private key`);
151
+ return await this.setupAccountWithPrivateKey(privateKey);
65
152
  } else {
153
+ this.log.info(`Setting up test account`);
66
154
  return await this.setupTestAccount();
67
155
  }
68
156
  }
69
- async setupAccountWithPrivateKey(privateKey) {
70
- const salt = Fr.ONE;
71
- const signingKey = deriveSigningKey(privateKey);
72
- const account = await getSchnorrAccount(this.pxe, privateKey, signingKey, salt);
73
- const isInit = (await this.pxe.getContractMetadata(account.getAddress())).isContractInitialized;
74
- if (isInit) {
75
- this.log.info(`Account at ${account.getAddress().toString()} already initialized`);
76
- const wallet = await account.register();
77
- return wallet;
157
+ async setupAccountWithPrivateKey(secret) {
158
+ const salt = this.config.senderSalt ?? Fr.ONE;
159
+ const signingKey = deriveSigningKey(secret);
160
+ const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
161
+ const metadata = await this.wallet.getContractMetadata(accountManager.address);
162
+ if (metadata.initializationStatus === ContractInitializationStatus.INITIALIZED) {
163
+ this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
164
+ const timer = new Timer();
165
+ const address = accountManager.address;
166
+ this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
167
+ await this.store.deleteBridgeClaim(address);
168
+ return address;
78
169
  } else {
79
- const address = account.getAddress();
170
+ const address = accountManager.address;
80
171
  this.log.info(`Deploying account at ${address}`);
81
- const claim = await this.bridgeL1FeeJuice(address, 10n ** 22n);
82
- const wallet = await account.getWallet();
83
- const paymentMethod = new FeeJuicePaymentMethodWithClaim(wallet, claim);
84
- const sentTx = account.deploy({
85
- fee: {
86
- paymentMethod
87
- }
88
- });
89
- const txHash = await sentTx.getTxHash();
90
- this.log.info(`Sent tx with hash ${txHash.toString()}`);
91
- await this.tryFlushTxs();
92
- this.log.verbose('Waiting for account deployment to settle');
93
- await sentTx.wait({
94
- timeout: this.config.txMinedWaitSeconds
172
+ const claim = await this.getOrCreateBridgeClaim(address);
173
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
174
+ const deployMethod = await accountManager.getDeployMethod();
175
+ await this.withNoMinTxsPerBlock(async ()=>{
176
+ const { txHash } = await deployMethod.send({
177
+ from: NO_FROM,
178
+ fee: {
179
+ paymentMethod
180
+ },
181
+ wait: NO_WAIT
182
+ });
183
+ this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
184
+ return waitForTx(this.aztecNode, txHash, {
185
+ timeout: this.config.txMinedWaitSeconds
186
+ });
95
187
  });
96
188
  this.log.info(`Account deployed at ${address}`);
97
- return wallet;
189
+ // Clean up the consumed bridge claim
190
+ await this.store.deleteBridgeClaim(address);
191
+ return accountManager.address;
98
192
  }
99
193
  }
100
194
  async setupTestAccount() {
101
- let [wallet] = await getDeployedTestAccountsWallets(this.pxe);
102
- if (wallet) {
103
- this.log.info(`Using funded test account: ${wallet.getAddress()}`);
104
- } else {
105
- this.log.info('Registering funded test account');
106
- const [account] = await getInitialTestAccounts();
107
- const manager = await getSchnorrAccount(this.pxe, account.secret, account.signingKey, account.salt);
108
- wallet = await manager.register();
109
- this.log.info(`Funded test account registered: ${wallet.getAddress()}`);
195
+ const [initialAccountData] = await getInitialTestAccountsData();
196
+ const accountManager = await this.wallet.createSchnorrAccount(initialAccountData.secret, initialAccountData.salt, initialAccountData.signingKey);
197
+ return accountManager.address;
198
+ }
199
+ /**
200
+ * Setup token and refuel first: if the token already exists (restart scenario),
201
+ * run ensureFeeJuiceBalance before any step that might need fee juice. When deploying,
202
+ * use a bridge claim if balance is below threshold.
203
+ */ async setupTokenWithOptionalEarlyRefuel(sender) {
204
+ const token = await this.getTokenInstance(sender);
205
+ const address = token.address;
206
+ const metadata = await this.wallet.getContractMetadata(address);
207
+ if (metadata.isContractPublished) {
208
+ this.log.info(`Token at ${address.toString()} already deployed, refueling before setup`);
209
+ await this.ensureFeeJuiceBalance(sender, token);
110
210
  }
111
- return wallet;
211
+ return this.setupToken(sender);
112
212
  }
113
213
  /**
114
- * Registers the recipient for txs in the pxe.
115
- */ async registerRecipient() {
116
- const recipient = await this.pxe.registerAccount(this.config.recipientEncryptionSecret, Fr.ONE);
117
- return recipient.address;
214
+ * Setup token0 for AMM with refuel-first behaviour when token already exists.
215
+ */ async setupTokenContractWithOptionalEarlyRefuel(deployer, salt, name, ticker, decimals = 18) {
216
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, {
217
+ salt,
218
+ universalDeploy: true
219
+ });
220
+ const instance = await deploy.getInstance();
221
+ const metadata = await this.wallet.getContractMetadata(instance.address);
222
+ if (metadata.isContractPublished) {
223
+ this.log.info(`Token ${name} at ${instance.address.toString()} already deployed, refueling before setup`);
224
+ const token = TokenContract.at(instance.address, this.wallet);
225
+ await this.ensureFeeJuiceBalance(deployer, token);
226
+ }
227
+ return this.setupTokenContract(deployer, salt, name, ticker, decimals);
228
+ }
229
+ async getTokenInstance(sender) {
230
+ const salt = this.config.tokenSalt;
231
+ if (this.config.contract === SupportedTokenContracts.TokenContract) {
232
+ const deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, {
233
+ salt,
234
+ universalDeploy: true
235
+ });
236
+ const instance = await deploy.getInstance();
237
+ return TokenContract.at(instance.address, this.wallet);
238
+ }
239
+ if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
240
+ const tokenSecretKey = Fr.random();
241
+ const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
242
+ const deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
243
+ salt,
244
+ universalDeploy: true,
245
+ publicKeys: tokenPublicKeys
246
+ });
247
+ const instance = await deploy.getInstance();
248
+ return PrivateTokenContract.at(instance.address, this.wallet);
249
+ }
250
+ throw new Error(`Unsupported token contract type: ${this.config.contract}`);
118
251
  }
119
252
  /**
120
253
  * Checks if the token contract is deployed and deploys it if necessary.
121
- * @param wallet - Wallet to deploy the token contract from.
122
- * @returns The TokenContract instance.
123
- */ async setupToken(wallet) {
254
+ * Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
255
+ * @param sender - Aztec address to deploy the token contract from.
256
+ * @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
257
+ * @returns The TokenContract or PrivateTokenContract instance.
258
+ */ async setupToken(sender) {
124
259
  let deploy;
260
+ const salt = this.config.tokenSalt;
125
261
  const deployOpts = {
126
- contractAddressSalt: this.config.tokenSalt,
127
- universalDeploy: true
262
+ from: sender
128
263
  };
264
+ let token;
129
265
  if (this.config.contract === SupportedTokenContracts.TokenContract) {
130
- deploy = TokenContract.deploy(wallet, wallet.getAddress(), 'BotToken', 'BOT', 18);
131
- } else if (this.config.contract === SupportedTokenContracts.EasyPrivateTokenContract) {
132
- deploy = EasyPrivateTokenContract.deploy(wallet, MINT_BALANCE, wallet.getAddress());
133
- deployOpts.skipPublicDeployment = true;
134
- deployOpts.skipClassRegistration = true;
266
+ deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, {
267
+ salt,
268
+ universalDeploy: true
269
+ });
270
+ const instance = await deploy.getInstance();
271
+ token = TokenContract.at(instance.address, this.wallet);
272
+ } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
273
+ // Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
274
+ const tokenSecretKey = Fr.random();
275
+ const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
276
+ deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
277
+ salt,
278
+ universalDeploy: true,
279
+ publicKeys: tokenPublicKeys
280
+ });
281
+ deployOpts.skipInstancePublication = true;
282
+ deployOpts.skipClassPublication = true;
135
283
  deployOpts.skipInitialization = false;
136
- deployOpts.skipPublicSimulation = true;
284
+ // Register the contract with the secret key before deployment
285
+ const tokenInstance = await deploy.getInstance();
286
+ token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
287
+ await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
288
+ // The contract constructor initializes private storage vars that need the contract's own nullifier key.
289
+ deployOpts.additionalScopes = [
290
+ tokenInstance.address
291
+ ];
137
292
  } else {
138
293
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
139
294
  }
140
- const address = (await deploy.getInstance(deployOpts)).address;
141
- if ((await this.pxe.getContractMetadata(address)).isContractPubliclyDeployed) {
142
- this.log.info(`Token at ${address.toString()} already deployed`);
143
- return deploy.register();
144
- } else {
145
- this.log.info(`Deploying token contract at ${address.toString()}`);
146
- const sentTx = deploy.send(deployOpts);
147
- const txHash = await sentTx.getTxHash();
148
- this.log.info(`Sent tx with hash ${txHash.toString()}`);
149
- await this.tryFlushTxs();
150
- this.log.verbose('Waiting for token setup to settle');
151
- return sentTx.deployed({
295
+ await this.registerOrDeployContract('token', deploy, deployOpts);
296
+ return token;
297
+ }
298
+ /**
299
+ * Checks if the token contract is deployed and deploys it if necessary.
300
+ * @param wallet - Wallet to deploy the token contract from.
301
+ * @returns The TokenContract instance.
302
+ */ async setupTokenContract(deployer, salt, name, ticker, decimals = 18) {
303
+ const deployOpts = {
304
+ from: deployer
305
+ };
306
+ const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, {
307
+ salt,
308
+ universalDeploy: true
309
+ });
310
+ const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
311
+ return TokenContract.at(instance.address, this.wallet);
312
+ }
313
+ async setupAmmContract(deployer, salt, token0, token1, lpToken) {
314
+ const deployOpts = {
315
+ from: deployer
316
+ };
317
+ const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address, {
318
+ salt,
319
+ universalDeploy: true
320
+ });
321
+ const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
322
+ const amm = AMMContract.at(instance.address, this.wallet);
323
+ this.log.info(`AMM deployed at ${amm.address}`);
324
+ const setMinterInteraction = lpToken.methods.set_minter(amm.address, true);
325
+ const { receipt: minterReceipt } = await setMinterInteraction.send({
326
+ from: deployer,
327
+ wait: {
152
328
  timeout: this.config.txMinedWaitSeconds
153
- });
329
+ }
330
+ });
331
+ this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
332
+ this.log.info(`Liquidity token initialized`);
333
+ return amm;
334
+ }
335
+ async fundAmm(defaultAccountAddress, liquidityProvider, amm, token0, token1, lpToken) {
336
+ const getPrivateBalances = ()=>Promise.all([
337
+ token0.methods.balance_of_private(liquidityProvider).simulate({
338
+ from: liquidityProvider
339
+ }).then((r)=>r.result),
340
+ token1.methods.balance_of_private(liquidityProvider).simulate({
341
+ from: liquidityProvider
342
+ }).then((r)=>r.result),
343
+ lpToken.methods.balance_of_private(liquidityProvider).simulate({
344
+ from: liquidityProvider
345
+ }).then((r)=>r.result)
346
+ ]);
347
+ const authwitNonce = Fr.random();
348
+ // keep some tokens for swapping
349
+ const amount0Max = MINT_BALANCE / 2;
350
+ const amount0Min = MINT_BALANCE / 4;
351
+ const amount1Max = MINT_BALANCE / 2;
352
+ const amount1Min = MINT_BALANCE / 4;
353
+ const [t0Bal, t1Bal, lpBal] = await getPrivateBalances();
354
+ this.log.info(`Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1. Current private balances of ${liquidityProvider}: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`);
355
+ // Add authwitnesses for the transfers in AMM::add_liquidity function
356
+ const token0Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
357
+ caller: amm.address,
358
+ call: await token0.methods.transfer_to_public_and_prepare_private_balance_increase(liquidityProvider, amm.address, amount0Max, authwitNonce).getFunctionCall()
359
+ });
360
+ const token1Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
361
+ caller: amm.address,
362
+ call: await token1.methods.transfer_to_public_and_prepare_private_balance_increase(liquidityProvider, amm.address, amount1Max, authwitNonce).getFunctionCall()
363
+ });
364
+ const mintBatch = new BatchCall(this.wallet, [
365
+ token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
366
+ token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE)
367
+ ]);
368
+ const { receipt: mintReceipt } = await mintBatch.send({
369
+ from: liquidityProvider,
370
+ wait: {
371
+ timeout: this.config.txMinedWaitSeconds
372
+ }
373
+ });
374
+ this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
375
+ const addLiquidityInteraction = amm.methods.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce);
376
+ const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
377
+ from: liquidityProvider,
378
+ authWitnesses: [
379
+ token0Authwit,
380
+ token1Authwit
381
+ ],
382
+ wait: {
383
+ timeout: this.config.txMinedWaitSeconds
384
+ }
385
+ });
386
+ this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`);
387
+ this.log.info(`Liquidity added`);
388
+ const [newT0Bal, newT1Bal, newLPBal] = await getPrivateBalances();
389
+ this.log.info(`Updated private balances of ${defaultAccountAddress} after minting and funding AMM: token0=${newT0Bal}, token1=${newT1Bal}, lp=${newLPBal}`);
390
+ }
391
+ async registerOrDeployContract(name, deploy, deployOpts) {
392
+ const instance = await deploy.getInstance();
393
+ const address = instance.address;
394
+ const metadata = await this.wallet.getContractMetadata(address);
395
+ if (metadata.isContractPublished) {
396
+ this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
397
+ await deploy.register();
398
+ } else {
399
+ const sender = deployOpts.from === NO_FROM ? undefined : deployOpts.from;
400
+ const balance = sender ? await getFeeJuiceBalance(sender, this.aztecNode) : 0n;
401
+ const useClaim = sender && balance < FEE_JUICE_TOP_UP_THRESHOLD && this.config.feePaymentMethod === 'fee_juice' && !!this.config.l1RpcUrls?.length;
402
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
403
+ if (useClaim && mnemonicOrPrivateKey) {
404
+ const claim = await this.getOrCreateBridgeClaim(sender);
405
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(sender, claim);
406
+ const { estimatedGas } = await deploy.simulate({
407
+ ...deployOpts,
408
+ fee: {
409
+ estimateGas: true,
410
+ paymentMethod
411
+ }
412
+ });
413
+ const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
414
+ const gasSettings = GasSettings.from({
415
+ ...estimatedGas,
416
+ maxFeesPerGas,
417
+ maxPriorityFeesPerGas: GasFees.empty()
418
+ });
419
+ await this.withNoMinTxsPerBlock(async ()=>{
420
+ const { txHash } = await deploy.send({
421
+ ...deployOpts,
422
+ fee: {
423
+ gasSettings,
424
+ paymentMethod
425
+ },
426
+ wait: NO_WAIT
427
+ });
428
+ this.log.info(`Sent contract ${name} deploy tx ${txHash.toString()} (using bridge claim, balance was ${balance})`);
429
+ return waitForTx(this.aztecNode, txHash, {
430
+ timeout: this.config.txMinedWaitSeconds
431
+ });
432
+ });
433
+ await this.store.deleteBridgeClaim(sender);
434
+ } else {
435
+ const { estimatedGas } = await deploy.simulate({
436
+ ...deployOpts,
437
+ fee: {
438
+ estimateGas: true
439
+ }
440
+ });
441
+ this.log.info(`Deploying contract ${name} at ${address.toString()}`, {
442
+ estimatedGas
443
+ });
444
+ await this.withNoMinTxsPerBlock(async ()=>{
445
+ const { txHash } = await deploy.send({
446
+ ...deployOpts,
447
+ fee: {
448
+ gasSettings: estimatedGas
449
+ },
450
+ wait: NO_WAIT
451
+ });
452
+ this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
453
+ return waitForTx(this.aztecNode, txHash, {
454
+ timeout: this.config.txMinedWaitSeconds
455
+ });
456
+ });
457
+ }
154
458
  }
459
+ return instance;
155
460
  }
156
461
  /**
157
462
  * Mints private and public tokens for the sender if their balance is below the minimum.
158
463
  * @param token - Token contract.
159
- */ async mintTokens(token) {
160
- const sender = token.wallet.getAddress();
464
+ */ /**
465
+ * Ensures the account has sufficient fee juice by bridging from L1 if balance is below threshold.
466
+ * Bridges repeatedly until balance reaches the target (10k FJ).
467
+ * Used on startup/restart to top up when the account has run out after previous runs.
468
+ */ async ensureFeeJuiceBalance(account, token) {
469
+ const { feePaymentMethod, l1RpcUrls } = this.config;
470
+ if (feePaymentMethod !== 'fee_juice' || !l1RpcUrls?.length) {
471
+ return;
472
+ }
473
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
474
+ if (!mnemonicOrPrivateKey) {
475
+ return;
476
+ }
477
+ let balance = await getFeeJuiceBalance(account, this.aztecNode);
478
+ if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
479
+ this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
480
+ return;
481
+ }
482
+ this.log.info(`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1 until ${FEE_JUICE_TOP_UP_TARGET}`);
483
+ const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
484
+ const minimalInteraction = isStandardTokenContract(token) ? token.methods.transfer_in_public(account, account, 0n, 0) : token.methods.transfer(0n, account, account);
485
+ while(balance < FEE_JUICE_TOP_UP_TARGET){
486
+ const claim = await this.bridgeL1FeeJuice(account);
487
+ const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
488
+ const { estimatedGas } = await minimalInteraction.simulate({
489
+ from: account,
490
+ fee: {
491
+ estimateGas: true,
492
+ paymentMethod
493
+ }
494
+ });
495
+ const gasSettings = GasSettings.from({
496
+ ...estimatedGas,
497
+ maxFeesPerGas,
498
+ maxPriorityFeesPerGas: GasFees.empty()
499
+ });
500
+ await this.withNoMinTxsPerBlock(async ()=>{
501
+ const { txHash } = await minimalInteraction.send({
502
+ from: account,
503
+ fee: {
504
+ gasSettings,
505
+ paymentMethod
506
+ },
507
+ wait: NO_WAIT
508
+ });
509
+ this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
510
+ return waitForTx(this.aztecNode, txHash, {
511
+ timeout: this.config.txMinedWaitSeconds
512
+ });
513
+ });
514
+ balance = await getFeeJuiceBalance(account, this.aztecNode);
515
+ this.log.info(`Fee juice balance after top-up: ${balance}`);
516
+ }
517
+ this.log.info(`Fee juice top-up complete for ${account.toString()}`);
518
+ }
519
+ async mintTokens(token, minter) {
161
520
  const isStandardToken = isStandardTokenContract(token);
162
521
  let privateBalance = 0n;
163
522
  let publicBalance = 0n;
164
523
  if (isStandardToken) {
165
- ({ privateBalance, publicBalance } = await getBalances(token, sender));
524
+ ({ privateBalance, publicBalance } = await getBalances(token, minter));
166
525
  } else {
167
- privateBalance = await getPrivateBalance(token, sender);
526
+ privateBalance = await getPrivateBalance(token, minter);
168
527
  }
169
528
  const calls = [];
170
529
  if (privateBalance < MIN_BALANCE) {
171
- this.log.info(`Minting private tokens for ${sender.toString()}`);
172
- const from = sender; // we are setting from to sender here because we need a sender to calculate the tag
173
- calls.push(isStandardToken ? await token.methods.mint_to_private(from, sender, MINT_BALANCE).request() : await token.methods.mint(MINT_BALANCE, sender).request());
530
+ this.log.info(`Minting private tokens for ${minter.toString()}`);
531
+ calls.push(isStandardToken ? token.methods.mint_to_private(minter, MINT_BALANCE) : token.methods.mint(MINT_BALANCE, minter));
174
532
  }
175
533
  if (isStandardToken && publicBalance < MIN_BALANCE) {
176
- this.log.info(`Minting public tokens for ${sender.toString()}`);
177
- calls.push(await token.methods.mint_to_public(sender, MINT_BALANCE).request());
534
+ this.log.info(`Minting public tokens for ${minter.toString()}`);
535
+ calls.push(token.methods.mint_to_public(minter, MINT_BALANCE));
178
536
  }
179
537
  if (calls.length === 0) {
180
- this.log.info(`Skipping minting as ${sender.toString()} has enough tokens`);
538
+ this.log.info(`Skipping minting as ${minter.toString()} has enough tokens`);
181
539
  return;
182
540
  }
183
- const sentTx = new BatchCall(token.wallet, calls).send();
184
- const txHash = await sentTx.getTxHash();
185
- this.log.info(`Sent tx with hash ${txHash.toString()}`);
186
- await this.tryFlushTxs();
187
- this.log.verbose('Waiting for token mint to settle');
188
- await sentTx.wait({
189
- timeout: this.config.txMinedWaitSeconds
541
+ // PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
542
+ const additionalScopes = isStandardToken ? undefined : [
543
+ token.address
544
+ ];
545
+ const mintBatch = new BatchCall(token.wallet, calls);
546
+ await this.withNoMinTxsPerBlock(async ()=>{
547
+ const { txHash } = await mintBatch.send({
548
+ from: minter,
549
+ additionalScopes,
550
+ wait: NO_WAIT
551
+ });
552
+ this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
553
+ return waitForTx(this.aztecNode, txHash, {
554
+ timeout: this.config.txMinedWaitSeconds
555
+ });
190
556
  });
191
557
  }
192
- async bridgeL1FeeJuice(recipient, amount) {
558
+ /**
559
+ * Gets or creates a bridge claim for the recipient.
560
+ * Checks if a claim already exists in the store and reuses it if valid.
561
+ * Only creates a new bridge if fee juice balance is below threshold.
562
+ */ async getOrCreateBridgeClaim(recipient) {
563
+ // Check if we have an existing claim in the store
564
+ const existingClaim = await this.store.getBridgeClaim(recipient);
565
+ if (existingClaim) {
566
+ this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
567
+ // Check if the message is ready on L2
568
+ try {
569
+ const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
570
+ await this.withNoMinTxsPerBlock(()=>waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
571
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds
572
+ }));
573
+ return existingClaim.claim;
574
+ } catch (err) {
575
+ this.log.warn(`Failed to verify existing claim, creating new one: ${err}`);
576
+ await this.store.deleteBridgeClaim(recipient);
577
+ }
578
+ }
579
+ const claim = await this.bridgeL1FeeJuice(recipient);
580
+ await this.store.saveBridgeClaim(recipient, claim);
581
+ return claim;
582
+ }
583
+ async bridgeL1FeeJuice(recipient) {
193
584
  const l1RpcUrls = this.config.l1RpcUrls;
194
585
  if (!l1RpcUrls?.length) {
195
586
  throw new Error('L1 Rpc url is required to bridge the fee juice to fund the deployment of the account.');
196
587
  }
197
- const mnemonicOrPrivateKey = this.config.l1PrivateKey || this.config.l1Mnemonic;
588
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
198
589
  if (!mnemonicOrPrivateKey) {
199
590
  throw new Error('Either a mnemonic or private key of an L1 account is required to bridge the fee juice to fund the deployment of the account.');
200
591
  }
201
- const { l1ChainId } = await this.pxe.getNodeInfo();
592
+ const { l1ChainId } = await this.aztecNode.getNodeInfo();
202
593
  const chain = createEthereumChain(l1RpcUrls, l1ChainId);
203
- const { publicClient, walletClient } = createL1Clients(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
204
- const portal = await L1FeeJuicePortalManager.new(this.pxe, publicClient, walletClient, this.log);
205
- const claim = await portal.bridgeTokensPublic(recipient, amount, true);
206
- const isSynced = async ()=>await this.pxe.isL1ToL2MessageSynced(Fr.fromHexString(claim.messageHash));
207
- await retryUntil(isSynced, `message ${claim.messageHash} sync`, 24, 1);
208
- this.log.info(`Created a claim for ${amount} L1 fee juice to ${recipient}.`, claim);
209
- // Progress by 2 L2 blocks so that the l1ToL2Message added above will be available to use on L2.
210
- await this.advanceL2Block();
211
- await this.advanceL2Block();
594
+ const extendedClient = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
595
+ const portal = await L1FeeJuicePortalManager.new(this.aztecNode, extendedClient, this.log);
596
+ const mintAmount = await portal.getTokenManager().getMintAmount();
597
+ const claim = await portal.bridgeTokensPublic(recipient, mintAmount, true);
598
+ await this.withNoMinTxsPerBlock(()=>waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
599
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds
600
+ }));
601
+ this.log.info(`Created a claim for ${mintAmount} L1 fee juice to ${recipient}.`, claim);
212
602
  return claim;
213
603
  }
214
- async advanceL2Block() {
215
- const initialBlockNumber = await this.node.getBlockNumber();
216
- await this.tryFlushTxs();
217
- await retryUntil(async ()=>await this.node.getBlockNumber() >= initialBlockNumber + 1);
218
- }
219
- async tryFlushTxs() {
220
- if (this.config.flushSetupTransactions) {
221
- this.log.verbose('Flushing transactions');
222
- try {
223
- await this.node.flushTxs();
224
- } catch (err) {
225
- this.log.error(`Failed to flush transactions: ${err}`);
604
+ /** Returns worst-case min fees across predicted slots, with fallback to current min fees. */ async getMinFees() {
605
+ try {
606
+ const predicted = await this.aztecNode.getPredictedMinFees(ManaUsageEstimate.Limit);
607
+ if (predicted.length === 0) {
608
+ return this.aztecNode.getCurrentMinFees();
226
609
  }
610
+ return predicted.reduce((worst, fees)=>fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst);
611
+ } catch {
612
+ return this.aztecNode.getCurrentMinFees();
613
+ }
614
+ }
615
+ async withNoMinTxsPerBlock(fn) {
616
+ if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
617
+ this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
618
+ return fn();
619
+ }
620
+ const { minTxsPerBlock } = await this.aztecNodeAdmin.getConfig();
621
+ this.log.warn(`Setting sequencer minTxsPerBlock to 0 from ${minTxsPerBlock} to flush setup transactions`);
622
+ await this.aztecNodeAdmin.setConfig({
623
+ minTxsPerBlock: 0
624
+ });
625
+ try {
626
+ return await fn();
627
+ } finally{
628
+ this.log.warn(`Restoring sequencer minTxsPerBlock to ${minTxsPerBlock}`);
629
+ await this.aztecNodeAdmin.setConfig({
630
+ minTxsPerBlock
631
+ });
227
632
  }
228
633
  }
229
634
  }