@aztec/bot 0.0.1-commit.23b0eb0 → 0.0.1-commit.2448fdb
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 -4
- package/dest/amm_bot.d.ts.map +1 -1
- package/dest/amm_bot.js +24 -17
- package/dest/base_bot.d.ts +6 -6
- package/dest/base_bot.d.ts.map +1 -1
- package/dest/base_bot.js +21 -32
- package/dest/bot.d.ts +4 -4
- package/dest/bot.d.ts.map +1 -1
- package/dest/bot.js +5 -8
- package/dest/config.d.ts +32 -16
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +38 -10
- package/dest/cross_chain_bot.d.ts +54 -0
- package/dest/cross_chain_bot.d.ts.map +1 -0
- package/dest/cross_chain_bot.js +134 -0
- package/dest/factory.d.ts +20 -5
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +94 -37
- package/dest/index.d.ts +2 -1
- package/dest/index.d.ts.map +1 -1
- package/dest/index.js +1 -0
- package/dest/l1_to_l2_seeding.d.ts +8 -0
- package/dest/l1_to_l2_seeding.d.ts.map +1 -0
- package/dest/l1_to_l2_seeding.js +63 -0
- package/dest/runner.d.ts +3 -3
- package/dest/runner.d.ts.map +1 -1
- package/dest/runner.js +17 -1
- package/dest/store/bot_store.d.ts +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 +16 -13
- package/src/amm_bot.ts +24 -19
- package/src/base_bot.ts +15 -33
- package/src/bot.ts +8 -10
- package/src/config.ts +43 -14
- package/src/cross_chain_bot.ts +203 -0
- package/src/factory.ts +137 -38
- package/src/index.ts +1 -0
- package/src/l1_to_l2_seeding.ts +79 -0
- package/src/runner.ts +18 -5
- package/src/store/bot_store.ts +60 -5
- package/src/store/index.ts +1 -1
- package/src/utils.ts +3 -3
package/src/config.ts
CHANGED
|
@@ -19,9 +19,12 @@ import type { ComponentsVersions } from '@aztec/stdlib/versioning';
|
|
|
19
19
|
|
|
20
20
|
import { z } from 'zod';
|
|
21
21
|
|
|
22
|
-
const BotFollowChain = ['NONE', '
|
|
22
|
+
const BotFollowChain = ['NONE', 'PROPOSED', 'CHECKPOINTED', 'PROVEN'] as const;
|
|
23
23
|
type BotFollowChain = (typeof BotFollowChain)[number];
|
|
24
24
|
|
|
25
|
+
const BotMode = ['transfer', 'amm', 'crosschain'] as const;
|
|
26
|
+
type BotMode = (typeof BotMode)[number];
|
|
27
|
+
|
|
25
28
|
export enum SupportedTokenContracts {
|
|
26
29
|
TokenContract = 'TokenContract',
|
|
27
30
|
PrivateTokenContract = 'PrivateTokenContract',
|
|
@@ -66,9 +69,9 @@ export type BotConfig = {
|
|
|
66
69
|
maxPendingTxs: number;
|
|
67
70
|
/** Whether to flush after sending each 'setup' transaction */
|
|
68
71
|
flushSetupTransactions: boolean;
|
|
69
|
-
/** L2 gas limit for the tx (empty to
|
|
72
|
+
/** L2 gas limit for the tx (empty to let the bot's wallet estimate). */
|
|
70
73
|
l2GasLimit: number | undefined;
|
|
71
|
-
/** DA gas limit for the tx (empty to
|
|
74
|
+
/** DA gas limit for the tx (empty to let the bot's wallet estimate). */
|
|
72
75
|
daGasLimit: number | undefined;
|
|
73
76
|
/** Token contract to use */
|
|
74
77
|
contract: SupportedTokenContracts;
|
|
@@ -76,8 +79,12 @@ export type BotConfig = {
|
|
|
76
79
|
maxConsecutiveErrors: number;
|
|
77
80
|
/** Stops the bot if service becomes unhealthy */
|
|
78
81
|
stopWhenUnhealthy: boolean;
|
|
79
|
-
/**
|
|
80
|
-
|
|
82
|
+
/** Bot mode: transfer, amm, or crosschain. */
|
|
83
|
+
botMode: BotMode;
|
|
84
|
+
/** Number of L2→L1 messages per tx (crosschain mode). */
|
|
85
|
+
l2ToL1MessagesPerTx: number;
|
|
86
|
+
/** Max L1→L2 messages to keep in-flight (crosschain mode). */
|
|
87
|
+
l1ToL2SeedCount: number;
|
|
81
88
|
} & Pick<DataStoreConfig, 'dataDirectory' | 'dataStoreMapSizeKb'>;
|
|
82
89
|
|
|
83
90
|
export const BotConfigSchema = zodFor<BotConfig>()(
|
|
@@ -107,7 +114,9 @@ export const BotConfigSchema = zodFor<BotConfig>()(
|
|
|
107
114
|
contract: z.nativeEnum(SupportedTokenContracts),
|
|
108
115
|
maxConsecutiveErrors: z.number().int().nonnegative(),
|
|
109
116
|
stopWhenUnhealthy: z.boolean(),
|
|
110
|
-
|
|
117
|
+
botMode: z.enum(BotMode).default('transfer'),
|
|
118
|
+
l2ToL1MessagesPerTx: z.number().int().nonnegative().default(1),
|
|
119
|
+
l1ToL2SeedCount: z.number().int().nonnegative().default(1),
|
|
111
120
|
dataDirectory: z.string().optional(),
|
|
112
121
|
dataStoreMapSizeKb: z.number().optional(),
|
|
113
122
|
})
|
|
@@ -213,10 +222,14 @@ export const botConfigMappings: ConfigMappingsType<BotConfig> = {
|
|
|
213
222
|
description: 'Which chain the bot follows',
|
|
214
223
|
defaultValue: 'NONE',
|
|
215
224
|
parseEnv(val) {
|
|
216
|
-
|
|
225
|
+
const upper = val.toUpperCase();
|
|
226
|
+
if (upper === 'PENDING') {
|
|
227
|
+
return 'CHECKPOINTED';
|
|
228
|
+
}
|
|
229
|
+
if (!(BotFollowChain as readonly string[]).includes(upper)) {
|
|
217
230
|
throw new Error(`Invalid value for BOT_FOLLOW_CHAIN: ${val}`);
|
|
218
231
|
}
|
|
219
|
-
return
|
|
232
|
+
return upper as BotFollowChain;
|
|
220
233
|
},
|
|
221
234
|
},
|
|
222
235
|
maxPendingTxs: {
|
|
@@ -231,12 +244,12 @@ export const botConfigMappings: ConfigMappingsType<BotConfig> = {
|
|
|
231
244
|
},
|
|
232
245
|
l2GasLimit: {
|
|
233
246
|
env: 'BOT_L2_GAS_LIMIT',
|
|
234
|
-
description:
|
|
247
|
+
description: "L2 gas limit for the tx (empty to let the bot's wallet estimate).",
|
|
235
248
|
...optionalNumberConfigHelper(),
|
|
236
249
|
},
|
|
237
250
|
daGasLimit: {
|
|
238
251
|
env: 'BOT_DA_GAS_LIMIT',
|
|
239
|
-
description:
|
|
252
|
+
description: "DA gas limit for the tx (empty to let the bot's wallet estimate).",
|
|
240
253
|
...optionalNumberConfigHelper(),
|
|
241
254
|
},
|
|
242
255
|
contract: {
|
|
@@ -264,10 +277,26 @@ export const botConfigMappings: ConfigMappingsType<BotConfig> = {
|
|
|
264
277
|
description: 'Stops the bot if service becomes unhealthy',
|
|
265
278
|
...booleanConfigHelper(false),
|
|
266
279
|
},
|
|
267
|
-
|
|
268
|
-
env: '
|
|
269
|
-
description: '
|
|
270
|
-
|
|
280
|
+
botMode: {
|
|
281
|
+
env: 'BOT_MODE',
|
|
282
|
+
description: 'Bot mode: transfer, amm, or crosschain',
|
|
283
|
+
defaultValue: 'transfer' as BotMode,
|
|
284
|
+
parseEnv(val: string) {
|
|
285
|
+
if (!(BotMode as readonly string[]).includes(val)) {
|
|
286
|
+
throw new Error(`Invalid value for BOT_MODE: ${val}`);
|
|
287
|
+
}
|
|
288
|
+
return val as BotMode;
|
|
289
|
+
},
|
|
290
|
+
},
|
|
291
|
+
l2ToL1MessagesPerTx: {
|
|
292
|
+
env: 'BOT_L2_TO_L1_MESSAGES_PER_TX',
|
|
293
|
+
description: 'Number of L2→L1 messages per tx (crosschain mode)',
|
|
294
|
+
...numberConfigHelper(1),
|
|
295
|
+
},
|
|
296
|
+
l1ToL2SeedCount: {
|
|
297
|
+
env: 'BOT_L1_TO_L2_SEED_COUNT',
|
|
298
|
+
description: 'Max L1→L2 messages to keep in-flight (crosschain mode)',
|
|
299
|
+
...numberConfigHelper(1),
|
|
271
300
|
},
|
|
272
301
|
...pickConfigMappings(dataConfigMappings, ['dataStoreMapSizeKb', 'dataDirectory']),
|
|
273
302
|
};
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CrossChainBot exercises L2->L1 and L1->L2 messaging.
|
|
3
|
+
*
|
|
4
|
+
* createAndSendTx onTxMined
|
|
5
|
+
* ────────────────────────────────────── ──────────────────────────────
|
|
6
|
+
*
|
|
7
|
+
* 1. SEED (fire-and-forget) 3. VERIFY L2->L1
|
|
8
|
+
* if store has fewer pending messages Query getTxEffect, confirm
|
|
9
|
+
* than seedCount and no seed is the expected L2->L1 messages
|
|
10
|
+
* in-flight: appeared in tx effects.
|
|
11
|
+
* * kick off L1 inbox tx
|
|
12
|
+
* * store msg on completion
|
|
13
|
+
*
|
|
14
|
+
* 2. BUILD & SEND BATCH
|
|
15
|
+
* Always:
|
|
16
|
+
* N x create_l2_to_l1_message
|
|
17
|
+
* (random content, fixed
|
|
18
|
+
* L1 recipient)
|
|
19
|
+
* If a ready L1->L2 msg exists:
|
|
20
|
+
* 1 x consume_message_from_
|
|
21
|
+
* arbitrary_sender_public
|
|
22
|
+
* delete consumed msg from store
|
|
23
|
+
* Send batch tx (no wait)
|
|
24
|
+
*
|
|
25
|
+
*/
|
|
26
|
+
import { AztecAddress } from '@aztec/aztec.js/addresses';
|
|
27
|
+
import { BatchCall, NO_WAIT } from '@aztec/aztec.js/contracts';
|
|
28
|
+
import { isL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
|
|
29
|
+
import { TxHash, TxReceipt } from '@aztec/aztec.js/tx';
|
|
30
|
+
import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
|
|
31
|
+
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
32
|
+
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
33
|
+
import type { TestContract } from '@aztec/noir-test-contracts.js/Test';
|
|
34
|
+
import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
|
|
35
|
+
import type { EmbeddedWallet } from '@aztec/wallets/embedded';
|
|
36
|
+
|
|
37
|
+
import { BaseBot } from './base_bot.js';
|
|
38
|
+
import type { BotConfig } from './config.js';
|
|
39
|
+
import { BotFactory } from './factory.js';
|
|
40
|
+
import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
|
|
41
|
+
import type { BotStore, PendingL1ToL2Message } from './store/index.js';
|
|
42
|
+
|
|
43
|
+
/** Stale message threshold: messages older than this are removed. */
|
|
44
|
+
const STALE_MESSAGE_THRESHOLD_MS = 2 * 60 * 60 * 1000; // 2 hours
|
|
45
|
+
|
|
46
|
+
/** Bot that exercises both L2→L1 and L1→L2 cross-chain messaging. */
|
|
47
|
+
export class CrossChainBot extends BaseBot {
|
|
48
|
+
private l2ToL1Sent = 0;
|
|
49
|
+
private l1ToL2Consumed = 0;
|
|
50
|
+
private pendingSeedPromise: Promise<void> | undefined;
|
|
51
|
+
|
|
52
|
+
protected constructor(
|
|
53
|
+
node: AztecNode,
|
|
54
|
+
wallet: EmbeddedWallet,
|
|
55
|
+
defaultAccountAddress: AztecAddress,
|
|
56
|
+
private readonly contract: TestContract,
|
|
57
|
+
private readonly l1Client: ExtendedViemWalletClient,
|
|
58
|
+
private readonly l1Recipient: EthAddress,
|
|
59
|
+
private readonly inboxAddress: EthAddress,
|
|
60
|
+
private readonly rollupVersion: bigint,
|
|
61
|
+
private readonly store: BotStore,
|
|
62
|
+
config: BotConfig,
|
|
63
|
+
) {
|
|
64
|
+
super(node, wallet, defaultAccountAddress, config);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
static async create(
|
|
68
|
+
config: BotConfig,
|
|
69
|
+
wallet: EmbeddedWallet,
|
|
70
|
+
aztecNode: AztecNode,
|
|
71
|
+
aztecNodeAdmin: AztecNodeAdmin | undefined,
|
|
72
|
+
store: BotStore,
|
|
73
|
+
): Promise<CrossChainBot> {
|
|
74
|
+
if (config.followChain === 'NONE') {
|
|
75
|
+
throw new Error(`CrossChainBot requires followChain to be set (got NONE)`);
|
|
76
|
+
}
|
|
77
|
+
const factory = new BotFactory(config, wallet, store, aztecNode, aztecNodeAdmin);
|
|
78
|
+
const { defaultAccountAddress, contract, l1Client, rollupVersion } = await factory.setupCrossChain();
|
|
79
|
+
const l1Recipient = EthAddress.fromString(l1Client.account!.address);
|
|
80
|
+
const { l1ContractAddresses } = await aztecNode.getNodeInfo();
|
|
81
|
+
const inboxAddress = EthAddress.fromString(l1ContractAddresses.inboxAddress.toString());
|
|
82
|
+
return new CrossChainBot(
|
|
83
|
+
aztecNode,
|
|
84
|
+
wallet,
|
|
85
|
+
defaultAccountAddress,
|
|
86
|
+
contract,
|
|
87
|
+
l1Client,
|
|
88
|
+
l1Recipient,
|
|
89
|
+
inboxAddress,
|
|
90
|
+
rollupVersion,
|
|
91
|
+
store,
|
|
92
|
+
config,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
protected async createAndSendTx(logCtx: object): Promise<TxHash> {
|
|
97
|
+
const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
98
|
+
|
|
99
|
+
// Send an L1→L2 message if we're below the threshold and not already seeding one
|
|
100
|
+
if (pendingMessages.length < this.config.l1ToL2SeedCount && !this.pendingSeedPromise) {
|
|
101
|
+
this.pendingSeedPromise = this.seedNewL1ToL2Message()
|
|
102
|
+
.catch(err => this.log.warn(`Failed to seed L1→L2 message: ${err}`, logCtx))
|
|
103
|
+
.finally(() => {
|
|
104
|
+
this.pendingSeedPromise = undefined;
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Build batch: always L2→L1, optionally consume L1→L2
|
|
109
|
+
const calls = [];
|
|
110
|
+
|
|
111
|
+
// L2→L1: create messages with random content
|
|
112
|
+
for (let i = 0; i < this.config.l2ToL1MessagesPerTx; i++) {
|
|
113
|
+
calls.push(
|
|
114
|
+
this.contract.methods.create_l2_to_l1_message_arbitrary_recipient_public(Fr.random(), this.l1Recipient),
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// L1→L2: consume oldest ready message if available
|
|
119
|
+
const readyMsg = await this.getReadyL1ToL2Message(pendingMessages);
|
|
120
|
+
if (readyMsg) {
|
|
121
|
+
calls.push(
|
|
122
|
+
this.contract.methods.consume_message_from_arbitrary_sender_public(
|
|
123
|
+
Fr.fromHexString(readyMsg.content),
|
|
124
|
+
Fr.fromHexString(readyMsg.secret),
|
|
125
|
+
EthAddress.fromString(readyMsg.sender),
|
|
126
|
+
new Fr(BigInt(readyMsg.globalLeafIndex)),
|
|
127
|
+
),
|
|
128
|
+
);
|
|
129
|
+
// Delete consumed message immediately so it works with FOLLOW_CHAIN=NONE
|
|
130
|
+
await this.store.deleteL1ToL2Message(readyMsg.msgHash);
|
|
131
|
+
this.l1ToL2Consumed++;
|
|
132
|
+
} else {
|
|
133
|
+
this.log.warn(`No ready L1→L2 message to consume`, {
|
|
134
|
+
...logCtx,
|
|
135
|
+
pendingCount: pendingMessages.length,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const batch = new BatchCall(this.wallet, calls);
|
|
140
|
+
const opts = this.getSendMethodOpts();
|
|
141
|
+
|
|
142
|
+
this.log.verbose(`Sending cross-chain batch with ${calls.length} calls`, logCtx);
|
|
143
|
+
const { txHash } = await batch.send({ ...opts, wait: NO_WAIT });
|
|
144
|
+
return txHash;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
protected override async onTxMined(receipt: TxReceipt, logCtx: object): Promise<void> {
|
|
148
|
+
// Verify L2→L1 messages appeared in this tx's effects
|
|
149
|
+
const indexed = await this.node.getTxEffect(receipt.txHash);
|
|
150
|
+
if (indexed) {
|
|
151
|
+
const l2ToL1Msgs = indexed.data.l2ToL1Msgs.filter(m => !m.isZero());
|
|
152
|
+
if (l2ToL1Msgs.length >= this.config.l2ToL1MessagesPerTx) {
|
|
153
|
+
this.l2ToL1Sent += l2ToL1Msgs.length;
|
|
154
|
+
} else {
|
|
155
|
+
this.log.error(`Expected ${this.config.l2ToL1MessagesPerTx} L2→L1 messages but found ${l2ToL1Msgs.length}`, {
|
|
156
|
+
...logCtx,
|
|
157
|
+
blockNumber: receipt.blockNumber,
|
|
158
|
+
txHash: receipt.txHash.toString(),
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const pendingCount = (await this.store.getUnconsumedL1ToL2Messages()).length;
|
|
164
|
+
this.log.info(`CrossChainBot txs mined`, {
|
|
165
|
+
...logCtx,
|
|
166
|
+
l2ToL1Sent: this.l2ToL1Sent,
|
|
167
|
+
l1ToL2Consumed: this.l1ToL2Consumed,
|
|
168
|
+
l1ToL2Pending: pendingCount,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Finds the oldest pending message that is ready for consumption. */
|
|
173
|
+
private async getReadyL1ToL2Message(
|
|
174
|
+
pendingMessages: PendingL1ToL2Message[],
|
|
175
|
+
): Promise<PendingL1ToL2Message | undefined> {
|
|
176
|
+
const now = Date.now();
|
|
177
|
+
for (const msg of pendingMessages) {
|
|
178
|
+
const ready = await isL1ToL2MessageReady(this.node, Fr.fromHexString(msg.msgHash));
|
|
179
|
+
if (ready) {
|
|
180
|
+
return msg;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Time-based stale detection: if the message is old and still not ready, remove it
|
|
184
|
+
if (now - msg.timestamp > STALE_MESSAGE_THRESHOLD_MS) {
|
|
185
|
+
await this.store.deleteL1ToL2Message(msg.msgHash);
|
|
186
|
+
this.log.warn(`Removed stale L1→L2 message ${msg.msgHash}`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Seeds a new L1→L2 message on L1 and stores it. */
|
|
193
|
+
private async seedNewL1ToL2Message(): Promise<void> {
|
|
194
|
+
await seedL1ToL2Message(
|
|
195
|
+
this.l1Client,
|
|
196
|
+
this.inboxAddress,
|
|
197
|
+
this.contract.address,
|
|
198
|
+
this.rollupVersion,
|
|
199
|
+
this.store,
|
|
200
|
+
this.log,
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
}
|
package/src/factory.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { SchnorrAccountContract } from '@aztec/accounts/schnorr';
|
|
2
1
|
import { getInitialTestAccountsData } from '@aztec/accounts/testing';
|
|
2
|
+
import { NO_FROM } from '@aztec/aztec.js/account';
|
|
3
3
|
import { AztecAddress } from '@aztec/aztec.js/addresses';
|
|
4
4
|
import {
|
|
5
5
|
BatchCall,
|
|
@@ -9,27 +9,32 @@ import {
|
|
|
9
9
|
type DeployOptions,
|
|
10
10
|
NO_WAIT,
|
|
11
11
|
} from '@aztec/aztec.js/contracts';
|
|
12
|
-
import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
|
|
13
12
|
import type { L2AmountClaim } from '@aztec/aztec.js/ethereum';
|
|
13
|
+
import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
|
|
14
14
|
import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
|
|
15
15
|
import { deriveKeys } from '@aztec/aztec.js/keys';
|
|
16
16
|
import { createLogger } from '@aztec/aztec.js/log';
|
|
17
17
|
import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
|
|
18
18
|
import { waitForTx } from '@aztec/aztec.js/node';
|
|
19
|
+
import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
|
|
19
20
|
import { createEthereumChain } from '@aztec/ethereum/chain';
|
|
20
21
|
import { createExtendedL1Client } from '@aztec/ethereum/client';
|
|
22
|
+
import { RollupContract } from '@aztec/ethereum/contracts';
|
|
23
|
+
import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
|
|
21
24
|
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
25
|
+
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
22
26
|
import { Timer } from '@aztec/foundation/timer';
|
|
23
27
|
import { AMMContract } from '@aztec/noir-contracts.js/AMM';
|
|
24
28
|
import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
|
|
25
29
|
import { TokenContract } from '@aztec/noir-contracts.js/Token';
|
|
30
|
+
import { TestContract } from '@aztec/noir-test-contracts.js/Test';
|
|
26
31
|
import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
|
|
27
|
-
import { GasSettings } from '@aztec/stdlib/gas';
|
|
28
32
|
import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
|
|
29
33
|
import { deriveSigningKey } from '@aztec/stdlib/keys';
|
|
30
|
-
import {
|
|
34
|
+
import { EmbeddedWallet } from '@aztec/wallets/embedded';
|
|
31
35
|
|
|
32
36
|
import { type BotConfig, SupportedTokenContracts } from './config.js';
|
|
37
|
+
import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
|
|
33
38
|
import type { BotStore } from './store/index.js';
|
|
34
39
|
import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
|
|
35
40
|
|
|
@@ -41,32 +46,36 @@ export class BotFactory {
|
|
|
41
46
|
|
|
42
47
|
constructor(
|
|
43
48
|
private readonly config: BotConfig,
|
|
44
|
-
private readonly wallet:
|
|
49
|
+
private readonly wallet: EmbeddedWallet,
|
|
45
50
|
private readonly store: BotStore,
|
|
46
51
|
private readonly aztecNode: AztecNode,
|
|
47
52
|
private readonly aztecNodeAdmin?: AztecNodeAdmin,
|
|
48
|
-
) {
|
|
53
|
+
) {
|
|
54
|
+
// Set fee padding on the wallet so that all transactions during setup
|
|
55
|
+
// (token deploy, minting, etc.) use the configured padding, not the default.
|
|
56
|
+
this.wallet.setMinFeePadding(config.minFeePadding);
|
|
57
|
+
}
|
|
49
58
|
|
|
50
59
|
/**
|
|
51
60
|
* Initializes a new bot by setting up the sender account, registering the recipient,
|
|
52
61
|
* deploying the token contract, and minting tokens if necessary.
|
|
53
62
|
*/
|
|
54
63
|
public async setup(): Promise<{
|
|
55
|
-
wallet:
|
|
64
|
+
wallet: EmbeddedWallet;
|
|
56
65
|
defaultAccountAddress: AztecAddress;
|
|
57
66
|
token: TokenContract | PrivateTokenContract;
|
|
58
67
|
node: AztecNode;
|
|
59
68
|
recipient: AztecAddress;
|
|
60
69
|
}> {
|
|
61
70
|
const defaultAccountAddress = await this.setupAccount();
|
|
62
|
-
const recipient = (await this.wallet.
|
|
71
|
+
const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
|
|
63
72
|
const token = await this.setupToken(defaultAccountAddress);
|
|
64
73
|
await this.mintTokens(token, defaultAccountAddress);
|
|
65
74
|
return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
|
|
66
75
|
}
|
|
67
76
|
|
|
68
77
|
public async setupAmm(): Promise<{
|
|
69
|
-
wallet:
|
|
78
|
+
wallet: EmbeddedWallet;
|
|
70
79
|
defaultAccountAddress: AztecAddress;
|
|
71
80
|
amm: AMMContract;
|
|
72
81
|
token0: TokenContract;
|
|
@@ -96,6 +105,89 @@ export class BotFactory {
|
|
|
96
105
|
return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
|
|
97
106
|
}
|
|
98
107
|
|
|
108
|
+
/**
|
|
109
|
+
* Initializes the cross-chain bot by deploying TestContract, creating an L1 client,
|
|
110
|
+
* seeding initial L1→L2 messages, and waiting for the first to be ready.
|
|
111
|
+
*/
|
|
112
|
+
public async setupCrossChain(): Promise<{
|
|
113
|
+
wallet: EmbeddedWallet;
|
|
114
|
+
defaultAccountAddress: AztecAddress;
|
|
115
|
+
contract: TestContract;
|
|
116
|
+
node: AztecNode;
|
|
117
|
+
l1Client: ExtendedViemWalletClient;
|
|
118
|
+
rollupVersion: bigint;
|
|
119
|
+
}> {
|
|
120
|
+
const defaultAccountAddress = await this.setupAccount();
|
|
121
|
+
|
|
122
|
+
// Create L1 client (same pattern as bridgeL1FeeJuice)
|
|
123
|
+
const l1RpcUrls = this.config.l1RpcUrls;
|
|
124
|
+
if (!l1RpcUrls?.length) {
|
|
125
|
+
throw new Error('L1 RPC URLs required for cross-chain bot');
|
|
126
|
+
}
|
|
127
|
+
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
128
|
+
if (!mnemonicOrPrivateKey) {
|
|
129
|
+
throw new Error('L1 mnemonic or private key required for cross-chain bot');
|
|
130
|
+
}
|
|
131
|
+
const { l1ChainId, l1ContractAddresses } = await this.aztecNode.getNodeInfo();
|
|
132
|
+
const chain = createEthereumChain(l1RpcUrls, l1ChainId);
|
|
133
|
+
const l1Client = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
|
|
134
|
+
|
|
135
|
+
// Fetch Rollup version (needed for Inbox L2Actor struct)
|
|
136
|
+
const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
|
|
137
|
+
const rollupVersion = await rollupContract.getVersion();
|
|
138
|
+
|
|
139
|
+
// Deploy TestContract
|
|
140
|
+
const contract = await this.setupTestContract(defaultAccountAddress);
|
|
141
|
+
|
|
142
|
+
// Recover any pending messages from store (clean up stale ones first)
|
|
143
|
+
await this.store.cleanupOldPendingMessages();
|
|
144
|
+
const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
145
|
+
|
|
146
|
+
// Seed initial L1→L2 messages if pipeline is empty
|
|
147
|
+
const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
|
|
148
|
+
for (let i = 0; i < seedCount; i++) {
|
|
149
|
+
await seedL1ToL2Message(
|
|
150
|
+
l1Client,
|
|
151
|
+
EthAddress.fromString(l1ContractAddresses.inboxAddress.toString()),
|
|
152
|
+
contract.address,
|
|
153
|
+
rollupVersion,
|
|
154
|
+
this.store,
|
|
155
|
+
this.log,
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Block until at least one message is ready
|
|
160
|
+
const allMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
161
|
+
if (allMessages.length > 0) {
|
|
162
|
+
this.log.info(`Waiting for first L1→L2 message to be ready...`);
|
|
163
|
+
const firstMsg = allMessages[0];
|
|
164
|
+
await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
|
|
165
|
+
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
166
|
+
});
|
|
167
|
+
this.log.info(`First L1→L2 message is ready`);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
wallet: this.wallet,
|
|
172
|
+
defaultAccountAddress,
|
|
173
|
+
contract,
|
|
174
|
+
node: this.aztecNode,
|
|
175
|
+
l1Client,
|
|
176
|
+
rollupVersion,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
private async setupTestContract(deployer: AztecAddress): Promise<TestContract> {
|
|
181
|
+
const deployOpts: DeployOptions = {
|
|
182
|
+
from: deployer,
|
|
183
|
+
contractAddressSalt: this.config.tokenSalt,
|
|
184
|
+
universalDeploy: true,
|
|
185
|
+
};
|
|
186
|
+
const deploy = TestContract.deploy(this.wallet);
|
|
187
|
+
const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
|
|
188
|
+
return TestContract.at(instance.address, this.wallet);
|
|
189
|
+
}
|
|
190
|
+
|
|
99
191
|
/**
|
|
100
192
|
* Checks if the sender account contract is initialized, and initializes it if necessary.
|
|
101
193
|
* @returns The sender wallet.
|
|
@@ -114,14 +206,9 @@ export class BotFactory {
|
|
|
114
206
|
private async setupAccountWithPrivateKey(secret: Fr) {
|
|
115
207
|
const salt = this.config.senderSalt ?? Fr.ONE;
|
|
116
208
|
const signingKey = deriveSigningKey(secret);
|
|
117
|
-
const
|
|
118
|
-
secret,
|
|
119
|
-
salt,
|
|
120
|
-
contract: new SchnorrAccountContract(signingKey!),
|
|
121
|
-
};
|
|
122
|
-
const accountManager = await this.wallet.createAccount(accountData);
|
|
209
|
+
const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
|
|
123
210
|
const metadata = await this.wallet.getContractMetadata(accountManager.address);
|
|
124
|
-
if (metadata.
|
|
211
|
+
if (metadata.initializationStatus === ContractInitializationStatus.INITIALIZED) {
|
|
125
212
|
this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
|
|
126
213
|
const timer = new Timer();
|
|
127
214
|
const address = accountManager.address;
|
|
@@ -136,13 +223,11 @@ export class BotFactory {
|
|
|
136
223
|
|
|
137
224
|
const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
|
|
138
225
|
const deployMethod = await accountManager.getDeployMethod();
|
|
139
|
-
const maxFeesPerGas = (await this.aztecNode.getCurrentMinFees()).mul(1 + this.config.minFeePadding);
|
|
140
|
-
const gasSettings = GasSettings.default({ maxFeesPerGas });
|
|
141
226
|
|
|
142
227
|
await this.withNoMinTxsPerBlock(async () => {
|
|
143
|
-
const txHash = await deployMethod.send({
|
|
144
|
-
from:
|
|
145
|
-
fee: {
|
|
228
|
+
const { txHash } = await deployMethod.send({
|
|
229
|
+
from: NO_FROM,
|
|
230
|
+
fee: { paymentMethod },
|
|
146
231
|
wait: NO_WAIT,
|
|
147
232
|
});
|
|
148
233
|
this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
|
|
@@ -159,12 +244,11 @@ export class BotFactory {
|
|
|
159
244
|
|
|
160
245
|
private async setupTestAccount() {
|
|
161
246
|
const [initialAccountData] = await getInitialTestAccountsData();
|
|
162
|
-
const
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
const accountManager = await this.wallet.createAccount(accountData);
|
|
247
|
+
const accountManager = await this.wallet.createSchnorrAccount(
|
|
248
|
+
initialAccountData.secret,
|
|
249
|
+
initialAccountData.salt,
|
|
250
|
+
initialAccountData.signingKey,
|
|
251
|
+
);
|
|
168
252
|
return accountManager.address;
|
|
169
253
|
}
|
|
170
254
|
|
|
@@ -199,6 +283,8 @@ export class BotFactory {
|
|
|
199
283
|
tokenInstance = await deploy.getInstance(deployOpts);
|
|
200
284
|
token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
|
|
201
285
|
await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
|
|
286
|
+
// The contract constructor initializes private storage vars that need the contract's own nullifier key.
|
|
287
|
+
deployOpts.additionalScopes = [tokenInstance.address];
|
|
202
288
|
} else {
|
|
203
289
|
throw new Error(`Unsupported token contract type: ${this.config.contract}`);
|
|
204
290
|
}
|
|
@@ -210,7 +296,7 @@ export class BotFactory {
|
|
|
210
296
|
await deploy.register();
|
|
211
297
|
} else {
|
|
212
298
|
this.log.info(`Deploying token contract at ${address.toString()}`);
|
|
213
|
-
const txHash = await deploy.send({ ...deployOpts, wait: NO_WAIT });
|
|
299
|
+
const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
|
|
214
300
|
this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
|
|
215
301
|
await this.withNoMinTxsPerBlock(async () => {
|
|
216
302
|
await waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
@@ -251,7 +337,7 @@ export class BotFactory {
|
|
|
251
337
|
const amm = AMMContract.at(instance.address, this.wallet);
|
|
252
338
|
|
|
253
339
|
this.log.info(`AMM deployed at ${amm.address}`);
|
|
254
|
-
const minterReceipt = await lpToken.methods
|
|
340
|
+
const { receipt: minterReceipt } = await lpToken.methods
|
|
255
341
|
.set_minter(amm.address, true)
|
|
256
342
|
.send({ from: deployer, wait: { timeout: this.config.txMinedWaitSeconds } });
|
|
257
343
|
this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
|
|
@@ -270,9 +356,18 @@ export class BotFactory {
|
|
|
270
356
|
): Promise<void> {
|
|
271
357
|
const getPrivateBalances = () =>
|
|
272
358
|
Promise.all([
|
|
273
|
-
token0.methods
|
|
274
|
-
|
|
275
|
-
|
|
359
|
+
token0.methods
|
|
360
|
+
.balance_of_private(liquidityProvider)
|
|
361
|
+
.simulate({ from: liquidityProvider })
|
|
362
|
+
.then(r => r.result),
|
|
363
|
+
token1.methods
|
|
364
|
+
.balance_of_private(liquidityProvider)
|
|
365
|
+
.simulate({ from: liquidityProvider })
|
|
366
|
+
.then(r => r.result),
|
|
367
|
+
lpToken.methods
|
|
368
|
+
.balance_of_private(liquidityProvider)
|
|
369
|
+
.simulate({ from: liquidityProvider })
|
|
370
|
+
.then(r => r.result),
|
|
276
371
|
]);
|
|
277
372
|
|
|
278
373
|
const authwitNonce = Fr.random();
|
|
@@ -313,14 +408,14 @@ export class BotFactory {
|
|
|
313
408
|
.getFunctionCall(),
|
|
314
409
|
});
|
|
315
410
|
|
|
316
|
-
const mintReceipt = await new BatchCall(this.wallet, [
|
|
411
|
+
const { receipt: mintReceipt } = await new BatchCall(this.wallet, [
|
|
317
412
|
token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
|
|
318
413
|
token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
|
|
319
414
|
]).send({ from: liquidityProvider, wait: { timeout: this.config.txMinedWaitSeconds } });
|
|
320
415
|
|
|
321
416
|
this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
|
|
322
417
|
|
|
323
|
-
const addLiquidityReceipt = await amm.methods
|
|
418
|
+
const { receipt: addLiquidityReceipt } = await amm.methods
|
|
324
419
|
.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce)
|
|
325
420
|
.send({
|
|
326
421
|
from: liquidityProvider,
|
|
@@ -351,7 +446,7 @@ export class BotFactory {
|
|
|
351
446
|
} else {
|
|
352
447
|
this.log.info(`Deploying contract ${name} at ${address.toString()}`);
|
|
353
448
|
await this.withNoMinTxsPerBlock(async () => {
|
|
354
|
-
const txHash = await deploy.send({ ...deployOpts, wait: NO_WAIT });
|
|
449
|
+
const { txHash } = await deploy.send({ ...deployOpts, wait: NO_WAIT });
|
|
355
450
|
this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
|
|
356
451
|
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
357
452
|
});
|
|
@@ -393,8 +488,14 @@ export class BotFactory {
|
|
|
393
488
|
return;
|
|
394
489
|
}
|
|
395
490
|
|
|
491
|
+
// PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
|
|
492
|
+
const additionalScopes = isStandardToken ? undefined : [token.address];
|
|
396
493
|
await this.withNoMinTxsPerBlock(async () => {
|
|
397
|
-
const txHash = await new BatchCall(token.wallet, calls).send({
|
|
494
|
+
const { txHash } = await new BatchCall(token.wallet, calls).send({
|
|
495
|
+
from: minter,
|
|
496
|
+
additionalScopes,
|
|
497
|
+
wait: NO_WAIT,
|
|
498
|
+
});
|
|
398
499
|
this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
|
|
399
500
|
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
400
501
|
});
|
|
@@ -417,7 +518,6 @@ export class BotFactory {
|
|
|
417
518
|
await this.withNoMinTxsPerBlock(() =>
|
|
418
519
|
waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
|
|
419
520
|
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
420
|
-
forPublicConsumption: false,
|
|
421
521
|
}),
|
|
422
522
|
);
|
|
423
523
|
return existingClaim.claim;
|
|
@@ -456,7 +556,6 @@ export class BotFactory {
|
|
|
456
556
|
await this.withNoMinTxsPerBlock(() =>
|
|
457
557
|
waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
|
|
458
558
|
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
459
|
-
forPublicConsumption: false,
|
|
460
559
|
}),
|
|
461
560
|
);
|
|
462
561
|
|