Skip to content

Integrating TON Kotlin with Java projects

Andrey Pfau edited this page Apr 12, 2023 · 1 revision

Simple application using the TON Kotlin SDK


Example: https://github.com/MrKamenAdmin/getBalance-TonBlockchain

Dependencies of the application

To run the application, we will need 2 dependencies:

Maven

To add dependencies to the pom.xml file:

<dependencies>
    <dependency>
        <groupId>org.ton</groupId>
        <artifactId>ton-kotlin-jvm</artifactId>
        <version>0.3.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-stdlib-jdk8</artifactId>
        <version>1.8.20</version>
    </dependency>
</dependencies>

Gradle

To add dependencies to the build.gradle file:

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.ton:ton-kotlin-jvm:0.3.0'
}

Application

Let's implement an example application that retrieves the balance of an account by wallet number.

Getting the JSON configuration

For the library to work, you need to get a configuration from the ton.org website.

public static String getJson() {
        try {
            String urlString = "https://ton.org/global-config.json";
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String inputLine;
            while ((inputLine = bufferedReader.readLine()) != null) {
                response.append(inputLine);
            }
            bufferedReader.close();
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
}

Note: The configuration is static, it is sufficient to load it during the first launch of the application.

Using suspend methods in a Java application.

To call them from Java, let's write a method.

public static <T> Future<T> callSuspend(Function<Continuation<? super T>, Object> continuation) {
    Deferred<T> async = BuildersKt.async(
            GlobalScope.INSTANCE,
            GlobalScope.INSTANCE.getCoroutineContext(),
            CoroutineStart.DEFAULT,
            ((coroutineScope, continuation1) -> continuation.apply(continuation1)
        );
            return FutureKt.asCompletableFuture(async);
}

Initialize a LiteClientConfigGlobal

Initialize a LiteClientConfigGlobal configuration to create the LiteClient object that sends requests to the TonBlockchain servers.

Json json = JsonKt.Json(Json.Default, (builder) -> {
    builder.setIgnoreUnknownKeys(true);
    return Unit.INSTANCE;
});

LiteClientConfigGlobal liteClientConfigGlobal = json.decodeFromString(
        LiteClientConfigGlobal.Companion.serializer(),
        Objects.requireNonNull(getJson())
        );

Note: create a JSON deserializer and then deserialize the received configuration into LiteClientConfigGlobal.

Getting the balance by wallet address

try (LiteClient liteClient = new LiteClient(context, liteClientConfigGlobal)) {
    String address = "EQDhfNEHdK06MNRjGyx5h0Pao5NgqFTE8ug2SrZ14c6bJnJF";
    AddrStd addrStd = AddrStd.parse(address);

    Future<FullAccountState> future = callSuspend((c) -> liteClient.getAccountState(addrStd, c));
    FullAccountState fullAccountState = future.get();
    Account account = fullAccountState.account().getValue();

    if (account instanceof AccountInfo) {
        String balance = ((AccountInfo) account).storage().balance().coins().toString();
        System.out.println(balance);
    }
} catch (Exception e) {
    e.printStackTrace();
}

Note: The LiteClient implements the Closeable interface, so we should use the try-with-resources construct.

Note: Account can be one of two types: AccountNone and AccountInfo. AccountNone - case we are trying to get an account that has not been created. AccountInfo - case we are trying to get a created account.