Develop a Blockchain Shopping App


Objective

Create a shopping application with Samsung Blockchain Platform SDK and pay using Ethereum network.

Overview

The Blockchain industry is expanding in many ways. Among them, it is growing the most as a means of payment. Samsung Blockchain Platform SDK helps to make payments easily with cryptocurrency. You can interact with Blockchain through a simple API call to create a Transaction.

In this Code Lab, you can pay for a product using the Ethereum network in a simple shopping app, which is a Decentralized Application (DApp). These apps run and store data on the Blockchain network instead of a central server.

Set up your environment

You will need the following:

  • Java SE Development Kit 8 or later
  • Android Studio (latest version recommended)
  • Mobile phone which supports Samsung Blockchain

Sample Code

Here is a sample code for you to start coding in this Code Lab. Download it and start your learning experience!

Platform SDK Sample Code
(11.06 MB)

Enable developer mode

To activate developer mode of Samsung Blockchain Keystore, tap the Samsung Blockchain Keystore area 10 times or more. Navigate it through Settings > Biometrics and security > Samsung Blockchain Keystore > About Blockchain Keystore.

Import project file

Open the downloaded sample code containing the shopping app project. Go to File > Open and select the Open File or Project window.

Every GUI resources are already included in the provided project. So what you need to do is fill out the code by following the next steps. Moreover, going through the SDK document will be helpful as well.

Initialize the instance

Create Sblockchain instance. This is the first step since Sblockchain is the initial base class of SDK. Along with that are:

  • HardwareWalletManager: responsible for wallet operations
  • AccountManager: responsible for account operations

mSBlockchain = new SBlockchain();
mSBlockchain.initialize(mContext);
mAccountManager = mSBlockchain.getAccountManager();
mHardwareWalletManager = mSBlockchain.getHardwareWalletManager();
mCoinNetworkInfo =
        new CoinNetworkInfo(
                CoinType.ETH,
                EthereumNetworkType.ROPSTEN,
                rpcUrl
        );

connectToKeyStore();

Connect to Samsung Blockchain Keystore

You can get hardware wallet instance from HardwareWalletManager. HardwareWalletType refers to the type of cold wallet to be connected, for example Samsung Blockchain Keystore, Ledger Nano S, etc.

Refer to the sample code:


mHardwareWalletManager 
        .connect(
                HardwareWalletType.SAMSUNG,
                false
        ).setCallback(new ListenableFutureTask.Callback<HardwareWallet>() {

    @Override
    public void onSuccess(HardwareWallet hardwareWallet) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG,"HardwareWallet is connected Successfully");
                mProgressDialog.dismiss();
                setAccountStatus();
            }
        });
    }

    @Override
    public void onFailure(@NotNull ExecutionException e) {
        mProgressDialog.dismiss();
        e.printStackTrace();
    }

    @Override
    public void onCancelled(@NotNull InterruptedException e) {
        mProgressDialog.dismiss();
        e.printStackTrace();
    }
});

The second parameter of connect API refers to reset. If you do not want to reset the wallet then keep it false, otherwise true.

Manage your account

Now your shopping DApp is connected to the Keystore. It means, if you have your own account and balance, you can now buy something using Ether (or ETH). Let’s create an Ethereum account to be used for payment.

For generating new account with Samsung Blockhain Platform SDK you need an instance of the AccountManager from SBlockchain. AccountManager which provides methods regarding fetching, creating, restoring accounts, etc. Once you have an instance of AccountManager, you can call generateNewAccount as shown below. It has methods regarding accounts such as get, create, restore, and more. Refer to SDK documents for more details.

Create your own account:


HardwareWallet connectedHardwareWallet =
        mHardwareWalletManager.getConnectedHardwareWallet();

if (connectedHardwareWallet != null) {
    try {
        return mAccountManager.generateNewAccount(connectedHardwareWallet, mCoinNetworkInfo).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
} else {
    Log.i(TAG, "connectedHardwareWallet is null");
}

If you already have an account, it will be shown in the TextView at the top and the button will be disabled to prevent further creation:


List<Account> accounts =
        mAccountManager
                .getAccounts(
                        null,
                        CoinType.ETH,
                        EthereumNetworkType.ROPSTEN
                );

if (!accounts.isEmpty()) {
    mEthereumAccount = (EthereumAccount) accounts.get(accounts.size() - 1);
    tvAccountStatus.setText(mEthereumAccount.getAddress());
    btnCreateAccount.setEnabled(false);
}

Get instance for Ledger Service

Now that you have created an account, you can use it for payment in your sample shopping app. Each coin (blockchain ledgers) has their own system to be stored in blocks. Samsung Blockchain Platform SDK provides abstracted API sets to developers for signing and sending supported cryptocurrency transactions over the Blockchain network. Create CoinServiceFactory and just use any ledger you want. In this scenario, use EthereumService:


EthereumService service =
        (EthereumService) CoinServiceFactory.getCoinService(mContext, mCoinNetworkInfo);
		

Now your shopping DApp is ready to provide payment methods working on Ethereum.

Show payment sheet

When your customer selects an item, you will show a payment sheet to them. It must show “Who will pay HOW MUCH Amount of ETHER to Whom”. In the Blockchain world, Ethereum ledgers need more information (i.e transaction nonce) to record that transaction into ledgers. But do no worry, Samsung Blockchain Platform SDK will do everything needed.

To show the payment sheet, intent should be created, which is to call payment activity on click event of product object. Fill the params required and startActivityForResult() to show a payment sheet:


Item item = itemList.get(position);
BigInteger price = EthereumUtils.convertEthToWei(item.getPrice());
EthereumService service =
                (EthereumService) CoinServiceFactory.getCoinService(mContext, mCoinNetworkInfo);

HardwareWallet connectedHardwareWallet =
        mHardwareWalletManager.getConnectedHardwareWallet();

Intent intent =
        service
                .createEthereumPaymentSheetActivityIntent(
                        mContext,
                        connectedHardwareWallet,
                        mEthereumAccount,
                        SAMPLE_TO_ADDERSS,
                        price,
                        null,
                        null
                );

startActivityForResult(intent, 0);

Get Ether from faucet

You need money when you buy something. You need Ether in this case. There’s a free faucet site already. If you have an Ethereum account, just go to WebView fragment and press request 1 ether from faucet button.

See the result of transaction

If payment performed successfully from the payment screen, result of transaction can be received from onActivityResult. If transaction is performed properly, you will find RESULT_OK at resultCode. From the intent, you will get txid which is used to search your transaction’s status.

  1. Call getTransactionDetail(txid: String) API (method in EthereumService) and check the block#. If there’s any valid countable number, your transaction is stored in blocks successfully and the payment is done. If you can’t find it, just wait. It’s processing among Ethereum nodes.

  2. Or just simply find txid in the Etherscan.io.

    • Set your network to Ropsten Testnet
    • Search with txid

Run the project you have created so far and verify that it works properly. Run the app and select the product from the list, the payment screen will be shown, select the fee to pay to the Ethereum network, and confirm the transaction with the button. Then, check the result of the generated transaction. Sample images of the app screen can be seen below:

You're done!

Congratulations! You have successfully achieved the goal of this Code Lab. Now, you develop a decentralized shopping app using Samsung Blockchain Platform SDK by yourself! If you're having trouble, you may download this file:

Platform SDK Complete Code
(2.03 MB)