Local Develop Env
Author of this section: @Fish
in the previous course, we tried to develop contracts through CloudIDE based on Remix. In the local development environment, we can use more tools to improve development efficiency, such as using Git for version management. This lecture will guide you through developing and debugging contracts locally, as well as writing unit tests to verify the logic of smart contracts.
Initialize project
the Ethereum ecosystem is rich in development tools, such Hardhat , Foundry wait. Here we will use Hardhat to set up a local development environment and migrate the contracts developed before this course to the local environment.
We refer hardhat's Quick Start Document execute the following command to quickly initialize a project:
mkdir demo-contract
cd demo-contract
npx hardhat@2.22.3 init
and chapter I initializing the Next.js project is similar, npx
it is a command that comes with Node.js after the installation is completed. The above command will be downloaded automatically. hardhat npm package and execute init
order. Use 2.22.3
Version because it is the latest version of this course at the time of writing, so you can ensure that your environment is consistent with this course. Of course, you can also remove the version number and use the latest version.
We chose the third option, using Typescript + viem, which is consistent with the technology stack of our previous courses.
After creation you will get the following directory structure:
the role of each part of the file is as follows:
contracts
: Store the Solidity contract code.test
: Store the test code.ignition
: Contract deployment scripts, such as parameters that define contract deployment.hardhat.config.ts
the Hardhat configuration file.
Local development and debugging
dependencies are automatically installed when the project is initialized. If they are not installed, they can be executed. npm I
try again. After the installation is complete, execute the following command to compile the contract:
npx hardhat compile
execute the following command to execute the test sample:
npx hardhat test
then run the following command to start a Test network locally for debugging:
npx hardhat node
After startup, you will see that some addresses will be assigned to you by default for debugging. Next, you can deploy the contract to the local node:
npx hardhat ignition deploy ./ignition/modules/Lock.ts --network localhost
after the deployment is successful, you can see the relevant transaction information in the local test network log:
at this point, our local environment has been set up. Next, we will try to put the NFT written before into the local environment and debug it.
Migration Contract
we will use the contract code of the previous course MyToken.sol copy it and put it in contracts
under the Directory, delete the original Lock.sol
sample code.
The contract relies on @openzeppelin/contracts
we need to install this dependency:
npm install @openzeppelin/contracts --save
we refer test/Lock.ts
also write a test file test/MyToken.ts
, as follows:
import { loadFixture } from "@nomicfoundation/hardhat-toolbox-viem/network-helpers";
import { expect } from "chai";
import hre from "hardhat";
describe("MyToken", function () {
async function deployFixture() {
const token = await hre.viem.deployContract("MyToken");
return {
token,
};
}
describe("ERC721", function () {
describe("name", function () {
it("Get NFT name", async function () {
const { token } = await loadFixture(deployFixture);
expect(await token.read.name()).to.equal("MyToken");
});
});
});
});
The test sample calls the contract's name
method to get the name of NFT. name
is the method of the NFT contract defined in the ERC721 specification.
We continue to add ignition/modules/MyToken.ts
for deployment, as follows:
import { buildModule } from "@nomicfoundation/hardhat-ignition/modules";
const MyTokenModule = buildModule("MyTokenModule", (m) => {
const lock = m.contract("MyToken");
return { lock };
});
export default MyTokenModule;
execution npx hardhat test
test the contract, which automatically compiles the contract.
Then we execute the following command to deploy the contract:
npx hardhat ignition deploy ./ignition/modules/MyToken.ts --network localhost
after the deployment is successful, we try to call the contract in the previous NFT project. Please refer to the previous course to start the front-end project of Next.js.
Add a Hardhat
network:
- import { mainnet, sepolia, polygon } from "wagmi/chains";
+ import { mainnet, sepolia, polygon, hardhat } from "wagmi/chains";
import {
WagmiWeb3ConfigProvider,
MetaMask,
Sepolia,
Polygon,
+ Hardhat,
WalletConnect,
} from "@ant-design/web3-wagmi";
// ...
const config = createConfig({
- chains: [mainnet, sepolia, polygon],
+ chains: [mainnet, sepolia, polygon, hardhat],
transports: {
[mainnet.id]: http(),
[sepolia.id]: http(),
[polygon.id]: http(),
+ [hardhat.id]: http("http://127.0.0.1:8545/"),
},
connectors: [
injected({
target: "metaMask",
}),
walletConnect({
projectId: "c07c0051c2055890eade3556618e38a6",
showQrModal: false,
}),
],
});
const contractInfo = [
{
id: 1,
name: "Ethereum",
contractAddress: "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512",
},
{
id: 5,
name: "Sepolia",
contractAddress: "0x418325c3979b7f8a17678ec2463a74355bdbe72c",
},
{
id: 137,
name: "Polygon",
contractAddress: "0x418325c3979b7f8a17678ec2463a74355bdbe72c",
},
+ {
+ id: hardhat.id,
+ name: "Hardhat",
+ contractAddress: "0x5FbDB2315678afecb367f032d93F642f64180aa3", // 这里需要替换为你本地部署后获得的地址
+ },
];
// ...
export default function Web3() {
return (
<WagmiWeb3ConfigProvider
config={config}
wallets={[MetaMask(), WalletConnect()]}
eip6963={{
autoAddInjectedWallets: true,
}}
chains={[
Sepolia,
Polygon,
+ Hardhat,
]}
>
<Address format address="0xEcd0D12E21805803f70de03B72B1C162dB0898d9" />
<NFTCard
address="0xEcd0D12E21805803f70de03B72B1C162dB0898d9"
tokenId={641}
/>
<Connector>
<ConnectButton />
</Connector>
<CallTest />
</WagmiWeb3ConfigProvider>
);
}
correspondingly, you need to add the network in MetaMask:
you can use npx hardhat node
The private key displayed on the console at startup is imported into the Test account MetaMask to feel the happiness of having 10000ETH.
Then open the locally launched Frontend Page http://localhost:3000/web3 , switch the network to Hardhat, you can happily Mint NFT.
It should be noted that if you restart the local Hardhat test network, you may see that the MetaMask connection to the local RPC is similar. Received invalid block tag 1. Latest block number is 0
for such errors, you need to click in MetaMask's account advanced settings. Clear activity and nonce data
to fix the problem.