public string ConfirmWithdrawal(ConversationMessage transactionMessage)
    {
        Money amount = transactionMessage.RepresentativeTransferAmount;

        //Lets validate
        //PayoutManager.ValidatePayout(User, amount);
        PayoutManager.CheckMaxPayout(PaymentProcessor.ViaRepresentative, User, amount);

        //Update payout proportions
        PaymentProportionsManager.MemberPaidOut(amount, PaymentProcessor.ViaRepresentative, User);

        History.AddCashout(User.Name, amount);

        User.MoneyCashout += amount;
        User.IsPhoneVerifiedBeforeCashout = false;
        User.CashoutsProceed++;
        User.Save();

        //Add paymentproof
        PaymentProof.Add(User.Id, amount, PaymentType.Manual, PaymentProcessor.ViaRepresentative);

        //Send message to the user
        Member RepresentativeUser = new Member(RepresentativeUserId);

        RepresentativeUser.SendMessage(User.Id, U6010.WITHDRAWALCONFIRMED);

        return(U6010.WITHDRAWALCONFIRMED);
    }
Ejemplo n.º 2
0
        public static void DepositOnLevel(InvestmentPlatformPlan platformPlan, int userPlanId, Member user)
        {
            if (!LevelsEnabled)
            {
                return;
            }

            var ticket = AddNewTicket(platformPlan, user.Id, userPlanId);

            //We want to give users money only on every second deposit
            if (ticket.TicketNumber % 2 == 0)
            {
                var targetTicket  = GetFirstUnpaidTicketFromLevel(ticket.Level);
                var targetUser    = new Member(targetTicket.UserId);
                var targetPP      = platformPlan.PaymentProcessor;
                var payoutManager = new PayoutManager(targetUser, targetTicket.LevelEarnings, targetPP.ToString(), false, 0, string.Empty);

                if (payoutManager.TryMakeInvestmentLevelsPayout())
                {
                    targetTicket.Status = TicketStatus.Finished;
                    targetTicket.Save();

                    var targetPlan = new InvestmentUsersPlans(targetTicket.UserPlanId);
                    targetPlan.Finish();
                }
            }
        }
Ejemplo n.º 3
0
        public async Task ProcessPaidRequest()
        {
            var message      = this.Context.Message;
            var stringSpaced = message.Content.Split(new char [] { ' ', '\n' }, 2);

            if (stringSpaced.Length != 2)
            {
                await message.Channel.SendMessageAsync("Invalid format of command, should be \"!paid player1,player2 or !paid player1\nplayer2\"");

                return;
            }
            var payoutTargetsString = stringSpaced[1];
            var payoutTargets       = payoutTargetsString.Split(',', '\n').Select(x => x.Trim()).ToArray();
            var mentionedUsersList  = message.MentionedUsers.ToList();
            var payoutManager       = new PayoutManager();
            var playerManager       = new PlayerManager();

            for (int idx = 0; idx < payoutTargets.Length; ++idx)
            {
                var currentTarget = payoutTargets[idx];
                if (string.IsNullOrWhiteSpace(currentTarget))
                {
                    continue;
                }

                await payoutManager.PayoutPlayer(currentTarget);

                await message.Channel.SendMessageAsync($"Payout complete for {await playerManager.GetDiscordMentionForCharacter(currentTarget)}.");
            }
        }
Ejemplo n.º 4
0
    public static void ValidatePayoutNotConnectedToAmount(Member user)
    {
        //Check the status
        if (user.Status == MemberStatus.VacationMode)
        {
            throw new MsgException(U4000.YOUAREINVACATIONMODE);
        }

        //Account verification
        if (AppSettings.Authentication.IsDocumentVerificationEnabled && user.VerificationStatus != VerificationStatus.Verified)
        {
            throw new MsgException(U5006.ACCOUNTNOTVERIFIED);
        }

        if (user.NumberOfPayoutsToday + 1 > user.Membership.MaxDailyPayouts)
        {
            throw new MsgException(string.Format(U6000.TOOMANYWITHDRAWSTODAY, user.Membership.MaxDailyPayouts));
        }

        //Payout Days
        if (!AppSettings.Representatives.RepresentativesIgnoreWitdrawalRules || !user.IsRepresentative())
        {
            PayoutManager.CheckPayoutsDays();
        }

        //Check negative balance
        if (user.IsAnyBalanceIsNegative())
        {
            throw new MsgException(U6012.NEGATIVEBALANCEWITHDRAWAL);
        }

        //Validate Credit Loans
        if (CreditLineManager.UserHasUnpaidLoans(user.Id))
        {
            throw new MsgException(U6008.REPAYCREDITLINETOWITHDRAW);
        }

        //Special Check amount of collected offers from different levels
        if (TitanFeatures.IsBobbyDonev && CPAOffer.CheckCollectedLevelsAmount(user.Name) < 20)
        {
            throw new MsgException(String.Format("You didn't collect enaugh CPA/GPT offers from different levels yet. You have already collected and confirmed {0} levels.", CPAOffer.CheckCollectedLevelsAmount(user.Name)));
        }

        //Special Check amount of collected offers from different levels
        if (TitanFeatures.IsBobbyDonev && user.CashoutsProceed > 0)
        {
            throw new MsgException("You already did one payout. You can't do more.");
        }

        //Check days restriction between each withdrawals
        var lastWidthdrawalDate = user.GetLastWithdrawalDate();

        if (lastWidthdrawalDate != null && lastWidthdrawalDate > AppSettings.ServerTime.AddDays(-user.Membership.BlockPayoutDays))
        {
            throw new MsgException(string.Format(U6013.TIMEBETWEENPAYOUTERROR, user.Membership.BlockPayoutDays));
        }
    }
Ejemplo n.º 5
0
        private static async Task Start()
        {
            // start share recorder
            shareRecorder = container.Resolve <ShareRecorder>();
            shareRecorder.Start(clusterConfig);

            // start API
            if (clusterConfig.Api == null || clusterConfig.Api.Enabled)
            {
                apiServer = container.Resolve <ApiServer>();
                apiServer.Start(clusterConfig);
            }

            // start payment processor
            if (clusterConfig.PaymentProcessing?.Enabled == true &&
                clusterConfig.Pools.Any(x => x.PaymentProcessing?.Enabled == true))
            {
                payoutManager = container.Resolve <PayoutManager>();
                payoutManager.Configure(clusterConfig);

                payoutManager.Start();
            }

            else
            {
                logger.Info("Payment processing is not enabled");
            }

            // start pool stats updater
            statsRecorder = container.Resolve <StatsRecorder>();
            statsRecorder.Configure(clusterConfig);
            statsRecorder.Start();

            // start pools
            await Task.WhenAll(clusterConfig.Pools.Where(x => x.Enabled).Select(async poolConfig =>
            {
                // resolve pool implementation
                var poolImpl = container.Resolve <IEnumerable <Meta <Lazy <IMiningPool, CoinMetadataAttribute> > > >()
                               .First(x => x.Value.Metadata.SupportedCoins.Contains(poolConfig.Coin.Type)).Value;

                // create and configure
                var pool = poolImpl.Value;
                pool.Configure(poolConfig, clusterConfig);

                // pre-start attachments
                shareRecorder.AttachPool(pool);
                statsRecorder.AttachPool(pool);

                await pool.StartAsync();

                // post-start attachments
                apiServer.AttachPool(pool);
            }));

            // keep running
            await Observable.Never <Unit>().ToTask();
        }
Ejemplo n.º 6
0
        public static void MarkAllRequestsAsPaid()
        {
            List <PayoutRequest> pendingRequests = TableHelper.GetListFromRawQuery <PayoutRequest>(GetPayoutRequestsSQLQuery());

            foreach (var request in pendingRequests)
            {
                PayoutManager.MarkAsPaid(request);
            }
        }
Ejemplo n.º 7
0
 // Use this for initialization
 void Start()
 {
     AllPlayers      = new List <PokerPlayer>();
     card_manager    = GetComponent <CardManager>();
     betting_manager = GetComponent <BettingManager>();
     payout_manager  = GetComponent <PayoutManager>();
     Debug.Log("Waiting for players to start...");
     game_state_text.text = "Game State: Waiting to start...";
 }
Ejemplo n.º 8
0
        private void ValidateWithdrawal(Member user, string userAddress, decimal amount, WithdrawalSourceBalance withdrawalSource)
        {
            if (!WithdrawalEnabled)
            {
                throw new MsgException("Withdrawal is currently disabled by the administrator");
            }

            if (CryptocurrencyApi.IsAdministratorAddress(userAddress, WithdrawalApiProcessor))
            {
                throw new MsgException("You can't withdraw to administrator-generated address.");
            }

            Money  amountInCorrectType = Money.Zero;
            string errorMessage        = String.Empty;

            //General validation
            PayoutManager.ValidatePayoutNotConnectedToAmount(user);

            //Amounts & Balances
            if (withdrawalSource == WithdrawalSourceBalance.MainBalance)
            {
                amountInCorrectType = new Money(amount);

                //Check the balance
                if (amountInCorrectType > user.MainBalance)
                {
                    throw new MsgException(L1.NOTENOUGHFUNDS);
                }

                PayoutManager.ValidatePayout(user, amountInCorrectType);
                PayoutManager.CheckMaxPayout(CryptocurrencyTypeHelper.ConvertToPaymentProcessor(CryptocurrencyType), user, amountInCorrectType);
            }
            else //Wallets
            {
                amountInCorrectType = new CryptocurrencyMoney(this.Type, amount);

                //Check the balance
                if (amountInCorrectType > user.GetCryptocurrencyBalance(CryptocurrencyType))
                {
                    throw new MsgException(string.Format(U6012.NOFUNDSINWALLET, CryptocurrencyType.ToString()));
                }
            }

            //Check MIN withdrawal
            if (amountInCorrectType < GetMinimumWithdrawalAmount(user, withdrawalSource))
            {
                throw new MsgException(U5003.WITHDRAWALMUSTBEHIGHER);
            }

            //Check MAX withdrawals
            if (amountInCorrectType > GetMaximumWithdrawalAmount(user, withdrawalSource, out errorMessage))
            {
                throw new MsgException(errorMessage);
            }
        }
Ejemplo n.º 9
0
    protected void SendWithdrawViaRepresentativeButtonConfirm_Click(object sender, EventArgs e)
    {
        RepresentativeErrorMessagePanel.Visible = false;
        try
        {
            string amount = Request.Form["price"].ToString();

            Money  Amount = Money.Parse(amount).FromMulticurrency();
            Member User   = Member.Current;

            //Anti-Injection Fix
            if (Amount <= new Money(0))
            {
                throw new MsgException(L1.ERROR);
            }

            if (string.IsNullOrEmpty(RepresentativeMessage.Text))
            {
                throw new MsgException(L1.REQ_TEXT);
            }

            //Lets validate
            PayoutManager.ValidatePayout(User, Amount);
            PayoutManager.CheckMaxPayout(PaymentProcessor.ViaRepresentative, User, Amount);

            string Message = InputChecker.HtmlEncode(RepresentativeMessage.Text, RepresentativeMessage.MaxLength, U5004.MESSAGE);

            var SelectedRepresentative = new Representative(Convert.ToInt32(AvaibleRepresentativeList.SelectedValue));

            if (ConversationMessage.CheckIfThisUserHavePendingActions(User.Id))
            {
                throw new MsgException(U6010.YOUHAVEPENDINGACTION);
            }

            //All OK, let's proceed
            RepresentativesTransferManager representativesTransferManager = new RepresentativesTransferManager(Member.CurrentId, SelectedRepresentative.UserId);
            representativesTransferManager.InvokeWithdrawal(Amount, Message);

            Response.Redirect("~/user/network/messenger.aspx");
        }
        catch (MsgException ex)
        {
            RepresentativeErrorMessagePanel.Visible = true;
            RepresentativeErrorMessage.Text         = ex.Message;
        }
        catch (Exception ex)
        {
            ErrorLogger.Log(ex);
            RepresentativeErrorMessagePanel.Visible = true;
            RepresentativeErrorMessage.Text         = ex.Message;
        }
    }
Ejemplo n.º 10
0
    protected void CashoutButtonConfirm_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            SuccMessagePanel.Visible     = false;
            ErrorMessagePanel.Visible    = false;
            CashoutButtonConfirm.Visible = false;

            try
            {
                //Parse amount
                Money Transferred;
                try
                {
                    Transferred = Money.Parse(AmountToCashoutTextBox.Text).FromMulticurrency();
                    Transferred = Money.Parse(Transferred.ToShortClearString());
                }
                catch (Exception ex)
                {
                    throw new MsgException(U2502.INVALIDMONEYFORMAT);
                }

                if (!AppSettings.Payments.WithdrawalEmailEnabled && AppSettings.Proxy.SMSType == ProxySMSType.EveryCashout)
                {
                    User.IsPhoneVerifiedBeforeCashout = true;
                    User.UnconfirmedSMSSent--;
                    User.Save();
                }

                //Lets process to cashout
                PayoutManager Manager = new PayoutManager(User, Transferred, RadioFrom.SelectedValue,
                                                          CustomPayoutProcessor.IsCustomPayoutProcessor(RadioFrom.SelectedValue), CustomPayoutProcessor.GetCustomPayoutProcessorId(RadioFrom.SelectedValue), Account.Text);

                SuccMessage.Text         = Manager.TryMakePayout();
                SuccMessagePanel.Visible = true;
            }
            catch (Exception ex)
            {
                ErrorMessagePanel.Visible = true;
                ErrorMessage.Text         = ex.Message;
            }
            finally
            {
                Account.Enabled = true;
                PIN.Enabled     = true;
                AmountToCashoutTextBox.Enabled       = true;
                CashoutButton.Visible                = true;
                ConfirmationCodePlaceHolder2.Visible = false;
                CashoutButtonConfirm.Visible         = false;
            }
        }
    }
Ejemplo n.º 11
0
        public Money GetMaximumWithdrawalAmount(Member user, WithdrawalSourceBalance withdrawalSource, out string errorMessage)
        {
            errorMessage = U6012.PAYOUTREQUESTTOOHIGH;

            if (withdrawalSource == WithdrawalSourceBalance.MainBalance)
            {
                return(PayoutManager.GetMaxPossiblePayout(CryptocurrencyTypeHelper.ConvertToPaymentProcessor(this.CryptocurrencyType), user, out errorMessage));
            }
            else //Wallet
            {
                return(user.GetCryptocurrencyBalance(this.Type)); //No limit
            }
        }
Ejemplo n.º 12
0
        private bool IsAutomaticWithdrawal(Member user, Money valueInMoney)
        {
            if (PayoutManager.IsManualCryptocurrencyPayout(user))
            {
                return(false);
            }

            if (valueInMoney > WithdrawalMaximumAutomaticAmount)
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 13
0
    /*==============================================================================*/
    /* 初期化処理																		*/
    /*==============================================================================*/
    void Start()
    {
        generateStructInstance();
        initRequest();
        initBingoMasuInfo();
        for (int masu = 0; masu < BINGO_MASU_MAX; masu++)
        {
            updateBingoMasuObjectDisplayState(masu);            //DisplayStateの初期化をGameObjectのsetActiveにも反映させる
        }
        initBingoTable();
        initNotifyStock();

        PayoutManagerInstance = GameObject.Find("Main Camera").GetComponent <PayoutManager>();
        CreditManagerInstance = GameObject.Find("Main Camera").GetComponent <CreditManager>();
        BallGeneratorInstance = GameObject.Find("BallEntrance").GetComponent <BallGenerator>();
    }
Ejemplo n.º 14
0
 public ExchangeService(IContextHolder contextHolder,
                        ITransferRequestRepository iTransferRequestRepository,
                        IConnectionFactory iConnectionFactory,
                        JsonSerializerSettings jsonSerializerSettings,
                        DaemonClientFactory daemonClientFactory,
                        PayoutManager payoutManager,
                        IJobManager jobManager)
 {
     _contextHolder = contextHolder;
     _iTransferRequestRepository = iTransferRequestRepository;
     _iConnectionFactory         = iConnectionFactory;
     _jsonSerializerSettings     = jsonSerializerSettings;
     _daemonClientFactory        = daemonClientFactory;
     _payoutManager = payoutManager;
     _jobManager    = jobManager;
 }
Ejemplo n.º 15
0
    // Start is called before the first frame update
    void Start()
    {
        CreditValueText = GameObject.Find("CreditValueText").GetComponent <Text>();
        PayoutValueText = GameObject.Find("PayoutValueText").GetComponent <Text>();
        GameOverCanvas  = GameObject.Find("GameOverCanvas");
        ContinueButton  = GameObject.Find("ContinueButton");
        Banner1         = GameObject.Find("Banner1");

        CreditManagerInstance      = GameObject.Find("Main Camera").GetComponent <CreditManager>();
        PayoutManagerInstance      = GameObject.Find("Main Camera").GetComponent <PayoutManager>();
        AdBannerControllerInstance = GameObject.Find("Banner1").GetComponent <AdBannerController>();

        CreditManagerInstance.InitCreditText();
        PayoutManagerInstance.InitPayoutText();

        InactivateGameOverCanvas();        //最初は非表示
    }
Ejemplo n.º 16
0
        private static async Task Start()
        {
            shareRecorder = container.Resolve <RewardRecorder>();
            shareRecorder.Start(clusterConfig);

            if (clusterConfig.Api == null || clusterConfig.Api.Enabled)
            {
                apiServer = container.Resolve <RestfulApiServer>();
                apiServer.Start(clusterConfig);
            }

            if (clusterConfig.PaymentProcessing?.Enabled == true &&
                clusterConfig.Pools.Any(x => x.PaymentProcessing?.Enabled == true))
            {
                payoutManager = container.Resolve <PayoutManager>();
                payoutManager.Configure(clusterConfig);

                payoutManager.Start();
            }

            else
            {
                logger.Info("Payment processing is not enabled");
            }


            statsRecorder = container.Resolve <StatsRecorder>();
            statsRecorder.Configure(clusterConfig);
            statsRecorder.Start();

            await Task.WhenAll(clusterConfig.Pools.Where(x => x.Enabled).Select(async poolConfig =>
            {
                var poolImpl = container.Resolve <IEnumerable <Meta <Lazy <IMiningPool, CoinMetadataAttribute> > > >()
                               .First(x => x.Value.Metadata.SupportedCoins.Contains(poolConfig.Coin.Type)).Value;

                var pool = poolImpl.Value;
                pool.Configure(poolConfig, clusterConfig);

                statsRecorder?.AttachPool(pool);

                await pool.StartAsync(cts.Token);
            }));

            await Observable.Never <Unit>().ToTask(cts.Token);
        }
Ejemplo n.º 17
0
        protected override ApiResultMessage HandleRequest(object args)
        {
            string  token          = ((JObject)args)["token"].ToString();
            int     pin            = Convert.ToInt32(((JObject)args)["pin"]);
            decimal amount         = Convert.ToDecimal(((JObject)args)["amount"]);
            string  processorValue = ((JObject)args)["processor"].ToString();

            int    userId = ApiAccessToken.ValidateAndGetUserId(token);
            Member User   = new Member(userId);

            User.ValidatePIN(pin.ToString());

            Money Amount = new Money(amount);

            Amount = Money.Parse(Amount.ToShortClearString());

            var userAccountAddress = String.Empty;

            try
            {
                var CustomProcessor = new CustomPayoutProcessor(int.Parse(processorValue));
                userAccountAddress = User.GetPaymentAddress(CustomProcessor.Id);
            }
            catch (Exception)
            {
                var selectedProcessor            = processorValue;
                PaymentProcessor targetprocessor = PaymentAccountDetails.GetFromStringType(selectedProcessor);
                userAccountAddress = User.GetPaymentAddress(targetprocessor);
            }

            //Lets process to cashout
            PayoutManager Manager = new PayoutManager(User, Amount, processorValue,
                                                      CustomPayoutProcessor.IsCustomPayoutProcessor(processorValue), CustomPayoutProcessor.GetCustomPayoutProcessorId(processorValue), userAccountAddress);

            string successMessage = Manager.TryMakePayout();

            return(new ApiResultMessage
            {
                success = true,
                message = successMessage,
                data = null
            });
        }
Ejemplo n.º 18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            IJobManager                jobManager                = new JobManager();
            IExchangeRateProvider      exchangeRateProvider      = new BitfinexExchangeRateProvider();
            IContextHolder             contextHolder             = new ContextHolder(Configuration, jsonSerializerSettings);
            DaemonClientFactory        daemonClientFactory       = new DaemonClientFactory(contextHolder, jsonSerializerSettings);
            IConnectionFactory         dbFactory                 = new PgConnectionFactory(contextHolder);
            ITransferRequestRepository transferRequestRepository = new TransferRequestRepository();
            ITransferRepository        transferRepository        = new TransferRepository();
            NotificationService        notificationService       = new NotificationService(contextHolder, jsonSerializerSettings);

            services.AddSingleton <IContextHolder>(contextHolder);
            services.AddSingleton <IExchangeRateProvider>(exchangeRateProvider);
            services.AddSingleton <IJobManager>(jobManager);
            services.AddSingleton <JsonSerializerSettings>(jsonSerializerSettings);
            services.AddSingleton <DaemonClientFactory>(daemonClientFactory);
            services.AddSingleton <IConnectionFactory>(dbFactory);
            services.AddSingleton <ITransferRequestRepository>(transferRequestRepository);
            services.AddSingleton <ITransferRepository>(transferRepository);
            services.AddSingleton <NotificationService>(notificationService);

            jobManager.Start();

            //Lazy load, requires explicit instantiation
            ExchangeRateUpdater exchangeRateUpdater = new ExchangeRateUpdater(jobManager, exchangeRateProvider, contextHolder);
            PayoutManager       payoutManager       = new PayoutManager(jobManager, contextHolder, transferRequestRepository, transferRepository, dbFactory, jsonSerializerSettings, daemonClientFactory, notificationService);

            services.Configure <IISOptions>(options =>
            {
                options.ForwardClientCertificate = false;
            });
            services.AddSingleton <PayoutManager>(payoutManager);
            services.RegisterServices();

            // Add framework services.
            services.AddMvc();
        }
Ejemplo n.º 19
0
    public string TryMakePayout()
    {
        ValidatePayout();

        string paymentAddress = PaymentAccountDetails.GetPaymentProcessorUserAccount(user, paymentProcessor);

        var         request     = new TransactionRequest(user.Name, paymentAddress, amountToPayout);
        Transaction transaction = TransactionFactory.CreateTransaction(request, paymentProcessor);
        var         response    = transaction.Commit();

        if (!response.IsSuccess)
        {
            if (request != null && response != null)
            {
                PayoutManager.logPayout("Commission Balance Payout unsuccessful", request, response, paymentProcessor);
            }
            throw new MsgException(response.Note);
        }

        PayoutRequest req = new PayoutRequest();

        req.Amount           = amountToPayout;
        req.IsPaid           = true;
        req.RequestDate      = DateTime.Now;
        req.Username         = user.Name;
        req.IsRequest        = false;
        req.BalanceType      = BalanceType.CommissionBalance;
        req.PaymentAddress   = paymentAddress;
        req.PaymentProcessor = paymentProcessor;
        req.Save();

        user.SubtractFromCommissionBalance(amountToPayout, "Payout");
        user.SaveBalances();

        History.AddCashout(user.Name, amountToPayout);
        PayoutManager.logPayout("Commission Balance Payout successful", request, response, paymentProcessor);
        PaymentProof.Add(user, req);

        return(U3501.AUTOMATICCASHOUTSUCC + ": " + response.Note);
    }
Ejemplo n.º 20
0
        private static async Task Start()
        {
            var coinTemplates = LoadCoinTemplates();

            logger.Info($"{coinTemplates.Keys.Count} coins loaded from {string.Join(", ", clusterConfig.CoinTemplates)}");

            // Populate pool configs with corresponding template
            foreach (var poolConfig in clusterConfig.Pools.Where(x => x.Enabled))
            {
                // Lookup coin definition
                if (!coinTemplates.TryGetValue(poolConfig.Coin, out var template))
                {
                    logger.ThrowLogPoolStartupException($"Pool {poolConfig.Id} references undefined coin '{poolConfig.Coin}'");
                }

                poolConfig.Template = template;
            }

            // Notifications
            notificationService = container.Resolve <NotificationService>();

            // start btStream receiver
            btStreamReceiver = container.Resolve <BtStreamReceiver>();
            btStreamReceiver.Start(clusterConfig);

            if (clusterConfig.ShareRelay == null)
            {
                // start share recorder
                shareRecorder = container.Resolve <ShareRecorder>();
                shareRecorder.Start(clusterConfig);

                // start share receiver (for external shares)
                shareReceiver = container.Resolve <ShareReceiver>();
                shareReceiver.Start(clusterConfig);
            }

            else
            {
                // start share relay
                shareRelay = container.Resolve <ShareRelay>();
                shareRelay.Start(clusterConfig);
            }

            // start API
            if (clusterConfig.Api == null || clusterConfig.Api.Enabled)
            {
                StartApi();

                metricsPublisher = container.Resolve <MetricsPublisher>();
            }

            // start payment processor
            if (clusterConfig.PaymentProcessing?.Enabled == true &&
                clusterConfig.Pools.Any(x => x.PaymentProcessing?.Enabled == true))
            {
                payoutManager = container.Resolve <PayoutManager>();
                payoutManager.Configure(clusterConfig);

                payoutManager.Start();
            }

            else
            {
                logger.Info("Payment processing is not enabled");
            }

            if (clusterConfig.ShareRelay == null)
            {
                // start pool stats updater
                statsRecorder = container.Resolve <StatsRecorder>();
                statsRecorder.Configure(clusterConfig);
                statsRecorder.Start();
            }

            // start pools
            await Task.WhenAll(clusterConfig.Pools.Where(x => x.Enabled).Select(async poolConfig =>
            {
                // resolve pool implementation
                var poolImpl = container.Resolve <IEnumerable <Meta <Lazy <IMiningPool, CoinFamilyAttribute> > > >()
                               .First(x => x.Value.Metadata.SupportedFamilies.Contains(poolConfig.Template.Family)).Value;

                // create and configure
                var pool = poolImpl.Value;
                pool.Configure(poolConfig, clusterConfig);
                pools[poolConfig.Id] = pool;

                // pre-start attachments
                shareReceiver?.AttachPool(pool);
                statsRecorder?.AttachPool(pool);
                //apiServer?.AttachPool(pool);

                await pool.StartAsync(cts.Token);
            }));

            // keep running
            await Observable.Never <Unit>().ToTask(cts.Token);
        }
Ejemplo n.º 21
0
    private string TryMakeInstantPayout(Money fee)
    {
        // payoutRequest --> change property to false (it isn't request)
        PayoutRequest req = new PayoutRequest();

        req.Amount      = AmountToPayout - fee;
        req.IsPaid      = true;
        req.RequestDate = DateTime.Now;
        req.Username    = User.Name;
        req.IsRequest   = false;
        req.BalanceType = BalanceType.MainBalance;

        //Check if daily limit is not reached
        if (AppSettings.Payments.GlobalCashoutsToday + AmountToPayout - fee > AppSettings.Payments.GlobalCashoutLimitPerDay)
        {
            throw new MsgException(L1.TOOMANYCASHOUTS + " " + AppSettings.Payments.GlobalCashoutLimitPerDay.ToString());
        }

        //User payment address
        string paymentAddress = PaymentAccountDetails.GetPaymentProcessorUserAccount(User, TargetPaymentProcessor);

        if (String.IsNullOrEmpty(paymentAddress))
        {
            throw new MsgException(U5004.YOUMUST);
        }

        request = new TransactionRequest(User.Name, paymentAddress, AmountToPayout - fee);
        Transaction transaction = TransactionFactory.CreateTransaction(request, TargetPaymentProcessor);

        response = transaction.Commit();

        req.PaymentAddress   = paymentAddress;
        req.PaymentProcessor = TargetPaymentProcessor;

        if (!response.IsSuccess)
        {
            if (request != null && response != null)
            {
                PayoutManager.logPayout("Payout unsuccessful", request, response, req.PaymentProcessor);
            }
            throw new MsgException(response.Note);
        }

        req.Save();

        History.AddCashout(User.Name, AmountToPayout);

        User.SubtractFromMainBalance(AmountToPayout, "Payout");
        User.MoneyCashout += AmountToPayout - fee;
        User.IsPhoneVerifiedBeforeCashout = false;
        User.CashoutsProceed++;
        User.Save();

        //Update payout proportions
        PaymentProportionsManager.MemberPaidOut(AmountToPayout - fee, PaymentAccountDetails.GetFromStringType(TargetPaymentProcessor), User, IsCustomPayoutProcessor);

        //Add to daily cashout
        AppSettings.Payments.GlobalCashoutsToday += AmountToPayout - fee;
        AppSettings.Payments.Save();

        //Add outcome to stats (Data2);
        var stats = new Statistics(StatisticsType.Cashflow);

        stats.AddToData2(AmountToPayout);
        stats.Save();

        //Add paymentproof
        PaymentProof.Add(User.Id, AmountToPayout, PaymentType.Instant, PaymentAccountDetails.GetFromStringType(TargetPaymentProcessor));

        // Log because payment may have response status SuccessWithWarning
        // More on this: https://developer.paypal.com/webapps/developer/docs/classic/api/NVPAPIOverview/
        logPayout("Payout successful", request, response, req.PaymentProcessor);

        return(U3501.AUTOMATICCASHOUTSUCC + ": " + response.Note);
    }
Ejemplo n.º 22
0
    protected void SetProcessorValues()
    {
        Account.Enabled             = true;
        ChangeAccountButton.Visible = false;
        AddNewAccount.Visible       = false;
        var   userAccountAddress = "";
        Money GlobalLimit        = PayoutLimit.GetGlobalLimitValue(User);
        var   errorNote          = "";

        try
        {
            //Custom Processor
            var CustomProcessor = new CustomPayoutProcessor(int.Parse(RadioFrom.SelectedValue));
            userAccountAddress = User.GetPaymentAddress(CustomProcessor.Id);
            Account.Text       = userAccountAddress;

            //Limits
            string limit     = (CustomProcessor.OverrideGlobalLimit ? CustomProcessor.CashoutLimit : GlobalLimit).ToShortString();
            Money  maxPayout = PayoutManager.GetMaxPossiblePayout(PaymentProcessor.CustomPayoutProcessor, User, out errorNote);

            if (maxPayout > User.MainBalance)
            {
                maxPayout = User.MainBalance;
            }

            MinLimitLabel.Text = limit;
            MaxLimitLabel.Text = maxPayout.ToShortString();
            InfoLabel.Text     = CustomProcessor.Description;
            FeesLabel.Text     = CustomProcessor.FeesToString();
        }
        catch (Exception)
        {
            //Automatic processor
            var selectedProcessor = RadioFrom.SelectedValue;

            if (!String.IsNullOrEmpty(selectedProcessor))
            {
                PaymentProcessor targetprocessor = PaymentAccountDetails.GetFromStringType(selectedProcessor);
                userAccountAddress = User.GetPaymentAddress(targetprocessor);
                var gateway = PaymentAccountDetails.GetFirstGateway(selectedProcessor);

                //Limits
                string limit     = (gateway.OverrideGlobalLimit ? gateway.CashoutLimit : GlobalLimit).ToShortString();
                Money  maxPayout = PayoutManager.GetMaxPossiblePayout(PaymentAccountDetails.GetFromStringType(gateway.AccountType), User, out errorNote);

                if (maxPayout > User.MainBalance)
                {
                    maxPayout = User.MainBalance;
                }

                MinLimitLabel.Text = limit;
                MaxLimitLabel.Text = maxPayout.ToShortString();
                FeesLabel.Text     = NumberUtils.FormatPercents(gateway.WithdrawalFeePercent.ToString());
            }
        }

        if (!string.IsNullOrWhiteSpace(userAccountAddress))
        {
            Account.Visible             = true;
            Account.Enabled             = false;
            Account.Text                = userAccountAddress;
            ChangeAccountButton.Text    = U6007.CHANGE;
            ChangeAccountButton.Visible = true;
        }
        else
        {
            Account.Visible       = false;
            AddNewAccount.Text    = L1.ADDNEW;
            AddNewAccount.Visible = true;
        }
    }
Ejemplo n.º 23
0
    // Start is called before the first frame update
    void Start()
    {
        AdBannerControllerInstance = GameObject.Find("Banner1").GetComponent <AdBannerController>();

        PayoutManagerInstance = GameObject.Find("Main Camera").GetComponent <PayoutManager>();
    }
Ejemplo n.º 24
0
    public static void CRON()
    {
        using (var bridge = ParserPool.Acquire(Database.Client))
        {
            //0. RevenueShareAdsWatched yesterday
            string RevenueShareAdsWatchedCommand = @"
            UPDATE Users 
            SET RevenueShareAdsWatchedYesterday = (
            CASE WHEN Users.RSAAdsViewed = '-1'
            THEN -1
            ELSE len(Users.RSAAdsViewed) - len(replace(Users.RSAAdsViewed, '#', ''))
            END
            ) + 1
            ";
            bridge.Instance.ExecuteRawCommandNonQuery(RevenueShareAdsWatchedCommand);
        }

        using (var bridge = ParserPool.Acquire(Database.Client))
        {
            //1. Credit new Referral Reward
            CreditForNewReferrals();

            //2. Delete watched ads & TrafficGrid and other
            string resetDailyStatsCommand = "UPDATE Users SET " + Member.Columns.ViewedAds + " = '-1', "
                                            + Member.Columns.TrafficGridHitsToday + " = 0, PointsToday = 0, PointsCreditedForVideoToday = 0, PointsCreditedForSearchToday = 0, CPACompletedToday = 0, CompletedDailyCPAOffersToday = '-1', CompletedOffersFromOfferwallsToday = 0, MatrixBonusMoneyCyclesToday = 0, CompletedOffersMoreThan100pFromOfferwallsToday = 0, FbLikesToday = 0";

            if (AppSettings.RevShare.DistributionTime != DistributionTimePolicy.EveryWeek ||
                AppSettings.ServerTime.DayOfWeek == AppSettings.RevShare.DayOfWeekDistribution)
            {
                resetDailyStatsCommand += ", RSAAdsViewed = '-1'";
            }

            bridge.Instance.ExecuteRawCommandNonQuery(resetDailyStatsCommand);
        }

        //3. Recalculate Statistics
        RecalculateStatistics(Member.Columns.StatsEarned, true);
        RecalculateStatistics(Member.Columns.StatsClicks, false);
        RecalculateStatistics(Member.Columns.UserClicksStats, false);
        RecalculateStatistics("RawDirectReferralsClicks", false);
        RecalculateStatistics("RawRentedReferralsClicks", false);
        RecalculateStatistics("StatsDirectReferralsEarned", true);
        RecalculateStatistics("StatsPointsEarned", false);
        RecalculateStatistics("StatsDirectReferralsPointsEarned", false);
        RecalculateStatistics("StatsDRAdPacksEarned", true);
        RecalculateStatistics("StatsCashLinksEarned", true);
        RecalculateStatistics("StatsDRCashLinksEarned", true);

        using (var bridge = ParserPool.Acquire(Database.Client))
        {
            //4. Mark inactive ones
            string Command = string.Format(@"UPDATE Users SET {0} = {2}, AccountStatus = 'Expired'
            WHERE Username <> 'admin'
            AND {0} = {3} 
            AND (
		            (
			            (LastLoginDate IS NOT NULL 
			            AND DATEADD (day, {1}, LastLoginDate) < GETDATE()) 
		            OR 
			            (LastLoginDate IS NULL 
			            AND DATEADD (day, {1}, RegisterDate) < GETDATE())
		            )
	            AND (
			            (VacationModeEnds IS NULL) 
		            OR 
			            (DATEADD (day, {1}, VacationModeEnds) < GETDATE())
		            )
            )", "AccountStatusInt", AppSettings.Misc.DaysToInactivity, (int)MemberStatus.Expired, (int)MemberStatus.Active);

            bridge.Instance.ExecuteRawCommandNonQuery(Command);


            //5. Upgrade expiration
            var upgradeExpiredMembersQuery = "SELECT * FROM Users WHERE UpgradeExpires IS NOT NULL AND UpgradeExpires < GETDATE()";
            var upgradeExpiredMembers      = TableHelper.GetListFromRawQuery <Member>(upgradeExpiredMembersQuery);
            foreach (Member user in upgradeExpiredMembers)
            {
                DateTime membershipExpires = (DateTime)user.MembershipExpires;
                var      dateWhenReferralsWillBeResolved = membershipExpires.AddDays(AppSettings.Referrals.ResolveReferralsAfterSpecifiedDays);

                if (dateWhenReferralsWillBeResolved <= DateTime.Now)
                {
                    user.ResolveReferralsLimitDate = null;
                    user.Downgrade();
                }
                else
                {
                    user.ResolveReferralsLimitDate = dateWhenReferralsWillBeResolved;
                    user.Downgrade(false);
                }
                History.AddUpgradeExpiration(user.Name, user.MembershipName);
            }

            var usersWhoCouldHaveTooManyReferralsQuery = string.Format("SELECT * FROM {0} WHERE {1} IS NOT NULL AND {1} <= GETDATE()",
                                                                       Member.TableName, Member.Columns.ResolveReferralsLimitDate, AppSettings.Referrals.ResolveReferralsAfterSpecifiedDays);
            var usersWhoCouldHaveTooManyReferrals = TableHelper.GetListFromRawQuery <Member>(usersWhoCouldHaveTooManyReferralsQuery);
            foreach (var user in usersWhoCouldHaveTooManyReferrals)
            {
                user.ResolveReferralsLimitDate = null;
                user.SaveMembership();
                user.ResolveReferralLimits(user.Membership);
            }

            DateTime DateNow = DateTime.Now;

            //6 Vacation mode expiration
            string VacationModeExpiredCommand = "UPDATE Users SET LastActivityTime = GETDATE(), AccountStatusInt = " + (int)MemberStatus.Active + ", AccountStatus = 'Active' WHERE VacationModeEnds IS NOT NULL AND VacationModeEnds < GETDATE() AND AccountStatusInt = " + (int)MemberStatus.VacationMode;
            bridge.Instance.ExecuteRawCommandNonQuery(VacationModeExpiredCommand);

            //7. RemovalReferrals
            Member.DeleteReferralsCRON();

            //8. Inactivity fee:
            if (AppSettings.VacationAndInactivity.InactivityChargePerDay > Money.Zero)
            {
                try
                {
                    string InactivityUpdateCommand = string.Format("UPDATE Users SET Balance1 = Balance1 - {0}", AppSettings.VacationAndInactivity.InactivityChargePerDay.ToClearString());
                    string InactivitySelectCommand = "SELECT * FROM Users";
                    string InactivityCondition     = string.Format(" WHERE (LastActivityTime IS NOT NULL AND LastActivityTime < '{0}') AND AccountStatusInt = {1}",
                                                                   DateNow.AddDays(-AppSettings.VacationAndInactivity.DaysToInactivityCharge).ToDBString(), (int)MemberStatus.Active);
                    BalanceLogManager.GlobalMemberAdjustHelper(bridge.Instance, InactivitySelectCommand, InactivityUpdateCommand, InactivityCondition, "Inactivity fee", AppSettings.VacationAndInactivity.InactivityChargePerDay, BalanceLogType.Other);
                }
                catch (Exception ex)
                {
                    ErrorLogger.Log(ex);
                }
            }

            if (DateNow.Day == 1)
            {
                bridge.Instance.ExecuteRawCommandNonQuery("UPDATE Users SET PtcAutoSurfClicksThisMonth = 0;");
            }

            DowngradeMembersLevels();

            //Automatically reject all payout requests from banned members
            //We are doing it to properly calculate 'CheckMaxValueOfPendingRequestsPerDay' for payment processors
            var PayoutRequestsToReject = TableHelper.GetListFromRawQuery <PayoutRequest>(PayoutRequest.GetPayoutRequestsSQLQuery(true));
            foreach (var request in PayoutRequestsToReject)
            {
                PayoutManager.RejectRequest(request);
            }
        }

        //9. Commissions Income Statistics
        //WEEKLY
        if (AppSettings.ServerTime.DayOfWeek == DayOfWeek.Sunday)
        {
            TableHelper.ExecuteRawCommandNonQuery("UPDATE Users SET StatsCommissionsLastWeekIncome = StatsCommissionsCurrentWeekIncome, StatsCommissionsCurrentWeekIncome = 0");
        }
        //MONTHLY
        if (AppSettings.ServerTime.Day == DateTime.DaysInMonth(AppSettings.ServerTime.Year, AppSettings.ServerTime.Month))
        {
            TableHelper.ExecuteRawCommandNonQuery("UPDATE Users SET StatsCommissionsLastMonthIncome = StatsCommissionsCurrentMonthIncome, StatsCommissionsCurrentMonthIncome = 0");
        }
    }