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

in Python2 years ago (edited)

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.



Sort:  

Interesting, I've been dealing with bugs and python library on my system for weeks now. Some functions are not working, I'm I free to follow-up to learn some thing and ask for help anytime I have a problem. Still learning on hive development, and the challenges is to come out with a big project that will benefit the ecosystem

Yeah, it was the case for a couple of years, the last hardfork must have changed some API, and the libraries all broke at the same time.

Btw. I just checked, and it looks like @emrebeyler pushed a new update to LightHive three days ago. That's actually Great news! This makes my above post a bit redundant though. 😅

Update yours now:

pip install --user --upgrade lighthive

Oh! Thank you for the update

You're welcome. I tried it, and it didn't work though. I'll try later to check whether I did something wrong.

format is a bit changed.

https://lighthive.readthedocs.io/en/latest/helpers.html#account-helper

see the updated example. if it still don't work, please post your code, the error and expected behaviour.

I'll post an update soon about the new version and changelog. Too busy with the stuff going on (earthquake at Turkey) so can't really find time to handle these things, but will make sure it's working at the end.

Just let me know if you still encounter any problems.

Great news concerning LightHive, not so great about the earthquake. I hope you are well!

I have created something new that uses the library, a comment counter, or Reply Tally, that takes URLs as an input, and counts the replies for each commenter. I'm planning to improve on it, but that's a start I guess. Oh, and thank you very much for your library, it's a lifesaver for a beginner Python enthusiast with a passion to code for Hive.

Stay safe!


Hey @emrebeyler, here is a little bit of BEER from @isnochys for you. Enjoy it!

We love your support by voting @detlev.witness on HIVE .


Hey @emrebeyler, here is a little bit of BEER from @isnochys for you. Enjoy it!

Learn how to earn FREE BEER each day by staking your BEER.

Thank you for your witness vote!
Have a !BEER on me!
To Opt-Out of my witness beer program just comment STOP below


Hey @emrebeyler, here is a little bit of BEER from @isnochys for you. Enjoy it!

Learn how to earn FREE BEER each day by staking your BEER.

Thank you for your witness vote!
Have a !BEER on me!
To Opt-Out of my witness beer program just comment STOP below

Thank you for your witness vote!
Have a !BEER on me!
To Opt-Out of my witness beer program just comment STOP below

$WINE


Congratulations, @theguruasia You Successfully Shared 0.300 WINEX With @gamer00.
You Earned 0.300 WINEX As Curation Reward.
You Utilized 3/4 Successful Calls.

wine_logo


Contact Us : WINEX Token Discord Channel
WINEX Current Market Price : 0.152


Swap Your Hive <=> Swap.Hive With Industry Lowest Fee (0.1%) : Click This Link
Read Latest Updates Or Contact Us