1

Q1.What is the recommended way to fetch current cluster co-ordinated timestamp ? is it via fetching the clock account and deserializing it if so is there a method which takes care of deserializing it, Q2 there exists something along the lines of getParsedAccountInfo but i dont understand how is it possible for it decode any account info without having knowledge of the underlying Structure.

1
  • Please make one post per question
    – Jacob Creech
    Commented Jul 13, 2022 at 12:34

2 Answers 2

4

You can get the timestamp of the last processed block quite easily if that's sufficient:

const slot = await connection.getSlot({ commitment: 'processed' });
const timestamp = await connection.getBlockTime(slot);
1

There might be a cleaner way to do this but you can fetch the clock sysvar and the decode it using the following snippet:

import { AccountInfo, PublicKey } from '@solana/web3.js'
import { BN } from 'bn.js'

export const SYSVAR_OWNER_PUBKEY = new PublicKey(
  'Sysvar1111111111111111111111111111111111111'
)

interface Clock {
  slot: number
  epochStartTimestamp: number
  epoch: number
  leaderScheduleEpoch: number
  unixTimestamp: number
}

export function decodeSysvarClock(info: AccountInfo<Buffer>): Clock {
  if (!info.owner.equals(SYSVAR_OWNER_PUBKEY) || info.data.length !== 40) {
    throw new Error('invalid clock account')
  }

  return {
    slot: new BN(info.data.slice(0, 7), undefined, 'le').toNumber(),
    epochStartTimestamp: new BN(
      info.data.slice(8, 15),
      undefined,
      'le'
    ).toNumber(),
    epoch: new BN(info.data.slice(16, 23), undefined, 'le').toNumber(),
    leaderScheduleEpoch: new BN(
      info.data.slice(24, 31),
      undefined,
      'le'
    ).toNumber(),
    unixTimestamp: new BN(info.data.slice(32, 39), undefined, 'le').toNumber(),
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.