Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Network plugin cleanup #6119

Merged
merged 18 commits into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading