Files
nym/documentation/scripts/api-scraping/api_targets.py
T
mx d6599b2933 [DOCs]: New docs framework (#5017)
* started todo list for rework

* startd long todo list

* startd long todo list

* remove ts docs from ts sdk dir

* started new docs draft

* rearranged code example dir structure

* modified code component filepaths

* first pass rust sdk

* small shift typescript org

* updated todo list

* consolidating images folders in one place

* first pass @ operator docs

* gen updates

* sdk in its own dir

* first pass developers structure

* first pass network structure

* structure

* add licensing

* moved old docs -> old_docs dir for clarity when devving

* moving around new docs - think this is the final dir structure

* updated todo list

* new autodoc version (#4781)

* Update rework_todo.md

* quick first sketch of landing page

* rework of structure of developers

* added arch and concepts stubs

* add new bits to todo list

* new list

* tweak to overview

* mixnet node overview

* tweak overview

* first pass new arch

* first pass concepts

* first pass traffic

* more network docs

* moved some chain files to the dev portal stubs

* removed old reference to archive

* note to client

* concepts 2nd pass

* crypto first proper pass, sphinx

* stub for not p2p

* structure change

* traffic 2nd pass

* misc

* hid root index

* overhaul arch

* overhaul arch

* add links + tweaks

* update todo list

* updating nyx section

* added zknym docs

* added zknym docs

* note on where to find deployed info

* smart contracts done

* started moving integrations docs over from ts sdk

* pass @ integration page

* todo for the tldr overview

* added ffi stub files

* updated todo list

* move sdks to developers

* initial pass at new clients overview for developers

* rework intro

* add echo serv to tools

* sidebar autocollapse

* integration overview work + tools

* concepts overview for devporta

* stub

* more for networking pages

* added to concepts in dev portal

* updated arch

* crypto overview page

* typo fix

* add credential stub

* first pass concepts done

* start reorg of rust sdk docs

* reorg + added FFI table

* added no scroll to inline code

* finished ffi overview page

* first pass @ rest of rust sdk doc

* first pass ffi

* tweaks

* added testnet example + note to custom topology example overview

* stripped unnecessary stuff from TS

* tweaks to ffi

* updated faq

* first pass tcpproxy

* commit before moving image dir

* moved images/ to correct place

* started on client redo

* chain first pass

* moved cli wallet out of tools

* first pass new ws client

* new chain info, left todo links in

* links

* more links

* chain registry

* added echo server to tools

* rust sdk links

* ts sdk links

* final linkchecks

* redo acks diagram as mermaid

* add mermaid flow diagram

* added links for codecs + full flow diagram

* removed todo

* remove forced dark mode

* diagram + concepts overview

* small correction re tcpproxy ffi

* remove diagram title

* new sock5 diagram, minor client docs tweaks

* diagrams

* change order in list

* added note for standalone: can be accessed via sdk

* tweaks

* replaced old diagram with mermaid

* fixed link

* hardcoded import version for the moment

* update deps

* remove test component

* recreated tools dir

* remove tools dir moved to wrong palce

* prebuild and predev script for autodoc commands

* make script own command instead of prebuild

* made code blocks sh

* updated autogenerated docs

* temp

* auto commit generated command files

* add link to autodoc generated files

* updated autodoc for committing changing else exit

* auto commit generated command files

* updated readme

* make subcommand headers smaller

* removed mdbook related scripts

* update readme

* update readme

* removed backups of root meta.json

* cherry pick yana commits + some extra config in theme

* update readme

* update theme: width of page and padding

* some more themeing

* changed erroneous note

* docs redirects first pass

* tweaking

* new pages + rest of redirects for old docs/

* brought in archive + done rewrites for devportal

* cherry pick yana landingpage

* tweaked landing page component

* changed theme of mermaid diagram to match everything else

* updated todo list

* [DOCs]: Operators rework to next.js (#4930)

* initialise operators guides v2

* new introduction page

* add variables csv and page

* add baseurl to allow short path

* add sandbox page

* added building from source page

* add binary pages

* add preliminary steps

* clean preliminary steps dir

* syntax edit

* syntax edit

* add configuration page

* create new proxy configuration page

* create new proxy configuration page

* create bonding.mdx page

* correct images path

* syntax edit

* add new validator setup page

* add api setup page

* add nyx configuration page

* add nym node and maintenance pages

* finish maintenance and add nymvisor conf page

* add manual upgrade page

* add nymvisor upgrade page

* add performance testing page and dir

* add node api check page

* add explore nym scripts page

* add testing pages

* fix menu issue by moving snippets to coomponents

* add all troubleshooting pages

* add general faq page

* add nym node faq page

* add nyx faq page

* revamp legal forum to community counsel and add all pages

* rewire relative paths to new structure

* simplify setup and remove lock file

* syntax fix

* rm package.json

* re add package.json, rm package-lock.json

* removed old books from commit

* address review comments

---------

Co-authored-by: mfahampshire <maxhampshire@pm.me>
Co-authored-by: mx <33262279+mfahampshire@users.noreply.github.com>

* tweak client links

* also moved matrix images to correct place

* Max/fix links new docs framework (#4989)

* tweak client links
* standardise images in public/
* old images move to public/archive

* rename overview to more descriptive

* links (#4990)

* links
* removed todos
* updated todo list

* minor themeing

* operator redirects

* pick yana's edits: remove specified callout theming

* added todo comments for old ts sdk redirects

* [new/docs/operators]: Create archive section - PR ready to merge (#5004)

* [new-docs/operators] : Fix callout syntax (#5006)

* fix callout syntax from color to type

* correct callout from danger to warning

* update footer

* updated footer

* finalised rewrites

* tweaks to clients and reintroduced old examples page

* update todo

* Max/individual command autodocs (#5015)


* auto commit generated command files

* added to autodoc.sh: build all binaries before running

* autodoc move individual command outputs to components

* Max/individual command autodocs (#5018)


* updated autodoc script

* updated autodoc script for fix + reintroduced gitignore file for generated markdown

* auto commit generated command files

* auto commit generated command files

* added command-outputs to autodoc script

* fix merge conflicts

* repush components

* remove old docs dirs

* auto commit generated command files

* auto commit generated command files

* updated messages paradigm with the standalone proxies

* [NEW-DOCs/operators]: Command output, accordion, api scraping & all final tasks (#5026)

* add custom scripts, create prebuild to import data to pages

* update after latest prebuild

* auto commit generated command files

* add accordion component

* add changbelog page

* add node_api_check outputs

* finish all command outputs

* more accordions beautifications

* finish accordion

* PR ready to go

* address review comments

---------

Co-authored-by: mfahampshire <maxhampshire@pm.me>

* Adjust padding

* Fix responsive design

* cherry pick yana landingpage flex update

* reremove old docs

* added dependencies to readme

* pushing build attempt changes

* fix merge errors, path errors, dump uselss dinosaurs - BUILT THE F*N DOCS w success

* moved prebuild to its own script

* generate timenow

* auto commit generated command files

* remove comment

* auto commit generated command files

* auto commit generated command files

* auto commit generated command files

* build from new configs

* add mdx type as explicit dep

* remove rc from version in package

* change predev script

* update readme with scripts

* update general info

* add license

* auto commit generated command files

* add updated components

* removed old examples page for the moment

* remove old list will reintroduce hidden behind gitignore for future

* reintroduce todo list behind gitignore

* added standalone tcpproxy binary info

* nothing change for redeploy test

* make build standalone

* updated readme

* working on new cd

* remove export

* updated ci/cd for docs

* added ci script for dist

* hide text on laptop wide screen

* add pnpm to ci/cd

* add pnpm version to ci/cd

* add default dir to ci/cd

* change path to script

* update projct name ci

* lint ci branch ignore

* add basePath to next.config.js

* update doc rewrites

* revert basePath addition

* update basePath

* add mobile styles

* fix responsive style

* remove old ts sdk docs workflow

* temp remove autodoc from workspace

* update sidebar for clarity: crypto = cryptography

* ignore documentation in pr-validation workflow

---------

Co-authored-by: Yana <yanok87@users.noreply.github.com>
Co-authored-by: import this <97586125+serinko@users.noreply.github.com>
Co-authored-by: fmtabbara <fmtabbara@hotmail.co.uk>
2024-11-04 11:42:56 +00:00

338 lines
10 KiB
Python

#!/usr/bin/python3
import argparse
import os
import requests
import json
import sys
import pandas as pd
from collections import namedtuple
from time import gmtime, strftime
import time
############################################
############## GENERAL FNs #################
############################################
def get_url(args, **kwargs):
config_file = "./api_targets_config.json"
with open(config_file, "r") as f:
config = json.load(f)
env = args.api
endpoint = args.endpoint
if env == "github":
url = f"{config[env]}/{endpoint}"
else:
url = f"{config[env]}/api/v1/{endpoint}"
return url
def subparser_read(args):
url = get_url(args)
r = requests.get(url)
response = r.json()
return response
def print_time_now(args):
#now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#now = time.ctime()
day = strftime("%d", gmtime())
if day[0] == "0":
day = day[1]
if day == "1" or day == "21" or day == "31":
suffix = "st"
elif day == "2" or day == "22":
suffix = "nd"
elif day == "3" or day == "23":
suffix = "rd"
else:
suffix = "th"
now = strftime(f"%A, %B {day}{suffix} %Y, %X UTC", gmtime())
print(now)
############################################
########### NYX RELATED FNs ################
############################################
def convert_u_nym(unym):
unym = float(unym)
nym = unym / 1000000
nym = int(nym)
return nym
def thousand_separator(n, separator):
if separator == " ":
n = f'{n:_}'
n = remove_underscore(n)
else:
n = f'{n:{separator}}'
return n
def remove_underscore(arg):
string = arg.replace("_", " ")
string = string.title()
return string
def display_supply_table(response, args):
separator = args.separator
df = pd.DataFrame(response)
df = df.T
del df['denom']
# df.set_axis(['**Item**', '**Amount in NYM**'], axis=1, inplace=True)
df = df.rename_axis('index1').reset_index()
df = df.rename(columns={'index1': '**Item**', 'amount': '**Amount in NYM**'})
df['**Item**'] = df['**Item**'].apply(remove_underscore)
df['**Amount in NYM**'] = df['**Amount in NYM**'].apply(convert_u_nym)
desc_column = _get_desc_column()
df.insert(1, '**Description**', desc_column, True)
stake_saturation = _get_stake_saturation()
df.loc[len(df.index)] = ['Stake Saturation', 'Optimal size of node self-bond + delegation', stake_saturation]
df['**Amount in NYM**'] = df['**Amount in NYM**'].apply(thousand_separator, args=(separator, ))
table = df.to_markdown(index=False,colalign=("left","left","right"))
print(table)
def _get_stake_saturation():
reward_params = get_api("https://validator.nymtech.net/api/v1/epoch/reward_params")
stake_saturation = get_dict_value(reward_params,["interval","stake_saturation_point"])
stake_saturation = convert_u_nym(stake_saturation)
return stake_saturation
def _get_desc_column():
supply = "Maximum amount of NYM token in existence"
reserve = "Tokens releasing for operators rewards"
vesting = "Tokens locked outside of cicrulation for future claim"
circulating = "Amount of unlocked tokens"
desc_column = [supply, reserve, vesting, circulating]
return desc_column
def read_supply(args):
separator = args.separator
response = subparser_read(args)
if args.endpoint == "circulating-supply":
if args.value:
value = get_nested_value(response, args)
value = convert_u_nym(value)
value = thousand_separator(value, separator)
print(value)
elif args.format == "markdown":
display_supply_table(response, args)
else:
value = response
print(value)
elif args.endpoint == "epoch/reward_params":
value = get_reward_params(response, args, separator)
print(value)
def get_reward_params(response, args, separator):
value = get_nested_value(response, args)
if args.format == "percent":
value = _return_percent_annotation(value)
else:
value = convert_u_nym(value)
value = thousand_separator(value, separator)
return value
def get_nested_value(response, args):
value = response
for key in args.value:
value = value[key]
return value
def _return_percent_annotation(value):
value = float(value) * 100
value = f"{value}%"
return value
###########################################
############# CALCULATE FNs ###############
###########################################
def calculate(args):
separator = args.separator
reward_params = get_api("https://validator.nymtech.net/api/v1/epoch/reward_params")
circulating_supply = get_api("https://validator.nymtech.net/api/v1/circulating-supply")
if args.staking_target:
display_staking_target(args, reward_params, circulating_supply, separator)
def get_api(url):
r = requests.get(url)
response = r.json()
return response
def display_staking_target(args, reward_params, circulating_supply, separator):
keys = ["interval", "staking_supply_scale_factor"]
staking_supply_scale_factor = get_dict_value(reward_params, keys)
keys = ["circulating_supply", "amount"]
circulating_supply = get_dict_value(circulating_supply, keys)
staking_target = float(staking_supply_scale_factor) * float(circulating_supply)
staking_target = convert_u_nym(staking_target)
if args.separator:
staking_target = thousand_separator(staking_target, separator)
print(staking_target)
def get_dict_value(json, keys):
value = json
for key in keys:
value = value[key]
return value
###########################################
############ GH RELATED FNs ###############
###########################################
def get_nym_vpn_version(args):
response = subparser_read(args)
if args.client == "desktop":
version = current_desktop_version(args, response)
elif args.client == "cli":
version = current_cli_version(args, response)
else:
print("Incorrect argument for -c, --client")
sys.exit(-1)
def current_cli_version(args, response):
df = pd.DataFrame(response)
print(df)
# NEEDS THIS IN PYTHON:
# current_cli_version=$(curl -s $release_url | jq -r '.[].tag_name' | grep '^nym-vpn-cli-v' | sort -Vr | head -n 1 | awk -F'-v' '{print $NF}')
def current_desktop_version(args, response):
# NEEDS THIS IN PYTHON:
df = pd.DataFrame(response)
print(df)
# version=$(curl -s $release_url | jq -r '.[].tag_name' | grep '^nym-vpn-desktop-v' | sort -Vr | head -n 1 | awk -F'-v' '{print $NF}')
###########################################
############### MAIN PARSER ###############
###########################################
def parser_main():
parser = argparse.ArgumentParser(
prog="Nym API scraper",
description='''Get any live data from Nyx validator''',
epilog=''
)
subparsers = parser.add_subparsers(help="")
parser_supply = subparsers.add_parser('validator',
help='Reads validaor API enpoints',
aliases=['v']
)
parser_supply.add_argument(
"-a","--api",
type=str,
default="mainnet",
help="choose: mainnet, perf, sandbox"
)
parser_supply.add_argument(
"-e","--endpoint",
type=str,
help="choose from: https://validator.nymtech.net/api/swagger/index.html"
)
parser_supply.add_argument(
"-v","--value",
type=str,
help="dictionary keys to get needed value separated by a space",
nargs = '+'
)
parser_supply.add_argument(
"-f","--format",
type=str,
help="'markdown' formats the output for documentation purpose; 'percent' returns a number with % annotation",
)
parser_supply.add_argument(
"-s", "--separator",
type=str,
default=" ",
help="Add custom thousand separator to --format flag (default is none)"
)
parser_supply.set_defaults(func=read_supply)
parser_calculate = subparsers.add_parser('calculate',
help='Calculate and print the values of optional args',
aliases=['c']
)
parser_calculate.add_argument(
"--staking_target",
action="store_true",
help="A multiplier of staking supply scale factor and circulating supply"
)
parser_calculate.add_argument(
"-s", "--separator",
type=str,
default=" ",
help="Add custom thousand separator to --format flag (default is none)"
)
# parser_calculate.add_argument(
# "--api",
# default="mainnet",
# )
parser_calculate.set_defaults(func=calculate)
parser_time_now = subparsers.add_parser('time_now',
help='Prints UTC time now',
aliases=['time', 't']
)
parser_time_now.set_defaults(func=print_time_now)
parser_nym_vpn = subparsers.add_parser('nym_vpn',
help='reads NymVPN latest version',
aliases=['n']
)
parser_nym_vpn.add_argument(
"-c","--client",
type=str,
default="desktop",
help="choose: desktop, cli - default: desktop"
)
parser_nym_vpn.add_argument(
"-a","--api",
type=str,
default="github",
help="choose: mainnet, perf, sandbox"
)
parser_nym_vpn.add_argument(
"-e","--endpoint",
type=str,
help="add the url suffix",
default="repos/nymtech/nym-vpn-client/releases"
)
parser_nym_vpn.set_defaults(func=get_nym_vpn_version)
args = parser.parse_args()
try:
args.func(args)
except AttributeError as e:
print("Error on argparser")
sys.exit(-1)
if __name__ == "__main__":
parser_main()