Giter Site home page Giter Site logo

web3j / web3j Goto Github PK

View Code? Open in Web Editor NEW
4.9K 225.0 1.6K 9.96 MB

Lightweight Java and Android library for integration with Ethereum clients

Home Page: https://www.web3labs.com/web3j-sdk

License: Other

Java 98.82% Shell 0.24% Solidity 0.90% JavaScript 0.01% Dockerfile 0.03%
ethereum blockchain java solidity rxjava android smart-contracts smart-contract-tools ether reactivex

web3j's Introduction

Web3j: Web3 Java Ethereum Ðapp API

Documentation Status build status codecov Discord

Web3j is a lightweight, highly modular, reactive, type safe Java and Android library for working with Smart Contracts and integrating with clients (nodes) on the Ethereum network:

image

This allows you to work with the Ethereum blockchain, without the additional overhead of having to write your own integration code for the platform.

The Java and the Blockchain talk provides an overview of blockchain, Ethereum and Web3j.

Features

It has five runtime dependencies:

It also uses JavaPoet for generating smart contract wrappers.

QuickStart

The simplest way to start your journey with Web3j is to create a project. We provide this functionality using the Web3j CLI. This latter can be installed as follows:

For Unix:

curl -L get.web3j.io | sh && source ~/.web3j/source.sh

For Windows, in Powershell:

Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/web3j/web3j-installer/master/installer.ps1'))

Create a new project by running:

$ web3j new 

Or use our Maven or Gradle plugins to generate java files from Solidity contracts.

Please head to the Web3j Documentation for further instructions on using Web3j.

Maven

Java:

<dependency>
  <groupId>org.web3j</groupId>
  <artifactId>core</artifactId>
  <version>4.11.0</version>
</dependency>

Android:

<dependency>
  <groupId>org.web3j</groupId>
  <artifactId>core</artifactId>
  <version>4.8.7-android</version>
</dependency>

Gradle

Java:

implementation ('org.web3j:core:4.11.0')

Android:

implementation ('org.web3j:core:4.8.7-android')

Build instructions

Web3j includes integration tests for running against a live Ethereum client. If you do not have a client running, you can exclude their execution as per the below instructions.

To run a full build (excluding integration tests):

$ ./gradlew check

To run the integration tests, you will need to set up these variables in order to pull the Docker images from the Docker Hub registry:

  • registry.username
  • registry.password

Then run the following command:

$ ./gradlew -Pintegration-tests=true :integration-tests:test

If you do not want the integration test to run:

$ ./gradlew -Pintegration-tests=false :test

Check the Docker client API for more information on configuration options.

Commercial support and training

Commercial support and training is available from web3labs.com.

License

Apache 2.0

web3j's People

Contributors

1329576606 avatar alexandrour avatar alexdupre avatar andrii-kl avatar antonydenyer avatar benesjan avatar cfelde avatar conor10 avatar drinkcoffee avatar eepstein avatar fcorneli avatar gtebrean avatar iikirilov avatar iongchun avatar josh-richardson avatar kberezin-p6 avatar lyotam avatar mdhondt avatar mohamedelshami avatar mushketyk avatar nicksneo avatar rach-id avatar rvullriede avatar snazha-blkio avatar tonykwok1992 avatar tramonex-nate avatar vpriscan avatar xaviarias avatar yasseralaa avatar yuriymyronovych 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  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

web3j's Issues

Suggestion for Address.java: Getter for address as Hex-String

Hi Conor,

I was trying to compare the Address-object that I got from my smart contract with the Credentials-object of the current user to find out if that object was created by the current user. Address returns the address as a decimal, Credentials as a Hex String.

Eventually I figured it out and its working now, but it would be nice if Address would also have a getter for the Hex-String, so these two can be easily compared.

with best regards,
Max

web3j throws exception at Android 4.4 (API Level 19)

Hi,
trying the web3j lib on Android on 4.4 (19) leads to the following exception:
java.lang.NoClassDefFoundError: org.web3j.protocol.http.HttpService

at line
Web3j web3 = Web3jFactory.build(new HttpService(NODE_1));

Dependency:
compile 'org.web3j:core-android:2.1.0'

Switching to Android 6 (API 23) and everything is working fine.
I used the normal Android images from the latest AndroidStudio.
Is there a way to get it run on 4.4?

Regards
Daniel

SolidityFunctionWrapperGenerator creates compile-time error for zero-argument constructor

Hi Conor,

The following slightly modified example contract:

pragma solidity ^0.4.0;

contract SimpleStorage {
    uint storedData;
    
    function SimpleStorage() {
        storedData = 5;
    }

    function set(uint x) {
        storedData = x;
    }

    function get() constant returns (uint retVal) {
        return storedData;
    }
}

creates this Java code:

...
    public static Future<SimpleStorage> deploy(Web3j web3j, Credentials credentials, BigInteger initialValue) {
        return deployAsync(SimpleStorage.class, web3j, credentials, BINARY, encodedConstructor, initialValue);
    }
...

encodedConstructor cannot be resolved to a variable. This is due to the zero-argument constructor. When I add a fake(as in not used anywhere) uint argument to the constructor everything is fine. I do believe zero-argument constructors are allowed in Solidity, though.
I used the solidity web compiler to create .bin and .abi and am using web3j 1.0.3. I really like that SolidityFunctionWrapperGenerator now logs what its doing :-)

Best regards,
Max

Java smart contract wrappers does not support ABI with type of "address[] storage"

Here is the a contract code:
++++++++++++++++++++++++++++++++

pragma solidity ^0.4.4;
library Lib1{
    function findAddress(address a, address[] storage arry) returns (int){
        for (uint i = 0 ; i < arry.length ; i++){
            if(arry[i] == a){return int(i);}
        }
        return -1;
    }
    function removeAddress(uint i, address[] storage arry){
        uint lengthMinusOne = arry.length - 1;
        arry[i] = arry[lengthMinusOne];
        delete arry[lengthMinusOne];
        arry.length = lengthMinusOne;
    }
}

++++++++++++++++++++++++++++++++

When we try to generate the wrapper code using web3j's Command line tools:
++++++++++++++++++++++++++++++++
web3j solidity generate in/Lib1.bin in/Lib1.abi -o out/src/main/java -p com.vianet.blockchain.web3j.support.wrappers
++++++++++++++++++++++++++++++++

error is reported:
++++++++++++++++++++++++++++++++
Exception in thread "main" java.lang.UnsupportedOperationException: Unsupported type encountered: address[] storage
++++++++++++++++++++++++++++++++
image

Web3j only supports 1 transaction per block

Due to the behaviour of getNonce in ManagedTransaction.java:

    protected BigInteger getNonce(String address) throws InterruptedException, ExecutionException {
        EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
                address, DefaultBlockParameterName.LATEST).sendAsync().get();

        return ethGetTransactionCount.getTransactionCount();
    }

If more than 1 transaction is sent per block, the nonce will be incorrect (all transactions sent in the same block will have the same nonce). This will lead to all transaction but one being invalid.

Suggestion:
Maintain a count of how many transactions have been sent from the address for the current block, and return ethGetTransactionCount.getTransactionCount() + sentTransactionCount. This could still lead to problems in various situations, but would be an improvement. Really open to alternate solutions

ethSendTransaction via Parity to an Ethereum Harmony Client Can't Deserialize Response

(Note: If there is another location I should put this, or if I'm doing something really stupid, please let me know.)

Whenever I make a call to "ethSendTransction" (sync call), I get the following:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: org.apache.http.conn.EofSensorInputStream@144440f5; line: 1, column: 93] (through reference chain: org.web3j.protocol.core.methods.response.EthSendTransaction["error"]->org.web3j.protocol.core.Response$Error["data"]) at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270) at com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1234) at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1122) at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1075) at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:60) at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11) at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:499) at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:101) at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:276) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140) at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:499) at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:101) at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:276) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3798) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2908) at org.web3j.protocol.http.HttpService.lambda$getResponseHandler$16(HttpService.java:85) at org.web3j.protocol.http.HttpService$$Lambda$7/257495665.handleResponse(Unknown Source) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:222) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:164) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:139) at org.web3j.protocol.http.HttpService.send(HttpService.java:63) at org.web3j.protocol.core.Request.send(Request.java:71) at com.foo.service.Web3jTest.testCreateWallet(Web3jTest.java:57) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Now while I appreciate that I might be doing something wrong in my sequence of calls, I can't even view the error coming back.

Here's my calling code against a running Ethereum Harmony instance (note that the calls preceding the one in question all work just fine):

` Parity parity = Parity.build(new HttpService("http://localhost:8080/"));
NewAccountIdentifier newAccount = parity.personalNewAccount(this.PASSWORD).send();

PersonalUnlockAccount unlockAccount = parity.personalUnlockAccount(newAccount.getAccountId(), this.PASSWORD).send();

BigInteger value = Convert.toWei("7.5", Unit.ETHER).toBigInteger();

EthGetTransactionCount ethGetTransactionCount = parity.ethGetTransactionCount(
    this.COINBASE, DefaultBlockParameterName.LATEST).send();

BigInteger nonce = ethGetTransactionCount.getTransactionCount();

Transaction transaction = Transaction.createEtherTransaction(this.COINBASE, nonce, this.GAS_PRICE, this.GAS_LIMIT, newAccount.getAccountId(), value);

EthSendTransaction sendTx = parity.ethSendTransaction(transaction).send();

`

Any thoughts/comments welcome, and again, apologies if it's something fairly obvious (still finding my footing with Web3j and Harmony).

Thanks.

parity.personalNewAccountFromWallet(...) returns NullPointerException with valid arguments

Goal
I am trying to create a wallet on a client that is not running a node and then create a new account on the blockchain from that wallet through parity.personalNewAccountFromWallet(...).

Context
I can't find a way to access the credentials of an account created with parity.personalNewAccount(...) because WalletUtils.loadCredentials(...) will try loading the wallet from the remote client instead of the machine running the node. Therefore, I thought that the best way to create an account would be through the wallet.

What I am doing
I am running personalNewAccountFromWallet(...) with non-null valid arguments (WalletFile and Password) yet the method throws a NullPointerException. My code is as follows:

ECKeyPair ecKeyPair = Keys.createEcKeyPair();
Credentials credentials = Credentials.create(ecKeyPair);
WalletFile wallet = Wallet.createLight(password, ecKeyPair);
ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
String output =  walletDir + "/" + wallet.getAddress() + ".json";
objectMapper.writeValue(new File(output), wallet);
parity.personalNewAccountFromWallet(wallet, password).send();

I need to know if this is an implementation error on my side or from the tools (web3j or ethereum)

Whether it was my mistake or not, I think the error message could be more helpful..

Class Generator error with public mapping

Hi, I'm using web3j v.1.0.6

I created this test Smart Contract:

pragma solidity ^0.4.2;
contract Test{
    
    enum Status{
        SHIPMENT_CREATED
    }
    
    struct Shipment{
        address sender;
        address receiver;
        uint creationDate;
        uint departureDate;
        Status status;
        uint packageWeight;
        string depot;
        bytes32 receiverHash;
    }
    
    mapping(address => Shipment) public shipments;
}

The ABI of this Smart Contract is:

[
  {
    "constant": true,
    "inputs": [
      {
        "name": "",
        "type": "address"
      }
    ],
    "name": "shipments",
    "outputs": [
      {
        "name": "sender",
        "type": "address"
      },
      {
        "name": "receiver",
        "type": "address"
      },
      {
        "name": "creationDate",
        "type": "uint256"
      },
      {
        "name": "departureDate",
        "type": "uint256"
      },
      {
        "name": "status",
        "type": "uint8"
      },
      {
        "name": "packageWeight",
        "type": "uint256"
      },
      {
        "name": "depot",
        "type": "string"
      },
      {
        "name": "receiverHash",
        "type": "bytes32"
      }
    ],
    "payable": false,
    "type": "function"
  }
]

And the compiled code is:

606060405261015c806100126000396000f3606060405260e060020a6000350463d51cd4ac811461001e575b610002565b3461000257600060208190526004803582526040909120805460018201546002830154600384015494840154600585015460078601546100869773ffffffffffffffffffffffffffffffffffffffff96871697969095169593949360ff909316926006019088565b6040805173ffffffffffffffffffffffffffffffffffffffff808b16825289166020820152908101879052606081018690526080810185905260a0810184905260e0810182905261010060c082018181528454600260018216158402600019019091160491830182905290610120830190859080156101465780601f1061011b57610100808354040283529160200191610146565b820191906000526020600020905b81548152906001019060200180831161012957829003601f168201915b5050995050505050505050505060405180910390f3

The problem is that the class generated is not correct, here is the class:

import java.lang.String;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;
import org.web3j.abi.Contract;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.Utf8String;
import org.web3j.abi.datatypes.generated.Bytes32;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.abi.datatypes.generated.Uint8;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;

/**
 * <p>Auto generated code.<br>
 * <strong>Do not modifiy!</strong><br>
 * Please use {@link org.web3j.codegen.SolidityFunctionWrapperGenerator} to update.</p>
 */
public final class Test extends Contract {
    private static final String BINARY = "606060405261015c806100126000396000f3606060405260e060020a6000350463d51cd4ac811461001e575b610002565b3461000257600060208190526004803582526040909120805460018201546002830154600384015494840154600585015460078601546100869773ffffffffffffffffffffffffffffffffffffffff96871697969095169593949360ff909316926006019088565b6040805173ffffffffffffffffffffffffffffffffffffffff808b16825289166020820152908101879052606081018690526080810185905260a0810184905260e0810182905261010060c082018181528454600260018216158402600019019091160491830182905290610120830190859080156101465780601f1061011b57610100808354040283529160200191610146565b820191906000526020600020905b81548152906001019060200180831161012957829003601f168201915b5050995050505050505050505060405180910390f3";

    private Test(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
        super(contractAddress, web3j, credentials, gasPrice, gasLimit);
    }

    public <T extends Type> Future<List<T>> shipments(Address param0) {
        Function function = new Function<Bytes32>("shipments", 
                Arrays<Type>.asList(param0), 
                Arrays<TypeReference<?>>.asList(new TypeReference<Address>() {}, new TypeReference<Address>() {}, new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}, new TypeReference<Uint8>() {}, new TypeReference<Uint256>() {}, new TypeReference<Utf8String>() {}, new TypeReference<Bytes32>() {}));
        return executeCallMultipleValueReturnAsync(function);
    }

    public static Future<Test> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialValue) {
        return deployAsync(Test.class, web3j, credentials, gasPrice, gasLimit, BINARY, "", initialValue);
    }

    public static Test load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
        return new Test(contractAddress, web3j, credentials, gasPrice, gasLimit);
    }
}

The List of TypeReference is giving error.
This is the part of code that is giving error:
Arrays<Type>.asList(param0), Arrays<TypeReference<?>>.asList(new TypeReference<Address>() {}, new TypeReference<Address>() {}, new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}, new TypeReference<Uint8>() {}, new TypeReference<Uint256>() {}, new TypeReference<Utf8String>() {}, new TypeReference<Bytes32>() {}));

Code generator: return statement in void method

The code generator generates following code:

  public void setGreeting(Utf8String s) throws InterruptedException, ExecutionException {
    Function function = new Function<>("setGreeting", Arrays.asList(s), Collections.emptyList());
    return executeSingleValueReturn(function);
  }

The return statement is not allowed.

Contract

contract hello {
    string greeting;

    function setGreeting(string s){
        greeting = s;
    }

    function getGreeting() constant returns (string s){
        s = greeting;
    }

    function killMe(){
        suicide(msg.sender);
    }
}

ABI

[{
        "constant": false,
        "inputs": [{
                "name": "s",
                "type": "string"
            }],
        "name": "setGreeting",
        "outputs": [],
        "payable": false,
        "type": "function"
    }, {
        "constant": false,
        "inputs": [],
        "name": "killMe",
        "outputs": [],
        "payable": false,
        "type": "function"
    }, {
        "constant": true,
        "inputs": [],
        "name": "getGreeting",
        "outputs": [{
                "name": "s",
                "type": "string"
            }],
        "payable": false,
        "type": "function"
    }]

Thanks for checking this.

Can't send transactions from accounts with less than 17 transactions

Hi Conor,

I am trying to send a Transaction with Credentials. That goes through ManagedTransaction.getNonce(). However, the method fails to get the nonce for a new account that I created. This seems to be because that account doesn't have enough transactions. With 16 TAs RPC returns "0x0f". When I have 17 it works.

I believe the problem is in org.web3j.utils.Numeric line 54:

private static boolean isValidHexQuantity(String value) {
        if (value == null) {
            return false;
        }

        if (value.length() < 3) {
            return false;
        }

        if (!value.startsWith(HEX_PREFIX)) {
            return false;
        }

        if (value.length() > 3 && value.charAt(2) == '0') {
            return false;
        }

        return true;
    }

Nonce calculated without counting pendig tx

Hi,
I'm working with web3j v1.1.2
I created the Smart Contract class from the SolidityFunctionWrapperGenerator.

The problem is that if I call, before a block is mined, more than one time a function that generates a transaction, the nonce is always the same, so only the first transaction will be valid, all the other one will have the same nonce and will be rejected.

The geth client manages this situation calculating the nonce with
getTransactionCount(pending)

In this way, even if you create more than one transaction before a block is mined, all transactions are valid because have an increasing nonce.

I suggest to change the code of the class:
ManagedTransaction and the method getNonce

From:

 protected BigInteger getNonce(String address) throws InterruptedException, ExecutionException {
        EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
                address, DefaultBlockParameterName.LATEST).sendAsync().get();

        return ethGetTransactionCount.getTransactionCount();
    }

To:

 protected BigInteger getNonce(String address) throws InterruptedException, ExecutionException {
        EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
                address, DefaultBlockParameterName.PENDING).sendAsync().get();

        return ethGetTransactionCount.getTransactionCount();
    }

Contract creation uses all gas

I'm using the android library and I try to deploy a simple purchase contract.
purchase.txt
Everything seems to work fine. Contract is created and contract address returned when invoking Contract.deploy() with a gas price of 50000000000 and a gas limit of 4500000.
I noticed that sometimes (~50% of all cases) after deployment, all function calls return null. In these cases all gas is used by the transaction according to the transaction hash, but I don't get any out of gas exception. In the successfull cases, a lot less gas (~500 000) is used.

I'm using geth in dev mode for testing with the following params:
geth --rpc --rpcaddr "0.0.0.0" --rpcport 8545 --rpcapi personal,db,eth,net,web3 --rpccorsdomain="*" -datadir /home/flo/.ethereum/ --dev --gpomin "20000000000" --gpomax "500000000000"

Any ideas what could be the problem?

Smart Contract Wrapper Generation in error with functions with parameters without name

Hi,
I was using web3j (0.5.1) to create the Smart Contract wrapper.
But I have this error:

Exception in thread "main" java.lang.IllegalArgumentException: not a valid name:
at com.squareup.javapoet.Util.checkArgument(Util.java:64)
at com.squareup.javapoet.ParameterSpec.builder(ParameterSpec.java:83)
at com.squareup.javapoet.MethodSpec$Builder.addParameter(MethodSpec.java:379)
at org.web3j.codegen.SolidityFunctionWrapperGenerator.createFunctionDefinitions(SolidityFunctionWrapperGenerator.java:191)
at org.web3j.codegen.SolidityFunctionWrapperGenerator.generateSolidityWrappers(SolidityFunctionWrapperGenerator.java:159)
at org.web3j.codegen.SolidityFunctionWrapperGenerator.generate(SolidityFunctionWrapperGenerator.java:124)
at org.web3j.codegen.SolidityFunctionWrapperGenerator.main(SolidityFunctionWrapperGenerator.java:66)
at com.nttdata.ethereum.marketplace.Test.main(Test.java:26)

I debugged the code, and I noticed that in the ABI there was a function like this:

{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"insuranceWithdraw","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"}

This function is created by Solidity because of I'm using a public map

mapping (address => unit) public insuranceWithdraw;

I think the best thing is to give a default name, with an increasing number.

Add initial value documentation

web3j would benefit from additional information on the initialValue parameter used to define the amount of Ether stored in a smart contract at creation.

TransactionReceipt with Geth 1.5.2 parsing errror

With geth 1.5.2 the getTransactionReceipt is returning:

{
"blockHash": "0xa7b997ddc84692ba0536d4de90a1abf9d4feaba83baf9058c1f1005cd42e8a4c",
"blockNumber": "0x1b",
"contractAddress": "0xaa1395f6afd14c755b11435474f830de2cb41237",
"cumulativeGasUsed": "0x28344a",
"from": "0x810840d715da2af2e2e7f9376ef799cc7ba1cb9e",
"gasUsed": "0x28344a",
"logs": [],
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"root": "0x7b830ae9bbf34b85d3722e510ff1fa397330347975f4928f8d9c496f22257586",
"to": null,
"transactionHash": "0x1a4898dc450ba5a157d3607a42e1368c87c5d73b5067c52f9ceacc0c2784ef4f",
"transactionIndex": "0x0"
}

But the class TransactionReceipt is not matching the logsBloom parameter, so gives Parsing error.

Add support for parity_ JSON-RPC API

The Parity team have renamed a number of personal_ calls to parity. See the parity_accounts-module & parity modules for details.

The existing Parity implementation in web3j should be adapted to accommodate this, so that the existing Parity implementation contains them, and those common Personal module calls should be moved into their own Personal module in web3j that is common to both Geth and Parity.

Decoding multiple return strings error

The code on the bottom should decode the return value of contract function function read(string globalName, uint i) returns (string vid, string pid, string suk, string vuk) as:

def1
ghi1
jkl1
mno2

but shows:

def1
jkl1

Did I miss anything?
Thanks,
Jonathan

List<Type> inputParams=new ArrayList<Type>();
List<TypeReference<?>> outputParams=new ArrayList<TypeReference<?>>();
inputParams.add(new Utf8String("abc"));
inputParams.add(new Uint(BigInteger.valueOf(1)));
 outputParams.add(new TypeReference<Utf8String>() { });
outputParams.add(new TypeReference<Utf8String>() { });
outputParams.add(new TypeReference<Utf8String>() { });
outputParams.add(new TypeReference<Utf8String>() { });
Function function = new Function("read",inputParams,outputParams);
String encodedFunction = FunctionEncoder.encode(function);
System.out.println("encodedFunction: "+encodedFunction);


List<Type> list=FunctionReturnDecoder.decode("0x000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000000464656631000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004676869310000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000046a6b6c310000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000046d6e6f3200000000000000000000000000000000000000000000000000000000", function.getOutputParameters());
System.out.println(list.size());
for(int i=0;i<list.size();i++)
{
            System.out.println(i+":"+((Utf8String)(list.get(i))).getValue().toString());
 }


doc: String responseValue

Hello,

in the doc, chapter 3.2.13 "Querying the state of a smart contract" you are calling the method FunctionReturnDecoder.decode(...) with the String variable "responseValue". However, that variable was never declared nor assigned in the code snippet. Where is that value coming from?

Thanks,
Max

Java 7 support

Hi,

I'd like to use web3j in a Java 7 project. Any chance you have a version without Futures and Observables etc.? Or maybe could point me to an old commit that had a working RPC client but none of that Java 8 goodness?

Otherwise I'll probably have to manually cull the async stuff...

public functions does not have a correct function name

using the command line wrapper generator, the functions for public variables are generated with invalid function name. (this is happening with variables with type array of structs)

Example:

struct Thing {
    string id;
    string name;
}

Thing[]    public things;

the generate function is like:

   Function function = new Function("org.web3j.abi.datatypes.generated.Uint256", 
            Arrays.<Type>asList(param0), 

instead:

    Function function = new Function("things", 
            Arrays.<Type>asList(param0), 

Account creation with custom N, R, P parameters

Hi,
I'm working with Android apps, and the decrypt time for the account is very high.
So i need to create accounts with different N, R, P so it doesn't take that much time.
Is it possible to add a new function in the Wallet class with the possibility to specify these parameters?
Thank you.

Compiling contract inside Java code

I'd like to compile a contract from within the Java code starting with Solidity source code. For this I was looking at your method CoreIT.testEthCompileSolidity and using TestRPC.

@Test
public void testEthCompileSolidity() throws Exception {
	String sourceCode = "pragma solidity ^0.4.0; contract test { function multiply(uint a) returns(uint d) { return a * 7; } }";
	EthCompileSolidity ethCompileSolidity = web3.ethCompileSolidity(sourceCode)
				.send();
	Assert.assertNotNull(ethCompileSolidity.getCompiledSolidity());
	Assert.assertEquals(ethCompileSolidity.getCompiledSolidity().getTest().getInfo().getSource(), sourceCode);
}

unfortunately ethCompileSolidity.getCompiledSolidity() returns null. Testing the same solidity code with curl does produce some meaningful output:

$ curl -X POST --data '{"jsonrpc":"2.0","method":"eth_compileSolidity","params":["pragma solidity ^0.4.0; contract test { function m
ultiply(uint a) returns(uint d) { return a * 7; } }"],"id":1}' 192.168.99.100:8545
{"id":1,"jsonrpc":"2.0","result":{"code":"0x6060604052346000575b60458060156000396000f3606060405260e060020a6000350463c6888fa18114601c575b6000565b346000576029600435603
b565b60408051918252519081900360200190f35b600781025b91905056","info":{"source":"pragma solidity ^0.4.0; contract test { function multiply(uint a) returns(uint d) { re
turn a * 7; } }","language":"Solidity","languageVersion":"0.4.6+commit.2dabbdf0.Emscripten.clang","compilerVersion":"0.4.6+commit.2dabbdf0.Emscripten.clang","abiDefi
nition":[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"payable":false,"type":"function"}],"
userDoc":{"methods":{}},"developerDoc":{"methods":{}}}}}

From this output I conclude that my TestRPC installation does seem to work and must have access to solc as well. So why does the JUnit test fail?

What am I missing?

SolidityFunctionWrapperGenerator creates return statement for void-methods

Hello,

the title basically says it all. SolidityFunctionWrapperGenerator actually checks if outputParameterType.isEmpty() but then creates a return-statement anyways. I believe line 214 needs to be deleted.

Other than that its amazing! So far, I have only tried querying the blockchain, without modifying it, but I am optimistic that I can use web3j in my project, so far it has been nothing but wunderful! :-)

Max

getBlockByNumber() throws Exception

I've just installed geth:
$ geth version Geth Version: 1.5.4-stable Git Commit: b70acf3c5bd335d8dedc2a5aa6eff05c4c32105e Protocol Versions: [63 62] Network Id: 1 Go Version: go1.7.3 OS: linux GOPATH= GOROOT=/usr/lib/go-1.7

web3j 1.0.8

The call web3.ethGetBlockByNumber(DefaultBlockParameter.valueOf(BigInteger.valueOf(1)), true).send() throws exception:

Can not deserialize value of type byte from String "0x1b": not a valid Byte value at [Source: org.apache.http.conn.EofSensorInputStream@18a35f13; line: 1, column: 2024] (through reference chain: org.web3j.protocol.core.methods.response.TransactionObject["v"]) (through reference chain: org.web3j.protocol.core.methods.response.EthBlock["result"]->org.web3j.protocol.core.methods.response.Block["transactions"]) com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize value of type byte from String "0x1b": not a valid Byte value at [Source: org.apache.http.conn.EofSensorInputStream@18a35f13; line: 1, column: 2024] (through reference chain: org.web3j.protocol.core.methods.response.TransactionObject["v"]) (through reference chain: org.web3j.protocol.core.methods.response.EthBlock["result"]->org.web3j.protocol.core.methods.response.Block["transactions"]) at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:379) at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:339) at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.wrapAndThrow(BeanDeserializerBase.java:1589) at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:278) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140) at com.fasterxml.jackson.databind.ObjectReader._bind(ObjectReader.java:1579) at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:961) at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:978) at org.web3j.protocol.core.methods.response.EthBlock$ResponseDeserialiser.deserialize(EthBlock.java:458) at org.web3j.protocol.core.methods.response.EthBlock$ResponseDeserialiser.deserialize(EthBlock.java:449) at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:490) at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95) at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:276) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3789) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2899) at org.web3j.protocol.http.HttpService.lambda$getResponseHandler$9(HttpService.java:91) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:222) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:164) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:139) at org.web3j.protocol.http.HttpService.send(HttpService.java:69) at org.web3j.protocol.core.Request.send(Request.java:68)

I've checked geth rpc itself, it works like a charm

Thank you for advice

Deployed contract doesn't seem to work.

Hi,
I have been working on implementing a simple token contract using web3j, but when it comes to actually deploying the contract by using the generated contract wrappers. I can't seem to mine that transaction properly. I am currently running a private geth 1.5.8 unstable version node, and I can see that a transaction has been put through, but when I check the contract at the address it was generated the transactionhash is null. Even after I confirmed that the block the transaction was part of was mined.
Below is my token deployment
MyToken asset = MyToken.deploy(web3, credentials, BigInteger.valueOf(2000000000), BigInteger.valueOf(9000000), BigInteger.valueOf(420), new Uint256(BigInteger.valueOf(1000000)), new Utf8String("asset"), new Uint8(BigInteger.valueOf(10)), new Utf8String("smt")).get();
where each parameter is:
MyToken.deploy(web3j, credentials, gasPrice, gasLimit, initialValue, initialSupply, tokenName, decimalUnits, tokenSymbol)
respectively.

Here is my geth console output:
Tx(c6143262606f20cc3216a6f2f742890c193c98e4c3ad9a97f8420c5fbbb7dd97) created: 0d0eba273e4f0213773e16602b5a915b36936daf

with eth.getTransaction("0xc6143262606f20cc3216a6f2f742890c193c98e4c3ad9a97f8420c5fbbb7dd97")
giving me:
{
blockHash: "0x7def5bacd197c4abe198f214df89da123d46a76484a449c59c4a2ca2ab79bca3",
blockNumber: 499,
from: "0x0a4a12963693bbf8f5439639a7908c90980c0e8a",
gas: 9000000,
gasPrice: 2000000000,
hash: "0xc6143262606f20cc3216a6f2f742890c193c98e4c3ad9a97f8420c5fbbb7dd97",
input: "0x6060604052604060405190810160405280600981526020017f546f6b656e20302e31000000000000000000000000000000000000000000000081525060009080519060200190828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200008857805160ff1916838001178555620000b9565b82800160010185558215620000b9579182015b82811115620000b85782518255916020019190600101906200009b565b5b509050620000e191905b80821115620000dd576000816000905550600101620000c3565b5090565b5050346200000057604051620014e3380380620014e3833981016040528080519060200190919080518201919060200180519060200190919080518201919050505b33600560006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555083600660003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550836004819055508260019080519060200190828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10620001fd57805160ff19168380011785556200022e565b828001600101855582156200022e579182015b828111156200022d57825182559160200191906001019062000210565b5b5090506200025691905b808211156200025257600081600090555060010162000238565b5090565b50508060029080519060200190828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10620002a657805160ff1916838001178555620002d7565b82800160010185558215620002d7579182015b82811115620002d6578251825591602001919060010190620002b9565b5b509050620002ff91905b80821115620002fb576000816000905550600101620002e1565b5090565b505081600360006101000a81548160ff021916908360ff1602179055505b505050505b6111b180620003326000396000f300606060405236156100ce576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100e0578063095ea7b31461017657806318160ddd146101ca57806323b872dd146101ed578063313ce567146102605780635a3b7e421461028957806370a082311461031f57806379c65068146103665780638da5cb5b146103a257806395d89b41146103f1578063a6f9dae114610487578063a9059cbb146104ba578063cae9ca51146104f6578063dd62ed3e1461058d575b34610000576100de5b610000565b565b005b34610000576100ed6105f3565b604051808060200182810382528381815181526020019150805190602001908083836000831461013c575b80518252602083111561013c57602082019150602081019050602083039250610118565b505050905090810190601f1680156101685780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34610000576101b0600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610691565b604051808215151515815260200191505060405180910390f35b34610000576101d761071f565b6040518082815260200191505060405180910390f35b3461000057610246600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610725565b604051808215151515815260200191505060405180910390f35b346100005761026d610a1e565b604051808260ff1660ff16815260200191505060405180910390f35b3461000057610296610a31565b60405180806020018281038252838181518152602001915080519060200190808383600083146102e5575b8051825260208311156102e5576020820191506020810190506020830392506102c1565b505050905090810190601f1680156103115780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3461000057610350600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610acf565b6040518082815260200191505060405180910390f35b34610000576103a0600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610ae7565b005b34610000576103af610c9e565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34610000576103fe610cc4565b604051808060200182810382528381815181526020019150805190602001908083836000831461044d575b80518252602083111561044d57602082019150602081019050602083039250610429565b505050905090810190601f1680156104795780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34610000576104b8600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610d62565b005b34610000576104f4600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610e03565b005b3461000057610573600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091905050610fe0565b604051808215151515815260200191505060405180910390f35b34610000576105dd600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050611160565b6040518082815260200191505060405180910390f35b60018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156106895780601f1061065e57610100808354040283529160200191610689565b820191906000526020600020905b81548152906001019060200180831161066c57829003601f168201915b505050505081565b600081600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550600190505b92915050565b60045481565b600081600660008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054101561077357610000565b600660008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482600660008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205401101561080057610000565b600760008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482111561088957610000565b81600660008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600660008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555081600760008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b9392505050565b600360009054906101000a900460ff1681565b60008054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610ac75780601f10610a9c57610100808354040283529160200191610ac7565b820191906000526020600020905b815481529060010190602001808311610aaa57829003601f168201915b505050505081565b60066020528060005260406000206000915090505481565b600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515610b4357610000565b80600660008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555080600460008282540192505081905550600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1660007fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a38173ffffffffffffffffffffffffffffffffffffffff16600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35b5050565b600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60028054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610d5a5780601f10610d2f57610100808354040283529160200191610d5a565b820191906000526020600020905b815481529060010190602001808311610d3d57829003601f168201915b505050505081565b600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515610dbe57610000565b80600560006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b50565b80600660003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015610e4f57610000565b600660008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205481600660008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054011015610edc57610000565b80600660003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555080600660008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35b5050565b60006000849050610ff18585610691565b15611157578073ffffffffffffffffffffffffffffffffffffffff16638f4ffcb1338630876040518563ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018481526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001806020018281038252838181518152602001915080519060200190808383600083146110fa575b8051825260208311156110fa576020820191506020810190506020830392506110d6565b505050905090810190601f1680156111265780820380516001836020036101000a031916815260200191505b5095505050505050600060405180830381600087803b156100005760325a03f1156100005750505060019150611158565b5b509392505050565b60076020528160005260406000206020528060005260406000206000915091505054815600a165627a7a7230582033c88a69b67b64d4b2f2b9790d6594cde7b81fd342257c1ee62a3da48e9d32d1002900000000000000000000000000000000000000000000000000000000000f42400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000000561737365740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003736d740000000000000000000000000000000000000000000000000000000000",
nonce: 14,
r: "0xb89b4c90d8f2cd30c7c714bde68dc04659ffe319e28758a5f97452128bae980c",
s: "0x280567341b59e0448b7dd6a6a0fea410166f1465a63d9435732d44b9d79e9d5a",
to: null,
transactionIndex: 0,
v: "0x1c",
value: 420
}
So it looks it was properly mined.
However when I set up eth.contract(MyToken.abi)
to equal my contract instance at the address given above, none of the parameters are returning correctly, and more importantly the transactionhash is null.

Request: Getter for signer address in TransactionManager interface

It would be great if one could get the signer address, so it doesn't have to be stored in multiple places. Getting the address works with the RawTransactionManager of course, through the credentials, but it is not possible from a ClientTransactionManager. At least not in version 2.0.2.

I guess a special accessor directly on ClientTransactionManager would work too but seems a bit clunky, since one of the main uses of the sender address is pre-conditions that guard against sending sure-to-fail transactions (e.g. transactions to permissioned contracts), and those generally depend only on the address and not the transaction method that happen to be used.

Fantastic library btw.

Contract deployments failing with ClientTransactionManager

Contract deployments are failing with the error:

{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"Invalid address length, expected 40 got 2 bytes"}

This is due to the to address field being populated with ""

{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x...","to":"","gas":"0x419ce0","value":"0x0","data":"0x..."]}],"id":1}"

Improving account import

I saw that you are using the Java Scrypt library to calculate the derived key.
I noticed that is not that fast and I found that the Bouncy Castle implementation is better.
Here is the class and method that you can call.

org.bouncycastle.crypto.generators.SCrypt.generate(...)

Hope this can improve the Web3j library.

deploy returning null contract address

Hi there. I just started using web3j, but really great tool!

I'm not sure if my issue is the same as either #51 or #11, but I believe it may be after I have messed around with Gas Limits (higher and lower).

The problem comes when deploying a contract without a constructor, I am getting the following java code output:

    public static Future<DefaultServiceRegistryContract> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialValue) {
        return deployAsync(DefaultServiceRegistryContract.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, "", initialValue);
    }

This may be expected behavior, but I thought I'd ask anyway. Now, this contract is "deployable" in Remix/browser Solidity--i.e., I can create and interact with it. So I'm not sure why the contract address is not returned.

This is frankly a stab in the dark, but I am wondering if the way the binary and constructor is put together in https://github.com/web3j/web3j/blob/master/src/main/java/org/web3j/tx/Contract.java#L233 is affecting how the contract deployment with no parameter constructors (e.g., https://ethereum.stackexchange.com/questions/10862/deploying-contract-with-constructor-arguments-via-geth-rpc).

Thank you for any guidance in advance.

Default Type values

Invoking contract functions with optional parameters (i.e. parameters that may be null, not overloaded functions, which are another issue) could be simplified by providing a zero-arg constructor or public DEFAULT constant.

e.g. I have a contract with the function:

function foo(bytes32 bar) returns (bytes32) {
    if (bar == bytes32(0)) return bar;
    // otherwise do meaningful stuff
    // ...
}

So far I haven't found a better way to invoke this contract using the web3j wrapper with a null value than to do something like this:

byte[] raw = new byte[32];
Arrays.fill(raw, (byte) 0);
contract.foo(new Bytes32(raw));

where I would much prefer something like:

contract.foo(new Bytes32());
// OR
contract.foo(new Bytes32(null));
// OR (my personal preference)
contract.foo(Bytes32.DEFAULT);

I think this will be valuable for a lot situations – if others agree, I'm happy to do the PR; just wanted to make sure it wouldn't be wasted effort before I started.

PS: Optionally, we could also trade some explicit type safety for convenience by teaching the FunctionEncoder to translate null inputParameter values to their Type's DEFAULT, allowing users to do contract.foo(null); but that's likely to be more controversial and would require some changes in the way Type introspection done, which would probably be invasive.

Don't work with parity 1.4.9 after ETC DieHard Fork

After 3000000 ETC block I started receive errors:

 at [Source: org.apache.http.conn.EofSensorInputStream@649b30e; line: 1, column: 3478] (through reference chain: org.web3j.protocol.core.methods.response.EthBlock$TransactionObject["v"]) (through reference chain: org.web3j.protocol.core.methods.response.EthBlock["result"]->org.web3j.protocol.core.methods.response.EthBlock$Block["transactions"])
2017-01-13 20:24:36 [error] s.BlockchainListener - Error fetching next 3000002 block: Error: com.fasterxml.jackson.databind.JsonMappingException: BigInteger out of byte range
 at [Source: org.apache.http.conn.EofSensorInputStream@211c3094; line: 1, column: 3478] (through reference chain: org.web3j.protocol.core.methods.response.EthBlock$TransactionObject["v"]) (through reference chain: org.web3j.protocol.core.methods.response.EthBlock["result"]->org.web3j.protocol.core.methods.response.EthBlock$Block["transactions"])
2017-01-13 20:24:37 [error] s.BlockchainListener - Error fetching next 3000002 block: Error: com.fasterxml.jackson.databind.JsonMappingException: BigInteger out of byte range
 at [Source: org.apache.http.conn.EofSensorInputStream@59da3a9; line: 1, column: 3478] (through reference chain: org.web3j.protocol.core.methods.response.EthBlock$TransactionObject["v"]) (through reference chain: org.web3j.protocol.core.methods.response.EthBlock["result"]->org.web3j.protocol.core.methods.response.EthBlock$Block["transactions"])
2017-01-13 20:24:38 [error] s.BlockchainListener - Error fetching next 3000002 block: Error: com.fasterxml.jackson.databind.JsonMappingException: BigInteger out of byte range
 at [Source: org.apache.http.conn.EofSensorInputStream@dc91bb4; line: 1, column: 3478] (through reference chain: org.web3j.protocol.core.methods.response.EthBlock$TransactionObject["v"]) (through reference chain: org.web3j.protocol.core.methods.response.EthBlock["result"]->org.web3j.protocol.core.methods.response.EthBlock$Block["transactions"])
2017-01-13 20:24:39 [error] s.BlockchainListener - Error fetching next 3000002 block: Error: com.fasterxml.jackson.databind.JsonMappingException: BigInteger out of byte range
 at [Source: org.apache.http.conn.EofSensorInputStream@347d7475; line: 1, column: 3478] (through reference chain: org.web3j.protocol.core.methods.response.EthBlock$TransactionObject["v"]) (through reference chain: org.web3j.protocol.core.methods.response.EthBlock["result"]->org.web3j.protocol.core.methods.response.EthBlock$Block["transactions"])
2017-01-13 20:24:40 [error] s.BlockchainListener - Error fetching next 3000002 block: Error: com.fasterxml.jackson.databind.JsonMappingException: BigInteger out of byte range
 at [Source: org.apache.http.conn.EofSensorInputStream@263600c8; line: 1, column: 3478] (through reference chain: org.web3j.protocol.core.methods.response.EthBlock$TransactionObject["v"]) (through reference chain: org.web3j.protocol.core.methods.response.EthBlock["result"]->org.web3j.protocol.core.methods.response.EthBlock$Block["transactions"])
2017-01-13 20:24:41 [error] s.BlockchainListener - Error fetching next 3000002 block: Error: com.fasterxml.jackson.databind.JsonMappingException: BigInteger out of byte range
 at [Source: org.apache.http.conn.EofSensorInputStream@156614aa; line: 1, column: 3478] (through reference chain: org.web3j.protocol.core.methods.response.EthBlock$TransactionObject["v"]) (through reference chain: org.web3j.protocol.core.methods.response.EthBlock["result"]->org.web3j.protocol.core.methods.response.EthBlock$Block["transactions"])
2017-01-13 20:24:42 [error] s.BlockchainListener - Error fetching next 3000002 block: Error: com.fasterxml.jackson.databind.JsonMappingException: BigInteger out of byte range
 at [Source: org.apache.http.conn.EofSensorInputStream@745f91bf; line: 1, column: 3478] (through reference chain: org.web3j.protocol.core.methods.response.EthBlock$TransactionObject["v"]) (through reference chain: org.web3j.protocol.core.methods.response.EthBlock["result"]->org.web3j.protocol.core.methods.response.EthBlock$Block["transactions"])

Before Die Hard Fork all was OK.

Android Ethereum Node

Hi @conor10. Thanks for this amazing library.

I have a question. This isn't a light node designed to be run on Android devices, right? You will need to connect to a centralized node hosted in some remote server.

Thanks.

Calls on contract hang after event subscription

Hello,
I'm using the Android library v2.1 and I want to subscribe to events on a contract and notify observers when the contract state changes.
I'm deriving from the Contract base class and have a static deploy method from which I call the "registerContractEvents" method before I return the contract object. After the subscription, no interactions (calls/transactions) with the contract are possible anymore. The calling thread is blocked indefinitely.
I have tested this code successfully with the Java8 library. So this problem occurs only with the android library.

protected void registerContractEvents() {
    Event event = new Event("purchaseConfirmed", new ArrayList<TypeReference<?>>(), new ArrayList<TypeReference<?>>());
    registerEvent(event);
    event = new Event("aborted", new ArrayList<TypeReference<?>>(), new ArrayList<TypeReference<?>>());
    registerEvent(event);
    event = new Event("itemReceived", new ArrayList<TypeReference<?>>(), new ArrayList<TypeReference<?>>());
    registerEvent(event);
}

private void registerEvent(final Event event)
{
    String encodedEventSignature = EventEncoder.encode(event);
    EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, getContractAddress()).addSingleTopic(encodedEventSignature);

    //After this subscription no calls/transactions on the contracts are possible anymore
    Subscription observable = web3j.ethLogObservable(filter).subscribe(
            new Action1<Log>() {
                @Override
                public void call(Log log) {
                    notifyObservers(event.getName(), null);
                }
            });
}

Found processing completed slower than mining completed (mining done = 30ms vs. web3j done processing= 10s++)

Are there any part of the code holding the response even the mining already done? (the block is created, and the value is already updated, somehow the response not received, and keep processing for 10s)

We created our own Ethereum custom network and tune it to be pretty fast in mining.
What we found during the poc & comparison between web3.js & web3.j is:

  1. Submit request by both method (modify a value in the hashmap and print out the value get directly from the hashmap)
  2. The mining done less than a sec > the block has been created successfully
  3. The mining stopped

web3.js = the value is modified, response received, and printed to the console less than a sec. it can handled quite some concurrent since it processed quite fast even sometimes the printed value operation faster than the mining

web3.j = once the transaction submitted, it seems like the response is hold (the value already changed, somehow it doesn't stop processing). At some point of concurrent, the memory consumption is very high and out of mem.

I think I might do something wrong at some point. Please suggest. Thanks in advance.

This is some part of t he code:

public void addCoin(long who, long value) throws Exception{
try {
TransactionReceipt result = wowClient.addCoin(new Uint256(BigInteger.valueOf(who)), new Uint256(BigInteger.valueOf(value))).get();
EventValues event = wowClient.processPrint2Event(result);
System.out.println(event.getNonIndexedValues().get(0).getValue());
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Android library is impossible to use due to apache httpclient incompatibility

Android studio gives me:
Warning:WARNING: Dependency org.apache.httpcomponents:httpclient:4.5.2 is ignored for debug as it may be conflicting with the internal version provided by Android.

At runtime app throws

Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/impl/client/HttpClients;
at org.web3j.protocol.http.HttpService.(HttpService.java:47)
at org.vikulin.etherwallet.DrawerActivity.onClick(DrawerActivity.java:131)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5637) 
at android.view.View$PerformClick.run(View.java:22429) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
E/AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.impl.client.HttpClients" on path: DexPathList

Sign.signedMessageToKey() can't be called because the Sign.SignatureData class is not public.

I looked around but couldn't find any way to create instances of SignatureData - could have missed it though.

Use case:

I like to use crypto utilities but I always do Ethereum signatures through RPC/IPC calls to the client (eth_sign); that way the private keys never have to leave the clients secure boundaries. To utilize signedMessageToKey I have to be able to create instances of SignatureData though.

There is no RPC binding for doing ecrecover through the client. Being able to call this function, either by creating a SignatureData object manually or if there is an overloaded version which takes a string, would be great.

Support for checksum addresses

EIP-55 provides an implementation of checksum addresses for Ethereum. This would add an optional additional layer of Ethereum address validation for users of web3j. The following post from the Golem team highlights why this is important.

ChecksumAddress could be implemented as a subclass as the Address class.

Code generation of function calls for non constants

Scenario:

You want to use call a contract function that is not a constant, which you may or not have control of it, but the function call is not declared as constant.

If using the wrapper service, you will be forced to modified the wrapper and / or create a different class.

send transaction to geth 1.4.17 get rlp decodeError

client:goClient geth-1.4.17
web3j:web3j-1.0.9
when I send transaction to geth rpc, I got follow Error:
java.lang.RuntimeException: Error processing transaction request: rlp: non-canonical integer (leading zero bytes) for *big.Int, decoding into (types.Transaction)(types.txdata).S
at org.web3j.abi.ManagedTransaction.signAndSend(ManagedTransaction.java:87)
at org.web3j.abi.Transfer.send(Transfer.java:75)
at org.web3j.abi.Transfer.sendFunds(Transfer.java:106)
at com.neusoft.ethereum.client.testcase.TransferThread.transfer(TransferTestCase.java:106)
at com.neusoft.ethereum.client.testcase.TransferThread.call(TransferTestCase.java:128)
at com.neusoft.ethereum.client.testcase.TransferThread.call(TransferTestCase.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
this error has a certain probability of occurrence,i find the problem is web3js signatureData encoding format is dfferent from the geth txdata struct geth-1.4.17 txdata struct is type txdata sturct { ... V type R, S *big.Int } but we3js code is:
if (signatureData != null) {
result.add(RlpString.create(signatureData.getV()));
result.add(RlpString.create(signatureData.getR()));//FIX ME here shoud be bigInteger not byte[]
result.add(RlpString.create(signatureData.getS()));//FIX ME here shoud be bigInteger not byte[]
}

Android: ParameterizedTypeImpl not found

In the android library, I get the exception:
java.lang.NoClassDefFoundError: Failed resolution of: Lsun/reflect/generics/reflectiveObjects/ParameterizedTypeImpl in the class "org.web3j.abi.TypeReference"

It seems that the class does not reference the correct implementation of "ParameterizedType". I think the correct class in android is "libcore.reflect.ParameterizedTypeImpl"

Best regards

How do I pass bytes32 to a solidity function call?

I create a Bytes32 instance this way:

new org.web3j.abi.datatypes.generated.Bytes32(hash.getBytes())

But I am getting this exception

input byte array must be in range 0 < M <= 32 and length must match type

My solidity function is of this type

function hasProof(bytes32 proof) constant returns (bool) {}

muti thread request Transaction Problem

hi , i try use muti thread send Transaction to geth rpc use web3j like follow:
Thread1 Account1 send 1 ether to Account2
Thread2 Account1 send 1 ether to Account2
when these finished i want Account2`s balance increase 2 ether

but real is sometimes i got a error
java.lang.RuntimeException: Error processing transaction request: Known transaction: 2c3868f5
at org.web3j.abi.ManagedTransaction.signAndSend(ManagedTransaction.java:86)
at org.web3j.abi.Transfer.send(Transfer.java:75)
at org.web3j.abi.Transfer.sendFunds(Transfer.java:106)
at com.neusoft.ethereum.client.testcase.TransferThread.transfer(TransferTestCase.java:112)
at com.neusoft.ethereum.client.testcase.TransferThread.call(TransferTestCase.java:134)
at com.neusoft.ethereum.client.testcase.TransferThread.call(TransferTestCase.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

,and sometime Account2s balance increase only 1 ether i find when you start 2 thread in a few seconds the Transactions nonce is same,this may case error or Transaction Overriding!!
what can i do with this problem?
is that means Transaction must ecuted serially?
testcase.zip

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.