def verify_destination(public_key): server = Server("https://horizon-testnet.stellar.org") try: server.load_account(public_key) except NotFoundError: return False return True
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_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
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]
def verificarCuentaActivada(self, destino): server = Server(horizon_url=self.Horizon_url) try: transactions = server.load_account(account_id=destino) return [True, transactions] except exceptions.NotFoundError as e: return [False, e]
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)
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))
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
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 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 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 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 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]
# The following source key was created by the friendbot at https://laboratory.stellar.org/#account-creator?network=test # before running this example create a new account, fund it and then copy and paste the # secret key where the current key is. source_secret_key = "SC7AUS23UKVZQL5KMIK4ZK3EZJUS6ZVMTQSVLH3VIK42W6RBQAQXOVQX" # The following obtains the keypair of the source account we will be dealing with. source_keypair = Keypair.from_secret(source_secret_key) source_public_key = source_keypair.public_key # This is the public key of another account created by the friendbot. When I wrote this # code it was active on the test network, but I would recommened creating a new account # the same way the source account was created. destination_public_key = "GANXMF6DCQNHZP5ULDONM4VNXBV5YECTDGLGXCESXNT66H6AZSAHLFGK" # loads the source account from the testnet source_account = server.load_account(source_public_key) # builds the transaction that merges the two accounts. # The current code uses the testnetwork and if you wanted to use # the public network 'Network.TESTNET_NETWORK_PASSPHRASE' would # have to be replaced with 'Network.PUBLIC_NETWORK_PASSPHRASE'. transaction = TransactionBuilder( source_account=source_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=100) \ .append_account_merge_op(destination=destination_public_key) \ .build() # source account signs the transaction transaction.sign(source_keypair)
from stellar_sdk import Keypair, Server, TransactionBuilder, Network, Asset server = Server(horizon_url="https://horizon-testnet.stellar.org") source_keypair = Keypair.from_secret( "SA6XHAH4GNLRWWWF6TEVEWNS44CBNFAJWHWOPZCVZOUXSQA7BOYN7XHC") source_account = server.load_account(account_id=source_keypair.public_key) path = [ Asset("USD", "GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB"), Asset("EUR", "GDTNXRLOJD2YEBPKK7KCMR7J33AAG5VZXHAJTHIG736D6LVEFLLLKPDL") ] transaction = TransactionBuilder( source_account=source_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=100) \ .append_path_payment_strict_receive_op(destination="GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB", send_code="XLM", send_issuer=None, send_max="1000", dest_code="GBP", dest_issuer="GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW", dest_amount="5.50", path=path) \ .set_timeout(30) \ .build() transaction.sign(source_keypair) response = server.submit_transaction(transaction)
import pprint from stellar_sdk import Keypair, Server, TransactionBuilder, Network from stellar_sdk.exceptions import BadRequestError horizon_url = "https://horizon-testnet.stellar.org/" network_passphrase = Network.TESTNET_NETWORK_PASSPHRASE fee_source_keypair = Keypair.from_secret( "SASZKBDB6PFHXN6LRH4NQNTRGLGDTI3PSUVIKMZMLTYYBB7NDVMA6DSL") 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)
from stellar_sdk import Server, TransactionBuilder, Keypair, Network sponsor_secret = "SAOJHTVFCYVKUMPNQI7RUSI566GKWXP7RXOHP4SV6JAVUQKSIWGPZFPJ" new_account_secret = "SCN5D72JHQAHUHGIA23SLS3LBYCPHJWD7HLYNJRBBZIG4PD74UCGQBYM" sponsor_keypair = Keypair.from_secret(sponsor_secret) newly_created_keypair = Keypair.from_secret(new_account_secret) server = Server("https://horizon-testnet.stellar.org") network_passphrase = Network.TESTNET_NETWORK_PASSPHRASE # 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
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)
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"]
print("Funding Random Account...") url = 'https://friendbot.stellar.org' response = requests.get(url, params={'addr': random_keypair_pub_key}) print(f"Friendbot responded with {response}") print("Funding Personal Account...") response = requests.get(url, params={'addr': quest_account_pub_key}) print(f"Friendbot responded with {response}") # 4. Create an object to represent the new asset asset = Asset("[FIGURE IT OUT]", random_keypair_pub_key) # 5. Allow for clawbacks base_fee = server.fetch_base_fee() stellar_account = server.load_account(quest_account_pub_key) print("Allowing Clawbacks...") transaction = ( TransactionBuilder( source_account=stellar_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=base_fee, ).append_set_options_op( set_flags= 10 # Authorization clawback enabled (8) + Authorization revocable (2) = 10 ).build()) print('Signing Transaction...') transaction.sign(quest_account_priv_key)
submitted to the network with x as a signature. This means anyone will be able to sign for that account with the hash(x) signer at that point. Often you want there to be additional signers so someone must have a particular secret key and know x in order to reach the weight threshold required to authorize transactions on the account. """ import hashlib from stellar_sdk import Server, TransactionBuilder, Network, Keypair server = Server(horizon_url="https://horizon-testnet.stellar.org") 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}")
server = Server(horizon_url="https://horizon-testnet.stellar.org") # Key for asset issuer # GDUGCRQWFXZM4MJ2VOEDNG5WZDJQKOP6CNMFHNL4Z4WFT2JMXOGLXD2K issuing_keypair = Keypair.from_secret( "SD3REN5OX2QR7PSWANAKKUQGXOHGCVUG2ZQ7OIJY2IN3O4CXWT42KSM2") issuing_public = issuing_keypair.public_key # Key for customer # GDEHVYLEMNKXMT75TOSB7SMPVZYFSAV7PKLO3O6JJ4RV7PONOXAN2Y6L customer_keypair = Keypair.from_secret( "SDG5FE6JR4VHXAEIT6KGGARWOLZF2ZSUV6VOP2JSOFOM7I65D7RKFLER") customer_public = customer_keypair.public_key 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)
# 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 other_account = Keypair.random() other_account_pub_key = other_account.public_key other_account_priv_key = other_account.secret # 2. Create Transaction print("Building Transaction...") base_fee = server.fetch_base_fee() account = server.load_account(quest_account_pub_key) transaction = TransactionBuilder( source_account=account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=base_fee, ).append_begin_sponsoring_future_reserves_op( sponsored_id=other_account_pub_key, source=quest_account_pub_key ).append_create_account_op( destination=other_account_pub_key, starting_balance="0", source=quest_account_pub_key ).append_end_sponsoring_future_reserves_op( source=other_account_pub_key ).build()
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"])
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
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}")
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