The Conflux Java SDK allows any Java client to interact with a local or remote Conflux node based on JSON-RPC 2.0 protocol. With Conflux Java SDK, user can easily manage accounts, send transactions, deploy smart contracts and query blockchain information.
The java-conflux-sdk is built on web3j, which providing a lot useful utilities:
- keccak
- secp256k1
- abi
- rlp
- hex utilities
We have published this package to maven central repository for easy import, you can import it
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
<dependency>
<groupId>io.github.conflux-chain</groupId>
<artifactId>conflux.web3j</artifactId>
<version>x.x.x</version>
</dependency>implementation 'io.github.conflux-chain:conflux.web3j:x.x.x'For detail version list check here
Or you can download jar package from github release page, or clone the source code build jar manually.
- Conflux developer documentation portal
- JAVA SDK API
- Conflux fullnode RPC API
- Conflux fullnode pub/sub API
- SDK updates for CIP37
- Testnet Faucet
- changelog
- Community Examples
- Contract method interaction ABI encode
With java-conflux-sdk it's very easy to query balance and send transaction.
importconflux.web3j.Account;
importconflux.web3j.Cfx;
importconflux.web3j.CfxUnit;
importconflux.web3j.types.Address;
importjava.math.BigInteger;
publicclassmain {
publicstaticvoidmain(String[] args) throwsException {
// Use testnet RPC url create a Cfx instance, which can be used to invoke RPC methodCfxcfx = Cfx.create("https://test.confluxrpc.com");
StringADDRESS = "cfxtest:aat9v7xdvszbj68x083kjjt52z32g94nwjaj7vdpxf";
// getBalance method can be used to query balance of one addressBigIntegerbalance = cfx.getBalance(newAddress(ADDRESS)).sendAndGet();
// default unit is dripSystem.out.println("balance in Drip: " + balance);
// Use CfxUnit.drip2Cfx convert unit to CFXSystem.out.println("balance in CFX: " + CfxUnit.drip2Cfx(balance));
// Create an account with private keyAccountaccount = Account.create(cfx, PRIVATE_KEY);
// Call account.transfer method to transfer CFX to another addressStringhash = account.transfer(newAddress(ADDRESS), BigInteger.valueOf(100));
System.out.println("Transaction hash: " + hash); }
}Use Cfx interface to query Conflux blockchain information, such as block, epoch, transaction, receipt. Following is an example to query the current epoch number:
packageconflux.sdk.examples;
importjava.math.BigInteger;
importconflux.web3j.types.Address;
importconflux.web3j.Cfx;
publicclassApp {
publicstaticvoidmain(String[] args) throwsException {
Cfxcfx = Cfx.create("https://test.confluxrpc.com", 3, 1000);
// Invoke RPC method cfx_getEpochNumberBigIntegerepoch = cfx.getEpochNumber().sendAndGet();
System.out.println("Current epoch: " + epoch);
Addressaddr = newAddress("cfxtest:aak2rra2njvd77ezwjvx04kkds9fzagfe6d5r8e957");
BigIntegernonce = cfx.getNonce(addr).sendAndGet();
}
}Cfx interface provides a factory method to create an instance, and allow client to enable auto-retry mechanism in case of temporary IO errors.
Conflux import a new base32 address at CIP37.
From conflux-rust v1.1.1, and java-conflux-sdk 1.0, the new CIP37 will be supported.
The Address class has added support for CIP37 address.
inttestNetId = 1; // mainnet is 1029Addressa = newAddress("0x13d2bA4eD43542e7c54fbB6c5fCCb9f269C1f94C", testNetId);
Addressb = newAddress("cfxtest:aak7fsws4u4yf38fk870218p1h3gxut3ku00u1k1da");
a.getAddress(); // "cfxtest:aak7fsws4u4yf38fk870218p1h3gxut3ku00u1k1da"a.getHexAddress(); // "0x13d2bA4eD43542e7c54fbB6c5fCCb9f269C1f94C"a.getVerboseAddress(); // "NET1921:TYPE.USER:AAR8JZYBZV0FHZREAV49SYXNZUT8S0JT1AT8UHK7M3"a.getNetworkId(); // 1a.getType(); // userFor complete CIP37 address updates check here
Note: java-conflux-sdkv1.0 is an incompatible version, it only work with conflux-rust1.1.1 or above.
Use AccountManager to manage accounts at local machine.
- Create/Import/Update/Delete an account.
- List all accounts.
- Unlock/Lock an account.
- Sign a transaction.
packageconflux.sdk.examples;
importconflux.web3j.AccountManager;
publicclassApp {
publicstaticvoidmain(String[] args) throwsException {
StringprivateKey = "0xxxxxx"; // replace this with your own privateKey// Initialize a accountManagerAccountManageram = newAccountManager(testNetId);
// import private keyam.imports(privateKey, "123456");
// import a keystore fileam.imports("keystore file path", "old password", "new password");
// then you can use am to signTransaction or signMessage
}
}- Sign a transaction with unlocked account:
AccountManager.signTransaction(RawTransactiontx, Addressaddress)- Sign a transaction with passphrase for locked account:
AccountManager.signTransaction(RawTransactiontx, Addressaddress, Stringpassword)To send a transaction, first you need to build a transaction and sign the transaction at local machine, then send the signed transaction to local or remote Conflux node.
BigIntegervalue = newBigInteger("1000", 16);
TransactionBuildertxBuilder = newTransactionBuilder("0x-the-sender-address");
txBuilder.withChainId(1);
txBuilder.withTo(newAddress("cfxtest:aak7fsws4u4yf38fk870218p1h3gxut3ku00u1k1da"));
txBuilder.withValue(value);
RawTransactionrawTx = txBuilder.build(cfx);
// get account from accountManager, `account.send` will sign the tx and send it to blockchainSendTransactionResultresult = account.send(rawTx);
System.out.println(result.getTxHash());
// or you can manually sign and sendStringhexEncodedTx = account.sign(rawTx);
StringtxHash = cfx.sendRawTransaction(hexEncodedTx).sendAndGet();If you just want to transfer some CFX, there is a simpler method account.transfer
Optionopt = newOption();
opt.withChainId(1);
account.waitForNonceUpdated();
Stringresult = account.transfer(opt, newAddress("0x13d2bA4eD43542e7c54fbB6c5fCCb9f269C1f94C"), value);The conflux-rust fullnode support PubSub through websocket, the default port is 12535, you need open it manually.
Now the SDK provide three methods subscribeNewHeads, subscribeLogs, subscribeEpochs you can use to sub respect events.
// initiate a WebSocketService and connect, then use it to create a CfxWebSocketServicewsService = newWebSocketService("ws://localhost:12535/", false);
wsService.connect();
Cfxcfx = Cfx.create(wsService);
// Invoke cfx method BigIntegerepoch = cfx.getEpochNumber().sendAndGet();
System.out.println("Current epoch: " + epoch);
// PubSub Subscribe to incoming events and process incoming eventsfinalFlowable<NewHeadsNotification> events = cfx.subscribeNewHeads();
finalDisposabledisposable = events.subscribe(event -> {
// You can get the detail through gettersSystem.out.println(event.getParams().getResult());
});
// closedisposable.dispose();To simple call a contract method you can use the ContractCall class
packageconflux.sdk.examples;
importconflux.web3j.contract.ContractCall;
importconflux.web3j.types.Address;
importconflux.web3j.contract.abi.DecodeUtil;
importorg.web3j.abi.datatypes.generated.Uint256;
publicclassApp {
publicstaticvoidmain(String[] args) throwsException {
ContractCallcontract = newContractCall(cfx, newAddress("0x824df34537b198d9955c01c4e5a2a68733707b4f", 1));
// passing method name and parameter to `contract.call`// note: parameters should use web3j.abi.datatypes typeStringamount = contract.call("balanceOf", newAddress("0x1386B4185A223EF49592233b69291bbe5a80C527", 1).getABIAddress()).sendAndGet();
BigIntegerbalance = DecodeUtil.decode(amount, Uint256.class);
System.out.print("account balance: ");
System.out.println(balance);
}
}To update a contract's state you need to send a transaction to contract with data info, java-conflux-sdk have some method can do this for you.
For example:
packageconflux.sdk.examples;
importconflux.web3j.Account;
importconflux.web3j.Account.Option;
importconflux.web3j.types.Address;
importorg.web3j.abi.datatypes.generated.Uint256;
publicclassApp {
publicstaticvoidmain(String[] args) throwsException {
StringprivateKey = "0xxxxxx";
intnetId = 1;
AddresscontractAddress = newAddress("0xxxxx", netId);
Addressrecipient = newAddress("0xxxx", netId);
BigIntegeramount = 100;
// create account, then call contract's methodAccountaccount = Account.create(cfx, privateKey);
Optionopt = newOption();
// build transaction option info: nonce, gas, gasPrice and etcStringtxHash = account.call(option, contractAddress, "transfer", recipient.getABIAddress(), newUint256(amount));
System.out.println("tx hash: " + txHash);
}
}Conflux Java SDK also provides some helpful tools:
Account: used for a single account to send multiple transactions and managenonceautomatically.CfxUnit: provides utilities for unit conversion.ContractCall: query contract data without ABI file.DecodeUtilandTupleDecoder: provides utilities for ABI decode.Recall: diagnose failed transactions.
Conflux network's vm is compatible with evm, and a lot web3j functionality can directly used on Conflux network,
For example Sign, encode and so on.