5

I'd like to obtain the slot number corresponding to a posixtime on Cardano Testnet.

For example, this might be useful if you need to set a slot number in cardano-cli, say building a transaction: cardano-cli transaction build --invalid-before slotNumber

2 Answers 2

8

I share this code snippet with the converter.

module Week03.Converter ( posixTimeToSlotTestnetConverter ) where 

import Ledger          ( POSIXTime(POSIXTime), Slot(Slot) )
import Ledger.TimeSlot ( SlotConfig(SlotConfig), posixTimeToEnclosingSlot )

posixTimeToSlotTestnetConverter :: POSIXTime -> Slot
posixTimeToSlotTestnetConverter time = slotWhenSlotChangedTo1Sec + posixTimeToEnclosingSlot testnetConf time

timeWhenSlotChangedTo1Sec :: POSIXTime
timeWhenSlotChangedTo1Sec = POSIXTime 1595967616000  -- 2020/07/28 20:20:16 - epoch:74 - slot:1598400 - block:1597133  

slotWhenSlotChangedTo1Sec :: Slot
slotWhenSlotChangedTo1Sec = Slot 1598400

testnetConf :: SlotConfig
testnetConf = SlotConfig 1000 timeWhenSlotChangedTo1Sec

Kudos to @Travis for timeWhenSlotChangedTo1Sec value. See: When was the slot duration set to 1 sec on Cardano Testnet?

2

The accepted answer already explains how the calculation must be made and provides a sample code in Haskell; however, I will also leave here a simple snippet of code in Java, removing all the Haskell boilerplate (and can be easily ported to any other language).

/**
 * Converts from POSIX time to slot.
 *
 * @param time The POSIX time to be converted (in seconds).
 *
 * @return The matching slot.
 */
static long posixTimeToSlot(long time)
{
    long slotWhenSlotChangedTo1Sec = 1598400;
    long timeWhenSlotChangedTo1Sec = 1595967616L;

    long remainingSeconds = time - timeWhenSlotChangedTo1Sec;

    return slotWhenSlotChangedTo1Sec + remainingSeconds;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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