Skip to main content

Using Web3Auth iOS SDK

mobileioswhitelabelcustom authenticationdapp shareswiftWeb3Auth Team | December 11, 2022

This guide will cover the basics of how to use the Web3Auth iOS SDK in your iOS application.

Repository: https://github.com/Web3Auth/web3auth-pnp-examples//raw/main/ios

Quick Start

npx degit Web3Auth/web3auth-pnp-examples/ios/ios-example w3a-ios-demo
# Open in Xcode

How it works?

When integrating Web3Auth iOS SDK with Social Login the flow looks something like this:

Web3Auth Core - Social Login Flow

  • When a user logs in with Google, Google sends a JWT id_token to the app. This JWT token is sent to the Web3Auth SDK's login function.

  • Finally, on successful validation of the JWT token, Web3Auth SDK will generate a private key for the user, in a self custodial way, resulting in easy onboarding for your user to the application.

Prerequisites

  • For Web Apps: A basic knowledge of JavaScript is required to use Web3Auth SDK.

  • For Mobile Apps: For the Web3Auth Mobile SDKs, you have a choice between iOS, Android, React Native & Flutter. Please refer to the Web3Auth SDK Reference for more information.

  • Create a Web3Auth account on the Web3Auth Dashboard

  • iOS 13.0 or later
  • Xcode 11.4+ / 12.x
  • Swift 4.x / 5.x

Setup

Setup your Web3Auth Dashboard

  • Create a Project from the Project Section of the Web3Auth Developer Dashboard.

    Plug n Play Project Creation on Web3Auth Dashboard

    • Enter your desired Project name.

    • Select the Product you want to use. For this guide, we'll be using the Plug n Play product.

    • Select the Platform type you want to use. For this guide, we'll be using the Web Application as the platform.

    • Select the Web3Auth Network as Sapphire Devnet. We recommend creating a project in the sapphire_devnet or tesnet network during development. While moving to a production environment, make sure to convert your project to sapphire_mainnet or any of the legacy mainnet network mainnet, aqua, or cyan network. Otherwise, you'll end up losing users and keys.

    • Select the blockchain(s) you'll be building this project on. For interoperability with Torus Wallets, you have the option of allowing the user's private key to be used in other applications using Torus Wallets (EVM, Solana, XRPL & Casper).

    • Finally, once you create the project, you have the option to whitelist your URLs for the project. Please whitelist the domains where your project will be hosted.

      Plug n Play Project - Whitelist

  • Add (bundleId)://auth in the Whitelist URL field of the Web3Auth Dashboard.

Using the Web3Auth SDK

Installation

Swift Package Manager

If you are using the Swift Package Manager, open the following menu item in Xcode:

File > Swift Packages > Add Package Dependency

In the Choose Package Repository prompt add this url:

https://github.com/Web3Auth/web3auth-swift-sdk/releases/tag/6.0.1

Cocoapods

pod 'Web3Auth', '~> 6.0.1'

After Installation, the next step to use Web3Auth is to Initialize the SDK. However, the Initialization can be done in 2 ways,

Please note that these are the most critical steps where you need to pass on different parameters according to the preference of your project. Additionally, Whitelabeling and Custom Authentication have to be configured within this step, if you wish to customise your Web3Auth Instance.

Initialization

With Web3Auth.plist

In your application bundle add a plist file named Web3Auth.plist with the following information:

<?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>ClientId</key>
<string>YOUR_OPENLOGIN_CLIENT_ID</string>
<key>Network</key>
<string>mainnet | testnet</string>
</dict>
</plist>

When you have a Web3Auth.plist and you have specified your Web3Auth configuration there, you can simply construct your Web3Auth instance with

import Web3Auth

let web3auth = Web3Auth()

Without Web3Auth.plist

If you don't have a Web3Auth.plist or want to use optional configurtion parameters, you can construct the Web3Auth instance with

import Web3Auth

let web3auth = Web3Auth(W3AInitParams(
clientId: "<your clientId>",
network: .MAINNET,
sdkUrl: ...,
redirectUrl: ...,
))

All the below code snippets are based on the above initialization. Please refer to the Web3Auth ios SDK Reference for more information.

After creating a Web3Auth instance using one of the above methods, you can use the instance to call various methods.

Authentication

Logging in

Once initialized, you can use the Web3Auth().login(W3ALoginParams(loginProvider: provider)) function to authenticate the user with the chosen provider.

func login(provider: Web3AuthProvider) {
Task {
do {
let result = try await Web3Auth(.init(
clientId: clientId,
network: network))
.login(W3ALoginParams(loginProvider: provider))

} catch {
print("Error")
}
}
}

// provider can be .GOOGLE, .APPLE, .FACEBOOK etc
let web3AuthResponse = login(provider: .GOOGLE)

When connecting, the login function takes the W3ALoginParams arguments for the login. See the W3ALoginParams for more details.

Sample Login Response

{
"ed25519PrivKey": "666523652352635....",
"privKey": "0ajjsdsd....",
"userInfo": {
"aggregateVerifier": "tkey-google",
"email": "john@gmail.com",
"name": "John Dash",
"profileImage": "https://lh3.googleusercontent.com/a/Ajjjsdsmdjmnm...",
"typeOfLogin": "google",
"verifier": "torus",
"verifierId": "john@gmail.com",
"dappShare": "<24 words seed phrase>", // will be sent only incase of custom verifiers
"idToken": "<jwtToken issued by Web3Auth>",
"oAuthIdToken": "<jwtToken issued by OAuth Provider>", // will be sent only incase of custom verifiers
"oAuthAccessToken": "<accessToken issued by OAuth Provider>" // will be sent only incase of custom verifiers
}
}

Get the User Profile

// Assuming the user is logged in, get the user profile from the web3AuthResponse
val userInfo = web3AuthResponse.userInfo

Using the web3Auth.login function, you can get the details of the logged in user. Please note that these details are not stored anywhere in Web3Auth network.

If you wish you add Multi Factor Authentication, use dApp Share or select Curve for your iOS application, read the linked documentation.

Logout

func logout() {
Task {
do {
let result = try await Web3Auth(.init(
clientId: clientId,
network: network))
.logout()

} catch {
print("Error")
}
}
}

Logging out your user is as simple as calling the Web3Auth.logout() function.

Interacting with the Blockchain

Blockchain calls

Checkout the full codes to interact with ETH Blockchain.

Get Account

// checkout the Connect Blockchain > Ethereum > iOS to get full code.
account = try EthereumAccount(keyStorage: user )
address = account.address

Get Balance

// checkout the Connect Blockchain > Ethereum > iOS to get full code.
client = EthereumClient(url: URL(string: RPC_URL)!)
latestBlock = client.eth_blockNumber
let balance = try client.eth_getBalance(address: address, block:latestBlock)

Send Transaction

let gasPrice = try await client.eth_gasPrice()
let maxTipInGwie = BigUInt(TorusWeb3Utils.toEther(Gwie: BigUInt(amount)))
let totalGas = gasPrice + maxTipInGwie
let amtInGwie = TorusWeb3Utils.toWei(ether: amount)
let nonce = try await client.eth_getTransactionCount(address: address, block: .Latest)
let transaction = EthereumTransaction(from: address, to: EthereumAddress(sendTo), value: amtInGwie, data: Data(), nonce: nonce + 1, gasPrice: totalGas, gasLimit: gasLimit, chainId: chainID)
let signed = try account.sign(transaction: transaction)
let val = try await client.eth_sendRawTransaction(signed.transaction, withAccount: account)

// checkout the Connect Blockchain > Ethereum > iOS to get full code.

import BigInt
import Foundation
import web3

public typealias Ether = Double
public typealias Wei = BigUInt

public final class TorusWeb3Utils {
public static func timeMinToSec(val: Double) -> Double {
return val * 60
}

// NOTE: calculate wei by 10^18
private static let etherInWei = pow(Double(10), 18)
private static let etherInGwei = pow(Double(10), 9)

/// Convert Wei(BInt) unit to Ether(Decimal) unit
public static func toEther(wei: Wei) -> Ether {
guard let decimalWei = Double(wei.description) else {
return 0
}
return decimalWei / etherInWei
}

public static func toEther(Gwie: BigUInt) -> Ether {
guard let decimalWei = Double(Gwie.description) else {
return 0
}
return decimalWei / etherInGwei
}

/// Convert Ether(Decimal) unit to Wei(BInt) unit
public static func toWei(ether: Ether) -> Wei {
let wei = Wei(ether * etherInWei)
return wei
}

/// Convert Ether(String) unit to Wei(BInt) unit
public static func toWei(ether: String) -> Wei {
guard let decimalEther = Double(ether) else {
return 0
}
return toWei(ether: decimalEther)
}

// Only used for calcurating gas price and gas limit.
public static func toWei(GWei: Double) -> Wei {
return Wei(GWei * 1000000000)
}
}

Example code

The code for the application we developed in this guide can be found in the Web3Auth iOS Example. Check it out and try running it locally yourself!

Also, checkout other examples:

Questions?

Ask us on Web3Auth's Community Portal