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
def merge_account(self, address): """ Delete the wallet and send all funds to the specified address :param address: address to send funds to :return: tx hash """ self.check_and_update_created_on_network() if not self.created_on_network: return fail( RuntimeError( 'Cannot do account merge operation: account is not created on network' )) self._logger.info( 'Deleting wallet and sending all funds to address %s', address) network = Network.PUBLIC_NETWORK_PASSPHRASE if not self.testnet else Network.TESTNET_NETWORK_PASSPHRASE tx = TransactionBuilder( source_account=self.account, base_fee=self.provider.get_base_fee(), network_passphrase=network, ).append_account_merge_op(address).build() tx.sign(self.keypair) xdr_tx_envelope = tx.to_xdr() tx_hash = self.provider.submit_transaction(xdr_tx_envelope) self.created_on_network = False return succeed(tx_hash)
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 remove_signer(self, public_key_signer): """remove_signer removes a public key as a signer from the source account :param public_key_signer: public key of an account :type public_key_signer: str """ account = self.load_account() horizon_server = self._get_horizon_server() base_fee = horizon_server.fetch_base_fee() tx = TransactionBuilder( account, network_passphrase=_NETWORK_PASSPHRASES[str(self.network)], base_fee=base_fee).append_ed25519_public_key_signer( public_key_signer, 0).build() source_keypair = Keypair.from_secret(self.secret) tx.sign(source_keypair) try: response = horizon_server.submit_transaction(tx) self._log_info(response) self._log_info("Multisig tx signed and sent") except BadRequestError: self._log_info( "Transaction need additional signatures in order to send") return tx.to_xdr()
def mainLoop(): account=server.load_account(keypair.public_key) print("account fetched") fee=server.fetch_base_fee() #Run everything! while True: print("main loop") #Construct TXN data=getNextData() memo_to_write=str(data[0]) txn=TransactionBuilder( source_account=account, network_passphrase=NET_PASS, base_fee=fee ).add_text_memo(memo_to_write).append_payment_op( destination=keypair.public_key, asset_code="XLM", amount="0.00001").set_timeout(100000).build() #sign and submit txn.sign(keypair) while sendTXN(txn) is False: time.sleep(4) while updateDBRecord(data[1]) is False: time.sleep(5) print("txn sent, db updated")
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 setup_multisig(): client_master_account = server.load_account( client_master_keypair.public_key) te = TransactionBuilder(client_master_account, network_passphrase) \ .append_ed25519_public_key_signer(client_signer_keypair1.public_key, 40) \ .append_ed25519_public_key_signer(client_signer_keypair2.public_key, 60) \ .append_set_options_op(master_weight=0, low_threshold=1, med_threshold=10, high_threshold=100) \ .build() te.sign(client_master_keypair) resp = server.submit_transaction(te) print(resp)
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 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 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]
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' }
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)
transaction = TransactionBuilder( source_account=root_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=100) \ .append_set_options_op( master_weight=1, # set master key weight low_threshold=1, med_threshold=2, # a payment is medium threshold high_threshold=2, # make sure to have enough weight to add up to the high threshold! signer=secondary_signer) \ .set_timeout(30) \ .build() # only need to sign with the root signer as the 2nd signer won't # be added to the account till after this transaction completes transaction.sign(root_keypair) response = server.submit_transaction(transaction) print(response) # now create a payment with the account that has two signers destination = "GBA5SMM5OYAOOPL6R773MV7O3CCLUDVLCWHIVVL3W4XTD3DA5FJ4JSEZ" transaction = TransactionBuilder( source_account=root_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=100) \ .append_payment_op( destination=destination, amount="2000", asset_code="XLM") \ .set_timeout(30) \ .build()
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) # submit the transaction to the server response = server.submit_transaction(transaction)
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 sponsor_account = server.load_account(sponsor_keypair.public_key) revoke_account_sponsorship_te = TransactionBuilder( source_account=sponsor_account, network_passphrase=network_passphrase ).append_revoke_account_sponsorship_op( account_id=newly_created_keypair.public_key, source=sponsor_keypair.public_key).build() revoke_account_sponsorship_te.sign(sponsor_keypair) revoke_account_sponsorship_resp = server.submit_transaction( revoke_account_sponsorship_te)
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
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() transaction.sign(quest_account_priv_key) transaction.sign(other_account_priv_key) response = server.submit_transaction(transaction) print(f"This is the final response: {response}")
from stellar_sdk import TransactionBuilder, Server, Network, Keypair server = Server(horizon_url="https://horizon-testnet.stellar.org") source = Keypair.from_secret( "SBFZCHU5645DOKRWYBXVOXY2ELGJKFRX6VGGPRYUWHQ7PMXXJNDZFMKD") destination = Keypair.random() source_account = server.load_account(account_id=source.public_key) transaction = TransactionBuilder( source_account=source_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=100) \ .append_create_account_op(destination=destination.public_key, starting_balance="12.25") \ .build() transaction.sign(source) response = server.submit_transaction(transaction) print("Transaction hash: {}".format(response["hash"])) print( "New Keypair: \n\taccount id: {account_id}\n\tsecret seed: {secret_seed}". format(account_id=destination.public_key, secret_seed=destination.secret))