From 9f71c1abb79b69309f57621359252b972525aab1 Mon Sep 17 00:00:00 2001 From: wangwll <214375933@qq.com> Date: Sat, 22 Aug 2020 17:26:55 +0800 Subject: [PATCH] The NEST3.0 automatic order taking arbitrage program is an example program. Related parameters such as price deviation percentage, the default value is 2%, which is not necessarily the optimal order taking arbitrage ratio, and users can adjust it according to the actual situation. --- NestEatOffer/.gitignore | 1 + NestEatOffer/README.md | 450 ++++++ NestEatOffer/eatOffer.iml | 120 ++ NestEatOffer/pom.xml | 121 ++ .../main/java/com/nest/ib/IbApplication.java | 17 + .../ib/config/ListenerAsyncConfiguration.java | 36 + .../java/com/nest/ib/config/MvcConfig.java | 35 + .../com/nest/ib/constant/AddressEnum.java | 44 + .../java/com/nest/ib/constant/Constant.java | 76 + .../main/java/com/nest/ib/contract/ERC20.java | 256 ++++ .../com/nest/ib/contract/MappingContract.java | 93 ++ .../com/nest/ib/contract/Nest3OfferMain.java | 536 +++++++ .../ib/contract/NestOfferPriceContract.java | 252 ++++ .../com/nest/ib/contract/VoteContract.java | 48 + .../nest/ib/controller/AuthController.java | 49 + .../com/nest/ib/controller/EatController.java | 194 +++ .../ib/interceptor/PermissionInterceptor.java | 53 + .../java/com/nest/ib/model/EatOfferDeal.java | 124 ++ .../com/nest/ib/model/OfferContractData.java | 146 ++ .../com/nest/ib/model/OfferThreeData.java | 108 ++ .../EatOfferAndTransactionService.java | 93 ++ .../ib/service/OfferThreeDataService.java | 16 + .../EatOfferAndTransactionServiceImpl.java | 1248 +++++++++++++++++ .../OfferThreeDataServiceImpl.java | 100 ++ .../com/nest/ib/utils/ContractFactory.java | 41 + .../java/com/nest/ib/utils/EthClient.java | 506 +++++++ .../com/nest/ib/utils/HttpClientUtil.java | 409 ++++++ .../java/com/nest/ib/utils/MathUtils.java | 60 + .../java/com/nest/ib/utils/api/ApiClient.java | 666 +++++++++ .../com/nest/ib/utils/api/ApiException.java | 28 + .../java/com/nest/ib/utils/api/JsonUtil.java | 39 + .../ib/utils/request/CreateOrderRequest.java | 57 + .../nest/ib/utils/request/DepthRequest.java | 32 + .../request/IntrustOrdersDetailRequest.java | 73 + .../com/nest/ib/utils/response/Account.java | 12 + .../com/nest/ib/utils/response/Accounts.java | 53 + .../ib/utils/response/AccountsResponse.java | 62 + .../nest/ib/utils/response/ApiResponse.java | 19 + .../com/nest/ib/utils/response/Balance.java | 63 + .../nest/ib/utils/response/BalanceBean.java | 43 + .../ib/utils/response/BalanceResponse.java | 63 + .../nest/ib/utils/response/Batchcancel.java | 28 + .../ib/utils/response/BatchcancelBean.java | 34 + .../utils/response/BatchcancelResponse.java | 53 + .../com/nest/ib/utils/response/Currencys.java | 10 + .../ib/utils/response/CurrencysResponse.java | 55 + .../ib/utils/response/DepositAddressBean.java | 45 + .../response/DepositAddressResponse.java | 37 + .../com/nest/ib/utils/response/Depth.java | 57 + .../nest/ib/utils/response/DepthResponse.java | 84 ++ .../ib/utils/response/DetailResponse.java | 73 + .../com/nest/ib/utils/response/Details.java | 104 ++ .../utils/response/ExtractERC20Response.java | 17 + .../ib/utils/response/ExtractQuotaBean.java | 28 + .../ib/utils/response/ExtractQuotaChains.java | 96 ++ .../utils/response/ExtractQuotaResponse.java | 28 + .../nest/ib/utils/response/HistoryTrade.java | 63 + .../utils/response/HistoryTradeResponse.java | 73 + .../ib/utils/response/HistoryTradess.java | 43 + .../nest/ib/utils/response/IntrustDetail.java | 194 +++ .../utils/response/IntrustDetailResponse.java | 53 + .../com/nest/ib/utils/response/Kline.java | 84 ++ .../nest/ib/utils/response/KlineResponse.java | 51 + .../response/MatchresultsOrdersDetail.java | 118 ++ .../MatchresultsOrdersDetailResponse.java | 53 + .../com/nest/ib/utils/response/Merged.java | 126 ++ .../ib/utils/response/MergedResponse.java | 81 ++ .../nest/ib/utils/response/OrdersDetail.java | 184 +++ .../utils/response/OrdersDetailResponse.java | 66 + .../com/nest/ib/utils/response/Place.java | 10 + .../QueryExtractServiceChargeChains.java | 170 +++ .../QueryExtractServiceChargeData.java | 37 + .../QueryExtractServiceChargeResponse.java | 37 + .../utils/response/SubmitcancelResponse.java | 53 + .../com/nest/ib/utils/response/Symbol.java | 9 + .../com/nest/ib/utils/response/Symbols.java | 104 ++ .../ib/utils/response/SymbolsResponse.java | 73 + .../ib/utils/response/TimestampResponse.java | 44 + .../com/nest/ib/utils/response/Trade.java | 44 + .../com/nest/ib/utils/response/TradeBean.java | 66 + .../nest/ib/utils/response/TradeResponse.java | 73 + .../java/com/nest/ib/vo/ScheduledTask.java | 56 + .../src/main/resources/application.properties | 9 + NestEatOffer/src/main/resources/log4j2.xml | 73 + .../src/main/resources/templates/eatData.html | 283 ++++ .../src/main/resources/templates/error.html | 20 + .../src/main/resources/templates/login.html | 32 + README.md | 98 ++ 88 files changed, 9671 insertions(+) create mode 100644 NestEatOffer/.gitignore create mode 100644 NestEatOffer/README.md create mode 100644 NestEatOffer/eatOffer.iml create mode 100644 NestEatOffer/pom.xml create mode 100644 NestEatOffer/src/main/java/com/nest/ib/IbApplication.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/config/ListenerAsyncConfiguration.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/config/MvcConfig.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/constant/AddressEnum.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/constant/Constant.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/contract/ERC20.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/contract/MappingContract.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/contract/Nest3OfferMain.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/contract/NestOfferPriceContract.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/contract/VoteContract.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/controller/AuthController.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/controller/EatController.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/interceptor/PermissionInterceptor.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/model/EatOfferDeal.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/model/OfferContractData.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/model/OfferThreeData.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/service/EatOfferAndTransactionService.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/service/OfferThreeDataService.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/service/serviceImpl/EatOfferAndTransactionServiceImpl.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/service/serviceImpl/OfferThreeDataServiceImpl.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/ContractFactory.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/EthClient.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/HttpClientUtil.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/MathUtils.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/api/ApiClient.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/api/ApiException.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/api/JsonUtil.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/request/CreateOrderRequest.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/request/DepthRequest.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/request/IntrustOrdersDetailRequest.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/Account.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/Accounts.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/AccountsResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/ApiResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/Balance.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/BalanceBean.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/BalanceResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/Batchcancel.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/BatchcancelBean.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/BatchcancelResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/Currencys.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/CurrencysResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/DepositAddressBean.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/DepositAddressResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/Depth.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/DepthResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/DetailResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/Details.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractERC20Response.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractQuotaBean.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractQuotaChains.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractQuotaResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/HistoryTrade.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/HistoryTradeResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/HistoryTradess.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/IntrustDetail.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/IntrustDetailResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/Kline.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/KlineResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/MatchresultsOrdersDetail.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/MatchresultsOrdersDetailResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/Merged.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/MergedResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/OrdersDetail.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/OrdersDetailResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/Place.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/QueryExtractServiceChargeChains.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/QueryExtractServiceChargeData.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/QueryExtractServiceChargeResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/SubmitcancelResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/Symbol.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/Symbols.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/SymbolsResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/TimestampResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/Trade.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/TradeBean.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/utils/response/TradeResponse.java create mode 100644 NestEatOffer/src/main/java/com/nest/ib/vo/ScheduledTask.java create mode 100644 NestEatOffer/src/main/resources/application.properties create mode 100644 NestEatOffer/src/main/resources/log4j2.xml create mode 100644 NestEatOffer/src/main/resources/templates/eatData.html create mode 100644 NestEatOffer/src/main/resources/templates/error.html create mode 100644 NestEatOffer/src/main/resources/templates/login.html create mode 100644 README.md diff --git a/NestEatOffer/.gitignore b/NestEatOffer/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/NestEatOffer/.gitignore @@ -0,0 +1 @@ +/target diff --git a/NestEatOffer/README.md b/NestEatOffer/README.md new file mode 100644 index 0000000..f6ca912 --- /dev/null +++ b/NestEatOffer/README.md @@ -0,0 +1,450 @@ +[toc] + +*** + +### NEST3.0 Automatic order taking arbitrage program + +*** + +#### 1. Create private key, node + +>Since calling the contract to obtain relevant data and send transactions, you need to interact with the chain, and you need to prepare an Ethereum node URL and private key. The node can apply for free after registration through https://infura.io/. +> + +```java +// Ethereum node +String ETH_NODE = ""; +// Private key +String USER_PRIVATE_KEY = ""; +Web3j web3j = Web3j.build(new HttpService(ETH_NODE)); +Credentials credentials = Credentials.create(USER_PRIVATE_KEY); +``` + +#### 2. Get Nest Protocol related contract address + +>The role of mapping contracts in Nest Protocol: manage all other contract addresses. +> +>The contracts involved in the quotation are: ERC20 token contract, mapping contract, quotation contract, mining pool contract, and price contract. + +```java +// nToken quotation contract mapping +if (!AddressEnum.USDT_TOKEN_CONTRACT_ADDRESS.getValue().equalsIgnoreCase(EatOfferAndTransactionServiceImpl.ERC20_TOKEN_ADDRESS)) { + String nTokenFactoryAddress = mapping(credentials, web3j, "nToken quotation factory", "nest.nToken.offerMain"); + AddressEnum.OFFER_CONTRACT_FACTORY_ADDRESS.setValue(nTokenFactoryAddress); +} else { + // NEST quote contract address + String nestFactoryAddress = mapping(credentials, web3j, "nest quotation factory", "nest.v3.offerMain"); + AddressEnum.OFFER_CONTRACT_FACTORY_ADDRESS.setValue(nestFactoryAddress); +} + +// Quote price contract +String offerPriceAddress = mapping(credentials, web3j, "Quote the price", "nest.v3.offerPrice"); +AddressEnum.OFFER_PRICE_CONTRACT_ADDRESS.setValue(offerPriceAddress); +``` + +#### 3. Authorized quotation contract ERC20 + +>Arbitrage needs to transfer ERC20 to the quotation contract. The transfer to ERC20 is performed by the quotation contract calling the ERC20 token contract, so ERC20 authorization is required for the quotation contract. + +```java +// Check the approved amount +BigInteger approveValue = allowance(); +BigInteger nonce = ethGetTransactionCount(); +// 1.5 times gasPrice, adjustable +BigInteger gasPrice = ethGasPrice().multiply(BigInteger.valueOf(15)).divide(BigInteger.TEN); +if (approveValue.compareTo(new BigInteger("100000000000000")) <= 0) { + + List typeList = Arrays.asList( + new Address(AddressEnum.OFFER_CONTRACT_FACTORY_ADDRESS.getValue()), + new Uint256(new BigInteger("999999999999999999999999999999999999999999")) + ); + + Function function = new Function("approve", typeList, Collections.>emptyList()); + String encode = FunctionEncoder.encode(function); + String transaction = ethSendErc20RawTransaction(gasPrice, nonce, Constant.OFFER_GAS_LIMIT, BigInteger.ZERO, encode); + LOG.info("One-time authorization hash:" + transaction); +} +``` + +#### 4. Get the latest 100 quotation directly for verification through the quotation contract list interface + +```java +// Get the latest 100 quotation +List list = null; +try { + list = ethClient.list(Constant.LIST_MAX_COUNT); +} catch (Exception e) { + LOG.error("list interface failed to obtain contract data:{}", e.getMessage()); + e.printStackTrace(); +} + +// Traverse the obtained 100 contracts and find the contracts that are in the verification period and whose verifiable amount is greater than 0 +List dataList = new ArrayList<>(); +int size = list.size(); +for (int i = 0; i < size; i++) { + OfferContractData t = list.get(i); + + //nToken take a single verification, only verify the specified ERC20token + if (!EatOfferAndTransactionServiceImpl.ERC20_TOKEN_ADDRESS.equalsIgnoreCase(t.getTokenAddress())) { + continue; + } + + OfferThreeData offerThreeData = new OfferThreeData(); + offerThreeData.setContractAddress(t.getUuid()); + offerThreeData.setErc20TokenAddress(t.getTokenAddress()); + offerThreeData.setErc20TokenName(transactionService.getTokenSymbol()); + offerThreeData.setOwner(t.getOwner()); + offerThreeData.setBlockNumber(new BigInteger(t.getBlockNum())); + offerThreeData.setIntervalBlock(transactionService.getBlockLimit().intValue()); + offerThreeData.setServiceCharge(new BigDecimal(t.getServiceCharge())); + + // Determine whether 25 blocks have passed + if (blockNumber.subtract(offerThreeData.getBlockNumber()).intValue() >= 25) { + continue; + } + + //Determine whether to get it back through whether the balance and handling fee are zero + BigDecimal ethAmount = new BigDecimal(t.getEthAmount()); + BigDecimal erc20Amount = new BigDecimal(t.getTokenAmount()); + if (ethAmount.compareTo(BigDecimal.ZERO) <= 0 + && erc20Amount.compareTo(BigDecimal.ZERO) <= 0 + && offerThreeData.getServiceCharge().compareTo(BigDecimal.ZERO) <= 0) { + continue; + } + + //Determine whether the remaining tradeable balance is 0, + BigDecimal dealEth = new BigDecimal(t.getDealEthAmount()); + BigDecimal dealErc20 = new BigDecimal(t.getDealTokenAmount()); + if (dealEth.compareTo(BigDecimal.ZERO) <= 0 && dealErc20.compareTo(BigDecimal.ZERO) <= 0) { + continue; + } + dataList.add(offerThreeData); +} +return dataList; +} +``` + +#### 5. Get the current ERC20-ETH price of the exchange + +>Get the price of ERC20-ETH through the exchange API with high trading frequency. +> +>Some exchange APIs require overseas nodes to access, the following is the Huobi Exchange API: + +```java +if (HUOBI_API == null) { + LOG.error("Huobi API failed to initialize successfully, and ERC20 symbol failed to get"); + return null; +} +String s = HttpClientUtil.sendHttpGet(HUOBI_API); +if (s == null) { + return null; +} +JSONObject jsonObject = JSONObject.parseObject(s); +JSONArray data = jsonObject.getJSONArray("data"); +if (data == null) { + return null; +} +BigDecimal totalPrice = new BigDecimal("0"); +BigDecimal n = new BigDecimal("0"); +if (data.size() == 0) { + return null; +} + +for (int i = 0; i < data.size(); i++) { + Object o = data.get(i); + JSONObject jsonObject1 = JSONObject.parseObject(String.valueOf(o)); + JSONArray data1 = jsonObject1.getJSONArray("data"); + if (data1 == null) { + continue; + } + if (data1.size() == 0) { + continue; + } + JSONObject jsonObject2 = JSONObject.parseObject(String.valueOf(data1.get(0))); + BigDecimal price = jsonObject2.getBigDecimal("price"); + if (price == null) { + continue; + } + totalPrice = totalPrice.add(price); + n = n.add(new BigDecimal("1")); +} +if (n.compareTo(new BigDecimal("0")) > 0) { + totalPrice = totalPrice.divide(n, 18, BigDecimal.ROUND_DOWN); + // Need to do different processing according to the transaction pair, if it is the end of eth, it must be converted to ethxxx + if (SYMBOLS.endsWith("eth")) { + totalPrice = BigDecimal.ONE.divide(totalPrice, 18, BigDecimal.ROUND_DOWN); + } + return totalPrice; +} +return null; +``` + +#### 6. Initiate an arbitrage transaction + +>Price of the quotation to be verified: the ratio of the ETH quantity to the ERC20 quantity of the quotation to be verified. +> +>The current exchange price is compared with the price of the quotation to be verified, and if the deviation meets expectations, arbitrage can be carried out. +> +>Note: If the price obtained by the current exchange and the latest effective price of the price contract deviate by more than 10%, then the two-way assets (ETH and ERC20) of the arbitrage initiated at the same time must be 10 times. + +#####1. Check whether there is an arbitrage opportunity in the quoted contract. If there is an arbitrage transaction, you must quote twice the amount of arbitrage ETH. + +```java +// Iterate through these contracts to find the contract whose price exceeds the specified offset percentage +for (OfferThreeData offerThreeData : offerThreeDatas) { + // Get contract information + String contractAddress = offerThreeData.getContractAddress(); + OfferContractData contractData = ethClient.getPrice(contractAddress); + if (contractData == null) { + LOG.error("未Find the relevant information of the contract:", contractAddress); + continue; + } + + // Get the exchange price + BigDecimal exchangePrice = getExchangePrice(); + if (exchangePrice == null || exchangePrice.compareTo(BigDecimal.ZERO) == 0) { + LOG.error("Huobi exchange price acquisition failed"); + continue; + } + LOG.info("Exchange price:{}", exchangePrice); + + // The remaining tradeable ETH quantity + BigInteger dealEthAmount = new BigInteger(contractData.getDealEthAmount()); + // Remaining tradable ERC20 quantity + BigInteger dealErc20Amount = new BigInteger(contractData.getDealTokenAmount()); + // Determine whether the quotation contract meets the conditions for taking orders: there is surplus and profitable + boolean canEat = canEat(contractAddress, dealEthAmount, dealErc20Amount, exchangePrice, offerThreeData); + if (!canEat) continue; + + // Get balance + BigInteger ethBalance = ethClient.ethGetBalance(); + BigInteger erc20Balance = ethClient.ethBalanceOfErc20(); + LOG.info("Current account balance:ETH={},{}={}", ethBalance, SYMBOL, erc20Balance); + if (ethBalance == null || erc20Balance == null) { + return; + } + + // The price of the quilt + BigDecimal eatPrice = calPrice(dealErc20Amount, dealEthAmount); + // Get single multiple + BigInteger multiple = getOfferMultiple(exchangePrice, eatPrice); + if (multiple == null) continue; + + // Determine the type of order + boolean eatEth = false; + // The exchange price is greater than the price of the taken order: pay ERC20, eat ETH + if (exchangePrice.compareTo(eatPrice) > 0) { + eatEth = true; + } else { // The exchange price is less than the price of the order being taken: pay EHT, eat ERC20 + eatEth = false; + } + + // Judge whether you can eat all + boolean canEatAll = canEatAll(multiple, exchangePrice, eatEth, dealEthAmount, dealErc20Amount, ethBalance, erc20Balance); + BigInteger copies = null; + // Can eat all + if (canEatAll) { + copies = dealEthAmount.divide(Constant.ONE_ETH_AMOUNT); + } else {//Can't eat all + // 10ETH one unit + copies = getCopies(eatEth, exchangePrice, ethBalance, erc20Balance, eatPrice, multiple); + if (copies.compareTo(BigInteger.ZERO) <= 0) { + LOG.info("Insufficient balance to take orders"); + return; + } + } + + String hash = sendEatOffer(exchangePrice, eatPrice, multiple, eatEth, copies, contractAddress, gasPrice); + Thread.sleep(1000 * 2); +} +``` + +#####2. Get the latest verified price of the price contract and judge the price deviation. + +```java +// Current latest block price +BigDecimal priceNow = checkPriceNow(); +if (priceNow == null) { + LOG.error("The current latest block price has not been successfully obtained"); + return null; +} + +// The offset between the exchange price and the latest effective quotation +BigDecimal offset1 = (priceNow.subtract(exchangePrice)).divide(priceNow, 2, BigDecimal.ROUND_DOWN).abs(); +// The offset between the price of the taken order and the latest effective quote +BigDecimal offset2 = (priceNow.subtract(eatPrice)).divide(priceNow, 2, BigDecimal.ROUND_DOWN).abs(); + +// The exchange price deviates from the latest effective price by more than 10% +if (offset1.compareTo(Constant.OFFER_PRICE_OFFERSET) > 0) { + // The price of the order being taken deviates from the latest effective price by more than 10% + if (offset2.compareTo(Constant.OFFER_PRICE_OFFERSET) > 0) { + // Need 2 times quote + return BigInteger.valueOf(2L); + } + // If the price of the taken order does not deviate by more than 10% from the latest effective quotation, a 10 times quotation will be made + return BigInteger.TEN; +} +// 2 times quote +return BigInteger.valueOf(2L); +``` + +#####3.Initiate a take-order quotation transaction, and save the take-order data for exchange trading after the transaction is successful. + +```java +// take:ETH +BigInteger tranEthAmout = copies.multiply(Constant.ONE_ETH_AMOUNT); +// take:ERC20 +BigInteger tranErc20Amount = MathUtils.toBigInt(MathUtils.decMulInt(eatPrice, copies.multiply(BigInteger.TEN)).multiply(MathUtils.toDecimal(DECIMAL))); +// quote:ETH +BigInteger offerEthAmount = tranEthAmout.multiply(multiple); +// quote:erc20 +BigInteger eth = MathUtils.toBigInt(MathUtils.toDecimal(offerEthAmount).divide(Constant.UNIT_ETH, 0, BigDecimal.ROUND_DOWN)); +BigInteger offerErc20Amount = MathUtils.toBigInt(MathUtils.decMulInt(exchangePrice, eth).multiply(MathUtils.toDecimal(DECIMAL))); +// fee +BigInteger serviceCharge = Constant.SERVICE_CHARGE.multiply(copies); +// ETH fees: quotation, take orders fees +BigInteger payEthAmount = null; + + +String msg = null; +String method = null; + +EatOfferDeal offerDeal = new EatOfferDeal(); +// take ETH +if (eatEth) { + msg = "eatEthtakeorders(transfer{}ObtainETH) ,Hash : {}"; + method = "sendErcBuyEth"; + payEthAmount = offerEthAmount.add(serviceCharge).subtract(tranEthAmout); + + offerDeal.setSellTokenName("eth"); + offerDeal.setSellTokenAmount(MathUtils.toDecimal(tranEthAmout)); +} else { // take ERC20 + msg = "eatErctakeorders(transferETHObtain{}) Hash : {}"; + method = "sendEthBuyErc"; + payEthAmount = offerEthAmount.add(serviceCharge).add(tranEthAmout); + + offerDeal.setSellTokenName(SYMBOL.toLowerCase()); + offerDeal.setSellTokenAmount(MathUtils.toDecimal(tranErc20Amount)); +} + +//Initiate transaction +List typeList = Arrays.asList( + new Uint256(offerEthAmount), + new Uint256(offerErc20Amount), + new Address(contractAddress), + new Uint256(tranEthAmout), + new Uint256(tranErc20Amount), + new Address(ERC20_TOKEN_ADDRESS) +); +LOG.info("Take orders quotations:takeETH={} take{}={} quoteETH={} quote{}={} payEthAmount={}", + tranEthAmout, SYMBOL, tranErc20Amount, offerEthAmount, SYMBOL, offerErc20Amount, payEthAmount); + +String transactionHash = ethClient.sendEatOffer(typeList, payEthAmount, method, gasPrice); + +//Save the take orders, and then trade on the exchange +if (!StringUtils.isEmpty(transactionHash)) { + offerDeal.setOfferHash(transactionHash); + offerDeal.setErc20TokenName(SYMBOL); + offerDeal.setOwner(ethClient.credentials.getAddress()); + offerDeal.setTransactionStatus(1); + + OFFER_DEAL_LIST.add(offerDeal); +} + +LOG.info(msg, SYMBOL, transactionHash); +``` + +#### 8. Retrieve assets + +>Query whether the ETH and ERC20 that have not been retrieved are both 0. If there is still remaining, and the price has passed 25 blocks, then initiate a retrieval transaction. + +```java +// The find interface gets the take-order quotation contract that you have not retrieved +List offerContractAddresses = getOfferContractAddress(); +if (offerContractAddresses.size() == 0) { + LOG.info("There is currently no quotation contract that needs to be retrieved"); + return; +} + +System.out.println("Unrecovered assets:====" + offerContractAddresses.size()); +BigInteger gasPrice = null; +try { + gasPrice = ethClient.ethGasPrice(); +} catch (IOException e) { + LOG.error("An exception occurred when getting gasPrice when retrieving:" + e); +} +gasPrice = gasPrice.multiply(Constant.TURNOUT_GAS_PRICE_MULTIPLE).divide(BigInteger.TEN); +BigInteger nonce = null; +try { + nonce = ethClient.ethGetTransactionCount(); +} catch (IOException e) { + LOG.error("An exception occurred when getting the nonce when retrieving it:" + e); +} + +// Traverse and retrieve all assets +for (OfferContractData contractData : offerContractAddresses) { + + List typeList = Arrays.asList(new Address(contractData.getUuid())); + String transaction = null; + try { + transaction = ethClient.turnOut(nonce, typeList, gasPrice); + } catch (Exception e) { + LOG.error("Abnormal return price", e.getMessage()); + } + nonce = nonce.add(BigInteger.ONE); + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + LOG.info("retrieve hash: " + transaction); +} +``` + +#### 9. Exchange trading + +>You need to create an Access Key and Secret Key in the Huobi Exchange API management, and fill in the withdrawal address in the withdrawal address management + +```java +// Check whether exchange trading is enabled +if (!START_HUOBI_EXCHANGE) { + return; +} + +// Check whether the API-KEY of the exchange is set +if (API_KEY.equalsIgnoreCase("") || API_SECRET.equalsIgnoreCase("")) { + System.out.println("If the asset needs to be exchanged on the exchange after taking a quote, please set the API-KEY of the exchange and open the deposit and withdrawal permissions"); + return; +} + +//When there is no unfinished or pending transaction, initiate a withdrawal operation +if (CollectionUtils.isEmpty(OFFER_DEAL_LIST)) { + System.out.println("There are no outstanding or pending transactions"); + // At this time, initiate a withdrawal operation + getToken("eth"); + getToken(EatOfferAndTransactionServiceImpl.SYMBOL.toLowerCase()); + return; +} + +// Traverse the data of taking orders and then buy and sell +for (EatOfferDeal offerDeal : OFFER_DEAL_LIST) { + System.out.println(offerDeal.toString()); + int transactionStatus = offerDeal.getTransactionStatus(); + + switch (transactionStatus) { + // Have a task, recharge + case 1: + LOG.info("Receipt of deposit to exchange task"); + recharge(offerDeal); + break; + // Recharge has been completed, initiate an order + case 2: + LOG.info("Enter the trading"); + if (makeOrder(offerDeal)) return; + break; + } +} +``` + diff --git a/NestEatOffer/eatOffer.iml b/NestEatOffer/eatOffer.iml new file mode 100644 index 0000000..72977ee --- /dev/null +++ b/NestEatOffer/eatOffer.iml @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/NestEatOffer/pom.xml b/NestEatOffer/pom.xml new file mode 100644 index 0000000..aab1237 --- /dev/null +++ b/NestEatOffer/pom.xml @@ -0,0 +1,121 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.6.RELEASE + + + com.nest + eatOffer + 0.0.1-SNAPSHOT + eatOffer + Demo project for Spring Boot + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web + + + spring-boot-starter-logging + org.springframework.boot + + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + com.google.guava + guava + 22.0 + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + + org.springframework.boot + spring-boot-starter-tomcat + + + + org.apache.httpcomponents + httpcore + + + + junit + junit + 4.12 + + + + org.apache.commons + commons-lang3 + 3.8.1 + + + + com.alibaba + fastjson + 1.2.56 + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + com.google.code.gson + gson + 2.8.5 + + + + org.web3j + core + 3.3.1 + + + + + org.apache.httpcomponents + httpclient + 4.3.5 + + + + org.apache.httpcomponents + httpmime + 4.5.6 + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/NestEatOffer/src/main/java/com/nest/ib/IbApplication.java b/NestEatOffer/src/main/java/com/nest/ib/IbApplication.java new file mode 100644 index 0000000..9b4ace0 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/IbApplication.java @@ -0,0 +1,17 @@ +package com.nest.ib; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) +@EnableScheduling +public class IbApplication { + + public static void main(String[] args) { + SpringApplication.run(IbApplication.class, args); + } + +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/config/ListenerAsyncConfiguration.java b/NestEatOffer/src/main/java/com/nest/ib/config/ListenerAsyncConfiguration.java new file mode 100644 index 0000000..b4921a7 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/config/ListenerAsyncConfiguration.java @@ -0,0 +1,36 @@ +package com.nest.ib.config; + +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.AsyncConfigurer; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; + +@Configuration +@EnableAsync +public class ListenerAsyncConfiguration implements AsyncConfigurer { + + /** + * Gets the asynchronous thread pool execution object + * + * @return + */ + @Override + public Executor getAsyncExecutor() { + // Use the Spring built-in thread pool task object + ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); + // Set the thread pool parameters + taskExecutor.setCorePoolSize(5); + taskExecutor.setMaxPoolSize(10); + taskExecutor.setQueueCapacity(25); + taskExecutor.initialize(); + return taskExecutor; + } + + @Override + public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { + return null; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/config/MvcConfig.java b/NestEatOffer/src/main/java/com/nest/ib/config/MvcConfig.java new file mode 100644 index 0000000..27ff9f7 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/config/MvcConfig.java @@ -0,0 +1,35 @@ +package com.nest.ib.config; + +import com.nest.ib.interceptor.PermissionInterceptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class MvcConfig implements WebMvcConfigurer { + + @Autowired + private PermissionInterceptor permissionInterceptor; + + /** + * + * @param registry + */ + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOrigins("*") + .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") + .allowCredentials(true).maxAge(3600); + } + + /** + * Add interceptor + */ + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(permissionInterceptor); + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/constant/AddressEnum.java b/NestEatOffer/src/main/java/com/nest/ib/constant/AddressEnum.java new file mode 100644 index 0000000..3f05874 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/constant/AddressEnum.java @@ -0,0 +1,44 @@ +package com.nest.ib.constant; + +/** + * @author wll + * @date 2020/7/20 10:54 + * Contract address + */ +public enum AddressEnum { + + /** + * Offer price contract address + */ + OFFER_PRICE_CONTRACT_ADDRESS(""), + + /** + * Quotation Factory Contract + */ + OFFER_CONTRACT_FACTORY_ADDRESS(""), + + /** + * USDT contract address: Calibration quote type, unchangeable + */ + USDT_TOKEN_CONTRACT_ADDRESS("0xdac17f958d2ee523a2206206994597c13d831ec7"), + + /** + * Voting contract address: Maps each contract address and cannot be changed + */ + VOTE_CONTRACT_ADDRESS("0x6Cd5698E8854Fb6879d6B1C694223b389B465dea") + ; + + AddressEnum(String value) { + this.value = value; + } + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/constant/Constant.java b/NestEatOffer/src/main/java/com/nest/ib/constant/Constant.java new file mode 100644 index 0000000..463dd74 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/constant/Constant.java @@ -0,0 +1,76 @@ +package com.nest.ib.constant; + +import java.math.BigDecimal; +import java.math.BigInteger; + +/** + * @author wll + * @date 2020/7/16 13:22 + */ +public interface Constant { + + /** + * The multiplier of gasPrice of arbitrage quotation:15/10 + */ + BigInteger EAT_OFFER_GAS_PRICE_MULTIPLE = new BigInteger("15"); + + /** + * GasPrice multiplier of quotation launched when retrieving arbitrage:12/10 + */ + BigInteger TURNOUT_GAS_PRICE_MULTIPLE = new BigInteger("12"); + + /** + * The default block interval T0 + */ + BigInteger DEFAULT_BLOCK_LIMIT = new BigInteger("25"); + + /** + * The number of ETH required to eat a single quote (WEI) + */ + BigInteger ONE_ETH_AMOUNT = new BigInteger("10000000000000000000"); + + /** + * Default miner packing fee + */ + BigInteger PACKAGING_COSTS = new BigInteger("200000000000000000"); + + /** + * Order gasLimit + */ + BigInteger OFFER_GAS_LIMIT = new BigInteger("2000000"); + + /** + * Fetch the transaction gasLimit + */ + BigInteger TURN_OUT_GAS_LIMIT = new BigInteger("200000"); + + /** + * The ETH unit + */ + BigDecimal UNIT_ETH = new BigDecimal("1000000000000000000"); + + /** + * Total amount of 10ETH quotation fee + */ + BigInteger SERVICE_CHARGE = new BigInteger("10000000000000000"); + + /** + * If the price offset exceeds 10%, the minimum quotation amount should be multiplied by 10 + */ + BigDecimal OFFER_PRICE_OFFERSET = new BigDecimal("0.1"); + + /** + * The list interface has the maximum number of queries per session:100 + */ + BigInteger LIST_MAX_COUNT = BigInteger.valueOf(100L); + + /** + * Gets the first query for an unretrieved asset contract + */ + BigInteger FIRST_FIND_COUNT = BigInteger.valueOf(50L); + + /** + * Find maxFindCount records up to 100 quote contracts at a time to find your own quote contract + */ + BigInteger MAX_FIND_COUNT = BigInteger.valueOf(100L); +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/contract/ERC20.java b/NestEatOffer/src/main/java/com/nest/ib/contract/ERC20.java new file mode 100644 index 0000000..9c11894 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/contract/ERC20.java @@ -0,0 +1,256 @@ +package com.nest.ib.contract; + +import org.web3j.abi.EventEncoder; +import org.web3j.abi.TypeReference; +import org.web3j.abi.datatypes.Address; +import org.web3j.abi.datatypes.Event; +import org.web3j.abi.datatypes.Function; +import org.web3j.abi.datatypes.Type; +import org.web3j.abi.datatypes.Utf8String; +import org.web3j.abi.datatypes.generated.Uint256; +import org.web3j.abi.datatypes.generated.Uint8; +import org.web3j.crypto.Credentials; +import org.web3j.protocol.Web3j; +import org.web3j.protocol.core.DefaultBlockParameter; +import org.web3j.protocol.core.RemoteCall; +import org.web3j.protocol.core.methods.request.EthFilter; +import org.web3j.protocol.core.methods.response.Log; +import org.web3j.protocol.core.methods.response.TransactionReceipt; +import org.web3j.tx.Contract; +import org.web3j.tx.TransactionManager; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import rx.Observable; +import rx.functions.Func1; + +/** + *

Auto generated code. + *

Do not modify! + *

Please use the web3j command line tools, + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the + * codegen module to update. + * + *

Generated with web3j version 3.3.1. + */ +public class ERC20 extends Contract { + private static final String BINARY = "60606040526040805190810160405280600981526020017f4c6f6f6d546f6b656e0000000000000000000000000000000000000000000000815250600390805190602001906200005192919062000135565b506040805190810160405280600481526020017f4c4f4f4d00000000000000000000000000000000000000000000000000000000815250600490805190602001906200009f92919062000135565b506012600560006101000a81548160ff021916908360ff1602179055503415620000c857600080fd5b600560009054906101000a900460ff1660ff16600a0a633b9aca00026001819055506001546000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550620001e4565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200017857805160ff1916838001178555620001a9565b82800160010185558215620001a9579182015b82811115620001a85782518255916020019190600101906200018b565b5b509050620001b89190620001bc565b5090565b620001e191905b80821115620001dd576000816000905550600101620001c3565b5090565b90565b6112e180620001f46000396000f3006060604052600436106100ba576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100bf578063095ea7b31461014d57806318160ddd146101a757806323b872dd146101d05780632ff2e9dc14610249578063313ce5671461027257806366188463146102a157806370a08231146102fb57806395d89b4114610348578063a9059cbb146103d6578063d73dd62314610430578063dd62ed3e1461048a575b600080fd5b34156100ca57600080fd5b6100d26104f6565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101125780820151818401526020810190506100f7565b50505050905090810190601f16801561013f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561015857600080fd5b61018d600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610594565b604051808215151515815260200191505060405180910390f35b34156101b257600080fd5b6101ba610686565b6040518082815260200191505060405180910390f35b34156101db57600080fd5b61022f600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610690565b604051808215151515815260200191505060405180910390f35b341561025457600080fd5b61025c610a4a565b6040518082815260200191505060405180910390f35b341561027d57600080fd5b610285610a52565b604051808260ff1660ff16815260200191505060405180910390f35b34156102ac57600080fd5b6102e1600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610a65565b604051808215151515815260200191505060405180910390f35b341561030657600080fd5b610332600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610cf6565b6040518082815260200191505060405180910390f35b341561035357600080fd5b61035b610d3e565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561039b578082015181840152602081019050610380565b50505050905090810190601f1680156103c85780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34156103e157600080fd5b610416600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610ddc565b604051808215151515815260200191505060405180910390f35b341561043b57600080fd5b610470600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610ffb565b604051808215151515815260200191505060405180910390f35b341561049557600080fd5b6104e0600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506111f7565b6040518082815260200191505060405180910390f35b60038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561058c5780601f106105615761010080835404028352916020019161058c565b820191906000526020600020905b81548152906001019060200180831161056f57829003601f168201915b505050505081565b600081600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b6000600154905090565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16141515156106cd57600080fd5b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054821115151561071a57600080fd5b600260008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482111515156107a557600080fd5b6107f6826000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461127e90919063ffffffff16565b6000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610889826000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461129790919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061095a82600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461127e90919063ffffffff16565b600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190509392505050565b633b9aca0081565b600560009054906101000a900460ff1681565b600080600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905080831115610b76576000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610c0a565b610b89838261127e90919063ffffffff16565b600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b8373ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a3600191505092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60048054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610dd45780601f10610da957610100808354040283529160200191610dd4565b820191906000526020600020905b815481529060010190602001808311610db757829003601f168201915b505050505081565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515610e1957600080fd5b6000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020548211151515610e6657600080fd5b610eb7826000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461127e90919063ffffffff16565b6000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610f4a826000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461129790919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b600061108c82600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461129790919063ffffffff16565b600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a36001905092915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600082821115151561128c57fe5b818303905092915050565b60008082840190508381101515156112ab57fe5b80915050929150505600a165627a7a72305820d1b29c2a9b3d8747ac9eb4d8a3de869bad3b44a8ef89287d144828e760ac6a2d0029"; + + protected ERC20(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected ERC20(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public List getApprovalEvents(TransactionReceipt transactionReceipt) { + final Event event = new Event("Approval", + Arrays.>asList(new TypeReference

() {}, new TypeReference
() {}), + Arrays.>asList(new TypeReference() {})); + List valueList = extractEventParametersWithLog(event, transactionReceipt); + ArrayList responses = new ArrayList(valueList.size()); + for (EventValuesWithLog eventValues : valueList) { + ApprovalEventResponse typedResponse = new ApprovalEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.owner = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.spender = (String) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public Observable approvalEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + final Event event = new Event("Approval", + Arrays.>asList(new TypeReference
() {}, new TypeReference
() {}), + Arrays.>asList(new TypeReference() {})); + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(event)); + return web3j.ethLogObservable(filter).map(new Func1() { + @Override + public ApprovalEventResponse call(Log log) { + EventValuesWithLog eventValues = extractEventParametersWithLog(event, log); + ApprovalEventResponse typedResponse = new ApprovalEventResponse(); + typedResponse.log = log; + typedResponse.owner = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.spender = (String) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + return typedResponse; + } + }); + } + + public List getTransferEvents(TransactionReceipt transactionReceipt) { + final Event event = new Event("Transfer", + Arrays.>asList(new TypeReference
() {}, new TypeReference
() {}), + Arrays.>asList(new TypeReference() {})); + List valueList = extractEventParametersWithLog(event, transactionReceipt); + ArrayList responses = new ArrayList(valueList.size()); + for (EventValuesWithLog eventValues : valueList) { + TransferEventResponse typedResponse = new TransferEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.to = (String) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public Observable transferEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + final Event event = new Event("Transfer", + Arrays.>asList(new TypeReference
() {}, new TypeReference
() {}), + Arrays.>asList(new TypeReference() {})); + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(event)); + return web3j.ethLogObservable(filter).map(new Func1() { + @Override + public TransferEventResponse call(Log log) { + EventValuesWithLog eventValues = extractEventParametersWithLog(event, log); + TransferEventResponse typedResponse = new TransferEventResponse(); + typedResponse.log = log; + typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.to = (String) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + return typedResponse; + } + }); + } + + public RemoteCall name() { + final Function function = new Function("name", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteCall approve(String _spender, BigInteger _value) { + final Function function = new Function( + "approve", + Arrays.asList(new Address(_spender), + new Uint256(_value)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall totalSupply() { + final Function function = new Function("totalSupply", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall transferFrom(String _from, String _to, BigInteger _value) { + final Function function = new Function( + "transferFrom", + Arrays.asList(new Address(_from), + new Address(_to), + new Uint256(_value)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall INITIAL_SUPPLY() { + final Function function = new Function("INITIAL_SUPPLY", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall decimals() { + final Function function = new Function("decimals", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall decreaseApproval(String _spender, BigInteger _subtractedValue) { + final Function function = new Function( + "decreaseApproval", + Arrays.asList(new Address(_spender), + new Uint256(_subtractedValue)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall balanceOf(String _owner) { + final Function function = new Function("balanceOf", + Arrays.asList(new Address(_owner)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall symbol() { + final Function function = new Function("symbol", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteCall transfer(String _to, BigInteger _value) { + final Function function = new Function( + "transfer", + Arrays.asList(new Address(_to), + new Uint256(_value)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall increaseApproval(String _spender, BigInteger _addedValue) { + final Function function = new Function( + "increaseApproval", + Arrays.asList(new Address(_spender), + new Uint256(_addedValue)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall allowance(String _owner, String _spender) { + final Function function = new Function("allowance", + Arrays.asList(new Address(_owner), + new Address(_spender)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(ERC20.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(ERC20.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } + + public static ERC20 load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return new ERC20(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + public static ERC20 load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return new ERC20(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static class ApprovalEventResponse { + public Log log; + + public String owner; + + public String spender; + + public BigInteger value; + } + + public static class TransferEventResponse { + public Log log; + + public String from; + + public String to; + + public BigInteger value; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/contract/MappingContract.java b/NestEatOffer/src/main/java/com/nest/ib/contract/MappingContract.java new file mode 100644 index 0000000..3b1583c --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/contract/MappingContract.java @@ -0,0 +1,93 @@ +package com.nest.ib.contract; + +import org.web3j.abi.TypeReference; +import org.web3j.abi.datatypes.Address; +import org.web3j.abi.datatypes.Bool; +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; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collections; + +/** + *

Auto generated code. + *

Do not modify! + *

Please use the web3j command line tools, + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the + * codegen module to update. + * + *

Generated with web3j version 3.3.1. + */ +public class MappingContract extends Contract { + private static final String BINARY = "608060405234801561001057600080fd5b5060018060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055506105df806100776000396000f3fe608060405234801561001057600080fd5b50600436106100575760003560e01c806353b1e0971461005c5780638fe77e8614610137578063a3bf06f114610232578063b6518bdb1461028e578063c7d55057146102d2575b600080fd5b6101356004803603604081101561007257600080fd5b810190808035906020019064010000000081111561008f57600080fd5b8201836020820111156100a157600080fd5b803590602001918460018302840111640100000000831117156100c357600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f820116905080830192505050505050509192919290803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610316565b005b6101f06004803603602081101561014d57600080fd5b810190808035906020019064010000000081111561016a57600080fd5b82018360208201111561017c57600080fd5b8035906020019184600183028401116401000000008311171561019e57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506103db565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6102746004803603602081101561024857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061046d565b604051808215151515815260200191505060405180910390f35b6102d0600480360360208110156102a457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506104c3565b005b610314600480360360208110156102e857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610536565b005b600115156103233361046d565b15151461032f57600080fd5b806000836040518082805190602001908083835b602083106103665780518252602082019150602081019050602083039250610343565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505050565b600080826040518082805190602001908083835b6020831061041257805182526020820191506020810190506020830392506103ef565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff169050919050565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff169050919050565b600115156104d03361046d565b1515146104dc57600080fd5b60018060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff02191690831515021790555050565b600115156105433361046d565b15151461054f57600080fd5b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055505056fea265627a7a723158202619ee23ce37cfc39537a810682693117b59f9df4e31e650cdcd0111b15046b364736f6c63430005110032"; + + protected MappingContract(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected MappingContract(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(MappingContract.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(MappingContract.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } + + public RemoteCall addContractAddress(String name, String contractAddress) { + final Function function = new Function( + "addContractAddress", + Arrays.asList(new org.web3j.abi.datatypes.Utf8String(name), + new Address(contractAddress)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall addSuperMan(String superMan) { + final Function function = new Function( + "addSuperMan", + Arrays.asList(new Address(superMan)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall checkAddress(String name) { + final Function function = new Function("checkAddress", + Arrays.asList(new org.web3j.abi.datatypes.Utf8String(name)), + Arrays.>asList(new TypeReference

() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteCall checkOwners(String man) { + final Function function = new Function("checkOwners", + Arrays.asList(new Address(man)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, Boolean.class); + } + + public RemoteCall deleteSuperMan(String superMan) { + final Function function = new Function( + "deleteSuperMan", + Arrays.asList(new Address(superMan)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public static MappingContract load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return new MappingContract(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + public static MappingContract load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return new MappingContract(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/contract/Nest3OfferMain.java b/NestEatOffer/src/main/java/com/nest/ib/contract/Nest3OfferMain.java new file mode 100644 index 0000000..39a00ba --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/contract/Nest3OfferMain.java @@ -0,0 +1,536 @@ +package com.nest.ib.contract; + +import org.web3j.abi.EventEncoder; +import org.web3j.abi.FunctionEncoder; +import org.web3j.abi.TypeReference; +import org.web3j.abi.datatypes.*; +import org.web3j.abi.datatypes.generated.Uint256; +import org.web3j.abi.datatypes.generated.Uint32; +import org.web3j.crypto.Credentials; +import org.web3j.protocol.Web3j; +import org.web3j.protocol.core.DefaultBlockParameter; +import org.web3j.protocol.core.RemoteCall; +import org.web3j.protocol.core.methods.request.EthFilter; +import org.web3j.protocol.core.methods.response.Log; +import org.web3j.protocol.core.methods.response.TransactionReceipt; +import org.web3j.tx.Contract; +import org.web3j.tx.TransactionManager; +import rx.Observable; +import rx.functions.Func1; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + *

Auto generated code. + *

Do not modify! + *

Please use the web3j command line tools, + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the + * codegen module to update. + * + *

Generated with web3j version 3.3.1. + */ +public class Nest3OfferMain extends Contract { + private static final String BINARY = ""; + + protected Nest3OfferMain(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected Nest3OfferMain(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public List getOfferContractAddressEvents(TransactionReceipt transactionReceipt) { + final Event event = new Event("OfferContractAddress", + Arrays.>asList(), + Arrays.>asList(new TypeReference

() {}, new TypeReference
() {}, new TypeReference() {}, new TypeReference() {}, new TypeReference() {}, new TypeReference() {})); + List valueList = extractEventParametersWithLog(event, transactionReceipt); + ArrayList responses = new ArrayList(valueList.size()); + for (EventValuesWithLog eventValues : valueList) { + OfferContractAddressEventResponse typedResponse = new OfferContractAddressEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.contractAddress = (String) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.tokenAddress = (String) eventValues.getNonIndexedValues().get(1).getValue(); + typedResponse.ethAmount = (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); + typedResponse.erc20Amount = (BigInteger) eventValues.getNonIndexedValues().get(3).getValue(); + typedResponse.continued = (BigInteger) eventValues.getNonIndexedValues().get(4).getValue(); + typedResponse.serviceCharge = (BigInteger) eventValues.getNonIndexedValues().get(5).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public Observable offerContractAddressEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + final Event event = new Event("OfferContractAddress", + Arrays.>asList(), + Arrays.>asList(new TypeReference
() {}, new TypeReference
() {}, new TypeReference() {}, new TypeReference() {}, new TypeReference() {}, new TypeReference() {})); + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(event)); + return web3j.ethLogObservable(filter).map(new Func1() { + @Override + public OfferContractAddressEventResponse call(Log log) { + EventValuesWithLog eventValues = extractEventParametersWithLog(event, log); + OfferContractAddressEventResponse typedResponse = new OfferContractAddressEventResponse(); + typedResponse.log = log; + typedResponse.contractAddress = (String) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.tokenAddress = (String) eventValues.getNonIndexedValues().get(1).getValue(); + typedResponse.ethAmount = (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); + typedResponse.erc20Amount = (BigInteger) eventValues.getNonIndexedValues().get(3).getValue(); + typedResponse.continued = (BigInteger) eventValues.getNonIndexedValues().get(4).getValue(); + typedResponse.serviceCharge = (BigInteger) eventValues.getNonIndexedValues().get(5).getValue(); + return typedResponse; + } + }); + } + + public List getOfferTranEvents(TransactionReceipt transactionReceipt) { + final Event event = new Event("OfferTran", + Arrays.>asList(), + Arrays.>asList(new TypeReference
() {}, new TypeReference
() {}, new TypeReference() {}, new TypeReference
() {}, new TypeReference() {}, new TypeReference
() {}, new TypeReference
() {})); + List valueList = extractEventParametersWithLog(event, transactionReceipt); + ArrayList responses = new ArrayList(valueList.size()); + for (EventValuesWithLog eventValues : valueList) { + OfferTranEventResponse typedResponse = new OfferTranEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.tranSender = (String) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.tranToken = (String) eventValues.getNonIndexedValues().get(1).getValue(); + typedResponse.tranAmount = (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); + typedResponse.otherToken = (String) eventValues.getNonIndexedValues().get(3).getValue(); + typedResponse.otherAmount = (BigInteger) eventValues.getNonIndexedValues().get(4).getValue(); + typedResponse.tradedContract = (String) eventValues.getNonIndexedValues().get(5).getValue(); + typedResponse.tradedOwner = (String) eventValues.getNonIndexedValues().get(6).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public Observable offerTranEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + final Event event = new Event("OfferTran", + Arrays.>asList(), + Arrays.>asList(new TypeReference
() {}, new TypeReference
() {}, new TypeReference() {}, new TypeReference
() {}, new TypeReference() {}, new TypeReference
() {}, new TypeReference
() {})); + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(event)); + return web3j.ethLogObservable(filter).map(new Func1() { + @Override + public OfferTranEventResponse call(Log log) { + EventValuesWithLog eventValues = extractEventParametersWithLog(event, log); + OfferTranEventResponse typedResponse = new OfferTranEventResponse(); + typedResponse.log = log; + typedResponse.tranSender = (String) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.tranToken = (String) eventValues.getNonIndexedValues().get(1).getValue(); + typedResponse.tranAmount = (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); + typedResponse.otherToken = (String) eventValues.getNonIndexedValues().get(3).getValue(); + typedResponse.otherAmount = (BigInteger) eventValues.getNonIndexedValues().get(4).getValue(); + typedResponse.tradedContract = (String) eventValues.getNonIndexedValues().get(5).getValue(); + typedResponse.tradedOwner = (String) eventValues.getNonIndexedValues().get(6).getValue(); + return typedResponse; + } + }); + } + + public RemoteCall checkDelayedAgain() { + final Function function = new Function("checkDelayedAgain", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall checkOfferBlockMining(BigInteger blockNum) { + final Function function = new Function("checkOfferBlockMining", + Arrays.asList(new Uint256(blockNum)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall changeTokenAllow(String token, Boolean allow) { + final Function function = new Function( + "changeTokenAllow", + Arrays.asList(new Address(token), + new Bool(allow)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall changeDeviationFromScale(BigInteger num) { + final Function function = new Function( + "changeDeviationFromScale", + Arrays.asList(new Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall checkDelayedAgain(BigInteger num) { + final Function function = new Function( + "checkDelayedAgain", + Arrays.asList(new Uint32(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall checkTranAddition() { + final Function function = new Function("checkTranAddition", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall list(BigInteger offset, BigInteger count, BigInteger order) { + final Function function = new Function("list", + Arrays.asList(new Uint256(offset), + new Uint256(count), + new Uint256(order)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteCall changeTranEth(BigInteger num) { + final Function function = new Function( + "changeTranEth", + Arrays.asList(new Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall checkTokenAllow(String token) { + final Function function = new Function("checkTokenAllow", + Arrays.asList(new Address(token)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, Boolean.class); + } + + public RemoteCall checkTranEth() { + final Function function = new Function("checkTranEth", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall changeDelayed(BigInteger num) { + final Function function = new Function( + "changeDelayed", + Arrays.asList(new Uint32(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall changeBlockLimit(BigInteger num) { + final Function function = new Function( + "changeBlockLimit", + Arrays.asList(new Uint32(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall checkDelayed() { + final Function function = new Function("checkDelayed", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall checkOfferEthLimit() { + final Function function = new Function("checkOfferEthLimit", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall changeInitialRatio(BigInteger coderNum, BigInteger NNNum, BigInteger otherNum) { + final Function function = new Function( + "changeInitialRatio", + Arrays.asList(new Uint256(coderNum), + new Uint256(NNNum), + new Uint256(otherNum)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall checkDeviationFromScale() { + final Function function = new Function("checkDeviationFromScale", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall checkDeviate() { + final Function function = new Function("checkDeviate", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall checkNNAmount() { + final Function function = new Function("checkNNAmount", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall checkCoderAmount() { + final Function function = new Function("checkCoderAmount", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall checkOfferSpan() { + final Function function = new Function("checkOfferSpan", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall sendEthBuyErc(BigInteger ethAmount, BigInteger tokenAmount, String contractAddress, BigInteger tranEthAmount, BigInteger tranTokenAmount, String tranTokenAddress, BigInteger weiValue) { + final Function function = new Function( + "sendEthBuyErc", + Arrays.asList(new Uint256(ethAmount), + new Uint256(tokenAmount), + new Address(contractAddress), + new Uint256(tranEthAmount), + new Uint256(tranTokenAmount), + new Address(tranTokenAddress)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function, weiValue); + } + + public RemoteCall toIndex(String contractAddress) { + final Function function = new Function("toIndex", + Arrays.asList(new Address(contractAddress)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall checkContractState(BigInteger delayedBlock, BigInteger createBlock) { + final Function function = new Function("checkContractState", + Arrays.asList(new Uint256(delayedBlock), + new Uint256(createBlock)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall checkOtherAmount() { + final Function function = new Function("checkOtherAmount", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall writeUInt(BigInteger iv, byte[] buf, BigInteger index) { + final Function function = new Function("writeUInt", + Arrays.asList(new Uint256(iv), + new org.web3j.abi.datatypes.DynamicBytes(buf), + new Uint256(index)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall changeMapping(String voteFacory) { + final Function function = new Function( + "changeMapping", + Arrays.asList(new Address(voteFacory)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall changeMiningETH(BigInteger num) { + final Function function = new Function( + "changeMiningETH", + Arrays.asList(new Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall sendErcBuyEth(BigInteger ethAmount, BigInteger tokenAmount, String contractAddress, BigInteger tranEthAmount, BigInteger tranTokenAmount, String tranTokenAddress, BigInteger weiValue) { + final Function function = new Function( + "sendErcBuyEth", + Arrays.asList(new Uint256(ethAmount), + new Uint256(tokenAmount), + new Address(contractAddress), + new Uint256(tranEthAmount), + new Uint256(tranTokenAmount), + new Address(tranTokenAddress)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function, weiValue); + } + + public RemoteCall changekDeviate(BigInteger num) { + final Function function = new Function( + "changekDeviate", + Arrays.asList(new Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall changeTranAddition(BigInteger num) { + final Function function = new Function( + "changeTranAddition", + Arrays.asList(new Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall changeOfferEthLimit(BigInteger num) { + final Function function = new Function( + "changeOfferEthLimit", + Arrays.asList(new Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall checkOfferBlockEth(BigInteger blockNum) { + final Function function = new Function("checkOfferBlockEth", + Arrays.asList(new Uint256(blockNum)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall getPriceCount() { + final Function function = new Function("getPriceCount", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall checkBlockLimit() { + final Function function = new Function("checkBlockLimit", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall find(String start, BigInteger count, BigInteger maxFindCount, String owner) { + final Function function = new Function("find", + Arrays.asList(new Address(start), + new Uint256(count), + new Uint256(maxFindCount), + new Address(owner)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteCall checkMiningETH() { + final Function function = new Function("checkMiningETH", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall toAddress(BigInteger index) { + final Function function = new Function("toAddress", + Arrays.asList(new Uint256(index)), + Arrays.>asList(new TypeReference
() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteCall changeLeastEth(BigInteger num) { + final Function function = new Function( + "changeLeastEth", + Arrays.asList(new Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall getPrice(BigInteger priceIndex) { + final Function function = new Function("getPrice", + Arrays.asList(new Uint256(priceIndex)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteCall turnOut(String contractAddress) { + final Function function = new Function( + "turnOut", + Arrays.asList(new Address(contractAddress)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall changeOfferSpan(BigInteger num) { + final Function function = new Function( + "changeOfferSpan", + Arrays.asList(new Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall offer(BigInteger ethAmount, BigInteger erc20Amount, String erc20Address, BigInteger weiValue) { + final Function function = new Function( + "offer", + Arrays.asList(new Uint256(ethAmount), + new Uint256(erc20Amount), + new Address(erc20Address)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function, weiValue); + } + + public RemoteCall checkleastEth() { + final Function function = new Function("checkleastEth", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall checkOfferMining(BigInteger blockNum, BigInteger serviceCharge) { + final Function function = new Function("checkOfferMining", + Arrays.asList(new Uint256(blockNum), + new Uint256(serviceCharge)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, String voteFacory) { + String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new Address(voteFacory))); + return deployRemoteCall(Nest3OfferMain.class, web3j, credentials, gasPrice, gasLimit, BINARY, encodedConstructor); + } + + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, String voteFacory) { + String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new Address(voteFacory))); + return deployRemoteCall(Nest3OfferMain.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, encodedConstructor); + } + + public static Nest3OfferMain load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return new Nest3OfferMain(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + public static Nest3OfferMain load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return new Nest3OfferMain(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static class OfferContractAddressEventResponse { + public Log log; + + public String contractAddress; + + public String tokenAddress; + + public BigInteger ethAmount; + + public BigInteger erc20Amount; + + public BigInteger continued; + + public BigInteger serviceCharge; + } + + public static class OfferTranEventResponse { + public Log log; + + public String tranSender; + + public String tranToken; + + public BigInteger tranAmount; + + public String otherToken; + + public BigInteger otherAmount; + + public String tradedContract; + + public String tradedOwner; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/contract/NestOfferPriceContract.java b/NestEatOffer/src/main/java/com/nest/ib/contract/NestOfferPriceContract.java new file mode 100644 index 0000000..41c5086 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/contract/NestOfferPriceContract.java @@ -0,0 +1,252 @@ +package com.nest.ib.contract; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import org.web3j.abi.EventEncoder; +import org.web3j.abi.FunctionEncoder; +import org.web3j.abi.TypeReference; +import org.web3j.abi.datatypes.Address; +import org.web3j.abi.datatypes.Bool; +import org.web3j.abi.datatypes.Event; +import org.web3j.abi.datatypes.Function; +import org.web3j.abi.datatypes.Type; +import org.web3j.abi.datatypes.generated.Uint256; +import org.web3j.crypto.Credentials; +import org.web3j.protocol.Web3j; +import org.web3j.protocol.core.DefaultBlockParameter; +import org.web3j.protocol.core.RemoteCall; +import org.web3j.protocol.core.methods.request.EthFilter; +import org.web3j.protocol.core.methods.response.Log; +import org.web3j.protocol.core.methods.response.TransactionReceipt; +import org.web3j.tuples.generated.Tuple2; +import org.web3j.tx.Contract; +import org.web3j.tx.TransactionManager; +import rx.Observable; +import rx.functions.Func1; + +/** + *

Auto generated code. + *

Do not modify! + *

Please use the web3j command line tools, + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the + * codegen module to update. + * + *

Generated with web3j version 3.3.1. + */ +public class NestOfferPriceContract extends Contract { + private static final String BINARY = "6080604052662386f26fc10000600455600260055560086006553480156200002657600080fd5b5060405160208062002962833981018060405260208110156200004857600080fd5b8101908080519060200190929190505050806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638fe77e866040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260118152602001807f6e6573742e76332e6f666665724d61696e00000000000000000000000000000081525060200191505060206040518083038186803b1580156200015957600080fd5b505afa1580156200016e573d6000803e3d6000fd5b505050506040513d60208110156200018557600080fd5b8101908080519060200190929190505050600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638fe77e866040518163ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018281038252600e8152602001807f6e6573742e76332e61626f6e757300000000000000000000000000000000000081525060200191505060206040518083038186803b1580156200029657600080fd5b505afa158015620002ab573d6000803e3d6000fd5b505050506040513d6020811015620002c257600080fd5b8101908080519060200190929190505050600760006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505061263e80620003246000396000f3fe6080604052600436106100c5576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806308d0099e146100ca57806317ae7a581461016d5780631892f494146101fc5780631b4418481461022e5780634a6238d41461029a5780635d4d3bf7146102c55780636e873d1f146103345780638f6f1c591461037957806391501949146103ef578063a781e7f81461042a578063a834d32e1461047b578063bb21baf8146104da578063e4f282ad14610537575b600080fd5b610116600480360360408110156100e057600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105a0565b6040518080602001828103825283818151815260200191508051906020019060200280838360005b8381101561015957808201518184015260208101905061013e565b505050509050019250505060405180910390f35b34801561017957600080fd5b506101fa600480360360a081101561019057600080fd5b81019080803590602001909291908035906020019092919080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506109f5565b005b34801561020857600080fd5b50610211610eeb565b604051808381526020018281526020019250505060405180910390f35b34801561023a57600080fd5b5061027d6004803603602081101561025157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610efc565b604051808381526020018281526020019250505060405180910390f35b3480156102a657600080fd5b506102af611044565b6040518082815260200191505060405180910390f35b3480156102d157600080fd5b50610332600480360360808110156102e857600080fd5b810190808035906020019092919080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061104e565b005b34801561034057600080fd5b506103776004803603604081101561035757600080fd5b8101908080359060200190929190803590602001909291905050506112a7565b005b34801561038557600080fd5b506103d26004803603604081101561039c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506114d9565b604051808381526020018281526020019250505060405180910390f35b3480156103fb57600080fd5b506104286004803603602081101561041257600080fd5b810190808035906020019092919050505061161b565b005b34801561043657600080fd5b506104796004803603602081101561044d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611795565b005b6104bd6004803603602081101561049157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611bbc565b604051808381526020018281526020019250505060405180910390f35b3480156104e657600080fd5b50610535600480360360408110156104fd57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803515159060200190929190505050611fc6565b005b34801561054357600080fd5b506105866004803603602081101561055a57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612191565b604051808215151515815260200191505060405180910390f35b606060001515600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16151514151561066a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600c8152602001807f496e20626c61636b4c697374000000000000000000000000000000000000000081525060200191505060405180910390fd5b6000600260008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000209050600081600401549050806106cb6001866121e790919063ffffffff16565b111515156106d857600080fd5b6000610709856106fb612710670de0b6b3a764000061223190919063ffffffff16565b61227b90919063ffffffff16565b905066071afd498d00008110156107345766071afd498d00003414151561072f57600080fd5b61076d565b662386f26fc1000081111561075d57662386f26fc100003414151561075857600080fd5b61076c565b803414151561076b57600080fd5b5b5b600061078360038761227b90919063ffffffff16565b905060008090506060826040519080825280602002602001820160405280156107bb5781602001602082028038833980820191505090505b50905060008090505b8383101561096157438760000160008881526020019081526020016000206003015410158061080b5750600087600001600088815260200190815260200160002060000154145b1561082357600086141561081e57610961565b610946565b86600001600087815260200190815260200160002060000154828480600101955081518110151561085057fe5b906020019060200201818152505086600001600087815260200190815260200160002060010154828480600101955081518110151561088b57fe5b90602001906020020181815250508660000160008781526020019081526020016000206002015482848060010195508151811015156108c657fe5b9060200190602002018181525050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156109455786600001600087815260200190815260200160002060040160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690505b5b61095a6001876121e790919063ffffffff16565b95506107c4565b6109b4600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166109af600a6109a16006543461227b90919063ffffffff16565b61223190919063ffffffff16565b612348565b6109e5816109e0600a6109d26005543461227b90919063ffffffff16565b61223190919063ffffffff16565b612348565b8197505050505050505092915050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638fe77e866040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260118152602001807f6e6573742e76332e6f666665724d61696e00000000000000000000000000000081525060200191505060206040518083038186803b158015610ab457600080fd5b505afa158015610ac8573d6000803e3d6000fd5b505050506040513d6020811015610ade57600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515610b91576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600c8152602001807f4e6f20617574686f72697479000000000000000000000000000000000000000081525060200191505060405180910390fd5b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020905060008160040154905081600001600082815260200190815260200160002060020154431415610d725760008260000160008381526020019081526020016000209050610c2d8882600001546123b790919063ffffffff16565b8160000181905550610c4c8782600101546123b790919063ffffffff16565b8160010181905550838160040160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508060030154861115610cad578581600301819055505b806002015443141515610cc4574381600201819055505b80836000016000848152602001908152602001600020600082015481600001556001820154816001015560028201548160020155600382015481600301556004820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff168160040160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555090505050610ee2565b610d8a600183600401546123b790919063ffffffff16565b82600401819055506000826000016000846004015481526020019081526020016000209050878160000181905550868160010181905550858160030181905550438160020181905550838160040160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508083600001600085600401548152602001908152602001600020600082015481600001556001820154816001015560028201548160020155600382015481600301556004820160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff168160040160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550905050826004015483600101600043815260200190815260200160002081905550505b50505050505050565b600080600554600654915091509091565b6000803273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515610fa2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260168152602001807f49742063616e2774206265206120636f6e74726163740000000000000000000081525060200191505060405180910390fd5b610faa6125d7565b600260008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206040805190810160405290816002820160408051908101604052908160008201548152602001600182015481525050815260200160048201548152505090508060000151600001518160000151602001519250925050915091565b6000600454905090565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638fe77e866040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260118152602001807f6e6573742e76332e6f666665724d61696e00000000000000000000000000000081525060200191505060206040518083038186803b15801561110d57600080fd5b505afa158015611121573d6000803e3d6000fd5b505050506040513d602081101561113757600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415156111ea576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600c8152602001807f4e6f20617574686f72697479000000000000000000000000000000000000000081525060200191505060405180910390fd5b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002090506000816001016000848152602001908152602001600020549050600082600001600083815260200190815260200160002090506112778782600001546121e790919063ffffffff16565b81600001819055506112968682600101546121e790919063ffffffff16565b816001018190555050505050505050565b600115156000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a3bf06f1336040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561136557600080fd5b505afa158015611379573d6000803e3d6000fd5b505050506040513d602081101561138f57600080fd5b81019080805190602001909291905050501515141515611417576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600c8152602001807f4e6f20617574686f72697479000000000000000000000000000000000000000081525060200191505060405180910390fd5b600a61142c82846123b790919063ffffffff16565b1415156114c7576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260238152602001807f57726f6e6720657870656e736520616c6c6f636174696f6e2070726f706f727481526020017f696f6e000000000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b81600581905550806006819055505050565b6000803273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561157f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260168152602001807f49742063616e2774206265206120636f6e74726163740000000000000000000081525060200191505060405180910390fd5b6000600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000209050600081600101600086815260200190815260200160002054905081600001600082815260200190815260200160002060000154826000016000838152602001908152602001600020600101549350935050509250929050565b600115156000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a3bf06f1336040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b1580156116d957600080fd5b505afa1580156116ed573d6000803e3d6000fd5b505050506040513d602081101561170357600080fd5b8101908080519060200190929190505050151514151561178b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600c8152602001807f4e6f20617574686f72697479000000000000000000000000000000000000000081525060200191505060405180910390fd5b8060048190555050565b600115156000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a3bf06f1336040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561185357600080fd5b505afa158015611867573d6000803e3d6000fd5b505050506040513d602081101561187d57600080fd5b81019080805190602001909291905050501515141515611905576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600c8152602001807f4e6f20617574686f72697479000000000000000000000000000000000000000081525060200191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638fe77e866040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825260118152602001807f6e6573742e76332e6f666665724d61696e00000000000000000000000000000081525060200191505060206040518083038186803b158015611a0457600080fd5b505afa158015611a18573d6000803e3d6000fd5b505050506040513d6020811015611a2e57600080fd5b8101908080519060200190929190505050600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638fe77e866040518163ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180806020018281038252600e8152602001807f6e6573742e76332e61626f6e757300000000000000000000000000000000000081525060200191505060206040518083038186803b158015611b3e57600080fd5b505afa158015611b52573d6000803e3d6000fd5b505050506040513d6020811015611b6857600080fd5b8101908080519060200190929190505050600760006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b60008060001515600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff161515141515611c87576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600c8152602001807f496e20626c61636b4c697374000000000000000000000000000000000000000081525060200191505060405180910390fd5b3273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614158015611d115750600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614155b15611d905760045434141515611d8f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260178152602001807f50726963652063616c6c20636861726765206572726f7200000000000000000081525060200191505060405180910390fd5b5b6000600260008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002090506000816004015490505b4382600001600083815260200190815260200160002060030154101580611e1c5750600082600001600083815260200190815260200160002060000154145b15611e4a576000811415611e2f57611e4a565b611e436001826121e790919063ffffffff16565b9050611ddd565b6000826000016000838152602001908152602001600020905080600001548360020160000181905550806001015483600201600101819055506000341115611f3557611edf600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16611eda600a611ecc6006543461227b90919063ffffffff16565b61223190919063ffffffff16565b612348565b611f348160040160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16611f2f600a611f216005543461227b90919063ffffffff16565b61223190919063ffffffff16565b612348565b5b7fddfa535cacea1d1e69a1a85fabd4691a3e0102bd5c80acd82f249a88d5d509888682600001548360010154604051808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001838152602001828152602001935050505060405180910390a18060000154816001015494509450505050915091565b600115156000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a3bf06f1336040518263ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561208457600080fd5b505afa158015612098573d6000803e3d6000fd5b505050506040513d60208110156120ae57600080fd5b81019080805190602001909291905050501515141515612136576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600c8152602001807f4e6f20617574686f72697479000000000000000000000000000000000000000081525060200191505060405180910390fd5b80600360008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055505050565b6000600360008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff169050919050565b600061222983836040805190810160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250612441565b905092915050565b600061227383836040805190810160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250612503565b905092915050565b60008083141561228e5760009050612342565b600082840290508284828115156122a157fe5b0414151561233d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260218152602001807f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f81526020017f770000000000000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b809150505b92915050565b60006123698373ffffffffffffffffffffffffffffffffffffffff166125cd565b90508073ffffffffffffffffffffffffffffffffffffffff166108fc839081150290604051600060405180830381858888f193505050501580156123b1573d6000803e3d6000fd5b50505050565b6000808284019050838110151515612437576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b600083831115829015156124f0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b838110156124b557808201518184015260208101905061249a565b50505050905090810190601f1680156124e25780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b6000808311829015156125b1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561257657808201518184015260208101905061255b565b50505050905090810190601f1680156125a35780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b50600083858115156125bf57fe5b049050809150509392505050565b6000819050919050565b6060604051908101604052806125eb6125f8565b8152602001600081525090565b60408051908101604052806000815260200160008152509056fea165627a7a72305820a3a965ad9342253f0d3b48be8e1c7f5b4a951fe1b8e41c8124b5ce84ceab11950029"; + + protected NestOfferPriceContract(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected NestOfferPriceContract(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public List getNowTokenPriceEvents(TransactionReceipt transactionReceipt) { + final Event event = new Event("NowTokenPrice", + Arrays.>asList(), + Arrays.>asList(new TypeReference

() {}, new TypeReference() {}, new TypeReference() {})); + List valueList = extractEventParametersWithLog(event, transactionReceipt); + ArrayList responses = new ArrayList(valueList.size()); + for (EventValuesWithLog eventValues : valueList) { + NowTokenPriceEventResponse typedResponse = new NowTokenPriceEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.a = (String) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.b = (BigInteger) eventValues.getNonIndexedValues().get(1).getValue(); + typedResponse.c = (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public Observable nowTokenPriceEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + final Event event = new Event("NowTokenPrice", + Arrays.>asList(), + Arrays.>asList(new TypeReference
() {}, new TypeReference() {}, new TypeReference() {})); + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(event)); + return web3j.ethLogObservable(filter).map(new Func1() { + @Override + public NowTokenPriceEventResponse call(Log log) { + EventValuesWithLog eventValues = extractEventParametersWithLog(event, log); + NowTokenPriceEventResponse typedResponse = new NowTokenPriceEventResponse(); + typedResponse.log = log; + typedResponse.a = (String) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.b = (BigInteger) eventValues.getNonIndexedValues().get(1).getValue(); + typedResponse.c = (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); + return typedResponse; + } + }); + } + + public RemoteCall updateAndCheckPriceList(String tokenAddress, BigInteger num, BigInteger weiValue) { + final Function function = new Function( + "updateAndCheckPriceList", + Arrays.asList(new Address(tokenAddress), + new Uint256(num)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function, weiValue); + } + + public RemoteCall addPrice(BigInteger ethAmount, BigInteger tokenAmount, BigInteger endBlock, String tokenAddress, String offerOwner) { + final Function function = new Function( + "addPrice", + Arrays.asList(new Uint256(ethAmount), + new Uint256(tokenAmount), + new Uint256(endBlock), + new Address(tokenAddress), + new Address(offerOwner)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall> checkPriceCostProportion() { + final Function function = new Function("checkPriceCostProportion", + Arrays.asList(), + Arrays.>asList(new TypeReference() {}, new TypeReference() {})); + return new RemoteCall>( + new Callable>() { + @Override + public Tuple2 call() throws Exception { + List results = executeCallMultipleValueReturn(function); + return new Tuple2( + (BigInteger) results.get(0).getValue(), + (BigInteger) results.get(1).getValue()); + } + }); + } + + public RemoteCall> checkPriceNow(String tokenAddress) { + final Function function = new Function("checkPriceNow", + Arrays.asList(new Address(tokenAddress)), + Arrays.>asList(new TypeReference() {}, new TypeReference() {})); + return new RemoteCall>( + new Callable>() { + @Override + public Tuple2 call() throws Exception { + List results = executeCallMultipleValueReturn(function); + return new Tuple2( + (BigInteger) results.get(0).getValue(), + (BigInteger) results.get(1).getValue()); + } + }); + } + + public RemoteCall checkPriceCost() { + final Function function = new Function("checkPriceCost", + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall changePrice(BigInteger ethAmount, BigInteger tokenAmount, String tokenAddress, BigInteger blockNum) { + final Function function = new Function( + "changePrice", + Arrays.asList(new Uint256(ethAmount), + new Uint256(tokenAmount), + new Address(tokenAddress), + new Uint256(blockNum)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall changePriceCostProportion(BigInteger user, BigInteger abonus) { + final Function function = new Function( + "changePriceCostProportion", + Arrays.asList(new Uint256(user), + new Uint256(abonus)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall> checkPriceForBlock(String tokenAddress, BigInteger blockNum) { + final Function function = new Function("checkPriceForBlock", + Arrays.asList(new Address(tokenAddress), + new Uint256(blockNum)), + Arrays.>asList(new TypeReference() {}, new TypeReference() {})); + return new RemoteCall>( + new Callable>() { + @Override + public Tuple2 call() throws Exception { + List results = executeCallMultipleValueReturn(function); + return new Tuple2( + (BigInteger) results.get(0).getValue(), + (BigInteger) results.get(1).getValue()); + } + }); + } + + public RemoteCall changePriceCost(BigInteger amount) { + final Function function = new Function( + "changePriceCost", + Arrays.asList(new Uint256(amount)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall changeMapping(String voteFactory) { + final Function function = new Function( + "changeMapping", + Arrays.asList(new Address(voteFactory)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall updateAndCheckPriceNow(String tokenAddress, BigInteger weiValue) { + final Function function = new Function( + "updateAndCheckPriceNow", + Arrays.asList(new Address(tokenAddress)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function, weiValue); + } + + public RemoteCall changeBlackList(String add, Boolean isBlack) { + final Function function = new Function( + "changeBlackList", + Arrays.asList(new Address(add), + new Bool(isBlack)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall checkBlackList(String add) { + final Function function = new Function("checkBlackList", + Arrays.asList(new Address(add)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, Boolean.class); + } + + public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, String voteFactory) { + String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new Address(voteFactory))); + return deployRemoteCall(NestOfferPriceContract.class, web3j, credentials, gasPrice, gasLimit, BINARY, encodedConstructor); + } + + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, String voteFactory) { + String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new Address(voteFactory))); + return deployRemoteCall(NestOfferPriceContract.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, encodedConstructor); + } + + public static NestOfferPriceContract load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return new NestOfferPriceContract(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + public static NestOfferPriceContract load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return new NestOfferPriceContract(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static class NowTokenPriceEventResponse { + public Log log; + + public String a; + + public BigInteger b; + + public BigInteger c; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/contract/VoteContract.java b/NestEatOffer/src/main/java/com/nest/ib/contract/VoteContract.java new file mode 100644 index 0000000..93e67de --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/contract/VoteContract.java @@ -0,0 +1,48 @@ +package com.nest.ib.contract; + +import org.web3j.abi.TypeReference; +import org.web3j.abi.datatypes.Address; +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.tx.Contract; +import org.web3j.tx.TransactionManager; + +import java.math.BigInteger; +import java.util.Arrays; + +/** + * @author wll + * @date 2020/7/25 19:26 + */ +public class VoteContract extends Contract { + private static final String BINARY = "0x60806040523480156200001157600080fd5b5060043610620002385760003560e01c8063690055011162000135578063b3f0433c11620000bd578063c7d550571162000087578063c7d5505714620006c1578063ddc5e6d414620006ea578063e74f8ed514620006f4578063f6a71bf41462000714578063f7e99aae14620007345762000238565b8063b3f0433c1462000645578063b6518bdb146200066e578063baa01af01462000697578063c179a34114620006b75762000238565b80638fe77e8611620000ff5780638fe77e8614620005375780639348cb4214620005e3578063a3bf06f114620005ed578063b12d96f714620006165762000238565b80636900550114620004c45780636990d93514620004e45780636c515bce14620004ee5780636d4f769614620005175762000238565b80633a037b8b11620001c557806357a0dc46116200018f57806357a0dc4614620004735780635ce1e2ff146200047d578063631fad3614620004a657806363cd610614620004b0578063674086f614620004ba5762000238565b80633a037b8b14620003695780633f782ad2146200038957806353424cbf146200039357806353b1e09714620003bc5762000238565b806309ddd882116200020757806309ddd88214620002de5780630fb4441114620003075780631c2700d4146200033657806327af0b53146200035f5762000238565b80630425f52f146200023d578063056a5d75146200025b57806307ceb41414620002a057806309c3454414620002bc575b600080fd5b6200024762000754565b604080519115158252519081900360200190f35b62000284600480360360208110156200027357600080fd5b50356001600160a01b03166200075d565b604080516001600160a01b039092168252519081900360200190f35b620002aa6200077e565b60408051918252519081900360200190f35b620002dc60048036036020811015620002d457600080fd5b503562000784565b005b620002dc60048036036020811015620002f657600080fd5b50356001600160a01b0316620007f9565b620002dc600480360360408110156200031f57600080fd5b506001600160a01b038135169060200135620009a4565b620002dc600480360360208110156200034e57600080fd5b50356001600160a01b031662000ba2565b620002dc62000cfc565b620002dc600480360360208110156200038157600080fd5b503562000df7565b620002aa62000e48565b620002dc60048036036020811015620003ab57600080fd5b50356001600160a01b031662000e4e565b620002dc60048036036040811015620003d457600080fd5b810190602081018135640100000000811115620003f057600080fd5b8201836020820111156200040357600080fd5b803590602001918460018302840111640100000000831117156200042657600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550505090356001600160a01b0316915062000ebb9050565b620002dc62000f8c565b62000247600480360360208110156200049557600080fd5b50356001600160a01b031662001162565b620002aa62001180565b620002aa62001186565b620002aa6200118c565b620002dc60048036036020811015620004dc57600080fd5b503562001192565b620002aa62001224565b620002aa600480360360208110156200050657600080fd5b50356001600160a01b03166200122a565b620002dc600480360360208110156200052f57600080fd5b503562001245565b62000284600480360360208110156200054f57600080fd5b8101906020810181356401000000008111156200056b57600080fd5b8201836020820111156200057e57600080fd5b80359060200191846001830284011164010000000083111715620005a157600080fd5b91908080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525092955062001296945050505050565b620002aa62001309565b62000247600480360360208110156200060557600080fd5b50356001600160a01b03166200130f565b620002dc600480360360408110156200062e57600080fd5b506001600160a01b0381351690602001356200132d565b62000247600480360360208110156200065d57600080fd5b50356001600160a01b031662001523565b620002dc600480360360208110156200068657600080fd5b50356001600160a01b03166200167a565b620002dc60048036036020811015620006af57600080fd5b5035620016ea565b620002aa6200177c565b620002dc60048036036020811015620006d957600080fd5b50356001600160a01b031662001782565b620002dc620017ef565b620002dc600480360360208110156200070c57600080fd5b50356200192a565b620002dc600480360360208110156200072c57600080fd5b5035620019f2565b620002dc600480360360208110156200074c57600080fd5b503562001a51565b600f5460ff1690565b6001600160a01b038082166000908152600c6020526040902054165b919050565b60065490565b6200078f336200130f565b620007d0576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b60008111620007de57600080fd5b620007f3816201518063ffffffff62001ae316565b60065550565b33321462000847576040805162461bcd60e51b8152602060048201526016602482015275125d0818d85b89dd08189948184818dbdb9d1c9858dd60521b604482015290519081900360640190fd5b6001600160a01b0381166000908152600e602052604090205460ff16620008b2576040805162461bcd60e51b815260206004820152601a602482015279125d09dcc81b9bdd0818481d9bdd1a5b99c818dbdb9d1c9858dd60321b604482015290519081900360640190fd5b6000819050806001600160a01b0316630425f52f6040518163ffffffff1660e01b815260040160206040518083038186803b158015620008f157600080fd5b505afa15801562000906573d6000803e3d6000fd5b505050506040513d60208110156200091d57600080fd5b5051600f5460ff161515901515146200093557600080fd5b6200094081620016c6565b806001600160a01b031663b47247566040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156200097c57600080fd5b505af115801562000991573d6000803e3d6000fd5b50505050620009a081620017ce565b5050565b333214620009f2576040805162461bcd60e51b8152602060048201526016602482015275125d0818d85b89dd08189948184818dbdb9d1c9858dd60521b604482015290519081900360640190fd5b6001600160a01b0382166000908152600e602052604090205460ff1662000a5d576040805162461bcd60e51b815260206004820152601a602482015279125d09dcc81b9bdd0818481d9bdd1a5b99c818dbdb9d1c9858dd60321b604482015290519081900360640190fd5b600854604080516323b872dd60e01b81523260048201526001600160a01b038086166024830152604482018590529151859392909216916323b872dd916064808201926020929091908290030181600087803b15801562000abd57600080fd5b505af115801562000ad2573d6000803e3d6000fd5b505050506040513d602081101562000ae957600080fd5b505162000b3d576040805162461bcd60e51b815260206004820152601d60248201527f417574686f72697a6174696f6e207472616e73666572206661696c6564000000604482015290519081900360640190fd5b806001600160a01b03166394bfed58836040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b15801562000b8457600080fd5b505af115801562000b99573d6000803e3d6000fd5b50505050505050565b33321462000bf0576040805162461bcd60e51b8152602060048201526016602482015275125d0818d85b89dd08189948184818dbdb9d1c9858dd60521b604482015290519081900360640190fd5b6001600160a01b0381166000908152600e602052604090205460ff1662000c5b576040805162461bcd60e51b815260206004820152601a602482015279125d09dcc81b9bdd0818481d9bdd1a5b99c818dbdb9d1c9858dd60321b604482015290519081900360640190fd5b62000c663362001523565b1562000c7157600080fd5b6000819050806001600160a01b03166374d414296040518163ffffffff1660e01b8152600401600060405180830381600087803b15801562000cb257600080fd5b505af115801562000cc7573d6000803e3d6000fd5b5050326000908152600c6020526040902080546001600160a01b0319166001600160a01b039590951694909417909355505050565b600f5460ff161562000d405760065460055462000d1f9163ffffffff62001b4a16565b421162000d2b57600080fd5b600f805460ff19169055600060055562000df5565b336000908152600d602052604090205462000d5a57600080fd5b600754600854604080516370a0823160e01b815230600482015290516001600160a01b03909216916370a0823191602480820192602092909190829003018186803b15801562000da957600080fd5b505afa15801562000dbe573d6000803e3d6000fd5b505050506040513d602081101562000dd557600080fd5b5051101562000de357600080fd5b600f805460ff19166001179055426005555b565b62000e02336200130f565b62000e43576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b600455565b60005490565b62000e59336200130f565b62000e9a576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b6001600160a01b03166000908152600e60205260409020805460ff19169055565b62000ec6336200130f565b62000f07576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b80600a836040518082805190602001908083835b6020831062000f3c5780518252601f19909201916020918201910162000f1b565b51815160209384036101000a6000190180199092169116179052920194855250604051938490030190922080546001600160a01b0319166001600160a01b03949094169390931790925550505050565b326000908152600d602052604090205462000fa657600080fd5b600854326000818152600d6020908152604080832054815163a9059cbb60e01b815260048101959095526024850152516001600160a01b039094169363a9059cbb93604480820194918390030190829087803b1580156200100657600080fd5b505af11580156200101b573d6000803e3d6000fd5b505050506040513d60208110156200103257600080fd5b50516200103e57600080fd5b326000908152600d6020908152604080832083905560095481516370a0823160e01b815230600482015291516001600160a01b03909116926370a082319260248082019391829003018186803b1580156200109857600080fd5b505afa158015620010ad573d6000803e3d6000fd5b505050506040513d6020811015620010c457600080fd5b5051600954600f546040805163a9059cbb60e01b81526001600160a01b036101009093048316600482015260248101859052905193945091169163a9059cbb916044808201926020929091908290030181600087803b1580156200112757600080fd5b505af11580156200113c573d6000803e3d6000fd5b505050506040513d60208110156200115357600080fd5b50516200115f57600080fd5b50565b6001600160a01b03166000908152600e602052604090205460ff1690565b60075490565b60055490565b60035490565b6200119d336200130f565b620011de576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b600081116200121f5760405162461bcd60e51b8152600401808060200182810382526024815260200180620038416024913960400191505060405180910390fd5b600255565b60025490565b6001600160a01b03166000908152600d602052604090205490565b62001250336200130f565b62001291576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b600355565b6000600a826040518082805190602001908083835b60208310620012cc5780518252601f199092019160209182019101620012ab565b51815160209384036101000a60001901801990921691161790529201948552506040519384900301909220546001600160a01b0316949350505050565b60045490565b6001600160a01b03166000908152600b602052604090205460ff1690565b3233146200137b576040805162461bcd60e51b8152602060048201526016602482015275125d0818d85b89dd08189948184818dbdb9d1c9858dd60521b604482015290519081900360640190fd5b6003548110156200138b57600080fd5b600f54604051600091849160ff909116908490620013a99062001ba5565b6001600160a01b03909316835290151560208301526040808301919091525190819003606001906000f080158015620013e6573d6000803e3d6000fd5b50600854604080516323b872dd60e01b81523260048201526001600160a01b0380851660248301526044820187905291519394509116916323b872dd916064808201926020929091908290030181600087803b1580156200144657600080fd5b505af11580156200145b573d6000803e3d6000fd5b505050506040513d60208110156200147257600080fd5b5051620014c6576040805162461bcd60e51b815260206004820152601d60248201527f417574686f72697a6174696f6e207472616e73666572206661696c6564000000604482015290519081900360640190fd5b6001600160a01b0381166000818152600e6020908152604091829020805460ff19166001179055815192835290517f1a0f921ce3c6f2f0f6be5b624a487bc1d5143e1fd1833154f39ab63e13d897559281900390910190a1505050565b6001600160a01b038181166000908152600c60205260408120549091166200154e5750600062000779565b6001600160a01b038083166000908152600c602090815260409182902054825163178f552d60e11b815292519316928392632f1eaa5a926004808301939192829003018186803b158015620015a257600080fd5b505afa158015620015b7573d6000803e3d6000fd5b505050506040513d6020811015620015ce57600080fd5b5051806200165e5750806001600160a01b031663723a3533846040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b1580156200162e57600080fd5b505afa15801562001643573d6000803e3d6000fd5b505050506040513d60208110156200165a57600080fd5b5051155b156200166f57600091505062000779565b600191505062000779565b62001685336200130f565b620016c6576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b6001600160a01b03166000908152600b60205260409020805460ff19166001179055565b620016f5336200130f565b62001736576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b60008111620017775760405162461bcd60e51b8152600401808060200182810382526024815260200180620038416024913960400191505060405180910390fd5b600155565b60015490565b6200178d336200130f565b620017ce576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b6001600160a01b03166000908152600b60205260409020805460ff19169055565b620017fa336200130f565b6200183b576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b62001866604051806040016040528060088152602001676e6573744e6f646560c01b81525062001296565b600880546001600160a01b0319166001600160a01b03929092169190911790556040805180820190915260138152723732b9ba173b19973232b9ba393ab1ba34b7b760691b6020820152620018bb9062001296565b600f60016101000a8154816001600160a01b0302191690836001600160a01b0316021790555062001908604051806040016040528060048152602001631b995cdd60e21b81525062001296565b600980546001600160a01b0319166001600160a01b0392909216919091179055565b600854604080516323b872dd60e01b81523260048201523060248201526044810184905290516001600160a01b03909216916323b872dd916064808201926020929091908290030181600087803b1580156200198557600080fd5b505af11580156200199a573d6000803e3d6000fd5b505050506040513d6020811015620019b157600080fd5b5051620019bd57600080fd5b326000908152600d6020526040902054620019df908263ffffffff62001b4a16565b326000908152600d602052604090205550565b620019fd336200130f565b62001a3e576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b6000811162001a4c57600080fd5b600755565b62001a5c336200130f565b62001a9d576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b6000811162001ade5760405162461bcd60e51b8152600401808060200182810382526024815260200180620038416024913960400191505060405180910390fd5b600055565b60008262001af45750600062001b44565b8282028284828162001b0257fe5b041462001b415760405162461bcd60e51b8152600401808060200182810382526021815260200180620038656021913960400191505060405180910390fd5b90505b92915050565b60008282018381101562001b41576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b611c8d8062001bb48339019056fe60806040526012805462ffffff191690553480156200001d57600080fd5b5060405162001c8d38038062001c8d833981810160405260608110156200004357600080fd5b508051602080830151604093840151600280546001600160a01b0319163390811790915585516347f3bf4360e11b815260048082018690526024820152631b995cdd60e21b6044820152955194959294919390928392638fe77e8692606480840193919291829003018186803b158015620000bd57600080fd5b505afa158015620000d2573d6000803e3d6000fd5b505050506040513d6020811015620000e957600080fd5b5051600480546001600160a01b0319166001600160a01b03928316178155604080516347f3bf4360e11b8152602092810183905260086024820152676e6573744e6f646560c01b6044820152905192841692638fe77e8692606480840193919291829003018186803b1580156200015f57600080fd5b505afa15801562000174573d6000803e3d6000fd5b505050506040513d60208110156200018b57600080fd5b5051600580546001600160a01b039283166001600160a01b03199182161790915560008054878416908316811790915560078054909216179055604080516347f3bf4360e11b8152602060048201819052601360248301527f6e6573742e76332e6465737472756374696f6e000000000000000000000000006044830152915192841692638fe77e8692606480840193919291829003018186803b1580156200023357600080fd5b505afa15801562000248573d6000803e3d6000fd5b505050506040513d60208110156200025f57600080fd5b5051600880546001600160a01b0319166001600160a01b03928316179055326000908152601460209081526040918290208590556011859055426009558151631fbc156960e11b815291516200031993851692633f782ad2926004808301939192829003018186803b158015620002d557600080fd5b505afa158015620002ea573d6000803e3d6000fd5b505050506040513d60208110156200030157600080fd5b505160095490620009ef602090811b62000d6f17901c565b600a81905550806001600160a01b031663c179a3416040518163ffffffff1660e01b815260040160206040518083038186803b1580156200035957600080fd5b505afa1580156200036e573d6000803e3d6000fd5b505050506040513d60208110156200038557600080fd5b5051600e55604080516349a465a160e11b815290516001600160a01b03831691639348cb42916004808301926020929190829003018186803b158015620003cb57600080fd5b505afa158015620003e0573d6000803e3d6000fd5b505050506040513d6020811015620003f757600080fd5b5051600f55601280548415801563010000000263ff00000019909216919091179091556200069b57604080516347f3bf4360e11b8152602060048201819052601360248301527f6e6573742e76332e746f6b656e41626f6e757300000000000000000000000000604483015291516001600160a01b03841692638fe77e869260648082019391829003018186803b1580156200049257600080fd5b505afa158015620004a7573d6000803e3d6000fd5b505050506040513d6020811015620004be57600080fd5b5051600380546001600160a01b0319166001600160a01b039283161790819055604080516325d4675b60e11b815290516200055f936002931691634ba8ceb6916004808301926020929190829003018186803b1580156200051e57600080fd5b505afa15801562000533573d6000803e3d6000fd5b505050506040513d60208110156200054a57600080fd5b50519062000a53602090811b62000ded17901c565b60108190556200056e57600080fd5b6200069260646200067e836001600160a01b0316636990d9356040518163ffffffff1660e01b815260040160206040518083038186803b158015620005b257600080fd5b505afa158015620005c7573d6000803e3d6000fd5b505050506040513d6020811015620005de57600080fd5b5051600354600480546010546040805163da3bba0560e01b81526001600160a01b039384169481019490945260248401919091525192169163da3bba0591604480820192602092909190829003018186803b1580156200063d57600080fd5b505afa15801562000652573d6000803e3d6000fd5b505050506040513d60208110156200066957600080fd5b50519062000a9d602090811b62000ec117901c565b62000afb60201b62000f1a1790919060201c565b600c55620009c9565b604080516347f3bf4360e11b815260206004820181905260126024830152716e6573742e76332e6d696e696e675361766560701b604483015291516001600160a01b03841692638fe77e869260648082019391829003018186803b1580156200070357600080fd5b505afa15801562000718573d6000803e3d6000fd5b505050506040513d60208110156200072f57600080fd5b5051600680546001600160a01b0319166001600160a01b03928316179055604080516347f3bf4360e11b815260206004820181905260116024830152706e6573742e76332e746f6b656e5361766560781b6044830152915192841692638fe77e8692606480840193919291829003018186803b158015620007af57600080fd5b505afa158015620007c4573d6000803e3d6000fd5b505050506040513d6020811015620007db57600080fd5b5051600180546001600160a01b0319166001600160a01b0392831617905560408051636990d93560e01b81529051620009c5926064926200067e9291861691636990d93591600480820192602092909190829003018186803b1580156200084157600080fd5b505afa15801562000856573d6000803e3d6000fd5b505050506040513d60208110156200086d57600080fd5b505160048054600854604080516370a0823160e01b81526001600160a01b039283169481019490945251620009b19391909216916370a0823191602480820192602092909190829003018186803b158015620008c857600080fd5b505afa158015620008dd573d6000803e3d6000fd5b505050506040513d6020811015620008f457600080fd5b505160048054600654604080516370a0823160e01b81526001600160a01b0392831694810194909452516200099d9391909216916370a0823191602480820192602092909190829003018186803b1580156200094f57600080fd5b505afa15801562000964573d6000803e3d6000fd5b505050506040513d60208110156200097b57600080fd5b50516b204fce5e3e250261100000009062000a53602090811b62000ded17901c565b62000a5360201b62000ded1790919060201c565b62000a9d60201b62000ec11790919060201c565b600c555b600f5460115410620009e5576012805461ff0019166101001790555b5050505062000c49565b60008282018381101562000a4a576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b90505b92915050565b600062000a4a83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525062000b4560201b60201c565b60008262000aae5750600062000a4d565b8282028284828162000abc57fe5b041462000a4a5760405162461bcd60e51b815260040180806020018281038252602181526020018062001c6c6021913960400191505060405180910390fd5b600062000a4a83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525062000be060201b60201c565b6000818484111562000bd85760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101562000b9c57818101518382015260200162000b82565b50505050905090810190601f16801562000bca5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b6000818362000c325760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831562000b9c57818101518382015260200162000b82565b50600083858162000c3f57fe5b0495945050505050565b6110138062000c596000396000f3fe608060405234801561001057600080fd5b50600436106101425760003560e01c80639348cb42116100b8578063b7091a191161007c578063b7091a1914610222578063b962364614610246578063c179a3411461024e578063d86ef1bc14610256578063f400ff5f1461025e578063fe317ef41461026657610142565b80639348cb42146101e557806394bfed58146101ed578063a03100211461020a578063aa70cc4414610212578063b47247561461021a57610142565b80632f1eaa5a1161010a5780632f1eaa5a1461019557806339e8cbd81461019d5780636bb9885c146101a5578063723a3533146101af57806374d41429146101d55780638a208c08146101dd57610142565b80630425f52f146101475780630a08a830146101635780631c3c7b791461017d578063268dae5b1461018557806328b560481461018d575b600080fd5b61014f61028c565b604080519115158252519081900360200190f35b61016b61029d565b60408051918252519081900360200190f35b61016b6102a3565b61014f6102a9565b61016b6102b8565b61014f6102be565b61016b6102e6565b6101ad6102ec565b005b61016b600480360360208110156101c557600080fd5b50356001600160a01b031661056b565b6101ad610586565b61016b61082d565b61016b610833565b6101ad6004803603602081101561020357600080fd5b5035610839565b61014f61095e565b61014f61096c565b6101ad610975565b61022a610bce565b604080516001600160a01b039092168252519081900360200190f35b61016b610bdd565b61016b610be3565b6101ad610be9565b61016b610d4e565b61016b6004803603602081101561027c57600080fd5b50356001600160a01b0316610d54565b6012546301000000900460ff165b90565b60105490565b600b5490565b60125462010000900460ff1690565b600a5490565b60125460009060ff16806102d35750600a5442115b156102e05750600161029a565b50600090565b60115490565b601254610100900460ff161561036d576012546301000000900460ff161580610318575060125460ff16155b1561036857600a544211610368576040805162461bcd60e51b8152602060048201526012602482015271566f746520756e656e666f72636561626c6560701b604482015290519081900360640190fd5b61038d565b600e546009546103829163ffffffff610d6f16565b421161038d57600080fd5b326000908152601460205260409020546103a657600080fd5b60055432600081815260146020908152604080832054815163a9059cbb60e01b815260048101959095526024850152516001600160a01b039094169363a9059cbb93604480820194918390030190829087803b15801561040557600080fd5b505af1158015610419573d6000803e3d6000fd5b505050506040513d602081101561042f57600080fd5b505161043a57600080fd5b3260009081526014602090815260408083208390556004805482516370a0823160e01b8152309281019290925291516001600160a01b03909216926370a0823192602480840193829003018186803b15801561049557600080fd5b505afa1580156104a9573d6000803e3d6000fd5b505050506040513d60208110156104bf57600080fd5b5051600d549091506104d7908263ffffffff610d6f16565b600d55600480546008546040805163a9059cbb60e01b81526001600160a01b0392831694810194909452602484018590525191169163a9059cbb9160448083019260209291908290030181600087803b15801561053357600080fd5b505af1158015610547573d6000803e3d6000fd5b505050506040513d602081101561055d57600080fd5b505161056857600080fd5b50565b6001600160a01b031660009081526013602052604090205490565b6002546001600160a01b031633146105d4576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b600a54421115610622576040805162461bcd60e51b8152602060048201526014602482015273159bdd1a5b99c81d1a5b5948195e18d95959195960621b604482015290519081900360640190fd5b60125460ff161561066a576040805162461bcd60e51b815260206004820152600d60248201526c566f746520696e20666f72636560981b604482015290519081900360640190fd5b601254610100900460ff1661067e57600080fd5b32600090815260136020526040902054156106cd576040805162461bcd60e51b815260206004820152600a60248201526912185d99481d9bdd195960b21b604482015290519081900360640190fd5b6012546000906301000000900460ff16156107775760035460048054601054604080516336569b5d60e21b81526001600160a01b039384169481019490945260248401919091523260448401525192169163d95a6d7491606480820192602092909190829003018186803b15801561074457600080fd5b505afa158015610758573d6000803e3d6000fd5b505050506040513d602081101561076e57600080fd5b505190506107fd565b60015460048054604080516335c14f4560e11b815232938101939093526001600160a01b03918216602484015251921691636b829e8a91604480820192602092909190829003018186803b1580156107ce57600080fd5b505afa1580156107e2573d6000803e3d6000fd5b505050506040513d60208110156107f857600080fd5b505190505b326000908152601360205260409020819055600b54610822908263ffffffff610d6f16565b600b55610568610dd2565b60095490565b600f5490565b6002546001600160a01b03163314610887576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b600e5460095461089c9163ffffffff610d6f16565b4211156108e7576040805162461bcd60e51b8152602060048201526014602482015273159bdd1a5b99c81d1a5b5948195e18d95959195960621b604482015290519081900360640190fd5b601254610100900460ff16156108fc57600080fd5b3260009081526014602052604090205461091c908263ffffffff610d6f16565b3260009081526014602052604090205560115461093f908263ffffffff610d6f16565b6011819055600f5411610568576012805461ff00191661010017905550565b601254610100900460ff1690565b60125460ff1690565b6002546001600160a01b031633146109c3576040805162461bcd60e51b815260206004820152600c60248201526b4e6f20617574686f7269747960a01b604482015290519081900360640190fd5b60125462010000900460ff16156109d957600080fd5b6012805462ff000019166201000017908190556301000000900460ff1615610a4c5760125460ff16610a47576040805162461bcd60e51b8152602060048201526012602482015271566f746520756e656e666f72636561626c6560701b604482015290519081900360640190fd5b610aa5565b60125460ff168015610a5f5750600a5442115b610aa5576040805162461bcd60e51b8152602060048201526012602482015271566f746520756e656e666f72636561626c6560701b604482015290519081900360640190fd5b600254600080546040805163b6518bdb60e01b81526001600160a01b0392831660048201529051919093169263b6518bdb92602480830193919282900301818387803b158015610af457600080fd5b505af1158015610b08573d6000803e3d6000fd5b50506000805460408051634d536fe360e01b815290516001600160a01b039092169450634d536fe39350600480820193929182900301818387803b158015610b4f57600080fd5b505af1158015610b63573d6000803e3d6000fd5b5050600254600080546040805163c7d5505760e01b81526001600160a01b039283166004820152905191909316945063c7d55057935060248084019382900301818387803b158015610bb457600080fd5b505af1158015610bc8573d6000803e3d6000fd5b50505050565b6007546001600160a01b031690565b600c5490565b600e5490565b333214610c36576040805162461bcd60e51b8152602060048201526016602482015275125d0818d85b89dd08189948184818dbdb9d1c9858dd60521b604482015290519081900360640190fd5b600a54421115610c84576040805162461bcd60e51b8152602060048201526014602482015273159bdd1a5b99c81d1a5b5948195e18d95959195960621b604482015290519081900360640190fd5b60125460ff1615610ccc576040805162461bcd60e51b815260206004820152600d60248201526c566f746520696e20666f72636560981b604482015290519081900360640190fd5b32600090815260136020526040902054610d17576040805162461bcd60e51b81526020600482015260076024820152664e6f20766f746560c81b604482015290519081900360640190fd5b32600090815260136020526040902054600b54610d399163ffffffff610ded16565b600b5532600090815260136020526040812055565b600d5490565b6001600160a01b031660009081526014602052604090205490565b600082820183811015610dc9576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b90505b92915050565b600c54600b5410610deb576012805460ff191660011790555b565b6000610dc983836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525060008184841115610eb95760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610e7e578181015183820152602001610e66565b50505050905090810190601f168015610eab5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b600082610ed057506000610dcc565b82820282848281610edd57fe5b0414610dc95760405162461bcd60e51b8152600401808060200182810382526021815260200180610fbd6021913960400191505060405180910390fd5b6000610dc983836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525060008183610fa65760405162461bcd60e51b8152602060048201818152835160248401528351909283926044909101919085019080838360008315610e7e578181015183820152602001610e66565b506000838581610fb257fe5b049594505050505056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a264697066735822122010ca6fc463ec15227c88f90eb2c6f4334c7cfcc42d601d8af8e8a5f990d3dea464736f6c63430006000033536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77506172616d65746572206e6565647320746f2062652067726561746572207468616e2030536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a2646970667358221220e245d2fac7fb05efe6914180891050801ac814d143bf1b6854d3455aed0b190e64736f6c63430006000033"; + + protected VoteContract(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected VoteContract(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public RemoteCall checkAddress(String name) { + final Function function = new Function("checkAddress", + Arrays.asList(new org.web3j.abi.datatypes.Utf8String(name)), + Arrays.>asList(new TypeReference
() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + + + + public static VoteContract load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return new VoteContract(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + public static VoteContract load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return new VoteContract(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/controller/AuthController.java b/NestEatOffer/src/main/java/com/nest/ib/controller/AuthController.java new file mode 100644 index 0000000..98b2332 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/controller/AuthController.java @@ -0,0 +1,49 @@ +package com.nest.ib.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import java.util.HashMap; +import java.util.Map; + +/** + * @author wll + * @date 2020/7/24 12:52 + */ +@Controller +@RequestMapping("/auth") +public class AuthController { + + @Value("${nest.user.name}") + private String userName; + + @Value("${nest.user.password}") + private String passwd; + + @RequestMapping(value = "/login") + public String login() { + return "login"; + } + + @RequestMapping(value = "/verify") + public String verify(@RequestParam String userName, String passwd, HttpServletRequest request, ModelMap mmp) { + if (userName.equalsIgnoreCase(this.userName) && passwd.equalsIgnoreCase(this.passwd)) { + HttpSession session = request.getSession(); + Map user = new HashMap<>(); + user.put("userName", userName); + user.put("passwd", passwd); + session.setAttribute("user", user); + session.setMaxInactiveInterval(3600); + + return "redirect:/eat/eatData"; + } + return "login"; + } + +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/controller/EatController.java b/NestEatOffer/src/main/java/com/nest/ib/controller/EatController.java new file mode 100644 index 0000000..a38e701 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/controller/EatController.java @@ -0,0 +1,194 @@ +package com.nest.ib.controller; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.nest.ib.service.EatOfferAndTransactionService; +import com.nest.ib.service.serviceImpl.EatOfferAndTransactionServiceImpl; +import com.nest.ib.utils.EthClient; +import com.nest.ib.utils.HttpClientUtil; +import com.nest.ib.utils.api.ApiClient; +import com.nest.ib.utils.api.JsonUtil; +import com.nest.ib.utils.response.Accounts; +import com.nest.ib.utils.response.AccountsResponse; +import com.nest.ib.utils.response.BalanceResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.ModelAndView; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; + +/** + * @author wll + * @date 2020/7/26 14:52 + */ +@RequestMapping("eat") +@RestController +public class EatController { + + @Autowired + EthClient ethClient; + + @Autowired + EatOfferAndTransactionService eatOfferAndTransactionService; + + /** + * Set the node + */ + @PostMapping("/updateNode") + public String updateNode(@RequestParam(name = "node") String node) { + ethClient.initNode(node); + + // If the key is already filled in, the node is reset, and a new registration is required + ethClient.resetBean(); + return node; + } + + /** + * Set token addresses and transaction pairs + */ + @PostMapping("/updateErc20") + public String updateErc20(@RequestParam(name = "erc20Addr") String erc20Addr, @RequestParam(name = "symbols") String symbols) { + EatOfferAndTransactionServiceImpl.ERC20_TOKEN_ADDRESS = erc20Addr; + EatOfferAndTransactionServiceImpl.SYMBOLS = symbols.toLowerCase(); + + // If the key has been filled in, the address and transaction pairs that have been reset need to be re-registered + ethClient.resetBean(); + return "ok"; + } + + /** + * Set the order ratio + */ + @PostMapping("/updateEatRate") + public BigDecimal updateEatRate(@RequestParam(name = "eatRate") BigDecimal eatRate) { + EatOfferAndTransactionServiceImpl.EAT_PRICE_OFFERSET = eatRate; + return eatRate; + } + + /** + * On/off eating menu. True on,false off + */ + @PostMapping("/startEat") + public boolean startEat() { + EatOfferAndTransactionServiceImpl.START_EAT = !EatOfferAndTransactionServiceImpl.START_EAT; + return EatOfferAndTransactionServiceImpl.START_EAT; + } + + /** + * Close/open the Huocoin Exchange (to buy and sell the assets acquired after the order) + */ + @PostMapping("/updateHuobiExchangeState") + public boolean updateHuobiExchangeState() { + return eatOfferAndTransactionService.updateHuobiExchange(); + } + + /** + * Sets whether user authentication is enabled + */ + @PostMapping("/updateAuthorizedUser") + public void updateAuthorizedUser() { + eatOfferAndTransactionService.updateAuthorizedUser(); + } + + /** + * Set the API-Key and API-Secret of huocoin exchange + * + * @return + */ + @PostMapping("/updateExchangeApiKey") + public List updateExchangeApiKey(@RequestParam(name = "apiKey") String apiKey, @RequestParam(name = "apiSecret") String apiSecret) { + ApiClient client = new ApiClient(apiKey, apiSecret); + AccountsResponse accounts = client.accounts(); + List listAccounts = (List) accounts.getData(); + if (!listAccounts.isEmpty()) { + //------------------------------------------------------ The account balance ------------------------------------------------------- + BalanceResponse balance = client.balance(String.valueOf(listAccounts.get(0).getId())); + String s = ""; + try { + s = JsonUtil.writeValue(balance); + } catch (IOException e) { + e.printStackTrace(); + } + + JSONObject jsonObject = JSONObject.parseObject(s); + String data = jsonObject.getString("data"); + JSONObject jsonObject1 = JSONObject.parseObject(data); + JSONArray list = jsonObject1.getJSONArray("list"); + List balanceList = new ArrayList<>(); + + list.forEach(li -> { + JSONObject jsonObject2 = JSONObject.parseObject(String.valueOf(li)); + String balanceStr = jsonObject2.getString("balance"); + String currency = jsonObject2.getString("currency"); + + // Find the balance of HT,ETH,USDT + if (currency.equalsIgnoreCase(EatOfferAndTransactionServiceImpl.SYMBOL) + || currency.equalsIgnoreCase("ETH")) { + HashMap hashMap = new HashMap(); + hashMap.put("balance", balanceStr); + hashMap.put("currency", currency); + balanceList.add(hashMap); + } + }); + + String result = eatOfferAndTransactionService.updateExchangeApiKey(apiKey, apiSecret); + if (result.equalsIgnoreCase("SUCCESS")) { + return balanceList; + } + } + return null; + } + + /** + * Set the account private key + */ + @PostMapping("/updatePrivateKey") + public String updateUserPrivatekey(@RequestParam(name = "privateKey") String privateKey) { + ethClient.updateUserPrivateKey(privateKey); + return ethClient.credentials.getAddress(); + } + + /** + * Set the network agent address and port + * @param proxyIp + * @param proxyPort + * @return + */ + @PostMapping("/updateProxy") + public String updateProxy(@RequestParam(name = "proxyIp") String proxyIp, @RequestParam(name = "proxyPort") int proxyPort) { + HttpClientUtil.updateProxy(proxyIp, proxyPort); + return "ok"; + } + + /** + * Configuration page + * + * @return + */ + @GetMapping("/eatData") + public ModelAndView miningData() { + String address = ethClient.getAddress(); + boolean b = EatOfferAndTransactionServiceImpl.START_EAT; + Map data = eatOfferAndTransactionService.eatOfferData(); + + ModelAndView mav = new ModelAndView("eatData"); + mav.addObject("address", address); + mav.addObject("startEat", b == true ? "Eat the arbitrage state: open" : "Eat the arbitrage state: close"); + mav.addObject("apiKey", data.get("apiKey")); + mav.addObject("apiSecret", data.get("apiSecret")); + mav.addObject("authorizedUser", data.get("authorizedUser").equalsIgnoreCase("true") ? "Exchange certification:open" : "Exchange certification:close"); + mav.addObject("huobiExchangeState", data.get("huobiExchangeState").equalsIgnoreCase("true") ? "Exchange state:Open business" : "Exchange state:Close business"); + // Convert to percentage + BigDecimal eatRate = EatOfferAndTransactionServiceImpl.EAT_PRICE_OFFERSET.multiply(BigDecimal.valueOf(100L)); + mav.addObject("eatRate", eatRate + "%"); + mav.addObject("node", EthClient.NODE); + mav.addObject("erc20Addr", EatOfferAndTransactionServiceImpl.ERC20_TOKEN_ADDRESS); + mav.addObject("symbols", EatOfferAndTransactionServiceImpl.SYMBOLS); + mav.addObject("proxyIp", HttpClientUtil.getProxyIp()); + mav.addObject("proxyPort", HttpClientUtil.getProxyPort()); + + return mav; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/interceptor/PermissionInterceptor.java b/NestEatOffer/src/main/java/com/nest/ib/interceptor/PermissionInterceptor.java new file mode 100644 index 0000000..a2c551e --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/interceptor/PermissionInterceptor.java @@ -0,0 +1,53 @@ +package com.nest.ib.interceptor; + +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +/** + * HTTP request interception + */ +@Component +public class PermissionInterceptor extends HandlerInterceptorAdapter { + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); + response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE"); + response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With,Access-Control-Allow-Headers, Content-Type, Accept, Connection, User-Agent, Cookie, Authorization"); + + // OPTIONS requests direct release + if (request.getMethod().toUpperCase().equals("OPTIONS")) { + return true; + } + + String uri = request.getRequestURI(); + // A URL with some extension + if (uri.indexOf(".") > -1) { + String extension = uri.substring(uri.lastIndexOf(".") + 1); + return "css".equalsIgnoreCase(extension) || "js".equalsIgnoreCase(extension) + || "jpg".equalsIgnoreCase(extension) || "gif".equalsIgnoreCase(extension) + || "png".equalsIgnoreCase(extension) || "mp4".equalsIgnoreCase(extension) + || "swf".equalsIgnoreCase(extension) || "html".equalsIgnoreCase(extension) + || "htm".equalsIgnoreCase(extension) || "doc".equalsIgnoreCase(extension) + || "xls".equalsIgnoreCase(extension); + } + + // The URI for direct release + if ("/auth/login".equalsIgnoreCase(uri)||"/auth/verify".equalsIgnoreCase(uri)) { + return true; + } + + HttpSession session = request.getSession(); + Object user = session.getAttribute("user"); + // Get the user, easy to authenticate + if (user == null) { + request.getRequestDispatcher("/auth/login").forward(request, response); + return false; + } + return true; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/model/EatOfferDeal.java b/NestEatOffer/src/main/java/com/nest/ib/model/EatOfferDeal.java new file mode 100644 index 0000000..04cdc3b --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/model/EatOfferDeal.java @@ -0,0 +1,124 @@ +package com.nest.ib.model; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +/** + * @author wll + * @date 2020/8/3 11:29 + * Exchange trading + */ +public class EatOfferDeal implements Serializable { + + private static final long serialVersionUID = 20200820L; + + /** + * Erc20 name + */ + private String erc20TokenName; + + /** + * Quotation miner address + */ + private String owner; + + /** + * Offer price hash + */ + private String offerHash; + + /** + * Recharge the transaction hash + */ + private String dealHash; + + /** + * Transaction order ID + */ + private long orderId; + + /** + * 0 No task; + * 1. Task; + * 2. Completed recharge to the corresponding wallet of the exchange; + * 3. Completed sending orders of trading pairs + */ + private int transactionStatus; + + /** + * Name of token to be sold + */ + private String sellTokenName; + + /** + * Quantity sold + */ + private BigDecimal sellTokenAmount; + + + public String getErc20TokenName() { + return erc20TokenName; + } + + public String getSellTokenName() { + return sellTokenName; + } + + public void setSellTokenName(String sellTokenName) { + this.sellTokenName = sellTokenName; + } + + public void setErc20TokenName(String erc20TokenName) { + this.erc20TokenName = erc20TokenName; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public String getOfferHash() { + return offerHash; + } + + public void setOfferHash(String offerHash) { + this.offerHash = offerHash; + } + + public BigDecimal getSellTokenAmount() { + return sellTokenAmount; + } + + public void setSellTokenAmount(BigDecimal sellTokenAmount) { + this.sellTokenAmount = sellTokenAmount; + } + + public String getDealHash() { + return dealHash; + } + + public void setDealHash(String dealHash) { + this.dealHash = dealHash; + } + + public long getOrderId() { + return orderId; + } + + public void setOrderId(long orderId) { + this.orderId = orderId; + } + + public int getTransactionStatus() { + return transactionStatus; + } + + public void setTransactionStatus(int transactionStatus) { + this.transactionStatus = transactionStatus; + } + +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/model/OfferContractData.java b/NestEatOffer/src/main/java/com/nest/ib/model/OfferContractData.java new file mode 100644 index 0000000..620e50c --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/model/OfferContractData.java @@ -0,0 +1,146 @@ +package com.nest.ib.model; + +import java.io.Serializable; + +/** + * @author wll + * @date 2020/7/17 12:13 + * Quotation contract data + */ +public class OfferContractData implements Serializable { + + private static final long serialVersionUID = 5920753423098691391L; + + /** + * Quotation contract + */ + private String uuid; + + /** + * Quotation owner + */ + private String owner; + + /** + * The ERC20 contract address of the target quote Token + */ + private String tokenAddress; + + /** + * Eth asset book in quotation sheet + */ + private String ethAmount; + + /** + * Token assets in the quotation book + */ + private String tokenAmount; + + /** + * Number of eth remaining tradable + */ + private String dealEthAmount; + + /** + * The number of tradable tokens remaining + */ + private String dealTokenAmount; + + /** + * The block number of the quotation + */ + private String blockNum; + + /** + * Charges for mining + */ + private String serviceCharge; + + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public String getTokenAddress() { + return tokenAddress; + } + + public void setTokenAddress(String tokenAddress) { + this.tokenAddress = tokenAddress; + } + + public String getEthAmount() { + return ethAmount; + } + + public void setEthAmount(String ethAmount) { + this.ethAmount = ethAmount; + } + + public String getTokenAmount() { + return tokenAmount; + } + + public void setTokenAmount(String tokenAmount) { + this.tokenAmount = tokenAmount; + } + + public String getDealEthAmount() { + return dealEthAmount; + } + + public void setDealEthAmount(String dealEthAmount) { + this.dealEthAmount = dealEthAmount; + } + + public String getDealTokenAmount() { + return dealTokenAmount; + } + + public void setDealTokenAmount(String dealTokenAmount) { + this.dealTokenAmount = dealTokenAmount; + } + + public String getBlockNum() { + return blockNum; + } + + public void setBlockNum(String blockNum) { + this.blockNum = blockNum; + } + + public String getServiceCharge() { + return serviceCharge; + } + + public void setServiceCharge(String serviceCharge) { + this.serviceCharge = serviceCharge; + } + + @Override + public String toString() { + return "OfferContractData{" + + "uuid='" + uuid + '\'' + + ", owner='" + owner + '\'' + + ", tokenAddress='" + tokenAddress + '\'' + + ", ethAmount='" + ethAmount + '\'' + + ", tokenAmount='" + tokenAmount + '\'' + + ", dealEthAmount='" + dealEthAmount + '\'' + + ", dealTokenAmount='" + dealTokenAmount + '\'' + + ", blockNum='" + blockNum + '\'' + + ", serviceCharge='" + serviceCharge + '\'' + + '}'; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/model/OfferThreeData.java b/NestEatOffer/src/main/java/com/nest/ib/model/OfferThreeData.java new file mode 100644 index 0000000..98a9e2c --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/model/OfferThreeData.java @@ -0,0 +1,108 @@ +package com.nest.ib.model; + + +import java.io.Serializable; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Date; + +/** + * Quotation contract + */ +public class OfferThreeData implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * Address of Quotation Contract + */ + private String contractAddress; + + /** + * Quote ERC20 token name + */ + private String erc20TokenName; + + /** + * Quote ERC20 token address + */ + private String erc20TokenAddress; + + /** + * Quotation miner address + */ + private String owner; + + /** + * Block Number + */ + private BigInteger blockNumber; + + /** + * Verify the block interval at time T0 + */ + private Integer intervalBlock; + + /** + * Quotation handling fee + */ + private BigDecimal serviceCharge; + + + public String getContractAddress() { + return contractAddress; + } + + public void setContractAddress(String contractAddress) { + this.contractAddress = contractAddress; + } + + public String getErc20TokenName() { + return erc20TokenName; + } + + public void setErc20TokenName(String erc20TokenName) { + this.erc20TokenName = erc20TokenName; + } + + public String getErc20TokenAddress() { + return erc20TokenAddress; + } + + + public void setErc20TokenAddress(String erc20TokenAddress) { + this.erc20TokenAddress = erc20TokenAddress; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public BigInteger getBlockNumber() { + return blockNumber; + } + + public void setBlockNumber(BigInteger blockNumber) { + this.blockNumber = blockNumber; + } + + public Integer getIntervalBlock() { + return intervalBlock; + } + + public void setIntervalBlock(Integer intervalBlock) { + this.intervalBlock = intervalBlock; + } + + public BigDecimal getServiceCharge() { + return serviceCharge; + } + + public void setServiceCharge(BigDecimal serviceCharge) { + this.serviceCharge = serviceCharge; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/service/EatOfferAndTransactionService.java b/NestEatOffer/src/main/java/com/nest/ib/service/EatOfferAndTransactionService.java new file mode 100644 index 0000000..cb30aee --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/service/EatOfferAndTransactionService.java @@ -0,0 +1,93 @@ +package com.nest.ib.service; +import java.math.BigInteger; +import java.util.Map; + + +/** + * ClassName:EatOfferAndTransactionService + * Description: + */ +public interface EatOfferAndTransactionService { + + /** + * Eat a single offer + */ + void eatOffer(); + + /** + * Retrieve the assets + */ + void retrieveAssets(); + + /** + * Set block intervals + * @param blockLimit + */ + void setBlockLimit(BigInteger blockLimit); + + /** + * Gets the validation period block interval + * @return + */ + BigInteger getBlockLimit(); + + /** + * Set the TOKNE decimal number + * @param decimal + */ + void setErc20Decimal(BigInteger decimal); + + /** + * Set the fire coin API + * @param url + */ + void setHuoBiApi(String url); + + /** + * Set token symbol + * @param symbol + */ + void setTokenSymbol(String symbol); + + /** + * Get token symbol + * @return + */ + String getTokenSymbol(); + + /** + * Modify the trading status of Huocoin exchange + * @return + */ + boolean updateHuobiExchange(); + + /** + * Sets whether the exchange has user authentication on + */ + void updateAuthorizedUser(); + + /** + * Change the exchange API-Key and API-Secret + * @param apiKey + * @param apiSecret + * @return + */ + String updateExchangeApiKey(String apiKey, String apiSecret); + + /** + * The data that the user interface needs to display + * @return + */ + Map eatOfferData(); + + /** + * Assets quoted on a sheet are traded on an exchange + */ + void exchangeBuyAndSell(); + + /** + * Mention currency operation + * @param + */ + void getToken(String tokenName); +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/service/OfferThreeDataService.java b/NestEatOffer/src/main/java/com/nest/ib/service/OfferThreeDataService.java new file mode 100644 index 0000000..c343b68 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/service/OfferThreeDataService.java @@ -0,0 +1,16 @@ +package com.nest.ib.service; + + +import com.nest.ib.model.OfferContractData; +import com.nest.ib.model.OfferThreeData; + +import java.util.List; + +public interface OfferThreeDataService { + + /** + * Obtain contract order information for verification + * @return + */ + List listOfferData(); +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/service/serviceImpl/EatOfferAndTransactionServiceImpl.java b/NestEatOffer/src/main/java/com/nest/ib/service/serviceImpl/EatOfferAndTransactionServiceImpl.java new file mode 100644 index 0000000..df755d5 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/service/serviceImpl/EatOfferAndTransactionServiceImpl.java @@ -0,0 +1,1248 @@ +package com.nest.ib.service.serviceImpl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.nest.ib.constant.Constant; +import com.nest.ib.contract.NestOfferPriceContract; +import com.nest.ib.model.EatOfferDeal; +import com.nest.ib.model.OfferContractData; +import com.nest.ib.model.OfferThreeData; +import com.nest.ib.service.EatOfferAndTransactionService; +import com.nest.ib.service.OfferThreeDataService; +import com.nest.ib.utils.EthClient; +import com.nest.ib.utils.HttpClientUtil; +import com.nest.ib.utils.MathUtils; +import com.nest.ib.utils.api.ApiClient; +import com.nest.ib.utils.api.JsonUtil; +import com.nest.ib.utils.request.CreateOrderRequest; +import com.nest.ib.utils.response.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; +import org.web3j.abi.FunctionEncoder; +import org.web3j.abi.TypeReference; +import org.web3j.abi.datatypes.Address; +import org.web3j.abi.datatypes.Function; +import org.web3j.abi.datatypes.Type; +import org.web3j.abi.datatypes.generated.Uint256; +import org.web3j.crypto.RawTransaction; +import org.web3j.protocol.core.methods.response.EthSendTransaction; +import org.web3j.protocol.core.methods.response.TransactionReceipt; +import org.web3j.tuples.generated.Tuple2; + + +import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.*; + +/** + * ClassName:EatOfferAndTransactionServiceImpl + * Description: + */ +@Service +public class EatOfferAndTransactionServiceImpl implements EatOfferAndTransactionService { + private static final Logger LOG = LoggerFactory.getLogger(EatOfferAndTransactionServiceImpl.class); + + // Validation period block interval + private static volatile BigInteger BLOCK_LIMIT; + + // ERC20 precision + private static volatile BigInteger DECIMAL = null; + + // Huocoin EXCHANGE API + private static volatile String HUOBI_API = null; + + // ERC20 symbol + public static volatile String SYMBOL = null; + + // Whether to enable verification eating order + public static volatile boolean START_EAT = false; + + // Whether to start trading on huocoin exchange + private volatile boolean START_HUOBI_EXCHANGE = false; + + // Whether the exchange has authenticated users + private volatile String AUTHORIZED_USER = "true"; + + private volatile String API_KEY = ""; + private volatile String API_SECRET = ""; + + /** + * To initiate a purchase order, the quotation price should be more than 2% off the exchange price + */ + public static volatile BigDecimal EAT_PRICE_OFFERSET = new BigDecimal("0.02"); + + // ERC20 address + public static volatile String ERC20_TOKEN_ADDRESS; + + // Huocoin exchange trades pairs + public static volatile String SYMBOLS; + + // All of the data saved is used for trading on the exchange + private static List OFFER_DEAL_LIST = Collections.synchronizedList(new ArrayList()); + + @Autowired + private EthClient ethClient; + @Autowired + private OfferThreeDataService offerThreeDataService; + + + /** + * Quotation for single + */ + @Override + public void eatOffer() { + if (!START_EAT) { + LOG.info("Order verification is not enabled"); + return; + } + + // Obtain contract order information for verification + List offerThreeDatas = offerThreeDataService.listOfferData(); + if (CollectionUtils.isEmpty(offerThreeDatas)) { + LOG.info("There are currently no quotes pending validation"); + return; + } + + BigInteger gasPrice = null; + try { + gasPrice = ethClient.ethGasPrice().multiply(Constant.EAT_OFFER_GAS_PRICE_MULTIPLE).divide(BigInteger.TEN); + } catch (IOException e) { + LOG.info("Eat order to obtain gasPrice anomaly: {}", e.getMessage()); + e.printStackTrace(); + } + + try { + // Traverse these contracts to find those whose prices exceed the specified offset percentage + for (OfferThreeData offerThreeData : offerThreeDatas) { + // Access to contract information + String contractAddress = offerThreeData.getContractAddress(); + OfferContractData contractData = ethClient.getPrice(contractAddress); + if (contractData == null) { + LOG.error("No information related to this contract was found:", contractAddress); + continue; + } + + // Get the exchange price + BigDecimal exchangePrice = getExchangePrice(); + if (exchangePrice == null || exchangePrice.compareTo(BigDecimal.ZERO) == 0) { + LOG.error("Huocoin exchange price failed to obtain"); + continue; + } + LOG.info("Exchange price:{}", exchangePrice); + + // Number of ETH remaining tradable + BigInteger dealEthAmount = new BigInteger(contractData.getDealEthAmount()); + // The number of ERC20 remaining available + BigInteger dealErc20Amount = new BigInteger(contractData.getDealTokenAmount()); + // Judge whether the offer contract meets the requirements of the order: surplus, profitable + boolean canEat = canEat(contractAddress, dealEthAmount, dealErc20Amount, exchangePrice, offerThreeData); + if (!canEat) continue; + + // Get the balance + BigInteger ethBalance = ethClient.ethGetBalance(); + BigInteger erc20Balance = ethClient.ethBalanceOfErc20(); + LOG.info("Current account balance:ETH={},{}={}", ethBalance, SYMBOL, erc20Balance); + if (ethBalance == null || erc20Balance == null) { + return; + } + + // The price of being eaten + BigDecimal eatPrice = calPrice(dealErc20Amount, dealEthAmount); + // Get eat haploid multiple + BigInteger multiple = getOfferMultiple(exchangePrice, eatPrice); + if (multiple == null) continue; + + // Determine the type of food eaten + boolean eatEth = false; + // The exchange price is higher than the order price: PAY ERC20, eat ETH + if (exchangePrice.compareTo(eatPrice) > 0) { + eatEth = true; + } else { // The exchange price is less than the order price: pay EHT, eat ERC20 + eatEth = false; + } + + // Decide if you can eat them all + boolean canEatAll = canEatAll(multiple, exchangePrice, eatEth, dealEthAmount, dealErc20Amount, ethBalance, erc20Balance); + BigInteger copies = null; + // You can eat them all + if (canEatAll) { + copies = dealEthAmount.divide(Constant.ONE_ETH_AMOUNT); + } else {// You can't eat them all + // Serving number: 10ETH per serving + copies = getCopies(eatEth, exchangePrice, ethBalance, erc20Balance, eatPrice, multiple); + if (copies.compareTo(BigInteger.ZERO) <= 0) { + LOG.info("The balance is not enough to take the order"); + return; + } + } + + String hash = sendEatOffer(exchangePrice, eatPrice, multiple, eatEth, copies, contractAddress, gasPrice); + Thread.sleep(1000 * 2); + } + } catch (Exception e) { + LOG.error("Eating order abnormal:{}", e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Send an order to trade + * + * @param exchangePrice Exchange price + * @param eatPrice Eat a single price + * @param multiple A multiple + * @param eatEth Whether to eat the ETH + * @param copies Eat a single number + * @param contractAddress A bill of lading contract + * @param gasPrice + */ + private String sendEatOffer(BigDecimal exchangePrice, BigDecimal eatPrice, BigInteger multiple, + boolean eatEth, BigInteger copies, String contractAddress, BigInteger gasPrice) { + // Trade: the ETH + BigInteger tranEthAmout = copies.multiply(Constant.ONE_ETH_AMOUNT); + // Trade: ERC20 + BigInteger tranErc20Amount = MathUtils.toBigInt(MathUtils.decMulInt(eatPrice, copies.multiply(BigInteger.TEN)).multiply(MathUtils.toDecimal(DECIMAL))); + // Quote: the ETH + BigInteger offerEthAmount = tranEthAmout.multiply(multiple); + // Quote: erc20 + BigInteger eth = MathUtils.toBigInt(MathUtils.toDecimal(offerEthAmount).divide(Constant.UNIT_ETH, 0, BigDecimal.ROUND_DOWN)); + BigInteger offerErc20Amount = MathUtils.toBigInt(MathUtils.decMulInt(exchangePrice, eth).multiply(MathUtils.toDecimal(DECIMAL))); + // The service fee + BigInteger serviceCharge = Constant.SERVICE_CHARGE.multiply(copies); + // ETH charges: quotation, menu, service charge + BigInteger payEthAmount = null; + + String msg = null; + String method = null; + EatOfferDeal offerDeal = new EatOfferDeal(); + // Eat the ETH + if (eatEth) { + msg = "EatEth menu (enter {} to get ETH) ,Hash : {}"; + method = "sendErcBuyEth"; + payEthAmount = offerEthAmount.add(serviceCharge).subtract(tranEthAmout); + + offerDeal.setSellTokenName("eth"); + offerDeal.setSellTokenAmount(MathUtils.toDecimal(tranEthAmout)); + } else { // eat the ERC20 + msg = "EatErc eating order (enter ETH to get {}) Hash : {}"; + method = "sendEthBuyErc"; + payEthAmount = offerEthAmount.add(serviceCharge).add(tranEthAmout); + + offerDeal.setSellTokenName(SYMBOL.toLowerCase()); + offerDeal.setSellTokenAmount(MathUtils.toDecimal(tranErc20Amount)); + } + + List typeList = Arrays.asList( + new Uint256(offerEthAmount), + new Uint256(offerErc20Amount), + new Address(contractAddress), + new Uint256(tranEthAmout), + new Uint256(tranErc20Amount), + new Address(ERC20_TOKEN_ADDRESS) + ); + + LOG.info("Eating list quotes: trading ETH={} trading {}={} quotes ETH={} quotes {}={} payEthAmount={}", + tranEthAmout, SYMBOL, tranErc20Amount, offerEthAmount, SYMBOL, offerErc20Amount, payEthAmount); + + // Initiate an order offer transaction + String transactionHash = ethClient.sendEatOffer(typeList, payEthAmount, method, gasPrice); + + // Keep order buying and selling, then trade on an exchange + if (!StringUtils.isEmpty(transactionHash)) { + offerDeal.setOfferHash(transactionHash); + offerDeal.setErc20TokenName(SYMBOL); + offerDeal.setOwner(ethClient.credentials.getAddress()); + offerDeal.setTransactionStatus(1); + + OFFER_DEAL_LIST.add(offerDeal); + } + + LOG.info(msg, SYMBOL, transactionHash); + return transactionHash; + } + + + /** + * Fetch quotation contract assets (over 25 blocks) + */ + @Override + public void retrieveAssets() { + List offerContractAddresses = getOfferContractAddress(); + if (CollectionUtils.isEmpty(offerContractAddresses)) { + LOG.info("There is no quotation contract that needs to be retrieved at present"); + return; + } + + LOG.info("Unretrieved assets:====" + offerContractAddresses.size()); + BigInteger gasPrice = null; + try { + gasPrice = ethClient.ethGasPrice(); + } catch (IOException e) { + LOG.error("There is an exception to the gasPrice obtained during fetch:" + e); + } + gasPrice = gasPrice.multiply(Constant.TURNOUT_GAS_PRICE_MULTIPLE).divide(BigInteger.TEN); + + BigInteger nonce = null; + try { + nonce = ethClient.ethGetTransactionCount(); + } catch (IOException e) { + LOG.error("An exception occurs when you get a nonce on a fetch:" + e); + } + + for (OfferContractData contractData : offerContractAddresses) { + List typeList = Arrays.asList(new Address(contractData.getUuid())); + String transaction = null; + try { + transaction = ethClient.turnOut(nonce, typeList, gasPrice); + } catch (Exception e) { + LOG.error("An exception has occurred to fetch the quote", e.getMessage()); + } + nonce = nonce.add(BigInteger.ONE); + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + LOG.info("hash: " + transaction); + } + } + + + /** + * The assets quoted by the purchase order are traded on the exchange : + * 0 no task; + * 1. There is a task; + * 2. The recharge has been completed and sent to the corresponding wallet of the exchange; + */ + @Override + public void exchangeBuyAndSell() { + + // Check to see if the exchange is open + if (!START_HUOBI_EXCHANGE) { + return; + } + + // Check to see if the exchange's API-Key and API-Secret are set + if (API_KEY.equalsIgnoreCase("") || API_SECRET.equalsIgnoreCase("")) { + LOG.info("If the assets need to be exchanged in the exchange after receiving the quotation, please set the EXCHANGE'S API-Key and open the charging permission"); + return; + } + + // Initiate a withdrawal operation when there are no pending or pending transactions + if (CollectionUtils.isEmpty(OFFER_DEAL_LIST)) { + LOG.info("There are no pending or pending transactions"); + // The withdrawal operation is initiated at this point + getToken("eth"); + getToken(EatOfferAndTransactionServiceImpl.SYMBOL.toLowerCase()); + return; + } + + // Go through the order data and buy and sell + for (EatOfferDeal offerDeal : OFFER_DEAL_LIST) { + int transactionStatus = offerDeal.getTransactionStatus(); + switch (transactionStatus) { + // Have a task, recharge + case 1: + LOG.info("Received recharge to the task of the exchange"); + recharge(offerDeal); + break; + // Recharge has been completed, order is initiated + case 2: + LOG.info("Into the buying and selling"); + if (makeOrder(offerDeal)) return; + break; + } + } + } + + // Mention currency operation + @Override + public void getToken(String BUY_TOKEN_NAME_EXCHANGE) { + // Query the coin chain information + QueryExtractServiceChargeResponse queryExtractServiceChargeResponse = apiReferenceCurrencies(BUY_TOKEN_NAME_EXCHANGE, AUTHORIZED_USER); + // Enquire currency withdrawal fee + String serviceCharge = queryExtractServiceCharge(BUY_TOKEN_NAME_EXCHANGE, queryExtractServiceChargeResponse); + // Chain name, default Ethereum + String chain = BUY_TOKEN_NAME_EXCHANGE.equalsIgnoreCase("usdt") ? "usdterc20" : ""; + ApiClient client = new ApiClient(API_KEY, API_SECRET); + // Query the TOKEN balance to be extracted from the account + HashMap exchangeBalance = getExchangeBalance(); + if (CollectionUtils.isEmpty(exchangeBalance)) { + LOG.info("All the assets of the exchange are empty, so the assets may not have been accounted for"); + return; + } + + String balance = exchangeBalance.get(BUY_TOKEN_NAME_EXCHANGE); + if (StringUtils.isEmpty(balance)) { + LOG.info("{}:The balance is empty", BUY_TOKEN_NAME_EXCHANGE); + return; + } + + if (new BigDecimal(balance).compareTo(new BigDecimal("1")) <= 0) { + LOG.info("There is no amount to withdraw"); + return; + } + + // Amount of currency withdrawal :(order quantity - handling fee) + BigDecimal getAmount = new BigDecimal(balance).subtract(new BigDecimal(serviceCharge)); + String amount = String.valueOf(getAmount); + LOG.info("The amount of money =" + amount); + // Send withdrawal request + ExtractERC20Response extractERC20Response = client.extractERC20( + ethClient.credentials.getAddress(), + amount, + BUY_TOKEN_NAME_EXCHANGE, + serviceCharge, + chain); + long data = extractERC20Response.getData(); + if (data == 0) { + LOG.info("The withdrawal is not successful. Please confirm whether the withdrawal address is set"); + return; + } + LOG.info("Withdrawal transaction no: " + data); + } + + /** + * Get the quote contract address that needs to be retrieved through the Find interface + * + * @return + */ + private List getOfferContractAddress() { + // All quotation data queried + List contractList = new ArrayList<>(); + try { + contractList = ethClient.find(Constant.FIRST_FIND_COUNT, Address.DEFAULT.getValue()); + } catch (Exception e) { + LOG.error("The Find interface failed to get the quote contract:{}", e.getMessage()); + e.printStackTrace(); + } + + if (CollectionUtils.isEmpty(contractList)) { + return Collections.EMPTY_LIST; + } + + BigInteger nowBlockNumber = null; + try { + nowBlockNumber = ethClient.ethBlockNumber(); + } catch (IOException e) { + e.printStackTrace(); + } + + // Unretrieved contract + List list = new ArrayList<>(); + int index = contractList.size() - 1; + for (int i = index; i >= 0; i--) { + + OfferContractData contractData = contractList.get(i); + + BigInteger tokenAmount = new BigInteger(contractData.getTokenAmount()); + BigInteger serviceCharge = new BigInteger(contractData.getServiceCharge()); + BigInteger ethAmount = new BigInteger(contractData.getEthAmount()); + BigInteger blockNumber = new BigInteger(contractData.getBlockNum()); + + // Fetch is not available until after the validation period + if (nowBlockNumber.subtract(blockNumber).compareTo(BLOCK_LIMIT) < 0) { + continue; + } + + // If the balance or service fee is greater than 0, the assets have not been retrieved + if (tokenAmount.compareTo(BigInteger.ZERO) > 0 + || serviceCharge.compareTo(BigInteger.ZERO) > 0 + || ethAmount.compareTo(BigInteger.ZERO) > 0) { + list.add(contractData); + } + } + + return list; + } + + + // Query order + private OrdersDetailResponse ordersDetail(String orderId) { + ApiClient client = new ApiClient(API_KEY, API_SECRET); + OrdersDetailResponse ordersDetail = client.ordersDetail(orderId); + return ordersDetail; + } + + // Enquire currency withdrawal fee + private String queryExtractServiceCharge(String currency, QueryExtractServiceChargeResponse queryExtractServiceChargeResponse) { + if (currency == null) return null; + List chains = queryExtractServiceChargeResponse.getData().get(0).getChains(); + if (currency.equalsIgnoreCase("usdt")) { + for (QueryExtractServiceChargeChains chain : chains) { + String chain1 = chain.getChain(); + if (chain1.equalsIgnoreCase("usdterc20")) { + String withdrawFeeType = chain.getWithdrawFeeType(); + if (withdrawFeeType.equalsIgnoreCase("fixed")) { + return chain.getTransactFeeWithdraw(); + } + + if (withdrawFeeType.equalsIgnoreCase("circulated")) { + return chain.getMinTransactFeeWithdraw(); + } + + if (withdrawFeeType.equalsIgnoreCase("ratio")) { + return chain.getTransactFeeRateWithdraw(); + } + } + } + } else { + QueryExtractServiceChargeChains queryExtractServiceChargeChains = chains.get(0); + String withdrawFeeType = queryExtractServiceChargeChains.getWithdrawFeeType(); + if (withdrawFeeType.equalsIgnoreCase("fixed")) { + return queryExtractServiceChargeChains.getTransactFeeWithdraw(); + } + + if (withdrawFeeType.equalsIgnoreCase("circulated")) { + return queryExtractServiceChargeChains.getMinTransactFeeWithdraw(); + } + + if (withdrawFeeType.equalsIgnoreCase("ratio")) { + return queryExtractServiceChargeChains.getTransactFeeRateWithdraw(); + } + } + return null; + } + + // Initiate buy and sell order + private boolean makeOrder(EatOfferDeal offerDeal) { + BigDecimal UNIT_TOKEN; + String sellTokenName = offerDeal.getSellTokenName(); + if (sellTokenName.equalsIgnoreCase("eth")) { + UNIT_TOKEN = Constant.UNIT_ETH; + } else { + UNIT_TOKEN = MathUtils.toDecimal(DECIMAL); + } + + // Gets all tokens that are assets of the exchange + HashMap exchangeBalance = getExchangeBalance(); + if (CollectionUtils.isEmpty(exchangeBalance)) { + LOG.info("All the assets of the exchange are empty, so the assets may not have been accounted for"); + return true; + } + + // The balance of assets to be sold + String exchangeToken = exchangeBalance.get(sellTokenName); + BigDecimal tokenBalance = new BigDecimal(exchangeToken).multiply(UNIT_TOKEN); + // Whether the exchange assets are sufficient + if (tokenBalance.compareTo(offerDeal.getSellTokenAmount()) >= 0) { + // The order number + long orderId = -1L; + // Initiate buy and sell order + if (sellTokenName.equalsIgnoreCase("eth")) { + orderId = exchangeOperation(BigDecimal.ZERO, SYMBOL, offerDeal.getSellTokenAmount()); + } else { + orderId = exchangeOperation(offerDeal.getSellTokenAmount(), "eth", BigDecimal.ZERO); + } + + LOG.info("Buy and Sell order ID:" + orderId); + if (orderId != -1L) { + // The order has been completed. Delete the task from the collection + OFFER_DEAL_LIST.remove(offerDeal); + } else { + LOG.info("Initiate order fail"); + } + } + return false; + } + + // A prepaid phone + private void recharge(EatOfferDeal offerDeal) { + + // Check to see if the purchase is complete + TransactionReceipt transactionReceipt = null; + try { + transactionReceipt = ethClient.ethGetTransactionReceipt(offerDeal.getOfferHash()); + } catch (IOException e) { + LOG.error("There is an error querying the transaction hash:{}", e.getMessage()); + return; + } + + String status = transactionReceipt.getStatus(); + if (status.equalsIgnoreCase("0x1")) { + + // Carry out recharge to huocoin exchange + String transactionHash = eatOfferRecharge(offerDeal.getSellTokenName(), MathUtils.toBigInt(offerDeal.getSellTokenAmount())); + + if (transactionHash != null) { + LOG.info("It has been recharged to the exchange to trade hash:" + transactionHash); + // Recharge completed modified status + offerDeal.setTransactionStatus(2); + offerDeal.setDealHash(transactionHash); + } + } else if (status.equalsIgnoreCase("0x0")) { // If the transaction fails, the task is deleted + OFFER_DEAL_LIST.remove(offerDeal); + } + } + + /** + * This node is used to query the static reference information (public data) of each currency and its block chain. + */ + public QueryExtractServiceChargeResponse apiReferenceCurrencies(String currency, String authorizedUser) { + ApiClient client = new ApiClient(API_KEY, API_SECRET); + String s = client.queryExtractServiceCharge(currency, authorizedUser); + JSONObject jsonObject = JSONObject.parseObject(s); + int code = jsonObject.getIntValue("code"); + String message = jsonObject.getString("message"); + if (code != 200) { + LOG.error("Query each currency static reference information exception:{};{}", code, message); + return null; + } + + JSONArray data = jsonObject.getJSONArray("data"); + List list = new ArrayList<>(); + + data.forEach(da -> { + JSONObject jsonObject1 = JSONObject.parseObject(String.valueOf(da)); + String currency1 = jsonObject1.getString("currency"); + String instStatus = jsonObject1.getString("instStatus"); + JSONArray chains = jsonObject1.getJSONArray("chains"); + List chainsList = new ArrayList<>(); + chains.forEach(tx -> { + JSONObject jsonObject2 = JSONObject.parseObject(String.valueOf(tx)); + + QueryExtractServiceChargeChains queryExtractServiceChargeChains = new QueryExtractServiceChargeChains(); + queryExtractServiceChargeChains.setChain(jsonObject2.getString("chain")); + queryExtractServiceChargeChains.setDepositStatus(jsonObject2.getString("depositStatus")); + queryExtractServiceChargeChains.setMaxTransactFeeWithdraw(jsonObject2.getString("maxTransactFeeWithdraw")); + queryExtractServiceChargeChains.setMaxWithdrawAmt(jsonObject2.getString("maxWithdrawAmt")); + queryExtractServiceChargeChains.setMinDepositAmt(jsonObject2.getString("minDepositAmt")); + queryExtractServiceChargeChains.setMinTransactFeeWithdraw(jsonObject2.getString("minTransactFeeWithdraw")); + queryExtractServiceChargeChains.setMinWithdrawAmt(jsonObject2.getString("minWithdrawAmt")); + queryExtractServiceChargeChains.setNumOfConfirmations(jsonObject2.getString("numOfConfirmations")); + queryExtractServiceChargeChains.setNumOfFastConfirmations(jsonObject2.getString("numOfFastConfirmations")); + queryExtractServiceChargeChains.setWithdrawFeeType(jsonObject2.getString("withdrawFeeType")); + queryExtractServiceChargeChains.setWithdrawPrecision(jsonObject2.getString("withdrawPrecision")); + queryExtractServiceChargeChains.setWithdrawQuotaPerDay(jsonObject2.getString("withdrawQuotaPerDay")); + queryExtractServiceChargeChains.setWithdrawQuotaPerYear(jsonObject2.getString("withdrawQuotaPerYear")); + queryExtractServiceChargeChains.setWithdrawQuotaTotal(jsonObject2.getString("withdrawQuotaTotal")); + queryExtractServiceChargeChains.setWithdrawStatus(jsonObject2.getString("withdrawStatus")); + queryExtractServiceChargeChains.setTransactFeeWithdraw(jsonObject2.getString("transactFeeWithdraw")); + queryExtractServiceChargeChains.setTransactFeeRateWithdraw(jsonObject2.getString("transactFeeRateWithdraw")); + queryExtractServiceChargeChains.setInstStatus("instStatus"); + chainsList.add(queryExtractServiceChargeChains); + }); + + QueryExtractServiceChargeData queryExtractServiceChargeData = new QueryExtractServiceChargeData(); + queryExtractServiceChargeData.setChains(chainsList); + queryExtractServiceChargeData.setCurrency(currency1); + queryExtractServiceChargeData.setInstStatus(instStatus); + list.add(queryExtractServiceChargeData); + }); + + QueryExtractServiceChargeResponse queryExtractServiceChargeResponse = new QueryExtractServiceChargeResponse(); + queryExtractServiceChargeResponse.setCode(code); + queryExtractServiceChargeResponse.setData(list); + return queryExtractServiceChargeResponse; + } + + + /** + * Set the validation period block interval + * + * @param blockLimit + */ + @Override + public void setBlockLimit(BigInteger blockLimit) { + BLOCK_LIMIT = blockLimit; + } + + /** + * Gets the validation period block interval + * + * @return + */ + @Override + public BigInteger getBlockLimit() { + return BLOCK_LIMIT; + } + + /** + * Set the TOKNE decimal number + * + * @param decimal + */ + @Override + public void setErc20Decimal(BigInteger decimal) { + DECIMAL = decimal; + } + + /** + * Set the fire coin API + * + * @param url + */ + @Override + public void setHuoBiApi(String url) { + HUOBI_API = url; + } + + /** + * Modify the trading status of Huocoin exchange + */ + @Override + public boolean updateHuobiExchange() { + if (START_HUOBI_EXCHANGE) { + START_HUOBI_EXCHANGE = false; + } else { + START_HUOBI_EXCHANGE = true; + } + return START_HUOBI_EXCHANGE; + } + + /** + * Sets whether the exchange has user authentication on + */ + @Override + public void updateAuthorizedUser() { + if (AUTHORIZED_USER.equalsIgnoreCase("true")) { + AUTHORIZED_USER = "false"; + } else { + AUTHORIZED_USER = "true"; + } + } + + /** + * Change the exchange API-Key and API-Secret + */ + @Override + public String updateExchangeApiKey(String apiKey, String apiSecret) { + API_KEY = apiKey; + API_SECRET = apiSecret; + return "SUCCESS"; + } + + /** + * The data that the user interface needs to display + */ + @Override + public Map eatOfferData() { + Map jsonObject = new HashMap<>(); + + if (API_KEY.equalsIgnoreCase("")) { + jsonObject.put("apiKey", "Please fill out the API - KEY"); + } else { + jsonObject.put("apiKey", "existing"); + } + + if (API_SECRET.equalsIgnoreCase("")) { + jsonObject.put("apiSecret", "Please fill out the API - SECRET"); + } else { + jsonObject.put("apiSecret", "existing"); + } + + jsonObject.put("huobiExchangeState", START_HUOBI_EXCHANGE + ""); + jsonObject.put("authorizedUser", AUTHORIZED_USER); + return jsonObject; + } + + + /** + * Set token symbol + * + * @param symbol + */ + @Override + public void setTokenSymbol(String symbol) { + SYMBOL = symbol; + } + + /** + * Get token symbol + * + * @return + */ + @Override + public String getTokenSymbol() { + return SYMBOL; + } + + + /** + * Get single servings: 10ETH for one serving + * + * @param eatEth Whether to eat the ETH + * @param exchangePrice Exchange price + * @param ethBalance Balance of ETH + * @param erc20Balance ERC20 balance + * @param eatPrice Eat a single price + * @param multiple Eat a single multiple + */ + private BigInteger getCopies(boolean eatEth, BigDecimal exchangePrice, BigInteger ethBalance, BigInteger erc20Balance, BigDecimal eatPrice, BigInteger multiple) { + // Quoted ETH quantity + BigInteger offerEth = multiple.multiply(Constant.ONE_ETH_AMOUNT); + // Take a portion, ETH needed + BigInteger eatOneEth = null; + + BigInteger ethCount = multiple.multiply(BigInteger.TEN);// Number of ETH + BigInteger offerErc20 = MathUtils.toBigInt(MathUtils.decMulInt(exchangePrice, ethCount)).multiply(DECIMAL); // Offer + BigInteger eatErc20 = MathUtils.toBigInt(MathUtils.decMulInt(eatPrice, ethCount)).multiply(DECIMAL); // Eat + // Take a portion, ERC20 needed + BigInteger eatOneErc20 = null; + + // Eat the ETH + if (eatEth) { + eatOneEth = offerEth.subtract(Constant.ONE_ETH_AMOUNT); + eatOneErc20 = offerErc20.add(eatErc20); + } else { // Eat the ERC20 + eatOneEth = offerEth.add(Constant.ONE_ETH_AMOUNT); + eatOneErc20 = offerErc20.subtract(eatErc20); + } + + // ETH balance can eat a single portion + BigInteger balance = ethBalance.subtract(Constant.PACKAGING_COSTS).subtract(Constant.SERVICE_CHARGE); + BigInteger copiesEth = MathUtils.toBigInt(MathUtils.intDivInt(balance, eatOneEth, 0)); + // The balance of ERC20 can be eaten as a single serving + BigInteger copiesErc20 = MathUtils.toBigInt(MathUtils.intDivInt(erc20Balance, eatOneErc20, 0)); + + if (copiesErc20.compareTo(copiesEth) < 0) { + return copiesErc20; + } + return copiesEth; + } + + /** + * Check the balance of the order :0 insufficient balance; 1. Don't eat all; 2 You can eat them all + * + * @param multiple A multiple + * @param exchangePrice Exchange price + * @param eatEth Whether to eat the ETH + * @param dealEthAmount ETH transaction amount + * @param dealErc20Amount ERC20 transaction amount + * @param ethBalance Balance of ETH + * @param erc20Balance ERC20 balance + */ + private boolean canEatAll(BigInteger multiple, BigDecimal exchangePrice, boolean eatEth, + BigInteger dealEthAmount, BigInteger dealErc20Amount, + BigInteger ethBalance, BigInteger erc20Balance) { + // Eat all quoted ETH quantity + BigInteger ethAmount = multiple.multiply(dealEthAmount); + // Eat all quoted ERC20 quantity + BigInteger eth = MathUtils.toBigInt(MathUtils.toDecimal(ethAmount).divide(Constant.UNIT_ETH, 0, BigDecimal.ROUND_DOWN)); + BigInteger erc20Amount = MathUtils.toBigInt(MathUtils.decMulInt(exchangePrice, eth)).multiply(DECIMAL); + // Eat all the minimum number of ETH required + BigInteger minEthAmount = null; + // Eat the minimum amount of ERC20 required + BigInteger minErc20Amount = null; + // Eat the ETH + if (eatEth) { + // Eat all the minimum NUMBER of ETH: quote number + eating order handling fee + miners packing fee - eating order to get the ETH + minEthAmount = ethAmount.add(Constant.SERVICE_CHARGE).add(Constant.PACKAGING_COSTS).subtract(dealEthAmount); + // Eat all minimum REQUIRED ERC20 quantity: quote ERC20+ eat order required ERC20 + minErc20Amount = erc20Amount.add(dealErc20Amount); + } else {// Eat ERC20 + // Eat all the minimum NUMBER of ETH: quoted number + eating order handling fee + miners packing fee + eating order required number of ETH + minEthAmount = ethAmount.add(Constant.SERVICE_CHARGE).add(Constant.PACKAGING_COSTS).add(dealEthAmount); + // Eat all minimum ERC20 quantity required: ETH* exchange price - the amount of ERC20 obtained by eating order + minErc20Amount = erc20Amount.subtract(dealErc20Amount); + } + + // You can't eat them all + if (ethBalance.compareTo(minEthAmount) < 0 || erc20Balance.compareTo(minErc20Amount) < 0) { + return false; + } + // Can eat all + return true; + } + + + /** + * The price is calculated by the amount of ERC20 and ETH + * + * @return + */ + private BigDecimal calPrice(BigInteger erc20Amount, BigInteger ethAmount) { + BigDecimal erc20Max = MathUtils.intDivDec(erc20Amount, MathUtils.toDecimal(DECIMAL), 18); + BigDecimal ethMax = MathUtils.intDivDec(ethAmount, Constant.UNIT_ETH, 18); + BigDecimal price = erc20Max.divide(ethMax, 18, BigDecimal.ROUND_DOWN); + return price; + } + + + /** + * Get the exchange price + */ + private BigDecimal getExchangePrice() { + if (HUOBI_API == null) { + LOG.error("The Huobi API failed to initialize, and ERC20's Symbol failed to obtain"); + return null; + } + + String s = HttpClientUtil.sendHttpGet(HUOBI_API); + if (s == null) { + return null; + } + + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray data = jsonObject.getJSONArray("data"); + if (data == null) { + return null; + } + + BigDecimal totalPrice = new BigDecimal("0"); + BigDecimal n = new BigDecimal("0"); + if (data.size() == 0) { + return null; + } + + for (int i = 0; i < data.size(); i++) { + Object o = data.get(i); + JSONObject jsonObject1 = JSONObject.parseObject(String.valueOf(o)); + JSONArray data1 = jsonObject1.getJSONArray("data"); + + if (data1 == null) { + continue; + } + + if (data1.size() == 0) { + continue; + } + + JSONObject jsonObject2 = JSONObject.parseObject(String.valueOf(data1.get(0))); + BigDecimal price = jsonObject2.getBigDecimal("price"); + if (price == null) { + continue; + } + + totalPrice = totalPrice.add(price); + n = n.add(new BigDecimal("1")); + } + + if (n.compareTo(new BigDecimal("0")) > 0) { + totalPrice = totalPrice.divide(n, 18, BigDecimal.ROUND_DOWN); + // Depending on the transaction pair, it needs to be processed differently, or converted to ethXXX if it ends in the ETH + if (SYMBOLS.endsWith("eth")) { + totalPrice = BigDecimal.ONE.divide(totalPrice, 18, BigDecimal.ROUND_DOWN); + } + return totalPrice; + } + return null; + } + + + /** + * Get quote multiple + * + * @param exchangePrice Exchange price + * @param eatPrice Be eaten at a single price + * @return + */ + private BigInteger getOfferMultiple(BigDecimal exchangePrice, BigDecimal eatPrice) { + // Current latest block price + BigDecimal priceNow = checkPriceNow(); + if (priceNow == null) { + LOG.error("The latest block price did not succeed"); + return null; + } + + // Deviation of the exchange price from the latest effective quotation + BigDecimal offset1 = (priceNow.subtract(exchangePrice)).divide(priceNow, 2, BigDecimal.ROUND_DOWN).abs(); + // Offset between the price being ordered and the latest effective offer + BigDecimal offset2 = (priceNow.subtract(eatPrice)).divide(priceNow, 2, BigDecimal.ROUND_DOWN).abs(); + + // The exchange price deviates more than 10% from the last effective quotation + if (offset1.compareTo(Constant.OFFER_PRICE_OFFERSET) > 0) { + // The price deviated from the latest effective quotation by more than 10% + if (offset2.compareTo(Constant.OFFER_PRICE_OFFERSET) > 0) { + // It only needs 2 times the quoted price + return BigInteger.valueOf(2L); + } + // If the price of the order is not more than 10% deviation from the latest effective quotation, make a 10-fold quotation + return BigInteger.TEN; + } + // 2 times the price + return BigInteger.valueOf(2L); + } + + /** + * Get the latest valid price in the current contract + */ + private BigDecimal checkPriceNow() { + Tuple2 latestPrice = null; + try { + latestPrice = ethClient.nestOfferPriceContract.checkPriceNow(ERC20_TOKEN_ADDRESS).sendAsync().get(); + } catch (Exception e) { + LOG.error("Get {} price through price contract exception :{}", SYMBOL, e.getMessage()); + e.printStackTrace(); + } + BigInteger ethAmount = latestPrice.getValue1(); + BigInteger erc20Amount = latestPrice.getValue2(); + + // The latest effective price in the price contract + return calPrice(erc20Amount, ethAmount); + } + + /** + * Determine if the contract meets the conditions for ordering + * + * @param contractAddress Contract address + * @param ethAmount Remaining ETH amount + * @param erc20Amount The remaining ERC20 amount + * @param coinPrice Exchange price + * @param offerThreeData + * @return + */ + private boolean canEat(String contractAddress, BigInteger ethAmount, BigInteger erc20Amount, BigDecimal coinPrice, OfferThreeData offerThreeData) { + // Determine whether the tradable balance is greater than 0 + if (ethAmount.compareTo(BigInteger.ZERO) == 0 && erc20Amount.compareTo(BigInteger.ZERO) == 0) { + LOG.info("The contract has been eaten up: " + offerThreeData.getContractAddress()); + return false; + } + + // Compared with huocoin exchange price offset, more than the specified value on the order + BigDecimal price = calPrice(erc20Amount, ethAmount); + BigDecimal offset = (price.subtract(coinPrice)).divide(coinPrice, 4, BigDecimal.ROUND_DOWN).abs(); + if (offset.compareTo(EAT_PRICE_OFFERSET) < 0) { + return false; + } + + LOG.info("{} The remaining ETH that can be traded:" + ethAmount + " The rest can be traded {}:" + erc20Amount, contractAddress, SYMBOL); + return true; + } + + /** + * Eat sheet quoted recharge + * + * @return + */ + private String eatOfferRecharge(String sellTokenName, BigInteger sellTokenAmount) { + /** + * Get the token exchange token corresponding to the address of the recharge wallet + */ + String currency = sellTokenName; + ApiClient client = new ApiClient(API_KEY, API_SECRET); + DepositAddressResponse depositAddress = client.getDepositAddress(currency); + int code = depositAddress.getCode(); + if (code != 200) { + LOG.info("Fire coin exchange failed to query recharge address"); + return null; + } + + String exchangeTokenAddress = depositAddress.getData().get(0).getAddress(); + LOG.info("Address of exchange charging currency:" + exchangeTokenAddress); + // Ethereum addresses are 42 bits long and begin with 0x (the ethereum that the exchange queries defaults to first, making sure to prevent changes) + if (exchangeTokenAddress.length() != 42 || !exchangeTokenAddress.substring(0, 2).equalsIgnoreCase("0x")) { + LOG.info("Error querying the exchange address, the address found is:" + exchangeTokenAddress); + return null; + } + + // Query balance + BigInteger balance = BigInteger.ZERO; + try { + if (currency.equalsIgnoreCase("eth")) { + balance = ethClient.ethGetBalance(); + } else { + balance = ethClient.ethBalanceOfErc20(); + } + } catch (Exception e) { + LOG.info("Query ETH balance failed, please check network status"); + return null; + } + + // Check if the balance is sufficient + if (balance.compareTo(sellTokenAmount) < 0) { + LOG.info("Fund is insufficient, still cannot transfer to address of exchange account, check whether there is quotation contract that has not got back"); + return null; + } + + String transactionHash; + // Recharge assets to the exchange + if (currency.equalsIgnoreCase("eth")) { + LOG.info("top-up:" + exchangeTokenAddress + " amount:" + sellTokenAmount); + transactionHash = transferEth(exchangeTokenAddress, sellTokenAmount); + } else { + LOG.info("top-up:" + ERC20_TOKEN_ADDRESS + " Exchange wallet address:" + exchangeTokenAddress + " amount:" + sellTokenAmount); + transactionHash = transferErc20(exchangeTokenAddress, sellTokenAmount); + } + + return transactionHash; + } + + /** + * Fire currency exchange -> for trading operations + * + * @return + */ + private Long exchangeOperation(BigDecimal rightTokenAmount, String buyTokenName, BigDecimal leftTokenAmount) { + Long orderId = -1L; + // Buy ETH, sell ERC20 + if (buyTokenName.equalsIgnoreCase("ETH")) { + if (SYMBOLS.endsWith("eth")) { + orderId = sendSellMarketOrder(SYMBOLS, String.valueOf(rightTokenAmount.divide(Constant.UNIT_ETH, 2, BigDecimal.ROUND_DOWN))); + } else { + orderId = sendBuyMarketOrder(SYMBOLS, String.valueOf(rightTokenAmount.divide(MathUtils.toDecimal(DECIMAL), 2, BigDecimal.ROUND_DOWN))); + } + } else { + // Buy ERC20, sell ETH + if (SYMBOLS.endsWith("eth")) { + orderId = sendBuyMarketOrder(SYMBOLS, String.valueOf(leftTokenAmount.divide(Constant.UNIT_ETH, 2, BigDecimal.ROUND_DOWN))); + } else { + orderId = sendSellMarketOrder(SYMBOLS, String.valueOf(leftTokenAmount.divide(Constant.UNIT_ETH, 2, BigDecimal.ROUND_DOWN))); + } + } + + return orderId; + } + + // Market selling order (e.g. trade to HTUSDT, sell HT to get USDT) + private Long sendSellMarketOrder(String symbol, String amount) { + ApiClient client = new ApiClient(API_KEY, API_SECRET); + AccountsResponse accounts = client.accounts(); + Long orderId = -1L; + List list = (List) accounts.getData(); + Accounts account = list.get(0); + long accountId = account.getId(); + + // create order: + CreateOrderRequest createOrderReq = new CreateOrderRequest(); + createOrderReq.accountId = String.valueOf(accountId); + createOrderReq.amount = amount; + createOrderReq.symbol = symbol; + createOrderReq.type = CreateOrderRequest.OrderType.SELL_MARKET; // The market price to sell + createOrderReq.source = "api"; + + //------------------------------------------------------ Create the order ------------------------------------------------------- + try { + orderId = client.createOrder(createOrderReq); + } catch (Exception e) { + LOG.info("There is an exception to the original sell order"); + return -1L; + } + + LOG.info("Order ID: " + orderId); + return orderId; + } + + /** + * Market order (e.g., trading to HTUSDT, buying TO HT and selling to USDT) + */ + private Long sendBuyMarketOrder(String symbol, String amount) { + ApiClient client = new ApiClient(API_KEY, API_SECRET); + AccountsResponse accounts = client.accounts(); + Long orderId = -1L; + List list = (List) accounts.getData(); + Accounts account = list.get(0); + long accountId = account.getId(); + + // create order: + CreateOrderRequest createOrderReq = new CreateOrderRequest(); + createOrderReq.accountId = String.valueOf(accountId); + createOrderReq.amount = amount; + createOrderReq.symbol = symbol; + createOrderReq.type = CreateOrderRequest.OrderType.BUY_MARKET; // The market price to sell + createOrderReq.source = "api"; + + //------------------------------------------------------ Create the order ------------------------------------------------------- + try { + orderId = client.createOrder(createOrderReq); + } catch (Exception e) { + LOG.info("Buy and buy abnormal"); + return -1L; + } + + LOG.info("Order ID: " + orderId); + return orderId; + } + + + /** + * Query the exchange's token balance + * + * @return + */ + private HashMap getExchangeBalance() { + ApiClient client = new ApiClient(API_KEY, API_SECRET); + AccountsResponse accounts = client.accounts(); + List listAccounts = (List) accounts.getData(); + if (!listAccounts.isEmpty()) { + //------------------------------------------------------ The account balance ------------------------------------------------------- + BalanceResponse balance = client.balance(String.valueOf(listAccounts.get(0).getId())); + + String s = ""; + try { + s = JsonUtil.writeValue(balance); + } catch (IOException e) { + e.printStackTrace(); + } + + JSONObject jsonObject = JSONObject.parseObject(s); + String data = jsonObject.getString("data"); + JSONObject jsonObject1 = JSONObject.parseObject(data); + JSONArray list = jsonObject1.getJSONArray("list"); + HashMap hashMap = new HashMap(); + + list.forEach(li -> { + JSONObject jsonObject2 = JSONObject.parseObject(String.valueOf(li)); + String balanceStr = jsonObject2.getString("balance"); + String currency = jsonObject2.getString("currency").toLowerCase(); + if (!balanceStr.equalsIgnoreCase("0")) { + if (hashMap.containsKey(currency)) { + // The same token may appear several times, and select the one with the largest amount + if (new BigDecimal(hashMap.get(currency)).compareTo(new BigDecimal(balanceStr)) < 0) { + hashMap.replace(currency, hashMap.get(currency), balanceStr); + } + } else { + hashMap.put(currency, balanceStr); + } + } + }); + LOG.info("All balances in the exchange account:" + hashMap); + return hashMap; + } + return null; + } + + // Initiate ETH transaction + private String transferEth(String address, BigInteger value) { + try { + BigInteger nonce = ethClient.ethGetTransactionCount(); + BigInteger gasPrice = ethClient.ethGasPrice(); + gasPrice = gasPrice.multiply(new BigInteger("3")); + BigInteger gasLimit = new BigInteger("200000"); + RawTransaction rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, address, value); + EthSendTransaction ethSendTransaction = ethClient.ethSendRawTransaction(rawTransaction); + return ethSendTransaction.getTransactionHash(); + } catch (Exception e) { + return null; + } + + } + + // Initiate AN ERC20 token transaction + private String transferErc20(String address, BigInteger value) { + try { + BigInteger nonce = ethClient.ethGetTransactionCount(); + BigInteger gasPrice = ethClient.ethGasPrice(); + gasPrice = gasPrice.multiply(new BigInteger("3")); + BigInteger gasLimit = new BigInteger("200000"); + if (address != null) { + final Function function = new Function( + "transfer", + Arrays.asList(new Address(address), + new Uint256(value)), + Collections.>emptyList()); + String encode = FunctionEncoder.encode(function); + RawTransaction rawTransaction = RawTransaction.createTransaction( + nonce, + gasPrice, + gasLimit, + ERC20_TOKEN_ADDRESS, + encode); + + String transactionHash = ethClient.ethSendRawTransaction(rawTransaction).getTransactionHash(); + return transactionHash; + } + } catch (Exception e) { + return null; + } + return null; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/service/serviceImpl/OfferThreeDataServiceImpl.java b/NestEatOffer/src/main/java/com/nest/ib/service/serviceImpl/OfferThreeDataServiceImpl.java new file mode 100644 index 0000000..cb86908 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/service/serviceImpl/OfferThreeDataServiceImpl.java @@ -0,0 +1,100 @@ +package com.nest.ib.service.serviceImpl; + +import com.nest.ib.constant.Constant; +import com.nest.ib.contract.Nest3OfferMain; +import com.nest.ib.model.OfferContractData; +import com.nest.ib.model.OfferThreeData; +import com.nest.ib.service.EatOfferAndTransactionService; +import com.nest.ib.service.OfferThreeDataService; +import com.nest.ib.utils.EthClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.List; + +@Service +public class OfferThreeDataServiceImpl implements OfferThreeDataService { + private static final Logger LOG = LoggerFactory.getLogger(OfferThreeDataServiceImpl.class); + + @Autowired + private EatOfferAndTransactionService transactionService; + @Autowired + private EthClient ethClient; + + @Override + public List listOfferData() { + + BigInteger blockNumber = null; + try { + blockNumber = ethClient.ethBlockNumber(); + } catch (IOException e) { + LOG.error("Gets the latest block number exception:{}", e.getMessage()); + e.printStackTrace(); + } + + // Obtain the latest 100 offer contracts + List list = null; + try { + list = ethClient.list(Constant.LIST_MAX_COUNT); + } catch (Exception e) { + LOG.error("The List interface failed to get contract data:{}", e.getMessage()); + e.printStackTrace(); + } + + if (CollectionUtils.isEmpty(list)) { + return null; + } + + List dataList = new ArrayList<>(); + int size = list.size(); + for (int i = 0; i < size; i++) { + OfferContractData t = list.get(i); + // Saves the data for the specified token + if (!EatOfferAndTransactionServiceImpl.ERC20_TOKEN_ADDRESS.equalsIgnoreCase(t.getTokenAddress())) { + continue; + } + + OfferThreeData offerThreeData = new OfferThreeData(); + offerThreeData.setContractAddress(t.getUuid()); + offerThreeData.setErc20TokenAddress(t.getTokenAddress()); + offerThreeData.setErc20TokenName(transactionService.getTokenSymbol()); + offerThreeData.setOwner(t.getOwner()); + offerThreeData.setBlockNumber(new BigInteger(t.getBlockNum())); + offerThreeData.setIntervalBlock(transactionService.getBlockLimit().intValue()); + offerThreeData.setServiceCharge(new BigDecimal(t.getServiceCharge())); + + // Determine if block 25 has passed + if (blockNumber.subtract(offerThreeData.getBlockNumber()).intValue() >= 25) { + continue; + } + + // Determine whether to get back by whether the balance and fee are zero + BigDecimal ethAmount = new BigDecimal(t.getEthAmount()); + BigDecimal erc20Amount = new BigDecimal(t.getTokenAmount()); + if (ethAmount.compareTo(BigDecimal.ZERO) <= 0 + && erc20Amount.compareTo(BigDecimal.ZERO) <= 0 + && offerThreeData.getServiceCharge().compareTo(BigDecimal.ZERO) <= 0) { + continue; + } + + // Determine whether the remaining tradable balance is 0 + BigDecimal dealEth = new BigDecimal(t.getDealEthAmount()); + BigDecimal dealErc20 = new BigDecimal(t.getDealTokenAmount()); + if (dealEth.compareTo(BigDecimal.ZERO) <= 0 && dealErc20.compareTo(BigDecimal.ZERO) <= 0) { + continue; + } + dataList.add(offerThreeData); + } + return dataList; + } + +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/ContractFactory.java b/NestEatOffer/src/main/java/com/nest/ib/utils/ContractFactory.java new file mode 100644 index 0000000..23569a4 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/ContractFactory.java @@ -0,0 +1,41 @@ +package com.nest.ib.utils; + +import com.nest.ib.constant.AddressEnum; +import com.nest.ib.contract.ERC20; +import com.nest.ib.contract.Nest3OfferMain; +import com.nest.ib.contract.NestOfferPriceContract; +import com.nest.ib.service.serviceImpl.EatOfferAndTransactionServiceImpl; +import org.web3j.crypto.Credentials; +import org.web3j.protocol.Web3j; +import org.web3j.tx.Contract; + +/** + * @author wll + * @date 2020/7/16 13:29 + * Contract class creation + */ +public class ContractFactory { + + /** + * Erc20 contracts + */ + public static ERC20 erc20(Credentials credentials, Web3j web3j) { + return ERC20.load(EatOfferAndTransactionServiceImpl.ERC20_TOKEN_ADDRESS, web3j, credentials, Contract.GAS_PRICE, Contract.GAS_LIMIT); + } + + /** + * Contract price + */ + public static NestOfferPriceContract nestOfferPriceContract(Credentials credentials, Web3j web3jFree) { + return NestOfferPriceContract.load(AddressEnum.OFFER_PRICE_CONTRACT_ADDRESS.getValue(), web3jFree, credentials, Contract.GAS_PRICE, Contract.GAS_LIMIT); + } + + /** + * Quote contract + */ + public static Nest3OfferMain nest3OfferMain(Credentials credentials, Web3j web3jFree) { + return Nest3OfferMain.load(AddressEnum.OFFER_CONTRACT_FACTORY_ADDRESS.getValue(), web3jFree, credentials, Contract.GAS_PRICE, Contract.GAS_LIMIT); + } + + +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/EthClient.java b/NestEatOffer/src/main/java/com/nest/ib/utils/EthClient.java new file mode 100644 index 0000000..e6e9ff5 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/EthClient.java @@ -0,0 +1,506 @@ +package com.nest.ib.utils; + +import com.nest.ib.constant.AddressEnum; +import com.nest.ib.constant.Constant; +import com.nest.ib.contract.ERC20; +import com.nest.ib.contract.Nest3OfferMain; +import com.nest.ib.contract.NestOfferPriceContract; +import com.nest.ib.contract.VoteContract; +import com.nest.ib.model.OfferContractData; +import com.nest.ib.service.EatOfferAndTransactionService; +import com.nest.ib.service.serviceImpl.EatOfferAndTransactionServiceImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; +import org.web3j.abi.FunctionEncoder; +import org.web3j.abi.TypeReference; +import org.web3j.abi.datatypes.Address; +import org.web3j.abi.datatypes.Function; +import org.web3j.abi.datatypes.Type; +import org.web3j.abi.datatypes.generated.Uint256; +import org.web3j.crypto.Credentials; +import org.web3j.crypto.RawTransaction; +import org.web3j.crypto.TransactionEncoder; +import org.web3j.protocol.Web3j; +import org.web3j.protocol.core.DefaultBlockParameterName; +import org.web3j.protocol.core.methods.response.EthSendTransaction; +import org.web3j.protocol.core.methods.response.TransactionReceipt; +import org.web3j.protocol.http.HttpService; +import org.web3j.tx.Contract; +import org.web3j.utils.Numeric; + +import java.io.IOException; +import java.math.BigInteger; +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.LinkedBlockingDeque; + + +/** + * @author wll + * @date 2020/7/16 13:25 + * Operate Ethereum, get data, send transactions + */ +@Component +public class EthClient { + private static final Logger LOG = LoggerFactory.getLogger(EthClient.class); + + @Autowired + private EatOfferAndTransactionService transactionService; + + public Web3j web3j; + public Credentials credentials; + public ERC20 erc20; + public NestOfferPriceContract nestOfferPriceContract; + public Nest3OfferMain nest3OfferMain; + + // node + public static String NODE; + + + /** + * Initializing node + */ + public void initNode(String node) { + web3j = Web3j.build(new HttpService(node)); + NODE = node; + } + + + /** + * User private key update + * + * @param userPrivateKey + */ + public void updateUserPrivateKey(String userPrivateKey) { + credentials = Credentials.create(userPrivateKey); + + resetBean(); + } + + /** + * Registered bean + */ + public void resetBean() { + if (credentials == null) { + return; + } + + // Mapping contract address + mappingContractAddress(); + + // Loading contract + erc20 = ContractFactory.erc20(credentials, web3j); + nestOfferPriceContract = ContractFactory.nestOfferPriceContract(credentials, web3j); + nest3OfferMain = ContractFactory.nest3OfferMain(credentials, web3j); + + // Get ERC20 token information + getErc20Info(); + + // Gets the upper limit of the block interval, which is the time T0 required for the validation period + setBlockLimit(); + + // Check the authorization + try { + approveToOfferFactoryContract(); + } catch (Exception e) { + LOG.error("ERC20 authorization for the quoted factory contract failed:{}", e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Get the wallet address + * + * @return + */ + public String getAddress() { + return credentials == null ? "Please fill in the correct private key first" : credentials.getAddress(); + } + + /** + * Map the address of each contract before registering it + */ + public void mappingContractAddress() { + // NToken offer contract mapping + if (!AddressEnum.USDT_TOKEN_CONTRACT_ADDRESS.getValue().equalsIgnoreCase(EatOfferAndTransactionServiceImpl.ERC20_TOKEN_ADDRESS)) { + String nTokenFactoryAddress = mapping(credentials, web3j, "NToken quote factory", "nest.nToken.offerMain"); + AddressEnum.OFFER_CONTRACT_FACTORY_ADDRESS.setValue(nTokenFactoryAddress); + } else { + // NEST quote contract address + String nestFactoryAddress = mapping(credentials, web3j, "Nest Quote Factory", "nest.v3.offerMain"); + AddressEnum.OFFER_CONTRACT_FACTORY_ADDRESS.setValue(nestFactoryAddress); + } + + // Quotation contract + String offerPriceAddress = mapping(credentials, web3j, "Quote the price", "nest.v3.offerPrice"); + AddressEnum.OFFER_PRICE_CONTRACT_ADDRESS.setValue(offerPriceAddress); + } + + + /** + * Check whether one-time authorization has been conducted. If not, one-time authorization is conducted + */ + public void approveToOfferFactoryContract() throws ExecutionException, InterruptedException, IOException { + // Check the authorized amount + BigInteger approveValue = allowance(); + BigInteger nonce = ethGetTransactionCount(); + // 1.5 times the authorization of gasPrice, which can be adjusted by itself + BigInteger gasPrice = ethGasPrice().multiply(BigInteger.valueOf(15)).divide(BigInteger.TEN); + + if (approveValue.compareTo(new BigInteger("100000000000000")) <= 0) { + + List typeList = Arrays.asList( + new Address(AddressEnum.OFFER_CONTRACT_FACTORY_ADDRESS.getValue()), + new Uint256(new BigInteger("999999999999999999999999999999999999999999")) + ); + + Function function = new Function("approve", typeList, Collections.>emptyList()); + String encode = FunctionEncoder.encode(function); + String transaction = ethSendErc20RawTransaction(gasPrice, nonce, Constant.OFFER_GAS_LIMIT, BigInteger.ZERO, encode); + LOG.info("One-time authorization hash:" + transaction); + } + } + + /** + * The default gasPrice + * + * @return + * @throws IOException + */ + public BigInteger ethGasPrice() throws IOException { + return web3j.ethGasPrice().send().getGasPrice(); + } + + /** + * View the authorized amount + * + * @return + * @throws ExecutionException + * @throws InterruptedException + */ + public BigInteger allowance() throws ExecutionException, InterruptedException { + return erc20.allowance(credentials.getAddress(), AddressEnum.OFFER_CONTRACT_FACTORY_ADDRESS.getValue()).sendAsync().get(); + } + + /** + * For the nonce value + * + * @return + * @throws IOException + */ + public BigInteger ethGetTransactionCount() throws IOException { + return web3j.ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.LATEST).send().getTransactionCount(); + } + + /** + * Get the latest ethereum block number + * + * @return + * @throws IOException + */ + public BigInteger ethBlockNumber() throws IOException { + return web3j.ethBlockNumber().send().getBlockNumber(); + } + + /** + * Obtain contract information from the contract address + * + * @param contractAddress + * @return + */ + public OfferContractData getPrice(String contractAddress) throws ExecutionException, InterruptedException { + BigInteger index = nest3OfferMain.toIndex(contractAddress).sendAsync().get(); + String prieInfo = nest3OfferMain.getPrice(index).sendAsync().get(); + + OfferContractData contractData = null; + if (!StringUtils.isEmpty(prieInfo)) { + contractData = transformToOfferContractData(prieInfo).get(0); + } + return contractData; + } + + /** + * Check the ETH balance in your wallet + * + * @return + * @throws IOException + */ + public BigInteger ethGetBalance() { + try { + return web3j.ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.LATEST).send().getBalance(); + } catch (IOException e) { + LOG.error("There is an exception to the ETH balance of the account:{}", e.getMessage()); + e.printStackTrace(); + } + return null; + } + + /** + * Query the ERC20 balance + * + * @return + * @throws Exception + */ + public BigInteger ethBalanceOfErc20() { + try { + return erc20.balanceOf(credentials.getAddress()).send(); + } catch (Exception e) { + LOG.error("There is an exception for getting the balance of account:{}", EatOfferAndTransactionServiceImpl.SYMBOL, e.getMessage()); + e.printStackTrace(); + } + return null; + } + + /** + * Find contract order information in reverse order + * + * @param count Maximum number of records returned + * @return + */ + public List list(BigInteger count) throws Exception { + String contracts = nest3OfferMain.list(BigInteger.ZERO, count, BigInteger.ZERO).send(); + if (StringUtils.isEmpty(contracts)) { + return null; + } + + return transformToOfferContractData(contracts); + } + + /** + * Find contract information + * + * @param count + * @param start + * @return + */ + public List find(BigInteger count, String start) throws Exception { + if (nest3OfferMain == null || credentials == null) { + return null; + } + + String contracts = nest3OfferMain.find(start, count, Constant.MAX_FIND_COUNT, credentials.getAddress()).send(); + if (StringUtils.isEmpty(contracts)) { + return null; + } + + // The data returned by the Find interface is parsed + List offerContractDataList = transformToOfferContractData(contracts); + + return offerContractDataList; + } + + /** + * Initiate order buying + * + * @param typeList Parameter collection + * @param payableEth Number of eth + * @param gasPrice + * @return + */ + public String sendEatOffer(List typeList, BigInteger payableEth, String method, BigInteger gasPrice) { + Function function = new Function(method, typeList, Collections.>emptyList()); + String encode = FunctionEncoder.encode(function); + + BigInteger nonce = null; + try { + nonce = ethGetTransactionCount(); + } catch (IOException e) { + LOG.error("Failure to obtain gasPrice by eating order", e.getMessage()); + e.printStackTrace(); + } + + String transaction = null; + try { + transaction = ethSendRawTransaction(gasPrice, nonce, Constant.OFFER_GAS_LIMIT, payableEth, encode); + } catch (Exception e) { + LOG.error("The order fell through", e.getMessage()); + e.printStackTrace(); + } + return transaction; + } + + /** + * Fetch quoted assets + * + * @return + */ + public String turnOut(BigInteger nonce, List typeList, BigInteger gasPrice) { + Function function = new Function("turnOut", typeList, Collections.>emptyList()); + String encode = FunctionEncoder.encode(function); + String transaction = null; + try { + transaction = ethSendRawTransaction(gasPrice, nonce, Constant.TURN_OUT_GAS_LIMIT, BigInteger.ZERO, encode); + } catch (Exception e) { + LOG.error("There is an exception for fetching quoted assets {}", e.getMessage()); + e.printStackTrace(); + } + return transaction; + } + + /** + * Get the total number of quoted contracts + */ + public BigInteger getPriceCount() throws Exception { + return nest3OfferMain.getPriceCount().send(); + } + + /** + * View transaction status + */ + public TransactionReceipt ethGetTransactionReceipt(String hash) throws IOException { + TransactionReceipt transactionReceipt = web3j.ethGetTransactionReceipt(hash).send().getTransactionReceipt().get(); + return transactionReceipt; + } + + + /** + * Send a deal + */ + public EthSendTransaction ethSendRawTransaction(RawTransaction rawTransaction) throws ExecutionException, InterruptedException { + byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials); + String hexValue = Numeric.toHexString(signMessage); + EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get(); + return ethSendTransaction; + } + + + /** + * Converts the data returned by the contract into an object + * + * @param contracts + * @return + */ + private List transformToOfferContractData(String contracts) { + List dataList = new ArrayList<>(); + + String[] split = contracts.split(","); + // The last one is empty + int n = split.length - 1; + String prefix = "0x"; + for (int i = 0; i < n; i += 9) { + OfferContractData contractData = new OfferContractData(); + contractData.setUuid(prefix + split[i]); + contractData.setOwner(prefix + split[i + 1]); + contractData.setTokenAddress(prefix + split[i + 2]); + contractData.setEthAmount(split[i + 3]); + contractData.setTokenAmount(split[i + 4]); + contractData.setDealEthAmount(split[i + 5]); + contractData.setDealTokenAmount(split[i + 6]); + contractData.setBlockNum(split[i + 7]); + contractData.setServiceCharge(split[i + 8]); + dataList.add(contractData); + } + + return dataList; + } + + /** + * Send a deal + */ + private String ethSendRawTransaction(BigInteger gasPrice, BigInteger nonce, BigInteger gasLimit, BigInteger payableEth, String encode) throws ExecutionException, InterruptedException { + RawTransaction rawTransaction = RawTransaction.createTransaction( + nonce, + gasPrice, + gasLimit, + AddressEnum.OFFER_CONTRACT_FACTORY_ADDRESS.getValue(), + payableEth, + encode); + byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials); + String hexValue = Numeric.toHexString(signedMessage); + String transactionHash = web3j.ethSendRawTransaction(hexValue).sendAsync().get().getTransactionHash(); + + return transactionHash; + } + + /** + * Send the ERC20 transaction + */ + private String ethSendErc20RawTransaction(BigInteger gasPrice, BigInteger nonce, BigInteger gasLimit, BigInteger payableEth, String encode) throws ExecutionException, InterruptedException { + RawTransaction rawTransaction = RawTransaction.createTransaction( + nonce, + gasPrice, + gasLimit, + EatOfferAndTransactionServiceImpl.ERC20_TOKEN_ADDRESS, + payableEth, + encode); + byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials); + String hexValue = Numeric.toHexString(signedMessage); + + String transactionHash = web3j.ethSendRawTransaction(hexValue).sendAsync().get().getTransactionHash(); + return transactionHash; + } + + + /** + * Mapping the contract + * + * @return + */ + private String mapping(Credentials credentials1, Web3j web3j1, String addressName, String mappingName) { + String address = null; + try { + VoteContract mappingContract = VoteContract.load(AddressEnum.VOTE_CONTRACT_ADDRESS.getValue(), web3j1, credentials1, Contract.GAS_PRICE, Contract.GAS_LIMIT); + address = mappingContract.checkAddress(mappingName).sendAsync().get(); + } catch (Exception e) { + LOG.error("{} contract address update failed:{}", addressName, e.getMessage()); + e.printStackTrace(); + } + + if (StringUtils.isEmpty(address) || address.equalsIgnoreCase(Address.DEFAULT.getValue())) { + LOG.error("{} contract address update failed", addressName); + return null; + } + + LOG.info("{} contract address update:{}", addressName, address); + return address; + } + + /** + * Set the validation block interval + */ + private void setBlockLimit() { + try { + BigInteger blockLimit = nest3OfferMain.checkBlockLimit().send(); + transactionService.setBlockLimit(blockLimit); + } catch (Exception e) { + LOG.error("Failed to get block interval upper limit. Set the default value of 25:{}", e.getMessage()); + transactionService.setBlockLimit(Constant.DEFAULT_BLOCK_LIMIT); + e.printStackTrace(); + } + } + + /** + * Get ERC20 token information + */ + private void getErc20Info() { + try { + BigInteger decimal = erc20.decimals().send(); + long unit = (long) Math.pow(10, decimal.intValue()); + transactionService.setErc20Decimal(BigInteger.valueOf(unit)); + + String symbol = erc20.symbol().send(); + + //HBTC special treatment should be replaced by BTC + if (symbol.equalsIgnoreCase("HBTC")) { + symbol = "BTC"; + } + + String huobiApi = "https://api.huobi.pro/market/history/trade?size=1&symbol="; + String url = huobiApi + EatOfferAndTransactionServiceImpl.SYMBOLS.toLowerCase(); + System.out.println(url); + + transactionService.setHuoBiApi(url); + transactionService.setTokenSymbol(symbol); + LOG.info("ERC20 scrip decimal places: {} trading on: eth{}", unit, symbol.toLowerCase()); + } catch (Exception e) { + LOG.error("Failed to get the ERC20 token {decimal} and identifier {symbol}:{}", e.getMessage()); + e.printStackTrace(); + } + } + +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/HttpClientUtil.java b/NestEatOffer/src/main/java/com/nest/ib/utils/HttpClientUtil.java new file mode 100644 index 0000000..6201391 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/HttpClientUtil.java @@ -0,0 +1,409 @@ +package com.nest.ib.utils; + + +import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.HttpStatus; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContextBuilder; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.entity.mime.content.StringBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.util.EntityUtils; +import org.thymeleaf.util.StringUtils; + +import java.io.File; +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class HttpClientUtil { + + // proxy address + private static String PROXY_IP = "127.0.0.1"; + // The proxy port + private static int PROXY_PORT = 0; + + // Utf-8 character encoding + private static final String CHARSET_UTF_8 = "utf-8"; + + // HTTP content types. In the form equivalent to a form, the data is submitted + private static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded"; + + // HTTP content types. In the form equivalent to a form, the data is submitted + private static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8"; + + // Connection manager + private static PoolingHttpClientConnectionManager pool; + + // Request configuration + private static RequestConfig requestConfig; + + static { + + try { + //"Initialize HttpClientTest~~~ start"; + SSLContextBuilder builder = new SSLContextBuilder(); + builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( + builder.build()); + // The configuration supports both HTTP and HTPPS + Registry socketFactoryRegistry = RegistryBuilder.create().register( + "http", PlainConnectionSocketFactory.getSocketFactory()).register( + "https", sslsf).build(); + // Initializes the connection manager + pool = new PoolingHttpClientConnectionManager( + socketFactoryRegistry); + // Increase the maximum number of connections to 200, which the actual project would be better off reading from the configuration file + pool.setMaxTotal(200); + // Set the maximum route + pool.setDefaultMaxPerRoute(2); + // Initializes requestConfig according to the default timeout limit + int socketTimeout = 10000; + int connectTimeout = 10000; + int connectionRequestTimeout = 10000; + requestConfig = RequestConfig.custom().setConnectionRequestTimeout( + connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout( + connectTimeout).build(); + + //Initialize HttpClientTest~~~ end; + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (KeyStoreException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } + + // Set the request timeout + requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000) + .setConnectionRequestTimeout(50000).build(); + } + + public static void updateProxy(String proxyIp, int proxyPort) { + if (!StringUtils.isEmpty(proxyIp)) { + PROXY_IP = proxyIp; + } + if (proxyPort > 0) { + PROXY_PORT = proxyPort; + } + } + + public static int getProxyPort() { + return PROXY_PORT; + } + + public static String getProxyIp() { + return PROXY_IP; + } + + public static CloseableHttpClient getHttpClient() { + CloseableHttpClient httpClient = HttpClients.custom() + // Set up connection pool management + .setConnectionManager(pool) + // Set request configuration + .setDefaultRequestConfig(requestConfig) + // Set the number of retries + .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)) + .build(); + + return httpClient; + } + + /** + * Send a Post request + * + * @param httpPost + * @return + */ + private static String sendHttpPost(HttpPost httpPost) { + CloseableHttpClient httpClient = null; + CloseableHttpResponse response = null; + // Response content + String responseContent = null; + try { + // Create the default httpClient instance. + httpClient = getHttpClient(); + // Configure request information + httpPost.setConfig(requestConfig); + // Perform the requested + response = httpClient.execute(httpPost); + // Get the response instance + HttpEntity entity = response.getEntity(); + + // Determine response state + if (response.getStatusLine().getStatusCode() >= 300) { + throw new Exception( + "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode()); + } + + if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { + responseContent = EntityUtils.toString(entity, CHARSET_UTF_8); + EntityUtils.consume(entity); + } + + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + // Release resources + if (response != null) { + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return responseContent; + } + + /** + * Send a Get request + * + * @param httpGet + * @return + */ + private static String sendHttpGet(HttpGet httpGet) { + CloseableHttpClient httpClient = null; + CloseableHttpResponse response = null; + // Response content + String responseContent = null; + try { + // Create the default httpClient instance. + httpClient = getHttpClient(); + // Configure request information + if (PROXY_PORT == 0) { + httpGet.setConfig(requestConfig); + } else { + HttpHost proxy = new HttpHost(PROXY_IP, PROXY_PORT); + RequestConfig proxyConfig = RequestConfig.custom().setProxy(proxy).build(); + httpGet.setConfig(proxyConfig); + } + // Perform the requested + response = httpClient.execute(httpGet); + // Get the response instance + HttpEntity entity = response.getEntity(); + + // Determine response state + if (response.getStatusLine().getStatusCode() >= 300) { + throw new Exception( + "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode()); + } + + if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { + responseContent = EntityUtils.toString(entity, CHARSET_UTF_8); + EntityUtils.consume(entity); + } + + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + // Release resources + if (response != null) { + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return responseContent; + } + + private static String sendHttpGet(HttpGet httpGet, String token, String headerName) { + CloseableHttpClient httpClient = null; + CloseableHttpResponse response = null; + // Response content + String responseContent = null; + try { + // Create the default httpClient instance. + httpClient = getHttpClient(); + // Configure request information + httpGet.setConfig(requestConfig); + httpGet.setHeader("Content-Type", CONTENT_TYPE_FORM_URL); + httpGet.setHeader(headerName, token); + // Perform the requested + response = httpClient.execute(httpGet); + // Get the response instance + HttpEntity entity = response.getEntity(); + + // Determine response state + if (response.getStatusLine().getStatusCode() >= 300) { + throw new Exception( + "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode()); + } + + if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { + responseContent = EntityUtils.toString(entity, CHARSET_UTF_8); + EntityUtils.consume(entity); + } + + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + // Release resources + if (response != null) { + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return responseContent; + } + + + /** + * Send a POST request + * + * @param httpUrl address + */ + public static String sendHttpPost(String httpUrl) { + // Create the httpPost + HttpPost httpPost = new HttpPost(httpUrl); + return sendHttpPost(httpPost); + } + + /** + * Send a GET request + * + * @param httpUrl + */ + public static String sendHttpGet(String httpUrl, String token, String headerName) { + // Create a GET request + HttpGet httpGet = new HttpGet(httpUrl); + return sendHttpGet(httpGet, token, headerName); + } + + public static String sendHttpGet(String httpUrl) { + // Create a GET request + HttpGet httpGet = new HttpGet(httpUrl); + return sendHttpGet(httpGet); + } + + /** + * Send a POST request (with file) + * + * @param httpUrl address + * @param maps parameter + * @param fileLists The attachment + */ + public static String sendHttpPost(String httpUrl, Map maps, List fileLists) { + HttpPost httpPost = new HttpPost(httpUrl); + MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create(); + if (maps != null) { + for (String key : maps.keySet()) { + meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN)); + } + } + if (fileLists != null) { + for (File file : fileLists) { + FileBody fileBody = new FileBody(file); + meBuilder.addPart("files", fileBody); + } + } + HttpEntity reqEntity = meBuilder.build(); + httpPost.setEntity(reqEntity); + return sendHttpPost(httpPost); + } + + /** + * Send a POST request + * + * @param httpUrl address + * @param params parameter(format:key1=value1&key2=value2) + */ + public static String sendHttpPost(String httpUrl, String params) { + HttpPost httpPost = new HttpPost(httpUrl); + try { + if (params != null && params.trim().length() > 0) { + StringEntity stringEntity = new StringEntity(params, "UTF-8"); + stringEntity.setContentType(CONTENT_TYPE_FORM_URL); + httpPost.setEntity(stringEntity); + } + } catch (Exception e) { + e.printStackTrace(); + } + return sendHttpPost(httpPost); + } + + /** + * Send a POST request + * + * @param maps parameter + */ + public static String sendHttpPost(String httpUrl, Map maps) { + String parem = convertStringParamter(maps); + return sendHttpPost(httpUrl, parem); + } + + /** + * Send a POST request to send JSON data + * + * @param httpUrl address + * @param paramsJson parameter(json) + */ + public static String sendHttpPostJson(String httpUrl, String paramsJson) { + HttpPost httpPost = new HttpPost(httpUrl); + try { + if (paramsJson != null && paramsJson.trim().length() > 0) { + StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8"); + stringEntity.setContentType(CONTENT_TYPE_JSON_URL); + httpPost.setEntity(stringEntity); + } + } catch (Exception e) { + e.printStackTrace(); + } + return sendHttpPost(httpPost); + } + + /** + * Converts the key-value pairs of the Map collection to the form: key1=value1& Key2 =value2 + * + * @param parameterMap The set of key-value pairs that need to be transformed + * @return string + */ + public static String convertStringParamter(Map parameterMap) { + StringBuffer parameterBuffer = new StringBuffer(); + if (parameterMap != null) { + Iterator iterator = parameterMap.keySet().iterator(); + String key = null; + String value = null; + while (iterator.hasNext()) { + key = (String) iterator.next(); + if (parameterMap.get(key) != null) { + value = (String) parameterMap.get(key); + } else { + value = ""; + } + parameterBuffer.append(key).append("=").append(value); + if (iterator.hasNext()) { + parameterBuffer.append("&"); + } + } + } + return parameterBuffer.toString(); + } + +} + diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/MathUtils.java b/NestEatOffer/src/main/java/com/nest/ib/utils/MathUtils.java new file mode 100644 index 0000000..fd90b0e --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/MathUtils.java @@ -0,0 +1,60 @@ +package com.nest.ib.utils; + +import java.math.BigDecimal; +import java.math.BigInteger; + +/** + * @author wll + * @date 2020/7/16 21:15 + * Digital manipulation tools class + */ +public class MathUtils { + + /** + * BigInteger / BigDecimal + */ + public static BigDecimal intDivDec(BigInteger bigInteger, BigDecimal decimal, int scale) { + return toDecimal(bigInteger).divide(decimal, scale, BigDecimal.ROUND_DOWN); + } + + /** + * BigDecimal * BigInteger + */ + public static BigDecimal decMulInt(BigDecimal decimal, BigInteger bigInteger) { + return decimal.multiply(toDecimal(bigInteger)); + } + + /** + * BigDecimal - BigInteger + */ + public static BigDecimal decSubInt(BigDecimal decimal, BigInteger bigInteger) { + return decimal.subtract(toDecimal(bigInteger)); + } + + /** + * BigDecimal to BigInteger + * @param decimal + * @return + */ + public static BigInteger toBigInt(BigDecimal decimal) { + return new BigInteger(String.valueOf(decimal.setScale(0, BigDecimal.ROUND_DOWN))); + } + + /** + * BigInteger to BigDecimal + * @param bigInteger + * @return + */ + public static BigDecimal toDecimal(BigInteger bigInteger) { + return new BigDecimal(String.valueOf(bigInteger)); + } + + /** + * BigInteger / BigInteger + * @return + */ + + public static BigDecimal intDivInt(BigInteger bigInteger1, BigInteger bigInteger2, int scale) { + return toDecimal(bigInteger1).divide(toDecimal(bigInteger2), scale, BigDecimal.ROUND_DOWN); + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/api/ApiClient.java b/NestEatOffer/src/main/java/com/nest/ib/utils/api/ApiClient.java new file mode 100644 index 0000000..a329044 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/api/ApiClient.java @@ -0,0 +1,666 @@ +package com.nest.ib.utils.api; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.nest.ib.utils.request.CreateOrderRequest; +import com.nest.ib.utils.request.DepthRequest; +import com.nest.ib.utils.request.IntrustOrdersDetailRequest; +import com.nest.ib.utils.response.*; +import okhttp3.*; +import okhttp3.OkHttpClient.Builder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.xml.bind.DatatypeConverter; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +/** + * API client. + * + * @Date 2018/1/14 + * @Time 16:02 + */ +public class ApiClient { + + static final int CONN_TIMEOUT = 5; + static final int READ_TIMEOUT = 5; + static final int WRITE_TIMEOUT = 5; + + + static final String API_URL = "https://api.huobi.pro"; + static final String API_HOST = getHost(); + + static final MediaType JSON = MediaType.parse("application/json"); + static final OkHttpClient client = createOkHttpClient(); + + final String accessKeyId; + final String accessKeySecret; + final String assetPassword; + + /** + * Create an instance of ApiClient + * + * @param accessKeyId AccessKeyId + * @param accessKeySecret AccessKeySecret + */ + public ApiClient(String accessKeyId, String accessKeySecret) { + this.accessKeyId = accessKeyId; + this.accessKeySecret = accessKeySecret; + this.assetPassword = null; + } + + /** + * Create an instance of ApiClient + * + * @param accessKeyId AccessKeyId + * @param accessKeySecret AccessKeySecret + * @param assetPassword AssetPassword + */ + public ApiClient(String accessKeyId, String accessKeySecret, String assetPassword) { + this.accessKeyId = accessKeyId; + this.accessKeySecret = accessKeySecret; + this.assetPassword = assetPassword; + } + /** + * Check the address of charging currency + * + * @return String of address. + */ + public DepositAddressResponse getDepositAddress(String currency){ + HashMap map = new HashMap(); + map.put("currency", currency); + DepositAddressResponse resp = + get("/v2/account/deposit/address", map, new TypeReference() { + }); + return resp; + } + + /** + * Check the withdrawal limit + * + * @return String of address. + */ + public String queryExtractQuota(String currency){ + HashMap map = new HashMap(); + map.put("currency", currency); + String resp = getReturnString("/v2/account/withdraw/quota", map, new TypeReference>>>() { + }); + return resp; + } + + /** + * Enquire currency withdrawal fee + * + * @return String of address. + */ + public String queryExtractServiceCharge(String currency, String authorizedUser) { + HashMap map = new HashMap(); + map.put("currency", currency); + map.put("authorizedUser",authorizedUser); + String resp = + getReturnString("/v2/reference/currencies", map, new TypeReference() { + }); + return resp; + } + + /** + * Mention money (ERC20) + * + * @return String of address. + */ + public ExtractERC20Response extractERC20(String address, String amount, String currency, String fee,String chain) { + HashMap map = new HashMap(); + map.put("address",address); + map.put("amount",amount); + map.put("currency", currency); + map.put("fee",fee); + if(chain != null){ + map.put("chain",chain); + } + ExtractERC20Response resp = + post("/v1/dw/withdraw/api/create", map, new TypeReference() { + }); + return resp; + } + + /** + * Query trade pairs + * + * @return List of symbols. + */ + public List getSymbols() { + ApiResponse> resp = + get("/v1/common/symbols", null, new TypeReference>>() { + }); + return resp.checkAndReturn(); + } + + /** + * Check all account information + * + * @return List of accounts. + */ + public List getAccounts() { + ApiResponse> resp = + get("/v1/account/accounts", null, new TypeReference>>() { + }); + return resp.checkAndReturn(); + } + + /** + * Create the order + * + * @param request CreateOrderRequest object. + * @return Order id. + */ + public Long createOrder(CreateOrderRequest request) { + ApiResponse resp = + post("/v1/order/orders/place", request, new TypeReference>() { + }); + return resp.checkAndReturn(); + } + + /** + * Executive orders + * + * @param orderId The id of created order. + * @return Order id. + */ + public String placeOrder(long orderId) { + ApiResponse resp = post("/v1/order/orders/" + orderId + "/place", null, + new TypeReference>() { + }); + return resp.checkAndReturn(); + } + + + // ----------------------------------------Quotation API------------------------------------------- + + /** + * GET /market/history/kline Get the K line data + * + * @param symbol + * @param period + * @param size + * @return + */ + public KlineResponse kline(String symbol, String period, String size) { + HashMap map = new HashMap(); + map.put("symbol", symbol); + map.put("period", period); + map.put("size", size); + KlineResponse resp = get("/market/history/kline", map, new TypeReference>>() { + }); + return resp; + } + + /** + * GET /market/detail/merged Get aggregate quotes (Ticker) + * + * @param symbol + * @return + */ + public MergedResponse merged(String symbol) { + HashMap map = new HashMap(); + map.put("symbol", symbol); + MergedResponse resp = get("/market/detail/merged", map, new TypeReference>>() { + }); + return resp; + } + + /** + * GET /market/depth Get the Market Depth data + * + * @param request + * @return + */ + public DepthResponse depth(DepthRequest request) { + HashMap map = new HashMap(); + map.put("symbol", request.getSymbol()); + map.put("type", request.getType()); + + DepthResponse resp = get("/market/depth", map, new TypeReference>>() { + }); + return resp; + } + + /** + * GET /market/trade Get the Trade Detail data + * + * @param symbol + * @return + */ + public TradeResponse trade(String symbol) { + HashMap map = new HashMap(); + map.put("symbol", symbol); + TradeResponse resp = get("/market/trade", map, new TypeReference() { + }); + return resp; + } + + /** + * GET /market/history/trade Get the most recent transaction records in bulk + * + * @param symbol + * @param size + * @return + */ + public HistoryTradeResponse historyTrade(String symbol, String size) { + HashMap map = new HashMap(); + map.put("symbol", symbol); + map.put("size", size); + HistoryTradeResponse resp = get("/market/history/trade", map, new TypeReference() { + }); + return resp; + } + + /** + * GET /market/detail Get 24-hour Market Detail volume data + * + * @param symbol + * @return + */ + public DetailResponse detail(String symbol) { + HashMap map = new HashMap(); + map.put("symbol", symbol); + DetailResponse resp = get("/market/detail", map, new TypeReference>() { + }); + return resp; + } + + + /** + * GET /v1/common/symbols Query all trading pairs and accuracy supported by the system + * + * @param symbol + * @return + */ + public SymbolsResponse symbols(String symbol) { + HashMap map = new HashMap(); + map.put("symbol", symbol); + SymbolsResponse resp = get("/v1/common/symbols", map, new TypeReference>() { + }); + return resp; + } + + /** + * GET /v1/common/currencys Query all currencies supported by the system + * + * @param symbol + * @return + */ + public CurrencysResponse currencys(String symbol) { + HashMap map = new HashMap(); + map.put("symbol", symbol); + CurrencysResponse resp = get("/v1/common/currencys", map, new TypeReference() { + }); + return resp; + } + + /** + * GET /v1/common/timestamp Query system current time + * + * @return + */ + public TimestampResponse timestamp() { + TimestampResponse resp = get("/v1/common/timestamp", null, new TypeReference() { + }); + return resp; + } + + /** + * GET /v1/account/accounts Query all accounts of the current user (that is, account-ID) + * + * @return + */ + public AccountsResponse accounts() { + AccountsResponse resp = get("/v1/account/accounts", null, new TypeReference>>() { + }); + return resp; + } + + /** + * GET /v1/account/accounts/{account-id}/balance Check the balance of the specified account + * + * @param accountId + * @return + */ + public BalanceResponse balance(String accountId) { + BalanceResponse resp = get("/v1/account/accounts/" + accountId + "/balance", null, new TypeReference>() { + }); + return resp; + } + + /** + * POST /v1/order/orders/{order-id}/submitcancel Request to cancel an order request + * + * @param orderId + * @return + */ + public SubmitcancelResponse submitcancel(String orderId) { + SubmitcancelResponse resp = post("/v1/order/orders/" + orderId + "/submitcancel", null, new TypeReference() { + }); + return resp; + } + + /** + * POST /v1/order/orders/batchcancel Bulk cancellation of order + * + * @param orderList + * @return + */ + public BatchcancelResponse submitcancels(List orderList) { + Map parameterMap = new HashMap(); + parameterMap.put("order-ids", orderList); + BatchcancelResponse resp = post("/v1/order/orders/batchcancel", parameterMap, new TypeReference>>>() { + }); + return resp; + } + + /** + * GET /v1/order/orders/{order-id} Inquire about the details of an order + * + * @param orderId + * @return + */ + public OrdersDetailResponse ordersDetail(String orderId) { + OrdersDetailResponse resp = get("/v1/order/orders/" + orderId, null, new TypeReference() { + }); + return resp; + } + + + /** + * GET /v1/order/orders/{order-id}/matchresults Query the transaction details of an order + * + * @param orderId + * @return + */ + public MatchresultsOrdersDetailResponse matchresults(String orderId) { + MatchresultsOrdersDetailResponse resp = get("/v1/order/orders/" + orderId + "/matchresults", null, new TypeReference() { + }); + return resp; + } + + public IntrustDetailResponse intrustOrdersDetail(IntrustOrdersDetailRequest req) { + HashMap map = new HashMap(); + map.put("symbol", req.symbol); + map.put("states", req.states); + if (req.startDate!=null) { + map.put("startDate",req.startDate); + } + if (req.startDate!=null) { + map.put("start-date",req.startDate); + } + if (req.endDate!=null) { + map.put("end-date",req.endDate); + } + if (req.types!=null) { + map.put("types",req.types); + } + if (req.from!=null) { + map.put("from",req.from); + } + if (req.direct!=null) { + map.put("direct",req.direct); + } + if (req.size!=null) { + map.put("size",req.size); + } + IntrustDetailResponse resp = get("/v1/order/orders/", map, new TypeReference>>() { + }); + return resp; + } + + // send a GET request. + T get(String uri, Map params, TypeReference ref) { + if (params == null) { + params = new HashMap<>(); + } + return call("GET", uri, null, params, ref); + } + String getReturnString(String uri, Map params, TypeReference ref) { + if (params == null) { + params = new HashMap<>(); + } + return callReturnString("GET", uri, null, params, ref); + } + // send a POST request. + T post(String uri, Object object, TypeReference ref) { + return call("POST", uri, object, new HashMap(), ref); + } + String postReturnString(String uri, Object object, TypeReference ref) { + return callReturnString("POST", uri, object, new HashMap(), ref); + } + + // call api by endpoint. + T call(String method, String uri, Object object, Map params, + TypeReference ref) { + ApiSignature sign = new ApiSignature(); + sign.createSignature(this.accessKeyId, this.accessKeySecret, method, API_HOST, uri, params); + try { + Request.Builder builder = null; + if ("POST".equals(method)) { + RequestBody body = RequestBody.create(JSON, JsonUtil.writeValue(object)); + builder = new Request.Builder().url(API_URL + uri + "?" + toQueryString(params)).post(body); + } else { + builder = new Request.Builder().url(API_URL + uri + "?" + toQueryString(params)).get(); + } + if (this.assetPassword != null) { + builder.addHeader("AuthData", authData()); + } + Request request = builder.build(); + Response response = client.newCall(request).execute(); + String s = response.body().string(); + return JsonUtil.readValue(s, ref); + } catch (IOException e) { + throw new ApiException(e); + } + } + + String callReturnString(String method, String uri, Object object, Map params, + TypeReference ref) { + ApiSignature sign = new ApiSignature(); + sign.createSignature(this.accessKeyId, this.accessKeySecret, method, API_HOST, uri, params); + try { + Request.Builder builder = null; + if ("POST".equals(method)) { + RequestBody body = RequestBody.create(JSON, JsonUtil.writeValue(object)); + builder = new Request.Builder().url(API_URL + uri + "?" + toQueryString(params)).post(body); + } else { + builder = new Request.Builder().url(API_URL + uri + "?" + toQueryString(params)).get(); + } + if (this.assetPassword != null) { + builder.addHeader("AuthData", authData()); + } + Request request = builder.build(); + Response response = client.newCall(request).execute(); + String s = response.body().string(); + return s; + } catch (IOException e) { + throw new ApiException(e); + } + } + + String authData() { + MessageDigest md = null; + try { + md = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + md.update(this.assetPassword.getBytes(StandardCharsets.UTF_8)); + md.update("hello, moto".getBytes(StandardCharsets.UTF_8)); + Map map = new HashMap<>(); + map.put("assetPwd", DatatypeConverter.printHexBinary(md.digest()).toLowerCase()); + try { + return ApiSignature.urlEncode(JsonUtil.writeValue(map)); + } catch (IOException e) { + throw new RuntimeException("Get json failed: " + e.getMessage()); + } + } + + // Encode as "a=1&b=%20&c=&d=AAA" + String toQueryString(Map params) { + return String.join("&", params.entrySet().stream().map((entry) -> { + return entry.getKey() + "=" + ApiSignature.urlEncode(entry.getValue()); + }).collect(Collectors.toList())); + } + + // create OkHttpClient: + static OkHttpClient createOkHttpClient() { + return new Builder().connectTimeout(CONN_TIMEOUT, TimeUnit.SECONDS) + .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS).writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) + .build(); + } + + static String getHost() { + String host = null; + try { + host = new URL(API_URL).getHost(); + } catch (MalformedURLException e) { + System.err.println("parse API_URL error,system exit!,please check API_URL:" + API_URL ); + System.exit(0); + } + return host; + } + +} + + +/** + * API signature, signature specification: + *

+ * http://docs.aws.amazon.com/zh_cn/general/latest/gr/signature-version-2.html + * + * @Date 2018/1/14 + * @Time 16:02 + */ +class ApiSignature { + + final Logger log = LoggerFactory.getLogger(getClass()); + + static final DateTimeFormatter DT_FORMAT = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss"); + static final ZoneId ZONE_GMT = ZoneId.of("Z"); + + /** + * Create a valid signature. This method is a client call, and AccessKeyId, Timestamp, SignatureVersion, SignatureMethod, Signature parameters will be added to the incoming params. + * + * @param appKey AppKeyId. + * @param appSecretKey AppKeySecret. + * @param method Request method, "GET" or "POST" + * @param host Request domain name, for example "be.huobi.com" + * @param uri Request path, note no? And the parameters after that, such as "/v1/ API /info" + * @param params The original request parameter is stored as key-value. Note that Value should not be encoded + */ + public void createSignature(String appKey, String appSecretKey, String method, String host, + String uri, Map params) { + StringBuilder sb = new StringBuilder(1024); + sb.append(method.toUpperCase()).append('\n') // GET + .append(host.toLowerCase()).append('\n') // Host + .append(uri).append('\n'); // /path + params.remove("Signature"); + params.put("AccessKeyId", appKey); + params.put("SignatureVersion", "2"); + params.put("SignatureMethod", "HmacSHA256"); + params.put("Timestamp", gmtNow()); + // build signature: + SortedMap map = new TreeMap<>(params); + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + sb.append(key).append('=').append(urlEncode(value)).append('&'); + } + // remove last '&': + sb.deleteCharAt(sb.length() - 1); + // sign: + Mac hmacSha256 = null; + try { + hmacSha256 = Mac.getInstance("HmacSHA256"); + SecretKeySpec secKey = + new SecretKeySpec(appSecretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); + hmacSha256.init(secKey); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("No such algorithm: " + e.getMessage()); + } catch (InvalidKeyException e) { + throw new RuntimeException("Invalid key: " + e.getMessage()); + } + String payload = sb.toString(); + byte[] hash = hmacSha256.doFinal(payload.getBytes(StandardCharsets.UTF_8)); + String actualSign = Base64.getEncoder().encodeToString(hash); + params.put("Signature", actualSign); + + if (log.isDebugEnabled()) { + log.debug("Dump parameters:"); + for (Map.Entry entry : params.entrySet()) { + log.debug(" key: " + entry.getKey() + ", value: " + entry.getValue()); + } + } + } + + + /** + * Use the standard URL Encode encoding. Note that, unlike the JDK default, Spaces are encoded as %20 instead of +. + * + * @param s String + * @return Url-encoded string + */ + public static String urlEncode(String s) { + try { + return URLEncoder.encode(s, "UTF-8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + throw new IllegalArgumentException("UTF-8 encoding not supported!"); + } + } + + /** + * Return epoch seconds + */ + long epochNow() { + return Instant.now().getEpochSecond(); + } + + String gmtNow() { + return Instant.ofEpochSecond(epochNow()).atZone(ZONE_GMT).format(DT_FORMAT); + } +} + +/*class JsonUtil { + + public static String writeValue(Object obj) throws IOException { + return objectMapper.writeValueAsString(obj); + } + + public static T readValue(String s, TypeReference ref) throws IOException { + return objectMapper.readValue(s, ref); + } + + static final ObjectMapper objectMapper = createObjectMapper(); + + static ObjectMapper createObjectMapper() { + final ObjectMapper mapper = new ObjectMapper(); + mapper.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE); + mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); + // disabled features: + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + return mapper; + } + +}*/ diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/api/ApiException.java b/NestEatOffer/src/main/java/com/nest/ib/utils/api/ApiException.java new file mode 100644 index 0000000..40aaaad --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/api/ApiException.java @@ -0,0 +1,28 @@ +package com.nest.ib.utils.api; + +/** + * ApiException if api returns error. + * + * @Date 2018/1/14 + * @Time 16:02 + */ + +public class ApiException extends RuntimeException { + + final String errCode; + + public ApiException(String errCode, String errMsg) { + super(errMsg); + this.errCode = errCode; + } + + public ApiException(Exception e) { + super(e); + this.errCode = e.getClass().getName(); + } + + public String getErrCode() { + return this.errCode; + } + +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/api/JsonUtil.java b/NestEatOffer/src/main/java/com/nest/ib/utils/api/JsonUtil.java new file mode 100644 index 0000000..214be23 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/api/JsonUtil.java @@ -0,0 +1,39 @@ +package com.nest.ib.utils.api; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.PropertyNamingStrategy; +import com.fasterxml.jackson.databind.SerializationFeature; + +import java.io.IOException; + +public class JsonUtil { + + + public static String writeValue(Object obj) throws IOException { + return objectMapper.writeValueAsString(obj); + } + + public static T readValue(String s, TypeReference ref) throws IOException { + return objectMapper.readValue(s, ref); + } + + public static T readValue(String s, Class valueType) throws IOException { + return objectMapper.readValue(s, valueType); + } + + static final ObjectMapper objectMapper = createObjectMapper(); + + static ObjectMapper createObjectMapper() { + final ObjectMapper mapper = new ObjectMapper(); + mapper.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE); + mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); + // disabled features: + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + return mapper; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/request/CreateOrderRequest.java b/NestEatOffer/src/main/java/com/nest/ib/utils/request/CreateOrderRequest.java new file mode 100644 index 0000000..e7df529 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/request/CreateOrderRequest.java @@ -0,0 +1,57 @@ +package com.nest.ib.utils.request; + +public class CreateOrderRequest { + public static interface OrderType { + /** + * Price to buy + */ + static final String BUY_LIMIT = "buy-limit"; + + /** + * Price to sell + */ + static final String SELL_LIMIT = "sell-limit"; + + /** + * The market price to buy + */ + static final String BUY_MARKET = "buy-market"; + + /** + * The market price to sell + */ + static final String SELL_MARKET = "sell-market"; + } + + /** + * Trade pairs, mandatory, e.g. "ethcny" + */ + public String symbol; + + /** + * Account ID, required, e.g. "12345" + */ + public String accountId; + + /** + * When the order type is buy-limit and sell-limit, it represents the order quantity; + * when the order type is buy-market, it represents the total amount of the order; + * and when the order type is sell-market, it represents the total amount of the order + */ + public String amount; + + /** + * Order price, valid for limit order only, e.g. "1234.56" + */ + public String price = "0.0"; + + /** + * Order type,sell-market,buy-limit,sell-limit + */ + public String type; + + /** + * Order source, for example: "API" + */ + public String source = "com/huobi/api"; +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/request/DepthRequest.java b/NestEatOffer/src/main/java/com/nest/ib/utils/request/DepthRequest.java new file mode 100644 index 0000000..9856749 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/request/DepthRequest.java @@ -0,0 +1,32 @@ +package com.nest.ib.utils.request; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 14:39 + */ + +public class DepthRequest { + + // Trading on + public String symbol; + + // Depth: step0, step1, step2, step3, step4, step5(合并深度0-5);step0时,不合并深度 + public String type; + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/request/IntrustOrdersDetailRequest.java b/NestEatOffer/src/main/java/com/nest/ib/utils/request/IntrustOrdersDetailRequest.java new file mode 100644 index 0000000..aacf323 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/request/IntrustOrdersDetailRequest.java @@ -0,0 +1,73 @@ +package com.nest.ib.utils.request; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 19:08 + */ + +public class IntrustOrdersDetailRequest { + + public static interface OrderType { + /** + * Price to buy + */ + static final String BUY_LIMIT = "buy-limit"; + + /** + * Price to sell + */ + static final String SELL_LIMIT = "sell-limit"; + + /** + * The market price to buy + */ + static final String BUY_MARKET = "buy-market"; + + /** + * The market price to sell + */ + static final String SELL_MARKET = "sell-market"; + } + + public static interface OrderStates { + /** + * pre-submitted + */ + static final String PRE_SUBMITTED = "pre-submitted"; + + /** + * submitted + */ + static final String SUBMITTED = "submitted"; + + /** + * partial-filled + */ + static final String PARTIAL_FILLED = "partial-filled"; + + /** + * partial-canceled + */ + static final String PARTIAL_CANCELED = "partial-canceled"; + + /** + * filled + */ + static final String FILLED = "filled"; + + /** + * canceled + */ + static final String CANCELED = "canceled"; + } + + public String symbol; //true string Trading on btcusdt, bccbtc, rcneth ... + public String types; //false string Query the order type combination, using ',' split + public String startDate; //false string 查Query start date, date format yyyy-mm-dd + public String endDate; //false string Query end date, date format yyyy-mm-dd + public String states; //true string Query the order status combination, using ',' split + public String from; //false string Query start ID + public String direct; //false string The query direction is prev forward and Next backward + public String size; //false string Query record size +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/Account.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Account.java new file mode 100644 index 0000000..2eb9cd9 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Account.java @@ -0,0 +1,12 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 16:02 + */ +public class Account { + public long id; + public String type; + public String state; +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/Accounts.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Accounts.java new file mode 100644 index 0000000..64bf674 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Accounts.java @@ -0,0 +1,53 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 16:02 + */ + +public class Accounts { + /** + * id : 100009 + * type : spot + * state : working + * user-id : 1000 + */ + + private int id; + private String type; + private String state; + private int userid; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public int getUserid() { + return userid; + } + + public void setUserid(int userid) { + this.userid = userid; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/AccountsResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/AccountsResponse.java new file mode 100644 index 0000000..84b62af --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/AccountsResponse.java @@ -0,0 +1,62 @@ +package com.nest.ib.utils.response; + + +import com.nest.ib.utils.api.ApiException; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 16:01 + */ + +public class AccountsResponse { + + /** + * status : ok + * data : [{"id":100009,"type":"spot","state":"working","user-id":1000}] + */ + + private String status; + public String errCode; + public String errMsg; + private T data; + + public T checkAndReturn() { + if ("ok".equals(status)) { + return data; + } + throw new ApiException(errCode, errMsg); + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/ApiResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/ApiResponse.java new file mode 100644 index 0000000..f608f94 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/ApiResponse.java @@ -0,0 +1,19 @@ +package com.nest.ib.utils.response; + + +import com.nest.ib.utils.api.ApiException; + +public class ApiResponse { + + public String status; + public String errCode; + public String errMsg; + public T data; + + public T checkAndReturn() { + if ("ok".equals(status)) { + return data; + } + throw new ApiException(errCode, errMsg); + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/Balance.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Balance.java new file mode 100644 index 0000000..b69bf12 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Balance.java @@ -0,0 +1,63 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 16:15 + */ + +public class Balance { + /** + * id : 100009 + * type : spot + * state : working + * list : [{"currency":"usdt","type":"trade","balance":"500009195917.4362872650"}] + * user-id : 1000 + */ + + private String id; + private String type; + private String state; + private String userid; + private T list; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getUserid() { + return userid; + } + + public void setUserid(String userid) { + this.userid = userid; + } + + public T getList() { + return list; + } + + public void setList(T list) { + this.list = list; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/BalanceBean.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/BalanceBean.java new file mode 100644 index 0000000..8b1740e --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/BalanceBean.java @@ -0,0 +1,43 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 16:23 + */ + +public class BalanceBean { + /** + * currency : usdt + * type : trade + * balance : 500009195917.4362872650 + */ + + private String currency; + private String type; + private String balance; + + public String getCurrency() { + return currency; + } + + public void setCurrency(String currency) { + this.currency = currency; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getBalance() { + return balance; + } + + public void setBalance(String balance) { + this.balance = balance; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/BalanceResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/BalanceResponse.java new file mode 100644 index 0000000..f7e9295 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/BalanceResponse.java @@ -0,0 +1,63 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 16:11 + */ + +public class BalanceResponse { + + + /** + * status : ok + * data : {"id":"100009","type":"spot","state":"working","list":[{"currency":"usdt","type":"trade","balance":"500009195917.4362872650"}],"user-id":"1000"} + */ + + private String status; + public String errCode; + public String errMsg; + private T data; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } + + @Override + public String toString() { + return "BalanceResponse{" + + "status='" + status + '\'' + + ", errCode='" + errCode + '\'' + + ", errMsg='" + errMsg + '\'' + + ", data=" + data + + '}'; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/Batchcancel.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Batchcancel.java new file mode 100644 index 0000000..5c310dc --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Batchcancel.java @@ -0,0 +1,28 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 17:52 + */ + +public class Batchcancel { + private T1 success; + private T2 failed; + + public T1 getSuccess() { + return success; + } + + public void setSuccess(T1 success) { + this.success = success; + } + + public T2 getFailed() { + return failed; + } + + public void setFailed(T2 failed) { + this.failed = failed; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/BatchcancelBean.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/BatchcancelBean.java new file mode 100644 index 0000000..a525f7a --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/BatchcancelBean.java @@ -0,0 +1,34 @@ +package com.nest.ib.utils.response; + +/** @Author ISME @Date 2018/1/14 @Time 17:53 */ +public class BatchcancelBean { + /** err-msg : Record is invalid order-id : 2 err-code : base-record-invalid */ + private String errMsg; + + private String orderId; + private String errCode; + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/BatchcancelResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/BatchcancelResponse.java new file mode 100644 index 0000000..0e1dd5a --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/BatchcancelResponse.java @@ -0,0 +1,53 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 17:51 + */ + +public class BatchcancelResponse { + + + /** + * status : ok + * data : {"success":["1","3"],"failed":[{"err-msg":"记录无效","order-id":"2","err-code":"base-record-invalid"}]} + */ + + private String status; + public String errCode; + public String errMsg; + private T data; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/Currencys.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Currencys.java new file mode 100644 index 0000000..e0b0334 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Currencys.java @@ -0,0 +1,10 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 15:47 + */ + +public class Currencys { +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/CurrencysResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/CurrencysResponse.java new file mode 100644 index 0000000..596e2d3 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/CurrencysResponse.java @@ -0,0 +1,55 @@ +package com.nest.ib.utils.response; + +import java.util.List; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 15:46 + */ + +public class CurrencysResponse { + + + /** + * status : ok + * data : ["usdt","eth","etc"] + */ + + private String status; + public String errCode; + public String errMsg; + private List data; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public List getData() { + return data; + } + + public void setData(List data) { + this.data = data; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/DepositAddressBean.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/DepositAddressBean.java new file mode 100644 index 0000000..cefb936 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/DepositAddressBean.java @@ -0,0 +1,45 @@ +package com.nest.ib.utils.response; + +/** + * ClassName:DepositAddressBean + * Description: + */ +public class DepositAddressBean { + + private String currency; + private String address; + private String addressTag; + private String chain; + + public String getCurrency() { + return currency; + } + + public void setCurrency(String currency) { + this.currency = currency; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getAddressTag() { + return addressTag; + } + + public void setAddressTag(String addressTag) { + this.addressTag = addressTag; + } + + public String getChain() { + return chain; + } + + public void setChain(String chain) { + this.chain = chain; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/DepositAddressResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/DepositAddressResponse.java new file mode 100644 index 0000000..9076849 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/DepositAddressResponse.java @@ -0,0 +1,37 @@ +package com.nest.ib.utils.response; + +import java.util.List; + +/** + * ClassName:DepositAddressResponse + * Description: + */ +public class DepositAddressResponse { + private int code; + private String message; + private List data; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public List getData() { + return data; + } + + public void setData(List data) { + this.data = data; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/Depth.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Depth.java new file mode 100644 index 0000000..bfcff2d --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Depth.java @@ -0,0 +1,57 @@ +package com.nest.ib.utils.response; + +import java.math.BigDecimal; +import java.util.List; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 14:39 + */ + +public class Depth { + + /** + * id : 1489464585407 + * ts : 1489464585407 + * bids : [[7964,0.0678],[7963,0.9162]] + * asks : [[7979,0.0736],[8020,13.6584]] + */ + + private String id; + private String ts; + private List> bids; + private List> asks; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTs() { + return ts; + } + + public void setTs(String ts) { + this.ts = ts; + } + + public List> getBids() { + return bids; + } + + public void setBids(List> bids) { + this.bids = bids; + } + + public List> getAsks() { + return asks; + } + + public void setAsks(List> asks) { + this.asks = asks; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/DepthResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/DepthResponse.java new file mode 100644 index 0000000..cb9d268 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/DepthResponse.java @@ -0,0 +1,84 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 14:38 + */ + +public class DepthResponse { + + + /** + * status : ok + * ch : market.btcusdt.depth.step1 + * ts : 1489472598812 + * tick : {"id":"1489464585407","ts":"1489464585407","bids":[[7964,0.0678],[7963,0.9162]],"asks":[[7979,0.0736],[8020,13.6584]]} + */ + + private String status; + private String ch; + private String ts; + public String errCode; + public String errMsg; + + /** + * tick instructions: + * "tick": { + * "id": Message id, + * "ts": Message generation time, in milliseconds, + * "bids": Buying,[price, amount], in descending order of price, + * "asks": To sell,[price, amount], in ascending order of price + * } + */ + private Depth tick; + + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCh() { + return ch; + } + + public void setCh(String ch) { + this.ch = ch; + } + + public String getTs() { + return ts; + } + + public void setTs(String ts) { + this.ts = ts; + } + + public Depth getTick() { + return tick; + } + + public void setTick(Depth tick) { + this.tick = tick; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/DetailResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/DetailResponse.java new file mode 100644 index 0000000..503c74e --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/DetailResponse.java @@ -0,0 +1,73 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 15:31 + */ + +public class DetailResponse { + + + /** + * status : ok + * ch : market.btcusdt.detail + * ts : 1489473538996 + * tick : {"amount":4316.4346,"open":8090.54,"close":7962.62,"high":8119,"ts":1489464451000,"id":1489464451,"count":9595,"low":7875,"vol":3.449727690576E7} + */ + + private String status; + private String ch; + private long ts; + public String errCode; + public String errMsg; + private T tick; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCh() { + return ch; + } + + public void setCh(String ch) { + this.ch = ch; + } + + public long getTs() { + return ts; + } + + public void setTs(long ts) { + this.ts = ts; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } + + public T getTick() { + return tick; + } + + public void setTick(T tick) { + this.tick = tick; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/Details.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Details.java new file mode 100644 index 0000000..a6e96eb --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Details.java @@ -0,0 +1,104 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 15:33 + */ + +public class Details { + + /** + * amount : 4316.4346 + * open : 8090.54 + * close : 7962.62 + * high : 8119 + * ts : 1489464451000 + * id : 1489464451 + * count : 9595 + * low : 7875 + * vol : 3.449727690576E7 + */ + + private double amount; + private double open; + private double close; + private int high; + private long ts; + private long id; + private int count; + private int low; + private double vol; + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } + + public double getOpen() { + return open; + } + + public void setOpen(double open) { + this.open = open; + } + + public double getClose() { + return close; + } + + public void setClose(double close) { + this.close = close; + } + + public int getHigh() { + return high; + } + + public void setHigh(int high) { + this.high = high; + } + + public long getTs() { + return ts; + } + + public void setTs(long ts) { + this.ts = ts; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + public int getLow() { + return low; + } + + public void setLow(int low) { + this.low = low; + } + + public double getVol() { + return vol; + } + + public void setVol(double vol) { + this.vol = vol; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractERC20Response.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractERC20Response.java new file mode 100644 index 0000000..c655120 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractERC20Response.java @@ -0,0 +1,17 @@ +package com.nest.ib.utils.response; + +/** + * ClassName:ExtractERC20Response + * Description: + */ +public class ExtractERC20Response { + private long data; + + public long getData() { + return data; + } + + public void setData(long data) { + this.data = data; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractQuotaBean.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractQuotaBean.java new file mode 100644 index 0000000..d25463b --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractQuotaBean.java @@ -0,0 +1,28 @@ +package com.nest.ib.utils.response; + +import java.io.Serializable; + +/** + * ClassName:ExtractQuotaBean + * Description: + */ +public class ExtractQuotaBean implements Serializable { + private String currency; + private T chains; + + public String getCurrency() { + return currency; + } + + public void setCurrency(String currency) { + this.currency = currency; + } + + public T getChains() { + return chains; + } + + public void setChains(T chains) { + this.chains = chains; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractQuotaChains.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractQuotaChains.java new file mode 100644 index 0000000..229a82f --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractQuotaChains.java @@ -0,0 +1,96 @@ +package com.nest.ib.utils.response; + +import java.io.Serializable; + +/** + * ClassName:ExtractQuotaChains + * Description: + */ +public class ExtractQuotaChains implements Serializable { + private String chain; // The name of the chain + private String maxWithdrawAmt; // Maximum withdrawal amount at one time + private String withdrawQuotaPerDay; // Daily withdrawal limit + private String remainWithdrawQuotaPerDay; // The amount remaining on the day of withdrawal + private String withdrawQuotaPerYear; // Current withdrawal limit + private String remainWithdrawQuotaPerYear; // The amount remaining in the year of withdrawal + private String withdrawQuotaTotal; // Total withdrawal limit + private String remainWithdrawQuotaTotal; // Total withdrawal amount remaining + + public String getChain() { + return chain; + } + + public void setChain(String chain) { + this.chain = chain; + } + + public String getMaxWithdrawAmt() { + return maxWithdrawAmt; + } + + public void setMaxWithdrawAmt(String maxWithdrawAmt) { + this.maxWithdrawAmt = maxWithdrawAmt; + } + + public String getWithdrawQuotaPerDay() { + return withdrawQuotaPerDay; + } + + public void setWithdrawQuotaPerDay(String withdrawQuotaPerDay) { + this.withdrawQuotaPerDay = withdrawQuotaPerDay; + } + + public String getRemainWithdrawQuotaPerDay() { + return remainWithdrawQuotaPerDay; + } + + public void setRemainWithdrawQuotaPerDay(String remainWithdrawQuotaPerDay) { + this.remainWithdrawQuotaPerDay = remainWithdrawQuotaPerDay; + } + + public String getWithdrawQuotaPerYear() { + return withdrawQuotaPerYear; + } + + public void setWithdrawQuotaPerYear(String withdrawQuotaPerYear) { + this.withdrawQuotaPerYear = withdrawQuotaPerYear; + } + + public String getRemainWithdrawQuotaPerYear() { + return remainWithdrawQuotaPerYear; + } + + public void setRemainWithdrawQuotaPerYear(String remainWithdrawQuotaPerYear) { + this.remainWithdrawQuotaPerYear = remainWithdrawQuotaPerYear; + } + + public String getWithdrawQuotaTotal() { + return withdrawQuotaTotal; + } + + public void setWithdrawQuotaTotal(String withdrawQuotaTotal) { + this.withdrawQuotaTotal = withdrawQuotaTotal; + } + + public String getRemainWithdrawQuotaTotal() { + return remainWithdrawQuotaTotal; + } + + public void setRemainWithdrawQuotaTotal(String remainWithdrawQuotaTotal) { + this.remainWithdrawQuotaTotal = remainWithdrawQuotaTotal; + } + + @Override + public String toString() { + return "ExtractQuotaChains{" + + "chain='" + chain + '\'' + + ", maxWithdrawAmt='" + maxWithdrawAmt + '\'' + + ", withdrawQuotaPerDay='" + withdrawQuotaPerDay + '\'' + + ", remainWithdrawQuotaPerDay='" + remainWithdrawQuotaPerDay + '\'' + + ", withdrawQuotaPerYear='" + withdrawQuotaPerYear + '\'' + + ", remainWithdrawQuotaPerYear='" + remainWithdrawQuotaPerYear + '\'' + + ", withdrawQuotaTotal='" + withdrawQuotaTotal + '\'' + + ", remainWithdrawQuotaTotal='" + remainWithdrawQuotaTotal + '\'' + + '}'; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractQuotaResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractQuotaResponse.java new file mode 100644 index 0000000..3a9b6f5 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/ExtractQuotaResponse.java @@ -0,0 +1,28 @@ +package com.nest.ib.utils.response; + +import java.io.Serializable; + +/** + * ClassName:ExtractQuotaResponse + * Description: + */ +public class ExtractQuotaResponse implements Serializable { + private int code; + private T data; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/HistoryTrade.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/HistoryTrade.java new file mode 100644 index 0000000..082d29e --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/HistoryTrade.java @@ -0,0 +1,63 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 15:24 + */ + +public class HistoryTrade { + /** + * id : 17592256642623 + * amount : 0.04 + * price : 1997 + * direction : buy + * ts : 1502448920106 + */ + + private long id; + private double amount; + private int price; + private String direction; + private long ts; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } + + public int getPrice() { + return price; + } + + public void setPrice(int price) { + this.price = price; + } + + public String getDirection() { + return direction; + } + + public void setDirection(String direction) { + this.direction = direction; + } + + public long getTs() { + return ts; + } + + public void setTs(long ts) { + this.ts = ts; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/HistoryTradeResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/HistoryTradeResponse.java new file mode 100644 index 0000000..607cda2 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/HistoryTradeResponse.java @@ -0,0 +1,73 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 15:22 + */ + +public class HistoryTradeResponse { + + + /** + * status : ok + * ch : market.ethusdt.trade.detail + * ts : 1502448925216 + * data : [{"id":31459998,"ts":1502448920106,"data":[{"id":17592256642623,"amount":0.04,"price":1997,"direction":"buy","ts":1502448920106}]}] + */ + + private String status; + private String ch; + private long ts; + public String errCode; + public String errMsg; + private T data; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCh() { + return ch; + } + + public void setCh(String ch) { + this.ch = ch; + } + + public long getTs() { + return ts; + } + + public void setTs(long ts) { + this.ts = ts; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/HistoryTradess.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/HistoryTradess.java new file mode 100644 index 0000000..14df059 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/HistoryTradess.java @@ -0,0 +1,43 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 15:25 + */ + +public class HistoryTradess { + /** + * id : 31459998 + * ts : 1502448920106 + * data : [{"id":17592256642623,"amount":0.04,"price":1997,"direction":"buy","ts":1502448920106}] + */ + + private long id; + private long ts; + private HistoryTrade data; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public long getTs() { + return ts; + } + + public void setTs(long ts) { + this.ts = ts; + } + + public HistoryTrade getData() { + return data; + } + + public void setData(HistoryTrade data) { + this.data = data; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/IntrustDetail.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/IntrustDetail.java new file mode 100644 index 0000000..73f6aa6 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/IntrustDetail.java @@ -0,0 +1,194 @@ +package com.nest.ib.utils.response; + +import com.google.gson.annotations.SerializedName; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 19:20 + */ + +public class IntrustDetail { + + /** + * id : 59378 + * symbol : ethusdt + * account-id : 100009 + * amount : 10.1000000000 + * price : 100.1000000000 + * created-at : 1494901162595 + * type : buy-limit + * field-amount : 10.1000000000 + * field-cash-amount : 1011.0100000000 + * field-fees : 0.0202000000 + * finished-at : 1494901400468 + * user-id : 1000 + * source : api + * state : filled + * canceled-at : 0 + * exchange : huobi + * batch : + */ + + private long id; + private String symbol; + @SerializedName("account-id") + private int accountid; + private String amount; + private String price; + @SerializedName("created-at") + private long createdat; + private String type; + @SerializedName("field-amount") + private String fieldamount; + @SerializedName("field-cash-amount") + private String fieldcashamount; + @SerializedName("field-fees") + private String fieldfees; + @SerializedName("finished-at") + private long finishedat; + @SerializedName("user-id") + private int userid; + private String source; + private String state; + @SerializedName("canceled-at") + private int canceledat; + private String exchange; + private String batch; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public int getAccountid() { + return accountid; + } + + public void setAccountid(int accountid) { + this.accountid = accountid; + } + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public long getCreatedat() { + return createdat; + } + + public void setCreatedat(long createdat) { + this.createdat = createdat; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getFieldamount() { + return fieldamount; + } + + public void setFieldamount(String fieldamount) { + this.fieldamount = fieldamount; + } + + public String getFieldcashamount() { + return fieldcashamount; + } + + public void setFieldcashamount(String fieldcashamount) { + this.fieldcashamount = fieldcashamount; + } + + public String getFieldfees() { + return fieldfees; + } + + public void setFieldfees(String fieldfees) { + this.fieldfees = fieldfees; + } + + public long getFinishedat() { + return finishedat; + } + + public void setFinishedat(long finishedat) { + this.finishedat = finishedat; + } + + public int getUserid() { + return userid; + } + + public void setUserid(int userid) { + this.userid = userid; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public int getCanceledat() { + return canceledat; + } + + public void setCanceledat(int canceledat) { + this.canceledat = canceledat; + } + + public String getExchange() { + return exchange; + } + + public void setExchange(String exchange) { + this.exchange = exchange; + } + + public String getBatch() { + return batch; + } + + public void setBatch(String batch) { + this.batch = batch; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/IntrustDetailResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/IntrustDetailResponse.java new file mode 100644 index 0000000..cb8744f --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/IntrustDetailResponse.java @@ -0,0 +1,53 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 19:08 + */ + +public class IntrustDetailResponse { + + + /** + * status : ok + * data : [{"id":59378,"symbol":"ethusdt","account-id":100009,"amount":"10.1000000000","price":"100.1000000000","created-at":1494901162595,"type":"buy-limit","field-amount":"10.1000000000","field-cash-amount":"1011.0100000000","field-fees":"0.0202000000","finished-at":1494901400468,"user-id":1000,"source":"api","state":"filled","canceled-at":0,"exchange":"huobi","batch":""}] + */ + + private String status; + public String errCode; + public String errMsg; + private T data; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/Kline.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Kline.java new file mode 100644 index 0000000..3fe39e2 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Kline.java @@ -0,0 +1,84 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 11:35 + */ + +public class Kline { + + + private long id; + private double amount; + private int count; + private double open; + private double close; + private double low; + private double high; + private double vol; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + public double getOpen() { + return open; + } + + public void setOpen(double open) { + this.open = open; + } + + public double getClose() { + return close; + } + + public void setClose(int close) { + this.close = close; + } + + public double getLow() { + return low; + } + + public void setLow(int low) { + this.low = low; + } + + public double getHigh() { + return high; + } + + public void setHigh(int high) { + this.high = high; + } + + public double getVol() { + return vol; + } + + public void setVol(double vol) { + this.vol = vol; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/KlineResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/KlineResponse.java new file mode 100644 index 0000000..6fef319 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/KlineResponse.java @@ -0,0 +1,51 @@ +package com.nest.ib.utils.response; + +import com.nest.ib.utils.api.ApiException; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 11:56 + */ + +public class KlineResponse { + + private String status; + private String ch; + private String ts; + public String errCode; + public String errMsg; + public T data; + + public T checkAndReturn() { + if ("ok".equals(status)) { + return data; + } + throw new ApiException(errCode, errMsg); + } + + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCh() { + return ch; + } + + public void setCh(String ch) { + this.ch = ch; + } + + public String getTs() { + return ts; + } + + public void setTs(String ts) { + this.ts = ts; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/MatchresultsOrdersDetail.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/MatchresultsOrdersDetail.java new file mode 100644 index 0000000..2598d90 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/MatchresultsOrdersDetail.java @@ -0,0 +1,118 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 18:50 + */ + +public class MatchresultsOrdersDetail { + /** + * id : 29553 + * order-id : 59378 + * match-id : 59335 + * symbol : ethusdt + * type : buy-limit + * source : api + * price : 100.1000000000 + * filled-amount : 9.1155000000 + * filled-fees : 0.0182310000 + * created-at : 1494901400435 + */ + + private long id; + @com.google.gson.annotations.SerializedName("order-id") + private long orderid; + @com.google.gson.annotations.SerializedName("match-id") + private long matchid; + private String symbol; + private String type; + private String source; + private String price; + @com.google.gson.annotations.SerializedName("filled-amount") + private String filledamount; + @com.google.gson.annotations.SerializedName("filled-fees") + private String filledfees; + @com.google.gson.annotations.SerializedName("created-at") + private long createdat; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public long getOrderid() { + return orderid; + } + + public void setOrderid(long orderid) { + this.orderid = orderid; + } + + public long getMatchid() { + return matchid; + } + + public void setMatchid(long matchid) { + this.matchid = matchid; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getFilledamount() { + return filledamount; + } + + public void setFilledamount(String filledamount) { + this.filledamount = filledamount; + } + + public String getFilledfees() { + return filledfees; + } + + public void setFilledfees(String filledfees) { + this.filledfees = filledfees; + } + + public long getCreatedat() { + return createdat; + } + + public void setCreatedat(long createdat) { + this.createdat = createdat; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/MatchresultsOrdersDetailResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/MatchresultsOrdersDetailResponse.java new file mode 100644 index 0000000..f1c3ae8 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/MatchresultsOrdersDetailResponse.java @@ -0,0 +1,53 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 18:48 + */ + +public class MatchresultsOrdersDetailResponse { + + + /** + * status : ok + * data : [{"id":29553,"order-id":59378,"match-id":59335,"symbol":"ethusdt","type":"buy-limit","source":"api","price":"100.1000000000","filled-amount":"9.1155000000","filled-fees":"0.0182310000","created-at":1494901400435}] + */ + + private String status; + public String errCode; + public String errMsg; + private T data; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/Merged.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Merged.java new file mode 100644 index 0000000..ae80e81 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Merged.java @@ -0,0 +1,126 @@ +package com.nest.ib.utils.response; + +import java.util.List; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 14:16 + */ + +public class Merged { + + /** + * id : 1499225271 + * ts : 1499225271000 + * close : 1885 + * open : 1960 + * high : 1985 + * low : 1856 + * amount : 81486.2926 + * count : 42122 + * vol : 1.57052744857082E8 + * ask : [1885,21.8804] + * bid : [1884,1.6702] + */ + + private long id; + private long ts; + private int close; + private int open; + private int high; + private int low; + private double amount; + private int count; + private double vol; + private List ask; + private List bid; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public long getTs() { + return ts; + } + + public void setTs(long ts) { + this.ts = ts; + } + + public int getClose() { + return close; + } + + public void setClose(int close) { + this.close = close; + } + + public int getOpen() { + return open; + } + + public void setOpen(int open) { + this.open = open; + } + + public int getHigh() { + return high; + } + + public void setHigh(int high) { + this.high = high; + } + + public int getLow() { + return low; + } + + public void setLow(int low) { + this.low = low; + } + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + public double getVol() { + return vol; + } + + public void setVol(double vol) { + this.vol = vol; + } + + public List getAsk() { + return ask; + } + + public void setAsk(List ask) { + this.ask = ask; + } + + public List getBid() { + return bid; + } + + public void setBid(List bid) { + this.bid = bid; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/MergedResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/MergedResponse.java new file mode 100644 index 0000000..817bd04 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/MergedResponse.java @@ -0,0 +1,81 @@ +package com.nest.ib.utils.response; + +import com.nest.ib.utils.api.ApiException; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 14:15 + */ + +public class MergedResponse { + + /** + * status : ok + * ch : market.ethusdt.detail.merged + * ts : 1499225276950 + * tick : {"id":1499225271,"ts":1499225271000,"close":1885,"open":1960,"high":1985,"low":1856,"amount":81486.2926,"count":42122,"vol":1.57052744857082E8,"ask":[1885,21.8804],"bid":[1884,1.6702]} + */ + + private String status; + private String ch; + private long ts; + public String errCode; + public String errMsg; + public T data; + + public T checkAndReturn() { + if ("ok".equals(status)) { + return data; + } + throw new ApiException(errCode, errMsg); + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCh() { + return ch; + } + + public void setCh(String ch) { + this.ch = ch; + } + + public long getTs() { + return ts; + } + + public void setTs(long ts) { + this.ts = ts; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/OrdersDetail.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/OrdersDetail.java new file mode 100644 index 0000000..ddfe54e --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/OrdersDetail.java @@ -0,0 +1,184 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 18:22 + */ + +public class OrdersDetail { + + /** + * id : 59378 + * symbol : ethusdt + * account-id : 100009 + * amount : 10.1000000000 + * price : 100.1000000000 + * created-at : 1494901162595 + * type : buy-limit + * field-amount : 10.1000000000 + * field-cash-amount : 1011.0100000000 + * field-fees : 0.0202000000 + * finished-at : 1494901400468 + * user-id : 1000 + * source : api + * state : filled + * canceled-at : 0 + * exchange : huobi + * batch : + */ + + private long id; + private String symbol; + private int accountid; + private String amount; + private String price; + private long createdat; + private String type; + private String fieldamount; + private String fieldcashamount; + private String fieldfees; + private long finishedat; + private int userid; + private String source; + private String state; + private long canceledat; + private String exchange; + private String batch; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public int getAccountid() { + return accountid; + } + + public void setAccountid(int accountid) { + this.accountid = accountid; + } + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public long getCreatedat() { + return createdat; + } + + public void setCreatedat(long createdat) { + this.createdat = createdat; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getFieldamount() { + return fieldamount; + } + + public void setFieldamount(String fieldamount) { + this.fieldamount = fieldamount; + } + + public String getFieldcashamount() { + return fieldcashamount; + } + + public void setFieldcashamount(String fieldcashamount) { + this.fieldcashamount = fieldcashamount; + } + + public String getFieldfees() { + return fieldfees; + } + + public void setFieldfees(String fieldfees) { + this.fieldfees = fieldfees; + } + + public long getFinishedat() { + return finishedat; + } + + public void setFinishedat(long finishedat) { + this.finishedat = finishedat; + } + + public int getUserid() { + return userid; + } + + public void setUserid(int userid) { + this.userid = userid; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public long getCanceledat() { + return canceledat; + } + + public void setCanceledat(long canceledat) { + this.canceledat = canceledat; + } + + public String getExchange() { + return exchange; + } + + public void setExchange(String exchange) { + this.exchange = exchange; + } + + public String getBatch() { + return batch; + } + + public void setBatch(String batch) { + this.batch = batch; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/OrdersDetailResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/OrdersDetailResponse.java new file mode 100644 index 0000000..4f3c62d --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/OrdersDetailResponse.java @@ -0,0 +1,66 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 18:21 + */ + +public class OrdersDetailResponse { + + /** + * status : ok + * data : {"id":59378,"symbol":"ethusdt","account-id":100009,"amount":"10.1000000000","price":"100.1000000000","created-at":1494901162595,"type":"buy-limit","field-amount":"10.1000000000","field-cash-amount":"1011.0100000000","field-fees":"0.0202000000","finished-at":1494901400468,"user-id":1000,"source":"api","state":"filled","canceled-at":0,"exchange":"huobi","batch":""} + */ + + private String status; + public String errCode; + public String errMsg; + private T data; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public static class DataBean { + + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } + + @Override + public String toString() { + return "OrdersDetailResponse{" + + "status='" + status + '\'' + + ", errCode='" + errCode + '\'' + + ", errMsg='" + errMsg + '\'' + + ", data=" + data + + '}'; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/Place.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Place.java new file mode 100644 index 0000000..5fe1352 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Place.java @@ -0,0 +1,10 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 17:10 + */ + +public class Place { +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/QueryExtractServiceChargeChains.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/QueryExtractServiceChargeChains.java new file mode 100644 index 0000000..37e978d --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/QueryExtractServiceChargeChains.java @@ -0,0 +1,170 @@ +package com.nest.ib.utils.response; + +/** + * ClassName:QueryExtractServiceChargeChains + * Description: + */ +public class QueryExtractServiceChargeChains { + private String chain; // The name of the chain + private String depositStatus; // State of charge money + private String maxTransactFeeWithdraw; // Largest single mention money handling charge (cap is only for the interval type and the proportion of type, effective withdrawFeeType = circulated or thewire) + private String maxWithdrawAmt; // Maximum withdrawal amount at one time + private String minDepositAmt; // Minimum charge amount per time + private String transactFeeWithdraw; // A single withdrawing fee (valid only for a fixed type, feeType =fixed) + private String minTransactFeeWithdraw; // Minimum single mention money handling charge (only the interval type, effective withdrawFeeType = circulated) + private String transactFeeRateWithdraw; // A single withdrawing rate (effective only for proportion type, descriptive type =ratio) + private String minWithdrawAmt; // Minimum withdrawal amount per time + private String numOfConfirmations; // Number of confirmations required for safe account Posting (currency withdrawal is allowed after the number of confirmations is reached) + private String numOfFastConfirmations; // The number of confirmations required for rapid account Posting (transactions are allowed after the number of confirmations is reached, but currency withdrawal is not allowed) + private String withdrawFeeType; // Withdrawal fee Type (the unique withdrawal fee type for a specific currency on a specific chain) + private String withdrawPrecision; // Mention money precision + private String withdrawQuotaPerDay; // Daily withdrawal limit + private String withdrawQuotaPerYear; // Current withdrawal limit + private String withdrawQuotaTotal; // Total withdrawal limit + private String withdrawStatus; // Mention currency status + private String instStatus; // State of the currency + + public String getTransactFeeWithdraw() { + return transactFeeWithdraw; + } + + public void setTransactFeeWithdraw(String transactFeeWithdraw) { + this.transactFeeWithdraw = transactFeeWithdraw; + } + + public String getTransactFeeRateWithdraw() { + return transactFeeRateWithdraw; + } + + public void setTransactFeeRateWithdraw(String transactFeeRateWithdraw) { + this.transactFeeRateWithdraw = transactFeeRateWithdraw; + } + + public String getInstStatus() { + return instStatus; + } + + public void setInstStatus(String instStatus) { + this.instStatus = instStatus; + } + + public String getChain() { + return chain; + } + + public void setChain(String chain) { + this.chain = chain; + } + + public String getDepositStatus() { + return depositStatus; + } + + public void setDepositStatus(String depositStatus) { + this.depositStatus = depositStatus; + } + + public String getMaxTransactFeeWithdraw() { + return maxTransactFeeWithdraw; + } + + public void setMaxTransactFeeWithdraw(String maxTransactFeeWithdraw) { + this.maxTransactFeeWithdraw = maxTransactFeeWithdraw; + } + + public String getMaxWithdrawAmt() { + return maxWithdrawAmt; + } + + public void setMaxWithdrawAmt(String maxWithdrawAmt) { + this.maxWithdrawAmt = maxWithdrawAmt; + } + + public String getMinDepositAmt() { + return minDepositAmt; + } + + public void setMinDepositAmt(String minDepositAmt) { + this.minDepositAmt = minDepositAmt; + } + + public String getMinTransactFeeWithdraw() { + return minTransactFeeWithdraw; + } + + public void setMinTransactFeeWithdraw(String minTransactFeeWithdraw) { + this.minTransactFeeWithdraw = minTransactFeeWithdraw; + } + + public String getMinWithdrawAmt() { + return minWithdrawAmt; + } + + public void setMinWithdrawAmt(String minWithdrawAmt) { + this.minWithdrawAmt = minWithdrawAmt; + } + + public String getNumOfConfirmations() { + return numOfConfirmations; + } + + public void setNumOfConfirmations(String numOfConfirmations) { + this.numOfConfirmations = numOfConfirmations; + } + + public String getNumOfFastConfirmations() { + return numOfFastConfirmations; + } + + public void setNumOfFastConfirmations(String numOfFastConfirmations) { + this.numOfFastConfirmations = numOfFastConfirmations; + } + + public String getWithdrawFeeType() { + return withdrawFeeType; + } + + public void setWithdrawFeeType(String withdrawFeeType) { + this.withdrawFeeType = withdrawFeeType; + } + + public String getWithdrawPrecision() { + return withdrawPrecision; + } + + public void setWithdrawPrecision(String withdrawPrecision) { + this.withdrawPrecision = withdrawPrecision; + } + + public String getWithdrawQuotaPerDay() { + return withdrawQuotaPerDay; + } + + public void setWithdrawQuotaPerDay(String withdrawQuotaPerDay) { + this.withdrawQuotaPerDay = withdrawQuotaPerDay; + } + + public String getWithdrawQuotaPerYear() { + return withdrawQuotaPerYear; + } + + public void setWithdrawQuotaPerYear(String withdrawQuotaPerYear) { + this.withdrawQuotaPerYear = withdrawQuotaPerYear; + } + + public String getWithdrawQuotaTotal() { + return withdrawQuotaTotal; + } + + public void setWithdrawQuotaTotal(String withdrawQuotaTotal) { + this.withdrawQuotaTotal = withdrawQuotaTotal; + } + + public String getWithdrawStatus() { + return withdrawStatus; + } + + public void setWithdrawStatus(String withdrawStatus) { + this.withdrawStatus = withdrawStatus; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/QueryExtractServiceChargeData.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/QueryExtractServiceChargeData.java new file mode 100644 index 0000000..5a67db9 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/QueryExtractServiceChargeData.java @@ -0,0 +1,37 @@ +package com.nest.ib.utils.response; + +import java.util.List; + +/** + * ClassName:QueryExtractServiceChargeData + * Description: + */ +public class QueryExtractServiceChargeData { + private List chains; + private String currency; + private String instStatus; + + public List getChains() { + return chains; + } + + public void setChains(List chains) { + this.chains = chains; + } + + public String getCurrency() { + return currency; + } + + public void setCurrency(String currency) { + this.currency = currency; + } + + public String getInstStatus() { + return instStatus; + } + + public void setInstStatus(String instStatus) { + this.instStatus = instStatus; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/QueryExtractServiceChargeResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/QueryExtractServiceChargeResponse.java new file mode 100644 index 0000000..c5cf200 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/QueryExtractServiceChargeResponse.java @@ -0,0 +1,37 @@ +package com.nest.ib.utils.response; + +import java.util.List; + +/** + * ClassName:QueryExtractServiceChargeResponse + * Description: + */ +public class QueryExtractServiceChargeResponse { + private int code; + private String message; + private List data; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public List getData() { + return data; + } + + public void setData(List data) { + this.data = data; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/SubmitcancelResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/SubmitcancelResponse.java new file mode 100644 index 0000000..fcddfb8 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/SubmitcancelResponse.java @@ -0,0 +1,53 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 17:15 + */ + +public class SubmitcancelResponse { + + + /** + * status : ok + * data : 59378 + */ + + private String status; + public String errCode; + public String errMsg; + private String data; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/Symbol.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Symbol.java new file mode 100644 index 0000000..49cf46f --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Symbol.java @@ -0,0 +1,9 @@ +package com.nest.ib.utils.response; + +public class Symbol { + + public String baseCurrency; + public String quoteCurrency; + public String symbol; + +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/Symbols.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Symbols.java new file mode 100644 index 0000000..a1c955e --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Symbols.java @@ -0,0 +1,104 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 15:39 + */ + +public class Symbols { + + /** + * amount : 4316.4346 + * open : 8090.54 + * close : 7962.62 + * high : 8119 + * ts : 1489464451000 + * id : 1489464451 + * count : 9595 + * low : 7875 + * vol : 3.449727690576E7 + */ + + private double amount; + private double open; + private double close; + private int high; + private long ts; + private long id; + private int count; + private int low; + private double vol; + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } + + public double getOpen() { + return open; + } + + public void setOpen(double open) { + this.open = open; + } + + public double getClose() { + return close; + } + + public void setClose(double close) { + this.close = close; + } + + public int getHigh() { + return high; + } + + public void setHigh(int high) { + this.high = high; + } + + public long getTs() { + return ts; + } + + public void setTs(long ts) { + this.ts = ts; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + public int getLow() { + return low; + } + + public void setLow(int low) { + this.low = low; + } + + public double getVol() { + return vol; + } + + public void setVol(double vol) { + this.vol = vol; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/SymbolsResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/SymbolsResponse.java new file mode 100644 index 0000000..81446f1 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/SymbolsResponse.java @@ -0,0 +1,73 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 15:39 + */ + +public class SymbolsResponse { + + + /** + * status : ok + * ch : market.btcusdt.detail + * ts : 1489473538996 + * tick : {"amount":4316.4346,"open":8090.54,"close":7962.62,"high":8119,"ts":1489464451000,"id":1489464451,"count":9595,"low":7875,"vol":3.449727690576E7} + */ + + private String status; + private String ch; + private long ts; + public String errCode; + public String errMsg; + private T tick; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCh() { + return ch; + } + + public void setCh(String ch) { + this.ch = ch; + } + + public long getTs() { + return ts; + } + + public void setTs(long ts) { + this.ts = ts; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } + + public T getTick() { + return tick; + } + + public void setTick(T tick) { + this.tick = tick; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/TimestampResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/TimestampResponse.java new file mode 100644 index 0000000..f5d7952 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/TimestampResponse.java @@ -0,0 +1,44 @@ +package com.nest.ib.utils.response; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 15:53 + */ + +public class TimestampResponse { + + /** + * status : ok + * data : 1494900087029 + */ + + private String status; + private long data; + private String dateTime; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public long getData() { + return data; + } + + public void setData(long data) { + this.data = data; + } + + public String getDateTime() { + SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); + Date date = new Date(data); + return sdf.format(date); + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/Trade.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Trade.java new file mode 100644 index 0000000..e77e989 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/Trade.java @@ -0,0 +1,44 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 14:52 + */ + +public class Trade { + + /** + * id : 600848670 + * ts : 1489464451000 + * data : [{"id":600848670,"price":7962.62,"amount":0.0122,"direction":"buy","ts":1489464451000}] + */ + + private long id; + private long ts; + private T data; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public long getTs() { + return ts; + } + + public void setTs(long ts) { + this.ts = ts; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/TradeBean.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/TradeBean.java new file mode 100644 index 0000000..4cf1d1b --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/TradeBean.java @@ -0,0 +1,66 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 14:57 + */ + +public class TradeBean { + + /** + * id : 600848670 + * price : 7962.62 + * amount : 0.0122 + * direction : buy + * ts : 1489464451000 + */ + + private long id; + private double price; + private double amount; + private String direction; + private long ts; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } + + public String getDirection() { + return direction; + } + + public void setDirection(String direction) { + this.direction = direction; + } + + public long getTs() { + return ts; + } + + public void setTs(long ts) { + this.ts = ts; + } + + +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/utils/response/TradeResponse.java b/NestEatOffer/src/main/java/com/nest/ib/utils/response/TradeResponse.java new file mode 100644 index 0000000..ad596ee --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/utils/response/TradeResponse.java @@ -0,0 +1,73 @@ +package com.nest.ib.utils.response; + +/** + * @Author ISME + * @Date 2018/1/14 + * @Time 14:52 + */ + +public class TradeResponse { + + + /** + * status : ok + * ch : market.btcusdt.trade.detail + * ts : 1489473346905 + * tick : {"id":600848670,"ts":1489464451000,"data":[{"id":600848670,"price":7962.62,"amount":0.0122,"direction":"buy","ts":1489464451000}]} + */ + + private String status; + private String ch; + private long ts; + public String errCode; + public String errMsg; + private Trade tick; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCh() { + return ch; + } + + public void setCh(String ch) { + this.ch = ch; + } + + public long getTs() { + return ts; + } + + public void setTs(long ts) { + this.ts = ts; + } + + public String getErrCode() { + return errCode; + } + + public void setErrCode(String errCode) { + this.errCode = errCode; + } + + public String getErrMsg() { + return errMsg; + } + + public void setErrMsg(String errMsg) { + this.errMsg = errMsg; + } + + public Trade getTick() { + return tick; + } + + public void setTick(Trade tick) { + this.tick = tick; + } +} diff --git a/NestEatOffer/src/main/java/com/nest/ib/vo/ScheduledTask.java b/NestEatOffer/src/main/java/com/nest/ib/vo/ScheduledTask.java new file mode 100644 index 0000000..2036d51 --- /dev/null +++ b/NestEatOffer/src/main/java/com/nest/ib/vo/ScheduledTask.java @@ -0,0 +1,56 @@ +package com.nest.ib.vo; + +import com.nest.ib.service.EatOfferAndTransactionService; + +import com.nest.ib.service.OfferThreeDataService; +import com.nest.ib.service.serviceImpl.EatOfferAndTransactionServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; +import org.springframework.stereotype.Component; + +/** + * ClassName: + * Description: + */ +@Component +public class ScheduledTask { + + @Bean + public TaskScheduler taskScheduler() { + ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); + taskScheduler.setPoolSize(50); + return taskScheduler; + } + + @Autowired + private EatOfferAndTransactionService eatOfferAndTransactionService; + + + /** + * Order quote :3 seconds + */ + @Scheduled(fixedDelay = 3 * 1000) + public void eatOfferContract() { + eatOfferAndTransactionService.eatOffer(); + } + + /** + * Retrieve assets: 2 minutes + */ + @Scheduled(fixedDelay = 2 * 60 * 1000) + public void retrieveAssets() { + eatOfferAndTransactionService.retrieveAssets(); + } + + + /** + * To exchange quoted assets: 10 seconds + */ + @Scheduled(fixedDelay = 10 * 1000) + public void exchangeBuyAndSell() { + eatOfferAndTransactionService.exchangeBuyAndSell(); + } +} diff --git a/NestEatOffer/src/main/resources/application.properties b/NestEatOffer/src/main/resources/application.properties new file mode 100644 index 0000000..4f8d305 --- /dev/null +++ b/NestEatOffer/src/main/resources/application.properties @@ -0,0 +1,9 @@ +server.port=8099 + + +nest.user.name=nest + +nest.user.password=nest + + + diff --git a/NestEatOffer/src/main/resources/log4j2.xml b/NestEatOffer/src/main/resources/log4j2.xml new file mode 100644 index 0000000..ffd36ae --- /dev/null +++ b/NestEatOffer/src/main/resources/log4j2.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NestEatOffer/src/main/resources/templates/eatData.html b/NestEatOffer/src/main/resources/templates/eatData.html new file mode 100644 index 0000000..bf6a96c --- /dev/null +++ b/NestEatOffer/src/main/resources/templates/eatData.html @@ -0,0 +1,283 @@ + + + + + NEST3.0 automatic eat single arbitrage program + + + +

+

NEST3.0 automatic eat single arbitrage program

+
+ +

+

+ +

+ +

+ +

+ +

+ +

+

+ +

+ +

+
+

+ +

+ +

+
+

+ +
+ + +
+ + +
+ + + +
+ + +
+ + + +
+

+ +
+ + +
+

+
+ +

+ +

+ +

+ +

+ +
+ +

+ + + +

+ +
+ + +
+ +
+
+ + + + + + + + diff --git a/NestEatOffer/src/main/resources/templates/error.html b/NestEatOffer/src/main/resources/templates/error.html new file mode 100644 index 0000000..f793115 --- /dev/null +++ b/NestEatOffer/src/main/resources/templates/error.html @@ -0,0 +1,20 @@ + + + + + NEST eats arbitrage + + +

The illegal log in

+ + + + + + + diff --git a/NestEatOffer/src/main/resources/templates/login.html b/NestEatOffer/src/main/resources/templates/login.html new file mode 100644 index 0000000..c60fe2a --- /dev/null +++ b/NestEatOffer/src/main/resources/templates/login.html @@ -0,0 +1,32 @@ + + + + + The user login + + +
+
+ + + + + +
+ +
+ + + + + + + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..defb17a --- /dev/null +++ b/README.md @@ -0,0 +1,98 @@ +### NEST3.0 Automatic order taking arbitrage program operating instructions + +[toc] + +#### Instructions +>The NEST3.0 automatic order taking arbitrage program is an example program. Related parameters such as price deviation percentage, the default value is 2%, which is not necessarily the optimal order taking arbitrage ratio, and users can adjust it according to the actual situation. + +>The exchange trading function is an optional feature. Users can choose whether to enable the exchange trading function. + +>Main functions: + * Check ETH and ERC20 balances + * ERC20 token approve + * Exchange price update and trading(The example exchange is Huobi) + * Take single arbitrage + * Take the return price asset + +#### Preparation before starting + +1. Get ready: wallet private key, Ethereum node URL, ERC20 token contract address, trading pair API. + * Wallet private key: Generated by mnemonic words, and can be registered through nestDapp. + * Ethereum node URL: You can apply for free via https://infura.io. + * If you want to trade on the Huobi Exchange after taking a quote, you need to create an Access Key and a Secret Key in the Huobi Exchange API management, and fill in the withdrawal address in the withdrawal address management. + * ERC20 token contract address: For example, if you quote USDT, you need to fill in the USDT token contract address: 0xdac17f958d2ee523a2206206994597c13d831ec7 + * Huobi trading pair settings: For example, if USDT is quoted, then the trading pair needs to fill in ethusdt. The Huobi trading pair query address is https://api.huobi.pro/v1/common/symbols + + +#### Startup and shutdown + +1. Run the arbitrage program: + * Double-click start.bat under the root path of the take-order arbitrage program to run the take-order arbitrage program, and a window will pop up. Please do not close it. You can view the take-order quotation and retrieve information in the window. + +2. log in: + * The browser enters http://127.0.0.1:8099/eat/eatData, it will enter the login page, the default user name is nest, and the password is nest. + * If you need to modify the password, you can modify the nest.user.name (user name) and nest.user.password (password) in NestEatOffer/src/main/resources/application.properties. + +3. Close the take-and-take arbitrage program: + * Before closing the order-taking arbitrage program, stop order-taking and arbitrage, and then wait 10 minutes, and then close the window after the quoted assets are retrieved. + +#### Related settings + +1. Ethereum node (required): + * The node address must be set first. + +2. Set ERC20 address and Huobi trading pair (required): + * Take arbitrage for ETH/USDT, fill 0xdac17f958d2ee523a2206206994597c13d831ec7 for ERC20 address, fill ethusdt for Huobi trading pair. + * For nToken oracle arbitrage, please fill in the corresponding ERC20 address and Huobi trading pair API. + +3. Deviation percentage (not required): + * The default value is 0.02, that is, when the price deviation exceeds 2%, it will initiate an arbitrage, pay attention to fill in the decimal. + +4. Set the agent address and port (not required): + * The agent address, which defaults to the native address of 127.0.0.1, if a network agent is used, the agent port must be configured. + +5. Set private key (required): + * Fill in the private key, and some initialization work will be performed, such as mapping the address of each contract, obtaining the ERC20 token ID, the number of bits, etc. Please be patient. + +6. Set Huobi API-KEY and API-SECRET (not required): + * If you want to trade on the Huobi Exchange after taking the order quote, please fill in API-KEY and API-SECRET. You can leave it blank if you don’t need to trade. + * Set whether to enable user authentication. If authentication is required, you can authenticate at Huobi Exchange Identity Authentication. + * Start trading on Huobi Exchange. + +7. Open take-order arbitrage: + * After the above configuration is completed, click the Modify Status button to change the order arbitrage status to open. You can view order information, exchange trading information (if exchange trading is enabled) in the background (the window that pops up when you click start.bat). + +#### Test take arbitrage + +```java +1. Notes on the code for arbitrage trading: + +LOG.info("Take orders quotation:take ETH={} take{}={} quoteETH={} quote{}={} payEthAmount={}", + tranEthAmout, SYMBOL, tranErc20Amount, offerEthAmount, SYMBOL, offerErc20Amount, payEthAmount); +// Initiate an arbitrage transaction +String transactionHash = ethClient.sendEatOffer(typeList, payEthAmount, method, gasPrice); + +2. Check the number of quoted ETH and quoted ERC20 in the printed log, and check the data. +``` + +#### Huobi Exchange Opens API-KEY + +1. Log in to the exchange, select API management + + ![](./picture/API-KEY-1.png) + +2. Create API-KEY and open permissions. + + * Accept open "read". For example: other people quote 10ETH: 3000USDT, Huobi exchange real-time price: 10ETH: 2600USDT, then the order will be put into 10ETH, get 3000USDT, then will read the exchange's USDT corresponding deposit address, and deposit 3000USDT Exchange. + * Open "deal". For example: the 3000USDT recharged will be sold at market price, and 3000USDT will be sold to get ETH. + * Open "Withdrawal". For example: Sell 3000USDT to get 11.5ETH, and 11.5ETH will be withdrawn to the current take-order quote wallet address. + + ![](./picture/API-KEY-2.png) + +3. After filling in, click "Create", then it will display: api-key and api-secret. Fill it in the configuration page and click "Submit". + + +#### Contract interaction + +[Contract interaction description](./NestEatOffer/README.md) +