示例#1
0
    def test_get_balance_non_zero(self):
        balance = get_balance(self.user.radcheck)
        card_value = 4
        balance = balance + card_value

        # Recharge user account
        recharge = RechargeAndUsage.objects.create(
            radcheck=self.radcheck,
            amount=card_value,
            balance=balance,
            action='REC',
            activity_id=30
        )

        self.assertEqual(get_balance(self.user.radcheck), 4)
示例#2
0
    def get_balance(self):
        # get the current balance
        _balance_elem = (By.XPATH, '//td[@class="gcBalance"]')
        if not self.is_visible(_balance_elem, wait_time=3):
            return False

        balance_elem = self.wait_visible_element(_balance_elem)
        self.balance = get_balance(balance_elem.text)
示例#3
0
    def get_balance(self):
        # get the current balance
        _balance_elem = [(By.XPATH, '//td[@class="gcBalance"]'),
                         (By.ID, 'gc-current-balance')]
        balance_elem = self.find_alternative_elem(_balance_elem)
        if not self.is_valid_elem(balance_elem):
            return False

        self.balance = get_balance(balance_elem.text)
示例#4
0
    def __init__(self, driver, params, account):
        BaseGiftCard.__init__(self, driver, params, account)

        price_str = str(self.params.get('actual_price', 0.0))
        self.price = get_balance(price_str)
        if '.' not in price_str:
            self.price = self.price * 100

        self.balance = 0
示例#5
0
def main():

    st.set_page_config(layout="wide")

    # ROW 1 ------------------------------------------------------------------------
    col1, col2 = st.beta_columns([1, 2])
    col1.image(
        'https://cdn.futura-sciences.com/buildsv6/images/wide1920/4/1/d/41d6867f78_50171855_bitcoin.jpg',
        width=300)
    col2.title("Welcome to the Crypto Trader Dashboard")

    # ROW 2 ------------------------------------------------------------------------
    exchange = utils.initialize_exchange(conf.market, conf.api_key,
                                         conf.secret_key)
    balance = utils.get_balance(exchange, conf.currency)
    wallet = round(balance['total'], 0)
    st.markdown(
        f"<h3> Your account balance is equal to <span style='font-weight:bolder;font-size:30px;'>{wallet:.0f}$</span> </h3>",
        unsafe_allow_html=True)

    ## ROW 3 ------------------------------------------------------------------------
    start_date = st.date_input("View trades since:")

    # ROW 4 ------------------------------------------------------------------------
    row4_1, row4_spacer1, row4_2 = st.beta_columns((2, .2, 1))
    start_date = datetime.combine(start_date, datetime.min.time())
    trades = utils.get_trades(exchange, since=start_date)
    stats = utils.get_statistics_on_trades(trades)

    with row4_1:
        row4_1.subheader('Statistics per day:')
        row4_1.write(stats)

    with row4_2:
        start = float(stats.head(1)['Amount'])
        end = float(stats.tail(1)['Amount']) + float(stats.tail(1)['Earnings'])
        evolution = end - start
        pourcentage = (end - start) / start * 100
        row4_2.markdown("<h3> \n </h3>", unsafe_allow_html=True)
        row4_2.markdown("<h3> \n </h3>", unsafe_allow_html=True)
        row4_2.markdown(
            f"<h3 style='text-align:center;'> Evolution during the selected period \n <span style='font-weight:bolder;font-size:30px;'>{evolution:.0f}$ ({pourcentage:.1f}%)</span> </h3>",
            unsafe_allow_html=True)

    # ROW 5 ------------------------------------------------------------------------
    st.subheader('Evolution of the amount (usd):')
    utils.plot_balance(stats)

    update = st.button('Update')
    if update:
        pass
示例#6
0
def group_details(group_name):

    group = groups.find_one({'name': group_name})
    is_member = next(
        filter(lambda x: x['username'] == current_user.username,
               group['members']), None)
    if not is_member:
        flash(u'Unauthorized', 'danger')
        return render_template('login.html')
    total_expenses = sum(map(lambda x: x['amount'], group['expenses']))
    group_balance = get_balance(group['expenses']).items()
    return render_template('details.html',
                           group=group,
                           total_expenses=total_expenses,
                           balances=group_balance)
示例#7
0
文件: forms.py 项目: deone/billing
    def save(self):
        voucher = self.cleaned_data

        balance = get_balance(self.user.radcheck)

        amount = voucher['value']
        balance = balance + amount
        activity_id = voucher['serial_number']

        RechargeAndUsage.objects.create(
            radcheck=self.user.radcheck,
            amount=amount,
            balance=balance,
            action='REC',
            activity_id=activity_id
        )

        return voucher
def start():
    print('Consulta Saldo Transurc\n')

    session = create_session()

    # first_response = send_first_request(session)
    # second_url = find_second_url(first_response)
    # second_response = send_second_request(session, second_url)

    # Create value of the header 'Cookie' necessary to the
    # third request and last request
    cookie_value = make_cookie_value(session)
    add_new_header(config.HEADERS_3, 'Cookie', cookie_value)
    add_new_header(config.HEADERS_4, 'Cookie', cookie_value)

    third_response = send_third_request(session, config.THIRD_URL)

    # save_file(third_response, 'consulta_saldo_form_file.html')

    # user_data = {
    #     'num_aplicacao': input('Digite o número antes do cartão (XX): '),
    #     'num_cartao': input('Digite o número do seu cartão (XX): '),
    #     'digito_verificador': input('Digite o número verificador (X): '),
    #     'data_nascimento': input(
    #         'Digite a sua data de nascimento (DD/MM/AAAA):'
    #     )
    # }

    user_data = {
        'num_aplicacao': sys.argv[1],
        'num_cartao': sys.argv[2],
        'digito_verificador': sys.argv[3],
        'data_nascimento': sys.argv[4],
    }

    # Last response contains the balance
    last_response = send_last_request(session, third_response, user_data)

    balance = get_balance(last_response)

    print('\nSeu saldo no bilhete único é ' + balance)
示例#9
0
 def test_get_balance_zero(self):
     # User has no recharge entry. Balance should be zero
     self.assertEqual(get_balance(self.user.radcheck), 0)
示例#10
0
def monitor(ctx, metrics_port, pause_duration):
    """Simple program that polls one or more ethereum accounts and reports metrics on them."""
    # Get config
    config = ctx.obj["CONFIG"]

    # Set up prometheus metrics
    metrics = {
        "wallet_balance":
        Gauge("ethereum_wallet_balance", "ETH Wallet Balance",
              ["role", "home", "address", "network"]),
        "transaction_count":
        Gauge("ethereum_transaction_count", "ETH Wallet Balance",
              ["role", "home", "address", "network"]),
        "block_number":
        Gauge("ethereum_block_height", "Block Height", ["network"])
    }

    # Set up logging
    logging.basicConfig(stream=sys.stdout, level=logging.INFO)

    # run metrics endpoint
    start_http_server(metrics_port)
    logging.info(f"Running Prometheus endpoint on port {metrics_port}")

    logging.info("Executing event loop, Ctrl+C to exit.")
    # main event loop
    while True:
        # top-up if we see a low balance
        should_top_up = False
        threshold = 150000000000000000
        # for each rpc
        for name, network in config["networks"].items():
            endpoint = network["endpoint"]

            # Fetch block height
            try:
                block_height = get_block_height(endpoint)
                metrics["block_number"].labels(network=name).set(block_height)
            except ValueError:
                continue

            # fetch bank balance
            account = network["bank"]["address"]
            logging.info(f"Fetching metrics for {account} via {endpoint}")
            wallet_wei = get_balance(account, endpoint)
            logging.info(f"Wallet Balance: {wallet_wei * 10**-18}")
            # fetch tx count
            tx_count = get_nonce(account, endpoint)
            logging.info(f"Transaction Count: {tx_count}")
            # report metrics
            metrics["wallet_balance"].labels(role="bank",
                                             home=name,
                                             address=account,
                                             network=name).set(wallet_wei)
            metrics["transaction_count"].labels(role="bank",
                                                home=name,
                                                address=account,
                                                network=name).set(tx_count)

            # for each account
            for home_name, home in config["homes"].items():
                for role, account in home["addresses"].items():
                    logging.info(
                        f"Fetching metrics for {account} via {endpoint}")
                    # fetch balance
                    wallet_wei = get_balance(account, endpoint)
                    logging.info(f"Wallet Balance: {wallet_wei * 10**-18}")
                    if wallet_wei < threshold:
                        logging.warn(
                            f"BALANCE IS LOW, MARKING FOR TOP-UP {wallet_wei} < {threshold}"
                        )
                        should_top_up = True
                    # fetch tx count
                    tx_count = get_nonce(account, endpoint)
                    logging.info(f"Transaction Count: {tx_count}")
                    # report metrics
                    metrics["wallet_balance"].labels(
                        role=role,
                        home=home_name,
                        address=account,
                        network=name).set(wallet_wei)
                    metrics["transaction_count"].labels(
                        role=role,
                        home=home_name,
                        address=account,
                        network=name).set(tx_count)

        if should_top_up:
            _top_up(ctx, auto_approve=True)

        logging.info(f"Sleeping for {pause_duration} seconds.")
        time.sleep(pause_duration)
示例#11
0
def _top_up(ctx, auto_approve=False):
    click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")
    config = ctx.obj["CONFIG"]
    transaction_queue = {}
    # Init transaction queue for each network
    for network in config["networks"]:
        transaction_queue[network] = []

    for home in config["homes"]:

        for role, address in config["homes"][home]["addresses"].items():
            logging.info(f"Processing {role}-{address} on {home}")
            # fetch config params
            home_upper_bound = config["networks"][home]["threshold"]
            # don't top up until balance has gone beneath lower bound
            home_lower_bound = 150000000000000000
            home_endpoint = config["networks"][home]["endpoint"]
            home_bank_signer = config["networks"][home]["bank"]["signer"]
            home_bank_address = config["networks"][home]["bank"]["address"]

            # check if balance is below threshold at home
            threshold_difference = is_wallet_below_threshold(
                address, home_lower_bound, home_upper_bound, home_endpoint)
            # get nonce
            home_bank_nonce = get_nonce(home_bank_address, home_endpoint)

            if threshold_difference:
                logging.info(
                    f"Threshold difference is {threshold_difference} for {role}-{address} on {home}, enqueueing transaction."
                )
                # if so, enqueue top up with (threshold - balance) ether
                transaction = create_transaction(
                    home_bank_signer, address, threshold_difference,
                    home_bank_nonce + len(transaction_queue[home]),
                    home_endpoint)
                transaction_queue[home].append(transaction)
            else:
                logging.info(
                    f"Threshold difference is satisfactory for {role}-{address} on {home}, no action."
                )

            for replica in config["homes"][home]["replicas"]:
                # fetch config params
                replica_upper_bound = config["networks"][replica]["threshold"]
                # don't top up until balance has gone beneath lower bound
                replica_lower_bound = 150000000000000000
                replica_endpoint = config["networks"][replica]["endpoint"]
                replica_bank_signer = config["networks"][replica]["bank"][
                    "signer"]
                replica_bank_address = config["networks"][replica]["bank"][
                    "address"]
                # check if balance is below threshold at replica
                threshold_difference = is_wallet_below_threshold(
                    address, replica_lower_bound, replica_upper_bound,
                    replica_endpoint)
                # get nonce
                replica_bank_nonce = get_nonce(replica_bank_address,
                                               replica_endpoint)
                # if so, enqueue top up with (threshold - balance) ether
                if threshold_difference:
                    logging.info(
                        f"Threshold difference is {threshold_difference} for {role}-{address} on {replica}, enqueueing transaction."
                    )
                    transaction = create_transaction(
                        replica_bank_signer, address, threshold_difference,
                        replica_bank_nonce + len(transaction_queue[replica]),
                        replica_endpoint)
                    transaction_queue[replica].append(transaction)
                else:
                    logging.info(
                        f"Threshold difference is satisfactory for {role}-{address} on {replica}, no action."
                    )

    # compute analytics about enqueued transactions
    click.echo("\n Transaction Stats:")
    for network in transaction_queue:
        if len(transaction_queue[network]) > 0:
            amount_sum = sum(tx[0]["value"]
                             for tx in transaction_queue[network])
            bank_balance = get_balance(
                config["networks"][network]["bank"]["address"],
                config["networks"][network]["endpoint"])
            click.echo(
                f"\t {network} Bank has {Web3.fromWei(bank_balance, 'ether')} ETH"
            )
            click.echo(
                f"\t About to send {len(transaction_queue[network])} transactions on {network} - Total of {Web3.fromWei(amount_sum, 'ether')} ETH \n"
            )

            if not auto_approve:
                click.confirm(
                    "Would you like to proceed with dispatching these transactions?",
                    abort=True)
            else:
                # Send it!!
                click.echo("Auto-Approved. Dispatching.")

            # Process enqueued transactions
            click.echo(f"Processing transactions for {network}")
            for transaction_tuple in transaction_queue[network]:
                click.echo(
                    f"Attempting to send transaction: {json.dumps(transaction_tuple[0], indent=2, default=str)}"
                )
                hash = dispatch_signed_transaction(
                    transaction_tuple[1],
                    config["networks"][network]["endpoint"])
                click.echo(f"Dispatched Transaction: {hash}")
                time.sleep(3)
        else:
            click.echo(
                f"\t No transactions to process for {network}, continuing...")