### 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 |-n |-p ] [helloworld|erc20|erc777] ``` -------------------------------- ### Create OpenAPI Project from Existing Contracts Source: https://docs.web3j.io/4.12.3/command_line_tools Creates an OpenAPI project by importing existing smart contracts. This is useful for generating services for pre-existing contract code. ```bash web3j openapi import ``` -------------------------------- ### Generate web3j OpenAPI Distribution Executable Source: https://docs.web3j.io/4.12.3/web3j_openapi Create a standalone server executable for web3j OpenAPI using Gradle. The executable will be found in the build/install/-shadow/bin/ directory. ```bash $ ./gradlew installShadowDist ``` -------------------------------- ### Besu Node Credentials and Enclave Keys Source: https://docs.web3j.io/4.12.3/privacy/privacy_support_web3j Defines static credentials and Base64 encoded enclave keys for network members (Alice, Bob, Charlie) used in Besu privacy quickstart. ```java private static final Credentials ALICE = Credentials.create("8f2a55949038a9610f50fb23b5883af3b4ecb3c3bb792cbcefbd1542c692be63"); private static final Credentials BOB = Credentials.create("c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3"); private static final Credentials CHARLIE = Credentials.create("ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f"); private static final Base64String ENCLAVE_KEY_ALICE = Base64String.wrap("A1aVtMxLCUHmBVHXoZzzBgPbW/wj5axDpW9X8l91SGo="); private static final Base64String ENCLAVE_KEY_BOB = Base64String.wrap("Ko2bVqD+nNlNYL5EE7y3IdOnviftjiizpjRt+HTuFBs="); private static final Base64String ENCLAVE_KEY_CHARLIE = Base64String.wrap("k2zXEin4Ip/qBGlRkJejnGWdP9cjkK+DAvKNW31L2C8="); ``` -------------------------------- ### Calculate KZG Commitment and Proofs from Blob Source: https://docs.web3j.io/4.12.3/transactions/EIP_transaction_types/eip4844_blob_transaction This snippet demonstrates how to use the BlobUtils class to compute the KZG commitment, proofs, and versioned hashes from a given blob. It also shows how to validate the proof. ```java Blob blob = new Blob( Numeric.hexStringToByteArray( loadResourceAsString("blob_data.txt"))); Bytes commitment = BlobUtils.getCommitment(blob); Bytes proofs = BlobUtils.getProof(blob, commitment); Bytes versionedHashes = BlobUtils.kzgToVersionedHash(commitment); BlobUtils.checkProofValidity(blob, commitment, proofs) ``` -------------------------------- ### Run Gradle Build Source: https://docs.web3j.io/4.12.3/plugins/web3j_gradle_plugin Execute the Gradle build to trigger contract wrapper generation. This command should be run from your project's root directory. ```bash ./gradlew build ``` -------------------------------- ### Get and Set ENS Text Records Source: https://docs.web3j.io/4.12.3/advanced/ethereum_name_service Retrieve and set text records associated with an ENS name. This is commonly used for storing metadata like URLs or other arbitrary string data. ```java // Get ENS text String url = ensResolver.getEnsText("nick.eth", "url"); // Set ENS text TransactionReceipt receiptResult3 = ensResolver.setEnsText("nick.eth", "url", "http://example.com", credentials); ``` -------------------------------- ### Interact with Deployed Contract using Web3j Client Source: https://docs.web3j.io/4.12.3/web3j_openapi Use the Web3j client library to deploy a contract, call the newGreeting method, and retrieve the greeting. ```kotlin val service = ClientService("http://localhost:9090") val helloWorldProject = ClientFactory.create(HelloWorldProjectApi::class.java, service) println("Deploying the HelloWorld contract...") val receipt = helloWorldProject.contracts.helloWorld.deploy(HelloWorldDeployParameters("Hello")) println("Deployed contract address: ${receipt.contractAddress}") val newGreetingHash = helloWorldProject.contracts .helloWorld .load(receipt.contractAddress) .newGreeting(NewGreetingParameters("Hello Web3j-OpenAPI")) .transactionHash println("NewGreeting method execution transaction hash: $newGreetingHash") val greeting = helloWorldProject.contracts .helloWorld .load(receipt.contractAddress) .greeting() .result println("Greeting method result: $greeting") ``` -------------------------------- ### Send Ethereum Transaction Request via cURL Source: https://docs.web3j.io/4.12.3/getting_started/run_node_locally Example of sending an `eth_sendTransaction` request to a local Ethereum node using cURL. Ensure 'host:port' is replaced with your node's address. ```bash curl -X POST --data '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{ "from": "0x8f496c16955a7bb9b5e1ea0383d01f87372ab520", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a", "nonce": "0x1" }],"id":1}' host:port ``` -------------------------------- ### Compile Solidity Smart Contract Source: https://docs.web3j.io/4.12.3/getting_started/deploy_interact_smart_contracts Compile your Solidity smart contract to generate binary and ABI files required for wrapper generation. ```bash solc .sol --bin --abi --optimize -o / ``` -------------------------------- ### Replay Past and Future Blocks Source: https://docs.web3j.io/4.12.3/advanced/filters_and_events Replays all blocks from a specified start block and continues to provide notifications for newly created blocks. Set the boolean parameter to true to include full transaction objects. ```java Subscription subscription = web3j.replayPastAndFutureBlocksFlowable( , ) .subscribe(block -> { ... }); ``` -------------------------------- ### Initialize Admin Connector and Unlock Account Source: https://docs.web3j.io/4.12.3/advanced/management_apis Initializes a web3j Admin connector and demonstrates unlocking an Ethereum account using the personalUnlockAccount method. Ensure the account and password are correct. ```java Admin web3j = Admin.build(new HttpService()); // defaults to http://localhost:8545/ PersonalUnlockAccount personalUnlockAccount = admin.personalUnlockAccount("0x000...", "a password").send(); if (personalUnlockAccount.accountUnlocked()) { // send a transaction } ``` -------------------------------- ### Get Owner and Resolver Address for ENS Name Source: https://docs.web3j.io/4.12.3/advanced/ethereum_name_service Retrieve the owner address and the resolver contract address for a given ENS name. This information is crucial for managing ENS records and understanding name ownership. ```java String resolver = ensResolver.getResolverAddress("luc.eth"); String owner = ensResolver.getOwnerAddress("luc.eth"); ``` -------------------------------- ### Running the Web3j Maven Plugin Source: https://docs.web3j.io/4.12.3/plugins/web3j_maven_plugin Execute this command in your Maven project to run the web3j plugin and generate sources. ```bash mvn web3j:generate-sources ``` -------------------------------- ### Build Web3j Instance Source: https://docs.web3j.io/4.12.3/use_cases/meta_transaction Create a Web3j instance to connect to a blockchain node via HTTP RPC. ```java Web3j web3j = Web3j.build(new HttpService("")); ``` -------------------------------- ### Generate Contract Wrappers with Gradle Source: https://docs.web3j.io/4.12.3/command_line_tools Run this command to update only the smart contract bindings after changes to Solidity code. ```bash ./gradlew generateContractWrappers ``` -------------------------------- ### Deploy and Interact with Smart Contracts in a Privacy Group using Web3j Source: https://docs.web3j.io/4.12.3/privacy/privacy_support_web3j Illustrates deploying and interacting with a `HumanStandardToken` contract within a privacy group. It shows how to create a group, set up private transaction managers for members, and deploy/load the contract from different nodes. ```java // Create a new privacy group Base64String aliceBobGroup = Base64String.wrap(generateRandomBytes(32)); final String createTxHash = nodeAlice .privOnChainCreatePrivacyGroup( aliceBobGroup, ALICE, ENCLAVE_KEY_ALICE, Collections.singletonList(ENCLAVE_KEY_BOB)) .send() .getTransactionHash(); TransactionReceipt createReceipt = processor.waitForTransactionReceipt(createTxHash); // Find the privacy group that was built by Alice from Bob's node final Base64String aliceBobGroupFromBobNode = nodeBob .privOnChainFindPrivacyGroup( Arrays.asList(ENCLAVE_KEY_ALICE, ENCLAVE_KEY_BOB)) .send().getGroups().stream() .filter(g -> g.getPrivacyGroupId().equals(aliceBobGroup)) .findFirst() .orElseThrow(RuntimeException::new) .getPrivacyGroupId(); // Create two private transaction manager instances for Alice and Bob in order to interact with smart contracts final PrivateTransactionManager tmAlice = new BesuPrivateTransactionManager( nodeAlice, ZERO_GAS_PROVIDER, ALICE, 2018, ENCLAVE_KEY_ALICE, aliceBobGroup); final PrivateTransactionManager tmBob = new BesuPrivateTransactionManager( nodeBob, ZERO_GAS_PROVIDER, BOB, 2018, ENCLAVE_KEY_BOB, aliceBobGroupFromBobNode); // Deploy the token from Alice's node final HumanStandardToken tokenAlice = HumanStandardToken.deploy( nodeAlice, tmAlice, ZERO_GAS_PROVIDER, BigInteger.TEN, "eea_token", BigInteger.TEN, "EEATKN") .send(); // Get an instance of the token from Bob's node final HumanStandardToken tokenBob = HumanStandardToken.load( tokenAlice.getContractAddress(), nodeBob, tmBob, ZERO_GAS_PROVIDER); ``` -------------------------------- ### Generate Unit Tests Interactively Source: https://docs.web3j.io/4.12.3/command_line_tools Use this command to generate unit tests for smart contracts. You will be prompted to provide paths for contract wrappers and the desired output location for tests. ```bash web3j generate tests ``` -------------------------------- ### Generate Executable JAR for OpenAPI Project Source: https://docs.web3j.io/4.12.3/web3j_openapi Create an executable JAR file for a Web3j OpenAPI project based on provided Solidity contracts. ```bash $ web3j openapi jar \ --solidity-path ``` -------------------------------- ### Generate Solidity Wrappers via Java Class Source: https://docs.web3j.io/4.12.3/smart_contracts/construction_and_deployment Generate smart contract wrappers by directly invoking the Java class. Provide paths to the binary and ABI files, the output directory, and the package name. ```java org.web3j.codegen.SolidityFunctionWrapperGenerator -b /path/to/.bin -a /path/to/.abi -o /path/to/src/main/java -p com.your.organisation.name ``` -------------------------------- ### Run web3j OpenAPI JAR Source: https://docs.web3j.io/4.12.3/web3j_openapi Execute the generated web3j OpenAPI JAR file, passing any necessary parameters as arguments. Refer to the parameters section for supported options. ```bash $ java -jar build/libs/-all.jar ``` -------------------------------- ### Generate Solidity Smart Contract Wrapper Source: https://docs.web3j.io/4.12.3/getting_started/deploy_interact_smart_contracts Use the Web3j CLI to generate Java wrapper code from your compiled smart contract's binary and ABI files. ```bash web3j generate solidity -b /path/to/.bin -a /path/to/.abi -o /path/to/src/main/java -p com.your.organisation.name ``` -------------------------------- ### Environment Variables for web3j OpenAPI Configuration Source: https://docs.web3j.io/4.12.3/web3j_openapi Set runtime parameters using environment variables, following the convention of replacing hyphens with underscores and uppercasing names. This is the simplest method for providing parameters. ```bash $ export WEB3J_ENDPOINT= $ export WEB3J_OPENAPI_HOST=localhost $ export WEB3J_OPENAPI_PORT=9090 $ export WEB3J_OPENAPI_NAME=Web3jOpenAPI $ export WEB3J_OPENAPI_CONTRACT_ADDRESSES=helloworld=0x1234,helloworld2=0x12345 $ export WEB3J_OEPNAPI_CONFIG_FILE=~/myConfig.yaml ``` ```bash $ export WEB3J_PRIVATE_KEY=0x1234 ``` ```bash $ export WEB3J_WALLET_PATH=~/myWallet.json $ export WEB3J_WALLET_PASSWORD=myStrongPassword ``` -------------------------------- ### Set Environment Variables for Web3j Source: https://docs.web3j.io/4.12.3/web3j_openapi Configure runtime parameters for Web3j by setting environment variables for the node endpoint, private key, and OpenAPI host/port. ```bash $ export WEB3J_ENDPOINT= $ export WEB3J_PRIVATE_KEY= $ export WEB3J_OPENAPI_HOST=localhost $ export WEB3J_OPENAPI_PORT=9090 ``` -------------------------------- ### Load Credentials from Wallet File Source: https://docs.web3j.io/4.12.3/transactions/wallet_files Load existing wallet credentials by providing the password and the path to the wallet file. These credentials are used for signing transactions. ```java Credentials credentials = WalletUtils.loadCredentials( "your password", "/path/to/walletfile"); ```