WEB3J Development Ethereum Smart Contract QuickStart (especially for Java and Android developers)

Source: Internet
Author: User

WEB3J Introduction

WEB3J is a lightweight, highly modular, responsive, type-safe Java and Android class library that provides a rich API for processing Ethereum smart contracts and integrating with clients (nodes) on the Ethereum network.

It enables the development of ethereum blockchain without the need to write integration code for your application platform.

You can quickly start the Dmeo sample

To get started quickly, there is a WEB3J Demo sample project available that demonstrates many of the core features of the Ethereum development through WEB3J, including:

    • Connect to a node on an Ethernet network
    • Loading an ethereum wallet file
    • Send an Ethernet token from one address to another
    • Deploy smart contracts to the network
    • Reading values from a deployed smart contract
    • Update values in a deployed smart contract
    • View events recorded by a smart contract
Introduction to WEB3J Development

First install the latest version of WEB3J into your project.

Maven

Java 8:

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

Android:

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

Java 8:

compile (‘org.web3j:core:3.4.0‘)

Android:

compile (‘org.web3j:core:3.3.1-android‘)
Start the client

You need to start an Ethereum client, of course, if you've already started it, you don't need to start it again.

If it's geth, start it up like this:

$ geth --rpcapi personal,db,eth,net,web3 --rpc --rinkeby

If it is parity boot:

$ parity --chain testnet

If you use the free cloud service provided by the Infura client, this starts:

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

If you want to learn more about Infura, see Using Infura with WEB3J.

How to obtain the relevant documents of the ETHERIC currency on the network can be seen in this: testnet section of the docs.

When a web3j instance is not required, the method needs to be called shutdown to free the resources it uses.

web3.shutdown()
Send Request

Send a sync request

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

Send an asynchronous request using Completablefuture (future on Android)

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

* use Rxjava's observable

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

Note how Android is used

Web3j web3 = Web3jFactory.build(new HttpService());  // defaults to http://localhost:8545/...
Ipc

WEB3J also supports the fast running of interprocess communication (IPC) via file sockets, enabling clients to run WEB3J concurrently on the same host. When you create a service, you can use the relevant to IPCService implement it without having to pass HTTPService .

// OS X/Linux/Unix:Web3j web3 = Web3j.build(new UnixIpcService("/path/to/socketfile"));...// WindowsWeb3j web3 = Web3j.build(new WindowsIpcService("/path/to/namedpipefile"));...

Note: IPC communication is not available in web3j-android.

Packaging Ethereum Smart Contracts via Java

WEB3J can automatically package smart contract codes to enable Ethereum Smart contract deployment and interaction without leaving the JVM.

To package the code, you need to compile the smart contract first:

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

Then use the WEB3J command-line tool to package the code:

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

Next, you can create and deploy smart contracts:

Web3j web3 = Web3j.build(new HttpService());  // defaults to http://localhost:8545/Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");YourSmartContract contract = YourSmartContract.deploy(        <web3j>, <credentials>,        GAS_PRICE, GAS_LIMIT,        <param1>, ..., <paramN>).send();  // constructor params

Or use an existing smart contract:

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

Then you can interact with the smart contract:

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

Call the Smart contract:

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

More information on packaging can be seen here: solidity Smart contract wrappers

Filters

WEB3J's responsive function allows the observer to notify the Subscriber of the message through the event that it becomes simple and can be recorded in the blockchain. Receive all new chunks and add them to the blockchain:

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

Receive all new transactions and add them to the blockchain:

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

Receive all transactions that have been submitted to the network for processing. (They are uniformly assigned to a block before.) )

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

Or you can reset all chunks to the newest location, and you'll be notified when a new block is created.

Subscription subscription = catchUpToLatestAndSubscribeToNewBlocksObservable(        <startBlockNumber>, <fullTxObjects>)        .subscribe(block -> {            ...});

topic filtering is also supported:

EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST,        DefaultBlockParameterName.LATEST, <contract-address>)             .addSingleTopic(...)|.addOptionalTopics(..., ...)|...;web3j.ethLogObservable(filter).subscribe(log -> {    ...});

The subscription should also be canceled when it is no longer needed:

subscription.unsubscribe();

Note: Filters is not supported in Infura.

To learn more about filters and events, you can view the interfaces of filters and event and Web3jrx.

Transaction

WEB3J supports the use of Ethereum wallet files (recommended) and the Ethereum Client management commands for sending transactions.

Use an Ethernet wallet file to send the etheric coin to someone else:

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

Or you want to build your own custom-made deals:

Web3j web3 = Web3j.build(new HttpService());  // defaults to http://localhost:8545/Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");// get the next available nonceEthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(             address, DefaultBlockParameterName.LATEST).send();BigInteger nonce = ethGetTransactionCount.getTransactionCount();// create our transactionRawTransaction rawTransaction  = RawTransaction.createEtherTransaction(             nonce, <gas price>, <gas limit>, <toAddress>, <value>);// sign & send our transactionbyte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);String hexValue = Numeric.toHexString(signedMessage);EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).send();// ...

It's much easier to trade with WEB3J's transfer for the ether currency.

Use the management commands of the Ethereum client (if your wallet key is already stored on the client):

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

If you want to use Parity's Personal or Trace functionality, or Geth ' s Personal client APIs, you can use the org.web3j:parity and org.web3j:geth modules.

Command-line tools

The WEB3J jar package provides a command-line tool for each version. Command-line tools allow you to use some of the web3j features directly from some commands:

    • Wallet Creation
    • Wallet Password Management
    • Money transferred from purse to another
    • Solidity Smart Contract feature packaging

Refer to the documentation for further information about the command line.

The other details

Java8 Bulid:

    • WEB3J provides secure access to all response types. Optional or NULL response is supported in Java 8.
    • The asynchronous request package is in a Java 8 completablefutures. WEB3J provides a packaging tool around all asynchronous requests to ensure that any exceptions can be caught during execution, and not just discarded. Because there are many exceptions that are missing support in a full check, these exceptions are usually identified as undetected exceptions, causing problems with the detection process. For more information, see Async.run () and its associated test.

Android version in Java 8:

    • The number of packages returned as Bigintegers. For simple results, you can Response.getResult() obtain the number of string types by the result.
    • Native JSON packets can also be placed in the response by parameters that exist in the Httpservice and Ipcservice classes includeRawResponse .

The Amway web3j tutorial, which focuses on Java and Android apps, is developed through WEB3J for blockchain development, suitable for Java programmers. WEB3J official text of this article please see here: web3j.

WEB3J Development Ethereum Smart Contract QuickStart (especially for Java and Android developers)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.