使用JavaScript异步函数通过JSON-RPC获取Phantom钱包余额失败如何解决
问题原因
- 你通过
phantom.request()调用getBalance方法不符合Phantom的API规范:Phantom注入的window.solana钱包提供者仅支持签名、连接、授权类的钱包交互方法,getBalance是Solana链的RPC查询方法,不归钱包提供者处理,因此会返回无对应响应的错误。 phantom.getBalance()本身不存在:Phantom没有向注入对象添加该原生方法,自然会报“不是函数”的错误。
解决方法
你不需要额外引入web3相关脚本也可以实现余额查询,只要直接向Solana的公开RPC节点发送查询请求即可,两种实现方案如下:
方案1:无额外依赖,直接发HTTP请求
// 原有get_provider方法保持不变 async function phantom_balance() { const phantom = get_provider(); if (!phantom?.isConnected) return; const walletAddress = phantom.publicKey.toString(); // 向Solana主网RPC节点发送getBalance查询请求 const rpcRes = await fetch("https://api.mainnet-beta.solana.com", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ "jsonrpc": "2.0", "id": 1, "method": "getBalance", "params": [walletAddress] }) }); const result = await rpcRes.json(); // 返回的余额单位是lamports,1 SOL = 10^9 lamports const solBalance = result.result.value / 1000000000; console.log("钱包SOL余额:", solBalance); return solBalance; }
如果需要查询测试网余额,把请求地址换成对应测试网的RPC节点即可。
方案2:引入@solana/web3.js简化开发
如果需要更便捷的处理各类Solana链上操作,可以在页面head中引入web3.js脚本:
<script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.min.js"></script>
之后就可以直接调用封装好的方法查询余额:
async function phantom_balance() { const phantom = get_provider(); if (!phantom?.isConnected) return; // 初始化主网RPC连接 const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('mainnet-beta')); // 直接传入公钥对象即可,无需转字符串 const balanceLamports = await connection.getBalance(phantom.publicKey); const solBalance = balanceLamports / 1e9; console.log("钱包SOL余额:", solBalance); return solBalance; }
内容的提问来源于stack exchange,提问作者Dapper
相关产品推荐
相关产品推荐

