rocketh 0.10.8 → 0.10.9

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