Web (JavaScript/TypeScript)

Leveraging Particle Connect within web applications

Particle Connect for Web

Particle Connect acts as a simple method of aggregating connection with both Web2 accounts through Particle Auth and Web3 accounts through traditional wallets, creating an equally accessible experience for both Web3 natives and traditional consumers. Specifically, Particle Connect is a custom connection modal built around interaction with Particle.

Leveraging Particle Connect as the primary connection mechanism (the "Connect" button within your application) only takes a few steps, as outlined below.

Demo

Before beginning, if you'd like to view a demo for Particle Connect, the official web demo contains a page with a standard implementation, viewable here.

Getting Started

Installation

Implementing Particle Connect can be achieved in four main steps. By the end of step four, your application will have a "Connect" button capable of onboarding both Web2 and Web3 users alike, powered directly by Particle Network.

For step one, you'll need to install the Particle Connect Web SDK. In this case, you'll need two libraries. We'll be focusing on the first, @particle-network/connect-react-ui, which includes a native RainbowKit-like UI for facilitating connection, although @particle-network/connect is available too and will be covered later for more direct control over and customization of Particle Connect.

yarn add @particle-network/connect-react-ui

yarn add @particle-network/connect

Setting up the Particle dashboard

Before jumping directly into configuration and implementation, you'll need to make sure that you've retrieved your projectId, clientKey, and appId from the Particle dashboard. These are required values that you'll need in the coming configuration process. Retrieving these can be done through the following:

  1. Sign up/log in to the Particle dashboard

  1. Create a new project or enter an existing project if you already have one.

  1. Create a new web application, or skip this step if you already have one.

  1. Retrieve the project ID (projectId), the client key (clientKey), and the application ID (appId).

‎‎

‎‎

‎‎

‎‎

Configuration

With Particle Connect installed, you'll need to open your index file and wrap your App component with ModalProvider, imported from @particle-network/connect-react-ui. Within ModalProvider, you'll have a variety of configurations to set:

  • projectId, clientKey, and appId, these are required values for configuring Particle Connect and can be retrieved from the Particle dashboard
  • particleWalletEntry, an optional object containing additional parameters determining the configuration of the Particle wallet modal.
    • displayWalletEntry, dictating whether or not the wallet modal (only upon social login) will display on-screen or not.
    • defaultWalletEntryPosition, if the former is set to true, then defaultWalletEntryPosition will determine the quadrant of the screen in which the wallet modal (small circle, opens a larger wallet menu) pops up.
    • supportChains, an array of chains to be supported within the wallet modal.
    • customStyle, JSON dictating further modal customizations.
  • securityAccount, an optional object containing additional parameters determining the configuration of a user's security account.
    • promptSettingWhenSign, the frequency at which a user will be reminded to set a payment password (password required upon state-changing signatures).
      • 0 for never, 1 for once (which is the default), and 2 for always.
    • promptMasterPasswordSettingWhenLogin, the frequency at which a user will be reminded to set a master password (password required upon login).
      • 0 for never, 1 for once (which is the default), and 2 for always.

In addition to the configurations within options, you can set:

  • theme, the theme of the connection UI, either light, dark, or auto (dependent on system settings).
  • language, the language used by the connection UI (optional.)
  • walletSort, the labels used for the different wallet categories (optional.)
  • particleAuthSort the specific Particle authentication mechanisms shown within the connection UI, and the order in which they're shown.

Below is a code snippet showcasing a structured configuration of ModalProvider, leveraging the parameters listed above.

import { ModalProvider } from '@particle-network/connect-react-ui'; // @particle-network/connectkit to use Auth Core
import { WalletEntryPosition } from '@particle-network/auth';
import { Ethereum, EthereumGoerli } from '@particle-network/chains';
import { evmWallets } from '@particle-network/connect';

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
  <React.StrictMode>
    <ModalProvider
      options={{
        projectId: 'replace with your projectId',
        clientKey: 'replace with your clientKey',
        appId: 'replace with your appId',  
        chains: [
          Ethereum,
          EthereumGoerli
        ],
        particleWalletEntry: {    //optional: particle wallet config
          displayWalletEntry: true, //display wallet button when connect particle success.
          defaultWalletEntryPosition: WalletEntryPosition.BR,
          supportChains:[
            Ethereum,
            EthereumGoerli  
          ],
          customStyle: {}, //optional: custom wallet style
        },
        securityAccount: { //optional: particle security account config
          //prompt set payment password. 0: None, 1: Once(default), 2: Always  
          promptSettingWhenSign: 1,
          //prompt set master password. 0: None(default), 1: Once, 2: Always
          promptMasterPasswordSettingWhenLogin: 1 
        },
        wallets: evmWallets({
          projectId: 'walletconnect projectId', //replace with walletconnect projectId
          showQrModal: false
       }),
      }}
      theme={'auto'}
      language={'en'}   //optional:localize, default en
      walletSort={['Particle Auth', 'Wallet']} //optional:walelt order
      particleAuthSort={[    //optional:display particle auth items and order
          'email',
          'phone',
          'google',
          'apple',
          'facebook'
      ]}
    >
      <App />
    </ModalProvider>
  </React.StrictMode>
);
import React from 'react'
import ReactDOM from 'react-dom/client'
import { Ethereum, EthereumGoerli } from '@particle-network/chains';
import { ModalProvider } from '@particle-network/connectkit';
import '@particle-network/connectkit/dist/index.css';
import { evmWallets, solanaWallets } from '@particle-network/connectors';

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <ModalProvider
        options={{
            projectId: process.env.REACT_APP_PROJECT_ID as string,
            clientKey: process.env.REACT_APP_CLIENT_KEY as string,
            appId: process.env.REACT_APP_APP_ID as string,
            chains: [Ethereum, EthereumGoerli],
            connectors: [
                ...evmWallets({ projectId: process.env.REACT_APP_WALLETCONNECT_ID, showQrModal: true }),
                ...solanaWallets(),
            ],
            erc4337: { //optional: account abstraction wallet UI config (displaying the smart account rather than EOA)
              name: "SIMPLE",
              version: "1.0.0"
            },
            wallet: { //optional: particle wallet config
                customStyle: {
                    supportChains: [Ethereum, EthereumGoerli],
                },
            },
        }}
    >
        <App />
    </ModalProvider>
  </React.StrictMode>
)

Adding the connection button

Moving out of your index file and into your main App component, you'll need to include the "Connect" button (ConnectButton from @particle-network/connect-react-ui or @particle-network/connectkit) to facilitate the utilization of Particle Connect.

A custom instance of the Connect button with modularized components can also be implemented by instead using ConnectButton.Customconfiguring specific customizations, as in the example below:

import '@particle-network/connect-react-ui/dist/index.css';
import { ConnectButton } from '@particle-network/connect-react-ui'; // @particle-network/connectkit to use Auth Core

// Standard ConnectButton utilization
export const App = () => {
  return <ConnectButton />;
};

// Custom ConnectButton utilization 
export const App = () => {
  return (
      <ConnectButton.Custom>
        {({ account, chain, openAccountModal, openConnectModal, openChainModal, accountLoading }) => {
          return (
            <div>
              <button onClick={openConnectModal} disabled={!!account}>
                Open Connect
              </button>
              <br />
              <br />
              <button onClick={openAccountModal} disabled={!account}>
                Open Account
              </button>
              <br />
              <br />  
              <button onClick={openChainModal} disabled={!account}>
                Open Switch Network
              </button>
              <div>
                <h3>account</h3>
                <p>{account}</p>
              </div>
            </div>
          );
        }}
      </ConnectButton.Custom>
  );
};

Examples of utilization

Check User is Connected

Once Particle Connect has been set up within a given application, you'll be able to check whether or not a user is connected (via Particle Connect, either with Particle Auth or a traditional Web3 wallet) through the utilization of useAccount.

import { useAccount } from '@particle-network/connect-react-ui';

const account = useAccount();
if (account) {
  // Truthy indicates a successful login, active session
}

Open Particle Web Wallet

If a user has chosen to connect with Particle Auth, they aren't confined to interacting with that account through the in-app modal previously mentioned. A redirect/instance of the web wallet can be opened, the specifics of which are determined by various configurations and customizations, as shown in the example below:

import { useConnectKit } from '@particle-network/connect-react-ui';

const connectKit = useConnectKit();
// Custom window style
connectKit.particle.openWallet(target?: string, features?: string);

// Custom iframe
const url = connectKit.particle.buildWalletUrl({
  // Optional: Top left navigation item
  // "fullscreen": Standard fullscreen toggle
  // "close": Click event needs specific handling, see below
  topMenuType: "close"
});

const iframe = document.createElement("iframe");
iframe.src = url;

// Handling for 'close' navigation item
window.addEventListener("message", (event) => {
  if (event.data === "PARTICLE_WALLET_CLOSE_IFRAME") {
    // Close click event
  }
})

Open Crypto Token Buy

Another useful feature post-connect is the ability to launch an onramp menu for those authenticated with Particle Auth. This onramp ("Buy" feature) takes in either developer-defined or user-defined values and provides an aggregation of onramp providers to complete the requested transaction.

If you'd like to specify these values for the user, you can choose from the following parameters:

  • network, a string representing the network in which the onramp will occur (currently limited to Solana, Ethereum, Binance Smart Chain, Polygon, Tron, Optimism, and Arbitrum One.)
  • fiatCoin, the input fiat currency to be used within the onramp transaction.
  • cryptoCoin, the output cryptocurrency to be received within the onramp transaction.
  • fiatAmt, the amount of fiatCoin to be exchanged for cryptoCoin.
  • fixFiatCoin, a Boolean that if set to true, will lock a user from changing the input fiatCoin.
  • fixCryptoCoin, a Boolean that if set to true, will lock a user from changing the output cryptoCoin.
  • fixFiatAmt, a Boolean that if set to true, will lock a user from changing the input amount of fiatCoin.
  • walletAddress the receiving address.
import { useConnectKit } from '@particle-network/connect-react-ui';

const connectKit = useConnectKit();
connectKit.particle.openBuy(options?: OpenBuyOptions, target?: string, features?: string)

Get User Info

If a user is connected with Particle Auth through Particle Connect, you can use the useConnectKit hook to call the standard getUserInfo (among other functions) method to retrieve a detailed JSON string containing email, username, wallet addresses, UUID, token, etc.

import { useConnectKit } from '@particle-network/connect-react-ui';

const connectKit = useConnectKit();
const userInfo = connectKit.particle.auth.getUserInfo();
// .auth corresponds with standard methods available through {an instance of ParticleNetwork}.auth
// See https://developers.particle.network/reference/auth-web for more information on this

Connect React Hooks

As you may have noticed, Particle Connect comes with a number of important React Hooks for interacting with both Particle Connect and Particle Auth. They are:

  • useParticleProvider - Retrieval of the EIP-1193 provider instance to be used in ethers, web3.js, or viem.

  • useAccount - Pulls the currently active account (address).

  • useParticleConnect - Facilitates connection through connect and disconnect.

  • useConnectKit - Utilizes Particle Auth Web SDK through connectKit.particle.{method}.

  • useConnectModal - Opens the connect modal (openConnectModal) without using ConnectButton.

  • useConnectId - Retrieval of the connected ID.

  • useSwitchChains - Switches and retrieves the current primary chain.

  • useLanguage - Switches and retrieves current language used in UI.

  • useWalletMetas - Returns wallet metadata.

Connect Core

As mentioned a few times throughout this document, an alternative to @particle-network/connect-react-ui (which uses Particle Auth) is @particle-network/connectkit (which used Particle Auth Core). This library operates in almost exactly the same way, although with some minor changes in configuration and the specific hooks used. Below is an example of configuring @particle-network/connectkit, ideally within an index file, similar to the formerly covered @particle-network/connect-react-ui configuration process.

With @particle-network/connectkit configured, you'll be able to facilitate connection through the same ConnectButton object that was present within @particle-network/connect-react-ui. ConnectButton is, by default, a standard "Connect Wallet" button; this operates exactly the same as @particle-network/connect-react-ui, with the main difference being that the social login options ("Particle Auth") are routed through Particle Auth Core, not the traditional Particle Auth SDK.

An example of configuring @particle-network/connectkit can be found on the "index.tsx" tab within the snippet below, while an example of leveraging ConnectButton can be found within the "App.tsx" tab (this is the same example as is covered above for @particle-network/connect-react-ui.

import { ModalProvider } from '@particle-network/connectkit';
import { Ethereum, EthereumGoerli } from '@particle-network/chains';
import { evmWallets } from '@particle-network/connectors';

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
    <React.StrictMode>
        <ModalProvider
            options={{
                projectId: 'replace with your projectId',
                clientKey: 'replace with your clientKey',
                appId: 'replace with your appId',
                chains: [
                    Ethereum,
                    EthereumGoerli
                ],
                wallet: {    //optional: particle wallet config
                    visible: true, //display wallet button when connect particle success.
                    supportChains:[
                        Ethereum,
                        EthereumGoerli
                    ],
                    customStyle: {}, //optional: custom wallet style
                },
                promptSettingConfig: { //optional: particle security account config
                    //prompt set payment password. 0: None, 1: Once(default), 2: Always
                    promptPaymentPasswordSettingWhenSign: 1,
                    //prompt set master password. 0: None(default), 1: Once, 2: Always
                    promptMasterPasswordSettingWhenLogin: 1
                },
                connectors: evmWallets({ 
                    projectId: 'walletconnect projectId', //replace with walletconnect projectId
                    showQrModal: false
                 }),
            }}
            theme={'light'}
            language={'en'}   //optional:localize, default en
            walletSort={['Particle Auth', 'Wallet']} //optional:wallet order
        >
            <App />
        </ModalProvider>
    </React.StrictMode>
);
import { ConnectButton } from '@particle-network/connectkit';
// Standard ConnectButton utilization
export const App = () => {
  return <ConnectButton />;
};

// Custom ConnectButton utilization 
export const App = () => {
  return (
      <ConnectButton.Custom>
        {({ account, chain, openAccountModal, openConnectModal, openChainModal, accountLoading }) => {
          return (
            <div>
              <button onClick={openConnectModal} disabled={!!account}>
                Open Connect
              </button>
              <br />
              <br />
              <button onClick={openAccountModal} disabled={!account}>
                Open Account
              </button>
              <br />
              <br />  
              <button onClick={openChainModal} disabled={!account}>
                Open Switch Network
              </button>
              <div>
                <h3>account</h3>
                <p>{account}</p>
              </div>
            </div>
          );
        }}
      </ConnectButton.Custom>
  );
};

📘

For an example of the differences between @particle-network/connect-react-ui and @particle-network/connectkit, see the below links.

@particle-network/connectkit demo application: https://core-demo.particle.network/connect.html

@particle-network/connect-react-ui demo application: https://web-demo.particle.network/connectKit

Connect Standalone

Finally, as briefly mentioned earlier, @particle-network/connect can be used independently (through an instance of ParticleConnect in this case) for direct and detached utilization of Particle Connect. This provides the same level of functionality present in @particle-network/connect-react-ui, but within an isolated environment, opening up the possibility for a custom UI implementation.

import { evmWallets, ParticleConnect } from '@particle-network/connect';
import { Ethereum } from '@particle-network/chains';


const connectKit = new ParticleConnect({
            projectId: 'projectId',
            clientKey: 'clientKey',
            appId: 'appId',
            chains: [
                Ethereum
            ],
            wallets: evmWallets({ qrcode: false }),
        });

connectKit.connect('wallet id');

connectKit.connect('particle', options);

connectKit.disconnect();

connectKit.connectToCachedProvider();

connectKit.on('connect', (provider) => {});
connectKit.on('disconnect', () => {});
connectKit.on('chainChanged', (chain) => {});
connectKit.on('accountsChanged', (accounts) => {});

connectKit.switchChain(chain);

connectKit.walletMetas();

evmWallets();

evmInjectedWallet();  

getInjectedProvider();

📘

For an example of the differences between @particle-network/connect-react-ui and @particle-network/connectkit, see the below links.

@particle-network/connectkit demo application: https://core-demo.particle.network/connect.html

@particle-network/connect-react-ui demo application: https://web-demo.particle.network/connectKit