public async Task <ActionResult <FullUser> > CreateCornaddy([FromBody] CreateCornaddyRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.Id))
                {
                    throw new ArgumentNullException("id");
                }

                var platformId = BitcornUtils.GetPlatformId(request.Id);

                var user = await BitcornUtils.GetUserForPlatform(platformId, _dbContext).FirstOrDefaultAsync();

                if (user != null)
                {
                    var walletResponse = await WalletUtils.CreateCornaddy(_dbContext, user.UserWallet, _configuration);

                    if (!walletResponse.WalletAvailable)
                    {
                        return(StatusCode((int)HttpStatusCode.ServiceUnavailable));
                    }
                    return(BitcornUtils.GetFullUser(user, user.UserIdentity, user.UserWallet, user.UserStat));
                }
                else
                {
                    return(StatusCode(500));
                }
            }
            catch (Exception e)
            {
                await BITCORNLogger.LogError(_dbContext, e);

                throw e;
            }
        }
예제 #2
0
        public async Task <ActionResult <object> > GetUserSubscriptions([FromRoute] string platformId, [FromRoute] string subscriptionName = null)
        {
            if (string.IsNullOrEmpty(platformId))
            {
                throw new ArgumentException("platformId");
            }

            try
            {
                var id   = BitcornUtils.GetPlatformId(platformId);
                var user = await BitcornUtils.GetUserForPlatform(id, _dbContext).FirstOrDefaultAsync();

                if (user != null)
                {
                    var now = DateTime.Now;
                    var subscriptionsQuery = SubscriptionUtils.GetUserSubscriptions(_dbContext, user)
                                             .Join(_dbContext.Subscription,
                                                   (UserSubcriptionTierInfo info) => info.SubscriptionTier.SubscriptionId,
                                                   (Subscription sub) => sub.SubscriptionId,
                                                   (info, sub) => new
                    {
                        userInfo         = info,
                        subscriptionInfo = sub
                    }).Where(s => s.userInfo.UserSubscription.LastSubDate.Value.AddDays(s.subscriptionInfo.Duration) > now);

                    if (string.IsNullOrEmpty(subscriptionName) || subscriptionName == "*")
                    {
                        return(await subscriptionsQuery.Select(s => new
                        {
                            daysLeft = (s.userInfo.UserSubscription.LastSubDate.Value.AddDays(s.subscriptionInfo.Duration) - now).TotalDays,
                            tier = s.userInfo.SubscriptionTier.Tier,
                            name = s.subscriptionInfo.Name,
                            description = s.subscriptionInfo.Description,
                            lastSubDate = s.userInfo.UserSubscription.LastSubDate
                        }).ToArrayAsync());
                    }
                    else
                    {
                        return(await subscriptionsQuery.Where(q => q.subscriptionInfo.Name.ToLower() == subscriptionName.ToLower()).Select(s => new
                        {
                            daysLeft = (s.userInfo.UserSubscription.LastSubDate.Value.AddDays(s.subscriptionInfo.Duration) - now).TotalDays,
                            tier = s.userInfo.SubscriptionTier.Tier,
                            name = s.subscriptionInfo.Name,
                            description = s.subscriptionInfo.Description,
                            lastSubDate = s.userInfo.UserSubscription.LastSubDate
                        }).ToArrayAsync());
                    }
                }
                else
                {
                    return(StatusCode(404));
                }
            }
            catch (Exception e)
            {
                await BITCORNLogger.LogError(_dbContext, e, JsonConvert.SerializeObject(new { platformId, subscriptionName }));

                throw e;
            }
        }
예제 #3
0
        public async Task <ActionResult <SubscriptionResponse> > New([FromBody] SubRequest subRequest)
        {
            var platformId = BitcornUtils.GetPlatformId(subRequest.Id);
            var user       = await BitcornUtils.GetUserForPlatform(platformId, _dbContext).FirstOrDefaultAsync();

            if (user != null && UserLockCollection.Lock(user.UserId))
            {
                try
                {
                    subRequest.Platform = platformId.Platform;
                    var tx = await SubscriptionUtils.Subscribe(_dbContext, user, subRequest);

                    if (tx != null)
                    {
                        return(tx);
                    }
                }
                catch (Exception e)
                {
                    await BITCORNLogger.LogError(_dbContext, e, JsonConvert.SerializeObject(subRequest));

                    throw e;
                }
                finally
                {
                    UserLockCollection.Release(user.UserId);
                }
            }

            return(StatusCode((int)HttpStatusCode.BadRequest));
        }
예제 #4
0
        public async Task <ActionResult <PlatformSyncResponse> > Register([FromBody] RegistrationData registrationData)
        {
            if (registrationData == null)
            {
                throw new ArgumentNullException("registrationData");
            }
            if (registrationData.Auth0Id == null)
            {
                throw new ArgumentNullException("registrationData.Auth0Id");
            }
            if (registrationData.PlatformId == null)
            {
                throw new ArgumentNullException("registrationData.PlatformId");
            }
            if (this.GetCachedUser() != null)
            {
                throw new InvalidOperationException();
            }
            try
            {
                string auth0Id     = registrationData.Auth0Id;
                var    auth0DbUser = await _dbContext.Auth0Query(auth0Id).FirstOrDefaultAsync();

                var platformId = BitcornUtils.GetPlatformId(registrationData.PlatformId);

                //get all classes that inherit from SocialRegisteration, map to dictionary based on name
                //for example TwitchRegisteration will have key "twitch"
                var registerController = SupportedPlatform.AllocateController(_dbContext, platformId, _configuration);
                if (registerController != null)
                {
                    if (!string.IsNullOrEmpty(platformId.Id) && platformId.Id.ToLower() != "undefined")
                    {
                        var result = await registerController.SyncPlatform(registrationData, auth0DbUser, platformId, auth0Id);

                        if (result != null)
                        {
                            //claim transactions etc..
                            await registerController.OnSyncSuccess(result.SocialCreationTime, platformId);
                        }

                        return(result);
                    }
                    else
                    {
                        return(registerController.GetSyncOutput(auth0DbUser?.CreationTime, auth0DbUser, false));
                    }
                }
                else
                {
                    return(StatusCode((int)HttpStatusCode.BadRequest));
                }
            }
            catch (Exception e)
            {
                throw new Exception($"registration failed for {JsonConvert.SerializeObject(registrationData)}");
            }
            throw new Exception("HOW THE F**K DID YOU GET HERE");
        }
        public async Task <object> Withdraw([FromBody] WithdrawRequest request)
        {
            try
            {
                var platformId = BitcornUtils.GetPlatformId(request.Id);
                var user       = await BitcornUtils.GetUserForPlatform(platformId, _dbContext).FirstOrDefaultAsync();

                var response = new Dictionary <string, object>();
                if (user != null)
                {
                    var withdrawResult = await WalletUtils.Withdraw(_dbContext, _configuration, user, request.CornAddy, request.Amount, platformId.Platform);

                    response.Add("usererror", withdrawResult.UserError);
                    response.Add("walletavailable", withdrawResult.WalletAvailable);
                    response.Add("txid", withdrawResult.WalletObject);
                    if (request.Columns.Length > 0)
                    {
                        var columns = await UserReflection.GetColumns(_dbContext, request.Columns, new int[] { user.UserId });

                        if (columns.Count > 0)
                        {
                            foreach (var item in columns.First().Value)
                            {
                                response.Add(item.Key, item.Value);
                            }
                        }
                    }
                    if (withdrawResult.WalletObject != null && request.Amount > 100000)
                    {
                        await BitcornUtils.TxTracking(_configuration, new
                        {
                            txid            = withdrawResult.WalletObject,
                            time            = DateTime.Now,
                            method          = "withdraw",
                            platform        = platformId.Platform,
                            amount          = request.Amount,
                            userid          = user.UserId,
                            twitchUsername  = user.UserIdentity.TwitchUsername,
                            discordUsername = user.UserIdentity.DiscordUsername,
                            cornaddy        = request.CornAddy,
                        });
                    }
                }
                return(response);
            }
            catch (Exception e)
            {
                await BITCORNLogger.LogError(_dbContext, e);

                throw e;
            }
        }
예제 #6
0
        public async Task <IActionResult> Delete([FromBody] RegistrationData registrationData)
        {
            var platformId   = BitcornUtils.GetPlatformId(registrationData.PlatformId);
            var userIdentity = await BitcornUtils.GetUserIdentityForPlatform(platformId, _dbContext);

            if (registrationData.Auth0Id == userIdentity.Auth0Id)
            {
                await BitcornUtils.DeleteIdForPlatform(userIdentity, platformId, _dbContext);

                return(Ok());
            }
            throw new Exception("Auth0Id did not match the Auth0Id in the database for this user");
        }
        public async Task <HttpStatusCode> Post([FromBody] ReferralUpload referralUpload)
        {
            var platformId = BitcornUtils.GetPlatformId(referralUpload.UserId);
            var user       = await BitcornUtils.GetUserForPlatform(platformId, _dbContext).FirstOrDefaultAsync();

            if (user != null)
            {
                if (!_dbContext.Referrer.Any(r => r.UserId == user.UserId))
                {
                    try
                    {
                        if (referralUpload == null)
                        {
                            throw new ArgumentNullException(nameof(referralUpload));
                        }

                        var referrer = new Referrer();
                        referrer.Amount   = 10;
                        referrer.UserId   = user.UserId;
                        referrer.Tier     = 0;
                        referrer.YtdTotal = 0;
                        referrer.ETag     = referralUpload.W9.ETag;
                        referrer.Key      = referralUpload.W9.Key;
                        _dbContext.Referrer.Add(referrer);
                        await _dbContext.SaveAsync();

                        return(HttpStatusCode.OK);
                    }
                    catch (Exception e)
                    {
                        await BITCORNLogger.LogError(_dbContext, e, JsonConvert.SerializeObject(referralUpload));

                        throw;
                    }
                }

                var referrer1 = await _dbContext.Referrer.FirstOrDefaultAsync(r => r.UserId == user.UserId);

                referrer1.ETag = referralUpload.W9.ETag;
                referrer1.Key  = referralUpload.W9.Key;
                await _dbContext.SaveAsync();

                return(HttpStatusCode.OK);
            }
            return(HttpStatusCode.BadRequest);
        }
예제 #8
0
        public async Task <ActionResult <bool> > IsSubbed([FromRoute] string platformId, [FromRoute] string subscriptionName, [FromQuery] string subTier = null)
        {
            if (string.IsNullOrEmpty(platformId))
            {
                throw new ArgumentException("platformId");
            }
            if (string.IsNullOrEmpty(subscriptionName))
            {
                throw new ArgumentException("subscriptionName");
            }
            try
            {
                var id   = BitcornUtils.GetPlatformId(platformId);
                var user = await BitcornUtils.GetUserForPlatform(id, _dbContext).FirstOrDefaultAsync();

                if (user != null)
                {
                    int?tier = null;
                    if (!string.IsNullOrEmpty(subTier))
                    {
                        try
                        {
                            tier = int.Parse(subTier);
                        }
                        catch { }
                    }

                    return(await SubscriptionUtils.HasSubscribed(_dbContext, user, subscriptionName, tier));
                }
                else
                {
                    return(StatusCode(404));
                }
            }
            catch (Exception e)
            {
                await BITCORNLogger.LogError(_dbContext, e, JsonConvert.SerializeObject(new {
                    subTier,
                    platformId,
                    subscriptionName
                }));

                throw e;
            }
        }
예제 #9
0
        public async Task <ActionResult <object> > Ban([FromBody] BanUserRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.Sender))
            {
                throw new ArgumentNullException("Sender");
            }

            if (string.IsNullOrWhiteSpace(request.BanUser))
            {
                throw new ArgumentNullException("BanUser");
            }

            var senderPlatformId = BitcornUtils.GetPlatformId(request.Sender);
            var senderUser       = await BitcornUtils.GetUserForPlatform(senderPlatformId, _dbContext).FirstOrDefaultAsync();

            if (senderUser != null && senderUser.Level == "5000")
            {
                var banPlatformId = BitcornUtils.GetPlatformId(request.BanUser);
                var primaryKey    = -1;

                var banUser = await BitcornUtils.GetUserForPlatform(banPlatformId, _dbContext).FirstOrDefaultAsync();

                if (banUser != null)
                {
                    primaryKey       = banUser.UserId;
                    banUser.IsBanned = true;
                    _dbContext.Update(banUser);

                    await _dbContext.SaveAsync();
                }
                var users = await UserReflection.GetColumns(_dbContext, new string[] { "*" }, new[] { primaryKey });

                if (users.Count > 0)
                {
                    return(users.First());
                }
                return(null);
            }
            else
            {
                return(StatusCode((int)HttpStatusCode.Forbidden));
            }
        }
예제 #10
0
        public async Task <ActionResult <FullUser> > Post([FromRoute] string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentNullException("id");
            }

            var platformId = BitcornUtils.GetPlatformId(id);
            var user       = await BitcornUtils.GetUserForPlatform(platformId, _dbContext).FirstOrDefaultAsync();

            if (user != null)
            {
                return(BitcornUtils.GetFullUser(user, user.UserIdentity, user.UserWallet, user.UserStat));
            }
            else
            {
                return(StatusCode(404));
            }
        }
예제 #11
0
        public async Task <ActionResult <FullUser> > CreateCornaddy([FromBody] CreateCornaddyRequest request)
        {
            try
            {
                if (this.GetCachedUser() != null)
                {
                    throw new InvalidOperationException();
                }
                if (string.IsNullOrWhiteSpace(request.Id))
                {
                    throw new ArgumentNullException("id");
                }

                var platformId = BitcornUtils.GetPlatformId(request.Id);

                var user = await BitcornUtils.GetUserForPlatform(platformId, _dbContext).FirstOrDefaultAsync();

                if (user != null)
                {
                    var walletResponse = await WalletUtils.CreateCornaddy(_dbContext, user.UserWallet, _configuration);

                    if (!walletResponse.WalletAvailable)
                    {
                        user.UserWallet.CornAddy = "<no enabled wallets found>";
                        await _dbContext.SaveAsync();

                        return(StatusCode(200));
                        //return StatusCode((int)HttpStatusCode.ServiceUnavailable);
                    }
                    return(BitcornUtils.GetFullUser(user, user.UserIdentity, user.UserWallet, user.UserStat));
                }
                else
                {
                    return(StatusCode(500));
                }
            }
            catch (Exception e)
            {
                await BITCORNLogger.LogError(_dbContext, e, JsonConvert.SerializeObject(request));

                throw e;
            }
        }
        public async Task <IActionResult> Delete([FromBody] RegistrationData registrationData)
        {
            if (this.GetCachedUser() != null)
            {
                throw new InvalidOperationException();
            }
            var platformId   = BitcornUtils.GetPlatformId(registrationData.PlatformId);
            var userIdentity = await BitcornUtils.GetUserIdentityForPlatform(platformId, _dbContext);

            if (userIdentity == null)
            {
                return(StatusCode(200));
            }
            if (registrationData.Auth0Id == userIdentity.Auth0Id)
            {
                await BitcornUtils.DeleteIdForPlatform(userIdentity, platformId, _dbContext);

                return(Ok());
            }
            throw new Exception("Auth0Id did not match the Auth0Id in the database for this user");
        }
예제 #13
0
        public async Task <ActionResult <object> > Get([FromRoute] string platform, [FromRoute] string id)
        {
            try
            {
                var platformId = BitcornUtils.GetPlatformId(id);
                //join wallet in dbContext.UserWallet on identity.UserId equals wallet.UserId

                /*var userQuery = BitcornUtils.GetUserForPlatform(platformId, _dbContext).Join(_dbContext.UserAvatar,
                 *  (User user) => user.UserId,
                 *  (UserAvatar avatar) => avatar.UserId, (us, av) => new
                 *  {
                 *      avatar = av,
                 *      user = us
                 *  });
                 * var userData = await userQuery.FirstOrDefaultAsync();*/
                var user = await BitcornUtils.GetUserForPlatform(platformId, _dbContext)
                           .FirstOrDefaultAsync();

                if (user != null)
                {
                    return(await GameUtils.GetAvatar(_dbContext, user, platform));
                }
                throw new NotImplementedException();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw e;
            }

            /*
             *
             * User user = null;
             * if ((user = this.GetCachedUser()) == null)
             *  return StatusCode(404);*/
            //return BitcornUtils.GetFullUser(user, user.UserIdentity, user.UserWallet, user.UserStat);
        }
        public async Task <UserWallet> Wallet([FromRoute] string id)
        {
            var platformId = BitcornUtils.GetPlatformId(id);
            var user       = await BitcornUtils.GetUserForPlatform(platformId, _dbContext).FirstOrDefaultAsync();

            if (user != null)
            {
                var userWallet = user.UserWallet;
                if (!UserLockCollection.Lock(userWallet.UserId))
                {
                    return(userWallet);
                }
                try
                {
                    var referralId = _dbContext.UserReferral.FirstOrDefault(r => r.UserId == userWallet.UserId)?.ReferralId;
                    if (referralId != 0 && referralId != null)
                    {
                        var userReferral = await _dbContext.UserReferral.FirstOrDefaultAsync(r => r.UserId == userWallet.UserId);

                        var referrer = await _dbContext.Referrer.FirstOrDefaultAsync(r => r.ReferralId == userReferral.ReferralId);

                        var referrerUser = await _dbContext.JoinUserModels().FirstOrDefaultAsync(w => w.UserId == referrer.UserId);

                        var referrerStat = await _dbContext.UserStat.FirstOrDefaultAsync(s => s.UserId == referrer.UserId);

                        await ReferralUtils.BonusPayout(_dbContext, userReferral, referrer, user, referrerUser, referrerStat);

                        if (referrer != null &&
                            userReferral != null &&
                            userReferral.MinimumBalanceDate == null &&
                            userWallet.Balance >= MIN_BALANCE_QUEST_AMOUNT)
                        {
                            if (referrer.YtdTotal < 600 || (referrer.ETag != null && referrer.Key != null))
                            {
                                var referralPayoutTotal = await ReferralUtils.TotalReward(_dbContext, referrer);

                                var miniumBalanceRewardUser = await TxUtils.SendFromBitcornhub(user, referrer.Amount, "BITCORNFarms", "Minium balance reward", _dbContext);

                                var miniumBalanceReward = await TxUtils.SendFromBitcornhub(referrerUser, referralPayoutTotal, "BITCORNFarms", "Minium balance reward", _dbContext);

                                if (miniumBalanceReward && miniumBalanceRewardUser)
                                {
                                    referrerStat.TotalReferralRewardsCorn += referralPayoutTotal;
                                    referrerStat.TotalReferralRewardsUsdt += (referralPayoutTotal * (await ProbitApi.GetCornPriceAsync(_dbContext)));
                                    userReferral.MinimumBalanceDate        = DateTime.Now;
                                    await ReferralUtils.UpdateYtdTotal(_dbContext, referrer, referralPayoutTotal);

                                    await ReferralUtils.LogReferralTx(_dbContext, user.UserId, referrer.Amount, "Recruit minimum balance Reward");

                                    await ReferralUtils.LogReferralTx(_dbContext, referrerUser.UserId, referralPayoutTotal, "Minimum balance Reward");

                                    await ReferralUtils.BonusPayout(_dbContext, userReferral, referrer, user, referrerUser, referrerStat);
                                }
                            }
                        }
                        await _dbContext.SaveAsync();
                    }
                }
                catch (Exception e)
                {
                    await BITCORNLogger.LogError(_dbContext, e, id);
                }
                finally
                {
                    UserLockCollection.Release(userWallet.UserId);
                }
                return(user.UserWallet);
            }
            else
            {
                return(null);
            }
        }
예제 #15
0
        public async Task <ActionResult <TxReceipt[]> > Tipcorn([FromBody] TipRequest tipRequest)
        {
            if (tipRequest == null)
            {
                throw new ArgumentNullException();
            }
            if (tipRequest.From == null)
            {
                throw new ArgumentNullException();
            }
            if (tipRequest.To == null)
            {
                throw new ArgumentNullException();
            }
            if (tipRequest.To == tipRequest.From)
            {
                return(StatusCode((int)HttpStatusCode.BadRequest));
            }
            if (tipRequest.Amount <= 0)
            {
                return(StatusCode((int)HttpStatusCode.BadRequest));
            }

            try
            {
                var processInfo = await TxUtils.ProcessRequest(tipRequest, _dbContext);

                var transactions = processInfo.Transactions;
                if (transactions != null && transactions.Length > 0)
                {
                    StringBuilder sql = new StringBuilder();
                    if (processInfo.WriteTransactionOutput(sql))
                    {
                        var receipt = transactions[0];
                        if (receipt.Tx != null)
                        {
                            var    to        = receipt.To.User.UserStat;
                            var    from      = receipt.From.User.UserStat;
                            var    amount    = tipRequest.Amount;
                            string table     = nameof(UserStat);
                            var    pk        = nameof(UserStat.UserId);
                            var    fromStats = new List <ColumnValuePair>();

                            fromStats.Add(new ColumnValuePair(nameof(UserStat.Tip), 1));
                            fromStats.Add(new ColumnValuePair(nameof(UserStat.TipTotal), amount));

                            sql.Append(TxUtils.ModifyNumbers(table, fromStats, '+', pk, from.UserId));

                            var toStats = new List <ColumnValuePair>();
                            toStats.Add(new ColumnValuePair(nameof(UserStat.Tipped), 1));
                            toStats.Add(new ColumnValuePair(nameof(UserStat.TippedTotal), amount));

                            sql.Append(TxUtils.ModifyNumbers(table, toStats, '+', pk, to.UserId));

                            sql.Append(TxUtils.UpdateNumberIfTop(table, nameof(UserStat.TopTip), amount, pk, from.UserId));
                            sql.Append(TxUtils.UpdateNumberIfTop(table, nameof(UserStat.TopTipped), amount, pk, to.UserId));

                            await _dbContext.Database.ExecuteSqlRawAsync(sql.ToString());

                            await _dbContext.SaveAsync(IsolationLevel.RepeatableRead);
                        }
                    }
                    else
                    {
                        if (processInfo.From != null && !processInfo.From.IsBanned && processInfo.Transactions[0].To == null)
                        {
                            if (processInfo.From.UserWallet.Balance >= tipRequest.Amount)
                            {
                                var unclaimed = new UnclaimedTx();
                                unclaimed.TxType             = ((ITxRequest)tipRequest).TxType;
                                unclaimed.Platform           = tipRequest.Platform;
                                unclaimed.ReceiverPlatformId = BitcornUtils.GetPlatformId(tipRequest.To).Id;
                                unclaimed.Amount             = tipRequest.Amount;
                                unclaimed.Timestamp          = DateTime.Now;
                                unclaimed.SenderUserId       = processInfo.From.UserId;
                                unclaimed.Expiration         = DateTime.Now.AddMinutes(TimeToClaimTipMinutes);
                                unclaimed.Claimed            = false;
                                unclaimed.Refunded           = false;

                                _dbContext.UnclaimedTx.Add(unclaimed);
                                await _dbContext.Database.ExecuteSqlRawAsync(TxUtils.ModifyNumber(nameof(UserWallet), nameof(UserWallet.Balance), tipRequest.Amount, '-', nameof(UserWallet.UserId), processInfo.From.UserId));

                                await _dbContext.SaveAsync();
                            }
                        }
                    }
                    await TxUtils.AppendTxs(transactions, _dbContext, tipRequest.Columns);
                }
                return(transactions);
            }
            catch (Exception e)
            {
                await BITCORNLogger.LogError(_dbContext, e);

                throw e;
            }
        }
        public async Task <UserIdentity> Auth0([FromRoute] string id)
        {
            var platformId = BitcornUtils.GetPlatformId(id);

            return(await BitcornUtils.GetUserForPlatform(platformId, _dbContext).Select(u => u.UserIdentity).FirstOrDefaultAsync());
        }
예제 #17
0
        public async Task <FullUser> Register([FromBody] RegistrationData registrationData)
        {
            if (registrationData == null)
            {
                throw new ArgumentNullException("registrationData");
            }
            if (registrationData.Auth0Id == null)
            {
                throw new ArgumentNullException("registrationData.Auth0Id");
            }
            if (registrationData.PlatformId == null)
            {
                throw new ArgumentNullException("registrationData.PlatformId");
            }

            try
            {
                string auth0Id     = registrationData.Auth0Id;
                var    auth0DbUser = await _dbContext.Auth0Query(auth0Id).FirstOrDefaultAsync();

                var platformId = BitcornUtils.GetPlatformId(registrationData.PlatformId);
                switch (platformId.Platform)
                {
                case "twitch":
                    var twitchUser = await TwitchKraken.GetTwitchUser(platformId.Id);

                    var twitchDbUser = await _dbContext.TwitchQuery(platformId.Id).FirstOrDefaultAsync();

                    if (twitchDbUser != null && twitchDbUser.UserIdentity.Auth0Id == null)
                    {
                        //   _dbContext.UserIdentity.Remove(auth0DbUser);
                        auth0DbUser.UserIdentity.TwitchId = twitchDbUser.UserIdentity.TwitchId;
                        CopyIdentity(auth0DbUser.UserIdentity, twitchDbUser.UserIdentity);
                        twitchDbUser.UserIdentity.TwitchUsername = twitchUser.name;
                        twitchDbUser.UserIdentity.Auth0Id        = auth0Id;
                        twitchDbUser.UserIdentity.Auth0Nickname  = auth0DbUser.UserIdentity.Auth0Nickname;

                        await MigrateUser(auth0DbUser, twitchDbUser);


                        await TxUtils.TryClaimTx(platformId, null, _dbContext);

                        return(GetFullUser(twitchDbUser));
                    }
                    else if (twitchDbUser == null && auth0DbUser != null)
                    {
                        auth0DbUser.UserIdentity.TwitchId       = platformId.Id;
                        auth0DbUser.UserIdentity.TwitchUsername = twitchUser.name;
                        await _dbContext.SaveAsync();

                        await TxUtils.TryClaimTx(platformId, null, _dbContext);

                        return(GetFullUser(auth0DbUser));
                    }
                    else if (twitchDbUser != null)
                    {
                        var e = new Exception($"A login id already exists for this twitch id {platformId.Id}");
                        await BITCORNLogger.LogError(_dbContext, e);

                        throw e;
                    }
                    else
                    {
                        var e = new Exception(
                            $"Failed to register twitch {platformId.Id} {auth0Id}");
                        await BITCORNLogger.LogError(_dbContext, e);

                        throw e;
                    }

                case "discord":
                    try
                    {
                        var discordToken = DiscordApi.GetDiscordBotToken(_configuration);
                        var discordUser  = await DiscordApi.GetDiscordUser(discordToken, platformId.Id);

                        var discordDbUser = await _dbContext.DiscordQuery(platformId.Id).FirstOrDefaultAsync();

                        if (discordDbUser != null && discordDbUser.UserIdentity.Auth0Id == null)
                        {
                            //_dbContext.UserIdentity.Remove(auth0DbUser);
                            //await _dbContext.SaveAsync();
                            auth0DbUser.UserIdentity.DiscordId = discordDbUser.UserIdentity.DiscordId;
                            CopyIdentity(auth0DbUser.UserIdentity, discordDbUser.UserIdentity);

                            discordDbUser.UserIdentity.DiscordUsername = DiscordApi.GetUsernameString(discordUser);
                            discordDbUser.UserIdentity.Auth0Id         = auth0Id;
                            discordDbUser.UserIdentity.Auth0Nickname   = auth0DbUser.UserIdentity.Auth0Nickname;
                            await MigrateUser(auth0DbUser, discordDbUser);

                            await TxUtils.TryClaimTx(platformId, null, _dbContext);

                            return(GetFullUser(discordDbUser));
                        }
                        else if (discordDbUser == null && auth0DbUser != null)
                        {
                            auth0DbUser.UserIdentity.DiscordId       = platformId.Id;
                            auth0DbUser.UserIdentity.DiscordUsername = DiscordApi.GetUsernameString(discordUser);

                            await _dbContext.SaveAsync();

                            await TxUtils.TryClaimTx(platformId, null, _dbContext);

                            return(GetFullUser(auth0DbUser));
                        }
                        else if (discordDbUser?.UserIdentity.Auth0Id != null)
                        {
                            var e = new Exception($"A login id already exists for this discord id");
                            await BITCORNLogger.LogError(_dbContext, e, $"Auth0Id already exists for user {platformId.Id}");

                            throw e;
                        }
                        else
                        {
                            var e = new Exception($"Failed to register discord");
                            await BITCORNLogger.LogError(_dbContext, e, $"Failed to register discord id for user {platformId.Id} {auth0Id}");

                            throw e;
                        }
                    }
                    catch (Exception e)
                    {
                        await BITCORNLogger.LogError(_dbContext, e);

                        throw new Exception($"Failed to add user's discord");
                    }

                    throw new Exception($"HOW THE F**K DID YOU GET HERE");

                case "twitter":
                    try
                    {
                        var twitterUser = await TwitterApi.GetTwitterUser(_configuration, platformId.Id);

                        var twitterDbUser = await _dbContext.TwitterQuery(platformId.Id).FirstOrDefaultAsync();

                        if (twitterDbUser != null && twitterDbUser.UserIdentity.Auth0Id == null)
                        {
                            auth0DbUser.UserIdentity.TwitterId = twitterDbUser.UserIdentity.TwitterId;
                            //_dbContext.UserIdentity.Remove(auth0DbUser);
                            CopyIdentity(auth0DbUser.UserIdentity, twitterDbUser.UserIdentity);
                            twitterDbUser.UserIdentity.Auth0Id         = auth0Id;
                            twitterDbUser.UserIdentity.TwitterUsername = twitterUser.Name;
                            twitterDbUser.UserIdentity.Auth0Nickname   = auth0DbUser.UserIdentity.Auth0Nickname;
                            await MigrateUser(auth0DbUser, twitterDbUser);

                            await TxUtils.TryClaimTx(platformId, null, _dbContext);

                            return(GetFullUser(twitterDbUser));
                        }
                        if (twitterDbUser == null && auth0DbUser != null)
                        {
                            auth0DbUser.UserIdentity.TwitterId       = platformId.Id;
                            auth0DbUser.UserIdentity.TwitterUsername = twitterUser.Name;
                            await _dbContext.SaveAsync();

                            await TxUtils.TryClaimTx(platformId, null, _dbContext);

                            return(GetFullUser(auth0DbUser));
                        }
                        if (twitterDbUser?.UserIdentity.Auth0Id != null)
                        {
                            var e = new Exception($"Auth0Id already exists for user {platformId.Id}");
                            await BITCORNLogger.LogError(_dbContext, e);

                            throw e;
                        }
                        var ex = new Exception($"Failed to register twitter id for user {platformId.Id} {auth0Id}");
                        await BITCORNLogger.LogError(_dbContext, ex);

                        throw ex;
                    }
                    catch (Exception e)
                    {
                        await BITCORNLogger.LogError(_dbContext, e);

                        throw e;
                    }
                    throw new Exception($"HOW THE F**K DID YOU GET HERE");

                case "reddit":
                    try
                    {
                        var redditDbUser = await _dbContext.RedditQuery(platformId.Id).FirstOrDefaultAsync();

                        if (redditDbUser != null && redditDbUser.UserIdentity.Auth0Id == null)
                        {
                            auth0DbUser.UserIdentity.RedditId = redditDbUser.UserIdentity.RedditId;
                            CopyIdentity(auth0DbUser.UserIdentity, redditDbUser.UserIdentity);
                            //_dbContext.UserIdentity.Remove(auth0DbUser);
                            redditDbUser.UserIdentity.Auth0Id       = auth0Id;
                            redditDbUser.UserIdentity.Auth0Nickname = auth0DbUser.UserIdentity.Auth0Nickname;
                            await MigrateUser(auth0DbUser, redditDbUser);

                            await TxUtils.TryClaimTx(platformId, null, _dbContext);

                            return(GetFullUser(redditDbUser));
                        }
                        else if (redditDbUser == null && auth0DbUser != null)
                        {
                            auth0DbUser.UserIdentity.RedditId = platformId.Id;
                            await _dbContext.SaveAsync();

                            await TxUtils.TryClaimTx(platformId, null, _dbContext);

                            return(GetFullUser(auth0DbUser));
                        }
                        else if (redditDbUser?.UserIdentity.Auth0Id != null)
                        {
                            var e = new Exception($"Auth0Id already exists for user {platformId.Id}");
                            await BITCORNLogger.LogError(_dbContext, e);

                            throw e;
                        }
                        else
                        {
                            var e = new Exception($"Failed to register reddit id for user {platformId.Id} {platformId.Id}");
                            await BITCORNLogger.LogError(_dbContext, e);

                            throw e;
                        }
                    }
                    catch (Exception e)
                    {
                        await BITCORNLogger.LogError(_dbContext, e);

                        throw e;
                    }

                    throw new Exception($"HOW THE F**K DID YOU GET HERE");

                default:
                    throw new Exception("Invalid platform provided in the Id");
                }
            }
            catch (Exception e)
            {
                throw new Exception($"registration failed for {registrationData}");
            }
            throw new Exception("HOW THE F**K DID YOU GET HERE");
        }
예제 #18
0
        /// <summary>
        /// method to prepare a transaction, calling this method will not move fund immediately
        /// </summary>
        /// <param name="req">transaction request</param>
        /// <returns>transaction tracker output</returns>
        public static async Task <TxProcessInfo> ProcessRequest(ITxRequest req, BitcornContext dbContext)
        {
            if (req.Amount <= 0)
            {
                throw new ArgumentException("Amount");
            }
            //create tx process info that will be tracking this transaction
            var info = new TxProcessInfo();
            //create hashset of receivers
            var platformIds = new HashSet <PlatformId>();

            //set sender user
            info.From = req.FromUser;
            //array of recipient ids
            var toArray = req.To.ToArray();
            //calculate total amount of corn being sent
            var  totalAmountRequired = toArray.Length * req.Amount;
            bool canExecuteAll       = false;

            //check if sender has enough corn to execute all transactions
            if (info.From != null && info.From.UserWallet.Balance >= totalAmountRequired)
            {
                if (info.From.UserWallet.IsLocked != null && info.From.UserWallet.IsLocked == true)
                {
                    canExecuteAll = false;
                }
                else
                {
                    if (!(await ShouldLockWallet(dbContext, info.From, totalAmountRequired)))
                    {
                        canExecuteAll = true;
                    }
                }
            }

            //get platform ids of recipients
            foreach (var to in toArray)
            {
                var toPlatformId = BitcornUtils.GetPlatformId(to);
                if (!platformIds.Contains(toPlatformId))
                {
                    platformIds.Add(toPlatformId);
                }
            }
            var platformIdArray = platformIds.ToArray();
            //get recipients query
            var userQuery = BitcornUtils.GetUsersForPlatform(platformIdArray, dbContext).AsNoTracking();
            //convert into dictionary mapped by their platformid
            var users = await BitcornUtils.ToPlatformDictionary(platformIdArray, userQuery, dbContext);

            //create list for receipts
            var output = new List <TxReceipt>();
            //create group transaction id
            var txid = Guid.NewGuid().ToString();

            var sql = new StringBuilder();
            //get corn usdt price at this time
            var cornUsdtPrice = (await ProbitApi.GetCornPriceAsync(dbContext));

            foreach (var to in platformIdArray)
            {
                var receipt = new TxReceipt();
                //if sender is registered, assign it to the receipt
                if (info.From != null)
                {
                    receipt.From = new SelectableUser(info.From);
                }
                //if recipient is registered, assign it to the receipt
                if (users.TryGetValue(to.Id, out User user))
                {
                    receipt.To = new SelectableUser(user);
                    //if all transactions can be executed, attempt to validate this transaction
                    if (canExecuteAll)
                    {
                        //verifytx returns corntx if this transaction will be made
                        receipt.Tx = VerifyTx(info.From, user, cornUsdtPrice, req.Amount, req.Platform, req.TxType, txid);
                    }
                    //if this transaction will be made, log it into corntx table
                    if (receipt.Tx != null)
                    {
                        dbContext.CornTx.Add(receipt.Tx);
                    }
                }
                //add receipt to the output
                output.Add(receipt);
            }
            //set receipts to the transaction tracker
            info.Transactions = output.ToArray();
            return(info);
        }
예제 #19
0
        public static async Task <TxProcessInfo> ProcessRequest(ITxRequest req, BitcornContext dbContext)
        {
            if (req.Amount <= 0)
            {
                throw new ArgumentException("Amount");
            }

            var info        = new TxProcessInfo();
            var platformIds = new HashSet <PlatformId>();

            var fromPlatformId = BitcornUtils.GetPlatformId(req.From);

            var fromUser = await BitcornUtils.GetUserForPlatform(fromPlatformId, dbContext).AsNoTracking().FirstOrDefaultAsync();

            info.From = fromUser;

            var toArray = req.To.ToArray();

            var  totalAmountRequired = toArray.Length * req.Amount;
            bool canExecuteAll       = false;

            if (fromUser != null && fromUser.UserWallet.Balance >= totalAmountRequired)
            {
                canExecuteAll = true;
            }

            foreach (var to in toArray)
            {
                var toPlatformId = BitcornUtils.GetPlatformId(to);
                if (!platformIds.Contains(toPlatformId))
                {
                    platformIds.Add(toPlatformId);
                }
            }
            var platformIdArray = platformIds.ToArray();
            var userQuery       = BitcornUtils.GetUsersForPlatform(platformIdArray, dbContext).AsNoTracking();
            var users           = await BitcornUtils.ToPlatformDictionary(platformIdArray, userQuery, dbContext);

            var output = new List <TxReceipt>();
            var txid   = Guid.NewGuid().ToString();
            var sql    = new StringBuilder();

            foreach (var to in platformIdArray)
            {
                var receipt = new TxReceipt();
                if (fromUser != null)
                {
                    receipt.From = new SelectableUser(fromUser);
                }

                if (users.TryGetValue(to.Id, out User user))
                {
                    receipt.To = new SelectableUser(user);
                    if (canExecuteAll)
                    {
                        receipt.Tx = VerifyTx(fromUser, user, req.Amount, req.Platform, req.TxType, txid);
                    }
                    if (receipt.Tx != null)
                    {
                        dbContext.CornTx.Add(receipt.Tx);
                    }
                }
                output.Add(receipt);
            }

            info.Transactions = output.ToArray();
            return(info);
        }
예제 #20
0
        public async Task <ActionResult <object> > Withdraw([FromBody] WithdrawRequest request)
        {
            try
            {
                var platformId = BitcornUtils.GetPlatformId(request.Id);
                var user       = this.GetCachedUser();//await BitcornUtils.GetUserForPlatform(platformId, _dbContext).FirstOrDefaultAsync();

                var response = new Dictionary <string, object>();
                if (user != null)
                {
                    if (user.UserWallet.IsLocked != null && user.UserWallet.IsLocked.Value)
                    {
                        return(StatusCode(420));
                    }

                    //if (user.MFA)
                    {
                        if (user.UserWallet.Balance < 30_000_000)
                        {
                            var withdrawResult = await WalletUtils.Withdraw(_dbContext, _configuration, user, request.CornAddy, request.Amount, platformId.Platform);

                            response.Add("usererror", withdrawResult.UserError);
                            response.Add("walletavailable", withdrawResult.WalletAvailable);
                            response.Add("txid", withdrawResult.WalletObject);

                            if (withdrawResult.ErrorCode != null && withdrawResult.ErrorCode == Utils.Wallet.Models.WalletErrorCodes.RPC_WALLET_INSUFFICIENT_FUNDS)
                            {
                                await BitcornUtils.TxTracking(_configuration, new
                                {
                                    message = "Insufficient funds detected on wallet on withdraw, (this might be because of no mature utxos) address to deposit from cold reserve  = " +
                                              withdrawResult.DepositAddress
                                });
                            }

                            await FillColumns(response, request, user);

                            if (withdrawResult.WalletObject != null && request.Amount > 100000)
                            {
                                await BitcornUtils.TxTracking(_configuration, new
                                {
                                    txid            = withdrawResult.WalletObject,
                                    time            = DateTime.Now,
                                    method          = "withdraw",
                                    platform        = platformId.Platform,
                                    amount          = request.Amount,
                                    userid          = user.UserId,
                                    twitchUsername  = user.UserIdentity.TwitchUsername,
                                    discordUsername = user.UserIdentity.DiscordUsername,
                                    cornaddy        = request.CornAddy,
                                });
                            }
                        }
                        else
                        {
                            response.Add("usererror", false);
                            response.Add("walletavailable", false);
                            response.Add("txid", null);
                            await FillColumns(response, request, user);

                            await BitcornUtils.TxTracking(_configuration, new
                            {
                                message = "Withdraw cancelled, manual withdraw required.",
                                time    = DateTime.Now,

                                platform        = platformId.Platform,
                                amount          = request.Amount,
                                userid          = user.UserId,
                                twitchUsername  = user.UserIdentity.TwitchUsername,
                                discordUsername = user.UserIdentity.DiscordUsername,
                                cornaddy        = request.CornAddy,
                            });
                        }
                    }

                    /*
                     * else
                     * {
                     *  await FillColumns(response, request, user);
                     *  response.Add("usererror", false);
                     *  response.Add("walletavailable", false);
                     *  response.Add("txid", null);
                     * }*/
                }
                return(response);
            }
            catch (Exception e)
            {
                await BITCORNLogger.LogError(_dbContext, e, JsonConvert.SerializeObject(request));

                throw e;
            }
        }