cometa: Idiomatic Haskell bindings to cardano-c

[ apache, blockchain, library, program ] [ Propose Tags ] [ Report a vulnerability ]

Haskell-owned Cardano values with transaction construction, signing, script evaluation and provider interfaces backed by cardano-c. Includes a Blockfrost provider.


[Skip to Readme]

Modules

[Index] [Quick Jump]

Flags

Manual Flags

NameDescriptionDefault
system-cardano-c

Link an installed cardano-c instead of the bundled source package.

Disabled

Use -f <flag> to enable a flag, or -f -<flag> to disable that flag. More info

Downloads

Maintainer's Corner

Package maintainers

For package maintainers and hackage trustees

Candidates

Versions [RSS] 0.2.0.0
Dependencies aeson (>=2.2 && <2.3), async (>=2.2 && <2.3), base (>=4.18 && <4.22), bech32 (>=1.1.10 && <1.2), bytestring (>=0.11 && <0.13), cardano-c-clib (==0.1.1.0), cborg (>=0.2.10 && <0.3), cometa, containers (>=0.6.7 && <0.8), crypton-x509-store (>=1.8 && <1.9), crypton-x509-system (>=1.8 && <1.9), directory (>=1.3 && <1.4), http-client (>=0.7.19 && <0.8), http-client-tls (>=0.3.6 && <0.4), http-types (>=0.12.3 && <0.13), network (>=3.2.12 && <3.3), network-uri (>=2.6.4 && <2.7), scientific (>=0.3.7 && <0.4), stm (>=2.5 && <2.6), text (>=2.0 && <2.2), tls (>=2.2 && <2.3), transformers (>=0.6 && <0.7) [details]
License Apache-2.0
Author Biglup Labs
Maintainer angel.castillob@protonmail.com
Uploaded by angelcastillob at 2026-11-26T19:25:26Z
Category Blockchain
Home page https://github.com/Biglup/cometa.hs
Bug tracker https://github.com/Biglup/cometa.hs/issues
Source repo head: git clone https://github.com/Biglup/cometa.hs.git
Distributions
Executables cometa-plutus-v4-guarded-subtransaction, cometa-deferred-withdraw-zero, cometa-propose-treasury-withdrawal, cometa-donate-to-treasury, cometa-vote-for-proposal-script, cometa-vote-for-proposal-pubkey, cometa-drep-script, cometa-drep-pubkey, cometa-reward-account-script, cometa-reward-account-pubkey, cometa-deferred-batch, cometa-deferred-self-index, cometa-spend-from-validator, cometa-spend-from-native-script, cometa-mint-burn-plutus-script, cometa-mint-burn-native-script, cometa-send-lovelace, cometa-sub-transaction-batch, cometa-sign-data, cometa-provider, cometa-secure-key-handler, cometa-bip39
Downloads 0 total (0 in the last 30 days)
Rating (no votes yet) [estimated by Bayesian average]
Your Rating
  • λ
  • λ
  • λ
Status Docs uploaded by user
Build status unknown [no reports yet]

Readme for cometa-0.2.0.0

[back to package description]
Cometa.hs

API documentation · Examples · User guide

Cometa.hs

Haskell bindings to cardano-c for building, signing and inspecting Cardano transactions. Compose immutable transaction plans, work with typed addresses, assets and credentials, and use Blockfrost, Koios, Kupmios or Hydra, or supply your own backend.

Pure validation returns Either Error; native operations and network requests return IO (Either Error a). Private keys stay inside explicit resource scopes.

Build · Send a payment · Explore the API · Run the examples

Build

Version 0.1.0.0 is available as a Hackage candidate.

The development version is 0.2.0.0 and uses cardano-c v2.0.0-rc.7 through cardano-c-clib 0.1.1.0. Protocol parameter 55 now uses parameterRefInputsCostPerMultiAssetByte and updateRefInputsCostPerMultiAssetByte. Use Builder.defaultConfig and set Builder.poolState to the latest registered pool parameters when estimating protocol-12 owner witnesses; prefer pending parameters over active ones. Unknown pools retain conservative estimates.

It is not yet in the main package index. To build this checkout, use GHC 9.6.7 or 9.10.3, Cabal and a C toolchain. Prepare the bundled native sources from the revision in native/cardano-c.ref:

python3 tools/package-native.py /path/to/pinned/cardano-c
cabal build all
cabal run cometa-bip39

See installation for platform requirements and linking an installed native library. Applications depend on cometa; Blockfrost is part of the same library.

Build, sign and submit a payment

The payment example reads a recipient and amount, unlocks the encrypted wallet, and runs the complete transaction lifecycle. Its local functions keep validation and wallet plumbing out of the main flow:

main :: IO ()
main = Support.entrypoint "SendLovelace" (runExceptT . payment)

payment :: WalletContext -> ExceptT Error IO Tx.Transaction
payment wallet = do
  output <- readPaymentOutput

  submitPlan (Support.context wallet) (Plan.payTo output)

submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction
submitPlan ctx plan = do
  unsignedTx <- buildTransaction ctx plan
  signedTx <- signTransaction ctx unsignedTx

  txId <- submitTransaction ctx signedTx
  awaitConfirmation ctx signedTx txId

  pure signedTx

These are local example functions, not an additional library API. Their implementations are in the same file: fetch current parameters and wallet inputs, build with Builder.build, sign with the scoped wallet, submit once, and wait for confirmation and wallet indexing. The wallet prompts for its password; runExceptT hands any failure to the runner once.

Explore the API

A Plan describes what a transaction should do. Compose requirements with (<>), then pass the whole plan to Builder.build. Output order is preserved; conflicting requirements and protocol constraints are checked when building.

The functions below use typed inputs: addresses parsed with Address.fromText, credentials derived from the wallet, and UTxOs resolved through a provider. The transaction recipes return plans; the payment workflow above shows how to build, sign and submit them. The final example inspects an existing transaction. Amounts are integer lovelace: 1 ADA = 1,000,000 lovelace.

Imports for the API examples
{-# LANGUAGE OverloadedStrings #-}

import qualified Cometa.Address as Address
import qualified Cometa.Address.Reward as Reward
import qualified Cometa.AssetId as Asset
import qualified Cometa.AssetName as AssetName
import qualified Cometa.Certificate as Certificate
import qualified Cometa.Credential as Credential
import Cometa.Error (Error (..))
import qualified Cometa.Governance.Action as Action
import qualified Cometa.Governance.ActionId as ActionId
import qualified Cometa.Governance.Anchor as Anchor
import qualified Cometa.Governance.DRep as DRep
import qualified Cometa.Governance.Voting as Voting
import qualified Cometa.Inspection as Inspection
import qualified Cometa.Metadata as Metadata
import qualified Cometa.PlutusData as Data
import qualified Cometa.PolicyId as Policy
import qualified Cometa.Script as Script
import qualified Cometa.Script.Native as Native
import qualified Cometa.SubTransaction as Sub
import qualified Cometa.Transaction as Tx
import qualified Cometa.Transaction.Datum as Datum
import qualified Cometa.Transaction.Indices as Indices
import qualified Cometa.Transaction.Output as Output
import qualified Cometa.Transaction.Plan as Plan
import qualified Cometa.Transaction.Utxo as Utxo
import qualified Cometa.Value as Value
import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)
import qualified Data.Aeson as Aeson
import Data.ByteString (ByteString)
import Data.Word (Word64)

Send ADA and native assets together

Pay two recipients, send tokens alongside ADA, and set an expiry slot. Output construction is pure; the builder checks minimum ADA and selects wallet inputs.

payments ::
  Address.Address ->
  Address.Address ->
  Asset.AssetId ->
  Word64 ->
  Either Error Plan.Plan
payments alice bob token expiry = do
  adaOutput <- Output.mkOutput alice (Value.lovelace 5000000) Datum.NoDatum Nothing

  let tokenValue = Value.lovelace 2000000 <> Value.singleton token 25
  tokenOutput <- Output.mkOutput bob tokenValue Datum.NoDatum Nothing

  pure $
    Plan.payTo adaOutput
      <> Plan.payTo tokenOutput
      <> Plan.validUntil expiry

Mint tokens and attach metadata

Build a native policy requiring the wallet's signature, derive its policy ID, mint 100 tokens and attach a text message under metadata label 674. Minted tokens can go to the builder's change output or an explicit Plan.payTo output.

mintTokens :: Credential.KeyHash Credential.Payment -> IO (Either Error Plan.Plan)
mintTokens paymentKey = runExceptT $ do
  let script = Script.Native (Native.signature paymentKey)
  scriptHash <- ExceptT (Script.hash script)

  name <- except (AssetName.fromText "CometaToken")
  message <- except (Metadata.mkText "Minted with Cometa.hs")
  messageKey <- except (Metadata.mkText "msg")

  let token = Asset.Native (Policy.fromScriptHash scriptHash) name
      metadata = Metadata.map [(messageKey, Metadata.list [message])]

  pure $
    Plan.attachScript script
      <> Plan.mint token 100
      <> Plan.metadata 674 metadata

A negative mint quantity burns tokens: Plan.mint token (-50). Plutus policies use Plan.mintWithRedeemer token quantity redeemer, together with an attached script or a reference input. See the complete native mint/burn and Plutus mint/burn examples for CIP-25 metadata and the confirmed mint → burn sequence.

Lock funds with an inline datum

Construct Plutus data in Haskell and attach it directly to a script output. Here, the datum is a constructor containing an order number and an amount; its shape must match the validator's schema.

lockFunds :: Address.Address -> Either Error Plan.Plan
lockFunds scriptAddress = do
  let order = Data.fromData (Data.Constr 0 [Data.Integer 42, Data.Integer 100])

  output <-
    Output.mkOutput
      scriptAddress
      (Value.lovelace 10000000)
      (Datum.InlineDatum order)
      Nothing

  pure (Plan.payTo output)

Spend through a reference script

Supply the resolved locked output, a UTxO carrying its validator, and the validator's expected redeemer. The plan references the deployed script instead of including another copy in its witnesses.

spendLocked ::
  Utxo.Utxo ->
  Utxo.Utxo ->
  Data.EncodedPlutusData ->
  Output.Output ->
  Plan.Plan
spendLocked locked validatorReference redeemer payout =
  Plan.referenceInput validatorReference
    <> Plan.spendWith locked (Just redeemer) Nothing
    <> Plan.payTo payout

Plutus builds need compatible protocol parameters, an evaluator and collateral in Builder.Config. The validator example shows the complete lock, confirm and spend workflow.

Compute a redeemer after balancing

Input ordering can change while the builder balances a transaction. A deferred redeemer receives the current draft and computes its argument from the final input position rather than guessing an index in advance.

spendWithOwnIndex :: Utxo.Utxo -> Script.Script -> Plan.Plan
spendWithOwnIndex locked validator =
  Plan.attachScript validator
    <> Plan.spendWithDeferredRedeemer locked ownIndex Nothing
  where
    ownIndex draft _ = do
      index <- case Indices.findInput (Utxo.input locked) draft of
        Nothing -> Left (InvalidBuildingRequest "Locked input is missing")
        Just position -> Right position

      pure (Data.fromData (Data.Constr 0 [Data.Integer (toInteger index)]))

Callbacks may run repeatedly during balancing and should remain pure. The self-index and order settlement examples provide matching validators and complete transactions. Deferred arguments also support minting, certificates, withdrawals, votes and proposals.

Register and delegate a stake credential

Combine registration, pool delegation and voting-power delegation in one plan. Supply the current key deposit from protocol parameters and a fresh, key-controlled stake credential.

registerStake ::
  Credential.Credential Credential.Stake ->
  Credential.KeyHash Credential.StakePool ->
  Word64 ->
  Plan.Plan
registerStake stake pool deposit =
  Plan.certificate (Certificate.Registration stake deposit)
    <> Plan.certificate (Certificate.StakeDelegation stake pool)
    <> Plan.certificate (Certificate.VoteDelegation stake DRep.AlwaysAbstain)

Later, withdraw the available rewards and reclaim the registration deposit. Use the reward account derived from the same stake credential, and supply the deposit recorded for its registration.

closeStake ::
  Reward.RewardAddress ->
  Credential.Credential Credential.Stake ->
  Word64 ->
  Word64 ->
  Plan.Plan
closeStake account stake rewards refund =
  Plan.withdraw account rewards
    <> Plan.certificate (Certificate.Unregistration stake refund)

See the key and script versions for querying rewards, supplying witnesses and confirming each stage.

Vote, donate and propose treasury withdrawals

A registered, key-controlled DRep can vote on an existing governance action and include a treasury donation in the same transaction.

voteAndDonate ::
  Credential.Credential Credential.DRep ->
  ActionId.ActionId ->
  Plan.Plan
voteAndDonate representative action =
  Plan.vote
    (Voting.DRepVoter representative)
    action
    (Voting.VotingProcedure Voting.Yes Nothing)
    <> Plan.donate 2000000

A treasury withdrawal is a proposal, not an immediate transfer. Its deposit comes from protocol parameters; the supplied anchor identifies the proposal's metadata. This version targets a constitution without a guardrails policy.

proposeWithdrawal ::
  Reward.RewardAddress ->
  Word64 ->
  Anchor.Anchor ->
  Either Error Plan.Plan
proposeWithdrawal returnAccount amount anchor = do
  withdrawals <- Action.withdrawalsFromList [(returnAccount, amount)]

  pure $
    Plan.propose
      returnAccount
      (Action.TreasuryWithdrawals withdrawals Nothing)
      anchor

The executable proposal example covers a constitution guardrails policy using a reference script. There are also complete DRep registration and script-authorized voting flows.

Batch independently signed subtransactions

Attach signed intents without changing their bytes or signatures. Each intent comes with its resolved spending and reference inputs; the outer transaction supplies the fee and any net funding deficit.

batchIntents ::
  Credential.Credential Credential.Guard ->
  [(Sub.SubTransaction, [Utxo.Utxo])] ->
  Plan.Plan
batchIntents batcher intents =
  foldMap (uncurry Plan.attachSubTransaction) intents
    <> Plan.requireGuard batcher

This requires a protocol-12+ network. The three-wallet exchange builds and signs the buyer and seller intents before the batcher submits them; the V4 example adds a script guard.

Decode and inspect transaction CBOR

Read an existing transaction and inspect its body, witnesses and other fields as JSON. Inspection does not sign, submit or establish ledger validity.

inspectTransaction :: ByteString -> IO (Either Error Aeson.Value)
inspectTransaction cbor = runExceptT $ do
  transaction <- except (Tx.decodeCbor cbor)
  ExceptT (Inspection.transaction transaction)

The API also exposes typed addresses, BIP39/BIP32 derivation, encrypted software key handlers, CIP-8 message signatures, CBOR codecs, transaction balancing and provider callbacks. Browse the API reference for their contracts and the runnable examples below for complete applications.

Providers

Use the same Cometa.Provider workflow with Blockfrost, Koios, Kupmios (Kupo + Ogmios), or an existing Hydra Head:

import qualified Cometa.Provider as Provider
import qualified Cometa.Provider.Koios as Koios

parameters <- Koios.withProvider (Koios.defaultConfig Koios.Preprod Nothing) $
  Provider.protocolParameters

Provider configuration and contracts cover credentials, explicit networks, bounded HTTP requests, and Hydra's L2 snapshot confirmation. Hydra has no remote evaluator or staking rewards; use a local evaluator for script transactions inside a Head.

Run the examples

Start by importing a recovery phrase into an encrypted wallet file. The terminal hides both the recovery phrase and password as you type:

cabal run cometa-secure-key-handler -- wallet.key
export COMETA_KEY_HANDLER_FILE="$PWD/wallet.key"
export COMETA_NETWORK=preprod
export BLOCKFROST_PROJECT_ID="your-preprod-project-id"

Set a current COMETA_INVALID_AFTER_SLOT, COMETA_RECIPIENT and COMETA_LOVELACE using the connected examples guide. Then run:

cabal run cometa-send-lovelace -- --describe
cabal run cometa-send-lovelace

Each transaction example shows its plan, build, sign, submit and confirmation steps in one file. Shared helpers handle wallet/provider setup. The examples prompt for the encrypted wallet password and submit on chain. Multi-stage examples confirm each transaction before continuing. --help prints usage without network requests.

Example What it demonstrates
BIP39 Recover keys and derive an address from a mnemonic.
Encrypted wallet Import a recovery phrase, encrypt, save and reopen a wallet.
Provider Query protocol parameters, UTxOs and rewards.
Send lovelace Build, sign, submit and confirm a payment.
Native mint/burn Mint tokens with CIP-25 metadata, then burn tokens.
Plutus mint/burn Mint and burn through a reference policy.
Native script spend Fund a script address, then spend its output.
Validator spend Lock funds and spend with a Plutus validator.
Deferred self index Compute a redeemer after input ordering is known.
Deferred batch Fund and settle two script orders.
Stake key / stake script Register, delegate, withdraw and deregister.
DRep key / DRep script Register a representative, delegate and clean up.
Key vote / script vote Register, vote on a proposal and deregister.
Treasury donation Donate ADA to the treasury.
Treasury withdrawal Submit a treasury withdrawal proposal.
Deferred withdrawal Forward input indexes through a withdrawal redeemer.
Subtransaction batch Three encrypted wallets sign and settle a buyer/seller exchange.
Guarded subtransaction Sign a guarded V4 intent and submit its enclosing batch.
Sign data Produce a CIP-8 message signature offline.

See the example index for Cabal commands and governance setup for required chain state. The batch and V4 examples require a network supporting protocol 12 or later. BIP39 and data-signing demos use public demonstration keys; never fund them.

Contributing

See development and coding conventions. Run cabal test all --test-show-details=direct and the configured formatter and linter before submitting changes.

Licensed under Apache-2.0. The bundled native dependency includes third-party components with their own notices.