You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测Phantom Wallet当前使用的Solana网络(mainnet/devnet/testnet)

判断Phantom钱包当前网络类型的可行方法

核心实现思路

Phantom钱包会在授权连接后向页面注入全局对象window.solana,通过该对象提供的属性和事件,就能直接获取或监听当前的网络类型。

具体实现方式

  • 直接获取当前网络
    确认钱包已连接后,通过window.solana.connection.rpcEndpoint拿到RPC端点地址,再根据地址特征判断网络:

    if (window.solana?.isPhantom) {
      const rpcEndpoint = window.solana.connection.rpcEndpoint;
      let currentNetwork;
      if (rpcEndpoint.includes('mainnet-beta')) {
        currentNetwork = 'mainnet';
      } else if (rpcEndpoint.includes('devnet')) {
        currentNetwork = 'devnet';
      } else if (rpcEndpoint.includes('testnet')) {
        currentNetwork = 'testnet';
      } else {
        currentNetwork = '自定义/未知网络';
      }
      console.log('当前钱包网络:', currentNetwork);
    }
    
  • 监听网络切换事件
    若需要实时感知用户切换网络的操作,可以监听networkChanged事件:

    if (window.solana?.isPhantom) {
      window.solana.on('networkChanged', (newRpcEndpoint) => {
        let updatedNetwork;
        if (newRpcEndpoint.includes('mainnet-beta')) {
          updatedNetwork = 'mainnet';
        } else if (newRpcEndpoint.includes('devnet')) {
          updatedNetwork = 'devnet';
        } else if (newRpcEndpoint.includes('testnet')) {
          updatedNetwork = 'testnet';
        } else {
          updatedNetwork = '自定义/未知网络';
        }
        console.log('钱包网络已切换为:', updatedNetwork);
      });
    }
    

注意事项

  • 必须在用户授权网站连接钱包后,才能正常访问window.solana.connection相关属性
  • 对于用户自行设置的自定义RPC端点,上述判断逻辑可能无法匹配,建议额外提示用户确认网络类型

内容的提问来源于stack exchange,提问作者Phat Vo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 04:25:27