Solana 查询区块接口
Solana
提供了多个接口用于获取区块链相关信息,包括当前区块高度、最近区块的信息、指定高度区块的信息、区块确认状态以及一次性获取多个区块的信息等。
1. 获取当前的区块高度
使用 getBlockHeight
方法可以获取当前区块链的最新区块高度。
我们在命令行中,通过 curl
命令发送 POST
请求到 Solana
的 RPC
接口。
curl https://api.devnet.solana.com -X POST -H "Content-Type: application/json" -d ' { "jsonrpc":"2.0",
"id":1, "method":"getBlockHeight" } '
返回结果:
{ "jsonrpc": "2.0", "result": 174302040, "id": 1 }
可以看到,当前测试网的高度到了 174302040。
2. 获取最近区块的 Hash
使用 getLatestBlockhash
方法可以获取连接最近的一个区块的 Hash
值和高度。
我们在命令行中,通过 curl
命令发送 POST
请求到 Solana
的 RPC
接口。
curl https://api.devnet.solana.com -X POST -H "Content-Type: application/json" -d ' { "jsonrpc":"2.0", "id":1, "method":"getLatestBlockhash", "params":[ { "commitment":"processed" } ] } '
返回结果包含了最近区块的 slot
、hash
和 block height
。
3. 获取指定区块的信息
使用 getBlock
方法获取指定高度的区块的信息。
curl https://api.devnet.solana.com -X POST -H "Content-Type: application/json" -d ' { "id":1, "jsonrpc": "2.0", "method":"getBlock", "params": [ 174302734, { "encoding": "jsonParsed", "maxSupportedTransactionVersion":0, "transactionDetails":"full", "rewards":false } ] } '
这里结果太多,不再罗列。
在请求中,我们加入了 "encoding": "jsonParsed",结果将按照 json 的格式进行展示。
transactionDetails 设置返回的交易信息的内容复杂等级,设置有"full", "accounts","signatures","none",默认是"full"。
maxSupportedTransactionVersion 这个参数和后面介绍的带版本号的交易有关,表示返回最大的版本号,默认是 0。
rewards 表示是否携带 rewards 信息。
4. 获取指定区块的确认状态
使用 getBlockCommitment
方法可以查看指定区块的确认状态。
我们在命令行中,通过 curl
命令发送 POST
请求到 Solana
的 RPC
接口。
curl https://api.devnet.solana.com -X POST -H "Content-Type: application/json" -d ' { "id": 1, "jsonrpc": "2.0", "method": "getBlockCommitment", "params":[174302734] } '
返回结果:
{ "jsonrpc": "2.0", "result": { "commitment": null, "totalStake": 144333782793465543 }, "id": 1 }
返回结果中包含了提交确认的节点总共 Stake
的 SOL
数目。
totalStake 表示提交确认的节点总共 Stake
的 SOL
数目,也就是 POS
的权重。
如果 commitment 不为 null 的时候,将是一个数组,表示各个集群中 Stake
的数量分布。
5. 获取多个区块的信息
使用 getBlocks
方法可以一次性获取多个指定区块的信息。
我们在命令行中,通过 curl
命令发送 POST
请求到 Solana
的 RPC
接口。
curl https://api.devnet.solana.com -X POST -H "Content-Type: application/json" -d ' { "jsonrpc": "2.0", "id": 1, "method": "getBlocks", "params": [ 174302734, 174302735 ] } '
这里参数中指定了多个区块号。
6. 分页获取区块
使用 getBlocksWithLimit
方法可以分页获取指定区块范围内的信息。
前面两个获取区块信息的方法,分别可以获得单个区块和多个指定区块的信息。
solana
还提供了一个分页查询的方式 getBlocksWithLimit
,从起始号连续查询多个区块的信息。
我们在命令行中,通过 curl
命令发送 POST
请求到 Solana
的 RPC
接口。
curl https://api.devnet.solana.com -X POST -H "Content-Type: application/json" -d ' { "jsonrpc": "2.0", "id":1, "method":"getBlocksWithLimit", "params":[174302734, 3] } '
这里的参数指定了起始区块号和要获取的区块数量。
返回结果:
{ "jsonrpc": "2.0", "result": [ 174302734, 174302735, 174302736 ], "id": 1 }
返回 3 个 BlockNumber
,我们可以使用前面的 GetBlocks
来获得它们的详细信息。