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

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

相关推荐
方始终_2 小时前
做一个图表MCP Server,分分钟的事儿?
前端·agent·mcp
白袜队今年挖矿机2 小时前
Spring事务基础概念
前端
三十_2 小时前
【实录】多 SDK 日志乱象的解决方案:统一日志 SDK 设计分享
前端·javascript
一枚前端小能手2 小时前
🛡️ Token莫名其妙就泄露了?JWT安全陷阱防不胜防
前端·javascript·安全
杰哥有只羊2 小时前
微信小程序-名片生成
前端
薛定谔的算法2 小时前
Vue.js 条件渲染与列表渲染详解:原理、用法与最佳实践
前端·vue.js·前端框架
_前端小李_2 小时前
关于预检请求
前端
复苏季风2 小时前
Vue3 小白的疑惑:为什么用 const 定义的变量还能改?
前端·javascript·vue.js
Mintopia2 小时前
在 Next.js 中接入 Google Analytics 与 PostHog —— 一场“数据偷窥”的艺术演出
前端·javascript·next.js