use Credential instead of PubKeyHash everywhere

This commit is contained in:
Emily Martins 2022-08-16 15:02:50 +02:00
parent 367a630cef
commit f730998326
15 changed files with 948 additions and 865 deletions

View file

@ -90,6 +90,7 @@ import Plutarch.Lift (PLifted, PUnsafeLiftDecl)
import PlutusLedgerApi.V1.Value (AssetClass (..)) import PlutusLedgerApi.V1.Value (AssetClass (..))
import PlutusLedgerApi.V1.Value qualified as Value import PlutusLedgerApi.V1.Value qualified as Value
import PlutusLedgerApi.V2 ( import PlutusLedgerApi.V2 (
Credential (PubKeyCredential),
DatumHash, DatumHash,
POSIXTime, POSIXTime,
POSIXTimeRange, POSIXTimeRange,
@ -241,8 +242,8 @@ data Validity = Validity
-- * Proposal -- * Proposal
-- | Mock cosigners. -- | Mock cosigners.
mkCosigners :: NumStake -> [PubKeyHash] mkCosigners :: NumStake -> [Credential]
mkCosigners = sort . flip take pubKeyHashes mkCosigners = sort . fmap PubKeyCredential . flip take pubKeyHashes
-- | Allocate the result tag for the effect at the given index. -- | Allocate the result tag for the effect at the given index.
outcomeIdxToResultTag :: Index -> ResultTag outcomeIdxToResultTag :: Index -> ResultTag
@ -347,7 +348,7 @@ proposalRedeemer = AdvanceProposal
-- * Stake -- * Stake
-- Mock owners of the stakes. -- Mock owners of the stakes.
mkStakeOwners :: NumStake -> [PubKeyHash] mkStakeOwners :: NumStake -> [Credential]
mkStakeOwners = mkCosigners mkStakeOwners = mkCosigners
-- | Create the input stake datums given the parameters. -- | Create the input stake datums given the parameters.
@ -356,7 +357,7 @@ mkStakeInputDatums ps =
let template = let template =
StakeDatum StakeDatum
{ stakedAmount = Tagged ps.perStakeGTs { stakedAmount = Tagged ps.perStakeGTs
, owner = "" , owner = PubKeyCredential ""
, delegatedTo = Nothing , delegatedTo = Nothing
, lockedBy = [] , lockedBy = []
} }
@ -399,9 +400,9 @@ mkStakeBuilder ps =
ps.perStakeGTs ps.perStakeGTs
perStake idx i o = perStake idx i o =
let withSig = let withSig =
if ps.transactionSignedByOwners case (i.owner, ps.transactionSignedByOwners) of
then signedWith i.owner (PubKeyCredential owner, True) -> signedWith owner
else mempty _ -> mempty
in mconcat in mconcat
[ withSig [ withSig
, input $ , input $

View file

@ -51,6 +51,7 @@ import Plutarch.Context (
) )
import PlutusLedgerApi.V1.Value qualified as Value import PlutusLedgerApi.V1.Value qualified as Value
import PlutusLedgerApi.V2 ( import PlutusLedgerApi.V2 (
Credential (PubKeyCredential),
POSIXTimeRange, POSIXTimeRange,
PubKeyHash, PubKeyHash,
TxOutRef (..), TxOutRef (..),
@ -77,7 +78,7 @@ import Test.Util (CombinableBuilder, closedBoundedInterval, mkSpending, pubKeyHa
-- | Parameters for cosigning a proposal. -- | Parameters for cosigning a proposal.
data Parameters = Parameters data Parameters = Parameters
{ newCosigners :: [PubKeyHash] { newCosigners :: [Credential]
-- ^ New cosigners to be added, and the owners of the generated stakes. -- ^ New cosigners to be added, and the owners of the generated stakes.
, proposalStatus :: ProposalStatus , proposalStatus :: ProposalStatus
-- ^ Current state of the proposal. -- ^ Current state of the proposal.
@ -108,7 +109,7 @@ mkProposalInputDatum ps =
{ proposalId = ProposalId 0 { proposalId = ProposalId 0
, effects = effects , effects = effects
, status = ps.proposalStatus , status = ps.proposalStatus
, cosigners = [proposalCreator] , cosigners = [PubKeyCredential proposalCreator]
, thresholds = def , thresholds = def
, votes = emptyVotesFor effects , votes = emptyVotesFor effects
, timingConfig = def , timingConfig = def
@ -128,7 +129,9 @@ mkProposalOutputDatum ps =
-- | Create all the input stakes given the parameters. -- | Create all the input stakes given the parameters.
mkStakeInputDatums :: Parameters -> [StakeDatum] mkStakeInputDatums :: Parameters -> [StakeDatum]
mkStakeInputDatums = fmap (\pk -> StakeDatum perStakedGTs pk Nothing []) . newCosigners mkStakeInputDatums =
fmap (\pk -> StakeDatum perStakedGTs pk Nothing [])
. newCosigners
-- | Create a 'TxInfo' that tries to cosign a proposal with new cosigners. -- | Create a 'TxInfo' that tries to cosign a proposal with new cosigners.
cosign :: forall b. CombinableBuilder b => Parameters -> b cosign :: forall b. CombinableBuilder b => Parameters -> b
@ -172,7 +175,9 @@ cosign ps = builder
, withValue stakeValue , withValue stakeValue
, withDatum stakeOutputDatum , withDatum stakeOutputDatum
] ]
, signedWith stakeDatum.owner , case stakeDatum.owner of
PubKeyCredential k -> signedWith k
_ -> mempty
] ]
) )
$ zip $ zip
@ -239,7 +244,7 @@ mkStakeRef idx =
-- | Create a proposal redeemer which cosigns with the new cosginers. -- | Create a proposal redeemer which cosigns with the new cosginers.
mkProposalRedeemer :: Parameters -> ProposalRedeemer mkProposalRedeemer :: Parameters -> ProposalRedeemer
mkProposalRedeemer (sort . newCosigners -> cs) = Cosign cs mkProposalRedeemer = Cosign . sort . newCosigners
-- | Stake redeemer for cosuming all the stakes generated in the module. -- | Stake redeemer for cosuming all the stakes generated in the module.
stakeRedeemer :: StakeRedeemer stakeRedeemer :: StakeRedeemer
@ -252,7 +257,7 @@ validCosignNParameters :: Int -> Parameters
validCosignNParameters n validCosignNParameters n
| n > 0 = | n > 0 =
Parameters Parameters
{ newCosigners = take n pubKeyHashes { newCosigners = take n (fmap PubKeyCredential pubKeyHashes)
, proposalStatus = Draft , proposalStatus = Draft
, alterOutputStakes = False , alterOutputStakes = False
} }
@ -266,7 +271,7 @@ validCosignNParameters n
duplicateCosignersParameters :: Parameters duplicateCosignersParameters :: Parameters
duplicateCosignersParameters = duplicateCosignersParameters =
Parameters Parameters
{ newCosigners = [proposalCreator] { newCosigners = [PubKeyCredential proposalCreator]
, proposalStatus = Draft , proposalStatus = Draft
, alterOutputStakes = False , alterOutputStakes = False
} }
@ -281,7 +286,7 @@ statusNotDraftCosignNParameters n =
map map
( \st -> ( \st ->
Parameters Parameters
{ newCosigners = take n pubKeyHashes { newCosigners = take n (fmap PubKeyCredential pubKeyHashes)
, proposalStatus = st , proposalStatus = st
, alterOutputStakes = False , alterOutputStakes = False
} }

View file

@ -61,9 +61,9 @@ import Plutarch.Context (
) )
import PlutusLedgerApi.V1.Value qualified as Value import PlutusLedgerApi.V1.Value qualified as Value
import PlutusLedgerApi.V2 ( import PlutusLedgerApi.V2 (
Credential (PubKeyCredential),
POSIXTime (POSIXTime), POSIXTime (POSIXTime),
POSIXTimeRange, POSIXTimeRange,
PubKeyHash,
TxOutRef (TxOutRef), TxOutRef (TxOutRef),
always, always,
) )
@ -121,14 +121,14 @@ stakedGTs :: Tagged _ Integer
stakedGTs = 5 stakedGTs = 5
-- | The owner of the stake. -- | The owner of the stake.
stakeOwner :: PubKeyHash stakeOwner :: Credential
stakeOwner = signer stakeOwner = PubKeyCredential signer
{- | The invalid stake owner. If the 'alterOutputStakeOwner' is set to true, {- | The invalid stake owner. If the 'alterOutputStakeOwner' is set to true,
the output stake owner will be set to this. the output stake owner will be set to this.
-} -}
alteredStakeOwner :: PubKeyHash alteredStakeOwner :: Credential
alteredStakeOwner = signer2 alteredStakeOwner = PubKeyCredential signer2
-- | Locks the stake that the input stake already has. -- | Locks the stake that the input stake already has.
defLocks :: [ProposalLock] defLocks :: [ProposalLock]
@ -247,7 +247,7 @@ mkProposalStartingTime ps =
else ProposalStartingTime 0 else ProposalStartingTime 0
-- | Who should be the 'owner' of the output stake. -- | Who should be the 'owner' of the output stake.
mkOwner :: Parameters -> PubKeyHash mkOwner :: Parameters -> Credential
mkOwner ps = mkOwner ps =
if ps.alterOutputStakeOwner if ps.alterOutputStakeOwner
then alteredStakeOwner then alteredStakeOwner
@ -288,7 +288,9 @@ createProposal ps = builder
withSig = withSig =
if ps.stakeOwnerSignsTheTransaction if ps.stakeOwnerSignsTheTransaction
then signedWith stakeOwner then case stakeOwner of
PubKeyCredential sig -> signedWith sig
_ -> mempty
else mempty else mempty
--- ---

View file

@ -52,6 +52,7 @@ import Plutarch.Context (
) )
import PlutusLedgerApi.V1.Value qualified as Value import PlutusLedgerApi.V1.Value qualified as Value
import PlutusLedgerApi.V2 ( import PlutusLedgerApi.V2 (
Credential (PubKeyCredential),
PubKeyHash, PubKeyHash,
TxOutRef (..), TxOutRef (..),
) )
@ -175,7 +176,7 @@ mkStakeInputDatum :: Parameters -> StakeDatum
mkStakeInputDatum ps = mkStakeInputDatum ps =
StakeDatum StakeDatum
{ stakedAmount = defStakedGTs { stakedAmount = defStakedGTs
, owner = defOwner , owner = PubKeyCredential defOwner
, delegatedTo = Nothing , delegatedTo = Nothing
, lockedBy = mkInputStakeLocks ps , lockedBy = mkInputStakeLocks ps
} }
@ -214,7 +215,7 @@ mkProposalDatumPair params pid =
{ proposalId = pid { proposalId = pid
, effects = emptyEffectFor votesTemplate , effects = emptyEffectFor votesTemplate
, status = params.proposalStatus , status = params.proposalStatus
, cosigners = [defOwner] , cosigners = [PubKeyCredential defOwner]
, thresholds = def , thresholds = def
, votes = inputVotes , votes = inputVotes
, timingConfig = def , timingConfig = def

View file

@ -45,6 +45,7 @@ import Plutarch.Context (
) )
import PlutusLedgerApi.V1.Value qualified as Value import PlutusLedgerApi.V1.Value qualified as Value
import PlutusLedgerApi.V2 ( import PlutusLedgerApi.V2 (
Credential (PubKeyCredential),
PubKeyHash, PubKeyHash,
TxOutRef (TxOutRef), TxOutRef (TxOutRef),
) )
@ -109,7 +110,7 @@ proposalInputDatum =
, (ResultTag 1, AssocMap.empty) , (ResultTag 1, AssocMap.empty)
] ]
, status = VotingReady , status = VotingReady
, cosigners = [stakeOwner] , cosigners = [PubKeyCredential stakeOwner]
, thresholds = def , thresholds = def
, votes = ProposalVotes initialVotes , votes = ProposalVotes initialVotes
, timingConfig = def , timingConfig = def
@ -133,10 +134,10 @@ mkStakeInputDatum :: Parameters -> StakeDatum
mkStakeInputDatum params = mkStakeInputDatum params =
StakeDatum StakeDatum
{ stakedAmount = Tagged params.voteCount { stakedAmount = Tagged params.voteCount
, owner = stakeOwner , owner = PubKeyCredential stakeOwner
, delegatedTo = , delegatedTo =
if params.voteAsDelegate if params.voteAsDelegate
then Just delegate then Just (PubKeyCredential delegate)
else Nothing else Nothing
, lockedBy = existingLocks , lockedBy = existingLocks
} }

View file

@ -47,6 +47,7 @@ import PlutusLedgerApi.V1.Value qualified as Value (
singleton, singleton,
) )
import PlutusLedgerApi.V2 ( import PlutusLedgerApi.V2 (
Credential (PubKeyCredential),
Datum (Datum), Datum (Datum),
ScriptContext (..), ScriptContext (..),
ScriptPurpose (Minting), ScriptPurpose (Minting),
@ -68,7 +69,7 @@ stakeCreation :: ScriptContext
stakeCreation = stakeCreation =
let st = Value.assetClassValue stakeAssetClass 1 -- Stake ST let st = Value.assetClassValue stakeAssetClass 1 -- Stake ST
datum :: StakeDatum datum :: StakeDatum
datum = StakeDatum 424242424242 signer Nothing [] datum = StakeDatum 424242424242 (PubKeyCredential signer) Nothing []
builder :: MintingBuilder builder :: MintingBuilder
builder = builder =
@ -90,7 +91,7 @@ stakeCreation =
stakeCreationWrongDatum :: ScriptContext stakeCreationWrongDatum :: ScriptContext
stakeCreationWrongDatum = stakeCreationWrongDatum =
let datum :: Datum let datum :: Datum
datum = Datum (toBuiltinData $ StakeDatum 4242424242424242 signer Nothing []) -- Too much GT datum = Datum (toBuiltinData $ StakeDatum 4242424242424242 (PubKeyCredential signer) Nothing []) -- Too much GT
in ScriptContext in ScriptContext
{ scriptContextTxInfo = stakeCreation.scriptContextTxInfo {txInfoData = AssocMap.fromList [("", datum)]} { scriptContextTxInfo = stakeCreation.scriptContextTxInfo {txInfoData = AssocMap.fromList [("", datum)]}
, scriptContextPurpose = Minting stakeSymbol , scriptContextPurpose = Minting stakeSymbol
@ -122,7 +123,7 @@ stakeDepositWithdraw :: DepositWithdrawExample -> ScriptContext
stakeDepositWithdraw config = stakeDepositWithdraw config =
let st = Value.assetClassValue stakeAssetClass 1 -- Stake ST let st = Value.assetClassValue stakeAssetClass 1 -- Stake ST
stakeBefore :: StakeDatum stakeBefore :: StakeDatum
stakeBefore = StakeDatum config.startAmount signer Nothing [] stakeBefore = StakeDatum config.startAmount (PubKeyCredential signer) Nothing []
stakeAfter :: StakeDatum stakeAfter :: StakeDatum
stakeAfter = stakeBefore {stakedAmount = stakeBefore.stakedAmount + config.delta} stakeAfter = stakeBefore {stakedAmount = stakeBefore.stakedAmount + config.delta}

View file

@ -41,6 +41,7 @@ import Plutarch.Context (
) )
import PlutusLedgerApi.V1.Value qualified as Value import PlutusLedgerApi.V1.Value qualified as Value
import PlutusLedgerApi.V2 ( import PlutusLedgerApi.V2 (
Credential (PubKeyCredential),
PubKeyHash, PubKeyHash,
ScriptContext, ScriptContext,
TxOutRef (TxOutRef), TxOutRef (TxOutRef),
@ -73,7 +74,7 @@ data Parameters = Parameters
-- | Select the correct stake redeemer based on the existence of the new delegate. -- | Select the correct stake redeemer based on the existence of the new delegate.
mkStakeRedeemer :: Parameters -> StakeRedeemer mkStakeRedeemer :: Parameters -> StakeRedeemer
mkStakeRedeemer (newDelegate -> d) = maybe ClearDelegate DelegateTo d mkStakeRedeemer = maybe ClearDelegate (DelegateTo . PubKeyCredential) . newDelegate
-- | The owner of the input stake. -- | The owner of the input stake.
stakeOwner :: PubKeyHash stakeOwner :: PubKeyHash
@ -84,8 +85,8 @@ mkStakeInputDatum :: Parameters -> StakeDatum
mkStakeInputDatum ps = mkStakeInputDatum ps =
StakeDatum StakeDatum
{ stakedAmount = 5 { stakedAmount = 5
, owner = stakeOwner , owner = PubKeyCredential stakeOwner
, delegatedTo = ps.existingDelegate , delegatedTo = PubKeyCredential <$> ps.existingDelegate
, lockedBy = [] , lockedBy = []
} }
@ -105,12 +106,14 @@ setDelegate ps = buildSpending' builder
else stakeInput.stakedAmount else stakeInput.stakedAmount
in stakeInput in stakeInput
{ stakedAmount = stakedAmount { stakedAmount = stakedAmount
, delegatedTo = ps.newDelegate , delegatedTo = PubKeyCredential <$> ps.newDelegate
} }
signer = signer =
if ps.signedByOwner if ps.signedByOwner
then stakeInput.owner then case stakeInput.owner of
PubKeyCredential c -> c
_ -> signer2
else signer2 else signer2
st = Value.assetClassValue stakeAssetClass 1 -- Stake ST st = Value.assetClassValue stakeAssetClass 1 -- Stake ST

View file

@ -16,6 +16,7 @@ import Agora.Stake (
) )
import Data.Bool (Bool (..)) import Data.Bool (Bool (..))
import Data.Maybe (Maybe (..)) import Data.Maybe (Maybe (..))
import PlutusLedgerApi.V1 (Credential (PubKeyCredential))
import Sample.Shared (agoraScripts) import Sample.Shared (agoraScripts)
import Sample.Stake ( import Sample.Stake (
DepositWithdrawExample ( DepositWithdrawExample (
@ -68,19 +69,19 @@ specs =
[ validatorSucceedsWith [ validatorSucceedsWith
"stakeDepositWithdraw deposit" "stakeDepositWithdraw deposit"
agoraScripts.compiledStakeValidator agoraScripts.compiledStakeValidator
(StakeDatum 100_000 signer Nothing []) (StakeDatum 100_000 (PubKeyCredential signer) Nothing [])
(DepositWithdraw 100_000) (DepositWithdraw 100_000)
(Stake.stakeDepositWithdraw $ DepositWithdrawExample {startAmount = 100_000, delta = 100_000}) (Stake.stakeDepositWithdraw $ DepositWithdrawExample {startAmount = 100_000, delta = 100_000})
, validatorSucceedsWith , validatorSucceedsWith
"stakeDepositWithdraw withdraw" "stakeDepositWithdraw withdraw"
agoraScripts.compiledStakeValidator agoraScripts.compiledStakeValidator
(StakeDatum 100_000 signer Nothing []) (StakeDatum 100_000 (PubKeyCredential signer) Nothing [])
(DepositWithdraw $ negate 100_000) (DepositWithdraw $ negate 100_000)
(Stake.stakeDepositWithdraw $ DepositWithdrawExample {startAmount = 100_000, delta = negate 100_000}) (Stake.stakeDepositWithdraw $ DepositWithdrawExample {startAmount = 100_000, delta = negate 100_000})
, validatorFailsWith , validatorFailsWith
"stakeDepositWithdraw negative GT" "stakeDepositWithdraw negative GT"
agoraScripts.compiledStakeValidator agoraScripts.compiledStakeValidator
(StakeDatum 100_000 signer Nothing []) (StakeDatum 100_000 (PubKeyCredential signer) Nothing [])
(DepositWithdraw 1_000_000) (DepositWithdraw 1_000_000)
(Stake.stakeDepositWithdraw $ DepositWithdrawExample {startAmount = 100_000, delta = negate 1_000_000}) (Stake.stakeDepositWithdraw $ DepositWithdrawExample {startAmount = 100_000, delta = negate 1_000_000})
, group , group

View file

@ -145,6 +145,7 @@ library
Agora.Aeson.Orphans Agora.Aeson.Orphans
Agora.AuthorityToken Agora.AuthorityToken
Agora.Bootstrap Agora.Bootstrap
Agora.Credential
Agora.Effect Agora.Effect
Agora.Effect.GovernorMutation Agora.Effect.GovernorMutation
Agora.Effect.NoOp Agora.Effect.NoOp

66
agora/Agora/Credential.hs Normal file
View file

@ -0,0 +1,66 @@
{- |
Module : Agora.Stake.Scripts
Maintainer : emi@haskell.fyi
Description: Functions for dealing with generalized credentials.
Functions for dealing with generalized credentials.
-}
module Agora.Credential (PAuthorizationCredential, AuthorizationCredential, pauthorizedBy, authorizationContext) where
import GHC.Records (HasField)
import Plutarch.Api.V1 (PCredential (..), PPubKeyHash)
import Plutarch.Api.V2 (PTxInInfo (..))
import Plutarch.Extra.ScriptContext (ptxSignedBy)
import Plutarch.Extra.TermCont (pmatchC)
import PlutusLedgerApi.V2 (Credential)
type AuthorizationCredential =
Credential
type PAuthorizationCredential =
PCredential
data PAuthorizationContext (s :: S) = PAuthorizationContext
{ signatories :: Term s (PBuiltinList (PAsData PPubKeyHash))
, inputs :: Term s (PBuiltinList PTxInInfo)
}
deriving stock
( -- | @since 0.2.0
Generic
)
deriving anyclass
( -- | @since 0.2.0
PlutusType
, -- | @since 0.2.0
PEq
)
instance DerivePlutusType PAuthorizationContext where
type DPTStrat _ = PlutusTypeScott
authorizationContext ::
forall {r} {s :: S}.
( HasField "inputs" r (Term s (PBuiltinList PTxInInfo))
, HasField "signatories" r (Term s (PBuiltinList (PAsData PPubKeyHash)))
) =>
r ->
Term s PAuthorizationContext
authorizationContext f =
pcon (PAuthorizationContext f.signatories f.inputs)
pauthorizedBy :: forall (s :: S). Term s (PAuthorizationContext :--> PAuthorizationCredential :--> PBool)
pauthorizedBy = phoistAcyclic $
plam $ \ctx credential -> unTermCont $ do
ctxF <- pmatchC ctx
pure $
pmatch credential $ \case
PPubKeyCredential ((pfield @"_0" #) -> pk) ->
ptxSignedBy # ctxF.signatories # pk
PScriptCredential ((pfield @"_0" #) -> _) ->
pany
# plam
( \input ->
(pfield @"credential" #$ pfield @"address" #$ pfield @"resolved" # input)
#== credential
)
# ctxF.inputs

View file

@ -42,6 +42,7 @@ module Agora.Proposal (
pisProposalThresholdsValid, pisProposalThresholdsValid,
) where ) where
import Agora.Credential (AuthorizationCredential, PAuthorizationCredential)
import Agora.Plutarch.Orphans () import Agora.Plutarch.Orphans ()
import Agora.Proposal.Time ( import Agora.Proposal.Time (
PProposalStartingTime, PProposalStartingTime,
@ -58,7 +59,6 @@ import Plutarch.Api.V2 (
KeyGuarantees (Unsorted), KeyGuarantees (Unsorted),
PDatumHash, PDatumHash,
PMaybeData, PMaybeData,
PPubKeyHash,
PScriptHash, PScriptHash,
PTuple, PTuple,
) )
@ -85,7 +85,7 @@ import Plutarch.Lift (
) )
import Plutarch.SafeMoney (PDiscrete (..)) import Plutarch.SafeMoney (PDiscrete (..))
import Plutarch.Show (PShow (..)) import Plutarch.Show (PShow (..))
import PlutusLedgerApi.V2 (DatumHash, PubKeyHash, ScriptHash, ValidatorHash) import PlutusLedgerApi.V2 (Credential, DatumHash, ScriptHash, ValidatorHash)
import PlutusTx qualified import PlutusTx qualified
import PlutusTx.AssocMap qualified as AssocMap import PlutusTx.AssocMap qualified as AssocMap
@ -299,7 +299,7 @@ data ProposalDatum = ProposalDatum
-- ^ Effect lookup table. First by result, then by effect hash. -- ^ Effect lookup table. First by result, then by effect hash.
, status :: ProposalStatus , status :: ProposalStatus
-- ^ The status the proposal is in. -- ^ The status the proposal is in.
, cosigners :: [PubKeyHash] , cosigners :: [Credential]
-- ^ Who created the proposal initially, and who cosigned it later. -- ^ Who created the proposal initially, and who cosigned it later.
-- --
-- This list should be sorted in **ascending** order. -- This list should be sorted in **ascending** order.
@ -347,7 +347,7 @@ data ProposalRedeemer
-- provided enough GT is shared among them. -- provided enough GT is shared among them.
-- --
-- This list should be sorted in ascending order. -- This list should be sorted in ascending order.
Cosign [PubKeyHash] Cosign [AuthorizationCredential]
| -- | Allow unlocking one or more stakes with votes towards particular 'ResultTag'. | -- | Allow unlocking one or more stakes with votes towards particular 'ResultTag'.
Unlock Unlock
| -- | Advance the proposal, performing the required checks for whether that is legal. | -- | Advance the proposal, performing the required checks for whether that is legal.
@ -617,7 +617,7 @@ newtype PProposalDatum (s :: S) = PProposalDatum
'[ "proposalId" ':= PProposalId '[ "proposalId" ':= PProposalId
, "effects" ':= PMap 'Unsorted PResultTag PProposalEffectGroup , "effects" ':= PMap 'Unsorted PResultTag PProposalEffectGroup
, "status" ':= PProposalStatus , "status" ':= PProposalStatus
, "cosigners" ':= PBuiltinList (PAsData PPubKeyHash) , "cosigners" ':= PBuiltinList (PAsData PAuthorizationCredential)
, "thresholds" ':= PProposalThresholds , "thresholds" ':= PProposalThresholds
, "votes" ':= PProposalVotes , "votes" ':= PProposalVotes
, "timingConfig" ':= PProposalTimingConfig , "timingConfig" ':= PProposalTimingConfig
@ -656,7 +656,7 @@ deriving via (DerivePConstantViaDataList ProposalDatum PProposalDatum) instance
-} -}
data PProposalRedeemer (s :: S) data PProposalRedeemer (s :: S)
= PVote (Term s (PDataRecord '["resultTag" ':= PResultTag])) = PVote (Term s (PDataRecord '["resultTag" ':= PResultTag]))
| PCosign (Term s (PDataRecord '["newCosigners" ':= PBuiltinList (PAsData PPubKeyHash)])) | PCosign (Term s (PDataRecord '["newCosigners" ':= PBuiltinList (PAsData PAuthorizationCredential)]))
| PUnlock (Term s (PDataRecord '[])) | PUnlock (Term s (PDataRecord '[]))
| PAdvanceProposal (Term s (PDataRecord '[])) | PAdvanceProposal (Term s (PDataRecord '[]))
deriving stock deriving stock

View file

@ -10,6 +10,7 @@ module Agora.Proposal.Scripts (
proposalPolicy, proposalPolicy,
) where ) where
import Agora.Credential (PAuthorizationCredential, authorizationContext, pauthorizedBy)
import Agora.Proposal ( import Agora.Proposal (
PProposalDatum (PProposalDatum), PProposalDatum (PProposalDatum),
PProposalRedeemer (..), PProposalRedeemer (..),
@ -45,7 +46,6 @@ import Agora.Utils (
import Plutarch.Api.V2 ( import Plutarch.Api.V2 (
PDatumHash, PDatumHash,
PMintingPolicy, PMintingPolicy,
PPubKeyHash,
PScriptContext (PScriptContext), PScriptContext (PScriptContext),
PScriptPurpose (PMinting, PSpending), PScriptPurpose (PMinting, PSpending),
PTxInfo (PTxInfo), PTxInfo (PTxInfo),
@ -63,7 +63,6 @@ import Plutarch.Extra.Record (mkRecordConstr, (.&), (.=))
import Plutarch.Extra.ScriptContext ( import Plutarch.Extra.ScriptContext (
pfindTxInByTxOutRef, pfindTxInByTxOutRef,
pisTokenSpent, pisTokenSpent,
ptxSignedBy,
) )
import Plutarch.Extra.TermCont ( import Plutarch.Extra.TermCont (
pguardC, pguardC,
@ -192,7 +191,7 @@ proposalValidator as maximumCosigners =
let stCurrencySymbol = pconstant $ proposalSTSymbol as let stCurrencySymbol = pconstant $ proposalSTSymbol as
signedBy <- pletC $ ptxSignedBy # txInfoF.signatories authorizedBy <- pletC $ pauthorizedBy # authorizationContext txInfoF
currentTime <- pletC $ currentProposalTime # txInfoF.validRange currentTime <- pletC $ currentProposalTime # txInfoF.validRange
@ -300,7 +299,7 @@ proposalValidator as maximumCosigners =
Term Term
_ _
( ( PInteger ( ( PInteger
:--> PBuiltinList (PAsData PPubKeyHash) :--> PBuiltinList (PAsData PAuthorizationCredential)
:--> PUnit :--> PUnit
) )
:--> PUnit :--> PUnit
@ -380,11 +379,11 @@ proposalValidator as maximumCosigners =
pure $ validationLogic # stakeIn # stakeOut # stakeUnchanged pure $ validationLogic # stakeIn # stakeOut # stakeUnchanged
let withMultipleStakes val = let withMultipleStakes val =
withMultipleStakes' #$ plam $ withMultipleStakes'
\totalStakedAmount #$ plam
sortedStakeOwner -> $ \totalStakedAmount sortedStakeOwner ->
unTermCont $ unTermCont $
val totalStakedAmount sortedStakeOwner val totalStakedAmount sortedStakeOwner
withSingleStake val = withSingleStake val =
withSingleStake' #$ plam $ \stakeIn stakeOut stakeUnchange -> unTermCont $ do withSingleStake' #$ plam $ \stakeIn stakeOut stakeUnchange -> unTermCont $ do
@ -402,7 +401,7 @@ proposalValidator as maximumCosigners =
newSigs <- pletC $ pfield @"newCosigners" # r newSigs <- pletC $ pfield @"newCosigners" # r
pguardC "Signed by all new cosigners" $ pguardC "Signed by all new cosigners" $
pall # signedBy # newSigs pall # plam ((authorizedBy #) . pfromData) # newSigs
updatedSigs <- updatedSigs <-
pletC $ pletC $

View file

@ -34,9 +34,9 @@ import Agora.Proposal (PProposalId, PResultTag, ProposalId (..), ResultTag (..))
import Agora.SafeMoney (GTTag) import Agora.SafeMoney (GTTag)
import Data.Tagged (Tagged (..)) import Data.Tagged (Tagged (..))
import Generics.SOP qualified as SOP import Generics.SOP qualified as SOP
import Plutarch.Api.V1 (PCredential)
import Plutarch.Api.V2 ( import Plutarch.Api.V2 (
PMaybeData, PMaybeData,
PPubKeyHash,
) )
import Plutarch.DataRepr ( import Plutarch.DataRepr (
DerivePConstantViaData (..), DerivePConstantViaData (..),
@ -52,7 +52,7 @@ import Plutarch.Extra.Traversable (pfoldMap)
import Plutarch.Lift (PConstantDecl, PUnsafeLiftDecl (..)) import Plutarch.Lift (PConstantDecl, PUnsafeLiftDecl (..))
import Plutarch.SafeMoney (PDiscrete) import Plutarch.SafeMoney (PDiscrete)
import Plutarch.Show (PShow (..)) import Plutarch.Show (PShow (..))
import PlutusLedgerApi.V1 (PubKeyHash) import PlutusLedgerApi.V1 (Credential)
import PlutusTx qualified import PlutusTx qualified
import Prelude hiding (Num (..)) import Prelude hiding (Num (..))
@ -148,7 +148,7 @@ data StakeRedeemer
WitnessStake WitnessStake
| -- | The owner can delegate the stake to another user, allowing the | -- | The owner can delegate the stake to another user, allowing the
-- delegate to vote on prooposals with the stake. -- delegate to vote on prooposals with the stake.
DelegateTo PubKeyHash DelegateTo Credential
| -- | Revoke the existing delegation. | -- | Revoke the existing delegation.
ClearDelegate ClearDelegate
deriving stock deriving stock
@ -177,12 +177,12 @@ data StakeDatum = StakeDatum
{ stakedAmount :: Tagged GTTag Integer { stakedAmount :: Tagged GTTag Integer
-- ^ Tracks the amount of governance token staked in the datum. -- ^ Tracks the amount of governance token staked in the datum.
-- This also acts as the voting weight for 'Agora.Proposal.Proposal's. -- This also acts as the voting weight for 'Agora.Proposal.Proposal's.
, owner :: PubKeyHash , owner :: Credential
-- ^ The hash of the public key this stake belongs to. -- ^ The hash of the public key this stake belongs to.
-- --
-- TODO Support for MultiSig/Scripts is tracked here: -- TODO Support for MultiSig/Scripts is tracked here:
-- https://github.com/Liqwid-Labs/agora/issues/45 -- https://github.com/Liqwid-Labs/agora/issues/45
, delegatedTo :: Maybe PubKeyHash , delegatedTo :: Maybe Credential
-- ^ To whom this stake has been delegated. -- ^ To whom this stake has been delegated.
, lockedBy :: [ProposalLock] , lockedBy :: [ProposalLock]
-- ^ The current proposals locking this stake. This field must be empty -- ^ The current proposals locking this stake. This field must be empty
@ -218,8 +218,8 @@ newtype PStakeDatum (s :: S) = PStakeDatum
s s
( PDataRecord ( PDataRecord
'[ "stakedAmount" ':= PDiscrete GTTag '[ "stakedAmount" ':= PDiscrete GTTag
, "owner" ':= PPubKeyHash , "owner" ':= PCredential
, "delegatedTo" ':= PMaybeData (PAsData PPubKeyHash) , "delegatedTo" ':= PMaybeData (PAsData PCredential)
, "lockedBy" ':= PBuiltinList (PAsData PProposalLock) , "lockedBy" ':= PBuiltinList (PAsData PProposalLock)
] ]
) )
@ -265,7 +265,7 @@ data PStakeRedeemer (s :: S)
| PPermitVote (Term s (PDataRecord '[])) | PPermitVote (Term s (PDataRecord '[]))
| PRetractVotes (Term s (PDataRecord '[])) | PRetractVotes (Term s (PDataRecord '[]))
| PWitnessStake (Term s (PDataRecord '[])) | PWitnessStake (Term s (PDataRecord '[]))
| PDelegateTo (Term s (PDataRecord '["pkh" ':= PPubKeyHash])) | PDelegateTo (Term s (PDataRecord '["pkh" ':= PCredential]))
| PClearDelegate (Term s (PDataRecord '[])) | PClearDelegate (Term s (PDataRecord '[]))
deriving stock deriving stock
( -- | @since 0.1.0 ( -- | @since 0.1.0

View file

@ -7,6 +7,7 @@ Plutus Scripts for Stakes.
-} -}
module Agora.Stake.Scripts (stakePolicy, stakeValidator) where module Agora.Stake.Scripts (stakePolicy, stakeValidator) where
import Agora.Credential (authorizationContext, pauthorizedBy)
import Agora.SafeMoney (GTTag) import Agora.SafeMoney (GTTag)
import Agora.Scripts (AgoraScripts, proposalSTAssetClass, stakeSTSymbol) import Agora.Scripts (AgoraScripts, proposalSTAssetClass, stakeSTSymbol)
import Agora.Stake ( import Agora.Stake (
@ -44,7 +45,7 @@ import Plutarch.Extra.Field (pletAllC)
import Plutarch.Extra.List (pmapMaybe, pmsortBy) import Plutarch.Extra.List (pmapMaybe, pmsortBy)
import Plutarch.Extra.Maybe (passertPJust, pdjust, pdnothing, pmaybeData) import Plutarch.Extra.Maybe (passertPJust, pdjust, pdnothing, pmaybeData)
import Plutarch.Extra.Record (mkRecordConstr, (.&), (.=)) import Plutarch.Extra.Record (mkRecordConstr, (.&), (.=))
import Plutarch.Extra.ScriptContext (pfindTxInByTxOutRef, ptxSignedBy, pvalueSpent) import Plutarch.Extra.ScriptContext (pfindTxInByTxOutRef, pvalueSpent)
import Plutarch.Extra.TermCont (pguardC, pletC, pletFieldsC, pmatchC, ptryFromC) import Plutarch.Extra.TermCont (pguardC, pletC, pletFieldsC, pmatchC, ptryFromC)
import Plutarch.Extra.Value ( import Plutarch.Extra.Value (
pgeqByClass', pgeqByClass',
@ -164,8 +165,8 @@ stakePolicy gtClassRef =
pvalueDiscrete' gtClassRef # outputF.value #== datumF.stakedAmount pvalueDiscrete' gtClassRef # outputF.value #== datumF.stakedAmount
let ownerSignsTransaction = let ownerSignsTransaction =
ptraceIfFalse "Stake Owner should sign the transaction" $ ptraceIfFalse "Stake Owner should sign the transaction" $
ptxSignedBy pauthorizedBy
# txInfoF.signatories # authorizationContext txInfoF
# datumF.owner # datumF.owner
pure $ hasExpectedStake #&& ownerSignsTransaction pure $ hasExpectedStake #&& ownerSignsTransaction
@ -263,15 +264,16 @@ stakeValidator as gtClassRef =
resolvedF <- pletFieldsC @'["address", "value", "datumHash"] resolved resolvedF <- pletFieldsC @'["address", "value", "datumHash"] resolved
-- Whether the owner signs this transaction or not. -- Whether the owner signs this transaction or not.
signedBy <- pletC $ ptxSignedBy # txInfoF.signatories signedBy <- pletC $ pauthorizedBy # authorizationContext txInfoF
ownerSignsTransaction <- pletC $ signedBy # stakeDatum.owner ownerSignsTransaction <- pletC $ signedBy # stakeDatum.owner
delegateSignsTransaction <- delegateSignsTransaction <-
pletC $ pletC $
pmaybeData # pconstant False pmaybeData
# signedBy # pconstant False
# stakeDatum.delegatedTo # plam ((signedBy #) . pfromData)
# pfromData stakeDatum.delegatedTo
stCurrencySymbol <- pletC $ pconstant $ stakeSTSymbol as stCurrencySymbol <- pletC $ pconstant $ stakeSTSymbol as
mintedST <- pletC $ psymbolValueOf # stCurrencySymbol # txInfoF.mint mintedST <- pletC $ psymbolValueOf # stCurrencySymbol # txInfoF.mint

1592
bench.csv

File diff suppressed because it is too large Load diff