Transaction

Definitions of transaction-related data types.

class pycardano.transaction.TransactionInput(transaction_id: 'TransactionId', index: 'int')

Bases: ArrayCBORSerializable

transaction_id: TransactionId
index: int
class pycardano.transaction.AssetName(payload: bytes)

Bases: ConstrainedBytes

MAX_SIZE = 32
class pycardano.transaction.Asset(*args, **kwargs)

Bases: DictCBORSerializable

KEY_TYPE

alias of AssetName

VALUE_TYPE

alias of int

normalize() Asset

Normalize the Asset by removing zero values.

union(other: Asset) Asset
classmethod from_primitive(value: dict) DictBase

Restore a primitive value to its original class type.

Parameters:
  • cls (DictBase) – The original class type.

  • value (Primitive) – A CBOR primitive.

Returns:

Restored object.

Return type:

DictBase

Raises:

DeserializeException – When the object could not be restored from primitives.

to_shallow_primitive() dict

Convert the instance to a CBOR primitive. If the primitive is a container, e.g. list, dict, the type of its elements could be either a Primitive or a CBORSerializable.

Returns:

A CBOR primitive.

Return type:

Primitive

Raises:

SerializeException – When the object could not be converted to CBOR primitive types.

class pycardano.transaction.MultiAsset(*args, **kwargs)

Bases: DictCBORSerializable

KEY_TYPE

alias of ScriptHash

VALUE_TYPE

alias of Asset

union(other: MultiAsset) MultiAsset
normalize() MultiAsset

Normalize the MultiAsset by removing zero values.

filter(criteria=typing.Callable[[pycardano.hash.ScriptHash, pycardano.transaction.AssetName, int], bool]) MultiAsset

Filter items by criteria.

Parameters:

criteria – A function that takes in three input arguments (policy_id, asset_name, amount) and returns a bool. If returned value is True, then the asset will be kept, otherwise discarded.

Returns:

A new filtered MultiAsset object.

count(criteria=typing.Callable[[pycardano.hash.ScriptHash, pycardano.transaction.AssetName, int], bool]) int

Count number of distinct assets that satisfy a certain criteria.

Parameters:

criteria – A function that takes in three input arguments (policy_id, asset_name, amount) and returns a bool.

Returns:

Total number of distinct assets that satisfy the criteria.

Return type:

int

classmethod from_primitive(value: dict) DictBase

Restore a primitive value to its original class type.

Parameters:
  • cls (DictBase) – The original class type.

  • value (Primitive) – A CBOR primitive.

Returns:

Restored object.

Return type:

DictBase

Raises:

DeserializeException – When the object could not be restored from primitives.

to_shallow_primitive() dict

Convert the instance to a CBOR primitive. If the primitive is a container, e.g. list, dict, the type of its elements could be either a Primitive or a CBORSerializable.

Returns:

A CBOR primitive.

Return type:

Primitive

Raises:

SerializeException – When the object could not be converted to CBOR primitive types.

class pycardano.transaction.Value(coin: 'int' = 0, multi_asset: 'MultiAsset' = <factory>)

Bases: ArrayCBORSerializable

coin: int = 0

Amount of ADA

multi_asset: MultiAsset

Multi-assets associated with the UTxO

union(other: Union[Value, int]) Value
to_shallow_primitive()
Returns:

A CBOR primitive.

Return type:

Primitive

Raises:

SerializeException – When the object could not be converted to CBOR primitive types.

class pycardano.transaction.TransactionOutput(address: 'Address', amount: 'Union[Value]', datum_hash: 'Optional[DatumHash]' = None, datum: 'Optional[Datum]' = None, script: 'Optional[Union[NativeScript, PlutusV1Script, PlutusV2Script, PlutusV3Script]]' = None, post_alonzo: 'Optional[bool]' = False)

Bases: CBORSerializable

address: Address
amount: Value
datum_hash: Optional[DatumHash] = None
datum: Optional[Union[PlutusData, dict, int, bytes, IndefiniteList, RawCBOR, RawPlutusData]] = None
script: Optional[Union[NativeScript, PlutusV1Script, PlutusV2Script, PlutusV3Script]] = None
post_alonzo: Optional[bool] = False
validate()

Validate the data stored in the current instance. Defaults to always pass.

Raises:

InvalidDataException – When the data is invalid.

property lovelace: int
to_primitive() Union[bytes, bytearray, str, int, float, Decimal, bool, None, tuple, list, IndefiniteList, dict, defaultdict, OrderedDict, datetime, Pattern, CBORSimpleValue, CBORTag, set, frozenset, frozendict, FrozenList, IndefiniteFrozenList, ByteString]

Convert the instance and its elements to CBOR primitives recursively.

Returns:

A CBOR primitive.

Return type:

Primitive

Raises:

SerializeException – When the object or its elements could not be converted to CBOR primitive types.

classmethod from_primitive(value: Union[bytes, bytearray, str, int, float, Decimal, bool, None, tuple, list, IndefiniteList, dict, defaultdict, OrderedDict, datetime, Pattern, CBORSimpleValue, CBORTag, set, frozenset, frozendict, FrozenList, IndefiniteFrozenList, ByteString]) TransactionOutput

Turn a CBOR primitive to its original class type.

Parameters:
  • cls (CBORBase) – The original class type.

  • value (Primitive) – A CBOR primitive.

Returns:

A CBOR serializable object.

Return type:

CBORBase

Raises:

DeserializeException – When the object could not be restored from primitives.

class pycardano.transaction.UTxO(input: 'TransactionInput', output: 'TransactionOutput')

Bases: ArrayCBORSerializable

input: TransactionInput
output: TransactionOutput
class pycardano.transaction.TransactionBody(inputs: 'List[TransactionInput]' = <factory>, outputs: 'List[TransactionOutput]' = <factory>, fee: 'int' = 0, ttl: 'Optional[int]' = None, certificates: 'Optional[List[Certificate]]' = None, withdraws: 'Optional[Withdrawals]' = None, update: 'Any' = None, auxiliary_data_hash: 'Optional[AuxiliaryDataHash]' = None, validity_start: 'Optional[int]' = None, mint: 'Optional[MultiAsset]' = None, script_data_hash: 'Optional[ScriptDataHash]' = None, collateral: 'Optional[List[TransactionInput]]' = None, required_signers: 'Optional[List[VerificationKeyHash]]' = None, network_id: 'Optional[Network]' = None, collateral_return: 'Optional[TransactionOutput]' = None, total_collateral: 'Optional[int]' = None, reference_inputs: 'Optional[List[TransactionInput]]' = None)

Bases: MapCBORSerializable

inputs: List[TransactionInput]
outputs: List[TransactionOutput]
fee: int = 0
ttl: Optional[int] = None
certificates: Optional[List[Union[StakeRegistration, StakeDeregistration, StakeDelegation, PoolRegistration, PoolRetirement]]] = None
withdraws: Optional[Withdrawals] = None
update: Any = None
auxiliary_data_hash: Optional[AuxiliaryDataHash] = None
validity_start: Optional[int] = None
mint: Optional[MultiAsset] = None
script_data_hash: Optional[ScriptDataHash] = None
collateral: Optional[List[TransactionInput]] = None
required_signers: Optional[List[VerificationKeyHash]] = None
network_id: Optional[Network] = None
collateral_return: Optional[TransactionOutput] = None
total_collateral: Optional[int] = None
reference_inputs: Optional[List[TransactionInput]] = None
validate()

Validate the data stored in the current instance. Defaults to always pass.

Raises:

InvalidDataException – When the data is invalid.

hash() bytes
property id: TransactionId
class pycardano.transaction.Transaction(transaction_body: 'TransactionBody', transaction_witness_set: 'TransactionWitnessSet', valid: 'bool' = True, auxiliary_data: 'Optional[AuxiliaryData]' = None)

Bases: ArrayCBORSerializable

transaction_body: TransactionBody
transaction_witness_set: TransactionWitnessSet
valid: bool = True
auxiliary_data: Optional[AuxiliaryData] = None
property id: TransactionId
class pycardano.transaction.Withdrawals(*args, **kwargs)

Bases: DictCBORSerializable

A disctionary of reward addresses to reward withdrawal amount.

Key is address bytes, value is an integer.

Examples

>>> 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\xfam\xdfmi':
1000000}
KEY_TYPE

alias of bytes

VALUE_TYPE

alias of int

class pycardano.txbuilder.TransactionBuilder(context: ~pycardano.backend.base.ChainContext, utxo_selectors: ~typing.List[~pycardano.coinselection.UTxOSelector] = <factory>, execution_memory_buffer: float = 0.2, execution_step_buffer: float = 0.2, fee_buffer: ~typing.Optional[int] = None, ttl: ~typing.Optional[int] = None, validity_start: ~typing.Optional[int] = None, auxiliary_data: ~typing.Optional[~pycardano.metadata.AuxiliaryData] = None, native_scripts: ~typing.Optional[~typing.List[~pycardano.nativescript.NativeScript]] = None, mint: ~typing.Optional[~pycardano.transaction.MultiAsset] = None, required_signers: ~typing.Optional[~typing.List[~pycardano.hash.VerificationKeyHash]] = None, collaterals: ~typing.List[~pycardano.transaction.UTxO] = <factory>, certificates: ~typing.Optional[~typing.List[~typing.Union[~pycardano.certificate.StakeRegistration, ~pycardano.certificate.StakeDeregistration, ~pycardano.certificate.StakeDelegation, ~pycardano.certificate.PoolRegistration, ~pycardano.certificate.PoolRetirement]]] = None, withdrawals: ~typing.Optional[~pycardano.transaction.Withdrawals] = None, witness_override: ~typing.Optional[int] = None, initial_stake_pool_registration: ~typing.Optional[bool] = False, use_redeemer_map: ~typing.Optional[bool] = True)

Bases: object

A class builder that makes it easy to build a transaction.

context: ChainContext
utxo_selectors: List[UTxOSelector]
execution_memory_buffer: float = 0.2

Additional amount of execution memory (in ratio) that will be on top of estimation

execution_step_buffer: float = 0.2

Additional amount of execution step (in ratio) that will be added on top of estimation

fee_buffer: Optional[int] = None

Additional amount of fee (in lovelace) that will be added on top of estimation.

ttl: Optional[int] = None
validity_start: Optional[int] = None
auxiliary_data: Optional[AuxiliaryData] = None
native_scripts: Optional[List[NativeScript]] = None
mint: Optional[MultiAsset] = None
required_signers: Optional[List[VerificationKeyHash]] = None
collaterals: List[UTxO]
certificates: Optional[List[Union[StakeRegistration, StakeDeregistration, StakeDelegation, PoolRegistration, PoolRetirement]]] = None
withdrawals: Optional[Withdrawals] = None
reference_inputs: Set[Union[UTxO, TransactionInput]]
witness_override: Optional[int] = None
initial_stake_pool_registration: Optional[bool] = False
use_redeemer_map: Optional[bool] = True

Whether to serialize redeemers as a map or a list. Default is True.

add_input(utxo: UTxO) TransactionBuilder

Add a specific UTxO to transaction’s inputs.

Parameters:

utxo (UTxO) – UTxO to be added.

Returns:

Current transaction builder.

Return type:

TransactionBuilder

add_script_input(utxo: UTxO, script: Optional[Union[UTxO, NativeScript, PlutusV1Script, PlutusV2Script, PlutusV3Script]] = None, datum: Optional[Union[PlutusData, dict, int, bytes, IndefiniteList, RawCBOR, RawPlutusData]] = None, redeemer: Optional[Redeemer] = None) TransactionBuilder

Add a script UTxO to transaction’s inputs.

Parameters:
  • utxo (UTxO) – Script UTxO to be added.

  • script (Optional[Union[UTxO, NativeScript, PlutusV1Script, PlutusV2Script, PlutusV3Script]]) – A plutus script. If not provided, the script will be inferred from the input UTxO (first arg of this method). The script can also be a specific UTxO whose output contains an inline script.

  • datum (Optional[Datum]) – A plutus datum to unlock the UTxO.

  • redeemer (Optional[Redeemer]) – A plutus redeemer to unlock the UTxO.

Returns:

Current transaction builder.

Return type:

TransactionBuilder

add_minting_script(script: Union[UTxO, NativeScript, PlutusV1Script, PlutusV2Script, PlutusV3Script], redeemer: Optional[Redeemer] = None) TransactionBuilder

Add a minting script along with its datum and redeemer to this transaction.

Parameters:
Returns:

Current transaction builder.

Return type:

TransactionBuilder

add_withdrawal_script(script: Union[UTxO, NativeScript, PlutusV1Script, PlutusV2Script, PlutusV3Script], redeemer: Optional[Redeemer] = None) TransactionBuilder

Add a withdrawal script along with its redeemer to this transaction.

Parameters:
Returns:

Current transaction builder.

Return type:

TransactionBuilder

add_input_address(address: Union[Address, str]) TransactionBuilder

Add an address to transaction’s input address. Unlike add_input(), which deterministically adds a UTxO to the transaction’s inputs, add_input_address will not immediately select any UTxO when called. Instead, it will delegate UTxO selection to UTxOSelector`s of the builder when :meth:`build is called.

Parameters:

address (Union[Address, str]) – Address to be added.

Returns:

The current transaction builder.

Return type:

TransactionBuilder

add_output(tx_out: TransactionOutput, datum: Optional[Union[PlutusData, dict, int, bytes, IndefiniteList, RawCBOR, RawPlutusData]] = None, add_datum_to_witness: bool = False) TransactionBuilder

Add a transaction output.

Parameters:
  • tx_out (TransactionOutput) – The transaction output to be added.

  • datum (Datum) – Attach a datum hash to this transaction output.

  • add_datum_to_witness (bool) – Optionally add the actual datum to transaction witness set. Defaults to False.

Returns:

Current transaction builder.

Return type:

TransactionBuilder

property inputs: List[UTxO]
property potential_inputs: List[UTxO]
property excluded_inputs: List[UTxO]
property input_addresses: List[Union[Address, str]]
property outputs: List[TransactionOutput]
property fee: int
property all_scripts: List[Union[bytes, NativeScript, PlutusV1Script, PlutusV2Script]]
property scripts: List[Union[bytes, NativeScript, PlutusV1Script, PlutusV2Script]]
property datums: Dict[DatumHash, Union[PlutusData, dict, int, bytes, IndefiniteList, RawCBOR, RawPlutusData]]
redeemers() Union[List[Redeemer], RedeemerMap]
property script_data_hash: Optional[ScriptDataHash]
build_witness_set(remove_dup_script: bool = False) TransactionWitnessSet

Build a transaction witness set, excluding verification key witnesses. This function is especially useful when the transaction involves Plutus scripts.

Parameters:

remove_dup_script (bool) – Whether to remove scripts, that are already attached to inputs, from the witness set.

Returns:

A transaction witness set without verification key witnesses.

Return type:

TransactionWitnessSet

build(*args, **kwargs)
build_and_sign(signing_keys: List[Union[SigningKey, ExtendedSigningKey]], change_address: Optional[Address] = None, merge_change: Optional[bool] = False, collateral_change_address: Optional[Address] = None, auto_validity_start_offset: Optional[int] = None, auto_ttl_offset: Optional[int] = None, auto_required_signers: Optional[bool] = None, force_skeys: Optional[bool] = False) Transaction

Build a transaction body from all constraints set through the builder and sign the transaction with provided signing keys.

Parameters:
  • signing_keys (List[Union[SigningKey, ExtendedSigningKey]]) – A list of signing keys that will be used to sign the transaction.

  • change_address (Optional[Address]) – Address to which changes will be returned. If not provided, the transaction body will likely be unbalanced (sum of inputs is greater than the sum of outputs).

  • merge_change (Optional[bool]) – If the change address match one of the transaction output, the change amount will be directly added to that transaction output, instead of being added as a separate output.

  • collateral_change_address (Optional[Address]) – Address to which collateral changes will be returned.

  • auto_validity_start_offset (Optional[int]) – Automatically set the validity start interval of the transaction to the current slot number + the given offset (default -1000). A manually set validity start will always take precedence.

  • auto_ttl_offset (Optional[int]) – Automatically set the validity end interval (ttl) of the transaction to the current slot number + the given offset (default 10_000). A manually set ttl will always take precedence.

  • auto_required_signers (Optional[bool]) – Automatically add all pubkeyhashes of transaction inputs and the given signers to required signatories (default only for Smart Contract transactions). Manually set required signers will always take precedence.

  • force_skeys (Optional[bool]) – Whether to force the use of signing keys for signing the transaction. Default is False, which means that provided signing keys will only be used to sign the transaction if they are actually required by the transaction. This is useful to reduce tx fees by not including unnecessary signatures. If set to True, all provided signing keys will be used to sign the transaction.

Returns:

A signed transaction.

Return type:

Transaction