-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
357 lines (324 loc) · 12 KB
/
cli.ts
File metadata and controls
357 lines (324 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/usr/bin/env node
import { Command, Option } from 'commander';
import fs from 'fs/promises';
import path from 'path';
import prettier from 'prettier';
import { ethers } from 'ethers';
import {
generateChainUpdateTransaction,
createChainUpdateJSON,
} from './generators/chainUpdateCalldata';
import logger from './utils/logger';
import {
generateTokenAndPoolDeployment,
createTokenDeploymentJSON,
} from './generators/tokenDeployment';
import {
generatePoolDeploymentTransaction,
createPoolDeploymentJSON,
} from './generators/poolDeployment';
import { TokenDeploymentParams } from './types/tokenDeployment';
import { PoolDeploymentParams } from './types/poolDeployment';
import { SafeMetadata } from './types/safe';
import { SafeChainUpdateMetadata } from './types/chainUpdate';
/**
* Base options interface for all commands
*/
interface BaseOptions {
input: string;
output?: string;
format?: 'calldata' | 'safe-json';
safe?: string;
owner?: string;
chainId?: string;
}
/**
* Options for chain update command
*/
interface ChainUpdateOptions extends BaseOptions {
tokenPool?: string;
}
/**
* Base options for deployment commands
*/
interface BaseDeploymentOptions extends BaseOptions {
deployer: string; // TokenPoolFactory contract address
salt: string;
safe: string;
}
/**
* Options for token deployment command
*/
interface TokenDeploymentOptions extends BaseDeploymentOptions {}
/**
* Options for pool deployment command
*/
interface PoolDeploymentOptions extends BaseDeploymentOptions {}
function createProgram(): Command {
return new Command()
.name('token-pools-calldata')
.description('Generate calldata for TokenPool contract interactions')
.version('1.0.0');
}
// Function to format JSON consistently using project's prettier config
async function formatJSON(obj: unknown): Promise<string> {
const config = await prettier.resolveConfig(process.cwd());
return prettier.format(JSON.stringify(obj), {
...config,
parser: 'json',
});
}
async function handleChainUpdate(options: ChainUpdateOptions): Promise<void> {
try {
// Validate Ethereum addresses if provided
if (options.safe && !ethers.isAddress(options.safe)) {
throw new Error(`Invalid Safe address: ${String(options.safe)}`);
}
if (options.owner && !ethers.isAddress(options.owner)) {
throw new Error(`Invalid owner address: ${String(options.owner)}`);
}
if (options.tokenPool && !ethers.isAddress(options.tokenPool)) {
throw new Error(`Invalid Token Pool address: ${String(options.tokenPool)}`);
}
const inputPath = path.resolve(options.input);
const inputJson = await fs.readFile(inputPath, 'utf-8');
const transaction = await generateChainUpdateTransaction(inputJson);
if (options.format === 'safe-json') {
if (!options.chainId || !options.safe || !options.owner) {
throw new Error(
'chainId, safe, and owner are required for Safe Transaction Builder JSON format',
);
}
const metadata: SafeChainUpdateMetadata = {
chainId: options.chainId,
safeAddress: options.safe,
ownerAddress: options.owner,
tokenPoolAddress: options.tokenPool || '0xYOUR_POOL_ADDRESS',
};
const safeJson = createChainUpdateJSON(transaction, metadata);
const formattedJson = await formatJSON(safeJson);
if (options.output) {
const outputPath = path.resolve(options.output);
await fs.writeFile(outputPath, formattedJson);
logger.info('Successfully wrote Safe Transaction Builder JSON to file', { outputPath });
} else {
console.log(formattedJson);
}
} else {
// Default format: just output the transaction data
if (options.output) {
const outputPath = path.resolve(options.output);
await fs.writeFile(outputPath, transaction.data + '\n');
logger.info('Successfully wrote transaction data to file', { outputPath });
} else {
console.log(transaction.data);
}
}
} catch (error) {
if (error instanceof Error) {
logger.error('Failed to generate chain update transaction', {
error: error.message,
stack: error.stack,
});
} else {
logger.error('Failed to generate chain update transaction', {
error: 'Unknown error',
});
}
process.exit(1);
}
}
async function handleTokenDeployment(options: TokenDeploymentOptions): Promise<void> {
try {
// Validate Ethereum addresses if provided
if (options.safe && !ethers.isAddress(options.safe)) {
throw new Error(`Invalid Safe address: ${String(options.safe)}`);
}
if (options.owner && !ethers.isAddress(options.owner)) {
throw new Error(`Invalid owner address: ${String(options.owner)}`);
}
if (!ethers.isAddress(options.deployer)) {
throw new Error(`Invalid deployer address: ${String(options.deployer)}`);
}
if (!options.salt) {
throw new Error('Salt is required');
}
if (ethers.dataLength(options.salt) !== 32) {
throw new Error('Salt must be a 32-byte hex string');
}
const inputPath = path.resolve(options.input);
const inputJson = await fs.readFile(inputPath, 'utf-8');
const transaction = await generateTokenAndPoolDeployment(
inputJson,
options.deployer,
options.salt,
options.safe,
);
// Parse input JSON for Safe JSON format
const parsedInput = JSON.parse(inputJson) as TokenDeploymentParams;
if (options.format === 'safe-json') {
if (!options.chainId || !options.safe || !options.owner) {
throw new Error(
'chainId, safe, and owner are required for Safe Transaction Builder JSON format',
);
}
const metadata: SafeMetadata = {
chainId: options.chainId,
safeAddress: options.safe,
ownerAddress: options.owner,
};
const safeJson = createTokenDeploymentJSON(transaction, parsedInput, metadata);
const formattedJson = await formatJSON(safeJson);
if (options.output) {
const outputPath = path.resolve(options.output);
await fs.writeFile(outputPath, formattedJson);
logger.info('Successfully wrote Safe Transaction Builder JSON to file', { outputPath });
} else {
console.log(formattedJson);
}
} else {
// Default format: just output the transaction data
if (options.output) {
const outputPath = path.resolve(options.output);
await fs.writeFile(outputPath, transaction.data + '\n');
logger.info('Successfully wrote transaction data to file', { outputPath });
} else {
console.log(transaction.data);
}
}
} catch (error) {
if (error instanceof Error) {
logger.error('Failed to generate token deployment', {
error: error.message,
stack: error.stack,
});
} else {
logger.error('Failed to generate token deployment', { error: 'Unknown error' });
}
process.exit(1);
}
}
async function handlePoolDeployment(options: PoolDeploymentOptions): Promise<void> {
try {
// Validate Ethereum addresses if provided
if (options.safe && !ethers.isAddress(options.safe)) {
throw new Error(`Invalid Safe address: ${String(options.safe)}`);
}
if (options.owner && !ethers.isAddress(options.owner)) {
throw new Error(`Invalid owner address: ${String(options.owner)}`);
}
if (!ethers.isAddress(options.deployer)) {
throw new Error(`Invalid deployer address: ${String(options.deployer)}`);
}
if (!options.salt) {
throw new Error('Salt is required');
}
if (ethers.dataLength(options.salt) !== 32) {
throw new Error('Salt must be a 32-byte hex string');
}
const inputPath = path.resolve(options.input);
const inputJson = await fs.readFile(inputPath, 'utf-8');
const transaction = await generatePoolDeploymentTransaction(
inputJson,
options.deployer,
options.salt,
);
// Parse input JSON for Safe JSON format
const parsedInput = JSON.parse(inputJson) as PoolDeploymentParams;
if (options.format === 'safe-json') {
if (!options.chainId || !options.safe || !options.owner) {
throw new Error(
'chainId, safe, and owner are required for Safe Transaction Builder JSON format',
);
}
const metadata: SafeMetadata = {
chainId: options.chainId,
safeAddress: options.safe,
ownerAddress: options.owner,
};
const safeJson = createPoolDeploymentJSON(transaction, parsedInput, metadata);
const formattedJson = await formatJSON(safeJson);
if (options.output) {
const outputPath = path.resolve(options.output);
await fs.writeFile(outputPath, formattedJson);
logger.info('Successfully wrote Safe Transaction Builder JSON to file', { outputPath });
} else {
console.log(formattedJson);
}
} else {
// Default format: just output the transaction data
if (options.output) {
const outputPath = path.resolve(options.output);
await fs.writeFile(outputPath, transaction.data + '\n');
logger.info('Successfully wrote transaction data to file', { outputPath });
} else {
console.log(transaction.data);
}
}
} catch (error) {
if (error instanceof Error) {
logger.error('Failed to generate pool deployment', {
error: error.message,
stack: error.stack,
});
} else {
logger.error('Failed to generate pool deployment', { error: 'Unknown error' });
}
process.exit(1);
}
}
// Initialize the program
const program = createProgram();
// Add commands
program
.command('generate-chain-update')
.description('Generate calldata for applyChainUpdates function')
.requiredOption('-i, --input <path>', 'Path to input JSON file')
.option('-o, --output <path>', 'Path to output file (defaults to stdout)')
.addOption(
new Option('-f, --format <type>', 'Output format')
.choices(['calldata', 'safe-json'])
.default('calldata'),
)
.option('-s, --safe <address>', 'Safe address (for safe-json format)')
.option('-w, --owner <address>', 'Owner address (for safe-json format)')
.option('-c, --chain-id <id>', 'Chain ID (for safe-json format)')
.option(
'-p, --token-pool <address>',
'Token Pool contract address (optional, defaults to placeholder)',
)
.action(handleChainUpdate);
program
.command('generate-token-deployment')
.description('Generate deployment transaction for BurnMintERC20 token')
.requiredOption('-i, --input <path>', 'Path to input JSON file')
.requiredOption('-d, --deployer <address>', 'TokenPoolFactory contract address')
.requiredOption('--salt <bytes32>', 'Salt for create2')
.option('-o, --output <path>', 'Path to output file (defaults to stdout)')
.addOption(
new Option('-f, --format <type>', 'Output format')
.choices(['calldata', 'safe-json'])
.default('calldata'),
)
.option('-s, --safe <address>', 'Safe address (required for safe-json format)')
.option('-w, --owner <address>', 'Owner address (required for safe-json format)')
.option('-c, --chain-id <id>', 'Chain ID (required for safe-json format)')
.action(handleTokenDeployment as (options: TokenDeploymentOptions) => Promise<void>);
program
.command('generate-pool-deployment')
.description('Generate deployment transaction for TokenPool')
.requiredOption('-i, --input <path>', 'Path to input JSON file')
.requiredOption('-d, --deployer <address>', 'TokenPoolFactory contract address')
.requiredOption('--salt <bytes32>', 'Salt for create2')
.option('-o, --output <path>', 'Path to output file (defaults to stdout)')
.addOption(
new Option('-f, --format <type>', 'Output format')
.choices(['calldata', 'safe-json'])
.default('calldata'),
)
.option('-s, --safe <address>', 'Safe address (required for safe-json format)')
.option('-w, --owner <address>', 'Owner address (required for safe-json format)')
.option('-c, --chain-id <id>', 'Chain ID (required for safe-json format)')
.action(handlePoolDeployment as (options: PoolDeploymentOptions) => Promise<void>);
// Parse command line arguments
void program.parse(process.argv);