Stellar Python SDK¶
Note
This branch is about v2, click here for the v1 branch. Thank you for your patience as we transition!
py-stellar-sdk is a Python library for communicating with a Stellar Horizon server. It is used for building Stellar apps on Python. It supports Python 3.6+ as well as PyPy 3.6+.
It provides:
- a networking layer API for Horizon endpoints.
- facilities for building and signing transactions, for communicating with a Stellar Horizon instance, and for submitting transactions or querying network history.
Quickstart¶
At the absolute basics, you’ll want to read up on Stellar’s Documentation Guides, as it contains a lot of information on the concepts used below (Transactions, Payments, Operations, KeyPairs, etc.).
Installation¶
Via pipenv or pip¶
To install py-stellar-sdk, use pipenv to install the module:
pipenv install stellar-sdk==2.6.0
If you’re not using pipenv, you should. Otherwise, you can install it via plain old pip. More on installing Python and dependencies can be found over in the Hitchhiker’s Guide to Python.
Via Source Code¶
Please use the code on pypi whenever possible. The latest code may be unstable.
You can clone the repository directly, and install it locally:
git clone https://github.com/StellarCN/py-stellar-base.git
cd py-stellar-base
git checkout 2.6.0
pip install .
Generate Keypair¶
Keypair
object represents key pair used to
sign transactions in Stellar network. Keypair
object can contain both a public and private key, or only a public key.
If Keypair
object does not contain private
key it can’t be used to sign transactions. The most convenient method of
creating new keypair is by passing the account’s secret seed:
1 2 3 4 5 | from stellar_sdk import Keypair
keypair = Keypair.from_secret("SBK2VIYYSVG76E7VC3QHYARNFLY2EAQXDHRC7BMXBBGIFG74ARPRMNQM")
public_key = keypair.public_key # GDHMW6QZOL73SHKG2JA3YHXFDHM46SS5ZRWEYF5BCYHX2C5TVO6KZBYL
can_sign = keypair.can_sign() # True
|
You can create a keypair from public key, but its function is limited:
1 2 3 4 | from stellar_sdk import Keypair
keypair = Keypair.from_public_key("GDHMW6QZOL73SHKG2JA3YHXFDHM46SS5ZRWEYF5BCYHX2C5TVO6KZBYL")
can_sign = keypair.can_sign() # False
|
You can also create a randomly generated keypair:
1 2 3 4 5 | from stellar_sdk import Keypair
keypair = Keypair.random()
print("Public Key: " + keypair.public_key)
print("Secret Seed: " + keypair.secret)
|
Create Account¶
Now, in order to create an account, you need to run a CreateAccount
operation with your new account ID.
Due to Stellar’s minimum account balance,
you’ll need to transfer the minimum account balance from another account with
the create account operation. As of this writing, minimum balance is 1 XLM (2
x 0.5 Base Reserve), and is subject to change.
Using The SDF Testnet¶
If you want to play in the Stellar test network, you can ask our Friendbot to create an account for you as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 | import requests
from stellar_sdk import Keypair
keypair = Keypair.random()
print("Public Key: " + keypair.public_key)
print("Secret Seed: " + keypair.secret)
url = 'https://friendbot.stellar.org'
response = requests.get(url, params={'addr': keypair.public_key})
print(response)
|
Using The Stellar Live Network¶
On the other hand, if you would like to create an account on the live network, you should buy some Stellar Lumens from an exchange. When you withdraw the Lumens into your new account, the exchange will automatically create the account for you. However, if you want to create an account from another account of your own, here’s an example of how to do so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | from stellar_sdk import TransactionBuilder, Server, Network, Keypair
server = Server(horizon_url="https://horizon-testnet.stellar.org")
source = Keypair.from_secret("SBFZCHU5645DOKRWYBXVOXY2ELGJKFRX6VGGPRYUWHQ7PMXXJNDZFMKD")
destination = Keypair.random()
source_account = server.load_account(account_id=source.public_key)
transaction = TransactionBuilder(
source_account=source_account,
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=100) \
.append_create_account_op(destination=destination.public_key, starting_balance="12.25") \
.build()
transaction.sign(source)
response = server.submit_transaction(transaction)
print("Transaction hash: {}".format(response["hash"]))
print("New Keypair: \n\taccount id: {account_id}\n\tsecret seed: {secret_seed}".format(
account_id=destination.public_key, secret_seed=destination.secret))
|
Querying Horizon¶
py-stellar-sdk gives you access to all the endpoints exposed by Horizon.
Building requests¶
py-stellar-sdk uses the Builder pattern to create the requests to send
to Horizon. Starting with a Server
object, you can chain methods together to generate a query.
(See the Horizon reference documentation for what methods are possible.)
1 2 3 4 5 6 7 8 9 10 11 12 13 | from stellar_sdk import Server
server = Server(horizon_url="https://horizon-testnet.stellar.org")
# get a list of transactions that occurred in ledger 1400
transactions = server.transactions().for_ledger(1400).call()
print(transactions)
# get a list of transactions submitted by a particular account
transactions = server.transactions() \
.for_account(account_id="GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW") \
.call()
print(transactions)
|
Once the request is built, it can be invoked with call()
or
with stream()
.
call()
will return the
response given by Horizon.
Streaming requests¶
Many requests can be invoked with stream()
.
Instead of returning a result like call()
does,
stream()
will return an EventSource.
Horizon will start sending responses from either the beginning of time or from the point
specified with cursor()
.
(See the Horizon reference documentation to learn which endpoints support streaming.)
For example, to log instances of transactions from a particular account:
1 2 3 4 5 6 7 8 9 10 11 12 13 | from stellar_sdk import Server
server = Server(horizon_url="https://horizon-testnet.stellar.org")
account_id = "GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW"
last_cursor = 'now' # or load where you left off
def tx_handler(tx_response):
print(tx_response)
for tx in server.transactions().for_account(account_id).cursor(last_cursor).stream():
tx_handler(tx)
|
Assets¶
Object of the Asset
class represents an asset in the Stellar network. Right now there are 3 possible types of assets in the Stellar network:
- native XLM asset (ASSET_TYPE_NATIVE),
- issued assets with asset code of maximum 4 characters (ASSET_TYPE_CREDIT_ALPHANUM4),
- issued assets with asset code of maximum 12 characters (ASSET_TYPE_CREDIT_ALPHANUM12).
To create a new native asset representation use static native()
method:
1 2 | from stellar_sdk import Asset
native = Asset.native()
|
To represent an issued asset you need to create a new object of type Asset
with an asset code and issuer:
1 2 3 4 5 6 7 | from stellar_sdk import Asset
# Creates TEST asset issued by GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB
test_asset = Asset("TEST", "GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB")
is_native = test_asset.is_native() # False
# Creates Google stock asset issued by GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB
google_stock_asset = Asset('US38259P7069', 'GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB')
google_stock_asset_type = google_stock_asset.type # credit_alphanum12
|
Building Transactions¶
Transactions are the commands that modify the state of the ledger. They include sending payments, creating offers, making account configuration changes, etc.
Every transaction has a source account. This is the account that pays the fee and uses up a sequence number for the transaction.
Transactions are made up of one or more operations. Each operation also has a source account, which defaults to the transaction’s source account.
TransactionBuilder¶
The TransactionBuilder
class is used to construct new transactions.
TransactionBuilder is given an account that is used as transaction’s source account.
The transaction will use the current sequence number of the given Account
object as its sequence number and increments the given account’s sequence number
when build()
is called on the TransactionBuilder.
Operations can be added to the transaction calling
append_operation
for
each operation you wish to add to the transaction.
See Operation for a list of possible operations you can add.
append_operation
returns the current TransactionBuilder
object so you can chain multiple calls. But you don’t need to call it directly,
we have prepared a lot of easy-to-use functions for you, such as
append_payment_op
can add a payment operation to the TransactionBuilder
.
After adding the desired operations, call the build()
method on the TransactionBuilder
.
This will return a fully constructed TransactionEnvelope
.
The transaction object is wrapped in an object called a TransactionEnvelope
,
the returned transaction will contain
the sequence number of the source account. This transaction is unsigned.
You must sign it before it will be accepted by the Stellar network.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from stellar_sdk import TransactionBuilder, Network, Keypair, Account
root_keypair = Keypair.from_secret("SA6XHAH4GNLRWWWF6TEVEWNS44CBNFAJWHWOPZCVZOUXSQA7BOYN7XHC")
# Create an Account object from an address and sequence number.
root_account = Account(account_id=root_keypair.public_key, sequence=1)
transaction = TransactionBuilder(
source_account=root_account,
# If you want to submit to pubnet, you need to change `network_passphrase` to `Network.PUBLIC_NETWORK_PASSPHRASE`
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=100) \
.append_payment_op( # add a payment operation to the transaction
destination="GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW",
asset_code="XLM",
amount="125.5") \
.append_set_options_op( # add a set options operation to the transaction
home_domain="overcat.me") \
.set_timeout(30) \
.build() # mark this transaction as valid only for the next 30 seconds
|
Sequence Numbers¶
The sequence number of a transaction has to match the sequence number stored by the source account or else the transaction is invalid. After the transaction is submitted and applied to the ledger, the source account’s sequence number increases by 1.
There are two ways to ensure correct sequence numbers:
- Read the source account’s sequence number before submitting a transaction
- Manage the sequence number locally
During periods of high transaction throughput, fetching a source account’s sequence number from the network may not return the correct value. So, if you’re submitting many transactions quickly, you will want to keep track of the sequence number locally.
Adding Memos¶
Transactions can contain a memo field you can use to attach additional information to the transaction. You can do this
by passing a Memo
object when you construct the TransactionBuilder.
There are 5 types of memos:
stellar_sdk.memo.NoneMemo
- empty memo,stellar_sdk.memo.TextMemo`
- 28-byte ascii encoded string memo,stellar_sdk.memo.IdMemo
- 64-bit number memo,stellar_sdk.memo.HashMemo
- 32-byte hash - ex. hash of an item in a content server,stellar_sdk.memo.ReturnHashMemo
- 32-byte hash used for returning payments - contains hash of the transaction being rejected.
1 2 3 4 5 6 7 8 9 10 | from stellar_sdk import TransactionBuilder, Network, Keypair, Account
root_keypair = Keypair.from_secret("SA6XHAH4GNLRWWWF6TEVEWNS44CBNFAJWHWOPZCVZOUXSQA7BOYN7XHC")
# Create an Account object from an address and sequence number.
root_account = Account(account_id=root_keypair.public_key, sequence=1)
transaction = TransactionBuilder(source_account=root_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=100).add_text_memo("Happy birthday!").append_payment_op(
destination="GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW", amount="2000",
asset_code="XLM").set_timeout(30).build()
|
Transaction and TransactionEnvelope¶
These two concepts may make the novices unclear, but the official has given a good explanation.
Transactions are commands that modify the ledger state. Among other things, Transactions are used to send payments, enter orders into the distributed exchange, change settings on accounts, and authorize another account to hold your currency. If you think of the ledger as a database, then transactions are SQL commands.
Once a transaction is ready to be signed, the transaction object is wrapped in an object called a Transaction Envelope, which contains the transaction as well as a set of signatures. Most transaction envelopes only contain a single signature along with the transaction, but in multi-signature setups it can contain many signatures. Ultimately, transaction envelopes are passed around the network and are included in transaction sets, as opposed to raw Transaction objects.
Creating a payment transaction¶
Payment¶
In this example, the destination account must exist. We use synchronous methods to submit transactions here, if you want, you can also use asynchronous methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | """
Create, sign, and submit a transaction using Python Stellar SDK.
Assumes that you have the following items:
1. Secret key of a funded account to be the source account
2. Public key of an existing account as a recipient
These two keys can be created and funded by the friendbot at
https://www.stellar.org/laboratory/ under the heading "Quick Start: Test Account"
3. Access to Python Stellar SDK (https://github.com/StellarCN/py-stellar-base) through Python shell.
"""
from stellar_sdk import Server, Keypair, TransactionBuilder, Network
# The source account is the account we will be signing and sending from.
source_secret_key = "SBFZCHU5645DOKRWYBXVOXY2ELGJKFRX6VGGPRYUWHQ7PMXXJNDZFMKD"
# Derive Keypair object and public key (that starts with a G) from the secret
source_keypair = Keypair.from_secret(source_secret_key)
source_public_key = source_keypair.public_key
receiver_public_key = "GA7YNBW5CBTJZ3ZZOWX3ZNBKD6OE7A7IHUQVWMY62W2ZBG2SGZVOOPVH"
# Configure StellarSdk to talk to the horizon instance hosted by Stellar.org
# To use the live network, set the hostname to 'horizon.stellar.org'
server = Server(horizon_url="https://horizon-testnet.stellar.org")
# Transactions require a valid sequence number that is specific to this account.
# We can fetch the current sequence number for the source account from Horizon.
source_account = server.load_account(source_public_key)
base_fee = server.fetch_base_fee()
# we are going to submit the transaction to the test network,
# so network_passphrase is `Network.TESTNET_NETWORK_PASSPHRASE`,
# if you want to submit to the public network, please use `Network.PUBLIC_NETWORK_PASSPHRASE`.
transaction = (
TransactionBuilder(
source_account=source_account,
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=base_fee,
)
.add_text_memo("Hello, Stellar!") # Add a memo
# Add a payment operation to the transaction
# Send 350.1234567 XLM to receiver
# Specify 350.1234567 lumens. Lumens are divisible to seven digits past the decimal.
.append_payment_op(receiver_public_key, "350.1234567", "XLM")
.set_timeout(30) # Make this transaction valid for the next 30 seconds only
.build()
)
# Sign this transaction with the secret key
# NOTE: signing is transaction is network specific. Test network transactions
# won't work in the public network. To switch networks, use the Network object
# as explained above (look for stellar_sdk.network.Network).
transaction.sign(source_keypair)
# Let's see the XDR (encoded in base64) of the transaction we just built
print(transaction.to_xdr())
# Submit the transaction to the Horizon server.
# The Horizon server will then submit the transaction into the network for us.
response = server.submit_transaction(transaction)
print(response)
|
Path Payment¶
In the example below we’re sending 1000 XLM (at max) from GABJLI6IVBKJ7HIC5NN7HHDCIEW3CMWQ2DWYHREQQUFWSWZ2CDAMZZX4 to GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB. Destination Asset will be GBP issued by GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW. Assets will be exchanged using the following path:
- USD issued by GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB
- EUR issued by GDTNXRLOJD2YEBPKK7KCMR7J33AAG5VZXHAJTHIG736D6LVEFLLLKPDL
The path payment will cause the destination address to get 5.5 GBP. It will cost the sender no more than 1000 XLM. In this example there will be 3 exchanges, XLM->USD, USD->EUR, EUR->GBP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | from stellar_sdk import Keypair, Server, TransactionBuilder, Network, Asset
server = Server(horizon_url="https://horizon-testnet.stellar.org")
source_keypair = Keypair.from_secret("SA6XHAH4GNLRWWWF6TEVEWNS44CBNFAJWHWOPZCVZOUXSQA7BOYN7XHC")
source_account = server.load_account(account_id=source_keypair.public_key)
path = [
Asset("USD", "GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB"),
Asset("EUR", "GDTNXRLOJD2YEBPKK7KCMR7J33AAG5VZXHAJTHIG736D6LVEFLLLKPDL")
]
transaction = TransactionBuilder(
source_account=source_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=100) \
.append_path_payment_op(destination="GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB",
send_code="XLM", send_issuer=None, send_max="1000", dest_code="GBP",
dest_issuer="GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW",
dest_amount="5.50", path=path) \
.set_timeout(30) \
.build()
transaction.sign(source_keypair)
response = server.submit_transaction(transaction)
|
Asynchronous¶
Now we have supported the use of asynchronous methods to submit transactions, py-stellar-sdk 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.
Server
has one parameter is client, here we need to talk about
the client parameter, if you do not specify the client, we will use
the RequestsClient
instance by default,
it is a synchronous HTTPClient, you can also specify an asynchronous HTTP Client,
for example: AiohttpClient
. If you use a synchronous client,
then all requests are synchronous, if you use an asynchronous client,
then all requests are asynchronous.
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | """
The effect of this example is the same as `payment.py`, but this example is asynchronous.
Create, sign, and submit a transaction using Python Stellar SDK.
Assumes that you have the following items:
1. Secret key of a funded account to be the source account
2. Public key of an existing account as a recipient
These two keys can be created and funded by the friendbot at
https://www.stellar.org/laboratory/ under the heading "Quick Start: Test Account"
3. Access to Python Stellar SDK (https://github.com/StellarCN/py-stellar-base) through Python shell.
"""
import asyncio
from stellar_sdk import Server, Keypair, TransactionBuilder, Network, AiohttpClient
# The source account is the account we will be signing and sending from.
source_secret_key = "SBFZCHU5645DOKRWYBXVOXY2ELGJKFRX6VGGPRYUWHQ7PMXXJNDZFMKD"
# Derive Keypair object and public key (that starts with a G) from the secret
source_keypair = Keypair.from_secret(source_secret_key)
source_public_key = source_keypair.public_key
receiver_public_key = "GA7YNBW5CBTJZ3ZZOWX3ZNBKD6OE7A7IHUQVWMY62W2ZBG2SGZVOOPVH"
async def main():
# Configure StellarSdk to talk to the horizon instance hosted by Stellar.org
# To use the live network, set the hostname to 'horizon.stellar.org'
# When we use the `with` syntax, it automatically releases the resources it occupies.
async with Server(
horizon_url="https://horizon-testnet.stellar.org", client=AiohttpClient()
) as server:
# Transactions require a valid sequence number that is specific to this account.
# We can fetch the current sequence number for the source account from Horizon.
source_account = await server.load_account(source_public_key)
base_fee = await server.fetch_base_fee()
# we are going to submit the transaction to the test network,
# so network_passphrase is `Network.TESTNET_NETWORK_PASSPHRASE`,
# if you want to submit to the public network, please use `Network.PUBLIC_NETWORK_PASSPHRASE`.
transaction = (
TransactionBuilder(
source_account=source_account,
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=base_fee,
)
.add_text_memo("Hello, Stellar!") # Add a memo
# Add a payment operation to the transaction
# Send 350.1234567 XLM to receiver
# Specify 350.1234567 lumens. Lumens are divisible to seven digits past the decimal.
.append_payment_op(receiver_public_key, "350.1234567", "XLM")
.set_timeout(30) # Make this transaction valid for the next 30 seconds only
.build()
)
# Sign this transaction with the secret key
# NOTE: signing is transaction is network specific. Test network transactions
# won't work in the public network. To switch networks, use the Network object
# as explained above (look for stellar_sdk.network.Network).
transaction.sign(source_keypair)
# Let's see the XDR (encoded in base64) of the transaction we just built
print(transaction.to_xdr())
# Submit the transaction to the Horizon server.
# The Horizon server will then submit the transaction into the network for us.
response = await server.submit_transaction(transaction)
print(response)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
# asyncio.run(main()) # Python 3.7+
|
The following example helps you listen to multiple endpoints asynchronously.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import asyncio
from stellar_sdk import AiohttpClient, Server
HORIZON_URL = "https://horizon.stellar.org"
async def payments():
async with Server(HORIZON_URL, AiohttpClient()) as server:
async for payment in server.payments().cursor(cursor="now").stream():
print(f"Payment: {payment}")
async def effects():
async with Server(HORIZON_URL, AiohttpClient()) as server:
async for effect in server.effects().cursor(cursor="now").stream():
print(f"Effect: {effect}")
async def operations():
async with Server(HORIZON_URL, AiohttpClient()) as server:
async for operation in server.operations().cursor(cursor="now").stream():
print(f"Operation: {operation}")
async def transactions():
async with Server(HORIZON_URL, AiohttpClient()) as server:
async for transaction in server.transactions().cursor(cursor="now").stream():
print(f"Transaction: {transaction}")
async def listen():
await asyncio.gather(
payments(),
effects(),
operations(),
transactions()
)
if __name__ == '__main__':
asyncio.run(listen())
|
Multi-signature account¶
Multi-signature accounts can be used to require that transactions require multiple public keys to sign before they are considered valid. This is done by first configuring your account’s threshold levels. Each operation has a threshold level of either low, medium, or high. You give each threshold level a number between 1-255 in your account. Then, for each key in your account, you assign it a weight (1-255, setting a 0 weight deletes the key). Any transaction must be signed with enough keys to meet the threshold.
For example, let’s say you set your threshold levels; low = 1, medium = 2, high = 3. You want to send a payment operation, which is a medium threshold operation. Your master key has weight 1. Additionally, you have a secondary key associated with your account which has a weight of 1. Now, the transaction you submit for this payment must include both signatures of your master key and secondary key since their combined weight is 2 which is enough to authorize the payment operation.
In this example, we will:
- Add a second signer to the account
- Set our account’s masterkey weight and threshold levels
- Create a multi signature transaction that sends a payment
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | from stellar_sdk import Server, TransactionBuilder, Signer, Network, Keypair
server = Server(horizon_url="https://horizon-testnet.stellar.org")
root_keypair = Keypair.from_secret("SA6XHAH4GNLRWWWF6TEVEWNS44CBNFAJWHWOPZCVZOUXSQA7BOYN7XHC")
root_account = server.load_account(account_id=root_keypair.public_key)
secondary_keypair = Keypair.from_secret("SAMZUAAPLRUH62HH3XE7NVD6ZSMTWPWGM6DS4X47HLVRHEBKP4U2H5E7")
secondary_signer = Signer.ed25519_public_key(account_id=secondary_keypair.public_key, weight=1)
transaction = TransactionBuilder(
source_account=root_account,
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=100) \
.append_set_options_op(
master_weight=1, # set master key weight
low_threshold=1,
med_threshold=2, # a payment is medium threshold
high_threshold=2, # make sure to have enough weight to add up to the high threshold!
signer=secondary_signer) \
.set_timeout(30) \
.build()
# only need to sign with the root signer as the 2nd signer won't
# be added to the account till after this transaction completes
transaction.sign(root_keypair)
response = server.submit_transaction(transaction)
print(response)
# now create a payment with the account that has two signers
destination = "GBA5SMM5OYAOOPL6R773MV7O3CCLUDVLCWHIVVL3W4XTD3DA5FJ4JSEZ"
transaction = TransactionBuilder(
source_account=root_account,
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=100) \
.append_payment_op(
destination=destination,
amount="2000",
asset_code="XLM") \
.set_timeout(30) \
.build()
# now we need to sign the transaction with both the root and the secondary_keypair
transaction.sign(root_keypair)
transaction.sign(secondary_keypair)
response = server.submit_transaction(transaction)
print(response)
|
API Documentation¶
Here you’ll find detailed documentation on specific functions, classes, and methods.
API Documentation¶
Account¶
-
class
stellar_sdk.account.
Account
(account_id, sequence)[source]¶ The
Account
object, which represents represents a single account in Stellar network and its sequence number.Account tracks the sequence number as it is used by
TransactionBuilder
See Accounts For more information about the formats used for asset codes and how issuers work on Stellar’s network,
Parameters: Raises: Ed25519PublicKeyInvalidError
: ifaccount_id
is not a valid ed25519 public key.
Asset¶
-
class
stellar_sdk.asset.
Asset
(code, issuer=None)[source]¶ The
Asset
object, which represents an asset and its corresponding issuer on the Stellar network.For more information about the formats used for asset codes and how issuers work on Stellar’s network, see Stellar’s guide on assets.
Parameters: - code (
str
) – The asset code, in the formats specified in Stellar’s guide on assets. - issuer (
Optional
[str
]) – The account ID of the issuer. Note if the currency is the native currency (XLM (Lumens)), no issuer is necessary.
Raises: AssetCodeInvalidError
: ifcode
is invalid.AssetIssuerInvalidError
: ifissuer
is not a valid ed25519 public key.-
classmethod
from_xdr_object
(asset_xdr_object)[source]¶ Create a
Asset
from an XDR Asset object.Parameters: asset_xdr_object ( Asset
) – The XDR Asset object.Return type: Asset
Returns: A new Asset
object from the given XDR Asset object.
-
guess_asset_type
()[source]¶ Return the type of the asset, Can be one of following types: native, credit_alphanum4 or credit_alphanum12
Return type: str
Returns: The type of the asset.
-
is_native
()[source]¶ Return true if the
Asset
is the native asset.Return type: bool
Returns: True if the Asset is native, False otherwise.
-
static
native
()[source]¶ Returns an asset object for the native asset.
Return type: Asset
Returns: An asset object for the native asset.
-
to_dict
()[source]¶ Generate a dict for this object’s attributes.
Return type: dict
Returns: A dict representing an Asset
- code (
Call Builder¶
BaseCallBuilder¶
-
class
stellar_sdk.call_builder.
BaseCallBuilder
(horizon_url, client)[source]¶ Creates a new
BaseCallBuilder
pointed to server defined by horizon_url.This is an abstract class. Do not create this object directly, use
stellar_sdk.server.Server
class.Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request.
-
call
()[source]¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)[source]¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
limit
(limit)[source]¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)[source]¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()[source]¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
- horizon_url (
AccountsCallBuilder¶
-
class
stellar_sdk.call_builder.
AccountsCallBuilder
(horizon_url, client)[source]¶ Creates a new
AccountsCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.accounts()
.Parameters: - horizon_url – Horizon server URL.
- client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request.
-
account_id
(account_id)[source]¶ Returns information and links relating to a single account. The balances section in the returned JSON will also list all the trust lines this account has set up.
See Account Details
Parameters: account_id ( str
) – account id, for example: GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDDReturn type: AccountsCallBuilder
Returns: current AccountCallBuilder instance
-
asset
(asset)[source]¶ Filtering accounts who have a trustline to an asset. The result is a list of accounts.
See Account Details
Parameters: asset ( Asset
) – an issued assetReturn type: AccountsCallBuilder
Returns: current AccountCallBuilder instance
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
for_asset
(asset)[source]¶ Filtering accounts who have a trustline to an asset. The result is a list of accounts.
See Account Details
Parameters: asset ( Asset
) – an issued assetReturn type: AccountsCallBuilder
Returns: current AccountCallBuilder instance
-
for_signer
(signer)[source]¶ Filtering accounts who have a given signer. The result is a list of accounts.
See Account Details
Parameters: signer ( str
) – signer’s account id, for example: GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDDReturn type: AccountsCallBuilder
Returns: current AccountCallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
signer
(signer)[source]¶ Filtering accounts who have a given signer. The result is a list of accounts.
See Account Details
Parameters: signer ( str
) – signer’s account id, for example: GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDDReturn type: AccountsCallBuilder
Returns: current AccountCallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
AssetsCallBuilder¶
-
class
stellar_sdk.call_builder.
AssetsCallBuilder
(horizon_url, client)[source]¶ Creates a new
AssetsCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.assets()
.See All Assets
Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request.
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
for_code
(asset_code)[source]¶ This endpoint filters all assets by the asset code.
Parameters: asset_code ( str
) – asset code, for example: USDReturn type: AssetsCallBuilder
Returns: current AssetCallBuilder instance
-
for_issuer
(asset_issuer)[source]¶ This endpoint filters all assets by the asset issuer.
Parameters: asset_issuer ( str
) – asset issuer, for example: GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDDReturn type: AssetsCallBuilder
Returns: current AssetCallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
- horizon_url (
DataCallBuilder¶
-
class
stellar_sdk.call_builder.
DataCallBuilder
(horizon_url, client, account_id, data_name)[source]¶ Creates a new
DataCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.data()
.See Data for Account
Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request. - account_id (
str
) – account id, for example: GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD - data_name (
str
) – Key name
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
- horizon_url (
EffectsCallBuilder¶
-
class
stellar_sdk.call_builder.
EffectsCallBuilder
(horizon_url, client)[source]¶ Creates a new
EffectsCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.effects()
.See All Effects
Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request.
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
for_account
(account_id)[source]¶ This endpoint represents all effects that changed a given account. It will return relevant effects from the creation of the account to the current ledger.
Parameters: account_id ( str
) – account id, for example: GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDDReturn type: EffectsCallBuilder
Returns: this EffectCallBuilder instance
-
for_ledger
(sequence)[source]¶ Effects are the specific ways that the ledger was changed by any operation. This endpoint represents all effects that occurred in the given ledger.
Parameters: sequence ( Union
[int
,str
]) – ledger sequenceReturn type: EffectsCallBuilder
Returns: this EffectCallBuilder instance
-
for_operation
(operation_id)[source]¶ This endpoint represents all effects that occurred as a result of a given operation.
Parameters: operation_id ( Union
[int
,str
]) – operation IDReturn type: EffectsCallBuilder
Returns: this EffectCallBuilder instance
-
for_transaction
(transaction_hash)[source]¶ This endpoint represents all effects that occurred as a result of a given transaction.
Parameters: transaction_hash ( str
) – transaction hashReturn type: EffectsCallBuilder
Returns: this EffectCallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
- horizon_url (
FeeStatsCallBuilder¶
-
class
stellar_sdk.call_builder.
FeeStatsCallBuilder
(horizon_url, client)[source]¶ Creates a new
FeeStatsCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.fee_stats()
.See Fee Stats
Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request.
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
- horizon_url (
LedgersCallBuilder¶
-
class
stellar_sdk.call_builder.
LedgersCallBuilder
(horizon_url, client)[source]¶ Creates a new
LedgersCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.ledgers()
.See All Ledgers
Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request.
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
ledger
(sequence)[source]¶ Provides information on a single ledger.
See Ledger Details
Parameters: sequence ( Union
[int
,str
]) – Ledger sequenceReturn type: LedgersCallBuilder
Returns: current LedgerCallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
- horizon_url (
OffersCallBuilder¶
-
class
stellar_sdk.call_builder.
OffersCallBuilder
(horizon_url, client)[source]¶ Creates a new
OffersCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.offers()
.See Offer Details See Offers
Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request.
-
account
(account_id)[source]¶ Returns all offers where the given account is the seller.
Parameters: account_id – Account ID Returns: this OffersCallBuilder instance
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
for_buying
(buying)[source]¶ Returns all offers buying an asset.
People on the Stellar network can make offers to buy or sell assets. This endpoint represents all the current offers, allowing filtering by seller, selling_asset or buying_asset.
See Offers
Parameters: buying ( Asset
) – The asset being bought.Returns: this OffersCallBuilder instance
-
for_seller
(seller)[source]¶ Returns all offers where the given account is the seller.
People on the Stellar network can make offers to buy or sell assets. This endpoint represents all the current offers, allowing filtering by seller, selling_asset or buying_asset.
See Offers
Parameters: seller ( str
) – Account ID of the offer creatorReturns: this OffersCallBuilder instance
-
for_selling
(selling)[source]¶ Returns all offers selling an asset.
People on the Stellar network can make offers to buy or sell assets. This endpoint represents all the current offers, allowing filtering by seller, selling_asset or buying_asset.
See Offers
Parameters: selling ( Asset
) – The asset being sold.Returns: this OffersCallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
offer
(offer_id)[source]¶ Returns information and links relating to a single offer.
See Offer Details
Parameters: offer_id ( Union
[str
,int
]) – Offer ID.Returns: this OffersCallBuilder instance
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
- horizon_url (
OperationsCallBuilder¶
-
class
stellar_sdk.call_builder.
OperationsCallBuilder
(horizon_url, client)[source]¶ Creates a new
OperationsCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.operations()
.See All Operations
Parameters: - horizon_url – Horizon server URL.
- client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request.
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
for_account
(account_id)[source]¶ This endpoint represents all operations that were included in valid transactions that affected a particular account.
Parameters: account_id ( str
) – Account IDReturn type: OperationsCallBuilder
Returns: this OperationCallBuilder instance
-
for_ledger
(sequence)[source]¶ This endpoint returns all operations that occurred in a given ledger.
Parameters: sequence ( Union
[int
,str
]) – Sequence IDReturn type: OperationsCallBuilder
Returns: this OperationCallBuilder instance
-
for_transaction
(transaction_hash)[source]¶ This endpoint represents all operations that are part of a given transaction.
See Operations for Transaction
Parameters: transaction_hash ( str
) –Return type: OperationsCallBuilder
Returns: this OperationCallBuilder instance
-
include_failed
(include_failed)[source]¶ Adds a parameter defining whether to include failed transactions. By default only operations of successful transactions are returned.
Parameters: include_failed ( bool
) – Set to True to include operations of failed transactions.Return type: OperationsCallBuilder
Returns: current OperationsCallBuilder instance
-
join
(join)[source]¶ join represents join param in queries, currently only supports transactions
Parameters: join ( str
) – join represents join param in queries, currently only supports transactionsReturn type: OperationsCallBuilder
Returns: current OperationsCallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
operation
(operation_id)[source]¶ The operation details endpoint provides information on a single operation. The operation ID provided in the id argument specifies which operation to load.
Parameters: operation_id ( Union
[int
,str
]) – Operation IDReturn type: OperationsCallBuilder
Returns: this OperationCallBuilder instance
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
OrderbookCallBuilder¶
-
class
stellar_sdk.call_builder.
OrderbookCallBuilder
(horizon_url, client, selling, buying)[source]¶ Creates a new
OrderbookCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.orderbook()
.Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request. - selling (
Asset
) – Asset being sold - buying (
Asset
) – Asset being bought
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
- horizon_url (
PathsCallBuilder¶
-
class
stellar_sdk.call_builder.
PathsCallBuilder
(horizon_url, client, source_account, destination_account, destination_asset, destination_amount)[source]¶ Creates a new
PathsCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.paths()
.The Stellar Network allows payments to be made across assets through path payments. A path payment specifies a series of assets to route a payment through, from source asset (the asset debited from the payer) to destination asset (the asset credited to the payee).
Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request. - source_account (
str
) – The sender’s account ID. Any returned path must use a source that the sender can hold. - destination_account (
str
) – The destination account ID that any returned path should use. - destination_asset (
Asset
) – The destination asset. - destination_amount (
str
) – The amount, denominated in the destination asset, that any returned path should be able to satisfy.
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
- horizon_url (
PaymentsCallBuilder¶
-
class
stellar_sdk.call_builder.
PaymentsCallBuilder
(horizon_url, client)[source]¶ Creates a new
PaymentsCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.payments()
.See All Payments
Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request.
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
for_account
(account_id)[source]¶ This endpoint responds with a collection of Payment operations where the given account was either the sender or receiver.
Parameters: account_id ( str
) – Account IDReturn type: PaymentsCallBuilder
Returns: current PaymentsCallBuilder instance
-
for_ledger
(sequence)[source]¶ This endpoint represents all payment operations that are part of a valid transactions in a given ledger.
Parameters: sequence ( Union
[int
,str
]) – Ledger sequenceReturn type: PaymentsCallBuilder
Returns: current PaymentsCallBuilder instance
-
for_transaction
(transaction_hash)[source]¶ This endpoint represents all payment operations that are part of a given transaction.
Parameters: transaction_hash ( str
) – Transaction hashReturn type: PaymentsCallBuilder
Returns: current PaymentsCallBuilder instance
-
include_failed
(include_failed)[source]¶ Adds a parameter defining whether to include failed transactions. By default only payments of successful transactions are returned.
Parameters: include_failed ( bool
) – Set toTrue
to include payments of failed transactions.Return type: PaymentsCallBuilder
Returns: current PaymentsCallBuilder instance
-
join
(join)[source]¶ join represents join param in queries, currently only supports transactions
Parameters: join ( str
) – join represents join param in queries, currently only supports transactionsReturn type: PaymentsCallBuilder
Returns: current OperationsCallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
- horizon_url (
RootCallBuilder¶
-
class
stellar_sdk.call_builder.
RootCallBuilder
(horizon_url, client)[source]¶ Creates a new
RootCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.root()
.Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request.
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
- horizon_url (
StrictReceivePathsCallBuilder¶
-
class
stellar_sdk.call_builder.
StrictReceivePathsCallBuilder
(horizon_url, client, source, destination_asset, destination_amount)[source]¶ Creates a new
StrictReceivePathsCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.strict_receive_paths()
.The Stellar Network allows payments to be made across assets through path payments. A path payment specifies a series of assets to route a payment through, from source asset (the asset debited from the payer) to destination asset (the asset credited to the payee).
A path search is specified using:
- The source address or source assets.
- The asset and amount that the destination account should receive.
As part of the search, horizon will load a list of assets available to the source address and will find any payment paths from those source assets to the desired destination asset. The search’s amount parameter will be used to determine if there a given path can satisfy a payment of the desired amount.
If a list of assets is passed as the source, horizon will find any payment paths from those source assets to the desired destination asset.
Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request. - source (
Union
[str
,List
[Asset
]]) – The sender’s account ID or a list of Assets. Any returned path must use a source that the sender can hold. - destination_asset (
Asset
) – The destination asset. - destination_amount (
str
) – The amount, denominated in the destination asset, that any returned path should be able to satisfy.
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
StrictSendPathsCallBuilder¶
-
class
stellar_sdk.call_builder.
StrictSendPathsCallBuilder
(horizon_url, client, source_asset, source_amount, destination)[source]¶ Creates a new
StrictSendPathsCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.strict_send_paths()
.The Stellar Network allows payments to be made across assets through path payments. A strict send path payment specifies a series of assets to route a payment through, from source asset (the asset debited from the payer) to destination asset (the asset credited to the payee).
A strict send path search is specified using:
- The source asset
- The source amount
- The destination assets or destination account.
As part of the search, horizon will load a list of assets available to the source address and will find any payment paths from those source assets to the desired destination asset. The search’s source_amount parameter will be used to determine if there a given path can satisfy a payment of the desired amount.
Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request. - source_asset (
Asset
) – The asset to be sent. - source_amount (
str
) – The amount, denominated in the source asset, that any returned path should be able to satisfy. - destination (
Union
[str
,List
[Asset
]]) – The destination account or the destination assets.
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
TradeAggregationsCallBuilder¶
-
class
stellar_sdk.call_builder.
TradeAggregationsCallBuilder
(horizon_url, client, base, counter, resolution, start_time=None, end_time=None, offset=None)[source]¶ Creates a new
TradeAggregationsCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.trade_aggregations()
.Trade Aggregations facilitate efficient gathering of historical trade data.
Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request. - base (
Asset
) – base asset - counter (
Asset
) – counter asset - resolution (
int
) – segment duration as millis since epoch. Supported values are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). - start_time (
Optional
[int
]) – lower time boundary represented as millis since epoch - end_time (
Optional
[int
]) – upper time boundary represented as millis since epoch - offset (
Optional
[int
]) – segments can be offset using this parameter. Expressed in milliseconds. Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours.
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
- horizon_url (
TradesCallBuilder¶
-
class
stellar_sdk.call_builder.
TradesCallBuilder
(horizon_url, client)[source]¶ Creates a new
TradesCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.trades()
.See Trades
Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request.
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
for_account
(account_id)[source]¶ Filter trades for a specific account
Parameters: account_id ( str
) – account idReturn type: TradesCallBuilder
Returns: current TradesCallBuilder instance
-
for_asset_pair
(base, counter)[source]¶ Filter trades for a specific asset pair (orderbook)
Parameters: Return type: TradesCallBuilder
Returns: current TradesCallBuilder instance
-
for_offer
(offer_id)[source]¶ Filter trades for a specific offer
See Trades for Offer
Parameters: offer_id ( Union
[int
,str
]) – offer idReturn type: TradesCallBuilder
Returns: current TradesCallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
- horizon_url (
TransactionsCallBuilder¶
-
class
stellar_sdk.call_builder.
TransactionsCallBuilder
(horizon_url, client)[source]¶ Creates a new
TransactionsCallBuilder
pointed to server defined by horizon_url. Do not create this object directly, usestellar_sdk.server.Server.transactions()
.See All Transactions
Parameters: - horizon_url (
str
) – Horizon server URL. - client (
Union
[BaseAsyncClient
,BaseSyncClient
]) – The client instance used to send request.
-
call
()¶ Triggers a HTTP request using this builder’s current configuration.
Return type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: If it is called synchronous, the response will be returned. If it is called asynchronously, it will return Coroutine. Raises: ConnectionError
: if you have not successfully connected to the server.NotFoundError
: if status_code == 404BadRequestError
: if 400 <= status_code < 500 and status_code != 404BadResponseError
: if 500 <= status_code < 600UnknownRequestError
: if an unknown error occurs, please submit an issue
-
cursor
(cursor)¶ Sets
cursor
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: cursor ( Union
) – A cursor is a value that points to a specific location in a collection of resources.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
for_account
(account_id)[source]¶ This endpoint represents all transactions that affected a given account.
Parameters: account_id ( str
) – account idReturn type: TransactionsCallBuilder
Returns: current TransactionsCallBuilder instance
-
for_ledger
(sequence)[source]¶ This endpoint represents all transactions in a given ledger.
Parameters: sequence ( Union
[str
,int
]) – ledger sequenceReturn type: TransactionsCallBuilder
Returns: current TransactionsCallBuilder instance
-
include_failed
(include_failed)[source]¶ Adds a parameter defining whether to include failed transactions. By default only transactions of successful transactions are returned.
Parameters: include_failed ( bool
) – Set to True to include failed transactions.Return type: TransactionsCallBuilder
Returns: current TransactionsCallBuilder instance
-
limit
(limit)¶ Sets
limit
parameter for the current call. Returns the CallBuilder object on which this method has been called.See Paging
Parameters: limit ( int
) – Number of records the server should return.Return type: BaseCallBuilder
Returns:
-
order
(desc=True)¶ Sets
order
parameter for the current call. Returns the CallBuilder object on which this method has been called.Parameters: desc ( bool
) – Sort direction,True
to get desc sort direction, the default setting isTrue
.Return type: BaseCallBuilder
Returns: current CallBuilder instance
-
stream
()¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Return type: Union
[AsyncGenerator
[Dict
[str
,Any
],None
],Generator
[Dict
[str
,Any
],None
,None
]]Returns: If it is called synchronous, it will return Generator
, If it is called asynchronously, it will returnAsyncGenerator
.Raise: StreamClientError
- Failed to fetch stream resource.
-
transaction
(transaction_hash)[source]¶ The transaction details endpoint provides information on a single transaction. The transaction hash provided in the hash argument specifies which transaction to load.
Parameters: transaction_hash ( str
) – transaction hashReturn type: TransactionsCallBuilder
Returns: current TransactionsCallBuilder instance
- horizon_url (
Client¶
BaseAsyncClient¶
-
class
stellar_sdk.client.base_async_client.
BaseAsyncClient
[source]¶ This is an abstract class, and if you want to implement your own asynchronous client, you must implement this class.
-
get
(url, params=None)[source]¶ Perform HTTP GET request.
Parameters: Return type: Returns: the response from server
Raise:
-
post
(url, data)[source]¶ Perform HTTP POST request.
Parameters: Return type: Returns: the response from server
Raise:
-
stream
(url, params=None)[source]¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Parameters: Return type: AsyncGenerator
[Dict
[str
,Any
],None
]Returns: a dict AsyncGenerator for server response
Raise:
-
BaseSyncClient¶
-
class
stellar_sdk.client.base_sync_client.
BaseSyncClient
[source]¶ This is an abstract class, and if you want to implement your own synchronous client, you must implement this class.
-
get
(url, params=None)[source]¶ Perform HTTP GET request.
Parameters: Return type: Returns: the response from server
Raise:
-
post
(url, data)[source]¶ Perform HTTP POST request.
Parameters: Return type: Returns: the response from server
Raise:
-
stream
(url, params=None)[source]¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Parameters: Return type: Returns: a dict Generator for server response
Raise:
-
AiohttpClient¶
-
class
stellar_sdk.client.aiohttp_client.
AiohttpClient
(pool_size=None, request_timeout=11, post_timeout=33.0, backoff_factor=0.5, user_agent=None, **kwargs)[source]¶ The
AiohttpClient
object is a asynchronous http client, which represents the interface for making requests to a server instance.Parameters: - pool_size (
Optional
[int
]) – persistent connection to Horizon and connection pool - request_timeout (
float
) – the timeout for all GET requests - post_timeout (
float
) – the timeout for all POST requests - backoff_factor (
Optional
[float
]) – a backoff factor to apply between attempts after the second try - user_agent (
Optional
[str
]) – the server can use it to identify you
-
get
(url, params=None)[source]¶ Perform HTTP GET request.
Parameters: Return type: Returns: the response from server
Raise:
-
post
(url, data=None)[source]¶ Perform HTTP POST request.
Parameters: Return type: Returns: the response from server
Raise:
- pool_size (
RequestsClient¶
-
class
stellar_sdk.client.requests_client.
RequestsClient
(pool_size=10, num_retries=3, request_timeout=11, post_timeout=33.0, backoff_factor=0.5, session=None, stream_session=None)[source]¶ The
RequestsClient
object is a synchronous http client, which represents the interface for making requests to a server instance.Parameters: - pool_size (
int
) – persistent connection to Horizon and connection pool - num_retries (
int
) – configurable request retry functionality - request_timeout (
int
) – the timeout for all GET requests - post_timeout (
float
) – the timeout for all POST requests - backoff_factor (
float
) – a backoff factor to apply between attempts after the second try - session (
Optional
[Session
]) – the request session - stream_session (
Optional
[Session
]) – the stream request session
-
get
(url, params=None)[source]¶ Perform HTTP GET request.
Parameters: Return type: Returns: the response from server
Raise:
-
post
(url, data=None)[source]¶ Perform HTTP POST request.
Parameters: Return type: Returns: the response from server
Raise:
-
stream
(url, params=None)[source]¶ Creates an EventSource that listens for incoming messages from the server.
See MDN EventSource
Parameters: Return type: Returns: a Generator for server response
Raise:
- pool_size (
SimpleRequestsClient¶
-
class
stellar_sdk.client.simple_requests_client.
SimpleRequestsClient
[source]¶ The
SimpleRequestsClient
object is a synchronous http client, which represents the interface for making requests to a server instance.This client is to guide you in writing a client that suits your needs. I don’t recommend that you actually use it.
-
get
(url, params=None)[source]¶ Perform HTTP GET request.
Parameters: Return type: Returns: the response from server
Raise:
-
Exceptions¶
SdkError¶
ValueError¶
BadSignatureError¶
Ed25519PublicKeyInvalidError¶
Ed25519SecretSeedInvalidError¶
MissingEd25519SecretSeedError¶
AssetCodeInvalidError¶
AssetIssuerInvalidError¶
NoApproximationError¶
SignatureExistError¶
BaseRequestError¶
ConnectionError¶
BaseHorizonError¶
NotFoundError¶
BadRequestError¶
Keypair¶
-
class
stellar_sdk.keypair.
Keypair
(verify_key, signing_key=None)[source]¶ The
Keypair
object, which represents a signing and verifying key for use with the Stellar network.Instead of instantiating the class directly, we recommend using one of several class methods:
Parameters: - verify_key (
VerifyKey
) – The verifying (public) Ed25519 key in the keypair. - signing_key (
Optional
[SigningKey
]) – The signing (private) Ed25519 key in the keypair.
-
can_sign
()[source]¶ Returns True if this
Keypair
object contains secret key and can sign.Return type: bool
Returns: True if this Keypair
object contains secret key and can sign
-
classmethod
from_mnemonic_phrase
(mnemonic_phrase, passphrase='', index=0)[source]¶ Generate a
Keypair
object via a mnemonic phrase.Parameters: - mnemonic_phrase (
str
) – A unique string used to deterministically generate keypairs. - passphrase (
str
) – An optional passphrase used as part of the salt during PBKDF2 rounds when generating the seed from the mnemonic. - index (
int
) –The index of the keypair generated by the mnemonic. This allows for multiple Keypairs to be derived from the same mnemonic, such as:
>>> from stellar_sdk.keypair import Keypair >>> mnemonic = 'update hello cry airport drive chunk elite boat shaft sea describe number' # Don't use this mnemonic in practice. >>> kp1 = Keypair.from_mnemonic_phrase(mnemonic, index=0) >>> kp2 = Keypair.from_mnemonic_phrase(mnemonic, index=1) >>> kp3 = Keypair.from_mnemonic_phrase(mnemonic, index=2)
Returns: A new
Keypair
instance derived from the mnemonic.- mnemonic_phrase (
-
classmethod
from_public_key
(public_key)[source]¶ Generate a
Keypair
object from a public key.Parameters: public_key ( str
) – strkey ed25519 public key, for example: GATPGGOIE6VWADVKD3ER3IFO2IH6DTOA5G535ITB3TT66FZFSIZEAU2BReturn type: Keypair
Returns: A new Keypair
instance derived by the public key.Raise: Ed25519PublicKeyInvalidError
: ifpublic_key
is not a valid ed25519 public key.
-
classmethod
from_raw_ed25519_public_key
(raw_public_key)[source]¶ Generate a
Keypair
object from ed25519 public key raw bytes.Parameters: raw_public_key ( bytes
) – ed25519 public key raw bytesReturn type: Keypair
Returns: A new Keypair
instance derived by the ed25519 public key raw bytes
-
classmethod
from_raw_ed25519_seed
(raw_seed)[source]¶ Generate a
Keypair
object from ed25519 secret key seed raw bytes.Parameters: raw_seed ( bytes
) – ed25519 secret key seed raw bytesReturn type: Keypair
Returns: A new Keypair
instance derived by the ed25519 secret key seed raw bytes
-
classmethod
from_secret
(secret)[source]¶ Generate a
Keypair
object from a secret seed.Parameters: secret ( str
) – strkey ed25519 seed, for example: SB2LHKBL24ITV2Y346BU46XPEL45BDAFOOJLZ6SESCJZ6V5JMP7D6G5XReturn type: Keypair
Returns: A new Keypair
instance derived by the secret.Raise: Ed25519SecretSeedInvalidError
: ifsecret
is not a valid ed25519 secret seed.
-
static
generate_mnemonic_phrase
(language=<Language.ENGLISH: 'english'>, strength=128)[source]¶ Generate a mnemonic phrase.
Parameters: Returns: A mnemonic phrase.
-
public_key
¶ Returns public key associated with this
Keypair
instanceReturn type: str
Returns: public key
-
classmethod
random
()[source]¶ Generate a
Keypair
object from a randomly generated seed.Return type: Keypair
Returns: A new Keypair
instance derived by the randomly seed.
-
secret
¶ Returns secret key associated with this
Keypair
instanceReturn type: str
Returns: secret key Raise: MissingEd25519SecretSeedError
TheKeypair
does not contain secret seed
-
sign
(data)[source]¶ Sign the provided data with the keypair’s private key.
Parameters: data ( bytes
) – The data to sign.Return type: bytes
Returns: signed bytes Raise: MissingEd25519SecretSeedError
: ifKeypair
does not contain secret seed.
-
sign_decorated
(data)[source]¶ Sign the provided data with the keypair’s private key and returns DecoratedSignature.
Parameters: data – signed bytes Return type: DecoratedSignature
Returns: sign decorated
-
signature_hint
()[source]¶ Returns signature hint associated with this
Keypair
instanceReturn type: bytes
Returns: signature hint
-
verify
(data, signature)[source]¶ Verify the provided data and signature match this keypair’s public key.
Parameters: Raise: BadSignatureError
: if the verification failed and the signature was incorrect.Return type: None
- verify_key (
Memo¶
Memo¶
-
class
stellar_sdk.memo.
Memo
[source]¶ The
Memo
object, which represents the base class for memos for use with Stellar transactions.The memo for a transaction contains optional extra information about the transaction taking place. It is the responsibility of the client to interpret this value.
See the following implementations that serve a more practical use with the library:
NoneMemo
- No memo.TextMemo
- A string encoded using either ASCII or UTF-8, up to 28-bytes long.IdMemo
- A 64 bit unsigned integer.HashMemo
- A 32 byte hash.RetHashMemo
- A 32 byte hash intended to be interpreted as the hash of the transaction the sender is refunding.
See Stellar’s documentation on Transactions for more information on how memos are used within transactions, as well as information on the available types of memos.
NoneMemo¶
TextMemo¶
-
class
stellar_sdk.memo.
TextMemo
(text)[source]¶ The
TextMemo
, which represents MEMO_TEXT in a transaction.Parameters: text (str, bytes) – A string encoded using either ASCII or UTF-8, up to 28-bytes long. Raises: MemoInvalidException
: iftext
is not a valid text memo.
IdMemo¶
-
class
stellar_sdk.memo.
IdMemo
(memo_id)[source]¶ The
IdMemo
which represents MEMO_ID in a transaction.Parameters: memo_id (int) – A 64 bit unsigned integer. Raises: MemoInvalidException
: ifid
is not a valid id memo.
HashMemo¶
-
class
stellar_sdk.memo.
HashMemo
(memo_hash)[source]¶ The
HashMemo
which represents MEMO_HASH in a transaction.Parameters: memo_hash ( Union
[bytes
,str
]) – A 32 byte hash hex encoded string.Raises: MemoInvalidException
: ifmemo_hash
is not a valid hash memo.
ReturnHashMemo¶
-
class
stellar_sdk.memo.
ReturnHashMemo
(memo_return)[source]¶ The
ReturnHashMemo
which represents MEMO_RETURN in a transaction.MEMO_RETURN is typically used with refunds/returns over the network - it is a 32 byte hash intended to be interpreted as the hash of the transaction the sender is refunding.
Parameters: memo_return ( bytes
) – A 32 byte hash or hex encoded string intended to be interpreted as the hash of the transaction the sender is refunding.Raises: MemoInvalidException
: ifmemo_return
is not a valid return hash memo.-
classmethod
from_xdr_object
(xdr_obj)[source]¶ Returns an
ReturnHashMemo
object from XDR memo object.Return type: ReturnHashMemo
-
to_xdr_object
()[source]¶ Creates an XDR Memo object that represents this
ReturnHashMemo
.Return type: Memo
-
classmethod
Network¶
-
class
stellar_sdk.network.
Network
(network_passphrase)[source]¶ The
Network
object, which represents a Stellar network.This class represents such a stellar network such as the Public network and the Test network.
Parameters: network_passphrase (str) – The passphrase for the network. (ex. ‘Public Global Stellar Network ; September 2015’) -
PUBLIC_NETWORK_PASSPHRASE
= 'Public Global Stellar Network ; September 2015'¶ Get the Public network passphrase.
-
TESTNET_NETWORK_PASSPHRASE
= 'Test SDF Network ; September 2015'¶ Get the Test network passphrase.
-
network_id
()[source]¶ Get the network ID of the network, which is an XDR hash of the passphrase.
Return type: bytes
Returns: The network ID of the network.
-
Operation¶
Operation¶
-
class
stellar_sdk.operation.
Operation
(source=None)[source]¶ The
Operation
object, which represents an operation on Stellar’s network.An operation is an individual command that mutates Stellar’s ledger. It is typically rolled up into a transaction (a transaction is a list of operations with additional metadata).
Operations are executed on behalf of the source account specified in the transaction, unless there is an override defined for the operation.
For more on operations, see Stellar’s documentation on operations as well as Stellar’s List of Operations, which includes information such as the security necessary for a given operation, as well as information about when validity checks occur on the network.
The
Operation
class is typically not used, but rather one of its subclasses is typically included in transactions.Parameters: source ( Optional
[str
]) – The source account for the payment. Defaults to the transaction’s source account.-
static
from_xdr_amount
(value)[source]¶ Converts an str amount from an XDR amount object
Parameters: value ( int
) – The amount to convert to a string from an XDR int64 amount.Return type: str
-
classmethod
from_xdr_object
(operation_xdr_object)[source]¶ Create the appropriate
Operation
subclass from the XDR object.Parameters: operation_xdr_object ( Operation
) – The XDR object to create anOperation
(or subclass) instance from.Return type: Operation
-
static
get_source_from_xdr_obj
(xdr_object)[source]¶ Get the source account from account the operation xdr object.
Parameters: xdr_object ( Operation
) – the operation xdr object.Return type: Optional
[str
]Returns: The source account from account the operation xdr object.
-
static
get_source_muxed_from_xdr_obj
(xdr_object)[source]¶ Get the source account from account the operation xdr object.
Parameters: xdr_object ( Operation
) – the operation xdr object.Return type: Optional
[MuxedAccount
]Returns: The source account from account the operation xdr object.
-
static
to_xdr_amount
(value)[source]¶ Converts an amount to the appropriate value to send over the network as a part of an XDR object.
Each asset amount is encoded as a signed 64-bit integer in the XDR structures. An asset amount unit (that which is seen by end users) is scaled down by a factor of ten million (10,000,000) to arrive at the native 64-bit integer representation. For example, the integer amount value 25,123,456 equals 2.5123456 units of the asset. This scaling allows for seven decimal places of precision in human-friendly amount units.
This static method correctly multiplies the value by the scaling factor in order to come to the integer value used in XDR structures.
See Stellar’s documentation on Asset Precision for more information.
Parameters: value ( Union
[str
,Decimal
]) – The amount to convert to an integer for XDR serialization.Return type: int
-
static
AccountMerge¶
-
class
stellar_sdk.operation.
AccountMerge
(destination, source=None)[source]¶ The
AccountMerge
object, which represents a AccountMerge operation on Stellar’s network.Transfers the native balance (the amount of XLM an account holds) to another account and removes the source account from the ledger.
Threshold: High
Parameters: -
classmethod
from_xdr_object
(operation_xdr_object)[source]¶ Creates a
AccountMerge
object from an XDR Operation object.Return type: AccountMerge
-
classmethod
AllowTrust¶
-
class
stellar_sdk.operation.
AllowTrust
(trustor, asset_code, authorize, source=None)[source]¶ The
AllowTrust
object, which represents a AllowTrust operation on Stellar’s network.Updates the authorized flag of an existing trustline. This can only be called by the issuer of a trustline’s asset.
The issuer can only clear the authorized flag if the issuer has the AUTH_REVOCABLE_FLAG set. Otherwise, the issuer can only set the authorized flag.
Threshold: Low
Parameters: - trustor (
str
) – The trusting account (the one being authorized). - asset_code (
str
) – The asset code being authorized. - authorize (
Union
[TrustLineEntryFlag
,bool
]) – True to authorize the line, False to deauthorize,if you need further control, you can also usestellar_sdk.operation.allow_trust.TrustLineEntryFlag
. - source (
Optional
[str
]) – The source account (defaults to transaction source).
-
classmethod
from_xdr_object
(operation_xdr_object)[source]¶ Creates a
AllowTrust
object from an XDR Operation object.Return type: AllowTrust
- trustor (
-
class
stellar_sdk.operation.allow_trust.
TrustLineEntryFlag
[source]¶ Indicates which flags to set. For details about the flags, please refer to the CAP-0018.
- UNAUTHORIZED_FLAG: The account can not hold a balance but cannot receive payments, send payments, maintain offers, or manage offers
- AUTHORIZED_FLAG: The account can hold a balance but cannot receive payments, send payments, maintain offers, or manage offers
- AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG: The account can hold a balance, receive payments, send payments, maintain offers, and manage offers
BumpSequence¶
-
class
stellar_sdk.operation.
BumpSequence
(bump_to, source=None)[source]¶ The
BumpSequence
object, which represents a BumpSequence operation on Stellar’s network.Bump sequence allows to bump forward the sequence number of the source account of the operation, allowing to invalidate any transactions with a smaller sequence number. If the specified bumpTo sequence number is greater than the source account’s sequence number, the account’s sequence number is updated with that value, otherwise it’s not modified.
Threshold: Low
Parameters: -
classmethod
from_xdr_object
(operation_xdr_object)[source]¶ Creates a
BumpSequence
object from an XDR Operation object.Return type: BumpSequence
-
classmethod
ChangeTrust¶
-
class
stellar_sdk.operation.
ChangeTrust
(asset, limit=None, source=None)[source]¶ The
ChangeTrust
object, which represents a ChangeTrust operation on Stellar’s network.Creates, updates, or deletes a trustline. For more on trustlines, please refer to the assets documentation <https://www.stellar.org/developers/guides/concepts/assets.html>_.
Threshold: Medium
Parameters: -
classmethod
from_xdr_object
(operation_xdr_object)[source]¶ Creates a
ChangeTrust
object from an XDR Operation object.Return type: ChangeTrust
-
classmethod
CreateAccount¶
-
class
stellar_sdk.operation.
CreateAccount
(destination, starting_balance, source=None)[source]¶ The
CreateAccount
object, which represents a Create Account operation on Stellar’s network.This operation creates and funds a new account with the specified starting balance.
Threshold: Medium
Parameters: - destination (
str
) – Destination account ID to create an account for. - starting_balance (
Union
[str
,Decimal
]) – Amount in XLM the account should be funded for. Must be greater than the reserve balance amount. - source (
Optional
[str
]) – The source account for the payment. Defaults to the transaction’s source account.
-
classmethod
from_xdr_object
(operation_xdr_object)[source]¶ Creates a
CreateAccount
object from an XDR Operation object.Return type: CreateAccount
- destination (
CreatePassiveSellOffer¶
-
class
stellar_sdk.operation.
CreatePassiveSellOffer
(selling, buying, amount, price, source=None)[source]¶ The
CreatePassiveSellOffer
object, which represents a CreatePassiveSellOffer operation on Stellar’s network.A passive sell offer is an offer that does not act on and take a reverse offer of equal price. Instead, they only take offers of lesser price. For example, if an offer exists to buy 5 BTC for 30 XLM, and you make a passive sell offer to buy 30 XLM for 5 BTC, your passive sell offer does not take the first offer.
Note that regular offers made later than your passive sell offer can act on and take your passive sell offer, even if the regular offer is of the same price as your passive sell offer.
Passive sell offers allow market makers to have zero spread. If you want to trade EUR for USD at 1:1 price and USD for EUR also at 1:1, you can create two passive sell offers so the two offers don’t immediately act on each other.
Once the passive sell offer is created, you can manage it like any other offer using the manage offer operation - see
ManageOffer
for more details.Parameters: - selling (
Asset
) – What you’re selling. - buying (
Asset
) – What you’re buying. - amount (
Union
[str
,Decimal
]) – The total amount you’re selling. If 0, deletes the offer. - price (
Union
[Price
,str
,Decimal
]) – Price of 1 unit of selling in terms of buying. - source (
Optional
[str
]) – The source account (defaults to transaction source).
-
classmethod
from_xdr_object
(operation_xdr_object)[source]¶ Creates a
CreatePassiveSellOffer
object from an XDR Operation object.Return type: CreatePassiveSellOffer
- selling (
Inflation¶
-
class
stellar_sdk.operation.
Inflation
(source=None)[source]¶ The
Inflation
object, which represents a Inflation operation on Stellar’s network.This operation runs inflation.
Threshold: Low
Parameters: source (str) – The source account (defaults to transaction source).
ManageBuyOffer¶
-
class
stellar_sdk.operation.
ManageBuyOffer
(selling, buying, amount, price, offer_id=0, source=None)[source]¶ The
ManageBuyOffer
object, which represents a ManageBuyOffer operation on Stellar’s network.Creates, updates, or deletes an buy offer.
If you want to create a new offer set Offer ID to 0.
If you want to update an existing offer set Offer ID to existing offer ID.
If you want to delete an existing offer set Offer ID to existing offer ID and set Amount to 0.
Threshold: Medium
Parameters: - selling (
Asset
) – What you’re selling. - buying (
Asset
) – What you’re buying. - amount (
Union
[str
,Decimal
]) – Amount being bought. if set to 0, delete the offer. - price (
Union
[Price
,str
,Decimal
]) – Price of thing being bought in terms of what you are selling. - offer_id (
int
) – If 0, will create a new offer (default). Otherwise, edits an existing offer. - source (
Optional
[str
]) – The source account (defaults to transaction source).
-
classmethod
from_xdr_object
(operation_xdr_object)[source]¶ Creates a
ManageBuyOffer
object from an XDR Operation object.Return type: ManageBuyOffer
- selling (
ManageData¶
-
class
stellar_sdk.operation.
ManageData
(data_name, data_value, source=None)[source]¶ The
ManageData
object, which represents a ManageData operation on Stellar’s network.Allows you to set, modify or delete a Data Entry (name/value pair) that is attached to a particular account. An account can have an arbitrary amount of DataEntries attached to it. Each DataEntry increases the minimum balance needed to be held by the account.
DataEntries can be used for application specific things. They are not used by the core Stellar protocol.
Threshold: Medium
Parameters: -
classmethod
from_xdr_object
(operation_xdr_object)[source]¶ Creates a
ManageData
object from an XDR Operation object.Return type: ManageData
-
classmethod
ManageSellOffer¶
-
class
stellar_sdk.operation.
ManageSellOffer
(selling, buying, amount, price, offer_id=0, source=None)[source]¶ The
ManageSellOffer
object, which represents a ManageSellOffer operation on Stellar’s network.Creates, updates, or deletes an sell offer.
If you want to create a new offer set Offer ID to 0.
If you want to update an existing offer set Offer ID to existing offer ID.
If you want to delete an existing offer set Offer ID to existing offer ID and set Amount to 0.
Threshold: Medium
Parameters: - selling (
Asset
) – What you’re selling. - buying (
Asset
) – What you’re buying. - amount (
Union
[str
,Decimal
]) – The total amount you’re selling. If 0, deletes the offer. - price (
Union
[Price
,str
,Decimal
]) – Price of 1 unit of selling in terms of buying. - offer_id (
int
) – If 0, will create a new offer (default). Otherwise, edits an existing offer. - source (
Optional
[str
]) – The source account (defaults to transaction source).
-
classmethod
from_xdr_object
(operation_xdr_object)[source]¶ Creates a
ManageSellOffer
object from an XDR Operation object.Return type: ManageSellOffer
- selling (
PathPayment¶
-
class
stellar_sdk.operation.
PathPayment
(destination, send_asset, send_max, dest_asset, dest_amount, path, source=None)[source]¶ The
PathPayment
object, which represents a PathPayment operation on Stellar’s network.Sends an amount in a specific asset to a destination account through a path of offers. This allows the asset sent (e.g. 450 XLM) to be different from the asset received (e.g. 6 BTC).
Threshold: Medium
Parameters: - destination (
str
) – The destination account to send to. - send_asset (
Asset
) – The asset to pay with. - send_max (
Union
[str
,Decimal
]) – The maximum amount of send_asset to send. - dest_asset (
Asset
) – The asset the destination will receive. - dest_amount (
Union
[str
,Decimal
]) – The amount the destination receives. - path (
List
[Asset
]) – A list of Asset objects to use as the path. - source (
Optional
[str
]) – The source account for the payment. Defaults to the transaction’s source account.
-
classmethod
from_xdr_object
(operation_xdr_object)¶ Creates a
PathPaymentStrictReceive
object from an XDR Operation object.Return type: PathPaymentStrictReceive
- destination (
PathPaymentStrictReceive¶
-
class
stellar_sdk.operation.
PathPaymentStrictReceive
(destination, send_asset, send_max, dest_asset, dest_amount, path, source=None)[source]¶ The
PathPaymentStrictReceive
object, which represents a PathPaymentStrictReceive operation on Stellar’s network.Sends an amount in a specific asset to a destination account through a path of offers. This allows the asset sent (e.g. 450 XLM) to be different from the asset received (e.g. 6 BTC).
Threshold: Medium
Parameters: - destination (
str
) – The destination account to send to. - send_asset (
Asset
) – The asset to pay with. - send_max (
Union
[str
,Decimal
]) – The maximum amount of send_asset to send. - dest_asset (
Asset
) – The asset the destination will receive. - dest_amount (
Union
[str
,Decimal
]) – The amount the destination receives. - path (
List
[Asset
]) – A list of Asset objects to use as the path. - source (
Optional
[str
]) – The source account for the payment. Defaults to the transaction’s source account.
-
classmethod
from_xdr_object
(operation_xdr_object)[source]¶ Creates a
PathPaymentStrictReceive
object from an XDR Operation object.Return type: PathPaymentStrictReceive
- destination (
PathPaymentStrictSend¶
-
class
stellar_sdk.operation.
PathPaymentStrictSend
(destination, send_asset, send_amount, dest_asset, dest_min, path, source=None)[source]¶ The
PathPaymentStrictSend
object, which represents a PathPaymentStrictSend operation on Stellar’s network.Sends an amount in a specific asset to a destination account through a path of offers. This allows the asset sent (e.g, 450 XLM) to be different from the asset received (e.g, 6 BTC).
Threshold: Medium
Parameters: - destination (
str
) – The destination account to send to. - send_asset (
Asset
) – The asset to pay with. - send_amount (
Union
[str
,Decimal
]) – Amount of send_asset to send. - dest_asset (
Asset
) – The asset the destination will receive. - dest_min (
Union
[str
,Decimal
]) – The minimum amount of dest_asset to be received. - path (
List
[Asset
]) – A list of Asset objects to use as the path. - source (
Optional
[str
]) – The source account for the payment. Defaults to the transaction’s source account.
-
classmethod
from_xdr_object
(operation_xdr_object)[source]¶ Creates a
PathPaymentStrictSend
object from an XDR Operation object.Return type: PathPaymentStrictSend
- destination (
Payment¶
-
class
stellar_sdk.operation.
Payment
(destination, asset, amount, source=None)[source]¶ The
Payment
object, which represents a Payment operation on Stellar’s network.Sends an amount in a specific asset to a destination account.
Threshold: Medium
Parameters:
SetOptions¶
-
class
stellar_sdk.operation.
SetOptions
(inflation_dest=None, clear_flags=None, set_flags=None, master_weight=None, low_threshold=None, med_threshold=None, high_threshold=None, signer=None, home_domain=None, source=None)[source]¶ The
SetOptions
object, which represents a SetOptions operation on Stellar’s network.This operation sets the options for an account.
For more information on the signing options, please refer to the multi-sig doc.
When updating signers or other thresholds, the threshold of this operation is high.
Threshold: Medium or High
Parameters: - inflation_dest (
Optional
[str
]) – Account of the inflation destination. - clear_flags (
Union
[int
,Flag
,None
]) – Indicates which flags to clear. For details about the flags, please refer to the accounts doc. The bit mask integer subtracts from the existing flags of the account. This allows for setting specific bits without knowledge of existing flags, you can also usestellar_sdk.operation.set_options.Flag
- AUTHORIZATION_REQUIRED = 1 - AUTHORIZATION_REVOCABLE = 2 - AUTHORIZATION_IMMUTABLE = 4 - set_flags (
Union
[int
,Flag
,None
]) –Indicates which flags to set. For details about the flags, please refer to the accounts doc. The bit mask integer adds onto the existing flags of the account. This allows for setting specific bits without knowledge of existing flags, you can also use
stellar_sdk.operation.set_options.Flag
- AUTHORIZATION_REQUIRED = 1 - AUTHORIZATION_REVOCABLE = 2 - AUTHORIZATION_IMMUTABLE = 4 - master_weight (
Optional
[int
]) – A number from 0-255 (inclusive) representing the weight of the master key. If the weight of the master key is updated to 0, it is effectively disabled. - low_threshold (
Optional
[int
]) – A number from 0-255 (inclusive) representing the threshold this account sets on all operations it performs that have a low threshold. - med_threshold (
Optional
[int
]) – A number from 0-255 (inclusive) representing the threshold this account sets on all operations it performs that have a medium threshold. - high_threshold (
Optional
[int
]) – A number from 0-255 (inclusive) representing the threshold this account sets on all operations it performs that have a high threshold. - home_domain (
Optional
[str
]) – sets the home domain used for reverse federation lookup. - signer (
Optional
[Signer
]) – Add, update, or remove a signer from the account. - source (
Optional
[str
]) – The source account (defaults to transaction source).
-
classmethod
from_xdr_object
(operation_xdr_object)[source]¶ Creates a
SetOptions
object from an XDR Operation object.Return type: SetOptions
- inflation_dest (
-
class
stellar_sdk.operation.set_options.
Flag
[source]¶ Indicates which flags to set. For details about the flags, please refer to the accounts doc. The bit mask integer adds onto the existing flags of the account.
Price¶
-
class
stellar_sdk.price.
Price
(n, d)[source]¶ Create a new price. Price in Stellar is represented as a fraction.
Parameters: -
classmethod
from_raw_price
(price)[source]¶ Create a
Price
from the given str price.Parameters: price ( str
) – the str price. (ex. ‘0.125’)Return type: Price
Returns: A new Price
object from the given str price.Raises: NoApproximationError
: if the approximation could not not be found.
-
classmethod
Server¶
-
class
stellar_sdk.server.
Server
(horizon_url='https://horizon-testnet.stellar.org/', client=None)[source]¶ Server handles the network connection to a Horizon instance and exposes an interface for requests to that instance.
Here we need to talk about the client parameter, if you do not specify the client, we will use the
stellar_sdk.client.requests_client.RequestsClient
instance by default, it is a synchronous HTTPClient, you can also specify an asynchronous HTTP Client, for example:stellar_sdk.client.aiohttp_client.AiohttpClient
. If you use a synchronous client, then all requests are synchronous. If you use an asynchronous client, then all requests are asynchronous. The choice is in your hands.Parameters: - horizon_url (
str
) – Horizon Server URL (ex. https://horizon-testnet.stellar.org) - client (
Union
[BaseAsyncClient
,BaseSyncClient
,None
]) – Http Client used to send the request
Raises: TypeError
: if theclient
does not meet the standard.-
accounts
()[source]¶ Return type: AccountsCallBuilder
Returns: New stellar_sdk.call_builder.AccountsCallBuilder
object configured by a current Horizon server configuration.
-
assets
()[source]¶ Return type: AssetsCallBuilder
Returns: New stellar_sdk.call_builder.AssetsCallBuilder
object configured by a current Horizon server configuration.
-
close
()[source]¶ Close underlying connector.
Release all acquired resources.
Return type: Optional
[Coroutine
[Any
,Any
,None
]]
-
data
(account_id, data_name)[source]¶ Returns: New stellar_sdk.call_builder.DataCallBuilder
object configured by a current Horizon server configuration.
-
effects
()[source]¶ Return type: EffectsCallBuilder
Returns: New stellar_sdk.call_builder.EffectsCallBuilder
object configured by a current Horizon server configuration.
-
fee_stats
()[source]¶ Return type: FeeStatsCallBuilder
Returns: New stellar_sdk.call_builder.FeeStatsCallBuilder
object configured by a current Horizon server configuration.
-
fetch_base_fee
()[source]¶ Fetch the base fee. Since this hits the server, if the server call fails, you might get an error. You should be prepared to use a default value if that happens.
Return type: Union
[int
,Coroutine
[Any
,Any
,int
]]Returns: the base fee Raises: ConnectionError
NotFoundError
BadRequestError
BadResponseError
UnknownRequestError
-
ledgers
()[source]¶ Return type: LedgersCallBuilder
Returns: New stellar_sdk.call_builder.LedgersCallBuilder
object configured by a current Horizon server configuration.
-
load_account
(account_id)[source]¶ Fetches an account’s most current state in the ledger and then creates and returns an
stellar_sdk.account.Account
object.Parameters: account_id ( Union
[Keypair
,str
]) – The account to load.Return type: Union
[Account
,Coroutine
[Any
,Any
,Account
]]Returns: an stellar_sdk.account.Account
object.Raises: ConnectionError
NotFoundError
BadRequestError
BadResponseError
UnknownRequestError
-
offers
()[source]¶ Return type: OffersCallBuilder
Returns: New stellar_sdk.call_builder.OffersCallBuilder
object configured by a current Horizon server configuration.
-
operations
()[source]¶ Return type: OperationsCallBuilder
Returns: New stellar_sdk.call_builder.OperationsCallBuilder
object configured by a current Horizon server configuration.
-
orderbook
(selling, buying)[source]¶ Parameters: Return type: OrderbookCallBuilder
Returns: New
stellar_sdk.call_builder.OrderbookCallBuilder
object configured by a current Horizon server configuration.
-
paths
(source_account, destination_account, destination_asset, destination_amount)[source]¶ Parameters: - source_account (
str
) – The sender’s account ID. Any returned path must use a source that the sender can hold. - destination_account (
str
) – The destination account ID that any returned path should use. - destination_asset (
Asset
) – The destination asset. - destination_amount (
str
) – The amount, denominated in the destination asset, that any returned path should be able to satisfy.
Return type: PathsCallBuilder
Returns: New
stellar_sdk.call_builder.PathsCallBuilder
object configured by a current Horizon server configuration.- source_account (
-
payments
()[source]¶ Return type: PaymentsCallBuilder
Returns: New stellar_sdk.call_builder.PaymentsCallBuilder
object configured by a current Horizon server configuration.
-
root
()[source]¶ Return type: RootCallBuilder
Returns: New stellar_sdk.call_builder.RootCallBuilder
object configured by a current Horizon server configuration.
-
strict_receive_paths
(source, destination_asset, destination_amount)[source]¶ Parameters: - source (
Union
[str
,List
[Asset
]]) – The sender’s account ID or a list of Assets. Any returned path must use a source that the sender can hold. - destination_asset (
Asset
) – The destination asset. - destination_amount (
str
) – The amount, denominated in the destination asset, that any returned path should be able to satisfy.
Returns: New
stellar_sdk.call_builder.StrictReceivePathsCallBuilder
object configured by a current Horizon server configuration.- source (
-
strict_send_paths
(source_asset, source_amount, destination)[source]¶ Parameters: Returns: New
stellar_sdk.call_builder.StrictReceivePathsCallBuilder
object configured by a current Horizon server configuration.
-
submit_transaction
(transaction_envelope, skip_memo_required_check=False)[source]¶ Submits a transaction to the network.
Parameters: transaction_envelope ( Union
[TransactionEnvelope
,FeeBumpTransactionEnvelope
,str
]) –stellar_sdk.transaction_envelope.TransactionEnvelope
object or base64 encoded xdrReturn type: Union
[Dict
[str
,Any
],Coroutine
[Any
,Any
,Dict
[str
,Any
]]]Returns: the response from horizon Raises: ConnectionError
NotFoundError
BadRequestError
BadResponseError
UnknownRequestError
AccountRequiresMemoError
-
trade_aggregations
(base, counter, resolution, start_time=None, end_time=None, offset=None)[source]¶ Parameters: - base (
Asset
) – base asset - counter (
Asset
) – counter asset - resolution (
int
) – segment duration as millis since epoch. Supported values are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). - start_time (
Optional
[int
]) – lower time boundary represented as millis since epoch - end_time (
Optional
[int
]) – upper time boundary represented as millis since epoch - offset (
Optional
[int
]) – segments can be offset using this parameter. Expressed in milliseconds. Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours.
Return type: TradeAggregationsCallBuilder
Returns: New
stellar_sdk.call_builder.TradeAggregationsCallBuilder
object configured by a current Horizon server configuration.- base (
-
trades
()[source]¶ Return type: TradesCallBuilder
Returns: New stellar_sdk.call_builder.TradesCallBuilder
object configured by a current Horizon server configuration.
-
transactions
()[source]¶ Return type: TransactionsCallBuilder
Returns: New stellar_sdk.call_builder.TransactionsCallBuilder
object configured by a current Horizon server configuration.
- horizon_url (
Signer¶
-
class
stellar_sdk.signer.
Signer
(signer_key, weight)[source]¶ The
Signer
object, which represents an account signer on Stellar’s network.Parameters: - signer_key (
SignerKey
) – The XDR signer object - weight –
-
classmethod
ed25519_public_key
(account_id, weight)[source]¶ Create ED25519 PUBLIC KEY Signer from account id.
Parameters: Return type: Returns: ED25519 PUBLIC KEY Signer
Raises: Ed25519PublicKeyInvalidError
: ifaccount_id
is not a valid ed25519 public key.
-
classmethod
from_xdr_object
(signer_xdr_object)[source]¶ Create a
Signer
from an XDR TimeBounds object.Parameters: signer_xdr_object ( Signer
) – The XDR Signer object.Return type: Signer
Returns: A new Signer
object from the given XDR Signer object.
-
classmethod
pre_auth_tx
(pre_auth_tx_hash, weight)[source]¶ Create Pre AUTH TX Signer from the sha256 hash of a transaction, click here for more information.
Parameters: Return type: Returns: Pre AUTH TX Signer
- signer_key (
TimeBounds¶
-
class
stellar_sdk.time_bounds.
TimeBounds
(min_time, max_time)[source]¶ TimeBounds represents the time interval that a transaction is valid.
The UNIX timestamp (in seconds), determined by ledger time, of a lower and upper bound of when this transaction will be valid. If a transaction is submitted too early or too late, it will fail to make it into the transaction set. max_time equal 0 means that it’s not set.
See Stellar’s documentation on Transactions for more information on how TimeBounds are used within transactions.
Parameters: Raises: ValueError
: ifmax_time
less thanmin_time
.-
classmethod
from_xdr_object
(time_bounds_xdr_object)[source]¶ Create a
TimeBounds
from an XDR TimeBounds object.Parameters: time_bounds_xdr_object ( TimeBounds
) – The XDR TimeBounds object.Return type: TimeBounds
Returns: A new TimeBounds
object from the given XDR TimeBounds object.
-
classmethod
Transaction¶
-
class
stellar_sdk.transaction.
Transaction
(source, sequence, fee, operations, memo=None, time_bounds=None, v1=True)[source]¶ The
Transaction
object, which represents a transaction(Transaction or TransactionV0) on Stellar’s network.A transaction contains a list of operations, which are all executed in order as one ACID transaction, along with an associated source account, fee, account sequence number, list of signatures, both an optional memo and an optional TimeBounds. Typically a
Transaction
is placed in aTransactionEnvelope
which is then signed before being sent over the network.For more information on Transactions in Stellar, see Stellar’s guide on transactions.
Parameters: - source (
Union
[Keypair
,str
]) – the source account for the transaction. - sequence (
int
) – The sequence number for the transaction. - fee (
int
) – The fee amount for the transaction, which should equal FEE (currently 100 stroops) multiplied by the number of operations in the transaction. See Stellar’s latest documentation on fees for more information. - operations (
List
[Operation
]) – A list of operations objects (typically its subclasses as defined instellar_sdk.operation.Operation
. - time_bounds (
Optional
[TimeBounds
]) – The timebounds for the validity of this transaction. - memo (
Optional
[Memo
]) – The memo being sent with the transaction, being represented as one of the subclasses of theMemo
object. - v1 (
bool
) – When this value is set to True, V1 transactions will be generated, otherwise V0 transactions will be generated. See CAP-0015 for more information.
-
classmethod
from_xdr
(xdr, v1=False)[source]¶ Create a new
Transaction
from an XDR string.Parameters: Return type: Returns: A new
Transaction
object from the given XDR Transaction base64 string object.
-
classmethod
from_xdr_object
(tx_xdr_object, v1=False)[source]¶ Create a new
Transaction
from an XDR object.Parameters: Return type: Returns: A new
Transaction
object from the given XDR Transaction object.
-
to_xdr_object
()[source]¶ Get an XDR object representation of this
Transaction
.Return type: Union
[Transaction
,TransactionV0
]Returns: XDR Transaction object
- source (
TransactionEnvelope¶
-
class
stellar_sdk.transaction_envelope.
TransactionEnvelope
(transaction, network_passphrase, signatures=None)[source]¶ The
TransactionEnvelope
object, which represents a transaction envelope ready to sign and submit to send over the network.When a transaction is ready to be prepared for sending over the network, it must be put into a
TransactionEnvelope
, which includes additional metadata such as the signers for a given transaction. Ultimately, this class handles signing and conversion to and from XDR for usage on Stellar’s network.Parameters: - transaction (
Transaction
) – The transaction that is encapsulated in this envelope. - signatures (list) – which contains a list of signatures that have already been created.
- network_passphrase (
str
) – The network to connect to for verifying and retrieving additional attributes from.
-
classmethod
from_xdr
(xdr, network_passphrase)¶ Create a new
BaseTransactionEnvelope
from an XDR string.Parameters: Return type: ~T
Returns: A new
BaseTransactionEnvelope
object from the given XDR TransactionEnvelope base64 string object.
-
classmethod
from_xdr_object
(te_xdr_object, network_passphrase)[source]¶ Create a new
TransactionEnvelope
from an XDR object.Parameters: - te_xdr_object (
TransactionEnvelope
) – The XDR object that represents a transaction envelope. - network_passphrase (
str
) – The network to connect to for verifying and retrieving additional attributes from.
Return type: Returns: A new
TransactionEnvelope
object from the given XDR TransactionEnvelope object.- te_xdr_object (
-
hash
()¶ Get the XDR Hash of the signature base.
This hash is ultimately what is signed before transactions are sent over the network. See
signature_base()
for more details about this process.Return type: bytes
Returns: The XDR Hash of this transaction envelope’s signature base.
-
hash_hex
()¶ Return a hex encoded hash for this transaction envelope.
Return type: str
Returns: A hex encoded hash for this transaction envelope.
-
sign
(signer)¶ Sign this transaction envelope with a given keypair.
Note that the signature must not already be in this instance’s list of signatures.
Parameters: signer ( Union
[Keypair
,str
]) – The keypair or secret to use for signing this transaction envelope.Raise: SignatureExistError
: if this signature already exists.Return type: None
-
sign_hashx
(preimage)¶ Sign this transaction envelope with a Hash(x) signature.
See Stellar’s documentation on Multi-Sig for more details on Hash(x) signatures.
Parameters: preimage ( bytes
) – 32 byte hash or hex encoded string , the “x” value to be hashed and used as a signature.Return type: None
-
signature_base
()[source]¶ Get the signature base of this transaction envelope.
Return the “signature base” of this transaction, which is the value that, when hashed, should be signed to create a signature that validators on the Stellar Network will accept.
It is composed of a 4 prefix bytes followed by the xdr-encoded form of this transaction.
Return type: bytes
Returns: The signature base of this transaction envelope.
-
to_transaction_envelope_v1
()[source]¶ Create a new
TransactionEnvelope
, if the internal tx is not v1, we will convert it to v1.Return type: TransactionEnvelope
-
to_xdr
()¶ Get the base64 encoded XDR string representing this
BaseTransactionEnvelope
.Return type: str
Returns: XDR TransactionEnvelope base64 string object
-
to_xdr_object
()[source]¶ Get an XDR object representation of this
TransactionEnvelope
.Return type: TransactionEnvelope
Returns: XDR TransactionEnvelope object
- transaction (
FeeBumpTransaction¶
-
class
stellar_sdk.fee_bump_transaction.
FeeBumpTransaction
(fee_source, base_fee, inner_transaction_envelope)[source]¶ The
FeeBumpTransaction
object, which represents a fee bump transaction on Stellar’s network.See CAP-0015 for more information.
Parameters: - fee_source (
Union
[Keypair
,str
]) – The account paying for the transaction. - base_fee (
int
) – The max fee willing to pay per operation in inner transaction (in stroops). - inner_transaction_envelope (
TransactionEnvelope
) – The TransactionEnvelope to be bumped by the fee bump transaction.
-
classmethod
from_xdr
(xdr, network_passphrase)[source]¶ Create a new
FeeBumpTransaction
from an XDR string.Parameters: Return type: Returns: A new
FeeBumpTransaction
object from the given XDR FeeBumpTransaction base64 string object.
-
classmethod
from_xdr_object
(tx_xdr_object, network_passphrase)[source]¶ Create a new
FeeBumpTransaction
from an XDR object.Parameters: - tx_xdr_object (
FeeBumpTransaction
) – The XDR object that represents a fee bump transaction. - network_passphrase (
str
) – The network to connect to for verifying and retrieving additional attributes from.
Return type: Returns: A new
FeeBumpTransaction
object from the given XDR Transaction object.- tx_xdr_object (
-
to_xdr_object
()[source]¶ Get an XDR object representation of this
FeeBumpTransaction
.Return type: FeeBumpTransaction
Returns: XDR Transaction object
- fee_source (
FeeBumpTransactionEnvelope¶
-
class
stellar_sdk.fee_bump_transaction_envelope.
FeeBumpTransactionEnvelope
(transaction, network_passphrase, signatures=None)[source]¶ The
FeeBumpTransactionEnvelope
object, which represents a transaction envelope ready to sign and submit to send over the network.When a transaction is ready to be prepared for sending over the network, it must be put into a
FeeBumpTransactionEnvelope
, which includes additional metadata such as the signers for a given transaction. Ultimately, this class handles signing and conversion to and from XDR for usage on Stellar’s network.Parameters: - transaction (
FeeBumpTransaction
) – The fee bump transaction that is encapsulated in this envelope. - signatures (list) – which contains a list of signatures that have already been created.
- network_passphrase (
str
) – The network to connect to for verifying and retrieving additional attributes from.
-
classmethod
from_xdr
(xdr, network_passphrase)¶ Create a new
BaseTransactionEnvelope
from an XDR string.Parameters: Return type: ~T
Returns: A new
BaseTransactionEnvelope
object from the given XDR TransactionEnvelope base64 string object.
-
classmethod
from_xdr_object
(te_xdr_object, network_passphrase)[source]¶ Create a new
FeeBumpTransactionEnvelope
from an XDR object.Parameters: - te_xdr_object (
TransactionEnvelope
) – The XDR object that represents a fee bump transaction envelope. - network_passphrase (
str
) – The network to connect to for verifying and retrieving additional attributes from.
Return type: Returns: A new
FeeBumpTransactionEnvelope
object from the given XDR TransactionEnvelope object.- te_xdr_object (
-
hash
()¶ Get the XDR Hash of the signature base.
This hash is ultimately what is signed before transactions are sent over the network. See
signature_base()
for more details about this process.Return type: bytes
Returns: The XDR Hash of this transaction envelope’s signature base.
-
hash_hex
()¶ Return a hex encoded hash for this transaction envelope.
Return type: str
Returns: A hex encoded hash for this transaction envelope.
-
sign
(signer)¶ Sign this transaction envelope with a given keypair.
Note that the signature must not already be in this instance’s list of signatures.
Parameters: signer ( Union
[Keypair
,str
]) – The keypair or secret to use for signing this transaction envelope.Raise: SignatureExistError
: if this signature already exists.Return type: None
-
sign_hashx
(preimage)¶ Sign this transaction envelope with a Hash(x) signature.
See Stellar’s documentation on Multi-Sig for more details on Hash(x) signatures.
Parameters: preimage ( bytes
) – 32 byte hash or hex encoded string , the “x” value to be hashed and used as a signature.Return type: None
-
signature_base
()[source]¶ Get the signature base of this transaction envelope.
Return the “signature base” of this transaction, which is the value that, when hashed, should be signed to create a signature that validators on the Stellar Network will accept.
It is composed of a 4 prefix bytes followed by the xdr-encoded form of this transaction.
Return type: bytes
Returns: The signature base of this transaction envelope.
- transaction (
TransactionBuilder¶
-
class
stellar_sdk.transaction_builder.
TransactionBuilder
(source_account, network_passphrase='Test SDF Network ; September 2015', base_fee=100, v1=True)[source]¶ Transaction builder helps constructs a new
TransactionEnvelope
using the givenAccount
as the transaction’s “source account”. The transaction will use the current sequence number of the given account as its sequence number and increment the given account’s sequence number by one. The given source account must include a private key for signing the transaction or an error will be thrown.Be careful about unsubmitted transactions! When you build a transaction, stellar-sdk automatically increments the source account’s sequence number. If you end up not submitting this transaction and submitting another one instead, it’ll fail due to the sequence number being wrong. So if you decide not to use a built transaction, make sure to update the source account’s sequence number with
stellar_sdk.Server.load_account()
before creating another transaction.Parameters: - source_account (
Account
) – The source account for this transaction. - network_passphrase (
str
) – The network to connect to for verifying and retrieving additional attributes from. Defaults to Test SDF Network ; September 2015. - base_fee (
int
) – Base fee in stroops. The network base fee is obtained by default from the latest ledger. Transaction fee is equal to base fee times number of operations in this transaction. - v1 (
bool
) –When this value is set to True, V1 transactions will be generated, otherwise V0 transactions will be generated. See CAP-0015 for more information.
-
add_hash_memo
(memo_hash)[source]¶ Set the memo for the transaction to a new
HashMemo
.Parameters: memo_hash ( Union
[bytes
,str
]) – A 32 byte hash or hex encoded string to use as the memo.Return type: TransactionBuilder
Returns: This builder instance. Raises: MemoInvalidException
: ifmemo_hash
is not a valid hash memo.
-
add_id_memo
(memo_id)[source]¶ Set the memo for the transaction to a new
IdMemo
.Parameters: memo_id ( int
) – A 64 bit unsigned integer to set as the memo.Return type: TransactionBuilder
Returns: This builder instance. Raises: MemoInvalidException
: ifmemo_id
is not a valid id memo.
-
add_memo
(memo)[source]¶ Set the memo for the transaction build by this
Builder
.Parameters: memo ( Memo
) – A memo to add to this transaction.Return type: TransactionBuilder
Returns: This builder instance.
-
add_return_hash_memo
(memo_return)[source]¶ Set the memo for the transaction to a new
RetHashMemo
.Parameters: memo_return ( Union
[bytes
,str
]) – A 32 byte hash or hex encoded string intended to be interpreted as the hash of the transaction the sender is refunding.Return type: TransactionBuilder
Returns: This builder instance. Raises: MemoInvalidException
: ifmemo_return
is not a valid return hash memo.
-
add_text_memo
(memo_text)[source]¶ Set the memo for the transaction to a new
TextMemo
.Parameters: memo_text ( Union
[str
,bytes
]) – The text for the memo to add.Return type: TransactionBuilder
Returns: This builder instance. Raises: MemoInvalidException
: ifmemo_text
is not a valid text memo.
-
add_time_bounds
(min_time, max_time)[source]¶ Add a time bound to this transaction.
Add a UNIX timestamp, determined by ledger time, of a lower and upper bound of when this transaction will be valid. If a transaction is submitted too early or too late, it will fail to make it into the transaction set. maxTime equal 0 means that it’s not set.
Parameters: Return type: Returns: This builder instance.
-
append_account_merge_op
(destination, source=None)[source]¶ Append a
AccountMerge
operation to the list of operations.Parameters: Return type: Returns: This builder instance.
-
append_allow_trust_op
(trustor, asset_code, authorize, source=None)[source]¶ Append an
AllowTrust
operation to the list of operations.Parameters: - trustor (
str
) – The account of the recipient of the trustline. - asset_code (
str
) – The asset of the trustline the source account is authorizing. For example, if an anchor wants to allow another account to hold its USD credit, the type is USD:anchor. - authorize (
Union
[TrustLineEntryFlag
,bool
]) – True to authorize the line, False to deauthorize,if you need further control, you can also usestellar_sdk.operation.allow_trust.TrustLineEntryFlag
. - source (
Optional
[str
]) – The source address that is establishing the trust in the allow trust operation.
Return type: Returns: This builder instance.
- trustor (
-
append_bump_sequence_op
(bump_to, source=None)[source]¶ Append a
BumpSequence
operation to the list of operations.Parameters: Return type: Returns: This builder instance.
-
append_change_trust_op
(asset_code, asset_issuer, limit=None, source=None)[source]¶ Append a
ChangeTrust
operation to the list of operations.Parameters: Return type: Returns: This builder instance.
-
append_create_account_op
(destination, starting_balance, source=None)[source]¶ Append a
CreateAccount
operation to the list of operations.Parameters: Return type: Returns: This builder instance.
-
append_create_passive_sell_offer_op
(selling_code, selling_issuer, buying_code, buying_issuer, amount, price, source=None)[source]¶ Append a
CreatePassiveSellOffer
operation to the list of operations.Parameters: - selling_code (
str
) – The asset code for the asset the offer creator is selling. - selling_issuer (
Optional
[str
]) – The issuing address for the asset the offer creator is selling. - buying_code (
str
) – The asset code for the asset the offer creator is buying. - buying_issuer (
Optional
[str
]) – The issuing address for the asset the offer creator is buying. - amount (
Union
[str
,Decimal
]) – Amount of the asset being sold. Set to 0 if you want to delete an existing offer. - price (
Union
[str
,Price
,Decimal
]) – Price of 1 unit of selling in terms of buying. - source (
Optional
[str
]) – The source address that is creating a passive offer on Stellar’s distributed exchange.
Return type: Returns: This builder instance.
- selling_code (
-
append_ed25519_public_key_signer
(account_id, weight, source=None)[source]¶ Add a ed25519 public key signer to an account.
Add a ed25519 public key signer to an account via a
SetOptions <stellar_sdk.operation.SetOptions
operation. This is a helper function forappend_set_options_op()
.Parameters: Return type: Returns: This builder instance.
-
append_hashx_signer
(sha256_hash, weight, source=None)[source]¶ Add a sha256 hash(HashX) signer to an account.
Add a HashX signer to an account via a
SetOptions <stellar_sdk.operation.SetOptions
operation. This is a helper function forappend_set_options_op()
.Parameters: Return type: Returns: This builder instance.
-
append_inflation_op
(source=None)[source]¶ Append a
Inflation
operation to the list of operations.Parameters: source ( Optional
[str
]) – The source address that is running the inflation operation.Return type: TransactionBuilder
Returns: This builder instance.
-
append_manage_buy_offer_op
(selling_code, selling_issuer, buying_code, buying_issuer, amount, price, offer_id=0, source=None)[source]¶ Append a
ManageBuyOffer
operation to the list of operations.Parameters: - selling_code (
str
) – The asset code for the asset the offer creator is selling. - selling_issuer (
Optional
[str
]) – The issuing address for the asset the offer creator is selling. - buying_code (
str
) – The asset code for the asset the offer creator is buying. - buying_issuer (
Optional
[str
]) – The issuing address for the asset the offer creator is buying. - amount (
Union
[str
,Decimal
]) – Amount being bought. if set to. Set to 0 if you want to delete an existing offer. - price (
Union
[str
,Decimal
,Price
]) – Price of thing being bought in terms of what you are selling. - offer_id (
int
) – The ID of the offer. 0 for new offer. Set to existing offer ID to update or delete. - source (
Optional
[str
]) – The source address that is managing a buying offer on Stellar’s distributed exchange.
Return type: Returns: This builder instance.
- selling_code (
-
append_manage_data_op
(data_name, data_value, source=None)[source]¶ Append a
ManageData
operation to the list of operations.Parameters: - data_name (
str
) – String up to 64 bytes long. If this is a new Name it will add the given name/value pair to the account. If this Name is already present then the associated value will be modified. - data_value (
Union
[str
,bytes
,None
]) – If not present then the existing Name will be deleted. If present then this value will be set in the DataEntry. Up to 64 bytes long. - source (
Optional
[str
]) – The source account on which data is being managed. operation.
Return type: Returns: This builder instance.
- data_name (
-
append_manage_sell_offer_op
(selling_code, selling_issuer, buying_code, buying_issuer, amount, price, offer_id=0, source=None)[source]¶ Append a
ManageSellOffer
operation to the list of operations.Parameters: - selling_code (
str
) – The asset code for the asset the offer creator is selling. - selling_issuer (
Optional
[str
]) – The issuing address for the asset the offer creator is selling. - buying_code (
str
) – The asset code for the asset the offer creator is buying. - buying_issuer (
Optional
[str
]) – The issuing address for the asset the offer creator is buying. - amount (
Union
[str
,Decimal
]) – Amount of the asset being sold. Set to 0 if you want to delete an existing offer. - price (
Union
[str
,Price
,Decimal
]) – Price of 1 unit of selling in terms of buying. - offer_id (
int
) – The ID of the offer. 0 for new offer. Set to existing offer ID to update or delete. - source (
Optional
[str
]) – The source address that is managing an offer on Stellar’s distributed exchange.
Return type: Returns: This builder instance.
- selling_code (
-
append_operation
(operation)[source]¶ Add an operation to the builder instance
Parameters: operation ( Operation
) – an operationReturn type: TransactionBuilder
Returns: This builder instance.
-
append_path_payment_op
(destination, send_code, send_issuer, send_max, dest_code, dest_issuer, dest_amount, path, source=None)[source]¶ Append a
PathPayment
operation to the list of operations.Parameters: - destination (
str
) – The destination address (Account ID) for the payment. - send_code (
str
) – The asset code for the source asset deducted from the source account. - send_issuer (
Optional
[str
]) – The address of the issuer of the source asset. - send_max (
Union
[str
,Decimal
]) – The maximum amount of send asset to deduct (excluding fees). - dest_code (
str
) – The asset code for the final destination asset sent to the recipient. - dest_issuer (
Optional
[str
]) – Account address that receives the payment. - dest_amount (
Union
[str
,Decimal
]) – The amount of destination asset the destination account receives. - path (
List
[Asset
]) – A list of Asset objects to use as the path. - source (
Optional
[str
]) – The source address of the path payment.
Return type: Returns: This builder instance.
- destination (
-
append_path_payment_strict_receive_op
(destination, send_code, send_issuer, send_max, dest_code, dest_issuer, dest_amount, path, source=None)[source]¶ Append a
PathPaymentStrictReceive
operation to the list of operations.Parameters: - destination (
str
) – The destination address (Account ID) for the payment. - send_code (
str
) – The asset code for the source asset deducted from the source account. - send_issuer (
Optional
[str
]) – The address of the issuer of the source asset. - send_max (
Union
[str
,Decimal
]) – The maximum amount of send asset to deduct (excluding fees). - dest_code (
str
) – The asset code for the final destination asset sent to the recipient. - dest_issuer (
Optional
[str
]) – Account address that receives the payment. - dest_amount (
Union
[str
,Decimal
]) – The amount of destination asset the destination account receives. - path (
List
[Asset
]) – A list of Asset objects to use as the path. - source (
Optional
[str
]) – The source address of the path payment.
Return type: Returns: This builder instance.
- destination (
-
append_path_payment_strict_send_op
(destination, send_code, send_issuer, send_amount, dest_code, dest_issuer, dest_min, path, source=None)[source]¶ Append a
PathPaymentStrictSend
operation to the list of operations.Parameters: - destination (
str
) – The destination address (Account ID) for the payment. - send_code (
str
) – The asset code for the source asset deducted from the source account. - send_issuer (
Optional
[str
]) – The address of the issuer of the source asset. - send_amount (
Union
[str
,Decimal
]) – Amount of send_asset to send. - dest_code (
str
) – The asset code for the final destination asset sent to the recipient. - dest_issuer (
Optional
[str
]) – Account address that receives the payment. - dest_min (
Union
[str
,Decimal
]) – The minimum amount of dest_asset to be received. - path (
List
[Asset
]) – A list of Asset objects to use as the path. - source (
Optional
[str
]) – The source address of the path payment.
Return type: Returns: This builder instance.
- destination (
-
append_payment_op
(destination, amount, asset_code='XLM', asset_issuer=None, source=None)[source]¶ Append a
Payment
operation to the list of operations.Parameters: - destination (
str
) – Account address that receives the payment. - amount (
Union
[str
,Decimal
]) – The amount of the currency to send in the payment. - asset_code (
str
) – The asset code for the asset to send. - asset_issuer (
Optional
[str
]) – The address of the issuer of the asset. - source (
Optional
[str
]) – The source address of the payment.
Return type: Returns: This builder instance.
- destination (
-
append_pre_auth_tx_signer
(pre_auth_tx_hash, weight, source=None)[source]¶ Add a PreAuthTx signer to an account.
Add a PreAuthTx signer to an account via a
SetOptions <stellar_sdk.operation.SetOptions
operation. This is a helper function forappend_set_options_op()
.Parameters: - pre_auth_tx_hash (
bytes
) – The address of the new preAuthTx signer - obtained by callinghash
on theTransactionEnvelope
, a 32 byte hash or hex encoded string. - weight (
int
) – The weight of the new signer. - source (
Optional
[str
]) – The source account that is adding a signer to its list of signers.
Return type: Returns: This builder instance.
- pre_auth_tx_hash (
-
append_set_options_op
(inflation_dest=None, clear_flags=None, set_flags=None, master_weight=None, low_threshold=None, med_threshold=None, high_threshold=None, home_domain=None, signer=None, source=None)[source]¶ Append a
SetOptions
operation to the list of operations.Parameters: - inflation_dest (
Optional
[str
]) – Account of the inflation destination. - clear_flags (
Union
[int
,Flag
,None
]) –Indicates which flags to clear. For details about the flags, please refer to the accounts doc. The bit mask integer subtracts from the existing flags of the account. This allows for setting specific bits without knowledge of existing flags, you can also use
stellar_sdk.operation.set_options.Flag
- AUTHORIZATION_REQUIRED = 1 - AUTHORIZATION_REVOCABLE = 2 - AUTHORIZATION_IMMUTABLE = 4 - set_flags (
Union
[int
,Flag
,None
]) – Indicates which flags to set. For details about the flags, please refer to the accounts doc. The bit mask integer adds onto the existing flags of the account. This allows for setting specific bits without knowledge of existing flags, you can also usestellar_sdk.operation.set_options.Flag
- AUTHORIZATION_REQUIRED = 1 - AUTHORIZATION_REVOCABLE = 2 - AUTHORIZATION_IMMUTABLE = 4 - master_weight (
Optional
[int
]) – A number from 0-255 (inclusive) representing the weight of the master key. If the weight of the master key is updated to 0, it is effectively disabled. - low_threshold (
Optional
[int
]) –A number from 0-255 (inclusive) representing the threshold this account sets on all operations it performs that have a low threshold.
- med_threshold (
Optional
[int
]) –A number from 0-255 (inclusive) representing the threshold this account sets on all operations it performs that have a medium threshold.
- high_threshold (
Optional
[int
]) –A number from 0-255 (inclusive) representing the threshold this account sets on all operations it performs that have a high threshold.
- home_domain (
Optional
[str
]) –sets the home domain used for reverse federation lookup.
- signer (
Optional
[Signer
]) – Add, update, or remove a signer from the account. - source (
Optional
[str
]) – The source account (defaults to transaction source).
Return type: Returns: This builder instance.
- inflation_dest (
-
build
()[source]¶ This will build the transaction envelope. It will also increment the source account’s sequence number by 1.
Return type: TransactionEnvelope
Returns: The transaction envelope.
-
static
build_fee_bump_transaction
(fee_source, base_fee, inner_transaction_envelope, network_passphrase='Test SDF Network ; September 2015')[source]¶ Create a
FeeBumpTransactionEnvelope
object.See CAP-0015 for more information.
Parameters: - fee_source (
Union
[Keypair
,str
]) – The account paying for the transaction. - base_fee (
int
) – The max fee willing to pay per operation in inner transaction (in stroops). - inner_transaction_envelope (
TransactionEnvelope
) – The TransactionEnvelope to be bumped by the fee bump transaction. - network_passphrase (
str
) – The network to connect to for verifying and retrieving additional attributes from.
Return type: Returns: a
TransactionBuilder
via the XDR object.- fee_source (
-
static
from_xdr
(xdr, network_passphrase)[source]¶ Create a
TransactionBuilder
orFeeBumpTransactionEnvelope
via an XDR object.In addition, if xdr is not of
TransactionEnvelope
, it sets the fields of this builder (the transaction envelope, transaction, operations, source, etc.) to all of the fields in the provided XDR transaction envelope, but the signature will not be added to it.Parameters: Return type: Returns: a
TransactionBuilder
orFeeBumpTransactionEnvelope
via the XDR object.
-
set_timeout
(timeout)[source]¶ Set timeout for the transaction, actually set a TimeBounds.
Parameters: timeout ( int
) – timeout in second.Return type: TransactionBuilder
Returns: This builder instance. Raises: ValueError
: if time_bound is already set.
- source_account (
Helpers¶
-
stellar_sdk.helpers.
parse_transaction_envelope_from_xdr
(xdr, network_passphrase)[source]¶ - When you are not sure whether your XDR belongs to
TransactionEnvelope
orFeeBumpTransactionEnvelope
, you can use this helper function.
Parameters: Raises: ValueError
- XDR is neitherTransactionEnvelope
norFeeBumpTransactionEnvelope
Return type:
Stellar Ecosystem Proposals¶
SEP 0001: stellar.toml¶
-
stellar_sdk.sep.stellar_toml.
fetch_stellar_toml
(domain, client=None, use_http=False)[source]¶ Retrieve the stellar.toml file from a given domain.
Retrieve the stellar.toml file for information about interacting with Stellar’s federation protocol for a given Stellar Anchor (specified by a domain).
Parameters: - domain (
str
) – The domain the .toml file is hosted at. - use_http (
bool
) – Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you always use HTTPS. - client (
Union
[BaseAsyncClient
,BaseSyncClient
,None
]) – Http Client used to send the request.
Return type: Returns: The stellar.toml file as a an object via
toml.loads()
.Raises: StellarTomlNotFoundError
: if the Stellar toml file could not not be found.- domain (
SEP 0002: Federation protocol¶
-
stellar_sdk.sep.federation.
resolve_stellar_address
(stellar_address, client=None, federation_url=None, use_http=False)[source]¶ Get the federation record if the user was found for a given Stellar address.
Parameters: - stellar_address (
str
) – address Stellar address (ex. bob*stellar.org). - client (
Union
[BaseAsyncClient
,BaseSyncClient
,None
]) – Http Client used to send the request. - federation_url (
Optional
[str
]) – The federation server URL (ex. https://stellar.org/federation), if you don’t set this value, we will try to get it fromstellar_address
. - use_http (
bool
) – Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you always use HTTPS.
Return type: Union
[Coroutine
[Any
,Any
,FederationRecord
],FederationRecord
]Returns: Federation record.
- stellar_address (
-
stellar_sdk.sep.federation.
resolve_account_id
(account_id, domain=None, federation_url=None, client=None, use_http=False)[source]¶ Given an account ID, get their federation record if the user was found
Parameters: - account_id (
str
) – Account ID (ex. GBYNR2QJXLBCBTRN44MRORCMI4YO7FZPFBCNOKTOBCAAFC7KC3LNPRYS) - domain (
Optional
[str
]) – Getfederation_url
from the domain, you don’t need to set this value iffederation_url
is set. - federation_url (
Optional
[str
]) – The federation server URL (ex. https://stellar.org/federation). - client (
Union
[BaseAsyncClient
,BaseSyncClient
,None
]) – Http Client used to send the request. - use_http (
bool
) – Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you always use HTTPS.
Return type: Union
[Coroutine
[Any
,Any
,FederationRecord
],FederationRecord
]Returns: Federation record.
- account_id (
SEP 0005: Key Derivation Methods for Stellar Accounts¶
-
class
stellar_sdk.sep.mnemonic.
StellarMnemonic
(language=<Language.ENGLISH: 'english'>)[source]¶ Please use
Keypair.generate_mnemonic_phrase()
andKeypair.from_mnemonic_phrase()
-
class
stellar_sdk.sep.mnemonic.
Language
[source]¶ The type of language supported by the mnemonic.
-
CHINESE_SIMPLIFIED
= 'chinese_simplified'¶
-
CHINESE_TRADITIONAL
= 'chinese_traditional'¶
-
ENGLISH
= 'english'¶
-
FRENCH
= 'french'¶
-
ITALIAN
= 'italian'¶
-
JAPANESE
= 'japanese'¶
-
KOREAN
= 'korean'¶
-
SPANISH
= 'spanish'¶
-
SEP 0010: Stellar Web Authentication¶
-
stellar_sdk.sep.stellar_web_authentication.
build_challenge_transaction
(server_secret, client_account_id, anchor_name, network_passphrase, timeout=900)[source]¶ Returns a valid SEP0010 challenge transaction which you can use for Stellar Web Authentication.
Parameters: - server_secret (
str
) – secret key for server’s signing account. - client_account_id (
str
) – The stellar account that the wallet wishes to authenticate with the server. - anchor_name (
str
) – Anchor’s name to be used in the manage_data key. - network_passphrase (
str
) – The network to connect to for verifying and retrieving additional attributes from. (ex. ‘Public Global Stellar Network ; September 2015’) - timeout (
int
) – Challenge duration in seconds (default to 15 minutes).
Return type: Returns: A base64 encoded string of the raw TransactionEnvelope xdr struct for the transaction.
- server_secret (
-
stellar_sdk.sep.stellar_web_authentication.
read_challenge_transaction
(challenge_transaction, server_account_id, network_passphrase)[source]¶ Reads a SEP 10 challenge transaction and returns the decoded transaction envelope and client account ID contained within.
It also verifies that transaction is signed by the server.
It does not verify that the transaction has been signed by the client or that any signatures other than the servers on the transaction are valid. Use one of the following functions to completely verify the transaction:
Parameters: - challenge_transaction (
str
) – SEP0010 transaction challenge transaction in base64. - server_account_id (
str
) – public key for server’s account. - network_passphrase (
str
) – The network to connect to for verifying and retrieving additional attributes from. (ex. ‘Public Global Stellar Network ; September 2015’)
Raises: InvalidSep10ChallengeError
- if the validation fails, the exception will be thrown.Return type: - challenge_transaction (
-
stellar_sdk.sep.stellar_web_authentication.
verify_challenge_transaction_threshold
(challenge_transaction, server_account_id, network_passphrase, threshold, signers)[source]¶ Verifies that for a SEP 10 challenge transaction all signatures on the transaction are accounted for and that the signatures meet a threshold on an account. A transaction is verified if it is signed by the server account, and all other signatures match a signer that has been provided as an argument, and those signatures meet a threshold on the account.
Parameters: - challenge_transaction (
str
) – SEP0010 transaction challenge transaction in base64. - server_account_id (
str
) – public key for server’s account. - network_passphrase (
str
) – The network to connect to for verifying and retrieving additional attributes from. (ex. ‘Public Global Stellar Network ; September 2015’) - threshold (
int
) – The medThreshold on the client account. - signers (
List
[Ed25519PublicKeySigner
]) – The signers of client account.
Raises: InvalidSep10ChallengeError
: - The transaction is invalid according tostellar_sdk.sep.stellar_web_authentication.read_challenge_transaction()
. - One or more signatures in the transaction are not identifiable as the server account or one of the signers provided in the arguments. - The signatures are all valid but do not meet the threshold.Return type: List
[Ed25519PublicKeySigner
]- challenge_transaction (
-
stellar_sdk.sep.stellar_web_authentication.
verify_challenge_transaction_signed_by_client_master_key
(challenge_transaction, server_account_id, network_passphrase)[source]¶ An alias for
stellar_sdk.sep.stellar_web_authentication.verify_challenge_transaction()
.Parameters: - challenge_transaction (
str
) – SEP0010 transaction challenge transaction in base64. - server_account_id (
str
) – public key for server’s account. - network_passphrase (
str
) – The network to connect to for verifying and retrieving additional attributes from. (ex. ‘Public Global Stellar Network ; September 2015’)
Raises: InvalidSep10ChallengeError
- if the validation fails, the exception will be thrown.Return type: None
- challenge_transaction (
-
stellar_sdk.sep.stellar_web_authentication.
verify_challenge_transaction_signers
(challenge_transaction, server_account_id, network_passphrase, signers)[source]¶ Verifies that for a SEP 10 challenge transaction all signatures on the transaction are accounted for. A transaction is verified if it is signed by the server account, and all other signatures match a signer that has been provided as an argument. Additional signers can be provided that do not have a signature, but all signatures must be matched to a signer for verification to succeed. If verification succeeds a list of signers that were found is returned, excluding the server account ID.
Parameters: - challenge_transaction (
str
) – SEP0010 transaction challenge transaction in base64. - server_account_id (
str
) – public key for server’s account. - network_passphrase (
str
) – The network to connect to for verifying and retrieving additional attributes from. (ex. ‘Public Global Stellar Network ; September 2015’) - signers (
List
[Ed25519PublicKeySigner
]) – The signers of client account.
Raises: InvalidSep10ChallengeError
: - The transaction is invalid according tostellar_sdk.sep.stellar_web_authentication.read_challenge_transaction()
. - One or more signatures in the transaction are not identifiable as the server account or one of the signers provided in the arguments.Return type: List
[Ed25519PublicKeySigner
]- challenge_transaction (
-
stellar_sdk.sep.stellar_web_authentication.
verify_challenge_transaction
(challenge_transaction, server_account_id, network_passphrase)[source]¶ Verifies if a transaction is a valid SEP0010 v1.2 challenge transaction, if the validation fails, an exception will be thrown.
This function performs the following checks:
- verify that transaction sequenceNumber is equal to zero;
- verify that transaction source account is equal to the server’s signing key;
- verify that transaction has time bounds set, and that current time is between the minimum and maximum bounds;
- verify that transaction contains a single Manage Data operation and it’s source account is not null;
- verify that transaction envelope has a correct signature by server’s signing key;
- verify that transaction envelope has a correct signature by the operation’s source account;
Parameters: - challenge_transaction (
str
) – SEP0010 transaction challenge transaction in base64. - server_account_id (
str
) – public key for server’s account. - network_passphrase (
str
) – The network to connect to for verifying and retrieving additional attributes from. (ex. ‘Public Global Stellar Network ; September 2015’)
Raises: InvalidSep10ChallengeError
- if the validation fails, the exception will be thrown.Return type: None
Exceptions¶
-
class
stellar_sdk.sep.exceptions.
StellarTomlNotFoundError
[source]¶ If the SEP 0010 toml file not found, the exception will be thrown.
-
class
stellar_sdk.sep.exceptions.
InvalidFederationAddress
[source]¶ If the federation address is invalid, the exception will be thrown.
-
class
stellar_sdk.sep.exceptions.
FederationServerNotFoundError
[source]¶ If the federation address is invalid, the exception will be thrown.
-
class
stellar_sdk.sep.exceptions.
BadFederationResponseError
(response)[source]¶ If the federation address is invalid, the exception will be thrown.
Parameters: response – client response
-
class
stellar_sdk.sep.exceptions.
InvalidSep10ChallengeError
[source]¶ If the SEP 0010 validation fails, the exception will be thrown.
-
class
stellar_sdk.sep.exceptions.
AccountRequiresMemoError
(message, account_id, operation_index)[source]¶ AccountRequiresMemoError is raised when a transaction is trying to submit an operation to an account which requires a memo.
This error contains two attributes to help you identify the account requiring the memo and the operation where the account is the destination.
See SEP-0029 for more information.
Links¶
- Document: https://stellar-sdk.readthedocs.io
- Code: https://github.com/StellarCN/py-stellar-base/tree/v2
- Docker: https://hub.docker.com/r/overcat/py-stellar-base
- Examples: https://github.com/StellarCN/py-stellar-base/blob/v2/examples
- Issue tracker: https://github.com/StellarCN/py-stellar-base/issues
- License: Apache License 2.0
- Releases: https://pypi.org/project/stellar-sdk/
Thanks¶
This document is based on Stellar JavaScript SDK documentation. Thank you to all the people who have already contributed to Stellar ecosystem!