rocketh 0.10.15 → 0.10.17

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