diff --git a/src/main/java/com/nynja/walletservice/WalletServiceApplication.java b/src/main/java/com/nynja/walletservice/WalletServiceApplication.java index 2416af03e9e33a1e6ef7730ea2c4c28a8cd9d155..e5dfab0972cd09517cc56ad1a9bad9d77a801fdf 100644 --- a/src/main/java/com/nynja/walletservice/WalletServiceApplication.java +++ b/src/main/java/com/nynja/walletservice/WalletServiceApplication.java @@ -13,5 +13,6 @@ public class WalletServiceApplication { public static void main(String[] args) { SpringApplication.run(WalletServiceApplication.class, args); + } } diff --git a/src/main/java/com/nynja/walletservice/config/ConfigValues.java b/src/main/java/com/nynja/walletservice/config/ConfigValues.java index abfb982b150112526723ea06b1e06a022fccf8bc..d275ea63409d12c23cf925a1a21477ca78dcd580 100644 --- a/src/main/java/com/nynja/walletservice/config/ConfigValues.java +++ b/src/main/java/com/nynja/walletservice/config/ConfigValues.java @@ -42,7 +42,14 @@ public class ConfigValues { // .orElseThrow(newExceptionWithMessage(CHAIN_ID_NOT_FOUND, chainId)); //} public NetworkProperties getNetworkProps(String chainId) { - String chainId_str = (chainId.equals("1")?"one":(chainId.equals("4")?"four":"")); + + String chainId_str = (chainId.equals("1")?"one":(chainId.equals("4")?"four":"")); + + if(chainId.equals("one") || chainId.equals("four")){ + chainId_str = chainId; + } + + return Optional.ofNullable(networks.get(chainId_str)) .orElseThrow(newExceptionWithMessage(CHAIN_ID_NOT_FOUND, chainId)); } diff --git a/src/main/java/com/nynja/walletservice/constant/Constants.java b/src/main/java/com/nynja/walletservice/constant/Constants.java index 1ce15ee8850f904c7ac75e952d8df9c119307a3a..62971863f8478503efcdfc5eb008c09c0cc35866 100644 --- a/src/main/java/com/nynja/walletservice/constant/Constants.java +++ b/src/main/java/com/nynja/walletservice/constant/Constants.java @@ -8,8 +8,14 @@ import java.util.function.Supplier; public interface Constants { + interface HttpStatus { + short SUCCESS_STATUS_CODE = 200; + + } + interface RestApi { String API_VERSION = "/api.v.1.0/"; + String API_VERSION_V2 = "/api.v.2.0/"; String ENTITIES_RETRIEVED = "Entities retrieved."; String REQUIRED_PARAM_MISSING = "Missing required param."; diff --git a/src/main/java/com/nynja/walletservice/controller/EthereumController.java b/src/main/java/com/nynja/walletservice/controller/EthereumController.java index 3156f6ca0640b4b5356fa949d20307d801da2fb7..1ff0322e461f6f9b8d41140a21dfad8396bb8bb8 100644 --- a/src/main/java/com/nynja/walletservice/controller/EthereumController.java +++ b/src/main/java/com/nynja/walletservice/controller/EthereumController.java @@ -11,9 +11,12 @@ import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.web3j.crypto.Credentials; +import org.web3j.protocol.core.methods.response.EthGetBalance; import org.web3j.utils.Convert; +import java.io.IOException; import java.math.BigDecimal; +import java.util.List; import java.util.concurrent.CompletableFuture; import static com.nynja.walletservice.constant.Constants.DataTypes.LONG; @@ -46,6 +49,17 @@ public class EthereumController { public CompletableFuture> checkClientVersion( @NotBlank(message = CHAIN_ID_VALIDATION_MESSAGE) @RequestParam String chainId ) { + + System.out.println(""); + System.out.println("===================="); + System.out.println(""); + System.out.println("CHECK HERE : "); + System.out.println(""); + System.out.println(web3JService.getClientVersion(chainId) + .thenApplyAsync(ResponseEntity::ok)); + System.out.println(""); + System.out.println("===================="); + System.out.println(""); return web3JService.getClientVersion(chainId) .thenApplyAsync(ResponseEntity::ok); } @@ -56,13 +70,50 @@ public class EthereumController { @ApiResponse(code = 200, message = RETRIEVED), @ApiResponse(code = 400, message = REQUIRED_PARAM_MISSING) }) - @GetMapping(API_VERSION + "/address-balance") + + // Updated By Jayendra +/* @GetMapping(API_VERSION + "/address-balance") public CompletableFuture> getBalanceForAddress( @NotBlank(message = CHAIN_ID_VALIDATION_MESSAGE) @RequestParam String chainId, @NotBlank(message = ADDRESS_VALIDATION_MESSAGE) @RequestParam String address ) { return web3JService.getBalance(chainId, address) .thenApplyAsync(ResponseEntity::ok); + }*/ + +// Updated By Jayendra + @GetMapping(API_VERSION + "/address-balance") + public EthGetBalance getBalanceForAddress( + @NotBlank(message = CHAIN_ID_VALIDATION_MESSAGE) @RequestParam String chainId, + @NotBlank(message = ADDRESS_VALIDATION_MESSAGE) @RequestParam String address + ) throws IOException { + System.out.println(""); + System.out.println("-------------->>>"); + System.out.println(""); + System.out.println("Get Balance API"); + System.out.println(""); + System.out.println("chainId : " + chainId); + System.out.println("address : " + address); + System.out.println(""); + System.out.println("-------------->>>"); + System.out.println(""); + + List allAccounts = web3JService.getAllAccounts(chainId); + + System.out.println("-------------->>>"); + System.out.println(""); + System.out.println("Size : " + allAccounts.size()); + System.out.println(""); + System.out.println("AllAccounts : "); + System.out.println(allAccounts); + System.out.println(""); + System.out.println("-------------->>>"); + System.out.println(""); + + + + return web3JService.getBalance(chainId, address); + } @ApiOperation(value = "Send ether to an ethereum account from alloc account", httpMethod = "GET") diff --git a/src/main/java/com/nynja/walletservice/controller/TokenControllerV2.java b/src/main/java/com/nynja/walletservice/controller/TokenControllerV2.java new file mode 100644 index 0000000000000000000000000000000000000000..2ed89a7da557fc5c2f72f00cf839fb76e5304493 --- /dev/null +++ b/src/main/java/com/nynja/walletservice/controller/TokenControllerV2.java @@ -0,0 +1,348 @@ +package com.nynja.walletservice.controller; + +import com.nynja.walletservice.config.ConfigValues; +import com.nynja.walletservice.constant.Constants; +import com.nynja.walletservice.model.network.NetworkProperties; +import com.nynja.walletservice.service.Web3JService; +import com.nynja.walletservice.util.RestTemplateUtil; +import com.nynja.walletservice.wrapper.NynjaCoin; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.web3j.crypto.Credentials; +import org.web3j.protocol.Web3j; +import org.web3j.protocol.core.methods.response.TransactionReceipt; +import org.web3j.tx.FastRawTransactionManager; +import org.web3j.tx.TransactionManager; +import org.web3j.tx.response.NoOpProcessor; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.nynja.walletservice.constant.Constants.RestApi.API_VERSION_V2; + +@RestController +@RequestMapping("/token") +public class TokenControllerV2 { + + @Autowired + private Web3JService web3JService; + + @Autowired + private ConfigValues conf; + + @Autowired + private RestTemplateUtil restTemplateUtil; + + + @GetMapping(API_VERSION_V2 + "/status") + public Map getTransactionStatus(@RequestParam String chainId, + @RequestParam String hash + ) { + + + System.out.println(""); + System.out.println("-------------------------->"); + System.out.println(""); + System.out.println("Check transaction Status"); + System.out.println(""); + System.out.println("chainId : " + chainId); + System.out.println("hash : " + hash); + System.out.println(""); + System.out.println("-------------------------->"); + System.out.println(""); + + Map transactionStatus = restTemplateUtil.getTransactionStatus(hash, chainId); + + return transactionStatus; + + } + + + @PostMapping(API_VERSION_V2 + "/transfer") + public Map tokenTransfer( + @RequestParam String chainId, + @RequestParam String address, + @RequestParam String amount + ) throws Exception { + + System.out.println(""); + System.out.println("------------->>"); + System.out.println(""); + System.out.println("TRANSFER TOKENS : "); + System.out.println(""); + System.out.println("chainId : " + chainId); + System.out.println("address : " + address); + System.out.println("amount : " + amount); + System.out.println("Coin-Address : " + conf.getNetworkProps(chainId).getNynjaCoinAddress()); + System.out.println(""); + System.out.println("------------->>"); + System.out.println(""); + + Credentials credentials = Credentials.create(conf.getNetworkProps(chainId).getAdminPrivateKey()); + Web3j web3j = web3JService.web3j(chainId); + NetworkProperties networkProperties = conf.getNetworkProps(chainId); + + NoOpProcessor processor = new NoOpProcessor(web3j); + TransactionManager txManager = new FastRawTransactionManager(web3j, credentials, processor); + + /*NynjaCoin nynjaCoin1 = NynjaCoin.load( + "0x1bd759504dd3a93f13ba807204c7a98a592559cc", + web3j, + new RawTransactionManager(web3j, credentials, conf.getAttempts(), conf.getInterval()), + new BigInteger("41000000000"), new BigInteger("400000") + ); +*/ + + NynjaCoin nynjaCoin1 = NynjaCoin.load( + networkProperties.getNynjaCoinAddress(), + web3j, + // new RawTransactionManager(web3j, credentials, conf.getAttempts(), conf.getInterval()), + txManager, + networkProperties.getGasPrice(), networkProperties.getGasLimit() + ); + + + // CompletableFuture receipt = nynjaCoin1.transfer("0xf6352139dFe0b1fFE5CCA0fD62cEd69fD2E66029", new BigInteger(amount)).sendAsync(); + TransactionReceipt receipt = nynjaCoin1.transfer(address, new BigInteger(amount)).send(); + + System.out.println(""); + System.out.println("----------------------->>"); + System.out.println(""); + System.out.println("Transaction-Hash : " + receipt.getTransactionHash()); + System.out.println(""); + System.out.println("----------------------->>"); + System.out.println(""); + + + Map response = new HashMap<>(3); + response.put("status", Constants.HttpStatus.SUCCESS_STATUS_CODE); + response.put("transaction_id", receipt.getTransactionHash()); + response.put("message", "Transaction will be initiated in 5-10 minutes."); + + return response; + } + + + @GetMapping(API_VERSION_V2 + "/balance") + public Map tokenBalance( + @RequestParam String chainId, + @RequestParam String address + ) throws Exception { + + System.out.println(""); + System.out.println("-----------"); + System.out.println(""); + System.out.println("Get Token Balance"); + System.out.println(""); + System.out.println("chainId : " + chainId); + System.out.println("address : " + address); + System.out.println("Coin-Address : " + conf.getNetworkProps(chainId).getNynjaCoinAddress()); + System.out.println(""); + System.out.println("-----------"); + System.out.println(""); + + /*Credentials credentials = Credentials.create(conf.getNetworkProps(chainId).getAdminPrivateKey()); + + Web3j web3j = web3JService.web3j(chainId); + NynjaCoin nynjaCoin1 = NynjaCoin.load( + conf.getNetworkProps(chainId).getNynjaCoinAddress(), + web3j, + new RawTransactionManager(web3j, credentials, conf.getAttempts(), conf.getInterval()), + new BigInteger("41000000000"), new BigInteger("400000") + ); + + + BigInteger balance = nynjaCoin1.balanceOf(address).send(); + + System.out.println(""); + System.out.println("Balance : " + balance); + System.out.println(""); + + Map response = new HashMap<>(2); + response.put("status", Constants.HttpStatus.SUCCESS_STATUS_CODE); + response.put("balance", balance);*/ + + Map getBalanceByAddress = restTemplateUtil.getBalanceByAddress(address, chainId); + + System.out.println(""); + System.out.println("GetBalanceByAddress"); + System.out.println(getBalanceByAddress); + System.out.println(""); + + return getBalanceByAddress; + + } + + + @GetMapping(API_VERSION_V2 + "/txHistory") + public Map getTransactionHistory(@RequestParam String chainId, + @RequestParam(required = false) String page, + @RequestParam(required = false) String offset, + @RequestParam(required = false) String sort + + ) { + System.out.println(""); + System.out.println("-----------"); + System.out.println(""); + System.out.println("Get Transaction History"); + System.out.println(""); + System.out.println("page : " + page); + System.out.println("sort : " + sort); + System.out.println("offset : " + offset); + System.out.println("chainId : " + chainId); + System.out.println(""); + System.out.println("-----------"); + System.out.println(""); + + Map transactionHistory = restTemplateUtil.getTransactionHistory(chainId, page, offset, sort); + + System.out.println("Transaction History : "); + System.out.println(transactionHistory); + System.out.println(transactionHistory.get("status")); + System.out.println(""); + + if(transactionHistory.get("status").toString().equals("1")) { + + int count = ((List) transactionHistory.get("result")).size(); + System.out.println("Size : " + count); + System.out.println(""); + + transactionHistory.put("count", String.valueOf(count)); + + } + return transactionHistory; + + } + + + @GetMapping(API_VERSION_V2 + "/txHistoryByAddress") + public Map getTransactionHistory(@RequestParam String chainId, + @RequestParam String address, + @RequestParam(required = false) String page, + @RequestParam(required = false) String offset, + @RequestParam(required = false) String sort + ) { + System.out.println(""); + System.out.println("-----------"); + System.out.println(""); + System.out.println("Get Transaction History By Address"); + System.out.println(""); + System.out.println("sort : " + sort); + System.out.println("page : " + page); + System.out.println("offset : " + offset); + System.out.println("chainId : " + chainId); + System.out.println("address : " + address); + System.out.println(""); + System.out.println("-----------"); + System.out.println(""); + + Map transactionHistory = restTemplateUtil.getTransactionHistoryByAddress(chainId, address, page, offset, sort); + + System.out.println("Transaction History By Address : "); + System.out.println(transactionHistory); + System.out.println(""); + + if(transactionHistory.get("status").equals("1")){ + + int count = ((List)transactionHistory.get("result")).size(); + System.out.println("Size : " + count); + System.out.println(""); + + transactionHistory.put("count", String.valueOf(count)); + + } + + return transactionHistory; + + } + + + /* @GetMapping("/token/load/test") + public String test( + @RequestParam String chainId, + @RequestParam String amount + ) throws Exception { + + System.out.println(""); + System.out.println("-------------->>"); + System.out.println(""); + System.out.println("Load Nynja Token"); + System.out.println(""); + System.out.println("amount : " + amount); + System.out.println(""); + System.out.println("-------------->>"); + System.out.println(""); + + Web3j web3j = web3JService.web3j(chainId); + + *//*BigInteger privkey = new BigInteger(conf.getNetworkProps(chainId).getAdminPrivateKey(), 16); + ECKeyPair ecKeyPair = ECKeyPair.create(privkey); + Credentials credentials = Credentials.create(ecKeyPair); + NoOpProcessor processor = new NoOpProcessor(web3j);*//* + + //deploy new contract + //TransactionManager txManager = new FastRawTransactionManager(web3j, credentials, processor); + + //ERC20 token = ERC20.load(contractAddress, web3j, txManager, DefaultGasProvider.GAS_PRICE, DefaultGasProvider.GAS_LIMIT); + + Credentials credentials = Credentials.create(conf.getNetworkProps(chainId).getAdminPrivateKey()); + + *//* NynjaCoin nynjaCoin1 =NynjaCoin.load( + "0x1bd759504dd3a93f13ba807204c7a98a592559cc", + web3j, + txManager, + new BigInteger("41000000000"), new BigInteger("400000") + );*//* + + NynjaCoin nynjaCoin1 = NynjaCoin.load( + "0x1bd759504dd3a93f13ba807204c7a98a592559cc", + web3j, + new RawTransactionManager(web3j, credentials, conf.getAttempts(), conf.getInterval()), + new BigInteger("41000000000"), new BigInteger("400000") + ); + + + BigInteger balance = nynjaCoin1.balanceOf("0x1bd759504dd3a93f13ba807204c7a98a592559cc").send(); + BigInteger addrBalance = nynjaCoin1.balanceOf("0xf6352139dFe0b1fFE5CCA0fD62cEd69fD2E66029").send(); + + System.out.println("--------------------------------------------->>"); + System.out.println("--------------------------------------------->>"); + System.out.println(""); + System.out.println("Admin Balance : "); + System.out.println(balance); + System.out.println(""); + System.out.println("Address Balance : "); + System.out.println(addrBalance); + System.out.println(""); + + System.out.println(""); + System.out.println("Transfering Coins"); + + CompletableFuture receipt = nynjaCoin1.transfer("0xf6352139dFe0b1fFE5CCA0fD62cEd69fD2E66029", new BigInteger("10000000000000000000")).sendAsync(); + + System.out.println(""); + System.out.println("Receipt "); + System.out.println("-------------------------------"); + //System.out.println("Status : " + receipt.getStatus()); + //System.out.println("Hash : " + receipt.getTransactionHash()); + System.out.println("-------------------------------"); + System.out.println(""); + + BigInteger newBalance = nynjaCoin1.balanceOf("0x1bd759504dd3a93f13ba807204c7a98a592559cc").send(); + BigInteger newaddrBalance = nynjaCoin1.balanceOf("0xf6352139dFe0b1fFE5CCA0fD62cEd69fD2E66029").send(); + + System.out.println(""); + System.out.println("Admin New Balance : "); + System.out.println(newBalance); + System.out.println(""); + System.out.println("Address New Balance : "); + System.out.println(newaddrBalance); + System.out.println(""); + System.out.println("--------------------------------------------->>"); + + return newBalance.toString(); + }*/ + + +} diff --git a/src/main/java/com/nynja/walletservice/controller/TransactionController.java b/src/main/java/com/nynja/walletservice/controller/TransactionController.java index cc6f5bb7cbc518d6f29bd741e227a9a9f35faa9a..a8f25e9df2deba86ec484e6bdf54e2ca94c2e570 100644 --- a/src/main/java/com/nynja/walletservice/controller/TransactionController.java +++ b/src/main/java/com/nynja/walletservice/controller/TransactionController.java @@ -3,6 +3,7 @@ package com.nynja.walletservice.controller; import com.nynja.walletservice.blockexplorer.EtherScanConsumer; import com.nynja.walletservice.blockexplorer.dto.Response; import com.nynja.walletservice.blockexplorer.dto.TxListItemDto; +import com.nynja.walletservice.config.ConfigValues; import com.nynja.walletservice.constant.enums.Sort; import com.nynja.walletservice.dto.EstimateGasRequestDto; import com.nynja.walletservice.dto.EstimateGasResponseDto; @@ -10,6 +11,7 @@ import com.nynja.walletservice.dto.SignedTransactionDto; import com.nynja.walletservice.dto.TransactionResponseDto; import com.nynja.walletservice.service.TokenService; import com.nynja.walletservice.service.Web3JService; +import com.nynja.walletservice.wrapper.NynjaCoin; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; @@ -18,7 +20,15 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.web3j.crypto.Credentials; +import org.web3j.crypto.ECKeyPair; +import org.web3j.protocol.Web3j; +import org.web3j.protocol.core.RemoteCall; import org.web3j.protocol.core.methods.response.TransactionReceipt; +import org.web3j.tx.FastRawTransactionManager; +import org.web3j.tx.RawTransactionManager; +import org.web3j.tx.TransactionManager; +import org.web3j.tx.response.NoOpProcessor; import javax.validation.Valid; import java.math.BigInteger; @@ -40,6 +50,7 @@ public class TransactionController { private Web3JService web3JService; private EtherScanConsumer etherScanConsumer; + @Autowired public TransactionController(TokenService tokenService, Web3JService web3JService, EtherScanConsumer etherScanConsumer) { this.tokenService = tokenService; @@ -66,9 +77,100 @@ public class TransactionController { @NotBlank(message = CHAIN_ID_VALIDATION_MESSAGE) @RequestParam String chainId, @Valid @RequestBody SignedTransactionDto dto ) { + + return web3JService.sendSignedTransaction(chainId, dto.getSignedTransaction()).thenApplyAsync(ResponseEntity::ok); } + + @Autowired + private ConfigValues conf; + + +/* + @GetMapping("/token/load/test") + public String test( + @RequestParam String chainId, + @RequestParam String address + ) throws Exception { + + System.out.println(""); + System.out.println("-------------->>"); + System.out.println(""); + System.out.println("Load Nynja Token"); + System.out.println(""); + System.out.println("-------------->>"); + System.out.println(""); + + Web3j web3j = web3JService.web3j(chainId); + + *//*BigInteger privkey = new BigInteger(conf.getNetworkProps(chainId).getAdminPrivateKey(), 16); + ECKeyPair ecKeyPair = ECKeyPair.create(privkey); + Credentials credentials = Credentials.create(ecKeyPair); + NoOpProcessor processor = new NoOpProcessor(web3j);*//* + + //deploy new contract + //TransactionManager txManager = new FastRawTransactionManager(web3j, credentials, processor); + + //ERC20 token = ERC20.load(contractAddress, web3j, txManager, DefaultGasProvider.GAS_PRICE, DefaultGasProvider.GAS_LIMIT); + + Credentials credentials = Credentials.create(conf.getNetworkProps(chainId).getAdminPrivateKey()); + + *//* NynjaCoin nynjaCoin1 =NynjaCoin.load( + "0x1bd759504dd3a93f13ba807204c7a98a592559cc", + web3j, + txManager, + new BigInteger("41000000000"), new BigInteger("400000") + );*//* + + NynjaCoin nynjaCoin1 =NynjaCoin.load( + "0x1bd759504dd3a93f13ba807204c7a98a592559cc", + web3j, + new RawTransactionManager(web3j, credentials, conf.getAttempts(), conf.getInterval()), + new BigInteger("41000000000"), new BigInteger("400000") + ); + + BigInteger balance = nynjaCoin1.balanceOf(address).send(); + BigInteger addrBalance = nynjaCoin1.balanceOf("0xf6352139dFe0b1fFE5CCA0fD62cEd69fD2E66029").send(); + + System.out.println("--------------------------------------------->>"); + System.out.println("--------------------------------------------->>"); + System.out.println(""); + System.out.println("Admin Balance : "); + System.out.println(balance); + System.out.println(""); + System.out.println("Address Balance : "); + System.out.println(addrBalance); + System.out.println(""); + + System.out.println(""); + System.out.println("Transfering Coins"); + + CompletableFuture receipt = nynjaCoin1.transfer("0xf6352139dFe0b1fFE5CCA0fD62cEd69fD2E66029", new BigInteger("10000000000000000000")).sendAsync(); + + System.out.println(""); + System.out.println("Receipt " ); + System.out.println("-------------------------------"); + //System.out.println("Status : " + receipt.getStatus()); + //System.out.println("Hash : " + receipt.getTransactionHash()); + System.out.println("-------------------------------"); + System.out.println(""); + + BigInteger newBalance = nynjaCoin1.balanceOf(address).send(); + BigInteger newaddrBalance = nynjaCoin1.balanceOf("0xf6352139dFe0b1fFE5CCA0fD62cEd69fD2E66029").send(); + + System.out.println(""); + System.out.println("Admin New Balance : "); + System.out.println(newBalance); + System.out.println(""); + System.out.println("Address New Balance : "); + System.out.println(newaddrBalance); + System.out.println(""); + System.out.println("--------------------------------------------->>"); + return newBalance.toString(); + }*/ + + @ApiOperation(value = "Endpoint for getting transaction info by hash", httpMethod = "GET") @ApiResponse(code = 200, message = RETRIEVED) @GetMapping(API_VERSION + "/single-transaction-info") diff --git a/src/main/java/com/nynja/walletservice/provider/ContractProvider.java b/src/main/java/com/nynja/walletservice/provider/ContractProvider.java index c646617df80d0ac1af4ce35c6ff5555892eb2271..a9f8f588ecb6d6e7dd4236c9c9962cfa18d95c6f 100644 --- a/src/main/java/com/nynja/walletservice/provider/ContractProvider.java +++ b/src/main/java/com/nynja/walletservice/provider/ContractProvider.java @@ -75,6 +75,12 @@ public class ContractProvider { } public NynjaCoin getNynjaCoin(String chainId, Credentials credentials) { + + System.out.println(""); + System.out.println("Get Nynja Coins"); + System.out.println(""); + System.out.println(credentials.getAddress()); + System.out.println(""); return loadNynjaCoin(web3jProvider.getInstance(chainId), chainId, credentials); } @@ -92,6 +98,11 @@ public class ContractProvider { return new RuntimeException("Nynja Contract is not deployed!"); })); + System.out.println(""); + System.out.println("Load Nynja Coin Address:"); + System.out.println(address); + System.out.println(""); + return NynjaCoin.load( address, web3j, diff --git a/src/main/java/com/nynja/walletservice/provider/Web3jProvider.java b/src/main/java/com/nynja/walletservice/provider/Web3jProvider.java index 29ff6773f0628863aea36f87c4c3e06ccd22d69b..b057e9ef662f6b451ce3a013677a201511b07686 100644 --- a/src/main/java/com/nynja/walletservice/provider/Web3jProvider.java +++ b/src/main/java/com/nynja/walletservice/provider/Web3jProvider.java @@ -9,10 +9,8 @@ import org.springframework.stereotype.Component; import org.web3j.protocol.Web3j; import org.web3j.protocol.http.HttpService; import org.web3j.utils.Async; - import java.util.HashMap; import java.util.Map; - import static org.apache.commons.lang3.StringUtils.isBlank; @Component @@ -30,10 +28,16 @@ public class Web3jProvider implements ApplicationListener @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { instances = new HashMap<>(); + + System.out.println(""); + System.out.println("Networks"); + System.out.println(conf.getNetworks()); + System.out.println(""); conf.getNetworks().forEach((k, v) -> instances.put(k, buildInstance(v.getUrl()))); } private Web3j buildInstance(String clientUrl) { + log.info("BUILDING Web3j INSTANCE FOR URL: {}", clientUrl); return Web3j.build(new HttpService( @@ -44,6 +48,21 @@ public class Web3jProvider implements ApplicationListener } public Web3j getInstance(String chainId) { + + System.out.println(""); + System.out.println(">>>>>>>>>>>"); + System.out.println(""); + System.out.println("instances : "); + System.out.println(instances); + System.out.println(""); + System.out.println("chainId : " + chainId); + System.out.println(""); + System.out.println(instances.get(chainId)); + System.out.println(""); + System.out.println(">>>>>>>>>>>"); + + // chainId = (chainId.equals("1")?"one":(chainId.equals("4")?"four":"")); + if (isBlank(chainId)) { return instances.get("4"); } else { diff --git a/src/main/java/com/nynja/walletservice/service/Web3JService.java b/src/main/java/com/nynja/walletservice/service/Web3JService.java index 36b9f23757e76e3b9b7fc3a81687b15c31e9b051..e3c4cc74b5599c84e86e341c6119d16f94303885 100644 --- a/src/main/java/com/nynja/walletservice/service/Web3JService.java +++ b/src/main/java/com/nynja/walletservice/service/Web3JService.java @@ -20,8 +20,10 @@ import org.web3j.tx.RawTransactionManager; import org.web3j.tx.Transfer; import org.web3j.utils.Convert; +import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; +import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; @@ -45,22 +47,127 @@ public class Web3JService { } public CompletableFuture getClientVersion(String chainId) { + + System.out.println(""); + System.out.println(">>>>>>>>>"); + System.out.println(""); + System.out.println("Chain Id : " + chainId); + System.out.println(""); + System.out.println(">>>>>>>>>"); + System.out.println(""); + System.out.println("One : "); + System.out.println(web3j(chainId).web3ClientVersion()); + System.out.println(""); + System.out.println("Two : "); + System.out.println(web3j(chainId).web3ClientVersion().sendAsync()); + System.out.println(""); + System.out.println("Three : "); + System.out.println(web3j(chainId).web3ClientVersion().sendAsync().thenApplyAsync(this::validateResponse)); + System.out.println(""); + System.out.println("Four : "); + System.out.println(web3j(chainId).web3ClientVersion().sendAsync().thenApplyAsync(this::validateResponse) + .thenApplyAsync(Web3ClientVersion::getWeb3ClientVersion)); + + System.out.println(""); return web3j(chainId).web3ClientVersion() .sendAsync() .thenApplyAsync(this::validateResponse) .thenApplyAsync(Web3ClientVersion::getWeb3ClientVersion); } + + // Updated By Jayendra +/* public CompletableFuture getBalance(String chainId, String address) { + return web3j(chainId).ethGetBalance(address, DefaultBlockParameterName.LATEST) + .sendAsync() + .thenApplyAsync(this::validateResponse) + .thenApplyAsync(EthGetBalance::getBalance) + .thenApplyAsync(BigInteger::toString); + }*/ + + // Updated By Jayendra + public EthGetBalance getBalance(String chainId, String address) throws IOException { + + System.out.println(""); + System.out.println("Checking Here"); + System.out.println("chainId - > " + chainId); + System.out.println("address - > " + address); + System.out.println(""); + + Web3j web3j = web3j(chainId); + + System.out.println("web3j:"); + System.out.println(web3j); + System.out.println(""); + + return web3j(chainId).ethGetBalance(address, DefaultBlockParameterName.LATEST).send(); + + } + + // Made By Jayendra + public List getAllAccounts(String chainId) throws IOException { + + System.out.println(""); + System.out.println("Checking Here"); + System.out.println("chainId - > " + chainId); + System.out.println(""); + + Web3j web3j = web3j(chainId); + + System.out.println("web3j:"); + System.out.println(web3j); + System.out.println(""); + + return web3j(chainId).ethAccounts().send().getAccounts(); + + } + + + public void sendEther(String chainId, Credentials credentials, String toAddress, BigDecimal value, Convert.Unit currency) throws IOException { + + Web3j web3j = web3j(chainId); + + System.out.println(""); + System.out.println("Admin-Address : " + conf.getNetworkProps(chainId).getAdminAddress()); + // Fetch Next Nonce + EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(conf.getNetworkProps(chainId).getAdminAddress(), DefaultBlockParameterName.LATEST).send(); + + System.out.println("Count : " + ethGetTransactionCount.getTransactionCount()); + System.out.println(""); + + + //web3j.ethSendRawTransaction("as"). + + } + public CompletableFuture> sendEtherAsync( String chainId, Credentials credentials, String toAddress, BigDecimal value, Convert.Unit currency ) { final Web3j web3j = web3j(chainId); final NetworkProperties networkProperties = conf.getNetworkProps(chainId); + System.out.println(">>>>>>>>>>>>>>"); + System.out.println(""); + System.out.println("Send Ether Async"); + System.out.println(""); + System.out.println("chainId: " + chainId); + System.out.println("credentials-Address: " + credentials.getAddress()); + System.out.println("credentials-PublicKey: " + credentials.getEcKeyPair().getPublicKey()); + System.out.println("credentials-PrivateKey: " + credentials.getEcKeyPair().getPrivateKey()); + System.out.println("toAddress: " + toAddress); + System.out.println("value: " + value); + System.out.println("currency: " + currency); + System.out.println(""); + System.out.println(">>>>>>>>>>>>>>"); + return new Transfer(web3j, new RawTransactionManager(web3j, credentials, conf.getAttempts(), conf.getInterval())) .sendFunds(toAddress, value, currency, networkProperties.getGasPrice(), networkProperties.getGasLimit()) .sendAsync() .thenApplyAsync(tr -> { + System.out.println(""); + System.out.println("Its Done"); + System.out.println("tr : " + tr.toString()); + System.out.println(""); log.info(ETH_TRANSFERRED, toAddress, value, currency); return new TransactionResponseDto<>(tr.getTransactionHash(), value.toString()); }).exceptionally(ex -> { @@ -68,14 +175,6 @@ public class Web3JService { }); } - public CompletableFuture getBalance(String chainId, String address) { - return web3j(chainId).ethGetBalance(address, DefaultBlockParameterName.LATEST) - .sendAsync() - .thenApplyAsync(this::validateResponse) - .thenApplyAsync(EthGetBalance::getBalance) - .thenApplyAsync(BigInteger::toString); - } - public CompletableFuture> sendSignedTransaction(String chainId, String transaction) { return web3j(chainId).ethSendRawTransaction(transaction) .sendAsync() diff --git a/src/main/java/com/nynja/walletservice/util/RestTemplateUtil.java b/src/main/java/com/nynja/walletservice/util/RestTemplateUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..e01e0953a178a6a0fc1c96d9ba31c5c1732b12a3 --- /dev/null +++ b/src/main/java/com/nynja/walletservice/util/RestTemplateUtil.java @@ -0,0 +1,150 @@ +package com.nynja.walletservice.util; + +import com.nynja.walletservice.config.ConfigValues; +import com.nynja.walletservice.model.network.NetworkProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.stereotype.Component; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; + +import javax.annotation.PostConstruct; +import java.util.Map; + + +@Component +public class RestTemplateUtil { + + @Autowired + private ConfigValues conf; + + // https://api-rinkeby.etherscan.io/api?module=transaction&action=gettxreceiptstatus&txhash=0xf280ccd85a77b42b6111d51660d615de94862de1430209e605ef7f4e8738c475&apikey=K8J2W58EGI3EIR2FI8SYGW7FR1QKV5KDBM + + // Trnxn List + // http://api-rinkeby.etherscan.io/api?module=account&action=tokentx&address=0xB9BbCB84B654316D8E23383434c4EC66A97038ED&&sort=asc&apikey=0x1bd759504dd3a93f13ba807204c7a98a592559cc + + + RestTemplate restTemplate; + + @PostConstruct + public void init() { + + restTemplate = new RestTemplate(); + } + + + public Map getTransactionStatus(String hash, String chainId) { + + NetworkProperties props = conf.getNetworks().get(chainId); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(props.getBlockExplorerUrl()) + .queryParam("module", "transaction") + .queryParam("action", "gettxreceiptstatus") + .queryParam("txhash", hash) + .queryParam("apikey", props.getBlockExplorerApiKey()); + + HttpEntity> httpEntity = new HttpEntity(new HttpHeaders()); + + return (Map) restTemplate.exchange( + builder.toUriString(), + HttpMethod.GET, + httpEntity, + Map.class).getBody(); + + } + + + // https://api-rinkeby.etherscan.io/api?module=account&action=tokentx&contractaddress=0x1bd759504dd3a93f13ba807204c7a98a592559cc&page=1&offset=100&sort=asc&apikey=K8J2W58EGI3EIR2FI8SYGW7FR1QKV5KDBM + + // Get contract's transaction history + public Map getTransactionHistory(String chainId, String page, String offset, String sort) { + + NetworkProperties props = conf.getNetworks().get(chainId); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(props.getBlockExplorerUrl()) + .queryParam("module", "account") + .queryParam("action", "tokentx") + .queryParam("contractaddress", props.getNynjaCoinAddress()) + .queryParam("sort", sort) + .queryParam("apikey", props.getBlockExplorerApiKey()); + + + if (page != null) { + builder.queryParam("page", page); + } + if (offset != null) { + builder.queryParam("offset", offset); + } + + HttpEntity> httpEntity = new HttpEntity(new HttpHeaders()); + + + return (Map) restTemplate.exchange( + builder.toUriString(), + HttpMethod.GET, + httpEntity, + Map.class).getBody(); + + } + + + // Get transaction history by address + public Map getTransactionHistoryByAddress(String chainId, String address, String page, String offset, String sort) { + + NetworkProperties props = conf.getNetworks().get(chainId); + + // http://api-rinkeby.etherscan.io/api?module=account&action=tokentx&address=0xeadc97586317a38da89044bf13f1b8095483ed3b&sort=asc&apikey=0x1bd759504dd3a93f13ba807204c7a98a592559cc + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(props.getBlockExplorerUrl()) + .queryParam("module", "account") + .queryParam("action", "tokentx") + .queryParam("address", address) + .queryParam("sort", sort) + .queryParam("apikey", props.getBlockExplorerApiKey()); + + if (page != null) { + builder.queryParam("page", page); + } + if (offset != null) { + builder.queryParam("offset", offset); + } + + HttpEntity> httpEntity = new HttpEntity<>(new HttpHeaders()); + + return (Map) restTemplate.exchange( + builder.toUriString(), + HttpMethod.GET, + httpEntity, + Map.class).getBody(); + + } + + + // http://api-rinkeby.etherscan.io/api?module=account&action=tokenbalance&contractaddress=0xb9c5164c426c25d0b399964bb294664688cca947&address=0x118a5cBE67465A8fc8671496E746A55B430a8484&tag=latest&apikey=K8J2W58EGI3EIR2FI8SYGW7FR1QKV5KDBM + public Map getBalanceByAddress(String address, String chainId) { + + NetworkProperties props = conf.getNetworks().get(chainId); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(props.getBlockExplorerUrl()) + .queryParam("module", "account") + .queryParam("action", "tokenbalance") + .queryParam("contractaddress", props.getNynjaCoinAddress()) + .queryParam("address", address) + .queryParam("tag", "latest") + .queryParam("apikey", props.getBlockExplorerApiKey()); + + + HttpEntity> httpEntity = new HttpEntity<>(new HttpHeaders()); + + Map balanceByAddress = restTemplate.exchange(builder.toUriString(), + HttpMethod.GET, + httpEntity, + Map.class + ).getBody(); + + + return balanceByAddress; + } + +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 85eddbc86397f25b8dab81767bf7bb623f2aa3df..d362753bd8cbdd586136f46a94cab2703b385125 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -4,7 +4,8 @@ server: spring: mvc: async: - request-timeout: 60000 + # request-timeout: 60000 + request-timeout: -1 datasource: url: jdbc:h2:file:./data/persistent_storage username: sa @@ -21,24 +22,27 @@ web3j: ethereum: networks: one: - url: http://35.242.240.78:8545 + # url: http://35.242.240.78:8545 + url: http://127.0.0.1:8545 block-explorer-url: http://api.etherscan.io/api block-explorer-api-key: "K8J2W58EGI3EIR2FI8SYGW7FR1QKV5KDBM" admin-address: "0xB9BbCB84B654316D8E23383434c4EC66A97038ED" admin-private-key: "3e3a8b9c6e92808a1c683aa9458f90cfbcf5c19bed87e443b82fc7814a134796" nynja-coin-listen-events: false - nynja-coin-address: "0xF36c7AdAd65c39A4848F3c85001F67f31d00d207" + #nynja-coin-address: "0xF36c7AdAd65c39A4848F3c85001F67f31d00d207" + nynja-coin-address: "0x5b52b324fc10cb43b9eeadaf9bd15afb98867942" gas-price: 41000000000 gas-limit: 400000 - four: - url: http://35.242.240.78:8545 + # url: http://35.242.240.78:8545 + url: http://127.0.0.1:8545 block-explorer-url: http://api-rinkeby.etherscan.io/api block-explorer-api-key: "K8J2W58EGI3EIR2FI8SYGW7FR1QKV5KDBM" admin-address: "0xB9BbCB84B654316D8E23383434c4EC66A97038ED" admin-private-key: "3e3a8b9c6e92808a1c683aa9458f90cfbcf5c19bed87e443b82fc7814a134796" nynja-coin-listen-events: true - nynja-coin-address: "0xF36c7AdAd65c39A4848F3c85001F67f31d00d207" + # nynja-coin-address: "0xF36c7AdAd65c39A4848F3c85001F67f31d00d207" + nynja-coin-address: "0x1bd759504dd3a93f13ba807204c7a98a592559cc" gas-price: 41000000000 gas-limit: 400000 event: @@ -48,3 +52,4 @@ wallet-discovery: message-broker: url: "http://dev2.ci.nynja.net/publish" topic: "/transfer-" + diff --git a/src/test/java/com/nynja/walletservice/controller/EthereumControllerTest.java b/src/test/java/com/nynja/walletservice/controller/EthereumControllerTest.java deleted file mode 100644 index b187b6dd427537a14abd14383b4c269ea43698da..0000000000000000000000000000000000000000 --- a/src/test/java/com/nynja/walletservice/controller/EthereumControllerTest.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.nynja.walletservice.controller; - -import com.nynja.walletservice.config.ConfigValues; -import com.nynja.walletservice.dto.TransactionResponseDto; -import com.nynja.walletservice.model.network.NetworkProperties; -import com.nynja.walletservice.service.Web3JService; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import org.web3j.crypto.Credentials; -import org.web3j.utils.Convert; - -import java.math.BigDecimal; -import java.util.concurrent.CompletableFuture; - -import static com.nynja.walletservice.constant.Constants.RestApi.API_VERSION; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * @author Oleg Zhymolokhov (oleg.zhimolokhov@dataart.com) - */ -@SpringBootTest -@RunWith(SpringRunner.class) -public class EthereumControllerTest { - - public static final String RINKEBY_CHAIN_ID = "4"; - static final String TEST_ADDRESS = "0x9028B59227c5EDdA388f04cef5e43020fEd1E73a"; - private static final String TEST_ADDRESS_PK = "3f5890282cc3b4eb8350823a1d1e950f7ba036b98cf074f299e1a9d09db196ca"; - - private MockMvc mvc; - private NetworkProperties networkProperties; - - @Autowired - private WebApplicationContext context; - @Autowired - private ConfigValues conf; - @Autowired - private Web3JService web3JService; - - - @Before - public void setup() { - mvc = MockMvcBuilders.webAppContextSetup(context).build(); - networkProperties = conf.getNetworkProps(RINKEBY_CHAIN_ID); - } - - @Test - public void testEthBalanceCheck() throws Exception { - MvcResult balanceResult = mvc.perform( - get("/ethereum" + API_VERSION + "address-balance") - .param("chainId", RINKEBY_CHAIN_ID) - .param("address", networkProperties.getAdminAddress()) - ).andExpect(request().asyncStarted()).andReturn(); - - mvc.perform(asyncDispatch(balanceResult)) - .andExpect(status().isOk()) - .andExpect(balance -> assertTrue( - new BigDecimal(balance.getResponse().getContentAsString()).compareTo(BigDecimal.ZERO) > 0 - )); - } - - @Test - public void testEthBalanceCheckBadRequest() throws Exception { - mvc.perform( - get("/ethereum" + API_VERSION + "address-balance") - .param("chainId", RINKEBY_CHAIN_ID) - .param("address", "") - ).andExpect(status().isBadRequest()); - } - - @Test - @SuppressWarnings("unchecked") - public void testEthSend() throws Exception { - String ethVal = "1"; - - MvcResult sendResult = mvc.perform( - get("/ethereum" + API_VERSION + "eth-send") - .param("chainId", RINKEBY_CHAIN_ID) - .param("address", TEST_ADDRESS) - .param("amount", ethVal) - ).andExpect(request().asyncStarted()).andReturn(); - - mvc.perform(asyncDispatch(sendResult)) - .andExpect(status().isOk()); - - TransactionResponseDto responseDto = ((ResponseEntity>) sendResult.getAsyncResult()).getBody(); - assertNotNull(responseDto.getHash()); - assertEquals(ethVal, responseDto.getValue()); - - //returning ether - CompletableFuture.supplyAsync(() -> web3JService.sendEtherAsync( - RINKEBY_CHAIN_ID, - Credentials.create(TEST_ADDRESS, TEST_ADDRESS_PK), - networkProperties.getAdminAddress(), - new BigDecimal("1"), - Convert.Unit.ETHER - )); - } -} diff --git a/src/test/java/com/nynja/walletservice/controller/TransactionControllerTest.java b/src/test/java/com/nynja/walletservice/controller/TransactionControllerTest.java deleted file mode 100644 index d700cdf32fa0055ab0d2de6885d46b91115759d7..0000000000000000000000000000000000000000 --- a/src/test/java/com/nynja/walletservice/controller/TransactionControllerTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.nynja.walletservice.controller; - -import com.nynja.walletservice.blockexplorer.dto.Response; -import com.nynja.walletservice.blockexplorer.dto.TxListItemDto; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import org.web3j.protocol.core.methods.response.TransactionReceipt; - -import java.math.BigInteger; - -import static com.nynja.walletservice.constant.Constants.RestApi.API_VERSION; -import static com.nynja.walletservice.controller.EthereumControllerTest.RINKEBY_CHAIN_ID; -import static com.nynja.walletservice.controller.EthereumControllerTest.TEST_ADDRESS; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * @author Oleg Zhymolokhov (oleg.zhimolokhov@dataart.com) - */ -@SpringBootTest -@RunWith(SpringRunner.class) -public class TransactionControllerTest { - - private MockMvc mvc; - - @Autowired - private WebApplicationContext context; - - @Before - public void setup() { - mvc = MockMvcBuilders - .webAppContextSetup(context) - .build(); - } - - @Test - @SuppressWarnings("unchecked") - public void testTransactionHistory() throws Exception { - MvcResult result = mvc.perform( - get("/wallet-service" + API_VERSION + "tx-history") - .param("address", "0xef253203acde5813a82ce53a67b0f93adbeef74d") - .param("chainId", RINKEBY_CHAIN_ID) - .param("contractAddress", "0xF36c7AdAd65c39A4848F3c85001F67f31d00d207") - .param("page", "1") - .param("offset", "10") - ).andReturn(); - - mvc.perform(asyncDispatch(result)).andExpect(status().isOk()); - - Response responseDto = ((ResponseEntity>) result.getAsyncResult()).getBody(); - assertNotNull(responseDto); - assertEquals("1", responseDto.getStatus()); - assertFalse(responseDto.getResult().isEmpty()); - } - - @Test - public void testTransactionHistoryBadRequest() throws Exception { - mvc.perform( - get("/wallet-service" + API_VERSION + "tx-history") - .param("address", "") - .param("chainId", RINKEBY_CHAIN_ID) - .param("contractAddress", "0xF36c7AdAd65c39A4848F3c85001F67f31d00d207") - .param("page", "1") - .param("offset", "10") - ).andExpect(status().isBadRequest()); - } - - @Test - @SuppressWarnings("unchecked") - public void testSingleTransactionInfo() throws Exception { - final String testTransaction = "0x42165f05b29fab8170bdb3bd5e3b0b7beab27afe1472952b022b57ec9f2d4eb9"; - - MvcResult result = mvc.perform( - get("/wallet-service" + API_VERSION + "single-transaction-info") - .param("chainId", RINKEBY_CHAIN_ID) - .param("hash", testTransaction) - ).andReturn(); - - mvc.perform(asyncDispatch(result)).andExpect(status().isOk()); - - TransactionReceipt receipt = ((ResponseEntity) result.getAsyncResult()).getBody(); - assertNotNull(receipt); - assertEquals(testTransaction, receipt.getTransactionHash()); - } - - @Test - public void testSingleTransactionInfoBadRequest() throws Exception { - mvc.perform( - get("/wallet-service" + API_VERSION + "single-transaction-info") - .param("chainId", RINKEBY_CHAIN_ID) - .param("hash", "") - ).andExpect(status().isBadRequest()); - } - - @Test - @SuppressWarnings("unchecked") - public void testGetTransactionCount() throws Exception { - MvcResult result = mvc.perform( - get("/wallet-service" + API_VERSION + "get-transaction-count") - .param("chainId", RINKEBY_CHAIN_ID) - .param("address", TEST_ADDRESS) - ).andReturn(); - - mvc.perform(asyncDispatch(result)).andExpect(status().isOk()); - - BigInteger txCount = ((ResponseEntity) result.getAsyncResult()).getBody(); - assertNotNull(txCount); - } -} diff --git a/src/test/java/com/nynja/walletservice/service/WalletServiceTest.java b/src/test/java/com/nynja/walletservice/service/WalletServiceTest.java deleted file mode 100644 index 7ce15da9893b82ef0f6b5a7bb1d795e07512718c..0000000000000000000000000000000000000000 --- a/src/test/java/com/nynja/walletservice/service/WalletServiceTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.nynja.walletservice.service; - -import com.nynja.walletservice.blockexplorer.EtherScanConsumer; -import com.nynja.walletservice.blockexplorer.dto.Response; -import com.nynja.walletservice.blockexplorer.dto.TxListItemDto; -import com.nynja.walletservice.config.ConfigValues; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.ArrayList; -import java.util.List; - -import static com.nynja.walletservice.controller.EthereumControllerTest.RINKEBY_CHAIN_ID; -import static com.nynja.walletservice.service.WalletService.BIP44_GAP; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.then; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.times; - -@SpringBootTest -@RunWith(SpringRunner.class) -public class WalletServiceTest { - - private static final String FIRST_ADDRESS = "0x07d4e5b036354019f8d6c4e4f993d9634a718bd2"; - private static final String SECOND_ADDRESS = "0x9d6e863638045998de777e7516e85be975a86ba3"; - - private static final String PUB = "A1tkbJ/iLb8+HfVoqebcIGsBOiCyT78ykj9A67b3uQ4s"; - private static final String CHAIN_CODE = "nci5w3gWUKopikWvOHxCcg8pUfIi36irMM6OkehnZ3Y"; - - private static final Response positiveResponse = Response.builder().status("1").message("OK") - .result(new ArrayList() {{ - add(TxListItemDto.builder() - .blockNumber("3849021") - .hash("0x736aa60b0b35d2a07696ece3ac71fb0f6b75b6299712975246c7a6700dc4bd40") - .confirmations("328317") - .build() - ); - }}).build(); - - private static final Response emptyResponse = Response.builder() - .status("0") - .message("No transactions found") - .result(new ArrayList<>()) - .build(); - - - private WalletService walletService; - - @Autowired - private ConfigValues configValues; - - @Mock - private EtherScanConsumer etherScanConsumer; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - this.walletService = new WalletService(etherScanConsumer, configValues); - } - - @Test - public void testSingleAccountScan() { - given(etherScanConsumer.getTxHistory(anyString(), anyString(), anyString(), anyString(), anyString(), any())) - .will(invocation -> { - String address = invocation.getArgumentAt(0, String.class); - return FIRST_ADDRESS.equals(address) || SECOND_ADDRESS.equals(address) ? positiveResponse : emptyResponse; - }); - - //when - List result = walletService.scanSingleAccount(PUB, CHAIN_CODE, RINKEBY_CHAIN_ID); - - //The test data implies that there will be transaction history only for 0th and 2th addresses - //This means that there will be 23 requests to the block-explorer to reach the BIP-44 gap and stop the discovery - then(etherScanConsumer).should(times(BIP44_GAP + 3)) - .getTxHistory(anyString(), anyString(), anyString(), anyString(), anyString(), any()); - - assertEquals(2, result.size()); - } - - @Test - public void testNoResults() { - given(etherScanConsumer.getTxHistory(anyString(), anyString(), anyString(), anyString(), anyString(), any())) - .willReturn(emptyResponse); - - //when - List result = walletService.scanSingleAccount(PUB, CHAIN_CODE, RINKEBY_CHAIN_ID); - - then(etherScanConsumer).should(times(BIP44_GAP)) - .getTxHistory(anyString(), anyString(), anyString(), anyString(), anyString(), any()); - assertEquals(0, result.size()); - } -}