Embedded Wallet SDK for iOS
Overview
The Web3Auth by MetaMask, Embedded Wallet SDK for iOS supports social sign-ins, email and SMS passwordless sign-ins, custom JWT sign-ins, and native session management. The SDK is written in Swift.
Prerequisites
- iOS 14+
- Xcode 15+
- Swift 5.9 or later
- A project configured on the Embedded Wallets dashboard. See the dashboard setup guide for details.
Installation
Install the Web3Auth iOS SDK using one of the following methods:
Swift package manager
-
In Xcode, with your app project open, navigate to File > Add Package Dependencies.
-
When prompted, add the Web3Auth iOS SDK repository:
https://github.com/Web3Auth/web3auth-swift-sdkFrom the Dependency Rule dropdown, select Up to Next Major Version and enter 13.0.0 as the minimum version.
-
Xcode automatically resolves and downloads your dependencies in the background.
CocoaPods
To install the Embedded Wallet SDK using CocoaPods, follow the steps:
- Open the Podfile, and add the Embedded Wallets pod:
pod 'Web3Auth', '~> 13.0'
- Once added, use
pod installcommand to download the Embedded Wallets dependency.
Configure redirection
To use Embedded Wallets for iOS, allowlist your bundleId in your Embedded Wallets project.
- Go to the Embedded Wallets developer dashboard and create or open an existing project.
- Allowlist
{bundleId}://authin the dashboard. This step is mandatory for the redirect to work.
Initialize Embedded Wallets
The iOS SDK uses an async initialization pattern.
The constructor fetches project configuration and restores any active session automatically.
The SDK does not require a separate initialize() call.
Create and initialize an Embedded Wallets instance
Import and configure Web3Auth in your application:
import Web3Auth
class ViewModel: ObservableObject {
var web3Auth: Web3Auth?
func setup() async {
do {
web3Auth = try await Web3Auth(
options: Web3AuthOptions(
clientId: "<YOUR_CLIENT_ID>", // From the Embedded Wallets dashboard
redirectUrl: "<YOUR_BUNDLE_ID>://auth",
web3AuthNetwork: .SAPPHIRE_MAINNET // or .SAPPHIRE_DEVNET
)
)
// Check for an active session
if web3Auth?.web3AuthResponse != nil {
// User is already signed in
}
} catch {
print("Error initializing Web3Auth: \(error)")
}
}
}
The async constructor throws if the SDK can't fetch your project configuration from the dashboard.
If restoring a stored session fails, the constructor doesn't throw. Instead, web3AuthResponse
stays nil and the stored session data is kept so the SDK can retry on the next launch.
Check web3AuthResponse to determine whether the user is signed in.
Web3AuthOptions has two initializers.
The full initializer requires its labeled arguments in declaration order: clientId,
redirectUrl, then optional parameters, with web3AuthNetwork after sessionTime and before
useSFAKey.
The snippets in these docs follow that order.
See Web3AuthOptions for the full parameter list.
Advanced configuration
The Embedded Wallets iOS SDK supports several advanced configuration options:
- Custom authentication: Define authentication methods.
- Whitelabeling and UI customization: Personalize the modal's appearance.
- Multi-Factor Authentication (MFA): Set up and manage MFA.
- Dapp share: Share dapp sessions across devices.
- Wallet Services: Configure the prebuilt wallet UI and signing screens.
See the advanced configuration sections to learn more about each configuration option.
- Basic Configuration
- Advanced Configuration
web3Auth = try await Web3Auth(
options: Web3AuthOptions(
clientId: "<YOUR_CLIENT_ID>",
redirectUrl: "<YOUR_BUNDLE_ID>://auth",
web3AuthNetwork: .SAPPHIRE_MAINNET // or .SAPPHIRE_DEVNET
)
)
web3Auth = try await Web3Auth(
options: Web3AuthOptions(
clientId: "<YOUR_CLIENT_ID>",
redirectUrl: "<YOUR_BUNDLE_ID>://auth",
authConnectionConfig: [
AuthConnectionConfig(
authConnectionId: "<YOUR_AUTH_CONNECTION_ID>", // From the Embedded Wallets dashboard
authConnection: .GOOGLE,
clientId: "YOUR_GOOGLE_CLIENT_ID"
)
],
web3AuthNetwork: .SAPPHIRE_MAINNET, // or .SAPPHIRE_DEVNET
mfaSettings: MfaSettings(
deviceShareFactor: MfaSetting(enable: true, priority: 1),
backUpShareFactor: MfaSetting(enable: true, priority: 2),
socialBackupFactor: MfaSetting(enable: true, priority: 3),
passwordFactor: MfaSetting(enable: true, priority: 4)
)
)
)
Single-factor authentication (SFA) support
The iOS SDK supports single-factor authentication (SFA), which authenticates users directly with a JWT token from your own authentication system. When MFA is disabled, users sign in using only the JWT token.
// SFA sign-in with custom JWT
let result = try await web3Auth.connectTo(
loginParams: LoginParams(
authConnection: .CUSTOM,
authConnectionId: "<YOUR_AUTH_CONNECTION_ID>",
idToken: "<YOUR_JWT_TOKEN>"
)
)
SFA mode is activated automatically when you provide an idToken parameter.
Users who sign in with SFA can't use enableMFA or
manageMFA.
Blockchain integration
Embedded Wallets supports any blockchain network, with built-in support for Ethereum and Solana.
Ethereum integration
Get the secp256k1 private key using the getPrivateKey method (or web3AuthResponse.privateKey)
and use it with web3.swift or other Ethereum libraries.
With web3.swift, conform Web3AuthResponse to EthereumSingleKeyStorageProtocol as shown in
Connect to Ethereum, then create the account:
import web3
import Web3Auth
// Use the response of your Web3Auth instance after the user signs in
let web3AuthResponse = web3Auth.web3AuthResponse!
// Generate the Ethereum Account
let account = try EthereumAccount(keyStorage: web3AuthResponse)
// Get the address
let address = account.address
// Create a client
let client = EthereumHttpClient(
// Please avoid using public RPC URL in production, use services like Infura.
url: URL(string: rpcUrl)!,
// Replace with the chain id of the network you want to connect to
network: .custom(chainId)
)
// Get the balance
let balanceResponse = try await client.eth_getBalance(
address: address,
block: .Latest
)
// Convert the balance from Wei to Ether format
let balance = toEther(wei: balanceResponse)
Solana integration
Get the Ed25519 private key using the getEd25519PrivateKey method and use it with SolanaSwift or
other Solana libraries:
import SolanaSwift
// Use your Web3Auth instance to get the private key
let ed25519PrivateKey = try web3Auth.getEd25519PrivateKey()
// Generate the KeyPair
let keyPair = try KeyPair(secretKey: Data(hex: ed25519PrivateKey))
// Get the user account
let userAccount = keyPair.publicKey.base58EncodedString
// Create the JSONRPCAPIClient instance
let endpoint = APIEndPoint(
address: "https://api.devnet.solana.com",
network: .devnet
)
let solanaJSONRPCClient = JSONRPCAPIClient(endpoint: endpoint)
// Get the balance
let balanceResponse = try await solanaJSONRPCClient.getBalance(
account: userAccount
)
// Solana's token decimals is set to be 9
let userBalance = balanceResponse.convertToBalance(decimals: 9)