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

solidity front ends

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

当我们构建 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-serevr或live-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

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

相关推荐
啾咪orJIUMI2 小时前
Vue 3 + 高德地图封装实战:点位、区域、Loca 流光与 Vue 信息窗体
前端·vue.js
掘金者阿豪2 小时前
AI数据库不只是向量检索:从数据语义到库内智能计算的技术演进
前端
梦里寻码2 小时前
我用 NestJS + Vue3 写了一套完整的研发管理系统(58 表 / 229 API / 130 项断言,全开源
前端·后端·算法
FRing032 小时前
vue2干货总结8(路由模块封装、router-link、声明式导航、路由重定向、编程式导航)
开发语言·前端·vue.js·vue2
SameX2 小时前
HarmonyOS ArkUI Dialog 复用 用 @CustomDialog + enum type 做多类型统一管理的做法
前端
AiMan2 小时前
豆包爱学还是不可以导出左侧所有对话,只能单容导出,方法不对吗
前端
AiMan3 小时前
Grok生成的内容能否下载吗?
前端
徐小夕3 小时前
JitArchives,一款基于JitWord协同AI文档打造的企业级电子档案系统
前端·vue.js·github
陈随易3 小时前
Node.js 2026上半年都有哪些性能提升?
前端·后端·程序员
墨林陌4 小时前
AI 热点日报(2026-11-09):苹果代理式Siri曝光,Anthropic推进IPO,编码智能体实测翻车
前端