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 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 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 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 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 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 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]
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}")
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
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): # pragma: no cover 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): # pragma: no cover 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, accounts[issuer.public_key], home_domain) def set_home_domain(self, issuer: Keypair, issuer_json: Dict, home_domain: str): envelope = (TransactionBuilder( self.account_from_json(issuer_json), base_fee=settings.MAX_TRANSACTION_FEE_STROOPS or self.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 self.server.fetch_base_fee(), network_passphrase="Test SDF Network ; September 2015", ) balance = self.get_balance(code, issuer.public_key, 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, issuer_public_key, json) -> Optional[str]: for balance_obj in json["balances"]: if (balance_obj.get("asset_code") == code and balance_obj.get("asset_issuer") == issuer_public_key): return balance_obj["balance"]
def send_payments(percent_stakes, POT, MEMO, public=False, multiplier=0, fixed_amount=0): receipt = " \nMemo: " + MEMO + "\n\n" POT = POT[0].split(":") pot = float(POT[0]) asset = POT[1] issuer = POT[2] sender = POT[3] source_keypair = Keypair.from_secret(POT[4]) receipt += "\n from " + source_keypair.public_key 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 sendpot = [] for i in range(len(percent_stakes) - 2): if not (multiplier or fixed_amount): amt = round( pot * float(percent_stakes[i + 1][len(percent_stakes[i + 1]) - 1][:-1]) / 100, 6) elif multiplier > 0: amt = round( multiplier * float( percent_stakes[i + 1][len(percent_stakes[i + 1]) - 1]), 6) else: amt = fixed_amount if amt > 0.0000001: sendpot.append([percent_stakes[i + 1][0], amt]) for s in sendpot: try: destination_p = s[0] amount = str(s[1]) source_acc = server.load_account(sender) base_fee = server.fetch_base_fee() transaction = TransactionBuilder( source_account=source_acc, network_passphrase=passphrase, base_fee=base_fee).add_text_memo(MEMO).append_payment_op( destination_p, amount, asset, issuer).set_timeout(30).build() transaction.sign(source_keypair) response = server.submit_transaction(transaction) if response['successful']: receipt += "\nSuccessfully sent " + str( s[1]) + " " + asset + " to " + s[0] else: print("\n something went wrong...") except: receipt += "\nfailed to send " + str( s[1]) + " " + asset + " to " + s[0] return sendpot, receipt