Skip to main content

A Cardano library in Python

Project description


PyCardano

PyPi version PyPI pyversions PyPI Downloads

PyCardano codecov Documentation Status

Discord Twitter

PyCardano is a Cardano library written in Python. It allows users to create and sign transactions without depending on third-party Cardano serialization tools, such as cardano-cli and cardano-serialization-lib, making it a lightweight library, which is simple and fast to set up in all types of environments.

Current goal of this project is to enable developers to write off-chain code and tests in pure Python for Plutus DApps. Nevertheless, we see the potential in expanding this project to a full Cardano node client, which could be beneficial for faster R&D iterations.

Features

  • Shelly address
  • Transaction builder
  • Transaction signing
  • Multi-asset
  • Chain backend integration
  • Fee calculation
  • UTxO selection
  • Native script
  • Native token
  • Metadata
  • Plutus script
  • Staking certificates
  • Reward withdraw
  • Mnemonic
  • HD Wallet
  • Pool certificate
  • Protocol proposal update
  • Governance actions
  • Byron Address

Installation

Install the library using pip:

pip install pycardano

Install cbor2 pure python implementation (Optional)

cbor2 is a dependency of pycardano. It is used to encode and decode CBOR data. It has two implementations: one is pure Python and the other is C, which is installed by default. The C implementation is faster, but it is less flexible than the pure Python implementation.

For some users, the C implementation may not work properly when deserializing cbor data. For example, the order of inputs of a transaction isn't guaranteed to be the same as the order of inputs in the original transaction (details could be found in this issue). This would result in a different transaction hash when the transaction is serialized again. For users who encounter this issue, we recommend to use the pure Python implementation of cbor2. You can do so by running ensure_pure_cbor2.sh, which inspect the cbor2 installed in the running environment and force install pure python implementation if necessary.

ensure_pure_cbor2.sh

Documentation

https://pycardano.readthedocs.io/en/latest/

Frequently asked questions

https://pycardano.readthedocs.io/en/latest/frequently_asked_questions.html

Examples

Transaction creation and signing

Expand code
"""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)

# Get all UTxOs currently sitting at this address
utxos = context.utxos(address)

# We can also tell the builder to include a specific UTxO in the transaction.
# Similarly, "add_input" could be called multiple times.
builder.add_input(utxos[0])

# Send 1.5 ADA and a native asset (CHOC) in quantity of 2000 to an address.
builder.add_output(
    TransactionOutput(
        Address.from_primitive(
            "addr_test1vrm9x2zsux7va6w892g38tvchnzahvcd9tykqf3ygnmwtaqyfg52x"
        ),
        Value.from_primitive(
            [
                1500000,
                {
                    bytes.fromhex(
                        "57fca08abbaddee36da742a839f7d83a7e1d2419f1507fcbf3916522"  # Policy ID
                    ): {
                        b"CHOC": 2000  # Asset name and amount
                    }
                },
            ]
        ),
    )
)

# We can add multiple outputs, similar to what we can do with inputs.
# Send 2 ADA and a native asset (CHOC) in quantity of 200 to ourselves
builder.add_output(
    TransactionOutput(
        address,
        Value.from_primitive(
            [
                2000000,
                {
                    bytes.fromhex(
                        "57fca08abbaddee36da742a839f7d83a7e1d2419f1507fcbf3916522"  # Policy ID
                    ): {
                        b"CHOC": 200  # Asset name and amount
                    }
                },
            ]
        ),
    )
)

# Create final signed transaction
signed_tx = builder.build_and_sign([psk], change_address=address)

# Submit signed transaction to the network
context.submit_tx(signed_tx)

See more usages under project examples.

There is also a collection of examples under awesome-pycardano.

Development

Click to expand

Workspace setup

Clone the repository:

git clone https://github.com/Python-Cardano/pycardano.git

PyCardano uses poetry to manage its dependencies. Install poetry for osx / linux / bashonwindows:

curl -sSL https://install.python-poetry.org | python3 -

Go to poetry installation for more details.

Change directory into the repo, install all dependencies using poetry, and you are all set!

cd pycardano && poetry install

When testing or running any program, it is recommended to enter a poetry shell in which all python dependencies are automatically configured: poetry shell.

Test

PyCardano uses pytest for unit testing.

Run all tests: make test

Run all tests in a specific test file: poetry run pytest test/pycardano/test_transaction.py

Run a specific test function: poetry run pytest -k "test_transaction_body"

Run a specific test function in a test file: poetry run pytest test/pycardano/test_transaction.py -k "test_transaction_body"

Test coverage

We use Coverage to calculate the test coverage.

Test coverage could be generated by: make cov

A html report could be generated and opened in browser by: make cov-html

Style guidelines

The package uses Google style docstring.

Code could be formatted with command: make format

The code style could be checked by flake8: make qa

Docs generation

The majority of package documentation is created by the docstrings in python files. We use sphinx with Read the Docs theme to generate the html pages.

Build docs and open the docs in browser:

make docs

Donation and Sponsor

If you find this project helpful, please consider donate or sponsor us. Your donation and sponsor will allow us to spend more time on improving PyCardano and adding more features in the future.

You can support us by 1) sponsoring through Github, or 2) donating ADA to our ADA Handle pycardano or to the address below:

addr1vxa4qadv7hk2dd3jtz9rep7sp92lkgwzefwkmsy3qkglq5qzv8c0d

Sponsors :heart:

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pycardano-0.17.0.tar.gz (89.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pycardano-0.17.0-py3-none-any.whl (104.5 kB view details)

Uploaded Python 3

File details

Details for the file pycardano-0.17.0.tar.gz.

File metadata

  • Download URL: pycardano-0.17.0.tar.gz
  • Upload date:
  • Size: 89.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.3 Linux/6.11.0-1018-azure

File hashes

Hashes for pycardano-0.17.0.tar.gz
Algorithm Hash digest
SHA256 0e1623b984d50293a1a68e7054ff890f55d20434d9c4b7b0d72133aa1623f9f0
MD5 5a2ea3fb471b912ff6b84c0332bf0fa7
BLAKE2b-256 dbae11dfd275f4ab36ec41a4499cdd65254b8e0e2edf2a93dc46d34be6858376

See more details on using hashes here.

File details

Details for the file pycardano-0.17.0-py3-none-any.whl.

File metadata

  • Download URL: pycardano-0.17.0-py3-none-any.whl
  • Upload date:
  • Size: 104.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.3 Linux/6.11.0-1018-azure

File hashes

Hashes for pycardano-0.17.0-py3-none-any.whl
Algorithm Hash digest
SHA256 057fa234d511222d1e060531fe2e452903c0aba06f47f894ed26999247b364b6
MD5 d19fe976d3b6c4b4e91ab5fd9d462bdb
BLAKE2b-256 724a18fb3fdfeb78db4ef782836424c449d47a9d597a829d04cc3b2cfff300b7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page