Search in sources :

Example 26 with Client

use of com.hedera.hashgraph.sdk.Client in project hedera-sdk-java by hashgraph.

the class ValidateChecksumExample method main.

public static void main(String[] args) throws TimeoutException, PrecheckStatusException {
    Client client = Client.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);
    /*
         * Entity IDs, such as TokenId and AccountId, can be constructed from strings.
         * For example, the AccountId.fromString(inputString) static method will attempt to parse
         * the input string and construct the expected AccountId object, and will throw an
         * IllegalArgumentException if the string is incorrectly formatted.
         *
         * From here on, we'll talk about methods on accountId, but equivalent methods exist
         * on every entity ID type.
         *
         * fromString() expects the input to look something like this: "1.2.3-asdfg".
         * Here, 1 is the shard, 2 is the realm, 3 is the number, and "asdfg" is the checksum.
         *
         * The checksum can be used to ensure that an entity ID was inputted correctly.
         * For example, if the string being parsed is from a config file, or from user input,
         * it could contain typos.
         *
         * You can use accountId.getChecksum() to get the checksum of an accountId object that was constructed
         * using fromString().  This will be the checksum from the input string.  fromString() will merely
         * parse the string and create an AccountId object with the expected shard, realm, num, and checksum
         * values.  fromString() will NOT verify that the AccountId maps to a valid account on the Hedera
         * network, and it will not verify the checksum.
         *
         * To verify a checksum, call accountId.validateChecksum(client).  If the checksum
         * is invalid, validateChecksum() will throw a BadEntityIdException, otherwise it will return normally.
         *
         * The validity of a checksum depends on which network the client is connected to (EG mainnet or
         * testnet or previewnet).  For example, a checksum that is valid for a particular shard/realm/num
         * on mainnet will be INVALID for the same shard/realm/num on testnet.
         *
         * As far as fromString() is concerned, the checksum is optional.
         * If you use fromString() to generate an AccountId from a string that does not include a checksum,
         * such as "1.2.3", fromString() will work, but a call to the getChecksum() method on the resulting
         * AccountId object will return null.
         *
         * Generally speaking, AccountId objects can come from three places:
         * 1) AccountId.fromString(inString)
         * 2) new AccountId(shard, realm, num)
         * 3) From the result of a query
         *
         * In the first case, the AccountId object will have a checksum (getChecksum() will not return null) if
         * the input string included a checksum, and it will not have a checksum if the string did not
         * include a checksum.
         *
         * In the second and third cases, the AccountId object will not have a checksum.
         *
         * If you call accountId.validateChecksum(client) and accountId has no checksum to validate,
         * validateChecksum() will silently pass, and will not throw an exception.
         *
         * accountId.toString() will stringify the account ID with no checksum,
         * accountId.toStringWithChecksum(client) will stringify the account ID with the correct checksum
         * for that shard/realm/num on the client's network.
         */
    System.out.println("An example of manual checksum validation:");
    while (true) {
        try {
            System.out.print("Enter an account ID with checksum: ");
            String inString = INPUT_SCANNER.nextLine();
            // Throws IllegalArgumentException if incorrectly formatted
            AccountId id = AccountId.fromString(inString);
            System.out.println("The ID with no checksum is " + id.toString());
            System.out.println("The ID with the correct checksum is " + id.toStringWithChecksum(client));
            if (id.getChecksum() == null) {
                System.out.println("You must enter a checksum.");
                continue;
            }
            System.out.println("The checksum entered was " + id.getChecksum());
            // Throws BadEntityIdException if checksum is incorrect
            id.validateChecksum(client);
            AccountBalance balance = new AccountBalanceQuery().setAccountId(id).execute(client);
            System.out.println(balance);
            // exit the loop
            break;
        } catch (IllegalArgumentException exc) {
            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);
        }
    }
    /*
         * It is also possible to perform automatic checksum validation.
         *
         * Automatic checksum validation is disabled by default, but it can be enabled with
         * client.setAutoValidateChecksums(true).  You can check whether automatic checksum
         * validation is enabled with client.isAutoValidateChecksumsEnabled().
         *
         * When this feature is enabled, the execute() method of a transaction or query
         * will automatically check the validity of checksums on any IDs in the
         * transaction or query.  It will throw an IllegalArgumentException if an
         * invalid checksum is encountered.
         */
    System.out.println("An example of automatic checksum validation:");
    client.setAutoValidateChecksums(true);
    while (true) {
        try {
            System.out.print("Enter an account ID with checksum: ");
            AccountId id = AccountId.fromString(INPUT_SCANNER.nextLine());
            if (id.getChecksum() == null) {
                System.out.println("You must enter a checksum.");
                continue;
            }
            AccountBalance balance = new AccountBalanceQuery().setAccountId(id).execute(client);
            System.out.println(balance);
            // exit the loop
            break;
        } catch (IllegalArgumentException exc) {
            System.out.println(exc.getMessage());
        }
    }
    System.out.println("Example complete!");
    client.close();
}
Also used : BadEntityIdException(com.hedera.hashgraph.sdk.BadEntityIdException) AccountId(com.hedera.hashgraph.sdk.AccountId) AccountBalance(com.hedera.hashgraph.sdk.AccountBalance) AccountBalanceQuery(com.hedera.hashgraph.sdk.AccountBalanceQuery) Client(com.hedera.hashgraph.sdk.Client)

Example 27 with Client

use of com.hedera.hashgraph.sdk.Client in project hedera-sdk-java by hashgraph.

the class ConstructClientExample method main.

public static void main(String[] args) throws Exception {
    /*
         * Here are some ways you can construct and configure a client.
         * A client has a network and an operator.
         *
         * A Hedera network is made up of nodes -- individual servers who participate
         * in the process of reaching consensus on the order and validity of transactions
         * on the network.  Three networks you likely know of are previewnet, testnet, and mainnet.
         *
         * For the purpose of connecting to it, each node has an IP address or URL and a port number.
         * Each node also has an AccountId used to refer to that node for several purposes,
         * including the paying of fees to that node when a client submits requests to it.
         *
         * You can configure what network you want a client to use -- in other words, you can specify
         * a list of URLS and port numbers with associated AccountIds, and
         * when that client is used to execute queries and transactions, the client will
         * submit requests only to nodes in that list.
         *
         * A Client has an operator, which has an AccountId and a PublicKey, and which can
         * sign requests.  A client's operator can also be configured.
         */
    // Here's the simplest way to construct a client:
    Client previewClient = Client.forPreviewnet();
    Client testClient = Client.forTestnet();
    Client mainClient = Client.forMainnet();
    // These clients' networks are filled with default lists of nodes that are baked into the SDK.
    // Their operators are not yet set, and trying to use them now will result in exceptions.
    // We can also construct a client for previewnet, testnet, or mainnet depending on the value of a
    // network name string.  If, for example, the input string equals "testnet", this client will be
    // configured to connect to testnet.
    Client namedNetworkClient = Client.forName(HEDERA_NETWORK);
    // Let's set the operator on testClient.
    // (The AccountId and PrivateKey here are fake, this is just an example.)
    testClient.setOperator(AccountId.fromString("0.0.3"), PrivateKey.fromString("302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e10"));
    // Let's create a client with a custom network.
    Map<String, AccountId> customNetwork = new HashMap<String, AccountId>();
    customNetwork.put("2.testnet.hedera.com:50211", new AccountId(5));
    customNetwork.put("3.testnet.hedera.com:50211", new AccountId(6));
    Client customClient = Client.forNetwork(customNetwork);
    // since our customClient's network is in this case a subset of testnet, we should set the
    // network's name to testnet. If we don't do this, checksum validation won't work.
    // See ValidateChecksumExample.java.  You can use customClient.getNetworkName()
    // to check the network name.  If not set, it will return null.
    // If you attempt to validate a checksum against a client whose networkName is not set,
    // an IllegalStateException will be thrown.
    customClient.setNetworkName(NetworkName.TESTNET);
    // using fromConfigFile() immediately.
    if (CONFIG_FILE != null) {
        Client configClient = Client.fromConfigFile(CONFIG_FILE);
        configClient.close();
    }
    // Always close a client when you're done with it
    previewClient.close();
    testClient.close();
    mainClient.close();
    namedNetworkClient.close();
    customClient.close();
    System.out.println("Success!");
}
Also used : AccountId(com.hedera.hashgraph.sdk.AccountId) HashMap(java.util.HashMap) Client(com.hedera.hashgraph.sdk.Client)

Example 28 with Client

use of com.hedera.hashgraph.sdk.Client in project hedera-sdk-java by hashgraph.

the class CreateAccountExample method main.

public static void main(String[] args) throws TimeoutException, PrecheckStatusException, ReceiptStatusException {
    Client client = Client.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);
    // Generate a Ed25519 private, public key pair
    PrivateKey newKey = PrivateKey.generateED25519();
    PublicKey newPublicKey = newKey.getPublicKey();
    System.out.println("private key = " + newKey);
    System.out.println("public key = " + newPublicKey);
    TransactionResponse transactionResponse = new AccountCreateTransaction().setKey(newPublicKey).setInitialBalance(Hbar.fromTinybars(1000)).execute(client);
    // This will wait for the receipt to become available
    TransactionReceipt receipt = transactionResponse.getReceipt(client);
    AccountId newAccountId = receipt.accountId;
    System.out.println("account = " + newAccountId);
}
Also used : PrivateKey(com.hedera.hashgraph.sdk.PrivateKey) TransactionResponse(com.hedera.hashgraph.sdk.TransactionResponse) AccountId(com.hedera.hashgraph.sdk.AccountId) PublicKey(com.hedera.hashgraph.sdk.PublicKey) TransactionReceipt(com.hedera.hashgraph.sdk.TransactionReceipt) Client(com.hedera.hashgraph.sdk.Client) AccountCreateTransaction(com.hedera.hashgraph.sdk.AccountCreateTransaction)

Example 29 with Client

use of com.hedera.hashgraph.sdk.Client in project hedera-sdk-java by hashgraph.

the class CreateAccountThresholdKeyExample method main.

public static void main(String[] args) throws PrecheckStatusException, TimeoutException, ReceiptStatusException {
    Client client = Client.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);
    // Generate three new Ed25519 private, public key pairs.
    // You do not need the private keys to create the Threshold Key List,
    // you only need the public keys, and if you're doing things correctly,
    // you probably shouldn't have these private keys.
    PrivateKey[] privateKeys = new PrivateKey[3];
    PublicKey[] publicKeys = new PublicKey[3];
    for (int i = 0; i < 3; i++) {
        PrivateKey key = PrivateKey.generateED25519();
        privateKeys[i] = key;
        publicKeys[i] = key.getPublicKey();
    }
    System.out.println("public keys: ");
    for (Key key : publicKeys) {
        System.out.println(key);
    }
    // require 2 of the 3 keys we generated to sign on anything modifying this account
    KeyList transactionKey = KeyList.withThreshold(2);
    Collections.addAll(transactionKey, publicKeys);
    TransactionResponse transactionResponse = new AccountCreateTransaction().setKey(transactionKey).setInitialBalance(new Hbar(10)).execute(client);
    // This will wait for the receipt to become available
    TransactionReceipt receipt = transactionResponse.getReceipt(client);
    AccountId newAccountId = Objects.requireNonNull(receipt.accountId);
    System.out.println("account = " + newAccountId);
    TransactionResponse transferTransactionResponse = new TransferTransaction().addHbarTransfer(newAccountId, new Hbar(10).negated()).addHbarTransfer(new AccountId(3), new Hbar(10)).freezeWith(client).sign(privateKeys[0]).sign(privateKeys[1]).execute(client);
    // (important!) wait for the transfer to go to consensus
    transferTransactionResponse.getReceipt(client);
    Hbar balanceAfter = new AccountBalanceQuery().setAccountId(newAccountId).execute(client).hbars;
    System.out.println("account balance after transfer: " + balanceAfter);
}
Also used : PrivateKey(com.hedera.hashgraph.sdk.PrivateKey) AccountId(com.hedera.hashgraph.sdk.AccountId) PublicKey(com.hedera.hashgraph.sdk.PublicKey) KeyList(com.hedera.hashgraph.sdk.KeyList) AccountBalanceQuery(com.hedera.hashgraph.sdk.AccountBalanceQuery) TransactionReceipt(com.hedera.hashgraph.sdk.TransactionReceipt) Hbar(com.hedera.hashgraph.sdk.Hbar) TransactionResponse(com.hedera.hashgraph.sdk.TransactionResponse) Client(com.hedera.hashgraph.sdk.Client) TransferTransaction(com.hedera.hashgraph.sdk.TransferTransaction) AccountCreateTransaction(com.hedera.hashgraph.sdk.AccountCreateTransaction) Key(com.hedera.hashgraph.sdk.Key) PublicKey(com.hedera.hashgraph.sdk.PublicKey) PrivateKey(com.hedera.hashgraph.sdk.PrivateKey)

Example 30 with Client

use of com.hedera.hashgraph.sdk.Client in project hedera-sdk-java by hashgraph.

the class CreateFileExample method main.

public static void main(String[] args) throws TimeoutException, PrecheckStatusException, ReceiptStatusException {
    Client client = Client.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);
    // The file is required to be a byte array,
    // you can easily use the bytes of a file instead.
    String fileContents = "Hedera hashgraph is great!";
    TransactionResponse transactionResponse = new FileCreateTransaction().setKeys(OPERATOR_KEY.getPublicKey()).setContents(fileContents).setMaxTransactionFee(// 2 HBAR
    new Hbar(2)).execute(client);
    TransactionReceipt receipt = transactionResponse.getReceipt(client);
    FileId newFileId = receipt.fileId;
    System.out.println("file: " + newFileId);
}
Also used : FileCreateTransaction(com.hedera.hashgraph.sdk.FileCreateTransaction) TransactionResponse(com.hedera.hashgraph.sdk.TransactionResponse) TransactionReceipt(com.hedera.hashgraph.sdk.TransactionReceipt) Hbar(com.hedera.hashgraph.sdk.Hbar) FileId(com.hedera.hashgraph.sdk.FileId) Client(com.hedera.hashgraph.sdk.Client)

Aggregations

Client (com.hedera.hashgraph.sdk.Client)41 Hbar (com.hedera.hashgraph.sdk.Hbar)23 AccountId (com.hedera.hashgraph.sdk.AccountId)20 TransactionResponse (com.hedera.hashgraph.sdk.TransactionResponse)20 PrivateKey (com.hedera.hashgraph.sdk.PrivateKey)16 TransactionReceipt (com.hedera.hashgraph.sdk.TransactionReceipt)16 TransferTransaction (com.hedera.hashgraph.sdk.TransferTransaction)13 AccountCreateTransaction (com.hedera.hashgraph.sdk.AccountCreateTransaction)12 AccountBalanceQuery (com.hedera.hashgraph.sdk.AccountBalanceQuery)9 Var (com.google.errorprone.annotations.Var)6 FileCreateTransaction (com.hedera.hashgraph.sdk.FileCreateTransaction)6 FileId (com.hedera.hashgraph.sdk.FileId)6 KeyList (com.hedera.hashgraph.sdk.KeyList)6 PublicKey (com.hedera.hashgraph.sdk.PublicKey)6 TimeoutException (java.util.concurrent.TimeoutException)6 AccountDeleteTransaction (com.hedera.hashgraph.sdk.AccountDeleteTransaction)5 ByteString (com.google.protobuf.ByteString)4 AccountBalance (com.hedera.hashgraph.sdk.AccountBalance)4 ScheduleId (com.hedera.hashgraph.sdk.ScheduleId)4 ScheduleInfoQuery (com.hedera.hashgraph.sdk.ScheduleInfoQuery)4