Example #1
0
 def test_pathPayment_min(self):
     result = b'AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAAAAAABAAAAAQAAAADTUozdcK3X4scPuMNM5il78cYpIOhCjIvUltQ5zT4TYwAAAAIAAAAAAAAAAACYloAAAAAAra4WiCvFr/vydTiUbSQF0HwkqErP8wc6BUQav3qSQI4AAAAAAAAAAACYloAAAAAAAAAAAAAAAAHNPhNjAAAAQFwSz9wwBEWCv9cNnuIq+Jjq36mXBI22f6uj/FZ6LbyLljkckSLkF/AqXcaOoOgY9mZ0NrXsHbA5/chSThtgMgQ='  # TODO
     assert (result == self.do(op=PathPayment({
         'source': self.source,
         'destination': self.dest,
         'send_asset': Asset.native(),
         'dest_asset': Asset.native(),
         'send_max': self.amount,
         'dest_amount': self.amount,
         'path': [],
     })))
Example #2
0
 def test_double_payment(self):
     result = b'AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAyAAAAAAAAAACAAAAAAAAAAAAAAACAAAAAAAAAAEAAAAAlMoegcSS0iHsTrJ5XNJH1ri4rO05uVmRHX6dbOj22fgAAAAAAAAAAAvrwgAAAAAAAAAAAQAAAABNqbPPMcFohrLf2BM4UPn/CB/t1jVq0x9DBET5ki/XaAAAAAAAAAAAF9eEAAAAAAAAAAABzT4TYwAAAEAhTZr3nE2w9LBziL54UuyuEgUa4MJaXfMnZpHpu9+TYgPaDE3M6DNe6Du8ZSSC89LCGfpS1Fs38JB0U5rikmMP'
     assert (result == self.make_envelope(
         Payment({
             'destination': self.accounts[0]['address'],
             'asset': Asset.native(),
             'amount': self.amount * 1,
         }),
         Payment({
             'destination': self.accounts[1]['address'],
             'asset': Asset.native(),
             'amount': self.amount * 2,
         }),
         ))
Example #3
0
 def test_payment_min(self):
     result = b"AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAAAAAABAAAAAQAAAADTUozdcK3X4scPuMNM5il78cYpIOhCjIvUltQ5zT4TYwAAAAEAAAAAra4WiCvFr/vydTiUbSQF0HwkqErP8wc6BUQav3qSQI4AAAAAAAAAAACYloAAAAAAAAAAAc0+E2MAAABAzEdbP2ISsB9pDqmIRPt6WEK0GkVOgAEljnelNQjNpDig6A60+jMtveQjdCocL13GwVbO1B8VBXgQdlAobs0fDg=="
     assert result == self.do(
         op=Payment(
             {"source": self.source, "destination": self.dest, "asset": Asset.native(), "amount": self.amount}
         )
     )
Example #4
0
 def test_mix_1(self):
     result = b'AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAADhAAAAAAAAAACAAAAAAAAAAAAAAAJAAAAAAAAAAAAAAAAlMoegcSS0iHsTrJ5XNJH1ri4rO05uVmRHX6dbOj22fgAAAAAC+vCAAAAAAAAAAABAAAAAE2ps88xwWiGst/YEzhQ+f8IH+3WNWrTH0MERPmSL9doAAAAAAAAAAAL68IAAAAAAAAAAAIAAAAAAAAAAAvrwgAAAAAAoEATyhnfBjtgSGL5Fr4oHlw/X4bIYnH44zIpor2MQbUAAAAAAAAAAAvrwgAAAAAAAAAAAAAAAAMAAAABYmVlcgAAAACUyh6BxJLSIexOsnlc0kfWuLis7Tm5WZEdfp1s6PbZ+AAAAAFiZWVyAAAAAE2ps88xwWiGst/YEzhQ+f8IH+3WNWrTH0MERPmSL9doAAAAADuaygAABMsvAAGGoAAAAAAAAAABAAAAAAAAAAQAAAABYmVlcgAAAABNqbPPMcFohrLf2BM4UPn/CB/t1jVq0x9DBET5ki/XaAAAAAFiZWVyAAAAAKBAE8oZ3wY7YEhi+Ra+KB5cP1+GyGJx+OMyKaK9jEG1AAAAADuaygAABMsvAAGGoAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAABYmVlcgAAAACUyh6BxJLSIexOsnlc0kfWuLis7Tm5WZEdfp1s6PbZ+H//////////AAAAAAAAAAcAAAAAlMoegcSS0iHsTrJ5XNJH1ri4rO05uVmRHX6dbOj22fgAAAABYmVlcgAAAAEAAAAAAAAACAAAAACUyh6BxJLSIexOsnlc0kfWuLis7Tm5WZEdfp1s6PbZ+AAAAAAAAAABzT4TYwAAAECnD5OPLjCC3vjtrsffS0fekR0rEgJZoDvJrOdp2G4LBKWLPsH4ZKVVGiOxPq2akIowWckiYXwZG45/mSLSbloN'
     assert (result == self.make_envelope(
         CreateAccount({
             'destination': self.accounts[0]['address'],
             'starting_balance': self.amount,
         }),
         Payment({
             'destination': self.accounts[1]['address'],
             'asset': Asset.native(),
             'amount': self.amount,
         }),
         PathPayment({
             'destination': self.accounts[2]['address'],
             'send_asset': Asset.native(),
             'dest_asset': Asset.native(),
             'send_max': self.amount,
             'dest_amount': self.amount,
             'path': [],
         }),
         ManageOffer({
             'selling': Asset('beer', self.accounts[0]['address']),
             'buying': Asset('beer', self.accounts[1]['address']),
             'amount': 100 * 10 ** 7,
             'price': 3.14159,
             'offer_id': 1,
         }),
         CreatePassiveOffer({
             'selling': Asset('beer', self.accounts[1]['address']),
             'buying': Asset('beer', self.accounts[2]['address']),
             'amount': 100 * 10 ** 7,
             'price': 3.14159,
         }),
         SetOptions({
         }),
         ChangeTrust({
             'asset': Asset('beer', self.accounts[0]['address']),
         }),
         AllowTrust({
             'trustor': self.accounts[0]['address'],
             'asset_code': 'beer',
             'authorize': True,
         }),
         AccountMerge({
             'destination': self.accounts[0]['address'],
         })
     ))
Example #5
0
def test_minimal_defaults():
    from stellar_base.asset import Asset

    result = b"AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAAAAAABAAAAAQAAAADTUozdcK3X4scPuMNM5il78cYpIOhCjIvUltQ5zT4TYwAAAAEAAAAAra4WiCvFr/vydTiUbSQF0HwkqErP8wc6BUQav3qSQI4AAAAAAAAAAACYloAAAAAAAAAAAc0+E2MAAABAzEdbP2ISsB9pDqmIRPt6WEK0GkVOgAEljnelNQjNpDig6A60+jMtveQjdCocL13GwVbO1B8VBXgQdlAobs0fDg=="
    assert result == do_single_signer(
        operation_opts={"source": SOURCE, "destination": DESTINATION, "asset": Asset.native(), "amount": AMOUNT},
        tx_opts={"seqNum": SEQ_NUM},
    )
Example #6
0
def test_textMemo_ascii():
    from stellar_base.asset import Asset
    from stellar_base.memo import TextMemo

    result = b"AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAEAAAAHdGVzdGluZwAAAAABAAAAAQAAAADTUozdcK3X4scPuMNM5il78cYpIOhCjIvUltQ5zT4TYwAAAAEAAAAAra4WiCvFr/vydTiUbSQF0HwkqErP8wc6BUQav3qSQI4AAAAAAAAAAACYloAAAAAAAAAAAc0+E2MAAABApJRB7KqhymuVzBcsit9QUZsFfk2DwSwwp1CSI6qI1scogBoNchw32lJzJqDDXXUmoi3blG8XxNGkzdFk0BDDAA=="
    assert result == do_single_signer(
        operation_opts={"source": SOURCE, "destination": DESTINATION, "asset": Asset.native(), "amount": AMOUNT},
        tx_opts={"seqNum": SEQ_NUM, "timeBounds": [], "memo": TextMemo("testing"), "fee": FEE},
    )
Example #7
0
def test_textMemo_unicode():
    from stellar_base.asset import Asset
    from stellar_base.memo import TextMemo

    result = b"AAAAANNSjN1wrdfixw+4w0zmKXvxxikg6EKMi9SW1DnNPhNjAAAAZAAAAAAAAAACAAAAAAAAAAEAAAAMdMSTxaF0xKvFhsSjAAAAAQAAAAEAAAAA01KM3XCt1+LHD7jDTOYpe/HGKSDoQoyL1JbUOc0+E2MAAAABAAAAAK2uFogrxa/78nU4lG0kBdB8JKhKz/MHOgVEGr96kkCOAAAAAAAAAAAAmJaAAAAAAAAAAAHNPhNjAAAAQJkdyCjp7w6UzRxaaHqg9lrIfWJlEyvEga2ZNhbJ7w1NZxwkqiI7AG2oJg0dg91m83W1ZP85VPOf4iDkIAI2YAs="
    assert result == do_single_signer(
        operation_opts={"source": SOURCE, "destination": DESTINATION, "asset": Asset.native(), "amount": AMOUNT},
        tx_opts={"seqNum": SEQ_NUM, "timeBounds": [], "memo": TextMemo("tēštīņģ"), "fee": FEE},
    )
Example #8
0
 def test_native(self):
     assert 'XLM' == Asset.native().code
     assert None == Asset.native().issuer
Example #9
0
 def test_to_xdr_object(self):
     cny = Asset('CNY', self.source)
     assert isinstance(cny.to_xdr_object(), Xdr.types.Asset)
Example #10
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
from stellar_base.keypair import Keypair
from stellar_base.asset import Asset
from stellar_base.builder import Builder

issuing_secret = 'Put-Your-Secret-Key-Here'
issuing_public = Keypair.from_seed(issuing_secret).address().decode()

receiving_secret = 'Put-Your-Secret-Key-Here'
receiving_public = Keypair.from_seed(receiving_secret).address().decode()

my_asset = Asset('YourAssetCode', issuing_public)
builder = Builder(
    receiving_secret, network='TESTNET').append_trust_op(
        destination=my_asset.issuer,
        code=my_asset.code,
        limit="7000")
builder.sign()
resp = builder.submit()
print(resp)

#for trasfering the coin
builder = Builder(
    issuing_secret, network='TESTNET').append_payment_op(
        destination=receiving_public,
        amount='1000',
        asset_code="YourAssetCode",  #asset_code="ICO"
        asset_issuer=issuing_public)
builder.sign()
resp = builder.submit()
print(resp)
Example #12
0
 def test_unxdr(self):
     xdr = self.cny.xdr()
     cny_x = Asset.from_xdr(xdr)
     assert self.cny == cny_x
Example #13
0
 def test_too_long(self):
     with pytest.raises(Exception, match='Asset code is invalid'):
         Asset('123456789012TooLong', self.source)
Example #14
0
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 = 'SAZJ3EDATROKTNNN4WZBZPRC34AN5WR43VEHAFKT5D66UEZTKDNKUHOK'
bob_address = 'GDLP3SP4WP72L4BAJWZUDZ6SAYE4NAWILT5WQDS7RWC4XCUNUQDRB2A4'
CNY_ISSUER = 'GDVDKQFP665JAO7A2LSHNLQIUNYNAAIGJ6FYJVMG4DT3YJQQJSRBLQDG'
amount = '100'
# This is the new account ID (the StrKey representation of your newly
# created public key). This is the destination account.
new_account_addr = "GXXX"
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
})
'''
op = CreateAccount({
    'destination': new_account_addr,
    'starting_balance': amount
})
# create a memo
msg = TextMemo('Buy yourself a beer !')
Example #15
0
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]
# construct Tx
Example #16
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)
Example #17
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)
                 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')


if __name__ == '__main__':
    at = Asset(code='YourAssetCode', issuer='Put-Your-Issuer-Public-Key-Here')
    transfer_fund(10, at, 'Put-Your-Reciver-Public-Key-Here',
                  'Put-Your-Issuer-Public-Key-Here',
                  'Put-Your-Issuer-Secret-Key-Here')
Example #19
0
# get seeds, channels from aws ssm:
base_seed, channel_seeds = ssm.get_stellar_credentials()
if not base_seed:
    log.error('could not get base seed - aborting')
    sys.exit(-1)

if channel_seeds is None:
    log.error('could not get channels seeds - aborting')
    sys.exit(-1)

# init sdk:
print('using kin-stellar sdk version: %s' % kin.version.__version__)
print("stellar horizon: %s" % config.STELLAR_HORIZON_URL)
# define an asset to forward to the SDK because sometimes we're using a custom issuer
from stellar_base.asset import Asset
kin_asset = Asset('KIN', config.STELLAR_KIN_ISSUER_ADDRESS)

if config.STELLAR_NETWORK != 'TESTNET':
    log.info('starting the sdk in a private network')
    network = 'CUSTOM'
    NETWORKS[network] = config.STELLAR_NETWORK
else:
    print('starting the sdk on the public testnet')
    network = config.STELLAR_NETWORK

app.kin_sdk = kin.SDK(secret_key=base_seed,
                      horizon_endpoint_uri=config.STELLAR_HORIZON_URL,
                      network=network,
                      channel_secret_keys=channel_seeds,
                      kin_asset=kin_asset)
Example #20
0
 def test_unxdr(self):
     cny = Asset('CNY', self.source)
     xdr = cny.xdr()
     cny_x = Asset.from_xdr(xdr)
     assert cny == cny_x
Example #21
0
from stellar_base.asset import Asset
from stellar_base.builder import Builder
from stellar_base.keypair import Keypair

# 发行(issue)账号
issue_secret = ''
issue_public = 'GC55P5MTVPOPPY7NBBS5RPRUF5K3667ZQ2GN4J5GGE6AZVLPC72S5K46'
# 分配(distribute)账号
distribute_secret = ''
distribute_public = 'GD7C4MQJDM3AHXKO2Z2OF7BK3FYL6QMNBGVEO4H2DHM65B7JMHD2IU2E'

# print 'issue_public     : %s' % issue_public
# print 'distribute_public: %s' % distribute_public

# 资产的表示
my_asset = Asset('MFN', issue_public)

# 创建一个从分配账号到发行账号的trustline.
builder = Builder(distribute_secret, network='PUBLIC').append_trust_op(
    destination=my_asset.issuer, code=my_asset.code, limit=10000000000)
builder.sign()
# 向Horizon发送交易, 返回一个dict表示JSON格式的回复.
resp = builder.submit()
print(resp)
print '-----------------------------------------------------------------'

# 发行账号用新建的资产向分配账号支付(即转账).
builder = Builder(issue_secret, network='PUBLIC').append_payment_op(
    destination=distribute_public,
    amount=10000000000,  # 可以是字符串, 也可以是整数或者浮点类型.
    asset_type=my_asset.code,  # 新版API的参数不是'asset_code'
Example #22
0
 def test_native(self):
     assert 'XLM' == Asset.native().code
     assert None == Asset.native().issuer
Example #23
0
def make_payment_op(account_id, amount):
    return Payment({
        'destination': account_id,
        'amount': str(amount),
        'asset': Asset('XLM')
    })
Example #24
0
def _load_operations():
    amount = "1"
    return [("create_account_min",
             CreateAccount(source=SOURCE,
                           destination=DEST,
                           starting_balance=amount)),
            ("payment_min",
             Payment(
                 source=SOURCE,
                 destination=DEST,
                 asset=Asset.native(),
                 amount=amount,
             )),
            ("payment_short_asset",
             Payment(
                 source=SOURCE,
                 destination=DEST,
                 asset=Asset('USD4', SOURCE),
                 amount=amount,
             )),
            ("payment_long_asset",
             Payment(
                 source=SOURCE,
                 destination=DEST,
                 asset=Asset('SNACKS789ABC', SOURCE),
                 amount=amount,
             )),
            ("path_payment_min",
             PathPayment(
                 source=SOURCE,
                 destination=DEST,
                 send_asset=Asset.native(),
                 dest_asset=Asset.native(),
                 send_max=amount,
                 dest_amount=amount,
                 path=[],
             )),
            ("allow_trust_short_asset",
             AllowTrust(
                 source=SOURCE,
                 trustor=DEST,
                 asset_code='beer',
                 authorize=True,
             )),
            ("allow_trust_long_asset",
             AllowTrust(
                 source=SOURCE,
                 trustor=DEST,
                 asset_code='pocketknives',
                 authorize=True,
             )),
            ("manage_offer_min",
             ManageOffer(
                 selling=Asset('beer', SOURCE),
                 buying=Asset('beer', DEST),
                 amount="100",
                 price=3.14159,
                 offer_id=1,
             )),
            ("manage_offer_dict_price",
             ManageOffer(
                 selling=Asset('beer', SOURCE),
                 buying=Asset('beer', DEST),
                 amount="100",
                 price={
                     'n': 314159,
                     'd': 100000
                 },
                 offer_id=1,
             )),
            ("create_passive_offer_min",
             CreatePassiveOffer(
                 selling=Asset('beer', SOURCE),
                 buying=Asset('beer', DEST),
                 amount="100",
                 price=3.14159,
             )), ("set_options_empty", SetOptions()),
            ("change_trust_min",
             ChangeTrust(source=SOURCE, asset=Asset('beer', DEST),
                         limit='100')),
            ("change_trust_default_limit",
             ChangeTrust(source=SOURCE, asset=Asset('beer', DEST))),
            ("account_merge_min",
             AccountMerge(
                 source=SOURCE,
                 destination=DEST,
             )), ("inflation", Inflation(source=SOURCE)),
            ("manage_data",
             ManageData(
                 source=SOURCE,
                 data_name='1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY',
                 data_value=SOURCE,
             )), ("bump_sequence", BumpSequence(bump_to=23333114514))]
Example #25
0
 def test_native(self):
     assert 'XLM' == Asset.native().code
     assert Asset.native().issuer is None
     assert 'native' == Asset.native().type
Example #26
0
 def test_no_issuer(self):
     with pytest.raises(
             Exception,
             match='Issuer cannot be `None` except native asset.'):
         Asset('beer', None)
Example #27
0
 def test_too_long(self):
     with pytest.raises(AssetCodeInvalidError, match='Asset code is invalid'):
         Asset('123456789012TooLong', self.source)
Example #28
0
from stellar_base.keypair import Keypair
from stellar_base.horizon import horizon_testnet
from stellar_base.transaction import Transaction
from stellar_base.asset import Asset
from stellar_base.memo import TextMemo
from stellar_base.transaction_envelope import TransactionEnvelope as Te

# KLV
ISSUER = 'GDHR6UNRMLFSOFTIA5EKLIC32BLYSPFLMXJ4G43DYJZOZROR2B65OAPH'
KLTV = Asset('KLTV', ISSUER)

# Distributor -> MAIN ACC
DIST_PUB = 'GAN7PYN7D5V76PQNOIDWPRN7TV7TWM24EY7434LI7O35PUPJC5PQOKKT'
DIST_SEED = 'SDNHI43C4NUEZZFKIFTSXD6JEPTMZLMNRL5X3NMWQOQ43A2HEIM2D274'
kp_dist = Keypair.from_seed(DIST_SEED)

# URL Testnet
URL = 'https://horizon-testnet.stellar.org/'

# Distributor Address
seckey_dist = 'SCXGWORDHZA42NBPL7RQBWDYHV7JR672QRBGB3MX2WINJF2YJROTUNYK'

# Testing seed
seed = 'SBTYKU5OOZE46X63NBGXJ5XW32Q244DFMLCSZQP263GJF2GJSV5O53RO'

# Horizon Testnet
horizon = horizon_testnet()
Example #29
0
 def test_bad_issuer(self):
     with pytest.raises(StellarAddressInvalidError, match='Invalid issuer account: BADADDRESS'):
         Asset('beer', 'BADADDRESS')
Example #30
0
def test_send_asset(setup, test_sdk):
    with pytest.raises(ValueError, match='invalid address'):
        test_sdk.send_asset('bad', setup.test_asset, 10)

    keypair = Keypair.random()
    address = keypair.address().decode()

    with pytest.raises(ValueError, match='amount must be positive'):
        test_sdk.send_asset(address, setup.test_asset, 0)

    with pytest.raises(ValueError, match='asset issuer invalid'):
        test_sdk.send_asset(address, Asset('TMP', 'bad'), 10)

    # account does not exist yet
    with pytest.raises(kin.SdkHorizonError,
                       match=kin.PaymentResultCode.NO_DESTINATION):
        test_sdk.send_asset(address, setup.test_asset, 10)

    tx_hash = test_sdk.create_account(address, starting_balance=100)
    assert tx_hash

    # no trustline yet
    with pytest.raises(kin.SdkHorizonError,
                       match=kin.PaymentResultCode.NO_TRUST):
        test_sdk.send_asset(address, setup.test_asset, 10)

    # add trustline from the newly created account to the kin issuer
    assert trust_asset(setup, test_sdk, keypair.seed())

    # send asset
    tx_hash = test_sdk.send_asset(address,
                                  setup.test_asset,
                                  10.123,
                                  memo_text='foobar')
    assert tx_hash
    assert test_sdk.get_address_asset_balance(
        address, setup.test_asset) == Decimal('10.123')

    # test get_transaction_data for this transaction
    sleep(1)
    tx_data = test_sdk.get_transaction_data(tx_hash)
    assert tx_data
    assert tx_data.hash == tx_hash
    assert tx_data.source_account == test_sdk.get_address()
    assert tx_data.created_at
    assert tx_data.source_account_sequence
    assert tx_data.fee_paid == 100
    assert tx_data.memo_type == 'text'
    assert tx_data.memo == 'foobar'
    assert len(tx_data.signatures) == 1
    assert len(tx_data.operations) == 1

    op = tx_data.operations[0]
    assert op.id
    assert op.type == 'payment'
    assert op.asset_code == setup.test_asset.code
    assert op.asset_type == 'credit_alphanum4'
    assert op.asset_issuer == setup.test_asset.issuer
    assert op.trustor is None
    assert op.trustee is None
    assert op.limit is None
    assert op.from_address is None
    assert op.to_address is None
    assert op.amount == Decimal('10.123')
def _load_operations():
    amount = "1"
    return [
        ("create_account_min",
         CreateAccount(
             source=SOURCE, destination=DEST, starting_balance=amount)),
        ("payment_min",
         Payment(
             source=SOURCE,
             destination=DEST,
             asset=Asset.native(),
             amount=amount,
         )),
        ("payment_short_asset",
         Payment(
             source=SOURCE,
             destination=DEST,
             asset=Asset('USD4', SOURCE),
             amount=amount,
         )),
        ("payment_long_asset",
         Payment(
             source=SOURCE,
             destination=DEST,
             asset=Asset('SNACKS789ABC', SOURCE),
             amount=amount,
         )),
        ("path_payment_min",
         PathPayment(
             source=SOURCE,
             destination=DEST,
             send_asset=Asset.native(),
             dest_asset=Asset.native(),
             send_max=amount,
             dest_amount=amount,
             path=[],
         )),
        ("path_payment",
         PathPayment(
             destination=DEST,
             send_asset=Asset.native(),
             dest_asset=Asset.native(),
             send_max=amount,
             dest_amount=amount,
             path=[Asset('MOE', DEST)],
         )),
        ("allow_trust_short_asset",
         AllowTrust(
             source=SOURCE,
             trustor=DEST,
             asset_code='beer',
             authorize=True,
         )),
        ("allow_trust_long_asset",
         AllowTrust(
             source=SOURCE,
             trustor=DEST,
             asset_code='pocketknives',
             authorize=True,
         )),
        ("manage_offer_min",
         ManageOffer(
             selling=Asset('beer', SOURCE),
             buying=Asset('beer', DEST),
             amount="100",
             price=3.14159,
             offer_id=1,
             source=SOURCE
         )),
        ("manage_offer_dict_price",
         ManageOffer(
             selling=Asset('beer', SOURCE),
             buying=Asset('beer', DEST),
             amount="100",
             price={
                 'n': 314159,
                 'd': 100000
             },
             offer_id=1,
         )),
        ("create_passive_offer_min",
         CreatePassiveOffer(
             selling=Asset('beer', SOURCE),
             buying=Asset('beer', DEST),
             amount="100",
             price=3.14159,
             source=SOURCE
         )),
        ("create_passive_dict_offer",
         CreatePassiveOffer(
             selling=Asset('beer', SOURCE),
             buying=Asset('beer', DEST),
             amount="100",
             price={
                 'n': 314159,
                 'd': 100000
             }
         )),
        ("set_options_empty", SetOptions()),
        ("set_options_ed25519PublicKey", SetOptions(signer_type='ed25519PublicKey', signer_address=DEST, signer_weight=1)),
        ("set_options_hashX", SetOptions(signer_type='hashX', signer_address=os.urandom(32), signer_weight=2)),
        ("set_options_preAuthTx", SetOptions(signer_type='preAuthTx', signer_address=os.urandom(32), signer_weight=3)),
        ("set_options_inflation_dest",
         SetOptions(inflation_dest=DEST, source=SOURCE)),
        ("change_trust_min",
         ChangeTrust(source=SOURCE, asset=Asset('beer', DEST), limit='100')),
        ("change_trust_default_limit",
         ChangeTrust(source=SOURCE, asset=Asset('beer', DEST))),
        ("account_merge_min", AccountMerge(
            source=SOURCE,
            destination=DEST,
        )),
        ("inflation", Inflation(source=SOURCE)),
        ("manage_data",
         ManageData(
             source=SOURCE,
             data_name='1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY',
             data_value=SOURCE,
         )),
        ("manage_data_none",
         ManageData(
             data_name='1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY',
             data_value=None,
         )),
        ("bump_sequence", BumpSequence(
            source=SOURCE,
            bump_to=23333114514
        )),
        ("bump_sequence_no_source", BumpSequence(
            bump_to=23333114514
        ))
    ]
Example #32
0
 def setUpClass(cls):
     cls.source = (
         'GDJVFDG5OCW5PYWHB64MGTHGFF57DRRJEDUEFDEL2SLNIOONHYJWHA3Z')
     cls.cny = Asset('CNY', cls.source)
Example #33
0
 def test_is_native(self):
     native = Asset('XLM')
     cny = Asset('CNY', self.source)
     assert native.is_native()
     assert not cny.is_native()
Example #34
0
 def test_is_native(self):
     native = Asset('XLM')
     assert native.is_native()
     assert not self.cny.is_native()
Example #35
0
 def test_to_xdr_object(self):
     cny = Asset('CNY', self.source)
     assert isinstance(cny.to_xdr_object(), Xdr.types.Asset)
Example #36
0
 def test_no_issuer(self):
     with pytest.raises(StellarAddressInvalidError, match='Issuer cannot be `None` except native asset.'):
         Asset('beer', None)
Example #37
0
 def test_too_long(self):
     Asset('123456789012TooLong', self.source)
Example #38
0
 def test_is_native(self):
     native = Asset('XLM')
     cny = Asset('CNY', self.source)
     assert native.is_native()
     assert not cny.is_native()
Example #39
0
 def test_no_issuer(self):
     Asset('beer', None)
Example #40
0
 def test_xdr(self):
     xdr = b'AAAAAUNOWQAAAAAA01KM3XCt1+LHD7jDTOYpe/HGKSDoQoyL1JbUOc0+E2M='
     cny = Asset('CNY',self.source)
     assert xdr == cny.xdr()
Example #41
0
 def test_xdr(self):
     xdr = b'AAAAAUNOWQAAAAAA01KM3XCt1+LHD7jDTOYpe/HGKSDoQoyL1JbUOc0+E2M='
     cny = Asset('CNY', self.source)
     assert xdr == cny.xdr()
Example #42
0
def packer(envelope=False):
	import base64
	from stellar_base.stellarxdr import StellarXDR_pack as Xdr
	x = Xdr.STELLARXDRPacker()
	x.pack_TransactionEnvelope(envelope.to_xdr_object())
	return base64.b64encode(x.get_buffer())

anna = newAccount()
bob = newAccount()
print('Anna: ', json.dumps(anna, sort_keys=True, indent=4 * ' '))
print('Bob: ', json.dumps(bob, sort_keys=True, indent=4 * ' '))

operation = Payment({
	'source': anna['address'],
	'destination': bob['address'],
	'asset': Asset.native(),
	'amount': '1000', # needs to be a string?
})
tx = Transaction(
	source=anna['address'],
	opts={
		'sequence': json.loads(requests.get(url+'/accounts/'+anna['address']).text)['sequence'],
		'timeBounds': [],
		'memo': NoneMemo(),
		'fee': 100,
		'operations': [
			operation,
		],
	},
)
envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
Example #43
0
 def test_unxdr(self):
     cny = Asset('CNY', self.source)
     xdr = cny.xdr()
     cny_x = Asset.from_xdr(xdr)
     assert cny == cny_x