### Install Web3j-CLI
Source: https://docs.web3j.io/4.12.3/web3j_openapi
Command to download and install the Web3j-CLI.
```bash
$ curl -L get.web3j.io | sh
```
--------------------------------
### Clone Besu Quickstart Repository
Source: https://docs.web3j.io/4.12.3/privacy/besu_quickstart
Clone the Besu Quickstart repository to your local machine. This repository contains the necessary files to set up a local private-transaction-enabled Ethereum network.
```bash
git clone https://github.com/PegaSysEng/besu-quickstart.git
```
--------------------------------
### Web3j Maven Plugin Build Output Example
Source: https://docs.web3j.io/4.12.3/plugins/web3j_maven_plugin
Example output from the web3j-maven-plugin during the 'generate-sources' goal execution, showing the processing of Solidity files and the build success.
```log
[INFO] --- web3j-maven-plugin:0.1.2:generate-sources (default-cli) @ hotel-showcase ---
[INFO] process 'HotelShowCaseProxy.sol'
[INFO] Built Class for contract 'HotelShowCaseProxy'
[INFO] Built Class for contract 'HotelShowCaseV2'
[INFO] Built Class for contract 'Owned'
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.681 s
[INFO] Finished at: 2017-06-13T07:07:04+02:00
[INFO] Final Memory: 14M/187M
[INFO] ------------------------------------------------------------------------
Process finished with exit code 0
```
--------------------------------
### Verify Web3j CLI Installation
Source: https://docs.web3j.io/4.12.3/command_line_tools
Checks if the Web3j CLI has been installed successfully by displaying its version information. This command should output version details and a Web3j logo.
```bash
web3j -v
```
--------------------------------
### Complete Web3j Maven Plugin Configuration Example
Source: https://docs.web3j.io/4.12.3/plugins/web3j_maven_plugin
An example of a comprehensive web3j-maven-plugin configuration in a Maven pom.xml. This includes package name, source destination, output format, contract filtering, and path prefixing.
```xml
org.web3j
web3j-maven-plugin
4.5.11
com.zuehlke.blockchain.model
src/main/java/generated
true
java,bin
src/main/resources
**/*.sol
src/java/generated
src/bin/generated
src/abi/generated
greeter
mortal
dep=../dependencies
```
--------------------------------
### Solidity Hello World Contract
Source: https://docs.web3j.io/4.12.3/web3j_openapi
Example of a Solidity smart contract including Mortal and HelloWorld contracts.
```solidity
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.0;
// Modified Greeter contract. Based on example at https://www.ethereum.org/greeter.
contract Mortal {
/* Define variable owner of the type address*/
address owner;
/* this function is executed at initialization and sets the owner of the contract */
constructor () {owner = msg.sender;}
modifier onlyOwner {
require(
msg.sender == owner,
"Only owner can call this function."
);
_;
}
/* Function to recover the funds on the contract */
function kill() onlyOwner public {selfdestruct(msg.sender);}
}
contract HelloWorld is Mortal {
/* define variable greeting of the type string */
string greet;
/* this runs when the contract is executed */
constructor (string memory _greet) {
greet = _greet;
}
function newGreeting(string memory _greet) onlyOwner public {
emit Modified(greet, _greet, greet, _greet);
greet = _greet;
}
/* main function */
function greeting() public view returns (string memory) {
return greet;
}
event Modified(
string indexed oldGreetingIdx, string indexed newGreetingIdx,
string oldGreeting, string newGreeting);
}
```
--------------------------------
### Generate New Ethereum Wallet
Source: https://docs.web3j.io/4.12.3/command_line_tools
Use this command to create a new Ethereum wallet. No specific setup is required beyond having the web3j tool installed.
```bash
$ web3j wallet create
```
--------------------------------
### HTTP Request Example
Source: https://docs.web3j.io/4.12.3/web3j_openapi
Example of how to interact with a deployed contract using a POST request via Curl.
```APIDOC
## POST /HelloWorldProject/contracts/helloworld/{contract address}/NewGreeting
### Description
Sends a request to execute the `NewGreeting` function on a deployed HelloWorld contract.
### Method
POST
### Endpoint
`http://{host}:{port}/HelloWorldProject/contracts/helloworld/{contract address}/NewGreeting`
### Parameters
#### Path Parameters
- **contract address** (string) - Required - The address of the deployed HelloWorld contract.
#### Headers
- **accept**: `application/json`
- **Content-Type**: `application/json`
### Request Body
- **_greet** (string) - Required - The greeting message to set.
### Request Example
```json
{
"_greet": "Hello Web3j-OpenAPI"
}
```
### Response
#### Success Response (200)
- **transactionHash** (string) - The hash of the transaction that executed the `NewGreeting` function.
#### Response Example
```json
{
"transactionHash": "0x..."
}
```
```
--------------------------------
### Deploy HelloWorld Smart Contract
Source: https://docs.web3j.io/4.12.3/quickstart
Example of deploying the HelloWorld smart contract using Web3j. Ensure you replace placeholders with your actual node URL and private key.
```java
Web3j web3j = Web3j.build(new HttpService(""));
HelloWorld helloWorld = HelloWorld.deploy(web3j, Credentials.create("your_private_key"), new DefaultGasProvider(), "Hello Blockchain World").send();
String greeting = helloWorld.greeting().send();
web3j.shutdown();
```
--------------------------------
### Web3j-OpenAPI Client Setup and Usage
Source: https://docs.web3j.io/4.12.3/web3j_openapi
This snippet demonstrates how to add the Web3j-OpenAPI client dependency and create a client instance to interact with the API.
```APIDOC
## Web3j-OpenAPI Client Setup and Usage
### Description
This section details how to integrate the Web3j-OpenAPI client into your Kotlin project and perform basic operations like contract deployment.
### Dependency
Add the following dependency to your `build.gradle` file:
```gradle
dependencies {
implementation "org.web3j.openapi:web3j-openapi-client:4.12.3"
}
```
### Client Initialization and Contract Deployment
Instantiate the client service and create an API client instance. Then, you can access contract-related operations such as deployment.
```kotlin
// Import necessary classes
import org.web3j.openapi.client.ClientService
import org.web3j.openapi.client.ClientFactory
import com.example.your_app_name.AppNameApi // Replace with your actual API interface
// Initialize the service with the server URL
val service = ClientService("http://localhost:9090")
// Create the API client instance
val app = ClientFactory.create(AppNameApi::class.java, service)
// Example: Deploy a contract
// Note: Replace 'contracts.contractName.deploy()' with the actual method for your contract
// The return type 'receipt.contractAddress' is an assumption based on common patterns.
// val receipt = app.contracts.contractName.deploy()
// println("Deployment receipt: ${receipt.contractAddress}")
// Placeholder for actual contract deployment call
println("Client initialized. Ready to interact with API.")
```
### Handling Events
This section explains how to subscribe to and handle events emitted by the server using Server-Sent Events (SSE).
### Event Subscription and Handling
To listen for events, load a contract and subscribe to a specific event.
```kotlin
// Import necessary classes
import org.web3j.openapi.client.ClientService
import org.web3j.openapi.client.ClientFactory
import com.example.your_app_name.AppNameApi // Replace with your actual API interface
// Initialize the service and client as shown above
val service = ClientService("http://localhost:9090")
val app = ClientFactory.create(AppNameApi::class.java, service)
// Example: Load a contract and subscribe to an event
// Note: Replace placeholders like '', '', '',
// and '()' with actual values.
// val eventSubscription = app.contracts.
// .load("")
// .events
// .
// .onEvent { eventData -> println("Received event: $eventData") }
// Example: Trigger an event (for demonstration purposes)
// app.contracts
// .
// .load("")
// .("")
println("Event listener setup complete. Waiting for events...")
```
```
--------------------------------
### Deploy a Contract using Web3j-OpenAPI Client
Source: https://docs.web3j.io/4.12.3/web3j_openapi
Instantiate the client service and create an application client to interact with smart contracts. This example shows contract deployment.
```kotlin
val service = ClientService("http://localhost:9090")
val app = ClientFactory.create(::class.java, service)
// Then you have access to all the API resources
val receipt = app.contracts.contractName.deploy()
println("Deployment receipt: ${receipt.contractAddress}")
```
--------------------------------
### Install Web3j CLI
Source: https://docs.web3j.io/4.12.3/command_line_tools
Installs the Web3j CLI using a curl script. Ensure to source the script to make the commands available in your current shell session.
```bash
curl -L get.web3j.io | sh && source ~/.web3j/source.sh
```
--------------------------------
### Example Usage of Sokt for Solidity Compilation
Source: https://docs.web3j.io/4.12.3/web3j_sokt
This example demonstrates how to use Sokt to process a Solidity file, resolve the appropriate compiler version, and execute the compilation with specified arguments. It prints the compiler version, exit code, and standard output/error.
```java
String fileName = filePath.substringAfterLast("/");
System.out.println("sokt Processing " + fileName);
SolidityFile solidityFile = new SolidityFile(filePath);
System.out.println("Resolving compiler version for " + fileName);
SolcInstance compilerInstance = solidityFile.getCompilerInstance();
System.out.println("Resolved" + compilerInstance.getSolcRelease().getVersion() + " for " + fileName);
SolcOutput result = compilerInstance.execute(
SolcArguments.OUTPUT_DIR.param(() -> "/tmp"),
SolcArguments.AST,
SolcArguments.BIN,
SolcArguments.OVERWRITE
);
System.out.println("Solc exited with code: " + result.getExitCode());
System.out.println("Solc standard output: " + result.getStdOut());
System.out.println("Solc standard error: " + result.getStdErr());
```
--------------------------------
### Run Geth with Testnet Configuration
Source: https://docs.web3j.io/4.12.3/getting_started/run_node_locally
Starts the Geth client with RPC API enabled for local interaction. Use the --testnet flag to connect to a test network.
```bash
$ geth --rpcapi personal,db,eth,net,web3 --rpc --testnet
```
--------------------------------
### Start Epirus Local Client
Source: https://docs.web3j.io/4.12.3/getting_started/run_node_locally
Initializes the Epirus Local client, creating a new genesis file with 10 pre-funded accounts. Specify a directory for genesis file storage and the RPC port.
```bash
epirus-local start -d=/path/to/directory -p=9090
```
--------------------------------
### Run OpenEthereum on Testnet
Source: https://docs.web3j.io/4.12.3/getting_started/run_node_locally
Starts the OpenEthereum client and connects it to the test network. Refer to the documentation for instructions on obtaining test Ether.
```bash
$ openethereum --chain testnet
```
--------------------------------
### Launch Teku Test Network
Source: https://docs.web3j.io/4.12.3/web3j_eth2_client
Start the Teku Beacon Chain local test network using the provided launch script. Ensure Docker is running.
```bash
$ teku/test-network/launch.sh
```
--------------------------------
### Configure Solidity Output Components
Source: https://docs.web3j.io/4.12.3/plugins/solidity_gradle_plugin
Customize the output components generated by the Solidity compiler. This example sets output components to BIN, ABI, and ASM_JSON, and configures optimizer runs.
```gradle
solidity {
outputComponents = [BIN, ABI, ASM_JSON]
optimizeRuns = 500
}
```
--------------------------------
### Java/Kotlin Client Interaction
Source: https://docs.web3j.io/4.12.3/web3j_openapi
Example of interacting with a Web3j-OpenAPI generated project using the provided Java/Kotlin client library.
```APIDOC
## Client Application Interaction
### Description
Demonstrates how to use the Web3j-OpenAPI client library to deploy a contract, call a function, and retrieve its result.
### Dependencies
```groovy
implementation "org.web3j.openapi:web3j-openapi-client:4.12.3"
```
### Usage
```kotlin
// Initialize the client service
val service = ClientService("http://localhost:9090")
// Create a client factory for the HelloWorldProjectApi
val helloWorldProject = ClientFactory.create(HelloWorldProjectApi::class.java, service)
println("Deploying the HelloWorld contract...")
// Deploy the HelloWorld contract
val receipt = helloWorldProject.contracts.helloWorld.deploy(HelloWorldDeployParameters("Hello"))
println("Deployed contract address: ${receipt.contractAddress}")
// Execute the NewGreeting function and get the transaction hash
val newGreetingHash = helloWorldProject.contracts
.helloWorld
.load(receipt.contractAddress)
.newGreeting(NewGreetingParameters("Hello Web3j-OpenAPI"))
.transactionHash
println("NewGreeting method execution transaction hash: $newGreetingHash")
// Retrieve the current greeting from the contract
val greeting = helloWorldProject.contracts
.helloWorld
.load(receipt.contractAddress)
.greeting()
.result
println("Greeting method result: $greeting")
```
```
--------------------------------
### Start Privacy-Enabled Ethereum Network
Source: https://docs.web3j.io/4.12.3/privacy/besu_quickstart
Invoke the `run-privacy.sh` script to start the Ethereum network with privacy enabled. This will launch multiple Docker containers, including Besu nodes that communicate over specific ports.
```bash
./run-privacy.sh
```
--------------------------------
### Listen for Beacon Node Events
Source: https://docs.web3j.io/4.12.3/web3j_eth2_client
Connect to a local Beacon Node, subscribe to all event types, and process received events. This example waits for at least one event.
```java
var service = new BeaconNodeService("http://localhost:19601/");
var client = BeaconNodeClientFactory.build(service);
// We want to receive at least one event
var latch = new CountDownLatch(1);
// At the moment we are interested in any topic
var topics = EnumSet.allOf(BeaconEventType.class);
// Then subscribe to each event
client.getEvents().onEvent(topics, event -> {
System.out.println("Received event: " + event);
latch.countDown();
});
// Wait for the event
latch.await();
```
--------------------------------
### Beacon Node Event Request and Response Log
Source: https://docs.web3j.io/4.12.3/web3j_eth2_client
Example log output showing a client request for events and the subsequent server response, including a 'head' event.
```log
00:15:47.744 [jersey-client-async-executor-0] DEBUG org.web3j.eth2.api.BeaconNodeService - 2 * Sending client request on thread jersey-client-async-executor-0
2 > GET http://localhost:19601/eth/v1/events?topics=head%2Cblock%2Cattestation%2Cvoluntary_exit%2Cfinalized_checkpoint%2Cchain_reorg
2 > Accept: text/event-stream
00:15:51.420 [jersey-client-async-executor-0] DEBUG org.web3j.eth2.api.BeaconNodeService - 2 * Client response received on thread jersey-client-async-executor-0
2 < 200
2 < Cache-Control: no-cache
2 < Connection: close
2 < Content-Type: text/event-stream;charset=utf-8
2 < Date: Thu, 10 Dec 2020 23:15:47 GMT
2 < Server: Javalin
event: head
data: {"slot":"33207","block":"0x1829e81553bb76ed92a7ae2d671e018b219b7eeee0cea80fac12b2a7d6924826","state":"0xe7339bff5fbb2a30f039a900532cb936e6afbd40ef1fd41cb645687659d8833a","epoch_transition":false,"previous_duty_dependent_root":"0xd34981d5ab59d4d091992099cedea95236dfcc2252f55f53e282ee847fb426e8","current_duty_dependent_root":"0x626db3e484c19fa8f0c57ca6c390bfa8a61313564d61f4c68764239a4e0c966e"}
```
--------------------------------
### Solidity Interface Mismatch Example
Source: https://docs.web3j.io/4.12.3/references/troubleshooting
Illustrates how a mismatch between a Solidity interface definition and its implementation can lead to a blank smart contract binary. The 'transfer' method signature differs between the interface and implementation.
```solidity
contract Web3jToken is ERC20Basic, Ownable {
...
function transfer(address _from, address _to, uint256 _value) onlyOwner returns (bool) {
...
}
```
```solidity
contract ERC20Basic {
...
function transfer(address to, uint256 value) returns (bool);
...
}
```
--------------------------------
### Implement HSMHTTPRequestProcessor for HSM Requests
Source: https://docs.web3j.io/4.12.3/advanced/HSM_transaction_signing
Instantiate your custom implementation of HSMHTTPRequestProcessor to handle requests directed to the HSM. This example uses a test implementation, requiring an HTTP client to be provided.
```java
HSMHTTPRequestProcessor hsmRequestProcessor =
new HSMHTTPRequestProcessorTestImpl<>();
```
--------------------------------
### Generate a Hello World OpenAPI Project
Source: https://docs.web3j.io/4.12.3/web3j_openapi
Create a new Web3j OpenAPI project with a sample Hello World contract.
```bash
$ web3j openapi new
```
--------------------------------
### Create and Deploy Smart Contract
Source: https://docs.web3j.io/4.12.3/getting_started/deploy_interact_smart_contracts
Instantiate a Web3j service, load credentials, and deploy a new instance of your generated smart contract wrapper. Ensure you provide the correct constructor parameters.
```java
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545 /
Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");
YourSmartContract contract = YourSmartContract.deploy(
web3, credentials,
,
, ..., ).send(); // constructor params
```
--------------------------------
### Replay Past and Future Transactions
Source: https://docs.web3j.io/4.12.3/advanced/filters_and_events
Replays all transactions from a specified start block and continues to provide notifications for new transactions. Replace placeholder with the start block number.
```java
Subscription subscription = web3j.replayPastAndFutureTransactionsFlowable(
)
.subscribe(tx -> {
...
});
```
--------------------------------
### Create Default 'helloworld' Project
Source: https://docs.web3j.io/4.12.3/command_line_tools
Creates a new project using the default 'helloworld' Solidity smart contract template for Java. This is the default behavior when no arguments are specified.
```bash
web3j new helloworld
```
--------------------------------
### Open Generated Documentation
Source: https://docs.web3j.io/4.12.3/references/developer_guide
After building the documentation, open the generated index.html file in your browser to view it.
```bash
$ open build/html/index.html
```
--------------------------------
### Replay Past and Future Blocks
Source: https://docs.web3j.io/4.12.3/getting_started/pub_sub
Subscribe to a Flowable that replays all blocks from a specified starting number up to the current block, and then continues to notify of new subsequent blocks. Requires specifying the start block number and whether to retrieve full transaction objects.
```java
Subscription subscription = replayPastAndFutureBlocksFlowable(
, )
.subscribe(block -> {
...
});
```
--------------------------------
### Get Transaction by Hash
Source: https://docs.web3j.io/4.12.3/transactions/transfer_eth
Retrieves transaction details using its hash.
```java
EthTransaction ethTransaction = web3j.ethGetTransactionByHash(String transactionHash).send();
```
--------------------------------
### Import Solidity Project
Source: https://docs.web3j.io/4.12.3/command_line_tools
Use this command to import Solidity smart contracts into a new Java project. The -s option accepts a single file or a folder. Unit tests are generated by default.
```bash
web3j import -s [-o |-n |-p ] -t
```
```bash
web3j import
```
--------------------------------
### Generated OpenAPI Specification
Source: https://docs.web3j.io/4.12.3/web3j_openapi
Example of OpenAPI specifications generated from a Solidity contract.
```json
{
"openapi":"3.0.1",
"info":{
"title":"Web3j OpenApi",
"contact":{
"name":"Web Web3 Labs",
"url":"http://web3labs.com",
"email":"hi@web3labs.com"
},
"version":"4.12.3"
},
"tags":[
{
"name":"default",
"description":"Lists existing contracts and events"
},
{
"name":"HelloWorld Methods",
"description":"List HelloWorld method's calls"
},
{
"name":"HelloWorld Events",
"description":"List HelloWorld event's calls"
}
],
"paths":{
"/Web3App/contracts/helloworld/{contractAddress}/Kill":{
"get":{
"tags":[
"HelloWorld Methods"
],
"summary":"Execute the Kill method",
"operationId":"kill",
"parameters":[
{
"name":"contractAddress",
"in":"path",
"required":true,
"schema":{
"type":"string"
}
}
],
"responses":{
"default":{
"description":"default response",
"content":{
"application/json":{
"schema":{
"$ref":"#/components/schemas/TransactionReceiptModel"
}
}
}
}
}
}
},
...
```
--------------------------------
### Web3j-CLI OpenAPI Import Help
Source: https://docs.web3j.io/4.12.3/web3j_openapi
Command to display help for the web3j openapi import command.
```bash
$ web3j openapi import --help
```
--------------------------------
### Get Uncle by Block Number
Source: https://docs.web3j.io/4.12.3/transactions/transfer_eth
Fetches an uncle block by its number and index.
```java
EthBlock.Block block = web3j.ethGetUncleByBlockNumberAndIndex(DefaultBlockParameter defaultBlockParameter, BigInteger transactionIndex);
```
--------------------------------
### Get Uncle by Block Hash
Source: https://docs.web3j.io/4.12.3/transactions/transfer_eth
Fetches an uncle block by its hash and index.
```java
EthBlock.Block block = web3j.ethGetUncleByBlockHashAndIndex(String blockHash, BigInteger transactionIndex);
```
--------------------------------
### Get Block by Hash
Source: https://docs.web3j.io/4.12.3/transactions/transfer_eth
Retrieves a block's information using its hash.
```java
EthBlock.Block block = web3j.ethGetBlockByHash(String blockHash, boolean returnFullTransactionObjects);
```
--------------------------------
### Run Application
Source: https://docs.web3j.io/4.12.3/command_line_tools
Execute your application on a specified Ethereum network. This command requires the node endpoint, wallet path, and wallet password.
```bash
web3j run
```
--------------------------------
### Get MinimalForwarder Contract Nonce
Source: https://docs.web3j.io/4.12.3/use_cases/meta_transaction
Retrieve the current nonce for the MinimalForwarder contract associated with the provided credentials.
```java
BigInteger nonce = minimalForwarder.getNonce(credentials.getAddress()).send();
```
--------------------------------
### Get Block Information
Source: https://docs.web3j.io/4.12.3/transactions/transfer_eth
Fetches block details by number and retrieves the base fee per gas.
```java
EthBlock.Block block = web3j.ethGetBlockByNumber(
DefaultBlockParameter.valueOf(“”),
true //returnFullTransactionObjects
).send().get().getBlock();
block.getBaseFeePerGas();
```
--------------------------------
### Run Application with Docker
Source: https://docs.web3j.io/4.12.3/command_line_tools
Build a Docker container for your application. This command requires the network, wallet path, and wallet password.
```bash
web3j docker run [-l]
```
--------------------------------
### Generate Documentation with Sphinx
Source: https://docs.web3j.io/4.12.3/references/developer_guide
Build a local copy of the web3j documentation using Sphinx. Navigate to the docs directory and run the make clean html command.
```bash
$ cd docs
$ make clean html
```
--------------------------------
### Send Transaction and Get Receipt
Source: https://docs.web3j.io/4.12.3/smart_contracts/interacting_with_smart_contract
Use this method to send a transaction to a smart contract and retrieve the transaction receipt.
```java
TransactionReceipt transactionReceipt = contract.someMethod(
,
...).send();
```
--------------------------------
### Get Smart Contract Address
Source: https://docs.web3j.io/4.12.3/transactions/transactions_and_smart_contracts
After deploying a contract, retrieve its address from the transaction receipt. If the receipt is not immediately available, retry.
```java
EthGetTransactionReceipt transactionReceipt =
web3j.ethGetTransactionReceipt(transactionHash).send();
if (transactionReceipt.getTransactionReceipt.isPresent()) {
String contractAddress = transactionReceipt.get().getContractAddress();
} else {
// try again
}
```
--------------------------------
### Build Admin Web3j Instance
Source: https://docs.web3j.io/4.12.3/transactions/transaction_mechanisms
Instantiate a web3j client that supports Geth/Besu/OpenEthereum admin commands for managing accounts and transactions.
```java
Admin web3j = Admin.build(new HttpService());
```
--------------------------------
### Run web3j Integration Tests
Source: https://docs.web3j.io/4.12.3/references/developer_guide
Execute the integration tests for web3j against a live Ethereum client using Gradle.
```bash
$ ./gradlew -Pintegration-tests=true :integration-tests:test
```
--------------------------------
### Get Next Transaction Nonce
Source: https://docs.web3j.io/4.12.3/transactions/transaction_nonce
Retrieve the next available nonce for a given address using `ethGetTransactionCount`. This is essential before sending new transactions.
```java
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
address, DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
```
--------------------------------
### Run Hyperledger Besu in Development Mode
Source: https://docs.web3j.io/4.12.3/getting_started/run_node_locally
Launches Hyperledger Besu using the 'dev' network configuration. This network provides convenient default parameters for local development.
```bash
$ besu ----network=dev
```
--------------------------------
### Get NameHash and LabelHash for ENS
Source: https://docs.web3j.io/4.12.3/advanced/ethereum_name_service
Calculate the NameHash and LabelHash for ENS names and labels. Also demonstrates DNS encoding for ENS names.
```java
// ENS name: luc.eth
String nameHashString = NameHash.nameHash("luc.eth");
byte[] nameHash = NameHash.nameHashAsBytes("luc.eth");
// ENS label: luc
String labelHashString = NameHash.nameHash("luc");
byte[] labelHash = NameHash.nameHashAsBytes("luc");
// DNS Encoded Name
String dnsEncodedName = NameHash.dnsEncode("name.eth");
```
--------------------------------
### Run Gradle Project
Source: https://docs.web3j.io/4.12.3/web3j_openapi
Execute the Gradle wrapper script to run the Web3j project.
```bash
$ ./gradlew run
```
--------------------------------
### Get Transaction by Block Number and Index
Source: https://docs.web3j.io/4.12.3/transactions/transfer_eth
Retrieves a transaction from a block using the block's number and the transaction's index within that block.
```java
EthTransaction ethTransaction = web3j.ethGetTransactionByBlockNumberAndIndex(
DefaultBlockParameter defaultBlockParameter, BigInteger transactionIndex).send();
```
--------------------------------
### Load Epirus Local from Genesis File
Source: https://docs.web3j.io/4.12.3/getting_started/run_node_locally
Loads an existing Epirus Local client configuration using a pre-defined genesis file. Provide the path to your genesis file.
```bash
epirus-local load -g=/path/to/genesis
```
--------------------------------
### Get Transaction by Block Hash and Index
Source: https://docs.web3j.io/4.12.3/transactions/transfer_eth
Fetches a transaction from a block using the block's hash and the transaction's index within that block.
```java
EthTransaction ethTransaction = web3j.ethGetTransactionByBlockHashAndIndex
(String blockHash, BigInteger transactionIndex).send();
```
--------------------------------
### Generate Solidity Wrappers via CLI
Source: https://docs.web3j.io/4.12.3/smart_contracts/construction_and_deployment
Use the web3j command-line tool to generate Java smart contract wrappers from Solidity ABI and optional binary files. Specify output directory and package name. The binary file is required for generating deploy methods.
```bash
$ web3j generate solidity [-hV] [-jt] [-st] -a= [-b=] -o= -p=
-h, --help Show this help message and exit.
-V, --version Print version information and exit.
-jt, --javaTypes use native java types. Default: true
-st, --solidityTypes use solidity types.
-a, --abiFile= abi file with contract definition.
-b, --binFile= optional bin file with contract compiled code in order to generate deploy methods.
-o, --outputDir= destination base directory.
-p, --package= base package name.
```
--------------------------------
### Example Ethereum JSON-RPC Response
Source: https://docs.web3j.io/4.12.3/getting_started/run_node_locally
Illustrates a typical JSON-RPC response for an Ethereum transaction. The 'result' field contains the transaction hash upon successful submission.
```json
{"id" : 1, "jsonrpc" : "2.0", "result" : "0xc631caa67cab48ead77a58321bbb0c76f4060751a4bb3d5b45b99c4a68b1a7b7"}
```
--------------------------------
### Deploy New Smart Contract
Source: https://docs.web3j.io/4.12.3/smart_contracts/construction_and_deployment
Use this method to create a new instance of a smart contract on the Ethereum blockchain. Provide credentials, gas provider, and constructor parameters. The `initialValue` parameter is only needed if the contract accepts Ether on construction.
```java
YourSmartContract contract = YourSmartContract.deploy(
, , ,
[,]
, ..., ).send();
```
--------------------------------
### Initialize WebSocketService
Source: https://docs.web3j.io/4.12.3/getting_started/pub_sub
Instantiate WebSocketClient and WebSocketService for WebSocket communication with an Ethereum client.
```java
final WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost/"));
final boolean includeRawResponses = false;
final WebSocketService webSocketService = new WebSocketService(webSocketClient, includeRawResponses);
```
--------------------------------
### Send and Get Transaction Hash
Source: https://docs.web3j.io/4.12.3/transactions/transactions_and_smart_contracts
Send a transaction to a smart contract and retrieve the transaction hash. Use getAsync().get() for asynchronous execution and to obtain the hash.
```java
org.web3j.protocol.core.methods.response.EthSendTransaction transactionResponse =
web3j.ethSendTransaction(transaction).sendAsync().get();
String transactionHash = transactionResponse.getTransactionHash();
```
--------------------------------
### Clone Teku Project
Source: https://docs.web3j.io/4.12.3/web3j_eth2_client
Clone the Teku project repository to set up a local test network.
```bash
$ git clone https://github.com/ConsenSys/teku.git
```
--------------------------------
### Prompt for Solidity Path
Source: https://docs.web3j.io/4.12.3/command_line_tools
When 'web3j import' is run without arguments, you will be prompted to enter the path to your Solidity files or folder.
```shell
Please enter the path to your solidity file/folder [Required Field]:
/path/to/solidity
```
--------------------------------
### Create Beacon Node Client Instance
Source: https://docs.web3j.io/4.12.3/web3j_eth2_client
Instantiate a BeaconNodeService and build a BeaconNodeClient to interact with a Beacon Chain node.
```java
var service = new BeaconNodeService("http://...");
var client = BeaconNodeClientFactory.build(service);
```
--------------------------------
### Replay Past Blocks and Notify Completion
Source: https://docs.web3j.io/4.12.3/advanced/filters_and_events
Replays all blocks from a specified start block up to the most current, providing notifications for each block. A separate Flowable notifies upon completion.
```java
Subscription subscription = web3j.replayPastBlocksFlowable(
, , )
.subscribe(block -> {
...
});
```
--------------------------------
### Generate OpenAPI Project from Custom Solidity Contracts
Source: https://docs.web3j.io/4.12.3/web3j_openapi
Import custom Solidity smart contracts to generate a Web3j OpenAPI project.
```bash
$ web3j openapi import \
--solidity-path \
--project-name \
--package
```
--------------------------------
### Get Ethereum Client Network Version
Source: https://docs.web3j.io/4.12.3/smart_contracts/interacting_with_smart_contract
Retrieve the chain ID of the network your Ethereum client is connected to. This is useful for configuring transaction managers to target the correct network.
```java
web3j.netVersion().send().getNetVersion();
```
--------------------------------
### Load ERC20 Contract and Get Balance
Source: https://docs.web3j.io/4.12.3/smart_contracts/contracts_supported_by_web3j
Loads an ERC20 contract wrapper and retrieves the token balance for a given account. Ensure you have initialized web3j, txManager, and gasPriceProvider.
```java
ERC20 contract = ERC20.load(tokenAddress, web3j, txManager, gasPriceProvider);
BigInteger balance = contract.balanceOf(account).send();
```
--------------------------------
### Create New Java/Kotlin Project
Source: https://docs.web3j.io/4.12.3/command_line_tools
Generates a new project for Java or Kotlin. Supports 'helloworld', 'erc20', or 'erc777' templates. Use '--kotlin' for Kotlin projects.
```bash
web3j new [--kotlin|-o