Boosting my passive income tracking with Hive API integration [EN/FR]
This morning, I had to work a bit on my freelance missions, and I will have to continue this afternoon. It’s not a bad thing in itself, since it allows me to finance my lifestyle. So, not much choice.
But I still took advantage of the beginning of the afternoon to make some improvements to my Hive simulator. If you don’t know what I’m talking about, I explain everything in another article. To put it simply, it’s a tool that tells you when you will be able to retire thanks to Hive and the magic of compound interest.
https://peakd.com/hive-167922/@genesisledger/when-will-you-be-able-to-retire-with-hive-enfr-82y
In my case, if I continue at the same pace, it will be in 32 years and 11 months. I’m quite satisfied because I will be able to live off the interest, and it will always be better than the retirement promised by the State. So, it’s not bad… even if that’s not specifically why I write here, it’s a real plus!
The Hive API
Hive provides an API for developers. Basically, it’s a bridge that allows two software programs to communicate with each other. Thanks to that, even without having direct access to Hive’s database (which, by the way, doesn’t really exist since it’s decentralized), I can still retrieve useful information.
It’s super handy for enriching an application with useful (or not) features that you don’t want to develop yourself. A classic example is the weather API: there are plenty of them, and they allow you to retrieve real-time weather data without having to calculate the temperature yourself. You can then display them in an app, make predictions, etc.
So, Hive provides us with its API: https://developers.hive.io.
I didn’t read everything in detail. I skimmed through, letting my eyes stop wherever they wanted. Actually, I already knew what I was looking for: retrieving the HP and HBD savings balance of an account.
By digging a little, I came across the Condenser API, which includes quite a few useful functions:
What interested me was the get_accounts() function:
I won’t detail everything this function returns, but basically, it provides enough information to retrieve the HP and HBD of a Hive account. So I could move on to implementation.
1. Adding a new entry
First step: add a field in my form so that the user can enter a Hive account and launch the search.
It’s basic HTML, so I won’t necessarily detail it. But the attribute data-i18n="hiveAccount" allows translating the string (I have a .js file for translations).
Then, the tool had to automatically retrieve the HP and HBD of the account when clicking on Fetch Data.
2. Retrieving data via the API
This is where JavaScript comes into play.
I used async
for my function fetchHiveData(), for readability. I could have used .then()
, but from experience, it quickly makes the code heavier. With async
, it’s clearer and easier to maintain, even if it requires a bit of adaptation at first. I also read some documentation about it because I’m bad at JavaScript. I had learned this concept in Flutter back in the day.
This line triggers the function when clicking the button:
document.getElementById("fetchHiveData").addEventListener("click", fetchHiveData);
As soon as the function starts, it checks if a name has been entered. If not, it displays an error.
Next, I retrieve the API response by calling get_accounts(). I use await
to wait for the response before moving on, otherwise my code would continue executing without waiting for the data. That’s the whole point of asynchronous functions.
Once the response is obtained, I check it. If it contains valid data, I display everything in the developer console. That allows me to see exactly what I’m retrieving.
That’s actually how I discovered that the API returns VESTS instead of HP directly.
At first, I didn’t understand, but basically, Hive uses VESTS to represent Hive Power more precisely. This avoids rounding errors in calculations.
Since the API gives me VESTS, I have to convert them to HP. For that, I need the conversion rate:
Conversion rate = Total number of HIVE staked in HP across the entire blockchain / Total number of VESTS held by all Hive accounts.
This rate changes regularly, but after reading Hive’s documentation, I found what I needed. I retrieve my data to calculate my rate using the function get_dynamic_global_properties() from the API:
Then, I retrieve the number of VESTS held by the user, as well as those they have delegated (I subtract them from the total to get their real balance).
Then, I perform the conversion to get the real HP:
For retrieving HBD savings, it was much simpler:
Once all the data is retrieved, I display it to the user by automatically filling in the fields Current HP (tokens) and Current HBD in savings ($).
For my account, here’s what it looks like:
Version Française
Ce matin, j’ai dû bosser un peu sur mes missions freelance, et je vais devoir continuer cet après-midi. Ce n’est pas une mauvaise chose en soi, puisque c’est ce qui me permet de financer mon mode de vie. Donc, pas trop le choix.
Mais j’ai quand même profité du début d’après-midi pour apporter quelques améliorations à mon simulateur Hive. Si vous ne voyez pas de quoi je parle, j’explique tout dans un autre article. Pour faire simple, c’est un outil qui vous dit quand vous pourrez prendre votre retraite grâce à Hive et à la magie des intérêts composés.
https://peakd.com/hive-167922/@genesisledger/when-will-you-be-able-to-retire-with-hive-enfr-82y
Dans mon cas, si je continue sur la même lancée, ce sera dans 32 ans et 11 mois. Je suis plutôt satisfait parce que je pourrai vivre des intérêts, et ça sera toujours mieux que la retraite promise par l’État. Ce n’est donc pas mauvais… même si ce n’est pas spécialement pour ça que j’écris ici, c’est un vrai plus !
L'API de Hive
Hive met à disposition une API pour les développeurs. En gros, c’est un pont qui permet à deux logiciels de communiquer entre eux. Grâce à ça, même sans avoir directement accès à la base de données de Hive (qui, d’ailleurs, n’existe pas vraiment puisque c’est décentralisé), je peux quand même récupérer des infos utiles.
C’est super pratique pour enrichir une application avec des fonctionnalités utiles (ou pas) que vous ne voulez pas développer. Un exemple classique, c’est l’API météo : il en existe plein, et elles permettent de récupérer des données météo en temps réel sans avoir à calculer soi-même la température. On peut ensuite les afficher dans une app, faire des prédictions, etc.
Hive nous met donc à disposition son API : https://developers.hive.io
Je n’ai pas tout lu en détail. J’ai survolé, laissant mes yeux s’arrêter là où ils voulaient. En fait, je savais déjà ce que je cherchais : récupérer le solde des HP et HBD savings d’un compte.
En fouillant un peu, je suis tombé sur la Condenser API, qui regroupe pas mal de fonctions utiles :
Ce qui allait m'intéresser était la fonction get_accounts :
Je ne vais pas détailler tout ce que cette fonction renvoie, mais en gros, elle fournit suffisamment d’infos pour récupérer les HP et HBD d’un compte Hive. Je pouvais donc passer à l’implémentation.
1. Ajout d'une nouvelle entrée
Première étape : ajouter un champ dans mon formulaire pour que l’utilisateur puisse entrer un compte Hive et lancer la recherche.
C'est du HTML basique, je ne vais donc pas forcément le détailler. Mais l'attribut data-i18n="hiveAccount" permet de traduire le chaine de caractères (j'ai un fichier .js pour les traductions).
Ensuite, il fallait que l’outil récupère tout seul les HP et HBD du compte quand on clique sur Fetch Data.
2. Récupérer les données grâce à l'API
C'est là que rentre en jeu le JavaScript.
J’ai utilisé async pour ma fonction fetchHiveData(), question de lisibilité. J’aurais pu utiliser .then(), mais par expérience, ça alourdit vite le code. Avec async, c’est plus clair et plus simple à maintenir, même si ça demande un peu d’adaptation au début. J'ai aussi lu de la documentation à propos parce que je suis mauvais en JavaScript. J'avais appris ce concept en Flutter, à l'époque.
Cette ligne déclenche la fonction lorsqu’on clique sur le bouton :
document.getElementById("fetchHiveData").addEventListener("click", fetchHiveData);
Dès que la fonction se lance, elle vérifie si un nom a bien été renseigné. Sinon, elle affiche une erreur.
Ensuite, je récupère la réponse de l’API en appelant get_accounts(). Important : j’utilise await pour attendre la réponse avant de passer à la suite, sinon mon code s’exécuterait sans attendre la donnée. C'est tout l'intérêt des fonctions asynchrones.
Une fois la réponse obtenue, je la vérifie. Si elle contient bien des infos, j’affiche tout dans la console développeur. Ça me permet de voir exactement ce que je récupère.
C’est d’ailleurs comme ça que j’ai découvert que l’API renvoie des VESTS au lieu des HP directement. Je ne comprenais pas au début, mais en gros, Hive utilise VESTS pour représenter le Hive Power de manière plus précise. Ça évite les erreurs d’arrondi dans les calculs.
Comme l’API me donne des VESTS, je dois les convertir en HP. Pour ça, j’ai besoin du taux de conversion :
Taux de conversion = Nombre total de HIVE engagés en HP sur toute la blockchain / Nombre total de VESTS détenus par tous les comptes Hive.
Ce taux change régulièrement, mais en lisant la document de Hive, j'ai trouvé mon bonheur. Je récupère mes données pour calculer mon taux avec la fonction get_dynamic_global_properties() de l’API :
Ensuite, je récupère le nombre de VESTS détenus par l’utilisateur, ainsi que ceux qu’il a délégués (je les soustrais du total pour avoir son vrai solde).
Puis, je fais la conversion pour obtenir les HP réels :
Pour récupérer les HBD savings, c'était beaucoup plus simple :
Une fois toutes les données récupérées, je les affiche à l’utilisateur en remplissant automatiquement les champs Current HP (tokens) et Current HBD in savings ($).
Pour mon compte, voici ce que ça donne :
Pictures are screenshots that I took. The English translation was done using DeepL's API.
Posted Using INLEO
Wonderful Job
Quel beaux simulateur j'ai mis 20 ans avec 10K HP et 1000 HBD , sa payais pas une retraite stable mais déjà un beaux terrain
!LOLZ !HUG
lolztoken.com
Every judge knows bananas splits.
Credit: reddit
@genesisledger, I sent you an $LOLZ on behalf of invest-time
(2/6)
Delegate Hive Tokens to Farm $LOLZ and earn 110% Rewards. Learn more.
!LOL
Your post has been manually reviewed for curation by the Principality of Bastion.
Check the Trail of posts we voted
Principality of Bastion - Our Leit Motiv? Let's Grow Together.
Principality's site | Minava NFT Market | Discord | Our Twitch Channel
You may TRAIL this account if you like the curation we do, or join our discord to know more about what we do.

lolztoken.com
Great food, no atmosphere.
Credit: reddit
@genesisledger, I sent you an $LOLZ on behalf of itharagaian
(4/10)
Farm LOLZ tokens when you Delegate Hive or Hive Tokens.
Click to delegate: 10 - 20 - 50 - 100 HP