Elven Guide

React MultiversX EGLD App

Elven Guide

元の共有チャットを開く

ユーザー

I would like a simple starter for an app that will integrate with MultiversX. It should sign and sign out the user. After the user is signed in, there is a form with two fields, the address and amount of EGLD to send to this address. I would like to have all UI states, like pending, and also hide/show parts of the UI for logged-in users. It should use React js

Elven Guide

Creating a simple React application that integrates with MultiversX, allows user sign-in/sign-out, and facilitates sending EGLD transactions involves several steps. I'll outline the process and provide code snippets for each part of the application.

This React app will utilize useElven for connecting to MultiversX and handling authentication and transactions. You'll need to have Node.js and npm installed on your system to follow along.

Step 1: Create a New React App

First, create a new React application using Create React App:

npx create-react-app multiversx-app
cd multiversx-app

Step 2: Install useElven Dependency

Install @useelven/core to integrate with MultiversX:

npm install @useelven/core

Step 3: Set Up useElven

In your App.js, import and initialize useElven:

import React from 'react';
import { useLogin, useTransaction } from '@useelven/core';

function App() {
  const { login, isLoggedIn, logout } = useLogin();
  const { triggerTx, pending } = useTransaction();

  // UI states (e.g., showing pending state, handling form submission)
  // ...

  return (
    <div className="App">
      {
        isLoggedIn ?
          <LoggedInView
            onSendEgld={handleSendEgld}
            onLogout={logout}
            isLoading={pending}
          /> :
          <LoginView onLogin={login} />
      }
    </div>
  );
}

// Components for LoggedInView and LoginView
// ...

export default App;

Step 4: Implement Login and Logout UI

Create components for login and logout views:

function LoginView({ onLogin }) {
  return (
    <div>
      <button onClick={() => onLogin()}>Login</button>
    </div>
  );
}

function LoggedInView({ onSendEgld, onLogout, isLoading }) {
  // Form submission logic and UI
  // ...

  return (
    <div>
      <button onClick={onLogout}>Logout</button>
      {/* Form for EGLD transfer */}
      {/* Loading indicator if isLoading is true */}
    </div>
  );
}

Step 5: Implement EGLD Transfer Functionality

In the LoggedInView, add a form to accept the address and amount, and handle submission:

// Inside LoggedInView component
const handleFormSubmit = (event) => {
  event.preventDefault();
  const address = event.target.address.value;
  const amount = event.target.amount.value;
  onSendEgld(address, amount);
};

return (
  <form onSubmit={handleFormSubmit}>
    <input name="address" type="text" placeholder="Address" required />
    <input name="amount" type="number" placeholder="Amount" required />
    <button type="submit">Send EGLD</button>
  </form>
);

Step 6: Sending EGLD Transaction

Implement the handleSendEgld function in App.js to create and send the EGLD transaction:

const handleSendEgld = async (address, amount) => {
  // Use triggerTx from useTransaction to send EGLD
  // ...

  try {
    await triggerTx({
      address,
      value: amount,
      // Additional parameters like gasLimit, data, etc.
    });
  } catch (error) {
    console.error('Transaction failed:', error);
  }
};

Step 7: Managing UI States

Handle different UI states (e.g., pending, error) using React state hooks. Show appropriate messages or loaders based on these states.

Step 8: Run the App

Finally, start your React application:

npm start

This app will now let users log in, send EGLD to a specified address, and log out. Remember to handle errors and edge cases appropriately for a production-level application. This example provides a basic structure and may require further customization based on your specific requirements.

ユーザー

could you be more specific with the code?

Elven Guide

Certainly! Let's create a more detailed React application that integrates with MultiversX. This app will include user authentication and a form for sending EGLD transactions. We'll use useElven for authentication and transaction handling.

Step 1: Create React App and Install Dependencies

  1. Create a new React app:

    npx create-react-app multiversx-app
    cd multiversx-app
    
  2. Install @useelven/core:

    npm install @useelven/core
    

Step 2: Initialize useElven in React

In your src/App.js, set up the basic structure:

import React, { useState } from 'react';
import { useLogin, useTransaction } from '@useelven/core';

function App() {
  const { login, isLoggedIn, logout } = useLogin();
  const { triggerTx, pending } = useTransaction();
  const [transactionStatus, setTransactionStatus] = useState('');

  const handleSendEgld = async (address, amount) => {
    try {
      await triggerTx({
        address,
        value: amount,
        data: '', // Transaction data (if any)
        gasLimit: 50000, // Adjust as necessary
      });
      setTransactionStatus('Transaction sent successfully');
    } catch (error) {
      console.error('Transaction failed:', error);
      setTransactionStatus('Transaction failed');
    }
  };

  return (
    <div className="App">
      {
        isLoggedIn ?
          <LoggedInView
            onSendEgld={handleSendEgld}
            onLogout={logout}
            isLoading={pending}
            transactionStatus={transactionStatus}
          /> :
          <LoginView onLogin={login} />
      }
    </div>
  );
}

export default App;

Step 3: Create Login and Logout Components

Create two components, LoginView and LoggedInView, in separate files or within App.js:

function LoginView({ onLogin }) {
  return (
    <div>
      <button onClick={() => onLogin()}>Login</button>
    </div>
  );
}

function LoggedInView({ onSendEgld, onLogout, isLoading, transactionStatus }) {
  const [address, setAddress] = useState('');
  const [amount, setAmount] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    onSendEgld(address, amount);
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={address}
          onChange={(e) => setAddress(e.target.value)}
          placeholder="Recipient Address"
          required
        />
        <input
          type="number"
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
          placeholder="Amount of EGLD"
          required
        />
        <button type="submit" disabled={isLoading}>Send EGLD</button>
      </form>
      <button onClick={onLogout}>Logout</button>
      {isLoading && <p>Sending transaction...</p>}
      {transactionStatus && <p>{transactionStatus}</p>}
    </div>
  );
}

Step 4: Styling (Optional)

For a basic styling, you can add CSS in src/App.css.

Step 5: Run Your Application

Start your app:

npm start

This setup provides a basic React application integrated with MultiversX using useElven. Users can log in, send EGLD, and log out. Make sure to handle errors and edge cases for a more robust application. This code serves as a starting point and might need adjustments based on your specific requirements and the useElven version.