2

Solana Rust smart contracts have access to

solana_program::clock::Clock::get()?.unix_timestamp

which is seconds from epoch (midnight Jan 1st 1970 GMT) but has a significant drift from any real-world time-zone as a product of Solana's slowdowns over time. Many contracts factor in this unix timestamp when calculating reward amounts (notably Step Finance and therefore Gem Farm which reuses the logic). How can I reconstruct this Solana unix timestamp on the front-end in JavaScript without requiring any transaction / wallet signature? Calls to a Solana node RPC are fine.

Ozymandias
  • 2,533
  • 29
  • 33

1 Answers1

1

You can use the getBlockTime endpoint from JSON RPC. First you'll need the highest slot using the getSlot. That would become:

const connection = new Connection('https://api.testnet.solana.com', 'processed');
const slot = await connection.getSlot();
const timestamp = await connection.getBlockTime(slot);

More info at https://docs.solana.com/developing/clients/jsonrpc-api#getblocktime and https://docs.solana.com/developing/clients/jsonrpc-api#getslot

Jon C
  • 7,019
  • 10
  • 17
  • This seems to somewhat work, however it seems to usually return a different value (off by a few seconds) than the value of the `unix_timestamp` which always seems to be consistent. – Ozymandias Jun 03 '22 at 04:24
  • 1
    good point -- since this example uses `'confirmed'`, it will be a little behind. I'll amend it to use `'processed'`, which should be better – Jon C Jun 03 '22 at 10:07