Web3.0的测试题

news/2024/7/6 3:56:38 标签: web3, 前端, javascript

任务: 在前端开发一个查询UI,查询当前用户账户的ETH余额和指定ERC20合约中的余额

目标:

  • UI框架指定使用 MUI (https://mui.com)
  • 需要查询到当前账户的ETH余额并展示在UI界面上
  • 需要输入ERC20合约地址后,查询到到当前账户在此ERC20合约中的余额,并展示在UI界面上

提示:

  • 需要安装 Metamask 插件
  • 链接到 Sepolia 网络
  • ERC20 合约地址 0x7939C9b7cE8BFFc6cb791eCB129f4c385e05727a
时间要求:24小时内给出相应网页,可以部署到github或其他托管平台,也可以通过腾讯会议运行demo代码演示

参考资料

  • https://web3camp.us/
  • https://github.com/web3camp-labs

实现:

首先,确保安装了MUI库和Web3.js库:

npm install @mui/material @emotion/react @emotion/styled web3

你可以创建一个JavaScript文件,并编写如下代码:

javascript">import React, { useState } from "react";
import Web3 from "web3";
import { Container, TextField, Button, Typography } from "@mui/material";

// 创建Web3实例连接到以太坊网络
const web3 = new Web3(window.ethereum);

// 定义要查询的ERC20合约地址
// const erc20ContractAddress = "0x7939C9b7cE8BFFc6cb791eCB129f4c385e05727a";

export default function Web3View() {
  const [ethBalance, setEthBalance] = useState(null);
  const [erc20Balance, setERC20Balance] = useState(null);
  const [erc20Address, setERC20Address] = useState("");

  // 检查是否有提供者可用
  if (typeof window.ethereum !== "undefined") {
    // 使用以太坊提供者进行初始化
    web3.setProvider(window.ethereum);
  } else {
    console.error("无可用的以太坊提供者");
  }

  // 查询当前用户账户的ETH余额
  async function handleGetEthBalance() {
    try {
      // 获取当前用户的账户地址
      const accounts = await web3.eth.requestAccounts();
      const account = accounts[0];

      // 使用web3.eth.getBalance方法查询ETH余额
      const balanceWei = await web3.eth.getBalance(account);

      // 将余额从Wei转换为ETH单位
      const balanceEth = web3.utils.fromWei(balanceWei, "ether");
      setEthBalance(balanceEth);
    } catch (error) {
      console.error("获取ETH余额失败:", error);
    }
  }

  // 查询指定ERC20合约中的余额
  async function handleGetERC20Balance() {
    try {
      // 获取当前用户的账户地址
      const accounts = await web3.eth.requestAccounts();
      const account = accounts[0];

      // 加载ERC20合约的ABI(应用二进制接口)
      const erc20ABI = [
        // 方法1:获取代币总供应量
        {
          constant: true,
          inputs: [],
          name: "totalSupply",
          outputs: [
            {
              name: "",
              type: "uint256",
            },
          ],
          payable: false,
          stateMutability: "view",
          type: "function",
        },
        // 方法2:获取指定地址的代币余额
        {
          constant: true,
          inputs: [
            {
              name: "_owner",
              type: "address",
            },
          ],
          name: "balanceOf",
          outputs: [
            {
              name: "balance",
              type: "uint256",
            },
          ],
          payable: false,
          stateMutability: "view",
          type: "function",
        },
        // 方法3:转账代币到指定地址
        {
          constant: false,
          inputs: [
            {
              name: "_to",
              type: "address",
            },
            {
              name: "_value",
              type: "uint256",
            },
          ],
          name: "transfer",
          outputs: [
            {
              name: "",
              type: "bool",
            },
          ],
          payable: false,
          stateMutability: "nonpayable",
          type: "function",
        },
      ]; // ERC20合约的ABI定义

      // 创建ERC20合约实例
      const erc20Contract = new web3.eth.Contract(erc20ABI, erc20Address);
      // 使用合约实例的balanceOf方法查询余额
      const balance = await erc20Contract.methods.balanceOf(account).call();
      setERC20Balance(balance.toString());
    } catch (error) {
      console.error("获取ERC20合约余额失败:", error);
    }
  }

  return (
    <Container maxWidth="sm">
      <Typography variant="h4" align="center" gutterBottom>
        查询账户余额
      </Typography>

      <Button variant="contained" onClick={handleGetEthBalance}>
        查询ETH余额
      </Button>
      {ethBalance && (
        <Typography variant="body1" gutterBottom>
          当前ETH余额:{ethBalance} ETH
        </Typography>
      )}

      <TextField
        label="ERC20合约地址"
        value={erc20Address}
        onChange={(e) => setERC20Address(e.target.value)}
        fullWidth
        margin="normal"
      />
      <Button variant="contained" onClick={handleGetERC20Balance}>
        查询ERC20余额
      </Button>
      {erc20Balance !== null && (
        <Typography variant="body1" gutterBottom>
          当前ERC20余额:{erc20Balance}
        </Typography>
      )}
    </Container>
  );
}

效果图:

在这里插入图片描述
在这里插入图片描述


http://www.niftyadmin.cn/n/5157365.html

相关文章

Qt中Opencv转Qimage出现重影或者颜色不对

废话不多说 在qt中opencv获取的图像转qimage时出现重影原因&#xff1a; 图像数据的内存对齐可能会导致画面重影&#xff0c;如果出现误差转换出来的图就会出现重影 解决办法&#xff1a; cv::Mat image_bgr cv::imread(“example.jpg”); cv::Mat image_aligned; cv::copyMak…

C语言之认识柔性数组(flexible array)

在学习之前&#xff0c;我们首先要了解柔性数组是放在结构体当中的&#xff0c;知道这一点&#xff0c;我们就开始今天的学习吧&#xff01; 1.柔性数组的声明 在C99中&#xff0c;结构中的最后一个元素允许是未知大小的数组&#xff0c;这就叫做柔性数组成员 这里的结构是结构…

华为H12-831题库

单选&#xff09;当IS-IS网络中有多条冗余链路时&#xff0c;可能会出现多条等价路由。关于IS-IS网络内的等价路由&#xff0c;以下哪个描述是错误的? A、当组网中存在的等价路由数量大于通过命令配置的数量&#xff0c;且这些路由优先级相同时&#xff0c;优选下一跳设备Sys…

ce从初阶到大牛--动态网络部署

1.基于域名www.openlab.com可以访问网站内容为 welcome to openlab!!! systemctl stop firewalld setenforce 0 cd /etc/httpd/conf.d/ vim openlab.conf ** <VirtualHost 192.168.170.100:80>DocumentRoot /www/openlabServerName 192.168.170.100 </VirtualHost>…

git工作流(待续)

一、git git是分布式管理系统和集中式的区别在于每个人具有的本地份数不同&#xff0c;集中式只有一份 分布式 主要是 协同工作 gitlab github 等是git仓库的一个托管平台 二、git安装、初始化 基础配置 第一次需要对身份进行说明 git config --global user.name "xx&…

实时数仓-hologres使用总结

我们回顾下&#xff0c;Hologres是一款实时HSAP产品&#xff0c;隶属阿里自研大数据品牌MaxCompute&#xff0c;兼容 PostgreSQL 生态、支持MaxCompute数据直接查询&#xff0c;支持实时写入实时查询&#xff0c;实时离线联邦分析&#xff0c;低成本、高时效、快速构筑企业实时…

asp.net docker-compose添加sql server

打开docker-compose.yml 添加 sqldata:image: mysql:8.1.0 打开docker-compose.override.yml 添加 sqldata:environment:- MYSQL_ROOT_PASSWORDPasswordports:- "8080:8080"volumes:- killsb-one-sqldata:/etc/mysql/conf.d 在docker里面就有了sql server容器镜像…

点云从入门到精通技术详解100篇-基于激光雷达点云的路面破损检测

目录 前言 国内外研究现状 相关关键技术 2.1 LiDAR 传感器工作原理