예제 #1
0
def main(inflation):
    # TODO: Let user select the connection type
    # The stellar/quickstart Docker image uses PostgreSQL
    conn = sqlite3.connect(db_address)

    # Get the next sequence number for the transactions
    sequence = horizon.account(pool_address).get('sequence')
    inflation = XLM_Decimal(inflation)
    transactions = []
    total_payments_cost = 0
    num_payments = 0
    total_fee_cost = 0

    # Create one transaction for each batch
    for batch in accounts_payouts(conn, pool_address, inflation):
        op_count = 0
        ops = {'sequence': sequence, 'operations': []}
        for aid, amount in batch:
            # Check if the payment destination (aid) is valid
            try:
                acc = horizon.get(aid)
            except AccountNotExistError:
                continue
            if not acc:
                continue
            # Include payment operation on ops{}
            ops['operations'].append(aid, amount)
            op_count += 1

        # Build transaction
        tx = Transaction(source=pool_address, opts=ops)
        tx.fee = op_count * BASE_FEE
        envelope = Te(tx=tx, opts={"network_id": network})
        # Append the transaction plain-text (JSON) on the list
        transactions.append(envelope.xdr().decode("utf-8"))

        # Calculate stats
        total_fee_cost += XLM_Decimal(tx.fee) / XLM_STROOP
        total_payments_cost += sum(
            [XLM_Decimal(payment.amount) for payment in tx.operations])
        num_payments += len(tx.operations)

        # Prepare the next sequence number for the transactions
        sequence = int(sequence) + 1

    print(("Stats: \n"
           "Inflation received: %s\n"
           "A total of %s XLM paid over %s inflation payments "
           "using %s XLM in fees. \n"
           "Number of people that donated votes: %s\n") % (
               inflation,
               total_payments_cost,
               num_payments,
               total_fee_cost,
               len(donors),
           ))

    with open("transactions.json", 'w') as outf:
        json.dump(transactions, outf)
    print("Done. Output to transactions.json")
예제 #2
0
def tx_build(address, operation, seq=None, time_bounds=None, memo=None, fee=None):
    if seq is None:
        seq = get_sequence(address)
    # TODO memo to Memo()
    opts = dict(seqNum=seq, timeBounds=time_bounds, memo=memo, fee=fee)
    tx = Transaction(address, opts)
    tx.add_operation(operation)
    return tx
예제 #3
0
 def do(self, network, op):
     tx = Transaction(self.source, sequence=1)
     tx.add_operation(op)
     envelope = Te(tx, network_id=network)
     signer = Keypair.from_seed(self.seed)
     envelope.sign(signer)
     envelope_b64 = envelope.xdr()
     return envelope_b64
예제 #4
0
 def do(self, network, opts):
     tx = Transaction(self.source, **opts)
     tx.add_operation(Inflation())
     envelope = Te(tx, network_id=network)
     signer = Keypair.from_seed(self.seed)
     envelope.sign(signer)
     envelope_b64 = envelope.xdr()
     print(envelope_b64)
     return envelope_b64
예제 #5
0
def send_asset(amt, from_addr, to_addr, asset_nm):
    asset = Asset(asset_nm, issuer_addr)
    tx = Transaction(source=from_addr['address'], opts={'sequence': str(get_sequence(from_addr['address'])), 'fee': 100})
    pay_dic = {'destination': to_addr['address'],'asset': asset, 'amount': str(amt)}
    tx.add_operation(operation=Payment(pay_dic))
    envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
    envelope.sign(Keypair.from_seed(from_addr['seed']))
    req = hz.submit(te=envelope.xdr())
    print(req)
예제 #6
0
 def do(self, op):
     from stellar_base.transaction import Transaction
     from stellar_base.keypair import Keypair
     from stellar_base.transaction_envelope import TransactionEnvelope as Te
     tx = Transaction(source=self.source, opts={'sequence': self.seq})
     tx.add_operation(operation=op)
     envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
     signer = Keypair.from_seed(seed=self.seed)
     envelope.sign(keypair=signer)
     envelope_b64 = envelope.xdr()
     print(envelope_b64)
     return envelope_b64
예제 #7
0
 def do(self, op):
     from stellar_base.transaction import Transaction
     from stellar_base.keypair import Keypair
     from stellar_base.transaction_envelope import TransactionEnvelope as Te
     tx = Transaction(source=self.source, opts={'sequence': self.seq})
     tx.add_operation(operation=op)
     envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
     signer = Keypair.from_seed(seed=self.seed)
     envelope.sign(keypair=signer)
     envelope_b64 = envelope.xdr()
     print(envelope_b64)
     return envelope_b64
예제 #8
0
 def make_envelope(self, network, *args, **kwargs):
     opts = {'sequence': 1, 'fee': 100 * len(args)}
     for opt, value in kwargs.items():
         opts[opt] = value
     tx = Transaction(self.address, **opts)
     for count, op in enumerate(args):
         tx.add_operation(op)
     envelope = Te(tx, network_id=network)
     signer = Keypair.from_seed(self.seed)
     envelope.sign(signer)
     envelope_b64 = envelope.xdr()
     print(envelope_b64)
     return envelope_b64
예제 #9
0
def make_envelope(network, horizon, address, seed, *args, **kwargs):
    opts = {
        'sequence': horizon.account(address)['sequence'],
        'fee': 100 * len(args)
    }
    for opt, value in kwargs.items():
        opts[opt] = value
    tx = Transaction(address, **opts)
    for count, op in enumerate(args):
        tx.add_operation(op)
    envelope = Te(tx, network_id=network)
    signer = Keypair.from_seed(seed)
    envelope.sign(signer)
    envelope_xdr = envelope.xdr()
    return envelope_xdr
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')
예제 #11
0
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 Place_buy_order(buyAsset, buyAssetIssuer, amount, offerID, price,
                    sourceAdd, sourceSeed):
    #the amount here need to be the amount of xlm you want to sell, and the price need to be the price of xlm in terms of the asset you want to buy
    from stellar_base.operation import ManageOffer
    sequence3 = horizon.account(sourceAdd).get('sequence')
    assetBuy = asset_Identifier(buyAsset, buyAssetIssuer)
    assetSell = Asset('XLM')
    op_so = ManageOffer({
        'selling': assetSell,
        'buying': assetBuy,
        'amount': str(amount),
        'price': str(price),
        'offer_id': offerID
    })
    tx_so = Transaction(source=sourceAdd,
                        opts={
                            'sequence': sequence3,
                            'operations': [op_so]
                        })
    envelope_so = Te(tx=tx_so, opts={"network_id": "PUBLIC"})
    kp = Keypair.from_seed(sourceSeed)
    envelope_so.sign(kp)
    xdr3 = envelope_so.xdr()
    response = horizon.submit(xdr3)
    result = passed_or_not(response)
    return response['result_xdr']
def Cancel_buy_order(buyAsset, buyAssetIssuer, price, xdr_result, sourceAdd,
                     sourceSeed):
    from stellar_base.operation import ManageOffer
    offerID = Get_offer_ID(xdr_result)
    sequence3 = horizon.account(sourceAdd).get('sequence')
    assetBuy = asset_Identifier(buyAsset, buyAssetIssuer)
    assetSell = Asset('XLM')
    op_so = ManageOffer({
        'selling': assetSell,
        'buying': assetBuy,
        'amount': str(0),
        'price': str(price),
        'offer_id': offerID
    })  #How to get the ID of existing order
    tx_so = Transaction(source=sourceAdd,
                        opts={
                            'sequence': sequence3,
                            'operations': [op_so]
                        })
    envelope_so = Te(tx=tx_so, opts={"network_id": "PUBLIC"})
    kp = Keypair.from_seed(sourceSeed)
    envelope_so.sign(kp)
    xdr3 = envelope_so.xdr()
    response = horizon.submit(xdr3)
    result = passed_or_not(response)
    return response['result_xdr']
예제 #14
0
def sending_asset(Asset_symbol,Asset_Issuer,desAdd,amount):
    '''Similar to sending_lumen except this function sends created assets.
    Asset_symbol: string, symbol of the asset, eg. 'BTC'
    Asset_Issuer: string, Address of the asset Issuer.
    desAdd:string, the address of the lumen receiver.
    amount:float, the amount of lumens you want to send.
    msg:string, optional, the message you want to attach to the transaction.'''
    data = Get_data()
    
    sourceAdd = data['Address']
    asset = asset_Identifier(Asset_symbol,Asset_Issuer)
    
    sequence = horizon.account(sourceAdd).get('sequence')
    op = Payment({'asset':asset,'amount':str(amount),'destination':desAdd})
    tx = Transaction(source=sourceAdd,opts={'sequence':sequence,'operations':[op]})
    envelope_send = Te(tx = tx,opts = {"network_id":"PUBLIC"})
    
    try: envelope_send.sign(Trezor_Access())
    except: raise Exception("Device is currently in use, try reconnect the device")
    
    xdr = envelope_send.xdr()
    xdr = xdr.decode()
    response = horizon.submit(xdr)
    passed_or_not(response)
    return response
예제 #15
0
 def make_envelope(self, *args, **kwargs):
     from stellar_base.transaction import Transaction
     from stellar_base.keypair import Keypair
     from stellar_base.transaction_envelope import TransactionEnvelope as Te
     opts = {'sequence': self.seq, 'fee': self.fee * len(args)}
     for opt, value in kwargs.items():
         opts[opt] = value
     tx = Transaction(source=self.address, opts=opts)
     for count, op in enumerate(args):
         tx.add_operation(operation=op)
     envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
     signer = Keypair.from_seed(seed=self.seed)
     envelope.sign(keypair=signer)
     envelope_b64 = envelope.xdr()
     print(envelope_b64)
     return envelope_b64
예제 #16
0
    def post(self, request):
        source_private_key = request.data.get('sourcePrivateKey')
        dest_address = request.data.get('destAddress')
        amount = request.data.get('amount', '0.0000001')
        source = Keypair.from_seed(source_private_key)
        source_address = source.address().decode('UTF-8')

        requests.get(url=friend_bot_url, params={'addr': source_address})
        requests.get(url=friend_bot_url, params={'addr': dest_address})

        # Create operations for transaction
        payment = Payment(destination=dest_address,
                          asset=Asset('XLM'),
                          amount=amount)
        memo = TextMemo('Transaction Memo')
        sequence = horizon.account(source_address).get('sequence')

        operations = [payment]

        try:
            transaction = Transaction(source=source_address,
                                      sequence=sequence,
                                      memo=memo,
                                      fee=100 * len(operations),
                                      operations=operations)
            envelope = TransactionEnvelope(tx=transaction, network_id="TESTNET")
            # Sign the sender
            envelope.sign(source)
            # Submit it to the network
            xdr = envelope.xdr()
            response = horizon.submit(xdr)

            return Response(response, status=status.HTTP_200_OK)
        except HorizonError as horizonError:
            return Response(horizonError.message, status=horizonError.status_code)
예제 #17
0
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))
예제 #18
0
def do_single_signer(operation_opts=False, tx_opts=False):
    assert operation_opts and tx_opts
    from stellar_base.operation import Payment
    from stellar_base.transaction import Transaction
    from stellar_base.keypair import Keypair
    from stellar_base.transaction_envelope import TransactionEnvelope as Te

    operation = Payment(opts=operation_opts)
    tx = Transaction(source=SOURCE, opts=tx_opts)
    tx.add_operation(operation=operation)
    envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
    signer = Keypair.from_seed(seed=SEED)
    envelope.sign(keypair=signer)
    envelope_b64 = bip(envelope)

    print(envelope_b64)
    return envelope_b64
예제 #19
0
    def make_envelope(self, *args, **kwargs):
        from stellar_base.transaction import Transaction
        from stellar_base.keypair import Keypair
        from stellar_base.transaction_envelope import TransactionEnvelope as Te

        opts = {"sequence": self.seq, "fee": self.fee * len(args)}
        for opt, value in kwargs.items():
            opts[opt] = value
        tx = Transaction(source=self.address, opts=opts)
        for count, op in enumerate(args):
            tx.add_operation(operation=op)
        envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
        signer = Keypair.from_seed(seed=self.seed)
        envelope.sign(keypair=signer)
        envelope_b64 = envelope.xdr()
        print(envelope_b64)
        return envelope_b64
예제 #20
0
def main(inflation):
	inflation = XLM_Decimal(inflation)

	conn = sqlite3.connect(db_address)
	transactions = []

	sequence = horizon.account(pool_address).get('sequence')
	total_payments_cost = 0
	num_payments = 0
	total_fee_cost = 0

	for batch in accounts_payout(conn, pool_address, inflation):
		tx = Transaction(
			source = pool_address,
			opts = {
				'sequence': sequence,
				'operations': [make_payment_op(aid, amount) for aid, amount in batch]
			}
		)
		tx.fee = len(tx.operations) * 100
		envelope = Te(tx = tx, opts = {"network_id": network})
		transactions.append(envelope.xdr().decode("utf-8"))

		total_fee_cost += XLM_Decimal(tx.fee) / XLM_STROOP
		total_payments_cost += sum([XLM_Decimal(payment.amount) for payment in tx.operations])
		num_payments += len(tx.operations)

		sequence = int(sequence) + 1

	print(
		"Stats: \n\
		Inflation received: " + str(inflation) + "\n\
		A total of " + str(total_payments_cost) +\
		" XLM paid over " + str(num_payments) +\
		" inflation payments using " + str(total_fee_cost) + " XLM in fees. \n\
		People donated " + str(sum([n for n in donations.values()])) +\
		" XLM to " + str(len(donations.keys())) +\
		" different addresses.\n"
	)

	with open("transactions.json", 'w') as outf:
		json.dump(transactions, outf)
	print("Done. Output to transactions.json")
예제 #21
0
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)
예제 #22
0
def set_account_signers(horizon, pool_keypair, signers, threshold):
	pool_address = pool_keypair.address().decode()

	operations = [
		SetOptions({
			"signer_address": signer_address,
			"signer_weight": 1,
			"signer_type": "ed25519PublicKey",
			"source_account": pool_address
		})
		for signer_address in signers
	]

	operations.append(
		SetOptions({
			"source_account": pool_address,
			"home_domain": bytes("lumenaut.net", "utf-8"),
			"master_weight": 0,
			"low_threshold": threshold["low"],
			"med_threshold": threshold["medium"],
			"high_threshold": threshold["high"],
			"inflation_dest": pool_address
		})
	)

	sequence = horizon.account(pool_address).get('sequence')
	tx = Transaction(
		source=pool_address,
		opts={
			'sequence': sequence,
			'fee': 100 * len(operations),
			'operations': operations,
		},
	)

	envelope = Te(tx=tx, opts={"network_id": network})
	envelope.sign(pool_keypair)

	xdr = envelope.xdr()
	response = horizon.submit(xdr)

	if "_links" in response:
		logger.debug(
			"Set options transaction href: ",
			response["_links"]["transaction"]["href"])
		logger.debug("Created successfully!")
		return True
	else:
		logger.error("Failed to set account signers, dumping response:")
		logger.error(response)
		return False
예제 #23
0
    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......")
예제 #24
0
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
예제 #25
0
 def create_te(self, user_kaykair, sequence, memo, op, FEE=200):
     """创建te"""
     tx = Transaction(
         source=user_kaykair.address().decode(),
         opts={
             'sequence': sequence,
             'memo': TextMemo(memo),
             'fee': FEE,
             'operations': [op],
         },
     )
     envelope = Te(tx=tx, opts=dict(network_id=self._network_id))
     envelope.sign(user_kaykair)
     te = envelope.xdr()
     tx_hash = hashlib.sha256(envelope.signature_base()).hexdigest()
     return te, tx_hash
예제 #26
0
def create_envelope(user_kaykair, sequence, memo, opers, FEE=0):
    """事务封包"""
    tx = Transaction(
        source=user_kaykair.address().decode(),  # 事务发起着的公钥
        opts={
            'sequence': sequence,  # 事务发起着的序列号
            'memo': TextMemo(memo),  # 备注
            'fee': len(opers) * FEE,  # 手续费
            'operations': opers,
        },
    )  # 操作
    envelope = Te(tx=tx, opts=dict(network_id='XIANDA_DEV_NET'))  # 操作封包的类Te
    envelope.sign(user_kaykair)  # 事务发起着签名
    # te = envelope.xdr()  # 转换xdr格式数据
    te_hash = hashlib.sha256(envelope.signature_base()).hexdigest()
    return te_hash
예제 #27
0
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 Trusting_asset(assetName, issuerAdd, truster, trusterSeed, limit):
    asset = Asset(assetName, issuerAdd)
    sequence2 = horizon.account(truster).get('sequence')
    op_ct = ChangeTrust({'asset': asset, 'limit': str(limit)})
    tx_ct = Transaction(source=truster,
                        opts={
                            'sequence': sequence2,
                            'operations': [
                                op_ct,
                            ]
                        })
    envelope_ct = Te(tx=tx_ct, opts={"network_id": "PUBLIC"})
    kp = Keypair.from_seed(trusterSeed)
    envelope_ct.sign(kp)  #sign
    xdr2 = envelope_ct.xdr()
    response = horizon.submit(xdr2)  #submit
    result = passed_or_not(response)
    return response
예제 #29
0
def create_envelope_submits(user_kaykair, sequence, memo, opers, FEE=FEE):
    """事务封包,并提交"""
    tx = Transaction(
        source=user_kaykair[0].address().decode(),  # 事务发起着的公钥
        opts={
            'sequence': sequence,  # 事务发起着的序列号
            'memo': TextMemo(memo),  # 备注
            'fee': len(opers) * FEE,  # 手续费
            'operations': opers,
        },
    )  # 操作
    envelope = Te(tx=tx, opts=dict(network_id='XIANDA_DEV_NET'))  # 操作封包的类Te
    for i in user_kaykair:
        print 2222, user_kaykair

        envelope.sign(i)
    # envelope.sign(user_kaykair)  # 事务发起着签名
    te = envelope.xdr()  # 转换xdr格式数据
    return submit(te, envelope)
def Fund_new_account(newAdd, IssuerAdd, IssuerSeed, XLMamount):
    from stellar_base.operation import CreateAccount
    sequence = horizon.account(IssuerAdd).get('sequence')
    op = CreateAccount({
        'destination': newAdd,
        'starting_balance': str(XLMamount)
    })
    tx = Transaction(source=IssuerAdd,
                     opts={
                         'sequence': sequence,
                         'operations': [op]
                     })
    envelope = Te(tx=tx, opts={"network_id": "PUBLIC"})
    kp = Keypair.from_seed(IssuerSeed)
    envelope.sign(kp)
    xdr = envelope.xdr()
    response = horizon.submit(xdr)
    result = passed_or_not(response)
    return response
def Sending_lumen(sourceAdd, sourceSeed, desAdd, amount):
    asset = Asset('XLM')
    sequence = horizon.account(sourceAdd).get('sequence')
    op = Payment({
        'asset': asset,
        'amount': str(amount),
        'destination': desAdd
    })
    tx = Transaction(source=sourceAdd,
                     opts={
                         'sequence': sequence,
                         'operations': [op]
                     })
    envelope_send = Te(tx=tx, opts={"network_id": "PUBLIC"})
    kp = Keypair.from_seed(sourceSeed)
    envelope_send.sign(kp)
    xdr = envelope_send.xdr()
    response = horizon.submit(xdr)
    result = passed_or_not(response)
    return response
예제 #32
0
파일: xlm.py 프로젝트: buyongji/wallet
    def create_account(self, old_account_seed, new_account_address, amount,
                       memo):
        """
        用已有账户创建新账户
        """
        horizon = self.client
        account_seed = old_account_seed
        old_account_keypair = Keypair.from_seed(account_seed)
        account_addr = new_account_address
        start_amount = amount  # Your new account minimum balance (in XLM) to transfer over
        # create the CreateAccount operation
        opts = {'destination': account_addr, 'starting_balance': start_amount}
        op = CreateAccount(opts)
        # create a memo
        txt_memo = TextMemo(memo)

        # Get the current sequence of the source account by contacting Horizon. You
        # should also check the response for errors!
        try:
            sequence = horizon.account(
                old_account_keypair.address().decode()).get('sequence')
        except Exception as e:
            logger.exception(e)
        # Create a transaction with our single create account operation, with the
        # default fee of 100 stroops as of this writing (0.00001 XLM)
        trans_ops = {
            'sequence': sequence,
            'memo': txt_memo,
            'operations': [op]
        }
        tx = Transaction(source=old_account_keypair.address().decode(),
                         opts=trans_ops)
        env_opts = {'network_id': 'TESTNET'}
        envelope = TransactionEnvelope(tx=tx, opts=env_opts)
        # Sign the transaction envelope with the source keypair
        envelope.sign(old_account_keypair)

        # Submit the transaction to Horizon
        te_xdr = envelope.xdr()
        response = horizon.submit(te_xdr)
        return response
def Sending_asset(assetName, issuerAdd, sourceAdd, sourceSeed, desAdd, amount):
    asset = Asset(assetName, issuerAdd)
    sequence1 = horizon.account(sourceAdd).get('sequence')
    op_pay = Payment({
        'asset': asset,
        'amount': str(amount),
        'destination': desAdd
    })
    tx_pay = Transaction(source=sourceAdd,
                         opts={
                             'sequence': sequence1,
                             'operations': [
                                 op_pay,
                             ]
                         })
    envelope_pay = Te(tx=tx_pay, opts={"network_id": "PUBLIC"})
    kp = Keypair.from_seed(sourceSeed)
    envelope_pay.sign(kp)
    xdr1 = envelope_pay.xdr()
    response = horizon.submit(xdr1)
    result = passed_or_not(response)
    return response
예제 #34
0
def Trusting_asset(assetName,issuerAdd,limit):
    data = Get_data()
    
    sourceAdd = data['Address']
    asset = asset_Identifier(assetName,issuerAdd)
    
    sequence2 = horizon.account(sourceAdd).get('sequence')
    op_ct = ChangeTrust({'asset':asset, 'limit':str(limit)})
    tx_ct = Transaction(source=sourceAdd, opts = {'sequence':sequence2, 'operations':[op_ct,]})
    envelope_ct = Te(tx=tx_ct, opts={"network_id": "PUBLIC"})
    kp = Keypair.from_seed(Trezor_Access())
    envelope_ct.sign(kp)                 #sign
    xdr2 = envelope_ct.xdr()
    response=horizon.submit(xdr2)           #submit
    passed_or_not(response)
    return response