简体   繁体   English

Solana - 如何获取国外账户的代币余额?

[英]Solana - How to get token balance for a foreign account?

In Solana you can get your own balance with the CLI在 Solana 中,您可以使用 CLI 获得自己的平衡

$ spl-token accounts

But how do I get the token balance of a foreign account if I have the account ID or his pubkey?但是如果我有账户ID或者他的pubkey怎么获取国外账户的token余额呢? When I use the solana explorer I can see the information I need when I search for the foreign account ID and then click on the Tokens tab (next to "History"): https://explorer.solana.com/address/DNuqHBGxzm96VLkLWCUctjYW9CX68DBY6jQ1cVuYP2Ai/tokens?cluster=de.net当我使用 solana explorer 时,我可以在搜索外国帐户 ID 时看到我需要的信息,然后单击令牌选项卡(在“历史记录”旁边): https://explorer.solana.com/address/DNuqHBGxzm96VLkLWCUctjYW9CX68DBY6jQ1cVuYP2Ai/ tokens?cluster=de.net

So if the explorer website can do it, everybody can, all info on the blockchain is public, right?所以如果浏览器网站可以做到,那么每个人都可以,区块链上的所有信息都是公开的,对吧?

To get the list of foreign accounts with their balances, the following CLI command can be used:要获取国外账户及其余额的列表,可以使用以下 CLI 命令:

$ spl-token accounts --owner <account owner's pubkey>
  • where <account owner's pubkey> is the public key or address of the wallet you want to get the info about.其中 <account owner's pubkey> 是您想要获取其信息的钱包的公钥或地址。

没错,一切都是公开的,所以如果你想获得别人账户的余额,你可以简单地使用getBalance如果它是 SOL ( https://docs.solana.com/developing/clients/jsonrpc-api#getbalance )或getTokenAccountBalance如果它是 SPL 令牌帐户 ( https://docs.solana.com/developing/clients/jsonrpc-api#gettokenaccountbalance )。

Following code worked to get the balance for SOL after Jon Cinque's answer (maybe helpful for others or future me):以下代码在 Jon Cinque 的回答之后为 SOL 取得平衡(可能对其他人或未来的我有帮助):

const web3 = require("@solana/web3.js");
const { Keypair, Transaction, SystemProgram, LAMPORTS_PER_SOL, sendAndConfirmTransaction, clusterApiUrl } = require("@solana/web3.js");

let secretKey = Uint8Array.from([233, 65, ... (rest of my secret)]);

let fromKeypair = Keypair.fromSecretKey(secretKey);

let connection = new web3.Connection(clusterApiUrl('devnet'));

(async () => {

    const balance = await connection.getBalance(
        fromKeypair.publicKey
    );
    console.log(balance)
})()

Output: 7912350560 which is correct, since I have 7.912350560 SOL in that account.输出: 7912350560这是正确的,因为我在那个账户中有 7.912350560 SOL。

But for the SPL Token it didn't work yet...但是对于 SPL 令牌,它还没有工作......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM