def test_network_and_horizon(self, setup, test_data): builder = Builder(secret=test_data.cold_secret, sequence=100, network='MOE') assert builder.network == 'MOE' assert builder.horizon.horizon_uri == horizon_testnet().horizon_uri builder = Builder(secret=test_data.cold_secret, sequence=100, network='testnet') assert builder.network == 'TESTNET' assert builder.horizon.horizon_uri == horizon_testnet().horizon_uri builder = Builder(secret=test_data.cold_secret, sequence=100, network='public') assert builder.network == 'PUBLIC' assert builder.horizon.horizon_uri == horizon_livenet().horizon_uri builder = Builder(secret=test_data.cold_secret, sequence=100, network='public', horizon_uri=setup.horizon_endpoint_uri) assert builder.network == 'PUBLIC' assert builder.horizon.horizon_uri == Horizon( horizon_uri=setup.horizon_endpoint_uri).horizon_uri
def opr_change_trust(asset_object, receiver_address, receiver_seed): horizon = horizon_testnet() sequence = horizon.account(receiver_address).get('sequence') print(sequence) op = ChangeTrust( asset=asset_object, limit='5000', source=receiver_address ) # print(op.__dict__) msg = TextMemo('Change Trust Operation') receiving_account = Keypair.from_seed(receiver_seed) tx = Transaction( source=receiving_account.address().decode(), sequence=sequence, time_bounds=None, memo=msg, fee=None, operations=[op], ) envelope = Te(tx=tx, signatures=None, network_id="TESTNET") envelope.sign(receiving_account) xdr_envelope = envelope.xdr() response = horizon.submit(xdr_envelope) print(response) if 'result_xdr' in response: print('Successful') else: print('Things go Fishy')
def create_account(user): # type: (User) -> None # create keypair keypair = Keypair.random() public_key = keypair.address().decode() seed = keypair.seed().decode() # store account StellarAccount.objects.create(seed=seed, address=public_key, user=user, balance=0.0) horizon = horizon_testnet() if settings.DEMO_MODE else horizon_livenet() # fund account if settings.DEMO_MODE: for _ in range(5): # noinspection PyBroadException try: funding_keypair = Keypair.from_seed( settings.FUNDING_ACCOUNT_SEED) # create operation create_account_operation = CreateAccount({ 'destination': public_key, 'starting_balance': '1' }) # create transaction sequence = horizon.account( funding_keypair.address().decode()).get('sequence') tx = Transaction(source=funding_keypair.address().decode(), opts={ 'sequence': sequence, 'memo': TextMemo('Creating new Zendi account.'), 'operations': [create_account_operation] }) # create and sign envelope envelope = TransactionEnvelope(tx=tx, opts={"network_id": "TESTNET"}) envelope.sign(funding_keypair) # Submit the transaction to Horizon te_xdr = envelope.xdr() horizon.submit(te_xdr) break except Exception as ex: logger.error('Error while funding account', ex) time.sleep(1) logger.info('Created Stellar Lumen account {} for {}'.format( public_key, user))
def send_xlm_vault_transaction(user, destination, amount): from stellar_base.transaction import Transaction wallet = VaultWallet.objects.get(username=user, name="xlm") User = Keypair.from_seed(wallet.private) horizon = horizon_testnet() asset = Asset.native() op = Payment({ 'destination': destination, 'asset': asset, 'amount': amount }) msg = TextMemo('From test net !') sequence = horizon.account(User.address().decode('utf-8')).get('sequence') tx = Transaction( source=User.address().decode(), opts={ 'sequence': sequence, 'memo': msg, 'operations': [ op, ], }, ) try: envelope = Te(tx=tx, opts={"network_id": "TESTNET"}) envelope.sign(User) xdr = envelope.xdr() response = horizon.submit(xdr) return response['hash'] except: return {"error": ""}
def test_create_pool_account(self): account_kp = Keypair.random() pool_kp = Keypair.random() # fixture for getting the account responses.add(responses.GET, 'https://horizon-testnet.stellar.org/accounts/%s' % (account_kp.address().decode()), body=json.dumps({'sequence': '1234'}), content_type='application/json') # fixture for creating a transaction responses.add(responses.POST, 'https://horizon-testnet.stellar.org/transactions/', body=json.dumps({ '_links': { 'transaction': { 'href': 'http://transaction-url/' } } }), content_type='application/json') self.assertTrue( create_pool_account(horizon_testnet(), 'TESTNET', account_kp.seed(), pool_kp))
def transfer_fund(amount, asset_object, customer_account, issuer_account, issuer_seed): horizon = horizon_testnet() print('Transferring fund to {}'.format(customer_account)) op = Payment(destination=customer_account, asset=asset_object, amount=str(amount), source=issuer_account) msg = TextMemo('Your first Payment !') sequence = horizon.account(issuer_account).get('sequence') tx = Transaction( source=issuer_account, sequence=sequence, memo=msg, fee=None, operations=[op], ) issuer_account1 = Keypair.from_seed(issuer_seed) envelope = Te(tx=tx, signatures=None, network_id="TESTNET") envelope.sign(issuer_account1) xdr_envelope = envelope.xdr() response = horizon.submit(xdr_envelope) print(response) if 'result_xdr' in response: print('Successful Transfer') else: print('Things go Fishy')
def test_set_account_signers(self): pool_kp = Keypair.random() signer1 = Keypair.random() signer2 = Keypair.random() # fixture for getting the account responses.add(responses.GET, 'https://horizon-testnet.stellar.org/accounts/%s' % (pool_kp.address().decode()), body=json.dumps({'sequence': '1234'}), content_type='application/json') # fixture for creating a transaction responses.add(responses.POST, 'https://horizon-testnet.stellar.org/transactions/', body=json.dumps({ '_links': { 'transaction': { 'href': 'http://transaction-url/' } } }), content_type='application/json') signers_file = self.mock_signers_file([ signer1, signer2, ]) signers = get_signers(signers_file.name) self.assertTrue( set_account_signers(horizon_testnet(), pool_kp, signers, SIGNING_THRESHOLD))
def main( desired_tail, funding_account_secret_key, network_id, signers_file): horizon = (horizon_livenet() if network == 'PUBLIC' else horizon_testnet()) pool_kp = generate_pool_keypair(desired_tail) logger.info("Pool keypair: %s | %s" % ( pool_kp.address().decode(), pool_kp.seed().decode())) if create_pool_account( horizon, network_id, funding_account_secret_key, pool_kp): signers = get_signers(signers_file) set_account_signers(horizon, pool_kp, signers, SIGNING_THRESHOLD)
def transaction( ): # Performs the transaction from one to another thus providing the current balance. amount = str(request.form['amount']) # Amount taken from the user. memo = TextMemo(request.form['memo']) # Memo entered by user. send = Keypair.from_seed(send_seed) horizon = horizon_testnet() asset = Asset('XLM') op = Payment({ 'destination': receive_publickey, 'asset': asset, 'amount': amount, }) sequence = horizon.account(send.address()).get('sequence') tx = Transaction( source=send.address().decode(), opts={ 'sequence': sequence, 'memo': memo, 'fee': 100, 'operations': [ op, ], }, ) envelope = Te(tx=tx, opts={"network_id": "TESTNET"}) envelope.sign(send) xdr = envelope.xdr() response = horizon.submit(xdr) trans = response['_links'] for values in trans.itervalues(): for confirmation in values.itervalues(): confirm = confirmation address1.get() # Receiving balance info in JSON format address2.get() for a1 in address1.balances: send_current = a1[ 'balance'] # Retrieving the eaxct balance info fron JSON. for a2 in address2.balances: receive_current = a2['balance'] cbalance = { # Current balance. 'send_current': send_current, 'receive_current': receive_current, 'confirm': confirm, # 'amount': amount, } return render_template("transaction.html", cbalance=cbalance)
def perform_transaction(self): send_seed = self.seed1 recieve_address = self.publickey2 amount = str(input("\nEnter the amount to be transferred(0-9998): ")) print("0.0000100 will be charged extra for the transaction") send = Keypair.from_seed(send_seed) horizon = horizon_testnet() asset = Asset('XLM') op = Payment({ 'destination': recieve_address, 'asset': asset, 'amount': amount, }) msg = TextMemo('Transaction Test') print("Transferring the ammount to the Receiver......") sequence = horizon.account(send.address()).get('sequence') tx = Transaction( source=send.address().decode(), opts={ 'sequence': sequence, 'memo': msg, 'fee': 100, 'operations': [ op, ], }, ) envelope = Te(tx=tx, opts={"network_id": "TESTNET"}) envelope.sign(send) xdr = envelope.xdr() response = horizon.submit(xdr) print("Transaction completed successfully.\n") trans = response['_links'] for values in trans.itervalues(): for confirmation in values.itervalues(): print("Confirmation Link: " + confirmation) print( "\n------------------------------------------------------------------------------" ) print("\nChecking the current balance......")
def connect_horizon(): horizon = horizon_testnet() return horizon
def get_transaction(cls, transaction_hash): # horizon = horizon_livenet() for LIVENET horizon = horizon_testnet() return horizon.transaction(transaction_hash)
def send_payment(sender_seed, tx): # Generate the sender's Keypair for signing and setting as the source sender_kp = Keypair.from_seed(sender_seed) tx = {key.decode("utf-8"): val.decode("utf-8") for key, val in tx.items()} # Address for the destination destination = tx.get("to") # create op amount = tx.get("amount") if tx.get("currency").upper() == "XLM": asset = Asset("XLM") else: raise UnknownIssuerError("Unknown currency and/or issuer.") # TODO: # Issuer's address # ISSUER = tx.get('issuer') # asset = Asset(tx.get('currency').upper(), ISSUER) op = Payment( # Source is also inferred from the transaction source, so it's optional. source=sender_kp.address().decode(), destination=destination, asset=asset, amount=amount, ) # create a memo msg = TextMemo("Stellar-SMS is dope!!!") horizon = horizon_testnet() # horizon = horizon_livenet() for LIVENET # Get the current sequence of sender sequence = horizon.account( sender_kp.address().decode("utf-8")).get("sequence") # TODO: track sequence locally for better accuracy, speed, and robustness # Construct a transaction tx = Transaction( source=sender_kp.address().decode(), sequence=sequence, # time_bounds = {'minTime': 1531000000, 'maxTime': 1531234600}, memo=msg, fee=100, # Can specify a fee or use the default by not specifying it operations=[op], ) # Build transaction envelope envelope = Te(tx=tx, network_id="TESTNET") # or 'PUBLIC' # Sign the envelope envelope.sign(sender_kp) # Submit the transaction to Horizon! xdr = envelope.xdr() response = horizon.submit(xdr) log.debug(str(response)) if response.get("status") not in [None, 200]: log.error( f"Submission unsuccessful. Horizon retured with error: {response.detail}" ) return log.debug("Transaction was successfully submitted to the network.") return True
def __init__(self, base_seed='', horizon_endpoint_uri='', network='PUBLIC', channel_seeds=[]): """Create a new instance of the KIN SDK for Stellar. If seed is not provided, the SDK can still be used in "anonymous" mode with only the following functions available: - get_address_lumen_balance - get_address_kin_balance - check_kin_trusted - check_account_exists - get_account_data - get_transaction_data - monitor_address_transactions :param str seed: a seed to initialize the sdk wallet account with. If not provided, the wallet will not be initialized and methods needing the wallet will raise exception. :param str horizon_endpoint_uri: a Horizon endpoint. If not provided, a default endpoint will be used, either a testnet or pubnet, depending on the `network` parameter. :param str network: either PUBLIC or TESTNET, will set the Horizon endpoint in the absence of `horizon_endpoint_uri`. :param list channel_seeds: a list of channels to sign transactions with. More channels means less blocking on transactions and better response time. :return: An instance of the SDK. :rtype: :class:`~kin.SDK` :raises: :class:`~kin.SdkConfigurationError` if some of the configuration parameters are invalid. """ self.network = network if not self.network: self.network = 'PUBLIC' if horizon_endpoint_uri: self.horizon = Horizon(horizon_endpoint_uri) else: if self.network == 'TESTNET': self.horizon = horizon_testnet() else: self.horizon = horizon_livenet() # check Horizon connection try: self.horizon.query('') except Exception as e: raise SdkConfigurationError('cannot connect to horizon') # init sdk account base_keypair if a base_seed is supplied self.base_keypair = None if base_seed: try: validate_seed(base_seed) except ValueError: raise SdkConfigurationError('invalid base seed: {}'.format(base_seed)) self.base_keypair = Keypair.from_seed(base_seed) # check channel seeds if channel_seeds: for channel_seed in channel_seeds: try: validate_seed(channel_seed) except ValueError: raise SdkConfigurationError('invalid channel seed: {}'.format(channel_seed)) else: channel_seeds = [base_seed] # init channel manager self.channel_manager = ChannelManager(base_seed, channel_seeds, self.network, self.horizon.horizon)
logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) fileHandler = logging.FileHandler("{0}/{1}.log".format(logDir, "main")) fileHandler.setFormatter(logFormatter) logger.addHandler(fileHandler) consoleHandler = logging.StreamHandler(sys.stdout) consoleHandler.setFormatter(logFormatter) logger.addHandler(consoleHandler) # print("Connecting to horizon-testnet...") logger.info("Connecting to horizon-testnet...") # GA7QE55JGHFT5OKB2WKFFVKAPLQSEAWILETXT63QA56HHU6PLZBOOOOO SBO3GNKMDNN5GUE6Z6AODW4UEZXGIRLMXRA4SBL2O2PPBO4UZOPDBJSY # noqa horizon = horizon_testnet() stream = horizon.operations(sse=True) INFLATION_TYPE = 9 POOL_ADDRESS = "GCFXD4OBX4TZ5GGBWIXLIJHTU2Z6OWVPYYU44QSKCCU7P2RGFOOHTEST" logger.info("Connected! Watching for inflation operation...") def investigate_inflation(effects_link): res = requests.get(effects_link) effects = res.json()["_embedded"]["records"] found = False for record in effects: if record["account"] == POOL_ADDRESS: logger.info("Paying out " + record["amount"]) start_payout(record["amount"])
from stellar_base.keypair import Keypair from stellar_base.asset import Asset from stellar_base.operation import Payment, SetOptions from stellar_base.transaction import Transaction from stellar_base.transaction_envelope import TransactionEnvelope as Te from stellar_base.memo import TextMemo from stellar_base.horizon import horizon_testnet, horizon_livenet alice_seed = 'SBUORYV26AZ3ULEEC5FQ4NKPVRO7MBAWTW26YKCDPPKFGMK7WAYNX4UN' bob_address = 'GBZF7GQJXXHD3OL3B5IOUICFDYIATZZ3F3XQ7SOQ5PXLVQMDSOI5ACEE' Alice = Keypair.from_seed(alice_seed) horizon = horizon_testnet() # for TESTNET # horizon = horizon_livenet() # for LIVENET # create op payment_op = Payment( # source=Alice.address().decode(), destination=bob_address, asset=Asset('XLM'), amount='10.5') set_home_domain_op = SetOptions(home_domain='fed.network') # create a memo msg = TextMemo('Buy yourself a beer!') # get sequence of Alice # Python 3 sequence = horizon.account(Alice.address().decode('utf-8')).get('sequence') # Python 2
from stellar_base.asset import Asset from stellar_base.operation import Payment from stellar_base.transaction import Transaction from stellar_base.transaction_envelope import TransactionEnvelope as Te from stellar_base.memo import TextMemo from stellar_base.horizon import horizon_testnet, horizon_livenet alice_seed = 'SAZJ3EDATROKTNNN4WZBZPRC34AN5WR43VEHAFKT5D66UEZTKDNKUHOK' bob_address = 'GDLP3SP4WP72L4BAJWZUDZ6SAYE4NAWILT5WQDS7RWC4XCUNUQDRB2A4' CNY_ISSUER = 'GDVDKQFP665JAO7A2LSHNLQIUNYNAAIGJ6FYJVMG4DT3YJQQJSRBLQDG' amount = '100' # This is the new account ID (the StrKey representation of your newly # created public key). This is the destination account. new_account_addr = "GXXX" Alice = Keypair.from_seed(alice_seed) horizon = horizon_testnet() # horizon = horizon_livenet() for LIVENET asset = Asset('CNY', CNY_ISSUER) # create op ''' op = Payment({ # 'source' : Alice.address().decode(), 'destination': bob_address, 'asset': asset, 'amount': amount }) ''' op = CreateAccount({ 'destination': new_account_addr, 'starting_balance': amount })