PyCardano

repository·main·Indexed 42 days ago

https://github.com/python-cardano/pycardano

A lightweight Python library for the Cardano blockchain (version 0.19.2) that enables developers to create, sign, and submit transactions without external dependencies like cardano-cli. It supports pure Python off-chain code and testing for Plutus DApps, including features for address management, asset minting, and support for CIP-008 and CIP-0014 standards.

Tokens
36.2K
Snippets
118
Records
149
Agent score
54%

What's inside PyCardano

  1. Available PyCardano usage patterns in examples

    main

    The more_examples directory contains recipes for common Cardano development tasks using PyCardano, including:

    • Address Management: Deriving addresses and querying address balances.
    • Transaction Construction: Creating transactions with multiple outputs and consolidating all inputs back into a single UTXO.
    • Asset Minting: Minting fungible assets within a policy and sending them to external addresses, as well as minting NFTs with metadata.
    • Asset Management: Burning NFTs.
    • CIP8 Operations: Downloading documents from a URL and signing them with CIP8, and verifying both valid and invalid CIP8 signatures.
    • Advanced Transactions: Transaction chaining using manual building and signing (bypassing the TransactionBuilder).
  2. What is a transaction builder and how to use it

    main

    A TransactionBuilder is a class that provides a user-friendly interface for constructing and signing Cardano transactions. It automatically manages transaction inputs, outputs, fees, and other technical details based on the provided ChainContext.

    Important: The TransactionBuilder is stateful. Once you call the build method, the instance cannot be reused. You must instantiate a new TransactionBuilder for every unique transaction you wish to create.

    # Create a transaction builder with a chain context
    builder = TransactionBuilder(context)
    
    # Add inputs from an address
    builder.add_input_address(address)
    
    # Add an output - sending 100 ADA to a recipient
    recipient = Address.from_primitive("addr_test1vrm9x2zsux7va6w892g38tvchnzahvcd9tykqf3ygnmwtaqyfg52x")
    builder.add_output(TransactionOutput(recipient, Value.from_primitive([100_000_000])))
    
    # Build, sign, and submit
    signed_tx = builder.build_and_sign([payment_signing_key], change_address=address)
    context.submit_tx(signed_tx)
  3. How raw transactions vs transaction builders differ

    main

    PyCardano provides two distinct mental models for transaction creation:

    Raw Transactions

    • Mechanism: You manually define TransactionInput, TransactionOutput, and the exact fee.
    • Complexity: High. You must calculate change amounts and identify specific UTxOs.
    • Use Case: Debugging, power users, or when precise control over every byte of the transaction is required.

    Transaction Builder

    • Mechanism: Uses a ChainContext to automatically select UTxOs from an address and calculate the required network fee.
    • Complexity: Low. It handles the heavy lifting of UTxO selection and change address management.
    • Use Case: Standard application logic, sending ADA, or interacting with smart contracts where automation is preferred.
  4. Vasil Upgrade capabilities overview

    main

    The Vasil upgrade brings several key capabilities to Cardano:

    • Reference inputs (CIP-31): Enables on-chain data sharing. Allows developers to inspect datums in UTXOs without spending them, useful for oracles.
    • Inline datums (CIP-32): Allows attaching datums directly to outputs instead of just hashes, making data visible without spending.
    • Reference scripts (CIP-33): Allows referencing a script stored in a UTXO instead of including the full script in every transaction, reducing size and cost.
    • Explicit collateral output (CIP-40): Allows specifying a change address for script collateral, so if a contract fails, only the collateral is lost and the rest is returned.
    • Plutus V2 scripts: Includes a new, lower-cost model and improved visibility of redeemers for all inputs.
  5. Core concepts of Cardano Smart Contracts

    main

    To work with smart contracts on Cardano, you must understand these key abstractions:

    • Plutus script: The validator logic compiled into Plutus Core binary. It evaluates transaction inputs to approve (True) or deny (False) spending a UTxO.
    • Script address: The hash of the Plutus script binary. UTxOs held at this address can only be consumed if the script returns True when evaluating the provided datum, redeemer, and script context.
    • Datum: Information associated with a UTxO used to "lock" funds. To unlock the funds, a user must provide a datum whose hash matches the one attached to the UTxO.
    • Redeemer: An input provided to the script to "unlock" funds. It shares the same data format as a datum but includes specific instructions (actions) and computational resources (execution units) required by the script.
    • Script context: Provides metadata about the pending transaction and the specific input triggering the validation.
  6. Core Governance Concepts

    main

    Cardano's Voltaire era governance model in PyCardano revolves around several key abstractions:

    • Delegate Representative (DRep): An on-chain identity that receives delegated voting power from ada holders to vote on governance actions.
    • Vote Delegation: The mechanism by which ada holders assign their voting power to a DRep.
    • Governance Actions: Proposals submitted to the blockchain (e.g., protocol parameter changes or treasury withdrawals) that require a vote.
    • Voting Procedures: The act of a voter (like a DRep) casting a Vote (Yes, No, or Abstain) on a specific GovActionId.
  7. Register a Delegate Representative (DRep)

    main

    To register a DRep on-chain, you must create a RegDRepCert certificate. This requires a new stake key pair to represent the DRep's identity. The registration includes a deposit (in Lovelace) and an optional Anchor for off-chain metadata.

    Key Requirements:

    • DRep Address: Must be constructed using both the payment verification key hash and the DRep's stake verification key hash. This address must be funded before submitting the registration.
    • Signing: The transaction must be signed by both the payment key (controlling the UTxOs) and the DRep's stake key.
    • Certificate: Use RegDRepCert with a DRepCredential (the stake verification key hash).
    # 1.1 Generate or load DRep stake key pair
    drep_stake_key_pair = StakeKeyPair.generate()
    
    # 1.2 Create DRep address
    drep_address = Address(
        payment_part=main_payment_vkey.hash(),
        staking_part=drep_stake_key_pair.verification_key.hash(),
        network=network,
    )
    
    # 1.4 Create DRep registration certificate
    drep_credential = DRepCredential(drep_stake_key_pair.verification_key.hash())
    anchor = Anchor(
        url="https://pycardano.drep.example.com/info",
        data_hash=AnchorDataHash(bytes.fromhex("00" * 32)),
    )
    drep_registration_cert = RegDRepCert(
        drep_credential=drep_credential,
        coin=500_000_000, # 500 ADA deposit
        anchor=anchor,
    )
    
    # 1.5 Build and submit transaction
    builder = TransactionBuilder(context)
    builder.add_input_address(str(drep_address))
    builder.certificates = [drep_registration_cert]
    
    signed_tx = builder.build_and_sign(
        signing_keys=[main_payment_skey, drep_stake_key_pair.signing_key],
        change_address=drep_address,
    )
    context.submit_tx(signed_tx)
  8. Setup PyCardano development environment

    main

    To contribute to or develop PyCardano, you can use either poetry or uv for dependency management.

    Using poetry

    curl -sSL https://install.python-poetry.org | python3 -
    cd pycardano && poetry install
    # To run commands in the configured environment:
    poetry shell

    Using uv

    curl -LsSf https://astral.sh/uv/install.sh | sh
    cd pycardano && uv sync
    # Poetry example
    curl -sSL https://install.python-poetry.org | python3 -
    cd pycardano && poetry install
    
    # uv example
    curl -LsSf https://astral.sh/uv/install.sh | sh
    cd pycardano && uv sync
  9. Delegate voting power to a DRep

    main

    Ada holders can delegate voting power to a DRep using the StakeRegistrationAndVoteDelegation certificate. This single certificate handles both the registration of a new stake key (and its deposit) and the delegation of votes to a specific DRep.

    Workflow:

    1. Generate a new StakeKeyPair for the voting identity.
    2. Create a DRep object using the target DRep's verification key hash and DRepKind.VERIFICATION_KEY_HASH.
    3. Construct a StakeRegistrationAndVoteDelegation certificate with a StakeCredential and the DRep object.
    4. Build a transaction using an address that includes the new stake part. The transaction must be signed by both the payment key and the new voting stake key.
    # 2.1 Generate a new stake key for the main account's voting delegation
    main_voting_stake_key_pair = StakeKeyPair.generate()
    
    # 2.4 Create StakeRegistrationAndVoteDelegation certificate
    stake_credential = StakeCredential(main_voting_stake_key_pair.verification_key.hash())
    
    # Create a DRep object pointing to the DRep we created
    drep_for_delegation = DRep(
        kind=DRepKind.VERIFICATION_KEY_HASH,
        credential=drep_stake_key_pair.verification_key.hash()
    )
    
    delegation_cert = StakeRegistrationAndVoteDelegation(
        stake_credential=stake_credential,
        drep=drep_for_delegation,
        coin=2_000_000, # 2 ADA stake key registration deposit
    )
    
    builder = TransactionBuilder(context)
    main_full_address = Address(
        payment_part=main_payment_vkey.hash(),
        staking_part=main_voting_stake_key_pair.verification_key.hash(),
        network=network,
    )
    builder.add_input_address(str(main_full_address))
    builder.certificates = [delegation_cert]
    
    signed_tx = builder.build_and_sign(
        signing_keys=[main_payment_skey, main_voting_stake_key_pair.signing_key],
        change_address=main_full_address,
    )
    context.submit_tx(signed_tx)
  10. Set up the PyCardano examples environment

    main

    To run the provided examples, you must first clone the repository and configure your environment variables. The examples rely on a .env file for configuration (likely containing API keys for providers like BlockFrost or chain context settings).

    1. Clone the repository.
    2. Rename .env-example to .env.
    3. Update the values in .env with your specific credentials and configuration.
    # Clone the repo
    # Rename the example env file
    cp .env-example .env
    
    # Edit .env with your actual values
    edit .env