Exemple #1
0
 def test_check_memo_required_with_fetch_account_error_raise_sync(
         self, httpserver):
     self.__inject_mock_server(httpserver)
     horizon_url = httpserver.url_for("/")
     server = Server(horizon_url)
     keypair = Keypair.from_secret(
         "SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY")
     account = Account(keypair.public_key, 1)
     transaction = (TransactionBuilder(account).append_payment_op(
         self.DESTINATION_ACCOUNT_FETCH_ERROR, "10",
         "XLM").append_path_payment_strict_receive_op(
             self.DESTINATION_ACCOUNT_NO_MEMO_REQUIRED,
             "XLM",
             None,
             "10",
             "BTC",
             "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2",
             "1",
             [],
         ).append_path_payment_strict_send_op(
             self.DESTINATION_ACCOUNT_NO_MEMO_REQUIRED,
             "XLM",
             None,
             "10",
             "BTC",
             "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2",
             "1",
             [],
         ).append_account_merge_op(
             self.DESTINATION_ACCOUNT_NO_MEMO_REQUIRED).build())
     transaction.sign(keypair)
     with pytest.raises(BadRequestError) as err:
         server.submit_transaction(transaction)
     assert err.value.status == 400
Exemple #2
0
	def send_txn(self, origin, dest, merge):
		keys=Keypair.from_secret(origin)
		server=Server("https://horizon.stellar.org/")
		NET_PASS=Network.PUBLIC_NETWORK_PASSPHRASE
		basefee=server.fetch_base_fee()

		txnSent=False
		while txnSent is False:
			try:
				account=server.load_account(keys.public_key)
				if merge !=  None and merge == True:
					txn=TransactionBuilder(
						source_account=account,
						network_passphrase=NET_PASS,
						base_fee=basefee,
							).append_account_merge_op(
							destination=dest
							).set_timeout(10000).build()
				else:
					txn=TransactionBuilder(
						source_account=account,
						network_passphrase=NET_PASS,
						base_fee=basefee,
						).append_create_account_op(
							destination=dest,
							starting_balance="1.11").set_timeout(1000).build()
				txn.sign(keys)
				server.submit_transaction(txn)
				txnSent=True
			except:
				time.sleep(0.5)
Exemple #3
0
 def test_check_memo_required_with_memo_muxed_account_sync(
         self, httpserver):
     self.__inject_mock_server(httpserver)
     horizon_url = httpserver.url_for("/")
     server = Server(horizon_url)
     keypair = Keypair.from_secret(
         "SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY")
     account = Account(keypair.public_key, 1)
     transaction = (TransactionBuilder(account).append_payment_op(
         self.DESTINATION_ACCOUNT_MEMO_REQUIRED_A, "10",
         "XLM").append_path_payment_strict_receive_op(
             self.DESTINATION_ACCOUNT_MEMO_REQUIRED_B,
             "XLM",
             None,
             "10",
             "BTC",
             "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2",
             "1",
             [],
         ).append_path_payment_strict_send_op(
             self.DESTINATION_ACCOUNT_MEMO_REQUIRED_C,
             "XLM",
             None,
             "10",
             "BTC",
             "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2",
             "1",
             [],
         ).append_account_merge_op(
             self.DESTINATION_ACCOUNT_MEMO_REQUIRED_D).add_text_memo(
                 "hello, world").build())
     transaction.sign(keypair)
     server.submit_transaction(transaction)
Exemple #4
0
 def test_check_memo_required_with_fee_bump_transaction_sync(
         self, httpserver):
     self.__inject_mock_server(httpserver)
     horizon_url = httpserver.url_for("/")
     server = Server(horizon_url)
     keypair = Keypair.from_secret(
         "SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY")
     account = Account(keypair.public_key, 1)
     transaction = (TransactionBuilder(account, v1=True).append_payment_op(
         self.DESTINATION_ACCOUNT_MEMO_REQUIRED_A, "10",
         "XLM").append_path_payment_strict_send_op(
             self.DESTINATION_ACCOUNT_MEMO_REQUIRED_C,
             "XLM",
             None,
             "10",
             "BTC",
             "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2",
             "1",
             [],
         ).append_account_merge_op(
             self.DESTINATION_ACCOUNT_MEMO_REQUIRED_D).add_text_memo(
                 "hello, world").build())
     transaction.sign(keypair)
     fee_bump_tx = TransactionBuilder.build_fee_bump_transaction(
         fee_source=Keypair.random().public_key,
         base_fee=200,
         inner_transaction_envelope=transaction,
         network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
     )
     server.submit_transaction(fee_bump_tx)
Exemple #5
0
 def test_check_memo_required_with_no_destination_operation_sync(
         self, httpserver):
     self.__inject_mock_server(httpserver)
     horizon_url = httpserver.url_for("/")
     server = Server(horizon_url)
     keypair = Keypair.from_secret(
         "SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY")
     account = Account(keypair.public_key, 1)
     transaction = (TransactionBuilder(account).append_manage_data_op(
         "Hello", "world").build())
     transaction.sign(keypair)
     server.submit_transaction(transaction)
Exemple #6
0
    def pagoEncuesta(self, Destino, monto, firmantes):
        validarCuenta = self.verificarCuentaActivada(destino=Destino)
        if validarCuenta[0]:
            server = Server(horizon_url=self.Horizon_url)
            root_keypair = Keypair.from_secret(self.sLlave)
            root_account = server.load_account(
                account_id=root_keypair.public_key)
            base_fee = server.fetch_base_fee()
            transaction = TransactionBuilder(
                source_account=root_account,
                network_passphrase=self.networkTrabajar,
                base_fee=base_fee) \
                .append_payment_op(  # add a payment operation to the transaction
                destination=Destino,
                asset_code="XLM",
                amount=str(monto)) \
                .set_timeout(30) \
                .build()  # mark this transaction as valid only for the next 30 seconds
            #            transaction.sign(root_keypair)
            for i in firmantes:
                transaction.sign(Keypair.from_secret(i))
            try:
                response = server.submit_transaction(transaction)
                return [True, response]
            except exceptions.BadRequestError as d:
                # print(d)
                return [False, d]

        else:
            server = Server(horizon_url=self.Horizon_url)
            root_keypair = Keypair.from_secret(self.sLlave)
            root_account = server.load_account(
                account_id=root_keypair.public_key)
            base_fee = server.fetch_base_fee()
            transaction = TransactionBuilder(
                source_account=root_account,
                network_passphrase=self.networkTrabajar,
                base_fee=base_fee) \
                .append_create_account_op(destination=Destino,starting_balance=str(monto))\
                .set_timeout(30)\
                .build()
            #            transaction.sign(root_keypair)
            for i in firmantes:
                transaction.sign(Keypair.from_secret(i))
            try:
                response = server.submit_transaction(transaction)
                return [True, response]
            except exceptions.BadRequestError as d:
                # print(d)
                return [False, d]
def make_bids(asset_code, issuing_keypair, distributing_keypair,
              market_supply):
    # Talk to Horizon testnet instance.
    server = Server(horizon_url=TESTNET)

    # Fetch the current sequence number for the source account from Horizon.
    source_account = server.load_account(distributing_keypair.public_key)

    # Build transaction around manage buy offer operation (setting market bids).
    transaction = (
        TransactionBuilder(
            source_account=source_account,
            network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
            base_fee=100,  # too lazy to fetch :)
        ).append_manage_buy_offer_op(
            'XLM', None, asset_code, issuing_keypair.public_key,
            market_supply, '.08').append_manage_buy_offer_op(
                'XLM', None, asset_code, issuing_keypair.public_key,
                market_supply,
                '.09').append_manage_buy_offer_op('XLM', None, asset_code,
                                                  issuing_keypair.public_key,
                                                  market_supply,
                                                  '.10').build())

    # Sign transaction with distributor private key.
    transaction.sign(distributing_keypair)

    # Submit signed transaction to Horizon.
    response = server.submit_transaction(transaction)
    print(json.dumps(response, indent=2))
Exemple #8
0
    def configurarBilleteraPrimeraVez(self, listaUsuarios, umbralLista):
        server = Server(horizon_url=self.Horizon_url)
        root_keypair = Keypair.from_secret(self.sLlave)
        root_account = server.load_account(account_id=root_keypair.public_key)
        base_fee = server.fetch_base_fee()

        transaction = TransactionBuilder(
            base_fee=base_fee,
            network_passphrase=self.networkTrabajar,
            source_account=root_account)\
            .append_set_options_op(master_weight=1,
                                low_threshold=int(umbralLista[1])-1,
                                med_threshold=int(umbralLista[1]),
                                high_threshold=int(umbralLista[0]))\
            .set_timeout(30)
        for i in listaUsuarios:
            transaction.append_ed25519_public_key_signer(account_id=i[3],
                                                         weight=1)

        transaction = transaction.build()
        transaction.sign(root_keypair)
        try:
            response = server.submit_transaction(transaction)
            return [True, response]
        except exceptions.BadRequestError as d:
            return [False, d]
        except exceptions.NotFoundError as n:
            return [False, n]
Exemple #9
0
def make_account():
    keypair = Keypair.random()

    print("Public Key: " + keypair.public_key)
    print("Secret Seed: " + keypair.secret)

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

    url = 'https://friendbot.stellar.org'
    response = requests.get(url, params={'addr': keypair.public_key})
    print(response)

    source_keypair = Keypair.from_secret(keypair.secret)
    source_public_key = source_keypair.public_key
    source_account = server.load_account(source_public_key)
    base_fee = server.fetch_base_fee()

    transaction = (
        TransactionBuilder(
            source_account=source_account,
            network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
            base_fee=base_fee,
        ).append_change_trust_op(
            "SAVEPOINTS",
            "GDG4SRXHATOQPRDAMK45YHL42N3RMQ6UJYAS2ETJQ2I5XZYSIQLCSGV6").
        set_timeout(
            30)  # Make this transaction valid for the next 30 seconds only
        .build())

    transaction.sign(source_keypair)
    print(transaction.to_xdr())
    response = server.submit_transaction(transaction)
    #print(response)

    return keypair.public_key, keypair.secret
def hello_world(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """
    if request.method == 'OPTIONS':
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET,POST',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('okay done', 204, headers)

    from stellar_sdk import Server, Keypair, TransactionBuilder, Network, Asset

    request_json = request.get_json()
    cash = request_json["money"]
    print(cash)

    source_keypair = Keypair.from_secret("xxxxxxxxxxxxxxxxxxxxxxxxxxx")
    server = Server(horizon_url="https://horizon-testnet.stellar.org")
    source_account = server.load_account(account_id=source_keypair.public_key)

    base_fee = server.fetch_base_fee()
    path = []

    transaction = (TransactionBuilder(
        source_account=source_account,
        network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
        base_fee=base_fee,
    ).append_path_payment_op(
        destination="GDYC7QBANT5HCU3CAJVYDBDMGKUMOSWRULN737XRSDV56HIGSIUEQ6WJ",
        send_code="XLM",
        send_issuer=None,
        send_max="100",
        dest_code="USD",
        dest_issuer="GACN4CNWBINPRWT2YKXXMEIPIBL5PEJNSKEBNOGCCXDKZBE5M44YFNXB",
        dest_amount=str(cash),
        path=path).set_timeout(30).build())
    transaction.sign(source_keypair)
    res = server.submit_transaction(transaction)
    print(res)
    import json
    import flask
    request_json = request.get_json()
    response = flask.jsonify(
        "https://horizon-testnet.stellar.org/accounts/GDYC7QBANT5HCU3CAJVYDBDMGKUMOSWRULN737XRSDV56HIGSIUEQ6WJ"
    )
    response.headers.set('Access-Control-Allow-Origin', '*')
    response.headers.set('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.set('Access-Control-Allow-Headers', 'Content-Type')
    return response
Exemple #11
0
def broadcast_tx(transaction, test_mode=True):
    network_settings = get_network_settings(test_mode=test_mode)
    server = Server(network_settings.get("horizon_url"))
    try:
        transaction_resp = server.submit_transaction(transaction)
        print("{}".format(json.dumps(transaction_resp, indent=4)))
    except BaseHorizonError as e:
        print("Error: {}".format(str(e)))
def submit_merge_txn(keys):
    url = "https://horizon.stellar.org/accounts/" + keys.public_key + "/transactions?limit=1"
    res = requests.get(url)
    res_as_json = json.loads(res.text)

    funds_origin = res_as_json["_embedded"]["records"][0]["source_account"]
    server = Server("https://horizon.stellar.org/")
    NET_PASS = Network.PUBLIC_NETWORK_PASSPHRASE
    account = server.load_account(keys.public_key)
    txn = TransactionBuilder(
        source_account=account,
        network_passphrase=NET_PASS,
        base_fee=server.fetch_base_fee()).append_account_merge_op(
            destination=funds_origin).set_timeout(10000).build()
    txn.sign(keys)
    try:
        server.submit_transaction(txn)
        return True
    except:
        return False
Exemple #13
0
 def test_check_memo_required_with_two_operation_with_same_destination_sync(
         self, httpserver):
     self.__inject_mock_server(httpserver)
     horizon_url = httpserver.url_for("/")
     server = Server(horizon_url)
     keypair = Keypair.from_secret(
         "SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY")
     account = Account(keypair.public_key, 1)
     transaction = (TransactionBuilder(account).append_payment_op(
         self.DESTINATION_ACCOUNT_NO_MEMO_REQUIRED, "10",
         "XLM").append_path_payment_strict_receive_op(
             self.DESTINATION_ACCOUNT_NO_MEMO_REQUIRED,
             "XLM",
             None,
             "10",
             "BTC",
             "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2",
             "1",
             [],
         ).append_path_payment_strict_send_op(
             self.DESTINATION_ACCOUNT_NO_MEMO_REQUIRED,
             "XLM",
             None,
             "10",
             "BTC",
             "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2",
             "1",
             [],
         ).append_account_merge_op(
             self.DESTINATION_ACCOUNT_MEMO_REQUIRED_D).build())
     transaction.sign(keypair)
     with pytest.raises(
             AccountRequiresMemoError,
             match="Destination account requires a memo in the transaction.",
     ) as err:
         server.submit_transaction(transaction)
     assert err.value.account_id == self.DESTINATION_ACCOUNT_MEMO_REQUIRED_D
     assert err.value.operation_index == 3
Exemple #14
0
    def convert_to_USDC(public_key, filename, amount, public=False):
        receipt = ""
        if public:
            server = Server(horizon_url="https://horizon.stellar.org")
            passphrase = Network.PUBLIC_NETWORK_PASSPHRASE
        else:
            server = Server(horizon_url="https://horizon-testnet.stellar.org")
            passphrase = Network.TESTNET_NETWORK_PASSPHRASE

        sender = hidden[0]
        source_keypair = Keypair.from_secret(hidden[1])

        # try:
        destination_p = sender
        source_acc = server.load_account(sender)
        base_fee = server.fetch_base_fee()
        path = [
            Asset('XLM', None),
            Asset("USDC",
                  'GC5W3BH2MQRQK2H4A6LP3SXDSAAY2W2W64OWKKVNQIAOVWSAHFDEUSDC')
        ]
        c_m_value = float(get_XLM_price())
        complete = False
        slip = 0
        while not complete:
            min_received = c_m_value * (1 - slip)
            slip += .25
            transaction = TransactionBuilder(
                source_account=source_acc,
                network_passphrase=passphrase,
                base_fee=base_fee).append_path_payment_strict_send_op(
                    destination_p, "XLM", None, amount, "USDC",
                    'GC5W3BH2MQRQK2H4A6LP3SXDSAAY2W2W64OWKKVNQIAOVWSAHFDEUSDC',
                    str(min_received), path).build()

            transaction.sign(source_keypair)
            try:
                response = server.submit_transaction(transaction)
                if response['successful']:
                    receipt += "Successfully sent " + str(
                        amount) + " XLM to USDC"
                    receipt += "\nslippage: " + str((1 - slip) * 100) + "%"
                    complete = True
            except:
                receipt += "\n Failed at " + str((1 - slip) * 100) + "% rate"
            if slip > 5:
                complete = True
                receipt += "Aborting attempts at transaction"
        return receipt
Exemple #15
0
def sendXLM(secret, toAddress): 
    server = Server(horizon_url="https://horizon-testnet.stellar.org")
    source_keypair = Keypair.from_secret(secret)

    source_account = server.load_account(account_id=source_keypair.public_key)

    transaction = TransactionBuilder(
        source_account=source_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=100) \
        .append_path_payment_strict_receive_op(destination=toAddress,
                                send_code="XLM", send_issuer=None, send_max="1000", dest_code="XLM",
                                dest_amount="5.50", path=path) \
        .set_timeout(30) \
        .build()
    transaction.sign(source_keypair)
    response = server.submit_transaction(transaction)
Exemple #16
0
 def crearAssets(self, codigo, monto, emisor):
     server = Server(horizon_url=self.Horizon_url)
     root_keypair = Keypair.from_secret(self.sLlave)
     root_account = server.load_account(account_id=root_keypair.public_key)
     transaction = TransactionBuilder(
         source_account=root_account,
         network_passphrase=self.networkTrabajar,
         base_fee=100).append_change_trust_op(limit=monto,
                                              asset_code=str(codigo),
                                              asset_issuer=emisor).build()
     transaction.sign(root_keypair)
     try:
         response = server.submit_transaction(transaction)
         return [True, response]
     except exceptions.BadRequestError as d:
         return [False, d]
Exemple #17
0
def transfer_points(source_secret_key,
                    receiver_public_key,
                    num_points,
                    memo=""):
    #source is distributor

    source_keypair = Keypair.from_secret(source_secret_key)
    source_public_key = source_keypair.public_key

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

    source_account = server.load_account(source_public_key)
    base_fee = server.fetch_base_fee()

    # if you want to submit to the public network, please use `Network.PUBLIC_NETWORK_PASSPHRASE`.

    if memo == "":
        transaction = (
            TransactionBuilder(
                source_account=source_account,
                network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
                base_fee=base_fee,
            ).append_payment_op(
                receiver_public_key, str(num_points), "SAVEPOINTS",
                "GDG4SRXHATOQPRDAMK45YHL42N3RMQ6UJYAS2ETJQ2I5XZYSIQLCSGV6").
            set_timeout(
                30)  # Make this transaction valid for the next 30 seconds only
            .build())

    else:
        transaction = (
            TransactionBuilder(
                source_account=source_account,
                network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
                base_fee=base_fee,
            ).append_payment_op(
                receiver_public_key, str(num_points), "SAVEPOINTS",
                "GDG4SRXHATOQPRDAMK45YHL42N3RMQ6UJYAS2ETJQ2I5XZYSIQLCSGV6").
            add_text_memo(memo).set_timeout(
                30)  # Make this transaction valid for the next 30 seconds only
            .build())

    transaction.sign(source_keypair)
    print(transaction.to_xdr())
    response = server.submit_transaction(transaction)
    print(response)
Exemple #18
0
def add_trust(wallet_file,
              asset,
              issuer,
              test_mode=True,
              trezor_mode=False,
              vzero=False,
              timeout=3600):
    network_settings = get_network_settings(test_mode=test_mode)
    if timeout is None:
        timeout = 3600
    v1_mode = not vzero
    if not trezor_mode:
        (private_key, public_key) = load_wallet(wallet_file=wallet_file)
        k = Keypair.from_secret(secret=private_key)
    else:
        public_key = get_trezor_public_key()
        k = Keypair.from_public_key(public_key=public_key)
        v1_mode = False
    server = Server(network_settings.get("horizon_url"))
    stellar_asset = Asset(asset, issuer)
    account = server.load_account(account_id=k.public_key)
    transaction = (TransactionBuilder(
        source_account=account,
        network_passphrase=network_settings.get("network_passphrase"),
        base_fee=100,
        v1=v1_mode).append_change_trust_op(
            asset_code=stellar_asset.code,
            asset_issuer=stellar_asset.issuer,
        ).set_timeout(timeout).build())
    if not trezor_mode:
        transaction.sign(k)
    else:
        transaction = sign_trezor_transaction(
            transaction,
            k,
            network_passphrase=network_settings.get("network_passphrase"))
    try:
        transaction_resp = server.submit_transaction(transaction)
        print("{}".format(json.dumps(transaction_resp, indent=4)))
    except BaseHorizonError as e:
        print("Error: {}".format(str(e)))
def send_asset(issuing_keypair, distributing_keypair, asset_code, supply):
    # Talk to Horizon testnet instance.
    server = Server(horizon_url=TESTNET)

    # Fetch the current sequence number for the source account from Horizon.
    source_account = server.load_account(issuing_keypair.public_key)

    # Build transaction around payment operation (sending asset to distributor).
    transaction = (
        TransactionBuilder(
            source_account=source_account,
            network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
            base_fee=100,  # too lazy to fetch :)
        ).append_payment_op(distributing_keypair.public_key, supply,
                            asset_code, issuing_keypair.public_key).build())

    # Sign transaction with issuing private key.
    transaction.sign(issuing_keypair)

    # Submit signed transaction to Horizon.
    response = server.submit_transaction(transaction)
    print(json.dumps(response, indent=2))
Exemple #20
0
 def pagoAssets(self, Destino, monto, codigo, asset_usuario):
     server = Server(horizon_url=self.Horizon_url)
     root_keypair = Keypair.from_secret(self.sLlave)
     root_account = server.load_account(account_id=root_keypair.public_key)
     base_fee = server.fetch_base_fee()
     transaction = TransactionBuilder(
         source_account=root_account,
         network_passphrase=self.networkTrabajar,
         base_fee=base_fee) \
         .append_payment_op(  # add a payment operation to the transaction
         destination=Destino,
         asset_code=str(codigo),
         amount=str(monto),
         asset_issuer=asset_usuario) \
         .set_timeout(30) \
         .build()  # mark this transaction as valid only for the next 30 seconds
     transaction.sign(root_keypair)
     try:
         response = server.submit_transaction(transaction)
         return [True, response]
     except exceptions.BadRequestError as d:
         # print(d)
         return [False, d]
import pprint

from stellar_sdk import Keypair, Server, MuxedAccount, TransactionBuilder, Network

horizon_url = "https://horizon-testnet.stellar.org/"
network_passphrase = Network.TESTNET_NETWORK_PASSPHRASE

alice_secret = "SC5O7VZUXDJ6JBDSZ74DSERXL7W3Y5LTOAMRF7RQRL3TAGAPS7LUVG3L"
bob_account = MuxedAccount(
    account_id="GBVKI23OQZCANDUZ2SI7XU7W6ICYKYT74JBXDD2CYRDAFZHZNRPASSQK",
    account_id_id=12387,
)
print(f"account_id_muxed: {bob_account.account_id_muxed}")

alice_keypair = Keypair.from_secret(alice_secret)

server = Server(horizon_url=horizon_url)
alice_account = server.load_account(alice_keypair.public_key)
transaction = TransactionBuilder(
    source_account=alice_account,
    network_passphrase=network_passphrase,
    base_fee=100,
    v1=True,  # If you want to build Protocol 13 transactions, you need to set `v1` to `True`
) \
    .append_payment_op(destination=bob_account, amount="100", asset_code="XLM") \
    .build()

transaction.sign(alice_keypair)
resp = server.submit_transaction(transaction)
pprint.pprint(resp)
Exemple #22
0
class Command(BaseCommand):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.reset_parser = None
        self.issue_parser = None
        self.server = Server("https://horizon-testnet.stellar.org")
        self.http = urllib3.PoolManager()

    def add_arguments(self, parser):
        subparsers = parser.add_subparsers(dest="subcommands", required=True)
        self.reset_parser = subparsers.add_parser(
            "reset", help="a sub-command for testnet resets"
        )
        self.issue_parser = subparsers.add_parser(
            "issue", help="a sub-command for issuing assets on testnet"
        )
        self.issue_parser.add_argument(
            "--asset", "-a", help="the code of the asset issued"
        )
        self.issue_parser.add_argument(
            "--issuer-seed", "-i", help="the issuer's secret key"
        )
        self.issue_parser.add_argument(
            "--distribution-seed", "-d", help="the distribution account's secret key"
        )
        self.issue_parser.add_argument(
            "--client-seed", "-c", help="the client account's secret key"
        )
        self.issue_parser.add_argument(
            "--issue-amount",
            type=Decimal,
            help="the amount sent to distribution account. Also the limit for the trustline.",
        )
        self.issue_parser.add_argument(
            "--client-amount",
            type=Decimal,
            help="the amount sent to client account. Also the limit for the trustline.",
        )

    def handle(self, *_args, **options):
        if options.get("subcommands") == "reset":
            self.reset(**options)
        elif options.get("subcommands") == "issue":
            self.issue(**options)

    def reset(self, **options):
        """
        Perform any necessary functions to ensure the anchor is in a valid
        state after a testnet reset. Currently this involves the following:

        - re-issuing every Asset object in the DB
        - moves all `pending_trust` Transactions to `error`
        - setting the most-recently streamed Transaction object's
            `paging_token` attribute to None. This signals to
            watch_transactions to stream using the `"now"` keyword.
        """
        print("\nResetting each asset's most recent paging token")
        for asset in Asset.objects.filter(distribution_seed__isnull=False):
            transaction = (
                Transaction.objects.filter(
                    Q(kind=Transaction.KIND.withdrawal) | Q(kind=Transaction.KIND.send),
                    receiving_anchor_account=asset.distribution_account,
                    status=Transaction.STATUS.completed,
                )
                .order_by("-completed_at")
                .first()
            )
            if transaction:
                transaction.paging_token = None
                transaction.save()
        print("\nPlacing all pending_trust transactions into error status")
        Transaction.objects.filter(status=Transaction.STATUS.pending_trust).update(
            status=Transaction.STATUS.error
        )
        for asset in Asset.objects.filter(issuer__isnull=False):
            print(f"\nIssuing {asset.code}")
            issuer_seed = input(f"Seed for {asset.code} issuer: ")
            try:
                Keypair.from_secret(issuer_seed)
            except Ed25519SecretSeedInvalidError:
                raise CommandError("Bad seed string for issuer account")
            distribution_seed = asset.distribution_seed
            if not distribution_seed:
                distribution_seed = input(
                    f"Seed for {asset.code} distribution account: "
                )
                try:
                    Keypair.from_secret(distribution_seed)
                except Ed25519SecretSeedInvalidError:
                    raise CommandError("Bad seed string for distribution account")
            self.issue(
                **{
                    "asset": asset.code,
                    "issuer_seed": issuer_seed,
                    "distribution_seed": distribution_seed,
                    "issue_amount": Decimal(10000000),
                }
            )

    def issue(self, **options):
        """
        Issue the asset specified using the `options` passed to the subcommand
        or function call. The code here is a port of the following project:

        https://github.com/stellar/create-stellar-token

        Users can setup distribution and client accounts for the asset being
        issued as well.
        """
        code = options.get("asset") or "TEST"
        issuer = Keypair.from_secret(
            options.get("issuer_seed") or Keypair.random().secret
        )
        distributor = Keypair.from_secret(
            options.get("distribution_seed") or Keypair.random().secret
        )
        client, client_amount = None, None
        if options.get("client_seed") or options.get("client_amount"):
            client = Keypair.from_secret(
                options.get("client_seed") or Keypair.random().secret
            )
            client_amount = options.get("client_amount") or Decimal(1000)
        issue_amount = options.get("issue_amount") or Decimal(100000)

        print("\nIssuer account public and private keys:")
        print(f"public key: {issuer.public_key}")
        print(f"secret key: {issuer.secret}\n")
        print("Distribution account public and private keys:")
        print(f"public key: {distributor.public_key}")
        print(f"secret key: {distributor.secret}\n")
        print(f"Issuing {issue_amount} {code} to the distribution account")
        if client:
            print("\nClient account public and private keys:")
            print(f"public key: {client.public_key}")
            print(f"secret key: {client.secret}\n")
            print(f"Sending {client_amount} to the client account\n")

        accounts = {}
        for kp in [issuer, distributor, client]:
            if not kp:
                continue
            try:
                accounts[kp.public_key] = (
                    self.server.accounts().account_id(kp.public_key).call()
                )
            except NotFoundError:
                print(f"Funding {kp.public_key} ...")
                self.http.request(
                    "GET", f"https://friendbot.stellar.org?addr={kp.public_key}"
                )
                accounts[kp.public_key] = (
                    self.server.accounts().account_id(kp.public_key).call()
                )

        self.add_balance(code, issue_amount, accounts, distributor, issuer, issuer)
        if client:
            self.add_balance(code, client_amount, accounts, client, distributor, issuer)

        home_domain = input("Home domain for the issuing account (optional): ")
        if home_domain:
            self.set_home_domain(issuer, home_domain)

    def set_home_domain(self, issuer: Keypair, home_domain: str):
        envelope = (
            TransactionBuilder(
                self.server.load_account(issuer.public_key),
                base_fee=settings.MAX_TRANSACTION_FEE_STROOPS
                or settings.HORIZON_SERVER.fetch_base_fee(),
                network_passphrase="Test SDF Network ; September 2015",
            )
            .append_set_options_op(home_domain=home_domain)
            .set_timeout(30)
            .build()
        )
        envelope.sign(issuer)
        try:
            self.server.submit_transaction(envelope)
        except BaseHorizonError as e:
            print(
                f"Failed to set {home_domain} as home_domain for {issuer.public_key}."
                f"Result codes: {e.extras.get('result_codes')}"
            )
        else:
            print("Success!")

    def add_balance(self, code, amount, accounts, dest, src, issuer):
        tb = TransactionBuilder(
            self.account_from_json(accounts[src.public_key]),
            base_fee=settings.MAX_TRANSACTION_FEE_STROOPS
            or settings.HORIZON_SERVER.fetch_base_fee(),
            network_passphrase="Test SDF Network ; September 2015",
        )
        balance = self.get_balance(code, accounts[dest.public_key])
        if not balance:
            print(f"\nCreating {code} trustline for {dest.public_key}")
            if settings.MAX_TRANSACTION_FEE_STROOPS:
                # halve the base_fee because there are 2 operations
                tb.base_fee = tb.base_fee // 2
            tb.append_change_trust_op(
                asset_code=code, asset_issuer=issuer.public_key, source=dest.public_key
            )
            payment_amount = amount
        elif Decimal(balance) < amount:
            print(f"\nReplenishing {code} balance to {amount} for {dest.public_key}")
            payment_amount = amount - Decimal(balance)
        else:
            print(
                "Destination account already has more than the amount "
                "specified, skipping\n"
            )
            return

        print(f"Sending {code} payment of {payment_amount} to {dest.public_key}")
        tb.append_payment_op(
            destination=dest.public_key,
            amount=payment_amount,
            asset_code=code,
            asset_issuer=issuer.public_key,
            source=src.public_key,
        )
        envelope = tb.set_timeout(30).build()
        if len(tb.operations) == 2:
            # add destination's signature if we're adding a trustline
            envelope.sign(dest)
        envelope.sign(src)
        try:
            self.server.submit_transaction(envelope)
        except BaseHorizonError as e:
            print(
                f"Failed to send {code} payment to {dest.public_key}. "
                f"Result codes: {e.extras.get('result_codes')}"
            )
        else:
            print("Success!")

    def account_from_json(self, json):
        sequence = int(json["sequence"])
        thresholds = Thresholds(
            json["thresholds"]["low_threshold"],
            json["thresholds"]["med_threshold"],
            json["thresholds"]["high_threshold"],
        )
        account = Account(account_id=json["id"], sequence=sequence)
        account.signers = json["signers"]
        account.thresholds = thresholds
        return account

    def get_balance(self, code, json) -> Optional[str]:
        for balance_obj in json["balances"]:
            if balance_obj.get("asset_code") == code:
                return balance_obj["balance"]
Exemple #23
0
root_keypair = Keypair.from_secret(
    "SDSMBDZKTGPTYGXOM7VLC52PICHMI3LOZTMKXSDCU3H75AGXLITMHBUG")
root_account = server.load_account(account_id=root_keypair.public_key)

# This is the `x` in the description
preimage = b"your_preimage_value"

# First we add sha256(preimage) as signer
add_signer_transaction = (TransactionBuilder(
    source_account=root_account,
    network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
    base_fee=100,
).append_hashx_signer(sha256_hash=hashlib.sha256(preimage).digest(),
                      weight=1).build())

add_signer_transaction.sign(root_keypair)
add_signer_transaction_resp = server.submit_transaction(add_signer_transaction)
print(f"add_signer_transaction_resp: {add_signer_transaction_resp}")

# Then we use preimage as the signer to sign another transaction.
manage_data_transaction = (TransactionBuilder(
    source_account=root_account,
    network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
    base_fee=100,
).append_manage_data_op("Hello", "Stellar").build())
# Sign with preimage
manage_data_transaction.sign_hashx(preimage)
manage_data_transaction_response = server.submit_transaction(
    manage_data_transaction)
print(f"manage_data_transaction_response: {manage_data_transaction_response}")
Exemple #24
0
issuing_account = server.load_account(issuing_public)
customer_account = server.load_account(customer_keypair)

hello_asset = Asset("Hello", issuing_public)

# First we enable `AUTHORIZATION_CLAWBACK_ENABLED` and `AUTHORIZATION_REVOCABLE`
# flags in the issuing account
set_options_transaction = (TransactionBuilder(
    source_account=issuing_account,
    network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
    base_fee=100,
).append_set_options_op(
    set_flags=AuthorizationFlag.AUTHORIZATION_CLAWBACK_ENABLED
    | AuthorizationFlag.AUTHORIZATION_REVOCABLE).build())
set_options_transaction.sign(issuing_keypair)
resp = server.submit_transaction(set_options_transaction)
print(f"SetOptions Op Resp:\n{resp}")
print("-" * 32)

# The customer creates a trustline to accept the asset.
trust_transaction = (TransactionBuilder(
    source_account=customer_account,
    network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
    base_fee=100,
).append_change_trust_op(asset_code=hello_asset.code,
                         asset_issuer=hello_asset.issuer).build())

trust_transaction.sign(customer_keypair)
resp = server.submit_transaction(trust_transaction)
print(f"Change Trust Op Resp:\n{resp}")
print("-" * 32)
Exemple #25
0
horizon = Server("https://horizon-testnet.stellar.org")

# create keys
sender_keypair = Keypair.random()
receiver_keypair = Keypair.random()

# create accounts
url = 'https://friendbot.stellar.org'
sender_create_response = requests.get(
    url, params={'addr': sender_keypair.public_key})
print("create sender account", sender_create_response)
receiver_create_response = requests.get(
    url, params={'addr': receiver_keypair.public_key})
print("create receiver account", receiver_create_response)

# load sender account
sender_account = horizon.load_account(sender_keypair.public_key)
print("get sender account", sender_account)

# make payment
base_fee = horizon.fetch_base_fee()
transaction = (TransactionBuilder(
    source_account=sender_account,
    network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
    base_fee=base_fee,
).append_payment_op(receiver_keypair.public_key, "5.0", "XLM").build())
transaction.sign(sender_keypair)
paymnet_response = horizon.submit_transaction(transaction)
print("payment tx id", paymnet_response["id"])
Exemple #26
0
inner_source_keypair = Keypair.from_secret(
    "SC5O7VZUXDJ6JBDSZ74DSERXL7W3Y5LTOAMRF7RQRL3TAGAPS7LUVG3L")
destination_address = "GBVKI23OQZCANDUZ2SI7XU7W6ICYKYT74JBXDD2CYRDAFZHZNRPASSQK"

server = Server(horizon_url=horizon_url)
inner_account = server.load_account(inner_source_keypair)

inner_tx = (TransactionBuilder(source_account=inner_account,
                               network_passphrase=network_passphrase,
                               base_fee=50,
                               v1=True).append_payment_op(
                                   destination=destination_address,
                                   amount="100",
                                   asset_code="XLM").build())
inner_tx.sign(inner_source_keypair)

try:
    # This transaction will fail.
    tx_insufficient_fee_resp = server.submit_transaction(inner_tx)
except BadRequestError as e:
    print(e)

fee_bump_tx = TransactionBuilder.build_fee_bump_transaction(
    fee_source=fee_source_keypair,
    base_fee=200,
    inner_transaction_envelope=inner_tx,
    network_passphrase=network_passphrase)
fee_bump_tx.sign(fee_source_keypair)
response = server.submit_transaction(fee_bump_tx)
pprint.pprint(response)
Exemple #27
0
# Sponsoring Account Creation
# https://github.com/stellar/stellar-protocol/blob/master/core/cap-0033.md#example-sponsoring-account-creation
sponsor_account = server.load_account(sponsor_keypair.public_key)
sponsoring_account_creation_te = TransactionBuilder(
    source_account=sponsor_account, network_passphrase=network_passphrase
).append_begin_sponsoring_future_reserves_op(
    sponsored_id=newly_created_keypair.public_key,
    source=sponsor_keypair.public_key).append_create_account_op(
        destination=newly_created_keypair.public_key,
        starting_balance="10",
        source=sponsor_keypair.public_key
    ).append_end_sponsoring_future_reserves_op(
        source=newly_created_keypair.public_key).build()
sponsoring_account_creation_te.sign(sponsor_keypair)
sponsoring_account_creation_te.sign(new_account_secret)
sponsoring_account_creation_resp = server.submit_transaction(
    sponsoring_account_creation_te)
print(sponsoring_account_creation_resp)

# Revoke Account Sponsorship
sponsor_account = server.load_account(sponsor_keypair.public_key)
revoke_account_sponsorship_te = TransactionBuilder(
    source_account=sponsor_account, network_passphrase=network_passphrase
).append_revoke_account_sponsorship_op(
    account_id=newly_created_keypair.public_key,
    source=sponsor_keypair.public_key).build()
revoke_account_sponsorship_te.sign(sponsor_keypair)
revoke_account_sponsorship_resp = server.submit_transaction(
    revoke_account_sponsorship_te)
print(revoke_account_sponsorship_resp)
Exemple #28
0
class StellarWallet:
    """
    Stellar Hot Wallet Handler on chain
    for live net use self.server = Server(horizon_url="https://horizon.stellar.org")  # Live network

    """

    def __init__(self, horizon_url: str, integrated_coins):
        helpers = Helpers()
        secret_details = helpers.read_json_file(file_name="walletSecrets.json")  # Load Stellar wallet secrets
        public_details = helpers.read_json_file(file_name="hotWallets.json")  # Load hot wallet details
        self.integrated_coins = integrated_coins
        self.public_key = public_details["xlm"]
        self.dev_key = public_details["xlmDev"]
        self.private_key = secret_details['stellar']
        self.root_keypair = Keypair.from_secret(self.private_key)
        self.root_account = Account(account_id=self.root_keypair.public_key, sequence=1)
        self.server = Server(horizon_url=horizon_url)  # Testnet

        # Decide network type
        if horizon_url == "https://horizon-testnet.stellar.org":
            self.network_phrase = Network.TESTNET_NETWORK_PASSPHRASE
            self.network_type = 'testnet'
        else:
            self.network_phrase = Network.PUBLIC_NETWORK_PASSPHRASE
            self.network_type = 'pub-net'

    def create_stellar_account(self):
        """
        Creates inactive stellar account which needs to be activated by depositing lumens
        """
        try:
            key_pair = Keypair.random()
            public_key = key_pair.public_key
            private_key = key_pair.secret
            return {f'address': f'{public_key}',
                    f'secret': f'{private_key}',
                    "network": f'{self.network_type}'}
        except NotFoundError:
            return {}

    def generate_uri(self, address: str, memo: str):

        """
        Returns Transaction as envelope
        """

        return stellar_uri.PayStellarUri(destination=address,
                                         memo=TextMemo(text=memo),
                                         asset=Asset.native(),
                                         network_passphrase=self.network_phrase,
                                         message='Deposit to Discord',
                                         ).to_uri()

    @staticmethod
    def __filter_error(result_code):
        if 'op_no_trust' in result_code:
            return 'no trust'
        elif 'op_no_source_account' in result_code:
            return 'No source account provided'
        else:
            return result_code

    def check_if_account_activate(self, address):
        "Try to load account on the network"
        try:
            self.server.load_account(account_id=address)
            return True
        except NotFoundError:
            return False

    def get_stellar_hot_wallet_details(self):
        """
        Return the stellar hot wallet balance
        :return:
        """
        data = self.server.accounts().account_id(account_id=self.public_key).call()
        if 'status' not in data:
            data.pop('_links')
            data.pop('data')
            data.pop('flags')
            data.pop('last_modified_ledger')
            data.pop('sequence')
            data.pop('subentry_count')
            data.pop('thresholds')
            data.pop('signers')
            data.pop('id')
            data.pop('paging_token')
            return data
        else:
            return {}

    def decode_transaction_envelope(self, envelope_xdr):
        """
        Decode envelope and get details
        Credits to overcat :
        https://stellar.stackexchange.com/questions/3022/how-can-i-get-the-value-of-the-stellar-transaction/3025#3025
        :param envelope_xdr: Xdr envelope from stellar network
        :return: Decoded transaction details
        """
        te = TransactionEnvelope.from_xdr(envelope_xdr, self.network_phrase)
        operations = te.transaction.operations

        # TODO make multiple payments inside one transaction
        for op in operations:
            if isinstance(op, Payment):
                asset = op.asset.to_dict()
                if asset.get('type') == 'native':
                    asset['code'] = 'XLM'  # Appending XLM code to asset incase if native
                asset["amount"] = op.to_xdr_amount(op.amount)
                # TODO count all deposits
                return asset

    def get_incoming_transactions(self, pag=None):
        """
        Gets all incoming transactions and removes certain values
        :return: List of incoming transfers
        """
        data = self.server.transactions().for_account(account_id=self.public_key).include_failed(False).order(
            desc=False).cursor(cursor=pag).limit(200).call()
        to_process = list()
        for tx in data['_embedded']['records']:
            # Get transaction envelope
            if tx['source_account'] != self.public_key and tx['successful'] is True:  # Get only incoming transactions
                tx.pop('_links')
                tx.pop('fee_charged')
                tx.pop('id')
                tx.pop('fee_account')
                tx.pop('fee_meta_xdr')
                tx.pop('ledger')
                tx.pop('max_fee')
                tx.pop('operation_count')
                tx.pop('result_meta_xdr')
                tx.pop('result_xdr')
                tx.pop('signatures')
                tx['asset_type'] = self.decode_transaction_envelope(envelope_xdr=tx['envelope_xdr'])
                tx.pop('envelope_xdr')
                to_process.append(tx)
        return to_process

    @staticmethod
    def check_if_memo(memo):
        """
        Check if memo has been provided
        :param memo:
        :return:
        """
        if memo != 'none':
            return True
        else:
            return False

    def token_withdrawal(self, address, token, amount: str):
        """
        Amount as full
        """

        if token != 'xlm':
            asset_issuer = self.integrated_coins[token.lower()]["assetIssuer"]
        else:
            asset_issuer = None

        source_account = self.server.load_account(self.public_key)
        tx = TransactionBuilder(
            source_account=source_account,
            network_passphrase=self.network_phrase,
            base_fee=self.server.fetch_base_fee()).append_payment_op(
            asset_issuer=asset_issuer,
            destination=address, asset_code=token.upper(), amount=amount).set_timeout(30).build()
        tx.sign(self.root_keypair)
        try:
            resp = self.server.submit_transaction(tx)
            details = self.decode_transaction_envelope(envelope_xdr=resp['envelope_xdr'])
            end_details = {
                "asset": details['code'],
                "explorer": resp['_links']['transaction']['href'],
                "hash": resp['hash'],
                "ledger": resp['ledger'],
                "destination": address,
                "amount": details['amount']
            }
            return end_details
        except exceptions.BadRequestError as e:
            # get operation from result_codes to be processed
            error = self.__filter_error(result_code=e.extras["result_codes"]['operations'])
            return {

                "error": f'{error} with {token.upper()} issuer'
            }

    def establish_trust(self, private_key, token):
        """
        Amount as full
        """
        # Load user secret and get account

        user_key_pair = Keypair.from_secret(private_key)
        root_account = Account(account_id=user_key_pair.public_key, sequence=1)
        public_key = root_account.account_id
        asset_issuer = self.integrated_coins[token.lower()]["assetIssuer"]

        try:
            source_account = self.server.load_account(public_key)
            tx = TransactionBuilder(
                source_account=source_account,
                network_passphrase=self.network_phrase,
                base_fee=self.server.fetch_base_fee()).append_change_trust_op(asset_code=f'{token.upper()}',
                                                                              asset_issuer=asset_issuer).set_timeout(
                30).build()
            tx.sign(private_key)

            self.server.submit_transaction(tx)
            return True
        except exceptions.NotFoundError:
            return False
Exemple #29
0
random_keypair = Keypair.random()
random_keypair_pub_key = random_keypair.public_key
random_keypair_priv_key = random_keypair.secret

# 3. Fund Another account using TestBot
print("Funding Random Account...")

url = 'https://friendbot.stellar.org'
response = requests.get(url, params={'addr': random_keypair.public_key})
print(f"Friendbot responded with {response}")

# 4. Use said account to fund my account
print("Building Transaction...")

base_fee = server.fetch_base_fee()
random_account = server.load_account(random_keypair_pub_key)

transaction = (TransactionBuilder(
    source_account=random_account,
    network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
    base_fee=base_fee,
).append_create_account_op(
    destination=quest_account_pub_key,
    starting_balance="1000",
).build())
print('Signing Transaction...')
transaction.sign(random_keypair)
response = server.submit_transaction(transaction)

print(f"This is the final response: {response}")
Exemple #30
0
class stellarWrapper:
    def __init__(self, network='test'):
        if network == 'test':
            self.server = Server("https://horizon-testnet.stellar.org")

    @staticmethod
    def create_account():
        kp = Keypair.random()
        print("Public Key is " + kp.public_key)
        print("Secret Seed is " + kp.secret)
        return kp

    @staticmethod
    def fund_test_account(publicKey):
        url = 'https://friendbot.stellar.org'
        res = requests.get(url, params={'addr': publicKey})
        print(res)

    def load_account(self, publicKey):
        account = self.server.load_account(publicKey)
        print(account)
        return account

    def load_server_account(self, publicKey):
        accountDetails = self.server.accounts().account_id(publicKey).call()
        print(accountDetails)
        return accountDetails

    def get_threshold(self, publicKey):
        accountDetails = self.load_server_account(publicKey)
        return accountDetails['thresholds']

    def get_native_balance(self, publicKey):
        accountDetails = self.load_server_account(publicKey)
        for x in accountDetails['balances']:
            if x['asset_type'] == 'native':
                return x['balance']

    def get_sequence(self, publicKey):
        accountDetails = self.load_server_account(publicKey)
        return accountDetails['sequence']

    def create_transaction(self, sourceAccountPublicKey, operationList):
        sourceAccount = self.load_account(sourceAccountPublicKey)
        transactionBuilder = TransactionBuilder(
            source_account=sourceAccount,
            network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE)
        #for operation in operationList:
        #    transactionBuilder.append_operation(operation)
        txnEnv = transactionBuilder.build()
        return txnEnv.to_xdr()

    @staticmethod
    def signTransaction(txnXdr, signature):
        txnEnv = TransactionEnvelope.from_xdr(txnXdr)
        txnEnv.sign(signature)
        txnEnv.to_xdr()

    def submitTransaction(self, txnXdr):
        txnEnv = Transaction.from_xdr(txnXdr)
        res = self.server.submit_transaction(txnEnv)
        print(res)
        return res