从零开始构建你的第一个DApp,以太坊开发实战教程
以太坊,作为智能合约平台的先驱,为去中心化应用(Dapps)的开发提供了强大的基础设施,如果你对区块链技术充满热情,渴望亲手构建一个属于自己的去中心化应用,那么这份以太坊开发实战教程将为你铺平道路,我们将从环境搭建开始,一步步带你走过智能合约编写、测试、部署以及与前端交互的全过程。

开发环境准备:工欲善其事,必先利其器
在开始之前,我们需要准备一系列开发工具:
-
Node.js 和 npm/yarn: 以太坊开发广泛使用JavaScript/TypeScript,Node.js是运行时环境,npm(或更快的yarn)是包管理工具。
- 下载安装:Node.js官网 (建议LTS版本)
-
代码编辑器: Visual Studio Code (VS Code) 是目前最受欢迎的选择,配合丰富的插件库,开发效率倍增。
推荐插件:Solidity (由Juan Blanco开发,提供语法高亮、智能提示)、Prettier (代码格式化)、Hardhat (后续会介绍,提供开发环境集成)
-
以太坊客户端/钱包:
- MetaMask: 浏览器插件钱包,是开发者和用户与以太坊交互的必备工具,用于管理账户、私钥,以及与测试网和主网上的DApp进行交互。
- 安装:MetaMask官网
- MetaMask: 浏览器插件钱包,是开发者和用户与以太坊交互的必备工具,用于管理账户、私钥,以及与测试网和主网上的DApp进行交互。
-
Truffle Suite / Hardhat: 这是以太坊最主流的两个智能合约开发框架,它们简化了编译、测试、部署等流程。
- Truffle: 成熟稳定,文档丰富,适合初学者。
- Hardhat: 更现代,插件生态更活跃,开发体验更好,性能更优。
- 本教程后续将以Hardhat为例进行讲解。
-
Ganache: 个人区块链,可以为开发提供私有的、可即时确认的交易环境,方便本地测试和调试。
- 下载安装:Ganache官网
你的第一个智能合约:Hello, Solidity!
智能合约是以太坊DApp的核心,它是一段部署在区块链上的、自动执行的代码,我们使用Solidity语言来编写。
-
创建Hardhat项目:
mkdir my-first-dapp cd my-first-dapp npm init -y npm install --save-dev hardhat npx hardhat
在交互式命令中,选择"Create a basic sample project",然后一路回车(或根据提示选择),Hardhat会帮你生成一个基础项目结构,包括
contracts/、scripts/、test/等目录。
-
编写合约: 打开
contracts/目录下的Lock.sol(Hardhat默认示例),我们将它改成一个简单的"HelloWorld"合约,或者更实用一点的"简单存储合约":// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title SimpleStorage * @dev 一个简单的存储合约,可以存储和获取一个uint256类型的数字 */ contract SimpleStorage { uint256 private myNumber; // 存储数字 function set(uint256 _newNumber) public { myNumber = _newNumber; } // 获取数字 function get() public view returns (uint256) { return myNumber; } } -
编译合约: 在项目根目录下运行:
npx hardhat compile
成功编译后,你会在
artifacts/目录下看到编译生成的ABI(应用二进制接口)和字节码文件,ABI是与合约交互的接口规范。
测试你的智能合约
测试是保证智能合约质量的关键环节,Hardhat支持使用Mocha和Chai(JavaScript测试框架)进行合约测试。
-
编写测试用例: 打开
test/目录下的lock.js,修改或重写测试文件:const { expect } = require("chai"); const { ethers } = require("hardhat"); describe("SimpleStorage", function () { it("Should store the value 89.", async function () { const SimpleStorage = await ethers.getContractFactory("SimpleStorage"); const simpleStorage = await SimpleStorage.deploy(); await simpleStorage.deployed(); await simpleStorage.set(89); const storedValue = await simpleStorage.get(); expect(storedValue).to.equal(89); }); }); -
运行测试:
npx hardhat test
Hardhat会启动一个临时的测试网络,部署你的合约,并执行测试用例,如果测试通过,说明你的合约逻辑基本正确。
部署智能合约到测试网
本地测试没问题后,我们可以将合约部署到以太坊的测试网(如Ropsten, Goerli, Sepolia),这些网络是免费的,供开发者测试。
-
获取测试ETH: 测试网ETH没有实际价值,但需要支付 gas 费,你可以从"水龙头"(Faucet)网站获取免费测试ETH。
- Goerli水龙头 (需要GitHub账号登录)
-
配置Hardhat连接测试网: 在项目根目录创建
.env文件,存储你的私钥(注意:不要将私钥提交到代码仓库!)和测试网RPC URL:
PRIVATE_KEY=你的MetaMask测试账户私钥 GOERLI_RPC_URL=https://goerli.infura.io/v3/你的Infura项目ID你可以在Infura注册免费项目获取RPC URL。
-
安装部署依赖:
npm install --save-dev dotenv @nomicfoundation/hardhat-toolbox
并修改
hardhat.config.js,引入插件并配置网络:require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ module.exports = { solidity: "0.8.9", networks: { goerli: { url: process.env.GOERLI_RPC_URL, accounts: [process.env.PRIVATE_KEY], }, }, }; -
编写部署脚本: 在
scripts/目录下创建deploy.js:async function main() { const SimpleStorage = await ethers.getContractFactory("SimpleStorage"); const simpleStorage = await SimpleStorage.deploy(); await simpleStorage.deployed(); console.log("SimpleStorage deployed to:", simpleStorage.address); } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); -
执行部署:
npx hardhat run scripts/deploy.js --network goerli
部署成功后,你会看到合约地址,请记下这个地址,我们将在前端与它交互。
构建前端与智能合约交互
我们来创建一个简单的前端页面,调用我们部署好的智能合约。
-
安装前端依赖:
npm install ethers npm install --save-dev vite @vitejs/plugin-react
创建
vite.config.js配置React项目:import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], })在
package.json中添加启动脚本:"scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" }, -
创建React组件: 在
src/目录下创建App.jsx:import { useState, useEffect } from 'react'; import { ethers } from 'ethers'; import SimpleStorageAbi from './artifacts/contracts/SimpleStorage.sol/SimpleStorage.json'; // 确保路径正确 function App() { const [contract, setContract] = useState(null); const [provider, setProvider] = useState(null); const [account, setAccount] = useState(''); const [number, setNumber] = useState(''); const [storedNumber, setStoredNumber] = useState(''); useEffect(() => { const init = async () => { if (typeof window.ethereum !== 'undefined') {
本文 原创,转载保留链接!网址:https://licai.bangqike.com/bixun/1394724.html
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。






