rocketh 0.10.0 → 0.10.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # rocketh
2
2
 
3
+ ## 0.10.2
4
+
5
+ ### Patch Changes
6
+
7
+ - report gas use
8
+
9
+ ## 0.10.1
10
+
11
+ ### Patch Changes
12
+
13
+ - ask before proceeding option
14
+
3
15
  ## 0.10.0
4
16
 
5
17
  ### Minor Changes
@@ -364,6 +364,31 @@ function mergeArtifacts(list) {
364
364
  };
365
365
  }
366
366
 
367
+ // src/environment/providers/BaseProvider.ts
368
+ var BaseProvider = class {
369
+ constructor(provider) {
370
+ this.provider = provider;
371
+ }
372
+ request(args) {
373
+ return this._request(args);
374
+ }
375
+ };
376
+
377
+ // src/environment/providers/TransactionHashTracker.ts
378
+ var TransactionHashTracker = class extends BaseProvider {
379
+ constructor(provider) {
380
+ super(provider);
381
+ this.transactionHashes = [];
382
+ }
383
+ async _request(args) {
384
+ const response = await this.provider.request(args);
385
+ if (args.method === "eth_sendRawTransaction" || args.method === "eth_sendTransaction") {
386
+ this.transactionHashes.push(response);
387
+ }
388
+ return response;
389
+ }
390
+ };
391
+
367
392
  // src/environment/index.ts
368
393
  globalThis.extensions = [];
369
394
  function extendEnvironment(extension) {
@@ -390,7 +415,8 @@ function displayTransaction(transaction) {
390
415
  }
391
416
  }
392
417
  async function createEnvironment(config, providedContext) {
393
- const provider = "provider" in config.network ? config.network.provider : new JSONRPCHTTPProvider(config.network.nodeUrl);
418
+ const rawProvider = "provider" in config.network ? config.network.provider : new JSONRPCHTTPProvider(config.network.nodeUrl);
419
+ const provider = new TransactionHashTracker(rawProvider);
394
420
  const transport = custom(provider);
395
421
  const viemClient = createPublicClient({ transport });
396
422
  const chainId = (await viemClient.getChainId()).toString();
@@ -870,7 +896,72 @@ async function createEnvironment(config, providedContext) {
870
896
  };
871
897
  }
872
898
 
899
+ // src/utils/eth.ts
900
+ function avg(arr) {
901
+ const sum = arr.reduce((a, v) => a + v);
902
+ return sum / BigInt(arr.length);
903
+ }
904
+ async function getGasPriceEstimate(provider, options) {
905
+ const defaultOptions = {
906
+ blockCount: 20,
907
+ newestBlock: "pending",
908
+ rewardPercentiles: [10, 50, 80]
909
+ };
910
+ const optionsResolved = options ? { ...defaultOptions, ...options } : defaultOptions;
911
+ const historicalBlocks = optionsResolved.blockCount;
912
+ const rawFeeHistory = await provider.request({
913
+ method: "eth_feeHistory",
914
+ params: [`0x${historicalBlocks.toString(16)}`, optionsResolved.newestBlock, optionsResolved.rewardPercentiles]
915
+ });
916
+ let blockNum = Number(rawFeeHistory.oldestBlock);
917
+ const lastBlock = blockNum + rawFeeHistory.reward.length;
918
+ let index = 0;
919
+ const blocksHistory = [];
920
+ while (blockNum < lastBlock) {
921
+ blocksHistory.push({
922
+ number: blockNum,
923
+ baseFeePerGas: BigInt(rawFeeHistory.baseFeePerGas[index]),
924
+ gasUsedRatio: Number(rawFeeHistory.gasUsedRatio[index]),
925
+ priorityFeePerGas: rawFeeHistory.reward[index].map((x) => BigInt(x))
926
+ });
927
+ blockNum += 1;
928
+ index += 1;
929
+ }
930
+ const percentilePriorityFeeAverages = [];
931
+ for (let i = 0; i < optionsResolved.rewardPercentiles.length; i++) {
932
+ percentilePriorityFeeAverages.push(avg(blocksHistory.map((b) => b.priorityFeePerGas[i])));
933
+ }
934
+ const baseFeePerGas = BigInt(rawFeeHistory.baseFeePerGas[rawFeeHistory.baseFeePerGas.length - 1]);
935
+ const result = [];
936
+ for (let i = 0; i < optionsResolved.rewardPercentiles.length; i++) {
937
+ result.push({
938
+ maxFeePerGas: percentilePriorityFeeAverages[i] + baseFeePerGas,
939
+ maxPriorityFeePerGas: percentilePriorityFeeAverages[i]
940
+ });
941
+ }
942
+ return result;
943
+ }
944
+ async function getRoughGasPriceEstimate(provider, options) {
945
+ const defaultOptions = {
946
+ blockCount: 20,
947
+ newestBlock: "pending",
948
+ rewardPercentiles: [10, 50, 80]
949
+ };
950
+ const optionsResolved = options ? { ...defaultOptions, ...options } : defaultOptions;
951
+ if (optionsResolved.rewardPercentiles.length !== 3) {
952
+ throw new Error(`rough gas estimate require 3 percentile, it defaults to [10,50,80]`);
953
+ }
954
+ const result = await getGasPriceEstimate(provider, optionsResolved);
955
+ return {
956
+ slow: result[0],
957
+ average: result[1],
958
+ fast: result[2]
959
+ };
960
+ }
961
+
873
962
  // src/executor/index.ts
963
+ import prompts from "prompts";
964
+ import { formatEther } from "viem";
874
965
  if (!process.env["ROCKETH_SKIP_ESBUILD"]) {
875
966
  __require("esbuild-register/dist/node").register();
876
967
  }
@@ -952,7 +1043,9 @@ function readConfig(options) {
952
1043
  saveDeployments: options.saveDeployments,
953
1044
  scripts: options.scripts,
954
1045
  tags: typeof options.tags === "undefined" ? void 0 : options.tags.split(","),
955
- logLevel: options.logLevel
1046
+ logLevel: options.logLevel,
1047
+ askBeforeProceeding: options.askBeforeProceeding,
1048
+ reportGasUse: options.reportGasUse
956
1049
  };
957
1050
  } else {
958
1051
  return {
@@ -966,7 +1059,9 @@ function readConfig(options) {
966
1059
  saveDeployments: options.saveDeployments,
967
1060
  scripts: options.scripts,
968
1061
  tags: typeof options.tags === "undefined" ? void 0 : options.tags.split(","),
969
- logLevel: options.logLevel
1062
+ logLevel: options.logLevel,
1063
+ askBeforeProceeding: options.askBeforeProceeding,
1064
+ reportGasUse: options.reportGasUse
970
1065
  };
971
1066
  }
972
1067
  }
@@ -1111,6 +1206,28 @@ async function executeDeployScripts(config, args) {
1111
1206
  for (const scriptFilePath of scriptFilePaths) {
1112
1207
  recurseDependencies(scriptFilePath);
1113
1208
  }
1209
+ if (config.askBeforeProceeding) {
1210
+ const gasPriceEstimate = await getRoughGasPriceEstimate(external.network.provider);
1211
+ const prompt = await prompts({
1212
+ type: "confirm",
1213
+ name: "proceed",
1214
+ message: `gas price is currently in this range:
1215
+ slow: ${formatEther(gasPriceEstimate.slow.maxFeePerGas)} (priority: ${formatEther(
1216
+ gasPriceEstimate.slow.maxPriorityFeePerGas
1217
+ )})
1218
+ average: ${formatEther(gasPriceEstimate.average.maxFeePerGas)} (priority: ${formatEther(
1219
+ gasPriceEstimate.average.maxPriorityFeePerGas
1220
+ )})
1221
+ fast: ${formatEther(gasPriceEstimate.fast.maxFeePerGas)} (priority: ${formatEther(
1222
+ gasPriceEstimate.fast.maxPriorityFeePerGas
1223
+ )})
1224
+
1225
+ Do you want to proceed (note that gas price can change for each tx)`
1226
+ });
1227
+ if (!prompt.proceed) {
1228
+ process.exit();
1229
+ }
1230
+ }
1114
1231
  for (const deployScript of scriptsToRun.concat(scriptsToRunAtTheEnd)) {
1115
1232
  const filename = path4.basename(deployScript.filePath);
1116
1233
  const relativeFilepath = path4.relative(".", deployScript.filePath);
@@ -1141,6 +1258,19 @@ async function executeDeployScripts(config, args) {
1141
1258
  }
1142
1259
  }
1143
1260
  }
1261
+ if (config.reportGasUse) {
1262
+ const provider = external.network.provider;
1263
+ const transactionHashes = provider.transactionHashes;
1264
+ let totalGasUsed = 0;
1265
+ for (const hash of transactionHashes) {
1266
+ const transactionReceipt = await provider.request({ method: "eth_getTransactionReceipt", params: [hash] });
1267
+ if (transactionReceipt) {
1268
+ const gasUsed = Number(transactionReceipt.gasUsed);
1269
+ totalGasUsed += gasUsed;
1270
+ }
1271
+ }
1272
+ console.log({ totalGasUsed });
1273
+ }
1144
1274
  return external;
1145
1275
  }
1146
1276
 
@@ -1159,4 +1289,4 @@ export {
1159
1289
  loadAndExecuteDeployments,
1160
1290
  executeDeployScripts
1161
1291
  };
1162
- //# sourceMappingURL=chunk-4RQLWJEN.js.map
1292
+ //# sourceMappingURL=chunk-5GXGLCHC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/fs.ts","../src/executor/index.ts","../src/environment/index.ts","../src/utils/json.ts","../src/environment/deployments.ts","../src/internal/logging.ts","../src/environment/utils/chains.ts","../src/environment/utils/artifacts.ts","../src/environment/providers/BaseProvider.ts","../src/environment/providers/TransactionHashTracker.ts","../src/utils/eth.ts"],"sourcesContent":["// taken from https://github.com/vitejs/vite/blob/63524bac878e8d3771d34ad7ad2e10cd16870ff4/packages/vite/src/node/utils.ts#L371-L400\nimport fs from 'node:fs';\nimport path from 'node:path';\n\ninterface LookupFileOptions {\n\tpathOnly?: boolean;\n\trootDir?: string;\n\tpredicate?: (file: string) => boolean;\n}\n\nexport function lookupFile(dir: string, formats: string[], options?: LookupFileOptions): string | undefined {\n\tfor (const format of formats) {\n\t\tconst fullPath = path.join(dir, format);\n\t\tif (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {\n\t\t\tconst result = options?.pathOnly ? fullPath : fs.readFileSync(fullPath, 'utf-8');\n\t\t\tif (!options?.predicate || options.predicate(result)) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t}\n\tconst parentDir = path.dirname(dir);\n\tif (parentDir !== dir && (!options?.rootDir || parentDir.startsWith(options?.rootDir))) {\n\t\treturn lookupFile(parentDir, formats, options);\n\t}\n}\n\nexport function traverseMultipleDirectory(dirs: string[]): string[] {\n\tconst filepaths = [];\n\tfor (const dir of dirs) {\n\t\tlet filesStats = traverse(dir);\n\t\tfilesStats = filesStats.filter((v) => !v.directory);\n\t\tfor (const filestat of filesStats) {\n\t\t\tfilepaths.push(path.join(dir, filestat.relativePath));\n\t\t}\n\t}\n\treturn filepaths;\n}\n\nexport const traverse = function (\n\tdir: string,\n\tresult: any[] = [],\n\ttopDir?: string,\n\tfilter?: (name: string, stats: any) => boolean // TODO any is Stats\n): Array<{\n\tname: string;\n\tpath: string;\n\trelativePath: string;\n\tmtimeMs: number;\n\tdirectory: boolean;\n}> {\n\tfs.readdirSync(dir).forEach((name) => {\n\t\tconst fPath = path.resolve(dir, name);\n\t\tconst stats = fs.statSync(fPath);\n\t\tif ((!filter && !name.startsWith('.')) || (filter && filter(name, stats))) {\n\t\t\tconst fileStats = {\n\t\t\t\tname,\n\t\t\t\tpath: fPath,\n\t\t\t\trelativePath: path.relative(topDir || dir, fPath),\n\t\t\t\tmtimeMs: stats.mtimeMs,\n\t\t\t\tdirectory: stats.isDirectory(),\n\t\t\t};\n\t\t\tif (fileStats.directory) {\n\t\t\t\tresult.push(fileStats);\n\t\t\t\treturn traverse(fPath, result, topDir || dir, filter);\n\t\t\t}\n\t\t\tresult.push(fileStats);\n\t\t}\n\t});\n\treturn result;\n};\n","import {traverseMultipleDirectory} from '../utils/fs';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport type {\n\tConfig,\n\tEnvironment,\n\tResolvedConfig,\n\tResolvedNamedAccounts,\n\tUnknownArtifacts,\n\tUnknownDeployments,\n\tUnresolvedUnknownNamedAccounts,\n} from '../environment/types';\nimport {createEnvironment} from '../environment';\nimport {DeployScriptFunction, DeployScriptModule, ProvidedContext} from './types';\nimport {logger, setLogLevel, spin} from '../internal/logging';\nimport {EIP1193GenericRequestProvider, EIP1193ProviderWithoutEvents} from 'eip-1193';\nimport {getRoughGasPriceEstimate} from '../utils/eth';\nimport prompts from 'prompts';\nimport {formatEther} from 'viem';\n\nif (!process.env['ROCKETH_SKIP_ESBUILD']) {\n\trequire('esbuild-register/dist/node').register();\n}\n\nexport function execute<\n\tArtifacts extends UnknownArtifacts = UnknownArtifacts,\n\tNamedAccounts extends UnresolvedUnknownNamedAccounts = UnresolvedUnknownNamedAccounts,\n\tArgumentsType = undefined,\n\tDeployments extends UnknownDeployments = UnknownDeployments\n>(\n\tcontext: ProvidedContext<Artifacts, NamedAccounts>,\n\tcallback: DeployScriptFunction<Artifacts, ResolvedNamedAccounts<NamedAccounts>, ArgumentsType, Deployments>,\n\toptions: {tags?: string[]; dependencies?: string[]}\n): DeployScriptModule<Artifacts, NamedAccounts, ArgumentsType, Deployments> {\n\tconst scriptModule = (\n\t\tenv: Environment<Artifacts, ResolvedNamedAccounts<NamedAccounts>, Deployments>,\n\t\targs?: ArgumentsType\n\t) => callback(env, args);\n\tscriptModule.providedContext = context;\n\tscriptModule.tags = options.tags;\n\tscriptModule.dependencies = options.dependencies;\n\t// TODO id + skip\n\treturn scriptModule as unknown as DeployScriptModule<Artifacts, NamedAccounts, ArgumentsType, Deployments>;\n}\n\nexport type ConfigOptions = {\n\tnetwork?: string | {fork: string};\n\tdeployments?: string;\n\tscripts?: string;\n\ttags?: string;\n\tlogLevel?: number;\n\tprovider?: EIP1193ProviderWithoutEvents | EIP1193GenericRequestProvider;\n\tignoreMissingRPC?: boolean;\n\tsaveDeployments?: boolean;\n\taskBeforeProceeding?: boolean;\n\treportGasUse?: boolean;\n};\n\nexport function readConfig(options: ConfigOptions): Config {\n\ttype Networks = {[name: string]: {rpcUrl?: string; tags?: string[]}};\n\ttype ConfigFile = {networks: Networks; deployments?: string; scripts?: string};\n\tlet configFile: ConfigFile | undefined;\n\ttry {\n\t\tconst configString = fs.readFileSync('./rocketh.json', 'utf-8');\n\t\tconfigFile = JSON.parse(configString);\n\t} catch {}\n\n\tif (configFile) {\n\t\tif (!options.deployments && configFile.deployments) {\n\t\t\toptions.deployments = configFile.deployments;\n\t\t}\n\t\tif (!options.scripts && configFile.scripts) {\n\t\t\toptions.scripts = configFile.scripts;\n\t\t}\n\t}\n\n\tconst fromEnv = process.env['ETH_NODE_URI_' + options.network];\n\tconst fork = typeof options.network !== 'string';\n\tlet networkName = 'memory';\n\tif (options.network) {\n\t\tif (typeof options.network === 'string') {\n\t\t\tnetworkName = options.network;\n\t\t} else if ('fork' in options.network) {\n\t\t\tnetworkName = options.network.fork;\n\t\t}\n\t}\n\n\tlet networkTags: string[] = (configFile?.networks && configFile?.networks[networkName]?.tags) || [];\n\tif (!options.provider) {\n\t\tlet nodeUrl: string;\n\t\tif (typeof fromEnv === 'string') {\n\t\t\tnodeUrl = fromEnv;\n\t\t} else {\n\t\t\tif (configFile) {\n\t\t\t\tconst network = configFile.networks && configFile.networks[networkName];\n\t\t\t\tif (network && network.rpcUrl) {\n\t\t\t\t\tnodeUrl = network.rpcUrl;\n\t\t\t\t} else {\n\t\t\t\t\tif (options?.ignoreMissingRPC) {\n\t\t\t\t\t\tnodeUrl = '';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (options.network === 'localhost') {\n\t\t\t\t\t\t\tnodeUrl = 'http://127.0.0.1:8545';\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlogger.error(`network \"${options.network}\" is not configured. Please add it to the rocketh.json file`);\n\t\t\t\t\t\t\tprocess.exit(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (options?.ignoreMissingRPC) {\n\t\t\t\t\tnodeUrl = '';\n\t\t\t\t} else {\n\t\t\t\t\tif (options.network === 'localhost') {\n\t\t\t\t\t\tnodeUrl = 'http://127.0.0.1:8545';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.error(`network \"${options.network}\" is not configured. Please add it to the rocketh.json file`);\n\t\t\t\t\t\tprocess.exit(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tnetwork: {\n\t\t\t\tnodeUrl,\n\t\t\t\tname: networkName,\n\t\t\t\ttags: networkTags,\n\t\t\t\tfork,\n\t\t\t},\n\t\t\tdeployments: options.deployments,\n\t\t\tsaveDeployments: options.saveDeployments,\n\t\t\tscripts: options.scripts,\n\t\t\ttags: typeof options.tags === 'undefined' ? undefined : options.tags.split(','),\n\t\t\tlogLevel: options.logLevel,\n\t\t\taskBeforeProceeding: options.askBeforeProceeding,\n\t\t\treportGasUse: options.reportGasUse,\n\t\t};\n\t} else {\n\t\treturn {\n\t\t\tnetwork: {\n\t\t\t\tprovider: options.provider as EIP1193ProviderWithoutEvents,\n\t\t\t\tname: networkName,\n\t\t\t\ttags: networkTags,\n\t\t\t\tfork,\n\t\t\t},\n\t\t\tdeployments: options.deployments,\n\t\t\tsaveDeployments: options.saveDeployments,\n\t\t\tscripts: options.scripts,\n\t\t\ttags: typeof options.tags === 'undefined' ? undefined : options.tags.split(','),\n\t\t\tlogLevel: options.logLevel,\n\t\t\taskBeforeProceeding: options.askBeforeProceeding,\n\t\t\treportGasUse: options.reportGasUse,\n\t\t};\n\t}\n}\n\nexport function readAndResolveConfig(options: ConfigOptions): ResolvedConfig {\n\treturn resolveConfig(readConfig(options));\n}\n\nexport function resolveConfig(config: Config): ResolvedConfig {\n\tconst resolvedConfig: ResolvedConfig = {\n\t\t...config,\n\t\tnetwork: config.network, // TODO default to || {name: 'memory'....}\n\t\tdeployments: config.deployments || 'deployments',\n\t\tscripts: config.scripts || 'deploy',\n\t\ttags: config.tags || [],\n\t\tnetworkTags: config.networkTags || [],\n\t\tsaveDeployments: config.saveDeployments,\n\t};\n\treturn resolvedConfig;\n}\n\nexport async function loadEnvironment<\n\tArtifacts extends UnknownArtifacts = UnknownArtifacts,\n\tNamedAccounts extends UnresolvedUnknownNamedAccounts = UnresolvedUnknownNamedAccounts\n>(options: ConfigOptions, context: ProvidedContext<Artifacts, NamedAccounts>): Promise<Environment> {\n\tconst resolvedConfig = readAndResolveConfig(options);\n\tconst {external, internal} = await createEnvironment(resolvedConfig, context);\n\treturn external;\n}\n\nexport async function loadAndExecuteDeployments<\n\tArtifacts extends UnknownArtifacts = UnknownArtifacts,\n\tNamedAccounts extends UnresolvedUnknownNamedAccounts = UnresolvedUnknownNamedAccounts,\n\tArgumentsType = undefined,\n\tDeployments extends UnknownDeployments = UnknownDeployments\n>(options: ConfigOptions, args?: ArgumentsType): Promise<Environment> {\n\tconst resolvedConfig = readAndResolveConfig(options);\n\t// console.log(JSON.stringify(options, null, 2));\n\t// console.log(JSON.stringify(resolvedConfig, null, 2));\n\treturn executeDeployScripts<Artifacts, NamedAccounts, ArgumentsType, Deployments>(resolvedConfig, args);\n}\n\nexport async function executeDeployScripts<\n\tArtifacts extends UnknownArtifacts = UnknownArtifacts,\n\tNamedAccounts extends UnresolvedUnknownNamedAccounts = UnresolvedUnknownNamedAccounts,\n\tArgumentsType = undefined,\n\tDeployments extends UnknownDeployments = UnknownDeployments\n>(config: ResolvedConfig, args?: ArgumentsType): Promise<Environment> {\n\tsetLogLevel(typeof config.logLevel === 'undefined' ? 0 : config.logLevel);\n\n\tlet filepaths;\n\tfilepaths = traverseMultipleDirectory([config.scripts]);\n\tfilepaths = filepaths\n\t\t.filter((v) => !path.basename(v).startsWith('_'))\n\t\t.sort((a: string, b: string) => {\n\t\t\tif (a < b) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (a > b) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\treturn 0;\n\t\t});\n\n\tlet providedContext: ProvidedContext<Artifacts, NamedAccounts> | undefined;\n\n\tconst scriptModuleByFilePath: {[filename: string]: DeployScriptModule<Artifacts, NamedAccounts, ArgumentsType>} = {};\n\tconst scriptPathBags: {[tag: string]: string[]} = {};\n\tconst scriptFilePaths: string[] = [];\n\n\tfor (const filepath of filepaths) {\n\t\tconst scriptFilePath = path.resolve(filepath);\n\t\tlet scriptModule: DeployScriptModule<Artifacts, NamedAccounts, ArgumentsType>;\n\t\ttry {\n\t\t\tif (require.cache) {\n\t\t\t\tdelete require.cache[scriptFilePath]; // ensure we reload it every time, so changes are taken in consideration\n\t\t\t}\n\t\t\tscriptModule = require(scriptFilePath);\n\n\t\t\tif ((scriptModule as any).default) {\n\t\t\t\tscriptModule = (scriptModule as any).default as DeployScriptModule<Artifacts, NamedAccounts, ArgumentsType>;\n\t\t\t\tif ((scriptModule as any).default) {\n\t\t\t\t\tlogger.warn(`double default...`);\n\t\t\t\t\tscriptModule = (scriptModule as any).default as DeployScriptModule<Artifacts, NamedAccounts, ArgumentsType>;\n\t\t\t\t}\n\t\t\t}\n\t\t\tscriptModuleByFilePath[scriptFilePath] = scriptModule;\n\t\t\tif (providedContext && providedContext !== scriptModule.providedContext) {\n\t\t\t\tthrow new Error(`context between 2 scripts is different, please share the same across them`);\n\t\t\t}\n\t\t\tprovidedContext = scriptModule.providedContext as ProvidedContext<Artifacts, NamedAccounts>;\n\t\t} catch (e) {\n\t\t\tlogger.error(`could not import ${filepath}`);\n\t\t\tthrow e;\n\t\t}\n\n\t\tlet scriptTags = scriptModule.tags;\n\t\tif (scriptTags !== undefined) {\n\t\t\tif (typeof scriptTags === 'string') {\n\t\t\t\tscriptTags = [scriptTags];\n\t\t\t}\n\t\t\tfor (const tag of scriptTags) {\n\t\t\t\tif (tag.indexOf(',') >= 0) {\n\t\t\t\t\tthrow new Error('Tag cannot contains commas');\n\t\t\t\t}\n\t\t\t\tconst bag = scriptPathBags[tag] || [];\n\t\t\t\tscriptPathBags[tag] = bag;\n\t\t\t\tbag.push(scriptFilePath);\n\t\t\t}\n\t\t}\n\n\t\tif (config.tags !== undefined && config.tags.length > 0) {\n\t\t\tlet found = false;\n\t\t\tif (scriptTags !== undefined) {\n\t\t\t\tfor (const tagToFind of config.tags) {\n\t\t\t\t\tfor (const tag of scriptTags) {\n\t\t\t\t\t\tif (tag === tagToFind) {\n\t\t\t\t\t\t\tscriptFilePaths.push(scriptFilePath);\n\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (found) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tscriptFilePaths.push(scriptFilePath);\n\t\t}\n\t}\n\n\tif (!providedContext) {\n\t\tthrow new Error(`no context loaded`);\n\t}\n\n\tconst {internal, external} = await createEnvironment(config, providedContext);\n\n\tawait internal.recoverTransactionsIfAny();\n\n\tconst scriptsRegisteredToRun: {[filename: string]: boolean} = {};\n\tconst scriptsToRun: Array<{\n\t\tfunc: DeployScriptModule<Artifacts, NamedAccounts, ArgumentsType>;\n\t\tfilePath: string;\n\t}> = [];\n\tconst scriptsToRunAtTheEnd: Array<{\n\t\tfunc: DeployScriptModule<Artifacts, NamedAccounts, ArgumentsType>;\n\t\tfilePath: string;\n\t}> = [];\n\tfunction recurseDependencies(scriptFilePath: string) {\n\t\tif (scriptsRegisteredToRun[scriptFilePath]) {\n\t\t\treturn;\n\t\t}\n\t\tconst scriptModule = scriptModuleByFilePath[scriptFilePath];\n\t\tif (scriptModule.dependencies) {\n\t\t\tfor (const dependency of scriptModule.dependencies) {\n\t\t\t\tconst scriptFilePathsToAdd = scriptPathBags[dependency];\n\t\t\t\tif (scriptFilePathsToAdd) {\n\t\t\t\t\tfor (const scriptFilenameToAdd of scriptFilePathsToAdd) {\n\t\t\t\t\t\trecurseDependencies(scriptFilenameToAdd);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!scriptsRegisteredToRun[scriptFilePath]) {\n\t\t\tif (scriptModule.runAtTheEnd) {\n\t\t\t\tscriptsToRunAtTheEnd.push({\n\t\t\t\t\tfilePath: scriptFilePath,\n\t\t\t\t\tfunc: scriptModule,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tscriptsToRun.push({\n\t\t\t\t\tfilePath: scriptFilePath,\n\t\t\t\t\tfunc: scriptModule,\n\t\t\t\t});\n\t\t\t}\n\t\t\tscriptsRegisteredToRun[scriptFilePath] = true;\n\t\t}\n\t}\n\tfor (const scriptFilePath of scriptFilePaths) {\n\t\trecurseDependencies(scriptFilePath);\n\t}\n\n\tif (config.askBeforeProceeding) {\n\t\tconst gasPriceEstimate = await getRoughGasPriceEstimate(external.network.provider);\n\t\tconst prompt = await prompts({\n\t\t\ttype: 'confirm',\n\t\t\tname: 'proceed',\n\t\t\tmessage: `gas price is currently in this range:\nslow: ${formatEther(gasPriceEstimate.slow.maxFeePerGas)} (priority: ${formatEther(\n\t\t\t\tgasPriceEstimate.slow.maxPriorityFeePerGas\n\t\t\t)})\naverage: ${formatEther(gasPriceEstimate.average.maxFeePerGas)} (priority: ${formatEther(\n\t\t\t\tgasPriceEstimate.average.maxPriorityFeePerGas\n\t\t\t)})\nfast: ${formatEther(gasPriceEstimate.fast.maxFeePerGas)} (priority: ${formatEther(\n\t\t\t\tgasPriceEstimate.fast.maxPriorityFeePerGas\n\t\t\t)})\n \nDo you want to proceed (note that gas price can change for each tx)`,\n\t\t});\n\n\t\tif (!prompt.proceed) {\n\t\t\tprocess.exit();\n\t\t}\n\t}\n\n\tfor (const deployScript of scriptsToRun.concat(scriptsToRunAtTheEnd)) {\n\t\tconst filename = path.basename(deployScript.filePath);\n\t\tconst relativeFilepath = path.relative('.', deployScript.filePath);\n\t\t// if (deployScript.func.id && this.db.migrations[deployScript.func.id]) {\n\t\t// \tlogger.info(`skipping ${filename} as migrations already executed and complete`);\n\t\t// \tcontinue;\n\t\t// }\n\t\tlet skip = false;\n\t\tconst spinner = spin(`- Executing ${filename}`);\n\t\tif (deployScript.func.skip) {\n\t\t\tconst spinner = spin(` - skip?()`);\n\t\t\ttry {\n\t\t\t\tskip = await deployScript.func.skip(external, args);\n\t\t\t\tspinner.succeed(skip ? `skipping ${filename}` : undefined);\n\t\t\t} catch (e) {\n\t\t\t\tspinner.fail();\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\tif (!skip) {\n\t\t\tlet result;\n\n\t\t\ttry {\n\t\t\t\tresult = await deployScript.func(external, args);\n\t\t\t\tspinner.succeed(`\\n`);\n\t\t\t} catch (e) {\n\t\t\t\tspinner.fail();\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tif (result && typeof result === 'boolean') {\n\t\t\t\t// if (!deployScript.func.id) {\n\t\t\t\t// \tthrow new Error(\n\t\t\t\t// \t\t`${deployScript.filePath} return true to not be executed again, but does not provide an id. the script function needs to have the field \"id\" to be set`\n\t\t\t\t// \t);\n\t\t\t\t// }\n\t\t\t\t// this.db.migrations[deployScript.func.id] = Math.floor(Date.now() / 1000);\n\n\t\t\t\tconst deploymentFolderPath = config.deployments;\n\n\t\t\t\t// TODO refactor to extract this whole path and folder existence stuff\n\t\t\t\t// const toSave = this.db.writeDeploymentsToFiles && this.network.saveDeployments;\n\t\t\t\t// if (toSave) {\n\t\t\t\t// \ttry {\n\t\t\t\t// \t\tfs.mkdirSync(this.deploymentsPath);\n\t\t\t\t// \t} catch (e) {}\n\t\t\t\t// \ttry {\n\t\t\t\t// \t\tfs.mkdirSync(path.join(this.deploymentsPath, deploymentFolderPath));\n\t\t\t\t// \t} catch (e) {}\n\t\t\t\t// \tfs.writeFileSync(\n\t\t\t\t// \t\tpath.join(this.deploymentsPath, deploymentFolderPath, '.migrations.json'),\n\t\t\t\t// \t\tJSON.stringify(this.db.migrations, null, ' ')\n\t\t\t\t// \t);\n\t\t\t\t// }\n\t\t\t}\n\t\t}\n\t}\n\n\tif (config.reportGasUse) {\n\t\tconst provider = external.network.provider;\n\t\tconst transactionHashes = provider.transactionHashes;\n\n\t\tlet totalGasUsed = 0;\n\t\tfor (const hash of transactionHashes) {\n\t\t\tconst transactionReceipt = await provider.request({method: 'eth_getTransactionReceipt', params: [hash]});\n\t\t\tif (transactionReceipt) {\n\t\t\t\tconst gasUsed = Number(transactionReceipt.gasUsed);\n\t\t\t\ttotalGasUsed += gasUsed;\n\t\t\t}\n\t\t}\n\n\t\tconsole.log({totalGasUsed});\n\t}\n\n\treturn external;\n}\n","import fs from 'node:fs';\n\nimport {TransactionReceipt, createPublicClient, custom} from 'viem';\n\nimport {\n\tAccountType,\n\tArtifact,\n\tDeployment,\n\tEnvironment,\n\tNamedSigner,\n\tPendingDeployment,\n\tPendingTransaction,\n\tResolvedAccount,\n\tResolvedConfig,\n\tResolvedNamedAccounts,\n\tResolvedNamedSigners,\n\tUnknownArtifacts,\n\tUnknownDeployments,\n\tUnresolvedUnknownNamedAccounts,\n} from './types';\nimport {JSONRPCHTTPProvider} from 'eip-1193-jsonrpc-provider';\nimport {Abi, Address} from 'abitype';\nimport {InternalEnvironment} from '../internal/types';\nimport path from 'node:path';\nimport {JSONToString, stringToJSON} from '../utils/json';\nimport {loadDeployments} from './deployments';\nimport {\n\tEIP1193Account,\n\tEIP1193DATA,\n\tEIP1193ProviderWithoutEvents,\n\tEIP1193QUANTITY,\n\tEIP1193Transaction,\n\tEIP1193TransactionReceipt,\n} from 'eip-1193';\nimport {ProvidedContext} from '../executor/types';\nimport {ProgressIndicator, log, spin} from '../internal/logging';\nimport {PendingExecution} from './types';\nimport {getChain} from './utils/chains';\nimport {mergeArtifacts} from './utils/artifacts';\nimport {TransactionHashTracker} from './providers/TransactionHashTracker';\n\ntype ReceiptResult = {receipt: EIP1193TransactionReceipt; latestBlockNumber: EIP1193QUANTITY};\n\nexport type EnvironmentExtenstion = (env: Environment) => Environment;\n//we store this globally so this is not lost\n(globalThis as any).extensions = [];\nexport function extendEnvironment(extension: EnvironmentExtenstion): void {\n\t(globalThis as any).extensions.push(extension);\n}\n\nexport type SignerProtocolFunction = (protocolString: string) => Promise<NamedSigner>;\nexport type SignerProtocol = {\n\tgetSigner: SignerProtocolFunction;\n};\n\n//we store this globally so this is not lost\n(globalThis as any).signerProtocols = {};\nexport function handleSignerProtocol(protocol: string, getSigner: SignerProtocolFunction): void {\n\t(globalThis as any).signerProtocols[protocol] = {\n\t\tgetSigner,\n\t};\n}\n\nfunction wait(numSeconds: number): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tsetTimeout(resolve, numSeconds * 1000);\n\t});\n}\n\nfunction displayTransaction(transaction: EIP1193Transaction) {\n\tif (transaction.type === '0x2') {\n\t\treturn `(maxFeePerGas: ${BigInt(transaction.maxFeePerGas).toString()}, maxPriorityFeePerGas: ${BigInt(\n\t\t\ttransaction.maxPriorityFeePerGas\n\t\t).toString()})`;\n\t} else {\n\t\treturn `(gasPrice: ${BigInt(transaction.gasPrice).toString()})`;\n\t}\n}\n\nexport async function createEnvironment<\n\tArtifacts extends UnknownArtifacts = UnknownArtifacts,\n\tNamedAccounts extends UnresolvedUnknownNamedAccounts = UnresolvedUnknownNamedAccounts,\n\tDeployments extends UnknownDeployments = UnknownDeployments\n>(\n\tconfig: ResolvedConfig,\n\tprovidedContext: ProvidedContext<Artifacts, NamedAccounts>\n): Promise<{internal: InternalEnvironment; external: Environment<Artifacts, NamedAccounts, Deployments>}> {\n\tconst rawProvider =\n\t\t'provider' in config.network\n\t\t\t? config.network.provider\n\t\t\t: (new JSONRPCHTTPProvider(config.network.nodeUrl) as EIP1193ProviderWithoutEvents);\n\n\tconst provider = new TransactionHashTracker(rawProvider);\n\n\tconst transport = custom(provider);\n\tconst viemClient = createPublicClient({transport});\n\n\tconst chainId = (await viemClient.getChainId()).toString();\n\tlet genesisHash: `0x${string}` | undefined;\n\ttry {\n\t\tgenesisHash = (await viemClient.getBlock({blockTag: 'earliest'})).hash;\n\t} catch (err) {\n\t\tconsole.error(`failed to get genesis hash`);\n\t}\n\n\tlet networkName: string;\n\tlet saveDeployments: boolean;\n\tlet networkTags: {[tag: string]: boolean} = {};\n\tfor (const networkTag of config.network.tags) {\n\t\tnetworkTags[networkTag] = true;\n\t}\n\n\tif ('nodeUrl' in config) {\n\t\tnetworkName = config.network.name;\n\t\tsaveDeployments = true;\n\t} else {\n\t\tif (config.network.name) {\n\t\t\tnetworkName = config.network.name;\n\t\t} else {\n\t\t\tnetworkName = 'memory';\n\t\t}\n\t\tif (networkName === 'memory' || networkName === 'hardhat') {\n\t\t\tnetworkTags['memory'] = true;\n\t\t\tsaveDeployments = false;\n\t\t} else {\n\t\t\tsaveDeployments = true;\n\t\t}\n\t}\n\n\tif (config.saveDeployments !== undefined) {\n\t\tsaveDeployments = config.saveDeployments;\n\t}\n\n\tconst resolvedAccounts: {[name: string]: ResolvedAccount} = {};\n\n\tconst accountCache: {[name: string]: ResolvedAccount} = {};\n\tasync function getAccount(\n\t\tname: string,\n\t\taccounts: UnresolvedUnknownNamedAccounts,\n\t\taccountDef: AccountType\n\t): Promise<ResolvedAccount | undefined> {\n\t\tif (accountCache[name]) {\n\t\t\treturn accountCache[name];\n\t\t}\n\t\tlet account: ResolvedAccount | undefined;\n\t\tif (typeof accountDef === 'number') {\n\t\t\tconst accounts = await provider.request({method: 'eth_accounts'});\n\t\t\tconst accountPerIndex = accounts[accountDef];\n\t\t\tif (accountPerIndex) {\n\t\t\t\taccountCache[name] = account = {\n\t\t\t\t\ttype: 'remote',\n\t\t\t\t\taddress: accountPerIndex,\n\t\t\t\t\tsigner: provider,\n\t\t\t\t};\n\t\t\t}\n\t\t} else if (typeof accountDef === 'string') {\n\t\t\tif (accountDef.startsWith('0x')) {\n\t\t\t\tif (accountDef.length === 66) {\n\t\t\t\t\tconst privateKeyProtocol: SignerProtocol = (globalThis as any).signerProtocols['privateKey'];\n\t\t\t\t\tif (privateKeyProtocol) {\n\t\t\t\t\t\tconst namedSigner = await privateKeyProtocol.getSigner(`privateKey:${accountDef}`);\n\t\t\t\t\t\tconst [address] = await namedSigner.signer.request({method: 'eth_accounts'});\n\t\t\t\t\t\taccountCache[name] = account = {\n\t\t\t\t\t\t\t...namedSigner,\n\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\taccountCache[name] = account = {\n\t\t\t\t\t\ttype: 'remote',\n\t\t\t\t\t\taddress: accountDef as `0x${string}`,\n\t\t\t\t\t\tsigner: provider,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (accountDef.indexOf(':') > 0) {\n\t\t\t\t\tconst [protocolID, extra] = accountDef.split(':');\n\t\t\t\t\tconst protocol: SignerProtocol = (globalThis as any).signerProtocols[protocolID];\n\t\t\t\t\tif (!protocol) {\n\t\t\t\t\t\tthrow new Error(`protocol: ${protocol} is not supported`);\n\t\t\t\t\t}\n\t\t\t\t\tconst namedSigner = await protocol.getSigner(accountDef);\n\t\t\t\t\tconst [address] = await namedSigner.signer.request({method: 'eth_accounts'});\n\t\t\t\t\taccountCache[name] = account = {\n\t\t\t\t\t\t...namedSigner,\n\t\t\t\t\t\taddress,\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\tconst accountFetched = await getAccount(name, accounts, accounts[accountDef]);\n\t\t\t\t\tif (accountFetched) {\n\t\t\t\t\t\taccountCache[name] = account = accountFetched;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tconst accountForNetwork = accountDef[networkName] || accountDef[chainId] || accountDef['default'];\n\t\t\tif (typeof accountForNetwork !== undefined) {\n\t\t\t\tconst accountFetched = await getAccount(name, accounts, accountForNetwork);\n\t\t\t\tif (accountFetched) {\n\t\t\t\t\taccountCache[name] = account = accountFetched;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn account;\n\t}\n\n\tif (providedContext.accounts) {\n\t\tconst accountNames = Object.keys(providedContext.accounts);\n\t\tfor (const accountName of accountNames) {\n\t\t\tlet account = await getAccount(accountName, providedContext.accounts, providedContext.accounts[accountName]);\n\t\t\t(resolvedAccounts as any)[accountName] = account;\n\t\t}\n\t}\n\n\tconst context = {\n\t\taccounts: resolvedAccounts,\n\t\tartifacts: providedContext.artifacts as Artifacts,\n\t\tnetwork: {\n\t\t\tname: networkName,\n\t\t\tfork: config.network.fork,\n\t\t\tsaveDeployments,\n\t\t\ttags: networkTags,\n\t\t},\n\t};\n\n\t// console.log(`context`, JSON.stringify(context.network, null, 2));\n\n\tconst {deployments} = loadDeployments(\n\t\tconfig.deployments,\n\t\tcontext.network.name,\n\t\tfalse,\n\t\tcontext.network.fork\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\tchainId,\n\t\t\t\t\tgenesisHash,\n\t\t\t\t\tdeleteDeploymentsIfDifferentGenesisHash: true,\n\t\t\t }\n\t);\n\n\tconst namedAccounts: {[name: string]: EIP1193Account} = {};\n\tconst namedSigners: {[name: string]: NamedSigner} = {};\n\tconst addressSigners: {[name: `0x${string}`]: NamedSigner} = {};\n\n\tfor (const entry of Object.entries(resolvedAccounts)) {\n\t\tconst name = entry[0];\n\t\tconst {address, ...namedSigner} = entry[1];\n\t\tnamedAccounts[name] = address;\n\t\taddressSigners[address] = namedSigner;\n\t\tnamedSigners[name] = namedSigner;\n\t}\n\n\tconst perliminaryEnvironment = {\n\t\tconfig,\n\t\tdeployments: deployments as Deployments,\n\t\taccounts: namedAccounts as ResolvedNamedAccounts<NamedAccounts>,\n\t\tsigners: namedSigners as ResolvedNamedSigners<ResolvedNamedAccounts<NamedAccounts>>,\n\t\taddressSigners: addressSigners,\n\t\tartifacts: context.artifacts,\n\t\tnetwork: {\n\t\t\tchain: getChain(chainId),\n\t\t\tname: context.network.name,\n\t\t\ttags: context.network.tags,\n\t\t\tprovider,\n\t\t},\n\t};\n\n\tfunction ensureDeploymentFolder(): string {\n\t\tconst folderPath = path.join(config.deployments, context.network.name);\n\t\tfs.mkdirSync(folderPath, {recursive: true});\n\t\t// const chainIdFilepath = path.join(folderPath, '.chainId');\n\t\t// if (!fs.existsSync(chainIdFilepath)) {\n\t\t// \tfs.writeFileSync(chainIdFilepath, chainId);\n\t\t// }\n\t\tconst chainFilepath = path.join(folderPath, '.chain');\n\t\tif (!fs.existsSync(chainFilepath)) {\n\t\t\tfs.writeFileSync(chainFilepath, JSON.stringify({chainId, genesisHash}));\n\t\t}\n\t\treturn folderPath;\n\t}\n\n\t// const signer = {\n\t// \tasync sendTransaction(\n\t// \t\tprovider: EIP1193ProviderWithoutEvents,\n\t// \t\taccount: {\n\t// \t\t\taddresss: EIP1193Account;\n\t// \t\t\tconfig: unknown;\n\t// \t\t},\n\t// \t\ttransaction: EIP1193TransactionEIP1193DATA\n\t// \t): Promise<EIP1193DATA> {\n\t// \t\treturn '0x';\n\t// \t},\n\t// };\n\n\t// async function sendTransaction(transaction: EIP1193TransactionEIP1193DATA): Promise<EIP1193DATA> {\n\t// \treturn '0x';\n\t// }\n\n\tfunction get<TAbi extends Abi>(name: string): Deployment<TAbi> {\n\t\tconst deployment = deployments[name] as Deployment<TAbi>;\n\t\tif (!deployment) {\n\t\t\tthrow new Error(`no deployment named \"${name}\" found.`);\n\t\t}\n\t\treturn deployment;\n\t}\n\n\tfunction getOrNull<TAbi extends Abi>(name: string): Deployment<TAbi> | null {\n\t\treturn (deployments[name] || null) as Deployment<TAbi> | null;\n\t}\n\n\tfunction fromAddressToNamedABIOrNull<TAbi extends Abi>(address: Address): {mergedABI: TAbi; names: string[]} | null {\n\t\tlet list: {name: string; artifact: Artifact<Abi>}[] = [];\n\t\tfor (const name of Object.keys(deployments)) {\n\t\t\tconst deployment = deployments[name];\n\t\t\tif (deployment.address.toLowerCase() == address.toLowerCase()) {\n\t\t\t\tlist.push({name, artifact: deployment});\n\t\t\t}\n\t\t}\n\t\tif (list.length === 0) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst {mergedABI} = mergeArtifacts(list);\n\t\treturn {\n\t\t\tmergedABI: mergedABI as unknown as TAbi,\n\t\t\tnames: list.map((v) => v.name),\n\t\t};\n\t}\n\n\tfunction fromAddressToNamedABI<TAbi extends Abi>(address: Address): {mergedABI: TAbi; names: string[]} {\n\t\tconst n = fromAddressToNamedABIOrNull<TAbi>(address);\n\t\tif (!n) {\n\t\t\tthrow new Error(`could not find artifact for address ${address}`);\n\t\t}\n\t\treturn n;\n\t}\n\n\tasync function save<TAbi extends Abi>(name: string, deployment: Deployment<TAbi>): Promise<Deployment<TAbi>> {\n\t\tdeployments[name] = deployment;\n\t\tif (context.network.saveDeployments) {\n\t\t\tconst folderPath = ensureDeploymentFolder();\n\t\t\tfs.writeFileSync(`${folderPath}/${name}.json`, JSONToString(deployment, 2));\n\t\t}\n\t\treturn deployment;\n\t}\n\n\tasync function recoverTransactionsIfAny<TAbi extends Abi = Abi>(): Promise<void> {\n\t\tif (!context.network.saveDeployments) {\n\t\t\treturn;\n\t\t}\n\t\tconst folderPath = ensureDeploymentFolder();\n\t\tconst filepath = path.join(folderPath, '.pending_transactions.json');\n\t\tlet existingPendingTansactions: PendingTransaction[];\n\t\ttry {\n\t\t\texistingPendingTansactions = stringToJSON(fs.readFileSync(filepath, 'utf-8'));\n\t\t} catch {\n\t\t\texistingPendingTansactions = [];\n\t\t}\n\t\tif (existingPendingTansactions.length > 0) {\n\t\t\twhile (existingPendingTansactions.length > 0) {\n\t\t\t\tconst pendingTransaction = existingPendingTansactions.shift();\n\t\t\t\tif (pendingTransaction) {\n\t\t\t\t\tif (pendingTransaction.type === 'deployment') {\n\t\t\t\t\t\tconst spinner = spin(\n\t\t\t\t\t\t\t`recovering ${pendingTransaction.name} with transaction ${pendingTransaction.transaction.hash}`\n\t\t\t\t\t\t);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait waitForDeploymentTransactionAndSave(pendingTransaction);\n\t\t\t\t\t\t\tfs.writeFileSync(filepath, JSONToString(existingPendingTansactions, 2));\n\t\t\t\t\t\t\tspinner.succeed();\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\tspinner.fail();\n\t\t\t\t\t\t\tthrow e;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst spinner = spin(`recovering execution's transaction ${pendingTransaction.transaction.hash}`);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait waitForTransaction(pendingTransaction.transaction.hash);\n\t\t\t\t\t\t\tfs.writeFileSync(filepath, JSONToString(existingPendingTansactions, 2));\n\t\t\t\t\t\t\tspinner.succeed();\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\tspinner.fail();\n\t\t\t\t\t\t\tthrow e;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfs.rmSync(filepath);\n\t\t}\n\t}\n\n\tasync function savePendingTransaction(pendingTransaction: PendingTransaction) {\n\t\tif (context.network.saveDeployments) {\n\t\t\tconst folderPath = ensureDeploymentFolder();\n\t\t\tconst filepath = path.join(folderPath, '.pending_transactions.json');\n\t\t\tlet existingPendinTransactions: PendingTransaction[];\n\t\t\ttry {\n\t\t\t\texistingPendinTransactions = stringToJSON(fs.readFileSync(filepath, 'utf-8'));\n\t\t\t} catch {\n\t\t\t\texistingPendinTransactions = [];\n\t\t\t}\n\t\t\texistingPendinTransactions.push(pendingTransaction);\n\t\t\tfs.writeFileSync(filepath, JSONToString(existingPendinTransactions, 2));\n\t\t}\n\t\treturn deployments;\n\t}\n\n\tasync function waitForTransactionReceipt(params: {\n\t\thash: EIP1193DATA;\n\t\t// confirmations?: number; // TODO\n\t\tpollingInterval?: number;\n\t\t// timeout?: number; // TODO\n\t}): Promise<ReceiptResult> {\n\t\t// const {hash, confirmations, pollingInterval, timeout} = {confirmations: 1, pollingInterval: 1, ...params};\n\t\tconst {hash, pollingInterval} = {pollingInterval: 1, ...params};\n\n\t\tlet latestBlockNumber = await provider.request({\n\t\t\tmethod: 'eth_blockNumber',\n\t\t});\n\n\t\tlet receipt = await provider.request({\n\t\t\tmethod: 'eth_getTransactionReceipt',\n\t\t\tparams: [hash],\n\t\t});\n\t\tif (!receipt || !receipt.blockHash) {\n\t\t\tawait wait(pollingInterval);\n\t\t\treturn waitForTransactionReceipt(params);\n\t\t}\n\t\treturn {receipt, latestBlockNumber};\n\t}\n\n\tasync function deleteTransaction<TAbi extends Abi = Abi>(hash: string) {\n\t\tif (context.network.saveDeployments) {\n\t\t\tconst folderPath = ensureDeploymentFolder();\n\t\t\tconst filepath = path.join(folderPath, '.pending_transactions.json');\n\t\t\tlet existingPendinTransactions: PendingTransaction[];\n\t\t\ttry {\n\t\t\t\texistingPendinTransactions = stringToJSON(fs.readFileSync(filepath, 'utf-8'));\n\t\t\t} catch {\n\t\t\t\texistingPendinTransactions = [];\n\t\t\t}\n\t\t\texistingPendinTransactions = existingPendinTransactions.filter((v) => v.transaction.hash !== hash);\n\t\t\tif (existingPendinTransactions.length === 0) {\n\t\t\t\tfs.rmSync(filepath);\n\t\t\t} else {\n\t\t\t\tfs.writeFileSync(filepath, JSONToString(existingPendinTransactions, 2));\n\t\t\t}\n\t\t}\n\t}\n\n\tasync function exportDeploymentsAsTypes() {\n\t\tconst folderPath = './generated';\n\t\tfs.mkdirSync(folderPath, {recursive: true});\n\t\tfs.writeFileSync(`${folderPath}/deployments.ts`, `export default ${JSONToString(deployments, 2)} as const;`);\n\t}\n\n\tasync function waitForTransaction(\n\t\thash: `0x${string}`,\n\t\tinfo?: {message?: string; transaction?: EIP1193Transaction | null}\n\t): Promise<ReceiptResult> {\n\t\tconst spinner = spin(\n\t\t\tinfo?.message\n\t\t\t\t? info.message\n\t\t\t\t: ` - Broadcasting tx:\\n ${hash}${\n\t\t\t\t\t\tinfo?.transaction ? `\\n ${displayTransaction(info?.transaction)}` : ''\n\t\t\t\t }`\n\t\t);\n\t\tlet receiptResult: {receipt: EIP1193TransactionReceipt; latestBlockNumber: EIP1193QUANTITY};\n\t\ttry {\n\t\t\treceiptResult = await waitForTransactionReceipt({\n\t\t\t\thash,\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tspinner.fail();\n\t\t\tthrow e;\n\t\t}\n\t\tif (!receiptResult) {\n\t\t\tthrow new Error(`receipt for ${hash} not found`);\n\t\t} else {\n\t\t\tspinner.succeed();\n\t\t}\n\t\treturn receiptResult;\n\t}\n\n\tasync function waitForDeploymentTransactionAndSave<TAbi extends Abi = Abi>(\n\t\tpendingDeployment: PendingDeployment<TAbi>,\n\t\ttransaction?: EIP1193Transaction | null\n\t): Promise<Deployment<TAbi>> {\n\t\tconst message = ` - Deploying ${pendingDeployment.name} with tx:\\n ${pendingDeployment.transaction.hash}${\n\t\t\ttransaction ? `\\n ${displayTransaction(transaction)}` : ''\n\t\t}`;\n\t\tconst {receipt, latestBlockNumber} = await waitForTransaction(pendingDeployment.transaction.hash, {\n\t\t\tmessage,\n\t\t\ttransaction,\n\t\t});\n\n\t\t// TODO we could make pendingDeployment.expectedAddress a spec for fetching address from event too\n\t\tconst contractAddress = pendingDeployment.expectedAddress || receipt.contractAddress;\n\t\tif (!contractAddress) {\n\t\t\tconsole.error(receipt);\n\t\t\tthrow new Error(`no contract address found for ${pendingDeployment.name}`);\n\t\t}\n\n\t\tshowMessage(` => ${contractAddress}`);\n\n\t\tconst {abi, ...artifactObjectWithoutABI} = pendingDeployment.partialDeployment;\n\n\t\tif (!pendingDeployment.transaction.hash) {\n\t\t\tconst spinner = spin(); // TODO spin(`fetching nonce for ${pendingDeployment.txHash}`);\n\t\t\tlet transaction: EIP1193Transaction | null = null;\n\t\t\ttry {\n\t\t\t\ttransaction = await provider.request({\n\t\t\t\t\tmethod: 'eth_getTransactionByHash',\n\t\t\t\t\tparams: [pendingDeployment.transaction.hash],\n\t\t\t\t});\n\t\t\t} catch (e) {\n\t\t\t\tspinner.fail();\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tif (!transaction) {\n\t\t\t\tspinner.fail(`tx ${pendingDeployment.transaction.hash} not found`);\n\t\t\t} else {\n\t\t\t\tspinner.stop();\n\t\t\t}\n\n\t\t\tif (transaction) {\n\t\t\t\tpendingDeployment.transaction = {\n\t\t\t\t\tnonce: transaction.nonce,\n\t\t\t\t\thash: transaction.hash,\n\t\t\t\t\torigin: transaction.from,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// TODO options\n\t\tfor (const key of Object.keys(artifactObjectWithoutABI)) {\n\t\t\tif (key.startsWith('_')) {\n\t\t\t\tdelete (artifactObjectWithoutABI as any)[key];\n\t\t\t}\n\t\t\tif (key === 'evm') {\n\t\t\t\tif (artifactObjectWithoutABI.evm) {\n\t\t\t\t\tif ('gasEstimates' in artifactObjectWithoutABI['evm']) {\n\t\t\t\t\t\tconst {gasEstimates} = artifactObjectWithoutABI.evm;\n\t\t\t\t\t\tartifactObjectWithoutABI.evm = {\n\t\t\t\t\t\t\tgasEstimates,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst latestBlockNumberAsNumber = parseInt(latestBlockNumber.slice(2), 16);\n\t\tconst receiptBlockNumber = parseInt(receipt.blockNumber.slice(2), 16);\n\t\tconst confirmations = Math.max(0, latestBlockNumberAsNumber - receiptBlockNumber);\n\n\t\tconst deployment = {\n\t\t\taddress: contractAddress,\n\t\t\tabi,\n\t\t\t...artifactObjectWithoutABI,\n\t\t\ttransaction: pendingDeployment.transaction,\n\t\t\treceipt: {\n\t\t\t\tconfirmations,\n\t\t\t\tblockHash: receipt.blockHash,\n\t\t\t\tblockNumber: receipt.blockNumber,\n\t\t\t\ttransactionIndex: receipt.transactionIndex,\n\t\t\t},\n\t\t};\n\t\treturn save(pendingDeployment.name, deployment);\n\t}\n\n\tasync function savePendingExecution(pendingExecution: PendingExecution) {\n\t\tawait savePendingTransaction(pendingExecution);\n\t\tlet transaction: EIP1193Transaction | null = null;\n\t\tconst spinner = spin(); // TODO spin(`fetching tx from peers ${pendingDeployment.txHash}`);\n\t\ttry {\n\t\t\ttransaction = await provider.request({\n\t\t\t\tmethod: 'eth_getTransactionByHash',\n\t\t\t\tparams: [pendingExecution.transaction.hash],\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tspinner.fail();\n\t\t\tthrow e;\n\t\t}\n\t\tif (!transaction) {\n\t\t\tspinner.fail(`tx ${pendingExecution.transaction.hash} not found`);\n\t\t} else {\n\t\t\tspinner.stop();\n\t\t}\n\n\t\tif (transaction) {\n\t\t\tpendingExecution.transaction.nonce = transaction.nonce;\n\t\t\tpendingExecution.transaction.origin = transaction.from;\n\t\t}\n\n\t\tconst {receipt} = await waitForTransaction(pendingExecution.transaction.hash, {transaction});\n\t\tawait deleteTransaction(pendingExecution.transaction.hash);\n\t\treturn receipt;\n\t}\n\n\tasync function savePendingDeployment<TAbi extends Abi = Abi>(pendingDeployment: PendingDeployment<TAbi>) {\n\t\tawait savePendingTransaction(pendingDeployment);\n\t\tlet transaction: EIP1193Transaction | null = null;\n\t\tconst spinner = spin(); // TODO spin(`fetching tx from peers ${pendingDeployment.txHash}`);\n\t\ttry {\n\t\t\ttransaction = await provider.request({\n\t\t\t\tmethod: 'eth_getTransactionByHash',\n\t\t\t\tparams: [pendingDeployment.transaction.hash],\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.error(`failed to fetch tx ${pendingDeployment.transaction.hash}. Can't know its status`);\n\t\t\tspinner.fail();\n\t\t\tthrow e;\n\t\t}\n\t\tif (!transaction) {\n\t\t\tspinner.fail(`tx ${pendingDeployment.transaction.hash} not found`);\n\t\t} else {\n\t\t\tspinner.stop();\n\t\t}\n\n\t\tif (transaction) {\n\t\t\t// we update the tx data with the one we get from the network\n\t\t\tpendingDeployment = {\n\t\t\t\t...pendingDeployment,\n\t\t\t\ttransaction: {hash: transaction.hash, nonce: transaction.nonce, origin: transaction.from},\n\t\t\t};\n\t\t}\n\n\t\tconst deployment = await waitForDeploymentTransactionAndSave<TAbi>(pendingDeployment, transaction);\n\t\tawait deleteTransaction(pendingDeployment.transaction.hash);\n\t\treturn deployment;\n\t}\n\n\tfunction showMessage(message: string) {\n\t\tlog(message);\n\t}\n\n\tfunction showProgress(message?: string): ProgressIndicator {\n\t\treturn spin(message);\n\t}\n\n\tlet env: Environment<Artifacts, NamedAccounts, Deployments> = {\n\t\t...perliminaryEnvironment,\n\t\tsave,\n\t\tsavePendingDeployment,\n\t\tsavePendingExecution,\n\t\tget,\n\t\tgetOrNull,\n\t\tfromAddressToNamedABI,\n\t\tfromAddressToNamedABIOrNull,\n\t\tshowMessage,\n\t\tshowProgress,\n\t};\n\tfor (const extension of (globalThis as any).extensions) {\n\t\tenv = extension(env);\n\t}\n\n\treturn {\n\t\texternal: env,\n\t\tinternal: {\n\t\t\texportDeploymentsAsTypes,\n\t\t\trecoverTransactionsIfAny,\n\t\t},\n\t};\n}\n","// TODO share with db-utils\nexport function bnReplacer(k: string, v: any): any {\n\tif (typeof v === 'bigint') {\n\t\treturn v.toString() + 'n';\n\t}\n\treturn v;\n}\n\nexport function bnReviver(k: string, v: any): any {\n\tif (\n\t\ttypeof v === 'string' &&\n\t\t(v.startsWith('-') ? !isNaN(parseInt(v.charAt(1))) : !isNaN(parseInt(v.charAt(0)))) &&\n\t\tv.charAt(v.length - 1) === 'n'\n\t) {\n\t\treturn BigInt(v.slice(0, -1));\n\t}\n\treturn v;\n}\n\nexport function JSONToString<T = unknown>(json: unknown, space?: string | number) {\n\treturn JSON.stringify(json, bnReplacer, space);\n}\n\nexport function stringToJSON<T = unknown>(str: string): T {\n\treturn JSON.parse(str, bnReviver);\n}\n","import path from 'node:path';\nimport fs from 'node:fs';\nimport {traverse} from '../utils/fs';\nimport {UnknownDeployments} from './types';\n\nexport function loadDeployments(\n\tdeploymentsPath: string,\n\tnetworkName: string,\n\tonlyABIAndAddress?: boolean,\n\texpectedChain?: {chainId: string; genesisHash?: `0x${string}`; deleteDeploymentsIfDifferentGenesisHash?: boolean}\n): {deployments: UnknownDeployments; chainId?: string; genesisHash?: `0x${string}`} {\n\tconst deploymentsFound: UnknownDeployments = {};\n\tconst deployPath = path.join(deploymentsPath, networkName);\n\n\tlet filesStats;\n\ttry {\n\t\tfilesStats = traverse(deployPath, undefined, undefined, (name) => !name.startsWith('.') && name !== 'solcInputs');\n\t} catch (e) {\n\t\t// console.log('no folder at ' + deployPath);\n\t\treturn {deployments: {}};\n\t}\n\tlet chainId: string;\n\tlet genesisHash: `0x${string}` | undefined;\n\tif (filesStats.length > 0) {\n\t\tconst chainIdFilepath = path.join(deployPath, '.chainId');\n\t\tif (fs.existsSync(chainIdFilepath)) {\n\t\t\tchainId = fs.readFileSync(chainIdFilepath, 'utf-8').trim();\n\t\t} else {\n\t\t\tconst chainFilepath = path.join(deployPath, '.chain');\n\t\t\tif (fs.existsSync(chainFilepath)) {\n\t\t\t\tconst chainSTR = fs.readFileSync(chainFilepath, 'utf-8');\n\t\t\t\tconst chainData = JSON.parse(chainSTR);\n\t\t\t\tchainId = chainData.chainId;\n\t\t\t\tgenesisHash = chainData.genesisHash;\n\t\t\t} else {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`A '.chain' or '.chainId' file is expected to be present in the deployment folder for network ${networkName}`\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tif (expectedChain) {\n\t\t\tif (expectedChain.chainId !== chainId) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Loading deployment in folder '${deployPath}' (with chainId: ${chainId}) for a different chainId (${expectedChain.chainId})`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (expectedChain.genesisHash && expectedChain.genesisHash !== genesisHash) {\n\t\t\t\tif (expectedChain.deleteDeploymentsIfDifferentGenesisHash) {\n\t\t\t\t\t// we delete the old folder\n\n\t\t\t\t\tfs.rmSync(deployPath, {recursive: true, force: true});\n\t\t\t\t\treturn {deployments: {}};\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Loading deployment in folder '${deployPath}' (with genesisHash: ${genesisHash}) for a different genesisHash (${expectedChain.genesisHash})`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn {deployments: {}};\n\t}\n\tlet fileNames = filesStats.map((a) => a.relativePath);\n\tfileNames = fileNames.sort((a, b) => {\n\t\tif (a < b) {\n\t\t\treturn -1;\n\t\t}\n\t\tif (a > b) {\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t});\n\n\tfor (const fileName of fileNames) {\n\t\tif (fileName.substring(fileName.length - 5) === '.json') {\n\t\t\tconst deploymentFileName = path.join(deployPath, fileName);\n\t\t\tlet deployment = JSON.parse(fs.readFileSync(deploymentFileName).toString());\n\t\t\t// truffleChainId argument:\n\t\t\t// if (!deployment.address && deployment.networks) {\n\t\t\t// \tif (truffleChainId && deployment.networks[truffleChainId]) {\n\t\t\t// \t\t// TRUFFLE support\n\t\t\t// \t\tconst truffleDeployment = deployment as any; // TruffleDeployment;\n\t\t\t// \t\tdeployment.address = truffleDeployment.networks[truffleChainId].address;\n\t\t\t// \t\tdeployment.transactionHash = truffleDeployment.networks[truffleChainId].transactionHash;\n\t\t\t// \t}\n\t\t\t// }\n\t\t\tif (onlyABIAndAddress) {\n\t\t\t\tdeployment = {\n\t\t\t\t\taddress: deployment.address,\n\t\t\t\t\tabi: deployment.abi,\n\t\t\t\t\tlinkedData: deployment.linkedData,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst name = fileName.slice(0, fileName.length - 5);\n\t\t\t// console.log('fetching ' + deploymentFileName + ' for ' + name);\n\n\t\t\tdeploymentsFound[name] = deployment;\n\t\t}\n\t}\n\treturn {deployments: deploymentsFound, chainId, genesisHash};\n}\n","import {logs} from 'named-logs';\n\nimport {hookup, factory as Logging} from 'named-logs-console';\n// import ora from 'ora-cjs';\nhookup();\n\nexport function setLogLevel(level: number) {\n\tLogging.level = level;\n\tif (Logging.level > 0) {\n\t\tLogging.enable();\n\t} else {\n\t\tLogging.disable();\n\t}\n}\n\nexport const logger = logs('rocketh');\n\nexport type ProgressIndicator = {\n\tstart(msg?: string): ProgressIndicator;\n\tstop(): ProgressIndicator;\n\tsucceed(msg?: string): ProgressIndicator;\n\tfail(msg?: string): ProgressIndicator;\n};\nconst loggerProgressIndicator: ProgressIndicator = {\n\tstart(msg?: string) {\n\t\tif (msg) {\n\t\t\tconsole.log(msg);\n\t\t}\n\t\treturn this;\n\t},\n\tstop() {\n\t\treturn this;\n\t},\n\tsucceed(msg?: string) {\n\t\tif (msg) {\n\t\t\tconsole.log(msg);\n\t\t}\n\t\treturn this;\n\t},\n\tfail(msg?: string) {\n\t\tif (msg) {\n\t\t\tconsole.error(msg);\n\t\t}\n\t\treturn this;\n\t},\n};\nconst voidProgressIndicator: ProgressIndicator = {\n\tstart() {\n\t\treturn this;\n\t},\n\tstop() {\n\t\treturn this;\n\t},\n\tsucceed() {\n\t\treturn this;\n\t},\n\tfail() {\n\t\treturn this;\n\t},\n};\n// export function spin(message: string): PartialOra {\n// \treturn Logging.level > 0 ? ora(message).start() : voidProgressIndicator;\n// }\n\n// let lastSpin = ora('rocketh');\nlet lastSpin = loggerProgressIndicator;\nexport function spin(message?: string): ProgressIndicator {\n\tif (Logging.level > 0) {\n\t\tlastSpin = lastSpin.start(message);\n\t\treturn lastSpin;\n\t} else {\n\t\treturn voidProgressIndicator;\n\t}\n}\n\nexport function log(message: string) {\n\tif (Logging.level > 0) {\n\t\tconsole.log(message);\n\t}\n}\n","import type {Chain} from 'viem/chains';\nimport chains from 'viem/chains';\n\nexport const chainById: {[chainId: string]: Chain} = {};\nconst allChains = (chains as any).default || chains;\nfor (const key of Object.keys(allChains)) {\n\tconst chain = (allChains as any)[key] as Chain;\n\tchainById[chain.id.toString()] = chain;\n}\n\nexport function getChain(id: string): Chain {\n\tconst chain = chainById[id];\n\tif (!chain) {\n\t\treturn {\n\t\t\tid: parseInt(id),\n\t\t\tname: 'unkwown',\n\t\t\t// TODO\n\t\t\tnativeCurrency: {\n\t\t\t\tname: 'Unknown Currency',\n\t\t\t\tsymbol: 'UNKNOWN',\n\t\t\t\tdecimals: 18,\n\t\t\t},\n\t\t\trpcUrls: {\n\t\t\t\tdefault: {\n\t\t\t\t\thttp: [],\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\treturn chain;\n}\n","import {Abi} from 'abitype';\nimport {Artifact, DevDoc, UserDoc} from '../types';\nimport {FunctionFragment} from 'ethers';\n\ntype CreateMutable<Type> = {\n\t-readonly [Property in keyof Type]: Type[Property];\n};\n\ntype ArrayElement<ArrayType extends readonly unknown[]> = ArrayType extends readonly (infer ElementType)[]\n\t? ElementType\n\t: never;\n\n// from https://gist.github.com/egardner/efd34f270cc33db67c0246e837689cb9\nfunction deepEqual(obj1: any, obj2: any): boolean {\n\t// Private\n\tfunction isObject(obj: any) {\n\t\tif (typeof obj === 'object' && obj != null) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tif (obj1 === obj2) {\n\t\treturn true;\n\t} else if (isObject(obj1) && isObject(obj2)) {\n\t\tif (Object.keys(obj1).length !== Object.keys(obj2).length) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (var prop in obj1) {\n\t\t\tif (!deepEqual(obj1[prop], obj2[prop])) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nfunction mergeDoc(values: any, mergedDevDocs: any, field: string) {\n\tif (values[field]) {\n\t\tconst mergedEventDocs = (mergedDevDocs[field] = mergedDevDocs[field] || {});\n\t\tfor (const signature of Object.keys(values[field])) {\n\t\t\tif (mergedEventDocs[signature] && !deepEqual(mergedEventDocs[signature], values[field][signature])) {\n\t\t\t\tthrow new Error(`Doc ${field} conflict: \"${signature}\" `);\n\t\t\t}\n\t\t\tmergedEventDocs[signature] = values[field][signature];\n\t\t}\n\t}\n}\n\nexport function mergeArtifacts(list: {name: string; artifact: Artifact<Abi>}[]) {\n\tconst mergedABI: CreateMutable<Abi> = [];\n\tconst added: Map<string, ArrayElement<Abi>> = new Map();\n\tconst mergedDevDocs: CreateMutable<DevDoc> = {kind: 'dev', version: 1, methods: {}};\n\tconst mergedUserDocs: CreateMutable<UserDoc> = {kind: 'user', version: 1, methods: {}};\n\tconst sigJSMap: Map<`0x${string}`, {index: number; routeName: string; functionName: string}> = new Map();\n\n\tfor (let i = 0; i < list.length; i++) {\n\t\tconst listElem = list[i];\n\t\tfor (const element of listElem.artifact.abi) {\n\t\t\tif (element.type === 'function') {\n\t\t\t\t// const selector = getFunctionSelector(element);\n\t\t\t\tconst selector = FunctionFragment.from(element).selector as `0x${string}`;\n\t\t\t\tif (sigJSMap.has(selector)) {\n\t\t\t\t\tconst existing = sigJSMap.get(selector);\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`ABI conflict: ${existing!.routeName} has function \"${existing!.functionName}\" which conflict with ${\n\t\t\t\t\t\t\tlistElem.name\n\t\t\t\t\t\t}'s \"${element.name}\" (selector: \"${selector}\") `\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tsigJSMap.set(selector, {index: i, routeName: listElem.name, functionName: element.name});\n\n\t\t\t\tconst exists = added.has(element.name);\n\t\t\t\tif (exists) {\n\t\t\t\t\t// TODO check if same\n\t\t\t\t} else {\n\t\t\t\t\tadded.set(element.name, element);\n\t\t\t\t\tmergedABI.push(element);\n\t\t\t\t}\n\t\t\t} else if (element.type === 'constructor') {\n\t\t\t\t// we skip it\n\t\t\t} else if (element.type === 'error') {\n\t\t\t\tconst exists = added.has(element.name);\n\t\t\t\tif (exists) {\n\t\t\t\t\t// TODO check if same\n\t\t\t\t} else {\n\t\t\t\t\tadded.set(element.name, element);\n\t\t\t\t\tmergedABI.push(element);\n\t\t\t\t}\n\t\t\t} else if (element.type === 'event') {\n\t\t\t\tconst exists = added.has(element.name);\n\t\t\t\tif (exists) {\n\t\t\t\t\t// TODO check if same\n\t\t\t\t} else {\n\t\t\t\t\tadded.set(element.name, element);\n\t\t\t\t\tmergedABI.push(element);\n\t\t\t\t}\n\t\t\t} else if (element.type === 'fallback') {\n\t\t\t} else if (element.type === 'receive') {\n\t\t\t} else {\n\t\t\t\t// if ('name' in element) {\n\t\t\t\t// \tconst exists = added.has(element.name);\n\t\t\t\t// \tif (exists) {\n\t\t\t\t// \t\t// TODO check if same\n\t\t\t\t// \t} else {\n\t\t\t\t// \t\tadded.set(element.name, element);\n\t\t\t\t// \t\tmergedABI.push(element);\n\t\t\t\t// \t}\n\t\t\t\t// }\n\t\t\t}\n\t\t}\n\t\tconst devdoc = listElem.artifact.devdoc;\n\t\tif (devdoc) {\n\t\t\tmergeDoc(devdoc, mergedDevDocs, 'events');\n\t\t\tmergeDoc(devdoc, mergedDevDocs, 'errors');\n\t\t\tmergeDoc(devdoc, mergedDevDocs, 'methods');\n\t\t\tif (devdoc.author) {\n\t\t\t\tif (mergedDevDocs.author && mergedDevDocs.author != devdoc.author) {\n\t\t\t\t\tthrow new Error(`DevDoc author conflict `);\n\t\t\t\t}\n\t\t\t\tmergedDevDocs.author = devdoc.author;\n\t\t\t\tif (mergedDevDocs.title && mergedDevDocs.title != devdoc.title) {\n\t\t\t\t\tthrow new Error(`DevDoc title conflict `);\n\t\t\t\t}\n\t\t\t\tmergedDevDocs.title = devdoc.title;\n\t\t\t}\n\t\t}\n\n\t\tconst userdoc = listElem.artifact.userdoc;\n\t\tif (userdoc) {\n\t\t\tmergeDoc(userdoc, mergedUserDocs, 'events');\n\t\t\tmergeDoc(userdoc, mergedUserDocs, 'errors');\n\t\t\tmergeDoc(userdoc, mergedUserDocs, 'methods');\n\t\t\tif (userdoc.notice) {\n\t\t\t\tif (mergedUserDocs.notice && mergedUserDocs.notice != userdoc.notice) {\n\t\t\t\t\tthrow new Error(`UserDoc notice conflict `);\n\t\t\t\t}\n\t\t\t\tmergedUserDocs.notice = userdoc.notice;\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\tmergedABI,\n\t\tadded,\n\t\tmergedDevDocs,\n\t\tmergedUserDocs,\n\t\tsigJSMap,\n\t};\n}\n","import {\n\tEIP1193Accounts,\n\tEIP1193AccountsRequest,\n\tEIP1193AddChainError,\n\tEIP1193Block,\n\tEIP1193BlockNumberRequest,\n\tEIP1193BlockWithTransactions,\n\tEIP1193CallRequest,\n\tEIP1193ChainIdRequest,\n\tEIP1193CoinbaseRequest,\n\tEIP1193EstimateGasRequest,\n\tEIP1193GasPriceRequest,\n\tEIP1193GenericRequest,\n\tEIP1193GenericRequestProvider,\n\tEIP1193GetBalanceRequest,\n\tEIP1193GetBlockByHashRequest,\n\tEIP1193GetBlockByNumberRequest,\n\tEIP1193GetCodeRequest,\n\tEIP1193GetLogsRequest,\n\tEIP1193GetStorageAtRequest,\n\tEIP1193GetTransactionByBlockHashAndIndexRequest,\n\tEIP1193GetTransactionByBlockNumberAndIndexRequest,\n\tEIP1193GetTransactionByHashRequest,\n\tEIP1193GetTransactionCountByHashRequest,\n\tEIP1193GetTransactionCountByNumberRequest,\n\tEIP1193GetTransactionCountRequest,\n\tEIP1193GetTransactionReceiptRequest,\n\tEIP1193GetUncleByBlockHashAndIndexRequest,\n\tEIP1193GetUncleByBlockNumberAndIndexRequest,\n\tEIP1193GetUncleCountByBlockHashRequest,\n\tEIP1193GetUncleCountByBlockNumberRequest,\n\tEIP1193LegacySignRequest,\n\tEIP1193Log,\n\tEIP1193NetListeningRequest,\n\tEIP1193NetPeerCountRequest,\n\tEIP1193NetVersionRequest,\n\tEIP1193PTypedSignRequest,\n\tEIP1193PTypedSignv4Request,\n\tEIP1193PersonalSignRequest,\n\tEIP1193ProtocolVersionRequest,\n\tEIP1193ProviderWithoutEvents,\n\tEIP1193RequestAccountsRequest,\n\tEIP1193SendRawTransactionRequest,\n\tEIP1193SendTransactionRequest,\n\tEIP1193SignTransactionRequest,\n\tEIP1193SubscribeRequest,\n\tEIP1193SwitchChainError,\n\tEIP1193SyncingRequest,\n\tEIP1193SyncingStatus,\n\tEIP1193Transaction,\n\tEIP1193TransactionReceipt,\n\tEIP1193UnsubscribeRequest,\n\tEIP1193Web3ClientVersionRequest,\n\tEIP1193Web3SHARequest,\n\tERIP1193AddChainRequest,\n\tERIP1193SwitchChainRequest,\n} from 'eip-1193';\n\nexport abstract class BaseProvider implements EIP1193ProviderWithoutEvents {\n\tconstructor(protected provider: EIP1193GenericRequestProvider) {}\n\trequest(args: EIP1193Web3ClientVersionRequest): Promise<string>;\n\trequest(args: EIP1193Web3SHARequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193NetVersionRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193NetListeningRequest): Promise<boolean>;\n\trequest(args: EIP1193NetPeerCountRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193ProtocolVersionRequest): Promise<string>;\n\trequest(args: EIP1193SyncingRequest): Promise<false | EIP1193SyncingStatus>;\n\trequest(args: EIP1193CoinbaseRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193GasPriceRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193AccountsRequest): Promise<EIP1193Accounts>;\n\trequest(args: EIP1193BlockNumberRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193GetBalanceRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193GetStorageAtRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193GetTransactionCountRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193GetTransactionCountByHashRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193GetTransactionCountByNumberRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193GetUncleCountByBlockHashRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193GetUncleCountByBlockNumberRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193GetCodeRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193LegacySignRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193SignTransactionRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193SendTransactionRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193SendRawTransactionRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193CallRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193EstimateGasRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193GetBlockByHashRequest<false>): Promise<EIP1193Block | null>;\n\trequest(args: EIP1193GetBlockByHashRequest<true>): Promise<EIP1193BlockWithTransactions | null>;\n\trequest(args: EIP1193GetBlockByNumberRequest<false>): Promise<EIP1193Block | null>;\n\trequest(args: EIP1193GetBlockByNumberRequest<true>): Promise<EIP1193BlockWithTransactions | null>;\n\trequest(args: EIP1193GetTransactionByHashRequest): Promise<EIP1193Transaction | null>;\n\trequest(args: EIP1193GetTransactionByBlockHashAndIndexRequest): Promise<EIP1193Transaction | null>;\n\trequest(args: EIP1193GetTransactionByBlockNumberAndIndexRequest): Promise<EIP1193Transaction | null>;\n\trequest(args: EIP1193GetTransactionReceiptRequest): Promise<EIP1193TransactionReceipt | null>;\n\trequest(args: EIP1193GetUncleByBlockHashAndIndexRequest): Promise<EIP1193Block | null>;\n\trequest(args: EIP1193GetUncleByBlockNumberAndIndexRequest): Promise<EIP1193Block | null>;\n\trequest(args: EIP1193GetLogsRequest): Promise<EIP1193Log[]>;\n\trequest(args: EIP1193PersonalSignRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193PTypedSignv4Request): Promise<`0x${string}`>;\n\trequest(args: EIP1193PTypedSignRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193ChainIdRequest): Promise<`0x${string}`>;\n\trequest(args: EIP1193RequestAccountsRequest): Promise<EIP1193Accounts>;\n\trequest(args: ERIP1193SwitchChainRequest): Promise<EIP1193SwitchChainError | null>;\n\trequest(args: ERIP1193AddChainRequest): Promise<EIP1193AddChainError | null>;\n\trequest(args: EIP1193SubscribeRequest): Promise<string>;\n\trequest(args: EIP1193UnsubscribeRequest): Promise<boolean>;\n\trequest<T = unknown, V extends EIP1193GenericRequest = EIP1193GenericRequest>(args: V): Promise<T>;\n\trequest<T = unknown, V extends EIP1193GenericRequest = EIP1193GenericRequest>(args: V): Promise<T> {\n\t\treturn this._request(args);\n\t}\n\n\tprotected abstract _request<T = unknown, V extends EIP1193GenericRequest = EIP1193GenericRequest>(\n\t\targs: V\n\t): Promise<T>;\n}\n","import {EIP1193GenericRequest, EIP1193GenericRequestProvider} from 'eip-1193';\nimport {BaseProvider} from './BaseProvider';\n\nexport class TransactionHashTracker extends BaseProvider {\n\tpublic transactionHashes: `0x${string}`[] = [];\n\n\tconstructor(provider: EIP1193GenericRequestProvider) {\n\t\tsuper(provider);\n\t}\n\n\tprotected async _request<T = unknown, V extends EIP1193GenericRequest = EIP1193GenericRequest>(args: V): Promise<T> {\n\t\tconst response = await this.provider.request<T>(args);\n\t\tif (args.method === 'eth_sendRawTransaction' || args.method === 'eth_sendTransaction') {\n\t\t\tthis.transactionHashes.push(response as `0x${string}`);\n\t\t}\n\t\treturn response;\n\t}\n}\n","import {EIP1193BlockTag, EIP1193ProviderWithoutEvents} from 'eip-1193';\n\nfunction avg(arr: bigint[]) {\n\tconst sum = arr.reduce((a: bigint, v: bigint) => a + v);\n\treturn sum / BigInt(arr.length);\n}\n\ntype EIP1193FeeHistory = {\n\toldestBlock: string;\n\treward: `0x${string}`[][];\n\tbaseFeePerGas: string[];\n\tgasUsedRatio: string[];\n};\n\nexport type EstimateGasPriceOptions = {\n\tblockCount: number;\n\tnewestBlock: EIP1193BlockTag;\n\trewardPercentiles: number[];\n};\n\nexport type RoughEstimateGasPriceOptions = {\n\tblockCount: number;\n\tnewestBlock: EIP1193BlockTag;\n\trewardPercentiles: [number, number, number];\n};\n\nexport type GasPrice = {maxFeePerGas: bigint; maxPriorityFeePerGas: bigint};\nexport type EstimateGasPriceResult = GasPrice[];\nexport type RoughEstimateGasPriceResult = {slow: GasPrice; average: GasPrice; fast: GasPrice};\n\nexport async function getGasPriceEstimate(\n\tprovider: EIP1193ProviderWithoutEvents,\n\toptions?: Partial<EstimateGasPriceOptions>\n): Promise<EstimateGasPriceResult> {\n\tconst defaultOptions: EstimateGasPriceOptions = {\n\t\tblockCount: 20,\n\t\tnewestBlock: 'pending',\n\t\trewardPercentiles: [10, 50, 80],\n\t};\n\tconst optionsResolved = options ? {...defaultOptions, ...options} : defaultOptions;\n\n\tconst historicalBlocks = optionsResolved.blockCount;\n\n\tconst rawFeeHistory = await provider.request<EIP1193FeeHistory>({\n\t\tmethod: 'eth_feeHistory',\n\t\tparams: [`0x${historicalBlocks.toString(16)}`, optionsResolved.newestBlock, optionsResolved.rewardPercentiles],\n\t});\n\n\tlet blockNum = Number(rawFeeHistory.oldestBlock);\n\tconst lastBlock = blockNum + rawFeeHistory.reward.length;\n\tlet index = 0;\n\tconst blocksHistory: {number: number; baseFeePerGas: bigint; gasUsedRatio: number; priorityFeePerGas: bigint[]}[] =\n\t\t[];\n\twhile (blockNum < lastBlock) {\n\t\tblocksHistory.push({\n\t\t\tnumber: blockNum,\n\t\t\tbaseFeePerGas: BigInt(rawFeeHistory.baseFeePerGas[index]),\n\t\t\tgasUsedRatio: Number(rawFeeHistory.gasUsedRatio[index]),\n\t\t\tpriorityFeePerGas: rawFeeHistory.reward[index].map((x) => BigInt(x)),\n\t\t});\n\t\tblockNum += 1;\n\t\tindex += 1;\n\t}\n\n\tconst percentilePriorityFeeAverages: bigint[] = [];\n\tfor (let i = 0; i < optionsResolved.rewardPercentiles.length; i++) {\n\t\tpercentilePriorityFeeAverages.push(avg(blocksHistory.map((b) => b.priorityFeePerGas[i])));\n\t}\n\n\tconst baseFeePerGas = BigInt(rawFeeHistory.baseFeePerGas[rawFeeHistory.baseFeePerGas.length - 1]);\n\n\tconst result: EstimateGasPriceResult = [];\n\tfor (let i = 0; i < optionsResolved.rewardPercentiles.length; i++) {\n\t\tresult.push({\n\t\t\tmaxFeePerGas: percentilePriorityFeeAverages[i] + baseFeePerGas,\n\t\t\tmaxPriorityFeePerGas: percentilePriorityFeeAverages[i],\n\t\t});\n\t}\n\treturn result;\n}\n\nexport async function getRoughGasPriceEstimate(\n\tprovider: EIP1193ProviderWithoutEvents,\n\toptions?: Partial<RoughEstimateGasPriceOptions>\n): Promise<RoughEstimateGasPriceResult> {\n\tconst defaultOptions: EstimateGasPriceOptions = {\n\t\tblockCount: 20,\n\t\tnewestBlock: 'pending',\n\t\trewardPercentiles: [10, 50, 80],\n\t};\n\tconst optionsResolved = options ? {...defaultOptions, ...options} : defaultOptions;\n\n\tif (optionsResolved.rewardPercentiles.length !== 3) {\n\t\tthrow new Error(`rough gas estimate require 3 percentile, it defaults to [10,50,80]`);\n\t}\n\n\tconst result = await getGasPriceEstimate(provider, optionsResolved);\n\treturn {\n\t\tslow: result[0],\n\t\taverage: result[1],\n\t\tfast: result[2],\n\t};\n}\n"],"mappings":";;;;;;;;;AACA,OAAO,QAAQ;AACf,OAAO,UAAU;AAwBV,SAAS,0BAA0B,MAA0B;AACnE,QAAM,YAAY,CAAC;AACnB,aAAW,OAAO,MAAM;AACvB,QAAI,aAAa,SAAS,GAAG;AAC7B,iBAAa,WAAW,OAAO,CAAC,MAAM,CAAC,EAAE,SAAS;AAClD,eAAW,YAAY,YAAY;AAClC,gBAAU,KAAK,KAAK,KAAK,KAAK,SAAS,YAAY,CAAC;AAAA,IACrD;AAAA,EACD;AACA,SAAO;AACR;AAEO,IAAM,WAAW,SACvB,KACA,SAAgB,CAAC,GACjB,QACA,QAOE;AACF,KAAG,YAAY,GAAG,EAAE,QAAQ,CAAC,SA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WAAWA,MAAK,SAAS,aAAa,QAAQ;AACpD,UAAM,mBAAmBA,MAAK,SAAS,KAAK,aAAa,QAAQ;AAKjE,QAAI,OAAO;AACX,UAAM,UAAU,KAAK,eAAe,QAAQ,EAAE;AAC9C,QAAI,aAAa,KAAK,MAAM;AAC3B,YAAMC,WAAU,KAAK,aAAa;AAClC,UAAI;AACH,eAAO,MAAM,aAAa,KAAK,KAAK,UAAU,IAAI;AAClD,QAAAA,SAAQ,QAAQ,OAAO,YAAY,QAAQ,KAAK,MAAS;AAAA,MAC1D,SAAS,GAAG;AACX,QAAAA,SAAQ,KAAK;AACb,cAAM;AAAA,MACP;AAAA,IACD;AACA,QAAI,CAAC,MAAM;AACV,UAAI;AAEJ,UAAI;AACH,iBAAS,MAAM,aAAa,KAAK,UAAU,IAAI;AAC/C,gBAAQ,QAAQ;AAAA,CAAI;AAAA,MACrB,SAAS,GAAG;AACX,gBAAQ,KAAK;AACb,cAAM;AAAA,MACP;AACA,UAAI,UAAU,OAAO,WAAW,WAAW;AAQ1C,cAAM,uBAAuB,OAAO;AAAA,MAgBrC;AAAA,IACD;AAAA,EACD;AAEA,MAAI,OAAO,cAAc;AACxB,UAAM,WAAW,SAAS,QAAQ;AAClC,UAAM,oBAAoB,SAAS;AAEnC,QAAI,eAAe;AACnB,eAAW,QAAQ,mBAAmB;AACrC,YAAM,qBAAqB,MAAM,SAAS,QAAQ,EAAC,QAAQ,6BAA6B,QAAQ,CAAC,IAAI,EAAC,CAAC;AACvG,UAAI,oBAAoB;AACvB,cAAM,UAAU,OAAO,mBAAmB,OAAO;AACjD,wBAAgB;AAAA,MACjB;AAAA,IACD;AAEA,YAAQ,IAAI,EAAC,aAAY,CAAC;AAAA,EAC3B;AAEA,SAAO;AACR;","names":["path","fs","fs","path","path","fs","path","fs","accounts","path","fs","transaction","fs","path","spinner"]}
package/dist/cli.cjs CHANGED
@@ -384,6 +384,31 @@ function mergeArtifacts(list) {
384
384
  };
385
385
  }
386
386
 
387
+ // src/environment/providers/BaseProvider.ts
388
+ var BaseProvider = class {
389
+ constructor(provider) {
390
+ this.provider = provider;
391
+ }
392
+ request(args) {
393
+ return this._request(args);
394
+ }
395
+ };
396
+
397
+ // src/environment/providers/TransactionHashTracker.ts
398
+ var TransactionHashTracker = class extends BaseProvider {
399
+ constructor(provider) {
400
+ super(provider);
401
+ this.transactionHashes = [];
402
+ }
403
+ async _request(args) {
404
+ const response = await this.provider.request(args);
405
+ if (args.method === "eth_sendRawTransaction" || args.method === "eth_sendTransaction") {
406
+ this.transactionHashes.push(response);
407
+ }
408
+ return response;
409
+ }
410
+ };
411
+
387
412
  // src/environment/index.ts
388
413
  globalThis.extensions = [];
389
414
  globalThis.signerProtocols = {};
@@ -402,7 +427,8 @@ function displayTransaction(transaction) {
402
427
  }
403
428
  }
404
429
  async function createEnvironment(config, providedContext) {
405
- const provider = "provider" in config.network ? config.network.provider : new import_eip_1193_jsonrpc_provider.JSONRPCHTTPProvider(config.network.nodeUrl);
430
+ const rawProvider = "provider" in config.network ? config.network.provider : new import_eip_1193_jsonrpc_provider.JSONRPCHTTPProvider(config.network.nodeUrl);
431
+ const provider = new TransactionHashTracker(rawProvider);
406
432
  const transport = (0, import_viem.custom)(provider);
407
433
  const viemClient = (0, import_viem.createPublicClient)({ transport });
408
434
  const chainId = (await viemClient.getChainId()).toString();
@@ -882,7 +908,72 @@ async function createEnvironment(config, providedContext) {
882
908
  };
883
909
  }
884
910
 
911
+ // src/utils/eth.ts
912
+ function avg(arr) {
913
+ const sum = arr.reduce((a, v) => a + v);
914
+ return sum / BigInt(arr.length);
915
+ }
916
+ async function getGasPriceEstimate(provider, options2) {
917
+ const defaultOptions = {
918
+ blockCount: 20,
919
+ newestBlock: "pending",
920
+ rewardPercentiles: [10, 50, 80]
921
+ };
922
+ const optionsResolved = options2 ? { ...defaultOptions, ...options2 } : defaultOptions;
923
+ const historicalBlocks = optionsResolved.blockCount;
924
+ const rawFeeHistory = await provider.request({
925
+ method: "eth_feeHistory",
926
+ params: [`0x${historicalBlocks.toString(16)}`, optionsResolved.newestBlock, optionsResolved.rewardPercentiles]
927
+ });
928
+ let blockNum = Number(rawFeeHistory.oldestBlock);
929
+ const lastBlock = blockNum + rawFeeHistory.reward.length;
930
+ let index = 0;
931
+ const blocksHistory = [];
932
+ while (blockNum < lastBlock) {
933
+ blocksHistory.push({
934
+ number: blockNum,
935
+ baseFeePerGas: BigInt(rawFeeHistory.baseFeePerGas[index]),
936
+ gasUsedRatio: Number(rawFeeHistory.gasUsedRatio[index]),
937
+ priorityFeePerGas: rawFeeHistory.reward[index].map((x) => BigInt(x))
938
+ });
939
+ blockNum += 1;
940
+ index += 1;
941
+ }
942
+ const percentilePriorityFeeAverages = [];
943
+ for (let i = 0; i < optionsResolved.rewardPercentiles.length; i++) {
944
+ percentilePriorityFeeAverages.push(avg(blocksHistory.map((b) => b.priorityFeePerGas[i])));
945
+ }
946
+ const baseFeePerGas = BigInt(rawFeeHistory.baseFeePerGas[rawFeeHistory.baseFeePerGas.length - 1]);
947
+ const result = [];
948
+ for (let i = 0; i < optionsResolved.rewardPercentiles.length; i++) {
949
+ result.push({
950
+ maxFeePerGas: percentilePriorityFeeAverages[i] + baseFeePerGas,
951
+ maxPriorityFeePerGas: percentilePriorityFeeAverages[i]
952
+ });
953
+ }
954
+ return result;
955
+ }
956
+ async function getRoughGasPriceEstimate(provider, options2) {
957
+ const defaultOptions = {
958
+ blockCount: 20,
959
+ newestBlock: "pending",
960
+ rewardPercentiles: [10, 50, 80]
961
+ };
962
+ const optionsResolved = options2 ? { ...defaultOptions, ...options2 } : defaultOptions;
963
+ if (optionsResolved.rewardPercentiles.length !== 3) {
964
+ throw new Error(`rough gas estimate require 3 percentile, it defaults to [10,50,80]`);
965
+ }
966
+ const result = await getGasPriceEstimate(provider, optionsResolved);
967
+ return {
968
+ slow: result[0],
969
+ average: result[1],
970
+ fast: result[2]
971
+ };
972
+ }
973
+
885
974
  // src/executor/index.ts
975
+ var import_prompts = __toESM(require("prompts"), 1);
976
+ var import_viem2 = require("viem");
886
977
  if (!process.env["ROCKETH_SKIP_ESBUILD"]) {
887
978
  require("esbuild-register/dist/node").register();
888
979
  }
@@ -957,7 +1048,9 @@ function readConfig(options2) {
957
1048
  saveDeployments: options2.saveDeployments,
958
1049
  scripts: options2.scripts,
959
1050
  tags: typeof options2.tags === "undefined" ? void 0 : options2.tags.split(","),
960
- logLevel: options2.logLevel
1051
+ logLevel: options2.logLevel,
1052
+ askBeforeProceeding: options2.askBeforeProceeding,
1053
+ reportGasUse: options2.reportGasUse
961
1054
  };
962
1055
  } else {
963
1056
  return {
@@ -971,7 +1064,9 @@ function readConfig(options2) {
971
1064
  saveDeployments: options2.saveDeployments,
972
1065
  scripts: options2.scripts,
973
1066
  tags: typeof options2.tags === "undefined" ? void 0 : options2.tags.split(","),
974
- logLevel: options2.logLevel
1067
+ logLevel: options2.logLevel,
1068
+ askBeforeProceeding: options2.askBeforeProceeding,
1069
+ reportGasUse: options2.reportGasUse
975
1070
  };
976
1071
  }
977
1072
  }
@@ -1111,6 +1206,28 @@ async function executeDeployScripts(config, args) {
1111
1206
  for (const scriptFilePath of scriptFilePaths) {
1112
1207
  recurseDependencies(scriptFilePath);
1113
1208
  }
1209
+ if (config.askBeforeProceeding) {
1210
+ const gasPriceEstimate = await getRoughGasPriceEstimate(external.network.provider);
1211
+ const prompt = await (0, import_prompts.default)({
1212
+ type: "confirm",
1213
+ name: "proceed",
1214
+ message: `gas price is currently in this range:
1215
+ slow: ${(0, import_viem2.formatEther)(gasPriceEstimate.slow.maxFeePerGas)} (priority: ${(0, import_viem2.formatEther)(
1216
+ gasPriceEstimate.slow.maxPriorityFeePerGas
1217
+ )})
1218
+ average: ${(0, import_viem2.formatEther)(gasPriceEstimate.average.maxFeePerGas)} (priority: ${(0, import_viem2.formatEther)(
1219
+ gasPriceEstimate.average.maxPriorityFeePerGas
1220
+ )})
1221
+ fast: ${(0, import_viem2.formatEther)(gasPriceEstimate.fast.maxFeePerGas)} (priority: ${(0, import_viem2.formatEther)(
1222
+ gasPriceEstimate.fast.maxPriorityFeePerGas
1223
+ )})
1224
+
1225
+ Do you want to proceed (note that gas price can change for each tx)`
1226
+ });
1227
+ if (!prompt.proceed) {
1228
+ process.exit();
1229
+ }
1230
+ }
1114
1231
  for (const deployScript of scriptsToRun.concat(scriptsToRunAtTheEnd)) {
1115
1232
  const filename = import_node_path4.default.basename(deployScript.filePath);
1116
1233
  const relativeFilepath = import_node_path4.default.relative(".", deployScript.filePath);
@@ -1141,6 +1258,19 @@ async function executeDeployScripts(config, args) {
1141
1258
  }
1142
1259
  }
1143
1260
  }
1261
+ if (config.reportGasUse) {
1262
+ const provider = external.network.provider;
1263
+ const transactionHashes = provider.transactionHashes;
1264
+ let totalGasUsed = 0;
1265
+ for (const hash of transactionHashes) {
1266
+ const transactionReceipt = await provider.request({ method: "eth_getTransactionReceipt", params: [hash] });
1267
+ if (transactionReceipt) {
1268
+ const gasUsed = Number(transactionReceipt.gasUsed);
1269
+ totalGasUsed += gasUsed;
1270
+ }
1271
+ }
1272
+ console.log({ totalGasUsed });
1273
+ }
1144
1274
  return external;
1145
1275
  }
1146
1276
 
@@ -1150,7 +1280,7 @@ var import_commander = require("commander");
1150
1280
  // package.json
1151
1281
  var package_default = {
1152
1282
  name: "rocketh",
1153
- version: "0.10.0",
1283
+ version: "0.10.1",
1154
1284
  description: "deploy smart contract on ethereum-compatible networks",
1155
1285
  publishConfig: {
1156
1286
  access: "public"
@@ -1165,8 +1295,9 @@ var package_default = {
1165
1295
  devDependencies: {
1166
1296
  "@types/figlet": "^1.5.8",
1167
1297
  "@types/node": "^20.11.19",
1298
+ "@types/prompts": "^2.4.9",
1168
1299
  abitype: "^1.0.0",
1169
- "eip-1193": "^0.4.7",
1300
+ "eip-1193": "^0.5.0",
1170
1301
  "ipfs-gateway-emulator": "4.2.1-ipfs.2",
1171
1302
  rimraf: "^5.0.5",
1172
1303
  tsup: "^8.0.2",
@@ -1183,6 +1314,7 @@ var package_default = {
1183
1314
  ldenv: "^0.3.9",
1184
1315
  "named-logs": "^0.2.2",
1185
1316
  "named-logs-console": "^0.3.0",
1317
+ prompts: "^2.4.2",
1186
1318
  viem: "^2.7.11"
1187
1319
  },
1188
1320
  scripts: {
@@ -1200,5 +1332,5 @@ var commandName = package_default.name;
1200
1332
  var program = new import_commander.Command();
1201
1333
  program.name(commandName).version(package_default.version).usage(`${commandName}`).description("execute deploy scripts and store the deployments").option("-s, --scripts <value>", "path the folder containing the deploy scripts to execute").option("-t, --tags <value>", "comma separated list of tags to execute").option("-d, --deployments <value>", "folder where deployments are saved").requiredOption("-n, --network <value>", "network context to use").parse(process.argv);
1202
1334
  var options = program.opts();
1203
- loadAndExecuteDeployments({ ...options, logLevel: 1 });
1335
+ loadAndExecuteDeployments({ ...options, logLevel: 1, askBeforeProceeding: true, reportGasUse: true });
1204
1336
  //# sourceMappingURL=cli.cjs.map