Skip to content

Commit 87a83d9

Browse files
authored
Merge pull request #4531 from NomicFoundation/update-viem-guide
Update viem guide with the latest blogpost info
2 parents cf38c1a + f6e6153 commit 87a83d9

File tree

1 file changed

+24
-109
lines changed

1 file changed

+24
-109
lines changed

docs/src/content/hardhat-runner/docs/advanced/using-viem.md

+24-109
Original file line numberDiff line numberDiff line change
@@ -4,90 +4,26 @@
44

55
Most of this documentation assumes that you are using [ethers](https://docs.ethers.org/v6/) as your connection library, but you can also use Hardhat with [Viem](https://viem.sh/docs/introduction.html), a more lightweight and type-safe alternative. This guide explains how to setup a project that uses [the Viem-based Toolbox](/hardhat-runner/plugins/nomicfoundation-hardhat-toolbox-viem) instead of the main one.
66

7-
## Installation
7+
## Quick start
88

9-
To kickstart a Hardhat project with Typescript and Viem, you can follow these steps:
9+
To create a new Hardhat project with Viem, initialize a project as [you normally do](/hardhat-runner/docs/guides/project-setup), but select the _“Create a TypeScript project (with Viem)”_ option.
1010

11-
1. Initialize a new npm project in an empty directory:
12-
13-
::::tabsgroup{options="npm 7+,npm 6,yarn"}
14-
15-
:::tab{value="npm 7+"}
16-
17-
```
18-
npm init -y
19-
```
20-
21-
:::
22-
23-
:::tab{value="npm 6"}
24-
25-
```
26-
npm init -y
27-
```
28-
29-
:::
30-
31-
:::tab{value="yarn"}
32-
33-
```
34-
yarn init -y
35-
```
36-
37-
:::
38-
39-
::::
40-
41-
2. Install `hardhat`:
42-
43-
::::tabsgroup{options="npm 7+,npm 6,yarn"}
44-
45-
:::tab{value="npm 7+"}
46-
47-
```
48-
npm i hardhat
49-
```
50-
51-
:::
52-
53-
:::tab{value="npm 6"}
54-
55-
```
56-
npm i hardhat
57-
```
58-
59-
:::
60-
61-
:::tab{value="yarn"}
62-
63-
```
64-
yarn add hardhat
65-
```
66-
67-
:::
68-
69-
::::
70-
71-
3. Run `npx hardhat init` and select the _Create a TypeScript project (with Viem)_ option.
72-
73-
**Note:** you might want to pin Viem-related dependencies because Viem does not strictly follow semantic versioning for type changes. You can read more [here](#managing-types-and-version-stability).
74-
75-
## Quick Start
11+
You can also try `hardhat-viem` in an existing project, even if it uses `hardhat-ethers`, since both plugins are compatible. To do this, just install the `@nomicfoundation/hardhat-viem` package and add it to your config.
7612

7713
### Clients
7814

79-
Viem provides a set of interfaces to interact with the blockchain. The `hardhat-viem` plugin wraps these interfaces and pre-configures them based on your Hardhat project settings, offering a more Hardhat-friendly experience.
15+
Viem provides a set of interfaces to interact with the blockchain. `hardhat-viem` wraps and auto-configures these based on your Hardhat project settings for a seamless experience.
8016

81-
These interfaces are called **clients**, and each one is tailored to a specific type of interaction:
17+
These **clients** are tailored for specific interactions:
8218

83-
- The **Public Client** is an interface to the "public” JSON-RPC API methods used to retrieve information from a node.
84-
- The **Wallet Client** is an interface to interact with Ethereum Accounts used to retrieve accounts, execute transactions, sign messages, etc.
85-
- The **Test Client** is an interface to the "test" JSON-RPC API methods used to perform actions that are only possible when connecting to a development node.
19+
- **Public Client** fetches node information from the public” JSON-RPC API.
20+
- **Wallet Client** interacts with Ethereum Accounts for tasks like transactions and message signing.
21+
- **Test Client** performs actions that are only available in development nodes.
8622

87-
To start using the client interfaces, you need to import the Hardhat Runtime Environment. You can then access them through the `viem` property of the `hre` object. In the following example, we will demonstrate how to use the public and wallet clients to log the balance of an account and then send a transaction. Follow these steps:
23+
You can access clients via `hre.viem`. Read our documentation to learn more about the [HRE](/hardhat-runner/docs/advanced/hardhat-runtime-environment). Find below an example of how to use the public and wallet clients:
8824

8925
1. Create a `scripts/clients.ts` inside your project directory.
90-
2. Copy and paste the following code snippet into your `scripts/clients.ts` file:
26+
2. Add this code to `scripts/clients.ts`:
9127

9228
```tsx
9329
import { parseEther, formatEther } from "viem";
@@ -98,61 +34,42 @@ To start using the client interfaces, you need to import the Hardhat Runtime Env
9834
await hre.viem.getWalletClients();
9935

10036
const publicClient = await hre.viem.getPublicClient();
101-
const balanceBefore = await publicClient.getBalance({
37+
const bobBalance = await publicClient.getBalance({
10238
address: bobWalletClient.account.address,
10339
});
10440

10541
console.log(
10642
`Balance of ${bobWalletClient.account.address}: ${formatEther(
107-
balanceBefore
43+
bobBalance
10844
)} ETH`
10945
);
11046

11147
const hash = await bobWalletClient.sendTransaction({
11248
to: aliceWalletClient.account.address,
11349
value: parseEther("1"),
11450
});
115-
116-
const tx = await publicClient.waitForTransactionReceipt({ hash });
117-
118-
console.log(
119-
`Transaction from ${tx.from} to ${tx.to} mined in block ${tx.blockNumber}`
120-
);
121-
122-
const balanceAfter = await publicClient.getBalance({
123-
address: bobWalletClient.account.address,
124-
});
125-
126-
console.log(
127-
`Balance of ${bobWalletClient.account.address}: ${formatEther(
128-
balanceAfter
129-
)} ETH`
130-
);
51+
await publicClient.waitForTransactionReceipt({ hash });
13152
}
13253

13354
main()
134-
.then(() => {
135-
process.exit();
136-
})
55+
.then(() => process.exit())
13756
.catch((error) => {
13857
console.error(error);
13958
process.exit(1);
14059
});
14160
```
14261

143-
3. Open your terminal and run `npx hardhat run scripts/clients.ts` to execute the script.
144-
145-
This will run the code and display the results in your terminal.
62+
3. Run `npx hardhat run scripts/clients.ts`.
14663

14764
For more detailed documentation on clients, you can visit the [hardhat-viem plugin site](/hardhat-runner/plugins/nomicfoundation-hardhat-viem#clients) and [Viem's official site](https://viem.sh/docs/clients/intro.html).
14865

14966
### Contracts
15067

151-
In addition to the client interfaces, Viem provides functionality for interacting with contracts. The `hardhat-viem` plugin once again provides wrappers for the most useful methods. Additionally, it offers **type generation** for all your contracts, enhancing type checking and suggestions within your IDE!
68+
Viem also provides functionality for interacting with contracts, and `hardhat-viem` provides wrappers for the most useful methods. Plus, it generates types for your contracts, enhancing type-checking and IDE suggestions.
15269

153-
To access contract methods, import the Hardhat Runtime Environment and use the `viem` property of the `hre` object, similar to how you access clients. In the following example, we'll obtain an instance of an existing contract to call one of its methods, and then use the retrieved value to deploy a different contract. Follow these steps:
70+
Use the `hre.viem` object to get these helpers, similar to how clients are used. The next example shows how to get a contract instance and call one of its methods:
15471

155-
1. Create a Solidity contract named `MyToken.sol` inside your project's `contract` directory and paste the following snippet:
72+
1. Create a `MyToken.sol` file inside your projects `contracts` directory:
15673

15774
```solidity
15875
// SPDX-License-Identifier: MIT
@@ -176,8 +93,8 @@ To access contract methods, import the Hardhat Runtime Environment and use the `
17693
}
17794
```
17895

179-
2. Compile your Solidity contract by running `npx hardhat compile`. This will generate the types for your contract inside the `artifacts` folder of your project.
180-
3. Create a `contracts.ts` inside your project's `scripts` directory with the following content:
96+
2. Run `npx hardhat compile` to compile your contracts and produce types in the `artifacts` directory.
97+
3. Create a `contracts.ts` inside the `scripts` directory:
18198

18299
```tsx
183100
import hre from "hardhat";
@@ -205,9 +122,7 @@ To access contract methods, import the Hardhat Runtime Environment and use the `
205122
});
206123
```
207124

208-
4. Open your terminal and run `npx hardhat run scripts/contracts.ts` to execute the script.
209-
210-
This will deploy the `MyToken` contract, use the `increaseSupply()` function to increase the initial supply, and display the result in your terminal.
125+
4. Open your terminal and run `npx hardhat run scripts/contracts.ts`. This will deploy the `MyToken` contract, call the `increaseSupply()` function, and display the new supply in your terminal.
211126

212127
#### Contract Type Generation
213128

@@ -231,9 +146,9 @@ If you want to learn more about working with contracts, you can visit the [`hard
231146

232147
### Testing
233148

234-
In this example, we'll demonstrate how to write tests for the `MyToken` contract defined earlier. These tests cover scenarios like increasing supply and ensuring that certain operations revert as expected.
149+
In this example, well test the `MyToken` contract, covering scenarios like supply increase and expected operation reverts.
235150

236-
1. Create a `test/my-token.ts` file inside your project's directory an copy the following code snippet:
151+
1. Create a `test/my-token.ts` file:
237152

238153
```tsx
239154
import hre from "hardhat";
@@ -277,7 +192,7 @@ In this example, we'll demonstrate how to write tests for the `MyToken` contract
277192
});
278193
```
279194

280-
2. Open your terminal and run `npx hardhat test` to run your tests.
195+
2. Open your terminal and run `npx hardhat test` to run these tests.
281196

282197
### Managing Types and Version Stability
283198

0 commit comments

Comments
 (0)