### Install Dependencies Source: https://github.com/python-cardano/pycardano/blob/main/examples/full_stack/README.md Install the project dependencies using Poetry. ```shell $ poetry install ``` -------------------------------- ### Start Flask Application Source: https://github.com/python-cardano/pycardano/blob/main/examples/full_stack/README.md Configure the BlockFrost project ID and start the Flask development server. ```shell $ export BLOCKFROST_ID="your_blockfrost_project_id" $ export FLASK_APP=server $ poetry run flask run ``` -------------------------------- ### Install PyCardano with uv Source: https://github.com/python-cardano/pycardano/blob/main/README.md Installs PyCardano and its dependencies using uv. It first installs uv if not present, then navigates to the project directory and runs `uv sync` to install dependencies. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh cd pycardano && uv sync ``` -------------------------------- ### Install PyCardano with Poetry Source: https://github.com/python-cardano/pycardano/blob/main/README.md Installs PyCardano and its dependencies using Poetry. It first installs Poetry itself if not present, then navigates to the project directory and runs `poetry install`. ```bash curl -sSL https://install.python-poetry.org | python3 - cd pycardano && poetry install ``` -------------------------------- ### Install PyCardano Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/tutorial.md Install the library using the pip package manager. ```shell $ pip install pycardano ``` -------------------------------- ### Launch Docker Services for Testing Source: https://github.com/python-cardano/pycardano/blob/main/integration-test/README.md Starts the Cardano node and Ogmios services in detached mode. ```bash docker-compose up -d ``` -------------------------------- ### Bootstrap Cardano Node Configuration Source: https://github.com/python-cardano/pycardano/blob/main/integration-test/README.md Use this script to generate configuration files for a single BFT node setup. ```bash ./bootstrap.sh local-alonzo ``` -------------------------------- ### Load Plutus Script and Get Address Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/api/pycardano.plutus.md Demonstrates loading a Plutus V2 script from a file and deriving its corresponding address on the testnet. Ensure the script file exists at the specified path. ```python >>> from pycardano import Address, Network >>> script = PlutusV2Script.load("test/resources/scriptV2.plutus") >>> Address(plutus_script_hash(script), network=Network.TESTNET).encode() 'addr_test1wrmz3pjz4dmfxj0fc0a0eyw69tp6h7mpndzf9g3kttq9cqqqw47ym' ``` -------------------------------- ### Generate Payment and Stake Keys Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/address.md Generate new payment and stake signing keys and derive their corresponding verification keys. Ensure pycardano is installed. ```python from pycardano import PaymentSigningKey, StakeSigningKey, PaymentVerificationKey, StakeVerificationKey payment_signing_key = PaymentSigningKey.generate() payment_verification_key = PaymentVerificationKey.from_signing_key(payment_signing_key) stake_signing_key = StakeSigningKey.generate() stake_verification_key = StakeVerificationKey.from_signing_key(stake_signing_key) ``` -------------------------------- ### Install deterministic cbor2 implementation Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/frequently_asked_questions.md Use the pure Python implementation of cbor2 to ensure deterministic serialization. This prevents transaction hash changes during re-encoding. ```bash ./ensure_pure_cbor2.sh ``` ```bash pip uninstall -y cbor2 pip install --no-binary cbor2 cbor2 ``` -------------------------------- ### Initialize PyCardano Governance Environment Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/governance.md Sets up the BlockFrostChainContext and loads the main payment key and address for interacting with the Cardano testnet. ```python from pycardano import ( # Core Network, BlockFrostChainContext, TransactionBuilder, # Keys & Addresses PaymentSigningKey, StakeKeyPair, Address, # Certificates RegDRepCert, StakeRegistrationAndVoteDelegation, DRepCredential, StakeCredential, DRep, DRepKind, # Governance GovActionId, InfoAction, Voter, VoterType, Vote, Anchor, AnchorDataHash, ) # Initialize chain context network = Network.TESTNET context = BlockFrostChainContext("your_blockfrost_project_id", base_url=ApiUrls.preprod.value) # Load main payment key and derive address main_payment_skey = PaymentSigningKey.load("path/to/payment.skey") main_payment_vkey = main_payment_skey.to_verification_key() main_address = Address(main_payment_vkey.hash(), network=network) ``` -------------------------------- ### Build Contract with Opsin Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/plutus.md Commands to set up a virtual environment and compile the gift contract. ```bash $ python3 -m venv venv $ source venv/bin/activate $ pip install opshin $ opshin build gift.py ``` -------------------------------- ### Initialize Chain Context Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/plutus.md Establishes a connection to the blockchain using BlockFrost. ```python >>> from blockfrost import ApiUrls >>> from pycardano import BlockFrostChainContext >>> context = BlockFrostChainContext("your_blockfrost_project_id", base_url=ApiUrls.preprod.value) ``` -------------------------------- ### GET /pool/validate Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/api/pycardano.poolparams.md Utility function to validate if a string is a valid Cardano stake pool ID in bech32 format. ```APIDOC ## is_bech32_cardano_pool_id ### Description Checks if a provided string is a valid Cardano stake pool ID in bech32 format. ### Parameters #### Query Parameters - **pool_id** (str) - Required - The stake pool ID string to validate. ### Response #### Success Response (200) - **result** (bool) - Returns True if valid, False otherwise. ``` -------------------------------- ### Build and Open PyCardano Documentation Source: https://github.com/python-cardano/pycardano/blob/main/README.md Builds the project's documentation using Sphinx and opens the generated HTML pages in the default web browser. This command is used to preview the documentation locally. ```bash make docs ``` -------------------------------- ### Access Local Demo Source: https://github.com/python-cardano/pycardano/blob/main/examples/full_stack/README.md Navigate to the local Flask server address in a browser with the Nami wallet extension. ```text http://127.0.0.1:5000/ ``` -------------------------------- ### Get Transaction ID Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/transaction.md Retrieve the unique transaction ID from the signed transaction object. This ID can be used to track the transaction on the blockchain. ```python tx.id ``` -------------------------------- ### Get Transaction ID - PyCardano Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/transaction.md Retrieves the transaction ID, which is the hash of the transaction body. This ID is used to identify the transaction on the blockchain. ```python tx_body.id ``` -------------------------------- ### Check Code Style with Flake8 Source: https://github.com/python-cardano/pycardano/blob/main/README.md Performs a static code analysis using Flake8 to check for style guide violations and potential errors. This helps maintain code quality. ```bash make qa ``` -------------------------------- ### Generate Payment Keys and Address Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/tutorial.md Create payment signing and verification keys, save them to disk, and derive a testnet address. ```python >>> from pycardano import Address, Network, PaymentSigningKey, PaymentVerificationKey >>> payment_signing_key = PaymentSigningKey.generate() >>> payment_signing_key.save("payment.skey") >>> payment_verification_key = PaymentVerificationKey.from_signing_key(payment_signing_key) >>> payment_verification_key.save("payment.vkey") >>> network = Network.TESTNET >>> address = Address(payment_part=payment_verification_key.hash(), network=network) >>> address 'addr_test1vr2p8st5t5cxqglyjky7vk98k7jtfhdpvhl4e97cezuhn0cqcexl7' ``` -------------------------------- ### Add Output with Reference Script Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/plutus.md Demonstrates how to include a script in a transaction output to be used as a reference script. ```python >>> builder = TransactionBuilder(context) >>> builder.add_input_address(giver_address) >>> datum = 42 >>> # Include scripts in the script address >>> builder.add_output( >>> TransactionOutput(script_address, 50000000, script=gift_script) >>> ) ``` -------------------------------- ### Run All Integration Tests Source: https://github.com/python-cardano/pycardano/blob/main/integration-test/README.md Executes the complete suite of integration tests. ```bash ./run_tests.sh ``` -------------------------------- ### Propose a Governance Action Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/governance.md Constructs and submits an InfoAction proposal, requiring a deposit and a reward account for potential refunds. ```python # 3.2 Create InfoAction info_action = InfoAction() # 3.3 Define anchor for the proposal proposal_anchor = Anchor( url="https://pycardano.infoaction.example.com/details", data_hash=AnchorDataHash(bytes.fromhex("11" * 32)), ) # 3.4 The reward account for the proposal deposit refund. reward_account_address = Address( staking_part=drep_stake_key_pair.verification_key.hash(), network=context.network ) # 3.5 Build and submit transaction builder = TransactionBuilder(context) builder.add_input_address(str(drep_address)) # DRep's address pays the proposal deposit builder.add_proposal( deposit=100_000_000_000, # Example: 100k ADA deposit reward_account=bytes(reward_account_address), gov_action=info_action, anchor=proposal_anchor, ) # Sign with the payment key and the DRep's stake key as the proposer. 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) # The GovActionId is derived from the transaction ID and the proposal's index gov_action_id = GovActionId(transaction_id=signed_tx.id, gov_action_index=0) ``` -------------------------------- ### Initialize Withdrawals with Reward Address Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/api/pycardano.transaction.md Create a Withdrawals object mapping a stake address to a withdrawal amount. ```pycon >>> address = Address.from_primitive("stake_test1upyz3gk6mw5he20apnwfn96cn9rscgvmmsxc9r86dh0k66gswf59n") >>> Withdrawals({bytes(address): 1000000}) {b'\xe0H(\xa2\xda\xdb\xa9|\xa9\xfd\x0c\xdc\x99\x97X\x99G\x0c!\x9b\xdc\r\x82\x8c\xfa\x6d\xdf\x6d\x69': 1000000} ``` -------------------------------- ### Initialize BlockFrost Chain Context Source: https://context7.com/python-cardano/pycardano/llms.txt Configure a blockchain context using the BlockFrost API for specific networks like preprod or mainnet. ```python from blockfrost import ApiUrls from pycardano import BlockFrostChainContext, Network # Create context for preprod testnet context = BlockFrostChainContext( project_id="your_blockfrost_project_id", base_url=ApiUrls.preprod.value ) # Create context for mainnet mainnet_context = BlockFrostChainContext( project_id="your_mainnet_project_id", base_url=ApiUrls.mainnet.value ) ``` -------------------------------- ### Initialize BlockFrostChainContext Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/transaction.md Create a chain context using your BlockFrost project ID and the appropriate base URL for the network. This context is necessary for the transaction builder to access protocol parameters and UTxOs. ```python from blockfrost import ApiUrls from pycardano import BlockFrostChainContext network = Network.TESTNET context = BlockFrostChainContext("your_blockfrost_project_id", base_url=ApiUrls.preprod.value) ``` -------------------------------- ### Propose governance action Source: https://context7.com/python-cardano/pycardano/llms.txt Initializes a governance proposal action with an associated anchor. ```python from pycardano import ( InfoAction, GovActionId, Voter, VoterType, Vote, Anchor, AnchorDataHash, ) # Create a governance proposal info_action = InfoAction() proposal_anchor = Anchor( url="https://example.com/proposal", data_hash=AnchorDataHash(bytes.fromhex("11" * 32)) ) ``` -------------------------------- ### Create Native Assets (Bottom-Up) Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/instance_creation.md Demonstrates the bottom-up creation of native assets, including AssetName, Asset, MultiAsset, and ScriptHash. This method involves multiple steps to build the nested structure. ```python >>> from pycardano import Asset, AssetName, MultiAsset, ScriptHash >>> # Create an asset container >>> my_asset = Asset() >>> # Create names for our assets >>> nft1 = AssetName(b"MY_NFT_1") >>> nft2 = AssetName(b"MY_NFT_2") >>> # Put assets into the asset container with a quantity of 1 >>> my_asset[nft1] = 1 >>> my_asset[nft2] = 1 >>> # Create a MultiAsset container >>> my_nft = MultiAsset() >>> # Create a policy id >>> policy_id = ScriptHash(bytes.fromhex("9c83e0e86689ae56c0753c9a1714980e6b7603bca12530b0e19b0dae")) >>> # Put assets into MultiAsset container. >>> my_nft[policy_id] = my_asset >>> my_nft {ScriptHash(hex='9c83e0e86689ae56c0753c9a1714980e6b7603bca12530b0e19b0dae'): {AssetName(b'MY_NFT_1'): 1, AssetName(b'MY_NFT_2'): 2}} ``` -------------------------------- ### Save and Load Keys Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/address.md Save payment signing and verification keys to files and subsequently load them back. Ensure the keys are generated or loaded before saving. ```python # Save payment_signing_key.save("payment.skey") payment_verification_key.save("payment.vkey") # Load payment_signing_key = payment_signing_key.load("payment.skey") payment_verification_key = payment_verification_key.load("payment.vkey") ``` -------------------------------- ### Create and Register a DRep with PyCardano Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/governance.md Generates a new DRep stake key pair, creates a DRep address, and constructs a DRep registration certificate with an anchor for off-chain metadata. The DRep address must be funded before submitting the registration transaction. ```python # 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, ) # The drep_address must be funded before it can submit the registration. # 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] # The transaction must be signed by the payment key controlling the UTxOs ``` -------------------------------- ### Build a Transaction Source: https://github.com/python-cardano/pycardano/blob/main/README.md Initialize a transaction builder using a BlockFrost context and specify input addresses. ```python """Build a transaction using transaction builder""" from blockfrost import ApiUrls from pycardano import * # Use testnet network = Network.TESTNET # Read keys to memory # Assume there is a payment.skey file sitting in current directory psk = PaymentSigningKey.load("payment.skey") # Assume there is a stake.skey file sitting in current directory ssk = StakeSigningKey.load("stake.skey") pvk = PaymentVerificationKey.from_signing_key(psk) svk = StakeVerificationKey.from_signing_key(ssk) # Derive an address from payment verification key and stake verification key address = Address(pvk.hash(), svk.hash(), network) # Create a BlockFrost chain context context = BlockFrostChainContext("your_blockfrost_project_id", base_url=ApiUrls.preprod.value) # Create a transaction builder builder = TransactionBuilder(context) # Tell the builder that transaction input will come from a specific address, assuming that there are some ADA and native # assets sitting at this address. "add_input_address" could be called multiple times with different address. builder.add_input_address(address) ``` -------------------------------- ### Run All PyCardano Tests Source: https://github.com/python-cardano/pycardano/blob/main/README.md Executes all unit tests for the PyCardano project using the make command. Supports running tests with either Poetry or uv. ```bash make test make RUN=uv test ``` -------------------------------- ### Create MultiAsset (from_primitive) Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/instance_creation.md Constructs a MultiAsset instance using the `from_primitive` method, which takes a dictionary representing the policy ID and asset names with their quantities. This is a more streamlined approach compared to bottom-up creation. ```python >>> my_nft_alternative = MultiAsset.from_primitive( ... { ... bytes.fromhex("9c83e0e86689ae56c0753c9a1714980e6b7603bca12530b0e19b0dae"): { ... b"MY_NFT_1": 1, ... b"MY_NFT_2": 1 ... } ... } ... ) >>> my_nft_alternative {ScriptHash(hex='9c83e0e86689ae56c0753c9a1714980e6b7603bca12530b0e19b0dae'): {AssetName(b'MY_NFT_1'): 1, AssetName(b'MY_NFT_2'): 1}} ``` -------------------------------- ### Access Protocol Parameters Source: https://context7.com/python-cardano/pycardano/llms.txt Retrieve and print various protocol parameters such as fee coefficients, key deposit, current epoch, and last block slot from the context. ```python print(f"Min fee coefficient: {context.protocol_param.min_fee_coefficient}") print(f"Min fee constant: {context.protocol_param.min_fee_constant}") print(f"Key deposit: {context.protocol_param.key_deposit}") # Get current epoch and slot print(f"Current epoch: {context.epoch}") print(f"Last block slot: {context.last_block_slot}") ``` -------------------------------- ### Create TransactionInput and TransactionOutput (from_primitive) Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/instance_creation.md Instantiates TransactionInput and TransactionOutput using the `from_primitive` class method, which accepts Python primitive types like lists and dictionaries for a more concise construction. ```python >>> from pycardano import Address, TransactionId, TransactionInput, TransactionOutput >>> tx_in = TransactionInput.from_primitive( ... [bytes.fromhex("732bfd67e66be8e8288349fcaaa2294973ef6271cc189a239bb431275401b8e5"), 0]) >>> tx_in {'index': 0, 'transaction_id': TransactionId(hex='732bfd67e66be8e8288349fcaaa2294973ef6271cc189a239bb431275401b8e5')} >>> tx_out = TransactionOutput.from_primitive( ... ["addr_test1vrm9x2zsux7va6w892g38tvchnzahvcd9tykqf3ygnmwtaqyfg52x", 100000000000]) >>> tx_out {'address': addr_test1vrm9x2zsux7va6w892g38tvchnzahvcd9tykqf3ygnmwtaqyfg52x, 'amount': 100000000000, 'datum_hash': None} ``` -------------------------------- ### ExUnitPrices Class Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/api/pycardano.governance.md Represents execution unit prices for memory and CPU steps. ```APIDOC ## ExUnitPrices Class ### Description Represents execution unit prices for memory and CPU steps. ### Class Definition `class pycardano.governance.ExUnitPrices(mem_price: Fraction, step_price: Fraction)` Bases: [`ArrayCBORSerializable`](pycardano.serialization.md#pycardano.serialization.ArrayCBORSerializable) ### Parameters #### mem_price - **Type**: Fraction - **Description**: Memory price as a nonnegative interval (numerator, denominator). #### step_price - **Type**: Fraction - **Description**: Step price as a nonnegative interval (numerator, denominator). ``` -------------------------------- ### Register stake and delegate Source: https://context7.com/python-cardano/pycardano/llms.txt Registers a stake key and delegates it to a specific stake pool using certificates. ```python from pycardano import ( StakeRegistration, StakeDelegation, StakeCredential, PoolKeyHash, ) # Stake credential from stake verification key stake_credential = StakeCredential(stake_verification_key.hash()) # Create certificates stake_registration = StakeRegistration(stake_credential) stake_delegation = StakeDelegation( stake_credential, pool_keyhash=PoolKeyHash(bytes.fromhex("pool_id_hex_here")) ) # Build transaction with certificates builder = TransactionBuilder(context) builder.add_input_address(base_address) builder.certificates = [stake_registration, stake_delegation] signed_tx = builder.build_and_sign( [payment_skey, stake_skey], change_address=base_address ) context.submit_tx(signed_tx) ``` -------------------------------- ### Prepare Unlock Transaction Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/plutus.md Initializes the transaction builder and redeemer for consuming the script UTxO. ```python >>> redeemer = Redeemer(Unit()) # The plutus equivalent of None >>> utxo_to_spend = context.utxos(str(script_address))[0] >>> builder = TransactionBuilder(context) ``` -------------------------------- ### Create and Decode Cardano Addresses Source: https://context7.com/python-cardano/pycardano/llms.txt Construct base, enterprise, or stake addresses from verification key hashes and decode existing addresses from strings. ```python from pycardano import Address, Network, PaymentVerificationKey, StakeVerificationKey # Create a base address (payment + staking) base_address = Address( payment_part=payment_verification_key.hash(), staking_part=stake_verification_key.hash(), network=Network.TESTNET ) print(base_address.encode()) # Output: addr_test1qz... # Create an enterprise address (payment only, no staking) enterprise_address = Address( payment_part=payment_verification_key.hash(), network=Network.TESTNET ) # Create a stake address (staking only) stake_address = Address( staking_part=stake_verification_key.hash(), network=Network.TESTNET ) # Decode an address from string decoded_address = Address.from_primitive( "addr_test1vrm9x2zsux7va6w892g38tvchnzahvcd9tykqf3ygnmwtaqyfg52x" ) # Decode a Byron-era address byron_address = Address.from_primitive( "Ae2tdPwUPEZFRbyhz3cpfC2CumGzNkFBN2L42rcUc2yjQpEkxDbkPodpMAi" ) ``` -------------------------------- ### Build and Sign Transaction Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/transaction.md Construct and sign the transaction using the provided signing keys. The builder automatically handles UTxO selection, fee calculation, and change address management. ```python signed_tx = builder.build_and_sign([sk], change_address=address) ``` -------------------------------- ### Build and Sign Transaction Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/plutus.md Builds and signs a transaction using provided outputs and a private key. Ensure the payment signing key and taker address are correctly configured. ```python >>> builder.add_output(take_output) >>> signed_tx = builder.build_and_sign([payment_skey], taker_address) ``` -------------------------------- ### Create Transaction Builder Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/transaction.md Instantiate a TransactionBuilder using the previously created chain context. This builder will manage the transaction construction process. ```python builder = TransactionBuilder(context) ``` -------------------------------- ### Enter Poetry Shell Environment Source: https://github.com/python-cardano/pycardano/blob/main/README.md Activates the Poetry shell, which automatically configures all necessary Python dependencies for running PyCardano programs. This is recommended for testing and development. ```bash poetry shell ``` -------------------------------- ### Build Minting Transaction Source: https://context7.com/python-cardano/pycardano/llms.txt Constructs a transaction to mint new native tokens. Ensure the policy and amount are correctly specified. ```python builder = TransactionBuilder(context) builder.add_input_address(sender_address) builder.native_scripts = [policy] builder.mint = MultiAsset({policy_id: Asset({asset_name: mint_amount})}) # Output the minted tokens to an address builder.add_output( TransactionOutput( sender_address, Value(coin=2_000_000, multi_asset=MultiAsset({ policy_id: Asset({asset_name: mint_amount}) })) ) ) # Set TTL to satisfy time lock builder.ttl = 50_000_000 signed_tx = builder.build_and_sign([psk], change_address=sender_address) context.submit_tx(signed_tx) ``` -------------------------------- ### Load Signing Key and Derive Verification Key Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/transaction.md Load a payment signing key from a file and derive its corresponding verification key. This is essential for signing transactions and deriving the payment address. ```python from pycardano import PaymentSigningKey, PaymentVerificationKey, Address, Network network = Network.TESTNET sk = PaymentSigningKey.load("path/to/payment.skey") vk = PaymentVerificationKey.from_signing_key(sk) address = Address(vk.hash(), network) ``` -------------------------------- ### Build and submit a transaction with TransactionBuilder Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/frequently_asked_questions.md Use the stateful TransactionBuilder to construct, sign, and submit transactions. Note that each builder instance is single-use and must be re-instantiated for subsequent transactions. ```python >>> # 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) ``` -------------------------------- ### Encode DRep to Bech32 Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/api/pycardano.certificate.md Demonstrates how to create a DRep instance using a verification key hash and encode it into a Bech32 string. ```pycon >>> vkey_bytes = bytes.fromhex("00000000000000000000000000000000000000000000000000000000") >>> credential = VerificationKeyHash(vkey_bytes) >>> print(DRep(kind=DRepKind.VERIFICATION_KEY_HASH, credential=credential).encode()) drep1ygqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq7vlc9n ``` -------------------------------- ### Generate Payment and Stake Key Pairs Source: https://context7.com/python-cardano/pycardano/llms.txt Generate signing and verification key pairs for both payment and staking operations. ```python from pycardano import PaymentKeyPair, StakeKeyPair # Generate payment key pair payment_key_pair = PaymentKeyPair.generate() payment_signing_key = payment_key_pair.signing_key payment_verification_key = payment_key_pair.verification_key # Generate stake key pair stake_key_pair = StakeKeyPair.generate() stake_signing_key = stake_key_pair.signing_key stake_verification_key = stake_key_pair.verification_key ``` -------------------------------- ### Generate Payment and Stake Key Pairs Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/address.md Generate payment and stake key pairs, which include both signing and verification keys. This is an alternative to generating them separately. ```python from pycardano import PaymentKeyPair, StakeKeyPair payment_key_pair = PaymentKeyPair.generate() payment_signing_key = payment_key_pair.signing_key payment_verification_key = payment_key_pair.verification_key stake_key_pair = StakeKeyPair.generate() stake_signing_key = stake_key_pair.signing_key stake_verification_key = stake_key_pair.verification_key ``` -------------------------------- ### Add Output with Inline Datum Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/plutus.md Demonstrates sending funds to a script address while attaching an inline datum directly to the output. ```python >>> builder = TransactionBuilder(context) >>> builder.add_input_address(giver_address) >>> datum = 42 >>> builder.add_output( >>> TransactionOutput(script_address, 50000000, datum=datum, script=gift_script) >>> ) ``` -------------------------------- ### Serialize an empty datum Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/plutus.md Demonstrates the creation and CBOR serialization of an empty unit datum. ```python >>> from pycardano import PlutusData, Unit >>> empty_datum = Unit() >>> empty_datum.to_cbor().hex() 'd87980' ``` -------------------------------- ### Add Script Input and Output Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/plutus.md Configures the transaction to spend the script input and send funds to the taker. ```python >>> builder.add_script_input(utxo_to_spend, gift_script, datum, redeemer) >>> take_output = TransactionOutput(taker_address, 25123456) >>> builder.add_output(take_output) ``` -------------------------------- ### Create Base Address Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/address.md Construct a base Cardano address using payment and staking verification keys for the testnet. Ensure keys are generated and imported. ```python from pycardano import Address, Network base_address = Address(payment_part=payment_verification_key.hash(), staking_part=stake_verification_key.hash(), network=Network.TESTNET) base_address "addr_test1vr2p8st5t5cxqglyjky7vk98k7jtfhdpvhl4e97cezuhn0cqcexl7" ``` -------------------------------- ### select(utxos, outputs, context, ...) Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/api/pycardano.coinselection.md Selects a subset of UTxOs from a provided list to satisfy the sum of transaction outputs. ```APIDOC ## select(utxos, outputs, context, ...) ### Description From an input list of UTxOs, select a subset of UTxOs whose sum (including ADA and multi-assets) is equal to or larger than the sum of a set of outputs. ### Parameters - **utxos** (List[UTxO]) - Required - A list of UTxO to select from. - **outputs** (List[TransactionOutput]) - Required - A list of transaction outputs which the selected set should satisfy. - **context** (ChainContext) - Required - A chain context where protocol parameters could be retrieved. - **max_input_count** (int) - Optional - Max number of input UTxOs to select. - **include_max_fee** (bool) - Optional - Have selected UTxOs to cover transaction fee. Defaults to True. - **respect_min_utxo** (bool) - Optional - Respect minimum amount of ADA required to hold a multi-asset bundle in the change. Defaults to True. - **existing_amount** (Value) - Optional - A starting amount already existed before selection. Defaults to 0. ### Response #### Success Response (200) - **selected** (List[UTxO]) - A list of selected UTxOs. - **changes** (Value) - Change amount to be returned. ``` -------------------------------- ### Governance Configuration Parameters Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/api/pycardano.governance.md Configuration parameters related to governance actions and settings. ```APIDOC ## Governance Configuration Parameters ### Description Configuration parameters that define various aspects of the Cardano governance system. ### Parameters #### max_value_size - **Type**: int | None - **Default**: None - **Description**: Maximum value size. #### collateral_percentage - **Type**: int | None - **Default**: None - **Description**: Collateral percentage. #### max_collateral_inputs - **Type**: int | None - **Default**: None - **Description**: Maximum number of collateral inputs. #### pool_voting_thresholds - **Type**: [PoolVotingThresholds](#pycardano.governance.PoolVotingThresholds) | None - **Default**: None - **Description**: Pool voting thresholds. #### drep_voting_thresholds - **Type**: [DRepVotingThresholds](#pycardano.governance.DRepVotingThresholds) | None - **Default**: None - **Description**: DRep voting thresholds. #### min_committee_size - **Type**: int | None - **Default**: None - **Description**: Minimum committee size. #### committee_term_limit - **Type**: int | None - **Default**: None - **Description**: Committee term limit in epochs (uint32). #### governance_action_validity_period - **Type**: int | None - **Default**: None - **Description**: Governance action validity period in epochs (uint32). #### governance_action_deposit - **Type**: int | None - **Default**: None - **Description**: Deposit required for governance actions. #### drep_deposit - **Type**: int | None - **Default**: None - **Description**: Deposit required for DRep registration. #### drep_inactivity_period - **Type**: int | None - **Default**: None - **Description**: DRep inactivity period in epochs (uint32). #### min_fee_ref_script_cost - **Type**: Fraction | None - **Default**: None - **Description**: Minimum fee for reference scripts as a nonnegative interval (numerator, denominator). ``` -------------------------------- ### Generate and Manage Payment Signing Keys Source: https://context7.com/python-cardano/pycardano/llms.txt Create Ed25519 payment signing keys, derive verification keys, and perform file I/O or message signing. ```python from pycardano import PaymentSigningKey, PaymentVerificationKey # Generate a new payment signing key payment_signing_key = PaymentSigningKey.generate() # Derive the verification (public) key payment_verification_key = PaymentVerificationKey.from_signing_key(payment_signing_key) # Save keys to files payment_signing_key.save("payment.skey") payment_verification_key.save("payment.vkey") # Load keys from files loaded_skey = PaymentSigningKey.load("payment.skey") loaded_vkey = PaymentVerificationKey.load("payment.vkey") # Sign a message message = b"Hello Cardano!" signature = payment_signing_key.sign(message) ``` -------------------------------- ### Clone PyCardano Repository Source: https://github.com/python-cardano/pycardano/blob/main/README.md Clones the PyCardano project repository from GitHub to your local machine. This is the first step for development or contributing. ```bash git clone https://github.com/Python-Cardano/pycardano.git ``` -------------------------------- ### Spend using reference script Source: https://context7.com/python-cardano/pycardano/llms.txt Uses a script stored in a UTxO to authorize a transaction without including the script in the transaction body itself. ```python utxo_with_script = None for utxo in context.utxos(str(script_address)): if utxo.output.datum and utxo.output.script: utxo_with_script = utxo break builder = TransactionBuilder(context) builder.add_script_input(utxo_with_script, redeemer=redeemer) # Script from UTxO builder.add_output(TransactionOutput(taker_address, Value(coin=25_000_000))) signed_tx = builder.build_and_sign([psk], change_address=taker_address) ``` -------------------------------- ### Query UTxOs at an Address Source: https://context7.com/python-cardano/pycardano/llms.txt Fetch and display Unspent Transaction Outputs (UTxOs) for a given address, showing transaction IDs and amounts in lovelace. ```python address = "addr_test1vrm9x2zsux7va6w892g38tvchnzahvcd9tykqf3ygnmwtaqyfg52x" utxos = context.utxos(address) for utxo in utxos: print(f"TxId: {utxo.input.transaction_id}, Index: {utxo.input.index}") print(f"Amount: {utxo.output.amount.coin} lovelace") ``` -------------------------------- ### Create Address from String Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/address.md Create Address objects from existing address strings, supporting both Shelley-era (base) and Byron-era formats. ```python address = Address.from_primitive("addr_test1vr2p8st5t5cxqglyjky7vk98k7jtfhdpvhl4e97cezuhn0cqcexl7") byron_address = Address.from_primitive("Ae2tdPwUPEZFRbyhz3cpfC2CumGzNkFBN2L42rcUc2yjQpEkxDbkPodpMAi") ``` -------------------------------- ### Decode Bech32 to DRep Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/api/pycardano.certificate.md Demonstrates how to decode a Bech32 string back into a DRep object and verify it against a constructed DRep instance. ```pycon >>> credential = DRep.decode("drep1ygqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq7vlc9n") >>> khash = VerificationKeyHash(bytes.fromhex("00000000000000000000000000000000000000000000000000000000")) >>> assert credential == DRep(DRepKind.VERIFICATION_KEY_HASH, khash) ``` -------------------------------- ### Build and Sign Transaction in PyCardano Source: https://github.com/python-cardano/pycardano/blob/main/README.md Finalizes the transaction construction process by building and signing it using provided private keys (psk) and specifying a change address. This step is crucial before submitting the transaction. ```python signed_tx = builder.build_and_sign([psk], change_address=address) ``` -------------------------------- ### Spend UTxO with Inline Datum Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/plutus.md Shows how to spend a UTxO that contains an inline datum, removing the need to include the datum in the transaction body. ```python >>> utxo_to_spend = None >>> # Speed the utxo that has both inline script and inline datum >>> for utxo in chain_context.utxos(str(script_address)): >>> if utxo.output.datum and utxo.output.script: >>> utxo_to_spend = utxo >>> break >>> builder = TransactionBuilder(context) >>> builder.add_script_input(utxo_to_spend, redeemer=redeemer) >>> take_output = TransactionOutput(taker_address, 25123456) ``` -------------------------------- ### Customize Map Keys with Metadata Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/api/pycardano.serialization.md Shows how to use the 'key' metadata in dataclass fields to override default serialization keys. ```pycon >>> from dataclasses import dataclass, field >>> @dataclass ... class Test1(MapCBORSerializable): ... a: str=field(default="", metadata={"key": "0"}) ... b: str=field(default="", metadata={"key": "1"}) >>> @dataclass ... class Test2(MapCBORSerializable): ... c: str=field(default=None, metadata={"key": "0", "optional": True}) ... test1: Test1=field(default_factory=Test1, metadata={"key": "1"}) >>> t = Test2(test1=Test1(a="a")) >>> t Test2(c=None, test1=Test1(a='a', b='')) >>> t.to_primitive() {'1': {'0': 'a', '1': ''}} >>> cbor_hex = t.to_cbor_hex() >>> cbor_hex 'a16131a261306161613160' >>> Test2.from_cbor(cbor_hex) Test2(c=None, test1=Test1(a='a', b='')) ``` -------------------------------- ### Create TransactionInput and TransactionOutput (Bottom-Up) Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/instance_creation.md Constructs TransactionInput and TransactionOutput instances by first creating their child components like TransactionId and Address. This method requires explicit instantiation of each part. ```python >>> from pycardano import Address, TransactionId, TransactionInput, TransactionOutput >>> tx_id_hex = "732bfd67e66be8e8288349fcaaa2294973ef6271cc189a239bb431275401b8e5" >>> tx_id = TransactionId(bytes.fromhex(tx_id_hex)) >>> tx_in = TransactionInput(tx_id, 0) >>> tx_in {'index': 0, 'transaction_id': TransactionId(hex='732bfd67e66be8e8288349fcaaa2294973ef6271cc189a239bb431275401b8e5')} >>> addr = Address.decode( ... "addr_test1vrm9x2zsux7va6w892g38tvchnzahvcd9tykqf3ygnmwtaqyfg52x" ... ) >>> tx_out = TransactionOutput(addr, 100000000000) >>> tx_out {'address': addr_test1vrm9x2zsux7va6w892g38tvchnzahvcd9tykqf3ygnmwtaqyfg52x, 'amount': 100000000000, 'datum_hash': None} ``` -------------------------------- ### Define and serialize a custom datum Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/plutus.md Shows how to define a custom dataclass inheriting from PlutusData and serialize it to CBOR. ```python >>> # Create sample datum >>> from typing import List, Dict >>> from dataclasses import dataclass >>> @dataclass ... class MyDatum(PlutusData): ... CONSTR_ID = 1 ... a: int ... b: bytes ... c: List[int] ... d: Dict[int, bytes] >>> datum = MyDatum(123, b"1234", [4, 5, 6], {1: b"1", 2: b"2"}) >>> datum.to_cbor().hex() 'd87a9f187b443132333483040506a2014131024132ff' ``` -------------------------------- ### Submit a Governance Proposal Source: https://context7.com/python-cardano/pycardano/llms.txt Constructs and submits a transaction containing a governance proposal using the TransactionBuilder. ```python builder = TransactionBuilder(context) builder.add_input_address(drep_address) builder.add_proposal( deposit=100_000_000_000, # Proposal deposit reward_account=bytes(reward_address), gov_action=info_action, anchor=proposal_anchor ) signed_tx = builder.build_and_sign( [payment_skey, drep_key_pair.signing_key], change_address=drep_address ) context.submit_tx(signed_tx) ``` -------------------------------- ### Sign Transaction and Create Complete Transaction - PyCardano Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/guides/transaction.md Signs the transaction body hash using a payment signing key and creates a complete, signed transaction with the necessary witness information. Ensure the signing key path is correct. ```python sk = PaymentSigningKey.load("path/to/payment.skey") # Derive a verification key from the signing key vk = PaymentVerificationKey.from_signing_key(sk) # Sign the transaction body hash signature = sk.sign(tx_body.hash()) # Alternatively, we can sign the transaction ID as well signature_alternative = sk.sign(tx_body.id.payload) assert signature == signature_alternative # Add verification key and the signature to the witness set vk_witnesses = [VerificationKeyWitness(vk, signature)] # Create final signed transaction signed_tx = Transaction(tx_body, TransactionWitnessSet(vkey_witnesses=vk_witnesses)) ``` -------------------------------- ### Manage HD Wallets Source: https://context7.com/python-cardano/pycardano/llms.txt Generate mnemonic phrases and derive payment or stake keys using BIP32-Ed25519 paths. ```python from pycardano import HDWallet, PaymentExtendedSigningKey, StakeExtendedSigningKey # Generate a new mnemonic mnemonic = HDWallet.generate_mnemonic(strength=256) # 24 words print(f"Mnemonic: {mnemonic}") # Create wallet from mnemonic hdwallet = HDWallet.from_mnemonic(mnemonic) # Derive payment key (account 0, external chain, address 0) hdwallet_payment = hdwallet.derive_from_path("m/1852'/1815'/0'/0/0") payment_signing_key = PaymentExtendedSigningKey.from_hdwallet(hdwallet_payment) # Derive stake key hdwallet_stake = hdwallet.derive_from_path("m/1852'/1815'/0'/2/0") stake_signing_key = StakeExtendedSigningKey.from_hdwallet(hdwallet_stake) # Get verification keys payment_vkey = payment_signing_key.to_verification_key() stake_vkey = stake_signing_key.to_verification_key() # Create address address = Address( payment_part=payment_vkey.hash(), staking_part=stake_vkey.hash(), network=Network.MAINNET ) ``` -------------------------------- ### Serialize Dataclasses with MapCBORSerializable Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/api/pycardano.serialization.md Demonstrates basic usage of MapCBORSerializable to convert dataclasses to CBOR primitives and hex strings. ```pycon >>> from dataclasses import dataclass, field >>> @dataclass ... class Test1(MapCBORSerializable): ... a: str="" ... b: str="" >>> @dataclass ... class Test2(MapCBORSerializable): ... c: str=None ... test1: Test1=field(default_factory=Test1) >>> t = Test2(test1=Test1(a="a")) >>> t Test2(c=None, test1=Test1(a='a', b='')) >>> t.to_primitive() {'c': None, 'test1': {'a': 'a', 'b': ''}} >>> cbor_hex = t.to_cbor_hex() >>> cbor_hex 'a26163f6657465737431a261616161616260' >>> Test2.from_cbor(cbor_hex) Test2(c=None, test1=Test1(a='a', b='')) ``` -------------------------------- ### pycardano.plutus.PlutusV3Script Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/api/pycardano.plutus.md Represents a Plutus V3 script, inheriting from PlutusScript. ```APIDOC ## *class* pycardano.plutus.PlutusV3Script Bases: [`PlutusScript`](#pycardano.plutus.PlutusScript) ### get_script_hash_prefix() → bytes ### *property* version *: int* ``` -------------------------------- ### TransactionBuilder Class Initialization Source: https://github.com/python-cardano/pycardano/blob/main/docs/source/api/pycardano.transaction.md Initializes a new TransactionBuilder instance to facilitate the creation of a Cardano transaction. ```APIDOC ## TransactionBuilder Initialization ### Description Initializes the TransactionBuilder class, which provides a builder pattern for constructing complex Cardano transactions. ### Parameters #### Request Body - **context** (ChainContext) - Required - The chain context for the transaction. - **utxo_selectors** (List[UTxOSelector]) - Optional - List of selectors for UTxO selection. - **execution_memory_buffer** (float) - Optional - Additional execution memory buffer ratio (default: 0.2). - **execution_step_buffer** (float) - Optional - Additional execution step buffer ratio (default: 0.2). - **fee_buffer** (int) - Optional - Additional fee in lovelace. - **ttl** (int) - Optional - Time to live for the transaction. - **validity_start** (int) - Optional - Validity start slot. - **auxiliary_data** (AuxiliaryData) - Optional - Metadata for the transaction. - **native_scripts** (List[NativeScript]) - Optional - Native scripts associated with the transaction. - **mint** (MultiAsset) - Optional - Assets to be minted. - **required_signers** (List[VerificationKeyHash]) - Optional - List of required signers. - **collaterals** (NonEmptyOrderedSet[UTxO]) - Optional - Collateral UTxOs for the transaction. ```