TxBuilder
- class cometa.transaction_builder.tx_builder.TxBuilder(protocol_params, slot_config)[source]
Bases:
objectHigh-level transaction builder for the Cardano blockchain.
The
TxBuilderprovides a fluent, Pythonic interface for constructing Cardano transactions. It encapsulates the complexities of transaction assembly, balancing, fee calculation, and UTXO management.Key Concepts:
UTXOs: Cardano uses an Unspent Transaction Output model. Each output from a previous transaction becomes an input for future transactions.
Coin Selection: The builder automatically selects UTXOs to cover the transaction’s outputs and fees using configurable strategies.
Balancing: The builder ensures inputs equal outputs + fees, sending any excess to the change address.
Plutus Scripts: Smart contracts that validate spending, minting, or staking operations. They require redeemers (arguments) and consume execution units (CPU/memory).
Basic Usage:
Example
>>> from cometa import TxBuilder, SlotConfig >>> >>> # Initialize with protocol parameters and slot configuration >>> slot_config = SlotConfig.mainnet() >>> builder = TxBuilder(protocol_params, slot_config) >>> >>> # Configure and build a simple transfer >>> tx = builder \ ... .set_change_address(my_address) \ ... .set_utxos(my_utxos) \ ... .send_lovelace(recipient, 5_000_000) \ ... .expires_in(3600) \ ... .build() >>> >>> # Sign and submit >>> signed_tx = wallet.sign_transaction(tx) >>> tx_hash = provider.submit_transaction(signed_tx)
Note
All configuration and validation errors are deferred until
build()is called. This allows for flexible, incremental transaction construction.See also
Transaction: The resulting transaction objectProtocolParameters: Required protocol configurationSlotConfig: Network timing configurationCoinSelector: Customizable UTXO selection strategiesTxEvaluator: Customizable Plutus script evaluation strategies
- Parameters:
protocol_params (ProtocolParameters)
slot_config (SlotConfig)
- __init__(protocol_params, slot_config)[source]
Create a new transaction builder. …
- Parameters:
protocol_params (ProtocolParameters)
slot_config (SlotConfig)
- Return type:
None
- set_coin_selector(coin_selector)[source]
Set the coin selection strategy for UTXO selection.
The coin selector determines how UTXOs are chosen to cover the transaction’s required value. Different strategies optimize for different goals:
Large First: Minimizes number of inputs by using largest UTXOs first
Random Improve: Balances between reducing fragmentation and privacy
If not set, defaults to the Large First strategy.
- Parameters:
coin_selector (CoinSelectorProtocol) – The coin selection strategy to use.
- Returns:
Self for method chaining.
- Return type:
Example
>>> class MySelector: ... def get_name(self) -> str: ... return "MySelector" ... def select(self, pre_selected, available, target): ... return selected, remaining >>> builder.set_coin_selector(MySelector())
- set_evaluator(evaluator)[source]
Set the transaction evaluator for Plutus script execution.
The evaluator computes execution units (CPU and memory) required for Plutus scripts. This is essential for accurate fee calculation when transactions contain smart contracts.
If not set, defaults to using the provider’s built-in evaluator.
- Parameters:
evaluator (TxEvaluatorProtocol) – The transaction evaluator to use.`
- Returns:
Self for method chaining.
- Return type:
Example
>>> class MyEvaluator: ... def get_name(self) -> str: ... return "MyEvaluator" ... def evaluate(self, transaction, additional_utxos): ... return redeemers >>> builder.set_evaluator(MyEvaluator())
- set_network_id(network_id)[source]
Set the target network for this transaction.
The network ID is included in the transaction body and ensures the transaction can only be submitted to the intended network.
- Parameters:
network_id (NetworkId) – The network identifier.
- Returns:
Self for method chaining.
- Return type:
Example
>>> builder.set_network_id(NetworkId.TESTNET) # Testnet >>> builder.set_network_id(NetworkId.MAINNET) # Mainnet
- set_change_address(address)[source]
Set the address for receiving change.
After covering outputs and fees, any remaining value from inputs is sent to this address. This is typically your own wallet address.
- Parameters:
address (Union['Address', str]) – The change address. Can be an
Addressobject or a bech32-encoded address string (e.g., “addr_test1…”).- Returns:
Self for method chaining.
- Return type:
Example
>>> builder.set_change_address("addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k...") >>> # Or with Address object >>> builder.set_change_address(my_address)
- set_collateral_change_address(address)[source]
Set the address for receiving collateral change.
When a transaction includes Plutus scripts, collateral is required as a guarantee. If the collateral inputs exceed the required amount, the excess is sent to this address.
If not set, defaults to the regular change address.
- Parameters:
address (Union['Address', str]) – The collateral change address. Can be an
Addressobject or a bech32-encoded address string.- Returns:
Self for method chaining.
- Return type:
Example
>>> builder.set_collateral_change_address("addr_test1...")
- set_minimum_fee(fee)[source]
Set a minimum fee for the transaction.
This overrides the calculated fee if it’s higher. Useful when you need to ensure a specific fee amount regardless of transaction size.
- Parameters:
fee (int) – The minimum fee in lovelace (1 ADA = 1,000,000 lovelace).
- Returns:
Self for method chaining.
- Return type:
Example
>>> builder.set_minimum_fee(200_000) # At least 0.2 ADA
- set_donation(amount)[source]
Set a treasury donation amount.
This Conway-era feature allows contributing ADA directly to the Cardano treasury as part of a transaction.
- Parameters:
amount (int) – The donation amount in lovelace.
- Returns:
Self for method chaining.
- Return type:
Example
>>> builder.set_donation(1_000_000) # Donate 1 ADA to treasury
- set_utxos(utxos)[source]
Set the available UTXOs for coin selection.
These UTXOs will be used by the coin selector to cover the transaction’s required inputs. Typically, these are all spendable UTXOs from your wallet.
- Parameters:
utxos (Union['UtxoList', List['Utxo']]) – List of available UTXOs. Can be a
UtxoListor a Python list ofUtxoobjects.- Returns:
Self for method chaining.
- Return type:
Example
>>> # Get UTXOs from provider >>> my_utxos = provider.get_utxos_at_address(my_address) >>> builder.set_utxos(my_utxos)
- set_collateral_utxos(utxos)[source]
Set UTXOs to use for script collateral.
Collateral is required when a transaction includes Plutus scripts. It serves as a guarantee that gets forfeited if script validation fails.
Collateral UTXOs should: - Contain only ADA (no native tokens) - Be from a key-based address (not a script address) - Have sufficient value to cover the collateral requirement
If not set, the builder will try to use UTXOs from
set_utxos().- Parameters:
utxos (Union['UtxoList', List['Utxo']]) – List of UTXOs designated for collateral.
- Returns:
Self for method chaining.
- Return type:
Example
>>> # Use specific UTXOs for collateral >>> builder.set_collateral_utxos(ada_only_utxos)
- set_valid_until(*, slot=None, unix_time=None)[source]
Set when the transaction expires (invalid_hereafter).
The transaction will be rejected if not included in a block before this point. You must specify either
slotorunix_time, not both.- Parameters:
slot (int | None) – The slot number after which the transaction becomes invalid.
unix_time (int | None) – Unix timestamp (seconds since epoch) after which the transaction becomes invalid.
- Returns:
Self for method chaining.
- Raises:
ValueError – If neither or both parameters are provided.
- Return type:
Example
>>> # Expire after specific slot >>> builder.set_valid_until(slot=12345678) >>> >>> # Expire 2 hours from now >>> import time >>> builder.set_valid_until(unix_time=int(time.time()) + 7200)
- set_valid_from(*, slot=None, unix_time=None)[source]
Set when the transaction becomes valid (invalid_before).
The transaction will be rejected if included in a block before this point. Useful for time-locked contracts.
You must specify either
slotorunix_time, not both.- Parameters:
slot (int | None) – The slot number before which the transaction is invalid.
unix_time (int | None) – Unix timestamp (seconds since epoch) before which the transaction is invalid.
- Returns:
Self for method chaining.
- Raises:
ValueError – If neither or both parameters are provided.
- Return type:
Example
>>> # Valid starting from specific slot >>> builder.set_valid_from(slot=12345000) >>> >>> # Valid starting 1 hour from now >>> import time >>> builder.set_valid_from(unix_time=int(time.time()) + 3600)
- expires_in(seconds)[source]
Sets the transaction to be valid for a specific duration from now.
This is a convenience method that calculates a future expiration date and sets it. The transaction will be marked as invalid if it is not included in a block within the specified duration.
- Parameters:
seconds (int) – The number of seconds from now that the transaction should remain valid.
- Returns:
Self for method chaining.
- Return type:
Example
>>> # Set the transaction to expire in 3 minutes (180 seconds) from now. >>> builder.expires_in(180)
- expires_after(date)[source]
Sets the transaction’s expiration to a specific, absolute date and time.
This function marks the transaction as invalid if it is not included in a block before the specified date.
- Parameters:
date (datetime) – The absolute date and time after which the transaction will be invalid.
- Returns:
Self for method chaining.
- Return type:
Example
>>> # Set the transaction to expire on New Year's Day, 2026. >>> from datetime import datetime, timezone >>> expiry_date = datetime(2026, 1, 1, tzinfo=timezone.utc) >>> builder.expires_after(expiry_date)
- set_invalid_before(slot)[source]
Sets the transaction’s validity start time using an absolute slot number.
This function marks the transaction as invalid if it is included in a block created before the specified slot.
- Parameters:
slot (int) – The absolute slot number before which this transaction is invalid.
- Returns:
Self for method chaining.
- Return type:
- valid_from_date(date)[source]
Sets the transaction’s validity start time to a specific, absolute date and time. The transaction will be invalid if processed before this date.
- Parameters:
date (datetime) – The absolute date and time from which the transaction will be valid.
- Returns:
Self for method chaining.
- Return type:
Example
>>> # Make the transaction valid starting on New Year's Day, 2026. >>> from datetime import datetime, timezone >>> start_date = datetime(2026, 1, 1, tzinfo=timezone.utc) >>> builder.valid_from_date(start_date)
- valid_after(seconds)[source]
Sets the transaction to become valid only after a specified duration from now. This is a convenience method that calculates a future start date.
- Parameters:
seconds (int) – The number of seconds from now to wait before the transaction becomes valid.
- Returns:
Self for method chaining.
- Return type:
Example
>>> # Make the transaction valid only after 1 hour (3600 seconds) has passed. >>> builder.valid_after(3600)
- send_lovelace(address, amount)[source]
Send ADA to an address.
Creates an output that sends the specified amount of lovelace to the given address. This is the simplest way to transfer ADA.
- Parameters:
address (Union['Address', str]) – The recipient address. Can be an
Addressobject or a bech32-encoded address string.amount (int) – The amount to send in lovelace (1 ADA = 1,000,000 lovelace).
- Returns:
Self for method chaining.
- Return type:
Example
>>> # Send 5 ADA >>> builder.send_lovelace("addr_test1...", 5_000_000) >>> >>> # Send 1.5 ADA >>> builder.send_lovelace(recipient_address, 1_500_000)
- send_value(address, value)[source]
Send a multi-asset value to an address.
Creates an output containing ADA and/or native tokens. Use this when transferring tokens or when you need precise control over the output value.
- Parameters:
address (Union['Address', str]) – The recipient address. Can be an
Addressobject or a bech32-encoded address string.value (Value) – The value to send, containing ADA and optional native tokens.
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa.transaction_body import Value >>> >>> # Create value with ADA and tokens >>> value = Value.from_coin(2_000_000) >>> value.add_asset(policy_id, asset_name, 100) >>> >>> builder.send_value("addr_test1...", value)
- lock_lovelace(script_address, amount, datum)[source]
Lock ADA at a script address with a datum.
Creates an output that sends ADA to a Plutus script address with an attached datum. The datum is required for the script to later validate spending of this output.
- Parameters:
script_address (Union['Address', str]) – The script address to lock funds at.
amount (int) – The amount to lock in lovelace.
datum (Datum) – The datum to attach to the output. This data is used by the script when validating spending.
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa import Datum, PlutusData >>> >>> # Create inline datum from PlutusData >>> plutus_data = PlutusData.from_int(42) >>> datum = Datum.from_inline_data(plutus_data) >>> >>> # Lock 10 ADA at script >>> builder.lock_lovelace(script_address, 10_000_000, datum)
- lock_value(script_address, value, datum)[source]
Lock a multi-asset value at a script address with a datum.
Creates an output that sends ADA and/or native tokens to a Plutus script address with an attached datum.
- Parameters:
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa import Datum, PlutusData >>> >>> # Create value with ADA and tokens >>> value = Value.from_coin(5_000_000) >>> value.add_asset(policy_id, asset_name, 50) >>> >>> # Create inline datum >>> datum = Datum.from_inline_data(PlutusData.from_int(42)) >>> >>> # Lock at script address >>> builder.lock_value(script_addr, value, datum)
- add_input(utxo, redeemer=None, datum=None)[source]
Add a specific UTXO as a transaction input.
Use this to explicitly include a UTXO in the transaction, bypassing automatic coin selection. This is typically used for:
Spending from script addresses (with redeemer)
Including specific UTXOs that must be consumed
Script interactions where input order matters
- Parameters:
utxo (Utxo) – The UTXO to spend.
redeemer (Optional['PlutusDataLike']) – The redeemer data for script validation. Required when spending from a Plutus script address.
datum (Optional['PlutusDataLike']) – The datum for the UTXO. Required if the UTXO doesn’t have an inline datum and you’re spending from a script address.
- Returns:
Self for method chaining.
- Return type:
Example
>>> # Spend from a key address (no redeemer needed) >>> builder.add_input(my_utxo) >>> >>> # Spend from a script address >>> builder.add_input(script_utxo, redeemer=spend_redeemer)
- add_reference_input(utxo)[source]
Add a reference input to the transaction.
Reference inputs allow reading UTXO data without spending it. This is useful for:
Reading on-chain data (oracles, configuration)
Referencing scripts without including them in the transaction
Sharing datum across multiple transactions
- Parameters:
utxo (Utxo) – The UTXO to reference (not spend).
- Returns:
Self for method chaining.
- Return type:
Example
>>> # Reference an oracle UTXO >>> builder.add_reference_input(oracle_utxo)
- add_output(output)[source]
Add a pre-built transaction output.
Use this when you need full control over output construction, including inline datums, reference scripts, or complex configurations.
- Parameters:
output (TransactionOutput) – A fully constructed
TransactionOutputobject.- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa.transaction_body import TransactionOutput >>> >>> output = TransactionOutput.new(address, 5_000_000) >>> output.set_inline_datum(my_datum) >>> builder.add_output(output)
- mint_token(policy_id, asset_name, amount, redeemer=None)[source]
Mint or burn native tokens.
Creates new tokens (positive amount) or burns existing tokens (negative amount) under the specified policy.
- Parameters:
policy_id (Union['Blake2bHash', str, bytes]) – The minting policy hash. Can be a
Blake2bHashobject, the raw bytes, or a hex-encoded string.asset_name (Union['AssetName', str, bytes]) – The token name. Can be an
AssetNameobject, hex string, or raw bytes. Empty string for unnamed tokens.amount (int) – Number of tokens to mint (positive) or burn (negative).
redeemer (Optional['PlutusDataLike']) – The redeemer for Plutus minting policies.
- Returns:
Self for method chaining.
- Return type:
Example
>>> # Mint 1000 tokens >>> builder.mint_token( ... policy_id="abc123...", ... asset_name="MyToken", ... amount=1000, ... redeemer=mint_redeemer, ... ) >>> >>> # Burn 50 tokens >>> builder.mint_token(policy_id, asset_name, amount=-50, redeemer=burn_redeemer)
- mint_token_with_id(asset_id, amount, redeemer=None)[source]
Mint or burn tokens using an asset ID.
Alternative to
mint_token()that uses the combined policy_id + asset_name identifier format.- Parameters:
asset_id (Union['AssetId', str, bytes]) – The full asset identifier. Can be an
AssetIdobject or a hex string in the format “{policy_id}{asset_name}”.amount (int) – Number of tokens to mint (positive) or burn (negative).
redeemer (Optional['PlutusDataLike']) – The redeemer for Plutus minting policies.
- Returns:
Self for method chaining.
- Return type:
Example
>>> builder.mint_token_with_id( ... "abc123...def456", # policy_id.asset_name_hex ... amount=500, ... redeemer=mint_redeemer, ... )
- add_script(script)[source]
Add a script to the transaction witness set.
Scripts must be included when: - Minting tokens with the script’s policy - Spending from the script’s address - Withdrawing from script-based stake credentials
For reference scripts (CIP-33), use
add_reference_input()instead.- Parameters:
script (ScriptLike) – The script to include (Native or Plutus).
- Returns:
Self for method chaining.
- Return type:
Example
>>> builder.add_script(minting_policy) >>> builder.add_script(spending_validator)
- add_datum(datum)[source]
Add a datum to the transaction witness set.
Datums are required when spending UTXOs that have datum hashes (not inline datums). The datum must hash to the UTXO’s datum hash.
- Parameters:
datum (PlutusDataLike) – The datum to include.
- Returns:
Self for method chaining.
- Return type:
Example
>>> builder.add_datum(original_datum)
- add_signer(pub_key_hash)[source]
Add a required signer to the transaction.
Required signers (CIP-30) specify that a particular key must sign the transaction. This is used by scripts that need to verify signatures from specific keys.
- Parameters:
pub_key_hash (Blake2bHash | str) – The public key hash of the required signer. Can be a
Blake2bHashor hex string.- Returns:
Self for method chaining.
- Return type:
Example
>>> builder.add_signer("abc123...") # Hex key hash >>> builder.add_signer(my_pub_key_hash)
- pad_signer_count(count)[source]
Reserve space for additional signers in fee calculation.
Use this when the final number of signers isn’t known during transaction building, but you need accurate fee estimation.
- Parameters:
count (int) – Number of additional signers to account for.
- Returns:
Self for method chaining.
- Return type:
Example
>>> # Expect 3 additional signers >>> builder.pad_signer_count(3)
- set_metadata(tag, metadata)[source]
Add metadata to the transaction.
Transaction metadata (auxiliary data) allows attaching arbitrary data to transactions. Common uses include:
NFT metadata (tag 721)
Token registry metadata (tag 20)
Application-specific data
- Parameters:
tag (int) – The metadata label (0 to 2^64-1).
metadata (Union['Metadatum', str, Dict[Any, Any], List[Any]]) – The metadata content. Can be: - A
Metadatumobject. - A Pythondictorlist(will be serialized to JSON). - A JSONstr.
- Returns:
Self for method chaining.
- Return type:
Example
>>> # Add NFT metadata using a dict >>> metadata = { ... "eb7e6282971727598462d39d7627bfa6fbbbf56496cb91b76840affb": { ... "BerryOnyx": { ... "color": "#0F0F0F", ... "image": "ipfs://ipfs/QmS7w3Q5oVL9NE1gJnsMVPp6fcxia1e38cRT5pE5mmxawL", ... "name": "Berry Onyx" ... }, ... } ... } >>> builder.set_metadata(721, metadata) >>> >>> # Add JSON string directly >>> builder.set_metadata(674, '{"msg": "Hello Cardano!"}')
- withdraw_rewards(reward_address, amount, redeemer=None)[source]
Withdraw staking rewards.
Withdraws accumulated staking rewards from a reward address. The withdrawal amount should match the available rewards.
- Parameters:
reward_address (Union['RewardAddress', str]) – The stake/reward address to withdraw from. Can be a
RewardAddressobject or bech32 string (stake_test1…).amount (int) – The amount to withdraw in lovelace.
redeemer (Optional['PlutusDataLike']) – Redeemer for script-based stake credentials.
- Returns:
Self for method chaining.
- Return type:
Example
>>> rewards = provider.get_rewards(stake_address) >>> builder.withdraw_rewards("stake_test1...", rewards)
- register_reward_address(reward_address, redeemer=None)[source]
Register a stake address.
Registers a new stake credential on-chain. This is required before the address can delegate to a pool or receive rewards.
Note: Registration requires a deposit (currently 2 ADA) that is refunded upon deregistration.
- Parameters:
reward_address (Union['RewardAddress', str]) – The stake address to register.
redeemer (Optional['PlutusDataLike']) – Redeemer for script-based stake credentials.
- Returns:
Self for method chaining.
- Return type:
Example
>>> builder.register_reward_address("stake_test1...")
- deregister_reward_address(reward_address, redeemer=None)[source]
Deregister a stake address.
Removes a stake credential from the chain. The deposit paid during registration is refunded.
- Parameters:
reward_address (Union['RewardAddress', str]) – The stake address to deregister.
redeemer (Optional['PlutusDataLike']) – Redeemer for script-based stake credentials.
- Returns:
Self for method chaining.
- Return type:
Example
>>> builder.deregister_reward_address("stake_test1...")
- delegate_stake(reward_address, pool_id, redeemer=None)[source]
Delegate stake to a pool.
Delegates the stake associated with a stake credential to a stake pool. Delegation determines which pool produces blocks on your behalf and earns you staking rewards.
How Staking Works:
Delegation takes effect at the next epoch boundary (~5 days on mainnet)
Your ADA remains in your wallet - only voting rights are delegated
Rewards start accumulating after 2 epochs from delegation
You can re-delegate at any time; the new delegation replaces the old one
Note
The stake address must be registered before delegating. Use
register_reward_address()first if the address is new.- Parameters:
reward_address (Union['RewardAddress', str]) – The stake address to delegate. Can be a
RewardAddressobject or bech32 string (e.g., “stake_test1…”).pool_id (str) – The stake pool’s bech32 ID (e.g., “pool1…”). You can find pool IDs on explorers like pool.pm or adapools.org.
redeemer (Optional['PlutusDataLike']) – Redeemer for script-based stake credentials. Only needed if the stake credential is controlled by a Plutus script.
- Returns:
Self for method chaining.
- Return type:
Example
>>> # Delegate to a stake pool >>> builder.delegate_stake( ... "stake_test1uqfu74w3wh4gfzu8m6e7j987h4lq9r3t7ef5gaw497uu85qsqfy27", ... "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy", ... )
- delegate_voting_power(reward_address, drep, redeemer=None)[source]
Delegate voting power to a DRep (Delegated Representative).
Conway-era Governance:
The Conway hard fork introduced on-chain governance to Cardano. DReps are community members who vote on governance proposals on behalf of delegators. Your voting power is proportional to your staked ADA.
Delegation Options:
DRep: Delegate to a specific representative who votes on your behalf
Abstain: Your stake counts toward quorum but not for/against proposals
No Confidence: Signals distrust in the current governance system
Note
Voting power delegation is separate from stake pool delegation. You can delegate to a pool for block production rewards and to a DRep for governance voting simultaneously.
- Parameters:
reward_address (Union['RewardAddress', str]) – The stake address delegating voting power. Can be a
RewardAddressobject or bech32 string (e.g., “stake_test1…”).drep (Union['DRep', str]) – The DRep to delegate to. Can be: - A
DRepobject - A DRep ID string (e.g., “drep1…”) -DRep.always_abstain()for abstaining -DRep.always_no_confidence()for no confidenceredeemer (Optional['PlutusDataLike']) – Redeemer for script-based stake credentials.
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa import DRep, DRepType, Credential >>> >>> # Delegate to a specific DRep >>> drep = DRep.new(DRepType.KEY_HASH, drep_credential) >>> builder.delegate_voting_power(reward_address, drep) >>> >>> # Or delegate to abstain (count towards quorum only) >>> builder.delegate_voting_power(reward_address, DRep.always_abstain())
- register_drep(drep, anchor=None, redeemer=None)[source]
Register as a DRep (Delegated Representative).
Registers a new Delegated Representative for Conway-era governance. DReps vote on governance proposals on behalf of ADA holders who delegate their voting power to them.
Requirements:
A deposit is required (defined in protocol parameters, ~500 ADA)
The deposit is refunded when the DRep is deregistered
An optional anchor can provide off-chain metadata about the DRep
The Anchor:
The anchor is a URL + hash pair pointing to off-chain metadata (usually JSON-LD) describing the DRep’s identity, platform, and voting philosophy. This helps delegators choose representatives.
- Parameters:
drep (Union['DRep', str]) – The DRep credential to register. Can be a
DRepobject constructed from a key hash or script hash.anchor (Optional['Anchor']) – Optional metadata anchor with URL pointing to DRep information and the hash of that document for verification.
redeemer (Optional['PlutusDataLike']) – Redeemer for script-based DRep credentials. Required when the DRep credential is controlled by a Plutus script.
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa import DRep, DRepType, Credential, Anchor, Blake2bHash >>> >>> # Create DRep from key credential >>> cred = Credential.from_key_hash(my_pub_key_hash) >>> drep = DRep.new(DRepType.KEY_HASH, cred) >>> >>> # Create anchor pointing to metadata >>> anchor = Anchor.new( ... url="https://example.com/drep-metadata.json", ... hash_value=Blake2bHash.from_hex("abc123...") ... ) >>> >>> builder.register_drep(drep, anchor=anchor)
- update_drep(drep, anchor=None, redeemer=None)[source]
Update DRep metadata.
Updates the metadata anchor for an existing DRep registration.
- Parameters:
drep (Union['DRep', str]) – The DRep to update. Can be a
DRepobject or DRep ID string.anchor (Optional['Anchor']) – New metadata anchor (URL and hash).
redeemer (Optional['PlutusDataLike']) – Redeemer for script-based DRep credentials.
- Returns:
Self for method chaining.
- Return type:
Example
>>> builder.update_drep(drep, anchor=new_anchor) >>> builder.update_drep("drep1...", anchor=new_anchor)
- deregister_drep(drep, redeemer=None)[source]
Deregister as a DRep.
Removes a DRep registration and refunds the deposit.
- Parameters:
drep (Union['DRep', str]) – The DRep to deregister. Can be a
DRepobject or DRep ID string.redeemer (Optional['PlutusDataLike']) – Redeemer for script-based DRep credentials.
- Returns:
Self for method chaining.
- Return type:
Example
>>> builder.deregister_drep(drep)
- vote(voter, action_id, voting_procedure, redeemer=None)[source]
Cast a governance vote on a proposal.
Conway-era Voting:
Governance votes are cast on active proposals by three voter types:
DReps: Delegated Representatives vote based on their delegators’ stake
SPOs: Stake Pool Operators vote with their pledged stake
Constitutional Committee: Vote on constitutional matters
Vote Options:
Yes: Support the proposal
No: Oppose the proposal
Abstain: Neither support nor oppose (counts toward quorum)
Each vote can include an optional anchor pointing to rationale.
- Parameters:
voter (Voter) – The voter identity. Create with
Voter.new()specifying the voter type and credential.action_id (GovernanceActionId) – The governance action to vote on. This identifies the specific proposal being decided.
voting_procedure (VotingProcedure) – The vote choice (yes/no/abstain) and optional anchor to voting rationale.
redeemer (Optional['PlutusDataLike']) – Redeemer for script-based voters. Required if the voter credential is controlled by a Plutus script.
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa import Voter, VoterType, Vote, VotingProcedure >>> >>> # Create voter from DRep credential >>> voter = Voter.new(VoterType.DREP, drep_credential) >>> >>> # Create voting procedure (yes vote with rationale) >>> procedure = VotingProcedure.new(Vote.YES, rationale_anchor) >>> >>> # Cast the vote >>> builder.vote(voter, proposal_action_id, procedure)
- add_certificate(certificate, redeemer=None)[source]
Add a certificate to the transaction.
Low-level method for adding any certificate type. For common operations, prefer the specific methods like
delegate_stake(),register_reward_address(), etc.- Parameters:
certificate (Certificate) – The certificate to include. This should be a
Certificatewrapper object created from a specific certificate type.redeemer (Optional['PlutusDataLike']) – Redeemer for script-based certificates.
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa import StakeRegistrationCert, Certificate >>> >>> stake_reg = StakeRegistrationCert.new(credential) >>> cert = Certificate(stake_reg) >>> builder.add_certificate(cert)
- propose_info(reward_address, anchor)[source]
Submit an info governance action.
Info Actions:
Info actions are used for signaling, polling, or community sentiment without any on-chain effects. They’re useful for:
Community sentiment polling
Non-binding resolutions
Signaling intent before formal proposals
Gathering feedback on ideas
Deposits and Refunds:
All governance proposals require a deposit (defined in protocol parameters) that is refunded to the specified reward address after the proposal is ratified, expired, or dropped.
- Parameters:
reward_address (Union['RewardAddress', str]) – Address to receive the deposit refund after the proposal concludes. Can be a
RewardAddressobject or bech32 string (e.g., “stake_test1…”).anchor (Anchor) – Metadata anchor with URL and hash pointing to proposal details. The document should explain the purpose and rationale.
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa import Anchor, Blake2bHash >>> >>> # Create anchor pointing to proposal metadata >>> anchor = Anchor.new( ... url="https://example.com/proposal.json", ... hash_value=Blake2bHash.from_hex("abc123...") ... ) >>> >>> builder.propose_info(reward_address, anchor)
- propose_new_constitution(reward_address, anchor, constitution, governance_action_id=None)[source]
Submit a new constitution governance action.
The Constitution:
The Cardano constitution is the foundational governance document that defines the rules, principles, and constraints for on-chain governance. It includes:
Governance principles and values
Rules for proposal submission and voting
Optional guardrails script for automated validation
Guardrails Script:
A constitution can include an optional Plutus script (guardrails) that automatically validates governance actions against constitutional rules.
- Parameters:
reward_address (Union['RewardAddress', str]) – Address to receive the proposal deposit refund. Can be a
RewardAddressobject or bech32 string.anchor (Anchor) – Metadata anchor pointing to the full constitution document (typically JSON-LD format with hash verification).
constitution (Constitution) – The new constitution object containing the anchor and optional guardrails script hash.
governance_action_id (Optional['GovernanceActionId']) – Optional ID of a previous constitution action this proposal builds upon.
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa import Constitution, Anchor, Blake2bHash >>> >>> # Create constitution with anchor and optional guardrails >>> const_anchor = Anchor.new( ... url="https://example.com/constitution.json", ... hash_value=Blake2bHash.from_hex("abc123...") ... ) >>> constitution = Constitution.new(const_anchor, guardrails_script_hash) >>> >>> builder.propose_new_constitution( ... reward_address, ... proposal_anchor, ... constitution, ... )
- propose_update_committee(reward_address, anchor, members_to_remove, members_to_add, new_quorum, governance_action_id=None)[source]
Submit an update committee governance action.
Constitutional Committee:
The Constitutional Committee (CC) is a group of members who vote on governance actions to ensure they align with the constitution. They serve as a check on the governance process.
Committee Updates:
This action can: - Add new committee members with term limits (epoch expiry) - Remove existing committee members - Change the quorum threshold (minimum votes required)
Quorum:
The quorum is expressed as a fraction (e.g., 2/3 means 67% must vote yes).
- Parameters:
reward_address (Union['RewardAddress', str]) – Address to receive the proposal deposit refund. Can be a
RewardAddressobject or bech32 string.anchor (Anchor) – Metadata anchor with URL and hash pointing to documentation explaining the rationale for committee changes.
members_to_remove (CredentialSet) – Set of credentials for members being removed. Use
CredentialSetto specify multiple credentials.members_to_add (CommitteeMembersMap) – Map of new member credentials to their term limits (epoch number when their term expires).
new_quorum (UnitInterval) – The new quorum threshold as a
UnitIntervalfraction (e.g.,UnitInterval.new(2, 3)for 2/3 majority).governance_action_id (Optional['GovernanceActionId']) – Optional ID of a previous committee update action this proposal builds upon.
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa import CredentialSet, CommitteeMembersMap, UnitInterval >>> >>> # Remove one member >>> to_remove = CredentialSet() >>> to_remove.add(old_member_credential) >>> >>> # Add new member with term limit at epoch 500 >>> to_add = CommitteeMembersMap() >>> to_add.insert(new_member_credential, 500) >>> >>> # Set 2/3 quorum >>> quorum = UnitInterval.new(2, 3) >>> >>> builder.propose_update_committee( ... reward_address, ... anchor, ... to_remove, ... to_add, ... quorum, ... )
- propose_no_confidence(reward_address, anchor, governance_action_id=None)[source]
Submit a no confidence governance action.
No Confidence Motion:
A no confidence action proposes that the community has lost trust in the current Constitutional Committee. If ratified:
The current committee enters a “state of no confidence”
A new committee must be elected before certain actions can proceed
Existing members remain until replaced by an Update Committee action
When to Use:
This action is appropriate when the committee: - Fails to fulfill their constitutional duties - Acts against the interests of the community - Becomes unresponsive or non-functional
- Parameters:
reward_address (Union['RewardAddress', str]) – Address to receive the proposal deposit refund. Can be a
RewardAddressobject or bech32 string.anchor (Anchor) – Metadata anchor with URL and hash pointing to documentation explaining the rationale for the no confidence motion.
governance_action_id (Optional['GovernanceActionId']) – Optional ID of a previous no confidence or committee-related action this proposal builds upon.
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa import Anchor, Blake2bHash >>> >>> # Create anchor with rationale for no confidence >>> anchor = Anchor.new( ... url="https://example.com/no-confidence-rationale.json", ... hash_value=Blake2bHash.from_hex("abc123...") ... ) >>> >>> builder.propose_no_confidence(reward_address, anchor)
- propose_treasury_withdrawals(reward_address, anchor, withdrawals, policy_hash=None)[source]
Submit a treasury withdrawals governance action.
Treasury System:
The Cardano treasury accumulates funds from transaction fees and monetary expansion. Treasury withdrawals allow the community to fund development, marketing, or other initiatives through governance votes.
Withdrawal Map:
The withdrawals parameter specifies which addresses receive funds and how much. Multiple recipients can be included in a single proposal.
- Parameters:
reward_address (Union['RewardAddress', str]) – Address to receive the proposal deposit refund. Can be a
RewardAddressobject or bech32 string.anchor (Anchor) – Metadata anchor with URL and hash pointing to proposal documentation explaining the purpose of the withdrawal.
withdrawals (WithdrawalMap) – Map of recipient reward addresses to lovelace amounts. Use
WithdrawalMap.from_dict()for convenient construction.policy_hash (Optional['Blake2bHash']) – Optional hash of the constitution guardrails script. Required if the current constitution has a guardrails script.
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa import WithdrawalMap, Anchor, Blake2bHash >>> >>> # Define withdrawal recipients and amounts >>> withdrawals = WithdrawalMap.from_dict({ ... "stake_test1uq...": 1_000_000_000_000, # 1M ADA ... "stake_test1up...": 500_000_000_000, # 500K ADA ... }) >>> >>> # Create proposal >>> builder.propose_treasury_withdrawals( ... reward_address, ... anchor, ... withdrawals, ... )
- propose_hardfork(reward_address, anchor, protocol_version, governance_action_id=None)[source]
Submit a hardfork initiation governance action.
Hardfork Process:
A hardfork (protocol upgrade) changes the rules of the blockchain. This includes major feature additions and breaking changes that require all nodes to upgrade. Examples: Shelley, Alonzo, Babbage, Conway.
Approval Requirements:
Hardfork proposals require approval from: - SPOs (Stake Pool Operators) - Constitutional Committee
The hardfork is enacted at an epoch boundary after ratification.
- Parameters:
reward_address (Union['RewardAddress', str]) – Address to receive the proposal deposit refund. Can be a
RewardAddressobject or bech32 string.anchor (Anchor) – Metadata anchor with URL and hash pointing to hardfork documentation, including rationale and upgrade instructions.
protocol_version (ProtocolVersion) – The target protocol version. Use
ProtocolVersion.new(major, minor)to create.governance_action_id (Optional['GovernanceActionId']) – Optional ID of a previous hardfork action this proposal builds upon (for chained upgrades).
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa import ProtocolVersion >>> >>> # Propose upgrade to protocol version 10.0 >>> version = ProtocolVersion.new(10, 0) >>> builder.propose_hardfork(reward_address, anchor, version)
- propose_parameter_change(reward_address, anchor, protocol_param_update, governance_action_id=None, policy_hash=None)[source]
Submit a parameter change governance action.
Protocol Parameters:
Protocol parameters control network behavior including:
Economic: Transaction fees, minimum UTXO value, treasury cut
Technical: Max block/tx size, max execution units
Governance: DRep deposit, proposal deposit, voting thresholds
Security: Collateral percentage, max collateral inputs
Parameter changes take effect at an epoch boundary after ratification.
Guardrails:
Some parameters may be constrained by a constitution guardrails script that validates proposed changes are within acceptable bounds.
- Parameters:
reward_address (Union['RewardAddress', str]) – Address to receive the proposal deposit refund. Can be a
RewardAddressobject or bech32 string.anchor (Anchor) – Metadata anchor with URL and hash pointing to documentation explaining the rationale for the parameter changes.
protocol_param_update (ProtocolParamUpdate) – The proposed parameter changes. Only changed parameters need to be specified; others remain unchanged.
governance_action_id (Optional['GovernanceActionId']) – Optional ID of a previous parameter change action this proposal builds upon.
policy_hash (Optional['Blake2bHash']) – Optional hash of the constitution guardrails script. Required if the constitution includes guardrails validation.
- Returns:
Self for method chaining.
- Return type:
Example
>>> from cometa import ProtocolParamUpdate >>> >>> # Create update with new min fee coefficient >>> update = ProtocolParamUpdate() >>> update.set_min_fee_a(45) # Change min fee coefficient >>> >>> builder.propose_parameter_change( ... reward_address, ... anchor, ... update, ... )
- build()[source]
Build and finalize the transaction.
This method: 1. Validates all configuration 2. Performs coin selection to balance inputs/outputs 3. Calculates fees 4. Adds change output 5. Evaluates Plutus scripts (if any) 6. Constructs the final transaction
- Returns:
The built (unsigned)
Transactionready for signing.- Raises:
CardanoError – If the transaction cannot be built due to: - Insufficient funds - Invalid configuration - Script evaluation failure - Protocol parameter violations
- Return type:
Example
>>> tx = builder.build() >>> print(f"Transaction fee: {tx.body.fee} lovelace") >>> >>> # Sign and submit >>> signed_tx = sign_transaction(tx, private_key) >>> tx_hash = provider.submit_transaction(signed_tx)
Note
The returned transaction is unsigned. You must sign it with the appropriate private keys before submission.