Quantcast
Jump to content


Recommended Posts

Posted

2021-04-20-01-banner.jpg

TRON is a well-known, blockchain-based, and decentralized platform that aims to create a global decentralized digital content system. By using blockchain technology, TRON has established a network between content creators and consumers, which eliminates the need for a middleman between these two parties.

Because TRON is an account-based blockchain system, a transaction in TRON is executed by an account and every transaction needs to pass the consensus process, which is known as DPoS. In this process, some witnesses are selected according to a vote to verify the transaction. Any token holder can vote to select these witnesses.

The Samsung Blockchain Platform (SBP) SDK provides an opportunity for Android developers to develop applications that can interact with Ethereum and TRON blockchain platforms. The SBP SDK supports coin transactions as well as smart contracts and tokens like TRC-10, TRC-20, and so on.

This blog describes the process of sending TRX (the base coin of the TRON platform) using the SBP SDK, with a sample application. For an example of sending Ether (the base coin of the Ethereum platform), see Send Ether with Samsung Blockchain Platform SDK.

Prerequisites

For developing a sample application that can perform TRX transactions, the following actions must be performed before the transaction takes place.

  1. Initialize the object
  2. Connect to a hardware wallet
  3. Get accounts

Each of these actions of the application has been implemented with a corresponding button so that the results of each action can be more visible and clearly illustrated.

Image 01

Initialize the object

To use the APIs of the SDK in an Android project, an object of the SDK is required. To create the object, follow the steps below.

  1. Create a new Android project and integrate the SBP SDK with the application. All dependencies need to be mentioned in the build.gradle file. To complete this step follow these instructions.
  2. After completing the synchronization of build.gradle with the file system, the project is ready for creating an instance of the Sblockchain class. Relevant source code can be found here.

Connect to a hardware wallet

A hardware wallet is a storage device with the facility of authentication for securely storing the public-private key pair. There are several hardware wallets in the market, and Samsung provides a hardware wallet integrated with select Samsung mobile devices, known as the Samsung Blockchain Keystore.

SBP provides an interface to connect hardware wallets. Alongside the Samsung Blockchain Keystore, SBP currently supports Ledger Nano X and Ledger Nano S. Connect your application with a hardware wallet using the following code.

In this article, the Samsung Blockchain Keystore has been used as the hardware wallet. While running the sample application on your device, please ensure you meet the device restrictions of the Samsung Blockchain Keystore. You can also change the hardware wallet type and test the same application with other supported hardware wallets.

Get accounts

An account is an important protocol of TRON. It functions as a gateway to interact with the TRON blockchain. Your TRX balance, token balance, bandwidth, energy, and so on are all attached to your account. TRX balance can be sent from one account to another. Moreover, an account can issue a smart contract. TRON accounts also provide the facility to vote for super representatives. To learn more about super representatives and voting, see the TRON documentation.

Every account consists of a private and public key pair. An account remains deactivated until a TRX or token transaction is performed. Creating an account consumes frozen bandwidth points. If none are available, then the action burns 0.1 TRX instead. If you want to know more about the underlying algorithm and the process of creating an account, see the TRON account documentation.

The SBP SDK allows you to create a new account or restore existing accounts from the TRON network. Restoring and creating accounts are network operations. For more information, see the account management guide for the SBP SDK. It discusses generating, restoring and fetching accounts using the SDK.

If you have no TRX in your account, you can get some by purchasing from the sites listed here or get test TRX.

2021-04-15-01-02.jpg2021-04-15-01-03.jpg

TRX Transaction

Let's send TRX from your account to another account. The SBP SDK provides an API called sendTransaction to perform a transaction between two accounts. This API needs four parameters.

  • wallet: A connected hardware wallet.
  • fromAccount: The sender’s TRON account.
  • toAddress: Where you want to transfer your TRX to, taking the address as a string.
  • value: How much TRX you want to transfer. Input unit is SUN (1 TRX= 10^6 SUN).

The CoinService class called TronService provides the sendTransaction API for transactions on the TRON platform. In addition, a Remote Procedure Call (RPC) is required to communicate with the TRON node. We are going to use TronGrid for this purpose, which allows developers to access a TRON client that is running on the cloud instead of creating one. You can learn more about the TronGrid here.

Before completing the example transaction, some terminology related to transactions, like bandwidth and energy, are discussed.

NetworkType networkType = TronNetworkType.SHASTA;

CoinType coinType = CoinType.TRX;

//Shasta rpc
String rpc = "https://api.shasta.trongrid.io";

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

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

Fetch TRX balance

TRX is the primary currency of TRON. It can be used to obtain Bandwidth, Energy, or Power. The SBP SDK provides the getBalance API for fetching the balance of an account.

public void onClickGetBalance(View view) {

    mCoinService = CoinServiceFactory.getCoinService(getApplicationContext(), mCoinNetworkInfo);
    TextView trxAmountTextView = findViewById(R.id.amount_tron);

    mCoinService.getBalance(mFirstAccount).setCallback(new ListenableFutureTask.Callback<BigInteger>() {
        @Override
        public void onSuccess(BigInteger bigInteger) {

            convertedAmount = TronUtils.convertSunToTrx(bigInteger);

            Log.i(LOG_TAG, "Balance has fetched successfully.");
            Log.i(LOG_TAG, "Balance is:" + convertedAmount.toString());
            runOnUiThread(() -> {
                    accountInfoButton.setEnabled(true);
                    trxAmountTextView.setText(convertedAmount.toString());
                }
            );
        }

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

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

Fetch bandwidth and energy

TRON implements some new and interesting features named freeze, bandwidth, and energy. You can freeze some of your TRX balance to gain bandwidth and energy. For every frozen TRX, the user receives 1 TRON power which is needed to cast a vote on super representatives. After freezing some of your TRX, it is not possible to use these TRX until they are unfrozen.

Bandwidth is used as a fee for TRX transactions. Energy is needed to execute smart contracts. The SBP SDK only provides an API to get a frozen balance amount. You can freeze TRX and gain bandwidth and energy using Tronscan. Tronscan is a blockchain explorer, which allows anyone to explore addresses, transactions, and tokens in the TRON blockchain.

The SBP SDK provides the getAccountInfo API for fetching bandwidth, energy and power (frozen balance) information. The input parameter is the account address of the sender. In the sample application, after pressing the Account Info button, the asynchronous task returns this information, which is set on a text view in the UI.

public void OnClickAccountInfo(View view) {
    tronService = (TronService) mCoinService;

    try {
        tronService.getAccountInfo(mFirstAccount.getAddress()).setCallback(new ListenableFutureTask.Callback<TronAccountInfo>() {
            @Override
            public void onSuccess(TronAccountInfo tronAccountInfo) {
                Log.i(LOG_TAG, "Account info is fetched successfully.");
                Log.i(LOG_TAG, "BandWidth is:" + tronAccountInfo.getBandwidth());
                Log.i(LOG_TAG, "Power is:" + tronAccountInfo.getFrozenBalance());
                runOnUiThread(() -> {
                        sendButton.setEnabled(true);
                          bandWidthTextView.setText(tronAccountInfo.getBandwidth().toString());
                        powerTextView.setText(tronAccountInfo.getFrozenBalance().toString());
                    }
                );
            }

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

            @Override
            public void onCancelled(@NotNull InterruptedException e) {
                Log.e(LOG_TAG, "Fetching account info is canceled.");
            }
        });
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error in fetching account info: " + e);
    }
}

After fetching bandwidth and energy, we can check them on the sample application UI.

Image 04

Transfer TRX

Now we have all the parameters needed for sending TRX. The sendTransaction API is used to transfer TRX to the recipient. If the transaction is successful, the onSuccess() callback returns the transaction hash.

Every transaction in the TRON blockchain can be found in Tronscan.

Image 05 Image 06
public void onClickSend(View view) {

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

        try {
            tronService.sendTransaction(mHardwareWallet, (TronAccount) mFirstAccount,
                    toAddress, convertedSendAmount).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);
        }
    }
}

Now that you can send TRX to another account, you can create your wallet application and implement a transfer function using the SBP SDK. Keep an eye on the Samsung Developers site for updates as the Samsung Blockchain keeps expanding support for new platforms.

Additional Resources:

Follow Up

This site has many resources for developers looking to build for and integrate with Samsung devices and services. Stay in touch with the latest news by creating a free account or by subscribing to our monthly newsletter. Visit the Marketing Resources page for information on promoting and distributing your apps. Finally, our developer forum is an excellent way to stay up-to-date on all things related to the Galaxy ecosystem.

View the full blog at its source



  • 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...
  • Similar Topics

    • By Samsung Newsroom
      View the full blog at its source
    • By Samsung Newsroom
      Whether you are an enthusiast or veteran TRON developer, Samsung is here to help your decentralized application (Dapp) reach more people. By using the features in the Samsung Blockchain Platform SDK, you can enable millions of users to access your Dapp on their Samsung Galaxy devices. In a few easy steps, this article demonstrates how to make a simple Android application that can integrate with an existing Web Dapp.
      Start by using the Samsung Blockchain Platform SDK to connect to a hardware wallet. Next, use the account manager to retrieve the user’s TRON account. Finally, display the Web Dapp using Cucumber WebView and enable it to send and receive payments.
      Let’s get started!
      Initialize Samsung Blockchain Platform SDK
      Before using the Samsung Blockchain Platform SDK, include the required supporting libraries. To learn more about the prerequisite libraries and supported hardware wallets, refer to the Samsung Blockchain Platform SDK Getting Started guide.
      To begin, initialize the Samsung Blockchain Platform SDK for your application. The SBlockchain object enables you to use the Samsung Blockchain Platform SDK features.
      try { mSBlockchain = new SBlockchain(); mSBlockchain.initialize(this); } catch (SsdkUnsupportedException e) { handlePlatformSDKUnsupportedError(e); } Connect to a hardware wallet
      Many Samsung Galaxy devices, such as the Galaxy Note10 and S20, already have a hardware wallet available: the Samsung Blockchain Keystore. You will connect to it in this demonstration. However, you can adapt the following code to connect to other supported hardware wallets, such as the Ledger Nano X, simply by changing the hardware wallet type.
      private HardwareWallet connectedHardwareWallet; ListenableFutureTask<HardwareWallet> connectionTask = mSBlockchain.getHardwareWalletManager().connect(HardwareWalletType.SAMSUNG, true); connectionTask.setCallback(new ListenableFutureTask.Callback<HardwareWallet>() { @Override public void onSuccess(HardwareWallet hardwareWallet) { connectedHardwareWallet = hardwareWallet; setupAccounts(connectedHardwareWallet); } @Override public void onFailure(ExecutionException e) { Log.e(LOG_TAG, "Connecting to Hardware Wallet failed."); Log.e(LOG_TAG, e.getMessage()); } @Override public void onCancelled(InterruptedException e) { Log.e(LOG_TAG, "Connecting to Hardware Wallet cancelled."); Log.e(LOG_TAG, e.getMessage()); } }); Once successfully connected to the hardware wallet, you can retrieve the accounts associated with it.
      Retrieve TRON accounts
      The Samsung Blockchain Platform account manager can retrieve the list of accounts associated with the hardware wallet.
      AccountManager accountManager = mSBlockchain.getAccountManager(); List<Account> accountList = accountManager.getAccounts(connectedWallet.getWalletId(), COIN_NETWORK_INFO.getCoinType(), COIN_NETWORK_INFO.getNetworkType()); To retrieve the account list, specify the wallet ID from the connected hardware wallet, the coin type (cryptocurrency), and the desired network type, such as MAINNET or SHASTA_TESTNET. In this case, the cryptocurrency is TRON.
      If the account list is empty, the account manager can generate a new account, based on the connected hardware wallet and the specified cryptocurrency and network.
      accountManager.generateNewAccount(connectedWallet, COIN_NETWORK_INFO).setCallback(new ListenableFutureTask.Callback<Account>() { @Override public void onSuccess(Account newAccount) { defaultAccount = newAccount; Log.d(LOG_TAG, "Account fetched."); } After the account is retrieved, you can proceed to loading the Web Dapp using Cucumber WebView.
      Initialize Cucumber WebView
      The next step is to prepare the Cucumber WebView and enable it to make transactions through the Dapp.
      dAppWebView = findViewById(R.id.dapp_web_view); dAppWebView.addCoinServiceConnector(COIN_NETWORK_INFO.getCoinType(), tronCoinService, defaultAccount, transactionListener); To communicate with the TRON blockchain network, use the CoinService interface of the Samsung Blockchain Platform. The coin service enables you to retrieve the information needed for the transaction, and also uploads the signed transaction to the blockchain network.
      Browser-based Web Dapps built using the TronWeb library typically use TronLink as their TRON Web provider. In your mobile application, Cucumber WebView acts as the TRON Web provider and forwards the TRON Web Javascript-prepared transaction to the BaseOnSendTransactionListener event handler, which handles the transaction created by the Web Dapp.
      After preparing the transaction, a payment intent powered by the Samsung Blockchain Platform SDK can be launched, which provides an interactive UI with the transaction details.
      CoinService tronCoinService = CoinServiceFactory.getCoinService(MainActivity.this, COIN_NETWORK_INFO); BaseOnSendTransactionListener transactionListener = new OnSendTronTransactionListener() { @Override public void onSendTransaction(@NotNull String requestID, @NotNull TronPaymentType tronPaymentType, @NotNull TronAccount fromAccount, @NotNull String toAddress, @org.jetbrains.annotations.Nullable BigInteger productPrice, @org.jetbrains.annotations.Nullable String tokenID, @org.jetbrains.annotations.Nullable BigInteger tokenValue, @org.jetbrains.annotations.Nullable String data, @org.jetbrains.annotations.Nullable BigInteger feeLimit) { //Write code for what happens when transaction is sent Intent paymentIntent = dAppWebView.createTronPaymentSheetActivityIntent( MainActivity.this, requestID, connectedHardwareWallet, fromAccount, toAddress, productPrice); MainActivity.this.startActivityForResult(paymentIntent, 0); } }; dAppWebView.addCoinServiceConnector(COIN_NETWORK_INFO.getCoinType(), tronCoinService, defaultAccount, transactionListener); Your Cucumber WebView (dAppWebView) is now ready to load the Web Dapp using its URL.
      dAppWebView.loadUrl("https://www.example.com"); When the marketplace has loaded, the Samsung Blockchain Platform prompts the user to allow the Dapp to connect to their hardware wallet.
      The Samsung Blockchain Platform’s payment intent UI enables the user to easily purchase items from the marketplace.
      Bonus: display transaction ID
      In addition to enabling users to sign in and send a transaction with your Dapp, the Samsung Blockchain Platform SDK can also retrieve the transaction ID.
      The payment intent returns the transaction information, which can be parsed using the onActivityResult method, if desired.
      @Override protected void onActivityResult( int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 0 && data != null) { dAppWebView.onActivityResult(requestCode, resultCode, data); switch (resultCode) { case Activity.RESULT_OK: String transactionID = data.getStringExtra("txid"); Log.d(LOG_TAG, "TransactionId : " + transactionID); showAlertDialog("Transaction Successful with Id : " + transactionID); break; case Activity.RESULT_CANCELED: Log.d(LOG_TAG, "Transaction canceled by user."); break; default: Log.d(LOG_TAG, "Unknown Activity Result Code. Result Code: " + resultCode); } } } Conclusion
      With the Samsung Blockchain Platform SDK, your Dapp is no longer confined to PCs. Both new and existing users can have your Dapp at their fingertips on Samsung Galaxy devices. It’s also easy to add support for new crypto-currencies and hardware wallets to your Dapp; the Samsung Blockchain Platform has you covered. Submit your application to the Samsung Galaxy Store and reach millions of new users today!
      Additional Resources
      Download the Samsung Blockchain Platform SDK Example App
      More information on Samsung Blockchain Platform SDK
      View the full blog at its source





×
×
  • Create New...