예제 #1
0
        private async Task SyncBlockAsync(BlockSyncRequest blockSyncRequest)
        {
            var blockBuilder    = Builders <Block> .Filter;
            var blockFilter     = blockBuilder.Where(x => x.BlockNumber == blockSyncRequest.BlockNumber);
            var excistingBlocks = await _blockRepository.FindAsync(blockFilter, null);

            var blockExists = excistingBlocks.Count() > 0;

            Web3.Models.DTOs.Block block;
            try
            {
                block = await _blockService.GetBlockFromNodeAsync(blockSyncRequest.BlockNumber);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error getting block {blockSyncRequest.BlockNumber} from the node.");
                return;
            }

            if (block == null)
            {
                Console.WriteLine($"Block {blockSyncRequest.BlockNumber} could not be find in the node.");
                return;
            }

            var dbBlock = await _blockService.ConvertToDbBlockAsync(block, _tokenRepository, _priceRepository, _currentPrice);

            if (!blockExists)
            {
                await SaveBlock(dbBlock);
            }

            var transactions = new List <Transaction>();

            foreach (var transaction in dbBlock.Transactions)
            {
                var builder        = Builders <Transaction> .Filter;
                var filter         = builder.Where(x => x.TransactionHash == transaction.TransactionHash);
                var dbTransactions = await _transactionRepository.FindAsync(filter, null);

                var dbTransaction = dbTransactions.FirstOrDefault();
                if (dbTransaction == null)
                {
                    transactions.Add(transaction);
                }
                else
                {
                    dbTransaction.BlockHash   = dbBlock.Hash;
                    dbTransaction.BlockNumber = dbBlock.BlockNumber;
                    dbTransaction.Timestamp   = dbBlock.Timestamp;
                    transactions.Add(dbTransaction);
                }
            }

            await SaveTransactions(transactions);

            blockSyncRequest.Processed = true;
            await _blockSyncRequestRepository.SaveAsync(blockSyncRequest);
        }