Пример #1
0
        public async Task <ActionResult <string> > Withdraw(BitcoinWithdrawal withdrawal)
        {
            if (MathDecimals.GetDecimals(withdrawal.Amount) > 8)
            {
                return(BadRequest("withdrawal amount cannot have more than 8 decimals"));
            }

            if (MathDecimals.GetDecimals(withdrawal.Fees) > 8)
            {
                return(BadRequest("withdrawal fees cannot have more than 8 decimals"));
            }

            string accountIdString = User.FindFirstValue(ClaimTypes.NameIdentifier);

            if (accountIdString == null)
            {
                return(BadRequest("AccountId missing from request"));
            }

            int accountId = int.Parse(accountIdString);

            var account = await _context.Account
                          .Include(x => x.MarketTransactions)
                          .FirstOrDefaultAsync(x => x.Id == accountId);

            if (account == null)
            {
                return(NotFound("User not found in database"));
            }

            if (account.WithdrawalAddress == null)
            {
                return(NotFound("User has not set a withdrawal address"));
            }

            var   address = BitcoinAddress.Create(account.WithdrawalAddress, Network.Main);
            Money amount  = Money.FromUnit(withdrawal.Amount, MoneyUnit.BTC);
            Money fees    = Money.FromUnit(withdrawal.Fees, MoneyUnit.BTC);

            var result = await _bitcoin.SendBitcoin(accountId, address, amount, fees);

            if (result == null)
            {
                return(Conflict("Failed to create/send transaction"));
            }

            decimal rate = Decimal.Zero;

            if (_ticker.MarketState == MarketState.Open)
            {
                rate = _ticker.Tickers["btcisk"].Ask;
            }

            MarketTransaction mtx = new MarketTransaction
            {
                AccountId = accountId,
                Time      = DateTime.Now,
                Coins     = -(withdrawal.Amount + withdrawal.Fees),
                TxId      = result.ToString(),
                Type      = TransactionType.Withdrawal,
                Rate      = rate,
                Status    = TransactionStatus.Completed
            };

            account.MarketTransactions.Add(mtx);
            await _context.SaveChangesAsync();

            return(result.ToString());
        }