Web3 开发教程

avatar
作者
筋斗云
阅读量:0
引言

Web3 是指第三代互联网,其核心特征之一是去中心化。通过区块链技术和智能合约,Web3 应用程序(dApps)能够在无需中心化服务器的情况下运行。本文将引导你完成一个简单的 Web3 应用程序的开发过程,包括环境搭建、智能合约编写、前端应用开发等步骤。

项目源码见最下方

1. 环境准备

确保你的开发环境中已安装了以下工具:

  • Node.js (建议使用 LTS 版本)
  • npm 或 yarn (建议使用 yarn,因为它更快)
  • Truffle Suite (用于智能合约开发)
  • Ganache (用于本地区块链测试)
  • MetaMask (用于浏览器中管理账户)
2. 安装 Truffle 和 Ganache

Truffle 是一个流行的开发框架,用于智能合约的开发、测试和部署。Ganache 则是一个本地的以太坊区块链模拟器,用于测试你的智能合约。

Bash

深色版本

1npm install -g truffle 2npm install -g ganache-cli
3. 创建 Truffle 项目

使用 Truffle 创建一个新的项目。

Bash

深色版本

1mkdir my-dapp 2cd my-dapp 3truffle init
4. 编写智能合约

创建一个简单的智能合约,用于存储和检索一条消息。

Solidity

深色版本

1// contracts/Greeting.sol 2pragma solidity ^0.8.0; 3 4contract Greeting { 5    string private _message; 6 7    constructor() { 8        _message = "Hello, World!"; 9    } 10 11    function setMessage(string memory message) public { 12        _message = message; 13    } 14 15    function getMessage() public view returns (string memory) { 16        return _message; 17    } 18}
5. 编译智能合约

使用 Truffle 编译智能合约。

Bash

深色版本

1truffle compile
6. 部署智能合约

truffle-config.js 文件中配置 Ganache 作为开发环境,并部署智能合约。

Javascript

深色版本

1// truffle-config.js 2module.exports = { 3  networks: { 4    development: { 5      host: "127.0.0.1", 6      port: 7545, 7      network_id: "*" 8    } 9  }, 10  compilers: { 11    solc: { 12      version: "^0.8.0" 13    } 14  } 15};

部署智能合约到本地 Ganache 链。

Bash

深色版本

1ganache-cli 2truffle migrate --network development
7. 使用 MetaMask

MetaMask 是一个流行的以太坊钱包插件,可以让你与以太坊网络上的 dApps 交互。

  • 安装 MetaMask:前往 MetaMask 官网下载并安装浏览器插件。
  • 连接到 Ganache:在 MetaMask 中选择本地网络,并输入 Ganache 的 RPC URL (http://127.0.0.1:7545)。
8. 前端开发

使用 Vue.js 创建一个简单的前端应用来与智能合约交互。

Bash

深色版本

1npm install -g @vue/cli 2vue create my-dapp-front 3cd my-dapp-front
9. 安装 Web3 库

安装 Web3.js 库,用于与以太坊网络通信。

Bash

深色版本

1npm install web3
10. 编写前端应用

src/App.vue 中编写前端应用。

Javascript

深色版本

1// src/App.vue 2<template> 3  <div id="app"> 4    <h1>Greeting Contract</h1> 5    <p>{{ message }}</p> 6    <input v-model="newMessage" placeholder="Enter a new message" /> 7    <button @click="updateMessage">Update Message</button> 8  </div> 9</template> 10 11<script> 12import Web3 from 'web3'; 13import Greeting from '../truffle-contracts/Greeting.json'; 14 15export default { 16  data() { 17    return { 18      web3: null, 19      accounts: [], 20      contract: null, 21      message: '', 22      newMessage: '' 23    }; 24  }, 25  async mounted() { 26    try { 27      // Get network provider and web3 instance. 28      const web3 = new Web3(Web3.givenProvider || 'http://localhost:7545'); 29      this.web3 = web3; 30 31      // Use web3 to get the user's accounts. 32      const accounts = await web3.eth.getAccounts(); 33      this.accounts = accounts; 34 35      // Get the contract reference. 36      const networkId = await web3.eth.net.getId(); 37      const deployedNetwork = Greeting.networks[networkId]; 38      this.contract = new web3.eth.Contract( 39        Greeting.abi, 40        deployedNetwork && deployedNetwork.address 41      ); 42 43      // Load the initial message. 44      const msg = await this.contract.methods.getMessage().call(); 45      this.message = msg; 46    } catch (error) { 47      alert(`Failed to load web3, accounts, or contract. Check console for details.`); 48      console.error(error); 49    } 50  }, 51  methods: { 52    async updateMessage() { 53      try { 54        const result = await this.contract.methods.setMessage(this.newMessage).send({ from: this.accounts[0] }); 55        console.log(result); 56        const msg = await this.contract.methods.getMessage().call(); 57        this.message = msg; 58      } catch (error) { 59        console.error(error); 60      } 61    } 62  } 63}; 64</script>
11. 运行前端应用

运行前端应用并与智能合约交互。

Bash

深色版本

1npm run serve
12. 测试应用

在浏览器中打开 http://localhost:8080/,你将看到一个简单的应用,可以更新并显示智能合约中的消息。

项目源码下载地址https://download.csdn.net/download/qq_42072014/89596725

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!