Search code examples
solanaanchor-solana

How can I get the current blockhash inside a Solana program function?


In Solidity, it's possible to use block.number and blockhash(uint blockNumber) returns (bytes32) to obtain the current blockhash from inside a function. I need do the same thing inside a Solana program. I'm using Anchor.

I went through Anchor docs and found a (deprecated) method to get recent blockhashes, but not the current blockhash. I've also tried finding similar projects that might rely on the current blockhash, but I haven't found anything yet.

Is it possible to access the current block hash from inside a Solana program function?


Solution

  • You were looking in the right place -- RecentBlockhashes is on its way out, but you can use the SlotHashes sysvar: https://docs.rs/solana-program/1.10.19/solana_program/slot_hashes/struct.SlotHashes.html

    It's tougher to use since you can't deserialize the whole thing into memory on-chain, but you can at least deserialize slices of it.