admin管理员组文章数量:1392101
I want to get the block number by timestamp, similar to the ETH getBlockByTime
method, but I haven’t found a good solution on Solana yet.
Currently I calculate it myself, but this is very troublesome. Is there a more convenient way?
public BigInteger getSlotForTimestamp(long targetTimestamp) throws Exception {
RpcClient client = new RpcClient(SOLANA_RPC_URL);
RpcApi api = client.getApi();
long latestSlot = api.getSlot();
if (latestSlot == 0) {
throw new Exception("Failed to get the latest slot");
}
long latestBlockTime = api.getBlockTime(latestSlot);
long earliestSlot = 0;
if (targetTimestamp <= earliestSlot) {
return BigInteger.valueOf(earliestSlot);
}
if (targetTimestamp >= latestBlockTime) {
return BigInteger.valueOf(latestSlot);
}
BigInteger left = BigInteger.valueOf(earliestSlot);
BigInteger right = BigInteger.valueOf(latestSlot);
BigInteger result = right;
while (leftpareTo(right) <= 0) {
BigInteger mid = left.add(right).divide(BigInteger.TWO);
long midTime = api.getBlockTime(mid.longValue());
if (midTime < targetTimestamp) {
result = mid;
left = mid.add(BigInteger.ONE);
} else if (midTime > targetTimestamp) {
right = mid.subtract(BigInteger.ONE);
} else {
return mid;
}
}
return result;
}
本文标签: javaIs there a way to get the solana block number by datetimeStack Overflow
版权声明:本文标题:java - Is there a way to get the solana block number by datetime? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744780422a2624676.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论