This documentation for the Particle Network Javascript SDK will get you started in minutes!
Particle Network SDK allows you to easily integrate your app with the EVM and Solana blockchain, whether you already have a dApp integrated with web3 or are starting from scratch. Particle Network provides a smooth and delightful experience for both you and your app's users.
Before you can add Auth Service to your app, you need to create a Particle project to connect to your app. Visit Particle Dashboard to learn more about Particle projects and apps.
import { ParticleNetwork, WalletEntryPosition } from"@particle-network/auth";import { ParticleProvider } from"@particle-network/provider";import { SolanaWallet } from"@particle-network/solana-wallet";import { Ethereum } from"@particle-network/chains";import Web3 from"web3";constparticle=newParticleNetwork({ projectId:"xx", clientKey:"xx", appId:"xx", chainName:Ethereum.name,//optional: current chain name, default Ethereum. chainId:Ethereum.id,//optional: current chain id, default 1. wallet: { //optional: by default, the wallet entry is displayed in the bottom right corner of the webpage. displayWalletEntry:true,//show wallet entry when connect particle. defaultWalletEntryPosition:WalletEntryPosition.BR,//wallet entry position uiMode:"dark",//optional: light or dark, if not set, the default is the same as web auth. supportChains: [{ id:1, name:"Ethereum"}, { id:5, name:"Ethereum"}],// optional: web wallet support chains. 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 },});constparticleProvider=newParticleProvider(particle.auth);//if you need support solana chainconstsolanaWallet=newSolanaWallet(particle.auth);//if you use web3.jswindow.web3 =newWeb3(particleProvider);window.web3.currentProvider.isParticleNetwork // => true//if you use ethers.jsimport { ethers } from"ethers";constethersProvider=newethers.providers.Web3Provider(particleProvider,"any");constethersSigner=ethersProvider.getSigner();
Your first Particle Network dApp! ๐ You can implement web3 functionalities just like how you would normally with MetaMask.
In order for web3 to work and grab the end-users' Ethereum wallet addresses, the users have to login first (similar to unlocking account in MetaMask). You can simply trigger the login for users with the web3 function call below. The Auth SDK will save the login status locally. Before calling the login method, it is necessary to determine whether user has been logged successful.
import Web3 from"web3";if (!particle.auth.isLogin()) {// Request user login if needed, returns current user infoconstuserInfo=awaitparticle.auth.login();}// optional: custom login params.// support auth types: email,phone,facebook,google,apple,discord,github,twitch,microsoft,linkedinconstuserInfo=particle.auth.login({// when set social login auth type, will open thirdparty auth page directly. preferredAuthType?: AuthType,// when set email/phone account and preferredAuthType is email or phone, // Particle Auth will enter directly input verification code page.// when set JWT value and preferredAuthType is jwt, Particle Auth will auto login. account?: string, supportAuthTypes?: string,//need support social login types, split with ','. default value 'all'. hideLoading?: boolean,//hide particle loading when use jwt authorization. socialLoginPrompt?: string,//social login prompt. none | consent | select_account authorization: { // optional, login with authorize message:'0x...',//hex sign message. uniq:false,//optional, default false. } })
Login with Phone and input verification code directly.
constuserInfo=awaitparticle.auth.login({ preferredAuthType:'phone', account:'+14155552671',//phone number must use E.164 });
Login with Social Account.
constuserInfo=awaitparticle.auth.login({ preferredAuthType:'google',//support facebook,google,twitter,apple,discord,github,twitch,microsoft,linkedin etc. })
import { ParticleProvider } from"@particle-network/provider";//when new ParticleNetwork, chainId and chainName use EVM chain config.constaccount=awaitparticle.evm.getAddress()//or get accounts with particleProviderconstparticleProvider=newParticleProvider(particle.auth);constaccounts=awaitparticleProvider.request({ method:'eth_accounts'});
Solana Chain
import { SolanaWallet } from"@particle-network/solana-wallet";//when new ParticleNetwork, chainId and chainName use Solana chain config.constaccount=awaitparticle.solana.getAddress()//or get accounts with solanaWalletconstsolanaWallet=newSolanaWallet(pn.auth);constpublicKey=solanaWallet.publicKey;constaccount=publicKey?.toBase58();
Send Transaction
If you have replaced your web3 provider with Particle Network provider, nothing needs to be changed for web3 send Ether transactions to continue working.
The Particle Network X modal will pop open and ask users to confirm their transaction once this web3 function is called on the client-side.
consttxnParams= { from:"0xXX", to: toAddress, value: sendValue};//for evm transaction: use web3window.web3.eth.sendTransaction(txnParams, (error, txnHash) => {if (error) throw error;console.log(txnHash);});//for evm transaction: use particleconsttxnHash=awaitparticle.evm.sendTransaction(txnParams);//for solana transaction: use particleconstresult=awaitparticle.solana.signAndSendTransaction(transaction)//for solana transaction: use particle SolanaWalletsolanWallet.signAndSendTransaction(transaction)
User Signing
This is a relatively advanced use case. If you use the signed typed data JSON RPC endpoint, Particle Network will support this as well.
If you use window.ethereum to call RPC, The following things need to be noted:
Only use the Particle
Use only the Particle wallet and block other plugin wallets. For example, you can directly replace the global variable window.ethereum injected by the Metamask plugin with particleProvider:
window.ethereum = particleProvider;
Co-exists with other wallets
The Particle wallet co-exists with other plug-in wallets. You can create a new Provider object when switching wallets, avoiding contamination of Particle or Ethereum with assignment operations๏ผ
The Auth SDK will save the login status locally. Before calling the login method, it is necessary to determine whether user has been logged successful.
import { ParticleNetwork } from"@particle-network/auth";constparticle=newParticleNetwork({...});//check user loggedconstresult=particle.auth.isLogin()//check user logged and whether the token is valid, this interface also refresh user//security account info.constuserInfo=awaitparticle.auth.isLoginAsync()
Get User Info
import { ParticleNetwork } from"@particle-network/auth";constparticle=newParticleNetwork({...});//get user info(token/wallet/uuid), return null when user not login.constinfo=particle.auth.getUserInfo();
Status Events
User can listen particle connect , disconnect and chainChanged events.
// support fiat coin values: 'USD' | 'CNY' | 'JPY' | 'HKD' | 'INR' | 'KRW'particle.setFiatCoin('USD');
Set ERC-4337
// enable ERC-4337, openWallet will open Account Abstraction Walletparticle.setERC4337({ name:'BICONOMY', version:'1.0.0',});
The name and version are configured when initializing SmartAccount.
Switch Chain Info
import { ParticleNetwork } from"@particle-network/auth";import { Polygon } from"@particle-network/chains";constparticle=newParticleNetwork({...});// you can set chain info when new ParticleNetwork, or call setChainInfoparticle.switchChain({ name:Polygon.name, id:Polygon.id,})
Security Account
Open user security account dashboard, user can set Master Password, Payment Password, and Link Other accounts.
import { ParticleNetwork } from"@particle-netwok/auth";// open security account settingsconstparticle=newParticleNetwork({...});particle.auth.openAccountAndSecurity().catch((error) => {if (error.code ===4011) {//ignore window close } elseif (error.code ===10005) {//invalid token } elseif (error.code ===8005) {//user not login }});// get security accountconstsecurityAccount=awaitparticle.auth.getSecurityAccount();// check user master passwordparticle.auth.hasMasterPassword();// check user payment passwordparticle.auth.hasPaymentPassword();// check user security accountparticle.auth.hasSecurityAccount();
Open Particle Web Wallet
When connect particle auth success, you can open particle wallet by below interface.
import { ParticleNetwork } from"@particle-network/auth";constparticle=newParticleNetwork({...});// Need check login state when open wallet.// To set target and features for custom window style, same as window.open().particle.openWallet(target?: string, features?: string)//open wallet in iframe.consturl=pn.buildWalletUrl({//optional: left top menu style, close or fullscreen//"fullscreen": wallet will be fullscreen when user click.//"close": developer need handle click event topMenuType:"close"});constiframe=document.createElement("iframe");iframe.src = url;//if topMenuType is "close"window.addEventListener("message", (event) => {if (event.data ==="PARTICLE_WALLET_CLOSE_IFRAME") {//close click event }})
Open Crypto Token Buy
When initializing the Particle is complete, you can open the Buy Tokens page.
import { ParticleNetwork } from"@particle-network/auth";constparticle=newParticleNetwork({...});// open buy// To set target and features for custom window style, same as window.open().particle.openBuy(options?: OpenBuyOptions, target?: string, features?: string)
You can customize the open buy page by setting options parameters.
The amount of fiat currency that the user wants to spend.It's just for Buy Crypto
number
False
fixFiatCoin
Prevent user from changing fiat currency
bool
False
fixCryptoCoin
Prevent user from changing fiat cryptocurrency
bool
False
fixFiatAmt
Prevent user from changing amount of fiat currency
bool
False
walletAddress
Wallet address for the predefined cryptocurrency
string
False
If Particle not connected. network and walletAddress are requried.
Custom Wallet Style
When "displayWalletEntry" true, you can custom wallet style by set "customStyle" config, refer to Custom Wallet Style
import { ParticleNetwork, WalletEntryPosition } from"@particle-network/auth";import { Ethereum, Polygon } from"@particle-network/chains";constparticle=newParticleNetwork({ projectId:"xx", clientKey:"xx", appId:"xx", chainName:Ethereum.name,//optional: current chain name, default Ethereum. chainId:Ethereum.id,//optional: current chain id, default 1. wallet: { //optional: by default, the wallet entry is displayed in the bottom right corner of the webpage. displayWalletEntry:true,//show wallet entry when connect particle. defaultWalletEntryPosition:WalletEntryPosition.BR,//wallet entry position uiMode:"light", supportChains: [Ethereum, Polygon],// optional: web wallet support chains. customStyle: {},//optional: custom wallet style }});
EVM Web3Modal Integration
If you use web3modal connect wallet, you can use custom provider to add particle auth.
Particle Auth support Solana official component wallet-adapter, you can quickly add Particle Auth to your DApp.
exportconstWallet:FC= () => {// The network can be set to 'devnet', 'testnet', or 'mainnet-beta'.constnetwork=WalletAdapterNetwork.Devnet;// You can also provide a custom RPC endpoint.constendpoint=useMemo(() =>clusterApiUrl(network), [network]);constwallets=useMemo( () => [/** * Select the wallets you wish to support, by instantiating wallet adapters here. * * Common adapters can be found in the npm package `@solana/wallet-adapter-wallets`. * That package supports tree shaking and lazy loading -- only the wallets you import * will be compiled into your application, and only the dependencies of wallets that * your users connect to will be loaded. */newParticleAdapter(),//add particle adapter ], [] );return (<ConnectionProvider endpoint={endpoint}><WalletProvider wallets={wallets} autoConnect> <WalletModalProvider><WalletMultiButton /><WalletDisconnectButton /> { /* Your app's components go here, nested within the context providers. */ }</WalletModalProvider></WalletProvider></ConnectionProvider> );};
For detailed usage, please refer to the wallet-adapter documentation.
Upgrade Guide
If you use Particle Auth SDK v0.x.x and wish to update to the 1.x.x, the process is straightforward. Below are the updated functions for reference.
// old: get user infoparticle.auth.userInfo()// new: get user infoparticle.auth.getUserInfo()// old: open account and securityparticle.auth.accountSecurity()// new: open account and securityparticle.auth.openAccountAndSecurity()// old: get current chain idparticle.auth.chainId()// new: get current chain idparticle.auth.getChainId()// old: get current chain infoparticle.auth.chain()// new: get current chain infoparticle.auth.getChain()// old: get wallet by typeparticle.auth.wallet(type)// new: get wallet by typeparticle.auth.getWallet(type)// old: import chain infoimport { Ethereum, BSC, Polygon } from'@particle-network/common';// new: import chain infoimport { Ethereum, BNBChain, Polygon } from'@particle-network/chains';