Esempio n. 1
0
        public async Task <IActionResult> WordingAsync(
            string id,
            GetBaseRequest request,
            [FromServices] KyubeyContext db,
            [FromServices] TokenRepositoryFactory tokenRepositoryFactory,
            CancellationToken cancellationToken)
        {
            var dbToken = await db.Tokens.FirstOrDefaultAsync(x => x.Id == id && x.Status == TokenStatus.Active, cancellationToken);

            if (dbToken == null)
            {
                return(ApiResult(404, "not found this token"));
            }
            var tokenRepository = await tokenRepositoryFactory.CreateAsync(request.Lang);

            var banners = tokenRepository.GetTokenIncubationBannereRelativePaths(id, request.Lang).Select(x => $"/token_assets/" + x).ToList();

            var updates = tokenRepository.GetTokenIncubatorUpdates(id, request.Lang)?.OrderBy(x => x.Time)?.OrderByDescending(x => x.Time).ToList();

            var response = new GetWordingResponse()
            {
                TokenId     = id,
                Description = tokenRepository.GetTokenDescription(id, request.Lang),
                Detail      = tokenRepository.GetTokenIncubationDetail(id, request.Lang),
                Updates     = updates,
                Sliders     = banners
            };

            return(ApiResult(response));
        }
Esempio n. 2
0
        public async Task <IActionResult> GetEOSBalanceAsync(string account, string symbol, string lang, [FromServices] ILogger logger, [FromServices] KyubeyContext db, [FromServices] TokenRepositoryFactory tokenRepositoryFactory, [FromServices] NodeApiInvoker nodeApiInvoker, CancellationToken cancellationToken)
        {
            var tokenRespository = await tokenRepositoryFactory.CreateAsync(lang);

            var buyTokens = await db.DexBuyOrders.Where(x => x.Account == account).Select(x => x.TokenId).Distinct().ToListAsync(cancellationToken);

            var sellTokens = await db.DexSellOrders.Where(x => x.Account == account).Select(x => x.TokenId).Distinct().ToListAsync(cancellationToken);

            var matchTokens = await db.MatchReceipts
                              .Where(x => x.Time >= DateTime.Now.AddMonths(-3) &&
                                     (x.Asker == account || x.Bidder == account))
                              .Select(x => x.TokenId).Distinct().ToListAsync(cancellationToken);

            var tokens = buyTokens.Concat(sellTokens).Concat(matchTokens).Distinct().ToList();

            if (!string.IsNullOrWhiteSpace(symbol))
            {
                if (!tokens.Contains(symbol))
                {
                    tokens.Add(symbol);
                }
            }

            var responseData = new Dictionary <string, double>();

            tokens.ForEach(x =>
            {
                var currentTokenBalance = 0.0;
                try
                {
                    var tokenInfo = tokenRespository.GetSingle(x);
                    if (tokenInfo != null)
                    {
                        currentTokenBalance = nodeApiInvoker.GetCurrencyBalanceAsync(account, tokenInfo?.Basic?.Contract?.Transfer, x, cancellationToken).Result;
                    }
                }
                catch (Newtonsoft.Json.JsonSerializationException ex)
                {
                    logger.LogError(ex.ToString());
                }
                finally
                {
                    responseData.Add(x, currentTokenBalance);
                }
            });
            responseData.Add("EOS", await nodeApiInvoker.GetCurrencyBalanceAsync(account, "eosio.token", "EOS", cancellationToken));
            return(ApiResult(responseData));
        }
Esempio n. 3
0
        public async Task <IActionResult> List(
            GetIncubatorListRequest request,
            [FromServices] KyubeyContext db,
            [FromServices] TokenRepositoryFactory tokenRepositoryFactory,
            CancellationToken cancellationToken
            )
        {
            var tokenRepository = await tokenRepositoryFactory.CreateAsync(request.Lang);


            var matchTokens = db.MatchReceipts.ToList().OrderByDescending(x => x.Time).GroupBy(x => x.TokenId).Select(x => new
            {
                Id    = x.Key,
                Price = x.FirstOrDefault()?.UnitPrice
            }).ToList();
            var tokens = db.Tokens.OrderByDescending(x => x.Priority).ToList().Select(x => new
            {
                Symbol   = x.Id,
                Contract = tokenRepository.GetSingle(x.Id).Basic.Contract?.Transfer,
                MaxPrice = (Math.Round((decimal)((x.NewDexAsk == 0 || x.NewDexAsk == null) ? matchTokens.FirstOrDefault(m => m.Id == x.Id)?.Price ?? 0 : x.NewDexAsk), 8) * 1.1m).ToString()
            }).ToList();

            var json = JsonConvert.SerializeObject(tokens);


            var tokenList        = tokenRepository.EnumerateAll();
            var projectManifests = new GetIncubatorPaginationResponse();

            projectManifests.IncubatorList = new List <GetIncubatorListResponse>();

            tokenList = tokenList.Where(x => x?.Incubation != null).ToList();
            var dbIncubations = await db.Tokens.Where(x =>
                                                      x.HasIncubation && tokenList.FirstOrDefault(t => x.Id == t.Id).Incubation != null &&
                                                      x.Status == TokenStatus.Active).ToListAsync(cancellationToken);

            switch (request.Status)
            {
            case "not_started":
                tokenList = tokenList.Where(x => (x.Incubation.Begin_Time ?? DateTime.MinValue) > DateTime.Now).ToList();
                break;

            case "in_progress":
                tokenList = tokenList.Where(x => (x.Incubation.Begin_Time ?? DateTime.MinValue) < DateTime.Now && x.Incubation.DeadLine > DateTime.Now).ToList();
                break;

            case "over":
                tokenList = tokenList.Where(x => x.Incubation.DeadLine < DateTime.Now).ToList();
                break;
            }

            switch (request.Ranking)
            {
            case "latest":
                tokenList = tokenList.OrderByDescending(x => (x.Incubation.Begin_Time ?? DateTime.MinValue));
                break;

            case "money":
                tokenList = tokenList.OrderByDescending(x => dbIncubations.FirstOrDefault(s => s.Id == x.Id)?.Raised ?? 0);
                break;
            }

            projectManifests.Total = tokenList.Count();

            tokenList = tokenList.Skip(request.Skip).Take(request.Take);

            foreach (var x in tokenList)
            {
                projectManifests.IncubatorList.Add(new GetIncubatorListResponse
                {
                    Id            = x.Id,
                    Introduction  = tokenRepository.GetTokenDescription(x.Id, request.Lang),
                    StartTime     = x.Incubation.Begin_Time ?? DateTime.MinValue,
                    DeadLine      = x.Incubation.DeadLine,
                    TargetAmount  = dbIncubations.FirstOrDefault(s => s.Id == x.Id)?.Raised ?? 0,
                    TargetCredits = x.Incubation.Goal
                });
            }
            return(ApiResultOld(projectManifests));
        }
Esempio n. 4
0
        public async Task <IActionResult> InfoAsync(
            string id,
            [FromQuery] string username,
            GetBaseRequest request,
            [FromServices] KyubeyContext db,
            [FromServices] TokenRepositoryFactory tokenRepositoryFactory,
            [FromServices] NodeApiInvoker nodeApiInvoker,
            [FromServices] ILogger logger,
            CancellationToken cancellationToken)
        {
            var dbToken = await db.Tokens.FirstOrDefaultAsync(x => x.Id == id && x.Status == TokenStatus.Active, cancellationToken);

            if (dbToken == null)
            {
                return(ApiResult(404, "not found this token"));
            }

            var tokenRepository = await tokenRepositoryFactory.CreateAsync(request.Lang);

            var tokenInfo      = tokenRepository.GetSingle(id);
            var supporterCount = await db.RaiseLogs.Where(x =>
                                                          (x.Timestamp > (tokenInfo.Incubation.Begin_Time ?? DateTime.MinValue) &&
                                                           x.Timestamp < tokenInfo.Incubation.DeadLine) &&
                                                          x.TokenId == dbToken.Id && !x.Account.StartsWith("eosio.")).Select(x => x.Account).Distinct().CountAsync();

            GetSymbolSupplyResponse symbolSupply = null;
            TokenContractPriceModel currentPrice = null;
            var eosBalance   = 0.0;
            var tokenBalance = 0.0;

            try
            {
                symbolSupply = await nodeApiInvoker.GetSymbolSupplyAsync(tokenInfo?.Basic?.Contract?.Transfer, id, cancellationToken);

                currentPrice = await tokenRepository.GetContractPriceAsync(id);

                eosBalance = await nodeApiInvoker.GetCurrencyBalanceAsync(username, "eosio.token", "EOS", cancellationToken);

                tokenBalance = await nodeApiInvoker.GetCurrencyBalanceAsync(username, tokenInfo?.Basic?.Contract?.Transfer, id, cancellationToken);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.ToString());
            }

            var whitepaperPath = tokenRepository.GetWhitePaper(id, request.Lang);

            var response = new GetIncubatorInfoResponse()
            {
                CurrentPrice   = currentPrice?.BuyPrice ?? 0,
                EOSBalance     = (decimal)eosBalance,
                TokenBalance   = (decimal)tokenBalance,
                Contract       = tokenInfo.Basic?.Contract?.Pricing ?? tokenInfo.Basic?.Contract?.Transfer,
                BuyMemo        = tokenInfo.Basic?.Contract_Exchange_Info?.Buy_Memo,
                CurrentRaised  = dbToken.Raised,
                IsFavorite     = false,
                Protocol       = tokenInfo.Basic?.Protocol,
                RemainingDay   = tokenInfo?.Incubation?.DeadLine == null ? -999 : Math.Max((tokenInfo.Incubation.DeadLine - DateTime.Now).Days, 0),
                BeginTime      = tokenInfo?.Incubation.Begin_Time,
                DeadLine       = tokenInfo?.Incubation.DeadLine ?? DateTime.MaxValue,
                SupporterCount = supporterCount,
                Target         = tokenInfo?.Incubation?.Goal ?? 0,
                TotalSupply    = (decimal)(symbolSupply?.MaxSupply ?? 0),
                WhitePaper     = whitepaperPath == null ? null : "/token_assets/" + whitepaperPath
            };

            return(ApiResult(response));
        }
Esempio n. 5
0
        public async Task <IActionResult> GetWalletAsync(string lang, string account, [FromServices] KyubeyContext db, [FromServices] TokenRepositoryFactory tokenRepositoryFactory, [FromServices] ILogger logger, [FromServices] NodeApiInvoker nodeApiInvoker, CancellationToken cancellationToken)
        {
            var tokenRespository = await tokenRepositoryFactory.CreateAsync(lang);

            var tokensCurrentPrice = await db.MatchReceipts.OrderByDescending(x => x.Time).GroupBy(x => x.TokenId).Select(g => new
            {
                TokenId = g.Key,
                Price   = g.FirstOrDefault().UnitPrice
            }).ToListAsync(cancellationToken);

            var buyList = await db.DexBuyOrders
                          .Where(x => x.Account == account)
                          .GroupBy(x => x.TokenId)
                          .Select(x => new
            {
                TokenId   = x.Key,
                FreezeEOS = x.Sum(s => s.Bid)
            }).ToListAsync(cancellationToken);

            var sellList = await db.DexSellOrders
                           .Where(x => x.Account == account)
                           .GroupBy(x => x.TokenId)
                           .Select(x => new
            {
                TokenId     = x.Key,
                FreezeToken = x.Sum(s => s.Ask)
            }).ToListAsync(cancellationToken);

            var matchTokens = await db.MatchReceipts
                              .Where(x => x.Time >= DateTime.Now.AddMonths(-3) &&
                                     (x.Asker == account || x.Bidder == account))
                              .Select(x => x.TokenId).Distinct().ToListAsync(cancellationToken);

            var tokens = buyList.Select(x => x.TokenId).Concat(sellList.Select(x => x.TokenId)).Concat(matchTokens).Distinct().ToList();

            var responseData = new List <GetWalletResponse>();

            responseData.Add(new GetWalletResponse()
            {
                IconSrc   = "/img/eos.png",
                Freeze    = buyList.Sum(x => x.FreezeEOS),
                Symbol    = "EOS",
                UnitPrice = 1,
                Valid     = nodeApiInvoker.GetCurrencyBalanceAsync(account, "eosio.token", "EOS", cancellationToken).Result
            });

            tokens.ForEach(x =>
            {
                var currentTokenBalance = 0.0;
                try
                {
                    var tokenInfo = tokenRespository.GetSingle(x);
                    if (tokenInfo != null)
                    {
                        currentTokenBalance = nodeApiInvoker.GetCurrencyBalanceAsync(account, tokenInfo?.Basic?.Contract?.Transfer, x, cancellationToken).Result;
                    }
                }
                catch (Newtonsoft.Json.JsonSerializationException ex)
                {
                    logger.LogError(ex.ToString());
                }
                finally
                {
                    responseData.Add(new GetWalletResponse()
                    {
                        IconSrc   = $"/token_assets/{x}/icon.png",
                        Valid     = currentTokenBalance,
                        Symbol    = x,
                        Freeze    = sellList.FirstOrDefault(s => s.TokenId == x)?.FreezeToken ?? 0,
                        UnitPrice = tokensCurrentPrice.FirstOrDefault(s => s.TokenId == x)?.Price ?? 0
                    });
                }
            });

            return(ApiResult(responseData));
        }
        public void GetRaised(KyubeyContext db, ILogger logger, NodeApiInvoker nodeApiInvoker, TokenRepositoryFactory tokenRepositoryFactory)
        {
            try
            {
                var tokenRepository = tokenRepositoryFactory.CreateAsync("en").Result;
                foreach (var x in db.Tokens
                         .Where(x => x.HasIncubation && x.HasContractExchange)
                         .ToList())
                {
                    var token = tokenRepository.GetSingle(x.Id);

                    if (DateTime.UtcNow < TimeZoneInfo.ConvertTimeToUtc(token.Incubation.Begin_Time ?? DateTime.MinValue))
                    {
                        continue;
                    }

                    if (DateTime.UtcNow > TimeZoneInfo.ConvertTimeToUtc(token.Incubation.DeadLine))
                    {
                        continue;
                    }

                    var depot = token.Basic.Contract.Depot ?? token.Basic.Contract.Pricing ?? token.Basic.Contract.Transfer;

                    if (string.IsNullOrWhiteSpace(depot) || token.Basic.Contract_Exchange_Info == null)
                    {
                        continue;
                    }

                    var seq = GetOrCreateRaisedSeq(token.Id, db);
                    logger.LogInfo($"Current incubator {token.Id} seq is " + seq);

                    var ret = nodeApiInvoker.GetActionsAsync(depot, seq).Result;
                    if (ret.actions.Count() == 0)
                    {
                        logger.LogInfo($"No new action in incubator {token.Id}");
                    }

                    if (ret.actions != null)
                    {
                        foreach (var act in ret.actions)
                        {
                            try
                            {
                                logger.LogInfo($"Handling incubator {token.Id} action log pos={act.account_action_seq}, act={act.action_trace.act.name}");

                                switch (act.action_trace.act.name)
                                {
                                case "transfer":
                                {
                                    var transferData = act.action_trace.act.data;

                                    if ((string)transferData.memo == token.Basic.Contract_Exchange_Info.Buy_Memo &&
                                        ((string)transferData.quantity).GetTokenAssetType() == "EOS")
                                    {
                                        var quantity = ((string)transferData.quantity).GetTokenAssetValue();
                                        HandleRaiseLogAsync(db, (int)act.account_action_seq, token.Id, depot, (string)transferData.from, (string)transferData.to, quantity, act.action_trace.block_time).Wait();
                                        HandleRaiseCountAsync(db, token.Id, TimeZoneInfo.ConvertTimeToUtc(token.Incubation.Begin_Time ?? DateTime.MinValue), TimeZoneInfo.ConvertTimeToUtc(token.Incubation.DeadLine)).Wait();
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                break;

                                default:
                                    continue;
                                }
                            }
                            catch (Exception ex)
                            {
                                logger.LogError($"incubator token: {token.Id} req: {seq} error: {token.Id} {seq} {ex.ToString()}");
                            }
                        }
                    }

                    seq += ret.actions.Count();
                    UpdateRaisedSeq(token.Id, seq, db);
                }
            }
            catch (Exception e)
            {
                logger.LogError("Sync Exception:" + JsonConvert.SerializeObject(e));
            }
        }
Esempio n. 7
0
        public async Task <IActionResult> TokenDetails(
            string id,
            GetBaseRequest request,
            [FromServices] KyubeyContext db,
            [FromServices] TokenRepositoryFactory tokenRepositoryFactory,
            [FromServices] NodeApiInvoker nodeApiInvoker,
            [FromServices] ILogger logger,
            CancellationToken cancellationToken
            )
        {
            var todayItem = await db.MatchReceipts.Where(x => x.TokenId == id && x.Time >= DateTime.Now.AddDays(-1)).OrderByDescending(x => x.Time).GroupBy(x => x.TokenId).Select(x => new
            {
                TokenId      = x.Key,
                CurrentPrice = x.FirstOrDefault().UnitPrice,
                MaxPrice     = x.Max(c => c.UnitPrice),
                MinPrice     = x.Min(c => c.UnitPrice),
                Volume       = x.Sum(c => c.IsSellMatch ? c.Bid : c.Ask)
            }).FirstOrDefaultAsync(cancellationToken);

            var lastItem = await db.MatchReceipts.Where(x => x.TokenId == id && x.Time <= DateTime.Now.AddDays(-1)).OrderByDescending(x => x.Time).GroupBy(x => x.TokenId).Select(x => new
            {
                TokenId      = x.Key,
                CurrentPrice = x.FirstOrDefault().UnitPrice
            }).FirstOrDefaultAsync(cancellationToken);

            var tokenRepository = await tokenRepositoryFactory.CreateAsync(request.Lang);

            var token = tokenRepository.GetSingle(id);

            GetSymbolSupplyResponse symbolSupply = null;

            try
            {
                symbolSupply = await nodeApiInvoker.GetSymbolSupplyAsync(token?.Basic?.Contract?.Transfer, id, cancellationToken);
            }
            catch (ArgumentNullException ex)
            {
                logger.LogError(ex.ToString());
            }

            var responseData = new GetTokenDetailResponse()
            {
                Symbol          = token.Id,
                ChangeRecentDay = (todayItem?.CurrentPrice == null || ((lastItem?.CurrentPrice ?? 0) == 0)) ? 0 :
                                  ((todayItem?.CurrentPrice ?? 0) / (lastItem?.CurrentPrice ?? 1) - 1),
                CurrentPrice      = todayItem?.CurrentPrice ?? lastItem?.CurrentPrice ?? 0,
                MaxPriceRecentDay = todayItem?.MaxPrice ?? 0,
                MinPriceRecentDay = todayItem?.MinPrice ?? 0,
                VolumeRecentDay   = todayItem?.Volume ?? 0,
                IsRecommend       = true,
                IconSrc           = $"/token_assets/{token.Id}/icon.png",
                Priority          = token.Priority,
                Description       = tokenRepository.GetTokenDescription(id, request.Lang),
                TotalSupply       = symbolSupply?.MaxSupply ?? 0,
                TotalCirculate    = symbolSupply?.Supply ?? 0,
                Contract          = new GetTokenResultContract()
                {
                    Depot    = token.Basic?.Contract?.Depot,
                    Pricing  = token.Basic?.Contract?.Pricing,
                    Transfer = token.Basic?.Contract?.Transfer
                },
                Website = token.Basic.Website
            };

            return(ApiResult(responseData));
        }