System.DateTimeOffset.ToUnixTimeSeconds()

Here are the examples of the csharp api System.DateTimeOffset.ToUnixTimeSeconds() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

588 Examples 7

19 Source : JsonSender.cs
with GNU Affero General Public License v3.0
from 3CORESec

public override async Task<string> SendAlert((string, Dictionary<string, dynamic>) res, string sourceIp, string path, string guid)
        {
            try
            {
                path = path.Split("/")[1];
                var _path = paths.ContainsKey(path)? paths[path] : path;
                var message = $"Trapdoor triggered in: {_path}";
                var temp = await GenerateAlert(res, sourceIp, message);
                var content = new StringContent(temp, Encoding.UTF8, "application/json");
                await _client.PostAsync(send_link, content);
                return new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }

19 Source : TokenAuthController.cs
with MIT License
from 52ABP

private static List<Claim> CreateJwtClaims(ClaimsIdenreplacedy idenreplacedy)
        {
            var claims = idenreplacedy.Claims.ToList();
            var nameIdClaim = claims.First(c => c.Type == ClaimTypes.NameIdentifier);

            // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims.
            claims.AddRange(new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, nameIdClaim.Value),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
            });

            return claims;
        }

19 Source : DelayedQueue.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task<bool> Publish<T>(int playerId, T t, int delayMin, int delayMax = 0)
        {
            var channel = t.GetType().Name.ToLower();

            Random rnd = new Random();
            var delay = delayMax > delayMin ? rnd.Next(delayMin, delayMax) : delayMin;
            var timestamp = DateTimeOffset.Now.AddSeconds(delay).ToUnixTimeSeconds();

            var hasAdd = await _redisDb.SortedSetAdd($"{queueName}_{channel}", playerId.ToString(), timestamp);
            if (hasAdd)
            {
                return await _redisDb.StringSet($"{queueName}_{channel}_{playerId}", t, DateTime.Now.AddSeconds(delay).AddDays(1));
            }
            return await Task.FromResult(false);
        }

19 Source : DelayedQueue.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task<List<T>> Subscribe<T>()
        {
            var channel = typeof(T).Name.ToLower();
            var list = new List<T>();
            var timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
            var playerIds = await _redisDb.SortedSetRangeByScore($"{queueName}_{channel}", timestamp);
            if (playerIds == null || playerIds.Count == 0)
            {
                return default;
            }
            foreach (var playerId in playerIds)
            {
                var t = await _redisDb.StringGet<T>($"{queueName}_{channel}_{playerId}");
                list.Add(t);

                await _redisDb.SortedSetRemove($"{queueName}_{channel}", playerId);

                await _redisDb.KeyDelete($"{queueName}_{channel}_{playerId}");
            }
            return list;
        }

19 Source : Program.cs
with MIT License
from 8x8

public JaaSJwtBuilder WithExpTime(DateTime expTime)
            {
                payload.Add("exp", new DateTimeOffset(expTime).ToUnixTimeSeconds());
                return this;
            }

19 Source : Program.cs
with MIT License
from 8x8

public JaaSJwtBuilder WithNbfTime(DateTime nbfTime)
            {
                payload.Add("nbf", new DateTimeOffset(nbfTime).ToUnixTimeSeconds());
                return this;
            }

19 Source : DataBaseManager.cs
with MIT License
from Abdesol

public CodeBoxModel AddCode(string replacedle, string desc, string code, string langType)
        {
            var time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();

            var dbCode = new CodeTable
            {
                replacedle = replacedle,
                desc = desc,
                code = code,
                lang = langType,
                isFav = false,
                timestamp = time
            };
            _db.Insert(dbCode);

            int id = (int)SQLite3.LastInsertRowid(_db.Handle);
            var codeModel = new CodeBoxModel(id, replacedle, desc, false, langType, code, time, themeService);
            AllCodes.Add(codeModel);
            PropertyChanged();

            return codeModel;
        }

19 Source : DataBaseManager.cs
with MIT License
from Abdesol

public CodeBoxModel AddCode(string replacedle, string desc, string code, string langType)
        {
            var time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();

            var dbCode = new CodeTable
            {
                replacedle = replacedle,
                desc = desc,
                code = code,
                lang = langType,
                isFav = false,
                timestamp = time
            };
            _db.Insert(dbCode);

            int id = (int)SQLite3.LastInsertRowid(_db.Handle);
            var codeModel = new CodeBoxModel(id, replacedle, desc, langType, false, code, time);
            AllCodes.Add(codeModel);
            PropertyChanged();

            return codeModel;
        }

19 Source : Formatter.cs
with MIT License
from Aiko-IT-Systems

public static string Timestamp(DateTimeOffset time, TimestampFormat format = TimestampFormat.RelativeTime)
            => $"<t:{time.ToUnixTimeSeconds()}:{(char)format}>";

19 Source : DateTimeHelper.cs
with MIT License
from aishang2015

public static string DateTime2TimeStamp(bool milliseconds = false)
        {
            // 废止
            //var ts = DateTime.Now - _startedDate;
            //return Convert.ToInt64(milliseconds ? ts.TotalMilliseconds : ts.TotalSeconds).ToString();

            return milliseconds ? DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString() :
                DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
        }

19 Source : AddServerViewModel.cs
with GNU General Public License v3.0
from ajmcateer

private string GenerateClientName()
        {
            string epoch = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
            return "GotifyDesktop-" + epoch.Substring(epoch.Length - 8);
        }

19 Source : ApnsClient_Tests.cs
with Apache License 2.0
from alexalok

[Fact]
        public void Ensure_Push_Expiration_Setting_Is_Respected()
        {
            var now = DateTimeOffset.UtcNow;
            long unixNow = now.ToUnixTimeSeconds();
            var (apns, httpHandlerMock) = BoostrapApnsClient();
            var push = CreateStubPush();
            push.AddExpiration(now);

            apns.SendAsync(push);

            httpHandlerMock
                .Protected()
                .Verify<Task<HttpResponseMessage>>(
                    "SendAsync",
                    Times.Once(),
                    ItExpr.Is<HttpRequestMessage>(m => m.Headers.Single(h => h.Key == "apns-expiration").Value.Single() == unixNow.ToString()),
                    ItExpr.IsAny<CancellationToken>()
                );
        }

19 Source : ApnsClient.cs
with Apache License 2.0
from alexalok

string GetOrGenerateJwt()
        {
            lock (_jwtRefreshLock)
            {
                return GetOrGenerateJwtInternal();
            }

            string GetOrGenerateJwtInternal()
            {
                if (_lastJwtGenerationTime > DateTime.UtcNow - TimeSpan.FromMinutes(20)) // refresh no more than once every 20 minutes
                    return _jwt;
                var now = DateTimeOffset.UtcNow;

                string header = JsonConvert.SerializeObject((new { alg = "ES256", kid = _keyId }));
                string payload = JsonConvert.SerializeObject(new { iss = _teamId, iat = now.ToUnixTimeSeconds() });

                string headerBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(header));
                string payloadBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(payload));
                string unsignedJwtData = $"{headerBase64}.{payloadBase64}";

                byte[] signature;
#if NET46
                using (var dsa = new ECDsaCng(_key))
                {
                    dsa.HashAlgorithm = CngAlgorithm.Sha256;
                    signature = dsa.SignData(Encoding.UTF8.GetBytes(unsignedJwtData));
                }
#else
                signature = _key.SignData(Encoding.UTF8.GetBytes(unsignedJwtData), HashAlgorithmName.SHA256);
#endif
                _jwt = $"{unsignedJwtData}.{Convert.ToBase64String(signature)}";
                _lastJwtGenerationTime = now.UtcDateTime;
                return _jwt;
            }
        }

19 Source : ImageGalleryWindowViewModel.cs
with GNU General Public License v3.0
from alexdillon

private void UpdateSearchResults()
        {
            if (this.DeferSearchUpdating)
            {
                return;
            }

            foreach (var image in this.Images)
            {
                image.Dispose();
            }

            this.Images.Clear();
            this.LastShownMessageIndex = 0;

            var startDate = this.FilterStartDate;
            var endDate = (this.FilterEndDate == DateTime.MinValue) ? DateTime.Now : this.FilterEndDate.AddDays(1);

            var startDateUnix = ((DateTimeOffset)startDate).ToUnixTimeSeconds();
            var endDateUnix = ((DateTimeOffset)endDate).ToUnixTimeSeconds();

            IQueryable<Message> messagesFromMember;
            if (this.FilterMessagesFrom == null)
            {
                // Show messages from all chat members
                messagesFromMember = this.CacheSession.CacheForGroupOrChat;
            }
            else
            {
                var userId = this.FilterMessagesFrom.UserId;
                if (string.IsNullOrEmpty(userId) && this.GroupChat is Chat chat)
                {
                    // In Chats, the OtherUser field doesn't have the UserId set from GroupMe's API...
                    userId = chat.Id;
                }

                messagesFromMember = this.CacheSession.CacheForGroupOrChat
                    .Where(m => m.UserId == userId);
            }

            this.MessagesWithAttachments = messagesFromMember
                .Where(m => m.CreatedAtUnixTime >= startDateUnix)
                .Where(m => m.CreatedAtUnixTime <= endDateUnix)
                .OrderByDescending(m => m.CreatedAtUnixTime);

            this.FilteredMessagesCount = this.MessagesWithAttachments.Count();

            Task.Run(this.LoadNextPage);
        }

19 Source : SearchViewModel.cs
with GNU General Public License v3.0
from alexdillon

private void UpdateSearchResults()
        {
            if (this.DeferSearchUpdating)
            {
                return;
            }

            this.ResultsView.DisplayMessages(null, null);

            var cacheContext = this.CacheManager.OpenNewContext();
            var messagesForGroupChat = cacheContext.GetMessagesForGroup(this.SelectedGroupChat);

            var startDate = this.FilterStartDate;
            var endDate = (this.FilterEndDate == DateTime.MinValue) ? DateTime.Now : this.FilterEndDate.AddDays(1);

            var startDateUnix = ((DateTimeOffset)startDate).ToUnixTimeSeconds();
            var endDateUnix = ((DateTimeOffset)endDate).ToUnixTimeSeconds();

            IQueryable<Message> messagesFromMemberForGroupChat;
            if (this.FilterMessagesFrom == null)
            {
                // Show messages from all chat members
                messagesFromMemberForGroupChat = messagesForGroupChat;
            }
            else
            {
                var userId = this.FilterMessagesFrom.UserId;
                if (string.IsNullOrEmpty(userId) && this.SelectedGroupChat is Chat chat)
                {
                    // In Chats, the OtherUser field doesn't have the UserId set from GroupMe's API...
                    userId = chat.Id;
                }

                messagesFromMemberForGroupChat = messagesForGroupChat
                    .Where(m => m.UserId == userId);
            }

            var results = messagesFromMemberForGroupChat;

            // Apply query terms
            if (this.FilterIsExact)
            {
                results = results.Where(m => m.Text.ToLower().Contains(this.SearchTerm.ToLower()));
            }
            else if (this.FilterIsANDTerm)
            {
                foreach (var keyword in this.SearchTerm.ToLower().Split(' '))
                {
                    results = results.Where(m => m.Text.ToLower().Contains(keyword));
                }
            }

            // Apply time range filter
            results = results
                .Where(m => m.CreatedAtUnixTime >= startDateUnix)
                .Where(m => m.CreatedAtUnixTime <= endDateUnix);

            var filteredMessages = Enumerable.Empty<Message>().AsQueryable();
            var filtersApplied = false;

            // TODO: Can we disable Client Side evaluation for filters? Breaking change in Enreplacedy Framework Core 3
            // Enabling filters will be a lot faster if we can.
            if (this.FilterHasAttachedImage)
            {
                var messagesWithImages = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<ImageAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithImages);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedLinkedImage)
            {
                var messagesWithLinkedImages = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<LinkedImageAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithLinkedImages);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedVideo)
            {
                var messagesWithVideos = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<VideoAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithVideos);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedDoreplacedent)
            {
                var messagesWithDoreplacedents = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<FileAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithDoreplacedents);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedMentions)
            {
                var messagesWithMentions = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<MentionsAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithMentions);
                filtersApplied = true;
            }

            if (!filtersApplied)
            {
                // No attachment filters were selected, so show all messages
                filteredMessages = results;
            }

            var orderedMessages = filteredMessages
                .OrderByDescending(m => m.Id);

            this.ResultsView.replacedociateWith = this.SelectedGroupChat;
            this.ResultsView.DisplayMessages(orderedMessages, cacheContext);
            _ = this.ResultsView.LoadPage(0);
        }

19 Source : SearchViewModel.cs
with GNU General Public License v3.0
from alexdillon

private void UpdateSearchResults()
        {
            if (this.DeferSearchUpdating)
            {
                return;
            }

            this.ResultsView.Messages = null;

            var messagesForGroupChat = this.GetMessagesForGroup(this.SelectedGroupChat);

            var startDate = this.FilterStartDate;
            var endDate = (this.FilterEndDate == DateTime.MinValue) ? DateTime.Now : this.FilterEndDate.AddDays(1);

            var startDateUnix = ((DateTimeOffset)startDate).ToUnixTimeSeconds();
            var endDateUnix = ((DateTimeOffset)endDate).ToUnixTimeSeconds();

            var results = messagesForGroupChat
                .Where(m => m.Text.ToLower().Contains(this.SearchTerm.ToLower()))
                .Where(m => m.CreatedAtUnixTime >= startDateUnix)
                .Where(m => m.CreatedAtUnixTime <= endDateUnix);

            var filteredMessages = Enumerable.Empty<Message>().AsQueryable();
            var filtersApplied = false;

            if (this.FilterHasAttachedImage)
            {
                var messagesWithImages = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<ImageAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithImages);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedLinkedImage)
            {
                var messagesWithLinkedImages = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<LinkedImageAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithLinkedImages);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedVideo)
            {
                var messagesWithVideos = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<VideoAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithVideos);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedMentions)
            {
                var messagesWithMentions = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<MentionsAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithMentions.AsEnumerable());
                filtersApplied = true;
            }

            if (!filtersApplied)
            {
                // No attachment filters were selected, so show all messages
                filteredMessages = results;
            }

            var orderedMessages = filteredMessages
                .OrderByDescending(m => m.Id);

            this.ResultsView.replacedociateWith = this.SelectedGroupChat;

            // TODO: Can we disable Client Side evaluation? Breaking change in Enreplacedy Framework Core 3
            // Enabling filters will be a lot faster if we can.
            this.ResultsView.Messages = orderedMessages;
            this.ResultsView.ChangePage(0);
        }

19 Source : DialogsApiServiceTests.cs
with MIT License
from alexvolchetsky

[Fact]
        public async Task CallbackDiscovery()
        {
            // arrange
            var request = new DialogsCallbackDiscoveryRequest
            {
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
                Payload = new DialogsCallbackDiscoveryPayload()
                {
                    UserId = SmartHomeDemoConstants.AliceUserId,
                },
            };

            // act
            var response = await _dialogsApiService.CallbackDiscoveryAsync(_smartHomeSkillId, request);

            // replacedert
            response.IsSuccess.Should().BeTrue(response.ErrorMessage ?? response.ErrorCode);
            response.Content.RequestId.Should().NotBeNullOrEmpty();
            response.Content.Status.Should().NotBeNullOrEmpty();
            response.Content.ErrorCode.Should().BeNull();
            response.Content.ErrorMessage.Should().BeNull();
        }

19 Source : DialogsApiServiceTests.cs
with MIT License
from alexvolchetsky

[Fact]
        public async Task CallbackState()
        {
            // arrange
            var request = new DialogsCallbackStateRequest
            {
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
                Payload = new DialogsCallbackStatePayload()
                {
                    UserId = SmartHomeDemoConstants.AliceUserId,
                    Devices = new List<DialogsCallbackStateDevice>()
                    {
                        new DialogsCallbackStateDevice()
                        {
                            Id = SmartHomeDemoConstants.LampDeviceId,
                            Capabilities = new List<SmartHomeDeviceCapabilityState>()
                            {
                                new SmartHomeDeviceOnOffCapabilityState()
                                {
                                    State = new SmartHomeDeviceOnOffCapabilityStateValue()
                                    {
                                        Instance = SmartHomeConstants.OnOffFunction.On,
                                        Value = false,
                                    },
                                },
                            },
                            Properties = new List<SmartHomeDevicePropertyState>()
                            {
                                new SmartHomeDeviceFloatPropertyState()
                                {
                                    State = new SmartHomeDeviceFloatPropertyStateValue()
                                    {
                                        Instance = SmartHomeConstants.FloatFunction.BatteryLevel,
                                        Value = 97,
                                    },
                                },
                            },
                        },
                    },
                },
            };

            // act
            var response = await _dialogsApiService.CallbackStateAsync(_smartHomeSkillId, request);

            // replacedert
            response.IsSuccess.Should().BeTrue(response.ErrorMessage ?? response.ErrorCode);
            response.Content.RequestId.Should().NotBeNullOrEmpty();
            response.Content.Status.Should().NotBeNullOrEmpty();
            response.Content.ErrorCode.Should().BeNull();
            response.Content.ErrorMessage.Should().BeNull();
        }

19 Source : InvokeAsyncExample.cs
with MIT License
from aliyun

public static async Task<GetLogsResult> Invoke(ILogServiceClient client)
        {
            var response = await client.GetLogsAsync
            (
                // 「必填参数」会在 Request 构造器中列出,并且不可set;
                new GetLogsRequest("example-logstore", (Int32) DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds(), (Int32) DateTimeOffset.UtcNow.ToUnixTimeSeconds())
                {
                    // 「可选参数」不会在 Request 构造器中列出,可通过setter设置。
                    Offset = 1,
                    Line = 100,
                }
            );

            var result = response
                // 此方法会确保返回的响应失败时候抛出`LogServiceException`。
                .EnsureSuccess()
                // 此处获取Result是安全的。
                .Result;

            Console.WriteLine($"RequestId:{response.RequestId}");
            Console.WriteLine($"日志总数:{result.Count}");
            Console.WriteLine($"首条日志:{result.Logs.FirstOrDefault()}");

            return result;
        }

19 Source : DefaultLogServiceClientBenchmark.cs
with MIT License
from aliyun

[GlobalSetup]
        public void Prepare()
        {
            this.client = LogServiceClientBuilders.HttpBuilder
                .Endpoint("cn-shenzhen.log.aliyuncs.com", "dotnet-sdk-sz")
                .Credential("<secret>", "<secret>")
                .Build();

            var timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
            this.logstoreName = $"logstore-dotnet-sdk-test-{timestamp}";

            // Create logstore for benchmark
            this.client.CreateLogStoreAsync(this.logstoreName, 1, 1).Result.EnsureSuccess();
            Console.WriteLine($"// LogStore {this.logstoreName} created.");

            // Wait logstore prepared
            this.WaitLogStorePrepared().Wait();

            // Prepare data
            var logLines = this.SizeK * 1024 / (10 * LogContentSize) + 1;
            this.logGroup = new LogGroupInfo
            {
                Topic = "PressureTest",
                Source = "PressureTest",
                LogTags =
                {
                    {"Tag1", "Value1"},
                    {"Tag2", "Value2"}
                },
                Logs = Enumerable.Repeat(new LogInfo
                {
                    Time = DateTimeOffset.Now,
                    Contents = Enumerable.Range(0, LogContentSize)
                        .Select(i => (key: $"key{i}", value: $"value{i}"))
                        .ToDictionary(kv => kv.key, kv => kv.value)
                }, logLines).ToList()
            };
            Console.WriteLine($"// Data ready, replacedume size: {10 * LogContentSize * logLines / 1024}KB per request.");
        }

19 Source : JwtToken.cs
with MIT License
from alonsoalon

public JwtResult GenerateToken(Claim[] claims)
        {
            var authTime = DateTime.UtcNow;
            var expiresAt = authTime.AddMinutes(expiresMinute);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Audience = audience,
                Issuer = issuer,
                Subject = new ClaimsIdenreplacedy(claims),
                Expires = expiresAt,
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(secret), SecurityAlgorithms.HmacSha256Signature)
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);
            return new JwtResult
            {
                access_token = tokenString,
                token_type = "Bearer",
                auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
            };
        }

19 Source : DataTimeExtension.cs
with MIT License
from AlphaYu

public static double GetTotalSeconds(this in DateTime dt) => new DateTimeOffset(dt).ToUnixTimeSeconds();

19 Source : IndexedBkManager.cs
with GNU General Public License v3.0
from Amazing-Favorites

public async Task AppendBookmarksAsync(IEnumerable<BookmarkNode> nodes)
        {
            var updated = false;
            var bkDic = nodes.ToLookup(x => x.Url, x => new Bk
            {
                replacedle = x.replacedle,
                replacedleLastUpdateTime = _clock.UtcNow,
                Url = x.Url,
                UrlHash = _urlHashService.GetHash(x.Url),
                LastCreateTime = x.DateAdded.HasValue
                    ? DateTimeOffset.FromUnixTimeMilliseconds((long)x.DateAdded.Value).ToUnixTimeSeconds()
                    : 0L,
                Tags = x.Tags.Distinct().ToList()
            });
            var bookmarksKeys = bkDic.Select(x => x.Key).ToHashSet();
            _logger.LogDebug("Found {Count} bookmark", bookmarksKeys.Count);

            foreach (var grouping in bkDic)
            {
                var url = grouping.Key;
                var node = grouping.First();
                var bk = await _bkRepo.GetAsync(url);
                if (bk != null)
                {
                    if (bk.replacedle != node.replacedle)
                    {
                        bk.replacedle = node.replacedle;
                        bk.replacedleLastUpdateTime = _clock.UtcNow;
                        await _bkRepo.UpsertAsync(bk);
                        updated = true;
                    }
                }
            }

            var bks = await _bkRepo.GetAllAsync();
            var newKeys = bookmarksKeys.Except(bks.Select(x => x.Url)).ToArray();

            if (newKeys.Length > 0)
            {
                foreach (var key in newKeys)
                {
                    var bk = bkDic[key].First();
                    await _bkRepo.UpsertAsync(bk);
                    if (bk.Tags?.Any() == true)
                    {
                        foreach (var tag in bk.Tags)
                        {
                            await AppendTagsAsync(tag);
                        }
                    }

                    updated = true;
                }

                _logger.LogInformation("There are {Count} links new, add to storage", newKeys.Length);
            }

            if (updated)
            {
                await UpdateMetadataAsync();
            }
        }

19 Source : HandlersTest.cs
with GNU General Public License v3.0
from Amazing-Favorites

[Test]
        [TestCase(false, true, true, 0)]
        [TestCase(false, true, false, 1)]
        [TestCase(false, false, true, 1)]
        [TestCase(false, false, false, 1)]
        [TestCase(true, true, true, 0)]
        [TestCase(true, true, false, 0)]
        [TestCase(true, false, true, 0)]
        [TestCase(true, false, false, 0)]
        public void RemoveHandlerIfHandleSuccess(bool handlerExpired, bool filterSuccess, bool done, int leftCount)
        {
            var clock = new StaticClock
            {
                UtcNow = DateTimeOffset.Now.ToUnixTimeSeconds()
            };

            using var mocker = AutoMock.GetLoose(builder =>
            {
                builder.RegisterInstance(clock)
                    .AsImplementedInterfaces();
            });
            var handlers = mocker.Create<MessageHandlerCollection>();
            long expiredAt;
            if (handlerExpired)
            {
                expiredAt = clock.UtcNow + Bus.DefaultExpiredDuration;
            }
            else
            {
                expiredAt = default;
            }

            handlers.AddHandler(message => filterSuccess,
                (scope, message) => done,
                expiredAt);

            if (handlerExpired)
            {
                clock.UtcNow = expiredAt + 1;
            }

            // act
            handlers.Handle(new BusMessage(), default!);
            handlers.HandlerItems.Count.Should().Be(leftCount);
        }

19 Source : AggregateRoot.cs
with MIT License
from amolines

internal IEnumerable<Event> FlushUncommittedChanges()
        {
            lock (_changes)
            {
                var changes = _changes.ToArray();
                var i = 0;
                foreach (var @event in changes)
                {
                    i++;
                    ((Event)@event).Version = Version + i;
                    ((Event)@event).TimeStamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
                    ((Event)@event).AggregateId = Id;
                }
                Version = Version + changes.Length;
                _changes.Clear();
                return changes;
            }
        }

19 Source : WebClientExtensions.cs
with Apache License 2.0
from AndcultureCode

public static RestRequest BuildRequestAuthorization(this RestClient webClient, ZoomClientOptions options, string resource, Method method)
        {
            var request = new RestRequest(resource, method);

            var payload = new Dictionary<string, object>()
            {
                { "iss", options.ZoomApiKey },
                { "exp", new DateTimeOffset(DateTime.UtcNow.AddMinutes(1)).ToUnixTimeSeconds() }
            };

            webClient.Authenticator = new JwtAuthenticator(JWT.Encode(payload, Encoding.UTF8.GetBytes(options.ZoomApiSecret), JwsAlgorithm.HS256));
            request.JsonSerializer = new NewtonsoftJsonSerializer();

            return request;
        }

19 Source : ZoomClientTests.cs
with Apache License 2.0
from AndcultureCode

[Test]
        [Ignore("This method should only work IF you have SSOCreate feature enabled on your zoom account. If you are confident it is enabled you can remove this line and test.")]
        public void Create_User_Returns_Valid_User()
        {
            // Arrange
            var email = $"testuser_{DateTimeOffset.Now.ToUnixTimeSeconds()}@gmail.com";
            var user = new CreateUser
            {
                Email = email,
                Type = UserTypes.Basic
            };

            // Act
            var result = _sut.Users.CreateUser(user, CreateUserAction.SsoCreate);

            // replacedert
            result.ShouldNotBeNull();
            result.Email.ShouldBe(email);
            result.Id.ShouldNotBeNull();

            // Cleanup
            _sut.Users.DeleteUser(result.Id, DeleteUserAction.Delete);
        }

19 Source : PluginUI.cs
with MIT License
from andruzzzhka

public void SetLobbyDiscordActivity()
        {
            Plugin.discordActivity = new Discord.Activity
            {
                State = "Playing multiplayer",
                Details = "In lobby",
                Timestamps =
                        {
                            Start = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
                        },
                Instance = false,
            };
            Plugin.discord.UpdateActivity(Plugin.discordActivity);
        }

19 Source : DateTimeExtensions.cs
with MIT License
from anet-team

public static long ToTimestamp(this DateTime time)
        {
            return ((DateTimeOffset)time).ToUnixTimeSeconds();
        }

19 Source : DateHelper.cs
with Apache License 2.0
from anjoy8

public static long ToUnixTimestampBySeconds(DateTime dt)
        {
            DateTimeOffset dto = new DateTimeOffset(dt);
            return dto.ToUnixTimeSeconds();
        }

19 Source : ByPassAuthMidd.cs
with Apache License 2.0
from anjoy8

public async Task Invoke(HttpContext context)
        {
            var path = context.Request.Path;
            // 请求地址,通过Url参数的形式,设置用户id和rolename
            if (path == "/noauth")
            {
                var userid = context.Request.Query["userid"];
                if (!string.IsNullOrEmpty(userid))
                {
                    _currentUserId = userid;
                }

                var rolename = context.Request.Query["rolename"];
                if (!string.IsNullOrEmpty(rolename))
                {
                    _currentRoleName = rolename;
                }

                await SendOkResponse(context, $"User set to {_currentUserId} and Role set to {_currentRoleName}.");
            }
            // 重置角色信息
            else if (path == "/noauth/reset")
            {
                _currentUserId = null;
                _currentRoleName = null;

                await SendOkResponse(context, $"User set to none. Token required for protected endpoints.");
            }
            else
            {
                var currentUserId = _currentUserId;
                var currentRoleName = _currentRoleName;

                // 你也可以通过Header的形式。

                //var authHeader = context.Request.Headers["Authorization"];
                //if (authHeader != StringValues.Empty)
                //{
                //    var header = authHeader.FirstOrDefault();
                //    if (!string.IsNullOrEmpty(header) && header.StartsWith("User ") && header.Length > "User ".Length)
                //    {
                //        currentUserId = header.Substring("User ".Length);
                //    }
                //}

                // 如果用户id和rolename都不为空
                // 可以配置HttpContext.User信息了,也就相当于登录了。
                if (!string.IsNullOrEmpty(currentUserId) && !string.IsNullOrEmpty(currentRoleName))
                {
                    var user = new ClaimsIdenreplacedy(new[] {
                    // 用户id   
                    new Claim("sub", currentUserId),

                    // 用户名、角色名
                    new Claim("name", "Test user"),
                    new Claim(ClaimTypes.Name, "Test user"),
                    new Claim("role", currentRoleName),
                    new Claim(ClaimTypes.Role, currentRoleName),

                    // 过期时间,两个:jwt/ids4
                    new Claim ("exp",$"{new DateTimeOffset(DateTime.Now.AddDays(10100)).ToUnixTimeSeconds()}"),
                    new Claim(ClaimTypes.Expiration, DateTime.Now.AddDays(1).ToString()),

                    // 其他参数
                    new Claim("nonce", Guid.NewGuid().ToString()),
                    new Claim("http://schemas.microsoft.com/idenreplacedy/claims/idenreplacedyprovider", "ByPreplacedAuthMiddleware"),
                    new Claim("http://schemas.xmlsoap.org/ws/2005/05/idenreplacedy/claims/surname","User"),
                    new Claim("http://schemas.xmlsoap.org/ws/2005/05/idenreplacedy/claims/givenname","Microsoft")}
                    , "ByPreplacedAuth");

                    context.User = new ClaimsPrincipal(user);
                }

                await _next.Invoke(context);
            }
        }

19 Source : JwtHelper.cs
with Apache License 2.0
from anjoy8

public static string IssueJwt(TokenModelJwt tokenModel)
        {
            string iss = Appsettings.app(new string[] { "Audience", "Issuer" });
            string aud = Appsettings.app(new string[] { "Audience", "Audience" });
            string secret = AppSecretConfig.Audience_Secret_String;

            //var claims = new Claim[] //old
            var claims = new List<Claim>
                {
                 /*
                 * 特别重要:
                   1、这里将用户的部分信息,比如 uid 存到了Claim 中,如果你想知道如何在其他地方将这个 uid从 Token 中取出来,请看下边的SerializeJwt() 方法,或者在整个解决方案,搜索这个方法,看哪里使用了!
                   2、你也可以研究下 HttpContext.User.Claims ,具体的你可以看看 Policys/PermissionHandler.cs 类中是如何使用的。
                 */

                    

                new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                //这个就是过期时间,目前是过期1000秒,可自定义,注意JWT有自己的缓冲过期时间
                new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(1000)).ToUnixTimeSeconds()}"),
                new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(1000).ToString()),
                new Claim(JwtRegisteredClaimNames.Iss,iss),
                new Claim(JwtRegisteredClaimNames.Aud,aud),
                
                //new Claim(ClaimTypes.Role,tokenModel.Role),//为了解决一个用户多个角色(比如:Admin,System),用下边的方法
               };

            // 可以将一个用户的多个角色全部赋予;
            // 作者:DX 提供技术支持;
            claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));



            //秘钥 (SymmetricSecurityKey 对安全性的要求,密钥的长度太短会报出异常)
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var jwt = new JwtSecurityToken(
                issuer: iss,
                claims: claims,
                signingCredentials: creds);

            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedJwt = jwtHandler.WriteToken(jwt);

            return encodedJwt;
        }

19 Source : Factory.cs
with GNU Affero General Public License v3.0
from ankenyr

public static Operand GetMediaType(ILibraryManager libraryManager, BaseItem baseItem, User user)
        {

            var operand = new Operand(baseItem.Name);
            var directors = new List<string> { };
            var people = libraryManager.GetPeople(baseItem);
            if (people.Any())
            {
                // Maps to MediaBrowser.Model.Enreplacedies.PersonType
                operand.Actors = people.Where(x => x.Type.Equals("Actor")).Select(x => x.Name).ToList();
                operand.Composers = people.Where(x => x.Type.Equals("Composer")).Select(x => x.Name).ToList();
                operand.Directors = people.Where(x => x.Type.Equals("Director")).Select(x => x.Name).ToList();
                operand.GuestStars = people.Where(x => x.Type.Equals("GuestStar")).Select(x => x.Name).ToList();
                operand.Producers = people.Where(x => x.Type.Equals("Producer")).Select(x => x.Name).ToList();
                operand.Writers = people.Where(x => x.Type.Equals("Writer")).Select(x => x.Name).ToList();
            }

            operand.Genres = baseItem.Genres.ToList();
            operand.IsPlayed = baseItem.IsPlayed(user);
            operand.Studios = baseItem.Studios.ToList();
            operand.CommunityRating = baseItem.CommunityRating.GetValueOrDefault();
            operand.CriticRating = baseItem.CriticRating.GetValueOrDefault();
            operand.MediaType = baseItem.MediaType;
            operand.Album = baseItem.Album;

            if (baseItem.PremiereDate.HasValue)
            {
                operand.PremiereDate = new DateTimeOffset(baseItem.PremiereDate.Value).ToUnixTimeSeconds();
            }
            operand.DateCreated = new DateTimeOffset(baseItem.DateCreated).ToUnixTimeSeconds();
            operand.DateLastRefreshed = new DateTimeOffset(baseItem.DateLastRefreshed).ToUnixTimeSeconds();
            operand.DateLastSaved = new DateTimeOffset(baseItem.DateLastSaved).ToUnixTimeSeconds();
            operand.DateModified = new DateTimeOffset(baseItem.DateModified).ToUnixTimeSeconds();
            
            operand.FolderPath = baseItem.ContainingFolderPath;
            return operand;
        }

19 Source : Collection.cs
with MIT License
from AnkiTools

private long GetDayStart()
        {
            var dateOffset = DateTimeOffset.Now;
            TimeSpan FourHoursSpan = new TimeSpan(4, 0, 0);
            dateOffset = dateOffset.Subtract(FourHoursSpan);
            dateOffset = new DateTimeOffset(dateOffset.Year, dateOffset.Month, dateOffset.Day,
                                            0, 0, 0, dateOffset.Offset);
            dateOffset = dateOffset.Add(FourHoursSpan);
            return dateOffset.ToUnixTimeSeconds();
        }

19 Source : JwtAuthenticationOptionTests.cs
with MIT License
from arcus-azure

private static string CreateToken(string key, string issuer, string audience)
        {
            var claims = new[] 
            {
                new Claim(ClaimTypes.Role, "Admin"),
                new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddMinutes(1)).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}")        
            };
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
         
            var securityToken = new JwtSecurityToken(
                issuer: issuer,
                audience: audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddMinutes(1),
                signingCredentials: new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256)
            );

            var securityTokenHandler = new JwtSecurityTokenHandler();
            return securityTokenHandler.WriteToken(securityToken);
        }

19 Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal

public async Task<(IReadOnlyCollection<LastFmRecentTrack> tracks, bool remaining)> GetRecentTracksPage(int page, int count, DateTimeOffset? from = null)
        {
            var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.getrecenttracks&user={User}&api_key={Key}&format=json&limit={count}&page={page}&extended=1" + (from.HasValue ? $"&from={from.Value.ToUnixTimeSeconds()}" : string.Empty));
            request.Timeout = (int)RequestTimeout.TotalMilliseconds;
            using (var response = (HttpWebResponse)await request.GetResponseAsync())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var text = await reader.ReadToEndAsync();
                var root = JObject.Parse(text);
                var tracks = root["recenttracks"]?["track"] as JArray;

                if (tracks != null && tracks.Any())
                {
                    var nowPlaying = page == 1 && string.Compare((string)tracks[0]["@attr"]?["nowplaying"], "true", true) == 0;
                    var result = tracks.Select((x, i) =>
                    {
                        var uts = (long?)x["date"]?["uts"];
                        return new LastFmRecentTrack(
                            (string)x["name"],
                            i == 0 && nowPlaying, 
                            (string)x["artist"]?["name"], 
                            (string)x["album"]?["#text"],
                            GetLargestImage(x["image"]),
                            uts.HasValue ? DateTimeOffset.FromUnixTimeSeconds(uts.Value) : (DateTimeOffset?)null);
                    });
                    
                    var more = page < (int)root["recenttracks"]["@attr"]["totalPages"];
                    return (result.ToList(), more);
                }
                else
                {
                    return (Array.Empty<LastFmRecentTrack>(), false);
                }
            }
        }

19 Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal

public async Task<int> GetTotalPlaycount(DateTimeOffset? from = null)
        {
            var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.getrecenttracks&user={User}&api_key={Key}&limit=1&format=json" + (from.HasValue ? $"&from={from.Value.ToUnixTimeSeconds()}" : string.Empty));
            request.Timeout = (int)RequestTimeout.TotalMilliseconds;
            using (var response = (HttpWebResponse)await request.GetResponseAsync())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var text = await reader.ReadToEndAsync();
                var root = JObject.Parse(text);
                return (int)root["recenttracks"]["@attr"]["total"];
            }
        }

19 Source : DateTimeExtensions.cs
with GNU General Public License v3.0
from atomex-me

public static long ToUnixTimeSeconds(this DateTime dateTime) =>
            ((DateTimeOffset)dateTime.ToUniversalTime()).ToUnixTimeSeconds();

19 Source : BitcoinBasedSwapSpentHelper.cs
with GNU General Public License v3.0
from atomex-me

public static Task StartSwapSpentControlAsync(
            Swap swap,
            CurrencyConfig currency,
            DateTime refundTimeUtc,
            TimeSpan interval,
            Func<Swap, ITxPoint, CancellationToken, Task> completionHandler = null,
            Func<Swap, CancellationToken, Task> refundTimeReachedHandler = null,
            CancellationToken cancellationToken = default)
        {
            return Task.Run(async () =>
            {
                try
                {
                    var bitcoinBased = (BitcoinBasedConfig)currency;

                    var side = swap.Symbol
                        .OrderSideForBuyCurrency(swap.PurchasedCurrency);

                    var requiredAmount = AmountHelper.QtyToAmount(side, swap.Qty, swap.Price, bitcoinBased.DigitsMultiplier);
                    var requiredAmountInSatoshi = bitcoinBased.CoinToSatoshi(requiredAmount);

                    var lockTimeInSeconds = swap.IsInitiator
                        ? CurrencySwap.DefaultInitiatorLockTimeInSeconds
                        : CurrencySwap.DefaultAcceptorLockTimeInSeconds;

                    var refundTimeUtcInSec = new DateTimeOffset(swap.TimeStamp.ToUniversalTime().AddSeconds(lockTimeInSeconds))
                        .ToUnixTimeSeconds();

                    var redeemScript = swap.RefundAddress == null && swap.RedeemScript != null
                        ? new Script(Convert.FromBase64String(swap.RedeemScript))
                        : BitcoinBasedSwapTemplate
                            .GenerateHtlcP2PkhSwapPayment(
                                aliceRefundAddress: swap.RefundAddress,
                                bobAddress: swap.PartyAddress,
                                lockTimeStamp: refundTimeUtcInSec,
                                secretHash: swap.SecretHash,
                                secretSize: CurrencySwap.DefaultSecretSize,
                                expectedNetwork: bitcoinBased.Network);

                    var swapOutput = ((IBitcoinBasedTransaction)swap.PaymentTx)
                        .Outputs
                        .Cast<BitcoinBasedTxOutput>()
                        .FirstOrDefault(o => o.IsPayToScriptHash(redeemScript) && o.Value >= requiredAmountInSatoshi);

                    if (swapOutput == null)
                        throw new InternalException(
                            code: Errors.SwapError,
                            description: "Payment tx have not swap output");

                    while (!cancellationToken.IsCancellationRequested)
                    {
                        Log.Debug("Output spent control for {@currency} swap {@swapId}", currency.Name, swap.Id);

                        var result = await currency
                            .GetSpentPointAsync(
                                hash: swap.PaymentTxId,
                                index: swapOutput.Index,
                                cancellationToken: cancellationToken)
                            .ConfigureAwait(false);

                        if (result != null && !result.HasError)
                        {
                            if (result.Value != null)
                            {
                                await completionHandler.Invoke(swap, result.Value, cancellationToken)
                                    .ConfigureAwait(false);

                                break;
                            }
                        }

                        if (DateTime.UtcNow >= refundTimeUtc)
                        {
                            await refundTimeReachedHandler.Invoke(swap, cancellationToken)
                                .ConfigureAwait(false);

                            break;
                        }

                        await Task.Delay(interval, cancellationToken)
                            .ConfigureAwait(false);
                    }
                }
                catch (OperationCanceledException)
                {
                    Log.Debug("StartSwapSpentControlAsync canceled.");
                }
                catch (Exception e)
                {
                    Log.Error(e, "StartSwapSpentControlAsync error");
                }

            }, cancellationToken);
        }

19 Source : ERC20Swap.cs
with GNU General Public License v3.0
from atomex-me

protected async Task<IEnumerable<EthereumTransaction>> CreatePaymentTxsAsync(
            Swap swap,
            int lockTimeInSeconds,
            CancellationToken cancellationToken = default)
        {
            var erc20Config = Erc20Config;

            Log.Debug("Create payment transactions for swap {@swapId}", swap.Id);

            var requiredAmountInERC20 = RequiredAmountInTokens(swap, erc20Config);

            var refundTimeStampUtcInSec = new DateTimeOffset(swap.TimeStamp.ToUniversalTime().AddSeconds(lockTimeInSeconds)).ToUnixTimeSeconds();
            var isInitTx = true;
            var rewardForRedeemInERC20 = swap.PartyRewardForRedeem;

            var unspentAddresses = (await Erc20Account
                .GetUnspentAddressesAsync(cancellationToken)
                .ConfigureAwait(false))
                .ToList()
                .SortList((a, b) => a.AvailableBalance().CompareTo(b.AvailableBalance()));

            var gasPrice = await EthConfig
                .GetGasPriceAsync(cancellationToken)
                .ConfigureAwait(false);

            var transactions = new List<EthereumTransaction>();

            foreach (var walletAddress in unspentAddresses)
            {
                Log.Debug("Create swap payment tx from address {@address} for swap {@swapId}", walletAddress.Address, swap.Id);

                var balanceInEth = (await EthereumAccount
                    .GetAddressBalanceAsync(
                        address: walletAddress.Address,
                        cancellationToken: cancellationToken)
                    .ConfigureAwait(false))
                    .Available;

                var balanceInERC20 = (await Erc20Account
                    .GetAddressBalanceAsync(
                        address: walletAddress.Address,
                        cancellationToken: cancellationToken)
                    .ConfigureAwait(false))
                    .Available;

                Log.Debug("Available balance: {@balance}", balanceInERC20);

                var feeAmountInEth = isInitTx
                    ? rewardForRedeemInERC20 == 0
                        ? erc20Config.InitiateFeeAmount(gasPrice)
                        : erc20Config.InitiateWithRewardFeeAmount(gasPrice)
                    : erc20Config.AddFeeAmount(gasPrice) + erc20Config.ApproveFeeAmount(gasPrice);

                if (balanceInEth - feeAmountInEth <= 0)
                {
                    Log.Warning(
                        "Insufficient funds at {@address}. Balance: {@balance}, feeAmount: {@feeAmount}, result: {@result}.",
                        walletAddress.Address,
                        balanceInEth,
                        feeAmountInEth,
                        balanceInEth - feeAmountInEth);

                    continue;
                }

                var amountInERC20 = requiredAmountInERC20 > 0
                    ? AmountHelper.DustProofMin(balanceInERC20, requiredAmountInERC20, erc20Config.DigitsMultiplier, erc20Config.DustDigitsMultiplier)
                    : 0;

                requiredAmountInERC20 -= amountInERC20;

                var nonceResult = await ((IEthereumBlockchainApi)erc20Config.BlockchainApi)
                    .GetTransactionCountAsync(walletAddress.Address, pending: false, cancellationToken)
                    .ConfigureAwait(false);

                if (nonceResult.HasError)
                {
                    Log.Error($"Getting nonce error: {nonceResult.Error.Description}");
                    return Enumerable.Empty<EthereumTransaction>();
                }

                TransactionInput txInput;

                //actual transfer              
                if (isInitTx)
                {
                    var initMessage = new ERC20InitiateFunctionMessage
                    {
                        HashedSecret    = swap.SecretHash,
                        ERC20Contract   = erc20Config.ERC20ContractAddress,
                        Participant     = swap.PartyAddress,
                        RefundTimestamp = refundTimeStampUtcInSec,
                        Countdown       = lockTimeInSeconds,
                        Value           = erc20Config.TokensToTokenDigits(amountInERC20),
                        RedeemFee       = erc20Config.TokensToTokenDigits(rewardForRedeemInERC20),
                        Active          = true,
                        FromAddress     = walletAddress.Address,
                        GasPrice        = EthereumConfig.GweiToWei(gasPrice),
                        Nonce           = nonceResult.Value
                    };

                    var initiateGasLimit = rewardForRedeemInERC20 == 0
                        ? erc20Config.InitiateGasLimit
                        : erc20Config.InitiateWithRewardGasLimit;

                    initMessage.Gas = await EstimateGasAsync(initMessage, new BigInteger(initiateGasLimit), cancellationToken)
                        .ConfigureAwait(false);

                    txInput = initMessage.CreateTransactionInput(erc20Config.SwapContractAddress);
                }
                else
                {
                    var addMessage = new ERC20AddFunctionMessage
                    {
                        HashedSecret = swap.SecretHash,
                        Value        = erc20Config.TokensToTokenDigits(amountInERC20),
                        FromAddress  = walletAddress.Address,
                        GasPrice     = EthereumConfig.GweiToWei(gasPrice),
                        Nonce        = nonceResult.Value
                    };

                    addMessage.Gas = await EstimateGasAsync(addMessage, new BigInteger(erc20Config.AddGasLimit), cancellationToken)
                        .ConfigureAwait(false);

                    txInput = addMessage.CreateTransactionInput(erc20Config.SwapContractAddress);
                }

                transactions.Add(new EthereumTransaction(erc20Config.Name, txInput)
                {
                    Type = BlockchainTransactionType.Output | BlockchainTransactionType.SwapPayment
                });

                if (isInitTx)
                    isInitTx = false;

                if (requiredAmountInERC20 <= 0)
                    break;
            }

            if (requiredAmountInERC20 > 0)
            {
                Log.Warning("Insufficient ERC20 or Eth funds (left {@requiredAmount}).", requiredAmountInERC20);
                return Enumerable.Empty<EthereumTransaction>();
            }

            return transactions;
        }

19 Source : FA12Swap.cs
with GNU General Public License v3.0
from atomex-me

protected async Task<IEnumerable<TezosTransaction>> CreatePaymentTxsAsync(
            Swap swap,
            int lockTimeSeconds,
            CancellationToken cancellationToken = default)
        {
            Log.Debug("Create payment transactions for swap {@swapId}", swap.Id);

            var fa12 = Fa12Config;
            var requiredAmountInTokens = RequiredAmountInTokens(swap, fa12); 
            var refundTimeStampUtcInSec = new DateTimeOffset(swap.TimeStamp.ToUniversalTime().AddSeconds(lockTimeSeconds)).ToUnixTimeSeconds();

            var rewardForRedeemInTokenDigits = swap.IsInitiator
                ? swap.PartyRewardForRedeem.ToTokenDigits(fa12.DigitsMultiplier)
                : 0;

            var unspentAddresses = (await Fa12Account
                .GetUnspentTokenAddressesAsync(cancellationToken)
                .ConfigureAwait(false))
                .ToList()
                .SortList(new AvailableBalanceAscending());

            var transactions = new List<TezosTransaction>();

            foreach (var walletAddress in unspentAddresses)
            {
                Log.Debug("Create swap payment tx from address {@address} for swap {@swapId}",
                    walletAddress.Address,
                    swap.Id);

                var balanceInTz = (await TezosAccount
                    .GetAddressBalanceAsync(
                        address: walletAddress.Address,
                        cancellationToken: cancellationToken)
                    .ConfigureAwait(false))
                    .Available;

                var balanceInTokens = (await Fa12Account
                    .GetAddressBalanceAsync(
                        address: walletAddress.Address,
                        cancellationToken: cancellationToken)
                    .ConfigureAwait(false))
                    .Available;

                Log.Debug("Available balance: {@balance}", balanceInTokens);

                var balanceInMtz = balanceInTz.ToMicroTez();

                var isRevealed = await TezosAccount
                    .IsRevealedSourceAsync(walletAddress.Address, cancellationToken)
                    .ConfigureAwait(false);

                var feeAmountInMtz = fa12.ApproveFee * 2 + fa12.InitiateFee +
                    (isRevealed ? 0 : fa12.RevealFee);

                var storageLimitInMtz = (fa12.ApproveStorageLimit * 2 + fa12.InitiateStorageLimit) *
                    fa12.StorageFeeMultiplier;

                if (balanceInMtz - feeAmountInMtz - storageLimitInMtz - XtzConfig.MicroTezReserve <= 0)
                {
                    Log.Warning(
                        "Insufficient funds at {@address}. Balance: {@balance}, " +
                        "feeAmount: {@feeAmount}, storageLimit: {@storageLimit}.",
                        walletAddress.Address,
                        balanceInMtz,
                        feeAmountInMtz,
                        storageLimitInMtz);

                    continue;
                }

                var amountInTokens = requiredAmountInTokens > 0
                    ? AmountHelper.DustProofMin(balanceInTokens, requiredAmountInTokens, fa12.DigitsMultiplier, fa12.DustDigitsMultiplier)
                    : 0;

                if (amountInTokens == 0)
                    break;

                if (requiredAmountInTokens > amountInTokens)
                    continue; // insufficient funds
                
                transactions.Add(new TezosTransaction
                {
                    Currency     = XtzConfig.Name,
                    CreationTime = DateTime.UtcNow,
                    From         = walletAddress.Address,
                    To           = fa12.SwapContractAddress,
                    Fee          = feeAmountInMtz,
                    GasLimit     = fa12.InitiateGasLimit,
                    StorageLimit = fa12.InitiateStorageLimit,
                    Params       = InitParams(swap, fa12.TokenContractAddress, amountInTokens.ToTokenDigits(fa12.DigitsMultiplier), refundTimeStampUtcInSec, (long)rewardForRedeemInTokenDigits),
                    Type         = BlockchainTransactionType.Output | BlockchainTransactionType.SwapPayment,

                    UseRun              = true,
                    UseSafeStorageLimit = true,
                    UseOfflineCounter   = true
                });

                break;
            }

            if (!transactions.Any())
                Log.Warning("Insufficient funds.");

            return transactions;
        }

19 Source : BitcoinBasedConfig.cs
with GNU General Public License v3.0
from atomex-me

public virtual IBitcoinBasedTransaction CreateHtlcP2PkhScriptSwapPaymentTx(
            IEnumerable<ITxOutput> unspentOutputs,
            string aliceRefundAddress,
            string bobAddress,
            DateTimeOffset lockTime,
            byte[] secretHash,
            int secretSize,
            long amount,
            long fee,
            out byte[] redeemScript)
        {
            var coins = unspentOutputs
                .Cast<BitcoinBasedTxOutput>()
                .Select(o => o.Coin);

            var swap = BitcoinBasedSwapTemplate.GenerateHtlcP2PkhSwapPayment(
                aliceRefundAddress: aliceRefundAddress,
                bobAddress: bobAddress,
                lockTimeStamp: lockTime.ToUnixTimeSeconds(),
                secretHash: secretHash,
                secretSize: secretSize,
                expectedNetwork: Network);

            redeemScript = swap.ToBytes();

            var change = BitcoinAddress.Create(aliceRefundAddress, Network)
                .ScriptPubKey;

            return BitcoinBasedTransaction.CreateTransaction(
                currency: this,
                coins: coins,
                destination: swap.PaymentScript,
                change: change,
                amount: amount,
                fee: fee);
        }

19 Source : BitcoinBasedSwap.cs
with GNU General Public License v3.0
from atomex-me

public override async Task RedeemAsync(
            Swap swap,
            CancellationToken cancellationToken = default)
        {
            Log.Debug("Redeem for swap {@swap}.", swap.Id);

            var currency = Currencies.GetByName(swap.PurchasedCurrency);

            var needReplaceTx= false;

            if (swap.StateFlags.HasFlag(SwapStateFlags.IsRedeemBroadcast))
            {
                Log.Debug("Check redeem confirmation for swap {@swap}.", swap.Id);

                // redeem already broadcast
                var result = await currency
                    .IsTransactionConfirmed(
                        txId: swap.RedeemTx.Id,
                        cancellationToken: cancellationToken)
                    .ConfigureAwait(false);

                if (result == null)
                {
                    Log.Error("Error while check bitcoin based redeem tx confirmation. Result is null.");
                    return;
                }
                else if (result.HasError && result.Error.Code == (int)HttpStatusCode.NotFound)
                {
                    // probably the transaction was deleted by miners
                    Log.Debug("Probably the transaction {@tx} was deleted by miners.", swap.RedeemTx.Id);
                    needReplaceTx = true;
                }
                else if (result.HasError)
                {
                    Log.Error("Error while check bitcoin based redeem tx confirmation. Code: {@code}. Description: {@description}.",
                        result.Error.Code,
                        result.Error.Description);

                    return;
                }
                else if (result.Value.IsConfirmed) // tx already confirmed
                {
                    Log.Debug("Transaction {@tx} is already confirmed.", swap.RedeemTx.Id);

                    await RedeemConfirmedEventHandler(swap, result.Value.Transaction, cancellationToken)
                        .ConfigureAwait(false);

                    return;
                }

                var currentTimeUtc = DateTime.UtcNow;

                var creationTimeUtc = swap.RedeemTx.CreationTime != null
                    ? swap.RedeemTx.CreationTime.Value.ToUniversalTime()
                    : swap.TimeStamp.ToUniversalTime();

                var difference = currentTimeUtc - creationTimeUtc;

                Log.Debug("Currenct time: {@current}, creation time: {@now}, difference: {@diff}",
                    currentTimeUtc,
                    creationTimeUtc,
                    difference);

                // check transaction creation time and try replacing it with a higher fee
                if (difference >= TimeSpan.FromHours(4))
                    needReplaceTx = true;

                if (!needReplaceTx)
                {
                    _ = TrackTransactionConfirmationAsync(
                        swap: swap,
                        currency: currency,
                        dataRepository: _account.DataRepository,
                        txId: swap.RedeemTx.Id,
                        confirmationHandler: RedeemConfirmedEventHandler,
                        cancellationToken: cancellationToken);

                    return;
                }
            }

            if (swap.IsInitiator)
            {
                var redeemDeadline = swap.TimeStamp.ToUniversalTime().AddSeconds(DefaultAcceptorLockTimeInSeconds) - RedeemTimeReserve;

                if (DateTime.UtcNow > redeemDeadline)
                {
                    Log.Error("Redeem dedline reached for swap {@swap}", swap.Id);
                    return;
                }
            }

            var redeemAddress = await _account
                .GetFreeInternalAddressAsync()
                .ConfigureAwait(false);

            var lockTimeInSeconds = swap.IsInitiator
                ? DefaultAcceptorLockTimeInSeconds
                : DefaultInitiatorLockTimeInSeconds;

            var refundTimeUtcInSec = new DateTimeOffset(swap.TimeStamp.ToUniversalTime().AddSeconds(lockTimeInSeconds))
                .ToUnixTimeSeconds();

            var bitcoinBased = (BitcoinBasedConfig)currency;

            var partyRedeemScript = swap.PartyRefundAddress == null && swap.PartyRedeemScript != null
                ? new Script(Convert.FromBase64String(swap.PartyRedeemScript))
                : BitcoinBasedSwapTemplate
                    .GenerateHtlcP2PkhSwapPayment(
                        aliceRefundAddress: swap.PartyRefundAddress,
                        bobAddress: swap.ToAddress,
                        lockTimeStamp: refundTimeUtcInSec,
                        secretHash: swap.SecretHash,
                        secretSize: DefaultSecretSize,
                        expectedNetwork: bitcoinBased.Network);

            var side = swap.Symbol
                .OrderSideForBuyCurrency(swap.PurchasedCurrency)
                .Opposite();

            // get party payment
            var partyPaymentResult = await BitcoinBasedSwapInitiatedHelper
                .TryToFindPaymentAsync(
                    swap: swap,
                    currency: currency,
                    side: side,
                    toAddress: swap.ToAddress,
                    refundAddress: swap.PartyRefundAddress,
                    refundTimeStamp: refundTimeUtcInSec,
                    redeemScriptBase64: swap.PartyRedeemScript,
                    cancellationToken: cancellationToken)
                .ConfigureAwait(false);

            if (partyPaymentResult == null || partyPaymentResult.HasError || partyPaymentResult.Value == null)
            {
                Log.Error($"BitcoinBased: can't get party payment for swap {swap.Id}");
                return;
            }

            // create redeem tx
            swap.RedeemTx = await CreateRedeemTxAsync(
                    swap: swap,
                    paymentTx: (IBitcoinBasedTransaction)partyPaymentResult.Value,
                    redeemAddress: redeemAddress.Address,
                    redeemScript: partyRedeemScript.ToBytes(),
                    increaseSequenceNumber: needReplaceTx)
                .ConfigureAwait(false);

            var toAddress = await _account
                .GetAddressAsync(currency.Name, swap.ToAddress, cancellationToken)
                .ConfigureAwait(false);

            // sign redeem tx
            swap.RedeemTx = await SignRedeemTxAsync(
                    swap: swap,
                    redeemTx: (IBitcoinBasedTransaction)swap.RedeemTx,
                    paymentTx: (IBitcoinBasedTransaction)partyPaymentResult.Value,
                    redeemAddress: toAddress,
                    redeemScript: partyRedeemScript.ToBytes())
                .ConfigureAwait(false);

            swap.StateFlags |= SwapStateFlags.IsRedeemSigned;

            await UpdateSwapAsync(swap, SwapStateFlags.IsRedeemSigned, cancellationToken)
                .ConfigureAwait(false);

            // broadcast redeem tx
            await BroadcastRedeemAsync(
                    swap: swap,
                    redeemTx: swap.RedeemTx,
                    cancellationToken: cancellationToken)
                .ConfigureAwait(false);

            swap.StateFlags |= SwapStateFlags.IsRedeemBroadcast;

            await UpdateSwapAsync(swap, SwapStateFlags.IsRedeemBroadcast, cancellationToken)
                .ConfigureAwait(false);

            // add new unconfirmed transaction
            await _account
                .UpsertTransactionAsync(
                    tx: swap.RedeemTx,
                    updateBalance: true,
                    cancellationToken: cancellationToken)
                .ConfigureAwait(false);

            _ = TrackTransactionConfirmationAsync(
                swap: swap,
                currency: currency,
                dataRepository: _account.DataRepository,
                txId: swap.RedeemTx.Id,
                confirmationHandler: RedeemConfirmedEventHandler,
                cancellationToken: cancellationToken);
        }

19 Source : BitcoinBasedSwap.cs
with GNU General Public License v3.0
from atomex-me

public override async Task<Result<IBlockchainTransaction>> TryToFindPaymentAsync(
            Swap swap,
            CancellationToken cancellationToken = default)
        {
            var lockTimeInSeconds = swap.IsInitiator
                ? DefaultInitiatorLockTimeInSeconds
                : DefaultAcceptorLockTimeInSeconds;

            var refundTimeUtcInSec = new DateTimeOffset(swap.TimeStamp.ToUniversalTime().AddSeconds(lockTimeInSeconds))
                .ToUnixTimeSeconds();

            var currency = Currencies
                .GetByName(swap.SoldCurrency);

            var side = swap.Symbol
                .OrderSideForBuyCurrency(swap.PurchasedCurrency);

            return await BitcoinBasedSwapInitiatedHelper
                .TryToFindPaymentAsync(
                    swap: swap,
                    currency: currency,
                    side: side,
                    toAddress: swap.PartyAddress,
                    refundAddress: swap.RefundAddress,
                    refundTimeStamp: refundTimeUtcInSec,
                    redeemScriptBase64: swap.RedeemScript,
                    cancellationToken: cancellationToken)
                .ConfigureAwait(false);
        }

19 Source : EthereumSwap.cs
with GNU General Public License v3.0
from atomex-me

public override Task StartPartyPaymentControlAsync(
            Swap swap,
            CancellationToken cancellationToken = default)
        {
            Log.Debug("Start party payment control for swap {@swap}.", swap.Id);

            // initiator waits "accepted" event, acceptor waits "initiated" event
            var initiatedHandler = swap.IsInitiator
                ? new Func<Swap, CancellationToken, Task>(SwapAcceptedHandler)
                : new Func<Swap, CancellationToken, Task>(SwapInitiatedHandler);

            var lockTimeInSeconds = swap.IsInitiator
                ? DefaultAcceptorLockTimeInSeconds
                : DefaultInitiatorLockTimeInSeconds;

            var refundTimeUtcInSec = new DateTimeOffset(swap.TimeStamp.ToUniversalTime().AddSeconds(lockTimeInSeconds)).ToUnixTimeSeconds();

            _ = EthereumSwapInitiatedHelper.StartSwapInitiatedControlAsync(
                swap: swap,
                currency: EthConfig,
                refundTimeStamp: refundTimeUtcInSec,
                interval: ConfirmationCheckInterval,
                initiatedHandler: initiatedHandler,
                canceledHandler: SwapCanceledHandler,
                cancellationToken: cancellationToken);

            return Task.CompletedTask;
        }

19 Source : FA12Swap.cs
with GNU General Public License v3.0
from atomex-me

public override Task StartPartyPaymentControlAsync(
            Swap swap,
            CancellationToken cancellationToken = default)
        {
            Log.Debug("Start party payment control for swap {@swap}.", swap.Id);

            // initiator waits "accepted" event, acceptor waits "initiated" event
            var initiatedHandler = swap.IsInitiator
                ? new Func<Swap, CancellationToken, Task>(SwapAcceptedHandler)
                : new Func<Swap, CancellationToken, Task>(SwapInitiatedHandler);

            var lockTimeSeconds = swap.IsInitiator
                ? DefaultAcceptorLockTimeInSeconds
                : DefaultInitiatorLockTimeInSeconds;

            var refundTimeUtcInSec = new DateTimeOffset(swap.TimeStamp.ToUniversalTime().AddSeconds(lockTimeSeconds)).ToUnixTimeSeconds();

            _ = Fa12SwapInitiatedHelper.StartSwapInitiatedControlAsync(
                swap: swap,
                currency: Fa12Config,
                tezos: XtzConfig,
                refundTimeStamp: refundTimeUtcInSec,
                interval: ConfirmationCheckInterval,
                initiatedHandler: initiatedHandler,
                canceledHandler: SwapCanceledHandler,
                cancellationToken: cancellationToken);

            return Task.CompletedTask;
        }

19 Source : BitcoinBasedSwap.cs
with GNU General Public License v3.0
from atomex-me

public override Task StartPartyPaymentControlAsync(
            Swap swap,
            CancellationToken cancellationToken = default)
        {
            Log.Debug("Start party payment control for swap {@swap}.", swap.Id);

            // initiator waits "accepted" event, acceptor waits "initiated" event
            var initiatedHandler = swap.IsInitiator
                ? new Func<Swap, CancellationToken, Task>(SwapAcceptedHandler)
                : new Func<Swap, CancellationToken, Task>(SwapInitiatedHandler);

            var lockTimeInSeconds = swap.IsInitiator
                ? DefaultAcceptorLockTimeInSeconds
                : DefaultInitiatorLockTimeInSeconds;

            var refundTimeUtcInSec = new DateTimeOffset(swap.TimeStamp.ToUniversalTime().AddSeconds(lockTimeInSeconds)).ToUnixTimeSeconds();

            _ = BitcoinBasedSwapInitiatedHelper.StartSwapInitiatedControlAsync(
                swap: swap,
                currency: Config,
                refundTimeStamp: refundTimeUtcInSec,
                interval: ConfirmationCheckInterval,
                initiatedHandler: initiatedHandler,
                canceledHandler: SwapCanceledHandler,
                cancellationToken: cancellationToken);

            return Task.CompletedTask;
        }

19 Source : TezosSwap.cs
with GNU General Public License v3.0
from atomex-me

protected virtual async Task<IEnumerable<TezosTransaction>> CreatePaymentTxsAsync(
            Swap swap,
            int lockTimeSeconds,
            CancellationToken cancellationToken = default)
        {
            var xtzConfig = XtzConfig;

            Log.Debug("Create payment transactions for swap {@swapId}", swap.Id);

            var requiredAmountInMtz = AmountHelper
                .QtyToAmount(swap.Side, swap.Qty, swap.Price, xtzConfig.DigitsMultiplier)
                .ToMicroTez();

            // maker network fee
            if (swap.MakerNetworkFee > 0)
            {
                var makerNetworkFeeInMtz = swap.MakerNetworkFee.ToMicroTez();

                if (makerNetworkFeeInMtz < requiredAmountInMtz) // network fee size check
                    requiredAmountInMtz += makerNetworkFeeInMtz;
            }

            var refundTimeStampUtcInSec = new DateTimeOffset(swap.TimeStamp.ToUniversalTime().AddSeconds(lockTimeSeconds)).ToUnixTimeSeconds();
            var isInitTx = true;
            var rewardForRedeemInMtz = swap.IsInitiator
                ? swap.PartyRewardForRedeem.ToMicroTez()
                : 0;

            var unspentAddresses = (await _account
                .GetUnspentAddressesAsync(cancellationToken)
                .ConfigureAwait(false))
                .ToList()
                .SortList(new AvailableBalanceAscending());

            var transactions = new List<TezosTransaction>();

            foreach (var walletAddress in unspentAddresses)
            {
                Log.Debug("Create swap payment tx from address {@address} for swap {@swapId}",
                    walletAddress.Address,
                    swap.Id);

                var balanceInTz = (await _account
                    .GetAddressBalanceAsync(
                        address: walletAddress.Address,
                        cancellationToken: cancellationToken)
                    .ConfigureAwait(false))
                    .Available;

                Log.Debug("Available balance: {@balance}", balanceInTz);

                var balanceInMtz = balanceInTz.ToMicroTez();

                var isRevealed = await _account
                    .IsRevealedSourceAsync(walletAddress.Address, cancellationToken)
                    .ConfigureAwait(false);

                var feeAmountInMtz = isInitTx
                    ? xtzConfig.InitiateFee + (isRevealed ? 0 : xtzConfig.RevealFee)
                    : xtzConfig.AddFee + (isRevealed ? 0 : xtzConfig.RevealFee);

                var storageLimitInMtz = isInitTx
                    ? xtzConfig.InitiateStorageLimit * xtzConfig.StorageFeeMultiplier
                    : xtzConfig.AddStorageLimit * xtzConfig.StorageFeeMultiplier;

                var amountInMtz = Math.Min(balanceInMtz - feeAmountInMtz - storageLimitInMtz, requiredAmountInMtz);

                if (amountInMtz <= 0)
                {
                    Log.Warning(
                        "Insufficient funds at {@address}. Balance: {@balance}, " +
                        "feeAmount: {@feeAmount}, storageLimit: {@storageLimit}, result: {@result}.",
                        walletAddress.Address,
                        balanceInMtz,
                        feeAmountInMtz,
                        storageLimitInMtz,
                        amountInMtz);

                    continue;
                }

                requiredAmountInMtz -= amountInMtz;

                if (isInitTx)
                {
                    transactions.Add(new TezosTransaction
                    {
                        Currency     = xtzConfig.Name,
                        CreationTime = DateTime.UtcNow,
                        From         = walletAddress.Address,
                        To           = xtzConfig.SwapContractAddress,
                        Amount       = Math.Round(amountInMtz, 0),
                        Fee          = feeAmountInMtz,
                        GasLimit     = xtzConfig.InitiateGasLimit,
                        StorageLimit = xtzConfig.InitiateStorageLimit,
                        Params       = InitParams(swap, refundTimeStampUtcInSec, (long)rewardForRedeemInMtz),
                        Type         = BlockchainTransactionType.Output | BlockchainTransactionType.SwapPayment,

                        UseRun              = true,
                        UseSafeStorageLimit = true,
                        UseOfflineCounter   = true
                    });
                }
                else
                {
                    transactions.Add(new TezosTransaction
                    {
                        Currency     = xtzConfig.Name,
                        CreationTime = DateTime.UtcNow,
                        From         = walletAddress.Address,
                        To           = xtzConfig.SwapContractAddress,
                        Amount       = Math.Round(amountInMtz, 0),
                        Fee          = feeAmountInMtz,
                        GasLimit     = xtzConfig.AddGasLimit,
                        StorageLimit = xtzConfig.AddStorageLimit,
                        Params       = AddParams(swap),
                        Type         = BlockchainTransactionType.Output | BlockchainTransactionType.SwapPayment,

                        UseRun              = true,
                        UseSafeStorageLimit = true,
                        UseOfflineCounter   = true
                    });
                }

                if (isInitTx)
                    isInitTx = false;

                if (requiredAmountInMtz == 0)
                    break;
            }

            if (requiredAmountInMtz > 0)
            {
                Log.Warning("Insufficient funds (left {@requredAmount}).", requiredAmountInMtz);
                return Enumerable.Empty<TezosTransaction>();
            }

            return transactions;
        }

19 Source : ERC20SwapInitiatedHelper.cs
with GNU General Public License v3.0
from atomex-me

public static async Task<Result<bool>> IsInitiatedAsync(
            Swap swap,
            CurrencyConfig currency,
            long lockTimeInSec,
            CancellationToken cancellationToken = default)
        {
            try
            {
                Log.Debug("Ethereum ERC20: check initiated event");

                var erc20 = (Erc20Config)currency;

                var side = swap.Symbol
                    .OrderSideForBuyCurrency(swap.PurchasedCurrency)
                    .Opposite();

                var refundTimeStamp = new DateTimeOffset(swap.TimeStamp.ToUniversalTime().AddSeconds(lockTimeInSec)).ToUnixTimeSeconds();
                var requiredAmountInERC20 = AmountHelper.QtyToAmount(side, swap.Qty, swap.Price, erc20.DigitsMultiplier);
                var requiredAmountInDecimals = erc20.TokensToTokenDigits(requiredAmountInERC20);
                var receivedAmountInDecimals = new BigInteger(0);
                var requiredRewardForRedeemInDecimals = swap.IsAcceptor
                    ? erc20.TokensToTokenDigits(swap.RewardForRedeem)
                    : 0;

                var api = new EtherScanApi(erc20);

                var initiateEventsResult = await api
                    .GetContractEventsAsync(
                        address: erc20.SwapContractAddress,
                        fromBlock: erc20.SwapContractBlockNumber,
                        toBlock: ulong.MaxValue,
                        topic0: EventSignatureExtractor.GetSignatureHash<ERC20InitiatedEventDTO>(),
                        topic1: "0x" + swap.SecretHash.ToHexString(),
                        topic2: "0x000000000000000000000000" + erc20.ERC20ContractAddress.Substring(2),  //??
                        topic3: "0x000000000000000000000000" + swap.ToAddress.Substring(2),
                        cancellationToken: cancellationToken)
                    .ConfigureAwait(false);

                if (initiateEventsResult == null)
                    return new Error(Errors.RequestError, $"Connection error while trying to get contract {erc20.SwapContractAddress} initiate event");

                if (initiateEventsResult.HasError)
                    return initiateEventsResult.Error;

                var events = initiateEventsResult.Value?.ToList();

                if (events == null || !events.Any())
                    return false;

                var contractInitEvent = events.Last();

                var initiatedEvent = contractInitEvent.ParseERC20InitiatedEvent();

                if (initiatedEvent.RefundTimestamp != refundTimeStamp)
                {
                    Log.Debug(
                        "Invalid refund time in initiated event. Expected value is {@expected}, actual is {@actual}",
                        refundTimeStamp,
                        (long)initiatedEvent.RefundTimestamp);

                    return new Error(
                        code: Errors.InvalidRefundLockTime,
                        description: $"Invalid refund time in initiated event. Expected value is {refundTimeStamp}, actual is {(long)initiatedEvent.RefundTimestamp}");
                }

                if (initiatedEvent.Countdown != lockTimeInSec)  //todo: use it
                {
                    Log.Debug(
                        "Invalid countdown in initiated event. Expected value is {@expected}, actual is {@actual}",
                        lockTimeInSec,
                        (long)initiatedEvent.Countdown);

                    return new Error(
                        code: Errors.InvalidRewardForRedeem,
                        description: $"Invalid countdown in initiated event. Expected value is {lockTimeInSec}, actual is {(long)initiatedEvent.Countdown}");
                }

                if (initiatedEvent.RedeemFee != requiredRewardForRedeemInDecimals)
                {
                    Log.Debug(
                        "Invalid redeem fee in initiated event. Expected value is {@expected}, actual is {@actual}",
                        requiredRewardForRedeemInDecimals,
                        (long)initiatedEvent.RedeemFee);

                    return new Error(
                        code: Errors.InvalidRewardForRedeem,
                        description: $"Invalid redeem fee in initiated event. Expected value is {requiredRewardForRedeemInDecimals}, actual is {(long)initiatedEvent.RedeemFee}");
                }

                if (!initiatedEvent.Active)
                {
                    Log.Debug(
                        "Invalid active value in initiated event. Expected value is {@expected}, actual is {@actual}",
                        true,
                        initiatedEvent.Active);

                    return new Error(
                        code: Errors.InvalidRewardForRedeem,
                        description: $"Invalid active value in initiated event. Expected value is {true}, actual is {initiatedEvent.Active}");
                }

                var erc20TransferValues = await GetTransferValuesAsync(
                        currency: currency,
                        from: initiatedEvent.Initiator.Substring(2),
                        to: erc20.SwapContractAddress.Substring(2),
                        blockNumber: contractInitEvent.HexBlockNumber,
                        cancellationToken: cancellationToken)
                    .ConfigureAwait(false);

                if (!erc20TransferValues.Contains(initiatedEvent.Value + initiatedEvent.RedeemFee))
                {
                    var actualTransferValue = string.Join(", ", erc20TransferValues.Select(v => v.ToString()));

                    Log.Debug(
                        "Invalid transfer value in erc20 initiated event. Expected value is {@expected}, actual is {@actual}",
                        initiatedEvent.Value.ToString(),
                        actualTransferValue);

                    return new Error(
                        code: Errors.InvalidSwapPaymentTx,
                        description: $"Invalid transfer value in erc20 initiated event. Expected value is {initiatedEvent.Value}, actual is {actualTransferValue}");
                }

                receivedAmountInDecimals = initiatedEvent.Value;

                if (receivedAmountInDecimals >= requiredAmountInDecimals - requiredRewardForRedeemInDecimals)
                    return true;

                Log.Debug(
                    "Ethereum ERC20 value is not enough. Expected value is {@expected}. Actual value is {@actual}",
                    (decimal)(requiredAmountInDecimals - requiredRewardForRedeemInDecimals),
                    (decimal)initiatedEvent.Value);

                var addEventsResult = await api
                    .GetContractEventsAsync(
                        address: erc20.SwapContractAddress,
                        fromBlock: erc20.SwapContractBlockNumber,
                        toBlock: ulong.MaxValue,
                        topic0: EventSignatureExtractor.GetSignatureHash<ERC20AddedEventDTO>(),
                        topic1: "0x" + swap.SecretHash.ToHexString(),
                        cancellationToken: cancellationToken)
                    .ConfigureAwait(false);

                if (addEventsResult == null)
                    return new Error(Errors.RequestError, $"Connection error while trying to get contract {erc20.SwapContractAddress} add event");

                if (addEventsResult.HasError)
                    return addEventsResult.Error;

                events = addEventsResult.Value?.ToList();

                if (events == null || !events.Any())
                    return false;

                foreach (var @event in events.Select(e => e.ParseERC20AddedEvent()))
                {
                    erc20TransferValues = await GetTransferValuesAsync(
                            currency: currency,
                            from: @event.Initiator.Substring(2),
                            to: erc20.SwapContractAddress.Substring(2),
                            blockNumber: contractInitEvent.HexBlockNumber,
                            cancellationToken: cancellationToken)
                        .ConfigureAwait(false);

                    if (!erc20TransferValues.Contains(@event.Value - receivedAmountInDecimals))
                    {
                        var actualTransferValue = string.Join(", ", erc20TransferValues.Select(v => v.ToString()));

                        Log.Debug(
                            "Invalid transfer value in added event. Expected value is {@expected}, actual is {@actual}",
                            (@event.Value - receivedAmountInDecimals).ToString(),
                            actualTransferValue);

                        return new Error(
                            code: Errors.InvalidSwapPaymentTx,
                            description: $"Invalid transfer value in initiated event. Expected value is {@event.Value - receivedAmountInDecimals}, actual is {actualTransferValue}");
                    }

                    receivedAmountInDecimals = @event.Value;

                    if (receivedAmountInDecimals >= requiredAmountInDecimals - requiredRewardForRedeemInDecimals)
                        return true;

                    Log.Debug(
                        "Ethereum ERC20 value is not enough. Expected value is {@expected}. Actual value is {@actual}",
                        requiredAmountInDecimals - requiredRewardForRedeemInDecimals,
                        (long)@event.Value);
                }

            }
            catch (Exception e)
            {
                Log.Error(e, "Ethereum ERC20 swap initiated control task error");

                return new Error(Errors.InternalError, e.Message);
            }

            return false;
        }

19 Source : ERC20Swap.cs
with GNU General Public License v3.0
from atomex-me

public override Task StartPartyPaymentControlAsync(
            Swap swap,
            CancellationToken cancellationToken = default)
        {
            Log.Debug("Start party payment control for swap {@swap}.", swap.Id);

            // initiator waits "accepted" event, acceptor waits "initiated" event
            var initiatedHandler = swap.IsInitiator
                ? new Func<Swap, CancellationToken, Task>(SwapAcceptedHandler)
                : new Func<Swap, CancellationToken, Task>(SwapInitiatedHandler);

            var lockTimeInSeconds = swap.IsInitiator
                ? DefaultAcceptorLockTimeInSeconds
                : DefaultInitiatorLockTimeInSeconds;

            var refundTimeUtcInSec = new DateTimeOffset(swap.TimeStamp.ToUniversalTime().AddSeconds(lockTimeInSeconds)).ToUnixTimeSeconds();

            _ = ERC20SwapInitiatedHelper.StartSwapInitiatedControlAsync(
                swap: swap,
                currency: Erc20Config,
                lockTimeInSec: lockTimeInSeconds,
                interval: ConfirmationCheckInterval,
                initiatedHandler: initiatedHandler,
                canceledHandler: SwapCanceledHandler,
                cancellationToken: cancellationToken);

            return Task.CompletedTask;
        }

See More Examples