Пример #1
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)
Пример #2
0
def make_payment_op(account_id, amount):
	return Payment({
		'destination': account_id,
		'source': pool_address,
		'amount': str(amount),
		'asset': Asset('XLM')
	})
Пример #3
0
def send_xlm_vault_transaction(user, destination, amount):
    from stellar_base.transaction import Transaction
    wallet = VaultWallet.objects.get(username=user, name="xlm")
    User = Keypair.from_seed(wallet.private)
    horizon = horizon_testnet()
    asset = Asset.native()

    op = Payment({
        'destination': destination,
        'asset': asset,
        'amount': amount
    })
    msg = TextMemo('From test net !')

    sequence = horizon.account(User.address().decode('utf-8')).get('sequence')

    tx = Transaction(
        source=User.address().decode(),
        opts={
            'sequence': sequence,
            'memo': msg,
            'operations': [
                op,
            ],
        },
    )
    try:
        envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
        envelope.sign(User)
        xdr = envelope.xdr()
        response = horizon.submit(xdr)
        return response['hash']
    except:
        return {"error": ""}
Пример #4
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
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')
Пример #6
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)
Пример #7
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)
Пример #8
0
def test_submit(setup, helpers):
    kp = Keypair.random()
    address = kp.address().decode()
    seed = kp.seed()

    helpers.fund_account(setup, address)

    horizon = Horizon(setup.horizon_endpoint_uri)

    envelope_xdr = make_envelope(
        setup.network, horizon, address, seed,
        Payment(destination=address, asset=Asset.native(), amount="0.0001618"))
    response = horizon.submit(envelope_xdr)
    assert 'hash' in response
Пример #9
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
Пример #10
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......")
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
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
Пример #13
0
def sending_lumen(desAdd,amount):
    '''Using trezor to send lumen. The required parameters are
    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('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"})
    
    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
from stellar_base.transaction import Transaction
from stellar_base.transaction_envelope import TransactionEnvelope as Te
from stellar_base.memo import TextMemo
from stellar_base.horizon import horizon_testnet, horizon_livenet

alice_seed = 'SBUORYV26AZ3ULEEC5FQ4NKPVRO7MBAWTW26YKCDPPKFGMK7WAYNX4UN'
bob_address = 'GBZF7GQJXXHD3OL3B5IOUICFDYIATZZ3F3XQ7SOQ5PXLVQMDSOI5ACEE'

Alice = Keypair.from_seed(alice_seed)
horizon = horizon_testnet()  # for TESTNET
# horizon = horizon_livenet() # for LIVENET

# create op
payment_op = Payment(
    # source=Alice.address().decode(),
    destination=bob_address,
    asset=Asset('XLM'),
    amount='10.5')

set_home_domain_op = SetOptions(home_domain='fed.network')

# create a memo
msg = TextMemo('Buy yourself a beer!')

# get sequence of Alice
# Python 3
sequence = horizon.account(Alice.address().decode('utf-8')).get('sequence')
# Python 2
# sequence = horizon.account(Alice.address()).get('sequence')

operations = [payment_op, set_home_domain_op]
Пример #15
0
 def app_payment_op(self, amount, destination):
     return Payment(opts={'destination': destination,
                          'amount': str(amount),
                          'asset': Client(self.network).get_stellar_asset(),
                          'source': self.app_keypair().address().decode()
                         })
Пример #16
0
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
Пример #17
0
    def send(self):
        """
		The method to make a payment
		"""
        address = self.receiverInput.get()
        asset = self.assetChosen.get()
        quantity = self.quantitySpin.get()
        valid = True
        #Verify address
        if self.address == address:
            messagebox.showerror("Bad address",
                                 "The destination address is your address")
            valid = False
        else:
            addressInfos = self.horizon.account(address)
            if "status" in addressInfos:
                messagebox.showerror(
                    "Invalid address",
                    "The address you provided doesn't refer to any account.")
                valid = False

        #Verifying that the destination accepts this asset
        if valid:
            valid = False
            if asset == "XLM":
                valid = True
            else:
                for i in addressInfos["balances"]:
                    if i["asset_type"] != "native":  #Else getting a Keyerror because the responded dict is different is asset is XLM
                        if i["asset_code"] == asset:
                            valid = True
                            break
            if not valid:
                messagebox.showwarning(
                    "Missing trustline",
                    "The destination account hasn't enabled the trustline for this currency"
                )

        #Verifying the quantity
        if valid:
            #Getting fresh infos about the user account
            freshInfos = self.horizon.account(self.address)
            #Checking the balances, we need greater or equal than the quantity if not XLM (and the XLM as minimum balance), if XLM we need more or greater than
            #the minimum balance (=1XLM + 0.5 XLM per subentry cf https://galactictalk.org/d/1371-cost-of-a-trustline, and 1 for the minimum balance cf https://www.stellar.org/faq/#_Why_is_there_a_minimum_balance)
            for i in freshInfos["balances"]:
                if i["asset_type"] != "native":
                    if i["asset_code"] == asset:
                        if float(i["balance"]) >= 0:
                            valid = True
                        else:
                            messagebox.showerror(
                                "Invalid Quantity",
                                "The quantity you entered doesn't match your balances"
                            )
                            valid = False
                else:
                    if asset == "XLM":
                        if float(i["balance"]) - float(
                                quantity) > self.nbOfSubentrys / 2 + 1:
                            valid = True
                        else:
                            messagebox.showerror(
                                "Invalid Quantity",
                                "The quantity you entered doesn't match your balances"
                            )
                            valid = False
                    else:
                        if float(i["balance"]) > self.nbOfSubentrys / 2 + 1:
                            valid = True
                        else:
                            messagebox.showerror(
                                "Invalid Quantity",
                                "The quantity you entered doesn't match your balances"
                            )
                            valid = False

        #If all the verification are passed, we build the tx
        if valid:
            #We create the operation
            if asset != "XLM":
                #We fetch the issuer of the token
                issuer = self.horizon.assets({
                    "asset_code": asset
                }).get("_embedded").get("records")[0].get(
                    "asset_issuer")  #ouch, cf Stellar.org and python SDK
                asset = Asset(asset, issuer)
            else:
                asset = Asset("XLM")
            operation = Payment({
                'source': self.address,
                'destination': address,
                'asset': asset,
                'amount': quantity
            })

            #MEMO ??

            #The sequence of the sender
            sequence = self.horizon.account(self.address).get("sequence")

            #Finally the tx
            tx = Transaction(source=self.address,
                             opts={
                                 'sequence': sequence,
                                 'operations': [operation]
                             })

            #We enveloppe, sign and submit it
            env = Te(tx=tx, opts={'network_id': 'PUBLIC'})
            env.sign(self.kp)
            response = self.horizon.submit(env.xdr())
            if response["status"] == 400:
                reason = response.get("extras").get("result_codes")
                messagebox.showerror("Transaction failed",
                                     reason.get("operations"))

            #To update
            self.run()
Пример #18
0
def send_payment(sender_seed, tx):
    # Generate the sender's Keypair for signing and setting as the source
    sender_kp = Keypair.from_seed(sender_seed)
    tx = {key.decode("utf-8"): val.decode("utf-8") for key, val in tx.items()}
    # Address for the destination
    destination = tx.get("to")

    # create op
    amount = tx.get("amount")
    if tx.get("currency").upper() == "XLM":
        asset = Asset("XLM")
    else:
        raise UnknownIssuerError("Unknown currency and/or issuer.")
        # TODO:
        # Issuer's address
        # ISSUER = tx.get('issuer')
        # asset = Asset(tx.get('currency').upper(), ISSUER)

    op = Payment(
        # Source is also inferred from the transaction source, so it's optional.
        source=sender_kp.address().decode(),
        destination=destination,
        asset=asset,
        amount=amount,
    )

    # create a memo
    msg = TextMemo("Stellar-SMS is dope!!!")

    horizon = horizon_testnet()
    # horizon = horizon_livenet() for LIVENET

    # Get the current sequence of sender
    sequence = horizon.account(
        sender_kp.address().decode("utf-8")).get("sequence")

    # TODO: track sequence locally for better accuracy, speed, and robustness

    # Construct a transaction
    tx = Transaction(
        source=sender_kp.address().decode(),
        sequence=sequence,
        # time_bounds = {'minTime': 1531000000, 'maxTime': 1531234600},
        memo=msg,
        fee=100,  # Can specify a fee or use the default by not specifying it
        operations=[op],
    )

    # Build transaction envelope
    envelope = Te(tx=tx, network_id="TESTNET")  # or 'PUBLIC'

    # Sign the envelope
    envelope.sign(sender_kp)

    # Submit the transaction to Horizon!
    xdr = envelope.xdr()
    response = horizon.submit(xdr)
    log.debug(str(response))
    if response.get("status") not in [None, 200]:
        log.error(
            f"Submission unsuccessful. Horizon retured with error: {response.detail}"
        )
        return
    log.debug("Transaction was successfully submitted to the network.")
    return True
Пример #19
0
from stellar_base.memo import TextMemo
from stellar_base.horizon import horizon_testnet, horizon_livenet

alice_seed = 'SAZJ3EDATROKTNNN4WZBZPRC34AN5WR43VEHAFKT5D66UEZTKDNKUHOK'
bob_address = 'GDLP3SP4WP72L4BAJWZUDZ6SAYE4NAWILT5WQDS7RWC4XCUNUQDRB2A4'
CNY_ISSUER = 'GDVDKQFP665JAO7A2LSHNLQIUNYNAAIGJ6FYJVMG4DT3YJQQJSRBLQDG'
amount = '10'

Alice = Keypair.from_seed(alice_seed)
horizon = horizon_testnet()  # horizon = horizon_livenet() for LIVENET

asset = Asset('CNY', CNY_ISSUER)
# create op
op = Payment({
    # 'source' : Alice.address().decode(),
    'destination': bob_address,
    'asset': asset,
    'amount': amount
})
# create a memo
msg = TextMemo('Buy yourself a beer !')

# get sequence of Alice
# Python 3
sequence = horizon.account(Alice.address().decode('utf-8')).get('sequence')
# Python 2
# sequence = horizon.account(Alice.address()).get('sequence')

# construct Tx
tx = Transaction(
    source=Alice.address().decode(),
    opts={
Пример #20
0
def pay_have_fee(
    collect_account_public,
    amount,
    coin_name,
    flow_status_id,
    pay_account_seed,
    sequence,
    memo_oreder_id,
    merchant_private,
    fee,
):
    fee = str(fee)
    amount = str(amount)
    opts = list()
    opt_frist = Payment(
        dict(destination=collect_account_public,
             asset=Asset.native(),
             amount=str(fee)))
    opt_sceond = Payment(
        dict(destination=collect_account_public,
             asset=Asset.native() if coin_name == PAYDEX_CODE else Asset(
                 coin_name, COINS_ISSUER),
             amount=str(amount)))
    opts.append(opt_frist)
    opts.append(opt_sceond)
    user = Keypair.from_seed(merchant_private)
    users = user.address()
    is_success, stellar_hash = create_envelope_submit(user, sequence,
                                                      memo_oreder_id, opts)
    if not is_success:
        try:
            order = OrderDetail()
            order.query.filter_by(orders=flow_status_id).update(
                {'pay_status': 2})
            db.session.commit()
        except Exception as e:
            logging.error(
                str(e) + u'user:%s, coin_name:%s, amount:%s转账成功存入数据哭失败' %
                (users, coin_name, amount))
            return False, u'paydex 修改状态失败转账失败'
        # 异步 请求恒星底层
        # stellar.pay_stellar(collect_account_public, amount, coin_name, flow_status_id, pay_account_seed,memo_oreder_id)
        stellar.pay_stellar.delay(collect_account_public, amount, coin_name,
                                  flow_status_id, pay_account_seed,
                                  memo_oreder_id)
        # 生产随机字符串
        rand_string = random_str()
        if rand_string is None:
            return False, u'随机字符串生成失败'

        # 验证签名
        sign_name = fun_var_kargs(flow_status_id=flow_status_id,
                                  status='2',
                                  rand_string=rand_string)
        url = PHP_URL
        params = dict(flow_status_id=flow_status_id,
                      status='2',
                      sign=sign_name,
                      rand_string=rand_string)
        print '111', params

        response = requests.post(url, data=params).json()
        if response.get('code') == 200:
            print "通知php成功"
        if response.get('code') != 200:
            return times.time_task.delay(params, stellar_hash, users,
                                         coin_name, amount, response,
                                         flow_status_id)
    else:
        # 生产随机字符串
        rand_string = random_str()
        if rand_string is None:
            return False, u'随机字符串生成失败'

        # 验证签名
        sign_name = fun_var_kargs(flow_status_id=flow_status_id,
                                  success_no=stellar_hash,
                                  status='1',
                                  rand_string=rand_string)
        url = PHP_URL
        params = dict(flow_status_id=flow_status_id,
                      success_no=stellar_hash,
                      status='1',
                      sign=sign_name,
                      rand_string=rand_string)
        print '111', params
        response = requests.post(url, data=params).json()
        print '2222', response
        if response.get('code') == 200:
            print "通知php成功***************************************************"
            if is_success:
                insert_tasks.delay(stellar_hash, flow_status_id, users,
                                   coin_name, amount)
                # insert_tasks(stellar_hash, flow_status_id, users, coin_name, amount)
                print "转账插入数据库成功!**********************************************"
            return True

        if response.get('code') != 200:
            return times.time_task.delay(params, stellar_hash, users,
                                         coin_name, amount, response,
                                         flow_status_id)
Пример #21
0
def pay_for_exchange(amount, coin_name, flow_status_id, exchange_account_seed,
                     sequence, fee, memo_oreder_id):
    exchange_amount = amount.split("/")[0]
    get_amount = amount.split("/")[1]
    exchange_coin_name = coin_name.split("/")[0]
    get_coin_name = coin_name.split("/")[1]
    user = Keypair.from_seed(exchange_account_seed)
    finania_kp = Keypair.from_seed(COIN_SEED)
    user_keypair = [user, finania_kp]
    memo = u'{}转账'.format(coin_name)
    opts = list()
    if fee != "0":
        op = Payment({
            'destination':
            COIN_ISSUER,
            'asset':
            Asset.native() if exchange_coin_name == PAYDEX_CODE else Asset(
                exchange_coin_name, COINS_ISSUER),
            'amount':
            str(exchange_amount),
            'source':
            user.address()
        })
        op1 = Payment({
            'destination': COIN_ISSUER,
            'asset': Asset.native(),
            'amount': str(fee),
            'source': user.address()
        })
        op2 = Payment({
            'destination':
            user.address(),
            'asset':
            Asset.native() if get_coin_name == PAYDEX_CODE else Asset(
                get_coin_name, COINS_ISSUER),
            'amount':
            str(get_amount),
            'source':
            COIN_ISSUER
        })
        opts.append(op)
        opts.append(op1)
        opts.append(op2)
    else:
        op = Payment({
            'destination':
            COIN_ISSUER,
            'asset':
            Asset.native() if exchange_coin_name == PAYDEX_CODE else Asset(
                exchange_coin_name, COINS_ISSUER),
            'amount':
            str(exchange_amount),
            'source':
            user.address()
        })
        op2 = Payment({
            'destination':
            user.address(),
            'asset':
            Asset.native() if get_coin_name == PAYDEX_CODE else Asset(
                get_coin_name, COINS_ISSUER),
            'amount':
            str(get_amount),
            'source':
            COIN_ISSUER
        })
        opts.append(op)
        opts.append(op2)
    is_success, stellar_hash = create_envelope_submits(user_keypair, sequence,
                                                       memo, opts)
    if not is_success:
        try:
            exchange = ExchangeDetail()
            exchange.query.filter_by(orders=flow_status_id).update({
                'pay_status':
                2,
                'stellar_hash':
                stellar_hash
            })
            db.session.commit()
        except Exception as e:
            logging.error(
                str(e) + u'user:%s, coin_name:%s, amount:%s转账成功存入数据哭失败' %
                (user_keypair, coin_name, amount))
            return False, u'paydex 修改状态失败转账失败'
        # 异步 请求恒星底层
        # stellar.pay_stellar(memo_oreder_id, amount, coin_name, flow_status_id, exchange_account_seed,
        #                     flow_status_id)
        stellar.pay_stellar.delay(memo_oreder_id, amount, coin_name,
                                  flow_status_id, exchange_account_seed,
                                  flow_status_id)
        # 生产随机字符串
        rand_string = random_str()
        if rand_string is None:
            return False, u'随机字符串生成失败'

        # 验证签名
        sign_name = fun_var_kargs(flow_status_id=flow_status_id,
                                  status='2',
                                  rand_string=rand_string)
        url = PHP_URL
        params = dict(flow_status_id=flow_status_id,
                      status='2',
                      sign=sign_name,
                      rand_string=rand_string)
        print '111', params
        response = requests.post(url, data=params).json()
        print '2222', response
        if response.get('code') == 200:
            print "通知PHP成功****************************************"
        else:
            return times.time_task.delay(params, stellar_hash, is_success,
                                         user, coin_name, amount, response,
                                         flow_status_id)

    else:
        # 生产随机字符串
        rand_string = random_str()
        if rand_string is None:
            return False, u'随机字符串生成失败'

        # 验证签名
        sign_name = fun_var_kargs(flow_status_id=flow_status_id,
                                  success_no=stellar_hash,
                                  status='1',
                                  rand_string=rand_string)
        url = PHP_URL
        params = dict(flow_status_id=flow_status_id,
                      success_no=stellar_hash,
                      status='1',
                      sign=sign_name,
                      rand_string=rand_string)
        print '111', params
        response = requests.post(url, data=params).json()
        print '2222', response
        if response.get('code') == 200:
            print "请求PHP成功******************************************"
            if is_success:
                # insert_tasks(stellar_hash, flow_status_id, user, coin_name, amount)
                insert_tasks.delay(stellar_hash, flow_status_id, user,
                                   coin_name, amount)
                return "插入数据库成功**************************************"

        if response.get('code') != 200:
            return times.time_task.delay(params, stellar_hash, is_success,
                                         user, coin_name, amount, response,
                                         flow_status_id)