@aztec/bot 0.0.0-test.1 → 0.0.1-fake-ceab37513c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dest/config.js CHANGED
@@ -1,4 +1,4 @@
1
- import { booleanConfigHelper, getConfigFromMappings, getDefaultConfig, numberConfigHelper, optionalNumberConfigHelper } from '@aztec/foundation/config';
1
+ import { booleanConfigHelper, getConfigFromMappings, getDefaultConfig, numberConfigHelper, optionalNumberConfigHelper, secretFrConfigHelper, secretStringConfigHelper } from '@aztec/foundation/config';
2
2
  import { Fr } from '@aztec/foundation/fields';
3
3
  import { getVKTreeRoot } from '@aztec/noir-protocol-circuits-types/vk-tree';
4
4
  import { protocolContractTreeRoot } from '@aztec/protocol-contracts';
@@ -11,17 +11,20 @@ const BotFollowChain = [
11
11
  ];
12
12
  export var SupportedTokenContracts = /*#__PURE__*/ function(SupportedTokenContracts) {
13
13
  SupportedTokenContracts["TokenContract"] = "TokenContract";
14
- SupportedTokenContracts["EasyPrivateTokenContract"] = "EasyPrivateTokenContract";
14
+ SupportedTokenContracts["PrivateTokenContract"] = "PrivateTokenContract";
15
15
  return SupportedTokenContracts;
16
16
  }({});
17
17
  export const BotConfigSchema = z.object({
18
18
  nodeUrl: z.string().optional(),
19
+ nodeAdminUrl: z.string().optional(),
19
20
  pxeUrl: z.string().optional(),
20
21
  l1RpcUrls: z.array(z.string()).optional(),
21
- l1Mnemonic: z.string().optional(),
22
- l1PrivateKey: z.string().optional(),
23
- senderPrivateKey: schemas.Fr.optional(),
24
- recipientEncryptionSecret: schemas.Fr,
22
+ l1Mnemonic: schemas.SecretValue(z.string()).optional(),
23
+ l1PrivateKey: schemas.SecretValue(z.string()).optional(),
24
+ l1ToL2MessageTimeoutSeconds: z.number(),
25
+ senderPrivateKey: schemas.SecretValue(schemas.Fr).optional(),
26
+ senderSalt: schemas.Fr.optional(),
27
+ recipientEncryptionSecret: schemas.SecretValue(schemas.Fr),
25
28
  tokenSalt: schemas.Fr,
26
29
  txIntervalSeconds: z.number(),
27
30
  privateTransfersPerTx: z.number().int().nonnegative(),
@@ -32,21 +35,23 @@ export const BotConfigSchema = z.object({
32
35
  followChain: z.enum(BotFollowChain),
33
36
  maxPendingTxs: z.number().int().nonnegative(),
34
37
  flushSetupTransactions: z.boolean(),
35
- skipPublicSimulation: z.boolean(),
36
38
  l2GasLimit: z.number().int().nonnegative().optional(),
37
39
  daGasLimit: z.number().int().nonnegative().optional(),
38
40
  contract: z.nativeEnum(SupportedTokenContracts),
39
41
  maxConsecutiveErrors: z.number().int().nonnegative(),
40
- stopWhenUnhealthy: z.boolean()
42
+ stopWhenUnhealthy: z.boolean(),
43
+ ammTxs: z.boolean().default(false)
41
44
  }).transform((config)=>({
42
45
  nodeUrl: undefined,
46
+ nodeAdminUrl: undefined,
43
47
  pxeUrl: undefined,
44
48
  l1RpcUrls: undefined,
49
+ senderSalt: undefined,
50
+ l2GasLimit: undefined,
51
+ daGasLimit: undefined,
45
52
  l1Mnemonic: undefined,
46
53
  l1PrivateKey: undefined,
47
54
  senderPrivateKey: undefined,
48
- l2GasLimit: undefined,
49
- daGasLimit: undefined,
50
55
  ...config
51
56
  }));
52
57
  export const botConfigMappings = {
@@ -54,6 +59,10 @@ export const botConfigMappings = {
54
59
  env: 'AZTEC_NODE_URL',
55
60
  description: 'The URL to the Aztec node to check for tx pool status.'
56
61
  },
62
+ nodeAdminUrl: {
63
+ env: 'AZTEC_NODE_ADMIN_URL',
64
+ description: 'The URL to the Aztec node admin API to force-flush txs if configured.'
65
+ },
57
66
  pxeUrl: {
58
67
  env: 'BOT_PXE_URL',
59
68
  description: 'URL to the PXE for sending txs, or undefined if an in-proc PXE is used.'
@@ -65,22 +74,34 @@ export const botConfigMappings = {
65
74
  },
66
75
  l1Mnemonic: {
67
76
  env: 'BOT_L1_MNEMONIC',
68
- description: 'The mnemonic for the account to bridge fee juice from L1.'
77
+ description: 'The mnemonic for the account to bridge fee juice from L1.',
78
+ ...secretStringConfigHelper()
69
79
  },
70
80
  l1PrivateKey: {
71
81
  env: 'BOT_L1_PRIVATE_KEY',
72
- description: 'The private key for the account to bridge fee juice from L1.'
82
+ description: 'The private key for the account to bridge fee juice from L1.',
83
+ ...secretStringConfigHelper()
84
+ },
85
+ l1ToL2MessageTimeoutSeconds: {
86
+ env: 'BOT_L1_TO_L2_TIMEOUT_SECONDS',
87
+ description: 'How long to wait for L1 to L2 messages to become available on L2',
88
+ ...numberConfigHelper(3600)
73
89
  },
74
90
  senderPrivateKey: {
75
91
  env: 'BOT_PRIVATE_KEY',
76
92
  description: 'Signing private key for the sender account.',
93
+ ...secretFrConfigHelper()
94
+ },
95
+ senderSalt: {
96
+ env: 'BOT_ACCOUNT_SALT',
97
+ description: 'The salt to use to deploys the sender account.',
77
98
  parseEnv: (val)=>val ? Fr.fromHexString(val) : undefined
78
99
  },
79
100
  recipientEncryptionSecret: {
80
101
  env: 'BOT_RECIPIENT_ENCRYPTION_SECRET',
81
102
  description: 'Encryption secret for a recipient account.',
82
- parseEnv: (val)=>Fr.fromHexString(val),
83
- defaultValue: Fr.fromHexString('0xcafecafe')
103
+ printDefault: (sv)=>sv?.getValue(),
104
+ ...secretFrConfigHelper(Fr.fromHexString('0xcafecafe'))
84
105
  },
85
106
  tokenSalt: {
86
107
  env: 'BOT_TOKEN_SALT',
@@ -140,11 +161,6 @@ export const botConfigMappings = {
140
161
  description: 'Make a request for the sequencer to build a block after each setup transaction.',
141
162
  ...booleanConfigHelper(false)
142
163
  },
143
- skipPublicSimulation: {
144
- env: 'BOT_SKIP_PUBLIC_SIMULATION',
145
- description: 'Whether to skip public simulation of txs before sending them.',
146
- ...booleanConfigHelper(false)
147
- },
148
164
  l2GasLimit: {
149
165
  env: 'BOT_L2_GAS_LIMIT',
150
166
  description: 'L2 gas limit for the tx (empty to have the bot trigger an estimate gas).',
@@ -175,6 +191,11 @@ export const botConfigMappings = {
175
191
  env: 'BOT_STOP_WHEN_UNHEALTHY',
176
192
  description: 'Stops the bot if service becomes unhealthy',
177
193
  ...booleanConfigHelper(false)
194
+ },
195
+ ammTxs: {
196
+ env: 'BOT_AMM_TXS',
197
+ description: 'Deploy an AMM and send swaps to it',
198
+ ...booleanConfigHelper(false)
178
199
  }
179
200
  };
180
201
  export function getBotConfigFromEnv() {
package/dest/factory.d.ts CHANGED
@@ -1,14 +1,18 @@
1
- import { AztecAddress, type AztecNode, type PXE } from '@aztec/aztec.js';
2
- import { EasyPrivateTokenContract } from '@aztec/noir-contracts.js/EasyPrivateToken';
1
+ import { AztecAddress, type PXE } from '@aztec/aztec.js';
2
+ import { AMMContract } from '@aztec/noir-contracts.js/AMM';
3
+ import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
3
4
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
5
+ import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
4
6
  import { type BotConfig } from './config.js';
5
7
  export declare class BotFactory {
6
8
  private readonly config;
7
9
  private pxe;
8
10
  private node?;
11
+ private nodeAdmin?;
9
12
  private log;
10
- constructor(config: BotConfig, dependencies?: {
13
+ constructor(config: BotConfig, dependencies: {
11
14
  pxe?: PXE;
15
+ nodeAdmin?: AztecNodeAdmin;
12
16
  node?: AztecNode;
13
17
  });
14
18
  /**
@@ -17,10 +21,19 @@ export declare class BotFactory {
17
21
  */
18
22
  setup(): Promise<{
19
23
  wallet: import("@aztec/aztec.js").AccountWalletWithSecretKey;
20
- token: TokenContract | EasyPrivateTokenContract;
24
+ defaultAccountAddress: AztecAddress;
25
+ token: TokenContract | PrivateTokenContract;
21
26
  pxe: PXE;
22
27
  recipient: AztecAddress;
23
28
  }>;
29
+ setupAmm(): Promise<{
30
+ wallet: import("@aztec/aztec.js").AccountWalletWithSecretKey;
31
+ defaultAccountAddress: AztecAddress;
32
+ amm: AMMContract;
33
+ token0: TokenContract;
34
+ token1: TokenContract;
35
+ pxe: PXE;
36
+ }>;
24
37
  /**
25
38
  * Checks if the sender account contract is initialized, and initializes it if necessary.
26
39
  * @returns The sender wallet.
@@ -38,13 +51,21 @@ export declare class BotFactory {
38
51
  * @returns The TokenContract instance.
39
52
  */
40
53
  private setupToken;
54
+ /**
55
+ * Checks if the token contract is deployed and deploys it if necessary.
56
+ * @param wallet - Wallet to deploy the token contract from.
57
+ * @returns The TokenContract instance.
58
+ */
59
+ private setupTokenContract;
60
+ private setupAmmContract;
61
+ private fundAmm;
62
+ private registerOrDeployContract;
41
63
  /**
42
64
  * Mints private and public tokens for the sender if their balance is below the minimum.
43
65
  * @param token - Token contract.
44
66
  */
45
67
  private mintTokens;
46
68
  private bridgeL1FeeJuice;
47
- private advanceL2Block;
48
- private tryFlushTxs;
69
+ private withNoMinTxsPerBlock;
49
70
  }
50
71
  //# sourceMappingURL=factory.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,YAAY,EACZ,KAAK,SAAS,EAMd,KAAK,GAAG,EAIT,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,wBAAwB,EAAE,MAAM,2CAA2C,CAAC;AACrF,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAK/D,OAAO,EAAE,KAAK,SAAS,EAAwC,MAAM,aAAa,CAAC;AAMnF,qBAAa,UAAU;IAKT,OAAO,CAAC,QAAQ,CAAC,MAAM;IAJnC,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,IAAI,CAAC,CAAY;IACzB,OAAO,CAAC,GAAG,CAAuB;gBAEL,MAAM,EAAE,SAAS,EAAE,YAAY,GAAE;QAAE,GAAG,CAAC,EAAE,GAAG,CAAC;QAAC,IAAI,CAAC,EAAE,SAAS,CAAA;KAAO;IAwBlG;;;OAGG;IACU,KAAK;;;;;;IAQlB;;;OAGG;YACW,YAAY;YAQZ,0BAA0B;YA4B1B,gBAAgB;IAc9B;;OAEG;YACW,iBAAiB;IAK/B;;;;OAIG;YACW,UAAU;IA8BxB;;;OAGG;YACW,UAAU;YAuCV,gBAAgB;YA+BhB,cAAc;YAMd,WAAW;CAU1B"}
1
+ {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,YAAY,EAQZ,KAAK,GAAG,EAIT,MAAM,iBAAiB,CAAC;AAIzB,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,KAAK,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAIjF,OAAO,EAAE,KAAK,SAAS,EAAwC,MAAM,aAAa,CAAC;AAMnF,qBAAa,UAAU;IAOnB,OAAO,CAAC,QAAQ,CAAC,MAAM;IANzB,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,IAAI,CAAC,CAAY;IACzB,OAAO,CAAC,SAAS,CAAC,CAAiB;IACnC,OAAO,CAAC,GAAG,CAAuB;gBAGf,MAAM,EAAE,SAAS,EAClC,YAAY,EAAE;QAAE,GAAG,CAAC,EAAE,GAAG,CAAC;QAAC,SAAS,CAAC,EAAE,cAAc,CAAC;QAAC,IAAI,CAAC,EAAE,SAAS,CAAA;KAAE;IA4B3E;;;OAGG;IACU,KAAK;;;;;;;IASL,QAAQ;;;;;;;;IAuCrB;;;OAGG;YACW,YAAY;YASZ,0BAA0B;YA8B1B,gBAAgB;IAc9B;;OAEG;YACW,iBAAiB;IAK/B;;;;OAIG;YACW,UAAU;IA+BxB;;;;OAIG;IACH,OAAO,CAAC,kBAAkB;YAaZ,gBAAgB;YAqBhB,OAAO;YA0EP,wBAAwB;IAkBtC;;;OAGG;YACW,UAAU;YAmCV,gBAAgB;YAgChB,oBAAoB;CAYnC"}
package/dest/factory.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import { getSchnorrAccount } from '@aztec/accounts/schnorr';
2
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';
3
+ import { BatchCall, FeeJuicePaymentMethodWithClaim, L1FeeJuicePortalManager, createLogger, createPXEClient, waitForL1ToL2MessageReady } from '@aztec/aztec.js';
4
+ import { createEthereumChain, createExtendedL1Client } from '@aztec/ethereum';
5
5
  import { Fr } from '@aztec/foundation/fields';
6
- import { EasyPrivateTokenContract } from '@aztec/noir-contracts.js/EasyPrivateToken';
6
+ import { Timer } from '@aztec/foundation/timer';
7
+ import { AMMContract } from '@aztec/noir-contracts.js/AMM';
8
+ import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
7
9
  import { TokenContract } from '@aztec/noir-contracts.js/Token';
8
10
  import { deriveSigningKey } from '@aztec/stdlib/keys';
9
11
  import { makeTracedFetch } from '@aztec/telemetry-client';
@@ -15,20 +17,22 @@ export class BotFactory {
15
17
  config;
16
18
  pxe;
17
19
  node;
20
+ nodeAdmin;
18
21
  log;
19
- constructor(config, dependencies = {}){
22
+ constructor(config, dependencies){
20
23
  this.config = config;
21
24
  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`);
25
+ if (config.flushSetupTransactions && !dependencies.nodeAdmin) {
26
+ throw new Error(`Either a node admin client or node admin url must be provided if transaction flushing is requested`);
24
27
  }
25
- if (config.senderPrivateKey && !dependencies.node) {
28
+ if (config.senderPrivateKey && config.senderPrivateKey.getValue() && !dependencies.node) {
26
29
  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
30
  }
28
31
  if (!dependencies.pxe && !config.pxeUrl) {
29
32
  throw new Error(`Either a PXE client or a PXE URL must be provided`);
30
33
  }
31
34
  this.node = dependencies.node;
35
+ this.nodeAdmin = dependencies.nodeAdmin;
32
36
  if (dependencies.pxe) {
33
37
  this.log.info(`Using local PXE`);
34
38
  this.pxe = dependencies.pxe;
@@ -47,38 +51,62 @@ export class BotFactory {
47
51
  */ async setup() {
48
52
  const recipient = await this.registerRecipient();
49
53
  const wallet = await this.setupAccount();
50
- const token = await this.setupToken(wallet);
51
- await this.mintTokens(token);
54
+ const defaultAccountAddress = wallet.getAddress();
55
+ const token = await this.setupToken(wallet, defaultAccountAddress);
56
+ await this.mintTokens(token, defaultAccountAddress);
52
57
  return {
53
58
  wallet,
59
+ defaultAccountAddress,
54
60
  token,
55
61
  pxe: this.pxe,
56
62
  recipient
57
63
  };
58
64
  }
65
+ async setupAmm() {
66
+ const wallet = await this.setupAccount();
67
+ const defaultAccountAddress = wallet.getAddress();
68
+ const token0 = await this.setupTokenContract(wallet, wallet.getAddress(), this.config.tokenSalt, 'BotToken0', 'BOT0');
69
+ const token1 = await this.setupTokenContract(wallet, wallet.getAddress(), this.config.tokenSalt, 'BotToken1', 'BOT1');
70
+ const liquidityToken = await this.setupTokenContract(wallet, wallet.getAddress(), this.config.tokenSalt, 'BotLPToken', 'BOTLP');
71
+ const amm = await this.setupAmmContract(wallet, wallet.getAddress(), this.config.tokenSalt, token0, token1, liquidityToken);
72
+ await this.fundAmm(wallet, wallet.getAddress(), amm, token0, token1, liquidityToken);
73
+ this.log.info(`AMM initialized and funded`);
74
+ return {
75
+ wallet,
76
+ defaultAccountAddress,
77
+ amm,
78
+ token0,
79
+ token1,
80
+ pxe: this.pxe
81
+ };
82
+ }
59
83
  /**
60
84
  * Checks if the sender account contract is initialized, and initializes it if necessary.
61
85
  * @returns The sender wallet.
62
86
  */ async setupAccount() {
63
- if (this.config.senderPrivateKey) {
64
- return await this.setupAccountWithPrivateKey(this.config.senderPrivateKey);
87
+ const privateKey = this.config.senderPrivateKey?.getValue();
88
+ if (privateKey) {
89
+ return await this.setupAccountWithPrivateKey(privateKey);
65
90
  } else {
66
91
  return await this.setupTestAccount();
67
92
  }
68
93
  }
69
94
  async setupAccountWithPrivateKey(privateKey) {
70
- const salt = Fr.ONE;
95
+ const salt = this.config.senderSalt ?? Fr.ONE;
71
96
  const signingKey = deriveSigningKey(privateKey);
72
97
  const account = await getSchnorrAccount(this.pxe, privateKey, signingKey, salt);
73
98
  const isInit = (await this.pxe.getContractMetadata(account.getAddress())).isContractInitialized;
74
99
  if (isInit) {
75
100
  this.log.info(`Account at ${account.getAddress().toString()} already initialized`);
101
+ const timer = new Timer();
76
102
  const wallet = await account.register();
103
+ this.log.info(`Account at ${account.getAddress()} registered. duration=${timer.ms()}`);
77
104
  return wallet;
78
105
  } else {
79
106
  const address = account.getAddress();
80
107
  this.log.info(`Deploying account at ${address}`);
81
- const claim = await this.bridgeL1FeeJuice(address, 10n ** 22n);
108
+ const claim = await this.bridgeL1FeeJuice(address);
109
+ // docs:start:claim_and_deploy
82
110
  const wallet = await account.getWallet();
83
111
  const paymentMethod = new FeeJuicePaymentMethodWithClaim(wallet, claim);
84
112
  const sentTx = account.deploy({
@@ -87,12 +115,11 @@ export class BotFactory {
87
115
  }
88
116
  });
89
117
  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
95
- });
118
+ // docs:end:claim_and_deploy
119
+ this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
120
+ await this.withNoMinTxsPerBlock(()=>sentTx.wait({
121
+ timeout: this.config.txMinedWaitSeconds
122
+ }));
96
123
  this.log.info(`Account deployed at ${address}`);
97
124
  return wallet;
98
125
  }
@@ -113,117 +140,215 @@ export class BotFactory {
113
140
  /**
114
141
  * Registers the recipient for txs in the pxe.
115
142
  */ async registerRecipient() {
116
- const recipient = await this.pxe.registerAccount(this.config.recipientEncryptionSecret, Fr.ONE);
143
+ const recipient = await this.pxe.registerAccount(this.config.recipientEncryptionSecret.getValue(), Fr.ONE);
117
144
  return recipient.address;
118
145
  }
119
146
  /**
120
147
  * Checks if the token contract is deployed and deploys it if necessary.
121
148
  * @param wallet - Wallet to deploy the token contract from.
122
149
  * @returns The TokenContract instance.
123
- */ async setupToken(wallet) {
150
+ */ async setupToken(wallet, sender) {
124
151
  let deploy;
125
152
  const deployOpts = {
153
+ from: sender,
126
154
  contractAddressSalt: this.config.tokenSalt,
127
155
  universalDeploy: true
128
156
  };
129
157
  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;
158
+ deploy = TokenContract.deploy(wallet, sender, 'BotToken', 'BOT', 18);
159
+ } else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
160
+ deploy = PrivateTokenContract.deploy(wallet, MINT_BALANCE, sender);
161
+ deployOpts.skipInstancePublication = true;
162
+ deployOpts.skipClassPublication = true;
135
163
  deployOpts.skipInitialization = false;
136
- deployOpts.skipPublicSimulation = true;
137
164
  } else {
138
165
  throw new Error(`Unsupported token contract type: ${this.config.contract}`);
139
166
  }
140
167
  const address = (await deploy.getInstance(deployOpts)).address;
141
- if ((await this.pxe.getContractMetadata(address)).isContractPubliclyDeployed) {
168
+ if ((await this.pxe.getContractMetadata(address)).isContractPublished) {
142
169
  this.log.info(`Token at ${address.toString()} already deployed`);
143
170
  return deploy.register();
144
171
  } else {
145
172
  this.log.info(`Deploying token contract at ${address.toString()}`);
146
173
  const sentTx = deploy.send(deployOpts);
147
174
  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({
152
- timeout: this.config.txMinedWaitSeconds
153
- });
175
+ this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
176
+ return this.withNoMinTxsPerBlock(()=>sentTx.deployed({
177
+ timeout: this.config.txMinedWaitSeconds
178
+ }));
179
+ }
180
+ }
181
+ /**
182
+ * Checks if the token contract is deployed and deploys it if necessary.
183
+ * @param wallet - Wallet to deploy the token contract from.
184
+ * @returns The TokenContract instance.
185
+ */ setupTokenContract(wallet, deployer, contractAddressSalt, name, ticker, decimals = 18) {
186
+ const deployOpts = {
187
+ from: deployer,
188
+ contractAddressSalt,
189
+ universalDeploy: true
190
+ };
191
+ const deploy = TokenContract.deploy(wallet, deployer, name, ticker, decimals);
192
+ return this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
193
+ }
194
+ async setupAmmContract(wallet, deployer, contractAddressSalt, token0, token1, lpToken) {
195
+ const deployOpts = {
196
+ from: deployer,
197
+ contractAddressSalt,
198
+ universalDeploy: true
199
+ };
200
+ const deploy = AMMContract.deploy(wallet, token0.address, token1.address, lpToken.address);
201
+ const amm = await this.registerOrDeployContract('AMM', deploy, deployOpts);
202
+ this.log.info(`AMM deployed at ${amm.address}`);
203
+ const minterTx = lpToken.methods.set_minter(amm.address, true).send({
204
+ from: deployer
205
+ });
206
+ this.log.info(`Set LP token minter to AMM txHash=${(await minterTx.getTxHash()).toString()}`);
207
+ await minterTx.wait({
208
+ timeout: this.config.txMinedWaitSeconds
209
+ });
210
+ this.log.info(`Liquidity token initialized`);
211
+ return amm;
212
+ }
213
+ async fundAmm(wallet, liquidityProvider, amm, token0, token1, lpToken) {
214
+ const getPrivateBalances = ()=>Promise.all([
215
+ token0.methods.balance_of_private(liquidityProvider).simulate({
216
+ from: liquidityProvider
217
+ }),
218
+ token1.methods.balance_of_private(liquidityProvider).simulate({
219
+ from: liquidityProvider
220
+ }),
221
+ lpToken.methods.balance_of_private(liquidityProvider).simulate({
222
+ from: liquidityProvider
223
+ })
224
+ ]);
225
+ const authwitNonce = Fr.random();
226
+ // keep some tokens for swapping
227
+ const amount0Max = MINT_BALANCE / 2;
228
+ const amount0Min = MINT_BALANCE / 4;
229
+ const amount1Max = MINT_BALANCE / 2;
230
+ const amount1Min = MINT_BALANCE / 4;
231
+ const [t0Bal, t1Bal, lpBal] = await getPrivateBalances();
232
+ this.log.info(`Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1. Current private balances of ${liquidityProvider}: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`);
233
+ // Add authwitnesses for the transfers in AMM::add_liquidity function
234
+ const token0Authwit = await wallet.createAuthWit({
235
+ caller: amm.address,
236
+ action: token0.methods.transfer_to_public_and_prepare_private_balance_increase(liquidityProvider, amm.address, amount0Max, authwitNonce)
237
+ });
238
+ const token1Authwit = await wallet.createAuthWit({
239
+ caller: amm.address,
240
+ action: token1.methods.transfer_to_public_and_prepare_private_balance_increase(liquidityProvider, amm.address, amount1Max, authwitNonce)
241
+ });
242
+ const mintTx = new BatchCall(wallet, [
243
+ token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
244
+ token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE)
245
+ ]).send({
246
+ from: liquidityProvider
247
+ });
248
+ this.log.info(`Sent mint tx: ${(await mintTx.getTxHash()).toString()}`);
249
+ await mintTx.wait({
250
+ timeout: this.config.txMinedWaitSeconds
251
+ });
252
+ const addLiquidityTx = amm.methods.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce).send({
253
+ from: liquidityProvider,
254
+ authWitnesses: [
255
+ token0Authwit,
256
+ token1Authwit
257
+ ]
258
+ });
259
+ this.log.info(`Sent tx to add liquidity to the AMM: ${(await addLiquidityTx.getTxHash()).toString()}`);
260
+ await addLiquidityTx.wait({
261
+ timeout: this.config.txMinedWaitSeconds
262
+ });
263
+ this.log.info(`Liquidity added`);
264
+ const [newT0Bal, newT1Bal, newLPBal] = await getPrivateBalances();
265
+ this.log.info(`Updated private balances of ${wallet.getAddress()} after minting and funding AMM: token0=${newT0Bal}, token1=${newT1Bal}, lp=${newLPBal}`);
266
+ }
267
+ async registerOrDeployContract(name, deploy, deployOpts) {
268
+ const address = (await deploy.getInstance(deployOpts)).address;
269
+ if ((await this.pxe.getContractMetadata(address)).isContractPublished) {
270
+ this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
271
+ return deploy.register();
272
+ } else {
273
+ this.log.info(`Deploying contract ${name} at ${address.toString()}`);
274
+ const sentTx = deploy.send(deployOpts);
275
+ const txHash = await sentTx.getTxHash();
276
+ this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
277
+ return this.withNoMinTxsPerBlock(()=>sentTx.deployed({
278
+ timeout: this.config.txMinedWaitSeconds
279
+ }));
154
280
  }
155
281
  }
156
282
  /**
157
283
  * Mints private and public tokens for the sender if their balance is below the minimum.
158
284
  * @param token - Token contract.
159
- */ async mintTokens(token) {
160
- const sender = token.wallet.getAddress();
285
+ */ async mintTokens(token, minter) {
161
286
  const isStandardToken = isStandardTokenContract(token);
162
287
  let privateBalance = 0n;
163
288
  let publicBalance = 0n;
164
289
  if (isStandardToken) {
165
- ({ privateBalance, publicBalance } = await getBalances(token, sender));
290
+ ({ privateBalance, publicBalance } = await getBalances(token, minter));
166
291
  } else {
167
- privateBalance = await getPrivateBalance(token, sender);
292
+ privateBalance = await getPrivateBalance(token, minter);
168
293
  }
169
294
  const calls = [];
170
295
  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());
296
+ this.log.info(`Minting private tokens for ${minter.toString()}`);
297
+ calls.push(isStandardToken ? token.methods.mint_to_private(minter, MINT_BALANCE) : token.methods.mint(MINT_BALANCE, minter));
174
298
  }
175
299
  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());
300
+ this.log.info(`Minting public tokens for ${minter.toString()}`);
301
+ calls.push(token.methods.mint_to_public(minter, MINT_BALANCE));
178
302
  }
179
303
  if (calls.length === 0) {
180
- this.log.info(`Skipping minting as ${sender.toString()} has enough tokens`);
304
+ this.log.info(`Skipping minting as ${minter.toString()} has enough tokens`);
181
305
  return;
182
306
  }
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
307
+ const sentTx = new BatchCall(token.wallet, calls).send({
308
+ from: minter
190
309
  });
310
+ const txHash = await sentTx.getTxHash();
311
+ this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
312
+ await this.withNoMinTxsPerBlock(()=>sentTx.wait({
313
+ timeout: this.config.txMinedWaitSeconds
314
+ }));
191
315
  }
192
- async bridgeL1FeeJuice(recipient, amount) {
316
+ async bridgeL1FeeJuice(recipient) {
193
317
  const l1RpcUrls = this.config.l1RpcUrls;
194
318
  if (!l1RpcUrls?.length) {
195
319
  throw new Error('L1 Rpc url is required to bridge the fee juice to fund the deployment of the account.');
196
320
  }
197
- const mnemonicOrPrivateKey = this.config.l1PrivateKey || this.config.l1Mnemonic;
321
+ const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
198
322
  if (!mnemonicOrPrivateKey) {
199
323
  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
324
  }
201
325
  const { l1ChainId } = await this.pxe.getNodeInfo();
202
326
  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();
327
+ const extendedClient = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
328
+ const portal = await L1FeeJuicePortalManager.new(this.pxe, extendedClient, this.log);
329
+ const mintAmount = await portal.getTokenManager().getMintAmount();
330
+ const claim = await portal.bridgeTokensPublic(recipient, mintAmount, true);
331
+ await this.withNoMinTxsPerBlock(()=>waitForL1ToL2MessageReady(this.pxe, Fr.fromHexString(claim.messageHash), {
332
+ timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
333
+ forPublicConsumption: false
334
+ }));
335
+ this.log.info(`Created a claim for ${mintAmount} L1 fee juice to ${recipient}.`, claim);
212
336
  return claim;
213
337
  }
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}`);
226
- }
338
+ async withNoMinTxsPerBlock(fn) {
339
+ if (!this.nodeAdmin || !this.config.flushSetupTransactions) {
340
+ return fn();
341
+ }
342
+ const { minTxsPerBlock } = await this.nodeAdmin.getConfig();
343
+ await this.nodeAdmin.setConfig({
344
+ minTxsPerBlock: 0
345
+ });
346
+ try {
347
+ return await fn();
348
+ } finally{
349
+ await this.nodeAdmin.setConfig({
350
+ minTxsPerBlock
351
+ });
227
352
  }
228
353
  }
229
354
  }
package/dest/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export { Bot } from './bot.js';
2
+ export { AmmBot } from './amm_bot.js';
2
3
  export { BotRunner } from './runner.js';
3
4
  export { type BotConfig, getBotConfigFromEnv, getBotDefaultConfig, botConfigMappings, SupportedTokenContracts, } from './config.js';
4
- export { createBotRunnerRpcServer, getBotRunnerApiHandler } from './rpc.js';
5
+ export { getBotRunnerApiHandler } from './rpc.js';
5
6
  export * from './interface.js';
6
7
  //# sourceMappingURL=index.d.ts.map
@@ -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,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EACL,KAAK,SAAS,EACd,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAC5E,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,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,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
+ export { AmmBot } from './amm_bot.js';
2
3
  export { BotRunner } from './runner.js';
3
4
  export { getBotConfigFromEnv, getBotDefaultConfig, botConfigMappings, SupportedTokenContracts } from './config.js';
4
- export { createBotRunnerRpcServer, getBotRunnerApiHandler } from './rpc.js';
5
+ export { getBotRunnerApiHandler } from './rpc.js';
5
6
  export * from './interface.js';
@@ -1,11 +1,22 @@
1
+ import { AztecAddress } from '@aztec/aztec.js';
1
2
  import type { ApiSchemaFor } from '@aztec/stdlib/schemas';
3
+ import { z } from 'zod';
2
4
  import { type BotConfig } from './config.js';
5
+ export declare const BotInfoSchema: z.ZodObject<{
6
+ botAddress: import("@aztec/stdlib/schemas").ZodFor<AztecAddress>;
7
+ }, "strip", z.ZodTypeAny, {
8
+ botAddress: AztecAddress;
9
+ }, {
10
+ botAddress?: any;
11
+ }>;
12
+ export type BotInfo = z.infer<typeof BotInfoSchema>;
3
13
  export interface BotRunnerApi {
4
14
  start(): Promise<void>;
5
15
  stop(): Promise<void>;
6
16
  run(): Promise<void>;
7
17
  setup(): Promise<void>;
8
18
  getConfig(): Promise<BotConfig>;
19
+ getInfo(): Promise<BotInfo>;
9
20
  update(config: BotConfig): Promise<void>;
10
21
  }
11
22
  export declare const BotRunnerApiSchema: ApiSchemaFor<BotRunnerApi>;