Skip to content

Commit

Permalink
fix unflatten and simplify flatten
Browse files Browse the repository at this point in the history
the unflatten needs to merge at the second level
  • Loading branch information
dcoutts committed Nov 22, 2020
1 parent 1f59ffc commit a9abdf1
Showing 1 changed file with 20 additions and 11 deletions.
31 changes: 20 additions & 11 deletions cardano-api/src/Cardano/Api/Value.hs
Expand Up @@ -135,23 +135,32 @@ instance ToJSON Value where
toJSON = toJSON . unflatten

unflatten :: Value -> AssetsBundle
unflatten (Value flatMap) = AssetsBundle [ toBundle aIdq | aIdq <- Map.toList flatMap]
where
toBundle :: (AssetId, Quantity) -> AssetIdBundle
toBundle (AssetId pId aName, q) = AssetIdBundle pId $ Map.singleton aName q
toBundle (AdaAssetId, q) = AdaAsset q
unflatten v@(Value flatMap) =
-- unflatten all the non-ada assets, and add ada separately
AssetsBundle $
[ AdaAsset q | let q = selectAsset v AdaAssetId, q /= 0 ]
++ [ AssetIdBundle pId qs | (pId, qs) <- Map.toList nonAdaAssets ]
where
nonAdaAssets :: Map PolicyId (Map AssetName Quantity)
nonAdaAssets =
Map.fromListWith (Map.unionWith (<>))
[ (pId, Map.singleton aName q)
| (AssetId pId aName, q) <- Map.toList flatMap ]

instance FromJSON Value where
parseJSON jv = flatten <$> parseJSON jv

flatten :: AssetsBundle -> Value
flatten (AssetsBundle bundles) =
Value . Map.fromList $ concat [ convToTuple aIdBundle | aIdBundle <- bundles]
where
convToTuple :: AssetIdBundle -> [(AssetId, Quantity)]
convToTuple (AssetIdBundle pId aNameAndQuantityMap) =
map (\(aName,q) -> (AssetId pId aName, q)) $ Map.toList aNameAndQuantityMap
convToTuple (AdaAsset q) = pure $ (AdaAssetId, q)
Value $
Map.fromList
[ (aId, q)
| bundle <- bundles
, (aId, q) <- case bundle of
AdaAsset q -> [ (AdaAssetId, q) ]
AssetIdBundle pId qs -> [ (AssetId pId aName, q)
| (aName, q) <- Map.toList qs ]
]

-- | Intermediate representation used in the JSON parsing\/rendering of 'Value'
newtype AssetsBundle = AssetsBundle [AssetIdBundle]
Expand Down

0 comments on commit a9abdf1

Please sign in to comment.