Giter VIP home page Giter VIP logo

xmtp-quickstart-reactjs's Introduction

Developer Quickstart

XMTP (Extensible Message Transport Protocol) is an open protocol and network for secure and private web3 messaging. For example, you can build an app with XMTP to send messages between blockchain accounts, including chat/DMs, alerts, announcements, and more.

Demo App

This repository demonstrates the implementation of these concepts within a simple chat app.

GitHub repo

git clone git@github.com:fabriguespe/xmtp-quickstart-reactjs.git
cd xmtp-quickstart-reactjs
npm install
npm run dev

Learning Objectives:

  • Setting up the ConnectWallet button
  • Signing in with XMTP
  • Loading a conversation
  • Sending a message

Getting Started

The first step involves creating and configuring the Next.js application.

To generate a new Next.js app, execute the following command in your terminal:

npx create-react-app xmtp-quickstart-reactjs

Next, navigate into the newly created directory and install the necessary dependencies:

npm i @dynamic-labs/sdk-react-core @dynamic-labs/ethereum-all @xmtp/xmtp-js

Trouble shooting

//When using client-side libraries, additional polyfills are required.
npm i assert stream -D
//To ignore the sourcemap warnings, create a .env file with the following in your root directory:

GENERATE_SOURCEMAP=false
Buffer polyfill

The Node Buffer API must be polyfilled in some cases. To do so, add the buffer dependency to your project and then polyfill it in your entry file.

  1. Create a polyfills.js file with the following code
import { Buffer } from "buffer";
window.Buffer = window.Buffer ?? Buffer;
  1. Insert it into your index.js on the first line
import "./polyfills";

Configuring the client

First we need to initialize XMTP client using as signer our wallet connection of choice.

import "./App.css";
import Home from "./components/Home";
import { DynamicContextProvider } from "@dynamic-labs/sdk-react-core";
import { EthereumWalletConnectors } from "@dynamic-labs/ethereum-all";

function App() {
  return (
    <DynamicContextProvider
      settings={{
        environmentId: "f0b977d0-b712-49f1-af89-2a24c47674da",
        walletConnectors: [EthereumWalletConnectors],
      }}
    >
      <Home />
    </DynamicContextProvider>
  );
}

export default App;

Display connect with XMTP

Now that we have the wrapper we can add a button that will sign our user in with XMTP.

{
  isConnected && !isOnNetwork && (
    <div className={styles.xmtp}>
      <DynamicWidget />
      <button onClick={initXmtp} className={styles.btnXmtp}>
        Connect to XMTP
      </button>
    </div>
  );
}
// Function to initialize the XMTP client
const initXmtp = async function () {
  // Create the XMTP client
  const xmtp = await Client.create(signer, { env: "production" });
  //Create or load conversation with Gm bot
  newConversation(xmtp, PEER_ADDRESS);
  // Set the XMTP client in state for later use
  setIsOnNetwork(!!xmtp.address);
  //Set the client in the ref
  clientRef.current = xmtp;
};

Load conversation and messages

Now using our hooks we are going to use the state to listen whan XMTP is connected.

Later we are going to load our conversations and we are going to simulate starting a conversation with one of our bots

useEffect(() => {
  if (isOnNetwork && convRef.current) {
    // Function to stream new messages in the conversation
    const streamMessages = async () => {
      const newStream = await convRef.current.streamMessages();
      for await (const msg of newStream) {
        const exists = messages.find((m) => m.id === msg.id);
        if (!exists) {
          setMessages((prevMessages) => {
            const msgsnew = [...prevMessages, msg];
            return msgsnew;
          });
        }
      }
    };
    streamMessages();
  }
}, [messages, isOnNetwork]);

Listen to conversations

In your component initialize the hook to listen to conversations

const [history, setHistory] = useState(null);
const { messages } = useMessages(conversation);
// Stream messages
const onMessage = useCallback((message) => {
  setHistory((prevMessages) => {
    const msgsnew = [...prevMessages, message];
    return msgsnew;
  });
}, []);
useStreamMessages(conversation, onMessage);

xmtp-quickstart-reactjs's People

Contributors

matthew1809 avatar fabriguespe avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.