@aztec/bot 0.0.1-commit.f504929 → 0.0.1-commit.f5a9928
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 +4 -3
- package/dest/amm_bot.d.ts.map +1 -1
- package/dest/amm_bot.js +3 -3
- package/dest/base_bot.d.ts +4 -4
- package/dest/base_bot.d.ts.map +1 -1
- package/dest/base_bot.js +12 -22
- package/dest/bot.d.ts +3 -2
- package/dest/bot.d.ts.map +1 -1
- package/dest/bot.js +3 -7
- package/dest/config.d.ts +31 -82
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +6 -7
- package/dest/cross_chain_bot.d.ts +6 -4
- package/dest/cross_chain_bot.d.ts.map +1 -1
- package/dest/cross_chain_bot.js +14 -17
- package/dest/factory.d.ts +17 -7
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +232 -177
- package/dest/interface.d.ts +2 -6
- package/dest/interface.d.ts.map +1 -1
- package/dest/interface.js +30 -7
- package/dest/runner.d.ts +3 -2
- package/dest/runner.d.ts.map +1 -1
- package/dest/runner.js +6 -4
- package/package.json +16 -16
- package/src/amm_bot.ts +5 -2
- package/src/base_bot.ts +10 -17
- package/src/bot.ts +4 -4
- package/src/config.ts +8 -8
- package/src/cross_chain_bot.ts +12 -14
- package/src/factory.ts +233 -195
- package/src/interface.ts +7 -7
- package/src/runner.ts +26 -3
package/src/factory.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { getInitialTestAccountsData } from '@aztec/accounts/testing';
|
|
2
|
+
import { deriveSecretKeyFromSigningKey } from '@aztec/accounts/utils';
|
|
2
3
|
import { AztecAddress } from '@aztec/aztec.js/addresses';
|
|
3
4
|
import {
|
|
4
5
|
BatchCall,
|
|
@@ -15,21 +16,21 @@ 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';
|
|
17
18
|
import { waitForTx } from '@aztec/aztec.js/node';
|
|
19
|
+
import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
|
|
18
20
|
import { createEthereumChain } from '@aztec/ethereum/chain';
|
|
19
21
|
import { createExtendedL1Client } from '@aztec/ethereum/client';
|
|
20
22
|
import { RollupContract } from '@aztec/ethereum/contracts';
|
|
21
23
|
import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
|
|
22
24
|
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
25
|
+
import { GrumpkinScalar } from '@aztec/foundation/curves/grumpkin';
|
|
23
26
|
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
24
|
-
import { Timer } from '@aztec/foundation/timer';
|
|
25
27
|
import { AMMContract } from '@aztec/noir-contracts.js/AMM';
|
|
26
28
|
import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
|
|
27
29
|
import { TokenContract } from '@aztec/noir-contracts.js/Token';
|
|
28
30
|
import { TestContract } from '@aztec/noir-test-contracts.js/Test';
|
|
31
|
+
import type { BlockTag } from '@aztec/stdlib/block';
|
|
29
32
|
import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
|
|
30
|
-
import { GasSettings } from '@aztec/stdlib/gas';
|
|
31
33
|
import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
|
|
32
|
-
import { deriveSigningKey } from '@aztec/stdlib/keys';
|
|
33
34
|
import { EmbeddedWallet } from '@aztec/wallets/embedded';
|
|
34
35
|
|
|
35
36
|
import { type BotConfig, SupportedTokenContracts } from './config.js';
|
|
@@ -39,16 +40,23 @@ import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils
|
|
|
39
40
|
|
|
40
41
|
const MINT_BALANCE = 1e12;
|
|
41
42
|
const MIN_BALANCE = 1e3;
|
|
43
|
+
const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
|
|
42
44
|
|
|
43
45
|
export class BotFactory {
|
|
44
46
|
private log = createLogger('bot');
|
|
45
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
|
+
|
|
46
53
|
constructor(
|
|
47
54
|
private readonly config: BotConfig,
|
|
48
55
|
private readonly wallet: EmbeddedWallet,
|
|
49
56
|
private readonly store: BotStore,
|
|
50
57
|
private readonly aztecNode: AztecNode,
|
|
51
58
|
private readonly aztecNodeAdmin?: AztecNodeAdmin,
|
|
59
|
+
private readonly syncChainTip?: BlockTag,
|
|
52
60
|
) {
|
|
53
61
|
// Set fee padding on the wallet so that all transactions during setup
|
|
54
62
|
// (token deploy, minting, etc.) use the configured padding, not the default.
|
|
@@ -67,7 +75,9 @@ export class BotFactory {
|
|
|
67
75
|
recipient: AztecAddress;
|
|
68
76
|
}> {
|
|
69
77
|
const defaultAccountAddress = await this.setupAccount();
|
|
70
|
-
const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random()))
|
|
78
|
+
const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random(), GrumpkinScalar.random()))
|
|
79
|
+
.address;
|
|
80
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress);
|
|
71
81
|
const token = await this.setupToken(defaultAccountAddress);
|
|
72
82
|
await this.mintTokens(token, defaultAccountAddress);
|
|
73
83
|
return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
|
|
@@ -82,23 +92,36 @@ export class BotFactory {
|
|
|
82
92
|
node: AztecNode;
|
|
83
93
|
}> {
|
|
84
94
|
const defaultAccountAddress = await this.setupAccount();
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
defaultAccountAddress,
|
|
95
|
-
|
|
96
|
-
token0,
|
|
97
|
-
token1,
|
|
98
|
-
liquidityToken,
|
|
99
|
-
);
|
|
95
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress);
|
|
96
|
+
|
|
97
|
+
const salt = this.config.tokenSalt;
|
|
98
|
+
|
|
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
|
+
]);
|
|
100
106
|
|
|
101
|
-
|
|
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);
|
|
102
125
|
this.log.info(`AMM initialized and funded`);
|
|
103
126
|
|
|
104
127
|
return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
|
|
@@ -117,6 +140,7 @@ export class BotFactory {
|
|
|
117
140
|
rollupVersion: bigint;
|
|
118
141
|
}> {
|
|
119
142
|
const defaultAccountAddress = await this.setupAccount();
|
|
143
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress);
|
|
120
144
|
|
|
121
145
|
// Create L1 client (same pattern as bridgeL1FeeJuice)
|
|
122
146
|
const l1RpcUrls = this.config.l1RpcUrls;
|
|
@@ -135,25 +159,32 @@ export class BotFactory {
|
|
|
135
159
|
const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
|
|
136
160
|
const rollupVersion = await rollupContract.getVersion();
|
|
137
161
|
|
|
138
|
-
//
|
|
139
|
-
|
|
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;
|
|
140
171
|
|
|
141
172
|
// Recover any pending messages from store (clean up stale ones first)
|
|
142
173
|
await this.store.cleanupOldPendingMessages();
|
|
143
174
|
const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
144
175
|
|
|
145
|
-
// 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.
|
|
146
178
|
const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
}
|
|
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
|
+
]);
|
|
157
188
|
|
|
158
189
|
// Block until at least one message is ready
|
|
159
190
|
const allMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
@@ -162,11 +193,7 @@ export class BotFactory {
|
|
|
162
193
|
const firstMsg = allMessages[0];
|
|
163
194
|
await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
|
|
164
195
|
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
165
|
-
|
|
166
|
-
// state. With true, it returns one block early which causes gas estimation simulation to
|
|
167
|
-
// fail since it runs against the current state.
|
|
168
|
-
// See https://linear.app/aztec-labs/issue/A-548 for details.
|
|
169
|
-
forPublicConsumption: false,
|
|
196
|
+
chainTip: this.syncChainTip,
|
|
170
197
|
});
|
|
171
198
|
this.log.info(`First L1→L2 message is ready`);
|
|
172
199
|
}
|
|
@@ -181,14 +208,8 @@ export class BotFactory {
|
|
|
181
208
|
};
|
|
182
209
|
}
|
|
183
210
|
|
|
184
|
-
private async
|
|
185
|
-
const
|
|
186
|
-
from: deployer,
|
|
187
|
-
contractAddressSalt: this.config.tokenSalt,
|
|
188
|
-
universalDeploy: true,
|
|
189
|
-
};
|
|
190
|
-
const deploy = TestContract.deploy(this.wallet);
|
|
191
|
-
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 });
|
|
192
213
|
return TestContract.at(instance.address, this.wallet);
|
|
193
214
|
}
|
|
194
215
|
|
|
@@ -207,50 +228,16 @@ export class BotFactory {
|
|
|
207
228
|
}
|
|
208
229
|
}
|
|
209
230
|
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
const timer = new Timer();
|
|
218
|
-
const address = accountManager.address;
|
|
219
|
-
this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
|
|
220
|
-
await this.store.deleteBridgeClaim(address);
|
|
221
|
-
return address;
|
|
222
|
-
} else {
|
|
223
|
-
const address = accountManager.address;
|
|
224
|
-
this.log.info(`Deploying account at ${address}`);
|
|
225
|
-
|
|
226
|
-
const claim = await this.getOrCreateBridgeClaim(address);
|
|
227
|
-
|
|
228
|
-
const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
|
|
229
|
-
const deployMethod = await accountManager.getDeployMethod();
|
|
230
|
-
const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
|
|
231
|
-
const gasSettings = GasSettings.default({ maxFeesPerGas });
|
|
232
|
-
|
|
233
|
-
await this.withNoMinTxsPerBlock(async () => {
|
|
234
|
-
const { txHash } = await deployMethod.send({
|
|
235
|
-
from: AztecAddress.ZERO,
|
|
236
|
-
fee: { gasSettings, paymentMethod },
|
|
237
|
-
wait: NO_WAIT,
|
|
238
|
-
});
|
|
239
|
-
this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
|
|
240
|
-
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
241
|
-
});
|
|
242
|
-
this.log.info(`Account deployed at ${address}`);
|
|
243
|
-
|
|
244
|
-
// Clean up the consumed bridge claim
|
|
245
|
-
await this.store.deleteBridgeClaim(address);
|
|
246
|
-
|
|
247
|
-
return accountManager.address;
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
|
|
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
|
+
*/
|
|
251
238
|
private async setupTestAccount() {
|
|
252
239
|
const [initialAccountData] = await getInitialTestAccountsData();
|
|
253
|
-
const accountManager = await this.wallet.
|
|
240
|
+
const accountManager = await this.wallet.createSchnorrInitializerlessAccount(
|
|
254
241
|
initialAccountData.secret,
|
|
255
242
|
initialAccountData.salt,
|
|
256
243
|
initialAccountData.signingKey,
|
|
@@ -258,35 +245,45 @@ export class BotFactory {
|
|
|
258
245
|
return accountManager.address;
|
|
259
246
|
}
|
|
260
247
|
|
|
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;
|
|
254
|
+
}
|
|
255
|
+
|
|
261
256
|
/**
|
|
262
257
|
* Checks if the token contract is deployed and deploys it if necessary.
|
|
263
|
-
*
|
|
264
|
-
* @
|
|
258
|
+
* Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
|
|
259
|
+
* @param sender - Aztec address to deploy the token contract from.
|
|
260
|
+
* @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
|
|
261
|
+
* @returns The TokenContract or PrivateTokenContract instance.
|
|
265
262
|
*/
|
|
266
263
|
private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
|
|
267
264
|
let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
|
|
268
|
-
|
|
269
|
-
const deployOpts: DeployOptions = {
|
|
270
|
-
from: sender,
|
|
271
|
-
contractAddressSalt: this.config.tokenSalt,
|
|
272
|
-
universalDeploy: true,
|
|
273
|
-
};
|
|
265
|
+
const salt = this.config.tokenSalt;
|
|
266
|
+
const deployOpts: DeployOptions = { from: sender };
|
|
274
267
|
let token: TokenContract | PrivateTokenContract;
|
|
275
268
|
if (this.config.contract === SupportedTokenContracts.TokenContract) {
|
|
276
|
-
deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
|
|
277
|
-
|
|
278
|
-
token = TokenContract.at(
|
|
269
|
+
deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
|
|
270
|
+
const instance = await deploy.getInstance();
|
|
271
|
+
token = TokenContract.at(instance.address, this.wallet);
|
|
279
272
|
} else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
|
|
280
273
|
// Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
|
|
281
274
|
const tokenSecretKey = Fr.random();
|
|
282
275
|
const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
|
|
283
|
-
deploy = PrivateTokenContract.
|
|
276
|
+
deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
|
|
277
|
+
salt,
|
|
278
|
+
universalDeploy: true,
|
|
279
|
+
publicKeys: tokenPublicKeys,
|
|
280
|
+
});
|
|
284
281
|
deployOpts.skipInstancePublication = true;
|
|
285
282
|
deployOpts.skipClassPublication = true;
|
|
286
283
|
deployOpts.skipInitialization = false;
|
|
287
284
|
|
|
288
285
|
// Register the contract with the secret key before deployment
|
|
289
|
-
tokenInstance = await deploy.getInstance(
|
|
286
|
+
const tokenInstance = await deploy.getInstance();
|
|
290
287
|
token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
|
|
291
288
|
await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
|
|
292
289
|
// The contract constructor initializes private storage vars that need the contract's own nullifier key.
|
|
@@ -295,20 +292,7 @@ export class BotFactory {
|
|
|
295
292
|
throw new Error(`Unsupported token contract type: ${this.config.contract}`);
|
|
296
293
|
}
|
|
297
294
|
|
|
298
|
-
|
|
299
|
-
const metadata = await this.wallet.getContractMetadata(address);
|
|
300
|
-
if (metadata.isContractPublished) {
|
|
301
|
-
this.log.info(`Token at ${address.toString()} already deployed`);
|
|
302
|
-
await deploy.register();
|
|
303
|
-
} else {
|
|
304
|
-
this.log.info(`Deploying token contract at ${address.toString()}`);
|
|
305
|
-
const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
|
|
306
|
-
this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
|
|
307
|
-
await this.withNoMinTxsPerBlock(async () => {
|
|
308
|
-
await waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
309
|
-
return token;
|
|
310
|
-
});
|
|
311
|
-
}
|
|
295
|
+
await this.registerOrDeployContract('token', deploy, deployOpts);
|
|
312
296
|
return token;
|
|
313
297
|
}
|
|
314
298
|
|
|
@@ -319,40 +303,48 @@ export class BotFactory {
|
|
|
319
303
|
*/
|
|
320
304
|
private async setupTokenContract(
|
|
321
305
|
deployer: AztecAddress,
|
|
322
|
-
|
|
306
|
+
salt: Fr,
|
|
323
307
|
name: string,
|
|
324
308
|
ticker: string,
|
|
325
309
|
decimals = 18,
|
|
326
310
|
): Promise<TokenContract> {
|
|
327
|
-
const deployOpts: DeployOptions = { from: deployer
|
|
328
|
-
const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
|
|
311
|
+
const deployOpts: DeployOptions = { from: deployer };
|
|
312
|
+
const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
|
|
329
313
|
const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
|
|
330
314
|
return TokenContract.at(instance.address, this.wallet);
|
|
331
315
|
}
|
|
332
316
|
|
|
333
|
-
private async
|
|
334
|
-
|
|
335
|
-
contractAddressSalt: Fr,
|
|
336
|
-
token0: TokenContract,
|
|
337
|
-
token1: TokenContract,
|
|
338
|
-
lpToken: TokenContract,
|
|
339
|
-
): Promise<AMMContract> {
|
|
340
|
-
const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
|
|
341
|
-
const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
|
|
342
|
-
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 });
|
|
343
319
|
const amm = AMMContract.at(instance.address, this.wallet);
|
|
344
|
-
|
|
345
320
|
this.log.info(`AMM deployed at ${amm.address}`);
|
|
346
|
-
const { receipt: minterReceipt } = await lpToken.methods
|
|
347
|
-
.set_minter(amm.address, true)
|
|
348
|
-
.send({ from: deployer, wait: { timeout: this.config.txMinedWaitSeconds } });
|
|
349
|
-
this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
|
|
350
|
-
this.log.info(`Liquidity token initialized`);
|
|
351
|
-
|
|
352
321
|
return amm;
|
|
353
322
|
}
|
|
354
323
|
|
|
355
|
-
|
|
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({
|
|
328
|
+
from: deployer,
|
|
329
|
+
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
330
|
+
});
|
|
331
|
+
this.log.info(`Set LP token minter to AMM txHash=${receipt.txHash.toString()}`);
|
|
332
|
+
}
|
|
333
|
+
|
|
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()}`);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
private async addAmmLiquidity(
|
|
356
348
|
defaultAccountAddress: AztecAddress,
|
|
357
349
|
liquidityProvider: AztecAddress,
|
|
358
350
|
amm: AMMContract,
|
|
@@ -360,22 +352,6 @@ export class BotFactory {
|
|
|
360
352
|
token1: TokenContract,
|
|
361
353
|
lpToken: TokenContract,
|
|
362
354
|
): Promise<void> {
|
|
363
|
-
const getPrivateBalances = () =>
|
|
364
|
-
Promise.all([
|
|
365
|
-
token0.methods
|
|
366
|
-
.balance_of_private(liquidityProvider)
|
|
367
|
-
.simulate({ from: liquidityProvider })
|
|
368
|
-
.then(r => r.result),
|
|
369
|
-
token1.methods
|
|
370
|
-
.balance_of_private(liquidityProvider)
|
|
371
|
-
.simulate({ from: liquidityProvider })
|
|
372
|
-
.then(r => r.result),
|
|
373
|
-
lpToken.methods
|
|
374
|
-
.balance_of_private(liquidityProvider)
|
|
375
|
-
.simulate({ from: liquidityProvider })
|
|
376
|
-
.then(r => r.result),
|
|
377
|
-
]);
|
|
378
|
-
|
|
379
355
|
const authwitNonce = Fr.random();
|
|
380
356
|
|
|
381
357
|
// keep some tokens for swapping
|
|
@@ -384,12 +360,6 @@ export class BotFactory {
|
|
|
384
360
|
const amount1Max = MINT_BALANCE / 2;
|
|
385
361
|
const amount1Min = MINT_BALANCE / 4;
|
|
386
362
|
|
|
387
|
-
const [t0Bal, t1Bal, lpBal] = await getPrivateBalances();
|
|
388
|
-
|
|
389
|
-
this.log.info(
|
|
390
|
-
`Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1. Current private balances of ${liquidityProvider}: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`,
|
|
391
|
-
);
|
|
392
|
-
|
|
393
363
|
// Add authwitnesses for the transfers in AMM::add_liquidity function
|
|
394
364
|
const token0Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
|
|
395
365
|
caller: amm.address,
|
|
@@ -414,14 +384,7 @@ export class BotFactory {
|
|
|
414
384
|
.getFunctionCall(),
|
|
415
385
|
});
|
|
416
386
|
|
|
417
|
-
const { receipt
|
|
418
|
-
token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
|
|
419
|
-
token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
|
|
420
|
-
]).send({ from: liquidityProvider, wait: { timeout: this.config.txMinedWaitSeconds } });
|
|
421
|
-
|
|
422
|
-
this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
|
|
423
|
-
|
|
424
|
-
const { receipt: addLiquidityReceipt } = await amm.methods
|
|
387
|
+
const { receipt } = await amm.methods
|
|
425
388
|
.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce)
|
|
426
389
|
.send({
|
|
427
390
|
from: liquidityProvider,
|
|
@@ -429,12 +392,25 @@ export class BotFactory {
|
|
|
429
392
|
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
430
393
|
});
|
|
431
394
|
|
|
432
|
-
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()}`);
|
|
433
396
|
this.log.info(`Liquidity added`);
|
|
434
397
|
|
|
435
|
-
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
|
+
]);
|
|
436
412
|
this.log.info(
|
|
437
|
-
`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}`,
|
|
438
414
|
);
|
|
439
415
|
}
|
|
440
416
|
|
|
@@ -443,27 +419,75 @@ export class BotFactory {
|
|
|
443
419
|
deploy: DeployMethod<T>,
|
|
444
420
|
deployOpts: DeployOptions,
|
|
445
421
|
): Promise<ContractInstanceWithAddress> {
|
|
446
|
-
const instance = await deploy.getInstance(
|
|
422
|
+
const instance = await deploy.getInstance();
|
|
447
423
|
const address = instance.address;
|
|
448
424
|
const metadata = await this.wallet.getContractMetadata(address);
|
|
449
425
|
if (metadata.isContractPublished) {
|
|
450
426
|
this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
|
|
451
427
|
await deploy.register();
|
|
452
|
-
|
|
453
|
-
this.log.info(`Deploying contract ${name} at ${address.toString()}`);
|
|
454
|
-
await this.withNoMinTxsPerBlock(async () => {
|
|
455
|
-
const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
|
|
456
|
-
this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
|
|
457
|
-
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
458
|
-
});
|
|
428
|
+
return instance;
|
|
459
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
|
+
|
|
460
441
|
return instance;
|
|
461
442
|
}
|
|
462
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
|
+
|
|
463
450
|
/**
|
|
464
|
-
*
|
|
465
|
-
*
|
|
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.
|
|
466
458
|
*/
|
|
459
|
+
private async ensureFeeJuiceBalance(account: AztecAddress): Promise<void> {
|
|
460
|
+
if (!this.isL1BridgingConfigured()) {
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
let balance = await getFeeJuiceBalance(account, this.aztecNode);
|
|
465
|
+
if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
|
|
466
|
+
this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
this.log.info(`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1`);
|
|
471
|
+
|
|
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);
|
|
476
|
+
const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
|
|
477
|
+
|
|
478
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
479
|
+
const executionPayload = await paymentMethod.getExecutionPayload();
|
|
480
|
+
const { txHash } = await this.wallet.sendTx(executionPayload, { from: account, wait: NO_WAIT });
|
|
481
|
+
this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
|
|
482
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
483
|
+
});
|
|
484
|
+
await this.store.deleteBridgeClaim(account);
|
|
485
|
+
balance = await getFeeJuiceBalance(account, this.aztecNode);
|
|
486
|
+
this.log.info(`Fee juice balance after top-up: ${balance}`);
|
|
487
|
+
}
|
|
488
|
+
this.log.info(`Fee juice top-up complete for ${account.toString()}`);
|
|
489
|
+
}
|
|
490
|
+
|
|
467
491
|
private async mintTokens(token: TokenContract | PrivateTokenContract, minter: AztecAddress) {
|
|
468
492
|
const isStandardToken = isStandardTokenContract(token);
|
|
469
493
|
let privateBalance = 0n;
|
|
@@ -496,8 +520,9 @@ export class BotFactory {
|
|
|
496
520
|
|
|
497
521
|
// PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
|
|
498
522
|
const additionalScopes = isStandardToken ? undefined : [token.address];
|
|
523
|
+
const mintBatch = new BatchCall(token.wallet, calls);
|
|
499
524
|
await this.withNoMinTxsPerBlock(async () => {
|
|
500
|
-
const { txHash } = await
|
|
525
|
+
const { txHash } = await mintBatch.send({
|
|
501
526
|
from: minter,
|
|
502
527
|
additionalScopes,
|
|
503
528
|
wait: NO_WAIT,
|
|
@@ -508,23 +533,20 @@ export class BotFactory {
|
|
|
508
533
|
}
|
|
509
534
|
|
|
510
535
|
/**
|
|
511
|
-
*
|
|
512
|
-
*
|
|
513
|
-
*
|
|
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.
|
|
514
539
|
*/
|
|
515
540
|
private async getOrCreateBridgeClaim(recipient: AztecAddress): Promise<L2AmountClaim> {
|
|
516
|
-
// Check if we have an existing claim in the store
|
|
517
541
|
const existingClaim = await this.store.getBridgeClaim(recipient);
|
|
518
542
|
if (existingClaim) {
|
|
519
543
|
this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
|
|
520
|
-
|
|
521
|
-
// Check if the message is ready on L2
|
|
522
544
|
try {
|
|
523
545
|
const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
|
|
524
546
|
await this.withNoMinTxsPerBlock(() =>
|
|
525
547
|
waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
|
|
526
548
|
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
527
|
-
|
|
549
|
+
chainTip: this.syncChainTip,
|
|
528
550
|
}),
|
|
529
551
|
);
|
|
530
552
|
return existingClaim.claim;
|
|
@@ -536,7 +558,6 @@ export class BotFactory {
|
|
|
536
558
|
|
|
537
559
|
const claim = await this.bridgeL1FeeJuice(recipient);
|
|
538
560
|
await this.store.saveBridgeClaim(recipient, claim);
|
|
539
|
-
|
|
540
561
|
return claim;
|
|
541
562
|
}
|
|
542
563
|
|
|
@@ -563,7 +584,7 @@ export class BotFactory {
|
|
|
563
584
|
await this.withNoMinTxsPerBlock(() =>
|
|
564
585
|
waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
|
|
565
586
|
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
566
|
-
|
|
587
|
+
chainTip: this.syncChainTip,
|
|
567
588
|
}),
|
|
568
589
|
);
|
|
569
590
|
|
|
@@ -572,19 +593,36 @@ export class BotFactory {
|
|
|
572
593
|
return claim as L2AmountClaim;
|
|
573
594
|
}
|
|
574
595
|
|
|
575
|
-
|
|
596
|
+
protected async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
|
|
576
597
|
if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
|
|
577
598
|
this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
|
|
578
599
|
return fn();
|
|
579
600
|
}
|
|
580
|
-
const
|
|
581
|
-
this
|
|
582
|
-
|
|
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
|
+
}
|
|
583
614
|
try {
|
|
615
|
+
await this.savedMinTxsPerBlock;
|
|
584
616
|
return await fn();
|
|
585
617
|
} finally {
|
|
586
|
-
this.
|
|
587
|
-
|
|
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
|
+
}
|
|
588
626
|
}
|
|
589
627
|
}
|
|
590
628
|
}
|