Skip to content

Commit

Permalink
Merge pull request #6119 from NomicFoundation/network-plugin-cleanup
Browse files Browse the repository at this point in the history
Network plugin cleanup
  • Loading branch information
schaable authored Jan 14, 2025
2 parents c8adb6d + 26f7733 commit 7e815f5
Show file tree
Hide file tree
Showing 37 changed files with 477 additions and 426 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { SensitiveString } from "../../../../types/config.js";

export interface DefaultHDAccountsConfigParams {
initialIndex: number;
count: number;
path: string;
passphrase: SensitiveString;
}

export const DEFAULT_HD_ACCOUNTS_CONFIG_PARAMS: DefaultHDAccountsConfigParams =
{
initialIndex: 0,
count: 20,
path: "m/44'/60'/0'/0",
passphrase: "",
};
Original file line number Diff line number Diff line change
@@ -1,34 +1,18 @@
import type { SensitiveString } from "../../../../types/config.js";

import { HardhatError } from "@ignored/hardhat-vnext-errors";
import { bytesToHexString } from "@ignored/hardhat-vnext-utils/bytes";
import { mnemonicToSeedSync } from "ethereum-cryptography/bip39";
import { HDKey } from "ethereum-cryptography/hdkey";

const HD_PATH_REGEX = /^m(:?\/\d+'?)+\/?$/;

export interface DefaultHDAccountsConfigParams {
initialIndex: number;
count: number;
path: string;
passphrase: SensitiveString;
}

export const DEFAULT_HD_ACCOUNTS_CONFIG_PARAMS: DefaultHDAccountsConfigParams =
{
initialIndex: 0,
count: 20,
path: "m/44'/60'/0'/0",
passphrase: "",
};

export function derivePrivateKeys(
mnemonic: string,
hdpath: string,
initialIndex: number,
count: number,
passphrase: string,
): Buffer[] {
if (hdpath.match(HD_PATH_REGEX) === null) {
): string[] {
if (!HD_PATH_REGEX.test(hdpath)) {
throw new HardhatError(HardhatError.ERRORS.NETWORK.INVALID_HD_PATH, {
path: hdpath,
});
Expand All @@ -38,7 +22,7 @@ export function derivePrivateKeys(
hdpath += "/";
}

const privateKeys: Buffer[] = [];
const privateKeys: string[] = [];

for (let i = initialIndex; i < initialIndex + count; i++) {
const privateKey = deriveKeyFromMnemonicAndPath(
Expand All @@ -64,7 +48,7 @@ function deriveKeyFromMnemonicAndPath(
mnemonic: string,
hdPath: string,
passphrase: string,
): Buffer | undefined {
): string | undefined {
// NOTE: If mnemonic has space or newline at the beginning or end, it will be trimmed.
// This is because mnemonic containing them may generate different private keys.
const trimmedMnemonic = mnemonic.trim();
Expand All @@ -76,5 +60,5 @@ function deriveKeyFromMnemonicAndPath(

return derived.privateKey === null
? undefined
: Buffer.from(derived.privateKey);
: bytesToHexString(derived.privateKey);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import type {
EthereumProvider,
JsonRpcRequest,
JsonRpcResponse,
RequestArguments,
SuccessfulJsonRpcResponse,
} from "../../../types/providers.js";

import EventEmitter from "node:events";
import util from "node:util";

import { ensureError } from "@ignored/hardhat-vnext-utils/error";

export abstract class BaseProvider
extends EventEmitter
implements EthereumProvider
{
public abstract request(
requestArguments: RequestArguments,
): Promise<SuccessfulJsonRpcResponse["result"]>;
public abstract close(): Promise<void>;

public send(
method: string,
params?: unknown[],
): Promise<SuccessfulJsonRpcResponse["result"]> {
return this.request({ method, params });
}

public sendAsync(
jsonRpcRequest: JsonRpcRequest,
callback: (error: any, jsonRpcResponse: JsonRpcResponse) => void,
): void {
const handleJsonRpcRequest = async () => {
let jsonRpcResponse: JsonRpcResponse;
try {
const result = await this.request({
method: jsonRpcRequest.method,
params: jsonRpcRequest.params,
});
jsonRpcResponse = {
jsonrpc: "2.0",
id: jsonRpcRequest.id,
result,
};
} catch (error) {
ensureError(error);

if (!("code" in error) || error.code === undefined) {
throw error;
}

/* eslint-disable-next-line @typescript-eslint/restrict-template-expressions
-- Allow string interpolation of unknown `error.code`. It will be converted
to a number, and we will handle NaN cases appropriately afterwards. */
const errorCode = parseInt(`${error.code}`, 10);
jsonRpcResponse = {
jsonrpc: "2.0",
id: jsonRpcRequest.id,
error: {
code: !isNaN(errorCode) ? errorCode : -1,
message: error.message,
data: {
stack: error.stack,
name: error.name,
},
},
};
}

return jsonRpcResponse;
};

util.callbackify(handleJsonRpcRequest)(callback);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type {
ConfigurationResolver,
ConfigurationVariableResolver,
EdrNetworkAccountsConfig,
EdrNetworkAccountsUserConfig,
EdrNetworkChainConfig,
Expand All @@ -22,7 +22,7 @@ import {
normalizeHexString,
} from "@ignored/hardhat-vnext-utils/hex";

import { DEFAULT_HD_ACCOUNTS_CONFIG_PARAMS } from "./accounts/derive-private-keys.js";
import { DEFAULT_HD_ACCOUNTS_CONFIG_PARAMS } from "./accounts/constants.js";
import {
DEFAULT_EDR_NETWORK_HD_ACCOUNTS_CONFIG_PARAMS,
EDR_NETWORK_DEFAULT_COINBASE,
Expand All @@ -36,7 +36,7 @@ export function resolveGasConfig(value: GasUserConfig = "auto"): GasConfig {

export function resolveHttpNetworkAccounts(
accounts: HttpNetworkAccountsUserConfig | undefined = "remote",
resolveConfigurationVariable: ConfigurationResolver,
resolveConfigurationVariable: ConfigurationVariableResolver,
): HttpNetworkAccountsConfig {
if (Array.isArray(accounts)) {
return accounts.map((acc) => {
Expand Down Expand Up @@ -68,7 +68,7 @@ export function resolveEdrNetworkAccounts(
accounts:
| EdrNetworkAccountsUserConfig
| undefined = DEFAULT_EDR_NETWORK_HD_ACCOUNTS_CONFIG_PARAMS,
resolveConfigurationVariable: ConfigurationResolver,
resolveConfigurationVariable: ConfigurationVariableResolver,
): EdrNetworkAccountsConfig {
if (Array.isArray(accounts)) {
return accounts.map(({ privateKey, balance }) => {
Expand Down Expand Up @@ -102,20 +102,12 @@ export function resolveEdrNetworkAccounts(
export function resolveForkingConfig(
forkingUserConfig: EdrNetworkForkingUserConfig | undefined,
cacheDir: string,
resolveConfigurationVariable: ConfigurationResolver,
resolveConfigurationVariable: ConfigurationVariableResolver,
): EdrNetworkForkingConfig | undefined {
if (forkingUserConfig === undefined) {
return undefined;
}

const httpHeaders =
forkingUserConfig.httpHeaders !== undefined
? Object.entries(forkingUserConfig.httpHeaders).map(([name, value]) => ({
name,
value,
}))
: undefined;

return {
enabled: forkingUserConfig.enabled ?? true,
url: resolveConfigurationVariable(forkingUserConfig.url),
Expand All @@ -124,7 +116,7 @@ export function resolveForkingConfig(
forkingUserConfig.blockNumber !== undefined
? BigInt(forkingUserConfig.blockNumber)
: undefined,
httpHeaders,
httpHeaders: forkingUserConfig.httpHeaders,
};
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {
EdrContext,
GENERIC_CHAIN_TYPE,
genericChainProviderFactory,
L1_CHAIN_TYPE,
l1ProviderFactory,
OPTIMISM_CHAIN_TYPE,
optimismProviderFactory,
} from "@ignored/edr-optimism";

let _globalEdrContext: EdrContext | undefined;

export async function getGlobalEdrContext(): Promise<EdrContext> {
if (_globalEdrContext === undefined) {
_globalEdrContext = new EdrContext();
await _globalEdrContext.registerProviderFactory(
GENERIC_CHAIN_TYPE,
genericChainProviderFactory(),
);
await _globalEdrContext.registerProviderFactory(
L1_CHAIN_TYPE,
l1ProviderFactory(),
);
await _globalEdrContext.registerProviderFactory(
OPTIMISM_CHAIN_TYPE,
optimismProviderFactory(),
);
}

return _globalEdrContext;
}
Loading

0 comments on commit 7e815f5

Please sign in to comment.