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

Solana 开发指南:如何使用原生 JS 获取 Phantom 钱包余额

问题根因
  • 你调用的getAccountTokenBalance不属于Phantom钱包Provider的公开方法,window.solana.request仅用于处理钱包连接、签名类交互,无法直接查询链上数据
  • 链上余额数据需要向Solana RPC节点发起请求获取
  • 你的原有代码未加await关键字,异步请求会直接返回Promise对象,无法读取实际返回值
原生JS实现方案

直接调用Solana公共RPC节点即可实现余额查询,不需要引入额外依赖:

获取原生SOL余额

// Solana主网公共RPC节点,可根据需求替换为自有节点
const SOLANA_RPC = "https://api.mainnet-beta.solana.com";

// 入参为你已获取到的钱包Base58格式公钥
async function getSolBalance(walletPubkey) {
  try {
    const res = await fetch(SOLANA_RPC, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: "balance-query",
        method: "getBalance",
        params: [walletPubkey]
      })
    });
    const data = await res.json();
    // 链上返回单位为lamports,1 SOL = 10^9 lamports,转换为可读单位
    const solBalance = data.result.value / 1e9;
    console.log("SOL余额:", solBalance);
    return solBalance;
  } catch (err) {
    console.error("SOL余额查询失败:", err);
  }
}

获取所有SPL代币(含FT、NFT)余额

solanart上展示的全量资产余额可通过getTokenAccountsByOwner接口获取:

async function getAllSplTokenBalances(walletPubkey) {
  try {
    const res = await fetch(SOLANA_RPC, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: "token-query",
        method: "getTokenAccountsByOwner",
        params: [
          walletPubkey,
          // SPL代币标准程序固定ID
          { programId: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" },
          { encoding: "jsonParsed" }
        ]
      })
    });
    const data = await res.json();
    // 解析返回的所有代币数据
    const tokenList = data.result.value.map(account => {
      const info = account.account.data.parsed.info;
      return {
        代币mint地址: info.mint,
        余额: info.tokenAmount.uiAmount,
        小数精度: info.tokenAmount.decimals
      };
    });
    console.log("全量SPL资产:", tokenList);
    return tokenList;
  } catch (err) {
    console.error("SPL资产查询失败:", err);
  }
}
调用方式

在你拿到钱包公钥的逻辑后直接调用即可:

// 示例:连接钱包拿到公钥后调用查询
if (window.solana.isConnected) {
  const walletPubkey = window.solana.publicKey.toString();
  // 查询SOL余额
  const solBalance = await getSolBalance(walletPubkey);
  // 查询所有SPL资产余额
  const splBalances = await getAllSplTokenBalances(walletPubkey);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:06:02