def main(): alice = (setup_account("key.dat")) bob = setup_account("bob.dat") carol = create_empty_acct(bob) alice_addr = Address(address=alice.address()) bob_addr = Address(address=bob.address()) carol_addr = Address(address=carol.address()) dave = Keypair.random() dave_addr = Address(address=dave.address()) alice_addr.get() bob_addr.get() carol_addr.get() print("PRECONDITIONS\n") print_acct("Alice", alice_addr) print_acct("Bob", bob_addr) print_acct("Carol", carol_addr) print_acct("Dave", dave_addr) print("========================") fakeusd = Asset("USD", alice_addr.address) # Transfer Funds to Bob, who has an account (and a prior trustline) _, tmp_addr = transfer_send(sender_kp=alice, receiver_address=bob_addr.address, asset=fakeusd, amount="10") transfer_receive(tmp_address=tmp_addr, receiver_kp=bob, asset=fakeusd) # Transfer funds to Carol who has a bare-bones account (no funds, no trustline) _, tmp_addr = transfer_send(sender_kp=alice, receiver_address=carol_addr.address, asset=fakeusd, amount="10") transfer_receive(tmp_address=tmp_addr, receiver_kp=carol, asset=fakeusd) # Transfer Funds to Dave, who has no account _, tmp_addr = transfer_send(sender_kp=alice, receiver_address=dave_addr.address, asset=fakeusd, amount="10") transfer_receive(tmp_address=tmp_addr, receiver_kp=dave, asset=fakeusd) alice_addr.get() bob_addr.get() carol_addr.get() dave_addr.get() print("POSTCONDITIONS\n") print_acct("Alice", alice_addr) print_acct("Bob", bob_addr) print_acct("Carol", carol_addr) print_acct("Dave", dave_addr)
def __init__(self, account): self.account = account if account.secret: self.builder = Builder(secret=account.secret, network=account.network) self.address = Address(address=account.account_id, network=account.network)
def deposit(request): asset_code = request.GET.get("asset_code") stellar_account = request.GET.get("account") # Verify that the request is valid. if not all([asset_code, stellar_account]): return render_error_response("asset_code and account are required parameters") # Verify that the asset code exists in our database, with deposit enabled. asset = Asset.objects.filter(name=asset_code).first() if not asset or not asset.deposit_enabled: return render_error_response(f"invalid operation for asset {asset_code}") try: address = Address(address=stellar_account) except (StellarAddressInvalidError, NotValidParamError): return render_error_response("invalid 'account'") # Verify the optional request arguments. verify_optional_args = _verify_optional_args(request) if verify_optional_args: return verify_optional_args # TODO: Check if the provided Stellar account exists, and if not, create it. # Construct interactive deposit pop-up URL. transaction_id = _create_transaction_id() url = _construct_interactive_url(request, transaction_id) return Response( {"type": "interactive_customer_info_needed", "url": url, "id": transaction_id}, status=status.HTTP_403_FORBIDDEN, )
def list_balances(check_asset=''): #print('Using public key: ' + CONF['public_key']) c = Address(CONF['public_key'], network=CONF['network']) try: c.get() except AccountNotExistError: print_formatted_text( HTML( '<ansiyellow>unfunded account... </ansiyellow> ' + 'you need to hit <ansiblue>f to fund for testnet or type key for public</ansiblue> ' )) return r = requests.get( "https://api.coinmarketcap.com/v1/ticker/stellar/?convert=EUR") rate = r.json()[0] # print('.. rate ' + str(rate)) for x in c.balances: if x['asset_type'] == 'native': if check_asset != '': continue usd_val = float(rate['price_usd']) * float(x['balance']) eur_val = float(rate['price_eur']) * float(x['balance']) print_formatted_text( HTML('XLM: <ansiblue>' + x['balance'] + '</ansiblue> value: USD:' + "{:.2f}".format(usd_val) + ' EUR:' + "{:.2f}".format(eur_val))) else: if check_asset != '': if check_asset.upper() == x['asset_code'].upper(): return True else: print_formatted_text( HTML(x['asset_code'] + ' <ansiblue>' + x['balance'] + '</ansiblue>')) if check_asset != '': return False
def __init__(self, address): self.address = address self.account = Address(address=self.address) try: self.account.get() except AccountNotExistError: self.account = None
def test_onboard(self): """test onboarding scenarios""" #TODO ensure there's enough money in the test account to begin with userid = str(uuid.uuid4()) resp = self.app.post('/user/register', data=json.dumps({ 'user_id': str(userid), 'os': 'android', 'device_model': 'samsung8', 'device_id': '234234', 'time_zone': '+05:00', 'token': 'fake_token', 'app_ver': '1.0' }), headers={}, content_type='application/json') self.assertEqual(resp.status_code, 200) # try to onboard user, should succeed kp = Keypair.random() resp = self.app.post('/user/onboard', data=json.dumps( {'public_address': kp.address().decode()}), headers={USER_ID_HEADER: str(userid)}, content_type='application/json') print(json.loads(resp.data)) self.assertEqual(resp.status_code, 200) # ensure that the account was created address = Address(address=kp.address().decode()) address.get() # get the updated information assert (address.balances[0]['asset_type'] == 'native' and int(float(address.balances[0]['balance'])) == 2 ) #TODO read 2 from config # try onboarding again with the same user - should fail resp = self.app.post('/user/onboard', data=json.dumps( {'public_address': kp.address().decode()}), headers={USER_ID_HEADER: str(userid)}, content_type='application/json') print(json.loads(resp.data)) self.assertEqual(resp.status_code, 400) # try sending kin to that public address resp = self.app.post('/send-kin', data=json.dumps({ 'public_address': kp.address().decode(), 'amount': 1 }), headers={USER_ID_HEADER: str(userid)}, content_type='application/json') print(json.loads(resp.data)) self.assertEqual(resp.status_code, 200)
def create_stellar_deposit(transaction_id): transaction = Transaction.objects.get(id=transaction_id) # Assume transaction has valid stellar_account, amount_in, asset.name stellar_account = transaction.stellar_account payment_amount = transaction.amount_in - transaction.amount_fee asset = transaction.asset.name # If the given Stellar account does not exist, create # the account with at least enough XLM for the minimum # reserve and a trust line (recommended 2.01 XLM), update # the transaction in our internal database, and return. address = Address(stellar_account) try: address.get() except HorizonError as e: # 404 code corresponds to Resource Missing. if e.status_code == 404: starting_balance = settings.ACCOUNT_STARTING_BALANCE builder = Builder(secret=settings.STELLAR_ACCOUNT_SEED) builder.append_create_account_op( destination=stellar_account, starting_balance=starting_balance, source=settings.STELLAR_ACCOUNT_ADDRESS, ) builder.sign() try: builder.submit() except HorizonError as exception: raise exception transaction.status = Transaction.STATUS.pending_trust transaction.save() return # If the account does exist, deposit the desired amount of the given # asset via a Stellar payment. If that payment succeeds, we update the # transaction to completed at the current time. If it fails due to a # trustline error, we update the database accordingly. Else, we do not update. builder = Builder(secret=settings.STELLAR_ACCOUNT_SEED) builder.append_payment_op( destination=stellar_account, asset_code=asset, asset_issuer=settings.STELLAR_ACCOUNT_ADDRESS, amount=str(payment_amount), ) builder.sign() try: builder.submit() except HorizonError as exception: if TRUSTLINE_FAILURE_XDR in exception.message: transaction.status = Transaction.STATUS.pending_trust transaction.save() return # If we reach here, the Stellar payment succeeded, so we # can mark the transaction as completed. transaction.status = Transaction.STATUS.completed transaction.completed_at = now() transaction.amount_out = payment_amount transaction.save()
def printAccountInfo(publickey): #publickey: 'GCZ2MXFXT44Z3OMXF4RZBS4BEWOOQR4EFVSJMNIR3JZ5GTRI7Y2TJLM6' address = Address( address=publickey ) # address = Address(address=publickey,network='public') for livenet address.get() # get the updated information return address.balances
def balance(self, address=None): if address: addr = Address(address=address) try: addr.get() return float(Decimal(addr.balances[0]['balance'])) except: return 0.0 else: user_addr = Wallet.objects.get( user=self.user, name=self.coin).addresses.all()[0].address address = Address(address=user_addr) try: address.get() return float(Decimal(address.balances[0]['balance'])) except: return 0.0
def getAddressDetails(self): while not thread_stop_event.isSet(): publickey = 'GBCCC62LUXPDL7DLNQPYJWASA672CCJOLCJRBSIFXNIPRMQRRQ2HCWW6' target = 1000 address = Address(address=publickey) # testnet # address = Address(address=publickey, network='public') # livenet address.get() # Get the latest information from Horizon last_payment = address.payments(order='desc', limit=1) if 'transaction_successful' in last_payment['_embedded'][ 'records'][0]: success = bool(last_payment['_embedded']['records'][0] ['transaction_successful']) else: success = False if 'amount' in last_payment['_embedded']['records'][0] and success: amount = int( float(last_payment['_embedded']['records'][0]['amount'])) else: amount = '' if 'asset_code' in last_payment['_embedded']['records'][ 0] and success: asset_code = last_payment['_embedded']['records'][0][ 'asset_code'] elif 'asset_code' not in last_payment['_embedded']['records'][ 0] and success: asset_code = 'XLM' else: asset_code = '' balance = address.balances if 'balance' in balance[-1] and success: balance = int(float(balance[-1]['balance'])) else: balance = '' last_transaction = address.transactions(order='desc', limit=1) if 'memo' in last_transaction['_embedded']['records'][ 0] and success: memo = last_transaction['_embedded']['records'][0]['memo'] else: memo = '' socketio.emit('address_details', { 'publickey': publickey, 'target': target, 'balance': balance, 'memo': memo, 'amount': amount, 'asset_code': asset_code }, namespace='/test') sleep(self.delay)
def getBalance(addr): address = Address(address=addr, network='PUBLIC') address.get() balance = 0 for b in address.balances: if b['asset_type'] == 'native': balance = float(b['balance']) break return balance
def Account_balance_check(): '''Check the balance in your account, you do not have to connect your Trezor to execute this.''' data = Get_data() Add = data['Address'] add_info = Address(address = Add,network = 'public') add_info.get() return add_info.balances
def get_xlm_vault_balance(user): user_addr = VaultWallet.objects.get( username=user, name='xlm').addresses.all()[0].address address = Address(address=user_addr) try: address.get() return Decimal(address.balances[0]['balance']) except: return None
def checkBalance(self): address = Address( address=self.publickey ) # address = Address(address=publickey,network='public') for livenet address.get() # get the updated information pprint("Balances: {}".format(address.balances)) pprint("Sequence Number: {}".format(address.sequence)) pprint("Flags: {}".format(address.flags)) pprint("Signers: {}".format(address.signers)) pprint("Data: {}".format(address.data))
def check_balance(self): print("\nChecking Initial Balance......") url = 'https://friendbot.stellar.org' req1 = requests.get(url, params={'addr': self.publickey1}) req2 = requests.get(url, params={'addr': self.publickey2}) self.address1 = Address(address=self.publickey1) self.address2 = Address(address=self.publickey2) self.address1.get() self.address2.get() # print("Initial Balance of Sender: {}".format(address1.balances[0])) for item in self.address1.balances: print("Initial Balance of Sender: " + item['balance']) for item in self.address2.balances: print("Initial Balance of Receiver: " + item['balance']) # print("Initial Balance of Receiver: {}".format(address2.balances[0])) print( "\n------------------------------------------------------------------------------" )
def get_balance_issuer(amount, asset): if asset == 'XLM': return 0, "" c = Address(CONF['public_key'], network=CONF['network']) c.get() for b in c.balances: if asset == b['asset_code']: if float(b['balance']) < float(amount): print('error insufficient funds') return 1, b['asset_issuer'] else: return 0, b['asset_issuer']
def history(): c = Address(CONF['public_key'], network=CONF['network']) c.get() h = c.payments(limit=30, order='desc') for x in h[u'_embedded']['records']: if x['type'] == 'create_account': print(x['created_at'] + ' ' + x['type'] + ' start ' + x['starting_balance'] + '\n' + horiz_lp() + '/operations/' + x['id']) else: print(x['created_at'] + ' ' + x['type'] + ' ' + x['to'] + ' ' + x['from'] + ' ' + x['amount'] + '\n' + horiz_lp() + '/operations/' + x['id'])
def see_account_pk(pk, name): address = Address(address=pk, network='TESTNET') address.get() bals = address.balances sigs = address.signers nots = address.data offs = address.offers() print name print 'sequence number is '+address.sequence print str(len(bals))+' ASSETS' C = 0 while C < len(bals): if bals[C]['asset_type']=='native': print '..... XLM: '+bals[C]['balance'] else: print '..... '+bals[C]['asset_code']+': '+bals[C]['balance'] print '..... (from '+bals[C]['asset_issuer'] C+=1 T = address.thresholds print 'SECURITY THRESHOLDS' print '..... high ops: '+str(T['high_threshold']) print '..... low ops: '+str(T['low_threshold']) print '..... medium ops: '+str(T['med_threshold']) print str(len(sigs))+' SIGNERS' C = 0 while C < len(sigs): print '..... '+sigs[C]['key'] print '..... '+sigs[C]['type']+' weight: '+str(sigs[C]['weight']) C+=1 print 'DATA' print nots print 'OFFERS' records = offs['_embedded']['records'] C = 0 while C < len(records): print '..... '+records[C]['amount']+' '+records[C]['selling']['asset_code']+' from '+records[C]['selling']['asset_issuer'] print '..... for '+records[C]['price']+' '+records[C]['buying']['asset_type']+' per '+records[C]['selling']['asset_code'] C+=1 print ''
def transfer_send(sender_kp, receiver_address, asset, amount): """ Execute the send portion of a transfer. This is used by the issuer, airdropper, or sender of an asset. When this is done, a new temporary account exists, which contains the transferred asset and enough XLM to merge it into the receiving account. Args: sender_kp (Keypair): keypair of sending account receiver_address (string): address of account to receive asset asset (Asset): asset to send amount (string): amount to transfer, float encoded as string Returns: response, tmp_dest: the Horizon response and the newly created account holding the transfer """ sender = Address(sender_kp.address()) sender.get() # Generate a tmp keypair tmp_kp = Keypair.random() tmp_dest = tmp_kp.address().decode() # This is a speculative transaction! # It may fail if someone pre-empts the CreateAccount -- in which case, it # should be either re-run with a new kp or it should be attempted again with # a payment to ensure at least 2.00006 native instead of create account # This has been left out of this demo for simplicity txn = Transaction(source=sender.address, sequence=sender.sequence, fee=400, operations=[ CreateAccount(destination=tmp_dest, starting_balance="4.1"), ChangeTrust(asset, amount, tmp_dest), Payment(tmp_dest, asset, amount), SetOptions(master_weight=0, signer_weight=1, source=tmp_dest, signer_address=receiver_address) ]) txe = Te(tx=txn, network_id="TESTNET") txe.sign(sender_kp) txe.sign(tmp_kp) xdr = txe.xdr() response = horizon.submit(xdr) return response, tmp_dest
def create_empty_acct(r_kp): """ Creates a tmp account which is empty except for min balance (no fees even) """ r = Address(address=r_kp.address().decode()) r.get() kp = Keypair.random() dest = kp.address().decode() tx = Transaction( source=r.address, sequence=r.sequence, fee=100, operations=[CreateAccount(destination=dest, starting_balance="1")]) env = Te(tx=tx, network_id="TESTNET") env.sign(r_kp) horizon.submit(env.xdr()) return kp
def deposit(request): """ `GET /deposit` initiates the deposit and returns an interactive deposit form to the user. """ asset_code = request.GET.get("asset_code") stellar_account = request.GET.get("account") # Verify that the request is valid. if not all([asset_code, stellar_account]): return render_error_response( "`asset_code` and `account` are required parameters") # Verify that the asset code exists in our database, with deposit enabled. asset = Asset.objects.filter(name=asset_code).first() if not asset or not asset.deposit_enabled: return render_error_response( f"invalid operation for asset {asset_code}") try: Address( address=stellar_account, network=settings.STELLAR_NETWORK, horizon_uri=settings.HORIZON_URI, ) except (StellarAddressInvalidError, NotValidParamError): return render_error_response("invalid 'account'") # Verify the optional request arguments. verify_optional_args = _verify_optional_args(request) if verify_optional_args: return verify_optional_args # Construct interactive deposit pop-up URL. transaction_id = create_transaction_id() url = _construct_interactive_url(request, transaction_id) return Response( { "type": "interactive_customer_info_needed", "url": url, "id": transaction_id }, status=status.HTTP_403_FORBIDDEN, )
def _get_transactions(self, time=True): address = Address(address=self._generate_keypair().address().decode()) address.get() # get the updated information transactions = address.transactions() if len(transactions['_embedded']['records']) < 2: return None if time: trx = [(record['created_at'], record['memo']) for record in transactions['_embedded']['records'] if record['memo_type'] == 'text'] else: trx = [ record['memo'] for record in transactions['_embedded']['records'] if record['memo_type'] == 'text' ] return trx
def validate(wallet_address: str, network: str) -> str: # Check wallet exists or not and check wallet have trust HTKN yet print('Validating wallet address: {}, network: {}'.format( wallet_address, network)) config = configs[network] try: wallet = Address(wallet_address, horizon_uri=config['HORIZON_URL'], network=network) wallet.get() if _is_trust_hot(wallet, config): print('PASSED') else: print('FAILED: This wallet doesn\'t trust HOT asset.') except exceptions.StellarAddressInvalidError as e: print('FAILED: {}'.format(e)) except (exceptions.HorizonError) as e: print('FAILED: Wallet not found.') except Exception as e: print('FAILED: {}'.format(e))
def __init__(self, public_key, webhook_url, data_dir="/var/lib/LumenautGazer", minimum_amount=0.1, dry_run=False): # On first run, we need to create the datadir if not os.path.exists(data_dir): os.makedirs(data_dir) if not public_key: raise ValueError("Please provide public_key.") self.public_key = public_key self.webhook_url = webhook_url self.minimum_amount = minimum_amount self.address = Address(address=self.public_key, network='public') self.last_cursor_filepath = os.path.join( data_dir, "{}{}".format(self.public_key, '_cursor')) self.dry_run = dry_run
def _getAccounts(self): for account in settings['stellar_exporter']['accounts']: a = Address(address=account, network='public') a.get() for balance in a.balances: if balance.get('asset_code'): currency = balance.get('asset_code') elif balance.get('asset_type') == 'native': currency = 'XLM' else: currency = balance.get('asset_type') self.accounts.update({ '{}-{}'.format(account, currency): { 'account': account, 'currency': currency, 'balance': float(balance.get('balance')) } }) log.debug('Found the following accounts: {}'.format(self.accounts))
def get_address_details_from_network(address): """ Queries the Stellar network regarding the details of the specified account address. :param str address: address to be evaluated. :return: In case of success returns a Stellar Address object with the updated address information, fetched from the Stellar network. In case of failure returns None :rtype: Address or None """ if not is_address_valid(address): print('Trying to get information of an invalid address.') return None try: address = Address(address=address) address.get() # Get the latest information from Horizon except AccountNotExistError: print('The specified account does not exist.') return None except HorizonError: print( 'A connection error occurred (Please check your Internet connection).' ) return None return address
def create_stellar_deposit(transaction_id): """Create and submit the Stellar transaction for the deposit.""" transaction = Transaction.objects.get(id=transaction_id) # We check the Transaction status to avoid double submission of a Stellar # transaction. The Transaction can be either `pending_anchor` if the task # is called from `GET deposit/confirm_transaction` or `pending_trust` if called # from the `check_trustlines()`. if transaction.status not in [ Transaction.STATUS.pending_anchor, Transaction.STATUS.pending_trust, ]: return transaction.status = Transaction.STATUS.pending_stellar transaction.save() # We can assume transaction has valid stellar_account, amount_in, and asset # because this task is only called after those parameters are validated. stellar_account = transaction.stellar_account payment_amount = round(transaction.amount_in - transaction.amount_fee, 7) asset = transaction.asset.name # If the given Stellar account does not exist, create # the account with at least enough XLM for the minimum # reserve and a trust line (recommended 2.01 XLM), update # the transaction in our internal database, and return. address = Address( stellar_account, network=settings.STELLAR_NETWORK, horizon_uri=settings.HORIZON_URI, ) try: address.get() except HorizonError as address_exc: # 404 code corresponds to Resource Missing. if address_exc.status_code != 404: return starting_balance = settings.ACCOUNT_STARTING_BALANCE builder = Builder( secret=settings.STELLAR_ACCOUNT_SEED, horizon_uri=settings.HORIZON_URI, network=settings.STELLAR_NETWORK, ) builder.append_create_account_op( destination=stellar_account, starting_balance=starting_balance, source=settings.STELLAR_ACCOUNT_ADDRESS, ) builder.sign() try: builder.submit() except HorizonError: return transaction.status = Transaction.STATUS.pending_trust transaction.save() return # If the account does exist, deposit the desired amount of the given # asset via a Stellar payment. If that payment succeeds, we update the # transaction to completed at the current time. If it fails due to a # trustline error, we update the database accordingly. Else, we do not update. builder = Builder( secret=settings.STELLAR_ACCOUNT_SEED, horizon_uri=settings.HORIZON_URI, network=settings.STELLAR_NETWORK, ) builder.append_payment_op( destination=stellar_account, asset_code=asset, asset_issuer=settings.STELLAR_ACCOUNT_ADDRESS, amount=str(payment_amount), ) builder.sign() try: response = builder.submit() # Functional errors at this stage are Horizon errors. except HorizonError as exception: if TRUSTLINE_FAILURE_XDR not in exception.message: return transaction.status = Transaction.STATUS.pending_trust transaction.save() return # If this condition is met, the Stellar payment succeeded, so we # can mark the transaction as completed. if response["result_xdr"] != SUCCESS_XDR: return transaction.stellar_transaction_id = response["hash"] transaction.status = Transaction.STATUS.completed transaction.completed_at = now() transaction.status_eta = 0 # No more status change. transaction.amount_out = payment_amount transaction.save()
def Account_info_update(Add): add_info = Address(address=Add, network='public') add_info.get() return add_info
from stellar_base.address import Address import requests import config address = Address(address=config.address, horizon_uri=config.horizon) def email_alert(transaction_id): report = { "value1": transaction_id } # Use this to add transaction information requests.post(config.trigger, data=report) # Trade complete response - Need to add transaction info def trade_handler(response): print(response) email_alert('transaction complete') # Email Message text # Check for new trade trades = address.trades(sse=True, cursor='now') for trade in trades: trade_handler(trades)
return r.text if __name__ == '__main__': #This would generate the address and the seed # address, password = gen_address() # print(address, password) ISSUERS_ADDRESS = "GCA3IT4NDEAZN5QPPWB72D2X5HFT3GPNONJKCAYHCBHN7MGBSYF4VEFU" ISSUERS_SEED = "SBFYTBQQPSIP3CSWU43FDFRPMETW56O7J2RUKVOKLDFL6XC4OTVUAUIT" RECEIVING_ADDRESS = "GBYXARVIA3SF5PQZOOKX2RRPZNUDWCERQZ7HEY5GQ4AZ32LD7M3J6RV2" RECEIVING_SEED = "SAJDKZPCNBYCGVRH7C3M5CJ2YAXVFCKLFJKID7S2VONJIVYDNUPCRHIU" horizon = horizon_testnet() ISSUER = Address(address=ISSUERS_ADDRESS) RECEIVER = Address(address=RECEIVING_ADDRESS) ISSUER.get() RECEIVER.get() #We get the balance of ISSUER and RECEIVER ISSUER_BALANCE = ISSUER.balances RECEIVER_BALANCE = RECEIVER.balances #We use testnet to fund the account for now # req = fund_account(RECEIVING_ADDRESS) # print(req) asset = Asset("FT", ISSUERS_ADDRESS)