@aztec/bot 0.0.0-test.1 → 0.0.1-commit.001888fc

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.
Files changed (57) hide show
  1. package/dest/amm_bot.d.ts +32 -0
  2. package/dest/amm_bot.d.ts.map +1 -0
  3. package/dest/amm_bot.js +108 -0
  4. package/dest/base_bot.d.ts +21 -0
  5. package/dest/base_bot.d.ts.map +1 -0
  6. package/dest/base_bot.js +79 -0
  7. package/dest/bot.d.ts +13 -18
  8. package/dest/bot.d.ts.map +1 -1
  9. package/dest/bot.js +26 -84
  10. package/dest/config.d.ts +106 -66
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +89 -39
  13. package/dest/cross_chain_bot.d.ts +54 -0
  14. package/dest/cross_chain_bot.d.ts.map +1 -0
  15. package/dest/cross_chain_bot.js +134 -0
  16. package/dest/factory.d.ts +43 -29
  17. package/dest/factory.d.ts.map +1 -1
  18. package/dest/factory.js +380 -139
  19. package/dest/index.d.ts +5 -2
  20. package/dest/index.d.ts.map +1 -1
  21. package/dest/index.js +4 -1
  22. package/dest/interface.d.ts +12 -1
  23. package/dest/interface.d.ts.map +1 -1
  24. package/dest/interface.js +5 -0
  25. package/dest/l1_to_l2_seeding.d.ts +8 -0
  26. package/dest/l1_to_l2_seeding.d.ts.map +1 -0
  27. package/dest/l1_to_l2_seeding.js +63 -0
  28. package/dest/rpc.d.ts +1 -7
  29. package/dest/rpc.d.ts.map +1 -1
  30. package/dest/rpc.js +0 -11
  31. package/dest/runner.d.ts +15 -11
  32. package/dest/runner.d.ts.map +1 -1
  33. package/dest/runner.js +457 -51
  34. package/dest/store/bot_store.d.ts +69 -0
  35. package/dest/store/bot_store.d.ts.map +1 -0
  36. package/dest/store/bot_store.js +138 -0
  37. package/dest/store/index.d.ts +2 -0
  38. package/dest/store/index.d.ts.map +1 -0
  39. package/dest/store/index.js +1 -0
  40. package/dest/utils.d.ts +8 -5
  41. package/dest/utils.d.ts.map +1 -1
  42. package/dest/utils.js +14 -5
  43. package/package.json +30 -23
  44. package/src/amm_bot.ts +129 -0
  45. package/src/base_bot.ts +82 -0
  46. package/src/bot.ts +52 -101
  47. package/src/config.ts +129 -71
  48. package/src/cross_chain_bot.ts +203 -0
  49. package/src/factory.ts +476 -152
  50. package/src/index.ts +4 -1
  51. package/src/interface.ts +9 -0
  52. package/src/l1_to_l2_seeding.ts +79 -0
  53. package/src/rpc.ts +0 -13
  54. package/src/runner.ts +51 -21
  55. package/src/store/bot_store.ts +196 -0
  56. package/src/store/index.ts +1 -0
  57. package/src/utils.ts +17 -6
@@ -0,0 +1,138 @@
1
+ import { Fr } from '@aztec/foundation/curves/bn254';
2
+ import { createLogger } from '@aztec/foundation/log';
3
+ import { DateProvider } from '@aztec/foundation/timer';
4
+ /**
5
+ * Simple data store for the bot to persist L1 bridge claims.
6
+ */ export class BotStore {
7
+ store;
8
+ log;
9
+ dateProvider;
10
+ static SCHEMA_VERSION = 1;
11
+ bridgeClaims;
12
+ pendingL1ToL2;
13
+ constructor(store, log = createLogger('bot:store'), dateProvider = new DateProvider()){
14
+ this.store = store;
15
+ this.log = log;
16
+ this.dateProvider = dateProvider;
17
+ this.bridgeClaims = store.openMap('bridge_claims');
18
+ this.pendingL1ToL2 = store.openMap('pending_l1_to_l2');
19
+ }
20
+ /**
21
+ * Saves a bridge claim for a recipient.
22
+ */ async saveBridgeClaim(recipient, claim) {
23
+ // Convert Fr fields and BigInts to strings for JSON serialization
24
+ const serializableClaim = {
25
+ claimAmount: claim.claimAmount.toString(),
26
+ claimSecret: claim.claimSecret.toString(),
27
+ claimSecretHash: claim.claimSecretHash.toString(),
28
+ messageHash: claim.messageHash,
29
+ messageLeafIndex: claim.messageLeafIndex.toString()
30
+ };
31
+ const data = {
32
+ claim: serializableClaim,
33
+ timestamp: this.dateProvider.now(),
34
+ recipient: recipient.toString()
35
+ };
36
+ await this.bridgeClaims.set(recipient.toString(), JSON.stringify(data));
37
+ this.log.info(`Saved bridge claim for ${recipient.toString()}`);
38
+ }
39
+ /**
40
+ * Gets a bridge claim for a recipient if it exists.
41
+ */ async getBridgeClaim(recipient) {
42
+ const data = await this.bridgeClaims.getAsync(recipient.toString());
43
+ if (!data) {
44
+ return undefined;
45
+ }
46
+ const parsed = JSON.parse(data);
47
+ // Reconstruct L2AmountClaim from serialized data
48
+ const claim = {
49
+ claimAmount: BigInt(parsed.claim.claimAmount),
50
+ claimSecret: Fr.fromString(parsed.claim.claimSecret),
51
+ claimSecretHash: Fr.fromString(parsed.claim.claimSecretHash),
52
+ messageHash: parsed.claim.messageHash,
53
+ messageLeafIndex: BigInt(parsed.claim.messageLeafIndex)
54
+ };
55
+ return {
56
+ claim,
57
+ timestamp: parsed.timestamp,
58
+ recipient: parsed.recipient
59
+ };
60
+ }
61
+ /**
62
+ * Deletes a bridge claim for a recipient.
63
+ */ async deleteBridgeClaim(recipient) {
64
+ await this.bridgeClaims.delete(recipient.toString());
65
+ this.log.info(`Deleted bridge claim for ${recipient.toString()}`);
66
+ }
67
+ /**
68
+ * Gets all stored bridge claims.
69
+ */ async getAllBridgeClaims() {
70
+ const claims = [];
71
+ const entries = this.bridgeClaims.entriesAsync();
72
+ for await (const [_, data] of entries){
73
+ const parsed = JSON.parse(data);
74
+ // Reconstruct L2AmountClaim from serialized data
75
+ const claim = {
76
+ claimAmount: BigInt(parsed.claim.claimAmount),
77
+ claimSecret: Fr.fromString(parsed.claim.claimSecret),
78
+ claimSecretHash: Fr.fromString(parsed.claim.claimSecretHash),
79
+ messageHash: parsed.claim.messageHash,
80
+ messageLeafIndex: BigInt(parsed.claim.messageLeafIndex)
81
+ };
82
+ claims.push({
83
+ claim,
84
+ timestamp: parsed.timestamp,
85
+ recipient: parsed.recipient
86
+ });
87
+ }
88
+ return claims;
89
+ }
90
+ /**
91
+ * Cleans up old bridge claims (older than 24 hours).
92
+ */ async cleanupOldClaims(maxAgeMs = 24 * 60 * 60 * 1000) {
93
+ const now = this.dateProvider.now();
94
+ let cleanedCount = 0;
95
+ const entries = this.bridgeClaims.entriesAsync();
96
+ for await (const [key, data] of entries){
97
+ const parsed = JSON.parse(data);
98
+ if (now - parsed.timestamp > maxAgeMs) {
99
+ await this.bridgeClaims.delete(key);
100
+ cleanedCount++;
101
+ this.log.info(`Cleaned up old bridge claim for ${parsed.recipient}`);
102
+ }
103
+ }
104
+ return cleanedCount;
105
+ }
106
+ /** Saves a pending L1→L2 message keyed by msgHash. */ async savePendingL1ToL2Message(msg) {
107
+ await this.pendingL1ToL2.set(msg.msgHash, JSON.stringify(msg));
108
+ this.log.info(`Saved pending L1→L2 message ${msg.msgHash}`);
109
+ }
110
+ /** Returns all unconsumed pending L1→L2 messages. */ async getUnconsumedL1ToL2Messages() {
111
+ const messages = [];
112
+ for await (const [_, data] of this.pendingL1ToL2.entriesAsync()){
113
+ messages.push(JSON.parse(data));
114
+ }
115
+ return messages;
116
+ }
117
+ /** Deletes a consumed L1→L2 message from the store. */ async deleteL1ToL2Message(msgHash) {
118
+ await this.pendingL1ToL2.delete(msgHash);
119
+ this.log.info(`Deleted consumed L1→L2 message ${msgHash}`);
120
+ }
121
+ /** Cleans up pending L1→L2 messages older than maxAgeMs. */ async cleanupOldPendingMessages(maxAgeMs = 24 * 60 * 60 * 1000) {
122
+ const now = this.dateProvider.now();
123
+ let cleanedCount = 0;
124
+ for await (const [key, data] of this.pendingL1ToL2.entriesAsync()){
125
+ const parsed = JSON.parse(data);
126
+ if (now - parsed.timestamp > maxAgeMs) {
127
+ await this.pendingL1ToL2.delete(key);
128
+ cleanedCount++;
129
+ this.log.info(`Cleaned up old pending L1→L2 message ${key}`);
130
+ }
131
+ }
132
+ return cleanedCount;
133
+ }
134
+ /** Closes the store. */ async close() {
135
+ await this.store.close();
136
+ this.log.info('Closed bot data store');
137
+ }
138
+ }
@@ -0,0 +1,2 @@
1
+ export { BotStore, type BridgeClaimData, type PendingL1ToL2Message } from './bot_store.js';
2
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9zdG9yZS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUUsUUFBUSxFQUFFLEtBQUssZUFBZSxFQUFFLEtBQUssb0JBQW9CLEVBQUUsTUFBTSxnQkFBZ0IsQ0FBQyJ9
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/store/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,KAAK,eAAe,EAAE,KAAK,oBAAoB,EAAE,MAAM,gBAAgB,CAAC"}
@@ -0,0 +1 @@
1
+ export { BotStore } from './bot_store.js';
package/dest/utils.d.ts CHANGED
@@ -1,4 +1,6 @@
1
- import type { EasyPrivateTokenContract } from '@aztec/noir-contracts.js/EasyPrivateToken';
1
+ import { ContractBase } from '@aztec/aztec.js/contracts';
2
+ import type { AMMContract } from '@aztec/noir-contracts.js/AMM';
3
+ import type { PrivateTokenContract } from '@aztec/noir-contracts.js/PrivateToken';
2
4
  import type { TokenContract } from '@aztec/noir-contracts.js/Token';
3
5
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
4
6
  /**
@@ -7,10 +9,11 @@ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
7
9
  * @param who - Address to get the balance for.
8
10
  * @returns - Private and public token balances as bigints.
9
11
  */
10
- export declare function getBalances(token: TokenContract, who: AztecAddress): Promise<{
12
+ export declare function getBalances(token: TokenContract, who: AztecAddress, from?: AztecAddress): Promise<{
11
13
  privateBalance: bigint;
12
14
  publicBalance: bigint;
13
15
  }>;
14
- export declare function getPrivateBalance(token: EasyPrivateTokenContract, who: AztecAddress): Promise<bigint>;
15
- export declare function isStandardTokenContract(token: TokenContract | EasyPrivateTokenContract): token is TokenContract;
16
- //# sourceMappingURL=utils.d.ts.map
16
+ export declare function getPrivateBalance(token: PrivateTokenContract, who: AztecAddress, from?: AztecAddress): Promise<bigint>;
17
+ export declare function isStandardTokenContract(token: ContractBase): token is TokenContract;
18
+ export declare function isAMMContract(contract: ContractBase): contract is AMMContract;
19
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXRpbHMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy91dGlscy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUUsWUFBWSxFQUFFLE1BQU0sMkJBQTJCLENBQUM7QUFDekQsT0FBTyxLQUFLLEVBQUUsV0FBVyxFQUFFLE1BQU0sOEJBQThCLENBQUM7QUFDaEUsT0FBTyxLQUFLLEVBQUUsb0JBQW9CLEVBQUUsTUFBTSx1Q0FBdUMsQ0FBQztBQUNsRixPQUFPLEtBQUssRUFBRSxhQUFhLEVBQUUsTUFBTSxnQ0FBZ0MsQ0FBQztBQUNwRSxPQUFPLEtBQUssRUFBRSxZQUFZLEVBQUUsTUFBTSw2QkFBNkIsQ0FBQztBQUVoRTs7Ozs7R0FLRztBQUNILHdCQUFzQixXQUFXLENBQy9CLEtBQUssRUFBRSxhQUFhLEVBQ3BCLEdBQUcsRUFBRSxZQUFZLEVBQ2pCLElBQUksQ0FBQyxFQUFFLFlBQVksR0FDbEIsT0FBTyxDQUFDO0lBQUUsY0FBYyxFQUFFLE1BQU0sQ0FBQztJQUFDLGFBQWEsRUFBRSxNQUFNLENBQUE7Q0FBRSxDQUFDLENBSTVEO0FBRUQsd0JBQXNCLGlCQUFpQixDQUNyQyxLQUFLLEVBQUUsb0JBQW9CLEVBQzNCLEdBQUcsRUFBRSxZQUFZLEVBQ2pCLElBQUksQ0FBQyxFQUFFLFlBQVksR0FDbEIsT0FBTyxDQUFDLE1BQU0sQ0FBQyxDQUdqQjtBQUVELHdCQUFnQix1QkFBdUIsQ0FBQyxLQUFLLEVBQUUsWUFBWSxHQUFHLEtBQUssSUFBSSxhQUFhLENBRW5GO0FBRUQsd0JBQWdCLGFBQWEsQ0FBQyxRQUFRLEVBQUUsWUFBWSxHQUFHLFFBQVEsSUFBSSxXQUFXLENBRTdFIn0=
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,2CAA2C,CAAC;AAC1F,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAEhE;;;;;GAKG;AACH,wBAAsB,WAAW,CAC/B,KAAK,EAAE,aAAa,EACpB,GAAG,EAAE,YAAY,GAChB,OAAO,CAAC;IAAE,cAAc,EAAE,MAAM,CAAC;IAAC,aAAa,EAAE,MAAM,CAAA;CAAE,CAAC,CAI5D;AAED,wBAAsB,iBAAiB,CAAC,KAAK,EAAE,wBAAwB,EAAE,GAAG,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC,CAG3G;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,aAAa,GAAG,wBAAwB,GAAG,KAAK,IAAI,aAAa,CAE/G"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAClF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAEhE;;;;;GAKG;AACH,wBAAsB,WAAW,CAC/B,KAAK,EAAE,aAAa,EACpB,GAAG,EAAE,YAAY,EACjB,IAAI,CAAC,EAAE,YAAY,GAClB,OAAO,CAAC;IAAE,cAAc,EAAE,MAAM,CAAC;IAAC,aAAa,EAAE,MAAM,CAAA;CAAE,CAAC,CAI5D;AAED,wBAAsB,iBAAiB,CACrC,KAAK,EAAE,oBAAoB,EAC3B,GAAG,EAAE,YAAY,EACjB,IAAI,CAAC,EAAE,YAAY,GAClB,OAAO,CAAC,MAAM,CAAC,CAGjB;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,YAAY,GAAG,KAAK,IAAI,aAAa,CAEnF;AAED,wBAAgB,aAAa,CAAC,QAAQ,EAAE,YAAY,GAAG,QAAQ,IAAI,WAAW,CAE7E"}
package/dest/utils.js CHANGED
@@ -3,18 +3,27 @@
3
3
  * @param token - Token contract.
4
4
  * @param who - Address to get the balance for.
5
5
  * @returns - Private and public token balances as bigints.
6
- */ export async function getBalances(token, who) {
7
- const privateBalance = await token.methods.balance_of_private(who).simulate();
8
- const publicBalance = await token.methods.balance_of_public(who).simulate();
6
+ */ export async function getBalances(token, who, from) {
7
+ const { result: privateBalance } = await token.methods.balance_of_private(who).simulate({
8
+ from: from ?? who
9
+ });
10
+ const { result: publicBalance } = await token.methods.balance_of_public(who).simulate({
11
+ from: from ?? who
12
+ });
9
13
  return {
10
14
  privateBalance,
11
15
  publicBalance
12
16
  };
13
17
  }
14
- export async function getPrivateBalance(token, who) {
15
- const privateBalance = await token.methods.get_balance(who).simulate();
18
+ export async function getPrivateBalance(token, who, from) {
19
+ const { result: privateBalance } = await token.methods.get_balance(who).simulate({
20
+ from: from ?? who
21
+ });
16
22
  return privateBalance;
17
23
  }
18
24
  export function isStandardTokenContract(token) {
19
25
  return 'mint_to_public' in token.methods;
20
26
  }
27
+ export function isAMMContract(contract) {
28
+ return 'add_liquidity' in contract.methods;
29
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/bot",
3
- "version": "0.0.0-test.1",
3
+ "version": "0.0.1-commit.001888fc",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./dest/index.js",
@@ -10,11 +10,9 @@
10
10
  "../package.common.json"
11
11
  ],
12
12
  "scripts": {
13
- "build": "yarn clean && tsc -b",
14
- "build:dev": "tsc -b --watch",
13
+ "build": "yarn clean && ../scripts/tsc.sh",
14
+ "build:dev": "../scripts/tsc.sh --watch",
15
15
  "clean": "rm -rf ./dest .tsbuildinfo",
16
- "formatting": "run -T prettier --check ./src && run -T eslint ./src",
17
- "formatting:fix": "run -T eslint --fix ./src && run -T prettier -w ./src",
18
16
  "bb": "node --no-warnings ./dest/bb/index.js",
19
17
  "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}"
20
18
  },
@@ -49,33 +47,42 @@
49
47
  "testTimeout": 120000,
50
48
  "setupFiles": [
51
49
  "../../foundation/src/jest/setup.mjs"
50
+ ],
51
+ "testEnvironment": "../../foundation/src/jest/env.mjs",
52
+ "setupFilesAfterEnv": [
53
+ "../../foundation/src/jest/setupAfterEnv.mjs"
52
54
  ]
53
55
  },
54
56
  "dependencies": {
55
- "@aztec/accounts": "0.0.0-test.1",
56
- "@aztec/aztec.js": "0.0.0-test.1",
57
- "@aztec/entrypoints": "0.0.0-test.1",
58
- "@aztec/ethereum": "0.0.0-test.1",
59
- "@aztec/foundation": "0.0.0-test.1",
60
- "@aztec/noir-contracts.js": "0.0.0-test.1",
61
- "@aztec/noir-protocol-circuits-types": "0.0.0-test.1",
62
- "@aztec/protocol-contracts": "0.0.0-test.1",
63
- "@aztec/stdlib": "0.0.0-test.1",
64
- "@aztec/telemetry-client": "0.0.0-test.1",
57
+ "@aztec/accounts": "0.0.1-commit.001888fc",
58
+ "@aztec/aztec.js": "0.0.1-commit.001888fc",
59
+ "@aztec/entrypoints": "0.0.1-commit.001888fc",
60
+ "@aztec/ethereum": "0.0.1-commit.001888fc",
61
+ "@aztec/foundation": "0.0.1-commit.001888fc",
62
+ "@aztec/kv-store": "0.0.1-commit.001888fc",
63
+ "@aztec/l1-artifacts": "0.0.1-commit.001888fc",
64
+ "@aztec/noir-contracts.js": "0.0.1-commit.001888fc",
65
+ "@aztec/noir-protocol-circuits-types": "0.0.1-commit.001888fc",
66
+ "@aztec/noir-test-contracts.js": "0.0.1-commit.001888fc",
67
+ "@aztec/protocol-contracts": "0.0.1-commit.001888fc",
68
+ "@aztec/stdlib": "0.0.1-commit.001888fc",
69
+ "@aztec/telemetry-client": "0.0.1-commit.001888fc",
70
+ "@aztec/wallets": "0.0.1-commit.001888fc",
65
71
  "source-map-support": "^0.5.21",
66
72
  "tslib": "^2.4.0",
73
+ "viem": "npm:@aztec/viem@2.38.2",
67
74
  "zod": "^3.23.8"
68
75
  },
69
76
  "devDependencies": {
70
- "@jest/globals": "^29.5.0",
71
- "@types/jest": "^29.5.0",
72
- "@types/memdown": "^3.0.0",
73
- "@types/node": "^18.7.23",
77
+ "@jest/globals": "^30.0.0",
78
+ "@types/jest": "^30.0.0",
79
+ "@types/node": "^22.15.17",
74
80
  "@types/source-map-support": "^0.5.10",
75
- "jest": "^29.5.0",
76
- "jest-mock-extended": "^3.0.3",
81
+ "@typescript/native-preview": "7.0.0-dev.20260113.1",
82
+ "jest": "^30.0.0",
83
+ "jest-mock-extended": "^4.0.0",
77
84
  "ts-node": "^10.9.1",
78
- "typescript": "^5.0.4"
85
+ "typescript": "^5.3.3"
79
86
  },
80
87
  "files": [
81
88
  "dest",
@@ -84,6 +91,6 @@
84
91
  ],
85
92
  "types": "./dest/index.d.ts",
86
93
  "engines": {
87
- "node": ">=18"
94
+ "node": ">=20.10"
88
95
  }
89
96
  }
package/src/amm_bot.ts ADDED
@@ -0,0 +1,129 @@
1
+ import { AztecAddress } from '@aztec/aztec.js/addresses';
2
+ import { NO_WAIT } from '@aztec/aztec.js/contracts';
3
+ import { Fr } from '@aztec/aztec.js/fields';
4
+ import { TxHash, TxReceipt } from '@aztec/aztec.js/tx';
5
+ import { jsonStringify } from '@aztec/foundation/json-rpc';
6
+ import type { AMMContract } from '@aztec/noir-contracts.js/AMM';
7
+ import type { TokenContract } from '@aztec/noir-contracts.js/Token';
8
+ import type { AztecNode, AztecNodeAdmin } from '@aztec/stdlib/interfaces/client';
9
+ import type { EmbeddedWallet } from '@aztec/wallets/embedded';
10
+
11
+ import { BaseBot } from './base_bot.js';
12
+ import type { BotConfig } from './config.js';
13
+ import { BotFactory } from './factory.js';
14
+ import type { BotStore } from './store/index.js';
15
+
16
+ const TRANSFER_BASE_AMOUNT = 1_000;
17
+ const TRANSFER_VARIANCE = 200;
18
+
19
+ type Balances = { token0: bigint; token1: bigint };
20
+
21
+ export class AmmBot extends BaseBot {
22
+ protected constructor(
23
+ node: AztecNode,
24
+ wallet: EmbeddedWallet,
25
+ defaultAccountAddress: AztecAddress,
26
+ public readonly amm: AMMContract,
27
+ public readonly token0: TokenContract,
28
+ public readonly token1: TokenContract,
29
+ config: BotConfig,
30
+ ) {
31
+ super(node, wallet, defaultAccountAddress, config);
32
+ }
33
+
34
+ static async create(
35
+ config: BotConfig,
36
+ wallet: EmbeddedWallet,
37
+ aztecNode: AztecNode,
38
+ aztecNodeAdmin: AztecNodeAdmin | undefined,
39
+ store: BotStore,
40
+ ): Promise<AmmBot> {
41
+ const { defaultAccountAddress, token0, token1, amm } = await new BotFactory(
42
+ config,
43
+ wallet,
44
+ store,
45
+ aztecNode,
46
+ aztecNodeAdmin,
47
+ ).setupAmm();
48
+ return new AmmBot(aztecNode, wallet, defaultAccountAddress, amm, token0, token1, config);
49
+ }
50
+
51
+ protected async createAndSendTx(logCtx: object): Promise<TxHash> {
52
+ const { feePaymentMethod } = this.config;
53
+ const { wallet, amm, token0, token1 } = this;
54
+
55
+ const balances = this.getBalances();
56
+ this.log.info(`Preparing tx with ${feePaymentMethod} fee to swap tokens. Balances: ${jsonStringify(balances)}`, {
57
+ ...logCtx,
58
+ balances,
59
+ });
60
+
61
+ // 1000 ± 200
62
+ const amountIn = Math.floor(TRANSFER_BASE_AMOUNT + (Math.random() - 0.5) * TRANSFER_VARIANCE);
63
+ const authwitNonce = Fr.random();
64
+
65
+ const [tokenIn, tokenOut] = Math.random() < 0.5 ? [token0, token1] : [token1, token0];
66
+
67
+ const swapAuthwit = await wallet.createAuthWit(this.defaultAccountAddress, {
68
+ caller: amm.address,
69
+ call: await tokenIn.methods
70
+ .transfer_to_public(this.defaultAccountAddress, amm.address, amountIn, authwitNonce)
71
+ .getFunctionCall(),
72
+ });
73
+
74
+ const { result: tokenInBalance } = await tokenIn.methods
75
+ .balance_of_public(amm.address)
76
+ .simulate({ from: this.defaultAccountAddress });
77
+ const { result: tokenOutBalance } = await tokenOut.methods
78
+ .balance_of_public(amm.address)
79
+ .simulate({ from: this.defaultAccountAddress });
80
+ const { result: amountOutMin } = await amm.methods
81
+ .get_amount_out_for_exact_in(tokenInBalance, tokenOutBalance, amountIn)
82
+ .simulate({ from: this.defaultAccountAddress });
83
+
84
+ const swapExactTokensInteraction = amm.methods
85
+ .swap_exact_tokens_for_tokens(tokenIn.address, tokenOut.address, amountIn, amountOutMin, authwitNonce)
86
+ .with({
87
+ authWitnesses: [swapAuthwit],
88
+ });
89
+
90
+ const opts = await this.getSendMethodOpts(swapExactTokensInteraction);
91
+
92
+ this.log.verbose(`Sending transaction`, logCtx);
93
+ this.log.info(`Tx. Balances: ${jsonStringify(balances)}`, { ...logCtx, balances });
94
+ const { txHash } = await swapExactTokensInteraction.send({ ...opts, wait: NO_WAIT });
95
+ return txHash;
96
+ }
97
+
98
+ protected override async onTxMined(receipt: TxReceipt, logCtx: object): Promise<void> {
99
+ const balances = await this.getBalances();
100
+ this.log.info(`Balances after swap in tx ${receipt.txHash}: ${jsonStringify(balances)}`, { ...logCtx, balances });
101
+ }
102
+
103
+ public getAmmBalances(): Promise<Balances> {
104
+ return this.getPublicBalanceFor(this.amm.address);
105
+ }
106
+
107
+ public async getBalances(): Promise<{ senderPublic: Balances; senderPrivate: Balances; amm: Balances }> {
108
+ return {
109
+ senderPublic: await this.getPublicBalanceFor(this.defaultAccountAddress),
110
+ senderPrivate: await this.getPrivateBalanceFor(this.defaultAccountAddress),
111
+ amm: await this.getPublicBalanceFor(this.amm.address, this.defaultAccountAddress),
112
+ };
113
+ }
114
+
115
+ private async getPublicBalanceFor(address: AztecAddress, from?: AztecAddress): Promise<Balances> {
116
+ const { result: token0 } = await this.token0.methods.balance_of_public(address).simulate({ from: from ?? address });
117
+ const { result: token1 } = await this.token1.methods.balance_of_public(address).simulate({ from: from ?? address });
118
+ return { token0, token1 };
119
+ }
120
+ private async getPrivateBalanceFor(address: AztecAddress, from?: AztecAddress): Promise<Balances> {
121
+ const { result: token0 } = await this.token0.methods
122
+ .balance_of_private(address)
123
+ .simulate({ from: from ?? address });
124
+ const { result: token1 } = await this.token1.methods
125
+ .balance_of_private(address)
126
+ .simulate({ from: from ?? address });
127
+ return { token0, token1 };
128
+ }
129
+ }
@@ -0,0 +1,82 @@
1
+ import { AztecAddress } from '@aztec/aztec.js/addresses';
2
+ import { BatchCall, ContractFunctionInteraction, type SendInteractionOptions } from '@aztec/aztec.js/contracts';
3
+ import { createLogger } from '@aztec/aztec.js/log';
4
+ import { waitForTx } from '@aztec/aztec.js/node';
5
+ import { TxHash, TxReceipt, TxStatus } from '@aztec/aztec.js/tx';
6
+ import { Gas } from '@aztec/stdlib/gas';
7
+ import type { AztecNode } from '@aztec/stdlib/interfaces/client';
8
+ import type { EmbeddedWallet } from '@aztec/wallets/embedded';
9
+
10
+ import type { BotConfig } from './config.js';
11
+
12
+ export abstract class BaseBot {
13
+ protected log = createLogger('bot');
14
+
15
+ protected attempts: number = 0;
16
+ protected successes: number = 0;
17
+
18
+ protected constructor(
19
+ public readonly node: AztecNode,
20
+ public readonly wallet: EmbeddedWallet,
21
+ public readonly defaultAccountAddress: AztecAddress,
22
+ public config: BotConfig,
23
+ ) {}
24
+
25
+ public async run(): Promise<TxReceipt | TxHash> {
26
+ this.attempts++;
27
+ const { followChain, txMinedWaitSeconds } = this.config;
28
+ const logCtx = { runId: Date.now() * 1000 + Math.floor(Math.random() * 1000), followChain, txMinedWaitSeconds };
29
+
30
+ this.log.verbose(`Creating tx`, logCtx);
31
+ const txHash = await this.createAndSendTx(logCtx);
32
+
33
+ if (followChain === 'NONE') {
34
+ this.log.info(`Transaction ${txHash.toString()} sent, not waiting for it to be mined`);
35
+ return txHash;
36
+ }
37
+
38
+ const waitForStatus = TxStatus[followChain];
39
+ this.log.verbose(`Awaiting tx ${txHash.toString()} to be on the ${followChain} chain`, logCtx);
40
+ const receipt = await waitForTx(this.node, txHash, { timeout: txMinedWaitSeconds, waitForStatus });
41
+ this.successes++;
42
+ this.log.info(
43
+ `Tx #${this.attempts} ${receipt.txHash} successfully mined in block ${receipt.blockNumber} (stats: ${this.successes}/${this.attempts} success)`,
44
+ logCtx,
45
+ );
46
+
47
+ await this.onTxMined(receipt, logCtx);
48
+
49
+ return receipt;
50
+ }
51
+
52
+ protected abstract createAndSendTx(logCtx: object): Promise<TxHash>;
53
+
54
+ protected onTxMined(_receipt: TxReceipt, _logCtx: object): Promise<void> {
55
+ // no-op
56
+ return Promise.resolve();
57
+ }
58
+
59
+ protected async getSendMethodOpts(
60
+ interaction: ContractFunctionInteraction | BatchCall,
61
+ ): Promise<SendInteractionOptions> {
62
+ const { l2GasLimit, daGasLimit, minFeePadding } = this.config;
63
+
64
+ this.wallet.setMinFeePadding(minFeePadding);
65
+
66
+ let gasSettings;
67
+ if (l2GasLimit !== undefined && l2GasLimit > 0 && daGasLimit !== undefined && daGasLimit > 0) {
68
+ gasSettings = { gasLimits: Gas.from({ l2Gas: l2GasLimit, daGas: daGasLimit }) };
69
+ this.log.verbose(`Using gas limits ${l2GasLimit} L2 gas ${daGasLimit} DA gas`);
70
+ } else {
71
+ this.log.verbose(`Estimating gas for transaction`);
72
+ ({ estimatedGas: gasSettings } = await interaction.simulate({
73
+ fee: { estimateGas: true },
74
+ from: this.defaultAccountAddress,
75
+ }));
76
+ }
77
+ return {
78
+ from: this.defaultAccountAddress,
79
+ fee: { gasSettings },
80
+ };
81
+ }
82
+ }