Ejemplo n.º 1
0
        public async Task UpdateAsync(BalanceOperationType balanceOperationType, decimal amount, string comment,
                                      string userId)
        {
            await _semaphore.WaitAsync();

            try
            {
                Funding funding = (await GetAsync()).Copy();

                string walletId = _settingsService.GetWalletId();

                string transactionId;

                switch (balanceOperationType)
                {
                case BalanceOperationType.CashIn:
                    funding.Add(amount);
                    transactionId =
                        await _lykkeExchangeService.CashInAsync(walletId, AssetId, amount, userId, comment);

                    break;

                case BalanceOperationType.CashOut:
                    funding.Subtract(amount);
                    try
                    {
                        transactionId =
                            await _lykkeExchangeService.CashOutAsync(walletId, AssetId, amount, userId, comment);
                    }
                    catch (NotEnoughFundsException)
                    {
                        throw new InvalidOperationException("No enough funds");
                    }

                    break;

                default:
                    throw new InvalidEnumArgumentException(nameof(balanceOperationType), (int)balanceOperationType,
                                                           typeof(BalanceOperationType));
                }

                await _fundingRepository.InsertOrReplaceAsync(funding);

                _cache.Set(funding);

                var balanceOperation = new BalanceOperation
                {
                    Timestamp     = DateTime.UtcNow,
                    AssetId       = AssetId,
                    Type          = balanceOperationType,
                    IsCredit      = true,
                    Amount        = amount,
                    Comment       = comment,
                    UserId        = userId,
                    TransactionId = transactionId
                };

                await _balanceOperationService.AddAsync(balanceOperation);

                _log.InfoWithDetails("Funding amount updated", balanceOperation);
            }
            catch (Exception exception)
            {
                _log.WarningWithDetails("An error occurred while updating funding", exception, new
                {
                    AssetId,
                    Type    = balanceOperationType,
                    Amount  = amount,
                    Comment = comment,
                    UserId  = userId
                });

                throw;
            }
            finally
            {
                _semaphore.Release();
            }
        }