Search in sources :

Example 11 with Client

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

the class GetAccountBalanceExample method main.

public static void main(String[] args) throws PrecheckStatusException, TimeoutException {
    Client client = Client.forName(HEDERA_NETWORK);
    // Because AccountBalanceQuery is a free query, we can make it without setting an operator on the client.
    Hbar balance = new AccountBalanceQuery().setAccountId(OPERATOR_ID).execute(client).hbars;
    System.out.println("balance = " + balance);
}
Also used : AccountBalanceQuery(com.hedera.hashgraph.sdk.AccountBalanceQuery) Hbar(com.hedera.hashgraph.sdk.Hbar) Client(com.hedera.hashgraph.sdk.Client)

Example 12 with Client

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

the class GetExchangeRatesExample method main.

public static void main(String[] args) throws ReceiptStatusException, TimeoutException, PrecheckStatusException, 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);
    // Get contents of file 0.0.112
    ByteString fileContentsByteString = new FileContentsQuery().setFileId(FileId.fromString("0.0.112")).execute(client);
    byte[] fileContents = fileContentsByteString.toByteArray();
    ExchangeRates exchangeRateSet = ExchangeRates.fromBytes(fileContents);
    // Prints query results to console
    System.out.println("Current numerator: " + exchangeRateSet.currentRate.cents);
    System.out.println("Current denominator: " + exchangeRateSet.currentRate.hbars);
    System.out.println("Current expiration time: " + exchangeRateSet.currentRate.expirationTime.toString());
    System.out.println("Current Exchange Rate: " + exchangeRateSet.currentRate.exchangeRateInCents);
    System.out.println("Next numerator: " + exchangeRateSet.nextRate.cents);
    System.out.println("Next denominator: " + exchangeRateSet.nextRate.hbars);
    System.out.println("Next expiration time: " + exchangeRateSet.nextRate.expirationTime.toString());
    System.out.println("Next Exchange Rate: " + exchangeRateSet.nextRate.exchangeRateInCents);
}
Also used : FileContentsQuery(com.hedera.hashgraph.sdk.FileContentsQuery) ByteString(com.google.protobuf.ByteString) ExchangeRates(com.hedera.hashgraph.sdk.ExchangeRates) Client(com.hedera.hashgraph.sdk.Client)

Example 13 with Client

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

the class MultiSigOfflineExample method main.

public static void main(String[] args) throws PrecheckStatusException, TimeoutException, ReceiptStatusException, 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);
    PrivateKey user1Key = PrivateKey.generateED25519();
    PrivateKey user2Key = PrivateKey.generateED25519();
    System.out.println("private key for user 1 = " + user1Key);
    System.out.println("public key for user 1 = " + user1Key.getPublicKey());
    System.out.println("private key for user 2 = " + user2Key);
    System.out.println("public key for user 2 = " + user2Key.getPublicKey());
    // create a multi-sig account
    KeyList keylist = new KeyList();
    keylist.add(user1Key);
    keylist.add(user2Key);
    TransactionResponse createAccountTransaction = new AccountCreateTransaction().setInitialBalance(new Hbar(2)).setKey(keylist).execute(client);
    @Var TransactionReceipt receipt = createAccountTransaction.getReceipt(client);
    System.out.println("account id = " + receipt.accountId);
    // create a transfer from new account to 0.0.3
    TransferTransaction transferTransaction = new TransferTransaction().setNodeAccountIds(Collections.singletonList(new AccountId(3))).addHbarTransfer(Objects.requireNonNull(receipt.accountId), Hbar.from(-1)).addHbarTransfer(new AccountId(3), new Hbar(1)).freezeWith(client);
    // convert transaction to bytes to send to signatories
    byte[] transactionBytes = transferTransaction.toBytes();
    Transaction<?> transactionToExecute = Transaction.fromBytes(transactionBytes);
    // ask users to sign and return signature
    byte[] user1Signature = user1Key.signTransaction(Transaction.fromBytes(transactionBytes));
    byte[] user2Signature = user2Key.signTransaction(Transaction.fromBytes(transactionBytes));
    // recreate the transaction from bytes
    transactionToExecute.signWithOperator(client);
    transactionToExecute.addSignature(user1Key.getPublicKey(), user1Signature);
    transactionToExecute.addSignature(user2Key.getPublicKey(), user2Signature);
    TransactionResponse result = transactionToExecute.execute(client);
    receipt = result.getReceipt(client);
    System.out.println(receipt.status);
}
Also used : PrivateKey(com.hedera.hashgraph.sdk.PrivateKey) TransactionResponse(com.hedera.hashgraph.sdk.TransactionResponse) AccountId(com.hedera.hashgraph.sdk.AccountId) Var(com.google.errorprone.annotations.Var) KeyList(com.hedera.hashgraph.sdk.KeyList) TransactionReceipt(com.hedera.hashgraph.sdk.TransactionReceipt) Hbar(com.hedera.hashgraph.sdk.Hbar) Client(com.hedera.hashgraph.sdk.Client) TransferTransaction(com.hedera.hashgraph.sdk.TransferTransaction) AccountCreateTransaction(com.hedera.hashgraph.sdk.AccountCreateTransaction)

Example 14 with Client

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

the class SDKClient method getValidatedClient.

private Client getValidatedClient(Map<String, AccountId> currentNetworkMap, Client client) throws InterruptedException {
    Map<String, AccountId> validNodes = new LinkedHashMap<>();
    for (var nodeEntry : currentNetworkMap.entrySet()) {
        try {
            if (validateNode(nodeEntry.getValue().toString(), client)) {
                validNodes.putIfAbsent(nodeEntry.getKey(), nodeEntry.getValue());
                log.trace("Added node {} at endpoint {} to list of valid nodes", nodeEntry.getValue(), nodeEntry.getKey());
            }
        } catch (Exception e) {
        // 
        }
    }
    log.info("{} of {} nodes are reachable", validNodes.size(), currentNetworkMap.size());
    if (validNodes.size() == 0) {
        throw new IllegalStateException("All provided nodes are unreachable!");
    }
    log.info("Creating validated client using nodes: {} nodes", validNodes);
    Client validatedClient = Client.forNetwork(validNodes);
    validatedClient.setOperator(expandedOperatorAccountId.getAccountId(), expandedOperatorAccountId.getPrivateKey());
    validatedClient.setMirrorNetwork(List.of(mirrorNodeAddress));
    return validatedClient;
}
Also used : AccountId(com.hedera.hashgraph.sdk.AccountId) ExpandedAccountId(com.hedera.mirror.test.e2e.acceptance.props.ExpandedAccountId) ByteString(com.google.protobuf.ByteString) Client(com.hedera.hashgraph.sdk.Client) TimeoutException(java.util.concurrent.TimeoutException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) PrecheckStatusException(com.hedera.hashgraph.sdk.PrecheckStatusException) LinkedHashMap(java.util.LinkedHashMap)

Example 15 with Client

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

the class TransactionPublisher method getClients.

private synchronized Flux<Client> getClients() {
    NodeValidationProperties validationProperties = monitorProperties.getNodeValidation();
    var configuredNodes = monitorProperties.getNodes();
    Map<String, AccountId> nodeMap = configuredNodes.stream().collect(Collectors.toMap(NodeProperties::getEndpoint, p -> AccountId.fromString(p.getAccountId())));
    this.nodes.addAll(configuredNodes);
    Client client = toClient(nodeMap);
    client.setMaxAttempts(validationProperties.getMaxAttempts());
    client.setMaxBackoff(validationProperties.getMaxBackoff());
    client.setMinBackoff(validationProperties.getMinBackoff());
    client.setRequestTimeout(validationProperties.getRequestTimeout());
    this.validationClient.set(client);
    if (validationProperties.isEnabled() && nodeValidator.get() == null) {
        int nodeCount = configuredNodes.size();
        int parallelism = Math.min(nodeCount, validationProperties.getMaxThreads());
        var scheduler = Schedulers.newParallel("validator", parallelism + 1);
        var disposable = Flux.interval(Duration.ZERO, validationProperties.getFrequency(), scheduler).filter(// In case it's later disabled
        i -> validationProperties.isEnabled()).flatMap(i -> Flux.fromIterable(configuredNodes)).parallel(parallelism).runOn(scheduler).map(this::validateNode).sequential().buffer(nodeCount).doOnNext(i -> log.info("{} of {} nodes are functional", nodes.size(), nodeCount)).doOnSubscribe(s -> log.info("Starting node validation")).onErrorContinue((e, i) -> log.error("Exception validating nodes: ", e)).subscribe();
        nodeValidator.set(disposable);
    }
    return Flux.range(0, publishProperties.getClients()).flatMap(i -> Mono.defer(() -> Mono.just(toClient(nodeMap))));
}
Also used : NodeProperties(com.hedera.mirror.monitor.NodeProperties) Disposable(reactor.core.Disposable) TransferTransaction(com.hedera.hashgraph.sdk.TransferTransaction) RequiredArgsConstructor(lombok.RequiredArgsConstructor) TimeoutException(java.util.concurrent.TimeoutException) Status(com.hedera.hashgraph.sdk.Status) AtomicReference(java.util.concurrent.atomic.AtomicReference) SecureRandom(java.security.SecureRandom) HbarUnit(com.hedera.hashgraph.sdk.HbarUnit) WithExecute(com.hedera.hashgraph.sdk.WithExecute) Duration(java.time.Duration) Map(java.util.Map) Transaction(com.hedera.hashgraph.sdk.Transaction) Schedulers(reactor.core.scheduler.Schedulers) AccountId(com.hedera.hashgraph.sdk.AccountId) Hbar(com.hedera.hashgraph.sdk.Hbar) Named(javax.inject.Named) TransactionResponse(com.hedera.hashgraph.sdk.TransactionResponse) TransactionId(com.hedera.hashgraph.sdk.TransactionId) TransactionRecordQuery(com.hedera.hashgraph.sdk.TransactionRecordQuery) NodeValidationProperties(com.hedera.mirror.monitor.NodeValidationProperties) Client(com.hedera.hashgraph.sdk.Client) Mono(reactor.core.publisher.Mono) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) TransactionReceiptQuery(com.hedera.hashgraph.sdk.TransactionReceiptQuery) Flux(reactor.core.publisher.Flux) SUCCESS(com.hedera.hashgraph.sdk.Status.SUCCESS) Log4j2(lombok.extern.log4j.Log4j2) PrivateKey(com.hedera.hashgraph.sdk.PrivateKey) MonitorProperties(com.hedera.mirror.monitor.MonitorProperties) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) AccountId(com.hedera.hashgraph.sdk.AccountId) NodeValidationProperties(com.hedera.mirror.monitor.NodeValidationProperties) 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