Reference implementation of DRep Groups, a draft Cardano standard for recording which DReps belong to which group, party or council, directly on chain.
A group publishes its rules in transaction metadata under label 8416. DReps join and leave with their own signatures. Any indexer that follows the standard computes the same membership list from the chain alone, without trusting a website or a database.
This package holds the rules in code: it decodes the metadata, checks every signature against the group's policies and replays the chain into groups and memberships. Pure TypeScript, no network access, no platform dependency.
Status: draft. The CIP is open as cardano-foundation/CIPs pull request 1318, metadata label
8416will be registered in CIP-10 together with it, and the API can still change.
- Open groups: any registered DRep can join, anyone can leave at any time.
- Permissioned groups: joining needs approval by the group's admission policy, leaving is always possible without anyone's consent.
- Multisig from day one: a group is controlled by a native script (for example 3 of 5 admins). A separate admission policy can approve and remove members with its own threshold.
- Consent of listed admins: every key a group names in a policy must sign explicitly, as a
required_signersentry, when it is added to a role, so nobody can be shown as an admin without agreeing. A key can resign from its roles at any time. - Profile: name, description, website, logo, a link to the charter and optional payment addresses, stored as a CIP-100 document and referenced by hash.
- Website verification: a group can prove a domain through a well-known file.
The protocol records affiliation only: a group holds no voting power, casts no votes on chain and never changes a delegation. Members may agree to vote together, as a party or council would, and each of them still casts its own vote with its own DRep.
Every action is an ordinary transaction with a small metadata payload. There is no smart contract, no token and no deposit.
| Event | Signed by | Effect |
|---|---|---|
create |
every key of the new policies, in required_signers |
new open or permissioned group |
update |
control policy, plus every key new to its role, in required_signers |
new policies or profile |
dissolve |
control policy | group closed for good, all memberships end |
resign |
the resigning key, in required_signers |
the key leaves every role whose policy lists it |
join |
the DRep | member (open group) or pending request (permissioned) |
approve |
admission policy | pending request becomes a membership |
leave |
the DRep | membership or request ends, always allowed |
remove |
admission policy | membership or request ends (permissioned groups only) |
The rules this library enforces, in short:
- Signatures come from the transaction, the union of
required_signersand the vkey witnesses, and satisfy the policies. Consent is stricter: a key that consents (listed in a new policy, resigning, or a key-based DRep joining) must appear inrequired_signers, so its wallet signed knowingly. A vkey witness alone never counts as consent. - Policies need a signature: a control or admission policy that can be satisfied without any signature, for example with only a time lock, is rejected when it is set.
- Group ids are shown as bech32
drep_groupover 33 bytes, the transaction hash and a one byte event index. - Scripts must be on chain at or before the event that uses them, published in the payload or, for script DReps, in their registration transaction. A cache can never change a verdict.
- Chain order decides: block height, position in the block, certificates before metadata events. DRep registrations and retirements are part of the replay, a retirement ends every membership of that DRep.
- Control actions carry a sequence number, so a stale multisig transaction cannot apply on top of a newer change.
- Malformed data never stops an indexer: invalid events are ignored one by one, decoding works without recursion, and deeply nested values cannot crash it.
npm install drep-groupsESM only.
import { decodeTransaction, replay, type ChainInput } from 'drep-groups';
// 1. Every transaction with metadata label 8416, as full CBOR plus its position in the chain
const tx = decodeTransaction(cborBytes, { txHash, blockHeight, txIndex });
// 2. DRep registrations and retirements of every credential that appears in a join
const registration: ChainInput = {
kind: 'ledger',
input: { kind: 'reg', credential: { kind: 'key', hash: drepKeyHash }, txHash, blockHeight, txIndex, certIndex: 0 },
};
// 3. Replay in any order, the library sorts by chain order and drops duplicates
const state = replay([{ kind: 'tx', tx }, registration]);
state.groups; // groups with mode, policies, profile anchor, seq and status
state.instances; // memberships and requests: pending, active or closed with a reason
state.verdicts; // valid or invalid for every event, with a reason text
state.ignored; // transactions whose payload did not count, and whyreplay is pure. After a rollback, replay again without the rolled back inputs.
Any chain source works. With the public Koios API the inputs come from three calls:
GET /tx_by_metalabel?_label=8416&_after_block_height=<cursor>lists new transactions with the label.POST /tx_cborwith{"_tx_hashes": [...]}returns their full CBOR.POST /tx_infowith the same hashes returnstx_block_index, the position inside the block.
DRep registrations and retirements come from GET /drep_updates, the position of each certificate again from tx_info.
replay recomputes everything from all inputs. An indexer with a database can instead call runEngine after every sync: it applies only the new label transactions and credential inputs to your Store, in steps bounded by a budget, and recovers after rollbacks. MemoryStore is a complete in-memory implementation. A store of your own can run the contract checks of drep-groups/conformance (runSchedule with seeded chains), which compare the engine against replay. Ingest and opening a recovery never run while a runEngine call is in flight, so serialize them with your runs, for example under the same lease holder.
import { MemoryStore, runEngine } from 'drep-groups';
const store = new MemoryStore();
store.ingestLabelTx(tx); // label transactions
store.ingestLedgerRow(row); // DRep registrations and retirements
store.setFrontiers({ L: labelHeight, R: ledgerHeight }); // heights read completely so far
const lease = store.acquireLease('indexer');
const budget = { controlTxs: 50, controlBytes: 200_000, credentialUnits: 50, credentialInputs: 500, truncateRows: 1000, resetRows: 1000 };
let report;
do report = await runEngine(store, budget, lease);
while (report.more);The library also writes. encodePayload turns events into the exact bytes of the label 8416 value, so a tool never hand-writes CBOR. Every function here is pure and works offline.
import { encodePayload, majorityScript } from 'drep-groups';
const control = majorityScript([keyHashA, keyHashB, keyHashC], 2); // 2 of 3
const payload = encodePayload({
events: [
{ tag: 'create', mode: 'open', control: control.hash, admission: null, profile: { url, dataHash } },
{ tag: 'join', group: { local: 0 }, member: { kind: 'key', hash: founderKeyHash } },
],
scripts: [control.script],
});
// payload goes into the transaction's metadata under label 8416-
Events and limits:
encodePayloadtakes{ events, scripts? }and throwsEncodeErrorfor anything the decoder would ignore: no events or more than 64, more than 8 scripts, a script beyond the node or depth limit, malformed hashes, a mode that does not match the admission policy, an empty anchor URL. Long anchor URLs and scripts are split into 64 byte chunks for you (chunkText,chunkBytes).encodeNativeScript(script)gives the bytes to hash withnativeScriptHash,encodeCboris the small definite length writer underneath. -
Local references: a group does not exist before its
createis on chain, so the founding transaction refers to it as{ local: 0 }, the index of the earlier event in the same payload. The same works for founderjoinevents in the create transaction. A local reference must point to an earlier event. Everything after that transaction uses the full reference{ txHash, index }. -
Publish every new policy: put the script of every policy a
createorupdateintroduces intoscripts(key 2). The indexer can only judge a policy it has seen on chain, and a policy that appears in no payload and no registration makes the event invalid ("control policy unresolved" or "new control policy unresolved"). -
Consent: a
createneeds every key listed in its control and admission policies inrequired_signers. Anupdatethat sets a new policy needs every key new to that role inrequired_signers, on top of the current control policy. A key that stays in its role does not sign again, a key that moves from admission into control does, and a key that resigned from a role counts as new when a policy lists it again. A vkey witness does not replace therequired_signersentry. Add every consenting key asrequired_signersbefore submitting. -
Resign: a
resignevent names a key and needs only that key inrequired_signers, no control policy and noseq. The key leaves every role whose current policy lists it. Itssigcounts as false in that role from then on, andGroupStatelists it inresignedControlorresignedAdmission. A new policy for a role clears that role's resignations. A resign bumpsseq, so control actions prepared before it become stale. It is rejected for a key that is listed in no role, or already resigned from every role it is in. -
Policies that need no signature:
satisfiableWithoutSignature(script)tells whether a script can be satisfied by a time lock alone. Acreateorupdatethat sets such a policy is invalid. -
Script DReps and reference scripts: the member script of a script DRep comes from the witness scripts of its registration transaction or from a native script in a reference script of an output that transaction spends or uses as a reference input. Set
LedgerInput.referenceScriptsto thosescript_refvalues.decodeTxRefs(cbor)reads the script references of a transaction's outputs, a collateral return sits at indexoutputs.length. Plutus reference scripts resolve nothing. -
Majority scripts:
majorityScript(keys, n)returns an n of k script over key leaves as{ script, bytes, hash, keys }. Keys are lowercased, deduplicated and sorted ascending, so one key set and one threshold always give one script hash, whichever order the signers were collected in. It throwsEncodeErrorfor an invalid key or a threshold outside 1 to k. -
Approvals together with an update: one transaction can carry
approveevents and a controlupdate. Order the events with the approvals first, then the update, because events are judged in order and an approval after a policy change is checked against the new admission policy. The transaction must satisfy both policies, so collect the signatures of both. -
One control action at a time: control actions carry
seq. Read the group's currentseqfrom the index, build the action with it and wait for it to be included before building the next one. A second action prepared in parallel becomes stale as soon as the first one is included, and a stale event is ignored. Anupdatewith an empty change set only incrementsseq, which cancels pending control actions on purpose. -
Bind the content before signing: a signer should not trust a transaction because it came from the right tool.
inspectTransaction(cbor)returnsTxFacts: whether the auxiliary data hash in the body matches the metadata that is actually attached (auxHashMatches), how many label8416payloads it carries (groupPayloads) and whether it also holds certificates, withdrawals, votes or proposals. It throws a plainErroron malformed CBOR. Compare the decoded events with what the signer was told and refuse anything unexpected, for example a vote hidden next to a join. -
Preview before submit:
previewTransaction(deps, tx)judges every event of an unsubmitted transaction with the engine's own rules and writes nothing. It returns{ ignored }when the payload would not count at all, otherwise onePreviewEventper event withvalidand areason. The preview is exact oncerunEnginereportsmore: falsewith the ledger frontier at or above the label frontier. While the ledger frontier lags, membership events between the two are still pending and the verdicts are inconclusive.txis aChainTxfromdecodeTransaction: set its position after everything you have ingested and fillrequiredSignersand the vkey witnesses the final transaction will carry.depsreads your committed state:const preview = await previewTransaction({ load: (keys) => store.load(keys, []), // a bounded view of the committed state queuedJoins: (refs) => store.queuedJoins(refs, []), }, tx);
-
Profile context: the profile document is CIP-100 JSON-LD. Embed the context object inline in the profile document, copied from
context/drep-groups-v1.jsonldin the package. The GitHub URLhttps://github.com/katomm/cardano-drep-groups/blob/main/context/drep-groups-v1.jsonldserves only as the term namespace. It definesname,description,website,image,charterandpaymentAddresseswithaddress,purposeandpaymentScript. The anchor hash is blake2b-256 over the raw document bytes.
| Function | Purpose |
|---|---|
decodeTransaction(cbor, position) |
full Conway transaction to a ChainTx (signers, validity interval, raw label 8416 payload, witness scripts) |
replay(inputs) |
chain inputs to a RegistryState |
decodePayload(bytes) |
one payload to its events and published scripts, null when the payload is ignored |
parseNativeScript(bytes), evaluateNativeScript(script, ctx), collectKeyHashes(script) |
native scripts with exact CBOR types and ledger semantics |
checkPaymentAddress(entry, network, scripts) |
checks a profile payment address: invalid, declared or script-controlled |
groupIdToBech32(ref), groupIdFromBech32(s) |
display form of a group id, bech32 with prefix drep_group over 33 bytes (tx_hash and a one byte event index, so an index above 255 throws) |
nativeScriptHash(bytes), keyHashOfVkey(vkey) |
Cardano hashes |
refKey(ref), credKey(credential), orderInputs(inputs) |
helpers for keys and ordering |
encodePayload({ events, scripts? }) |
events and scripts to the label 8416 payload bytes, throws EncodeError on anything the decoder would ignore |
encodeNativeScript(script), encodeCbor(value), chunkText(s), chunkBytes(b) |
native script bytes, the definite length CBOR writer and the 64 byte chunking |
majorityScript(keys, n) |
n of k script over sorted, deduplicated key hashes with its bytes and hash |
inspectTransaction(cbor) |
TxFacts of a transaction: auxiliary data hash binding, label 8416 payload count, certificates, withdrawals, votes and proposals |
previewTransaction(deps, tx) |
every event of an unsubmitted transaction judged with the engine's rules over committed state, nothing written |
runEngine(store, budget, lease, opts?) |
one bounded incremental run over a Store: an open recovery, or new label transactions and credential inputs |
MemoryStore |
complete in-memory Store, with ingest hooks, frontiers, a lease and snapshot() |
effectiveClose(instance, dissolveAt, firstUnregAfterJoin, q?) |
when and why a membership ends: explicit close, dissolve or retirement, whichever comes first |
comparePos(a, b), endOf(height), posOfCert(input), posOfScripts(tx), posOfEvent(tx, index) |
total order of certificates, payload scripts and events |
scriptComplexity(script) |
node count and nesting depth of a native script, counted the way the payload limits count them |
memberScriptWitness(credential, witnessScripts, referenceScripts?) |
the member script a script DRep's registration proves through a witness or a native reference script, null when none matches |
decodeTxRefs(cbor) |
inputs, reference inputs and the script_ref of every output of a transaction, for filling LedgerInput.referenceScripts |
nativeScriptFromScriptRef(bytes) |
the native script inside a script_ref value, null for Plutus or malformed data |
satisfiableWithoutSignature(script) |
whether a native script can be satisfied with no signature |
drep-groups/conformance |
generateChain, generateSchedule and runSchedule: contract checks of a Store against replay |
All types are exported, among them ChainTx, LedgerInput, ChainInput, GroupState, Instance, EventVerdict and RegistryState.
Hex strings: every hash passed in and returned is lowercase hex without a prefix. Hashes are compared as strings, so lowercase hex from other sources before passing it in.
Ledger inputs must come from transactions with is_valid = true. The caller guarantees this.
checkPaymentAddress({ address, paymentScript }, network, state.scripts) returns a status:
invalid: not a bech32 address, wrong network, a pointer address or not a payment address. Do not show it.declared: a valid base or enterprise address without a proven controller.reasonsays why a payment script claim did not hold.script-controlled: the payment credential is a script, it equalspaymentScriptand the script is published on chain.scriptholds it for display, for example "3 of 5: Alice, Bob, ...".
hasStake is false for enterprise addresses, which cannot delegate their votes.
vectors/vectors.json (also importable as drep-groups/vectors/vectors.json) holds 50 scenarios with inputs and expected results: open and permissioned lifecycles, the consent rule, signature-free policies, resign, policy rotation, retirement and re-registration, certificate ordering, script DReps including reference scripts, time locks, malformed payloads, duplicate keys and deeply nested data.
Payloads are CBOR hex, so the file works for any language. An implementation passes when it produces the same groups and instances and the same valid flag for every verdict. Reason texts are informative. Compared groups include resignedControl and resignedAdmission. A ledger input can carry referenceScriptsHex: the raw script_ref values of the outputs that the registration transaction spends or uses as reference inputs, in any order, absent when empty. Only native scripts resolve a member script.
npm install
npm test # unit tests, differential tests and test vectors
npm run typecheck
npm run build # emits dist/
npm run vectors # regenerates vectors/vectors.json from vectors/definitions.tsExpected results in vectors/definitions.ts are written by hand from the specification. When a vector fails, check the case against the rules before changing either side.
Releases are tag driven and staged:
- Bump the version in a pull request with
npm version <patch|minor> --no-git-tag-versionand add a changelog entry. - After the squash merge, tag the merge commit
v<version>and push the tag. - The release workflow checks the tag against
package.jsonandmain, runs the tests and stages the package on npm with provenance. - A maintainer approves the staged version on npmjs.com with 2FA. The workflow also creates the GitHub release.