def main():
    from stellar_sdk.server import Server

    def load_last_paging_token():
        # Get the last paging token from a local database or file
        return "now"

    def save_paging_token(paging_token):
        # In most cases, you should save this to a local database or file so that
        # you can load it next time you stream new payments.
        pass

    # server = Server("https://horizon-testnet.stellar.org")
    server = Server("https://horizon.stellar.org")
    account_id = "GDTIZ3P6L33OZE3B437ZPX5KAS7APTGUMUTS34TXX6Z5BHD7IAABZDJZ"

    # Create an API call to query payments involving the account.
    payments = server.payments().for_account(account_id)

    # If some payments have already been handled, start the results from the
    # last seen payment. (See below in `handle_payment` where it gets saved.)
    last_token = load_last_paging_token()
    # if last_token:
    #     payments.cursor(last_token)

    # `stream` will send each recorded payment, one by one, then keep the
    # connection open and continue to send you new payments as they occur.
    #  基于  EventSource(http长连接) , 而不是Websocket
    for payment in payments.stream():
        # Record the paging token so we can start from here next time.
        save_paging_token(payment["paging_token"])
        from pprint import pprint
        pprint(payment)

        # We only process `payment`, ignore `create_account` and `account_merge`.
        if payment["type"] != "payment":
            continue

        # The payments stream includes both sent and received payments. We
        # only want to process received payments here.
        if payment['to'] != account_id:
            continue

        # In Stellar’s API, Lumens are referred to as the “native” type. Other
        # asset types have more detailed information.
        if payment["asset_type"] == "native":
            asset = "Lumens"
        else:
            asset = f"{payment['asset_code']}:{payment['asset_issuer']}"
        print(f"{payment['amount']} {asset} from {payment['from']}")

        #获取更多信息  memo_type  和 memo
        ret = server.transactions().transaction(
            payment['transaction_hash']).call()
        from pprint import pprint
        pprint(ret)

    pass
def chargeUser(uid, amount):
    """
    Charge the user for a transaction.
    """
    def load_last_paging_token():
        # Get the last paging token from a local database or file
        return "now"

    def save_paging_token(paging_token):
        # In most cases, you should save this to a local database or file so that
        # you can load it next time you stream new payments.
        pass

    server = Server("https://horizon-testnet.stellar.org")
    account_id = "GA4QPSGBHK7RAJZBBEDCIKFPSYLG3O2UTBT2I56RN4B5KIQF2GFZKSMF"

    # Create an API call to query payments involving the account.
    payments = server.payments().for_account(account_id)

    # If some payments have already been handled, start the results from the
    # last seen payment. (See below in `handle_payment` where it gets saved.)
    last_token = load_last_paging_token()
    if last_token:
        payments.cursor(last_token)

    # `stream` will send each recorded payment, one by one, then keep the
    # connection open and continue to send you new payments as they occur.
    for payment in payments.stream():
        # Record the paging token so we can start from here next time.
        save_paging_token(payment["paging_token"])

        # We only process `payment`, ignore `create_account` and `account_merge`.
        if payment["type"] != "payment":
            continue

        # The payments stream includes both sent and received payments. We
        # only want to process received payments here.
        if payment['to'] != account_id:
            continue

        # In Stellar’s API, Lumens are referred to as the “native” type. Other
        # asset types have more detailed information.
        if payment["asset_type"] == "native":
            asset = "Lumens"
        else:
            asset = f"{payment['asset_code']}:{payment['asset_issuer']}"
        print(f"{payment['amount']} {asset} from {payment['from']}")

        return None
def main():
    from stellar_sdk.server import Server

    server = Server("https://horizon-testnet.stellar.org")
    public_key = "GDTIZ3P6L33OZE3B437ZPX5KAS7APTGUMUTS34TXX6Z5BHD7IAABZDJZ"
    account = server.accounts().account_id(public_key).call()

    pprint(account)

    for balance in account['balances']:
        print(f"Type: {balance['asset_type']}, Balance: {balance['balance']}")



    pass
Exemple #4
0
 def test_load_acount_sync(self):
     account_id = "GDV6FVHPY4JH7EEBSJYPQQYZA3OC6TKTM2TAXRHWT4EEL7BJ2BTDQT5D"
     horizon_url = "https://horizon.stellar.org"
     with Server(horizon_url) as server:
         account = server.load_account(account_id)
         assert account.account_id == account_id
         assert isinstance(account.sequence, int)
Exemple #5
0
 def test_submit_transaction_with_xdr(self):
     xdr = "AAAAAHI7fpgo+b7tgpiFyYWimjV7L7IOYLwmQS7k7F8SronXAAAAZAE+QT4AAAAJAAAAAQAAAAAAAAAAAAAAAF1MG8cAAAAAAAAAAQAAAAAAAAAAAAAAAOvi1O/HEn+QgZJw+EMZBtwvTVNmpgvE9p8IRfwp0GY4AAAAAAExLQAAAAAAAAAAARKuidcAAABAJVc1ASGp35hUquGNbzzSqWPoTG0zgc89zc4p+19QkgbPqsdyEfHs7+ng9VJA49YneEXRa6Fv7pfKpEigb3VTCg=="
     horizon_url = "https://horizon.stellar.org"
     client = RequestsClient()
     with Server(horizon_url, client) as server:
         resp = server.submit_transaction(xdr, True)
         assert resp["envelope_xdr"] == xdr
    async def _for_account(self, account: str):  # pragma: no cover
        """
        Stream transactions for the server Stellar address.
        """
        async with Server(settings.HORIZON_URI,
                          client=AiohttpClient()) as server:
            try:
                # Ensure the distribution account actually exists
                await server.load_account(account)
            except NotFoundError:
                # This exception will crash the process, but the anchor needs
                # to provide valid accounts to watch.
                raise RuntimeError(
                    "Stellar distribution account does not exist in horizon")
            last_completed_transaction = (Transaction.objects.filter(
                Q(kind=Transaction.KIND.withdrawal)
                | Q(kind=Transaction.KIND.send),
                receiving_anchor_account=account,
                status=Transaction.STATUS.completed,
            ).order_by("-completed_at").first())

            cursor = "now"
            if last_completed_transaction:
                cursor = last_completed_transaction.paging_token

            endpoint = server.transactions().for_account(account).cursor(
                cursor)
            async for response in endpoint.stream():
                self.process_response(response, account)
Exemple #7
0
 async def test_submit_transaction_with_te(self):
     xdr = "AAAAAHI7fpgo+b7tgpiFyYWimjV7L7IOYLwmQS7k7F8SronXAAAAZAE+QT4AAAAJAAAAAQAAAAAAAAAAAAAAAF1MG8cAAAAAAAAAAQAAAAAAAAAAAAAAAOvi1O/HEn+QgZJw+EMZBtwvTVNmpgvE9p8IRfwp0GY4AAAAAAExLQAAAAAAAAAAARKuidcAAABAJVc1ASGp35hUquGNbzzSqWPoTG0zgc89zc4p+19QkgbPqsdyEfHs7+ng9VJA49YneEXRa6Fv7pfKpEigb3VTCg=="
     te = TransactionEnvelope.from_xdr(xdr, Network.PUBLIC_NETWORK_PASSPHRASE)
     horizon_url = "https://horizon.stellar.org"
     client = AiohttpClient()
     async with Server(horizon_url, client) as server:
         resp = await server.submit_transaction(te, True)
         assert resp["envelope_xdr"] == xdr
Exemple #8
0
 async def test_load_acount_async(self):
     account_id = "GDV6FVHPY4JH7EEBSJYPQQYZA3OC6TKTM2TAXRHWT4EEL7BJ2BTDQT5D"
     horizon_url = "https://horizon.stellar.org"
     client = AiohttpClient()
     async with Server(horizon_url, client) as server:
         account = await server.load_account(account_id)
         assert account.account_id == account_id
         assert isinstance(account.sequence, int)
         assert account.thresholds == Thresholds(1, 2, 3)
Exemple #9
0
 def test_load_acount_muxed_account_sync(self):
     account_id = MuxedAccount(
         "GDV6FVHPY4JH7EEBSJYPQQYZA3OC6TKTM2TAXRHWT4EEL7BJ2BTDQT5D", 1234
     )
     horizon_url = "https://horizon.stellar.org"
     with Server(horizon_url) as server:
         account = server.load_account(account_id)
         assert account.account_id == account_id
         assert isinstance(account.sequence, int)
         assert account.thresholds == Thresholds(1, 2, 3)
Exemple #10
0
 def test_bad_type_client_raise(self):
     horizon_url = "https://h.fchain.io"
     client = "BAD TYPE"
     with pytest.raises(
             TypeError,
             match="This `client` class should be an instance "
             "of `stellar_sdk.client.base_async_client.BaseAsyncClient` "
             "or `stellar_sdk.client.base_sync_client.BaseSyncClient`.",
     ):
         Server(horizon_url, client)
Exemple #11
0
 async def test_load_acount_muxed_account_str_async(self):
     account_id = (
         "MAAAAAAAAAAAJUXL4LKO7RYSP6IIDETQ7BBRSBW4F5GVGZVGBPCPNHYIIX6CTUDGHDUWO"
     )
     horizon_url = "https://horizon.stellar.org"
     client = AiohttpClient()
     async with Server(horizon_url, client) as server:
         account = await server.load_account(account_id)
         assert account.account_id == MuxedAccount.from_account(account_id)
         assert isinstance(account.sequence, int)
         assert account.thresholds == Thresholds(1, 2, 3)
def rewardUser(uid, amount):
    """
    Reward the user by increasing his karma points via blockchain
    """
    server = Server("https://horizon-testnet.stellar.org")
    source_key = Keypair.from_secret(
        "SA6HHDJ5KZKYFZVOOGHENIPVKV2HGKICN4RYQ2UZNZHZP7ZIYSQIQDCI")
    destination_id = "GA4QPSGBHK7RAJZBBEDCIKFPSYLG3O2UTBT2I56RN4B5KIQF2GFZKSMF"

    # First, check to make sure that the destination account exists.
    # You could skip this, but if the account does not exist, you will be charged
    # the transaction fee when the transaction fails.
    try:
        server.load_account(destination_id)
    except NotFoundError:
        # If the account is not found, surface an error message for logging.
        raise Exception("The destination account does not exist!")

    # If there was no error, load up-to-date information on your account.
    source_account = server.load_account(source_key.public_key)

    # Let's fetch base_fee from network
    base_fee = server.fetch_base_fee()

    # Start building the transaction.
    transaction = (
        TransactionBuilder(
            source_account=source_account,
            network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
            base_fee=base_fee,
        )
        # Because Stellar allows transaction in many currencies, you must specify the asset type.
        # Here we are sending Lumens.
        .append_payment_op(destination=destination_id,
                           amount="10",
                           asset_code="XLM")
        # A memo allows you to add your own metadata to a transaction. It's
        # optional and does not affect how Stellar treats the transaction.
        .add_text_memo("Test Transaction")
        # Wait a maximum of three minutes for the transaction
        .set_timeout(10).build())

    # Sign the transaction to prove you are actually the person sending it.
    transaction.sign(source_key)

    try:
        # And finally, send it off to Stellar!
        response = server.submit_transaction(transaction)
        print(f"Response: {response}")
    except (BadRequestError, BadResponseError) as err:
        print(f"Something went wrong!\n{err}")

    return None
Exemple #13
0
    async def _for_account(self, account: str):  # pragma: no cover
        """
        Stream transactions for the server Stellar address.
        """
        async with Server(settings.HORIZON_URI,
                          client=AiohttpClient()) as server:
            try:
                # Ensure the distribution account actually exists
                await server.load_account(account)
            except NotFoundError:
                # This exception will crash the process, but the anchor needs
                # to provide valid accounts to watch.
                raise RuntimeError(
                    "Stellar distribution account does not exist in horizon")

            endpoint = server.transactions().for_account(account).cursor("now")
            async for response in endpoint.stream():
                self.process_response(response)
Exemple #14
0
class StellarConnector(Connector):
    """ The StellarConnector class """
    settings = {}
    params = {
        'addresses': {
            'key_type': 'list',
            'default': None,
            'mandatory': True,
        },
        'url': {
            'key_type': 'string',
            'default': 'https://horizon.stellar.org/',
            'mandatory': False,
        },
    }

    def __init__(self):
        self.exchange = 'stellar'
        self.params.update(super().params)  # merge with the global params
        self.settings = utils.gather_environ(self.params)
        self.server = Server(horizon_url=self.settings['url'])
        super().__init__()

    def retrieve_accounts(self):
        """ Connects to the Stellar network and retrieves the account information """
        log.info('Retrieving accounts')
        for account in self.settings['addresses']:
            balances = self.server.accounts().account_id(account).call().get('balances')
            if isinstance(balances, list):
                for balance in balances:
                    if balance.get('asset_code'):
                        currency = balance.get('asset_code')
                    elif balance.get('asset_type') == 'native':
                        currency = 'XLM'
                    else:
                        currency = balance.get('asset_type')
                    if currency not in self._accounts:
                        self._accounts.update({currency: {}})
                    self._accounts[currency].update({
                        f'{account}': float(balance.get('balance'))
                    })

        log.log(5, f'Found the following accounts: {self._accounts}')
Exemple #15
0
def server():
    return Server(horizon_url=horizon_url())
Exemple #16
0
 def test_endpoint(self):
     horizon_url = "https://horizon.stellar.org"
     client = RequestsClient()
     with Server(horizon_url, client) as server:
         assert server.accounts() == AccountsCallBuilder(
             horizon_url, client)
         assert server.assets() == AssetsCallBuilder(horizon_url, client)
         assert server.effects() == EffectsCallBuilder(horizon_url, client)
         assert server.fee_stats() == FeeStatsCallBuilder(
             horizon_url, client)
         assert server.ledgers() == LedgersCallBuilder(horizon_url, client)
         assert server.offers(
             "GDV6FVHPY4JH7EEBSJYPQQYZA3OC6TKTM2TAXRHWT4EEL7BJ2BTDQT5D"
         ) == OffersCallBuilder(
             horizon_url,
             client,
             "GDV6FVHPY4JH7EEBSJYPQQYZA3OC6TKTM2TAXRHWT4EEL7BJ2BTDQT5D",
         )
         assert server.operations() == OperationsCallBuilder(
             horizon_url, client)
         buying = Asset.native()
         selling = Asset(
             "MOE",
             "GDV6FVHPY4JH7EEBSJYPQQYZA3OC6TKTM2TAXRHWT4EEL7BJ2BTDQT5D")
         assert server.orderbook(buying, selling) == OrderbookCallBuilder(
             horizon_url, client, buying, selling)
         source_account = "GABUVMDURJFF477AEDAXOG5TL7JBHGDAKJQLH5K6FB5QONMLEV52C6IO"
         destination_account = (
             "GDV6FVHPY4JH7EEBSJYPQQYZA3OC6TKTM2TAXRHWT4EEL7BJ2BTDQT5D")
         destination_asset = Asset.native()
         destination_amount = "100.0"
         assert server.paths(
             source_account,
             destination_account,
             destination_asset,
             destination_amount,
         ) == PathsCallBuilder(
             horizon_url,
             client,
             source_account,
             destination_account,
             destination_asset,
             destination_amount,
         )
         assert server.payments() == PaymentsCallBuilder(
             horizon_url, client)
         assert server.root() == RootCallBuilder(horizon_url, client)
         base = Asset.native()
         counter = Asset(
             "MOE",
             "GDV6FVHPY4JH7EEBSJYPQQYZA3OC6TKTM2TAXRHWT4EEL7BJ2BTDQT5D")
         resolution = 3600000
         start_time = 1565272000000
         end_time = 1565278000000
         offset = 3600000
         assert server.trade_aggregations(
             base, counter, resolution, start_time, end_time,
             offset) == TradeAggregationsCallBuilder(
                 horizon_url,
                 client,
                 base,
                 counter,
                 resolution,
                 start_time,
                 end_time,
                 offset,
             )
         assert server.trades() == TradesCallBuilder(horizon_url, client)
         assert server.transactions() == TransactionsCallBuilder(
             horizon_url, client)
Exemple #17
0
 async def test_fetch_base_fee_async(self):
     horizon_url = "https://horizon.stellar.org"
     client = AiohttpClient()
     async with Server(horizon_url, client) as server:
         base_fee = await server.fetch_base_fee()
         assert isinstance(base_fee, int)
Exemple #18
0
    def test_endpoint(self):
        horizon_url = "https://horizon.stellar.org"
        client = RequestsClient()
        with Server(horizon_url, client) as server:
            assert server.accounts() == AccountsCallBuilder(
                horizon_url, client)
            assert server.assets() == AssetsCallBuilder(horizon_url, client)
            assert server.claimable_balances() == ClaimableBalancesCallBuilder(
                horizon_url, client)
            assert server.data(
                "GDV6FVHPY4JH7EEBSJYPQQYZA3OC6TKTM2TAXRHWT4EEL7BJ2BTDQT5D",
                "hello") == DataCallBuilder(
                    horizon_url,
                    client,
                    "GDV6FVHPY4JH7EEBSJYPQQYZA3OC6TKTM2TAXRHWT4EEL7BJ2BTDQT5D",
                    "hello",
                )
            assert server.effects() == EffectsCallBuilder(horizon_url, client)
            assert server.fee_stats() == FeeStatsCallBuilder(
                horizon_url, client)
            assert server.ledgers() == LedgersCallBuilder(horizon_url, client)
            assert server.offers() == OffersCallBuilder(horizon_url, client)
            assert server.operations() == OperationsCallBuilder(
                horizon_url, client)
            buying = Asset.native()
            selling = Asset(
                "MOE",
                "GDV6FVHPY4JH7EEBSJYPQQYZA3OC6TKTM2TAXRHWT4EEL7BJ2BTDQT5D")
            assert server.orderbook(buying, selling) == OrderbookCallBuilder(
                horizon_url, client, buying, selling)
            source = "GAYSHLG75RPSMXWJ5KX7O7STE6RSZTD6NE4CTWAXFZYYVYIFRUVJIBJH"
            destination_asset = Asset(
                "EUR",
                "GDSBCQO34HWPGUGQSP3QBFEXVTSR2PW46UIGTHVWGWJGQKH3AFNHXHXN")
            destination_amount = "20.0"
            assert server.strict_receive_paths(
                source, destination_asset,
                destination_amount) == StrictReceivePathsCallBuilder(
                    horizon_url, client, source, destination_asset,
                    destination_amount)

            source_asset = Asset(
                "EUR",
                "GDSBCQO34HWPGUGQSP3QBFEXVTSR2PW46UIGTHVWGWJGQKH3AFNHXHXN")
            source_amount = "10.25"
            destination = "GARSFJNXJIHO6ULUBK3DBYKVSIZE7SC72S5DYBCHU7DKL22UXKVD7MXP"
            assert server.strict_send_paths(
                source_asset, source_amount,
                destination) == StrictSendPathsCallBuilder(
                    horizon_url, client, source_asset, source_amount,
                    destination)
            assert server.payments() == PaymentsCallBuilder(
                horizon_url, client)
            assert server.root() == RootCallBuilder(horizon_url, client)
            base = Asset.native()
            counter = Asset(
                "MOE",
                "GDV6FVHPY4JH7EEBSJYPQQYZA3OC6TKTM2TAXRHWT4EEL7BJ2BTDQT5D")
            resolution = 3600000
            start_time = 1565272000000
            end_time = 1565278000000
            offset = 3600000
            assert server.trade_aggregations(
                base, counter, resolution, start_time, end_time,
                offset) == TradeAggregationsCallBuilder(
                    horizon_url,
                    client,
                    base,
                    counter,
                    resolution,
                    start_time,
                    end_time,
                    offset,
                )
            assert server.trades() == TradesCallBuilder(horizon_url, client)
            assert server.transactions() == TransactionsCallBuilder(
                horizon_url, client)
Exemple #19
0
from stellar_sdk.server import Server
import json

fileName = 'accounts.json'
with open(fileName) as r:
    accounts = json.load(r)

server = Server("https://horizon-testnet.stellar.org")

for user in accounts:
    account = server.accounts().account_id(user['publicKey']).call()
    for balance in account['balances']:
        print(f"User: {user['name']}, ID: {account['id']}")
        print(f"Type: {balance['asset_type']}, Balance: {balance['balance']}")
        print()
Exemple #20
0
 def test_fetch_base_fee_sync(self):
     horizon_url = "https://horizon.stellar.org"
     with Server(horizon_url) as server:
         base_fee = server.fetch_base_fee()
         assert base_fee == 100
def main():

    # server = Server("https://horizon-testnet.stellar.org")
    server = Server("https://horizon.stellar.org")
    # source_key = Keypair.from_secret("SARJMVBEUC32ITKBIBYRQZUFEWKYHMR7PET5NDZH6KPREY3CPCUQSBJU")  #test1
    # destination_id = "GBMHN7DQ7MQTFPUPAYJR6HUGI2WX55LDTJ4AJNBQPIWMHNHSN34A2ENS"  #test2

    # test2
    # Secret: SARJMVBEUC32ITKBIBYRQZUFEWKYHMR7PET5NDZH6KPREY3CPCUQSBJU
    # Public Key: GDTIZ3P6L33OZE3B437ZPX5KAS7APTGUMUTS34TXX6Z5BHD7IAABZDJZ

    source_key = Keypair.from_secret(
        "SARJMVBEUC32ITKBIBYRQZUFEWKYHMR7PET5NDZH6KPREY3CPCUQSBJU")
    # destination_id = "GC2QRLQCNCIK3FEIPEO7KP64PBOTFREGNCLMUG64QYOQFVQVARQCNPTV"
    destination_id = "GDKSN4MKI3VCX4ZN6P6WVQR64TGKPOHPKVBCO5ERJABMHI7GJHNAF6PX"

    #如果目的账户不存在, 则使用  append_create_account_op
    #如果目的账号存在, 则使用 append_payment_op
    # First, check to make sure that the destination account exists.
    # You could skip this, but if the account does not exist, you will be charged
    # the transaction fee when the transaction fails.

    is_acc_exits = False
    try:
        server.load_account(destination_id)
        is_acc_exits = True
    except NotFoundError:
        # If the account is not found, surface an error message for logging.
        # raise Exception("The destination account does not exist!")
        print(f"{destination_id} not found, will create it")
        is_acc_exits = False

    # If there was no error, load up-to-date information on your account.
    source_account = server.load_account(source_key.public_key)

    # Let's fetch base_fee from network
    base_fee = server.fetch_base_fee()

    # Start building the transaction.

    txbuilder = TransactionBuilder(
        source_account=source_account,
        # network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
        network_passphrase=Network.PUBLIC_NETWORK_PASSPHRASE,
        base_fee=base_fee,
    )

    if is_acc_exits:
        txbuilder.append_payment_op(destination=destination_id,
                                    amount="1.6666",
                                    asset_code="XLM")
    else:
        txbuilder.append_create_account_op(destination=destination_id,
                                           starting_balance="1.001")

    txbuilder.add_text_memo("101108")\
            .set_timeout(1000)

    transaction = txbuilder.build()

    # transaction = (
    #     TransactionBuilder(
    #         source_account=source_account,
    #         # network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
    #         network_passphrase=Network.PUBLIC_NETWORK_PASSPHRASE,
    #         base_fee=base_fee,
    #     )
    #         # Because Stellar allows transaction in many currencies, you must specify the asset type.
    #         # Here we are sending Lumens.
    #         # .append_payment_op(destination=destination_id, amount="1.001", asset_code="XLM")
    #         .append_create_account_op(destination=destination_id, starting_balance="1.001")
    #         # A memo allows you to add your own metadata to a transaction. It's
    #         # optional and does not affect how Stellar treats the transaction.
    #         .add_text_memo("556850")
    #         # Wait a maximum of three minutes for the transaction
    #         .set_timeout(10)
    #         .build()
    # )

    # Sign the transaction to prove you are actually the person sending it.
    transaction.sign(source_key)

    print(f'xdr trx: {transaction.to_xdr()}')

    xdr = transaction.to_xdr()
    print(f'len : {len(xdr)}')
    print(type(server))
    # rsp = server.submit_transaction(xdr)
    # print(rsp)

    try:
        # And finally, send it off to Stellar!
        response = server.submit_transaction(transaction)
        print(f"Response: {response}")
    except (BadRequestError, BadResponseError) as err:
        print(f"Something went wrong!\n{err}")

    pass
Exemple #22
0
import os
import sys
from pprint import pprint

import dotenv
from stellar_sdk.asset import Asset
from stellar_sdk.keypair import Keypair
from stellar_sdk.network import Network
from stellar_sdk.operation.set_options import Flag as AuthFlag
from stellar_sdk.server import Server
from stellar_sdk.transaction_builder import TransactionBuilder

dotenv.load_dotenv(verbose=True)

STELLAR_HORIZON_TESTNET = os.getenv("STELLAR_HORIZON_TESTNET")
server = Server(STELLAR_HORIZON_TESTNET)


def create_assets_for_distributing(amount):

    # Keys for accounts to issue and receive the new asset
    issuing_keypair = Keypair.from_secret(os.getenv("ISSUING_PRIVATE"))
    issuing_public = issuing_keypair.public_key
    issuing_account = server.load_account(issuing_public)

    distributor_keypair = Keypair.from_secret(os.getenv("DISTRIBUTOR_INRX_PRIVATE_KEY"))
    distributor_public = distributor_keypair.public_key
    distributor_account = server.load_account(distributor_public)

    inr_asset = Asset("INRx", issuing_public)
from stellar_sdk.keypair import Keypair
import requests
from stellar_sdk.server import Server
import json

server = Server("https://horizon-testnet.stellar.org")
accounts = {}

for i in range(3):
    # Create a Keypair
    pair = Keypair.random()
    print(f"Secret: {pair.secret}")
    print(f"Public Key: {pair.public_key}")

    # Create Account
    public_key = pair.public_key
    response = requests.get(f"https://friendbot.stellar.org?addr={public_key}")
    if response.status_code == 200:
        print(f"SUCCESS! You have a new account :)\n{response.text}")

        # Get Account details
        account = server.accounts().account_id(public_key).call()
        for balance in account['balances']:
            print(
                f"Type: {balance['asset_type']}, Balance: {balance['balance']}"
            )

        # Save Account Keys
        accounts[i] = {"sk": pair.secret, "pk": pair.public_key}

    else:
Exemple #24
0
SERVER_JWT_KEY = None
if any(sep in ACTIVE_SEPS for sep in ["sep-10", "sep-24"]):
    SERVER_JWT_KEY = env_or_settings("SERVER_JWT_KEY")

STELLAR_NETWORK_PASSPHRASE = (
    env_or_settings("STELLAR_NETWORK_PASSPHRASE", required=False)
    or "Test SDF Network ; September 2015"
)

HORIZON_URI = (
    env_or_settings("HORIZON_URI", required=False)
    or "https://horizon-testnet.stellar.org"
)
if not HORIZON_URI.startswith("http"):
    raise ImproperlyConfigured("HORIZON_URI must include a protocol (http or https)")
HORIZON_SERVER = Server(horizon_url=HORIZON_URI)

LOCAL_MODE = env_or_settings("LOCAL_MODE", bool=True, required=False) or False

HOST_URL = env_or_settings("HOST_URL")
if not HOST_URL.startswith("http"):
    raise ImproperlyConfigured("HOST_URL must include a protocol (http or https)")
elif LOCAL_MODE and HOST_URL.startswith("https"):
    raise ImproperlyConfigured("HOST_URL uses HTTPS but LOCAL_MODE only supports HTTP")
elif not LOCAL_MODE and not HOST_URL.startswith("https"):
    raise ImproperlyConfigured("HOST_URL uses HTTP but LOCAL_MODE is off")

SEP10_HOME_DOMAINS = env_or_settings(
    "SEP10_HOME_DOMAINS", list=True, required=False
) or [urlparse(HOST_URL).netloc]
if any(d.startswith("http") for d in SEP10_HOME_DOMAINS):
Exemple #25
0
 def __init__(self):
     self.exchange = 'stellar'
     self.params.update(super().params)  # merge with the global params
     self.settings = utils.gather_environ(self.params)
     self.server = Server(horizon_url=self.settings['url'])
     super().__init__()
Exemple #26
0
# See: https://www.stellar.org/developers/guides/issuing-assets.html

from stellar_sdk.keypair import Keypair
from stellar_sdk.asset import Asset
from stellar_sdk.transaction_builder import TransactionBuilder
from stellar_sdk.server import Server
from stellar_sdk.network import Network

# 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")

# Keys for accounts to issue and receive the new asset
issuing_keypair = Keypair.from_secret(
    "SCBHQEGSNBTT4S7Y73YAF3M3JSVSTSNBGAVU5M4XVFGUF7664EUXQHFU")
issuing_public = issuing_keypair.public_key

distributor_keypair = Keypair.from_secret(
    "SB6MJ6M3BPJZUGFP2QCODUIKWQWF6AIN4Z6L3J6PWL3QGDW4L6YR3QIU")
distributor_public = distributor_keypair.public_key

# 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.
distributor_account = server.load_account(distributor_public)

# Create an object to represent the new asset
hello_asset = Asset("Hello", issuing_public)

# First, the receiving account must trust the asset
trust_transaction = (TransactionBuilder(
    source_account=distributor_account,
from stellar_sdk.keypair import Keypair
from stellar_sdk.network import Network
from stellar_sdk.server import Server
from stellar_sdk.transaction_builder import TransactionBuilder
from stellar_sdk.exceptions import NotFoundError, BadResponseError, BadRequestError
import json
from stellar_base.builder import Builder

server = Server("https://horizon-testnet.stellar.org")

fileName = 'accounts.json'
with open(fileName) as r:
    accounts = json.load(r)

source_acc_key = accounts[0]['secret']
source_acc_id = accounts[0]['publicKey']
destination_acc_id = accounts[1]['publicKey']

try:
    server.load_account(destination_acc_id)
except NotFoundError:
    # If the account is not found, surface an error message for logging.
    raise Exception("The destination account does not exist!")
'''builder = Builder(secret=source_acc_key)
bob_address = destination_acc_id
builder.append_payment_op(bob_address, '10', 'XLM')
builder.add_text_memo('For beers') # string length <= 28 bytes
builder.sign()
builder.submit()'''

base_fee = server.fetch_base_fee()