Skip to main content

Integrate Embedded Wallets with the Moonbeam Blockchain in Android

While using the Web3Auth Android SDK, you get the private key within the user scope after successful authorization. This private key can be used to retrieve the user's address, and interact with Moonbeam to make any blockchain calls. We have highlighted a few here for getting you started quickly on that.

Chain details for Moonbeam

Prerequisites

This doc assumes you have already setup your project in the Embedded Wallets Dashboard (formerly Web3Auth), and have integrated Embedded Wallets in your Android app. If you haven't done that yet, you can learn how to integrate Embedded Wallets in your Android app.

Installation

To interact with Ethereum in Android, you can use any EIP1193-compatible package available for Android. Here we're using web3j to demonstrate how to make blockchain calls using it with Embedded Wallets.

dependencies {
// ...
implementation 'org.web3j:core:4.8.7-android'
}

Initialize

We'll initialize the Web3j instance with the RPC URL of the network you want to connect to. This client allows us to interact with the blockchain. To get the public RPC URL, see ChainList.

import org.web3j.protocol.Web3j
import org.web3j.protocol.http.HttpService

// Please avoid using public RPC URL in production, use services
// like Infura.
val web3 = Web3j.build(HttpService("YOUR_RPC_URL"))

Get account

Once user has successfully logged in, you can retrieve the user's private key using the getPrivKey method from the Embedded Wallets Android SDK. We'll use this private key to generate the Credentials for the user.

This Credentials object has the user's keypair of private key and public key, and can be used to sign the transactions. Please note, that this assumes that the user has already logged in and the private key is available.

import org.web3j.crypto.Credentials

// Use your Embedded Wallets SDK 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

Get balance

To retrieve the native balance of the user, you can use the Web3j instance we created earlier. It has ethGetBalance method which fetches the user's native token balance.

The result we get from Web3Client is in wei, the smallest unit of ether. To convert wei to ether, divide by 10^18, where 18 denotes the decimals for wei.

import org.web3j.protocol.core.DefaultBlockParameterName

// Use the existing Web3j instance, and address from the previous step
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))

Sign a message

To sign the message, you need to use the Sign.signPrefixedMessage method. The method takes in the data of the message, ecKeyPair, and returns the Signature object which has r, s and v value of the signature.

We can append the r, s, and v values to generate the signed hash. The r value is the first 32 bytes of the signature, s is the next 32 bytes, and v is the last 1 byte of the signature.

import org.web3j.utils.Numeric
import org.web3j.crypto.Sign

val message = "Hello World"
val signature = Sign.signPrefixedMessage(message.toByteArray(), credentials.ecKeyPair)

val r = Numeric.toHexString(signature.r)
val s = Numeric.toHexString(signature.s).substring(2)
val v = Numeric.toHexString(signature.v).substring(2)

val signedHash = StringBuilder(r).append(s).append(v).toString()

Send transaction

To send a transaction, you can use the Web3j instance we created earlier. It has ethSendRawTransaction method which sends the raw transaction to the network. To create a raw transaction, you need to retrieve nonce, gas price, gas limit, and the value of the transaction:

  • nonce is the number of transactions sent from the sender's address
  • gas price is the unit of account for the transaction
  • gas limit is the maximum amount of gas that the sender is willing to pay for the transaction

The gas values are in ether. The default gas limit for a transfer ETH transaction is 21000, but you can also estimate the gas limit explicitly using ethEstimateGas method.

import org.web3j.protocol.core.methods.response.EthGetTransactionCount
import org.web3j.protocol.core.methods.response.EthSendTransaction
import org.web3j.crypto.TransactionEncoder
import org.web3j.crypto.RawTransaction
import org.web3j.utils.Numeric

val ethGetTransactionCount: EthGetTransactionCount = web3.ethGetTransactionCount(
address, DefaultBlockParameterName.LATEST
).sendAsync().get()

val nonce: BigInteger = ethGetTransactionCount.transactionCount
// Convert the amount to wei
val value: BigInteger = Convert.toWei("0.0001", Convert.Unit.ETHER).toBigInteger()
val gasLimit: BigInteger = BigInteger.valueOf(21000)
val gasPrice = web3.ethGasPrice().sendAsync().get()


val rawTransaction: RawTransaction = RawTransaction.createEtherTransaction(
nonce,
gasPrice.gasPrice,
gasLimit,
"RECEIVER_ADDRESS_IN_HEX",
value
)

val signedMessage: ByteArray = TransactionEncoder.signMessage(rawTransaction, credentials)
val hexValue: String = Numeric.toHexString(signedMessage)

val ethSendTransaction: EthSendTransaction = web3.ethSendRawTransaction(hexValue).sendAsync().get()

if (ethSendTransaction.error != null) {
// Handle error
throw Exception(ethSendTransaction.error.message)
}

val transactionHash = ethSendTransaction.transactionHash