Shuffling UI, trying to ditch variables

This commit is contained in:
ben 2022-12-08 10:24:37 +00:00
parent 53e910d549
commit 08ed86fb18
6 changed files with 1240 additions and 914 deletions

View file

@ -10,6 +10,7 @@ from loguru import logger
from . import db
from .models import Gerty, Mempool, MempoolEndpoint
async def create_gerty(wallet_id: str, data: Gerty) -> Gerty:
gerty_id = urlsafe_short_hash()
await db.execute(
@ -78,13 +79,20 @@ async def delete_gerty(gerty_id: str) -> None:
#############MEMPOOL###########
async def get_mempool_info(endPoint: str, gerty) -> Optional[Mempool]:
endpoints = MempoolEndpoint()
url = ""
for endpoint in endpoints:
if endPoint == endpoint[0]:
url = endpoint[1]
row = await db.fetchone("SELECT * FROM gerty.mempool WHERE endpoint = ?", (endPoint,))
row = await db.fetchone(
"SELECT * FROM gerty.mempool WHERE endpoint = ? AND mempool_endpoint = ?",
(
endPoint,
gerty.mempool_endpoint,
),
)
if not row:
async with httpx.AsyncClient() as client:
response = await client.get(gerty.mempool_endpoint + url)
@ -93,19 +101,30 @@ async def get_mempool_info(endPoint: str, gerty) -> Optional[Mempool]:
INSERT INTO gerty.mempool (
data,
endpoint,
time
time,
mempool_endpoint
)
VALUES (?, ?, ?)
VALUES (?, ?, ?, ?)
""",
(json.dumps(response.json()), endPoint, int(time.time())),
(
json.dumps(response.json()),
endPoint,
int(time.time()),
gerty.mempool_endpoint,
),
)
return response.json()
if int(time.time()) - row.time > 20:
async with httpx.AsyncClient() as client:
response = await client.get(gerty.mempool_endpoint + url)
await db.execute(
"UPDATE gerty.mempool SET data = ?, time = ? WHERE endpoint = ?",
(json.dumps(response.json()), int(time.time()), endPoint),
"UPDATE gerty.mempool SET data = ?, time = ? WHERE endpoint = ? AND mempool_endpoint = ?",
(
json.dumps(response.json()),
int(time.time()),
endPoint,
gerty.mempool_endpoint,
),
)
return response.json()
return json.loads(row.data)

View file

@ -12,13 +12,20 @@ from .number_prefixer import *
from ...settings import LNBITS_PATH
from lnbits.utils.exchange_rates import satoshis_amount_as_fiat
def get_percent_difference(current, previous, precision=3):
difference = (current - previous) / current * 100
return "{0}{1}%".format("+" if difference > 0 else "", round(difference, precision))
# A helper function get a nicely formated dict for the text
def get_text_item_dict(text: str, font_size: int, x_pos: int = None, y_pos: int = None, gerty_type: str = 'Gerty'):
def get_text_item_dict(
text: str,
font_size: int,
x_pos: int = None,
y_pos: int = None,
gerty_type: str = "Gerty",
):
# Get line size by font size
line_width = 20
if font_size <= 12:
@ -31,7 +38,7 @@ def get_text_item_dict(text: str, font_size: int, x_pos: int = None, y_pos: int
line_width = 25
# Get font sizes for Gerty mini
if(gerty_type.lower() == 'mini gerty'):
if gerty_type.lower() == "mini gerty":
if font_size <= 12:
font_size = 1
if font_size <= 15:
@ -43,8 +50,6 @@ def get_text_item_dict(text: str, font_size: int, x_pos: int = None, y_pos: int
else:
font_size = 5
# wrap the text
wrapper = textwrap.TextWrapper(width=line_width)
word_list = wrapper.wrap(text=text)
@ -81,10 +86,16 @@ async def get_mining_dashboard(gerty):
hashrateOneWeekAgo = data["hashrates"][6]["avgHashrate"]
text = []
text.append(get_text_item_dict(text="Current mining hashrate", font_size=12,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="{0}hash".format(si_format(hashrateNow, 6, True, " ")), font_size=20,gerty_type=gerty.type
text="Current mining hashrate", font_size=12, gerty_type=gerty.type
)
)
text.append(
get_text_item_dict(
text="{0}hash".format(si_format(hashrateNow, 6, True, " ")),
font_size=20,
gerty_type=gerty.type,
)
)
text.append(
@ -92,7 +103,8 @@ async def get_mining_dashboard(gerty):
text="{0} vs 7 days ago".format(
get_percent_difference(hashrateNow, hashrateOneWeekAgo, 3)
),
font_size=12,gerty_type=gerty.type
font_size=12,
gerty_type=gerty.type,
)
)
areas.append(text)
@ -102,27 +114,54 @@ async def get_mining_dashboard(gerty):
# timeAvg
text = []
progress = "{0}%".format(round(r["progressPercent"], 2))
text.append(get_text_item_dict(text="Progress through current epoch", font_size=12,gerty_type=gerty.type))
text.append(get_text_item_dict(text=progress, font_size=60,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="Progress through current epoch",
font_size=12,
gerty_type=gerty.type,
)
)
text.append(
get_text_item_dict(text=progress, font_size=60, gerty_type=gerty.type)
)
areas.append(text)
# difficulty adjustment
text = []
stat = r["remainingTime"]
text.append(get_text_item_dict(text="Time to next difficulty adjustment", font_size=12,gerty_type=gerty.type))
text.append(get_text_item_dict(text=get_time_remaining(stat / 1000, 3), font_size=12,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="Time to next difficulty adjustment",
font_size=12,
gerty_type=gerty.type,
)
)
text.append(
get_text_item_dict(
text=get_time_remaining(stat / 1000, 3),
font_size=12,
gerty_type=gerty.type,
)
)
areas.append(text)
# difficultyChange
text = []
difficultyChange = round(r["difficultyChange"], 2)
text.append(get_text_item_dict(text="Estimated difficulty change", font_size=12,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="Estimated difficulty change",
font_size=12,
gerty_type=gerty.type,
)
)
text.append(
get_text_item_dict(
text="{0}{1}%".format(
"+" if difficultyChange > 0 else "", round(difficultyChange, 2)
),
font_size=60,gerty_type=gerty.type
font_size=60,
gerty_type=gerty.type,
)
)
areas.append(text)
@ -137,55 +176,106 @@ async def get_mining_dashboard(gerty):
return areas
async def get_lightning_stats(gerty):
data = await get_mempool_info("statistics", gerty)
areas = []
text = []
text.append(get_text_item_dict(text="Channel Count", font_size=12, gerty_type=gerty.type))
text.append(get_text_item_dict(text=format_number(data["latest"]["channel_count"]), font_size=20, gerty_type=gerty.type))
text.append(
get_text_item_dict(text="Channel Count", font_size=12, gerty_type=gerty.type)
)
text.append(
get_text_item_dict(
text=format_number(data["latest"]["channel_count"]),
font_size=20,
gerty_type=gerty.type,
)
)
difference = get_percent_difference(
current=data["latest"]["channel_count"],
previous=data["previous"]["channel_count"],
)
text.append(get_text_item_dict(text="{0} in last 7 days".format(difference), font_size=12, gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="{0} in last 7 days".format(difference),
font_size=12,
gerty_type=gerty.type,
)
)
areas.append(text)
text = []
text.append(get_text_item_dict(text="Number of Nodes", font_size=12,gerty_type=gerty.type))
text.append(get_text_item_dict(text=format_number(data["latest"]["node_count"]), font_size=20,gerty_type=gerty.type))
text.append(
get_text_item_dict(text="Number of Nodes", font_size=12, gerty_type=gerty.type)
)
text.append(
get_text_item_dict(
text=format_number(data["latest"]["node_count"]),
font_size=20,
gerty_type=gerty.type,
)
)
difference = get_percent_difference(
current=data["latest"]["node_count"], previous=data["previous"]["node_count"]
)
text.append(get_text_item_dict(text="{0} in last 7 days".format(difference), font_size=12,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="{0} in last 7 days".format(difference),
font_size=12,
gerty_type=gerty.type,
)
)
areas.append(text)
text = []
text.append(get_text_item_dict(text="Total Capacity", font_size=12,gerty_type=gerty.type))
text.append(
get_text_item_dict(text="Total Capacity", font_size=12, gerty_type=gerty.type)
)
avg_capacity = float(data["latest"]["total_capacity"]) / float(100000000)
text.append(
get_text_item_dict(text="{0} BTC".format(format_number(avg_capacity, 2)), font_size=20,gerty_type=gerty.type)
get_text_item_dict(
text="{0} BTC".format(format_number(avg_capacity, 2)),
font_size=20,
gerty_type=gerty.type,
)
)
difference = get_percent_difference(
current=data["latest"]["total_capacity"],
previous=data["previous"]["total_capacity"],
)
text.append(get_text_item_dict(text="{0} in last 7 days".format(difference), font_size=12,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="{0} in last 7 days".format(difference),
font_size=12,
gerty_type=gerty.type,
)
)
areas.append(text)
text = []
text.append(get_text_item_dict(text="Average Channel Capacity", font_size=12,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="{0} sats".format(format_number(data["latest"]["avg_capacity"])), font_size=20,gerty_type=gerty.type
text="Average Channel Capacity", font_size=12, gerty_type=gerty.type
)
)
text.append(
get_text_item_dict(
text="{0} sats".format(format_number(data["latest"]["avg_capacity"])),
font_size=20,
gerty_type=gerty.type,
)
)
difference = get_percent_difference(
current=data["latest"]["avg_capacity"],
previous=data["previous"]["avg_capacity"],
)
text.append(get_text_item_dict(text="{0} in last 7 days".format(difference), font_size=12, gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="{0} in last 7 days".format(difference),
font_size=12,
gerty_type=gerty.type,
)
)
areas.append(text)
return areas
@ -244,21 +334,52 @@ async def get_mining_stat(stat_slug: str, gerty):
text = []
if stat_slug == "mining_current_hash_rate":
stat = await api_get_mining_stat(stat_slug, gerty)
current = "{0}hash".format(si_format(stat['current'], 6, True, " "))
text.append(get_text_item_dict(text="Current Mining Hashrate", font_size=20,gerty_type=gerty.type))
text.append(get_text_item_dict(text=current, font_size=40,gerty_type=gerty.type))
current = "{0}hash".format(si_format(stat["current"], 6, True, " "))
text.append(
get_text_item_dict(
text="Current Mining Hashrate", font_size=20, gerty_type=gerty.type
)
)
text.append(
get_text_item_dict(text=current, font_size=40, gerty_type=gerty.type)
)
# compare vs previous time period
difference = get_percent_difference(current=stat['current'], previous=stat['1w'])
text.append(get_text_item_dict(text="{0} in last 7 days".format(difference), font_size=12,gerty_type=gerty.type))
difference = get_percent_difference(
current=stat["current"], previous=stat["1w"]
)
text.append(
get_text_item_dict(
text="{0} in last 7 days".format(difference),
font_size=12,
gerty_type=gerty.type,
)
)
elif stat_slug == "mining_current_difficulty":
stat = await api_get_mining_stat(stat_slug, gerty)
text.append(get_text_item_dict(text="Current Mining Difficulty", font_size=20,gerty_type=gerty.type))
text.append(get_text_item_dict(text=format_number(stat['current']), font_size=40,gerty_type=gerty.type))
difference = get_percent_difference(current=stat['current'], previous=stat['previous'])
text.append(get_text_item_dict(text="{0} since last adjustment".format(difference), font_size=12,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="Current Mining Difficulty", font_size=20, gerty_type=gerty.type
)
)
text.append(
get_text_item_dict(
text=format_number(stat["current"]), font_size=40, gerty_type=gerty.type
)
)
difference = get_percent_difference(
current=stat["current"], previous=stat["previous"]
)
text.append(
get_text_item_dict(
text="{0} since last adjustment".format(difference),
font_size=12,
gerty_type=gerty.type,
)
)
# text.append(get_text_item_dict("Required threshold for mining proof-of-work", 12))
return text
async def api_get_mining_stat(stat_slug: str, gerty):
stat = ""
if stat_slug == "mining_current_hash_rate":
@ -266,20 +387,23 @@ async def api_get_mining_stat(stat_slug: str, gerty):
r = await get_mempool_info("hashrate_1m", gerty)
data = r
stat = {}
stat['current'] = data['currentHashrate']
stat['1w'] = data['hashrates'][len(data['hashrates']) - 7]['avgHashrate']
stat["current"] = data["currentHashrate"]
stat["1w"] = data["hashrates"][len(data["hashrates"]) - 7]["avgHashrate"]
elif stat_slug == "mining_current_difficulty":
async with httpx.AsyncClient() as client:
r = await get_mempool_info("hashrate_1m", gerty)
data = r
stat = {}
stat['current'] = data['currentDifficulty']
stat['previous'] = data['difficulty'][len(data['difficulty']) - 2]['difficulty']
stat["current"] = data["currentDifficulty"]
stat["previous"] = data["difficulty"][len(data["difficulty"]) - 2][
"difficulty"
]
return stat
###########################################
async def get_satoshi():
maxQuoteLength = 186
with open(os.path.join(LNBITS_PATH, "extensions/gerty/static/satoshi.json")) as fd:
@ -292,6 +416,7 @@ async def get_satoshi():
else:
return quote
# Get a screen slug by its position in the screens_list
def get_screen_slug_by_index(index: int, screens_list):
if index <= len(screens_list) - 1:
@ -314,8 +439,20 @@ async def get_screen_data(screen_num: int, screens_list: dict, gerty):
wallets = await get_lnbits_wallet_balances(gerty)
text = []
for wallet in wallets:
text.append(get_text_item_dict(text="{0}'s Wallet".format(wallet['name']), font_size=20,gerty_type=gerty.type))
text.append(get_text_item_dict(text="{0} sats".format(format_number(wallet['balance'])), font_size=40,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="{0}'s Wallet".format(wallet["name"]),
font_size=20,
gerty_type=gerty.type,
)
)
text.append(
get_text_item_dict(
text="{0} sats".format(format_number(wallet["balance"])),
font_size=40,
gerty_type=gerty.type,
)
)
areas.append(text)
elif screen_slug == "fun_satoshi_quotes":
areas.append(await get_satoshi_quotes(gerty))
@ -325,7 +462,13 @@ async def get_screen_data(screen_num: int, screens_list: dict, gerty):
areas.append(await get_onchain_stat(screen_slug, gerty))
elif screen_slug == "onchain_block_height":
text = []
text.append(get_text_item_dict(text=format_number(await get_mempool_info("tip_height", gerty)), font_size=80, gerty_type=gerty.type))
text.append(
get_text_item_dict(
text=format_number(await get_mempool_info("tip_height", gerty)),
font_size=80,
gerty_type=gerty.type,
)
)
areas.append(text)
elif screen_slug == "onchain_difficulty_retarget_date":
areas.append(await get_onchain_stat(screen_slug, gerty))
@ -364,34 +507,68 @@ async def get_dashboard(gerty):
# XC rate
text = []
amount = await satoshis_amount_as_fiat(100000000, gerty.exchange)
text.append(get_text_item_dict(text=format_number(amount), font_size=40,gerty_type=gerty.type))
text.append(get_text_item_dict(text="BTC{0} price".format(gerty.exchange), font_size=15,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text=format_number(amount), font_size=40, gerty_type=gerty.type
)
)
text.append(
get_text_item_dict(
text="BTC{0} price".format(gerty.exchange),
font_size=15,
gerty_type=gerty.type,
)
)
areas.append(text)
# balance
text = []
wallets = await get_lnbits_wallet_balances(gerty)
text = []
for wallet in wallets:
text.append(get_text_item_dict(text="{0}".format(wallet["name"]), font_size=15,gerty_type=gerty.type))
text.append(
get_text_item_dict(text="{0} sats".format(format_number(wallet["balance"])), font_size=20,gerty_type=gerty.type)
get_text_item_dict(
text="{0}".format(wallet["name"]), font_size=15, gerty_type=gerty.type
)
)
text.append(
get_text_item_dict(
text="{0} sats".format(format_number(wallet["balance"])),
font_size=20,
gerty_type=gerty.type,
)
)
areas.append(text)
# Mempool fees
text = []
text.append(get_text_item_dict(text=format_number(await get_mempool_info("tip_height", gerty)), font_size=40,gerty_type=gerty.type))
text.append(get_text_item_dict(text="Current block height", font_size=15,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text=format_number(await get_mempool_info("tip_height", gerty)),
font_size=40,
gerty_type=gerty.type,
)
)
text.append(
get_text_item_dict(
text="Current block height", font_size=15, gerty_type=gerty.type
)
)
areas.append(text)
# difficulty adjustment time
text = []
text.append(
get_text_item_dict(
text=await get_time_remaining_next_difficulty_adjustment(gerty), font_size=15,gerty_type=gerty.type
text=await get_time_remaining_next_difficulty_adjustment(gerty),
font_size=15,
gerty_type=gerty.type,
)
)
text.append(
get_text_item_dict(
text="until next difficulty adjustment", font_size=12, gerty_type=gerty.type
)
)
text.append(get_text_item_dict(text="until next difficulty adjustment", font_size=12,gerty_type=gerty.type))
areas.append(text)
return areas
@ -416,8 +593,20 @@ async def get_lnbits_wallet_balances(gerty):
async def get_placeholder_text():
return [
get_text_item_dict(text="Some placeholder text", x_pos=15, y_pos=10, font_size=50,gerty_type=gerty.type),
get_text_item_dict(text="Some placeholder text", x_pos=15, y_pos=10, font_size=50,gerty_type=gerty.type),
get_text_item_dict(
text="Some placeholder text",
x_pos=15,
y_pos=10,
font_size=50,
gerty_type=gerty.type,
),
get_text_item_dict(
text="Some placeholder text",
x_pos=15,
y_pos=10,
font_size=50,
gerty_type=gerty.type,
),
]
@ -427,10 +616,18 @@ async def get_satoshi_quotes(gerty):
quote = await get_satoshi()
if quote:
if quote["text"]:
text.append(get_text_item_dict(text=quote["text"], font_size=15,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text=quote["text"], font_size=15, gerty_type=gerty.type
)
)
if quote["date"]:
text.append(
get_text_item_dict(text="Satoshi Nakamoto - {0}".format(quote["date"]), font_size=15,gerty_type=gerty.type)
get_text_item_dict(
text="Satoshi Nakamoto - {0}".format(quote["date"]),
font_size=15,
gerty_type=gerty.type,
)
)
return text
@ -445,44 +642,91 @@ async def get_exchange_rate(gerty):
price = format_number(amount)
text.append(
get_text_item_dict(
text="Current {0}/BTC price".format(gerty.exchange), font_size=15,gerty_type=gerty.type
text="Current {0}/BTC price".format(gerty.exchange),
font_size=15,
gerty_type=gerty.type,
)
)
text.append(get_text_item_dict(text=price, font_size=80,gerty_type=gerty.type))
text.append(
get_text_item_dict(text=price, font_size=80, gerty_type=gerty.type)
)
except:
pass
return text
async def get_onchain_stat(stat_slug: str, gerty):
text = []
if (
stat_slug == "onchain_difficulty_epoch_progress" or
stat_slug == "onchain_difficulty_retarget_date" or
stat_slug == "onchain_difficulty_blocks_remaining" or
stat_slug == "onchain_difficulty_epoch_time_remaining"
stat_slug == "onchain_difficulty_epoch_progress"
or stat_slug == "onchain_difficulty_retarget_date"
or stat_slug == "onchain_difficulty_blocks_remaining"
or stat_slug == "onchain_difficulty_epoch_time_remaining"
):
async with httpx.AsyncClient() as client:
r = await get_mempool_info("difficulty_adjustment", gerty)
if stat_slug == "onchain_difficulty_epoch_progress":
stat = round(r['progressPercent'])
text.append(get_text_item_dict(text="Progress through current difficulty epoch", font_size=15,gerty_type=gerty.type))
text.append(get_text_item_dict(text="{0}%".format(stat), font_size=80,gerty_type=gerty.type))
stat = round(r["progressPercent"])
text.append(
get_text_item_dict(
text="Progress through current difficulty epoch",
font_size=15,
gerty_type=gerty.type,
)
)
text.append(
get_text_item_dict(
text="{0}%".format(stat), font_size=80, gerty_type=gerty.type
)
)
elif stat_slug == "onchain_difficulty_retarget_date":
stat = r['estimatedRetargetDate']
stat = r["estimatedRetargetDate"]
dt = datetime.fromtimestamp(stat / 1000).strftime("%e %b %Y at %H:%M")
text.append(get_text_item_dict(text="Date of next difficulty adjustment", font_size=15,gerty_type=gerty.type))
text.append(get_text_item_dict(text=dt, font_size=40,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="Date of next difficulty adjustment",
font_size=15,
gerty_type=gerty.type,
)
)
text.append(
get_text_item_dict(text=dt, font_size=40, gerty_type=gerty.type)
)
elif stat_slug == "onchain_difficulty_blocks_remaining":
stat = r['remainingBlocks']
text.append(get_text_item_dict(text="Blocks until next difficulty adjustment", font_size=15,gerty_type=gerty.type))
text.append(get_text_item_dict(text="{0}".format(format_number(stat)), font_size=80,gerty_type=gerty.type))
stat = r["remainingBlocks"]
text.append(
get_text_item_dict(
text="Blocks until next difficulty adjustment",
font_size=15,
gerty_type=gerty.type,
)
)
text.append(
get_text_item_dict(
text="{0}".format(format_number(stat)),
font_size=80,
gerty_type=gerty.type,
)
)
elif stat_slug == "onchain_difficulty_epoch_time_remaining":
stat = r['remainingTime']
text.append(get_text_item_dict(text="Time until next difficulty adjustment", font_size=15,gerty_type=gerty.type))
text.append(get_text_item_dict(text=get_time_remaining(stat / 1000, 4), font_size=20,gerty_type=gerty.type))
stat = r["remainingTime"]
text.append(
get_text_item_dict(
text="Time until next difficulty adjustment",
font_size=15,
gerty_type=gerty.type,
)
)
text.append(
get_text_item_dict(
text=get_time_remaining(stat / 1000, 4),
font_size=20,
gerty_type=gerty.type,
)
)
return text
async def get_onchain_dashboard(gerty):
areas = []
if isinstance(gerty.mempool_endpoint, str):
@ -490,27 +734,61 @@ async def get_onchain_dashboard(gerty):
r = await get_mempool_info("difficulty_adjustment", gerty)
text = []
stat = round(r["progressPercent"])
text.append(get_text_item_dict(text="Progress through epoch", font_size=12,gerty_type=gerty.type))
text.append(get_text_item_dict(text="{0}%".format(stat), font_size=60,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="Progress through epoch", font_size=12, gerty_type=gerty.type
)
)
text.append(
get_text_item_dict(
text="{0}%".format(stat), font_size=60, gerty_type=gerty.type
)
)
areas.append(text)
text = []
stat = r["estimatedRetargetDate"]
dt = datetime.fromtimestamp(stat / 1000).strftime("%e %b %Y at %H:%M")
text.append(get_text_item_dict(text="Date of next adjustment", font_size=12,gerty_type=gerty.type))
text.append(get_text_item_dict(text=dt, font_size=20,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="Date of next adjustment", font_size=12, gerty_type=gerty.type
)
)
text.append(
get_text_item_dict(text=dt, font_size=20, gerty_type=gerty.type)
)
areas.append(text)
text = []
stat = r["remainingBlocks"]
text.append(get_text_item_dict(text="Blocks until adjustment", font_size=12,gerty_type=gerty.type))
text.append(get_text_item_dict(text="{0}".format(format_number(stat)), font_size=60,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="Blocks until adjustment", font_size=12, gerty_type=gerty.type
)
)
text.append(
get_text_item_dict(
text="{0}".format(format_number(stat)),
font_size=60,
gerty_type=gerty.type,
)
)
areas.append(text)
text = []
stat = r["remainingTime"]
text.append(get_text_item_dict(text="Time until adjustment", font_size=12,gerty_type=gerty.type))
text.append(get_text_item_dict(text=get_time_remaining(stat / 1000, 4), font_size=20,gerty_type=gerty.type))
text.append(
get_text_item_dict(
text="Time until adjustment", font_size=12, gerty_type=gerty.type
)
)
text.append(
get_text_item_dict(
text=get_time_remaining(stat / 1000, 4),
font_size=20,
gerty_type=gerty.type,
)
)
areas.append(text)
return areas
@ -531,9 +809,19 @@ async def get_mempool_stat(stat_slug: str, gerty):
r = get_mempool_info("mempool", gerty)
if stat_slug == "mempool_tx_count":
stat = round(r["count"])
text.append(get_text_item_dict(text="Transactions in the mempool", font_size=15,gerty_type=gerty.type))
text.append(
get_text_item_dict(text="{0}".format(format_number(stat)), font_size=80,gerty_type=gerty.type)
get_text_item_dict(
text="Transactions in the mempool",
font_size=15,
gerty_type=gerty.type,
)
)
text.append(
get_text_item_dict(
text="{0}".format(format_number(stat)),
font_size=80,
gerty_type=gerty.type,
)
)
elif stat_slug == "mempool_recommended_fees":
y_offset = 60
@ -541,7 +829,9 @@ async def get_mempool_stat(stat_slug: str, gerty):
pos_y = 80 + y_offset
text.append(get_text_item_dict("mempool.space", 40, 160, pos_y, gerty.type))
pos_y = 180 + y_offset
text.append(get_text_item_dict("Recommended Tx Fees", 20, 240, pos_y, gerty.type))
text.append(
get_text_item_dict("Recommended Tx Fees", 20, 240, pos_y, gerty.type)
)
pos_y = 280 + y_offset
text.append(
@ -571,7 +861,7 @@ async def get_mempool_stat(stat_slug: str, gerty):
font_size=font_size,
x_pos=30,
y_pos=pos_y,
gerty_type=gerty.type
gerty_type=gerty.type,
)
)
@ -586,7 +876,7 @@ async def get_mempool_stat(stat_slug: str, gerty):
font_size=font_size,
x_pos=235,
y_pos=pos_y,
gerty_type=gerty.type
gerty_type=gerty.type,
)
)
@ -601,7 +891,7 @@ async def get_mempool_stat(stat_slug: str, gerty):
font_size=font_size,
x_pos=460,
y_pos=pos_y,
gerty_type=gerty.type
gerty_type=gerty.type,
)
)
@ -616,7 +906,7 @@ async def get_mempool_stat(stat_slug: str, gerty):
font_size=font_size,
x_pos=750,
y_pos=pos_y,
gerty_type=gerty.type
gerty_type=gerty.type,
)
)
return text
@ -628,13 +918,14 @@ def get_date_suffix(dayNumber):
else:
return ["st", "nd", "rd"][dayNumber % 10 - 1]
def get_time_remaining(seconds, granularity=2):
intervals = (
# ('weeks', 604800), # 60 * 60 * 24 * 7
('days', 86400), # 60 * 60 * 24
('hours', 3600), # 60 * 60
('minutes', 60),
('seconds', 1),
("days", 86400), # 60 * 60 * 24
("hours", 3600), # 60 * 60
("minutes", 60),
("seconds", 1),
)
result = []
@ -644,6 +935,6 @@ def get_time_remaining(seconds, granularity=2):
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
name = name.rstrip("s")
result.append("{} {}".format(round(value), name))
return ', '.join(result[:granularity])
return ", ".join(result[:granularity])

View file

@ -24,6 +24,7 @@ async def m002_add_utc_offset_col(db):
"""
await db.execute("ALTER TABLE gerty.gertys ADD COLUMN utc_offset INT;")
async def m003_add_gerty_model_col(db):
"""
support for Gerty model col
@ -33,6 +34,7 @@ async def m003_add_gerty_model_col(db):
#########MEMPOOL MIGRATIONS########
async def m004_initial(db):
"""
Initial Gertys table.
@ -40,6 +42,7 @@ async def m004_initial(db):
await db.execute(
"""
CREATE TABLE gerty.mempool (
mempool_endpoint TEXT PRIMARY KEY,
endpoint TEXT NOT NULL,
data TEXT NOT NULL,
time TIMESTAMP

View file

@ -27,6 +27,7 @@ class Gerty(BaseModel):
#########MEMPOOL MODELS###########
class MempoolEndpoint(BaseModel):
fees_recommended: str = "/api/v1/fees/recommended"
hashrate_1w: str = "/api/v1/mining/hashrate/1w"
@ -36,7 +37,9 @@ class MempoolEndpoint(BaseModel):
tip_height: str = "/api/blocks/tip/height"
mempool: str = "/api/mempool"
class Mempool(BaseModel):
mempool_endpoint: str = Query(None)
endpoint: str = Query(None)
data: str = Query(None)
time: int = Query(None)

View file

@ -1,4 +1,5 @@
{% extends "base.html" %} {% from "macros.jinja" import window_vars with context %} {% block page %}
{% extends "base.html" %} {% from "macros.jinja" import window_vars with context
%} {% block page %}
<div class="row q-col-gutter-md">
<div class="col-12 col-md-8 col-lg-7 q-gutter-y-md">
<q-card>
@ -127,15 +128,42 @@
label="Name"
placeholder="Son of Gerty"
></q-input>
<p>Use the toggles below to control what your Gerty will display</p>
<div class="column">
<div class="col">
<q-toggle
v-model="formDialog.data.display_preferences.fun_satoshi_quotes"
label="Satoshi Quotes"
>
<q-tooltip>Displays random quotes from Satoshi</q-tooltip>
</q-toggle>
</div>
<div class="col">
<q-toggle
v-model="formDialog.data.display_preferences.fun_exchange_market_rate"
label="Fiat to BTC price"
></q-toggle>
<q-select
v-if="formDialog.data.display_preferences.fun_exchange_market_rate"
filled
dense
emit-value
v-model="formDialog.data.type"
:options="['Gerty', 'Mini Gerty']"
label="Gerty Type *"
v-model="formDialog.data.exchange"
:options="currencyOptions"
label="Exchange rate"
></q-select>
</div>
<div class="col">
<q-toggle
v-model="formDialog.data.display_preferences.lnbits_wallets_balance"
label="Show LNbits wallet balances"
@input="setWallets"
></q-toggle>
<q-select
v-if="formDialog.data.display_preferences.lnbits_wallets_balance"
filled
multiple
dense
@ -150,24 +178,127 @@
>
<q-tooltip>Hit enter to add values</q-tooltip>
</q-select>
<q-select
filled
dense
emit-value
v-model="formDialog.data.exchange"
:options="currencyOptions"
label="Exchange rate"
></q-select>
</div>
<div class="col">
<q-toggle
v-model="toggleStates.onchain"
label="Onchain Information"
@input="setOnchain"
>
</q-toggle>
<br />
<div class="row">
<div class="col">
<q-toggle
class="q-pl-lg"
v-if="toggleStates.onchain"
v-model="formDialog.data.display_preferences.onchain_difficulty_epoch_progress"
label="Epoch percentage"
></q-toggle>
</div>
<div class="col">
<q-toggle
class="q-pl-lg"
v-if="toggleStates.onchain"
v-model="formDialog.data.display_preferences.onchain_difficulty_retarget_date"
label="Retarget date"
></q-toggle>
</div>
</div>
<div class="row">
<div class="col">
<q-toggle
class="q-pl-lg"
v-if="toggleStates.onchain"
v-model="formDialog.data.display_preferences.onchain_difficulty_blocks_remaining"
label="Blocks until adjustment"
></q-toggle>
</div>
<div class="col">
<q-toggle
class="q-pl-lg"
v-if="toggleStates.onchain"
v-model="formDialog.data.display_preferences.onchain_difficulty_epoch_time_remaining"
label="Time until adjustment"
></q-toggle>
</div>
</div>
<q-toggle
class="q-pl-lg"
v-if="toggleStates.onchain"
v-model="formDialog.data.display_preferences.onchain_block_height"
label="Current block height"
></q-toggle>
</div>
<div class="col">
<q-toggle v-model="toggleStates.mempool" label="The Mempool">
</q-toggle>
<br />
<div class="row">
<div class="col">
<q-toggle
class="q-pl-lg"
v-model="formDialog.data.display_preferences.mempool_recommended_fees"
v-if="toggleStates.mempool"
label="Recommended fees"
></q-toggle>
</div>
<div class="col">
<q-toggle
class="q-pl-lg"
v-model="formDialog.data.display_preferences.mempool_tx_count"
v-if="toggleStates.mempool"
label="Transactions in mempool"
></q-toggle>
</div>
</div>
</div>
<div class="col">
<q-toggle
label="Mining Data"
v-model="toggleStates.mining"
@input="setMining"
></q-toggle>
<br />
<div class="row">
<div class="col">
<q-toggle
class="q-pl-lg"
v-if="toggleStates.mining"
v-model="formDialog.data.display_preferences.mining_current_hash_rate"
label="Mining hashrate"
></q-toggle>
</div>
<div class="col">
<q-toggle
class="q-pl-lg"
v-if="toggleStates.mining"
v-model="formDialog.data.display_preferences.mining_current_difficulty"
label="Mining difficulty"
></q-toggle>
</div>
</div>
</div>
<div class="col">
<q-toggle
label="*Advanced"
v-model="toggleStates.advanced"
@input="setAdvanced"
></q-toggle>
<br />
<q-input
v-if="toggleStates.advanced"
filled
dense
v-model.trim="formDialog.data.mempool_endpoint"
label="Mempool link"
>
<q-tooltip>Used for getting onchain/ln stats</q-tooltip>
</q-input>
<br />
<q-input
v-if="toggleStates.advanced"
filled
dense
v-model.trim="formDialog.data.refresh_time"
@ -175,168 +306,10 @@
>
<q-tooltip
>The amount of time in seconds between screen updates
</q-tooltip
>
</q-tooltip>
</q-input>
<q-input
filled
dense
v-model.trim="formDialog.data.utc_offset"
label="UTC Time Offset (e.g. -1)"
>
<q-tooltip>Enter a UTC time offset value (e.g. -1)</q-tooltip>
</q-input>
<p>Use the toggles below to control what your Gerty will display</p>
<q-expansion-item
v-if="!isMiniGerty"
expand-separator
icon="grid_view"
label="Dashboards"
>
<q-toggle
v-model="formDialog.data.display_preferences.dashboard"
label="LNbits Dashboard"
></q-toggle>
<q-toggle
v-model="formDialog.data.display_preferences.dashboard_onchain"
label="Onchain Dashboard"
></q-toggle>
<q-toggle
v-model="formDialog.data.display_preferences.dashboard_mining"
label="Mining Dashboard"
></q-toggle>
<q-toggle
v-model="formDialog.data.display_preferences.lightning_dashboard"
label="Lightning Network Dashboard"
></q-toggle>
</q-expansion-item>
<q-expansion-item
expand-separator
icon="pin"
label="Single Data Points"
ref="single-data-points-expansion"
>
<q-toggle
v-model="formDialog.data.display_preferences.fun_exchange_market_rate"
label="Fiat to BTC price"
></q-toggle>
<q-toggle
v-if="!isMiniGerty"
v-model="formDialog.data.display_preferences.fun_satoshi_quotes"
label="Satoshi Quotes"
>
<q-tooltip>Displays random quotes from Satoshi</q-tooltip>
</q-toggle>
<q-expansion-item
expand-separator
icon="perm_identity"
label="LNbits Wallets"
>
<q-toggle
v-model="formDialog.data.display_preferences.lnbits_wallets_balance"
label="Show LNbits wallet balances"
></q-toggle>
</q-expansion-item>
<q-expansion-item
expand-separator
icon="link"
label="Onchain Information"
>
<q-toggle
v-model="toggleStates.onchain"
label="Toggle all"
>
<q-tooltip>Toggle all</q-tooltip>
</q-toggle>
<br>
<q-toggle
v-model="formDialog.data.display_preferences.onchain_difficulty_epoch_progress"
label="Percent of current difficulty epoch complete"
></q-toggle>
<q-toggle
v-model="formDialog.data.display_preferences.onchain_difficulty_retarget_date"
label="Estimated retarget date"
></q-toggle>
<q-toggle
v-model="formDialog.data.display_preferences.onchain_difficulty_blocks_remaining"
label="Blocks until next difficulty adjustment"
></q-toggle>
<q-toggle
v-model="formDialog.data.display_preferences.onchain_difficulty_epoch_time_remaining"
label="Estimated time until next difficulty adjustment"
></q-toggle>
<q-toggle
v-model="formDialog.data.display_preferences.onchain_block_height"
label="Current block height"
></q-toggle>
</q-expansion-item>
<q-expansion-item
expand-separator
icon="psychology"
label="The Mempool"
>
<q-toggle
v-model="toggleStates.mempool"
label="Toggle all"
>
<q-tooltip>Toggle all</q-tooltip>
</q-toggle>
<br>
<q-toggle
v-model="formDialog.data.display_preferences.mempool_recommended_fees"
v-if="!isMiniGerty"
label="Recommended fees"
></q-toggle>
<q-toggle
v-model="formDialog.data.display_preferences.mempool_tx_count"
label="Number of transactions in the mempool"
></q-toggle>
</q-expansion-item>
<q-expansion-item
expand-separator
icon="money"
label="Mining Data"
>
<q-toggle
v-model="toggleStates.mining"
label="Toggle all"
>
<q-tooltip>Toggle all</q-tooltip>
</q-toggle>
<br>
<q-toggle
v-model="formDialog.data.display_preferences.mining_current_hash_rate"
label="Current mining hashrate"
></q-toggle>
<q-toggle
v-model="formDialog.data.display_preferences.mining_current_difficulty"
label="Current mining difficulty"
></q-toggle>
</q-expansion-item>
</q-expansion-item>
</div>
</div>
<div class="row q-mt-lg">
<q-btn
@ -383,11 +356,12 @@
data: function () {
return {
toggleStates: {
fun: true,
onchain: true,
mempool: true,
mining: true,
lightning: true
fun: false,
onchain: false,
mempool: false,
mining: false,
lightning: false,
advanced: false
},
oldToggleStates: {},
gertys: [],
@ -572,7 +546,7 @@
name: 'exchange',
align: 'left',
label: 'Exchange',
field: 'exchange',
field: 'exchange'
},
{
name: 'mempool_endpoint',
@ -580,8 +554,7 @@
label: 'Mempool Endpoint',
field: 'mempool_endpoint'
},
{name: 'id', align: 'left', label: 'Gerty ID', field: 'id'},
{name: 'id', align: 'left', label: 'Gerty ID', field: 'id'}
],
pagination: {
rowsPerPage: 10
@ -590,47 +563,69 @@
formDialog: {
show: false,
data: {
utc_offset: 0,
type: 'Gerty',
utc_offset: new Date().getTimezoneOffset(),
display_preferences: {
dashboard: true,
fun_satoshi_quotes: true,
fun_exchange_market_rate: true,
dashboard_onchain: true,
mempool_recommended_fees: true,
dashboard_mining: true,
lightning_dashboard: true,
onchain: true,
onchain_difficulty_epoch_progress: true,
onchain_difficulty_retarget_date: true,
onchain_difficulty_blocks_remaining: true,
onchain_difficulty_epoch_time_remaining: true,
onchain_block_height: true,
mempool_tx_count: true,
mining_current_hash_rate: true,
mining_current_difficulty: true,
lnbits_wallets_balance: true,
dashboard: false,
fun_satoshi_quotes: false,
fun_exchange_market_rate: false,
dashboard_onchain: false,
mempool_recommended_fees: false,
dashboard_mining: false,
lightning_dashboard: false,
onchain: false,
onchain_difficulty_epoch_progress: false,
onchain_difficulty_retarget_date: false,
onchain_difficulty_blocks_remaining: false,
onchain_difficulty_epoch_time_remaining: false,
onchain_block_height: false,
mempool_tx_count: false,
mining_current_hash_rate: false,
mining_current_difficulty: false,
lnbits_wallets_balance: false
},
lnbits_wallets: [],
mempool_endpoint: "https://mempool.space",
refresh_time: 300,
mempool_endpoint: 'https://mempool.space',
refresh_time: 300
}
}
}
},
mounted() {
console.log('this.formDialog', this.formDialog.data.display_preferences)
},
methods: {
setAdvanced: function(){
self = this
self.formDialog.data.mempool_endpoint = 'https://mempool.space'
self.formDialog.data.refresh_time = 300
},
setWallets: function() {
self = this
if(!self.formDialog.data.display_preferences.lnbits_wallets_balance){
self.formDialog.data.lnbits_wallets = []
}
},
setOnchain: function() {
self = this
self.formDialog.data.display_preferences.onchain_difficulty_epoch_progress = self.toggleStates.onchain
self.formDialog.data.display_preferences.onchain_difficulty_retarget_date = self.toggleStates.onchain
self.formDialog.data.display_preferences.onchain_difficulty_blocks_remaining = !self.toggleStates.onchain
self.formDialog.data.display_preferences.onchain_difficulty_epoch_time_remaining = self.toggleStates.onchain
self.formDialog.data.display_preferences.onchain_block_height = self.toggleStates.onchain
},
setMining: function() {
self = this
self.formDialog.data.display_preferences.mining_current_hash_rate = self.toggleStates.mining
self.formDialog.data.display_preferences.mining_current_difficulty = self.toggleStates.mining
},
closeFormDialog: function () {
this.formDialog.data = {
utc_offset: 0,
lnbits_wallets: [],
mempool_endpoint: "https://mempool.space",
mempool_endpoint: 'https://mempool.space',
refresh_time: 300,
type: 'Gerty',
display_preferences: {},
display_preferences: {}
}
},
getGertys: function () {
@ -655,11 +650,13 @@
this.formDialog.data.type = gerty.type
this.formDialog.data.utc_offset = gerty.utc_offset
this.formDialog.data.lnbits_wallets = JSON.parse(gerty.lnbits_wallets)
this.formDialog.data.exchange = gerty.exchange,
this.formDialog.data.mempool_endpoint = gerty.mempool_endpoint,
this.formDialog.data.refresh_time = gerty.refresh_time,
this.formDialog.data.display_preferences = JSON.parse(gerty.display_preferences),
this.formDialog.show = true
;(this.formDialog.data.exchange = gerty.exchange),
(this.formDialog.data.mempool_endpoint = gerty.mempool_endpoint),
(this.formDialog.data.refresh_time = gerty.refresh_time),
(this.formDialog.data.display_preferences = JSON.parse(
gerty.display_preferences
)),
(this.formDialog.show = true)
},
sendFormDataGerty: function () {
if (this.formDialog.data.id) {
@ -683,7 +680,9 @@
exchange: this.formDialog.data.exchange,
mempool_endpoint: this.formDialog.data.mempool_endpoint,
refresh_time: this.formDialog.data.refresh_time,
display_preferences: JSON.stringify(this.formDialog.data.display_preferences)
display_preferences: JSON.stringify(
this.formDialog.data.display_preferences
)
}
var self = this
@ -706,15 +705,14 @@
var self = this
data.utc_offset = this.formDialog.data.utc_offset
data.type = this.formDialog.data.type
data.lnbits_wallets = JSON.stringify(this.formDialog.data.lnbits_wallets)
data.display_preferences = JSON.stringify(this.formDialog.data.display_preferences)
LNbits.api
.request(
'PUT',
'/gerty/api/v1/gerty/' + data.id,
wallet,
data
data.lnbits_wallets = JSON.stringify(
this.formDialog.data.lnbits_wallets
)
data.display_preferences = JSON.stringify(
this.formDialog.data.display_preferences
)
LNbits.api
.request('PUT', '/gerty/api/v1/gerty/' + data.id, wallet, data)
.then(function (response) {
self.gertys = _.reject(self.gertys, function (obj) {
return obj.id == data.id
@ -755,7 +753,7 @@
},
computed: {
isMiniGerty() {
return (this.formDialog.data.type == 'Mini Gerty')
return this.formDialog.data.type == 'Mini Gerty'
}
},
created: function () {
@ -767,22 +765,26 @@
'formDialog.data.type': {
handler(value) {
if (value == 'Mini Gerty') {
this.formDialog.data.display_preferences.dashboard = false;
this.formDialog.data.display_preferences.dashboard_onchain = false;
this.formDialog.data.display_preferences.dashboard_mining = false;
this.formDialog.data.display_preferences.lightning_dashboard = false;
this.formDialog.data.display_preferences.fun_satoshi_quotes = false;
this.formDialog.data.display_preferences.mempool_recommended_fees = false;
this.formDialog.data.display_preferences.onchain = false;
this.formDialog.data.display_preferences.dashboard = false
this.formDialog.data.display_preferences.dashboard_onchain = false
this.formDialog.data.display_preferences.dashboard_mining = false
this.formDialog.data.display_preferences.lightning_dashboard = false
this.formDialog.data.display_preferences.fun_satoshi_quotes = false
this.formDialog.data.display_preferences.mempool_recommended_fees = false
this.formDialog.data.display_preferences.onchain = false
}
}
},
toggleStates: {
handler(toggleStatesValue) {
// Switch all the toggles in each section to the relevant state
for (const [toggleKey, toggleValue] of Object.entries(toggleStatesValue)) {
for (const [toggleKey, toggleValue] of Object.entries(
toggleStatesValue
)) {
if (this.oldToggleStates[toggleKey] !== toggleValue) {
for (const [dpKey, dpValue] of Object.entries(this.formDialog.data.display_preferences)) {
for (const [dpKey, dpValue] of Object.entries(
this.formDialog.data.display_preferences
)) {
if (dpKey.indexOf(toggleKey) === 0) {
this.formDialog.data.display_preferences[dpKey] = toggleValue
}

View file

@ -28,12 +28,13 @@ from .crud import (
get_gerty,
get_gertys,
update_gerty,
get_mempool_info
get_mempool_info,
)
from .helpers import *
from .models import Gerty, MempoolEndpoint
@gerty_ext.get("/api/v1/gerty", status_code=HTTPStatus.OK)
async def api_gertys(
all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type)
@ -145,39 +146,46 @@ async def api_gerty_json(gerty_id: str, p: int = None): # page number
},
}
###########CACHED MEMPOOL##############
@gerty_ext.get("/api/v1/gerty/fees-recommended/{gerty_id}")
async def api_gerty_get_fees_recommended(gerty_id):
gerty = await get_gerty(gerty_id)
return await get_mempool_info("fees_recommended", gerty)
@gerty_ext.get("/api/v1/gerty/hashrate-1w/{gerty_id}")
async def api_gerty_get_hashrate_1w(gerty_id):
gerty = await get_gerty(gerty_id)
return await get_mempool_info("hashrate_1w", gerty)
@gerty_ext.get("/api/v1/gerty/hashrate-1m/{gerty_id}")
async def api_gerty_get_hashrate_1m(gerty_id):
gerty = await get_gerty(gerty_id)
return await get_mempool_info("hashrate_1m", gerty)
@gerty_ext.get("/api/v1/gerty/statistics/{gerty_id}")
async def api_gerty_get_statistics(gerty_id):
gerty = await get_gerty(gerty_id)
return await get_mempool_info("statistics", gerty)
@gerty_ext.get("/api/v1/gerty/difficulty-adjustment/{gerty_id}")
async def api_gerty_get_difficulty_adjustment(gerty_id):
gerty = await get_gerty(gerty_id)
return await get_mempool_info("difficulty_adjustment", gerty)
@gerty_ext.get("/api/v1/gerty/tip-height/{gerty_id}")
async def api_gerty_get_tip_height(gerty_id):
gerty = await get_gerty(gerty_id)
return await get_mempool_info("tip_height", gerty)
@gerty_ext.get("/api/v1/gerty/mempool/{gerty_id}")
async def api_gerty_get_mempool(gerty_id):
gerty = await get_gerty(gerty_id)