High-level interfaces

PyTezos client

class pytezos.client.PyTezosClient(context: Optional[pytezos.context.impl.ExecutionContext] = None)[source]

Entry point for a developer, start your script with:

from pytezos import pytezos
account(account_id=None)dict[source]

Shortcut for RPC contract request.

Parameters

account_id – tz/KT address, leave None to show info about current key

activate_account(activation_code='', pkh='')

Activate recommended allocations for contributions to the TF fundraiser.

More info https://activate.tezos.com/

Parameters
  • activation_code – Secret code from pdf, leave empty for autocomplete

  • pkh – Public key hash, leave empty for autocomplete

Returns

dict or OperationGroup

activate_protocol(protocol_hash: str)pytezos.block.header.BlockHeader[source]

Initiate user-activated upgrade (sandbox only)

Parameters

protocol_hash – Protocol hash

Return type

BlockHeader

bake_block(min_fee: int = 0)pytezos.block.header.BlockHeader[source]

Create and inject new block with operations from mempool

Parameters

min_fee – filter operations by fee (default is 0)

Return type

BlockHeader

balance()decimal.Decimal[source]

Get account balance.

Returns

amount in tez

ballot(proposal, ballot, source='', period=0)

Vote for a proposal in a given voting period.

Can only be submitted during Testing_vote or Promotion_vote periods, and only once per period. More info https://tezos.gitlab.io/master/whitedoc/voting.html

Parameters
  • proposal – Hash of the proposal

  • ballot – ‘Yay’, ‘Nay’ or ‘Pass’

  • source – Public key hash (of the signatory), leave None for autocomplete

  • period – Number of the current voting period, leave None for autocomplete

Returns

dict or OperationGroup

bulk(*operations: Union[pytezos.operation.group.OperationGroup, pytezos.contract.call.ContractCall])pytezos.operation.group.OperationGroup[source]

Batch multiple operations and contract calls in a single operation group

Parameters

operations – a tuple of operations or contract calls

Return type

OperationGroup

check_message(message: str, public_key: str, signature: str, block: str = 'genesis')None[source]

Check message signature

Parameters
  • message – Signed operation

  • public_key – Signer’s public key

  • signature – Message signature

  • block – Specify block, defaults to genesis

contract(address)pytezos.contract.interface.ContractInterface[source]

Get a high-level interface for a given smart contract id.

Parameters

address – KT address of a smart contract

Return type

ContractInterface

delegation(delegate='', source='', counter=0, fee=0, gas_limit=0, storage_limit=0)

Delegate funds or register yourself as a delegate.

Parameters
  • delegate – tz address of delegate, leave None to register yourself as a delegate

  • source – Address from which funds will be delegated, leave None to use signatory address

  • counter – Current account counter, leave None for autocomplete

  • fee – Leave None for autocomplete

  • gas_limit – Leave None for autocomplete

  • storage_limit – Leave None for autocomplete

Returns

dict or OperationGroup

double_baking_evidence(bh1: str, bh2: str)

Provide evidence of double baking (two different blocks at the same height).

Parameters
  • bh1 – First block hash

  • bh2 – Second block hash

Returns

dict or OperationGroup

double_endorsement_evidence(op1: Dict[str, Any], op2: Dict[str, Any])

Provide evidence of double endorsement (endorsing two different blocks at the same block height).

Inline endorsement format:

{
    "branch": $block_hash,
    "operations": {
        "kind": "endorsement",
        "level": integer ∈ [-2^31-2, 2^31+2]
    },
    "signature"?: $Signature
}
Parameters
  • op1 – Inline endorsement

  • op2 – Inline endorsement

Returns

dict or OperationGroup

endorsement(level: int)Dict[str, Any]

Endorse a block.

Parameters

level – Endorsed level

Returns

dict or OperationGroup

endorsement_with_slot(endorsement: dict, slot: int)

Wrap endorsement

Parameters
  • endorsement – Inlined endorsement

  • slot – Minimum of the slots endorsed

Returns

dict or OperationGroup

failing_noop(arbitrary: str)

Operation to sign arbitrary data without the risk it will be used onchain.

Parameters

arbitrary – Message to sign

Returns

dict or OperationGroup

now()int[source]

Timestamp of the latest block + block time (UTC).

operation(content: dict)pytezos.operation.group.OperationGroup[source]

Create an operation group with single content.

Parameters

content – Operation body (depending on kind)

Return type

OperationGroup

operation_group(protocol=None, branch=None, contents=None, signature=None)pytezos.operation.group.OperationGroup[source]

Create new operation group (multiple contents).

You can leave all fields empty in order to create an empty operation group.

Parameters
  • protocol – Leave None for autocomplete, unless you know what you are doing

  • branch – Leave None for autocomplete

  • contents – List of operation contents (optional)

  • signature – Can be set later

Return type

OperationGroup

origination(script, balance=0, delegate=None, source='', counter=0, fee=0, gas_limit=0, storage_limit=0)

Deploy smart contract (scriptless KT accounts are not used for delegation since Babylon).

Parameters
  • script – {“code”: $Micheline, “storage”: $Micheline}

  • balance – Amount transferred on the balance, WARNING: there is no default way to withdraw funds. More info: https://tezos.stackexchange.com/questions/1315/can-i-withdraw-funds-from-an-empty-smart-contract

  • delegate – Set contract delegate, default None

  • source – Address from which funds will be sent, leave None to use signatory address

  • counter – Current account counter, leave None for autocomplete

  • fee – Leave None for autocomplete

  • gas_limit – Leave None for autocomplete

  • storage_limit – Leave None for autocomplete

Returns

dict or OperationGroup

proposals(proposals, source='', period=0)

Submit and/or upvote proposals to amend the protocol.

Can only be submitted during a proposal period. More info https://tezos.gitlab.io/master/whitedoc/voting.html

Parameters
  • proposals – List of proposal hashes or single proposal hash

  • source – Public key hash (of the signatory), leave None for autocomplete

  • period – Number of the current voting period, leave 0 for autocomplete

Returns

dict or OperationGroup

reveal(public_key='', source='', counter=0, fee=0, gas_limit=0, storage_limit=0)

Reveal the public key associated with a tz address.

Parameters
  • public_key – Public key to reveal, Base58 encoded

  • source – Public key hash of the key revealed, leave None to use signatory address

  • counter – Current account counter, leave None for autocomplete (More info https://tezos.stackexchange.com/questions/632/how-counter-grows)

  • fee – Leave None for autocomplete

  • gas_limit – Leave None for autocomplete

  • storage_limit – Leave None for autocomplete

Returns

dict or OperationGroup

seed_nonce_revelation(level: int, nonce: str)

Reveal the nonce committed operation in the previous cycle.

More info https://tezos.stackexchange.com/questions/567/what-are-nonce-revelations

Parameters
  • level – When nonce hash was committed

  • nonce – Hex string

Returns

dict or OperationGroup

sign_message(message: str, block: Union[str, int] = 'genesis')str[source]

Sign arbitrary message with guarantee that resulting operation won’t be used onchain.

Parameters
  • message – Message to sign

  • block – Specify block, defaults to genesis

Returns

Base58-encoded signature (non-generic)

transaction(destination, amount=0, parameters=None, source='', counter=0, fee=0, gas_limit=0, storage_limit=0)

Transfer tez to a given address (implicit or originated).

If the receiver is a smart contract, then optional parameters may be passed.

Parameters
  • source – Address from which funds will be sent, leave None to use signatory address

  • destination – Address

  • amount – Amount to send in microtez (int) or tez (Decimal) (optional)

  • counter – Current account counter, leave None for autocomplete

  • parameters – { “entrypoint”: $string, “value”: $Micheline expression } (optional)

  • fee – Leave None for autocomplete

  • gas_limit – Leave None for autocomplete

  • storage_limit – Leave None for autocomplete

Returns

dict or OperationGroup

using(shell: Optional[Union[pytezos.rpc.shell.ShellQuery, str]] = None, key: Optional[Union[pytezos.crypto.key.Key, str, dict]] = None, mode: Optional[str] = None, ipfs_gateway: Optional[str] = None)[source]

Change current RPC endpoint and account (private key).

Parameters
  • shell – one of ‘mainnet’, ‘***net’, or RPC node uri, or instance of pytezos.rpc.shell.ShellQuery

  • key – base58 encoded key, path to the faucet file, faucet file itself, alias from tezos-client, or Key

  • mode – whether to use readable or optimized encoding for parameters/storage/other

Returns

A copy of current object with changes applied

wait(*operation_groups: pytezos.operation.group.OperationGroup, min_confirmations: int = 1, num_blocks_wait: int = 5, time_between_blocks: Optional[int] = None, prev_hash: Optional[str] = None)List[dict][source]

Wait for multiple injected operations to get enough confirmations

Parameters
  • min_confirmations – number of block injections to wait for before returning

  • num_blocks_wait – number of blocks to wait for injection

  • time_between_blocks – override the corresponding parameter from constants

  • prev_hash – Current block hash (optional). If not set, current head is used.

Contract interface

class pytezos.contract.interface.ContractInterface(context: pytezos.context.impl.ExecutionContext)[source]

Proxy class for interacting with a contract.

big_map_get(path)[source]

Get BigMap entry as Python object by plain key and block height.

Parameters

path – JSON path to the key (or just key to access default BigMap location). Use / to separate nodes and :: to separate tuple args. In any other case you’d need to escape those symbols.

Returns

object

Deprecated since version 3.0.0: This will be removed in 3.1.0. use .storage[path][to][big_map][key]() instead

property call

Deprecated since version 3.0.0.

This will be removed in 3.1.0. use default() instead

property code

Deprecated since version 3.0.0.

This will be removed in 3.1.0. use to_micheline() instead

property contract

Deprecated since version 3.0.0.

This will be removed in 3.1.0. access ContractInterface directly

classmethod create_from(source)[source]

Create contract interface from its code.

Parameters

source – Michelson code, filename, or Micheline JSON

Return type

ContractInterface

Deprecated since version 3.0.0: This will be removed in 3.1.0. use one of from_file, from_michelson, from_micheline, from_url

static from_context(context: pytezos.context.impl.ExecutionContext)pytezos.contract.interface.ContractInterface[source]

Create contract from the previously loaded context data.

Parameters

context – execution context

Returns

ContractInterface

static from_file(path: str, context: Optional[pytezos.context.impl.ExecutionContext] = None)pytezos.contract.interface.ContractInterface[source]

Create contract from michelson source code stored in a file.

Parameters
  • path – Path to the .tz file

  • context – optional execution context

Return type

ContractInterface

static from_micheline(expression: List[Dict[str, Any]], context: Optional[pytezos.context.impl.ExecutionContext] = None)pytezos.contract.interface.ContractInterface[source]

Create contract from micheline expression.

Parameters
  • expression – [{‘prim’: ‘parameter’}, {‘prim’: ‘storage’}, {‘prim’: ‘code’}]

  • context – optional execution context

Return type

ContractInterface

static from_michelson(source: str, context: Optional[pytezos.context.impl.ExecutionContext] = None)pytezos.contract.interface.ContractInterface[source]

Create contract from michelson source code.

Parameters
  • source – Michelson source code

  • context – optional execution context

Return type

ContractInterface

static from_url(url: str, context: Optional[pytezos.context.impl.ExecutionContext] = None)pytezos.contract.interface.ContractInterface[source]

Create contract from michelson source code available via URL

Parameters
  • url – link to the Michelson file

  • context – optional execution context

Return type

ContractInterface

metadata

Get TZIP-016 contract metadata, if exists

Return type

ContractMetadata

operation_result(operation_group: Dict[str, Any])List[pytezos.contract.result.ContractCallResult][source]

Get operation parameters, and resulting storage as Python objects. Can locate operation inside operation groups with multiple contents and/or internal operations.

Parameters

operation_group – {‘branch’, ‘protocol’, ‘contents’, ‘signature’}

Return type

ContractCallResult

originate(initial_storage=None, mode: Optional[str] = None, balance: Union[int, decimal.Decimal] = 0, delegate: Optional[str] = None)pytezos.operation.group.OperationGroup[source]

Create an origination operation

Parameters
  • initial_storage – Python object, leave None to generate default

  • mode – whether to use readable or optimized (or legacy_optimized) encoding for initial storage

  • balance – initial balance

  • delegate – initial delegator

Return type

OperationGroup

script(initial_storage=None, mode: Optional[str] = None)Dict[str, Any][source]

Generate script for contract origination.

Parameters
  • initial_storage – Python object, leave None to generate default (attach shell/key for smart fill)

  • mode – whether to use readable or optimized (or legacy_optimized) encoding for initial storage

Returns

{“code”: $Micheline, “storage”: $Micheline}

storage_from_file(path: str)None[source]

Load contract storage from file

Parameters

path – path to .tz file

storage_from_micheline(expression)None[source]

Load contract storage from Micheline expression

Parameters

expression – Micheline expression

storage_from_michelson(source: str)None[source]

Load contract storage from Michelson code

Parameters

source – Michelson code

property text

Deprecated since version 3.0.0.

This will be removed in 3.1.0. use to_michelson() instead

to_file(path: str)None[source]

Write contract source to a .tz file

Parameters

path – path to the file

to_micheline()List[Dict[str, Any]][source]

Get contract script in Micheline JSON

Returns

[{‘prim’: ‘parameter’}, {‘prim’: ‘storage’}, {‘prim’: ‘code’}]

to_michelson()str[source]

Get contract listing in formatted Michelson

Returns

string

property token_metadata

Get TZIP-021 contract token metadata proxy

Return type

ContractTokenMetadataProxy

using(shell: Optional[Union[pytezos.rpc.shell.ShellQuery, str]] = None, key: Optional[Union[pytezos.crypto.key.Key, str]] = None, block_id: Optional[Union[str, int]] = None, mode: Optional[str] = None, ipfs_gateway: Optional[str] = None)pytezos.contract.interface.ContractInterface[source]

Change the block at which the current contract is inspected.

Also, if address is undefined you can specify RPC endpoint, and private key.

Parameters
  • shell – one of ‘mainnet’, ‘***net’, or RPC node uri, or instance of pytezos.rpc.shell.ShellQuery

  • key – base58 encoded key, path to the faucet file, alias from tezos-client, or instance of Key

  • block_id – block height / hash / offset to use, default is head

  • mode – whether to use readable or optimized encoding for parameters/storage/other

Return type

ContractInterface

Contract entrypoint proxy

class pytezos.contract.entrypoint.ContractEntrypoint(context: pytezos.context.impl.ExecutionContext, entrypoint: str)[source]

Proxy class for spawning ContractCall instances.

__call__(*args, **kwargs)pytezos.contract.call.ContractCall[source]

Spawn a contract call proxy initialized with the entrypoint name

Parameters
  • args – entrypoint args

  • kwargs – entrypoint key-value args

Return type

ContractCall

decode(value: Union[str, Dict[str, Any]], entrypoint: Optional[str] = None)Dict[str, Any][source]

Convert from Michelson to Python type system

Parameters
  • value – Micheline JSON expression or Michelson value

  • entrypoint – overwrite current entrypoint (in case you want to parse tx parameters)

Returns

Python object {entrypoint: value}

encode(py_obj, mode: Optional[str] = None)dict[source]

Encode transaction parameters from the given Python object

Parameters
  • py_obj – Python object

  • mode – whether to use readable or optimized (or legacy_optimized) encoding

Returns

{entrypoint, value}

Contract call proxy

class pytezos.contract.call.ContractCall(context: pytezos.context.impl.ExecutionContext, parameters: dict, amount: Union[int, decimal.Decimal] = 0)[source]

Proxy class encapsulating a contract call: contract type scheme, contract address, parameters, and amount

as_transaction(**kwargs)pytezos.operation.group.OperationGroup[source]

Get operation content.

Return type

OperationGroup

callback_view()[source]

Get return value of an on-chain callback method.

Returns

Decoded parameters of a callback

cmdline()str[source]

Generate command line for tezos-client.

inject(_async=True, preapply=True, check_result=True, num_blocks_wait=5)pytezos.operation.group.OperationGroup[source]

Send operation to blockchain.

Deprecated since version 3.2.2: This will be removed in 4.0.0. use send() instead

interpret(storage=None, source=None, sender=None, amount=None, balance=None, chain_id=None, level=None, now=None, self_address=None)pytezos.contract.result.ContractCallResult[source]

Run code in the builtin REPL (WARNING! Not recommended for critical tasks).

Parameters
  • storage – initial storage as Python object, leave None if you want to generate a dummy one

  • source – patch SOURCE

  • sender – patch SENDER

  • amount – patch AMOUNT

  • balance – patch BALANCE

  • chain_id – patch CHAIN_ID

  • level – patch LEVEL

  • now – patch NOW

  • self_address – patch SELF/SELF_ADDRESS

Return type

pytezos.contract.result.ContractCallResult

property operation_group

Deprecated since version 3.0.0.

This will be removed in 4.0.0. use as_transaction() instead

result(storage=None, source=None, sender=None, gas_limit=None)pytezos.contract.result.ContractCallResult[source]

Simulate operation and parse the result.

Parameters
  • storage – Python object only. If storage is specified, run_code is called instead of run_operation.

  • source – Can be specified for unit testing purposes

  • sender – Can be specified for unit testing purposes, see https://tezos.gitlab.io/whitedoc/michelson.html#operations-on-contracts for the difference

  • gas_limit – Specify gas limit (default is gas hard limit)

Return type

ContractCallResult

Deprecated since version 3.0.0: This will be removed in 3.1.0. use either run_code or run_operation

run_code(storage=None, source=None, sender=None, amount=None, balance=None, chain_id=None, gas_limit=None)pytezos.contract.result.ContractCallResult[source]

Execute using RPC interpreter.

Parameters
  • storage – initial storage as Python object, leave None if you want to generate a dummy one

  • source – patch SOURCE

  • sender – patch SENDER

  • amount – patch AMOUNT

  • balance – patch BALANCE

  • chain_id – patch CHAIN_ID

  • gas_limit – restrict max consumed gas

Return type

ContractCallResult

run_operation()pytezos.contract.result.ContractCallResult[source]

Simulate operation using real context.

Return type

ContractCallResult

send(gas_reserve: int = 100, burn_reserve: int = 100, min_confirmations: int = 0, ttl: Optional[int] = None)pytezos.operation.group.OperationGroup[source]

Fill, sign, and broadcast the transaction

Parameters
  • gas_reserve – Add a safe reserve for dynamically calculated gas limit (default is 100).

  • burn_reserve – Add a safe reserve for dynamically calculated storage limit (default is 100).

  • min_confirmations – number of block injections to wait for before returning (default is 0, i.e. async mode)

  • ttl – Number of blocks to wait in the mempool before removal (default is 5 for public network, 60 for sandbox)

Returns

OperationGroup with hash filled

send_async(ttl: int, counter: int, gas_limit: int, storage_limit: int, minimal_nanotez_per_gas_unit: Optional[int] = None)pytezos.operation.group.OperationGroup[source]

Send operation without simulation or pre-validation

Parameters
  • ttl – Number of blocks to wait in the mempool before removal (default is 5 for public network, 60 for sandbox)

  • counter – Set counter value

  • gas_limit – Set gas_limit value

  • storage_limit – Set storage_limit value

  • minimal_nanotez_per_gas_unit – Override minimal_nanotez_per_gas_unit constant

Return type

OperationGroup

storage_view()[source]

Get return value of an off-chain storage view.

Returns

Decoded parameters of a callback

view()[source]

Deprecated since version 3.0.4: This will be removed in 3.1.0. Use callback_view instead

with_amount(amount: Union[int, decimal.Decimal])pytezos.contract.call.ContractCall[source]

Set amount of funds to send with transaction to the contract.

Parameters

amount – amount in microtez (int) or tez (Decimal)

Return type

ContractCall

Contract call result

class pytezos.contract.result.ContractCallResult(**props)[source]

Encapsulates the result of a contract invocation.

classmethod from_run_code(response: Dict[str, Any], parameters, context: pytezos.context.impl.ExecutionContext)pytezos.contract.result.ContractCallResult[source]

Parse a result of pytezos.contract.call.ContractCall.run_code() execution.

Parameters
  • response – RPC response (JSON)

  • parameters – {“entrypoint”: str, “value”: $Micheline}

  • context – execution context

Return type

ContractCallResult

classmethod from_run_operation(operation_group: Dict[str, Any], context: pytezos.context.impl.ExecutionContext)List[pytezos.contract.result.ContractCallResult][source]

Get a list of results from an operation group content with metadata.

Parameters
  • operation_group – {…, “contents”: [{…, kind: “transaction”, …}]}

  • context – execution context

Return type

ContractCallResult

Contract storage proxy

class pytezos.contract.data.ContractData(context: pytezos.context.impl.ExecutionContext, data: pytezos.michelson.types.base.MichelsonType, path='', title=None)[source]
__call__(try_unpack=False)[source]

Get Michelson value as a Python object

Parameters

try_unpack – try to unpack utf8-encoded strings or PACKed Michelson expressions

decode(value)[source]

Convert from Michelson to Python type system

Parameters

value – Micheline JSON expression or Michelson value

Returns

Python object

default()[source]

Deprecated since version 3.0.0: This will be removed in 3.1.0.

dummy()[source]

Try to generate a dummy (empty) value

Returns

Python object

encode(py_obj, mode: Optional[str] = None)[source]

Convert from Python to Michelson type system

Parameters
  • py_obj – Python object

  • mode – whether to use readable or optimized (or legacy_optimized) encoding

Returns

Micheline JSON expression

to_micheline(optimized=False)[source]

Get as Micheline JSON expression

Parameters

optimized – use optimized data form for some domain types (timestamp, address, etc.)

to_michelson(optimized=False)[source]

Get as Michelson value

Parameters

optimized – use optimized data form for some domain types (timestamp, address, etc.)