dApp入门:使用React创建你的dApp前端
去中心化应用(dApp)简介
使用 React 和 ethers.js 创建 dApp 前端
dApp入门:使用React创建你的dApp前端
我经常收到开发者的私信,问我如何入门 Web3,在 Twitter 上也经常看到类似的问题,在 Discord 上也能看到相关的讨论。看来很多开发者都对这个领域很感兴趣。
如果你也是其中一员,那么你来对地方了!在这篇文章中,我将首先尝试解释web3应用程序的基础知识,提供一个框架,然后指导你使用React创建你的dApp前端。
请注意:本文中,我们将讨论以太坊区块链上的去中心化应用程序(dApp)。
去中心化应用(dApp)简介
什么是dApp?
去中心化应用(dApp)与其他软件应用——例如网站或手机应用——并无本质区别。不同之处在于,其后端代码运行在去中心化网络上,例如点对点网络或区块链。
所以以太坊上的应用程序就是dApp。
有哪些好处?
-
由于去中心化应用(dApp)的后端代码(智能合约)运行在去中心化网络上,因此dApp不受任何中心化机构的控制,也无法被修改或移除。开发者和创建者可以信任底层基础设施,无需担心被终止或审查。
-
智能合约一旦部署到以太坊网络,任何人都无法更改它。因此,用户可以完全信任它的运行方式,因为即使是部署合约的人也无法修改它。
-
以太坊上的所有智能合约都是公开且可访问的;它是一个开源生态系统。这种开源特性使其具有可组合性,这意味着您可以重用其他人的代码片段。您可以在Etherscan上查看所有智能合约;这里有一个智能合约示例。
去中心化应用(dApp)仅意味着其后端代码(智能合约)位于去中心化网络上。需要注意的是,并非应用的所有组件都必须是去中心化的。例如,应用开发者可以决定前端的托管位置以及应用数据的存储位置。
去中心化世界倡导将整个技术栈去中心化,并且正在构建它!
dApp 有什么用途?
目前,dApp 最热门的类别是游戏、金融服务和数字商品。
以下是一些以太坊区块链上热门的去中心化应用(dApp):
- Uniswap - 代币兑换平台,提供代币以实现流动性和奖励(金融服务)
- Axie - 使用名为“Axie”的虚拟形象进行游戏并赢取奖励(游戏)
- Decenterland - 在虚拟世界中收集和交易(虚拟世界)
- Open Sea:买卖、交易数字资产(数字商品)
可能还有更多我们尚未发现的类别。
我该如何使用dApp?
大多数去中心化应用(dApp)都使用您的加密货币钱包作为您的首选登录方式。(太棒了!无需再输入用户名和密码,也无需关联其他社交媒体账号。)
你基本上需要一个加密货币钱包和ETH ——ETH是以太坊区块链的原生货币。钱包可以让你连接到网络并创建交易,而ETH则用于支付交易费用。
创建去中心化应用
最基本的去中心化应用(dApp)由后端(智能合约)和前端用户界面组成。前端是客户端,后端是服务器端。
-
dApp 的后端是智能合约。智能合约是存储在区块链中的自执行计算机程序,在以太坊上,所有智能合约都是公开且可访问的。您可以通过 Etherscan 查看它们;这里有一个智能合约示例。关于智能合约,另一个需要注意的重要事项是,一旦智能合约被修改,任何人都无法再对其进行更改。Solidity 是以太坊上最流行的智能合约语言之一。
-
dApp的前端可以用任何能够与后端通信的语言编写。前端可以托管在中心化服务或去中心化服务上。
简而言之,dApp 是一种后端运行在去中心化平台上,前端与之连接的应用程序。要使用 dApp,您需要一个加密货币钱包和一些加密货币。
使用 React 和 ethers.js 创建 dApp 前端
在这个项目中,我们将创建一个 React 项目,并将其连接到我们的加密钱包,加密钱包是我们与区块链的接口。
项目工具
- MetaMask钱包:加密钱包
- React:用于构建用户界面的 JavaScript 库
- ethers.js:开源 JavaScript 客户端库,包含与以太坊区块链通信的工具。(另一个非常流行的选择是web3.js。您可以在这里找到两者的比较。)
请注意:本项目仅包含应用程序的前端部分。若要添加后端,我们需要一个以太坊开发环境。Hardhat和Truffle是常用的以太坊开发环境。此外,要将应用程序部署到网络,我们需要使用区块链开发平台,例如Alchemy或Infura。
先决条件
创建 D-app 前端
-
创建项目文件夹并设置 React 应用
npx create-react-app edas-dapp cd edas-dapp npm start -
使用npm安装 ethers.js 库:npm install ethers用毛线:
yarn add ethers -
以下代码创建了一个按钮,用户点击该按钮后将提示用户连接到 Metamask 钱包。我已添加注释来解释代码的运行机制。请将以下代码添加到 App.js 文件中。
import './App.css'; import { useEffect, useState } from 'react'; const App = () => { //state variable to store user's public wallet const [currentAccount, setCurrentAccount] = useState(""); // check wallet connection when the page loads const checkIfWalletIsConnected = async () => { // access to window.ethereum const {ethereum} = window; //check if user has metamask if(!ethereum) { alert("Make sure you have metamask"); return; } //get the wallet account const accounts = await ethereum.request({method: 'eth_accounts'}); //get the first account if(accounts.length !== 0){ const account = accounts[0]; console.log("Found account:", account); //set the account as a state setCurrentAccount(account); } else{ console.log("No account"); } } // connect to wallet const connectWallet = async () => { try { // get the wallet const {ethereum} = window; // there is no wallet extension if(!ethereum) { alert("Opps, looks like there is no wallet!"); return; } const currentNetwork = ethereum.networkVersion; console.log("Current network", currentNetwork); // request access to account const accounts = await ethereum.request({ method: "eth_requestAccounts"}); //set the account in the state setCurrentAccount(accounts[0]); } catch( error){ console.log(error); } } //run function checkIfWalletIsConnected when the page loads useEffect(()=> { checkIfWalletIsConnected(); }, []); //connect to wallet const walletNotConnected = () => ( <button onClick={connectWallet} className="connect-to-wallet-button"> Connect to Wallet </button> ); //wallet connected const walletConnected = () => ( <div> <p>Connected to the wallet</p> </div> ); return ( <div className="App"> <div style={{display: 'flex', justifyContent:'center', height: '50px'}}> {currentAccount === "" ? walletNotConnected() : walletConnected()} <br /> </div> </div> ); }; export default App;以下代码将连接到最新的活跃网络。因此,如果用户之前连接的是以太坊主网,它将连接到以太坊;如果用户之前连接的是 Rinkeby 测试网,它将连接到 Rinkeby 测试网。然而,在很多情况下,我们需要用户连接到特定的网络。
-
您可以检查用户当前连接的网络,并提示用户更改网络。请按如下方式修改 App.js 中的connectWallet 函数。
const connectWallet = async () => { try { const {ethereum} = window; if(!ethereum) { alert("Opps, looks like there is no wallet!"); return; } const currentNetwork = ethereum.networkVersion; console.log("Current network", currentNetwork); //check which network the wallet is connected on if(currentNetwork != 4){ // prompt user with a message to switch to network 4 which is the rinkeby network on metamask alert("Opps, only works on Rinkeby! Please change your //network :)"); return; }; const accounts = await ethereum.request({ method: "eth_requestAccounts"}); setCurrentAccount(accounts[0]); } catch( error){ console.log(error); } } -
更好的方法是直接提示用户切换网络,而不是询问用户如何更改他们当前连接的网络。请将 if 语句修改为以下几行。
// request to switch the network const tx = await ethereum.request({method: 'wallet_switchEthereumChain', params:[{chainId: '0x4'}]}).catch() if (tx) { console.log(tx) } -
MetaMask 默认已定义 Chain 4。您也可以提示用户添加尚未定义的网络。以下是如何添加 Avalanche 网络的方法。在请求访问帐户之前添加以下代码片段。
// define avax network values const avax_mainnet = [{ chainId: '0xA86A', chainName: 'Avalanche Mainnet C-Chain', nativeCurrency: { name: 'Avalanche', symbol: 'AVAX', decimals: 18 }, rpcUrls: ['https://api.avax.network/ext/bc/C/rpc'], blockExplorerUrls: ['https://snowtrace.io/'] }] // request to add the new network const tx = await ethereum.request({method: 'wallet_addEthereumChain', params:avax_mainnet}).catch() if (tx) { console.log(tx) }
🎉 瞧!这就是如何在你的应用程序中使用加密钱包的方法!下一步是连接到智能合约,然后就可以做一些很酷的事情了,比如铸造你的NFT、交换代币等等。
总的来说,了解一些 js 和 html 知识对于为你的应用程序搭建一个量身定制的前端是有益的。
文章来源:https://dev.to/edatweets_/intro-to-dapps-create-your-dapp-frontend-wreact-38fi