# 极简Solidity开发入门 **Published by:** [Safu](https://paragraph.com/@yoomin/) **Published on:** 2022-05-30 **URL:** https://paragraph.com/@yoomin/solidity ## Content 本文目的很简单, 搭建一个基本的Solidity开发环境, 包含前后端, 实现基本的合约交互方便, 以学习Solidity. Let‘s go! 第一步, 安装运行Hardhat这是什么? Hardhat是一个Solidity的集成开发环境, 包含运行在本地的Blockchain的EVM(类比于生产环境的EVM公链)、JSON-PRC服务用于和前端通信(类比于生产环境的Infura等节点同步服务提供商), 以及测试、部署等服务 https://hardhat.org/提前建立好项目文件夹❯ mkdir hardhat-intro ❯ cd hradhat-intro 在该文件夹下:选择‘Create an advanced sample project that uses TypeScript’, 剩下的一路next/yes即可 第二步, 运行本地节点&部署合约初始目录结构这里, contracts包含需要部署的合约(注意, 这里合约和.sol文件可能并不是一一对应的关系); scripts包含hardhat部署合约时需要的文件; test则是测试相关文件. 接下来我们让hardhat跑起一个本地EVM区块链or❯ ./node_modules/.bin/hardhat node 做了什么? 这里hardhat在本地运行了一个EVM区块链(称为hardhat network), 并提供了与其通信的JSON-RPC服务 ’Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/‘ 有什么不一样? hardhat network默认交互才产出区块, 也可以设置定时出块; 同时提供了错误栈的输出.新开终端窗口, 我们把自带的Greeter.sol部署到这个本地区块链中:❯ npx hardhat run --network localhost ./scripts/deploy.ts 可以看出hardhat完成了合约的编译(生成了artifact文件, 输出了合约地址);❯ npx hardhat run --network localhost ./scripts/deploy.ts Downloading compiler 0.8.4 Generating typings for: 2 artifacts in dir: typechain for target: ethers-v5 Successfully generated 5 typings! Compiled 2 Solidity files successfully Greeter deployed to: 0x5FbDB2315678afecb367f032d93F642f64180aa3 同时运行node的终端窗口也输出了相关信息. Contract deployment: Greeter Contract address: 0x5fbdb2315678afecb367f032d93f642f64180aa3 Transaction: 0x7269d154f4fe421d28cd94b0f36485036b4fd82a48d623148c2d61c1484e42b2 From: 0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266 Value: 0 ETH Gas used: 497026 of 497026 Block #1: 0x48de628ad9758862292b079c9e24c28d156922e8271e5fbd0f0c8470dc4bbfd3 console.log: Deploying a Greeter with greeting: Hello, Hardhat! 到这里hardhat的部分就完成了, 我们进行前端的设置. 第三步, metamask链接本地JSON-PRC网络 打开metamask, 进入Settings → Networks, 添加如下网络(该网络已经内置, 所以只需要修改参数即可)完成后就相当于连接到了hardhat网络 接下来导入账号, 使用运行hardhat node的窗口, 默认提供了20个测试账号, 我们选择第一个Account #0: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 (10000 ETH) Private Key: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80选择右上角 → Import Account, 输入Private Key账号就成功导入了 第四步, 前端合约交互 选择你喜欢的框架, 这里我们使用create-react-app❯ npx create-react-app hardhat-playground-fe --template typescript 这里直接贴出App.tsx的代码: https://gist.github.com/KobiMaster/889e494811f127713351c0c6fbf8fb16 注意合约初始化里的abi和合约地址, 这些都要去hardhat生成的文件和终端输出里拿到. 至此就全部完成了! Keep Build! 推荐阅读: https://solidity-by-example.org/hello-world ## Publication Information - [Safu](https://paragraph.com/@yoomin/): Publication homepage - [All Posts](https://paragraph.com/@yoomin/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@yoomin): Subscribe to updates - [Twitter](https://twitter.com/Yoomin95709132): Follow on Twitter