@aztec/bot 0.0.0-test.0 → 0.0.1-commit.24de95ac
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 +33 -0
- package/dest/amm_bot.d.ts.map +1 -0
- package/dest/amm_bot.js +97 -0
- package/dest/base_bot.d.ts +21 -0
- package/dest/base_bot.d.ts.map +1 -0
- package/dest/base_bot.js +80 -0
- package/dest/bot.d.ts +12 -17
- package/dest/bot.d.ts.map +1 -1
- package/dest/bot.js +24 -86
- package/dest/config.d.ts +66 -41
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +55 -32
- package/dest/factory.d.ts +38 -16
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +277 -132
- package/dest/index.d.ts +3 -1
- package/dest/index.d.ts.map +1 -1
- package/dest/index.js +3 -1
- package/dest/interface.d.ts +11 -0
- package/dest/interface.d.ts.map +1 -1
- package/dest/interface.js +5 -0
- package/dest/rpc.d.ts +0 -6
- package/dest/rpc.d.ts.map +1 -1
- package/dest/rpc.js +0 -11
- package/dest/runner.d.ts +14 -10
- package/dest/runner.d.ts.map +1 -1
- package/dest/runner.js +33 -25
- package/dest/store/bot_store.d.ts +44 -0
- package/dest/store/bot_store.d.ts.map +1 -0
- package/dest/store/bot_store.js +107 -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 +7 -4
- package/dest/utils.d.ts.map +1 -1
- package/dest/utils.js +14 -5
- package/package.json +24 -21
- package/src/amm_bot.ts +124 -0
- package/src/base_bot.ts +96 -0
- package/src/bot.ts +52 -103
- package/src/config.ts +66 -38
- package/src/factory.ts +321 -145
- package/src/index.ts +3 -1
- package/src/interface.ts +9 -0
- package/src/rpc.ts +0 -13
- package/src/runner.ts +38 -21
- package/src/store/bot_store.ts +141 -0
- package/src/store/index.ts +1 -0
- package/src/utils.ts +17 -6
package/src/factory.ts
CHANGED
|
@@ -1,72 +1,81 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { SchnorrAccountContract } from '@aztec/accounts/schnorr';
|
|
2
|
+
import { getInitialTestAccountsData } from '@aztec/accounts/testing';
|
|
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/
|
|
17
|
-
import { createEthereumChain, createL1Clients } from '@aztec/ethereum';
|
|
10
|
+
} from '@aztec/aztec.js/contracts';
|
|
11
|
+
import { L1FeeJuicePortalManager } from '@aztec/aztec.js/ethereum';
|
|
12
|
+
import type { L2AmountClaim } from '@aztec/aztec.js/ethereum';
|
|
13
|
+
import { FeeJuicePaymentMethodWithClaim } from '@aztec/aztec.js/fee';
|
|
14
|
+
import { createLogger } from '@aztec/aztec.js/log';
|
|
15
|
+
import { waitForL1ToL2MessageReady } from '@aztec/aztec.js/messaging';
|
|
16
|
+
import { createEthereumChain, createExtendedL1Client } from '@aztec/ethereum';
|
|
18
17
|
import { Fr } from '@aztec/foundation/fields';
|
|
19
|
-
import {
|
|
18
|
+
import { Timer } from '@aztec/foundation/timer';
|
|
19
|
+
import { AMMContract } from '@aztec/noir-contracts.js/AMM';
|
|
20
|
+
import { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
|
|
20
21
|
import { TokenContract } from '@aztec/noir-contracts.js/Token';
|
|
21
|
-
import
|
|
22
|
+
import { GasSettings } from '@aztec/stdlib/gas';
|
|
23
|
+
import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
|
|
22
24
|
import { deriveSigningKey } from '@aztec/stdlib/keys';
|
|
23
|
-
import {
|
|
25
|
+
import { TestWallet } from '@aztec/test-wallet/server';
|
|
24
26
|
|
|
25
|
-
import { type BotConfig, SupportedTokenContracts
|
|
27
|
+
import { type BotConfig, SupportedTokenContracts } from './config.js';
|
|
28
|
+
import type { BotStore } from './store/index.js';
|
|
26
29
|
import { getBalances, getPrivateBalance, isStandardTokenContract } from './utils.js';
|
|
27
30
|
|
|
28
31
|
const MINT_BALANCE = 1e12;
|
|
29
32
|
const MIN_BALANCE = 1e3;
|
|
30
33
|
|
|
31
34
|
export class BotFactory {
|
|
32
|
-
private pxe: PXE;
|
|
33
|
-
private node?: AztecNode;
|
|
34
35
|
private log = createLogger('bot');
|
|
35
36
|
|
|
36
|
-
constructor(
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
);
|
|
44
|
-
}
|
|
45
|
-
if (!dependencies.pxe && !config.pxeUrl) {
|
|
46
|
-
throw new Error(`Either a PXE client or a PXE URL must be provided`);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
this.node = dependencies.node;
|
|
50
|
-
|
|
51
|
-
if (dependencies.pxe) {
|
|
52
|
-
this.log.info(`Using local PXE`);
|
|
53
|
-
this.pxe = dependencies.pxe;
|
|
54
|
-
return;
|
|
55
|
-
}
|
|
56
|
-
this.log.info(`Using remote PXE at ${config.pxeUrl!}`);
|
|
57
|
-
this.pxe = createPXEClient(config.pxeUrl!, getVersions(), makeTracedFetch([1, 2, 3], false));
|
|
58
|
-
}
|
|
37
|
+
constructor(
|
|
38
|
+
private readonly config: BotConfig,
|
|
39
|
+
private readonly wallet: TestWallet,
|
|
40
|
+
private readonly store: BotStore,
|
|
41
|
+
private readonly aztecNode: AztecNode,
|
|
42
|
+
private readonly aztecNodeAdmin?: AztecNodeAdmin,
|
|
43
|
+
) {}
|
|
59
44
|
|
|
60
45
|
/**
|
|
61
46
|
* Initializes a new bot by setting up the sender account, registering the recipient,
|
|
62
47
|
* deploying the token contract, and minting tokens if necessary.
|
|
63
48
|
*/
|
|
64
49
|
public async setup() {
|
|
65
|
-
const recipient = await this.
|
|
66
|
-
const
|
|
67
|
-
const token = await this.setupToken(
|
|
68
|
-
await this.mintTokens(token);
|
|
69
|
-
return { wallet, token,
|
|
50
|
+
const recipient = (await this.wallet.createAccount()).address;
|
|
51
|
+
const defaultAccountAddress = await this.setupAccount();
|
|
52
|
+
const token = await this.setupToken(defaultAccountAddress);
|
|
53
|
+
await this.mintTokens(token, defaultAccountAddress);
|
|
54
|
+
return { wallet: this.wallet, defaultAccountAddress, token, node: this.aztecNode, recipient };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
public async setupAmm() {
|
|
58
|
+
const defaultAccountAddress = await this.setupAccount();
|
|
59
|
+
const token0 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken0', 'BOT0');
|
|
60
|
+
const token1 = await this.setupTokenContract(defaultAccountAddress, this.config.tokenSalt, 'BotToken1', 'BOT1');
|
|
61
|
+
const liquidityToken = await this.setupTokenContract(
|
|
62
|
+
defaultAccountAddress,
|
|
63
|
+
this.config.tokenSalt,
|
|
64
|
+
'BotLPToken',
|
|
65
|
+
'BOTLP',
|
|
66
|
+
);
|
|
67
|
+
const amm = await this.setupAmmContract(
|
|
68
|
+
defaultAccountAddress,
|
|
69
|
+
this.config.tokenSalt,
|
|
70
|
+
token0,
|
|
71
|
+
token1,
|
|
72
|
+
liquidityToken,
|
|
73
|
+
);
|
|
74
|
+
|
|
75
|
+
await this.fundAmm(defaultAccountAddress, defaultAccountAddress, amm, token0, token1, liquidityToken);
|
|
76
|
+
this.log.info(`AMM initialized and funded`);
|
|
77
|
+
|
|
78
|
+
return { wallet: this.wallet, defaultAccountAddress, amm, token0, token1, node: this.aztecNode };
|
|
70
79
|
}
|
|
71
80
|
|
|
72
81
|
/**
|
|
@@ -74,61 +83,65 @@ export class BotFactory {
|
|
|
74
83
|
* @returns The sender wallet.
|
|
75
84
|
*/
|
|
76
85
|
private async setupAccount() {
|
|
77
|
-
|
|
78
|
-
|
|
86
|
+
const privateKey = this.config.senderPrivateKey?.getValue();
|
|
87
|
+
if (privateKey) {
|
|
88
|
+
this.log.info(`Setting up account with provided private key`);
|
|
89
|
+
return await this.setupAccountWithPrivateKey(privateKey);
|
|
79
90
|
} else {
|
|
91
|
+
this.log.info(`Setting up test account`);
|
|
80
92
|
return await this.setupTestAccount();
|
|
81
93
|
}
|
|
82
94
|
}
|
|
83
95
|
|
|
84
|
-
private async setupAccountWithPrivateKey(
|
|
85
|
-
const salt = Fr.ONE;
|
|
86
|
-
const signingKey = deriveSigningKey(
|
|
87
|
-
const
|
|
88
|
-
|
|
96
|
+
private async setupAccountWithPrivateKey(secret: Fr) {
|
|
97
|
+
const salt = this.config.senderSalt ?? Fr.ONE;
|
|
98
|
+
const signingKey = deriveSigningKey(secret);
|
|
99
|
+
const accountData = {
|
|
100
|
+
secret,
|
|
101
|
+
salt,
|
|
102
|
+
contract: new SchnorrAccountContract(signingKey!),
|
|
103
|
+
};
|
|
104
|
+
const accountManager = await this.wallet.createAccount(accountData);
|
|
105
|
+
const isInit = (await this.wallet.getContractMetadata(accountManager.address)).isContractInitialized;
|
|
89
106
|
if (isInit) {
|
|
90
|
-
this.log.info(`Account at ${
|
|
91
|
-
const
|
|
92
|
-
|
|
107
|
+
this.log.info(`Account at ${accountManager.address.toString()} already initialized`);
|
|
108
|
+
const timer = new Timer();
|
|
109
|
+
const address = accountManager.address;
|
|
110
|
+
this.log.info(`Account at ${address} registered. duration=${timer.ms()}`);
|
|
111
|
+
await this.store.deleteBridgeClaim(address);
|
|
112
|
+
return address;
|
|
93
113
|
} else {
|
|
94
|
-
const address =
|
|
114
|
+
const address = accountManager.address;
|
|
95
115
|
this.log.info(`Deploying account at ${address}`);
|
|
96
116
|
|
|
97
|
-
const claim = await this.
|
|
117
|
+
const claim = await this.getOrCreateBridgeClaim(address);
|
|
98
118
|
|
|
99
|
-
const
|
|
100
|
-
const
|
|
101
|
-
const
|
|
119
|
+
const paymentMethod = new FeeJuicePaymentMethodWithClaim(accountManager.address, claim);
|
|
120
|
+
const deployMethod = await accountManager.getDeployMethod();
|
|
121
|
+
const maxFeesPerGas = (await this.aztecNode.getCurrentBaseFees()).mul(1 + this.config.baseFeePadding);
|
|
122
|
+
const gasSettings = GasSettings.default({ maxFeesPerGas });
|
|
123
|
+
const sentTx = deployMethod.send({ from: AztecAddress.ZERO, fee: { gasSettings, paymentMethod } });
|
|
102
124
|
const txHash = await sentTx.getTxHash();
|
|
103
|
-
this.log.info(`Sent tx with hash ${txHash.toString()}`);
|
|
104
|
-
await this.
|
|
105
|
-
this.log.verbose('Waiting for account deployment to settle');
|
|
106
|
-
await sentTx.wait({ timeout: this.config.txMinedWaitSeconds });
|
|
125
|
+
this.log.info(`Sent tx for account deployment with hash ${txHash.toString()}`);
|
|
126
|
+
await this.withNoMinTxsPerBlock(() => sentTx.wait({ timeout: this.config.txMinedWaitSeconds }));
|
|
107
127
|
this.log.info(`Account deployed at ${address}`);
|
|
108
|
-
return wallet;
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
128
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
} else {
|
|
117
|
-
this.log.info('Registering funded test account');
|
|
118
|
-
const [account] = await getInitialTestAccounts();
|
|
119
|
-
const manager = await getSchnorrAccount(this.pxe, account.secret, account.signingKey, account.salt);
|
|
120
|
-
wallet = await manager.register();
|
|
121
|
-
this.log.info(`Funded test account registered: ${wallet.getAddress()}`);
|
|
129
|
+
// Clean up the consumed bridge claim
|
|
130
|
+
await this.store.deleteBridgeClaim(address);
|
|
131
|
+
|
|
132
|
+
return accountManager.address;
|
|
122
133
|
}
|
|
123
|
-
return wallet;
|
|
124
134
|
}
|
|
125
135
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
136
|
+
private async setupTestAccount() {
|
|
137
|
+
const [initialAccountData] = await getInitialTestAccountsData();
|
|
138
|
+
const accountData = {
|
|
139
|
+
secret: initialAccountData.secret,
|
|
140
|
+
salt: initialAccountData.salt,
|
|
141
|
+
contract: new SchnorrAccountContract(initialAccountData.signingKey),
|
|
142
|
+
};
|
|
143
|
+
const accountManager = await this.wallet.createAccount(accountData);
|
|
144
|
+
return accountManager.address;
|
|
132
145
|
}
|
|
133
146
|
|
|
134
147
|
/**
|
|
@@ -136,33 +149,167 @@ export class BotFactory {
|
|
|
136
149
|
* @param wallet - Wallet to deploy the token contract from.
|
|
137
150
|
* @returns The TokenContract instance.
|
|
138
151
|
*/
|
|
139
|
-
private async setupToken(
|
|
140
|
-
let deploy: DeployMethod<TokenContract |
|
|
141
|
-
const deployOpts: DeployOptions = {
|
|
152
|
+
private async setupToken(sender: AztecAddress): Promise<TokenContract | PrivateTokenContract> {
|
|
153
|
+
let deploy: DeployMethod<TokenContract | PrivateTokenContract>;
|
|
154
|
+
const deployOpts: DeployOptions = {
|
|
155
|
+
from: sender,
|
|
156
|
+
contractAddressSalt: this.config.tokenSalt,
|
|
157
|
+
universalDeploy: true,
|
|
158
|
+
};
|
|
142
159
|
if (this.config.contract === SupportedTokenContracts.TokenContract) {
|
|
143
|
-
deploy = TokenContract.deploy(wallet,
|
|
144
|
-
} else if (this.config.contract === SupportedTokenContracts.
|
|
145
|
-
deploy =
|
|
146
|
-
deployOpts.
|
|
147
|
-
deployOpts.
|
|
160
|
+
deploy = TokenContract.deploy(this.wallet, sender, 'BotToken', 'BOT', 18);
|
|
161
|
+
} else if (this.config.contract === SupportedTokenContracts.PrivateTokenContract) {
|
|
162
|
+
deploy = PrivateTokenContract.deploy(this.wallet, MINT_BALANCE, sender);
|
|
163
|
+
deployOpts.skipInstancePublication = true;
|
|
164
|
+
deployOpts.skipClassPublication = true;
|
|
148
165
|
deployOpts.skipInitialization = false;
|
|
149
|
-
deployOpts.skipPublicSimulation = true;
|
|
150
166
|
} else {
|
|
151
167
|
throw new Error(`Unsupported token contract type: ${this.config.contract}`);
|
|
152
168
|
}
|
|
153
169
|
|
|
154
170
|
const address = (await deploy.getInstance(deployOpts)).address;
|
|
155
|
-
if ((await this.
|
|
171
|
+
if ((await this.wallet.getContractMetadata(address)).isContractPublished) {
|
|
156
172
|
this.log.info(`Token at ${address.toString()} already deployed`);
|
|
157
173
|
return deploy.register();
|
|
158
174
|
} else {
|
|
159
175
|
this.log.info(`Deploying token contract at ${address.toString()}`);
|
|
160
176
|
const sentTx = deploy.send(deployOpts);
|
|
161
177
|
const txHash = await sentTx.getTxHash();
|
|
162
|
-
this.log.info(`Sent tx with hash ${txHash.toString()}`);
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
178
|
+
this.log.info(`Sent tx for token setup with hash ${txHash.toString()}`);
|
|
179
|
+
return this.withNoMinTxsPerBlock(() => sentTx.deployed({ timeout: this.config.txMinedWaitSeconds }));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Checks if the token contract is deployed and deploys it if necessary.
|
|
185
|
+
* @param wallet - Wallet to deploy the token contract from.
|
|
186
|
+
* @returns The TokenContract instance.
|
|
187
|
+
*/
|
|
188
|
+
private setupTokenContract(
|
|
189
|
+
deployer: AztecAddress,
|
|
190
|
+
contractAddressSalt: Fr,
|
|
191
|
+
name: string,
|
|
192
|
+
ticker: string,
|
|
193
|
+
decimals = 18,
|
|
194
|
+
): Promise<TokenContract> {
|
|
195
|
+
const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
|
|
196
|
+
const deploy = TokenContract.deploy(this.wallet, deployer, name, ticker, decimals);
|
|
197
|
+
return this.registerOrDeployContract('Token - ' + name, deploy, deployOpts);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
private async setupAmmContract(
|
|
201
|
+
deployer: AztecAddress,
|
|
202
|
+
contractAddressSalt: Fr,
|
|
203
|
+
token0: TokenContract,
|
|
204
|
+
token1: TokenContract,
|
|
205
|
+
lpToken: TokenContract,
|
|
206
|
+
): Promise<AMMContract> {
|
|
207
|
+
const deployOpts: DeployOptions = { from: deployer, contractAddressSalt, universalDeploy: true };
|
|
208
|
+
const deploy = AMMContract.deploy(this.wallet, token0.address, token1.address, lpToken.address);
|
|
209
|
+
const amm = await this.registerOrDeployContract('AMM', deploy, deployOpts);
|
|
210
|
+
|
|
211
|
+
this.log.info(`AMM deployed at ${amm.address}`);
|
|
212
|
+
const minterTx = lpToken.methods.set_minter(amm.address, true).send({ from: deployer });
|
|
213
|
+
this.log.info(`Set LP token minter to AMM txHash=${(await minterTx.getTxHash()).toString()}`);
|
|
214
|
+
await minterTx.wait({ timeout: this.config.txMinedWaitSeconds });
|
|
215
|
+
this.log.info(`Liquidity token initialized`);
|
|
216
|
+
|
|
217
|
+
return amm;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
private async fundAmm(
|
|
221
|
+
defaultAccountAddress: AztecAddress,
|
|
222
|
+
liquidityProvider: AztecAddress,
|
|
223
|
+
amm: AMMContract,
|
|
224
|
+
token0: TokenContract,
|
|
225
|
+
token1: TokenContract,
|
|
226
|
+
lpToken: TokenContract,
|
|
227
|
+
): Promise<void> {
|
|
228
|
+
const getPrivateBalances = () =>
|
|
229
|
+
Promise.all([
|
|
230
|
+
token0.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
|
|
231
|
+
token1.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
|
|
232
|
+
lpToken.methods.balance_of_private(liquidityProvider).simulate({ from: liquidityProvider }),
|
|
233
|
+
]);
|
|
234
|
+
|
|
235
|
+
const authwitNonce = Fr.random();
|
|
236
|
+
|
|
237
|
+
// keep some tokens for swapping
|
|
238
|
+
const amount0Max = MINT_BALANCE / 2;
|
|
239
|
+
const amount0Min = MINT_BALANCE / 4;
|
|
240
|
+
const amount1Max = MINT_BALANCE / 2;
|
|
241
|
+
const amount1Min = MINT_BALANCE / 4;
|
|
242
|
+
|
|
243
|
+
const [t0Bal, t1Bal, lpBal] = await getPrivateBalances();
|
|
244
|
+
|
|
245
|
+
this.log.info(
|
|
246
|
+
`Minting ${MINT_BALANCE} tokens of each BotToken0 and BotToken1. Current private balances of ${liquidityProvider}: token0=${t0Bal}, token1=${t1Bal}, lp=${lpBal}`,
|
|
247
|
+
);
|
|
248
|
+
|
|
249
|
+
// Add authwitnesses for the transfers in AMM::add_liquidity function
|
|
250
|
+
const token0Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
|
|
251
|
+
caller: amm.address,
|
|
252
|
+
call: await token0.methods
|
|
253
|
+
.transfer_to_public_and_prepare_private_balance_increase(
|
|
254
|
+
liquidityProvider,
|
|
255
|
+
amm.address,
|
|
256
|
+
amount0Max,
|
|
257
|
+
authwitNonce,
|
|
258
|
+
)
|
|
259
|
+
.getFunctionCall(),
|
|
260
|
+
});
|
|
261
|
+
const token1Authwit = await this.wallet.createAuthWit(defaultAccountAddress, {
|
|
262
|
+
caller: amm.address,
|
|
263
|
+
call: await token1.methods
|
|
264
|
+
.transfer_to_public_and_prepare_private_balance_increase(
|
|
265
|
+
liquidityProvider,
|
|
266
|
+
amm.address,
|
|
267
|
+
amount1Max,
|
|
268
|
+
authwitNonce,
|
|
269
|
+
)
|
|
270
|
+
.getFunctionCall(),
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
const mintTx = new BatchCall(this.wallet, [
|
|
274
|
+
token0.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
|
|
275
|
+
token1.methods.mint_to_private(liquidityProvider, MINT_BALANCE),
|
|
276
|
+
]).send({ from: liquidityProvider });
|
|
277
|
+
|
|
278
|
+
this.log.info(`Sent mint tx: ${(await mintTx.getTxHash()).toString()}`);
|
|
279
|
+
await mintTx.wait({ timeout: this.config.txMinedWaitSeconds });
|
|
280
|
+
|
|
281
|
+
const addLiquidityTx = amm.methods
|
|
282
|
+
.add_liquidity(amount0Max, amount1Max, amount0Min, amount1Min, authwitNonce)
|
|
283
|
+
.send({
|
|
284
|
+
from: liquidityProvider,
|
|
285
|
+
authWitnesses: [token0Authwit, token1Authwit],
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
this.log.info(`Sent tx to add liquidity to the AMM: ${(await addLiquidityTx.getTxHash()).toString()}`);
|
|
289
|
+
await addLiquidityTx.wait({ timeout: this.config.txMinedWaitSeconds });
|
|
290
|
+
this.log.info(`Liquidity added`);
|
|
291
|
+
|
|
292
|
+
const [newT0Bal, newT1Bal, newLPBal] = await getPrivateBalances();
|
|
293
|
+
this.log.info(
|
|
294
|
+
`Updated private balances of ${defaultAccountAddress} after minting and funding AMM: token0=${newT0Bal}, token1=${newT1Bal}, lp=${newLPBal}`,
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
private async registerOrDeployContract<T extends ContractBase>(
|
|
299
|
+
name: string,
|
|
300
|
+
deploy: DeployMethod<T>,
|
|
301
|
+
deployOpts: DeployOptions,
|
|
302
|
+
): Promise<T> {
|
|
303
|
+
const address = (await deploy.getInstance(deployOpts)).address;
|
|
304
|
+
if ((await this.wallet.getContractMetadata(address)).isContractPublished) {
|
|
305
|
+
this.log.info(`Contract ${name} at ${address.toString()} already deployed`);
|
|
306
|
+
return deploy.register();
|
|
307
|
+
} else {
|
|
308
|
+
this.log.info(`Deploying contract ${name} at ${address.toString()}`);
|
|
309
|
+
const sentTx = deploy.send(deployOpts);
|
|
310
|
+
const txHash = await sentTx.getTxHash();
|
|
311
|
+
this.log.info(`Sent contract ${name} setup tx with hash ${txHash.toString()}`);
|
|
312
|
+
return this.withNoMinTxsPerBlock(() => sentTx.deployed({ timeout: this.config.txMinedWaitSeconds }));
|
|
166
313
|
}
|
|
167
314
|
}
|
|
168
315
|
|
|
@@ -170,90 +317,119 @@ export class BotFactory {
|
|
|
170
317
|
* Mints private and public tokens for the sender if their balance is below the minimum.
|
|
171
318
|
* @param token - Token contract.
|
|
172
319
|
*/
|
|
173
|
-
private async mintTokens(token: TokenContract |
|
|
174
|
-
const sender = token.wallet.getAddress();
|
|
320
|
+
private async mintTokens(token: TokenContract | PrivateTokenContract, minter: AztecAddress) {
|
|
175
321
|
const isStandardToken = isStandardTokenContract(token);
|
|
176
322
|
let privateBalance = 0n;
|
|
177
323
|
let publicBalance = 0n;
|
|
178
324
|
|
|
179
325
|
if (isStandardToken) {
|
|
180
|
-
({ privateBalance, publicBalance } = await getBalances(token,
|
|
326
|
+
({ privateBalance, publicBalance } = await getBalances(token, minter));
|
|
181
327
|
} else {
|
|
182
|
-
privateBalance = await getPrivateBalance(token,
|
|
328
|
+
privateBalance = await getPrivateBalance(token, minter);
|
|
183
329
|
}
|
|
184
330
|
|
|
185
|
-
const calls:
|
|
331
|
+
const calls: ContractFunctionInteraction[] = [];
|
|
186
332
|
if (privateBalance < MIN_BALANCE) {
|
|
187
|
-
this.log.info(`Minting private tokens for ${
|
|
333
|
+
this.log.info(`Minting private tokens for ${minter.toString()}`);
|
|
188
334
|
|
|
189
|
-
const from = sender; // we are setting from to sender here because we need a sender to calculate the tag
|
|
190
335
|
calls.push(
|
|
191
336
|
isStandardToken
|
|
192
|
-
?
|
|
193
|
-
:
|
|
337
|
+
? token.methods.mint_to_private(minter, MINT_BALANCE)
|
|
338
|
+
: token.methods.mint(MINT_BALANCE, minter),
|
|
194
339
|
);
|
|
195
340
|
}
|
|
196
341
|
if (isStandardToken && publicBalance < MIN_BALANCE) {
|
|
197
|
-
this.log.info(`Minting public tokens for ${
|
|
198
|
-
calls.push(
|
|
342
|
+
this.log.info(`Minting public tokens for ${minter.toString()}`);
|
|
343
|
+
calls.push(token.methods.mint_to_public(minter, MINT_BALANCE));
|
|
199
344
|
}
|
|
200
345
|
if (calls.length === 0) {
|
|
201
|
-
this.log.info(`Skipping minting as ${
|
|
346
|
+
this.log.info(`Skipping minting as ${minter.toString()} has enough tokens`);
|
|
202
347
|
return;
|
|
203
348
|
}
|
|
204
|
-
const sentTx = new BatchCall(token.wallet, calls).send();
|
|
349
|
+
const sentTx = new BatchCall(token.wallet, calls).send({ from: minter });
|
|
205
350
|
const txHash = await sentTx.getTxHash();
|
|
206
|
-
this.log.info(`Sent tx with hash ${txHash.toString()}`);
|
|
207
|
-
await this.
|
|
208
|
-
|
|
209
|
-
|
|
351
|
+
this.log.info(`Sent token mint tx with hash ${txHash.toString()}`);
|
|
352
|
+
await this.withNoMinTxsPerBlock(() => sentTx.wait({ timeout: this.config.txMinedWaitSeconds }));
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Gets or creates a bridge claim for the recipient.
|
|
357
|
+
* Checks if a claim already exists in the store and reuses it if valid.
|
|
358
|
+
* Only creates a new bridge if fee juice balance is below threshold.
|
|
359
|
+
*/
|
|
360
|
+
private async getOrCreateBridgeClaim(recipient: AztecAddress): Promise<L2AmountClaim> {
|
|
361
|
+
// Check if we have an existing claim in the store
|
|
362
|
+
const existingClaim = await this.store.getBridgeClaim(recipient);
|
|
363
|
+
if (existingClaim) {
|
|
364
|
+
this.log.info(`Found existing bridge claim for ${recipient.toString()}, checking validity...`);
|
|
365
|
+
|
|
366
|
+
// Check if the message is ready on L2
|
|
367
|
+
try {
|
|
368
|
+
const messageHash = Fr.fromHexString(existingClaim.claim.messageHash);
|
|
369
|
+
await this.withNoMinTxsPerBlock(() =>
|
|
370
|
+
waitForL1ToL2MessageReady(this.aztecNode, messageHash, {
|
|
371
|
+
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
372
|
+
forPublicConsumption: false,
|
|
373
|
+
}),
|
|
374
|
+
);
|
|
375
|
+
return existingClaim.claim;
|
|
376
|
+
} catch (err) {
|
|
377
|
+
this.log.warn(`Failed to verify existing claim, creating new one: ${err}`);
|
|
378
|
+
await this.store.deleteBridgeClaim(recipient);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const claim = await this.bridgeL1FeeJuice(recipient);
|
|
383
|
+
await this.store.saveBridgeClaim(recipient, claim);
|
|
384
|
+
|
|
385
|
+
return claim;
|
|
210
386
|
}
|
|
211
387
|
|
|
212
|
-
private async bridgeL1FeeJuice(recipient: AztecAddress
|
|
388
|
+
private async bridgeL1FeeJuice(recipient: AztecAddress): Promise<L2AmountClaim> {
|
|
213
389
|
const l1RpcUrls = this.config.l1RpcUrls;
|
|
214
390
|
if (!l1RpcUrls?.length) {
|
|
215
391
|
throw new Error('L1 Rpc url is required to bridge the fee juice to fund the deployment of the account.');
|
|
216
392
|
}
|
|
217
|
-
const mnemonicOrPrivateKey = this.config.l1PrivateKey
|
|
393
|
+
const mnemonicOrPrivateKey = this.config.l1PrivateKey?.getValue() ?? this.config.l1Mnemonic?.getValue();
|
|
218
394
|
if (!mnemonicOrPrivateKey) {
|
|
219
395
|
throw new Error(
|
|
220
396
|
'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
397
|
);
|
|
222
398
|
}
|
|
223
399
|
|
|
224
|
-
const { l1ChainId } = await this.
|
|
400
|
+
const { l1ChainId } = await this.aztecNode.getNodeInfo();
|
|
225
401
|
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 */);
|
|
230
|
-
|
|
231
|
-
const isSynced = async () => await this.pxe.isL1ToL2MessageSynced(Fr.fromHexString(claim.messageHash));
|
|
232
|
-
await retryUntil(isSynced, `message ${claim.messageHash} sync`, 24, 1);
|
|
402
|
+
const extendedClient = createExtendedL1Client(chain.rpcUrls, mnemonicOrPrivateKey, chain.chainInfo);
|
|
233
403
|
|
|
234
|
-
|
|
404
|
+
const portal = await L1FeeJuicePortalManager.new(this.aztecNode, extendedClient, this.log);
|
|
405
|
+
const mintAmount = await portal.getTokenManager().getMintAmount();
|
|
406
|
+
const claim = await portal.bridgeTokensPublic(recipient, mintAmount, true /* mint */);
|
|
235
407
|
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
408
|
+
await this.withNoMinTxsPerBlock(() =>
|
|
409
|
+
waitForL1ToL2MessageReady(this.aztecNode, Fr.fromHexString(claim.messageHash), {
|
|
410
|
+
timeoutSeconds: this.config.l1ToL2MessageTimeoutSeconds,
|
|
411
|
+
forPublicConsumption: false,
|
|
412
|
+
}),
|
|
413
|
+
);
|
|
239
414
|
|
|
240
|
-
|
|
241
|
-
}
|
|
415
|
+
this.log.info(`Created a claim for ${mintAmount} L1 fee juice to ${recipient}.`, claim);
|
|
242
416
|
|
|
243
|
-
|
|
244
|
-
const initialBlockNumber = await this.node!.getBlockNumber();
|
|
245
|
-
await this.tryFlushTxs();
|
|
246
|
-
await retryUntil(async () => (await this.node!.getBlockNumber()) >= initialBlockNumber + 1);
|
|
417
|
+
return claim as L2AmountClaim;
|
|
247
418
|
}
|
|
248
419
|
|
|
249
|
-
private async
|
|
250
|
-
if (this.config.flushSetupTransactions) {
|
|
251
|
-
this.log.verbose(
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
420
|
+
private async withNoMinTxsPerBlock<T>(fn: () => Promise<T>): Promise<T> {
|
|
421
|
+
if (!this.aztecNodeAdmin || !this.config.flushSetupTransactions) {
|
|
422
|
+
this.log.verbose(`No node admin client or flushing not requested (not setting minTxsPerBlock to 0)`);
|
|
423
|
+
return fn();
|
|
424
|
+
}
|
|
425
|
+
const { minTxsPerBlock } = await this.aztecNodeAdmin.getConfig();
|
|
426
|
+
this.log.warn(`Setting sequencer minTxsPerBlock to 0 from ${minTxsPerBlock} to flush setup transactions`);
|
|
427
|
+
await this.aztecNodeAdmin.setConfig({ minTxsPerBlock: 0 });
|
|
428
|
+
try {
|
|
429
|
+
return await fn();
|
|
430
|
+
} finally {
|
|
431
|
+
this.log.warn(`Restoring sequencer minTxsPerBlock to ${minTxsPerBlock}`);
|
|
432
|
+
await this.aztecNodeAdmin.setConfig({ minTxsPerBlock });
|
|
257
433
|
}
|
|
258
434
|
}
|
|
259
435
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export { Bot } from './bot.js';
|
|
2
|
+
export { AmmBot } from './amm_bot.js';
|
|
2
3
|
export { BotRunner } from './runner.js';
|
|
4
|
+
export { BotStore } from './store/bot_store.js';
|
|
3
5
|
export {
|
|
4
6
|
type BotConfig,
|
|
5
7
|
getBotConfigFromEnv,
|
|
@@ -7,5 +9,5 @@ export {
|
|
|
7
9
|
botConfigMappings,
|
|
8
10
|
SupportedTokenContracts,
|
|
9
11
|
} from './config.js';
|
|
10
|
-
export {
|
|
12
|
+
export { getBotRunnerApiHandler } from './rpc.js';
|
|
11
13
|
export * from './interface.js';
|
package/src/interface.ts
CHANGED
|
@@ -1,15 +1,23 @@
|
|
|
1
|
+
import { AztecAddress } from '@aztec/aztec.js/addresses';
|
|
1
2
|
import type { ApiSchemaFor } from '@aztec/stdlib/schemas';
|
|
2
3
|
|
|
3
4
|
import { z } from 'zod';
|
|
4
5
|
|
|
5
6
|
import { type BotConfig, BotConfigSchema } from './config.js';
|
|
6
7
|
|
|
8
|
+
export const BotInfoSchema = z.object({
|
|
9
|
+
botAddress: AztecAddress.schema,
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
export type BotInfo = z.infer<typeof BotInfoSchema>;
|
|
13
|
+
|
|
7
14
|
export interface BotRunnerApi {
|
|
8
15
|
start(): Promise<void>;
|
|
9
16
|
stop(): Promise<void>;
|
|
10
17
|
run(): Promise<void>;
|
|
11
18
|
setup(): Promise<void>;
|
|
12
19
|
getConfig(): Promise<BotConfig>;
|
|
20
|
+
getInfo(): Promise<BotInfo>;
|
|
13
21
|
update(config: BotConfig): Promise<void>;
|
|
14
22
|
}
|
|
15
23
|
|
|
@@ -18,6 +26,7 @@ export const BotRunnerApiSchema: ApiSchemaFor<BotRunnerApi> = {
|
|
|
18
26
|
stop: z.function().args().returns(z.void()),
|
|
19
27
|
run: z.function().args().returns(z.void()),
|
|
20
28
|
setup: z.function().args().returns(z.void()),
|
|
29
|
+
getInfo: z.function().args().returns(BotInfoSchema),
|
|
21
30
|
getConfig: z.function().args().returns(BotConfigSchema),
|
|
22
31
|
update: z.function().args(BotConfigSchema).returns(z.void()),
|
|
23
32
|
};
|
package/src/rpc.ts
CHANGED
|
@@ -1,21 +1,8 @@
|
|
|
1
1
|
import type { ApiHandler } from '@aztec/foundation/json-rpc/server';
|
|
2
|
-
import { createTracedJsonRpcServer } from '@aztec/telemetry-client';
|
|
3
2
|
|
|
4
3
|
import { BotRunnerApiSchema } from './interface.js';
|
|
5
4
|
import type { BotRunner } from './runner.js';
|
|
6
5
|
|
|
7
|
-
/**
|
|
8
|
-
* Wraps a bot runner with a JSON RPC HTTP server.
|
|
9
|
-
* @param botRunner - The BotRunner.
|
|
10
|
-
* @returns An JSON-RPC HTTP server
|
|
11
|
-
*/
|
|
12
|
-
export function createBotRunnerRpcServer(botRunner: BotRunner) {
|
|
13
|
-
createTracedJsonRpcServer(botRunner, BotRunnerApiSchema, {
|
|
14
|
-
http200OnError: false,
|
|
15
|
-
healthCheck: botRunner.isHealthy.bind(botRunner),
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
|
|
19
6
|
export function getBotRunnerApiHandler(botRunner: BotRunner): ApiHandler {
|
|
20
7
|
return [botRunner, BotRunnerApiSchema, botRunner.isHealthy.bind(botRunner)];
|
|
21
8
|
}
|