diff --git a/.github/workflows/release-artifacts.yml b/.github/workflows/release-artifacts.yml index 5a9a05f3b..8f06b545f 100644 --- a/.github/workflows/release-artifacts.yml +++ b/.github/workflows/release-artifacts.yml @@ -129,4 +129,4 @@ jobs: env: NEXUS_USERNAME: ${{ secrets.SONATYPE_USERNAME }} NEXUS_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} - run: ./gradlew releaseMavenCentral -PpublishingPackageGroup=org.hiero -PpublishSigningEnabled=true --scan --no-configuration-cache + run: ./gradlew releaseMavenCentral -PpublishingPackageGroup=org.hiero.sdk -PpublishSigningEnabled=true --scan --no-configuration-cache diff --git a/.gitignore b/.gitignore index be8eecb16..22fa8f6f0 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,4 @@ bin/ gradle.properties .DS_Store /examples/address-book.proto.bin +local.properties diff --git a/LICENSE b/LICENSE index 1b207f927..355e364b4 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2020 Hedera Hashgraph LLC + Copyright 2024 Hiero LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README.md b/README.md index 3edd6cb15..85433ce1b 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,13 @@ -# Hedera™ Hashgraph Java SDK +# Hiero Java SDK ![](https://img.shields.io/badge/java-17%2B-blue?style=flat-square) ![](https://img.shields.io/badge/android-26%2B-blue?style=flat-square) [![](https://img.shields.io/github/actions/workflow/status/hashgraph/hedera-sdk-java/build.yml?style=flat-square)](https://github.com/hashgraph/hedera-sdk-java/actions) [![](https://img.shields.io/maven-central/v/com.hedera.hashgraph/sdk/2?label=maven&style=flat-square)](https://search.maven.org/artifact/com.hedera.hashgraph/sdk) -> The Java SDK for interacting with Hedera Hashgraph: the official distributed +> The Java SDK for interacting with Hiero: the official distributed > consensus platform built using the hashgraph consensus algorithm for fast, -> fair and secure transactions. Hedera enables and empowers developers to +> fair and secure transactions. Hiero enables and empowers developers to > build an entirely new class of decentralized applications. **NOTE**: v1 of the SDK is deprecated and support was discontinued after October 2021. @@ -15,35 +15,43 @@ Please install the latest version 2.x.x or migrate from v1 to the latest 2.x.x v You can reference the [migration documentation](docs/sdk/MIGRATING_V1.md). ## Java app quickstart + [The Java application quickstart guide](docs/java-app/java-app-quickstart.md) covers how to properly set up the dependencies -needed to start developing your Java project using the Hedera™ Java SDK. +needed to start developing your Java project using the Hiero Java SDK. ## Android app quickstart + [The Android application quickstart guide](docs/android-app/android-app-quickstart.md) covers how to properly set up the dependencies -needed to start developing your Android project using the Hedera™ Java SDK. +needed to start developing your Android project using the Hiero Java SDK. ## Examples + This repository includes [Java examples](examples/README.md) and [an Android example](example-android/README.md) that showcase different use cases and workflows. ## Developer quickstart + The [developer quickstart guide](docs/sdk/developer-guide.md) provides instructions on how to set up the environment, run unit and integration tests, and configure the project to work with different networks -such as the Hedera test network, preview network, etc. +such as the Hiero test network, preview network, etc. ## Support + If you have a question on how to use the product, please see our [support guide](https://github.com/hashgraph/.github/blob/main/SUPPORT.md). ## Contributing + We welcome participation from all developers!\ For instructions on how to contribute to this repo, please review the [Contributing Guide](docs/sdk/CONTRIBUTING.md).\ More instructions for contribution can be found in the [Global Contributing Guide](https://github.com/hashgraph/.github/blob/main/CONTRIBUTING.md). ## Code of Conduct + This project is governed by the [Contributor Covenant Code of Conduct](https://github.com/hashgraph/.github/blob/main/CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code of conduct. ## License + [Apache License 2.0](LICENSE) diff --git a/Taskfile.yml b/Taskfile.yml index 0c367294c..df203f4ff 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -40,7 +40,7 @@ tasks: "update:snapshots": cmds: - - rm sdk/src/test/java/com/hedera/hashgraph/sdk/*.snap + - rm sdk/src/test/java/org/hiero/sdk/*.snap - ./gradlew clean test "update:proto": diff --git a/docs/sdk/SDK_ANATOMY.md b/docs/sdk/SDK_ANATOMY.md index 5ddab1363..c2c01183d 100644 --- a/docs/sdk/SDK_ANATOMY.md +++ b/docs/sdk/SDK_ANATOMY.md @@ -32,25 +32,13 @@ Augments the Java compiler to output more comprehensive errors and warnings. Library to assist in code generation (see **FunctionalExecutableProcessor**). - - - - ## Classes: - - - - ### `LockableList`: An internal utility class that represents a list of things, and which has these capabilities: - * It can be locked, which prevents the list from being mutated. - * It has an index which can be incremented with the `advance()` method, and the index will loop back around to 0 on reaching the end of the list. - - - - +* It can be locked, which prevents the list from being mutated. +* It has an index which can be incremented with the `advance()` method, and the index will loop back around to 0 on reaching the end of the list. ### `Client`: @@ -62,10 +50,6 @@ A `Client` can be initialized from a config file (json). A `Client` can be init `executor` will be used to initialize the gRPC `BaseChannel`, and in the event that an RPC fails and needs to be retried after a delay, `executor` will be used to schedule that delayed retry. - - - - ### `BaseNode`: Has an `address`, a `channel`, an `executor` (ultimately from `Client`), `lastUsed` and `useCount`. @@ -78,11 +62,7 @@ Has an `address`, a `channel`, an `executor` (ultimately from `Client`), `lastUs `BaseNode` has the methods `inUse()`, which causes the `BaseNode` to record that it is being used, `getChannel()`, `close()`, and `getUserAgent()`. -The user agent is a string that is used to identify the client to the server. In this case, it's `"hedera-sdk-java/v{NUMBER}"`. - - - - +The user agent is a string that is used to identify the client to the server. In this case, it's `"hiero-sdk-java/v{NUMBER}"`. ### `BaseNetwork`: @@ -96,28 +76,16 @@ Has these critical fields: `setNetwork()` will update this `Network` to the given list. It will close a `Node` and remove it from this network if it is not in the given list, and then it will then add nodes from the list. - - - - ### `Network`: This represents a network of Hedera nodes, a `Client` connects to a `Network`. `getNodeAccountIdsForExecute()` gets a list of N randomly selected `AccountId`s where N is 1/3rd (rounded up) of healthy nodes in this `Network`. This is used by `Query` and `Transaction` to populate their `nodeAccountId`s, lists containing the `AccountId`s of `Node`s that the `Query` or `Transaction` will be attempted with. - - - - ### `Node`: This is a connection to one node in the network. Inherits from `BaseNode` (which is where much of the meat is). - - - - ### `Executable`: An `Executable` object represents a request to the server. @@ -156,10 +124,6 @@ It should also be noted that the future returned by `grpc.ClientCalls.futureUnar `execute()` is simpler by virtue of not being async, but it does approximately the same thing, just without the future mumbo jumbo. - - - - ### `Query`: The `Query` class extends `Executable`. @@ -180,23 +144,19 @@ Query also adds some abstract methods of its own: `onExecute[async]()` seems to be where most of the action is in `Query`. It first makes sure that `nodeAccountIds` is filled, then it fetches the `queryPayment` amount (via `QueryCostQuery`) if one hasn't been set, then it generates the payment transactions for paying the query fee. The `paymentTransactions` list is a parallel array to `nodeAccountIds`. The `Query` proto message includes a `Transaction` proto message inside of it for paying the query fee, and `onExecuteAsync()` just goes ahead and builds a parallel array of `Transaction` messages which are to be used in the event that we attempt to send our query to that node. - - - - ### `Transaction`: The `Transaction` class extends `Executable`. A transaction is used like this: - - Instantiate a subclass of `Transaction`. - - Call methods to configure it. - - OPTIONAL: - - Freeze the transaction. - - Add more signatures. - - Execute the transaction (it will be frozen if not already frozen, and will be signed with client operator). - - `execute()` returns (or in the case of `executeAsync()`, returns in future) a `TransactionResponse`. - - OPTIONAL: use the resulting `TransactionResponse` to get the `TransactionReceipt` for free, or pay a fee to get the `TransactionRecord`. Fetching either of these is itself a query. +- Instantiate a subclass of `Transaction`. +- Call methods to configure it. +- OPTIONAL: +- Freeze the transaction. +- Add more signatures. +- Execute the transaction (it will be frozen if not already frozen, and will be signed with client operator). +- `execute()` returns (or in the case of `executeAsync()`, returns in future) a `TransactionResponse`. +- OPTIONAL: use the resulting `TransactionResponse` to get the `TransactionReceipt` for free, or pay a fee to get the `TransactionRecord`. Fetching either of these is itself a query. The `Transaction` class is greatly complicated by three factors: @@ -309,10 +269,6 @@ The `Transaction` is not immediately sent after freezing. Instead, the user of `validateChecksums()` has the same function as in `Query` - - - - ### `TopicMessageQuery` Unlike most classes in the Hedera SDK, this is _not_ a query to a Hedera Hashgraph network, it is a query to a _mirror_ network. As such, it is _not_ a subclass of `Query`, despite its name. @@ -325,10 +281,6 @@ The responses may be chunked. If they are, `TopicMessageQuery` will collect all In addition to the `onNext()` handler, there are several optional handlers which can be set with `setCompletionHandler()`, `setErrorhandler()`, and `setRetryHandler()`. The retry handler returns a boolean to indicate whether the query should be retried. - - - - ### `FunctionalExecutable` and `FunctionalExecutableProcessor` These classes aren't themselves components of the SDK, they are components in the SDK's build process. `FunctionalExecutable` is a custom annotation defined in the `executable-annotation` directory, and we use this annotation is in the SDK source code to mark methods that require additional processing during the build process. This additional processing is performed by the `FunctionalExecutableProcessor`, which is defined in the `executable-processor` directory. @@ -348,11 +300,6 @@ Note that the last two are synchronous versions, and in `Executable`, the synchr The `FunctionalAnnotationProcessor` can't add these methods to `Bar` directly. Instead, it will generate a new interface called `WithFoo`. The `WithFoo` interface will have an abstract `CompletableFuture fooAsync(Client client)` method, and it will have all of the variations of the `fooAsync()` and `foo()` methods which are listed above, which will use and build on the abstract `fooAsync()` method. You are expected to declare `Bar` as an implementation of this generated `WithFoo` interface. You should use the `@Override` annotation on your `fooAsync()` method in `Bar` to make sure that it overrides the abstract `fooAsync()` method from `WithFoo`. -If you want to get a better grasp on what the `FunctionalExecutableProcessor` actually does, I suggest that after building the SDK, you should look at the files in `sdk/build/generated/sources/annotationProcessor/java/main/com/hedera/hashgraph/sdk/`. These are the `With*.java` files that are generated by the `FunctionalExecutableProcessor` during the build process. For example, the `WithExecute.java` file was generated because of the `@FunctionalExecutable` annotation on the `Executable.executeAsync()` method, and if you look at `WithExecute.java` side-by-side with the `FunctionalExecutableProcessor.process()` method body, you should be able to see how each of the default methods in the `WithExecute` interface were generated by the processor - - - - +If you want to get a better grasp on what the `FunctionalExecutableProcessor` actually does, I suggest that after building the SDK, you should look at the files in `sdk/build/generated/sources/annotationProcessor/java/main/org/hiero/sdk/`. These are the `With*.java` files that are generated by the `FunctionalExecutableProcessor` during the build process. For example, the `WithExecute.java` file was generated because of the `@FunctionalExecutable` annotation on the `Executable.executeAsync()` method, and if you look at `WithExecute.java` side-by-side with the `FunctionalExecutableProcessor.process()` method body, you should be able to see how each of the default methods in the `WithExecute` interface were generated by the processor **This document is not comprehensive. There are classes I have not yet documented, or which I have only documented in passing, like `ChunkedTransaction`.** - diff --git a/example-android/app/build.gradle.kts b/example-android/app/build.gradle.kts index fc46e3df5..ac6031469 100644 --- a/example-android/app/build.gradle.kts +++ b/example-android/app/build.gradle.kts @@ -12,10 +12,10 @@ repositories { android { compileSdk = 34 - namespace = "com.hedera.android_example" + namespace = "org.hiero.android_example" defaultConfig { - applicationId = "com.hedera.android_example" + applicationId = "org.hiero.android_example" minSdk = 26 targetSdk = 34 versionCode = 1 @@ -47,10 +47,10 @@ android { dependencies { // --- Remove to use a published SDK version --- - implementation(platform("com.hedera.hashgraph:hiero-dependency-versions")) + implementation(platform("org.hiero:hiero-dependency-versions")) // --------------------------------------------- - implementation("com.hedera.hashgraph:sdk:2.46.0") + implementation("org.hiero.sdk:sdk:2.46.0") implementation("com.google.android.material:material:1.11.0") diff --git a/example-android/app/src/main/AndroidManifest.xml b/example-android/app/src/main/AndroidManifest.xml index 192e9181a..fa162f1bb 100644 --- a/example-android/app/src/main/AndroidManifest.xml +++ b/example-android/app/src/main/AndroidManifest.xml @@ -9,7 +9,7 @@ android:supportsRtl="true" android:theme="@style/AppTheme"> diff --git a/example-android/app/src/main/java/com/hedera/android_example/MainActivity.kt b/example-android/app/src/main/java/org/hiero/android_example/MainActivity.kt similarity index 92% rename from example-android/app/src/main/java/com/hedera/android_example/MainActivity.kt rename to example-android/app/src/main/java/org/hiero/android_example/MainActivity.kt index 64c81df30..f5e046e4a 100644 --- a/example-android/app/src/main/java/com/hedera/android_example/MainActivity.kt +++ b/example-android/app/src/main/java/org/hiero/android_example/MainActivity.kt @@ -1,9 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 -package com.hedera.android_example +package org.hiero.android_example import android.os.Bundle import androidx.appcompat.app.AppCompatActivity -import com.hedera.android_example.ui.main.SectionsPagerAdapter +import org.hiero.android_example.ui.main.SectionsPagerAdapter import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.TabLayoutMediator diff --git a/example-android/app/src/main/java/com/hedera/android_example/ui/main/AccountBalanceFragment.kt b/example-android/app/src/main/java/org/hiero/android_example/ui/main/AccountBalanceFragment.kt similarity index 92% rename from example-android/app/src/main/java/com/hedera/android_example/ui/main/AccountBalanceFragment.kt rename to example-android/app/src/main/java/org/hiero/android_example/ui/main/AccountBalanceFragment.kt index ced61c3dd..3bd5b5ff7 100644 --- a/example-android/app/src/main/java/com/hedera/android_example/ui/main/AccountBalanceFragment.kt +++ b/example-android/app/src/main/java/org/hiero/android_example/ui/main/AccountBalanceFragment.kt @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package com.hedera.android_example.ui.main +package org.hiero.android_example.ui.main import android.os.Bundle import android.view.LayoutInflater @@ -11,11 +11,11 @@ import android.widget.ProgressBar import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope -import com.hedera.android_example.R -import com.hedera.hashgraph.sdk.AccountBalanceQuery -import com.hedera.hashgraph.sdk.AccountId -import com.hedera.hashgraph.sdk.Client -import com.hedera.hashgraph.sdk.PrecheckStatusException +import org.hiero.android_example.R +import org.hiero.sdk.AccountBalanceQuery +import org.hiero.sdk.AccountId +import org.hiero.sdk.Client +import org.hiero.sdk.PrecheckStatusException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch diff --git a/example-android/app/src/main/java/com/hedera/android_example/ui/main/CryptoTransferFragment.kt b/example-android/app/src/main/java/org/hiero/android_example/ui/main/CryptoTransferFragment.kt similarity index 97% rename from example-android/app/src/main/java/com/hedera/android_example/ui/main/CryptoTransferFragment.kt rename to example-android/app/src/main/java/org/hiero/android_example/ui/main/CryptoTransferFragment.kt index d5916527c..f38827974 100644 --- a/example-android/app/src/main/java/com/hedera/android_example/ui/main/CryptoTransferFragment.kt +++ b/example-android/app/src/main/java/org/hiero/android_example/ui/main/CryptoTransferFragment.kt @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package com.hedera.android_example.ui.main +package org.hiero.android_example.ui.main import android.os.Bundle import android.view.LayoutInflater @@ -11,8 +11,8 @@ import android.widget.ProgressBar import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope -import com.hedera.android_example.R -import com.hedera.hashgraph.sdk.* +import org.hiero.android_example.R +import org.hiero.sdk.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch diff --git a/example-android/app/src/main/java/com/hedera/android_example/ui/main/PrivateKeyFragment.kt b/example-android/app/src/main/java/org/hiero/android_example/ui/main/PrivateKeyFragment.kt similarity index 89% rename from example-android/app/src/main/java/com/hedera/android_example/ui/main/PrivateKeyFragment.kt rename to example-android/app/src/main/java/org/hiero/android_example/ui/main/PrivateKeyFragment.kt index 73d443816..724e1f375 100644 --- a/example-android/app/src/main/java/com/hedera/android_example/ui/main/PrivateKeyFragment.kt +++ b/example-android/app/src/main/java/org/hiero/android_example/ui/main/PrivateKeyFragment.kt @@ -1,14 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 -package com.hedera.android_example.ui.main +package org.hiero.android_example.ui.main import android.widget.TextView import android.view.LayoutInflater import android.view.ViewGroup import android.os.Bundle import android.view.View -import com.hedera.android_example.R +import org.hiero.android_example.R import androidx.fragment.app.Fragment -import com.hedera.hashgraph.sdk.PrivateKey +import org.hiero.sdk.PrivateKey class PrivateKeyFragment : Fragment() { private lateinit var privateKey: TextView diff --git a/example-android/app/src/main/java/com/hedera/android_example/ui/main/SectionsPagerAdapter.kt b/example-android/app/src/main/java/org/hiero/android_example/ui/main/SectionsPagerAdapter.kt similarity index 94% rename from example-android/app/src/main/java/com/hedera/android_example/ui/main/SectionsPagerAdapter.kt rename to example-android/app/src/main/java/org/hiero/android_example/ui/main/SectionsPagerAdapter.kt index 1a1300418..55ef31903 100644 --- a/example-android/app/src/main/java/com/hedera/android_example/ui/main/SectionsPagerAdapter.kt +++ b/example-android/app/src/main/java/org/hiero/android_example/ui/main/SectionsPagerAdapter.kt @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package com.hedera.android_example.ui.main +package org.hiero.android_example.ui.main import androidx.fragment.app.FragmentActivity import androidx.viewpager2.adapter.FragmentStateAdapter diff --git a/example-android/gradle/module.properties b/example-android/gradle/module.properties new file mode 100644 index 000000000..68e1d911f --- /dev/null +++ b/example-android/gradle/module.properties @@ -0,0 +1,2 @@ +org.hiero.sdk=org.hiero.sdk:sdk +org.hiero.sdk.full=org.hiero.sdk:sdk-full diff --git a/examples/README.md b/examples/README.md index 1cf8ce3dd..a4fb9cdc7 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,86 +1,98 @@ ## Java examples ### SDK -* [Construct a client](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConstructClientExample.java) -* [Generate a key](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/GenerateKeyExample.java) -* [Generate a key (with mnemonic)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/GenerateKeyWithMnemonicExample.java) -* [Get address book](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetAddressBookExample.java) -* [Get exchange rates](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetExchangeRatesExample.java) -* [Logger](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/LoggerFunctionalitiesExample.java) + +* [Construct a client](../examples/src/main/java/org/hiero/sdk/examples/ConstructClientExample.java) +* [Generate a key](../examples/src/main/java/org/hiero/sdk/examples/GenerateKeyExample.java) +* [Generate a key (with mnemonic)](../examples/src/main/java/org/hiero/sdk/examples/GenerateKeyWithMnemonicExample.java) +* [Get address book](../examples/src/main/java/org/hiero/sdk/examples/GetAddressBookExample.java) +* [Get exchange rates](../examples/src/main/java/org/hiero/sdk/examples/GetExchangeRatesExample.java) +* [Logger](../examples/src/main/java/org/hiero/sdk/examples/LoggerFunctionalitiesExample.java) ### Transactions -* [Sign a transaction](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/SignTransactionExample.java) -* [Transaction serialization (HIP-745)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransactionSerializationExample.java) + +* [Sign a transaction](../examples/src/main/java/org/hiero/sdk/examples/SignTransactionExample.java) +* [Transaction serialization (HIP-745)](../examples/src/main/java/org/hiero/sdk/examples/TransactionSerializationExample.java) ### Schedule Transaction -* [Sign a scheduled transfer transaction](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduleExample.java) -* [Sign a scheduled transfer transaction (with comments)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduledTransferExample.java) -* [Schedule identical transaction](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduleIdenticalTransactionExample.java) -* [Schedule multisig transaction](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduleMultiSigTransactionExample.java) -* [Schedule multisig transaction (with threshold)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduledTransactionMultiSigThresholdExample.java) + +* [Sign a scheduled transfer transaction](../examples/src/main/java/org/hiero/sdk/examples/ScheduleExample.java) +* [Sign a scheduled transfer transaction (with comments)](../examples/src/main/java/org/hiero/sdk/examples/ScheduledTransferExample.java) +* [Schedule identical transaction](../examples/src/main/java/org/hiero/sdk/examples/ScheduleIdenticalTransactionExample.java) +* [Schedule multisig transaction](../examples/src/main/java/org/hiero/sdk/examples/ScheduleMultiSigTransactionExample.java) +* [Schedule multisig transaction (with threshold)](../examples/src/main/java/org/hiero/sdk/examples/ScheduledTransactionMultiSigThresholdExample.java) ### Accounts and HBAR -* [Create an account](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateAccountExample.java) -* [Create an account (threshold key)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateAccountThresholdKeyExample.java) -* [Create an account (with alias)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateAccountWithAliasExample.java) -* [Create an account (with alias and receiver signature required)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateAccountWithAliasAndReceiverSignatureRequiredExample.java) -* [Account creation ways](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountCreationWaysExample.java) -* [Create an account with Hts](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountCreateWithHtsExample.java) -* [Auto create an account with transfer transaction](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/AutoCreateAccountTransferTransactionExample.java) -* [Account alias](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountAliasExample.java) -* [Account allowance](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountAllowanceExample.java) -* [Get account info](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetAccountInfoExample.java) -* [Get account balance](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetAccountBalanceExample.java) -* [Update an account](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/UpdateAccountPublicKeyExample.java) -* [Delete an account](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/DeleteAccountExample.java) -* [Staking](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/StakingExample.java) -* [Staking (with update)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/StakingWithUpdateExample.java) -* [Multisig](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/MultiSigOfflineExample.java) + +* [Create an account](../examples/src/main/java/org/hiero/sdk/examples/CreateAccountExample.java) +* [Create an account (threshold key)](../examples/src/main/java/org/hiero/sdk/examples/CreateAccountThresholdKeyExample.java) +* [Create an account (with alias)](../examples/src/main/java/org/hiero/sdk/examples/CreateAccountWithAliasExample.java) +* [Create an account (with alias and receiver signature required)](../examples/src/main/java/org/hiero/sdk/examples/CreateAccountWithAliasAndReceiverSignatureRequiredExample.java) +* [Account creation ways](../examples/src/main/java/org/hiero/sdk/examples/AccountCreationWaysExample.java) +* [Create an account with Hts](../examples/src/main/java/org/hiero/sdk/examples/AccountCreateWithHtsExample.java) +* [Auto create an account with transfer transaction](../examples/src/main/java/org/hiero/sdk/examples/AutoCreateAccountTransferTransactionExample.java) +* [Account alias](../examples/src/main/java/org/hiero/sdk/examples/AccountAliasExample.java) +* [Account allowance](../examples/src/main/java/org/hiero/sdk/examples/AccountAllowanceExample.java) +* [Get account info](../examples/src/main/java/org/hiero/sdk/examples/GetAccountInfoExample.java) +* [Get account balance](../examples/src/main/java/org/hiero/sdk/examples/GetAccountBalanceExample.java) +* [Update an account](../examples/src/main/java/org/hiero/sdk/examples/UpdateAccountPublicKeyExample.java) +* [Delete an account](../examples/src/main/java/org/hiero/sdk/examples/DeleteAccountExample.java) +* [Staking](../examples/src/main/java/org/hiero/sdk/examples/StakingExample.java) +* [Staking (with update)](../examples/src/main/java/org/hiero/sdk/examples/StakingWithUpdateExample.java) +* [Multisig](../examples/src/main/java/org/hiero/sdk/examples/MultiSigOfflineExample.java) ### Consensus Service -* [Create a topic](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateTopicExample.java) -* [Topic management](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/TopicWithAdminKeyExample.java) -* [Consensus Pub Sub](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConsensusPubSubExample.java) -* [Consensus Pub Sub (chunked)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConsensusPubSubChunkedExample.java) -* [Consensus Pub Sub (with submit key)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConsensusPubSubWithSubmitKeyExample.java) + +* [Create a topic](../examples/src/main/java/org/hiero/sdk/examples/CreateTopicExample.java) +* [Topic management](../examples/src/main/java/org/hiero/sdk/examples/TopicWithAdminKeyExample.java) +* [Consensus Pub Sub](../examples/src/main/java/org/hiero/sdk/examples/ConsensusPubSubExample.java) +* [Consensus Pub Sub (chunked)](../examples/src/main/java/org/hiero/sdk/examples/ConsensusPubSubChunkedExample.java) +* [Consensus Pub Sub (with submit key)](../examples/src/main/java/org/hiero/sdk/examples/ConsensusPubSubWithSubmitKeyExample.java) ### Token Service -* [Transfer Hbar](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransferCryptoExample.java) -* [Transfer Hbar (multi app)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/MultiAppTransferExample.java) -* [Transfer tokens](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransferTokensExample.java) -* [Transfer using EVM address](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransferUsingEvmAddressExample.java) -* [Custom fees](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/CustomFeesExample.java) -* [Custom fees (exempt)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ExemptCustomFeesExample.java) -* [NFT Allowances](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/NftAddRemoveAllowancesExample.java) -* [Zero token operations](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ZeroTokenOperationsExample.java) -* [Change Or Remove Existing Keys From A Token (HIP-540)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ChangeRemoveTokenKeys.java) -* [Reject A Token (HIP-904)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/TokenRejectExample.java) + +* [Transfer Hbar](../examples/src/main/java/org/hiero/sdk/examples/TransferCryptoExample.java) +* [Transfer Hbar (multi app)](../examples/src/main/java/org/hiero/sdk/examples/MultiAppTransferExample.java) +* [Transfer tokens](../examples/src/main/java/org/hiero/sdk/examples/TransferTokensExample.java) +* [Transfer using EVM address](../examples/src/main/java/org/hiero/sdk/examples/TransferUsingEvmAddressExample.java) +* [Custom fees](../examples/src/main/java/org/hiero/sdk/examples/CustomFeesExample.java) +* [Custom fees (exempt)](../examples/src/main/java/org/hiero/sdk/examples/ExemptCustomFeesExample.java) +* [NFT Allowances](../examples/src/main/java/org/hiero/sdk/examples/NftAddRemoveAllowancesExample.java) +* [Zero token operations](../examples/src/main/java/org/hiero/sdk/examples/ZeroTokenOperationsExample.java) +* [Change Or Remove Existing Keys From A Token (HIP-540)](../examples/src/main/java/org/hiero/sdk/examples/ChangeRemoveTokenKeys.java) +* [Reject A Token (HIP-904)](../examples/src/main/java/org/hiero/sdk/examples/TokenRejectExample.java) ### File Service -* [Create a file](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateFileExample.java) -* [File append (chunked)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/FileAppendChunkedExample.java) -* [Get file contents](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetFileContentsExample.java) -* [Delete a file](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/DeleteFileExample.java) + +* [Create a file](../examples/src/main/java/org/hiero/sdk/examples/CreateFileExample.java) +* [File append (chunked)](../examples/src/main/java/org/hiero/sdk/examples/FileAppendChunkedExample.java) +* [Get file contents](../examples/src/main/java/org/hiero/sdk/examples/GetFileContentsExample.java) +* [Delete a file](../examples/src/main/java/org/hiero/sdk/examples/DeleteFileExample.java) ### Smart Contract Service -* [Create a contract](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateSimpleContractExample.java) -* [Create a stateful contract](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateStatefulContractExample.java) -* [Contract nonce (HIP-729)](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ContractNoncesExample.java) -* [Interaction with a contract](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/SolidityPrecompileExample.java) + +* [Create a contract](../examples/src/main/java/org/hiero/sdk/examples/CreateSimpleContractExample.java) +* [Create a stateful contract](../examples/src/main/java/org/hiero/sdk/examples/CreateStatefulContractExample.java) +* [Contract nonce (HIP-729)](../examples/src/main/java/org/hiero/sdk/examples/ContractNoncesExample.java) +* [Interaction with a contract](../examples/src/main/java/org/hiero/sdk/examples/SolidityPrecompileExample.java) ### Miscellaneous -* [Checksum validation](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/ValidateChecksumExample.java) -* [Pseudorandom Number Generator](../examples/src/main/java/com/hedera/hashgraph/sdk/examples/PrngExample.java) + +* [Checksum validation](../examples/src/main/java/org/hiero/sdk/examples/ValidateChecksumExample.java) +* [Pseudorandom Number Generator](../examples/src/main/java/org/hiero/sdk/examples/PrngExample.java) ## Usage ### Configuration + Running the examples requires `.env` file to exist in the [`examples`](.) folder if running with Gradle: ```sh cp .env.sample .env ``` + And in the root project folder if running with Intellij IDEA: + ```sh cp .env.sample ../.env ``` @@ -92,7 +104,7 @@ for configuring the network. If the `HEDERA_NETWORK` is not set, it will default - You can set the `SDK_LOG_LEVEL` to `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR` or `SILENT` for configuring the logging. If the `SDK_LOG_LEVEL` is not set, it will default to `SILENT`. Important pre-requisite to see logs: set simple logger log level to same level as the `SDK_LOG_LEVEL`, -for example via VM options: `-Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace`. +for example via VM options: `-Dorg.slf4j.simpleLogger.log.org.hiero=trace`. Therefore, the format of the configuration file should be as follows: @@ -121,4 +133,5 @@ Concrete example: ``` ### Running with Intellij + Simply execute the main function of the desired example. diff --git a/examples/build.gradle.kts b/examples/build.gradle.kts index 90c5f84ac..461c3f893 100644 --- a/examples/build.gradle.kts +++ b/examples/build.gradle.kts @@ -35,9 +35,8 @@ tasks.addRule("Pattern: run: Runs an example.") { tasks.register(this) { workingDir = rootDir classpath = configurations.runtimeClasspath.get() + files(tasks.jar) - mainModule = "com.hedera.hashgraph.examples" - mainClass = - "com.hedera.hashgraph.sdk.examples.${this@addRule.substring("run".length)}Example" + mainModule = "org.hiero.sdk.examples" + mainClass = "org.hiero.sdk.examples.${this@addRule.substring("run".length)}Example" } } } @@ -82,11 +81,11 @@ abstract class RunAllExample : DefaultTask() { exec.javaexec { workingDir = workingDirectory.get().asFile classpath = rtClasspath - mainModule = "com.hedera.hashgraph.examples" - mainClass = "com.hedera.hashgraph.sdk.examples.$className" + mainModule = "org.hiero.sdk.examples" + mainClass = "org.hiero.sdk.examples.$className" // NOTE: Uncomment to enable trace logs in the SDK during the examples - // jvmArgs "-Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace" + // jvmArgs "-Dorg.slf4j.simpleLogger.log.org.hiero=trace" } } } diff --git a/examples/gradle/modules.properties b/examples/gradle/modules.properties new file mode 100644 index 000000000..68e1d911f --- /dev/null +++ b/examples/gradle/modules.properties @@ -0,0 +1,2 @@ +org.hiero.sdk=org.hiero.sdk:sdk +org.hiero.sdk.full=org.hiero.sdk:sdk-full diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/DynamicAddressBookExample.java b/examples/src/main/java/com/hedera/hashgraph/sdk/examples/DynamicAddressBookExample.java deleted file mode 100644 index dcd1c060c..000000000 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/DynamicAddressBookExample.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.hedera.hashgraph.sdk.examples; - -import com.hedera.hashgraph.sdk.AccountId; -import com.hedera.hashgraph.sdk.Client; -import com.hedera.hashgraph.sdk.Endpoint; -import com.hedera.hashgraph.sdk.NodeCreateTransaction; -import com.hedera.hashgraph.sdk.NodeDeleteTransaction; -import com.hedera.hashgraph.sdk.NodeUpdateTransaction; -import com.hedera.hashgraph.sdk.PrecheckStatusException; -import com.hedera.hashgraph.sdk.PrivateKey; -import com.hedera.hashgraph.sdk.ReceiptStatusException; -import io.github.cdimascio.dotenv.Dotenv; -import java.util.Collections; -import java.util.Objects; -import java.util.concurrent.TimeoutException; - -/** - * hip-869 - */ -public class DynamicAddressBookExample { - // see `.env.sample` in the repository root for how to specify these values - // or set environment variables with the same names - private static final AccountId OPERATOR_ID = AccountId.fromString( - Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString( - Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); - // HEDERA_NETWORK defaults to testnet if not specified in dotenv - private static final String HEDERA_NETWORK = Dotenv.load().get("HEDERA_NETWORK", "testnet"); - - public static void main(String[] args) - throws TimeoutException, PrecheckStatusException, ReceiptStatusException, InterruptedException { - Client client = ClientHelper.forName(HEDERA_NETWORK); - - // Defaults the operator account ID and key such that all generated transactions will be paid for - // by this account and be signed by this key - client.setOperator(OPERATOR_ID, OPERATOR_KEY); - - AccountId accountId = AccountId.fromString("0.0.1999"); - String description = "Hedera™ cryptocurrency"; - String newDescription = "Hedera™ cryptocurrency - updated"; - - // Set up IPv4 address - Endpoint gossipEndpoint = new Endpoint(); - gossipEndpoint - .setAddress(new byte[] {0x00, 0x01, 0x02, 0x03}); - - // Set up service endpoint - Endpoint serviceEndpoint = new Endpoint(); - serviceEndpoint - .setAddress(new byte[] {0x00, 0x01, 0x02, 0x03}); - - // Generate admin key - PrivateKey adminKey = PrivateKey.generateED25519(); - - // Create node create transaction - NodeCreateTransaction nodeCreateTransaction = new NodeCreateTransaction() - .setAccountId(accountId) - .setDescription(description) - .setGossipCaCertificate("gossipCaCertificate".getBytes()) - .setServiceEndpoints(Collections.singletonList(serviceEndpoint)) - .setGossipEndpoints(Collections.singletonList(gossipEndpoint)) - .setAdminKey(adminKey.getPublicKey()); - - try { - nodeCreateTransaction.execute(client).getReceipt(client); - } catch (Exception e){ - System.out.println(e); - } - - var nodeUpdateTransaction = new NodeUpdateTransaction() - .setNodeId(123) - .setAccountId(accountId) - .setDescription(newDescription) - .setGossipCaCertificate("gossipCaCertificate".getBytes()) - .setServiceEndpoints(Collections.singletonList(serviceEndpoint)) - .setGossipEndpoints(Collections.singletonList(gossipEndpoint)) - .setAdminKey(adminKey.getPublicKey()); - - try { - nodeUpdateTransaction.execute(client).getReceipt(client); - } catch (Exception e){ - System.out.println(e); - } - - var nodeDeleteTransaction = new NodeDeleteTransaction() - .setNodeId(123); - - try { - nodeDeleteTransaction.execute(client).getReceipt(client); - } catch (Exception e){ - System.out.println(e); - } - } -} diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GenerateKeyExample.java b/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GenerateKeyExample.java deleted file mode 100644 index dfbff5b0e..000000000 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GenerateKeyExample.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; - -import com.hedera.hashgraph.sdk.PrivateKey; -import com.hedera.hashgraph.sdk.PublicKey; - -/** - * How to generate ED25519 key pair. - */ -class GenerateKeyExample { - - public static void main(String[] args) { - System.out.println("Generate ED25519 Private And Public Key Pair Example Start!"); - - System.out.println("Generating the ED25519 private key..."); - PrivateKey privateKey = PrivateKey.generateED25519(); - System.out.println("Private Key: " + privateKey); - - System.out.println("Deriving a public key from the above private key"); - PublicKey publicKey = privateKey.getPublicKey(); - System.out.println("Public key: " + publicKey); - - System.out.println("Generate ED25519 Private And Public Key Pair Example Complete!"); - } -} diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/MirrorNodeContractQueriesExample.java b/examples/src/main/java/com/hedera/hashgraph/sdk/examples/MirrorNodeContractQueriesExample.java deleted file mode 100644 index b90eab231..000000000 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/MirrorNodeContractQueriesExample.java +++ /dev/null @@ -1,187 +0,0 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2023 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package com.hedera.hashgraph.sdk.examples; - -import com.hedera.hashgraph.sdk.AccountId; -import com.hedera.hashgraph.sdk.Client; -import com.hedera.hashgraph.sdk.ContractCallQuery; -import com.hedera.hashgraph.sdk.ContractCreateTransaction; -import com.hedera.hashgraph.sdk.Hbar; -import com.hedera.hashgraph.sdk.MirrorNodeContractCallQuery; -import com.hedera.hashgraph.sdk.MirrorNodeContractEstimateGasQuery; -import com.hedera.hashgraph.sdk.PrivateKey; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; -import io.github.cdimascio.dotenv.Dotenv; -import java.nio.charset.StandardCharsets; -import java.util.Objects; -import org.bouncycastle.util.encoders.Hex; - -public class MirrorNodeContractQueriesExample { - /* - * See .env.sample in the examples folder root for how to specify values below - * or set environment variables with the same names. - */ - - /** - * Operator's account ID. Used to sign and pay for operations on Hedera. - */ - private static final AccountId OPERATOR_ID = AccountId.fromString( - Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); - - /** - * Operator's private key. - */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString( - Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); - - /** - * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. Network can be: localhost, testnet, - * previewnet or mainnet. - */ - private static final String HEDERA_NETWORK = Dotenv.load().get("HEDERA_NETWORK", "testnet"); - - /** - * SDK_LOG_LEVEL defaults to SILENT if not specified in dotenv file. Log levels can be: TRACE, DEBUG, INFO, WARN, - * ERROR, SILENT. - *

- * Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, for example via VM - * options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace - */ - private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); - - private static final String SMART_CONTRACT_BYTECODE = "60806040526040518060400160405280600581526020017f68656c6c6f0000000000000000000000000000000000000000000000000000008152505f90816100479190610293565b50348015610053575f80fd5b50610362565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806100d457607f821691505b6020821081036100e7576100e6610090565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f600883026101497fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8261010e565b610153868361010e565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f61019761019261018d8461016b565b610174565b61016b565b9050919050565b5f819050919050565b6101b08361017d565b6101c46101bc8261019e565b84845461011a565b825550505050565b5f90565b6101d86101cc565b6101e38184846101a7565b505050565b5b81811015610206576101fb5f826101d0565b6001810190506101e9565b5050565b601f82111561024b5761021c816100ed565b610225846100ff565b81016020851015610234578190505b610248610240856100ff565b8301826101e8565b50505b505050565b5f82821c905092915050565b5f61026b5f1984600802610250565b1980831691505092915050565b5f610283838361025c565b9150826002028217905092915050565b61029c82610059565b67ffffffffffffffff8111156102b5576102b4610063565b5b6102bf82546100bd565b6102ca82828561020a565b5f60209050601f8311600181146102fb575f84156102e9578287015190505b6102f38582610278565b86555061035a565b601f198416610309866100ed565b5f5b828110156103305784890151825560018201915060208501945060208101905061030b565b8683101561034d5784890151610349601f89168261025c565b8355505b6001600288020188555050505b505050505050565b6102178061036f5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063ce6d41de1461002d575b5f80fd5b61003561004b565b6040516100429190610164565b60405180910390f35b60605f8054610059906101b1565b80601f0160208091040260200160405190810160405280929190818152602001828054610085906101b1565b80156100d05780601f106100a7576101008083540402835291602001916100d0565b820191905f5260205f20905b8154815290600101906020018083116100b357829003601f168201915b5050505050905090565b5f81519050919050565b5f82825260208201905092915050565b5f5b838110156101115780820151818401526020810190506100f6565b5f8484015250505050565b5f601f19601f8301169050919050565b5f610136826100da565b61014081856100e4565b93506101508185602086016100f4565b6101598161011c565b840191505092915050565b5f6020820190508181035f83015261017c818461012c565b905092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806101c857607f821691505b6020821081036101db576101da610184565b5b5091905056fea26469706673582212202a86c27939bfab6d4a2c61ebbf096d8424e17e22dfdd42320f6e2654863581e964736f6c634300081a0033"; - - public static void main(String[] args) throws Exception { - System.out.println("Mirror Node contract queries Example Start!"); - /* - * Step 0: - * Create and configure the SDK Client. - */ - Client client = ClientHelper.forName(HEDERA_NETWORK); - // All generated transactions will be paid by this account and signed by this key. - client.setOperator(OPERATOR_ID, OPERATOR_KEY); - // Attach logger to the SDK Client. - client.setLogger(new Logger(LogLevel.valueOf(SDK_LOG_LEVEL))); - - /* - * Step 1: - * Create the contract - */ - var response = new ContractCreateTransaction() - .setGas(200_000) - .setBytecode(Hex.decode(SMART_CONTRACT_BYTECODE)) - .setContractMemo("Simple contract with string field") - .execute(client); - - var contractId = Objects.requireNonNull(response.getReceipt(client).contractId); - System.out.println("Created new contract with ID: " + contractId); - - /* - * Step 3: - * Wait for mirror node to import data - */ - Thread.sleep(5000); - - /* - * Step 4: - * Estimate the gas needed - */ - var gas = new MirrorNodeContractEstimateGasQuery() - .setContractId(contractId) - .setSender(client.getOperatorAccountId()) - .setGasLimit(30_000) - .setGasPrice(1234) - .setFunction("getMessage") - .execute(client); - - System.out.println("Gas needed for this query: " + gas); - - /* - * Step 5: - * Do the query against the consensus node using the estimated gas - */ - var callQuery = new ContractCallQuery() - .setContractId(contractId) - .setGas(gas) - .setFunction("getMessage") - .setQueryPayment(new Hbar(1)); - - var result = callQuery - .execute(client); - - /* - * Step 6: - * Simulate the transaction for free, using the mirror node - */ - var simulationResult = new MirrorNodeContractCallQuery() - .setContractId(contractId) - .setSender(client.getOperatorAccountId()) - .setGasLimit(30_000) - .setBlockNumber(10000) - .setGasPrice(1234) - .setFunction("getMessage") - .execute(client); - - // Decode the result since it's coming in ABI Hex format from the Mirror Node - var decodedResult = decodeABIHexString(simulationResult); - System.out.println("Simulation result: " + decodedResult); - System.out.println("Contract call result: " + result.getString(0)); - } - - /** - * Decodes a hex-encoded ABI (Application Binary Interface) string into a UTF-8 string. - *

- * The function assumes the input follows the ABI encoding standard for dynamic data. Specifically, it parses the - * length of the dynamic data and extracts the corresponding substring. - *

- * The structure of the input hex string is as follows: - The first 64 characters represent metadata, such as - * offsets and other header information. - Characters from index 64 to 128 encode the length of the dynamic data in - * bytes. - Characters from index 128 onward represent the actual dynamic data. - *

- * This method removes the `0x` prefix if present, parses the length, and decodes the dynamic data into UTF-8. - * - * @param hex the hex string to decode, which follows the ABI encoding standard - * @return the decoded UTF-8 string - */ - private static String decodeABIHexString(String hex) { - // Trim 0x at the beginning - if (hex.startsWith("0x")) { - hex = hex.substring(2); - } - - // Extract the length of the data by parsing the substring from position 64 to 128 as a hexadecimal integer - // This section represents the length of the dynamic data, specifically the number of bytes in the string or array - int length = Integer.parseInt(hex.substring(64, 128), 16); - - // Using the extracted length, the code calculates the substring containing the actual data starting from position 128. - String hexStringData = hex.substring(128, 128 + length * 2); - - byte[] bytes = new byte[length]; - // Iterate through the extracted hex data, two characters at a time, converting each pair to a byte and storing it in a byte array. - for (int i = 0; i < length; i++) { - bytes[i] = (byte) Integer.parseInt(hexStringData.substring(i * 2, i * 2 + 2), 16); - } - - // Convert to UTF 8 - return new String(bytes, StandardCharsets.UTF_8); - } -} diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TokenAirdropExample.java b/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TokenAirdropExample.java deleted file mode 100644 index b9de23e6a..000000000 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TokenAirdropExample.java +++ /dev/null @@ -1,390 +0,0 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; - -import com.hedera.hashgraph.sdk.AccountBalanceQuery; -import com.hedera.hashgraph.sdk.AccountCreateTransaction; -import com.hedera.hashgraph.sdk.AccountId; -import com.hedera.hashgraph.sdk.Client; -import com.hedera.hashgraph.sdk.Hbar; -import com.hedera.hashgraph.sdk.PrivateKey; -import com.hedera.hashgraph.sdk.TokenAirdropTransaction; -import com.hedera.hashgraph.sdk.TokenCancelAirdropTransaction; -import com.hedera.hashgraph.sdk.TokenClaimAirdropTransaction; -import com.hedera.hashgraph.sdk.TokenCreateTransaction; -import com.hedera.hashgraph.sdk.TokenMintTransaction; -import com.hedera.hashgraph.sdk.TokenRejectTransaction; -import com.hedera.hashgraph.sdk.TokenSupplyType; -import com.hedera.hashgraph.sdk.TokenType; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; -import io.github.cdimascio.dotenv.Dotenv; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -public class TokenAirdropExample { - - /* - * See .env.sample in the examples folder root for how to specify values below - * or set environment variables with the same names. - */ - - /** - * Operator's account ID. Used to sign and pay for operations on Hedera. - */ - private static final AccountId OPERATOR_ID = AccountId.fromString( - Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); - - /** - * Operator's private key. - */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString( - Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); - - /** - * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. Network can be: localhost, testnet, - * previewnet or mainnet. - */ - private static final String HEDERA_NETWORK = Dotenv.load().get("HEDERA_NETWORK", "testnet"); - - /** - * SDK_LOG_LEVEL defaults to SILENT if not specified in dotenv file. Log levels can be: TRACE, DEBUG, INFO, WARN, - * ERROR, SILENT. - *

- * Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, for example via VM - * options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace - */ - private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); - - public static void main(String[] args) throws Exception { - System.out.println("Example Start!"); - - /* - * Step 0: - * Create and configure SDK Client. - */ - Client client = ClientHelper.forName(HEDERA_NETWORK); - // All generated transactions will be paid by this account and signed by this key. - client.setOperator(OPERATOR_ID, OPERATOR_KEY); - // Attach logger to the SDK Client. - client.setLogger(new Logger(LogLevel.valueOf(SDK_LOG_LEVEL))); - - /* - * Step 1: - * Create 4 accounts - */ - var privateKey1 = PrivateKey.generateECDSA(); - var alice = new AccountCreateTransaction() - .setKey(privateKey1) - .setInitialBalance(new Hbar(10)) - .setMaxAutomaticTokenAssociations(-1) - .execute(client) - .getReceipt(client) - .accountId; - - var privateKey2 = PrivateKey.generateECDSA(); - var bob = new AccountCreateTransaction() - .setKey(privateKey2) - .setMaxAutomaticTokenAssociations(1) - .execute(client) - .getReceipt(client) - .accountId; - - var privateKey3 = PrivateKey.generateECDSA(); - var carol = new AccountCreateTransaction() - .setKey(privateKey3) - .setMaxAutomaticTokenAssociations(0) - .execute(client) - .getReceipt(client) - .accountId; - - var treasuryKey = PrivateKey.generateECDSA(); - var treasuryAccount = new AccountCreateTransaction() - .setKey(treasuryKey) - .setInitialBalance(new Hbar(10)) - .execute(client) - .getReceipt(client) - .accountId; - - /* - * Step 2: - * Create FT and NFT and mint - */ - var tokenID = new TokenCreateTransaction() - .setTokenName("Fungible Token") - .setTokenSymbol("TFT") - .setTokenMemo("Example memo") - .setDecimals(3) - .setInitialSupply(100) - .setMaxSupply(100) - .setTreasuryAccountId(treasuryAccount) - .setSupplyType(TokenSupplyType.FINITE) - .setAdminKey(client.getOperatorPublicKey()) - .setFreezeKey(client.getOperatorPublicKey()) - .setSupplyKey(client.getOperatorPublicKey()) - .setMetadataKey(client.getOperatorPublicKey()) - .setPauseKey(client.getOperatorPublicKey()) - .freezeWith(client) - .sign(treasuryKey) - .execute(client) - .getReceipt(client) - .tokenId; - - var nftID = new TokenCreateTransaction() - .setTokenName("Test NFT") - .setTokenSymbol("TNFT") - .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) - .setTreasuryAccountId(treasuryAccount) - .setSupplyType(TokenSupplyType.FINITE) - .setMaxSupply(10) - .setSupplyType(TokenSupplyType.FINITE) - .setAdminKey(client.getOperatorPublicKey()) - .setFreezeKey(client.getOperatorPublicKey()) - .setSupplyKey(client.getOperatorPublicKey()) - .setMetadataKey(client.getOperatorPublicKey()) - .setPauseKey(client.getOperatorPublicKey()) - .freezeWith(client) - .sign(treasuryKey) - .execute(client) - .getReceipt(client) - .tokenId; - - new TokenMintTransaction() - .setTokenId(nftID) - .setMetadata(generateNftMetadata((byte) 3)) - .execute(client) - .getReceipt(client); - - - /* - * Step 3: - * Airdrop fungible tokens to all 3 accounts - */ - System.out.println("Airdropping fts"); - var txnRecord = new TokenAirdropTransaction() - .addTokenTransfer(tokenID, alice, 10) - .addTokenTransfer(tokenID, treasuryAccount, -10) - .addTokenTransfer(tokenID, bob, 10) - .addTokenTransfer(tokenID, treasuryAccount, -10) - .addTokenTransfer(tokenID, carol, 10) - .addTokenTransfer(tokenID, treasuryAccount, -10) - .freezeWith(client) - .sign(treasuryKey) - .execute(client) - .getRecord(client); - - /* - * Step 4: - * Get the transaction record and see one pending airdrop (for carol) - */ - System.out.println("Pending airdrops length: " + txnRecord.pendingAirdropRecords.size()); - System.out.println("Pending airdrops: " + txnRecord.pendingAirdropRecords.get(0)); - - /* - * Step 5: - * Query to verify alice and bob received the airdrops and carol did not - */ - var aliceBalance = new AccountBalanceQuery() - .setAccountId(alice) - .execute(client); - var bobBalance = new AccountBalanceQuery() - .setAccountId(bob) - .execute(client); - var carolBalance = new AccountBalanceQuery() - .setAccountId(carol) - .execute(client); - - System.out.println("Alice ft balance after airdrop: " + aliceBalance.tokens.get(tokenID)); - System.out.println("Bob ft balance after airdrop: " + bobBalance.tokens.get(tokenID)); - System.out.println("Carol ft balance after airdrop: " + carolBalance.tokens.get(tokenID)); - - /* - * Step 6: - * Claim the airdrop for carol - */ - System.out.println("Claiming ft with carol"); - new TokenClaimAirdropTransaction() - .addPendingAirdrop(txnRecord.pendingAirdropRecords.get(0).getPendingAirdropId()) - .freezeWith(client) - .sign(privateKey3) - .execute(client) - .getReceipt(client); - - carolBalance = new AccountBalanceQuery() - .setAccountId(carol) - .execute(client); - System.out.println("Carol ft balance after claim: " + carolBalance.tokens.get(tokenID)); - - /* - * Step 7: - * Airdrop the NFTs to all three accounts - */ - System.out.println("Airdropping nfts"); - txnRecord = new TokenAirdropTransaction() - .addNftTransfer(nftID.nft(1), treasuryAccount, alice) - .addNftTransfer(nftID.nft(2), treasuryAccount, bob) - .addNftTransfer(nftID.nft(3), treasuryAccount, carol) - .freezeWith(client) - .sign(treasuryKey) - .execute(client) - .getRecord(client); - - /* - * Step 8: - * Get the transaction record and verify two pending airdrops (for bob & carol) - */ - System.out.println("Pending airdrops length: " + txnRecord.pendingAirdropRecords.size()); - System.out.println("Pending airdrops for Bob: " + txnRecord.pendingAirdropRecords.get(0)); - System.out.println("Pending airdrops for Carol: " + txnRecord.pendingAirdropRecords.get(1)); - - /* - * Step 9: - * Query to verify alice received the airdrop and bob and carol did not - */ - aliceBalance = new AccountBalanceQuery() - .setAccountId(alice) - .execute(client); - bobBalance = new AccountBalanceQuery() - .setAccountId(bob) - .execute(client); - carolBalance = new AccountBalanceQuery() - .setAccountId(carol) - .execute(client); - - System.out.println("Alice nft balance after airdrop: " + aliceBalance.tokens.get(nftID)); - System.out.println("Bob nft balance after airdrop: " + bobBalance.tokens.get(nftID)); - System.out.println("Carol nft balance after airdrop: " + carolBalance.tokens.get(nftID)); - - /* - * Step 10: - * Claim the airdrop for bob - */ - System.out.println("Claiming nft with Bob"); - new TokenClaimAirdropTransaction() - .addPendingAirdrop(txnRecord.pendingAirdropRecords.get(0).getPendingAirdropId()) - .freezeWith(client) - .sign(privateKey2) - .execute(client) - .getReceipt(client); - - bobBalance = new AccountBalanceQuery() - .setAccountId(bob) - .execute(client); - System.out.println("Bob nft balance after claim: " + bobBalance.tokens.get(nftID)); - - /* - * Step 11: - * Cancel the airdrop for carol - */ - System.out.println("Canceling nft for Carol"); - new TokenCancelAirdropTransaction() - .addPendingAirdrop(txnRecord.pendingAirdropRecords.get(1).getPendingAirdropId()) - .freezeWith(client) - .sign(treasuryKey) - .execute(client) - .getReceipt(client); - - carolBalance = new AccountBalanceQuery() - .setAccountId(carol) - .execute(client); - System.out.println("Carol nft balance after cancel: " + carolBalance.tokens.get(nftID)); - - /* - * Step 12: - * Reject the NFT for bob - */ - System.out.println("Rejecting nft with Bob"); - new TokenRejectTransaction() - .setOwnerId(bob) - .addNftId(nftID.nft(2)) - .freezeWith(client) - .sign(privateKey2) - .execute(client) - .getReceipt(client); - - /* - * Step 13: - * Query to verify bob no longer has the NFT - */ - bobBalance = new AccountBalanceQuery() - .setAccountId(bob) - .execute(client); - System.out.println("Bob nft balance after reject: " + bobBalance.tokens.get(nftID)); - - /* - * Step 13: - * Query to verify the NFT was returned to the Treasury - */ - var treasuryBalance = new AccountBalanceQuery() - .setAccountId(treasuryAccount) - .execute(client); - System.out.println("Treasury nft balance after reject: " + treasuryBalance.tokens.get(nftID)); - - /* - * Step 14: - * Reject the fungible tokens for Carol - */ - System.out.println("Rejecting ft with Carol"); - new TokenRejectTransaction() - .setOwnerId(carol) - .addTokenId(tokenID) - .freezeWith(client) - .sign(privateKey3) - .execute(client) - .getReceipt(client); - - /* - * Step 14: - * Query to verify carol no longer has the fungible tokens - */ - carolBalance = new AccountBalanceQuery() - .setAccountId(carol) - .execute(client); - System.out.println("Carol ft balance after reject: " + carolBalance.tokens.get(tokenID)); - - /* - * Step 15: - * Query to verify Treasury received the rejected fungible tokens - */ - treasuryBalance = new AccountBalanceQuery() - .setAccountId(treasuryAccount) - .execute(client); - System.out.println("Treasury ft balance after reject: " + treasuryBalance.tokens.get(tokenID)); - - /* - * Clean up: - */ - client.close(); - - System.out.println("Example Complete!"); - } - - private static List generateNftMetadata(byte metadataCount) { - List metadatas = new ArrayList<>(); - - for (byte i = 0; i < metadataCount; i++) { - byte[] md = {i}; - metadatas.add(md); - } - - return metadatas; - } -} diff --git a/examples/src/main/java/module-info.java b/examples/src/main/java/module-info.java index 858487390..40729dd8c 100644 --- a/examples/src/main/java/module-info.java +++ b/examples/src/main/java/module-info.java @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 -module com.hedera.hashgraph.examples { - requires com.hedera.hashgraph.sdk; // .full; +module org.hiero.sdk.examples { + requires org.hiero.sdk; // .full; requires com.google.gson; requires io.github.cdimascio.dotenv.java; requires org.bouncycastle.provider; diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountAliasExample.java b/examples/src/main/java/org/hiero/sdk/examples/AccountAliasExample.java similarity index 73% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountAliasExample.java rename to examples/src/main/java/org/hiero/sdk/examples/AccountAliasExample.java index 34ef05438..cdbc73ad4 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountAliasExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/AccountAliasExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to use auto account creation (HIP-32). @@ -59,12 +40,14 @@ class AccountAliasExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -77,7 +60,7 @@ class AccountAliasExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -126,10 +109,11 @@ public static void main(String[] args) throws Exception { System.out.println("New account ID: " + aliasAccountId); System.out.println("Just the aliasKey: " + aliasAccountId.aliasKey); - AccountId fromStringExample = AccountId.fromString("0.0.302a300506032b6570032100114e6abc371b82dab5c15ea149f02d34a012087b163516dd70f44acafabf7777"); + AccountId fromStringExample = AccountId.fromString( + "0.0.302a300506032b6570032100114e6abc371b82dab5c15ea149f02d34a012087b163516dd70f44acafabf7777"); - AccountId fromKeyStringExample = PublicKey - .fromString("302a300506032b6570032100114e6abc371b82dab5c15ea149f02d34a012087b163516dd70f44acafabf7777") + AccountId fromKeyStringExample = PublicKey.fromString( + "302a300506032b6570032100114e6abc371b82dab5c15ea149f02d34a012087b163516dd70f44acafabf7777") .toAccountId(0, 0); /* @@ -141,10 +125,10 @@ public static void main(String[] args) throws Exception { */ System.out.println("Transferring Hbar to the new account..."); new TransferTransaction() - .addHbarTransfer(OPERATOR_ID, Hbar.from(1).negated()) - .addHbarTransfer(aliasAccountId, Hbar.from(1)) - .execute(client) - .getReceipt(client); + .addHbarTransfer(OPERATOR_ID, Hbar.from(1).negated()) + .addHbarTransfer(aliasAccountId, Hbar.from(1)) + .execute(client) + .getReceipt(client); /* * Step 4: @@ -156,15 +140,13 @@ public static void main(String[] args) throws Exception { * Users may continue to refer to the account by its aliasKey AccountId, but they may also * now refer to it by its normal AccountId */ - AccountBalance newAccountBalance = new AccountBalanceQuery() - .setAccountId(aliasAccountId) - .execute(client); + AccountBalance newAccountBalance = + new AccountBalanceQuery().setAccountId(aliasAccountId).execute(client); System.out.println("Balances of the new account: " + newAccountBalance); - AccountInfo newAccountInfo = new AccountInfoQuery() - .setAccountId(aliasAccountId) - .execute(client); + AccountInfo newAccountInfo = + new AccountInfoQuery().setAccountId(aliasAccountId).execute(client); Objects.requireNonNull(newAccountInfo.accountId); @@ -177,12 +159,12 @@ public static void main(String[] args) throws Exception { * Delete created account and close the client. */ new AccountDeleteTransaction() - .setAccountId(newAccountInfo.accountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(privateKey) - .execute(client) - .getReceipt(client); + .setAccountId(newAccountInfo.accountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(privateKey) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountAllowanceExample.java b/examples/src/main/java/org/hiero/sdk/examples/AccountAllowanceExample.java similarity index 50% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountAllowanceExample.java rename to examples/src/main/java/org/hiero/sdk/examples/AccountAllowanceExample.java index 8eb700689..4a3f93fa4 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountAllowanceExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/AccountAllowanceExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to approve and delete allowance. @@ -50,12 +31,14 @@ class AccountAllowanceExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -68,7 +51,7 @@ class AccountAllowanceExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -106,45 +89,39 @@ public static void main(String[] args) throws Exception { System.out.println("Creating Alice's, Bob's and Charlie's accounts..."); AccountId aliceId = new AccountCreateTransaction() - .setKey(alicePublicKey) - .setInitialBalance(Hbar.from(5)) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(alicePublicKey) + .setInitialBalance(Hbar.from(5)) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(aliceId); AccountId bobId = new AccountCreateTransaction() - .setKey(bobPublicKey) - .setInitialBalance(Hbar.from(5)) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(bobPublicKey) + .setInitialBalance(Hbar.from(5)) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(bobId); AccountId charlieId = new AccountCreateTransaction() - .setKey(charliePublicKey) - .setInitialBalance(Hbar.from(5)) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(charliePublicKey) + .setInitialBalance(Hbar.from(5)) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(charlieId); System.out.println("Alice's account ID: " + aliceId); System.out.println("Bob's account ID: " + bobId); System.out.println("Charlie's account ID: " + charlieId); - System.out.println( - "Alice's balance: " + - new AccountBalanceQuery().setAccountId(aliceId).execute(client).hbars - ); - System.out.println( - "Bob's balance: " + - new AccountBalanceQuery().setAccountId(bobId).execute(client).hbars - ); - System.out.println( - "Charlie's balance: " + - new AccountBalanceQuery().setAccountId(charlieId).execute(client).hbars - ); + System.out.println("Alice's balance: " + + new AccountBalanceQuery().setAccountId(aliceId).execute(client).hbars); + System.out.println("Bob's balance: " + + new AccountBalanceQuery().setAccountId(bobId).execute(client).hbars); + System.out.println("Charlie's balance: " + + new AccountBalanceQuery().setAccountId(charlieId).execute(client).hbars); /* * Step 3: @@ -153,59 +130,47 @@ public static void main(String[] args) throws Exception { System.out.println("Approving an allowance of 2 Hbar with owner Alice and spender Bob..."); new AccountAllowanceApproveTransaction() - .approveHbarAllowance(aliceId, bobId, Hbar.from(2)) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); - - System.out.println( - "Alice's balance: " + - new AccountBalanceQuery().setAccountId(aliceId).execute(client).hbars - ); - System.out.println( - "Bob's balance: " + - new AccountBalanceQuery().setAccountId(bobId).execute(client).hbars - ); - System.out.println( - "Charlie's balance: " + - new AccountBalanceQuery().setAccountId(charlieId).execute(client).hbars - ); + .approveHbarAllowance(aliceId, bobId, Hbar.from(2)) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); + + System.out.println("Alice's balance: " + + new AccountBalanceQuery().setAccountId(aliceId).execute(client).hbars); + System.out.println("Bob's balance: " + + new AccountBalanceQuery().setAccountId(bobId).execute(client).hbars); + System.out.println("Charlie's balance: " + + new AccountBalanceQuery().setAccountId(charlieId).execute(client).hbars); /* * Step 4: * Demonstrate allowance -- transfer 1 Hbar from Alice to Charlie, but the transaction is signed only by Bob * (Bob is dipping into his allowance from Alice). */ - System.out.println("Transferring 1 Hbar from Alice to Charlie, " + - "but the transaction is signed only by Bob (Bob is dipping into his allowance from Alice)..."); + System.out.println("Transferring 1 Hbar from Alice to Charlie, " + + "but the transaction is signed only by Bob (Bob is dipping into his allowance from Alice)..."); new TransferTransaction() - // "addApproved*Transfer()" means that the transfer has been approved by an allowance - .addApprovedHbarTransfer(aliceId, Hbar.from(1).negated()) - .addHbarTransfer(charlieId, Hbar.from(1)) - // The allowance spender must be pay the fee for the transaction. - // use setTransactionId() to set the account ID that will pay the fee for the transaction. - .setTransactionId(TransactionId.generate(bobId)) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + // "addApproved*Transfer()" means that the transfer has been approved by an allowance + .addApprovedHbarTransfer(aliceId, Hbar.from(1).negated()) + .addHbarTransfer(charlieId, Hbar.from(1)) + // The allowance spender must be pay the fee for the transaction. + // use setTransactionId() to set the account ID that will pay the fee for the transaction. + .setTransactionId(TransactionId.generate(bobId)) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); System.out.println("Transfer succeeded. Bob should now have 1 Hbar left in his allowance."); - System.out.println( - "Alice's balance: " + - new AccountBalanceQuery().setAccountId(aliceId).execute(client).hbars - ); - System.out.println( - "Bob's balance: " + - new AccountBalanceQuery().setAccountId(bobId).execute(client).hbars - ); - System.out.println( - "Charlie's balance: " + - new AccountBalanceQuery().setAccountId(charlieId).execute(client).hbars - ); + System.out.println("Alice's balance: " + + new AccountBalanceQuery().setAccountId(aliceId).execute(client).hbars); + System.out.println("Bob's balance: " + + new AccountBalanceQuery().setAccountId(bobId).execute(client).hbars); + System.out.println("Charlie's balance: " + + new AccountBalanceQuery().setAccountId(charlieId).execute(client).hbars); /* * Step 5: @@ -214,17 +179,17 @@ public static void main(String[] args) throws Exception { * This should fail, because there is only 1 Hbar left in Bob's allowance. */ try { - System.out.println("Attempting to transfer 2 Hbar from Alice to Charlie using Bob's allowance... " + - "(this should fail, because there is only 1 Hbar left in Bob's allowance)."); + System.out.println("Attempting to transfer 2 Hbar from Alice to Charlie using Bob's allowance... " + + "(this should fail, because there is only 1 Hbar left in Bob's allowance)."); new TransferTransaction() - .addApprovedHbarTransfer(aliceId, Hbar.from(2).negated()) - .addHbarTransfer(charlieId, Hbar.from(2)) - .setTransactionId(TransactionId.generate(bobId)) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + .addApprovedHbarTransfer(aliceId, Hbar.from(2).negated()) + .addHbarTransfer(charlieId, Hbar.from(2)) + .setTransactionId(TransactionId.generate(bobId)) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); throw new Exception("This transfer shouldn't have succeeded!"); } catch (Throwable error) { @@ -238,77 +203,71 @@ public static void main(String[] args) throws Exception { System.out.println("Adjusting Bob's allowance to 3 Hbar..."); new AccountAllowanceApproveTransaction() - .approveHbarAllowance(aliceId, bobId, Hbar.from(3)) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .approveHbarAllowance(aliceId, bobId, Hbar.from(3)) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); /* * Step 7: * Demonstrate allowance -- transfer 2 Hbar from Alice to Charlie using Bob's allowance again. */ - System.out.println("Attempting to transfer 2 Hbar from Alice to Charlie using Bob's allowance again... " + - "(this time it should succeed)."); + System.out.println("Attempting to transfer 2 Hbar from Alice to Charlie using Bob's allowance again... " + + "(this time it should succeed)."); new TransferTransaction() - .addApprovedHbarTransfer(aliceId, Hbar.from(2).negated()) - .addHbarTransfer(charlieId, Hbar.from(2)) - .setTransactionId(TransactionId.generate(bobId)) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + .addApprovedHbarTransfer(aliceId, Hbar.from(2).negated()) + .addHbarTransfer(charlieId, Hbar.from(2)) + .setTransactionId(TransactionId.generate(bobId)) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); System.out.println("Transfer succeeded."); - System.out.println( - "Alice's balance: " + - new AccountBalanceQuery().setAccountId(aliceId).execute(client).hbars - ); - System.out.println( - "Bob's balance: " + - new AccountBalanceQuery().setAccountId(bobId).execute(client).hbars - ); - System.out.println( - "Charlie's balance: " + - new AccountBalanceQuery().setAccountId(charlieId).execute(client).hbars - ); + System.out.println("Alice's balance: " + + new AccountBalanceQuery().setAccountId(aliceId).execute(client).hbars); + System.out.println("Bob's balance: " + + new AccountBalanceQuery().setAccountId(bobId).execute(client).hbars); + System.out.println("Charlie's balance: " + + new AccountBalanceQuery().setAccountId(charlieId).execute(client).hbars); /* * Clean up: * Delete allowance and created accounts. */ new AccountAllowanceApproveTransaction() - .approveHbarAllowance(aliceId, bobId, Hbar.ZERO) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .approveHbarAllowance(aliceId, bobId, Hbar.ZERO) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(aliceId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(aliceId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(bobId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(bobId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(charlieId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(charliePrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(charlieId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(charliePrivateKey) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountCreateWithHtsExample.java b/examples/src/main/java/org/hiero/sdk/examples/AccountCreateWithHtsExample.java similarity index 70% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountCreateWithHtsExample.java rename to examples/src/main/java/org/hiero/sdk/examples/AccountCreateWithHtsExample.java index fecb71cc0..6b98dd50e 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountCreateWithHtsExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/AccountCreateWithHtsExample.java @@ -1,32 +1,13 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.List; import java.util.Map; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to use auto account creation via HTS assets (HIP-542). @@ -47,12 +28,14 @@ class AccountCreateWithHtsExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -65,7 +48,7 @@ class AccountCreateWithHtsExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -121,21 +104,21 @@ public static void main(String[] args) throws Exception { System.out.println("Creating NFT using the Hedera Token Service..."); TokenCreateTransaction nftCreateTx = new TokenCreateTransaction() - .setTokenName("HIP-542 Example Collection") - .setTokenSymbol("HIP-542") - .setTokenName("HIP-542 NFT") - .setTokenSymbol("HIP542NFT") - .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) - .setDecimals(0) - .setInitialSupply(0) - .setMaxSupply(CIDs.length) - .setTreasuryAccountId(OPERATOR_ID) - .setSupplyType(TokenSupplyType.FINITE) - .setAdminKey(operatorPublicKey) - .setFreezeKey(freezePublicKey) - .setWipeKey(wipePublicKey) - .setSupplyKey(supplyPublicKey) - .freezeWith(client); + .setTokenName("HIP-542 Example Collection") + .setTokenSymbol("HIP-542") + .setTokenName("HIP-542 NFT") + .setTokenSymbol("HIP542NFT") + .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) + .setDecimals(0) + .setInitialSupply(0) + .setMaxSupply(CIDs.length) + .setTreasuryAccountId(OPERATOR_ID) + .setSupplyType(TokenSupplyType.FINITE) + .setAdminKey(operatorPublicKey) + .setFreezeKey(freezePublicKey) + .setWipeKey(wipePublicKey) + .setSupplyKey(supplyPublicKey) + .freezeWith(client); // Sign the transaction with the operator key. TokenCreateTransaction nftCreateTxSigned = nftCreateTx.sign(OPERATOR_KEY); @@ -160,16 +143,17 @@ public static void main(String[] args) throws Exception { byte[] nftMetadata = CIDs[i].getBytes(); TokenMintTransaction nftMintTx = new TokenMintTransaction() - .setTokenId(nftTokenId) - .setMetadata(List.of(nftMetadata)) - .freezeWith(client); + .setTokenId(nftTokenId) + .setMetadata(List.of(nftMetadata)) + .freezeWith(client); TokenMintTransaction nftMintTxSigned = nftMintTx.sign(supplyPrivateKey); TransactionResponse nftMintTxResponse = nftMintTxSigned.execute(client); nftMintTxReceipts[i] = nftMintTxResponse.getReceipt(client); - System.out.println("Minted NFT (token ID: " + nftTokenId + ") with serial: " + nftMintTxReceipts[i].serials.get(0)); + System.out.println( + "Minted NFT (token ID: " + nftTokenId + ") with serial: " + nftMintTxReceipts[i].serials.get(0)); } long exampleNftId = nftMintTxReceipts[0].serials.get(0); @@ -197,8 +181,8 @@ public static void main(String[] args) throws Exception { System.out.println("Transferring NFT to Alice's account..."); TransferTransaction nftTransferTx = new TransferTransaction() - .addNftTransfer(nftTokenId.nft(exampleNftId), OPERATOR_ID, aliceAliasAccountId) - .freezeWith(client); + .addNftTransfer(nftTokenId.nft(exampleNftId), OPERATOR_ID, aliceAliasAccountId) + .freezeWith(client); // Sign the transaction with the operator key. TransferTransaction nftTransferTxSigned = nftTransferTx.sign(OPERATOR_KEY); @@ -213,9 +197,8 @@ public static void main(String[] args) throws Exception { * Step 6: * Get the new account ID from the child record. */ - List nftsInfo = new TokenNftInfoQuery() - .setNftId(nftTokenId.nft(exampleNftId)) - .execute(client); + List nftsInfo = + new TokenNftInfoQuery().setNftId(nftTokenId.nft(exampleNftId)).execute(client); String nftOwnerAccountId_FromChildRecord = nftsInfo.get(0).accountId.toString(); System.out.println("Current owner account ID: " + nftOwnerAccountId_FromChildRecord); @@ -225,9 +208,10 @@ public static void main(String[] args) throws Exception { * Show the normal account ID of account which owns the NFT. */ String nftOwnerAccountId_FromQuery = new AccountInfoQuery() - .setAccountId(aliceAliasAccountId) - .execute(client) - .accountId.toString(); + .setAccountId(aliceAliasAccountId) + .execute(client) + .accountId + .toString(); System.out.println("The \"normal\" account ID of the given alias: " + nftOwnerAccountId_FromQuery); @@ -250,16 +234,16 @@ public static void main(String[] args) throws Exception { System.out.println("Creating Fungible Token using the Hedera Token Service..."); TokenCreateTransaction ftCreateTx = new TokenCreateTransaction() - .setTokenName("HIP-542 Fungible Token") - .setTokenSymbol("HIP542FT") - .setInitialSupply(10_000) // Total supply = 10000 / 10 ^ 2 - .setDecimals(2) - .setTokenType(TokenType.FUNGIBLE_COMMON) - .setTreasuryAccountId(OPERATOR_ID) - .setAutoRenewAccountId(OPERATOR_ID) - .setAdminKey(operatorPublicKey) - .setWipeKey(wipePrivateKey) - .freezeWith(client); + .setTokenName("HIP-542 Fungible Token") + .setTokenSymbol("HIP542FT") + .setInitialSupply(10_000) // Total supply = 10000 / 10 ^ 2 + .setDecimals(2) + .setTokenType(TokenType.FUNGIBLE_COMMON) + .setTreasuryAccountId(OPERATOR_ID) + .setAutoRenewAccountId(OPERATOR_ID) + .setAdminKey(operatorPublicKey) + .setWipeKey(wipePrivateKey) + .freezeWith(client); // Sign the transaction with the operator key. TokenCreateTransaction ftCreateTxSigned = ftCreateTx.sign(OPERATOR_KEY); @@ -295,9 +279,9 @@ public static void main(String[] args) throws Exception { */ System.out.println("Transferring Fungible Token the Bob's account..."); TransferTransaction tokenTransferTx = new TransferTransaction() - .addTokenTransfer(fungibleTokenId, OPERATOR_ID, -10) - .addTokenTransfer(fungibleTokenId, bobAliasAccountId, 10) - .freezeWith(client); + .addTokenTransfer(fungibleTokenId, OPERATOR_ID, -10) + .addTokenTransfer(fungibleTokenId, bobAliasAccountId, 10) + .freezeWith(client); // Sign the transaction with the operator key. TransferTransaction tokenTransferTxSign = tokenTransferTx.sign(OPERATOR_KEY); @@ -313,10 +297,10 @@ public static void main(String[] args) throws Exception { * Get the new account ID from the child record. */ String bobAccountInfo = new AccountInfoQuery() - .setAccountId(bobAliasAccountId) - .execute(client) - .accountId - .toString(); + .setAccountId(bobAliasAccountId) + .execute(client) + .accountId + .toString(); System.out.println("The \"normal\" account ID of the given alias: " + bobAccountInfo); @@ -324,9 +308,8 @@ public static void main(String[] args) throws Exception { * Step 13: * Show the normal account ID of account which owns the NFT. */ - AccountBalance bobAccountBalances = new AccountBalanceQuery() - .setAccountId(bobAliasAccountId) - .execute(client); + AccountBalance bobAccountBalances = + new AccountBalanceQuery().setAccountId(bobAliasAccountId).execute(client); /* * Step 14: @@ -346,59 +329,57 @@ public static void main(String[] args) throws Exception { AccountId nftOwnerAccountId = AccountId.fromString(nftOwnerAccountId_FromQuery); new TokenWipeTransaction() - .setTokenId(nftTokenId) - .addSerial(exampleNftId) - .setAccountId(nftOwnerAccountId) - .freezeWith(client) - .sign(wipePrivateKey) - .execute(client) - .getReceipt(client); + .setTokenId(nftTokenId) + .addSerial(exampleNftId) + .setAccountId(nftOwnerAccountId) + .freezeWith(client) + .sign(wipePrivateKey) + .execute(client) + .getReceipt(client); AccountId bobAccountId = AccountId.fromString(bobAccountInfo); - Map bobsTokens = new AccountBalanceQuery() - .setAccountId(bobAccountId) - .execute(client) - .tokens; + Map bobsTokens = + new AccountBalanceQuery().setAccountId(bobAccountId).execute(client).tokens; new TokenWipeTransaction() - .setTokenId(fungibleTokenId) - .setAmount(bobsTokens.get(fungibleTokenId)) - .setAccountId(bobAccountId) - .freezeWith(client) - .sign(wipePrivateKey) - .execute(client) - .getReceipt(client); + .setTokenId(fungibleTokenId) + .setAmount(bobsTokens.get(fungibleTokenId)) + .setAccountId(bobAccountId) + .freezeWith(client) + .sign(wipePrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(nftOwnerAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(nftOwnerAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(bobAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(bobAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); new TokenDeleteTransaction() - .setTokenId(nftTokenId) - .freezeWith(client) - .sign(OPERATOR_KEY) - .execute(client) - .getReceipt(client); + .setTokenId(nftTokenId) + .freezeWith(client) + .sign(OPERATOR_KEY) + .execute(client) + .getReceipt(client); new TokenDeleteTransaction() - .setTokenId(fungibleTokenId) - .freezeWith(client) - .sign(OPERATOR_KEY) - .execute(client) - .getReceipt(client); + .setTokenId(fungibleTokenId) + .freezeWith(client) + .sign(OPERATOR_KEY) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountCreationWaysExample.java b/examples/src/main/java/org/hiero/sdk/examples/AccountCreationWaysExample.java similarity index 75% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountCreationWaysExample.java rename to examples/src/main/java/org/hiero/sdk/examples/AccountCreationWaysExample.java index b5c3fc552..1bc5ca3f4 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/AccountCreationWaysExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/AccountCreationWaysExample.java @@ -1,27 +1,9 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2023 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.AccountId; -import com.hedera.hashgraph.sdk.PrivateKey; -import com.hedera.hashgraph.sdk.PublicKey; +import org.hiero.sdk.AccountId; +import org.hiero.sdk.PrivateKey; +import org.hiero.sdk.PublicKey; /** * How to create a Hedera account in different ways. diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/AutoCreateAccountTransferTransactionExample.java b/examples/src/main/java/org/hiero/sdk/examples/AutoCreateAccountTransferTransactionExample.java similarity index 70% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/AutoCreateAccountTransferTransactionExample.java rename to examples/src/main/java/org/hiero/sdk/examples/AutoCreateAccountTransferTransactionExample.java index 8b3a54b91..96725edcb 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/AutoCreateAccountTransferTransactionExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/AutoCreateAccountTransferTransactionExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2023 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to use auto account creation (HIP-583). @@ -45,12 +26,14 @@ public class AutoCreateAccountTransferTransactionExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -63,7 +46,7 @@ public class AutoCreateAccountTransferTransactionExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -110,9 +93,9 @@ public static void main(String[] args) throws Exception { * assigned to authorize transfers out of the account. */ TransferTransaction transferTx = new TransferTransaction() - .addHbarTransfer(OPERATOR_ID, Hbar.from(1).negated()) - .addHbarTransfer(AccountId.fromEvmAddress(evmAddress), Hbar.from(1)) - .freezeWith(client); + .addHbarTransfer(OPERATOR_ID, Hbar.from(1).negated()) + .addHbarTransfer(AccountId.fromEvmAddress(evmAddress), Hbar.from(1)) + .freezeWith(client); /* * Step 5: @@ -128,9 +111,9 @@ public static void main(String[] args) throws Exception { * (the AccountCreateTransaction is executed as a child transaction triggered by the TransferTransaction). */ TransactionReceipt transferTxReceipt = new TransactionReceiptQuery() - .setTransactionId(transferTxResponse.transactionId) - .setIncludeChildren(true) - .execute(client); + .setTransactionId(transferTxResponse.transactionId) + .setIncludeChildren(true) + .execute(client); AccountId aliceAccountId = transferTxReceipt.children.get(0).accountId; Objects.requireNonNull(aliceAccountId); @@ -146,9 +129,8 @@ public static void main(String[] args) throws Exception { * - the alias property of the account does not have the public address; * - referred to as a hollow account. */ - AccountInfo aliceAccountInfo_BeforeEnhancing = new AccountInfoQuery() - .setAccountId(aliceAccountId) - .execute(client); + AccountInfo aliceAccountInfo_BeforeEnhancing = + new AccountInfoQuery().setAccountId(aliceAccountId).execute(client); if (((KeyList) aliceAccountInfo_BeforeEnhancing.key).isEmpty()) { System.out.println("The newly created account is a hollow account! (Success)"); @@ -165,13 +147,13 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new topic..."); TransactionReceipt topicCreateTxReceipt = new TopicCreateTransaction() - .setAdminKey(publicKey) - .setTransactionId(TransactionId.generate(aliceAccountId)) - .setTopicMemo("Memo") - .freezeWith(client) - .sign(privateKey) - .execute(client) - .getReceipt(client); + .setAdminKey(publicKey) + .setTransactionId(TransactionId.generate(aliceAccountId)) + .setTopicMemo("Memo") + .freezeWith(client) + .sign(privateKey) + .execute(client) + .getReceipt(client); System.out.println("Created new topic with ID: " + topicCreateTxReceipt.topicId); @@ -179,30 +161,30 @@ public static void main(String[] args) throws Exception { * Step 9: * Get the account info and return public key to show its complete account. */ - AccountInfo aliceAccountInfo_AfterEnhancing = new AccountInfoQuery() - .setAccountId(aliceAccountId) - .execute(client); + AccountInfo aliceAccountInfo_AfterEnhancing = + new AccountInfoQuery().setAccountId(aliceAccountId).execute(client); - System.out.println("The public key of the newly created and now complete account: " + aliceAccountInfo_AfterEnhancing.key); + System.out.println( + "The public key of the newly created and now complete account: " + aliceAccountInfo_AfterEnhancing.key); /* * Clean up: * Delete created account and topic. */ new AccountDeleteTransaction() - .setTransferAccountId(OPERATOR_ID) - .setAccountId(aliceAccountId) - .freezeWith(client) - .sign(privateKey) - .execute(client) - .getReceipt(client); + .setTransferAccountId(OPERATOR_ID) + .setAccountId(aliceAccountId) + .freezeWith(client) + .sign(privateKey) + .execute(client) + .getReceipt(client); new TopicDeleteTransaction() - .setTopicId(topicCreateTxReceipt.topicId) - .freezeWith(client) - .sign(privateKey) - .execute(client) - .getReceipt(client); + .setTopicId(topicCreateTxReceipt.topicId) + .freezeWith(client) + .sign(privateKey) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ChangeRemoveTokenKeys.java b/examples/src/main/java/org/hiero/sdk/examples/ChangeRemoveTokenKeys.java similarity index 64% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ChangeRemoveTokenKeys.java rename to examples/src/main/java/org/hiero/sdk/examples/ChangeRemoveTokenKeys.java index 08a7b9b67..8aae39954 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ChangeRemoveTokenKeys.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ChangeRemoveTokenKeys.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to change or remove existing keys from a token (HIP-540). @@ -48,12 +29,14 @@ class ChangeRemoveTokenKeys { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -66,7 +49,7 @@ class ChangeRemoveTokenKeys { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -106,27 +89,23 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating NFT using the Hedera Token Service..."); var nftTokenId = new TokenCreateTransaction() - .setTokenName("HIP-540 NFT") - .setTokenSymbol("HIP540NFT") - .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) - .setTreasuryAccountId(OPERATOR_ID) - .setAdminKey(adminPublicKey) - .setWipeKey(wipePublicKey) - .setSupplyKey(supplyPublicKey) - .freezeWith(client) - .sign(adminPrivateKey) - .execute(client) - .getReceipt(client) - .tokenId; + .setTokenName("HIP-540 NFT") + .setTokenSymbol("HIP540NFT") + .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) + .setTreasuryAccountId(OPERATOR_ID) + .setAdminKey(adminPublicKey) + .setWipeKey(wipePublicKey) + .setSupplyKey(supplyPublicKey) + .freezeWith(client) + .sign(adminPrivateKey) + .execute(client) + .getReceipt(client) + .tokenId; Objects.requireNonNull(nftTokenId); - var nftInfoBefore = new TokenInfoQuery() - .setTokenId(nftTokenId) - .execute(client); + var nftInfoBefore = new TokenInfoQuery().setTokenId(nftTokenId).execute(client); - if (nftInfoBefore.adminKey != null && - nftInfoBefore.supplyKey != null && - nftInfoBefore.wipeKey != null) { + if (nftInfoBefore.adminKey != null && nftInfoBefore.supplyKey != null && nftInfoBefore.wipeKey != null) { System.out.println("Admin public key in the newly created token: " + nftInfoBefore.adminKey); System.out.println("Supply public key in the newly created token: " + nftInfoBefore.supplyKey); System.out.println("Wipe public key in the newly created token: " + nftInfoBefore.wipeKey); @@ -146,18 +125,17 @@ public static void main(String[] args) throws Exception { var emptyKeyList = new KeyList(); new TokenUpdateTransaction() - .setTokenId(nftTokenId) - .setWipeKey(emptyKeyList) - // It is set by default, but we set it here explicitly for illustration. - .setKeyVerificationMode(TokenKeyValidation.FULL_VALIDATION) - .freezeWith(client) - .sign(adminPrivateKey) - .execute(client) - .getReceipt(client); - - var nftInfoAfterWipeKeyRemoval = new TokenInfoQuery() - .setTokenId(nftTokenId) - .execute(client); + .setTokenId(nftTokenId) + .setWipeKey(emptyKeyList) + // It is set by default, but we set it here explicitly for illustration. + .setKeyVerificationMode(TokenKeyValidation.FULL_VALIDATION) + .freezeWith(client) + .sign(adminPrivateKey) + .execute(client) + .getReceipt(client); + + var nftInfoAfterWipeKeyRemoval = + new TokenInfoQuery().setTokenId(nftTokenId).execute(client); if (nftInfoAfterWipeKeyRemoval.wipeKey == null) { System.out.println("Token Wipe Public Key (after removal): " + nftInfoAfterWipeKeyRemoval.wipeKey); @@ -172,17 +150,16 @@ public static void main(String[] args) throws Exception { System.out.println("Removing the Admin Key...(updating to an empty Key List)."); new TokenUpdateTransaction() - .setTokenId(nftTokenId) - .setAdminKey(emptyKeyList) - .setKeyVerificationMode(TokenKeyValidation.NO_VALIDATION) - .freezeWith(client) - .sign(adminPrivateKey) - .execute(client) - .getReceipt(client); - - var nftInfoAfterAdminKeyRemoval = new TokenInfoQuery() - .setTokenId(nftTokenId) - .execute(client); + .setTokenId(nftTokenId) + .setAdminKey(emptyKeyList) + .setKeyVerificationMode(TokenKeyValidation.NO_VALIDATION) + .freezeWith(client) + .sign(adminPrivateKey) + .execute(client) + .getReceipt(client); + + var nftInfoAfterAdminKeyRemoval = + new TokenInfoQuery().setTokenId(nftTokenId).execute(client); if (nftInfoAfterAdminKeyRemoval.adminKey == null) { System.out.println("Token Admin Public Key (after removal): " + nftInfoAfterAdminKeyRemoval.adminKey); @@ -197,18 +174,17 @@ public static void main(String[] args) throws Exception { System.out.println("Updating the Supply Key...(to the new key)."); new TokenUpdateTransaction() - .setTokenId(nftTokenId) - .setSupplyKey(newSupplyPublicKey) - .setKeyVerificationMode(TokenKeyValidation.FULL_VALIDATION) - .freezeWith(client) - .sign(supplyPrivateKey) - .sign(newSupplyPrivateKey) - .execute(client) - .getReceipt(client); - - var nftInfoAfterSupplyKeyUpdate = new TokenInfoQuery() - .setTokenId(nftTokenId) - .execute(client); + .setTokenId(nftTokenId) + .setSupplyKey(newSupplyPublicKey) + .setKeyVerificationMode(TokenKeyValidation.FULL_VALIDATION) + .freezeWith(client) + .sign(supplyPrivateKey) + .sign(newSupplyPrivateKey) + .execute(client) + .getReceipt(client); + + var nftInfoAfterSupplyKeyUpdate = + new TokenInfoQuery().setTokenId(nftTokenId).execute(client); if (nftInfoAfterSupplyKeyUpdate.supplyKey.equals(newSupplyPublicKey)) { System.out.println("Token Supply Public Key (after update): " + nftInfoAfterSupplyKeyUpdate.supplyKey); @@ -223,17 +199,16 @@ public static void main(String[] args) throws Exception { System.out.println("Removing the Supply Key...(updating to the unusable key)."); new TokenUpdateTransaction() - .setTokenId(nftTokenId) - .setSupplyKey(PublicKey.unusableKey()) - .setKeyVerificationMode(TokenKeyValidation.NO_VALIDATION) - .freezeWith(client) - .sign(newSupplyPrivateKey) - .execute(client) - .getReceipt(client); - - var nftInfoAfterSupplyKeyRemoval = new TokenInfoQuery() - .setTokenId(nftTokenId) - .execute(client); + .setTokenId(nftTokenId) + .setSupplyKey(PublicKey.unusableKey()) + .setKeyVerificationMode(TokenKeyValidation.NO_VALIDATION) + .freezeWith(client) + .sign(newSupplyPrivateKey) + .execute(client) + .getReceipt(client); + + var nftInfoAfterSupplyKeyRemoval = + new TokenInfoQuery().setTokenId(nftTokenId).execute(client); var supplyKeyAfterRemoval = (PublicKey) nftInfoAfterSupplyKeyRemoval.supplyKey; diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ClientHelper.java b/examples/src/main/java/org/hiero/sdk/examples/ClientHelper.java similarity index 51% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ClientHelper.java rename to examples/src/main/java/org/hiero/sdk/examples/ClientHelper.java index 027727722..ca54c30ae 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ClientHelper.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ClientHelper.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2023 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; - -import com.hedera.hashgraph.sdk.AccountId; -import com.hedera.hashgraph.sdk.Client; -import com.hedera.hashgraph.sdk.Hbar; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; import java.util.HashMap; import java.util.List; +import org.hiero.sdk.AccountId; +import org.hiero.sdk.Client; +import org.hiero.sdk.Hbar; public class ClientHelper { @@ -51,7 +32,6 @@ public static Client forLocalNetwork() throws InterruptedException { var network = new HashMap(); network.put(LOCAL_CONSENSUS_NODE_ENDPOINT, LOCAL_CONSENSUS_NODE_ACCOUNT_ID); - return Client.forNetwork(network) - .setMirrorNetwork(List.of(LOCAL_MIRROR_NODE_GRPC_ENDPOINT)); + return Client.forNetwork(network).setMirrorNetwork(List.of(LOCAL_MIRROR_NODE_GRPC_ENDPOINT)); } } diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConsensusPubSubChunkedExample.java b/examples/src/main/java/org/hiero/sdk/examples/ConsensusPubSubChunkedExample.java similarity index 68% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConsensusPubSubChunkedExample.java rename to examples/src/main/java/org/hiero/sdk/examples/ConsensusPubSubChunkedExample.java index 0a295a1a6..06871e386 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConsensusPubSubChunkedExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ConsensusPubSubChunkedExample.java @@ -1,29 +1,9 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; -import io.github.cdimascio.dotenv.Dotenv; +import static java.nio.charset.StandardCharsets.UTF_8; +import io.github.cdimascio.dotenv.Dotenv; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -32,8 +12,9 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; - -import static java.nio.charset.StandardCharsets.UTF_8; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to send large message to the private HCS topic and how to subscribe to the topic to receive it. @@ -51,12 +32,14 @@ class ConsensusPubSubChunkedExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -69,7 +52,7 @@ class ConsensusPubSubChunkedExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -103,12 +86,12 @@ public static void main(String[] args) throws Exception { System.out.println("Creating new topic..."); TopicId hederaTopicID = new TopicCreateTransaction() - .setTopicMemo("hedera-sdk-java/ConsensusPubSubChunkedExample") - .setAdminKey(operatorPublicKey) - .setSubmitKey(submitPublicKey) - .execute(client) - .getReceipt(client) - .topicId; + .setTopicMemo("hedera-sdk-java/ConsensusPubSubChunkedExample") + .setAdminKey(operatorPublicKey) + .setSubmitKey(submitPublicKey) + .execute(client) + .getReceipt(client) + .topicId; Objects.requireNonNull(hederaTopicID); System.out.println("Created new topic with ID: " + hederaTopicID); @@ -126,15 +109,13 @@ public static void main(String[] args) throws Exception { * Hedera mirror node. */ System.out.println("Setting up a mirror client..."); - new TopicMessageQuery() - .setTopicId(hederaTopicID) - .subscribe(client, topicMessage -> { - System.out.println("Topic message received!" + - " | Time: " + topicMessage.consensusTimestamp + - " | Sequence No.: " + topicMessage.sequenceNumber + - " | Size: " + topicMessage.contents.length + " bytes."); - LARGE_MESSAGE_LATCH.countDown(); - }); + new TopicMessageQuery().setTopicId(hederaTopicID).subscribe(client, topicMessage -> { + System.out.println("Topic message received!" + " | Time: " + + topicMessage.consensusTimestamp + " | Sequence No.: " + + topicMessage.sequenceNumber + " | Size: " + + topicMessage.contents.length + " bytes."); + LARGE_MESSAGE_LATCH.countDown(); + }); /* * Step 5: @@ -145,14 +126,14 @@ public static void main(String[] args) throws Exception { // Prepare a message send transaction that requires a submit key from "somewhere else". Transaction topicMessageSubmitTx = new TopicMessageSubmitTransaction() - // This is value 10 by default, - // increasing so large message will "fit". - .setMaxChunks(15) - .setTopicId(hederaTopicID) - .setMessage(largeMessage) - // Sign with the operator or "sender" of the message, - // this is the party who will be charged the transaction fee. - .signWithOperator(client); + // This is value 10 by default, + // increasing so large message will "fit". + .setMaxChunks(15) + .setTopicId(hederaTopicID) + .setMessage(largeMessage) + // Sign with the operator or "sender" of the message, + // this is the party who will be charged the transaction fee. + .signWithOperator(client); // Serialize to bytes, so we can be signed "somewhere else" by the submit key. byte[] transactionBytes = topicMessageSubmitTx.toBytes(); @@ -163,8 +144,11 @@ public static void main(String[] args) throws Exception { // View out the message size from the parsed transaction. // This can be useful to display what we are about to sign. - long transactionMessageSize = ((TopicMessageSubmitTransaction) topicMessageSubmitTx).getMessage().size(); - System.out.println("Preparing to submit a message to the created topic (size of the message: " + transactionMessageSize + " bytes)..."); + long transactionMessageSize = ((TopicMessageSubmitTransaction) topicMessageSubmitTx) + .getMessage() + .size(); + System.out.println("Preparing to submit a message to the created topic (size of the message: " + + transactionMessageSize + " bytes)..."); // Sign with that Submit Key. topicMessageSubmitTx.sign(submitPrivateKey); @@ -179,10 +163,7 @@ public static void main(String[] args) throws Exception { * Clean up: * Delete created topic. */ - new TopicDeleteTransaction() - .setTopicId(hederaTopicID) - .execute(client) - .getReceipt(client); + new TopicDeleteTransaction().setTopicId(hederaTopicID).execute(client).getReceipt(client); client.close(); @@ -197,7 +178,8 @@ public static void main(String[] args) throws Exception { private static String readResources(String filename) { InputStream inputStream = ConsensusPubSubChunkedExample.class.getResourceAsStream(filename); StringBuilder bigContents = new StringBuilder(); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(inputStream), UTF_8))) { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(Objects.requireNonNull(inputStream), UTF_8))) { String line; while ((line = reader.readLine()) != null) { bigContents.append(line).append("\n"); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConsensusPubSubExample.java b/examples/src/main/java/org/hiero/sdk/examples/ConsensusPubSubExample.java similarity index 66% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConsensusPubSubExample.java rename to examples/src/main/java/org/hiero/sdk/examples/ConsensusPubSubExample.java index 61d44e3b9..950394933 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConsensusPubSubExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ConsensusPubSubExample.java @@ -1,34 +1,15 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to operate with a public HCS topic. @@ -50,12 +31,14 @@ class ConsensusPubSubExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -68,7 +51,7 @@ class ConsensusPubSubExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -93,9 +76,8 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new topic..."); - TransactionResponse topicCreateTxResponse = new TopicCreateTransaction() - .setAdminKey(operatorPublicKey) - .execute(client); + TransactionResponse topicCreateTxResponse = + new TopicCreateTransaction().setAdminKey(operatorPublicKey).execute(client); TransactionReceipt transactionReceipt = topicCreateTxResponse.getReceipt(client); TopicId hederaTopicId = Objects.requireNonNull(transactionReceipt.topicId); @@ -114,15 +96,13 @@ public static void main(String[] args) throws Exception { * Hedera mirror node. */ System.out.println("Setting up a mirror client..."); - new TopicMessageQuery() - .setTopicId(hederaTopicId) - .subscribe(client, resp -> { - String messageAsString = new String(resp.contents, StandardCharsets.UTF_8); - System.out.println("Topic message received!" + - " | Time: " + resp.consensusTimestamp + - " | Content: " + messageAsString); - MESSAGES_LATCH.countDown(); - }); + new TopicMessageQuery().setTopicId(hederaTopicId).subscribe(client, resp -> { + String messageAsString = new String(resp.contents, StandardCharsets.UTF_8); + System.out.println("Topic message received!" + " | Time: " + + resp.consensusTimestamp + " | Content: " + + messageAsString); + MESSAGES_LATCH.countDown(); + }); /* * Step 4: @@ -134,10 +114,10 @@ public static void main(String[] args) throws Exception { System.out.println("Publishing message to the topic: " + message); new TopicMessageSubmitTransaction() - .setTopicId(hederaTopicId) - .setMessage(message) - .execute(client) - .getReceipt(client); + .setTopicId(hederaTopicId) + .setMessage(message) + .execute(client) + .getReceipt(client); Thread.sleep(2_000); } @@ -149,10 +129,7 @@ public static void main(String[] args) throws Exception { * Clean up: * Delete created topic. */ - new TopicDeleteTransaction() - .setTopicId(hederaTopicId) - .execute(client) - .getReceipt(client); + new TopicDeleteTransaction().setTopicId(hederaTopicId).execute(client).getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConsensusPubSubWithSubmitKeyExample.java b/examples/src/main/java/org/hiero/sdk/examples/ConsensusPubSubWithSubmitKeyExample.java similarity index 66% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConsensusPubSubWithSubmitKeyExample.java rename to examples/src/main/java/org/hiero/sdk/examples/ConsensusPubSubWithSubmitKeyExample.java index dc92c18c8..348e446d4 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConsensusPubSubWithSubmitKeyExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ConsensusPubSubWithSubmitKeyExample.java @@ -1,29 +1,7 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Objects; @@ -31,6 +9,9 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to operate with a private HCS topic. @@ -54,12 +35,14 @@ class ConsensusPubSubWithSubmitKeyExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -72,7 +55,7 @@ class ConsensusPubSubWithSubmitKeyExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -106,13 +89,14 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new HCS topic..."); TransactionResponse topicCreateTxResponse = new TopicCreateTransaction() - .setTopicMemo("HCS topic with Submit Key") - .setAdminKey(operatorPublicKey) - .setSubmitKey(submitPublicKey) - .execute(client); + .setTopicMemo("HCS topic with Submit Key") + .setAdminKey(operatorPublicKey) + .setSubmitKey(submitPublicKey) + .execute(client); TopicId hederaTopicId = Objects.requireNonNull(topicCreateTxResponse.getReceipt(client).topicId); - System.out.println("Created topic with ID: " + hederaTopicId + " and public ED25519 submit key: " + submitPrivateKey); + System.out.println( + "Created topic with ID: " + hederaTopicId + " and public ED25519 submit key: " + submitPrivateKey); /* * Step 3: @@ -128,15 +112,15 @@ public static void main(String[] args) throws Exception { */ System.out.println("Setting up a mirror client..."); new TopicMessageQuery() - .setTopicId(hederaTopicId) - .setStartTime(Instant.ofEpochSecond(0)) - .subscribe(client, (resp) -> { - String messageAsString = new String(resp.contents, StandardCharsets.UTF_8); - System.out.println("Topic message received!" + - " | Time: " + resp.consensusTimestamp + - " | Content: " + messageAsString); - MESSAGES_LATCH.countDown(); - }); + .setTopicId(hederaTopicId) + .setStartTime(Instant.ofEpochSecond(0)) + .subscribe(client, (resp) -> { + String messageAsString = new String(resp.contents, StandardCharsets.UTF_8); + System.out.println("Topic message received!" + " | Time: " + + resp.consensusTimestamp + " | Content: " + + messageAsString); + MESSAGES_LATCH.countDown(); + }); /* * Step 5: @@ -149,17 +133,16 @@ public static void main(String[] args) throws Exception { System.out.println("Publishing message to the topic: " + message); new TopicMessageSubmitTransaction() - .setTopicId(hederaTopicId) - .setMessage(message) - .freezeWith(client) - - // The transaction is automatically signed by the payer. - // Due to the topic having a submitKey requirement, additionally sign the transaction with that key. - .sign(submitPrivateKey) + .setTopicId(hederaTopicId) + .setMessage(message) + .freezeWith(client) - .execute(client) - .transactionId - .getReceipt(client); + // The transaction is automatically signed by the payer. + // Due to the topic having a submitKey requirement, additionally sign the transaction with that key. + .sign(submitPrivateKey) + .execute(client) + .transactionId + .getReceipt(client); Thread.sleep(2_000); } @@ -171,10 +154,7 @@ public static void main(String[] args) throws Exception { * Clean up: * Delete created topic. */ - new TopicDeleteTransaction() - .setTopicId(hederaTopicId) - .execute(client) - .getReceipt(client); + new TopicDeleteTransaction().setTopicId(hederaTopicId).execute(client).getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConstructClientExample.java b/examples/src/main/java/org/hiero/sdk/examples/ConstructClientExample.java similarity index 80% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConstructClientExample.java rename to examples/src/main/java/org/hiero/sdk/examples/ConstructClientExample.java index e8cef46f1..1437b99b4 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ConstructClientExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ConstructClientExample.java @@ -1,33 +1,14 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.AccountId; -import com.hedera.hashgraph.sdk.Client; -import com.hedera.hashgraph.sdk.NetworkName; -import com.hedera.hashgraph.sdk.PrivateKey; import io.github.cdimascio.dotenv.Dotenv; - -import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; +import javax.annotation.Nullable; +import org.hiero.sdk.AccountId; +import org.hiero.sdk.Client; +import org.hiero.sdk.NetworkName; +import org.hiero.sdk.PrivateKey; /** * How to construct and configure a client in different ways. @@ -87,9 +68,9 @@ public static void main(String[] args) throws Exception { // Let's set the operator on testnetClient. // (The AccountId and PrivateKey here are fake, this is just an example.) testnetClient.setOperator( - AccountId.fromString("0.0.3"), - PrivateKey.fromString("302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e10") - ); + AccountId.fromString("0.0.3"), + PrivateKey.fromString( + "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e10")); // Let's create a client with a custom network. Map customNetwork = new HashMap<>(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ContractHelper.java b/examples/src/main/java/org/hiero/sdk/examples/ContractHelper.java similarity index 91% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ContractHelper.java rename to examples/src/main/java/org/hiero/sdk/examples/ContractHelper.java index 965eb854a..014732f44 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ContractHelper.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ContractHelper.java @@ -1,23 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 -package com.hedera.hashgraph.sdk.examples; +package org.hiero.sdk.examples; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.hedera.hashgraph.sdk.AccountId; -import com.hedera.hashgraph.sdk.Client; -import com.hedera.hashgraph.sdk.ContractCreateFlow; -import com.hedera.hashgraph.sdk.ContractExecuteTransaction; -import com.hedera.hashgraph.sdk.ContractFunctionParameters; -import com.hedera.hashgraph.sdk.ContractFunctionResult; -import com.hedera.hashgraph.sdk.ContractId; -import com.hedera.hashgraph.sdk.Hbar; -import com.hedera.hashgraph.sdk.PrecheckStatusException; -import com.hedera.hashgraph.sdk.PrivateKey; -import com.hedera.hashgraph.sdk.ReceiptStatusException; -import com.hedera.hashgraph.sdk.Status; -import com.hedera.hashgraph.sdk.TransactionId; -import com.hedera.hashgraph.sdk.TransactionRecord; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; @@ -27,6 +13,20 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; +import org.hiero.sdk.AccountId; +import org.hiero.sdk.Client; +import org.hiero.sdk.ContractCreateFlow; +import org.hiero.sdk.ContractExecuteTransaction; +import org.hiero.sdk.ContractFunctionParameters; +import org.hiero.sdk.ContractFunctionResult; +import org.hiero.sdk.ContractId; +import org.hiero.sdk.Hbar; +import org.hiero.sdk.PrecheckStatusException; +import org.hiero.sdk.PrivateKey; +import org.hiero.sdk.ReceiptStatusException; +import org.hiero.sdk.Status; +import org.hiero.sdk.TransactionId; +import org.hiero.sdk.TransactionRecord; /* ContractHelper declutters PrecompileExample.java @@ -36,7 +36,7 @@ Each of these step functions is assumed to take no function parameters, and to return a Hedera ResponseCode which ought to be SUCCESS -- in other words, an int32 with value 22. -See resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/HederaResponseCodes.sol +See resources/org/hiero/sdk/examples/contracts/precompile/HederaResponseCodes.sol If a step takes function parameters, or if its ContractFunctionResult should be validated with a different method, the user can specify a supplier for a particular step with setParameterSupplier(stepIndex, parametersSupplier), diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ContractNoncesExample.java b/examples/src/main/java/org/hiero/sdk/examples/ContractNoncesExample.java similarity index 63% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ContractNoncesExample.java rename to examples/src/main/java/org/hiero/sdk/examples/ContractNoncesExample.java index a3e82db26..24700faef 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ContractNoncesExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ContractNoncesExample.java @@ -1,31 +1,12 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.List; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to check contract nonces and validate HIP-729 behaviour. @@ -47,12 +28,14 @@ class ContractNoncesExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -65,7 +48,7 @@ class ContractNoncesExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -90,12 +73,13 @@ public static void main(String[] args) throws Exception { * Step 1: * Create a file with smart contract bytecode. */ - String contractBytecodeHex = ContractHelper.getBytecodeHex("contracts/parent_deploys_child/parent_deploys_child.json"); + String contractBytecodeHex = + ContractHelper.getBytecodeHex("contracts/parent_deploys_child/parent_deploys_child.json"); TransactionResponse bytecodeFileCreateTxResponse = new FileCreateTransaction() - .setKeys(operatorPublicKey) - .setContents(contractBytecodeHex) - .setMaxTransactionFee(Hbar.from(2)) - .execute(client); + .setKeys(operatorPublicKey) + .setContents(contractBytecodeHex) + .setMaxTransactionFee(Hbar.from(2)) + .execute(client); TransactionReceipt bytecodeFileCreateTxReceipt = bytecodeFileCreateTxResponse.getReceipt(client); FileId bytecodeFileId = bytecodeFileCreateTxReceipt.fileId; @@ -106,11 +90,11 @@ public static void main(String[] args) throws Exception { * Create a smart contract. */ TransactionResponse contractCreateTxResponse = new ContractCreateTransaction() - .setAdminKey(operatorPublicKey) - .setGas(100_000) - .setBytecodeFileId(bytecodeFileId) - .setContractMemo("HIP-729 Contract") - .execute(client); + .setAdminKey(operatorPublicKey) + .setGas(100_000) + .setBytecodeFileId(bytecodeFileId) + .setContractMemo("HIP-729 Contract") + .execute(client); TransactionReceipt contractCreateTxReceipt = contractCreateTxResponse.getReceipt(client); ContractId contractId = contractCreateTxReceipt.contractId; @@ -123,10 +107,8 @@ public static void main(String[] args) throws Exception { * Get a record from a contract create transaction to check contracts nonces. * We expect to see `nonce=2` as we deploy a contract that creates another contract in its constructor. */ - List contractNonces = contractCreateTxResponse. - getRecord(client) - .contractFunctionResult - .contractNonces; + List contractNonces = + contractCreateTxResponse.getRecord(client).contractFunctionResult.contractNonces; System.out.println("Contract nonces: " + contractNonces); @@ -135,11 +117,11 @@ public static void main(String[] args) throws Exception { * Delete created contract. */ new ContractDeleteTransaction() - .setContractId(contractId) - .setTransferAccountId(contractCreateTxReceipt.transactionId.accountId) - .setMaxTransactionFee(Hbar.from(1)) - .execute(client) - .getReceipt(client); + .setContractId(contractId) + .setTransferAccountId(contractCreateTxReceipt.transactionId.accountId) + .setMaxTransactionFee(Hbar.from(1)) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateAccountExample.java b/examples/src/main/java/org/hiero/sdk/examples/CreateAccountExample.java similarity index 65% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateAccountExample.java rename to examples/src/main/java/org/hiero/sdk/examples/CreateAccountExample.java index 1522690ed..02a427bc8 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateAccountExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/CreateAccountExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to create a Hedera account. @@ -40,12 +21,14 @@ class CreateAccountExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -58,7 +41,7 @@ class CreateAccountExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -90,10 +73,10 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new account..."); TransactionResponse accountCreateTxResponse = new AccountCreateTransaction() - // The only required property here is `key`. - .setKey(publicKey) - .setInitialBalance(Hbar.from(1)) - .execute(client); + // The only required property here is `key`. + .setKey(publicKey) + .setInitialBalance(Hbar.from(1)) + .execute(client); // This will wait for the receipt to become available. TransactionReceipt accountCreateTxReceipt = accountCreateTxResponse.getReceipt(client); @@ -106,12 +89,12 @@ public static void main(String[] args) throws Exception { * Delete created account. */ new AccountDeleteTransaction() - .setTransferAccountId(OPERATOR_ID) - .setAccountId(newAccountId) - .freezeWith(client) - .sign(privateKey) - .execute(client) - .getReceipt(client); + .setTransferAccountId(OPERATOR_ID) + .setAccountId(newAccountId) + .freezeWith(client) + .sign(privateKey) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateAccountThresholdKeyExample.java b/examples/src/main/java/org/hiero/sdk/examples/CreateAccountThresholdKeyExample.java similarity index 67% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateAccountThresholdKeyExample.java rename to examples/src/main/java/org/hiero/sdk/examples/CreateAccountThresholdKeyExample.java index f6aaa8da2..3203dfa28 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateAccountThresholdKeyExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/CreateAccountThresholdKeyExample.java @@ -1,31 +1,12 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Collections; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to create a Hedera account with threshold key. @@ -41,12 +22,14 @@ class CreateAccountThresholdKeyExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -59,7 +42,7 @@ class CreateAccountThresholdKeyExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -112,9 +95,9 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new account..."); TransactionResponse accountCreateTxResponse = new AccountCreateTransaction() - .setKey(thresholdKey) - .setInitialBalance(Hbar.from(1)) - .execute(client); + .setKey(thresholdKey) + .setInitialBalance(Hbar.from(1)) + .execute(client); TransactionReceipt accountCreateTxReceipt = accountCreateTxResponse.getReceipt(client); AccountId newAccountId = Objects.requireNonNull(accountCreateTxReceipt.accountId); @@ -127,22 +110,20 @@ public static void main(String[] args) throws Exception { */ System.out.println("Transferring 1 Hbar from a newly created account..."); TransactionResponse transferTxResponse = new TransferTransaction() - .addHbarTransfer(newAccountId, Hbar.from(1).negated()) - .addHbarTransfer(new AccountId(3), Hbar.from(1)) - // To manually sign, you must explicitly build the Transaction. - .freezeWith(client) - // We sign with 2 of the 3 keys. - .sign(privateKeys[0]) - .sign(privateKeys[1]) - .execute(client); + .addHbarTransfer(newAccountId, Hbar.from(1).negated()) + .addHbarTransfer(new AccountId(3), Hbar.from(1)) + // To manually sign, you must explicitly build the Transaction. + .freezeWith(client) + // We sign with 2 of the 3 keys. + .sign(privateKeys[0]) + .sign(privateKeys[1]) + .execute(client); // (Important!) Wait for the transfer to reach the consensus. transferTxResponse.getReceipt(client); - Hbar accountBalanceAfterTransfer = new AccountBalanceQuery() - .setAccountId(newAccountId) - .execute(client) - .hbars; + Hbar accountBalanceAfterTransfer = + new AccountBalanceQuery().setAccountId(newAccountId).execute(client).hbars; System.out.println("New account's Hbar balance after transfer: " + accountBalanceAfterTransfer); @@ -151,13 +132,13 @@ public static void main(String[] args) throws Exception { * Delete created account. */ new AccountDeleteTransaction() - .setTransferAccountId(OPERATOR_ID) - .setAccountId(newAccountId) - .freezeWith(client) - .sign(privateKeys[0]) - .sign(privateKeys[1]) - .execute(client) - .getReceipt(client); + .setTransferAccountId(OPERATOR_ID) + .setAccountId(newAccountId) + .freezeWith(client) + .sign(privateKeys[0]) + .sign(privateKeys[1]) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateAccountWithAliasExample.java b/examples/src/main/java/org/hiero/sdk/examples/CreateAccountWithAliasExample.java similarity index 68% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateAccountWithAliasExample.java rename to examples/src/main/java/org/hiero/sdk/examples/CreateAccountWithAliasExample.java index ac09abc0d..637a67238 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateAccountWithAliasExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/CreateAccountWithAliasExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2023 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to create a Hedera account with alias. @@ -41,12 +22,14 @@ class CreateAccountWithAliasExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -59,7 +42,7 @@ class CreateAccountWithAliasExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -104,10 +87,10 @@ public static void main(String[] args) throws Exception { * Set the EVM address field to the Ethereum public address. */ AccountCreateTransaction accountCreateTx = new AccountCreateTransaction() - .setInitialBalance(Hbar.from(1)) - .setKey(operatorPublicKey) - .setAlias(evmAddress) - .freezeWith(client); + .setInitialBalance(Hbar.from(1)) + .setKey(operatorPublicKey) + .setAlias(evmAddress) + .freezeWith(client); /* * Step 5: @@ -117,19 +100,18 @@ public static void main(String[] args) throws Exception { TransactionResponse accountCreateTxResponse = accountCreateTx.execute(client); AccountId newAccountId = new TransactionReceiptQuery() - .setTransactionId(accountCreateTxResponse.transactionId) - .execute(client) - .accountId; + .setTransactionId(accountCreateTxResponse.transactionId) + .execute(client) + .accountId; Objects.requireNonNull(newAccountId); System.out.println("Created account with ID: " + newAccountId); - /* + /* * Step 6: * Get the AccountInfo and show that the account has contractAccountId. */ - AccountInfo newAccountInfo = new AccountInfoQuery() - .setAccountId(newAccountId) - .execute(client); + AccountInfo newAccountInfo = + new AccountInfoQuery().setAccountId(newAccountId).execute(client); if (newAccountInfo.contractAccountId != null) { System.out.println("The newly account has alias: " + newAccountInfo.contractAccountId); @@ -142,10 +124,10 @@ public static void main(String[] args) throws Exception { * Delete created account. */ new AccountDeleteTransaction() - .setAccountId(newAccountId) - .setTransferAccountId(OPERATOR_ID) - .execute(client) - .getReceipt(client); + .setAccountId(newAccountId) + .setTransferAccountId(OPERATOR_ID) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateFileExample.java b/examples/src/main/java/org/hiero/sdk/examples/CreateFileExample.java similarity index 61% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateFileExample.java rename to examples/src/main/java/org/hiero/sdk/examples/CreateFileExample.java index 06d0076b0..873a93317 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateFileExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/CreateFileExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to create a file. @@ -40,12 +21,14 @@ class CreateFileExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -58,7 +41,7 @@ class CreateFileExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -87,13 +70,13 @@ public static void main(String[] args) throws Exception { System.out.println("Creating new file..."); TransactionResponse fileCreateTxResponse = new FileCreateTransaction() - // Use the same key as the operator to "own" this file. - .setKeys(operatorPublicKey) - .setContents(fileContents) - // The default max fee of 1 Hbar is not enough to create a file (starts around ~1.1 Hbar). - .setMaxTransactionFee(Hbar.from(2)) - .execute(client); - + // Use the same key as the operator to "own" this file. + .setKeys(operatorPublicKey) + .setContents(fileContents) + // The default max fee of 1 Hbar is not enough to create a file (starts around ~1.1 Hbar). + .setMaxTransactionFee(Hbar.from(2)) + .execute(client); + TransactionReceipt fileCreateTxReceipt = fileCreateTxResponse.getReceipt(client); FileId newFileId = fileCreateTxReceipt.fileId; Objects.requireNonNull(newFileId); @@ -103,10 +86,7 @@ public static void main(String[] args) throws Exception { * Clean up: * Delete created file. */ - new FileDeleteTransaction() - .setFileId(newFileId) - .execute(client) - .getReceipt(client); + new FileDeleteTransaction().setFileId(newFileId).execute(client).getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateSimpleContractExample.java b/examples/src/main/java/org/hiero/sdk/examples/CreateSimpleContractExample.java similarity index 65% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateSimpleContractExample.java rename to examples/src/main/java/org/hiero/sdk/examples/CreateSimpleContractExample.java index 83482b17d..9a72bcaee 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateSimpleContractExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/CreateSimpleContractExample.java @@ -1,31 +1,12 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.nio.charset.StandardCharsets; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to create a simple stateless smart contract and call its function. @@ -41,12 +22,14 @@ class CreateSimpleContractExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -59,7 +42,7 @@ class CreateSimpleContractExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -86,11 +69,11 @@ public static void main(String[] args) throws Exception { String contractBytecodeHex = ContractHelper.getBytecodeHex("contracts/hello_world/hello_world.json"); TransactionResponse fileCreateTxResponse = new FileCreateTransaction() - // Use the same key as the operator to "own" this file. - .setKeys(operatorPublicKey) - .setContents(contractBytecodeHex.getBytes(StandardCharsets.UTF_8)) - .setMaxTransactionFee(Hbar.from(2)) - .execute(client); + // Use the same key as the operator to "own" this file. + .setKeys(operatorPublicKey) + .setContents(contractBytecodeHex.getBytes(StandardCharsets.UTF_8)) + .setMaxTransactionFee(Hbar.from(2)) + .execute(client); TransactionReceipt fileCreateTxReceipt = fileCreateTxResponse.getReceipt(client); FileId newFileId = Objects.requireNonNull(fileCreateTxReceipt.fileId); @@ -103,12 +86,12 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new contract..."); TransactionResponse contractCreateTxResponse = new ContractCreateTransaction() - .setGas(100_000) - .setBytecodeFileId(newFileId) - // Set an admin key, so we can delete the contract later. - .setAdminKey(operatorPublicKey) - .setMaxTransactionFee(Hbar.from(16)) - .execute(client); + .setGas(100_000) + .setBytecodeFileId(newFileId) + // Set an admin key, so we can delete the contract later. + .setAdminKey(operatorPublicKey) + .setMaxTransactionFee(Hbar.from(16)) + .execute(client); TransactionReceipt contractCreateTxReceipt = contractCreateTxResponse.getReceipt(client); ContractId newContractId = Objects.requireNonNull(contractCreateTxReceipt.contractId); @@ -121,11 +104,11 @@ public static void main(String[] args) throws Exception { */ System.out.println("Calling contract function \"greet\"..."); ContractFunctionResult contractCallResult = new ContractCallQuery() - .setGas(100_000) - .setContractId(newContractId) - .setFunction("greet") - .setMaxQueryPayment(Hbar.from(1)) - .execute(client); + .setGas(100_000) + .setContractId(newContractId) + .setFunction("greet") + .setMaxQueryPayment(Hbar.from(1)) + .execute(client); if (contractCallResult.errorMessage != null) { throw new Exception("Error calling contract function \"greet\": " + contractCallResult.errorMessage); @@ -139,11 +122,11 @@ public static void main(String[] args) throws Exception { * Delete created contract. */ new ContractDeleteTransaction() - .setContractId(newContractId) - .setTransferAccountId(contractCreateTxResponse.transactionId.accountId) - .setMaxTransactionFee(Hbar.from(1)) - .execute(client) - .getReceipt(client); + .setContractId(newContractId) + .setTransferAccountId(contractCreateTxResponse.transactionId.accountId) + .setMaxTransactionFee(Hbar.from(1)) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateStatefulContractExample.java b/examples/src/main/java/org/hiero/sdk/examples/CreateStatefulContractExample.java similarity index 63% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateStatefulContractExample.java rename to examples/src/main/java/org/hiero/sdk/examples/CreateStatefulContractExample.java index 7a872ae3c..75dfb35d7 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateStatefulContractExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/CreateStatefulContractExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to create a stateful smart contract and call its function. @@ -40,12 +21,14 @@ class CreateStatefulContractExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -58,7 +41,7 @@ class CreateStatefulContractExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -88,10 +71,10 @@ public static void main(String[] args) throws Exception { String contractBytecodeHex = ContractHelper.getBytecodeHex("contracts/stateful/stateful.json"); TransactionResponse fileCreateTxResponse = new FileCreateTransaction() - // Use the same key as the operator to "own" this file. - .setKeys(operatorPublicKey) - .setContents(contractBytecodeHex) - .execute(client); + // Use the same key as the operator to "own" this file. + .setKeys(operatorPublicKey) + .setContents(contractBytecodeHex) + .execute(client); TransactionReceipt fileCreateTxReceipt = fileCreateTxResponse.getReceipt(client); FileId newFileId = Objects.requireNonNull(fileCreateTxReceipt.fileId); @@ -103,14 +86,12 @@ public static void main(String[] args) throws Exception { * Create a smart contract. */ TransactionResponse contractCreateTxResponse = new ContractCreateTransaction() - // Set an Admin Key, so we can delete the contract later. - .setGas(150_000) - .setBytecodeFileId(newFileId) - .setAdminKey(operatorPublicKey) - .setConstructorParameters( - new ContractFunctionParameters() - .addString("Hello from Hedera!")) - .execute(client); + // Set an Admin Key, so we can delete the contract later. + .setGas(150_000) + .setBytecodeFileId(newFileId) + .setAdminKey(operatorPublicKey) + .setConstructorParameters(new ContractFunctionParameters().addString("Hello from Hedera!")) + .execute(client); TransactionReceipt contractCreateTxReceipt = contractCreateTxResponse.getReceipt(client); ContractId newContractId = Objects.requireNonNull(contractCreateTxReceipt.contractId); @@ -123,26 +104,27 @@ public static void main(String[] args) throws Exception { */ System.out.println("Calling contract function \"get_message\"..."); ContractFunctionResult contractCallResult_BeforeSetMessage = new ContractCallQuery() - .setContractId(newContractId) - .setGas(100_000) - .setFunction("get_message") - .setMaxQueryPayment(Hbar.from(1)) - .execute(client); + .setContractId(newContractId) + .setGas(100_000) + .setFunction("get_message") + .setMaxQueryPayment(Hbar.from(1)) + .execute(client); if (contractCallResult_BeforeSetMessage.errorMessage != null) { - throw new Exception("Error calling contract function \"get_message\": " + contractCallResult_BeforeSetMessage.errorMessage); + throw new Exception("Error calling contract function \"get_message\": " + + contractCallResult_BeforeSetMessage.errorMessage); } String contractCallResult_BeforeSetMessage_String = contractCallResult_BeforeSetMessage.getString(0); - System.out.println("Contract call result (\"get_message\" function returned): " + contractCallResult_BeforeSetMessage_String); + System.out.println("Contract call result (\"get_message\" function returned): " + + contractCallResult_BeforeSetMessage_String); System.out.println("Calling contract function \"set_message\"..."); TransactionResponse contractExecuteTxResponse = new ContractExecuteTransaction() - .setContractId(newContractId) - .setGas(100_000) - .setFunction("set_message", new ContractFunctionParameters() - .addString("Hello from hedera again!")) - .execute(client); + .setContractId(newContractId) + .setGas(100_000) + .setFunction("set_message", new ContractFunctionParameters().addString("Hello from hedera again!")) + .execute(client); // If this doesn't throw then we know the contract executed successfully. contractExecuteTxResponse.getReceipt(client); @@ -153,29 +135,31 @@ public static void main(String[] args) throws Exception { */ System.out.println("Calling contract function \"get_message\"..."); ContractFunctionResult contractCallResult_AfterSetMessage = new ContractCallQuery() - .setGas(100_000) - .setContractId(newContractId) - .setFunction("get_message") - .setMaxQueryPayment(Hbar.from(1)) - .execute(client); + .setGas(100_000) + .setContractId(newContractId) + .setFunction("get_message") + .setMaxQueryPayment(Hbar.from(1)) + .execute(client); if (contractCallResult_AfterSetMessage.errorMessage != null) { - throw new Exception("Error calling contract function \"get_message\": " + contractCallResult_AfterSetMessage.errorMessage); + throw new Exception("Error calling contract function \"get_message\": " + + contractCallResult_AfterSetMessage.errorMessage); } String contractCallResult_AfterSetMessage_String = contractCallResult_AfterSetMessage.getString(0); - System.out.println("Contract call result (\"get_message\" function returned): " + contractCallResult_AfterSetMessage_String); + System.out.println("Contract call result (\"get_message\" function returned): " + + contractCallResult_AfterSetMessage_String); /* * Clean up: * Delete created contract. */ new ContractDeleteTransaction() - .setContractId(newContractId) - .setTransferAccountId(contractCreateTxResponse.transactionId.accountId) - .setMaxTransactionFee(Hbar.from(1)) - .execute(client) - .getReceipt(client); + .setContractId(newContractId) + .setTransferAccountId(contractCreateTxResponse.transactionId.accountId) + .setMaxTransactionFee(Hbar.from(1)) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateTopicExample.java b/examples/src/main/java/org/hiero/sdk/examples/CreateTopicExample.java similarity index 65% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateTopicExample.java rename to examples/src/main/java/org/hiero/sdk/examples/CreateTopicExample.java index eff03f1ef..530594ffd 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CreateTopicExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/CreateTopicExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to create a public HCS topic and submit a message to it. @@ -40,12 +21,14 @@ class CreateTopicExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -58,7 +41,7 @@ class CreateTopicExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -83,9 +66,8 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new topic..."); - TransactionResponse topicCreateTxResponse = new TopicCreateTransaction() - .setAdminKey(operatorPublicKey) - .execute(client); + TransactionResponse topicCreateTxResponse = + new TopicCreateTransaction().setAdminKey(operatorPublicKey).execute(client); TransactionReceipt topicCreateTxReceipt = topicCreateTxResponse.getReceipt(client); TopicId topicId = topicCreateTxReceipt.topicId; @@ -98,9 +80,9 @@ public static void main(String[] args) throws Exception { */ System.out.println("Publishing message to the topic..."); TransactionResponse topicMessageSubmitTxResponse = new TopicMessageSubmitTransaction() - .setTopicId(topicCreateTxReceipt.topicId) - .setMessage("Hello World") - .execute(client); + .setTopicId(topicCreateTxReceipt.topicId) + .setMessage("Hello World") + .execute(client); TransactionReceipt topicMessageSubmitTxReceipt = topicMessageSubmitTxResponse.getReceipt(client); System.out.println("Topic sequence number: " + topicMessageSubmitTxReceipt.topicSequenceNumber); @@ -110,9 +92,9 @@ public static void main(String[] args) throws Exception { * Delete created topic. */ new TopicDeleteTransaction() - .setTopicId(topicCreateTxReceipt.topicId) - .execute(client) - .getReceipt(client); + .setTopicId(topicCreateTxReceipt.topicId) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CustomFeesExample.java b/examples/src/main/java/org/hiero/sdk/examples/CustomFeesExample.java similarity index 54% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/CustomFeesExample.java rename to examples/src/main/java/org/hiero/sdk/examples/CustomFeesExample.java index be25d653b..abe1380b8 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/CustomFeesExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/CustomFeesExample.java @@ -1,33 +1,14 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to set and receive custom fees. @@ -43,12 +24,14 @@ class CustomFeesExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -61,7 +44,7 @@ class CustomFeesExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -91,37 +74,37 @@ public static void main(String[] args) throws Exception { PrivateKey alicePrivateKey = PrivateKey.generateED25519(); PublicKey alicePublicKey = alicePrivateKey.getPublicKey(); AccountId aliceAccountId = new AccountCreateTransaction() - .setInitialBalance(initialAccountBalance) - .setKey(alicePublicKey) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client) - .accountId; + .setInitialBalance(initialAccountBalance) + .setKey(alicePublicKey) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(aliceAccountId); PrivateKey bobPrivateKey = PrivateKey.generateED25519(); PublicKey bobPublicKey = bobPrivateKey.getPublicKey(); AccountId bobAccountId = new AccountCreateTransaction() - .setInitialBalance(initialAccountBalance) - .setKey(bobPublicKey) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client) - .accountId; + .setInitialBalance(initialAccountBalance) + .setKey(bobPublicKey) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(bobAccountId); PrivateKey charliePrivateKey = PrivateKey.generateED25519(); PublicKey charliePublicKey = charliePrivateKey.getPublicKey(); AccountId charlieAccountId = new AccountCreateTransaction() - .setInitialBalance(initialAccountBalance) - .setKey(charliePublicKey) - .freezeWith(client) - .sign(charliePrivateKey) - .execute(client) - .getReceipt(client) - .accountId; + .setInitialBalance(initialAccountBalance) + .setKey(charliePublicKey) + .freezeWith(client) + .sign(charliePrivateKey) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(charlieAccountId); System.out.println("Alice's account ID: " + aliceAccountId); @@ -144,9 +127,8 @@ public static void main(String[] args) throws Exception { * To charge a fixed fee in tokens, instead of calling setHbarAmount(), call * setDenominatingTokenId(tokenForFee) and setAmount(tokenFeeAmount). */ - CustomFixedFee customHbarFee = new CustomFixedFee() - .setHbarAmount(Hbar.from(1)) - .setFeeCollectorAccountId(aliceAccountId); + CustomFixedFee customHbarFee = + new CustomFixedFee().setHbarAmount(Hbar.from(1)).setFeeCollectorAccountId(aliceAccountId); List hbarFeeList = Collections.singletonList(customHbarFee); /* @@ -160,29 +142,28 @@ public static void main(String[] args) throws Exception { System.out.println("Creating new Fungible Token using the Hedera Token Service..."); TokenId fungibleTokenId = new TokenCreateTransaction() - .setTokenName("Custom Fees Example Fungible Token") - .setTokenSymbol("CFEFT") - .setAdminKey(alicePublicKey) - .setSupplyKey(alicePublicKey) - .setFeeScheduleKey(alicePublicKey) - .setWipeKey(alicePublicKey) - .setTreasuryAccountId(aliceAccountId) - .setCustomFees(hbarFeeList) - .setInitialSupply(100) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client) - .tokenId; + .setTokenName("Custom Fees Example Fungible Token") + .setTokenSymbol("CFEFT") + .setAdminKey(alicePublicKey) + .setSupplyKey(alicePublicKey) + .setFeeScheduleKey(alicePublicKey) + .setWipeKey(alicePublicKey) + .setTreasuryAccountId(aliceAccountId) + .setCustomFees(hbarFeeList) + .setInitialSupply(100) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client) + .tokenId; Objects.requireNonNull(fungibleTokenId); - TokenInfo fungibleTokenInfo = new TokenInfoQuery() - .setTokenId(fungibleTokenId) - .execute(client); + TokenInfo fungibleTokenInfo = + new TokenInfoQuery().setTokenId(fungibleTokenId).execute(client); System.out.println("Created new fungible token with ID: " + fungibleTokenId + " and custom fees: " - + fungibleTokenInfo.customFees); + + fungibleTokenInfo.customFees); /* * Step 4: @@ -191,20 +172,20 @@ public static void main(String[] args) throws Exception { System.out.println("Associate created fungible token with Bob's and Charlie's accounts..."); new TokenAssociateTransaction() - .setAccountId(bobAccountId) - .setTokenIds(Collections.singletonList(fungibleTokenId)) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(bobAccountId) + .setTokenIds(Collections.singletonList(fungibleTokenId)) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); new TokenAssociateTransaction() - .setAccountId(charlieAccountId) - .setTokenIds(Collections.singletonList(fungibleTokenId)) - .freezeWith(client) - .sign(charliePrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(charlieAccountId) + .setTokenIds(Collections.singletonList(fungibleTokenId)) + .freezeWith(client) + .sign(charliePrivateKey) + .execute(client) + .getReceipt(client); /* * Step 5: @@ -213,21 +194,19 @@ public static void main(String[] args) throws Exception { System.out.println("Transferring all 100 tokens from Alice to Bob..."); new TransferTransaction() - .addTokenTransfer(fungibleTokenId, bobAccountId, 100) - .addTokenTransfer(fungibleTokenId, aliceAccountId, -100) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .addTokenTransfer(fungibleTokenId, bobAccountId, 100) + .addTokenTransfer(fungibleTokenId, aliceAccountId, -100) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); /* * Step 6: * Check Alice's Hbar balance. */ - Hbar aliceAccountBalanceHbars_BeforeCollectingFees = new AccountBalanceQuery() - .setAccountId(aliceAccountId) - .execute(client) - .hbars; + Hbar aliceAccountBalanceHbars_BeforeCollectingFees = + new AccountBalanceQuery().setAccountId(aliceAccountId).execute(client).hbars; if (aliceAccountBalanceHbars_BeforeCollectingFees.equals(initialAccountBalance)) { System.out.println("Alice's Hbar balance before: " + aliceAccountBalanceHbars_BeforeCollectingFees); @@ -242,12 +221,12 @@ public static void main(String[] args) throws Exception { System.out.println("Transferring 20 tokens from Bob to Charlie..."); TransactionRecord transferTxRecord = new TransferTransaction() - .addTokenTransfer(fungibleTokenId, bobAccountId, -20) - .addTokenTransfer(fungibleTokenId, charlieAccountId, 20) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getRecord(client); + .addTokenTransfer(fungibleTokenId, bobAccountId, -20) + .addTokenTransfer(fungibleTokenId, charlieAccountId, 20) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getRecord(client); /* * Step 8: @@ -255,14 +234,12 @@ public static void main(String[] args) throws Exception { * * It should increase, because of the fee taken from the transfer in the previous step. */ - Hbar aliceAccountBalanceHbars_AfterCollectingFees = new AccountBalanceQuery() - .setAccountId(aliceAccountId) - .execute(client) - .hbars; + Hbar aliceAccountBalanceHbars_AfterCollectingFees = + new AccountBalanceQuery().setAccountId(aliceAccountId).execute(client).hbars; if (aliceAccountBalanceHbars_AfterCollectingFees.equals(Hbar.from(2))) { System.out.println("Alice's Hbar balance after Bob transferred 20 tokens to Charlie: " - + aliceAccountBalanceHbars_AfterCollectingFees); + + aliceAccountBalanceHbars_AfterCollectingFees); } else { throw new Exception("Custom fee was not set correctly! (Fail)"); } @@ -284,27 +261,25 @@ public static void main(String[] args) throws Exception { * will be transferred to Alice. */ CustomFractionalFee customFractionalFee = new CustomFractionalFee() - .setNumerator(1) - .setDenominator(10) - .setMin(1) - .setMax(10) - // .setAssessmentMethod(FeeAssessmentMethod.EXCLUSIVE) - .setFeeCollectorAccountId(aliceAccountId); + .setNumerator(1) + .setDenominator(10) + .setMin(1) + .setMax(10) + // .setAssessmentMethod(FeeAssessmentMethod.EXCLUSIVE) + .setFeeCollectorAccountId(aliceAccountId); List fractionalFeeList = Collections.singletonList(customFractionalFee); System.out.println("Updating the custom fees for a fungible token..."); new TokenFeeScheduleUpdateTransaction() - .setTokenId(fungibleTokenId) - .setCustomFees(fractionalFeeList) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .setTokenId(fungibleTokenId) + .setCustomFees(fractionalFeeList) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); - TokenInfo tokenInfo2 = new TokenInfoQuery() - .setTokenId(fungibleTokenId) - .execute(client); + TokenInfo tokenInfo2 = new TokenInfoQuery().setTokenId(fungibleTokenId).execute(client); System.out.println("Updated custom fees: " + tokenInfo2.customFees); @@ -312,13 +287,11 @@ public static void main(String[] args) throws Exception { * Step 10: * Check Alice's token balance. */ - Map aliceAccountBalanceTokens_BeforeCollectingFees = new AccountBalanceQuery() - .setAccountId(aliceAccountId) - .execute(client) - .tokens; + Map aliceAccountBalanceTokens_BeforeCollectingFees = + new AccountBalanceQuery().setAccountId(aliceAccountId).execute(client).tokens; if (aliceAccountBalanceTokens_BeforeCollectingFees.get(fungibleTokenId) == 0) { System.out.println("Alice's token balance before Bob transfers 20 tokens to Charlie: " - + aliceAccountBalanceTokens_BeforeCollectingFees.get(fungibleTokenId)); + + aliceAccountBalanceTokens_BeforeCollectingFees.get(fungibleTokenId)); } else { throw new Exception("Alice's account initial token balance is not zero! (Fail)"); } @@ -330,26 +303,24 @@ public static void main(String[] args) throws Exception { System.out.println("Transferring 20 tokens from Bob to Charlie..."); TransactionRecord transferTxRecord_2 = new TransferTransaction() - .addTokenTransfer(fungibleTokenId, bobAccountId, -20) - .addTokenTransfer(fungibleTokenId, charlieAccountId, 20) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getRecord(client); + .addTokenTransfer(fungibleTokenId, bobAccountId, -20) + .addTokenTransfer(fungibleTokenId, charlieAccountId, 20) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getRecord(client); /* * Step 12: * Check Alice's token balance. It should increase, because of the fee taken from the * transfer in the previous step. */ - Map aliceAccountBalanceTokens_AfterCollectingFees = new AccountBalanceQuery() - .setAccountId(aliceAccountId) - .execute(client) - .tokens; + Map aliceAccountBalanceTokens_AfterCollectingFees = + new AccountBalanceQuery().setAccountId(aliceAccountId).execute(client).tokens; if (aliceAccountBalanceTokens_AfterCollectingFees.get(fungibleTokenId) == 2) { System.out.println("Alice's token balance after Bob transfers 20 tokens to Charlie: " - + aliceAccountBalanceTokens_AfterCollectingFees.get(fungibleTokenId)); + + aliceAccountBalanceTokens_AfterCollectingFees.get(fungibleTokenId)); } else { throw new Exception("Custom fractional fee was not set correctly! (Fail)"); } @@ -364,100 +335,94 @@ public static void main(String[] args) throws Exception { // Move token to operator account. new TokenAssociateTransaction() - .setAccountId(client.getOperatorAccountId()) - .setTokenIds(Collections.singletonList(fungibleTokenId)) - .freezeWith(client) - .sign(OPERATOR_KEY) - .execute(client) - .getReceipt(client); + .setAccountId(client.getOperatorAccountId()) + .setTokenIds(Collections.singletonList(fungibleTokenId)) + .freezeWith(client) + .sign(OPERATOR_KEY) + .execute(client) + .getReceipt(client); new TokenUpdateTransaction() - .setTokenId(fungibleTokenId) - .setAdminKey(OPERATOR_KEY) - .setSupplyKey(OPERATOR_KEY) - .setFeeScheduleKey(OPERATOR_KEY) - .setWipeKey(OPERATOR_KEY) - .setTreasuryAccountId(client.getOperatorAccountId()) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .setTokenId(fungibleTokenId) + .setAdminKey(OPERATOR_KEY) + .setSupplyKey(OPERATOR_KEY) + .setFeeScheduleKey(OPERATOR_KEY) + .setWipeKey(OPERATOR_KEY) + .setTreasuryAccountId(client.getOperatorAccountId()) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); // Wipe token on created accounts. - Map charlieTokensBeforeWipe = new AccountBalanceQuery() - .setAccountId(charlieAccountId) - .execute(client) - .tokens; + Map charlieTokensBeforeWipe = + new AccountBalanceQuery().setAccountId(charlieAccountId).execute(client).tokens; new TokenWipeTransaction() - .setTokenId(fungibleTokenId) - .setAmount(charlieTokensBeforeWipe.get(fungibleTokenId)) - .setAccountId(charlieAccountId) - .freezeWith(client) - .sign(OPERATOR_KEY) - .execute(client) - .getReceipt(client); - - Map bobsTokens = new AccountBalanceQuery() - .setAccountId(bobAccountId) - .execute(client) - .tokens; + .setTokenId(fungibleTokenId) + .setAmount(charlieTokensBeforeWipe.get(fungibleTokenId)) + .setAccountId(charlieAccountId) + .freezeWith(client) + .sign(OPERATOR_KEY) + .execute(client) + .getReceipt(client); + + Map bobsTokens = + new AccountBalanceQuery().setAccountId(bobAccountId).execute(client).tokens; new TokenWipeTransaction() - .setTokenId(fungibleTokenId) - .setAmount(bobsTokens.get(fungibleTokenId)) - .setAccountId(bobAccountId) - .freezeWith(client) - .sign(OPERATOR_KEY) - .execute(client) - .getReceipt(client); - - Map aliceTokensBeforeWipe = new AccountBalanceQuery() - .setAccountId(aliceAccountId) - .execute(client) - .tokens; + .setTokenId(fungibleTokenId) + .setAmount(bobsTokens.get(fungibleTokenId)) + .setAccountId(bobAccountId) + .freezeWith(client) + .sign(OPERATOR_KEY) + .execute(client) + .getReceipt(client); + + Map aliceTokensBeforeWipe = + new AccountBalanceQuery().setAccountId(aliceAccountId).execute(client).tokens; new TokenWipeTransaction() - .setTokenId(fungibleTokenId) - .setAmount(aliceTokensBeforeWipe.get(fungibleTokenId)) - .setAccountId(aliceAccountId) - .freezeWith(client) - .sign(OPERATOR_KEY) - .execute(client) - .getReceipt(client); + .setTokenId(fungibleTokenId) + .setAmount(aliceTokensBeforeWipe.get(fungibleTokenId)) + .setAccountId(aliceAccountId) + .freezeWith(client) + .sign(OPERATOR_KEY) + .execute(client) + .getReceipt(client); // Delete created accounts. new AccountDeleteTransaction() - .setAccountId(charlieAccountId) - .setTransferAccountId(client.getOperatorAccountId()) - .freezeWith(client) - .sign(charliePrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(charlieAccountId) + .setTransferAccountId(client.getOperatorAccountId()) + .freezeWith(client) + .sign(charliePrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(bobAccountId) - .setTransferAccountId(client.getOperatorAccountId()) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(bobAccountId) + .setTransferAccountId(client.getOperatorAccountId()) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(aliceAccountId) - .setTransferAccountId(client.getOperatorAccountId()) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(aliceAccountId) + .setTransferAccountId(client.getOperatorAccountId()) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); // Delete created token. new TokenDeleteTransaction() - .setTokenId(fungibleTokenId) - .freezeWith(client) - .sign(OPERATOR_KEY) - .execute(client) - .getReceipt(client); + .setTokenId(fungibleTokenId) + .freezeWith(client) + .sign(OPERATOR_KEY) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/org/hiero/sdk/examples/DynamicAddressBookExample.java b/examples/src/main/java/org/hiero/sdk/examples/DynamicAddressBookExample.java new file mode 100644 index 000000000..320393427 --- /dev/null +++ b/examples/src/main/java/org/hiero/sdk/examples/DynamicAddressBookExample.java @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; + +import io.github.cdimascio.dotenv.Dotenv; +import java.util.Collections; +import java.util.Objects; +import java.util.concurrent.TimeoutException; +import org.hiero.sdk.AccountId; +import org.hiero.sdk.Client; +import org.hiero.sdk.Endpoint; +import org.hiero.sdk.NodeCreateTransaction; +import org.hiero.sdk.NodeDeleteTransaction; +import org.hiero.sdk.NodeUpdateTransaction; +import org.hiero.sdk.PrecheckStatusException; +import org.hiero.sdk.PrivateKey; +import org.hiero.sdk.ReceiptStatusException; + +/** + * hip-869 + */ +public class DynamicAddressBookExample { + // see `.env.sample` in the repository root for how to specify these values + // or set environment variables with the same names + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + // HEDERA_NETWORK defaults to testnet if not specified in dotenv + private static final String HEDERA_NETWORK = Dotenv.load().get("HEDERA_NETWORK", "testnet"); + + public static void main(String[] args) + throws TimeoutException, PrecheckStatusException, ReceiptStatusException, InterruptedException { + Client client = ClientHelper.forName(HEDERA_NETWORK); + + // Defaults the operator account ID and key such that all generated transactions will be paid for + // by this account and be signed by this key + client.setOperator(OPERATOR_ID, OPERATOR_KEY); + + AccountId accountId = AccountId.fromString("0.0.1999"); + String description = "Hedera™ cryptocurrency"; + String newDescription = "Hedera™ cryptocurrency - updated"; + + // Set up IPv4 address + Endpoint gossipEndpoint = new Endpoint(); + gossipEndpoint.setAddress(new byte[] {0x00, 0x01, 0x02, 0x03}); + + // Set up service endpoint + Endpoint serviceEndpoint = new Endpoint(); + serviceEndpoint.setAddress(new byte[] {0x00, 0x01, 0x02, 0x03}); + + // Generate admin key + PrivateKey adminKey = PrivateKey.generateED25519(); + + // Create node create transaction + NodeCreateTransaction nodeCreateTransaction = new NodeCreateTransaction() + .setAccountId(accountId) + .setDescription(description) + .setGossipCaCertificate("gossipCaCertificate".getBytes()) + .setServiceEndpoints(Collections.singletonList(serviceEndpoint)) + .setGossipEndpoints(Collections.singletonList(gossipEndpoint)) + .setAdminKey(adminKey.getPublicKey()); + + try { + nodeCreateTransaction.execute(client).getReceipt(client); + } catch (Exception e) { + System.out.println(e); + } + + var nodeUpdateTransaction = new NodeUpdateTransaction() + .setNodeId(123) + .setAccountId(accountId) + .setDescription(newDescription) + .setGossipCaCertificate("gossipCaCertificate".getBytes()) + .setServiceEndpoints(Collections.singletonList(serviceEndpoint)) + .setGossipEndpoints(Collections.singletonList(gossipEndpoint)) + .setAdminKey(adminKey.getPublicKey()); + + try { + nodeUpdateTransaction.execute(client).getReceipt(client); + } catch (Exception e) { + System.out.println(e); + } + + var nodeDeleteTransaction = new NodeDeleteTransaction().setNodeId(123); + + try { + nodeDeleteTransaction.execute(client).getReceipt(client); + } catch (Exception e) { + System.out.println(e); + } + } +} diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ExampleTemplate.java b/examples/src/main/java/org/hiero/sdk/examples/ExampleTemplate.java similarity index 67% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ExampleTemplate.java rename to examples/src/main/java/org/hiero/sdk/examples/ExampleTemplate.java index 824093fbf..ae6f5b462 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ExampleTemplate.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ExampleTemplate.java @@ -1,33 +1,14 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; - -import com.hedera.hashgraph.sdk.AccountId; -import com.hedera.hashgraph.sdk.Client; -import com.hedera.hashgraph.sdk.PrivateKey; -import com.hedera.hashgraph.sdk.PublicKey; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; -import io.github.cdimascio.dotenv.Dotenv; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; +import io.github.cdimascio.dotenv.Dotenv; import java.util.Objects; +import org.hiero.sdk.AccountId; +import org.hiero.sdk.Client; +import org.hiero.sdk.PrivateKey; +import org.hiero.sdk.PublicKey; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * This is a template for examples. @@ -53,12 +34,14 @@ class ExampleTemplate { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -71,7 +54,7 @@ class ExampleTemplate { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ExemptCustomFeesExample.java b/examples/src/main/java/org/hiero/sdk/examples/ExemptCustomFeesExample.java similarity index 50% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ExemptCustomFeesExample.java rename to examples/src/main/java/org/hiero/sdk/examples/ExemptCustomFeesExample.java index 00e22ba94..2c41dd4e0 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ExemptCustomFeesExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ExemptCustomFeesExample.java @@ -1,32 +1,13 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.List; import java.util.Map; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to exempt token creators all of their token’s fee collectors from a custom fee (HIP-573). @@ -42,12 +23,14 @@ class ExemptCustomFeesExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -60,7 +43,7 @@ class ExemptCustomFeesExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -88,37 +71,37 @@ public static void main(String[] args) throws Exception { PrivateKey alicePrivateKey = PrivateKey.generateED25519(); PublicKey alicePublicKey = alicePrivateKey.getPublicKey(); AccountId aliceAccountId = new AccountCreateTransaction() - .setInitialBalance(initialBalance) - .setKey(alicePublicKey) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client) - .accountId; + .setInitialBalance(initialBalance) + .setKey(alicePublicKey) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(aliceAccountId); PrivateKey bobPrivateKey = PrivateKey.generateED25519(); PublicKey bobPublicKey = bobPrivateKey.getPublicKey(); AccountId bobAccountId = new AccountCreateTransaction() - .setInitialBalance(initialBalance) - .setKey(bobPublicKey) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client) - .accountId; + .setInitialBalance(initialBalance) + .setKey(bobPublicKey) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(bobAccountId); PrivateKey charilePrivateKey = PrivateKey.generateED25519(); PublicKey charilePublicKey = charilePrivateKey.getPublicKey(); AccountId charlieAccountId = new AccountCreateTransaction() - .setInitialBalance(initialBalance) - .setKey(charilePublicKey) - .freezeWith(client) - .sign(charilePrivateKey) - .execute(client) - .getReceipt(client) - .accountId; + .setInitialBalance(initialBalance) + .setKey(charilePublicKey) + .freezeWith(client) + .sign(charilePrivateKey) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(charlieAccountId); /* @@ -129,43 +112,43 @@ public static void main(String[] args) throws Exception { * - charlieFee sends 3/100 of the transferred value to Charlie's account. */ CustomFractionalFee aliceFee = new CustomFractionalFee() - .setFeeCollectorAccountId(aliceAccountId) - .setNumerator(1) - .setDenominator(100) - .setAllCollectorsAreExempt(true); + .setFeeCollectorAccountId(aliceAccountId) + .setNumerator(1) + .setDenominator(100) + .setAllCollectorsAreExempt(true); CustomFractionalFee bobFee = new CustomFractionalFee() - .setFeeCollectorAccountId(bobAccountId) - .setNumerator(2) - .setDenominator(100) - .setAllCollectorsAreExempt(true); + .setFeeCollectorAccountId(bobAccountId) + .setNumerator(2) + .setDenominator(100) + .setAllCollectorsAreExempt(true); CustomFractionalFee charlieFee = new CustomFractionalFee() - .setFeeCollectorAccountId(charlieAccountId) - .setNumerator(3) - .setDenominator(100) - .setAllCollectorsAreExempt(true); + .setFeeCollectorAccountId(charlieAccountId) + .setNumerator(3) + .setDenominator(100) + .setAllCollectorsAreExempt(true); System.out.println("Creating new Fungible Token using the Hedera Token Service..."); TokenId fungibleTokenId = new TokenCreateTransaction() - .setTokenName("HIP-573 Fungible Token") - .setTokenSymbol("HIP573FT") - .setTokenType(TokenType.FUNGIBLE_COMMON) - .setTreasuryAccountId(OPERATOR_ID) - .setAutoRenewAccountId(OPERATOR_ID) - .setAdminKey(operatorPublicKey) - .setFreezeKey(operatorPublicKey) - .setWipeKey(operatorPublicKey) - .setInitialSupply(100_000_000) - .setDecimals(2) - .setCustomFees(List.of(aliceFee, bobFee, charlieFee)) - .freezeWith(client) - .sign(alicePrivateKey) - .sign(bobPrivateKey) - .sign(charilePrivateKey) - .execute(client) - .getReceipt(client) - .tokenId; + .setTokenName("HIP-573 Fungible Token") + .setTokenSymbol("HIP573FT") + .setTokenType(TokenType.FUNGIBLE_COMMON) + .setTreasuryAccountId(OPERATOR_ID) + .setAutoRenewAccountId(OPERATOR_ID) + .setAdminKey(operatorPublicKey) + .setFreezeKey(operatorPublicKey) + .setWipeKey(operatorPublicKey) + .setInitialSupply(100_000_000) + .setDecimals(2) + .setCustomFees(List.of(aliceFee, bobFee, charlieFee)) + .freezeWith(client) + .sign(alicePrivateKey) + .sign(bobPrivateKey) + .sign(charilePrivateKey) + .execute(client) + .getReceipt(client) + .tokenId; Objects.requireNonNull(fungibleTokenId); System.out.println("Created new fungible token with ID: " + fungibleTokenId); @@ -177,27 +160,25 @@ public static void main(String[] args) throws Exception { */ System.out.println("Transferring 10_000 units of the Fungible Token from the operator's to Bob's account..."); new TransferTransaction() - .addTokenTransfer(fungibleTokenId, OPERATOR_ID, -10_000) - .addTokenTransfer(fungibleTokenId, bobAccountId, 10_000) - .freezeWith(client) - .sign(OPERATOR_KEY) - .execute(client); + .addTokenTransfer(fungibleTokenId, OPERATOR_ID, -10_000) + .addTokenTransfer(fungibleTokenId, bobAccountId, 10_000) + .freezeWith(client) + .sign(OPERATOR_KEY) + .execute(client); System.out.println("Transferring 10_000 units of the Fungible Token from Bob's to Alice's account..."); TransactionResponse transferTxResponse = new TransferTransaction() - .addTokenTransfer(fungibleTokenId, bobAccountId, -10_000) - .addTokenTransfer(fungibleTokenId, aliceAccountId, 10_000) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client); + .addTokenTransfer(fungibleTokenId, bobAccountId, -10_000) + .addTokenTransfer(fungibleTokenId, aliceAccountId, 10_000) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client); /* * Step 4: * Get the transaction fee for that transfer transaction. */ - Hbar transactionFee = transferTxResponse - .getRecord(client) - .transactionFee; + Hbar transactionFee = transferTxResponse.getRecord(client).transactionFee; System.out.println("Transaction fee for the transfer above: " + transactionFee); @@ -207,70 +188,69 @@ public static void main(String[] args) throws Exception { * of the token that was created was not charged a custom fee in the transfer. */ Long aliceAccountBalanceAfter = new AccountBalanceQuery() - .setAccountId(aliceAccountId) - .execute(client) - .tokens.get(fungibleTokenId); + .setAccountId(aliceAccountId) + .execute(client) + .tokens + .get(fungibleTokenId); Long bobAccountBalanceAfter = new AccountBalanceQuery() - .setAccountId(bobAccountId) - .execute(client) - .tokens.get(fungibleTokenId); + .setAccountId(bobAccountId) + .execute(client) + .tokens + .get(fungibleTokenId); Long charlieAccountBalanceAfter = new AccountBalanceQuery() - .setAccountId(charlieAccountId) - .execute(client) - .tokens.get(fungibleTokenId); + .setAccountId(charlieAccountId) + .execute(client) + .tokens + .get(fungibleTokenId); System.out.println("Alice's balance after transferring the fungible token: " + aliceAccountBalanceAfter); System.out.println("Bob's account balance after transferring the fungible token: " + bobAccountBalanceAfter); - System.out.println("Charlie's account balance after transferring the fungible token: " + charlieAccountBalanceAfter); + System.out.println( + "Charlie's account balance after transferring the fungible token: " + charlieAccountBalanceAfter); /* * Clean up: * Delete created accounts and token. */ - Map alicesTokens = new AccountBalanceQuery() - .setAccountId(aliceAccountId) - .execute(client) - .tokens; + Map alicesTokens = + new AccountBalanceQuery().setAccountId(aliceAccountId).execute(client).tokens; new TokenWipeTransaction() - .setTokenId(fungibleTokenId) - .setAmount(alicesTokens.get(fungibleTokenId)) - .setAccountId(aliceAccountId) - .freezeWith(client) - .sign(OPERATOR_KEY) - .execute(client) - .getReceipt(client); + .setTokenId(fungibleTokenId) + .setAmount(alicesTokens.get(fungibleTokenId)) + .setAccountId(aliceAccountId) + .freezeWith(client) + .sign(OPERATOR_KEY) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(aliceAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(aliceAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(bobAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(bobAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(charlieAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(charilePrivateKey) - .execute(client) - .getReceipt(client); - - new TokenDeleteTransaction() - .setTokenId(fungibleTokenId) - .execute(client) - .getReceipt(client); + .setAccountId(charlieAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(charilePrivateKey) + .execute(client) + .getReceipt(client); + + new TokenDeleteTransaction().setTokenId(fungibleTokenId).execute(client).getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/FileAppendChunkedExample.java b/examples/src/main/java/org/hiero/sdk/examples/FileAppendChunkedExample.java similarity index 59% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/FileAppendChunkedExample.java rename to examples/src/main/java/org/hiero/sdk/examples/FileAppendChunkedExample.java index ce8cbf788..aa1e47d45 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/FileAppendChunkedExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/FileAppendChunkedExample.java @@ -1,31 +1,12 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Collections; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to append to already created file. @@ -41,12 +22,14 @@ class FileAppendChunkedExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -59,7 +42,7 @@ class FileAppendChunkedExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -88,12 +71,12 @@ public static void main(String[] args) throws Exception { System.out.println("Creating new file..."); TransactionResponse fileCreateTxResponse = new FileCreateTransaction() - // Use the same key as the operator to "own" this file. - .setKeys(operatorPublicKey) - .setContents(fileContents) - // The default max fee of 1 Hbar is not enough to create a file (starts around ~1.1 Hbar). - .setMaxTransactionFee(Hbar.from(2)) - .execute(client); + // Use the same key as the operator to "own" this file. + .setKeys(operatorPublicKey) + .setContents(fileContents) + // The default max fee of 1 Hbar is not enough to create a file (starts around ~1.1 Hbar). + .setMaxTransactionFee(Hbar.from(2)) + .execute(client); TransactionReceipt fileCreateTxReceipt = fileCreateTxResponse.getReceipt(client); FileId newFileId = fileCreateTxReceipt.fileId; @@ -104,11 +87,10 @@ public static void main(String[] args) throws Exception { * Step 2: * Query file info to check its size after creation. */ - FileInfo fileInfoAfterCreate = new FileInfoQuery() - .setFileId(newFileId) - .execute(client); + FileInfo fileInfoAfterCreate = new FileInfoQuery().setFileId(newFileId).execute(client); - System.out.println("Created file size after create (according to `FileInfoQuery`): " + fileInfoAfterCreate.size + " bytes."); + System.out.println("Created file size after create (according to `FileInfoQuery`): " + fileInfoAfterCreate.size + + " bytes."); /* * Step 3: @@ -125,25 +107,24 @@ public static void main(String[] args) throws Exception { */ System.out.println("Appending new contents to the created file..."); new FileAppendTransaction() - .setNodeAccountIds(Collections.singletonList(fileCreateTxResponse.nodeId)) - .setFileId(newFileId) - .setContents(contents.toString()) - .setMaxChunks(40) - .setMaxTransactionFee(Hbar.from(100)) - .freezeWith(client) - .execute(client) - .getReceipt(client); + .setNodeAccountIds(Collections.singletonList(fileCreateTxResponse.nodeId)) + .setFileId(newFileId) + .setContents(contents.toString()) + .setMaxChunks(40) + .setMaxTransactionFee(Hbar.from(100)) + .freezeWith(client) + .execute(client) + .getReceipt(client); /* * Step 5: * Query file info to check its size after append. */ - FileInfo fileInfoAfterAppend = new FileInfoQuery() - .setFileId(newFileId) - .execute(client); + FileInfo fileInfoAfterAppend = new FileInfoQuery().setFileId(newFileId).execute(client); if (fileInfoAfterCreate.size < fileInfoAfterAppend.size) { - System.out.println("File size after append (according to `FileInfoQuery`): " + fileInfoAfterAppend.size + " bytes."); + System.out.println( + "File size after append (according to `FileInfoQuery`): " + fileInfoAfterAppend.size + " bytes."); } else { throw new Exception("File append was unsuccessful! (Fail)"); } @@ -152,10 +133,7 @@ public static void main(String[] args) throws Exception { * Clean up: * Delete created file. */ - new FileDeleteTransaction() - .setFileId(newFileId) - .execute(client) - .getReceipt(client); + new FileDeleteTransaction().setFileId(newFileId).execute(client).getReceipt(client); client.close(); diff --git a/examples/src/main/java/org/hiero/sdk/examples/GenerateKeyExample.java b/examples/src/main/java/org/hiero/sdk/examples/GenerateKeyExample.java new file mode 100644 index 000000000..5de59ef66 --- /dev/null +++ b/examples/src/main/java/org/hiero/sdk/examples/GenerateKeyExample.java @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; + +import org.hiero.sdk.PrivateKey; +import org.hiero.sdk.PublicKey; + +/** + * How to generate ED25519 key pair. + */ +class GenerateKeyExample { + + public static void main(String[] args) { + System.out.println("Generate ED25519 Private And Public Key Pair Example Start!"); + + System.out.println("Generating the ED25519 private key..."); + PrivateKey privateKey = PrivateKey.generateED25519(); + System.out.println("Private Key: " + privateKey); + + System.out.println("Deriving a public key from the above private key"); + PublicKey publicKey = privateKey.getPublicKey(); + System.out.println("Public key: " + publicKey); + + System.out.println("Generate ED25519 Private And Public Key Pair Example Complete!"); + } +} diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GenerateKeyWithMnemonicExample.java b/examples/src/main/java/org/hiero/sdk/examples/GenerateKeyWithMnemonicExample.java similarity index 68% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/GenerateKeyWithMnemonicExample.java rename to examples/src/main/java/org/hiero/sdk/examples/GenerateKeyWithMnemonicExample.java index e8abd39e3..7f503486f 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GenerateKeyWithMnemonicExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/GenerateKeyWithMnemonicExample.java @@ -1,27 +1,9 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.Mnemonic; -import com.hedera.hashgraph.sdk.PrivateKey; -import com.hedera.hashgraph.sdk.PublicKey; +import org.hiero.sdk.Mnemonic; +import org.hiero.sdk.PrivateKey; +import org.hiero.sdk.PublicKey; /** * How to generate ED25519 key with mnemonic phrase. diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetAccountBalanceExample.java b/examples/src/main/java/org/hiero/sdk/examples/GetAccountBalanceExample.java similarity index 60% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetAccountBalanceExample.java rename to examples/src/main/java/org/hiero/sdk/examples/GetAccountBalanceExample.java index 4255f377d..0c614eb1e 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetAccountBalanceExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/GetAccountBalanceExample.java @@ -1,33 +1,14 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.AccountBalanceQuery; -import com.hedera.hashgraph.sdk.AccountId; -import com.hedera.hashgraph.sdk.Client; -import com.hedera.hashgraph.sdk.Hbar; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.AccountBalanceQuery; +import org.hiero.sdk.AccountId; +import org.hiero.sdk.Client; +import org.hiero.sdk.Hbar; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to get balance of a Hedera account. @@ -43,7 +24,8 @@ class GetAccountBalanceExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -56,7 +38,7 @@ class GetAccountBalanceExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -77,10 +59,8 @@ public static void main(String[] args) throws Exception { * Step 1: * Execute AccountBalanceQuery and output operator's account balance. */ - Hbar operatorsBalance = new AccountBalanceQuery() - .setAccountId(OPERATOR_ID) - .execute(client) - .hbars; + Hbar operatorsBalance = + new AccountBalanceQuery().setAccountId(OPERATOR_ID).execute(client).hbars; System.out.println("Operator's Hbar account balance: " + operatorsBalance); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetAccountInfoExample.java b/examples/src/main/java/org/hiero/sdk/examples/GetAccountInfoExample.java similarity index 61% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetAccountInfoExample.java rename to examples/src/main/java/org/hiero/sdk/examples/GetAccountInfoExample.java index 95adc4b18..061e584ad 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetAccountInfoExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/GetAccountInfoExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to get information about Hedera account. @@ -40,12 +21,14 @@ class GetAccountInfoExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -58,7 +41,7 @@ class GetAccountInfoExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -80,12 +63,13 @@ public static void main(String[] args) throws Exception { * Execute AccountBalanceQuery and output operator's account info. */ AccountInfo operatorsAccountInfo = new AccountInfoQuery() - .setAccountId(OPERATOR_ID) - .setMaxQueryPayment(Hbar.from(1)) - .execute(client); + .setAccountId(OPERATOR_ID) + .setMaxQueryPayment(Hbar.from(1)) + .execute(client); System.out.println("Operator's account public key: " + operatorsAccountInfo.key); - System.out.println("Operator's account require receiver signature: " + operatorsAccountInfo.isReceiverSignatureRequired); + System.out.println( + "Operator's account require receiver signature: " + operatorsAccountInfo.isReceiverSignatureRequired); System.out.println("Operator's account expiration time: " + operatorsAccountInfo.expirationTime); /* diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetAddressBookExample.java b/examples/src/main/java/org/hiero/sdk/examples/GetAddressBookExample.java similarity index 62% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetAddressBookExample.java rename to examples/src/main/java/org/hiero/sdk/examples/GetAddressBookExample.java index 36ce6eee2..ecdab8c1d 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetAddressBookExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/GetAddressBookExample.java @@ -1,36 +1,17 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.AddressBookQuery; -import com.hedera.hashgraph.sdk.Client; -import com.hedera.hashgraph.sdk.FileId; -import com.hedera.hashgraph.sdk.NodeAddressBook; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.io.ByteArrayInputStream; import java.nio.file.FileSystems; import java.nio.file.Files; import java.util.Objects; +import org.hiero.sdk.AddressBookQuery; +import org.hiero.sdk.Client; +import org.hiero.sdk.FileId; +import org.hiero.sdk.NodeAddressBook; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to get the network address book and then inspect node public keys, etc. @@ -53,7 +34,7 @@ class GetAddressBookExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -75,9 +56,8 @@ public static void main(String[] args) throws Exception { */ System.out.println("Getting address book for " + HEDERA_NETWORK + "..."); - NodeAddressBook addressBook = new AddressBookQuery() - .setFileId(FileId.ADDRESS_BOOK) - .execute(client); + NodeAddressBook addressBook = + new AddressBookQuery().setFileId(FileId.ADDRESS_BOOK).execute(client); Objects.requireNonNull(addressBook); System.out.println("Address book for " + HEDERA_NETWORK + ": " + addressBook); @@ -88,8 +68,9 @@ public static void main(String[] args) throws Exception { Files.deleteIfExists(FileSystems.getDefault().getPath("address-book.proto.bin")); client.close(); - Files.copy(new ByteArrayInputStream(addressBook.toBytes().toByteArray()), - FileSystems.getDefault().getPath("address-book.proto.bin")); + Files.copy( + new ByteArrayInputStream(addressBook.toBytes().toByteArray()), + FileSystems.getDefault().getPath("address-book.proto.bin")); System.out.println("Get Address Book Example Complete!"); } diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetExchangeRatesExample.java b/examples/src/main/java/org/hiero/sdk/examples/GetExchangeRatesExample.java similarity index 71% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetExchangeRatesExample.java rename to examples/src/main/java/org/hiero/sdk/examples/GetExchangeRatesExample.java index 1d81bd129..b0b293416 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetExchangeRatesExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/GetExchangeRatesExample.java @@ -1,31 +1,12 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; import com.google.protobuf.ByteString; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to get exchange rates info from the Hedera network. @@ -41,12 +22,14 @@ class GetExchangeRatesExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -59,7 +42,7 @@ class GetExchangeRatesExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -81,9 +64,8 @@ public static void main(String[] args) throws Exception { * Get contents of the file '0.0.112'. It is a system file, where exchange rate is stored. */ System.out.println("Getting contents of the file `0.0.112`..."); - ByteString fileContentsByteString = new FileContentsQuery() - .setFileId(FileId.fromString("0.0.112")) - .execute(client); + ByteString fileContentsByteString = + new FileContentsQuery().setFileId(FileId.fromString("0.0.112")).execute(client); Objects.requireNonNull(fileContentsByteString); /* diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetFileContentsExample.java b/examples/src/main/java/org/hiero/sdk/examples/GetFileContentsExample.java similarity index 63% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetFileContentsExample.java rename to examples/src/main/java/org/hiero/sdk/examples/GetFileContentsExample.java index 9f2750369..fac383e70 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/GetFileContentsExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/GetFileContentsExample.java @@ -1,32 +1,13 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; import com.google.protobuf.ByteString; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.nio.charset.StandardCharsets; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to get file contents. @@ -43,12 +24,14 @@ class GetFileContentsExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -61,7 +44,7 @@ class GetFileContentsExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -90,12 +73,12 @@ public static void main(String[] args) throws Exception { // Create the new file and set its properties. System.out.println("Creating new file..."); TransactionResponse fileCreateTxResponse = new FileCreateTransaction() - // The public key of the owner of the file. - .setKeys(operatorPublicKey) - // Contents of the file. - .setContents(fileContents) - .setMaxTransactionFee(Hbar.from(2)) - .execute(client); + // The public key of the owner of the file. + .setKeys(operatorPublicKey) + // Contents of the file. + .setContents(fileContents) + .setMaxTransactionFee(Hbar.from(2)) + .execute(client); FileId newFileId = Objects.requireNonNull(fileCreateTxResponse.getReceipt(client).fileId); Objects.requireNonNull(newFileId); @@ -105,9 +88,7 @@ public static void main(String[] args) throws Exception { * Step 2: * Get file contents and print them. */ - ByteString contents = new FileContentsQuery() - .setFileId(newFileId) - .execute(client); + ByteString contents = new FileContentsQuery().setFileId(newFileId).execute(client); Objects.requireNonNull(contents); // Prints query results to console. @@ -117,10 +98,7 @@ public static void main(String[] args) throws Exception { * Clean up: * Delete created file. */ - new FileDeleteTransaction() - .setFileId(newFileId) - .execute(client) - .getReceipt(client); + new FileDeleteTransaction().setFileId(newFileId).execute(client).getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/InitializeClientWithMirrorNetworkExample.java b/examples/src/main/java/org/hiero/sdk/examples/InitializeClientWithMirrorNetworkExample.java similarity index 53% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/InitializeClientWithMirrorNetworkExample.java rename to examples/src/main/java/org/hiero/sdk/examples/InitializeClientWithMirrorNetworkExample.java index 20ba0e68b..eb653c4f2 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/InitializeClientWithMirrorNetworkExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/InitializeClientWithMirrorNetworkExample.java @@ -1,35 +1,16 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -package com.hedera.hashgraph.sdk.examples; - -import com.hedera.hashgraph.sdk.AccountCreateTransaction; -import com.hedera.hashgraph.sdk.AccountId; -import com.hedera.hashgraph.sdk.Client; -import com.hedera.hashgraph.sdk.Hbar; -import com.hedera.hashgraph.sdk.PrivateKey; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; import java.util.List; import java.util.Objects; +import org.hiero.sdk.AccountCreateTransaction; +import org.hiero.sdk.AccountId; +import org.hiero.sdk.Client; +import org.hiero.sdk.Hbar; +import org.hiero.sdk.PrivateKey; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; public class InitializeClientWithMirrorNetworkExample { /* @@ -40,21 +21,21 @@ public class InitializeClientWithMirrorNetworkExample { /** * Operator's account ID. Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString( - Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString( - Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * SDK_LOG_LEVEL defaults to SILENT if not specified in dotenv file. Log levels can be: TRACE, DEBUG, INFO, WARN, * ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, for example via VM - * options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -81,11 +62,11 @@ public static void main(String[] args) throws Exception { * Create account */ AccountId aliceId = new AccountCreateTransaction() - .setKey(privateKey) - .setInitialBalance(Hbar.from(5)) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(privateKey) + .setInitialBalance(Hbar.from(5)) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(aliceId); System.out.println("Alice's account ID: " + aliceId); } diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/LoggerFunctionalitiesExample.java b/examples/src/main/java/org/hiero/sdk/examples/LoggerFunctionalitiesExample.java similarity index 62% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/LoggerFunctionalitiesExample.java rename to examples/src/main/java/org/hiero/sdk/examples/LoggerFunctionalitiesExample.java index 27dd7d127..59b5d8f85 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/LoggerFunctionalitiesExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/LoggerFunctionalitiesExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2023 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How SDK Logger works. @@ -41,12 +22,14 @@ public class LoggerFunctionalitiesExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -99,10 +82,10 @@ public static void main(String[] args) throws Exception { */ System.out.println("Transferring Hbar to the the new account..."); new TransferTransaction() - .addHbarTransfer(OPERATOR_ID, Hbar.from(1).negated()) - .addHbarTransfer(aliasAccountId, Hbar.from(1)) - .setTransactionMemo("") - .execute(client); + .addHbarTransfer(OPERATOR_ID, Hbar.from(1).negated()) + .addHbarTransfer(aliasAccountId, Hbar.from(1)) + .setTransactionMemo("") + .execute(client); /* * Step 5: @@ -110,12 +93,12 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new topic...(with attached info logger)."); TopicId hederaTopicId = new TopicCreateTransaction() - .setLogger(infoLogger) - .setTopicMemo("Hedera topic") - .setAdminKey(operatorPublicKey) - .execute(client) - .getReceipt(client) - .topicId; + .setLogger(infoLogger) + .setTopicMemo("Hedera topic") + .setAdminKey(operatorPublicKey) + .execute(client) + .getReceipt(client) + .topicId; Objects.requireNonNull(hederaTopicId); /* @@ -132,12 +115,12 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new topic...(with attached info logger)."); var logisticsTopicId = new TopicCreateTransaction() - .setLogger(infoLogger) - .setTopicMemo("Logistics topic") - .setAdminKey(operatorPublicKey) - .execute(client) - .getReceipt(client) - .topicId; + .setLogger(infoLogger) + .setTopicMemo("Logistics topic") + .setAdminKey(operatorPublicKey) + .execute(client) + .getReceipt(client) + .topicId; Objects.requireNonNull(logisticsTopicId); /* @@ -155,12 +138,12 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new topic...(with attached debug logger)."); var supplyChainTopicId = new TopicCreateTransaction() - .setLogger(debugLogger) - .setTopicMemo("Supply chain topic") - .setAdminKey(operatorPublicKey) - .execute(client) - .getReceipt(client) - .topicId; + .setLogger(debugLogger) + .setTopicMemo("Supply chain topic") + .setAdminKey(operatorPublicKey) + .execute(client) + .getReceipt(client) + .topicId; Objects.requireNonNull(supplyChainTopicId); /* @@ -177,37 +160,31 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new topic...(with attached debug logger)."); var chatTopicId = new TopicCreateTransaction() - .setLogger(debugLogger) - .setTopicMemo("Chat topic") - .setAdminKey(operatorPublicKey) - .execute(client) - .getReceipt(client) - .topicId; + .setLogger(debugLogger) + .setTopicMemo("Chat topic") + .setAdminKey(operatorPublicKey) + .execute(client) + .getReceipt(client) + .topicId; Objects.requireNonNull(chatTopicId); /* * Clean up: * Delete created topics. */ - new TopicDeleteTransaction() - .setTopicId(hederaTopicId) - .execute(client) - .getReceipt(client); + new TopicDeleteTransaction().setTopicId(hederaTopicId).execute(client).getReceipt(client); new TopicDeleteTransaction() - .setTopicId(logisticsTopicId) - .execute(client) - .getReceipt(client); + .setTopicId(logisticsTopicId) + .execute(client) + .getReceipt(client); new TopicDeleteTransaction() - .setTopicId(supplyChainTopicId) - .execute(client) - .getReceipt(client); + .setTopicId(supplyChainTopicId) + .execute(client) + .getReceipt(client); - new TopicDeleteTransaction() - .setTopicId(chatTopicId) - .execute(client) - .getReceipt(client); + new TopicDeleteTransaction().setTopicId(chatTopicId).execute(client).getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/LongTermScheduledTransactionExample.java b/examples/src/main/java/org/hiero/sdk/examples/LongTermScheduledTransactionExample.java similarity index 56% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/LongTermScheduledTransactionExample.java rename to examples/src/main/java/org/hiero/sdk/examples/LongTermScheduledTransactionExample.java index 7c56bfc6f..5ea3a0c95 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/LongTermScheduledTransactionExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/LongTermScheduledTransactionExample.java @@ -1,41 +1,23 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; - -import com.hedera.hashgraph.sdk.AccountBalanceQuery; -import com.hedera.hashgraph.sdk.AccountCreateTransaction; -import com.hedera.hashgraph.sdk.AccountId; -import com.hedera.hashgraph.sdk.AccountUpdateTransaction; -import com.hedera.hashgraph.sdk.Client; -import com.hedera.hashgraph.sdk.Hbar; -import com.hedera.hashgraph.sdk.KeyList; -import com.hedera.hashgraph.sdk.PrivateKey; -import com.hedera.hashgraph.sdk.ScheduleInfo; -import com.hedera.hashgraph.sdk.ScheduleInfoQuery; -import com.hedera.hashgraph.sdk.ScheduleSignTransaction; -import com.hedera.hashgraph.sdk.TransferTransaction; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; + import io.github.cdimascio.dotenv.Dotenv; import java.time.Instant; import java.util.Objects; +import org.hiero.sdk.AccountBalanceQuery; +import org.hiero.sdk.AccountCreateTransaction; +import org.hiero.sdk.AccountId; +import org.hiero.sdk.AccountUpdateTransaction; +import org.hiero.sdk.Client; +import org.hiero.sdk.Hbar; +import org.hiero.sdk.KeyList; +import org.hiero.sdk.PrivateKey; +import org.hiero.sdk.ScheduleInfo; +import org.hiero.sdk.ScheduleInfoQuery; +import org.hiero.sdk.ScheduleSignTransaction; +import org.hiero.sdk.TransferTransaction; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to long term schedule transactions (HIP-423). @@ -50,14 +32,14 @@ class LongTermScheduledTransactionExample { /** * Operator's account ID. Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString( - Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString( - Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. Network can be: localhost, testnet, @@ -70,7 +52,7 @@ class LongTermScheduledTransactionExample { * ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, for example via VM - * options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -95,8 +77,9 @@ public static void main(String[] args) throws Exception { var publicKey1 = privateKey1.getPublicKey(); var privateKey2 = PrivateKey.generateED25519(); - System.out.println("Creating a Key List..." + - "(with threshold, it will require 2 of 2 keys we generated to sign on anything modifying this account)."); + System.out.println( + "Creating a Key List..." + + "(with threshold, it will require 2 of 2 keys we generated to sign on anything modifying this account)."); KeyList thresholdKey = KeyList.withThreshold(2); thresholdKey.add(privateKey1); thresholdKey.add(privateKey2); @@ -108,10 +91,11 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new account...(with the above Key List as an account key)."); var alice = new AccountCreateTransaction() - .setKey(thresholdKey) - .setInitialBalance(new Hbar(2)) - .execute(client) - .getReceipt(client).accountId; + .setKey(thresholdKey) + .setInitialBalance(new Hbar(2)) + .execute(client) + .getReceipt(client) + .accountId; System.out.println("Created new account with ID: " + alice); /* @@ -122,17 +106,16 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new scheduled transaction with 1 day expiry"); TransferTransaction transfer = new TransferTransaction() - .addHbarTransfer(alice, new Hbar(1).negated()) - .addHbarTransfer(client.getOperatorAccountId(), new Hbar(1)); + .addHbarTransfer(alice, new Hbar(1).negated()) + .addHbarTransfer(client.getOperatorAccountId(), new Hbar(1)); int oneDayInSecs = 86400; - var scheduleId = transfer - .schedule() - .setWaitForExpiry(false) - .setExpirationTime(Instant.now().plusSeconds(oneDayInSecs)) - .execute(client) - .getReceipt(client) - .scheduleId; + var scheduleId = transfer.schedule() + .setWaitForExpiry(false) + .setExpirationTime(Instant.now().plusSeconds(oneDayInSecs)) + .execute(client) + .getReceipt(client) + .scheduleId; /* * Step 4: @@ -140,42 +123,34 @@ public static void main(String[] args) throws Exception { */ System.out.println("Signing the new scheduled transaction with 1 key"); new ScheduleSignTransaction() - .setScheduleId(scheduleId) - .freezeWith(client) - .sign(privateKey1) - .execute(client) - .getReceipt(client); - - ScheduleInfo info = new ScheduleInfoQuery() - .setScheduleId(scheduleId) - .execute(client); + .setScheduleId(scheduleId) + .freezeWith(client) + .sign(privateKey1) + .execute(client) + .getReceipt(client); + + ScheduleInfo info = new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client); System.out.println("Scheduled transaction is not yet executed. Executed at: " + info.executedAt); /* * Step 5: * Sign the transaction with the other key and verify the transaction executes successfully */ - var accountBalance = new AccountBalanceQuery() - .setAccountId(alice) - .execute(client); + var accountBalance = new AccountBalanceQuery().setAccountId(alice).execute(client); System.out.println("Alice's account balance before schedule transfer: " + accountBalance.hbars); System.out.println("Signing the new scheduled transaction with the 2nd key"); new ScheduleSignTransaction() - .setScheduleId(scheduleId) - .freezeWith(client) - .sign(privateKey2) - .execute(client) - .getReceipt(client); - - accountBalance = new AccountBalanceQuery() - .setAccountId(alice) - .execute(client); + .setScheduleId(scheduleId) + .freezeWith(client) + .sign(privateKey2) + .execute(client) + .getReceipt(client); + + accountBalance = new AccountBalanceQuery().setAccountId(alice).execute(client); System.out.println("Alice's account balance after schedule transfer: " + accountBalance.hbars); - info = new ScheduleInfoQuery() - .setScheduleId(scheduleId) - .execute(client); + info = new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client); System.out.println("Scheduled transaction is executed. Executed at: " + info.executedAt); /* @@ -185,16 +160,15 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new scheduled transaction with 10 seconds expiry"); transfer = new TransferTransaction() - .addHbarTransfer(alice, new Hbar(1).negated()) - .addHbarTransfer(client.getOperatorAccountId(), new Hbar(1)); - - var scheduleId2 = transfer - .schedule() - .setWaitForExpiry(true) - .setExpirationTime(Instant.now().plusSeconds(10)) - .execute(client) - .getReceipt(client) - .scheduleId; + .addHbarTransfer(alice, new Hbar(1).negated()) + .addHbarTransfer(client.getOperatorAccountId(), new Hbar(1)); + + var scheduleId2 = transfer.schedule() + .setWaitForExpiry(true) + .setExpirationTime(Instant.now().plusSeconds(10)) + .execute(client) + .getReceipt(client) + .scheduleId; long startTime = System.currentTimeMillis(); long elapsedTime = 0; @@ -204,15 +178,13 @@ public static void main(String[] args) throws Exception { */ System.out.println("Signing the new scheduled transaction with 1 key"); new ScheduleSignTransaction() - .setScheduleId(scheduleId2) - .freezeWith(client) - .sign(privateKey1) - .execute(client) - .getReceipt(client); - - info = new ScheduleInfoQuery() - .setScheduleId(scheduleId2) - .execute(client); + .setScheduleId(scheduleId2) + .freezeWith(client) + .sign(privateKey1) + .execute(client) + .getReceipt(client); + + info = new ScheduleInfoQuery().setScheduleId(scheduleId2).execute(client); System.out.println("Scheduled transaction is not yet executed. Executed at: " + info.executedAt); /* @@ -222,21 +194,19 @@ public static void main(String[] args) throws Exception { */ System.out.println("Updating Alice's key to be the 1st key"); new AccountUpdateTransaction() - .setAccountId(alice) - .setKey(publicKey1) - .freezeWith(client) - .sign(privateKey1) - .sign(privateKey2) - .execute(client) - .getReceipt(client); + .setAccountId(alice) + .setKey(publicKey1) + .freezeWith(client) + .sign(privateKey1) + .sign(privateKey2) + .execute(client) + .getReceipt(client); /* * Step 9: * Verify that the transfer successfully executes roughly at the time of its expiration. */ - accountBalance = new AccountBalanceQuery() - .setAccountId(alice) - .execute(client); + accountBalance = new AccountBalanceQuery().setAccountId(alice).execute(client); System.out.println("Alice's account balance before schedule transfer: " + accountBalance.hbars); while (elapsedTime < 10 * 1000) { @@ -244,9 +214,7 @@ public static void main(String[] args) throws Exception { System.out.printf("Elapsed time: %.1f seconds\r", elapsedTime / 1000.0); Thread.sleep(100); // Pause briefly to reduce CPU usage } - accountBalance = new AccountBalanceQuery() - .setAccountId(alice) - .execute(client); + accountBalance = new AccountBalanceQuery().setAccountId(alice).execute(client); System.out.println("Alice's account balance after schedule transfer: " + accountBalance.hbars); System.out.println("Long Term Scheduled Transaction Example Complete!"); diff --git a/examples/src/main/java/org/hiero/sdk/examples/MirrorNodeContractQueriesExample.java b/examples/src/main/java/org/hiero/sdk/examples/MirrorNodeContractQueriesExample.java new file mode 100644 index 000000000..c6ea6a256 --- /dev/null +++ b/examples/src/main/java/org/hiero/sdk/examples/MirrorNodeContractQueriesExample.java @@ -0,0 +1,171 @@ +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; + +import io.github.cdimascio.dotenv.Dotenv; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import org.bouncycastle.util.encoders.Hex; +import org.hiero.sdk.AccountId; +import org.hiero.sdk.Client; +import org.hiero.sdk.ContractCallQuery; +import org.hiero.sdk.ContractCreateTransaction; +import org.hiero.sdk.Hbar; +import org.hiero.sdk.MirrorNodeContractCallQuery; +import org.hiero.sdk.MirrorNodeContractEstimateGasQuery; +import org.hiero.sdk.PrivateKey; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; + +public class MirrorNodeContractQueriesExample { + /* + * See .env.sample in the examples folder root for how to specify values below + * or set environment variables with the same names. + */ + + /** + * Operator's account ID. Used to sign and pay for operations on Hedera. + */ + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + + /** + * Operator's private key. + */ + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + + /** + * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. Network can be: localhost, testnet, + * previewnet or mainnet. + */ + private static final String HEDERA_NETWORK = Dotenv.load().get("HEDERA_NETWORK", "testnet"); + + /** + * SDK_LOG_LEVEL defaults to SILENT if not specified in dotenv file. Log levels can be: TRACE, DEBUG, INFO, WARN, + * ERROR, SILENT. + *

+ * Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, for example via VM + * options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace + */ + private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); + + private static final String SMART_CONTRACT_BYTECODE = + "60806040526040518060400160405280600581526020017f68656c6c6f0000000000000000000000000000000000000000000000000000008152505f90816100479190610293565b50348015610053575f80fd5b50610362565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806100d457607f821691505b6020821081036100e7576100e6610090565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f600883026101497fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8261010e565b610153868361010e565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f61019761019261018d8461016b565b610174565b61016b565b9050919050565b5f819050919050565b6101b08361017d565b6101c46101bc8261019e565b84845461011a565b825550505050565b5f90565b6101d86101cc565b6101e38184846101a7565b505050565b5b81811015610206576101fb5f826101d0565b6001810190506101e9565b5050565b601f82111561024b5761021c816100ed565b610225846100ff565b81016020851015610234578190505b610248610240856100ff565b8301826101e8565b50505b505050565b5f82821c905092915050565b5f61026b5f1984600802610250565b1980831691505092915050565b5f610283838361025c565b9150826002028217905092915050565b61029c82610059565b67ffffffffffffffff8111156102b5576102b4610063565b5b6102bf82546100bd565b6102ca82828561020a565b5f60209050601f8311600181146102fb575f84156102e9578287015190505b6102f38582610278565b86555061035a565b601f198416610309866100ed565b5f5b828110156103305784890151825560018201915060208501945060208101905061030b565b8683101561034d5784890151610349601f89168261025c565b8355505b6001600288020188555050505b505050505050565b6102178061036f5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063ce6d41de1461002d575b5f80fd5b61003561004b565b6040516100429190610164565b60405180910390f35b60605f8054610059906101b1565b80601f0160208091040260200160405190810160405280929190818152602001828054610085906101b1565b80156100d05780601f106100a7576101008083540402835291602001916100d0565b820191905f5260205f20905b8154815290600101906020018083116100b357829003601f168201915b5050505050905090565b5f81519050919050565b5f82825260208201905092915050565b5f5b838110156101115780820151818401526020810190506100f6565b5f8484015250505050565b5f601f19601f8301169050919050565b5f610136826100da565b61014081856100e4565b93506101508185602086016100f4565b6101598161011c565b840191505092915050565b5f6020820190508181035f83015261017c818461012c565b905092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806101c857607f821691505b6020821081036101db576101da610184565b5b5091905056fea26469706673582212202a86c27939bfab6d4a2c61ebbf096d8424e17e22dfdd42320f6e2654863581e964736f6c634300081a0033"; + + public static void main(String[] args) throws Exception { + System.out.println("Mirror Node contract queries Example Start!"); + /* + * Step 0: + * Create and configure the SDK Client. + */ + Client client = ClientHelper.forName(HEDERA_NETWORK); + // All generated transactions will be paid by this account and signed by this key. + client.setOperator(OPERATOR_ID, OPERATOR_KEY); + // Attach logger to the SDK Client. + client.setLogger(new Logger(LogLevel.valueOf(SDK_LOG_LEVEL))); + + /* + * Step 1: + * Create the contract + */ + var response = new ContractCreateTransaction() + .setGas(200_000) + .setBytecode(Hex.decode(SMART_CONTRACT_BYTECODE)) + .setContractMemo("Simple contract with string field") + .execute(client); + + var contractId = Objects.requireNonNull(response.getReceipt(client).contractId); + System.out.println("Created new contract with ID: " + contractId); + + /* + * Step 3: + * Wait for mirror node to import data + */ + Thread.sleep(5000); + + /* + * Step 4: + * Estimate the gas needed + */ + var gas = new MirrorNodeContractEstimateGasQuery() + .setContractId(contractId) + .setSender(client.getOperatorAccountId()) + .setGasLimit(30_000) + .setGasPrice(1234) + .setFunction("getMessage") + .execute(client); + + System.out.println("Gas needed for this query: " + gas); + + /* + * Step 5: + * Do the query against the consensus node using the estimated gas + */ + var callQuery = new ContractCallQuery() + .setContractId(contractId) + .setGas(gas) + .setFunction("getMessage") + .setQueryPayment(new Hbar(1)); + + var result = callQuery.execute(client); + + /* + * Step 6: + * Simulate the transaction for free, using the mirror node + */ + var simulationResult = new MirrorNodeContractCallQuery() + .setContractId(contractId) + .setSender(client.getOperatorAccountId()) + .setGasLimit(30_000) + .setBlockNumber(10000) + .setGasPrice(1234) + .setFunction("getMessage") + .execute(client); + + // Decode the result since it's coming in ABI Hex format from the Mirror Node + var decodedResult = decodeABIHexString(simulationResult); + System.out.println("Simulation result: " + decodedResult); + System.out.println("Contract call result: " + result.getString(0)); + } + + /** + * Decodes a hex-encoded ABI (Application Binary Interface) string into a UTF-8 string. + *

+ * The function assumes the input follows the ABI encoding standard for dynamic data. Specifically, it parses the + * length of the dynamic data and extracts the corresponding substring. + *

+ * The structure of the input hex string is as follows: - The first 64 characters represent metadata, such as + * offsets and other header information. - Characters from index 64 to 128 encode the length of the dynamic data in + * bytes. - Characters from index 128 onward represent the actual dynamic data. + *

+ * This method removes the `0x` prefix if present, parses the length, and decodes the dynamic data into UTF-8. + * + * @param hex the hex string to decode, which follows the ABI encoding standard + * @return the decoded UTF-8 string + */ + private static String decodeABIHexString(String hex) { + // Trim 0x at the beginning + if (hex.startsWith("0x")) { + hex = hex.substring(2); + } + + // Extract the length of the data by parsing the substring from position 64 to 128 as a hexadecimal integer + // This section represents the length of the dynamic data, specifically the number of bytes in the string or + // array + int length = Integer.parseInt(hex.substring(64, 128), 16); + + // Using the extracted length, the code calculates the substring containing the actual data starting from + // position 128. + String hexStringData = hex.substring(128, 128 + length * 2); + + byte[] bytes = new byte[length]; + // Iterate through the extracted hex data, two characters at a time, converting each pair to a byte and storing + // it in a byte array. + for (int i = 0; i < length; i++) { + bytes[i] = (byte) Integer.parseInt(hexStringData.substring(i * 2, i * 2 + 2), 16); + } + + // Convert to UTF 8 + return new String(bytes, StandardCharsets.UTF_8); + } +} diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/MultiAppTransferExample.java b/examples/src/main/java/org/hiero/sdk/examples/MultiAppTransferExample.java similarity index 59% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/MultiAppTransferExample.java rename to examples/src/main/java/org/hiero/sdk/examples/MultiAppTransferExample.java index d3fbe6809..58a317130 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/MultiAppTransferExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/MultiAppTransferExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to transfer Hbar to an account with the receiver signature enabled. @@ -40,12 +21,14 @@ class MultiAppTransferExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -58,7 +41,7 @@ class MultiAppTransferExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -94,35 +77,31 @@ public static void main(String[] args) throws Exception { System.out.println("Creating exchange and receiver accounts..."); // The exchange creates an account for the user to transfer funds to. AccountId exchangeAccountId = new AccountCreateTransaction() - // The exchange only accepts transfers that it validates through a side channel (e.g. REST API). - .setReceiverSignatureRequired(true) - .setKey(exchangePublicKey) - // The owner key has to sign this transaction when setReceiverSignatureRequired is true. - .freezeWith(client) - .sign(exchangePrivateKey) - .execute(client) - .getReceipt(client) - .accountId; + // The exchange only accepts transfers that it validates through a side channel (e.g. REST API). + .setReceiverSignatureRequired(true) + .setKey(exchangePublicKey) + // The owner key has to sign this transaction when setReceiverSignatureRequired is true. + .freezeWith(client) + .sign(exchangePrivateKey) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(exchangeAccountId); // For the purpose of this example we create an account for the user with a balance of 5 Hbar. AccountId userAccountId = new AccountCreateTransaction() - .setInitialBalance(Hbar.from(2)) - .setKey(userPublicKey) - .execute(client) - .getReceipt(client) - .accountId; + .setInitialBalance(Hbar.from(2)) + .setKey(userPublicKey) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(userAccountId); - Hbar senderBalanceBefore = new AccountBalanceQuery() - .setAccountId(userAccountId) - .execute(client) - .hbars; + Hbar senderBalanceBefore = + new AccountBalanceQuery().setAccountId(userAccountId).execute(client).hbars; - Hbar exchangeBalanceBefore = new AccountBalanceQuery() - .setAccountId(exchangeAccountId) - .execute(client) - .hbars; + Hbar exchangeBalanceBefore = + new AccountBalanceQuery().setAccountId(exchangeAccountId).execute(client).hbars; System.out.println("User account (" + userAccountId + ") balance: " + senderBalanceBefore); System.out.println("Exchange account (" + exchangeAccountId + ") balance: " + exchangeBalanceBefore); @@ -132,23 +111,28 @@ public static void main(String[] args) throws Exception { * Make a transfer from the user account to the exchange account, this requires signing by both parties. */ TransferTransaction transferTx = new TransferTransaction() - .addHbarTransfer(userAccountId, Hbar.from(1).negated()) - .addHbarTransfer(exchangeAccountId, Hbar.from(1)) - // The exchange-provided memo required to validate the transaction. - .setTransactionMemo("https://some-exchange.com/user1/account1") - // NOTE: to manually sign, you must freeze the Transaction first - .freezeWith(client) - .sign(userPrivateKey); + .addHbarTransfer(userAccountId, Hbar.from(1).negated()) + .addHbarTransfer(exchangeAccountId, Hbar.from(1)) + // The exchange-provided memo required to validate the transaction. + .setTransactionMemo("https://some-exchange.com/user1/account1") + // NOTE: to manually sign, you must freeze the Transaction first + .freezeWith(client) + .sign(userPrivateKey); // The exchange must sign the transaction in order for it to be accepted by the network // (assume this is some REST call to the exchange API server). - byte[] signedTransferTxBytes = Transaction.fromBytes(transferTx.toBytes()).sign(exchangePrivateKey).toBytes(); + byte[] signedTransferTxBytes = Transaction.fromBytes(transferTx.toBytes()) + .sign(exchangePrivateKey) + .toBytes(); // Parse the transaction bytes returned from the exchange. Transaction signedTransferTx = Transaction.fromBytes(signedTransferTxBytes); // Get the amount we are about to transfer (we built this with +2, -2). - Hbar transferAmount = ((TransferTransaction) signedTransferTx).getHbarTransfers().values().toArray(new Hbar[0])[0]; + Hbar transferAmount = ((TransferTransaction) signedTransferTx) + .getHbarTransfers() + .values() + .toArray(new Hbar[0])[0]; System.out.println("Transferring " + transferAmount + " from the user account to the exchange account..."); @@ -162,15 +146,11 @@ public static void main(String[] args) throws Exception { * Step 4: * Query user and exchange account balance to validate the transfer was successfully complete. */ - Hbar senderBalanceAfter = new AccountBalanceQuery() - .setAccountId(userAccountId) - .execute(client) - .hbars; + Hbar senderBalanceAfter = + new AccountBalanceQuery().setAccountId(userAccountId).execute(client).hbars; - Hbar exchangeBalanceAfter = new AccountBalanceQuery() - .setAccountId(exchangeAccountId) - .execute(client) - .hbars; + Hbar exchangeBalanceAfter = + new AccountBalanceQuery().setAccountId(exchangeAccountId).execute(client).hbars; System.out.println("User account (" + userAccountId + ") balance: " + senderBalanceAfter); System.out.println("Exchange account (" + exchangeAccountId + ") balance: " + exchangeBalanceAfter); @@ -180,20 +160,20 @@ public static void main(String[] args) throws Exception { * Delete created accounts. */ new AccountDeleteTransaction() - .setAccountId(exchangeAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(exchangePrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(exchangeAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(exchangePrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(userAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(userPrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(userAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(userPrivateKey) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/MultiSigOfflineExample.java b/examples/src/main/java/org/hiero/sdk/examples/MultiSigOfflineExample.java similarity index 75% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/MultiSigOfflineExample.java rename to examples/src/main/java/org/hiero/sdk/examples/MultiSigOfflineExample.java index 74899972e..4d95828ae 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/MultiSigOfflineExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/MultiSigOfflineExample.java @@ -1,32 +1,13 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Arrays; import java.util.Collections; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to sign a transaction with multi-sig account. @@ -42,12 +23,14 @@ class MultiSigOfflineExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -60,7 +43,7 @@ class MultiSigOfflineExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -107,9 +90,9 @@ public static void main(String[] args) throws Exception { System.out.println("Creating a new account..."); TransactionResponse createAccountTxResponse = new AccountCreateTransaction() - .setInitialBalance(Hbar.from(2)) - .setKey(keylist) - .execute(client); + .setInitialBalance(Hbar.from(2)) + .setKey(keylist) + .execute(client); TransactionReceipt createAccountTxReceipt = createAccountTxResponse.getReceipt(client); var newAccountId = createAccountTxReceipt.accountId; @@ -122,10 +105,12 @@ public static void main(String[] args) throws Exception { */ System.out.println("Transferring 1 Hbar from new account to the account with ID `0.0.3`..."); TransferTransaction transferTx = new TransferTransaction() - .setNodeAccountIds(Collections.singletonList(new AccountId(3))) - .addHbarTransfer(Objects.requireNonNull(createAccountTxReceipt.accountId), Hbar.from(1).negated()) - .addHbarTransfer(new AccountId(3), Hbar.from(1)) - .freezeWith(client); + .setNodeAccountIds(Collections.singletonList(new AccountId(3))) + .addHbarTransfer( + Objects.requireNonNull(createAccountTxReceipt.accountId), + Hbar.from(1).negated()) + .addHbarTransfer(new AccountId(3), Hbar.from(1)) + .freezeWith(client); /* * Step 3: @@ -167,13 +152,13 @@ public static void main(String[] args) throws Exception { * Delete created account. */ new AccountDeleteTransaction() - .setAccountId(newAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(alicePrivateKey) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(newAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(alicePrivateKey) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/NftAddRemoveAllowancesExample.java b/examples/src/main/java/org/hiero/sdk/examples/NftAddRemoveAllowancesExample.java similarity index 60% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/NftAddRemoveAllowancesExample.java rename to examples/src/main/java/org/hiero/sdk/examples/NftAddRemoveAllowancesExample.java index e45dc96e2..b22bc774d 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/NftAddRemoveAllowancesExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/NftAddRemoveAllowancesExample.java @@ -1,33 +1,14 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to grant another account the right to transfer hbar, fungible and non-fungible tokens from your account (HIP-336). @@ -43,12 +24,14 @@ class NftAddRemoveAllowancesExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -61,7 +44,7 @@ class NftAddRemoveAllowancesExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -95,20 +78,20 @@ public static void main(String[] args) throws Exception { System.out.println("Creating NFT using the Hedera Token Service..."); TransactionReceipt nftCreateTxReceipt = new TokenCreateTransaction() - .setTokenName("HIP-336 NFT1") - .setTokenSymbol("HIP336NFT1") - .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) - .setDecimals(0) - .setInitialSupply(0) - .setMaxSupply(CIDs.length) - .setTreasuryAccountId(OPERATOR_ID) - .setSupplyType(TokenSupplyType.FINITE) - .setAdminKey(operatorPublicKey) - .setSupplyKey(operatorPublicKey) - .setWipeKey(operatorPublicKey) - .freezeWith(client) - .execute(client) - .getReceipt(client); + .setTokenName("HIP-336 NFT1") + .setTokenSymbol("HIP336NFT1") + .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) + .setDecimals(0) + .setInitialSupply(0) + .setMaxSupply(CIDs.length) + .setTreasuryAccountId(OPERATOR_ID) + .setSupplyType(TokenSupplyType.FINITE) + .setAdminKey(operatorPublicKey) + .setSupplyKey(operatorPublicKey) + .setWipeKey(operatorPublicKey) + .freezeWith(client) + .execute(client) + .getReceipt(client); TokenId nftTokenId = nftCreateTxReceipt.tokenId; Objects.requireNonNull(nftTokenId); @@ -122,13 +105,14 @@ public static void main(String[] args) throws Exception { List nftMintTxReceipts = new ArrayList<>(); for (int i = 0; i < CIDs.length; i++) { nftMintTxReceipts.add(new TokenMintTransaction() - .setTokenId(nftTokenId) - .setMetadata(List.of(CIDs[i].getBytes(StandardCharsets.UTF_8))) - .freezeWith(client) - .execute(client) - .getReceipt(client)); - - System.out.println("Minted NFT (token ID: " + nftTokenId + ") with serial: " + nftMintTxReceipts.get(i).serials.get(0)); + .setTokenId(nftTokenId) + .setMetadata(List.of(CIDs[i].getBytes(StandardCharsets.UTF_8))) + .freezeWith(client) + .execute(client) + .getReceipt(client)); + + System.out.println("Minted NFT (token ID: " + nftTokenId + ") with serial: " + + nftMintTxReceipts.get(i).serials.get(0)); } /* @@ -139,22 +123,22 @@ public static void main(String[] args) throws Exception { PrivateKey spenderPrivateKey = PrivateKey.generateECDSA(); PublicKey spenderPublicKey = spenderPrivateKey.getPublicKey(); AccountId spenderAccountId = new AccountCreateTransaction() - .setKey(spenderPublicKey) - .setInitialBalance(Hbar.from(2)) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(spenderPublicKey) + .setInitialBalance(Hbar.from(2)) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(spenderAccountId); System.out.println("Created spender account with ID: " + spenderAccountId); PrivateKey receiverPrivateKey = PrivateKey.generateECDSA(); PublicKey receiverPublicKey = receiverPrivateKey.getPublicKey(); AccountId receiverAccountId = new AccountCreateTransaction() - .setKey(receiverPublicKey) - .setInitialBalance(Hbar.from(2)) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(receiverPublicKey) + .setInitialBalance(Hbar.from(2)) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(receiverAccountId); System.out.println("Created receiver account with ID: " + receiverAccountId); @@ -164,22 +148,24 @@ public static void main(String[] args) throws Exception { */ System.out.println("Associating spender and receiver accounts with the NFT..."); TransactionReceipt spenderAssociateReceipt = new TokenAssociateTransaction() - .setAccountId(spenderAccountId) - .setTokenIds(List.of(nftTokenId)) - .freezeWith(client) - .sign(spenderPrivateKey) - .execute(client) - .getReceipt(client); - System.out.println("Spender association transaction was complete with status: " + spenderAssociateReceipt.status); + .setAccountId(spenderAccountId) + .setTokenIds(List.of(nftTokenId)) + .freezeWith(client) + .sign(spenderPrivateKey) + .execute(client) + .getReceipt(client); + System.out.println( + "Spender association transaction was complete with status: " + spenderAssociateReceipt.status); TransactionReceipt receiverAssociateReceipt = new TokenAssociateTransaction() - .setAccountId(receiverAccountId) - .setTokenIds(List.of(nftTokenId)) - .freezeWith(client) - .sign(receiverPrivateKey) - .execute(client) - .getReceipt(client); - System.out.println("Receiver association transaction was complete with status: " + receiverAssociateReceipt.status); + .setAccountId(receiverAccountId) + .setTokenIds(List.of(nftTokenId)) + .freezeWith(client) + .sign(receiverPrivateKey) + .execute(client) + .getReceipt(client); + System.out.println( + "Receiver association transaction was complete with status: " + receiverAssociateReceipt.status); /* * Step 5: @@ -190,10 +176,10 @@ public static void main(String[] args) throws Exception { System.out.println("Approving spender account allowance for NFT (serials #1 and #2)..."); TransactionReceipt approveReceipt = new AccountAllowanceApproveTransaction() - .approveTokenNftAllowance(nft1, OPERATOR_ID, spenderAccountId) - .approveTokenNftAllowance(nft2, OPERATOR_ID, spenderAccountId) - .execute(client) - .getReceipt(client); + .approveTokenNftAllowance(nft1, OPERATOR_ID, spenderAccountId) + .approveTokenNftAllowance(nft2, OPERATOR_ID, spenderAccountId) + .execute(client) + .getReceipt(client); System.out.println("Approve spender allowance transaction was complete with status: " + approveReceipt.status); /* @@ -207,12 +193,12 @@ public static void main(String[] args) throws Exception { System.out.println("Transferring NFT (serial #1) on behalf of the spender..."); TransactionReceipt approvedSendReceipt = new TransferTransaction() - .addApprovedNftTransfer(nft1, OPERATOR_ID, receiverAccountId) - .setTransactionId(onBehalfOfTransactionId) - .freezeWith(client) - .sign(spenderPrivateKey) - .execute(client) - .getReceipt(client); + .addApprovedNftTransfer(nft1, OPERATOR_ID, receiverAccountId) + .setTransactionId(onBehalfOfTransactionId) + .freezeWith(client) + .sign(spenderPrivateKey) + .execute(client) + .getReceipt(client); System.out.println("Transfer transaction was complete with status: " + approvedSendReceipt.status); /* @@ -221,9 +207,9 @@ public static void main(String[] args) throws Exception { */ System.out.println("Removing all NFT token allowances (for serial #2)..."); TransactionReceipt deleteAllowanceReceipt = new AccountAllowanceDeleteTransaction() - .deleteAllTokenNftAllowances(nft2, OPERATOR_ID) - .execute(client) - .getReceipt(client); + .deleteAllTokenNftAllowances(nft2, OPERATOR_ID) + .execute(client) + .getReceipt(client); System.out.println("Remove allowance transaction was complete with status: " + deleteAllowanceReceipt.status); /* @@ -236,12 +222,12 @@ public static void main(String[] args) throws Exception { try { System.out.println("Transferring NFT (serial #2) on behalf of the spender..."); new TransferTransaction() - .addApprovedNftTransfer(nft2, OPERATOR_ID, receiverAccountId) - .setTransactionId(onBehalfOfTransactionId2) - .freezeWith(client) - .sign(spenderPrivateKey) - .execute(client) - .getReceipt(client); + .addApprovedNftTransfer(nft2, OPERATOR_ID, receiverAccountId) + .setTransactionId(onBehalfOfTransactionId2) + .freezeWith(client) + .sign(spenderPrivateKey) + .execute(client) + .getReceipt(client); } catch (Exception e) { System.out.println("Transferring NFT (serial #2) was failed (as expected): " + e.getMessage()); } @@ -253,7 +239,8 @@ public static void main(String[] args) throws Exception { * The beginning of the second example (approve/delete allowances for ALL serial numbers at once). * Create a fungible HTS token using the Hedera Token Service. */ - System.out.println("The beginning of the second example (approve/delete allowances for ALL serial numbers at once)."); + System.out.println( + "The beginning of the second example (approve/delete allowances for ALL serial numbers at once)."); String[] CIDs2 = { "QmNPCiNA3Dsu3K5FxDPMG5Q3fZRwVTg14EXA92uqEeSRXn", @@ -263,20 +250,20 @@ public static void main(String[] args) throws Exception { System.out.println("Creating NFT using the Hedera Token Service..."); TransactionReceipt nftCreateReceipt2 = new TokenCreateTransaction() - .setTokenName("HIP336NFT2") - .setTokenSymbol("HIP336NFT2") - .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) - .setDecimals(0) - .setInitialSupply(0) - .setMaxSupply(CIDs2.length) - .setTreasuryAccountId(OPERATOR_ID) - .setSupplyType(TokenSupplyType.FINITE) - .setAdminKey(operatorPublicKey) - .setSupplyKey(operatorPublicKey) - .setWipeKey(operatorPublicKey) - .freezeWith(client) - .execute(client) - .getReceipt(client); + .setTokenName("HIP336NFT2") + .setTokenSymbol("HIP336NFT2") + .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) + .setDecimals(0) + .setInitialSupply(0) + .setMaxSupply(CIDs2.length) + .setTreasuryAccountId(OPERATOR_ID) + .setSupplyType(TokenSupplyType.FINITE) + .setAdminKey(operatorPublicKey) + .setSupplyKey(operatorPublicKey) + .setWipeKey(operatorPublicKey) + .freezeWith(client) + .execute(client) + .getReceipt(client); TokenId nftTokenId2 = nftCreateReceipt2.tokenId; Objects.requireNonNull(nftCreateReceipt2); @@ -290,13 +277,14 @@ public static void main(String[] args) throws Exception { List nftCollection2 = new ArrayList<>(); for (int i = 0; i < CIDs2.length; i++) { nftCollection2.add(new TokenMintTransaction() - .setTokenId(nftTokenId2) - .setMetadata(List.of(CIDs2[i].getBytes(StandardCharsets.UTF_8))) - .freezeWith(client) - .execute(client) - .getReceipt(client)); - - System.out.println("Minted NFT (token ID: " + nftTokenId2 + ") with serial: " + nftCollection2.get(i).serials.get(0)); + .setTokenId(nftTokenId2) + .setMetadata(List.of(CIDs2[i].getBytes(StandardCharsets.UTF_8))) + .freezeWith(client) + .execute(client) + .getReceipt(client)); + + System.out.println("Minted NFT (token ID: " + nftTokenId2 + ") with serial: " + + nftCollection2.get(i).serials.get(0)); } /* @@ -307,22 +295,22 @@ public static void main(String[] args) throws Exception { PrivateKey delegatingSpenderPrivateKey = PrivateKey.generateECDSA(); PublicKey delegatingSpenderPublicKey2 = delegatingSpenderPrivateKey.getPublicKey(); AccountId delegatingSpenderAccountId = new AccountCreateTransaction() - .setKey(delegatingSpenderPublicKey2) - .setInitialBalance(Hbar.from(2)) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(delegatingSpenderPublicKey2) + .setInitialBalance(Hbar.from(2)) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(delegatingSpenderAccountId); System.out.println("Created spender account with ID: " + delegatingSpenderAccountId); PrivateKey receiverPrivateKey2 = PrivateKey.generateECDSA(); PublicKey receiverPublicKey2 = receiverPrivateKey2.getPublicKey(); AccountId receiverAccountId2 = new AccountCreateTransaction() - .setKey(receiverPublicKey2) - .setInitialBalance(Hbar.from(2)) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(receiverPublicKey2) + .setInitialBalance(Hbar.from(2)) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(receiverAccountId2); System.out.println("Created receiver account with ID: " + receiverAccountId2); @@ -332,22 +320,24 @@ public static void main(String[] args) throws Exception { */ System.out.println("Associating spender and receiver accounts with the NFT..."); TransactionReceipt spenderAssociateReceipt2 = new TokenAssociateTransaction() - .setAccountId(delegatingSpenderAccountId) - .setTokenIds(List.of(nftTokenId2)) - .freezeWith(client) - .sign(delegatingSpenderPrivateKey) - .execute(client) - .getReceipt(client); - System.out.println("Spender association transaction was complete with status: " + spenderAssociateReceipt2.status); + .setAccountId(delegatingSpenderAccountId) + .setTokenIds(List.of(nftTokenId2)) + .freezeWith(client) + .sign(delegatingSpenderPrivateKey) + .execute(client) + .getReceipt(client); + System.out.println( + "Spender association transaction was complete with status: " + spenderAssociateReceipt2.status); TransactionReceipt receiverAssociateReceipt2 = new TokenAssociateTransaction() - .setAccountId(receiverAccountId2) - .setTokenIds(List.of(nftTokenId2)) - .freezeWith(client) - .sign(receiverPrivateKey2) - .execute(client) - .getReceipt(client); - System.out.println("Receiver association transaction was complete with status: " + receiverAssociateReceipt2.status); + .setAccountId(receiverAccountId2) + .setTokenIds(List.of(nftTokenId2)) + .freezeWith(client) + .sign(receiverPrivateKey2) + .execute(client) + .getReceipt(client); + System.out.println( + "Receiver association transaction was complete with status: " + receiverAssociateReceipt2.status); /* * Step 13: @@ -359,9 +349,9 @@ public static void main(String[] args) throws Exception { System.out.println("Approving spender account allowance for NFT (all serials)..."); TransactionReceipt approveReceipt2 = new AccountAllowanceApproveTransaction() - .approveTokenNftAllowanceAllSerials(nftTokenId2, OPERATOR_ID, delegatingSpenderAccountId) - .execute(client) - .getReceipt(client); + .approveTokenNftAllowanceAllSerials(nftTokenId2, OPERATOR_ID, delegatingSpenderAccountId) + .execute(client) + .getReceipt(client); System.out.println("Approve spender allowance transaction was complete with status: " + approveReceipt2.status); /* @@ -372,11 +362,11 @@ public static void main(String[] args) throws Exception { PrivateKey spenderPrivateKey2 = PrivateKey.generateECDSA(); PublicKey spenderPublicKey2 = spenderPrivateKey2.getPublicKey(); AccountId spenderAccountId2 = new AccountCreateTransaction() - .setKey(spenderPublicKey2) - .setInitialBalance(Hbar.from(2)) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(spenderPublicKey2) + .setInitialBalance(Hbar.from(2)) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(spenderAccountId2); System.out.println("Created delegate spender account with ID: : " + spenderAccountId2); @@ -384,14 +374,16 @@ public static void main(String[] args) throws Exception { * Step 15: * Give delegatingSpender allowance for NFT with serial #3 on behalf of spender account which has approveForAll rights. */ - System.out.println("Approving delegate spender account allowance for NFT (serial #3) on behalf of spender account which has `approveForAll` rights..."); + System.out.println( + "Approving delegate spender account allowance for NFT (serial #3) on behalf of spender account which has `approveForAll` rights..."); TransactionReceipt approveDelegateAllowanceReceipt = new AccountAllowanceApproveTransaction() - .approveTokenNftAllowance(example2Nft3, OPERATOR_ID, spenderAccountId2, delegatingSpenderAccountId) - .freezeWith(client) - .sign(delegatingSpenderPrivateKey) - .execute(client) - .getReceipt(client); - System.out.println("Approve delegated spender allowance for serial 3 - status: " + approveDelegateAllowanceReceipt.status); + .approveTokenNftAllowance(example2Nft3, OPERATOR_ID, spenderAccountId2, delegatingSpenderAccountId) + .freezeWith(client) + .sign(delegatingSpenderPrivateKey) + .execute(client) + .getReceipt(client); + System.out.println( + "Approve delegated spender allowance for serial 3 - status: " + approveDelegateAllowanceReceipt.status); /* * Step 16: @@ -404,12 +396,12 @@ public static void main(String[] args) throws Exception { TransactionId delegatedOnBehalfOfTxId = TransactionId.generate(spenderAccountId2); TransactionReceipt delegatedSendTx = new TransferTransaction() - .addApprovedNftTransfer(example2Nft3, OPERATOR_ID, receiverAccountId2) - .setTransactionId(delegatedOnBehalfOfTxId) - .freezeWith(client) - .sign(spenderPrivateKey2) - .execute(client) - .getReceipt(client); + .addApprovedNftTransfer(example2Nft3, OPERATOR_ID, receiverAccountId2) + .setTransactionId(delegatedOnBehalfOfTxId) + .freezeWith(client) + .sign(spenderPrivateKey2) + .execute(client) + .getReceipt(client); System.out.println("Transfer serial 3 on behalf of the delegated spender status:" + delegatedSendTx.status); /* @@ -423,12 +415,12 @@ public static void main(String[] args) throws Exception { TransactionId onBehalfOfTransactionId3 = TransactionId.generate(delegatingSpenderAccountId); TransactionReceipt approvedSendReceipt3 = new TransferTransaction() - .addApprovedNftTransfer(example2Nft1, OPERATOR_ID, receiverAccountId2) - .setTransactionId(onBehalfOfTransactionId3) - .freezeWith(client) - .sign(delegatingSpenderPrivateKey) - .execute(client) - .getReceipt(client); + .addApprovedNftTransfer(example2Nft1, OPERATOR_ID, receiverAccountId2) + .setTransactionId(onBehalfOfTransactionId3) + .freezeWith(client) + .sign(delegatingSpenderPrivateKey) + .execute(client) + .getReceipt(client); System.out.println("Transfer serial 1 on behalf of the spender status:" + approvedSendReceipt3.status); /* @@ -436,9 +428,9 @@ public static void main(String[] args) throws Exception { * Remove delegatingSpender allowance for all of NFT serials. */ TransactionReceipt deleteAllowanceReceipt2 = new AccountAllowanceApproveTransaction() - .deleteTokenNftAllowanceAllSerials(nftTokenId2, OPERATOR_ID, delegatingSpenderAccountId) - .execute(client) - .getReceipt(client); + .deleteTokenNftAllowanceAllSerials(nftTokenId2, OPERATOR_ID, delegatingSpenderAccountId) + .execute(client) + .getReceipt(client); System.out.println("Remove spender's allowance for serial 2 - status: " + deleteAllowanceReceipt2.status); /* @@ -452,12 +444,12 @@ public static void main(String[] args) throws Exception { try { new TransferTransaction() - .addApprovedNftTransfer(example2Nft2, OPERATOR_ID, receiverAccountId2) - .setTransactionId(onBehalfOfTransactionId4) - .freezeWith(client) - .sign(delegatingSpenderPrivateKey) - .execute(client) - .getReceipt(client); + .addApprovedNftTransfer(example2Nft2, OPERATOR_ID, receiverAccountId2) + .setTransactionId(onBehalfOfTransactionId4) + .freezeWith(client) + .sign(delegatingSpenderPrivateKey) + .execute(client) + .getReceipt(client); } catch (Exception e) { System.out.println(e.getMessage()); } @@ -467,65 +459,59 @@ public static void main(String[] args) throws Exception { * Delete created accounts and tokens. */ new TokenWipeTransaction() - .setTokenId(nftTokenId) - .addSerial(1) - .setAccountId(receiverAccountId) - .freezeWith(client) - .sign(OPERATOR_KEY) - .execute(client) - .getReceipt(client); + .setTokenId(nftTokenId) + .addSerial(1) + .setAccountId(receiverAccountId) + .freezeWith(client) + .sign(OPERATOR_KEY) + .execute(client) + .getReceipt(client); new TokenWipeTransaction() - .setTokenId(nftTokenId2) - .addSerial(1) - .addSerial(3) - .setAccountId(receiverAccountId2) - .freezeWith(client) - .sign(OPERATOR_KEY) - .execute(client) - .getReceipt(client); + .setTokenId(nftTokenId2) + .addSerial(1) + .addSerial(3) + .setAccountId(receiverAccountId2) + .freezeWith(client) + .sign(OPERATOR_KEY) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(spenderAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(spenderPrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(spenderAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(spenderPrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(receiverAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(receiverPrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(receiverAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(receiverPrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(delegatingSpenderAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(delegatingSpenderPrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(delegatingSpenderAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(delegatingSpenderPrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(receiverAccountId2) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(receiverPrivateKey2) - .execute(client) - .getReceipt(client); - - new TokenDeleteTransaction() - .setTokenId(nftTokenId) - .execute(client) - .getReceipt(client); - - new TokenDeleteTransaction() - .setTokenId(nftTokenId2) - .execute(client) - .getReceipt(client); + .setAccountId(receiverAccountId2) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(receiverPrivateKey2) + .execute(client) + .getReceipt(client); + + new TokenDeleteTransaction().setTokenId(nftTokenId).execute(client).getReceipt(client); + + new TokenDeleteTransaction().setTokenId(nftTokenId2).execute(client).getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/PrngExample.java b/examples/src/main/java/org/hiero/sdk/examples/PrngExample.java similarity index 65% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/PrngExample.java rename to examples/src/main/java/org/hiero/sdk/examples/PrngExample.java index 5e88c5d9e..3f3634e1a 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/PrngExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/PrngExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to generate random number. @@ -40,12 +21,14 @@ class PrngExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -58,7 +41,7 @@ class PrngExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -81,9 +64,9 @@ public static void main(String[] args) throws Exception { */ System.out.println("Executing Prng Transaction (range: 100)..."); TransactionResponse transactionResponse = new PrngTransaction() - // The only required property here is `key`. - .setRange(100) - .execute(client); + // The only required property here is `key`. + .setRange(100) + .execute(client); // This will wait for the receipt to become available. TransactionRecord record = transactionResponse.getRecord(client); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduleExample.java b/examples/src/main/java/org/hiero/sdk/examples/ScheduleExample.java similarity index 58% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduleExample.java rename to examples/src/main/java/org/hiero/sdk/examples/ScheduleExample.java index acf8fcd15..03f9849e5 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduleExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ScheduleExample.java @@ -1,31 +1,12 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.time.Instant; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to schedule a transaction. @@ -41,12 +22,14 @@ class ScheduleExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -59,7 +42,7 @@ class ScheduleExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -92,11 +75,11 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new account..."); AccountId accountId = new AccountCreateTransaction() - .setKey(KeyList.of(publicKey1, publicKey2)) - .setInitialBalance(Hbar.from(1)) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(KeyList.of(publicKey1, publicKey2)) + .setInitialBalance(Hbar.from(1)) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(accountId); System.out.println("Created new account with ID: " + accountId); @@ -106,14 +89,14 @@ public static void main(String[] args) throws Exception { */ System.out.println("Scheduling token transfer..."); TransactionResponse transferTxResponse = new TransferTransaction() - .addHbarTransfer(accountId, Hbar.from(1).negated()) - .addHbarTransfer(client.getOperatorAccountId(), Hbar.from(1)) - .schedule() - // Set expiration time to be now + 24 hours - .setExpirationTime(Instant.now().plusSeconds(24 * 60 * 60)) - // Set wait for expiry to true - .setWaitForExpiry(true) - .execute(client); + .addHbarTransfer(accountId, Hbar.from(1).negated()) + .addHbarTransfer(client.getOperatorAccountId(), Hbar.from(1)) + .schedule() + // Set expiration time to be now + 24 hours + .setExpirationTime(Instant.now().plusSeconds(24 * 60 * 60)) + // Set wait for expiry to true + .setWaitForExpiry(true) + .execute(client); System.out.println("Scheduled transaction ID: " + transferTxResponse.transactionId); @@ -129,22 +112,21 @@ public static void main(String[] args) throws Exception { */ System.out.println("Appending private key #1 signature to a schedule transaction..."); var scheduleSignTxReceiptFirstSignature = new ScheduleSignTransaction() - .setScheduleId(scheduleId) - .freezeWith(client) - .sign(privateKey1) - .execute(client) - .getReceipt(client); + .setScheduleId(scheduleId) + .freezeWith(client) + .sign(privateKey1) + .execute(client) + .getReceipt(client); - System.out.println("A transaction that appends signature to a schedule transaction (private key #1) " + - "was complete with status: " + scheduleSignTxReceiptFirstSignature.status); + System.out.println("A transaction that appends signature to a schedule transaction (private key #1) " + + "was complete with status: " + scheduleSignTxReceiptFirstSignature.status); /* * Step 4: * Query the state of a schedule transaction. */ - ScheduleInfo scheduleInfo = new ScheduleInfoQuery() - .setScheduleId(scheduleId) - .execute(client); + ScheduleInfo scheduleInfo = + new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client); System.out.println("Schedule info: " + scheduleInfo); @@ -154,31 +136,34 @@ public static void main(String[] args) throws Exception { */ System.out.println("Appending private key #2 signature to a schedule transaction..."); var scheduleSignTxReceiptSecondSignature = new ScheduleSignTransaction() - .setScheduleId(scheduleId) - .freezeWith(client) - .sign(privateKey2) - .execute(client) - .getReceipt(client); + .setScheduleId(scheduleId) + .freezeWith(client) + .sign(privateKey2) + .execute(client) + .getReceipt(client); - System.out.println("A transaction that appends signature to a schedule transaction (private key #2) " + - "was complete with status: " + scheduleSignTxReceiptSecondSignature.status); + System.out.println("A transaction that appends signature to a schedule transaction (private key #2) " + + "was complete with status: " + scheduleSignTxReceiptSecondSignature.status); TransactionId transactionId = transferTxResponse.transactionId; - String validMirrorTransactionId = transactionId.accountId.toString() + "-" + transactionId.validStart.getEpochSecond() + "-" + transactionId.validStart.getNano(); - String mirrorNodeUrl = "https://" + HEDERA_NETWORK + ".mirrornode.hedera.com/api/v1/transactions/" + validMirrorTransactionId; - System.out.println("The following link should query the mirror node for the scheduled transaction: " + mirrorNodeUrl); + String validMirrorTransactionId = transactionId.accountId.toString() + "-" + + transactionId.validStart.getEpochSecond() + "-" + transactionId.validStart.getNano(); + String mirrorNodeUrl = + "https://" + HEDERA_NETWORK + ".mirrornode.hedera.com/api/v1/transactions/" + validMirrorTransactionId; + System.out.println( + "The following link should query the mirror node for the scheduled transaction: " + mirrorNodeUrl); /* * Clean up: * Delete created account. */ new AccountDeleteTransaction() - .setAccountId(accountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(privateKey1) - .sign(privateKey2) - .execute(client); + .setAccountId(accountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(privateKey1) + .sign(privateKey2) + .execute(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduleIdenticalTransactionExample.java b/examples/src/main/java/org/hiero/sdk/examples/ScheduleIdenticalTransactionExample.java similarity index 68% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduleIdenticalTransactionExample.java rename to examples/src/main/java/org/hiero/sdk/examples/ScheduleIdenticalTransactionExample.java index 7badc153a..0faacefe5 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduleIdenticalTransactionExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ScheduleIdenticalTransactionExample.java @@ -1,31 +1,12 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Collections; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to schedule identical transactions. @@ -41,12 +22,14 @@ class ScheduleIdenticalTransactionExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -59,7 +42,7 @@ class ScheduleIdenticalTransactionExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -87,7 +70,7 @@ public static void main(String[] args) throws Exception { ScheduleId scheduleId = null; - for (int i = 0; i < 3 ; i++) { + for (int i = 0; i < 3; i++) { System.out.println("Generating ED25519 key pair..."); PrivateKey newPrivateKey = PrivateKey.generateED25519(); @@ -96,14 +79,14 @@ public static void main(String[] args) throws Exception { privateKeys[i] = newPrivateKey; publicKeys[i] = newPublicKey; - System.out.println("Key pair #" + (i + 1) +" | Private key: " + privateKeys[i]); - System.out.println("Key pair #" + (i + 1) +" | Public key: " + publicKeys[i]); + System.out.println("Key pair #" + (i + 1) + " | Private key: " + privateKeys[i]); + System.out.println("Key pair #" + (i + 1) + " | Public key: " + publicKeys[i]); System.out.println("Creating new account..."); TransactionResponse accountCreateTxResponse = new AccountCreateTransaction() - .setKey(newPublicKey) - .setInitialBalance(Hbar.from(1)) - .execute(client); + .setKey(newPublicKey) + .setInitialBalance(Hbar.from(1)) + .execute(client); // Make sure the transaction succeeded. TransactionReceipt accountCreateTxReceipt = accountCreateTxResponse.getReceipt(client); @@ -122,8 +105,9 @@ public static void main(String[] args) throws Exception { * Create a threshold key with a threshold of 2 and length of 3 requires * (at least 2 of 3 keys to sign anything modifying the account). */ - System.out.println("Creating a Key List..." + - "(with threshold, it will require 2 of 3 keys we generated to sign on anything modifying this account)."); + System.out.println( + "Creating a Key List..." + + "(with threshold, it will require 2 of 3 keys we generated to sign on anything modifying this account)."); KeyList thresholdKey = KeyList.withThreshold(2); Collections.addAll(thresholdKey, publicKeys); System.out.println("Created a Key List: " + thresholdKey); @@ -136,11 +120,11 @@ public static void main(String[] args) throws Exception { // It works perfectly fine with just one key. System.out.println("Creating new account...(with the above Key List as an account key)."); TransactionResponse accountCreateTxResponse = new AccountCreateTransaction() - // The key that must sign each transfer out of the account. If receiverSigRequired is true, then - // it must also sign any transfer into the account. - .setKey(thresholdKey) - .setInitialBalance(Hbar.from(10)) - .execute(client); + // The key that must sign each transfer out of the account. If receiverSigRequired is true, then + // it must also sign any transfer into the account. + .setKey(thresholdKey) + .setInitialBalance(Hbar.from(10)) + .execute(client); // Make sure the transaction succeeded. TransactionReceipt accountCreateTxReceipt = accountCreateTxResponse.getReceipt(client); @@ -164,11 +148,11 @@ public static void main(String[] args) throws Exception { for (AccountId account : accounts) { transferTx.addHbarTransfer(account, Hbar.from(1)); } - transferTx.addHbarTransfer(Objects.requireNonNull(thresholdAccount), Hbar.from(3).negated()); + transferTx.addHbarTransfer( + Objects.requireNonNull(thresholdAccount), Hbar.from(3).negated()); System.out.println("Scheduling created transfer transaction..."); - ScheduleCreateTransaction scheduledTx = new ScheduleCreateTransaction() - .setScheduledTransaction(transferTx); + ScheduleCreateTransaction scheduledTx = new ScheduleCreateTransaction().setScheduledTransaction(transferTx); scheduledTx.setPayerAccountId(thresholdAccount); @@ -176,9 +160,9 @@ public static void main(String[] args) throws Exception { System.out.println("Executing scheduled transaction..."); TransactionReceipt loopReceipt = new TransactionReceiptQuery() - .setTransactionId(scheduledTxResponse.transactionId) - .setNodeAccountIds(Collections.singletonList(scheduledTxResponse.nodeId)) - .execute(loopClient); + .setTransactionId(scheduledTxResponse.transactionId) + .setNodeAccountIds(Collections.singletonList(scheduledTxResponse.nodeId)) + .execute(loopClient); System.out.println("Operator (ID: " + operatorId + ") | Schedule ID: " + loopReceipt.scheduleId); @@ -188,27 +172,30 @@ public static void main(String[] args) throws Exception { } if (!scheduleId.equals(Objects.requireNonNull(loopReceipt.scheduleId))) { - throw new Exception("Invalid generated schedule ID! Expected " + scheduleId + ", got " + loopReceipt.scheduleId); + throw new Exception( + "Invalid generated schedule ID! Expected " + scheduleId + ", got " + loopReceipt.scheduleId); } // If the status return by the receipt is related to already created, execute a schedule sign transaction. if (loopReceipt.status == Status.IDENTICAL_SCHEDULE_ALREADY_CREATED) { System.out.println("Appending signature to a schedule transaction..."); TransactionResponse scheduleSignTxResponse = new ScheduleSignTransaction() - .setScheduleId(scheduleId) - .setNodeAccountIds(Collections.singletonList(accountCreateTxResponse.nodeId)) - .setScheduleId(loopReceipt.scheduleId) - .execute(loopClient); + .setScheduleId(scheduleId) + .setNodeAccountIds(Collections.singletonList(accountCreateTxResponse.nodeId)) + .setScheduleId(loopReceipt.scheduleId) + .execute(loopClient); TransactionReceipt scheduleSignTxReceipt = new TransactionReceiptQuery() - .setTransactionId(scheduleSignTxResponse.transactionId) - .execute(client); + .setTransactionId(scheduleSignTxResponse.transactionId) + .execute(client); - System.out.println("A transaction that appends signature to a schedule transaction " + - "was complete with status: " + scheduleSignTxReceipt.status); + System.out.println("A transaction that appends signature to a schedule transaction " + + "was complete with status: " + scheduleSignTxReceipt.status); - if (scheduleSignTxReceipt.status != Status.SUCCESS && scheduleSignTxReceipt.status != Status.SCHEDULE_ALREADY_EXECUTED) { - throw new Exception("Bad status while getting receipt of schedule sign with operator " + operatorId + ": " + scheduleSignTxReceipt.status); + if (scheduleSignTxReceipt.status != Status.SUCCESS + && scheduleSignTxReceipt.status != Status.SCHEDULE_ALREADY_EXECUTED) { + throw new Exception("Bad status while getting receipt of schedule sign with operator " + operatorId + + ": " + scheduleSignTxReceipt.status); } } System.out.println("---"); @@ -220,9 +207,8 @@ public static void main(String[] args) throws Exception { * Step 5: * Query the state of a schedule transaction. */ - ScheduleInfo scheduleInfo = new ScheduleInfoQuery() - .setScheduleId(scheduleId) - .execute(client); + ScheduleInfo scheduleInfo = + new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client); System.out.println("Scheduled transaction info: " + scheduleInfo); /* @@ -230,24 +216,22 @@ public static void main(String[] args) throws Exception { * Delete created accounts and close created clients. */ AccountDeleteTransaction accountDeleteTx = new AccountDeleteTransaction() - .setAccountId(thresholdAccount) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client); + .setAccountId(thresholdAccount) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client); for (int i = 0; i < 3; i++) { accountDeleteTx.sign(privateKeys[i]); new AccountDeleteTransaction() - .setAccountId(accounts[i]) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(privateKeys[i]) - .execute(client) - .getReceipt(client); + .setAccountId(accounts[i]) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(privateKeys[i]) + .execute(client) + .getReceipt(client); } - accountDeleteTx - .execute(client) - .getReceipt(client); + accountDeleteTx.execute(client).getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduleMultiSigTransactionExample.java b/examples/src/main/java/org/hiero/sdk/examples/ScheduleMultiSigTransactionExample.java similarity index 68% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduleMultiSigTransactionExample.java rename to examples/src/main/java/org/hiero/sdk/examples/ScheduleMultiSigTransactionExample.java index 1f0de7271..e19a0af90 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduleMultiSigTransactionExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ScheduleMultiSigTransactionExample.java @@ -1,32 +1,13 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Collections; import java.util.Map; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to schedule a transaction with a multi-sig account. @@ -42,12 +23,14 @@ class ScheduleMultiSigTransactionExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -60,7 +43,7 @@ class ScheduleMultiSigTransactionExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -112,11 +95,11 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new account..."); TransactionResponse accountCreateTxResponse = new AccountCreateTransaction() - .setNodeAccountIds(Collections.singletonList(new AccountId(3))) - // The only required property here is key. - .setKey(keyList) - .setInitialBalance(Hbar.from(2)) - .execute(client); + .setNodeAccountIds(Collections.singletonList(new AccountId(3))) + // The only required property here is key. + .setKey(keyList) + .setInitialBalance(Hbar.from(2)) + .execute(client); // This will wait for the receipt to become available. TransactionReceipt accountCreateTxReceipt = accountCreateTxResponse.getReceipt(client); @@ -136,16 +119,17 @@ public static void main(String[] args) throws Exception { // Create a transfer transaction with 2/3 signatures. System.out.println("Creating a token transfer transaction..."); TransferTransaction transferTx = new TransferTransaction() - .addHbarTransfer(accountId, Hbar.from(1).negated()) - .addHbarTransfer(OPERATOR_ID, Hbar.from(1)); + .addHbarTransfer(accountId, Hbar.from(1).negated()) + .addHbarTransfer(OPERATOR_ID, Hbar.from(1)); // Schedule the transaction. System.out.println("Scheduling the token transfer transaction..."); - ScheduleCreateTransaction scheduled = transferTx.schedule() - .setPayerAccountId(OPERATOR_ID) - .setAdminKey(operatorPublicKey) - .freezeWith(client) - .sign(privateKey2); + ScheduleCreateTransaction scheduled = transferTx + .schedule() + .setPayerAccountId(OPERATOR_ID) + .setAdminKey(operatorPublicKey) + .freezeWith(client) + .sign(privateKey2); accountCreateTxReceipt = scheduled.execute(client).getReceipt(client); // Get the schedule ID from the receipt. @@ -157,9 +141,9 @@ public static void main(String[] args) throws Exception { * Get the schedule info to see if signatories is populated with 2/3 signatures. */ ScheduleInfo scheduleInfo_BeforeLastSignature = new ScheduleInfoQuery() - .setNodeAccountIds(Collections.singletonList(accountCreateTxResponse.nodeId)) - .setScheduleId(scheduleId) - .execute(client); + .setNodeAccountIds(Collections.singletonList(accountCreateTxResponse.nodeId)) + .setScheduleId(scheduleId) + .execute(client); System.out.println("Schedule info: " + scheduleInfo_BeforeLastSignature); @@ -176,7 +160,8 @@ public static void main(String[] args) throws Exception { } if (!transfers.get(OPERATOR_ID).equals(Hbar.from(1))) { - throw new Exception("Transfer for " + OPERATOR_ID + " is not what is expected " + transfers.get(OPERATOR_ID)); + throw new Exception( + "Transfer for " + OPERATOR_ID + " is not what is expected " + transfers.get(OPERATOR_ID)); } System.out.println("Sending schedule sign transaction..."); @@ -187,27 +172,28 @@ public static void main(String[] args) throws Exception { * * This last signature should mean the transaction executes since all 3 signatures have been provided. */ - System.out.println("Appending private key #3 signature to a schedule transaction..." + - "(This last signature should mean the transaction executes since all 3 signatures have been provided)"); + System.out.println( + "Appending private key #3 signature to a schedule transaction..." + + "(This last signature should mean the transaction executes since all 3 signatures have been provided)"); TransactionReceipt scheduleSignTxReceipt = new ScheduleSignTransaction() - .setNodeAccountIds(Collections.singletonList(accountCreateTxResponse.nodeId)) - .setScheduleId(scheduleId) - .freezeWith(client) - .sign(privateKey3) - .execute(client) - .getReceipt(client); + .setNodeAccountIds(Collections.singletonList(accountCreateTxResponse.nodeId)) + .setScheduleId(scheduleId) + .freezeWith(client) + .sign(privateKey3) + .execute(client) + .getReceipt(client); - System.out.println("A transaction that appends signature to a schedule transaction (private key #3) " + - "was complete with status: " + scheduleSignTxReceipt.status); + System.out.println("A transaction that appends signature to a schedule transaction (private key #3) " + + "was complete with status: " + scheduleSignTxReceipt.status); /* * Step 7: * Query the schedule info again. */ ScheduleInfo scheduleInfo_AfterAllSigned = new ScheduleInfoQuery() - .setNodeAccountIds(Collections.singletonList(accountCreateTxResponse.nodeId)) - .setScheduleId(scheduleId) - .execute(client); + .setNodeAccountIds(Collections.singletonList(accountCreateTxResponse.nodeId)) + .setScheduleId(scheduleId) + .execute(client); System.out.println("Schedule info: " + scheduleInfo_AfterAllSigned); @@ -216,13 +202,13 @@ public static void main(String[] args) throws Exception { * Delete created account. */ new AccountDeleteTransaction() - .setAccountId(accountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(privateKey1) - .sign(privateKey2) - .sign(privateKey3) - .execute(client); + .setAccountId(accountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(privateKey1) + .sign(privateKey2) + .sign(privateKey3) + .execute(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduledTransactionMultiSigThresholdExample.java b/examples/src/main/java/org/hiero/sdk/examples/ScheduledTransactionMultiSigThresholdExample.java similarity index 61% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduledTransactionMultiSigThresholdExample.java rename to examples/src/main/java/org/hiero/sdk/examples/ScheduledTransactionMultiSigThresholdExample.java index 596bd65fa..ae6c34c0b 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduledTransactionMultiSigThresholdExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ScheduledTransactionMultiSigThresholdExample.java @@ -1,31 +1,12 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Collections; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to schedule a transaction with a multi-sig account with a threshold. @@ -41,12 +22,14 @@ class ScheduledTransactionMultiSigThresholdExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -59,7 +42,7 @@ class ScheduledTransactionMultiSigThresholdExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -87,8 +70,8 @@ public static void main(String[] args) throws Exception { PrivateKey key = PrivateKey.generateED25519(); privateKeys[i] = key; publicKeys[i] = key.getPublicKey(); - System.out.println("Key pair #" + (i + 1) +" | Private key: " + privateKeys[i]); - System.out.println("Key pair #" + (i + 1) +" | Public key: " + publicKeys[i]); + System.out.println("Key pair #" + (i + 1) + " | Private key: " + privateKeys[i]); + System.out.println("Key pair #" + (i + 1) + " | Public key: " + publicKeys[i]); } /* @@ -96,8 +79,9 @@ public static void main(String[] args) throws Exception { * Create a Key List with threshold * (require 3 of 4 keys we generated to sign on anything modifying this account). */ - System.out.println("Creating a Key List..." + - "(with threshold, it will require 3 of 4 keys we generated to sign on anything modifying this account)."); + System.out.println( + "Creating a Key List..." + + "(with threshold, it will require 3 of 4 keys we generated to sign on anything modifying this account)."); KeyList thresholdKey = KeyList.withThreshold(3); Collections.addAll(thresholdKey, publicKeys); System.out.println("Created a Key List: " + thresholdKey); @@ -108,10 +92,10 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new account...(with the above Key List as an account key)."); TransactionResponse accountCreateTxResponse = new AccountCreateTransaction() - .setKey(thresholdKey) - .setInitialBalance(Hbar.from(1)) - .setAccountMemo("3-of-4 multi-sig account") - .execute(client); + .setKey(thresholdKey) + .setInitialBalance(Hbar.from(1)) + .setAccountMemo("3-of-4 multi-sig account") + .execute(client); // This will wait for the receipt to become available. TransactionReceipt accountCreateTxReceipt = accountCreateTxResponse.getReceipt(client); @@ -123,11 +107,11 @@ public static void main(String[] args) throws Exception { * Step 4: * Check the balance of the newly created account. */ - AccountBalance accountBalance = new AccountBalanceQuery() - .setAccountId(multiSigAccountId) - .execute(client); + AccountBalance accountBalance = + new AccountBalanceQuery().setAccountId(multiSigAccountId).execute(client); - System.out.println("Balance of a newly created account with ID " + multiSigAccountId + ": " + accountBalance.hbars.toTinybars() + " tinybar."); + System.out.println("Balance of a newly created account with ID " + multiSigAccountId + ": " + + accountBalance.hbars.toTinybars() + " tinybar."); /* * Step 5: @@ -135,13 +119,13 @@ public static void main(String[] args) throws Exception { */ System.out.println("Scheduling crypto transfer from multi-sig account to operator account..."); TransactionResponse transferTxScheduled = new TransferTransaction() - .addHbarTransfer(multiSigAccountId, Hbar.from(1).negated()) - .addHbarTransfer(Objects.requireNonNull(client.getOperatorAccountId()), Hbar.from(1)) - .schedule() - .freezeWith(client) - // Add first signature. - .sign(privateKeys[0]) - .execute(client); + .addHbarTransfer(multiSigAccountId, Hbar.from(1).negated()) + .addHbarTransfer(Objects.requireNonNull(client.getOperatorAccountId()), Hbar.from(1)) + .schedule() + .freezeWith(client) + // Add first signature. + .sign(privateKeys[0]) + .execute(client); TransactionReceipt transferTxScheduledReceipt = transferTxScheduled.getReceipt(client); System.out.println("Schedule status: " + transferTxScheduledReceipt.status); @@ -152,42 +136,42 @@ public static void main(String[] args) throws Exception { // Add second signature. TransactionResponse scheduleSignTxResponseSecondSignature = new ScheduleSignTransaction() - .setScheduleId(scheduleId) - .freezeWith(client) - .sign(privateKeys[1]) - .execute(client); + .setScheduleId(scheduleId) + .freezeWith(client) + .sign(privateKeys[1]) + .execute(client); - TransactionReceipt scheduleSignTxReceiptSecondSignature = scheduleSignTxResponseSecondSignature.getReceipt(client); - System.out.println("A transaction that appends signature to a schedule transaction (private key #2) " + - "was complete with status: " + scheduleSignTxReceiptSecondSignature.status); + TransactionReceipt scheduleSignTxReceiptSecondSignature = + scheduleSignTxResponseSecondSignature.getReceipt(client); + System.out.println("A transaction that appends signature to a schedule transaction (private key #2) " + + "was complete with status: " + scheduleSignTxReceiptSecondSignature.status); // Add third signature. TransactionResponse scheduleSignTxResponseThirdSignature = new ScheduleSignTransaction() - .setScheduleId(scheduleId) - .freezeWith(client) - .sign(privateKeys[2]) - .execute(client); + .setScheduleId(scheduleId) + .freezeWith(client) + .sign(privateKeys[2]) + .execute(client); - TransactionReceipt scheduleSignTxReceiptThirdSignature = scheduleSignTxResponseThirdSignature.getReceipt(client); - System.out.println("A transaction that appends signature to a schedule transaction (private key #3) " + - "was complete with status: " + scheduleSignTxReceiptThirdSignature.status); + TransactionReceipt scheduleSignTxReceiptThirdSignature = + scheduleSignTxResponseThirdSignature.getReceipt(client); + System.out.println("A transaction that appends signature to a schedule transaction (private key #3) " + + "was complete with status: " + scheduleSignTxReceiptThirdSignature.status); /* * Step 6: * Query schedule. */ - ScheduleInfo scheduleInfo = new ScheduleInfoQuery() - .setScheduleId(scheduleId) - .execute(client); + ScheduleInfo scheduleInfo = + new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client); System.out.println("Schedule info: " + scheduleInfo); /* * Step 7: * Query triggered scheduled transaction. */ - TransactionRecord recordScheduledTx = new TransactionRecordQuery() - .setTransactionId(scheduledTxId) - .execute(client); + TransactionRecord recordScheduledTx = + new TransactionRecordQuery().setTransactionId(scheduledTxId).execute(client); System.out.println("Triggered scheduled transaction info: " + recordScheduledTx); /* @@ -195,14 +179,14 @@ public static void main(String[] args) throws Exception { * Delete created account. */ new AccountDeleteTransaction() - .setAccountId(multiSigAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(privateKeys[0]) - .sign(privateKeys[1]) - .sign(privateKeys[2]) - .execute(client) - .getReceipt(client); + .setAccountId(multiSigAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(privateKeys[0]) + .sign(privateKeys[1]) + .sign(privateKeys[2]) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduledTransferExample.java b/examples/src/main/java/org/hiero/sdk/examples/ScheduledTransferExample.java similarity index 70% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduledTransferExample.java rename to examples/src/main/java/org/hiero/sdk/examples/ScheduledTransferExample.java index d22ef23dd..7feb1a279 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ScheduledTransferExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ScheduledTransferExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to schedule a transfer transaction. @@ -64,12 +45,14 @@ class ScheduledTransferExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -82,7 +65,7 @@ class ScheduledTransferExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -100,7 +83,7 @@ public static void main(String[] args) throws Exception { client.setLogger(new Logger(LogLevel.valueOf(SDK_LOG_LEVEL))); System.out.println("In this example Alice's account ID would be equal to the Operator's account ID: " - + client.getOperatorAccountId()); + + client.getOperatorAccountId()); /* * Step 1: @@ -116,14 +99,14 @@ public static void main(String[] args) throws Exception { */ System.out.println("Create Bob's account...(with receiver signature property enabled)."); AccountId bobAccountId = new AccountCreateTransaction() - .setReceiverSignatureRequired(true) - .setKey(bobPublicKey) - .setInitialBalance(Hbar.from(1)) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client) - .accountId; + .setReceiverSignatureRequired(true) + .setKey(bobPublicKey) + .setInitialBalance(Hbar.from(1)) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(bobAccountId); System.out.println("Created Bob's account with ID: " + bobAccountId); @@ -131,9 +114,8 @@ public static void main(String[] args) throws Exception { * Step 3: * Check Bob's initial balance. */ - AccountBalance bobsInitialBalance = new AccountBalanceQuery() - .setAccountId(bobAccountId) - .execute(client); + AccountBalance bobsInitialBalance = + new AccountBalanceQuery().setAccountId(bobAccountId).execute(client); System.out.println("Bob's initial account balance: " + bobsInitialBalance); /* @@ -141,8 +123,8 @@ public static void main(String[] args) throws Exception { * Create a transfer transaction which we will schedule. */ TransferTransaction transferTx = new TransferTransaction() - .addHbarTransfer(client.getOperatorAccountId(), Hbar.from(1).negated()) - .addHbarTransfer(bobAccountId, Hbar.from(1)); + .addHbarTransfer(client.getOperatorAccountId(), Hbar.from(1).negated()) + .addHbarTransfer(bobAccountId, Hbar.from(1)); System.out.println("Scheduling token transfer: " + transferTx); /* @@ -163,11 +145,11 @@ public static void main(String[] args) throws Exception { * will be charged for executing the scheduled transaction. */ ScheduleId scheduleId = new ScheduleCreateTransaction() - .setScheduledTransaction(transferTx) - .setPayerAccountId(bobAccountId) - .execute(client) - .getReceipt(client) - .scheduleId; + .setScheduledTransaction(transferTx) + .setPayerAccountId(bobAccountId) + .execute(client) + .getReceipt(client) + .scheduleId; Objects.requireNonNull(scheduleId); System.out.println("Schedule ID for the transaction above: " + scheduleId); @@ -176,10 +158,10 @@ public static void main(String[] args) throws Exception { * Check Bob's balance -- it should be unchanged, because the transfer has been scheduled, * but it hasn't been executed yet as it requires Bob's signature. */ - AccountBalance bobsBalanceAfterSchedule = new AccountBalanceQuery() - .setAccountId(bobAccountId) - .execute(client); - System.out.println("Bob's balance after scheduling the transfer (should be unchanged): " + bobsBalanceAfterSchedule); + AccountBalance bobsBalanceAfterSchedule = + new AccountBalanceQuery().setAccountId(bobAccountId).execute(client); + System.out.println( + "Bob's balance after scheduling the transfer (should be unchanged): " + bobsBalanceAfterSchedule); /* * Step 7: @@ -188,9 +170,8 @@ public static void main(String[] args) throws Exception { * Once Alice has communicated the scheduleId to Bob, Bob can query for information about the * scheduled transaction. */ - ScheduleInfo scheduledTransactionInfo = new ScheduleInfoQuery() - .setScheduleId(scheduleId) - .execute(client); + ScheduleInfo scheduledTransactionInfo = + new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client); System.out.println("Scheduled transaction info: " + scheduledTransactionInfo); // getScheduledTransaction() will return an SDK Transaction object identical to the transaction @@ -211,43 +192,42 @@ public static void main(String[] args) throws Exception { */ System.out.println("Appending Bob's signature to a schedule transaction..."); var scheduleSignTxReceipt = new ScheduleSignTransaction() - .setScheduleId(scheduleId) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); - System.out.println("A transaction that appends Bob's signature to a schedule transfer transaction " + - "was complete with status: " + scheduleSignTxReceipt.status); + .setScheduleId(scheduleId) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); + System.out.println("A transaction that appends Bob's signature to a schedule transfer transaction " + + "was complete with status: " + scheduleSignTxReceipt.status); /* * Step 9: * Check Bob's account balance after signing the scheduled transaction. */ - AccountBalance balanceAfterSigning = new AccountBalanceQuery() - .setAccountId(bobAccountId) - .execute(client); + AccountBalance balanceAfterSigning = + new AccountBalanceQuery().setAccountId(bobAccountId).execute(client); System.out.println("Bob's balance after signing the scheduled transaction: " + balanceAfterSigning); /* * Step 10: * Query the state of a schedule transaction. */ - ScheduleInfo postTransactionInfo = new ScheduleInfoQuery() - .setScheduleId(scheduleId) - .execute(client); - System.out.println("Scheduled transaction info (`executedAt` should no longer be `null`): " + postTransactionInfo); + ScheduleInfo postTransactionInfo = + new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client); + System.out.println( + "Scheduled transaction info (`executedAt` should no longer be `null`): " + postTransactionInfo); /* * Clean up: * Delete created account. */ new AccountDeleteTransaction() - .setTransferAccountId(client.getOperatorAccountId()) - .setAccountId(bobAccountId) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + .setTransferAccountId(client.getOperatorAccountId()) + .setAccountId(bobAccountId) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/SignTransactionExample.java b/examples/src/main/java/org/hiero/sdk/examples/SignTransactionExample.java similarity index 70% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/SignTransactionExample.java rename to examples/src/main/java/org/hiero/sdk/examples/SignTransactionExample.java index c89b8b27b..5ab10dfc0 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/SignTransactionExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/SignTransactionExample.java @@ -1,31 +1,12 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Collections; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to sign a transaction with a multi-sig account. @@ -41,12 +22,14 @@ class SignTransactionExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -59,7 +42,7 @@ class SignTransactionExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -102,9 +85,9 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new account..."); TransactionResponse createAccountTxResponse = new AccountCreateTransaction() - .setInitialBalance(Hbar.from(2)) - .setKey(keylist) - .execute(client); + .setInitialBalance(Hbar.from(2)) + .setKey(keylist) + .execute(client); TransactionReceipt createAccountTxReceipt = createAccountTxResponse.getReceipt(client); var accountId = createAccountTxReceipt.accountId; @@ -117,10 +100,12 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating a transfer transaction..."); TransferTransaction transferTx = new TransferTransaction() - .setNodeAccountIds(Collections.singletonList(new AccountId(3))) - .addHbarTransfer(Objects.requireNonNull(createAccountTxReceipt.accountId), Hbar.from(1).negated()) - .addHbarTransfer(new AccountId(3), Hbar.from(1)) - .freezeWith(client); + .setNodeAccountIds(Collections.singletonList(new AccountId(3))) + .addHbarTransfer( + Objects.requireNonNull(createAccountTxReceipt.accountId), + Hbar.from(1).negated()) + .addHbarTransfer(new AccountId(3), Hbar.from(1)) + .freezeWith(client); /* * Step 5: @@ -145,13 +130,13 @@ public static void main(String[] args) throws Exception { * Delete created account. */ new AccountDeleteTransaction() - .setAccountId(accountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(privateKey1) - .sign(privateKey2) - .execute(client) - .getReceipt(client); + .setAccountId(accountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(privateKey1) + .sign(privateKey2) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/SolidityPrecompileExample.java b/examples/src/main/java/org/hiero/sdk/examples/SolidityPrecompileExample.java similarity index 96% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/SolidityPrecompileExample.java rename to examples/src/main/java/org/hiero/sdk/examples/SolidityPrecompileExample.java index 4d380acb7..db2ec2505 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/SolidityPrecompileExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/SolidityPrecompileExample.java @@ -1,16 +1,16 @@ // SPDX-License-Identifier: Apache-2.0 -package com.hedera.hashgraph.sdk.examples; +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; import io.github.cdimascio.dotenv.Dotenv; import java.util.Arrays; import java.util.Objects; import java.util.function.Consumer; +import org.hiero.sdk.*; /* This example just instantiates the solidity contract -defined in resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/PrecompileExample.sol, which has been -compiled into resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/PrecompileExample.json. +defined in resources/org/hiero/sdk/examples/contracts/precompile/PrecompileExample.sol, which has been +compiled into resources/org/hiero/sdk/examples/contracts/precompile/PrecompileExample.json. You should go look at that PrecompileExample.sol file, because that's where the meat of this example is. diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/StakingExample.java b/examples/src/main/java/org/hiero/sdk/examples/StakingExample.java similarity index 68% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/StakingExample.java rename to examples/src/main/java/org/hiero/sdk/examples/StakingExample.java index dab731ff2..d1b5be0ba 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/StakingExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/StakingExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to stake to some account. @@ -41,12 +22,14 @@ class StakingExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -59,7 +42,7 @@ class StakingExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -95,12 +78,12 @@ public static void main(String[] args) throws Exception { System.out.println("Creating new account with staked account ID..."); AccountId stakedAccountId = AccountId.fromString("0.0.3"); AccountId newAccountId = new AccountCreateTransaction() - .setKey(publicKey) - .setInitialBalance(Hbar.from(1)) - .setStakedAccountId(stakedAccountId) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(publicKey) + .setInitialBalance(Hbar.from(1)) + .setStakedAccountId(stakedAccountId) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(newAccountId); System.out.println("Created new account with ID: " + newAccountId); @@ -114,9 +97,7 @@ public static void main(String[] args) throws Exception { * Step 3: * Query the account info, it should show the staked account ID to be 0.0.3. */ - AccountInfo info = new AccountInfoQuery() - .setAccountId(newAccountId) - .execute(client); + AccountInfo info = new AccountInfoQuery().setAccountId(newAccountId).execute(client); if (info.stakingInfo.stakedAccountId.equals(stakedAccountId)) { System.out.println("New account staking info: " + info.stakingInfo); @@ -129,12 +110,12 @@ public static void main(String[] args) throws Exception { * Delete created account. */ new AccountDeleteTransaction() - .setAccountId(newAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(privateKey) - .execute(client) - .getReceipt(client); + .setAccountId(newAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(privateKey) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/StakingWithUpdateExample.java b/examples/src/main/java/org/hiero/sdk/examples/StakingWithUpdateExample.java similarity index 68% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/StakingWithUpdateExample.java rename to examples/src/main/java/org/hiero/sdk/examples/StakingWithUpdateExample.java index f41f6477e..f803dd726 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/StakingWithUpdateExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/StakingWithUpdateExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to stake to some account and then unstake. @@ -40,12 +21,14 @@ class StakingWithUpdateExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -58,7 +41,7 @@ class StakingWithUpdateExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -94,12 +77,12 @@ public static void main(String[] args) throws Exception { System.out.println("Creating new account with staked account ID..."); AccountId stakedAccountId = AccountId.fromString("0.0.3"); AccountId newAccountId = new AccountCreateTransaction() - .setKey(publicKey) - .setInitialBalance(Hbar.from(1)) - .setStakedAccountId(stakedAccountId) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(publicKey) + .setInitialBalance(Hbar.from(1)) + .setStakedAccountId(stakedAccountId) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(newAccountId); System.out.println("Created new account with ID: " + newAccountId); @@ -113,9 +96,8 @@ public static void main(String[] args) throws Exception { * Step 3: * Query the account info, it should show the staked account ID to be 0.0.3. */ - AccountInfo accountInfo = new AccountInfoQuery() - .setAccountId(newAccountId) - .execute(client); + AccountInfo accountInfo = + new AccountInfoQuery().setAccountId(newAccountId).execute(client); if (accountInfo.stakingInfo.stakedAccountId.equals(stakedAccountId)) { System.out.println("New account staking info: " + accountInfo.stakingInfo); @@ -131,20 +113,18 @@ public static void main(String[] args) throws Exception { */ System.out.println("Updating the new account...(unstake Hbar)."); new AccountUpdateTransaction() - .setAccountId(newAccountId) - .clearStakedAccountId() - .freezeWith(client) - .sign(privateKey) - .execute(client) - .getReceipt(client); + .setAccountId(newAccountId) + .clearStakedAccountId() + .freezeWith(client) + .sign(privateKey) + .execute(client) + .getReceipt(client); /* * Step 5: * Query the account info, it should show the staked account ID to be null. */ - accountInfo = new AccountInfoQuery() - .setAccountId(newAccountId) - .execute(client); + accountInfo = new AccountInfoQuery().setAccountId(newAccountId).execute(client); if (accountInfo.stakingInfo.stakedAccountId == null) { System.out.println("New account staking info: " + accountInfo.stakingInfo); @@ -157,12 +137,12 @@ public static void main(String[] args) throws Exception { * Delete created account. */ new AccountDeleteTransaction() - .setAccountId(newAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(privateKey) - .execute(client) - .getReceipt(client); + .setAccountId(newAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(privateKey) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/org/hiero/sdk/examples/TokenAirdropExample.java b/examples/src/main/java/org/hiero/sdk/examples/TokenAirdropExample.java new file mode 100644 index 000000000..c3ed74f5b --- /dev/null +++ b/examples/src/main/java/org/hiero/sdk/examples/TokenAirdropExample.java @@ -0,0 +1,347 @@ +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; + +import io.github.cdimascio.dotenv.Dotenv; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import org.hiero.sdk.AccountBalanceQuery; +import org.hiero.sdk.AccountCreateTransaction; +import org.hiero.sdk.AccountId; +import org.hiero.sdk.Client; +import org.hiero.sdk.Hbar; +import org.hiero.sdk.PrivateKey; +import org.hiero.sdk.TokenAirdropTransaction; +import org.hiero.sdk.TokenCancelAirdropTransaction; +import org.hiero.sdk.TokenClaimAirdropTransaction; +import org.hiero.sdk.TokenCreateTransaction; +import org.hiero.sdk.TokenMintTransaction; +import org.hiero.sdk.TokenRejectTransaction; +import org.hiero.sdk.TokenSupplyType; +import org.hiero.sdk.TokenType; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; + +public class TokenAirdropExample { + + /* + * See .env.sample in the examples folder root for how to specify values below + * or set environment variables with the same names. + */ + + /** + * Operator's account ID. Used to sign and pay for operations on Hedera. + */ + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + + /** + * Operator's private key. + */ + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + + /** + * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. Network can be: localhost, testnet, + * previewnet or mainnet. + */ + private static final String HEDERA_NETWORK = Dotenv.load().get("HEDERA_NETWORK", "testnet"); + + /** + * SDK_LOG_LEVEL defaults to SILENT if not specified in dotenv file. Log levels can be: TRACE, DEBUG, INFO, WARN, + * ERROR, SILENT. + *

+ * Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, for example via VM + * options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace + */ + private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); + + public static void main(String[] args) throws Exception { + System.out.println("Example Start!"); + + /* + * Step 0: + * Create and configure SDK Client. + */ + Client client = ClientHelper.forName(HEDERA_NETWORK); + // All generated transactions will be paid by this account and signed by this key. + client.setOperator(OPERATOR_ID, OPERATOR_KEY); + // Attach logger to the SDK Client. + client.setLogger(new Logger(LogLevel.valueOf(SDK_LOG_LEVEL))); + + /* + * Step 1: + * Create 4 accounts + */ + var privateKey1 = PrivateKey.generateECDSA(); + var alice = new AccountCreateTransaction() + .setKey(privateKey1) + .setInitialBalance(new Hbar(10)) + .setMaxAutomaticTokenAssociations(-1) + .execute(client) + .getReceipt(client) + .accountId; + + var privateKey2 = PrivateKey.generateECDSA(); + var bob = new AccountCreateTransaction() + .setKey(privateKey2) + .setMaxAutomaticTokenAssociations(1) + .execute(client) + .getReceipt(client) + .accountId; + + var privateKey3 = PrivateKey.generateECDSA(); + var carol = new AccountCreateTransaction() + .setKey(privateKey3) + .setMaxAutomaticTokenAssociations(0) + .execute(client) + .getReceipt(client) + .accountId; + + var treasuryKey = PrivateKey.generateECDSA(); + var treasuryAccount = new AccountCreateTransaction() + .setKey(treasuryKey) + .setInitialBalance(new Hbar(10)) + .execute(client) + .getReceipt(client) + .accountId; + + /* + * Step 2: + * Create FT and NFT and mint + */ + var tokenID = new TokenCreateTransaction() + .setTokenName("Fungible Token") + .setTokenSymbol("TFT") + .setTokenMemo("Example memo") + .setDecimals(3) + .setInitialSupply(100) + .setMaxSupply(100) + .setTreasuryAccountId(treasuryAccount) + .setSupplyType(TokenSupplyType.FINITE) + .setAdminKey(client.getOperatorPublicKey()) + .setFreezeKey(client.getOperatorPublicKey()) + .setSupplyKey(client.getOperatorPublicKey()) + .setMetadataKey(client.getOperatorPublicKey()) + .setPauseKey(client.getOperatorPublicKey()) + .freezeWith(client) + .sign(treasuryKey) + .execute(client) + .getReceipt(client) + .tokenId; + + var nftID = new TokenCreateTransaction() + .setTokenName("Test NFT") + .setTokenSymbol("TNFT") + .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) + .setTreasuryAccountId(treasuryAccount) + .setSupplyType(TokenSupplyType.FINITE) + .setMaxSupply(10) + .setSupplyType(TokenSupplyType.FINITE) + .setAdminKey(client.getOperatorPublicKey()) + .setFreezeKey(client.getOperatorPublicKey()) + .setSupplyKey(client.getOperatorPublicKey()) + .setMetadataKey(client.getOperatorPublicKey()) + .setPauseKey(client.getOperatorPublicKey()) + .freezeWith(client) + .sign(treasuryKey) + .execute(client) + .getReceipt(client) + .tokenId; + + new TokenMintTransaction() + .setTokenId(nftID) + .setMetadata(generateNftMetadata((byte) 3)) + .execute(client) + .getReceipt(client); + + /* + * Step 3: + * Airdrop fungible tokens to all 3 accounts + */ + System.out.println("Airdropping fts"); + var txnRecord = new TokenAirdropTransaction() + .addTokenTransfer(tokenID, alice, 10) + .addTokenTransfer(tokenID, treasuryAccount, -10) + .addTokenTransfer(tokenID, bob, 10) + .addTokenTransfer(tokenID, treasuryAccount, -10) + .addTokenTransfer(tokenID, carol, 10) + .addTokenTransfer(tokenID, treasuryAccount, -10) + .freezeWith(client) + .sign(treasuryKey) + .execute(client) + .getRecord(client); + + /* + * Step 4: + * Get the transaction record and see one pending airdrop (for carol) + */ + System.out.println("Pending airdrops length: " + txnRecord.pendingAirdropRecords.size()); + System.out.println("Pending airdrops: " + txnRecord.pendingAirdropRecords.get(0)); + + /* + * Step 5: + * Query to verify alice and bob received the airdrops and carol did not + */ + var aliceBalance = new AccountBalanceQuery().setAccountId(alice).execute(client); + var bobBalance = new AccountBalanceQuery().setAccountId(bob).execute(client); + var carolBalance = new AccountBalanceQuery().setAccountId(carol).execute(client); + + System.out.println("Alice ft balance after airdrop: " + aliceBalance.tokens.get(tokenID)); + System.out.println("Bob ft balance after airdrop: " + bobBalance.tokens.get(tokenID)); + System.out.println("Carol ft balance after airdrop: " + carolBalance.tokens.get(tokenID)); + + /* + * Step 6: + * Claim the airdrop for carol + */ + System.out.println("Claiming ft with carol"); + new TokenClaimAirdropTransaction() + .addPendingAirdrop(txnRecord.pendingAirdropRecords.get(0).getPendingAirdropId()) + .freezeWith(client) + .sign(privateKey3) + .execute(client) + .getReceipt(client); + + carolBalance = new AccountBalanceQuery().setAccountId(carol).execute(client); + System.out.println("Carol ft balance after claim: " + carolBalance.tokens.get(tokenID)); + + /* + * Step 7: + * Airdrop the NFTs to all three accounts + */ + System.out.println("Airdropping nfts"); + txnRecord = new TokenAirdropTransaction() + .addNftTransfer(nftID.nft(1), treasuryAccount, alice) + .addNftTransfer(nftID.nft(2), treasuryAccount, bob) + .addNftTransfer(nftID.nft(3), treasuryAccount, carol) + .freezeWith(client) + .sign(treasuryKey) + .execute(client) + .getRecord(client); + + /* + * Step 8: + * Get the transaction record and verify two pending airdrops (for bob & carol) + */ + System.out.println("Pending airdrops length: " + txnRecord.pendingAirdropRecords.size()); + System.out.println("Pending airdrops for Bob: " + txnRecord.pendingAirdropRecords.get(0)); + System.out.println("Pending airdrops for Carol: " + txnRecord.pendingAirdropRecords.get(1)); + + /* + * Step 9: + * Query to verify alice received the airdrop and bob and carol did not + */ + aliceBalance = new AccountBalanceQuery().setAccountId(alice).execute(client); + bobBalance = new AccountBalanceQuery().setAccountId(bob).execute(client); + carolBalance = new AccountBalanceQuery().setAccountId(carol).execute(client); + + System.out.println("Alice nft balance after airdrop: " + aliceBalance.tokens.get(nftID)); + System.out.println("Bob nft balance after airdrop: " + bobBalance.tokens.get(nftID)); + System.out.println("Carol nft balance after airdrop: " + carolBalance.tokens.get(nftID)); + + /* + * Step 10: + * Claim the airdrop for bob + */ + System.out.println("Claiming nft with Bob"); + new TokenClaimAirdropTransaction() + .addPendingAirdrop(txnRecord.pendingAirdropRecords.get(0).getPendingAirdropId()) + .freezeWith(client) + .sign(privateKey2) + .execute(client) + .getReceipt(client); + + bobBalance = new AccountBalanceQuery().setAccountId(bob).execute(client); + System.out.println("Bob nft balance after claim: " + bobBalance.tokens.get(nftID)); + + /* + * Step 11: + * Cancel the airdrop for carol + */ + System.out.println("Canceling nft for Carol"); + new TokenCancelAirdropTransaction() + .addPendingAirdrop(txnRecord.pendingAirdropRecords.get(1).getPendingAirdropId()) + .freezeWith(client) + .sign(treasuryKey) + .execute(client) + .getReceipt(client); + + carolBalance = new AccountBalanceQuery().setAccountId(carol).execute(client); + System.out.println("Carol nft balance after cancel: " + carolBalance.tokens.get(nftID)); + + /* + * Step 12: + * Reject the NFT for bob + */ + System.out.println("Rejecting nft with Bob"); + new TokenRejectTransaction() + .setOwnerId(bob) + .addNftId(nftID.nft(2)) + .freezeWith(client) + .sign(privateKey2) + .execute(client) + .getReceipt(client); + + /* + * Step 13: + * Query to verify bob no longer has the NFT + */ + bobBalance = new AccountBalanceQuery().setAccountId(bob).execute(client); + System.out.println("Bob nft balance after reject: " + bobBalance.tokens.get(nftID)); + + /* + * Step 13: + * Query to verify the NFT was returned to the Treasury + */ + var treasuryBalance = + new AccountBalanceQuery().setAccountId(treasuryAccount).execute(client); + System.out.println("Treasury nft balance after reject: " + treasuryBalance.tokens.get(nftID)); + + /* + * Step 14: + * Reject the fungible tokens for Carol + */ + System.out.println("Rejecting ft with Carol"); + new TokenRejectTransaction() + .setOwnerId(carol) + .addTokenId(tokenID) + .freezeWith(client) + .sign(privateKey3) + .execute(client) + .getReceipt(client); + + /* + * Step 14: + * Query to verify carol no longer has the fungible tokens + */ + carolBalance = new AccountBalanceQuery().setAccountId(carol).execute(client); + System.out.println("Carol ft balance after reject: " + carolBalance.tokens.get(tokenID)); + + /* + * Step 15: + * Query to verify Treasury received the rejected fungible tokens + */ + treasuryBalance = + new AccountBalanceQuery().setAccountId(treasuryAccount).execute(client); + System.out.println("Treasury ft balance after reject: " + treasuryBalance.tokens.get(tokenID)); + + /* + * Clean up: + */ + client.close(); + + System.out.println("Example Complete!"); + } + + private static List generateNftMetadata(byte metadataCount) { + List metadatas = new ArrayList<>(); + + for (byte i = 0; i < metadataCount; i++) { + byte[] md = {i}; + metadatas.add(md); + } + + return metadatas; + } +} diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TokenMetadataExample.java b/examples/src/main/java/org/hiero/sdk/examples/TokenMetadataExample.java similarity index 61% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/TokenMetadataExample.java rename to examples/src/main/java/org/hiero/sdk/examples/TokenMetadataExample.java index 4c44712f6..dd7299360 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TokenMetadataExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/TokenMetadataExample.java @@ -1,31 +1,12 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Arrays; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to set and update token's metadata. @@ -49,12 +30,14 @@ public class TokenMetadataExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -67,7 +50,7 @@ public class TokenMetadataExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -101,24 +84,24 @@ public static void main(String[] args) throws Exception { * Create a mutable fungible token with a metadata, but without a Metadata Key. */ System.out.println("The beginning of the first example (mutable token's metadata)."); - byte[] initialTokenMetadata = new byte[]{1, 1, 1, 1, 1}; + byte[] initialTokenMetadata = new byte[] {1, 1, 1, 1, 1}; System.out.println("Creating mutable Fungible Token using the Hedera Token Service..."); var mutableFungibleTokenId = new TokenCreateTransaction() - .setTokenName("HIP-646 Mutable FT") - .setTokenSymbol("HIP646MFT") - .setTokenMetadata(initialTokenMetadata) - // The same flow can be executed with a TokenType.NON_FUNGIBLE_UNIQUE (i.e. HIP-765). - .setTokenType(TokenType.FUNGIBLE_COMMON) - .setTreasuryAccountId(OPERATOR_ID) - .setDecimals(3) - .setInitialSupply(1_000_000) - .setAdminKey(adminPublicKey) - .freezeWith(client) - .sign(adminPrivateKey) - .execute(client) - .getReceipt(client) - .tokenId; + .setTokenName("HIP-646 Mutable FT") + .setTokenSymbol("HIP646MFT") + .setTokenMetadata(initialTokenMetadata) + // The same flow can be executed with a TokenType.NON_FUNGIBLE_UNIQUE (i.e. HIP-765). + .setTokenType(TokenType.FUNGIBLE_COMMON) + .setTreasuryAccountId(OPERATOR_ID) + .setDecimals(3) + .setInitialSupply(1_000_000) + .setAdminKey(adminPublicKey) + .freezeWith(client) + .sign(adminPrivateKey) + .execute(client) + .getReceipt(client) + .tokenId; Objects.requireNonNull(mutableFungibleTokenId); System.out.println("Created mutable Fungible Token with ID: " + mutableFungibleTokenId); @@ -126,14 +109,13 @@ public static void main(String[] args) throws Exception { * Step 3: * Query and output mutable Fungible Token info after its creation. */ - var mutableFungibleTokenInfo_AfterCreation = new TokenInfoQuery() - .setTokenId(mutableFungibleTokenId) - .execute(client); + var mutableFungibleTokenInfo_AfterCreation = + new TokenInfoQuery().setTokenId(mutableFungibleTokenId).execute(client); // Check that metadata was set correctly. if (Arrays.equals(mutableFungibleTokenInfo_AfterCreation.metadata, initialTokenMetadata)) { System.out.println("Mutable Fungible Token metadata after creation: " - + Arrays.toString(mutableFungibleTokenInfo_AfterCreation.metadata)); + + Arrays.toString(mutableFungibleTokenInfo_AfterCreation.metadata)); } else { throw new Exception("Mutable Fungible Token metadata was not set correctly! (Fail)"); } @@ -142,28 +124,27 @@ public static void main(String[] args) throws Exception { * Step 4: * Update mutable Fungible Token metadata. */ - byte[] updatedTokenMetadata = new byte[]{2, 2, 2, 2, 2}; + byte[] updatedTokenMetadata = new byte[] {2, 2, 2, 2, 2}; System.out.println("Updating mutable Fungible Token metadata..."); new TokenUpdateTransaction() - .setTokenId(mutableFungibleTokenId) - .setTokenMetadata(updatedTokenMetadata) - .freezeWith(client) - .sign(adminPrivateKey) - .execute(client) - .getReceipt(client); + .setTokenId(mutableFungibleTokenId) + .setTokenMetadata(updatedTokenMetadata) + .freezeWith(client) + .sign(adminPrivateKey) + .execute(client) + .getReceipt(client); /* * Step 5: * Query and output mutable Fungible Token info after its metadata was updated. */ - var mutableFungibleTokenInfo_AfterMetadataUpdate = new TokenInfoQuery() - .setTokenId(mutableFungibleTokenId) - .execute(client); + var mutableFungibleTokenInfo_AfterMetadataUpdate = + new TokenInfoQuery().setTokenId(mutableFungibleTokenId).execute(client); // Check that metadata was updated correctly. if (Arrays.equals(mutableFungibleTokenInfo_AfterMetadataUpdate.metadata, updatedTokenMetadata)) { System.out.println("Mutable Fungible Token metadata after update: " - + Arrays.toString(mutableFungibleTokenInfo_AfterMetadataUpdate.metadata)); + + Arrays.toString(mutableFungibleTokenInfo_AfterMetadataUpdate.metadata)); } else { throw new Exception("Mutable Fungible Token metadata was not updated correctly! (Fail)"); } @@ -178,18 +159,18 @@ public static void main(String[] args) throws Exception { System.out.println("Creating immutable Fungible Token using the Hedera Token Service..."); var immutableFungibleTokenId = new TokenCreateTransaction() - .setTokenName("HIP-646 Immutable FT") - .setTokenSymbol("HIP646IMMFT") - .setTokenMetadata(initialTokenMetadata) - // The same flow can be executed with a TokenType.NON_FUNGIBLE_UNIQUE (i.e. HIP-765). - .setTokenType(TokenType.FUNGIBLE_COMMON) - .setTreasuryAccountId(OPERATOR_ID) - .setMetadataKey(metadataPublicKey) - .setDecimals(3) - .setInitialSupply(1_000_000) - .execute(client) - .getReceipt(client) - .tokenId; + .setTokenName("HIP-646 Immutable FT") + .setTokenSymbol("HIP646IMMFT") + .setTokenMetadata(initialTokenMetadata) + // The same flow can be executed with a TokenType.NON_FUNGIBLE_UNIQUE (i.e. HIP-765). + .setTokenType(TokenType.FUNGIBLE_COMMON) + .setTreasuryAccountId(OPERATOR_ID) + .setMetadataKey(metadataPublicKey) + .setDecimals(3) + .setInitialSupply(1_000_000) + .execute(client) + .getReceipt(client) + .tokenId; Objects.requireNonNull(immutableFungibleTokenId); System.out.println("Created an immutable Fungible Token with ID: " + immutableFungibleTokenId); @@ -197,14 +178,13 @@ public static void main(String[] args) throws Exception { * Step 7: * Query and output immutable Fungible Token info after its creation. */ - var immutableFungibleTokenTokenInfo_AfterCreation = new TokenInfoQuery() - .setTokenId(immutableFungibleTokenId) - .execute(client); + var immutableFungibleTokenTokenInfo_AfterCreation = + new TokenInfoQuery().setTokenId(immutableFungibleTokenId).execute(client); // Check that metadata was set correctly. if (Arrays.equals(immutableFungibleTokenTokenInfo_AfterCreation.metadata, initialTokenMetadata)) { System.out.println("Immutable Fungible Token metadata after creation: " - + Arrays.toString(immutableFungibleTokenTokenInfo_AfterCreation.metadata)); + + Arrays.toString(immutableFungibleTokenTokenInfo_AfterCreation.metadata)); } else { throw new Exception("Immutable Fungible Token metadata was not set correctly! (Fail)"); } @@ -215,25 +195,24 @@ public static void main(String[] args) throws Exception { */ System.out.println("Updating immutable Fungible Token metadata..."); new TokenUpdateTransaction() - .setTokenId(immutableFungibleTokenId) - .setTokenMetadata(updatedTokenMetadata) - .freezeWith(client) - .sign(metadataPrivateKey) - .execute(client) - .getReceipt(client); + .setTokenId(immutableFungibleTokenId) + .setTokenMetadata(updatedTokenMetadata) + .freezeWith(client) + .sign(metadataPrivateKey) + .execute(client) + .getReceipt(client); /* * Step 5: * Query and output immutable Fungible Token info after its metadata was updated. */ - var immutableFungibleTokenInfo_AfterMetadataUpdate = new TokenInfoQuery() - .setTokenId(immutableFungibleTokenId) - .execute(client); + var immutableFungibleTokenInfo_AfterMetadataUpdate = + new TokenInfoQuery().setTokenId(immutableFungibleTokenId).execute(client); // Check that metadata was updated correctly. if (Arrays.equals(immutableFungibleTokenInfo_AfterMetadataUpdate.metadata, updatedTokenMetadata)) { System.out.println("Immutable Fungible Token metadata after update: " - + Arrays.toString(immutableFungibleTokenInfo_AfterMetadataUpdate.metadata)); + + Arrays.toString(immutableFungibleTokenInfo_AfterMetadataUpdate.metadata)); } else { throw new Exception("Immutable Fungible Token metadata was not updated correctly! (Fail)"); } @@ -243,11 +222,11 @@ public static void main(String[] args) throws Exception { * Delete created mutable token. */ new TokenDeleteTransaction() - .setTokenId(mutableFungibleTokenId) - .freezeWith(client) - .sign(adminPrivateKey) - .execute(client) - .getReceipt(client); + .setTokenId(mutableFungibleTokenId) + .freezeWith(client) + .sign(adminPrivateKey) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TokenRejectExample.java b/examples/src/main/java/org/hiero/sdk/examples/TokenRejectExample.java similarity index 53% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/TokenRejectExample.java rename to examples/src/main/java/org/hiero/sdk/examples/TokenRejectExample.java index 5d4be4bb1..24fe6cc2e 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TokenRejectExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/TokenRejectExample.java @@ -1,32 +1,13 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.ArrayList; import java.util.List; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to reject a token (part of HIP-904). @@ -42,12 +23,14 @@ class TokenRejectExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -60,7 +43,7 @@ class TokenRejectExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -94,24 +77,24 @@ public static void main(String[] args) throws Exception { System.out.println("Creating treasury and receiver accounts..."); // Create a treasury account. var treasuryAccountId = new AccountCreateTransaction() - .setKey(treasuryAccountPublicKey) - .setMaxAutomaticTokenAssociations(100) - .freezeWith(client) - .sign(treasuryAccountPrivateKey) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(treasuryAccountPublicKey) + .setMaxAutomaticTokenAssociations(100) + .freezeWith(client) + .sign(treasuryAccountPrivateKey) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(treasuryAccountId); // Create a receiver account with unlimited max auto associations (-1). var receiverAccountId = new AccountCreateTransaction() - .setKey(receiverAccountPublicKey) - .setMaxAutomaticTokenAssociations(-1) - .freezeWith(client) - .sign(receiverAccountPrivateKey) - .execute(client) - .getReceipt(client) - .accountId; + .setKey(receiverAccountPublicKey) + .setMaxAutomaticTokenAssociations(-1) + .freezeWith(client) + .sign(receiverAccountPrivateKey) + .execute(client) + .getReceipt(client) + .accountId; Objects.requireNonNull(receiverAccountId); /* @@ -122,36 +105,36 @@ public static void main(String[] args) throws Exception { // Create a Fungible Token. final int FUNGIBLE_TOKEN_SUPPLY = 1_000_000; TokenId fungibleTokenId = new TokenCreateTransaction() - .setTokenName("HIP-904 FT") - .setTokenSymbol("HIP904FT") - .setDecimals(0) - .setInitialSupply(FUNGIBLE_TOKEN_SUPPLY) - .setMaxSupply(FUNGIBLE_TOKEN_SUPPLY) - .setTreasuryAccountId(treasuryAccountId) - .setSupplyType(TokenSupplyType.FINITE) - .setAdminKey(treasuryAccountPublicKey) - .freezeWith(client) - .sign(treasuryAccountPrivateKey) - .execute(client) - .getReceipt(client) - .tokenId; + .setTokenName("HIP-904 FT") + .setTokenSymbol("HIP904FT") + .setDecimals(0) + .setInitialSupply(FUNGIBLE_TOKEN_SUPPLY) + .setMaxSupply(FUNGIBLE_TOKEN_SUPPLY) + .setTreasuryAccountId(treasuryAccountId) + .setSupplyType(TokenSupplyType.FINITE) + .setAdminKey(treasuryAccountPublicKey) + .freezeWith(client) + .sign(treasuryAccountPrivateKey) + .execute(client) + .getReceipt(client) + .tokenId; Objects.requireNonNull(fungibleTokenId); // Create NFT. TokenId nftId = new TokenCreateTransaction() - .setTokenName("HIP-904 NFT") - .setTokenSymbol("HIP904NFT") - .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) - .setTreasuryAccountId(treasuryAccountId) - .setSupplyType(TokenSupplyType.FINITE) - .setMaxSupply(3) - .setAdminKey(treasuryAccountPublicKey) - .setSupplyKey(treasuryAccountPublicKey) - .freezeWith(client) - .sign(treasuryAccountPrivateKey) - .execute(client) - .getReceipt(client) - .tokenId; + .setTokenName("HIP-904 NFT") + .setTokenSymbol("HIP904NFT") + .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) + .setTreasuryAccountId(treasuryAccountId) + .setSupplyType(TokenSupplyType.FINITE) + .setMaxSupply(3) + .setAdminKey(treasuryAccountPublicKey) + .setSupplyKey(treasuryAccountPublicKey) + .freezeWith(client) + .sign(treasuryAccountPrivateKey) + .execute(client) + .getReceipt(client) + .tokenId; Objects.requireNonNull(nftId); /* @@ -160,12 +143,12 @@ public static void main(String[] args) throws Exception { */ System.out.println("Minting three NFTs..."); var tokenMintTxReceipt = new TokenMintTransaction() - .setTokenId(nftId) - .setMetadata(generateNftMetadata((byte) 3)) - .freezeWith(client) - .sign(treasuryAccountPrivateKey) - .execute(client) - .getReceipt(client); + .setTokenId(nftId) + .setMetadata(generateNftMetadata((byte) 3)) + .freezeWith(client) + .sign(treasuryAccountPrivateKey) + .execute(client) + .getReceipt(client); var nftSerials = tokenMintTxReceipt.serials; /* @@ -174,26 +157,26 @@ public static void main(String[] args) throws Exception { */ System.out.println("Transferring tokens to the receiver..."); new TransferTransaction() - .addTokenTransfer(fungibleTokenId, treasuryAccountId, -1_000) - .addTokenTransfer(fungibleTokenId, receiverAccountId, 1_000) - .addNftTransfer(nftId.nft(nftSerials.get(0)), treasuryAccountId, receiverAccountId) - .addNftTransfer(nftId.nft(nftSerials.get(1)), treasuryAccountId, receiverAccountId) - .addNftTransfer(nftId.nft(nftSerials.get(2)), treasuryAccountId, receiverAccountId) - .freezeWith(client) - .sign(treasuryAccountPrivateKey) - .execute(client) - .getReceipt(client); + .addTokenTransfer(fungibleTokenId, treasuryAccountId, -1_000) + .addTokenTransfer(fungibleTokenId, receiverAccountId, 1_000) + .addNftTransfer(nftId.nft(nftSerials.get(0)), treasuryAccountId, receiverAccountId) + .addNftTransfer(nftId.nft(nftSerials.get(1)), treasuryAccountId, receiverAccountId) + .addNftTransfer(nftId.nft(nftSerials.get(2)), treasuryAccountId, receiverAccountId) + .freezeWith(client) + .sign(treasuryAccountPrivateKey) + .execute(client) + .getReceipt(client); /* * Step 6: * Check receiver account balance. */ - var receiverAccountBalance = new AccountBalanceQuery() - .setAccountId(receiverAccountId) - .execute(client); + var receiverAccountBalance = + new AccountBalanceQuery().setAccountId(receiverAccountId).execute(client); if (receiverAccountBalance.tokens.get(fungibleTokenId) == 1_000) { - System.out.println("Receiver account has: " + receiverAccountBalance.tokens.get(fungibleTokenId) + " example fungible tokens."); + System.out.println("Receiver account has: " + receiverAccountBalance.tokens.get(fungibleTokenId) + + " example fungible tokens."); } else { throw new Exception("Failed to transfer Fungible Token to the receiver account!"); } @@ -210,12 +193,12 @@ public static void main(String[] args) throws Exception { */ System.out.println("Receiver rejects example fungible tokens..."); new TokenRejectTransaction() - .setOwnerId(receiverAccountId) - .addTokenId(fungibleTokenId) - .freezeWith(client) - .sign(receiverAccountPrivateKey) - .execute(client) - .getReceipt(client); + .setOwnerId(receiverAccountId) + .addTokenId(fungibleTokenId) + .freezeWith(client) + .sign(receiverAccountPrivateKey) + .execute(client) + .getReceipt(client); /* * Step 8: @@ -223,35 +206,32 @@ public static void main(String[] args) throws Exception { */ System.out.println("Receiver rejects example NFTs..."); new TokenRejectFlow() - .setOwnerId(receiverAccountId) - .setNftIds(List.of( - nftId.nft(nftSerials.get(0)), - nftId.nft(nftSerials.get(1)), - nftId.nft(nftSerials.get(2)) - )) - .freezeWith(client) - .sign(receiverAccountPrivateKey) - .execute(client) - .getReceipt(client); + .setOwnerId(receiverAccountId) + .setNftIds(List.of( + nftId.nft(nftSerials.get(0)), nftId.nft(nftSerials.get(1)), nftId.nft(nftSerials.get(2)))) + .freezeWith(client) + .sign(receiverAccountPrivateKey) + .execute(client) + .getReceipt(client); /* * Step 9: * Check receiver account balance after token reject. */ - var receiverAccountBalance_AfterTokenReject = new AccountBalanceQuery() - .setAccountId(receiverAccountId) - .execute(client); + var receiverAccountBalance_AfterTokenReject = + new AccountBalanceQuery().setAccountId(receiverAccountId).execute(client); if (receiverAccountBalance_AfterTokenReject.tokens.get(fungibleTokenId) == 0) { System.out.println("Receiver account has (after rejecting tokens): " - + receiverAccountBalance_AfterTokenReject.tokens.get(fungibleTokenId) + " example fungible tokens."); + + receiverAccountBalance_AfterTokenReject.tokens.get(fungibleTokenId) + + " example fungible tokens."); } else { throw new Exception("Failed to reject Fungible Token!"); } if (receiverAccountBalance_AfterTokenReject.tokens.get(nftId) == null) { System.out.println("Receiver account has (after rejecting tokens): " - + receiverAccountBalance_AfterTokenReject.tokens.get(nftId) + " example NFTs."); + + receiverAccountBalance_AfterTokenReject.tokens.get(nftId) + " example NFTs."); } else { throw new Exception("Failed to reject NFT!"); } @@ -260,20 +240,18 @@ public static void main(String[] args) throws Exception { * Step 10: * Check treasury account balance after token reject. */ - var treasuryAccountBalance = new AccountBalanceQuery() - .setAccountId(treasuryAccountId) - .execute(client); + var treasuryAccountBalance = + new AccountBalanceQuery().setAccountId(treasuryAccountId).execute(client); if (treasuryAccountBalance.tokens.get(fungibleTokenId) == FUNGIBLE_TOKEN_SUPPLY) { System.out.println("Treasury account has: " + treasuryAccountBalance.tokens.get(fungibleTokenId) - + " example fungible tokens."); + + " example fungible tokens."); } else { throw new Exception("Failed to transfer Fungible Token to the treasury account during token rejection!"); } if (treasuryAccountBalance.tokens.get(nftId) == 3) { - System.out.println("Receiver account has: " + receiverAccountBalance.tokens.get(nftId) - + " example NFTs."); + System.out.println("Receiver account has: " + receiverAccountBalance.tokens.get(nftId) + " example NFTs."); } else { throw new Exception("Failed to transfer NFT to the treasury account during token rejection!"); } @@ -283,32 +261,32 @@ public static void main(String[] args) throws Exception { * Delete created accounts and tokens. */ new AccountDeleteTransaction() - .setAccountId(treasuryAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(treasuryAccountPrivateKey) - .execute(client); + .setAccountId(treasuryAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(treasuryAccountPrivateKey) + .execute(client); new AccountDeleteTransaction() - .setAccountId(receiverAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(receiverAccountPrivateKey) - .execute(client); + .setAccountId(receiverAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(receiverAccountPrivateKey) + .execute(client); new TokenDeleteTransaction() - .setTokenId(fungibleTokenId) - .freezeWith(client) - .sign(treasuryAccountPrivateKey) - .execute(client) - .getReceipt(client); + .setTokenId(fungibleTokenId) + .freezeWith(client) + .sign(treasuryAccountPrivateKey) + .execute(client) + .getReceipt(client); new TokenDeleteTransaction() - .setTokenId(nftId) - .freezeWith(client) - .sign(treasuryAccountPrivateKey) - .execute(client) - .getReceipt(client); + .setTokenId(nftId) + .freezeWith(client) + .sign(treasuryAccountPrivateKey) + .execute(client) + .getReceipt(client); client.close(); @@ -325,5 +303,4 @@ private static List generateNftMetadata(byte metadataCount) { return metadatas; } - } diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TopicWithAdminKeyExample.java b/examples/src/main/java/org/hiero/sdk/examples/TopicWithAdminKeyExample.java similarity index 80% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/TopicWithAdminKeyExample.java rename to examples/src/main/java/org/hiero/sdk/examples/TopicWithAdminKeyExample.java index 0ce17ea2d..df17d90c7 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TopicWithAdminKeyExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/TopicWithAdminKeyExample.java @@ -1,32 +1,13 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Arrays; import java.util.Collections; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to create and manage HCS topic using a threshold key as the adminKey and going through a key rotation to a new @@ -46,12 +27,14 @@ class TopicWithAdminKeyExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -64,7 +47,7 @@ class TopicWithAdminKeyExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -108,9 +91,9 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating topic create transaction..."); Transaction topicCreateTx = new TopicCreateTransaction() - .setTopicMemo("demo topic") - .setAdminKey(thresholdKey) - .freezeWith(client); + .setTopicMemo("demo topic") + .setAdminKey(thresholdKey) + .freezeWith(client); /* * Step 4: @@ -157,10 +140,10 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating topic update transaction..."); Transaction topicUpdateTx = new TopicUpdateTransaction() - .setTopicId(hederaTopicId) - .setTopicMemo("This topic will be updated") - .setAdminKey(newThresholdKey) - .freezeWith(client); + .setTopicId(hederaTopicId) + .setTopicMemo("This topic will be updated") + .setAdminKey(newThresholdKey) + .freezeWith(client); /* * Step 9: @@ -197,18 +180,16 @@ public static void main(String[] args) throws Exception { * Step 11: * Query the topic info and output it. */ - TopicInfo hederaTopicInfo = new TopicInfoQuery() - .setTopicId(hederaTopicId) - .execute(client); + TopicInfo hederaTopicInfo = + new TopicInfoQuery().setTopicId(hederaTopicId).execute(client); System.out.println("Topic info: " + hederaTopicInfo); /* * Clean up: * Delete created topic. */ - var topicDeleteTransaction = new TopicDeleteTransaction() - .setTopicId(hederaTopicId) - .freezeWith(client); + var topicDeleteTransaction = + new TopicDeleteTransaction().setTopicId(hederaTopicId).freezeWith(client); Arrays.stream(newAdminKeys, 0, 3).forEach(k -> { topicDeleteTransaction.sign(k); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransactionSerializationExample.java b/examples/src/main/java/org/hiero/sdk/examples/TransactionSerializationExample.java similarity index 66% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransactionSerializationExample.java rename to examples/src/main/java/org/hiero/sdk/examples/TransactionSerializationExample.java index 07833f989..551d06edf 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransactionSerializationExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/TransactionSerializationExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to serialize incomplete transaction, deserialize it, complete and execute (HIP-745). @@ -40,12 +21,14 @@ class TransactionSerializationExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -58,7 +41,7 @@ class TransactionSerializationExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -80,15 +63,11 @@ public static void main(String[] args) throws Exception { * Check Hbar balance of sender and recipient. */ AccountId recipientId = AccountId.fromString("0.0.3"); - Hbar senderBalanceBefore = new AccountBalanceQuery() - .setAccountId(OPERATOR_ID) - .execute(client) - .hbars; + Hbar senderBalanceBefore = + new AccountBalanceQuery().setAccountId(OPERATOR_ID).execute(client).hbars; - Hbar recipientBalanceBefore = new AccountBalanceQuery() - .setAccountId(recipientId) - .execute(client) - .hbars; + Hbar recipientBalanceBefore = + new AccountBalanceQuery().setAccountId(recipientId).execute(client).hbars; System.out.println("Sender (" + OPERATOR_ID + ") balance before transfer: " + senderBalanceBefore); System.out.println("Recipient (" + recipientId + ") balance before transfer: " + recipientBalanceBefore); @@ -100,9 +79,9 @@ public static void main(String[] args) throws Exception { System.out.println("Creating the transfer transaction..."); Hbar transferAmount = Hbar.from(1); var transferTx = new TransferTransaction() - // addSender and addRecipient can be called as many times as you want as long as the total sum from - // both sides is equivalent. - .addHbarTransfer(OPERATOR_ID, transferAmount.negated()); + // addSender and addRecipient can be called as many times as you want as long as the total sum from + // both sides is equivalent. + .addHbarTransfer(OPERATOR_ID, transferAmount.negated()); /* * Step 3: @@ -125,9 +104,9 @@ public static void main(String[] args) throws Exception { */ System.out.println("Completing and executing the transfer transaction..."); var transferTxResponse = transferTxDeserialized - .addHbarTransfer(recipientId, transferAmount) - .setTransactionMemo("HIP-745 example") - .execute(client); + .addHbarTransfer(recipientId, transferAmount) + .setTransactionMemo("HIP-745 example") + .execute(client); System.out.println("Transaction info: " + transferTxResponse); TransactionRecord transferTxRecord = transferTxResponse.getRecord(client); @@ -138,15 +117,11 @@ public static void main(String[] args) throws Exception { * Step 6: * Check Hbar balance of the sender and recipient after transfer transaction was executed. */ - Hbar senderBalanceAfter = new AccountBalanceQuery() - .setAccountId(OPERATOR_ID) - .execute(client) - .hbars; - - Hbar receiptBalanceAfter = new AccountBalanceQuery() - .setAccountId(recipientId) - .execute(client) - .hbars; + Hbar senderBalanceAfter = + new AccountBalanceQuery().setAccountId(OPERATOR_ID).execute(client).hbars; + + Hbar receiptBalanceAfter = + new AccountBalanceQuery().setAccountId(recipientId).execute(client).hbars; System.out.println("Sender (" + OPERATOR_ID + ") balance after transfer: " + senderBalanceAfter); System.out.println("Recipient (" + recipientId + ") balance after transfer: " + receiptBalanceAfter); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransferCryptoExample.java b/examples/src/main/java/org/hiero/sdk/examples/TransferCryptoExample.java similarity index 60% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransferCryptoExample.java rename to examples/src/main/java/org/hiero/sdk/examples/TransferCryptoExample.java index a99e149f6..02cfe3f17 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransferCryptoExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/TransferCryptoExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to transfer Hbar between accounts. @@ -40,12 +21,14 @@ class TransferCryptoExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -58,7 +41,7 @@ class TransferCryptoExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -81,15 +64,11 @@ public static void main(String[] args) throws Exception { * Step 1: * Check Hbar balance of sender and recipient. */ - Hbar senderBalanceBefore = new AccountBalanceQuery() - .setAccountId(OPERATOR_ID) - .execute(client) - .hbars; + Hbar senderBalanceBefore = + new AccountBalanceQuery().setAccountId(OPERATOR_ID).execute(client).hbars; - Hbar recipientBalanceBefore = new AccountBalanceQuery() - .setAccountId(recipientId) - .execute(client) - .hbars; + Hbar recipientBalanceBefore = + new AccountBalanceQuery().setAccountId(recipientId).execute(client).hbars; System.out.println("Sender (" + OPERATOR_ID + ") balance before transfer: " + senderBalanceBefore); System.out.println("Recipient (" + recipientId + ") balance before transfer: " + recipientBalanceBefore); @@ -101,12 +80,12 @@ public static void main(String[] args) throws Exception { System.out.println("Executing the transfer transaction..."); Hbar transferAmount = Hbar.from(1); TransactionResponse transferTxResponse = new TransferTransaction() - // addSender and addRecipient can be called as many times as you want as long as the total sum from - // both sides is equivalent. - .addHbarTransfer(OPERATOR_ID, transferAmount.negated()) - .addHbarTransfer(recipientId, transferAmount) - .setTransactionMemo("Transfer example") - .execute(client); + // addSender and addRecipient can be called as many times as you want as long as the total sum from + // both sides is equivalent. + .addHbarTransfer(OPERATOR_ID, transferAmount.negated()) + .addHbarTransfer(recipientId, transferAmount) + .setTransactionMemo("Transfer example") + .execute(client); System.out.println("Transaction info: " + transferTxResponse); TransactionRecord record = transferTxResponse.getRecord(client); @@ -117,15 +96,11 @@ public static void main(String[] args) throws Exception { * Step 6: * Check Hbar balance of the sender and recipient after transfer transaction was executed. */ - Hbar senderBalanceAfter = new AccountBalanceQuery() - .setAccountId(OPERATOR_ID) - .execute(client) - .hbars; - - Hbar receiptBalanceAfter = new AccountBalanceQuery() - .setAccountId(recipientId) - .execute(client) - .hbars; + Hbar senderBalanceAfter = + new AccountBalanceQuery().setAccountId(OPERATOR_ID).execute(client).hbars; + + Hbar receiptBalanceAfter = + new AccountBalanceQuery().setAccountId(recipientId).execute(client).hbars; System.out.println("Sender (" + OPERATOR_ID + ") balance after transfer: " + senderBalanceAfter); System.out.println("Recipient (" + recipientId + ") balance after transfer: " + receiptBalanceAfter); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransferTokensExample.java b/examples/src/main/java/org/hiero/sdk/examples/TransferTokensExample.java similarity index 52% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransferTokensExample.java rename to examples/src/main/java/org/hiero/sdk/examples/TransferTokensExample.java index f0b9821b6..165d76900 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransferTokensExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/TransferTokensExample.java @@ -1,31 +1,12 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Collections; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to transfer tokens between accounts. @@ -41,12 +22,14 @@ class TransferTokensExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -59,7 +42,7 @@ class TransferTokensExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -95,10 +78,10 @@ public static void main(String[] args) throws Exception { System.out.println("Creating accounts..."); Hbar initialBalance = Hbar.from(1); TransactionResponse aliceAccountCreateTxResponse = new AccountCreateTransaction() - // The only required property here is key. - .setKey(alicePublicKey) - .setInitialBalance(initialBalance) - .execute(client); + // The only required property here is key. + .setKey(alicePublicKey) + .setInitialBalance(initialBalance) + .execute(client); // This will wait for the receipt to become available. TransactionReceipt aliceAccountCreateTxReceipt = aliceAccountCreateTxResponse.getReceipt(client); @@ -107,10 +90,10 @@ public static void main(String[] args) throws Exception { System.out.println("Created Alice's account with ID: " + aliceAccountId); TransactionResponse bobAccountCreateTxResponse = new AccountCreateTransaction() - // The only required property here is key. - .setKey(bobPublicKey) - .setInitialBalance(initialBalance) - .execute(client); + // The only required property here is key. + .setKey(bobPublicKey) + .setInitialBalance(initialBalance) + .execute(client); // This will wait for the receipt to become available. TransactionReceipt bobAccountCreateTxReceipt = bobAccountCreateTxResponse.getReceipt(client); @@ -124,19 +107,19 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating Fungible Token..."); TransactionResponse tokenCreateTxResponse = new TokenCreateTransaction() - .setNodeAccountIds(Collections.singletonList(bobAccountCreateTxResponse.nodeId)) - .setTokenName("Example Fungible Token for Transfer demo") - .setTokenSymbol("EFT") - .setDecimals(3) - .setInitialSupply(1_000_000) - .setTreasuryAccountId(OPERATOR_ID) - .setAdminKey(operatorPublicKey) - .setFreezeKey(operatorPublicKey) - .setWipeKey(operatorPublicKey) - .setKycKey(operatorPublicKey) - .setSupplyKey(operatorPublicKey) - .setFreezeDefault(false) - .execute(client); + .setNodeAccountIds(Collections.singletonList(bobAccountCreateTxResponse.nodeId)) + .setTokenName("Example Fungible Token for Transfer demo") + .setTokenSymbol("EFT") + .setDecimals(3) + .setInitialSupply(1_000_000) + .setTreasuryAccountId(OPERATOR_ID) + .setAdminKey(operatorPublicKey) + .setFreezeKey(operatorPublicKey) + .setWipeKey(operatorPublicKey) + .setKycKey(operatorPublicKey) + .setSupplyKey(operatorPublicKey) + .setFreezeDefault(false) + .execute(client); TokenId tokenId = Objects.requireNonNull(tokenCreateTxResponse.getReceipt(client).tokenId); Objects.requireNonNull(tokenId); @@ -148,26 +131,26 @@ public static void main(String[] args) throws Exception { */ System.out.println("Associating the token with created accounts..."); new TokenAssociateTransaction() - .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) - .setAccountId(aliceAccountId) - .setTokenIds(Collections.singletonList(tokenId)) - .freezeWith(client) - .sign(OPERATOR_KEY) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) + .setAccountId(aliceAccountId) + .setTokenIds(Collections.singletonList(tokenId)) + .freezeWith(client) + .sign(OPERATOR_KEY) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); System.out.println("Associated account " + aliceAccountId + " with token " + tokenId); new TokenAssociateTransaction() - .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) - .setAccountId(bobAccountId) - .setTokenIds(Collections.singletonList(tokenId)) - .freezeWith(client) - .sign(OPERATOR_KEY) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) + .setAccountId(bobAccountId) + .setTokenIds(Collections.singletonList(tokenId)) + .freezeWith(client) + .sign(OPERATOR_KEY) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); System.out.println("Associated account " + bobAccountId + " with token " + tokenId); @@ -177,20 +160,20 @@ public static void main(String[] args) throws Exception { */ System.out.println("Granting token KYC for created accounts..."); new TokenGrantKycTransaction() - .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) - .setAccountId(aliceAccountId) - .setTokenId(tokenId) - .execute(client) - .getReceipt(client); + .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) + .setAccountId(aliceAccountId) + .setTokenId(tokenId) + .execute(client) + .getReceipt(client); System.out.println("Granted KYC for account " + aliceAccountId + " on token " + tokenId); new TokenGrantKycTransaction() - .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) - .setAccountId(bobAccountId) - .setTokenId(tokenId) - .execute(client) - .getReceipt(client); + .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) + .setAccountId(bobAccountId) + .setTokenId(tokenId) + .execute(client) + .getReceipt(client); System.out.println("Granted KYC for account " + bobAccountId + " on token " + tokenId); @@ -200,13 +183,14 @@ public static void main(String[] args) throws Exception { */ System.out.println("Transferring tokens from operator's (treasury) account to the `accountId1`..."); new TransferTransaction() - .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) - .addTokenTransfer(tokenId, OPERATOR_ID, -10) - .addTokenTransfer(tokenId, aliceAccountId, 10) - .execute(client) - .getReceipt(client); + .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) + .addTokenTransfer(tokenId, OPERATOR_ID, -10) + .addTokenTransfer(tokenId, aliceAccountId, 10) + .execute(client) + .getReceipt(client); - System.out.println("Sent 10 tokens from account " + OPERATOR_ID + " to account " + aliceAccountId + " on token " + tokenId); + System.out.println("Sent 10 tokens from account " + OPERATOR_ID + " to account " + aliceAccountId + " on token " + + tokenId); /* * Step 6: @@ -214,15 +198,16 @@ public static void main(String[] args) throws Exception { */ System.out.println("Transferring tokens from the `accountId1` to the `accountId2`..."); new TransferTransaction() - .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) - .addTokenTransfer(tokenId, aliceAccountId, -10) - .addTokenTransfer(tokenId, bobAccountId, 10) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) + .addTokenTransfer(tokenId, aliceAccountId, -10) + .addTokenTransfer(tokenId, bobAccountId, 10) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); - System.out.println("Sent 10 tokens from account " + aliceAccountId + " to account " + bobAccountId + " on token " + tokenId); + System.out.println("Sent 10 tokens from account " + aliceAccountId + " to account " + bobAccountId + + " on token " + tokenId); /* * Step 6: @@ -230,51 +215,52 @@ public static void main(String[] args) throws Exception { */ System.out.println("Transferring tokens from the `accountId2` to the `accountId1`..."); new TransferTransaction() - .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) - .addTokenTransfer(tokenId, bobAccountId, -10) - .addTokenTransfer(tokenId, aliceAccountId, 10) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) + .addTokenTransfer(tokenId, bobAccountId, -10) + .addTokenTransfer(tokenId, aliceAccountId, 10) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); - System.out.println("Sent 10 tokens from account " + bobAccountId + " to account " + aliceAccountId + " on token " + tokenId); + System.out.println("Sent 10 tokens from account " + bobAccountId + " to account " + aliceAccountId + + " on token " + tokenId); /* * Clean up: * Delete created accounts and tokens. */ new TokenWipeTransaction() - .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) - .setTokenId(tokenId) - .setAccountId(aliceAccountId) - .setAmount(10) - .execute(client) - .getReceipt(client); + .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) + .setTokenId(tokenId) + .setAccountId(aliceAccountId) + .setAmount(10) + .execute(client) + .getReceipt(client); new TokenDeleteTransaction() - .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) - .setTokenId(tokenId) - .execute(client) - .getReceipt(client); + .setNodeAccountIds(Collections.singletonList(tokenCreateTxResponse.nodeId)) + .setTokenId(tokenId) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(aliceAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(OPERATOR_KEY) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(aliceAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(OPERATOR_KEY) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(bobAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(OPERATOR_KEY) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(bobAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(OPERATOR_KEY) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransferUsingEvmAddressExample.java b/examples/src/main/java/org/hiero/sdk/examples/TransferUsingEvmAddressExample.java similarity index 68% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransferUsingEvmAddressExample.java rename to examples/src/main/java/org/hiero/sdk/examples/TransferUsingEvmAddressExample.java index 2ab3961ed..c7f05bec6 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/TransferUsingEvmAddressExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/TransferUsingEvmAddressExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2023 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to transfer Hbar or tokens to a Hedera account using their public-address (HIP-583). @@ -40,12 +21,14 @@ class TransferUsingEvmAddressExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -58,7 +41,7 @@ class TransferUsingEvmAddressExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -102,9 +85,9 @@ public static void main(String[] args) throws Exception { */ System.out.println("Transferring Hbar to Alice's account..."); TransferTransaction transferTx = new TransferTransaction() - .addHbarTransfer(OPERATOR_ID, Hbar.from(1).negated()) - .addHbarTransfer(aliceEvmAddress, Hbar.from(1)) - .freezeWith(client); + .addHbarTransfer(OPERATOR_ID, Hbar.from(1).negated()) + .addHbarTransfer(aliceEvmAddress, Hbar.from(1)) + .freezeWith(client); TransferTransaction transferTxSigned = transferTx.sign(OPERATOR_KEY); TransactionResponse transferTxResponse = transferTxSigned.execute(client); @@ -114,9 +97,9 @@ public static void main(String[] args) throws Exception { * Get the child receipt or child record to return the Hedera Account ID for the new account that was created. */ TransactionReceipt transferTxReceipt = new TransactionReceiptQuery() - .setTransactionId(transferTxResponse.transactionId) - .setIncludeChildren(true) - .execute(client); + .setTransactionId(transferTxResponse.transactionId) + .setIncludeChildren(true) + .execute(client); AccountId aliceAccountId = transferTxReceipt.children.get(0).accountId; Objects.requireNonNull(aliceAccountId); @@ -126,9 +109,8 @@ public static void main(String[] args) throws Exception { * Step 6: * Get the AccountInfo on the new account and show it is a hollow account by not having a public key. */ - AccountInfo aliceAccountInfo_BeforeEnhancing = new AccountInfoQuery() - .setAccountId(aliceAccountId) - .execute(client); + AccountInfo aliceAccountInfo_BeforeEnhancing = + new AccountInfoQuery().setAccountId(aliceAccountId).execute(client); System.out.println("Alice's account info: " + aliceAccountInfo_BeforeEnhancing); @@ -142,9 +124,8 @@ public static void main(String[] args) throws Exception { PublicKey bobPublicKey = bobPrivateKey.getPublicKey(); System.out.println("Creating Bob's account..."); - AccountCreateTransaction accountCreateTx = new AccountCreateTransaction() - .setKey(bobPublicKey) - .freezeWith(client); + AccountCreateTransaction accountCreateTx = + new AccountCreateTransaction().setKey(bobPublicKey).freezeWith(client); /* * Step 8: @@ -162,11 +143,11 @@ public static void main(String[] args) throws Exception { * Get the AccountInfo of the account and show the account is now a complete account * by returning the public key on the account. */ - AccountInfo aliceAccountInfo_AfterEnhancing = new AccountInfoQuery() - .setAccountId(aliceAccountId) - .execute(client); + AccountInfo aliceAccountInfo_AfterEnhancing = + new AccountInfoQuery().setAccountId(aliceAccountId).execute(client); - System.out.println("The public key of the newly created (and now complete) account: " + aliceAccountInfo_AfterEnhancing.key); + System.out.println("The public key of the newly created (and now complete) account: " + + aliceAccountInfo_AfterEnhancing.key); /* * Clean up: @@ -175,20 +156,20 @@ public static void main(String[] args) throws Exception { client.setOperator(OPERATOR_ID, OPERATOR_KEY); new AccountDeleteTransaction() - .setAccountId(aliceAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(aliceAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); new AccountDeleteTransaction() - .setAccountId(bobAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(bobPrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(bobAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(bobPrivateKey) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/UpdateAccountPublicKeyExample.java b/examples/src/main/java/org/hiero/sdk/examples/UpdateAccountPublicKeyExample.java similarity index 64% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/UpdateAccountPublicKeyExample.java rename to examples/src/main/java/org/hiero/sdk/examples/UpdateAccountPublicKeyExample.java index e1b0eeea2..46f0a10d4 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/UpdateAccountPublicKeyExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/UpdateAccountPublicKeyExample.java @@ -1,30 +1,11 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to update account's key. @@ -40,12 +21,14 @@ class UpdateAccountPublicKeyExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -58,7 +41,7 @@ class UpdateAccountPublicKeyExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -93,9 +76,9 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating new account..."); TransactionResponse accountCreateTxResponse = new AccountCreateTransaction() - .setKey(publicKey1) - .setInitialBalance(Hbar.from(1)) - .execute(client); + .setKey(publicKey1) + .setInitialBalance(Hbar.from(1)) + .execute(client); AccountId accountId = Objects.requireNonNull(accountCreateTxResponse.getReceipt(client).accountId); Objects.requireNonNull(accountId); @@ -107,14 +90,14 @@ public static void main(String[] args) throws Exception { */ System.out.println("Updating public key of new account...(Setting key: " + publicKey2 + ")."); TransactionResponse accountUpdateTxResponse = new AccountUpdateTransaction() - .setAccountId(accountId) - .setKey(publicKey2) - .freezeWith(client) - // Sign with the previous key and the new key. - .sign(privateKey1) - .sign(privateKey2) - // Execute will implicitly sign with the operator. - .execute(client); + .setAccountId(accountId) + .setKey(publicKey2) + .freezeWith(client) + // Sign with the previous key and the new key. + .sign(privateKey1) + .sign(privateKey2) + // Execute will implicitly sign with the operator. + .execute(client); // (Important!) Wait for the transaction to complete by querying the receipt. accountUpdateTxResponse.getReceipt(client); @@ -123,9 +106,7 @@ public static void main(String[] args) throws Exception { * Step 3: * Get account info to confirm the key was changed. */ - AccountInfo accountInfo = new AccountInfoQuery() - .setAccountId(accountId) - .execute(client); + AccountInfo accountInfo = new AccountInfoQuery().setAccountId(accountId).execute(client); System.out.println("New account public key: " + accountInfo.key); @@ -134,12 +115,12 @@ public static void main(String[] args) throws Exception { * Delete created account. */ new AccountDeleteTransaction() - .setAccountId(accountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(privateKey2) - .execute(client) - .getReceipt(client); + .setAccountId(accountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(privateKey2) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/UpdateNftsMetadataExample.java b/examples/src/main/java/org/hiero/sdk/examples/UpdateNftsMetadataExample.java similarity index 66% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/UpdateNftsMetadataExample.java rename to examples/src/main/java/org/hiero/sdk/examples/UpdateNftsMetadataExample.java index bacf9d84f..7d68d45af 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/UpdateNftsMetadataExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/UpdateNftsMetadataExample.java @@ -1,32 +1,13 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Arrays; import java.util.List; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to update NFTs' metadata (HIP-657). @@ -42,12 +23,14 @@ class UpdateNftsMetadataExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -60,7 +43,7 @@ class UpdateNftsMetadataExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -94,17 +77,17 @@ public static void main(String[] args) throws Exception { * Create a non-fungible token (NFT) with the metadata key field set. */ System.out.println("The beginning of the first example (mutable token's metadata)."); - byte[] initialMetadata = new byte[]{1}; + byte[] initialMetadata = new byte[] {1}; System.out.println("Creating mutable NFT with the metadata key field set..."); var mutableNftCreateTx = new TokenCreateTransaction() - .setTokenName("HIP-657 Mutable NFT") - .setTokenSymbol("HIP657MNFT") - .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) - .setTreasuryAccountId(OPERATOR_ID) - .setAdminKey(operatorKeyPublic) - .setSupplyKey(operatorKeyPublic) - .setMetadataKey(metadataPublicKey) - .freezeWith(client); + .setTokenName("HIP-657 Mutable NFT") + .setTokenSymbol("HIP657MNFT") + .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) + .setTreasuryAccountId(OPERATOR_ID) + .setAdminKey(operatorKeyPublic) + .setSupplyKey(operatorKeyPublic) + .setMetadataKey(metadataPublicKey) + .freezeWith(client); var mutableNftCreateTxResponse = mutableNftCreateTx.sign(OPERATOR_KEY).execute(client); var mutableNftCreateTxReceipt = mutableNftCreateTxResponse.getReceipt(client); @@ -117,9 +100,7 @@ public static void main(String[] args) throws Exception { * Step 3: * Query for the mutable token information stored in consensus node state to see that the Metadata Key is set. */ - var mutableNftInfo = new TokenInfoQuery() - .setTokenId(mutableNftId) - .execute(client); + var mutableNftInfo = new TokenInfoQuery().setTokenId(mutableNftId).execute(client); System.out.println("Mutable NFT metadata key: " + mutableNftInfo.metadataKey); @@ -128,9 +109,8 @@ public static void main(String[] args) throws Exception { * Mint the first NFT and set the initial metadata for the NFT. */ System.out.println("Minting NFTs..."); - var mutableNftMintTx = new TokenMintTransaction() - .setMetadata(List.of(initialMetadata)) - .setTokenId(mutableNftId); + var mutableNftMintTx = + new TokenMintTransaction().setMetadata(List.of(initialMetadata)).setTokenId(mutableNftId); mutableNftMintTx.getMetadata().forEach(metadata -> { System.out.println("Setting metadata: " + Arrays.toString(metadata)); @@ -155,11 +135,11 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating Alice's account..."); var aliceAccountCreateTx = new AccountCreateTransaction() - .setKey(operatorKeyPublic) - // If the account does not have any automatic token association, - // slots open ONLY then associate the NFT to the account. - .setMaxAutomaticTokenAssociations(10) - .execute(client); + .setKey(operatorKeyPublic) + // If the account does not have any automatic token association, + // slots open ONLY then associate the NFT to the account. + .setMaxAutomaticTokenAssociations(10) + .execute(client); var aliceAccountId = aliceAccountCreateTx.getReceipt(client).accountId; Objects.requireNonNull(aliceAccountId); @@ -171,27 +151,29 @@ public static void main(String[] args) throws Exception { */ System.out.println("Transferring the NFT to Alice's account..."); new TransferTransaction() - .addNftTransfer(mutableNftId.nft(mutableNftSerials.get(0)), OPERATOR_ID, aliceAccountId) - .execute(client); + .addNftTransfer(mutableNftId.nft(mutableNftSerials.get(0)), OPERATOR_ID, aliceAccountId) + .execute(client); /* * Step 7: * Update NFTs' metadata. */ - byte[] updatedMetadata = new byte[]{1, 2}; + byte[] updatedMetadata = new byte[] {1, 2}; System.out.println("Updating NFTs' metadata..."); var tokenUpdateNftsTx = new TokenUpdateNftsTransaction() - .setTokenId(mutableNftId) - .setSerials(mutableNftSerials) - .setMetadata(updatedMetadata) - .freezeWith(client); + .setTokenId(mutableNftId) + .setSerials(mutableNftSerials) + .setMetadata(updatedMetadata) + .freezeWith(client); System.out.println("Updated NFTs' metadata: " + Arrays.toString(tokenUpdateNftsTx.getMetadata())); - var tokenUpdateNftsTxResponse = tokenUpdateNftsTx.sign(metadataPrivateKey).execute(client); + var tokenUpdateNftsTxResponse = + tokenUpdateNftsTx.sign(metadataPrivateKey).execute(client); // Get receipt for update NFTs metadata transaction. var tokenUpdateNftsTxReceipt = tokenUpdateNftsTxResponse.getReceipt(client); - System.out.println("Token update nfts metadata transaction was complete with status: " + tokenUpdateNftsTxReceipt.status); + System.out.println( + "Token update nfts metadata transaction was complete with status: " + tokenUpdateNftsTxReceipt.status); // Check that metadata for the NFT was updated correctly. getMetadataList(client, mutableNftId, mutableNftSerials).forEach(metadata -> { @@ -207,15 +189,16 @@ public static void main(String[] args) throws Exception { System.out.println("The beginning of the second example (immutable token's metadata)."); System.out.println("Creating immutable NFT with the metadata key field set..."); var immutableNftCreateTx = new TokenCreateTransaction() - .setTokenName("HIP-657 Immutable NFT") - .setTokenSymbol("HIP657IMMNFT") - .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) - .setTreasuryAccountId(OPERATOR_ID) - .setSupplyKey(operatorKeyPublic) - .setMetadataKey(metadataPublicKey) - .freezeWith(client); - - var immutableNftCreateTxResponse = immutableNftCreateTx.sign(OPERATOR_KEY).execute(client); + .setTokenName("HIP-657 Immutable NFT") + .setTokenSymbol("HIP657IMMNFT") + .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) + .setTreasuryAccountId(OPERATOR_ID) + .setSupplyKey(operatorKeyPublic) + .setMetadataKey(metadataPublicKey) + .freezeWith(client); + + var immutableNftCreateTxResponse = + immutableNftCreateTx.sign(OPERATOR_KEY).execute(client); var immutableNftCreateTxReceipt = immutableNftCreateTxResponse.getReceipt(client); // Get the token ID of the token that was created. var immutableNftId = immutableNftCreateTxReceipt.tokenId; @@ -226,9 +209,7 @@ public static void main(String[] args) throws Exception { * Step 9: * Query for the mutable token information stored in consensus node state to see that the metadata key is set. */ - var immutableNftInfo = new TokenInfoQuery() - .setTokenId(immutableNftId) - .execute(client); + var immutableNftInfo = new TokenInfoQuery().setTokenId(immutableNftId).execute(client); System.out.println("Immutable NFT metadata key: " + immutableNftInfo.metadataKey); @@ -237,9 +218,8 @@ public static void main(String[] args) throws Exception { * Mint the first NFT and set the initial metadata for the NFT. */ System.out.println("Minting NFTs..."); - var immutableNftMintTx = new TokenMintTransaction() - .setMetadata(List.of(initialMetadata)) - .setTokenId(immutableNftId); + var immutableNftMintTx = + new TokenMintTransaction().setMetadata(List.of(initialMetadata)).setTokenId(immutableNftId); immutableNftMintTx.getMetadata().forEach(metadata -> { System.out.println("Setting metadata: " + Arrays.toString(metadata)); @@ -263,11 +243,11 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating Bob's account..."); var bobAccountCreateTx = new AccountCreateTransaction() - .setKey(operatorKeyPublic) - // If the account does not have any automatic token association, - // slots open ONLY then associate the NFT to the account. - .setMaxAutomaticTokenAssociations(10) - .execute(client); + .setKey(operatorKeyPublic) + // If the account does not have any automatic token association, + // slots open ONLY then associate the NFT to the account. + .setMaxAutomaticTokenAssociations(10) + .execute(client); var bobAccountId = bobAccountCreateTx.getReceipt(client).accountId; Objects.requireNonNull(bobAccountId); @@ -279,8 +259,8 @@ public static void main(String[] args) throws Exception { */ System.out.println("Transferring the NFT to Bob's account..."); new TransferTransaction() - .addNftTransfer(immutableNftId.nft(immutableNftSerials.get(0)), OPERATOR_ID, bobAccountId) - .execute(client); + .addNftTransfer(immutableNftId.nft(immutableNftSerials.get(0)), OPERATOR_ID, bobAccountId) + .execute(client); /* * Step 13: @@ -288,17 +268,19 @@ public static void main(String[] args) throws Exception { */ System.out.println("Updating NFTs' metadata..."); var immutableNftUpdateNftsTx = new TokenUpdateNftsTransaction() - .setTokenId(immutableNftId) - .setSerials(immutableNftSerials) - .setMetadata(updatedMetadata) - .freezeWith(client); + .setTokenId(immutableNftId) + .setSerials(immutableNftSerials) + .setMetadata(updatedMetadata) + .freezeWith(client); System.out.println("Updated NFTs' metadata: " + Arrays.toString(immutableNftUpdateNftsTx.getMetadata())); - var immutableNftUpdateNftsTxResponse = immutableNftUpdateNftsTx.sign(metadataPrivateKey).execute(client); + var immutableNftUpdateNftsTxResponse = + immutableNftUpdateNftsTx.sign(metadataPrivateKey).execute(client); // Get receipt for update NFTs metadata transaction. var immutableNftUpdateNftsTxReceipt = immutableNftUpdateNftsTxResponse.getReceipt(client); - System.out.println("Token update nfts metadata transaction was complete with status: " + immutableNftUpdateNftsTxReceipt.status); + System.out.println("Token update nfts metadata transaction was complete with status: " + + immutableNftUpdateNftsTxReceipt.status); // Check that metadata for the NFT was updated correctly. getMetadataList(client, immutableNftId, immutableNftSerials).forEach(metadata -> { @@ -309,10 +291,7 @@ public static void main(String[] args) throws Exception { * Clean up: * Delete created mutable token. */ - new TokenDeleteTransaction() - .setTokenId(mutableNftId) - .execute(client) - .getReceipt(client); + new TokenDeleteTransaction().setTokenId(mutableNftId).execute(client).getReceipt(client); client.close(); @@ -321,17 +300,15 @@ public static void main(String[] args) throws Exception { private static List getMetadataList(Client client, TokenId tokenId, List nftSerials) { return nftSerials.stream() - .map(serial -> new NftId(tokenId, serial)) - .flatMap(nftId -> { - try { - return new TokenNftInfoQuery() - .setNftId(nftId) - .execute(client).stream(); - } catch (Exception e) { - throw new RuntimeException(e); - } - }) - .map(tokenNftInfo -> tokenNftInfo.metadata) - .toList(); + .map(serial -> new NftId(tokenId, serial)) + .flatMap(nftId -> { + try { + return new TokenNftInfoQuery().setNftId(nftId).execute(client).stream(); + } catch (Exception e) { + throw new RuntimeException(e); + } + }) + .map(tokenNftInfo -> tokenNftInfo.metadata) + .toList(); } } diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ValidateChecksumExample.java b/examples/src/main/java/org/hiero/sdk/examples/ValidateChecksumExample.java similarity index 81% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ValidateChecksumExample.java rename to examples/src/main/java/org/hiero/sdk/examples/ValidateChecksumExample.java index 6d5073851..730f63964 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ValidateChecksumExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ValidateChecksumExample.java @@ -1,32 +1,13 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.nio.charset.Charset; import java.util.Objects; import java.util.Scanner; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * How to validate account ID checksum. @@ -93,12 +74,14 @@ class ValidateChecksumExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -111,7 +94,7 @@ class ValidateChecksumExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -145,7 +128,8 @@ public static void main(String[] args) throws Exception { AccountId accountId = AccountId.fromString(inputString); System.out.println("The account ID with no checksum is: " + accountId.toString()); - System.out.println("The account ID with the correct checksum is: " + accountId.toStringWithChecksum(client)); + System.out.println( + "The account ID with the correct checksum is: " + accountId.toStringWithChecksum(client)); if (accountId.getChecksum() == null) { System.out.println("You must enter a checksum."); @@ -156,9 +140,8 @@ public static void main(String[] args) throws Exception { // Throws BadEntityIdException if checksum is incorrect. accountId.validateChecksum(client); - AccountBalance accountBalance = new AccountBalanceQuery() - .setAccountId(accountId) - .execute(client); + AccountBalance accountBalance = + new AccountBalanceQuery().setAccountId(accountId).execute(client); System.out.println("Account Balance: " + accountBalance); @@ -168,10 +151,8 @@ public static void main(String[] args) throws Exception { System.out.println(exc.getMessage()); } catch (BadEntityIdException exc) { System.out.println(exc.getMessage()); - System.out.println( - "You entered " + exc.shard + "." + exc.realm + "." + exc.num + "-" + exc.presentChecksum + - ", the expected checksum was " + exc.expectedChecksum - ); + System.out.println("You entered " + exc.shard + "." + exc.realm + "." + exc.num + "-" + + exc.presentChecksum + ", the expected checksum was " + exc.expectedChecksum); } } @@ -205,9 +186,8 @@ public static void main(String[] args) throws Exception { continue; } - AccountBalance accountBalance = new AccountBalanceQuery() - .setAccountId(accountId) - .execute(client); + AccountBalance accountBalance = + new AccountBalanceQuery().setAccountId(accountId).execute(client); System.out.println("Account Balance: " + accountBalance); diff --git a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ZeroTokenOperationsExample.java b/examples/src/main/java/org/hiero/sdk/examples/ZeroTokenOperationsExample.java similarity index 66% rename from examples/src/main/java/com/hedera/hashgraph/sdk/examples/ZeroTokenOperationsExample.java rename to examples/src/main/java/org/hiero/sdk/examples/ZeroTokenOperationsExample.java index 747099f8d..ce6e690e1 100644 --- a/examples/src/main/java/com/hedera/hashgraph/sdk/examples/ZeroTokenOperationsExample.java +++ b/examples/src/main/java/org/hiero/sdk/examples/ZeroTokenOperationsExample.java @@ -1,31 +1,12 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk.examples; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk.examples; -import com.hedera.hashgraph.sdk.*; -import com.hedera.hashgraph.sdk.logger.LogLevel; -import com.hedera.hashgraph.sdk.logger.Logger; import io.github.cdimascio.dotenv.Dotenv; - import java.util.Collections; import java.util.Objects; +import org.hiero.sdk.*; +import org.hiero.sdk.logger.LogLevel; +import org.hiero.sdk.logger.Logger; /** * Steps 1-5 are executed through ContractHelper and calling HIP564Example Contract. @@ -42,12 +23,14 @@ class ZeroTokenOperationsExample { * Operator's account ID. * Used to sign and pay for operations on Hedera. */ - private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); + private static final AccountId OPERATOR_ID = + AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); /** * Operator's private key. */ - private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); + private static final PrivateKey OPERATOR_KEY = + PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); /** * HEDERA_NETWORK defaults to testnet if not specified in dotenv file. @@ -60,7 +43,7 @@ class ZeroTokenOperationsExample { * Log levels can be: TRACE, DEBUG, INFO, WARN, ERROR, SILENT. *

* Important pre-requisite: set simple logger log level to same level as the SDK_LOG_LEVEL, - * for example via VM options: -Dorg.slf4j.simpleLogger.log.com.hedera.hashgraph=trace + * for example via VM options: -Dorg.slf4j.simpleLogger.log.org.hiero=trace */ private static final String SDK_LOG_LEVEL = Dotenv.load().get("SDK_LOG_LEVEL", "SILENT"); @@ -93,9 +76,9 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating Alice account..."); AccountCreateTransaction accountCreateTx = new AccountCreateTransaction() - .setKey(alicePublicKey) - .setInitialBalance(Hbar.from(1)) - .freezeWith(client); + .setKey(alicePublicKey) + .setInitialBalance(Hbar.from(1)) + .freezeWith(client); accountCreateTx = accountCreateTx.signWithOperator(client); TransactionResponse accountCreateTxResponse = accountCreateTx.execute(client); @@ -109,23 +92,20 @@ public static void main(String[] args) throws Exception { */ System.out.println("Instantiating `ContractHelper`..."); ContractHelper contractHelper = new ContractHelper( - "contracts/precompile/ZeroTokenOperations.json", - new ContractFunctionParameters() - .addAddress(OPERATOR_ID.toSolidityAddress()) - .addAddress(aliceAccountId.toSolidityAddress()), - client - ); + "contracts/precompile/ZeroTokenOperations.json", + new ContractFunctionParameters() + .addAddress(OPERATOR_ID.toSolidityAddress()) + .addAddress(aliceAccountId.toSolidityAddress()), + client); /* * Step 4: * Configure steps in ContractHelper. */ System.out.println("Configuring steps in `ContractHelper`..."); - contractHelper - .setPayableAmountForStep(0, Hbar.from(20)) - .addSignerForStep(1, alicePrivateKey); + contractHelper.setPayableAmountForStep(0, Hbar.from(20)).addSignerForStep(1, alicePrivateKey); - /* + /* * Step 5: * Execute steps in ContractHelper. * - step 0 creates a fungible token; @@ -134,28 +114,27 @@ public static void main(String[] args) throws Exception { * - step 3 mint the token by passing a zero value; * - step 4 burn the token by passing a zero value; * - step 5 wipe the token by passing a zero value. - */ + */ System.out.println("Executing steps in `ContractHelper`."); // Update the signer to have contractId KeyList (this is by security requirement) new AccountUpdateTransaction() - .setAccountId(OPERATOR_ID) - .setKey(KeyList.of(OPERATOR_KEY.getPublicKey(), contractHelper.contractId).setThreshold(1)) - .execute(client) - .getReceipt(client); + .setAccountId(OPERATOR_ID) + .setKey(KeyList.of(OPERATOR_KEY.getPublicKey(), contractHelper.contractId) + .setThreshold(1)) + .execute(client) + .getReceipt(client); // Update the Alice account to have contractId KeyList (this is by security requirement) new AccountUpdateTransaction() - .setAccountId(aliceAccountId) - .setKey(KeyList.of(alicePublicKey, contractHelper.contractId).setThreshold(1)) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(aliceAccountId) + .setKey(KeyList.of(alicePublicKey, contractHelper.contractId).setThreshold(1)) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); // Configure steps in ContractHelper - contractHelper - .setPayableAmountForStep(0, Hbar.from(40)) - .addSignerForStep(1, alicePrivateKey); + contractHelper.setPayableAmountForStep(0, Hbar.from(40)).addSignerForStep(1, alicePrivateKey); // step 0 creates a fungible token // step 1 Associate with account @@ -171,14 +150,14 @@ public static void main(String[] args) throws Exception { */ System.out.println("Creating a Fungible Token..."); TokenCreateTransaction tokenCreateTx = new TokenCreateTransaction() - .setTokenName("Zero Token Ops Fungible Token") - .setTokenSymbol("ZTOFT") - .setTreasuryAccountId(OPERATOR_ID) - // Total supply = 10000 / 10 ^ 2. - .setInitialSupply(10_000) - .setDecimals(2) - .setAutoRenewAccountId(OPERATOR_ID) - .freezeWith(client); + .setTokenName("Zero Token Ops Fungible Token") + .setTokenSymbol("ZTOFT") + .setTreasuryAccountId(OPERATOR_ID) + // Total supply = 10000 / 10 ^ 2. + .setInitialSupply(10_000) + .setDecimals(2) + .setAutoRenewAccountId(OPERATOR_ID) + .freezeWith(client); tokenCreateTx = tokenCreateTx.signWithOperator(client); TransactionResponse tokenCreateTxResponse = tokenCreateTx.execute(client); @@ -191,9 +170,9 @@ public static void main(String[] args) throws Exception { // Accounts on hedera have to opt in to receive any types of token that aren't Hbar. System.out.println("Associate Token with Alice's account..."); TokenAssociateTransaction tokenAssociateTx = new TokenAssociateTransaction() - .setAccountId(aliceAccountId) - .setTokenIds(Collections.singletonList(fungibleTokenId)) - .freezeWith(client); + .setAccountId(aliceAccountId) + .setTokenIds(Collections.singletonList(fungibleTokenId)) + .freezeWith(client); TokenAssociateTransaction tokenAssociateTxSigned = tokenAssociateTx.sign(alicePrivateKey); TransactionResponse tokenAssociateTxResponse = tokenAssociateTxSigned.execute(client); @@ -203,11 +182,11 @@ public static void main(String[] args) throws Exception { // Transfer token. System.out.println("Transferring zero tokens from operator's account to Alice's account..."); TransferTransaction transferTx = new TransferTransaction() - // Deduct 0 tokens. - .addTokenTransfer(fungibleTokenId, OPERATOR_ID, 0) - // Increase balance by 0. - .addTokenTransfer(fungibleTokenId, aliceAccountId, 0) - .freezeWith(client); + // Deduct 0 tokens. + .addTokenTransfer(fungibleTokenId, OPERATOR_ID, 0) + // Increase balance by 0. + .addTokenTransfer(fungibleTokenId, aliceAccountId, 0) + .freezeWith(client); TransferTransaction transferTxSigned = transferTx.signWithOperator(client); TransactionResponse transferTxResponse = transferTxSigned.execute(client); @@ -216,7 +195,7 @@ public static void main(String[] args) throws Exception { TransactionRecord transferTxRecord = transferTxResponse.getRecord(client); System.out.println( - "step 6 completed, and returned valid result. TransactionId: " + transferTxRecord.transactionId); + "step 6 completed, and returned valid result. TransactionId: " + transferTxRecord.transactionId); System.out.println("All steps completed with valid results."); @@ -225,12 +204,12 @@ public static void main(String[] args) throws Exception { * Delete created account and contract. */ new AccountDeleteTransaction() - .setAccountId(aliceAccountId) - .setTransferAccountId(OPERATOR_ID) - .freezeWith(client) - .sign(alicePrivateKey) - .execute(client) - .getReceipt(client); + .setAccountId(aliceAccountId) + .setTransferAccountId(OPERATOR_ID) + .freezeWith(client) + .sign(alicePrivateKey) + .execute(client) + .getReceipt(client); client.close(); diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/hello_world/hello_world.json b/examples/src/main/resources/org/hiero/sdk/examples/contracts/hello_world/hello_world.json similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/hello_world/hello_world.json rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/hello_world/hello_world.json diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/hello_world/hello_world.sol b/examples/src/main/resources/org/hiero/sdk/examples/contracts/hello_world/hello_world.sol similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/hello_world/hello_world.sol rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/hello_world/hello_world.sol diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/parent_deploys_child/parent_deploys_child.json b/examples/src/main/resources/org/hiero/sdk/examples/contracts/parent_deploys_child/parent_deploys_child.json similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/parent_deploys_child/parent_deploys_child.json rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/parent_deploys_child/parent_deploys_child.json diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/parent_deploys_child/parent_deploys_child.sol b/examples/src/main/resources/org/hiero/sdk/examples/contracts/parent_deploys_child/parent_deploys_child.sol similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/parent_deploys_child/parent_deploys_child.sol rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/parent_deploys_child/parent_deploys_child.sol diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/ExpiryHelper.sol b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/ExpiryHelper.sol similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/ExpiryHelper.sol rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/ExpiryHelper.sol diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/FeeHelper.sol b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/FeeHelper.sol similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/FeeHelper.sol rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/FeeHelper.sol diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/HederaResponseCodes.sol b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/HederaResponseCodes.sol similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/HederaResponseCodes.sol rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/HederaResponseCodes.sol diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/HederaTokenService.sol b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/HederaTokenService.sol similarity index 99% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/HederaTokenService.sol rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/HederaTokenService.sol index 871a3e332..8b3e5b5f0 100644 --- a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/HederaTokenService.sol +++ b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/HederaTokenService.sol @@ -4,7 +4,7 @@ pragma experimental ABIEncoderV2; // This file was copied from github.com/hashgraph/hedera-smart-contracts on Aug 7 2024 -import "../HederaResponseCodes.sol"; +import "./HederaResponseCodes.sol"; import "./IHederaTokenService.sol"; abstract contract HederaTokenService { diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/IHederaTokenService.sol b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/IHederaTokenService.sol similarity index 99% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/IHederaTokenService.sol rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/IHederaTokenService.sol index 871a3e332..8b3e5b5f0 100644 --- a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/IHederaTokenService.sol +++ b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/IHederaTokenService.sol @@ -4,7 +4,7 @@ pragma experimental ABIEncoderV2; // This file was copied from github.com/hashgraph/hedera-smart-contracts on Aug 7 2024 -import "../HederaResponseCodes.sol"; +import "./HederaResponseCodes.sol"; import "./IHederaTokenService.sol"; abstract contract HederaTokenService { diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/IPrngSystemContract.sol b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/IPrngSystemContract.sol similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/IPrngSystemContract.sol rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/IPrngSystemContract.sol diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/KeyHelper.sol b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/KeyHelper.sol similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/KeyHelper.sol rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/KeyHelper.sol diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/PrecompileExample.json b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/PrecompileExample.json similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/PrecompileExample.json rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/PrecompileExample.json diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/PrecompileExample.sol b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/PrecompileExample.sol similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/PrecompileExample.sol rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/PrecompileExample.sol diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/PrngSystemContract.sol b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/PrngSystemContract.sol similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/PrngSystemContract.sol rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/PrngSystemContract.sol diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/ZeroTokenOperations.json b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/ZeroTokenOperations.json similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/ZeroTokenOperations.json rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/ZeroTokenOperations.json diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/ZeroTokenOperations.sol b/examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/ZeroTokenOperations.sol similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/precompile/ZeroTokenOperations.sol rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/precompile/ZeroTokenOperations.sol diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/stateful/stateful.json b/examples/src/main/resources/org/hiero/sdk/examples/contracts/stateful/stateful.json similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/stateful/stateful.json rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/stateful/stateful.json diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/stateful/stateful.sol b/examples/src/main/resources/org/hiero/sdk/examples/contracts/stateful/stateful.sol similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/contracts/stateful/stateful.sol rename to examples/src/main/resources/org/hiero/sdk/examples/contracts/stateful/stateful.sol diff --git a/examples/src/main/resources/com/hedera/hashgraph/sdk/examples/util/large_message.txt b/examples/src/main/resources/org/hiero/sdk/examples/util/large_message.txt similarity index 100% rename from examples/src/main/resources/com/hedera/hashgraph/sdk/examples/util/large_message.txt rename to examples/src/main/resources/org/hiero/sdk/examples/util/large_message.txt diff --git a/hiero-dependency-versions/build.gradle.kts b/hiero-dependency-versions/build.gradle.kts index c202d9e97..91b972dfe 100644 --- a/hiero-dependency-versions/build.gradle.kts +++ b/hiero-dependency-versions/build.gradle.kts @@ -6,7 +6,7 @@ plugins { id("org.hiero.gradle.check.spotless-kotlin") } -group = "com.hedera.hashgraph" +group = "org.hiero" val bouncycastle = "1.79" val grpc = "1.69.0" diff --git a/scripts/premade/FeeDataType-0.txt b/scripts/premade/FeeDataType-0.txt index 4774bdc53..107a40059 100644 --- a/scripts/premade/FeeDataType-0.txt +++ b/scripts/premade/FeeDataType-0.txt @@ -1,25 +1,7 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk; -import com.hedera.hashgraph.sdk.proto.SubType; +import org.hiero.sdk.proto.SubType; /** * Enum for the fee data types. diff --git a/scripts/premade/FreezeType-0.txt b/scripts/premade/FreezeType-0.txt index b412fbc7f..4596c96d7 100644 --- a/scripts/premade/FreezeType-0.txt +++ b/scripts/premade/FreezeType-0.txt @@ -1,23 +1,5 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk; /** * Enum for the freeze types. diff --git a/scripts/premade/RequestType-0.txt b/scripts/premade/RequestType-0.txt index 518de2499..2f43c9134 100644 --- a/scripts/premade/RequestType-0.txt +++ b/scripts/premade/RequestType-0.txt @@ -1,23 +1,5 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk; import com.hedera.hashgraph.sdk.proto.HederaFunctionality; diff --git a/scripts/premade/Status-0.txt b/scripts/premade/Status-0.txt index 4a5933fff..85915c4fd 100644 --- a/scripts/premade/Status-0.txt +++ b/scripts/premade/Status-0.txt @@ -1,25 +1,7 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.hedera.hashgraph.sdk; +// SPDX-License-Identifier: Apache-2.0 +package org.hiero.sdk; -import com.hedera.hashgraph.sdk.proto.ResponseCodeEnum; +import org.hiero.sdk.proto.ResponseCodeEnum; import java.util.Objects; diff --git a/scripts/update_protobufs.py b/scripts/update_protobufs.py index 38e805d33..3277c5555 100755 --- a/scripts/update_protobufs.py +++ b/scripts/update_protobufs.py @@ -13,7 +13,7 @@ if len(sys.argv) == 1: print(">>> Usage: `" + sys.argv[0] + " ref`") - print(">>> Where \"ref\" is a valid branch or tag in the Hedera Protobufs git repo") + print(">>> Where \"ref\" is a valid branch or tag in the Services git repo") print("\n\n") @@ -31,7 +31,7 @@ def go_to_script_dir(): PROTO_GIT_REMOTE = "https://github.com/hashgraph/hedera-services.git" -PROTO_GIT_PATH = os.path.join("hedera-protos-git") +PROTO_GIT_PATH = os.path.join("hiero-protos-git") PROTO_GIT_REF = sys.argv[1] if len(sys.argv)>1 else "" @@ -46,7 +46,7 @@ def go_to_script_dir(): MAIN_PATH = os.path.join("..", "sdk", "src", "main") PROTO_OUT_PATH = os.path.join(MAIN_PATH, "proto") PROTO_MIRROR_OUT_PATH = os.path.join(PROTO_OUT_PATH, "mirror") -JAVA_OUT_PATH = os.path.join(MAIN_PATH, "java", "com", "hedera", "hashgraph", "sdk") +JAVA_OUT_PATH = os.path.join(MAIN_PATH, "java", "org", "hiero", "sdk") REQUEST_TYPE_OUT_PATH = os.path.join(JAVA_OUT_PATH, "RequestType.java") STATUS_OUT_PATH = os.path.join(JAVA_OUT_PATH, "Status.java") FEE_DATA_TYPE_OUT_PATH = os.path.join(JAVA_OUT_PATH, "FeeDataType.java") @@ -100,7 +100,7 @@ def do_replacements_proto_imports(s, replacements): for r in replacements: # Check if the replacement should be skipped # Skip statements like `import "google/protobuf/wrappers.proto"` - # to update imports ONLY referred to hedera protobufs + # to update imports ONLY referred to hiero protobufs if 'google' in s: continue s = re.sub(r[0], r[1], s) diff --git a/sdk-full/build.gradle.kts b/sdk-full/build.gradle.kts index ebbc450d4..dcb86f9b1 100644 --- a/sdk-full/build.gradle.kts +++ b/sdk-full/build.gradle.kts @@ -4,7 +4,7 @@ plugins { id("org.hiero.gradle.feature.protobuf") } -description = "Hedera™ Hashgraph SDK for Java" +description = "Hiero SDK for Java" // TODO following block to be extracted into a plugin // https://github.com/hiero-ledger/hiero-gradle-conventions/issues/41 diff --git a/sdk-full/src/main/java/module-info.java b/sdk-full/src/main/java/module-info.java index 252a0434a..f61960686 100644 --- a/sdk-full/src/main/java/module-info.java +++ b/sdk-full/src/main/java/module-info.java @@ -1,22 +1,4 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ +// SPDX-License-Identifier: Apache-2.0 module org.hiero.sdk.full { requires transitive com.google.protobuf; diff --git a/sdk/src/main/java/org/hiero/sdk/package-info.java b/sdk/src/main/java/org/hiero/sdk/package-info.java index b7076599c..3a598a349 100644 --- a/sdk/src/main/java/org/hiero/sdk/package-info.java +++ b/sdk/src/main/java/org/hiero/sdk/package-info.java @@ -1,23 +1,5 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * See Hedera Documentation - */ +// SPDX-License-Identifier: Apache-2.0 + @ParametersAreNonnullByDefault package org.hiero.sdk; diff --git a/sdk/src/testIntegration/java/module-info.java b/sdk/src/testIntegration/java/module-info.java index e4fb4fd78..b9ee884ef 100644 --- a/sdk/src/testIntegration/java/module-info.java +++ b/sdk/src/testIntegration/java/module-info.java @@ -1,22 +1,4 @@ -/*- - * - * Hedera Java SDK - * - * Copyright (C) 2024 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ +// SPDX-License-Identifier: Apache-2.0 open module org.hiero.sdk.test.integration { requires org.hiero.sdk; diff --git a/settings.gradle.kts b/settings.gradle.kts index 4435b73aa..6a72d0140 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -4,8 +4,8 @@ plugins { id("org.hiero.gradle.build") version "0.1.1" } rootProject.name = "hiero-sdk-java" javaModules { - module("sdk") { group = "org.hiero" } - module("sdk-full") { group = "org.hiero" } + module("sdk") { group = "org.hiero.sdk" } + module("sdk-full") { group = "org.hiero.sdk" } module("tck") { group = "org.hiero.sdk.tck" } } diff --git a/tck/README.md b/tck/README.md index d4c804af9..9b6095ed4 100644 --- a/tck/README.md +++ b/tck/README.md @@ -1,24 +1,32 @@ # Java SDK TCK Server ## Description -This module contains implementation of the JSON-RPC server for the Java SDK to interpret and process requests from the Test Driver based on the [TCK's](https://github.com/hashgraph/hedera-sdk-tck/) requirements. Upon receiving a request, it executes the corresponding function or procedure associated with the method specified in the request. Subsequently, it prepares the response in JSON format and sends it back to the test driver. + +This module contains implementation of the JSON-RPC server for the Java SDK to interpret and process requests from the Test Driver based on the [TCK's](https://github.com/hiero-ledger/hiero-sdk-tck) requirements. Upon receiving a request, it executes the corresponding function or procedure associated with the method specified in the request. Subsequently, it prepares the response in JSON format and sends it back to the test driver. ## Setup + **1. Navigate into tck directory.** + ```shell cd tck ``` + **2. Build the project using Gradle.** + ```shell ./gradlew build ``` + **3. Run the server.** + ```shell ./gradlew bootRun ``` By default, the server will occupy port 80. If you need to specify a different port, modify the port in the `application.yml` file: -``` yaml + +```yaml server: port: ```