1、创建utils文件夹在这个文件夹下创建web3.ts文件:

import { ethers } from 'ethers'
import { ExternalProvider, JsonRpcFetchFunc } from '@ethersproject/providers';
import { InjectedConnector } from '@web3-react/injected-connector'// 提供一个provider转成web3providerexport const getLibray = (provider: ExternalProvider | JsonRpcFetchFunc) => {const web3Provider = new ethers.providers.Web3Provider(provider)return web3Provider
}export const InjectConnector = new InjectedConnector({ supportedChainIds: [56] })

2、创建chain文件夹,在这个文件夹下创建一个index.ts文件:

// 支持的链
export const SuportChain = {eth: {chanId: 1,name: 'eth'},bsc: {chainId: 56,name: 'bsc'},polygon: {chainId: 56,name: 'polygon'}
}// 链id 网络id
export enum NetworkID {// 主网Mainnet = 56,// 测试网Testnet = 97
}export enum SUPPORT_CHAIN {BSC = 56,BSCTEST = 97
}// 当前链ID
export const CURRENT_CHAIN = 56// MetaMask 中 request 请求中的 methods 方法
export enum MetaMaskRequestMethods {// 添加在metamask中不存在的链addEthereumChain = "wallet_addEthereumChain",// 吧Token代币添加到钱包中watchAsset = 'wallet_watchAsset',// 获取当前链接的网络IdchainId = 'eth_chainId',// eth_requestAccunts 获取账号(可以理解为链接钱包)requestAccount = 'eth_requestAccounts',// 获取账户地址accounts = 'eth_accounts',// 获取最新区块编号blockNumber = 'eth_blockNumber'
}
// 添加一条链到metamask上时请求网络参数
export const AddEthereumChainParams: { [key: number]: any } = {8: {chainId: '0x8',chainName: 'Ubiq',chativeCurrency: {name: 'Ubiq Ether',symbol: 'BUQ',decimals: 18,},rpcUrl: ['https://rpc.octano.dev/'],blockExplorerUrls: ['https://ubiqscan.io/']},56: {chainId: '0x38',chainName: 'Binance Smart Chain Mainnet',nativeCurrency: {name: 'BNB',symbol: 'bnb',decimals: 18},rpcUrls: ['https://bsc-dataseed1.ninicoin.io', 'https://bsc-dataseed1.defibit.io', 'https://bsc-dataseed.binance.org'],blockExplorerUrls: ['https://bscscan.com/'],}
}

3、在react-app-env.d.ts内添加:

/// <reference types="react-scripts" />
interface Window {ethereum?:{isMetaMask?:truerequest?:(...args:any[])=>Promise<void>}BinanceChain?:{bnbSign?:(address:string,message:string) => Promise<{publicKey:string;signature:string}>}web3:any
}

4、创建types文件夹,在这个文件夹中创建ethereum.tsx文件:

type EthereumProviderEip1193 = {request: (args: {method: stringparams?: unknown[] | object}) => Promise<unknown>
}type EthereumProviderSend = {send: (method: string, params: string[]) => Promise<unknown>
}type EthereumProviderSendAsync = {sendAsync: (params: {method: stringparams: string[]from: stringjsonrpc: '2.0'id: number},callback: (err: Error, result: unknown) => void) => voidselectedAddress: string
}/*** window.ethereum 类型* Eip-1193 规范*/
export type EthereumProvider = EthereumProviderEip1193 &EthereumProviderSend &EthereumProviderSendAsync

5、再到utils文件夹中创建ethereum.ts文件:

import { AddEthereumChainParams, MetaMaskRequestMethods } from "chain";
import { EthereumProvider } from "types/ethereum";function isUnwrappedRpcResult(response: unknown): response is {error?: stringresult?: unknown
} {return (typeof response === 'object' && response !== null && 'jsonrpc' in response)
}
/*** 防止有的客户端没有包裹response*/
export function rpcResult(response: unknown): unknown | null {// Some providers don’t wrap the responseif (isUnwrappedRpcResult(response)) {if (response.error) {throw new Error(response.error)}return response.result || null}return response || null
}
/*** metamask request 方法封装* @param ethereum provider, 浏览器中使用window.ethereum* @param method 请求方法* @param params 参数* @returns */
export async function ethereumRequest(ethereum: EthereumProvider,method: string,params: string[]
): Promise<any> {// If ethereum.request() exists, the provider is probably EIP-1193 compliant.if (ethereum.request) {return ethereum.request({ method, params }).then(rpcResult)}// This is specific to some older versions of MetaMask combined with Web3.js.if (ethereum.sendAsync && ethereum.selectedAddress) {return new Promise((resolve, reject) => {ethereum.sendAsync({method,params,from: ethereum.selectedAddress,jsonrpc: '2.0',id: 0,},(err: Error, result: any) => {if (err) {reject(err)} else {resolve(result)}})}).then(rpcResult)}// If none of the previous two exist, we assume the provider is pre EIP-1193,// using .send() rather than .request().if (ethereum.send) {return ethereum.send(method, params).then(rpcResult)}throw new Error('The Ethereum provider doesn’t seem to provide a request method.')
}/*** 获取区块编码* @param ethereum provider, 默认使用window.ethereum* @returns */
export async function getBlockNumber(ethereum?: EthereumProvider) {ethereum = ethereum ?? window.ethereum as anyreturn ethereumRequest(ethereum!, MetaMaskRequestMethods.blockNumber, [])
}
/*** 添加链到metamask 上*/
export async function addChainToBlock(id: number, ethereum?: EthereumProvider) {ethereum = ethereum ?? window.ethereum as anyconst params = AddEthereumChainParams[id]// ! 确保ethereum 部位nullreturn ethereumRequest(ethereum!, MetaMaskRequestMethods.addEthereumChain, [params])
}

6、在创建hooks文件夹,在这个文件夹里创建useAuth.ts:

import { UnsupportedChainIdError, useWeb3React } from '@web3-react/core'
import { InjectConnector } from '../utils/web3'
import { addChainToBlock } from 'utils/ethereum'export const useAuth = () => {const { activate } = useWeb3React()const Login = () => {if (InjectConnector) {activate(InjectConnector, async (error: Error) => {if (error instanceof UnsupportedChainIdError) {const hasSetup = await addChainToBlock(56)if (hasSetup) {activate(InjectConnector)}}})}}return Login
}

然后再src目录下的index.tsx文件下这么写:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
// 这下边的两个是添加的引入文件
import { getLibray } from "./utils/web3";
import { Web3ReactProvider } from "@web3-react/core";ReactDOM.render(<React.StrictMode>{/* 在这里用 Web3ReactProvider 包裹 app 文件 */}<Web3ReactProvider getLibrary={getLibray}><App /></Web3ReactProvider></React.StrictMode>,document.getElementById("root")
);// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

在然后再你需要获取MetaMask小狐狸地址的地方这么写:

import React, { useEffect } from "react";
import "./App.css";
import { useWeb3React } from "@web3-react/core";
import { useAuth } from "hooks/useAuth";function App() {const Login = useAuth();const { account, library, chainId } = useWeb3React();console.log("地址1", account);const GetClick = () => {Login();console.log("地址2", account);};useEffect(() => {Login();}, []);return (<div className="App"><button onClick={GetClick}>获取钱包地址</button></div>);
}export default App;

你只需要按我说的创建文件夹步骤复制代码,就可以链接到你的小狐狸了,记得要在tsconfig.json文件中添加"baseUrl": "src",

希望我能帮到你。我技术有限,有不对的地方请在评论区指教;

如何配置web3.js和连接MetaMask相关推荐

  1. 使用 Web3.js 连接以太坊节点并查询区块链数据

    Web3.js 是一个用于连接以太坊网络的 JavaScript 库.在本文中,我们将介绍如何使用 Web3.js 来连接以太坊节点,并且查询以太坊区块链上的数据. 1. 安装 Web3.js 首先, ...

  2. 前端Vue项目调用页面web3.js:连接metaMask钱包,(查询钱包ETH余额,查询代币余额,ETH转账,代币转账,代币授权,查询授权数量,计算价格)等功能

    这里分享下相关文档 1.web3.js中文文档 https://learnblockchain.cn/docs/web3.js/getting-started.html 2.metamask官方文档: ...

  3. 【一步步一起学DApp开发】(四)web3.js 基本使用 | 连接geth | 创建web客户端

    概述 web3.js内部使用JSONRPC与geth通信.它把所有JSON-RPC API当作JavaScript API,也就是说,它不仅支持所有与以太坊相关的API,还支持与Whisper和Swa ...

  4. web3入门-web3.js通过Ganache连接truffle智能合约

    //环境 Truffle v5.5.21 (core: 5.5.21) Ganache v7.2.0 Solidity v0.5.16 (solc-js) Node v14.17.3 Web3.js ...

  5. 区块链教程(四):搭建私链、web3.js基础

    注:本教程为技术教程,不谈论且不涉及炒作任何数字货币 区块连教程(一):前置知识-linux补充 区块链教程(二):基础概念介绍 区块链教程(三):Solidity编程基础 区块链教程(四):搭建私链 ...

  6. web3.js以太坊客户端

    以太坊客户端是一个软件应用程序,它实现以太坊规范并通过p2p网络与其他以太坊客户端进行通信.如果不同的以太坊客户端符合参考规范和标准化通信协议,则可以进行相互操作. 这些基于以太坊的网络中有:以太坊, ...

  7. 【区块链】以太坊Solidity编程:合约调用与web3.js

    以太坊Solidity编程:合约调用与Web3.js 合约部署方法 合约的编译 使用浏览器编译器Remix 使用truffle编译,目前是最常用的编译方式 Solc或者Web3.js编译合约,使用相对 ...

  8. 第十二课 从宠物商店案例看DAPP架构和WEB3.JS交互接口

    1. 文章摘要 [本文目标] 了解ETH生态下DAPP去中心化应用程序的框架和交互流程,了解WEB3.JS的作用和接口函数. [前置条件] 完成了<第六课 技术小白如何开发一个DAPP区块链应用 ...

  9. 区块链100讲:从宠物商店案例看DAPP架构和WEB3.JS交互接口

    1 文章摘要 [本文目标] 了解ETH生态下DAPP去中心化应用程序的框架和交互流程,了解WEB3.JS的作用和接口函数. [前置条件] 完成了<技术小白如何开发一个DAPP区块链应用(以宠物商 ...

最新文章

  1. sql中exists,not exists的用法
  2. Windows安装NodeJS
  3. Android开发之购物车加减按钮(附加源码)
  4. superset 时区问题Timestamp subtraction must have the same timezones or no timezones
  5. 雷电模拟器 脚本_精灵盛典辅助雷电模拟器使用教程
  6. 美团架构师带你深入理解Nginx模块开发与架构解析
  7. HIKROBT海康系列软件下载
  8. 惠普HP LaserJet Pro MFP M126nw 打印机驱动
  9. 关于解决keil5中*** FATAL ERROR L250: CODE SIZE LIMIT IN RESTRICTED VERSION EXCEEDED的问题
  10. 机器学习知识总结 —— 8. 什么是有监督学习、无监督学习、半监督学习
  11. 抽签 java_「抽签软件」基于Javafx制作的随机抽签软件 - seo实验室
  12. 计算机显卡升级不符,电脑升级之显卡篇:电脑显卡也有升级需要,但显卡不匹配也用不了...
  13. 写给需要面试经验的交互设计师(下)
  14. Ubuntu 16.04 LTS 初体验 (转载)
  15. echarts一个legend同时控制柱状图和折线图
  16. ios和android前景!阿里面试100%会问到的JVM,架构师必备技能
  17. 开源社区Github在2022年06月09日公测了三个新的成就徽章
  18. 基于android平台的条码扫描软件的设计与实现,基于android平台的条码扫描软件的设计与实现...
  19. Java毕设项目户籍管理系统(java+VUE+Mybatis+Maven+Mysql)
  20. Carson带你学Android:图文详解RxJava背压策略

热门文章

  1. final 评论 I
  2. 英语重要性逐步降低,取消英语必修课有必要吗?
  3. 同样是应届生,为什么有的同学一毕业就月薪1万以上?
  4. MySQL初步学习及实例1
  5. 安卓手机来电防火墙_手机号拉黑了能收到短信吗
  6. 计算机考试三个文档是哪三个,2016职称计算机考试word2003考前押题3
  7. cs224n Assignment 1:exploring_word_vectors
  8. codecombat之KithGard地牢19-37关代码分享
  9. php快手小程序微信H5支付
  10. 教育论文发表期刊《中国教育技术装备》杂志简介及投稿须知