Using PnP iOS SDK
Logging in a User
login()
Trigger login flow will navigate the user to a browser model allowing the user to login into the
service. You can pass in the supported providers to the login method for specific social logins such
as Google, Apple, Facebook, etc., and do whitelabel login. Web3Auth.login()
takes in
W3ALoginParams
as a required input.
Arguments
W3ALoginParams
- Table
- Struct
Parameter | Description |
---|---|
loginProvider | It sets the OAuth login method to be used. You can use any of the supported values are GOOGLE , FACEBOOK , REDDIT , DISCORD , TWITCH , APPLE , LINE , GITHUB , KAKAO , LINKEDIN , TWITTER , WEIBO , WECHAT , EMAIL_PASSWORDLESS , SMS_PASSWORDLESS , and FARCASTER . |
extraLoginOptions? | It can be used to set the OAuth login options for corresponding loginProvider . For instance, you'll need to pass user's email address as. Default value for the field is nil , and it accepts ExtraLoginOptions as a value. |
redirectUrl? | Url where user will be redirected after successfull login. By default user will be redirected to same page where login will be initiated. Default value for the field is nil , and accepts URL as a value. |
appState? | It can be used to keep track of the app state when user will be redirected to app after login. Default is nil , and accepts String as a value. |
mfaLevel? | Customize the MFA screen shown to the user during OAuth authentication. Default value for field is MFALevel.DEFAULT , which shows MFA screen every 3rd login. It accepts MFALevel as a value. |
dappShare? | Custom verifier logins can get a dapp share returned to them post successful login. This is useful if the dapps want to use this share to allow users to login seamlessly. It accepts String as a value. |
curve? | It will be used to determine the public key encoded in the jwt token which returned in getUserInfo function after user login. This parameter won't change format of private key returned by We3Auth. Private key returned by getPrivKey is always secp256k1. To get the ed25519 key you can use getEd25519PrivKey method. The default value is SUPPORTED_KEY_CURVES.SECP256K1 . |
public struct W3ALoginParams: Codable {
public init() {
loginProvider = nil
dappShare = nil
extraLoginOptions = nil
redirectUrl = nil
appState = nil
mfaLevel = nil
curve = .SECP256K1
}
let loginProvider: String?
var dappShare: String?
let extraLoginOptions: ExtraLoginOptions?
let redirectUrl: String?
let appState: String?
let mfaLevel: MFALevel?
let curve: SUPPORTED_KEY_CURVES
}
public enum Web3AuthProvider: String, Codable {
case GOOGLE = "google"
case FACEBOOK = "facebook"
case REDDIT = "reddit"
case DISCORD = "discord"
case TWITCH = "twitch"
case APPLE = "apple"
case LINE = "line"
case GITHUB = "github"
case KAKAO = "kakao"
case LINKEDIN = "linkedin"
case TWITTER = "twitter"
case WEIBO = "weibo"
case WECHAT = "wechat"
case EMAIL_PASSWORDLESS = "email_passwordless"
case JWT = "jwt"
case SMS_PASSWORDLESS = "sms_passwordless"
case FARCASTER = "farcaster"
}
getPrivkey()
Use getPrivkey() to get the private key of the user. The method returns an EVM compatible private key which can be used to sign transactions on EVM compatible chains.
getEd25519PrivKey()
Use getEd25519PrivKey() to get the Ed25519 private key of the user. This private key can be used to sign transactions on Solana.
getUserInfo()
Use getUserInfo() to get the user info of the user.
UserInfo Response
{
"userInfo": {
"email": "w3a-heroes@web3auth.com",
"name": "Web3Auth Heroes",
"profileImage": "https://lh3.googleusercontent.com/a/Ajjjsdsmdjmnm...",
"verifier": "torus",
"verifierId": "w3a-heroes@web3auth.com",
"typeOfLogin": "google",
"aggregateVerifier": "w3a-google-sapphire",
"dappShare": "", // 24 words of 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
"isMfaEnabled": false // Returns whether the user has enabled MFA or not
}
}
- Discord
- Twitch
- Email Passwordless
- SMS Passwordless
- Farcaster
- JWT
func login(provider: Web3AuthProvider) {
Task {
do {
let result = try await Web3Auth().login(W3ALoginParams(loginProvider: provider))
// Perform action upon success
} catch {
print("Error")
}
}
}
login(provider: .GOOGLE)
func login(provider: Web3AuthProvider) {
Task {
do {
let result = try await Web3Auth().login(W3ALoginParams(loginProvider: provider))
// Perform action upon success
} catch {
print("Error")
}
}
}
login(provider: .FACEBOOK)
func login(provider: Web3AuthProvider) {
Task {
do {
let result = try await Web3Auth().login(W3ALoginParams(loginProvider: provider))
// Perform action upon success
} catch {
print("Error")
}
}
}
login(provider: .DISCORD)
func login(provider: Web3AuthProvider) {
Task {
do {
let result = try await Web3Auth().login(W3ALoginParams(loginProvider: provider))
// Perform action upon success
} catch {
print("Error")
}
}
}
login(provider: .TWITCH)
func login(provider: Web3AuthProvider) {
Task {
do {
let result = try await Web3Auth().login(
W3ALoginParams(
loginProvider: provider,
extraLoginOptions: .init(loginHint: "hello@web3auth.io")
))
// Perform action upon success
} catch {
print("Error")
}
}
}
login(provider: .EMAIL_PASSWORDLESS)
let result = await Web3Auth().login(W3ALoginParams(
Web3AuthProvider.SMS_PASSWORDLESS,
// The phone number should be in format of +{country_code}-{phone_number}
extraLoginOptions: .init(loginHint: "+91-9911223344")
))
do {
let result = try await Web3Auth().login(W3ALoginParams(loginProvider: .Farcaster))
// Perform action upon success
} catch {
print("Error")
}
func login(provider: Web3AuthProvider) {
Task {
do {
let result = try await Web3Auth().login(W3ALoginParams(
selectedLoginProvider,
extraLoginOptions: .init(domain:"your-domain", id_token: "your_jwt_token")
))
// Perform action upon success
} catch {
print("Error")
}
}
}
login(provider: .JWT)
Session Management
The Session Management feature allows you to check the existing sessions with Web3Auth. The
Web3AuthState
will allow users to remain authenticated with Web3Auth for 1 day by default, or a
maximum of 7 days, or until the user logout or session data is cleared.
The Web3Auth
initialization accepts a sessionTime
parameter.
let sessionTime = 86400 // 1 day
import Foundation
// IMP START - Quick Start
import Web3Auth
// IMP END - Quick Start
class ViewModel: ObservableObject {
var web3Auth: Web3Auth?
@Published var loggedIn: Bool = false
@Published var user: Web3AuthState?
@Published var isLoading = false
@Published var navigationTitle: String = ""
func setup() async {
guard web3Auth == nil else { return }
await MainActor.run(body: {
isLoading = true
navigationTitle = "Loading"
})
web3Auth = await Web3Auth(W3AInitParams(
clientId: "<Your client id>",
network: .sapphire_mainnet,
sessionTime: 86400, // 1 day
))
await MainActor.run(body: {
if self.web3Auth?.state != nil {
user = web3Auth?.state
loggedIn = true
}
isLoading = false
navigationTitle = loggedIn ? "UserInfo" : "SignIn"
})
}
func login(provider: Web3AuthProvider) {
Task {
do {
let result = try await web3Auth?.login(
W3ALoginParams(loginProvider: provider)
)
await MainActor.run(body: {
user = result
loggedIn = true
})
} catch {
print("Error")
}
}
}
func logout() throws {
Task {
try await web3Auth?.logout()
await MainActor.run(body: {
loggedIn = false
})
}
}
Logging out a user
Web3Auth().logout()
This method will logout the user and remove the session id from the device. The user will need to login again to use the dApp next time the dApp is opened.
await Web3Auth().logout()
Enable MFA for a user
The enableMFA
method is used to trigger MFA setup flow for users. The method takes
W3ALoginParams
which will used during custom verifiers. If you are using default login providers,
you don't need to pass W3ALoginParams
. If you are using custom jwt verifiers, you need to pass the
valid JWT token in W3ALoginParams
as well.
- Default Verifier
- Custom JWT Verifier
do {
let isMFAEnabled = try await self.web3Auth.enableMFA()
} catch {
print(error.localizedDescription)
// Handle Error
}
do {
let loginParams = W3ALoginParams(
.JWT,
extraLoginOptions: .init(id_token: "your_jwt_token")
)
let isMFAEnabled = try await self.web3Auth.enableMFA(loginParams)
} catch { print(error.localizedDescription) // Handle Error }
Launch Wallet Services
The launchWalletServices
method launches a WebView which allows you to use the templated wallet UI
services. The method takes ChainConfig
as the required input. Wallet Services is currently only
available for EVM chains.
Access to Wallet Services is gated. You can use this feature in the development environment for free. The minimum pricing plan to use this feature in a production environment is the Scale Plan.
Arguments
ChainConfig
- Table
- Class
Parameter | Description |
---|---|
chainNamespace | Custom configuration for your preferred blockchain. As of now only EVM supported. Default value is ChainNamespace.eip155 . |
decimals? | Number of decimals for the currency ticker. Default value is 18, and accepts Int as value. |
blockExplorerUrl? | Blockchain's explorer URL. (eg: https://etherscan.io ) |
chainId | The chain id of the selected blockchain String . |
displayName? | Display Name for the chain. |
logo? | Logo for the selected chainNamespace & chainId . |
rpcTarget | RPC Target URL for the selected chainNamespace & chainId . |
ticker? | Default currency ticker of the network (e.g: ETH ) |
tickerName? | Name for currency ticker (e.g: Ethereum ) |
public struct ChainConfig: Codable {
public init(chainNamespace: ChainNamespace = ChainNamespace.eip155, decimals: Int? = 18, blockExplorerUrl: String? = nil, chainId: String, displayName: String? = nil, logo: String? = nil, rpcTarget: String, ticker: String? = nil, tickerName: String? = nil) {
self.chainNamespace = chainNamespace
self.decimals = decimals
self.blockExplorerUrl = blockExplorerUrl
self.chainId = chainId
self.displayName = displayName
self.logo = logo
self.rpcTarget = rpcTarget
self.ticker = ticker
self.tickerName = tickerName
}
}
Usage
do {
try await web3Auth!.launchWalletServices(
chainConfig: ChainConfig(
chainId: "11155111",
rpcTarget: "https://eth-sepolia.public.blastapi.io"
)
)
} catch {
print(error.localizedDescription)
// Handle error
}
Request signature
The request
method facilitates the use of templated transaction screens for signing transactions.
Upon successful completion, you can retrieve the signature for the request using the
getSignResponse
static method.
Please check the list of JSON RPC methods, noting that the request method currently supports only the signing methods.
Arguments
Arguments | Description |
---|---|
chainConfig | Defines the chain to be used for signature. |
method | JSON RPC method name in String . Currently, the request method only supports the singing methods. |
requestParams | Parameters for the corresponding method. The parameters should be in the list and correct sequence. Take a look at RPC methods to know more. |
Usage
do {
var params = [Any]()
// Message to be signed
params.append("Hello, Web3Auth from iOS!")
// User's EOA address
params.append(address)
try await self.web3Auth?.request(
chainConfig: ChainConfig(
chainId: "11155111",
rpcTarget: "https://eth-sepolia.public.blastapi.io"
),
method: "personal_sign",
requestParams: params
)
let response = try Web3Auth.getSignResponse()
if response!.success {
print(response!.result!)
} else {
// Handle Error
print(response!.error!)
}
} catch {
print(error.localizedDescription)
// Handle error
}