Using Web3Auth Android SDK
This guide will cover the basics of how to use the Web3Auth Android SDK in your Android application.
Demo APK: Download
Repository: https://github.com/Web3Auth/web3auth-pnp-examples/tree/main/android/android-example
Quick Start
npx degit Web3Auth/web3auth-pnp-examples/android/android-example w3a-android-demo
# Open in Android Studio
How it works?
When integrating Web3Auth Android SDK with Social Login the flow looks something like this:
When a user logs in with
Google
, Google sends a JWTid_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
- Android API version 21 or newer.
Setup
Setup your Web3Auth Dashboard
Create a Project from the Project Section of the Web3Auth Developer 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 thesapphire_devnet
ortesnet
network during development. While moving to a production environment, make sure to convert your project tosapphire_mainnet
or any of the legacy mainnet networkmainnet
,aqua
, orcyan
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.
- Add
{YOUR_APP_PACKAGE_NAME}://auth
in the Whitelist URL field of the Web3Auth Dashboard.
Configure Deep Link
Open your app's AndroidManifest.xml
file and add the following deep link intent filter to your sign-in activity:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Accept URIs: {YOUR_APP_PACKAGE_NAME}://* -->
<data android:scheme="{YOUR_APP_PACKAGE_NAME}" />
</intent-filter>
Make sure your sign-in activity launchMode is set to singleTop in your AndroidManifest.xml
<activity
android:launchMode="singleTop"
android:name=".YourActivity">
<!-- ... -->
</activity>
Using the Web3Auth SDK
To use the Web3Auth SDK, you'll need to add the dependency of the respective platform SDK of Web3Auth to your project. To know more about the available SDKs, please have a look at our SDK page.
For this guide, we will be using the Web3Auth Android SDK.
Installation
Add Web3Auth to Gradle
In your project-level settings.gradle
file, add JitPack repository:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
maven { url "https://jitpack.io" } // <-- Add this line
}
}
Then, in your app-level build.gradle
dependencies section, add the following:
dependencies {
// ...
implementation 'com.github.Web3Auth:web3auth-android-sdk:4.0.8'
}
Permissions
Open your app's AndroidManifest.xml
file and add the following permission:
<uses-permission android:name="android.permission.INTERNET" />
Note: The
<uses-permission>
element must be a direct child of the<manifest>
root element
Initialization
Initialization is a two-step process:
Please note that these are the most critical steps where you must pass on different parameters according to the preference of your project. Additionally, You must configure Whitelabeling and Custom Authentication within this step if you wish to customize your Web3Auth Instance.
Create Web3Auth Instance
In your activity, create a Web3Auth
instance with your Web3Auth project's configurations.
web3Auth = Web3Auth(
Web3AuthOptions(
context = this,
clientId = getString(R.string.web3auth_project_id), // pass over your Web3Auth Client ID from Developer Dashboard
network = Network.MAINNET, // pass over the network you want to use (MAINNET, TESTNET, CYAN, AQUA )
redirectUrl = Uri.parse("{YOUR_APP_PACKAGE_NAME}://auth"), // your app's redirect URL
)
)
// Handle user signing in when app is not alive
web3Auth.setResultUrl(intent?.data)
Add the below line to your app/res/values/strings.xml
file and paste your Web3Auth Client ID:
<resources>
<!-- ... -->
<string name="web3auth_project_id">CLIENT_ID_FROM_WEB3AUTH_DASHBOARD</string>
<!-- ... -->
</resources>
Read more about initialising the Android SDK here.
Set Result URL
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
// Handle user signing in when app is active
web3Auth.setResultUrl(intent?.data)
}
Authentication
Logging in
Once initialized, you can use the web3Auth.login(LoginParams("{selectedLoginProvider}"))
function to authenticate the user when they click the login
button.
private fun signIn() {
val selectedLoginProvider = Provider.GOOGLE // Can be GOOGLE, FACEBOOK, TWITCH etc.
val loginCompletableFuture: CompletableFuture<Web3AuthResponse> = web3Auth.login(LoginParams(selectedLoginProvider))
loginCompletableFuture.whenComplete { loginResponse, error ->
if (error == null) {
// render logged in UI
println(loginResponse)
} else {
// render error UI
}
}
}
When connecting, the login
function takes the LoginParams arguments for the login. See the LoginParams for more
details.
Sample loginResponse
{
"privKey": "0ajjsdsd....",
"userInfo": {
"name": "John Dash",
"profileImage": "https://lh3.googleusercontent.com/a/Ajjjsdsmdjmnm...",
"typeOfLogin": "google",
"aggregateVerifier": "tkey-google",
"verifier": "torus",
"verifierId": "john@gmail.com",
"email": "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
},
"ed25519PrivKey": "666523652352635....",
"coreKitKey": "0xajjsdsd....",
"coreKitEd25519PrivKey": "666523652352635....",
"sessionId": "0xajjsdsd...."
}
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 Android application, read the linked documentation.
Logout
private fun signOut() {
val logoutCompletableFuture = web3Auth.logout()
logoutCompletableFuture.whenComplete { _, error ->
if (error == null) {
// render logout UI
} else {
// render error UI
}
}
}
Logging out your user is as simple as calling the web3Auth.logout()
function.
Interacting with the Blockchain
Checkout the full codes to interact with the ETH Blockchain.
Get Account
// checkout the Connect Blockchain > Ethereum > Android to get full code.
private fun getAddress(): String {
println("Address:, ${credentials.address}")
return credentials.address
}
// Setup UI and event handlers
val getBalanceButton = findViewById<Button>(R.id.getBalanceButton)
getBalanceButton.setOnClickListener { getAddress() }
Get Balance
// checkout the Connect Blockchain > Ethereum > Android to get full code.
private fun getBalance(): BigInteger? {
val publicAddress = credentials.address
val ethBalance: EthGetBalance = web3.ethGetBalance(publicAddress, DefaultBlockParameterName.LATEST).sendAsync().get()
println("Balance: ${ethBalance.balance}")
return ethBalance.balance
}
// Setup UI and event handlers
val getBalanceButton = findViewById<Button>(R.id.getBalanceButton)
getBalanceButton.setOnClickListener { getBalance() }
Send Transaction
// checkout the Connect Blockchain > Ethereum > Android to get full code.
private fun sendTransaction(amount: Double, recipientAddress: String): String? {
val ethGetTransactionCount: EthGetTransactionCount = web3.ethGetTransactionCount(credentials.address, DefaultBlockParameterName.LATEST).sendAsync().get()
val nonce: BigInteger = ethGetTransactionCount.transactionCount
val value: BigInteger = Convert.toWei(amount.toString(), Convert.Unit.ETHER).toBigInteger()
val gasLimit: BigInteger = BigInteger.valueOf(21000)
val chainId: EthChainId = web3.ethChainId().sendAsync().get()
// Raw Transaction
val rawTransaction: RawTransaction = RawTransaction.createTransaction(
chainId.chainId.toLong(),
nonce,
gasLimit,
recipientAddress,
value,
"",
BigInteger.valueOf(5000000000),
BigInteger.valueOf(6000000000000)
)
val signedMessage: ByteArray = TransactionEncoder.signMessage(rawTransaction, credentials)
val hexValue: String = Numeric.toHexString(signedMessage)
val ethSendTransaction: EthSendTransaction = web3.ethSendRawTransaction(hexValue).sendAsync().get()
return if(ethSendTransaction.error != null) {
println("Tx Error: ${ethSendTransaction.error.message}")
ethSendTransaction.error.message
} else {
println("Tx Hash: ${ethSendTransaction.transactionHash}")
ethSendTransaction.transactionHash
}
}
// Setup UI and event handlers
val sendTransactionButton = findViewById<Button>(R.id.sendTransactionButton)
sendTransactionButton.setOnClickListener { sendTransaction() }
Example code
The code for the application we developed in this guide can be found in the Web3Auth Android Example. Check it out and try running it locally yourself!
Also, checkout other examples:
- Using Auth0 with Android SDK
- Using Custom JWT (via Firebase) with Android SDK
- Using Aggregate Verifier with Android SDK
Questions?
Ask us on Web3Auth's Community Portal