public async Task <IActionResult> LoginCallbackAsync([FromBody] PostSimpleWalletLoginRequest request,
                                                             [FromServices] NodeApiInvoker nodeApiInvoker,
                                                             [FromServices] EosSignatureValidator eosSignatureValidator,
                                                             [FromServices] IHubContext <SimpleWalletHub> hubContext,
                                                             [FromServices] ILogger logger,
                                                             CancellationToken cancellationToken)
        {
            logger.LogInfo(JsonConvert.SerializeObject(request));
            var accountInfo = await nodeApiInvoker.GetAccountAsync(request.Account, cancellationToken);

            var keys = accountInfo.Permissions.Select(x => x.RequiredAuth).SelectMany(x => x.Keys).Select(x => x.Key).ToList();
            var data = request.Timestamp + request.Account + request.UUID + request.Ref;

            //var verify = keys.Any(k => eosSignatureValidator.Verify(request.Sign, data, k).Result);
            //we will fix it later
            if (true)
            {
                await hubContext.Clients.Groups(request.UUID).SendAsync("simpleWalletLoginSucceeded", request.Account);

                return(Json(new PostSimpleWalletLoginResponse
                {
                    Code = 0
                }));
            }

            return(Json(new PostSimpleWalletLoginResponse
            {
                Code = 1,
                Error = "sign error"
            }));
        }
示例#2
0
        static void Main(string[] args)
        {
            var nodeAPI = new NodeApiInvoker();

            //var ct = nodeAPI.GetContractTransactionsAsync("TK6EDrMUfiRcso1uR7rNBVDjHRayKPQMoA").Result;
            //var t = nodeAPI.GetTransactionAsync("56d8123b79a05ff093bc5b55a86b13e11a0a907a31c2abcaea02561def53f50b").Result;
            //var t2 = nodeAPI.GetTransactionListAsync().Result;

            //var b = nodeAPI.GetBalanceAsync("TBVbLiQirADEdMsTL4WeTgNmMAgeoS16cF").Result;

            Console.ReadKey();

            var address         = "TPq7HbnLXuapW9oazU6Pqsrp1cduapZhj8";
            var privateKey      = "7b81cd82b28dbf9a6efb21de40fb263d83e286644ca04f910f486cb90a7a8357";
            var contractAddress = "TMWkPhsb1dnkAVNy8ej53KrFNGWy9BJrfu";
            var pwd             = "Passw0rd";
            var client          = new TronCliClient(@"C:\wallet-cli\", @"build\libs\wallet-cli.jar");

            //client.ImportWalletAsync(pwd, privateKey).Wait();
            client.LoginAsync("Passw0rd").Wait();
            client.TransferTRC20Async(address, contractAddress, 10).Wait();

            //client.SendCoinAsync(address, 1).Wait();
            //client.TransferAssetAsync(address, "REVOLUTION", 1).Wait();

            Console.ReadKey();
        }
示例#3
0
        public async Task <IActionResult> GetEOSActionsAsync([FromServices] NodeApiInvoker nodeApiInvoker, GetEOSActionsRequest request, CancellationToken cancellationToken)
        {
            var apiActions = await nodeApiInvoker.GetActionsAsync(request.Account, request.Skip, request.Take, cancellationToken);

            var responseData = apiActions.actions.Select(x => new GetEOSActionsResponse()
            {
                act  = x.action_trace.act,
                time = x.action_trace.block_time
            });

            return(ApiResult(responseData));
        }
示例#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));
        }
示例#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));
            }
        }
示例#7
0
        public async Task <IActionResult> GetEOSTableAsync([FromServices] NodeApiInvoker nodeApiInvoker, GetEOSTableRequest request, CancellationToken cancellationToken)
        {
            var responseData = await nodeApiInvoker.GetTableRowsAsync <object>(request.Code, request.Table, request.Account, request.Skip, request.Take, cancellationToken);

            return(ApiResult(responseData));
        }
示例#8
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));
        }
示例#9
0
        public async Task <IActionResult> GetAbiJsonToBinAsync(GetAbiJsonToBinRequest request, [FromServices] NodeApiInvoker nodeApiInvoker, CancellationToken cancellationToken)
        {
            var args       = JsonConvert.DeserializeObject(request.JsonArgs);
            var nodeResult = await nodeApiInvoker.GetAbiJsonToBinAsync(request.Code, request.Action, args);

            return(ApiResult(nodeResult.Binargs));
        }
示例#10
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));
        }