# Embedded Wallets SDK for iOS

> MetaMask Embedded Wallets SDK for iOS | Web3Auth Plug and Play for iOS

## Overview

MetaMask Embedded Wallets SDK (formerly Web3Auth Plug and Play) provides a seamless authentication experience for iOS applications with social logins, external wallets, and more. Our iOS SDK, written in Swift, simplifies connecting users to their preferred wallets and manage authentication state natively.

## Requirements

- iOS 14+
- Xcode 12+
- Swift 5.x
- Basic knowledge of Swift and iOS Development

## Prerequisites

- Set up your project on the [Embedded Wallets dashboard](https://developer.metamask.io/)

:::tip

See the [dashboard setup](../../dashboard/README.mdx) guide to learn more.

:::

## Installation

Install the Web3Auth iOS SDK using one of the following methods:

### Swift package manager

1. In Xcode, with your app project open, navigate to **File > Add Package Dependencies**.

2. When prompted, add the Web3Auth iOS SDK repository:

   ```sh
   https://github.com/Web3Auth/web3auth-swift-sdk
   ```

   From the **Dependency Rule** dropdown, select **Exact Version** and enter **11.1.0** as the version.

3. When finished, Xcode will automatically begin resolving and downloading your dependencies in the background.

### CocoaPods

To install the Embedded Wallets SDK using CocoaPods, follow the steps:

1. Open the Podfile, and add the Embedded Wallets pod:

```sh
pod 'Web3Auth', '~> 11.1.0'
```

2. Once added, use `pod install` command to download the Embedded Wallets dependency.

### Configure redirection

To use Embedded Wallets for iOS you need to allowlist your `bundleId` in your Embedded Wallets project.

- Go to [Embedded Wallets developer dashboard](https://developer.metamask.io), and create or open an existing Embedded Wallets project.
- Allowlist `{bundleId}://auth` in the dashboard. This step is mandatory for the redirect to work.

## Initialize Embedded Wallets

### Configure Redirection

To use Web3Auth for iOS you need to allowlist your `bundleId` in your Web3Auth project.

- Go to [Embedded Wallets developer dashboard](https://developer.metamask.io), and create or open an existing Embedded Wallets project.
- Allowlist `{bundleId}://auth` in the developer dashboard. This step is mandatory for the redirect to work.

### 1. Create an Embedded Wallets instance

Import and configure Web3Auth in your application:

```swift

class ViewController: UIViewController {
    var web3Auth: Web3Auth?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Configure Web3Auth
        web3Auth = Web3Auth(W3AInitParams(
            clientId: "YOUR_WEB3AUTH_CLIENT_ID", // Pass your Web3Auth Client ID, ideally using an environment variable // Get your Client ID from MetaMask Developer Dashboard
            network: .sapphire_mainnet, // or .sapphire_devnet
            redirectUrl: "com.yourapp.bundleid://auth"
        ))
    }
}
```

### 2. Initialize the Embedded Wallets instance

Initialize the Web3Auth instance:

```swift
override func viewDidLoad() {
    super.viewDidLoad()

    Task {
        do {
            try await web3Auth?.initialize()
            print("Web3Auth initialized successfully")
        } catch {
            print("Error initializing Web3Auth: \(error)")
        }
    }
}
```

### 3. Handle URL callbacks

Configure your application to handle URL callbacks in your `SceneDelegate`:

```swift

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    guard let url = URLContexts.first?.url else { return }
    Web3Auth().setResultUrl(url: url)
}
```

For applications using `AppDelegate`:

```swift
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
    Web3Auth().setResultUrl(url: url)
    return true
}
```

## Advanced configuration

The Embedded Wallets iOS SDK offers a rich set of advanced configuration options:

- **[Custom authentication](./advanced/custom-authentication.mdx):** Define authentication methods.
- **[Whitelabeling and UI customization](./advanced/whitelabel.mdx):** Personalize the modal's appearance.
- **[Multi-Factor Authentication (MFA)](./advanced/mfa.mdx):** Set up and manage MFA.
- **[Dapp share](./advanced/dapp-share.mdx):** Share dapp sessions across devices.

:::tip

See the [advanced configuration sections](./advanced/) to learn more about each configuration option.

:::

<Tabs
  defaultValue="basic-config"
  values={[
    { label: "Basic Configuration", value: "basic-config" },
    { label: "Advanced Configuration", value: "advanced-config" },
  ]}
>

<TabItem value="basic-config">

```swift
web3Auth = Web3Auth(W3AInitParams(
    clientId: "YOUR_WEB3AUTH_CLIENT_ID", // Pass your Web3Auth Client ID, ideally using an environment variable
    network: .sapphire_mainnet, // or .sapphire_devnet
    redirectUrl: "com.yourapp.bundleid://auth"
))
```

</TabItem>

<TabItem value="advanced-config">

```swift
web3Auth = Web3Auth(W3AInitParams(
    clientId: "YOUR_WEB3AUTH_CLIENT_ID", // Pass your Web3Auth Client ID, ideally using an environment variable
    network: .sapphire_mainnet, // or .sapphire_devnet
    redirectUrl: "com.yourapp.bundleid://auth",
    loginConfig: [
      Web3AuthProvider.JWT.rawValue: .init(
        verifier: "YOUR_VERIFIER_NAME", // Get it from MetaMask Developer Dashboard
        typeOfLogin: TypeOfLogin.google,
        clientId: "YOUR_GOOGLE_CLIENT_ID",
      )
    ],
    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
        )
    )
))
```

</TabItem>

</Tabs>

## Blockchain integration

Embedded Wallets is blockchain agnostic, enabling integration with any blockchain network. Out of the box, Embedded Wallets offers robust support for both **Solana** and **Ethereum**.

### Ethereum integration

For Ethereum integration, you can get the private key and use it with web3.swift or other Ethereum libraries:

```swift

// Use your Web3Auth instance to get the private key
val privateKey = web3Auth.getPrivKey()

// Generate the Ethereum Account
let account = try EthereumAccount(privateKey)

// 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.init(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(
    // Use the address from previous step
    address: address,
    block: .Latest
)

// Convert the balance from Wei to Ether format
let balance = toEther(wei: balanceResponse)
```

### Solana integration

For Solana integration, you can get the Ed25519 private key:

```swift

// Use your Web3Auth instance to get the private key
let ed25519PrivateKey = web3Auth.getEd25519PrivKey()

// 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(
     // Use userAccount from above
    account: userAccount
)

// We are dividing the balance by 10^9, because Solana's token decimals is set to be 9;
let userBalance = return balanceResponse.convertToBalance(decimals: 9)
```
