org.fisco.bcos.web3j.protocol.core.methods.request.Transaction Java Examples

The following examples show how to use org.fisco.bcos.web3j.protocol.core.methods.request.Transaction. 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: TransService.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
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 #2
Source File: CallContract.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
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 #3
Source File: Contract.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Execute constant function call - i.e. a call that does not change state of the contract
 *
 * @param function to call
 * @return {@link List} of values returned by function call
 */
private List<Type> executeCall(Function function) throws IOException {
    String encodedFunction = FunctionEncoder.encode(function);
    Call ethCall =
            web3j.call(
                            Transaction.createEthCallTransaction(
                                    transactionManager.getFromAddress(),
                                    contractAddress,
                                    encodedFunction),
                            defaultBlockParameter)
                    .send();

    String value = ethCall.getValue().getOutput();
    return FunctionReturnDecoder.decode(value, function.getOutputParameters());
}
 
Example #4
Source File: TransService.java    From WeBASE-Front with Apache License 2.0 4 votes vote down vote up
/**
 * 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 #5
Source File: TransService.java    From WeBASE-Transaction with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
    }
}