rocketh 0.10.8 → 0.10.10

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/dist/cli.cjs CHANGED
@@ -1,1492 +1,99 @@
1
- #! /usr/bin/env node
2
- "use strict";
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var ldenv = require('ldenv');
5
+ var index = require('./index-AgLCQD7y.cjs');
6
+ require('node:path');
7
+ require('node:fs');
8
+ require('ethers');
9
+ var commander = require('commander');
10
+ require('module');
11
+ require('viem');
12
+ require('eip-1193-jsonrpc-provider');
13
+ require('named-logs');
14
+ require('named-logs-console');
15
+ require('viem/chains');
16
+ require('prompts');
17
+
18
+ var name = "rocketh";
19
+ var version = "0.10.9";
20
+ var description = "deploy smart contract on ethereum-compatible networks";
21
+ var publishConfig = {
22
+ access: "public"
12
23
  };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
24
+ var type = "module";
25
+ var main = "dist/index.cjs";
26
+ var module$1 = "dist/index.mjs";
27
+ var types = "dist/index.d.ts";
28
+ var bin = {
29
+ rocketh: "dist/cli.cjs"
20
30
  };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
-
30
- // src/cli.ts
31
- var import_ldenv = require("ldenv");
32
-
33
- // src/utils/fs.ts
34
- var import_node_fs = __toESM(require("fs"), 1);
35
- var import_node_path = __toESM(require("path"), 1);
36
- function traverseMultipleDirectory(dirs) {
37
- const filepaths = [];
38
- for (const dir of dirs) {
39
- let filesStats = traverse(dir);
40
- filesStats = filesStats.filter((v) => !v.directory);
41
- for (const filestat of filesStats) {
42
- filepaths.push(import_node_path.default.join(dir, filestat.relativePath));
43
- }
44
- }
45
- return filepaths;
46
- }
47
- var traverse = function(dir, result = [], topDir, filter) {
48
- import_node_fs.default.readdirSync(dir).forEach((name) => {
49
- const fPath = import_node_path.default.resolve(dir, name);
50
- const stats = import_node_fs.default.statSync(fPath);
51
- if (!filter && !name.startsWith(".") || filter && filter(name, stats)) {
52
- const fileStats = {
53
- name,
54
- path: fPath,
55
- relativePath: import_node_path.default.relative(topDir || dir, fPath),
56
- mtimeMs: stats.mtimeMs,
57
- directory: stats.isDirectory()
58
- };
59
- if (fileStats.directory) {
60
- result.push(fileStats);
61
- return traverse(fPath, result, topDir || dir, filter);
62
- }
63
- result.push(fileStats);
64
- }
65
- });
66
- return result;
67
- };
68
-
69
- // src/executor/index.ts
70
- var import_node_path4 = __toESM(require("path"), 1);
71
- var import_node_fs4 = __toESM(require("fs"), 1);
72
-
73
- // src/environment/index.ts
74
- var import_node_fs3 = __toESM(require("fs"), 1);
75
- var import_viem3 = require("viem");
76
- var import_eip_1193_jsonrpc_provider = require("eip-1193-jsonrpc-provider");
77
- var import_node_path3 = __toESM(require("path"), 1);
78
-
79
- // src/utils/json.ts
80
- function bnReplacer(k, v) {
81
- if (typeof v === "bigint") {
82
- return v.toString() + "n";
83
- }
84
- return v;
85
- }
86
- function bnReviver(k, v) {
87
- if (typeof v === "string" && (v.startsWith("-") ? !isNaN(parseInt(v.charAt(1))) : !isNaN(parseInt(v.charAt(0)))) && v.charAt(v.length - 1) === "n") {
88
- return BigInt(v.slice(0, -1));
89
- }
90
- return v;
91
- }
92
- function JSONToString(json, space) {
93
- return JSON.stringify(json, bnReplacer, space);
94
- }
95
- function stringToJSON(str) {
96
- return JSON.parse(str, bnReviver);
97
- }
98
-
99
- // src/environment/deployments.ts
100
- var import_node_path2 = __toESM(require("path"), 1);
101
- var import_node_fs2 = __toESM(require("fs"), 1);
102
- function loadDeployments(deploymentsPath, networkName, onlyABIAndAddress, expectedChain) {
103
- const deploymentsFound = {};
104
- const deployPath = import_node_path2.default.join(deploymentsPath, networkName);
105
- let filesStats;
106
- try {
107
- filesStats = traverse(deployPath, void 0, void 0, (name) => !name.startsWith(".") && name !== "solcInputs");
108
- } catch (e) {
109
- return { deployments: {} };
110
- }
111
- let chainId;
112
- let genesisHash;
113
- if (filesStats.length > 0) {
114
- const chainIdFilepath = import_node_path2.default.join(deployPath, ".chainId");
115
- if (import_node_fs2.default.existsSync(chainIdFilepath)) {
116
- chainId = import_node_fs2.default.readFileSync(chainIdFilepath, "utf-8").trim();
117
- } else {
118
- const chainFilepath = import_node_path2.default.join(deployPath, ".chain");
119
- if (import_node_fs2.default.existsSync(chainFilepath)) {
120
- const chainSTR = import_node_fs2.default.readFileSync(chainFilepath, "utf-8");
121
- const chainData = JSON.parse(chainSTR);
122
- chainId = chainData.chainId;
123
- genesisHash = chainData.genesisHash;
124
- } else {
125
- throw new Error(
126
- `A '.chain' or '.chainId' file is expected to be present in the deployment folder for network ${networkName}`
127
- );
128
- }
129
- }
130
- if (expectedChain) {
131
- if (expectedChain.chainId !== chainId) {
132
- throw new Error(
133
- `Loading deployment in folder '${deployPath}' (with chainId: ${chainId}) for a different chainId (${expectedChain.chainId})`
134
- );
135
- }
136
- if (expectedChain.genesisHash && expectedChain.genesisHash !== genesisHash) {
137
- if (expectedChain.deleteDeploymentsIfDifferentGenesisHash) {
138
- import_node_fs2.default.rmSync(deployPath, { recursive: true, force: true });
139
- return { deployments: {} };
140
- } else {
141
- throw new Error(
142
- `Loading deployment in folder '${deployPath}' (with genesisHash: ${genesisHash}) for a different genesisHash (${expectedChain.genesisHash})`
143
- );
144
- }
145
- }
146
- }
147
- } else {
148
- return { deployments: {} };
149
- }
150
- let fileNames = filesStats.map((a) => a.relativePath);
151
- fileNames = fileNames.sort((a, b) => {
152
- if (a < b) {
153
- return -1;
154
- }
155
- if (a > b) {
156
- return 1;
157
- }
158
- return 0;
159
- });
160
- for (const fileName of fileNames) {
161
- if (fileName.substring(fileName.length - 5) === ".json") {
162
- const deploymentFileName = import_node_path2.default.join(deployPath, fileName);
163
- let deployment = JSON.parse(import_node_fs2.default.readFileSync(deploymentFileName).toString());
164
- if (onlyABIAndAddress) {
165
- deployment = {
166
- address: deployment.address,
167
- abi: deployment.abi,
168
- linkedData: deployment.linkedData
169
- };
170
- }
171
- const name = fileName.slice(0, fileName.length - 5);
172
- deploymentsFound[name] = deployment;
173
- }
174
- }
175
- return { deployments: deploymentsFound, chainId, genesisHash };
176
- }
177
-
178
- // src/internal/logging.ts
179
- var import_named_logs = require("named-logs");
180
- var import_named_logs_console = require("named-logs-console");
181
- (0, import_named_logs_console.hookup)();
182
- function setLogLevel(level) {
183
- import_named_logs_console.factory.level = level;
184
- if (import_named_logs_console.factory.level > 0) {
185
- import_named_logs_console.factory.enable();
186
- } else {
187
- import_named_logs_console.factory.disable();
188
- }
189
- }
190
- var logger = (0, import_named_logs.logs)("rocketh");
191
- var loggerProgressIndicator = {
192
- start(msg) {
193
- if (msg) {
194
- console.log(msg);
195
- }
196
- return this;
197
- },
198
- stop() {
199
- return this;
200
- },
201
- succeed(msg) {
202
- if (msg) {
203
- console.log(msg);
204
- }
205
- return this;
206
- },
207
- fail(msg) {
208
- if (msg) {
209
- console.error(msg);
210
- }
211
- return this;
212
- }
213
- };
214
- var voidProgressIndicator = {
215
- start() {
216
- return this;
217
- },
218
- stop() {
219
- return this;
220
- },
221
- succeed() {
222
- return this;
223
- },
224
- fail() {
225
- return this;
226
- }
227
- };
228
- var lastSpin = loggerProgressIndicator;
229
- function spin(message) {
230
- if (import_named_logs_console.factory.level > 0) {
231
- lastSpin = lastSpin.start(message);
232
- return lastSpin;
233
- } else {
234
- return voidProgressIndicator;
235
- }
236
- }
237
- function log(message) {
238
- if (import_named_logs_console.factory.level > 0) {
239
- console.log(message);
240
- }
241
- }
242
-
243
- // src/environment/utils/chains.ts
244
- var import_chains = __toESM(require("viem/chains"), 1);
245
-
246
- // src/environment/utils/extra-chains/index.ts
247
- var extra_chains_exports = {};
248
- __export(extra_chains_exports, {
249
- ancient8: () => ancient8,
250
- ancient8Sepolia: () => ancient8Sepolia
251
- });
252
-
253
- // src/environment/utils/extra-chains/ancient8.ts
254
- var import_viem = require("viem");
255
- var import_op_stack = require("viem/op-stack");
256
- var sourceId = 1;
257
- var ancient8 = (0, import_viem.defineChain)({
258
- ...import_op_stack.chainConfig,
259
- id: 888888888,
260
- name: "Ancient8",
261
- nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
262
- rpcUrls: {
263
- default: {
264
- http: ["https://rpc.ancient8.gg"]
265
- }
266
- },
267
- blockExplorers: {
268
- default: {
269
- name: "Ancient8 explorer",
270
- url: "https://scan.ancient8.gg",
271
- apiUrl: "https://scan.ancient8.gg/api"
272
- }
273
- },
274
- contracts: {
275
- ...import_op_stack.chainConfig.contracts,
276
- l2OutputOracle: {
277
- [sourceId]: {
278
- address: "0xB09DC08428C8b4EFB4ff9C0827386CDF34277996"
279
- }
280
- },
281
- portal: {
282
- [sourceId]: {
283
- address: "0x639F2AECE398Aa76b07e59eF6abe2cFe32bacb68",
284
- blockCreated: 19070571
285
- }
286
- },
287
- l1StandardBridge: {
288
- [sourceId]: {
289
- address: "0xd5e3eDf5b68135D559D572E26bF863FBC1950033",
290
- blockCreated: 19070571
291
- }
292
- }
293
- },
294
- sourceId
295
- });
296
-
297
- // src/environment/utils/extra-chains/ancient8Sepolia.ts
298
- var import_viem2 = require("viem");
299
- var import_op_stack2 = require("viem/op-stack");
300
- var sourceId2 = 11155111;
301
- var ancient8Sepolia = (0, import_viem2.defineChain)({
302
- ...import_op_stack2.chainConfig,
303
- id: 28122024,
304
- name: "Ancient8 Testnet",
305
- nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
306
- rpcUrls: {
307
- default: {
308
- http: ["https://rpcv2-testnet.ancient8.gg"]
309
- }
310
- },
311
- blockExplorers: {
312
- default: {
313
- name: "Ancient8 Celestia Testnet explorer",
314
- url: "https://scanv2-testnet.ancient8.gg",
315
- apiUrl: "https://scanv2-testnet.ancient8.gg/api"
316
- }
317
- },
318
- contracts: {
319
- ...import_op_stack2.chainConfig.contracts,
320
- l2OutputOracle: {
321
- [sourceId2]: {
322
- address: "0x942fD5017c0F60575930D8574Eaca13BEcD6e1bB"
323
- }
324
- },
325
- portal: {
326
- [sourceId2]: {
327
- address: "0xfa1d9E26A6aCD7b22115D27572c1221B9803c960",
328
- blockCreated: 4972908
329
- }
330
- },
331
- l1StandardBridge: {
332
- [sourceId2]: {
333
- address: "0xF6Bc0146d3c74D48306e79Ae134A260E418C9335",
334
- blockCreated: 4972908
335
- }
336
- }
337
- },
338
- sourceId: sourceId2
339
- });
340
-
341
- // src/environment/utils/chains.ts
342
- var chainTypesByNames = {
343
- base: "op-stack",
344
- baseGoerli: "op-stack",
345
- baseSepolia: "op-stack",
346
- optimism: "op-stack",
347
- optimismGoerli: "op-stack",
348
- optimismSepolia: "op-stack",
349
- pgn: "op-stack",
350
- pgnTestnet: "op-stack",
351
- zora: "op-stack",
352
- zoraSepolia: "op-stack",
353
- zoraTestnet: "op-stack",
354
- ancient8: "op-stack",
355
- ancient8Sepolia: "op-stack",
356
- celoAlfajores: "celo",
357
- celo: "celo",
358
- zkSync: "zksync",
359
- zkSyncTestnet: "zksync",
360
- zkSyncSepoliaTestnet: "zksync"
31
+ var devDependencies = {
32
+ "@types/node": "^20.12.7",
33
+ abitype: "^1.0.2",
34
+ "eip-1193": "^0.5.0",
35
+ "ipfs-gateway-emulator": "4.2.1-ipfs.2",
36
+ pkgroll: "^2.0.2",
37
+ rimraf: "^5.0.5",
38
+ typedoc: "^0.25.13",
39
+ typescript: "^5.4.5"
361
40
  };
362
- var chainTypes = {};
363
- var chainById = {};
364
- var allChains = import_chains.default.default || import_chains.default;
365
- for (const key of Object.keys(allChains)) {
366
- const chain = allChains[key];
367
- const chainId = chain.id.toString();
368
- const specificChainType = chainTypesByNames[key];
369
- if (specificChainType) {
370
- chainTypes[chainId] = specificChainType;
371
- }
372
- chainById[chainId] = chain;
373
- }
374
- var moreChains = extra_chains_exports;
375
- for (const key of Object.keys(moreChains)) {
376
- const chain = moreChains[key];
377
- const chainId = chain.id.toString();
378
- const specificChainType = chainTypesByNames[key];
379
- if (specificChainType) {
380
- chainTypes[chainId] = specificChainType;
381
- }
382
- chainById[chainId] = chain;
383
- }
384
- function getChain(id) {
385
- const chain = chainById[id];
386
- if (!chain) {
387
- return {
388
- id: parseInt(id),
389
- name: "unkwown",
390
- // TODO
391
- nativeCurrency: {
392
- name: "Unknown Currency",
393
- symbol: "UNKNOWN",
394
- decimals: 18
395
- },
396
- rpcUrls: {
397
- default: {
398
- http: []
399
- }
400
- }
401
- };
402
- }
403
- return chain;
404
- }
405
-
406
- // src/environment/utils/artifacts.ts
407
- var import_ethers = require("ethers");
408
- function deepEqual(obj1, obj2) {
409
- function isObject(obj) {
410
- if (typeof obj === "object" && obj != null) {
411
- return true;
412
- } else {
413
- return false;
414
- }
415
- }
416
- if (obj1 === obj2) {
417
- return true;
418
- } else if (isObject(obj1) && isObject(obj2)) {
419
- if (Object.keys(obj1).length !== Object.keys(obj2).length) {
420
- return false;
421
- }
422
- for (var prop in obj1) {
423
- if (!deepEqual(obj1[prop], obj2[prop])) {
424
- return false;
425
- }
426
- }
427
- return true;
428
- }
429
- return false;
430
- }
431
- function mergeDoc(values, mergedDevDocs, field) {
432
- if (values[field]) {
433
- const mergedEventDocs = mergedDevDocs[field] = mergedDevDocs[field] || {};
434
- for (const signature of Object.keys(values[field])) {
435
- if (mergedEventDocs[signature] && !deepEqual(mergedEventDocs[signature], values[field][signature])) {
436
- throw new Error(`Doc ${field} conflict: "${signature}" `);
437
- }
438
- mergedEventDocs[signature] = values[field][signature];
439
- }
440
- }
441
- }
442
- function mergeArtifacts(list) {
443
- const mergedABI = [];
444
- const added = /* @__PURE__ */ new Map();
445
- const mergedDevDocs = { kind: "dev", version: 1, methods: {} };
446
- const mergedUserDocs = { kind: "user", version: 1, methods: {} };
447
- const sigJSMap = /* @__PURE__ */ new Map();
448
- for (let i = 0; i < list.length; i++) {
449
- const listElem = list[i];
450
- for (const element of listElem.artifact.abi) {
451
- if (element.type === "function") {
452
- const selector = import_ethers.FunctionFragment.from(element).selector;
453
- if (sigJSMap.has(selector)) {
454
- const existing = sigJSMap.get(selector);
455
- throw new Error(
456
- `ABI conflict: ${existing.routeName} has function "${existing.functionName}" which conflict with ${listElem.name}'s "${element.name}" (selector: "${selector}") `
457
- );
458
- }
459
- sigJSMap.set(selector, { index: i, routeName: listElem.name, functionName: element.name });
460
- const exists = added.has(element.name);
461
- if (exists) {
462
- } else {
463
- added.set(element.name, element);
464
- mergedABI.push(element);
465
- }
466
- } else if (element.type === "constructor") {
467
- } else if (element.type === "error") {
468
- const exists = added.has(element.name);
469
- if (exists) {
470
- } else {
471
- added.set(element.name, element);
472
- mergedABI.push(element);
473
- }
474
- } else if (element.type === "event") {
475
- const exists = added.has(element.name);
476
- if (exists) {
477
- } else {
478
- added.set(element.name, element);
479
- mergedABI.push(element);
480
- }
481
- } else if (element.type === "fallback") {
482
- } else if (element.type === "receive") {
483
- } else {
484
- }
485
- }
486
- const devdoc = listElem.artifact.devdoc;
487
- if (devdoc) {
488
- mergeDoc(devdoc, mergedDevDocs, "events");
489
- mergeDoc(devdoc, mergedDevDocs, "errors");
490
- mergeDoc(devdoc, mergedDevDocs, "methods");
491
- if (devdoc.author) {
492
- if (mergedDevDocs.author && mergedDevDocs.author != devdoc.author) {
493
- throw new Error(`DevDoc author conflict `);
494
- }
495
- mergedDevDocs.author = devdoc.author;
496
- if (mergedDevDocs.title && mergedDevDocs.title != devdoc.title) {
497
- throw new Error(`DevDoc title conflict `);
498
- }
499
- mergedDevDocs.title = devdoc.title;
500
- }
501
- }
502
- const userdoc = listElem.artifact.userdoc;
503
- if (userdoc) {
504
- mergeDoc(userdoc, mergedUserDocs, "events");
505
- mergeDoc(userdoc, mergedUserDocs, "errors");
506
- mergeDoc(userdoc, mergedUserDocs, "methods");
507
- if (userdoc.notice) {
508
- if (mergedUserDocs.notice && mergedUserDocs.notice != userdoc.notice) {
509
- throw new Error(`UserDoc notice conflict `);
510
- }
511
- mergedUserDocs.notice = userdoc.notice;
512
- }
513
- }
514
- }
515
- return {
516
- mergedABI,
517
- added,
518
- mergedDevDocs,
519
- mergedUserDocs,
520
- sigJSMap
521
- };
522
- }
523
-
524
- // src/environment/providers/BaseProvider.ts
525
- var BaseProvider = class {
526
- constructor(provider) {
527
- this.provider = provider;
528
- }
529
- request(args) {
530
- return this._request(args);
531
- }
41
+ var dependencies = {
42
+ "@types/figlet": "^1.5.8",
43
+ "@types/prompts": "^2.4.9",
44
+ commander: "^12.0.0",
45
+ "eip-1193-jsonrpc-provider": "^0.3.0",
46
+ esbuild: "^0.20.2",
47
+ "esbuild-register": "^3.5.0",
48
+ ethers: "^6.11.1",
49
+ figlet: "^1.7.0",
50
+ ldenv: "^0.3.10",
51
+ "named-logs": "^0.2.4",
52
+ "named-logs-console": "^0.3.1",
53
+ prompts: "^2.4.2",
54
+ viem: "^2.9.16"
532
55
  };
533
-
534
- // src/environment/providers/TransactionHashTracker.ts
535
- var TransactionHashTracker = class extends BaseProvider {
536
- constructor(provider) {
537
- super(provider);
538
- this.transactionHashes = [];
539
- }
540
- async _request(args) {
541
- let response;
542
- try {
543
- response = await this.provider.request(args);
544
- } catch (err) {
545
- console.error(`failed to execute ${args.method}`, args);
546
- throw err;
547
- }
548
- if (args.method === "eth_sendRawTransaction" || args.method === "eth_sendTransaction") {
549
- this.transactionHashes.push(response);
550
- }
551
- return response;
552
- }
56
+ var scripts = {
57
+ build: "rimraf dist && pkgroll --sourcemap",
58
+ dev: "pkgroll --watch",
59
+ "gen-docs": "typedoc --out docs src",
60
+ "serve-docs": "ipfs-emulator --only -d docs -p 8080"
553
61
  };
554
-
555
- // src/environment/index.ts
556
- globalThis.extensions = [];
557
- globalThis.signerProtocols = {};
558
- function wait(numSeconds) {
559
- return new Promise((resolve) => {
560
- setTimeout(resolve, numSeconds * 1e3);
561
- });
562
- }
563
- function displayTransaction(transaction) {
564
- if (transaction.type === "0x2") {
565
- return `(maxFeePerGas: ${BigInt(transaction.maxFeePerGas).toString()}, maxPriorityFeePerGas: ${BigInt(
566
- transaction.maxPriorityFeePerGas
567
- ).toString()})`;
568
- } else {
569
- return `(gasPrice: ${BigInt(transaction.gasPrice).toString()})`;
570
- }
571
- }
572
- async function createEnvironment(config, providedContext) {
573
- const rawProvider = "provider" in config.network ? config.network.provider : new import_eip_1193_jsonrpc_provider.JSONRPCHTTPProvider(config.network.nodeUrl);
574
- const provider = new TransactionHashTracker(rawProvider);
575
- const transport = (0, import_viem3.custom)(provider);
576
- const viemClient = (0, import_viem3.createPublicClient)({ transport });
577
- const chainId = (await viemClient.getChainId()).toString();
578
- let genesisHash;
579
- try {
580
- genesisHash = (await viemClient.getBlock({ blockTag: "earliest" })).hash;
581
- } catch (err) {
582
- console.error(`failed to get genesis hash`);
583
- }
584
- let networkName;
585
- let saveDeployments;
586
- let networkTags = {};
587
- for (const networkTag of config.network.tags) {
588
- networkTags[networkTag] = true;
589
- }
590
- if ("nodeUrl" in config) {
591
- networkName = config.network.name;
592
- saveDeployments = true;
593
- } else {
594
- if (config.network.name) {
595
- networkName = config.network.name;
596
- } else {
597
- networkName = "memory";
598
- }
599
- if (networkName === "memory" || networkName === "hardhat") {
600
- networkTags["memory"] = true;
601
- saveDeployments = false;
602
- } else {
603
- saveDeployments = true;
604
- }
605
- }
606
- if (config.saveDeployments !== void 0) {
607
- saveDeployments = config.saveDeployments;
608
- }
609
- const resolvedAccounts = {};
610
- const accountCache = {};
611
- async function getAccount(name, accounts, accountDef) {
612
- if (accountCache[name]) {
613
- return accountCache[name];
614
- }
615
- let account;
616
- if (typeof accountDef === "number") {
617
- const accounts2 = await provider.request({ method: "eth_accounts" });
618
- const accountPerIndex = accounts2[accountDef];
619
- if (accountPerIndex) {
620
- accountCache[name] = account = {
621
- type: "remote",
622
- address: accountPerIndex,
623
- signer: provider
624
- };
625
- }
626
- } else if (typeof accountDef === "string") {
627
- if (accountDef.startsWith("0x")) {
628
- if (accountDef.length === 66) {
629
- const privateKeyProtocol = globalThis.signerProtocols["privateKey"];
630
- if (privateKeyProtocol) {
631
- const namedSigner = await privateKeyProtocol.getSigner(`privateKey:${accountDef}`);
632
- const [address] = await namedSigner.signer.request({ method: "eth_accounts" });
633
- accountCache[name] = account = {
634
- ...namedSigner,
635
- address
636
- };
637
- }
638
- } else {
639
- accountCache[name] = account = {
640
- type: "remote",
641
- address: accountDef,
642
- signer: provider
643
- };
644
- }
645
- } else {
646
- if (accountDef.indexOf(":") > 0) {
647
- const [protocolID, extra] = accountDef.split(":");
648
- const protocol = globalThis.signerProtocols[protocolID];
649
- if (!protocol) {
650
- throw new Error(`protocol: ${protocol} is not supported`);
651
- }
652
- const namedSigner = await protocol.getSigner(accountDef);
653
- const [address] = await namedSigner.signer.request({ method: "eth_accounts" });
654
- accountCache[name] = account = {
655
- ...namedSigner,
656
- address
657
- };
658
- } else {
659
- const accountFetched = await getAccount(name, accounts, accounts[accountDef]);
660
- if (accountFetched) {
661
- accountCache[name] = account = accountFetched;
662
- }
663
- }
664
- }
665
- } else {
666
- const accountForNetwork = accountDef[networkName] || accountDef[chainId] || accountDef["default"];
667
- if (typeof accountForNetwork !== void 0) {
668
- const accountFetched = await getAccount(name, accounts, accountForNetwork);
669
- if (accountFetched) {
670
- accountCache[name] = account = accountFetched;
671
- }
672
- }
673
- }
674
- return account;
675
- }
676
- if (providedContext.accounts) {
677
- const accountNames = Object.keys(providedContext.accounts);
678
- for (const accountName of accountNames) {
679
- let account = await getAccount(accountName, providedContext.accounts, providedContext.accounts[accountName]);
680
- resolvedAccounts[accountName] = account;
681
- }
682
- }
683
- const context = {
684
- accounts: resolvedAccounts,
685
- artifacts: providedContext.artifacts,
686
- network: {
687
- name: networkName,
688
- fork: config.network.fork,
689
- saveDeployments,
690
- tags: networkTags
691
- }
692
- };
693
- const { deployments } = loadDeployments(
694
- config.deployments,
695
- context.network.name,
696
- false,
697
- context.network.fork ? void 0 : {
698
- chainId,
699
- genesisHash,
700
- deleteDeploymentsIfDifferentGenesisHash: true
701
- }
702
- );
703
- const namedAccounts = {};
704
- const namedSigners = {};
705
- const addressSigners = {};
706
- for (const entry of Object.entries(resolvedAccounts)) {
707
- const name = entry[0];
708
- const { address, ...namedSigner } = entry[1];
709
- namedAccounts[name] = address;
710
- addressSigners[address] = namedSigner;
711
- namedSigners[name] = namedSigner;
712
- }
713
- const perliminaryEnvironment = {
714
- config,
715
- deployments,
716
- accounts: namedAccounts,
717
- signers: namedSigners,
718
- addressSigners,
719
- artifacts: context.artifacts,
720
- network: {
721
- chain: getChain(chainId),
722
- name: context.network.name,
723
- tags: context.network.tags,
724
- provider
725
- }
726
- };
727
- function ensureDeploymentFolder() {
728
- const folderPath = import_node_path3.default.join(config.deployments, context.network.name);
729
- import_node_fs3.default.mkdirSync(folderPath, { recursive: true });
730
- const chainFilepath = import_node_path3.default.join(folderPath, ".chain");
731
- if (!import_node_fs3.default.existsSync(chainFilepath)) {
732
- import_node_fs3.default.writeFileSync(chainFilepath, JSON.stringify({ chainId, genesisHash }));
733
- }
734
- return folderPath;
735
- }
736
- function get(name) {
737
- const deployment = deployments[name];
738
- if (!deployment) {
739
- throw new Error(`no deployment named "${name}" found.`);
740
- }
741
- return deployment;
742
- }
743
- function getOrNull(name) {
744
- return deployments[name] || null;
745
- }
746
- function fromAddressToNamedABIOrNull(address) {
747
- let list = [];
748
- for (const name of Object.keys(deployments)) {
749
- const deployment = deployments[name];
750
- if (deployment.address.toLowerCase() == address.toLowerCase()) {
751
- list.push({ name, artifact: deployment });
752
- }
753
- }
754
- if (list.length === 0) {
755
- return null;
756
- }
757
- const { mergedABI } = mergeArtifacts(list);
758
- return {
759
- mergedABI,
760
- names: list.map((v) => v.name)
761
- };
762
- }
763
- function fromAddressToNamedABI(address) {
764
- const n = fromAddressToNamedABIOrNull(address);
765
- if (!n) {
766
- throw new Error(`could not find artifact for address ${address}`);
767
- }
768
- return n;
769
- }
770
- async function save(name, deployment) {
771
- deployments[name] = deployment;
772
- if (context.network.saveDeployments) {
773
- const folderPath = ensureDeploymentFolder();
774
- import_node_fs3.default.writeFileSync(`${folderPath}/${name}.json`, JSONToString(deployment, 2));
775
- }
776
- return deployment;
777
- }
778
- async function recoverTransactionsIfAny() {
779
- if (!context.network.saveDeployments) {
780
- return;
781
- }
782
- const folderPath = ensureDeploymentFolder();
783
- const filepath = import_node_path3.default.join(folderPath, ".pending_transactions.json");
784
- let existingPendingTansactions;
785
- try {
786
- existingPendingTansactions = stringToJSON(import_node_fs3.default.readFileSync(filepath, "utf-8"));
787
- } catch {
788
- existingPendingTansactions = [];
789
- }
790
- if (existingPendingTansactions.length > 0) {
791
- while (existingPendingTansactions.length > 0) {
792
- const pendingTransaction = existingPendingTansactions.shift();
793
- if (pendingTransaction) {
794
- if (pendingTransaction.type === "deployment") {
795
- const spinner = spin(
796
- `recovering ${pendingTransaction.name} with transaction ${pendingTransaction.transaction.hash}`
797
- );
798
- try {
799
- await waitForDeploymentTransactionAndSave(pendingTransaction);
800
- import_node_fs3.default.writeFileSync(filepath, JSONToString(existingPendingTansactions, 2));
801
- spinner.succeed();
802
- } catch (e) {
803
- spinner.fail();
804
- throw e;
805
- }
806
- } else {
807
- const spinner = spin(`recovering execution's transaction ${pendingTransaction.transaction.hash}`);
808
- try {
809
- await waitForTransaction(pendingTransaction.transaction.hash);
810
- import_node_fs3.default.writeFileSync(filepath, JSONToString(existingPendingTansactions, 2));
811
- spinner.succeed();
812
- } catch (e) {
813
- spinner.fail();
814
- throw e;
815
- }
816
- }
817
- }
818
- }
819
- import_node_fs3.default.rmSync(filepath);
820
- }
821
- }
822
- async function savePendingTransaction(pendingTransaction) {
823
- if (context.network.saveDeployments) {
824
- const folderPath = ensureDeploymentFolder();
825
- const filepath = import_node_path3.default.join(folderPath, ".pending_transactions.json");
826
- let existingPendinTransactions;
827
- try {
828
- existingPendinTransactions = stringToJSON(import_node_fs3.default.readFileSync(filepath, "utf-8"));
829
- } catch {
830
- existingPendinTransactions = [];
831
- }
832
- existingPendinTransactions.push(pendingTransaction);
833
- import_node_fs3.default.writeFileSync(filepath, JSONToString(existingPendinTransactions, 2));
834
- }
835
- return deployments;
836
- }
837
- async function waitForTransactionReceipt(params) {
838
- const { hash, pollingInterval } = { pollingInterval: 1, ...params };
839
- let latestBlockNumber = await provider.request({
840
- method: "eth_blockNumber"
841
- });
842
- let receipt = await provider.request({
843
- method: "eth_getTransactionReceipt",
844
- params: [hash]
845
- });
846
- if (!receipt || !receipt.blockHash) {
847
- await wait(pollingInterval);
848
- return waitForTransactionReceipt(params);
849
- }
850
- return { receipt, latestBlockNumber };
851
- }
852
- async function deleteTransaction(hash) {
853
- if (context.network.saveDeployments) {
854
- const folderPath = ensureDeploymentFolder();
855
- const filepath = import_node_path3.default.join(folderPath, ".pending_transactions.json");
856
- let existingPendinTransactions;
857
- try {
858
- existingPendinTransactions = stringToJSON(import_node_fs3.default.readFileSync(filepath, "utf-8"));
859
- } catch {
860
- existingPendinTransactions = [];
861
- }
862
- existingPendinTransactions = existingPendinTransactions.filter((v) => v.transaction.hash !== hash);
863
- if (existingPendinTransactions.length === 0) {
864
- import_node_fs3.default.rmSync(filepath);
865
- } else {
866
- import_node_fs3.default.writeFileSync(filepath, JSONToString(existingPendinTransactions, 2));
867
- }
868
- }
869
- }
870
- async function exportDeploymentsAsTypes() {
871
- const folderPath = "./generated";
872
- import_node_fs3.default.mkdirSync(folderPath, { recursive: true });
873
- import_node_fs3.default.writeFileSync(`${folderPath}/deployments.ts`, `export default ${JSONToString(deployments, 2)} as const;`);
874
- }
875
- async function waitForTransaction(hash, info) {
876
- const spinner = spin(
877
- info?.message ? info.message : ` - Broadcasting tx:
878
- ${hash}${info?.transaction ? `
879
- ${displayTransaction(info?.transaction)}` : ""}`
880
- );
881
- let receiptResult;
882
- try {
883
- receiptResult = await waitForTransactionReceipt({
884
- hash
885
- });
886
- } catch (e) {
887
- spinner.fail();
888
- throw e;
889
- }
890
- if (!receiptResult) {
891
- throw new Error(`receipt for ${hash} not found`);
892
- } else {
893
- spinner.succeed();
894
- }
895
- return receiptResult;
896
- }
897
- async function waitForDeploymentTransactionAndSave(pendingDeployment, transaction) {
898
- const message = ` - Deploying ${pendingDeployment.name} with tx:
899
- ${pendingDeployment.transaction.hash}${transaction ? `
900
- ${displayTransaction(transaction)}` : ""}`;
901
- const { receipt, latestBlockNumber } = await waitForTransaction(pendingDeployment.transaction.hash, {
902
- message,
903
- transaction
904
- });
905
- const contractAddress = pendingDeployment.expectedAddress || receipt.contractAddress;
906
- if (!contractAddress) {
907
- console.error(receipt);
908
- throw new Error(`no contract address found for ${pendingDeployment.name}`);
909
- }
910
- showMessage(` => ${contractAddress}`);
911
- const { abi, ...artifactObjectWithoutABI } = pendingDeployment.partialDeployment;
912
- if (!pendingDeployment.transaction.hash) {
913
- const spinner = spin();
914
- let transaction2 = null;
915
- try {
916
- transaction2 = await provider.request({
917
- method: "eth_getTransactionByHash",
918
- params: [pendingDeployment.transaction.hash]
919
- });
920
- } catch (e) {
921
- spinner.fail();
922
- throw e;
923
- }
924
- if (!transaction2) {
925
- spinner.fail(`tx ${pendingDeployment.transaction.hash} not found`);
926
- } else {
927
- spinner.stop();
928
- }
929
- if (transaction2) {
930
- pendingDeployment.transaction = {
931
- nonce: transaction2.nonce,
932
- hash: transaction2.hash,
933
- origin: transaction2.from
934
- };
935
- }
936
- }
937
- for (const key of Object.keys(artifactObjectWithoutABI)) {
938
- if (key.startsWith("_")) {
939
- delete artifactObjectWithoutABI[key];
940
- }
941
- if (key === "evm") {
942
- if (artifactObjectWithoutABI.evm) {
943
- if ("gasEstimates" in artifactObjectWithoutABI["evm"]) {
944
- const { gasEstimates } = artifactObjectWithoutABI.evm;
945
- artifactObjectWithoutABI.evm = {
946
- gasEstimates
947
- };
948
- }
949
- }
950
- }
951
- }
952
- const latestBlockNumberAsNumber = parseInt(latestBlockNumber.slice(2), 16);
953
- const receiptBlockNumber = parseInt(receipt.blockNumber.slice(2), 16);
954
- const confirmations = Math.max(0, latestBlockNumberAsNumber - receiptBlockNumber);
955
- const deployment = {
956
- address: contractAddress,
957
- abi,
958
- ...artifactObjectWithoutABI,
959
- transaction: pendingDeployment.transaction,
960
- receipt: {
961
- confirmations,
962
- blockHash: receipt.blockHash,
963
- blockNumber: receipt.blockNumber,
964
- transactionIndex: receipt.transactionIndex
965
- }
966
- };
967
- return save(pendingDeployment.name, deployment);
968
- }
969
- async function savePendingExecution(pendingExecution) {
970
- await savePendingTransaction(pendingExecution);
971
- let transaction = null;
972
- const spinner = spin();
973
- try {
974
- transaction = await provider.request({
975
- method: "eth_getTransactionByHash",
976
- params: [pendingExecution.transaction.hash]
977
- });
978
- } catch (e) {
979
- spinner.fail();
980
- throw e;
981
- }
982
- if (!transaction) {
983
- spinner.fail(`tx ${pendingExecution.transaction.hash} not found`);
984
- } else {
985
- spinner.stop();
986
- }
987
- if (transaction) {
988
- pendingExecution.transaction.nonce = transaction.nonce;
989
- pendingExecution.transaction.origin = transaction.from;
990
- }
991
- const { receipt } = await waitForTransaction(pendingExecution.transaction.hash, { transaction });
992
- await deleteTransaction(pendingExecution.transaction.hash);
993
- return receipt;
994
- }
995
- async function savePendingDeployment(pendingDeployment) {
996
- await savePendingTransaction(pendingDeployment);
997
- let transaction = null;
998
- const spinner = spin();
999
- try {
1000
- transaction = await provider.request({
1001
- method: "eth_getTransactionByHash",
1002
- params: [pendingDeployment.transaction.hash]
1003
- });
1004
- } catch (e) {
1005
- console.error(`failed to fetch tx ${pendingDeployment.transaction.hash}. Can't know its status`);
1006
- spinner.fail();
1007
- throw e;
1008
- }
1009
- if (!transaction) {
1010
- spinner.fail(`tx ${pendingDeployment.transaction.hash} not found`);
1011
- } else {
1012
- spinner.stop();
1013
- }
1014
- if (transaction) {
1015
- pendingDeployment = {
1016
- ...pendingDeployment,
1017
- transaction: { hash: transaction.hash, nonce: transaction.nonce, origin: transaction.from }
1018
- };
1019
- }
1020
- const deployment = await waitForDeploymentTransactionAndSave(pendingDeployment, transaction);
1021
- await deleteTransaction(pendingDeployment.transaction.hash);
1022
- return deployment;
1023
- }
1024
- function showMessage(message) {
1025
- log(message);
1026
- }
1027
- function showProgress(message) {
1028
- return spin(message);
1029
- }
1030
- let env = {
1031
- ...perliminaryEnvironment,
1032
- save,
1033
- savePendingDeployment,
1034
- savePendingExecution,
1035
- get,
1036
- getOrNull,
1037
- fromAddressToNamedABI,
1038
- fromAddressToNamedABIOrNull,
1039
- showMessage,
1040
- showProgress
1041
- };
1042
- for (const extension of globalThis.extensions) {
1043
- env = extension(env);
1044
- }
1045
- return {
1046
- external: env,
1047
- internal: {
1048
- exportDeploymentsAsTypes,
1049
- recoverTransactionsIfAny
1050
- }
1051
- };
1052
- }
1053
-
1054
- // src/utils/eth.ts
1055
- function avg(arr) {
1056
- const sum = arr.reduce((a, v) => a + v);
1057
- return sum / BigInt(arr.length);
1058
- }
1059
- async function getGasPriceEstimate(provider, options2) {
1060
- const defaultOptions = {
1061
- blockCount: 20,
1062
- newestBlock: "pending",
1063
- rewardPercentiles: [10, 50, 80]
1064
- };
1065
- const optionsResolved = options2 ? { ...defaultOptions, ...options2 } : defaultOptions;
1066
- const historicalBlocks = optionsResolved.blockCount;
1067
- const rawFeeHistory = await provider.request({
1068
- method: "eth_feeHistory",
1069
- params: [`0x${historicalBlocks.toString(16)}`, optionsResolved.newestBlock, optionsResolved.rewardPercentiles]
1070
- });
1071
- let blockNum = Number(rawFeeHistory.oldestBlock);
1072
- const lastBlock = blockNum + rawFeeHistory.reward.length;
1073
- let index = 0;
1074
- const blocksHistory = [];
1075
- while (blockNum < lastBlock) {
1076
- blocksHistory.push({
1077
- number: blockNum,
1078
- baseFeePerGas: BigInt(rawFeeHistory.baseFeePerGas[index]),
1079
- gasUsedRatio: Number(rawFeeHistory.gasUsedRatio[index]),
1080
- priorityFeePerGas: rawFeeHistory.reward[index].map((x) => BigInt(x))
1081
- });
1082
- blockNum += 1;
1083
- index += 1;
1084
- }
1085
- const percentilePriorityFeeAverages = [];
1086
- for (let i = 0; i < optionsResolved.rewardPercentiles.length; i++) {
1087
- percentilePriorityFeeAverages.push(avg(blocksHistory.map((b) => b.priorityFeePerGas[i])));
1088
- }
1089
- const baseFeePerGas = BigInt(rawFeeHistory.baseFeePerGas[rawFeeHistory.baseFeePerGas.length - 1]);
1090
- const result = [];
1091
- for (let i = 0; i < optionsResolved.rewardPercentiles.length; i++) {
1092
- result.push({
1093
- maxFeePerGas: percentilePriorityFeeAverages[i] + baseFeePerGas,
1094
- maxPriorityFeePerGas: percentilePriorityFeeAverages[i]
1095
- });
1096
- }
1097
- return result;
1098
- }
1099
- async function getRoughGasPriceEstimate(provider, options2) {
1100
- const defaultOptions = {
1101
- blockCount: 20,
1102
- newestBlock: "pending",
1103
- rewardPercentiles: [10, 50, 80]
1104
- };
1105
- const optionsResolved = options2 ? { ...defaultOptions, ...options2 } : defaultOptions;
1106
- if (optionsResolved.rewardPercentiles.length !== 3) {
1107
- throw new Error(`rough gas estimate require 3 percentile, it defaults to [10,50,80]`);
1108
- }
1109
- const result = await getGasPriceEstimate(provider, optionsResolved);
1110
- return {
1111
- slow: result[0],
1112
- average: result[1],
1113
- fast: result[2]
1114
- };
1115
- }
1116
-
1117
- // src/executor/index.ts
1118
- var import_prompts = __toESM(require("prompts"), 1);
1119
- var import_viem4 = require("viem");
1120
- if (!process.env["ROCKETH_SKIP_ESBUILD"]) {
1121
- require("esbuild-register/dist/node").register();
1122
- }
1123
- function readConfig(options2) {
1124
- let configFile;
1125
- try {
1126
- const configString = import_node_fs4.default.readFileSync("./rocketh.json", "utf-8");
1127
- configFile = JSON.parse(configString);
1128
- } catch {
1129
- }
1130
- if (configFile) {
1131
- if (!options2.deployments && configFile.deployments) {
1132
- options2.deployments = configFile.deployments;
1133
- }
1134
- if (!options2.scripts && configFile.scripts) {
1135
- options2.scripts = configFile.scripts;
1136
- }
1137
- }
1138
- const fromEnv = process.env["ETH_NODE_URI_" + options2.network];
1139
- const fork = typeof options2.network !== "string";
1140
- let networkName = "memory";
1141
- if (options2.network) {
1142
- if (typeof options2.network === "string") {
1143
- networkName = options2.network;
1144
- } else if ("fork" in options2.network) {
1145
- networkName = options2.network.fork;
1146
- }
1147
- }
1148
- let networkTags = configFile?.networks && configFile?.networks[networkName]?.tags || [];
1149
- if (!options2.provider) {
1150
- let nodeUrl;
1151
- if (typeof fromEnv === "string") {
1152
- nodeUrl = fromEnv;
1153
- } else {
1154
- if (configFile) {
1155
- const network = configFile.networks && configFile.networks[networkName];
1156
- if (network && network.rpcUrl) {
1157
- nodeUrl = network.rpcUrl;
1158
- } else {
1159
- if (options2?.ignoreMissingRPC) {
1160
- nodeUrl = "";
1161
- } else {
1162
- if (options2.network === "localhost") {
1163
- nodeUrl = "http://127.0.0.1:8545";
1164
- } else {
1165
- logger.error(`network "${options2.network}" is not configured. Please add it to the rocketh.json file`);
1166
- process.exit(1);
1167
- }
1168
- }
1169
- }
1170
- } else {
1171
- if (options2?.ignoreMissingRPC) {
1172
- nodeUrl = "";
1173
- } else {
1174
- if (options2.network === "localhost") {
1175
- nodeUrl = "http://127.0.0.1:8545";
1176
- } else {
1177
- logger.error(`network "${options2.network}" is not configured. Please add it to the rocketh.json file`);
1178
- process.exit(1);
1179
- }
1180
- }
1181
- }
1182
- }
1183
- return {
1184
- network: {
1185
- nodeUrl,
1186
- name: networkName,
1187
- tags: networkTags,
1188
- fork
1189
- },
1190
- deployments: options2.deployments,
1191
- saveDeployments: options2.saveDeployments,
1192
- scripts: options2.scripts,
1193
- tags: typeof options2.tags === "undefined" ? void 0 : options2.tags.split(","),
1194
- logLevel: options2.logLevel,
1195
- askBeforeProceeding: options2.askBeforeProceeding,
1196
- reportGasUse: options2.reportGasUse
1197
- };
1198
- } else {
1199
- return {
1200
- network: {
1201
- provider: options2.provider,
1202
- name: networkName,
1203
- tags: networkTags,
1204
- fork
1205
- },
1206
- deployments: options2.deployments,
1207
- saveDeployments: options2.saveDeployments,
1208
- scripts: options2.scripts,
1209
- tags: typeof options2.tags === "undefined" ? void 0 : options2.tags.split(","),
1210
- logLevel: options2.logLevel,
1211
- askBeforeProceeding: options2.askBeforeProceeding,
1212
- reportGasUse: options2.reportGasUse
1213
- };
1214
- }
1215
- }
1216
- function readAndResolveConfig(options2) {
1217
- return resolveConfig(readConfig(options2));
1218
- }
1219
- function resolveConfig(config) {
1220
- const resolvedConfig = {
1221
- ...config,
1222
- network: config.network,
1223
- // TODO default to || {name: 'memory'....}
1224
- deployments: config.deployments || "deployments",
1225
- scripts: config.scripts || "deploy",
1226
- tags: config.tags || [],
1227
- networkTags: config.networkTags || [],
1228
- saveDeployments: config.saveDeployments
1229
- };
1230
- return resolvedConfig;
1231
- }
1232
- async function loadAndExecuteDeployments(options2, args) {
1233
- const resolvedConfig = readAndResolveConfig(options2);
1234
- return executeDeployScripts(resolvedConfig, args);
1235
- }
1236
- async function executeDeployScripts(config, args) {
1237
- setLogLevel(typeof config.logLevel === "undefined" ? 0 : config.logLevel);
1238
- let filepaths;
1239
- filepaths = traverseMultipleDirectory([config.scripts]);
1240
- filepaths = filepaths.filter((v) => !import_node_path4.default.basename(v).startsWith("_")).sort((a, b) => {
1241
- if (a < b) {
1242
- return -1;
1243
- }
1244
- if (a > b) {
1245
- return 1;
1246
- }
1247
- return 0;
1248
- });
1249
- let providedContext;
1250
- const scriptModuleByFilePath = {};
1251
- const scriptPathBags = {};
1252
- const scriptFilePaths = [];
1253
- for (const filepath of filepaths) {
1254
- const scriptFilePath = import_node_path4.default.resolve(filepath);
1255
- let scriptModule;
1256
- try {
1257
- if (require.cache) {
1258
- delete require.cache[scriptFilePath];
1259
- }
1260
- scriptModule = require(scriptFilePath);
1261
- if (scriptModule.default) {
1262
- scriptModule = scriptModule.default;
1263
- if (scriptModule.default) {
1264
- logger.warn(`double default...`);
1265
- scriptModule = scriptModule.default;
1266
- }
1267
- }
1268
- scriptModuleByFilePath[scriptFilePath] = scriptModule;
1269
- if (providedContext && providedContext !== scriptModule.providedContext) {
1270
- throw new Error(`context between 2 scripts is different, please share the same across them`);
1271
- }
1272
- providedContext = scriptModule.providedContext;
1273
- } catch (e) {
1274
- logger.error(`could not import ${filepath}`);
1275
- throw e;
1276
- }
1277
- let scriptTags = scriptModule.tags;
1278
- if (scriptTags !== void 0) {
1279
- if (typeof scriptTags === "string") {
1280
- scriptTags = [scriptTags];
1281
- }
1282
- for (const tag of scriptTags) {
1283
- if (tag.indexOf(",") >= 0) {
1284
- throw new Error("Tag cannot contains commas");
1285
- }
1286
- const bag = scriptPathBags[tag] || [];
1287
- scriptPathBags[tag] = bag;
1288
- bag.push(scriptFilePath);
1289
- }
1290
- }
1291
- if (config.tags !== void 0 && config.tags.length > 0) {
1292
- let found = false;
1293
- if (scriptTags !== void 0) {
1294
- for (const tagToFind of config.tags) {
1295
- for (const tag of scriptTags) {
1296
- if (tag === tagToFind) {
1297
- scriptFilePaths.push(scriptFilePath);
1298
- found = true;
1299
- break;
1300
- }
1301
- }
1302
- if (found) {
1303
- break;
1304
- }
1305
- }
1306
- }
1307
- } else {
1308
- scriptFilePaths.push(scriptFilePath);
1309
- }
1310
- }
1311
- if (!providedContext) {
1312
- throw new Error(`no context loaded`);
1313
- }
1314
- const { internal, external } = await createEnvironment(config, providedContext);
1315
- await internal.recoverTransactionsIfAny();
1316
- const scriptsRegisteredToRun = {};
1317
- const scriptsToRun = [];
1318
- const scriptsToRunAtTheEnd = [];
1319
- function recurseDependencies(scriptFilePath) {
1320
- if (scriptsRegisteredToRun[scriptFilePath]) {
1321
- return;
1322
- }
1323
- const scriptModule = scriptModuleByFilePath[scriptFilePath];
1324
- if (scriptModule.dependencies) {
1325
- for (const dependency of scriptModule.dependencies) {
1326
- const scriptFilePathsToAdd = scriptPathBags[dependency];
1327
- if (scriptFilePathsToAdd) {
1328
- for (const scriptFilenameToAdd of scriptFilePathsToAdd) {
1329
- recurseDependencies(scriptFilenameToAdd);
1330
- }
1331
- }
1332
- }
1333
- }
1334
- if (!scriptsRegisteredToRun[scriptFilePath]) {
1335
- if (scriptModule.runAtTheEnd) {
1336
- scriptsToRunAtTheEnd.push({
1337
- filePath: scriptFilePath,
1338
- func: scriptModule
1339
- });
1340
- } else {
1341
- scriptsToRun.push({
1342
- filePath: scriptFilePath,
1343
- func: scriptModule
1344
- });
1345
- }
1346
- scriptsRegisteredToRun[scriptFilePath] = true;
1347
- }
1348
- }
1349
- for (const scriptFilePath of scriptFilePaths) {
1350
- recurseDependencies(scriptFilePath);
1351
- }
1352
- if (config.askBeforeProceeding) {
1353
- console.log(
1354
- `Network: ${external.network.name}
1355
- Chain: ${external.network.chain.name}
1356
- Tags: ${Object.keys(
1357
- external.network.tags
1358
- ).join("',")}`
1359
- );
1360
- const gasPriceEstimate = await getRoughGasPriceEstimate(external.network.provider);
1361
- const prompt = await (0, import_prompts.default)({
1362
- type: "confirm",
1363
- name: "proceed",
1364
- message: `gas price is currently in this range:
1365
- slow: ${(0, import_viem4.formatEther)(gasPriceEstimate.slow.maxFeePerGas)} (priority: ${(0, import_viem4.formatEther)(
1366
- gasPriceEstimate.slow.maxPriorityFeePerGas
1367
- )})
1368
- average: ${(0, import_viem4.formatEther)(gasPriceEstimate.average.maxFeePerGas)} (priority: ${(0, import_viem4.formatEther)(
1369
- gasPriceEstimate.average.maxPriorityFeePerGas
1370
- )})
1371
- fast: ${(0, import_viem4.formatEther)(gasPriceEstimate.fast.maxFeePerGas)} (priority: ${(0, import_viem4.formatEther)(
1372
- gasPriceEstimate.fast.maxPriorityFeePerGas
1373
- )})
1374
-
1375
- Do you want to proceed (note that gas price can change for each tx)`
1376
- });
1377
- if (!prompt.proceed) {
1378
- process.exit();
1379
- }
1380
- }
1381
- for (const deployScript of scriptsToRun.concat(scriptsToRunAtTheEnd)) {
1382
- const filename = import_node_path4.default.basename(deployScript.filePath);
1383
- const relativeFilepath = import_node_path4.default.relative(".", deployScript.filePath);
1384
- let skip = false;
1385
- const spinner = spin(`- Executing ${filename}`);
1386
- if (deployScript.func.skip) {
1387
- const spinner2 = spin(` - skip?()`);
1388
- try {
1389
- skip = await deployScript.func.skip(external, args);
1390
- spinner2.succeed(skip ? `skipping ${filename}` : void 0);
1391
- } catch (e) {
1392
- spinner2.fail();
1393
- throw e;
1394
- }
1395
- }
1396
- if (!skip) {
1397
- let result;
1398
- try {
1399
- result = await deployScript.func(external, args);
1400
- spinner.succeed(`
1401
- `);
1402
- } catch (e) {
1403
- spinner.fail();
1404
- throw e;
1405
- }
1406
- if (result && typeof result === "boolean") {
1407
- const deploymentFolderPath = config.deployments;
1408
- }
1409
- }
1410
- }
1411
- if (config.reportGasUse) {
1412
- const provider = external.network.provider;
1413
- const transactionHashes = provider.transactionHashes;
1414
- let totalGasUsed = 0;
1415
- for (const hash of transactionHashes) {
1416
- const transactionReceipt = await provider.request({ method: "eth_getTransactionReceipt", params: [hash] });
1417
- if (transactionReceipt) {
1418
- const gasUsed = Number(transactionReceipt.gasUsed);
1419
- totalGasUsed += gasUsed;
1420
- }
1421
- }
1422
- console.log({ totalGasUsed });
1423
- }
1424
- return external;
1425
- }
1426
-
1427
- // src/cli.ts
1428
- var import_commander = require("commander");
1429
-
1430
- // package.json
1431
- var package_default = {
1432
- name: "rocketh",
1433
- version: "0.10.7",
1434
- description: "deploy smart contract on ethereum-compatible networks",
1435
- publishConfig: {
1436
- access: "public"
1437
- },
1438
- type: "module",
1439
- main: "dist/index.cjs",
1440
- module: "dist/index.js",
1441
- types: "dist/index.d.ts",
1442
- bin: {
1443
- rocketh: "dist/cli.cjs"
1444
- },
1445
- devDependencies: {
1446
- "@types/figlet": "^1.5.8",
1447
- "@types/node": "^20.11.19",
1448
- "@types/prompts": "^2.4.9",
1449
- abitype: "^1.0.0",
1450
- "eip-1193": "^0.5.0",
1451
- "ipfs-gateway-emulator": "4.2.1-ipfs.2",
1452
- rimraf: "^5.0.5",
1453
- tsup: "^8.0.2",
1454
- typedoc: "^0.25.8",
1455
- typescript: "^5.3.3"
1456
- },
1457
- dependencies: {
1458
- commander: "^12.0.0",
1459
- "eip-1193-jsonrpc-provider": "^0.3.0",
1460
- esbuild: "^0.20.1",
1461
- "esbuild-register": "^3.5.0",
1462
- ethers: "^6.11.1",
1463
- figlet: "^1.7.0",
1464
- ldenv: "^0.3.9",
1465
- "named-logs": "^0.2.2",
1466
- "named-logs-console": "^0.3.0",
1467
- prompts: "^2.4.2",
1468
- viem: "^2.7.11"
1469
- },
1470
- scripts: {
1471
- build: "rimraf dist && tsup --entry src/index.ts --entry src/cli.ts --dts --format esm,cjs",
1472
- dev: "rimraf dist && tsup --entry src/index.ts --entry src/cli.ts --dts --format esm,cjs --watch",
1473
- "dev-no-reset": "tsup --entry src/index.ts --entry src/cli.ts --dts --format esm,cjs --watch",
1474
- "gen-docs": "typedoc --out docs src",
1475
- "serve-docs": "ipfs-emulator --only -d docs -p 8080"
1476
- }
62
+ var pkg = {
63
+ name: name,
64
+ version: version,
65
+ description: description,
66
+ publishConfig: publishConfig,
67
+ type: type,
68
+ main: main,
69
+ module: module$1,
70
+ types: types,
71
+ ".": {
72
+ require: {
73
+ types: "./dist/index.d.ts",
74
+ "default": "./dist/index.cjs"
75
+ },
76
+ "import": {
77
+ types: "./dist/index.d.ts",
78
+ "default": "./dist/index.mjs"
79
+ }
80
+ },
81
+ bin: bin,
82
+ devDependencies: devDependencies,
83
+ dependencies: dependencies,
84
+ scripts: scripts
1477
85
  };
1478
86
 
1479
- // src/cli.ts
1480
- (0, import_ldenv.loadEnv)();
1481
- var commandName = package_default.name;
1482
- var program = new import_commander.Command();
1483
- program.name(commandName).version(package_default.version).usage(`${commandName}`).description("execute deploy scripts and store the deployments").option("-s, --scripts <value>", "path the folder containing the deploy scripts to execute").option("-t, --tags <value>", "comma separated list of tags to execute").option("-d, --deployments <value>", "folder where deployments are saved").option("--skip-gas-report", "if set skip gas report").option("--skip-prompts", "if set skip any prompts").requiredOption("-n, --network <value>", "network context to use").parse(process.argv);
1484
- var options = program.opts();
87
+ ldenv.loadEnv();
88
+ const commandName = pkg.name;
89
+ const program = new commander.Command();
90
+ program.name(commandName).version(pkg.version).usage(`${commandName}`).description("execute deploy scripts and store the deployments").option("-s, --scripts <value>", "path the folder containing the deploy scripts to execute").option("-t, --tags <value>", "comma separated list of tags to execute").option("-d, --deployments <value>", "folder where deployments are saved").option("--skip-gas-report", "if set skip gas report").option("--skip-prompts", "if set skip any prompts").requiredOption("-n, --network <value>", "network context to use").parse(process.argv);
91
+ const options = program.opts();
1485
92
  console.log(options);
1486
- loadAndExecuteDeployments({
93
+ index.loadAndExecuteDeployments({
1487
94
  ...options,
1488
95
  logLevel: 1,
1489
96
  askBeforeProceeding: options.skipPrompts ? false : true,
1490
97
  reportGasUse: options.skipGasReport ? false : true
1491
98
  });
1492
- //# sourceMappingURL=cli.cjs.map
99
+ //# sourceMappingURL=cli.cjs.map