-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathindex.ts
More file actions
614 lines (562 loc) · 21.2 KB
/
index.ts
File metadata and controls
614 lines (562 loc) · 21.2 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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
#!/usr/bin/env node
import { Command } from "commander";
import { walletCommand } from "../src/commands/wallet.js";
import { balanceCommand } from "../src/commands/balance.js";
import { transferCommand } from "../src/commands/transfer.js";
import { txCommand } from "../src/commands/tx.js";
import figlet from "figlet";
import chalk from "chalk";
import { deployCommand } from "../src/commands/deploy.js";
import { logError } from "../src/utils/logger.js";
import { verifyCommand } from "../src/commands/verify.js";
import { ReadContract } from "../src/commands/contract.js";
import { Address } from "viem";
import { bridgeCommand } from "../src/commands/bridge.js";
import { batchTransferCommand } from "../src/commands/batchTransfer.js";
import { historyCommand } from "../src/commands/history.js";
import { selectAddress } from "../src/commands/selectAddress.js";
import { resolveCommand } from "../src/commands/resolve.js";
import { configCommand } from "../src/commands/config.js";
import { transactionCommand } from "../src/commands/transaction.js";
import { monitorCommand, listMonitoringSessions, stopMonitoringSession } from "../src/commands/monitor.js";
import { simulateCommand, TransactionSimulationOptions } from "../src/commands/simulate.js";
import { parseEther } from "viem";
import { resolveRNSToAddress } from "../src/utils/rnsHelper.js";
import { validateAndFormatAddressRSK } from "../src/utils/index.js";
import { txExplainCommand } from "../src/commands/txExplain.js";
import { rnsUpdateCommand } from "../src/commands/rnsUpdate.js";
import { rnsTransferCommand } from "../src/commands/rnsTransfer.js";
import { rnsRegisterCommand } from "../src/commands/rnsRegister.js";
interface CommandOptions {
testnet?: boolean;
address?: Address;
contract?: Address;
value?: string;
txid?: string;
abi?: string;
bytecode?: string;
apiKey?: string;
args?: any;
json?: any;
name?: string;
decodedArgs?: any;
wallet?: string;
number?: string;
file?: string;
interactive?: boolean;
token?: Address;
reverse?: boolean;
tx?: string;
confirmations?: number;
balance?: boolean;
transactions?: boolean;
list?: boolean;
stop?: string;
monitor?: boolean;
gasLimit?: string;
gasPrice?: string;
data?: string;
attestDeployment?: boolean;
attestVerification?: boolean;
attestTransfer?: boolean;
attestSchemaUid?: string;
attestRecipient?: string;
attestReason?: string;
rns?: string;
raw?: boolean;
}
const orange = chalk.rgb(255, 165, 0);
console.log(
orange(
figlet.textSync("Rootstock", {
font: "3D-ASCII",
horizontalLayout: "fitted",
verticalLayout: "fitted",
})
)
);
const program = new Command();
program
.name("rsk-cli")
.description("CLI tool for interacting with Rootstock blockchain")
.version("1.4.0", "-v, --version", "Display the current version");
program
.command("wallet")
.description(
"Manage your wallet: create a new one, use an existing wallet, or import a custom wallet"
)
.action(async () => {
await walletCommand();
});
program
.command("balance")
.description("Check the balance of the saved wallet")
.option("-t, --testnet", "Check the balance on the testnet")
.option("--wallet <wallet>", "Name of the wallet")
.option("-a ,--address <address>", "Token holder address")
.option("--rns <domain>", "Token holder RNS domain (e.g., alice.rsk)")
.action(async (options: CommandOptions) => {
let holderAddress = options.address;
if (options.rns) {
const resolvedAddress = await resolveRNSToAddress({
name: options.rns,
testnet: !!options.testnet,
isExternal: false
});
if (!resolvedAddress) {
throw new Error(`Failed to resolve RNS domain: ${options.rns}`);
}
holderAddress = resolvedAddress;
}
await balanceCommand({
testnet: options.testnet,
walletName: options.wallet!,
address: holderAddress,
});
});
program
.command("transfer")
.description("Transfer RBTC or ERC20 tokens to the provided address")
.option("-t, --testnet", "Transfer on the testnet")
.option("--wallet <wallet>", "Name of the wallet")
.option("-a, --address <address>", "Recipient address")
.option("--rns <domain>", "Recipient RNS domain (e.g., alice.rsk)")
.option("--token <address>", "ERC20 token contract address (optional, for token transfers)")
.option("--value <value>", "Amount to transfer")
.option("-i, --interactive", "Execute interactively and input transactions")
.option("--gas-limit <limit>", "Custom gas limit")
.option("--gas-price <price>", "Custom gas price in RBTC")
.option("--data <data>", "Custom transaction data (hex)")
.option("--attest-transfer", "Create attestation for significant transfers")
.option("--attest-schema-uid <uid>", "Custom schema UID for attestation")
.option("--attest-recipient <address>", "Custom recipient for attestation (default: transfer recipient)")
.option("--attest-reason <reason>", "Reason/purpose for the transfer (e.g., 'Grant payment', 'Bounty reward')")
.action(async (options: CommandOptions) => {
try {
if (options.interactive) {
await batchTransferCommand({
testnet: !!options.testnet,
interactive: true,
attestation: {
enabled: !!options.attestTransfer,
schemaUID: options.attestSchemaUid,
recipient: options.attestRecipient,
reason: options.attestReason
}
});
return;
}
if (!options.value) {
throw new Error("Value is required for the transfer.");
}
const value = parseFloat(options.value);
if (isNaN(value) || value <= 0) {
throw new Error("Invalid value specified for transfer.");
}
let address: `0x${string}`;
if (options.rns) {
const resolvedAddress = await resolveRNSToAddress({
name: options.rns,
testnet: !!options.testnet,
isExternal: false
});
if (!resolvedAddress) {
throw new Error(`Failed to resolve RNS domain: ${options.rns}`);
}
const formatted = validateAndFormatAddressRSK(resolvedAddress as string, !!options.testnet);
if (!formatted) {
throw new Error(`Invalid resolved address for domain: ${options.rns}`);
}
address = formatted as `0x${string}`;
} else if (options.address) {
const formatted = validateAndFormatAddressRSK(String(options.address), !!options.testnet);
if (!formatted) {
throw new Error("Invalid recipient address");
}
address = formatted as `0x${string}`;
} else {
address = await selectAddress();
}
const txOptions = {
...(options.gasLimit && { gasLimit: BigInt(options.gasLimit) }),
...(options.gasPrice && { gasPrice: parseEther(options.gasPrice.toString()) }),
...(options.data && { data: options.data as `0x${string}` })
};
await transferCommand(
{
testnet: !!options.testnet,
toAddress: address,
value: value,
name: options.wallet!,
tokenAddress: options.token as `0x${string}` | undefined,
attestation: {
enabled: !!options.attestTransfer,
schemaUID: options.attestSchemaUid,
recipient: options.attestRecipient,
reason: options.attestReason
}
}
);
} catch (error: any) {
logError(false, `Error during transfer: ${error.message || error}`);
}
});
program
.command("tx")
.description("Check the status of a transaction")
.option("-t, --testnet", "Check the transaction status on the testnet")
.requiredOption("-i, --txid <txid>", "Transaction ID")
.option("--monitor", "Keep monitoring the transaction until confirmation")
.option("--confirmations <number>", "Required confirmations for monitoring (default: 12)")
.action(async (options: CommandOptions) => {
const formattedTxId = options.txid!.startsWith("0x")
? options.txid
: `0x${options.txid}`;
await txCommand({
testnet: !!options.testnet,
txid: formattedTxId as `0x${string}`,
isExternal: false,
monitor: !!options.monitor,
confirmations: options.confirmations ? parseInt(options.confirmations.toString()) : undefined,
});
});
program
.command("deploy")
.description("Deploy a contract")
.requiredOption("--abi <path>", "Path to the ABI file")
.requiredOption("--bytecode <path>", "Path to the bytecode file")
.option("--wallet <wallet>", "Name of the wallet")
.option("--args <args...>", "Constructor arguments (space-separated)")
.option("-t, --testnet", "Deploy on the testnet")
.option("--attest-deployment", "Create attestation for deployment")
.option("--attest-schema-uid <uid>", "Custom schema UID for attestation")
.option("--attest-recipient <address>", "Custom recipient for attestation (default: contract address)")
.action(async (options: CommandOptions) => {
const args = options.args || [];
await deployCommand(
{
abiPath: options.abi!,
bytecodePath: options.bytecode!,
testnet: options.testnet,
args: args,
name: options.wallet!,
attestation: {
enabled: !!options.attestDeployment,
schemaUID: options.attestSchemaUid,
recipient: options.attestRecipient
}
}
);
});
program
.command("verify")
.description("Verify a contract")
.requiredOption("--json <path>", "Path to the JSON Standard Input")
.requiredOption("--name <name>", "Name of the contract")
.requiredOption("-a, --address <address>", "Address of the deployed contract")
.option("-t, --testnet", "Deploy on the testnet")
.option(
"--decodedArgs <args...>",
"Decoded Constructor arguments (space-separated)"
)
.option("--attest-verification", "Create attestation for contract verification")
.option("--attest-schema-uid <uid>", "Custom schema UID for attestation")
.option("--attest-recipient <address>", "Custom recipient for attestation (default: contract address)")
.action(async (options: CommandOptions) => {
const args = options.decodedArgs || [];
await verifyCommand(
{
jsonPath: options.json!,
address: options.address!,
name: options.name!,
testnet: options.testnet === undefined ? undefined : !!options.testnet,
args: args,
attestation: {
enabled: !!options.attestVerification,
schemaUID: options.attestSchemaUid,
recipient: options.attestRecipient
}
}
);
});
program
.command("contract")
.description("Interact with a contract")
.requiredOption("-a, --address <address>", "Address of a verified contract")
.option("-t, --testnet", "Deploy on the testnet")
.action(async (options: CommandOptions) => {
await ReadContract({
address: options.address! as `0x${string}`,
testnet: !!options.testnet,
});
});
program
.command("bridge")
.description("Interact with RSK bridge")
.option("-t, --testnet", "Deploy on the testnet")
.option("--wallet <wallet>", "Name of the wallet")
.action(async (options: CommandOptions) => {
await bridgeCommand({
testnet: options.testnet === undefined ? undefined : !!options.testnet,
name: options.wallet!,
});
});
program
.command("history")
.description("Fetch history for current wallet")
.option("--apiKey <apiKey", "Alchemy API key")
.option("--number <number>", "Number of transactions to fetch")
.option("-t, --testnet", "History of wallet on the testnet")
.action(async (options: CommandOptions) => {
await historyCommand({
testnet: !!options.testnet,
apiKey: options.apiKey!,
number: options.number!,
});
});
program
.command("batch-transfer")
.description("Execute batch transactions interactively or from stdin")
.option("-i, --interactive", "Execute interactively and input transactions")
.option("-t, --testnet", "Execute on the testnet")
.option("-f, --file <path>", "Execute transactions from a file")
.option("--rns", "Enable RNS domain resolution for recipient addresses")
.action(async (options) => {
try {
const interactive = !!options.interactive;
const testnet = !!options.testnet;
const file = options.file;
const resolveRNS = !!options.rns;
if (interactive && file) {
logError(false, "Cannot use both interactive mode and file input simultaneously.");
return;
}
await batchTransferCommand({
filePath: file,
testnet: testnet,
interactive: interactive,
resolveRNS: resolveRNS,
});
} catch (error: any) {
logError(false, `Error during batch transfer: ${error.message || "Unknown error"}`);
}
});
program
.command("config")
.description("Manage CLI configuration settings")
.action(async () => {
await configCommand();
});
program
.command("transaction")
.description("Create and send transactions (simple, advanced, or raw)")
.option("-t, --testnet", "Execute on the testnet")
.option("--wallet <wallet>", "Name of the wallet")
.option("-a, --address <address>", "Recipient address")
.option("--token <address>", "ERC20 token contract address (optional, for token transfers)")
.option("--value <value>", "Amount to transfer")
.option("--gas-limit <limit>", "Custom gas limit")
.option("--gas-price <price>", "Custom gas price in RBTC")
.option("--data <data>", "Custom transaction data (hex)")
.action(async (options: CommandOptions) => {
try {
await transactionCommand(
options.testnet,
options.address as `0x${string}` | undefined,
options.value ? parseFloat(options.value) : undefined,
options.wallet,
options.token as `0x${string}` | undefined,
{
...(options.gasLimit && { gasLimit: BigInt(options.gasLimit) }),
...(options.gasPrice && { gasPrice: parseEther(options.gasPrice.toString()) }),
...(options.data && { data: options.data as `0x${string}` })
}
);
} catch (error: any) {
logError(false, `Error during transaction: ${error.message || error}`);
}
});
program
.command("monitor")
.description("Monitor addresses or transactions with real-time updates")
.option("-t, --testnet", "Monitor on the testnet")
.option("-a, --address <address>", "Address to monitor")
.option("--tx <txid>", "Transaction ID to monitor")
.option("--confirmations <number>", "Required confirmations for transaction monitoring (default: 12)")
.option("--balance", "Monitor address balance changes")
.option("--transactions", "Monitor address transaction history")
.option("--list", "List active monitoring sessions")
.option("--stop <sessionId>", "Stop a specific monitoring session")
.action(async (options: CommandOptions) => {
try {
if (options.list) {
await listMonitoringSessions(!!options.testnet);
return;
}
if (options.stop) {
await stopMonitoringSession(options.stop, !!options.testnet);
return;
}
const address = options.address
? (`0x${options.address.replace(/^0x/, "")}` as `0x${string}`)
: undefined;
const tx = options.tx
? (options.tx.startsWith("0x") ? options.tx : `0x${options.tx}`) as `0x${string}`
: undefined;
await monitorCommand({
testnet: !!options.testnet,
address: address as Address | undefined,
monitorBalance: options.balance !== false,
monitorTransactions: !!options.transactions,
tx,
confirmations: options.confirmations ? parseInt(options.confirmations.toString()) : undefined,
isExternal: false
});
} catch (error: any) {
logError(false, `Error during monitoring: ${error.message || error}`);
}
});
program
.command("simulate")
.description("Simulate RBTC or ERC20 token transfers without execution")
.option("-t, --testnet", "Simulate on the testnet")
.option("--wallet <wallet>", "Name of the wallet")
.requiredOption("-a, --address <address>", "Recipient address")
.option("--token <address>", "ERC20 token contract address (optional, for token transfers)")
.requiredOption("--value <value>", "Amount to transfer")
.option("--gas-limit <limit>", "Custom gas limit")
.option("--gas-price <price>", "Custom gas price in RBTC")
.option("--data <data>", "Custom transaction data (hex)")
.action(async (options: CommandOptions) => {
try {
if (!options.value) {
throw new Error("Value is required for the simulation.");
}
const value = parseFloat(options.value);
if (isNaN(value) || value <= 0) {
throw new Error("Invalid value specified for simulation.");
}
const address = options.address
? (`0x${options.address.replace(/^0x/, "")}` as `0x${string}`)
: null;
if (!address) {
throw new Error("Recipient address is required for simulation.");
}
const simulateOptions: TransactionSimulationOptions = {
testnet: !!options.testnet,
toAddress: address,
value: value,
name: options.wallet,
tokenAddress: options.token as `0x${string}` | undefined,
...(options.gasLimit && { gasLimit: BigInt(options.gasLimit) }),
...(options.gasPrice && { gasPrice: parseEther(options.gasPrice.toString()) }),
...(options.data && { data: options.data as `0x${string}` })
};
await simulateCommand(simulateOptions);
} catch (error: any) {
console.error(
chalk.red("Error during simulation:"),
error.message || error
);
}
});
program
.command("tx-explain <txhash>")
.description("Transform raw hexadecimal blockchain data into a human-readable summary")
.option("-t, --testnet", "Query the transaction on the Rootstock testnet")
.option("--raw", "Display raw calldata without decoding attempt")
.action(async (txhash: string, options: CommandOptions) => {
try {
const formattedTxHash = txhash.startsWith("0x") ? txhash : `0x${txhash}`;
const isValidHash = /^0x[0-9a-fA-F]{64}$/.test(formattedTxHash);
if (!isValidHash) {
throw new Error("Invalid transaction hash format. It must be a valid 32-byte hex string (64 characters long).");
}
await txExplainCommand({
testnet: !!options.testnet,
txhash: formattedTxHash as `0x${string}`,
raw: !!options.raw
});
} catch (error: any) {
console.error(
chalk.red("Error explaining transaction:"),
error.message || error
);
}
});
program
.command("rns")
.description("RNS Manager: Register, Transfer, Update, or Resolve domains")
.option("--register <domain>", "Register a new RNS domain")
.option("--transfer <domain>", "Transfer ownership of a domain")
.option("--update <domain>", "Update resolver records for a domain")
.option("--resolve <name>", "Resolve a name to address (or address to name)")
.option("-t, --testnet", "Use testnet network")
.option("-w, --wallet <wallet>", "Wallet name or private key to use")
.option("--recipient <address>", "Recipient address (required for --transfer)")
.option("--address <address>", "New address to set (required for --update)")
.option("-r, --reverse", "Perform reverse lookup (required for --resolve)")
.action(async (options: any) => {
const actions = [
options.register ? "register" : null,
options.transfer ? "transfer" : null,
options.update ? "update" : null,
options.resolve ? "resolve" : null,
].filter(Boolean);
if (actions.length === 0) {
console.error(chalk.red("❌ Error: You must specify an action."));
console.log("Try: --register, --transfer, --update, or --resolve");
process.exit(1);
}
if (actions.length > 1) {
console.error(chalk.red("❌ Error: Please specify only one action at a time."));
process.exit(1);
}
const action = actions[0];
try {
switch (action) {
case "register":
await rnsRegisterCommand({
domain: options.register,
wallet: options.wallet,
testnet: !!options.testnet,
});
break;
case "transfer":
if (!options.recipient) {
console.error(chalk.red("❌ Error: --recipient <address> is required for transfer."));
process.exit(1);
}
await rnsTransferCommand({
domain: options.transfer,
recipient: options.recipient,
wallet: options.wallet,
testnet: !!options.testnet,
});
break;
case "update":
if (!options.address) {
console.error(chalk.red("❌ Error: --address <address> is required for update."));
process.exit(1);
}
await rnsUpdateCommand({
domain: options.update,
address: options.address,
wallet: options.wallet,
testnet: !!options.testnet,
});
break;
case "resolve":
await resolveCommand({
name: options.resolve,
testnet: !!options.testnet,
reverse: !!options.reverse,
});
break;
}
} catch (error: any) {
console.error(chalk.red(`❌ Operation failed: ${error.message || error}`));
process.exit(1);
}
});
program.parse(process.argv);