Skip to content

Commit

Permalink
Make hydra-plutus compile
Browse files Browse the repository at this point in the history
  • Loading branch information
ch1bo committed Jul 20, 2021
1 parent 75ca039 commit ba29065
Show file tree
Hide file tree
Showing 9 changed files with 63 additions and 59 deletions.
17 changes: 9 additions & 8 deletions hydra-plutus/exe/hydra-pab/Main.hs
Expand Up @@ -11,9 +11,9 @@ import Control.Monad.Freer.Extras.Log (LogMsg)
import qualified Hydra.Contract.OnChain as OnChain
import Hydra.Contract.PAB (PABContract (..))
import qualified Hydra.ContractSM as ContractSM
import Ledger (MonetaryPolicy, MonetaryPolicyHash, PubKeyHash, TxOut, TxOutRef, TxOutTx, monetaryPolicyHash, pubKeyAddress, pubKeyHash)
import Ledger (MintingPolicy, MintingPolicyHash, PubKeyHash, TxOut, TxOutRef, TxOutTx, mintingPolicyHash, pubKeyAddress, pubKeyHash)
import Ledger.AddressMap (UtxoMap)
import Plutus.Contract (BlockchainActions, Contract, ContractError, Empty, logInfo, ownPubKey, tell, utxoAt, waitNSlots)
import Plutus.Contract (Contract, ContractError, Empty, logInfo, ownPubKey, tell, utxoAt, waitNSlots)
import Plutus.Contract.Test (walletPubKey)
import Plutus.PAB.Effects.Contract (ContractEffect (..))
import Plutus.PAB.Effects.Contract.Builtin (Builtin, SomeBuiltin (..), endpointsToSchemas)
Expand All @@ -25,6 +25,7 @@ import Plutus.PAB.Types (PABError (..))
import qualified Plutus.PAB.Webserver.Server as PAB.Server
import Schema (FormSchema (..), ToSchema (..))
import Wallet.Emulator.Types (Wallet (..))
import Data.Default (def)

main :: IO ()
main = void $
Expand All @@ -45,7 +46,7 @@ main = void $

handlers :: SimulatorEffectHandlers (Builtin PABContract)
handlers =
Simulator.mkSimulatorHandlers @(Builtin PABContract) [] $
Simulator.mkSimulatorHandlers @(Builtin PABContract) def [] $
interpret handleStarterContract

handleStarterContract ::
Expand All @@ -68,7 +69,7 @@ handleStarterContract = Builtin.handleBuiltin getSchema getContract
GetUtxos -> SomeBuiltin getUtxo
WatchInit -> SomeBuiltin ContractSM.watchInit

getUtxo :: Contract (Last UtxoMap) BlockchainActions ContractError ()
getUtxo :: Contract (Last UtxoMap) Empty ContractError ()
getUtxo = do
logInfo @Text $ "getUtxo: Starting to get and report utxo map every slot"
address <- pubKeyAddress <$> ownPubKey
Expand All @@ -80,11 +81,11 @@ getUtxo = do
void $ waitNSlots 1
loop address

testPolicy :: MonetaryPolicy
testPolicy = OnChain.hydraMonetaryPolicy 42
testPolicy :: MintingPolicy
testPolicy = OnChain.hydraMintingPolicy 42

testPolicyId :: MonetaryPolicyHash
testPolicyId = monetaryPolicyHash testPolicy
testPolicyId :: MintingPolicyHash
testPolicyId = mintingPolicyHash testPolicy

vk :: Wallet -> PubKeyHash
vk = pubKeyHash . walletPubKey
Expand Down
3 changes: 2 additions & 1 deletion hydra-plutus/hydra-plutus.cabal
Expand Up @@ -96,8 +96,8 @@ library
lens,
playground-common,
plutus-core,
plutus-tx,
plutus-contract,
plutus-tx,
plutus-ledger,
plutus-tx-plugin,
plutus-use-cases,
Expand Down Expand Up @@ -148,6 +148,7 @@ executable hydra-pab
aeson
, base
, cardano-prelude
, data-default
, containers
, directory
, freer-extras
Expand Down
27 changes: 12 additions & 15 deletions hydra-plutus/src/Hydra/Contract/OffChain.hs
Expand Up @@ -16,8 +16,8 @@ import Ledger.Constraints.OffChain (ScriptLookups (..))
import Ledger.Constraints.TxConstraints (
TxConstraints,
mustBeSignedBy,
mustForgeCurrency,
mustForgeValue,
mustMintCurrency,
mustMintValue,
mustIncludeDatum,
mustPayToOtherScript,
mustPayToPubKey,
Expand All @@ -29,7 +29,6 @@ import Ledger.Credential (Credential (..))
import Ledger.Typed.Scripts (TypedValidator, ValidatorTypes (..))
import Plutus.Contract (
AsContractError,
BlockchainActions,
Contract,
Endpoint,
endpoint,
Expand All @@ -40,9 +39,8 @@ import Plutus.Contract (
tell,
utxoAt,
type (.\/),
awaitTxConfirmed,
)
import Plutus.Contract.Effects.AwaitTxConfirmed (awaitTxConfirmed)
import Plutus.Contract.Effects.UtxoAt (HasUtxoAt)

import qualified Data.Map.Strict as Map
import qualified Hydra.Contract.OnChain as OnChain
Expand All @@ -55,15 +53,15 @@ import qualified Ledger.Value as Value

data HeadParameters = HeadParameters
{ participants :: [PubKeyHash]
, policy :: MonetaryPolicy
, policyId :: MonetaryPolicyHash
, policy :: MintingPolicy
, policyId :: MintingPolicyHash
}

mkHeadParameters :: [PubKeyHash] -> MonetaryPolicy -> HeadParameters
mkHeadParameters :: [PubKeyHash] -> MintingPolicy -> HeadParameters
mkHeadParameters participants policy =
HeadParameters{participants, policy, policyId}
where
policyId = monetaryPolicyHash policy
policyId = mintingPolicyHash policy

--
-- Init
Expand Down Expand Up @@ -104,7 +102,7 @@ init params@HeadParameters{participants, policy, policyId} = do
(Scripts.validatorHash $ initialTypedValidator params)
(asDatum @(DatumType OnChain.Initial) vk)
participationToken
, mustForgeValue
, mustMintValue
participationToken
]
)
Expand Down Expand Up @@ -274,7 +272,7 @@ abort params@HeadParameters{participants, policy, policyId} = do
[ mustBeSignedBy headMember
, mustPayToTheScript OnChain.Final (lovelaceValueOf 0)
, foldMap
(\vk -> mustForgeCurrency policyId (OnChain.mkPartyName vk) (-1))
(\vk -> mustMintCurrency policyId (OnChain.mkPartyName vk) (-1))
participants
, foldMap mustRefund toRefund
, foldMap
Expand Down Expand Up @@ -304,8 +302,7 @@ setupForTesting params = do
foldMap (mustPayToPubKey vk)

type Schema =
BlockchainActions
.\/ Endpoint "setupForTesting" (PubKeyHash, [Value])
Endpoint "setupForTesting" (PubKeyHash, [Value])
.\/ Endpoint "init" ()
.\/ Endpoint "commit" (PubKeyHash, (TxOutRef, TxOutTx))
.\/ Endpoint "collectCom" (PubKeyHash, [TxOut])
Expand Down Expand Up @@ -363,7 +360,7 @@ mustRefund txOut =

utxoAtWithDatum ::
forall w s e.
(AsContractError e, HasUtxoAt s) =>
(AsContractError e) =>
Address ->
Datum ->
Contract w s e UtxoMap
Expand All @@ -382,7 +379,7 @@ utxoAtWithDatum addr datum = do
-- Instead, we must associate each commited utxo to their key using the
-- participation token that they all carry.
zipOnParty ::
MonetaryPolicyHash ->
MintingPolicyHash ->
[PubKeyHash] ->
UtxoMap ->
[(PubKeyHash, TxOutRef)]
Expand Down
36 changes: 19 additions & 17 deletions hydra-plutus/src/Hydra/Contract/OnChain.hs
Expand Up @@ -13,7 +13,7 @@ import Ledger.Ada (lovelaceValueOf)
import Ledger.Constraints (checkScriptContext)
import Ledger.Constraints.TxConstraints (
mustBeSignedBy,
mustForgeCurrency,
mustMintCurrency,
mustPayToOtherScript,
mustPayToTheScript,
mustProduceAtLeast,
Expand All @@ -39,7 +39,7 @@ import Text.Show (Show)

data HeadParameters = HeadParameters
{ participants :: [PubKeyHash]
, policyId :: MonetaryPolicyHash
, policyId :: MintingPolicyHash
}

PlutusTx.makeLift ''HeadParameters
Expand Down Expand Up @@ -113,7 +113,7 @@ hydraValidator HeadParameters{participants, policyId} s i ctx =
decodeCommit =
txOutDatumHash
>=> (`findDatum` scriptContextTxInfo ctx)
>=> (fromData @(DatumType Commit) . getDatum)
>=> (fromBuiltinData @(DatumType Commit) . getDatum)

{- ORMOLU_DISABLE -}
hydraTypedValidator
Expand Down Expand Up @@ -270,11 +270,13 @@ type FakeTxOutRef = Integer
-- has been partially applied. This is similar to what is called 'closures' in
-- some languages. Fundamentally, the parameter 'FakeTxOutRef' is embedded within the
-- policy and is part of the on-chain code itself!
validateMonetaryPolicy ::
validateMintingPolicy ::
FakeTxOutRef ->
-- | REVIEW(SN): Second context added in recent dependency update!?
ScriptContext ->
ScriptContext ->
Bool
validateMonetaryPolicy _outRef _ctx =
validateMintingPolicy _outRef _ctx _ctx2 =
validateMinting || validateBurning
where
-- FIXME
Expand All @@ -288,12 +290,12 @@ validateMonetaryPolicy _outRef _ctx =
validateMinting =
True

hydraMonetaryPolicy ::
hydraMintingPolicy ::
FakeTxOutRef ->
MonetaryPolicy
hydraMonetaryPolicy outRef =
mkMonetaryPolicyScript $
$$(PlutusTx.compile [||Scripts.wrapMonetaryPolicy . validateMonetaryPolicy||])
MintingPolicy
hydraMintingPolicy outRef =
mkMintingPolicyScript $
$$(PlutusTx.compile [||Scripts.wrapMintingPolicy . validateMintingPolicy||])
`PlutusTx.applyCode` PlutusTx.liftCode outRef

--
Expand All @@ -319,12 +321,12 @@ hydraMonetaryPolicy outRef =
-- always explicitly specify the source type when using this function,
-- preferably using the data-family from the 'ValidatorTypes' instance.
asDatum :: IsData a => a -> Datum
asDatum = Datum . toData
asDatum = Datum . toBuiltinData
{-# INLINEABLE asDatum #-}

-- | Always use with explicit type-annotation, See warnings on 'asDatum'.
asRedeemer :: IsData a => a -> Redeemer
asRedeemer = Redeemer . toData
asRedeemer = Redeemer . toBuiltinData
{-# INLINEABLE asRedeemer #-}

mustBeSignedByOneOf ::
Expand Down Expand Up @@ -365,7 +367,7 @@ mustRunContract script redeemer ctx =

mustForwardParty ::
ScriptContext ->
MonetaryPolicyHash ->
MintingPolicyHash ->
PubKeyHash ->
Bool
mustForwardParty ctx policyId vk =
Expand All @@ -381,16 +383,16 @@ mustForwardParty ctx policyId vk =

mustBurnParty ::
ScriptContext ->
MonetaryPolicyHash ->
MintingPolicyHash ->
PubKeyHash ->
Bool
mustBurnParty ctx policyId vk =
let assetName = mkPartyName vk
in checkScriptContext @() @() (mustForgeCurrency policyId assetName (-1)) ctx
in checkScriptContext @() @() (mustMintCurrency policyId assetName (-1)) ctx
{-# INLINEABLE mustBurnParty #-}

mkParty ::
MonetaryPolicyHash ->
MintingPolicyHash ->
PubKeyHash ->
Value
mkParty policyId vk =
Expand All @@ -404,7 +406,7 @@ mkPartyName =
TokenName . getPubKeyHash
{-# INLINEABLE mkPartyName #-}

hasParty :: MonetaryPolicyHash -> TxInInfo -> Bool
hasParty :: MintingPolicyHash -> TxInInfo -> Bool
hasParty policyId input =
let currency = Value.mpsSymbol policyId
in currency `elem` symbols (txOutValue $ txInInfoResolved input)
Expand Down
6 changes: 4 additions & 2 deletions hydra-plutus/src/Hydra/Contract/Party.hs
Expand Up @@ -30,6 +30,8 @@ instance ToSchema Party where
toSchema = FormSchemaUnsupported "Party"

instance PlutusTx.IsData Party where
toData (UnsafeParty k) = toData k
toBuiltinData (UnsafeParty k) = toBuiltinData k

fromData = fmap fromInteger . fromData
fromBuiltinData = fmap fromInteger . fromBuiltinData

unsafeFromBuiltinData = fromInteger . unsafeFromBuiltinData
14 changes: 7 additions & 7 deletions hydra-plutus/src/Hydra/ContractSM.hs
Expand Up @@ -22,9 +22,9 @@ import Ledger.Typed.Tx (tyTxOutData, typeScriptTxOut)
import Ledger.Value (AssetClass, TokenName (..), assetClass, flattenValue, singleton)
import Plutus.Contract (
AsContractError (..),
BlockchainActions,
Contract,
ContractError (..),
Empty,
Endpoint,
currentSlot,
endpoint,
Expand All @@ -33,7 +33,6 @@ import Plutus.Contract (
ownPubKey,
tell,
throwError,
type (.\/),
)
import Plutus.Contract.StateMachine (StateMachine, StateMachineClient, WaitingResult (..))
import qualified Plutus.Contract.StateMachine as SM
Expand Down Expand Up @@ -160,7 +159,7 @@ data InitParams = InitParams
}
deriving (Generic, FromJSON, ToJSON)

setup :: Contract () (BlockchainActions .\/ Endpoint "init" InitParams) HydraPlutusError ()
setup :: Contract () (Endpoint "init" InitParams) HydraPlutusError ()
setup = do
-- NOTE: These are the cardano/chain keys to send PTs to
InitParams{cardanoPubKeys, hydraParties} <- endpoint @"init" @InitParams
Expand All @@ -169,9 +168,10 @@ setup = do
participationTokens = map ((,1) . participationTokenName) cardanoPubKeys
tokens = stateThreadToken : participationTokens

-- TODO(SN): replace with SM.getThreadToken
logInfo $ "Forging tokens: " <> show @String tokens
ownPK <- pubKeyHash <$> ownPubKey
symbol <- Currency.currencySymbol <$> Currency.forgeContract ownPK tokens
symbol <- Currency.currencySymbol <$> Currency.mintContract ownPK tokens
let threadToken = mkThreadToken symbol
tokenValues = map (uncurry (singleton symbol)) participationTokens

Expand All @@ -185,7 +185,7 @@ setup = do

-- | Watch 'initialAddress' (with hard-coded parameters) and report all datums
-- seen on each run.
watchInit :: Contract (Last [Party]) BlockchainActions ContractError ()
watchInit :: Contract (Last [Party]) Empty ContractError ()
watchInit = do
logInfo @String $ "watchInit: Looking for an init tx and it's parties"
pubKey <- ownPubKey
Expand Down Expand Up @@ -220,12 +220,12 @@ watchInit = do
lookupDatum token txOutTx = tyTxOutData <$> typeScriptTxOut (typedValidator token) txOutTx

-- | Wait for 'Init' transaction to appear on chain and return the observed state of the state machine
watchStateMachine :: AssetClass -> Contract () BlockchainActions HydraPlutusError State
watchStateMachine :: AssetClass -> Contract () Empty HydraPlutusError State
watchStateMachine threadToken = do
logInfo @String $ "watchStateMachine: Looking for transitions of SM: " <> show threadToken
let client = machineClient threadToken
sl <- currentSlot
SM.waitForUpdateUntil client (sl + 10) >>= \case
SM.waitForUpdateUntilSlot client (sl + 10) >>= \case
(Timeout _s) -> throwError $ HydraError "Timed out waiting for transaction"
ContractEnded -> throwError $ HydraError "Contract ended"
(WaitingResult s) -> pure s
6 changes: 3 additions & 3 deletions hydra-plutus/test/Hydra/ContractModelTest.hs
Expand Up @@ -10,7 +10,7 @@ import qualified Hydra.Contract.OffChain as OffChain
import qualified Hydra.Contract.OnChain as OnChain
import Ledger (pubKeyHash)
import Ledger.Ada as Ada
import Ledger.Typed.Scripts (MonetaryPolicy)
import Ledger.Typed.Scripts (MintingPolicy)
import Plutus.Contract (Contract)
import Plutus.Contract.Test (Wallet, walletPubKey)
import Plutus.Contract.Test.ContractModel
Expand Down Expand Up @@ -58,8 +58,8 @@ instance Show (ContractInstanceKey HydraModel w schema err) where
instanceSpec :: [ContractInstanceSpec HydraModel]
instanceSpec = [ContractInstanceSpec (HeadParty w) w hydraContract | w <- wallets]
where
testPolicy :: MonetaryPolicy
testPolicy = OnChain.hydraMonetaryPolicy 42
testPolicy :: MintingPolicy
testPolicy = OnChain.hydraMintingPolicy 42

hydraContract :: Contract [OnChain.State] OffChain.Schema ContractError ()
hydraContract = OffChain.contract headParameters
Expand Down
8 changes: 4 additions & 4 deletions hydra-plutus/test/Hydra/ContractTest.hs
Expand Up @@ -47,11 +47,11 @@ alice = Wallet 1
bob :: Wallet
bob = Wallet 2

testPolicy :: MonetaryPolicy
testPolicy = OnChain.hydraMonetaryPolicy 42
testPolicy :: MintingPolicy
testPolicy = OnChain.hydraMintingPolicy 42

testPolicyId :: MonetaryPolicyHash
testPolicyId = monetaryPolicyHash testPolicy
testPolicyId :: MintingPolicyHash
testPolicyId = mintingPolicyHash testPolicy

contract :: Contract [OnChain.State] OffChain.Schema ContractError ()
contract = OffChain.contract headParameters
Expand Down

0 comments on commit ba29065

Please sign in to comment.