cometa-0.2.0.0: README.md
<div align="center">
<img src="assets/cometa_hs.png" alt="Cometa.hs" width="320" />
[API documentation](https://hackage.haskell.org/package/cometa-0.1.0.0/candidate/docs/index.html) · [Examples](examples/README.md) · [User guide](https://cometahs.readthedocs.io/en/latest/)
</div>
# Cometa.hs
Haskell bindings to [cardano-c](https://github.com/Biglup/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](#build) · [Send a payment](#build-sign-and-submit-a-payment) ·
[Explore the API](#explore-the-api) · [Run the examples](#run-the-examples)
## Build
Version 0.1.0.0 is available as a [Hackage candidate](https://hackage.haskell.org/package/cometa-0.1.0.0/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`](native/cardano-c.ref):
```sh
python3 tools/package-native.py /path/to/pinned/cardano-c
cabal build all
cabal run cometa-bip39
```
See [installation](docs/userguide/installation.md) 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](examples/SendLovelace.hs) 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:
```haskell
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](examples/SendLovelace.hs): 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**.
<details>
<summary>Imports for the API examples</summary>
```haskell
{-# 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)
```
</details>
### 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.
```haskell
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.
```haskell
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](examples/MintBurnNativeScript.hs) and
[Plutus mint/burn](examples/MintBurnPlutusScript.hs) 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.
```haskell
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.
```haskell
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](examples/SpendFromValidator.hs)
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.
```haskell
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](examples/DeferredRedeemerSelfIndex.hs) and
[order settlement](examples/DeferredRedeemerBatch.hs) 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.
```haskell
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.
```haskell
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](examples/RewardAccountPubkey.hs) and
[script](examples/RewardAccountScript.hs) 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.
```haskell
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.
```haskell
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](examples/ProposeTreasuryWithdrawal.hs) covers
a constitution guardrails policy using a reference script. There are also
complete [DRep registration](examples/DRepPubkey.hs) and
[script-authorized voting](examples/VoteForProposalScript.hs) 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.
```haskell
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](examples/SubTransactionBatch.hs) builds and signs the
buyer and seller intents before the batcher submits them; the
[V4 example](examples/PlutusV4GuardedSubTransaction.hs) 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.
```haskell
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](https://hackage.haskell.org/package/cometa-0.1.0.0/candidate/docs/index.html)
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:
```haskell
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](docs/userguide/providers.md) 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:
```sh
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](docs/userguide/connected-examples.md).
Then run:
```sh
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](examples/Bip39.hs) | Recover keys and derive an address from a mnemonic. |
| [Encrypted wallet](examples/SecureKeyHandler.hs) | Import a recovery phrase, encrypt, save and reopen a wallet. |
| [Provider](examples/Provider.hs) | Query protocol parameters, UTxOs and rewards. |
| [Send lovelace](examples/SendLovelace.hs) | Build, sign, submit and confirm a payment. |
| [Native mint/burn](examples/MintBurnNativeScript.hs) | Mint tokens with CIP-25 metadata, then burn tokens. |
| [Plutus mint/burn](examples/MintBurnPlutusScript.hs) | Mint and burn through a reference policy. |
| [Native script spend](examples/SpendFromNativeScript.hs) | Fund a script address, then spend its output. |
| [Validator spend](examples/SpendFromValidator.hs) | Lock funds and spend with a Plutus validator. |
| [Deferred self index](examples/DeferredRedeemerSelfIndex.hs) | Compute a redeemer after input ordering is known. |
| [Deferred batch](examples/DeferredRedeemerBatch.hs) | Fund and settle two script orders. |
| [Stake key](examples/RewardAccountPubkey.hs) / [stake script](examples/RewardAccountScript.hs) | Register, delegate, withdraw and deregister. |
| [DRep key](examples/DRepPubkey.hs) / [DRep script](examples/DRepScript.hs) | Register a representative, delegate and clean up. |
| [Key vote](examples/VoteForProposalPubkey.hs) / [script vote](examples/VoteForProposalScript.hs) | Register, vote on a proposal and deregister. |
| [Treasury donation](examples/DonateToTreasury.hs) | Donate ADA to the treasury. |
| [Treasury withdrawal](examples/ProposeTreasuryWithdrawal.hs) | Submit a treasury withdrawal proposal. |
| [Deferred withdrawal](examples/DeferredWithdrawZero.hs) | Forward input indexes through a withdrawal redeemer. |
| [Subtransaction batch](examples/SubTransactionBatch.hs) | Three encrypted wallets sign and settle a buyer/seller exchange. |
| [Guarded subtransaction](examples/PlutusV4GuardedSubTransaction.hs) | Sign a guarded V4 intent and submit its enclosing batch. |
| [Sign data](examples/SignData.hs) | Produce a CIP-8 message signature offline. |
See the [example index](examples/README.md) for Cabal commands and
[governance setup](docs/userguide/connected-governance.md) 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](docs/userguide/development.md) and
[coding conventions](CODING_CONVENTIONS.md). Run `cabal test all
--test-show-details=direct` and the configured formatter and linter before
submitting changes.
Licensed under [Apache-2.0](LICENSE). The bundled native dependency includes
third-party components with their own [notices](native/NOTICE).