-
Notifications
You must be signed in to change notification settings - Fork 0
/
Governance.hs
271 lines (227 loc) · 9.96 KB
/
Governance.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-ignore-interface-pragmas #-}
{-# OPTIONS_GHC -fno-omit-interface-pragmas #-}
{-# OPTIONS_GHC -fno-specialise #-}
{-# OPTIONS_GHC -fno-spec-constr #-}
-- | A basic governance contract in Plutus.
module Plutus.Contracts.Governance (
-- $governance
mainContract
, proposalContract
, Params(..)
, Proposal(..)
, Schema
, mkTokenName
, typedValidator
, mkValidator
, test
, GovState(..)
, Voting(..)
, GovError
) where
import Control.Lens (makeClassyPrisms, review)
import Control.Monad
import Data.Aeson (FromJSON, ToJSON)
import Data.ByteString (ByteString)
import Data.Semigroup (Sum (..))
import Data.String (fromString)
import Data.Text (Text)
import GHC.Generics (Generic)
import Ledger (MintingPolicyHash, POSIXTime, PubKeyHash, TokenName)
import Ledger.Ada qualified as Ada
import Ledger.Constraints (TxConstraints)
import Ledger.Constraints qualified as Constraints
import Ledger.Interval qualified as Interval
import Ledger.Typed.Scripts qualified as Scripts
import Ledger.Value qualified as Value
import Plutus.Contract
import Plutus.Contract.StateMachine (AsSMContractError, State (..), StateMachine (..), Void)
import Plutus.Contract.StateMachine qualified as SM
import Plutus.Trace.Emulator as Trace
import PlutusTx qualified
import PlutusTx.AssocMap qualified as AssocMap
import PlutusTx.Prelude
import Prelude qualified as Haskell
import Wallet.Emulator.Wallet
import Ledger.TimeSlot qualified as TimeSlot
-- $governance
-- * When the contract starts it produces a number of tokens that represent voting rights.
-- * Holders of those tokens can propose changes to the state of the contract and vote on them.
-- * After a certain period of time the voting ends and the proposal is rejected or accepted.
-- | The parameters for the proposal contract.
data Proposal = Proposal
{ newLaw :: BuiltinByteString
-- ^ The new contents of the law
, tokenName :: TokenName
-- ^ The name of the voting tokens. Only voting token owners are allowed to propose changes.
, votingDeadline :: POSIXTime
-- ^ The time when voting ends and the votes are tallied.
}
deriving stock (Haskell.Show, Generic)
deriving anyclass (ToJSON, FromJSON)
data Voting = Voting
{ proposal :: Proposal
, votes :: AssocMap.Map TokenName Bool
}
deriving stock (Haskell.Show, Generic)
deriving anyclass (ToJSON, FromJSON)
data GovState = GovState
{ law :: BuiltinByteString
, mph :: MintingPolicyHash
, voting :: Maybe Voting
}
deriving stock (Haskell.Show, Generic)
deriving anyclass (ToJSON, FromJSON)
data GovInput
= MintTokens [TokenName]
| ProposeChange Proposal
| AddVote TokenName Bool
| FinishVoting
deriving stock (Haskell.Show, Generic)
deriving anyclass (ToJSON, FromJSON)
-- | The endpoints of governance contracts are
--
-- * @new-law@ to create a new law and distribute voting tokens
-- * @add-vote@ to vote on a proposal with the name of the voting token and a boolean to vote in favor or against.
type Schema =
Endpoint "new-law" ByteString
.\/ Endpoint "add-vote" (TokenName, Bool)
-- | The governace contract parameters.
data Params = Params
{ baseTokenName :: TokenName
-- ^ The token names that allow voting are generated by adding an increasing number to the base token name. See `mkTokenName`.
, initialHolders :: [PubKeyHash]
-- ^ The public key hashes of the initial holders of the voting tokens.
, requiredVotes :: Integer
-- ^ The number of votes in favor required for a proposal to be accepted.
}
data GovError =
GovContractError ContractError
| GovStateMachineError SM.SMContractError
deriving stock (Haskell.Eq, Haskell.Show, Generic)
deriving anyclass (ToJSON, FromJSON)
makeClassyPrisms ''GovError
instance AsContractError GovError where
_ContractError = _GovContractError
instance AsSMContractError GovError where
_SMContractError = _GovStateMachineError
type GovernanceMachine = StateMachine GovState GovInput
{-# INLINABLE machine #-}
machine :: Params -> GovernanceMachine
machine params = SM.mkStateMachine Nothing (transition params) isFinal where
{-# INLINABLE isFinal #-}
isFinal _ = False
{-# INLINABLE mkValidator #-}
mkValidator :: Params -> Scripts.ValidatorType GovernanceMachine
mkValidator params = SM.mkValidator $ machine params
typedValidator :: Params -> Scripts.TypedValidator GovernanceMachine
typedValidator = Scripts.mkTypedValidatorParam @GovernanceMachine
$$(PlutusTx.compile [|| mkValidator ||])
$$(PlutusTx.compile [|| wrap ||])
where
wrap = Scripts.wrapValidator
client :: Params -> SM.StateMachineClient GovState GovInput
client params = SM.mkStateMachineClient $ SM.StateMachineInstance (machine params) (typedValidator params)
-- | Generate a voting token name by tagging on a number after the base token name.
mkTokenName :: TokenName -> Integer -> TokenName
mkTokenName base ix = fromString (Value.toString base ++ Haskell.show ix)
{-# INLINABLE votingValue #-}
votingValue :: MintingPolicyHash -> TokenName -> Value.Value
votingValue mph tokenName =
Value.singleton (Value.mpsSymbol mph) tokenName 1
{-# INLINABLE ownsVotingToken #-}
ownsVotingToken :: MintingPolicyHash -> TokenName -> TxConstraints Void Void
ownsVotingToken mph tokenName = Constraints.mustSpendAtLeast (votingValue mph tokenName)
{-# INLINABLE transition #-}
transition :: Params -> State GovState -> GovInput -> Maybe (TxConstraints Void Void, State GovState)
transition Params{..} State{ stateData = s, stateValue} i = case (s, i) of
(GovState{mph}, MintTokens tokenNames) ->
let (total, constraints) = foldMap
(\(pk, nm) -> let v = votingValue mph nm in (v, Constraints.mustPayToPubKey pk v))
(zip initialHolders tokenNames)
in Just (constraints <> Constraints.mustMintValue total, State s stateValue)
(GovState law mph Nothing, ProposeChange proposal@Proposal{tokenName}) ->
let constraints = ownsVotingToken mph tokenName
in Just (constraints, State (GovState law mph (Just (Voting proposal AssocMap.empty))) stateValue)
(GovState law mph (Just (Voting p oldMap)), AddVote tokenName vote) ->
let newMap = AssocMap.insert tokenName vote oldMap
constraints = ownsVotingToken mph tokenName
<> Constraints.mustValidateIn (Interval.to (votingDeadline p))
in Just (constraints, State (GovState law mph (Just (Voting p newMap))) stateValue)
(GovState oldLaw mph (Just (Voting p votes)), FinishVoting) ->
let Sum ayes = foldMap (\b -> Sum $ if b then 1 else 0) votes
in Just (mempty, State (GovState (if ayes >= requiredVotes then newLaw p else oldLaw) mph Nothing) stateValue)
_ -> Nothing
-- | The main contract for creating a new law and for voting on proposals.
mainContract :: AsGovError e => Params -> Contract () Schema e ()
mainContract params = forever $ mapError (review _GovError) endpoints where
theClient = client params
endpoints = selectList [initLaw, addVote]
addVote = endpoint @"add-vote" $ \(tokenName, vote) ->
void $ SM.runStep theClient (AddVote tokenName vote)
initLaw = endpoint @"new-law" $ \bsLaw -> do
let mph = Scripts.forwardingMintingPolicyHash (typedValidator params)
void $ SM.runInitialise theClient (GovState (toBuiltin bsLaw) mph Nothing) (Ada.lovelaceValueOf 1)
let tokens = Haskell.zipWith (const (mkTokenName (baseTokenName params))) (initialHolders params) [1..]
void $ SM.runStep theClient $ MintTokens tokens
-- | The contract for proposing changes to a law.
proposalContract :: AsGovError e => Params -> Proposal -> Contract () EmptySchema e ()
proposalContract params proposal = mapError (review _GovError) propose where
theClient = client params
propose = do
void $ SM.runStep theClient (ProposeChange proposal)
logInfo @Text "SMART CONTRACT AUDIT TOKEN STARTING VOTING STAGE"
void $ awaitTime $ votingDeadline proposal
logInfo @Text "SMART CONTRACT AUDIT TOKEN FINISH VOTING STAGE"
void $ SM.runStep theClient FinishVoting
PlutusTx.makeLift ''Params
PlutusTx.unstableMakeIsData ''Proposal
PlutusTx.makeLift ''Proposal
PlutusTx.unstableMakeIsData ''Voting
PlutusTx.makeLift ''Voting
PlutusTx.unstableMakeIsData ''GovState
PlutusTx.makeLift ''GovState
PlutusTx.unstableMakeIsData ''GovInput
PlutusTx.makeLift ''GovInput
test :: Haskell.IO ()
test = runEmulatorTraceIO scatTrace
numberOfHolders :: Integer
numberOfHolders = 10
baseName :: Ledger.TokenName
baseName = "AUDIT"
newName :: Ledger.TokenName
newName = "NEWTOKEN"
params :: Params
params = Params
{ baseTokenName = baseName
, initialHolders = walletPubKeyHash . knownWallet <$> [1..numberOfHolders]
, requiredVotes = 6
}
law1,law2 :: BuiltinByteString
law1 = "LAW 1"
law2 = "LAW 2"
scatTrace :: EmulatorTrace ()
scatTrace = do
h1 <- Trace.activateContractWallet (knownWallet 1)
(mainContract @GovError params)
callEndpoint @"new-law" h1 (fromBuiltin law1)
void $ Trace.waitNSlots 2
slotCfg <- Trace.getSlotConfig
h2 <- Trace.activateContractWallet (knownWallet 2)
(proposalContract @GovError params Proposal
{ newLaw = law2
, tokenName = baseName
, votingDeadline = TimeSlot.slotToEndPOSIXTime slotCfg $ 2
})
void $ Trace.waitNSlots 2