solidity front-ends(html+js+ethers v6)

solidity front ends

对于大部分人(非程序员)来说,无法自己开发,故需提供用户界面(website)供其操作。一般使用javascriptnodejs

当我们构建 solidity dapp 时, 经常使用两个 repo:

  • smart contracts, eg. hardhat-fund-me-fcc
  • front ends / website, eg. html-fund-me-fcc

FullStack = Smart Contracts(Backend) + html/js/website/nodejs stuff(frontend)

与区块链交互,需要链接链的对等节点,钱包插件(eg metamask)自带访问节点功能。一些第三方机构提供了节点服务API,如 alchemy.

前端项目实例

shell 复制代码
mkdir html-fund-me-fcc
code . // 打开vscode

编写index.html

html 复制代码
<!DOCTYPE html>
<html lang="en">     
    <head>
        <title> Fund Me App</title>
    </head>

    <body>
        <button id="connectButton">Connect</button>
        <button id="balanceButton">Get Balance</button>
        <button id="withdrawButton">Withdraw</button>
        <!-- <form> -->
        <label for="ethAmount">ETH Amount:</label>
        <input id="ethAmount" type="number" placeholder="0.1"/>
        <button id="fundButton" type="button">Fund</button>
        <!-- </from> -->
    </body>

    <script src="./index.js" type="module"></script>
</html>

type="module" 的作用是将 JavaScript 文件视为 ES 模块,这是 ES6(ECMAScript 2015)引入的模块系统:

  • 支持 import 和 export 语法;
  • 将代码分割成模块,提高代码复用性和可维护性;
  • 作用域独立,不会污染全局作用域;
  • 异步加载,执行效率更高;
  • 模块文件必须使用服务器加载(http-serevrlive-serevr),不能直接打开本地文件.

启动可以选择以下任何一种方式:

  • live server插件启动

输入 >Live Server: Open with live server 即可在浏览器打开.

  • 引入http-serevr 安装:
shell 复制代码
> yarn init -y
> yarn add --dev http-server

会生成很多项目配置文件,package.json如下:

json 复制代码
{
  "name": "html-fund-me-fcc",
  "packageManager": "yarn@4.6.0",
  "devDependencies": {
    "http-server": "^14.1.1"
  }
}

启动:

shell 复制代码
> yarn http-server
Starting up http-server, serving ./

http-server version: 14.1.1

http-server settings:
CORS: disabled
Cache: 3600 seconds
Connection Timeout: 120 seconds
Directory Listings: visible
AutoIndex: visible
Serve GZIP Files: false
Serve Brotli Files: false
Default File Extension: none

Available on:
  http://192.168.211.100:8080
  http://127.0.0.1:8080
  http://172.26.16.1:8080
Hit CTRL-C to stop the server

MetaMask for JS Simple

  • window.ethereum 连接 metamask :
js 复制代码
const connectButton = document.getElementById("connectButton");
connectButton.onclick = connect;

async function connect() {
    if (typeof window.ethereum !== "undefined") {
        try {
            await window.ethereum.request({
                method: "eth_requestAccounts",
            });
        } catch (error) {
            console.error("Error connecting to MetaMask:", error);
        }

        connectButton.innerHTML = "Connected";
        connectButton.disabled = true;
        const accounts = await window.ethereum.request({
            method: "eth_accounts",
        });
        console.log("Connected account:", accounts);
    } else {
        connectButton.innerHTML = "Please install MetaMask";
    }
}

js中导入ethers的方式,参考 ethers v6 getting-start

js 复制代码
import { ethers } from "./ethers-6.7.0.min.js" // 下载到项目目录
// import { ethers } from "https://cdnjs.cloudflare.com/ajax/libs/ethers/6.7.0/ethers.min.js"

migrating v5 to v6

本地测试

  • 启动本地节点,部署合约
csharp 复制代码
Deploying FundMe and waiting for confirmations...
deploying "FundMe" (tx: 0x6a97ceb3049b38b6e4edcd8f4d92794fbbcdb62b3ece28825ff4be7e84e16cae)...: deployed at 0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512 with 1096977 gas
FundMe deployed at 0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512
  • metamask 添加本地网络
  • 将本地网络的wallet 导入 metamask
vbnet 复制代码
ARNING: These accounts, and their private keys, are publicly known.
Any funds sent to them on Mainnet or any other live network WILL BE LOST.

Account #0: 0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266 (10000 ETH)
Private Key: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80

Account #1: 0x70997970c51812dc3a010c7d01b50e0d17dc79c8 (10000 ETH)
Private Key: 0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d

Account #2: 0x3c44cdddb6a900fa2b585dd299e03d12fa4293bc (10000 ETH)
Private Key: 0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a

添加完成后,可通过前端网页与本地区块链网络及合约交互。

相关推荐
fruge1 小时前
Vue项目中的Electron桌面应用开发实践指南
前端·vue.js·electron
漂流瓶jz7 小时前
Webpack中各种devtool配置的含义与SourceMap生成逻辑
前端·javascript·webpack
前端架构师-老李7 小时前
React 中 useCallback 的基本使用和原理解析
前端·react.js·前端框架
木易 士心7 小时前
CSS 中 `data-status` 的使用详解
前端·css
明月与玄武7 小时前
前端缓存战争:回车与刷新按钮的终极对决!
前端·缓存·回车 vs 点击刷新
牧马少女8 小时前
css 画一个圆角渐变色边框
前端·css
zy happy8 小时前
RuoyiApp 在vuex,state存储nickname vue2
前端·javascript·小程序·uni-app·vue·ruoyi
小雨青年8 小时前
Cursor 项目实战:AI播客策划助手(二)—— 多轮交互打磨播客文案的技术实现与实践
前端·人工智能·状态模式·交互
小光学长8 小时前
基于Vue的儿童手工创意店管理系统as8celp7(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
前端·数据库·vue.js
meichaoWen9 小时前
【Vue】Vue框架的基础知识强化
前端·javascript·vue.js