以太坊作为全球领先的智能合约平台和去中心化应用(DApps)的底层操作系统,为开发者提供了构建去中心化金融(DeFi)、非同质化代币(NFT)、游戏、社交等众多创新应用的可能性,本文将为你提供一份详尽的有以太坊开发攻略,从环境搭建到智能合约编写,再到DApp前端集成与部署,助你一步步踏入Web3开发的世界。

以太坊作为全球领先的智能合约平台和去中心化应用(DApps)的底层操作系统,为开发者提供了构建去中心化金融(DeFi)、非同质化代币(NFT)、游戏、社交等众多创新应用的可能性,本文将为你提供一份详尽的有以太坊开发攻略,从环境搭建到智能合约编写,再到DApp前端集成与部署,助你一步步踏入Web3开发的世界。

以太坊开发基础认知
在开始编码之前,理解一些核心概念至关重要:
开发环境搭建
安装Node.js 和 npm/yarn:
npm install -g yarn)。安装代码编辑器:
Solidity by Juan Blanco:Solidity语言支持、语法高亮、编译错误提示。Prettier - Code formatter:代码格式化。ESLint:JavaScript代码检查。Hardhat for VS Code:Hardhat集成(如果使用Hardhat)。安装以太坊客户端/开发环境:
npx hardhat,然后按照提示初始化项目。npm install -g truffle,然后truffle init初始化项目。安装MetaMask:
智能合约开发 (以Solidity + Hardhat为例)
创建智能合约项目:
mkdir my-ethereum-dapp cd my-ethereum-dapp npx hardhat init # 选择 "Create a basic sample project",选择JavaScript/TypeScript,安装依赖
编写智能合约:
在 contracts/ 目录下创建新的Solidity文件,SimpleStorage.sol。
Solidity合约结构:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract SimpleStorage {
uint256 private storedData;
function set(uint256 x) public {
storedData = x;
}
function get() public view returns (uint256) {
return storedData;
}
}
关键字说明:
pragma solidity ^0.8.20;:指定Solidity编译器版本。contract:定义合约。uint256:无符号256位整数。public:修饰函数,表示外部可调用。view:表示函数只读取状态,不修改,执行不消耗Gas(由调用方支付)。returns:指定函数返回类型。编译智能合约:
scripts/ 目录下生成编译脚本。npx hardhat compile,编译成功后,合约的ABI(Application Binary Interface)和字节码会生成在 artifacts/ 目录下,ABI是前端与合约交互的接口。编写测试脚本:
在 test/ 目录下编写测试脚本,使用JavaScript/TypeScript和Mocha/Chai等测试框架。
示例 (simpleStorage.test.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 value = await simpleStorage.get();
expect(value).to.equal(89);
});
});
运行测试:npx hardhat test。
智能合约部署
配置部署脚本:
在 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);
});
连接到以太坊网络:
在 hardhat.config.js 中配置网络:
require("@nomicfoundation/hardhat-toolbox");
const PRIVATE_KEY = "YOUR_PRIVATE_KEY_HERE"; // 测试账户私钥
const RPC_URL = "YOUR_LOCAL_RPC_URL_OR_TESTNET_RPC_URL"; // 如 Ganache的RPC URL或Infura/Alchemy的测试网URL
module.exports = {
solidity: "0.8.20",
networks: {
hardhat: {},
// sepolia: {
// url: RPC_URL,
// accounts: [PRIVATE_KEY]
// }
},
};
本地测试网:默认使用Hardhat Network或Ganache。
公共测试网(如Sepolia):需要从Infura或Alchemy获取RPC URL,并拥有测试网ETH(可通过水龙头获取)。
执行部署:
npx hardhat run scripts/deploy.js --network hardhatnpx hardhat run scripts/deploy.js --network sepolia (确保配置了sepolia网络且账户有ETH)DApp前端开发与交互
创建前端项目:
npx create-react-app frontend cd frontend npm install ethers
连接MetaMask:
在React组件中,使用ethers库连接MetaMask:
import { ethers } from "ethers";
async function connectWallet() {
if (window.ethereum) {
try {
await window.ethereum.request({ method: 'eth_requestAccounts' });
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const address = await signer.getAddress();
console.log("Connected address:", address);
// 更新UI状态