Mastering TON Blockchain Transaction Sending: Building Interactive React Apps with TonConnect Integration Tutorial

In this comprehensive tutorial, we will delve deep into the process of sending TON transactions using a React component named TxForm, which is facilitated by the @tonconnect/ui-react library. The objective is to create a seamless experience for users to interact with the TON blockchain by utilizing a straightforward “EchoContract” that echoes the sent amount back to the sender. This feature is particularly useful for testing purposes, as it eliminates the risk of accidental spending on the blockchain.

Prerequisites

Before we embark on this journey, it is essential to ensure that your development environment is properly set up with the following dependencies:

  • React: The core library for building user interfaces.
  • @tonconnect/ui-react: This package is pivotal for connecting and managing TON wallets within your application.
  • @ton/ton: A crucial library for interacting with the TON blockchain, providing a suite of functions to handle transactions and smart contracts.
  • react-json-view: A user-friendly component that allows for the editing of JSON data directly within the interface.

Code Explanation

Let’s dissect the code of the TxForm component, breaking down each segment for a clearer understanding.

Importing Dependencies

We begin by importing the necessary hooks and components from React, as well as the required functions and types from the @tonconnect/ui-react and @ton/ton libraries. This sets the stage for the component’s functionality.

import { useCallback, useState } from "react";
import ReactJson, { InteractionProps } from "react-json-view";
import "./style.scss";
import {
  SendTransactionRequest,
  useTonConnectUI,
  useTonWallet,
} from "@tonconnect/ui-react";
import {
  Address,
  beginCell,
  Cell,
  loadMessage,
  storeMessage,
  Transaction,
} from "@ton/core";
import { useTonClient } from "../../hooks/useTonClient";
import { TonClient } from "@ton/ton";

Default Transaction Object

The defaultTx object serves as a template for transactions, containing all the necessary information such as the validity period, recipient address, amount, and payload. This simplifies the process of creating new transactions.

const defaultTx: SendTransactionRequest = {
  // ... (specific content omitted)
};

Function to Wait for Transaction Completion

The waitForTransaction function is an asynchronous operation that polls the blockchain until the transaction is confirmed. It accepts transaction options and a TON client instance, returning the completed transaction details or null if the transaction fails.

const waitForTransaction = async (
  options: WaitForTransactionOptions,
  client: TonClient
): Promise<Transaction | null> => {
  // ... (specific content omitted)
};

TxForm Component

The TxForm component is the heart of our transaction interface, providing the structure and logic for users to configure and send transactions.

export function TxForm() {
  // ... (specific content omitted)
}

State Definition

Within the TxForm component, we define several pieces of state to track the transaction’s progress and outcome. This includes the transaction object, the finalized transaction, the message hash, and a loading indicator.

const [tx, setTx] = useState(defaultTx);
const [finalizedTx, setFinalizedTx] = useState<Transaction | null>(null);
const [msgHash, setMsgHash] = useState<string>("");
const [loading, setLoading] = useState<boolean>(false);
const { client } = useTonClient();
const wallet = useTonWallet();
const [tonConnectUi] = useTonConnectUI();

Handling JSON Editing

The onChange callback function is triggered whenever changes are made within the react-json-view component. It updates the transaction state with the new values, allowing for real-time editing of transaction parameters.

const onChange = useCallback((value: InteractionProps) => {
  setTx(value.updated_src as SendTransactionRequest);
}, []);

Send Transaction Button

The send transaction button is a critical component that initiates the transaction process. It triggers the tonConnectUi.sendTransaction method and handles the loading state to provide feedback to the user.

<button
  // ... (specific content omitted)
>
  {loading ? "Loading..." : "Send transaction"}
</button>

Full Code

The complete code for the TxForm component is as follows. It integrates all the previously discussed elements into a cohesive interface that allows users to configure and send transactions.

export function TxForm() {
  // ... (specific content omitted)
  return (
    <div className="send-tx-form">
      <h3>Configure and send transaction</h3>
      <ReactJson
        theme="ocean"
        src={defaultTx}
        onEdit={onChange}
        onAdd={onChange}
        onDelete={onChange}
      />
      {wallet ? (
        <button
          // ... (specific content omitted)
          onClick={async () => {
            setLoading(true);
            const txHash = await tonConnectUi.sendTransaction(tx);
            setMsgHash(txHash);
            const completedTx = await waitForTransaction({ hash: txHash }, client);
            setFinalizedTx(completedTx);
            setLoading(false);
          }}
        >
          {loading ? "Loading..." : "Send transaction"}
        </button>
      ) : (
        <button onClick={() => tonConnectUi.openModal()}>
          Connect wallet to send the transaction
        </button>
      )}
      <div>Sending Tx Message Hash: {msgHash}</div>
      <div>Sending Tx Hash: {finalizedTx?.hash().toString("hex")}</div>
    </div>
  );
}

Summary

This tutorial has guided you through the process of creating a simple yet effective transaction form using React and the @tonconnect/ui-react library. The TxForm component serves as a user-friendly interface for configuring transaction details, connecting a wallet, and dispatching transactions to the TON blockchain. By following the steps outlined, users can interact with the TON blockchain in a controlled and secure manner.

Key Steps Review

1. Setting Up Default Transaction Information

The defaultTx object is a blueprint for transactions, providing a starting point with pre-filled information that can be edited by the user. This setup ensures that all necessary transaction details are accounted for before any interaction with the blockchain occurs.

2. Creating a Function to Wait for Transaction Completion

The waitForTransaction function is a vital tool for ensuring that the application can confirm the completion of a transaction. It abstracts the complexities of blockchain polling and provides a straightforward way to obtain the final transaction details.

3. Creating the React Component

The TxForm component is the central piece of our application. It leverages React’s state management and effect hooks to create a dynamic and responsive interface for sending transactions.

4. Implementing Transaction Editing Features

By incorporating the react-json-view component, we empower users to edit transaction details in real-time. The onChange callback ensures that any modifications are immediately reflected in the component’s state.

5. Sending the Transaction

The transaction sending process is initiated by the user through the “Send transaction” button. Behind the scenes, the component uses the tonConnectUi.sendTransaction method to broadcast the transaction and the waitForTransaction function to await its confirmation.

6. Displaying Transaction Information

Once a transaction is sent, the component updates the interface to display the message hash and the transaction hash. This information is crucial for users to track the status of their transactions on the blockchain.

Expansion Suggestions

  • Error Handling: To enhance the robustness of the application, implement comprehensive error handling to catch and display any issues that may arise during the transaction process.
  • User Feedback: Improve the user experience by providing more immediate and informative feedback. Modal pop-ups or inline notifications can inform users of the transaction’s progress and outcome.
  • Security: Safeguard the handling of transaction details to prevent sensitive information from being exposed. Implement best practices for security in client-side applications.
  • Feature Expansion: Extend the application’s capabilities by adding features such as balance querying, transaction history viewing, and more complex interactions with smart contracts.

Conclusion

Through this tutorial, you have gained insights into how to utilize React and the @tonconnect/ui-react library to construct a basic interface for sending TON transactions. This knowledge paves the way for further exploration of the TON blockchain and the development of more sophisticated decentralized applications (dApps). As you continue to learn and practice, you will be equipped to build richer and more powerful applications that leverage the capabilities of the TON blockchain.