Example #1
0
def release_order(order):
    from core.models import Transaction
    from nexchange.api_clients.factory import ApiClientFactory

    order.refresh_from_db()
    if order.status >= order.RELEASED:
        return

    currency = order.withdraw_currency
    amount = order.withdraw_amount
    address = order.withdraw_address

    factory = ApiClientFactory()
    api = factory.get_api_client(currency.wallet)

    txid, b = api.release_coins(currency, address, amount)
    order.status = order.RELEASED
    order.save()
    tx, created = Transaction.objects.get_or_create(**{
        convert_camel_to_snake_case(order.__class__.__name__): order,
        'type': 'W',
        'address_to': address,
        'amount': amount
    })

    tx.tx_id = txid
    tx.save()
    order.refresh_from_db()
    tx.refresh_from_db()
    print(order)
    print(tx)
    print(tx.tx_id)
    return order, tx
def _update_pending_transaction(tx, logger, next_tasks=None):
    currency_to = tx.currency
    api = ApiClientFactory.get_api_client(currency_to.wallet)
    order = tx.order if tx.order else tx.limit_order

    logger.info('Look-up transaction with txid api {} '.format(tx.tx_id_api))
    tx_completed, num_confirmations = api.check_tx(tx, currency_to)

    # Uphold is shit, fall back to external source to confirm tx
    # num_confirmations < 2 is to fix the uphold bug that returns
    # 1 for any amount of confirmations
    # TODO: remove, if and when Uphold API gets better
    tx_completed, num_confirmations = check_uphold_txn_status_with_blockchain(
        tx, tx_completed, num_confirmations, logger)

    tx.confirmations = num_confirmations
    with transaction.atomic():
        tx.save()

        order_closed = True
        if isinstance(order, LimitOrder) \
                and tx.address_to.type == Address.DEPOSIT:
            tx_order_book_completed = \
                tx.confirmations >= currency_to.min_order_book_confirmations
            order_is_fresh = \
                order.status == order.PAID_UNCONFIRMED \
                and order.book_status == order.NEW
            to_order_book = tx_order_book_completed and order_is_fresh
            if to_order_book:
                order.open(tx)
            order.refresh_from_db()
            order_closed = order.book_status == order.CLOSED

        withdrawal_completed = tx.type == Address.WITHDRAW and \
            tx_completed and order.status != order.COMPLETED
        deposit_completed = \
            tx.type == Address.DEPOSIT and tx_completed and \
            order.status not in order.IN_PAID and order_closed

        if withdrawal_completed:
            order.complete(tx)

        if deposit_completed:
            confirm_res = order.confirm_deposit(tx)
            order.refresh_from_db()
            confirm_status_ok = confirm_res.get('status') == 'OK'

            if confirm_status_ok and order.status == order.PAID:
                card_check_time = settings.CARD_CHECK_TIME_BTC \
                    if tx.currency.code == 'USDT' \
                    else settings.CARD_CHECK_TIME
                app.send_task(CHECK_CARD_BALANCE_TASK, [tx.pk],
                              countdown=card_check_time)
                if tx.currency.is_token:
                    app.send_task(SEND_GAS_TASK, [tx.pk])
                if tx.currency.code == "USDT":
                    app.send_task(SEND_BTC_TASK, [tx.pk])
Example #3
0
 def get_wallet_transactions(
         self,
         currency=None,
         tx_count=settings.RPC_IMPORT_TRANSACTIONS_VALIDATION_COUNT):
     factory = ApiClientFactory()
     client = factory.get_api_client(currency.wallet)
     accounts, name = self.set_client_accounts_name(currency, client)
     if all([client, accounts, name]):
         action = 'txlist' if not currency.is_token else 'tokentx'
         txs = client._list_txs(currency.wallet,
                                tx_count=tx_count,
                                action=action)
         process_txs_func = getattr(self, 'process_{}_txs'.format(name))
         out_txs, in_txs, other_txs = process_txs_func(txs,
                                                       accounts,
                                                       client=client,
                                                       currency=currency)
     else:
         return None
     return {'out_txs': out_txs, 'in_txs': in_txs, 'other_txs': other_txs}
Example #4
0
    def setUpClass(cls):
        cls.ENABLED_TICKER_PAIRS = ['USDTBTC', 'BTCUSDT']
        super(OmniRawE2ETestCase, cls).setUpClass()
        cls.import_txs_task = import_transaction_deposit_crypto_invoke
        cls.update_confirmation_task = update_pending_transactions_invoke
        cls.factory = ApiClientFactory()
        cls.api_client = APIClient()
        cls.USDT = Currency.objects.get(code='USDT')

        cls.reserves = Reserve.objects.all()
        for r in cls.reserves:
            for account in r.account_set.filter(disabled=False):
                if account.wallet != 'rpc10':
                    account.disabled = True
                    account.save()
Example #5
0
class ApiClientsTestCase(TestCase):

    fixtures = [
        'currency_algorithm.json', 'transaction_price.json',
        'currency_crypto.json'
    ]

    def __init__(self, *args, **kwargs):
        super(ApiClientsTestCase, self).__init__(*args, **kwargs)
        self.factory = ApiClientFactory()

    def setUp(self):
        self.BTC = Currency.objects.get(code='BTC')

    @data_provider(lambda: (
        scrypt_check_tx_params(case_name='1 Confirmation, not confirmed',
                               tx_count=1,
                               min_confs=12,
                               expected_return=(False, 1)),
        scrypt_check_tx_params(case_name='Min Confirmations, confirmed',
                               tx_count=12,
                               min_confs=12,
                               expected_return=(True, 12)),
        scrypt_check_tx_params(case_name='Min Confirmations 0, not confirmed',
                               tx_count=0,
                               min_confs=0,
                               expected_return=(False, 0)),
    ))
    @patch(SCRYPT_ROOT + '_get_tx')
    def test_check_tx_scrypt(self, get_tx, **kwargs):
        tx = Transaction(tx_id='123')
        self.BTC.min_confirmations = kwargs['min_confs']
        self.BTC.save()
        api = self.factory.get_api_client(self.BTC.wallet)
        get_tx.return_value = {'confirmations': kwargs['tx_count']}
        res = api.check_tx(tx, self.BTC)
        self.assertEqual(res, kwargs['expected_return'], kwargs['case_name'])
Example #6
0
from functools import wraps
from nexchange.api_clients.factory import ApiClientFactory
from .models import Order, LimitOrder
from nexchange.utils import get_nexchange_logger

factory = ApiClientFactory()
logger = get_nexchange_logger('Orders Decorator logger')


def get_task(**kwargs):
    def _get_task(task_fn):
        @wraps(task_fn)
        def _wrapped_fn(search_val):
            Task = kwargs.get('task_cls')
            key = kwargs.get('key')
            lookup = {key: [search_val]}
            try:
                order = Order.objects.get(**lookup)
            except Order.DoesNotExist:
                order = None
            try:
                limit_order = LimitOrder.objects.get(**lookup)
            except LimitOrder.DoesNotExist:
                limit_order = None
            if bool(limit_order) == bool(order):
                logger.error(
                    '{} lookup for order found both Order and '
                    'LimitOrder'.format(lookup)
                )
                return
            _order = order if order else limit_order
Example #7
0
 def __init__(self, *args, **kwargs):
     super(ApiClientsTestCase, self).__init__(*args, **kwargs)
     self.factory = ApiClientFactory()
Example #8
0
from decimal import Decimal
from django.utils.translation import ugettext as _
from django_fsm import FSMIntegerField, transition
from django.core.exceptions import ValidationError
from django.db.models import Sum
from django.utils.timezone import now, timedelta
from copy import deepcopy
from nexchange.api_clients.bittrex import BittrexApiClient
from payments.utils import money_format
from audit_log.models import AuthStampedModel
from nexchange.api_clients.factory import ApiClientFactory
from .utils import get_native_pairs
from django.core.exceptions import ObjectDoesNotExist

BITTREX_API = BittrexApiClient()
API_FACTORY = ApiClientFactory()


class Reserve(TimeStampedModel):
    currency = models.OneToOneField(Currency, on_delete=models.DO_NOTHING)
    is_limit_reserve = models.BooleanField(default=False)
    target_level = models.DecimalField(max_digits=18,
                                       decimal_places=8,
                                       default=Decimal('0'))
    allowed_diff = models.DecimalField(max_digits=18,
                                       decimal_places=8,
                                       default=Decimal('0'))
    maximum_level = models.DecimalField(max_digits=18,
                                        decimal_places=8,
                                        default=Decimal('0'))
    minimum_level = models.DecimalField(max_digits=18,