:2026-03-15 14:06 点击:3
以太坊作为全球领先的智能合约平台,不仅仅是一种加密货币,更是一个去中心化的应用(DApp)开发平台,它允许开发者构建和运行无需信任第三方、公开透明、抗审查的应用程序,本教程将带你从零开始,逐步了解并实践如何制作一个简单的以太坊应用(DApp)。
了解基础知识:以太坊是什么?
在动手之前,我们需要对以太坊的核心概念有所了解:
开发环境搭建
开始开发前,你需要准备以下工具和环境:
Solidity by Juan Blanco,提供语法高亮、代码提示、编译等功能。npm install -g truffle ganache-cli,Ganache 也有图形界面版本,可以从其官网下载。创建你的第一个以太坊项目
初始化项目:
my-first-dapp,然后进入该文件夹。truffle init,这将创建一个标准的 Truffle 项目结构,包括:contracts/:存放你的 Solidity 智能合约文件。migrations/:部署脚本文件。test/:测试文件。truffle-config.js:Truffle 的配置文件。编写智能合约:
打开 contracts/ 文件夹,删除 Migrations.sol(这是 Truffle 自带的,我们暂时用不到),然后创建一个新的 Solidity 文件,SimpleStorage.sol。
编写一个简单的智能合约,用于存储和读取一个数字:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 private storedData;
event DataUpdated(uint256 newValue);
function set(uint256 x) public {
storedData = x;
emit DataUpdated(x);
}
function get() public view returns (uint256) {
return storedData;
}
}
代码解释:
SPDX-License-Identifier 和 pragma solidity 是 Solidity 合约的标准开头。contract SimpleStorage { ... } 定义了一个名为 SimpleStorage 的合约。uint256 private storedData; 声明一个私有的无符号256位整型变量 storedData。event DataUpdated(uint256 newValue); 定义一个事件,用于在数据更新时通知前端。function set(uint256 x) public:一个公共函数,用于设置 storedData 的值,并触发 DataUpdated 事件。function get() public view returns (uint256):一个公共视图函数,用于读取 storedData 的值,view 表示它不会修改链上状态。编译智能合约:
truffle-config.js 文件已经正确配置(Truffle 初始化后会默认配置好)。truffle compile,如果成功,你会在 build/contracts/ 目录下看到编译后的合约 ABI(应用程序二进制接口)和字节码。部署智能合约 (测试):
启动 Ganache
ganache-cli(确保另一个终端窗口在项目根目录)。配置 MetaMask:
HTTP://127.0.0.1:7545 或 HTTP://localhost:7545,具体看 Ganache 界面显示)。导入 Ganache 测试账户到 MetaMask:
在 MetaMask 中点击 "导入账户",粘贴 Ganache 提供的测试账户私钥,然后点击 "导入账户",确保该账户有足够的 ETH(Ganache 每个账户默认会分配 100 ETH)。
编写迁移脚本:
打开 migrations/ 文件夹,创建一个新的迁移文件,2_deploy_contracts.js(数字表示部署顺序)。
const SimpleStorage = artifacts.require("SimpleStorage");
module.exports = function (deployer) {
deployer.deploy(SimpleStorage);
};
执行部署:
truffle migrate --network development(如果你的 truffle-config.js 中默认网络是 development,可以省略 --network development)。与智能合约交互 (前端 DApp)
frontend,然后进入该文件夹。npm init -y 初始化一个 Node.js 项目。web3:用于与以太坊节点交互的 JavaScript 库。react 和 react-dom (如果你想用 React):流行的前端框架。web3:npm install web3index.html 在 frontend 目录下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SimpleStorage DApp</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
input, button { padding: 8px; margin: 5px; }
</style>
</head>
<body>
<h1>SimpleStorage DApp</h1>
<div>
<label for="valueInput">Set Value:</label>
<input type="number" id="valueInput" placeholder="Enter a number">
<button onclick="setValue()">Set Value</button>
</div>
<div>
<button onclick="getValue()">Get Value</button>
<p>Current Value: <span id="currentValue">
本文由用户投稿上传,若侵权请提供版权资料并联系删除!