Full Code Alchemist ::: 耶郎 ::: avatar

I managed to fix the essential part of my 'transfers and rewards' Python script.

gamer00

Published: 09 Feb 2023 › Updated: 09 Feb 2023I managed to fix the essential part of my 'transfers and rewards' Python script.

I managed to fix the essential part of my 'transfers and rewards' Python script.

My local use Hive script Hive transfers and rewards tool - local use - 0.1.py is now almost fully working. It evolved from the small snippet I used as an example on a previous post of mine.

I managed to print out the (HIVE, HBD and HP) totals from a chosen range of dates.


Karate Hacker Daniel LaRusso

Since the lighthive library isn't working yet, I had to change the script to read the transactions from a locally backed up json file containing the complete history of my account. However since it's only a backup of my own account, and the lighthive library isn't working yet, I can't test whether it works (not even sure it would, because it's designed completely around the json file) for multiple accounts.

I will need to check and modify my original script when the lighthive library is fixed.

(Update: It appears the LightHive library has been updated three days ago, and my post is now kind of redundant.

Let's upgrade it immediately: pip install --user --upgrade lighthive)

import json
import datetime
import string
from lighthive.client import Client
from lighthive.helpers.amount import Amount

# Ask for the account name:
ac_input = input("Tell me the account you want to process: ")

client = Client()
account = client.account(ac_input)


# Ask the user for start and end dates
start_date_input = input("Enter start date (YYYY-MM-DD): ")
end_date_input = input("Enter end date (YYYY-MM-DD): ")

# Ask the user if they want to see daily totals
daily_totals = input("Do you want to see daily totals of each HIVE, HBD and HP? [y/n] ")

# Convert the input strings to datetime objects
start_datetime = datetime.datetime.strptime(start_date_input, '%Y-%m-%d')
end_datetime = datetime.datetime.strptime(end_date_input, '%Y-%m-%d')

# Fetch the global properties so that VESTS can be converted into, and shown in HP:
dynamic_global_properties = client.get_dynamic_global_properties()
total_vests = Amount(dynamic_global_properties['total_vesting_shares']).amount
total_vesting_fund_hive = Amount(dynamic_global_properties['total_vesting_fund_hive']).amount

'''
Open the file with the recorded history (the file was broken, and
not recognized as json, so split the lines in appropriate places ("\n")
with line breaks, in order to adhere to the JSON standard:
'''
def read_from_file(file_path, start_datetime=None, end_datetime=None):
    with open(file_path, "r") as file:
        lines = file.read().split("\n")
        records = []
        for line in lines:
            if line:
                record = json.loads(line)
                timestamp = datetime.datetime.strptime(record['timestamp'], "%Y-%m-%dT%H:%M:%S")
                if start_datetime and timestamp < start_datetime:
                    continue
                if end_datetime and timestamp > end_datetime:
                    continue
                records.append(record)
    return records

# Define the data file path, and carry the data from the file into 'records'.
file_path = "tapahtumat.json"
records = read_from_file(file_path, start_datetime, end_datetime)

# Reset and initialize values and transaction lists:
hive_reward = 0
hbd_reward = 0
vests_reward = 0
incoming_transactions = []
outgoing_transactions = []


if daily_totals.lower() == 'y':
    # Establish a set called daily_totals:
    daily_totals = {}
    # Calculate the totals for each day:
    for op in records:
        date = datetime.datetime.strptime(op['timestamp'], '%Y-%m-%dT%H:%M:%S')
        date = date.date()
        if date not in daily_totals:
            daily_totals[date] = {"HIVE": 0, "HBD": 0, "HP": 0}
        if op['type'] == 'claim_reward_balance':
            vests = float(op['reward_vests']["amount"])
            HP = float(vests) / 1e6 * float(total_vesting_fund_hive) / float(total_vests)
            daily_totals[date]["HIVE"] += float(op.get("reward_hive", {"amount": 0})["amount"]) * pow(10, -op.get("amount", {"precision"
: 3})["precision"])
            daily_totals[date]["HBD"] += float(op.get("reward_hbd", {"amount": 0})["amount"]) * pow(10, -op.get("amount", {"precision":
3})["precision"])
            daily_totals[date]["HP"] += HP
        elif op['type'] == 'transfer':
            if op['to'] == str(ac_input):
                if op["amount"]["nai"] == "@@000000021": # HBD
                    daily_totals[date]["HBD"] += float(op.get("amount")["amount"]) * pow(10, -op["amount"]["precision"])
                elif op["amount"]["nai"] == "@@000000013": # HIVE
                    daily_totals[date]["HIVE"] += float(op.get("amount")["amount"]) * pow(10, -op["amount"]["precision"])
            elif op['to'] != str(ac_input):
                if op["amount"]["nai"] == "@@000000021": # HBD
                    daily_totals[date]["HBD"] -= float(op.get("amount")["amount"]) * pow(10, -op["amount"]["precision"])
                elif op["amount"]["nai"] == "@@000000013": # HIVE
                    daily_totals[date]["HIVE"] -= float(op.get("amount")["amount"]) * pow(10, -op["amount"]["precision"])

    for date, totals in daily_totals.items():
        print(f"{date}: HIVE={totals['HIVE']} HBD={totals['HBD']} HP={totals['HP']}")
else:
    
    # INCOMPLETE :: Under Construction
    # List all the transadctions and 'claim_reward_balance' operations with values from 'records'
    for op in records:
        if op['type'] == 'claim_reward_balance':
            vests = float(op['reward_vests']["amount"])
            HP = float(vests) / 1e6 * float(total_vesting_fund_hive) / float(total_vests)
            print(op['timestamp'], ['reward_hbd'], ['reward_hive'], HP, 'HP')
        if transaction['type'] == 'transfer':
            if  op["amount"]["nai"] == "@@000000021": # HBD
                print(op['timestamp'], ['from']1]['op'][1]['to'], op[1]['op'][1]['amount'])
            elif op["amount"]["nai"] == "@@000000013": # HIVE

Well, I'll go now, and prepare for tonight's Go club activities. See you again later!



Join the Hive community and be a part of a growing decentralized platform that values your contributions. Hive is a social blockchain that connects content creators and fosters engagement.

Sign up and discover the limitless possibilities of Hive.



Leave I managed to fix the essential part of my 'transfers and rewards' Python script. to:

Written by

Gaming, FLOSS, Arts, Photography, Weiqi/Go/Baduk... All photos are my own unless otherwise specified.

Read more #hive-129924 posts


Best Posts From Full Code Alchemist ::: 耶郎 :::

We have not curated any of gamer00's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Full Code Alchemist ::: 耶郎 :::