def handle(self, *args, **options): server = Server(horizon_url="https://horizon-testnet.stellar.org") ledgers = server.ledgers().order(desc=True).call() Ledger.objects.all().delete() Ledger(raw_json=json.dumps(ledgers)).save()
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
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 get_balance(public_key, asset=0, public=False): if public: server = Server(horizon_url="https://horizon.stellar.org") else: server = Server(horizon_url="https://horizon-testnet.stellar.org") account = server.accounts().account_id(public_key).call() if asset: for b in account['balances']: if b['asset_code'] == asset[0] and b['asset_issuer'] == asset[ 1]: balance = float(b['balance']) break else: for b in account['balances']: if b['asset_type'] == 'native': balance = float(b['balance']) return balance
def pagoSinMemo(self, Destino, monto): 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) 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)) \ .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: return [False, d]
async def test_check_memo_required_with_no_destination_operation_async( self, httpserver): self.__inject_mock_server(httpserver) horizon_url = httpserver.url_for("/") keypair = Keypair.from_secret( "SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY") account = Account(keypair.public_key, 1) async with Server(horizon_url, AiohttpClient()) as server: transaction = (TransactionBuilder(account).append_manage_data_op( "Hello", "world").build()) transaction.sign(keypair) await server.submit_transaction(transaction)
def list_transactions(wallet_file, test_mode=True, trezor_mode=False): network_settings = get_network_settings(test_mode=test_mode) 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) server = Server(network_settings.get("horizon_url")) response = server.transactions().for_account( account_id=k.public_key).call() print(json.dumps(response, indent=4))
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)
def assetsActivo(self, direccionEmisor, codigo): pLlave = self.pLlave try: server = Server(horizon_url=self.Horizon_url) cuenta = server.accounts().account_id(pLlave).call() resultado = False for balance in cuenta['balances']: if balance['asset_type'] != 'native': if balance['asset_code'] == codigo and balance[ 'asset_issuer'] == direccionEmisor: resultado = True except exceptions.NotFoundError: return resultado return resultado
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]
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)
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'
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)
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
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 informacionAssets(self): pLlave = self.pLlave try: texto = "Assets\n➖➖➖➖➖➖➖➖➖➖➖➖➖➖\n" #asset_issuer="" server = Server(horizon_url=self.Horizon_url) cuenta = server.accounts().account_id(pLlave).call() for i in cuenta['balances']: if i['asset_type'] != "native": asset_issuer = i['asset_issuer'] texto += ("Asset Code:" + i['asset_code'] + "\n") texto += ("Limit:" + i['limit'] + "\n") Assets = server.assets().for_code( i['asset_code']).for_issuer(asset_issuer).call() for e in Assets['_embedded']['records']: texto += ("Amount:" + str(e['amount'])) texto += ("\nNum Accounts:" + str(e['num_accounts'])) texto += ("\n➖➖➖➖➖➖➖➖➖➖➖➖➖➖\n") return texto except: return "Sorry you have not created any assets, please click the button (Create Assets)"
async def test_check_memo_required_with_fee_bump_transaction_async( self, httpserver): self.__inject_mock_server(httpserver) horizon_url = httpserver.url_for("/") keypair = Keypair.from_secret( "SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY") account = Account(keypair.public_key, 1) async with Server(horizon_url, AiohttpClient()) as server: transaction = (TransactionBuilder( account, v1=True).append_payment_op( self.DESTINATION_ACCOUNT_MEMO_REQUIRED_A, "10", "XLM" ).append_path_payment_strict_receive_op( self.ACCOUNT_ID_MUXED, "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) 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, ) await server.submit_transaction(fee_bump_tx)
async def test_check_memo_required_with_account_merge_raise_async( self, httpserver): self.__inject_mock_server(httpserver) horizon_url = httpserver.url_for("/") keypair = Keypair.from_secret( "SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY") account = Account(keypair.public_key, 1) async with Server(horizon_url, AiohttpClient()) as server: 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: await server.submit_transaction(transaction) assert err.value.account_id == self.DESTINATION_ACCOUNT_MEMO_REQUIRED_D assert err.value.operation_index == 3
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))
def balance(self): pLlave = self.pLlave try: server = Server(horizon_url=self.Horizon_url) cuenta = server.accounts().account_id(pLlave).call() resultado = [] texto = "Balances:\n" if len(cuenta['balances']) > 1: for balance in cuenta['balances']: if balance['asset_type'] == 'native': texto += ("XML = " + str(balance['balance'])) else: texto += (str(balance['asset_code']) + " = " + str(balance['balance']) + "\n") else: texto += "XLM =" + str(cuenta['balances'][0]['balance']) resultado.append(True) resultado.append(texto) return resultado except exceptions.NotFoundError: texto = "su cuenta no esta activa" return [False, texto]
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]
def assetsPosibles(self): pLlave = self.pLlave try: AssetsPosibles = [] server = Server(horizon_url=self.Horizon_url) cuenta = server.accounts().account_id(pLlave).call() #Assets no creados por el for i in cuenta['balances']: if i['asset_type'] != 'native': AssetsPosibles.append((i['asset_code'], i['asset_issuer'])) # Assets no creados por el try: Assets = server.assets().for_issuer(pLlave).call() for e in Assets['_embedded']['records']: if not self.busqueda(AssetsPosibles, e['asset_code'], e['asset_issuer']): AssetsPosibles.append( (e['asset_code'], e['asset_issuer'])) except: pass texto = md.text( md.bold("Seleccione un numero Assets:")) + "\n➖➖➖➖➖➖➖➖➖➖➖➖➖➖\n" contador = 0 for i in AssetsPosibles: texto += (md.text(md.bold(str(contador))) + ". Assets Code: " + md.text(md.code(str(i[0]))) + "\n Asset Issuer:" + md.text(md.code(str(i[1]))) + "\n") texto += ("\n➖➖➖➖➖➖➖➖➖➖➖➖➖➖\n") contador += 1 return [texto, AssetsPosibles, contador] except: print("error") return []
""" Challenge 1: Create a Stellar Account """ from stellar_sdk import Server, Keypair, TransactionBuilder, Network import requests # 1. Load Keys server = Server("https://horizon-testnet.stellar.org") stellar_quest_keypair = Keypair.from_secret("Shhhhh") quest_account_pub_key = stellar_quest_keypair.public_key quest_account_priv_key = stellar_quest_keypair.secret # 2. Create Another account print("Loading Accounts...") 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)
def _get_horizon_server(self): return Server(horizon_url=_HORIZON_NETWORKS[str(self.network)])
from typing import List import dotenv import requests import stellar_sdk from stellar_sdk import Asset, Claimant from stellar_sdk import Flag as AuthFlag from stellar_sdk import Keypair, Network, Server, TransactionBuilder LUMEN_MINIMUM_SPONSORED = "10" GOVT_STIMULUS_MINIMUM_INRX = "2500" dotenv.load_dotenv(verbose=True) STELLAR_HORIZON_TESTNET = os.getenv("STELLAR_HORIZON_TESTNET") server = Server(STELLAR_HORIZON_TESTNET) fee_source_private_key = os.getenv("FEE_SOURCE_PRIVATE_KEY") distributor_inrx_private_key = os.getenv("DISTRIBUTOR_INRX_PRIVATE_KEY") issuing_public = os.getenv("ISSUING_PUBLIC") inr_asset = Asset("INRx", issuing_public) @dataclass class OrdinaryTransaction: sender_private_key: str recipient_public_key: str amount: str memo: str
def balances(pub_key): server - Server("https://horizon-testnet.stellar.org") acount = server.accounts().account_id(public_key).call() return acount['balances']
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)
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()
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 transactions(): async with Server(HORIZON_URL, AiohttpClient()) as server: async for transaction in server.transactions().cursor( cursor="now").stream(): print(f"Transaction: {transaction}")