-- Copyright 2026 Biglup Labs
-- SPDX-License-Identifier: Apache-2.0
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE OverloadedStrings #-}

-- | Immutable signed asset bundles with arbitrary-precision quantities.
-- Duplicate assets add, zero quantities disappear, and missing assets have
-- quantity zero. Signed deltas compose without overflow or clamping.
--
-- @
-- import qualified Cometa.AssetId as AssetId
-- import qualified Cometa.Value as Value
--
-- remaining :: Value.Value -> Value.Value -> Integer
-- remaining available required =
--   Value.quantity AssetId.Ada (Value.difference available required)
-- @
module Cometa.Value
  ( Value,

    -- * Construction
    singleton,
    lovelace,
    fromList,

    -- * Inspection
    toList,
    quantity,
    isZero,
    isNonNegative,
    assetCount,
    intersection,

    -- * Arithmetic
    negate,
    difference,
    scale,
    positivePart,
    negativePart,

    -- * Serialization
    encodeCbor,
    decodeCbor,
    encodeMintCbor,
    decodeMintCbor,
  )
where

-- IMPORTS --------------------------------------------------------------------

import qualified Codec.CBOR.Decoding as D
import qualified Codec.CBOR.Encoding as E
import Cometa.AssetId (AssetId (..))
import qualified Cometa.AssetName as Name
import Cometa.Error (Error (..))
import qualified Cometa.Internal.TransactionCbor as Cbor
import qualified Cometa.PolicyId as Policy
import Control.Monad (unless)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Int (Int64)
import Data.List (sortOn)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Prelude hiding (negate)

-- TYPES ----------------------------------------------------------------------

-- | A finite bundle of signed asset quantities. Ada quantities count
-- lovelace; native quantities count units of the corresponding asset.
-- Equality compares quantities, ignoring absent zero entries. 'Show' is
-- diagnostic output. Signed values need not be valid transaction outputs or
-- mint quantities; those uses impose additional constraints.
newtype Value = Value (Map AssetId Integer) deriving (Value -> Value -> Bool
(Value -> Value -> Bool) -> (Value -> Value -> Bool) -> Eq Value
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Value -> Value -> Bool
== :: Value -> Value -> Bool
$c/= :: Value -> Value -> Bool
/= :: Value -> Value -> Bool
Eq, Int -> Value -> ShowS
[Value] -> ShowS
Value -> String
(Int -> Value -> ShowS)
-> (Value -> String) -> ([Value] -> ShowS) -> Show Value
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Value -> ShowS
showsPrec :: Int -> Value -> ShowS
$cshow :: Value -> String
show :: Value -> String
$cshowList :: [Value] -> ShowS
showList :: [Value] -> ShowS
Show)

-- | Pointwise addition with zero results removed. Associative and commutative.
instance Semigroup Value where
  Value Map AssetId Integer
left <> :: Value -> Value -> Value
<> Value Map AssetId Integer
right = Map AssetId Integer -> Value
normalized ((Integer -> Integer -> Integer)
-> Map AssetId Integer
-> Map AssetId Integer
-> Map AssetId Integer
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
Map.unionWith Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
(+) Map AssetId Integer
left Map AssetId Integer
right)

-- | The empty bundle is the identity for addition.
instance Monoid Value where
  mempty :: Value
mempty = Map AssetId Integer -> Value
Value Map AssetId Integer
forall k a. Map k a
Map.empty

-- DEFINITIONS ----------------------------------------------------------------

-- | One asset quantity. Zero produces 'mempty'; negative quantities are retained.
singleton :: AssetId -> Integer -> Value
singleton :: AssetId -> Integer -> Value
singleton AssetId
asset Integer
amount = Map AssetId Integer -> Value
normalized (AssetId -> Integer -> Map AssetId Integer
forall k a. k -> a -> Map k a
Map.singleton AssetId
asset Integer
amount)

-- | An Ada quantity measured in lovelace. Zero produces 'mempty'; negative
-- amounts represent signed Ada deltas.
lovelace :: Integer -> Value
lovelace :: Integer -> Value
lovelace = AssetId -> Integer -> Value
singleton AssetId
Ada

-- | Assemble entries by adding duplicate assets and removing zero totals.
-- Input order does not affect the resulting value.
fromList :: [(AssetId, Integer)] -> Value
fromList :: [(AssetId, Integer)] -> Value
fromList = Map AssetId Integer -> Value
normalized (Map AssetId Integer -> Value)
-> ([(AssetId, Integer)] -> Map AssetId Integer)
-> [(AssetId, Integer)]
-> Value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Integer -> Integer -> Integer)
-> [(AssetId, Integer)] -> Map AssetId Integer
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
(+)

-- | Nonzero entries in ascending 'AssetId' order: Ada, then policy/name bytes
-- lexicographically. This is not insertion order or CBOR map ordering.
toList :: Value -> [(AssetId, Integer)]
toList :: Value -> [(AssetId, Integer)]
toList (Value Map AssetId Integer
amounts) = Map AssetId Integer -> [(AssetId, Integer)]
forall k a. Map k a -> [(k, a)]
Map.toAscList Map AssetId Integer
amounts

-- | Quantity of the requested asset, or zero when absent.
quantity :: AssetId -> Value -> Integer
quantity :: AssetId -> Value -> Integer
quantity AssetId
asset (Value Map AssetId Integer
amounts) = Integer -> AssetId -> Map AssetId Integer -> Integer
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Integer
0 AssetId
asset Map AssetId Integer
amounts

-- | Negate every quantity exactly. The sum of a value and its negation is zero.
negate :: Value -> Value
negate :: Value -> Value
negate = Integer -> Value -> Value
scale (-Integer
1)

-- | Left value minus right value, retaining negative results.
difference :: Value -> Value -> Value
difference :: Value -> Value -> Value
difference Value
left Value
right = Value
left Value -> Value -> Value
forall a. Semigroup a => a -> a -> a
<> Value -> Value
negate Value
right

-- | Multiply every quantity by an arbitrary signed scalar. Scaling by zero
-- yields 'mempty'; no quantity limit is imposed.
scale :: Integer -> Value -> Value
scale :: Integer -> Value -> Value
scale Integer
factor (Value Map AssetId Integer
amounts) = Map AssetId Integer -> Value
normalized ((Integer -> Integer) -> Map AssetId Integer -> Map AssetId Integer
forall a b k. (a -> b) -> Map k a -> Map k b
Map.map (Integer
factor Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
*) Map AssetId Integer
amounts)

-- | Whether all quantities are zero, equivalently whether the bundle is empty.
isZero :: Value -> Bool
isZero :: Value -> Bool
isZero (Value Map AssetId Integer
amounts) = Map AssetId Integer -> Bool
forall k a. Map k a -> Bool
Map.null Map AssetId Integer
amounts

-- | Whether every quantity is nonnegative. True for the empty bundle. This
-- inspection does not check quantity limits, minimum Ada or other output requirements.
isNonNegative :: Value -> Bool
isNonNegative :: Value -> Bool
isNonNegative (Value Map AssetId Integer
amounts) = (Integer -> Bool) -> Map AssetId Integer -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Integer
0) Map AssetId Integer
amounts

normalized :: Map AssetId Integer -> Value
normalized :: Map AssetId Integer -> Value
normalized = Map AssetId Integer -> Value
Value (Map AssetId Integer -> Value)
-> (Map AssetId Integer -> Map AssetId Integer)
-> Map AssetId Integer
-> Value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Integer -> Bool) -> Map AssetId Integer -> Map AssetId Integer
forall a k. (a -> Bool) -> Map k a -> Map k a
Map.filter (Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
/= Integer
0)

-- | Encode a standalone native value as an unsigned Ada integer, or
-- @[Ada, {policy: {name: signed quantity}}]@ when native assets are present.
-- Ada must be in 0 through 2^63-1; native quantities must fit signed 64 bits.
-- Invalid quantities return 'InvalidValueQuantity' before encoding. These are
-- serialization bounds, not transaction output validation: negative native
-- quantities are retained. Maps use canonical byte-length/lexicographic order.
-- This is fresh semantic encoding; zero entries have already been removed.
encodeCbor :: Value -> Either Error ByteString
encodeCbor :: Value -> Either Error ByteString
encodeCbor Value
value = do
  ((AssetId, Integer) -> Either Error ())
-> [(AssetId, Integer)] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (AssetId, Integer) -> Either Error ()
validate (Value -> [(AssetId, Integer)]
toList Value
value)
  ByteString -> Either Error ByteString
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Encoding -> ByteString
Cbor.encode Encoding
encoding)
  where
    coin :: Integer
coin = AssetId -> Value -> Integer
quantity AssetId
Ada Value
value
    validate :: (AssetId, Integer) -> Either Error ()
validate (AssetId
asset, Integer
amount)
      | Integer
amount Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64
forall a. Bounded a => a
maxBound :: Int64) = Error -> Either Error ()
forall a b. a -> Either a b
Left (Integer -> Error
InvalidValueQuantity Integer
amount)
      | Integer
amount Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< (if AssetId
asset AssetId -> AssetId -> Bool
forall a. Eq a => a -> a -> Bool
== AssetId
Ada then Integer
0 else Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64
forall a. Bounded a => a
minBound :: Int64)) = Error -> Either Error ()
forall a b. a -> Either a b
Left (Integer -> Error
InvalidValueQuantity Integer
amount)
      | Bool
otherwise = () -> Either Error ()
forall a b. b -> Either a b
Right ()
    encoding :: Encoding
encoding
      | Value -> Int
assetCount Value
value Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== (if Integer
coin Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
== Integer
0 then Int
0 else Int
1) = Integer -> Encoding
E.encodeInteger Integer
coin
      | Bool
otherwise = Word -> Encoding
E.encodeListLen Word
2 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Integer -> Encoding
E.encodeInteger Integer
coin Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Value -> Encoding
assetsEncoding Value
value

-- | Decode exactly one complete standalone value. Definite or indefinite arrays
-- and maps and nonminimal integers are accepted. Duplicate policies or names,
-- invalid identifiers, out-of-range quantities, wrong schemas and trailing bytes
-- return 'InvalidValueCbor'. Zero entries and empty policy maps normalize away;
-- original bytes are not retained. Ada is limited to 0 through 2^63-1.
decodeCbor :: ByteString -> Either Error Value
decodeCbor :: ByteString -> Either Error Value
decodeCbor = (Text -> Error)
-> (forall s. Decoder s Value) -> ByteString -> Either Error Value
forall a.
(Text -> Error)
-> (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decodeAs Text -> Error
InvalidValueCbor Decoder s Value
forall s. Decoder s Value
decoder
  where
    decoder :: Decoder s Value
decoder = do
      TokenType
token <- Decoder s TokenType
forall s. Decoder s TokenType
D.peekTokenType
      case TokenType
token of
        TokenType
D.TypeUInt -> Integer -> Value
lovelace (Integer -> Value) -> Decoder s Integer -> Decoder s Value
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s Integer
forall {s}. Decoder s Integer
coinDecoder
        TokenType
D.TypeUInt64 -> Integer -> Value
lovelace (Integer -> Value) -> Decoder s Integer -> Decoder s Value
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s Integer
forall {s}. Decoder s Integer
coinDecoder
        TokenType
_ -> Int -> Decoder s Value -> Decoder s Value
forall s a. Int -> Decoder s a -> Decoder s a
Cbor.array Int
2 (Value -> Value -> Value
forall a. Semigroup a => a -> a -> a
(<>) (Value -> Value -> Value)
-> (Integer -> Value) -> Integer -> Value -> Value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Integer -> Value
lovelace (Integer -> Value -> Value)
-> Decoder s Integer -> Decoder s (Value -> Value)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s Integer
forall {s}. Decoder s Integer
coinDecoder Decoder s (Value -> Value) -> Decoder s Value -> Decoder s Value
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Decoder s Value
forall s. Decoder s Value
assetsDecoder)
    coinDecoder :: Decoder s Integer
coinDecoder = do
      Integer
amount <- Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Word64 -> Integer) -> Decoder s Word64 -> Decoder s Integer
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s Word64
forall s. Decoder s Word64
D.decodeWord64
      Bool -> Decoder s () -> Decoder s ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Integer
amount Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64
forall a. Bounded a => a
maxBound :: Int64)) (String -> Decoder s ()
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Ada exceeds signed native coin range")
      Integer -> Decoder s Integer
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Integer
amount

-- | Number of distinct nonzero assets, including Ada when its quantity is
-- nonzero. Negative amounts count as present, just as positive amounts do.
assetCount :: Value -> Int
assetCount :: Value -> Int
assetCount (Value Map AssetId Integer
amounts) = Map AssetId Integer -> Int
forall k a. Map k a -> Int
Map.size Map AssetId Integer
amounts

-- | Left-biased intersection: retain the left quantities for assets with
-- nonzero quantities in both bundles, regardless of sign. This includes signed
-- Ada; it does not clamp amounts or take a minimum. Results use normal asset
-- ordering. Useful for restricting a requested bundle to available asset kinds.
intersection :: Value -> Value -> Value
intersection :: Value -> Value -> Value
intersection (Value Map AssetId Integer
left) (Value Map AssetId Integer
right) = Map AssetId Integer -> Value
Value (Map AssetId Integer -> Map AssetId Integer -> Map AssetId Integer
forall k a b. Ord k => Map k a -> Map k b -> Map k a
Map.intersection Map AssetId Integer
left Map AssetId Integer
right)

-- | Retain strictly positive quantities, including Ada. The sum of
-- 'positivePart' and 'negativePart' recovers the original signed value.
positivePart :: Value -> Value
positivePart :: Value -> Value
positivePart (Value Map AssetId Integer
amounts) = Map AssetId Integer -> Value
Value ((Integer -> Bool) -> Map AssetId Integer -> Map AssetId Integer
forall a k. (a -> Bool) -> Map k a -> Map k a
Map.filter (Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Integer
0) Map AssetId Integer
amounts)

-- | Retain strictly negative quantities, including Ada, without negating them.
negativePart :: Value -> Value
negativePart :: Value -> Value
negativePart (Value Map AssetId Integer
amounts) = Map AssetId Integer -> Value
Value ((Integer -> Bool) -> Map AssetId Integer -> Map AssetId Integer
forall a k. (a -> Bool) -> Map k a -> Map k a
Map.filter (Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
0) Map AssetId Integer
amounts)

-- | Encode a mint/burn bundle as @{policy: {name: signed quantity}}@ CBOR.
-- Native quantities must fit signed 64 bits, otherwise 'InvalidValueQuantity'.
-- Any nonzero Ada returns 'InvalidValueCbor': Ada cannot be minted. Empty
-- bundles encode an empty map. This does not validate policies or witnesses
-- against a transaction; identifiers are already validated by their types.
encodeMintCbor :: Value -> Either Error ByteString
encodeMintCbor :: Value -> Either Error ByteString
encodeMintCbor Value
value
  | AssetId -> Value -> Integer
quantity AssetId
Ada Value
value Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
/= Integer
0 = Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Text -> Error
InvalidValueCbor Text
"Mint cannot contain Ada")
  | Bool
otherwise = do
      ((AssetId, Integer) -> Either Error ())
-> [(AssetId, Integer)] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (AssetId, Integer) -> Either Error ()
forall {a}. (a, Integer) -> Either Error ()
valid (Value -> [(AssetId, Integer)]
toList Value
value)
      ByteString -> Either Error ByteString
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Encoding -> ByteString
Cbor.encode (Value -> Encoding
assetsEncoding Value
value))
  where
    valid :: (a, Integer) -> Either Error ()
valid (a
_, Integer
amount)
      | Integer
amount Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64
forall a. Bounded a => a
minBound :: Int64) Bool -> Bool -> Bool
|| Integer
amount Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64
forall a. Bounded a => a
maxBound :: Int64) = Error -> Either Error ()
forall a b. a -> Either a b
Left (Integer -> Error
InvalidValueQuantity Integer
amount)
      | Bool
otherwise = () -> Either Error ()
forall a b. b -> Either a b
Right ()

-- | Decode exactly one complete standalone mint/burn map. Policy and name
-- lengths, signed 64-bit quantities and duplicate keys are checked. Invalid
-- encodings or trailing bytes return 'InvalidValueCbor'. Definite/indefinite
-- maps are accepted; zero entries and empty policy maps normalize away.
decodeMintCbor :: ByteString -> Either Error Value
decodeMintCbor :: ByteString -> Either Error Value
decodeMintCbor = (Text -> Error)
-> (forall s. Decoder s Value) -> ByteString -> Either Error Value
forall a.
(Text -> Error)
-> (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decodeAs Text -> Error
InvalidValueCbor Decoder s Value
forall s. Decoder s Value
assetsDecoder

assetsEncoding :: Value -> E.Encoding
assetsEncoding :: Value -> Encoding
assetsEncoding Value
value = Word -> Encoding
E.encodeMapLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Map PolicyId [(AssetName, Integer)] -> Int
forall k a. Map k a -> Int
Map.size Map PolicyId [(AssetName, Integer)]
policies)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ((PolicyId, [(AssetName, Integer)]) -> Encoding)
-> [(PolicyId, [(AssetName, Integer)])] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (PolicyId, [(AssetName, Integer)]) -> Encoding
encodePolicy (Map PolicyId [(AssetName, Integer)]
-> [(PolicyId, [(AssetName, Integer)])]
forall k a. Map k a -> [(k, a)]
Map.toAscList Map PolicyId [(AssetName, Integer)]
policies)
  where
    policies :: Map PolicyId [(AssetName, Integer)]
policies = ([(AssetName, Integer)]
 -> [(AssetName, Integer)] -> [(AssetName, Integer)])
-> [(PolicyId, [(AssetName, Integer)])]
-> Map PolicyId [(AssetName, Integer)]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith [(AssetName, Integer)]
-> [(AssetName, Integer)] -> [(AssetName, Integer)]
forall a. [a] -> [a] -> [a]
(++) [(PolicyId
policy, [(AssetName
name, Integer
amount)]) | (Native PolicyId
policy AssetName
name, Integer
amount) <- Value -> [(AssetId, Integer)]
toList Value
value]
    encodePolicy :: (PolicyId, [(AssetName, Integer)]) -> Encoding
encodePolicy (PolicyId
policy, [(AssetName, Integer)]
assets) = ByteString -> Encoding
E.encodeBytes (PolicyId -> ByteString
Policy.toBytes PolicyId
policy) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Word -> Encoding
E.encodeMapLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([(AssetName, Integer)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(AssetName, Integer)]
assets)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ((AssetName, Integer) -> Encoding)
-> [(AssetName, Integer)] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (AssetName, Integer) -> Encoding
encodeAsset (((AssetName, Integer) -> (Int, ByteString))
-> [(AssetName, Integer)] -> [(AssetName, Integer)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (\(AssetName
name, Integer
_) -> (ByteString -> Int
B.length (AssetName -> ByteString
Name.toBytes AssetName
name), AssetName -> ByteString
Name.toBytes AssetName
name)) [(AssetName, Integer)]
assets)
    encodeAsset :: (AssetName, Integer) -> Encoding
encodeAsset (AssetName
name, Integer
amount) = ByteString -> Encoding
E.encodeBytes (AssetName -> ByteString
Name.toBytes AssetName
name) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Integer -> Encoding
E.encodeInteger Integer
amount

assetsDecoder :: D.Decoder s Value
assetsDecoder :: forall s. Decoder s Value
assetsDecoder = do
  [(PolicyId, [(AssetName, Integer)])]
policies <- Decoder s (PolicyId, [(AssetName, Integer)])
-> Decoder s [(PolicyId, [(AssetName, Integer)])]
forall s a. Decoder s a -> Decoder s [a]
Cbor.entries (Decoder s (PolicyId, [(AssetName, Integer)])
 -> Decoder s [(PolicyId, [(AssetName, Integer)])])
-> Decoder s (PolicyId, [(AssetName, Integer)])
-> Decoder s [(PolicyId, [(AssetName, Integer)])]
forall a b. (a -> b) -> a -> b
$ do
    PolicyId
policy <- Decoder s ByteString
forall s. Decoder s ByteString
D.decodeBytes Decoder s ByteString
-> (ByteString -> Decoder s PolicyId) -> Decoder s PolicyId
forall a b. Decoder s a -> (a -> Decoder s b) -> Decoder s b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Error -> Decoder s PolicyId)
-> (PolicyId -> Decoder s PolicyId)
-> Either Error PolicyId
-> Decoder s PolicyId
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> Decoder s PolicyId
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> Decoder s PolicyId)
-> (Error -> String) -> Error -> Decoder s PolicyId
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Error -> String
forall a. Show a => a -> String
show) PolicyId -> Decoder s PolicyId
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error PolicyId -> Decoder s PolicyId)
-> (ByteString -> Either Error PolicyId)
-> ByteString
-> Decoder s PolicyId
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either Error PolicyId
Policy.fromBytes
    [(AssetName, Integer)]
assets <- Decoder s (AssetName, Integer) -> Decoder s [(AssetName, Integer)]
forall s a. Decoder s a -> Decoder s [a]
Cbor.entries (Decoder s (AssetName, Integer)
 -> Decoder s [(AssetName, Integer)])
-> Decoder s (AssetName, Integer)
-> Decoder s [(AssetName, Integer)]
forall a b. (a -> b) -> a -> b
$ do
      AssetName
name <- Decoder s ByteString
forall s. Decoder s ByteString
D.decodeBytes Decoder s ByteString
-> (ByteString -> Decoder s AssetName) -> Decoder s AssetName
forall a b. Decoder s a -> (a -> Decoder s b) -> Decoder s b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Error -> Decoder s AssetName)
-> (AssetName -> Decoder s AssetName)
-> Either Error AssetName
-> Decoder s AssetName
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> Decoder s AssetName
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> Decoder s AssetName)
-> (Error -> String) -> Error -> Decoder s AssetName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Error -> String
forall a. Show a => a -> String
show) AssetName -> Decoder s AssetName
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error AssetName -> Decoder s AssetName)
-> (ByteString -> Either Error AssetName)
-> ByteString
-> Decoder s AssetName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either Error AssetName
Name.fromBytes
      Integer
amount <- Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64 -> Integer) -> Decoder s Int64 -> Decoder s Integer
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s Int64
forall s. Decoder s Int64
D.decodeInt64
      (AssetName, Integer) -> Decoder s (AssetName, Integer)
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (AssetName
name, Integer
amount)
    Bool -> Decoder s () -> Decoder s ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Set AssetName -> Int
forall a. Set a -> Int
Set.size ([AssetName] -> Set AssetName
forall a. Ord a => [a] -> Set a
Set.fromList (((AssetName, Integer) -> AssetName)
-> [(AssetName, Integer)] -> [AssetName]
forall a b. (a -> b) -> [a] -> [b]
map (AssetName, Integer) -> AssetName
forall a b. (a, b) -> a
fst [(AssetName, Integer)]
assets)) Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [(AssetName, Integer)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(AssetName, Integer)]
assets) (String -> Decoder s ()
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Duplicate asset name")
    (PolicyId, [(AssetName, Integer)])
-> Decoder s (PolicyId, [(AssetName, Integer)])
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PolicyId
policy, [(AssetName, Integer)]
assets)
  Bool -> Decoder s () -> Decoder s ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Set PolicyId -> Int
forall a. Set a -> Int
Set.size ([PolicyId] -> Set PolicyId
forall a. Ord a => [a] -> Set a
Set.fromList (((PolicyId, [(AssetName, Integer)]) -> PolicyId)
-> [(PolicyId, [(AssetName, Integer)])] -> [PolicyId]
forall a b. (a -> b) -> [a] -> [b]
map (PolicyId, [(AssetName, Integer)]) -> PolicyId
forall a b. (a, b) -> a
fst [(PolicyId, [(AssetName, Integer)])]
policies)) Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [(PolicyId, [(AssetName, Integer)])] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(PolicyId, [(AssetName, Integer)])]
policies) (String -> Decoder s ()
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Duplicate policy")
  Value -> Decoder s Value
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([(AssetId, Integer)] -> Value
fromList [(PolicyId -> AssetName -> AssetId
Native PolicyId
policy AssetName
name, Integer
amount) | (PolicyId
policy, [(AssetName, Integer)]
assets) <- [(PolicyId, [(AssetName, Integer)])]
policies, (AssetName
name, Integer
amount) <- [(AssetName, Integer)]
assets])