Skip to content

Commit d677557

Browse files
authored
Merge pull request #4686 from input-output-hk/ch1bo/cardano-api-chain-point-json-instances
[cardano-api] Add ToJSON/FromJSON instances for ChainPoint
2 parents 8d969ec + 3b01002 commit d677557

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

cardano-api/src/Cardano/Api/Block.hs

+19
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
{-# LANGUAGE FlexibleContexts #-}
33
{-# LANGUAGE FlexibleInstances #-}
44
{-# LANGUAGE GADTs #-}
5+
{-# LANGUAGE LambdaCase #-}
56
{-# LANGUAGE NamedFieldPuns #-}
67
{-# LANGUAGE PatternSynonyms #-}
78
{-# LANGUAGE RankNTypes #-}
@@ -358,6 +359,24 @@ instance Ord ChainPoint where
358359
compare _ ChainPointAtGenesis = GT
359360
compare (ChainPoint sn _) (ChainPoint sn' _) = compare sn sn'
360361

362+
instance ToJSON ChainPoint where
363+
toJSON = \case
364+
ChainPointAtGenesis -> object ["tag" .= String "ChainPointAtGenesis"]
365+
ChainPoint slot blockHash ->
366+
object
367+
[ "tag" .= String "ChainPoint"
368+
, "slot" .= toJSON slot
369+
, "blockHash" .= toJSON blockHash
370+
]
371+
372+
instance FromJSON ChainPoint where
373+
parseJSON = withObject "ChainPoint" $ \o -> do
374+
tag <- o .: "tag"
375+
case tag :: Text of
376+
"ChainPointAtGenesis" -> pure ChainPointAtGenesis
377+
"ChainPoint" -> ChainPoint <$> o .: "slot" <*> o .: "blockHash"
378+
_ -> fail "Expected tag to be ChainPointAtGenesis | ChainPoint"
379+
361380
toConsensusPointInMode :: ConsensusMode mode
362381
-> ChainPoint
363382
-> Consensus.Point (ConsensusBlockForMode mode)

0 commit comments

Comments
 (0)