Python SDK
CashScript-Py is a Python SDK for building smart contract transactions on Bitcoin Cash (BCH), both on the server and in scripts/tools. The SDK enables:
standardized network providers to query UTXOs, block height, and broadcast transactions
a simple API for transaction building when spending CashScript contracts
ergonomic signature handling via
SignatureTemplate
Info: CashScript-Py can be used in any Python codebase. You do not need any special framework to use it.
When to use the SDK
The CashScript-Py SDK is designed to make it as easy as possible to create smart contract transactions for contracts written in CashScript (the smart contract language). We recommend using the SDK whenever you are using CashScript.
If you are not using the CashScript contract language, you can still use the CashScript SDK for transaction building and BCH networking functionality! This can be especially useful if you are familiar with the CashScript classes and want manual control over the input and outputs in a transaction. The SDK makes it easy to spend from P2PKH inputs and send to different types of outputs, including OP_RETURN data outputs.
It’s also possible to use the SDK with hand-optimized scripts not produced by cashc, but this is considered advanced
usage (see Advanced: non-CashScript contracts).
The 4 SDK classes
The CashScript-Py SDK consists of 4 classes that form one cohesive structure:
ContractTransactionBuilderNetworkProviderSignatureTemplate
SDK usage
Typical usage is:
Compile one or more contract artifacts with
cashc(JSON).Instantiate a
NetworkProvider.Instantiate a
Contractfrom an artifact and constructor args.Create a
TransactionBuilderand add inputs/outputs.Use
SignatureTemplateif you need to generate a signature.
For complete end-to-end examples, see: Examples.
Example
from cashscript_py import Contract, ElectrumNetworkProvider, SignatureTemplate, TransactionBuilder
from .somewhere import contract_args, alice_wif
provider = ElectrumNetworkProvider("chipnet")
contract = Contract(artifact, contract_args, provider)
alice_template = SignatureTemplate(alice_wif)
unlocker = contract.unlock["transfer"](alice_template)
builder = TransactionBuilder(provider)
# then use the builder to spend a UTXO with the contract unlocker
builder.add_input(contract_utxo, unlocker)
builder.add_output(...)
tx_hex = builder.build()
print(tx_hex)
Advanced: non-CashScript contracts
You can also use the SDK without relying on the CashScript language/compiler. You can either:
implement custom locking/unlocking bytecode and use
TransactionBuilderdirectly, orimplement a custom
Unlockerto use during transaction building