public async Task <Unit> Handle(DepositCommand request, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); var userId = request.UserId; var balance = request.Balance; var currency = request.Currency; var user = await GetUserAsync(userId, cancellationToken); if (user == null) { throw new UserNotFoundException(nameof(UserEntity), userId); } var wallet = await GetWalletAsync(userId, currency, cancellationToken); if (wallet == null) { var entity = new WalletEntity(balance, currency, user); await AddWalletAsync(entity, cancellationToken); return(Unit.Value); } wallet.AddBalance(balance); await _dbContext.SaveChangesAsync(cancellationToken); return(Unit.Value); }
public async Task <Unit> Handle(WithdrawCommand request, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); var userId = request.UserId; var withdraw = request.Withdraw; var currency = request.Currency; var userExists = await UserAnyAsync(userId, cancellationToken); if (!userExists) { throw new UserNotFoundException(nameof(UserEntity), userId); } var wallet = await GetWalletAsync(userId, currency, cancellationToken); if (wallet == null) { throw new WalletNotFoundException(nameof(WalletEntity), $"{nameof(currency)}: {currency}"); } if (wallet.Balance < withdraw) { throw new BalanceNotEnoughException(); } wallet.SubtractBalance(withdraw); await _dbContext.SaveChangesAsync(cancellationToken); return(Unit.Value); }
public async Task <BalanceDto> Handle(ConvertCommand request, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); var userId = request.UserId; var fromCurrency = request.FromCurrency; var toCurrency = request.ToCurrency; var userExists = await UserAnyAsync(userId, cancellationToken); if (!userExists) { throw new UserNotFoundException(nameof(UserEntity), userId); } var wallet = await GetWalletAsync(userId, fromCurrency, cancellationToken); if (wallet == null) { throw new WalletNotFoundException(nameof(WalletEntity), $"{nameof(fromCurrency)}: {fromCurrency}"); } var envelope = await _ecuEuropa.GetEnvelope(); var fromRate = envelope.GetRate(x => (int)x.Currency == (int)fromCurrency); var toRate = envelope.GetRate(x => (int)x.Currency == (int)toCurrency); var balance = wallet.Balance; // [converted amount] = [balance] * [rate(1)] / [rate(2)] var amount = balance * toRate / fromRate; wallet.SetBalance(amount); wallet.SetCurrency(toCurrency); await _dbContext.SaveChangesAsync(cancellationToken); return(new BalanceDto { Balance = amount, Currency = toCurrency }); }
public void AddBlock(Block block) { entities.Blocks.Add(block); entities.SaveChangesAsync(); }