DEV Community

晓道
晓道

Posted on

1

solana 获取钱包token余额,及优化

这几天练习使用golang调用solana合约,切换一门语言,感觉不那么轻松,搞evm的时候,有ethereum的代码是go实现的,感觉golang 像是evm第一语言。
早上的时候,看群友提问

需求
1.想判断solana地址是否合法
2.想判断合法地址下,是否持有三个token中的任意一个,即balance > 1

刚好做练习,所以简单写写,思路如下:
用钱包地址和token地址算token的账号地址,再调用GetTokenAccountBalance

lokey :=solana.MustPublicKeyFromBase58("HgJ5zad5N4pwKpAM8HQDA3g2r2H7EMLVN6S5HvHdiNyR") //钱包地址
tokenmint := solana.MustPublicKeyFromBase58("J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn") //token 地址
tokenacc, _, _ := solana.FindAssociatedTokenAddress(lokey, tokenmint) //算出token账号地址
outtbl, err = client.GetTokenAccountBalance(context.Background(), tokenacc,rpc.CommitmentFinalized)
Enter fullscreen mode Exit fullscreen mode

后面群友提出更高效的方案:

可以用 rpc getMultipleAccounts 一次请求几百个token账户,批量拿几次应该就够了,降低helius rpc的额度消耗,同时性能也好

相对来说群友这个方法更好,毕竟helius的rpc都是有限额的,一条能搞定,就不要搞3条

这个思路上有一点点差异,这个是获取的账号数据,所以代码这么写:

//获取token 账号代码和前面一样
out, _ := client.GetMultipleAccounts(context.Background(), lokey, tokenacc, tokenacc2, tokenacc3, tokenacc4)
for _, ov := range out.Value {
    if ov != nil {
    if ov.Owner.String() == "11111111111111111111111111111111" { 
            log.Debugf("acc %s,bl %d", ov.Owner.String(), ov.Lamports)
    } else {
            var ta token.Account
            err = bin.NewBinDecoder(ov.Data.GetBinary()).Decode(&ta)
            log.Debugf("acc %s,bl %d", ta.Owner.String(), ta.Amount)
    }
    }
}
Enter fullscreen mode Exit fullscreen mode

我就随便发发,做做笔记,欢迎交流。

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay