Quantcast
Jump to content

Send Ether with Samsung Blockchain Platform SDK


STF News
 Share

Recommended Posts

2020-09-17-01-banner.jpg

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.


2020-09-17-01-01.jpg?width=350px

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.


2020-09-17-01-02.jpg?width=350px 2020-09-17-01-03.jpg?width=350px

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.");
            }
        });
    }
}

2020-09-17-01-04.jpg?width=350px 2020-09-17-01-05.jpg?width=350px

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:

View the full blog at its source

Link to comment
Share on other sites

  • Replies 0
  • Created
  • Last Reply

Top Posters In This Topic

Popular Days

Top Posters In This Topic

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Similar Topics

    • By STF News
      We celebrate the year's top performing apps in creativity, quality, design, and innovation at our Best of Galaxy Store Awards. Next in our blog series, we feature Sonic Forces, winner of Best Adventure Game.
      Gabor Gyarmati, Product Manager at Sonic Forces, speaks to us about how he got started in game development, the challenges the team faced developing Sonic Forces, and tips for games that stand out from the crowd. Check out Gabor’s advice on developing games to help you on your way to becoming a Best of Galaxy Store Awards 2020 winner.
      How did you get your start developing games?
      I initially got into developing games through following my brother’s game development company making strategy games for Amiga and PC almost 30 years ago. The next step came after I finished my studies, when I co-founded a development studio with my brother back in Hungary. Later on, I joined the online gaming space and spent the last 12 years developing free to play games for various PC, console, and mobile platforms.
      Please tell us about Sonic Forces: Speed Battle.
      Sonic Forces is a super-fast paced, multiplayer runner game. Players collect their favourite characters from the Sonic universe and dash through the tracks jumping and dodging obstacles, enemies, and traps. Players compete against up to 3 other players from around the world in a single-speed battle. Sonic Forces includes regular content and feature updates. The game runs an ever-changing live event schedule that offers something new and exciting such as themed events, special characters, and more. Oh, and this is all available to play for free.
      What was the development process like for Sonic Forces? What were the biggest challenges you faced?
      Sonic Forces started off with a very small team focused on making a prototype that would prove whether the game could work from a technical perspective and whether we could make it fun. We succeeded in proving this pretty quickly. Then it became a question of making sure that we kept what made the prototype fun as we built it out into a full game. We also developed good tools very early on that allowed us to rapidly build and test tracks, which was a big help when it came to development and iteration.
      In terms of challenges, one of the biggest is always keeping the game balanced. Since Sonic Forces is a true competitive, multiplayer game, we spend a lot of time and focus facilitating an ongoing, iterative cycle to keep the game fair for all players. This includes tweaking the stats of characters, their powers, the tracks, etc. and feedback from our player community is incredibly valuable in this respect.
      What do you think has made Sonic Forces such a successful game?
      I think that there are several components that have contributed to Sonic Forces’ success. As a Sonic game, the characters, the environments, the music, and the core gameplay certainly resonate with the Sonic The Hedgehog fanbase. However, Sonic Forces also has a unique competitive multiplayer element that provides a short and sweet adrenaline boost, which is a great match for the playstyle of casual, competitive, mobile players. On top of this, Sonic Forces runs a lot of attractive live events and new content updates, which has helped to drive a very loyal and engaged player base to keep returning to the game for over 2 years now.
      What is the most important thing to consider when building games for Samsung?
      The most important thing is a strong focus on delivering regular high-quality updates, features, events, and new content. This can help Samsung as a platform provider showcase quality games that are popular with their community, while also helping keep players engaged over the long term.
      How do you create games that stand out from the crowd?
      We have a very talented team that comes from a variety of different development backgrounds across handheld, console, and PC platforms. The team has many years of experience in mobile games with live operations. We utilize our cumulative experience, from both our successes and challenges along the way, and this has enabled us to create new and exciting gameplay that’s based on solid learnings.

      When designing a game, what is the most important UX consideration?
      The most important UX consideration, for me, is to keep the core gameplay easy and fun, especially if you are developing a game that will be played by a younger audience on a mobile platform. I have a young son and I like to see him start and play the games without needing any instructions. If the game passes this test, I know players will be able to play it intuitively.
      What guidance do you have for new developers looking to develop successful games?
      My advice is to do thorough research before starting any development, know who the game’s audience will be, and design a fun experience that can be scaled and expanded over time. Have your ideas, prototypes, and later versions tested by friends, and then by actual players in order to get valuable early feedback. If you plan to develop a free-to-play game, make sure to plan ahead for delivering a long-lasting experience and develop tools that will allow you to grow and maintain live operations in the future.
      How do you think game development will change in the next few years? Are there emerging technologies you are keeping an eye on?
      With the arrival of super-fast internet, cloud gaming, and rapidly growing hardware capabilities, the mobile market is transforming to become the most versatile platform for gaming. This brings a lot of potential and new opportunities for big IP games that previously only appeared on consoles to thrive on mobile platforms.
      How has working with Samsung helped your business?
      Working with Samsung continues to be a great experience for our studio. We’ve found the Samsung editorial team to be very easy to work with, and their continuous support has made it possible for Sonic Forces to receive great exposure on Galaxy Store. This helps not only to drive an increase in new installs, but we’ve also found that the players discovering Sonic Forces through Samsung’s platform tend to be very engaged in and committed to the game. We love seeing how they interact with the gameplay and contribute to the growing Sonic Forces community.
      Thanks to Gabor Gyarmati of Sonic Forces for sharing his insights on how to develop successful games and emerging opportunities to watch for in the next few years. Follow @samsung_dev on Twitter for more developer interviews and tips for building games, apps, and more for the Galaxy Store. Find out more about our Best of Galaxy Store Awards.
      View the full blog at its source

×
×
  • Create New...