Introducing nectarflower-ts v1.0.0 | Presentando nectarflower-ts version 1.0.0 en/es

nectarflower-ts-introducing.png

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 blockchainLos nodos RPC permiten que las aplicaciones se conecten y obtengan información de la blockchain de Hive.
🔍 Obtener datos de cuentaPermiten obtener información sobre las cuentas de Hive, como publicaciones y balances.
📊 Consulta de bloquesLos nodos RPC permiten la consulta de bloques para obtener historial de transacciones y eventos.
🛠️ Envío de transaccionesFacilitan la comunicación para enviar transacciones como votos, transferencias y comentarios.
🧪 Monitoreo de estado y rendimientoSe utilizan para monitorear el estado y la sincronización de la blockchain en tiempo real.
🔄 Cambios de nodos dinámicosPermiten cambiar de nodo RPC si uno está inactivo o presenta problemas de rendimiento.

image.png
fuente img

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ísticaJavaScriptTypeScript
TipadoDinámicoEstático
Detección de erroresEn tiempo de ejecuciónEn tiempo de compilación
Autocompletado IDELimitadoMejorado y preciso
EscalabilidadMenos adecuadaIdeal para proyectos grandes

image.png

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 cosaTypeScript exige que retorne un Client, asegurando compatibilidad
🧨 El catch puede recibir errores sin .messageEl error se tipa como any (o unknown) y se maneja con seguridad
📦 client puede ser de cualquier tipoSe 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?

Y para los curiosos programadores una lista de lo que ves es lo obtienes

🧵 Lenguaje🌐 URL del Repositorio
🟨 JavaScripthttps://github.com/TheCrazyGM/nectarflower
🟩 TypeScripthttps://github.com/TheCrazyGM/nectarflower-ts
🟥 Gohttps://github.com/TheCrazyGM/nectarflower-go
🟪 Rusthttps://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.

FeatureJavaScriptTypeScript
TypingDynamicStatic
Error detectionAt runtimeAt compile time
IDE AutocompleteLimitedImproved and accurate
ScalabilityLess suitableIdeal 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() returnsIt is defined as Promise<string[]>, avoiding errors with invalid nodes
🤷‍♂ ️ reinitializeDhive() can return anythingTypeScript requires a Client to return, ensuring compatibility
🧨 The catch can receive errors without .messageThe error is typed as any (or unknown) and is handled safely
📦 client can be of any typeEnsures that client is an instance of Client
🧪 Full function return (Client) is not validatedThe 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?

And for curious programmers a list of what you see is what you get

🧵 Language🌐 Repository URL
🟨 JavaScripthttps://github.com/TheCrazyGM/nectarflower
🟩 TypeScripthttps://github.com/TheCrazyGM/nectarflower-ts
🟥 Gohttps://github.com/TheCrazyGM/nectarflower-go
🟪 Rusthttps://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:

support-apps-hive-tipjar-keychain.png

Sort:  

It gives me the warm fuzzies!

Buddy you have done such a great work. It is my honor to contribute with this. I am 100% to keep making HIVE a better place not just for people, users, whales but also for developers

Any other ideas you may have please let me know. There is lot more we can do!

Gracias amigo!

image.png
source

a simpler version of this that doesn't recreate the client but just fetches that data with a raw api call and returns a list of strings would probably be my next suggestion if you want to break it away from dhive (i used it because it's common) but that would also give the benefit of working with @flowerengine for a list of hive-engine nodes as well as @nectarflower for just the hive nodes.

Hi there @thecrazygm thanks for the confirmation about how it works. I was almost certain about this "the benchmark repo" is the one getting the data about the nodes. About breaking it away from dhive, well I can do that. It could even be done in a separate function call but it will depends on what the final users wants i guess.

At anytime you can send me a pm in discord so we can talk about it. I would gladly listen to your ideas and make them happen!

Tremendo! 🚀 v1.0.0 de nectarflower-ts pinta genial para la red de HIVE. A darle! 🐎

Gracias. Asi estamos creando codigo y siempre que sea bueno y efectivo para la comunidad. Al servicio por aca siempre que tengan ideas, ya sea fullstack o frontend o librerias o paquetes, estoy a la orden!

Este tema me impacto ya que lo veo tan necesario como mantener un testigo. Tener acceso a nodos actualizados cada hora y poder tener ayuda del tipado cuando desarrollamos es invaluable.

Saludos!