js连接web3,连接小狐狸metamask钱包,实现链不对后切换网络和创建网络

本文档展示了如何使用JavaScript通过web3库连接Metamask钱包,并在链ID不匹配时自动切换或创建以太坊网络。代码示例详细说明了配置过程,包括在网络更改后重新连接web3和智能合约的步骤。

直接上代码,我这里吧所有配置都改成正式的链56,一旦用户的小狐狸钱包现在的链不一致,就询问切换网络,没有就创建网络,网络切换成功后,收到监听,重新连接一下web3,就是重新调用一些connectWeb3这个方法,再连接合约

  connectWeb3: async function () { 
// 判断链对不,链不对就请求切换网络,或者添加网络,
    if (window.ethereum) {
      try {
        await (window.ethereum as any).request({
          method: 'wallet_switchEthereumChain',
          params: [{
            chainId: Web3.utils.numberToHex(56) // 目标链ID
          }]
        })
      } catch (e) {
        if ((e as any).code === 4902) {
          try {
            await (window.ethereum as any).request({
                method: 'wallet_addEthereumChain',
                params: [
                  {
                    chainId: Web3.utils.numberToHex(56), // 目标链ID
                    chainName: 'Binance Smart Chain Mainnet',
                    nativeCurrency: {
                      name: 'bnb',
                      symbol: 'bnb',
                      decimals: 18
                    },
                    rpcUrls: ['https://bsc-dataseed.binance.org'], // 节点
                    blockExplorerUrls: ['https://www.bscscan.com']
                  }
                ]
              })
          } catch (ee) {
            //
          }
        } else if ((e as any).code === 4001) return
      }
    }


    // 监听账户变化
    const func: Function = async function (accounts) {
      _this.account = accounts[0];
      if (_this.isConnect) {
        console.log("Contract Account Changed");
        _this.init();// 清空数据
        _this.connectWeb3();// 链变化,然后重新调用此方法,连接web3
      }
    };
    let web3Provider: any = null;
    if (window.ethereum) {
      (window.ethereum as any).autoRefreshOnNetworkChange = false;
      (window.ethereum as any).on("accountsChanged", func);
    // 监听链id变化
      (window.ethereum as any).on("chainChanged", (chainId1) => {
        console.log("Chain Changed");
        _this.chainId = chainId1;
        func([_this.account]);
      });
      web3Provider = window.ethereum;
      try {
        await (window.ethereum as any).enable();
      } catch (error) {
        console.error("User denied account access");
      }
    } else if (window.web3) {
      web3Provider = window.web3.currentProvider;
    } else {
      web3Provider = new                 
      Web3.providers.HttpProvider(ChainLink[TargetChainId.toString()]);// 连接rpc网络
    }
    _this.web3 = new Web3(web3Provider);
    _this.web3.eth.getAccounts(function (error, result) {
      if (!error) console.log(result);
    });
    _this.isConnect = true;
    _this.account = (window.ethereum as any).selectedAddress || null;
    _this.chainId = (window.ethereum as any).networkVersion || null;
    if(_this.chainId!=TargetChainId) return;// 链不对,就不去连接合约了
    if (_this.account) {
      const time = Math.round(new Date().valueOf() / 1000);
    // 签名
      _this.web3.eth.personal.sign("Sign this message to login Game." + time, _this.account)
        .then((res) => {
          _this.signature = res + "|" + time;
        });
      _this.connectContract();// 连接合约
    }
    return _this.account;
}

### 如何在Web3应用程序中集成并连接MetaMask钱包 #### 准备工作 为了使Web3应用程序能够与MetaMask钱包交互,需确保已安装MetaMask插件于浏览器环境内[^1]。 #### 初始化Web3实例并与MetaMask建立连接 现代版本的MetaMask会自动注入`window.ethereum`对象至页面环境中。此对象遵循Ethereum Provider API标准,允许开发者与其进行互动。基于该特性,在初始化Web3实例时应优先尝试获取这个全局变量作为provider参数传递给Web3构造器: ```javascript if (typeof window.ethereum !== 'undefined') { console.log('MetaMask is installed!'); } else { console.log('Please install MetaMask'); } // Import the provider from ethers.js or use web3.js directly. const { ethers } = require("ethers"); // Modern dapps should always fall back to this method of detecting providers. let provider; if (window.ethereum) { provider = new ethers.providers.Web3Provider(window.ethereum); try { // Request account access if needed await provider.send("eth_requestAccounts", []); } catch (err) { // Some error occurred, handle it here. } } else if (window.web3) { provider = new ethers.providers.Web3Provider(window.web3.currentProvider); } else { alert('Non-Ethereum browser detected. You should consider trying MetaMask!'); } ``` 上述代码片段展示了如何检测是否存在`ethereum`对象以及怎样利用它来创建一个新的`Web3Provider`实例。如果成功,则可以进一步请求账户权限;若失败则提示用户考虑使用支持以太坊钱包扩展程序如MetaMask[^4]。 #### 获取当前选中的账号地址 一旦建立了有效的提供者接之后,就可以调用相应方法查询当前被激活的默认账户列表: ```javascript async function getAccount() { const accounts = await ethereum.request({ method: 'eth_accounts' }); return accounts[0]; } getAccount().then(console.log); // 打印第一个可用账户 ``` 这段脚本定义了一个异步函数`getAccount()`用来发送RPC请求检索所有可访问的ETH账户,并返回其中的第一个作为代表性的身份标识符[^2]。 #### 处理切换事件监听 当用户的网络配置发生变化时(比如更换了不同的测试网/主网),可以通过订阅特定类型的事件来进行响应处理: ```javascript ethereum.on('chainChanged', (_chainId) => { // Handle chain changed event... }); ethereum.on('accountsChanged', (accounts) => { // Handle accounts changed event... }); ``` 这里注册了两个重要的回调机制——一个是针对区块变更的通知(`chainChanged`),另一个则是关注个人资料更新情况(`accountsChanged`)。每当发生这些变动的时候都会触发相应的逻辑操作[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值