Asynchronous

Now we have supported the use of asynchronous methods to submit transactions, py-stellar-base gives you the choice, rather than forcing you into always writing async; sync code is easier to write, generally safer, and has many more libraries to choose from.

The following is an example of send a payment by an asynchronous method, the same example of using the synchronization method can be found here:

 1"""
 2The effect of this example is the same as `payment.py`, but this example is asynchronous.
 3
 4Create, sign, and submit a transaction using Python Stellar SDK.
 5
 6Assumes that you have the following items:
 71. Secret key of a funded account to be the source account
 82. Public key of an existing account as a recipient
 9    These two keys can be created and funded by the friendbot at
10    https://www.stellar.org/laboratory/ under the heading "Quick Start: Test Account"
113. Access to Python Stellar SDK (https://github.com/StellarCN/py-stellar-base) through Python shell.
12
13See: https://developers.stellar.org/docs/start/list-of-operations/#payment
14"""
15import asyncio
16
17from stellar_sdk import (
18    AiohttpClient,
19    Asset,
20    Keypair,
21    Network,
22    ServerAsync,
23    TransactionBuilder,
24)
25
26
27def create_account():
28    """To make this script work, create an account on the testnet."""
29    import requests
30
31    from stellar_sdk import Keypair
32
33    keypair = Keypair.random()
34    url = "https://friendbot.stellar.org"
35    _response = requests.get(url, params={"addr": keypair.public_key})
36    # Check _response.json() in case something goes wrong
37    return keypair
38
39
40# The source account is the account we will be signing and sending from.
41example_keypair = create_account()
42source_secret_key = example_keypair.secret
43
44# Derive Keypair object and public key (that starts with a G) from the secret
45source_keypair = Keypair.from_secret(source_secret_key)
46source_public_key = source_keypair.public_key
47
48# We just send lumen to ourselves in this simple example
49receiver_public_key = example_keypair.public_key
50
51
52async def main():
53    # Configure StellarSdk to talk to the horizon instance hosted by Stellar.org
54    # To use the live network, set the hostname to 'horizon.stellar.org'
55    # When we use the `with` syntax, it automatically releases the resources it occupies.
56    async with ServerAsync(
57        horizon_url="https://horizon-testnet.stellar.org", client=AiohttpClient()
58    ) as server:
59        # Transactions require a valid sequence number that is specific to this account.
60        # We can fetch the current sequence number for the source account from Horizon.
61        source_account = await server.load_account(source_public_key)
62
63        base_fee = 100
64        # we are going to submit the transaction to the test network,
65        # so network_passphrase is `Network.TESTNET_NETWORK_PASSPHRASE`,
66        # if you want to submit to the public network, please use `Network.PUBLIC_NETWORK_PASSPHRASE`.
67        transaction = (
68            TransactionBuilder(
69                source_account=source_account,
70                network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
71                base_fee=base_fee,
72            )
73            .add_text_memo("Hello, Stellar!")  # Add a memo
74            # Add a payment operation to the transaction
75            # Send 350.1234567 XLM to receiver
76            # Specify 350.1234567 lumens. Lumens are divisible to seven digits past the decimal.
77            .append_payment_op(receiver_public_key, Asset.native(), "350.1234567")
78            .set_timeout(30)  # Make this transaction valid for the next 30 seconds only
79            .build()
80        )
81
82        # Sign this transaction with the secret key
83        # NOTE: signing is transaction is network specific. Test network transactions
84        # won't work in the public network. To switch networks, use the Network object
85        # as explained above (look for stellar_sdk.network.Network).
86        transaction.sign(source_keypair)
87
88        # Let's see the XDR (encoded in base64) of the transaction we just built
89        print(transaction.to_xdr())
90
91        # Submit the transaction to the Horizon server.
92        # The Horizon server will then submit the transaction into the network for us.
93        response = await server.submit_transaction(transaction)
94        print(response)
95
96
97if __name__ == "__main__":
98    asyncio.run(main())

The following example helps you listen to multiple endpoints asynchronously.

 1"""
 2See: https://stellar-sdk.readthedocs.io/en/latest/asynchronous.html
 3"""
 4import asyncio
 5
 6from stellar_sdk import AiohttpClient, ServerAsync
 7
 8HORIZON_URL = "https://horizon.stellar.org"
 9
10
11async def payments():
12    async with ServerAsync(HORIZON_URL, AiohttpClient()) as server:
13        async for payment in server.payments().cursor(cursor="now").stream():
14            print(f"Payment: {payment}")
15
16
17async def effects():
18    async with ServerAsync(HORIZON_URL, AiohttpClient()) as server:
19        async for effect in server.effects().cursor(cursor="now").stream():
20            print(f"Effect: {effect}")
21
22
23async def operations():
24    async with ServerAsync(HORIZON_URL, AiohttpClient()) as server:
25        async for operation in server.operations().cursor(cursor="now").stream():
26            print(f"Operation: {operation}")
27
28
29async def transactions():
30    async with ServerAsync(HORIZON_URL, AiohttpClient()) as server:
31        async for transaction in server.transactions().cursor(cursor="now").stream():
32            print(f"Transaction: {transaction}")
33
34
35async def listen():
36    await asyncio.gather(payments(), effects(), operations(), transactions())
37
38
39if __name__ == "__main__":
40    asyncio.run(listen())