Git Product home page Git Product logo

webu.java's Introduction

Webuj: Web3 Java HappyUC Ðapp API

Documentation Status Build Status codecov Join the chat at https://gitter.im/Webuj/Webuj

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

https://raw.githubusercontent.com/Webuj/Webuj/master/docs/source/images/webuj_network.png

This allows you to work with the HappyUC 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, HappyUC and Webuj.

Features

  • Complete implementation of HappyUC's JSON-RPC client API over HTTP and IPC
  • HappyUC wallet support
  • Auto-generation of Java smart contract wrappers to create, deploy, transact with and call smart contracts from native Java code (Solidity and Truffle definition formats supported)
  • Reactive-functional API for working with filters
  • HappyUC Name Service (ENS) support
  • Support for Parity's Personal, and Ghuc's Personal client APIs
  • Support for Infura, so you don't have to run an HappyUC client yourself
  • Comprehensive integration tests demonstrating a number of the above scenarios
  • Command line tools
  • Android compatible
  • Support for JP Morgan's Quorum via Webuj-quorum

It has five runtime dependencies:

It also uses JavaPoet for generating smart contract wrappers.

Full project documentation is available at docs.Webuj.io.

Donate

You can help fund the development of Webuj by donating to the following wallet addresses:

Commercial support and training

Commercial support and training is available from blk.io.

Quickstart

A Webuj sample project is available that demonstrates a number of core features of HappyUC with Webuj, including:

  • Connecting to a node on the HappyUC network
  • Loading an HappyUC wallet file
  • Sending Huc from one address to another
  • Deploying a smart contract to the network
  • Reading a value from the deployed smart contract
  • Updating a value in the deployed smart contract
  • Viewing an event logged by the smart contract

Getting started

Add the relevant dependency to your project:

Maven

Java 8:

<dependency>
  <groupId>org.Webuj</groupId>
  <artifactId>core</artifactId>
  <version>3.3.1</version>
</dependency>

Android:

<dependency>
  <groupId>org.Webuj</groupId>
  <artifactId>core</artifactId>
  <version>3.3.1-android</version>
</dependency>

Gradle

Java 8:

compile ('org.Webuj:core:3.3.1')

Android:

compile ('org.Webuj:core:3.3.1-android')

Start a client

Start up an HappyUC client if you don't already have one running, such as Ghuc:

$ ghuc --rpcapi personal,db,huc,net,web3 --rpc --testnet

Or Parity:

$ parity --chain testnet

Or use Infura, which provides free clients running in the cloud:

Webuj web3 = Webuj.build(new HttpService("https://ropsten.infura.io/your-token"));

For further information refer to Using Infura with Webuj

Instructions on obtaining Huc to transact on the network can be found in the testnet section of the docs.

Start sending requests

To send synchronous requests:

Webuj web3 = Webuj.build(new HttpService());  // defaults to http://localhost:8545/
Web3ClientVersion webuClientVersion = web3.webuClientVersion().send();
String clientVersion = webuClientVersion.getWeb3ClientVersion();

To send asynchronous requests using a CompletableFuture (Future on Android):

Webuj web3 = Webuj.build(new HttpService());  // defaults to http://localhost:8545/
Web3ClientVersion webuClientVersion = web3.webuClientVersion().sendAsync().get();
String clientVersion = webuClientVersion.getWeb3ClientVersion();

To use an RxJava Observable:

Webuj web3 = Webuj.build(new HttpService());  // defaults to http://localhost:8545/
web3.webuClientVersion().observable().subscribe(x -> {
    String clientVersion = x.getWeb3ClientVersion();
    ...
});

Note: for Android use:

Webuj web3 = webujFactory.build(new HttpService());  // defaults to http://localhost:8545/
...

IPC

Webuj also supports fast inter-process communication (IPC) via file sockets to clients running on the same host as Webuj. To connect simply use the relevant IpcService implementation instead of HttpService when you create your service:

// OS X/Linux/Unix:
Webuj web3 = Webuj.build(new UnixIpcService("/path/to/socketfile"));
...

// Windows
Webuj web3 = Webuj.build(new WindowsIpcService("/path/to/namedpipefile"));
...

Note: IPC is not currently available on Webuj-android.

Working with smart contracts with Java smart contract wrappers

Webuj can auto-generate smart contract wrapper code to deploy and interact with smart contracts without leaving the JVM.

To generate the wrapper code, compile your smart contract:

$ solc <contract>.sol --bin --abi --optimize -o <output-dir>/

Then generate the wrapper code using Webuj's Command line tools:

Webuj solidity generate /path/to/<smart-contract>.bin /path/to/<smart-contract>.abi -o /path/to/src/main/java -p com.your.organisation.name

Now you can create and deploy your smart contract:

Webuj web3 = Webuj.build(new HttpService());  // defaults to http://localhost:8545/
Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");

YourSmartContract contract = YourSmartContract.deploy(
        <Webuj>, <credentials>,
        GAS_PRICE, GAS_LIMIT,
        <param1>, ..., <paramN>).send();  // constructor params

Alternatively, if you use Truffle, you can make use of its .json output files:

# Inside your Truffle project
$ truffle compile
$ truffle deploy

Then generate the wrapper code using Webuj's Command line tools:

$ cd /path/to/your/Webuj/java/project
$ Webuj truffle generate /path/to/<truffle-smart-contract-output>.json -o /path/to/src/main/java -p com.your.organisation.name

Whether using Truffle or solc directly, either way you get a ready-to-use Java wrapper for your contract.

So, to use an existing contract:

YourSmartContract contract = YourSmartContract.load(
        "0x<address>|<ensName>", <Webuj>, <credentials>, GAS_PRICE, GAS_LIMIT);

To transact with a smart contract:

TransactionReceipt repTransactionReceipt = contract.someMethod(
             <param1>,
             ...).send();

To call a smart contract:

Type result = contract.someMethod(<param1>, ...).send();

For more information refer to Smart Contracts.

Filters

Webuj functional-reactive nature makes it really simple to setup observers that notify subscribers of events taking place on the blockchain.

To receive all new blocks as they are added to the blockchain:

Subscription subscription = Webuj.blockObservable(false).subscribe(block -> {
    ...
});

To receive all new transactions as they are added to the blockchain:

Subscription subscription = Webuj.transactionObservable().subscribe(tx -> {
    ...
});

To receive all pending transactions as they are submitted to the network (i.e. before they have been grouped into a block together):

Subscription subscription = Webuj.pendingTransactionObservable().subscribe(tx -> {
    ...
});

Or, if you'd rather replay all blocks to the most current, and be notified of new subsequent blocks being created:

There are a number of other reqTransaction and block replay Observables described in the docs.

Topic filters are also supported:

HucFilter filter = new HucFilter(DefaultBlockParameterName.EARLIEST,
        DefaultBlockParameterName.LATEST, <contract-address>)
             .addSingleTopic(...)|.addOptionalTopics(..., ...)|...;
Webuj.hucLogObservable(filter).subscribe(log -> {
    ...
});

Subscriptions should always be cancelled when no longer required:

subscription.unsubscribe();

Note: filters are not supported on Infura.

For further information refer to Filters and Events and the webujRx interface.

Transactions

Webuj provides support for both working with HappyUC wallet files (recommended) and HappyUC client admin commands for sending transactions.

Create my wallet

String filePath = Environment.getExternalStorageDirectory().toString() + "/MyWallet";
String fileName = WalletUtils.generateNewWalletFile("123456",new File(filePath),false);
Credentials credentials = WalletUtils.loadCredentials("123456", filePath+"/"+fileName);

To send Huc to another party using your HappyUC wallet file:

Webuj web3 = Webuj.build(new HttpService());  // defaults to http://localhost:8545/
Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");
TransactionReceipt repTransactionReceipt = Transfer.sendFunds(
        web3, credentials, "0x<address>|<ensName>",
        BigDecimal.valueOf(1.0), Convert.Unit.HUC)
        .send();

Or if you wish to create your own custom reqTransaction:

Webuj web3 = Webuj.build(new HttpService());  // defaults to http://localhost:8545/
Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");

// get the next available nonce
HucGetTransactionCount hucGetRepTransactionCount = Webuj.hucGetRepTransactionCount(
             address, DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger nonce = hucGetRepTransactionCount.getTransactionCount();

// create our reqTransaction
RawTransaction rawTransaction  = RawTransaction.createHucTransaction(
             nonce, <gas price>, <gas limit>, <toAddress>, <value>);

// sign & send our reqTransaction
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Hex.toHexString(signedMessage);
HucSendTransaction hucSendRepTransaction = Webuj.hucSendRawRepTransaction(hexValue).send();
// ...

Although it's far simpler using Webuj's Transfer for transacting with Huc.

Using an HappyUC client's admin commands (make sure you have your wallet in the client's keystore):

Admin Webuj = Admin.build(new HttpService());  // defaults to http://localhost:8545/
PersonalUnlockAccount personalUnlockAccount = Webuj.personalUnlockAccount("0x000...", "a password").sendAsync().get();
if (personalUnlockAccount.accountUnlocked()) {
    // send a reqTransaction
}

If you want to make use of Parity's Personal or Trace, or Ghuc's Personal client APIs, you can use the org.Webuj:parity and org.Webuj:ghuc modules respectively.

Command line tools

A Webuj fat jar is distributed with each release providing command line tools. The command line tools allow you to use some of the functionality of Webuj from the command line:

  • Wallet creation
  • Wallet password management
  • Transfer of funds from one wallet to another
  • Generate Solidity smart contract function wrappers

Please refer to the documentation for further information.

Further details

In the Java 8 build:

  • Webuj provides type safe access to all responses. Optional or null responses are wrapped in Java 8's Optional type.
  • Asynchronous requests are wrapped in a Java 8 CompletableFutures. Webuj provides a wrapper around all async requests to ensure that any exceptions during execution will be captured rather then silently discarded. This is due to the lack of support in CompletableFutures for checked exceptions, which are often rethrown as unchecked exception causing problems with detection. See the Async.run() and its associated test for details.

In both the Java 8 and Android builds:

  • Quantity payload types are returned as BigIntegers. For simple results, you can obtain the quantity as a String via Response.getResult().
  • It's also possible to include the raw JSON payload in responses via the includeRawResponse parameter, present in the HttpService and IpcService classes.

Tested clients

  • Ghuc
  • Parity

You can run the integration test class CoreIT to verify clients.

Related projects

For a .NET implementation, check out Nhappyuc.

For a pure Java implementation of the HappyUC client, check out HappyUCJ and HappyUC Harmony.

Projects using Webuj

Please submit a pull request if you wish to include your project on the list:

Companies using Webuj

Please submit a pull request if you wish to include your company on the list:

Build instructions

Webuj includes integration tests for running against a live HappyUC 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:

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

Thanks and credits

  • The Nhappyuc project for the inspiration
  • Othera for the great things they are building on the platform
  • Finhaus guys for putting me onto Nhappyuc
  • bitcoinj for the reference Elliptic Curve crypto implementation
  • Everyone involved in the HappyUC project and its surrounding ecosystem
  • And of course the users of the library, who've provided valuable input & feedback

webu.java's People

Contributors

conor10 avatar eepstein avatar ldcc avatar fcorneli avatar iikirilov avatar yuriymyronovych avatar xaviarias avatar tramonex-nate avatar mushketyk avatar alimate avatar jaycarey avatar nickfitton avatar joanesespanol avatar fooock avatar fergarrui avatar clowdrgn avatar matthewleon avatar maratsubkhankulov avatar eztierney avatar dukei avatar iongchun avatar the-wastl avatar lethimgo avatar dmi3coder avatar taivokasper avatar bitcoinwarrior1 avatar danieldietrich avatar craigwilliams84 avatar richmerrill68 avatar ligi avatar

Watchers

yiping avatar James Cloos avatar  avatar

Forkers

lethimgo

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.