@aztec/bot 0.0.1-commit.2f68f620 → 0.0.1-commit.321f6a9
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 +3 -2
- package/dest/amm_bot.d.ts.map +1 -1
- package/dest/amm_bot.js +2 -2
- package/dest/bot.d.ts +3 -2
- package/dest/bot.d.ts.map +1 -1
- package/dest/bot.js +2 -2
- package/dest/config.d.ts +1 -1
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +3 -3
- package/dest/cross_chain_bot.d.ts +5 -3
- package/dest/cross_chain_bot.d.ts.map +1 -1
- package/dest/cross_chain_bot.js +7 -6
- package/dest/factory.d.ts +16 -11
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +183 -285
- package/dest/runner.d.ts +3 -2
- package/dest/runner.d.ts.map +1 -1
- package/dest/runner.js +6 -4
- package/package.json +15 -15
- package/src/amm_bot.ts +3 -0
- package/src/bot.ts +3 -0
- package/src/config.ts +3 -2
- package/src/cross_chain_bot.ts +6 -2
- package/src/factory.ts +189 -315
- package/src/runner.ts +26 -3
package/src/factory.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { getInitialTestAccountsData } from '@aztec/accounts/testing';
|
|
2
|
-
import {
|
|
2
|
+
import { deriveSecretKeyFromSigningKey } from '@aztec/accounts/utils';
|
|
3
3
|
import { AztecAddress } from '@aztec/aztec.js/addresses';
|
|
4
4
|
import {
|
|
5
5
|
BatchCall,
|
|
@@ -17,22 +17,20 @@ import { createLogger } from '@aztec/aztec.js/log';
|
|
|
17
17
|
import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
|
|
18
18
|
import { waitForTx } from '@aztec/aztec.js/node';
|
|
19
19
|
import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
|
|
20
|
-
import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
|
|
21
20
|
import { createEthereumChain } from '@aztec/ethereum/chain';
|
|
22
21
|
import { createExtendedL1Client } from '@aztec/ethereum/client';
|
|
23
22
|
import { RollupContract } from '@aztec/ethereum/contracts';
|
|
24
23
|
import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
|
|
25
24
|
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
25
|
+
import { GrumpkinScalar } from '@aztec/foundation/curves/grumpkin';
|
|
26
26
|
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
27
|
-
import { Timer } from '@aztec/foundation/timer';
|
|
28
27
|
import { AMMContract } from '@aztec/noir-contracts.js/AMM';
|
|
29
28
|
import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
|
|
30
29
|
import { TokenContract } from '@aztec/noir-contracts.js/Token';
|
|
31
30
|
import { TestContract } from '@aztec/noir-test-contracts.js/Test';
|
|
31
|
+
import type { BlockTag } from '@aztec/stdlib/block';
|
|
32
32
|
import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
|
|
33
|
-
import { GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
|
|
34
33
|
import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
|
|
35
|
-
import { deriveSigningKey } from '@aztec/stdlib/keys';
|
|
36
34
|
import { EmbeddedWallet } from '@aztec/wallets/embedded';
|
|
37
35
|
|
|
38
36
|
import { type BotConfig, SupportedTokenContracts } from './config.js';
|
|
@@ -43,17 +41,22 @@ import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils
|
|
|
43
41
|
const MINT_BALANCE = 1e12;
|
|
44
42
|
const MIN_BALANCE = 1e3;
|
|
45
43
|
const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
|
|
46
|
-
const FEE_JUICE_TOP_UP_TARGET = 10_000n * 10n ** 18n;
|
|
47
44
|
|
|
48
45
|
export class BotFactory {
|
|
49
46
|
private log = createLogger('bot');
|
|
50
47
|
|
|
48
|
+
/** Number of in-flight withNoMinTxsPerBlock calls; see that method for why they are counted. */
|
|
49
|
+
private noMinTxsPerBlockDepth = 0;
|
|
50
|
+
/** Set by the first withNoMinTxsPerBlock entrant; resolves to the minTxsPerBlock value to restore. */
|
|
51
|
+
private savedMinTxsPerBlock?: Promise<{ minTxsPerBlock?: number }>;
|
|
52
|
+
|
|
51
53
|
constructor(
|
|
52
54
|
private readonly config: BotConfig,
|
|
53
55
|
private readonly wallet: EmbeddedWallet,
|
|
54
56
|
private readonly store: BotStore,
|
|
55
57
|
private readonly aztecNode: AztecNode,
|
|
56
58
|
private readonly aztecNodeAdmin?: AztecNodeAdmin,
|
|
59
|
+
private readonly syncChainTip?: BlockTag,
|
|
57
60
|
) {
|
|
58
61
|
// Set fee padding on the wallet so that all transactions during setup
|
|
59
62
|
// (token deploy, minting, etc.) use the configured padding, not the default.
|
|
@@ -72,9 +75,10 @@ export class BotFactory {
|
|
|
72
75
|
recipient: AztecAddress;
|
|
73
76
|
}> {
|
|
74
77
|
const defaultAccountAddress = await this.setupAccount();
|
|
75
|
-
const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random()))
|
|
76
|
-
|
|
77
|
-
await this.ensureFeeJuiceBalance(defaultAccountAddress
|
|
78
|
+
const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random(), GrumpkinScalar.random()))
|
|
79
|
+
.address;
|
|
80
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress);
|
|
81
|
+
const token = await this.setupToken(defaultAccountAddress);
|
|
78
82
|
await this.mintTokens(token, defaultAccountAddress);
|
|
79
83
|
return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
|
|
80
84
|
}
|
|
@@ -88,29 +92,36 @@ export class BotFactory {
|
|
|
88
92
|
node: AztecNode;
|
|
89
93
|
}> {
|
|
90
94
|
const defaultAccountAddress = await this.setupAccount();
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
'BotToken0',
|
|
95
|
-
'BOT0',
|
|
96
|
-
);
|
|
97
|
-
await this.ensureFeeJuiceBalance(defaultAccountAddress, token0);
|
|
98
|
-
const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
|
|
99
|
-
const liquidityToken = await this.setupTokenContract(
|
|
100
|
-
defaultAccountAddress,
|
|
101
|
-
this.config.tokenSalt,
|
|
102
|
-
'BotLPToken',
|
|
103
|
-
'BOTLP',
|
|
104
|
-
);
|
|
105
|
-
const amm = await this.setupAmmContract(
|
|
106
|
-
defaultAccountAddress,
|
|
107
|
-
this.config.tokenSalt,
|
|
108
|
-
token0,
|
|
109
|
-
token1,
|
|
110
|
-
liquidityToken,
|
|
111
|
-
);
|
|
95
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress);
|
|
96
|
+
|
|
97
|
+
const salt = this.config.tokenSalt;
|
|
112
98
|
|
|
113
|
-
|
|
99
|
+
// token0, token1 and the LP token are independent contracts with no shared state, so deploy them
|
|
100
|
+
// concurrently rather than one slot at a time.
|
|
101
|
+
const [token0, token1, liquidityToken] = await Promise.all([
|
|
102
|
+
this.setupTokenContract(defaultAccountAddress, salt, 'BotToken0', 'BOT0'),
|
|
103
|
+
this.setupTokenContract(defaultAccountAddress, salt, 'BotToken1', 'BOT1'),
|
|
104
|
+
this.setupTokenContract(defaultAccountAddress, salt, 'BotLPToken', 'BOTLP'),
|
|
105
|
+
]);
|
|
106
|
+
|
|
107
|
+
const ammDeploy = AMMContract.deploy(this.wallet, token0.address, token1.address, liquidityToken.address, {
|
|
108
|
+
salt,
|
|
109
|
+
universalDeploy: true,
|
|
110
|
+
});
|
|
111
|
+
const ammAddress = (await ammDeploy.getInstance()).address;
|
|
112
|
+
|
|
113
|
+
// The AMM constructor only stores the (already-derived) token addresses, and set_minter only records
|
|
114
|
+
// the AMM address on the LP token: neither reads the other's on-chain state, so the AMM deploy, the
|
|
115
|
+
// LP-minter grant, and the token0/token1 mints are mutually independent and run concurrently.
|
|
116
|
+
const [amm] = await Promise.all([
|
|
117
|
+
this.deployAmmContract(defaultAccountAddress, ammDeploy),
|
|
118
|
+
this.grantLpTokenMinter(defaultAccountAddress, liquidityToken, ammAddress),
|
|
119
|
+
this.mintAmmLiquidity(defaultAccountAddress, token0, token1),
|
|
120
|
+
]);
|
|
121
|
+
|
|
122
|
+
// add_liquidity spends the minted token0/token1 balances and mints LP tokens, so it must follow both
|
|
123
|
+
// the mints and the minter grant, and target the deployed AMM.
|
|
124
|
+
await this.addAmmLiquidity(defaultAccountAddress, defaultAccountAddress, amm, token0, token1, liquidityToken);
|
|
114
125
|
this.log.info(`AMM initialized and funded`);
|
|
115
126
|
|
|
116
127
|
return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
|
|
@@ -129,6 +140,7 @@ export class BotFactory {
|
|
|
129
140
|
rollupVersion: bigint;
|
|
130
141
|
}> {
|
|
131
142
|
const defaultAccountAddress = await this.setupAccount();
|
|
143
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress);
|
|
132
144
|
|
|
133
145
|
// Create L1 client (same pattern as bridgeL1FeeJuice)
|
|
134
146
|
const l1RpcUrls = this.config.l1RpcUrls;
|
|
@@ -147,25 +159,32 @@ export class BotFactory {
|
|
|
147
159
|
const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
|
|
148
160
|
const rollupVersion = await rollupContract.getVersion();
|
|
149
161
|
|
|
150
|
-
//
|
|
151
|
-
|
|
162
|
+
// Derive the TestContract address up front (deterministic from the salt). Seeding L1→L2 messages only
|
|
163
|
+
// needs the L2 recipient address — the messages are queued on L1 and don't require the L2 contract to
|
|
164
|
+
// exist yet (they're consumed later, after setup completes) — so the deploy (an L2 tx paying from the
|
|
165
|
+
// standing balance funded above) and the L1 seeding run concurrently.
|
|
166
|
+
const testContractDeploy = TestContract.deploy(this.wallet, {
|
|
167
|
+
salt: this.config.tokenSalt,
|
|
168
|
+
universalDeploy: true,
|
|
169
|
+
});
|
|
170
|
+
const contractAddress = (await testContractDeploy.getInstance()).address;
|
|
152
171
|
|
|
153
172
|
// Recover any pending messages from store (clean up stale ones first)
|
|
154
173
|
await this.store.cleanupOldPendingMessages();
|
|
155
174
|
const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
156
175
|
|
|
157
|
-
// Seed initial L1→L2 messages if pipeline is empty
|
|
176
|
+
// Seed initial L1→L2 messages if pipeline is empty. The seeds are sent one at a time: they share the
|
|
177
|
+
// bot's L1 account, so concurrent sends would race on the L1 nonce.
|
|
158
178
|
const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
}
|
|
179
|
+
const inboxAddress = EthAddress.fromString(l1ContractAddresses.inboxAddress.toString());
|
|
180
|
+
const [contract] = await Promise.all([
|
|
181
|
+
this.deployTestContract(defaultAccountAddress, testContractDeploy),
|
|
182
|
+
(async () => {
|
|
183
|
+
for (let i = 0; i < seedCount; i++) {
|
|
184
|
+
await seedL1ToL2Message(l1Client, inboxAddress, contractAddress, rollupVersion, this.store, this.log);
|
|
185
|
+
}
|
|
186
|
+
})(),
|
|
187
|
+
]);
|
|
169
188
|
|
|
170
189
|
// Block until at least one message is ready
|
|
171
190
|
const allMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
@@ -174,6 +193,7 @@ export class BotFactory {
|
|
|
174
193
|
const firstMsg = allMessages[0];
|
|
175
194
|
await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
|
|
176
195
|
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
196
|
+
chainTip: this.syncChainTip,
|
|
177
197
|
});
|
|
178
198
|
this.log.info(`First L1→L2 message is ready`);
|
|
179
199
|
}
|
|
@@ -188,10 +208,8 @@ export class BotFactory {
|
|
|
188
208
|
};
|
|
189
209
|
}
|
|
190
210
|
|
|
191
|
-
private async
|
|
192
|
-
const
|
|
193
|
-
const deploy = TestContract.deploy(this.wallet, { salt: this.config.tokenSalt, universalDeploy: true });
|
|
194
|
-
const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
|
|
211
|
+
private async deployTestContract(deployer: AztecAddress, deploy: DeployMethod<TestContract>): Promise<TestContract> {
|
|
212
|
+
const instance = await this.registerOrDeployContract('TestContract', deploy, { from: deployer });
|
|
195
213
|
return TestContract.at(instance.address, this.wallet);
|
|
196
214
|
}
|
|
197
215
|
|
|
@@ -210,48 +228,16 @@ export class BotFactory {
|
|
|
210
228
|
}
|
|
211
229
|
}
|
|
212
230
|
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
const timer = new Timer();
|
|
221
|
-
const address = accountManager.address;
|
|
222
|
-
this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
|
|
223
|
-
await this.store.deleteBridgeClaim(address);
|
|
224
|
-
return address;
|
|
225
|
-
} else {
|
|
226
|
-
const address = accountManager.address;
|
|
227
|
-
this.log.info(`Deploying account at ${address}`);
|
|
228
|
-
|
|
229
|
-
const claim = await this.getOrCreateBridgeClaim(address);
|
|
230
|
-
|
|
231
|
-
const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
|
|
232
|
-
const deployMethod = await accountManager.getDeployMethod();
|
|
233
|
-
|
|
234
|
-
await this.withNoMinTxsPerBlock(async () => {
|
|
235
|
-
const { txHash } = await deployMethod.send({
|
|
236
|
-
from: NO_FROM,
|
|
237
|
-
fee: { paymentMethod },
|
|
238
|
-
wait: NO_WAIT,
|
|
239
|
-
});
|
|
240
|
-
this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
|
|
241
|
-
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
242
|
-
});
|
|
243
|
-
this.log.info(`Account deployed at ${address}`);
|
|
244
|
-
|
|
245
|
-
// Clean up the consumed bridge claim
|
|
246
|
-
await this.store.deleteBridgeClaim(address);
|
|
247
|
-
|
|
248
|
-
return accountManager.address;
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
|
|
231
|
+
/**
|
|
232
|
+
* Keyless fallback for tests and local dev: reuses the first genesis test account, whose address is
|
|
233
|
+
* pre-funded with fee juice via `initialFundedAccounts`. The test accounts are initializerless, so this
|
|
234
|
+
* must create an initializerless account for the address to match the funded one. Production bots set a
|
|
235
|
+
* sender private key and fund the resulting initializerless account from L1 instead; see
|
|
236
|
+
* setupAccountWithPrivateKey.
|
|
237
|
+
*/
|
|
252
238
|
private async setupTestAccount() {
|
|
253
239
|
const [initialAccountData] = await getInitialTestAccountsData();
|
|
254
|
-
const accountManager = await this.wallet.
|
|
240
|
+
const accountManager = await this.wallet.createSchnorrInitializerlessAccount(
|
|
255
241
|
initialAccountData.secret,
|
|
256
242
|
initialAccountData.salt,
|
|
257
243
|
initialAccountData.signingKey,
|
|
@@ -259,62 +245,12 @@ export class BotFactory {
|
|
|
259
245
|
return accountManager.address;
|
|
260
246
|
}
|
|
261
247
|
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
const token = await this.getTokenInstance(sender);
|
|
269
|
-
const address = token.address;
|
|
270
|
-
const metadata = await this.wallet.getContractMetadata(address);
|
|
271
|
-
if (metadata.isContractPublished) {
|
|
272
|
-
this.log.info(`Token at ${address.toString()} already deployed, refueling before setup`);
|
|
273
|
-
await this.ensureFeeJuiceBalance(sender, token);
|
|
274
|
-
}
|
|
275
|
-
return this.setupToken(sender);
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/**
|
|
279
|
-
* Setup token0 for AMM with refuel-first behaviour when token already exists.
|
|
280
|
-
*/
|
|
281
|
-
private async setupTokenContractWithOptionalEarlyRefuel(
|
|
282
|
-
deployer: AztecAddress,
|
|
283
|
-
salt: Fr,
|
|
284
|
-
name: string,
|
|
285
|
-
ticker: string,
|
|
286
|
-
decimals = 18,
|
|
287
|
-
): Promise<TokenContract> {
|
|
288
|
-
const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
|
|
289
|
-
const instance = await deploy.getInstance();
|
|
290
|
-
const metadata = await this.wallet.getContractMetadata(instance.address);
|
|
291
|
-
if (metadata.isContractPublished) {
|
|
292
|
-
this.log.info(`Token ${name} at ${instance.address.toString()} already deployed, refueling before setup`);
|
|
293
|
-
const token = TokenContract.at(instance.address, this.wallet);
|
|
294
|
-
await this.ensureFeeJuiceBalance(deployer, token);
|
|
295
|
-
}
|
|
296
|
-
return this.setupTokenContract(deployer, salt, name, ticker, decimals);
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
private async getTokenInstance(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
|
|
300
|
-
const salt = this.config.tokenSalt;
|
|
301
|
-
if (this.config.contract === SupportedTokenContracts.TokenContract) {
|
|
302
|
-
const deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
|
|
303
|
-
const instance = await deploy.getInstance();
|
|
304
|
-
return TokenContract.at(instance.address, this.wallet);
|
|
305
|
-
}
|
|
306
|
-
if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
|
|
307
|
-
const tokenSecretKey = Fr.random();
|
|
308
|
-
const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
|
|
309
|
-
const deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
|
|
310
|
-
salt,
|
|
311
|
-
universalDeploy: true,
|
|
312
|
-
publicKeys: tokenPublicKeys,
|
|
313
|
-
});
|
|
314
|
-
const instance = await deploy.getInstance();
|
|
315
|
-
return PrivateTokenContract.at(instance.address, this.wallet);
|
|
316
|
-
}
|
|
317
|
-
throw new Error(`Unsupported token contract type: ${this.config.contract}`);
|
|
248
|
+
private async setupAccountWithPrivateKey(privateKey: Fr) {
|
|
249
|
+
const salt = this.config.senderSalt ?? Fr.ONE;
|
|
250
|
+
const signingKey = GrumpkinScalar.fromBuffer(privateKey.toBuffer());
|
|
251
|
+
const secret = await deriveSecretKeyFromSigningKey(signingKey);
|
|
252
|
+
const accountManager = await this.wallet.createSchnorrInitializerlessAccount(secret, salt, signingKey);
|
|
253
|
+
return accountManager.address;
|
|
318
254
|
}
|
|
319
255
|
|
|
320
256
|
/**
|
|
@@ -378,34 +314,37 @@ export class BotFactory {
|
|
|
378
314
|
return TokenContract.at(instance.address, this.wallet);
|
|
379
315
|
}
|
|
380
316
|
|
|
381
|
-
private async
|
|
382
|
-
|
|
383
|
-
salt: Fr,
|
|
384
|
-
token0: TokenContract,
|
|
385
|
-
token1: TokenContract,
|
|
386
|
-
lpToken: TokenContract,
|
|
387
|
-
): Promise<AMMContract> {
|
|
388
|
-
const deployOpts: DeployOptions = { from: deployer };
|
|
389
|
-
const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address, {
|
|
390
|
-
salt,
|
|
391
|
-
universalDeploy: true,
|
|
392
|
-
});
|
|
393
|
-
const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
|
|
317
|
+
private async deployAmmContract(deployer: AztecAddress, deploy: DeployMethod<AMMContract>): Promise<AMMContract> {
|
|
318
|
+
const instance = await this.registerOrDeployContract('AMM', deploy, { from: deployer });
|
|
394
319
|
const amm = AMMContract.at(instance.address, this.wallet);
|
|
395
|
-
|
|
396
320
|
this.log.info(`AMM deployed at ${amm.address}`);
|
|
397
|
-
|
|
398
|
-
|
|
321
|
+
return amm;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** Grants the AMM minting rights over the LP token. set_minter only records the address, so it does not
|
|
325
|
+
* require the AMM contract to be deployed first. */
|
|
326
|
+
private async grantLpTokenMinter(deployer: AztecAddress, lpToken: TokenContract, amm: AztecAddress): Promise<void> {
|
|
327
|
+
const { receipt } = await lpToken.methods.set_minter(amm, true).send({
|
|
399
328
|
from: deployer,
|
|
400
329
|
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
401
330
|
});
|
|
402
|
-
this.log.info(`Set LP token minter to AMM txHash=${
|
|
403
|
-
|
|
331
|
+
this.log.info(`Set LP token minter to AMM txHash=${receipt.txHash.toString()}`);
|
|
332
|
+
}
|
|
404
333
|
|
|
405
|
-
|
|
334
|
+
private async mintAmmLiquidity(minter: AztecAddress, token0: TokenContract, token1: TokenContract): Promise<void> {
|
|
335
|
+
this.log.info(`Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1 for ${minter}`);
|
|
336
|
+
const mintBatch = new BatchCall(this.wallet, [
|
|
337
|
+
token0.methods.mint_to_private(minter, MINT_BALANCE),
|
|
338
|
+
token1.methods.mint_to_private(minter, MINT_BALANCE),
|
|
339
|
+
]);
|
|
340
|
+
const { receipt } = await mintBatch.send({
|
|
341
|
+
from: minter,
|
|
342
|
+
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
343
|
+
});
|
|
344
|
+
this.log.info(`Sent mint tx: ${receipt.txHash.toString()}`);
|
|
406
345
|
}
|
|
407
346
|
|
|
408
|
-
private async
|
|
347
|
+
private async addAmmLiquidity(
|
|
409
348
|
defaultAccountAddress: AztecAddress,
|
|
410
349
|
liquidityProvider: AztecAddress,
|
|
411
350
|
amm: AMMContract,
|
|
@@ -413,22 +352,6 @@ export class BotFactory {
|
|
|
413
352
|
token1: TokenContract,
|
|
414
353
|
lpToken: TokenContract,
|
|
415
354
|
): Promise<void> {
|
|
416
|
-
const getPrivateBalances = () =>
|
|
417
|
-
Promise.all([
|
|
418
|
-
token0.methods
|
|
419
|
-
.balance_of_private(liquidityProvider)
|
|
420
|
-
.simulate({ from: liquidityProvider })
|
|
421
|
-
.then(r => r.result),
|
|
422
|
-
token1.methods
|
|
423
|
-
.balance_of_private(liquidityProvider)
|
|
424
|
-
.simulate({ from: liquidityProvider })
|
|
425
|
-
.then(r => r.result),
|
|
426
|
-
lpToken.methods
|
|
427
|
-
.balance_of_private(liquidityProvider)
|
|
428
|
-
.simulate({ from: liquidityProvider })
|
|
429
|
-
.then(r => r.result),
|
|
430
|
-
]);
|
|
431
|
-
|
|
432
355
|
const authwitNonce = Fr.random();
|
|
433
356
|
|
|
434
357
|
// keep some tokens for swapping
|
|
@@ -437,12 +360,6 @@ export class BotFactory {
|
|
|
437
360
|
const amount1Max = MINT_BALANCE / 2;
|
|
438
361
|
const amount1Min = MINT_BALANCE / 4;
|
|
439
362
|
|
|
440
|
-
const [t0Bal, t1Bal, lpBal] = await getPrivateBalances();
|
|
441
|
-
|
|
442
|
-
this.log.info(
|
|
443
|
-
`Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1. Current private balances of ${liquidityProvider}: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`,
|
|
444
|
-
);
|
|
445
|
-
|
|
446
363
|
// Add authwitnesses for the transfers in AMM::add_liquidity function
|
|
447
364
|
const token0Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
|
|
448
365
|
caller: amm.address,
|
|
@@ -467,36 +384,33 @@ export class BotFactory {
|
|
|
467
384
|
.getFunctionCall(),
|
|
468
385
|
});
|
|
469
386
|
|
|
470
|
-
const
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
});
|
|
478
|
-
|
|
479
|
-
this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
|
|
480
|
-
|
|
481
|
-
const addLiquidityInteraction = amm.methods.add_liquidity(
|
|
482
|
-
amount0Max,
|
|
483
|
-
amount1Max,
|
|
484
|
-
amount0Min,
|
|
485
|
-
amount1Min,
|
|
486
|
-
authwitNonce,
|
|
487
|
-
);
|
|
488
|
-
const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
|
|
489
|
-
from: liquidityProvider,
|
|
490
|
-
authWitnesses: [token0Authwit, token1Authwit],
|
|
491
|
-
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
492
|
-
});
|
|
387
|
+
const { receipt } = await amm.methods
|
|
388
|
+
.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce)
|
|
389
|
+
.send({
|
|
390
|
+
from: liquidityProvider,
|
|
391
|
+
authWitnesses: [token0Authwit, token1Authwit],
|
|
392
|
+
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
393
|
+
});
|
|
493
394
|
|
|
494
|
-
this.log.info(`Sent tx to add liquidity to the AMM: ${
|
|
395
|
+
this.log.info(`Sent tx to add liquidity to the AMM: ${receipt.txHash.toString()}`);
|
|
495
396
|
this.log.info(`Liquidity added`);
|
|
496
397
|
|
|
497
|
-
const [
|
|
398
|
+
const [t0Bal, t1Bal, lpBal] = await Promise.all([
|
|
399
|
+
token0.methods
|
|
400
|
+
.balance_of_private(liquidityProvider)
|
|
401
|
+
.simulate({ from: liquidityProvider })
|
|
402
|
+
.then(r => r.result),
|
|
403
|
+
token1.methods
|
|
404
|
+
.balance_of_private(liquidityProvider)
|
|
405
|
+
.simulate({ from: liquidityProvider })
|
|
406
|
+
.then(r => r.result),
|
|
407
|
+
lpToken.methods
|
|
408
|
+
.balance_of_private(liquidityProvider)
|
|
409
|
+
.simulate({ from: liquidityProvider })
|
|
410
|
+
.then(r => r.result),
|
|
411
|
+
]);
|
|
498
412
|
this.log.info(
|
|
499
|
-
`Updated private balances of ${defaultAccountAddress} after minting and funding AMM: token0=${
|
|
413
|
+
`Updated private balances of ${defaultAccountAddress} after minting and funding AMM: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`,
|
|
500
414
|
);
|
|
501
415
|
}
|
|
502
416
|
|
|
@@ -511,66 +425,39 @@ export class BotFactory {
|
|
|
511
425
|
if (metadata.isContractPublished) {
|
|
512
426
|
this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
|
|
513
427
|
await deploy.register();
|
|
514
|
-
|
|
515
|
-
const sender = deployOpts.from === NO_FROM ? undefined : deployOpts.from;
|
|
516
|
-
const balance = sender ? await getFeeJuiceBalance(sender, this.aztecNode) : 0n;
|
|
517
|
-
const useClaim =
|
|
518
|
-
sender &&
|
|
519
|
-
balance < FEE_JUICE_TOP_UP_THRESHOLD &&
|
|
520
|
-
this.config.feePaymentMethod === 'fee_juice' &&
|
|
521
|
-
!!this.config.l1RpcUrls?.length;
|
|
522
|
-
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
523
|
-
|
|
524
|
-
if (useClaim && mnemonicOrPrivateKey) {
|
|
525
|
-
const claim = await this.getOrCreateBridgeClaim(sender!);
|
|
526
|
-
const paymentMethod = new FeeJuicePaymentMethodWithClaim(sender!, claim);
|
|
527
|
-
const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true, paymentMethod } });
|
|
528
|
-
const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
|
|
529
|
-
const gasSettings = GasSettings.from({
|
|
530
|
-
...estimatedGas!,
|
|
531
|
-
maxFeesPerGas,
|
|
532
|
-
maxPriorityFeesPerGas: GasFees.empty(),
|
|
533
|
-
});
|
|
534
|
-
await this.withNoMinTxsPerBlock(async () => {
|
|
535
|
-
const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings, paymentMethod }, wait: NO_WAIT });
|
|
536
|
-
this.log.info(
|
|
537
|
-
`Sent contract ${name} deploy tx ${txHash.toString()} (using bridge claim, balance was ${balance})`,
|
|
538
|
-
);
|
|
539
|
-
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
540
|
-
});
|
|
541
|
-
await this.store.deleteBridgeClaim(sender!);
|
|
542
|
-
} else {
|
|
543
|
-
const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true } });
|
|
544
|
-
this.log.info(`Deploying contract ${name} at ${address.toString()}`, { estimatedGas });
|
|
545
|
-
await this.withNoMinTxsPerBlock(async () => {
|
|
546
|
-
const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings: estimatedGas }, wait: NO_WAIT });
|
|
547
|
-
this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
|
|
548
|
-
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
549
|
-
});
|
|
550
|
-
}
|
|
428
|
+
return instance;
|
|
551
429
|
}
|
|
430
|
+
|
|
431
|
+
// Setup always runs ensureFeeJuiceBalance before any deploy, so the account pays from its standing
|
|
432
|
+
// balance here. No manual gas estimation: the embedded wallet simulates before sending and derives
|
|
433
|
+
// the gas limits and padded maxFeesPerGas itself.
|
|
434
|
+
this.log.info(`Deploying contract ${name} at ${address.toString()}`);
|
|
435
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
436
|
+
const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
|
|
437
|
+
this.log.info(`Sent contract ${name} deploy tx ${txHash.toString()}`);
|
|
438
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
439
|
+
});
|
|
440
|
+
|
|
552
441
|
return instance;
|
|
553
442
|
}
|
|
554
443
|
|
|
444
|
+
/** True when the config allows bridging fee juice from L1 (fee_juice mode, an L1 RPC, and an L1 key). */
|
|
445
|
+
private isL1BridgingConfigured(): boolean {
|
|
446
|
+
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
447
|
+
return this.config.feePaymentMethod === 'fee_juice' && !!this.config.l1RpcUrls?.length && !!mnemonicOrPrivateKey;
|
|
448
|
+
}
|
|
449
|
+
|
|
555
450
|
/**
|
|
556
|
-
*
|
|
557
|
-
*
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
*
|
|
561
|
-
*
|
|
562
|
-
*
|
|
451
|
+
* Ensures the account holds enough fee juice before any other setup step. The account starts empty
|
|
452
|
+
* (initializerless accounts have no deployment tx) and the runtime loop pays fees from this balance and
|
|
453
|
+
* never refuels itself, so every flow funds the account up front. Bridges claims from L1 and consumes
|
|
454
|
+
* each with a claim-only tx until the balance clears the threshold, working from a zero (fresh run) or
|
|
455
|
+
* drained (restart) balance. Each bridge mints a fixed amount well above the threshold, so this is a
|
|
456
|
+
* single bridge in practice. No-op when L1 bridging is not configured or the balance is already above
|
|
457
|
+
* the threshold.
|
|
563
458
|
*/
|
|
564
|
-
private async ensureFeeJuiceBalance(
|
|
565
|
-
|
|
566
|
-
token: TokenContract | PrivateTokenContract,
|
|
567
|
-
): Promise<void> {
|
|
568
|
-
const { feePaymentMethod, l1RpcUrls } = this.config;
|
|
569
|
-
if (feePaymentMethod !== 'fee_juice' || !l1RpcUrls?.length) {
|
|
570
|
-
return;
|
|
571
|
-
}
|
|
572
|
-
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
573
|
-
if (!mnemonicOrPrivateKey) {
|
|
459
|
+
private async ensureFeeJuiceBalance(account: AztecAddress): Promise<void> {
|
|
460
|
+
if (!this.isL1BridgingConfigured()) {
|
|
574
461
|
return;
|
|
575
462
|
}
|
|
576
463
|
|
|
@@ -580,36 +467,21 @@ export class BotFactory {
|
|
|
580
467
|
return;
|
|
581
468
|
}
|
|
582
469
|
|
|
583
|
-
this.log.info(
|
|
584
|
-
`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1 until ${FEE_JUICE_TOP_UP_TARGET}`,
|
|
585
|
-
);
|
|
586
|
-
const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
|
|
587
|
-
const minimalInteraction = isStandardTokenContract(token)
|
|
588
|
-
? token.methods.transfer_in_public(account, account, 0n, 0)
|
|
589
|
-
: token.methods.transfer(0n, account, account);
|
|
470
|
+
this.log.info(`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1`);
|
|
590
471
|
|
|
591
|
-
while (balance <
|
|
592
|
-
|
|
472
|
+
while (balance < FEE_JUICE_TOP_UP_THRESHOLD) {
|
|
473
|
+
// Persist the claim before consuming it: if the top-up tx fails or the bot crashes mid-loop, the
|
|
474
|
+
// next run reuses the pending claim instead of bridging again (and wasting the bridged funds).
|
|
475
|
+
const claim = await this.getOrCreateBridgeClaim(account);
|
|
593
476
|
const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
|
|
594
|
-
const { estimatedGas } = await minimalInteraction.simulate({
|
|
595
|
-
from: account,
|
|
596
|
-
fee: { estimateGas: true, paymentMethod },
|
|
597
|
-
});
|
|
598
|
-
const gasSettings = GasSettings.from({
|
|
599
|
-
...estimatedGas!,
|
|
600
|
-
maxFeesPerGas,
|
|
601
|
-
maxPriorityFeesPerGas: GasFees.empty(),
|
|
602
|
-
});
|
|
603
477
|
|
|
604
478
|
await this.withNoMinTxsPerBlock(async () => {
|
|
605
|
-
const
|
|
606
|
-
|
|
607
|
-
fee: { gasSettings, paymentMethod },
|
|
608
|
-
wait: NO_WAIT,
|
|
609
|
-
});
|
|
479
|
+
const executionPayload = await paymentMethod.getExecutionPayload();
|
|
480
|
+
const { txHash } = await this.wallet.sendTx(executionPayload, { from: account, wait: NO_WAIT });
|
|
610
481
|
this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
|
|
611
482
|
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
612
483
|
});
|
|
484
|
+
await this.store.deleteBridgeClaim(account);
|
|
613
485
|
balance = await getFeeJuiceBalance(account, this.aztecNode);
|
|
614
486
|
this.log.info(`Fee juice balance after top-up: ${balance}`);
|
|
615
487
|
}
|
|
@@ -661,22 +533,20 @@ export class BotFactory {
|
|
|
661
533
|
}
|
|
662
534
|
|
|
663
535
|
/**
|
|
664
|
-
*
|
|
665
|
-
*
|
|
666
|
-
*
|
|
536
|
+
* Returns a usable bridge claim for the recipient, reusing a persisted one when its L1→L2 message is
|
|
537
|
+
* still available (resuming a top-up that failed or crashed before the claim was consumed) and bridging
|
|
538
|
+
* a fresh claim otherwise. The caller deletes the claim from the store once it has been consumed.
|
|
667
539
|
*/
|
|
668
540
|
private async getOrCreateBridgeClaim(recipient: AztecAddress): Promise<L2AmountClaim> {
|
|
669
|
-
// Check if we have an existing claim in the store
|
|
670
541
|
const existingClaim = await this.store.getBridgeClaim(recipient);
|
|
671
542
|
if (existingClaim) {
|
|
672
543
|
this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
|
|
673
|
-
|
|
674
|
-
// Check if the message is ready on L2
|
|
675
544
|
try {
|
|
676
545
|
const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
|
|
677
546
|
await this.withNoMinTxsPerBlock(() =>
|
|
678
547
|
waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
|
|
679
548
|
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
549
|
+
chainTip: this.syncChainTip,
|
|
680
550
|
}),
|
|
681
551
|
);
|
|
682
552
|
return existingClaim.claim;
|
|
@@ -688,7 +558,6 @@ export class BotFactory {
|
|
|
688
558
|
|
|
689
559
|
const claim = await this.bridgeL1FeeJuice(recipient);
|
|
690
560
|
await this.store.saveBridgeClaim(recipient, claim);
|
|
691
|
-
|
|
692
561
|
return claim;
|
|
693
562
|
}
|
|
694
563
|
|
|
@@ -715,6 +584,7 @@ export class BotFactory {
|
|
|
715
584
|
await this.withNoMinTxsPerBlock(() =>
|
|
716
585
|
waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
|
|
717
586
|
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
587
|
+
chainTip: this.syncChainTip,
|
|
718
588
|
}),
|
|
719
589
|
);
|
|
720
590
|
|
|
@@ -723,32 +593,36 @@ export class BotFactory {
|
|
|
723
593
|
return claim as L2AmountClaim;
|
|
724
594
|
}
|
|
725
595
|
|
|
726
|
-
|
|
727
|
-
private async getMinFees(): Promise<GasFees> {
|
|
728
|
-
try {
|
|
729
|
-
const predicted = await this.aztecNode.getPredictedMinFees(ManaUsageEstimate.Limit);
|
|
730
|
-
if (predicted.length === 0) {
|
|
731
|
-
return this.aztecNode.getCurrentMinFees();
|
|
732
|
-
}
|
|
733
|
-
return predicted.reduce((worst, fees) => (fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst));
|
|
734
|
-
} catch {
|
|
735
|
-
return this.aztecNode.getCurrentMinFees();
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
private async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
|
|
596
|
+
protected async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
|
|
740
597
|
if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
|
|
741
598
|
this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
|
|
742
599
|
return fn();
|
|
743
600
|
}
|
|
744
|
-
const
|
|
745
|
-
this
|
|
746
|
-
|
|
601
|
+
const aztecNodeAdmin = this.aztecNodeAdmin;
|
|
602
|
+
// Setup steps run concurrently, so this wrapper can be re-entered while another call is in flight.
|
|
603
|
+
// Reference-count the entrants: the first saves the current value and zeroes it, the last restores it.
|
|
604
|
+
// A naive save/zero/restore per call could interleave, with a late entrant reading the already-zeroed
|
|
605
|
+
// value and "restoring" 0 at the end.
|
|
606
|
+
if (this.noMinTxsPerBlockDepth++ === 0) {
|
|
607
|
+
this.savedMinTxsPerBlock = (async () => {
|
|
608
|
+
const { minTxsPerBlock } = await aztecNodeAdmin.getConfig();
|
|
609
|
+
this.log.warn(`Setting sequencer minTxsPerBlock to 0 from ${minTxsPerBlock} to flush setup transactions`);
|
|
610
|
+
await aztecNodeAdmin.setConfig({ minTxsPerBlock: 0 });
|
|
611
|
+
return { minTxsPerBlock };
|
|
612
|
+
})();
|
|
613
|
+
}
|
|
747
614
|
try {
|
|
615
|
+
await this.savedMinTxsPerBlock;
|
|
748
616
|
return await fn();
|
|
749
617
|
} finally {
|
|
750
|
-
this.
|
|
751
|
-
|
|
618
|
+
if (--this.noMinTxsPerBlockDepth === 0) {
|
|
619
|
+
// If saving/zeroing itself failed there is nothing to restore.
|
|
620
|
+
const saved = await this.savedMinTxsPerBlock!.catch(() => undefined);
|
|
621
|
+
if (saved) {
|
|
622
|
+
this.log.warn(`Restoring sequencer minTxsPerBlock to ${saved.minTxsPerBlock}`);
|
|
623
|
+
await aztecNodeAdmin.setConfig({ minTxsPerBlock: saved.minTxsPerBlock });
|
|
624
|
+
}
|
|
625
|
+
}
|
|
752
626
|
}
|
|
753
627
|
}
|
|
754
628
|
}
|