How to Connect to Ethereum Mainnet and Generate Wallets with Web3j and Infura
This guide walks through obtaining an Infura API key, using Web3j’s HTTP API to connect to Ethereum’s mainnet, creating and sending requests, handling responses, and generating local wallets with private keys, while highlighting common pitfalls and asynchronous issues for Java developers.
In this tutorial the author shares a step‑by‑step experience of accessing the Ethereum mainnet using the Infura service and the Java library Web3j, followed by a simple method to generate a local wallet and retrieve its address and keys.
Obtaining an Infura API key
Register on the Infura website, create a new project, and copy the generated project ID, which serves as the API key. The free tier allows up to 100,000 requests per 24 hours, which is sufficient for basic experimentation.
Connecting to the mainnet with Web3j
Web3j uses okhttp under the hood. To create a client that talks to Infura, replace {your apikey} with the project ID obtained earlier:
static Web3j web3 = Web3j.build(new HttpService("https://mainnet.infura.io/v3/{your apikey}"));Creating and sending a request
Web3j follows a builder‑style API. For example, to query the network version:
Request<?, NetVersion> netVersionRequest = web3.netVersion();Sending the request returns a typed response object:
NetVersion netVersion = netVersionRequest.send();All request types are defined in org.web3j.protocol.core.Ethereum, and each has a corresponding response class that can be inspected for detailed information.
Handling transaction results (a common pitfall)
When retrieving block data, the transaction list contains generic TransactionResult objects that must be cast to TransactionObject before accessing fields. A typical pattern is:
List<EthBlock.TransactionResult> transactions = web3.ethGetBlockByNumber(
new DefaultBlockParameterNumber(blockNumber), true).send().getBlock().getTransactions();
transactions.forEach(f -> {
EthBlock.TransactionObject tx = (EthBlock.TransactionObject) f;
// process tx
});Asynchronous calls
The author notes that asynchronous usage of Web3j can prevent the JVM from exiting, referencing an open issue on the project’s GitHub. For production services, the two known work‑arounds can be applied, but the problem remains unresolved in the library.
Generating a local wallet
Web3j also provides utilities to create a wallet file (JSON format) and load it later. The following example creates a new wallet, prints the address, private key, and public key, and stores the file on disk:
import org.web3j.crypto.CipherException;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import java.io.File;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
public class Wallet {
public static void main(String[] args) throws CipherException, IOException,
InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
String walletFilePath = "/Users/vallet/test"; // directory to store the wallet
String password = ""; // wallet password
String walletFileName = WalletUtils.generateNewWalletFile(password,
new File(walletFilePath), false);
Credentials credentials = WalletUtils.loadCredentials(password,
walletFilePath + "/" + walletFileName);
String address = credentials.getAddress();
System.out.println("address:" + address);
System.out.println("PrivateKey:" + credentials.getEcKeyPair().getPrivateKey());
System.out.println("PublicKey:" + credentials.getEcKeyPair().getPublicKey());
}
}The generated file is a JSON string that can be further encrypted so that the plaintext keys exist only in memory.
Notes on test networks
Goerli testnet has been deprecated and will be replaced by Sepolia in 2023. Developers should migrate their applications accordingly.
Overall, the article provides a practical introduction to Ethereum mainnet interaction via Infura and Web3j, demonstrates request/response handling, warns about asynchronous pitfalls, and supplies a ready‑to‑run wallet‑generation snippet for Java developers.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
