nem-apps-lib icon indicating copy to clipboard operation
nem-apps-lib copied to clipboard

Semantic Java API Library for NEM Platform

NEM Apps Library

Java API library for NEM.io blockchain platform. This directly calls the https://github.com/NEMModules/nem.core that then calls the endpoints based on https://bob.nem.ninja/docs/

Library has the following features/functionalities

  • Initiate a transfer transactoin (including mosaic)
  • Initiate a multisig transaction (including mosaic)
  • Cosign a multisig transaction
  • Configurable Custom Fee Calculation
  • Get All Transaction (Confirmed/Unconfirmed/Incoming/Outgoing) for an Account
  • Get All Owned Mosaics of an Account
  • Get Block and Chain Info
  • Node Information and Check Node Heartbeats
  • Transaction Monitoring (using nem-transaction-monitor)

Technology Stack

  • Java 1.8
  • nem.core

How to build

Make sure to clone NEMModules fork of nem.core and build.
git clone https://github.com/NEMPH/nem.core.git
cd nem.core
mvn clean install

build the nem-apps-lib after.

git clone https://github.com/NEMPH/nem-apps-lib.git
cd nem-apps-lib
mvn clean install

Import it as a maven dependency

<dependency>
    <groupId>io.nem.apps</groupId>
    <artifactId>nem-apps-lib</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

Configuration Setup

Before starting, make sure you have the node endpoint is all set. Note that this should only be called once.

ConfigurationBuilder.nodeNetworkName("<network name>")
    .nodeNetworkProtocol("http")
    .nodeNetworkUri("<node url>")
    .nodeNetworkPort("7895")
    .setup();
    

You can also change the node endpoint on the fly.

Globals.setNodeEndpoint(new NodeEndpoint("http","<node url>",7895));

Transactions

Use the following set of builders to create transactions.

Transfer Transaction

TransferTransactionBuilder.sender(new Account(this.senderPrivateKeyPair))
    .recipient(new Account(this.recipientPublicKeyPair))
    .amount(0l)
    .buildAndSendTransaction();

Multisig Transaction


TransferTransaction transaction = TransferTransactionBuilder
    .sender(new Account(this.senderPrivateKeyPair)) // multisig account
    .recipient(new Account(this.recipientPublicKeyPair)) 
    .amount(0l)
    .buildTransaction();
    
MultisigTransactionBuilder.sender(this.senderPrivateAccount) // co-signer as sender
    .otherTransaction(transaction)
    .buildAndSendMultisigTransaction();
	

MultisigSignature Transaction

Single Signer

MultisigSignatureTransactionBuilder.multisig(this.multisigPublicAccount) // multisig account
    .signer(this.senderPrivateAccount) // signer
    .otherTransaction(Hash.fromHexString("hash")) // hash
    .buildMultisigSignatureTransaction();

Multiple Signer

MultisigSignatureTransactionBuilder.multisig(this.multisigPublicAccount) // multisig
		.startAssignSigners()
			.addSigner(this.senderPrivateAccount1) // signer 1
			.addSigner(this.senderPrivateAccount2) // signer 2
		.endAssignSigners()
	.otherTransaction(Hash.fromHexString("hash"))
	.coSign();

Transaction Callbacks

Developers can catch callbacks before and after a transaction is made. All the developer needs to do is define a Callback class and use it either on per Transaction or for All Transaction.

Fee Calculation

Fees can be calculated either on a Global level or per transaction.

Global Level Fees

Fees can also be configurable. With the API, the developers can put in their own Fee Calculation on either per Transaction or for All Transaction.

ConfigurationBuilder.nodeNetworkName("<network name>").nodeNetworkProtocol("http")
	.nodeNetworkUri("<node url>").nodeNetworkPort("7895")
	.transactionFee(new TransactionFeeCalculatorAfterFork()) // global
	.setup();

Transaction Level Fees

Fee on the Transaction

fee can also be set on the transaction level via the fee() method.

TransferTransactionBuilder
    .sender(new Account(this.senderPrivateKeyPair))
    .recipient(new Account(this.recipientPublicKeyPair))
    .amount(0l)
    .fee(Amount.fromMicroNem(0l)) // fee
    .buildAndSendTransaction();

Fee Calculation via Fee Calculation Object

fee calculation can also be set on the transaction level using the feeCalculator() method.

TransferTransactionBuilder
    .sender(new Account(this.senderPrivateKeyPair))
    .recipient(new Account(this.recipientPublicKeyPair))
    .amount(0l)
    .feeCalculator(new TransactionFeeCalculatorAfterForkForApp()) // custom fee calculator
    .buildAndSendTransaction();

Decode/Encode Secure Message/Payload

Use the following static methods to encode and decode Secure Message Payloads.

Encode

SecureMessageEncoder.encode(Account senderPrivateKey, Account recipientPublicKey, String message) 
//or 
SecureMessageEncoder.encode(String senderPrivateKey, String recipientPublicKey, String message) 

Decode

SecureMessageDecoder.decode(Account recipientPrivateKey, Account senderPublicKey, String encryptedPayload) SecureMessageDecoder.decode(Account recipientPrivateKey, Account senderPublicKey, byte[] encryptedPayload) 
//or 
SecureMessageDecoder.decode(String recipientPrivateKey, String senderPublicKey, String encryptedPayload)
SecureMessageDecoder.decode(String recipientPrivateKey, String senderPublicKey, byte[] encryptedPayload) 

Data Encryption (Encrypt/Decrypt) from nem.core


CryptoEngine engine = CryptoEngines.ed25519Engine();

//encrypt
byte[] encrypted = engine
		.createBlockCipher(
				new KeyPair(PrivateKey.fromHexString(xPvkey), engine),
				new KeyPair(PublicKey.fromHexString(xPubkey), engine))
		.encrypt("hello".getBytes());

// decrypt
byte[] decrypted = engine
		.createBlockCipher(
				new KeyPair(PublicKey.fromHexString(xPubkey), engine),
				new KeyPair(PrivateKey.fromHexString(xPvkey), engine)).decrypt(encrypted);

Accounts

Generate a new Account

GeneratedAccount AccountApi.generateAccount()

Get Account Info using Address

AccountMetaDataPair AccountApi.getAccountByAddress(String address) 

Get All Transactions for an Account

List<TransactionMetaDataPair> AccountApi.getAllTransactions(String address)

Get All Confirmed Transactions for an Account

List<TransactionMetaDataPair> AccountApi.getAllConfirmedTransactions(String address)

Get All Unconfirmed Transactions for an Account

List<TransactionMetaDataPair> AccountApi.getAllUnconfirmedTransactions(String address)

Get All Incoming Transactions for an Account

List<TransactionMetaDataPair> AccountApi.getIncomingTransactions(String address)

Get All Outgoing Transactions for an Account

List<TransactionMetaDataPair> AccountApi.getOutgoingTransactions(String address)

Get All Mosaics for an Account

List<Mosaic> AccountApi.getAccountOwnedMosaic(String address)

Blocks

Get Block by Block Height

Block BlockApi.getBlockByHeight(int blockHeight)

Get Block After Given Block Height

Block getBlockAfterGivenBlockHeight(int height) 

Chains

Get Chain Height

Block ChainApi.getChainHeight()

Get Chain Last Score

Block ChainApi.getChainScore()

Get Chain Last Block

Block ChainApi.getChainLastBlock()

Validations

Validate if Address is Valid

boolean ValidationApi.isAddressValid(String address)
boolean ValidationApi.isAddressValid(String address, NodeEndpoint nodeEndpoint)
boolean ValidationApi.isAddressValid(String address, String protocol, String host, int port)
boolean ValidationApi.isAddressPatternValid(String address)

Nodes

Check Node Info

Node NodeApi.getNodeInfo()

Check Node Extenteded Info

NisNodeInfo NodeApi.getNodeExtendedInfo()

Check Nem Node Heartbeat

NemRequestResult NodeApi.getNemNodeHeartBeat()

Incorporating Transaction Monitor

You can incorporate the nem-transaction-monitor library to monitor the transactions that's coming in.
git clone https://github.com/NEMPH/nem-transaction-monitor.git
cd nem-transaction-monitor
mvn clean install

Import maven dependency

<dependency>
    <groupId>io.nem.apps</groupId>
    <artifactId>nem-transaction-monitor</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

WsNemTransactionMonitor.init().host("<node url>").port("7895").wsPort("7778")
	.addressToMonitor("MDYSYWVWGC6JDD7BGE4JBZMUEM5KXDZ7J77U4X2Y") // address to monitor
	.subscribe(io.nem.utils.Constants.URL_WS_TRANSACTIONS, new TransactionMonitor()) // multiple subscription and a handler
	.subscribe(io.nem.utils.Constants.URL_WS_UNCONFIRMED, new UnconfirmedTransactionMonitor())
	.monitor(); // trigger the monitoring process

Custom Transaction Monitor

You can create your own handler to handle the incoming payload.
public class CustomTransactionMonitor implements TransactionMonitorHandler {
	@Override
	public Type getPayloadType(StompHeaders headers) {
		return String.class;
	}
	@Override
	public void handleFrame(StompHeaders headers, Object payload) {
		System.out.println(payload.toString()); // handle the payload.
	}
}

Support

Need help integration your Java Application with NEM.io Platform? I can definitely help you with that, send me a message via

telegram

Tips are appreciated but not required. :bowtie: :muscle: :metal:
XEM: NA6IT2-ZSTQLT-YO223Z-ZMH2J7-2GVG7G-ZY72FN-47IF
BTC: 3JYAYPxN9RL4UvbxMd1svbQynMpFbf5ehy

Copyright (c) 2017