def create_transaction(cls, text): builder = Builder(secret=cls.key) # use this to use local node e.g with docker instead of public node # builder = Builder(secret=cls.key, horizon_uri="http://localhost:8000/") builder.append_payment_op(cls.address, '100', 'XLM') builder.add_text_memo(text) # string length <= 28 bytes return builder
def bounty_dispatcher(document, amount): """ Dispatch amount specified to the destination address :param document: Desetination address :param amount: Amount of nwc to dispatch :return: response object """ for line in document: builder = Builder(secret=REAL_SEED, network='public') builder.add_text_memo( "NWC bounty reward amount: {}".format(amount)).append_payment_op( destination=line, amount=amount, asset_code='NWC', asset_issuer=ISSUER) builder.sign() response = builder.submit() print(response) with open("bounty.log", "a+") as log: log.write("\n") log.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) log.write("\n") log.write("=============================================") log.write("\n") log.write(json.dumps(response)) log.write("\n") return response
def burn_tokens(address): """ Burn the recent payments to the address for the percent specified in the BURN_RATE constant :param address: address to burn the tokens on :return: response object """ # get recent payments address_obj = Address(address=address) payments = address_obj.payments() asset_sum = 0 for payment in payments: asset_sum += payment burn_sum = asset_sum * BURN_RATE # send the BURN % of tokens to the issuer ultimately taking them out of circulation builder = Builder(secret=REAL_SEED, network='public') builder.add_text_memo( "NWC daily burn: {}".format(burn_sum)).append_payment_op( destination=ISSUER, amount=burn_sum, asset_code='NWC', asset_issuer=ISSUER) builder.sign() response = builder.submit() return response
def submit_operations(account_seed, operations, transaction_memo): """ This method signs the given operations and submits them to the Stellar network :param str account_seed: Seed of the account submitting the operations. It is required to sign the transactions. :param Operation operations: Operations to be submitted. :param str transaction_memo: Text memo to be included in Stellar transaction. Maximum size of 28 bytes. :return: Returns a string containing the server response or None if the transaction could not be submitted. :rtype: str or None """ try: builder = Builder(secret=account_seed) except Exception: # Too broad exception because no specific exception is being thrown by the stellar_base package. # TODO: This should be fixed in future versions print("An error occurred (Please check your Internet connection)") return None builder.add_text_memo(transaction_memo) for operation in operations: builder.append_op(operation) builder.sign() try: return builder.submit() except Exception: # Too broad exception because no specific exception is being thrown by the stellar_base package. # TODO: This should be fixed in future versions print("An error occurred (Please check your Internet connection)") return None
def send_asset(text): # send 10 EURT antb123*papayame.com or send 1 XLM PUBKEY memo text if CONF['private_key'] == '': print( 'no private key setup - pls type set to set key or c to create wallet' ) return val = text.split() memo_type = 'text' if len(val) < 3: print( 'invalid syntax please use send amount asset receiver e.g. s 10 EURT antb123*papayame.com' ) return amount, asset, address = val[1], val[2].upper(), val[3] if '*' in address: res = fed(address.split('*')[1], address) sendto = res['account_id'] memo = res['memo'] memo_type = res['memo_type'] else: sendto = address memo = '' # override memo, type if given if len(val) == 6: memo = val[4] memo_type = val[5] if len(val) == 5: memo = val[4] memo_type = 'text' print_formatted_text( HTML("""Are you sure you want to send <ansiyellow>%s</ansiyellow> <ansired>%s %s</ansired> with memo of <ansiblue>%s</ansiblue> (y/n) """ % (sendto, asset, amount, memo))) text = session.prompt(u'> ', default='y') if text != 'y': return ret, asset_issuer = get_balance_issuer(amount, asset) if ret: return retsan = send_sanity(sendto, memo_type, asset) if not retsan: return send = Builder(CONF['private_key'], network=CONF['network']) if asset != 'XLM': send.append_payment_op(sendto, amount, asset, asset_issuer) else: send.append_payment_op(sendto, amount) if memo != '' and memo_type == 'text': send.add_text_memo(memo) if memo != '' and memo_type == 'id': send.add_id_memo(memo) if CONF['multisig'] != '': print( 'You have 2of2 multisig - send this data to the other key to sign when you get it back type signsend data' ) print(send.gen_xdr()) return send.sign() send.submit()
def send_payment(request,amount,currency,sender,account): builder = Builder(secret=sender) builder.append_payment_op(account,amount,currency) builder.add_text_memo("first payment") builder.sign() s = builder.submit() print(s['_links']) return HttpResponse("send successfully plz check user transaction here")
def trust_asset(setup, secret_key, memo_text=None): """A helper to establish a trustline""" builder = Builder(secret=secret_key, horizon_uri=setup.horizon_endpoint_uri, network=setup.network) builder.append_trust_op(setup.test_asset.issuer, setup.test_asset.code) if memo_text: builder.add_text_memo(memo_text[:28]) # max memo length is 28 builder.sign() reply = builder.submit() return reply.get('hash')
def create_signed_tx(private_key, to_address, amount, network='PUBLIC', memo=None): amount = round(amount, 7) builder = Builder(secret=private_key, network=network) builder.append_payment_op(to_address, amount, 'XLM') if memo: builder.add_text_memo(memo) builder.sign() return builder.gen_xdr().decode()
def send_asset(cls, setup, secret_key, address, amount, memo_text=None): """A helper to send asset""" builder = Builder(secret=secret_key, horizon_uri=setup.horizon_endpoint_uri, network=setup.network) builder.append_payment_op(address, amount, setup.test_asset.code, setup.test_asset.issuer) if memo_text: builder.add_text_memo(memo_text[:28]) # max memo length is 28 builder.sign() reply = builder.submit() return reply.get('hash')
def pay(message, amount, secret, address): sender_secret = secret receiver_address = address builder = Builder(secret=sender_secret, horizon_uri=None, network='TESTNET') builder.add_text_memo(message).append_payment_op( destination=receiver_address, amount=amount, asset_code='XLM') builder.sign() response = builder.submit()
def award_degree(self, address, student_name, birthdate, year): """Sends a transaction with a hash of the student's informations as text memo. :param student_name: in format prenamesurname with only one prename :param year: 4-digits number :return: Horizon return of the tx """ memo = hash128((student_name+birthdate+year).encode()) builder = Builder(secret=self.kp.seed().decode()) builder.add_text_memo(memo) builder.append_payment_op(address, 0.0000001) builder.sign() return builder.submit()
def transfer_lumen(sender, to_address, amount, memo=None): # type: (User, str, float, Optional[str]) -> None # ToDo: check remaining lumen of sending account (fee + base reserve) # (take base reserve https://www.stellar.org/developers/guides/concepts/fees.html) builder = Builder(secret=sender.stellaraccount.seed, network=network) builder.append_payment_op(to_address, str(amount), 'XLM') if memo: builder.add_text_memo(memo) # string length <= 28 bytes builder.sign() builder.submit()
def send(self, destination, amount): destination = check_pay_by_name(destination, "XLM") wallet = Wallet.objects.get(user=self.user, name=self.coin) try: builder = Builder(secret=wallet.private) builder.add_text_memo("EXMR, Stellar!").append_payment_op( destination=destination.strip(), amount=str(amount), asset_code='XLM') builder.sign() response = builder.submit() return response["hash"] except: return {"error": "insufficient funds"}
def test_add_memo(self, test_data): builder = Builder(test_data.cold_secret, sequence=1, fee=100) builder.add_text_memo("hello") assert builder.memo == memo.TextMemo("hello") builder.add_id_memo(123123) assert builder.memo == memo.IdMemo(123123) hash = b"\x95\xe5\xbb\x95\x15\xd9\x9f\x82\x9d\xf9\x93\xc3'\x8e\xeb\xf1\nj!\xda\xa4\xa1\xe4\xf2<6cG}\x17\x97\xfe" builder.add_hash_memo(hash) assert builder.memo == memo.HashMemo(hash) builder.add_ret_hash_memo(hash) assert builder.memo == memo.RetHashMemo(hash)
def send_payment(amount, item, asset='XLM'): flag = False try: builder = Builder(secret=MEMBER_SEED) builder.append_payment_op(SITE_ADDR, amount, asset) builder.add_text_memo(item) builder.sign() s = builder.submit() print(s) flag = True except Exception as ex: print('Error in Payment') print(str(ex)) finally: return flag
def transfer(self, amount, to_address, description): ''' ''' if float(self._get_balance()) < float(amount): return 'Insufficient Balance' seed = self.get_seed() builder = Builder(secret=seed) # builder = Builder(secret=seed, network='public') for LIVENET builder.append_payment_op(to_address, amount, 'XLM') builder.add_text_memo(description) # string length <= 28 bytes builder.sign() # Uses an internal horizon instance to submit over the network builder.submit() return 'SUCCESS'
def send_payment(amount, item, asset='XLM'): flag = False try: builder = Builder( secret=MEMBER_SEED) #send payment from member to site builder.append_payment_op(SITE_ADDRESS, amount, asset) builder.add_text_memo(item) builder.sign() s = builder.submit() global balance balance = calculate_balance(s) flag = True except Exception as e: print('Error', e) finally: return flag
def transaction(): # Performs the transaction from one to another thus providing the current balance. builder = Builder(secret=send_seed) builder.append_payment_op(receive_publickey, '500', 'XLM') # Assigning of Receiver address, amount & Asset. builder.add_text_memo('testing') # Assigning of a memo or remark. builder.sign() s = builder.submit() # Submitting the result of the transaction. 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, } return render_template("transaction.html", cbalance=cbalance)
def send_payment(address, amount): builder = Builder(secret=REAL_SEED, network='public') builder.add_text_memo( "NWC transaction amount: {}".format(amount)).append_payment_op( destination=address, amount=amount, asset_code='NWC', asset_issuer=ISSUER) builder.sign() response = builder.submit() print(response) with open("transaction.log", "a+") as log: log.write("\n") log.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) log.write("\n") log.write("=============================================") log.write("\n") log.write(json.dumps(response)) log.write("\n")
def withdraw(key, to_address, amount=None, dst_tag=None): keypair = RawKeypair(key) builder = Builder(address=public_key_to_address(keypair.raw_public_key()), network='PUBLIC') if amount is None: builder.append_account_merge_op(to_address) else: builder.append_payment_op(to_address, str(round(float(amount), 7)), 'XLM') if dst_tag is not None: builder.add_text_memo(dst_tag) builder.keypair = keypair builder.sign() ret = builder.submit() if ret['successful']: return ret['hash'] print(ret) return None
def send_payment_and_lock(address, amount, release, valid): """ Send the payment to the specified address and lock it for the specified time period :param address: Destination address :param amount: Amount of NWC to payout :param release: Start of token lock date :param valid: End of token lock date :return: response object """ timestamp_release = (release - datetime.datetime(1970, 1, 1)).total_seconds() timestamp_valid = (valid - datetime.datetime(1970, 1, 1)).total_seconds() builder = Builder(secret=REAL_SEED, network='public') builder.add_text_memo( "NWC transaction amount: {}; asset locked till: {}".format( amount, release)).append_payment_op(destination=address, amount=amount, asset_code='NWC', asset_issuer=ISSUER).add_time_bounds({ 'minTime': timestamp_release, 'maxTime': timestamp_valid }) builder.sign() response = builder.submit() print(response) with open("transaction.log", "a+") as log: log.write("\n") log.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) log.write("\n") log.write("unlocks: " + release.strftime("%Y-%m-%d %H:%M:%S")) log.write("\n") log.write("valid till: " + valid.strftime("%Y-%m-%d %H:%M:%S")) log.write("=============================================") log.write("\n") log.write(json.dumps(response)) log.write("\n") return response
def create_transaction(self, from_address, to_address, amount, memo): """ 创建一笔交易 :param from_address: 发起账户的私钥 :param to_address: 目的账户的公钥 :return: response """ builder = Builder(secret=from_address, horizon_uri=self.rpc_uri) builder_memo = builder.add_text_memo(memo) builder_memo.append_payment_op(destination=to_address, amount=amount, asset_code='XLM') builder.sign() response = builder.submit() return response
class Interface: """ Interface to handle all API calls to third-party account. """ 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 _get_new_receives(self): # Get all stored transactions for account transactions = ReceiveTransaction.filter(admin_account=self.account) # Set the cursor according to latest stored transaction: if not transactions: cursor = None else: cursor = int(transactions.latest().data['paging_token']) + 1 # Get new transactions from the stellar network: new_transactions = self._get_receives(cursor=cursor) return new_transactions def _get_receives(self, cursor=None): # If cursor was specified, get all transactions after the cursor: if cursor: transactions = self.address.payments(cursor=cursor)['_embedded']['records'] print(transactions) for i, tx in enumerate(transactions): if tx.get('to') != self.account.account_id: transactions.pop(i) # remove sends # else just get all the transactions: else: transactions = self.address.payments()['_embedded']['records'] for i, tx in enumerate(transactions): if tx.get('from') == self.account.account_id: transactions.pop(i) # remove sends return transactions def _process_receive(self, tx): # Get memo: details = requests.get(url=tx['_links']['transaction']['href']).json() memo = details.get('memo') print('memo: ' + str(memo)) if memo: account_id = memo + '*rehive.com' user_account = UserAccount.objects.get(account_id=account_id) user_email = user_account.user_id # for this implementation, user_id is the user's email amount = to_cents(Decimal(tx['amount']), 7) if tx['asset_type'] == 'native': currency = 'XLM' issuer = '' else: currency = tx['asset_code'] issuer_address = tx['asset_issuer'] issuer = Asset.objects.get(account_id=issuer_address, code=currency).issuer # Create Transaction: tx = ReceiveTransaction.objects.create(user_account=user_account, external_id=tx['hash'], recipient=user_email, amount=amount, currency=currency, issuer=issuer, status='Waiting', data=tx, metadata={'type': 'stellar'} ) # TODO: Move tx.upload_to_rehive() to a signal to auto-run after Transaction creation. tx.upload_to_rehive() return True @staticmethod def _is_valid_address(address: str) -> bool: # TODO: Replace with real address check. if len(address) == 56 and '*' not in address: return True else: return False # This function should always be included if transactions are received to admin account and not added via webhooks: def process_receives(self): # Get new receive transactions new_transactions = self._get_new_receives() # Add each transaction to Rehive and log in transaction table: for tx in new_transactions: self._process_receive(tx) # This function should always be included. def process_send(self, tx): if self._is_valid_address(tx.recipient): address = tx.recipient else: federation = get_federation_details(tx.recipient) if federation['memo_type'] == 'text': self.builder.add_text_memo(federation['memo']) elif federation['memo_type'] == 'id': self.builder.add_id_memo(federation['memo']) elif federation['memo_type'] == 'hash': self.builder.add_hash_memo(federation['memo']) else: raise NotImplementedAPIError('Invalid memo type specified.') address = federation['account_id'] # Create account or create payment: if tx.currency == 'XLM': try: address_obj = self.address address_obj.get() self.builder.append_payment_op(address, tx.amount, 'XLM') except APIException as exc: if exc.status_code == 404: self.builder.append_create_account_op(address, tx.amount) else: # Get issuer address details: issuer_address = get_issuer_address(tx.issuer, tx.currency) address_obj = self.address address_obj.get() self.builder.append_payment_op(address, tx.amount, tx.currency, issuer_address) try: self.builder.sign() self.builder.submit() except Exception as exc: print(exc.payload) def get_balance(self): address = self.address address.get() for balance in address.balances: if balance['asset_type'] == 'native': return to_cents(Decimal(balance['balance']), 7) def get_issuer_address(self, issuer, asset_code): if self._is_valid_address(issuer): address = issuer else: if '*' in issuer: address = get_federation_details(issuer)['account_id'] else: # assume it is an anchor domain address = address_from_domain(issuer, asset_code) return address def trust_issuer(self, asset_code, issuer): logger.info('Trusting issuer: %s %s' % (issuer, asset_code)) address = self.get_issuer_address(issuer, asset_code) self.builder.append_trust_op(address, asset_code) try: self.builder.sign() self.builder.submit() except Exception as exc: print(exc.payload) # Generate new crypto address/ account id @staticmethod def new_account_id(**kwargs): metadata = kwargs.get('metadata') account_id = metadata['username'] + '*' + getattr(settings, 'STELLAR_WALLET_DOMAIN') return account_id def get_account_details(self): address = self.account.account_id qr_code = create_qr_code_url('stellar:' + str(address)) return {'account_id': address, 'metadata': {'qr_code': qr_code}}
def sendTransaction(self, receiverAddress, amount, message='Test'): builder = Builder(secret=self.seed) builder.append_payment_op(receiverAddress, amount, 'XLM') builder.add_text_memo(message) builder.sign() builder.submit()
from stellar_base.builder import Builder import csv from array import * sender_secret = 'SBIQIV2XQBBVXK7FFNNRDTTKG2YTQI5GI4DNY75SDCP2IBMQ2NFZNQNS' receiver_address = [] with open('assetHoldersExport(testnet).csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) next(csv_reader) for line in csv_reader: receiver_address.append(line[1]) for i in range(len(receiver_address)): builder = Builder(secret=sender_secret, horizon_uri='https://horizon-testnet.stellar.org', network='TESTNET') builder.add_text_memo("Thank you for using TXBNB!").append_payment_op( destination=receiver_address[i], amount='1.6333', asset_code='TXBNB', asset_issuer='GDHAFLI6STAHO2GPJEG56CEWRC5QNT54QNWIPREHI4NXJHANSKOGDDTI' ) builder.sign() response = builder.submit() print(response)
async def build_unsigned_transfer( transaction_source_address: str, source_address: str, destination_address: str, amount_hot: Decimal, amount_xlm: Decimal, tax_amount_hot: Decimal = None, sequence: int = None, memo_text: str = None, ) -> Tuple[str, str]: """"Build unsigned transfer transaction return unsigned XDR and transaction hash. Args: source_address: Owner of operation destination_address: wallet id of new wallet amount_hot: amount of hot that would be transfer amount_xlm: amount of xlm that would be transfer sequence: sequence number for generate transaction [optional] memo: memo text [optional] """ builder = Builder( address=transaction_source_address, sequence=sequence, horizon=settings['HORIZON_URL'], network=settings['PASSPHRASE'], ) wallet = await get_wallet_detail(destination_address) if amount_hot and not wallet['asset'].get(settings['ASSET_CODE'], False): raise web.HTTPBadRequest(reason="{} is not trusted {}".format( destination_address, settings['ASSET_CODE'])) if amount_xlm: builder.append_payment_op(destination_address, amount_xlm, source=source_address) if amount_hot and wallet['asset'].get(settings['ASSET_CODE'], False): builder.append_payment_op( destination_address, amount_hot, asset_code=settings['ASSET_CODE'], asset_issuer=settings['ISSUER'], source=source_address, ) if tax_amount_hot and Decimal(tax_amount_hot) > 0: builder.append_payment_op( settings['TAX_COLLECTOR_ADDRESS'], Decimal(tax_amount_hot), asset_code=settings['ASSET_CODE'], asset_issuer=settings['ISSUER'], source=source_address, ) if memo_text: builder.add_text_memo(memo_text) unsigned_xdr = builder.gen_xdr() tx_hash = builder.te.hash_meta() return unsigned_xdr.decode('utf8'), binascii.hexlify(tx_hash).decode()
from stellar_base.builder import Builder alice_secret = 'SCB6JIZUC3RDHLRGFRTISOUYATKEE63EP7MCHNZNXQMQGZSLZ5CNRTKK' bob_address = 'GA7YNBW5CBTJZ3ZZOWX3ZNBKD6OE7A7IHUQVWMY62W2ZBG2SGZVOOPVH' builder = Builder(secret=alice_secret, horizon='https://horizon.stellar.org', network='PUBLIC') builder.add_text_memo("Hello, Stellar!").append_payment_op( destination=bob_address, amount='12.25', asset_code='XLM') builder.sign() response = builder.submit() print(response)
print('Alice Balances: {}'.format(address.balances)) # Bob's address, for the destination kp = Keypair.random() bob_address = kp.address().decode() print('bobs_address: {}'.format(bob_address)) url = 'https://friendbot.stellar.org' r = requests.get(url, params={'addr': bob_address}) address = Address(address=bob_address) # See signature for additional args address.get() # Get the latest information from Horizon print('Bobs Balances: {}'.format(address.balances)) builder = Builder(secret=seed) builder.append_payment_op(bob_address, '100', 'XLM') builder.add_text_memo('For beers') # string length <= 28 bytes builder.sign() # Uses an internal horizon instance to submit over the network response = builder.submit() address = Address(address=bob_address) # See signature for additional args address.get() # Get the latest information from Horizon print('Bobs Balances: {}'.format(address.balances)) address = Address(address=alice_address) # See signature for additional args address.get() # Get the latest information from Horizon print('Alice Balances: {}'.format(address.balances))
from stellar_base.builder import Builder seed = "SAUV4WPT2IY3N5OVQHGYLMOH4SPOUFS27YEER3BYFWVVIWSEETFIHTLQ" builder = Builder(secret=seed) # builder = Builder(secret=seed, network='public') for LIVENET bob_address = 'GBCCC62LUXPDL7DLNQPYJWASA672CCJOLCJRBSIFXNIPRMQRRQ2HCWW6' builder.append_payment_op(bob_address, '100', 'XLM') builder.add_text_memo("K L P") # string length <= 28 bytes builder.sign() # Uses an internal horizon instance to submit over the network builder.submit()