{-# LANGUAGE NamedFieldPuns #-}
module Cardano.Node.Params where

import Cardano.Api.NetworkId.Extra (NetworkIdWrapper (..))
import Cardano.Api.Shelley (ProtocolParameters)
import Cardano.Node.Emulator.Params
import Cardano.Node.Types
import Data.Aeson (eitherDecode)
import Data.ByteString.Lazy qualified as BSL
import Data.Default (def)

fromPABServerConfig :: PABServerConfig -> IO Params
fromPABServerConfig :: PABServerConfig -> IO Params
fromPABServerConfig PABServerConfig{SlotConfig
pscSlotConfig :: PABServerConfig -> SlotConfig
pscSlotConfig :: SlotConfig
pscSlotConfig, NetworkIdWrapper
pscNetworkId :: PABServerConfig -> NetworkIdWrapper
pscNetworkId :: NetworkIdWrapper
pscNetworkId, Maybe FilePath
pscProtocolParametersJsonPath :: PABServerConfig -> Maybe FilePath
pscProtocolParametersJsonPath :: Maybe FilePath
pscProtocolParametersJsonPath} = do
  let NetworkIdWrapper NetworkId
networkId = NetworkIdWrapper
pscNetworkId
  ProtocolParameters
protocolParameters <- Maybe FilePath -> IO ProtocolParameters
readProtocolParameters Maybe FilePath
pscProtocolParametersJsonPath
  Params -> IO Params
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Params -> IO Params) -> Params -> IO Params
forall a b. (a -> b) -> a -> b
$ SlotConfig -> ProtocolParameters -> NetworkId -> Params
paramsWithProtocolsParameters SlotConfig
pscSlotConfig ProtocolParameters
protocolParameters NetworkId
networkId

readProtocolParameters :: Maybe FilePath -> IO ProtocolParameters
readProtocolParameters :: Maybe FilePath -> IO ProtocolParameters
readProtocolParameters = IO ProtocolParameters
-> (FilePath -> IO ProtocolParameters)
-> Maybe FilePath
-> IO ProtocolParameters
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (ProtocolParameters -> IO ProtocolParameters
forall (f :: * -> *) a. Applicative f => a -> f a
pure ProtocolParameters
forall a. Default a => a
def) FilePath -> IO ProtocolParameters
forall b. FromJSON b => FilePath -> IO b
readPP
  where
    readPP :: FilePath -> IO b
readPP FilePath
path = do
      ByteString
bs <- FilePath -> IO ByteString
BSL.readFile FilePath
path
      case ByteString -> Either FilePath b
forall a. FromJSON a => ByteString -> Either FilePath a
eitherDecode ByteString
bs of
        Left FilePath
err -> FilePath -> IO b
forall a. HasCallStack => FilePath -> a
error (FilePath -> IO b) -> FilePath -> IO b
forall a b. (a -> b) -> a -> b
$ FilePath
"Error reading protocol parameters JSON file: "
                         FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath -> FilePath
forall a. Show a => a -> FilePath
show FilePath
path FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
" (" FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
err FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
")"
        Right b
params -> b -> IO b
forall (f :: * -> *) a. Applicative f => a -> f a
pure b
params