Saludos Hivers espero que la esten pasando muy bien en este nuevo dia, una nueva oportunidad para vivir, respirar, soñar y crear. Todo hasta cuando el Padre creador decida.
English at the bottom!
@nectarflower?
Es una libreria muy útil desarrollada por el amigo @thecrazygm que hace un trabajo que a mi parecer deberia ser invaluable para la red de HIVE.
La librería nectarflower-js es una herramienta en JavaScript que permite actualizar dinámicamente la lista de nodos RPC utilizados por clientes de la blockchain de Hive. Utiliza los metadatos del campo account_json_metadata de la cuenta nectarflower para obtener una lista actualizada de nodos confiables. Esto es especialmente útil para mantener la resiliencia y disponibilidad de las aplicaciones que interactúan con Hive, ya que permite adaptarse automáticamente a cambios en la infraestructura de nodos sin intervención manual. La librería incluye ejemplos prácticos de cómo integrar esta funcionalidad en proyectos existentes.
Importancia de contar con Nodos RPC testeados
Usamos los nodos RPC para llevar a cabo: consultas, movimientos, escritura y lectura en la cadena de bloques de HIVE. Además podemos decidir si hacer todo eso en la capa 1 o la capa 2. Es evidente la importancia que tiene, estar conectado a un nodo RPC confiable, rapido y actualizado.
Ejemplo vago: tengo una app que hice para HIVE. Ella se encarga de revisar publicaciones para una comunidad y cada hora debe ejecutar un autovoto. Ella utiliza siempre el mismo nodo RPC y casualmente cada hora ese nodo falla. En un supuesto dia comun la falla se repite cada hora, justo cuando la app deberia emitir el autovoto. Resultado: desastre total para esa app y probablemente a ese programador le caiga toda la culpa.
Solución? Contar con un módulo que chequee y garantice estar conectado al nodo que mejor y mas rapido responde. Alli entra en juego esta libreria.
🔧 Acción con Nodos RPC | 📋 Descripción |
---|---|
🌐 Conexión con la blockchain | Los nodos RPC permiten que las aplicaciones se conecten y obtengan información de la blockchain de Hive. |
🔍 Obtener datos de cuenta | Permiten obtener información sobre las cuentas de Hive, como publicaciones y balances. |
📊 Consulta de bloques | Los nodos RPC permiten la consulta de bloques para obtener historial de transacciones y eventos. |
🛠️ Envío de transacciones | Facilitan la comunicación para enviar transacciones como votos, transferencias y comentarios. |
🧪 Monitoreo de estado y rendimiento | Se utilizan para monitorear el estado y la sincronización de la blockchain en tiempo real. |
🔄 Cambios de nodos dinámicos | Permiten cambiar de nodo RPC si uno está inactivo o presenta problemas de rendimiento. |
Typescript
Usar TypeScript es importante porque añade tipado estático a JavaScript, lo que permite detectar errores en tiempo de desarrollo en lugar de en tiempo de ejecución. Esto mejora la calidad del código, facilita el mantenimiento en proyectos grandes y ofrece una mejor experiencia con autocompletado y documentación integrada en editores modernos. En resumen, TypeScript ayuda a escribir código más seguro, claro y escalable.
Característica | JavaScript | TypeScript |
---|---|---|
Tipado | Dinámico | Estático |
Detección de errores | En tiempo de ejecución | En tiempo de compilación |
Autocompletado IDE | Limitado | Mejorado y preciso |
Escalabilidad | Menos adecuada | Ideal para proyectos grandes |
Que has hecho theghost1980?
A petición del amigo y gran HIVER @ecoinstant he hecho una actualización a manera de repositorio nuevo y la librería ahora cuenta con tipado estricto para prevenir fallas en su uso en modo de desarrollo.
🚫 Problema en JavaScript | ✅ Solución con TypeScript |
---|---|
❓ No sabes qué tipo de dato retorna getNodesFromAccount() | Se define como Promise<string[]> , evitando errores con nodos inválidos |
🤷♂️ reinitializeDhive() puede retornar cualquier cosa | TypeScript exige que retorne un Client , asegurando compatibilidad |
🧨 El catch puede recibir errores sin .message | El error se tipa como any (o unknown ) y se maneja con seguridad |
📦 client puede ser de cualquier tipo | Se asegura que client sea una instancia de Client |
🧪 No se valida el retorno total de la función (Client ) | Se tipa la función como Promise<Client> para garantizar consistencia |
En resumen
La migración de nectarflower-js a nectarflower-ts introduce un sistema de tipos estrictos que mejora significativamente la seguridad y claridad del código. Al definir estructuras de datos precisas y tipos de retorno, se minimizan errores comunes como accesos a propiedades inexistentes o malinterpretaciones de datos. Esto es crucial en aplicaciones que interactúan con la blockchain de Hive, donde la integridad de los datos y la confiabilidad de las operaciones son esenciales. Además, el uso de TypeScript facilita el mantenimiento y escalabilidad del proyecto, proporcionando una base sólida para futuras extensiones y colaboraciones.
Una pequena muestra del código que ya ha sido trabajado y propuesto
import { Client } from "@hiveio/dhive";
declare const client: Client;
declare function getNodesFromAccount(accountName: string): Promise<string[]>;
declare function reinitializeDhive(nodes: string[]): Client;
async function updateNodesFromAccount(accountName: string = "nectarflower"): Promise<Client> {
try {
const nodeData: string[] = await getNodesFromAccount(accountName);
const updatedClient: Client = reinitializeDhive(nodeData);
console.log("Successfully updated dhive client with new nodes");
return updatedClient;
} catch (error: any) {
console.error(`Failed to update nodes: ${error.message}`);
return client; // Se asume que ya existe una instancia default
}
}
Y tanto alarde para eso nada mas?
- Puedes mirar el codigo completo, sus interfaces y demas en: https://github.com/TheCrazyGM/nectarflower-ts
- No puedo irme sin mencionar que el codigo inicial hecho por su creador yace y estará en el mismo lugar: https://github.com/TheCrazyGM/nectarflower-js
Y para los curiosos programadores una lista de lo que ves es lo obtienes
🧵 Lenguaje | 🌐 URL del Repositorio |
---|---|
🟨 JavaScript | https://github.com/TheCrazyGM/nectarflower |
🟩 TypeScript | https://github.com/TheCrazyGM/nectarflower-ts |
🟥 Go | https://github.com/TheCrazyGM/nectarflower-go |
🟪 Rust | https://github.com/TheCrazyGM/nectarflower-rs |
No te vayas sin dar un ejemplo de uso por favor.
Para uso local:
- Descarga el repositorio, instala dependencias:
npm i
- Construye la libreria localmente:
npm run build
- Hacemos link a la libreria para uso local usando:
npm link
- Y en el proyecto de prueba, donde usaras la libreria, usamos:
npm link nectarflower-ts
- Ya tienes la libreria localmente lista para usar. Deberias poder probar, mejorar o usar el codigo:
import { NodeUpdater } from "nectarflower-ts";
//Recommended always use the account that holds the metadata as expected.
const accountName = "nectarflower";
const updatedClient = await NodeUpdater.updateNodesFromAccount(accountName);
// Use updatedClient as your dhive client
const props = await updatedClient.database.getDynamicGlobalProperties();
console.log(props);
English Here
Greetings Hivers, I hope you are having a great time on this new day, a new opportunity to live, breathe, dream and create. Everything until the creator Father decides.
@nectarflower?
It is a very useful library developed by friend @thecrazygm that does work that in my opinion should be invaluable for the HIVE network.
The nectarflower-js library is a JavaScript tool that allows you to dynamically update the list of RPC nodes used by clients of the Hive blockchain. Uses the metadata from the account_json_metadata field of the nectarflower account to obtain an updated list of trusted nodes. This is especially useful for maintaining the resiliency and availability of applications that interact with Hive, as it allows you to automatically adapt to changes in node infrastructure without manual intervention. The library includes practical examples of how to integrate this functionality into existing projects.
Importance of having tested RPC Nodes
We use RPC nodes to perform: queries, movements, write and read on the HIVE blockchain. We can also decide whether to do all that at layer 1 or layer 2. The importance of being connected to a reliable, fast and updated RPC node is evident.
Vague example: I have an app I made for HIVE. She is in charge of reviewing publications for a community and every hour she must execute a self-vote. She always uses the same RPC node and coincidentally every hour that node fails. On a supposed common day the failure repeats itself every hour, just when the app should cast the self-vote. Result: total disaster for that app and probably that programmer will be entirely to blame.
Solution? Have a module that checks and guarantees being connected to the node that responds best and fastest. This library comes into play there.
Typescript
Using TypeScript is important because it adds static typing to JavaScript, allowing errors to be detected at development time rather than runtime. This improves code quality, makes it easier to maintain large projects, and offers a better experience with autocompletion and documentation built into modern editors. In short, TypeScript helps write more secure, clear, and scalable code.
Feature | JavaScript | TypeScript |
---|---|---|
Typing | Dynamic | Static |
Error detection | At runtime | At compile time |
IDE Autocomplete | Limited | Improved and accurate |
Scalability | Less suitable | Ideal for large projects |
What have you done theghost1980?
At the request of my friend and great HIVER @ecoinstant I have made an update as a new repository and the library now has strict typing to prevent failures in its use in development mode.
🚫 JavaScript Problem | ✅ Solution with TypeScript |
---|---|
❓ You don't know what type of data getNodesFromAccount() returns | It is defined as Promise<string[]> , avoiding errors with invalid nodes |
🤷♂ ️ reinitializeDhive() can return anything | TypeScript requires a Client to return, ensuring compatibility |
🧨 The catch can receive errors without .message | The error is typed as any (or unknown ) and is handled safely |
📦 client can be of any type | Ensures that client is an instance of Client |
🧪 Full function return (Client ) is not validated | The function is typed as Promise<Client> to ensure consistency |
In summary
The migration from nectarflower-js to nectarflower-ts introduces a strict type system that significantly improves code security and clarity. By defining precise data structures and return types, common errors such as accesses to non-existent properties or data misinterpretations are minimized. This is crucial in applications that interact with the Hive blockchain, where data integrity and operational reliability are essential. Additionally, the use of TypeScript facilitates project maintenance and scalability, providing a solid foundation for future extensions and collaborations.
A small sample of the code that has already been worked on and proposed
import {Client } from "@hiveio/dhive";
client const declaration: Client;
declare function getNodesFromAccount(accountName: string): Promise<string[]>;
declare function reinitializeDhive(nodes: string[]): Client;
async function updateNodesFromAccount(accountName: string = "nectarflower"): Promise<Client> {
try {
const nodeData: string[] = await getNodesFromAccount(accountName);
const updatedClient: Client = reinitializeDhive(nodeData);
console.log("Successfully updated dhive client with new nodes");
return updatedClient;
} catch (error: any) {
console.error(`Failed to update nodes: ${error.message}`);
return client; //It is assumed that a default instance already exists
}
}
And all the bragging for that?
- You can see the complete code, its interfaces and more at: https://github.com/TheCrazyGM/nectarflower-ts
- I cannot leave without mentioning that the initial code made by its creator lies and will be in the same place: https://github.com/TheCrazyGM/nectarflower-js
And for curious programmers a list of what you see is what you get
🧵 Language | 🌐 Repository URL |
---|---|
🟨 JavaScript | https://github.com/TheCrazyGM/nectarflower |
🟩 TypeScript | https://github.com/TheCrazyGM/nectarflower-ts |
🟥 Go | https://github.com/TheCrazyGM/nectarflower-go |
🟪 Rust | https://github.com/TheCrazyGM/nectarflower-rs |
Please don't leave without giving an example of use.
For local use:
- Download the repository, install dependencies:
npm i
- Build the library locally:
npm run build
- We link to the library for local use using:
npm link
- And in the test project, where you will use the library, we use:
npm link nectarflower-ts
- You now have the library locally ready to use. You should be able to test, improve or use the code:
import { NodeUpdater } from "nectarflower-ts";
//Recommended always use the account that holds the metadata as expected.
const accountName = "nectarflower";
const updatedClient = await NodeUpdater.updateNodesFromAccount(accountName);
//Use updatedClient as your dhive client
const props = await updatedClient.database.getDynamicGlobalProperties();
console.log(props);
@theghost1980
Send me some love using the link in the image bellow:
Mándame algo de amor usando el enlace en la imagen de abajo: