@aztec/bot 0.0.1-commit.3469e52 → 0.0.1-commit.350e0a4d
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 +7 -7
- package/dest/amm_bot.d.ts.map +1 -1
- package/dest/amm_bot.js +30 -19
- package/dest/base_bot.d.ts +8 -8
- package/dest/base_bot.d.ts.map +1 -1
- package/dest/base_bot.js +24 -35
- package/dest/bot.d.ts +7 -6
- package/dest/bot.d.ts.map +1 -1
- package/dest/bot.js +11 -11
- package/dest/config.d.ts +47 -82
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +42 -15
- package/dest/cross_chain_bot.d.ts +56 -0
- package/dest/cross_chain_bot.d.ts.map +1 -0
- package/dest/cross_chain_bot.js +138 -0
- package/dest/factory.d.ts +25 -11
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +241 -141
- package/dest/index.d.ts +2 -1
- package/dest/index.d.ts.map +1 -1
- package/dest/index.js +1 -0
- package/dest/interface.d.ts +2 -6
- package/dest/interface.d.ts.map +1 -1
- package/dest/interface.js +30 -7
- package/dest/l1_to_l2_seeding.d.ts +8 -0
- package/dest/l1_to_l2_seeding.d.ts.map +1 -0
- package/dest/l1_to_l2_seeding.js +63 -0
- package/dest/runner.d.ts +4 -3
- package/dest/runner.d.ts.map +1 -1
- package/dest/runner.js +20 -2
- package/dest/store/bot_store.d.ts +30 -5
- package/dest/store/bot_store.d.ts.map +1 -1
- package/dest/store/bot_store.js +37 -6
- package/dest/store/index.d.ts +2 -2
- package/dest/store/index.d.ts.map +1 -1
- package/dest/utils.js +3 -3
- package/package.json +17 -14
- package/src/amm_bot.ts +30 -22
- package/src/base_bot.ts +19 -40
- package/src/bot.ts +14 -12
- package/src/config.ts +47 -18
- package/src/cross_chain_bot.ts +208 -0
- package/src/factory.ts +276 -129
- package/src/index.ts +1 -0
- package/src/interface.ts +7 -7
- package/src/l1_to_l2_seeding.ts +79 -0
- package/src/runner.ts +41 -5
- package/src/store/bot_store.ts +60 -5
- package/src/store/index.ts +1 -1
- package/src/utils.ts +3 -3
package/src/factory.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { SchnorrAccountContract } from '@aztec/accounts/schnorr';
|
|
2
1
|
import { getInitialTestAccountsData } from '@aztec/accounts/testing';
|
|
3
2
|
import { AztecAddress } from '@aztec/aztec.js/addresses';
|
|
4
3
|
import {
|
|
@@ -7,64 +6,78 @@ import {
|
|
|
7
6
|
ContractFunctionInteraction,
|
|
8
7
|
type DeployMethod,
|
|
9
8
|
type DeployOptions,
|
|
9
|
+
NO_WAIT,
|
|
10
10
|
} from '@aztec/aztec.js/contracts';
|
|
11
|
-
import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
|
|
12
11
|
import type { L2AmountClaim } from '@aztec/aztec.js/ethereum';
|
|
12
|
+
import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
|
|
13
13
|
import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
|
|
14
14
|
import { deriveKeys } from '@aztec/aztec.js/keys';
|
|
15
15
|
import { createLogger } from '@aztec/aztec.js/log';
|
|
16
16
|
import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
|
|
17
|
+
import { waitForTx } from '@aztec/aztec.js/node';
|
|
18
|
+
import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
|
|
17
19
|
import { createEthereumChain } from '@aztec/ethereum/chain';
|
|
18
20
|
import { createExtendedL1Client } from '@aztec/ethereum/client';
|
|
21
|
+
import { RollupContract } from '@aztec/ethereum/contracts';
|
|
22
|
+
import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
|
|
19
23
|
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
20
|
-
import {
|
|
24
|
+
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
21
25
|
import { AMMContract } from '@aztec/noir-contracts.js/AMM';
|
|
22
26
|
import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
|
|
23
27
|
import { TokenContract } from '@aztec/noir-contracts.js/Token';
|
|
28
|
+
import { TestContract } from '@aztec/noir-test-contracts.js/Test';
|
|
29
|
+
import type { BlockTag } from '@aztec/stdlib/block';
|
|
24
30
|
import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
|
|
25
|
-
import { GasSettings } from '@aztec/stdlib/gas';
|
|
26
31
|
import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
|
|
27
32
|
import { deriveSigningKey } from '@aztec/stdlib/keys';
|
|
28
|
-
import {
|
|
33
|
+
import { EmbeddedWallet } from '@aztec/wallets/embedded';
|
|
29
34
|
|
|
30
35
|
import { type BotConfig, SupportedTokenContracts } from './config.js';
|
|
36
|
+
import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
|
|
31
37
|
import type { BotStore } from './store/index.js';
|
|
32
38
|
import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
|
|
33
39
|
|
|
34
40
|
const MINT_BALANCE = 1e12;
|
|
35
41
|
const MIN_BALANCE = 1e3;
|
|
42
|
+
const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
|
|
36
43
|
|
|
37
44
|
export class BotFactory {
|
|
38
45
|
private log = createLogger('bot');
|
|
39
46
|
|
|
40
47
|
constructor(
|
|
41
48
|
private readonly config: BotConfig,
|
|
42
|
-
private readonly wallet:
|
|
49
|
+
private readonly wallet: EmbeddedWallet,
|
|
43
50
|
private readonly store: BotStore,
|
|
44
51
|
private readonly aztecNode: AztecNode,
|
|
45
52
|
private readonly aztecNodeAdmin?: AztecNodeAdmin,
|
|
46
|
-
|
|
53
|
+
private readonly syncChainTip?: BlockTag,
|
|
54
|
+
) {
|
|
55
|
+
// Set fee padding on the wallet so that all transactions during setup
|
|
56
|
+
// (token deploy, minting, etc.) use the configured padding, not the default.
|
|
57
|
+
this.wallet.setMinFeePadding(config.minFeePadding);
|
|
58
|
+
}
|
|
47
59
|
|
|
48
60
|
/**
|
|
49
61
|
* Initializes a new bot by setting up the sender account, registering the recipient,
|
|
50
62
|
* deploying the token contract, and minting tokens if necessary.
|
|
51
63
|
*/
|
|
52
64
|
public async setup(): Promise<{
|
|
53
|
-
wallet:
|
|
65
|
+
wallet: EmbeddedWallet;
|
|
54
66
|
defaultAccountAddress: AztecAddress;
|
|
55
67
|
token: TokenContract | PrivateTokenContract;
|
|
56
68
|
node: AztecNode;
|
|
57
69
|
recipient: AztecAddress;
|
|
58
70
|
}> {
|
|
59
71
|
const defaultAccountAddress = await this.setupAccount();
|
|
60
|
-
const recipient = (await this.wallet.
|
|
72
|
+
const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
|
|
73
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress);
|
|
61
74
|
const token = await this.setupToken(defaultAccountAddress);
|
|
62
75
|
await this.mintTokens(token, defaultAccountAddress);
|
|
63
76
|
return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
|
|
64
77
|
}
|
|
65
78
|
|
|
66
79
|
public async setupAmm(): Promise<{
|
|
67
|
-
wallet:
|
|
80
|
+
wallet: EmbeddedWallet;
|
|
68
81
|
defaultAccountAddress: AztecAddress;
|
|
69
82
|
amm: AMMContract;
|
|
70
83
|
token0: TokenContract;
|
|
@@ -72,6 +85,7 @@ export class BotFactory {
|
|
|
72
85
|
node: AztecNode;
|
|
73
86
|
}> {
|
|
74
87
|
const defaultAccountAddress = await this.setupAccount();
|
|
88
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress);
|
|
75
89
|
const token0 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
|
|
76
90
|
const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
|
|
77
91
|
const liquidityToken = await this.setupTokenContract(
|
|
@@ -94,6 +108,87 @@ export class BotFactory {
|
|
|
94
108
|
return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
|
|
95
109
|
}
|
|
96
110
|
|
|
111
|
+
/**
|
|
112
|
+
* Initializes the cross-chain bot by deploying TestContract, creating an L1 client,
|
|
113
|
+
* seeding initial L1→L2 messages, and waiting for the first to be ready.
|
|
114
|
+
*/
|
|
115
|
+
public async setupCrossChain(): Promise<{
|
|
116
|
+
wallet: EmbeddedWallet;
|
|
117
|
+
defaultAccountAddress: AztecAddress;
|
|
118
|
+
contract: TestContract;
|
|
119
|
+
node: AztecNode;
|
|
120
|
+
l1Client: ExtendedViemWalletClient;
|
|
121
|
+
rollupVersion: bigint;
|
|
122
|
+
}> {
|
|
123
|
+
const defaultAccountAddress = await this.setupAccount();
|
|
124
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress);
|
|
125
|
+
|
|
126
|
+
// Create L1 client (same pattern as bridgeL1FeeJuice)
|
|
127
|
+
const l1RpcUrls = this.config.l1RpcUrls;
|
|
128
|
+
if (!l1RpcUrls?.length) {
|
|
129
|
+
throw new Error('L1 RPC URLs required for cross-chain bot');
|
|
130
|
+
}
|
|
131
|
+
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
132
|
+
if (!mnemonicOrPrivateKey) {
|
|
133
|
+
throw new Error('L1 mnemonic or private key required for cross-chain bot');
|
|
134
|
+
}
|
|
135
|
+
const { l1ChainId, l1ContractAddresses } = await this.aztecNode.getNodeInfo();
|
|
136
|
+
const chain = createEthereumChain(l1RpcUrls, l1ChainId);
|
|
137
|
+
const l1Client = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
|
|
138
|
+
|
|
139
|
+
// Fetch Rollup version (needed for Inbox L2Actor struct)
|
|
140
|
+
const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
|
|
141
|
+
const rollupVersion = await rollupContract.getVersion();
|
|
142
|
+
|
|
143
|
+
// Deploy TestContract (pays from the standing balance funded above).
|
|
144
|
+
const contract = await this.setupTestContract(defaultAccountAddress);
|
|
145
|
+
|
|
146
|
+
// Recover any pending messages from store (clean up stale ones first)
|
|
147
|
+
await this.store.cleanupOldPendingMessages();
|
|
148
|
+
const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
149
|
+
|
|
150
|
+
// Seed initial L1→L2 messages if pipeline is empty
|
|
151
|
+
const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
|
|
152
|
+
for (let i = 0; i < seedCount; i++) {
|
|
153
|
+
await seedL1ToL2Message(
|
|
154
|
+
l1Client,
|
|
155
|
+
EthAddress.fromString(l1ContractAddresses.inboxAddress.toString()),
|
|
156
|
+
contract.address,
|
|
157
|
+
rollupVersion,
|
|
158
|
+
this.store,
|
|
159
|
+
this.log,
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Block until at least one message is ready
|
|
164
|
+
const allMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
165
|
+
if (allMessages.length > 0) {
|
|
166
|
+
this.log.info(`Waiting for first L1→L2 message to be ready...`);
|
|
167
|
+
const firstMsg = allMessages[0];
|
|
168
|
+
await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
|
|
169
|
+
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
170
|
+
chainTip: this.syncChainTip,
|
|
171
|
+
});
|
|
172
|
+
this.log.info(`First L1→L2 message is ready`);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return {
|
|
176
|
+
wallet: this.wallet,
|
|
177
|
+
defaultAccountAddress,
|
|
178
|
+
contract,
|
|
179
|
+
node: this.aztecNode,
|
|
180
|
+
l1Client,
|
|
181
|
+
rollupVersion,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
private async setupTestContract(deployer: AztecAddress): Promise<TestContract> {
|
|
186
|
+
const deployOpts: DeployOptions = { from: deployer };
|
|
187
|
+
const deploy = TestContract.deploy(this.wallet, { salt: this.config.tokenSalt, universalDeploy: true });
|
|
188
|
+
const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
|
|
189
|
+
return TestContract.at(instance.address, this.wallet);
|
|
190
|
+
}
|
|
191
|
+
|
|
97
192
|
/**
|
|
98
193
|
* Checks if the sender account contract is initialized, and initializes it if necessary.
|
|
99
194
|
* @returns The sender wallet.
|
|
@@ -109,100 +204,71 @@ export class BotFactory {
|
|
|
109
204
|
}
|
|
110
205
|
}
|
|
111
206
|
|
|
207
|
+
/**
|
|
208
|
+
* Keyless fallback for tests and local dev: reuses the first genesis test account, whose address is
|
|
209
|
+
* pre-funded with fee juice via `initialFundedAccounts`. The test accounts are initializerless, so this
|
|
210
|
+
* must create an initializerless account for the address to match the funded one. Production bots set a
|
|
211
|
+
* sender private key and fund the resulting initializerless account from L1 instead; see
|
|
212
|
+
* setupAccountWithPrivateKey.
|
|
213
|
+
*/
|
|
214
|
+
private async setupTestAccount() {
|
|
215
|
+
const [initialAccountData] = await getInitialTestAccountsData();
|
|
216
|
+
const accountManager = await this.wallet.createSchnorrInitializerlessAccount(
|
|
217
|
+
initialAccountData.secret,
|
|
218
|
+
initialAccountData.salt,
|
|
219
|
+
initialAccountData.signingKey,
|
|
220
|
+
);
|
|
221
|
+
return accountManager.address;
|
|
222
|
+
}
|
|
223
|
+
|
|
112
224
|
private async setupAccountWithPrivateKey(secret: Fr) {
|
|
113
225
|
const salt = this.config.senderSalt ?? Fr.ONE;
|
|
114
226
|
const signingKey = deriveSigningKey(secret);
|
|
115
|
-
const
|
|
116
|
-
secret,
|
|
117
|
-
salt,
|
|
118
|
-
contract: new SchnorrAccountContract(signingKey!),
|
|
119
|
-
};
|
|
120
|
-
const accountManager = await this.wallet.createAccount(accountData);
|
|
121
|
-
const metadata = await this.wallet.getContractMetadata(accountManager.address);
|
|
122
|
-
if (metadata.isContractInitialized) {
|
|
123
|
-
this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
|
|
124
|
-
const timer = new Timer();
|
|
125
|
-
const address = accountManager.address;
|
|
126
|
-
this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
|
|
127
|
-
await this.store.deleteBridgeClaim(address);
|
|
128
|
-
return address;
|
|
129
|
-
} else {
|
|
130
|
-
const address = accountManager.address;
|
|
131
|
-
this.log.info(`Deploying account at ${address}`);
|
|
132
|
-
|
|
133
|
-
const claim = await this.getOrCreateBridgeClaim(address);
|
|
134
|
-
|
|
135
|
-
const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
|
|
136
|
-
const deployMethod = await accountManager.getDeployMethod();
|
|
137
|
-
const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
|
|
138
|
-
const gasSettings = GasSettings.default({ maxFeesPerGas });
|
|
139
|
-
const sentTx = deployMethod.send({ from: AztecAddress.ZERO, fee: { gasSettings, paymentMethod } });
|
|
140
|
-
const txHash = await sentTx.getTxHash();
|
|
141
|
-
this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
|
|
142
|
-
await this.withNoMinTxsPerBlock(() => sentTx.wait({ timeout: this.config.txMinedWaitSeconds }));
|
|
143
|
-
this.log.info(`Account deployed at ${address}`);
|
|
144
|
-
|
|
145
|
-
// Clean up the consumed bridge claim
|
|
146
|
-
await this.store.deleteBridgeClaim(address);
|
|
147
|
-
|
|
148
|
-
return accountManager.address;
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
private async setupTestAccount() {
|
|
153
|
-
const [initialAccountData] = await getInitialTestAccountsData();
|
|
154
|
-
const accountData = {
|
|
155
|
-
secret: initialAccountData.secret,
|
|
156
|
-
salt: initialAccountData.salt,
|
|
157
|
-
contract: new SchnorrAccountContract(initialAccountData.signingKey),
|
|
158
|
-
};
|
|
159
|
-
const accountManager = await this.wallet.createAccount(accountData);
|
|
227
|
+
const accountManager = await this.wallet.createSchnorrInitializerlessAccount(secret, salt, signingKey);
|
|
160
228
|
return accountManager.address;
|
|
161
229
|
}
|
|
162
230
|
|
|
163
231
|
/**
|
|
164
232
|
* Checks if the token contract is deployed and deploys it if necessary.
|
|
165
|
-
*
|
|
166
|
-
* @
|
|
233
|
+
* Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
|
|
234
|
+
* @param sender - Aztec address to deploy the token contract from.
|
|
235
|
+
* @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
|
|
236
|
+
* @returns The TokenContract or PrivateTokenContract instance.
|
|
167
237
|
*/
|
|
168
238
|
private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
|
|
169
239
|
let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
|
|
170
|
-
|
|
171
|
-
const deployOpts: DeployOptions = {
|
|
172
|
-
|
|
173
|
-
contractAddressSalt: this.config.tokenSalt,
|
|
174
|
-
universalDeploy: true,
|
|
175
|
-
};
|
|
240
|
+
const salt = this.config.tokenSalt;
|
|
241
|
+
const deployOpts: DeployOptions = { from: sender };
|
|
242
|
+
let token: TokenContract | PrivateTokenContract;
|
|
176
243
|
if (this.config.contract === SupportedTokenContracts.TokenContract) {
|
|
177
|
-
deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
|
|
244
|
+
deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
|
|
245
|
+
const instance = await deploy.getInstance();
|
|
246
|
+
token = TokenContract.at(instance.address, this.wallet);
|
|
178
247
|
} else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
|
|
179
248
|
// Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
|
|
180
249
|
const tokenSecretKey = Fr.random();
|
|
181
250
|
const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
|
|
182
|
-
deploy = PrivateTokenContract.
|
|
251
|
+
deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
|
|
252
|
+
salt,
|
|
253
|
+
universalDeploy: true,
|
|
254
|
+
publicKeys: tokenPublicKeys,
|
|
255
|
+
});
|
|
183
256
|
deployOpts.skipInstancePublication = true;
|
|
184
257
|
deployOpts.skipClassPublication = true;
|
|
185
258
|
deployOpts.skipInitialization = false;
|
|
186
259
|
|
|
187
260
|
// Register the contract with the secret key before deployment
|
|
188
|
-
tokenInstance = await deploy.getInstance(
|
|
261
|
+
const tokenInstance = await deploy.getInstance();
|
|
262
|
+
token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
|
|
189
263
|
await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
|
|
264
|
+
// The contract constructor initializes private storage vars that need the contract's own nullifier key.
|
|
265
|
+
deployOpts.additionalScopes = [tokenInstance.address];
|
|
190
266
|
} else {
|
|
191
267
|
throw new Error(`Unsupported token contract type: ${this.config.contract}`);
|
|
192
268
|
}
|
|
193
269
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
if (metadata.isContractPublished) {
|
|
197
|
-
this.log.info(`Token at ${address.toString()} already deployed`);
|
|
198
|
-
return deploy.register();
|
|
199
|
-
} else {
|
|
200
|
-
this.log.info(`Deploying token contract at ${address.toString()}`);
|
|
201
|
-
const sentTx = deploy.send(deployOpts);
|
|
202
|
-
const txHash = await sentTx.getTxHash();
|
|
203
|
-
this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
|
|
204
|
-
return this.withNoMinTxsPerBlock(() => sentTx.deployed({ timeout: this.config.txMinedWaitSeconds }));
|
|
205
|
-
}
|
|
270
|
+
await this.registerOrDeployContract('token', deploy, deployOpts);
|
|
271
|
+
return token;
|
|
206
272
|
}
|
|
207
273
|
|
|
208
274
|
/**
|
|
@@ -210,33 +276,41 @@ export class BotFactory {
|
|
|
210
276
|
* @param wallet - Wallet to deploy the token contract from.
|
|
211
277
|
* @returns The TokenContract instance.
|
|
212
278
|
*/
|
|
213
|
-
private setupTokenContract(
|
|
279
|
+
private async setupTokenContract(
|
|
214
280
|
deployer: AztecAddress,
|
|
215
|
-
|
|
281
|
+
salt: Fr,
|
|
216
282
|
name: string,
|
|
217
283
|
ticker: string,
|
|
218
284
|
decimals = 18,
|
|
219
285
|
): Promise<TokenContract> {
|
|
220
|
-
const deployOpts: DeployOptions = { from: deployer
|
|
221
|
-
const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
|
|
222
|
-
|
|
286
|
+
const deployOpts: DeployOptions = { from: deployer };
|
|
287
|
+
const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
|
|
288
|
+
const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
|
|
289
|
+
return TokenContract.at(instance.address, this.wallet);
|
|
223
290
|
}
|
|
224
291
|
|
|
225
292
|
private async setupAmmContract(
|
|
226
293
|
deployer: AztecAddress,
|
|
227
|
-
|
|
294
|
+
salt: Fr,
|
|
228
295
|
token0: TokenContract,
|
|
229
296
|
token1: TokenContract,
|
|
230
297
|
lpToken: TokenContract,
|
|
231
298
|
): Promise<AMMContract> {
|
|
232
|
-
const deployOpts: DeployOptions = { from: deployer
|
|
233
|
-
const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address
|
|
234
|
-
|
|
299
|
+
const deployOpts: DeployOptions = { from: deployer };
|
|
300
|
+
const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address, {
|
|
301
|
+
salt,
|
|
302
|
+
universalDeploy: true,
|
|
303
|
+
});
|
|
304
|
+
const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
|
|
305
|
+
const amm = AMMContract.at(instance.address, this.wallet);
|
|
235
306
|
|
|
236
307
|
this.log.info(`AMM deployed at ${amm.address}`);
|
|
237
|
-
const
|
|
238
|
-
|
|
239
|
-
|
|
308
|
+
const setMinterInteraction = lpToken.methods.set_minter(amm.address, true);
|
|
309
|
+
const { receipt: minterReceipt } = await setMinterInteraction.send({
|
|
310
|
+
from: deployer,
|
|
311
|
+
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
312
|
+
});
|
|
313
|
+
this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
|
|
240
314
|
this.log.info(`Liquidity token initialized`);
|
|
241
315
|
|
|
242
316
|
return amm;
|
|
@@ -252,9 +326,18 @@ export class BotFactory {
|
|
|
252
326
|
): Promise<void> {
|
|
253
327
|
const getPrivateBalances = () =>
|
|
254
328
|
Promise.all([
|
|
255
|
-
token0.methods
|
|
256
|
-
|
|
257
|
-
|
|
329
|
+
token0.methods
|
|
330
|
+
.balance_of_private(liquidityProvider)
|
|
331
|
+
.simulate({ from: liquidityProvider })
|
|
332
|
+
.then(r => r.result),
|
|
333
|
+
token1.methods
|
|
334
|
+
.balance_of_private(liquidityProvider)
|
|
335
|
+
.simulate({ from: liquidityProvider })
|
|
336
|
+
.then(r => r.result),
|
|
337
|
+
lpToken.methods
|
|
338
|
+
.balance_of_private(liquidityProvider)
|
|
339
|
+
.simulate({ from: liquidityProvider })
|
|
340
|
+
.then(r => r.result),
|
|
258
341
|
]);
|
|
259
342
|
|
|
260
343
|
const authwitNonce = Fr.random();
|
|
@@ -295,23 +378,31 @@ export class BotFactory {
|
|
|
295
378
|
.getFunctionCall(),
|
|
296
379
|
});
|
|
297
380
|
|
|
298
|
-
const
|
|
381
|
+
const mintBatch = new BatchCall(this.wallet, [
|
|
299
382
|
token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
|
|
300
383
|
token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
|
|
301
|
-
])
|
|
384
|
+
]);
|
|
385
|
+
const { receipt: mintReceipt } = await mintBatch.send({
|
|
386
|
+
from: liquidityProvider,
|
|
387
|
+
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
388
|
+
});
|
|
302
389
|
|
|
303
|
-
this.log.info(`Sent mint tx: ${
|
|
304
|
-
await mintTx.wait({ timeout: this.config.txMinedWaitSeconds });
|
|
390
|
+
this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
|
|
305
391
|
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
392
|
+
const addLiquidityInteraction = amm.methods.add_liquidity(
|
|
393
|
+
amount0Max,
|
|
394
|
+
amount1Max,
|
|
395
|
+
amount0Min,
|
|
396
|
+
amount1Min,
|
|
397
|
+
authwitNonce,
|
|
398
|
+
);
|
|
399
|
+
const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
|
|
400
|
+
from: liquidityProvider,
|
|
401
|
+
authWitnesses: [token0Authwit, token1Authwit],
|
|
402
|
+
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
403
|
+
});
|
|
312
404
|
|
|
313
|
-
this.log.info(`Sent tx to add liquidity to the AMM: ${
|
|
314
|
-
await addLiquidityTx.wait({ timeout: this.config.txMinedWaitSeconds });
|
|
405
|
+
this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`);
|
|
315
406
|
this.log.info(`Liquidity added`);
|
|
316
407
|
|
|
317
408
|
const [newT0Bal, newT1Bal, newLPBal] = await getPrivateBalances();
|
|
@@ -324,25 +415,76 @@ export class BotFactory {
|
|
|
324
415
|
name: string,
|
|
325
416
|
deploy: DeployMethod<T>,
|
|
326
417
|
deployOpts: DeployOptions,
|
|
327
|
-
): Promise<
|
|
328
|
-
const
|
|
418
|
+
): Promise<ContractInstanceWithAddress> {
|
|
419
|
+
const instance = await deploy.getInstance();
|
|
420
|
+
const address = instance.address;
|
|
329
421
|
const metadata = await this.wallet.getContractMetadata(address);
|
|
330
422
|
if (metadata.isContractPublished) {
|
|
331
423
|
this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
this.log.info(`Deploying contract ${name} at ${address.toString()}`);
|
|
335
|
-
const sentTx = deploy.send(deployOpts);
|
|
336
|
-
const txHash = await sentTx.getTxHash();
|
|
337
|
-
this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
|
|
338
|
-
return this.withNoMinTxsPerBlock(() => sentTx.deployed({ timeout: this.config.txMinedWaitSeconds }));
|
|
424
|
+
await deploy.register();
|
|
425
|
+
return instance;
|
|
339
426
|
}
|
|
427
|
+
|
|
428
|
+
// Setup always runs ensureFeeJuiceBalance before any deploy, so the account pays from its standing
|
|
429
|
+
// balance here. No manual gas estimation: the embedded wallet simulates before sending and derives
|
|
430
|
+
// the gas limits and padded maxFeesPerGas itself.
|
|
431
|
+
this.log.info(`Deploying contract ${name} at ${address.toString()}`);
|
|
432
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
433
|
+
const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
|
|
434
|
+
this.log.info(`Sent contract ${name} deploy tx ${txHash.toString()}`);
|
|
435
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
436
|
+
});
|
|
437
|
+
|
|
438
|
+
return instance;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** True when the config allows bridging fee juice from L1 (fee_juice mode, an L1 RPC, and an L1 key). */
|
|
442
|
+
private isL1BridgingConfigured(): boolean {
|
|
443
|
+
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
444
|
+
return this.config.feePaymentMethod === 'fee_juice' && !!this.config.l1RpcUrls?.length && !!mnemonicOrPrivateKey;
|
|
340
445
|
}
|
|
341
446
|
|
|
342
447
|
/**
|
|
343
|
-
*
|
|
344
|
-
*
|
|
448
|
+
* Ensures the account holds enough fee juice before any other setup step. The account starts empty
|
|
449
|
+
* (initializerless accounts have no deployment tx) and the runtime loop pays fees from this balance and
|
|
450
|
+
* never refuels itself, so every flow funds the account up front. Bridges claims from L1 and consumes
|
|
451
|
+
* each with a claim-only tx until the balance clears the threshold, working from a zero (fresh run) or
|
|
452
|
+
* drained (restart) balance. Each bridge mints a fixed amount well above the threshold, so this is a
|
|
453
|
+
* single bridge in practice. No-op when L1 bridging is not configured or the balance is already above
|
|
454
|
+
* the threshold.
|
|
345
455
|
*/
|
|
456
|
+
private async ensureFeeJuiceBalance(account: AztecAddress): Promise<void> {
|
|
457
|
+
if (!this.isL1BridgingConfigured()) {
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
let balance = await getFeeJuiceBalance(account, this.aztecNode);
|
|
462
|
+
if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
|
|
463
|
+
this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
this.log.info(`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1`);
|
|
468
|
+
|
|
469
|
+
while (balance < FEE_JUICE_TOP_UP_THRESHOLD) {
|
|
470
|
+
// Persist the claim before consuming it: if the top-up tx fails or the bot crashes mid-loop, the
|
|
471
|
+
// next run reuses the pending claim instead of bridging again (and wasting the bridged funds).
|
|
472
|
+
const claim = await this.getOrCreateBridgeClaim(account);
|
|
473
|
+
const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
|
|
474
|
+
|
|
475
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
476
|
+
const executionPayload = await paymentMethod.getExecutionPayload();
|
|
477
|
+
const { txHash } = await this.wallet.sendTx(executionPayload, { from: account, wait: NO_WAIT });
|
|
478
|
+
this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
|
|
479
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
480
|
+
});
|
|
481
|
+
await this.store.deleteBridgeClaim(account);
|
|
482
|
+
balance = await getFeeJuiceBalance(account, this.aztecNode);
|
|
483
|
+
this.log.info(`Fee juice balance after top-up: ${balance}`);
|
|
484
|
+
}
|
|
485
|
+
this.log.info(`Fee juice top-up complete for ${account.toString()}`);
|
|
486
|
+
}
|
|
487
|
+
|
|
346
488
|
private async mintTokens(token: TokenContract | PrivateTokenContract, minter: AztecAddress) {
|
|
347
489
|
const isStandardToken = isStandardTokenContract(token);
|
|
348
490
|
let privateBalance = 0n;
|
|
@@ -372,30 +514,36 @@ export class BotFactory {
|
|
|
372
514
|
this.log.info(`Skipping minting as ${minter.toString()} has enough tokens`);
|
|
373
515
|
return;
|
|
374
516
|
}
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
517
|
+
|
|
518
|
+
// PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
|
|
519
|
+
const additionalScopes = isStandardToken ? undefined : [token.address];
|
|
520
|
+
const mintBatch = new BatchCall(token.wallet, calls);
|
|
521
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
522
|
+
const { txHash } = await mintBatch.send({
|
|
523
|
+
from: minter,
|
|
524
|
+
additionalScopes,
|
|
525
|
+
wait: NO_WAIT,
|
|
526
|
+
});
|
|
527
|
+
this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
|
|
528
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
529
|
+
});
|
|
379
530
|
}
|
|
380
531
|
|
|
381
532
|
/**
|
|
382
|
-
*
|
|
383
|
-
*
|
|
384
|
-
*
|
|
533
|
+
* Returns a usable bridge claim for the recipient, reusing a persisted one when its L1→L2 message is
|
|
534
|
+
* still available (resuming a top-up that failed or crashed before the claim was consumed) and bridging
|
|
535
|
+
* a fresh claim otherwise. The caller deletes the claim from the store once it has been consumed.
|
|
385
536
|
*/
|
|
386
537
|
private async getOrCreateBridgeClaim(recipient: AztecAddress): Promise<L2AmountClaim> {
|
|
387
|
-
// Check if we have an existing claim in the store
|
|
388
538
|
const existingClaim = await this.store.getBridgeClaim(recipient);
|
|
389
539
|
if (existingClaim) {
|
|
390
540
|
this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
|
|
391
|
-
|
|
392
|
-
// Check if the message is ready on L2
|
|
393
541
|
try {
|
|
394
542
|
const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
|
|
395
543
|
await this.withNoMinTxsPerBlock(() =>
|
|
396
544
|
waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
|
|
397
545
|
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
398
|
-
|
|
546
|
+
chainTip: this.syncChainTip,
|
|
399
547
|
}),
|
|
400
548
|
);
|
|
401
549
|
return existingClaim.claim;
|
|
@@ -407,7 +555,6 @@ export class BotFactory {
|
|
|
407
555
|
|
|
408
556
|
const claim = await this.bridgeL1FeeJuice(recipient);
|
|
409
557
|
await this.store.saveBridgeClaim(recipient, claim);
|
|
410
|
-
|
|
411
558
|
return claim;
|
|
412
559
|
}
|
|
413
560
|
|
|
@@ -434,7 +581,7 @@ export class BotFactory {
|
|
|
434
581
|
await this.withNoMinTxsPerBlock(() =>
|
|
435
582
|
waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
|
|
436
583
|
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
437
|
-
|
|
584
|
+
chainTip: this.syncChainTip,
|
|
438
585
|
}),
|
|
439
586
|
);
|
|
440
587
|
|
package/src/index.ts
CHANGED
package/src/interface.ts
CHANGED
|
@@ -22,11 +22,11 @@ export interface BotRunnerApi {
|
|
|
22
22
|
}
|
|
23
23
|
|
|
24
24
|
export const BotRunnerApiSchema: ApiSchemaFor<BotRunnerApi> = {
|
|
25
|
-
start: z.function(
|
|
26
|
-
stop: z.function(
|
|
27
|
-
run: z.function(
|
|
28
|
-
setup: z.function(
|
|
29
|
-
getInfo: z.function(
|
|
30
|
-
getConfig: z.function(
|
|
31
|
-
update: z.function(
|
|
25
|
+
start: z.function({ input: z.tuple([]), output: z.void() }),
|
|
26
|
+
stop: z.function({ input: z.tuple([]), output: z.void() }),
|
|
27
|
+
run: z.function({ input: z.tuple([]), output: z.void() }),
|
|
28
|
+
setup: z.function({ input: z.tuple([]), output: z.void() }),
|
|
29
|
+
getInfo: z.function({ input: z.tuple([]), output: BotInfoSchema }),
|
|
30
|
+
getConfig: z.function({ input: z.tuple([]), output: BotConfigSchema }),
|
|
31
|
+
update: z.function({ input: z.tuple([BotConfigSchema]), output: z.void() }),
|
|
32
32
|
};
|