How can a Solana Rust smart contract get block height or Unix time?

Viewed 1954

I know how to pass the current Unix time from the frontend:

web3.js:

anchor.web3.SYSVAR_CLOCK_PUBKEY

Rust:

let current_time = ctx.accounts.clock.unix_timestamp;

I do not want that. I need the smart contract itself to get the current time.

2 Answers

I'm assuming you're using anchor

let now_ts = Clock::get().unwrap().unix_timestamp;

You will need to pass in the system program account

Take a look at the sysvar data examples at the top of this page: https://docs.solana.com/developing/runtime-facilities/sysvars

You have two ways from the smart contract / on-chain program:

let clock = Clock::get();

or you pass in the account to the instruction from the outside, then deserialize the clock from that account:

let clock_sysvar_info = next_account_info(account_info_iter)?;
let clock = Clock::from_account_info(&clock_sysvar_info)?;
Related