Tutorial: Autenticación Hive con Hive Keychain React + Vite + TypeScript english/español


Saludos hivers espero de todo corazón que todos esten muy contentos y felices. Un saludo especial para los programadores que dia a dia mejoran el ecosistema web3.

Para seguir ayudando en la formación de futuras estrellas de la programación en HIVE, les traigo un tutorial basico pero lleno de algo que es y deberia ser vital.

Objetivo

Este tutorial te guiará para implementar la autenticación de usuarios en la blockchain de Hive utilizando Hive Keychain en una aplicación React configurada con Vite y TypeScript.

Requisitos previos

fuente link

Pasos

  • Crear el proyecto con Vite
    Ejecuta el siguiente comando en tu terminal:
npm create vite@latest hive-login-app -- --template react-ts
cd hive-login-app
npm install
npm run dev
  • Instalar dependencias necesarias
    -Instala la biblioteca @hiveio/dhive para interactuar con la blockchain de Hive
npm install @hiveio/dhive
  • Crear el componente de autenticación
    • Crea un nuevo archivo src/components/HiveLogin.tsx con el siguiente contenido:
import React, { useState } from 'react';

declare global {
  interface Window {
    hive_keychain: any;
  }
}

const HiveLogin: React.FC = () => {
  const [username, setUsername] = useState('');
  const [loggedInUser, setLoggedInUser] = useState('');

  const handleLogin = () => {
    if (window.hive_keychain) {
      window.hive_keychain.requestSignBuffer(
        username,
        'Autenticación en Hive',
        'Posting',
        (response: any) => {
          if (response.success) {
            setLoggedInUser(username);
            alert('¡Autenticación exitosa!');
          } else {
            alert('Error en la autenticación.');
          }
        }
      );
    } else {
      alert('Hive Keychain no está instalado.');
    }
  };

  return (
    <div>
      <h2>Iniciar sesión con Hive</h2>
      <input
        type="text"
        placeholder="Nombre de usuario"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
      />
      <button onClick={handleLogin}>Iniciar sesión</button>
      {loggedInUser && <p>Usuario autenticado: {loggedInUser}</p>}
    </div>
  );
};

export default HiveLogin;
  • Integrar el componente en la aplicación principal
    • Modifica el archivo src/App.tsx para incluir el componente de autenticación:
import React from 'react';
import HiveLogin from './components/HiveLogin';

const App: React.FC = () => {
  return (
    <div>
      <h1>Aplicación Hive + React</h1>
      <HiveLogin />
    </div>
  );
};

export default App;
  • Probar la aplicación

Inicia la aplicación con npm run dev y abre http://localhost:5173 en tu navegador. Ingresa tu nombre de usuario de Hive y haz clic en "Iniciar sesión". Se solicitará la firma a través de Hive Keychain.


Resultado

Has implementado con éxito la autenticación de usuarios en Hive utilizando Hive Keychain en una aplicación React con Vite y TypeScript.

¡Claro! A continuación, te presento un documento en formato Markdown que aborda:

  1. ¿Qué puedes hacer después de implementar el inicio de sesión en Hive?
  2. Ideas de aplicaciones que podrías desarrollar.
  3. Ventajas de utilizar un frontend con Hive.
  4. Una tabla con algunos de los tutoriales que ya has creado, incluyendo enlaces a tu repositorio de GitHub.

🔐 ¿Qué puedes hacer después de implementar el inicio de sesión en Hive?

Una vez que has integrado la autenticación con Hive (por ejemplo, utilizando Hive Keychain), puedes expandir las funcionalidades de tu aplicación para interactuar plenamente con la blockchain. Algunas acciones posibles incluyen:

  • Publicar contenido: Permitir a los usuarios crear publicaciones, comentarios o blogs que se almacenan en la blockchain.
  • Votar contenido: Implementar sistemas de votación para que los usuarios puedan apoyar publicaciones de otros.
  • Transferencias de tokens: Facilitar el envío y recepción de tokens HIVE o HBD entre usuarios.
  • Delegación de poder: Permitir a los usuarios delegar su Hive Power a otros usuarios o proyectos.
  • Participación en gobernanza: Integrar funciones para que los usuarios voten por testigos o propuestas en el Decentralized Hive Fund (DHF).
  • Gestión de NFTs: Crear, comprar o vender tokens no fungibles (NFTs) utilizando plataformas como NFT Showroom.(Hive Projects, Wikipedia, Moralis Academy, The Dapp List)

💡 Ideas de aplicaciones que podrías desarrollar

Con tus conocimientos en React, Vite, TypeScript y Hive, puedes emprender diversos proyectos. Algunas ideas incluyen:

  • Plataforma de blogging descentralizada: Donde los usuarios puedan publicar y monetizar contenido sin intermediarios.
  • Mercado de NFTs: Para artistas y coleccionistas que deseen intercambiar arte digital.
  • Aplicación de votaciones: Para encuestas comunitarias o decisiones descentralizadas.
  • Juego basado en blockchain: Que utilice tokens y activos digitales únicos.
  • Red social temática: Focalizada en nichos específicos, como música, deportes o educación.
  • Herramienta de análisis de datos: Que visualice estadísticas y métricas de la blockchain de Hive.

Para más inspiración, puedes explorar Hive Projects y Awesome Hive, donde encontrarás una amplia gama de aplicaciones y herramientas desarrolladas por la comunidad.(GitHub)


⚙️ Ventajas de utilizar un frontend con Hive

Integrar Hive en el frontend de tus aplicaciones ofrece múltiples beneficios:

  • Transacciones sin comisiones: Hive permite realizar operaciones sin tarifas, lo que mejora la experiencia del usuario.
  • Rapidez: Las transacciones en Hive se confirman en aproximadamente 3 segundos.
  • Descentralización: Almacena datos de forma inmutable y accesible sin depender de servidores centralizados.
  • Identidades legibles: Los nombres de usuario en Hive son fáciles de recordar y utilizar.
  • Ecosistema activo: Hive cuenta con una comunidad vibrante y una amplia gama de aplicaciones descentralizadas (dApps).(Hive)

📚 Tabla de tutoriales existentes

A continuación, se presenta una tabla con algunos de los tutoriales que has desarrollado, incluyendo enlaces a tu repositorio de GitHub:

Título del TutorialDescripción breveEnlace al repositorio
Multiples TutorialesAprende a integrar React con la blockchain de Hive.Ver en GitHub


Aquí tienes una tabla en formato Markdown que resume tus proyectos actuales en Hive, incluyendo una breve descripción de cada uno y enlaces a sus respectivos repositorios en GitHub:


🚧 Proyectos en marcha en Hive

ProyectoDescripción
hive-sbi-onboardingAplicación sencilla para identificar nuevos usuarios de Hive y facilitar su incorporación al programa Hive SBI.
be-hive-sqlServidor backend que permite ejecutar consultas SQL en la blockchain de Hive, proporcionando una API segura mediante Hive Keychain y tokens JWT para acceder a datos de cuentas y transacciones.
keychain-helperLibrería ligera y amigable para TypeScript y JavaScript que facilita la interacción con Hive Keychain, permitiendo realizar firmas de operaciones y logins seguros de forma sencilla en aplicaciones Web3 modernas.


ENGLISH mini logo

Tutorial: Hive Authentication with Hive Keychain React + Vite + TypeScript english / Spanish

Greetingshiversi sincerely hope that everyone will be very happy and happy. A special greeting for programmers that day by day improve the web ecosystem 3.

To continue to help in the formation of future programming stars in HIVE, I bring you a basic tutorial but full of something that is and should be vital.

Objective

This tutorial will guide you to implement user authentication in the Hive blockchain using Hive Keychain in a React application configured with Vite and TypeScript.

Previous requirements

sourcelink

Steps

  • Create the project with Vite
    Run the following command on your terminal:
npm create vite@latest hive-login-app -- --template react-ts
cd hive-login-app
npm install
npm run dev
  • Install required units
    -Install the library
npm install @hiveio/dhive
  • Create the authentication component
    • Create a new filesrc/components/HiveLogin.tsxwith the following content:
import React, { useState } from 'react';

declare global {
  interface Window {
    hive_keychain: any;
  }
}

const HiveLogin: React.FC = () => {
  const [username, setUsername] = useState('');
  const [loggedInUser, setLoggedInUser] = useState('');

  const handleLogin = () => {
    if (window.hive_keychain) {
      window.hive_keychain.requestSignBuffer(
        username,
        'Autenticación en Hive',
        'Posting',
        (response: any) => {
          if (response.success) {
            setLoggedInUser(username);
            alert('¡Autenticación exitosa!');
          } else {
            alert('Error en la autenticación.');
          }
        }
      );
    } else {
      alert('Hive Keychain no está instalado.');
    }
  };

  return (
    <div>
      <h2>Iniciar sesión con Hive</h2>
      <input
        type="text"
        placeholder="Nombre de usuario"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
      />
      <button onClick={handleLogin}>Iniciar sesión</button>
      {loggedInUser && <p>Usuario autenticado: {loggedInUser}</p>}
    </div>
  );
};

export default HiveLogin;
  • Integrate the component into the main application
    • Modify the filesrc/App.tsxto include the authentication component:
import React from 'react';
import HiveLogin from './components/HiveLogin';

const App: React.FC = () => {
  return (
    <div>
      <h1>Aplicación Hive + React</h1>
      <HiveLogin />
    </div>
  );
};

export default App;
  • Test implementation

Start the application with npm run dev and openhttp://localhost:5173in your browser. Enter your Hive user name and click "Login." The signature will be requested through Hive Keychain.


Outcome

You have successfully implemented the Hive user authentication using Hive Keychain in a React with Vite and TypeScript application.

Sure! Here is a Markdown document that addresses:

  1. What can you do after implementing the Hive login?
  2. Ideas of applications you could develop.
  3. Advantages of using a front with Hive.
  4. A table with some of the tutorials you've already created, including links to your GitHub repository.

- What can you do after implementing the Hive login?

Once you have integrated the Hive authentication (for example, using Hive Keychain), you can expand the functionality of your application to fully interact with the blockchain. Some possible actions include:

  • Publish content: Allow users to create publications, comments or blogs that are stored in the lockchain.
  • Voting: Implement voting systems to enable users to support publications from others.
  • Tokens transfers: Facilitate the sending and reception of HIVE or HBD tokens between users.
  • Delegation of power: Allow users to delegate their Hive Power to other users or projects.
  • Participation in governance: Integrate functions for users to vote for witnesses or proposals in the Decentralized Hive Fund (DHF).
  • NFTs management: Create, buy or sell non-expendable tokens (NFTs) using platforms such as NFT Showroom. (Hive Projects,Wikipedia,Moralis Academy,The Dapp List)

Ideas of applications you could develop

With your knowledge in React, Vite, TypeScript and Hive, you can undertake various projects. Some ideas include:

  • Decentralized blogging platform: Where users can publish and monetize content without intermediaries.
  • NFTs market: For artists and collectors who wish to exchange digital art.
  • VotingFor community surveys or decentralized decisions.
  • Blockchain-based game: Use tokens and unique digital assets.
  • Thematic social network: Focused on specific niches, such as music, sports or education.
  • Data analysis tool: To visualize statistics and metrics of Hive's blockchain.

For more inspiration, you can exploreHive ProjectsandAwesome Hivewhere you will find a wide range of applications and tools developed by the community. (GitHub)


Advantages of using a front with Hive

Integrating Hive into the front of your applications offers multiple benefits:

  • Transactions without commissions: Hive allows free operations, which improves the user's experience.
  • Rapidity: Hive transactions are confirmed in approximately 3 seconds.
  • Decentralization: Stores data in an unchanging and accessible way without relying on centralized servers.
  • Eligible entities: The user names in Hive are easy to remember and use.
  • Active ecosystem: Hive has a vibrant community and a wide range of decentralized applications (dApps). (Hive)

Table of existing tutorials

Below is a table with some of the tutorials you have developed, including links to your GitHub repository:

Title of the tutorialShort descriptionLink to the repository
Multiple tutorialsLearn to integrate React with Hive's blockchain.See in GitHub

Sort:  

Keep it up friend!

!PAKX
!PIMP
!PIZZA

View or trade PAKX tokens.

@ecoinstant, PAKX has voted the post by @theghost1980. (1/1 calls)

Use !PAKX command if you hold enough balance to call for a @pakx vote on worthy posts! More details available on PAKX Blog.

PIZZA!

$PIZZA slices delivered:
@ecoinstant(2/20) tipped @theghost1980

Come get MOONed!