-- SPDX-FileCopyrightText: 2021 Oxhead Alpha
-- SPDX-License-Identifier: LicenseRef-MIT-OA

-- | Abstract cleveland interface not bound to a particular
-- implementation.
--
-- The interface may look a bit untyped and unsafe in some places.
-- For example, in order to call a contract one should supply a
-- simple address rather than a contract ref, so it is easy to pass
-- a value of wrong type. Also it is easy to call a non-existing entrypoint.
--
-- Subjectively, it makes writing test scenarios easier because you
-- have to prove less to the compiler. It also makes implementation of
-- cleveland engine a bit easier. Of course, it also makes it easier
-- to make certain mistakes. However, we expect users of this interface
-- to also use the functionality of the "Test.Cleveland.Internal.Pure" module
-- and convert cleveland scenarios to purely testable scenarios for
-- integrational testing engine. In this case errors should be detected
-- almost as quickly as they would reported by the compiler, at least
-- before trying to run scenario on a live network.
--
-- Also this interface uses 'Address' rather than 'EpAddress'.
-- I (\@gromak) concluded that 'EpAddress' can not be passed to @tezos-client@.
-- For key addresses it just does not make sense and for contract addresses
-- I get such errors:
--
-- @
--   bad contract notation
--   Invalid contract notation "KT1VrFpBPwBTm3hsK7DB7SPmY8fTHJ3vY6sJ%mint"
-- @
module Test.Cleveland.Internal.Abstract
  ( ContractHandle (..)
  , OriginateData (..)
  , TransferData (..)
  , Sender (..)
  , Moneybag (..)
  , UntypedOriginateData (..)
  , RunCode(..)
  , ClevelandInput

  , DefaultAliasCounter (..)
  , SpecificOrDefaultAliasHint (..)

  -- * Actions
  , ClevelandOpsImpl (..)
  , ClevelandMiscImpl (..)
  , EmulatedImpl(..)

  , mapClevelandOpsImplExceptions
  , mapClevelandMiscImplExceptions

  -- * Batching
  , BatchResultMismatch(..)
  , ClevelandOpsBatch
  , runBatched
  , batchedOpsImpl
  , runOperationBatchM
  , runSingleOperation

  -- * Validation
  , TransferFailure (..)
  , TransferFailureReason (..)
  , FailedInBranch (..)
  , ScenarioBranchName(..)
  , GenericTestError (..)
  , ExpressionOrTypedValue (..)

  -- * Helpers
  , auto
  , ep
  , mkDefaultAlias

  -- * Morley client re-exports
  , AliasHint

  -- * Capability records
  , ClevelandCaps(..)
  , EmulatedCaps(..)
  , HasClevelandCaps(..)
  , senderL
  , moneybagL
  , getMiscCap
  , getOpsCap
  , HasEmulatedCaps(..)

  , MonadCleveland
  , MonadEmulated
  , ClevelandT
  , EmulatedT

  -- * Log utilities
  , LogsInfo
  , ScenarioLogs(..)
  , slAddr
  , slLog
  , logsL
  , filterLogsByAddrL
  , logsForAddress
  , collectLogs
  ) where

import Control.Lens (Each, each, filtered, makeLenses, makeLensesFor)
import Data.Default (Default(..))
import Data.Type.Equality (pattern Refl)
import Data.Typeable (cast)
import Fmt (Buildable(..), Builder, pretty, (+|), (|+))
import Prelude hiding (Each)
import Time (KnownDivRat, Second, Time)

import Lorentz (Contract(..))
import Lorentz.Constraints
import Morley.AsRPC (HasRPCRepr(AsRPC), MaybeRPC)
import Morley.Client (AliasHint, Result)
import Morley.Client.Types
import Morley.Micheline (Expression, fromExpression)
import Morley.Michelson.ErrorPos (InstrCallStack)
import Morley.Michelson.Interpret (MorleyLogs(..))
import Morley.Michelson.Runtime (VotingPowers)
import Morley.Michelson.Typed (BigMapId)
import Morley.Michelson.Typed qualified as T
import Morley.Michelson.Typed.AnnotatedValue (SomeAnnotatedValue)
import Morley.Michelson.Typed.Entrypoints
import Morley.Michelson.Typed.Scope (ConstantScope)
import Morley.Michelson.Untyped qualified as U
import Morley.Tezos.Address
import Morley.Tezos.Core (ChainId, Mutez, Timestamp)
import Morley.Tezos.Crypto
import Morley.Tezos.Crypto qualified as Crypto
import Morley.Util.Batching
import Morley.Util.Sing (eqI)
import Morley.Util.TypeLits
import Test.Cleveland.Internal.Exceptions (WithCallStack(..))
import Test.Cleveland.Lorentz.Types

data OriginateData param st vd =
  OriginateData
  { OriginateData param st vd -> AliasHint
odName :: AliasHint
  -- ^ Alias for the originated contract.
  , OriginateData param st vd -> Mutez
odBalance :: Mutez
  -- ^ Initial balance.
  , OriginateData param st vd -> st
odStorage :: st
  -- ^ Initial storage.
  , OriginateData param st vd -> Contract param st vd
odContract :: Contract param st vd
  -- ^ The contract itself.
  --
  -- We are using Lorentz version here which is convenient. However, keep in
  -- mind that if someone wants to test a contract from @.tz@ file, they should use
  -- 'UntypedOriginateData'.
  }

-- | Untyped version of OriginateData. It can be used for interaction with raw
-- Michelson contracts
data UntypedOriginateData = UntypedOriginateData
  { UntypedOriginateData -> AliasHint
uodName :: AliasHint
  -- ^ Alias for the originated contract.
  , UntypedOriginateData -> Mutez
uodBalance :: Mutez
  -- ^ Initial balance.
  , UntypedOriginateData -> Value
uodStorage :: U.Value
  -- ^ Initial storage.
  , UntypedOriginateData -> Contract
uodContract :: U.Contract
  -- ^ The contract itself.
  }

-- | Information about transfer operation.
data TransferData =
  forall v addr. (NiceParameter v, ToAddress addr) => TransferData
  { ()
tdTo :: addr
  -- ^ Receiver address for this transaction.
  , TransferData -> Mutez
tdAmount :: Mutez
  -- ^ Amount to be transferred.
  , TransferData -> EpName
tdEntrypoint :: EpName
  -- ^ An entrypoint to be called. Consider using 'ep' in testing
  -- scenarios.
  , ()
tdParameter :: v
  -- ^ Parameter that will be used for a contract call. Set to @()@
  -- for transfers to key addresses.
  }

-- | Designates an operation input.
data ClevelandInput
instance OperationInfoDescriptor ClevelandInput where
  type TransferInfo ClevelandInput = TransferData
  type OriginationInfo ClevelandInput = UntypedOriginateData
  type RevealInfo ClevelandInput = PublicKey

-- | A batch returned invalid output, e.g. origination address when transaction
-- was supplied.
data BatchResultMismatch
  = BatchResultMismatch Text  -- ^ Carries expected operation type in lowercase

instance Buildable BatchResultMismatch where
  build :: BatchResultMismatch -> Builder
build = \case
    BatchResultMismatch Text
expected ->
      Builder
"For " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| Text
expected Text -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ Builder
" operation received inappropriate result"

-- | Designates the special sender address.
--
-- Transfers and some other operations will occur on behalf of this address.
-- This is initialized to @moneybag@ address and then can be locally modified.
--
-- Operations in `ClevelandOpsImpl` are affected by this address.
newtype Sender = Sender { Sender -> Address
unSender :: Address }

-- | Designates the address that gifts money to new addresses.
--
-- Once a new address is allocated in a test scenario, we have to transfer some
-- money to it so that it is able to serve as transactions sender. 'Moneybag'
-- serves as a source of that money.
--
-- We do not use 'Sender' for this purpose because in most situations changing
-- moneybag is not necessary. If a user wraps a large piece of their script with
-- 'Test.Cleveland.withSender' call and that changes the moneybag - this behaviour may be
-- undesired and unexpected to the user.
newtype Moneybag = Moneybag { Moneybag -> Address
unMoneybag :: Address }

-- | An alias hint with default value that can be used to define unique alias
-- automatically.
data SpecificOrDefaultAliasHint
  = SpecificAliasHint AliasHint
  | DefaultAliasHint
  deriving stock (Int -> SpecificOrDefaultAliasHint -> ShowS
[SpecificOrDefaultAliasHint] -> ShowS
SpecificOrDefaultAliasHint -> String
(Int -> SpecificOrDefaultAliasHint -> ShowS)
-> (SpecificOrDefaultAliasHint -> String)
-> ([SpecificOrDefaultAliasHint] -> ShowS)
-> Show SpecificOrDefaultAliasHint
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [SpecificOrDefaultAliasHint] -> ShowS
$cshowList :: [SpecificOrDefaultAliasHint] -> ShowS
show :: SpecificOrDefaultAliasHint -> String
$cshow :: SpecificOrDefaultAliasHint -> String
showsPrec :: Int -> SpecificOrDefaultAliasHint -> ShowS
$cshowsPrec :: Int -> SpecificOrDefaultAliasHint -> ShowS
Show)

instance IsString SpecificOrDefaultAliasHint where
  fromString :: String -> SpecificOrDefaultAliasHint
fromString = AliasHint -> SpecificOrDefaultAliasHint
SpecificAliasHint (AliasHint -> SpecificOrDefaultAliasHint)
-> (String -> AliasHint) -> String -> SpecificOrDefaultAliasHint
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> AliasHint
forall a. IsString a => String -> a
fromString

instance Default SpecificOrDefaultAliasHint where
  def :: SpecificOrDefaultAliasHint
def = SpecificOrDefaultAliasHint
DefaultAliasHint

mkDefaultAlias :: Natural -> AliasHint
mkDefaultAlias :: Natural -> AliasHint
mkDefaultAlias Natural
counter =
  String -> AliasHint
forall a. IsString a => String -> a
fromString (String -> AliasHint) -> String -> AliasHint
forall a b. (a -> b) -> a -> b
$ (String
"default_cleveland_alias" String -> ShowS
forall a. Semigroup a => a -> a -> a
<> Natural -> String
forall b a. (PrettyShow a, Show a, IsString b) => a -> b
show Natural
counter)

-- | Helper to use automatically determined unique alias.
auto :: SpecificOrDefaultAliasHint
auto :: SpecificOrDefaultAliasHint
auto = SpecificOrDefaultAliasHint
forall a. Default a => a
def

-- | Counter which is used to provide different default aliases.
newtype DefaultAliasCounter = DefaultAliasCounter {DefaultAliasCounter -> Natural
unDefaultAliasCounter :: Natural}
  deriving stock Int -> DefaultAliasCounter -> ShowS
[DefaultAliasCounter] -> ShowS
DefaultAliasCounter -> String
(Int -> DefaultAliasCounter -> ShowS)
-> (DefaultAliasCounter -> String)
-> ([DefaultAliasCounter] -> ShowS)
-> Show DefaultAliasCounter
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [DefaultAliasCounter] -> ShowS
$cshowList :: [DefaultAliasCounter] -> ShowS
show :: DefaultAliasCounter -> String
$cshow :: DefaultAliasCounter -> String
showsPrec :: Int -> DefaultAliasCounter -> ShowS
$cshowsPrec :: Int -> DefaultAliasCounter -> ShowS
Show

-- | A record data type with operations creating primitives.
data ClevelandOpsImpl m = ClevelandOpsImpl
  { ClevelandOpsImpl m
-> HasCallStack =>
   [OperationInfo ClevelandInput] -> m [OperationInfo Result]
coiRunOperationBatch
      :: HasCallStack => [OperationInfo ClevelandInput] -> m [OperationInfo Result]
  -- ^ Perform a batch of operations.
  }

-- | A record data type with all base methods one can use during a cleveland test.
data ClevelandMiscImpl m = ClevelandMiscImpl
  { ClevelandMiscImpl m -> forall res. HasCallStack => IO res -> m res
cmiRunIO :: forall res. HasCallStack => IO res -> m res
  -- ^ Runs an 'IO' action.
  , ClevelandMiscImpl m -> HasCallStack => AliasHint -> m Address
cmiResolveAddress :: HasCallStack => AliasHint -> m Address
  -- ^ Get the address of the implicit account / contract associated with the given alias.
  , ClevelandMiscImpl m
-> HasCallStack => SpecificOrDefaultAliasHint -> m Address
cmiGenKey :: HasCallStack => SpecificOrDefaultAliasHint -> m Address
  -- ^ Generate a secret key and store it with given alias.
  -- If a key with this alias already exists, the corresponding address
  -- will be returned and no state will be changed.
  , ClevelandMiscImpl m
-> HasCallStack => SpecificOrDefaultAliasHint -> m Address
cmiGenFreshKey :: HasCallStack => SpecificOrDefaultAliasHint -> m Address
  -- ^ Generate a secret key and store it with given alias.
  -- Unlike 'cmiGenKey' this function overwrites the existing key when
  -- given alias is already stored.
  , ClevelandMiscImpl m
-> HasCallStack => ByteString -> Address -> m Signature
cmiSignBytes :: HasCallStack => ByteString -> Address -> m Crypto.Signature
  -- ^ Get the signature of the preapplied operation.
  , ClevelandMiscImpl m
-> HasCallStack => Sender -> UntypedOriginateData -> m Address
cmiOriginateLargeUntyped :: HasCallStack => Sender -> UntypedOriginateData -> m Address
  -- ^ Originate a new raw Michelson contract that doesn't fit into the
  -- origination size limit, by executing multiple operation steps.
  --
  -- Note that this is not part of 'ClevelandOpsImpl' because large origination is
  -- _not_ a primitive operation. Also, it cannot appear in a batch (it simply
  -- may not fit).
  , ClevelandMiscImpl m -> HasCallStack => Text -> m ()
cmiComment :: HasCallStack => Text -> m ()
  -- ^ Print the given string verbatim as a comment.
  -- At the moment, this is a no-op in emulator tests.
  , ClevelandMiscImpl m -> HasCallStack => Address -> m Mutez
cmiGetBalance :: HasCallStack => Address -> m Mutez
  -- ^ Get the balance of the given address.
  , ClevelandMiscImpl m
-> HasCallStack => Address -> m SomeAnnotatedValue
cmiGetSomeStorage :: HasCallStack => Address -> m SomeAnnotatedValue
  -- Retrieves the contract's storage.
  , ClevelandMiscImpl m
-> forall k v.
   (HasCallStack, NiceComparable k, NicePackedValue k,
    NiceUnpackedValue v) =>
   BigMapId k v -> k -> m (Maybe v)
cmiGetBigMapValueMaybe
      :: forall k v. (HasCallStack, NiceComparable k, NicePackedValue k, NiceUnpackedValue v)
      => BigMapId k v -> k -> m (Maybe v)
  -- ^ Retrieve a big_map value, given a big_map ID and a key.
  -- Returns 'Nothing' when the big_map ID does not exist, or it exists but
  -- does not contain the given key.
  , ClevelandMiscImpl m
-> forall k v.
   (HasCallStack, NiceComparable k, NiceUnpackedValue v) =>
   BigMapId k v -> m (Maybe [v])
cmiGetAllBigMapValuesMaybe
      :: forall k v. (HasCallStack, NiceComparable k, NiceUnpackedValue v)
      => BigMapId k v -> m (Maybe [v])
  -- ^ Retrieve all big_map values, given a big_map ID.
  -- Returns 'Nothing' when the big_map ID does not exist.
  , ClevelandMiscImpl m -> HasCallStack => Address -> m PublicKey
cmiGetPublicKey :: HasCallStack => Address -> m Crypto.PublicKey
  -- ^ Get the public key associated with the given address.
  -- Fail if the given address is not an implicit account.
  , ClevelandMiscImpl m -> HasCallStack => Address -> m (Maybe KeyHash)
cmiGetDelegate :: HasCallStack => Address -> m (Maybe Crypto.KeyHash)
  -- ^ Get the delegate for the given contract. Fails on implicit contracts.
  , ClevelandMiscImpl m -> HasCallStack => Address -> m ()
cmiRegisterDelegate :: HasCallStack => Address -> m ()
  -- ^ Register the given address as a valid delegate.
  , ClevelandMiscImpl m -> HasCallStack => m ChainId
cmiGetChainId :: HasCallStack => m ChainId
  -- ^ Get the chain's @ChainId@.
  , ClevelandMiscImpl m
-> forall (unit :: Rat).
   (HasCallStack, KnownDivRat unit Second) =>
   Time unit -> m ()
cmiAdvanceTime :: forall unit. (HasCallStack, KnownDivRat unit Second) => Time unit -> m ()
  -- ^ Advance at least the given amount of time, or until a new block is baked,
  -- whichever happens last.
  --
  -- On a real network, this is implemented using @threadDelay@, so it's advisable
  -- to use small amounts of time only.
  , ClevelandMiscImpl m -> HasCallStack => (Natural -> Natural) -> m ()
cmiAdvanceToLevel :: HasCallStack => (Natural -> Natural) -> m ()
  -- ^ Advance at least to the level returned by the callback, accepting current level.
  , ClevelandMiscImpl m -> HasCallStack => m Timestamp
cmiGetNow :: HasCallStack => m Timestamp
  -- ^ Get the timestamp observed by the last block to be baked.
  , ClevelandMiscImpl m -> HasCallStack => m Natural
cmiGetLevel :: HasCallStack => m Natural
  -- ^ Get the current level observed by the last block to be baked.
  , ClevelandMiscImpl m -> forall a. HasCallStack => Builder -> m a
cmiFailure :: forall a. HasCallStack => Builder -> m a
  -- ^ Fails the test with the given error message.
  , ClevelandMiscImpl m
-> forall a. HasCallStack => SomeException -> m a
cmiThrow :: forall a. HasCallStack => SomeException -> m a
  -- ^ Rethrow arbitrary error without affecting the call stack. Used
  -- internally. You probably want to use 'cmiFailure'
  , ClevelandMiscImpl m -> HasCallStack => m (Time Second)
cmiGetApproximateBlockInterval :: HasCallStack => m (Time Second)
  -- ^ Get approximate block interval in seconds. Note, that this value
  -- is minimal bound and real intervals can be larger.
  , ClevelandMiscImpl m
-> forall a e. (Exception e, HasCallStack) => m a -> m (Either e a)
cmiAttempt :: forall a e. (Exception e, HasCallStack) => m a -> m (Either e a)
  -- ^ Attempts to perform an action, returning either the result of the action or an exception.
  , ClevelandMiscImpl m -> Address -> m ()
cmiMarkAddressRefillable :: Address -> m ()
  -- ^ Marks a given address as "refillable", i.e. if the address lacks funds for the next operation,
  -- some funds will automatically be transferred to it.
  , ClevelandMiscImpl m -> m (Maybe (EmulatedImpl m))
cmiEmulatedImpl :: m (Maybe (EmulatedImpl m))
  -- ^ Produce 'EmulatedImpl' if possible. Used to run emulated actions in polymorphic context.
  , ClevelandMiscImpl m
-> forall cp st vd.
   (HasCallStack, HasRPCRepr st, IsoValue (AsRPC st)) =>
   Sender -> RunCode cp st vd -> m (AsRPC st)
cmiRunCode
      :: forall cp st vd. (HasCallStack, HasRPCRepr st, T.IsoValue (AsRPC st))
      => Sender -> RunCode cp st vd -> m (AsRPC st)
  -- ^ Execute a contract's code without originating it.
  -- The chain's state will not be modified.
  }

-- | The data needed to call the @/run_code@ RPC endpoint.
data RunCode cp st vd = RunCode
  { RunCode cp st vd -> Contract cp st vd
rcContract :: Contract cp st vd
  , RunCode cp st vd -> MaybeRPC st
rcStorage :: MaybeRPC st
  , RunCode cp st vd -> MaybeRPC cp
rcParameter :: MaybeRPC cp
  , RunCode cp st vd -> Mutez
rcAmount :: Mutez
  -- ^ The value that will be returned by the @AMOUNT@ instruction.
  , RunCode cp st vd -> Mutez
rcBalance :: Mutez
  -- ^ The balance that will be returned by the @BALANCE@ instruction.
  , RunCode cp st vd -> Maybe Address
rcSource :: Maybe Address
  -- ^ The value that will be returned by the @SOURCE@ instruction.
  }

-- | A record data type with all base methods one can use during cleveland, but which are available
-- only when running on an emulated environment (e.g. "Morley.Michelson.Runtime") and not on a real network.
data EmulatedImpl m = EmulatedImpl
  { EmulatedImpl m -> [(Text, m ())] -> m ()
eiBranchout :: [(Text, m ())] -> m ()
  -- ^ Execute multiple testing scenarios independently.
  --
  -- * Actions performed before 'eiBranchout' will be observed by all branches.
  -- * Actions performed in branches will _not_ be observed by any actions performed after 'eiBranchout'.
  -- * Actions performed in one branch will _not_ be observed by another branch.
  -- * The test succeeds IFF all branches succeed.
  -- * If any branch fails, the test ends immediately and the remaining branches
  --    won't be executed.
  --
  -- The following property holds:
  --
  -- > pre >> branchout [a, b, c] = branchout [pre >> a, pre >> b, pre >> c]
  --
  -- The list of branches must be non-empty.
  , EmulatedImpl m
-> forall st addr.
   (HasCallStack, ToStorageType st addr) =>
   addr -> m st
eiGetStorage
      :: forall st addr. (HasCallStack, ToStorageType st addr)
      => addr -> m st
  -- ^ Retrieve a contract's full storage, including the contents of its big_maps.
  -- This function can only be used in emulator-only tests.
  , EmulatedImpl m -> forall a. m a -> m (LogsInfo, a)
eiGetMorleyLogs :: forall a. m a -> m (LogsInfo, a)
  -- ^ Returns the result of the action with the logs it produced
  , EmulatedImpl m -> VotingPowers -> m ()
eiSetVotingPowers :: VotingPowers -> m ()
  -- ^ Change voting power distribution.
  }

----------------------------------------------------------------------------
-- Log helpers
----------------------------------------------------------------------------

data ScenarioLogs = ScenarioLogs
  { ScenarioLogs -> Address
_slAddr :: Address
  , ScenarioLogs -> MorleyLogs
_slLog :: MorleyLogs
  } deriving stock (ScenarioLogs -> ScenarioLogs -> Bool
(ScenarioLogs -> ScenarioLogs -> Bool)
-> (ScenarioLogs -> ScenarioLogs -> Bool) -> Eq ScenarioLogs
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: ScenarioLogs -> ScenarioLogs -> Bool
$c/= :: ScenarioLogs -> ScenarioLogs -> Bool
== :: ScenarioLogs -> ScenarioLogs -> Bool
$c== :: ScenarioLogs -> ScenarioLogs -> Bool
Eq, Int -> ScenarioLogs -> ShowS
LogsInfo -> ShowS
ScenarioLogs -> String
(Int -> ScenarioLogs -> ShowS)
-> (ScenarioLogs -> String)
-> (LogsInfo -> ShowS)
-> Show ScenarioLogs
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: LogsInfo -> ShowS
$cshowList :: LogsInfo -> ShowS
show :: ScenarioLogs -> String
$cshow :: ScenarioLogs -> String
showsPrec :: Int -> ScenarioLogs -> ShowS
$cshowsPrec :: Int -> ScenarioLogs -> ShowS
Show)

type LogsInfo = [ScenarioLogs]

makeLenses ''ScenarioLogs

-- | An alias for 'slLog' with a clearer name
logsL :: Lens' ScenarioLogs MorleyLogs
logsL :: (MorleyLogs -> f MorleyLogs) -> ScenarioLogs -> f ScenarioLogs
logsL = (MorleyLogs -> f MorleyLogs) -> ScenarioLogs -> f ScenarioLogs
Lens' ScenarioLogs MorleyLogs
slLog

-- | Lens combinator specified for filtering logs by address from 'LogsInfo'
filterLogsByAddrL
  :: (ToAddress addr, Applicative f)
  => addr
  -> (MorleyLogs -> f MorleyLogs)
  -> ScenarioLogs
  -> f ScenarioLogs
filterLogsByAddrL :: addr
-> (MorleyLogs -> f MorleyLogs) -> ScenarioLogs -> f ScenarioLogs
filterLogsByAddrL (addr -> Address
forall a. ToAddress a => a -> Address
toAddress -> Address
addr) = (ScenarioLogs -> Bool) -> Optic' (->) f ScenarioLogs ScenarioLogs
forall (p :: * -> * -> *) (f :: * -> *) a.
(Choice p, Applicative f) =>
(a -> Bool) -> Optic' p f a a
filtered (\(ScenarioLogs Address
a MorleyLogs
_) -> Address
a Address -> Address -> Bool
forall a. Eq a => a -> a -> Bool
== Address
addr) Optic' (->) f ScenarioLogs ScenarioLogs
-> ((MorleyLogs -> f MorleyLogs) -> ScenarioLogs -> f ScenarioLogs)
-> (MorleyLogs -> f MorleyLogs)
-> ScenarioLogs
-> f ScenarioLogs
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (MorleyLogs -> f MorleyLogs) -> ScenarioLogs -> f ScenarioLogs
Lens' ScenarioLogs MorleyLogs
logsL

-- | Get logs for a given address from 'LogsInfo'
logsForAddress
  :: ( Each s s ScenarioLogs ScenarioLogs
     , ToAddress addr
     )
  => addr
  -> s
  -> [MorleyLogs]
logsForAddress :: addr -> s -> [MorleyLogs]
logsForAddress addr
addr = (s -> Getting (Endo [MorleyLogs]) s MorleyLogs -> [MorleyLogs]
forall s a. s -> Getting (Endo [a]) s a -> [a]
^.. (ScenarioLogs -> Const (Endo [MorleyLogs]) ScenarioLogs)
-> s -> Const (Endo [MorleyLogs]) s
forall s t a b. Each s t a b => Traversal s t a b
each ((ScenarioLogs -> Const (Endo [MorleyLogs]) ScenarioLogs)
 -> s -> Const (Endo [MorleyLogs]) s)
-> ((MorleyLogs -> Const (Endo [MorleyLogs]) MorleyLogs)
    -> ScenarioLogs -> Const (Endo [MorleyLogs]) ScenarioLogs)
-> Getting (Endo [MorleyLogs]) s MorleyLogs
forall b c a. (b -> c) -> (a -> b) -> a -> c
. addr
-> (MorleyLogs -> Const (Endo [MorleyLogs]) MorleyLogs)
-> ScenarioLogs
-> Const (Endo [MorleyLogs]) ScenarioLogs
forall addr (f :: * -> *).
(ToAddress addr, Applicative f) =>
addr
-> (MorleyLogs -> f MorleyLogs) -> ScenarioLogs -> f ScenarioLogs
filterLogsByAddrL addr
addr)

-- | Collect logs produced by all contracts into the single list
collectLogs :: LogsInfo -> MorleyLogs
collectLogs :: LogsInfo -> MorleyLogs
collectLogs = (Element LogsInfo -> MorleyLogs) -> LogsInfo -> MorleyLogs
forall t m. (Container t, Monoid m) => (Element t -> m) -> t -> m
foldMap Element LogsInfo -> MorleyLogs
ScenarioLogs -> MorleyLogs
_slLog

----------------------------------------------------------------------------
-- Batched operations
----------------------------------------------------------------------------

-- | Where the batched operations occur.
--
-- Note that this is not a 'Monad', rather an 'Applicative' - use
-- @-XApplicativeDo@ extension for nicer experience.
newtype ClevelandOpsBatch a = ClevelandOpsBatch
  { ClevelandOpsBatch a
-> BatchingM
     (OperationInfo ClevelandInput) (OperationInfo Result) Void a
unClevelandOpsBatch
      :: BatchingM (OperationInfo ClevelandInput) (OperationInfo Result) Void a
  } deriving newtype (a -> ClevelandOpsBatch b -> ClevelandOpsBatch a
(a -> b) -> ClevelandOpsBatch a -> ClevelandOpsBatch b
(forall a b.
 (a -> b) -> ClevelandOpsBatch a -> ClevelandOpsBatch b)
-> (forall a b. a -> ClevelandOpsBatch b -> ClevelandOpsBatch a)
-> Functor ClevelandOpsBatch
forall a b. a -> ClevelandOpsBatch b -> ClevelandOpsBatch a
forall a b. (a -> b) -> ClevelandOpsBatch a -> ClevelandOpsBatch b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
<$ :: a -> ClevelandOpsBatch b -> ClevelandOpsBatch a
$c<$ :: forall a b. a -> ClevelandOpsBatch b -> ClevelandOpsBatch a
fmap :: (a -> b) -> ClevelandOpsBatch a -> ClevelandOpsBatch b
$cfmap :: forall a b. (a -> b) -> ClevelandOpsBatch a -> ClevelandOpsBatch b
Functor, Functor ClevelandOpsBatch
a -> ClevelandOpsBatch a
Functor ClevelandOpsBatch
-> (forall a. a -> ClevelandOpsBatch a)
-> (forall a b.
    ClevelandOpsBatch (a -> b)
    -> ClevelandOpsBatch a -> ClevelandOpsBatch b)
-> (forall a b c.
    (a -> b -> c)
    -> ClevelandOpsBatch a
    -> ClevelandOpsBatch b
    -> ClevelandOpsBatch c)
-> (forall a b.
    ClevelandOpsBatch a -> ClevelandOpsBatch b -> ClevelandOpsBatch b)
-> (forall a b.
    ClevelandOpsBatch a -> ClevelandOpsBatch b -> ClevelandOpsBatch a)
-> Applicative ClevelandOpsBatch
ClevelandOpsBatch a -> ClevelandOpsBatch b -> ClevelandOpsBatch b
ClevelandOpsBatch a -> ClevelandOpsBatch b -> ClevelandOpsBatch a
ClevelandOpsBatch (a -> b)
-> ClevelandOpsBatch a -> ClevelandOpsBatch b
(a -> b -> c)
-> ClevelandOpsBatch a
-> ClevelandOpsBatch b
-> ClevelandOpsBatch c
forall a. a -> ClevelandOpsBatch a
forall a b.
ClevelandOpsBatch a -> ClevelandOpsBatch b -> ClevelandOpsBatch a
forall a b.
ClevelandOpsBatch a -> ClevelandOpsBatch b -> ClevelandOpsBatch b
forall a b.
ClevelandOpsBatch (a -> b)
-> ClevelandOpsBatch a -> ClevelandOpsBatch b
forall a b c.
(a -> b -> c)
-> ClevelandOpsBatch a
-> ClevelandOpsBatch b
-> ClevelandOpsBatch c
forall (f :: * -> *).
Functor f
-> (forall a. a -> f a)
-> (forall a b. f (a -> b) -> f a -> f b)
-> (forall a b c. (a -> b -> c) -> f a -> f b -> f c)
-> (forall a b. f a -> f b -> f b)
-> (forall a b. f a -> f b -> f a)
-> Applicative f
<* :: ClevelandOpsBatch a -> ClevelandOpsBatch b -> ClevelandOpsBatch a
$c<* :: forall a b.
ClevelandOpsBatch a -> ClevelandOpsBatch b -> ClevelandOpsBatch a
*> :: ClevelandOpsBatch a -> ClevelandOpsBatch b -> ClevelandOpsBatch b
$c*> :: forall a b.
ClevelandOpsBatch a -> ClevelandOpsBatch b -> ClevelandOpsBatch b
liftA2 :: (a -> b -> c)
-> ClevelandOpsBatch a
-> ClevelandOpsBatch b
-> ClevelandOpsBatch c
$cliftA2 :: forall a b c.
(a -> b -> c)
-> ClevelandOpsBatch a
-> ClevelandOpsBatch b
-> ClevelandOpsBatch c
<*> :: ClevelandOpsBatch (a -> b)
-> ClevelandOpsBatch a -> ClevelandOpsBatch b
$c<*> :: forall a b.
ClevelandOpsBatch (a -> b)
-> ClevelandOpsBatch a -> ClevelandOpsBatch b
pure :: a -> ClevelandOpsBatch a
$cpure :: forall a. a -> ClevelandOpsBatch a
$cp1Applicative :: Functor ClevelandOpsBatch
Applicative)

instance
  TypeError
  ( 'Text "Attempt to use monad capabilities within a batch" ':$$:
    'Text "In case you are using a do-block, make sure that" ':$$:
    'Text "• `ApplicativeDo` extension is enabled" ':$$:
    'Text "• there is a return statement in the end" ':$$:
    'Text "• returned value picks variables in the order in which they are defined"
  ) =>
  Monad ClevelandOpsBatch where
    >>= :: ClevelandOpsBatch a
-> (a -> ClevelandOpsBatch b) -> ClevelandOpsBatch b
(>>=) = Text
-> ClevelandOpsBatch a
-> (a -> ClevelandOpsBatch b)
-> ClevelandOpsBatch b
forall a. HasCallStack => Text -> a
error Text
"impossible"

{- | Run a series of operations within a batch.

Example:

@
contract <- runBatched impl $ do
  -- this block is executed within 'ClevelandOpsBatch'
  contract <- runSingleOperation batchedOpsImpl "origination" ...
  for_ [1..3] \i ->
    runSingleOperation batchedOpsImpl "transfer" ...
  return contract
@

See 'ClevelandOpsBatch' for some precautions.
-}
runBatched
  :: (HasCallStack, Functor m)
  => ClevelandOpsImpl m
  -> ClevelandOpsBatch a
  -> m a
runBatched :: ClevelandOpsImpl m -> ClevelandOpsBatch a -> m a
runBatched ClevelandOpsImpl m
impl =
  Proxy Void
-> ClevelandOpsImpl m
-> BatchingM
     (OperationInfo ClevelandInput) (OperationInfo Result) Void a
-> m a
forall e (m :: * -> *) a.
(HasCallStack, Buildable e, Functor m) =>
Proxy e
-> ClevelandOpsImpl m
-> BatchingM
     (OperationInfo ClevelandInput) (OperationInfo Result) e a
-> m a
runOperationBatchM (Proxy Void
forall k (t :: k). Proxy t
Proxy @Void) ClevelandOpsImpl m
impl (BatchingM
   (OperationInfo ClevelandInput) (OperationInfo Result) Void a
 -> m a)
-> (ClevelandOpsBatch a
    -> BatchingM
         (OperationInfo ClevelandInput) (OperationInfo Result) Void a)
-> ClevelandOpsBatch a
-> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ClevelandOpsBatch a
-> BatchingM
     (OperationInfo ClevelandInput) (OperationInfo Result) Void a
forall a.
ClevelandOpsBatch a
-> BatchingM
     (OperationInfo ClevelandInput) (OperationInfo Result) Void a
unClevelandOpsBatch

-- | 'ClevelandOpsImpl' suitable for methods executed within a batch.
batchedOpsImpl :: ClevelandOpsImpl ClevelandOpsBatch
batchedOpsImpl :: ClevelandOpsImpl ClevelandOpsBatch
batchedOpsImpl = ClevelandOpsImpl :: forall (m :: * -> *).
(HasCallStack =>
 [OperationInfo ClevelandInput] -> m [OperationInfo Result])
-> ClevelandOpsImpl m
ClevelandOpsImpl
  { coiRunOperationBatch :: HasCallStack =>
[OperationInfo ClevelandInput]
-> ClevelandOpsBatch [OperationInfo Result]
coiRunOperationBatch = BatchingM
  (OperationInfo ClevelandInput)
  (OperationInfo Result)
  Void
  [OperationInfo Result]
-> ClevelandOpsBatch [OperationInfo Result]
forall a.
BatchingM
  (OperationInfo ClevelandInput) (OperationInfo Result) Void a
-> ClevelandOpsBatch a
ClevelandOpsBatch (BatchingM
   (OperationInfo ClevelandInput)
   (OperationInfo Result)
   Void
   [OperationInfo Result]
 -> ClevelandOpsBatch [OperationInfo Result])
-> ([OperationInfo ClevelandInput]
    -> BatchingM
         (OperationInfo ClevelandInput)
         (OperationInfo Result)
         Void
         [OperationInfo Result])
-> [OperationInfo ClevelandInput]
-> ClevelandOpsBatch [OperationInfo Result]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (OperationInfo ClevelandInput
 -> BatchingM
      (OperationInfo ClevelandInput)
      (OperationInfo Result)
      Void
      (OperationInfo Result))
-> [OperationInfo ClevelandInput]
-> BatchingM
     (OperationInfo ClevelandInput)
     (OperationInfo Result)
     Void
     [OperationInfo Result]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse (OperationInfo ClevelandInput
-> (OperationInfo Result -> Either Void (OperationInfo Result))
-> BatchingM
     (OperationInfo ClevelandInput)
     (OperationInfo Result)
     Void
     (OperationInfo Result)
forall i o e a. i -> (o -> Either e a) -> BatchingM i o e a
`submitThenParse` OperationInfo Result -> Either Void (OperationInfo Result)
forall (f :: * -> *) a. Applicative f => a -> f a
pure)
  }

-- | Version of 'coiRunOperationBatch' that uses 'BatchingM'.
--
-- This is an internal function.
--
-- Invariant: all errors described by @e@ must be internal and should not occur
-- in practice (we require @e@ type to be specified explicitly to hinder
-- incorrect usage).
runOperationBatchM
  :: (HasCallStack, Buildable e, Functor m)
  => Proxy e
  -> ClevelandOpsImpl m
  -> BatchingM (OperationInfo ClevelandInput) (OperationInfo Result) e a
  -> m a
runOperationBatchM :: Proxy e
-> ClevelandOpsImpl m
-> BatchingM
     (OperationInfo ClevelandInput) (OperationInfo Result) e a
-> m a
runOperationBatchM Proxy e
_ ClevelandOpsImpl m
impl =
  (((), a) -> a) -> m ((), a) -> m a
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((), a) -> a
forall a b. (a, b) -> b
snd (m ((), a) -> m a)
-> (BatchingM
      (OperationInfo ClevelandInput) (OperationInfo Result) e a
    -> m ((), a))
-> BatchingM
     (OperationInfo ClevelandInput) (OperationInfo Result) e a
-> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([OperationInfo ClevelandInput] -> m ((), [OperationInfo Result]))
-> BatchingM
     (OperationInfo ClevelandInput) (OperationInfo Result) e a
-> m ((), a)
forall (m :: * -> *) e i r o a.
(Functor m, Buildable e) =>
([i] -> m (r, [o])) -> BatchingM i o e a -> m (r, a)
unsafeRunBatching (([OperationInfo Result] -> ((), [OperationInfo Result]))
-> m [OperationInfo Result] -> m ((), [OperationInfo Result])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((), ) (m [OperationInfo Result] -> m ((), [OperationInfo Result]))
-> ([OperationInfo ClevelandInput] -> m [OperationInfo Result])
-> [OperationInfo ClevelandInput]
-> m ((), [OperationInfo Result])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ClevelandOpsImpl m
-> HasCallStack =>
   [OperationInfo ClevelandInput] -> m [OperationInfo Result]
forall (m :: * -> *).
ClevelandOpsImpl m
-> HasCallStack =>
   [OperationInfo ClevelandInput] -> m [OperationInfo Result]
coiRunOperationBatch ClevelandOpsImpl m
impl)

-- | Helper that runs a single operation using 'ClevelandOpsImpl'.
runSingleOperation
  :: (HasCallStack, Functor m)
  => ClevelandOpsImpl m
  -> Text
  -> OperationInfo ClevelandInput
  -> (OperationInfo Result -> Maybe a)
  -> m a
runSingleOperation :: ClevelandOpsImpl m
-> Text
-> OperationInfo ClevelandInput
-> (OperationInfo Result -> Maybe a)
-> m a
runSingleOperation ClevelandOpsImpl m
impl Text
desc OperationInfo ClevelandInput
opData OperationInfo Result -> Maybe a
parseRes =
  Proxy BatchResultMismatch
-> ClevelandOpsImpl m
-> BatchingM
     (OperationInfo ClevelandInput)
     (OperationInfo Result)
     BatchResultMismatch
     a
-> m a
forall e (m :: * -> *) a.
(HasCallStack, Buildable e, Functor m) =>
Proxy e
-> ClevelandOpsImpl m
-> BatchingM
     (OperationInfo ClevelandInput) (OperationInfo Result) e a
-> m a
runOperationBatchM (Proxy BatchResultMismatch
forall k (t :: k). Proxy t
Proxy @BatchResultMismatch) ClevelandOpsImpl m
impl (BatchingM
   (OperationInfo ClevelandInput)
   (OperationInfo Result)
   BatchResultMismatch
   a
 -> m a)
-> BatchingM
     (OperationInfo ClevelandInput)
     (OperationInfo Result)
     BatchResultMismatch
     a
-> m a
forall a b. (a -> b) -> a -> b
$
    OperationInfo ClevelandInput
opData OperationInfo ClevelandInput
-> (OperationInfo Result -> Either BatchResultMismatch a)
-> BatchingM
     (OperationInfo ClevelandInput)
     (OperationInfo Result)
     BatchResultMismatch
     a
forall i o e a. i -> (o -> Either e a) -> BatchingM i o e a
`submitThenParse` BatchResultMismatch -> Maybe a -> Either BatchResultMismatch a
forall l r. l -> Maybe r -> Either l r
maybeToRight (Text -> BatchResultMismatch
BatchResultMismatch Text
desc) (Maybe a -> Either BatchResultMismatch a)
-> (OperationInfo Result -> Maybe a)
-> OperationInfo Result
-> Either BatchResultMismatch a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. OperationInfo Result -> Maybe a
parseRes

----------------------------------------------------------------------------
-- Validation
----------------------------------------------------------------------------

-- | Representation of Expression we got from the RPC or a typed value we
-- got from the emulator.
data ExpressionOrTypedValue where
  EOTVExpression :: Expression -> ExpressionOrTypedValue
  EOTVTypedValue :: (T.SingI t, ConstantScope t) => T.Value t -> ExpressionOrTypedValue

deriving stock instance Show ExpressionOrTypedValue
instance Eq ExpressionOrTypedValue where
  == :: ExpressionOrTypedValue -> ExpressionOrTypedValue -> Bool
(==) (EOTVExpression Expression
x) (EOTVExpression Expression
y) = Expression
x Expression -> Expression -> Bool
forall a. Eq a => a -> a -> Bool
== Expression
y
  (==) (EOTVTypedValue (Value t
x :: T.Value t)) (EOTVTypedValue (Value t
y :: T.Value u))
    = case (SingI t, SingI t, TestEquality Sing) => Maybe (t :~: t)
forall k (a :: k) (b :: k).
(SingI a, SingI b, TestEquality Sing) =>
Maybe (a :~: b)
eqI @t @u of
      Just t :~: t
Refl -> Value t
x Value t -> Value t -> Bool
forall a. Eq a => a -> a -> Bool
== Value t
Value t
y
      Maybe (t :~: t)
Nothing -> Bool
False
  (==) ExpressionOrTypedValue
_ ExpressionOrTypedValue
_ = Bool
False

instance Buildable ExpressionOrTypedValue where
  build :: ExpressionOrTypedValue -> Builder
build = \case
    EOTVExpression Expression
e -> (FromExpressionError -> Builder)
-> (Value -> Builder)
-> Either FromExpressionError Value
-> Builder
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Builder -> FromExpressionError -> Builder
forall a b. a -> b -> a
const (Builder -> FromExpressionError -> Builder)
-> Builder -> FromExpressionError -> Builder
forall a b. (a -> b) -> a -> b
$ Expression -> Builder
forall p. Buildable p => p -> Builder
build Expression
e) Value -> Builder
forall p. Buildable p => p -> Builder
build (Either FromExpressionError Value -> Builder)
-> Either FromExpressionError Value -> Builder
forall a b. (a -> b) -> a -> b
$ Expression -> Either FromExpressionError Value
forall a.
FromExpression a =>
Expression -> Either FromExpressionError a
fromExpression @U.Value Expression
e
    EOTVTypedValue Value t
v -> Value t -> Builder
forall p. Buildable p => p -> Builder
build Value t
v

-- | Failures that could be expected in the execution of a transfer.
-- These can be caught and handled with 'Test.Cleveland.attempt'.
data TransferFailure = TransferFailure
  { TransferFailure -> Address
tfAddress :: Address
  , TransferFailure -> TransferFailureReason
tfReason :: TransferFailureReason
  } deriving stock (Int -> TransferFailure -> ShowS
[TransferFailure] -> ShowS
TransferFailure -> String
(Int -> TransferFailure -> ShowS)
-> (TransferFailure -> String)
-> ([TransferFailure] -> ShowS)
-> Show TransferFailure
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [TransferFailure] -> ShowS
$cshowList :: [TransferFailure] -> ShowS
show :: TransferFailure -> String
$cshow :: TransferFailure -> String
showsPrec :: Int -> TransferFailure -> ShowS
$cshowsPrec :: Int -> TransferFailure -> ShowS
Show, TransferFailure -> TransferFailure -> Bool
(TransferFailure -> TransferFailure -> Bool)
-> (TransferFailure -> TransferFailure -> Bool)
-> Eq TransferFailure
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: TransferFailure -> TransferFailure -> Bool
$c/= :: TransferFailure -> TransferFailure -> Bool
== :: TransferFailure -> TransferFailure -> Bool
$c== :: TransferFailure -> TransferFailure -> Bool
Eq)

data TransferFailureReason
  = FailedWith ExpressionOrTypedValue (Maybe InstrCallStack)
  -- ^ Expect that interpretation of contract with the given address ended
  -- with @FAILWITH@.
  | EmptyTransaction
  -- ^ Expect failure due to an attempt to transfer 0tz towards a simple address.
  | BadParameter
  -- ^ Expect failure due to an attempt to call a contract with an invalid parameter.
  | MutezArithError T.MutezArithErrorType
  -- ^ Expect failure due to an arithmetic over-/underflow
  | ShiftOverflow
  -- ^ Expect that interpretation of contract with the given address ended
  -- with an overflow error.
  | GasExhaustion
  -- TODO: [#284] add more errors here!
  deriving stock (Int -> TransferFailureReason -> ShowS
[TransferFailureReason] -> ShowS
TransferFailureReason -> String
(Int -> TransferFailureReason -> ShowS)
-> (TransferFailureReason -> String)
-> ([TransferFailureReason] -> ShowS)
-> Show TransferFailureReason
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [TransferFailureReason] -> ShowS
$cshowList :: [TransferFailureReason] -> ShowS
show :: TransferFailureReason -> String
$cshow :: TransferFailureReason -> String
showsPrec :: Int -> TransferFailureReason -> ShowS
$cshowsPrec :: Int -> TransferFailureReason -> ShowS
Show, TransferFailureReason -> TransferFailureReason -> Bool
(TransferFailureReason -> TransferFailureReason -> Bool)
-> (TransferFailureReason -> TransferFailureReason -> Bool)
-> Eq TransferFailureReason
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: TransferFailureReason -> TransferFailureReason -> Bool
$c/= :: TransferFailureReason -> TransferFailureReason -> Bool
== :: TransferFailureReason -> TransferFailureReason -> Bool
$c== :: TransferFailureReason -> TransferFailureReason -> Bool
Eq)

-- | When an exception is thrown in a 'Test.Cleveland.branchout' branch, we wrap it in this
-- constructor to remember in _which_ branch it was thrown.
-- We use this information to provide better error messages when a test fails.
data FailedInBranch = FailedInBranch ScenarioBranchName SomeException
  deriving stock (Int -> FailedInBranch -> ShowS
[FailedInBranch] -> ShowS
FailedInBranch -> String
(Int -> FailedInBranch -> ShowS)
-> (FailedInBranch -> String)
-> ([FailedInBranch] -> ShowS)
-> Show FailedInBranch
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [FailedInBranch] -> ShowS
$cshowList :: [FailedInBranch] -> ShowS
show :: FailedInBranch -> String
$cshow :: FailedInBranch -> String
showsPrec :: Int -> FailedInBranch -> ShowS
$cshowsPrec :: Int -> FailedInBranch -> ShowS
Show)

-- | When using 'Test.Cleveland.branchout' function for building test scenarios - names
-- of branches we are currently within.
newtype ScenarioBranchName = ScenarioBranchName { ScenarioBranchName -> [Text]
unTestBranch :: [Text] }
  deriving stock (Int -> ScenarioBranchName -> ShowS
[ScenarioBranchName] -> ShowS
ScenarioBranchName -> String
(Int -> ScenarioBranchName -> ShowS)
-> (ScenarioBranchName -> String)
-> ([ScenarioBranchName] -> ShowS)
-> Show ScenarioBranchName
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [ScenarioBranchName] -> ShowS
$cshowList :: [ScenarioBranchName] -> ShowS
show :: ScenarioBranchName -> String
$cshow :: ScenarioBranchName -> String
showsPrec :: Int -> ScenarioBranchName -> ShowS
$cshowsPrec :: Int -> ScenarioBranchName -> ShowS
Show, ScenarioBranchName -> ScenarioBranchName -> Bool
(ScenarioBranchName -> ScenarioBranchName -> Bool)
-> (ScenarioBranchName -> ScenarioBranchName -> Bool)
-> Eq ScenarioBranchName
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: ScenarioBranchName -> ScenarioBranchName -> Bool
$c/= :: ScenarioBranchName -> ScenarioBranchName -> Bool
== :: ScenarioBranchName -> ScenarioBranchName -> Bool
$c== :: ScenarioBranchName -> ScenarioBranchName -> Bool
Eq)

instance Buildable ScenarioBranchName where
  build :: ScenarioBranchName -> Builder
build = [Builder] -> Builder
forall a. Monoid a => [a] -> a
mconcat ([Builder] -> Builder)
-> (ScenarioBranchName -> [Builder])
-> ScenarioBranchName
-> Builder
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Builder -> [Builder] -> [Builder]
forall a. a -> [a] -> [a]
intersperse Builder
"/" ([Builder] -> [Builder])
-> (ScenarioBranchName -> [Builder])
-> ScenarioBranchName
-> [Builder]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text -> Builder) -> [Text] -> [Builder]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
map Text -> Builder
forall p. Buildable p => p -> Builder
build ([Text] -> [Builder])
-> (ScenarioBranchName -> [Text])
-> ScenarioBranchName
-> [Builder]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ScenarioBranchName -> [Text]
unTestBranch

instance Buildable TransferFailure where
  build :: TransferFailure -> Builder
build (TransferFailure Address
addr TransferFailureReason
reason) = case TransferFailureReason
reason of
    TransferFailureReason
EmptyTransaction -> TransferFailureReason
reason TransferFailureReason -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ Builder
": " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| Address
addr Address -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ Builder
""
    TransferFailureReason
BadParameter -> Builder
"Attempted to call contract " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| Address
addr Address -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ Builder
" with a " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| TransferFailureReason
reason TransferFailureReason -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ Builder
""
    FailedWith{} -> Builder
"Contract: " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| Address
addr Address -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ Builder
" " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| TransferFailureReason
reason TransferFailureReason -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ Builder
""
    TransferFailureReason
_ -> Builder
"Contract: " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| Address
addr Address -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ Builder
" failed due to a " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| TransferFailureReason
reason TransferFailureReason -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ Builder
""

instance Buildable TransferFailureReason where
  build :: TransferFailureReason -> Builder
build = \case
    FailedWith ExpressionOrTypedValue
expr Maybe InstrCallStack
loc -> Builder
"failed with: " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| ExpressionOrTypedValue
expr ExpressionOrTypedValue -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ Builder
-> (InstrCallStack -> Builder) -> Maybe InstrCallStack -> Builder
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Builder
"" ((Builder
" at " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+|) (Builder -> Builder)
-> (InstrCallStack -> Builder) -> InstrCallStack -> Builder
forall b c a. (b -> c) -> (a -> b) -> a -> c
. InstrCallStack -> Builder
forall p. Buildable p => p -> Builder
build) Maybe InstrCallStack
loc
    TransferFailureReason
EmptyTransaction -> Builder
"Attempted to transfer 0tz to a simple address"
    TransferFailureReason
BadParameter -> Builder
"parameter of the wrong type"
    MutezArithError MutezArithErrorType
typ -> Builder
"mutez " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| MutezArithErrorType
typ MutezArithErrorType -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ Builder
""
    TransferFailureReason
ShiftOverflow -> Builder
"overflow error"
    TransferFailureReason
GasExhaustion -> Builder
"gas exhaustion"

instance Buildable FailedInBranch where
  build :: FailedInBranch -> Builder
build (FailedInBranch ScenarioBranchName
branchName (SomeException e
err)) = Builder
"In '" Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| ScenarioBranchName
branchName ScenarioBranchName -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+
    Builder
"' branch:\n" Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| (String -> Builder
forall p. Buildable p => p -> Builder
build (String -> Builder) -> String -> Builder
forall a b. (a -> b) -> a -> b
$ e -> String
forall e. Exception e => e -> String
displayException e
err)

data GenericTestError
  = UnexpectedSuccess
  deriving stock Int -> GenericTestError -> ShowS
[GenericTestError] -> ShowS
GenericTestError -> String
(Int -> GenericTestError -> ShowS)
-> (GenericTestError -> String)
-> ([GenericTestError] -> ShowS)
-> Show GenericTestError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [GenericTestError] -> ShowS
$cshowList :: [GenericTestError] -> ShowS
show :: GenericTestError -> String
$cshow :: GenericTestError -> String
showsPrec :: Int -> GenericTestError -> ShowS
$cshowsPrec :: Int -> GenericTestError -> ShowS
Show

instance Buildable GenericTestError where
  build :: GenericTestError -> Builder
build = \case
    GenericTestError
UnexpectedSuccess ->
      Builder
"Expected an exception to be thrown, but it wasn't"

instance Exception TransferFailure where
  displayException :: TransferFailure -> String
displayException = TransferFailure -> String
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty
  fromException :: SomeException -> Maybe TransferFailure
fromException someEx :: SomeException
someEx@(SomeException e
ex) =
    e -> Maybe TransferFailure
forall a b. (Typeable a, Typeable b) => a -> Maybe b
cast @_ @TransferFailure e
ex
    Maybe TransferFailure
-> Maybe TransferFailure -> Maybe TransferFailure
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|>
    ( do
        WithCallStack CallStack
_ SomeException
exInner <- SomeException -> Maybe WithCallStack
forall e. Exception e => SomeException -> Maybe e
fromException @WithCallStack SomeException
someEx
        SomeException -> Maybe TransferFailure
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
exInner
    )
    Maybe TransferFailure
-> Maybe TransferFailure -> Maybe TransferFailure
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|>
    ( do
        FailedInBranch ScenarioBranchName
_ SomeException
exInner <- SomeException -> Maybe FailedInBranch
forall e. Exception e => SomeException -> Maybe e
fromException @FailedInBranch SomeException
someEx
        SomeException -> Maybe TransferFailure
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
exInner
    )


instance Exception FailedInBranch where
  displayException :: FailedInBranch -> String
displayException = FailedInBranch -> String
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty

instance Exception GenericTestError where
  displayException :: GenericTestError -> String
displayException = GenericTestError -> String
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty

----------------------------------------------------------------------------
-- Other helpers
----------------------------------------------------------------------------

-- | A short partial constructor for 'EpName'. It is supposed to be
-- applied to string constants, so programmer is responsible for
-- validity. And this code is for tests anyway, so each failure is a
-- programmer mistake.
--
-- It is intentionally here and not in some deeper module because the
-- name is really short and more suitable for writing scenarios.
ep :: HasCallStack => Text -> EpName
ep :: Text -> EpName
ep = Either String EpName -> EpName
forall a b. (HasCallStack, Buildable a) => Either a b -> b
unsafe (Either String EpName -> EpName)
-> (Text -> Either String EpName) -> Text -> EpName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Either String EpName
U.buildEpName

-- | Runs a handler over every action.
mapClevelandOpsImplExceptions
  :: (forall a. HasCallStack => m a -> m a)
  -> ClevelandOpsImpl m -> ClevelandOpsImpl m
mapClevelandOpsImplExceptions :: (forall a. HasCallStack => m a -> m a)
-> ClevelandOpsImpl m -> ClevelandOpsImpl m
mapClevelandOpsImplExceptions forall a. HasCallStack => m a -> m a
f ClevelandOpsImpl{HasCallStack =>
[OperationInfo ClevelandInput] -> m [OperationInfo Result]
coiRunOperationBatch :: HasCallStack =>
[OperationInfo ClevelandInput] -> m [OperationInfo Result]
coiRunOperationBatch :: forall (m :: * -> *).
ClevelandOpsImpl m
-> HasCallStack =>
   [OperationInfo ClevelandInput] -> m [OperationInfo Result]
..} = ClevelandOpsImpl :: forall (m :: * -> *).
(HasCallStack =>
 [OperationInfo ClevelandInput] -> m [OperationInfo Result])
-> ClevelandOpsImpl m
ClevelandOpsImpl
    { coiRunOperationBatch :: HasCallStack =>
[OperationInfo ClevelandInput] -> m [OperationInfo Result]
coiRunOperationBatch = \[OperationInfo ClevelandInput]
op -> m [OperationInfo Result] -> m [OperationInfo Result]
forall a. HasCallStack => m a -> m a
f (m [OperationInfo Result] -> m [OperationInfo Result])
-> m [OperationInfo Result] -> m [OperationInfo Result]
forall a b. (a -> b) -> a -> b
$ HasCallStack =>
[OperationInfo ClevelandInput] -> m [OperationInfo Result]
[OperationInfo ClevelandInput] -> m [OperationInfo Result]
coiRunOperationBatch [OperationInfo ClevelandInput]
op
    }

-- | Runs a handler over every action (except 'cmiAttempt' and 'cmiThrow'),
-- possibly transforming exceptions thrown by those actions.
mapClevelandMiscImplExceptions
  :: (forall a. HasCallStack => m a -> m a)
  -> ClevelandMiscImpl m -> ClevelandMiscImpl m
mapClevelandMiscImplExceptions :: (forall a. HasCallStack => m a -> m a)
-> ClevelandMiscImpl m -> ClevelandMiscImpl m
mapClevelandMiscImplExceptions forall a. HasCallStack => m a -> m a
f ClevelandMiscImpl{m (Maybe (EmulatedImpl m))
HasCallStack => m Natural
HasCallStack => m (Time Second)
HasCallStack => m ChainId
HasCallStack => m Timestamp
HasCallStack => ByteString -> Address -> m Signature
HasCallStack => Text -> m ()
HasCallStack => Address -> m (Maybe KeyHash)
HasCallStack => Address -> m ()
HasCallStack => Address -> m PublicKey
HasCallStack => Address -> m Mutez
HasCallStack => Address -> m SomeAnnotatedValue
HasCallStack => AliasHint -> m Address
HasCallStack => SpecificOrDefaultAliasHint -> m Address
HasCallStack => Sender -> UntypedOriginateData -> m Address
HasCallStack => (Natural -> Natural) -> m ()
Address -> m ()
forall res. HasCallStack => IO res -> m res
forall a. HasCallStack => Builder -> m a
forall a. HasCallStack => SomeException -> m a
forall k v.
(HasCallStack, NiceComparable k, NiceUnpackedValue v) =>
BigMapId k v -> m (Maybe [v])
forall k v.
(HasCallStack, NiceComparable k, NicePackedValue k,
 NiceUnpackedValue v) =>
BigMapId k v -> k -> m (Maybe v)
forall a e. (Exception e, HasCallStack) => m a -> m (Either e a)
forall cp st vd.
(HasCallStack, HasRPCRepr st, IsoValue (AsRPC st)) =>
Sender -> RunCode cp st vd -> m (AsRPC st)
forall (unit :: Rat).
(HasCallStack, KnownDivRat unit Second) =>
Time unit -> m ()
cmiRunCode :: forall cp st vd.
(HasCallStack, HasRPCRepr st, IsoValue (AsRPC st)) =>
Sender -> RunCode cp st vd -> m (AsRPC st)
cmiEmulatedImpl :: m (Maybe (EmulatedImpl m))
cmiMarkAddressRefillable :: Address -> m ()
cmiAttempt :: forall a e. (Exception e, HasCallStack) => m a -> m (Either e a)
cmiGetApproximateBlockInterval :: HasCallStack => m (Time Second)
cmiThrow :: forall a. HasCallStack => SomeException -> m a
cmiFailure :: forall a. HasCallStack => Builder -> m a
cmiGetLevel :: HasCallStack => m Natural
cmiGetNow :: HasCallStack => m Timestamp
cmiAdvanceToLevel :: HasCallStack => (Natural -> Natural) -> m ()
cmiAdvanceTime :: forall (unit :: Rat).
(HasCallStack, KnownDivRat unit Second) =>
Time unit -> m ()
cmiGetChainId :: HasCallStack => m ChainId
cmiRegisterDelegate :: HasCallStack => Address -> m ()
cmiGetDelegate :: HasCallStack => Address -> m (Maybe KeyHash)
cmiGetPublicKey :: HasCallStack => Address -> m PublicKey
cmiGetAllBigMapValuesMaybe :: forall k v.
(HasCallStack, NiceComparable k, NiceUnpackedValue v) =>
BigMapId k v -> m (Maybe [v])
cmiGetBigMapValueMaybe :: forall k v.
(HasCallStack, NiceComparable k, NicePackedValue k,
 NiceUnpackedValue v) =>
BigMapId k v -> k -> m (Maybe v)
cmiGetSomeStorage :: HasCallStack => Address -> m SomeAnnotatedValue
cmiGetBalance :: HasCallStack => Address -> m Mutez
cmiComment :: HasCallStack => Text -> m ()
cmiOriginateLargeUntyped :: HasCallStack => Sender -> UntypedOriginateData -> m Address
cmiSignBytes :: HasCallStack => ByteString -> Address -> m Signature
cmiGenFreshKey :: HasCallStack => SpecificOrDefaultAliasHint -> m Address
cmiGenKey :: HasCallStack => SpecificOrDefaultAliasHint -> m Address
cmiResolveAddress :: HasCallStack => AliasHint -> m Address
cmiRunIO :: forall res. HasCallStack => IO res -> m res
cmiRunCode :: forall (m :: * -> *).
ClevelandMiscImpl m
-> forall cp st vd.
   (HasCallStack, HasRPCRepr st, IsoValue (AsRPC st)) =>
   Sender -> RunCode cp st vd -> m (AsRPC st)
cmiEmulatedImpl :: forall (m :: * -> *).
ClevelandMiscImpl m -> m (Maybe (EmulatedImpl m))
cmiMarkAddressRefillable :: forall (m :: * -> *). ClevelandMiscImpl m -> Address -> m ()
cmiAttempt :: forall (m :: * -> *).
ClevelandMiscImpl m
-> forall a e. (Exception e, HasCallStack) => m a -> m (Either e a)
cmiGetApproximateBlockInterval :: forall (m :: * -> *).
ClevelandMiscImpl m -> HasCallStack => m (Time Second)
cmiThrow :: forall (m :: * -> *).
ClevelandMiscImpl m
-> forall a. HasCallStack => SomeException -> m a
cmiFailure :: forall (m :: * -> *).
ClevelandMiscImpl m -> forall a. HasCallStack => Builder -> m a
cmiGetLevel :: forall (m :: * -> *).
ClevelandMiscImpl m -> HasCallStack => m Natural
cmiGetNow :: forall (m :: * -> *).
ClevelandMiscImpl m -> HasCallStack => m Timestamp
cmiAdvanceToLevel :: forall (m :: * -> *).
ClevelandMiscImpl m -> HasCallStack => (Natural -> Natural) -> m ()
cmiAdvanceTime :: forall (m :: * -> *).
ClevelandMiscImpl m
-> forall (unit :: Rat).
   (HasCallStack, KnownDivRat unit Second) =>
   Time unit -> m ()
cmiGetChainId :: forall (m :: * -> *).
ClevelandMiscImpl m -> HasCallStack => m ChainId
cmiRegisterDelegate :: forall (m :: * -> *).
ClevelandMiscImpl m -> HasCallStack => Address -> m ()
cmiGetDelegate :: forall (m :: * -> *).
ClevelandMiscImpl m -> HasCallStack => Address -> m (Maybe KeyHash)
cmiGetPublicKey :: forall (m :: * -> *).
ClevelandMiscImpl m -> HasCallStack => Address -> m PublicKey
cmiGetAllBigMapValuesMaybe :: forall (m :: * -> *).
ClevelandMiscImpl m
-> forall k v.
   (HasCallStack, NiceComparable k, NiceUnpackedValue v) =>
   BigMapId k v -> m (Maybe [v])
cmiGetBigMapValueMaybe :: forall (m :: * -> *).
ClevelandMiscImpl m
-> forall k v.
   (HasCallStack, NiceComparable k, NicePackedValue k,
    NiceUnpackedValue v) =>
   BigMapId k v -> k -> m (Maybe v)
cmiGetSomeStorage :: forall (m :: * -> *).
ClevelandMiscImpl m
-> HasCallStack => Address -> m SomeAnnotatedValue
cmiGetBalance :: forall (m :: * -> *).
ClevelandMiscImpl m -> HasCallStack => Address -> m Mutez
cmiComment :: forall (m :: * -> *).
ClevelandMiscImpl m -> HasCallStack => Text -> m ()
cmiOriginateLargeUntyped :: forall (m :: * -> *).
ClevelandMiscImpl m
-> HasCallStack => Sender -> UntypedOriginateData -> m Address
cmiSignBytes :: forall (m :: * -> *).
ClevelandMiscImpl m
-> HasCallStack => ByteString -> Address -> m Signature
cmiGenFreshKey :: forall (m :: * -> *).
ClevelandMiscImpl m
-> HasCallStack => SpecificOrDefaultAliasHint -> m Address
cmiGenKey :: forall (m :: * -> *).
ClevelandMiscImpl m
-> HasCallStack => SpecificOrDefaultAliasHint -> m Address
cmiResolveAddress :: forall (m :: * -> *).
ClevelandMiscImpl m -> HasCallStack => AliasHint -> m Address
cmiRunIO :: forall (m :: * -> *).
ClevelandMiscImpl m -> forall res. HasCallStack => IO res -> m res
..} = ClevelandMiscImpl :: forall (m :: * -> *).
(forall res. HasCallStack => IO res -> m res)
-> (HasCallStack => AliasHint -> m Address)
-> (HasCallStack => SpecificOrDefaultAliasHint -> m Address)
-> (HasCallStack => SpecificOrDefaultAliasHint -> m Address)
-> (HasCallStack => ByteString -> Address -> m Signature)
-> (HasCallStack => Sender -> UntypedOriginateData -> m Address)
-> (HasCallStack => Text -> m ())
-> (HasCallStack => Address -> m Mutez)
-> (HasCallStack => Address -> m SomeAnnotatedValue)
-> (forall k v.
    (HasCallStack, NiceComparable k, NicePackedValue k,
     NiceUnpackedValue v) =>
    BigMapId k v -> k -> m (Maybe v))
-> (forall k v.
    (HasCallStack, NiceComparable k, NiceUnpackedValue v) =>
    BigMapId k v -> m (Maybe [v]))
-> (HasCallStack => Address -> m PublicKey)
-> (HasCallStack => Address -> m (Maybe KeyHash))
-> (HasCallStack => Address -> m ())
-> (HasCallStack => m ChainId)
-> (forall (unit :: Rat).
    (HasCallStack, KnownDivRat unit Second) =>
    Time unit -> m ())
-> (HasCallStack => (Natural -> Natural) -> m ())
-> (HasCallStack => m Timestamp)
-> (HasCallStack => m Natural)
-> (forall a. HasCallStack => Builder -> m a)
-> (forall a. HasCallStack => SomeException -> m a)
-> (HasCallStack => m (Time Second))
-> (forall a e.
    (Exception e, HasCallStack) =>
    m a -> m (Either e a))
-> (Address -> m ())
-> m (Maybe (EmulatedImpl m))
-> (forall cp st vd.
    (HasCallStack, HasRPCRepr st, IsoValue (AsRPC st)) =>
    Sender -> RunCode cp st vd -> m (AsRPC st))
-> ClevelandMiscImpl m
ClevelandMiscImpl
    { cmiRunIO :: forall res. HasCallStack => IO res -> m res
cmiRunIO = \IO res
action -> m res -> m res
forall a. HasCallStack => m a -> m a
f (m res -> m res) -> m res -> m res
forall a b. (a -> b) -> a -> b
$ IO res -> m res
forall res. HasCallStack => IO res -> m res
cmiRunIO IO res
action
    , cmiResolveAddress :: HasCallStack => AliasHint -> m Address
cmiResolveAddress = \AliasHint
address -> m Address -> m Address
forall a. HasCallStack => m a -> m a
f (m Address -> m Address) -> m Address -> m Address
forall a b. (a -> b) -> a -> b
$ HasCallStack => AliasHint -> m Address
AliasHint -> m Address
cmiResolveAddress AliasHint
address
    , cmiSignBytes :: HasCallStack => ByteString -> Address -> m Signature
cmiSignBytes = \ByteString
bs Address
alias -> m Signature -> m Signature
forall a. HasCallStack => m a -> m a
f (m Signature -> m Signature) -> m Signature -> m Signature
forall a b. (a -> b) -> a -> b
$ HasCallStack => ByteString -> Address -> m Signature
ByteString -> Address -> m Signature
cmiSignBytes ByteString
bs Address
alias
    , cmiGenKey :: HasCallStack => SpecificOrDefaultAliasHint -> m Address
cmiGenKey = \SpecificOrDefaultAliasHint
aliasHint -> m Address -> m Address
forall a. HasCallStack => m a -> m a
f (m Address -> m Address) -> m Address -> m Address
forall a b. (a -> b) -> a -> b
$ HasCallStack => SpecificOrDefaultAliasHint -> m Address
SpecificOrDefaultAliasHint -> m Address
cmiGenKey SpecificOrDefaultAliasHint
aliasHint
    , cmiGenFreshKey :: HasCallStack => SpecificOrDefaultAliasHint -> m Address
cmiGenFreshKey = \SpecificOrDefaultAliasHint
aliasHint -> m Address -> m Address
forall a. HasCallStack => m a -> m a
f (m Address -> m Address) -> m Address -> m Address
forall a b. (a -> b) -> a -> b
$ HasCallStack => SpecificOrDefaultAliasHint -> m Address
SpecificOrDefaultAliasHint -> m Address
cmiGenFreshKey SpecificOrDefaultAliasHint
aliasHint
    , cmiOriginateLargeUntyped :: HasCallStack => Sender -> UntypedOriginateData -> m Address
cmiOriginateLargeUntyped = \Sender
sender UntypedOriginateData
uodata -> m Address -> m Address
forall a. HasCallStack => m a -> m a
f (m Address -> m Address) -> m Address -> m Address
forall a b. (a -> b) -> a -> b
$ HasCallStack => Sender -> UntypedOriginateData -> m Address
Sender -> UntypedOriginateData -> m Address
cmiOriginateLargeUntyped Sender
sender UntypedOriginateData
uodata
    , cmiComment :: HasCallStack => Text -> m ()
cmiComment = \Text
t -> m () -> m ()
forall a. HasCallStack => m a -> m a
f (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$ HasCallStack => Text -> m ()
Text -> m ()
cmiComment Text
t
    , cmiGetBalance :: HasCallStack => Address -> m Mutez
cmiGetBalance = \Address
addr -> m Mutez -> m Mutez
forall a. HasCallStack => m a -> m a
f (m Mutez -> m Mutez) -> m Mutez -> m Mutez
forall a b. (a -> b) -> a -> b
$ HasCallStack => Address -> m Mutez
Address -> m Mutez
cmiGetBalance Address
addr
    , cmiGetSomeStorage :: HasCallStack => Address -> m SomeAnnotatedValue
cmiGetSomeStorage = \Address
addr -> m SomeAnnotatedValue -> m SomeAnnotatedValue
forall a. HasCallStack => m a -> m a
f (m SomeAnnotatedValue -> m SomeAnnotatedValue)
-> m SomeAnnotatedValue -> m SomeAnnotatedValue
forall a b. (a -> b) -> a -> b
$ HasCallStack => Address -> m SomeAnnotatedValue
Address -> m SomeAnnotatedValue
cmiGetSomeStorage Address
addr
    , cmiGetBigMapValueMaybe :: forall k v.
(HasCallStack, NiceComparable k, NicePackedValue k,
 NiceUnpackedValue v) =>
BigMapId k v -> k -> m (Maybe v)
cmiGetBigMapValueMaybe = \BigMapId k v
bmId k
k -> m (Maybe v) -> m (Maybe v)
forall a. HasCallStack => m a -> m a
f (m (Maybe v) -> m (Maybe v)) -> m (Maybe v) -> m (Maybe v)
forall a b. (a -> b) -> a -> b
$ BigMapId k v -> k -> m (Maybe v)
forall k v.
(HasCallStack, NiceComparable k, NicePackedValue k,
 NiceUnpackedValue v) =>
BigMapId k v -> k -> m (Maybe v)
cmiGetBigMapValueMaybe BigMapId k v
bmId k
k
    , cmiGetAllBigMapValuesMaybe :: forall k v.
(HasCallStack, NiceComparable k, NiceUnpackedValue v) =>
BigMapId k v -> m (Maybe [v])
cmiGetAllBigMapValuesMaybe = \BigMapId k v
bmId -> m (Maybe [v]) -> m (Maybe [v])
forall a. HasCallStack => m a -> m a
f (m (Maybe [v]) -> m (Maybe [v])) -> m (Maybe [v]) -> m (Maybe [v])
forall a b. (a -> b) -> a -> b
$ BigMapId k v -> m (Maybe [v])
forall k v.
(HasCallStack, NiceComparable k, NiceUnpackedValue v) =>
BigMapId k v -> m (Maybe [v])
cmiGetAllBigMapValuesMaybe BigMapId k v
bmId
    , cmiGetPublicKey :: HasCallStack => Address -> m PublicKey
cmiGetPublicKey = \Address
addr -> m PublicKey -> m PublicKey
forall a. HasCallStack => m a -> m a
f (m PublicKey -> m PublicKey) -> m PublicKey -> m PublicKey
forall a b. (a -> b) -> a -> b
$ HasCallStack => Address -> m PublicKey
Address -> m PublicKey
cmiGetPublicKey Address
addr
    , cmiGetDelegate :: HasCallStack => Address -> m (Maybe KeyHash)
cmiGetDelegate = m (Maybe KeyHash) -> m (Maybe KeyHash)
forall a. HasCallStack => m a -> m a
f (m (Maybe KeyHash) -> m (Maybe KeyHash))
-> (Address -> m (Maybe KeyHash)) -> Address -> m (Maybe KeyHash)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HasCallStack => Address -> m (Maybe KeyHash)
Address -> m (Maybe KeyHash)
cmiGetDelegate
    , cmiRegisterDelegate :: HasCallStack => Address -> m ()
cmiRegisterDelegate = m () -> m ()
forall a. HasCallStack => m a -> m a
f (m () -> m ()) -> (Address -> m ()) -> Address -> m ()
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> HasCallStack => Address -> m ()
Address -> m ()
cmiRegisterDelegate
    , cmiGetChainId :: HasCallStack => m ChainId
cmiGetChainId = m ChainId -> m ChainId
forall a. HasCallStack => m a -> m a
f (m ChainId -> m ChainId) -> m ChainId -> m ChainId
forall a b. (a -> b) -> a -> b
$ m ChainId
HasCallStack => m ChainId
cmiGetChainId
    , cmiAdvanceTime :: forall (unit :: Rat).
(HasCallStack, KnownDivRat unit Second) =>
Time unit -> m ()
cmiAdvanceTime = \Time unit
time -> m () -> m ()
forall a. HasCallStack => m a -> m a
f (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$ Time unit -> m ()
forall (unit :: Rat).
(HasCallStack, KnownDivRat unit Second) =>
Time unit -> m ()
cmiAdvanceTime Time unit
time
    , cmiAdvanceToLevel :: HasCallStack => (Natural -> Natural) -> m ()
cmiAdvanceToLevel = \Natural -> Natural
level -> m () -> m ()
forall a. HasCallStack => m a -> m a
f (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$ HasCallStack => (Natural -> Natural) -> m ()
(Natural -> Natural) -> m ()
cmiAdvanceToLevel Natural -> Natural
level
    , cmiGetNow :: HasCallStack => m Timestamp
cmiGetNow = m Timestamp -> m Timestamp
forall a. HasCallStack => m a -> m a
f (m Timestamp -> m Timestamp) -> m Timestamp -> m Timestamp
forall a b. (a -> b) -> a -> b
$ m Timestamp
HasCallStack => m Timestamp
cmiGetNow
    , cmiGetLevel :: HasCallStack => m Natural
cmiGetLevel = m Natural -> m Natural
forall a. HasCallStack => m a -> m a
f (m Natural -> m Natural) -> m Natural -> m Natural
forall a b. (a -> b) -> a -> b
$ m Natural
HasCallStack => m Natural
cmiGetLevel
    , cmiFailure :: forall a. HasCallStack => Builder -> m a
cmiFailure = \Builder
builder -> m a -> m a
forall a. HasCallStack => m a -> m a
f (m a -> m a) -> m a -> m a
forall a b. (a -> b) -> a -> b
$ Builder -> m a
forall a. HasCallStack => Builder -> m a
cmiFailure Builder
builder
    , cmiGetApproximateBlockInterval :: HasCallStack => m (Time Second)
cmiGetApproximateBlockInterval = m (Time (1 :% 1)) -> m (Time (1 :% 1))
forall a. HasCallStack => m a -> m a
f (m (Time (1 :% 1)) -> m (Time (1 :% 1)))
-> m (Time (1 :% 1)) -> m (Time (1 :% 1))
forall a b. (a -> b) -> a -> b
$ m (Time (1 :% 1))
HasCallStack => m (Time Second)
cmiGetApproximateBlockInterval
    , cmiAttempt :: forall a e. (Exception e, HasCallStack) => m a -> m (Either e a)
cmiAttempt = \m a
action -> m a -> m (Either e a)
forall a e. (Exception e, HasCallStack) => m a -> m (Either e a)
cmiAttempt m a
action
    , cmiMarkAddressRefillable :: Address -> m ()
cmiMarkAddressRefillable = m () -> m ()
forall a. HasCallStack => m a -> m a
f (m () -> m ()) -> (Address -> m ()) -> Address -> m ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Address -> m ()
cmiMarkAddressRefillable
    , cmiThrow :: forall a. HasCallStack => SomeException -> m a
cmiThrow = forall a. HasCallStack => SomeException -> m a
cmiThrow
    , cmiEmulatedImpl :: m (Maybe (EmulatedImpl m))
cmiEmulatedImpl = m (Maybe (EmulatedImpl m)) -> m (Maybe (EmulatedImpl m))
forall a. HasCallStack => m a -> m a
f (m (Maybe (EmulatedImpl m)) -> m (Maybe (EmulatedImpl m)))
-> m (Maybe (EmulatedImpl m)) -> m (Maybe (EmulatedImpl m))
forall a b. (a -> b) -> a -> b
$ m (Maybe (EmulatedImpl m))
cmiEmulatedImpl
    , cmiRunCode :: forall cp st vd.
(HasCallStack, HasRPCRepr st, IsoValue (AsRPC st)) =>
Sender -> RunCode cp st vd -> m (AsRPC st)
cmiRunCode = m (AsRPC st) -> m (AsRPC st)
forall a. HasCallStack => m a -> m a
f (m (AsRPC st) -> m (AsRPC st))
-> (Sender -> RunCode cp st vd -> m (AsRPC st))
-> Sender
-> RunCode cp st vd
-> m (AsRPC st)
forall a b c. SuperComposition a b c => a -> b -> c
... Sender -> RunCode cp st vd -> m (AsRPC st)
forall cp st vd.
(HasCallStack, HasRPCRepr st, IsoValue (AsRPC st)) =>
Sender -> RunCode cp st vd -> m (AsRPC st)
cmiRunCode
    }

-- | A record with all the capabilities available to any cleveland test.
data ClevelandCaps m = ClevelandCaps
  { ClevelandCaps m -> Sender
ccSender :: Sender
  , ClevelandCaps m -> Moneybag
ccMoneybag :: Moneybag
  , ClevelandCaps m -> ClevelandMiscImpl m
ccMiscCap :: ClevelandMiscImpl m
  , ClevelandCaps m -> Sender -> ClevelandOpsImpl m
ccOpsCap :: Sender -> ClevelandOpsImpl m
  }

-- | A record with all the capabilities available to a cleveland test on the emulator.
data EmulatedCaps m = EmulatedCaps
  { EmulatedCaps m -> EmulatedImpl m
ecEmulatedCap :: EmulatedImpl m
  , EmulatedCaps m -> ClevelandCaps m
ecClevelandCaps :: ClevelandCaps m
  }

makeLensesFor [("ccSender", "ccSenderL"), ("ccMoneybag", "ccMoneybagL")] ''ClevelandCaps
makeLensesFor [("ecClevelandCaps", "ecClevelandCapsL")] ''EmulatedCaps

-- | A proof that the given @caps@ record contains
-- the basic cleveland capabilities.
class Monad (ClevelandBaseMonad caps) => HasClevelandCaps caps where
  -- | This will be either @PureM@ or @ClientM@.
  type ClevelandBaseMonad caps :: Type -> Type
  clevelandCapsL :: Lens' caps (ClevelandCaps (ClevelandBaseMonad caps))

-- | A proof that the given @caps@ record contains
-- the basic cleveland capabilities + the emulator capabiilities.
class HasClevelandCaps caps => HasEmulatedCaps caps where
  getEmulatedCap :: caps -> EmulatedImpl (ClevelandBaseMonad caps)

instance Monad m => HasClevelandCaps (ClevelandCaps m) where
  type ClevelandBaseMonad (ClevelandCaps m) = m
  clevelandCapsL :: (ClevelandCaps (ClevelandBaseMonad (ClevelandCaps m))
 -> f (ClevelandCaps (ClevelandBaseMonad (ClevelandCaps m))))
-> ClevelandCaps m -> f (ClevelandCaps m)
clevelandCapsL = (ClevelandCaps (ClevelandBaseMonad (ClevelandCaps m))
 -> f (ClevelandCaps (ClevelandBaseMonad (ClevelandCaps m))))
-> ClevelandCaps m -> f (ClevelandCaps m)
forall a. a -> a
id

instance Monad m => HasClevelandCaps (EmulatedCaps m) where
  type ClevelandBaseMonad (EmulatedCaps m) = m
  clevelandCapsL :: (ClevelandCaps (ClevelandBaseMonad (EmulatedCaps m))
 -> f (ClevelandCaps (ClevelandBaseMonad (EmulatedCaps m))))
-> EmulatedCaps m -> f (EmulatedCaps m)
clevelandCapsL = (ClevelandCaps (ClevelandBaseMonad (EmulatedCaps m))
 -> f (ClevelandCaps (ClevelandBaseMonad (EmulatedCaps m))))
-> EmulatedCaps m -> f (EmulatedCaps m)
forall (m :: * -> *). Lens' (EmulatedCaps m) (ClevelandCaps m)
ecClevelandCapsL

senderL :: HasClevelandCaps caps => Lens' caps Sender
senderL :: Lens' caps Sender
senderL = (ClevelandCaps (ClevelandBaseMonad caps)
 -> f (ClevelandCaps (ClevelandBaseMonad caps)))
-> caps -> f caps
forall caps.
HasClevelandCaps caps =>
Lens' caps (ClevelandCaps (ClevelandBaseMonad caps))
clevelandCapsL ((ClevelandCaps (ClevelandBaseMonad caps)
  -> f (ClevelandCaps (ClevelandBaseMonad caps)))
 -> caps -> f caps)
-> ((Sender -> f Sender)
    -> ClevelandCaps (ClevelandBaseMonad caps)
    -> f (ClevelandCaps (ClevelandBaseMonad caps)))
-> (Sender -> f Sender)
-> caps
-> f caps
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Sender -> f Sender)
-> ClevelandCaps (ClevelandBaseMonad caps)
-> f (ClevelandCaps (ClevelandBaseMonad caps))
forall (m :: * -> *). Lens' (ClevelandCaps m) Sender
ccSenderL

moneybagL :: HasClevelandCaps caps => Lens' caps Moneybag
moneybagL :: Lens' caps Moneybag
moneybagL = (ClevelandCaps (ClevelandBaseMonad caps)
 -> f (ClevelandCaps (ClevelandBaseMonad caps)))
-> caps -> f caps
forall caps.
HasClevelandCaps caps =>
Lens' caps (ClevelandCaps (ClevelandBaseMonad caps))
clevelandCapsL ((ClevelandCaps (ClevelandBaseMonad caps)
  -> f (ClevelandCaps (ClevelandBaseMonad caps)))
 -> caps -> f caps)
-> ((Moneybag -> f Moneybag)
    -> ClevelandCaps (ClevelandBaseMonad caps)
    -> f (ClevelandCaps (ClevelandBaseMonad caps)))
-> (Moneybag -> f Moneybag)
-> caps
-> f caps
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Moneybag -> f Moneybag)
-> ClevelandCaps (ClevelandBaseMonad caps)
-> f (ClevelandCaps (ClevelandBaseMonad caps))
forall (m :: * -> *). Lens' (ClevelandCaps m) Moneybag
ccMoneybagL

getMiscCap :: HasClevelandCaps caps => caps -> ClevelandMiscImpl (ClevelandBaseMonad caps)
getMiscCap :: caps -> ClevelandMiscImpl (ClevelandBaseMonad caps)
getMiscCap = ClevelandCaps (ClevelandBaseMonad caps)
-> ClevelandMiscImpl (ClevelandBaseMonad caps)
forall (m :: * -> *). ClevelandCaps m -> ClevelandMiscImpl m
ccMiscCap (ClevelandCaps (ClevelandBaseMonad caps)
 -> ClevelandMiscImpl (ClevelandBaseMonad caps))
-> (caps -> ClevelandCaps (ClevelandBaseMonad caps))
-> caps
-> ClevelandMiscImpl (ClevelandBaseMonad caps)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Getting
  (ClevelandCaps (ClevelandBaseMonad caps))
  caps
  (ClevelandCaps (ClevelandBaseMonad caps))
-> caps -> ClevelandCaps (ClevelandBaseMonad caps)
forall s (m :: * -> *) a. MonadReader s m => Getting a s a -> m a
view Getting
  (ClevelandCaps (ClevelandBaseMonad caps))
  caps
  (ClevelandCaps (ClevelandBaseMonad caps))
forall caps.
HasClevelandCaps caps =>
Lens' caps (ClevelandCaps (ClevelandBaseMonad caps))
clevelandCapsL

getOpsCap :: HasClevelandCaps caps => caps -> ClevelandOpsImpl (ClevelandBaseMonad caps)
getOpsCap :: caps -> ClevelandOpsImpl (ClevelandBaseMonad caps)
getOpsCap caps
r = ClevelandCaps (ClevelandBaseMonad caps)
-> Sender -> ClevelandOpsImpl (ClevelandBaseMonad caps)
forall (m :: * -> *).
ClevelandCaps m -> Sender -> ClevelandOpsImpl m
ccOpsCap (caps
r caps
-> Getting
     (ClevelandCaps (ClevelandBaseMonad caps))
     caps
     (ClevelandCaps (ClevelandBaseMonad caps))
-> ClevelandCaps (ClevelandBaseMonad caps)
forall s a. s -> Getting a s a -> a
^. Getting
  (ClevelandCaps (ClevelandBaseMonad caps))
  caps
  (ClevelandCaps (ClevelandBaseMonad caps))
forall caps.
HasClevelandCaps caps =>
Lens' caps (ClevelandCaps (ClevelandBaseMonad caps))
clevelandCapsL) (caps
r caps -> Getting Sender caps Sender -> Sender
forall s a. s -> Getting a s a -> a
^. Getting Sender caps Sender
forall caps. HasClevelandCaps caps => Lens' caps Sender
senderL)

instance Monad m => HasEmulatedCaps (EmulatedCaps m) where
  getEmulatedCap :: EmulatedCaps m
-> EmulatedImpl (ClevelandBaseMonad (EmulatedCaps m))
getEmulatedCap = EmulatedCaps m
-> EmulatedImpl (ClevelandBaseMonad (EmulatedCaps m))
forall (m :: * -> *). EmulatedCaps m -> EmulatedImpl m
ecEmulatedCap

-- | Constraint for a monad in which we can do cleveland actions.
type MonadCleveland caps m =
  ( m ~ ReaderT caps (ClevelandBaseMonad caps)
  , HasClevelandCaps caps
  )

-- | Constraint for a monad in which we can do cleveland actions that can't be run on a real network.
-- It requires the 'EmulatedImpl' capability.
type MonadEmulated caps m =
  ( MonadCleveland caps m
  , HasEmulatedCaps caps
  )

-- | Monad transformer that adds only the 'ClevelandCaps' capabilities.
type ClevelandT m = ReaderT (ClevelandCaps m) m

-- | Monad transformer that adds both 'ClevelandCaps' and 'EmulatedCaps' capabilities.
type EmulatedT m = ReaderT (EmulatedCaps m) m