Particle Connect for React Native

Particle Connect fully supports React Native, facilitating unified Web2 and Web3 onboarding within mobile applications leveraging React Native.

It is a custom connection modal meant to act as an SSO for Web3, aggregating social logins and traditional Web3 wallets (even using imported accounts) within one interface, enabling universal accessibility for both Web3 natives and typical Web2 consumers.

Details on installing, configuring, and utilizing the Particle Connect React Native SDK are below.

Repository

The ‘particle-react-native ’ GitHub repository includes a demo showcasing the utilization of the Particle Connect React Native SDK, alongside the source code powering the SDK. Before diving in, consider reviewing the code within this repository for an initial understanding of the underlying architecture.

Using a private key or the mnemonic import/generate function is strongly discouraged. If you use it, you need to secure the data yourself, as Particle doesn’t have a relationship with the imported/generated mnemonic or private key.

Getting Started

The setup process for the Particle Connect React Native SDK is relatively straightforward but expectedly deviates depending on the platform.

Before diving into the platform-specific configuration, all Particle Connect (& Auth) SDKs require three standard initialization values: projectId, clientKey, and appId. These can be retrieved from the Particle dashboard.

Follow the quickstart tutorial to set up a project and find the required keys: Create a new project.

Adding the Particle Connect React Native SDK to your application

Another constant in the setup process is the installation of @particle-network/rn-connect, either through npm or Yarn, depending on your preference, as is shown below.

Terminal
npm install @particle-network/rn-connect

// Or

yarn add @particle-network/rn-connect

Android configuration

If you’re planning on using Android for your React Native application, ensure that you meet the following prerequisites (otherwise, expect issues or non-functionality):

  • minSdkVersion 23 or higher.
  • compileSdkVersion, targetSdkVersion 34 or higher.
  • JavaVersion 17.
  • Jetpack (AndroidX).
  • Android Gradle Plugin Version : 8.5.1 or higher.
  • Gradle Version : 8.9 or higher.(before react-native:0.75.2, use 8.8)

Once you’ve made sure your project meets these requirements, you’ll need to move on and define the configuration above values (projectId, clientKey, and appId) within your build.grade file (generally found at ${project name}/android/app/build.gradle). These directly link your application’s instance of Particle Connect with the dashboard.

Specifically, within build.gradle, you’ll need to set four different values:

  1. dataBinding, this should be enabled with enabled = true.
  2. manifestPlaceholders["PN_PROJECT_ID"], the projectId previously retrieved from the Particle dashboard.
  3. manifestPlaceholders["PN_PROJECT_CLIENT_KEY"], the clientKey previously retrieved from the Particle dashboard.
  4. manifestPlaceholders["PN_APP_ID"], the appId previously retrieved from the Particle dashboard.
build.gradle
android {
  ...
  defaultConfig {
      ......
      manifestPlaceholders["PN_PROJECT_ID"] = "Your project ID"
      manifestPlaceholders["PN_PROJECT_CLIENT_KEY"] = "Your client key"
      manifestPlaceholders["PN_APP_ID"] = "Your app ID"
  }

  dataBinding {
      enabled = true
  }

}

iOS configuration

Alternatively, if you plan to use iOS for your React Native application, the underlying setup process differs slightly. Before diving in, ensure that your project meets the following requirements:

  • Xcode 15.0 or later.

  • iOS 14 or later.

With these requirements set, you’ll need to open an exported iOS project and find ios/{project name}.xcworkspace.

At the root of your Xcode project, create a new file, ParticleNetwork-Info.plist. Ensure this is marked under “Target Membership.”

From here, with a fresh ParticleNetwork-Info.plist file, go ahead and fill it in with the following:

ParticleNetwork-Info.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>PROJECT_UUID</key>
	<string>YOUR_PROJECT_UUID</string>
	<key>PROJECT_CLIENT_KEY</key>
	<string>YOUR_PROJECT_CLIENT_KEY</string>
	<key>PROJECT_APP_UUID</key>
	<string>YOUR_PROJECT_APP_UUID</string>
</dict>
</plist>

Similar to the Android configuration, you’ll need to fill in PROJECT_UUID (projectId), PROJECT_CLIENT_KEY (clientKey), and PROJECT_APP_UUID (appId) with the corresponding values retrieved from the Particle dashboard.

Next, you’ll need to head over to your AppDelegate.swift file to add an import of react_native_particle_connect.

AppDelegate.swift
#import <react_native_particle_connect/react_native_particle_connect-Swift.h>

Additionally, within your application’s application method (as shown below), you’ll need to include a handler condition derived from ParticleConnectSchemeManager handleUrl:url. This should be as simple as a YES (true) return upon a true value of ParticleConnectSchemeManager handleUrl:url.

AppDelegate.swift
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
  if ([ParticleConnectSchemeManager handleUrl:url] == YES) {
    return YES;
  } else {
    // Other methods
  }
  return YES;
}

To wrap up, you’ll need to configure your application’s scheme URL. To do so, select your application from “TARGETS” under the “Info” section, then click ”+” to add a URL type.

This should be set to “pn” + your projectId (retrieved and configured prior), resulting in a scheme URL that looks something like the following:

pn63bfa427-cf5f-4742-9ff1-e8f5a1b9828f

Additionally, head over to your Info.plist file and include the following snippet.

Info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
	<string>metamask</string>
	<string>phantom</string>
	<string>bitkeep</string>
	<string>imtokenv2</string>
	<string>rainbow</string>
	<string>trust</string>
	<string>zerion</string>
  <string>mathwallet</string>
  <string>oneinch</string>
  <string>awallet</string>
  <string>okex</string>
  <string>bnc</string>
</array>
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access in order to open photos of barcodes</string>
<key>NSCameraUsageDescription</key>
<string>We use the camera to scan barcodes</string>
<key>NSFaceIDUsageDescription</key>
<string>We use Face ID for secure access to the app.</string>

Finally, you must edit your Podfile to ensure that particle_connect is correctly imported. If you haven’t already, head over to the linked guide to complete this


Examples of Utilization

Initialization

Now that you’ve configured your project, it’s time to move on to initialization. This is required before the rest of the SDK will function. First, you’ll need to import @particle-network/rn-connect, which generally can be imported in whole as a singular variable (in the example below, particleConnect.)

import * as particleConnect from '@particle-network/rn-connect';

Initialization happens through init on your imported instance of @particle-network/rn-connect, particleConnect in this case. init takes the following parameters:

  • chainInfo contains relevant information that determines the primary chain to be used within Particle Connect. (ChainInfo objects, such as Ethereum, Polygon, etc. can be imported from @particle-network/chains)
  • env, imported from @particle-network/rn-connect, and can be either:
  • Env.Production.
  • Env.Staging.
  • Env.Dev.
  • metadata, an instance of DappMetaData containing the following parameters:
  • walletConnectProjectId, your WalletConnect project ID retrieved from the WalletConnect dashboard.
  • name is the name of your project.
  • icon, your project’s logo, ideally 512x512.
  • url, the URL of your project’s website.
  • description is a description of your project.
  • redirect is a provided redirect that can be left blank.
  • verifyUrl, a URL for verification, can be left blank.

Additionally, extra chains can be configured for WalletConnect through setWalletConnectV2SupportChainInfos and passing in an array of ChainInfo objects representing the different chains you’d like to be supported by your instance of WalletConnect. E.g.:

const chainInfo: ChainInfo = Ethereum;
    const env = Env.Dev;
    const metadata = {
      walletConnectProjectId: 'Your WalletConnect Project ID',
      url: 'https://connect.particle.network',
      icon: 'https://connect.particle.network/icons/512.png',
      name: 'Particle Connect',
      description: 'Particle Wallet'
    }

particleConnect.init(chainInfo, env, metadata);
particleAuthCore.init();

const chainInfos = [Ethereum, Polygon, EthereumSepolia];
particleConnect.setWalletConnectV2SupportChainInfos(chainInfos);

Connect Wallet V2

particleConnect.connectWithConnectKitConfig is a one-click login function that can present a customizable login UI. The parameter config can be derived from ConnectKitConfig.

ConnectKitConfig.init includes the following parameters:

FieldTypeDescription
connectOptionsConnectOption[]Methods supported for connection, EMAIL, PHONE, SOCIAL and WALLET; the order in which these are placed will be reflected within the modal.
socialProvidersEnableSocialProvider[]?Supported social login methods, such as GOOGLE, APPLE and other social options; the order in which these are placed will be reflected within the modal.
walletProvidersEnableWalletProvider[]?Supported wallet providers, such as MetaMask, Trust and other wallet options; the order in which these are placed will be reflected.
additionalLayoutOptionsAdditionalLayoutOptions?Layout options.
logostring?Image URL or base64 string representing the logo used within the modal.
const config = {
      //  You can control the array elements and adjust the order shown in the UI
      connectOptions: [ConnectOption.Email, ConnectOption.Phone, ConnectOption.Social, ConnectOption.Wallet],
      //  You can control the array elements and adjust the order shown in the UI
      socialProviders: [EnableSocialProvider.Google, EnableSocialProvider.Apple, EnableSocialProvider.Twitter, EnableSocialProvider.Discord, EnableSocialProvider.Github],
      //  You can control the array elements and adjust the order shown in the UI
      walletProviders: [{ enableWallet: EnableWallet.MetaMask, label: EnableWalletLabel.Recommended },
      { enableWallet: EnableWallet.OKX, label: EnableWalletLabel.Popular },
      { enableWallet: EnableWallet.Trust, label: EnableWalletLabel.None },
      { enableWallet: EnableWallet.Bitget, label: EnableWalletLabel.None }
      ],

      additionalLayoutOptions: {
        isCollapseWalletList: false,
        isSplitEmailAndSocial: true,
        isSplitEmailAndPhone: false,
        isHideContinueButton: false,
      },
      logo: base64Icon // base64 string or image URL
    };

const accountInfo = await particleConnect.connectWithConnectKitConfig(config);

Connect Wallet V1 (Legacy)

To directly connect a user with a given wallet type (throwing a connection menu within the current instance), you’ll need to use connect. Within connect, you’ll need to pass in a given walletType, an item selected from WalletType, imported from @particle-network/rn-connect. WalletType can be set to any of the following:

  • AuthCore, Particle Auth Core, an alternative to Particle Auth (Particle).
  • EvmPrivateKey, custom EVM wallet imports/exports.
  • SolanaPrivateKey, custom Solana wallet imports/exports.
  • MetaMask.
  • Rainbow.
  • Trust.
  • ImToken.
  • BitKeep.
  • WalletConnect.
  • Phantom, intended for Solana.
  • Zerion.
  • Math.
  • Inch1, 1inch.
  • Zengo.
  • Alpha.
  • Bitpie.
  • OKX.
  • TokenPocket, not supported by iOS.

If you’re using AuthCore, you’ll also need to pass in a ParticleConnectConfig object containing:

FieldTypeDescription
loginTypeLoginTypeThe specific social login to be used. This can be either .email, .phone, .google, .apple, .jwt, .facebook, .twitter, .discord, .github, .twitch, .microsoft or linkedin.
accountstring?(Optional) When type is set to either .email, .phone, or .jwt, you can use the account parameter to pass in an expected email, phone number, or JWT. This is optional for the former two, but required for .jwt. When passing a phone number, it must be in E.164 format.
codestring?(Optional) when type is set to either .email pr .phone, you can use the code parameter to pass the verification code.
supportAuthTypeSupportAuthType[]The methods of authentication visible on the authentication popup UI. By default, this will be exclusive to the chosen social login method, although by passing in additional types, you can expand the UI to include the ability to login with those as an alternative to type.
socialLoginPromptSocialLoginPrompt?(Optional) either .None, .Consent, or .SelectAccount
loginPageConfigLoginPageConfig?(Optional) Changes what the OAuth provider prompts a user to do; either .none, .consent, or .select_account. Only Google, Discord and Microsoft support it.

E.g:

const connectConfig = {
  loginType: LoginType.Google,
  supportAuthType: [SupportAuthType.Phone, SupportAuthType.Google, SupportAuthType.Apple],
  socialLoginPrompt: SocialLoginPrompt.SelectAccount,
  loginPageConifg: {
    projectName: "React Native Example",
    description: "Welcome to login",
    imagePath: "https://connect.particle.network/icons/512.png"
  }
};

const result = await particleConnect.connect(
  WalletType.AuthCore,
  connectConfig
);

Disconnect

Additionally, after connecting and initiating an active session, you can programmatically disconnect a given user (defined by an address within a specified WalletType) from your application through disconnect. This requires both the relevant WalletType and associated address as parameters. E.g.:

const result = await particleConnect.disconnect(walletType, publicAddress);

Is Connected

Often, it helps to know whether or not a user is connected. This can be retrieved as a Boolean indicating connection status by calling isConnected and passing in the corresponding WalletType and address. E.g.:

const result = await particleConnect.isConnected(walletType, publicAddress);

Sign Message (EIP191)

A simple message (UTF-8 string) can be signed on both EVM & Solana through ParticleConnect.signMessage, passing in the WalletType, address (publicAddress in this example), and the message in question. message should either be a hex-encoded string for EVM, or a base58 string for Solana. E.g.:

const signature = await particleConnect.signMessage(walletType, publicAddress, message);

Sign Transaction

For Solana, as an alternative to signAndSendTransaction, you can sign a given transaction without pushing it to the network with particleConnect.signTransaction, taking WalletType, address (publicAddress), and a base58 transaction string representing a structured transaction object.

Alternatively, the plural of this method is particleConnect.signAllTransactions, which instead takes an array of base58 transaction strings to be prompted for signature.

const signature = await particleConnect.signTransaction(WalletType.authCore, publicAddress, transaction);

// Plural
const signature = await particleConnect.signAllTransactions(WalletType.authCore, publicAddress, transactions);

Sign and Send Transaction

As the primary mechanism of sending transactions, particleConnect.signAndSendTransaction takes in a transaction and prompts a user (through a UI corresponding with WalletType) for confirmation/signature.

Specifically, particleConnect.signAndSendTransaction takes a WalletType, address (publicAddress), and transaction string. For EVM chains, this should be a hex-encoded string Solana and a base58 string. An example of this can be found below.

const txHash = await particleConnect.signAndSendTransaction(WalletType.authCore, publicAddress, transaction);

Sign Typed Data V4 (EIP712)

Additionally, for EVM chains, if standard UTF-8 string signatures aren’t enough, you can use ParticleConnect.signTypedData to prompt the signature of typed (structured) data adjacent to eth_signTypedData.

ParticleConnect.signTypedData requires WalletType, address (publicAddress), and the typedData to be signed. typedData should be a hex-encoded string representing a data structure. E.g.:

const signature = await particleConnect.signTypedData(walletType, publicAddress, typedData)

Import Wallet

If you’re using the ‘EvmPrivateKeyorSolanaPrivateKey` wallet types, you can import wallets through either a seed phrase or private key. These methods will associate an account instance derived from these keys, allowing utilization within your application.

These can be achieved through either importPrivateKey for importing a private key, or importMnemonic for importing a mnemonic (seed phrase). These methods require the WalletType (either EvmPrivateKey or SolanaPrivateKey) and the private key/seed phrase to be imported.

Additionally, you can export one of these wallets with exportPrivateKey, passing in the address (of the EvmPrivateKey or SolanaPrivateKey imported/generated wallet) that you’d like to export.

const account = await particleConnect.importPrivateKey(walletType, privateKey);

const account = await particleConnect.importMnemonic(walletType, mnemonic);

const privateKey = await particleConnect.exportPrivateKey(walletType, publicAddress);

Get Accounts

Within an active session, you can retrieve the accounts (addresses) that belong to a specific WalletType (connection mechanism). This is done through getAccounts and returns an array of addresses within the current session associated with a given WalletType. E.g.:

const accounts = await particleConnect.getAccounts(walletType);

(Optional) Custom WalletConnect Projcet ID

// Call before particleConnect.init
particleConnect.setWalletConnectProjectId("Your WalletConnect Project ID")

Dive Deeper

@particle-network/rn-connect includes @partcile-connect/rn-auth-core.

If you log in with a Particle account, you can access additional functions such as getUserInfo, openAccountAndSecurity, hasMasterPassword and hasPaymentPassword and changeMasterPassword. You can also reference the docs from Auth SDK reference.