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))
class Details: def __init__(self, address): self.address = address self.account = Address(address=self.address) try: self.account.get() except AccountNotExistError: self.account = None @property def check(self): return True if self.account else False @property def get(self): if self.account: return self.account, self.address, self.balance, self.asset else: return None @property def balance(self): balance = 0 try: balance = self.account.balances[0]['balance'] except AttributeError: balance = None finally: return balance @property def asset(self): asset = None try: asset = self.account.balances[0]['asset_type'] asset = 'XLM' if asset == 'native' else asset except AttributeError: asset = None finally: return asset
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 _get_address(public_key): # type: (str) -> Address address = Address(address=public_key, network=network) address.get() return address
# sign envelope.sign(Alice) # submit xdr = envelope.xdr() response = horizon.submit(xdr) # In[54]: print response # In[51]: from stellar_base.address import Address publickey = 'GDVDKQFP665JAO7A2LSHNLQIUNYNAAIGJ6FYJVMG4DT3YJQQJSRBLQDG' address = Address(address=publickey) # See signature for additional args address.get() # Get the latest information from Horizon # In[52]: print("Balances: {}".format(address.balances)) print("Sequence Number: {}".format(address.sequence)) print("Flags: {}".format(address.flags)) print("Signers: {}".format(address.signers)) print("Data: {}".format(address.data)) # In[68]: from stellar_base.keypair import Keypair from stellar_base.asset import Asset from stellar_base.operation import Payment from stellar_base.transaction import Transaction
def get_account_data(self): # 获取账户信息 account = Address(address=self.address, network=self.network, horizon=self.horizon_url) account.get() return account
def _get_data(self): address = Address(address=self._generate_keypair().address().decode()) address.get() # get the updated information return address.data
def get_balance(pub_key): _address = Address(address=pub_key) _address.get() print(_address.balances) return int(float(_address.balances[0]['balance']))
def transfer_receive(tmp_address, receiver_kp, asset): """ Receive a transfer. This is used by a wallet on behalf of the receiving user to pull the new asset in. When it's done the receiving account has all of the asset from tmp_address, and all of the XLM reserve required to perform the transfer. Args: tmp_address (string): address of temporary account containing the transfer asset receiver_kp (Keypair): Keypair for the (optionally created) receiving account asset (Asset): asset to receive Returns: response: the Horizon response """ account_exists = False receiver_address = receiver_kp.address() receiver_acct = Address(receiver_address) try: receiver_acct.get() account_exists = True except stellar_base.exceptions.HorizonError: pass needs_trustline = True if account_exists: for b in receiver_acct.balances: if balance_to_asset(b) == asset: needs_trustline = False break tmp_acct = Address(tmp_address) tmp_acct.get() # assumes that the temp account cointains the specified asset amount = [ b['balance'] for b in tmp_acct.balances if balance_to_asset(b) == asset ][0] operations = [] if not account_exists: operations.append(CreateAccount(receiver_address, "1")) if needs_trustline: operations.extend([ # enough for trustline and one offer Payment(receiver_address, Asset.native(), "1"), ChangeTrust(asset, source=receiver_kp.address()) ]) else: operations.append( # enough for one offer Payment(receiver_address, Asset.native(), "0.5"), ) operations.extend([ # Send Asset Payment(receiver_address, asset, amount), # Clear signers SetOptions(signer_weight=0, signer_address=receiver_address), # Clear trustlines ChangeTrust(asset, "0"), # Merge Account AccountMerge(receiver_address) ]) txn = Transaction(source=tmp_acct.address, sequence=tmp_acct.sequence, fee=100 * len(operations), operations=operations) txe = Te(tx=txn, network_id="TESTNET") txe.sign(receiver_kp) # Potentially the issuer needs to sign this too with an allow trust -- # depends on the asset in question! response = horizon.submit(txe.xdr()) return response
def _get_balance(self): address = Address(address=self._generate_keypair().address().decode()) address.get() # get the updated information return address.balances[0]['balance']
def account_balance(keypair): address = Address(address=keypair.address().decode(), network='TESTNET') address.get() balance = address.balances[0] return Decimal(balance['balance'])
def Account_info_update(Add): add_info = Address(address=Add, network='public') add_info.get() return add_info
def get(self, publickey): address = Address(address=publickey, network='public') address.get() # get the updated information return { 'balances': address.balances }
from stellar_base.keypair import Keypair import requests from stellar_base.address import Address kp = Keypair.random() publickey = kp.address().decode() r = requests.get('https://friendbot.stellar.org/?addr=' + publickey) print(publickey) print(r) print(kp) #publickey = 'GDVDKQFP665JAO7A2LSHNLQIUNYNAAIGJ6FYJVMG4DT3YJQQJSRBLQDG' address = Address( address=publickey ) # address = Address(address=publickey,network='public') for livenet address.get() # get the updated information print("Balances: {}".format(address.balances)) print("Sequence Number: {}".format(address.sequence)) print("Flags: {}".format(address.flags)) print("Signers: {}".format(address.signers)) print("Data: {}".format(address.data))
def refreshSingleWallet(wallet): print wallet.address # Bitcoin Cash balance lookup #if wallet.coin == "bch": #client = blocktrail.APIClient(api_key="27624245730869da2e0ea49573486a50658d3d2f", api_secret="eb55ec22439129cb8ed85d0570324edca80a061a", network="BCH", testnet=False) #address = client.address(wallet.address) #latest_block = client.block_latest() ## need to check this for errors #wallet.balance = address['balance'] #wallet.error = '' #wallet.save() #return wallet.balance # Ripple balance lookup if wallet.coin == "xrp": balanceReturn = requests.get('https://data.ripple.com/v2/accounts/' + wallet.address + '/balances') if (balanceReturn.status_code == 400) or (balanceReturn.status_code == 404): wallet.error = balanceReturn.json()["message"] wallet.balance = 99999999 wallet.save() return balanceReturn.json()["message"] elif balanceReturn.status_code == 200: #return balanceReturn.json()["balances"][0]["value"] wallet.balance = float( balanceReturn.json()["balances"][0]["value"]) wallet.error = '' wallet.save() return wallet.balance # Bitcoin balance lookup if wallet.coin == "btc": balanceReturn = requests.get( 'https://api.blockcypher.com/v1/btc/main/addrs/' + wallet.address + '/balance?token=' + blockcypher_token) if (balanceReturn.status_code == 400) or (balanceReturn.status_code == 404) or (balanceReturn.status_code == 429): wallet.error = balanceReturn.json()["error"] wallet.balance = 99999999 wallet.save() return balanceReturn.json()["error"] else: # convert satoshi to BTC wallet.balance = float( Decimal(balanceReturn.json()["balance"]) / Decimal(100000000)) wallet.error = '' wallet.save() return wallet.balance # Litecoin balance lookup if wallet.coin == "ltc": balanceReturn = requests.get( 'https://api.blockcypher.com/v1/ltc/main/addrs/' + wallet.address + '/balance?token=' + blockcypher_token) if (balanceReturn.status_code == 400) or (balanceReturn.status_code == 404) or (balanceReturn.status_code == 429): wallet.error = balanceReturn.json()["error"] wallet.balance = 99999999 wallet.save() return balanceReturn.json()["error"] else: wallet.balance = float( Decimal(balanceReturn.json()["balance"]) / Decimal(100000000)) wallet.error = '' wallet.save() return wallet.balance # Ethereum balance lookup if wallet.coin == "eth": balanceReturn = requests.get( 'https://api.blockcypher.com/v1/eth/main/addrs/' + wallet.address + '/balance?token=' + blockcypher_token) if (balanceReturn.status_code == 400) or (balanceReturn.status_code == 404) or (balanceReturn.status_code == 429): wallet.error = balanceReturn.json()["error"] wallet.balance = 99999999 wallet.save() return balanceReturn.json()["error"] else: wallet.balance = float( Decimal(balanceReturn.json()["balance"]) / Decimal(1000000000000000000)) wallet.error = '' wallet.save() return wallet.balance # Stellar balance lookup if wallet.coin == "xlm": address = Address(address=wallet.address, network='public') try: address.get() except: wallet.error = "Error" wallet.balance = 99999999 wallet.save() return "Error" wallet.balance = float(address.balances[0]["balance"]) wallet.error = '' wallet.save() return wallet.balance # Verge balance lookup if wallet.coin == "xvg": balanceReturn = requests.get( 'https://verge-blockchain.info/ext/getbalance/' + wallet.address) if isinstance(balanceReturn.json(), float): wallet.balance = float(balanceReturn.json()) wallet.error = '' wallet.save() return wallet.balance else: wallet.error = balanceReturn.json()["error"] wallet.balance = 99999999 wallet.save() return balanceReturn.json()["error"]
def clean(self): """ Override to verify Stellar account using Data Entry added client-side. Decoded data entry must match request.user.id """ # TODO: HANDLE THE RAISED ERRORS TO OUTPUT A VALIDATION ERROR (WORRY ABOUT TAMPERED WITH SIGNATURE ERROR) # Call the super super(AccountCreateForm, self).clean() # Obtain form input parameters creating_stellar = self.cleaned_data.get("creating_stellar") public_key = self.cleaned_data.get("public_key") if creating_stellar: # Creating a new Stellar account # NOTE: https://stellar-base.readthedocs.io/en/latest/quickstart.html#create-an-account request_user = self.request_user # Check current request user is an admin allowed to approve funding if not request_user.is_superuser: raise ValidationError( _('Invalid request. You must be an admin to approve funding of new accounts.' )) # Check that account for this public key does not already exist elif Account.objects.filter(public_key=public_key).exists(): raise ValidationError( _('Invalid public key. This account has already been funded.' )) # Check that a funding request exists for this public key and fetch it try: funding_request = AccountFundRequest.objects.get( public_key=public_key) except ObjectDoesNotExist: funding_request = None raise ValidationError( _('Funding request for this public key does not exist.')) # Make a call to Horizon to fund new account with Nucleo base account horizon = settings.STELLAR_HORIZON_INITIALIZATION_METHOD() # Assemble the CreateAccount operation amount = settings.STELLAR_CREATE_ACCOUNT_MINIMUM_BALANCE memo = TextMemo('Nucleo Created Account') op_create = CreateAccount({ 'destination': public_key, 'starting_balance': amount, }) # Get the current sequence of the source account by contacting Horizon. # TODO: You should also check the response for errors! sequence = horizon.account( settings.STELLAR_BASE_KEY_PAIR.address()).get('sequence') # Create a transaction with our single create account operation, with the # default fee of 100 stroops as of this writing (0.00001 XLM) tx = Transaction( source=settings.STELLAR_BASE_KEY_PAIR.address().decode(), opts={ 'sequence': sequence, 'memo': memo, 'operations': [op_create], }, ) # Build a transaction envelope, ready to be signed. envelope = Te(tx=tx, opts={"network_id": settings.STELLAR_NETWORK}) # Sign the transaction envelope with the source keypair envelope.sign(settings.STELLAR_BASE_KEY_PAIR) # Submit the transaction to Horizon # TODO: Make sure to look at the response body carefully, as it can be an error or a successful response. te_xdr = envelope.xdr() response = horizon.submit(te_xdr) # Check whether account actually created on ledger if 'hash' not in response: raise ValidationError( _('Nucleo was not able to create a Stellar account at this time' )) # If successful, increment the user's account quota val by one user_funding = funding_request.requester self.account_user = user_funding profile_funding = user_funding.profile profile_funding.accounts_created += 1 profile_funding.save() # Delete the funding request funding_request.delete() # Email the requester to notify them of approved funding for new account profile_path = reverse('nc:user-detail', kwargs={'slug': user_funding.username}) profile_url = build_absolute_uri(self.request, profile_path) current_site = get_current_site(self.request) email_settings_path = reverse('nc:user-settings-redirect') email_settings_url = build_absolute_uri(self.request, email_settings_path) ctx_email = { 'current_site': current_site, 'username': user_funding.username, 'account_public_key': public_key, 'profile_url': profile_url, 'email_settings_url': email_settings_url, } get_adapter(self.request).send_mail('nc/email/account_create', user_funding.email, ctx_email) else: # Verify Stellar public key with the added Data Entry # Get the Stellar account for given public key # NOTE: Need to decouple Address initialization from get() method to work! address = Address(address=public_key, network=settings.STELLAR_NETWORK) try: address.get() except AccountNotExistError: raise ValidationError(_( 'Invalid account. Stellar Account associated with given public key does not exist.' ), code='invalid_account') # Obtain the signed_user data entry signed_user = address.data.get( settings.STELLAR_DATA_VERIFICATION_KEY, None) if not signed_user: raise ValidationError(_( 'Invalid data entry. Decoded Stellar Data Entry does not exist.' ), code='invalid_data_entry') # Now decode and verify data self.loaded_user_id = signing.loads(base64.b64decode(signed_user)) if self.request_user.id != self.loaded_user_id: raise ValidationError(_( 'Invalid user id. Decoded Stellar Data Entry does not match your user id.' ), code='invalid_user') # Associate request user with this account self.account_user = self.request_user # Delete any existing funding request associated with that key AccountFundRequest.objects.filter(public_key=public_key).delete() # TODO: SEND EMAIL IF KEY HAS BEEN COMPROMISED, SOMEHOW ALLOW UNFUNDED ACCOUNTS TO BE SEEN? return self.cleaned_data
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)
from flask import Flask, send_file, render_template, request, Response import json, base64 from stellar_base.keypair import Keypair from stellar_base.address import Address app = Flask(__name__) pool_address = "GCCD6AJOYZCUAQLX32ZJF2MKFFAUJ53PVCFQI3RHWKL3V47QYE2BNAUT" phrase = b"Lumenaut" pool = Address(address=pool_address, network="public") pool.get() pool_signers = [acc["public_key"] for acc in pool.signers if acc["weight"] > 0] @app.route("/") def index(): return render_template("index.html") # verify base64-encoded string def verify(pubkey, data): if pubkey not in pool_signers: return False data = bytes(base64.b64decode(data)) pubkp = Keypair.from_address(pubkey) try: pubkp.verify(phrase, data) except:
class stellar: def generate_account(self): kp1 = Keypair.random() kp2 = Keypair.random() self.publickey1 = kp1.address().decode() self.seed1 = kp1.seed().decode() self.publickey2 = kp2.address().decode() self.seed2 = kp2.seed().decode() print("\nCreating users & Generating Keys......") time.sleep(5) # print("Sender Public key: "+ publickey1) print("\nSender's Address: " + self.seed1) print("Receiver's Address: " + self.publickey2) # print("Receiver Private key: "+ seed2) print( "\n------------------------------------------------------------------------------" ) 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 check_final_balance(self): self.address1.get() self.address2.get() # print("Current Balance of Sender: {}".format(address1.balances[0])) for item in self.address1.balances: print("Current Balance of Sender: " + item['balance']) for item in self.address2.balances: print("Current Balance of Receiver: " + item['balance']) # print("Current Balance of Receiver: {}".format(address2.balances[0])) print( "\n------------------------------------------------------------------------------" ) 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......")
#Bob bob_secret = 'SCICYKDGHKKXG24T654QO6HU2MI6WNY2W5MSAZV6LIDHJ2V6XZIT66OF' bob_public = Keypair.from_seed(bob_secret).address().decode() #Charlie charlie_secret = 'SCC757FBKA7C6MOIY4MR677R5L7NOXCQKNA6OOCKMPXPG7EZADWUGQ2M' charlie_public = Keypair.from_seed(charlie_secret).address().decode() #Diana diana_secret = 'SAJ3WR4BWQPLLCBQKVVMMHBIKXUOOJ6MSCAZ6GCWDHVSWOESAMSZTLKT' diana_public = Keypair.from_seed(diana_secret).address().decode() print("\nAlice\n") publickey = alice_public address = Address(address=publickey) address.get() print('Balances: {}'.format(address.balances)) print("\nBob\n") publickey = bob_public address = Address(address=publickey) address.get() print('Balances: {}'.format(address.balances)) print("\nCharlie\n") publickey = charlie_public address = Address(address=publickey) address.get() print('Balances: {}'.format(address.balances)) print("\nDiana\n")
def adress(request, adress): c = CurrencyConverter() url = ("https://api.coinmarketcap.com/v1/ticker/stellar") response = request_market(url) symbol = response[0]['symbol'] price_usd = response[0]['price_usd'] price_btc = response[0]['price_btc'] rank = response[0]['rank'] market_cap = float(response[0]['market_cap_usd']) x24h_volume = float(response[0]['24h_volume_usd']) x1h_change = response[0]['percent_change_1h'] x24h_change = response[0]['percent_change_24h'] x7d_change = response[0]['percent_change_7d'] market_cap = format(round(int(market_cap)), ',d') x24h_volume = format(round(int(x24h_volume)), ',d') cena_eur = c.convert(price_usd, 'USD', 'EUR') cena_eur = float("{0:.5f}".format(cena_eur)) cena_yen = c.convert(price_usd, 'USD', 'CNY') cena_yen = float("{0:.5f}".format(cena_yen)) up_green = "#2ECC40" down_red = "#FF4136" change_1h = "" change_24h = "" change_7d = "" if float(x1h_change) < 0: change_1h = down_red elif float(x1h_change) > 0: change_1h = up_green if float(x24h_change) < 0: change_24h = down_red elif float(x24h_change) > 0: change_24h = up_green if float(x7d_change) < 0: change_7d = down_red elif float(x7d_change) > 0: change_7d = up_green publickey = adress address = STELLAR( address=publickey, network='public' ) # address = Address(address=publickey,network='public') for livenet address.get() # get the updated information balans = address.balances[0]['balance'] template = loader.get_template('art/balance.html') context = { 'balance': balans, 'donations': donations, 'adress': adress, 'symbol': symbol, 'price_usd': price_usd, 'price_btc': price_btc, 'rank': rank, 'change_1h': change_1h, 'change_24h': change_24h, 'change_7d': change_7d, 'cena_eur': cena_eur, 'cena_yen': cena_yen, 'market_cap': market_cap, '24h_volume': x24h_volume, '1h_change': x1h_change, '24h_change': x24h_change, '7d_change': x7d_change, "x1h_change": x1h_change, 'x24h_change': x24h_change, 'x7d_change': x7d_change, } return HttpResponse(template.render(context, request))
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) builder = Builder( RECEIVING_SEED, network="TESTNET"
kp_a_2_address = kp_a_2.address().decode() kp_a_1_seed = kp_a_1.seed().decode() kp_a_2_seed = kp_a_2.seed().decode() accounts_builder = Builder(secret=kp_carol.seed().decode()) accounts_builder.append_create_account_op( kp_a_1_address, '202.50009') accounts_builder.append_create_account_op( kp_a_2_address, '202.50009') accounts_builder.sign() response = accounts_builder.submit() assert 'hash' in response print('Initializing transactions') address_a_1 = Address(address=kp_a_1_address) address_a_2 = Address(address=kp_a_2_address) address_a_1.get() address_a_2.get() starting_sequence_a_1 = int(address_a_1.sequence) starting_sequence_a_2 = int(address_a_2.sequence) tau = datetime.datetime.now() + datetime.timedelta(seconds=30) tau_unix = int(time.mktime(tau.timetuple())) tau_plus_delta = tau + datetime.timedelta(seconds=DELTA) tau_plus_delta_unix = int(time.mktime(tau_plus_delta.timetuple())) tx_timebound = TimeBounds( minTime=tau_unix, maxTime=tau_plus_delta_unix) counter_tx_timebound = TimeBounds(minTime=0, maxTime=tau_unix) builder_t_1_1 = Builder(secret=kp_a_1_seed, sequence=starting_sequence_a_1+1)
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 genptxs( systemdb, timestamp): """generates contract ptxs 1-3 given systemdb, including a contract manifest in production, will add ptxs will be hosted along with manifest on e.g. IPFS """ q = Query() a_sk = systemdb.search(q.name == 'Contract')[0]['sk'] a_pk = systemdb.search(q.name == 'Contract')[0]['pk'] pr_pk = systemdb.search(q.name == 'Printer')[0]['pk'] pi_pk = systemdb.search(q.name == 'Pipe')[0]['pk'] UND = systemdb.search(q.type == 'manifest')[0]['UND'] UND_pk = systemdb.search(q.type == 'manifest')[0]['UND_source'] QUO = systemdb.search(q.type == 'manifest')[0]['QUO'] QUO_pk = systemdb.search(q.type == 'manifest')[0]['QUO_source'] strike = systemdb.search(q.type == 'manifest')[0]['strike'] size = systemdb.search(q.type == 'manifest')[0]['size'] address = Address(address=a_pk, network='TESTNET') address.get() ####2 PREAUTH TX ONE ##### b = Builder( secret = str(a_sk), horizon_uri = 'https://horizon.stellar.org', network = 'TESTNET', sequence = int(address.sequence)+3) """seq incremented by two bc acct will need to add hash signer, data entry, and lock """ strikeXsize = str(int(strike)*int(size)) b.append_payment_op(pr_pk, '0.5', 'OCA', pr_pk) if QUO_pk == None: b.append_payment_op(pi_pk, strikeXsize, QUO, asset_issuer=None) else: b.append_payment_op(pi_pk, strikeXsize, QUO, QUO_pk) b.append_manage_offer_op('SPA', pr_pk, 'OCA', pr_pk, '0.0000001', '5000000', offer_id=0) b.append_manage_offer_op('GTA', pr_pk, 'SPA', pr_pk, '1', '0.0000001', offer_id=0) price = str(float(1)/int(size)) b.append_manage_offer_op(UND, UND_pk, 'GTA', pr_pk, str(size), price, offer_id=0) envelope1 = b.gen_te() hashish1 = envelope1.hash_meta() xdr1 = b.gen_xdr() systemdb.insert({ 'type': 'ptx', 'name': 'ptx1', 'xdr': xdr1 }) ####2 PREAUTH TX TWO ##### b2 = Builder( secret = a_sk, horizon_uri ='https://horizon.stellar.org', network = 'TESTNET', sequence = int(address.sequence)+3) b2.append_payment_op(pi_pk, str(strike), UND, UND_pk) b2.append_set_options_op(master_weight=1, low_threshold=0, med_threshold=0, high_threshold=0) envelope2 = b2.gen_te() hashish2 = envelope2.hash_meta() xdr2 = b2.gen_xdr() systemdb.insert({ 'type': 'ptx', 'name': 'ptx2', 'xdr': xdr2 }) ####2 PREAUTH TX THREE ##### b3 = Builder( secret = a_sk, horizon_uri ='https://horizon.stellar.org', network = 'TESTNET', sequence = int(address.sequence)+4) b3.append_set_options_op(master_weight=1, low_threshold=0, med_threshold=0, high_threshold=0) envelope3 = b3.gen_te() hashish3 = envelope3.hash_meta() xdr3 = b3.gen_xdr() systemdb.insert({ 'type': 'ptx', 'name': 'ptx3', 'xdr': xdr3 }) bX = Builder(secret = a_sk, network='TESTNET') bX.append_pre_auth_tx_signer(hashish1, 1, source=None) bX.append_pre_auth_tx_signer(hashish2, 1, source=None) bX.append_pre_auth_tx_signer(hashish3, 1, source=None) bX.sign() print bX.submit()