Skip to main content

Embedded Wallets SDK for Android

Overview

MetaMask Embedded Wallets SDK (formerly Web3Auth Plug and Play/ W3A PnP) provides a seamless authentication experience for Android applications with social logins, external wallets, and more. Using our Android SDK written in Kotlin, you can easily connect users to their preferred wallets and manage authentication state natively.

Requirements

  • Android API version 24 or newer
  • Android Compile and Target SDK: 34
  • Basic knowledge of Java or Kotlin Development

Installation

Install the Web3Auth Android SDK by adding it to your project dependencies:

1. Add JitPack Repository

In your project-level gradle file add JitPack repository:

dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
maven { url "https://jitpack.io" } // <-- Add this line
}
}

2. Add Web3Auth Dependency

Then, in your app-level build.gradle dependencies section, add the following:

dependencies {
// ...
implementation 'com.github.web3auth:web3auth-android-sdk:9.1.2'
}

Setup

info

Prerequisites Before you start, make sure you have registered on the Web3Auth Dashboard and have set up your project. You can look into the Dashboard Setup guide to learn more.

1. Update Permissions

Open your app's AndroidManifest.xml file and add the following permission. Please make sure the <uses-permission> element should be a direct child of the <manifest> root element.

<uses-permission android:name="android.permission.INTERNET" />

2. Configure AndroidManifest.xml File

Make sure your Main activity launchMode is set to singleTop in your AndroidManifest.xml:

<activity
android:launchMode="singleTop"
android:name=".YourActivity">
// ...
</activity>

From version 7.1.2, please make sure to set android:allowBackup to false, and add tools:replace="android:fullBackupContent" in your AndroidManifest.xml file:

<application
android:allowBackup="false"
tools:replace="android:fullBackupContent"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher">
</application>

3. Handle Redirects

Once the gradles and permission has been updated, you need to configure Web3Auth project by whitelisting your scheme and package name.

Configure a Plug n Play project

  • Go to Web3Auth Developer Dashboard, and create or open an existing Web3Auth project.
  • Whitelist {SCHEME}://{YOUR_APP_PACKAGE_NAME} in the developer dashboard. This step is mandatory for the redirect to work.

Open your app's AndroidManifest.xml file and add the following deep link intent filter to your Main activity

<intent-filter>
<action android:name="android.intent.action.VIEW" />

<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />

<data android:scheme="{scheme}" android:host="{YOUR_APP_PACKAGE_NAME}"/>
<!-- Accept URIs: w3a://com.example.w3aflutter -->
</intent-filter>

4. Triggering Login exceptions

The setCustomTabsClosed method can be used to trigger login exceptions for Android. The Android SDK uses the custom tabs and from current implementation of chrome custom tab, it's not possible to add a listener directly to chrome custom tab close button and trigger login exceptions.

Hence, it's necessary to use setCustomTabsClosed method in your login screen to trigger exceptions.

class MainActivity : AppCompatActivity() {
// Additional code

override fun onResume() {
super.onResume()
if (Web3Auth.getCustomTabsClosed()) {
Toast.makeText(this, "User closed the browser.", Toast.LENGTH_SHORT).show()
web3Auth.setResultUrl(null)
Web3Auth.setCustomTabsClosed(false)
}
}

// Additional code
}

Initialize Web3Auth

1. Create a Web3Auth instance

Create a Web3Auth instance and configure it with your project settings:

import com.web3auth.core.Web3Auth
import com.web3auth.core.types.Web3AuthOptions

var web3Auth = Web3Auth(
Web3AuthOptions(
context = this,
clientId = "YOUR_WEB3AUTH_CLIENT_ID", // Pass over your Web3Auth Client ID from Developer Dashboard
network = Network.MAINNET,
redirectUrl = Uri.parse("{YOUR_APP_PACKAGE_NAME}://auth"),
)
)

// Handle user signing in when app is in background
web3Auth.setResultUrl(intent?.data)

2. Set Result URL

Whenever user initiates a login flow, a new intent of CustomTabs is launched. It's necessary step to use setResultUrl in onNewIntent method to successful track the login process.

override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)

// Handle user signing in when app is active
web3Auth.setResultUrl(intent.data)
}

3. Initialize the Web3Auth instance

After instantiating Web3Auth, the next step is to initialize it using the initialize method. This method is essential for setting up the SDK, checking for any active sessions, and fetching the whitelabel configuration from your dashboard.

Once the initialize method executes successfully, you can use the getPrivKey or getEd25519PrivKey methods to verify if an active session exists. If there is no active session, these methods will return an empty string; otherwise, they will return the respective private key.

note

If the API call to fetch the project configuration fails, the method will throw an error.

val initializeCF: CompletableFuture<Void> = web3Auth.initialize()
initializeCF.whenComplete { _, error ->
if (error == null) {
// Check for the active session
if(web3Auth.getPrivKey()isNotEmpty()) {
// Active session found
}
// No active session is not present

} else {
// Handle the error
}
}

Advanced Configuration

The Web3Auth Android SDK offers a rich set of advanced configuration options:

tip

Head over to the advanced configuration sections to learn more about each configuration option.

val web3Auth = Web3Auth(
Web3AuthOptions(
context = this,
clientId = "YOUR_CLIENT_ID",
network = Network.SAPPHIRE_MAINNET, // or Network.SAPPHIRE_DEVNET
redirectUrl = "YOUR_APP_SCHEME://auth"
)
)

Blockchain Integration

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

Ethereum Integration

For Ethereum integration, you can get the private key using the getPrivKey method and use it with web3j or other Ethereum libraries:

import org.web3j.crypto.Credentials
import org.web3j.protocol.core.DefaultBlockParameterName
import org.web3j.protocol.Web3j
import org.web3j.protocol.http.HttpService

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

// Generate the Credentials
val credentials = Credentials.create(privateKey)

// Get the address
val address = credentials.address

// Create the Web3j instance using your RPC URL
val web3 = Web3j.build(HttpService("YOUR_RPC_URL"))

// Get the balance
val balanceResponse = web3.ethGetBalance(address, DefaultBlockParameterName.LATEST).send()

// Convert the balance from Wei to Ether format
val ethBalance = BigDecimal.valueOf(balanceResponse.balance.toDouble()).divide(BigDecimal.TEN.pow(18))

Solana Integration

For Solana integration, you can get the Ed25519 private key using the getEd25519PrivKey method and use it with sol4k or any other Solana libraries:

import org.sol4k.Connection
import org.sol4k.Keypair

val connection = Connection(RpcUrl.DEVNET)

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

// Generate the Solana KeyPair
val solanaKeyPair = Keypair.fromSecretKey(ed25519PrivateKey.hexToByteArray())

// Get the user account
val userAccount = solanaKeyPair.publicKey.toBase58()

// Get the user balance
val userBalance = connection.getBalance(userAccount).toBigDecimal()