Development

The given android application project is a simple comments DApp based on Ethereum Ropsten test network. It retrieves comments data from smart contract, displays them on the screen, and makes a transaction to execute smart contract function to post user’s comment.

In the following steps, you can get an account address and execute DApp service with Blockchain Keystore and you can see the result of successful DApp execution.

Step 1: Setting App ID

In this tutorial, you don’t need to set the application ID to use Samsung Blockchain Keystore SDK. Instead, you must enable developer mode as described in the previous section.

For the release version of your Android app, in your Android Manifest file, add a metadata with a name as scw_app_id and a value as the App ID issued by Samsung Blockchain Keystore team. Samsung Blockchain Keystore aar file will read this value when your Android app is initialized and help your Android app connect to Samsung Blockchain Keystore.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.samsung.android.sdk.coldwallet.test"
        android:versionCode="1"
        android:versionName="1.0">
    <application>
        <meta-data android:name="scw_app_id"
                   android:value= <!-- PUT YOUR APP ID HERE --> />
    </application>
</manifest>

Step 2: Import Samsung Blockchain Keystore SDK library into project

The SDK library is located at aar/KeystoreSDK_v1.1.0.aar of the project file. To import the library go to Gradle Scripts > build.gradle and enter the following dependencies.

dependencies {
    repositories {
            flatDir{
                dirs 'aar'
            }
    }
    
    implementation 'com.samsung.android.sdk.coldwallet:KeystoreSDK_v1.1.0@aar'
}

Step 3: Checking the status of Samsung Blockchain Keystore

The first thing to do is to check the status of Samsung Blockchain Keystore. In the sample application, it is implemented at initializeKeystore() in presenter IntroPresenter.java. You can find the following steps to check the status of Keystore.

  1. In your Android app, call ScwService.getInstance(). If the returned value is an instance and not null, then it means Samsung Blockchain Keystore is supported on the device. However, if null is returned, the user must use a different keystore. In the sample code, toast a message to notify the device doesn’t support the keystore.

    // Check Samsung blockchain keystore is supported or not.
    if (ScwService.getInstance() == null) {
        mContract.toastMessage("Samsung blockchain Keystore is not supported on your device.");
        return false;
    }
    

  2. Call getKeystoreApiLevel API to see if the current Samsung Blockchain Keystore being used properly supports the features that your Android app is currently aiming for. If the required API level is higher than the current Samsung Blockchain Keystore level, users are directed to Samsung Blockchain Keystore app page in Galaxy Store through the provided deeplink to update.

     // check installed api level
    else if (ScwService.getInstance().getKeystoreApiLevel() < 1) {
        // if api level is lower, jump to galaxy apps to update keystore app.
        mContract.showDialog(""
            , "OK"
            , "The api level is too low. Jump to galaxy store"
            , () -> mContract.launchDeepLink(ScwDeepLink.GALAXY_STORE));
    }
    
    

  3. Check if a user has set up the Samsung Blockchain Keystore and is ready to use it by calling getSeedHash API. If the Seed Hash value in string is zero-length, this means the user has not set up Samsung Blockchain Keystore yet. Hence, your app will need to guide the user to jump to Samsung Blockchain Keystore via deeplink to either create or import a wallet.

    // check seed hash exist.
    else if (ScwService.getInstance().getSeedHash().length() == 0) {
        // if seed hash is empty,
        // jump to blockchain keystore to create or import wallet
        mContract.showDialog(""
            , "OK"
            , "The seed hash is empty." +
                "Jump to blockchain keystore to create/import wallet."
            , () -> mContract.launchDeepLink(ScwDeepLink.MAIN));
    }
    

  4. If the getSeedHash API returned value is not zero-length, it means that the user has successfully set up Samsung Blockchain Keystore. If there is a previously saved or cached Seed Hash value, compare the two Seed Hash values. If those two values are not equal, nor if there is no such saved cached Seed Hash value, then the address has to be checked again. If the Seed Hash value has been changed, it means the Master Seed has been changed as well, meaning the address that your Android app was linked to may no longer be the same address.

    // check seed hash cached
    else if (!TextUtils.equals(cachedSeedHash, ScwService.getInstance().getSeedHash())) {
        // if the seed hash is different from cached, update seed hash and address
        // if success, go to next activity.
        final String ethereumHdPath = "m/44'/60'/0'/0/0";
        getEthereumAddress(ethereumHdPath
                , (success, errorCode, address, seedHash) -> {
            if (success) {
                updateAddress(address);
                updateSeedHash(seedHash);
                mContract.showTimelineActivity(true);
            } else {
                mContract.toastMessage("Cannot get address. error:" + errorCode);
            }
        });
    } 
    
    

  5. If those two values are equal, it means checking the Keystore status was successful, and you can move on to the next step.

    // success
    else {
        // set address from cached value
        // go to next activity
        String address = PrefsHelper.getInstance().getCachedAddress();
    
        updateSeedHash(cachedSeedHash);
        updateAddress(address);
        mContract.showTimelineActivity(false);
    } 
    

Step 4: Get Ethereum address

In the Blockchain network, the address can be used like a user’s account as the balance and the transaction history can be checked using the address. In this sample project, get the address from Keystore and display the address and account balance in bottom sheet of the screen. Keystore is a Hierarchical Deterministic (HD) Wallet, a standard tree structure represented by derivation paths. For the Ethereum address, use “m/44'/60'/0'/0/0” follow BIP44.

It is implemented at getEthereumAddress(String hdpath, GetEthereumAddressCallback callback) in presenter/IntroPresenter.java.

ArrayList<String> path = new ArrayList<>();
path.add(hdpath);
ScwService.getInstance().getAddressList(new ScwService.ScwGetAddressListCallback() {
    @Override
    public void onSuccess(List<String> list) {
        String seedHash = ScwService.getInstance().getSeedHash();
        String address = list.get(0);
        callback.OnAddressReceived(true, 0, address, seedHash);
    }
 
    @Override
    public void onFailure(int errorCode) {
        callback.OnAddressReceived(false, errorCode, "", "");
    }
}, path); 


Step 5: Sign a transaction

Ether value transfer or smart contract execution is executed by transactions that users create and sign. Signing a transaction is the process of generating a signature on it using the private key of transaction sender.

Samsung Blockchain Keystore can be utilized to sign a cryptocurrency transaction, such as Ethereum by implementing the following steps:

  1. Creates an unsigned transaction, and requests Samsung Blockchain Keystore to sign the transaction via APIs like signEthTransaction.
  2. Then the user will see a transaction confirmation page on a secure screen called, Trusted User Interface (TUI) executed in Trusted Execution Environment (TEE) by Samsung Blockchain Keystore.
  3. Once the user confirms the transaction with PIN or Biometrics Authentication, like fingerprint, Samsung Blockchain Keystore will sign a transaction with the private key derived from the given HD Path.
  4. When Samsung Blockchain Keystore returns the signed transaction, your app can submit or send the signed transaction to the Blockchain network.

In this sample project, create an unsigned transaction to execute posting a comment smart contract. Then sign the transaction with Keystore and send the transaction.

It is implemented at signTransaction() in presenter/WriteFeedPresenter.java.

// Sign the transaction with Samsung blockchain keystore
// Use HDPath m/44'/60'/0'/0/0
final String HDPath = "m/44'/60'/0'/0/0";
 
ScwService.getInstance().signEthTransaction(
    new ScwService.ScwSignEthTransactionCallback() {
        @Override
        public void onSuccess(byte[] signedTransaction) {
            boolean result = sendSignedTransaction(signedTransaction);
            listener.transactionDidFinish(result, "");
        }

        @Override
        public void onFailure(int errorCode) {
            listener.transactionDidFinish(false, "Error code : " + errorCode);
        }
    }, unsignedTx, HDPath);

Run the app and try it out. The app screen should look like below.

You're done!

Congratulations! You have successfully achieved the goal of this Code Lab activity. Now, you can create a decentralized app by yourself! But, if you're having trouble, you may check out the link below.

Keystore SDK Complete Code886.34 KB