Working with wallets

The example presented in the quickstart section will certainly fail in your environment, as you don’t have the same wallet created yet. In order to set up a new wallet, you need to learn first about two kinds of objects:

  1. Wallet which represents a single Cardano wallet and allows for operations like balance retrieval, searching through the transaction history and spending funds. Wallets are identified by unique ID which is deterministically derived from the seed (mnemonic phrase), so each time you delete and create a wallet again, it receives the same ID.

  2. WalletService which is responsible for creating new and listing or retrieving existing wallets.

  3. Backend, which represents the underlying service layer. At the moment the only backend available is the REST API provided by cardano-wallet, represented by the WalletREST objects.

Note

Remember that creating or deleting a wallet will not record any information on the blockchain. If the wallet you’re creating existed before, you’ll be presented its’ entire history. Likweise, if you delete a wallet, you’ll be able to create it again in this or any other software and claim the funds or see historical transactions.

Creating wallets

Let’s assume your backend doesn’t know anything about the wallet eff9cc89621111677a501493ace8c3f05608c0ce, which is exactly your starting scenario. In order to obtain that wallet object, you’d have first to create it:

In [1]: from cardano.wallet import WalletService

In [2]: from cardano.backends.walletrest import WalletREST

In [3]: ws = WalletService(WalletREST(port=8090))

In [4]: wal = ws.create_wallet(
        name="test wallet",
        mnemonic="resist render west spin antique wild gossip thing syrup network risk gospel seek drop receive",
        passphrase="xxx",
        )

In [4]: wal.sync_progress()
Out[4]: 0.05

In [5]: wal.balance()
Out[5]: Balance(total=Decimal('0.000000'), available=Decimal('0.000000'), reward=Decimal('0.000000'))

Even though this wallet may contain some funds (on testnet), right after creation the balance will be null and the transaction history empty. This is because of ongoing sync process which scans the entire blockchain for transaction history.

Balance tuple

The balance returned by wal.balance() (as well as balances of native assets) is a subclass of collections.namedtuple. It consists of three elements:

  1. total — indicating the total amount of funds in the wallet, without going into too much

    details.

  2. available — the amount of funds without staking rewards, might be also considered as the

    principal paid to the wallet and used for staking.

  3. reward — the amount received as staking interest.

Hence, to just get the full balance, you may use wal.balance().total.

Sync progress

The value returned by .sync_progress() is a float number that represents how advanced the synchronization process is. It starts from 0.0 and goes up to 1.0 which says the wallet is up to date with the blockchain. A simple synchronization wait loop might look like the following:

In [6]: import time

In [7]: while wal.sync_progress() < 1.0:
            time.sleep(1)

Depending on your conditions, you may use other sleep period value. Just remember to call it within the loop, as it releases CPU time to other processes instead of constantly bombarding your REST API with requests.

Retrieving existing wallets

In case your backend already knows about the wallet, you may use much simpler approach:

In [1]: from cardano.wallet import Wallet

In [2]: from cardano.backends.walletrest import WalletREST

In [3]: wal = Wallet("eff9cc89621111677a501493ace8c3f05608c0ce", backend=WalletREST(port=8090))

In [4]: wal.sync_progress()
Out[4]: 1.0

In [5]: wal.balance()
Out[5]: Balance(total=Decimal('998.831199'), available=Decimal('998.831199'), reward=Decimal('0.000000'))

Note

Although the backend is a required argument right now, the example passes it to the contstructor like it was optional. This is because in the near future some offline functionality will be added to the Wallet class and initialization without backend will be available.

Removing wallets

This is a trivial operation:

In [6]: wal.delete()

After that, if you try to use the wallet object again, the cardano.backends.walletrest.exceptions.NotFound exception will be raised.

API reference

class cardano.wallet.Wallet(wid, backend, passphrase=None)

Represents a single wallet. Allows for browsing the history, checking balance and spending funds.

Parameters
  • wid – the wallet ID

  • backend – the backend used to handle the underlying service layer

  • passphrase – the passphrase protecting the wallet’s spending functionality, not required for read-only operations. It will be stored for the entire lifetime of the object in .passphrase field. It might be also provided for each individual spend operation, then it will be discarded after use.

addresses(with_usage=False)

Returns full list of already generated addresses.

Parameters

with_usage – A bool indicating whether to retrieve used/unused address status too.

Return type

list of Address objects when with_usage == False and of (Address, bool) tuples otherwise.

assets()

Returns the balance of native assets.

Return type

dict of AssetID: Balance pairs

balance()

Returns the Balance of the wallet.

delete()

Deletes the wallet from the backend. It doesn’t wipe the funds; the wallet may be restored later on, using the mnemonic phrase.

estimate_fee(destinations, metadata=None)

Estimates the fee for a potential transaction to specified destinations and carrying optional metadata. Returns a tuple of estimated minimum and maximum fee, in ADA.

Parameters
  • destinations – a list of Address and amount pairs [(address, amount), ...]

  • metadata – metadata to be sent, as Metadata instance od dict mapping int keys to values of acceptable types

Return type

(Decimal, Decimal)

first_unused_address()

Returns the first unused address. There is no internal pointer and the result is based on blockchain and mempool state only, and their interpretation by the backend, so multiple subsequent calls will return the same address if no transfer is received between them.

stake(pool, passphrase=None)

Stakes all wallet balance at the given pool.

Parameters
  • pool – The pool to stake ADA at

  • passphrase – the passphrase to the wallet. It takes precedence over self.passphrase and is discarded after use. If neither self.passphrase nor passphrase is set, a MissingPassphrase exception will be raised.

Return type

Transaction

stake_pools(stake=None)

Returns a list of known stake pools ordered by descending rewards.

Parameters

stake (Decimal) – The amount of ADA to be staked. Optional. If omitted, the wallet’s total balance will be used instead.

Return type

list

staking_status()

Returns information about staking status.

Return type

StakingStatus

sync_progress()

Returns the progress of synchronization with the blockchain. The value is float ranging from 0.0 to 1.0.

transfer(address, amount, assets=None, metadata=None, allow_withdrawal=False, ttl=None, passphrase=None)

Sends a transfer from the wallet. Returns the resulting transaction.

Parameters
  • address – destination Address or subtype

  • amount – amount to send

  • assets – a sequence of AssetID and quantity pairs

  • metadata – metadata to be sent, as Metadata instance od dict mapping int keys to values of acceptable types

  • allow_withdrawal – Allow withdrawing staking rewards to cover the transaction amount or fee.

  • ttl – Time To Live in seconds. After TTL has lapsed the nodes give up on broadcasting the transaction. Leave None to use the default value.

  • passphrase – the passphrase to the wallet. It takes precedence over self.passphrase and is discarded after use. If neither self.passphrase nor passphrase is set, a MissingPassphrase exception will be raised.

Return type

Transaction

transfer_multiple(destinations, metadata=None, allow_withdrawal=False, ttl=None, passphrase=None)

Sends multiple transfers from the wallet. Returns the resulting transaction.

Parameters
  • destinations – a list of Address and amount pairs [(address, amount), ...] or triples where the third element is a sequence of AssetID and quantity pairs

  • metadata – metadata to be sent, as Metadata instance od dict mapping int keys to values of acceptable types

  • allow_withdrawal – Allow withdrawing staking rewards to cover the transaction amount or fee.

  • ttl – Time To Live in seconds. After TTL has lapsed the nodes give up on broadcasting the transaction. Leave None to use the default value.

  • passphrase – the passphrase to the wallet. It takes precedence over self.passphrase and is discarded after use. If neither self.passphrase nor passphrase is set, a MissingPassphrase exception will be raised.

Return type

Transaction

unstake(passphrase=None)

Cancels active stake delegation.

Parameters

passphrase – the passphrase to the wallet. It takes precedence over self.passphrase and is discarded after use. If neither self.passphrase nor passphrase is set, a MissingPassphrase exception will be raised.

Return type

Transaction

utxo_stats()

Returns UTXO statistics as a tuple of (total_balance, histogram, scale).

class cardano.wallet.WalletService(backend=None)

Represents the service responsible for listing and retrieving the existing wallets or creating new ones.

Parameters

backend – the backend used to handle the underlying service layer

create_wallet(name, mnemonic, passphrase, mnemonic_2f=None)

Creates/restores a wallet internally in the backend. Returns only ID as the backend may need some time to sync before being able to return full wallet data.

Parameters
  • name – Name of the wallet

  • mnemonic – The mnemonic seed

  • passphrase – The wallet passphrase for spending operations (plain text string)

  • mnemonic_2f – An optional passphrase used to encrypt the mnemonic sentence

Return type

str

wallet(wid, passphrase=None)

Returns the wallet of given ID, connected to the backend and equipped with the passphrase if given.

Parameters
  • wid – The wallet ID (hex string)

  • passphrase – The wallet passphrase for spending operations (plain text string)

Return type

Wallet

wallets()

Returns the list of all Wallets handled by the backend.