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

Viem types improvements #6239

Closed
wants to merge 7 commits into from
Closed
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
53 changes: 31 additions & 22 deletions v-next/hardhat-viem/src/internal/chains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { hardhat, anvil, optimism } from "viem/chains";
-- TODO: this assertion should not be necessary */
const chains = Object.values(chainsModule) as ViemChain[];

const chainCache = new WeakMap<EthereumProvider, ViemChain>();
const chainIdCache = new WeakMap<EthereumProvider, number>();
const isHardhatNetworkCache = new WeakMap<EthereumProvider, boolean>();
const isAnvilNetworkCache = new WeakMap<EthereumProvider, boolean>();
Expand All @@ -26,47 +27,55 @@ export async function getChain(
provider: EthereumProvider,
chainType: ChainType | string,
): Promise<ViemChain> {
const cachedChain = chainCache.get(provider);
if (cachedChain !== undefined) {
return cachedChain;
}

const chainId = await getChainId(provider);

const chain = extractChain({
let chain = extractChain({
chains,
id: chainId,
});

if ((await isDevelopmentNetwork(provider)) || chain === undefined) {
if (await isHardhatNetwork(provider)) {
// TODO: We shoud improve how we handle the chains for the different chain
// types, as this is both a hardhat and an optimism chain.
//
// We are currently creating our chain based off optimism's, but that's
// not always the correct behavior, as the user may be connecting to
// a different chain.
if (chainType === "optimism") {
// TODO: We may need a better way to merge this info.
return { ...optimism, id: chainId };
chain = { ...optimism, id: chainId };
} else {
chain = {
...hardhat,
id: chainId,
};
}

return {
...hardhat,
id: chainId,
};
}

if (await isAnvilNetwork(provider)) {
return {
} else if (await isAnvilNetwork(provider)) {
chain = {
...anvil,
id: chainId,
};
}

// If the chain couldn't be found and we can't detect the development
// network we throw an error
if (chain === undefined) {
} else if (chain === undefined) {
// If the chain couldn't be found and we can't detect the development
// network we throw an error.
throw new HardhatError(HardhatError.ERRORS.VIEM.NETWORK_NOT_FOUND, {
chainId,
});
} else {
assertHardhatInvariant(
false,
"This should not happen, as we check in isDevelopmentNetwork that it's either hardhat or anvil",
);
}

assertHardhatInvariant(
false,
"This should not happen, as we check in isDevelopmentNetwork that it's either hardhat or anvil",
);
}

chainCache.set(provider, chain);

return chain;
}

Expand Down
6 changes: 3 additions & 3 deletions v-next/hardhat-viem/src/internal/clients.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type {
GetPublicClientReturnType,
PublicClientType,
GetWalletClientReturnType,
TestClient,
} from "../types.js";
Expand Down Expand Up @@ -28,7 +28,7 @@ export async function getPublicClient<ChainTypeT extends ChainType | string>(
provider: EthereumProvider,
chainType: ChainTypeT,
publicClientConfig?: Partial<ViemPublicClientConfig>,
): Promise<GetPublicClientReturnType<ChainTypeT>> {
): Promise<PublicClientType<ChainTypeT>> {
const chain =
publicClientConfig?.chain ?? (await getChain(provider, chainType));
const parameters = {
Expand All @@ -48,7 +48,7 @@ export async function getPublicClient<ChainTypeT extends ChainType | string>(

/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions --
We need to assert the type because TS gets confused with the conditional type */
return publicClient as GetPublicClientReturnType<ChainTypeT>;
return publicClient as PublicClientType<ChainTypeT>;
}

export async function getWalletClients<ChainTypeT extends ChainType | string>(
Expand Down
18 changes: 11 additions & 7 deletions v-next/hardhat-viem/src/internal/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ import { resolveLinkedBytecode } from "@ignored/hardhat-vnext-utils/bytecode";
import { ensureError } from "@ignored/hardhat-vnext-utils/error";
import { getContractAddress, getContract } from "viem";

import { getDefaultWalletClient, getPublicClient } from "./clients.js";
import { getDefaultWalletClient } from "./clients.js";

export async function deployContract<ContractName extends string>(
provider: EthereumProvider,
artifactManager: ArtifactManager,
defaultPublicClient: PublicClient,
contractName: ContractName,
constructorArgs: unknown[] = [],
deployContractConfig: DeployContractConfig = {},
Expand All @@ -47,8 +48,8 @@ export async function deployContract<ContractName extends string>(
});
}

const [publicClient, walletClient, { abi, bytecode }] = await Promise.all([
client?.public ?? getPublicClient(provider, "l1"),
const publicClient = client?.public ?? defaultPublicClient;
const [walletClient, { abi, bytecode }] = await Promise.all([
client?.wallet ?? getDefaultWalletClient(provider, "l1"),
getContractAbiAndBytecode(artifactManager, contractName, libraries),
]);
Expand Down Expand Up @@ -104,6 +105,7 @@ export async function deployContract<ContractName extends string>(
export async function sendDeploymentTransaction<ContractName extends string>(
provider: EthereumProvider,
artifactManager: ArtifactManager,
defaultPublicClient: PublicClient,
contractName: ContractName,
constructorArgs: unknown[] = [],
sendDeploymentTransactionConfig: SendDeploymentTransactionConfig = {},
Expand All @@ -116,8 +118,8 @@ export async function sendDeploymentTransaction<ContractName extends string>(
libraries = {},
...deployContractParameters
} = sendDeploymentTransactionConfig;
const [publicClient, walletClient, { abi, bytecode }] = await Promise.all([
client?.public ?? getPublicClient(provider, "l1"),
const publicClient = client?.public ?? defaultPublicClient;
const [walletClient, { abi, bytecode }] = await Promise.all([
client?.wallet ?? getDefaultWalletClient(provider, "l1"),
getContractAbiAndBytecode(artifactManager, contractName, libraries),
]);
Expand Down Expand Up @@ -167,12 +169,14 @@ export async function sendDeploymentTransaction<ContractName extends string>(
export async function getContractAt<ContractName extends string>(
provider: EthereumProvider,
artifactManager: ArtifactManager,
defaultPublicClient: PublicClient,
contractName: ContractName,
address: ViemAddress,
getContractAtConfig: GetContractAtConfig = {},
): Promise<ContractReturnType<ContractName>> {
const [publicClient, walletClient, artifact] = await Promise.all([
getContractAtConfig.client?.public ?? getPublicClient(provider, "l1"),
const publicClient =
getContractAtConfig.client?.public ?? defaultPublicClient;
const [walletClient, artifact] = await Promise.all([
getContractAtConfig.client?.wallet ??
getDefaultWalletClient(provider, "l1"),
artifactManager.readArtifact(contractName),
Expand Down
2 changes: 1 addition & 1 deletion v-next/hardhat-viem/src/internal/hook-handlers/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default async (): Promise<Partial<NetworkHooks>> => {
) {
const connection: NetworkConnection<ChainTypeT> = await next(context);

connection.viem = initializeViem(
connection.viem = await initializeViem(
connection.chainType,
connection.provider,
context.artifacts,
Expand Down
11 changes: 9 additions & 2 deletions v-next/hardhat-viem/src/internal/initialization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@ import {
sendDeploymentTransaction,
} from "./contracts.js";

export function initializeViem<ChainTypeT extends ChainType | string>(
export async function initializeViem<ChainTypeT extends ChainType | string>(
chainType: ChainTypeT,
provider: EthereumProvider,
artifactManager: ArtifactManager,
): HardhatViemHelpers<ChainTypeT> {
): Promise<HardhatViemHelpers<ChainTypeT>> {
const defaultPublicClient = await getPublicClient(provider, chainType);

return {
publicClient: defaultPublicClient,

getPublicClient: (publicClientConfig) =>
getPublicClient(provider, chainType, publicClientConfig),

Expand All @@ -37,6 +41,7 @@ export function initializeViem<ChainTypeT extends ChainType | string>(
deployContract(
provider,
artifactManager,
defaultPublicClient,
contractName,
constructorArgs,
deployContractConfig,
Expand All @@ -50,6 +55,7 @@ export function initializeViem<ChainTypeT extends ChainType | string>(
sendDeploymentTransaction(
provider,
artifactManager,
defaultPublicClient,
contractName,
constructorArgs,
sendDeploymentTransactionConfig,
Expand All @@ -59,6 +65,7 @@ export function initializeViem<ChainTypeT extends ChainType | string>(
getContractAt(
provider,
artifactManager,
defaultPublicClient,
contractName,
address,
getContractAtConfig,
Expand Down
8 changes: 5 additions & 3 deletions v-next/hardhat-viem/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ import type {
export interface HardhatViemHelpers<
ChainTypeT extends ChainType | string = DefaultChainType,
> {
publicClient: PublicClientType<ChainTypeT>;

/**
* Creates a public client configured with the provided settings.
*
Expand All @@ -42,7 +44,7 @@ export interface HardhatViemHelpers<
*/
getPublicClient: (
publicClientConfig?: Partial<ViemPublicClientConfig>,
) => Promise<GetPublicClientReturnType<ChainTypeT>>;
) => Promise<PublicClientType<ChainTypeT>>;
/**
* Creates a wallet client configured with the provided settings for each
* account in the provider.
Expand Down Expand Up @@ -135,7 +137,7 @@ export interface HardhatViemHelpers<
) => Promise<ContractReturnType<ContractName>>;
}

export type GetPublicClientReturnType<ChainTypeT extends ChainType | string> =
export type PublicClientType<ChainTypeT extends ChainType | string> =
ChainTypeT extends "optimism" ? OpPublicClient : PublicClient;

export type GetWalletClientReturnType<ChainTypeT extends ChainType | string> =
Expand All @@ -146,7 +148,7 @@ export type PublicClient = ViemPublicClient<ViemTransport, ViemChain>;
export type OpPublicClient = ViemClient<
ViemTransport,
ViemChain,
ViemAccount,
undefined,
ViemRpcSchema,
ViemPublicActions<ViemTransport, ViemChain, ViemAccount> &
ViemOpStackPublicActionsL2<ViemChain, ViemAccount>
Expand Down
1 change: 1 addition & 0 deletions v-next/hardhat-viem/test/fixture-projects/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/*/cache
5 changes: 4 additions & 1 deletion v-next/hardhat-viem/test/hook-handlers/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ describe("hook-handlers/network", () => {

it("should be extended with viem", () => {
assert.ok(isObject(connection.viem), "viem should be defined");

assert.ok(
isObject(connection.viem.publicClient),
"viem should have publicClient object",
);
assert.ok(
typeof connection.viem.getPublicClient === "function",
"viem should have a getPublicClient function",
Expand Down
Loading