public void GetMergedTokenNetworkDeltas_WhenCalled_ReturnsCorrectlyMergedList(
            List <RaidenDelta> delta,
            RaidenSnapshot RaidenSnapshot,
            List <TokenNetworkDelta> expected)
        {
            var result = RaidenHelpers.GetMergedTokenNetworkDeltas(delta, RaidenSnapshot);

            Assert.That(result, Is.EquivalentTo(expected));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "v1/tokenNetwork/{tnAddress}/{timestamp}")] HttpRequest req,
            string tnAddress,
            long timestamp,
            ILogger log
            )
        {
            var client = new MongoClient(MongoDbConnectionString);

            log.LogInformation($"{DateTime.UtcNow} INFO Retrievieng Nearest State.");
            var(nearestTnState, states) = await RetrieveNearestState(timestamp, tnAddress, client);

            if (RaidenHelpers.TimestampsAreClose(nearestTnState.StateTimestamp, timestamp))
            {
                log.LogInformation($"{DateTime.UtcNow} INFO A near enough state was already available.");
                return(new OkObjectResult(nearestTnState));
            }

            log.LogInformation($"{DateTime.UtcNow} INFO Computing Delta.");
            var(delta, aggregates) =
                await RaidenHelpers.RetrieveDelta <TokenNetworkDelta>(
                    nearestTnState.StateTimestamp,
                    timestamp,
                    client,
                    DatabaseName,
                    TokenNetworkAggregateCollection
                    );

            var tnStates =
                nearestTnState
                .TokenNetworkDeltas
                .OrderByDescending(s => s.BlockNumber)
                .ToList();

            var howManyToRemove = delta.Count() - 1;
            var howManyToRetain = nearestTnState.TokenNetworkDeltas.Count() - delta.Count();

            // Remove unneded aggregates
            tnStates.RemoveRange(howManyToRetain, howManyToRemove);
            tnStates.AddRange(delta);

            nearestTnState.TokenNetworkDeltas = tnStates;

            nearestTnState.StateBlockNumber = delta.Max(x => x.BlockNumber);
            nearestTnState.StateTimestamp   = delta.Max(x => x.Timestamp);

            nearestTnState.Channels = RaidenHelpers.GetMergedChannels(delta, nearestTnState);

            nearestTnState.MongoId = new ObjectId();

            log.LogInformation($"{DateTime.UtcNow} INFO Inserting newly computed state in database");
            // Could run in a separate Task
            await states.InsertOneAsync(nearestTnState);

            log.LogInformation($"{DateTime.UtcNow} INFO Returning computed state.");
            return(new OkObjectResult(nearestTnState));
        }