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