@aztec/bot 0.0.0-test.1 → 0.0.1-commit.017a351
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 +32 -0
- package/dest/amm_bot.d.ts.map +1 -0
- package/dest/amm_bot.js +108 -0
- package/dest/base_bot.d.ts +21 -0
- package/dest/base_bot.d.ts.map +1 -0
- package/dest/base_bot.js +69 -0
- package/dest/bot.d.ts +13 -18
- package/dest/bot.d.ts.map +1 -1
- package/dest/bot.js +23 -85
- package/dest/config.d.ts +88 -99
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +91 -41
- 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 +137 -0
- package/dest/factory.d.ts +48 -29
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +549 -144
- package/dest/index.d.ts +5 -2
- package/dest/index.d.ts.map +1 -1
- package/dest/index.js +4 -1
- package/dest/interface.d.ts +8 -1
- package/dest/interface.d.ts.map +1 -1
- package/dest/interface.js +34 -6
- 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/rpc.d.ts +1 -7
- package/dest/rpc.d.ts.map +1 -1
- package/dest/rpc.js +0 -11
- package/dest/runner.d.ts +15 -11
- package/dest/runner.d.ts.map +1 -1
- package/dest/runner.js +457 -51
- package/dest/store/bot_store.d.ts +69 -0
- package/dest/store/bot_store.d.ts.map +1 -0
- package/dest/store/bot_store.js +138 -0
- package/dest/store/index.d.ts +2 -0
- package/dest/store/index.d.ts.map +1 -0
- package/dest/store/index.js +1 -0
- package/dest/utils.d.ts +8 -5
- package/dest/utils.d.ts.map +1 -1
- package/dest/utils.js +14 -5
- package/package.json +31 -24
- package/src/amm_bot.ts +129 -0
- package/src/base_bot.ts +75 -0
- package/src/bot.ts +51 -103
- package/src/config.ts +133 -75
- package/src/cross_chain_bot.ts +204 -0
- package/src/factory.ts +644 -149
- package/src/index.ts +4 -1
- package/src/interface.ts +15 -6
- package/src/l1_to_l2_seeding.ts +79 -0
- package/src/rpc.ts +0 -13
- package/src/runner.ts +51 -21
- package/src/store/bot_store.ts +196 -0
- package/src/store/index.ts +1 -0
- package/src/utils.ts +17 -6
package/src/factory.ts
CHANGED
|
@@ -1,72 +1,198 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { getInitialTestAccountsData } from '@aztec/accounts/testing';
|
|
2
|
+
import { NO_FROM } from '@aztec/aztec.js/account';
|
|
3
|
+
import { AztecAddress } from '@aztec/aztec.js/addresses';
|
|
3
4
|
import {
|
|
4
|
-
type AccountWallet,
|
|
5
|
-
AztecAddress,
|
|
6
|
-
type AztecNode,
|
|
7
5
|
BatchCall,
|
|
6
|
+
ContractBase,
|
|
7
|
+
ContractFunctionInteraction,
|
|
8
8
|
type DeployMethod,
|
|
9
9
|
type DeployOptions,
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
} from '@aztec/aztec.js';
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
10
|
+
NO_WAIT,
|
|
11
|
+
} from '@aztec/aztec.js/contracts';
|
|
12
|
+
import type { L2AmountClaim } from '@aztec/aztec.js/ethereum';
|
|
13
|
+
import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
|
|
14
|
+
import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
|
|
15
|
+
import { deriveKeys } from '@aztec/aztec.js/keys';
|
|
16
|
+
import { createLogger } from '@aztec/aztec.js/log';
|
|
17
|
+
import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
|
|
18
|
+
import { waitForTx } from '@aztec/aztec.js/node';
|
|
19
|
+
import { getFeeJuiceBalance } from '@aztec/aztec.js/utils';
|
|
20
|
+
import { ContractInitializationStatus } from '@aztec/aztec.js/wallet';
|
|
21
|
+
import { createEthereumChain } from '@aztec/ethereum/chain';
|
|
22
|
+
import { createExtendedL1Client } from '@aztec/ethereum/client';
|
|
23
|
+
import { RollupContract } from '@aztec/ethereum/contracts';
|
|
24
|
+
import type { ExtendedViemWalletClient } from '@aztec/ethereum/types';
|
|
25
|
+
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
26
|
+
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
27
|
+
import { Timer } from '@aztec/foundation/timer';
|
|
28
|
+
import { AMMContract } from '@aztec/noir-contracts.js/AMM';
|
|
29
|
+
import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
|
|
20
30
|
import { TokenContract } from '@aztec/noir-contracts.js/Token';
|
|
21
|
-
import
|
|
31
|
+
import { TestContract } from '@aztec/noir-test-contracts.js/Test';
|
|
32
|
+
import type { ContractInstanceWithAddress } from '@aztec/stdlib/contract';
|
|
33
|
+
import { GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
|
|
34
|
+
import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
|
|
22
35
|
import { deriveSigningKey } from '@aztec/stdlib/keys';
|
|
23
|
-
import {
|
|
36
|
+
import { EmbeddedWallet } from '@aztec/wallets/embedded';
|
|
24
37
|
|
|
25
|
-
import { type BotConfig, SupportedTokenContracts
|
|
38
|
+
import { type BotConfig, SupportedTokenContracts } from './config.js';
|
|
39
|
+
import { seedL1ToL2Message } from './l1_to_l2_seeding.js';
|
|
40
|
+
import type { BotStore } from './store/index.js';
|
|
26
41
|
import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
|
|
27
42
|
|
|
28
43
|
const MINT_BALANCE = 1e12;
|
|
29
44
|
const MIN_BALANCE = 1e3;
|
|
45
|
+
const FEE_JUICE_TOP_UP_THRESHOLD = 100n * 10n ** 18n;
|
|
46
|
+
const FEE_JUICE_TOP_UP_TARGET = 10_000n * 10n ** 18n;
|
|
30
47
|
|
|
31
48
|
export class BotFactory {
|
|
32
|
-
private pxe: PXE;
|
|
33
|
-
private node?: AztecNode;
|
|
34
49
|
private log = createLogger('bot');
|
|
35
50
|
|
|
36
|
-
constructor(
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
51
|
+
constructor(
|
|
52
|
+
private readonly config: BotConfig,
|
|
53
|
+
private readonly wallet: EmbeddedWallet,
|
|
54
|
+
private readonly store: BotStore,
|
|
55
|
+
private readonly aztecNode: AztecNode,
|
|
56
|
+
private readonly aztecNodeAdmin?: AztecNodeAdmin,
|
|
57
|
+
) {
|
|
58
|
+
// Set fee padding on the wallet so that all transactions during setup
|
|
59
|
+
// (token deploy, minting, etc.) use the configured padding, not the default.
|
|
60
|
+
this.wallet.setMinFeePadding(config.minFeePadding);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Initializes a new bot by setting up the sender account, registering the recipient,
|
|
65
|
+
* deploying the token contract, and minting tokens if necessary.
|
|
66
|
+
*/
|
|
67
|
+
public async setup(): Promise<{
|
|
68
|
+
wallet: EmbeddedWallet;
|
|
69
|
+
defaultAccountAddress: AztecAddress;
|
|
70
|
+
token: TokenContract | PrivateTokenContract;
|
|
71
|
+
node: AztecNode;
|
|
72
|
+
recipient: AztecAddress;
|
|
73
|
+
}> {
|
|
74
|
+
const defaultAccountAddress = await this.setupAccount();
|
|
75
|
+
const recipient = (await this.wallet.createSchnorrAccount(Fr.random(), Fr.random())).address;
|
|
76
|
+
const token = await this.setupTokenWithOptionalEarlyRefuel(defaultAccountAddress);
|
|
77
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress, token);
|
|
78
|
+
await this.mintTokens(token, defaultAccountAddress);
|
|
79
|
+
return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
public async setupAmm(): Promise<{
|
|
83
|
+
wallet: EmbeddedWallet;
|
|
84
|
+
defaultAccountAddress: AztecAddress;
|
|
85
|
+
amm: AMMContract;
|
|
86
|
+
token0: TokenContract;
|
|
87
|
+
token1: TokenContract;
|
|
88
|
+
node: AztecNode;
|
|
89
|
+
}> {
|
|
90
|
+
const defaultAccountAddress = await this.setupAccount();
|
|
91
|
+
const token0 = await this.setupTokenContractWithOptionalEarlyRefuel(
|
|
92
|
+
defaultAccountAddress,
|
|
93
|
+
this.config.tokenSalt,
|
|
94
|
+
'BotToken0',
|
|
95
|
+
'BOT0',
|
|
96
|
+
);
|
|
97
|
+
await this.ensureFeeJuiceBalance(defaultAccountAddress, token0);
|
|
98
|
+
const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
|
|
99
|
+
const liquidityToken = await this.setupTokenContract(
|
|
100
|
+
defaultAccountAddress,
|
|
101
|
+
this.config.tokenSalt,
|
|
102
|
+
'BotLPToken',
|
|
103
|
+
'BOTLP',
|
|
104
|
+
);
|
|
105
|
+
const amm = await this.setupAmmContract(
|
|
106
|
+
defaultAccountAddress,
|
|
107
|
+
this.config.tokenSalt,
|
|
108
|
+
token0,
|
|
109
|
+
token1,
|
|
110
|
+
liquidityToken,
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
await this.fundAmm(defaultAccountAddress, defaultAccountAddress, amm, token0, token1, liquidityToken);
|
|
114
|
+
this.log.info(`AMM initialized and funded`);
|
|
115
|
+
|
|
116
|
+
return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Initializes the cross-chain bot by deploying TestContract, creating an L1 client,
|
|
121
|
+
* seeding initial L1→L2 messages, and waiting for the first to be ready.
|
|
122
|
+
*/
|
|
123
|
+
public async setupCrossChain(): Promise<{
|
|
124
|
+
wallet: EmbeddedWallet;
|
|
125
|
+
defaultAccountAddress: AztecAddress;
|
|
126
|
+
contract: TestContract;
|
|
127
|
+
node: AztecNode;
|
|
128
|
+
l1Client: ExtendedViemWalletClient;
|
|
129
|
+
rollupVersion: bigint;
|
|
130
|
+
}> {
|
|
131
|
+
const defaultAccountAddress = await this.setupAccount();
|
|
132
|
+
|
|
133
|
+
// Create L1 client (same pattern as bridgeL1FeeJuice)
|
|
134
|
+
const l1RpcUrls = this.config.l1RpcUrls;
|
|
135
|
+
if (!l1RpcUrls?.length) {
|
|
136
|
+
throw new Error('L1 RPC URLs required for cross-chain bot');
|
|
44
137
|
}
|
|
45
|
-
|
|
46
|
-
|
|
138
|
+
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
139
|
+
if (!mnemonicOrPrivateKey) {
|
|
140
|
+
throw new Error('L1 mnemonic or private key required for cross-chain bot');
|
|
47
141
|
}
|
|
142
|
+
const { l1ChainId, l1ContractAddresses } = await this.aztecNode.getNodeInfo();
|
|
143
|
+
const chain = createEthereumChain(l1RpcUrls, l1ChainId);
|
|
144
|
+
const l1Client = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
|
|
48
145
|
|
|
49
|
-
|
|
146
|
+
// Fetch Rollup version (needed for Inbox L2Actor struct)
|
|
147
|
+
const rollupContract = new RollupContract(l1Client, l1ContractAddresses.rollupAddress.toString());
|
|
148
|
+
const rollupVersion = await rollupContract.getVersion();
|
|
50
149
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
150
|
+
// Deploy TestContract
|
|
151
|
+
const contract = await this.setupTestContract(defaultAccountAddress);
|
|
152
|
+
|
|
153
|
+
// Recover any pending messages from store (clean up stale ones first)
|
|
154
|
+
await this.store.cleanupOldPendingMessages();
|
|
155
|
+
const pendingMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
156
|
+
|
|
157
|
+
// Seed initial L1→L2 messages if pipeline is empty
|
|
158
|
+
const seedCount = Math.max(0, this.config.l1ToL2SeedCount - pendingMessages.length);
|
|
159
|
+
for (let i = 0; i < seedCount; i++) {
|
|
160
|
+
await seedL1ToL2Message(
|
|
161
|
+
l1Client,
|
|
162
|
+
EthAddress.fromString(l1ContractAddresses.inboxAddress.toString()),
|
|
163
|
+
contract.address,
|
|
164
|
+
rollupVersion,
|
|
165
|
+
this.store,
|
|
166
|
+
this.log,
|
|
167
|
+
);
|
|
55
168
|
}
|
|
56
|
-
|
|
57
|
-
|
|
169
|
+
|
|
170
|
+
// Block until at least one message is ready
|
|
171
|
+
const allMessages = await this.store.getUnconsumedL1ToL2Messages();
|
|
172
|
+
if (allMessages.length > 0) {
|
|
173
|
+
this.log.info(`Waiting for first L1→L2 message to be ready...`);
|
|
174
|
+
const firstMsg = allMessages[0];
|
|
175
|
+
await waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(firstMsg.msgHash), {
|
|
176
|
+
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
177
|
+
});
|
|
178
|
+
this.log.info(`First L1→L2 message is ready`);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
wallet: this.wallet,
|
|
183
|
+
defaultAccountAddress,
|
|
184
|
+
contract,
|
|
185
|
+
node: this.aztecNode,
|
|
186
|
+
l1Client,
|
|
187
|
+
rollupVersion,
|
|
188
|
+
};
|
|
58
189
|
}
|
|
59
190
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const recipient = await this.registerRecipient();
|
|
66
|
-
const wallet = await this.setupAccount();
|
|
67
|
-
const token = await this.setupToken(wallet);
|
|
68
|
-
await this.mintTokens(token);
|
|
69
|
-
return { wallet, token, pxe: this.pxe, recipient };
|
|
191
|
+
private async setupTestContract(deployer: AztecAddress): Promise<TestContract> {
|
|
192
|
+
const deployOpts: DeployOptions = { from: deployer };
|
|
193
|
+
const deploy = TestContract.deploy(this.wallet, { salt: this.config.tokenSalt, universalDeploy: true });
|
|
194
|
+
const instance = await this.registerOrDeployContract('TestContract', deploy, deployOpts);
|
|
195
|
+
return TestContract.at(instance.address, this.wallet);
|
|
70
196
|
}
|
|
71
197
|
|
|
72
198
|
/**
|
|
@@ -74,186 +200,555 @@ export class BotFactory {
|
|
|
74
200
|
* @returns The sender wallet.
|
|
75
201
|
*/
|
|
76
202
|
private async setupAccount() {
|
|
77
|
-
|
|
78
|
-
|
|
203
|
+
const privateKey = this.config.senderPrivateKey?.getValue();
|
|
204
|
+
if (privateKey) {
|
|
205
|
+
this.log.info(`Setting up account with provided private key`);
|
|
206
|
+
return await this.setupAccountWithPrivateKey(privateKey);
|
|
79
207
|
} else {
|
|
208
|
+
this.log.info(`Setting up test account`);
|
|
80
209
|
return await this.setupTestAccount();
|
|
81
210
|
}
|
|
82
211
|
}
|
|
83
212
|
|
|
84
|
-
private async setupAccountWithPrivateKey(
|
|
85
|
-
const salt = Fr.ONE;
|
|
86
|
-
const signingKey = deriveSigningKey(
|
|
87
|
-
const
|
|
88
|
-
const
|
|
89
|
-
if (
|
|
90
|
-
this.log.info(`Account at ${
|
|
91
|
-
const
|
|
92
|
-
|
|
213
|
+
private async setupAccountWithPrivateKey(secret: Fr) {
|
|
214
|
+
const salt = this.config.senderSalt ?? Fr.ONE;
|
|
215
|
+
const signingKey = deriveSigningKey(secret);
|
|
216
|
+
const accountManager = await this.wallet.createSchnorrAccount(secret, salt, signingKey);
|
|
217
|
+
const metadata = await this.wallet.getContractMetadata(accountManager.address);
|
|
218
|
+
if (metadata.initializationStatus === ContractInitializationStatus.INITIALIZED) {
|
|
219
|
+
this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
|
|
220
|
+
const timer = new Timer();
|
|
221
|
+
const address = accountManager.address;
|
|
222
|
+
this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
|
|
223
|
+
await this.store.deleteBridgeClaim(address);
|
|
224
|
+
return address;
|
|
93
225
|
} else {
|
|
94
|
-
const address =
|
|
226
|
+
const address = accountManager.address;
|
|
95
227
|
this.log.info(`Deploying account at ${address}`);
|
|
96
228
|
|
|
97
|
-
const claim = await this.
|
|
229
|
+
const claim = await this.getOrCreateBridgeClaim(address);
|
|
98
230
|
|
|
99
|
-
const
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
231
|
+
const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
|
|
232
|
+
const deployMethod = await accountManager.getDeployMethod();
|
|
233
|
+
|
|
234
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
235
|
+
const { txHash } = await deployMethod.send({
|
|
236
|
+
from: NO_FROM,
|
|
237
|
+
fee: { paymentMethod },
|
|
238
|
+
wait: NO_WAIT,
|
|
239
|
+
});
|
|
240
|
+
this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
|
|
241
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
242
|
+
});
|
|
107
243
|
this.log.info(`Account deployed at ${address}`);
|
|
108
|
-
|
|
244
|
+
|
|
245
|
+
// Clean up the consumed bridge claim
|
|
246
|
+
await this.store.deleteBridgeClaim(address);
|
|
247
|
+
|
|
248
|
+
return accountManager.address;
|
|
109
249
|
}
|
|
110
250
|
}
|
|
111
251
|
|
|
112
252
|
private async setupTestAccount() {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
253
|
+
const [initialAccountData] = await getInitialTestAccountsData();
|
|
254
|
+
const accountManager = await this.wallet.createSchnorrAccount(
|
|
255
|
+
initialAccountData.secret,
|
|
256
|
+
initialAccountData.salt,
|
|
257
|
+
initialAccountData.signingKey,
|
|
258
|
+
);
|
|
259
|
+
return accountManager.address;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Setup token and refuel first: if the token already exists (restart scenario),
|
|
264
|
+
* run ensureFeeJuiceBalance before any step that might need fee juice. When deploying,
|
|
265
|
+
* use a bridge claim if balance is below threshold.
|
|
266
|
+
*/
|
|
267
|
+
private async setupTokenWithOptionalEarlyRefuel(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
|
|
268
|
+
const token = await this.getTokenInstance(sender);
|
|
269
|
+
const address = token.address;
|
|
270
|
+
const metadata = await this.wallet.getContractMetadata(address);
|
|
271
|
+
if (metadata.isContractPublished) {
|
|
272
|
+
this.log.info(`Token at ${address.toString()} already deployed, refueling before setup`);
|
|
273
|
+
await this.ensureFeeJuiceBalance(sender, token);
|
|
122
274
|
}
|
|
123
|
-
return
|
|
275
|
+
return this.setupToken(sender);
|
|
124
276
|
}
|
|
125
277
|
|
|
126
278
|
/**
|
|
127
|
-
*
|
|
279
|
+
* Setup token0 for AMM with refuel-first behaviour when token already exists.
|
|
128
280
|
*/
|
|
129
|
-
private async
|
|
130
|
-
|
|
131
|
-
|
|
281
|
+
private async setupTokenContractWithOptionalEarlyRefuel(
|
|
282
|
+
deployer: AztecAddress,
|
|
283
|
+
salt: Fr,
|
|
284
|
+
name: string,
|
|
285
|
+
ticker: string,
|
|
286
|
+
decimals = 18,
|
|
287
|
+
): Promise<TokenContract> {
|
|
288
|
+
const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
|
|
289
|
+
const instance = await deploy.getInstance();
|
|
290
|
+
const metadata = await this.wallet.getContractMetadata(instance.address);
|
|
291
|
+
if (metadata.isContractPublished) {
|
|
292
|
+
this.log.info(`Token ${name} at ${instance.address.toString()} already deployed, refueling before setup`);
|
|
293
|
+
const token = TokenContract.at(instance.address, this.wallet);
|
|
294
|
+
await this.ensureFeeJuiceBalance(deployer, token);
|
|
295
|
+
}
|
|
296
|
+
return this.setupTokenContract(deployer, salt, name, ticker, decimals);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
private async getTokenInstance(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
|
|
300
|
+
const salt = this.config.tokenSalt;
|
|
301
|
+
if (this.config.contract === SupportedTokenContracts.TokenContract) {
|
|
302
|
+
const deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
|
|
303
|
+
const instance = await deploy.getInstance();
|
|
304
|
+
return TokenContract.at(instance.address, this.wallet);
|
|
305
|
+
}
|
|
306
|
+
if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
|
|
307
|
+
const tokenSecretKey = Fr.random();
|
|
308
|
+
const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
|
|
309
|
+
const deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
|
|
310
|
+
salt,
|
|
311
|
+
universalDeploy: true,
|
|
312
|
+
publicKeys: tokenPublicKeys,
|
|
313
|
+
});
|
|
314
|
+
const instance = await deploy.getInstance();
|
|
315
|
+
return PrivateTokenContract.at(instance.address, this.wallet);
|
|
316
|
+
}
|
|
317
|
+
throw new Error(`Unsupported token contract type: ${this.config.contract}`);
|
|
132
318
|
}
|
|
133
319
|
|
|
134
320
|
/**
|
|
135
321
|
* Checks if the token contract is deployed and deploys it if necessary.
|
|
136
|
-
*
|
|
137
|
-
* @
|
|
322
|
+
* Uses a bridge claim for deploy when balance is below threshold to avoid failing before refuel.
|
|
323
|
+
* @param sender - Aztec address to deploy the token contract from.
|
|
324
|
+
* @param existingToken - Optional token instance when called from setupTokenWithOptionalEarlyRefuel.
|
|
325
|
+
* @returns The TokenContract or PrivateTokenContract instance.
|
|
138
326
|
*/
|
|
139
|
-
private async setupToken(
|
|
140
|
-
let deploy: DeployMethod<TokenContract |
|
|
141
|
-
const
|
|
327
|
+
private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
|
|
328
|
+
let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
|
|
329
|
+
const salt = this.config.tokenSalt;
|
|
330
|
+
const deployOpts: DeployOptions = { from: sender };
|
|
331
|
+
let token: TokenContract | PrivateTokenContract;
|
|
142
332
|
if (this.config.contract === SupportedTokenContracts.TokenContract) {
|
|
143
|
-
deploy = TokenContract.deploy(wallet,
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
333
|
+
deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18, { salt, universalDeploy: true });
|
|
334
|
+
const instance = await deploy.getInstance();
|
|
335
|
+
token = TokenContract.at(instance.address, this.wallet);
|
|
336
|
+
} else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
|
|
337
|
+
// Generate keys for the contract since PrivateToken uses SinglePrivateMutable which requires keys
|
|
338
|
+
const tokenSecretKey = Fr.random();
|
|
339
|
+
const tokenPublicKeys = (await deriveKeys(tokenSecretKey)).publicKeys;
|
|
340
|
+
deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender, {
|
|
341
|
+
salt,
|
|
342
|
+
universalDeploy: true,
|
|
343
|
+
publicKeys: tokenPublicKeys,
|
|
344
|
+
});
|
|
345
|
+
deployOpts.skipInstancePublication = true;
|
|
346
|
+
deployOpts.skipClassPublication = true;
|
|
148
347
|
deployOpts.skipInitialization = false;
|
|
149
|
-
|
|
348
|
+
|
|
349
|
+
// Register the contract with the secret key before deployment
|
|
350
|
+
const tokenInstance = await deploy.getInstance();
|
|
351
|
+
token = PrivateTokenContract.at(tokenInstance.address, this.wallet);
|
|
352
|
+
await this.wallet.registerContract(tokenInstance, PrivateTokenContract.artifact, tokenSecretKey);
|
|
353
|
+
// The contract constructor initializes private storage vars that need the contract's own nullifier key.
|
|
354
|
+
deployOpts.additionalScopes = [tokenInstance.address];
|
|
150
355
|
} else {
|
|
151
356
|
throw new Error(`Unsupported token contract type: ${this.config.contract}`);
|
|
152
357
|
}
|
|
153
358
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
359
|
+
await this.registerOrDeployContract('token', deploy, deployOpts);
|
|
360
|
+
return token;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Checks if the token contract is deployed and deploys it if necessary.
|
|
365
|
+
* @param wallet - Wallet to deploy the token contract from.
|
|
366
|
+
* @returns The TokenContract instance.
|
|
367
|
+
*/
|
|
368
|
+
private async setupTokenContract(
|
|
369
|
+
deployer: AztecAddress,
|
|
370
|
+
salt: Fr,
|
|
371
|
+
name: string,
|
|
372
|
+
ticker: string,
|
|
373
|
+
decimals = 18,
|
|
374
|
+
): Promise<TokenContract> {
|
|
375
|
+
const deployOpts: DeployOptions = { from: deployer };
|
|
376
|
+
const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals, { salt, universalDeploy: true });
|
|
377
|
+
const instance = await this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
|
|
378
|
+
return TokenContract.at(instance.address, this.wallet);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
private async setupAmmContract(
|
|
382
|
+
deployer: AztecAddress,
|
|
383
|
+
salt: Fr,
|
|
384
|
+
token0: TokenContract,
|
|
385
|
+
token1: TokenContract,
|
|
386
|
+
lpToken: TokenContract,
|
|
387
|
+
): Promise<AMMContract> {
|
|
388
|
+
const deployOpts: DeployOptions = { from: deployer };
|
|
389
|
+
const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address, {
|
|
390
|
+
salt,
|
|
391
|
+
universalDeploy: true,
|
|
392
|
+
});
|
|
393
|
+
const instance = await this.registerOrDeployContract('AMM', deploy, deployOpts);
|
|
394
|
+
const amm = AMMContract.at(instance.address, this.wallet);
|
|
395
|
+
|
|
396
|
+
this.log.info(`AMM deployed at ${amm.address}`);
|
|
397
|
+
const setMinterInteraction = lpToken.methods.set_minter(amm.address, true);
|
|
398
|
+
const { receipt: minterReceipt } = await setMinterInteraction.send({
|
|
399
|
+
from: deployer,
|
|
400
|
+
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
401
|
+
});
|
|
402
|
+
this.log.info(`Set LP token minter to AMM txHash=${minterReceipt.txHash.toString()}`);
|
|
403
|
+
this.log.info(`Liquidity token initialized`);
|
|
404
|
+
|
|
405
|
+
return amm;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
private async fundAmm(
|
|
409
|
+
defaultAccountAddress: AztecAddress,
|
|
410
|
+
liquidityProvider: AztecAddress,
|
|
411
|
+
amm: AMMContract,
|
|
412
|
+
token0: TokenContract,
|
|
413
|
+
token1: TokenContract,
|
|
414
|
+
lpToken: TokenContract,
|
|
415
|
+
): Promise<void> {
|
|
416
|
+
const getPrivateBalances = () =>
|
|
417
|
+
Promise.all([
|
|
418
|
+
token0.methods
|
|
419
|
+
.balance_of_private(liquidityProvider)
|
|
420
|
+
.simulate({ from: liquidityProvider })
|
|
421
|
+
.then(r => r.result),
|
|
422
|
+
token1.methods
|
|
423
|
+
.balance_of_private(liquidityProvider)
|
|
424
|
+
.simulate({ from: liquidityProvider })
|
|
425
|
+
.then(r => r.result),
|
|
426
|
+
lpToken.methods
|
|
427
|
+
.balance_of_private(liquidityProvider)
|
|
428
|
+
.simulate({ from: liquidityProvider })
|
|
429
|
+
.then(r => r.result),
|
|
430
|
+
]);
|
|
431
|
+
|
|
432
|
+
const authwitNonce = Fr.random();
|
|
433
|
+
|
|
434
|
+
// keep some tokens for swapping
|
|
435
|
+
const amount0Max = MINT_BALANCE / 2;
|
|
436
|
+
const amount0Min = MINT_BALANCE / 4;
|
|
437
|
+
const amount1Max = MINT_BALANCE / 2;
|
|
438
|
+
const amount1Min = MINT_BALANCE / 4;
|
|
439
|
+
|
|
440
|
+
const [t0Bal, t1Bal, lpBal] = await getPrivateBalances();
|
|
441
|
+
|
|
442
|
+
this.log.info(
|
|
443
|
+
`Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1. Current private balances of ${liquidityProvider}: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`,
|
|
444
|
+
);
|
|
445
|
+
|
|
446
|
+
// Add authwitnesses for the transfers in AMM::add_liquidity function
|
|
447
|
+
const token0Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
|
|
448
|
+
caller: amm.address,
|
|
449
|
+
call: await token0.methods
|
|
450
|
+
.transfer_to_public_and_prepare_private_balance_increase(
|
|
451
|
+
liquidityProvider,
|
|
452
|
+
amm.address,
|
|
453
|
+
amount0Max,
|
|
454
|
+
authwitNonce,
|
|
455
|
+
)
|
|
456
|
+
.getFunctionCall(),
|
|
457
|
+
});
|
|
458
|
+
const token1Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
|
|
459
|
+
caller: amm.address,
|
|
460
|
+
call: await token1.methods
|
|
461
|
+
.transfer_to_public_and_prepare_private_balance_increase(
|
|
462
|
+
liquidityProvider,
|
|
463
|
+
amm.address,
|
|
464
|
+
amount1Max,
|
|
465
|
+
authwitNonce,
|
|
466
|
+
)
|
|
467
|
+
.getFunctionCall(),
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
const mintBatch = new BatchCall(this.wallet, [
|
|
471
|
+
token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
|
|
472
|
+
token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
|
|
473
|
+
]);
|
|
474
|
+
const { receipt: mintReceipt } = await mintBatch.send({
|
|
475
|
+
from: liquidityProvider,
|
|
476
|
+
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
477
|
+
});
|
|
478
|
+
|
|
479
|
+
this.log.info(`Sent mint tx: ${mintReceipt.txHash.toString()}`);
|
|
480
|
+
|
|
481
|
+
const addLiquidityInteraction = amm.methods.add_liquidity(
|
|
482
|
+
amount0Max,
|
|
483
|
+
amount1Max,
|
|
484
|
+
amount0Min,
|
|
485
|
+
amount1Min,
|
|
486
|
+
authwitNonce,
|
|
487
|
+
);
|
|
488
|
+
const { receipt: addLiquidityReceipt } = await addLiquidityInteraction.send({
|
|
489
|
+
from: liquidityProvider,
|
|
490
|
+
authWitnesses: [token0Authwit, token1Authwit],
|
|
491
|
+
wait: { timeout: this.config.txMinedWaitSeconds },
|
|
492
|
+
});
|
|
493
|
+
|
|
494
|
+
this.log.info(`Sent tx to add liquidity to the AMM: ${addLiquidityReceipt.txHash.toString()}`);
|
|
495
|
+
this.log.info(`Liquidity added`);
|
|
496
|
+
|
|
497
|
+
const [newT0Bal, newT1Bal, newLPBal] = await getPrivateBalances();
|
|
498
|
+
this.log.info(
|
|
499
|
+
`Updated private balances of ${defaultAccountAddress} after minting and funding AMM: token0=${newT0Bal}, token1=${newT1Bal}, lp=${newLPBal}`,
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
private async registerOrDeployContract<T extends ContractBase>(
|
|
504
|
+
name: string,
|
|
505
|
+
deploy: DeployMethod<T>,
|
|
506
|
+
deployOpts: DeployOptions,
|
|
507
|
+
): Promise<ContractInstanceWithAddress> {
|
|
508
|
+
const instance = await deploy.getInstance();
|
|
509
|
+
const address = instance.address;
|
|
510
|
+
const metadata = await this.wallet.getContractMetadata(address);
|
|
511
|
+
if (metadata.isContractPublished) {
|
|
512
|
+
this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
|
|
513
|
+
await deploy.register();
|
|
158
514
|
} else {
|
|
159
|
-
|
|
160
|
-
const
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
515
|
+
const sender = deployOpts.from === NO_FROM ? undefined : deployOpts.from;
|
|
516
|
+
const balance = sender ? await getFeeJuiceBalance(sender, this.aztecNode) : 0n;
|
|
517
|
+
const useClaim =
|
|
518
|
+
sender &&
|
|
519
|
+
balance < FEE_JUICE_TOP_UP_THRESHOLD &&
|
|
520
|
+
this.config.feePaymentMethod === 'fee_juice' &&
|
|
521
|
+
!!this.config.l1RpcUrls?.length;
|
|
522
|
+
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
523
|
+
|
|
524
|
+
if (useClaim && mnemonicOrPrivateKey) {
|
|
525
|
+
const claim = await this.getOrCreateBridgeClaim(sender!);
|
|
526
|
+
const paymentMethod = new FeeJuicePaymentMethodWithClaim(sender!, claim);
|
|
527
|
+
const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true, paymentMethod } });
|
|
528
|
+
const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
|
|
529
|
+
const gasSettings = GasSettings.from({
|
|
530
|
+
...estimatedGas!,
|
|
531
|
+
maxFeesPerGas,
|
|
532
|
+
maxPriorityFeesPerGas: GasFees.empty(),
|
|
533
|
+
});
|
|
534
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
535
|
+
const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings, paymentMethod }, wait: NO_WAIT });
|
|
536
|
+
this.log.info(
|
|
537
|
+
`Sent contract ${name} deploy tx ${txHash.toString()} (using bridge claim, balance was ${balance})`,
|
|
538
|
+
);
|
|
539
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
540
|
+
});
|
|
541
|
+
await this.store.deleteBridgeClaim(sender!);
|
|
542
|
+
} else {
|
|
543
|
+
const { estimatedGas } = await deploy.simulate({ ...deployOpts, fee: { estimateGas: true } });
|
|
544
|
+
this.log.info(`Deploying contract ${name} at ${address.toString()}`, { estimatedGas });
|
|
545
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
546
|
+
const { txHash } = await deploy.send({ ...deployOpts, fee: { gasSettings: estimatedGas }, wait: NO_WAIT });
|
|
547
|
+
this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
|
|
548
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
549
|
+
});
|
|
550
|
+
}
|
|
166
551
|
}
|
|
552
|
+
return instance;
|
|
167
553
|
}
|
|
168
554
|
|
|
169
555
|
/**
|
|
170
556
|
* Mints private and public tokens for the sender if their balance is below the minimum.
|
|
171
557
|
* @param token - Token contract.
|
|
172
558
|
*/
|
|
173
|
-
|
|
174
|
-
|
|
559
|
+
/**
|
|
560
|
+
* Ensures the account has sufficient fee juice by bridging from L1 if balance is below threshold.
|
|
561
|
+
* Bridges repeatedly until balance reaches the target (10k FJ).
|
|
562
|
+
* Used on startup/restart to top up when the account has run out after previous runs.
|
|
563
|
+
*/
|
|
564
|
+
private async ensureFeeJuiceBalance(
|
|
565
|
+
account: AztecAddress,
|
|
566
|
+
token: TokenContract | PrivateTokenContract,
|
|
567
|
+
): Promise<void> {
|
|
568
|
+
const { feePaymentMethod, l1RpcUrls } = this.config;
|
|
569
|
+
if (feePaymentMethod !== 'fee_juice' || !l1RpcUrls?.length) {
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
573
|
+
if (!mnemonicOrPrivateKey) {
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
let balance = await getFeeJuiceBalance(account, this.aztecNode);
|
|
578
|
+
if (balance >= FEE_JUICE_TOP_UP_THRESHOLD) {
|
|
579
|
+
this.log.info(`Fee juice balance ${balance} above threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, skipping top-up`);
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
this.log.info(
|
|
584
|
+
`Fee juice balance ${balance} below threshold ${FEE_JUICE_TOP_UP_THRESHOLD}, bridging from L1 until ${FEE_JUICE_TOP_UP_TARGET}`,
|
|
585
|
+
);
|
|
586
|
+
const maxFeesPerGas = (await this.getMinFees()).mul(1 + this.config.minFeePadding);
|
|
587
|
+
const minimalInteraction = isStandardTokenContract(token)
|
|
588
|
+
? token.methods.transfer_in_public(account, account, 0n, 0)
|
|
589
|
+
: token.methods.transfer(0n, account, account);
|
|
590
|
+
|
|
591
|
+
while (balance < FEE_JUICE_TOP_UP_TARGET) {
|
|
592
|
+
const claim = await this.bridgeL1FeeJuice(account);
|
|
593
|
+
const paymentMethod = new FeeJuicePaymentMethodWithClaim(account, claim);
|
|
594
|
+
const { estimatedGas } = await minimalInteraction.simulate({
|
|
595
|
+
from: account,
|
|
596
|
+
fee: { estimateGas: true, paymentMethod },
|
|
597
|
+
});
|
|
598
|
+
const gasSettings = GasSettings.from({
|
|
599
|
+
...estimatedGas!,
|
|
600
|
+
maxFeesPerGas,
|
|
601
|
+
maxPriorityFeesPerGas: GasFees.empty(),
|
|
602
|
+
});
|
|
603
|
+
|
|
604
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
605
|
+
const { txHash } = await minimalInteraction.send({
|
|
606
|
+
from: account,
|
|
607
|
+
fee: { gasSettings, paymentMethod },
|
|
608
|
+
wait: NO_WAIT,
|
|
609
|
+
});
|
|
610
|
+
this.log.info(`Sent fee juice top-up tx ${txHash.toString()}`);
|
|
611
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
612
|
+
});
|
|
613
|
+
balance = await getFeeJuiceBalance(account, this.aztecNode);
|
|
614
|
+
this.log.info(`Fee juice balance after top-up: ${balance}`);
|
|
615
|
+
}
|
|
616
|
+
this.log.info(`Fee juice top-up complete for ${account.toString()}`);
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
private async mintTokens(token: TokenContract | PrivateTokenContract, minter: AztecAddress) {
|
|
175
620
|
const isStandardToken = isStandardTokenContract(token);
|
|
176
621
|
let privateBalance = 0n;
|
|
177
622
|
let publicBalance = 0n;
|
|
178
623
|
|
|
179
624
|
if (isStandardToken) {
|
|
180
|
-
({ privateBalance, publicBalance } = await getBalances(token,
|
|
625
|
+
({ privateBalance, publicBalance } = await getBalances(token, minter));
|
|
181
626
|
} else {
|
|
182
|
-
privateBalance = await getPrivateBalance(token,
|
|
627
|
+
privateBalance = await getPrivateBalance(token, minter);
|
|
183
628
|
}
|
|
184
629
|
|
|
185
|
-
const calls:
|
|
630
|
+
const calls: ContractFunctionInteraction[] = [];
|
|
186
631
|
if (privateBalance < MIN_BALANCE) {
|
|
187
|
-
this.log.info(`Minting private tokens for ${
|
|
632
|
+
this.log.info(`Minting private tokens for ${minter.toString()}`);
|
|
188
633
|
|
|
189
|
-
const from = sender; // we are setting from to sender here because we need a sender to calculate the tag
|
|
190
634
|
calls.push(
|
|
191
635
|
isStandardToken
|
|
192
|
-
?
|
|
193
|
-
:
|
|
636
|
+
? token.methods.mint_to_private(minter, MINT_BALANCE)
|
|
637
|
+
: token.methods.mint(MINT_BALANCE, minter),
|
|
194
638
|
);
|
|
195
639
|
}
|
|
196
640
|
if (isStandardToken && publicBalance < MIN_BALANCE) {
|
|
197
|
-
this.log.info(`Minting public tokens for ${
|
|
198
|
-
calls.push(
|
|
641
|
+
this.log.info(`Minting public tokens for ${minter.toString()}`);
|
|
642
|
+
calls.push(token.methods.mint_to_public(minter, MINT_BALANCE));
|
|
199
643
|
}
|
|
200
644
|
if (calls.length === 0) {
|
|
201
|
-
this.log.info(`Skipping minting as ${
|
|
645
|
+
this.log.info(`Skipping minting as ${minter.toString()} has enough tokens`);
|
|
202
646
|
return;
|
|
203
647
|
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
this.
|
|
209
|
-
|
|
648
|
+
|
|
649
|
+
// PrivateToken's mint accesses contract-level private storage vars (admin, total_supply).
|
|
650
|
+
const additionalScopes = isStandardToken ? undefined : [token.address];
|
|
651
|
+
const mintBatch = new BatchCall(token.wallet, calls);
|
|
652
|
+
await this.withNoMinTxsPerBlock(async () => {
|
|
653
|
+
const { txHash } = await mintBatch.send({
|
|
654
|
+
from: minter,
|
|
655
|
+
additionalScopes,
|
|
656
|
+
wait: NO_WAIT,
|
|
657
|
+
});
|
|
658
|
+
this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
|
|
659
|
+
return waitForTx(this.aztecNode, txHash, { timeout: this.config.txMinedWaitSeconds });
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* Gets or creates a bridge claim for the recipient.
|
|
665
|
+
* Checks if a claim already exists in the store and reuses it if valid.
|
|
666
|
+
* Only creates a new bridge if fee juice balance is below threshold.
|
|
667
|
+
*/
|
|
668
|
+
private async getOrCreateBridgeClaim(recipient: AztecAddress): Promise<L2AmountClaim> {
|
|
669
|
+
// Check if we have an existing claim in the store
|
|
670
|
+
const existingClaim = await this.store.getBridgeClaim(recipient);
|
|
671
|
+
if (existingClaim) {
|
|
672
|
+
this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
|
|
673
|
+
|
|
674
|
+
// Check if the message is ready on L2
|
|
675
|
+
try {
|
|
676
|
+
const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
|
|
677
|
+
await this.withNoMinTxsPerBlock(() =>
|
|
678
|
+
waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
|
|
679
|
+
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
680
|
+
}),
|
|
681
|
+
);
|
|
682
|
+
return existingClaim.claim;
|
|
683
|
+
} catch (err) {
|
|
684
|
+
this.log.warn(`Failed to verify existing claim, creating new one: ${err}`);
|
|
685
|
+
await this.store.deleteBridgeClaim(recipient);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
const claim = await this.bridgeL1FeeJuice(recipient);
|
|
690
|
+
await this.store.saveBridgeClaim(recipient, claim);
|
|
691
|
+
|
|
692
|
+
return claim;
|
|
210
693
|
}
|
|
211
694
|
|
|
212
|
-
private async bridgeL1FeeJuice(recipient: AztecAddress
|
|
695
|
+
private async bridgeL1FeeJuice(recipient: AztecAddress): Promise<L2AmountClaim> {
|
|
213
696
|
const l1RpcUrls = this.config.l1RpcUrls;
|
|
214
697
|
if (!l1RpcUrls?.length) {
|
|
215
698
|
throw new Error('L1 Rpc url is required to bridge the fee juice to fund the deployment of the account.');
|
|
216
699
|
}
|
|
217
|
-
const mnemonicOrPrivateKey = this.config.l1PrivateKey
|
|
700
|
+
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
218
701
|
if (!mnemonicOrPrivateKey) {
|
|
219
702
|
throw new Error(
|
|
220
703
|
'Either a mnemonic or private key of an L1 account is required to bridge the fee juice to fund the deployment of the account.',
|
|
221
704
|
);
|
|
222
705
|
}
|
|
223
706
|
|
|
224
|
-
const { l1ChainId } = await this.
|
|
707
|
+
const { l1ChainId } = await this.aztecNode.getNodeInfo();
|
|
225
708
|
const chain = createEthereumChain(l1RpcUrls, l1ChainId);
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
const portal = await L1FeeJuicePortalManager.new(this.pxe, publicClient, walletClient, this.log);
|
|
229
|
-
const claim = await portal.bridgeTokensPublic(recipient, amount, true /* mint */);
|
|
709
|
+
const extendedClient = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
|
|
230
710
|
|
|
231
|
-
const
|
|
232
|
-
|
|
711
|
+
const portal = await L1FeeJuicePortalManager.new(this.aztecNode, extendedClient, this.log);
|
|
712
|
+
const mintAmount = await portal.getTokenManager().getMintAmount();
|
|
713
|
+
const claim = await portal.bridgeTokensPublic(recipient, mintAmount, true /* mint */);
|
|
233
714
|
|
|
234
|
-
this.
|
|
715
|
+
await this.withNoMinTxsPerBlock(() =>
|
|
716
|
+
waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
|
|
717
|
+
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
718
|
+
}),
|
|
719
|
+
);
|
|
235
720
|
|
|
236
|
-
|
|
237
|
-
await this.advanceL2Block();
|
|
238
|
-
await this.advanceL2Block();
|
|
721
|
+
this.log.info(`Created a claim for ${mintAmount} L1 fee juice to ${recipient}.`, claim);
|
|
239
722
|
|
|
240
|
-
return claim;
|
|
723
|
+
return claim as L2AmountClaim;
|
|
241
724
|
}
|
|
242
725
|
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
726
|
+
/** Returns worst-case min fees across predicted slots, with fallback to current min fees. */
|
|
727
|
+
private async getMinFees(): Promise<GasFees> {
|
|
728
|
+
try {
|
|
729
|
+
const predicted = await this.aztecNode.getPredictedMinFees(ManaUsageEstimate.Limit);
|
|
730
|
+
if (predicted.length === 0) {
|
|
731
|
+
return this.aztecNode.getCurrentMinFees();
|
|
732
|
+
}
|
|
733
|
+
return predicted.reduce((worst, fees) => (fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst));
|
|
734
|
+
} catch {
|
|
735
|
+
return this.aztecNode.getCurrentMinFees();
|
|
736
|
+
}
|
|
247
737
|
}
|
|
248
738
|
|
|
249
|
-
private async
|
|
250
|
-
if (this.config.flushSetupTransactions) {
|
|
251
|
-
this.log.verbose(
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
739
|
+
private async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
|
|
740
|
+
if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
|
|
741
|
+
this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
|
|
742
|
+
return fn();
|
|
743
|
+
}
|
|
744
|
+
const { minTxsPerBlock } = await this.aztecNodeAdmin.getConfig();
|
|
745
|
+
this.log.warn(`Setting sequencer minTxsPerBlock to 0 from ${minTxsPerBlock} to flush setup transactions`);
|
|
746
|
+
await this.aztecNodeAdmin.setConfig({ minTxsPerBlock: 0 });
|
|
747
|
+
try {
|
|
748
|
+
return await fn();
|
|
749
|
+
} finally {
|
|
750
|
+
this.log.warn(`Restoring sequencer minTxsPerBlock to ${minTxsPerBlock}`);
|
|
751
|
+
await this.aztecNodeAdmin.setConfig({ minTxsPerBlock });
|
|
257
752
|
}
|
|
258
753
|
}
|
|
259
754
|
}
|