-- SPDX-FileCopyrightText: 2020 Tocqueville Group
--
-- SPDX-License-Identifier: LicenseRef-MIT-TQ

-- | Executor and typechecker of a contract in Morley language.

module Michelson.Runtime
  (
    -- * High level interface for end user
    originateContract
  , runContract
  , transfer

  -- * Other helpers
  , parseContract
  , parseExpandContract
  , readAndParseContract
  , prepareContract

  -- * Re-exports
  , ContractState (..)
  , AddressState (..)
  , TxData (..)
  , TxParam (..)

  -- * For testing
  , ExecutorOp (..)
  , ExecutorRes (..)
  , ExecutorError' (..)
  , ExecutorError
  , ExecutorM
  , runExecutorM
  , runExecutorMWithDB
  , executeGlobalOperations
  , executeGlobalOrigination
  , executeOrigination
  , executeTransfer

  -- * To avoid warnings (can't generate lenses only for some fields)
  , erInterpretResults
  , erUpdates
  , erGState
  , erRemainingSteps
  , elInterpreterResults
  , elUpdates
  ) where

import Control.Lens (assign, at, makeLenses, (+=), (.=), (<>=))
import Control.Monad.Except (Except, liftEither, runExcept, throwError)
import Data.Binary.Put (putWord64be, runPut)
import qualified Data.ByteString.Lazy as BSL
import Data.Semigroup.Generic
import Data.Text.IO (getContents)
import qualified Data.Text.IO.Utf8 as Utf8 (readFile)
import Fmt (Buildable(build), blockListF, fmt, fmtLn, nameF, pretty, (+|), (|+))
import Named ((:!), (:?), arg, argDef, defaults, (!))
import Text.Megaparsec (parse)

import Data.Singletons (demote)
import Data.Typeable (gcast)
import Michelson.Interpret
  (ContractEnv(..), InterpretError(..), InterpretResult(..), InterpreterState(..), MorleyLogs(..),
  RemainingSteps(..), handleContractReturn, interpret)
import qualified Michelson.Interpret.Pack as Pack
import Michelson.Macro (ParsedOp, expandContract)
import qualified Michelson.Parser as P
import Michelson.Runtime.GState
import Michelson.Runtime.TxData
import Michelson.TypeCheck
  (SomeContractAndStorage(..), TCError, typeCheckContractAndStorage, typeVerifyParameter)
import Michelson.Typed
  (CreateContract(..), EntrypointCallT, EpAddress(..), EpName, Operation'(..), ParameterScope,
  SomeValue'(..), TransferTokens(..), starNotes, starParamNotes, untypeValue)
import qualified Michelson.Typed as T
import Michelson.Typed.Origination (OriginationOperation(..), mkOriginationOperationHash)
import Michelson.Untyped (Contract, OperationHash(..))
import qualified Michelson.Untyped as U
import Tezos.Address (Address(..), OriginationIndex(..), mkContractAddress)
import Tezos.Core
  (Mutez, Timestamp(..), getCurrentTime, toMutez, unMutez, unsafeAddMutez, unsafeSubMutez)
import Tezos.Crypto (KeyHash, blake2b, parseKeyHash)
import Util.Named ((.!))

----------------------------------------------------------------------------
-- Auxiliary types
----------------------------------------------------------------------------

-- | Operations executed by interpreter.
-- In our model one Michelson's operation (`operation` type in Michelson)
-- corresponds to 0 or 1 interpreter operation.
--
-- Note: 'Address' is not part of 'TxData', because 'TxData' is
-- supposed to be provided by the user, while 'Address' can be
-- computed by our code.
data ExecutorOp
  = OriginateOp OriginationOperation
  -- ^ Originate a contract.
  | TransferOp Address TxData
  -- ^ Send a transaction to given address which is assumed to be the
  -- address of an originated contract.
  deriving stock (Int -> ExecutorOp -> ShowS
[ExecutorOp] -> ShowS
ExecutorOp -> String
(Int -> ExecutorOp -> ShowS)
-> (ExecutorOp -> String)
-> ([ExecutorOp] -> ShowS)
-> Show ExecutorOp
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [ExecutorOp] -> ShowS
$cshowList :: [ExecutorOp] -> ShowS
show :: ExecutorOp -> String
$cshow :: ExecutorOp -> String
showsPrec :: Int -> ExecutorOp -> ShowS
$cshowsPrec :: Int -> ExecutorOp -> ShowS
Show)

-- | Result of a single execution of interpreter.
data ExecutorRes = ExecutorRes
  { ExecutorRes -> GState
_erGState :: GState
  -- ^ New 'GState'.
  , ExecutorRes -> [GStateUpdate]
_erUpdates :: [GStateUpdate]
  -- ^ Updates applied to 'GState'.
  , ExecutorRes -> [(Address, InterpretResult)]
_erInterpretResults :: [(Address, InterpretResult)]
  -- ^ During execution a contract can print logs and in the end it returns
  -- a pair. All logs and returned values are kept until all called contracts
  -- are executed. In the end they are printed.
  , ExecutorRes -> RemainingSteps
_erRemainingSteps :: RemainingSteps
  -- ^ Now much gas all remaining executions can consume.
  } deriving stock (Int -> ExecutorRes -> ShowS
[ExecutorRes] -> ShowS
ExecutorRes -> String
(Int -> ExecutorRes -> ShowS)
-> (ExecutorRes -> String)
-> ([ExecutorRes] -> ShowS)
-> Show ExecutorRes
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [ExecutorRes] -> ShowS
$cshowList :: [ExecutorRes] -> ShowS
show :: ExecutorRes -> String
$cshow :: ExecutorRes -> String
showsPrec :: Int -> ExecutorRes -> ShowS
$cshowsPrec :: Int -> ExecutorRes -> ShowS
Show)

data ExecutorEnv = ExecutorEnv
  { ExecutorEnv -> Timestamp
_eeNow :: Timestamp
  , ExecutorEnv -> Natural
_eeLevel :: Natural
  }
  deriving stock (Int -> ExecutorEnv -> ShowS
[ExecutorEnv] -> ShowS
ExecutorEnv -> String
(Int -> ExecutorEnv -> ShowS)
-> (ExecutorEnv -> String)
-> ([ExecutorEnv] -> ShowS)
-> Show ExecutorEnv
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [ExecutorEnv] -> ShowS
$cshowList :: [ExecutorEnv] -> ShowS
show :: ExecutorEnv -> String
$cshow :: ExecutorEnv -> String
showsPrec :: Int -> ExecutorEnv -> ShowS
$cshowsPrec :: Int -> ExecutorEnv -> ShowS
Show, (forall x. ExecutorEnv -> Rep ExecutorEnv x)
-> (forall x. Rep ExecutorEnv x -> ExecutorEnv)
-> Generic ExecutorEnv
forall x. Rep ExecutorEnv x -> ExecutorEnv
forall x. ExecutorEnv -> Rep ExecutorEnv x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cto :: forall x. Rep ExecutorEnv x -> ExecutorEnv
$cfrom :: forall x. ExecutorEnv -> Rep ExecutorEnv x
Generic)

data ExecutorState = ExecutorState
  { ExecutorState -> GState
_esGState :: GState
  , ExecutorState -> RemainingSteps
_esRemainingSteps :: RemainingSteps
  , ExecutorState -> Int32
_esOriginationNonce :: Int32
  , ExecutorState -> Maybe Address
_esSourceAddress :: Maybe Address
  , ExecutorState -> ExecutorLog
_esLog :: ExecutorLog
  , ExecutorState -> OperationHash
_esOperationHash :: ~OperationHash
  }
  deriving stock (Int -> ExecutorState -> ShowS
[ExecutorState] -> ShowS
ExecutorState -> String
(Int -> ExecutorState -> ShowS)
-> (ExecutorState -> String)
-> ([ExecutorState] -> ShowS)
-> Show ExecutorState
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [ExecutorState] -> ShowS
$cshowList :: [ExecutorState] -> ShowS
show :: ExecutorState -> String
$cshow :: ExecutorState -> String
showsPrec :: Int -> ExecutorState -> ShowS
$cshowsPrec :: Int -> ExecutorState -> ShowS
Show, (forall x. ExecutorState -> Rep ExecutorState x)
-> (forall x. Rep ExecutorState x -> ExecutorState)
-> Generic ExecutorState
forall x. Rep ExecutorState x -> ExecutorState
forall x. ExecutorState -> Rep ExecutorState x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cto :: forall x. Rep ExecutorState x -> ExecutorState
$cfrom :: forall x. ExecutorState -> Rep ExecutorState x
Generic)

data ExecutorLog = ExecutorLog
  { ExecutorLog -> [GStateUpdate]
_elUpdates :: [GStateUpdate]
  , ExecutorLog -> [(Address, InterpretResult)]
_elInterpreterResults :: [(Address, InterpretResult)]
  }
  deriving stock (Int -> ExecutorLog -> ShowS
[ExecutorLog] -> ShowS
ExecutorLog -> String
(Int -> ExecutorLog -> ShowS)
-> (ExecutorLog -> String)
-> ([ExecutorLog] -> ShowS)
-> Show ExecutorLog
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [ExecutorLog] -> ShowS
$cshowList :: [ExecutorLog] -> ShowS
show :: ExecutorLog -> String
$cshow :: ExecutorLog -> String
showsPrec :: Int -> ExecutorLog -> ShowS
$cshowsPrec :: Int -> ExecutorLog -> ShowS
Show, (forall x. ExecutorLog -> Rep ExecutorLog x)
-> (forall x. Rep ExecutorLog x -> ExecutorLog)
-> Generic ExecutorLog
forall x. Rep ExecutorLog x -> ExecutorLog
forall x. ExecutorLog -> Rep ExecutorLog x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cto :: forall x. Rep ExecutorLog x -> ExecutorLog
$cfrom :: forall x. ExecutorLog -> Rep ExecutorLog x
Generic)
  deriving (b -> ExecutorLog -> ExecutorLog
NonEmpty ExecutorLog -> ExecutorLog
ExecutorLog -> ExecutorLog -> ExecutorLog
(ExecutorLog -> ExecutorLog -> ExecutorLog)
-> (NonEmpty ExecutorLog -> ExecutorLog)
-> (forall b. Integral b => b -> ExecutorLog -> ExecutorLog)
-> Semigroup ExecutorLog
forall b. Integral b => b -> ExecutorLog -> ExecutorLog
forall a.
(a -> a -> a)
-> (NonEmpty a -> a)
-> (forall b. Integral b => b -> a -> a)
-> Semigroup a
stimes :: b -> ExecutorLog -> ExecutorLog
$cstimes :: forall b. Integral b => b -> ExecutorLog -> ExecutorLog
sconcat :: NonEmpty ExecutorLog -> ExecutorLog
$csconcat :: NonEmpty ExecutorLog -> ExecutorLog
<> :: ExecutorLog -> ExecutorLog -> ExecutorLog
$c<> :: ExecutorLog -> ExecutorLog -> ExecutorLog
Semigroup, Semigroup ExecutorLog
ExecutorLog
Semigroup ExecutorLog =>
ExecutorLog
-> (ExecutorLog -> ExecutorLog -> ExecutorLog)
-> ([ExecutorLog] -> ExecutorLog)
-> Monoid ExecutorLog
[ExecutorLog] -> ExecutorLog
ExecutorLog -> ExecutorLog -> ExecutorLog
forall a.
Semigroup a =>
a -> (a -> a -> a) -> ([a] -> a) -> Monoid a
mconcat :: [ExecutorLog] -> ExecutorLog
$cmconcat :: [ExecutorLog] -> ExecutorLog
mappend :: ExecutorLog -> ExecutorLog -> ExecutorLog
$cmappend :: ExecutorLog -> ExecutorLog -> ExecutorLog
mempty :: ExecutorLog
$cmempty :: ExecutorLog
$cp1Monoid :: Semigroup ExecutorLog
Monoid) via GenericSemigroupMonoid ExecutorLog

makeLenses ''ExecutorRes
makeLenses ''ExecutorEnv
makeLenses ''ExecutorState
makeLenses ''ExecutorLog

-- | Errors that can happen during contract interpreting.
-- Type parameter @a@ determines how contracts will be represented
-- in these errors, e.g. 'Address'.
data ExecutorError' a
  = EEUnknownContract a
  -- ^ The interpreted contract hasn't been originated.
  | EEInterpreterFailed a
                        InterpretError
  -- ^ Interpretation of Michelson contract failed.
  | EEAlreadyOriginated a
                        ContractState
  -- ^ A contract is already originated.
  | EEUnknownSender a
  -- ^ Sender address is unknown.
  | EEUnknownManager a
  -- ^ Manager address is unknown.
  | EENotEnoughFunds a Mutez
  -- ^ Sender doesn't have enough funds.
  | EEZeroTransaction a
  -- ^ Sending 0tz towards an address.
  | EEFailedToApplyUpdates GStateUpdateError
  -- ^ Failed to apply updates to GState.
  | EEIllTypedParameter TCError
  -- ^ Contract parameter is ill-typed.
  | EEUnexpectedParameterType T.T T.T
  -- ^ Contract parameter is well-typed, but its type does
  -- not match the entrypoint's type.
  | EEUnknownEntrypoint EpName
  -- ^ Specified entrypoint to run is not found.
  | EETransactionFromContract a Mutez
  -- ^ A transaction from an originated contract was attempted as a global operation.
  deriving stock (Int -> ExecutorError' a -> ShowS
[ExecutorError' a] -> ShowS
ExecutorError' a -> String
(Int -> ExecutorError' a -> ShowS)
-> (ExecutorError' a -> String)
-> ([ExecutorError' a] -> ShowS)
-> Show (ExecutorError' a)
forall a. Show a => Int -> ExecutorError' a -> ShowS
forall a. Show a => [ExecutorError' a] -> ShowS
forall a. Show a => ExecutorError' a -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [ExecutorError' a] -> ShowS
$cshowList :: forall a. Show a => [ExecutorError' a] -> ShowS
show :: ExecutorError' a -> String
$cshow :: forall a. Show a => ExecutorError' a -> String
showsPrec :: Int -> ExecutorError' a -> ShowS
$cshowsPrec :: forall a. Show a => Int -> ExecutorError' a -> ShowS
Show, a -> ExecutorError' b -> ExecutorError' a
(a -> b) -> ExecutorError' a -> ExecutorError' b
(forall a b. (a -> b) -> ExecutorError' a -> ExecutorError' b)
-> (forall a b. a -> ExecutorError' b -> ExecutorError' a)
-> Functor ExecutorError'
forall a b. a -> ExecutorError' b -> ExecutorError' a
forall a b. (a -> b) -> ExecutorError' a -> ExecutorError' b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
<$ :: a -> ExecutorError' b -> ExecutorError' a
$c<$ :: forall a b. a -> ExecutorError' b -> ExecutorError' a
fmap :: (a -> b) -> ExecutorError' a -> ExecutorError' b
$cfmap :: forall a b. (a -> b) -> ExecutorError' a -> ExecutorError' b
Functor)

instance (Buildable a) => Buildable (ExecutorError' a) where
  build :: ExecutorError' a -> Builder
build =
    \case
      EEUnknownContract addr :: a
addr -> "The contract is not originated " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| a
addr a -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ ""
      EEInterpreterFailed addr :: a
addr err :: InterpretError
err ->
        "Michelson interpreter failed for contract " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| a
addr a -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ ": " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| InterpretError
err InterpretError -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ ""
      EEAlreadyOriginated addr :: a
addr cs :: ContractState
cs ->
        "The following contract is already originated: " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| a
addr a -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+
        ", " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| ContractState
cs ContractState -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ ""
      EEUnknownSender addr :: a
addr -> "The sender address is unknown " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| a
addr a -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ ""
      EEUnknownManager addr :: a
addr -> "The manager address is unknown " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| a
addr a -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ ""
      EENotEnoughFunds addr :: a
addr amount :: Mutez
amount ->
        "The sender (" Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| a
addr a -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+
        ") doesn't have enough funds (has only " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| Mutez
amount Mutez -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ ")"
      EEZeroTransaction addr :: a
addr ->
        "Transaction of 0ꜩ towards a key address " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| a
addr a -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ " which has no code is prohibited"
      EEFailedToApplyUpdates err :: GStateUpdateError
err -> "Failed to update GState: " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| GStateUpdateError
err GStateUpdateError -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ ""
      EEIllTypedParameter err :: TCError
err -> "The contract parameter is ill-typed: " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| TCError
err TCError -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ ""
      EEUnexpectedParameterType expectedT :: T
expectedT actualT :: T
actualT ->
        "The contract parameter is well-typed, but did not match the contract's entrypoint's type.\n" Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<>
        "Expected: " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| T
expectedT T -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ "\n" Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<>
        "Got: " Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| T
actualT T -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ ""
      EEUnknownEntrypoint epName :: EpName
epName -> "The contract does not contain entrypoint '" Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| EpName
epName EpName -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ "'"
      EETransactionFromContract addr :: a
addr amount :: Mutez
amount ->
        "Global transaction of funds (" Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| Mutez
amount Mutez -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ ") from an originated contract (" Builder -> Builder -> Builder
forall b. FromBuilder b => Builder -> Builder -> b
+| a
addr a -> Builder -> Builder
forall a b. (Buildable a, FromBuilder b) => a -> Builder -> b
|+ ") is prohibited."

type ExecutorError = ExecutorError' Address

instance (Typeable a, Show a, Buildable a) => Exception (ExecutorError' a) where
  displayException :: ExecutorError' a -> String
displayException = ExecutorError' a -> String
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty

----------------------------------------------------------------------------
-- Interface
----------------------------------------------------------------------------

-- | Parse a contract from 'Text'.
parseContract ::
     Maybe FilePath -> Text -> Either P.ParserException (U.Contract' ParsedOp)
parseContract :: Maybe String -> Text -> Either ParserException (Contract' ParsedOp)
parseContract mFileName :: Maybe String
mFileName =
  (ParseErrorBundle Text CustomParserException -> ParserException)
-> Either
     (ParseErrorBundle Text CustomParserException) (Contract' ParsedOp)
-> Either ParserException (Contract' ParsedOp)
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first ParseErrorBundle Text CustomParserException -> ParserException
P.ParserException (Either
   (ParseErrorBundle Text CustomParserException) (Contract' ParsedOp)
 -> Either ParserException (Contract' ParsedOp))
-> (Text
    -> Either
         (ParseErrorBundle Text CustomParserException) (Contract' ParsedOp))
-> Text
-> Either ParserException (Contract' ParsedOp)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Parsec CustomParserException Text (Contract' ParsedOp)
-> String
-> Text
-> Either
     (ParseErrorBundle Text CustomParserException) (Contract' ParsedOp)
forall e s a.
Parsec e s a -> String -> s -> Either (ParseErrorBundle s e) a
parse Parsec CustomParserException Text (Contract' ParsedOp)
P.program (String -> Maybe String -> String
forall a. a -> Maybe a -> a
fromMaybe "<stdin>" Maybe String
mFileName)

-- | Parse a contract from 'Text' and expand macros.
parseExpandContract ::
     Maybe FilePath -> Text -> Either P.ParserException Contract
parseExpandContract :: Maybe String -> Text -> Either ParserException Contract
parseExpandContract mFileName :: Maybe String
mFileName = (Contract' ParsedOp -> Contract)
-> Either ParserException (Contract' ParsedOp)
-> Either ParserException Contract
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Contract' ParsedOp -> Contract
expandContract (Either ParserException (Contract' ParsedOp)
 -> Either ParserException Contract)
-> (Text -> Either ParserException (Contract' ParsedOp))
-> Text
-> Either ParserException Contract
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe String -> Text -> Either ParserException (Contract' ParsedOp)
parseContract Maybe String
mFileName

-- | Read and parse a contract from give path or `stdin` (if the
-- argument is 'Nothing'). The contract is not expanded.
readAndParseContract :: Maybe FilePath -> IO (U.Contract' ParsedOp)
readAndParseContract :: Maybe String -> IO (Contract' ParsedOp)
readAndParseContract mFilename :: Maybe String
mFilename = do
  Text
code <- Maybe String -> IO Text
readCode Maybe String
mFilename
  (ParserException -> IO (Contract' ParsedOp))
-> (Contract' ParsedOp -> IO (Contract' ParsedOp))
-> Either ParserException (Contract' ParsedOp)
-> IO (Contract' ParsedOp)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either ParserException -> IO (Contract' ParsedOp)
forall (m :: * -> *) e a. (MonadThrow m, Exception e) => e -> m a
throwM Contract' ParsedOp -> IO (Contract' ParsedOp)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either ParserException (Contract' ParsedOp)
 -> IO (Contract' ParsedOp))
-> Either ParserException (Contract' ParsedOp)
-> IO (Contract' ParsedOp)
forall a b. (a -> b) -> a -> b
$ Maybe String -> Text -> Either ParserException (Contract' ParsedOp)
parseContract Maybe String
mFilename Text
code
  where
    readCode :: Maybe FilePath -> IO Text
    readCode :: Maybe String -> IO Text
readCode = IO Text -> (String -> IO Text) -> Maybe String -> IO Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe IO Text
getContents String -> IO Text
forall (m :: * -> *). MonadIO m => String -> m Text
Utf8.readFile

-- | Read a contract using 'readAndParseContract', expand and
-- flatten. The contract is not type checked.
prepareContract :: Maybe FilePath -> IO Contract
prepareContract :: Maybe String -> IO Contract
prepareContract mFile :: Maybe String
mFile = Contract' ParsedOp -> Contract
expandContract (Contract' ParsedOp -> Contract)
-> IO (Contract' ParsedOp) -> IO Contract
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe String -> IO (Contract' ParsedOp)
readAndParseContract Maybe String
mFile

-- | Originate a contract. Returns the address of the originated
-- contract.
originateContract
  :: FilePath
  -> Address
  -> Maybe KeyHash
  -> Mutez
  -> U.Value
  -> U.Contract
  -> "verbose" :! Bool
  -> IO Address
originateContract :: String
-> Address
-> Maybe KeyHash
-> Mutez
-> Value
-> Contract
-> ("verbose" :! Bool)
-> IO Address
originateContract dbPath :: String
dbPath originator :: Address
originator delegate :: Maybe KeyHash
delegate balance :: Mutez
balance uStorage :: Value
uStorage uContract :: Contract
uContract verbose :: "verbose" :! Bool
verbose = do
  OriginationOperation
origination <- (TCError -> IO OriginationOperation)
-> (OriginationOperation -> IO OriginationOperation)
-> Either TCError OriginationOperation
-> IO OriginationOperation
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either TCError -> IO OriginationOperation
forall (m :: * -> *) e a. (MonadThrow m, Exception e) => e -> m a
throwM OriginationOperation -> IO OriginationOperation
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either TCError OriginationOperation -> IO OriginationOperation)
-> Either TCError OriginationOperation -> IO OriginationOperation
forall a b. (a -> b) -> a -> b
$
    SomeContractAndStorage -> OriginationOperation
mkOrigination (SomeContractAndStorage -> OriginationOperation)
-> Either TCError SomeContractAndStorage
-> Either TCError OriginationOperation
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Contract -> Value -> Either TCError SomeContractAndStorage
typeCheckContractAndStorage Contract
uContract Value
uStorage
  -- pass 100500 as maxSteps, because it doesn't matter for origination,
  -- as well as 'now'
  ((ExecutorRes, Address) -> Address)
-> IO (ExecutorRes, Address) -> IO Address
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (ExecutorRes, Address) -> Address
forall a b. (a, b) -> b
snd (IO (ExecutorRes, Address) -> IO Address)
-> IO (ExecutorRes, Address) -> IO Address
forall a b. (a -> b) -> a -> b
$ Maybe Timestamp
-> Maybe Natural
-> String
-> RemainingSteps
-> ("verbose" :! Bool)
-> ("dryRun" :? Bool)
-> ExecutorM Address
-> IO (ExecutorRes, Address)
forall a.
Maybe Timestamp
-> Maybe Natural
-> String
-> RemainingSteps
-> ("verbose" :! Bool)
-> ("dryRun" :? Bool)
-> ExecutorM a
-> IO (ExecutorRes, a)
runExecutorMWithDB Maybe Timestamp
forall a. Maybe a
Nothing Maybe Natural
forall a. Maybe a
Nothing String
dbPath 100500 "verbose" :! Bool
verbose (("dryRun" :? Bool)
 -> ExecutorM Address -> IO (ExecutorRes, Address))
-> Param Defaults -> ExecutorM Address -> IO (ExecutorRes, Address)
forall p fn fn'. WithParam p fn fn' => fn -> Param p -> fn'
! Param Defaults
defaults (ExecutorM Address -> IO (ExecutorRes, Address))
-> ExecutorM Address -> IO (ExecutorRes, Address)
forall a b. (a -> b) -> a -> b
$ do
    OriginationOperation -> ExecutorM Address
executeGlobalOrigination OriginationOperation
origination
  where
    mkOrigination :: SomeContractAndStorage -> OriginationOperation
mkOrigination (SomeContractAndStorage contract :: Contract cp st
contract storage :: Value st
storage) = $WOriginationOperation :: forall (cp :: T) (st :: T).
(StorageScope st, ParameterScope cp) =>
Address
-> Maybe KeyHash
-> Mutez
-> Value st
-> Contract cp st
-> OriginationOperation
OriginationOperation
      { ooOriginator :: Address
ooOriginator = Address
originator
      , ooDelegate :: Maybe KeyHash
ooDelegate = Maybe KeyHash
delegate
      , ooBalance :: Mutez
ooBalance = Mutez
balance
      , ooStorage :: Value st
ooStorage = Value st
storage
      , ooContract :: Contract cp st
ooContract = Contract cp st
contract
      }

-- | Run a contract. The contract is originated first (if it's not
-- already) and then we pretend that we send a transaction to it.
runContract
  :: Maybe Timestamp
  -> Maybe Natural
  -> Word64
  -> Mutez
  -> FilePath
  -> U.Value
  -> U.Contract
  -> TxData
  -> "verbose" :! Bool
  -> "dryRun" :! Bool
  -> IO U.Value
runContract :: Maybe Timestamp
-> Maybe Natural
-> Word64
-> Mutez
-> String
-> Value
-> Contract
-> TxData
-> ("verbose" :! Bool)
-> ("dryRun" :! Bool)
-> IO Value
runContract maybeNow :: Maybe Timestamp
maybeNow maybeLevel :: Maybe Natural
maybeLevel maxSteps :: Word64
maxSteps initBalance :: Mutez
initBalance dbPath :: String
dbPath uStorage :: Value
uStorage uContract :: Contract
uContract txData :: TxData
txData
  verbose :: "verbose" :! Bool
verbose (Name "dryRun" -> ("dryRun" :! Bool) -> Bool
forall (name :: Symbol) a. Name name -> (name :! a) -> a
arg IsLabel "dryRun" (Name "dryRun")
Name "dryRun"
#dryRun -> Bool
dryRun) = do
  OriginationOperation
origination <- (TCError -> IO OriginationOperation)
-> (OriginationOperation -> IO OriginationOperation)
-> Either TCError OriginationOperation
-> IO OriginationOperation
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either TCError -> IO OriginationOperation
forall (m :: * -> *) e a. (MonadThrow m, Exception e) => e -> m a
throwM OriginationOperation -> IO OriginationOperation
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either TCError OriginationOperation -> IO OriginationOperation)
-> Either TCError OriginationOperation -> IO OriginationOperation
forall a b. (a -> b) -> a -> b
$
    SomeContractAndStorage -> OriginationOperation
mkOrigination (SomeContractAndStorage -> OriginationOperation)
-> Either TCError SomeContractAndStorage
-> Either TCError OriginationOperation
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Contract -> Value -> Either TCError SomeContractAndStorage
typeCheckContractAndStorage Contract
uContract Value
uStorage
  (_, newSt :: Value
newSt) <- Maybe Timestamp
-> Maybe Natural
-> String
-> RemainingSteps
-> ("verbose" :! Bool)
-> ("dryRun" :? Bool)
-> ExecutorM Value
-> IO (ExecutorRes, Value)
forall a.
Maybe Timestamp
-> Maybe Natural
-> String
-> RemainingSteps
-> ("verbose" :! Bool)
-> ("dryRun" :? Bool)
-> ExecutorM a
-> IO (ExecutorRes, a)
runExecutorMWithDB Maybe Timestamp
maybeNow Maybe Natural
maybeLevel String
dbPath (Word64 -> RemainingSteps
RemainingSteps Word64
maxSteps) "verbose" :! Bool
verbose (("dryRun" :? Bool) -> ExecutorM Value -> IO (ExecutorRes, Value))
-> Param ("dryRun" :? Bool)
-> ExecutorM Value
-> IO (ExecutorRes, Value)
forall p fn fn'. WithParam p fn fn' => fn -> Param p -> fn'
! IsLabel "dryRun" (Bool -> Param ("dryRun" :? Bool))
Bool -> Param ("dryRun" :? Bool)
#dryRun Bool
dryRun (ExecutorM Value -> IO (ExecutorRes, Value))
-> ExecutorM Value -> IO (ExecutorRes, Value)
forall a b. (a -> b) -> a -> b
$ do
    -- Here we are safe to bypass executeGlobalOperations for origination,
    -- since origination can't generate more operations.
    Address
addr <- OriginationOperation -> ExecutorM Address
executeGlobalOrigination OriginationOperation
origination
    let transferOp :: ExecutorOp
transferOp = Address -> TxData -> ExecutorOp
TransferOp Address
addr TxData
txData
    [ExecutorOp] -> ExecutorM ()
executeGlobalOperations [ExecutorOp
transferOp]
    Address -> ExecutorM Value
getContractStorage Address
addr
  Value -> IO Value
forall (m :: * -> *) a. Monad m => a -> m a
return Value
newSt
  where
    -- We hardcode some random key hash here as delegate to make sure that:
    -- 1. Contract's address won't clash with already originated one (because
    -- it may have different storage value which may be confusing).
    -- 2. If one uses this functionality twice with the same contract and
    -- other data, the contract will have the same address.
    delegate :: KeyHash
delegate =
      (CryptoParseError -> KeyHash)
-> (KeyHash -> KeyHash)
-> Either CryptoParseError KeyHash
-> KeyHash
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Text -> KeyHash
forall a. HasCallStack => Text -> a
error (Text -> KeyHash)
-> (CryptoParseError -> Text) -> CryptoParseError -> KeyHash
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text -> Text
forall a. Monoid a => a -> a -> a
mappend "runContract can't parse delegate: " (Text -> Text)
-> (CryptoParseError -> Text) -> CryptoParseError -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CryptoParseError -> Text
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty) KeyHash -> KeyHash
forall a. a -> a
id (Either CryptoParseError KeyHash -> KeyHash)
-> Either CryptoParseError KeyHash -> KeyHash
forall a b. (a -> b) -> a -> b
$
      Text -> Either CryptoParseError KeyHash
parseKeyHash "tz1YCABRTa6H8PLKx2EtDWeCGPaKxUhNgv47"
    mkOrigination :: SomeContractAndStorage -> OriginationOperation
mkOrigination (SomeContractAndStorage contract :: Contract cp st
contract storage :: Value st
storage) = $WOriginationOperation :: forall (cp :: T) (st :: T).
(StorageScope st, ParameterScope cp) =>
Address
-> Maybe KeyHash
-> Mutez
-> Value st
-> Contract cp st
-> OriginationOperation
OriginationOperation
      { ooOriginator :: Address
ooOriginator = Address
genesisAddress
      , ooDelegate :: Maybe KeyHash
ooDelegate = KeyHash -> Maybe KeyHash
forall a. a -> Maybe a
Just KeyHash
delegate
      , ooBalance :: Mutez
ooBalance = Mutez
initBalance
      , ooStorage :: Value st
ooStorage = Value st
storage
      , ooContract :: Contract cp st
ooContract = Contract cp st
contract
      }

    getContractStorage :: Address -> ExecutorM U.Value
    getContractStorage :: Address -> ExecutorM Value
getContractStorage addr :: Address
addr = do
      Map Address AddressState
addrs <- Getting
  (Map Address AddressState) ExecutorState (Map Address AddressState)
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Map Address AddressState)
forall s (m :: * -> *) a. MonadState s m => Getting a s a -> m a
use ((GState -> Const (Map Address AddressState) GState)
-> ExecutorState -> Const (Map Address AddressState) ExecutorState
Lens' ExecutorState GState
esGState ((GState -> Const (Map Address AddressState) GState)
 -> ExecutorState -> Const (Map Address AddressState) ExecutorState)
-> ((Map Address AddressState
     -> Const (Map Address AddressState) (Map Address AddressState))
    -> GState -> Const (Map Address AddressState) GState)
-> Getting
     (Map Address AddressState) ExecutorState (Map Address AddressState)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Map Address AddressState
 -> Const (Map Address AddressState) (Map Address AddressState))
-> GState -> Const (Map Address AddressState) GState
Lens' GState (Map Address AddressState)
gsAddressesL)
      case Map Address AddressState
addrs Map Address AddressState
-> Getting
     (Maybe AddressState)
     (Map Address AddressState)
     (Maybe AddressState)
-> Maybe AddressState
forall s a. s -> Getting a s a -> a
^. Index (Map Address AddressState)
-> Lens'
     (Map Address AddressState)
     (Maybe (IxValue (Map Address AddressState)))
forall m. At m => Index m -> Lens' m (Maybe (IxValue m))
at Index (Map Address AddressState)
Address
addr of
        Nothing -> Text -> ExecutorM Value
forall a. HasCallStack => Text -> a
error (Text -> ExecutorM Value) -> Text -> ExecutorM Value
forall a b. (a -> b) -> a -> b
$ Address -> Text
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty Address
addr Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> " is unknown"
        Just (ASSimple {}) -> Text -> ExecutorM Value
forall a. HasCallStack => Text -> a
error (Text -> ExecutorM Value) -> Text -> ExecutorM Value
forall a b. (a -> b) -> a -> b
$ Address -> Text
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty Address
addr Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> " is a simple address"
        Just (ASContract (ContractState{..})) -> Value -> ExecutorM Value
forall (m :: * -> *) a. Monad m => a -> m a
return (Value -> ExecutorM Value) -> Value -> ExecutorM Value
forall a b. (a -> b) -> a -> b
$ Value st -> Value
forall (t :: T). (SingI t, HasNoOp t) => Value' Instr t -> Value
untypeValue Value st
csStorage

-- | Send a transaction to given address with given parameters.
transfer ::
     Maybe Timestamp
  -> Maybe Natural
  -> Word64
  -> FilePath
  -> Address
  -> TxData
  -> "verbose" :! Bool
  -> "dryRun" :? Bool
  -> IO ()
transfer :: Maybe Timestamp
-> Maybe Natural
-> Word64
-> String
-> Address
-> TxData
-> ("verbose" :! Bool)
-> ("dryRun" :? Bool)
-> IO ()
transfer maybeNow :: Maybe Timestamp
maybeNow maybeLevel :: Maybe Natural
maybeLevel maxSteps :: Word64
maxSteps dbPath :: String
dbPath destination :: Address
destination txData :: TxData
txData verbose :: "verbose" :! Bool
verbose dryRun :: "dryRun" :? Bool
dryRun = do
  IO (ExecutorRes, ()) -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO (ExecutorRes, ()) -> IO ()) -> IO (ExecutorRes, ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ Maybe Timestamp
-> Maybe Natural
-> String
-> RemainingSteps
-> ("verbose" :! Bool)
-> ("dryRun" :? Bool)
-> ExecutorM ()
-> IO (ExecutorRes, ())
forall a.
Maybe Timestamp
-> Maybe Natural
-> String
-> RemainingSteps
-> ("verbose" :! Bool)
-> ("dryRun" :? Bool)
-> ExecutorM a
-> IO (ExecutorRes, a)
runExecutorMWithDB Maybe Timestamp
maybeNow Maybe Natural
maybeLevel String
dbPath (Word64 -> RemainingSteps
RemainingSteps Word64
maxSteps) "verbose" :! Bool
verbose "dryRun" :? Bool
dryRun (ExecutorM () -> IO (ExecutorRes, ()))
-> ExecutorM () -> IO (ExecutorRes, ())
forall a b. (a -> b) -> a -> b
$
    [ExecutorOp] -> ExecutorM ()
executeGlobalOperations [Address -> TxData -> ExecutorOp
TransferOp Address
destination TxData
txData]

----------------------------------------------------------------------------
-- Executor
----------------------------------------------------------------------------

-- | A monad in which contract executor runs.
type ExecutorM =
  ReaderT ExecutorEnv
    (StateT ExecutorState
      (Except ExecutorError)
    )

-- | Run some executor action, returning its result and final executor state in 'ExecutorRes'.
--
-- The action has access to the hash of currently executed global operation, in order to construct
-- addresses of originated contracts. It is expected that the action uses @#isGlobalOp .! True@
-- to specify this hash. Otherwise it is initialized with 'error'.
runExecutorM
  :: Timestamp
  -> Natural
  -> RemainingSteps
  -> GState
  -> ExecutorM a
  -> Either ExecutorError (ExecutorRes, a)
runExecutorM :: Timestamp
-> Natural
-> RemainingSteps
-> GState
-> ExecutorM a
-> Either ExecutorError (ExecutorRes, a)
runExecutorM now :: Timestamp
now level :: Natural
level remainingSteps :: RemainingSteps
remainingSteps gState :: GState
gState action :: ExecutorM a
action =
  ((a, ExecutorState) -> (ExecutorRes, a))
-> Either ExecutorError (a, ExecutorState)
-> Either ExecutorError (ExecutorRes, a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (a, ExecutorState) -> (ExecutorRes, a)
forall a. (a, ExecutorState) -> (ExecutorRes, a)
preResToRes
    (Either ExecutorError (a, ExecutorState)
 -> Either ExecutorError (ExecutorRes, a))
-> Either ExecutorError (a, ExecutorState)
-> Either ExecutorError (ExecutorRes, a)
forall a b. (a -> b) -> a -> b
$ Except ExecutorError (a, ExecutorState)
-> Either ExecutorError (a, ExecutorState)
forall e a. Except e a -> Either e a
runExcept
    (Except ExecutorError (a, ExecutorState)
 -> Either ExecutorError (a, ExecutorState))
-> Except ExecutorError (a, ExecutorState)
-> Either ExecutorError (a, ExecutorState)
forall a b. (a -> b) -> a -> b
$ StateT ExecutorState (Except ExecutorError) a
-> ExecutorState -> Except ExecutorError (a, ExecutorState)
forall s (m :: * -> *) a. StateT s m a -> s -> m (a, s)
runStateT (ExecutorM a
-> ExecutorEnv -> StateT ExecutorState (Except ExecutorError) a
forall r (m :: * -> *) a. ReaderT r m a -> r -> m a
runReaderT ExecutorM a
action (ExecutorEnv -> StateT ExecutorState (Except ExecutorError) a)
-> ExecutorEnv -> StateT ExecutorState (Except ExecutorError) a
forall a b. (a -> b) -> a -> b
$ Timestamp -> Natural -> ExecutorEnv
ExecutorEnv Timestamp
now Natural
level)
      ExecutorState
initialState
  where
    initialOpHash :: a
initialOpHash = Text -> a
forall a. HasCallStack => Text -> a
error "Initial OperationHash touched"

    initialState :: ExecutorState
initialState = $WExecutorState :: GState
-> RemainingSteps
-> Int32
-> Maybe Address
-> ExecutorLog
-> OperationHash
-> ExecutorState
ExecutorState
      { _esGState :: GState
_esGState = GState
gState
      , _esRemainingSteps :: RemainingSteps
_esRemainingSteps = RemainingSteps
remainingSteps
      , _esOriginationNonce :: Int32
_esOriginationNonce = 0
      , _esSourceAddress :: Maybe Address
_esSourceAddress = Maybe Address
forall a. Maybe a
Nothing
      , _esLog :: ExecutorLog
_esLog = ExecutorLog
forall a. Monoid a => a
mempty
      , _esOperationHash :: OperationHash
_esOperationHash = OperationHash
forall a. a
initialOpHash
      }

    preResToRes :: (a, ExecutorState) -> (ExecutorRes, a)
    preResToRes :: (a, ExecutorState) -> (ExecutorRes, a)
preResToRes (r :: a
r, ExecutorState{..}) =
      ( $WExecutorRes :: GState
-> [GStateUpdate]
-> [(Address, InterpretResult)]
-> RemainingSteps
-> ExecutorRes
ExecutorRes
          { _erGState :: GState
_erGState = GState
_esGState
          , _erUpdates :: [GStateUpdate]
_erUpdates = ExecutorLog
_esLog ExecutorLog
-> Getting [GStateUpdate] ExecutorLog [GStateUpdate]
-> [GStateUpdate]
forall s a. s -> Getting a s a -> a
^. Getting [GStateUpdate] ExecutorLog [GStateUpdate]
Lens' ExecutorLog [GStateUpdate]
elUpdates
          , _erInterpretResults :: [(Address, InterpretResult)]
_erInterpretResults = ExecutorLog
_esLog ExecutorLog
-> Getting
     [(Address, InterpretResult)]
     ExecutorLog
     [(Address, InterpretResult)]
-> [(Address, InterpretResult)]
forall s a. s -> Getting a s a -> a
^. Getting
  [(Address, InterpretResult)]
  ExecutorLog
  [(Address, InterpretResult)]
Lens' ExecutorLog [(Address, InterpretResult)]
elInterpreterResults
          , _erRemainingSteps :: RemainingSteps
_erRemainingSteps = RemainingSteps
_esRemainingSteps
          }
      , a
r
      )

-- | Run some executor action, reading state from the DB on disk.
--
-- Unless @dryRun@ is @False@, the final state is written back to the disk.
--
-- If the executor fails with 'ExecutorError' it will be thrown as an exception.
runExecutorMWithDB
  :: Maybe Timestamp
  -> Maybe Natural
  -> FilePath
  -> RemainingSteps
  -> "verbose" :! Bool
  -> "dryRun" :? Bool
  -> ExecutorM a
  -> IO (ExecutorRes, a)
runExecutorMWithDB :: Maybe Timestamp
-> Maybe Natural
-> String
-> RemainingSteps
-> ("verbose" :! Bool)
-> ("dryRun" :? Bool)
-> ExecutorM a
-> IO (ExecutorRes, a)
runExecutorMWithDB maybeNow :: Maybe Timestamp
maybeNow maybeLevel :: Maybe Natural
maybeLevel dbPath :: String
dbPath remainingSteps :: RemainingSteps
remainingSteps
  (Name "verbose" -> ("verbose" :! Bool) -> Bool
forall (name :: Symbol) a. Name name -> (name :! a) -> a
arg IsLabel "verbose" (Name "verbose")
Name "verbose"
#verbose -> Bool
verbose)
  (Name "dryRun" -> Bool -> ("dryRun" :? Bool) -> Bool
forall (name :: Symbol) a. Name name -> a -> (name :? a) -> a
argDef IsLabel "dryRun" (Name "dryRun")
Name "dryRun"
#dryRun Bool
False -> Bool
dryRun)
  action :: ExecutorM a
action = do
  GState
gState <- String -> IO GState
readGState String
dbPath
  Timestamp
now <- IO Timestamp
-> (Timestamp -> IO Timestamp) -> Maybe Timestamp -> IO Timestamp
forall b a. b -> (a -> b) -> Maybe a -> b
maybe IO Timestamp
getCurrentTime Timestamp -> IO Timestamp
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe Timestamp
maybeNow
  let level :: Natural
level = Natural -> Maybe Natural -> Natural
forall a. a -> Maybe a -> a
fromMaybe 0 Maybe Natural
maybeLevel
  (res :: ExecutorRes
res@ExecutorRes{..}, a :: a
a) <- (ExecutorError -> IO (ExecutorRes, a))
-> ((ExecutorRes, a) -> IO (ExecutorRes, a))
-> Either ExecutorError (ExecutorRes, a)
-> IO (ExecutorRes, a)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either ExecutorError -> IO (ExecutorRes, a)
forall (m :: * -> *) e a. (MonadThrow m, Exception e) => e -> m a
throwM (ExecutorRes, a) -> IO (ExecutorRes, a)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either ExecutorError (ExecutorRes, a) -> IO (ExecutorRes, a))
-> Either ExecutorError (ExecutorRes, a) -> IO (ExecutorRes, a)
forall a b. (a -> b) -> a -> b
$ Timestamp
-> Natural
-> RemainingSteps
-> GState
-> ExecutorM a
-> Either ExecutorError (ExecutorRes, a)
forall a.
Timestamp
-> Natural
-> RemainingSteps
-> GState
-> ExecutorM a
-> Either ExecutorError (ExecutorRes, a)
runExecutorM Timestamp
now Natural
level RemainingSteps
remainingSteps GState
gState ExecutorM a
action

  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless Bool
dryRun (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
    String -> GState -> IO ()
writeGState String
dbPath GState
_erGState

  (Element [(Address, InterpretResult)] -> IO ())
-> [(Address, InterpretResult)] -> IO ()
forall t (m :: * -> *) b.
(Container t, Monad m) =>
(Element t -> m b) -> t -> m ()
mapM_ (Address, InterpretResult) -> IO ()
Element [(Address, InterpretResult)] -> IO ()
printInterpretResult [(Address, InterpretResult)]
_erInterpretResults
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool
verbose Bool -> Bool -> Bool
&& Bool -> Bool
not ([GStateUpdate] -> Bool
forall t. Container t => t -> Bool
null [GStateUpdate]
_erUpdates)) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
    Builder -> IO ()
forall b. FromBuilder b => Builder -> b
fmtLn (Builder -> IO ()) -> Builder -> IO ()
forall a b. (a -> b) -> a -> b
$ Builder -> Builder -> Builder
nameF "Updates" ([GStateUpdate] -> Builder
forall (f :: * -> *) a. (Foldable f, Buildable a) => f a -> Builder
blockListF [GStateUpdate]
_erUpdates)
    Text -> IO ()
forall (m :: * -> *). MonadIO m => Text -> m ()
putTextLn (Text -> IO ()) -> Text -> IO ()
forall a b. (a -> b) -> a -> b
$ "Remaining gas: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> RemainingSteps -> Text
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty RemainingSteps
_erRemainingSteps Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> "."

  return (ExecutorRes
res, a
a)
  where
    printInterpretResult
      :: (Address, InterpretResult) -> IO ()
    printInterpretResult :: (Address, InterpretResult) -> IO ()
printInterpretResult (addr :: Address
addr, InterpretResult {..}) = do
      Text -> IO ()
forall (m :: * -> *). MonadIO m => Text -> m ()
putTextLn (Text -> IO ()) -> Text -> IO ()
forall a b. (a -> b) -> a -> b
$ "Executed contract " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Address -> Text
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty Address
addr
      case [Operation]
iurOps of
        [] -> Text -> IO ()
forall (m :: * -> *). MonadIO m => Text -> m ()
putTextLn "It didn't return any operations."
        _ -> Builder -> IO ()
forall b. FromBuilder b => Builder -> b
fmt (Builder -> IO ()) -> Builder -> IO ()
forall a b. (a -> b) -> a -> b
$ Builder -> Builder -> Builder
nameF "It returned operations" ([Operation] -> Builder
forall (f :: * -> *) a. (Foldable f, Buildable a) => f a -> Builder
blockListF [Operation]
iurOps)
      Text -> IO ()
forall (m :: * -> *). MonadIO m => Text -> m ()
putTextLn (Text -> IO ()) -> Text -> IO ()
forall a b. (a -> b) -> a -> b
$
        "It returned storage: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Value -> Text
forall a b. (Buildable a, FromBuilder b) => a -> b
pretty (Value st -> Value
forall (t :: T). (SingI t, HasNoOp t) => Value' Instr t -> Value
untypeValue Value st
iurNewStorage) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> "."
      let MorleyLogs logs :: [Text]
logs = InterpreterState -> MorleyLogs
isMorleyLogs InterpreterState
iurNewState
      Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([Text] -> Bool
forall t. Container t => t -> Bool
null [Text]
logs) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
        (Element [Text] -> IO ()) -> [Text] -> IO ()
forall t (m :: * -> *) b.
(Container t, Monad m) =>
(Element t -> m b) -> t -> m ()
mapM_ Element [Text] -> IO ()
forall (m :: * -> *). MonadIO m => Text -> m ()
putTextLn [Text]
logs
      Text -> IO ()
forall (m :: * -> *). MonadIO m => Text -> m ()
putTextLn "" -- extra break line to separate logs from two sequence contracts

-- | Execute a list of global operations, discarding their results.
executeGlobalOperations
  :: [ExecutorOp]
  -> ExecutorM ()
executeGlobalOperations :: [ExecutorOp] -> ExecutorM ()
executeGlobalOperations = (Element [ExecutorOp] -> ExecutorM ())
-> [ExecutorOp] -> ExecutorM ()
forall t (m :: * -> *) b.
(Container t, Monad m) =>
(Element t -> m b) -> t -> m ()
mapM_ ((Element [ExecutorOp] -> ExecutorM ())
 -> [ExecutorOp] -> ExecutorM ())
-> (Element [ExecutorOp] -> ExecutorM ())
-> [ExecutorOp]
-> ExecutorM ()
forall a b. (a -> b) -> a -> b
$ \op :: Element [ExecutorOp]
op ->
  ("isGlobalOp" :! Bool) -> [ExecutorOp] -> ExecutorM ()
executeMany (IsLabel "isGlobalOp" (Name "isGlobalOp")
Name "isGlobalOp"
#isGlobalOp Name "isGlobalOp" -> Bool -> "isGlobalOp" :! Bool
forall (name :: Symbol) a. Name name -> a -> NamedF Identity a name
.! Bool
True) [Element [ExecutorOp]
ExecutorOp
op]
  where
    -- | Execute a list of operations and additional operations they return, until there are none.
    executeMany :: "isGlobalOp" :! Bool -> [ExecutorOp] -> ExecutorM ()
    executeMany :: ("isGlobalOp" :! Bool) -> [ExecutorOp] -> ExecutorM ()
executeMany isGlobalOp :: "isGlobalOp" :! Bool
isGlobalOp = \case
        [] -> ExecutorM ()
forall (f :: * -> *). Applicative f => f ()
pass
        (op :: ExecutorOp
op:opsTail :: [ExecutorOp]
opsTail) -> do
          case ExecutorOp
op of
            OriginateOp origination :: OriginationOperation
origination -> ExecutorM Address -> ExecutorM ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (ExecutorM Address -> ExecutorM ())
-> ExecutorM Address -> ExecutorM ()
forall a b. (a -> b) -> a -> b
$ ("isGlobalOp" :! Bool) -> OriginationOperation -> ExecutorM Address
executeOrigination "isGlobalOp" :! Bool
isGlobalOp OriginationOperation
origination
            TransferOp addr :: Address
addr txData :: TxData
txData -> do
              [ExecutorOp]
moreOps <- ("isGlobalOp" :! Bool)
-> Address -> TxData -> ExecutorM [ExecutorOp]
executeTransfer "isGlobalOp" :! Bool
isGlobalOp Address
addr TxData
txData
              ("isGlobalOp" :! Bool) -> [ExecutorOp] -> ExecutorM ()
executeMany (IsLabel "isGlobalOp" (Name "isGlobalOp")
Name "isGlobalOp"
#isGlobalOp Name "isGlobalOp" -> Bool -> "isGlobalOp" :! Bool
forall (name :: Symbol) a. Name name -> a -> NamedF Identity a name
.! Bool
False) ([ExecutorOp] -> ExecutorM ()) -> [ExecutorOp] -> ExecutorM ()
forall a b. (a -> b) -> a -> b
$ [ExecutorOp]
opsTail [ExecutorOp] -> [ExecutorOp] -> [ExecutorOp]
forall a. Semigroup a => a -> a -> a
<> [ExecutorOp]
moreOps

-- | Execute a global origination operation.
executeGlobalOrigination :: OriginationOperation -> ExecutorM Address
executeGlobalOrigination :: OriginationOperation -> ExecutorM Address
executeGlobalOrigination = ("isGlobalOp" :! Bool) -> OriginationOperation -> ExecutorM Address
executeOrigination (("isGlobalOp" :! Bool)
 -> OriginationOperation -> ExecutorM Address)
-> Param ("isGlobalOp" :! Bool)
-> OriginationOperation
-> ExecutorM Address
forall p fn fn'. WithParam p fn fn' => fn -> Param p -> fn'
! IsLabel "isGlobalOp" (Bool -> Param ("isGlobalOp" :! Bool))
Bool -> Param ("isGlobalOp" :! Bool)
#isGlobalOp Bool
True

-- | Execute an origination operation.
executeOrigination
  :: "isGlobalOp" :! Bool
  -> OriginationOperation
  -> ExecutorM Address
executeOrigination :: ("isGlobalOp" :! Bool) -> OriginationOperation -> ExecutorM Address
executeOrigination (Name "isGlobalOp" -> ("isGlobalOp" :! Bool) -> Bool
forall (name :: Symbol) a. Name name -> (name :! a) -> a
arg IsLabel "isGlobalOp" (Name "isGlobalOp")
Name "isGlobalOp"
#isGlobalOp -> Bool
isGlobalOp) origination :: OriginationOperation
origination = do
  Bool -> ExecutorM () -> ExecutorM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
isGlobalOp (ExecutorM () -> ExecutorM ()) -> ExecutorM () -> ExecutorM ()
forall a b. (a -> b) -> a -> b
$ do
    ExecutorM ()
beginGlobalOperation
    ASetter ExecutorState ExecutorState OperationHash OperationHash
-> OperationHash -> ExecutorM ()
forall s (m :: * -> *) a b.
MonadState s m =>
ASetter s s a b -> b -> m ()
assign ASetter ExecutorState ExecutorState OperationHash OperationHash
Lens' ExecutorState OperationHash
esOperationHash (OperationHash -> ExecutorM ()) -> OperationHash -> ExecutorM ()
forall a b. (a -> b) -> a -> b
$ OriginationOperation -> OperationHash
mkOriginationOperationHash OriginationOperation
origination

  OperationHash
opHash <- Getting OperationHash ExecutorState OperationHash
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     OperationHash
forall s (m :: * -> *) a. MonadState s m => Getting a s a -> m a
use Getting OperationHash ExecutorState OperationHash
Lens' ExecutorState OperationHash
esOperationHash

  GState
gs <- Getting GState ExecutorState GState
-> ReaderT
     ExecutorEnv (StateT ExecutorState (Except ExecutorError)) GState
forall s (m :: * -> *) a. MonadState s m => Getting a s a -> m a
use Getting GState ExecutorState GState
Lens' ExecutorState GState
esGState
  Int32
originationNonce <- Getting Int32 ExecutorState Int32
-> ReaderT
     ExecutorEnv (StateT ExecutorState (Except ExecutorError)) Int32
forall s (m :: * -> *) a. MonadState s m => Getting a s a -> m a
use Getting Int32 ExecutorState Int32
Lens' ExecutorState Int32
esOriginationNonce
  let contractState :: ContractState
contractState =
        case OriginationOperation
origination of
          OriginationOperation _ _ bal :: Mutez
bal st :: Value st
st contract :: Contract cp st
contract -> Mutez -> Contract cp st -> Value st -> ContractState
forall (cp :: T) (st :: T).
(ParameterScope cp, StorageScope st) =>
Mutez -> Contract cp st -> Value st -> ContractState
ContractState Mutez
bal Contract cp st
contract Value st
st
  let originatorAddress :: Address
originatorAddress = OriginationOperation -> Address
ooOriginator OriginationOperation
origination
  Mutez
originatorBalance <- case GState -> Map Address AddressState
gsAddresses GState
gs Map Address AddressState
-> Getting
     (Maybe AddressState)
     (Map Address AddressState)
     (Maybe AddressState)
-> Maybe AddressState
forall s a. s -> Getting a s a -> a
^. Index (Map Address AddressState)
-> Lens'
     (Map Address AddressState)
     (Maybe (IxValue (Map Address AddressState)))
forall m. At m => Index m -> Lens' m (Maybe (IxValue m))
at Index (Map Address AddressState)
Address
originatorAddress of
    Nothing -> ExecutorError
-> ReaderT
     ExecutorEnv (StateT ExecutorState (Except ExecutorError)) Mutez
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (Address -> ExecutorError
forall a. a -> ExecutorError' a
EEUnknownManager Address
originatorAddress)
    Just (AddressState -> Mutez
asBalance -> Mutez
oldBalance)
      | Mutez
oldBalance Mutez -> Mutez -> Bool
forall a. Ord a => a -> a -> Bool
< OriginationOperation -> Mutez
ooBalance OriginationOperation
origination ->
        ExecutorError
-> ReaderT
     ExecutorEnv (StateT ExecutorState (Except ExecutorError)) Mutez
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (ExecutorError
 -> ReaderT
      ExecutorEnv (StateT ExecutorState (Except ExecutorError)) Mutez)
-> ExecutorError
-> ReaderT
     ExecutorEnv (StateT ExecutorState (Except ExecutorError)) Mutez
forall a b. (a -> b) -> a -> b
$ Address -> Mutez -> ExecutorError
forall a. a -> Mutez -> ExecutorError' a
EENotEnoughFunds Address
originatorAddress Mutez
oldBalance
      | Bool
otherwise ->
        -- Subtraction is safe because we have checked its
        -- precondition in guard.
        Mutez
-> ReaderT
     ExecutorEnv (StateT ExecutorState (Except ExecutorError)) Mutez
forall (m :: * -> *) a. Monad m => a -> m a
return (Mutez
 -> ReaderT
      ExecutorEnv (StateT ExecutorState (Except ExecutorError)) Mutez)
-> Mutez
-> ReaderT
     ExecutorEnv (StateT ExecutorState (Except ExecutorError)) Mutez
forall a b. (a -> b) -> a -> b
$ Mutez
oldBalance HasCallStack => Mutez -> Mutez -> Mutez
Mutez -> Mutez -> Mutez
`unsafeSubMutez` OriginationOperation -> Mutez
ooBalance OriginationOperation
origination
  let
    address :: Address
address = OperationHash -> OriginationIndex -> GlobalCounter -> Address
mkContractAddress OperationHash
opHash (Int32 -> OriginationIndex
OriginationIndex Int32
originationNonce) (GState -> GlobalCounter
gsCounter GState
gs)
    updates :: [GStateUpdate]
updates =
      [ Address -> AddressState -> GStateUpdate
GSAddAddress Address
address (ContractState -> AddressState
ASContract ContractState
contractState)
      , Address -> Mutez -> GStateUpdate
GSSetBalance Address
originatorAddress Mutez
originatorBalance
      , GStateUpdate
GSIncrementCounter
      ]
  case [GStateUpdate] -> GState -> Either GStateUpdateError GState
applyUpdates [GStateUpdate]
updates GState
gs of
    Left _ ->
      ExecutorError -> ExecutorM Address
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (ExecutorError -> ExecutorM Address)
-> ExecutorError -> ExecutorM Address
forall a b. (a -> b) -> a -> b
$ Address -> ContractState -> ExecutorError
forall a. a -> ContractState -> ExecutorError' a
EEAlreadyOriginated Address
address ContractState
contractState
    Right newGS :: GState
newGS -> do
      (GState -> Identity GState)
-> ExecutorState -> Identity ExecutorState
Lens' ExecutorState GState
esGState ((GState -> Identity GState)
 -> ExecutorState -> Identity ExecutorState)
-> GState -> ExecutorM ()
forall s (m :: * -> *) a b.
MonadState s m =>
ASetter s s a b -> b -> m ()
.= GState
newGS
      (Int32 -> Identity Int32)
-> ExecutorState -> Identity ExecutorState
Lens' ExecutorState Int32
esOriginationNonce ((Int32 -> Identity Int32)
 -> ExecutorState -> Identity ExecutorState)
-> Int32 -> ExecutorM ()
forall s (m :: * -> *) a.
(MonadState s m, Num a) =>
ASetter' s a -> a -> m ()
+= 1

      (ExecutorLog -> Identity ExecutorLog)
-> ExecutorState -> Identity ExecutorState
Lens' ExecutorState ExecutorLog
esLog ((ExecutorLog -> Identity ExecutorLog)
 -> ExecutorState -> Identity ExecutorState)
-> ExecutorLog -> ExecutorM ()
forall s (m :: * -> *) a.
(MonadState s m, Monoid a) =>
ASetter' s a -> a -> m ()
<>= [GStateUpdate] -> [(Address, InterpretResult)] -> ExecutorLog
ExecutorLog [GStateUpdate]
updates []

      return Address
address

-- | Execute a transfer operation.
executeTransfer
  :: "isGlobalOp" :! Bool
  -> Address
  -> TxData
  -> ExecutorM [ExecutorOp]
executeTransfer :: ("isGlobalOp" :! Bool)
-> Address -> TxData -> ExecutorM [ExecutorOp]
executeTransfer (Name "isGlobalOp" -> ("isGlobalOp" :! Bool) -> Bool
forall (name :: Symbol) a. Name name -> (name :! a) -> a
arg IsLabel "isGlobalOp" (Name "isGlobalOp")
Name "isGlobalOp"
#isGlobalOp -> Bool
isGlobalOp) addr :: Address
addr txData :: TxData
txData = do
    Bool -> ExecutorM () -> ExecutorM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
isGlobalOp (ExecutorM () -> ExecutorM ()) -> ExecutorM () -> ExecutorM ()
forall a b. (a -> b) -> a -> b
$
      ExecutorM ()
beginGlobalOperation

    Timestamp
now <- Getting Timestamp ExecutorEnv Timestamp
-> ReaderT
     ExecutorEnv (StateT ExecutorState (Except ExecutorError)) Timestamp
forall s (m :: * -> *) a. MonadReader s m => Getting a s a -> m a
view Getting Timestamp ExecutorEnv Timestamp
Lens' ExecutorEnv Timestamp
eeNow
    Natural
level <- Getting Natural ExecutorEnv Natural
-> ReaderT
     ExecutorEnv (StateT ExecutorState (Except ExecutorError)) Natural
forall s (m :: * -> *) a. MonadReader s m => Getting a s a -> m a
view Getting Natural ExecutorEnv Natural
Lens' ExecutorEnv Natural
eeLevel
    GState
gs <- Getting GState ExecutorState GState
-> ReaderT
     ExecutorEnv (StateT ExecutorState (Except ExecutorError)) GState
forall s (m :: * -> *) a. MonadState s m => Getting a s a -> m a
use Getting GState ExecutorState GState
Lens' ExecutorState GState
esGState
    RemainingSteps
remainingSteps <- Getting RemainingSteps ExecutorState RemainingSteps
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     RemainingSteps
forall s (m :: * -> *) a. MonadState s m => Getting a s a -> m a
use Getting RemainingSteps ExecutorState RemainingSteps
Lens' ExecutorState RemainingSteps
esRemainingSteps
    Maybe Address
mSourceAddr <- Getting (Maybe Address) ExecutorState (Maybe Address)
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Maybe Address)
forall s (m :: * -> *) a. MonadState s m => Getting a s a -> m a
use Getting (Maybe Address) ExecutorState (Maybe Address)
Lens' ExecutorState (Maybe Address)
esSourceAddress

    let addresses :: Map Address AddressState
addresses = GState -> Map Address AddressState
gsAddresses GState
gs
    let sourceAddr :: Address
sourceAddr = Address -> Maybe Address -> Address
forall a. a -> Maybe a -> a
fromMaybe (TxData -> Address
tdSenderAddress TxData
txData) Maybe Address
mSourceAddr
    let senderAddr :: Address
senderAddr = TxData -> Address
tdSenderAddress TxData
txData
    let isKeyAddress :: Address -> Bool
isKeyAddress (KeyAddress _) = Bool
True
        isKeyAddress _ = Bool
False
    let isZeroTransfer :: Bool
isZeroTransfer = TxData -> Mutez
tdAmount TxData
txData Mutez -> Mutez -> Bool
forall a. Eq a => a -> a -> Bool
== Word32 -> Mutez
toMutez 0

    -- Transferring 0 XTZ to a key address is prohibited.
    Bool -> ExecutorM () -> ExecutorM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool
isZeroTransfer Bool -> Bool -> Bool
&& Address -> Bool
isKeyAddress Address
addr) (ExecutorM () -> ExecutorM ()) -> ExecutorM () -> ExecutorM ()
forall a b. (a -> b) -> a -> b
$
      ExecutorError -> ExecutorM ()
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (ExecutorError -> ExecutorM ()) -> ExecutorError -> ExecutorM ()
forall a b. (a -> b) -> a -> b
$ Address -> ExecutorError
forall a. a -> ExecutorError' a
EEZeroTransaction Address
addr
    Maybe GStateUpdate
mDecreaseSenderBalance <- case (Bool
isZeroTransfer, Map Address AddressState
addresses Map Address AddressState
-> Getting
     (Maybe AddressState)
     (Map Address AddressState)
     (Maybe AddressState)
-> Maybe AddressState
forall s a. s -> Getting a s a -> a
^. Index (Map Address AddressState)
-> Lens'
     (Map Address AddressState)
     (Maybe (IxValue (Map Address AddressState)))
forall m. At m => Index m -> Lens' m (Maybe (IxValue m))
at Index (Map Address AddressState)
Address
senderAddr) of
      (True, _) -> Maybe GStateUpdate
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Maybe GStateUpdate)
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe GStateUpdate
forall a. Maybe a
Nothing
      (False, Nothing) -> ExecutorError
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Maybe GStateUpdate)
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (ExecutorError
 -> ReaderT
      ExecutorEnv
      (StateT ExecutorState (Except ExecutorError))
      (Maybe GStateUpdate))
-> ExecutorError
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Maybe GStateUpdate)
forall a b. (a -> b) -> a -> b
$ Address -> ExecutorError
forall a. a -> ExecutorError' a
EEUnknownSender Address
senderAddr
      (False, Just (AddressState -> Mutez
asBalance -> Mutez
balance))
        | Mutez
balance Mutez -> Mutez -> Bool
forall a. Ord a => a -> a -> Bool
< TxData -> Mutez
tdAmount TxData
txData ->
          ExecutorError
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Maybe GStateUpdate)
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (ExecutorError
 -> ReaderT
      ExecutorEnv
      (StateT ExecutorState (Except ExecutorError))
      (Maybe GStateUpdate))
-> ExecutorError
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Maybe GStateUpdate)
forall a b. (a -> b) -> a -> b
$ Address -> Mutez -> ExecutorError
forall a. a -> Mutez -> ExecutorError' a
EENotEnoughFunds Address
senderAddr Mutez
balance
        | Bool
otherwise ->
          -- Subtraction is safe because we have checked its
          -- precondition in guard.
          Maybe GStateUpdate
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Maybe GStateUpdate)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe GStateUpdate
 -> ReaderT
      ExecutorEnv
      (StateT ExecutorState (Except ExecutorError))
      (Maybe GStateUpdate))
-> Maybe GStateUpdate
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Maybe GStateUpdate)
forall a b. (a -> b) -> a -> b
$ GStateUpdate -> Maybe GStateUpdate
forall a. a -> Maybe a
Just (GStateUpdate -> Maybe GStateUpdate)
-> GStateUpdate -> Maybe GStateUpdate
forall a b. (a -> b) -> a -> b
$ Address -> Mutez -> GStateUpdate
GSSetBalance Address
senderAddr (Mutez
balance HasCallStack => Mutez -> Mutez -> Mutez
Mutez -> Mutez -> Mutez
`unsafeSubMutez` TxData -> Mutez
tdAmount TxData
txData)
    Bool -> ExecutorM () -> ExecutorM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not (Address -> Bool
isKeyAddress Address
senderAddr) Bool -> Bool -> Bool
&& Bool
isGlobalOp) (ExecutorM () -> ExecutorM ()) -> ExecutorM () -> ExecutorM ()
forall a b. (a -> b) -> a -> b
$
      ExecutorError -> ExecutorM ()
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (ExecutorError -> ExecutorM ()) -> ExecutorError -> ExecutorM ()
forall a b. (a -> b) -> a -> b
$ Address -> Mutez -> ExecutorError
forall a. a -> Mutez -> ExecutorError' a
EETransactionFromContract Address
senderAddr (Mutez -> ExecutorError) -> Mutez -> ExecutorError
forall a b. (a -> b) -> a -> b
$ TxData -> Mutez
tdAmount TxData
txData
    let onlyUpdates :: [GStateUpdate]
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     ([GStateUpdate], [Operation], Maybe InterpretResult,
      RemainingSteps)
onlyUpdates updates :: [GStateUpdate]
updates = ([GStateUpdate], [Operation], Maybe InterpretResult,
 RemainingSteps)
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     ([GStateUpdate], [Operation], Maybe InterpretResult,
      RemainingSteps)
forall (m :: * -> *) a. Monad m => a -> m a
return ([GStateUpdate]
updates, [], Maybe InterpretResult
forall a. Maybe a
Nothing, RemainingSteps
remainingSteps)
    (otherUpdates :: [GStateUpdate]
otherUpdates, sideEffects :: [Operation]
sideEffects, Maybe InterpretResult
maybeInterpretRes :: Maybe InterpretResult, newRemSteps :: RemainingSteps
newRemSteps)
        <- case (Map Address AddressState
addresses Map Address AddressState
-> Getting
     (Maybe AddressState)
     (Map Address AddressState)
     (Maybe AddressState)
-> Maybe AddressState
forall s a. s -> Getting a s a -> a
^. Index (Map Address AddressState)
-> Lens'
     (Map Address AddressState)
     (Maybe (IxValue (Map Address AddressState)))
forall m. At m => Index m -> Lens' m (Maybe (IxValue m))
at Index (Map Address AddressState)
Address
addr, Address
addr) of
      (Nothing, ContractAddress _) ->
        ExecutorError
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     ([GStateUpdate], [Operation], Maybe InterpretResult,
      RemainingSteps)
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (ExecutorError
 -> ReaderT
      ExecutorEnv
      (StateT ExecutorState (Except ExecutorError))
      ([GStateUpdate], [Operation], Maybe InterpretResult,
       RemainingSteps))
-> ExecutorError
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     ([GStateUpdate], [Operation], Maybe InterpretResult,
      RemainingSteps)
forall a b. (a -> b) -> a -> b
$ Address -> ExecutorError
forall a. a -> ExecutorError' a
EEUnknownContract Address
addr
      (Nothing, KeyAddress _) -> do
        let
          transferAmount :: Mutez
transferAmount = TxData -> Mutez
tdAmount TxData
txData
          addrState :: AddressState
addrState = Mutez -> AddressState
ASSimple Mutez
transferAmount
          upd :: GStateUpdate
upd = Address -> AddressState -> GStateUpdate
GSAddAddress Address
addr AddressState
addrState
        [GStateUpdate]
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     ([GStateUpdate], [Operation], Maybe InterpretResult,
      RemainingSteps)
onlyUpdates [GStateUpdate
upd]
      (Just (ASSimple oldBalance :: Mutez
oldBalance), _) -> do
        -- can't overflow if global state is correct (because we can't
        -- create money out of nowhere)
        let
          newBalance :: Mutez
newBalance = Mutez
oldBalance HasCallStack => Mutez -> Mutez -> Mutez
Mutez -> Mutez -> Mutez
`unsafeAddMutez` TxData -> Mutez
tdAmount TxData
txData
          upd :: GStateUpdate
upd = Address -> Mutez -> GStateUpdate
GSSetBalance Address
addr Mutez
newBalance
        [GStateUpdate]
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     ([GStateUpdate], [Operation], Maybe InterpretResult,
      RemainingSteps)
onlyUpdates [GStateUpdate
upd]
      (Just (ASContract (ContractState {..})), _) -> do
        let
          existingContracts :: TcOriginatedContracts
existingContracts = GState -> TcOriginatedContracts
extractAllContracts GState
gs
          -- can't overflow if global state is correct (because we can't
          -- create money out of nowhere)
          newBalance :: Mutez
newBalance = Mutez
csBalance HasCallStack => Mutez -> Mutez -> Mutez
Mutez -> Mutez -> Mutez
`unsafeAddMutez` TxData -> Mutez
tdAmount TxData
txData
          epName :: EpName
epName = TxData -> EpName
tdEntrypoint TxData
txData

        T.MkEntrypointCallRes _ (EntrypointCallT cp arg
epc :: EntrypointCallT cp epArg)
          <- EpName -> ParamNotes cp -> Maybe (MkEntrypointCallRes cp)
forall (param :: T).
ParameterScope param =>
EpName -> ParamNotes param -> Maybe (MkEntrypointCallRes param)
T.mkEntrypointCall EpName
epName (Contract cp st -> ParamNotes cp
forall (cp :: T) (st :: T). Contract cp st -> ParamNotes cp
T.cParamNotes Contract cp st
csContract)
             Maybe (MkEntrypointCallRes cp)
-> (Maybe (MkEntrypointCallRes cp)
    -> ReaderT
         ExecutorEnv
         (StateT ExecutorState (Except ExecutorError))
         (MkEntrypointCallRes cp))
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (MkEntrypointCallRes cp)
forall a b. a -> (a -> b) -> b
& ReaderT
  ExecutorEnv
  (StateT ExecutorState (Except ExecutorError))
  (MkEntrypointCallRes cp)
-> (MkEntrypointCallRes cp
    -> ReaderT
         ExecutorEnv
         (StateT ExecutorState (Except ExecutorError))
         (MkEntrypointCallRes cp))
-> Maybe (MkEntrypointCallRes cp)
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (MkEntrypointCallRes cp)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (ExecutorError
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (MkEntrypointCallRes cp)
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (ExecutorError
 -> ReaderT
      ExecutorEnv
      (StateT ExecutorState (Except ExecutorError))
      (MkEntrypointCallRes cp))
-> ExecutorError
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (MkEntrypointCallRes cp)
forall a b. (a -> b) -> a -> b
$ EpName -> ExecutorError
forall a. EpName -> ExecutorError' a
EEUnknownEntrypoint EpName
epName) MkEntrypointCallRes cp
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (MkEntrypointCallRes cp)
forall (f :: * -> *) a. Applicative f => a -> f a
pure

        -- If the parameter has already been typechecked, simply check if
        -- its type matches the contract's entrypoint's type.
        -- Otherwise (e.g. if it was parsed from stdin via the CLI),
        -- we need to typecheck the parameter.
        Value arg
typedParameter <-
          case TxData -> TxParam
tdParameter TxData
txData of
            TxTypedParam (Value t
typedVal :: T.Value t) ->
              ReaderT
  ExecutorEnv
  (StateT ExecutorState (Except ExecutorError))
  (Value arg)
-> (Value arg
    -> ReaderT
         ExecutorEnv
         (StateT ExecutorState (Except ExecutorError))
         (Value arg))
-> Maybe (Value arg)
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Value arg)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (ExecutorError
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Value arg)
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (ExecutorError
 -> ReaderT
      ExecutorEnv
      (StateT ExecutorState (Except ExecutorError))
      (Value arg))
-> ExecutorError
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Value arg)
forall a b. (a -> b) -> a -> b
$ T -> T -> ExecutorError
forall a. T -> T -> ExecutorError' a
EEUnexpectedParameterType ((SingKind T, SingI arg) => Demote T
forall k (a :: k). (SingKind k, SingI a) => Demote k
demote @epArg) ((SingKind T, SingI t) => Demote T
forall k (a :: k). (SingKind k, SingI a) => Demote k
demote @t)) Value arg
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Value arg)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe (Value arg)
 -> ReaderT
      ExecutorEnv
      (StateT ExecutorState (Except ExecutorError))
      (Value arg))
-> Maybe (Value arg)
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Value arg)
forall a b. (a -> b) -> a -> b
$
                Value t -> Maybe (Value arg)
forall k (a :: k) (b :: k) (c :: k -> *).
(Typeable a, Typeable b) =>
c a -> Maybe (c b)
gcast @t @epArg Value t
typedVal
            TxUntypedParam untypedVal :: Value
untypedVal ->
              Either ExecutorError (Value arg)
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Value arg)
forall e (m :: * -> *) a. MonadError e m => Either e a -> m a
liftEither (Either ExecutorError (Value arg)
 -> ReaderT
      ExecutorEnv
      (StateT ExecutorState (Except ExecutorError))
      (Value arg))
-> Either ExecutorError (Value arg)
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     (Value arg)
forall a b. (a -> b) -> a -> b
$ (TCError -> ExecutorError)
-> Either TCError (Value arg) -> Either ExecutorError (Value arg)
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first TCError -> ExecutorError
forall a. TCError -> ExecutorError' a
EEIllTypedParameter (Either TCError (Value arg) -> Either ExecutorError (Value arg))
-> Either TCError (Value arg) -> Either ExecutorError (Value arg)
forall a b. (a -> b) -> a -> b
$
                TcOriginatedContracts -> Value -> Either TCError (Value arg)
forall (t :: T).
SingI t =>
TcOriginatedContracts -> Value -> Either TCError (Value t)
typeVerifyParameter @epArg TcOriginatedContracts
existingContracts Value
untypedVal

        -- I'm not entirely sure why we need to pattern match on `()` here,
        -- but, if we don't, we get a compiler error that I suspect is somehow related
        -- to the existential types we're matching on a few lines above.
        --
        -- • Couldn't match type ‘a0’
        --                  with ‘(InterpretResult, RemainingSteps, [Operation], [GStateUpdate])’
        --     ‘a0’ is untouchable inside the constraints: StorageScope st1
        () <- Bool -> ExecutorM () -> ExecutorM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
isGlobalOp (ExecutorM () -> ExecutorM ()) -> ExecutorM () -> ExecutorM ()
forall a b. (a -> b) -> a -> b
$
          ASetter ExecutorState ExecutorState OperationHash OperationHash
Lens' ExecutorState OperationHash
esOperationHash ASetter ExecutorState ExecutorState OperationHash OperationHash
-> OperationHash -> ExecutorM ()
forall s (m :: * -> *) a b.
MonadState s m =>
ASetter s s a b -> b -> m ()
.= Address -> Value arg -> EpName -> Mutez -> OperationHash
forall (t :: T).
ParameterScope t =>
Address -> Value t -> EpName -> Mutez -> OperationHash
mkTransferOperationHash
            Address
addr
            Value arg
typedParameter
            (TxData -> EpName
tdEntrypoint TxData
txData)
            (TxData -> Mutez
tdAmount TxData
txData)

        OperationHash
opHash <- Getting OperationHash ExecutorState OperationHash
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     OperationHash
forall s (m :: * -> *) a. MonadState s m => Getting a s a -> m a
use Getting OperationHash ExecutorState OperationHash
Lens' ExecutorState OperationHash
esOperationHash
        let
          contractEnv :: ContractEnv
contractEnv = $WContractEnv :: Timestamp
-> RemainingSteps
-> Mutez
-> TcOriginatedContracts
-> Address
-> Address
-> Address
-> Mutez
-> ChainId
-> Maybe OperationHash
-> GlobalCounter
-> Natural
-> ContractEnv
ContractEnv
            { ceNow :: Timestamp
ceNow = Timestamp
now
            , ceMaxSteps :: RemainingSteps
ceMaxSteps = RemainingSteps
remainingSteps
            , ceBalance :: Mutez
ceBalance = Mutez
newBalance
            , ceContracts :: TcOriginatedContracts
ceContracts = TcOriginatedContracts
existingContracts
            , ceSelf :: Address
ceSelf = Address
addr
            , ceSource :: Address
ceSource = Address
sourceAddr
            , ceSender :: Address
ceSender = Address
senderAddr
            , ceAmount :: Mutez
ceAmount = TxData -> Mutez
tdAmount TxData
txData
            , ceChainId :: ChainId
ceChainId = GState -> ChainId
gsChainId GState
gs
            , ceOperationHash :: Maybe OperationHash
ceOperationHash = OperationHash -> Maybe OperationHash
forall a. a -> Maybe a
Just OperationHash
opHash
            , ceGlobalCounter :: GlobalCounter
ceGlobalCounter = GState -> GlobalCounter
gsCounter GState
gs
            , ceLevel :: Natural
ceLevel = Natural
level
            }

        iur :: InterpretResult
iur@InterpretResult
          { iurOps :: InterpretResult -> [Operation]
iurOps = [Operation]
sideEffects
          , iurNewStorage :: ()
iurNewStorage = Value st
newValue
          , iurNewState :: InterpretResult -> InterpreterState
iurNewState = InterpreterState _ newRemainingSteps :: RemainingSteps
newRemainingSteps _
          }
          <- Either ExecutorError InterpretResult
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     InterpretResult
forall e (m :: * -> *) a. MonadError e m => Either e a -> m a
liftEither (Either ExecutorError InterpretResult
 -> ReaderT
      ExecutorEnv
      (StateT ExecutorState (Except ExecutorError))
      InterpretResult)
-> Either ExecutorError InterpretResult
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     InterpretResult
forall a b. (a -> b) -> a -> b
$ (InterpretError -> ExecutorError)
-> Either InterpretError InterpretResult
-> Either ExecutorError InterpretResult
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (Address -> InterpretError -> ExecutorError
forall a. a -> InterpretError -> ExecutorError' a
EEInterpreterFailed Address
addr) (Either InterpretError InterpretResult
 -> Either ExecutorError InterpretResult)
-> Either InterpretError InterpretResult
-> Either ExecutorError InterpretResult
forall a b. (a -> b) -> a -> b
$
             ContractReturn st -> Either InterpretError InterpretResult
forall (st :: T).
StorageScope st =>
ContractReturn st -> Either InterpretError InterpretResult
handleContractReturn (ContractReturn st -> Either InterpretError InterpretResult)
-> ContractReturn st -> Either InterpretError InterpretResult
forall a b. (a -> b) -> a -> b
$
                Contract cp st
-> EntrypointCallT cp arg
-> Value arg
-> Value st
-> ContractEnv
-> ContractReturn st
forall (cp :: T) (st :: T) (arg :: T).
Contract cp st
-> EntrypointCallT cp arg
-> Value arg
-> Value st
-> ContractEnv
-> ContractReturn st
interpret Contract cp st
csContract EntrypointCallT cp arg
epc
                Value arg
typedParameter Value st
csStorage ContractEnv
contractEnv
        let
          updBalance :: Maybe GStateUpdate
updBalance
            | Mutez
newBalance Mutez -> Mutez -> Bool
forall a. Eq a => a -> a -> Bool
== Mutez
csBalance = Maybe GStateUpdate
forall a. Maybe a
Nothing
            | Bool
otherwise = GStateUpdate -> Maybe GStateUpdate
forall a. a -> Maybe a
Just (GStateUpdate -> Maybe GStateUpdate)
-> GStateUpdate -> Maybe GStateUpdate
forall a b. (a -> b) -> a -> b
$ Address -> Mutez -> GStateUpdate
GSSetBalance Address
addr Mutez
newBalance
          updStorage :: Maybe GStateUpdate
updStorage
            | Value st -> SomeValue' Instr
forall (t :: T) (instr :: [T] -> [T] -> *).
KnownT t =>
Value' instr t -> SomeValue' instr
SomeValue Value st
newValue SomeValue' Instr -> SomeValue' Instr -> Bool
forall a. Eq a => a -> a -> Bool
== Value st -> SomeValue' Instr
forall (t :: T) (instr :: [T] -> [T] -> *).
KnownT t =>
Value' instr t -> SomeValue' instr
SomeValue Value st
csStorage = Maybe GStateUpdate
forall a. Maybe a
Nothing
            | Bool
otherwise = GStateUpdate -> Maybe GStateUpdate
forall a. a -> Maybe a
Just (GStateUpdate -> Maybe GStateUpdate)
-> GStateUpdate -> Maybe GStateUpdate
forall a b. (a -> b) -> a -> b
$ Address -> Value st -> GStateUpdate
forall (st :: T).
StorageScope st =>
Address -> Value st -> GStateUpdate
GSSetStorageValue Address
addr Value st
newValue
          updates :: [GStateUpdate]
updates = [Maybe GStateUpdate] -> [GStateUpdate]
forall a. [Maybe a] -> [a]
catMaybes
            [ Maybe GStateUpdate
updBalance
            , Maybe GStateUpdate
updStorage
            ]
        ([GStateUpdate], [Operation], Maybe InterpretResult,
 RemainingSteps)
-> ReaderT
     ExecutorEnv
     (StateT ExecutorState (Except ExecutorError))
     ([GStateUpdate], [Operation], Maybe InterpretResult,
      RemainingSteps)
forall (m :: * -> *) a. Monad m => a -> m a
return ([GStateUpdate]
updates, [Operation]
sideEffects, InterpretResult -> Maybe InterpretResult
forall a. a -> Maybe a
Just InterpretResult
iur, RemainingSteps
newRemainingSteps)

    let
      -- According to the reference implementation, counter is incremented for transfers as well.
      updates :: [GStateUpdate]
updates = (([GStateUpdate] -> [GStateUpdate])
-> (GStateUpdate -> [GStateUpdate] -> [GStateUpdate])
-> Maybe GStateUpdate
-> [GStateUpdate]
-> [GStateUpdate]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [GStateUpdate] -> [GStateUpdate]
forall a. a -> a
id (:) Maybe GStateUpdate
mDecreaseSenderBalance [GStateUpdate]
otherUpdates) [GStateUpdate] -> [GStateUpdate] -> [GStateUpdate]
forall a. [a] -> [a] -> [a]
++ [GStateUpdate
GSIncrementCounter]

    GState
newGState <- Either ExecutorError GState
-> ReaderT
     ExecutorEnv (StateT ExecutorState (Except ExecutorError)) GState
forall e (m :: * -> *) a. MonadError e m => Either e a -> m a
liftEither (Either ExecutorError GState
 -> ReaderT
      ExecutorEnv (StateT ExecutorState (Except ExecutorError)) GState)
-> Either ExecutorError GState
-> ReaderT
     ExecutorEnv (StateT ExecutorState (Except ExecutorError)) GState
forall a b. (a -> b) -> a -> b
$ (GStateUpdateError -> ExecutorError)
-> Either GStateUpdateError GState -> Either ExecutorError GState
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first GStateUpdateError -> ExecutorError
forall a. GStateUpdateError -> ExecutorError' a
EEFailedToApplyUpdates (Either GStateUpdateError GState -> Either ExecutorError GState)
-> Either GStateUpdateError GState -> Either ExecutorError GState
forall a b. (a -> b) -> a -> b
$ [GStateUpdate] -> GState -> Either GStateUpdateError GState
applyUpdates [GStateUpdate]
updates GState
gs

    (GState -> Identity GState)
-> ExecutorState -> Identity ExecutorState
Lens' ExecutorState GState
esGState ((GState -> Identity GState)
 -> ExecutorState -> Identity ExecutorState)
-> GState -> ExecutorM ()
forall s (m :: * -> *) a b.
MonadState s m =>
ASetter s s a b -> b -> m ()
.= GState
newGState
    (RemainingSteps -> Identity RemainingSteps)
-> ExecutorState -> Identity ExecutorState
Lens' ExecutorState RemainingSteps
esRemainingSteps ((RemainingSteps -> Identity RemainingSteps)
 -> ExecutorState -> Identity ExecutorState)
-> RemainingSteps -> ExecutorM ()
forall s (m :: * -> *) a b.
MonadState s m =>
ASetter s s a b -> b -> m ()
.= RemainingSteps
newRemSteps
    (Maybe Address -> Identity (Maybe Address))
-> ExecutorState -> Identity ExecutorState
Lens' ExecutorState (Maybe Address)
esSourceAddress ((Maybe Address -> Identity (Maybe Address))
 -> ExecutorState -> Identity ExecutorState)
-> Maybe Address -> ExecutorM ()
forall s (m :: * -> *) a b.
MonadState s m =>
ASetter s s a b -> b -> m ()
.= Address -> Maybe Address
forall a. a -> Maybe a
Just Address
sourceAddr

    (ExecutorLog -> Identity ExecutorLog)
-> ExecutorState -> Identity ExecutorState
Lens' ExecutorState ExecutorLog
esLog ((ExecutorLog -> Identity ExecutorLog)
 -> ExecutorState -> Identity ExecutorState)
-> ExecutorLog -> ExecutorM ()
forall s (m :: * -> *) a.
(MonadState s m, Monoid a) =>
ASetter' s a -> a -> m ()
<>= [GStateUpdate] -> [(Address, InterpretResult)] -> ExecutorLog
ExecutorLog [GStateUpdate]
updates ([(Address, InterpretResult)]
-> (InterpretResult -> [(Address, InterpretResult)])
-> Maybe InterpretResult
-> [(Address, InterpretResult)]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [(Address, InterpretResult)]
forall a. Monoid a => a
mempty ((Address, InterpretResult) -> [(Address, InterpretResult)]
forall x. One x => OneItem x -> x
one ((Address, InterpretResult) -> [(Address, InterpretResult)])
-> (InterpretResult -> (Address, InterpretResult))
-> InterpretResult
-> [(Address, InterpretResult)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Address
addr, )) Maybe InterpretResult
maybeInterpretRes)

    return $ (Operation -> Maybe ExecutorOp) -> [Operation] -> [ExecutorOp]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (Address -> Operation -> Maybe ExecutorOp
convertOp Address
addr) [Operation]
sideEffects

----------------------------------------------------------------------------
-- Simple helpers
----------------------------------------------------------------------------

mkTransferOperationHash :: ParameterScope t => Address -> T.Value t -> EpName -> Mutez -> OperationHash
mkTransferOperationHash :: Address -> Value t -> EpName -> Mutez -> OperationHash
mkTransferOperationHash to :: Address
to param :: Value t
param epName :: EpName
epName amount :: Mutez
amount =
  ByteString -> OperationHash
OperationHash (ByteString -> OperationHash) -> ByteString -> OperationHash
forall a b. (a -> b) -> a -> b
$ ByteString -> ByteString
blake2b ByteString
packedOperation
  where
    -- In Tezos, transfer operations are encoded as 4-tuple of
    -- (amount, destination, entrypoint, value)
    --
    -- See https://gitlab.com/tezos/tezos/-/blob/f57c50e3a657956d69a1699978de9873c98f0018/src/proto_006_PsCARTHA/lib_protocol/operation_repr.ml#L275-282
    packedOperation :: ByteString
packedOperation =
      ByteString -> ByteString
BSL.toStrict (ByteString -> ByteString) -> ByteString -> ByteString
forall a b. (a -> b) -> a -> b
$
        (Put -> ByteString
runPut (Put -> ByteString) -> Put -> ByteString
forall a b. (a -> b) -> a -> b
$ Word64 -> Put
putWord64be (Word64 -> Put) -> Word64 -> Put
forall a b. (a -> b) -> a -> b
$ Mutez -> Word64
unMutez Mutez
amount)
        ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> EpAddress -> ByteString
Pack.encodeEpAddress (Address -> EpName -> EpAddress
EpAddress Address
to EpName
epName)
        ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Value t -> ByteString
forall (t :: T). (SingI t, HasNoOp t) => Value t -> ByteString
Pack.encodeValue Value t
param

-- The argument is the address of the contract that generated this operation.
convertOp :: Address -> T.Operation -> Maybe ExecutorOp
convertOp :: Address -> Operation -> Maybe ExecutorOp
convertOp interpretedAddr :: Address
interpretedAddr =
  \case
    OpTransferTokens tt :: TransferTokens Instr p
tt ->
      case TransferTokens Instr p -> Value' Instr ('TContract p)
forall (instr :: [T] -> [T] -> *) (p :: T).
TransferTokens instr p -> Value' instr ('TContract p)
ttContract TransferTokens Instr p
tt of
        T.VContract destAddress :: Address
destAddress sepc :: SomeEntrypointCallT arg
sepc ->
          let txData :: TxData
txData =
                $WTxData :: Address -> TxParam -> EpName -> Mutez -> TxData
TxData
                  { tdSenderAddress :: Address
tdSenderAddress = Address
interpretedAddr
                  , tdEntrypoint :: EpName
tdEntrypoint = SomeEntrypointCallT arg -> EpName
forall (arg :: T). SomeEntrypointCallT arg -> EpName
T.sepcName SomeEntrypointCallT arg
sepc
                  , tdParameter :: TxParam
tdParameter = Value p -> TxParam
forall (t :: T). ParameterScope t => Value t -> TxParam
TxTypedParam (TransferTokens Instr p -> Value p
forall (instr :: [T] -> [T] -> *) (p :: T).
TransferTokens instr p -> Value' instr p
ttTransferArgument TransferTokens Instr p
tt)
                  , tdAmount :: Mutez
tdAmount = TransferTokens Instr p -> Mutez
forall (instr :: [T] -> [T] -> *) (p :: T).
TransferTokens instr p -> Mutez
ttAmount TransferTokens Instr p
tt
                  }
          in ExecutorOp -> Maybe ExecutorOp
forall a. a -> Maybe a
Just (Address -> TxData -> ExecutorOp
TransferOp Address
destAddress TxData
txData)
    OpSetDelegate {} -> Maybe ExecutorOp
forall a. Maybe a
Nothing
    OpCreateContract cc :: CreateContract Instr cp st
cc ->
      let origination :: OriginationOperation
origination = $WOriginationOperation :: forall (cp :: T) (st :: T).
(StorageScope st, ParameterScope cp) =>
Address
-> Maybe KeyHash
-> Mutez
-> Value st
-> Contract cp st
-> OriginationOperation
OriginationOperation
            { ooOriginator :: Address
ooOriginator = CreateContract Instr cp st -> Address
forall (instr :: [T] -> [T] -> *) (cp :: T) (st :: T).
CreateContract instr cp st -> Address
ccOriginator CreateContract Instr cp st
cc
            , ooDelegate :: Maybe KeyHash
ooDelegate = CreateContract Instr cp st -> Maybe KeyHash
forall (instr :: [T] -> [T] -> *) (cp :: T) (st :: T).
CreateContract instr cp st -> Maybe KeyHash
ccDelegate CreateContract Instr cp st
cc
            , ooBalance :: Mutez
ooBalance = CreateContract Instr cp st -> Mutez
forall (instr :: [T] -> [T] -> *) (cp :: T) (st :: T).
CreateContract instr cp st -> Mutez
ccBalance CreateContract Instr cp st
cc
            , ooStorage :: Value st
ooStorage = CreateContract Instr cp st -> Value st
forall (instr :: [T] -> [T] -> *) (cp :: T) (st :: T).
CreateContract instr cp st -> Value' instr st
ccStorageVal CreateContract Instr cp st
cc
            , ooContract :: Contract cp st
ooContract =
                $WContract :: forall (cp :: T) (st :: T).
(ParameterScope cp, StorageScope st) =>
ContractCode cp st
-> ParamNotes cp -> Notes st -> EntriesOrder -> Contract cp st
T.Contract
                  { cCode :: ContractCode cp st
cCode = CreateContract Instr cp st -> ContractCode cp st
forall (instr :: [T] -> [T] -> *) (cp :: T) (st :: T).
CreateContract instr cp st
-> instr (ContractInp cp st) (ContractOut st)
ccContractCode CreateContract Instr cp st
cc
                  , cParamNotes :: ParamNotes cp
cParamNotes = ParamNotes cp
forall (t :: T). SingI t => ParamNotes t
starParamNotes
                  , cStoreNotes :: Notes st
cStoreNotes = Notes st
forall (t :: T). SingI t => Notes t
starNotes
                  , cEntriesOrder :: EntriesOrder
cEntriesOrder = EntriesOrder
U.canonicalEntriesOrder
                  }
            }
       in ExecutorOp -> Maybe ExecutorOp
forall a. a -> Maybe a
Just (OriginationOperation -> ExecutorOp
OriginateOp OriginationOperation
origination)

-- | Reset nonce and source address before executing a global operation.
beginGlobalOperation :: ExecutorM ()
beginGlobalOperation :: ExecutorM ()
beginGlobalOperation = do
  (Int32 -> Identity Int32)
-> ExecutorState -> Identity ExecutorState
Lens' ExecutorState Int32
esOriginationNonce ((Int32 -> Identity Int32)
 -> ExecutorState -> Identity ExecutorState)
-> Int32 -> ExecutorM ()
forall s (m :: * -> *) a b.
MonadState s m =>
ASetter s s a b -> b -> m ()
.= 0
  (Maybe Address -> Identity (Maybe Address))
-> ExecutorState -> Identity ExecutorState
Lens' ExecutorState (Maybe Address)
esSourceAddress ((Maybe Address -> Identity (Maybe Address))
 -> ExecutorState -> Identity ExecutorState)
-> Maybe Address -> ExecutorM ()
forall s (m :: * -> *) a b.
MonadState s m =>
ASetter s s a b -> b -> m ()
.= Maybe Address
forall a. Maybe a
Nothing