Integrate Web3Auth with the Klaytn 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 Klaytn to make any blockchain calls. We have highlighted a few here for getting you started quickly on that.
Prerequisites
This doc assumes you have already setup your project in Web3Auth Dashboard, and have integrated Web3Auth in your Android app. If you haven't done that yet, you can learn how to integrate Web3Auth in your Android app.
Installation
To interact with the Ethereum Compatible Blockchain 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 Web3Auth.
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, you can checkout ChainList.
import org.web3j.protocol.Web3j
import org.web3j.protocol.http.HttpService
// Please avoid using public RPC URL in production, use services
// like Infura, Quicknode, etc.
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 Web3Auth instance. We'll use this private key to generate the Credentials for the user.
This Credentials object has the user's key pair 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 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
Get Balance
To retrieve the native balance of the user, you can use the Web3j
instance we created earlier. It
has ethGetBalance
method which helps to fetch the user's native token balance.
The result we get from method is in wei, the smallest value. To convert the value to ether, you can divide it with 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 helps to send 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.
The nonce is the number of transactions sent from the sender's address. The gas price is the price
of the gas, which is the unit of account for the transaction. The gas limit is the maximum amount of
gas that the sender is willing to pay for the transaction. The value is the amount of ether to send.
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