Transfer ERC20 Token with Blockchain App


Objective

Develop a decentralized application (DApp) to transfer ERC20 tokens between Ethereum accounts using Samsung Blockchain Platform SDK.

Overview

Blockchain technology has been creating a significant impact in multiple sectors, such as banking, cybersecurity, and supply chain management. It is widely used as a means of secure payment between different parties. Samsung Blockchain Platform SDK brings developers and consumers to the Blockchain world by providing a complete set of functions that the decentralized app (DApp) or Blockchain app needs.

Ethereum is a decentralized Blockchain network where you can perform transactions using its native currency, Ether, and token. You can interact with the network through simple API calls provided by the SDK.

For detailed information, see Samsung Blockchain Platform SDK.

Set up your environment

You will need the following:

  • Java SE Development Kit 8 or later
  • Android Studio (latest version recommended)
  • Samsung Galaxy device that 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!

Token Transaction Sample Code
(2.73 MB)

Enable developer mode

To activate Developer Mode on your mobile device, follow the steps below:

  1. Navigate through Settings > Biometrics and security > Samsung Blockchain Keystore and click About Blockchain Keystore.
  2. Tap the Samsung Blockchain Keystore app name quickly, ten times or more.
  3. If succeeded, (Developer Mode) will show.

Start your project

After downloading the sample code containing the project files, in Android Studio, click Open to open the existing project.

Locate the downloaded Android Project (CodeLab-Send-Token-Transaction-Blank-Code) from the directory and click OK.

Initialize the instance

Since SBlockchain is the initial base class of the Samsung Blockchain Platform SDK, the first thing you need to do is create an SBlockchain instance. Along with that, create the following in SendTokenFragment.java:

  • HardwareWalletManager for wallet operations
  • AccountManager for account operations
  • EthereumService for transactions
mSBlockchain = new SBlockchain();
try {
    mSBlockchain.initialize(mContext);
}
catch (SsdkUnsupportedException e) {
    e.printStackTrace();
}

mAccountManager = mSBlockchain.getAccountManager();
mHardwareWalletManager = mSBlockchain.getHardwareWalletManager();
mCoinNetworkInfo = new CoinNetworkInfo(
	CoinType.ETH,
	EthereumNetworkType.GOERLI,
	rpcUrl
);
mCoinService = CoinServiceFactory.getCoinService(getContext(), mCoinNetworkInfo);
ethereumService = (EthereumService) mCoinService;
connectToHardwareWallet();

Connect to Samsung Blockchain Keystore

Connect the app to the hardware wallet, which, in this case, is the Samsung Blockchain Keystore. You can get a hardware wallet instance from HardwareWalletManager.

If you want to reset the wallet, set the second parameter of connect API to true. Otherwise, set it to false.

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.");
                    mProgressBar.setVisibility(View.INVISIBLE);
                    getAccount();
                }
            });
        }

        @Override
        public void onFailure(@NonNull ExecutionException e) {
            mProgressBar.setVisibility(View.INVISIBLE);
            Log.e(TAG, "HardwareWallet connection failed. " + e);
        }

        @Override
        public void onCancelled(@NonNull InterruptedException e) {
            mProgressBar.setVisibility(View.INVISIBLE);
            Log.e(TAG, "HardwareWallet connection cancelled. " + e);
        }
    }
);

Generate new account

Samsung Blockchain Platform SDK manages the address on Blockchain as an account. It contains the information required for signing and the Blockchain address.

AccountManager provides APIs dedicated for fetching, creating, and restoring accounts.

Use generateNewAccount API for the creation of a new Ethereum account upon clicking the Create Account button in the app.

HardwareWallet connectedHardwareWallet = mHardwareWalletManager.getConnectedHardwareWallet();
mAccountManager.generateNewAccount(connectedHardwareWallet, mCoinNetworkInfo).setCallback(
    new ListenableFutureTask.Callback<Account>() {
        @Override
        public void onSuccess(Account account) {
            mProgressBar.setVisibility(View.INVISIBLE);
            Log.i(TAG, "Generate New Account Successful. " + account);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    getAccount();
                }
            });
        }

        @Override
        public void onFailure(@NonNull ExecutionException e) {
            mProgressBar.setVisibility(View.INVISIBLE);
            Log.e(TAG, "Generate New Account failed. " + e);
        }

        @Override
        public void onCancelled(@NonNull InterruptedException e) {
            mProgressBar.setVisibility(View.INVISIBLE);
            Log.e(TAG, "Generate New Account cancelled. " + e);
        }
    }
);

After creating a new account, call the getAccounts API to get the account list.

If you already have an account, the TextView will show the account's address and the Create Account button will be disabled in the app.

accounts = mAccountManager.getAccounts(
    null,
    CoinType.ETH,
    EthereumNetworkType.GOERLI
);
if(!accounts.isEmpty()){
    mEthereumAccount = (EthereumAccount) accounts.get(accounts.size() - 1);
    showAccountTextView.setText(mEthereumAccount.getAddress());
    generateAccountButton.setEnabled(false);
}

Create a token account

To perform a token transaction, add the token address with the corresponding Ethereum account and create a token account by calling the addTokenAddress API.

Use the generated token account to perform token-related actions. An Ethereum account can add one or more tokens.

ethereumService.addTokenAddress(mEthereumAccount, tokenAddress).setCallback(
    new ListenableFutureTask.Callback<EthereumAccount>() {
        @Override
        public void onSuccess(EthereumAccount ethereumAccount) {
            mProgressBar.setVisibility(View.INVISIBLE);
            Log.i(TAG, "Add Token Successful " + ethereumAccount);

            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(), "Add Token Successful", Toast.LENGTH_SHORT).show();
                }
            });
        }

        @Override
        public void onFailure(@NonNull ExecutionException e) {
            mProgressBar.setVisibility(View.INVISIBLE);
            Log.e(TAG, "Add Token failed " + e);
        }

        @Override
        public void onCancelled(@NonNull InterruptedException e) {
            mProgressBar.setVisibility(View.INVISIBLE);
            Log.e(TAG, "Add Token cancelled " + e);
        }
    }
);		

Get token balance

Fetch the balance of the added token using getTokenBalance API.

ethereumService.getTokenBalance(mTokenAccount, EthereumBlockParameter.LATEST).setCallback(
    new ListenableFutureTask.Callback<BigInteger>() {
        @Override
        public void onSuccess(BigInteger bigInteger) {
            mProgressBar.setVisibility(View.INVISIBLE);

            BigDecimal tokenDecimal = BigDecimal.TEN.pow(18);
            BigDecimal balance = new BigDecimal(bigInteger).divide(tokenDecimal);

            Log.d(TAG, "getTokenBalance success " + balance);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    tokenBalance.setText(balance.toString());
                }
            });
        }

        @Override
        public void onFailure(@NonNull ExecutionException e) {
            mProgressBar.setVisibility(View.INVISIBLE);
            Log.e(TAG, "getTokenBalance failed " + e);
        }

        @Override
        public void onCancelled(@NonNull InterruptedException e) {
            mProgressBar.setVisibility(View.INVISIBLE);
            Log.e(TAG, "getTokenBalance cancelled " + e);
        }
    }
);

Transfer token

To transfer tokens between accounts, set the receiver address and the amount of tokens to send.

The trusted UI of the Samsung Blockchain Keystore hardware wallet appears upon pressing the Send button in the app, showing all the information regarding the transaction for confirmation. Generate a Transaction Hash upon confirmation of the transaction.

ethereumService.sendTokenTransaction(
    mHardwareWalletManager.getConnectedHardwareWallet(),
    mTokenAccount,
    mToAddress,
    tokenAddress,
    maxPriorityFee,
    mEthereumFeeInfo.getEstimatedBaseFee().add(maxPriorityFee),
    mGasLimit,
    mSendTokenAmount,
    null
).setCallback(new ListenableFutureTask.Callback<TransactionResult>() {
    @Override
    public void onSuccess(TransactionResult transactionResult) {
        mProgressBar.setVisibility(View.INVISIBLE);
        Log.i(TAG, "Send Token Successful " + transactionResult.getHash());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "Transaction Hash: " + transactionResult.getHash(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onFailure(@NonNull ExecutionException e) {
        mProgressBar.setVisibility(View.INVISIBLE);
        Log.e(TAG, "Send Token failed " + e);
    }

    @Override
    public void onCancelled(@NonNull InterruptedException e) {
        mProgressBar.setVisibility(View.INVISIBLE);
        Log.i(TAG, "Send Token cancelled " + e);
    }
});

Run the app

After building the APK, follow the steps below to test the application on a Samsung Blockchain-compatible device:

  1. In Send Token tab, click Create Account. Copy the generated account address.

  1. Go to Eth Faucet tab to open the free faucet site already added to the application. Paste the account address and press the Send Me ETH button.
  2. Click the hash string under Your Transactions to open Etherscan and wait until the transaction succeeded.

  1. Go to Token Faucet tab and press Get Token to add some tokens in the account. Confirm the transaction.

  1. Go back to Send Token tab, click Add Token and press Token Balance to see added tokens.
  2. Press Gas Limit and Max Priority Fee.
  3. Lastly, press Send to transfer tokens. Confirm the transaction.

  1. Check the transaction status and details by finding the account address or the generated transaction hash (Txn Hash) in Goerli Testnet Explorer.

You're done!

Congratulations! You have successfully achieved the goal of this Code Lab. Now, you can develop a decentralized application that can transfer ERC20 tokens using Samsung Blockchain Platform SDK. If you face any trouble, you may download this file:

Token Transaction Complete Code
(2.73 MB)

To learn more about developing apps with Samsung Blockchain, visit:
developer.samsung.com/blockchain