-
Notifications
You must be signed in to change notification settings - Fork 722
/
Value.hs
409 lines (326 loc) · 12.6 KB
/
Value.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
-- | Currency values
--
module Cardano.Api.Value
( Lovelace(..)
-- * Multi-asset values
, Quantity(..)
, PolicyId(..)
, scriptPolicyId
, AssetName(..)
, AssetId(..)
, Value
, selectAsset
, valueFromList
, valueToList
, filterValue
, negateValue
, calcMinimumDeposit
-- ** Ada \/ Lovelace specifically
, quantityToLovelace
, lovelaceToQuantity
, selectLovelace
, lovelaceToValue
, valueToLovelace
-- ** Alternative nested representation
, ValueNestedRep(..)
, ValueNestedBundle(..)
, valueToNestedRep
, valueFromNestedRep
-- ** Rendering
, renderValue
, renderValuePretty
-- * Internal conversion functions
, toByronLovelace
, fromByronLovelace
, toShelleyLovelace
, fromShelleyLovelace
, fromShelleyDeltaLovelace
, toMaryValue
, fromMaryValue
-- * Data family instances
, AsType(..)
) where
import Prelude
import Data.Aeson (FromJSON, FromJSONKey, ToJSON, object, parseJSON, toJSON, withObject)
import qualified Data.Aeson as Aeson
import Data.Aeson.Types (Parser, ToJSONKey)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Map.Merge.Strict as Map
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.String (IsString (..))
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import qualified Cardano.Chain.Common as Byron
import qualified Cardano.Ledger.Coin as Shelley
import Cardano.Ledger.Crypto (StandardCrypto)
import qualified Cardano.Ledger.Mary.Value as Mary
import qualified Cardano.Ledger.ShelleyMA.Rules.Utxo as Shelley
import Cardano.Api.HasTypeProxy
import Cardano.Api.Script
import Cardano.Api.SerialiseCBOR
import Cardano.Api.SerialiseRaw
import Cardano.Api.SerialiseUsing
-- ----------------------------------------------------------------------------
-- Lovelace
--
newtype Lovelace = Lovelace Integer
deriving stock (Eq, Ord, Show)
deriving newtype (Enum, Num, ToJSON, FromJSON, ToCBOR, FromCBOR)
instance Semigroup Lovelace where
Lovelace a <> Lovelace b = Lovelace (a + b)
instance Monoid Lovelace where
mempty = Lovelace 0
toByronLovelace :: Lovelace -> Maybe Byron.Lovelace
toByronLovelace (Lovelace x) =
case Byron.integerToLovelace x of
Left _ -> Nothing
Right x' -> Just x'
fromByronLovelace :: Byron.Lovelace -> Lovelace
fromByronLovelace = Lovelace . Byron.lovelaceToInteger
toShelleyLovelace :: Lovelace -> Shelley.Coin
toShelleyLovelace (Lovelace l) = Shelley.Coin l
--TODO: validate bounds
fromShelleyLovelace :: Shelley.Coin -> Lovelace
fromShelleyLovelace (Shelley.Coin l) = Lovelace l
fromShelleyDeltaLovelace :: Shelley.DeltaCoin -> Lovelace
fromShelleyDeltaLovelace (Shelley.DeltaCoin d) = Lovelace d
-- ----------------------------------------------------------------------------
-- Multi asset Value
--
newtype Quantity = Quantity Integer
deriving newtype (Eq, Ord, Num, Show, ToJSON, FromJSON)
instance Semigroup Quantity where
Quantity a <> Quantity b = Quantity (a + b)
instance Monoid Quantity where
mempty = Quantity 0
lovelaceToQuantity :: Lovelace -> Quantity
lovelaceToQuantity (Lovelace x) = Quantity x
quantityToLovelace :: Quantity -> Lovelace
quantityToLovelace (Quantity x) = Lovelace x
newtype PolicyId = PolicyId ScriptHash
deriving stock (Eq, Ord)
deriving (Show, IsString, ToJSON, FromJSON) via UsingRawBytesHex PolicyId
instance HasTypeProxy PolicyId where
data AsType PolicyId = AsPolicyId
proxyToAsType _ = AsPolicyId
instance SerialiseAsRawBytes PolicyId where
serialiseToRawBytes (PolicyId sh) = serialiseToRawBytes sh
deserialiseFromRawBytes AsPolicyId bs =
PolicyId <$> deserialiseFromRawBytes AsScriptHash bs
scriptPolicyId :: Script lang -> PolicyId
scriptPolicyId = PolicyId . hashScript
newtype AssetName = AssetName ByteString
deriving stock (Eq, Ord)
deriving newtype (Show)
deriving (ToJSON, FromJSON, ToJSONKey, FromJSONKey)
via UsingRawBytesHex AssetName
instance IsString AssetName where
fromString s
| let bs = Text.encodeUtf8 (Text.pack s)
, BS.length bs <= 32 = AssetName (BSC.pack s)
| otherwise = error "fromString: AssetName over 32 bytes"
instance HasTypeProxy AssetName where
data AsType AssetName = AsAssetName
proxyToAsType _ = AsAssetName
instance SerialiseAsRawBytes AssetName where
serialiseToRawBytes (AssetName bs) = bs
deserialiseFromRawBytes AsAssetName bs
| BS.length bs <= 32 = Just (AssetName bs)
| otherwise = Nothing
data AssetId = AdaAssetId
| AssetId !PolicyId !AssetName
deriving (Eq, Ord, Show)
newtype Value = Value (Map AssetId Quantity)
deriving Eq
instance Show Value where
showsPrec d v = showParen (d > 10) $
showString "valueFromList " . shows (valueToList v)
instance Semigroup Value where
Value a <> Value b = Value (mergeAssetMaps a b)
instance Monoid Value where
mempty = Value Map.empty
{-# NOINLINE mergeAssetMaps #-} -- as per advice in Data.Map.Merge docs
mergeAssetMaps :: Map AssetId Quantity
-> Map AssetId Quantity
-> Map AssetId Quantity
mergeAssetMaps =
Map.merge
Map.preserveMissing
Map.preserveMissing
(Map.zipWithMaybeMatched mergeQuantity)
where
mergeQuantity :: AssetId -> Quantity -> Quantity -> Maybe Quantity
mergeQuantity _k a b =
case a <> b of
Quantity 0 -> Nothing
c -> Just c
instance ToJSON Value where
toJSON = toJSON . valueToNestedRep
instance FromJSON Value where
parseJSON v = valueFromNestedRep <$> parseJSON v
selectAsset :: Value -> (AssetId -> Quantity)
selectAsset (Value m) a = Map.findWithDefault mempty a m
valueFromList :: [(AssetId, Quantity)] -> Value
valueFromList = Value
. Map.filter (/= 0)
. Map.fromListWith (<>)
valueToList :: Value -> [(AssetId, Quantity)]
valueToList (Value m) = Map.toList m
-- | This lets you write @a - b@ as @a <> negateValue b@.
--
negateValue :: Value -> Value
negateValue (Value m) = Value (Map.map negate m)
filterValue :: (AssetId -> Bool) -> Value -> Value
filterValue p (Value m) = Value (Map.filterWithKey (\k _v -> p k) m)
selectLovelace :: Value -> Lovelace
selectLovelace = quantityToLovelace . flip selectAsset AdaAssetId
lovelaceToValue :: Lovelace -> Value
lovelaceToValue = Value . Map.singleton AdaAssetId . lovelaceToQuantity
-- | Check if the 'Value' consists of /only/ 'Lovelace' and no other assets,
-- and if so then return the Lovelace.
--
-- See also 'selectLovelace' to select the Lovelace quantity from the Value,
-- ignoring other assets.
--
valueToLovelace :: Value -> Maybe Lovelace
valueToLovelace v =
case valueToList v of
[] -> Just (Lovelace 0)
[(AdaAssetId, q)] -> Just (quantityToLovelace q)
_ -> Nothing
toMaryValue :: Value -> Mary.Value StandardCrypto
toMaryValue v =
Mary.Value lovelace other
where
Quantity lovelace = selectAsset v AdaAssetId
--TODO: write QC tests to show it's ok to use Map.fromAscListWith here
other = Map.fromListWith Map.union
[ (toMaryPolicyID pid, Map.singleton (toMaryAssetName name) q)
| (AssetId pid name, Quantity q) <- valueToList v ]
toMaryPolicyID :: PolicyId -> Mary.PolicyID StandardCrypto
toMaryPolicyID (PolicyId sh) = Mary.PolicyID (toShelleyScriptHash sh)
toMaryAssetName :: AssetName -> Mary.AssetName
toMaryAssetName (AssetName n) = Mary.AssetName n
fromMaryValue :: Mary.Value StandardCrypto -> Value
fromMaryValue (Mary.Value lovelace other) =
Value $
--TODO: write QC tests to show it's ok to use Map.fromAscList here
Map.fromList $
[ (AdaAssetId, Quantity lovelace) | lovelace /= 0 ]
++ [ (AssetId (fromMaryPolicyID pid) (fromMaryAssetName name), Quantity q)
| (pid, as) <- Map.toList other
, (name, q) <- Map.toList as ]
where
fromMaryPolicyID :: Mary.PolicyID StandardCrypto -> PolicyId
fromMaryPolicyID (Mary.PolicyID sh) = PolicyId (fromShelleyScriptHash sh)
fromMaryAssetName :: Mary.AssetName -> AssetName
fromMaryAssetName (Mary.AssetName n) = AssetName n
-- | Calculate cost of making a UTxO entry for a given 'Value' and
-- mininimum UTxO value derived from the 'ProtocolParameters'
calcMinimumDeposit :: Value -> Lovelace -> Lovelace
calcMinimumDeposit v minUTxo =
fromShelleyLovelace $ Shelley.scaledMinDeposit (toMaryValue v) (toShelleyLovelace minUTxo)
-- ----------------------------------------------------------------------------
-- An alternative nested representation
--
-- | An alternative nested representation for 'Value' that groups assets that
-- share a 'PolicyId'.
--
newtype ValueNestedRep = ValueNestedRep [ValueNestedBundle]
deriving (Eq, Ord, Show)
-- | A bundle within a 'ValueNestedRep' for a single 'PolicyId', or for the
-- special case of ada.
--
data ValueNestedBundle = ValueNestedBundleAda Quantity
| ValueNestedBundle PolicyId (Map AssetName Quantity)
deriving (Eq, Ord, Show)
valueToNestedRep :: Value -> ValueNestedRep
valueToNestedRep v =
-- unflatten all the non-ada assets, and add ada separately
ValueNestedRep $
[ ValueNestedBundleAda q | let q = selectAsset v AdaAssetId, q /= 0 ]
++ [ ValueNestedBundle 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) <- valueToList v ]
valueFromNestedRep :: ValueNestedRep -> Value
valueFromNestedRep (ValueNestedRep bundles) =
valueFromList
[ (aId, q)
| bundle <- bundles
, (aId, q) <- case bundle of
ValueNestedBundleAda q -> [ (AdaAssetId, q) ]
ValueNestedBundle pId qs -> [ (AssetId pId aName, q)
| (aName, q) <- Map.toList qs ]
]
instance ToJSON ValueNestedRep where
toJSON (ValueNestedRep bundles) = object $ map toPair bundles
where
toPair :: ValueNestedBundle -> (Text, Aeson.Value)
toPair (ValueNestedBundleAda q) = ("lovelace", toJSON q)
toPair (ValueNestedBundle pid assets) = (renderPolicyId pid, toJSON assets)
instance FromJSON ValueNestedRep where
parseJSON =
withObject "ValueNestedRep" $ \obj ->
ValueNestedRep <$> sequenceA [ parsePid keyValTuple
| keyValTuple <- HashMap.toList obj ]
where
parsePid :: (Text, Aeson.Value) -> Parser ValueNestedBundle
parsePid ("lovelace", q) = ValueNestedBundleAda <$> parseJSON q
parsePid (pid, quantityBundleJson) = do
sHash <-
note ("Expected hex encoded PolicyId but got: " <> Text.unpack pid) $
deserialiseFromRawBytesHex AsScriptHash $ Text.encodeUtf8 pid
quantityBundle <- parseJSON quantityBundleJson
pure $ ValueNestedBundle (PolicyId sHash) quantityBundle
note :: MonadFail m => String -> Maybe a -> m a
note msg = \case
Nothing -> fail msg
Just a -> pure a
-- ----------------------------------------------------------------------------
-- Printing and pretty-printing
--
-- | Render a textual representation of a 'Value'.
--
renderValue :: Value -> Text
renderValue v =
Text.intercalate
" + "
(map renderAssetIdQuantityPair vals)
where
vals :: [(AssetId, Quantity)]
vals = valueToList v
-- | Render a \"prettified\" textual representation of a 'Value'.
renderValuePretty :: Value -> Text
renderValuePretty v =
Text.intercalate
("\n" <> Text.replicate 4 " " <> "+ ")
(map renderAssetIdQuantityPair vals)
where
vals :: [(AssetId, Quantity)]
vals = valueToList v
renderAssetIdQuantityPair :: (AssetId, Quantity) -> Text
renderAssetIdQuantityPair (aId, quant) =
Text.pack (show quant) <> " " <> renderAssetId aId
renderPolicyId :: PolicyId -> Text
renderPolicyId (PolicyId scriptHash) = serialiseToRawBytesHexText scriptHash
renderAssetId :: AssetId -> Text
renderAssetId AdaAssetId = "lovelace"
renderAssetId (AssetId polId (AssetName "")) = renderPolicyId polId
renderAssetId (AssetId polId assetName) =
renderPolicyId polId <> "." <> serialiseToRawBytesHexText assetName