@aztec/bot 0.0.1-commit.1142ef1 → 0.0.1-commit.11bf3dd6e
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/amm_bot.d.ts +6 -7
- package/dest/amm_bot.d.ts.map +1 -1
- package/dest/amm_bot.js +28 -17
- package/dest/base_bot.d.ts +7 -7
- package/dest/base_bot.d.ts.map +1 -1
- package/dest/base_bot.js +24 -35
- package/dest/bot.d.ts +6 -6
- package/dest/bot.d.ts.map +1 -1
- package/dest/bot.js +9 -9
- package/dest/config.d.ts +34 -18
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +39 -12
- package/dest/cross_chain_bot.d.ts +54 -0
- package/dest/cross_chain_bot.d.ts.map +1 -0
- package/dest/cross_chain_bot.js +134 -0
- package/dest/factory.d.ts +25 -10
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +346 -100
- package/dest/index.d.ts +2 -1
- package/dest/index.d.ts.map +1 -1
- package/dest/index.js +1 -0
- package/dest/l1_to_l2_seeding.d.ts +8 -0
- package/dest/l1_to_l2_seeding.d.ts.map +1 -0
- package/dest/l1_to_l2_seeding.js +63 -0
- package/dest/runner.d.ts +3 -3
- package/dest/runner.d.ts.map +1 -1
- package/dest/runner.js +17 -1
- package/dest/store/bot_store.d.ts +31 -6
- package/dest/store/bot_store.d.ts.map +1 -1
- package/dest/store/bot_store.js +37 -6
- package/dest/store/index.d.ts +2 -2
- package/dest/store/index.d.ts.map +1 -1
- package/dest/utils.js +3 -3
- package/package.json +17 -14
- package/src/amm_bot.ts +27 -22
- package/src/base_bot.ts +18 -40
- package/src/bot.ts +11 -12
- package/src/config.ts +44 -16
- package/src/cross_chain_bot.ts +203 -0
- package/src/factory.ts +383 -82
- package/src/index.ts +1 -0
- package/src/l1_to_l2_seeding.ts +79 -0
- package/src/runner.ts +18 -5
- package/src/store/bot_store.ts +60 -5
- package/src/store/index.ts +1 -1
- package/src/utils.ts +3 -3
package/src/factory.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { SchnorrAccountContract } from '@aztec/accounts/schnorr';
|
|
2
1
|
import { getInitialTestAccountsData } from '@aztec/accounts/testing';
|
|
2
|
+
import { NO_FROM } from '@aztec/aztec.js/account';
|
|
3
3
|
import { AztecAddress } from '@aztec/aztec.js/addresses';
|
|
4
4
|
import {
|
|
5
5
|
BatchCall,
|
|
@@ -7,64 +7,80 @@ import {
|
|
|
7
7
|
ContractFunctionInteraction,
|
|
8
8
|
type DeployMethod,
|
|
9
9
|
type DeployOptions,
|
|
10
|
+
NO_WAIT,
|
|
10
11
|
} from '@aztec/aztec.js/contracts';
|
|
11
|
-
import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
|
|
12
12
|
import type { L2AmountClaim } from '@aztec/aztec.js/ethereum';
|
|
13
|
+
import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
|
|
13
14
|
import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
|
|
14
15
|
import { deriveKeys } from '@aztec/aztec.js/keys';
|
|
15
16
|
import { createLogger } from '@aztec/aztec.js/log';
|
|
16
17
|
import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
|
|
18
|
+
import { waitForTx } from '@aztec/aztec.js/node';
|
|
19
|
+
import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
|
|
20
|
+
import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
|
|
17
21
|
import { createEthereumChain } from '@aztec/ethereum/chain';
|
|
18
22
|
import { createExtendedL1Client } from '@aztec/ethereum/client';
|
|
23
|
+
import { RollupContract } from '@aztec/ethereum/contracts';
|
|
24
|
+
import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
|
|
19
25
|
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
26
|
+
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
20
27
|
import { Timer } from '@aztec/foundation/timer';
|
|
21
28
|
import { AMMContract } from '@aztec/noir-contracts.js/AMM';
|
|
22
29
|
import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
|
|
23
30
|
import { TokenContract } from '@aztec/noir-contracts.js/Token';
|
|
31
|
+
import { TestContract } from '@aztec/noir-test-contracts.js/Test';
|
|
24
32
|
import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
|
|
25
|
-
import { GasSettings } from '@aztec/stdlib/gas';
|
|
33
|
+
import { GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
|
|
26
34
|
import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
|
|
27
35
|
import { deriveSigningKey } from '@aztec/stdlib/keys';
|
|
28
|
-
import {
|
|
36
|
+
import { EmbeddedWallet } from '@aztec/wallets/embedded';
|
|
29
37
|
|
|
30
38
|
import { type BotConfig, SupportedTokenContracts } from './config.js';
|
|
39
|
+
import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
|
|
31
40
|
import type { BotStore } from './store/index.js';
|
|
32
41
|
import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
|
|
33
42
|
|
|
34
43
|
const MINT_BALANCE = 1e12;
|
|
35
44
|
const MIN_BALANCE = 1e3;
|
|
45
|
+
const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
|
|
46
|
+
const FEE_JUICE_TOP_UP_TARGET = 10_000n * 10n ** 18n;
|
|
36
47
|
|
|
37
48
|
export class BotFactory {
|
|
38
49
|
private log = createLogger('bot');
|
|
39
50
|
|
|
40
51
|
constructor(
|
|
41
52
|
private readonly config: BotConfig,
|
|
42
|
-
private readonly wallet:
|
|
53
|
+
private readonly wallet: EmbeddedWallet,
|
|
43
54
|
private readonly store: BotStore,
|
|
44
55
|
private readonly aztecNode: AztecNode,
|
|
45
56
|
private readonly aztecNodeAdmin?: AztecNodeAdmin,
|
|
46
|
-
) {
|
|
57
|
+
) {
|
|
58
|
+
// Set fee padding on the wallet so that all transactions during setup
|
|
59
|
+
// (token deploy, minting, etc.) use the configured padding, not the default.
|
|
60
|
+
this.wallet.setMinFeePadding(config.minFeePadding);
|
|
61
|
+
}
|
|
47
62
|
|
|
48
63
|
/**
|
|
49
64
|
* Initializes a new bot by setting up the sender account, registering the recipient,
|
|
50
65
|
* deploying the token contract, and minting tokens if necessary.
|
|
51
66
|
*/
|
|
52
67
|
public async setup(): Promise<{
|
|
53
|
-
wallet:
|
|
68
|
+
wallet: EmbeddedWallet;
|
|
54
69
|
defaultAccountAddress: AztecAddress;
|
|
55
70
|
token: TokenContract | PrivateTokenContract;
|
|
56
71
|
node: AztecNode;
|
|
57
72
|
recipient: AztecAddress;
|
|
58
73
|
}> {
|
|
59
|
-
const recipient = (await this.wallet.createAccount()).address;
|
|
60
74
|
const defaultAccountAddress = await this.setupAccount();
|
|
61
|
-
const
|
|
75
|
+
const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
|
|
76
|
+
const token = await this.setupTokenWithOptionalEarlyRefuel(defaultAccountAddress);
|
|
77
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress, token);
|
|
62
78
|
await this.mintTokens(token, defaultAccountAddress);
|
|
63
79
|
return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
|
|
64
80
|
}
|
|
65
81
|
|
|
66
82
|
public async setupAmm(): Promise<{
|
|
67
|
-
wallet:
|
|
83
|
+
wallet: EmbeddedWallet;
|
|
68
84
|
defaultAccountAddress: AztecAddress;
|
|
69
85
|
amm: AMMContract;
|
|
70
86
|
token0: TokenContract;
|
|
@@ -72,7 +88,13 @@ export class BotFactory {
|
|
|
72
88
|
node: AztecNode;
|
|
73
89
|
}> {
|
|
74
90
|
const defaultAccountAddress = await this.setupAccount();
|
|
75
|
-
const token0 = await this.
|
|
91
|
+
const token0 = await this.setupTokenContractWithOptionalEarlyRefuel(
|
|
92
|
+
defaultAccountAddress,
|
|
93
|
+
this.config.tokenSalt,
|
|
94
|
+
'BotToken0',
|
|
95
|
+
'BOT0',
|
|
96
|
+
);
|
|
97
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress, token0);
|
|
76
98
|
const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
|
|
77
99
|
const liquidityToken = await this.setupTokenContract(
|
|
78
100
|
defaultAccountAddress,
|
|
@@ -94,6 +116,89 @@ export class BotFactory {
|
|
|
94
116
|
return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
|
|
95
117
|
}
|
|
96
118
|
|
|
119
|
+
/**
|
|
120
|
+
* Initializes the cross-chain bot by deploying TestContract, creating an L1 client,
|
|
121
|
+
* seeding initial L1→L2 messages, and waiting for the first to be ready.
|
|
122
|
+
*/
|
|
123
|
+
public async setupCrossChain(): Promise<{
|
|
124
|
+
wallet: EmbeddedWallet;
|
|
125
|
+
defaultAccountAddress: AztecAddress;
|
|
126
|
+
contract: TestContract;
|
|
127
|
+
node: AztecNode;
|
|
128
|
+
l1Client: ExtendedViemWalletClient;
|
|
129
|
+
rollupVersion: bigint;
|
|
130
|
+
}> {
|
|
131
|
+
const defaultAccountAddress = await this.setupAccount();
|
|
132
|
+
|
|
133
|
+
// Create L1 client (same pattern as bridgeL1FeeJuice)
|
|
134
|
+
const l1RpcUrls = this.config.l1RpcUrls;
|
|
135
|
+
if (!l1RpcUrls?.length) {
|
|
136
|
+
throw new Error('L1 RPC URLs required for cross-chain bot');
|
|
137
|
+
}
|
|
138
|
+
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
139
|
+
if (!mnemonicOrPrivateKey) {
|
|
140
|
+
throw new Error('L1 mnemonic or private key required for cross-chain bot');
|
|
141
|
+
}
|
|
142
|
+
const { l1ChainId, l1ContractAddresses } = await this.aztecNode.getNodeInfo();
|
|
143
|
+
const chain = createEthereumChain(l1RpcUrls, l1ChainId);
|
|
144
|
+
const l1Client = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
|
|
145
|
+
|
|
146
|
+
// Fetch Rollup version (needed for Inbox L2Actor struct)
|
|
147
|
+
const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
|
|
148
|
+
const rollupVersion = await rollupContract.getVersion();
|
|
149
|
+
|
|
150
|
+
// Deploy TestContract
|
|
151
|
+
const contract = await this.setupTestContract(defaultAccountAddress);
|
|
152
|
+
|
|
153
|
+
// Recover any pending messages from store (clean up stale ones first)
|
|
154
|
+
await this.store.cleanupOldPendingMessages();
|
|
155
|
+
const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
156
|
+
|
|
157
|
+
// Seed initial L1→L2 messages if pipeline is empty
|
|
158
|
+
const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
|
|
159
|
+
for (let i = 0; i < seedCount; i++) {
|
|
160
|
+
await seedL1ToL2Message(
|
|
161
|
+
l1Client,
|
|
162
|
+
EthAddress.fromString(l1ContractAddresses.inboxAddress.toString()),
|
|
163
|
+
contract.address,
|
|
164
|
+
rollupVersion,
|
|
165
|
+
this.store,
|
|
166
|
+
this.log,
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Block until at least one message is ready
|
|
171
|
+
const allMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
172
|
+
if (allMessages.length > 0) {
|
|
173
|
+
this.log.info(`Waiting for first L1→L2 message to be ready...`);
|
|
174
|
+
const firstMsg = allMessages[0];
|
|
175
|
+
await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
|
|
176
|
+
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
177
|
+
});
|
|
178
|
+
this.log.info(`First L1→L2 message is ready`);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
wallet: this.wallet,
|
|
183
|
+
defaultAccountAddress,
|
|
184
|
+
contract,
|
|
185
|
+
node: this.aztecNode,
|
|
186
|
+
l1Client,
|
|
187
|
+
rollupVersion,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
private async setupTestContract(deployer: AztecAddress): Promise<TestContract> {
|
|
192
|
+
const deployOpts: DeployOptions = {
|
|
193
|
+
from: deployer,
|
|
194
|
+
contractAddressSalt: this.config.tokenSalt,
|
|
195
|
+
universalDeploy: true,
|
|
196
|
+
};
|
|
197
|
+
const deploy = TestContract.deploy(this.wallet);
|
|
198
|
+
const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
|
|
199
|
+
return TestContract.at(instance.address, this.wallet);
|
|
200
|
+
}
|
|
201
|
+
|
|
97
202
|
/**
|
|
98
203
|
* Checks if the sender account contract is initialized, and initializes it if necessary.
|
|
99
204
|
* @returns The sender wallet.
|
|
@@ -112,14 +217,9 @@ export class BotFactory {
|
|
|
112
217
|
private async setupAccountWithPrivateKey(secret: Fr) {
|
|
113
218
|
const salt = this.config.senderSalt ?? Fr.ONE;
|
|
114
219
|
const signingKey = deriveSigningKey(secret);
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
contract: new SchnorrAccountContract(signingKey!),
|
|
119
|
-
};
|
|
120
|
-
const accountManager = await this.wallet.createAccount(accountData);
|
|
121
|
-
const isInit = (await this.wallet.getContractMetadata(accountManager.address)).isContractInitialized;
|
|
122
|
-
if (isInit) {
|
|
220
|
+
const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
|
|
221
|
+
const metadata = await this.wallet.getContractMetadata(accountManager.address);
|
|
222
|
+
if (metadata.initializationStatus === ContractInitializationStatus.INITIALIZED) {
|
|
123
223
|
this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
|
|
124
224
|
const timer = new Timer();
|
|
125
225
|
const address = accountManager.address;
|
|
@@ -134,12 +234,16 @@ export class BotFactory {
|
|
|
134
234
|
|
|
135
235
|
const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
|
|
136
236
|
const deployMethod = await accountManager.getDeployMethod();
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
237
|
+
|
|
238
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
239
|
+
const { txHash } = await deployMethod.send({
|
|
240
|
+
from: NO_FROM,
|
|
241
|
+
fee: { paymentMethod },
|
|
242
|
+
wait: NO_WAIT,
|
|
243
|
+
});
|
|
244
|
+
this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
|
|
245
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
246
|
+
});
|
|
143
247
|
this.log.info(`Account deployed at ${address}`);
|
|
144
248
|
|
|
145
249
|
// Clean up the consumed bridge claim
|
|
@@ -151,30 +255,97 @@ export class BotFactory {
|
|
|
151
255
|
|
|
152
256
|
private async setupTestAccount() {
|
|
153
257
|
const [initialAccountData] = await getInitialTestAccountsData();
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
const accountManager = await this.wallet.createAccount(accountData);
|
|
258
|
+
const accountManager = await this.wallet.createSchnorrAccount(
|
|
259
|
+
initialAccountData.secret,
|
|
260
|
+
initialAccountData.salt,
|
|
261
|
+
initialAccountData.signingKey,
|
|
262
|
+
);
|
|
160
263
|
return accountManager.address;
|
|
161
264
|
}
|
|
162
265
|
|
|
266
|
+
/**
|
|
267
|
+
* Setup token and refuel first: if the token already exists (restart scenario),
|
|
268
|
+
* run ensureFeeJuiceBalance before any step that might need fee juice. When deploying,
|
|
269
|
+
* use a bridge claim if balance is below threshold.
|
|
270
|
+
*/
|
|
271
|
+
private async setupTokenWithOptionalEarlyRefuel(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
|
|
272
|
+
const token = await this.getTokenInstance(sender);
|
|
273
|
+
const address = token.address;
|
|
274
|
+
const metadata = await this.wallet.getContractMetadata(address);
|
|
275
|
+
if (metadata.isContractPublished) {
|
|
276
|
+
this.log.info(`Token at ${address.toString()} already deployed, refueling before setup`);
|
|
277
|
+
await this.ensureFeeJuiceBalance(sender, token);
|
|
278
|
+
}
|
|
279
|
+
return this.setupToken(sender);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Setup token0 for AMM with refuel-first behaviour when token already exists.
|
|
284
|
+
*/
|
|
285
|
+
private async setupTokenContractWithOptionalEarlyRefuel(
|
|
286
|
+
deployer: AztecAddress,
|
|
287
|
+
contractAddressSalt: Fr,
|
|
288
|
+
name: string,
|
|
289
|
+
ticker: string,
|
|
290
|
+
decimals = 18,
|
|
291
|
+
): Promise<TokenContract> {
|
|
292
|
+
const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
|
|
293
|
+
const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
|
|
294
|
+
const instance = await deploy.getInstance(deployOpts);
|
|
295
|
+
const metadata = await this.wallet.getContractMetadata(instance.address);
|
|
296
|
+
if (metadata.isContractPublished) {
|
|
297
|
+
this.log.info(`Token ${name} at ${instance.address.toString()} already deployed, refueling before setup`);
|
|
298
|
+
const token = TokenContract.at(instance.address, this.wallet);
|
|
299
|
+
await this.ensureFeeJuiceBalance(deployer, token);
|
|
300
|
+
}
|
|
301
|
+
return this.setupTokenContract(deployer, contractAddressSalt, name, ticker, decimals);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
private async getTokenInstance(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
|
|
305
|
+
const deployOpts: DeployOptions = {
|
|
306
|
+
from: sender,
|
|
307
|
+
contractAddressSalt: this.config.tokenSalt,
|
|
308
|
+
universalDeploy: true,
|
|
309
|
+
};
|
|
310
|
+
if (this.config.contract === SupportedTokenContracts.TokenContract) {
|
|
311
|
+
const deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
|
|
312
|
+
const instance = await deploy.getInstance(deployOpts);
|
|
313
|
+
return TokenContract.at(instance.address, this.wallet);
|
|
314
|
+
}
|
|
315
|
+
if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
|
|
316
|
+
const tokenSecretKey = Fr.random();
|
|
317
|
+
const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
|
|
318
|
+
const deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
|
|
319
|
+
const instance = await deploy.getInstance({
|
|
320
|
+
...deployOpts,
|
|
321
|
+
skipInstancePublication: true,
|
|
322
|
+
skipClassPublication: true,
|
|
323
|
+
skipInitialization: false,
|
|
324
|
+
});
|
|
325
|
+
return PrivateTokenContract.at(instance.address, this.wallet);
|
|
326
|
+
}
|
|
327
|
+
throw new Error(`Unsupported token contract type: ${this.config.contract}`);
|
|
328
|
+
}
|
|
329
|
+
|
|
163
330
|
/**
|
|
164
331
|
* Checks if the token contract is deployed and deploys it if necessary.
|
|
165
|
-
*
|
|
166
|
-
* @
|
|
332
|
+
* Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
|
|
333
|
+
* @param sender - Aztec address to deploy the token contract from.
|
|
334
|
+
* @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
|
|
335
|
+
* @returns The TokenContract or PrivateTokenContract instance.
|
|
167
336
|
*/
|
|
168
337
|
private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
|
|
169
338
|
let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
|
|
170
|
-
let tokenInstance: ContractInstanceWithAddress | undefined;
|
|
171
339
|
const deployOpts: DeployOptions = {
|
|
172
340
|
from: sender,
|
|
173
341
|
contractAddressSalt: this.config.tokenSalt,
|
|
174
342
|
universalDeploy: true,
|
|
175
343
|
};
|
|
344
|
+
let token: TokenContract | PrivateTokenContract;
|
|
176
345
|
if (this.config.contract === SupportedTokenContracts.TokenContract) {
|
|
177
346
|
deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
|
|
347
|
+
const instance = await deploy.getInstance(deployOpts);
|
|
348
|
+
token = TokenContract.at(instance.address, this.wallet);
|
|
178
349
|
} else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
|
|
179
350
|
// Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
|
|
180
351
|
const tokenSecretKey = Fr.random();
|
|
@@ -185,23 +356,17 @@ export class BotFactory {
|
|
|
185
356
|
deployOpts.skipInitialization = false;
|
|
186
357
|
|
|
187
358
|
// Register the contract with the secret key before deployment
|
|
188
|
-
tokenInstance = await deploy.getInstance(deployOpts);
|
|
359
|
+
const tokenInstance = await deploy.getInstance(deployOpts);
|
|
360
|
+
token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
|
|
189
361
|
await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
|
|
362
|
+
// The contract constructor initializes private storage vars that need the contract's own nullifier key.
|
|
363
|
+
deployOpts.additionalScopes = [tokenInstance.address];
|
|
190
364
|
} else {
|
|
191
365
|
throw new Error(`Unsupported token contract type: ${this.config.contract}`);
|
|
192
366
|
}
|
|
193
367
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
this.log.info(`Token at ${address.toString()} already deployed`);
|
|
197
|
-
return deploy.register();
|
|
198
|
-
} else {
|
|
199
|
-
this.log.info(`Deploying token contract at ${address.toString()}`);
|
|
200
|
-
const sentTx = deploy.send(deployOpts);
|
|
201
|
-
const txHash = await sentTx.getTxHash();
|
|
202
|
-
this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
|
|
203
|
-
return this.withNoMinTxsPerBlock(() => sentTx.deployed({ timeout: this.config.txMinedWaitSeconds }));
|
|
204
|
-
}
|
|
368
|
+
await this.registerOrDeployContract('token', deploy, deployOpts);
|
|
369
|
+
return token;
|
|
205
370
|
}
|
|
206
371
|
|
|
207
372
|
/**
|
|
@@ -209,7 +374,7 @@ export class BotFactory {
|
|
|
209
374
|
* @param wallet - Wallet to deploy the token contract from.
|
|
210
375
|
* @returns The TokenContract instance.
|
|
211
376
|
*/
|
|
212
|
-
private setupTokenContract(
|
|
377
|
+
private async setupTokenContract(
|
|
213
378
|
deployer: AztecAddress,
|
|
214
379
|
contractAddressSalt: Fr,
|
|
215
380
|
name: string,
|
|
@@ -218,7 +383,8 @@ export class BotFactory {
|
|
|
218
383
|
): Promise<TokenContract> {
|
|
219
384
|
const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
|
|
220
385
|
const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
|
|
221
|
-
|
|
386
|
+
const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
|
|
387
|
+
return TokenContract.at(instance.address, this.wallet);
|
|
222
388
|
}
|
|
223
389
|
|
|
224
390
|
private async setupAmmContract(
|
|
@@ -230,12 +396,16 @@ export class BotFactory {
|
|
|
230
396
|
): Promise<AMMContract> {
|
|
231
397
|
const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
|
|
232
398
|
const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
|
|
233
|
-
const
|
|
399
|
+
const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
|
|
400
|
+
const amm = AMMContract.at(instance.address, this.wallet);
|
|
234
401
|
|
|
235
402
|
this.log.info(`AMM deployed at ${amm.address}`);
|
|
236
|
-
const
|
|
237
|
-
|
|
238
|
-
|
|
403
|
+
const setMinterInteraction = lpToken.methods.set_minter(amm.address, true);
|
|
404
|
+
const { receipt: minterReceipt } = await setMinterInteraction.send({
|
|
405
|
+
from: deployer,
|
|
406
|
+
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
407
|
+
});
|
|
408
|
+
this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
|
|
239
409
|
this.log.info(`Liquidity token initialized`);
|
|
240
410
|
|
|
241
411
|
return amm;
|
|
@@ -251,9 +421,18 @@ export class BotFactory {
|
|
|
251
421
|
): Promise<void> {
|
|
252
422
|
const getPrivateBalances = () =>
|
|
253
423
|
Promise.all([
|
|
254
|
-
token0.methods
|
|
255
|
-
|
|
256
|
-
|
|
424
|
+
token0.methods
|
|
425
|
+
.balance_of_private(liquidityProvider)
|
|
426
|
+
.simulate({ from: liquidityProvider })
|
|
427
|
+
.then(r => r.result),
|
|
428
|
+
token1.methods
|
|
429
|
+
.balance_of_private(liquidityProvider)
|
|
430
|
+
.simulate({ from: liquidityProvider })
|
|
431
|
+
.then(r => r.result),
|
|
432
|
+
lpToken.methods
|
|
433
|
+
.balance_of_private(liquidityProvider)
|
|
434
|
+
.simulate({ from: liquidityProvider })
|
|
435
|
+
.then(r => r.result),
|
|
257
436
|
]);
|
|
258
437
|
|
|
259
438
|
const authwitNonce = Fr.random();
|
|
@@ -294,23 +473,31 @@ export class BotFactory {
|
|
|
294
473
|
.getFunctionCall(),
|
|
295
474
|
});
|
|
296
475
|
|
|
297
|
-
const
|
|
476
|
+
const mintBatch = new BatchCall(this.wallet, [
|
|
298
477
|
token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
|
|
299
478
|
token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
|
|
300
|
-
])
|
|
479
|
+
]);
|
|
480
|
+
const { receipt: mintReceipt } = await mintBatch.send({
|
|
481
|
+
from: liquidityProvider,
|
|
482
|
+
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
483
|
+
});
|
|
301
484
|
|
|
302
|
-
this.log.info(`Sent mint tx: ${
|
|
303
|
-
await mintTx.wait({ timeout: this.config.txMinedWaitSeconds });
|
|
485
|
+
this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
|
|
304
486
|
|
|
305
|
-
const
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
487
|
+
const addLiquidityInteraction = amm.methods.add_liquidity(
|
|
488
|
+
amount0Max,
|
|
489
|
+
amount1Max,
|
|
490
|
+
amount0Min,
|
|
491
|
+
amount1Min,
|
|
492
|
+
authwitNonce,
|
|
493
|
+
);
|
|
494
|
+
const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
|
|
495
|
+
from: liquidityProvider,
|
|
496
|
+
authWitnesses: [token0Authwit, token1Authwit],
|
|
497
|
+
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
498
|
+
});
|
|
311
499
|
|
|
312
|
-
this.log.info(`Sent tx to add liquidity to the AMM: ${
|
|
313
|
-
await addLiquidityTx.wait({ timeout: this.config.txMinedWaitSeconds });
|
|
500
|
+
this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`);
|
|
314
501
|
this.log.info(`Liquidity added`);
|
|
315
502
|
|
|
316
503
|
const [newT0Bal, newT1Bal, newLPBal] = await getPrivateBalances();
|
|
@@ -323,24 +510,118 @@ export class BotFactory {
|
|
|
323
510
|
name: string,
|
|
324
511
|
deploy: DeployMethod<T>,
|
|
325
512
|
deployOpts: DeployOptions,
|
|
326
|
-
): Promise<
|
|
327
|
-
const
|
|
328
|
-
|
|
513
|
+
): Promise<ContractInstanceWithAddress> {
|
|
514
|
+
const instance = await deploy.getInstance(deployOpts);
|
|
515
|
+
const address = instance.address;
|
|
516
|
+
const metadata = await this.wallet.getContractMetadata(address);
|
|
517
|
+
if (metadata.isContractPublished) {
|
|
329
518
|
this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
|
|
330
|
-
|
|
519
|
+
await deploy.register();
|
|
331
520
|
} else {
|
|
332
|
-
|
|
333
|
-
const
|
|
334
|
-
const
|
|
335
|
-
|
|
336
|
-
|
|
521
|
+
const sender = deployOpts.from === NO_FROM ? undefined : deployOpts.from;
|
|
522
|
+
const balance = sender ? await getFeeJuiceBalance(sender, this.aztecNode) : 0n;
|
|
523
|
+
const useClaim =
|
|
524
|
+
sender &&
|
|
525
|
+
balance < FEE_JUICE_TOP_UP_THRESHOLD &&
|
|
526
|
+
this.config.feePaymentMethod === 'fee_juice' &&
|
|
527
|
+
!!this.config.l1RpcUrls?.length;
|
|
528
|
+
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
529
|
+
|
|
530
|
+
if (useClaim && mnemonicOrPrivateKey) {
|
|
531
|
+
const claim = await this.getOrCreateBridgeClaim(sender!);
|
|
532
|
+
const paymentMethod = new FeeJuicePaymentMethodWithClaim(sender!, claim);
|
|
533
|
+
const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true, paymentMethod } });
|
|
534
|
+
const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
|
|
535
|
+
const gasSettings = GasSettings.from({
|
|
536
|
+
...estimatedGas!,
|
|
537
|
+
maxFeesPerGas,
|
|
538
|
+
maxPriorityFeesPerGas: GasFees.empty(),
|
|
539
|
+
});
|
|
540
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
541
|
+
const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings, paymentMethod }, wait: NO_WAIT });
|
|
542
|
+
this.log.info(
|
|
543
|
+
`Sent contract ${name} deploy tx ${txHash.toString()} (using bridge claim, balance was ${balance})`,
|
|
544
|
+
);
|
|
545
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
546
|
+
});
|
|
547
|
+
await this.store.deleteBridgeClaim(sender!);
|
|
548
|
+
} else {
|
|
549
|
+
const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true } });
|
|
550
|
+
this.log.info(`Deploying contract ${name} at ${address.toString()}`, { estimatedGas });
|
|
551
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
552
|
+
const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings: estimatedGas }, wait: NO_WAIT });
|
|
553
|
+
this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
|
|
554
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
555
|
+
});
|
|
556
|
+
}
|
|
337
557
|
}
|
|
558
|
+
return instance;
|
|
338
559
|
}
|
|
339
560
|
|
|
340
561
|
/**
|
|
341
562
|
* Mints private and public tokens for the sender if their balance is below the minimum.
|
|
342
563
|
* @param token - Token contract.
|
|
343
564
|
*/
|
|
565
|
+
/**
|
|
566
|
+
* Ensures the account has sufficient fee juice by bridging from L1 if balance is below threshold.
|
|
567
|
+
* Bridges repeatedly until balance reaches the target (10k FJ).
|
|
568
|
+
* Used on startup/restart to top up when the account has run out after previous runs.
|
|
569
|
+
*/
|
|
570
|
+
private async ensureFeeJuiceBalance(
|
|
571
|
+
account: AztecAddress,
|
|
572
|
+
token: TokenContract | PrivateTokenContract,
|
|
573
|
+
): Promise<void> {
|
|
574
|
+
const { feePaymentMethod, l1RpcUrls } = this.config;
|
|
575
|
+
if (feePaymentMethod !== 'fee_juice' || !l1RpcUrls?.length) {
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
579
|
+
if (!mnemonicOrPrivateKey) {
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
let balance = await getFeeJuiceBalance(account, this.aztecNode);
|
|
584
|
+
if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
|
|
585
|
+
this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
this.log.info(
|
|
590
|
+
`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1 until ${FEE_JUICE_TOP_UP_TARGET}`,
|
|
591
|
+
);
|
|
592
|
+
const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
|
|
593
|
+
const minimalInteraction = isStandardTokenContract(token)
|
|
594
|
+
? token.methods.transfer_in_public(account, account, 0n, 0)
|
|
595
|
+
: token.methods.transfer(0n, account, account);
|
|
596
|
+
|
|
597
|
+
while (balance < FEE_JUICE_TOP_UP_TARGET) {
|
|
598
|
+
const claim = await this.bridgeL1FeeJuice(account);
|
|
599
|
+
const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
|
|
600
|
+
const { estimatedGas } = await minimalInteraction.simulate({
|
|
601
|
+
from: account,
|
|
602
|
+
fee: { estimateGas: true, paymentMethod },
|
|
603
|
+
});
|
|
604
|
+
const gasSettings = GasSettings.from({
|
|
605
|
+
...estimatedGas!,
|
|
606
|
+
maxFeesPerGas,
|
|
607
|
+
maxPriorityFeesPerGas: GasFees.empty(),
|
|
608
|
+
});
|
|
609
|
+
|
|
610
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
611
|
+
const { txHash } = await minimalInteraction.send({
|
|
612
|
+
from: account,
|
|
613
|
+
fee: { gasSettings, paymentMethod },
|
|
614
|
+
wait: NO_WAIT,
|
|
615
|
+
});
|
|
616
|
+
this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
|
|
617
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
618
|
+
});
|
|
619
|
+
balance = await getFeeJuiceBalance(account, this.aztecNode);
|
|
620
|
+
this.log.info(`Fee juice balance after top-up: ${balance}`);
|
|
621
|
+
}
|
|
622
|
+
this.log.info(`Fee juice top-up complete for ${account.toString()}`);
|
|
623
|
+
}
|
|
624
|
+
|
|
344
625
|
private async mintTokens(token: TokenContract | PrivateTokenContract, minter: AztecAddress) {
|
|
345
626
|
const isStandardToken = isStandardTokenContract(token);
|
|
346
627
|
let privateBalance = 0n;
|
|
@@ -370,10 +651,19 @@ export class BotFactory {
|
|
|
370
651
|
this.log.info(`Skipping minting as ${minter.toString()} has enough tokens`);
|
|
371
652
|
return;
|
|
372
653
|
}
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
654
|
+
|
|
655
|
+
// PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
|
|
656
|
+
const additionalScopes = isStandardToken ? undefined : [token.address];
|
|
657
|
+
const mintBatch = new BatchCall(token.wallet, calls);
|
|
658
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
659
|
+
const { txHash } = await mintBatch.send({
|
|
660
|
+
from: minter,
|
|
661
|
+
additionalScopes,
|
|
662
|
+
wait: NO_WAIT,
|
|
663
|
+
});
|
|
664
|
+
this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
|
|
665
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
666
|
+
});
|
|
377
667
|
}
|
|
378
668
|
|
|
379
669
|
/**
|
|
@@ -393,7 +683,6 @@ export class BotFactory {
|
|
|
393
683
|
await this.withNoMinTxsPerBlock(() =>
|
|
394
684
|
waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
|
|
395
685
|
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
396
|
-
forPublicConsumption: false,
|
|
397
686
|
}),
|
|
398
687
|
);
|
|
399
688
|
return existingClaim.claim;
|
|
@@ -432,7 +721,6 @@ export class BotFactory {
|
|
|
432
721
|
await this.withNoMinTxsPerBlock(() =>
|
|
433
722
|
waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
|
|
434
723
|
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
435
|
-
forPublicConsumption: false,
|
|
436
724
|
}),
|
|
437
725
|
);
|
|
438
726
|
|
|
@@ -441,6 +729,19 @@ export class BotFactory {
|
|
|
441
729
|
return claim as L2AmountClaim;
|
|
442
730
|
}
|
|
443
731
|
|
|
732
|
+
/** Returns worst-case min fees across predicted slots, with fallback to current min fees. */
|
|
733
|
+
private async getMinFees(): Promise<GasFees> {
|
|
734
|
+
try {
|
|
735
|
+
const predicted = await this.aztecNode.getPredictedMinFees(ManaUsageEstimate.Limit);
|
|
736
|
+
if (predicted.length === 0) {
|
|
737
|
+
return this.aztecNode.getCurrentMinFees();
|
|
738
|
+
}
|
|
739
|
+
return predicted.reduce((worst, fees) => (fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst));
|
|
740
|
+
} catch {
|
|
741
|
+
return this.aztecNode.getCurrentMinFees();
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
444
745
|
private async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
|
|
445
746
|
if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
|
|
446
747
|
this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
|