org.fisco.bcos.web3j.protocol.core.DefaultBlockParameterName Java Examples
The following examples show how to use
org.fisco.bcos.web3j.protocol.core.DefaultBlockParameterName.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Contract.java From web3sdk with Apache License 2.0 | 6 votes |
/** * Check that the contract deployed at the address associated with this smart contract wrapper * is in fact the contract you believe it is. * * <p>This method uses the <a href= * "https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode">eth_getCode</a> method to get * the contract byte code and validates it against the byte code stored in this smart contract * wrapper. * * @return true if the contract is valid * @throws IOException if unable to connect to web3j node */ public boolean isValid() throws IOException { if (contractBinary.equals(BIN_NOT_PROVIDED)) { throw new UnsupportedOperationException( "Contract binary not present in contract wrapper, " + "please generate your wrapper using -abiFile=<file>"); } if (contractAddress.equals("")) { throw new UnsupportedOperationException( "Contract binary not present, you will need to regenerate your smart " + "contract wrapper with web3j v2.2.0+"); } Code gcode = web3j.getCode(contractAddress, DefaultBlockParameterName.LATEST).send(); if (gcode.hasError()) { return false; } String code = Numeric.cleanHexPrefix(gcode.getCode()); // There may be multiple contracts in the Solidity bytecode, hence we only // check for a match with a subset return !code.isEmpty() && contractBinary.contains(code); }
Example #2
Source File: TransService.java From WeBASE-Front with Apache License 2.0 | 5 votes |
public Object sendQueryTransaction(String encodeStr, String contractAddress, String funcName, String contractAbi, int groupId, String userAddress) { Web3j web3j = web3ApiService.getWeb3j(groupId); String callOutput ; try { callOutput = web3j.call(Transaction.createEthCallTransaction(userAddress, contractAddress, encodeStr), DefaultBlockParameterName.LATEST) .send().getValue().getOutput(); } catch (IOException e) { throw new FrontException(TRANSACTION_FAILED); } AbiDefinition abiDefinition = getFunctionAbiDefinition(funcName, contractAbi); if (Objects.isNull(abiDefinition)) { throw new FrontException(IN_FUNCTION_ERROR); } List<String> funOutputTypes = AbiUtil.getFuncOutputType(abiDefinition); List<TypeReference<?>> finalOutputs = AbiUtil.outputFormat(funOutputTypes); List<Type> typeList = FunctionReturnDecoder.decode(callOutput, Utils.convert(finalOutputs)); Object response; if (typeList.size() > 0) { response = AbiUtil.callResultParse(funOutputTypes, typeList); } else { response = typeList; } return response; }
Example #3
Source File: CallContract.java From web3sdk with Apache License 2.0 | 5 votes |
public CallResult call(String contractAddress, String funcName, Type... args) { final Function function = new Function( funcName, Arrays.<Type>asList(args), Collections.<TypeReference<?>>emptyList()); String data = FunctionEncoder.encode(function); Call ethCall; try { ethCall = web3j.call( Transaction.createEthCallTransaction( credentials.getAddress(), contractAddress, data), DefaultBlockParameterName.LATEST) .send(); } catch (Exception e) { return new CallResult(StatusCode.ExceptionCatched, e.getMessage(), "0x"); } Call.CallOutput callOutput = ethCall.getValue(); if (callOutput != null) { return new CallResult( callOutput.getStatus(), StatusCode.getStatusMessage(callOutput.getStatus()), callOutput.getOutput()); } else { return new CallResult( StatusCode.ErrorInRPC, StatusCode.getStatusMessage(StatusCode.ErrorInRPC), "0x"); } }
Example #4
Source File: EventLogUserParams.java From web3sdk with Apache License 2.0 | 5 votes |
/** * check if valid fromBlock and toBlock * * @param blockNumber * @return */ private boolean validBlockRange(BigInteger blockNumber) { if (Strings.isEmpty(getFromBlock()) || Strings.isEmpty(getToBlock())) { return false; } boolean isValidBlockRange = true; try { if (getFromBlock().equals(DefaultBlockParameterName.LATEST.getValue()) && !getToBlock().equals(DefaultBlockParameterName.LATEST.getValue())) { // fromBlock="latest" but toBlock is not isValidBlockRange = validToBlock(blockNumber); } else if (!getFromBlock().equals(DefaultBlockParameterName.LATEST.getValue()) && getToBlock().equals(DefaultBlockParameterName.LATEST.getValue())) { // toBlock="latest" but fromBlock is not isValidBlockRange = validFromBlock(blockNumber); } else if (!getFromBlock().equals(DefaultBlockParameterName.LATEST.getValue()) && !getToBlock().equals(DefaultBlockParameterName.LATEST.getValue())) { isValidBlockRange = validFromToBlock(blockNumber); } } catch (Exception e) { // invalid blockNumber format string isValidBlockRange = false; } return isValidBlockRange; }
Example #5
Source File: Contract.java From web3sdk with Apache License 2.0 | 5 votes |
public void registerEventLogPushFilter( String abi, String bin, String topic0, EventLogPushWithDecodeCallback callback) { registerEventLogPushFilter( abi, bin, topic0, new String(DefaultBlockParameterName.LATEST.getValue()), new String(DefaultBlockParameterName.LATEST.getValue()), new ArrayList<String>(), callback); }
Example #6
Source File: CnsService.java From web3sdk with Apache License 2.0 | 5 votes |
boolean isSynced() throws Exception { SyncStatus ethSyncing = web3j.getSyncStatus().send(); if (ethSyncing.isSyncing()) { return false; } else { BcosBlock block = web3j.getBlockByNumber(DefaultBlockParameterName.LATEST, false).send(); long timestamp = block.getBlock().getTimestamp().longValueExact() * 1000; return System.currentTimeMillis() - syncThreshold < timestamp; } }
Example #7
Source File: TransService.java From WeBASE-Front with Apache License 2.0 | 4 votes |
/** * handleTransByFunction by whether is constant */ private Object handleTransByFunction(int groupId, Web3j web3j, String signUserId, String contractAddress, Function function, ContractFunction contractFunction) throws IOException, InterruptedException, ExecutionException, TimeoutException { String encodedFunction = FunctionEncoder.encode(function); Object response; Instant startTime = Instant.now(); // if constant, signUserId can be "" if (contractFunction.getConstant()) { KeyStoreInfo keyStoreInfo = keyStoreService.getKeyStoreInfoForQuery(); String callOutput = web3j .call(Transaction.createEthCallTransaction(keyStoreInfo.getAddress(), contractAddress, encodedFunction), DefaultBlockParameterName.LATEST) .send().getValue().getOutput(); List<Type> typeList = FunctionReturnDecoder.decode(callOutput, function.getOutputParameters()); if (typeList.size() > 0) { response = AbiUtil.callResultParse(contractFunction.getOutputList(), typeList); } else { response = typeList; } } else { // data sign String signMsg = signMessage(groupId, web3j, signUserId, contractAddress, encodedFunction); if (StringUtils.isBlank(signMsg)) { throw new FrontException(ConstantCode.DATA_SIGN_ERROR); } Instant nodeStartTime = Instant.now(); // send transaction final CompletableFuture<TransactionReceipt> transFuture = new CompletableFuture<>(); sendMessage(web3j, signMsg, transFuture); TransactionReceipt receipt = transFuture.get(constants.getTransMaxWait(), TimeUnit.SECONDS); response = receipt; log.info("***node cost time***: {}", Duration.between(nodeStartTime, Instant.now()).toMillis()); } log.info("***transaction total cost time***: {}", Duration.between(startTime, Instant.now()).toMillis()); log.info("transHandleWithSign end. func:{} baseRsp:{}", contractFunction.getFuncName(), JsonUtils.toJSONString(response)); return response; }
Example #8
Source File: Web3jApITest.java From WeBASE-Front with Apache License 2.0 | 4 votes |
@Test public void getCode() throws Exception { Code code = web3j.getCode(address, DefaultBlockParameterName.LATEST).send(); assertNotNull(code.getCode()); }
Example #9
Source File: TransService.java From WeBASE-Transaction with Apache License 2.0 | 4 votes |
/** * transaction query. * * @param req parameter * @return */ public ResponseEntity call(ReqTransCallInfo req) throws BaseException { int groupId = req.getGroupId(); String uuidDeploy = req.getUuidDeploy(); String contractAddress = req.getContractAddress(); List<Object> abiList = req.getContractAbi(); String funcName = req.getFuncName(); List<Object> params = req.getFuncParam(); try { // check groupId if (!checkGroupId(groupId)) { log.warn("call fail. groupId:{} has not been configured", groupId); throw new BaseException(ConstantCode.GROUPID_NOT_CONFIGURED); } // check request style if (StringUtils.isBlank(uuidDeploy) && (StringUtils.isBlank(contractAddress) || abiList.isEmpty())) { throw new BaseException(ConstantCode.ADDRESS_ABI_EMPTY); } // check if contract has been deployed if (StringUtils.isBlank(contractAddress)) { contractAddress = contractMapper.selectContractAddress(groupId, uuidDeploy); } if (StringUtils.isBlank(contractAddress)) { log.warn("save fail. contract has not been deployed"); throw new BaseException(ConstantCode.CONTRACT_NOT_DEPLOED); } // check contractAbi String contractAbi = ""; if (abiList.isEmpty()) { contractAbi = contractMapper.selectContractAbi(groupId, uuidDeploy); if (StringUtils.isBlank(contractAbi)) { log.warn("save fail. uuidDeploy:{} abi is not exists", uuidDeploy); throw new BaseException(ConstantCode.CONTRACT_ABI_EMPTY); } } else { contractAbi = JsonUtils.toJSONString(abiList); } // check function AbiDefinition abiDefinition = ContractAbiUtil.getAbiDefinition(funcName, contractAbi); if (abiDefinition == null) { log.warn("call fail. func:{} is not exists", funcName); throw new BaseException(ConstantCode.FUNCTION_NOT_EXISTS); } if (!abiDefinition.isConstant()) { log.warn("call fail. func:{} is not constant", funcName); throw new BaseException(ConstantCode.FUNCTION_MUST_CONSTANT); } // check function parameter List<String> funcInputTypes = ContractAbiUtil.getFuncInputType(abiDefinition); if (funcInputTypes.size() != params.size()) { log.warn("call fail. funcInputTypes:{}, params:{}", funcInputTypes, params); throw new BaseException(ConstantCode.IN_FUNCPARAM_ERROR); } // check input format List<Type> finalInputs = ContractAbiUtil.inputFormat(funcInputTypes, params); // check output format List<String> funOutputTypes = ContractAbiUtil.getFuncOutputType(abiDefinition); List<TypeReference<?>> finalOutputs = ContractAbiUtil.outputFormat(funOutputTypes); // encode function Function function = new Function(funcName, finalInputs, finalOutputs); String encodedFunction = FunctionEncoder.encode(function); String callOutput = web3jMap.get(groupId) .call(Transaction.createEthCallTransaction(keyStoreService.getRandomAddress(), contractAddress, encodedFunction), DefaultBlockParameterName.LATEST) .send().getValue().getOutput(); List<Type> typeList = FunctionReturnDecoder.decode(callOutput, function.getOutputParameters()); ResponseEntity response = new ResponseEntity(ConstantCode.RET_SUCCEED); if (typeList.size() > 0) { response.setData(ContractAbiUtil.callResultParse(funOutputTypes, typeList)); } else { response.setData(typeList); } return response; } catch (IOException e) { log.error("call funcName:{} Exception:{}", funcName, e); throw new BaseException(ConstantCode.TRANSACTION_QUERY_FAILED); } }
Example #10
Source File: EthClient.java From WeBASE-Collect-Bee with Apache License 2.0 | 4 votes |
@Cacheable(cacheNames = { "code" }) public String getCodeByContractAddress(String contractAddress) throws IOException { return web3j.getCode(contractAddress, DefaultBlockParameterName.LATEST).sendForReturnString(); }