├── docs ├── requirements.txt ├── source │ ├── _static │ │ └── web3j.png │ ├── images │ │ ├── favicon.ico │ │ ├── infura_cert.png │ │ ├── web3j_network.png │ │ ├── smart_contract.png │ │ ├── web3j_transaction.png │ │ ├── pending_transaction.png │ │ └── transaction_process.png │ ├── companies.rst │ ├── credits.rst │ ├── projects.rst │ ├── development.rst │ ├── links.rst │ ├── modules.rst │ ├── rlp.rst │ ├── management_apis.rst │ ├── abi.rst │ ├── infura.rst │ ├── ens.rst │ ├── index.rst │ ├── command_line.rst │ ├── trouble.rst │ ├── filters.rst │ ├── getting_started.rst │ ├── smart_contracts.rst │ └── transactions.rst ├── quickstart.md ├── watch.sh ├── make.bat └── Makefile └── README.md /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | Sphinx==1.3.6 2 | watchdog==0.8.3 3 | -------------------------------------------------------------------------------- /docs/source/_static/web3j.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethjava/web3j-doc-zh/HEAD/docs/source/_static/web3j.png -------------------------------------------------------------------------------- /docs/source/images/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethjava/web3j-doc-zh/HEAD/docs/source/images/favicon.ico -------------------------------------------------------------------------------- /docs/source/images/infura_cert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethjava/web3j-doc-zh/HEAD/docs/source/images/infura_cert.png -------------------------------------------------------------------------------- /docs/source/images/web3j_network.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethjava/web3j-doc-zh/HEAD/docs/source/images/web3j_network.png -------------------------------------------------------------------------------- /docs/source/images/smart_contract.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethjava/web3j-doc-zh/HEAD/docs/source/images/smart_contract.png -------------------------------------------------------------------------------- /docs/source/images/web3j_transaction.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethjava/web3j-doc-zh/HEAD/docs/source/images/web3j_transaction.png -------------------------------------------------------------------------------- /docs/source/images/pending_transaction.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethjava/web3j-doc-zh/HEAD/docs/source/images/pending_transaction.png -------------------------------------------------------------------------------- /docs/source/images/transaction_process.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ethjava/web3j-doc-zh/HEAD/docs/source/images/transaction_process.png -------------------------------------------------------------------------------- /docs/quickstart.md: -------------------------------------------------------------------------------- 1 | ## 快速开始(Quickstart) 2 | 一个[web3j示例项目](https://github.com/web3j/sample-project-gradle)可用于展示以太坊带有web3j的许多核心功能,其中包括: 3 | 4 | - 连接到以太坊网络上的节点 5 | - 加载以太坊钱包文件 6 | - 从一个地址发送以太网到另一个地址 7 | - 将智能合约部署到网络 8 | - 从已部署的智能合约中读取值 9 | - 更新已部署的智能合约中的值 10 | - 查看智能合约记录的事件 11 | -------------------------------------------------------------------------------- /docs/source/companies.rst: -------------------------------------------------------------------------------- 1 | Companies using web3j 2 | ===================== 3 | 4 | - `Amberdata `_ 5 | - `blk.io `_ 6 | - `comitFS `_ 7 | - `ConsenSys `_ 8 | - `ING `_ 9 | - `Othera `_ 10 | - `TrustWallet `_ 11 | -------------------------------------------------------------------------------- /docs/watch.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | command -v watchmedo >/dev/null 2>&1 || { printf >&2 "Please install watch via pip:\npip install watch\n"; exit 1; } 4 | 5 | make clean html 6 | 7 | watchmedo shell-command \ 8 | --patterns='*.rst;*.py' \ 9 | --ignore-pattern='_build/*' \ 10 | --recursive \ 11 | --command='make html' \ 12 | --wait \ 13 | source 14 | 15 | -------------------------------------------------------------------------------- /docs/source/credits.rst: -------------------------------------------------------------------------------- 1 | Thanks and Credits 2 | ================== 3 | 4 | - The `Nethereum `_ project for the inspiration 5 | - `Othera `_ for the great things they are building on the platform 6 | - `Finhaus `_ guys for putting me onto Nethereum 7 | - `bitcoinj `_ for the reference Elliptic Curve crypto implementation 8 | - Everyone involved in the Ethererum project and its surrounding ecosystem 9 | - And of course the users of the library, who've provided valuable input & feedback 10 | -------------------------------------------------------------------------------- /docs/source/projects.rst: -------------------------------------------------------------------------------- 1 | Projects using web3j 2 | ==================== 3 | 4 | - `Ether Wallet `_ by 5 | `@vikulin `_ 6 | - `eth-contract-api `_ by 7 | `@adridadou `_ 8 | - `Ethereum Paper Wallet `_ by 9 | `@matthiaszimmermann `_ 10 | - `web3j-scala `_ by 11 | `@mslinn `_ 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # web3j-doc-zh 2 | web3j文档中文翻译 3 | [原文链接](https://docs.web3j.io/) 4 | ## 导航 5 | [快速开始(Quickstart)](https://github.com/ethjava/web3j-doc-zh/tree/master/docs/quickstart.md)
6 | [入门(Getting Started)](https://docs.web3j.io/)
7 | [模块(Modules)](https://docs.web3j.io/)
8 | [交易(Transactions)](https://docs.web3j.io/)
9 | [智能合约(Smart Contracts)](https://docs.web3j.io/)
10 | [二进制接口(Application Binary Interface)](https://docs.web3j.io/)
11 | [递归长度前缀(Recursive Length Prefix)](https://docs.web3j.io/)
12 | [过滤器和事件(Filters and Events)](https://docs.web3j.io/)
13 | [命令行工具(Command Line Tools)](https://docs.web3j.io/)
14 | [管理API(Management APIs)](https://docs.web3j.io/)
15 | [在web3j中使用Infura(Using Infura with web3j)](https://docs.web3j.io/)
16 | [以太坊名称解析服务(Ethereum Name Service)](https://docs.web3j.io/)
17 | [故障排除(Troubleshooting)](https://docs.web3j.io/)
18 | 19 | - [x] 快速开始(Quickstart) -------------------------------------------------------------------------------- /docs/source/development.rst: -------------------------------------------------------------------------------- 1 | Developer Guide 2 | =============== 3 | 4 | Building web3j 5 | -------------- 6 | 7 | web3j includes integration tests for running against a live Ethereum client. If you do not have a 8 | client running, you can exclude their execution as per the below instructions. 9 | 10 | To run a full build (excluding integration tests): 11 | 12 | .. code-block:: bash 13 | 14 | $ ./gradlew check 15 | 16 | 17 | To run the integration tests: 18 | 19 | .. code-block:: bash 20 | 21 | $ ./gradlew -Pintegration-tests=true :integration-tests:test 22 | 23 | 24 | Generating documentation 25 | ------------------------ 26 | 27 | web3j uses the `Sphinx `_ documentation generator. 28 | 29 | All documentation (apart from the project README.md) resides under the 30 | `/docs `_ directory. 31 | 32 | To build a copy of the documentation, from the project root: 33 | 34 | .. code-block:: bash 35 | 36 | $ cd docs 37 | $ make clean html 38 | 39 | Then browse the build documentation via: 40 | 41 | .. code-block:: bash 42 | 43 | $ open build/html/index.html 44 | -------------------------------------------------------------------------------- /docs/source/links.rst: -------------------------------------------------------------------------------- 1 | Links and Useful Resources 2 | ========================== 3 | 4 | - Ethereum `Homestead Documentation `_ 5 | - Ethereum `Wiki `_ 6 | - Ethereum `JSON-RPC specification `_ 7 | - Ethereum `Yellow Paper `_ and 8 | `GitHub `_ repository 9 | - `Homestead `_ docs 10 | - `Solidity `_ docs 11 | - `Layout of variables in storage `_ 12 | - `Ethereum tests `_ contains lots of common tests for clients 13 | - `Etherscan `_ is very useful for exploring blocks and transactions, it also 14 | has a `testnet site `_ 15 | - `Ethstats `_ provides a useful network dashboard. There is also a 16 | dedicated `Parity dashboard `_, 17 | `Rinkeby testnet dashboard `_, and one for the 18 | `Kovan testnet `_. 19 | - `Ethereum reddit `_ 20 | -------------------------------------------------------------------------------- /docs/source/modules.rst: -------------------------------------------------------------------------------- 1 | Modules 2 | ======= 3 | 4 | To provide greater flexibility for developers wishing to work with web3j, the project is made up 5 | of a number of modules. 6 | 7 | In dependency order, they are as follows: 8 | 9 | * utils - Minimal set of utility classes 10 | * rlp - Recursive Length Prefix (RLP) encoders 11 | * abi - Application Binary Interface (ABI) encoders 12 | * crypto - cryptographic library for for transaction signing and key/wallet management in Ethereum 13 | * tuples - Simple tuples library 14 | * core - Much like the previous web3j core artifact without the code generators 15 | * codegen - code generators 16 | * console - command-line tools 17 | 18 | The below modules only depend on the core module. 19 | 20 | * geth - Geth specific JSON-RPC module 21 | * parity - Parity specific JSON-RPC module 22 | * infura - Infura specific HTTP header support 23 | 24 | For most use cases (interacting with the network and smart contracts) the *core* module should be 25 | all you need. The dependencies of the core module are very granular and only likely to be of use 26 | if your project is focussed on a very specific interaction with the Ethereum network (such as 27 | ABI/RLP encoding, transaction signing but not submission, etc). 28 | 29 | All modules are published to both Maven Central and Bintray, with the published artifact names 30 | using the names listed above, i.e.: 31 | 32 | For Java: 33 | org.web3j:: 34 | 35 | For Android: 36 | org.web3j::-android 37 | -------------------------------------------------------------------------------- /docs/source/rlp.rst: -------------------------------------------------------------------------------- 1 | Recursive Length Prefix 2 | ======================= 3 | 4 | The Recursive Length Prefix (RLP) encoding scheme is a space efficient object serialization scheme 5 | used in Ethereum. 6 | 7 | The specification itself is defined in the `Yellow Paper `_, 8 | and the following page on the `Ethereum Wiki `_. 9 | 10 | 11 | RLP Types 12 | --------- 13 | 14 | The RLP encoder defined two supported types: 15 | 16 | - string 17 | - list 18 | 19 | The list type can be nested an arbitrary number of times allowing complex data structures to be 20 | encoded. 21 | 22 | 23 | The `RLP module `_ in web3j provides RLP encoding 24 | capabilities, with the 25 | `RlpEncoderTest `_ 26 | demonstrating encoding of a number of different values. 27 | 28 | 29 | Transaction encoding 30 | -------------------- 31 | 32 | Within web3j, RLP encoding is used to encode Ethereum transaction objects into a byte array which 33 | is signed before submission to the network. The transaction types and signing logic are located 34 | within the Crypto module, with the 35 | `TransactionEncoderTest `_ 36 | providing examples of transaction signing and encoding. 37 | 38 | 39 | Dependencies 40 | ------------ 41 | 42 | This is a very lightweight module, with no other dependencies. The hope is that other 43 | projects wishing to work with Ethereum's RLP encoding on the JVM or Android will choose to make 44 | use of this module rather then write their own implementations. 45 | -------------------------------------------------------------------------------- /docs/source/management_apis.rst: -------------------------------------------------------------------------------- 1 | Management APIs 2 | =============== 3 | 4 | In addition to implementing the standard 5 | `JSON-RPC `_ API, Ethereum clients, such as 6 | `Geth `__ and 7 | `Parity `__ provide additional management via JSON-RPC. 8 | 9 | One of the key common pieces of functionality that they provide is the ability to create and 10 | unlock Ethereum accounts for transacting on the network. In Geth and Parity, this is implemented 11 | in their Personal modules, details of which are available below: 12 | 13 | - `Parity `__ 14 | - `Geth `__ 15 | 16 | Support for the personal modules is available in web3j. Those methods that are common to both Geth 17 | and Parity reside in the `Admin `_ module of web3j. 18 | 19 | You can initialise a new web3j connector that supports this module using the factory method:: 20 | 21 | Admin web3j = Admin.build(new HttpService()); // defaults to http://localhost:8545/ 22 | PersonalUnlockAccount personalUnlockAccount = admin.personalUnlockAccount("0x000...", "a password").send(); 23 | if (personalUnlockAccount.accountUnlocked()) { 24 | // send a transaction 25 | } 26 | 27 | For Geth specific methods, you can use the 28 | `Geth `_ 29 | connector, and for Parity you can use the associated 30 | `Parity `_ 31 | connector. The *Parity* connector also provides support for Parity's 32 | `Trace `_ module. These connectors 33 | are available in the web3j *geth* and *parity* modules respectively. 34 | 35 | You can refer to the integration test 36 | `ParityIT `_ 37 | for further examples of working with these APIs. 38 | -------------------------------------------------------------------------------- /docs/source/abi.rst: -------------------------------------------------------------------------------- 1 | Application Binary Interface 2 | ============================ 3 | 4 | The Application Binary Interface (ABI) is a data encoding scheme used in Ethereum for working with 5 | smart contracts. The types defined in the ABI are the same as those you encounter when writing 6 | :doc:`smart_contracts` with Solidity - i.e. *uint8, ..., uint256, int8, ..., int256, bool, string,* 7 | etc. 8 | 9 | The `ABI module `_ in web3j provides full support 10 | for the ABI specification, and includes: 11 | 12 | - Java implementations of all ABI types, including conversion from and to native Java types 13 | - Function and event support 14 | - Plenty of unit tests 15 | 16 | Type mappings 17 | ------------- 18 | 19 | The native Java to ABI type mappings used within web3j are as follows: 20 | 21 | - boolean -> bool 22 | - BigInteger -> uint/int 23 | - byte[] -> bytes 24 | - String -> string and address types 25 | - List<> -> dynamic/static array 26 | 27 | BigInteger types have to be used for numeric types, as numeric types in Ethereum are 256 bit 28 | integer values. 29 | 30 | `Fixed point types `_ 31 | have been defined for Ethereum, but are 32 | `not currently implemented in Solidity `_, 33 | hence web3j does not currently support them (they were provided in versions prior to 34 | 3.x). Once available in Solidity, they will be reintroduced back into the web3j ABI module. 35 | 36 | For more information on using ABI types in Java, refer to :ref:`smart-contract-wrappers`. 37 | 38 | Further details 39 | --------------- 40 | 41 | Please refer to the various 42 | `ABI unit tests `_ 43 | for encoding/decoding examples. 44 | 45 | A full ABI specification is maintained with the 46 | `Solidity documentation `_. 47 | 48 | 49 | Dependencies 50 | ------------ 51 | 52 | This is a very lightweight module, with the only third-party dependency being 53 | `Bouncy Castle `_ for cryptographic hashing 54 | (`Spongy Castle `_ on Android). The hope is that other 55 | projects wishing to work with Ethereum's ABI on the JVM or Android will choose to make use of this 56 | module rather then write their own implementations. 57 | -------------------------------------------------------------------------------- /docs/source/infura.rst: -------------------------------------------------------------------------------- 1 | Using Infura with web3j 2 | ======================= 3 | 4 | Signing up 5 | ---------- 6 | 7 | The `Infura `_ service by `ConsenSys `_, provides 8 | Ethereum clients running in the cloud, so you don't have to run one yourself to work with Ethereum. 9 | 10 | When you sign up to the service you are provided with a token you can use to connect to the 11 | relevant Ethereum network: 12 | 13 | Main Ethereum Network: 14 | https://mainnet.infura.io/ 15 | 16 | Test Ethereum Network (Rinkeby): 17 | https://rinkeby.infura.io/ 18 | 19 | Test Ethereum Network (Kovan): 20 | https://kovan.infura.io/ 21 | 22 | Test Ethereum Network (Ropsten): 23 | https://ropsten.infura.io/ 24 | 25 | 26 | For obtaining ether to use in these networks, you can refer to :ref:`ethereum-testnets` 27 | 28 | 29 | InfuraHttpClient 30 | ---------------- 31 | 32 | The web3j infura module provides an Infura HTTP client 33 | (`InfuraHttpService `_) 34 | which provides support for the Infura specific *Infura-Ethereum-Preferred-Client* header. This 35 | allows you to specify whether you want a Geth or Parity client to respond to your request. You 36 | can create the client just like the regular HTTPClient:: 37 | 38 | Web3j web3 = Web3j.build(new HttpService("https://rinkeby.infura.io/")); 39 | Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send(); 40 | System.out.println(web3ClientVersion.getWeb3ClientVersion()); 41 | 42 | .. code-block:: bash 43 | 44 | Geth/v1.7.2-stable-1db4ecdc/darwin-amd64/go1.9.1 45 | 46 | If you want to test a number of the JSON-RPC calls against Infura, update the integration test 47 | `CoreIT `_ 48 | with your Infura URL & run it. 49 | 50 | For further information, refer to the 51 | `Infura docs `_. 52 | 53 | 54 | Transactions 55 | ------------ 56 | 57 | In order to transact with Infura nodes, you will need to create and sign transactions offline 58 | before sending them, as Infura nodes have no visibility of your encrypted Ethereum key files, which 59 | are required to unlock accounts via the Personal Geth/Parity admin commands. 60 | 61 | Refer to the :ref:`offline-signing` and :doc:`management_apis` sections for further details. 62 | -------------------------------------------------------------------------------- /docs/source/ens.rst: -------------------------------------------------------------------------------- 1 | Ethereum Name Service 2 | ===================== 3 | 4 | The `Ethereum Name Service (ENS) `_ provides a human readable names to 5 | identify addresses on the Ethereum network. It is similar to the internet's domain name service 6 | (DNS) which provides human-readable domain names which are mapped to IP addresses. 7 | 8 | In the case of ENS, the addresses are either wallet or smart contract addresses. 9 | 10 | E.g. instead of using the wallet address *0x19e03255f667bdfd50a32722df860b1eeaf4d635*, you can 11 | use *web3j.eth*. 12 | 13 | 14 | Usage in web3j 15 | -------------- 16 | 17 | You can use ENS names anywhere you wish to transact in web3j. In practice this means, in smart 18 | contract wrappers, when you load them, such as:: 19 | 20 | YourSmartContract contract = YourSmartContract.load( 21 | "0x
|", web3j, credentials, GAS_PRICE, GAS_LIMIT); 22 | 23 | Also, when performing Ether transfers, such as using the command line tools: 24 | 25 | .. code-block:: bash 26 | 27 | $ web3j wallet send 0x
| 28 | 29 | 30 | .. _ens-implementation: 31 | 32 | web3j implementation 33 | -------------------- 34 | 35 | Behind the scenes, whenever you using web3j's transaction managers (which are derived from the 36 | `ManagedTransaction `_ 37 | class), the `EnsResolver `_ 38 | is invoked to perform an ENS lookup if applicable. 39 | 40 | The resolution process is as follows: 41 | 42 | - Check to see if our Ethereum node is fully synced 43 | - If not fail 44 | - If it is synced, check the timestamp on the most recent block it has. 45 | - If it's more than 3 minutes old, fail. 46 | - Otherwise perform the lookup 47 | 48 | If you need to change the threshold parameter of what constitutes being synced to something other 49 | then 3 minutes, this can be done via the *setSyncThreshold* method in the 50 | `ManagedTransaction `_ 51 | class. 52 | 53 | 54 | Unicode Technical Standard (UTS) #46 55 | ------------------------------------ 56 | 57 | `UTS #46 `_ is the standard used to sanitise input on domain names. 58 | The web3j ENS implementation peforms this santisation on all inputs before attempting resolution. 59 | For details of the implementation, refer to the 60 | `NameHash `_ class. 61 | 62 | 63 | Registering domain names 64 | ------------------------ 65 | 66 | Currently, web3j only supports the resolution of ENS domains. It does not support the registration. 67 | For instructions on how to do this, refer to the ENS 68 | `quickstart `_. 69 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. web3j documentation master file 2 | 3 | web3j 4 | ===== 5 | 6 | web3j is a highly modular, reactive, type safe Java and Android library for working with 7 | Smart Contracts and integrating with clients (nodes) on the Ethereum network: 8 | 9 | .. image:: /images/web3j_network.png 10 | 11 | This allows you to work with the `Ethereum `_ blockchain, without the 12 | additional overhead of having to write your own integration code for the platform. 13 | 14 | The `Java and the Blockchain `_ talk provides an 15 | overview of blockchain, Ethereum and web3j. 16 | 17 | 18 | Features 19 | ======== 20 | 21 | - Complete implementation of Ethereum's `JSON-RPC `_ 22 | client API over HTTP and IPC 23 | - Ethereum wallet support 24 | - Auto-generation of Java smart contract wrappers to create, deploy, transact with and call smart 25 | contracts from native Java code 26 | (`Solidity `_ 27 | and 28 | `Truffle `_ definition formats supported) 29 | - Reactive-functional API for working with filters 30 | - `Ethereum Name Service (ENS) `_ support 31 | - Support for Parity's 32 | `Personal `__, and Geth's 33 | `Personal `__ client APIs 34 | - Support for `Infura `_, so you don't have to run an Ethereum client yourself 35 | - Comprehensive integration tests demonstrating a number of the above scenarios 36 | - Command line tools 37 | - Android compatible 38 | - Support for JP Morgan's Quorum via `web3j-quorum `_ 39 | 40 | 41 | Dependencies 42 | ============ 43 | 44 | It has five runtime dependencies: 45 | 46 | - `RxJava `_ for its reactive-functional API 47 | - `OKHttp `_ for HTTP connections 48 | - `Jackson Core `_ for fast JSON 49 | serialisation/deserialisation 50 | - `Bouncy Castle `_ 51 | (`Spongy Castle `_ on Android) for crypto 52 | - `Jnr-unixsocket `_ for \*nix IPC (not available on 53 | Android) 54 | 55 | It also uses `JavaPoet `_ for generating smart contract 56 | wrappers 57 | 58 | 59 | Donate 60 | ====== 61 | 62 | You can help fund the development of web3j by donating to the following wallet addresses: 63 | 64 | +----------+--------------------------------------------+ 65 | | Ethereum | 0x2dfBf35bb7c3c0A466A6C48BEBf3eF7576d3C420 | 66 | +----------+--------------------------------------------+ 67 | | Bitcoin | 1DfUeRWUy4VjekPmmZUNqCjcJBMwsyp61G | 68 | +----------+--------------------------------------------+ 69 | 70 | 71 | Commercial support and training 72 | =============================== 73 | 74 | Commercial support and training is available from `blk.io `_. 75 | 76 | 77 | 78 | Contents: 79 | ========= 80 | 81 | .. toctree:: 82 | :maxdepth: 2 83 | 84 | quickstart.rst 85 | getting_started.rst 86 | modules.rst 87 | transactions.rst 88 | smart_contracts.rst 89 | abi.rst 90 | rlp.rst 91 | filters.rst 92 | command_line.rst 93 | management_apis.rst 94 | infura.rst 95 | ens.rst 96 | trouble.rst 97 | projects.rst 98 | companies.rst 99 | development.rst 100 | links.rst 101 | credits.rst 102 | -------------------------------------------------------------------------------- /docs/source/command_line.rst: -------------------------------------------------------------------------------- 1 | Command Line Tools 2 | ================== 3 | 4 | A web3j fat jar is distributed with each release providing command line tools. The command line 5 | allow you to use some of the functionality of web3j from your terminal: 6 | 7 | These tools provide: 8 | 9 | - Wallet creation 10 | - Wallet password management 11 | - Ether transfer from one wallet to another 12 | - Generation of Solidity smart contract wrappers 13 | 14 | The command line tools can be obtained as a zipfile/tarball from the 15 | `releases `_ page of the project repository, under 16 | the **Downloads** section, or for OS X users via 17 | `Homebrew `_. 18 | 19 | .. code-block:: bash 20 | 21 | brew tap web3j/web3j 22 | brew install web3j 23 | 24 | To run via the zipfile, simply extract the zipfile and run the binary: 25 | 26 | .. code-block:: bash 27 | 28 | $ unzip web3j-.zip 29 | creating: web3j-3.0.0/lib/ 30 | inflating: web3j-3.0.0/lib/core-1.0.2-all.jar 31 | creating: web3j-3.0.0/bin/ 32 | inflating: web3j-3.0.0/bin/web3j 33 | inflating: web3j-3.0.0/bin/web3j.bat 34 | $ ./web3j-/bin/web3j 35 | 36 | _ _____ _ _ 37 | | | |____ (_) (_) 38 | __ _____| |__ / /_ _ ___ 39 | \ \ /\ / / _ \ '_ \ \ \ | | | / _ \ 40 | \ V V / __/ |_) |.___/ / | _ | || (_) | 41 | \_/\_/ \___|_.__/ \____/| |(_)|_| \___/ 42 | _/ | 43 | |__/ 44 | 45 | Usage: web3j version|wallet|solidity ... 46 | 47 | 48 | Wallet tools 49 | ------------ 50 | 51 | To generate a new Ethereum wallet: 52 | 53 | .. code-block:: bash 54 | 55 | $ web3j wallet create 56 | 57 | To update the password for an existing wallet: 58 | 59 | .. code-block:: bash 60 | 61 | $ web3j wallet update 62 | 63 | To send Ether to another address: 64 | 65 | .. code-block:: bash 66 | 67 | $ web3j wallet send 0x
| 68 | 69 | When sending Ether to another address you will be asked a series of questions before the 70 | transaction takes place. See the below for a full example 71 | 72 | The following example demonstrates using web3j to send Ether to another wallet. 73 | 74 | .. code-block:: bash 75 | 76 | $ ./web3j-/bin/web3j wallet send 0x
| 77 | 78 | _ _____ _ _ 79 | | | |____ (_) (_) 80 | __ _____| |__ / /_ _ ___ 81 | \ \ /\ / / _ \ '_ \ \ \ | | | / _ \ 82 | \ V V / __/ |_) |.___/ / | _ | || (_) | 83 | \_/\_/ \___|_.__/ \____/| |(_)|_| \___/ 84 | _/ | 85 | |__/ 86 | 87 | Please enter your existing wallet file password: 88 | Wallet for address 0x19e03255f667bdfd50a32722df860b1eeaf4d635 loaded 89 | Please confirm address of running Ethereum client you wish to send the transfer request to [http://localhost:8545/]: 90 | Connected successfully to client: Geth/v1.4.18-stable-c72f5459/darwin/go1.7.3 91 | What amound would you like to transfer (please enter a numeric value): 0.000001 92 | Please specify the unit (ether, wei, ...) [ether]: 93 | Please confim that you wish to transfer 0.000001 ether (1000000000000 wei) to address 0x9c98e381edc5fe1ac514935f3cc3edaa764cf004 94 | Please type 'yes' to proceed: yes 95 | Commencing transfer (this may take a few minutes)...................................................................................................................$ 96 | 97 | Funds have been successfully transferred from 0x19e03255f667bdfd50a32722df860b1eeaf4d635 to 0x9c98e381edc5fe1ac514935f3cc3edaa764cf004 98 | Transaction hash: 0xb00afc5c2bb92a76d03e17bd3a0175b80609e877cb124c02d19000d529390530 99 | Mined block number: 1849039 100 | 101 | 102 | Solidity smart contract wrapper generator 103 | ------------------------------------------ 104 | 105 | Please refer to :ref:`smart-contract-wrappers`. 106 | -------------------------------------------------------------------------------- /docs/source/trouble.rst: -------------------------------------------------------------------------------- 1 | Troubleshooting 2 | =============== 3 | 4 | Do you have a sample web3j project 5 | ---------------------------------- 6 | 7 | Yes, refer to the web3j sample project outlined in the :doc:`quickstart`. 8 | 9 | 10 | I'm submitting a transaction, but it's not being mined 11 | ------------------------------------------------------ 12 | After creating and sending a transaction, you receive a transaction hash, however calling 13 | `eth_getTransactionReceipt `_ 14 | always returns a blank value, indicating the transaction has not been mined:: 15 | 16 | String transactionHash = sendTransaction(...); 17 | 18 | // you loop through the following expecting to eventually get a receipt once the transaction 19 | // is mined 20 | EthGetTransactionReceipt.TransactionReceipt transactionReceipt = 21 | web3j.ethGetTransactionReceipt(transactionHash).sendAsync().get(); 22 | 23 | if (!transactionReceipt.isPresent()) { 24 | // try again, ad infinitum 25 | } 26 | 27 | However, you never receive a transaction receipt. Unfortunately there may not be a an error 28 | in your Ethereum client indicating any issues with the transaction:: 29 | 30 | I1025 18:13:32.817691 eth/api.go:1185] Tx(0xeaac9aab7f9aeab189acd8714c5a60c7424f86820884b815c4448cfcd4d9fc79) to: 0x9c98e381edc5fe1ac514935f3cc3edaa764cf004 31 | 32 | The easiest way to see if the submission is waiting to mined is to refer to Etherscan 33 | and search for the address the transaction was sent using https://testnet.etherscan.io/address/0x... 34 | If the submission has been successful it should be visible in Etherscan within seconds of you 35 | performing the transaction submission. The wait is for the mining to take place. 36 | 37 | .. image:: /images/pending_transaction.png 38 | 39 | If there is no sign of it then the transaction has vanished into the ether (sorry). The likely 40 | cause of this is likely to be to do with the transaction's nonce either not being set, or 41 | being too low. Please refer to the section :ref:`nonce` for more information. 42 | 43 | 44 | I want to see details of the JSON-RPC requests and responses 45 | ------------------------------------------------------------ 46 | 47 | web3j uses the `SLF4J `_ logging facade, which you can easily integrate 48 | with your preferred logging framework. One lightweight approach is to use 49 | `LOGBack `_, which is already configured in the integration-tests module. 50 | 51 | Include the LOGBack dependencies listed in 52 | `integration-tests/build.gradle `_ 53 | and associated log configuration as per 54 | `integration-tests/src/test/resources/logback-test.xml `_. 55 | 56 | **Note:** if you are configuring logging for an application (not tests), you will need to ensure that 57 | the Logback dependencies are configured as *compile* dependencies, and that the configuration file 58 | is named and located in *src/main/resources/logback.xml*. 59 | 60 | 61 | I want to obtain some Ether on Testnet, but don't want to have to mine it myself 62 | -------------------------------------------------------------------------------- 63 | 64 | Please refer to the :ref:`ethereum-testnets` for how to obtain some Ether. 65 | 66 | 67 | How do I obtain the return value from a smart contract method invoked by a transaction? 68 | --------------------------------------------------------------------------------------- 69 | 70 | You can't. It is not possible to return values from methods on smart contracts that are called as 71 | part of a transaction. If you wish to read a value during a transaction, you must use 72 | `Events `_. To query values 73 | from smart contracts you must use a call, which is separate to a transaction. These methods should 74 | be marked as 75 | `constant `_ 76 | functions. :ref:`smart-contract-wrappers` created by web3j handle these differences for you. 77 | 78 | The following StackExchange 79 | `post `__ 80 | is useful for background. 81 | 82 | 83 | Is it possible to send arbitrary text with transactions? 84 | -------------------------------------------------------- 85 | 86 | Yes it is. Text should be ASCII encoded and provided as a hexadecimal String in the data field 87 | of the transaction. This is demonstrated below:: 88 | 89 | RawTransaction.createTransaction( 90 | , GAS_PRICE, GAS_LIMIT, "0x
", , "0x"); 91 | 92 | byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, ALICE); 93 | String hexValue = Numeric.toHexString(signedMessage); 94 | 95 | EthSendTransaction ethSendTransaction = 96 | web3j.ethSendRawTransaction(hexValue).send(); 97 | String transactionHash = ethSendTransaction.getTransactionHash(); 98 | ... 99 | 100 | *Note*: Please ensure you increase the gas limit on the transaction to allow for the storage of 101 | text. 102 | 103 | The following StackExchange 104 | `post `__ 105 | is useful for background. 106 | 107 | 108 | I've generated my smart contract wrapper, but the binary for the smart contract is empty? 109 | ----------------------------------------------------------------------------------------- 110 | 111 | If you have defined an interface in Solidity, but one of your method implementations doesn't 112 | match the original interface definitions, the produced binary will be blank. 113 | 114 | In the following example:: 115 | 116 | contract Web3jToken is ERC20Basic, Ownable { 117 | ... 118 | function transfer(address _from, address _to, uint256 _value) onlyOwner returns (bool) { 119 | ... 120 | } 121 | 122 | We forgot to define the *from* parameter in one of the inherited contracts:: 123 | 124 | contract ERC20Basic { 125 | ... 126 | function transfer(address to, uint256 value) returns (bool); 127 | ... 128 | } 129 | 130 | The Solidity compiler will not complain about this, however, the produced binary file for the 131 | Web3jToken will be blank. 132 | 133 | 134 | My ENS lookups are failing 135 | -------------------------- 136 | 137 | Are you sure that you are connecting to the correct network to perform the lookup? 138 | 139 | If web3j is telling you that the node is not in sync, you may need to change the *syncThreshold* 140 | in the :ref:`ENS resolver `. 141 | 142 | 143 | Do you have a project donation address? 144 | --------------------------------------- 145 | 146 | Absolutely, you can contribute Bitcoin or Ether to help fund the development of web3j. 147 | 148 | +----------+--------------------------------------------+ 149 | | Ethereum | 0x2dfBf35bb7c3c0A466A6C48BEBf3eF7576d3C420 | 150 | +----------+--------------------------------------------+ 151 | | Bitcoin | 1DfUeRWUy4VjekPmmZUNqCjcJBMwsyp61G | 152 | +----------+--------------------------------------------+ 153 | 154 | 155 | Where can I get commercial support for web3j? 156 | --------------------------------------------- 157 | 158 | Commercial support and training is available from `blk.io `_. 159 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source 10 | set I18NSPHINXOPTS=%SPHINXOPTS% source 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | echo. coverage to run coverage check of the documentation if enabled 41 | goto end 42 | ) 43 | 44 | if "%1" == "clean" ( 45 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 46 | del /q /s %BUILDDIR%\* 47 | goto end 48 | ) 49 | 50 | 51 | REM Check if sphinx-build is available and fallback to Python version if any 52 | %SPHINXBUILD% 1>NUL 2>NUL 53 | if errorlevel 9009 goto sphinx_python 54 | goto sphinx_ok 55 | 56 | :sphinx_python 57 | 58 | set SPHINXBUILD=python -m sphinx.__init__ 59 | %SPHINXBUILD% 2> nul 60 | if errorlevel 9009 ( 61 | echo. 62 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 63 | echo.installed, then set the SPHINXBUILD environment variable to point 64 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 65 | echo.may add the Sphinx directory to PATH. 66 | echo. 67 | echo.If you don't have Sphinx installed, grab it from 68 | echo.http://sphinx-doc.org/ 69 | exit /b 1 70 | ) 71 | 72 | :sphinx_ok 73 | 74 | 75 | if "%1" == "html" ( 76 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 77 | if errorlevel 1 exit /b 1 78 | echo. 79 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 80 | goto end 81 | ) 82 | 83 | if "%1" == "dirhtml" ( 84 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 85 | if errorlevel 1 exit /b 1 86 | echo. 87 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 88 | goto end 89 | ) 90 | 91 | if "%1" == "singlehtml" ( 92 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 93 | if errorlevel 1 exit /b 1 94 | echo. 95 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 96 | goto end 97 | ) 98 | 99 | if "%1" == "pickle" ( 100 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 101 | if errorlevel 1 exit /b 1 102 | echo. 103 | echo.Build finished; now you can process the pickle files. 104 | goto end 105 | ) 106 | 107 | if "%1" == "json" ( 108 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 109 | if errorlevel 1 exit /b 1 110 | echo. 111 | echo.Build finished; now you can process the JSON files. 112 | goto end 113 | ) 114 | 115 | if "%1" == "htmlhelp" ( 116 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 117 | if errorlevel 1 exit /b 1 118 | echo. 119 | echo.Build finished; now you can run HTML Help Workshop with the ^ 120 | .hhp project file in %BUILDDIR%/htmlhelp. 121 | goto end 122 | ) 123 | 124 | if "%1" == "qthelp" ( 125 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 129 | .qhcp project file in %BUILDDIR%/qthelp, like this: 130 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\web3j.qhcp 131 | echo.To view the help file: 132 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\web3j.ghc 133 | goto end 134 | ) 135 | 136 | if "%1" == "devhelp" ( 137 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 138 | if errorlevel 1 exit /b 1 139 | echo. 140 | echo.Build finished. 141 | goto end 142 | ) 143 | 144 | if "%1" == "epub" ( 145 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 146 | if errorlevel 1 exit /b 1 147 | echo. 148 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 149 | goto end 150 | ) 151 | 152 | if "%1" == "latex" ( 153 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 154 | if errorlevel 1 exit /b 1 155 | echo. 156 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 157 | goto end 158 | ) 159 | 160 | if "%1" == "latexpdf" ( 161 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 162 | cd %BUILDDIR%/latex 163 | make all-pdf 164 | cd %~dp0 165 | echo. 166 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdfja" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf-ja 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "text" ( 181 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 182 | if errorlevel 1 exit /b 1 183 | echo. 184 | echo.Build finished. The text files are in %BUILDDIR%/text. 185 | goto end 186 | ) 187 | 188 | if "%1" == "man" ( 189 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 190 | if errorlevel 1 exit /b 1 191 | echo. 192 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 193 | goto end 194 | ) 195 | 196 | if "%1" == "texinfo" ( 197 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 198 | if errorlevel 1 exit /b 1 199 | echo. 200 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 201 | goto end 202 | ) 203 | 204 | if "%1" == "gettext" ( 205 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 206 | if errorlevel 1 exit /b 1 207 | echo. 208 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 209 | goto end 210 | ) 211 | 212 | if "%1" == "changes" ( 213 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 214 | if errorlevel 1 exit /b 1 215 | echo. 216 | echo.The overview file is in %BUILDDIR%/changes. 217 | goto end 218 | ) 219 | 220 | if "%1" == "linkcheck" ( 221 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 222 | if errorlevel 1 exit /b 1 223 | echo. 224 | echo.Link check complete; look for any errors in the above output ^ 225 | or in %BUILDDIR%/linkcheck/output.txt. 226 | goto end 227 | ) 228 | 229 | if "%1" == "doctest" ( 230 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 231 | if errorlevel 1 exit /b 1 232 | echo. 233 | echo.Testing of doctests in the sources finished, look at the ^ 234 | results in %BUILDDIR%/doctest/output.txt. 235 | goto end 236 | ) 237 | 238 | if "%1" == "coverage" ( 239 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 240 | if errorlevel 1 exit /b 1 241 | echo. 242 | echo.Testing of coverage in the sources finished, look at the ^ 243 | results in %BUILDDIR%/coverage/python.txt. 244 | goto end 245 | ) 246 | 247 | if "%1" == "xml" ( 248 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 249 | if errorlevel 1 exit /b 1 250 | echo. 251 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 252 | goto end 253 | ) 254 | 255 | if "%1" == "pseudoxml" ( 256 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 257 | if errorlevel 1 exit /b 1 258 | echo. 259 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 260 | goto end 261 | ) 262 | 263 | :end 264 | -------------------------------------------------------------------------------- /docs/source/filters.rst: -------------------------------------------------------------------------------- 1 | Filters and Events 2 | ================== 3 | 4 | Filters provide notifications of certain events taking place in the Ethereum network. There are 5 | three classes of filter supported in Ethereum: 6 | 7 | #. Block filters 8 | #. Pending transaction filters 9 | #. Topic filters 10 | 11 | Block filters and pending transaction filters provide notification of the creation of new 12 | transactions or blocks on the network. 13 | 14 | Topic filters are more flexible. These allow you to create a filter based on specific criteria 15 | that you provide. 16 | 17 | Unfortunately, unless you are using a WebSocket connection to Geth, working with filters via the 18 | JSON-RPC API is a tedious process, where you need to poll the Ethereum client in order to find out 19 | if there are any updates to your filters due to the synchronous nature of HTTP and IPC requests. 20 | Additionally the block and transaction filters only provide the transaction or block hash, so a 21 | further request is required to obtain the actual transaction or block referred to by the hash. 22 | 23 | web3j's managed `Filter `_ 24 | implementation address these issues, so you have a fully asynchronous event based API for working 25 | with filters. It uses `RxJava `_'s 26 | `Observables `_ which provides a consistent API 27 | for working with events, which facilitates the chaining together of JSON-RPC calls via 28 | functional composition. 29 | 30 | **Note:** filters are not supported on Infura. 31 | 32 | 33 | Block and transaction filters 34 | ----------------------------- 35 | 36 | To receive all new blocks as they are added to the blockchain (the false parameter specifies that 37 | we only want the blocks, not the embedded transactions too):: 38 | 39 | Subscription subscription = web3j.blockObservable(false).subscribe(block -> { 40 | ... 41 | }); 42 | 43 | To receive all new transactions as they are added to the blockchain:: 44 | 45 | Subscription subscription = web3j.transactionObservable().subscribe(tx -> { 46 | ... 47 | }); 48 | 49 | To receive all pending transactions as they are submitted to the network (i.e. before they have 50 | been grouped into a block together):: 51 | 52 | Subscription subscription = web3j.pendingTransactionObservable().subscribe(tx -> { 53 | ... 54 | }); 55 | 56 | Subscriptions should always be cancelled when no longer required via *unsubscribe*:: 57 | 58 | subscription.unsubscribe(); 59 | 60 | Other callbacks are also provided which provide simply the block or transaction hashes, 61 | for details of these refer to the 62 | `Web3jRx `_ 63 | interface. 64 | 65 | 66 | Replay filters 67 | -------------- 68 | 69 | web3j also provides filters for replaying block and transaction history. 70 | 71 | To replay a range of blocks from the blockchain:: 72 | 73 | Subscription subscription = web3j.replayBlocksObservable( 74 | , , ) 75 | .subscribe(block -> { 76 | ... 77 | }); 78 | 79 | To replay the individual transactions contained within a range of blocks:: 80 | 81 | Subscription subscription = web3j.replayTransactionsObservable( 82 | , ) 83 | .subscribe(tx -> { 84 | ... 85 | }); 86 | 87 | You can also get web3j to replay all blocks up to the most current, and provide notification 88 | (via the submitted Observable) once you've caught up:: 89 | 90 | Subscription subscription = web3j.catchUpToLatestBlockObservable( 91 | , , ) 92 | .subscribe(block -> { 93 | ... 94 | }); 95 | 96 | Or, if you'd rather replay all blocks to the most current, then be notified of new subsequent 97 | blocks being created:: 98 | 99 | Subscription subscription = web3j.catchUpToLatestAndSubscribeToNewBlocksObservable( 100 | , ) 101 | .subscribe(block -> { 102 | ... 103 | }); 104 | 105 | As above, but with transactions contained within blocks:: 106 | 107 | Subscription subscription = web3j.catchUpToLatestAndSubscribeToNewTransactionsObservable( 108 | ) 109 | .subscribe(tx -> { 110 | ... 111 | }); 112 | 113 | All of the above filters are exported via the 114 | `Web3jRx `_ 115 | interface. 116 | 117 | 118 | .. _filters-and-events: 119 | 120 | Topic filters and EVM events 121 | ---------------------------- 122 | 123 | Topic filters capture details of Ethereum Virtual Machine (EVM) events taking place in the network. 124 | These events are created by smart contracts and stored in the transaction log associated with a 125 | smart contract. 126 | 127 | The `Solidity documentation `_ 128 | provides a good overview of EVM events. 129 | 130 | You use the 131 | `EthFilter `_ 132 | type to specify the topics that you wish to apply to the filter. This can include the address of 133 | the smart contract you wish to apply the filter to. You can also provide specific topics to filter 134 | on. Where the individual topics represent indexed parameters on the smart contract:: 135 | 136 | EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, 137 | DefaultBlockParameterName.LATEST, ) 138 | [.addSingleTopic(...) | .addOptionalTopics(..., ...) | ...]; 139 | 140 | This filter can then be created using a similar syntax to the block and transaction filters above:: 141 | 142 | web3j.ethLogObservable(filter).subscribe(log -> { 143 | ... 144 | }); 145 | 146 | The filter topics can only refer to the indexed Solidity event parameters. It is not possible to 147 | filter on the non-indexed event parameters. Additionally, for any indexed event parameters that are 148 | variable length array types such as string and bytes, the Keccak-256 hash of their value is stored 149 | on the EVM log. It is not possible to store or filter using their full value. 150 | 151 | If you create a filter instance with no topics associated with it, all EVM events taking place in 152 | the network will be captured by the filter. 153 | 154 | 155 | A note on functional composition 156 | -------------------------------- 157 | 158 | In addition to *send()* and *sendAsync*, all JSON-RPC method implementations in web3j support the 159 | *observable()* method to create an Observable to execute the request asynchronously. This makes it 160 | very straight forwards to compose JSON-RPC calls together into new functions. 161 | 162 | For instance, the 163 | `blockObservable `_ is 164 | itself composed of a number of separate JSON-RPC calls:: 165 | 166 | public Observable blockObservable( 167 | boolean fullTransactionObjects, long pollingInterval) { 168 | return this.ethBlockHashObservable(pollingInterval) 169 | .flatMap(blockHash -> 170 | web3j.ethGetBlockByHash(blockHash, fullTransactionObjects).observable()); 171 | } 172 | 173 | Here we first create an observable that provides notifications of the block hash of each newly 174 | created block. We then use *flatMap* to invoke a call to *ethGetBlockByHash* to obtain the full 175 | block details which is what is passed to the subscriber of the observable. 176 | 177 | 178 | Further examples 179 | ---------------- 180 | 181 | Please refer to the integration test 182 | `ObservableIT `_ 183 | for further examples. 184 | 185 | For a demonstration of using the manual filter API, you can take a look at the test 186 | `EventFilterIT `_.. 187 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 21 | 22 | .PHONY: help 23 | help: 24 | @echo "Please use \`make ' where is one of" 25 | @echo " html to make standalone HTML files" 26 | @echo " dirhtml to make HTML files named index.html in directories" 27 | @echo " singlehtml to make a single large HTML file" 28 | @echo " pickle to make pickle files" 29 | @echo " json to make JSON files" 30 | @echo " htmlhelp to make HTML files and a HTML help project" 31 | @echo " qthelp to make HTML files and a qthelp project" 32 | @echo " applehelp to make an Apple Help Book" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | @echo " coverage to run coverage check of the documentation (if enabled)" 49 | 50 | .PHONY: clean 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | .PHONY: html 55 | html: 56 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 57 | @echo 58 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 59 | 60 | .PHONY: dirhtml 61 | dirhtml: 62 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 63 | @echo 64 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 65 | 66 | .PHONY: singlehtml 67 | singlehtml: 68 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 69 | @echo 70 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 71 | 72 | .PHONY: pickle 73 | pickle: 74 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 75 | @echo 76 | @echo "Build finished; now you can process the pickle files." 77 | 78 | .PHONY: json 79 | json: 80 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 81 | @echo 82 | @echo "Build finished; now you can process the JSON files." 83 | 84 | .PHONY: htmlhelp 85 | htmlhelp: 86 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 87 | @echo 88 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 89 | ".hhp project file in $(BUILDDIR)/htmlhelp." 90 | 91 | .PHONY: qthelp 92 | qthelp: 93 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 94 | @echo 95 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 96 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 97 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/web3j.qhcp" 98 | @echo "To view the help file:" 99 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/web3j.qhc" 100 | 101 | .PHONY: applehelp 102 | applehelp: 103 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 104 | @echo 105 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 106 | @echo "N.B. You won't be able to view it unless you put it in" \ 107 | "~/Library/Documentation/Help or install it in your application" \ 108 | "bundle." 109 | 110 | .PHONY: devhelp 111 | devhelp: 112 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 113 | @echo 114 | @echo "Build finished." 115 | @echo "To view the help file:" 116 | @echo "# mkdir -p $$HOME/.local/share/devhelp/web3j" 117 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/web3j" 118 | @echo "# devhelp" 119 | 120 | .PHONY: epub 121 | epub: 122 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 123 | @echo 124 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 125 | 126 | .PHONY: latex 127 | latex: 128 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 129 | @echo 130 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 131 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 132 | "(use \`make latexpdf' here to do that automatically)." 133 | 134 | .PHONY: latexpdf 135 | latexpdf: 136 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 137 | @echo "Running LaTeX files through pdflatex..." 138 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 139 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 140 | 141 | .PHONY: latexpdfja 142 | latexpdfja: 143 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 144 | @echo "Running LaTeX files through platex and dvipdfmx..." 145 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 146 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 147 | 148 | .PHONY: text 149 | text: 150 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 151 | @echo 152 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 153 | 154 | .PHONY: man 155 | man: 156 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 157 | @echo 158 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 159 | 160 | .PHONY: texinfo 161 | texinfo: 162 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 163 | @echo 164 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 165 | @echo "Run \`make' in that directory to run these through makeinfo" \ 166 | "(use \`make info' here to do that automatically)." 167 | 168 | .PHONY: info 169 | info: 170 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 171 | @echo "Running Texinfo files through makeinfo..." 172 | make -C $(BUILDDIR)/texinfo info 173 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 174 | 175 | .PHONY: gettext 176 | gettext: 177 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 178 | @echo 179 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 180 | 181 | .PHONY: changes 182 | changes: 183 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 184 | @echo 185 | @echo "The overview file is in $(BUILDDIR)/changes." 186 | 187 | .PHONY: linkcheck 188 | linkcheck: 189 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 190 | @echo 191 | @echo "Link check complete; look for any errors in the above output " \ 192 | "or in $(BUILDDIR)/linkcheck/output.txt." 193 | 194 | .PHONY: doctest 195 | doctest: 196 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 197 | @echo "Testing of doctests in the sources finished, look at the " \ 198 | "results in $(BUILDDIR)/doctest/output.txt." 199 | 200 | .PHONY: coverage 201 | coverage: 202 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 203 | @echo "Testing of coverage in the sources finished, look at the " \ 204 | "results in $(BUILDDIR)/coverage/python.txt." 205 | 206 | .PHONY: xml 207 | xml: 208 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 209 | @echo 210 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 211 | 212 | .PHONY: pseudoxml 213 | pseudoxml: 214 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 215 | @echo 216 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 217 | -------------------------------------------------------------------------------- /docs/source/getting_started.rst: -------------------------------------------------------------------------------- 1 | Getting Started 2 | =============== 3 | 4 | Add the latest web3j version to your project build configuration. 5 | 6 | Maven 7 | ----- 8 | 9 | Java 8: 10 | 11 | .. code-block:: xml 12 | 13 | 14 | org.web3j 15 | core 16 | 3.3.1 17 | 18 | 19 | Android: 20 | 21 | .. code-block:: xml 22 | 23 | 24 | org.web3j 25 | core 26 | 3.3.1-android 27 | 28 | 29 | Gradle 30 | ------ 31 | 32 | Java 8: 33 | 34 | .. code-block:: groovy 35 | 36 | compile ('org.web3j:core:3.3.1') 37 | 38 | Android: 39 | 40 | .. code-block:: groovy 41 | 42 | compile ('org.web3j:core:3.3.1-android') 43 | 44 | 45 | Start a client 46 | -------------- 47 | 48 | Start up an Ethereum client if you don't already have one running, such as 49 | `Geth `_: 50 | 51 | .. code-block:: bash 52 | 53 | $ geth --rpcapi personal,db,eth,net,web3 --rpc --rinkeby 54 | 55 | Or `Parity `_: 56 | 57 | .. code-block:: bash 58 | 59 | $ parity --chain testnet 60 | 61 | Or use `Infura `_, which provides **free clients** running in the cloud: 62 | 63 | .. code-block:: java 64 | 65 | Web3j web3 = Web3j.build(new HttpService("https://morden.infura.io/your-token")); 66 | 67 | For further information refer to :doc:`infura`. 68 | 69 | Instructions on obtaining Ether to transact on the network can be found in the 70 | :ref:`testnet section of the docs `. 71 | 72 | 73 | Start sending requests 74 | ---------------------- 75 | 76 | To send synchronous requests:: 77 | 78 | Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/ 79 | Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send(); 80 | String clientVersion = web3ClientVersion.getWeb3ClientVersion(); 81 | 82 | To send asynchronous requests using a CompletableFuture (Future on Android):: 83 | 84 | Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/ 85 | Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().sendAsync().get(); 86 | String clientVersion = web3ClientVersion.getWeb3ClientVersion(); 87 | 88 | To use an RxJava Observable:: 89 | 90 | Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/ 91 | web3.web3ClientVersion().observable().subscribe(x -> { 92 | String clientVersion = x.getWeb3ClientVersion(); 93 | ... 94 | }); 95 | 96 | **Note:** for Android use:: 97 | 98 | Web3j web3 = Web3jFactory.build(new HttpService()); // defaults to http://localhost:8545/ 99 | ... 100 | 101 | 102 | IPC 103 | --- 104 | 105 | web3j also supports fast inter-process communication (IPC) via file sockets to clients running on 106 | the same host as web3j. To connect simply use the relevant *IpcService* implementation instead of 107 | *HttpService* when you create your service: 108 | 109 | .. code-block:: java 110 | 111 | // OS X/Linux/Unix: 112 | Web3j web3 = Web3j.build(new UnixIpcService("/path/to/socketfile")); 113 | ... 114 | 115 | // Windows 116 | Web3j web3 = Web3j.build(new WindowsIpcService("/path/to/namedpipefile")); 117 | ... 118 | 119 | **Note:** IPC is not available on *web3j-android*. 120 | 121 | 122 | .. _smart-contract-wrappers-summary: 123 | 124 | Working with smart contracts with Java smart contract wrappers 125 | -------------------------------------------------------------- 126 | 127 | web3j can auto-generate smart contract wrapper code to deploy and interact with smart contracts 128 | without leaving the JVM. 129 | 130 | To generate the wrapper code, compile your smart contract: 131 | 132 | .. code-block:: bash 133 | 134 | $ solc .sol --bin --abi --optimize -o / 135 | 136 | Then generate the wrapper code using web3j's :doc:`command_line`: 137 | 138 | .. code-block:: bash 139 | 140 | web3j solidity generate /path/to/.bin /path/to/.abi -o /path/to/src/main/java -p com.your.organisation.name 141 | 142 | Now you can create and deploy your smart contract:: 143 | 144 | Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/ 145 | Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile"); 146 | 147 | YourSmartContract contract = YourSmartContract.deploy( 148 | , , 149 | GAS_PRICE, GAS_LIMIT, 150 | , ..., ).send(); // constructor params 151 | 152 | Or use an existing contract:: 153 | 154 | YourSmartContract contract = YourSmartContract.load( 155 | "0x
|", , , GAS_PRICE, GAS_LIMIT); 156 | 157 | To transact with a smart contract:: 158 | 159 | TransactionReceipt transactionReceipt = contract.someMethod( 160 | , 161 | ...).send(); 162 | 163 | To call a smart contract:: 164 | 165 | Type result = contract.someMethod(, ...).send(); 166 | 167 | For more information refer to :ref:`smart-contract-wrappers`. 168 | 169 | 170 | Filters 171 | ------- 172 | 173 | web3j functional-reactive nature makes it really simple to setup observers that notify subscribers 174 | of events taking place on the blockchain. 175 | 176 | To receive all new blocks as they are added to the blockchain:: 177 | 178 | Subscription subscription = web3j.blockObservable(false).subscribe(block -> { 179 | ... 180 | }); 181 | 182 | To receive all new transactions as they are added to the blockchain:: 183 | 184 | Subscription subscription = web3j.transactionObservable().subscribe(tx -> { 185 | ... 186 | }); 187 | 188 | To receive all pending transactions as they are submitted to the network (i.e. before they have 189 | been grouped into a block together):: 190 | 191 | Subscription subscription = web3j.pendingTransactionObservable().subscribe(tx -> { 192 | ... 193 | }); 194 | 195 | Or, if you'd rather replay all blocks to the most current, and be notified of new subsequent 196 | blocks being created:: 197 | 198 | Subscription subscription = catchUpToLatestAndSubscribeToNewBlocksObservable( 199 | , ) 200 | .subscribe(block -> { 201 | ... 202 | }); 203 | 204 | There are a number of other transaction and block replay Observables described in :doc:`filters`. 205 | 206 | Topic filters are also supported:: 207 | 208 | EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, 209 | DefaultBlockParameterName.LATEST, ) 210 | .addSingleTopic(...)|.addOptionalTopics(..., ...)|...; 211 | web3j.ethLogObservable(filter).subscribe(log -> { 212 | ... 213 | }); 214 | 215 | Subscriptions should always be cancelled when no longer required:: 216 | 217 | subscription.unsubscribe(); 218 | 219 | **Note:** filters are not supported on Infura. 220 | 221 | For further information refer to :doc:`filters` and the 222 | `Web3jRx `_ 223 | interface. 224 | 225 | 226 | Transactions 227 | ------------ 228 | 229 | web3j provides support for both working with Ethereum wallet files (*recommended*) and Ethereum 230 | client admin commands for sending transactions. 231 | 232 | To send Ether to another party using your Ethereum wallet file:: 233 | 234 | Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/ 235 | Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile"); 236 | TransactionReceipt transactionReceipt = Transfer.sendFunds( 237 | web3, credentials, "0x
|", 238 | BigDecimal.valueOf(1.0), Convert.Unit.ETHER) 239 | .send(); 240 | 241 | Or if you wish to create your own custom transaction:: 242 | 243 | Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/ 244 | Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile"); 245 | 246 | // get the next available nonce 247 | EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount( 248 | address, DefaultBlockParameterName.LATEST).send(); 249 | BigInteger nonce = ethGetTransactionCount.getTransactionCount(); 250 | 251 | // create our transaction 252 | RawTransaction rawTransaction = RawTransaction.createEtherTransaction( 253 | nonce, , , , ); 254 | 255 | // sign & send our transaction 256 | byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials); 257 | String hexValue = Numeric.toHexString(signedMessage); 258 | EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).send(); 259 | // ... 260 | 261 | Although it's far simpler using web3j's `Transfer `_ 262 | for transacting with Ether. 263 | 264 | Using an Ethereum client's admin commands (make sure you have your wallet in the client's 265 | keystore):: 266 | 267 | Admin web3j = Admin.build(new HttpService()); // defaults to http://localhost:8545/ 268 | PersonalUnlockAccount personalUnlockAccount = web3j.personalUnlockAccount("0x000...", "a password").sendAsync().get(); 269 | if (personalUnlockAccount.accountUnlocked()) { 270 | // send a transaction 271 | } 272 | 273 | If you want to make use of Parity's 274 | `Personal `__ or 275 | `Trace `_, or Geth's 276 | `Personal `__ client APIs, 277 | you can use the *org.web3j:parity* and *org.web3j:geth* modules respectively. 278 | 279 | 280 | Command line tools 281 | ------------------ 282 | 283 | A web3j fat jar is distributed with each release providing command line tools. The command line 284 | tools allow you to use some of the functionality of web3j from the command line: 285 | 286 | - Wallet creation 287 | - Wallet password management 288 | - Transfer of funds from one wallet to another 289 | - Generate Solidity smart contract function wrappers 290 | 291 | Please refer to the :doc:`documentation ` for further 292 | information. 293 | 294 | 295 | Further details 296 | --------------- 297 | In the Java 8 build: 298 | 299 | - web3j provides type safe access to all responses. Optional or null responses 300 | are wrapped in Java 8's 301 | `Optional `_ type. 302 | - Asynchronous requests are wrapped in a Java 8 303 | `CompletableFutures `_. 304 | web3j provides a wrapper around all async requests to ensure that any exceptions during 305 | execution will be captured rather then silently discarded. This is due to the lack of support 306 | in *CompletableFutures* for checked exceptions, which are often rethrown as unchecked exception 307 | causing problems with detection. See the 308 | `Async.run() `_ and its associated 309 | `test `_ for details. 310 | 311 | In both the Java 8 and Android builds: 312 | 313 | - Quantity payload types are returned as `BigIntegers `_. 314 | For simple results, you can obtain the quantity as a String via 315 | `Response `_.getResult(). 316 | - It's also possible to include the raw JSON payload in responses via the *includeRawResponse* 317 | parameter, present in the 318 | `HttpService `_ 319 | and 320 | `IpcService `_ 321 | classes. 322 | -------------------------------------------------------------------------------- /docs/source/smart_contracts.rst: -------------------------------------------------------------------------------- 1 | Smart Contracts 2 | =============== 3 | 4 | Developers have the choice of three languages for writing smart contracts: 5 | 6 | `Solidity `_ 7 | The flagship language of Ethereum, and most popular language for smart contracts. 8 | 9 | `Serpent `_ 10 | A Python like language for writing smart contracts. 11 | 12 | LISP Like Language (LLL) 13 | A low level language, Serpent provides a superset of LLL. There's not a great deal of information 14 | for working with LLL, the following blog `/var/log/syrinx `_ and 15 | associated `lll-resurrected GitHub `_ repository 16 | is a good place to start. 17 | 18 | 19 | In order to deploy a smart contract onto the Ethereum blockchain, it must first be compiled into 20 | a bytecode format, then it can be sent as part of a transaction. web3j can do all of this for you 21 | with its :ref:`smart-contract-wrappers`. To understand what is happening behind the scenes, you 22 | can refer to the details in :ref:`creation-of-smart-contract`. 23 | 24 | Given that Solidity is the language of choice for writing smart contracts, it is the language 25 | supported by web3j, and is used for all subsequent examples. 26 | 27 | 28 | Getting started with Solidity 29 | ----------------------------- 30 | 31 | An overview of Solidity is beyond the scope of these docs, however, the following resources are a 32 | good place to start: 33 | 34 | - `Contract Tutorial `_ on the Go 35 | Ethereum Wiki 36 | - `Introduction to Smart Contracts `_ 37 | in the Solidity project documentation 38 | - `Writing a contract `_ 39 | in the Ethereum Homestead Guide 40 | 41 | .. _compiling-Solidity: 42 | 43 | Compiling Solidity source code 44 | ------------------------------ 45 | 46 | Compilation to bytecode is performed by the Solidity compiler, *solc*. You can install the compiler, 47 | locally following the instructions as per 48 | `the project documentation `_. 49 | 50 | To compile the Solidity code run: 51 | 52 | .. code-block:: bash 53 | 54 | $ solc .sol --bin --abi --optimize -o / 55 | 56 | The *--bin* and *--abi* compiler arguments are both required to take full advantage of working 57 | with smart contracts from web3j. 58 | 59 | *--bin* 60 | Outputs a Solidity binary file containing the hex-encoded binary to provide with the transaction 61 | request. 62 | 63 | *--abi* 64 | Outputs a Solidity :doc:`abi` (ABI) file which details all of the publicly 65 | accessible contract methods and their associated parameters. These details along with the 66 | contract address are crucial for interacting with smart contracts. The ABI file is also used for 67 | the generation of :ref:`smart-contract-wrappers`. 68 | 69 | There is also a *--gas* argument for providing estimates of the :ref:`gas` required to create a 70 | contract and transact with its methods. 71 | 72 | 73 | Alternatively, you can write and compile Solidity code in your browser via the 74 | `browser-solidity `_ project. browser-solidity is 75 | great for smaller smart contracts, but you may run into issues working with larger contracts. 76 | 77 | You can also compile Solidity code via Ethereum clients such as Geth and Parity, using the JSON-RPC 78 | method `eth_compileSolidity `_ 79 | which is also supported in web3j. However, the Solidity compiler must be installed on the client 80 | for this to work. 81 | 82 | There are further options available, please refer to the 83 | `relevant section `_ 84 | in the Homestead documentation. 85 | 86 | 87 | Deploying and interacting with smart contracts 88 | ---------------------------------------------- 89 | 90 | If you want to avoid the underlying implementation detail for working with smart contracts, web3j 91 | provides :ref:`smart-contract-wrappers` which enable you to interact directly with all of a smart 92 | contract's methods via a generated wrapper object. 93 | 94 | Alternatively, if you wish to send regular transactions or have more control over your 95 | interactions with your smart contracts, please refer to the sections 96 | :ref:`creation-of-smart-contract`, :ref:`transacting-with-contract` and :ref:`querying-state` 97 | for details. 98 | 99 | 100 | Smart contract examples 101 | ----------------------- 102 | 103 | web3j provides a number of smart contract examples in the project directory 104 | `codegen/src/test/resources/solidity `_ 105 | 106 | It also provides integration tests for demonstrating the deploying and working with those smart 107 | contracts in the 108 | `integration-tests/src/test/java/org/web3j/protocol/scenarios `_ 109 | module. 110 | 111 | .. image:: /images/smart_contract.png 112 | 113 | .. _eip: 114 | 115 | EIP-20 Ethereum token standard smart contract 116 | --------------------------------------------- 117 | 118 | There an Ethereum standard, `EIP-20 `_ 119 | which started off as an 120 | `Ethereum Improvement Proposal (EIP) `_, that defines the 121 | standard functions that a smart contract providing tokens should implement. 122 | 123 | The EIP-20 standard provides function definitions, but does not provide an implementation example. 124 | However, there is an implementation provided in 125 | `codegen/src/test/resources/solidity/contracts `_, 126 | which has been taken from ConsenSys' 127 | `Tokens project `_. 128 | 129 | Open Zepplin also provide an example implementation on 130 | `GitHub `_. 131 | 132 | There are two integration tests that have been written to fully demonstrate the functionality of 133 | this token smart contract. 134 | 135 | `HumanStandardTokenGeneratedIT `_ 136 | uses the generated 137 | `HumanStandardTokenGenerated `_ 138 | :ref:`smart contract wrapper ` to demonstrate this. 139 | 140 | Alternatively, if you do not wish to use a smart contract wrapper and would like to work directly 141 | with the underlying JSON-RPC calls, please refer to 142 | `HumanStandardTokenIT `_. 143 | 144 | 145 | .. _smart-contract-wrappers: 146 | 147 | Solidity smart contract wrappers 148 | -------------------------------- 149 | 150 | web3j supports the auto-generation of smart contract function wrappers in Java from Solidity ABI 151 | files. 152 | 153 | The web3j :doc:`command_line` tools ship with a command line utility for generating the smart contract function wrappers: 154 | 155 | .. code-block:: bash 156 | 157 | $ web3j solidity generate [--javaTypes|--solidityTypes] /path/to/.bin /path/to/.abi -o /path/to/src/main/java -p com.your.organisation.name 158 | 159 | In versions prior to 3.x of web3j, the generated smart contract wrappers used native Solidity 160 | types. From web3j 3.x onwards, Java types are created by default. You can create Solidity types 161 | using the *--solidityTypes* command line argument. 162 | 163 | You can also generate the wrappers by calling the Java class directly: 164 | 165 | .. code-block:: bash 166 | 167 | org.web3j.codegen.SolidityFunctionWrapperGenerator /path/to/.bin /path/to/.abi -o /path/to/src/main/java -p com.your.organisation.name 168 | 169 | Where the *bin* and *abi* are obtained as per :ref:`compiling-Solidity`. 170 | 171 | The native Java to Solidity type conversions used are detailed in the :doc:`abi` section. 172 | 173 | The smart contract wrappers support all common operations for working with smart contracts: 174 | 175 | - :ref:`construction-and-deployment` 176 | - :ref:`invoking-transactions` 177 | - :ref:`constant-methods` 178 | - :ref:`contract-validity` 179 | 180 | Any method calls that requires an underlying JSON-RPC call to take place will return a Future to 181 | avoid blocking. 182 | 183 | web3j also supports the generation of Java smart contract function wrappers directly from 184 | `Truffle's `_ 185 | `Contract Schema `_ 186 | via the :doc:`command_line` utility. 187 | 188 | .. code-block:: bash 189 | 190 | $ web3j truffle generate [--javaTypes|--solidityTypes] /path/to/.json -o /path/to/src/main/java -p com.your.organisation.name 191 | 192 | And this also can be invoked by calling the Java class: 193 | 194 | .. code-block:: bash 195 | 196 | org.web3j.codegen.TruffleJsonFunctionWrapperGenerator /path/to/.json -o /path/to/src/main/java -p com.your.organisation.name 197 | 198 | A wrapper generated this way ia "enhanced" to expose the per-network deployed address of the 199 | contract. These addresses are from the truffle deployment at the time the wrapper is generared. 200 | 201 | .. _construction-and-deployment: 202 | 203 | Construction and deployment 204 | --------------------------- 205 | 206 | Construction and deployment of smart contracts happens with the *deploy* method:: 207 | 208 | YourSmartContract contract = YourSmartContract.deploy( 209 | , , GAS_PRICE, GAS_LIMIT, 210 | [,] 211 | , ..., ).send(); 212 | 213 | This will create a new instance of the smart contract on the Ethereum blockchain using the 214 | supplied credentials, and constructor parameter values. 215 | 216 | The ** parameter is only required if your smart contract accepts Ether on 217 | construction. This requires the Solidity 218 | `payable `_ 219 | modifier to be present in the contract. 220 | 221 | It returns a new smart contract wrapper instance which contains the underlying address of the 222 | smart contract. If you wish to construct an instance of a smart contract wrapper with an existing 223 | smart contract, simply pass in it's address:: 224 | 225 | YourSmartContract contract = YourSmartContract.load( 226 | "0x
|", web3j, credentials, GAS_PRICE, GAS_LIMIT); 227 | 228 | 229 | .. _contract-validity: 230 | 231 | Contract validity 232 | ----------------- 233 | 234 | Using this method, you may want to ascertain that the contract address that you have loaded is the 235 | smart contract that you expect. For this you can use the *isValid* smart contract method, which will 236 | only return true if the deployed bytecode at the contract address matches the bytecode in the 237 | smart contract wrapper.:: 238 | 239 | contract.isValid(); // returns false if the contract bytecode does not match what's deployed 240 | // at the provided address 241 | 242 | 243 | .. _transaction-managers: 244 | 245 | Transaction Managers 246 | -------------------- 247 | 248 | web3j provides a 249 | `TransactionManager `_ 250 | abstraction to control the manner you connect to Ethereum clients with. The default mechanism uses 251 | web3j's 252 | `RawTransactionManager `_ 253 | which works with Ethereum wallet files to sign transactions offline before submitting them to the 254 | network. 255 | 256 | However, you may wish to modify the transaction manager, which you can pass to the smart 257 | contract deployment and creation methods instead of a credentials object, i.e.:: 258 | 259 | YourSmartContract contract = YourSmartContract.deploy( 260 | , , GAS_PRICE, GAS_LIMIT, 261 | , ..., ).send(); 262 | 263 | In addition to the RawTransactionManager, web3j provides a 264 | `ClientTransactionManager `_ 265 | which passes the responsibility of signing your transaction on to the Ethereum client you are 266 | connecting to. 267 | 268 | There is also a 269 | `ReadonlyTransactionManager `_ 270 | for when you only want to retrieve data from a smart contract, but not transact with it. 271 | 272 | 273 | Specifying the Chain Id on Transactions (EIP-155) 274 | ------------------------------------------------- 275 | 276 | The RawTransactionManager takes an optional *chainId* parameter to specify the chain id to be used 277 | on transactions as per 278 | `EIP-155 `_. This prevents transactions from one chain 279 | being re-broadcast onto another chain, such as from Ropsten to Mainnet:: 280 | 281 | TransactionManager transactionManager = new RawTransactionManager( 282 | web3j, credentials, ChainId.MAIN_NET); 283 | 284 | In order to avoid having to change config or code to specify which chain you are working with, 285 | web3j's default behaviour is to not specify chain ids on transactions to simplify working with the 286 | library. However, the recommendation of the Ethereum community is to use them. 287 | 288 | You can obtain the chain id of the network that your Ethereum client is connected to with the 289 | following request:: 290 | 291 | web3j.netVersion().send().getNetVersion(); 292 | 293 | 294 | .. transaction-processors: 295 | 296 | Transaction Receipt Processors 297 | ------------------------------ 298 | 299 | By default, when a new transaction is submitted by web3j to an Ethereum client, web3j will 300 | continually poll the client until it receives a 301 | `TransactionReceipt `_, 302 | indicating that the transaction has been added to the blockchain. If you are sending a number of 303 | transactions asynchronously with web3j, this can result in a number of threads polling the client 304 | concurrently. 305 | 306 | To reduce this polling overhead, web3j provides configurable 307 | `TransactionReceiptProcessors `_. 308 | 309 | There are a number of processors provided in web3j: 310 | 311 | - `PollingTransactionReceiptProcessor `_ 312 | is the default processor used in web3j, which polls periodically for a transaction receipt for 313 | each individual pending transaction. 314 | - `QueuingTransactionReceiptProcessor `_ 315 | has an internal queue of all pending transactions. It contains a worker that runs periodically 316 | to query if a transaction receipt is available yet. If a receipt is found, a callback to the 317 | client is invoked. 318 | - `NoOpProcessor `_ 319 | provides an 320 | `EmptyTransactionReceipt `_ 321 | to clients which only contains the transaction hash. This is for clients who do not want web3j 322 | to perform any polling for a transaction receipt. 323 | 324 | **Note:** the 325 | `EmptyTransactionReceipt `_ 326 | is also provided in the the initial response from the `QueuingTransactionReceiptProcessor `_. 327 | This allows the caller to have the transaction hash for the transaction that was submitted to the 328 | network. 329 | 330 | If you do not wish to use the default processor 331 | (`PollingTransactionReceiptProcessor `_), you can 332 | specify the transaction receipt processor to use as follows:: 333 | 334 | TransactionReceiptProcessor transactionReceiptProcessor = 335 | new QueuingTransactionReceiptProcessor(web3j, new Callback() { 336 | @Override 337 | public void accept(TransactionReceipt transactionReceipt) { 338 | // process transactionReceipt 339 | } 340 | 341 | @Override 342 | public void exception(Exception exception) { 343 | // handle exception 344 | } 345 | TransactionManager transactionManager = new RawTransactionManager( 346 | web3j, credentials, ChainId.MAIN_NET, transactionReceiptProcessor); 347 | 348 | 349 | If you require further information, the 350 | `FastRawTransactionManagerIT `_ 351 | demonstrates the polling and queuing approaches. 352 | 353 | 354 | .. _invoking-transactions: 355 | 356 | Invoking transactions and events 357 | -------------------------------- 358 | 359 | All transactional smart contract methods are named identically to their Solidity methods, taking 360 | the same parameter values. Transactional calls do not return any values, regardless of the return 361 | type specified on the method. Hence, for all transactional methods the 362 | `Transaction Receipt `_ 363 | associated with the transaction is returned.:: 364 | 365 | TransactionReceipt transactionReceipt = contract.someMethod( 366 | , 367 | ...).send(); 368 | 369 | 370 | The transaction receipt is useful for two reasons: 371 | 372 | #. It provides details of the mined block that the transaction resides in 373 | #. `Solidity events `_ 374 | that are called will be logged as part of the transaction, which can then be extracted 375 | 376 | Any events defined within a smart contract will be represented in the smart contract wrapper with 377 | a method named *processEvent*, which takes the Transaction Receipt and from this 378 | extracts the indexed and non-indexed event parameters, which are returned decoded in an instance of 379 | the 380 | `EventValues `_ 381 | object.:: 382 | 383 | EventValues eventValues = contract.processSomeEvent(transactionReceipt); 384 | 385 | Alternatively you can use an Observable filter instead which will listen for events associated with 386 | the smart contract:: 387 | 388 | contract.someEventObservable(startBlock, endBlock). 389 | .subscribe(event -> ...); 390 | 391 | For more information on working with Observable filters, refer to :doc:`filters`. 392 | 393 | **Remember** that for any indexed array, bytes and string Solidity parameter 394 | types, a Keccak-256 hash of their values will be returned, see the 395 | `documentation `_ 396 | for further information. 397 | 398 | 399 | .. _constant-methods: 400 | 401 | Calling constant methods 402 | ------------------------ 403 | 404 | Constant methods are those that read a value in a smart contract, and do not alter the state of 405 | the smart contract. These methods are available with the same method signature as the smart 406 | contract they were generated from:: 407 | 408 | Type result = contract.someMethod(, ...).send(); 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | Examples 417 | -------- 418 | 419 | Please refer to :ref:`eip`. 420 | -------------------------------------------------------------------------------- /docs/source/transactions.rst: -------------------------------------------------------------------------------- 1 | Transactions 2 | ============ 3 | 4 | Broadly speaking there are three types transactions supported on Ethereum: 5 | 6 | #. :ref:`transfer-of-ether` 7 | #. :ref:`creation-of-smart-contract` 8 | #. :ref:`transacting-with-contract` 9 | 10 | To undertake any of these transactions, it is necessary to have Ether (the fuel of the Ethereum 11 | blockchain) residing in the Ethereum account which the transactions are taking place from. This is 12 | to pay for the :ref:`Gas` costs, which is the transaction execution cost for the Ethereum client that 13 | performs the transaction on your behalf, comitting the result to the Ethereum blockchain. 14 | Instructions for obtaining Ether are described below in :ref:`obtaining-ether`. 15 | 16 | Additionally, it is possible to query the state of a smart contract, this is described in 17 | :ref:`querying-state`. 18 | 19 | .. image:: /images/web3j_transaction.png 20 | :scale: 20% 21 | 22 | 23 | .. _obtaining-ether: 24 | 25 | Obtaining Ether 26 | --------------- 27 | 28 | To obtain Ether you have two options: 29 | 30 | #. Mine it yourself 31 | #. Obtain Ether from another party 32 | 33 | Mining it yourself in a private environment, or the public test environment (testnet) is very 34 | straight forwards. However, in the main live environment (mainnet) it requires significant 35 | dedicated GPU time which is not likely to be feasible unless you already have a gaming PC with 36 | multiple dedicated GPUs. If you wish to use a private environment, there is some guidance on the 37 | `Homestead documentation `__. 38 | 39 | To purchase Ether you will need to go via an exchange. As different regions have different 40 | exchanges, you will need to research the best location for this yourself. The 41 | `Homestead documentation `__ 42 | contains a number of exchanges which is a good place to start. 43 | 44 | 45 | .. _ethereum-testnets: 46 | 47 | Ethereum testnets 48 | ----------------- 49 | 50 | There are a number of dedicated test networks in Ethereum, which are supported by various clients. 51 | 52 | - Rinkeby (Geth only) 53 | - Kovan (Parity only) 54 | - Ropsten (Geth and Parity) 55 | 56 | For development, its recommended you use the Rinkeby or Kovan test networks. This is because they 57 | use a Proof of Authority (PoA) consensus mechanism, ensuring transactions and blocks are created in 58 | a consistent and timely manner. The Ropsten testnet, although closest to the Mainnet as it uses 59 | Proof of Work (PoW) consensus, has been subject to attacks in the past and tends to be more 60 | problematic for developers. 61 | 62 | You can request Ether for the Rinkeby testnet via the Rinkeby Crypto Faucet, available at 63 | https://www.rinkeby.io/. 64 | 65 | Details of how to request Ether for the Kovan testnet are available 66 | `here `_. 67 | 68 | If you need some Ether on the Ropsten testnet to get started, please post a message with your 69 | wallet address to the `web3j Gitter channel `_ and you will be 70 | sent some. 71 | 72 | 73 | 74 | Mining on testnet/private blockchains 75 | ------------------------------------- 76 | 77 | In the Ethereum test environment (testnet), the mining difficulty is set lower then the main 78 | environment (mainnet). This means that you can mine new Ether with a regular CPU, such as your 79 | laptop. What you'll need to do is run an Ethereum client such as Geth or Parity to start building 80 | up reserves. Further instructions are available on the respective sites. 81 | 82 | Geth 83 | https://github.com/ethereum/go-ethereum/wiki/Mining 84 | 85 | Parity 86 | https://github.com/paritytech/parity/wiki/Mining 87 | 88 | Once you have mined some Ether, you can start transacting with the blockchain. 89 | 90 | However, as mentioned :ref:`above ` it's simpler to use the Kovan or Rinkeby 91 | test networks. 92 | 93 | 94 | .. _gas: 95 | 96 | Gas 97 | --- 98 | 99 | When a transaction takes place in Ethereum, a transaction cost must be paid to the client that 100 | executes the transaction on your behalf, committing the output of this transaction to the Ethereum 101 | blockchain. 102 | 103 | This cost is measure in gas, where gas is the number of instructions used to execute a transaction 104 | in the Ethereum Virtual Machine. Please refer to the 105 | `Homestead documentation `__ 106 | for further information. 107 | 108 | What this means for you when working with Ethereum clients is that there are two parameters which 109 | are used to dictate how much Ether you wish to spend in order for a tranaction to complete: 110 | 111 | *Gas price* 112 | 113 | This is the amount you are prepared in Ether per unit of gas. web3j uses a default price 114 | of 22,000,000,000 Wei 115 | (22 x 10\ :sup:`-8` Ether). This is defined in 116 | `ManagedTransaction `_. 117 | 118 | 119 | *Gas limit* 120 | 121 | This is the total amount of gas you are happy to spend on the transaction execution. There is an 122 | upper limit of how large a single transaction can be in an Ethereum block which restricts this 123 | value typically to less then 6,700,000. The current gas limit is visible at https://ethstats.net/. 124 | 125 | 126 | These parameters taken together dictate the maximum amount of Ether you are willing to spend on 127 | transaction costs. i.e. you can spend no more then *gas price * gas limit*. The gas price can also 128 | affect how quickly a transaction takes place depending on what other transactions are available 129 | with a more profitable gas price for miners. 130 | 131 | You may need to adjust these parameters to ensure that transactions take place in a timely manner. 132 | 133 | 134 | Transaction mechanisms 135 | ---------------------- 136 | 137 | When you have a valid account created with some Ether, there are two mechanisms you can use to 138 | transact with Ethereum. 139 | 140 | #. :ref:`signing-via-client` 141 | #. :ref:`offline-signing` 142 | 143 | Both mechanisms are supported via web3j. 144 | 145 | 146 | .. _signing-via-client: 147 | 148 | Transaction signing via an Ethereum client 149 | ------------------------------------------- 150 | 151 | In order to transact via an Ethereum client, you first need to ensure that the client you're 152 | transacting with knows about your wallet address. You are best off running your own Ethereum client 153 | such as Geth/Parity in order to do this. Once you have a client running, you can create a wallet 154 | via: 155 | 156 | - The `Geth Wiki `_ contains 157 | a good run down of the different mechanisms Geth supports such as importing private key files, 158 | and creating a new account via it's console 159 | - Alternatively you can use a JSON-RPC admin command for your client, such as *personal_newAccount* 160 | for `Parity `_ 161 | or `Geth `_ 162 | 163 | With your wallet file created, you can unlock your account via web3j by first of all creating an 164 | instance of web3j that supports Parity/Geth admin commands:: 165 | 166 | Admin web3j = Admin.build(new HttpService()); 167 | 168 | Then you can unlock the account, and providing this was successful, send a transaction:: 169 | 170 | PersonalUnlockAccount personalUnlockAccount = web3j.personalUnlockAccount("0x000...", "a password").send(); 171 | if (personalUnlockAccount.accountUnlocked()) { 172 | // send a transaction 173 | } 174 | 175 | 176 | Transactions for sending in this manner should be created via 177 | `EthSendTransaction `_, 178 | with the `Transaction `_ type:: 179 | 180 | Transaction transaction = Transaction.createContractTransaction( 181 | , 182 | , 183 | BigInteger.valueOf(), // we use default gas limit 184 | "0x..." 185 | ); 186 | 187 | org.web3j.protocol.core.methods.response.EthSendTransaction 188 | transactionResponse = parity.ethSendTransaction(ethSendTransaction) 189 | .send(); 190 | 191 | String transactionHash = transactionResponse.getTransactionHash(); 192 | 193 | // poll for transaction response via org.web3j.protocol.Web3j.ethGetTransactionReceipt() 194 | 195 | Where the ** value is obtained as per :ref:`below `. 196 | 197 | Please refer to the integration test 198 | `DeployContractIT `_ 199 | and its superclass 200 | `Scenario `_ 201 | for further details of this transaction workflow. 202 | 203 | Further details of working with the different admin commands supported by web3j are available in 204 | the section :doc:`management_apis`. 205 | 206 | 207 | .. _offline-signing: 208 | 209 | Offline transaction signing 210 | --------------------------- 211 | 212 | If you'd prefer not to manage your own Ethereum client, or do not want to provide wallet details 213 | such as your password to an Ethereum client, then offline transaction signing is the way to go. 214 | 215 | Offline transaction signing allows you to sign a transaction using your Ethereum Ethereum wallet 216 | within web3j, allowing you to have complete control over your private credentials. A transaction 217 | created offline can then be sent to any Ethereum client on the network, which will propagate the 218 | transaction out to other nodes, provided it is a valid transaction. 219 | 220 | You can also perform out of process transaction signing if required. This can be achieved by 221 | overriding the *sign* method in 222 | `ECKeyPair `_. 223 | 224 | 225 | .. _wallet-files: 226 | 227 | Creating and working with wallet files 228 | -------------------------------------- 229 | 230 | In order to sign transactions offline, you need to have either your Ethereum wallet file or the 231 | public and private keys associated with an Ethereum wallet/account. 232 | 233 | web3j is able to both generate a new secure Ethereum wallet file for you, or work with an existing 234 | wallet file. 235 | 236 | To create a new wallet file:: 237 | 238 | String fileName = WalletUtils.generateNewWalletFile( 239 | "your password", 240 | new File("/path/to/destination")); 241 | 242 | To load the credentials from a wallet file:: 243 | 244 | Credentials credentials = WalletUtils.loadCredentials( 245 | "your password", 246 | "/path/to/walletfile"); 247 | 248 | These credentials are then used to sign transactions. 249 | 250 | Please refer to the 251 | `Web3 Secret Storage Definition `_ 252 | for the full wallet file specification. 253 | 254 | 255 | Signing transactions 256 | -------------------- 257 | 258 | Transactions to be used in an offline signing capacity, should use the 259 | `RawTransaction `_ 260 | type for this purpose. The RawTransaction is similar to the previously mentioned Transaction type, 261 | however it does not require a *from* address, as this can be inferred from the signature. 262 | 263 | In order to create and sign a raw transaction, the sequence of events is as follows: 264 | 265 | #. Identify the next available :ref:`nonce ` for the sender account 266 | #. Create the RawTransaction object 267 | #. Encode the RawTransaction object using :doc:`rlp` encoding 268 | #. Sign the RawTransaction object 269 | #. Send the RawTransaction object to a node for processing 270 | 271 | The nonce is an increasing numeric value which is used to uniquely identify transactions. A nonce 272 | can only be used once and until a transaction is mined, it is possible to send multiple versions of 273 | a transaction with the same nonce, however, once mined, any subsequent submissions will be rejected. 274 | 275 | Once you have obtained the next available :ref:`nonce `, the value can then be used to 276 | create your transaction object:: 277 | 278 | RawTransaction rawTransaction = RawTransaction.createEtherTransaction( 279 | nonce, , , , ); 280 | 281 | The transaction can then be signed and encoded:: 282 | 283 | byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, ); 284 | String hexValue = Numeric.toHexString(signedMessage); 285 | 286 | Where the credentials are those loaded as per :ref:`wallet-files`. 287 | 288 | The transaction is then sent using `eth_sendRawTransaction `_:: 289 | 290 | EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get(); 291 | String transactionHash = ethSendTransaction.getTransactionHash(); 292 | // poll for transaction response via org.web3j.protocol.Web3j.ethGetTransactionReceipt() 293 | 294 | 295 | Please refer to the integration test 296 | `CreateRawTransactionIT `_ 297 | for a full example of creating and sending a raw transaction. 298 | 299 | 300 | .. _nonce: 301 | 302 | The transaction nonce 303 | --------------------- 304 | 305 | The nonce is an increasing numeric value which is used to uniquely identify transactions. A nonce 306 | can only be used once and until a transaction is mined, it is possible to send multiple versions of 307 | a transaction with the same nonce, however, once mined, any subsequent submissions will be rejected. 308 | 309 | You can obtain the next available nonce via the 310 | `eth_getTransactionCount `_ method:: 311 | 312 | EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount( 313 | address, DefaultBlockParameterName.LATEST).sendAsync().get(); 314 | 315 | BigInteger nonce = ethGetTransactionCount.getTransactionCount(); 316 | 317 | The nonce can then be used to create your transaction object:: 318 | 319 | RawTransaction rawTransaction = RawTransaction.createEtherTransaction( 320 | nonce, , , , ); 321 | 322 | 323 | 324 | 325 | Transaction types 326 | ----------------- 327 | 328 | The different types of transaction in web3j work with both Transaction and RawTransaction objects. 329 | The key difference is that Transaction objects must always have a from address, so that the 330 | Ethereum client which processes the 331 | `eth_sendTransaction `_ 332 | request know which wallet to use in order to sign and send the transaction on the message senders 333 | behalf. As mentioned :ref:`above `, this is not necessary for raw transactions 334 | which are signed offline. 335 | 336 | The subsequent sections outline the key transaction attributes required for the different 337 | transaction types. The following attributes remain constant for all: 338 | 339 | - Gas price 340 | - Gas limit 341 | - Nonce 342 | - From 343 | 344 | Transaction and RawTransaction objects are used interchangeably in all of the subsequent examples. 345 | 346 | 347 | .. _transfer-of-ether: 348 | 349 | Transfer of Ether from one party to another 350 | ------------------------------------------- 351 | 352 | The sending of Ether between two parties requires a minimal number of details of the transaction 353 | object: 354 | 355 | *to* 356 | the destination wallet address 357 | 358 | *value* 359 | the amount of Ether you wish to send to the destination address 360 | 361 | :: 362 | 363 | BigInteger value = Convert.toWei("1.0", Convert.Unit.ETHER).toBigInteger(); 364 | RawTransaction rawTransaction = RawTransaction.createEtherTransaction( 365 | , , , , value); 366 | // send... 367 | 368 | However, it is recommended that you use the 369 | `Transfer class `_ 370 | for sending Ether, which takes care of the nonce management and polling for a 371 | response for you:: 372 | 373 | Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/ 374 | Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile"); 375 | TransactionReceipt transactionReceipt = Transfer.sendFunds( 376 | web3, credentials, "0x
|", 377 | BigDecimal.valueOf(1.0), Convert.Unit.ETHER).send(); 378 | 379 | 380 | Recommended approach for working with smart contracts 381 | ----------------------------------------------------- 382 | 383 | When working with smart contract wrappers as outlined below, you will have to perform all of 384 | the conversions from Solidity to native Java types manually. It is far more effective to use 385 | web3j's :ref:`smart-contract-wrappers` which take care of all code generation and this conversion 386 | for you. 387 | 388 | 389 | .. _creation-of-smart-contract: 390 | 391 | Creation of a smart contract 392 | ---------------------------- 393 | 394 | To deploy a new smart contract, the following attributes will need to be provided 395 | 396 | *value* 397 | the amount of Ether you wish to deposit in the smart contract (assumes zero if not provided) 398 | 399 | *data* 400 | the hex formatted, compiled smart contract creation code 401 | 402 | :: 403 | 404 | // using a raw transaction 405 | RawTransaction rawTransaction = RawTransaction.createContractTransaction( 406 | , 407 | , 408 | , 409 | , 410 | "0x "); 411 | // send... 412 | 413 | // get contract address 414 | EthGetTransactionReceipt transactionReceipt = 415 | web3j.ethGetTransactionReceipt(transactionHash).send(); 416 | 417 | if (transactionReceipt.getTransactionReceipt.isPresent()) { 418 | String contractAddress = transactionReceipt.get().getContractAddress(); 419 | } else { 420 | // try again 421 | } 422 | 423 | 424 | If the smart contract contains a constructor, the associated constructor field values must be 425 | encoded and appended to the *compiled smart contract code*:: 426 | 427 | String encodedConstructor = 428 | FunctionEncoder.encodeConstructor(Arrays.asList(new Type(value), ...)); 429 | 430 | // using a regular transaction 431 | Transaction transaction = Transaction.createContractTransaction( 432 | , 433 | , 434 | , 435 | , 436 | , 437 | "0x " + encodedConstructor); 438 | 439 | // send... 440 | 441 | 442 | 443 | .. _transacting-with-contract: 444 | 445 | Transacting with a smart contract 446 | --------------------------------- 447 | 448 | To transact with an existing smart contract, the following attributes will need to be provided: 449 | 450 | *to* 451 | the smart contract address 452 | 453 | *value* 454 | the amount of Ether you wish to deposit in the smart contract (if the smart contract accepts 455 | ether) 456 | 457 | *data* 458 | the encoded function selector and parameter arguments 459 | 460 | web3j takes care of the function encoding for you, for further details on the implementation refer 461 | to the :doc:`abi` section. 462 | 463 | :: 464 | 465 | Function function = new Function<>( 466 | "functionName", // function we're calling 467 | Arrays.asList(new Type(value), ...), // Parameters to pass as Solidity Types 468 | Arrays.asList(new TypeReference() {}, ...)); 469 | 470 | String encodedFunction = FunctionEncoder.encode(function) 471 | Transaction transaction = Transaction.createFunctionCallTransaction( 472 | , , , contractAddress, , encodedFunction); 473 | 474 | org.web3j.protocol.core.methods.response.EthSendTransaction transactionResponse = 475 | web3j.ethSendTransaction(transaction).sendAsync().get(); 476 | 477 | String transactionHash = transactionResponse.getTransactionHash(); 478 | 479 | // wait for response using EthGetTransactionReceipt... 480 | 481 | It is not possible to return values from transactional functional calls, regardless of the return 482 | type of the message signature. However, it is possible to capture values returned by functions 483 | using filters. Please refer to the :doc:`filters` section for details. 484 | 485 | 486 | .. _querying-state: 487 | 488 | Querying the state of a smart contract 489 | -------------------------------------- 490 | 491 | This functionality is facilitated by the `eth_call `_ 492 | JSON-RPC call. 493 | 494 | eth_call allows you to call a method on a smart contract to query a value. There is no transaction 495 | cost associated with this function, this is because it does not change the state of any smart 496 | contract method's called, it simply returns the value from them:: 497 | 498 | Function function = new Function<>( 499 | "functionName", 500 | Arrays.asList(new Type(value)), // Solidity Types in smart contract functions 501 | Arrays.asList(new TypeReference() {}, ...)); 502 | 503 | String encodedFunction = FunctionEncoder.encode(function) 504 | org.web3j.protocol.core.methods.response.EthCall response = web3j.ethCall( 505 | Transaction.createEthCallTransaction(, contractAddress, encodedFunction), 506 | DefaultBlockParameterName.LATEST) 507 | .sendAsync().get(); 508 | 509 | List someTypes = FunctionReturnDecoder.decode( 510 | response.getValue(), function.getOutputParameters()); 511 | 512 | **Note:** If an invalid function call is made, or a null result is obtained, the return value will 513 | be an instance of `Collections.emptyList() `_ --------------------------------------------------------------------------------