Code Monkey home page Code Monkey logo

hedera-sdk-java's Introduction

Hedera™ Hashgraph Java SDK

The Java SDK for interacting with Hedera Hashgraph: the official distributed consensus platform built using the hashgraph consensus algorithm for fast, fair and secure transactions. Hedera 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. Please install the latest version 2.x.x or migrate from v1 to the latest 2.x.x version. You can reference the migration documentation.

Java app quickstart

The Java application quickstart guide covers how to properly set up the dependencies needed to start developing your Java project using the Hedera™ Java SDK.

Android app quickstart

The Android application quickstart guide covers how to properly set up the dependencies needed to start developing your Android project using the Hedera™ Java SDK.

Examples

This repository includes Java examples and an Android example that showcase different use cases and workflows.

Developer quickstart

The developer quickstart guide 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.

Support

If you have a question on how to use the product, please see our support guide.

Contributing

We welcome participation from all developers!
For instructions on how to contribute to this repo, please review the Contributing Guide.
More instructions for contribution can be found in the Global Contributing Guide.

Code of Conduct

This project is governed by the Contributor Covenant Code of Conduct. By participating, you are expected to uphold this code of conduct.

License

Apache License 2.0

hedera-sdk-java's People

Contributors

agadzhalov avatar andrix10 avatar dependabot[bot] avatar dikel avatar gregscullard avatar janaakhterov avatar jivkokelchev avatar mehcode avatar nathanklick avatar petreze avatar pinpong avatar qtbeee avatar questofiranon avatar rbarkersl avatar regan-koopmans avatar rickyrodmac avatar sean-tedrow-lb avatar shemnon avatar sheng-long avatar simihunjan avatar steven-sheehy avatar superboo avatar thenswan avatar timmolter avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hedera-sdk-java's Issues

Error in mapping documentation. Line 829 of HederaContract.java

hedera-sdk-java/sdk/src/main/java/com/hedera/sdk/contract/HederaContract.java
Release 0.3.0
Java SDK

--------------------- Issue: mvn install fails. ----------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:3.0.1:javadoc (attach-javadocs) on project hedera-java-sdk: An error has occurred in Javadoc report generation:
[ERROR] Exit code: 1 - C:\Swirlds\hedera-sdk-java-0.3.0\sdk\src\main\java\com\hedera\sdk\contract\HederaContract.java:829: error: @param name not found
[ERROR] * @param accountID accountID of the account records being queried
[ERROR] ^
[ERROR] C:\Swirlds\hedera-sdk-java-0.3.0\sdk\src\main\java\com\hedera\sdk\contract\HederaContract.java:833: warning: no @param for contractID
[ERROR] public boolean getRecords(HederaTransaction payment, HederaQueryHeader.QueryResponseType responseType, HederaContractID contractID) throws InterruptedException {

----------------------------Correction -----------------------
Line 829 @param accountID accountID of the account records being queried
does not map the parameters.
replace with * @param contractID contractID of the contract records being queried

Enable checkstyle for tests

This has to be done explicitly by adding <includeTestSourceDirectory>true</includeTestSourceDirectory> to the plugin config.

I attempted this in #111 but it resulted in a lot of errors so we decided it should be done in a separate task.

Double deduction of Account query fee

Issue summary:

As per the current setup, the cost of account query is 100000 Tinybars.
But, 200000 Tinybars is deducted.

OS version:

macOS Mojave
Version 10.14.1 (18B75)

--
Java -version
java version "10.0.2" 2018-07-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.2+13)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.2+13, mixed mode)

--
Source code:
HederaAccountTest.java

--
Test output:

Run 1 log:

header {
    cost: 100000
  }
  accountID {
    accountNum: 1001
  }
  balance: 100498205000
}

Run 2 log:

  header {
    cost: 100000
  }
  accountID {
    accountNum: 1001
  }
  balance: 100498005000
}

--
Issue:

First run balance:
100498205000

Second run balance:
100498005000

According to the 'cost' metioned, which is, 100000 TinyBars, the call should return a balance of 100498105000 instead of 100498005000.

This needs to be fixed.

DecoderException for private key string (DecoderException) when reading OPERATOR_KEY from .env file

Exception in thread "main" org.bouncycastle.util.encoders.DecoderException: exception decoding Hex string: invalid characters encountered in Hex string
at org.bouncycastle.util.encoders.Hex.decode(Unknown Source)
at com.hedera.hashgraph.sdk.crypto.ed25519.Ed25519PrivateKey.fromString(Ed25519PrivateKey.java:94)
at client.hederaClient(client.java:20)
at client.main(client.java:47)
Caused by: java.io.IOException: invalid characters encountered in Hex string
at org.bouncycastle.util.encoders.HexEncoder.decode(Unknown Source)
... 4 more

It's private key so I would rather not place it here. :)

Download Data Files like Fee,Address Book from Node

The address for the corresponding data files on the main-net are as follows
101 - Address Book
102 - Fee Schedule

The Fee Schedule will have two set of schedules, current & future.
All the clients are required to download a copy of the file for calculating the fees.

Example StatefulContract.java not working

Says method addString() not defined (used while passing parameters to functions)
Works by changing to add() but add() only accepts string parameters. Not uint, int, address etc.

To pass ints, I tried first converting the int to a byte array like so:

byte newValue = (byte) 3;  // x is an integer
byte[] newValueBytes = ByteBuffer.allocate(1).put(newValue).array();
new ContractExecuteTransaction(client).setContractId(newContractId)
            .setGas(100_000_000)
            setConstructorParams(
                CallParams.constructor()
                    .add( newValueBytes ));

On calling "get_int()" I get "32" instead of 3 which makes no sense.
And When I later tried calling "set_int()" it does absolutely nothing

(Working on Stateful.sol provided in examples. Just changed get/set_message() to get/set_int() respectively)

Solidity require statement not throwing errors on hedera

I slightly modified the stateful.sol used in examples to include a onlyOwner modifier (i.e.
require that only owner can call set_message().
Then in the CreateStatefulContract.java, I called set_message from a different account (i.e. not the one that deployed the contract). Although the message doesn't change, there are no errors thrown by the smart contract or Hedera (I tried catching HederaException and HederaNetworkException).

I have attached the CreateStatefulContract.java and the output of my console for reference.

Stateful.sol that I am working with:

pragma solidity >=0.4.22 <0.6.0;

contract StatefulContract {
    // the contract's owner, set in the constructor
    address public owner;

    // the message we're storing
    uint private _message;
    
    modifier onlyOwner {
        require(msg.sender == owner);
        _;
    }

    constructor(uint message_) public {
        // set the owner of the contract for `kill()`
        owner = msg.sender;
        _message = message_;
    }

    function set_message(uint message_) public onlyOwner {
        // only allow the owner to update the message
        _message = message_;
    }

    // return a string
    function get_message() public view returns (uint) {
        return _message;
    }
}

CONSOLE OUTPUT:

contract bytecode file: 0.0.21691
new contract ID: 0.0.21692
contract returned message: 1234
Calling set_message from new client.
Waiting 5s for consensus and contract execution
Calling get_message again to see if changes occurred.
contract returned message: 1234

CreateStatefulContract.java.txt

mvn install fails

When I clone the repository and run mvn build, I get the following error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project sdk: Compilation failure [ERROR] ~/hedera-sdk-java/src/main/java/com/hedera/sdk/common/HederaKeyList.java:[12,42] cannot access com.hederahashgraph.api.proto.java.Key [ERROR] bad class file: ~/.m2/repository/com/opencrowd/hapi-proto/1.1/hapi-proto-1.1.jar(com/hederahashgraph/api/proto/java/Key.class) [ERROR] class file has wrong version 54.0, should be 52.0 [ERROR] Please remove or make sure it appears in the correct subdirectory of the classpath.

This is on MacOS High Sierra 10.19.6, Maven 3.5.4, java version 1.8.0_121

receiverSignatureRequired = true requires signature by account owner

When creating a new account with receiverSignatureRequired, two signatures at a minimum are required.
-The signature for the key(s) paying for the transaction (and funding the account)
-The signature for the public key(s) of the new account.

The second signature serves as a verification that the public key is valid and that the account isn't locked for receiving funds.

Sporadic/inconsistent erroneous DUPLICATE_TRANSACTION errors in testnet.

When submitting CryptoTransfers using async calls in rapid succession that differ only in memo (same sender/recipient/amount), I'm getting sporadic DUPLICATE_TRANSACTION results.
Sometimes they happen, sometimes they don't.

A modified examples TransferCrypto.java (edit SET_YOUR_RECIPIENT_ID_HERE):

package com.hedera.hashgraph.sdk.examples.advanced;

import com.hedera.hashgraph.sdk.HederaException;
import com.hedera.hashgraph.sdk.HederaThrowable;
import com.hedera.hashgraph.sdk.TransactionRecord;
import com.hedera.hashgraph.sdk.account.AccountId;
import com.hedera.hashgraph.sdk.account.CryptoTransferTransaction;
import com.hedera.hashgraph.sdk.examples.ExampleHelper;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public final class TransferCrypto {
    private TransferCrypto() { }

    private static final int CONCURRENT_TRANSACTIONS = 10;

    public static void main(String[] args) throws HederaException, InterruptedException {
        var operatorId = ExampleHelper.getOperatorId();
        var client = ExampleHelper.createHederaClient();
        var recipientId = AccountId.fromString(SET_YOUR_RECIPIENT_ID_HERE);
        var amount = 1;

        var latch = new CountDownLatch(CONCURRENT_TRANSACTIONS);

        var senderBalanceBefore = client.getAccountBalance(operatorId);
        var receiptBalanceBefore = client.getAccountBalance(recipientId);
        System.out.println("" + operatorId + " balance = " + senderBalanceBefore + " , " +
                recipientId + " balance = " + receiptBalanceBefore);

        Consumer<TransactionRecord> onSuccess = (record) -> {
            System.out.println(System.currentTimeMillis() + " " + record.getMemo() + " completed " +
                record.getConsensusTimestamp());
            latch.countDown();
        };

        Consumer<HederaThrowable> onError = (e) -> {
            System.out.println(e);
            if (e instanceof HederaException) {
                var he = (HederaException)e;
                System.out.println(he.getMessage());
                System.out.println(he.responseCode);
                he.printStackTrace();
            }
            latch.countDown();
        };

        for (var i = 0; i < CONCURRENT_TRANSACTIONS; ++i) {
            var memo = "async-test-" + System.currentTimeMillis(); // i;
            var cryptoTransfer = new CryptoTransferTransaction(client)
                    .addSender(operatorId, amount)
                    .addRecipient(recipientId, amount)
                    .setMemo(memo);
            System.out.println(System.currentTimeMillis() + " " + memo + " sent.");
            cryptoTransfer.executeForRecordAsync(onSuccess, onError);
            Thread.sleep(5);
        }
        try {
            latch.await(20, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        var senderBalanceAfter = client.getAccountBalance(operatorId);
        var receiptBalanceAfter = client.getAccountBalance(recipientId);
        System.out.println("" + operatorId + " balance = " + senderBalanceAfter + " , " +
                recipientId + " balance = " + receiptBalanceAfter);
    }
}

Exceptions seen:

com.hedera.hashgraph.sdk.HederaException: DUPLICATE_TRANSACTION
DUPLICATE_TRANSACTION
DUPLICATE_TRANSACTION
com.hedera.hashgraph.sdk.HederaException: DUPLICATE_TRANSACTION
    at com.hedera.hashgraph.sdk.HederaException.throwIfExceptional(HederaException.java:39)
    at com.hedera.hashgraph.sdk.QueryBuilder.mapResponse(QueryBuilder.java:173)
    at com.hedera.hashgraph.sdk.QueryBuilder.mapResponse(QueryBuilder.java:13)
    at com.hedera.hashgraph.sdk.HederaCall$1.onNext(HederaCall.java:40)
    at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onMessage(ClientCalls.java:421)
    at io.grpc.ForwardingClientCallListener.onMessage(ForwardingClientCallListener.java:33)
    at io.grpc.ForwardingClientCallListener.onMessage(ForwardingClientCallListener.java:33)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1MessagesAvailable.runInContext(ClientCallImpl.java:519)
    at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
    at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)

Hedera Exception: INVALID_NODE_ACCOUNT when calling client.getAccountBalance(newAccountId1)

Hedera Exception: INVALID_NODE_ACCOUNT when calling client.getAccountBalance(AccountId.fromString(newAccountId1));
about the new upgraded Testnets and support for 4 nodes in Hedera Java SDK v:0.5.0;
I have updated my Java code (class ClientExample) to read 4 nodes from my .env file (which now contains 4 pairs of Node ID & Node Addresses);
I have also included the Java statement: hederaClient1 = new Client(Map.of(nodeId1, nodeAddress1, nodeId2, nodeAddress2, nodeId3, nodeAddress3, nodeId4, nodeAddress4));
as specified by Greg Scullard; the program creates a new account on Hedera Testnet, with new Account ID: 0.0.10480;
but it gets an error (INVALID_NODE_ACCOUNT) when it tries to get the Account Balance:
Java statement: accountBalance1 = client1.getAccountBalance(AccountId.fromString(newAccountId1));
Here is the Output, displayed by my Program:
Hello Hedera Java SDK World from Kamal !
clientExample --> main entered.
Client Example --> getEnv entered.
clientExample --> hederaClient --> Operator ID 1: 0.0.1613
clientExample --> hederaClient --> Operator Key 1: 302e.....
clientExample --> hederaClient --> Node ID 1: 0.0.3
clientExample --> hederaClient --> Node Address 1: 0.testnet.hedera.com:50211
clientExample --> hederaClient --> Node ID 2: 0.0.4
clientExample --> hederaClient --> Node Address 2: 1.testnet.hedera.com:50211
clientExample --> hederaClient --> Node ID 3: 0.0.5
clientExample --> hederaClient --> Node Address 3: 2.testnet.hedera.com:50211
clientExample --> hederaClient --> Node ID 4: 0.0.6
clientExample --> hederaClient --> Node Address 4: 3.testnet.hedera.com:50211
Client --> constructor entered.
New Account ID: 0.0.10480
Main Program --> Client Example --> Main error --> Hedera Exception.
com.hedera.hashgraph.sdk.HederaException: INVALID_NODE_ACCOUNT
at com.hedera.hashgraph.sdk.HederaException.throwIfExceptional(HederaException.java:38)
at com.hedera.hashgraph.sdk.QueryBuilder.mapResponse(QueryBuilder.java:168)
at com.hedera.hashgraph.sdk.QueryBuilder.mapResponse(QueryBuilder.java:10)
at com.hedera.hashgraph.sdk.HederaCall.execute(HederaCall.java:31)
at com.hedera.hashgraph.sdk.Client.getAccountBalance(Client.java:133)
at com.hedera.hashgraph.sdk.examples.simple.ClientExample.main(ClientExample.java:107)
at pkg.Program.main(Program.java:38)
This issue persists, please could you solve the problem ?

Request for async calls to include more info (context) in returns and error handlers.

Regarding specifically CryptoTransferTransaction, the async calls executeAsync(), executeForRecordAsync() and executeForReceiptAsync().

They currently return void and the error handlers (handling HederaThrowable/HederaException) don't provide any context about the request (transaction ID, etc).

If possible, could/should the exec*Async() calls return a transaction ID and the error handler also provide that context (transaction ID or the request itself)? If the context is available (in either case), it would be useful.

ContractExecuteTransaction.executeForRecord() returns RECORD_NOT_FOUND

When running a smart contract function with ContractExecuteTransaction.executeForRecord(), the method returns RECORD_NOT_FOUND.

example

ContractExecuteTransaction tx = new ContractExecuteTransaction(hedera.getClient());
        tx.setContract(new ContractId(shardNum, realmNum, contractNum));
        tx.setFunctionParameters(CallParams.function("set_message").add("hi there"));
        tx.setGas(gas);
        TransactionRecord record = tx.executeForRecord();
        FunctionResult result = record.getCallResult();

a workaround which gets a receipt first, then a record works

   ContractExecuteTransaction tx = new ContractExecuteTransaction(client);
        tx.setContract(newContractId);
        tx.setFunctionParameters(CallParams.function("set_message").add("hi there"));
        var operatorId = new AccountId(2);
        var transactionId = new TransactionId(operatorId);
        tx.setTransactionId(transactionId);

        tx.setGas(gas);

        var receipt = tx.executeForReceipt();

in the executeForRecord() scenario, the SDK should first wait for a receipt, and only fetch a record if the receipt ResponseCodeEnum is OK in the first place.

At the time the record is requested, the transaction status is likely still UNKNOWN leading to a RECORD_NOT_FOUND since one doesn't exist yet.

Note: Pausing the execution in debug, and waiting for the transaction to complete results in a record being recovered from the network.

Exceptions should not be eaten.

Throughout the project exceptions are being eaten.

try {
} catch (InterruptedException e) {
    e.printStackTrace();
}

Exception from third party components should be thrown out to be handled by calling components.

try {
} catch (InterruptedException e) {
    throw e;
}

CreateStatefulContract does not work

The CreateStatefulContract does not work. I made the following changes which fixes some of the issues but still leaves the issue that the set_message call fails to update the message.

  • changed hello_world.json to stateful.json
  • changed var byteCode = ExampleHelper.parseHex(byteCodeHex); to var byteCode = byteCodeHex.getBytes();
  • added the following to the new ContractCreateTranscation() call: .setAutoRenewPeriod(Duration.ofHours(1)).setGas(100_000_000)
  • added .setGas(100_000_000) to the other transaction and query calls.

After making the above changes, it runs but still returns "hello from hedera!" as shown below:

contract bytecode file: 0.0.10566
new contract ID: 0.0.10567
contract returned message: hello from hedera!
contract returned message: hello from hedera!

Add output to files (can be encrypted)

https://github.com/hashgraph/hedera-sdk-java/blob/master/examples/src/main/java/com/hedera/hashgraph/sdk/examples/simple/CreateAccount.java

Inside this file, we can add the output to files. It has to be encrypted by the secret in that we can set in .env file, so it's easier to use later on private and public keys.

Just printing to console is not ideal.

Then again writing to file private key is also not ideal despite encryption. So let me know your thoughts.

If it's okay for you I can help with this.

Request to prefix artifact-id with 'hedera'

Few artifactIds are named as java-sdk-full and java-sdk, in the pom.xml files.
These should be renamed as hedera-java-sdk-full and hedera-java-sdk, respectively.

Though they're unique in the maven repo, it's not helpful to locate the hedera related sdk jars under lib directory.

For example:

myMac:hh-core admin$ ls -ltr target/libs/ | grep hedera
-rw-r--r--  1 admin  staff    44612 Jan 15 17:43 hedera-sdk-java-examples-0.2.0.jar
myMac:hh-core admin$ 

But, a generic search brings a java sdk (which should have been a hedera sdk)!

myMac:hh-core admin$ ls -ltr target/libs/ | grep sdk
-rw-r--r--  1 admin  staff   223679 Jan 15 17:43 java-sdk-0.2.0.jar
-rw-r--r--  1 admin  staff    44612 Jan 15 17:43 hedera-sdk-java-examples-0.2.0.jar
myMac:hh-core admin$ 

Another potential problem is that, if someone publishes an artifactId with the SIMILAR name java-sdk, like below, this will cause confusions and/or conflicts - besides, it will be difficult to isolate the problem.

<groupId>com.example.company</groupId>
<artifactId>java-sdk</artifactId>
<version>0.2.0</version>
<packaging>jar</packaging>

So, I strongly recommend that, all the hedera related artifacts are prefixed with 'hedera' or something similar and unique.

Thanks!

Missing errors when node or txQueryDefaults not set

If a developer forgets to set a node, a node's properties (host+port) or txQuerydefault parameters such as payingAccountID, node, payingKeyPair, etc... the sdk doesn't provide much feedback to help debugging.

Hedera Exception: INVALID_NODE_ACCOUNT when calling client.getAccountBalance(AccountId.fromString(newAccountId1))

about the new upgraded Testnets and support for 4 nodes in Hedera Java SDK v:0.5.0;
I have updated my Java code (class ClientExample) to read 4 nodes from my .env file
(which now contains 4 pairs of Node ID & Node Addresses);
I have also included the Java statement:
hederaClient1 = new Client(Map.of(nodeId1, nodeAddress1, nodeId2, nodeAddress2, nodeId3, nodeAddress3, nodeId4, nodeAddress4)); as specified by Greg Scullard.
The program creates a new account on Hedera Testnet, with new Account ID: 0.0.10480;
but it gets an error (INVALID_NODE_ACCOUNT) when it tries to get the Account Balance:
Java statement:
accountBalance1 = client1.getAccountBalance(AccountId.fromString(newAccountId1));
Here is the Output, displayed by my Program:
Hello Hedera Java SDK World from Kamal !
clientExample --> main entered.
Client Example --> getEnv entered.
clientExample --> hederaClient --> Operator ID 1: 0.0.1613
clientExample --> hederaClient --> Operator Key 1: 302e.....
clientExample --> hederaClient --> Node ID 1: 0.0.3
clientExample --> hederaClient --> Node Address 1: 0.testnet.hedera.com:50211
clientExample --> hederaClient --> Node ID 2: 0.0.4
clientExample --> hederaClient --> Node Address 2: 1.testnet.hedera.com:50211
clientExample --> hederaClient --> Node ID 3: 0.0.5
clientExample --> hederaClient --> Node Address 3: 2.testnet.hedera.com:50211
clientExample --> hederaClient --> Node ID 4: 0.0.6
clientExample --> hederaClient --> Node Address 4: 3.testnet.hedera.com:50211
Client --> constructor entered.
New Account ID: 0.0.10480
Main Program --> Client Example --> Main error --> Hedera Exception.
com.hedera.hashgraph.sdk.HederaException: INVALID_NODE_ACCOUNT
at com.hedera.hashgraph.sdk.HederaException.throwIfExceptional(HederaException.java:38)
at com.hedera.hashgraph.sdk.QueryBuilder.mapResponse(QueryBuilder.java:168)
at com.hedera.hashgraph.sdk.QueryBuilder.mapResponse(QueryBuilder.java:10)
at com.hedera.hashgraph.sdk.HederaCall.execute(HederaCall.java:31)
at com.hedera.hashgraph.sdk.Client.getAccountBalance(Client.java:133)
at com.hedera.hashgraph.sdk.examples.simple.ClientExample.main(ClientExample.java:107)
at pkg.Program.main(Program.java:38)

Please could you solve the problem ?

Generating Solidity Address from Hedera Account ID

Useful for ERC20 Token Contracts, when you need to pass solidity addresses as a parameter.
Based on the code of sdk 0.3.0,
I have slightly modified it to make it compatible with the current SDK:

Import java.nio.ByteBuffer;

import com.hedera.hashgraph.sdk.account.AccountId;
import com.hedera.hashgraph.sdk.contract.ContractId;
import com.hedera.hashgraph.sdk.file.FileId;

public class SolidityAddressGenerator {
	
	private static String	digits = "0123456789abcdef";
	
	
	public static String calculateSolidityAddress(long accountNum) {
        return calculateSolidityAddress(0,0,accountNum);
    }
    public static String calculateSolidityAddress(AccountId accountID) {
        return calculateSolidityAddress(accountID.getShardNum(), accountID.getRealmNum(), accountID.getAccountNum());
    }
    public static String calculateSolidityAddress(ContractId contractID) {
        return calculateSolidityAddress(contractID.getShardNum(), contractID.getRealmNum(), contractID.getContractNum());
    }
    public static String calculateSolidityAddress(FileId fileID) {
        return calculateSolidityAddress(fileID.getShardNum(), fileID.getRealmNum(), fileID.getFileNum());
    }
    
    public static String calculateSolidityAddress(long shardNum, long realNum, long accountNum) {
        
    	byte[] solidityByteArray = new byte[20];
        
        int shard = (int)shardNum;
        byte[] bytes = ByteBuffer.allocate(4).putInt(shard).array();
        // byte 0 to 3 are shard
        for (int i=0; i < 4; i++) {
            solidityByteArray[i] = bytes[i];
        }
        // byte 4 to 11 are realm
        bytes = ByteBuffer.allocate(8).putLong(realNum).array();
        for (int i=0; i < 8; i++) {
            solidityByteArray[i+4] = bytes[i];
        }
        
        bytes = ByteBuffer.allocate(8).putLong(accountNum).array();
        // byte 12 to 19 are account number
        for (int i=0; i < 8; i++) {
            solidityByteArray[i+12] = bytes[i];
        }
        return toHex(solidityByteArray);        
    }
    
    public static String toHex(byte[] data) {
        StringBuffer	buf = new StringBuffer();
        int length = data.length;
        
        for (int i = 0; i != length; i++)
        {
            int	v = data[i] & 0xff;
            
            buf.append(digits.charAt(v >> 4));
            buf.append(digits.charAt(v & 0xf));
        }
        
        return buf.toString();
    }
}

Would be great if this is included within the SDK for easy calls!

PS - Thanks to @gregscullard for providing me with the above code.

Standardization of some function names

When I use “FileInfoQuery” or “FileContentsQuery”, I need to use “setFileId”. But if I use “FileUpdateTransaction”, I can use a method called “setFile”. It may be nice to always have the same method name.

AccountUpdateTransaction fails if setKey() not called

If attempting to update attributes of the account other than the public key, AccountUpdateTransaction will fail client-side validation error.

Easy test is to modify and run (from sdk examples) UpdateAccountPublicKey.main() to:

new AccountUpdateTransaction(client)
    .setAccountForUpdate(ExampleHelper.getOperatorId())
    .setReceiveRecordThreshold(33)
    .executeForReceipt();

Resulting in the following exception:

Exception in thread "main" java.lang.IllegalStateException: transaction builder failed validation:
.setKey() required
	at com.hedera.hashgraph.sdk.HederaCall.checkValidationErrors(HederaCall.java:69)
	at com.hedera.hashgraph.sdk.TransactionBuilder.validate(TransactionBuilder.java:110)
	at com.hedera.hashgraph.sdk.TransactionBuilder.build(TransactionBuilder.java:124)
	at com.hedera.hashgraph.sdk.TransactionBuilder.executeForReceipt(TransactionBuilder.java:155)
	at com.hedera.hashgraph.sdk.examples.advanced.UpdateAccountPublicKey.main(UpdateAccountPublicKey.java:39)

Appears to either be an implementation bug (if setKey should not be required unless updating the key), or documentation issue if setKey is required in order to update any attributes.

Public key reduction on signatures (optional)

A feature of the next version of HAPI is signatureMaps to replace the old method of providing signatures to a transaction.
Not only is the signatureMap much easier to use being a flat list of public key + signature compared to the hierarchical lists of old, it is possible to reduce the public keys provided in the map to the bare minimum required to uniquely identify them, it's even possible to leave the public key blank/null if there is only one key on an account/file. This causes a potential problem in multi-signature scenarios.

-User 1 creates and signs a transaction, sends it to user 2
-User 2 signs the transaction and submits to the network

If the transaction created by user 1 has had its public key reduced, it will potentially be null. When user 2 signs the transaction, it's no longer possible to ensure the public key reduction will result in uniquely identifiable keys.

When a transaction payload is created and signed, the full public keys should be included in the signatureMap.
Only when the transaction is sent to Hedera should the public keys be reduced.

FileInfoQuery throws UNRECOGNIZED exception for deleted files

FileInfoQuery works before I delete a file but after I delete a file it throws a HederaException with the text UNRECOGNIZED. Since deleting a file just marks it as deleted until it expires, I would expect FileInfoQuery to work until the file expires.

Smart contract calls with parameters other than string

Trying to run a smart contract function with a uint8 input value to no avail.
This is how the call is put together, but the contract reverts.

byte newValue = 10;
        byte[] newValueBytes = ByteBuffer.allocate(1).put(newValue).array();
        new ContractExecuteTransaction(client).setContractId(newContractId)
        .setGas(100_000_000)
        .setFunctionParameters(CallParams.function("set_value")
            .add(newValueBytes))
        .executeForReceipt();

Suggest implementing methods for setting a boolean, byte, int, long, bigInteger and address.

Also, the methods for recovering data from a call are limited to int and string, what about boolean, address, BigInteger, etc... for datatypes larger than int or long (e.g. int256).

Finally, how would an array of values be passed to a contract and returned from it ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.