Send Ether with Samsung Blockchain Platform SDK

M.A. Hasan Molla

Engineer, Samsung Developer Program

Blockchain, an emerging technology, is a distributed database for storing and managing records of transactions. It has already created a huge impact in the financial sector.

The transaction is the main feature in any blockchain-based system. In Ethereum, one of the better-known blockchain systems, every transaction is executed by either an account or a smart contract. When an account tries to execute a transaction, it creates one and publishes it in the Ethereum blockchain. Every transaction needs to pass the consensus process. Some nodes in the Ethereum blockchain, known as miners, validate and authenticate the transaction. “Gas” is an incentive that is paid out for executing transactions. On the Ethereum platform, gas is paid to miners for completing the consensus process.

The Samsung Blockchain Platform SDK enables Android developers to develop applications that interact with the Etherum blockchain platform. In addition to transactions, the Samsung Blockchain Platform SDK also supports operations related to smart contracts and tokens.

Through a sample application, this blog describes how to use the Samsung Blockchain Platform SDK to transfer Ether, which is the base coin for the Ethereum platform.

Prerequisites

Before the application can make a transaction, it must first perform the following actions in order:

  1. Initialize and create the instance
  2. Connect to the hardware wallet
  3. Get the account

Let’s associate each of these actions with a button in our sample application.


1. Initialize and create the instance
In the Android project, integrate the Samsung Blockchain Platform SDK with the application and mention all the dependencies in build.gradle. Next, create an instance of the Sblockchain class.

2. Connect to the hardware wallet
The Samsung Blockchain Platform provides an interface to connect to hardware wallets, which are special devices that securely store private keys. Samsung mobile devices have an integrated hardware wallet, the Samsung Blockchain Keystore. Besides the Samsung Blockchain Keystore, the Samsung Blockchain Platform also supports USB-connected Ledger devices and BLE-connected Nano X devices.

The sample application connects to the Samsung Blockchain Keystore hardware wallet. Before you run the sample application on your device, check that the device is supported. You can also modify the sample application and test it with other supported hardware wallets.

3. Get the account
An account is a gateway for interacting with the Ethereum blockchain. Each account consists of a private and public key pair, for which the shortened public key is the account address. Every initial action in the Ethereum blockchain must be initiated by an account.

The Samsung Blockchain Platform SDK enables the user to create a new account or to restore their accounts from the Ethereum network. Account management features in the Samsung Blockchain Platform SDK include generating, restoring and fetching accounts. Because they are network operations, the create account and restore accounts operations must perform asynchronously.

After creating a new account, the user must utilize the account to receive or send Ether before the Samsung Blockchain Platform SDK allows them to create another account.

If you do not have any Ether to use with the sample application, you can use test Ether.


Performing Ether Transactions

The sendTransaction API of the Samsung Blockchain Platform SDK initiates a transaction between two accounts. It requires the following information in its parameters:

  • wallet: connected hardware wallet
  • fromAccount: sender’s Ethereum account address
  • gasPrice: price of each gas unit, which defines how quickly someone wants to execute the transaction
  • gasLimit: maximum number of gas units to spend on the transaction
  • toAddress: recipient’s Ethereum account address
  • value: amount of Ethereum to transfer, in wei (1 eth = 10^18 wei).
  • nonce: transaction counter for the account.

The CoinService class named EthereumService provides methods needed to create transactions on the Ethereum platform. For example, the getFeeInfo() and estimateGasLimit() methods can retrieve the values for use with the gasPrice and gasLimit parameters, respectively.

To communicate with the Ethereum node, RPC is also needed. In the sample application, the Infura node is used to access the Ethereum blockchain. Learn about integrating the Infura API with the JSON RPC.

CoinType coinType = CoinType.ETH;
 
NetworkType networkType = (NetworkType) EthereumNetworkType.ROPSTEN;
//might use your own rpc
String rpc = "https://ropsten.infura.io/v3/71cf9f88c5b54962a394d80890e41d5b";

// creating coinNetworkInfo
CoinNetworkInfo mCoinNetworkInfo = new CoinNetworkInfo(coinType, networkType, rpc);

//Creating CoinService
CoinService  mCoinService = CoinServiceFactory.getCoinService
                                          (getApplicationContext(), mCoinNetworkInfo);

//Creating EthereumService
EthereumService ethereumService = (EthereumService) mCoinService;

//Access TextView and EditTexts on UI
private RadioGroup transactionSpeedGroup =      findViewById(R.id.transaction_speed_radio_group);

private TextView gasLimitText = findViewById(R.id.gas_limit_text_view);
private EditText toAddressEditText = findViewById(R.id.to_address);
private EditText sendAmountEditText = findViewById(R.id.send_amount);

Retrieve the gas price

Gas price retrieval is an asynchronous task. Use the getFeeInfo API to retrieve the gas price. The getFeeInfo API returns three gas prices which depend on the speed of the transaction: fast, normal, and slow.

To give full control over the gas price for advanced users, you can also enable numerical price input.

In the sample application, when the user selects Gas Price, an asynchronous task retrieves the three gas prices, and assigns them to radio buttons. The user can select the transaction speed they want based on the gas price.

public void OnClickGasPrice(View view) {

    ethereumService = (EthereumService) mCoinService;

    ethereumService.getFeeInfo().setCallback(new ListenableFutureTask.Callback<EthereumFeeInfo>() {
        @Override
        public void onSuccess(EthereumFeeInfo ethereumFeeInfo) {
            convertedAmount = EthereumUtils.convertWeiToGwei(ethereumFeeInfo.getNormal());
            Log.i(LOG_TAG, "Fee info is fetched successfully.");
            mEthereumFeeInfo = ethereumFeeInfo;
            runOnUiThread(() -> {
                        gasLimitButton.setEnabled(true);
                        Toast.makeText(getApplicationContext(), "Fee info is fetched successfully.", Toast.LENGTH_SHORT).show();
                    }
            );
        }

        @Override
        public void onFailure(@NotNull ExecutionException e) {
            Log.e(LOG_TAG, "Fetching Fee info is failed.");
            Log.e(LOG_TAG, "" + e.getMessage());
        }

        @Override
        public void onCancelled(@NotNull InterruptedException e) {
            Log.e(LOG_TAG, "Fetching Fee info is canceled.");
        }
    });
}

Fetching the gas limit

Fetching the gas limit is also an asynchronous task. Use the estimateGasLimit API to calculate the gas limit. The input parameters are the account addresses of the sender and the receiver, the amount of Ether (in wei units), and the data to be sent.

The sample application sends only Ether, so the data field is null. When the user selects Gas Limit, the gas limit is determined and shown on the screen.

public void onClickGasLimit(View view) {

    String toAddress = toAddressEditText.getText().toString();
    String amount = sendAmountEditText.getText().toString();

    if (toAddress.isEmpty() || amount.isEmpty()) {
        Toast.makeText(getApplicationContext(), "Fill Send Address and Amount Field", Toast.LENGTH_SHORT).show();
    } else if(!ethereumService.isValidAddress(toAddress)){
        Toast.makeText(getApplicationContext(), "Invalid Address.", Toast.LENGTH_SHORT).show();
    } else {
        BigDecimal sendAmount = new BigDecimal(amount);
        BigInteger convertedSendAmount = EthereumUtils.convertEthToWei(sendAmount);

        ethereumService.estimateGasLimit((EthereumAccount) mFirstAccount, toAddress, convertedSendAmount, null).setCallback(new ListenableFutureTask.Callback<BigInteger>() {
            @Override
            public void onSuccess(BigInteger bigInteger) {
                mGasLimit = bigInteger;
                Log.i(LOG_TAG, "Gas limit is fetched successfully.");
                Log.i(LOG_TAG, "Gas limit is:" + bigInteger.toString());
                runOnUiThread(() -> {
                    sendButton.setEnabled(true);
                    gasLimitText.setText(bigInteger.toString());
                });
            }

            @Override
            public void onFailure(@NotNull ExecutionException e) {
                Log.e(LOG_TAG, "Fetching Gas limit is failed.");
                Log.e(LOG_TAG, "" + e.getMessage());
            }

            @Override
            public void onCancelled(@NotNull InterruptedException e) {
                Log.e(LOG_TAG, "Fetching Gas limit is canceled.");
            }
        });
    }
}

Send the Ether

All the parameter values needed to send the Ether are now known. Use the sendTransaction API to initiate the transaction.

In the sample application, the value of the nonce parameter has not been set manually. By leaving the value null, the platform handles the nonce value itself. If the transaction is successful, the onSuccess() event handler returns the transaction hash.

A record of every Ethereum transaction is viewable in Etherscan, a blockchain explorer. It allows anyone to explore addresses, transactions, and tokens in the Ethereum blockchain.

public void onClickSend(View view) {

    String toAddress = toAddressEditText.getText().toString();
    BigDecimal sendAmount = new BigDecimal(sendAmountEditText.getText().toString());
    BigInteger convertedSendAmount = EthereumUtils.convertEthToWei(sendAmount);

    //Getting Gas Price
    int transactionSpeedID = transactionSpeedGroup.getCheckedRadioButtonId();
    if (transactionSpeedID == -1) {
        Toast.makeText(getApplicationContext(), "Select a Transaction Speed.", Toast.LENGTH_SHORT).show();
    } else {
        switch (transactionSpeedID) {
            case R.id.transaction_speed_slow:
                mGasPrice = mEthereumFeeInfo.getSlow();
                Log.d(LOG_TAG, "GasPrice: " + mGasPrice);
                break;
            case R.id.transaction_speed_normal:
                mGasPrice = mEthereumFeeInfo.getNormal();
                Log.d(LOG_TAG, "GasPrice: " + mGasPrice);
                break;
            case R.id.transaction_speed_fast:
                mGasPrice = mEthereumFeeInfo.getFast();
                Log.d(LOG_TAG, "GasPrice: " + mGasPrice);
                break;
        }
    }

    if(transactionSpeedID != -1) {
        try {
            ethereumService.sendTransaction(mHardwareWallet, (EthereumAccount) mFirstAccount, mGasPrice
                    , mGasLimit, toAddress, convertedSendAmount, null).setCallback(new ListenableFutureTask.Callback<TransactionResult>() {
                @Override
                public void onSuccess(TransactionResult transactionResult) {
                    Log.d(LOG_TAG, "Transaction Hash: " + transactionResult.getHash());
                    runOnUiThread(() ->
                            Toast.makeText(getApplicationContext(), "Transaction Hash: " + transactionResult.getHash(), Toast.LENGTH_SHORT).show()
                    );
                }

                @Override
                public void onFailure(@NotNull ExecutionException e) {
                    Log.e(LOG_TAG, "Transaction failed.");
                    Log.e(LOG_TAG, "" + e.getMessage());
                }

                @Override
                public void onCancelled(@NotNull InterruptedException e) {
                    Log.e(LOG_TAG, "Transaction canceled.");
                }
            });
        } catch (AvailabilityException e) {
            Log.e(LOG_TAG, "Error in sending: " + e);
        }
    }
}

Conclusion

This blog has demonstrated how you can send Ether to another account, an example of a feature you can implement in a wallet application using the Samsung Blockchain Platform SDK.

Check the Samsung Developers site periodically for updates as Samsung Blockchain Platform SDK keeps expanding support for new platforms.

Additional Resources:

Preferences Submitted

You have successfully updated your cookie preferences.