@aztec/bot 0.0.1-commit.4d3c002 → 0.0.1-commit.4d9804df
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 +2 -2
- package/dest/base_bot.d.ts +2 -2
- package/dest/base_bot.d.ts.map +1 -1
- 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 +28 -79
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +3 -3
- 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 +13 -9
- package/dest/factory.d.ts +16 -10
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +207 -293
- 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 +4 -1
- package/src/base_bot.ts +2 -1
- package/src/bot.ts +3 -0
- package/src/config.ts +3 -2
- package/src/cross_chain_bot.ts +11 -6
- package/src/factory.ts +203 -322
- package/src/interface.ts +7 -7
- package/src/runner.ts +26 -3
package/dest/factory.js
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 { BatchCall, NO_WAIT } from '@aztec/aztec.js/contracts';
|
|
4
4
|
import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
|
|
5
5
|
import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
|
|
@@ -8,40 +8,41 @@ import { createLogger } from '@aztec/aztec.js/log';
|
|
|
8
8
|
import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
|
|
9
9
|
import { waitForTx } from '@aztec/aztec.js/node';
|
|
10
10
|
import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
|
|
11
|
-
import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
|
|
12
11
|
import { createEthereumChain } from '@aztec/ethereum/chain';
|
|
13
12
|
import { createExtendedL1Client } from '@aztec/ethereum/client';
|
|
14
13
|
import { RollupContract } from '@aztec/ethereum/contracts';
|
|
15
14
|
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
15
|
+
import { GrumpkinScalar } from '@aztec/foundation/curves/grumpkin';
|
|
16
16
|
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
17
|
-
import { Timer } from '@aztec/foundation/timer';
|
|
18
17
|
import { AMMContract } from '@aztec/noir-contracts.js/AMM';
|
|
19
18
|
import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
|
|
20
19
|
import { TokenContract } from '@aztec/noir-contracts.js/Token';
|
|
21
20
|
import { TestContract } from '@aztec/noir-test-contracts.js/Test';
|
|
22
|
-
import { GasFees, GasSettings } from '@aztec/stdlib/gas';
|
|
23
|
-
import { deriveSigningKey } from '@aztec/stdlib/keys';
|
|
24
21
|
import { SupportedTokenContracts } from './config.js';
|
|
25
22
|
import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
|
|
26
23
|
import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
|
|
27
24
|
const MINT_BALANCE = 1e12;
|
|
28
25
|
const MIN_BALANCE = 1e3;
|
|
29
26
|
const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
|
|
30
|
-
const FEE_JUICE_TOP_UP_TARGET = 10_000n * 10n ** 18n;
|
|
31
27
|
export class BotFactory {
|
|
32
28
|
config;
|
|
33
29
|
wallet;
|
|
34
30
|
store;
|
|
35
31
|
aztecNode;
|
|
36
32
|
aztecNodeAdmin;
|
|
33
|
+
syncChainTip;
|
|
37
34
|
log;
|
|
38
|
-
|
|
35
|
+
/** Number of in-flight withNoMinTxsPerBlock calls; see that method for why they are counted. */ noMinTxsPerBlockDepth;
|
|
36
|
+
/** Set by the first withNoMinTxsPerBlock entrant; resolves to the minTxsPerBlock value to restore. */ savedMinTxsPerBlock;
|
|
37
|
+
constructor(config, wallet, store, aztecNode, aztecNodeAdmin, syncChainTip){
|
|
39
38
|
this.config = config;
|
|
40
39
|
this.wallet = wallet;
|
|
41
40
|
this.store = store;
|
|
42
41
|
this.aztecNode = aztecNode;
|
|
43
42
|
this.aztecNodeAdmin = aztecNodeAdmin;
|
|
43
|
+
this.syncChainTip = syncChainTip;
|
|
44
44
|
this.log = createLogger('bot');
|
|
45
|
+
this.noMinTxsPerBlockDepth = 0;
|
|
45
46
|
// Set fee padding on the wallet so that all transactions during setup
|
|
46
47
|
// (token deploy, minting, etc.) use the configured padding, not the default.
|
|
47
48
|
this.wallet.setMinFeePadding(config.minFeePadding);
|
|
@@ -51,9 +52,9 @@ export class BotFactory {
|
|
|
51
52
|
* deploying the token contract, and minting tokens if necessary.
|
|
52
53
|
*/ async setup() {
|
|
53
54
|
const defaultAccountAddress = await this.setupAccount();
|
|
54
|
-
const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
|
|
55
|
-
|
|
56
|
-
await this.
|
|
55
|
+
const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random(), GrumpkinScalar.random())).address;
|
|
56
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress);
|
|
57
|
+
const token = await this.setupToken(defaultAccountAddress);
|
|
57
58
|
await this.mintTokens(token, defaultAccountAddress);
|
|
58
59
|
return {
|
|
59
60
|
wallet: this.wallet,
|
|
@@ -65,12 +66,31 @@ export class BotFactory {
|
|
|
65
66
|
}
|
|
66
67
|
async setupAmm() {
|
|
67
68
|
const defaultAccountAddress = await this.setupAccount();
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
const
|
|
73
|
-
|
|
69
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress);
|
|
70
|
+
const salt = this.config.tokenSalt;
|
|
71
|
+
// token0, token1 and the LP token are independent contracts with no shared state, so deploy them
|
|
72
|
+
// concurrently rather than one slot at a time.
|
|
73
|
+
const [token0, token1, liquidityToken] = await Promise.all([
|
|
74
|
+
this.setupTokenContract(defaultAccountAddress, salt, 'BotToken0', 'BOT0'),
|
|
75
|
+
this.setupTokenContract(defaultAccountAddress, salt, 'BotToken1', 'BOT1'),
|
|
76
|
+
this.setupTokenContract(defaultAccountAddress, salt, 'BotLPToken', 'BOTLP')
|
|
77
|
+
]);
|
|
78
|
+
const ammDeploy = AMMContract.deploy(this.wallet, token0.address, token1.address, liquidityToken.address, {
|
|
79
|
+
salt,
|
|
80
|
+
universalDeploy: true
|
|
81
|
+
});
|
|
82
|
+
const ammAddress = (await ammDeploy.getInstance()).address;
|
|
83
|
+
// The AMM constructor only stores the (already-derived) token addresses, and set_minter only records
|
|
84
|
+
// the AMM address on the LP token: neither reads the other's on-chain state, so the AMM deploy, the
|
|
85
|
+
// LP-minter grant, and the token0/token1 mints are mutually independent and run concurrently.
|
|
86
|
+
const [amm] = await Promise.all([
|
|
87
|
+
this.deployAmmContract(defaultAccountAddress, ammDeploy),
|
|
88
|
+
this.grantLpTokenMinter(defaultAccountAddress, liquidityToken, ammAddress),
|
|
89
|
+
this.mintAmmLiquidity(defaultAccountAddress, token0, token1)
|
|
90
|
+
]);
|
|
91
|
+
// add_liquidity spends the minted token0/token1 balances and mints LP tokens, so it must follow both
|
|
92
|
+
// the mints and the minter grant, and target the deployed AMM.
|
|
93
|
+
await this.addAmmLiquidity(defaultAccountAddress, defaultAccountAddress, amm, token0, token1, liquidityToken);
|
|
74
94
|
this.log.info(`AMM initialized and funded`);
|
|
75
95
|
return {
|
|
76
96
|
wallet: this.wallet,
|
|
@@ -86,6 +106,7 @@ export class BotFactory {
|
|
|
86
106
|
* seeding initial L1→L2 messages, and waiting for the first to be ready.
|
|
87
107
|
*/ async setupCrossChain() {
|
|
88
108
|
const defaultAccountAddress = await this.setupAccount();
|
|
109
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress);
|
|
89
110
|
// Create L1 client (same pattern as bridgeL1FeeJuice)
|
|
90
111
|
const l1RpcUrls = this.config.l1RpcUrls;
|
|
91
112
|
if (!l1RpcUrls?.length) {
|
|
@@ -101,23 +122,38 @@ export class BotFactory {
|
|
|
101
122
|
// Fetch Rollup version (needed for Inbox L2Actor struct)
|
|
102
123
|
const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
|
|
103
124
|
const rollupVersion = await rollupContract.getVersion();
|
|
104
|
-
//
|
|
105
|
-
|
|
125
|
+
// Derive the TestContract address up front (deterministic from the salt). Seeding L1→L2 messages only
|
|
126
|
+
// needs the L2 recipient address — the messages are queued on L1 and don't require the L2 contract to
|
|
127
|
+
// exist yet (they're consumed later, after setup completes) — so the deploy (an L2 tx paying from the
|
|
128
|
+
// standing balance funded above) and the L1 seeding run concurrently.
|
|
129
|
+
const testContractDeploy = TestContract.deploy(this.wallet, {
|
|
130
|
+
salt: this.config.tokenSalt,
|
|
131
|
+
universalDeploy: true
|
|
132
|
+
});
|
|
133
|
+
const contractAddress = (await testContractDeploy.getInstance()).address;
|
|
106
134
|
// Recover any pending messages from store (clean up stale ones first)
|
|
107
135
|
await this.store.cleanupOldPendingMessages();
|
|
108
136
|
const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
109
|
-
// Seed initial L1→L2 messages if pipeline is empty
|
|
137
|
+
// Seed initial L1→L2 messages if pipeline is empty. The seeds are sent one at a time: they share the
|
|
138
|
+
// bot's L1 account, so concurrent sends would race on the L1 nonce.
|
|
110
139
|
const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
140
|
+
const inboxAddress = EthAddress.fromString(l1ContractAddresses.inboxAddress.toString());
|
|
141
|
+
const [contract] = await Promise.all([
|
|
142
|
+
this.deployTestContract(defaultAccountAddress, testContractDeploy),
|
|
143
|
+
(async ()=>{
|
|
144
|
+
for(let i = 0; i < seedCount; i++){
|
|
145
|
+
await seedL1ToL2Message(l1Client, inboxAddress, contractAddress, rollupVersion, this.store, this.log);
|
|
146
|
+
}
|
|
147
|
+
})()
|
|
148
|
+
]);
|
|
114
149
|
// Block until at least one message is ready
|
|
115
150
|
const allMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
116
151
|
if (allMessages.length > 0) {
|
|
117
152
|
this.log.info(`Waiting for first L1→L2 message to be ready...`);
|
|
118
153
|
const firstMsg = allMessages[0];
|
|
119
154
|
await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
|
|
120
|
-
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds
|
|
155
|
+
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
156
|
+
chainTip: this.syncChainTip
|
|
121
157
|
});
|
|
122
158
|
this.log.info(`First L1→L2 message is ready`);
|
|
123
159
|
}
|
|
@@ -130,14 +166,10 @@ export class BotFactory {
|
|
|
130
166
|
rollupVersion
|
|
131
167
|
};
|
|
132
168
|
}
|
|
133
|
-
async
|
|
134
|
-
const
|
|
135
|
-
from: deployer
|
|
136
|
-
|
|
137
|
-
universalDeploy: true
|
|
138
|
-
};
|
|
139
|
-
const deploy = TestContract.deploy(this.wallet);
|
|
140
|
-
const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
|
|
169
|
+
async deployTestContract(deployer, deploy) {
|
|
170
|
+
const instance = await this.registerOrDeployContract('TestContract', deploy, {
|
|
171
|
+
from: deployer
|
|
172
|
+
});
|
|
141
173
|
return TestContract.at(instance.address, this.wallet);
|
|
142
174
|
}
|
|
143
175
|
/**
|
|
@@ -153,104 +185,23 @@ export class BotFactory {
|
|
|
153
185
|
return await this.setupTestAccount();
|
|
154
186
|
}
|
|
155
187
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
const timer = new Timer();
|
|
164
|
-
const address = accountManager.address;
|
|
165
|
-
this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
|
|
166
|
-
await this.store.deleteBridgeClaim(address);
|
|
167
|
-
return address;
|
|
168
|
-
} else {
|
|
169
|
-
const address = accountManager.address;
|
|
170
|
-
this.log.info(`Deploying account at ${address}`);
|
|
171
|
-
const claim = await this.getOrCreateBridgeClaim(address);
|
|
172
|
-
const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
|
|
173
|
-
const deployMethod = await accountManager.getDeployMethod();
|
|
174
|
-
await this.withNoMinTxsPerBlock(async ()=>{
|
|
175
|
-
const { txHash } = await deployMethod.send({
|
|
176
|
-
from: NO_FROM,
|
|
177
|
-
fee: {
|
|
178
|
-
paymentMethod
|
|
179
|
-
},
|
|
180
|
-
wait: NO_WAIT
|
|
181
|
-
});
|
|
182
|
-
this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
|
|
183
|
-
return waitForTx(this.aztecNode, txHash, {
|
|
184
|
-
timeout: this.config.txMinedWaitSeconds
|
|
185
|
-
});
|
|
186
|
-
});
|
|
187
|
-
this.log.info(`Account deployed at ${address}`);
|
|
188
|
-
// Clean up the consumed bridge claim
|
|
189
|
-
await this.store.deleteBridgeClaim(address);
|
|
190
|
-
return accountManager.address;
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
async setupTestAccount() {
|
|
188
|
+
/**
|
|
189
|
+
* Keyless fallback for tests and local dev: reuses the first genesis test account, whose address is
|
|
190
|
+
* pre-funded with fee juice via `initialFundedAccounts`. The test accounts are initializerless, so this
|
|
191
|
+
* must create an initializerless account for the address to match the funded one. Production bots set a
|
|
192
|
+
* sender private key and fund the resulting initializerless account from L1 instead; see
|
|
193
|
+
* setupAccountWithPrivateKey.
|
|
194
|
+
*/ async setupTestAccount() {
|
|
194
195
|
const [initialAccountData] = await getInitialTestAccountsData();
|
|
195
|
-
const accountManager = await this.wallet.
|
|
196
|
+
const accountManager = await this.wallet.createSchnorrInitializerlessAccount(initialAccountData.secret, initialAccountData.salt, initialAccountData.signingKey);
|
|
196
197
|
return accountManager.address;
|
|
197
198
|
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
const address = token.address;
|
|
205
|
-
const metadata = await this.wallet.getContractMetadata(address);
|
|
206
|
-
if (metadata.isContractPublished) {
|
|
207
|
-
this.log.info(`Token at ${address.toString()} already deployed, refueling before setup`);
|
|
208
|
-
await this.ensureFeeJuiceBalance(sender, token);
|
|
209
|
-
}
|
|
210
|
-
return this.setupToken(sender);
|
|
211
|
-
}
|
|
212
|
-
/**
|
|
213
|
-
* Setup token0 for AMM with refuel-first behaviour when token already exists.
|
|
214
|
-
*/ async setupTokenContractWithOptionalEarlyRefuel(deployer, contractAddressSalt, name, ticker, decimals = 18) {
|
|
215
|
-
const deployOpts = {
|
|
216
|
-
from: deployer,
|
|
217
|
-
contractAddressSalt,
|
|
218
|
-
universalDeploy: true
|
|
219
|
-
};
|
|
220
|
-
const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
|
|
221
|
-
const instance = await deploy.getInstance(deployOpts);
|
|
222
|
-
const metadata = await this.wallet.getContractMetadata(instance.address);
|
|
223
|
-
if (metadata.isContractPublished) {
|
|
224
|
-
this.log.info(`Token ${name} at ${instance.address.toString()} already deployed, refueling before setup`);
|
|
225
|
-
const token = TokenContract.at(instance.address, this.wallet);
|
|
226
|
-
await this.ensureFeeJuiceBalance(deployer, token);
|
|
227
|
-
}
|
|
228
|
-
return this.setupTokenContract(deployer, contractAddressSalt, name, ticker, decimals);
|
|
229
|
-
}
|
|
230
|
-
async getTokenInstance(sender) {
|
|
231
|
-
const deployOpts = {
|
|
232
|
-
from: sender,
|
|
233
|
-
contractAddressSalt: this.config.tokenSalt,
|
|
234
|
-
universalDeploy: true
|
|
235
|
-
};
|
|
236
|
-
if (this.config.contract === SupportedTokenContracts.TokenContract) {
|
|
237
|
-
const deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
|
|
238
|
-
const instance = await deploy.getInstance(deployOpts);
|
|
239
|
-
return TokenContract.at(instance.address, this.wallet);
|
|
240
|
-
}
|
|
241
|
-
if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
|
|
242
|
-
const tokenSecretKey = Fr.random();
|
|
243
|
-
const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
|
|
244
|
-
const deploy = PrivateTokenContract.deployWithPublicKeys(tokenPublicKeys, this.wallet, MINT_BALANCE, sender);
|
|
245
|
-
const instance = await deploy.getInstance({
|
|
246
|
-
...deployOpts,
|
|
247
|
-
skipInstancePublication: true,
|
|
248
|
-
skipClassPublication: true,
|
|
249
|
-
skipInitialization: false
|
|
250
|
-
});
|
|
251
|
-
return PrivateTokenContract.at(instance.address, this.wallet);
|
|
252
|
-
}
|
|
253
|
-
throw new Error(`Unsupported token contract type: ${this.config.contract}`);
|
|
199
|
+
async setupAccountWithPrivateKey(privateKey) {
|
|
200
|
+
const salt = this.config.senderSalt ?? Fr.ONE;
|
|
201
|
+
const signingKey = GrumpkinScalar.fromBuffer(privateKey.toBuffer());
|
|
202
|
+
const secret = await deriveSecretKeyFromSigningKey(signingKey);
|
|
203
|
+
const accountManager = await this.wallet.createSchnorrInitializerlessAccount(secret, salt, signingKey);
|
|
204
|
+
return accountManager.address;
|
|
254
205
|
}
|
|
255
206
|
/**
|
|
256
207
|
* Checks if the token contract is deployed and deploys it if necessary.
|
|
@@ -260,26 +211,32 @@ export class BotFactory {
|
|
|
260
211
|
* @returns The TokenContract or PrivateTokenContract instance.
|
|
261
212
|
*/ async setupToken(sender) {
|
|
262
213
|
let deploy;
|
|
214
|
+
const salt = this.config.tokenSalt;
|
|
263
215
|
const deployOpts = {
|
|
264
|
-
from: sender
|
|
265
|
-
contractAddressSalt: this.config.tokenSalt,
|
|
266
|
-
universalDeploy: true
|
|
216
|
+
from: sender
|
|
267
217
|
};
|
|
268
218
|
let token;
|
|
269
219
|
if (this.config.contract === SupportedTokenContracts.TokenContract) {
|
|
270
|
-
deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18
|
|
271
|
-
|
|
220
|
+
deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, {
|
|
221
|
+
salt,
|
|
222
|
+
universalDeploy: true
|
|
223
|
+
});
|
|
224
|
+
const instance = await deploy.getInstance();
|
|
272
225
|
token = TokenContract.at(instance.address, this.wallet);
|
|
273
226
|
} else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
|
|
274
227
|
// Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
|
|
275
228
|
const tokenSecretKey = Fr.random();
|
|
276
229
|
const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
|
|
277
|
-
deploy = PrivateTokenContract.
|
|
230
|
+
deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
|
|
231
|
+
salt,
|
|
232
|
+
universalDeploy: true,
|
|
233
|
+
publicKeys: tokenPublicKeys
|
|
234
|
+
});
|
|
278
235
|
deployOpts.skipInstancePublication = true;
|
|
279
236
|
deployOpts.skipClassPublication = true;
|
|
280
237
|
deployOpts.skipInitialization = false;
|
|
281
238
|
// Register the contract with the secret key before deployment
|
|
282
|
-
const tokenInstance = await deploy.getInstance(
|
|
239
|
+
const tokenInstance = await deploy.getInstance();
|
|
283
240
|
token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
|
|
284
241
|
await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
|
|
285
242
|
// The contract constructor initializes private storage vars that need the contract's own nullifier key.
|
|
@@ -296,57 +253,56 @@ export class BotFactory {
|
|
|
296
253
|
* Checks if the token contract is deployed and deploys it if necessary.
|
|
297
254
|
* @param wallet - Wallet to deploy the token contract from.
|
|
298
255
|
* @returns The TokenContract instance.
|
|
299
|
-
*/ async setupTokenContract(deployer,
|
|
256
|
+
*/ async setupTokenContract(deployer, salt, name, ticker, decimals = 18) {
|
|
300
257
|
const deployOpts = {
|
|
301
|
-
from: deployer
|
|
302
|
-
contractAddressSalt,
|
|
303
|
-
universalDeploy: true
|
|
258
|
+
from: deployer
|
|
304
259
|
};
|
|
305
|
-
const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals
|
|
260
|
+
const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, {
|
|
261
|
+
salt,
|
|
262
|
+
universalDeploy: true
|
|
263
|
+
});
|
|
306
264
|
const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
|
|
307
265
|
return TokenContract.at(instance.address, this.wallet);
|
|
308
266
|
}
|
|
309
|
-
async
|
|
310
|
-
const
|
|
311
|
-
from: deployer
|
|
312
|
-
|
|
313
|
-
universalDeploy: true
|
|
314
|
-
};
|
|
315
|
-
const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
|
|
316
|
-
const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
|
|
267
|
+
async deployAmmContract(deployer, deploy) {
|
|
268
|
+
const instance = await this.registerOrDeployContract('AMM', deploy, {
|
|
269
|
+
from: deployer
|
|
270
|
+
});
|
|
317
271
|
const amm = AMMContract.at(instance.address, this.wallet);
|
|
318
272
|
this.log.info(`AMM deployed at ${amm.address}`);
|
|
319
|
-
|
|
320
|
-
|
|
273
|
+
return amm;
|
|
274
|
+
}
|
|
275
|
+
/** Grants the AMM minting rights over the LP token. set_minter only records the address, so it does not
|
|
276
|
+
* require the AMM contract to be deployed first. */ async grantLpTokenMinter(deployer, lpToken, amm) {
|
|
277
|
+
const { receipt } = await lpToken.methods.set_minter(amm, true).send({
|
|
321
278
|
from: deployer,
|
|
322
279
|
wait: {
|
|
323
280
|
timeout: this.config.txMinedWaitSeconds
|
|
324
281
|
}
|
|
325
282
|
});
|
|
326
|
-
this.log.info(`Set LP token minter to AMM txHash=${
|
|
327
|
-
this.log.info(`Liquidity token initialized`);
|
|
328
|
-
return amm;
|
|
283
|
+
this.log.info(`Set LP token minter to AMM txHash=${receipt.txHash.toString()}`);
|
|
329
284
|
}
|
|
330
|
-
async
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
285
|
+
async mintAmmLiquidity(minter, token0, token1) {
|
|
286
|
+
this.log.info(`Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1 for ${minter}`);
|
|
287
|
+
const mintBatch = new BatchCall(this.wallet, [
|
|
288
|
+
token0.methods.mint_to_private(minter, MINT_BALANCE),
|
|
289
|
+
token1.methods.mint_to_private(minter, MINT_BALANCE)
|
|
290
|
+
]);
|
|
291
|
+
const { receipt } = await mintBatch.send({
|
|
292
|
+
from: minter,
|
|
293
|
+
wait: {
|
|
294
|
+
timeout: this.config.txMinedWaitSeconds
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
this.log.info(`Sent mint tx: ${receipt.txHash.toString()}`);
|
|
298
|
+
}
|
|
299
|
+
async addAmmLiquidity(defaultAccountAddress, liquidityProvider, amm, token0, token1, lpToken) {
|
|
342
300
|
const authwitNonce = Fr.random();
|
|
343
301
|
// keep some tokens for swapping
|
|
344
302
|
const amount0Max = MINT_BALANCE / 2;
|
|
345
303
|
const amount0Min = MINT_BALANCE / 4;
|
|
346
304
|
const amount1Max = MINT_BALANCE / 2;
|
|
347
305
|
const amount1Min = MINT_BALANCE / 4;
|
|
348
|
-
const [t0Bal, t1Bal, lpBal] = await getPrivateBalances();
|
|
349
|
-
this.log.info(`Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1. Current private balances of ${liquidityProvider}: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`);
|
|
350
306
|
// Add authwitnesses for the transfers in AMM::add_liquidity function
|
|
351
307
|
const token0Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
|
|
352
308
|
caller: amm.address,
|
|
@@ -356,19 +312,7 @@ export class BotFactory {
|
|
|
356
312
|
caller: amm.address,
|
|
357
313
|
call: await token1.methods.transfer_to_public_and_prepare_private_balance_increase(liquidityProvider, amm.address, amount1Max, authwitNonce).getFunctionCall()
|
|
358
314
|
});
|
|
359
|
-
const
|
|
360
|
-
token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
|
|
361
|
-
token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE)
|
|
362
|
-
]);
|
|
363
|
-
const { receipt: mintReceipt } = await mintBatch.send({
|
|
364
|
-
from: liquidityProvider,
|
|
365
|
-
wait: {
|
|
366
|
-
timeout: this.config.txMinedWaitSeconds
|
|
367
|
-
}
|
|
368
|
-
});
|
|
369
|
-
this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
|
|
370
|
-
const addLiquidityInteraction = amm.methods.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce);
|
|
371
|
-
const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
|
|
315
|
+
const { receipt } = await amm.methods.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce).send({
|
|
372
316
|
from: liquidityProvider,
|
|
373
317
|
authWitnesses: [
|
|
374
318
|
token0Authwit,
|
|
@@ -378,95 +322,60 @@ export class BotFactory {
|
|
|
378
322
|
timeout: this.config.txMinedWaitSeconds
|
|
379
323
|
}
|
|
380
324
|
});
|
|
381
|
-
this.log.info(`Sent tx to add liquidity to the AMM: ${
|
|
325
|
+
this.log.info(`Sent tx to add liquidity to the AMM: ${receipt.txHash.toString()}`);
|
|
382
326
|
this.log.info(`Liquidity added`);
|
|
383
|
-
const [
|
|
384
|
-
|
|
327
|
+
const [t0Bal, t1Bal, lpBal] = await Promise.all([
|
|
328
|
+
token0.methods.balance_of_private(liquidityProvider).simulate({
|
|
329
|
+
from: liquidityProvider
|
|
330
|
+
}).then((r)=>r.result),
|
|
331
|
+
token1.methods.balance_of_private(liquidityProvider).simulate({
|
|
332
|
+
from: liquidityProvider
|
|
333
|
+
}).then((r)=>r.result),
|
|
334
|
+
lpToken.methods.balance_of_private(liquidityProvider).simulate({
|
|
335
|
+
from: liquidityProvider
|
|
336
|
+
}).then((r)=>r.result)
|
|
337
|
+
]);
|
|
338
|
+
this.log.info(`Updated private balances of ${defaultAccountAddress} after minting and funding AMM: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`);
|
|
385
339
|
}
|
|
386
340
|
async registerOrDeployContract(name, deploy, deployOpts) {
|
|
387
|
-
const instance = await deploy.getInstance(
|
|
341
|
+
const instance = await deploy.getInstance();
|
|
388
342
|
const address = instance.address;
|
|
389
343
|
const metadata = await this.wallet.getContractMetadata(address);
|
|
390
344
|
if (metadata.isContractPublished) {
|
|
391
345
|
this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
|
|
392
346
|
await deploy.register();
|
|
393
|
-
|
|
394
|
-
const sender = deployOpts.from === NO_FROM ? undefined : deployOpts.from;
|
|
395
|
-
const balance = sender ? await getFeeJuiceBalance(sender, this.aztecNode) : 0n;
|
|
396
|
-
const useClaim = sender && balance < FEE_JUICE_TOP_UP_THRESHOLD && this.config.feePaymentMethod === 'fee_juice' && !!this.config.l1RpcUrls?.length;
|
|
397
|
-
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
398
|
-
if (useClaim && mnemonicOrPrivateKey) {
|
|
399
|
-
const claim = await this.getOrCreateBridgeClaim(sender);
|
|
400
|
-
const paymentMethod = new FeeJuicePaymentMethodWithClaim(sender, claim);
|
|
401
|
-
const { estimatedGas } = await deploy.simulate({
|
|
402
|
-
...deployOpts,
|
|
403
|
-
fee: {
|
|
404
|
-
estimateGas: true,
|
|
405
|
-
paymentMethod
|
|
406
|
-
}
|
|
407
|
-
});
|
|
408
|
-
const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
|
|
409
|
-
const gasSettings = GasSettings.from({
|
|
410
|
-
...estimatedGas,
|
|
411
|
-
maxFeesPerGas,
|
|
412
|
-
maxPriorityFeesPerGas: GasFees.empty()
|
|
413
|
-
});
|
|
414
|
-
await this.withNoMinTxsPerBlock(async ()=>{
|
|
415
|
-
const { txHash } = await deploy.send({
|
|
416
|
-
...deployOpts,
|
|
417
|
-
fee: {
|
|
418
|
-
gasSettings,
|
|
419
|
-
paymentMethod
|
|
420
|
-
},
|
|
421
|
-
wait: NO_WAIT
|
|
422
|
-
});
|
|
423
|
-
this.log.info(`Sent contract ${name} deploy tx ${txHash.toString()} (using bridge claim, balance was ${balance})`);
|
|
424
|
-
return waitForTx(this.aztecNode, txHash, {
|
|
425
|
-
timeout: this.config.txMinedWaitSeconds
|
|
426
|
-
});
|
|
427
|
-
});
|
|
428
|
-
await this.store.deleteBridgeClaim(sender);
|
|
429
|
-
} else {
|
|
430
|
-
const { estimatedGas } = await deploy.simulate({
|
|
431
|
-
...deployOpts,
|
|
432
|
-
fee: {
|
|
433
|
-
estimateGas: true
|
|
434
|
-
}
|
|
435
|
-
});
|
|
436
|
-
this.log.info(`Deploying contract ${name} at ${address.toString()}`, {
|
|
437
|
-
estimatedGas
|
|
438
|
-
});
|
|
439
|
-
await this.withNoMinTxsPerBlock(async ()=>{
|
|
440
|
-
const { txHash } = await deploy.send({
|
|
441
|
-
...deployOpts,
|
|
442
|
-
fee: {
|
|
443
|
-
gasSettings: estimatedGas
|
|
444
|
-
},
|
|
445
|
-
wait: NO_WAIT
|
|
446
|
-
});
|
|
447
|
-
this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
|
|
448
|
-
return waitForTx(this.aztecNode, txHash, {
|
|
449
|
-
timeout: this.config.txMinedWaitSeconds
|
|
450
|
-
});
|
|
451
|
-
});
|
|
452
|
-
}
|
|
347
|
+
return instance;
|
|
453
348
|
}
|
|
349
|
+
// Setup always runs ensureFeeJuiceBalance before any deploy, so the account pays from its standing
|
|
350
|
+
// balance here. No manual gas estimation: the embedded wallet simulates before sending and derives
|
|
351
|
+
// the gas limits and padded maxFeesPerGas itself.
|
|
352
|
+
this.log.info(`Deploying contract ${name} at ${address.toString()}`);
|
|
353
|
+
await this.withNoMinTxsPerBlock(async ()=>{
|
|
354
|
+
const { txHash } = await deploy.send({
|
|
355
|
+
...deployOpts,
|
|
356
|
+
wait: NO_WAIT
|
|
357
|
+
});
|
|
358
|
+
this.log.info(`Sent contract ${name} deploy tx ${txHash.toString()}`);
|
|
359
|
+
return waitForTx(this.aztecNode, txHash, {
|
|
360
|
+
timeout: this.config.txMinedWaitSeconds
|
|
361
|
+
});
|
|
362
|
+
});
|
|
454
363
|
return instance;
|
|
455
364
|
}
|
|
456
|
-
/**
|
|
457
|
-
* Mints private and public tokens for the sender if their balance is below the minimum.
|
|
458
|
-
* @param token - Token contract.
|
|
459
|
-
*/ /**
|
|
460
|
-
* Ensures the account has sufficient fee juice by bridging from L1 if balance is below threshold.
|
|
461
|
-
* Bridges repeatedly until balance reaches the target (10k FJ).
|
|
462
|
-
* Used on startup/restart to top up when the account has run out after previous runs.
|
|
463
|
-
*/ async ensureFeeJuiceBalance(account, token) {
|
|
464
|
-
const { feePaymentMethod, l1RpcUrls } = this.config;
|
|
465
|
-
if (feePaymentMethod !== 'fee_juice' || !l1RpcUrls?.length) {
|
|
466
|
-
return;
|
|
467
|
-
}
|
|
365
|
+
/** True when the config allows bridging fee juice from L1 (fee_juice mode, an L1 RPC, and an L1 key). */ isL1BridgingConfigured() {
|
|
468
366
|
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
469
|
-
|
|
367
|
+
return this.config.feePaymentMethod === 'fee_juice' && !!this.config.l1RpcUrls?.length && !!mnemonicOrPrivateKey;
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Ensures the account holds enough fee juice before any other setup step. The account starts empty
|
|
371
|
+
* (initializerless accounts have no deployment tx) and the runtime loop pays fees from this balance and
|
|
372
|
+
* never refuels itself, so every flow funds the account up front. Bridges claims from L1 and consumes
|
|
373
|
+
* each with a claim-only tx until the balance clears the threshold, working from a zero (fresh run) or
|
|
374
|
+
* drained (restart) balance. Each bridge mints a fixed amount well above the threshold, so this is a
|
|
375
|
+
* single bridge in practice. No-op when L1 bridging is not configured or the balance is already above
|
|
376
|
+
* the threshold.
|
|
377
|
+
*/ async ensureFeeJuiceBalance(account) {
|
|
378
|
+
if (!this.isL1BridgingConfigured()) {
|
|
470
379
|
return;
|
|
471
380
|
}
|
|
472
381
|
let balance = await getFeeJuiceBalance(account, this.aztecNode);
|
|
@@ -474,31 +383,16 @@ export class BotFactory {
|
|
|
474
383
|
this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
|
|
475
384
|
return;
|
|
476
385
|
}
|
|
477
|
-
this.log.info(`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
const claim = await this.
|
|
386
|
+
this.log.info(`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1`);
|
|
387
|
+
while(balance < FEE_JUICE_TOP_UP_THRESHOLD){
|
|
388
|
+
// Persist the claim before consuming it: if the top-up tx fails or the bot crashes mid-loop, the
|
|
389
|
+
// next run reuses the pending claim instead of bridging again (and wasting the bridged funds).
|
|
390
|
+
const claim = await this.getOrCreateBridgeClaim(account);
|
|
482
391
|
const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
|
|
483
|
-
const { estimatedGas } = await minimalInteraction.simulate({
|
|
484
|
-
from: account,
|
|
485
|
-
fee: {
|
|
486
|
-
estimateGas: true,
|
|
487
|
-
paymentMethod
|
|
488
|
-
}
|
|
489
|
-
});
|
|
490
|
-
const gasSettings = GasSettings.from({
|
|
491
|
-
...estimatedGas,
|
|
492
|
-
maxFeesPerGas,
|
|
493
|
-
maxPriorityFeesPerGas: GasFees.empty()
|
|
494
|
-
});
|
|
495
392
|
await this.withNoMinTxsPerBlock(async ()=>{
|
|
496
|
-
const
|
|
393
|
+
const executionPayload = await paymentMethod.getExecutionPayload();
|
|
394
|
+
const { txHash } = await this.wallet.sendTx(executionPayload, {
|
|
497
395
|
from: account,
|
|
498
|
-
fee: {
|
|
499
|
-
gasSettings,
|
|
500
|
-
paymentMethod
|
|
501
|
-
},
|
|
502
396
|
wait: NO_WAIT
|
|
503
397
|
});
|
|
504
398
|
this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
|
|
@@ -506,6 +400,7 @@ export class BotFactory {
|
|
|
506
400
|
timeout: this.config.txMinedWaitSeconds
|
|
507
401
|
});
|
|
508
402
|
});
|
|
403
|
+
await this.store.deleteBridgeClaim(account);
|
|
509
404
|
balance = await getFeeJuiceBalance(account, this.aztecNode);
|
|
510
405
|
this.log.info(`Fee juice balance after top-up: ${balance}`);
|
|
511
406
|
}
|
|
@@ -551,19 +446,18 @@ export class BotFactory {
|
|
|
551
446
|
});
|
|
552
447
|
}
|
|
553
448
|
/**
|
|
554
|
-
*
|
|
555
|
-
*
|
|
556
|
-
*
|
|
449
|
+
* Returns a usable bridge claim for the recipient, reusing a persisted one when its L1→L2 message is
|
|
450
|
+
* still available (resuming a top-up that failed or crashed before the claim was consumed) and bridging
|
|
451
|
+
* a fresh claim otherwise. The caller deletes the claim from the store once it has been consumed.
|
|
557
452
|
*/ async getOrCreateBridgeClaim(recipient) {
|
|
558
|
-
// Check if we have an existing claim in the store
|
|
559
453
|
const existingClaim = await this.store.getBridgeClaim(recipient);
|
|
560
454
|
if (existingClaim) {
|
|
561
455
|
this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
|
|
562
|
-
// Check if the message is ready on L2
|
|
563
456
|
try {
|
|
564
457
|
const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
|
|
565
458
|
await this.withNoMinTxsPerBlock(()=>waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
|
|
566
|
-
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds
|
|
459
|
+
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
460
|
+
chainTip: this.syncChainTip
|
|
567
461
|
}));
|
|
568
462
|
return existingClaim.claim;
|
|
569
463
|
} catch (err) {
|
|
@@ -591,7 +485,8 @@ export class BotFactory {
|
|
|
591
485
|
const mintAmount = await portal.getTokenManager().getMintAmount();
|
|
592
486
|
const claim = await portal.bridgeTokensPublic(recipient, mintAmount, true);
|
|
593
487
|
await this.withNoMinTxsPerBlock(()=>waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
|
|
594
|
-
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds
|
|
488
|
+
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
489
|
+
chainTip: this.syncChainTip
|
|
595
490
|
}));
|
|
596
491
|
this.log.info(`Created a claim for ${mintAmount} L1 fee juice to ${recipient}.`, claim);
|
|
597
492
|
return claim;
|
|
@@ -601,18 +496,37 @@ export class BotFactory {
|
|
|
601
496
|
this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
|
|
602
497
|
return fn();
|
|
603
498
|
}
|
|
604
|
-
const
|
|
605
|
-
this
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
499
|
+
const aztecNodeAdmin = this.aztecNodeAdmin;
|
|
500
|
+
// Setup steps run concurrently, so this wrapper can be re-entered while another call is in flight.
|
|
501
|
+
// Reference-count the entrants: the first saves the current value and zeroes it, the last restores it.
|
|
502
|
+
// A naive save/zero/restore per call could interleave, with a late entrant reading the already-zeroed
|
|
503
|
+
// value and "restoring" 0 at the end.
|
|
504
|
+
if (this.noMinTxsPerBlockDepth++ === 0) {
|
|
505
|
+
this.savedMinTxsPerBlock = (async ()=>{
|
|
506
|
+
const { minTxsPerBlock } = await aztecNodeAdmin.getConfig();
|
|
507
|
+
this.log.warn(`Setting sequencer minTxsPerBlock to 0 from ${minTxsPerBlock} to flush setup transactions`);
|
|
508
|
+
await aztecNodeAdmin.setConfig({
|
|
509
|
+
minTxsPerBlock: 0
|
|
510
|
+
});
|
|
511
|
+
return {
|
|
512
|
+
minTxsPerBlock
|
|
513
|
+
};
|
|
514
|
+
})();
|
|
515
|
+
}
|
|
609
516
|
try {
|
|
517
|
+
await this.savedMinTxsPerBlock;
|
|
610
518
|
return await fn();
|
|
611
519
|
} finally{
|
|
612
|
-
this.
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
520
|
+
if (--this.noMinTxsPerBlockDepth === 0) {
|
|
521
|
+
// If saving/zeroing itself failed there is nothing to restore.
|
|
522
|
+
const saved = await this.savedMinTxsPerBlock.catch(()=>undefined);
|
|
523
|
+
if (saved) {
|
|
524
|
+
this.log.warn(`Restoring sequencer minTxsPerBlock to ${saved.minTxsPerBlock}`);
|
|
525
|
+
await aztecNodeAdmin.setConfig({
|
|
526
|
+
minTxsPerBlock: saved.minTxsPerBlock
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
}
|
|
616
530
|
}
|
|
617
531
|
}
|
|
618
532
|
}
|