@@ -232,6 +232,8 @@ import Data.ByteString
232
232
( ByteString )
233
233
import Data.Either.Extra
234
234
( maybeToEither )
235
+ import Data.Foldable
236
+ ( asum )
235
237
import Data.Function
236
238
( (&) )
237
239
import Data.Generics.Internal.VL.Lens
@@ -246,6 +248,8 @@ import Data.Proxy
246
248
( Proxy (.. ) )
247
249
import Data.Quantity
248
250
( Percentage , Quantity (.. ) )
251
+ import Data.Scientific
252
+ ( Scientific , toBoundedInteger )
249
253
import Data.String
250
254
( IsString )
251
255
import Data.Text
@@ -274,6 +278,8 @@ import GHC.TypeLits
274
278
( Nat , Symbol )
275
279
import Numeric.Natural
276
280
( Natural )
281
+ import Safe
282
+ ( readMay )
277
283
import Servant.API
278
284
( MimeRender (.. ), MimeUnrender (.. ), OctetStream )
279
285
import Web.HttpApiData
@@ -954,9 +960,40 @@ instance FromJSON ApiAddressDerivationPath where
954
960
parseJSON = fmap ApiAddressDerivationPath . parseJSON
955
961
956
962
instance ToJSON ApiAddressDerivationSegment where
957
- toJSON = genericToJSON defaultRecordTypeOptions
963
+ toJSON (ApiAddressDerivationSegment (ApiRelativeAddressIndex ix) typ)
964
+ | typ == Hardened = toJSON (show ix <> " H" )
965
+ | otherwise = toJSON (show ix)
958
966
instance FromJSON ApiAddressDerivationSegment where
959
- parseJSON = genericParseJSON defaultRecordTypeOptions
967
+ parseJSON value = asum
968
+ [ parseJSON value >>= parseAsScientific
969
+ , parseJSON value >>= parseAsText
970
+ ]
971
+ where
972
+ parseAsText :: Text -> Aeson. Parser ApiAddressDerivationSegment
973
+ parseAsText txt =
974
+ if " H" `T.isSuffixOf` txt then do
975
+ path <- castNumber (T. init txt) >>= parseAsScientific
976
+ pure $ path { derivationType = Hardened }
977
+ else
978
+ castNumber txt >>= parseAsScientific
979
+
980
+ parseAsScientific :: Scientific -> Aeson. Parser ApiAddressDerivationSegment
981
+ parseAsScientific x =
982
+ case toBoundedInteger x of
983
+ Nothing -> fail " expected an unsigned int31"
984
+ Just ix -> pure ApiAddressDerivationSegment
985
+ { derivationIndex = ApiRelativeAddressIndex ix
986
+ , derivationType = Soft
987
+ }
988
+
989
+ castNumber :: Text -> Aeson. Parser Scientific
990
+ castNumber txt =
991
+ case readMay (T. unpack txt) of
992
+ Nothing ->
993
+ fail " expected a number as string with an optional 'H' \
994
+ \suffix (e.g. \" 1815H\" or \" 44\" "
995
+ Just s ->
996
+ pure s
960
997
961
998
instance ToJSON (ApiAddressDerivationType ) where
962
999
toJSON = genericToJSON defaultSumTypeOptions
0 commit comments