aelf-sdk.java - aelf Java API
Introduction
aelf-sdk.java is a set of libraries that allow interaction with a local or remote aelf node using an HTTP connection. This documentation guides you through installing and running aelf-sdk.java, along with providing API reference documentation and examples.
For more information, you can check out the repository.
Adding aelf-sdk.java Package
To add the aelf-sdk.java package to your project, use the following Maven dependency:
<!-- https://mvnrepository.com/artifact/io.aelf/aelf-sdk -->
<dependency>
    <groupId>io.aelf</groupId>
    <artifactId>aelf-sdk</artifactId>
    <version>0.X.X</version>
</dependency>
Examples
Create Instance
Create a new instance of AElfClient, and set the URL of an aelf chain node.
import AElf.Client.Service;
// Create a new instance of AElfClient, change the URL if needed
AElfClient client = new AElfClient("http://127.0.0.1:1235");
Test Connection
Check if the aelf chain node is connectable.
boolean isConnected = client.isConnected();
Initiate a Transfer Transaction
// Get token contract address.
String tokenContractAddress = client.getContractAddressByName(privateKey, Sha256.getBytesSha256("AElf.ContractNames.Token"));
Client.Address.Builder to = Client.Address.newBuilder();
to.setValue(ByteString.copyFrom(Base58.decodeChecked("7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz")));
Client.Address toObj = to.build();
TokenContract.TransferInput.Builder paramTransfer = TokenContract.TransferInput.newBuilder();
paramTransfer.setTo(toObj);
paramTransfer.setSymbol("ELF");
paramTransfer.setAmount(1000000000);
paramTransfer.setMemo("transfer in demo");
TokenContract.TransferInput paramTransferObj = paramTransfer.build();
String ownerAddress = client.getAddressFromPrivateKey(privateKey);
Transaction.Builder transactionTransfer = client.generateTransaction(ownerAddress, tokenContractAddress, "Transfer", paramTransferObj.toByteArray());
Transaction transactionTransferObj = transactionTransfer.build();
transactionTransfer.setSignature(ByteString.copyFrom(ByteArrayHelper.hexToByteArray(client.signTransaction(privateKey, transactionTransferObj))));
transactionTransferObj = transactionTransfer.build();
// Send the transfer transaction to aelf chain node.
SendTransactionInput sendTransactionInputObj = new SendTransactionInput();
sendTransactionInputObj.setRawTransaction(Hex.toHexString(transactionTransferObj.toByteArray()));
SendTransactionOutput sendResult = client.sendTransaction(sendTransactionInputObj);
Thread.sleep(4000);
// After the transaction is mined, query the execution results.
TransactionResultDto transactionResult = client.getTransactionResult(sendResult.getTransactionId());
System.out.println(transactionResult.getStatus());
// Query account balance.
Client.Address.Builder owner = Client.Address.newBuilder();
owner.setValue(ByteString.copyFrom(Base58.decodeChecked(ownerAddress)));
Client.Address ownerObj = owner.build();
TokenContract.GetBalanceInput.Builder paramGetBalance = TokenContract.GetBalanceInput.newBuilder();
paramGetBalance.setSymbol("ELF");
paramGetBalance.setOwner(ownerObj);
TokenContract.GetBalanceInput paramGetBalanceObj = paramGetBalance.build();
Transaction.Builder transactionGetBalance = client.generateTransaction(ownerAddress, tokenContractAddress, "GetBalance", paramGetBalanceObj.toByteArray());
Transaction transactionGetBalanceObj = transactionGetBalance.build();
String signature = client.signTransaction(privateKey, transactionGetBalanceObj);
transactionGetBalance.setSignature(ByteString.copyFrom(ByteArrayHelper.hexToByteArray(signature)));
transactionGetBalanceObj = transactionGetBalance.build();
ExecuteTransactionDto executeTransactionDto = new ExecuteTransactionDto();
executeTransactionDto.setRawTransaction(Hex.toHexString(transactionGetBalanceObj.toByteArray()));
String transactionGetBalanceResult = client.executeTransaction(executeTransactionDto);
TokenContract.GetBalanceOutput balance = TokenContract.GetBalanceOutput.getDefaultInstance().parseFrom(ByteArrayHelper.hexToByteArray(transactionGetBalanceResult));
System.out.println(balance.getBalance());
This guide provides basic steps to interact with an aelf node using the aelf-sdk.java library. For more detailed information and advanced usage, please refer to the repository documentation.
Web API
You can see how the Web API of the node works at {chainAddress}/swagger/index.html. For example, if you are using a local address, it would be: http://127.0.0.1:1235/swagger/index.html.
The usage of these methods is based on the AElfClient instance. So, if you don’t have one, please create it:
import AElf.Client.Service;
// Create a new instance of AElfClient, change the URL if needed
AElfClient client = new AElfClient("http://127.0.0.1:1235");
GetChainStatus
Get the current status of the blockchain.
Web API path: /api/blockChain/chainStatus
Parameters: None
Returns: ChainStatusDto
ChainId- StringBranches- HashMap<String, Long>NotLinkedBlocks- HashMap<String, String>LongestChainHeight- longLongestChainHash- StringGenesisBlockHash- StringGenesisContractAddress- StringLastIrreversibleBlockHash- StringLastIrreversibleBlockHeight- longBestChainHash- StringBestChainHeight- long
Example:
client.getChainStatus();
GetContractFileDescriptorSet
Get the protobuf definitions related to a contract.
Web API path: /api/blockChain/contractFileDescriptorSet
Parameters:
contractAddress- String (address of a contract)
Returns: byte[]
Example:
client.getContractFileDescriptorSet(address);
GetBlockHeight
Get the current best height of the chain.
Web API path: /api/blockChain/blockHeight
Parameters:: None
Returns: long
Example:
client.getBlockHeight();
GetBlock
Get block information by block hash.
Web API path: /api/blockChain/block
Parameters:
blockHash- StringincludeTransactions- boolean (true to include transaction ids list in the block, false otherwise)
Returns:
BlockDtoBlockHash- StringHeader- BlockHeaderDtoPreviousBlockHash- StringMerkleTreeRootOfTransactions- StringMerkleTreeRootOfWorldState- StringExtra- StringHeight- longTime- DateChainId- StringBloom- StringSignerPubkey- String
Body- BlockBodyDtoTransactionsCount- intTransactions- ListtransactionId- String
Example:
client.getBlockByHash(blockHash);
GetBlockByHeight
Web API path: /api/blockChain/blockByHeight
Parameters:
blockHeight- longincludeTransactions- boolean (true to include transaction ids list in the block, false otherwise)
Returns:
BlockDtoBlockHash- StringHeader- BlockHeaderDtoPreviousBlockHash- StringMerkleTreeRootOfTransactions- StringMerkleTreeRootOfWorldState- StringExtra- StringHeight- longTime- DateChainId- StringBloom- StringSignerPubkey- String
Body- BlockBodyDtoTransactionsCount- intTransactions- ListtransactionId- String
Example:
client.getBlockByHeight(height);
GetTransactionResult
Web API path: /api/blockChain/transactionResult
Parameters:
transactionId- String
Returns: TransactionResultDto
jsonTransactionId- StringStatus- StringLogs- ListAddress- StringName- StringIndexed- ListNonIndexed- String
Bloom- StringBlockNumber- NumberTransaction- ListFrom- StringTo- StringRefBlockNumber- NumberRefBlockPrefix- StringMethodName- StringParams- jsonSignature- String
ReadableReturnValue- jsonError- String
Example:
client.getTransactionResult(transactionId);
GetTransactionResults
Web API path: /api/blockChain/transactionResults
Parameters:
blockHash- Stringoffset- intlimit- int
Returns: List<TransactionResultDto> - The array of transaction results
Example:
client.getTransactionResults(blockHash, 0, 10);
GetTransactionPoolStatus
Web API path: /api/blockChain/transactionPoolStatus
Parameters:: None
Returns:
TransactionPoolStatusOutputQueued- intValidated- int
Example:
client.getTransactionPoolStatus();
SendTransaction
Web API path: /api/blockChain/sendTransaction
Method: POST
Parameters:
SendTransactionInput- Serialization of data into protobuf format:RawTransaction- String
Returns:
SendTransactionOutputTransactionId- String
Example:
client.sendTransaction(input);
SendRawTransaction
Web API path: /api/blockChain/sendTransaction
Method: POST
Parameters:
SendRawTransactionInput- Serialization of data into protobuf format:Transaction- StringSignature- StringReturnTransaction- boolean
Returns:
SendRawTransactionOutputTransactionId- StringTransaction- TransactionDto
Example:
client.sendRawTransaction(input);
SendTransactions
Broadcast multiple transactions.
Web API path: /api/blockChain/sendTransactions
Method: POST
Parameters:
SendTransactionsInput- Serialization of data into protobuf format:RawTransactions- String
Returns: List<String>
Example:
client.sendTransactions(input);
CreateRawTransaction
Create an unsigned serialized transaction.
Web API path: /api/blockChain/rawTransaction
Method: POST
Parameters:
CreateRawTransactionInputFrom- StringTo- StringRefBlockNumber- longRefBlockHash- StringMethodName- StringParams- String
Returns:
CreateRawTransactionOutput- Serialization of data into protobuf format:RawTransaction- String
Example:
client.createRawTransaction(input);
ExecuteTransaction
Web API path: /api/blockChain/executeTransaction
Method: POST
Parameters:
ExecuteTransactionDto- Serialization of data into protobuf format:RawTransaction- String
Returns: String
Example:
client.executeTransaction(input);
ExecuteRawTransaction
Web API path: /api/blockChain/executeRawTransaction
Method: POST
Parameters:
ExecuteRawTransactionDto- Serialization of data into protobuf format:RawTransaction- StringSignature- String
Returns: String
Example:
client.executeRawTransaction(input);
GetPeers
Get peer information about the connected network nodes.
Web API path: /api/net/peers
Parameters:
withMetrics- boolean
Returns:
List<PeerDto>IpAddress- StringProtocolVersion- intConnectionTime- longConnectionStatus- StringInbound- booleanBufferedTransactionsCount- intBufferedBlocksCount- intBufferedAnnouncementsCount- intNodeVersion- StringRequestMetrics- List<RequestMetric>RoundTripTime- longMethodName- StringInfo- StringRequestTime- String
Example:
client.getPeers(false);
AddPeer
Attempts to add a node to the connected network nodes.
Web API path: /api/net/peer
Method: POST
Parameters:
AddPeerInputAddress- String
Returns: boolean
Example:
client.addPeer("127.0.0.1:7001");
RemovePeer
Attempts to remove a node from the connected network nodes.
Web API path: /api/net/peer
Method: DELETE
Parameters:
Address- String
Returns: boolean
Example:
client.removePeer("127.0.0.1:7001");
CalculateTransactionFee
Estimate transaction fee.
Web API path: /api/blockChain/calculateTransactionFee
Method: POST
Parameters:
CalculateTransactionFeeInputRawTransaction- String
Returns:
CalculateTransactionFeeOutputSuccess- booleanTransactionFee- HashMap<String, Long>ResourceFee- HashMap<String, Long>
Example:
CalculateTransactionFeeOutput output = client.calculateTransactionFee(input);
GetNetworkInfo
Web API path: /api/net/networkInfo
Parameters: None
Returns:
NetworkInfoOutputVersion- StringProtocolVersion- intConnections- int
Example:
client.getNetworkInfo();
AElf Client
IsConnected
Verify whether this SDK successfully connects to the chain.
Parameters: None
Returns: boolean
Example:
client.isConnected();
GetGenesisContractAddress
Parameters: None
Returns: String
Example:
client.getGenesisContractAddress();
GetContractAddressByName
Get the address of a contract by the given contract name hash.
Parameters::
privateKey- StringcontractNameHash- byte[]
Returns: String
Example:
client.getContractAddressByName(privateKey, contractNameHash);
GenerateTransaction
Build a transaction from the input parameters.
Parameters:
from- Stringto- StringmethodName- Stringinput- byte[]
Returns: Transaction
Example:
client.generateTransaction(from, to, methodName, input);
GetFormattedAddress
Convert the Address to the displayed string: symbol_base58-string_base58-String-chain-id.
Parameters:
privateKey- Stringaddress- String
Returns: String
Example:
client.getFormattedAddress(privateKey, address);
SignTransaction
Parameters:
privateKeyHex- Stringtransaction- Transaction
Returns: String
Example:
client.signTransaction(privateKeyHex, transaction);
GetAddressFromPubKey
Parameters:
pubKey- String
Returns: String
Example:
client.getAddressFromPubKey(pubKey);
GetAddressFromPrivateKey
Parameters:
privateKey- String
Returns: String
Example:
client.getAddressFromPrivateKey(privateKey);
GenerateKeyPairInfo
Parameters: None
Returns:
- 
KeyPairInfoPrivateKey- StringPublicKey- StringAddress- String
 
Example:
client.generateKeyPairInfo();
Supports
- JDK1.8+
 - Log4j2.6.2