I need help in calculating Slot Number from Current Epoch and Slot. Is there a formula to calculate that?
5 Answers
You can check the genesis file for timestamp network started on (mainnet/testnet started on Byron) and use epoch/Slot for Byron (where an epoch consisted of 21600 slots, 1 slot being 20s) and shelley (where epoch consists of 432000 slots, 1 slot being 1s) respectively - all of this is in genesis JSONs you refer your node to on startup. The important bit here is knowing when Byron transited to Shelley, for mainnet, the epoch was 208.
You can find sample of how gLiveView calculates it here. You can also use ogmios to fetch era info from node (or use dbsync to know which epoch did forks get applied in).
Unfortunately while there may be such a formula it would be rather complex and would be different for each network (eg mainnet, testnet etc).
For all of the Byron Era, one slot has been 20 seconds long. Since the Shelley Hardfork (Epoch 208), one slot has been 1 second long. Assuming 1 slot will continue to be 1 second long, we can derive an approximate formula using the Unix Epoch time standard.
Epoch 208 started at 07/29/2020 at 21:44:51 PM UTC, or 1596059091 in UNIX time, at an absolute slot number of 4492800 (according to Cardanoscan)
Therefore, we can approximate that the current slot is:
<CURRENT_UNIX_TIME> - 1596059091 + 4492800 or simply,
<CURRENT_UNIX_TIME> - 1591566291
Which is a reasonable estimate after a quick test...
Since cardano-cli version 8.2.0 there exists cardano-cli query slot-number
which will calculate slot number from UTC time.
E.g a sample query (taken from the merge request):
cardano-cli -- query slot-number --mainnet --socket-path /path/to/socket '2023-04-24T09:12:42Z'
will give you slot 90761271.
a couple informations from the genses file are neede; particoularly you will need the POSIX timestap at which the chain was started ("system start") and the slot length in milliseconds
The formula in used in plu-ts is the following:
function POSIXToSlot( POSIX: number, sysStartPOSIX: number, slotLenMs: number ): number
{
return Math.floor( (POSIX - sysStartPOSIX) / slotLenMs );
}
function slotToPOSIX( slotN: number, sysStartPOSIX: number, slotLenMs: number ): number
{
return sysStartPOSIX + (slotLenMs * slotN);
}