Search in sources :

Example 6 with Client

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

the class CustomFeesExample 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);
    // Create three accounts, Alice, Bob, and Charlie.  Alice will be the treasury for our example token.
    // Fees only apply in transactions not involving the treasury, so we need two other accounts.
    PrivateKey aliceKey = PrivateKey.generateED25519();
    AccountId aliceId = new AccountCreateTransaction().setInitialBalance(new Hbar(10)).setKey(aliceKey).freezeWith(client).sign(aliceKey).execute(client).getReceipt(client).accountId;
    PrivateKey bobKey = PrivateKey.generateED25519();
    AccountId bobId = new AccountCreateTransaction().setInitialBalance(new Hbar(10)).setKey(bobKey).freezeWith(client).sign(bobKey).execute(client).getReceipt(client).accountId;
    PrivateKey charlieKey = PrivateKey.generateED25519();
    AccountId charlieId = new AccountCreateTransaction().setInitialBalance(new Hbar(10)).setKey(charlieKey).freezeWith(client).sign(charlieKey).execute(client).getReceipt(client).accountId;
    System.out.println("Alice: " + aliceId);
    System.out.println("Bob: " + bobId);
    System.out.println("Charlie: " + charlieId);
    // Let's start with a custom fee list of 1 fixed fee.  A custom fee list can be a list of up to
    // 10 custom fees, where each fee is a fixed fee or a fractional fee.
    // This fixed fee will mean that every time Bob transfers any number of tokens to Charlie,
    // Alice will collect 1 Hbar from each account involved in the transaction who is SENDING
    // the Token (in this case, Bob).
    CustomFixedFee customHbarFee = new CustomFixedFee().setHbarAmount(new Hbar(1)).setFeeCollectorAccountId(aliceId);
    List<CustomFee> hbarFeeList = Collections.singletonList(customHbarFee);
    // In this example the fee is in Hbar, but you can charge a fixed fee in a token if you'd like.
    // EG, you can make it so that each time an account transfers Foo tokens,
    // they must pay a fee in Bar tokens to the fee collecting account.
    // To charge a fixed fee in tokens, instead of calling setHbarAmount(), call
    // setDenominatingTokenId(tokenForFee) and setAmount(tokenFeeAmount).
    // Setting the feeScheduleKey to Alice's key will enable Alice to change the custom
    // fees list on this token later using the TokenFeeScheduleUpdateTransaction.
    // We will create an initial supply of 100 of these tokens.
    TokenId tokenId = new TokenCreateTransaction().setTokenName("Example Token").setTokenSymbol("EX").setAdminKey(aliceKey).setSupplyKey(aliceKey).setFeeScheduleKey(aliceKey).setTreasuryAccountId(aliceId).setCustomFees(hbarFeeList).setInitialSupply(100).freezeWith(client).sign(aliceKey).execute(client).getReceipt(client).tokenId;
    System.out.println("Token: " + tokenId);
    TokenInfo tokenInfo1 = new TokenInfoQuery().setTokenId(tokenId).execute(client);
    System.out.println("Custom Fees according to TokenInfoQuery:");
    System.out.println(tokenInfo1.customFees);
    // We must associate the token with Bob and Charlie before they can trade in it.
    new TokenAssociateTransaction().setAccountId(bobId).setTokenIds(Collections.singletonList(tokenId)).freezeWith(client).sign(bobKey).execute(client).getReceipt(client);
    new TokenAssociateTransaction().setAccountId(charlieId).setTokenIds(Collections.singletonList(tokenId)).freezeWith(client).sign(charlieKey).execute(client).getReceipt(client);
    // give all 100 tokens to Bob
    new TransferTransaction().addTokenTransfer(tokenId, bobId, 100).addTokenTransfer(tokenId, aliceId, -100).freezeWith(client).sign(aliceKey).execute(client).getReceipt(client);
    Hbar aliceHbar1 = new AccountBalanceQuery().setAccountId(aliceId).execute(client).hbars;
    System.out.println("Alice's Hbar balance before Bob transfers 20 tokens to Charlie: " + aliceHbar1);
    TransactionRecord record1 = new TransferTransaction().addTokenTransfer(tokenId, bobId, -20).addTokenTransfer(tokenId, charlieId, 20).freezeWith(client).sign(bobKey).execute(client).getRecord(client);
    Hbar aliceHbar2 = new AccountBalanceQuery().setAccountId(aliceId).execute(client).hbars;
    System.out.println("Alices's Hbar balance after Bob transfers 20 tokens to Charlie: " + aliceHbar2);
    System.out.println("Assessed fees according to transaction record:");
    System.out.println(record1.assessedCustomFees);
    // Let's use the TokenUpdateFeeScheduleTransaction with Alice's key to change the custom fees on our token.
    // TokenUpdateFeeScheduleTransaction will replace the list of fees that apply to the token with
    // an entirely new list.  Let's charge a 10% fractional fee.  This means that when Bob attempts to transfer
    // 20 tokens to Charlie, 10% of the tokens he attempts to transfer (2 in this case) will be transferred to
    // Alice instead.
    // Fractional fees default to FeeAssessmentMethod.INCLUSIVE, which is the behavior described above.
    // If you set the assessment method to EXCLUSIVE, then when Bob attempts to transfer 20 tokens to Charlie,
    // Charlie will receive all 20 tokens, and Bob will be charged an _additional_ 10% fee which
    // will be transferred to Alice.
    CustomFractionalFee customFractionalFee = new CustomFractionalFee().setNumerator(1).setDenominator(10).setMin(1).setMax(10).setFeeCollectorAccountId(aliceId);
    List<CustomFee> fractionalFeeList = Collections.singletonList(customFractionalFee);
    new TokenFeeScheduleUpdateTransaction().setTokenId(tokenId).setCustomFees(fractionalFeeList).freezeWith(client).sign(aliceKey).execute(client).getReceipt(client);
    TokenInfo tokenInfo2 = new TokenInfoQuery().setTokenId(tokenId).execute(client);
    System.out.println("Custom Fees according to TokenInfoQuery:");
    System.out.println(tokenInfo2.customFees);
    Map<TokenId, Long> aliceTokens3 = new AccountBalanceQuery().setAccountId(aliceId).execute(client).tokens;
    System.out.println("Alice's token balance before Bob transfers 20 tokens to Charlie: " + aliceTokens3);
    TransactionRecord record2 = new TransferTransaction().addTokenTransfer(tokenId, bobId, -20).addTokenTransfer(tokenId, charlieId, 20).freezeWith(client).sign(bobKey).execute(client).getRecord(client);
    Map<TokenId, Long> aliceTokens4 = new AccountBalanceQuery().setAccountId(aliceId).execute(client).tokens;
    System.out.println("Alices's token balance after Bob transfers 20 tokens to Charlie: " + aliceTokens4);
    System.out.println("Token transfers according to transaction record:");
    System.out.println(record2.tokenTransfers);
    System.out.println("Assessed fees according to transaction record:");
    System.out.println(record2.assessedCustomFees);
    // clean up
    new TokenDeleteTransaction().setTokenId(tokenId).freezeWith(client).sign(aliceKey).execute(client).getReceipt(client);
    new AccountDeleteTransaction().setAccountId(charlieId).setTransferAccountId(client.getOperatorAccountId()).freezeWith(client).sign(charlieKey).execute(client).getReceipt(client);
    new AccountDeleteTransaction().setAccountId(bobId).setTransferAccountId(client.getOperatorAccountId()).freezeWith(client).sign(bobKey).execute(client).getReceipt(client);
    new AccountDeleteTransaction().setAccountId(aliceId).setTransferAccountId(client.getOperatorAccountId()).freezeWith(client).sign(aliceKey).execute(client).getReceipt(client);
    client.close();
}
Also used : CustomFractionalFee(com.hedera.hashgraph.sdk.CustomFractionalFee) PrivateKey(com.hedera.hashgraph.sdk.PrivateKey) AccountId(com.hedera.hashgraph.sdk.AccountId) TokenAssociateTransaction(com.hedera.hashgraph.sdk.TokenAssociateTransaction) TokenDeleteTransaction(com.hedera.hashgraph.sdk.TokenDeleteTransaction) AccountBalanceQuery(com.hedera.hashgraph.sdk.AccountBalanceQuery) AccountDeleteTransaction(com.hedera.hashgraph.sdk.AccountDeleteTransaction) Hbar(com.hedera.hashgraph.sdk.Hbar) TokenCreateTransaction(com.hedera.hashgraph.sdk.TokenCreateTransaction) TokenFeeScheduleUpdateTransaction(com.hedera.hashgraph.sdk.TokenFeeScheduleUpdateTransaction) TokenInfoQuery(com.hedera.hashgraph.sdk.TokenInfoQuery) CustomFee(com.hedera.hashgraph.sdk.CustomFee) CustomFixedFee(com.hedera.hashgraph.sdk.CustomFixedFee) TokenInfo(com.hedera.hashgraph.sdk.TokenInfo) Client(com.hedera.hashgraph.sdk.Client) TokenId(com.hedera.hashgraph.sdk.TokenId) TransferTransaction(com.hedera.hashgraph.sdk.TransferTransaction) AccountCreateTransaction(com.hedera.hashgraph.sdk.AccountCreateTransaction) TransactionRecord(com.hedera.hashgraph.sdk.TransactionRecord)

Example 7 with Client

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

the class DeleteAccountExample 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(newKey).setInitialBalance(new Hbar(2)).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);
    new AccountDeleteTransaction().setTransactionId(TransactionId.generate(newAccountId)).setAccountId(newAccountId).setTransferAccountId(OPERATOR_ID).freezeWith(client).sign(newKey).execute(client).getReceipt(client);
}
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) AccountDeleteTransaction(com.hedera.hashgraph.sdk.AccountDeleteTransaction) TransactionReceipt(com.hedera.hashgraph.sdk.TransactionReceipt) Hbar(com.hedera.hashgraph.sdk.Hbar) Client(com.hedera.hashgraph.sdk.Client) AccountCreateTransaction(com.hedera.hashgraph.sdk.AccountCreateTransaction)

Example 8 with Client

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

the class ConsensusPubSubChunkedExample method main.

public static void main(String[] args) throws TimeoutException, PrecheckStatusException, ReceiptStatusException, InterruptedException, InvalidProtocolBufferException {
    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 submit key to use with the topic
    PrivateKey submitKey = PrivateKey.generateED25519();
    // make a new topic ID to use
    TopicId newTopicId = new TopicCreateTransaction().setTopicMemo("hedera-sdk-java/ConsensusPubSubChunkedExample").setSubmitKey(submitKey).execute(client).getReceipt(client).topicId;
    assert newTopicId != null;
    System.out.println("for topic " + newTopicId);
    // Let's wait a bit
    System.out.println("wait 10s to propagate to the mirror ...");
    Thread.sleep(10000);
    // setup a mirror client to print out messages as we receive them
    new TopicMessageQuery().setTopicId(newTopicId).subscribe(client, topicMessage -> {
        System.out.println("at " + topicMessage.consensusTimestamp + " ( seq = " + topicMessage.sequenceNumber + " ) received topic message of " + topicMessage.contents.length + " bytes");
    });
    // get a large file to send
    String bigContents = readResources("large_message.txt");
    System.out.println("about to prepare a transaction to send a message of " + bigContents.length() + " bytes");
    // prepare a message send transaction that requires a submit key from "somewhere else"
    @Var Transaction<?> transaction = new TopicMessageSubmitTransaction().setMaxChunks(// this is 10 by default
    15).setTopicId(newTopicId).setMessage(bigContents).signWithOperator(client);
    // serialize to bytes so we can be signed "somewhere else" by the submit key
    byte[] transactionBytes = transaction.toBytes();
    // now pretend we sent those bytes across the network
    // parse them into a transaction so we can sign as the submit key
    transaction = Transaction.fromBytes(transactionBytes);
    // view out the message size from the parsed transaction
    // this can be useful to display what we are about to sign
    long transactionMessageSize = ((TopicMessageSubmitTransaction) transaction).getMessage().size();
    System.out.println("about to send a transaction with a message of " + transactionMessageSize + " bytes");
    // sign with that submit key
    transaction.sign(submitKey);
    // now actually submit the transaction
    // get the receipt to ensure there were no errors
    transaction.execute(client).getReceipt(client);
    // noinspection InfiniteLoopStatement
    while (true) {
        System.out.println("waiting ...");
        // noinspection BusyWait
        Thread.sleep(2500);
    }
}
Also used : TopicCreateTransaction(com.hedera.hashgraph.sdk.TopicCreateTransaction) PrivateKey(com.hedera.hashgraph.sdk.PrivateKey) Var(com.google.errorprone.annotations.Var) TopicId(com.hedera.hashgraph.sdk.TopicId) Client(com.hedera.hashgraph.sdk.Client) TopicMessageQuery(com.hedera.hashgraph.sdk.TopicMessageQuery) TopicMessageSubmitTransaction(com.hedera.hashgraph.sdk.TopicMessageSubmitTransaction)

Example 9 with Client

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

the class ConsensusPubSubExample method main.

public static void main(String[] args) throws TimeoutException, InterruptedException, 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);
    TransactionResponse transactionResponse = new TopicCreateTransaction().execute(client);
    TransactionReceipt transactionReceipt = transactionResponse.getReceipt(client);
    TopicId topicId = Objects.requireNonNull(transactionReceipt.topicId);
    System.out.println("New topic created: " + topicId);
    Thread.sleep(5000);
    new TopicMessageQuery().setTopicId(topicId).subscribe(client, resp -> {
        String messageAsString = new String(resp.contents, StandardCharsets.UTF_8);
        System.out.println(resp.consensusTimestamp + " received topic message: " + messageAsString);
    });
    // noinspection InfiniteLoopStatement
    for (int i = 0; ; i++) {
        new TopicMessageSubmitTransaction().setTopicId(topicId).setMessage("hello, HCS! " + i).execute(client).getReceipt(client);
        Thread.sleep(2500);
    }
}
Also used : TopicCreateTransaction(com.hedera.hashgraph.sdk.TopicCreateTransaction) TransactionResponse(com.hedera.hashgraph.sdk.TransactionResponse) TransactionReceipt(com.hedera.hashgraph.sdk.TransactionReceipt) TopicId(com.hedera.hashgraph.sdk.TopicId) Client(com.hedera.hashgraph.sdk.Client) TopicMessageQuery(com.hedera.hashgraph.sdk.TopicMessageQuery) TopicMessageSubmitTransaction(com.hedera.hashgraph.sdk.TopicMessageSubmitTransaction)

Example 10 with Client

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

the class DeleteFileExample 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);
    // 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).setContents(fileContents).setMaxTransactionFee(new Hbar(2)).execute(client);
    TransactionReceipt receipt = transactionResponse.getReceipt(client);
    FileId newFileId = Objects.requireNonNull(receipt.fileId);
    System.out.println("file: " + newFileId);
    // now delete the file
    TransactionResponse fileDeleteTransactionResponse = new FileDeleteTransaction().setFileId(newFileId).execute(client);
    // if this doesn't throw then the transaction was a success
    fileDeleteTransactionResponse.getReceipt(client);
    System.out.println("File deleted successfully.");
    new FileInfoQuery().setFileId(newFileId).execute(client);
// note the above fileInfo will fail with FILE_DELETED due to a known issue on Hedera
}
Also used : FileCreateTransaction(com.hedera.hashgraph.sdk.FileCreateTransaction) FileInfoQuery(com.hedera.hashgraph.sdk.FileInfoQuery) TransactionResponse(com.hedera.hashgraph.sdk.TransactionResponse) FileDeleteTransaction(com.hedera.hashgraph.sdk.FileDeleteTransaction) 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