BAEL-3091: The Prototype Pattern in Java (changed code based on valid comments from a reader)

This commit is contained in:
Vivek Balasubramaniam
2019-10-29 22:27:15 +05:30
parent db85c8f275
commit d3d5b060e7
20517 changed files with 1642290 additions and 0 deletions
@@ -0,0 +1,16 @@
package com.baeldung.ethereumj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.support.SpringBootServletInitializer;
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@SpringBootApplication
public class ApplicationMain extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ApplicationMain.class, args);
}
}
@@ -0,0 +1,9 @@
package com.baeldung.ethereumj;
public class Constants {
public static final String ENDPOINT_ONE = "/api/get/bestblock/";
public static final String ENDPOINT_TWO = "/api/get/difficulty/";
public static final String RESPONSE_TYPE ="application/json/";
}
@@ -0,0 +1,25 @@
package com.baeldung.ethereumj.beans;
import com.baeldung.ethereumj.listeners.EthListener;
import org.ethereum.core.Block;
import org.ethereum.facade.Ethereum;
import org.ethereum.facade.EthereumFactory;
import java.math.BigInteger;
public class EthBean {
private Ethereum ethereum;
public void start() {
this.ethereum = EthereumFactory.createEthereum();
this.ethereum.addListener(new EthListener(ethereum));
}
public Block getBestBlock() {
return this.ethereum.getBlockchain().getBestBlock();
}
public BigInteger getTotalDifficulty() {
return this.ethereum.getBlockchain().getTotalDifficulty();
}
}
@@ -0,0 +1,18 @@
package com.baeldung.ethereumj.config;
import com.baeldung.ethereumj.beans.EthBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.Executors;
@Configuration
public class EthConfig {
@Bean
EthBean ethBeanConfig() throws Exception {
EthBean eBean = new EthBean();
Executors.newSingleThreadExecutor().submit(eBean::start);
return eBean;
}
}
@@ -0,0 +1,44 @@
package com.baeldung.ethereumj.controllers;
import com.baeldung.ethereumj.Constants;
import com.baeldung.ethereumj.beans.EthBean;
import com.baeldung.ethereumj.transfer.EthResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
@RestController
public class EthController {
@Autowired
EthBean ethBean;
@Autowired
private ServletContext servletContext;
private Logger l = LoggerFactory.getLogger(EthController.class);
@RequestMapping(Constants.ENDPOINT_ONE)
public EthResponse getBestBlock() {
l.debug("Request received - fetching best block.");
EthResponse r = new EthResponse();
r.setResponse(ethBean.getBestBlock().toString());
return r;
}
@RequestMapping(Constants.ENDPOINT_TWO)
public EthResponse getTotalDifficulty() {
l.debug("Request received - calculating total difficulty.");
EthResponse r = new EthResponse();
r.setResponse(ethBean.getTotalDifficulty().toString());
return r;
}
@PostConstruct
public void showIt() {
l.debug(servletContext.getContextPath());
}
}
@@ -0,0 +1,71 @@
package com.baeldung.ethereumj.listeners;
import org.ethereum.core.Block;
import org.ethereum.core.TransactionReceipt;
import org.ethereum.facade.Ethereum;
import org.ethereum.listener.EthereumListenerAdapter;
import org.ethereum.util.BIUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.util.List;
public class EthListener extends EthereumListenerAdapter {
private Logger l = LoggerFactory.getLogger(EthListener.class);
private Ethereum ethereum;
private boolean syncDone = false;
private static final int thou = 1000;
private void out(String t) {
l.info(t);
}
private String calcNetHashRate(Block block) {
String response = "Net hash rate not available";
if (block.getNumber() > thou) {
long timeDelta = 0;
for (int i = 0; i < thou; ++i) {
Block parent = ethereum
.getBlockchain()
.getBlockByHash(block.getParentHash());
timeDelta += Math.abs(block.getTimestamp() - parent.getTimestamp());
}
response = String.valueOf(block
.getDifficultyBI()
.divide(BIUtil.toBI(timeDelta / thou))
.divide(new BigInteger("1000000000"))
.doubleValue()) + " GH/s";
}
return response;
}
public EthListener(Ethereum ethereum) {
this.ethereum = ethereum;
}
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (syncDone) {
out("Net hash rate: " + calcNetHashRate(block));
out("Block difficulty: " + block.getDifficultyBI().toString());
out("Block transactions: " + block.getTransactionsList().toString());
out("Best block (last block): " + ethereum
.getBlockchain()
.getBestBlock().toString());
out("Total difficulty: " + ethereum
.getBlockchain()
.getTotalDifficulty().toString());
}
}
@Override
public void onSyncDone(SyncState state) {
out("onSyncDone " + state);
if (!syncDone) {
out(" ** SYNC DONE ** ");
syncDone = true;
}
}
}
@@ -0,0 +1,14 @@
package com.baeldung.ethereumj.transfer;
public class EthResponse {
private String response;
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
@@ -0,0 +1,41 @@
package com.baeldung.web3j;
import com.baeldung.web3j.contracts.Greeting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.Contract;
import org.web3j.tx.ManagedTransaction;
public class Template {
private Logger l = LoggerFactory.getLogger(Template.class);
private void deployContract() throws Exception{
Web3j web3j = Web3j.build(new HttpService("https://rinkeby.infura.io/<your_token>"));
Credentials credentials =
WalletUtils.loadCredentials(
"<password>",
"/path/to/<walletfile>");
Greeting contract = Greeting.deploy(
web3j, credentials,
ManagedTransaction.GAS_PRICE, Contract.GAS_LIMIT,
"Hello blockchain world!").send();
String contractAddress = contract.getContractAddress();
l.debug("Smart contract deployed to address "+ contractAddress);
l.debug("Value stored in remote smart contract: "+ contract.greet().send());
TransactionReceipt transactionReceipt = contract.setGreeting("Well hello again").send();
l.debug("New value stored in remote smart contract: "+ contract.greet().send());
}
}
@@ -0,0 +1,68 @@
package com.baeldung.web3j.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import java.util.concurrent.Executor;
@Configuration
@EnableWebMvc
@EnableAsync
@ComponentScan("com.baeldung.web3j")
public class AppConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
/**
* Static resource locations including themes
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**/*")
.addResourceLocations("/", "/resources/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
/**
* View resolver for JSP
*/
@Bean
public UrlBasedViewResolver viewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
/**
* Configuration for async thread bean
*
* More: https://docs.spring.io/autorepo/docs/spring-framework/5.0.3.RELEASE/javadoc-api/org/springframework/scheduling/SchedulingTaskExecutor.html
*/
@Bean
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("CsvThread");
executor.initialize();
return executor;
}
}
@@ -0,0 +1,28 @@
package com.baeldung.web3j.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
//AbstractDispatcherServletInitializer override DEFAULT_SERVLET_NAME
@Override
protected String getServletName() {
return "dispatcher";
}
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{AppConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
@@ -0,0 +1,18 @@
package com.baeldung.web3j.constants;
public class Constants {
public static final String API_BLOCK = "/api/block";
public static final String API_ACCOUNTS = "/api/accounts";
public static final String API_TRANSACTIONS = "/api/transactions";
public static final String API_BALANCE = "/api/balance";
public static final String GENERIC_EXCEPTION = "Exception encountered!";
public static final String PLEASE_SUPPLY_REAL_DATA = "Please Supply Real Data!";
public static final String DEFAULT_ADDRESS = "0x281055afc982d96fab65b3a49cac8b878184cb16";
public static final String DEFAULT_CONTRACT_ADDRESS = "00000000000000000000";
}
@@ -0,0 +1,74 @@
package com.baeldung.web3j.contracts;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tx.Contract;
import org.web3j.tx.TransactionManager;
/**
* <p>Auto generated code.
* <p><strong>Do not modify!</strong>
* <p>Please use the <a href="https://docs.web3j.io/command_line.html">web3j command line tools</a>,
* or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the
* <a href="https://github.com/web3j/web3j/tree/master/codegen">codegen module</a> to update.
*
* <p>Generated with web3j version 3.3.1.
*/
public class Example extends Contract {
private static final String BINARY = "0x60606040523415600e57600080fd5b60848061001c6000396000f300606060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063b818dacd146044575b600080fd5b3415604e57600080fd5b60546056565b005b5600a165627a7a72305820bebcbbdf06550591bc772dfcb0eadc842f95953869feb7a9528bac91487d95240029";
protected static final HashMap<String, String> _addresses;
static {
_addresses = new HashMap<>();
}
protected Example(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);
}
protected Example(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}
public static RemoteCall<Example> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
return deployRemoteCall(Example.class, web3j, credentials, gasPrice, gasLimit, BINARY, "");
}
public static RemoteCall<Example> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
return deployRemoteCall(Example.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, "");
}
public RemoteCall<TransactionReceipt> ExampleFunction() {
final Function function = new Function(
"ExampleFunction",
Arrays.<Type>asList(),
Collections.<TypeReference<?>>emptyList());
return executeRemoteCallTransaction(function);
}
public static Example load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
return new Example(contractAddress, web3j, credentials, gasPrice, gasLimit);
}
public static Example load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
return new Example(contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}
protected String getStaticDeployedAddress(String networkId) {
return _addresses.get(networkId);
}
public static String getPreviouslyDeployedAddress(String networkId) {
return _addresses.get(networkId);
}
}
@@ -0,0 +1,71 @@
package com.baeldung.web3j.contracts;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.Utf8String;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tx.Contract;
import org.web3j.tx.TransactionManager;
/**
* <p>Auto generated code.
* <p><strong>Do not modify!</strong>
* <p>Please use the <a href="https://docs.web3j.io/command_line.html">web3j command line tools</a>,
* or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the
* <a href="https://github.com/web3j/web3j/tree/master/codegen">codegen module</a> to update.
*
* <p>Generated with web3j version 3.3.1.
*/
public class Greeting extends Contract {
private static final String BINARY = "6060604052341561000f57600080fd5b6040516103cc3803806103cc833981016040528080519091019050600181805161003d92916020019061005f565b505060008054600160a060020a03191633600160a060020a03161790556100fa565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100a057805160ff19168380011785556100cd565b828001600101855582156100cd579182015b828111156100cd5782518255916020019190600101906100b2565b506100d99291506100dd565b5090565b6100f791905b808211156100d957600081556001016100e3565b90565b6102c3806101096000396000f30060606040526004361061004b5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663a41368628114610050578063cfae3217146100a3575b600080fd5b341561005b57600080fd5b6100a160046024813581810190830135806020601f8201819004810201604051908101604052818152929190602084018383808284375094965061012d95505050505050565b005b34156100ae57600080fd5b6100b6610144565b60405160208082528190810183818151815260200191508051906020019080838360005b838110156100f25780820151838201526020016100da565b50505050905090810190601f16801561011f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60018180516101409291602001906101ed565b5050565b61014c61026b565b60018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156101e25780601f106101b7576101008083540402835291602001916101e2565b820191906000526020600020905b8154815290600101906020018083116101c557829003601f168201915b505050505090505b90565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061022e57805160ff191683800117855561025b565b8280016001018555821561025b579182015b8281111561025b578251825591602001919060010190610240565b5061026792915061027d565b5090565b60206040519081016040526000815290565b6101ea91905b8082111561026757600081556001016102835600a165627a7a723058206cfb726ed213c2fe842a4c886c8089e918b6de9c6cdfb372fa459eca4840c5740029";
protected Greeting(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);
}
protected Greeting(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}
public RemoteCall<TransactionReceipt> setGreeting(String _message) {
final Function function = new Function(
"setGreeting",
Arrays.<Type>asList(new org.web3j.abi.datatypes.Utf8String(_message)),
Collections.<TypeReference<?>>emptyList());
return executeRemoteCallTransaction(function);
}
public RemoteCall<String> greet() {
final Function function = new Function("greet",
Arrays.<Type>asList(),
Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {}));
return executeRemoteCallSingleValueReturn(function, String.class);
}
public static RemoteCall<Greeting> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, String _message) {
String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.<Type>asList(new org.web3j.abi.datatypes.Utf8String(_message)));
return deployRemoteCall(Greeting.class, web3j, credentials, gasPrice, gasLimit, BINARY, encodedConstructor);
}
public static RemoteCall<Greeting> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, String _message) {
String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.<Type>asList(new org.web3j.abi.datatypes.Utf8String(_message)));
return deployRemoteCall(Greeting.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, encodedConstructor);
}
public static Greeting load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
return new Greeting(contractAddress, web3j, credentials, gasPrice, gasLimit);
}
public static Greeting load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
return new Greeting(contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}
}
@@ -0,0 +1,103 @@
package com.baeldung.web3j.controllers;
import com.baeldung.web3j.constants.Constants;
import com.baeldung.web3j.helpers.TimeHelper;
import com.baeldung.web3j.services.Web3Service;
import com.baeldung.web3j.transfers.ResponseTransfer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.web3j.protocol.core.methods.response.EthAccounts;
import org.web3j.protocol.core.methods.response.EthBlockNumber;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import static com.baeldung.web3j.constants.Constants.GENERIC_EXCEPTION;
@RestController
public class EthereumRestController {
@Autowired
Web3Service web3Service;
@RequestMapping(value = Constants.API_BLOCK, method = RequestMethod.GET)
public Future<ResponseTransfer> getBlock() {
ResponseTransfer responseTransfer = new ResponseTransfer();
Instant start = TimeHelper.start();
return CompletableFuture.supplyAsync(() -> {
try {
EthBlockNumber result = web3Service.getBlockNumber();
responseTransfer.setMessage(result.toString());
} catch (Exception e) {
responseTransfer.setMessage(GENERIC_EXCEPTION);
}
return responseTransfer;
}).thenApplyAsync(result -> {
result.setPerformance(TimeHelper.stop(start));
return result;
});
}
@RequestMapping(value = Constants.API_ACCOUNTS, method = RequestMethod.GET)
public Future<ResponseTransfer> getAccounts() {
ResponseTransfer responseTransfer = new ResponseTransfer();
Instant start = TimeHelper.start();
return CompletableFuture.supplyAsync(() -> {
try {
EthAccounts result = web3Service.getEthAccounts();
responseTransfer.setMessage(result.toString());
} catch (Exception e) {
responseTransfer.setMessage(GENERIC_EXCEPTION);
}
return responseTransfer;
}).thenApplyAsync(result -> {
result.setPerformance(TimeHelper.stop(start));
return result;
});
}
@RequestMapping(value = Constants.API_TRANSACTIONS, method = RequestMethod.GET)
public Future<ResponseTransfer> getTransactions() {
ResponseTransfer responseTransfer = new ResponseTransfer();
Instant start = TimeHelper.start();
return CompletableFuture.supplyAsync(() -> {
try {
EthGetTransactionCount result = web3Service.getTransactionCount();
responseTransfer.setMessage(result.toString());
} catch (Exception e) {
responseTransfer.setMessage(GENERIC_EXCEPTION);
}
return responseTransfer;
}).thenApplyAsync(result -> {
result.setPerformance(TimeHelper.stop(start));
return result;
});
}
@RequestMapping(value = Constants.API_BALANCE, method = RequestMethod.GET)
public Future<ResponseTransfer> getBalance() {
ResponseTransfer responseTransfer = new ResponseTransfer();
Instant start = TimeHelper.start();
return CompletableFuture.supplyAsync(() -> {
try {
EthGetBalance result = web3Service.getEthBalance();
responseTransfer.setMessage(result.toString());
} catch (Exception e) {
responseTransfer.setMessage(GENERIC_EXCEPTION);
}
return responseTransfer;
}).thenApplyAsync(result -> {
result.setPerformance(TimeHelper.stop(start));
return result;
});
}
}
@@ -0,0 +1,16 @@
package com.baeldung.web3j.helpers;
import java.time.Duration;
import java.time.Instant;
public class TimeHelper {
public static Instant start() {
return Instant.now();
}
public static Duration stop(Instant start) {
Instant end = Instant.now();
return Duration.between(start, end);
}
}
@@ -0,0 +1,151 @@
package com.baeldung.web3j.services;
import com.baeldung.web3j.contracts.Example;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.datatypes.Function;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthAccounts;
import org.web3j.protocol.core.methods.response.EthBlockNumber;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.Contract;
import org.web3j.tx.ManagedTransaction;
import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import static com.baeldung.web3j.constants.Constants.DEFAULT_ADDRESS;
import static com.baeldung.web3j.constants.Constants.GENERIC_EXCEPTION;
import static com.baeldung.web3j.constants.Constants.PLEASE_SUPPLY_REAL_DATA;
@Service
public class Web3Service {
private Web3j web3j = Web3j.build(new HttpService());
//Create and Init the default Web3J connection
public void customInit(String provider) {
this.web3j = Web3j.build(new HttpService(provider));
}
//Convert to and from supplied contract ABI bytecode
public static String toBinary(String bytecode) {
return bytecode.replaceFirst("^0x", "");
}
public static String toByteCode(String binary) {
return "0x" + binary;
}
public EthBlockNumber getBlockNumber() {
EthBlockNumber result = new EthBlockNumber();
try {
result = this.web3j.ethBlockNumber().sendAsync().get();
} catch (Exception ex) {
System.out.println(GENERIC_EXCEPTION);
}
return result;
}
public EthAccounts getEthAccounts() {
EthAccounts result = new EthAccounts();
try {
result = this.web3j.ethAccounts().sendAsync().get();
} catch (Exception ex) {
System.out.println(GENERIC_EXCEPTION);
}
return result;
}
public EthGetTransactionCount getTransactionCount() {
EthGetTransactionCount result = new EthGetTransactionCount();
try {
result = this.web3j.ethGetTransactionCount(DEFAULT_ADDRESS, DefaultBlockParameter.valueOf("latest")).sendAsync().get();
} catch (Exception ex) {
System.out.println(GENERIC_EXCEPTION);
}
return result;
}
public EthGetBalance getEthBalance() {
EthGetBalance result = new EthGetBalance();
try {
result = this.web3j.ethGetBalance(DEFAULT_ADDRESS, DefaultBlockParameter.valueOf("latest")).sendAsync().get();
} catch (Exception ex) {
System.out.println(GENERIC_EXCEPTION);
}
return result;
}
public String fromScratchContractExample() {
String contractAddress = "";
try {
//Create a wallet
WalletUtils.generateNewWalletFile("PASSWORD", new File("/path/to/destination"), true);
//Load the credentials from it
Credentials credentials = WalletUtils.loadCredentials("PASSWORD", "/path/to/walletfile");
//Deploy contract to address specified by wallet
Example contract = Example.deploy(this.web3j,
credentials,
ManagedTransaction.GAS_PRICE,
Contract.GAS_LIMIT).send();
//Het the address
contractAddress = contract.getContractAddress();
} catch (Exception ex) {
System.out.println(PLEASE_SUPPLY_REAL_DATA);
return PLEASE_SUPPLY_REAL_DATA;
}
return contractAddress;
}
@Async
public String sendTx() {
String transactionHash = "";
try {
List inputParams = new ArrayList();
List outputParams = new ArrayList();
Function function = new Function("fuctionName", inputParams, outputParams);
String encodedFunction = FunctionEncoder.encode(function);
BigInteger nonce = BigInteger.valueOf(100);
BigInteger gasprice = BigInteger.valueOf(100);
BigInteger gaslimit = BigInteger.valueOf(100);
Transaction transaction = Transaction.createFunctionCallTransaction("FROM_ADDRESS", nonce, gasprice, gaslimit, "TO_ADDRESS", encodedFunction);
org.web3j.protocol.core.methods.response.EthSendTransaction transactionResponse = web3j.ethSendTransaction(transaction).sendAsync().get();
transactionHash = transactionResponse.getTransactionHash();
} catch (Exception ex) {
System.out.println(PLEASE_SUPPLY_REAL_DATA);
return PLEASE_SUPPLY_REAL_DATA;
}
return transactionHash;
}
}
@@ -0,0 +1,28 @@
package com.baeldung.web3j.transfers;
import java.time.Duration;
public class ResponseTransfer {
public ResponseTransfer() {}
private Duration performance;
private String message;
public Duration getPerformance() {
return performance;
}
public void setPerformance(Duration performance) {
this.performance = performance;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}