Particle Auth for Unity (Mobile)

In addition to the Windows/macOS Unity SDK, Particle Auth also extends to standard Unity for Mobile platforms (through C#). This SDK includes all the standard functions required for initializing and interacting with Particle Auth to craft a Web2-adjacent onboarding flow within your Unity games.

Instructions setting up, and a rundown of some common functions and examples are covered below.


Getting Started

Prerequisites

Your Unity project needs to meet several requirements to avoid any compatibility issues. These requirements will be, in some capacity, dependent on the platform that you’ve decided to use. They are:

  • Unity 2022.3.43f1 or higher.
  • If you’re using iOS:
    • Xcode 15.0 or higher.
    • CocoaPods 1.14.3 or higher.
    • iOS 14 or higher.
  • If you’re using Android:
    • 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.

Setting up the Particle dashboard

Once you’ve ensured that your project meets the above prerequisites, you’ll also need three key values from the Particle dashboard: your projectId, clientKey, and appId.

These connect your Unity project with the Particle dashboard, enabling customization, analytics, tracking, etc.

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

Configuration

With these values retrieved, you can move on to initial configuration and dependency management. This will vary in complexity depending on the platform in question. To begin, you’ll need to download and install the Particle Unity package, which includes the necessary files for both Particle Connect and Particle Auth.

Head over to the particle-unity GitHub repository, and download the latest release (.unitypackage), then import it into your project.

iOS configuration

If you’re building a Unity game on iOS, you must follow a specific configuration process to ensure that Particle Connect functions. The first step within this process is to set up a scheme URL within the Unity editor.

  1. Head into the iOS Player Settings menu (Edit -> Project Settings -> Player Settings -> iOS).
  2. From here, select Other, then scroll down to Configuration.
  3. Open the Supported URL schemes section, and within the Element 0 field, paste in your projectId with a prefix of pn.
    1. For example, if your projectId (from the Particle dashboard) is something like 63bfa427-cf5f-4742-9ff1-e8f5a1b9828f, then the scheme URL would be pn63bfa427-cf5f-4742-9ff1-e8f5a1b9828f.

Remove other services, if needed

Within ParticleNetworkIOSBridge.cs, you’ll have a number of services included in the SDK:

- ParticleNetworkBase - required universally.

- ParticleAuthCore - required for Particle Auth Core.

- ParticleConnect- required for Particle Connect.

  • ParticleWalletGUI - usage of the Particle Wallet UI, contains all services.

- ParticleAA - usage of the Particle AA, contains all services.

You’ll also need to configure your Podfile if you haven’t already. If you don’t have a Podfile, go to the root of your project directory and run pod init, which will generate a Podfile.

Copy our example Podfile

You can copy our examole Podfile, it will always use the latest version.

Open this Podfile, and insert the specific pods (services) you’d like to use within your project. In this case, ParticleConnect and CommonConnect will generally suffice, but additional services can be added if needed.

Additionally, you’ll need to paste the code snippet below for installation handling:

Podfile
  # Particle Network Base
  pod 'ParticleNetworkBase', '1.4.10'

  # Particle Connect Service
  pod 'ConnectCommon', '0.2.26'
  pod 'ConnectEVMAdapter', '0.2.26'
  pod 'ConnectSolanaAdapter', '0.2.26'
  pod 'ConnectWalletConnectAdapter', '0.2.26'
  pod 'ConnectPhantomAdapter', '0.2.26'
  pod 'ParticleConnect', '0.2.26'

  # Particle Wallet Service
  pod 'ParticleWalletConnect', '1.4.10'
  pod 'ParticleWalletAPI', '1.4.10'
  pod 'ParticleWalletGUI', '1.4.10'

  # Particle AA
  pod 'ParticleAA', '1.4.10'

  # Particle Auth Core
  pod 'AuthCoreAdapter', '1.4.10'
  pod 'ParticleAuthCore', '1.4.10'
  pod 'ParticleMPCCore', '1.4.10'
  pod 'Thresh', '1.4.10'

  pod 'SkeletonView', :git => 'https://github.com/SunZhiC/SkeletonView.git', :branch => 'main'
  pod 'SwiftyUserDefaults', :git => 'https://github.com/SunZhiC/SwiftyUserDefaults.git', :branch => 'master'
  pod 'WalletConnectSwiftV2', :git => 'https://github.com/SunZhiC/WalletConnectSwiftV2.git', :branch => 'particle'

// Paste this
post_install do |installer|
installer.pods_project.targets.each do |target|
  target.build_configurations.each do |config|
  config.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES'
    end
  end
 end

Also you can copy the example Podfile .

With your Podfile set, you’ll need to run pod install and open your .xcworkspace file, such as is shown below:

Terminal
pod install --repo-update

open {your project}.xcworkspace

Finally, for iOS, you’ll need to formally use the projectId, clientKey, and appId previously retrieved. To do this, head into the root of your Xcode project and create a file, ParticleNetwork-Info.plist. Within this file, paste the following text (then replace the placeholders):

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>

Follow the steps to configure your Xcode workspace.

  1. Download UnityManger.swift, Unity-iPhone-Bridging-Header.h and AppDelegate.swift from under github /Assets/Plugins/iOS/.Swift , Copy files into the root of your Xcode project. Xcode will ask you if auto create Bridging file, click yes.

  2. Make sure Build Settings, Swift Compiler - General, has Objective-C Bridging Header, its connect is Unity-iPhone-Bridging-Header.h ‘s local path.

  3. Remove main.mm under MainApp folder.

  4. Under /Assets/Plugins/iOS are NativeCallProxy files and Swift files , they are required by Unity to interact with iOS code. Remove code under Particle Wallet GUI if you don’t need wallet service.

  5. In UnityManger.swift, it has implemented methods defined in NativeCallProxy.h.

  6. Select NativeCallProxy.h, in the file inspector, check public in Target Membership.

  7. If you want to use ParticleConnect, you should add LSApplicationQueriesSchemes to info.plist.

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>

Android configuration

Alternatively, if you’re building your Unity game for Android, you’ll just need to configure two files before you’re ready to go. The first of these two files can be found at Assets/Plugins/Android/launcherTemplate.gradle within your project. Here, you’ll need to ensure that you have the necessary dependencies.

Specifically, you’ll need the following dependencies at a minimum:

  • network.particle:auth-serviceif you’re planning on using Particle Auth Directly
  • network.particle:unity-bridge, required universally
  • The full list of network.particle packages can be found here.
launcherTemplate.gradle
dependencies {
    implementation project(':unityLibrary')
    implementation "network.particle:auth-service:${sdkVersion}"
    implementation "network.particle:unity-bridge:${sdkVersion}"
  	implementation "network.particle:connect:${sdkVersion}"
  	// Other dependencies
}

Finally, for Android, you’ll need to place your projectId, clientKey, and appId within gradleTemplate.properties, found at Assets/Plugins/Android/gradleTemplate.properties.

gradleTemplate.properties
particle.network.project_client_key=Your Client Key
particle.network.project_id=Your Project ID
particle.network.app_id=Your App ID

Initialization

Before you can call core functions within the SDK, you’ll need to initialize ParticleNetwork. For the Unity SDK, this is handled by calling init on ParticleNetwork, which is derived from Network.Particle.Scripts.Core and passing in information about the primary chain being used. This is generally pulled from a child of ChainInfo.

The Particle Auth Unity SDK does not require authentication from the Particle dashboard.

ParticleNetwork.Init(ChainInfo.Ethereum);
ParticleAuthCoreInteraction.Init();

Add the prefab to your scene

Additionally, you’ll need to ensure ParticleAuthCore.prefab is added to your main scene. This is required as Particle Auth Core will not function otherwise.


Examples of Utilization

Connect

With Particle Auth Core configured and included within your first scene, you can leverage Particle Auth Core to initiate the social login onboarding process and thus unlock the remaining functions within the SDK (post-login).

This is achieved and configured via ParticleAuthCore.Instance.Connect. Once this method is called, a corresponding login popup will be displayed requesting user authentication before returning to the application in a signed-in state.

ParticleAuthCore.Instance.Connect takes the following parameters:

FieldTypeDescription
loginTypeLoginTypeThe specific social login to be used. This can be either .EMAIL, .PHONE, .GOOGLE, .FACEBOOK, .APPLE, .TWITTER, .DISCORD, .GITHUB, .TWITCH, .MICROSOFT, .LINKEDIN or JWT.
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. The phone number must be in E.164 format.
supportAuthTypeode[SupportAuthType]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) Changes what the OAuth provider prompts a user to do; either .none, .consent, or .select_account. Only Google, Discord and Microsoft support it.
loginPageConfigLoginPageConfig?(Optional) to customize the UI page, contains project name, icon and description.
var loginConfig = new LoginPageConfig("Particle Unity Example", "Welcome to login",
                            "https://connect.particle.network/icons/512.png");
List<SupportLoginType> allSupportLoginTypes =
                    new List<SupportLoginType>(Enum.GetValues(typeof(SupportLoginType)) as SupportLoginType[]);
await ParticleAuthCore.Instance.Connect(LoginType.EMAIL, null, SupportAuthType.ALL, SocialLoginPrompt.SelectAccount, loginConfig);

You can also costumize login page for email/phone, send code with method ParticleAuthCore.Instance.SendPhoneCode or ParticleAuthCore.Instance.SendEmailCode, connect with method ParticleAuthCore.Instance.ConnectWithCode

Disconnect

Once a user has been logged in, you can programmatically initiate logout through ParticleAuthCore.Instance.Disconnect.

await ParticleAuthCore.Instance.Disconnect();

Is Connected

Whether or not a user is logged in may need to be retrieved, specifically in cases where a user stays logged in after refreshing an application due to the continuation of a given session. To check the currently active login status, you can call ParticleAuthCore.Instance.IsConnected.

await ParticleAuthCore.Instance.IsConnected();

Get User Info

After connected, you can call ParticleAuthCoreInteraction.GetUserInfo to retrieve the userInfo.

var userInfo = ParticleAuthCoreInteraction.GetUserInfo()

Get Address

To retrieve the address of the currently active account (either EVM or Solana, depending on the previously selected chain), ParticleAuthCoreInteraction.EvmGetAddress or ParticleAuthCoreInteraction.SolanaGetAddress can be called.

var evmAddress = ParticleAuthCoreInteraction.EvmGetAddress()
var solanaAddress = ParticleAuthCoreInteraction.SolanaGetAddress()

Sign Message

Simple message signing can be achieved by calling ParticleAuthCore.Instance.EvmPersonalSign or ParticleAuthCore.Instance.SolanaPersonalSign and passing in a standard string (no need for encoding on this method) with the message you’d like to be prompted for signature.

var message = "Hello Particle!";

await ParticleAuthCore.Instance.EvmPersonalSign(message);
await ParticleAuthCore.Instance.EvmPersonalSignUnique(message);

await ParticleAuthCore.Instance.SolanaPersonalSign(message);

Sign Transaction

Similarly, for signing a transaction, you’ll need to call ParticleAuthCore.Instance.SolanaSignTransaction and pass in a serialized (string) standard transaction object to be prompted for signature. This is a Solana-specific method.

var transaction = "Your transaction";
await ParticleAuthCore.Instance.SolanaSignTransaction(transaction);

Sign All Transactions

ParticleAuthCore.Instance.SolanaSignAllTransactions is another Solana-specific method that functions adjacent to the former but instead signs multiple (a list of) transactions represented as strings.

var transaction1 = "Transaction1";
var transaction2 = "Transaction2";

string[] transactions = new[] { transaction1, transaction2 };

await ParticleAuthCore.Instance.SolanaSignAllTransactions(transactions);

Sign And Send Transaction

ParticleAuthCore.Instance.EvmSendTransaction and ParticleAuthCore.Instance.SolanaSignAndSendTransactionare the primary methods within the SDK for sending transactions as it immediately sends a given transaction after requesting signature (confirmation). This will also take a serialized (string) representation of a transaction,

var transaction = "Transaction";

var nativeResultData = await ParticleAuthCore.Instance.EvmSendTransaction(transaction);

var nativeResultData = await ParticleAuthCore.Instance.SolanaSendTransaction(transaction);

Sign Type Data

ParticleAuthCore.Instance.EvmSignTypedData is an EVM-specific method for signing structured (typed) data. For more information on signTypedData, see the Web (JavaScript/TypeScript) page.

string typedData = "Your typedata";

await ParticleAuthCore.Instance.EvmSignTypedData(typedData);

Set ChainInfo

If you’d like to set the primary chain after initial configuration, you’ll need to use ParticleNetwork.SetChainInfo, which simply takes a chainInfo object parallel to the type of object passed into the original ParticleNetwork.Init call.

ParticleNetwork.SetChainInfo(ChainInfo.Ethereum);

// Asynchronous, used for switch from evm to solana, or switch from solana to evm.
await ParticleAuthCore.Instance.SwitchChain(ChainInfo.Ethereum);

Open Account and Security Page

Following the above, if you’d like to force the opening of account/security settings (in-UI), you can do so with ParticleAuthCore.Instance.OpenAccountAndSecurity.

await ParticleAuthCore.Instance.OpenAccountAndSecurity();

Has Master Password, Payment Password, Security Account

Similarly to the isConnected function covered prior, there are various scenarios in which knowing whether or not a user has specific security settings enabled may be useful. In the case of the Particle Auth Flutter SDK, this can happen in one of two ways:

With the built-in ParticleAuthCoreInteraction.HasMasterPassword, ParticleAuthCoreInteraction.HasPaymentPassword, and ParticleAuthCore.Instance.ChangeMasterPassword methods.

ParticleAuthCoreInteraction.HasMasterPassword();

ParticleAuthCoreInteraction.HasPaymentPassword();

await ParticleAuthCore.Instance.ChangeMasterPassword();

Enable Blind Signing

Silently sign messages/transactions, this switch will work if the following conditions are met:

  1. Your account is connected with JWT
  2. Your account does not set payment password
  3. SecurityAccountConfig.promptSettingWhenSign is 0, you can call ParticleNetwork.SetSecurityAccountConfig to update its value.
// Enable blind signing
ParticleAuthCoreInteraction.SetBlindEnable(true);
// Retrieve whether or not blind signing is enabled
var enable = ParticleAuthCoreInteraction.GetBlindEnable();

EvmService utilization examples

In addition to ParticleAuthCore for authentication and interaction with Particle’s Wallet-as-a-Service, the Unity mobile SDK also includes a class, EvmService, for general interaction with EVM chains.

Write Contract

EvmService.WriteContract allows you to execute a write contract call defined by a specific method and set of parameters. This requires a corresponding ABI, contract address, and requester public address.

FieldTypeDescription
fromstringThe user’s public address
contractAddressstringThe contract address
methodNamestringThe method name that defined in the contract, add prefix custom_, like custom_balanceOf, custom_mint
parametersList<object>The method’s parameters
abiJsonStringstring?The method’s abi json string
gasFeeLevelGasFeeLevel(Optional) the gas fee level, High, Medium or Low, default is High
// Contract ABI, JSON string
// For example,
// [{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"quantity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]

var transaction = await EvmService.WriteContract(from, contractAddress, methodName, parameters,abiJsonString);

Read Contract

EvmService.ReadContract allows you to execute a read-only contract call defined by a specific method and set of parameters. This requires a corresponding ABI, contract address, and requester public address.

FieldTypeDescription
fromstringThe user’s public address
contractAddressstringThe contract address
methodNamestringThe method name that defined in the contract, add prefix custom_, like custom_balanceOf, custom_mint
parametersList<object>The method’s parameters
abiJsonStringstring?The method’s abi json string
// Contract ABI, JSON string
// For example,
// [{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"quantity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]

string rpcResult =
  await EvmService.ReadContract(from, contractAddress, methodName, parameters, abiJsonString);

var result = (string)JObject.Parse(rpcResult)["result"];

Create Transaction

EvmService.CreateTransaction facilitates the construction of a transaction object derived from the standard from, to (receiver in this example), amount (value), and data fields. This transaction, once constructed with EvmService.CreateTransaction, can be passed for in-UI proposal with ParticleAuthCore.Instance.EvmSendTransaction.

FieldTypeDescription
fromstringThe user’s public address.
datastringThe transaction’s data.
valueBigIntegerThe native amount.
toStringThe parameters of this method.
gasFeeLevelGasFeeLevel(Optional) the gas fee level, High, Medium or Low, default is High.
var transaction = await EvmService.CreateTransaction(from, data, value, reciver);

Estimate Gas

Given a standard transaction structure (detached set of values, as shown below), gas estimations can be ran to simulate and retrieve the volume of gas to be consumed by a specified transaction (wrapper for eth_estimateGas). This is done through EvmService.EstimateGas.

final result = await EvmService.EstimateGas(from, to, value, data);
var gasLimit = (string)JObject.Parse(result)["result"];

Get Suggested Gas Fees

To retrieve categorized gas price suggestions (3 categories scaling from low to high) based upon current network conditions, you can call EvmService.SuggestedGasFees.

var gasFeesResult = await EvmService.SuggestedGasFees();

Get Tokens and NFTs

EvmService also extends to Data API methods such as GetTokensAndNFTs, which returns a highly detailed JSON list of ERC20 tokens and ERC721 NFTs belonging to a specified address. This is accessible through EvmService.GetTokensAndNFTs, passing in the public address to retrieve the tokens and NFTs of.

tokenAddresses is an optional parameter, for get the specific tokens.

await EvmService.GetTokensAndNFTs(publicAddress, tokenAddresses);
await EvmService.GetTokens(publicAddress, tokenAddresses)
await EvmService.GetNFTs(publicAddress)

Get Transactions by Address

Similar to the former method, EvmService.GetTransactionsByAddress enables the retrieval of a detailed JSON response containing a complete list of transactions involving a specified address.

await EvmService.GetTransactionsByAddress(publicAddress);

Get Price

To retrieve the price of specified tokens, you can call EvmService.GetPrice.

 await EvmService.GetPrice(tokenAddresses, currencies);

Basic RPC method

Basic RPC methods can be called manually through EvmService.Rpc, as shown below.

await EvmService.Rpc(method, params);

SolanaService utilization examples

In addition to ParticleAuthCore for authentication and interaction with Particle’s Wallet-as-a-Service, the Unity mobile SDK also includes a class, SolanaService, for general interaction with Solana chains.

Get Tokens and NFTs

SolanaService also extends to Data API methods such as GetTokensAndNFTs, which returns a highly detailed JSON list of SPL tokens and NFTs belonging to a specified address. This is accessible through SolanaService.GetTokensAndNFTs, passing in the public address to retrieve the tokens and NFTs of.

await SolanaService.GetTokensAndNFTs(publicAddress, true);

Serialize Transactions

SolanaService.SerializeSOLTransaction facilitates the construction of a SOL transaction object.

These transactions, once constructed , can be passed for in-UI proposal with ParticleAuthCore.Instance.SolanaSendTransaction.

string receiver = "";
long amount = 10000000;
SerializeSOLTransReq req = new SerializeSOLTransReq(sender, receiver, amount);
var result = await SolanaService.SerializeSOLTransaction(req);

var resultData = JObject.Parse(result);
var transaction = (string)resultData["result"]["transaction"]["serialized"];

Get Price

To retrieve the price of specified tokens, you can call SolanaService.GetPrice.

 await SolanaService.GetPrice(tokenAddresses, currencies);

Get transactions by Address

To retrieve transactions executed by a given address, you can call SolanaService.getTransactionsByAddress.

await SolanaService.GetTransactionsByAddress(address);

Get Token by Token Address

To obtain the balance of a specified token at a specified address, you can call SolanaService.GetTokenByTokenAddresses.

await SolanaService.GetTokenByTokenAddresses(address, tokenAddresses);

Basic RPC Method

Similar to EvmService, standard RPC methods can be called through SolanaService.Rpc.

await SolanaService.Rpc(method, params);